@needle-tools/engine 6.0.0-alpha.5 → 6.0.0-alpha.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +4 -0
- package/dist/{materialx-B3qY8vPU.js → materialx-Bd9BE6LR.js} +1 -1
- package/dist/{materialx-BwYvA-4x.umd.cjs → materialx-CzRx9AGf.umd.cjs} +2 -2
- package/dist/{materialx-CTPhpPxI.min.js → materialx-x1m4IJd1.min.js} +1 -1
- package/dist/{needle-engine.bundle-_kAszB-k.min.js → needle-engine.bundle-D6mZl1dR.min.js} +9 -9
- package/dist/{needle-engine.bundle-D3nBMgfk.umd.cjs → needle-engine.bundle-DOHf03pR.umd.cjs} +9 -9
- package/dist/{needle-engine.bundle-4xlWxOTF.js → needle-engine.bundle-Hu7ZAxEI.js} +550 -555
- package/dist/needle-engine.d.ts +14 -14
- package/dist/needle-engine.js +562 -562
- package/dist/needle-engine.min.js +1 -1
- package/dist/needle-engine.umd.cjs +1 -1
- package/dist/{vendor-BQUQwut5.js → vendor-BatPc34p.js} +50 -41
- package/dist/{vendor-BJviq-Oq.umd.cjs → vendor-CDN1hirK.umd.cjs} +1 -1
- package/dist/{vendor-CdNldo8c.min.js → vendor-T07c_9f_.min.js} +1 -1
- package/lib/engine/api.d.ts +1 -1
- package/lib/engine/api.js +1 -1
- package/lib/engine/api.js.map +1 -1
- package/lib/engine/engine_init.js +2 -2
- package/lib/engine/engine_init.js.map +1 -1
- package/lib/engine/engine_license.d.ts +7 -7
- package/lib/engine/engine_license.js +73 -73
- package/lib/engine/engine_license.js.map +1 -1
- package/lib/engine/engine_networking_blob.js +3 -3
- package/lib/engine/engine_networking_blob.js.map +1 -1
- package/lib/engine/engine_utils_qrcode.js +2 -2
- package/lib/engine/engine_utils_qrcode.js.map +1 -1
- package/lib/engine/webcomponents/needle menu/needle-menu-spatial.js +2 -2
- package/lib/engine/webcomponents/needle menu/needle-menu-spatial.js.map +1 -1
- package/lib/engine/webcomponents/needle menu/needle-menu.js +5 -5
- package/lib/engine/webcomponents/needle menu/needle-menu.js.map +1 -1
- package/lib/engine/webcomponents/needle-engine.js +2 -2
- package/lib/engine/webcomponents/needle-engine.js.map +1 -1
- package/lib/engine/webcomponents/needle-engine.loading.js +2 -2
- package/lib/engine/webcomponents/needle-engine.loading.js.map +1 -1
- package/lib/engine/xr/TempXRContext.js +2 -2
- package/lib/engine/xr/TempXRContext.js.map +1 -1
- package/lib/engine-components/Renderer.d.ts +1 -1
- package/lib/engine-components/Renderer.js +2 -11
- package/lib/engine-components/Renderer.js.map +1 -1
- package/lib/engine-components/export/usdz/USDZExporter.js +4 -4
- package/lib/engine-components/export/usdz/USDZExporter.js.map +1 -1
- package/package.json +2 -2
- package/plugins/common/license.js +4 -4
- package/plugins/license/cli.js +7 -4
- package/plugins/vite/license.js +4 -4
- package/src/engine/api.ts +1 -1
- package/src/engine/engine_init.ts +2 -2
- package/src/engine/engine_license.ts +70 -70
- package/src/engine/engine_networking_blob.ts +3 -3
- package/src/engine/engine_utils_qrcode.ts +2 -2
- package/src/engine/webcomponents/needle menu/needle-menu-spatial.ts +2 -2
- package/src/engine/webcomponents/needle menu/needle-menu.ts +5 -5
- package/src/engine/webcomponents/needle-engine.loading.ts +2 -2
- package/src/engine/webcomponents/needle-engine.ts +2 -2
- package/src/engine/xr/TempXRContext.ts +2 -2
- package/src/engine-components/Renderer.ts +4 -13
- package/src/engine-components/export/usdz/USDZExporter.ts +4 -4
package/dist/{needle-engine.bundle-D3nBMgfk.umd.cjs → needle-engine.bundle-DOHf03pR.umd.cjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var dP=Object.defineProperty;var uP=(s,e,t)=>e in s?dP(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var Vb=(s,e,t)=>uP(s,typeof e!="symbol"?e+"":e,t);const c=require("./three-core.umd.cjs"),re=require("./gltf-progressive-BpT9M5Mt.umd.cjs"),V=require("./three-examples.umd.cjs"),ee=require("./vendor-
|
|
1
|
+
"use strict";var dP=Object.defineProperty;var uP=(s,e,t)=>e in s?dP(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var Vb=(s,e,t)=>uP(s,typeof e!="symbol"?e+"":e,t);const c=require("./three-core.umd.cjs"),re=require("./gltf-progressive-BpT9M5Mt.umd.cjs"),V=require("./three-examples.umd.cjs"),ee=require("./vendor-CDN1hirK.umd.cjs"),le=require("./three-mesh-ui-CzHaC-a-.umd.cjs");var Ha=typeof document<"u"?document.currentScript:null;const Wb=typeof window<"u"?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 se{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&&(Wb&&console.warn("Registering context"),this.Registered.push(e),this.dispatchCallback("ContextRegistered",e))}static unregister(e){const t=this.Registered.indexOf(e);t!==-1&&(Wb&&console.warn("Unregistering context"),this.Registered.splice(t,1))}static _callbacks={};static registerCallback(e,t){return this._callbacks[e]||(this._callbacks[e]=[]),this._callbacks[e].indexOf(t)!==-1?()=>this.unregisterCallback(e,t):(this._callbacks[e].push(t),()=>this.unregisterCallback(e,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 Hp=new Map;function ki(s=globalThis.location?.hostname){if(Hp.has(s))return Hp.get(s);const e=/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|localhost/.test(s);return Hp.set(s,e),e===!0}function Rw(){return window.location.hostname.includes("glitch.me")}const Tw=()=>s=>s;function fP(s){return Tw()(s)}function pP(){return!!x("debug")}class Mi{_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 lr=!1;const lg=new Array;typeof window<"u"&&setTimeout(()=>{if(lr){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 lg){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=lr===!0?"":` (containing "${lr}")`;console.group("Available URL parameters:"+n);for(const o of Object.keys(s).sort())typeof lr=="string"&&!o.toLowerCase().includes(lr.toLowerCase())||(console.groupCollapsed(o),console.log("Reload with this flag enabled:"),console.log(s[o]),console.groupEnd());console.groupEnd()}},100);function xh(){return new URLSearchParams(globalThis.location?.search)}function x(s){lr&&!lg.includes(s)&&lg.push(s);const e=xh();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}lr=x("help");function mP(s,e){const t=xh();t.has(s)?t.set(s,e):t.append(s,e),document.location.search=t.toString()}function Yc(s,e,t=!0){const i=xh();i.has(s)?e===null?i.delete(s):i.set(s,e):e!==null&&i.append(s,e),t?Aw(s,i):Sy(s,i)}function cg(s,e,t){s.has(e)?s.set(e,t.toString()):s.append(e,t.toString())}function Aw(s,e,t){window.history.pushState(t,s,"?"+e.toString()+window.location.hash)}function Sy(s,e,t){window.history.replaceState(t,s,"?"+e.toString()+window.location.hash)}function gP(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 yP(s,e){return Math.floor(Math.random()*(e-s+1))+s}const Gb=["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"],Hb=["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 Dw(){const s=Gb[Math.floor(Math.random()*Gb.length)],e=Hb[Math.floor(Math.random()*Hb.length)];return s+"_"+e}function Iw(s){return s=s.replace(/[^a-z0-9áéíóúñü \.,_-]/gim,""),s.trim()}function Kc(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=Kc(s,o,t,i);if(r)return r}if(e.children)for(const n in e.children){const o=e.children[n],r=Kc(s,o,t,i);if(r)return r}}}function _P(s){return!!(typeof EventTarget<"u"&&s instanceof EventTarget||s instanceof Date||s instanceof RegExp||s instanceof Map||s instanceof Set||s instanceof WeakMap||s instanceof WeakSet||s instanceof Promise||typeof ArrayBuffer<"u"&&s instanceof ArrayBuffer||ArrayBuffer.isView(s))}function Sh(s,e,t){if(s!=null&&typeof s=="object"){if(t||(t=new WeakSet),t.has(s)||(t.add(s),_P(s)))return s;let i;if(Array.isArray(s))i=[];else{i=Object.create(Object.getPrototypeOf(s));const n=Object.getOwnPropertyDescriptors(s);for(const o in n){const r=n[o];if(r.set||r.writable!==!1)try{i[o]=s[o]}catch{}}}for(const n of Object.keys(s)){const o=s[n];e&&!e(s,n,o)?i[n]=o:o?.clone!==void 0&&typeof o.clone=="function"?i[n]=o.clone():i[n]=Sh(o,e,t)}return i}return s}function Ds(s){return new Promise((e,t)=>{setTimeout(e,s)})}function kf(s,e){if(s<=0)return Promise.resolve();if(e||(e=se.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 md=x("debugresolveurl"),Lw="rel:";function bP(s,e){return cs(s,e)}function cs(s,e){if(e===void 0)return md&&console.warn("getPath: uri is undefined, returning uri",e),e;if(e.startsWith("./"))return e;if(e.startsWith("http"))return md&&console.warn("getPath: uri is absolute, returning uri",e),e;if(s===void 0)return md&&console.warn("getPath: source is undefined, returning uri",e),e;e.startsWith(Lw)&&(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 md&&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
|
-
`,Yo?.prepend(n),s===!0&&jw()<=0&&sx(),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.":"")),ic=!1,ai=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.15.1/dist/vconsole.min.js",document.body.appendChild(e)}function Sk(){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"),ai?.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 gg="padding: 10px; font-family: monospace;",ov="margin-bottom: 10px;",Ko="margin-bottom: 10px; margin-top: 15px;",Ck="width: 100%; border-collapse: collapse; border: 1px solid rgba(0,0,0,0.1); table-layout: fixed;",ox="border: 1px solid rgba(0,0,0,0.1); padding: 5px;",Pk=ox,kk=ox+" word-break: break-all;";function zn(s,e=!1){e&&s.sort((i,n)=>(n.value?1:0)-(i.value?1:0));let t=`<table style='${Ck}'>`;t+="<tbody>";for(const i of s){const n=typeof i.value=="boolean"?i.value?"✅":"❌":i.value;t+=`<tr><td style='${Pk}'>${i.label}</td><td style='${kk}'>${n}</td></tr>`}return t+="</tbody></table>",t}function rx(){try{if(Ef())return"✅"}catch{}return"❌"}function Mk(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("device-utilities","📱 Device Info");return s.on("renderTab",function(e){let t=`<div style='${gg}'>`;const i=Fk();t+=`<h3 style='${ov}'>Device: ${i}</h3>`,t+=zn([{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+=zn(n,!1)),t+="</div>",t+=`<div style='${gg} margin-top: 20px;'>`,t+=`<h3 style='${ov}'>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:rx()}];t+=zn(l,!1),t+="</div>",e(t)}),s}function Ok(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("graphics-info","🎨 Graphics Info");return s.on("renderTab",async function(e){let t=`<div style='${gg}'>`;const i=Ek();i.length>0&&(t+=`<h3 style='${Ko}'>General GPU Info</h3>`,t+=zn(i,!1));const n=Tk();n.length>0&&(t+=`<h3 style='${Ko}'>WebGL</h3>`,t+=zn(n,!1));const o=Ak();o.length>0&&(t+=`<h3 style='${Ko}'>WebGL 2 Features</h3>`,t+=zn(o,!1));const r=Dk();r.length>0&&(t+=`<h3 style='${Ko}'>WebGL Limits</h3>`,t+=zn(r,!1));const a=Ik();a.length>0&&(t+=`<h3 style='${Ko}'>Texture Formats</h3>`,t+=zn(a,!1));const l=await Lk();if(l.length>0&&(t+=`<h3 style='${Ko}'>WebGPU</h3>`,t+=zn(l,!1)),exports.DeviceUtilities.isSafari()){const h=Bk();h.length>0&&(t+=`<h3 style='${Ko}'>Safari GPU Info</h3>`,t+=zn(h,!1))}t+="</div>",e(t)}),s}function Ek(){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=ax();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=Rk(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 Rk(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 Tk(){const s=[],e=ax();return e&&(s.push({label:"📊 WebGL Version",value:e.version}),s.push({label:"🎮 WebGL 2 Available",value:rx()})),s}function Ak(){const s=[];try{const e=Ef();if(!e)return s;s.push({label:"Float Color Buffer",value:e.getExtension("EXT_color_buffer_float")?"✅":"❌"}),s.push({label:"Anisotropic Filtering",value:e.getExtension("EXT_texture_filter_anisotropic")?"✅":"❌"}),s.push({label:"Float Texture Linear",value:e.getExtension("OES_texture_float_linear")?"✅":"❌"}),s.push({label:"S3TC Compression",value:e.getExtension("WEBGL_compressed_texture_s3tc")?"✅":"❌"}),s.push({label:"ETC Compression",value:e.getExtension("WEBGL_compressed_texture_etc")?"✅":"❌"}),s.push({label:"PVRTC Compression",value:e.getExtension("WEBGL_compressed_texture_pvrtc")?"✅":"❌"}),s.push({label:"ASTC Compression",value:e.getExtension("WEBGL_compressed_texture_astc")?"✅":"❌"})}catch{}return s}function Dk(){const s=[];try{const e=nx();if(!e)return s;const t=e instanceof WebGL2RenderingContext;s.push({label:"📏 Max Texture Size",value:e.getParameter(e.MAX_TEXTURE_SIZE).toString()}),s.push({label:"🎨 Max Renderbuffer Size",value:e.getParameter(e.MAX_RENDERBUFFER_SIZE).toString()}),s.push({label:"🔗 Max Vertex Attribs",value:e.getParameter(e.MAX_VERTEX_ATTRIBS).toString()}),s.push({label:"🎯 Max Texture Units",value:e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS).toString()}),t&&(s.push({label:"⚡ Max Samples",value:e.getParameter(e.MAX_SAMPLES).toString()}),s.push({label:"🔄 Max Uniform Buffer Bindings",value:e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS).toString()}),s.push({label:"📐 Max 3D Texture Size",value:e.getParameter(e.MAX_3D_TEXTURE_SIZE).toString()}))}catch{}return s}function Ik(){const s=[];try{Wu()&&(s.push({label:"WebGL 1 RGBA",value:"✅"}),s.push({label:"WebGL 1 RGB",value:"✅"}));const t=Ef();t&&(s.push({label:"WebGL 2 RGBA32F",value:t.getExtension("EXT_color_buffer_float")?"✅":"❌"}),s.push({label:"WebGL 2 RGB32F",value:t.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 Lk(){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 ax(){try{const s=nx();if(!s)return null;const e=s.getExtension("WEBGL_debug_renderer_info"),t=e?s.getParameter(e.UNMASKED_RENDERER_WEBGL):s.getParameter(s.RENDERER),i=e?s.getParameter(e.UNMASKED_VENDOR_WEBGL):s.getParameter(s.VENDOR),n=s.getParameter(s.VERSION);let o;if(t&&t.includes("ANGLE")){const r=t.match(/ANGLE \(([^)]+)\)/);r&&(o=r[1])}return{renderer:t,vendor:i,version:n,angle:o}}catch{return null}}function Bk(){const s=[];try{const e=Wu();if(e){const t=e.getExtension("WEBGL_debug_renderer_info");if(t){const i=e.getParameter(t.UNMASKED_RENDERER_WEBGL);i&&i.includes("Apple")&&s.push({label:"🍎 Apple GPU",value:i})}}}catch{}try{const e=Wu();e&&(e.getSupportedExtensions()||[]).includes("WEBGL_compressed_texture_pvrtc")&&s.push({label:"🗜️ PVRTC Support",value:"✅"})}catch{}return s}function Fk(){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 jk(){const s=document.querySelector("#__vconsole .vc-switch");return s||null}function Uk(){const s=document.querySelector("#__vconsole");return s||null}const bd=x("debugtypes");class zk{_types=new Map;_reverseTypes=new Map;_lazyLoaders=new Map;constructor(){bd&&console.warn("TypeStore: Created",this)}add(e,t){bd&&console.warn("ADD TYPE",e);const i=this._types.get(e);i?bd&&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){bd&&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}get types(){return this._types}}const Nk=Symbol("BuiltInType"),M=new zk,Ly=function(s){M.get(s.name)||M.add(s.name,s)};class $k{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)}}exports.AnimationUtils=void 0;(s=>{function e(d,u){const f=d.getRoot();return f&&(f.userData.static||f.matrixAutoUpdate===!1||f.matrixWorldAutoUpdate===!1)?((u===!0||u===void 0&&E())&&console.warn(`AnimationUtils: The root object (${f.name||f.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:f.userData.static,name:f.userData.name,tag:f.userData.tag,matrixAutoUpdate:f.matrixAutoUpdate,matrixWorldAutoUpdate:f.matrixWorldAutoUpdate}),!1):!0}s.testIfRootCanAnimate=e;function t(d){const u=d._actions;return u||null}s.tryGetActionsFromMixer=t;function i(d,u){if(u||(u=new Array),d)d.animations&&u.push(...d.animations);else return u;if(d.children)for(const f of d.children)i(f,u);return u}s.tryGetAnimationClipsFromObjectHierarchy=i;const n=Symbol("objectIsAnimatedData");function o(d,u,f){if(!d)return;if(d[n]===void 0){if(!f)return;d[n]=new Set}const m=d[n];f?m.add(u):m.has(u)&&m.delete(u)}s.setObjectAnimated=o;function r(d){if(!d)return!1;const u=d[n];return u!==void 0&&u.size>0}s.getObjectAnimated=r;function a(d){if(!d||!d.animations)return console.debug("No animations found in file"),null;const u="scene"in d?d.scene:d,f=new Array;for(let g=0;g<d.animations.length;g++){const v=d.animations[g];if(!v.tracks||v.tracks.length<=0){console.warn("Animation has no tracks");continue}for(const _ in v.tracks){const y=v.tracks[_],b=c.PropertyBinding.parseTrackName(y.name);let w=c.PropertyBinding.findNode(u,b.nodeName);if(!w){const k=y.__objectName??y.name.substring(0,y.name.indexOf("."));if(w=u.getObjectByProperty("uuid",k)??null,!w)continue}let C=m(w)||m(u);if(!C){const k=M.get("Animation");if(C=u.addComponent(k),!C){console.error("Failed creating Animation component: No 'Animation' component found in TypeStore");break}}f.push(C),C.addClip&&C.addClip(v)}}return f;function m(g){if(!g)return null;const v=g.userData?.components;if(v&&v.length>0)for(let _=0;_<v.length;_++){const y=v[_];if(y.isAnimationComponent===!0)return y}return m(g.parent)}}s.autoplayAnimations=a;function l(){return new c.AnimationClip("empty",0,[])}s.emptyClip=l;function h(d){const u=d?.duration??.3;let f={x:1,y:1,z:1};d?.scale!==void 0&&(typeof d.scale=="number"?f={x:d.scale,y:d.scale,z:d.scale}:f=d.scale);const m=d?.type??"linear",g=d?.scaleFactor??1.2,v=new Array,_=new Array;switch(m){case"linear":v.push(0,u),_.push(f.x,f.y,f.z,f.x*g,f.y*g,f.z*g);break;case"spring":v.push(0,u*.3,u*.5,u*.7,u*.9,u),_.push(f.x,f.y,f.z,f.x*g,f.y*g,f.z*g,f.x*.9,f.y*.9,f.z*.9,f.x*1.05,f.y*1.05,f.z*1.05,f.x*.98,f.y*.98,f.z*.98,f.x,f.y,f.z);break}const y=new c.KeyframeTrack(".scale",v,_);return new c.AnimationClip("scale",v[v.length-1],[y])}s.createScaleClip=h})(exports.AnimationUtils||(exports.AnimationUtils={}));const Qe=function(s){return p(s)},p=function(s){if(s===void 0&&(s=null),!Array.isArray(s))s=rv(s);else for(let e=0;e<s.length;e++){const t=s[e];s[e]=rv(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 rv(s){switch(s?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return s}const av=x("debugcomponentevents");class Rf{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),av&&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(av&&console.log("Dispatching event "+e,i),!!i)for(const n of i)n(t)}}const lx=x("debugdefines");Bo('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";');Bo('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";');Bo('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";');Bo('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";');Bo('globalThis["__NEEDLE_ENGINE_VERSION__"] = "6.0.0-alpha.5";');Bo('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');Bo('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Mon Oct 05 2026 13:00:42 GMT+0000 (Coordinated Universal Time)";');Bo('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const Zt="6.0.0-alpha.5",al="undefined",Zc="Mon Oct 05 2026 13:00:42 GMT+0000 (Coordinated Universal Time)";lx&&console.log(`Engine version: ${Zt} (generator: ${al})
|
|
143
|
+
`,Yo?.prepend(n),s===!0&&jw()<=0&&sx(),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.":"")),ic=!1,ai=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.15.1/dist/vconsole.min.js",document.body.appendChild(e)}function Sk(){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"),ai?.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 gg="padding: 10px; font-family: monospace;",ov="margin-bottom: 10px;",Ko="margin-bottom: 10px; margin-top: 15px;",Ck="width: 100%; border-collapse: collapse; border: 1px solid rgba(0,0,0,0.1); table-layout: fixed;",ox="border: 1px solid rgba(0,0,0,0.1); padding: 5px;",Pk=ox,kk=ox+" word-break: break-all;";function zn(s,e=!1){e&&s.sort((i,n)=>(n.value?1:0)-(i.value?1:0));let t=`<table style='${Ck}'>`;t+="<tbody>";for(const i of s){const n=typeof i.value=="boolean"?i.value?"✅":"❌":i.value;t+=`<tr><td style='${Pk}'>${i.label}</td><td style='${kk}'>${n}</td></tr>`}return t+="</tbody></table>",t}function rx(){try{if(Ef())return"✅"}catch{}return"❌"}function Mk(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("device-utilities","📱 Device Info");return s.on("renderTab",function(e){let t=`<div style='${gg}'>`;const i=Fk();t+=`<h3 style='${ov}'>Device: ${i}</h3>`,t+=zn([{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+=zn(n,!1)),t+="</div>",t+=`<div style='${gg} margin-top: 20px;'>`,t+=`<h3 style='${ov}'>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:rx()}];t+=zn(l,!1),t+="</div>",e(t)}),s}function Ok(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("graphics-info","🎨 Graphics Info");return s.on("renderTab",async function(e){let t=`<div style='${gg}'>`;const i=Ek();i.length>0&&(t+=`<h3 style='${Ko}'>General GPU Info</h3>`,t+=zn(i,!1));const n=Tk();n.length>0&&(t+=`<h3 style='${Ko}'>WebGL</h3>`,t+=zn(n,!1));const o=Ak();o.length>0&&(t+=`<h3 style='${Ko}'>WebGL 2 Features</h3>`,t+=zn(o,!1));const r=Dk();r.length>0&&(t+=`<h3 style='${Ko}'>WebGL Limits</h3>`,t+=zn(r,!1));const a=Ik();a.length>0&&(t+=`<h3 style='${Ko}'>Texture Formats</h3>`,t+=zn(a,!1));const l=await Lk();if(l.length>0&&(t+=`<h3 style='${Ko}'>WebGPU</h3>`,t+=zn(l,!1)),exports.DeviceUtilities.isSafari()){const h=Bk();h.length>0&&(t+=`<h3 style='${Ko}'>Safari GPU Info</h3>`,t+=zn(h,!1))}t+="</div>",e(t)}),s}function Ek(){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=ax();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=Rk(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 Rk(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 Tk(){const s=[],e=ax();return e&&(s.push({label:"📊 WebGL Version",value:e.version}),s.push({label:"🎮 WebGL 2 Available",value:rx()})),s}function Ak(){const s=[];try{const e=Ef();if(!e)return s;s.push({label:"Float Color Buffer",value:e.getExtension("EXT_color_buffer_float")?"✅":"❌"}),s.push({label:"Anisotropic Filtering",value:e.getExtension("EXT_texture_filter_anisotropic")?"✅":"❌"}),s.push({label:"Float Texture Linear",value:e.getExtension("OES_texture_float_linear")?"✅":"❌"}),s.push({label:"S3TC Compression",value:e.getExtension("WEBGL_compressed_texture_s3tc")?"✅":"❌"}),s.push({label:"ETC Compression",value:e.getExtension("WEBGL_compressed_texture_etc")?"✅":"❌"}),s.push({label:"PVRTC Compression",value:e.getExtension("WEBGL_compressed_texture_pvrtc")?"✅":"❌"}),s.push({label:"ASTC Compression",value:e.getExtension("WEBGL_compressed_texture_astc")?"✅":"❌"})}catch{}return s}function Dk(){const s=[];try{const e=nx();if(!e)return s;const t=e instanceof WebGL2RenderingContext;s.push({label:"📏 Max Texture Size",value:e.getParameter(e.MAX_TEXTURE_SIZE).toString()}),s.push({label:"🎨 Max Renderbuffer Size",value:e.getParameter(e.MAX_RENDERBUFFER_SIZE).toString()}),s.push({label:"🔗 Max Vertex Attribs",value:e.getParameter(e.MAX_VERTEX_ATTRIBS).toString()}),s.push({label:"🎯 Max Texture Units",value:e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS).toString()}),t&&(s.push({label:"⚡ Max Samples",value:e.getParameter(e.MAX_SAMPLES).toString()}),s.push({label:"🔄 Max Uniform Buffer Bindings",value:e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS).toString()}),s.push({label:"📐 Max 3D Texture Size",value:e.getParameter(e.MAX_3D_TEXTURE_SIZE).toString()}))}catch{}return s}function Ik(){const s=[];try{Wu()&&(s.push({label:"WebGL 1 RGBA",value:"✅"}),s.push({label:"WebGL 1 RGB",value:"✅"}));const t=Ef();t&&(s.push({label:"WebGL 2 RGBA32F",value:t.getExtension("EXT_color_buffer_float")?"✅":"❌"}),s.push({label:"WebGL 2 RGB32F",value:t.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 Lk(){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 ax(){try{const s=nx();if(!s)return null;const e=s.getExtension("WEBGL_debug_renderer_info"),t=e?s.getParameter(e.UNMASKED_RENDERER_WEBGL):s.getParameter(s.RENDERER),i=e?s.getParameter(e.UNMASKED_VENDOR_WEBGL):s.getParameter(s.VENDOR),n=s.getParameter(s.VERSION);let o;if(t&&t.includes("ANGLE")){const r=t.match(/ANGLE \(([^)]+)\)/);r&&(o=r[1])}return{renderer:t,vendor:i,version:n,angle:o}}catch{return null}}function Bk(){const s=[];try{const e=Wu();if(e){const t=e.getExtension("WEBGL_debug_renderer_info");if(t){const i=e.getParameter(t.UNMASKED_RENDERER_WEBGL);i&&i.includes("Apple")&&s.push({label:"🍎 Apple GPU",value:i})}}}catch{}try{const e=Wu();e&&(e.getSupportedExtensions()||[]).includes("WEBGL_compressed_texture_pvrtc")&&s.push({label:"🗜️ PVRTC Support",value:"✅"})}catch{}return s}function Fk(){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 jk(){const s=document.querySelector("#__vconsole .vc-switch");return s||null}function Uk(){const s=document.querySelector("#__vconsole");return s||null}const bd=x("debugtypes");class zk{_types=new Map;_reverseTypes=new Map;_lazyLoaders=new Map;constructor(){bd&&console.warn("TypeStore: Created",this)}add(e,t){bd&&console.warn("ADD TYPE",e);const i=this._types.get(e);i?bd&&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){bd&&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}get types(){return this._types}}const Nk=Symbol("BuiltInType"),M=new zk,Ly=function(s){M.get(s.name)||M.add(s.name,s)};class $k{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)}}exports.AnimationUtils=void 0;(s=>{function e(d,u){const f=d.getRoot();return f&&(f.userData.static||f.matrixAutoUpdate===!1||f.matrixWorldAutoUpdate===!1)?((u===!0||u===void 0&&E())&&console.warn(`AnimationUtils: The root object (${f.name||f.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:f.userData.static,name:f.userData.name,tag:f.userData.tag,matrixAutoUpdate:f.matrixAutoUpdate,matrixWorldAutoUpdate:f.matrixWorldAutoUpdate}),!1):!0}s.testIfRootCanAnimate=e;function t(d){const u=d._actions;return u||null}s.tryGetActionsFromMixer=t;function i(d,u){if(u||(u=new Array),d)d.animations&&u.push(...d.animations);else return u;if(d.children)for(const f of d.children)i(f,u);return u}s.tryGetAnimationClipsFromObjectHierarchy=i;const n=Symbol("objectIsAnimatedData");function o(d,u,f){if(!d)return;if(d[n]===void 0){if(!f)return;d[n]=new Set}const m=d[n];f?m.add(u):m.has(u)&&m.delete(u)}s.setObjectAnimated=o;function r(d){if(!d)return!1;const u=d[n];return u!==void 0&&u.size>0}s.getObjectAnimated=r;function a(d){if(!d||!d.animations)return console.debug("No animations found in file"),null;const u="scene"in d?d.scene:d,f=new Array;for(let g=0;g<d.animations.length;g++){const v=d.animations[g];if(!v.tracks||v.tracks.length<=0){console.warn("Animation has no tracks");continue}for(const _ in v.tracks){const y=v.tracks[_],b=c.PropertyBinding.parseTrackName(y.name);let w=c.PropertyBinding.findNode(u,b.nodeName);if(!w){const k=y.__objectName??y.name.substring(0,y.name.indexOf("."));if(w=u.getObjectByProperty("uuid",k)??null,!w)continue}let C=m(w)||m(u);if(!C){const k=M.get("Animation");if(C=u.addComponent(k),!C){console.error("Failed creating Animation component: No 'Animation' component found in TypeStore");break}}f.push(C),C.addClip&&C.addClip(v)}}return f;function m(g){if(!g)return null;const v=g.userData?.components;if(v&&v.length>0)for(let _=0;_<v.length;_++){const y=v[_];if(y.isAnimationComponent===!0)return y}return m(g.parent)}}s.autoplayAnimations=a;function l(){return new c.AnimationClip("empty",0,[])}s.emptyClip=l;function h(d){const u=d?.duration??.3;let f={x:1,y:1,z:1};d?.scale!==void 0&&(typeof d.scale=="number"?f={x:d.scale,y:d.scale,z:d.scale}:f=d.scale);const m=d?.type??"linear",g=d?.scaleFactor??1.2,v=new Array,_=new Array;switch(m){case"linear":v.push(0,u),_.push(f.x,f.y,f.z,f.x*g,f.y*g,f.z*g);break;case"spring":v.push(0,u*.3,u*.5,u*.7,u*.9,u),_.push(f.x,f.y,f.z,f.x*g,f.y*g,f.z*g,f.x*.9,f.y*.9,f.z*.9,f.x*1.05,f.y*1.05,f.z*1.05,f.x*.98,f.y*.98,f.z*.98,f.x,f.y,f.z);break}const y=new c.KeyframeTrack(".scale",v,_);return new c.AnimationClip("scale",v[v.length-1],[y])}s.createScaleClip=h})(exports.AnimationUtils||(exports.AnimationUtils={}));const Qe=function(s){return p(s)},p=function(s){if(s===void 0&&(s=null),!Array.isArray(s))s=rv(s);else for(let e=0;e<s.length;e++){const t=s[e];s[e]=rv(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 rv(s){switch(s?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return s}const av=x("debugcomponentevents");class Rf{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),av&&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(av&&console.log("Dispatching event "+e,i),!!i)for(const n of i)n(t)}}const lx=x("debugdefines");Bo('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";');Bo('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";');Bo('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";');Bo('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";');Bo('globalThis["__NEEDLE_ENGINE_VERSION__"] = "6.0.0-alpha.6";');Bo('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');Bo('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Tue Oct 06 2026 10:27:28 GMT+0000 (Coordinated Universal Time)";');Bo('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const Zt="6.0.0-alpha.6",al="undefined",Zc="Tue Oct 06 2026 10:27:28 GMT+0000 (Coordinated Universal Time)";lx&&console.log(`Engine version: ${Zt} (generator: ${al})
|
|
144
144
|
Project built at ${Zc}`);const wo=NEEDLE_PUBLIC_KEY,Zn="needle_isActiveInHierarchy",cr="builtin_components",Rs="needle_editor_guid";function Bo(s){try{(0,eval)(s)}catch(e){lx&&console.error(e)}}globalThis.NEEDLE_USE_RAPIER=globalThis.NEEDLE_USE_RAPIER!==void 0?globalThis.NEEDLE_USE_RAPIER:!0;globalThis.NEEDLE_USE_POSTPROCESSING=globalThis.NEEDLE_USE_POSTPROCESSING!==void 0?globalThis.NEEDLE_USE_POSTPROCESSING:!0;const By={experimentalSmartHierarchyUpdate:!1},xi=Symbol("shadowDomOwner"),Vk=x("debugpatch");function Tf(s,e,t,i){const n=Vk===e;if(!t&&!i)return;const o=e+"___needle";Gk(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]=cv(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]=cv(l,s,e);else{const h=this[o];cx(s,e,this,h,l),this[o]=l,hx(s,e,this,h,l)}},get:function(){const l=this[o];return typeof l=="function"&&l[o]?l[o]:l}}))}function Wk(s,e,t){const i=Fy(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 lv=Symbol("Needle:Patches:WrappedFunction");function cv(s,e,t){if(s[lv])return s;const i=function(...n){cx(e,t,this,...n);const o=s.apply(this,n);return hx(e,t,this,o,...n),o};return i[lv]=!0,i}const gu="Needle:Patches";function yg(){return globalThis[gu]||(globalThis[gu]=new WeakMap),globalThis[gu]}function Fy(s,e){const t=yg().get(s);return t?t.get(e):null}function Gk(s,e,t,i){let n=yg().get(s);n||(n=new Map,yg().set(s,n));let o=n.get(e);o||(o=[],n.set(e,o)),o.push({prefix:t,postfix:i})}function cx(s,e,t,...i){if(!t)return;const n=Fy(s,e);if(n)for(const o of n)o.prefix?.call(t,...i)}function hx(s,e,t,i,...n){if(!t)return;const o=Fy(s,e);if(o)for(const r of o)r.postfix?.call(t,i,...n)}function Hk(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 E()&&console.debug("Spector available: Add '?spector=<frame>' to the URL to enable it and capture a frame.")}}function dx(s){const e=s;return!!(e.parser&&e.parser.json)}var as=(s=>(s[s.None=0]="None",s[s.DontExport=1]="DontExport",s[s.DontInstantiate=2]="DontInstantiate",s))(as||{});const Gu=Symbol("component-name");function Af(s){return s&&typeof s=="object"&&s.isComponent}const qk=Symbol("object"),Zp=new Mi(()=>new c.Vector3,20);class ux{_point;_normal;_tangentVelocity;distance;impulse;friction;get point(){return Zp.get().set(this._point.x,this._point.y,this._point.z)}get normal(){return Zp.get().set(this._normal.x,this._normal.y,this._normal.z)}get tangentVelocity(){return Zp.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 fx{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 px{object;collider;constructor(e,t){this.object=e,this.collider=t}}class Hu{constructor(e){this.context=e,this.root.style.cssText=`
|
|
145
145
|
position: absolute;
|
|
146
146
|
width: 1px; height: 1px;
|
|
@@ -271,7 +271,7 @@ TEX `+i.texture_lod;if(sm=="density"&&(v+=`
|
|
|
271
271
|
`+(g/n.lastScreenCoverage).toFixed(0)+` dens
|
|
272
272
|
`+(n.lastScreenCoverage*100).toFixed(1)+`% cov
|
|
273
273
|
`+(n.lastCentrality*100).toFixed(1)+`% centr
|
|
274
|
-
`+(Sd.min.x.toFixed(2)+"-"+Sd.max.x.toFixed(2)+"x"+Sd.min.y.toFixed(2)+"-"+Sd.max.y.toFixed(2))+" scr"),n.lastScreenCoverage>.1){const _=e,y=_.worldForward,b=_.worldPosition,C=F(y).multiplyScalar(h*.7).add(l),k=C.distanceTo(b),O=d[Math.min(d.length-1,Math.max(0,o))]+"88",D=this.context.domHeight>0?screen.height/this.context.domHeight:1,I=e.isPerspectiveCamera?Math.tan(e.fov*Math.PI/180/2):1;B.DrawLabel(C,v,k*.012*D*I,void 0,16777215,O)}}}}}const qy={};function Xy(s,e){qy[s]=e}function Vx(s){const e=s.getBufferIdentifier(),t=qy[e];return t(s)}function Wx(s){return typeof s.guid=="function"?s.guid():null}class WM{_url;_ws;onOpen=null;onClose=null;onError=null;onMessage=null;get url(){return this._ws?.url??this._url}constructor(e){this._url=e}async start(){const e=await Promise.resolve().then(()=>require("./vendor-BJviq-Oq.umd.cjs")).then(o=>o.index),t=e.default?.WebsocketBuilder??e.WebsocketBuilder,i=e.default?.ExponentialBackoff??e.ExponentialBackoff,n=new t(this._url).withMaxRetries(10).withBackoff(new i(2e3,4)).onOpen(()=>{this._ws=n,this.onOpen?.()}).onClose(()=>{this.onClose?.()}).onError(()=>{this.onError?.(new Error("Websocket connection failed"))}).onRetry(()=>{console.log("Retry connecting to networking websocket")}).build();n.addEventListener(e.WebsocketEvent.message,(o,r)=>{this.onMessage?.(r.data)})}send(e){this._ws?.send(e)}close(){this._ws?.close(),this._ws=void 0}}function sc(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 A={MaterialX:sc(()=>Promise.resolve().then(()=>require("./materialx-BwYvA-4x.umd.cjs"))),RAPIER_PHYSICS:sc(()=>Promise.resolve().then(()=>require("./rapier-DQltNJbN.umd.cjs"))),POSTPROCESSING:sc(()=>Promise.resolve().then(()=>require("./postprocessing-DwcCsALK.umd.cjs")).then(s=>s.index)),POSTPROCESSING_AO:sc(()=>Promise.resolve().then(()=>require("./postprocessing-DwcCsALK.umd.cjs")).then(s=>s.N8AO)),PEERJS:sc(()=>Promise.resolve().then(()=>require("./vendor-BJviq-Oq.umd.cjs")).then(s=>s.bundler))};let Qy;const yo=x("debugpeer")!==void 0;function GM(){return Qy}function HM(s){Qy=s}async function Gx(s,e){const i=(await A.PEERJS.load()).default;return e||(e={}),e={...Qy,...e},s?new i(s,e):new i(e)}async function Cv(){const s=await A.PEERJS.load();return s.default===void 0?s:s.default}class Hx{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 Cv(),i=new t(e);i.on("error",n=>{yo&&console.error(n),this._host=void 0,this.trySetupClient(e)}),i.on("open",n=>{this._host=new XM(i)})}async trySetupClient(e){const t=await Cv();this._client=new t,this._client.on("error",i=>{yo&&console.error("Client error",i)}),this._client.on("open",i=>{yo&&console.debug("client connected",i),this._clientData=this._client.connect(e,{metadata:{id:i}}),this._clientData.on("open",()=>{yo&&console.debug("Connected to host")}),this._clientData.on("data",n=>{yo&&console.debug("<<",n)})})}}class qM{_peer;constructor(e){this._peer=e}}class XM extends qM{get isHost(){return!0}_connections=[];constructor(e){super(e),this._peer?.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("bye")})}onConnection(e){yo&&console.debug("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){yo&&console.debug(">>",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 yo&&console.warn(i)}}}}const Pv="https://urls.needle.tools/default-networking-backend/index";let ys="wss://networking-2.needle.tools/socket";const Pd=Symbol("originalCallback"),oi=!!x("debugnet"),Oa=!!(oi||x("debugowner")),kd=x("debugnetbin");var qx=(s=>(s.ConnectionInfo="connection-start-info",s))(qx||{}),te=(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))(te||{});class QM{room;viewId;allowEditing;inRoom}class YM{room}class KM{userId}var Xx=(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))(Xx||{});class Qx{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;_pendingOwnershipResolve=null;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||(Oa&&console.log("request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid})))}requestOwnership(){return this._hasOwnership?Promise.resolve(!0):(this._pendingOwnershipResolve?.(!1),this._pendingOwnershipResolve=null,Oa&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),new Promise(e=>{this._pendingOwnershipResolve=e,setTimeout(()=>{this._pendingOwnershipResolve===e&&(this._pendingOwnershipResolve=null,e(!1))},2e3)}))}async requestOwnershipAsync(){return Oa&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),this}freeOwnership(){return this._hasOwnership?(this._hasOwnership=!1,this.connection.send("remove-ownership",{guid:this.guid}),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this):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),this._pendingOwnershipResolve?.(!1),this._pendingOwnershipResolve=null}onGainedOwnership(e){e.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===e.owner?(Oa&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0,this._pendingOwnershipResolve&&(this._pendingOwnershipResolve(!0),this._pendingOwnershipResolve=null)):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(Oa&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1,this._pendingOwnershipResolve&&(this._pendingOwnershipResolve(!1),this._pendingOwnershipResolve=null))}}class th{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new Hx),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return oi}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._transport?.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(),oi&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},yn.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,i=yn.Queued){if(i===yn.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){kd&&console.log("<< send binary",this.context.time.frame,e.length/1024+" KB"),this._transport?.send(e)}_defaultMessagesBuffer=[];_defaultMessagesBufferArray=[];sendBufferedMessagesNow(){if(!this._transport)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,yn.Immediate);break}const o=this.toMessage(n.key,n.value);this._defaultMessagesBufferArray.push(o)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&oi&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;const t=JSON.stringify(this._defaultMessagesBufferArray);this._transport?.send(t)}beginListen(e,t){this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t);const i=()=>this.stopListen(e,t);return i[Pd]=t,i}stopListening(e,t){return this.stopListen(e,t)}static _didLogStopListenHint=!1;stopListen(e,t){if(!t||!this._listeners[e])return;const i=t[Pd]??t;i!==t&&E()&&!th._didLogStopListenHint&&(th._didLogStopListenHint=!0,console.warn("[Needle Engine] Tip: beginListen() returns an unsubscribe function — you can call it directly instead of using stopListen()."));const n=this._listeners[e].indexOf(i);n>=0&&this._listeners[e].splice(n,1)}beginListenBinary(e,t){this._listenersBinary[e]||(this._listenersBinary[e]=[]),this._listenersBinary[e].push(t);const i=()=>this.stopListenBinary(e,t);return i[Pd]=t,i}stopListenBinary(e,t){if(!this._listenersBinary[e])return;const i=t?.[Pd]??t,n=this._listenersBinary[e].indexOf(i);n>=0&&this._listenersBinary[e].splice(n,1)}netWebSocketUrlProvider;registerProvider(e){this.netWebSocketUrlProvider=e}async connect(e,t){if(this.connected&&e&&e!==ys)return Promise.reject("Can not connect to different server url. Please disconnect first.");if(this.connected)return Promise.resolve(!0);if(t)return this.connectTransport(t);e&&console.debug("Connecting to user provided url "+e);const i=e||this.netWebSocketUrlProvider?.getWebsocketUrl();return i?ys=i:Rw()&&(ys="wss://"+window.location.host+"/socket"),this.connectWebsocket()}disconnect(){this._transport&&(this._transport.onOpen=null,this._transport.onClose=null,this._transport.onError=null,this._transport.onMessage=null,this._transport.close(),this._transport=void 0),ys=void 0,this.connected=!1,this._connectionId=null,this._currentRoomAllowEditing=!0,this._currentRoomName=null,this._currentRoomViewId=null,this._isInRoom=!1,this._currentInRoom.length=0,this._state={},this._currentDelay=-1,this._connectingToWebsocketPromise=null}dispose(){this.disconnect(),this._listeners={},this._listenersBinary={},this._waitingForSocket={},this._peer=null}_listeners={};_listenersBinary={};connected=!1;_connectionId=null;_transport;_waitingForSocket={};_isInRoom=!1;_currentRoomName=null;_currentRoomViewId=null;_currentRoomAllowEditing=!0;_currentInRoom=[];_state={};_currentDelay=-1;_connectingToWebsocketPromise=null;connectTransport(e){return this._connectingToWebsocketPromise?this._connectingToWebsocketPromise:this._connectingToWebsocketPromise=new Promise(t=>{let i=!1;const n=o=>{i||(i=!0,t(o))};e.onOpen=()=>{this._connectingToWebsocketPromise=null,this._transport=e,this.connected=!0,E()||oi?console.log(`Connected to networking backend
|
|
274
|
+
`+(Sd.min.x.toFixed(2)+"-"+Sd.max.x.toFixed(2)+"x"+Sd.min.y.toFixed(2)+"-"+Sd.max.y.toFixed(2))+" scr"),n.lastScreenCoverage>.1){const _=e,y=_.worldForward,b=_.worldPosition,C=F(y).multiplyScalar(h*.7).add(l),k=C.distanceTo(b),O=d[Math.min(d.length-1,Math.max(0,o))]+"88",D=this.context.domHeight>0?screen.height/this.context.domHeight:1,I=e.isPerspectiveCamera?Math.tan(e.fov*Math.PI/180/2):1;B.DrawLabel(C,v,k*.012*D*I,void 0,16777215,O)}}}}}const qy={};function Xy(s,e){qy[s]=e}function Vx(s){const e=s.getBufferIdentifier(),t=qy[e];return t(s)}function Wx(s){return typeof s.guid=="function"?s.guid():null}class WM{_url;_ws;onOpen=null;onClose=null;onError=null;onMessage=null;get url(){return this._ws?.url??this._url}constructor(e){this._url=e}async start(){const e=await Promise.resolve().then(()=>require("./vendor-CDN1hirK.umd.cjs")).then(o=>o.index),t=e.default?.WebsocketBuilder??e.WebsocketBuilder,i=e.default?.ExponentialBackoff??e.ExponentialBackoff,n=new t(this._url).withMaxRetries(10).withBackoff(new i(2e3,4)).onOpen(()=>{this._ws=n,this.onOpen?.()}).onClose(()=>{this.onClose?.()}).onError(()=>{this.onError?.(new Error("Websocket connection failed"))}).onRetry(()=>{console.log("Retry connecting to networking websocket")}).build();n.addEventListener(e.WebsocketEvent.message,(o,r)=>{this.onMessage?.(r.data)})}send(e){this._ws?.send(e)}close(){this._ws?.close(),this._ws=void 0}}function sc(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 A={MaterialX:sc(()=>Promise.resolve().then(()=>require("./materialx-CzRx9AGf.umd.cjs"))),RAPIER_PHYSICS:sc(()=>Promise.resolve().then(()=>require("./rapier-DQltNJbN.umd.cjs"))),POSTPROCESSING:sc(()=>Promise.resolve().then(()=>require("./postprocessing-DwcCsALK.umd.cjs")).then(s=>s.index)),POSTPROCESSING_AO:sc(()=>Promise.resolve().then(()=>require("./postprocessing-DwcCsALK.umd.cjs")).then(s=>s.N8AO)),PEERJS:sc(()=>Promise.resolve().then(()=>require("./vendor-CDN1hirK.umd.cjs")).then(s=>s.bundler))};let Qy;const yo=x("debugpeer")!==void 0;function GM(){return Qy}function HM(s){Qy=s}async function Gx(s,e){const i=(await A.PEERJS.load()).default;return e||(e={}),e={...Qy,...e},s?new i(s,e):new i(e)}async function Cv(){const s=await A.PEERJS.load();return s.default===void 0?s:s.default}class Hx{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 Cv(),i=new t(e);i.on("error",n=>{yo&&console.error(n),this._host=void 0,this.trySetupClient(e)}),i.on("open",n=>{this._host=new XM(i)})}async trySetupClient(e){const t=await Cv();this._client=new t,this._client.on("error",i=>{yo&&console.error("Client error",i)}),this._client.on("open",i=>{yo&&console.debug("client connected",i),this._clientData=this._client.connect(e,{metadata:{id:i}}),this._clientData.on("open",()=>{yo&&console.debug("Connected to host")}),this._clientData.on("data",n=>{yo&&console.debug("<<",n)})})}}class qM{_peer;constructor(e){this._peer=e}}class XM extends qM{get isHost(){return!0}_connections=[];constructor(e){super(e),this._peer?.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("bye")})}onConnection(e){yo&&console.debug("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){yo&&console.debug(">>",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 yo&&console.warn(i)}}}}const Pv="https://urls.needle.tools/default-networking-backend/index";let ys="wss://networking-2.needle.tools/socket";const Pd=Symbol("originalCallback"),oi=!!x("debugnet"),Oa=!!(oi||x("debugowner")),kd=x("debugnetbin");var qx=(s=>(s.ConnectionInfo="connection-start-info",s))(qx||{}),te=(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))(te||{});class QM{room;viewId;allowEditing;inRoom}class YM{room}class KM{userId}var Xx=(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))(Xx||{});class Qx{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;_pendingOwnershipResolve=null;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||(Oa&&console.log("request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid})))}requestOwnership(){return this._hasOwnership?Promise.resolve(!0):(this._pendingOwnershipResolve?.(!1),this._pendingOwnershipResolve=null,Oa&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),new Promise(e=>{this._pendingOwnershipResolve=e,setTimeout(()=>{this._pendingOwnershipResolve===e&&(this._pendingOwnershipResolve=null,e(!1))},2e3)}))}async requestOwnershipAsync(){return Oa&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),this}freeOwnership(){return this._hasOwnership?(this._hasOwnership=!1,this.connection.send("remove-ownership",{guid:this.guid}),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this):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),this._pendingOwnershipResolve?.(!1),this._pendingOwnershipResolve=null}onGainedOwnership(e){e.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===e.owner?(Oa&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0,this._pendingOwnershipResolve&&(this._pendingOwnershipResolve(!0),this._pendingOwnershipResolve=null)):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(Oa&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1,this._pendingOwnershipResolve&&(this._pendingOwnershipResolve(!1),this._pendingOwnershipResolve=null))}}class th{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new Hx),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return oi}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._transport?.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(),oi&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},yn.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,i=yn.Queued){if(i===yn.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){kd&&console.log("<< send binary",this.context.time.frame,e.length/1024+" KB"),this._transport?.send(e)}_defaultMessagesBuffer=[];_defaultMessagesBufferArray=[];sendBufferedMessagesNow(){if(!this._transport)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,yn.Immediate);break}const o=this.toMessage(n.key,n.value);this._defaultMessagesBufferArray.push(o)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&oi&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;const t=JSON.stringify(this._defaultMessagesBufferArray);this._transport?.send(t)}beginListen(e,t){this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t);const i=()=>this.stopListen(e,t);return i[Pd]=t,i}stopListening(e,t){return this.stopListen(e,t)}static _didLogStopListenHint=!1;stopListen(e,t){if(!t||!this._listeners[e])return;const i=t[Pd]??t;i!==t&&E()&&!th._didLogStopListenHint&&(th._didLogStopListenHint=!0,console.warn("[Needle Engine] Tip: beginListen() returns an unsubscribe function — you can call it directly instead of using stopListen()."));const n=this._listeners[e].indexOf(i);n>=0&&this._listeners[e].splice(n,1)}beginListenBinary(e,t){this._listenersBinary[e]||(this._listenersBinary[e]=[]),this._listenersBinary[e].push(t);const i=()=>this.stopListenBinary(e,t);return i[Pd]=t,i}stopListenBinary(e,t){if(!this._listenersBinary[e])return;const i=t?.[Pd]??t,n=this._listenersBinary[e].indexOf(i);n>=0&&this._listenersBinary[e].splice(n,1)}netWebSocketUrlProvider;registerProvider(e){this.netWebSocketUrlProvider=e}async connect(e,t){if(this.connected&&e&&e!==ys)return Promise.reject("Can not connect to different server url. Please disconnect first.");if(this.connected)return Promise.resolve(!0);if(t)return this.connectTransport(t);e&&console.debug("Connecting to user provided url "+e);const i=e||this.netWebSocketUrlProvider?.getWebsocketUrl();return i?ys=i:Rw()&&(ys="wss://"+window.location.host+"/socket"),this.connectWebsocket()}disconnect(){this._transport&&(this._transport.onOpen=null,this._transport.onClose=null,this._transport.onError=null,this._transport.onMessage=null,this._transport.close(),this._transport=void 0),ys=void 0,this.connected=!1,this._connectionId=null,this._currentRoomAllowEditing=!0,this._currentRoomName=null,this._currentRoomViewId=null,this._isInRoom=!1,this._currentInRoom.length=0,this._state={},this._currentDelay=-1,this._connectingToWebsocketPromise=null}dispose(){this.disconnect(),this._listeners={},this._listenersBinary={},this._waitingForSocket={},this._peer=null}_listeners={};_listenersBinary={};connected=!1;_connectionId=null;_transport;_waitingForSocket={};_isInRoom=!1;_currentRoomName=null;_currentRoomViewId=null;_currentRoomAllowEditing=!0;_currentInRoom=[];_state={};_currentDelay=-1;_connectingToWebsocketPromise=null;connectTransport(e){return this._connectingToWebsocketPromise?this._connectingToWebsocketPromise:this._connectingToWebsocketPromise=new Promise(t=>{let i=!1;const n=o=>{i||(i=!0,t(o))};e.onOpen=()=>{this._connectingToWebsocketPromise=null,this._transport=e,this.connected=!0,E()||oi?console.log(`Connected to networking backend
|
|
275
275
|
`+(e.url??"")):console.debug("Connected to networking backend",e.url??""),n(!0),this.onSendQueued(yn.OnConnection)},e.onClose=()=>{this._connectingToWebsocketPromise=null,this.connected=!1,this._isInRoom=!1,n(!1);let o="Websocket connection closed...";e.url?.includes("/socket")||(o+=' Do you perhaps mean to connect to "/socket"?'),console.error(o)},e.onError=()=>{console.error("Websocket connection failed..."),n(!1),st.sendEvent(this.context,"networking",{event:"connection_error"})},e.onMessage=o=>{this.onMessage(o)},e.start()})}async connectWebsocket(){if(this._connectingToWebsocketPromise)return this._connectingToWebsocketPromise;if(ys===void 0&&(console.log("Fetch default backend url: "+Pv),ys=await(await fetch(Pv)).text()),ys===void 0)return!1;console.debug(`Connecting to networking backend on
|
|
276
276
|
`+ys);const e=new WM(ys);return this.connectTransport(e)}onMessage(e){const t=e;try{if(typeof t!="string"){t.size&&this.handleIncomingBinaryMessage(t);return}const i=JSON.parse(t);if(Array.isArray(i))for(const n of i)this.handleIncomingStringMessage(n);else this.handleIncomingStringMessage(i);return}catch(i){oi&&t==="pong"?console.log("<<",t):E()&&console.error("Failed to parse message",i)}}async handleIncomingBinaryMessage(e){kd&&console.log("<< bin",this.context.time.frame);const t=await e.arrayBuffer();var i=new Uint8Array(t);const n=new ee.ByteBuffer(i),o=n.getBufferIdentifier(),r=this._listenersBinary[o],a=Vx(n),l=Wx(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(oi&&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,st.sendEvent(this.context,"networking",{event:"connected"}))}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(oi&&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),(kd||E())&&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(yn.OnRoomJoin),st.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,(kd||E())&&console.debug("Left Needle Engine Room: "+n.room)),st.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),oi&&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&&(oi&&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":oi&&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),oi&&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=yn.OnRoomJoin){if(!this._transport){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));oi&&console.log(">>",e),this._transport.send(n)}onSendQueued(e){const t=this._waitingForSocket[e];if(t){for(const i of t)i();t.length=0}}}const ZM=x("debugplayerview");var Ts=(s=>(s.Browser="browser",s.Headset="headset",s.Handheld="handheld",s))(Ts||{});class Yx{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 Kx{context;playerViews=new Map;constructor(e){this.context=e}setPlayerView(e,t,i){let n=this.playerViews.get(e);n||(n=new Yx(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&&(ZM&&console.log("REMOVE",e),i.removed=!0,this.playerViews.delete(e))}}const JM=new Proxy({},{get(s,e){if(e==="then")return;const t=se.Current;if(!t)return(E()?console.error:console.warn)(`[needle] needle.${e} was accessed before the scene started. Use "needle" inside event handlers or callbacks, not at module top-level. For setup code use: onStart(ctx => { ... })`),Qa("needle not ready — scene hasn't started yet");const i=t[e];return typeof i=="function"?i.bind(t):i},set(s,e,t){const i=se.Current;return i?(i[e]=t,!0):((E()?console.error:console.warn)(`[needle] needle.${e} was set before the scene started. Use "needle" inside event handlers or callbacks, not at module top-level. For setup code use: onStart(ctx => { ... })`),!0)}}),kv=new WeakMap;function Qa(s){const e={get(t,i){return i==="then"||typeof i=="symbol"?void 0:((E()?console.error:console.warn)(`[SceneData] ${s}`),Qa(s))},set(t,i){return typeof i=="symbol"||(E()?console.error:console.warn)(`[SceneData] ${s} (tried to set "${i}")`),!0}};return new Proxy({},e)}function Zx(s,e){return new Proxy({},{get(t,i){if(i==="$object")return e;if(i==="$components")return new Proxy({},{get(o,r){if(r==="then")return;const a=M.get(r);if(!a)return Qa(`Component type "${r}" not registered (node "${e.name}")`);const l=Bs(e,a);return l||Qa(`Component "${r}" not found on node "${e.name}"`)}});if(i==="then")return;const n=e.children.find(o=>o.name===i)??null;return n?Zx(s,n):((E()?console.error:console.warn)(`[SceneData] "${i}" is not a child of "${e.name}". Use .$object to get the Three.js object or .$components.Name to access a component.`),Qa(`"${i}" not found on node "${e.name}"`))}})}function Jx(s){let e=kv.get(s);return e||(e=new Proxy({},{get(t,i){return new Proxy({},{get(n,o){if(o==="then")return;const r=s.scene.getObjectByName(o)??null;return r?Zx(s,r):Qa(`Node "${o}" not found in scene`)}})}}),kv.set(s,e)),e}const Rh=new Uint8Array(4);Rh[0]=255;Rh[1]=255;Rh[2]=255;Rh[3]=255;const eO=new c.DataTexture(Rh,1,1,c.RGBAFormat);function Yy(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 tO(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 f=0;f<n;f++){const m=Math.floor(f/n*l),g=L.clamp(m+1,0,l-1),v=a[m],_=a[g],y=f/n*l%1;d.lerpColors(v,_,y);const b=Math.floor(d.r*255),w=Math.floor(d.g*255),C=Math.floor(d.b*255);for(let k=0;k<i;k++){const O=(f*i+k)*4;h[O+0]=b,h[O+1]=w,h[O+2]=C,h[O+3]=255}}const u=new c.DataTexture(h,i,n);return u.needsUpdate=!0,u}function Zu(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 om=[],Mv=[];function iO(s,e){if(om.length===0)for(let t=0;t<27;t++)om.push(0);e||(e=om);for(let t=0;t<27;t++)Mv[t]=e[t];e=Mv,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 nO{vertexShader;fragmentShader;technique;constructor(e,t,i){this.vertexShader=e,this.fragmentShader=t,this.technique=i}}async function sO(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 Ov(o),!r.code&&r.uri&&await Ov(r),!o.code||!r.code)return null;const a=s.techniques[e];return new nO(o.code,r.code,a)}}return console.error("Shader technique not found",e),null}async function Ov(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=oO(s.uri)}function oO(s){return decodeURIComponent(Array.prototype.map.call(atob(s),function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}const dn=x("debugenvlight");var Ya=(s=>(s[s.Skybox=0]="Skybox",s[s.Trilight=1]="Trilight",s[s.Flat=3]="Flat",s[s.Custom=4]="Custom",s))(Ya||{}),Ju=(s=>(s[s.Skybox=0]="Skybox",s[s.Custom=1]="Custom",s))(Ju||{});class eS{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 J&&(e=e.url);const t=this._sceneLightSettings?.get(e);return t?(dn&&console.log("Enable scene light settings",e,t),e!==this._currentLightSettingsId&&this._currentLightSettingsId&&this.disable(this._currentLightSettingsId),this._currentLightSettingsId=e,t.enabled=!0,!0):(dn&&console.warn("No light settings found for",e),!1)}disable(e){if(e instanceof J&&(e=e.url),e==null)return!1;const t=this._sceneLightSettings?.get(e);return t?(dn&&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}dn&&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}dn&&console.log("Unregister "+e?.sourceId+" lighting",e),this._sceneLightSettings&&this._sceneLightSettings.delete(t)}internalRegisterReflection(e,t){dn&&console.log("Register reflection",e,t);const i=new tS(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(dn&&console.log("Enable reflection",e,t?Ya[t.ambientMode]:"Unknown ambient mode",t),t?.ambientMode){case 0:case 4:const i=this.internalGetReflection(e);if(i&&i.Source){dn&&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 dn&&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=tO(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=Yy(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){dn&&console.log("Not disabling reflection for",e,"because it is not the current light settings id",this.__currentReflectionId);return}dn&&console.log("Disable reflection",e);const t=this.context.scene;t.environment=null}_lighting={}}class tS{get Source(){return this._source}_source;constructor(e,t,i=1){this._source=t,t.mapping!==c.CubeUVReflectionMapping&&(t.mapping=c.EquirectangularReflectionMapping)}}let Eg;function rO(s){Eg=s}function aO(s){return s.isWebGPURenderer===!0&&Eg?new Eg(s):new c.PMREMGenerator(s)}const Ev=x("timescale");let Rg=1;typeof Ev=="number"&&(Rg=Ev);class iS{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._elapsedUnscaled}get fps(){return 1/this.deltaTime}get smoothedFps(){return this._smoothedFps}get smoothedDeltaTime(){return 1/this._smoothedFps}_clockStartTime=performance.now();_lastUpdateTime=this._clockStartTime;_elapsedUnscaled=0;_smoothedFps=0;_smoothedDeltaTime=0;_fpsSamples=[];_fpsSampleIndex=0;constructor(){typeof Rg=="number"&&(this.timeScale=Rg)}update(){const e=performance.now();this.deltaTime=(e-this._lastUpdateTime)/1e3,this._lastUpdateTime=e,this._elapsedUnscaled+=this.deltaTime,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 t=0;for(let i=0;i<this._fpsSamples.length;i++)t+=this._fpsSamples[i];this._smoothedDeltaTime=t/this._fpsSamples.length,this._smoothedFps=1/this._smoothedDeltaTime}}let Rv=!1;function nS(s){Rv||(Rv=!0,lO(),cO())}function lO(){const s=`
|
|
@@ -408,7 +408,7 @@ vec3 AgXToneMapping( vec3 color ) {
|
|
|
408
408
|
return color;
|
|
409
409
|
`,e="vec3 AgXToneMapping( vec3 color ) {",t="return color;",i=c.ShaderChunk.tonemapping_pars_fragment.indexOf(e),n=c.ShaderChunk.tonemapping_pars_fragment.indexOf(t,i);if(i>=0&&n>=0){const o=c.ShaderChunk.tonemapping_pars_fragment.substring(i,n+t.length);c.ShaderChunk.tonemapping_pars_fragment=c.ShaderChunk.tonemapping_pars_fragment.replace(o,s)}else E()&&console.error("Couldn't find AgXToneMapping in ShaderChunk.tonemapping_pars_fragment")}function sS(s){if(typeof s=="string")switch(s=s.toLowerCase(),s){case"none":return c.NoToneMapping;case"neutral":return c.NeutralToneMapping;case"aces":return c.ACESFilmicToneMapping;case"agx":return c.AgXToneMapping;case"khronos_neutral":return c.NeutralToneMapping;default:console.warn("[PostProcessing] Unknown tone mapping mode",s);return}}const Zo=x("debugpost");class oS{_context;_handler=null;_effects=[];_isDirty=!1;get effects(){return this._effects}get dirty(){return this._isDirty}set dirty(e){this._isDirty=e}_enabled=!0;get enabled(){return this._enabled}set enabled(e){e!==this._enabled&&(this._enabled=e,this.markDirty())}get handler(){return this._handler}get composer(){return this._composer}set composer(e){this._composer=e}_composer=null;multisampling="auto";adaptiveResolution=!1;constructor(e){this._context=e}addEffect(e){this._effects.includes(e)||(this._effects.push(e),this._isDirty=!0)}removeEffect(e){const t=this._effects.indexOf(e);t!==-1&&(this._effects.splice(t,1),this._isDirty=!0)}markDirty(){this._isDirty=!0}_enabledTime=-1;_multisampleAutoChangeTime=0;_multisampleAutoDecreaseTime=0;update(){const e=this._context;if(e.isInXR)return;if(this._isDirty&&e.mainCamera&&this.apply(),this._tonemappingOnlyActive){const i=this._effects.filter(n=>n.active&&n.enabled&&n.isToneMapping===!0);if(i.length>0){const n=i[i.length-1];e.renderer.toneMapping=n.threeToneMapping,e.renderer.toneMappingExposure=n.toneMappingExposure}return}if(!this._handler||!this._composer||this._handler.composer!==this._composer)return;const t=this._composer;if(e.renderer.getContext().isContextLost()&&e.renderer.forceContextRestore(),t.getRenderer()!==e.renderer&&t.setRenderer(e.renderer),t.setMainScene(e.scene),this.multisampling==="auto")if(this._handler.hasSmaaEffect)this._handler.multisampling!==0&&(this._handler.multisampling=0,(Zo||E())&&console.log(`[PostProcessing] multisampling is disabled because it's set to 'auto' and there is an SMAA effect.
|
|
410
410
|
|
|
411
|
-
If you need multisampling consider changing 'auto' to a fixed value (e.g. 4).`));else{const i=e.time.realtimeSinceStartup-this._multisampleAutoChangeTime;if(e.time.realtimeSinceStartup-this._enabledTime>2&&i>.5){const n=this._handler.multisampling;if(this._handler.multisampling>0&&e.time.smoothedFps<=50){this._multisampleAutoChangeTime=e.time.realtimeSinceStartup,this._multisampleAutoDecreaseTime=e.time.realtimeSinceStartup;let o=this._handler.multisampling*.5;o=Math.floor(o),o!=this._handler.multisampling&&(this._handler.multisampling=o),Zo&&console.debug(`[PostProcessing] Reduced multisampling from ${n} to ${this._handler.multisampling}`)}else if(i>1&&e.time.smoothedFps>=59&&this._handler.multisampling<e.renderer.capabilities.maxSamples&&e.time.realtimeSinceStartup-this._multisampleAutoDecreaseTime>10){this._multisampleAutoChangeTime=e.time.realtimeSinceStartup;let o=this._handler.multisampling<=0?1:this._handler.multisampling*2;o=Math.floor(o),o!==this._handler.multisampling&&(this._handler.multisampling=o),Zo&&console.debug(`[PostProcessing] Increased multisampling from ${n} to ${this._handler.multisampling}`)}}}else{const i=Math.max(0,Math.min(this.multisampling,e.renderer.capabilities.maxSamples));i!==this._handler.multisampling&&(this._handler.multisampling=i)}if(this._handler.adaptivePixelRatio=this.adaptiveResolution,this._handler.updateAdaptivePixelRatio(),e.mainCamera){const i=t.passes;for(const n of i)if(n.mainCamera&&n.mainCamera!==e.mainCamera){t.setMainCamera(e.mainCamera);break}}}_lastApplyTime;_rapidApplyCount=0;_tonemappingOnlyActive=!1;_previousToneMapping;_previousToneMappingExposure;apply(){Zo&&console.log(`[PostProcessing] Apply stack (${this._effects.length} effects)`),E()&&(this._lastApplyTime!==void 0&&Date.now()-this._lastApplyTime<100&&(this._rapidApplyCount++,this._rapidApplyCount===5&&console.warn("[PostProcessing] Detected rapid post processing modifications - this might be a bug")),this._lastApplyTime=Date.now()),this._isDirty=!1;const e=this._enabled?this._effects.filter(i=>i.active&&i.enabled):[];if(e.length<=0){this.restoreTonemapping(),this._handler?.unapply(!1);return}if(e.every(i=>i.isToneMapping===!0)){const i=e[e.length-1];Zo&&console.log("[PostProcessing] Only tonemapping effects in stack — applying directly to renderer"),this._tonemappingOnlyActive||(this._previousToneMapping=this._context.renderer.toneMapping,this._previousToneMappingExposure=this._context.renderer.toneMappingExposure,this._tonemappingOnlyActive=!0),this._context.renderer.toneMapping=i.threeToneMapping,this._context.renderer.toneMappingExposure=i.toneMappingExposure,this._handler?.unapply(!1);return}this.restoreTonemapping(),this.ensureHandler().then(i=>{if(i)return i.apply(e)}).then(()=>{this._handler&&(this.multisampling==="auto"?this._handler.multisampling=exports.DeviceUtilities.isMobileDevice()?2:4:this._handler.multisampling=Math.max(0,Math.min(this.multisampling,this._context.renderer.capabilities.maxSamples)),Zo&&console.debug(`[PostProcessing] Set multisampling to ${this._handler.multisampling} (Is Mobile: ${exports.DeviceUtilities.isMobileDevice()})`))}).catch(i=>{console.error("[PostProcessing] Failed to build/apply the postprocessing pipeline",i)}),this._enabledTime=this._context.time.realtimeSinceStartup}restoreTonemapping(){this._tonemappingOnlyActive&&(this._previousToneMapping!==void 0&&(this._context.renderer.toneMapping=this._previousToneMapping),this._previousToneMappingExposure!==void 0&&(this._context.renderer.toneMappingExposure=this._previousToneMappingExposure),this._tonemappingOnlyActive=!1,this._previousToneMapping=void 0,this._previousToneMappingExposure=void 0,Zo&&console.log("[PostProcessing] Restored renderer tonemapping"))}async ensureHandler(){if(!this._handler){const{PostProcessingHandler:e}=await Promise.resolve().then(()=>F3);this._handler||(this._handler=new e(this._context))}return this._handler}dispose(){this.restoreTonemapping(),this._handler?.dispose(),this._handler=null,this._composer=null,this._effects.length=0}}const mr=[],Su=[];exports.NeedleEngineModelLoader=void 0;(s=>{function e(i,n){const o={name:n?.name,priority:n?.priority??0,callback:i};return mr.push(o),mr.sort((r,a)=>r.priority===a.priority?0:r.priority>a.priority?-1:1),()=>{const r=mr.indexOf(o);r>=0&&mr.splice(r,1)}}s.onCreateCustomModelLoader=e;function t(i){return Su.push(i),()=>{const n=Su.indexOf(i);n>=0&&Su.splice(n,1)}}s.onDetermineModelMimetype=t})(exports.NeedleEngineModelLoader||(exports.NeedleEngineModelLoader={}));const rm="Gaussian Splat Loader",hO=x("debugsplats")||x("debugsplatsort")||x("debugspatsort"),dO=(()=>{const s=x("splatcull"),e=typeof s=="number"?s:typeof s=="string"?parseFloat(s):NaN;return Number.isFinite(e)&&e>0?Math.min(Math.PI,e*(Math.PI/180)):void 0})(),uO={high:{maxSh:3,minSortIntervalMs:150,fetchers:3,lodRenderScale:1,lodSplatScale:1,maxStdDev:Math.sqrt(8),maxPixelRadius:512,coneFoveate:.4,behindFoveate:.2,xrFramebufferScale:1,maxPagedSplats:0,minAlpha:.5/255,resolutionScale:1,sortCullHalfAngle:Math.PI,xrMaxFps:0},medium:{maxSh:2,minSortIntervalMs:200,fetchers:2,lodRenderScale:1,lodSplatScale:1,maxStdDev:Math.sqrt(8),maxPixelRadius:384,coneFoveate:.3,behindFoveate:.15,xrFramebufferScale:.9,maxPagedSplats:0,minAlpha:.5/255,resolutionScale:1,sortCullHalfAngle:120/180*Math.PI,xrMaxFps:0},low:{maxSh:1,minSortIntervalMs:250,fetchers:1,lodRenderScale:1,lodSplatScale:1,maxStdDev:Math.sqrt(7),maxPixelRadius:320,coneFoveate:.25,behindFoveate:.1,xrFramebufferScale:.8,maxPagedSplats:48*65536,minAlpha:.5/255,resolutionScale:1,sortCullHalfAngle:110/180*Math.PI,xrMaxFps:30}};function Ff(s,e=exports.DeviceUtilities.isMobileDevice()){return{...uO[s==="auto"?e?"low":"high":s]}}function Tg(s,e,t){const i=Ff(t),n=gr.get(s);n&&(n.quality=t,t!=="auto"&&(n.level=0,n.fpsBeforeStep=null,n.downBackoffUntil=0,n.goodStreak=0,n.stepFromLevel=null,n.jumpBackoffUntil=0,n.fpsBeforeProbe=null,n.upBackoffUntil=0,n.stableStreak=0),Zy(n));const o=e;if(o){typeof o.maxSh=="number"&&(o.maxSh=i.maxSh);const r=o.paged;r&&(r.setMaxSh(i.maxSh),r.pager&&(r.pager.numFetchers=i.fetchers))}return i}const ef=[{lodRenderScale:1,lodSplatScale:1,maxPixelRadius:1,maxStdDevCap:Number.POSITIVE_INFINITY,foveate:1,minAlphaFloor:0,resolutionScale:1},{lodRenderScale:1.5,lodSplatScale:.75,maxPixelRadius:1,maxStdDevCap:Number.POSITIVE_INFINITY,foveate:.8,minAlphaFloor:0,resolutionScale:1},{lodRenderScale:2.25,lodSplatScale:.5,maxPixelRadius:.75,maxStdDevCap:Math.sqrt(7),foveate:.6,minAlphaFloor:0,resolutionScale:1},{lodRenderScale:3.5,lodSplatScale:.35,maxPixelRadius:.5,maxStdDevCap:Math.sqrt(6),foveate:.45,minAlphaFloor:0,resolutionScale:1},{lodRenderScale:3.5,lodSplatScale:.35,maxPixelRadius:.5,maxStdDevCap:Math.sqrt(6),foveate:.45,minAlphaFloor:4/255,resolutionScale:1},{lodRenderScale:3.5,lodSplatScale:.35,maxPixelRadius:.5,maxStdDevCap:Math.sqrt(6),foveate:.45,minAlphaFloor:10/255,resolutionScale:1},{lodRenderScale:3.5,lodSplatScale:.35,maxPixelRadius:.5,maxStdDevCap:Math.sqrt(6),foveate:.45,minAlphaFloor:10/255,resolutionScale:.75},{lodRenderScale:3.5,lodSplatScale:.35,maxPixelRadius:.5,maxStdDevCap:Math.sqrt(6),foveate:.45,minAlphaFloor:10/255,resolutionScale:.6}],hr=ef.length-1;function Ky(s,e){const t=Math.max(0,Math.min(hr,Math.round(e))),i=ef[t];return{...s,lodRenderScale:s.lodRenderScale*i.lodRenderScale,lodSplatScale:s.lodSplatScale*i.lodSplatScale,maxPixelRadius:Math.round(s.maxPixelRadius*i.maxPixelRadius),maxStdDev:Math.min(s.maxStdDev,i.maxStdDevCap),coneFoveate:Math.max(.05,s.coneFoveate*i.foveate),behindFoveate:Math.max(.05,s.behindFoveate*i.foveate),minAlpha:Math.max(s.minAlpha,i.minAlphaFloor),resolutionScale:s.resolutionScale*i.resolutionScale}}const gr=new WeakMap;function fO(s){const e=gr.get(s);return e?{quality:e.quality,adaptationLevel:e.level,effective:Ky(Ff(e.quality),e.level)}:null}const pO=1,mO=2,gO=.8,yO=.95,_O=4,Tv=3,bO=1.1,oc=30,Av=2,vO=10,Dv=.8,wO=8,xO=.9,Iv=.5;function rS(s,e,t){const i=gr.get(s);if(!i||i.quality!=="auto")return;let n=i.level;e.streaming&&(i.lastStreamingTime=Math.max(i.lastStreamingTime,t));const o=t-i.lastStreamingTime>=Av||t-i.lastChangeTime>=vO;i.fpsBeforeStep!==null&&t-i.lastChangeTime>=Tv&&o&&(e.smoothedFps<i.fpsBeforeStep*Dv?E()&&console.debug(`[SplatQuality] conditions collapsed since the degradation (${i.fpsBeforeStep.toFixed(1)} → ${e.smoothedFps.toFixed(1)}) — discarding the measurement, keeping level ${n}`):e.smoothedFps<i.fpsBeforeStep*bO?(n=i.stepFromLevel??Math.max(0,n-1),i.downBackoffUntil=t+oc,i.stepFromLevel!==null&&i.level-i.stepFromLevel>1&&(i.jumpBackoffUntil=t+oc),E()&&console.debug(`[SplatQuality] degradation bought no fps (${i.fpsBeforeStep.toFixed(1)} → ${e.smoothedFps.toFixed(1)}) — reverting to level ${n}, backing off ${oc}s`)):E()&&console.debug(`[SplatQuality] degradation bought fps (${i.fpsBeforeStep.toFixed(1)} → ${e.smoothedFps.toFixed(1)}) — keeping level ${n}`),i.fpsBeforeStep=null,i.stepFromLevel=null),i.fpsBeforeProbe!==null&&t-i.lastChangeTime>=Tv&&o&&(e.smoothedFps<i.fpsBeforeProbe*Dv?(n=Math.min(hr,n+1),E()&&console.debug(`[SplatQuality] conditions collapsed during recovery probe (${i.fpsBeforeProbe.toFixed(1)} → ${e.smoothedFps.toFixed(1)}) — restoring level ${n}`)):e.smoothedFps<i.fpsBeforeProbe*xO?(n=Math.min(hr,n+1),i.upBackoffUntil=t+oc,E()&&console.debug(`[SplatQuality] recovery probe cost fps (${i.fpsBeforeProbe.toFixed(1)} → ${e.smoothedFps.toFixed(1)}) — restoring level ${n}, backing off ${oc}s`)):E()&&console.debug(`[SplatQuality] recovery probe kept (fps ${i.fpsBeforeProbe.toFixed(1)} → ${e.smoothedFps.toFixed(1)}), level ${n}`),i.fpsBeforeProbe=null);const r=e.smoothedFps<e.targetFps*gO,a=e.smoothedFps>=e.targetFps*yO,l=t-i.lastChangeTime>=mO;r?(i.goodStreak=0,l&&t>=i.downBackoffUntil&&n===i.level&&i.fpsBeforeStep===null&&i.fpsBeforeProbe===null&&n<hr?(!(ef[n+1].resolutionScale<ef[n].resolutionScale)||e.smoothedFps<e.targetFps*Iv)&&(i.fpsBeforeStep=e.smoothedFps,i.stepFromLevel=n,n++):l&&t<i.downBackoffUntil&&t>=i.jumpBackoffUntil&&e.smoothedFps<e.targetFps*Iv&&n===i.level&&i.fpsBeforeStep===null&&i.fpsBeforeProbe===null&&n<hr&&(i.fpsBeforeStep=e.smoothedFps,i.stepFromLevel=n,n=hr)):a?(i.goodStreak++,i.goodStreak>=_O&&l&&i.fpsBeforeProbe===null&&n>0&&(n--,i.goodStreak=0)):i.goodStreak=0;const h=n===i.level&&i.fpsBeforeStep===null&&i.fpsBeforeProbe===null;i.stableStreak=h?i.stableStreak+1:0,h&&!r&&n>0&&i.stableStreak>=wO&&l&&t>=i.upBackoffUntil&&t-i.lastStreamingTime>=Av&&(i.fpsBeforeProbe=e.smoothedFps,i.stableStreak=0,n--),n!==i.level&&(E()&&console.debug(`[SplatQuality] adaptation level ${i.level} → ${n} (fps ${e.smoothedFps.toFixed(1)}/${e.targetFps}${n>i.level?", verifying fps gain":i.fpsBeforeProbe!==null?", probing recovery":""})`),i.level=n,i.lastChangeTime=t,Zy(i))}const za=new WeakMap;function aS(s,e){if((za.get(s)??0)>0)return!0;const t=e.renderer.pager;return!!t&&((t.fetchers?.length??0)>0||(t.fetched?.length??0)>0)}const SO=1500;function CO(s,e){e.resumeQuietUntil!==0&&performance.now()>=e.resumeQuietUntil&&(e.renderer.pauseWork=!1,e.resumeQuietUntil=0,E()&&console.debug("[SplatQuality] calm resume over — splat work resumed"));const t=s.time.time,i=aS(s,e);if(i&&(e.lastStreamingTime=Math.max(e.lastStreamingTime,t)),t-e.lastEvalTime<pO||(e.lastEvalTime=t,hO&&PO(s,e),s.time.frameCount<60))return;const n=s.isInXR;let o=(n?s.xrSession?.frameRate:void 0)??60;n&&s.xrFrameRateLimit>0&&(o=Math.min(o,s.xrFrameRateLimit)),rS(s,{smoothedFps:s.time.smoothedFps,targetFps:o,streaming:i},t)}function PO(s,e){const t=e.renderer;if(!t.sortedCenter)return;const i=(a,l)=>{const h=l.getWorldPosition(kO),d=l.getWorldScale(MO),u=(d.x+d.y+d.z)/3,f=t.sortedCenter?h.distanceTo(t.sortedCenter):-1,m=t.lastLod?t.lastLod.pos.distanceTo(h):-1;console.debug(`[SplatSort] ${a} pos=(${h.x.toFixed(4)}, ${h.y.toFixed(4)}, ${h.z.toFixed(4)}) scale=${u.toFixed(4)} sortedCenterDist=${f.toFixed(5)} threshold=${(.001*u).toFixed(5)} lodPosDist=${m.toFixed(4)} activeSplats=${t.activeSplats}`)};if(s.mainCamera){i("mainCamera",s.mainCamera);let a="";for(let l=s.mainCamera.parent;l;l=l.parent)a+=`${l.name||l.type}(s=${l.scale.x.toFixed(2)}) > `;console.debug(`[SplatSort] mainCamera parents: ${a||"none"}`)}if(s.isInXR){const a=s.renderer.xr.getCamera();a&&(i("xrCamera",a),a.cameras?.[0]&&i("xrCamera.eye0",a.cameras[0]))}let n=0;s.scene.traverse(a=>{a.constructor?.name?.includes("SplatMesh")&&n++});const o=(t.pager?.pageLru?.size??0)*(t.pager?.pageSplats??0),r=aS(s,e);console.debug(`[SplatSort] fps=${s.time.smoothedFps.toFixed(1)} splatMeshes=${n} resident=${o}/${t.pager?.maxSplats??0} streaming=${r}(f=${t.pager?.fetchers?.length??0},q=${t.pager?.fetched?.length??0},l=${za.get(s)??0}) lod renderScale=${t.lodRenderScale} splatScale=${t.lodSplatScale} pixelScaleLimit=${t.lastLod?.pixelScaleLimit?.toExponential(3)} maxSplats=${t.lastLod?.maxSplats} adaptLevel=${e.level}`)}const kO=new c.Vector3,MO=new c.Vector3;function OO(s,e){s.minSortIntervalMs=e.minSortIntervalMs,s.numLodFetchers=e.fetchers,s.lodRenderScale=e.lodRenderScale;const t=exports.DeviceUtilities.isiOS()?2/3:1;s.lodSplatScale=e.lodSplatScale*t,s.sortCullHalfAngle=dO??e.sortCullHalfAngle,s.maxStdDev=e.maxStdDev,s.maxPixelRadius=e.maxPixelRadius,s.coneFoveate=e.coneFoveate,s.behindFoveate=e.behindFoveate,s.minAlpha=e.minAlpha,e.maxPagedSplats>0&&!s.pager&&(s.maxPagedSplats=e.maxPagedSplats),s.pager&&(s.pager.numFetchers=e.fetchers),lS=e.xrFramebufferScale}let lS;function Lv(){return lS}let cS=1;function EO(){return cS}function Zy(s){const e=Ky(Ff(s.quality),s.level);if(OO(s.renderer,e),e.resolutionScale!==s.appliedResolutionScale){const t=s.context.resolutionScaleFactor/s.appliedResolutionScale;s.context.resolutionScaleFactor=t*e.resolutionScale,s.appliedResolutionScale=e.resolutionScale,cS=e.resolutionScale,s.context.xr?.setDynamicResolutionScale(e.resolutionScale)}s.context.xr?.refreshRenderResolution(),e.xrMaxFps!==s.appliedXrMaxFps&&(s.context.xrFrameRateLimit===s.appliedXrMaxFps&&(s.context.xrFrameRateLimit=e.xrMaxFps),s.appliedXrMaxFps=e.xrMaxFps),s.context.scene.traverse(t=>t.updateVersion?.())}function RO(s,e){let t;if(s.scene.traverse(i=>{i instanceof e&&(t=i)}),t||(t=new e({renderer:s.renderer}),s.scene.add(t)),gr.has(s))gr.get(s).renderer=t;else{const i={context:s,renderer:t,quality:"auto",level:0,lastChangeTime:0,lastEvalTime:0,goodStreak:0,fpsBeforeStep:null,downBackoffUntil:0,lastStreamingTime:-1/0,stepFromLevel:null,jumpBackoffUntil:0,fpsBeforeProbe:null,upBackoffUntil:0,stableStreak:0,appliedResolutionScale:1,appliedXrMaxFps:0,resumeQuietUntil:0};gr.set(s,i),Zy(i),s.pre_render_callbacks.push(()=>CO(s,i)),typeof document<"u"&&document.addEventListener("visibilitychange",()=>{const n=gr.get(s);if(!n)return;const o=n.renderer;document.visibilityState==="hidden"?(o.pauseWork=!0,n.resumeQuietUntil=Number.POSITIVE_INFINITY):n.resumeQuietUntil=performance.now()+SO})}return t}function TO(s){return!/^(blob:|data:)/i.test(s)}function AO(){mr.some(s=>s.name===rm)||exports.NeedleEngineModelLoader.onCreateCustomModelLoader(s=>{switch(s.mimetype){case"model/ply":case"model/spz":case"model/splat":case"model/ksplat":case"model/sog":case"model/rad":{const e=s.mimetype,t=s.context,i={name:rm,loadAsync:async(n,o)=>{const r=await Promise.resolve().then(()=>require("./vendor-BJviq-Oq.umd.cjs")).then(m=>m.spark_module);if(RO(t,r.SparkRenderer),e==="model/rad"&&TO(n))return new r.SplatMesh({url:n,paged:!0});za.set(t,(za.get(t)??0)+1);const a=()=>za.set(t,Math.max(0,(za.get(t)??1)-1)),l=new r.SplatLoader,h={"model/ply":r.SplatFileType.PLY,"model/spz":r.SplatFileType.SPZ,"model/splat":r.SplatFileType.SPLAT,"model/ksplat":r.SplatFileType.KSPLAT,"model/sog":r.SplatFileType.PCSOGSZIP,"model/rad":r.SplatFileType.RAD}[e];let d;try{d=await new Promise((m,g)=>{l.loadInternal({url:n,fileType:h,onLoad:m,onError:g,onProgress:v=>{if(o&&v.type==="progress"){const _=v;o(new ProgressEvent("progress",{loaded:_.loaded??0,total:_.total??0,lengthComputable:_.total!=null&&_.total>0}))}}})})}catch(m){throw a(),m}const u=d instanceof r.PackedSplats?{packedSplats:d,lod:!0}:{extSplats:d,lod:!0},f=new r.SplatMesh(u);return f.createLodSplats().catch(m=>console.warn("[Needle Engine] Building the splat LOD tree failed — rendering without LOD",m)).finally(a),(e==="model/ply"||e==="model/sog")&&f.quaternion.set(1,0,0,0),f},parse:n=>{const o=typeof n=="string"?new TextEncoder().encode(n):n,r=URL.createObjectURL(new Blob([o]));return i.loadAsync(r).finally(()=>URL.revokeObjectURL(r))}};return i}}return null},{name:rm})}const Ka=new c.Matrix4().makeRotationY(Math.PI),Wi=new c.Quaternion().setFromAxisAngle(new c.Vector3(0,1,0),Math.PI),DO=x("debugwebxr");class IO{priority=-1e5;gameObject;isXRRig(){return!0}get isActive(){return this.gameObject.visible}constructor(){if(this.gameObject=new c.Object3D,this.gameObject.name="Implicit XR Rig",DO){const e=s_(16733661);e.position.y+=.5,this.gameObject.add(e)}}}const _s=x("debugwebxr"),Md=x("debugcustomgesture"),LO="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",BO="generic-trigger",FO=new c.Quaternion().setFromEuler(new c.Euler(c.MathUtils.degToRad(0),c.MathUtils.degToRad(-90),c.MathUtils.degToRad(-90))),jO=new c.Vector3(.04,-.04,0);class Jy{xr;get context(){return this.xr.context}inputSource;index=0;emitEvents=!0;get connected(){return this._connected}_connected=!0;get isTracking(){return this._isTracking}_isTracking=!1;get gamepad(){return this.__gamepad??=this.inputSource.gamepad}__gamepad;get isHand(){return this.hand!=null}get hand(){return this.__hand??=this.inputSource.hand}__hand;get handObject(){return this.context.renderer.xr.getHand(this.index)}get profiles(){return this.inputSource.profiles}get layout(){return this._layout}get targetRayMode(){return this.inputSource.targetRayMode}get targetRaySpace(){return this.inputSource.targetRaySpace}get gripSpace(){return this.inputSource.gripSpace}get side(){return this.__side??=this.inputSource.handedness}__side=void 0;get isRight(){return this.side==="right"}get isLeft(){return this.side==="left"}get isStylus(){return this._isMxInk}getHitTestSource(){return this._hitTestSource||this._requestHitTestSource(),this._hitTestSource}get hasHitTestSource(){return this._hitTestSource}cancelHitTestSource(){this._hitTestSource&&(this._hitTestSource.cancel(),this._hitTestSource=void 0)}_hitTestSource=void 0;_hasSelectEvent=!1;get hasSelectEvent(){return this._hasSelectEvent}_isMxInk=!1;_isMetaQuestTouchController=!1;getHitTest(){return this.xr.getHitTest(this)}_handJointPoses=new Map;getHandJointPose(e,t){if(t=t||this.xr.frame,!this.hand||!t?.getJointPose||!this.xr.referenceSpace)return null;let i=this._handJointPoses?.get(e);return i||(i=t.getJointPose(e,this.xr.referenceSpace),i&&this._handJointPoses.set(e,i),i)}_gripMatrix=new c.Matrix4;_gripPosition=new c.Vector3;_gripQuaternion=new c.Quaternion;_linearVelocity=new c.Vector3;_rayPositionRaw=new c.Vector3;_rayRotationRaw=new c.Quaternion;_rayMatrix=new c.Matrix4;_rayPosition=new c.Vector3;_rayQuaternion=new c.Quaternion;get gripPosition(){return F(this._gripPosition)}get gripQuaternion(){return ci(this._gripQuaternion)}get gripMatrix(){return this._gripMatrix}get gripLinearVelocity(){return F(this._linearVelocity).applyQuaternion(Wi)}get rayPosition(){return F(this._rayPosition)}get rayQuaternion(){return ci(this._rayQuaternion)}get gripWorldPosition(){return F(this._gripWorldPosition)}_gripWorldPosition=new c.Vector3;get gripWorldQuaternion(){return ci(this._gripWorldQuaternion)}_gripWorldQuaternion=new c.Quaternion;get rayWorldPosition(){return F(this._rayWorldPosition)}_rayWorldPosition=new c.Vector3;updateRayWorldPosition(){const e=this.xr.context.mainCamera?.parent;this._rayWorldPosition.copy(this._rayPositionRaw),e&&this._rayWorldPosition.applyMatrix4(e.matrixWorld)}get rayWorldQuaternion(){return ci(this._rayWorldQuaternion)}_rayWorldQuaternion=new c.Quaternion;get pinchPosition(){return F(this._pinchPosition)}_pinchPosition=new c.Vector3;updateRayWorldQuaternion(){const e=this.xr.context.mainCamera?.parent,t=e?Se(e):void 0;this._rayWorldQuaternion.copy(this._rayRotationRaw).multiply(Wi),t&&this._rayWorldQuaternion.premultiply(t)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy(F(0,0,1).applyQuaternion(this.rayWorldQuaternion)),this._ray}_ray;_hand_wristDotUp=void 0;get handWristDotUp(){if(this._hand_wristDotUp!==void 0)return this._hand_wristDotUp;const e=this.handObject?.joints.wrist;if(e){const t=F(0,1,0).applyQuaternion(e.quaternion),i=F(0,1,0).dot(t);return this._hand_wristDotUp=i}}get isHandUpsideDown(){return this.handWristDotUp!==void 0?this.handWristDotUp<-.7:!1}get isTeleportGesture(){return this.isHandUpsideDown&&this.getGesture("pinch")?.isDown}get object(){return this._object}_object;_gripSpaceObject;_raySpaceObject;model=null;_debugAxesHelper=new c.AxesHelper(.15);_debugGripAxesHelper=new c.AxesHelper(.07);_debugRayAxesHelper=new c.AxesHelper(.07);async getModelUrl(){return this.getMotionController?.then(e=>e?.assetUrl||null)}constructor(e,t,i){this.xr=e,this.inputSource=t,this.index=i,this._object=new c.Object3D,this._object.name=`NeedleXRController_${i}`,_s&&(this._object.add(this._debugAxesHelper),this._gripSpaceObject=new c.Object3D,this._raySpaceObject=new c.Object3D,this._gripSpaceObject.name=`NeedleXRController_${i}_gripSpace`,this._raySpaceObject.name=`NeedleXRController_${i}_raySpace`,this._gripSpaceObject.add(this._debugGripAxesHelper),this._raySpaceObject.add(this._debugRayAxesHelper),this.xr.context.scene.add(this._gripSpaceObject),this.xr.context.scene.add(this._raySpaceObject)),this.xr.context.scene.add(this._object),this._ray=new c.Ray,this.pointerInit={origin:this,pointerType:this.hand?"hand":"controller",deviceIndex:this.index,pointerId:-1,mode:this.inputSource.targetRayMode,ray:this._ray,device:this._object,buttonName:"none"},this.initialize(),this.subscribeEvents()}_hitTestSourcePromise=null;_requestHitTestSource(){return this._hitTestSourcePromise?this._hitTestSourcePromise:this.xr.mode==="immersive-ar"&&this.inputSource.targetRayMode==="tracked-pointer"&&this.xr.session.requestHitTestSourceForTransientInput?this._hitTestSourcePromise=this.xr.session.requestHitTestSourceForTransientInput({profile:this.inputSource.profiles[0],offsetRay:new XRRay})?.then(e=>(this._hitTestSourcePromise=null,this.connected?this._hitTestSource=e:(e.cancel(),null)))??null:null}onPointerHits=e=>{};onUpdate(e){this.onUpdateFrame(e),this.updateInputEvents(),this.onUpdateMove()}onRenderDebug(){B.DrawSphere(this.rayWorldPosition,.003),B.DrawDirection(this.rayWorldPosition,F(0,0,10).applyQuaternion(this.rayWorldQuaternion));const t=(this.inputSource.gripSpace?this.gripWorldPosition:this.object.worldPosition).sub(this.object.worldForward.multiplyScalar(.1)),i=this.inputSource.profiles.join(`
|
|
411
|
+
If you need multisampling consider changing 'auto' to a fixed value (e.g. 4).`));else{const i=e.time.realtimeSinceStartup-this._multisampleAutoChangeTime;if(e.time.realtimeSinceStartup-this._enabledTime>2&&i>.5){const n=this._handler.multisampling;if(this._handler.multisampling>0&&e.time.smoothedFps<=50){this._multisampleAutoChangeTime=e.time.realtimeSinceStartup,this._multisampleAutoDecreaseTime=e.time.realtimeSinceStartup;let o=this._handler.multisampling*.5;o=Math.floor(o),o!=this._handler.multisampling&&(this._handler.multisampling=o),Zo&&console.debug(`[PostProcessing] Reduced multisampling from ${n} to ${this._handler.multisampling}`)}else if(i>1&&e.time.smoothedFps>=59&&this._handler.multisampling<e.renderer.capabilities.maxSamples&&e.time.realtimeSinceStartup-this._multisampleAutoDecreaseTime>10){this._multisampleAutoChangeTime=e.time.realtimeSinceStartup;let o=this._handler.multisampling<=0?1:this._handler.multisampling*2;o=Math.floor(o),o!==this._handler.multisampling&&(this._handler.multisampling=o),Zo&&console.debug(`[PostProcessing] Increased multisampling from ${n} to ${this._handler.multisampling}`)}}}else{const i=Math.max(0,Math.min(this.multisampling,e.renderer.capabilities.maxSamples));i!==this._handler.multisampling&&(this._handler.multisampling=i)}if(this._handler.adaptivePixelRatio=this.adaptiveResolution,this._handler.updateAdaptivePixelRatio(),e.mainCamera){const i=t.passes;for(const n of i)if(n.mainCamera&&n.mainCamera!==e.mainCamera){t.setMainCamera(e.mainCamera);break}}}_lastApplyTime;_rapidApplyCount=0;_tonemappingOnlyActive=!1;_previousToneMapping;_previousToneMappingExposure;apply(){Zo&&console.log(`[PostProcessing] Apply stack (${this._effects.length} effects)`),E()&&(this._lastApplyTime!==void 0&&Date.now()-this._lastApplyTime<100&&(this._rapidApplyCount++,this._rapidApplyCount===5&&console.warn("[PostProcessing] Detected rapid post processing modifications - this might be a bug")),this._lastApplyTime=Date.now()),this._isDirty=!1;const e=this._enabled?this._effects.filter(i=>i.active&&i.enabled):[];if(e.length<=0){this.restoreTonemapping(),this._handler?.unapply(!1);return}if(e.every(i=>i.isToneMapping===!0)){const i=e[e.length-1];Zo&&console.log("[PostProcessing] Only tonemapping effects in stack — applying directly to renderer"),this._tonemappingOnlyActive||(this._previousToneMapping=this._context.renderer.toneMapping,this._previousToneMappingExposure=this._context.renderer.toneMappingExposure,this._tonemappingOnlyActive=!0),this._context.renderer.toneMapping=i.threeToneMapping,this._context.renderer.toneMappingExposure=i.toneMappingExposure,this._handler?.unapply(!1);return}this.restoreTonemapping(),this.ensureHandler().then(i=>{if(i)return i.apply(e)}).then(()=>{this._handler&&(this.multisampling==="auto"?this._handler.multisampling=exports.DeviceUtilities.isMobileDevice()?2:4:this._handler.multisampling=Math.max(0,Math.min(this.multisampling,this._context.renderer.capabilities.maxSamples)),Zo&&console.debug(`[PostProcessing] Set multisampling to ${this._handler.multisampling} (Is Mobile: ${exports.DeviceUtilities.isMobileDevice()})`))}).catch(i=>{console.error("[PostProcessing] Failed to build/apply the postprocessing pipeline",i)}),this._enabledTime=this._context.time.realtimeSinceStartup}restoreTonemapping(){this._tonemappingOnlyActive&&(this._previousToneMapping!==void 0&&(this._context.renderer.toneMapping=this._previousToneMapping),this._previousToneMappingExposure!==void 0&&(this._context.renderer.toneMappingExposure=this._previousToneMappingExposure),this._tonemappingOnlyActive=!1,this._previousToneMapping=void 0,this._previousToneMappingExposure=void 0,Zo&&console.log("[PostProcessing] Restored renderer tonemapping"))}async ensureHandler(){if(!this._handler){const{PostProcessingHandler:e}=await Promise.resolve().then(()=>F3);this._handler||(this._handler=new e(this._context))}return this._handler}dispose(){this.restoreTonemapping(),this._handler?.dispose(),this._handler=null,this._composer=null,this._effects.length=0}}const mr=[],Su=[];exports.NeedleEngineModelLoader=void 0;(s=>{function e(i,n){const o={name:n?.name,priority:n?.priority??0,callback:i};return mr.push(o),mr.sort((r,a)=>r.priority===a.priority?0:r.priority>a.priority?-1:1),()=>{const r=mr.indexOf(o);r>=0&&mr.splice(r,1)}}s.onCreateCustomModelLoader=e;function t(i){return Su.push(i),()=>{const n=Su.indexOf(i);n>=0&&Su.splice(n,1)}}s.onDetermineModelMimetype=t})(exports.NeedleEngineModelLoader||(exports.NeedleEngineModelLoader={}));const rm="Gaussian Splat Loader",hO=x("debugsplats")||x("debugsplatsort")||x("debugspatsort"),dO=(()=>{const s=x("splatcull"),e=typeof s=="number"?s:typeof s=="string"?parseFloat(s):NaN;return Number.isFinite(e)&&e>0?Math.min(Math.PI,e*(Math.PI/180)):void 0})(),uO={high:{maxSh:3,minSortIntervalMs:150,fetchers:3,lodRenderScale:1,lodSplatScale:1,maxStdDev:Math.sqrt(8),maxPixelRadius:512,coneFoveate:.4,behindFoveate:.2,xrFramebufferScale:1,maxPagedSplats:0,minAlpha:.5/255,resolutionScale:1,sortCullHalfAngle:Math.PI,xrMaxFps:0},medium:{maxSh:2,minSortIntervalMs:200,fetchers:2,lodRenderScale:1,lodSplatScale:1,maxStdDev:Math.sqrt(8),maxPixelRadius:384,coneFoveate:.3,behindFoveate:.15,xrFramebufferScale:.9,maxPagedSplats:0,minAlpha:.5/255,resolutionScale:1,sortCullHalfAngle:120/180*Math.PI,xrMaxFps:0},low:{maxSh:1,minSortIntervalMs:250,fetchers:1,lodRenderScale:1,lodSplatScale:1,maxStdDev:Math.sqrt(7),maxPixelRadius:320,coneFoveate:.25,behindFoveate:.1,xrFramebufferScale:.8,maxPagedSplats:48*65536,minAlpha:.5/255,resolutionScale:1,sortCullHalfAngle:110/180*Math.PI,xrMaxFps:30}};function Ff(s,e=exports.DeviceUtilities.isMobileDevice()){return{...uO[s==="auto"?e?"low":"high":s]}}function Tg(s,e,t){const i=Ff(t),n=gr.get(s);n&&(n.quality=t,t!=="auto"&&(n.level=0,n.fpsBeforeStep=null,n.downBackoffUntil=0,n.goodStreak=0,n.stepFromLevel=null,n.jumpBackoffUntil=0,n.fpsBeforeProbe=null,n.upBackoffUntil=0,n.stableStreak=0),Zy(n));const o=e;if(o){typeof o.maxSh=="number"&&(o.maxSh=i.maxSh);const r=o.paged;r&&(r.setMaxSh(i.maxSh),r.pager&&(r.pager.numFetchers=i.fetchers))}return i}const ef=[{lodRenderScale:1,lodSplatScale:1,maxPixelRadius:1,maxStdDevCap:Number.POSITIVE_INFINITY,foveate:1,minAlphaFloor:0,resolutionScale:1},{lodRenderScale:1.5,lodSplatScale:.75,maxPixelRadius:1,maxStdDevCap:Number.POSITIVE_INFINITY,foveate:.8,minAlphaFloor:0,resolutionScale:1},{lodRenderScale:2.25,lodSplatScale:.5,maxPixelRadius:.75,maxStdDevCap:Math.sqrt(7),foveate:.6,minAlphaFloor:0,resolutionScale:1},{lodRenderScale:3.5,lodSplatScale:.35,maxPixelRadius:.5,maxStdDevCap:Math.sqrt(6),foveate:.45,minAlphaFloor:0,resolutionScale:1},{lodRenderScale:3.5,lodSplatScale:.35,maxPixelRadius:.5,maxStdDevCap:Math.sqrt(6),foveate:.45,minAlphaFloor:4/255,resolutionScale:1},{lodRenderScale:3.5,lodSplatScale:.35,maxPixelRadius:.5,maxStdDevCap:Math.sqrt(6),foveate:.45,minAlphaFloor:10/255,resolutionScale:1},{lodRenderScale:3.5,lodSplatScale:.35,maxPixelRadius:.5,maxStdDevCap:Math.sqrt(6),foveate:.45,minAlphaFloor:10/255,resolutionScale:.75},{lodRenderScale:3.5,lodSplatScale:.35,maxPixelRadius:.5,maxStdDevCap:Math.sqrt(6),foveate:.45,minAlphaFloor:10/255,resolutionScale:.6}],hr=ef.length-1;function Ky(s,e){const t=Math.max(0,Math.min(hr,Math.round(e))),i=ef[t];return{...s,lodRenderScale:s.lodRenderScale*i.lodRenderScale,lodSplatScale:s.lodSplatScale*i.lodSplatScale,maxPixelRadius:Math.round(s.maxPixelRadius*i.maxPixelRadius),maxStdDev:Math.min(s.maxStdDev,i.maxStdDevCap),coneFoveate:Math.max(.05,s.coneFoveate*i.foveate),behindFoveate:Math.max(.05,s.behindFoveate*i.foveate),minAlpha:Math.max(s.minAlpha,i.minAlphaFloor),resolutionScale:s.resolutionScale*i.resolutionScale}}const gr=new WeakMap;function fO(s){const e=gr.get(s);return e?{quality:e.quality,adaptationLevel:e.level,effective:Ky(Ff(e.quality),e.level)}:null}const pO=1,mO=2,gO=.8,yO=.95,_O=4,Tv=3,bO=1.1,oc=30,Av=2,vO=10,Dv=.8,wO=8,xO=.9,Iv=.5;function rS(s,e,t){const i=gr.get(s);if(!i||i.quality!=="auto")return;let n=i.level;e.streaming&&(i.lastStreamingTime=Math.max(i.lastStreamingTime,t));const o=t-i.lastStreamingTime>=Av||t-i.lastChangeTime>=vO;i.fpsBeforeStep!==null&&t-i.lastChangeTime>=Tv&&o&&(e.smoothedFps<i.fpsBeforeStep*Dv?E()&&console.debug(`[SplatQuality] conditions collapsed since the degradation (${i.fpsBeforeStep.toFixed(1)} → ${e.smoothedFps.toFixed(1)}) — discarding the measurement, keeping level ${n}`):e.smoothedFps<i.fpsBeforeStep*bO?(n=i.stepFromLevel??Math.max(0,n-1),i.downBackoffUntil=t+oc,i.stepFromLevel!==null&&i.level-i.stepFromLevel>1&&(i.jumpBackoffUntil=t+oc),E()&&console.debug(`[SplatQuality] degradation bought no fps (${i.fpsBeforeStep.toFixed(1)} → ${e.smoothedFps.toFixed(1)}) — reverting to level ${n}, backing off ${oc}s`)):E()&&console.debug(`[SplatQuality] degradation bought fps (${i.fpsBeforeStep.toFixed(1)} → ${e.smoothedFps.toFixed(1)}) — keeping level ${n}`),i.fpsBeforeStep=null,i.stepFromLevel=null),i.fpsBeforeProbe!==null&&t-i.lastChangeTime>=Tv&&o&&(e.smoothedFps<i.fpsBeforeProbe*Dv?(n=Math.min(hr,n+1),E()&&console.debug(`[SplatQuality] conditions collapsed during recovery probe (${i.fpsBeforeProbe.toFixed(1)} → ${e.smoothedFps.toFixed(1)}) — restoring level ${n}`)):e.smoothedFps<i.fpsBeforeProbe*xO?(n=Math.min(hr,n+1),i.upBackoffUntil=t+oc,E()&&console.debug(`[SplatQuality] recovery probe cost fps (${i.fpsBeforeProbe.toFixed(1)} → ${e.smoothedFps.toFixed(1)}) — restoring level ${n}, backing off ${oc}s`)):E()&&console.debug(`[SplatQuality] recovery probe kept (fps ${i.fpsBeforeProbe.toFixed(1)} → ${e.smoothedFps.toFixed(1)}), level ${n}`),i.fpsBeforeProbe=null);const r=e.smoothedFps<e.targetFps*gO,a=e.smoothedFps>=e.targetFps*yO,l=t-i.lastChangeTime>=mO;r?(i.goodStreak=0,l&&t>=i.downBackoffUntil&&n===i.level&&i.fpsBeforeStep===null&&i.fpsBeforeProbe===null&&n<hr?(!(ef[n+1].resolutionScale<ef[n].resolutionScale)||e.smoothedFps<e.targetFps*Iv)&&(i.fpsBeforeStep=e.smoothedFps,i.stepFromLevel=n,n++):l&&t<i.downBackoffUntil&&t>=i.jumpBackoffUntil&&e.smoothedFps<e.targetFps*Iv&&n===i.level&&i.fpsBeforeStep===null&&i.fpsBeforeProbe===null&&n<hr&&(i.fpsBeforeStep=e.smoothedFps,i.stepFromLevel=n,n=hr)):a?(i.goodStreak++,i.goodStreak>=_O&&l&&i.fpsBeforeProbe===null&&n>0&&(n--,i.goodStreak=0)):i.goodStreak=0;const h=n===i.level&&i.fpsBeforeStep===null&&i.fpsBeforeProbe===null;i.stableStreak=h?i.stableStreak+1:0,h&&!r&&n>0&&i.stableStreak>=wO&&l&&t>=i.upBackoffUntil&&t-i.lastStreamingTime>=Av&&(i.fpsBeforeProbe=e.smoothedFps,i.stableStreak=0,n--),n!==i.level&&(E()&&console.debug(`[SplatQuality] adaptation level ${i.level} → ${n} (fps ${e.smoothedFps.toFixed(1)}/${e.targetFps}${n>i.level?", verifying fps gain":i.fpsBeforeProbe!==null?", probing recovery":""})`),i.level=n,i.lastChangeTime=t,Zy(i))}const za=new WeakMap;function aS(s,e){if((za.get(s)??0)>0)return!0;const t=e.renderer.pager;return!!t&&((t.fetchers?.length??0)>0||(t.fetched?.length??0)>0)}const SO=1500;function CO(s,e){e.resumeQuietUntil!==0&&performance.now()>=e.resumeQuietUntil&&(e.renderer.pauseWork=!1,e.resumeQuietUntil=0,E()&&console.debug("[SplatQuality] calm resume over — splat work resumed"));const t=s.time.time,i=aS(s,e);if(i&&(e.lastStreamingTime=Math.max(e.lastStreamingTime,t)),t-e.lastEvalTime<pO||(e.lastEvalTime=t,hO&&PO(s,e),s.time.frameCount<60))return;const n=s.isInXR;let o=(n?s.xrSession?.frameRate:void 0)??60;n&&s.xrFrameRateLimit>0&&(o=Math.min(o,s.xrFrameRateLimit)),rS(s,{smoothedFps:s.time.smoothedFps,targetFps:o,streaming:i},t)}function PO(s,e){const t=e.renderer;if(!t.sortedCenter)return;const i=(a,l)=>{const h=l.getWorldPosition(kO),d=l.getWorldScale(MO),u=(d.x+d.y+d.z)/3,f=t.sortedCenter?h.distanceTo(t.sortedCenter):-1,m=t.lastLod?t.lastLod.pos.distanceTo(h):-1;console.debug(`[SplatSort] ${a} pos=(${h.x.toFixed(4)}, ${h.y.toFixed(4)}, ${h.z.toFixed(4)}) scale=${u.toFixed(4)} sortedCenterDist=${f.toFixed(5)} threshold=${(.001*u).toFixed(5)} lodPosDist=${m.toFixed(4)} activeSplats=${t.activeSplats}`)};if(s.mainCamera){i("mainCamera",s.mainCamera);let a="";for(let l=s.mainCamera.parent;l;l=l.parent)a+=`${l.name||l.type}(s=${l.scale.x.toFixed(2)}) > `;console.debug(`[SplatSort] mainCamera parents: ${a||"none"}`)}if(s.isInXR){const a=s.renderer.xr.getCamera();a&&(i("xrCamera",a),a.cameras?.[0]&&i("xrCamera.eye0",a.cameras[0]))}let n=0;s.scene.traverse(a=>{a.constructor?.name?.includes("SplatMesh")&&n++});const o=(t.pager?.pageLru?.size??0)*(t.pager?.pageSplats??0),r=aS(s,e);console.debug(`[SplatSort] fps=${s.time.smoothedFps.toFixed(1)} splatMeshes=${n} resident=${o}/${t.pager?.maxSplats??0} streaming=${r}(f=${t.pager?.fetchers?.length??0},q=${t.pager?.fetched?.length??0},l=${za.get(s)??0}) lod renderScale=${t.lodRenderScale} splatScale=${t.lodSplatScale} pixelScaleLimit=${t.lastLod?.pixelScaleLimit?.toExponential(3)} maxSplats=${t.lastLod?.maxSplats} adaptLevel=${e.level}`)}const kO=new c.Vector3,MO=new c.Vector3;function OO(s,e){s.minSortIntervalMs=e.minSortIntervalMs,s.numLodFetchers=e.fetchers,s.lodRenderScale=e.lodRenderScale;const t=exports.DeviceUtilities.isiOS()?2/3:1;s.lodSplatScale=e.lodSplatScale*t,s.sortCullHalfAngle=dO??e.sortCullHalfAngle,s.maxStdDev=e.maxStdDev,s.maxPixelRadius=e.maxPixelRadius,s.coneFoveate=e.coneFoveate,s.behindFoveate=e.behindFoveate,s.minAlpha=e.minAlpha,e.maxPagedSplats>0&&!s.pager&&(s.maxPagedSplats=e.maxPagedSplats),s.pager&&(s.pager.numFetchers=e.fetchers),lS=e.xrFramebufferScale}let lS;function Lv(){return lS}let cS=1;function EO(){return cS}function Zy(s){const e=Ky(Ff(s.quality),s.level);if(OO(s.renderer,e),e.resolutionScale!==s.appliedResolutionScale){const t=s.context.resolutionScaleFactor/s.appliedResolutionScale;s.context.resolutionScaleFactor=t*e.resolutionScale,s.appliedResolutionScale=e.resolutionScale,cS=e.resolutionScale,s.context.xr?.setDynamicResolutionScale(e.resolutionScale)}s.context.xr?.refreshRenderResolution(),e.xrMaxFps!==s.appliedXrMaxFps&&(s.context.xrFrameRateLimit===s.appliedXrMaxFps&&(s.context.xrFrameRateLimit=e.xrMaxFps),s.appliedXrMaxFps=e.xrMaxFps),s.context.scene.traverse(t=>t.updateVersion?.())}function RO(s,e){let t;if(s.scene.traverse(i=>{i instanceof e&&(t=i)}),t||(t=new e({renderer:s.renderer}),s.scene.add(t)),gr.has(s))gr.get(s).renderer=t;else{const i={context:s,renderer:t,quality:"auto",level:0,lastChangeTime:0,lastEvalTime:0,goodStreak:0,fpsBeforeStep:null,downBackoffUntil:0,lastStreamingTime:-1/0,stepFromLevel:null,jumpBackoffUntil:0,fpsBeforeProbe:null,upBackoffUntil:0,stableStreak:0,appliedResolutionScale:1,appliedXrMaxFps:0,resumeQuietUntil:0};gr.set(s,i),Zy(i),s.pre_render_callbacks.push(()=>CO(s,i)),typeof document<"u"&&document.addEventListener("visibilitychange",()=>{const n=gr.get(s);if(!n)return;const o=n.renderer;document.visibilityState==="hidden"?(o.pauseWork=!0,n.resumeQuietUntil=Number.POSITIVE_INFINITY):n.resumeQuietUntil=performance.now()+SO})}return t}function TO(s){return!/^(blob:|data:)/i.test(s)}function AO(){mr.some(s=>s.name===rm)||exports.NeedleEngineModelLoader.onCreateCustomModelLoader(s=>{switch(s.mimetype){case"model/ply":case"model/spz":case"model/splat":case"model/ksplat":case"model/sog":case"model/rad":{const e=s.mimetype,t=s.context,i={name:rm,loadAsync:async(n,o)=>{const r=await Promise.resolve().then(()=>require("./vendor-CDN1hirK.umd.cjs")).then(m=>m.spark_module);if(RO(t,r.SparkRenderer),e==="model/rad"&&TO(n))return new r.SplatMesh({url:n,paged:!0});za.set(t,(za.get(t)??0)+1);const a=()=>za.set(t,Math.max(0,(za.get(t)??1)-1)),l=new r.SplatLoader,h={"model/ply":r.SplatFileType.PLY,"model/spz":r.SplatFileType.SPZ,"model/splat":r.SplatFileType.SPLAT,"model/ksplat":r.SplatFileType.KSPLAT,"model/sog":r.SplatFileType.PCSOGSZIP,"model/rad":r.SplatFileType.RAD}[e];let d;try{d=await new Promise((m,g)=>{l.loadInternal({url:n,fileType:h,onLoad:m,onError:g,onProgress:v=>{if(o&&v.type==="progress"){const _=v;o(new ProgressEvent("progress",{loaded:_.loaded??0,total:_.total??0,lengthComputable:_.total!=null&&_.total>0}))}}})})}catch(m){throw a(),m}const u=d instanceof r.PackedSplats?{packedSplats:d,lod:!0}:{extSplats:d,lod:!0},f=new r.SplatMesh(u);return f.createLodSplats().catch(m=>console.warn("[Needle Engine] Building the splat LOD tree failed — rendering without LOD",m)).finally(a),(e==="model/ply"||e==="model/sog")&&f.quaternion.set(1,0,0,0),f},parse:n=>{const o=typeof n=="string"?new TextEncoder().encode(n):n,r=URL.createObjectURL(new Blob([o]));return i.loadAsync(r).finally(()=>URL.revokeObjectURL(r))}};return i}}return null},{name:rm})}const Ka=new c.Matrix4().makeRotationY(Math.PI),Wi=new c.Quaternion().setFromAxisAngle(new c.Vector3(0,1,0),Math.PI),DO=x("debugwebxr");class IO{priority=-1e5;gameObject;isXRRig(){return!0}get isActive(){return this.gameObject.visible}constructor(){if(this.gameObject=new c.Object3D,this.gameObject.name="Implicit XR Rig",DO){const e=s_(16733661);e.position.y+=.5,this.gameObject.add(e)}}}const _s=x("debugwebxr"),Md=x("debugcustomgesture"),LO="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",BO="generic-trigger",FO=new c.Quaternion().setFromEuler(new c.Euler(c.MathUtils.degToRad(0),c.MathUtils.degToRad(-90),c.MathUtils.degToRad(-90))),jO=new c.Vector3(.04,-.04,0);class Jy{xr;get context(){return this.xr.context}inputSource;index=0;emitEvents=!0;get connected(){return this._connected}_connected=!0;get isTracking(){return this._isTracking}_isTracking=!1;get gamepad(){return this.__gamepad??=this.inputSource.gamepad}__gamepad;get isHand(){return this.hand!=null}get hand(){return this.__hand??=this.inputSource.hand}__hand;get handObject(){return this.context.renderer.xr.getHand(this.index)}get profiles(){return this.inputSource.profiles}get layout(){return this._layout}get targetRayMode(){return this.inputSource.targetRayMode}get targetRaySpace(){return this.inputSource.targetRaySpace}get gripSpace(){return this.inputSource.gripSpace}get side(){return this.__side??=this.inputSource.handedness}__side=void 0;get isRight(){return this.side==="right"}get isLeft(){return this.side==="left"}get isStylus(){return this._isMxInk}getHitTestSource(){return this._hitTestSource||this._requestHitTestSource(),this._hitTestSource}get hasHitTestSource(){return this._hitTestSource}cancelHitTestSource(){this._hitTestSource&&(this._hitTestSource.cancel(),this._hitTestSource=void 0)}_hitTestSource=void 0;_hasSelectEvent=!1;get hasSelectEvent(){return this._hasSelectEvent}_isMxInk=!1;_isMetaQuestTouchController=!1;getHitTest(){return this.xr.getHitTest(this)}_handJointPoses=new Map;getHandJointPose(e,t){if(t=t||this.xr.frame,!this.hand||!t?.getJointPose||!this.xr.referenceSpace)return null;let i=this._handJointPoses?.get(e);return i||(i=t.getJointPose(e,this.xr.referenceSpace),i&&this._handJointPoses.set(e,i),i)}_gripMatrix=new c.Matrix4;_gripPosition=new c.Vector3;_gripQuaternion=new c.Quaternion;_linearVelocity=new c.Vector3;_rayPositionRaw=new c.Vector3;_rayRotationRaw=new c.Quaternion;_rayMatrix=new c.Matrix4;_rayPosition=new c.Vector3;_rayQuaternion=new c.Quaternion;get gripPosition(){return F(this._gripPosition)}get gripQuaternion(){return ci(this._gripQuaternion)}get gripMatrix(){return this._gripMatrix}get gripLinearVelocity(){return F(this._linearVelocity).applyQuaternion(Wi)}get rayPosition(){return F(this._rayPosition)}get rayQuaternion(){return ci(this._rayQuaternion)}get gripWorldPosition(){return F(this._gripWorldPosition)}_gripWorldPosition=new c.Vector3;get gripWorldQuaternion(){return ci(this._gripWorldQuaternion)}_gripWorldQuaternion=new c.Quaternion;get rayWorldPosition(){return F(this._rayWorldPosition)}_rayWorldPosition=new c.Vector3;updateRayWorldPosition(){const e=this.xr.context.mainCamera?.parent;this._rayWorldPosition.copy(this._rayPositionRaw),e&&this._rayWorldPosition.applyMatrix4(e.matrixWorld)}get rayWorldQuaternion(){return ci(this._rayWorldQuaternion)}_rayWorldQuaternion=new c.Quaternion;get pinchPosition(){return F(this._pinchPosition)}_pinchPosition=new c.Vector3;updateRayWorldQuaternion(){const e=this.xr.context.mainCamera?.parent,t=e?Se(e):void 0;this._rayWorldQuaternion.copy(this._rayRotationRaw).multiply(Wi),t&&this._rayWorldQuaternion.premultiply(t)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy(F(0,0,1).applyQuaternion(this.rayWorldQuaternion)),this._ray}_ray;_hand_wristDotUp=void 0;get handWristDotUp(){if(this._hand_wristDotUp!==void 0)return this._hand_wristDotUp;const e=this.handObject?.joints.wrist;if(e){const t=F(0,1,0).applyQuaternion(e.quaternion),i=F(0,1,0).dot(t);return this._hand_wristDotUp=i}}get isHandUpsideDown(){return this.handWristDotUp!==void 0?this.handWristDotUp<-.7:!1}get isTeleportGesture(){return this.isHandUpsideDown&&this.getGesture("pinch")?.isDown}get object(){return this._object}_object;_gripSpaceObject;_raySpaceObject;model=null;_debugAxesHelper=new c.AxesHelper(.15);_debugGripAxesHelper=new c.AxesHelper(.07);_debugRayAxesHelper=new c.AxesHelper(.07);async getModelUrl(){return this.getMotionController?.then(e=>e?.assetUrl||null)}constructor(e,t,i){this.xr=e,this.inputSource=t,this.index=i,this._object=new c.Object3D,this._object.name=`NeedleXRController_${i}`,_s&&(this._object.add(this._debugAxesHelper),this._gripSpaceObject=new c.Object3D,this._raySpaceObject=new c.Object3D,this._gripSpaceObject.name=`NeedleXRController_${i}_gripSpace`,this._raySpaceObject.name=`NeedleXRController_${i}_raySpace`,this._gripSpaceObject.add(this._debugGripAxesHelper),this._raySpaceObject.add(this._debugRayAxesHelper),this.xr.context.scene.add(this._gripSpaceObject),this.xr.context.scene.add(this._raySpaceObject)),this.xr.context.scene.add(this._object),this._ray=new c.Ray,this.pointerInit={origin:this,pointerType:this.hand?"hand":"controller",deviceIndex:this.index,pointerId:-1,mode:this.inputSource.targetRayMode,ray:this._ray,device:this._object,buttonName:"none"},this.initialize(),this.subscribeEvents()}_hitTestSourcePromise=null;_requestHitTestSource(){return this._hitTestSourcePromise?this._hitTestSourcePromise:this.xr.mode==="immersive-ar"&&this.inputSource.targetRayMode==="tracked-pointer"&&this.xr.session.requestHitTestSourceForTransientInput?this._hitTestSourcePromise=this.xr.session.requestHitTestSourceForTransientInput({profile:this.inputSource.profiles[0],offsetRay:new XRRay})?.then(e=>(this._hitTestSourcePromise=null,this.connected?this._hitTestSource=e:(e.cancel(),null)))??null:null}onPointerHits=e=>{};onUpdate(e){this.onUpdateFrame(e),this.updateInputEvents(),this.onUpdateMove()}onRenderDebug(){B.DrawSphere(this.rayWorldPosition,.003),B.DrawDirection(this.rayWorldPosition,F(0,0,10).applyQuaternion(this.rayWorldQuaternion));const t=(this.inputSource.gripSpace?this.gripWorldPosition:this.object.worldPosition).sub(this.object.worldForward.multiplyScalar(.1)),i=this.inputSource.profiles.join(`
|
|
412
412
|
`);let n=`Controller[${this.index}] (${this.inputSource.targetRayMode}, ${this.side})
|
|
413
413
|
C:${this.connected?"x":"-"} T:${this.isTracking?"x":"-"} Hand:${this.inputSource.hand?"x":"-"} Pen: ${this._isMxInk?"x":"-"}`;if(this.inputSource.hand&&(n+=`
|
|
414
414
|
Pinch: ${this.getGesture("pinch")?.value.toFixed(3)}`),n+=`
|
|
@@ -879,7 +879,7 @@ Possible solutions:
|
|
|
879
879
|
Render:`,{shaders:this.renderer.info.programs?.length,...this.renderer.info.render},`
|
|
880
880
|
Memory:`,{usedMemory:t,...this.renderer.info.memory},`
|
|
881
881
|
Renderer:`,{dpr:this.renderer.getPixelRatio(),windowDpr:window.devicePixelRatio,antialias:i.getContextAttributes()?.antialias,samples:i.getParameter(i.SAMPLES),resolution:`${this.renderer.domElement.width}x${this.renderer.domElement.height}`},`
|
|
882
|
-
Target Framerate: `+this.targetFrameRate)}}this._dispatchReadyAfterFrame&&(this._dispatchReadyAfterFrame=!1,this.domElement.dispatchEvent(new CustomEvent("ready")),se.dispatchCallback(ae.ContextFirstFrameRendered,this))}_tempClearColor=new c.Color;_tempClearColor2=new c.Color;renderNow(e){if(!e&&(e=this.mainCamera,!e))return!1;if(this.handleRendererContextLost(),this._isRendering=!0,this.renderRequiredTextures(),this.renderer.toneMapping!==c.NoToneMapping&&nS(),this.postprocessing.update(),this.composer&&!this.isInXR){e&&"setMainCamera"in this.composer&&this.composer.passes[0]?.mainCamera!=e&&this.composer.setMainCamera(e);const t=this.renderer.getClearColor(this._tempClearColor),i=this.renderer.getClearAlpha();this._tempClearColor2.copy(t),this.renderer.setClearColor(t.convertSRGBToLinear(),this.renderer.getClearAlpha()),this.composer.render(this.time.deltaTime),this.renderer.setClearColor(this._tempClearColor2,i)}else e&&(this.isInXR&&exports.DeviceUtilities.isMacOS()&&this.renderer.clearDepth(),this.renderer.render(this.scene,e));return this._isRendering=!1,!0}_contextRestoreTries=0;handleRendererContextLost(){this.time.frame%10&&this.renderer.getContext().isContextLost()&&this._contextRestoreTries++<100&&(console.warn("Attempting to recover WebGL context..."),this.renderer.forceContextRestore())}_wasPaused=!1;onHandlePaused(){const e=this.evaluatePaused();if(this._wasPaused!==e){aE&&console.log("Paused?",e,"context:"+this.alias);for(let t=0;t<this.scripts_pausedChanged.length;t++){const i=this.scripts_pausedChanged[t];i.activeAndEnabled&&i.onPausedChanged!==void 0&&(_e.Current=this,i.onPausedChanged(e,this._wasPaused))}}return this._wasPaused=e,e}evaluatePaused(){return this.isInXR?!1:this.isPaused?!0:this.runInBackground?!1:!this.isVisibleToUser}renderRequiredTextures(){if(!this.mainCamera||!this._requireDepthTexture&&!this._requireColorTexture)return;if(!this._renderTarget){if(this._renderTarget=new c.WebGLRenderTarget(this.domWidth,this.domHeight),this._requireDepthTexture){const i=new c.DepthTexture(this.domWidth,this.domHeight);this._renderTarget.depthTexture=i}this._requireColorTexture&&(this._renderTarget.texture=new c.Texture,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=c.NearestFilter,this._renderTarget.texture.magFilter=c.NearestFilter,this._renderTarget.texture.format=c.RGBAFormat)}const e=this._renderTarget;e.texture&&(e.texture.colorSpace=this.renderer.outputColorSpace);const t=this.renderer.getRenderTarget();this.renderer.setRenderTarget(e),this.renderer.render(this.scene,this.mainCamera),this.renderer.setRenderTarget(t)}executeCoroutines(e){if(this.coroutines[e]){const i=this.coroutines[e];for(let n=0;n<i.length;n++)try{const o=i[n];if(!o.comp||o.comp.destroyed||!o.main||o.comp.enabled===!1){cE&&console.log("Removing coroutine",o.comp,o.comp.enabled),i.splice(n,1),--n;continue}const a=o.chained;if(a&&a.length>0){const u=a[a.length-1].next();if(u.done&&a.pop(),t(u)&&(o.chained||(o.chained=[]),o.chained.push(u.value)),!u.done)continue}const l=o.main.next();if(l.done===!0){i.splice(n,1),--n;continue}const h=l.value;if(t(h)){if(h.next().done)continue;o.chained||(o.chained=[]),o.chained.push(h)}else if(h instanceof Promise){const d=h;o.chained||(o.chained=[]);const u=zx(d);o.chained?.push(u);continue}}catch(o){console.error(o)}}function t(i){return!!(i&&i.next&&i.return)}}};ye([ge()],me.prototype,"scripts");ye([ge()],me.prototype,"scripts_pausedChanged");ye([ge()],me.prototype,"scripts_earlyUpdate");ye([ge()],me.prototype,"scripts_update");ye([ge()],me.prototype,"scripts_lateUpdate");ye([ge()],me.prototype,"scripts_onBeforeRender");ye([ge()],me.prototype,"scripts_onAfterRender");ye([ge()],me.prototype,"scripts_WithCorroutines");ye([ge()],me.prototype,"scripts_immersive_vr");ye([ge()],me.prototype,"scripts_immersive_ar");ye([ge()],me.prototype,"coroutines");ye([ge("keep")],me.prototype,"post_setup_callbacks");ye([ge("keep")],me.prototype,"pre_update_callbacks");ye([ge("keep")],me.prototype,"pre_render_callbacks");ye([ge("keep")],me.prototype,"post_render_callbacks");ye([ge()],me.prototype,"pre_update_oneshot_callbacks");ye([ge()],me.prototype,"new_scripts");ye([ge()],me.prototype,"new_script_start");ye([ge()],me.prototype,"new_scripts_pre_setup_callbacks");ye([ge()],me.prototype,"new_scripts_post_setup_callbacks");ye([ge()],me.prototype,"new_scripts_xr");ye([ge("undefined")],me.prototype,"mainCameraComponent");ye([ge("null")],me.prototype,"_mainCamera");ye([ge("null")],me.prototype,"_fallbackCamera");ye([ge("custom")],me.prototype,"_events");ye([ge("custom")],me.prototype,"lights");ye([ge("keep")],me.prototype,"_disposeCallbacks");ye([ge()],me.prototype,"_cameraStack");ye([ge("custom")],me.prototype,"_onBeforeRenderListeners");ye([ge("custom")],me.prototype,"_onAfterRenderListeners");ye([ge("keep")],me.prototype,"rootSceneSourceIdentifiers");let X=me;const um=x("debugwebxr");class wS{static tryFindAvatarObjects(e,t,i){if(i.head&&i.leftHand&&i.rightHand)return;const n=e.name.toLocaleLowerCase();!i.head&&n.includes("head")&&(um&&console.log("FOUND AVATAR HEAD",e.name),i.head=new J("",t,e)),n.includes("hand")&&(!i.leftHand&&n.includes("left")&&(um&&console.log("FOUND AVATAR LEFT HAND",e.name),i.leftHand=new J("",t,e)),!i.rightHand&&n.includes("right")&&(um&&console.log("FOUND AVATAR RIGHT HAND",e.name),i.rightHand=new J("",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 oe 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.setRGB(Number.isFinite(e)?e:0,Number.isFinite(t)?t:0,Number.isFinite(i)?i:0),this.alpha=typeof n=="number"&&Number.isFinite(n)?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=L.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=L.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 oe(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 oe(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 oe(i/255,n/255,o/255,1)}else if(e.startsWith("rgba")){const t=e.slice(5,-1).split(",").map(Number);return new oe(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 oe(t[0]/255,t[1]/255,t[2]/255,1)}}else if(Array.isArray(e)){if(e.length===4)return new oe(e[0],e[1],e[2],e[3]);if(e.length===3)return new oe(e[0],e[1],e[2],1);console.error("Invalid color array length. Expected 3 or 4, got "+e.length)}return new oe(e)}}const Bt=new c.Vector3,Vv=new c.Vector3,Wv=new c.Quaternion,uE=x("debuggizmos"),un=8947848,fm=32;class B{constructor(){}static enabled=!0;static isGizmo(e){return e[Lg]!==void 0}static setVisible(e){for(const t of ri.timedObjectsBuffer)t.visible=e}static DrawLabel(e,t,i=.05,n=0,o,r,a,l=!0){if(!B.enabled)return null;o||(o=un);const h=N.active?.rigScale??1,d=ri.getTextLabel(n,t,i*h,o,r);return d[xS]=l===!1,a instanceof c.Object3D&&a.add(d),d.position.x=e.x,d.position.y=e.y,d.position.z=e.z,d}static DrawRay(e,t,i=un,n=0,o=!0){if(!B.enabled)return;const r=ri.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),Bt.set(t.x,t.y,t.z).multiplyScalar(999999999),a.setXYZ(1,e.x+Bt.x,e.y+Bt.y,e.z+Bt.z),a.needsUpdate=!0,r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1,mn(r.material,i)}static DrawDirection(e,t,i=un,n=0,o=!0,r=1){if(!B.enabled)return;const a=ri.getLine(n),l=a.geometry.getAttribute("position");l.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(Bt.set(0,0,-r),Wv.set(t.x,t.y,t.z,t.w),Bt.applyQuaternion(Wv)):(Bt.set(t.x,t.y,t.z),Bt.multiplyScalar(r)),l.setXYZ(1,e.x+Bt.x,e.y+Bt.y,e.z+Bt.z),l.needsUpdate=!0,a.material.depthTest=o,a.material.depthWrite=!1,mn(a.material,i)}static DrawLine(e,t,i=un,n=0,o=!0){if(!B.enabled)return;const r=ri.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,mn(r.material,i)}static DrawCircle(e,t,i,n=un,o=0,r=!0){if(!B.enabled)return;const a=ri.getCircle(o);a.position.set(e.x,e.y,e.z),a.scale.set(i,i,i),a.quaternion.setFromUnitVectors(this._up,Bt.set(t.x,t.y,t.z).normalize()),a.material.depthTest=r,a.material.depthWrite=!1,a.material.fog=!1,mn(a.material,n)}static DrawWireSphere(e,t,i=un,n=0,o=!0){if(!B.enabled)return;const r=ri.getSphere(t,n,!0);Ar(r,e.x,e.y,e.z),r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1,mn(r.material,i)}static DrawSphere(e,t,i=un,n=0,o=!0){if(!B.enabled)return;const r=ri.getSphere(t,n,!1);Ar(r,e.x,e.y,e.z),r.material.depthTest=o,r.material.depthWrite=!1,mn(r.material,i)}static DrawWireBox(e,t,i=un,n=0,o=!0,r=void 0){if(!B.enabled)return;const a=ri.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,mn(a.material,i)}static DrawWireBox3(e,t=un,i=0,n=!0){if(!B.enabled)return;const o=ri.getBox(i);o.position.copy(e.getCenter(Bt)),o.scale.copy(e.getSize(Bt)),o.material.depthTest=n,o.material.wireframe=!0,o.material.depthWrite=!1,o.material.fog=!1,mn(o.material,t)}static _up=new c.Vector3(0,1,0);static DrawArrow(e,t,i=un,n=0,o=!0,r=!1){if(!B.enabled)return;const a=ri.getArrowHead(n);a.position.set(t.x,t.y,t.z),a.quaternion.setFromUnitVectors(this._up.set(0,1,0),Bt.set(t.x,t.y,t.z).sub(Vv.set(e.x,e.y,e.z)).normalize());const h=Bt.set(t.x,t.y,t.z).sub(Vv.set(e.x,e.y,e.z)).length()*.1;a.scale.set(h,h,h),a.material.depthTest=o,a.material.wireframe=r,mn(a.material,i),this.DrawLine(e,t,i,n,o)}static DrawWireMesh(e){const t=ri.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,mn(t.material,e.color??un)}}const fE=new c.BoxGeometry(1,1,1);function s_(s=null){const e=new c.Color(s??14540253),t=new c.EdgesGeometry(fE);return new c.LineSegments(t,new c.LineBasicMaterial({color:e}))}function mn(s,e){if(Array.isArray(s)){for(const i of s)mn(i,e);return}const t=e instanceof oe?e.a:1;s.color.set(e),s.opacity=t,s.transparent=t<1}const Lg=Symbol("GizmoCache"),xS=Symbol("GizmoLabelOnTop");class ri{static familyName="needle-gizmos";static ensureFont(){let e=le.__webpack_exports__default.FontLibrary.getFontFamily(this.familyName);e||(e=le.__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",()=>{le.__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),uE&&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 le.__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(X.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(X.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(X.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(fm*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/(fm-1);for(let h=0;h<fm+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(X.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(X.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(X.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(X.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[Lg]=n,t.castShadow=!1,t.receiveShadow=!1,t.isGizmo=!0,this.timedObjectsBuffer.push(t),this.timesBuffer.push(X.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,le.__webpack_exports__default.update());for(let i=0;i<t.length;i++){const n=t[i];if(e.mainCamera&&n instanceof le.__webpack_exports__default.MeshUIBaseElement){if(Ao(n))continue;const o=e.isInVR,r=!1,a=!o;Ch(n,e.mainCamera,r,a),n[xS]===!0&&ri.applyLabelOnTop(n)}}}static applyLabelOnTop(e){e.traverse(t=>{const i=t.material;if(i){t.renderOrder=999999;for(const n of Array.isArray(i)?i:[i])n.depthTest=!1,n.depthWrite=!1}})}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(),Ao(r)!=!0&&r[Lg].push(r))}}}const Yt=x("debugphysics"),pE=x("debugworker"),Gv=new c.Layers;class zr{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){Gv.set(e),this.layerMask=Gv}setMask(e){this.layerMask||(this.layerMask=new c.Layers);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}class o_{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}}let Bg=null;function SS(s){Bg=s}class pl{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;get engine(){return this._engine}set engine(e){this._engine=e}getOrCreatePhysicsEngine(){return this._engine===void 0&&Bg&&(this._engine=Bg(this.context)),this._engine??null}constructor(e){this.context=e}raycaster=new c.Raycaster;defaultRaycastOptions=new zr;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){Yt&&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 Yt&&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)),Yt&&console.time("raycast"),o.length=0,pl._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))),pl._raycasting--,Yt&&(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,h=!l&&o.raycast!==c.Object3D.prototype.raycast;if(o.raycastAllowed===!1&&(r=!1),r&&n.testObject){const d=n.testObject?.(o);if(d===!1)continue;d==="continue in children"&&(r=!1)}else r&&(!l&&!h||l&&!Hv(l))&&(r=!1);if(r){const d=i.length;if(h)e.intersectObject(a,!1,i);else{const u=o.raycastPreference||"lod";let f=u!=="bounds";if(n.precise===!1&&(f=!1),l&&(f||=l.getAttribute("position")?.array?.length<64),a instanceof V.GroundedSkybox&&(f=!1),u==="lod"){const m=re.getRaycastMesh(o);m&&(a.geometry=m)}!f&&gE(a,e,i)||(n.useAcceleratedRaycast!==!1?nf.runMeshBVHRaycast(e,a,i,this.context,n):e.intersectObject(a,!1,i)),a.geometry=l}if(Yt&&i.length!=d){const u=i[i.length-1];B.DrawWireSphere(u.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 V.GroundedSkybox);const d=e,u=d.geometry;if(h&&l){const f=l(e);if(f===!1)return;f==="continue in children"&&(h=!1)}if(u&&Hv(u)||(h=!1),h){if(a){const f=this.sphere;f.center.copy(t),f.radius=i;const m=o.length;if(nf.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 f=this.tempBoundingBox.copy(u.boundingBox).applyMatrix4(d.matrixWorld),m=this.sphere;if(m.center.copy(t),m.radius=i,m.intersectsBox(f)){const g=ie(e),v=g.distanceTo(m.center),_=new o_(e,v,g);if(o.push(_),!r)return}}}if(e.children)for(const f of e.children){const m=o.length;if(this.intersectSphere(f,t,i,n,o,r,a,l),m!=o.length&&!r)return}}}function Hv(s){return!(s.index&&s.index.array.length<3)}const Jo=new c.Sphere,Td=new c.Plane,mE=new c.Matrix3;function gE(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 V.GroundedSkybox){Td.setFromNormalAndCoplanarPoint(F(0,1,0),F(0,-l.position.y,0)),Td.applyMatrix4(l.matrixWorld,mE);const u=o.ray.intersectPlane(Td,F());if(u){Jo.copy(h),Jo.applyMatrix4(l.matrixWorld);const m=F(u).sub(o.ray.origin).length(),g=Jo.radius*.5;m<g&&r.push({distance:m,point:u,object:l,normal:Td.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),f=u.length();if(f>Jo.radius){const m=u.clone().normalize();r.push({distance:f,point:d,object:l,normal:m})}}}}),s._computeIntersections=n,e.intersectObject(s,!1,t),s._computeIntersections=i,!0}function Fg(s,e){const t=s.children;s.children=[];try{return e()}finally{s.children=t}}var nf;(s=>{let e=0;function t(b,w,C,k,O){if(!w.geometry||!w.geometry.hasAttribute("position"))return!1;const D=w.geometry;if(w?.isSkinnedMesh){const I=w,j=I.bvhNeedsUpdate;if(!I.staticGenerator)l(),r&&(Fg(w,()=>{I.staticGenerator=new r(w),I.staticGenerator.applyWorldTransforms=!1,I.staticGeometry=I.staticGenerator.generate()}),D.boundsTree=a?.call(I.staticGeometry),I.staticGeometryLastUpdate=performance.now()+Math.random()*200,I.bvhNeedsUpdate=!0);else if(D.boundsTree&&(I.autoUpdateMeshBvhInterval!==void 0&&I.autoUpdateMeshBvhInterval>=0||j===!0)){const $=performance.now(),W=$-I.staticGeometryLastUpdate,R=I.autoUpdateMeshBvhInterval??100;(j||W>R)&&(Yt&&console.warn(`Physics: updating skinned mesh bvh for ${w.name} after ${W.toFixed(2)}ms`),I.bvhNeedsUpdate=!1,I.staticGeometryLastUpdate=$,Fg(w,()=>I.staticGenerator?.generate(I.staticGeometry)),D.boundsTree.refit())}}else if(!D.boundsTree){d||y();let I=!0;if((k.xr||D[g]===!1||D.getAttribute("position")?.isInterleavedBufferAttribute||D.index&&D.index?.isInterleavedBufferAttribute||e>10)&&(I=!1),I&&f){if(D[m]===void 0){let j=null;if(_.length>0){const $=_.shift();$&&!$.running&&(j=$)}if(!j&&v.length<3)try{pE&&console.warn("[GenerateMeshBVHWorker] Creating worker with import.meta.url:",typeof document>"u"?require("url").pathToFileURL(__filename).href:Ha&&Ha.tagName.toUpperCase()==="SCRIPT"&&Ha.src||new URL("needle-engine.bundle-D3nBMgfk.umd.cjs",document.baseURI).href),j=new f,v.push(j)}catch($){$ instanceof DOMException&&$.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($),e+=10):(console.error("Failed to create MeshBVH worker. Please see below for more details:"),console.log($)),e++}if(j!=null&&!j.running){const $=w.name;Yt&&console.log("<<<< worker start",$,j),D[m]="queued",performance.mark("bvh.create.start");const W=D.clone();try{j.generate(W).then(R=>{D[m]="done",D.boundsTree=R}).catch(R=>{D[m]="failed - "+R?.message,D[g]=!1,Yt&&console.error("Failed to generate mesh bvh on worker",R)}).finally(()=>{Yt&&console.log(">>>>> worker done",$,{hasBoundsTre:D.boundsTree!=null}),_.push(j),W.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch(R){console.error("Failed to generate mesh bvh on worker",R)}}else Yt&&console.warn("No worker available")}}else(!u||!I)&&(l(),o&&(performance.mark("bvh.create.start"),D.boundsTree=new o(D),performance.mark("bvh.create.end"),performance.measure("bvh.create","bvh.create.start","bvh.create.end")))}if(b instanceof c.Raycaster){const I=b,j=w.raycast;if(D.boundsTree)l(),n&&(w.acceleratedRaycast||(w.acceleratedRaycast=n.bind(w),Yt&&console.debug(`Physics: bind acceleratedRaycast fn to "${w.name}"`)),w.raycast=w.acceleratedRaycast);else if(Yt&&console.warn("No bounds tree found for mesh",w.name,{workerTask:D[m],hasAcceleratedRaycast:n!=null}),O.allowSlowRaycastFallback===!1&&(D.getAttribute("position")?.array?.length??0)>2e3)return Yt&&console.warn("Skipping raycast because no bounds tree is available and allowSlowRaycastFallback is false"),!1;const $=I.firstHitOnly;return I.firstHitOnly=!1,I.intersectObject(w,!1,C),I.firstHitOnly=$,w.raycast=j,!0}else if(b instanceof c.Sphere){const I=D.boundsTree;if(I){const j=b;if(h.copy(w.matrixWorld).invert(),j.applyMatrix4(h),I.intersectsSphere(j)){const W=ie(w),R=W.distanceTo(j.center),U=new o_(w,R,W);C.push(U)}}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-BJviq-Oq.umd.cjs")).then(b=>b.index$1).then(b=>{n=b.acceleratedRaycast,o=b.MeshBVH,r=b.StaticGeometryGenerator,a=b.computeBoundsTree}).catch(b=>{(Yt||E())&&console.error("Failed to load BVH library...",b.message)}))}const h=new c.Matrix4;let d=!1,u=!1,f=null;const m=Symbol("Needle:MeshBVH-Worker"),g=Symbol("Needle:MeshBVH-CanUseWorker"),v=[],_=[];function y(){d=!0,u=!0,Promise.resolve().then(()=>z3).then(b=>{f=b.GenerateMeshBVHWorker}).catch(b=>{Yt||E()?console.warn("Failed to setup mesh bvh worker"):console.debug("Failed to setup mesh bvh worker",b)}).finally(()=>{u=!1})}})(nf||(nf={}));const qv=Symbol("gltf-loader-internal-usage-tracker"),yE=x("debugusers");class Za{get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(e){return Za._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(){Za._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[qv]=e._loadingId),r)),o},null}afterRoot(e){Za._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[qv],t instanceof c.Object3D&&(t.parent||t instanceof c.Mesh&&setTimeout(()=>{yE&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}}class CS{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:
|
|
882
|
+
Target Framerate: `+this.targetFrameRate)}}this._dispatchReadyAfterFrame&&(this._dispatchReadyAfterFrame=!1,this.domElement.dispatchEvent(new CustomEvent("ready")),se.dispatchCallback(ae.ContextFirstFrameRendered,this))}_tempClearColor=new c.Color;_tempClearColor2=new c.Color;renderNow(e){if(!e&&(e=this.mainCamera,!e))return!1;if(this.handleRendererContextLost(),this._isRendering=!0,this.renderRequiredTextures(),this.renderer.toneMapping!==c.NoToneMapping&&nS(),this.postprocessing.update(),this.composer&&!this.isInXR){e&&"setMainCamera"in this.composer&&this.composer.passes[0]?.mainCamera!=e&&this.composer.setMainCamera(e);const t=this.renderer.getClearColor(this._tempClearColor),i=this.renderer.getClearAlpha();this._tempClearColor2.copy(t),this.renderer.setClearColor(t.convertSRGBToLinear(),this.renderer.getClearAlpha()),this.composer.render(this.time.deltaTime),this.renderer.setClearColor(this._tempClearColor2,i)}else e&&(this.isInXR&&exports.DeviceUtilities.isMacOS()&&this.renderer.clearDepth(),this.renderer.render(this.scene,e));return this._isRendering=!1,!0}_contextRestoreTries=0;handleRendererContextLost(){this.time.frame%10&&this.renderer.getContext().isContextLost()&&this._contextRestoreTries++<100&&(console.warn("Attempting to recover WebGL context..."),this.renderer.forceContextRestore())}_wasPaused=!1;onHandlePaused(){const e=this.evaluatePaused();if(this._wasPaused!==e){aE&&console.log("Paused?",e,"context:"+this.alias);for(let t=0;t<this.scripts_pausedChanged.length;t++){const i=this.scripts_pausedChanged[t];i.activeAndEnabled&&i.onPausedChanged!==void 0&&(_e.Current=this,i.onPausedChanged(e,this._wasPaused))}}return this._wasPaused=e,e}evaluatePaused(){return this.isInXR?!1:this.isPaused?!0:this.runInBackground?!1:!this.isVisibleToUser}renderRequiredTextures(){if(!this.mainCamera||!this._requireDepthTexture&&!this._requireColorTexture)return;if(!this._renderTarget){if(this._renderTarget=new c.WebGLRenderTarget(this.domWidth,this.domHeight),this._requireDepthTexture){const i=new c.DepthTexture(this.domWidth,this.domHeight);this._renderTarget.depthTexture=i}this._requireColorTexture&&(this._renderTarget.texture=new c.Texture,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=c.NearestFilter,this._renderTarget.texture.magFilter=c.NearestFilter,this._renderTarget.texture.format=c.RGBAFormat)}const e=this._renderTarget;e.texture&&(e.texture.colorSpace=this.renderer.outputColorSpace);const t=this.renderer.getRenderTarget();this.renderer.setRenderTarget(e),this.renderer.render(this.scene,this.mainCamera),this.renderer.setRenderTarget(t)}executeCoroutines(e){if(this.coroutines[e]){const i=this.coroutines[e];for(let n=0;n<i.length;n++)try{const o=i[n];if(!o.comp||o.comp.destroyed||!o.main||o.comp.enabled===!1){cE&&console.log("Removing coroutine",o.comp,o.comp.enabled),i.splice(n,1),--n;continue}const a=o.chained;if(a&&a.length>0){const u=a[a.length-1].next();if(u.done&&a.pop(),t(u)&&(o.chained||(o.chained=[]),o.chained.push(u.value)),!u.done)continue}const l=o.main.next();if(l.done===!0){i.splice(n,1),--n;continue}const h=l.value;if(t(h)){if(h.next().done)continue;o.chained||(o.chained=[]),o.chained.push(h)}else if(h instanceof Promise){const d=h;o.chained||(o.chained=[]);const u=zx(d);o.chained?.push(u);continue}}catch(o){console.error(o)}}function t(i){return!!(i&&i.next&&i.return)}}};ye([ge()],me.prototype,"scripts");ye([ge()],me.prototype,"scripts_pausedChanged");ye([ge()],me.prototype,"scripts_earlyUpdate");ye([ge()],me.prototype,"scripts_update");ye([ge()],me.prototype,"scripts_lateUpdate");ye([ge()],me.prototype,"scripts_onBeforeRender");ye([ge()],me.prototype,"scripts_onAfterRender");ye([ge()],me.prototype,"scripts_WithCorroutines");ye([ge()],me.prototype,"scripts_immersive_vr");ye([ge()],me.prototype,"scripts_immersive_ar");ye([ge()],me.prototype,"coroutines");ye([ge("keep")],me.prototype,"post_setup_callbacks");ye([ge("keep")],me.prototype,"pre_update_callbacks");ye([ge("keep")],me.prototype,"pre_render_callbacks");ye([ge("keep")],me.prototype,"post_render_callbacks");ye([ge()],me.prototype,"pre_update_oneshot_callbacks");ye([ge()],me.prototype,"new_scripts");ye([ge()],me.prototype,"new_script_start");ye([ge()],me.prototype,"new_scripts_pre_setup_callbacks");ye([ge()],me.prototype,"new_scripts_post_setup_callbacks");ye([ge()],me.prototype,"new_scripts_xr");ye([ge("undefined")],me.prototype,"mainCameraComponent");ye([ge("null")],me.prototype,"_mainCamera");ye([ge("null")],me.prototype,"_fallbackCamera");ye([ge("custom")],me.prototype,"_events");ye([ge("custom")],me.prototype,"lights");ye([ge("keep")],me.prototype,"_disposeCallbacks");ye([ge()],me.prototype,"_cameraStack");ye([ge("custom")],me.prototype,"_onBeforeRenderListeners");ye([ge("custom")],me.prototype,"_onAfterRenderListeners");ye([ge("keep")],me.prototype,"rootSceneSourceIdentifiers");let X=me;const um=x("debugwebxr");class wS{static tryFindAvatarObjects(e,t,i){if(i.head&&i.leftHand&&i.rightHand)return;const n=e.name.toLocaleLowerCase();!i.head&&n.includes("head")&&(um&&console.log("FOUND AVATAR HEAD",e.name),i.head=new J("",t,e)),n.includes("hand")&&(!i.leftHand&&n.includes("left")&&(um&&console.log("FOUND AVATAR LEFT HAND",e.name),i.leftHand=new J("",t,e)),!i.rightHand&&n.includes("right")&&(um&&console.log("FOUND AVATAR RIGHT HAND",e.name),i.rightHand=new J("",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 oe 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.setRGB(Number.isFinite(e)?e:0,Number.isFinite(t)?t:0,Number.isFinite(i)?i:0),this.alpha=typeof n=="number"&&Number.isFinite(n)?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=L.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=L.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 oe(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 oe(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 oe(i/255,n/255,o/255,1)}else if(e.startsWith("rgba")){const t=e.slice(5,-1).split(",").map(Number);return new oe(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 oe(t[0]/255,t[1]/255,t[2]/255,1)}}else if(Array.isArray(e)){if(e.length===4)return new oe(e[0],e[1],e[2],e[3]);if(e.length===3)return new oe(e[0],e[1],e[2],1);console.error("Invalid color array length. Expected 3 or 4, got "+e.length)}return new oe(e)}}const Bt=new c.Vector3,Vv=new c.Vector3,Wv=new c.Quaternion,uE=x("debuggizmos"),un=8947848,fm=32;class B{constructor(){}static enabled=!0;static isGizmo(e){return e[Lg]!==void 0}static setVisible(e){for(const t of ri.timedObjectsBuffer)t.visible=e}static DrawLabel(e,t,i=.05,n=0,o,r,a,l=!0){if(!B.enabled)return null;o||(o=un);const h=N.active?.rigScale??1,d=ri.getTextLabel(n,t,i*h,o,r);return d[xS]=l===!1,a instanceof c.Object3D&&a.add(d),d.position.x=e.x,d.position.y=e.y,d.position.z=e.z,d}static DrawRay(e,t,i=un,n=0,o=!0){if(!B.enabled)return;const r=ri.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),Bt.set(t.x,t.y,t.z).multiplyScalar(999999999),a.setXYZ(1,e.x+Bt.x,e.y+Bt.y,e.z+Bt.z),a.needsUpdate=!0,r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1,mn(r.material,i)}static DrawDirection(e,t,i=un,n=0,o=!0,r=1){if(!B.enabled)return;const a=ri.getLine(n),l=a.geometry.getAttribute("position");l.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(Bt.set(0,0,-r),Wv.set(t.x,t.y,t.z,t.w),Bt.applyQuaternion(Wv)):(Bt.set(t.x,t.y,t.z),Bt.multiplyScalar(r)),l.setXYZ(1,e.x+Bt.x,e.y+Bt.y,e.z+Bt.z),l.needsUpdate=!0,a.material.depthTest=o,a.material.depthWrite=!1,mn(a.material,i)}static DrawLine(e,t,i=un,n=0,o=!0){if(!B.enabled)return;const r=ri.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,mn(r.material,i)}static DrawCircle(e,t,i,n=un,o=0,r=!0){if(!B.enabled)return;const a=ri.getCircle(o);a.position.set(e.x,e.y,e.z),a.scale.set(i,i,i),a.quaternion.setFromUnitVectors(this._up,Bt.set(t.x,t.y,t.z).normalize()),a.material.depthTest=r,a.material.depthWrite=!1,a.material.fog=!1,mn(a.material,n)}static DrawWireSphere(e,t,i=un,n=0,o=!0){if(!B.enabled)return;const r=ri.getSphere(t,n,!0);Ar(r,e.x,e.y,e.z),r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1,mn(r.material,i)}static DrawSphere(e,t,i=un,n=0,o=!0){if(!B.enabled)return;const r=ri.getSphere(t,n,!1);Ar(r,e.x,e.y,e.z),r.material.depthTest=o,r.material.depthWrite=!1,mn(r.material,i)}static DrawWireBox(e,t,i=un,n=0,o=!0,r=void 0){if(!B.enabled)return;const a=ri.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,mn(a.material,i)}static DrawWireBox3(e,t=un,i=0,n=!0){if(!B.enabled)return;const o=ri.getBox(i);o.position.copy(e.getCenter(Bt)),o.scale.copy(e.getSize(Bt)),o.material.depthTest=n,o.material.wireframe=!0,o.material.depthWrite=!1,o.material.fog=!1,mn(o.material,t)}static _up=new c.Vector3(0,1,0);static DrawArrow(e,t,i=un,n=0,o=!0,r=!1){if(!B.enabled)return;const a=ri.getArrowHead(n);a.position.set(t.x,t.y,t.z),a.quaternion.setFromUnitVectors(this._up.set(0,1,0),Bt.set(t.x,t.y,t.z).sub(Vv.set(e.x,e.y,e.z)).normalize());const h=Bt.set(t.x,t.y,t.z).sub(Vv.set(e.x,e.y,e.z)).length()*.1;a.scale.set(h,h,h),a.material.depthTest=o,a.material.wireframe=r,mn(a.material,i),this.DrawLine(e,t,i,n,o)}static DrawWireMesh(e){const t=ri.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,mn(t.material,e.color??un)}}const fE=new c.BoxGeometry(1,1,1);function s_(s=null){const e=new c.Color(s??14540253),t=new c.EdgesGeometry(fE);return new c.LineSegments(t,new c.LineBasicMaterial({color:e}))}function mn(s,e){if(Array.isArray(s)){for(const i of s)mn(i,e);return}const t=e instanceof oe?e.a:1;s.color.set(e),s.opacity=t,s.transparent=t<1}const Lg=Symbol("GizmoCache"),xS=Symbol("GizmoLabelOnTop");class ri{static familyName="needle-gizmos";static ensureFont(){let e=le.__webpack_exports__default.FontLibrary.getFontFamily(this.familyName);e||(e=le.__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",()=>{le.__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),uE&&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 le.__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(X.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(X.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(X.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(fm*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/(fm-1);for(let h=0;h<fm+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(X.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(X.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(X.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(X.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[Lg]=n,t.castShadow=!1,t.receiveShadow=!1,t.isGizmo=!0,this.timedObjectsBuffer.push(t),this.timesBuffer.push(X.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,le.__webpack_exports__default.update());for(let i=0;i<t.length;i++){const n=t[i];if(e.mainCamera&&n instanceof le.__webpack_exports__default.MeshUIBaseElement){if(Ao(n))continue;const o=e.isInVR,r=!1,a=!o;Ch(n,e.mainCamera,r,a),n[xS]===!0&&ri.applyLabelOnTop(n)}}}static applyLabelOnTop(e){e.traverse(t=>{const i=t.material;if(i){t.renderOrder=999999;for(const n of Array.isArray(i)?i:[i])n.depthTest=!1,n.depthWrite=!1}})}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(),Ao(r)!=!0&&r[Lg].push(r))}}}const Yt=x("debugphysics"),pE=x("debugworker"),Gv=new c.Layers;class zr{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){Gv.set(e),this.layerMask=Gv}setMask(e){this.layerMask||(this.layerMask=new c.Layers);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}class o_{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}}let Bg=null;function SS(s){Bg=s}class pl{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;get engine(){return this._engine}set engine(e){this._engine=e}getOrCreatePhysicsEngine(){return this._engine===void 0&&Bg&&(this._engine=Bg(this.context)),this._engine??null}constructor(e){this.context=e}raycaster=new c.Raycaster;defaultRaycastOptions=new zr;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){Yt&&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 Yt&&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)),Yt&&console.time("raycast"),o.length=0,pl._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))),pl._raycasting--,Yt&&(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,h=!l&&o.raycast!==c.Object3D.prototype.raycast;if(o.raycastAllowed===!1&&(r=!1),r&&n.testObject){const d=n.testObject?.(o);if(d===!1)continue;d==="continue in children"&&(r=!1)}else r&&(!l&&!h||l&&!Hv(l))&&(r=!1);if(r){const d=i.length;if(h)e.intersectObject(a,!1,i);else{const u=o.raycastPreference||"lod";let f=u!=="bounds";if(n.precise===!1&&(f=!1),l&&(f||=l.getAttribute("position")?.array?.length<64),a instanceof V.GroundedSkybox&&(f=!1),u==="lod"){const m=re.getRaycastMesh(o);m&&(a.geometry=m)}!f&&gE(a,e,i)||(n.useAcceleratedRaycast!==!1?nf.runMeshBVHRaycast(e,a,i,this.context,n):e.intersectObject(a,!1,i)),a.geometry=l}if(Yt&&i.length!=d){const u=i[i.length-1];B.DrawWireSphere(u.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 V.GroundedSkybox);const d=e,u=d.geometry;if(h&&l){const f=l(e);if(f===!1)return;f==="continue in children"&&(h=!1)}if(u&&Hv(u)||(h=!1),h){if(a){const f=this.sphere;f.center.copy(t),f.radius=i;const m=o.length;if(nf.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 f=this.tempBoundingBox.copy(u.boundingBox).applyMatrix4(d.matrixWorld),m=this.sphere;if(m.center.copy(t),m.radius=i,m.intersectsBox(f)){const g=ie(e),v=g.distanceTo(m.center),_=new o_(e,v,g);if(o.push(_),!r)return}}}if(e.children)for(const f of e.children){const m=o.length;if(this.intersectSphere(f,t,i,n,o,r,a,l),m!=o.length&&!r)return}}}function Hv(s){return!(s.index&&s.index.array.length<3)}const Jo=new c.Sphere,Td=new c.Plane,mE=new c.Matrix3;function gE(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 V.GroundedSkybox){Td.setFromNormalAndCoplanarPoint(F(0,1,0),F(0,-l.position.y,0)),Td.applyMatrix4(l.matrixWorld,mE);const u=o.ray.intersectPlane(Td,F());if(u){Jo.copy(h),Jo.applyMatrix4(l.matrixWorld);const m=F(u).sub(o.ray.origin).length(),g=Jo.radius*.5;m<g&&r.push({distance:m,point:u,object:l,normal:Td.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),f=u.length();if(f>Jo.radius){const m=u.clone().normalize();r.push({distance:f,point:d,object:l,normal:m})}}}}),s._computeIntersections=n,e.intersectObject(s,!1,t),s._computeIntersections=i,!0}function Fg(s,e){const t=s.children;s.children=[];try{return e()}finally{s.children=t}}var nf;(s=>{let e=0;function t(b,w,C,k,O){if(!w.geometry||!w.geometry.hasAttribute("position"))return!1;const D=w.geometry;if(w?.isSkinnedMesh){const I=w,j=I.bvhNeedsUpdate;if(!I.staticGenerator)l(),r&&(Fg(w,()=>{I.staticGenerator=new r(w),I.staticGenerator.applyWorldTransforms=!1,I.staticGeometry=I.staticGenerator.generate()}),D.boundsTree=a?.call(I.staticGeometry),I.staticGeometryLastUpdate=performance.now()+Math.random()*200,I.bvhNeedsUpdate=!0);else if(D.boundsTree&&(I.autoUpdateMeshBvhInterval!==void 0&&I.autoUpdateMeshBvhInterval>=0||j===!0)){const $=performance.now(),W=$-I.staticGeometryLastUpdate,R=I.autoUpdateMeshBvhInterval??100;(j||W>R)&&(Yt&&console.warn(`Physics: updating skinned mesh bvh for ${w.name} after ${W.toFixed(2)}ms`),I.bvhNeedsUpdate=!1,I.staticGeometryLastUpdate=$,Fg(w,()=>I.staticGenerator?.generate(I.staticGeometry)),D.boundsTree.refit())}}else if(!D.boundsTree){d||y();let I=!0;if((k.xr||D[g]===!1||D.getAttribute("position")?.isInterleavedBufferAttribute||D.index&&D.index?.isInterleavedBufferAttribute||e>10)&&(I=!1),I&&f){if(D[m]===void 0){let j=null;if(_.length>0){const $=_.shift();$&&!$.running&&(j=$)}if(!j&&v.length<3)try{pE&&console.warn("[GenerateMeshBVHWorker] Creating worker with import.meta.url:",typeof document>"u"?require("url").pathToFileURL(__filename).href:Ha&&Ha.tagName.toUpperCase()==="SCRIPT"&&Ha.src||new URL("needle-engine.bundle-DOHf03pR.umd.cjs",document.baseURI).href),j=new f,v.push(j)}catch($){$ instanceof DOMException&&$.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($),e+=10):(console.error("Failed to create MeshBVH worker. Please see below for more details:"),console.log($)),e++}if(j!=null&&!j.running){const $=w.name;Yt&&console.log("<<<< worker start",$,j),D[m]="queued",performance.mark("bvh.create.start");const W=D.clone();try{j.generate(W).then(R=>{D[m]="done",D.boundsTree=R}).catch(R=>{D[m]="failed - "+R?.message,D[g]=!1,Yt&&console.error("Failed to generate mesh bvh on worker",R)}).finally(()=>{Yt&&console.log(">>>>> worker done",$,{hasBoundsTre:D.boundsTree!=null}),_.push(j),W.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch(R){console.error("Failed to generate mesh bvh on worker",R)}}else Yt&&console.warn("No worker available")}}else(!u||!I)&&(l(),o&&(performance.mark("bvh.create.start"),D.boundsTree=new o(D),performance.mark("bvh.create.end"),performance.measure("bvh.create","bvh.create.start","bvh.create.end")))}if(b instanceof c.Raycaster){const I=b,j=w.raycast;if(D.boundsTree)l(),n&&(w.acceleratedRaycast||(w.acceleratedRaycast=n.bind(w),Yt&&console.debug(`Physics: bind acceleratedRaycast fn to "${w.name}"`)),w.raycast=w.acceleratedRaycast);else if(Yt&&console.warn("No bounds tree found for mesh",w.name,{workerTask:D[m],hasAcceleratedRaycast:n!=null}),O.allowSlowRaycastFallback===!1&&(D.getAttribute("position")?.array?.length??0)>2e3)return Yt&&console.warn("Skipping raycast because no bounds tree is available and allowSlowRaycastFallback is false"),!1;const $=I.firstHitOnly;return I.firstHitOnly=!1,I.intersectObject(w,!1,C),I.firstHitOnly=$,w.raycast=j,!0}else if(b instanceof c.Sphere){const I=D.boundsTree;if(I){const j=b;if(h.copy(w.matrixWorld).invert(),j.applyMatrix4(h),I.intersectsSphere(j)){const W=ie(w),R=W.distanceTo(j.center),U=new o_(w,R,W);C.push(U)}}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-CDN1hirK.umd.cjs")).then(b=>b.index$1).then(b=>{n=b.acceleratedRaycast,o=b.MeshBVH,r=b.StaticGeometryGenerator,a=b.computeBoundsTree}).catch(b=>{(Yt||E())&&console.error("Failed to load BVH library...",b.message)}))}const h=new c.Matrix4;let d=!1,u=!1,f=null;const m=Symbol("Needle:MeshBVH-Worker"),g=Symbol("Needle:MeshBVH-CanUseWorker"),v=[],_=[];function y(){d=!0,u=!0,Promise.resolve().then(()=>z3).then(b=>{f=b.GenerateMeshBVHWorker}).catch(b=>{Yt||E()?console.warn("Failed to setup mesh bvh worker"):console.debug("Failed to setup mesh bvh worker",b)}).finally(()=>{u=!1})}})(nf||(nf={}));const qv=Symbol("gltf-loader-internal-usage-tracker"),yE=x("debugusers");class Za{get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(e){return Za._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(){Za._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[qv]=e._loadingId),r)),o},null}afterRoot(e){Za._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[qv],t instanceof c.Object3D&&(t.parent||t instanceof c.Mesh&&setTimeout(()=>{yE&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}}class CS{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:
|
|
883
883
|
`+i.src),e.preventDefault())}})}}const Nf=x("trackresources");function PS(){return Nf==="dispose"}let Nr=!0;Nf===0&&(Nr=!1);function _E(s){Nr=s}function kS(){return Nr}const MS=Symbol("disposable");function OS(s,e){s&&(s[MS]=e,Cr&&console.warn("Set disposable",e,s))}const ES=Symbol("disposed");function bE(s){return s[ES]===!0}function Oe(s){if(s){if(s[MS]===!1){Cr&&console.warn("Object is marked as not disposable",s);return}if(typeof s=="object"&&(s[ES]=!0),s instanceof c.Scene)Oe(s.environment),Oe(s.background),Oe(s.customDepthMaterial),Oe(s.customDistanceMaterial);else if(s instanceof c.SkinnedMesh)Oe(s.geometry),Oe(s.material),Oe(s.skeleton),Oe(s.bindMatrix),Oe(s.bindMatrixInverse),Oe(s.customDepthMaterial),Oe(s.customDistanceMaterial),s.visible=!1;else if(s instanceof c.Mesh)Oe(s.geometry),Oe(s.material),Oe(s.customDepthMaterial),Oe(s.customDistanceMaterial),s.visible=!1;else if(s instanceof c.Object3D)s.visible=!1;else if(s instanceof c.BufferGeometry){ya(s);for(const e of Object.keys(s.attributes)){const t=s.attributes[e];Oe(t)}}else if(s instanceof c.BufferAttribute||s instanceof c.InterleavedBufferAttribute)Cr&&console.warn("BufferAttribute dispose not supported",s.count);else if(s instanceof Array)for(const e of s)e instanceof c.Material&&Oe(e);else if(s instanceof c.Material){ya(s);for(const t of Object.keys(s)){const i=s[t];i instanceof c.Texture&&Oe(i)}const e=s.uniforms;if(e)for(const t of Object.keys(e)){const i=e[t];i instanceof c.Texture?Oe(i):i instanceof c.Uniform&&Oe(i.value)}}else s instanceof c.Texture?(ya(s),ya(s.source),s.source?.data instanceof ImageBitmap&&ya(s.source.data)):s instanceof c.Skeleton?(ya(s.boneTexture),s.boneTexture=null):s instanceof c.Bone||!(s instanceof c.Object3D)&&Cr&&console.warn("Unknown object type",s)}}function ya(s){s&&((Cr||PS()||Nf)&&console.warn("🧨 FREE",s),s instanceof ImageBitmap||"dispose"in s&&typeof s.dispose=="function"&&s.dispose())}function vE(s){}const wE=new Set;function r_(s,e,t=null,i){if(i||(i=wE,i.clear()),!s)return i;const n=s[oh];if(n)for(const o of n)i.has(o)||t?.call(null,o)!==!1&&(i.add(o),e&&r_(o,!0,t,i));return i}function xE(s){return s[Sc]}const Cr=x("debugresourceusers")||x("debugmemory"),oh=Symbol("needle-resource-users"),Sc=Symbol("needle-resource-users-count");function Gt(s,e){Tf(s,e,function(t,i){Nr&&!pl.raycasting&&(sf(oh,this,t,!1),sf(oh,this,i,!0))})}Nr&&(Gt(c.Mesh.prototype,"material"),Gt(c.Mesh.prototype,"geometry"),Gt(c.Material.prototype,"map"),Gt(c.Material.prototype,"bumpMap"),Gt(c.Material.prototype,"alphaMap"),Gt(c.Material.prototype,"normalMap"),Gt(c.Material.prototype,"displacementMap"),Gt(c.Material.prototype,"roughnessMap"),Gt(c.Material.prototype,"metalnessMap"),Gt(c.Material.prototype,"emissiveMap"),Gt(c.Material.prototype,"specularMap"),Gt(c.Material.prototype,"envMap"),Gt(c.Material.prototype,"lightMap"),Gt(c.Material.prototype,"aoMap"),Gt(c.Material.prototype,"gradientMap"));function SE(s){if(Nr===!1)return;const e=s[oh];if(e)for(const t of e)sf(oh,t,s,!1)}Nr&&Tf(c.Material.prototype,"dispose",function(){SE(this)});let jg=0;function sf(s,e,t,i){if(jg>0)return;if(Array.isArray(t)){for(const o of t)sf(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[Sc]||0;o+=1,t[Sc]=o,Cr&&console.warn(`🟢 Added user of "${t.type}"`,e,t,o,"users:",n)}}else if(e&&n.has(e)){n.delete(e);let o=t[Sc]||0;o>0&&(o-=1,t[Sc]=o),Cr&&console.warn(`🔴 Removed user of "${t.type}"`,e,t,o,"users:",n),o<=0&&(Za.isLoading(t)||(Nf&&console.warn(`🔴 Removed all user of "${t.type}"`,t),PS()&&Oe(t)))}t[s]=n}try{Tf(c.WebGLRenderer.prototype,"render",function(){jg++},function(){jg--})}catch(s){console.warn("Could not wrap WebGLRenderer.render",s)}const rh=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),RS=Symbol("isUsingInstancing"),TS=Symbol("instancingRenderer"),Cc=Symbol("instancingAutoUpdateBounds");class Ki{static isUsingInstancing(e){return e[RS]===!0}static getRenderer(e){return e[TS]||null}setAutoUpdateBounds(e,t){const i=Ki.getRenderer(e);i&&(i[Cc]=t)}static markDirty(e,t=!0){if(e&&(this.isUsingInstancing(e)&&(e[rh]=!0,e.matrixWorldNeedsUpdate=!0),t))for(const i of e.children)Ki.markDirty(i,!0)}}const ko=x("debuginstantiate"),_a=new Map,ah=Symbol("original-component-name");function Ug(s,e,t){if(e===null||!s)return;const i=s.guid,n=s.guid;n?.length&&(_a.has(n)||(ko&&console.log('Creating InstanceIdProvider with key "'+n+'" for object '+s.name),_a.set(n,new ot(n))));const o=n&&_a.get(n)||e;if(s.guid=o.generateUUID(),i&&i!=="invalid"&&(t[i]=s.guid),s&&s.userData&&s.userData.components)for(const r of s.userData.components){if(r===null)continue;const a=r.guid;a?_a.has(a)||(ko&&console.log('Creating InstanceIdProvider with key "'+a+'" for component '+r[ah]),_a.set(a,new ot(a))):ko&&console.warn("Can not create IdProvider: component "+r[ah]+" has no guid",r.guid);const l=_a.get(a)||e,h=r.guid;r.guid=l.generateUUID(),h&&h!=="invalid"&&(t[h]=r.guid)}if(s.children)for(const r of s.children)Ug(r,e,t)}function CE(s){for(const e in s){const i=s[e].clone;if(!(!i?.isObject3D||!i?.userData?.components))for(let n=0;n<i.userData.components.length;n++){const o=i.userData.components[n],r=Object.entries(o);for(const[a,l]of r){if(l==null||a==="guid"||a===Rs||typeof l!="object"&&typeof l!="string")continue;const h=Dr(a,l,s);h!==void 0&&(o[a]=h)}}}}let wi=null;function Xv(s,e){if(!ko){zg(s,e);return}wi={objects:0,components:0,props:0,remapped:0};const t=typeof performance<"u"?performance.now():Date.now();zg(s,e);const i=(typeof performance<"u"?performance.now():Date.now())-t,n=wi;wi=null,console.log(`[resolveStringGuids] root="${s.name}" objects=${n.objects} components=${n.components} propsVisited=${n.props} remapped=${n.remapped} mapSize=${Object.keys(e).length} in ${i.toFixed(2)}ms`)}function zg(s,e){if(wi&&wi.objects++,s.userData?.components)for(const t of s.userData.components)t!==null&&(wi&&wi.components++,Ng(t,e));if(s.children)for(const t of s.children)zg(t,e)}function Ng(s,e,t){if(t||(t=new WeakSet),!t.has(s)){t.add(s);for(const i of Object.keys(s)){wi&&wi.props++;const n=s[i];if(n!=null)if(typeof n=="string"){const o=e[n];o&&(s[i]=o,wi&&wi.remapped++)}else if(Array.isArray(n))for(let o=0;o<n.length;o++){const r=n[o];if(typeof r=="string"){const a=e[r];a&&(n[o]=a,wi&&wi.remapped++)}else(Array.isArray(r)||$g(r))&&Ng(r,e,t)}else $g(n)&&Ng(n,e,t)}}}function Dr(s,e,t){if(e!==void 0){if(e===null)return null;if(typeof e=="string"){const i=t[e];return i?i.clone:void 0}if(typeof e=="object"){if(Af(e))return PE(e,t);if(e.isObject3D===!0){if(s==="gameObject")return;const i=e.uuid,n=t[i]?.clone;return n?(ko&&console.log(s,"old",e,"new",n),n):void 0}if(TE(e))return e.clone();if(Array.isArray(e))return kE(s,e,t);if(e instanceof Map)return ME(e,t);if(e instanceof Set)return OE(e,t);if(!(e instanceof WeakMap||e instanceof WeakSet)){if(kM(e)&&e.$serializedTypes)return EE(e,t);if($g(e))return RE(s,e,t)}}}}function PE(s,e){const t=s.gameObject;if(!t)return;const i=t.uuid,n=e[i]?.clone;if(!n){ko&&console.log("Component reference did not change (external)",s);return}const o=t.userData.components.indexOf(s);if(o>=0&&n.isObject3D)return ko&&console.log("Resolved component",i,"at index",o),n.userData.components[o];console.warn("Could not find component at expected index",s)}function kE(s,e,t){const i=[];for(let n=0;n<e.length;n++){const o=e[n];if(o==null){i.push(o);continue}if(typeof o!="object"&&typeof o!="string"){i.push(o);continue}const r=Dr(s,o,t);i.push(r!==void 0?r:o)}return i}function ME(s,e){const t=new Map;let i=!1;for(const[n,o]of s){let r=n,a=o;if(typeof n=="object"&&n!==null){const l=Dr("",n,e);l!==void 0&&(r=l,i=!0)}if(typeof o=="object"&&o!==null){const l=Dr("",o,e);l!==void 0&&(a=l,i=!0)}t.set(r,a)}return t}function OE(s,e){const t=new Set;for(const i of s)if(typeof i=="object"&&i!==null){const n=Dr("",i,e);t.add(n!==void 0?n:i)}else t.add(i);return t}function EE(s,e){const t=Object.assign(Object.create(Object.getPrototypeOf(s)),s);let i=!1;for(const n in t.$serializedTypes){const o=t[n];if(o!=null&&typeof o=="object"){ko&&console.log("Recursively resolve references for",n,o);const r=Dr(n,o,e);r!==void 0&&(t[n]=r,i=!0)}}return i?t:void 0}function RE(s,e,t){let i=!1;const n={...e};for(const o of Object.keys(n)){const r=n[o];if(r==null||typeof r!="object"&&typeof r!="string")continue;const a=Dr(o,r,t);a!==void 0&&(n[o]=a,i=!0)}return i?n:void 0}function $g(s){if(typeof s!="object"||s===null)return!1;const e=Object.getPrototypeOf(s);return e===Object.prototype||e===null}function TE(s){return s.isVector2===!0||s.isVector3===!0||s.isVector4===!0||s.isQuaternion===!0||s.isEuler===!0||s.isColor===!0||s.isMatrix2===!0||s.isMatrix3===!0||s.isMatrix4===!0}const AS=new Map;function DS(s,e){if(!s)return;if(!e){console.warn("No prototype found",s,s.prototype,s.constructor);return}const t=AS.get(e);t&&t.apply(s)}function a_(s){const e=AE(s.prototype);AS.set(s,e)}function AE(s){return new DE(s)}class DE{$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 lh(s){s&&s.isObject3D===!0&&DS(s,c.Object3D)}let Qv=!1;function IE(){if(Qv)return;if(Qv=!0,By.experimentalSmartHierarchyUpdate){const i=c.Object3D.prototype.add;c.Object3D.prototype.add=function(...r){return Ja(),i.apply(this,r)};const n=c.Object3D.prototype.attach;c.Object3D.prototype.attach=function(...r){return Ja(),n.apply(this,r)};const o=c.Object3D.prototype.remove;c.Object3D.prototype.remove=function(...r){return Ja(),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(){fi(this)},c.Object3D.prototype.addComponent=function(i,n){return ss(this,i,n)},c.Object3D.prototype.addNewComponent=function(i,n){return ss(this,i,n)},c.Object3D.prototype.removeComponent=function(i){return Wf(this,i)},c.Object3D.prototype.getOrAddComponent=function(i,n){return Th(this,i,n)},c.Object3D.prototype.getComponent=function(i){return Bs(this,i)},c.Object3D.prototype.getComponents=function(i,n){return Cl(this,i,n)},c.Object3D.prototype.getComponentInChildren=function(i,n=!1){return Ah(this,i,n)},c.Object3D.prototype.getComponentsInChildren=function(i,n){return Pl(this,i,n)},c.Object3D.prototype.getComponentInParent=function(i,n=!1){return ch(this,i,n)},c.Object3D.prototype.getComponentsInParent=function(i,n){return Gf(this,i,n)},Object.getOwnPropertyDescriptor(c.Object3D.prototype,"activeSelf")||Object.defineProperty(c.Object3D.prototype,"activeSelf",{get:function(){return Sl(this)},set:function(i){Pr(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 V.TransformControlsGizmo?ie(this.object):ie(this)},set:function(i){Oi(this,i)}}),Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldQuaternion")||Object.defineProperty(c.Object3D.prototype,"worldQuaternion",{get:function(){return this instanceof V.TransformControlsGizmo?Se(this.object):Se(this)},set:function(i){vn(this,i)}}),Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldRotation")||Object.defineProperty(c.Object3D.prototype,"worldRotation",{get:function(){return Of(this)},set:function(i){Qw(this,i)}}),Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldScale")||Object.defineProperty(c.Object3D.prototype,"worldScale",{get:function(){return Ve(this)},set:function(i){rl(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(Se(this))},set:function(i){const n=ci().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(Se(this))}}),Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldUp")||Object.defineProperty(c.Object3D.prototype,"worldUp",{get:function(){return F().set(0,1,0).applyQuaternion(Se(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}}),a_(c.Object3D)}const Pu=x("debuggetcomponent"),LE=x("debuginstantiate");class hs{idProvider;parent;keepWorldPosition;position;rotation;scale;visible;context;components;clone(){const e=new hs;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 Sl(s){return s.visible}function Pr(s,e){return typeof e=="number"&&(e=e>.5),s.visible=e,s.visible}function IS(s){return s[Zn]||$f(s)}function LS(s,e){s[RS]=e}function $f(s){return Ki.isUsingInstancing(s)}function l_(s,e){return Kc(s,e,!0,!0)}const BS=Symbol("isDestroyed");function Ao(s){return s[BS]}function FS(s,e){s[BS]=e}const Vg=Symbol("isDontDestroy");function Ea(s,e=!0){s[Vg]=e}const ku=[],Mu=[];function fi(s,e=!0,t=!1){ku.length=0,Mu.length=0,Wg(s,e,!0);for(const i of ku)i.gameObject=null,i.context=null;for(const i of Mu)FS(i,!0),t&&Oe(i);Mu.length=0,ku.length=0}function Wg(s,e=!0,t=!0){if(s==null)return;const i=s;if(i.isComponent){if(i[Vg])return;ku.push(i);const r=i.gameObject;i.__internalDisable?.(),i.__internalDestroy?.(),i.gameObject=r;return}if(s[Vg])return;const n=s;Pu&&console.log(n),Mu.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];Wg(l,e,!1),o.length<r&&(r=o.length,a--)}}if(e&&n.children)for(const r of n.children)Wg(r,e,!1);t&&n.removeFromParent()}function xn(s,e,t=!0){return jS(s,e,t)}function*c_(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*c_(o,e,!0,i,n+1)}}function jS(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=jS(r,e,t,n);if(a!==void 0)return a}}}}function Ls(s,e){if("isAssetReference"in s)return s.instantiate(e??void 0);let t=null;e!=null&&(e.x!==void 0?(t=new hs,t.position=e):t=e);let i=X.Current;t?.context&&(i=t.context),Pu&&i.alias&&console.log("context",i.alias),t&&!t.idProvider&&(t.idProvider=new ot(Date.now()));const n=[],o={},r={},a=US(i,s,t,n,o,r);a&&(CE(o),jE(r,o),FE(o)),Pu&&($u(s,!0),$u(a,!0));const l={};for(const h in o){const d=o[h],u=d.original,f=d.clone;u instanceof c.Object3D&&f instanceof c.Object3D&&(l[u.guid||u.uuid]=f.guid||f.uuid)}if(t?.components!==!1){const h=new Set;for(const d in n){const u=n[d],f=u.guid;if(t&&t.idProvider){const m=u[Rs],g=typeof m=="string"&&m.length>0?m:f;if(u.guid=g&&t.idProvider.remapUUID?t.idProvider.remapUUID(g):t.idProvider.generateUUID(),h.has(u.guid))if(console.warn(`[instantiate] duplicate component guid in source content ("${g}") — deriving a disambiguated guid. Fix the source: two components must not share a guid.`),t.idProvider.remapUUID&&g){let v=1;do u.guid=t.idProvider.remapUUID(`${g}:dup:${v++}`);while(h.has(u.guid))}else u.guid=t.idProvider.generateUUID();h.add(u.guid),l[f]=u.guid,g!==f&&(l[g]=u.guid),Pu&&console.log(u.name,u.guid)}zf(u,i),u.__internalNewInstanceCreated&&u.__internalNewInstanceCreated()}for(const d in n){const u=n[d];u.enabled!==!1&&(u.enabled=!0)}of(i)}return a}function US(s,e,t,i,n,o){if(!e||e[xi]||e instanceof c.Audio||e instanceof c.AudioListener||e.hideFlags&as.DontInstantiate)return null;const r=e.userData;e.userData={};const a=e.children;e.children=[];const l=e.clone(!1);lh(l),e.userData=r,e.children=a;const h={original:e,clone:l};if(n[e.uuid]=h,e.guid&&e.guid!==e.uuid&&(n[e.guid]=h),LE&&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){const u=e.userData?.["needle-id"];l.uuid=u&&t.idProvider.remapUUID?t.idProvider.remapUUID(u):t.idProvider.generateUUID();const f=l;f&&(f.guid=l.uuid)}e.animations&&e.animations.length>0&&(l.animations=[...e.animations]);const d=e.parent;if(d&&d.add(l),t?.position)if(Array.isArray(t.position)){const u=new c.Vector3;u.fromArray(t.position),l.worldPosition=u}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=ci().setFromEuler(t.rotation);else if(Array.isArray(t.rotation)){const u=new c.Euler;u.fromArray(t.rotation),l.worldQuaternion=ci().setFromEuler(u)}}else l.quaternion.copy(e.quaternion);if(t?.scale)if(Array.isArray(t.scale)){const u=new c.Vector3;u.fromArray(t.scale),t.scale=u}else l.scale.copy(t.scale);else l.scale.copy(e.scale);if(t?.parent&&t.parent!=="scene"){let u=null;if(typeof t.parent=="string"?u=Kc(t.parent,s.scene,!0):u=t.parent,u){const f=t.keepWorldPosition===!0?u.attach:u.add;f?f.call(u,l):console.error("Invalid parent object",u,"received when instantiating:",e)}else console.warn("could not find parent:",t.parent)}for(const[u,f]of Object.entries(e.userData))u!=="components"&&(l.userData[u]=f);if(e.userData?.components){const u=e.userData.components,f=[];l.userData.components=f;for(let m=0;m<u.length;m++){const g=u[m],v=new g.constructor;BE(g,v),g[Rs]!==void 0&&(v[Rs]=g[Rs]),f.push(v),v.gameObject=l,i.push(v),n[g.guid]={original:g,clone:v},Rf.dispatchComponentLifecycleEvent("component-added",v)}}t&&(t.position=void 0,t.rotation=void 0,t.scale=void 0,t.parent=void 0,t.visible=void 0);for(const u in e.children){const f=e.children[u],m=US(s,f,t,i,n,o);m&&(n[m.uuid]={original:f,clone:m},l.add(m))}return l}function BE(s,e,t){cl(e,s,void 0,{})}function FE(s){for(const e in s){const t=s[e],i=t.original;if(i.isDirectionalLight!==!0&&i.isSpotLight!==!0)continue;const n=i.target;if(!n||n.parent!==i)continue;const o=Object.values(s).find(a=>a.original===n);if(!o)continue;const r=o.clone;t.clone.target=r,r.hideFlags|=as.DontExport}}function jE(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 zc(s,e){try{e||s()}catch(t){return console.error(t),!1}return!0}const Gg=x("debugnewscripts"),UE=x("debughierarchy"),Te=[];function zE(){return Te.length>0}function of(s){if(Gg&&console.log("Register new components",s.new_scripts.length,[...s.new_scripts],s.alias?"element: "+s.alias:s.hash,s),zS(s),!(s.new_scripts.length<=0)){Te.length=0,s.new_scripts.length>0&&Te.push(...s.new_scripts),s.new_scripts.length=0;for(let e=0;e<Te.length;e++)try{const t=Te[e];if(t.isComponent!==!0){(E()||Gg)&&console.error(`Registered script is not a Needle Engine component.
|
|
884
884
|
The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
|
|
885
885
|
`,t),Te.splice(e,1),e--;continue}if(t.destroyed)continue;if(!t.gameObject){console.warn(`Component can not be initialized: no GameObject assigned.
|
|
@@ -1084,7 +1084,7 @@ Consider registering a custom loader via the 'onCreateCustomModelLoader' callbac
|
|
|
1084
1084
|
Content-Type: "${t.headers.get("content-type")}"
|
|
1085
1085
|
"Text: "${o}"
|
|
1086
1086
|
Binary:`,i)}else Ae&&console.debug("Could not determine file type from binary data");return"unknown"}const Pm=x("debugstencil");function cA(s,e){return(s&1<<e.layer)!=0}const hA=Symbol("stencils");class bo{get name(){return"NEEDLE_render_objects"}static stencils={};static applyStencil(e){if(!e)return;const t=e.sourceId;if(Pm&&console.log(t,bo.stencils),!t)return;const i=bo.stencils[t];if(i)for(let n=i.length-1;n>=0;n--){const o=i[n];if(cA(o.layer,e)){Pm&&console.log(o),setTimeout(()=>{ki()&&$f(e.gameObject)&&(de("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[hA]=!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[uA];if(i){Pm&&console.log(i);const n=i.stencil;if(n&&Array.isArray(n))for(const o of n){const r={...o};r.compareFunc=dA(r.compareFunc),r.passOp=km(r.passOp),r.failOp=km(r.failOp),r.zFailOp=km(r.zFailOp),bo.stencils[this.source]||(bo.stencils[this.source]=[]),bo.stencils[this.source].push(r)}}}return null}}function km(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 dA(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 uA="NEEDLE_render_objects";class fA{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 So=new fA;class As{_overrides=[];_defines={};_object=null;get object(){return this._object}constructor(e=null){this._object=e}static get(e){let t=So.getBlock(e);return t||(t=new As(e),So.setBlock(e,t),yA(e,t)),t}static hasOverrides(e){const t=So.getBlock(e);return t?t.hasOverrides():!1}dispose(){this._object&&So.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)}removeOverride(e){const t=this._overrides.findIndex(i=>i.name===e);t>=0&&this._overrides.splice(t,1)}removeOveride(e){this.removeOverride(e)}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 Ru=Symbol("originalValues"),Tu=Symbol("savedTextureTransforms");function A_(s){let e=So.getBlock(s);if(e)return{block:e,owner:s};if(s.parent&&s.parent.type==="Group"&&(e=So.getBlock(s.parent),e))return{block:e,owner:s.parent}}const tl=Symbol("beforeRenderingFlag"),sy=new WeakMap,oy=new WeakMap,pA=function(s,e,t,i){const n=A_(this)?.block;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&&(oy.set(this,t.transmission),t.transmission=o),r!==void 0&&typeof r=="boolean"&&r!==t.transparent&&(sy.set(this,t.transparent),t.transparent=r)}},mA=function(s,e,t,i){const n=sy.get(s);n!==void 0&&(sy.delete(s),t.transparent=n);const o=oy.get(s);o!==void 0&&(oy.delete(s),t.transmission=o)};let R0=!1;const gA=x("debugreflectionprobe"),T0=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[tl]===void 0&&(this[tl]=new WeakSet),this[tl].add(n);const a=A_(this);if(!a)return;const{block:l,owner:h}=a,d=l.overrides,u=n,f=l.getDefines(),m=Object.keys(f);if(m.length>0){u.defines||(u.defines={});for(const _ of m){const y=f[_];y!==void 0&&(u.defines[_]=y)}}if(d.length===0&&m.length===0)return;let g=m.length>0;u[Ru]||(u[Ru]=[]);const v=u[Ru];for(const _ of d){if(_.value===null)continue;if(u.isMeshBasicMaterial===!0&&(_.name==="envMap"||_.name==="envMapRotation"||_.name==="envMapIntensity")){_.name==="envMap"&&!R0&&(E()||gA)&&(R0=!0,console.warn(`MaterialPropertyBlock: Ignoring envMap override on MeshBasicMaterial (object: "${this.name}", material: "${n.name}"). Use a lit material such as MeshStandardMaterial if reflection probes are intended.`));continue}const y=u[_.name],b=v.find(w=>w.name===_.name);if(b?b.value=y:v.push({name:_.name,value:y}),!g&&!!y!=!!_.value&&(g=!0),u[_.name]=_.value,_.textureTransform&&_.value instanceof c.Texture){const w=_.value;u[Tu]||(u[Tu]=[]),u[Tu].push({name:_.name,offsetX:w.offset.x,offsetY:w.offset.y,repeatX:w.repeat.x,repeatY:w.repeat.y});const C=_.textureTransform;C.offset&&w.offset.copy(C.offset),C.repeat&&w.repeat.copy(C.repeat)}}g&&(u.needsUpdate=!0),u._forceRefresh=!0},A0=function(s,e,t,i,n,o){if(this[tl]===void 0||!this[tl].has(n))return;this[tl].delete(n);const r=A_(this);if(!r)return;const{block:a,owner:l}=r,h=a.overrides,d=n,u=d[Ru],f=a.getDefines(),m=Object.keys(f);let g=!1;if(m.length>0&&d.defines){for(const _ of m)delete d.defines[_];g=!0}if(h.length===0){g&&(d.needsUpdate=!0,d._forceRefresh=!0);return}if(!u)return;const v=d[Tu];if(v&&v.length>0){for(const _ of v){const y=h.find(b=>b.name===_.name);y?.value instanceof c.Texture&&(y.value.offset.set(_.offsetX,_.offsetY),y.value.repeat.set(_.repeatX,_.repeatY))}v.length=0}for(const _ of h){const y=u.find(b=>b.name===_.name);y&&(!g&&!!_.value!=!!y.value&&(g=!0),d[_.name]=y.value)}g&&(d.needsUpdate=!0),d._forceRefresh=!0};function yA(s,e){s.type==="Group"?s.children.forEach(t=>{(t.type==="Mesh"||t.type==="SkinnedMesh")&&D0(t,s,e)}):(s.type==="Mesh"||s.type==="SkinnedMesh")&&D0(s,s,e)}function D0(s,e,t){if(!So.isHooked(s,e)){if(So.addHook(s,e),s["needle:materialPropertyBlock"]=t,!s.onBeforeRender)s.onBeforeRender=T0;else{const i=s.onBeforeRender;s.onBeforeRender=function(n,o,r,a,l,h){i.call(this,n,o,r,a,l,h),T0.call(this,n,o,r,a,l,h)}}if(!s.onAfterRender)s.onAfterRender=A0;else{const i=s.onAfterRender;s.onAfterRender=function(n,o,r,a,l,h){A0.call(this,n,o,r,a,l,h),i.call(this,n,o,r,a,l,h)}}s.onBeforeRenderListPush=pA,s.onAfterRenderListPush=mA}}var _A=Object.defineProperty,bA=Object.getOwnPropertyDescriptor,lp=(s,e,t,i)=>{for(var n=i>1?void 0:i?bA(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&&_A(e,t,n),n};const va=x("debugreflectionprobe"),I0=x("noreflectionprobe");let tr=null;const vA=Symbol("reflectionProbeKey"),$h=class gn extends T{static _probes=new Map;static testBox=new c.Box3;static isUsingReflectionProbe(e){return!!e[vA]}static onEnabled=new Z;static onDisabled=new Z;static get(e,t,i,n){if(!e||e.isObject3D!==!0||I0)return null;const o=gn._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 va&&console.log("Found reflection probe",e.name,r.name),r}}return va&&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"){va&&console.debug(`[ReflectionProbe] Loading reflection probe texture from URL: ${e}`),this._textureUrlInFlight=e;const t=cs(this.sourceId,e);Bh(t,this.context.renderer).then(i=>{this._textureUrlInFlight===e&&i&&(this._textureUrlInFlight=void 0,va&&console.debug(`[ReflectionProbe] Successfully loaded reflection probe texture: ${e}`),this.texture=i)});return}this.__didAwake&&(this._textureUrlInFlight=void 0),this._texture=e,va&&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 tr??=new c.Box3,tr.setFromCenterAndSize(this.gameObject.worldPosition.add(this.center),this.size),pi([e],void 0,void 0,gn.testBox),gn.testBox.isEmpty()?tr.containsPoint(e.worldPosition):tr?.intersectsBox(gn.testBox)}constructor(){super(),gn._probes.has(this.context)||gn._probes.set(this.context,[]),gn._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(){va&&(tr??=new c.Box3,tr.setFromCenterAndSize(this.gameObject.worldPosition.add(this.center),this.size),B.DrawWireBox3(tr,5592320))}onEnable(){gn.onEnabled?.invoke(this)}onDisable(){gn.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=gn._probes.get(this.context);if(e){const t=e.indexOf(this);t>=0&&e.splice(t,1)}}apply(e){if(I0||!this.enabled||!this.texture)return;const t=As.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=As.get(e);t&&t.getOverride("envMap")?.value===this.texture&&(t.removeOverride("envMap"),t.removeOverride("envMapRotation"),t.removeOverride("envMapIntensity"))}};lp([p([c.Texture,String])],$h.prototype,"texture",1);lp([p()],$h.prototype,"intensity",2);lp([p(c.Vector3)],$h.prototype,"center",2);lp([p(c.Vector3)],$h.prototype,"size",2);let Ps=$h;const Mm=x("debugexr");class wA{get name(){return"EXT_texture_exr"}parser;constructor(e){this.parser=e,Mm&&console.log(e)}loadTexture(e){const t=this.name,i=this.parser,o=i.json.textures[e];if(Mm&&console.log("EXT_texture_exr.loadTexture",e,o),!o.extensions||!o.extensions[t])return null;const r=o.extensions[t],a=new V.EXRLoader(i.options.manager);return Mm&&console.log("EXT_texture_exr.loadTexture",r),i.loadTextureImage(e,r.source,a)}}typeof window<"u"&&window.addEventListener("unhandledrejection",s=>{});const Ln=_t,Wd="$___Export_Components",xA="NEEDLE_components";class SA{[cr]}class CA{node;nodeIndex;nodeDef;constructor(e,t,i){this.node=e,this.nodeIndex=t,this.nodeDef=i}}class D_{get name(){return xA}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[Wd]=i,!0)}afterSerializeUserData(e,t){if(e.type==="Scene"&&Ln&&console.log("DONE",JSON.stringify(t)),e[Wd]===void 0)return;const i=e[Wd];delete e[Wd],i!==null&&(e.userData.components=i)}writeNode(e,t){Ln&&console.log(e.name,e.uuid);const i=new CA(e,-1,t);this.exportContext[e.uuid]=i}afterParse(e){Ln&&console.log("AFTER",e);const t=this.writer?.nodeMap;if(t)for(const[n,o]of t)this.objectToNodeMap[n.uuid]=o;for(const n in this.exportContext){const o=this.exportContext[n],r=o.node,a=o.nodeDef,l=t?.get(r)??o.nodeIndex;l===void 0||l<0||this.writeComponentsIntoDef(r,a,l)}const i=this.writer?.json?.scenes;if(i){const n=Array.isArray(e)?e:[e];let o=0;for(const r of n)if(r?.isScene===!0){if(o>=i.length)break;this.writeComponentsIntoDef(r,i[o]),o++}}}writeComponentsIntoDef(e,t,i){const n=e.userData?.components;if(!n||n.length<=0)return;this.context.object=e,this.context.nodeId=i,this.context.objectToNode=this.objectToNodeMap;const o=[];for(const r of n){this.context.target=r;const a=Is().writeBuiltinComponentData(r,this.context);a!==null&&o.push(a)}if(o.length>0){const r=new SA;r[cr]=o,t.extensions=t.extensions||{},t.extensions[this.name]=r,Ln&&console.log("DID WRITE",e,i!==void 0?`nodeIndex ${i}`:"(scene)",o)}}parser;nodeToObjectMap={};gltf=null;beforeRoot(){return Ln&&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];Ln&&console.log("After root",e,this.parser,i);const o=[];if(n===!0){const r=t.json.nodes;if(r){for(let l=0;l<r.length;l++){const h=await t.getDependency("node",l);this.nodeToObjectMap[l]=h}for(let l=0;l<r.length;l++){const h=r[l],d=l,u=h.extensions;if(!u)continue;const f=u[this.name];if(!f)continue;Ln&&console.log("NODE",h);const m=this.nodeToObjectMap[d];if(!m){console.error("Could not find object for node index: "+d,h,t);continue}lh(m),o.push(this.createComponents(e,h,m,f))}}const a=t.json.scenes;if(a)for(let l=0;l<a.length;l++){const h=a[l],d=h?.extensions?.[this.name];if(!d)continue;const u=await t.getDependency("scene",l);if(!u){console.error("Could not find scene for index: "+l,h,t);continue}lh(u),o.push(this.createComponents(e,h,u,d))}}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;xM(r,l)}}}async createComponents(e,t,i,n){if(!n)return;const o=n[cr];if(o){const r=new Array;Ln&&console.log(i.name,o);for(const a in o){const l=o[a];if(Ln&&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(f=>"/materials/"+(f.material??0)),h=!0)}}!h&&(Ln||E())&&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(Gy(this.parser,l).catch(h=>console.error(`Error while resolving references (see console for details)
|
|
1087
|
-
`,h,i,l))),i.userData=i.userData||{},i.userData[cr]=i.userData[cr]||[],i.userData[cr].push(l)}await Promise.all(r).catch(a=>{console.error("Error while loading components",a)})}}}const L0="NEEDLE_gameobject_data",PA={Default:0,"Ignore Raycast":2},Gd=new Map,Om=8,Hd=31;function kA(s){if(typeof s=="number"&&isFinite(s))return s;if(typeof s=="string"&&s.length>0){const e=PA[s];if(e!==void 0)return e;let t=Gd.get(s);return t===void 0&&(t=Math.min(Om+Gd.size,Hd),Om+Gd.size>Hd&&console.warn(`[NEEDLE_gameobject_data] more than ${Hd-Om+1} named layers — "${s}" shares index ${Hd}`),Gd.set(s,t)),t}return 0}class MA{get name(){return L0}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[L0];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(kA(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 B0="NEEDLE_lighting_settings",Aa=x("debugenvlight");class OA{get name(){return B0}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[B0];if(i){Aa&&console.log('Loaded "'+this.name+'", src: "'+this.sourceId+'"',i);let n;if(e.scene.children.length===1){const o=e.scene.children[0];n=P.addComponent(o,ff,{},{callAwake:!1})}else{const o=new c.Object3D;o.name="LightSettings "+this.sourceId,e.scene.add(o),n=P.addComponent(o,ff,{},{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}}se.registerCallback(ae.ContextCreated,s=>{const e=s.context,t=P.findObjectOfType(ff,e);t?.sourceId&&(t.enabled=!0)});class ff extends T{ambientMode=Ya.Skybox;ambientLight;ambientTrilight;ambientIntensity=1;environmentReflectionSource=Ju.Skybox;_hasReflection=!1;_ambientLightObj;_hemisphereLightObj;awake(){if(this.sourceId){const t=this.environmentReflectionSource===Ju.Skybox?$n.Skybox:$n.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),Aa&&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*L.lerp(0,1.33,t)}onEnable(){if(Aa&&console.warn("💡🟡 >>> Enable lighting",this.sourceId,this.enabled,this),this.ambientMode==Ya.Flat){if(this.ambientLight&&!this._ambientLightObj){const e=this.calculateIntensityFactor(this.ambientLight);this._ambientLightObj=new c.AmbientLight(this.ambientLight,this.ambientIntensity*e),Aa&&console.log("Created ambient light",this.sourceId,this._ambientLightObj,this.ambientIntensity,e)}this._ambientLightObj&&this.gameObject.add(this._ambientLightObj)}else if(this.ambientMode===Ya.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),Aa&&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(){Aa&&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 A.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 EA 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 jo.createPrimitive("ShaderBall",{material:e})}}class RA{constructor(e,t,i,n){this.context=e,this.url=i,this.parser=n}context;url;parser;get name(){return"materialx-loading-helper"}mtlxLoader;async beforeRoot(){if(this.parser.json.extensions?.NEEDLE_materials_mtlx){const t=await A.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 kC=(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))(kC||{});const Un=x("debugcustomshader"),wa="NEEDLE_techniques_webgl";class TA{objectToWorldMatrix=new c.Matrix4;worldToObjectMatrix=new c.Matrix4;objectToWorld=new Array;worldToObject=new Array;updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),Zu(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),Zu(this.worldToObjectMatrix,this.worldToObject)}}class Me extends c.RawShaderMaterial{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);clone(){const e=super.clone();return MC(e),e}constructor(e,...t){super(...t),this.identifier=e,Un&&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)&&X.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}dispose(){super.dispose();const e=X.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&X.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 TA;get depthTextureUniform(){if(this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&X.Current.setRequireColor(!0),this.depthTextureUniform&&X.Current.setRequireDepth(!0)}onBeforeRender(e,t,i,n,o,r){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,o)}onUpdateUniforms(e,t){const i=X.Current;if(e&&(Me.viewProjection&&this.uniforms[this._viewProjectionName]&&(Me.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),Zu(Me.viewProjection,Me._viewProjectionValues)),Me.viewMatrix&&this.uniforms[this._viewMatrixName]&&(Me.viewMatrix.copy(e.matrixWorldInverse),Zu(Me.viewMatrix,Me._viewMatrixValues)),this.uniforms[Me._worldSpaceCameraPosName]&&Me._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=ie(n.gameObject,Me._mainLightPosition);this.uniforms._MainLightPosition={value:a.normalize()},Me._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:Me._mainLightColor};const l=n.intensity;Me._lightData.z=l,this.uniforms.unity_LightData={value:Me._lightData}}if(e&&(Me.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=Me._viewProjectionValues),Me.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=Me._viewMatrixValues),this.uniforms[Me._worldSpaceCameraPosName]&&(this.uniforms[Me._worldSpaceCameraPosName]={value:Me._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 AA{get name(){return wa}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){const t=this.parser.json.materials[e];if(!t)return Un&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[wa])return Un&&console.log(`Material ${e} does not use NEEDLE_techniques_webgl`),null;Un&&console.log(`Material ${e} uses NEEDLE_techniques_webgl`,t);const i=t.extensions[wa].technique;if(i<0)return console.debug(`Material ${e} does not have a valid technique index`),null;const n=this.parser.json.extensions[wa];if(!n)return Un?console.error("Missing shader data",this.parser.json.extensions):console.debug("Missing custom shader data in parser.json.extensions"),null;Un&&console.log(n);const o=n.techniques[i];return o?new Promise(async(r,a)=>{const l=await sO(n,o.program),h=l?.fragmentShader,d=l?.vertexShader;if(!h||!d)return a();Un&&console.log("loadMaterial",t,l);const u={},f=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 y in f){const b=y;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[wa]){const y=t.extensions[wa];if(y.technique===i){Un&&console.log(t.name,"Material Properties",y);for(const b in y.values){const w=y.values[b];if(typeof w=="string"){if(w.startsWith("/textures/")){const C=w.substring(10),k=Number.parseInt(C);if(k>=0){const O=await this.parser.getDependency("texture",k);O instanceof c.Texture&&(O.colorSpace=c.LinearSRGBColorSpace,O.needsUpdate=!0),u[b]={value:O};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 g=new Me(this.identifier,{name:t.name??"",uniforms:u,vertexShader:d,fragmentShader:h,lights:!1});switch(g.glslVersion=c.GLSL3,g.vertexShader=g.vertexShader.replace("#version 300 es",""),g.fragmentShader=g.fragmentShader.replace("#version 300 es",""),u._Cull?.value){case 0:g.side=c.DoubleSide;break;case 1:g.side=c.BackSide;break;case 2:g.side=c.FrontSide;break;default:g.side=c.FrontSide;break}switch(u._ZTest?.value){case 3:g.depthTest=!0,g.depthFunc=c.EqualDepth;break;case 6:g.depthTest=!0,g.depthFunc=c.NotEqualDepth;break;case 2:g.depthTest=!0,g.depthFunc=c.LessDepth;break;case 4:g.depthTest=!0,g.depthFunc=c.LessEqualDepth;break;case 5:g.depthTest=!0,g.depthFunc=c.GreaterDepth;break;case 7:g.depthTest=!0,g.depthFunc=c.GreaterEqualDepth;break;case 8:g.depthTest=!1,g.depthFunc=c.AlwaysDepth;break}g.transparent=m,m&&(g.depthWrite=!1),iO(u),g.onUpdateUniforms();for(const y in f){const b=y,w=f[y].type;u[b]?.value===void 0&&(w===kC.SAMPLER_2D?(u[b]={value:eO},console.warn("Missing/unassigned texture, fallback to white: "+b)):b==="unity_OrthoParams"||console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+b,f[y]))}Un&&console.log(g.uuid,u),MC(g),r(g)}):null}}function MC(s){if(s.uniforms){Un&&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 DA=x("debugextensions");let pf;const IA=Promise.resolve().then(()=>require("./vendor-BJviq-Oq.umd.cjs")).then(s=>s.index$2).then(async s=>(pf=s.GLTFAnimationPointerExtension,pf)).catch(s=>{console.warn("Failed to import GLTFLoaderAnimationPointer. Please use @needle-tools/three-animationpointer for full KHR_animation support",s)}),Fr=new Array;function LA(s){Fr.includes(s)||Fr.push(s)}function BA(s){const e=Fr.indexOf(s);e>=0&&Fr.splice(e,1)}function I_(s){if(s instanceof V.GLTFLoader){const e=new D_;return s.register(t=>(e.parser=t,e)),e}return null}class FA{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 mf(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 MA(o)),s.register(o=>new CM(o)),s.register(o=>new $M(o,e.lightmaps,i)),s.register(o=>new OA(o,i,e)),s.register(o=>new AA(o,i)),s.register(o=>new bo(o,i)),s.register(o=>new re.NEEDLE_progressive(o)),s.register(o=>new wA(o)),s.register(o=>new Bf(o)),s.register(o=>new RA(e,s,t,o)),kS()&&s.register(o=>new Za(o)),await IA.catch(o=>{}),s.register(o=>{if(pf){const r=new pf(o);return r.setAnimationPointerResolver.bind(r)(new FA),r}else return(DA||E())&&console.error("Missing KHR_animation_pointer extension..."),{name:"KHR_animation_pointer_NOT_AVAILABLE"}});for(const o of Fr)o.onImport&&o.onImport(s,t,e)}function L_(s,e){for(const t of Fr)t.onExport&&t.onExport(s,e)}function OC(s,e,t){for(const i of Fr)i.onLoaded&&i.onLoaded(s,e,t)}const gt=x("debuginstancing"),jA=gt==="lods",Em=x("debugprogressive")==="colors"||jA;function ry(s,e,t,i){return s.lodsManager.manager?.trackLoadingPromise(e,t,i),i}function EC(s){return s.determinant()<0}class jr{static instance=new jr;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(h=>ry(i,"texture",h,re.NEEDLE_progressive.assignTextureLOD(h,0))):ry(i,"texture",l,re.NEEDLE_progressive.assignTextureLOD(l,0))}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 gt&&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.geometry,a=o.material;if(Array.isArray(a))return null;o.updateWorldMatrix(!0,!1);const l=EC(o.matrixWorld);for(const m of this.objs){if(!m.canAdd(r,a,l))continue;return m.addInstance(o,r)}let h=jr.getStartInstanceCount(e);(!h||h<0)&&(h=4);let d=e.name;d?.length||(d=Dw());const u=new fo(d,r,a,h,t,l);return this.objs.push(u),u.addInstance(o,r)}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[rh]||i.equals(a)===!1)&&(i.copy(a),e[rh]=!0),a};e.matrixWorld.multiplyMatrices=n}}class Rr{static all=[];get name(){return this.object.name}get isActive(){return this.__instanceIndex>=0}get vertexCount(){return this.geometry.attributes.position.count}get maxVertexCount(){return Math.max(this.meshInformation.vertexCount,this.vertexCount)}get reservedVertexCount(){return this.__reservedVertexRange}get indexCount(){return this.geometry.index?this.geometry.index.count:0}get maxIndexCount(){return Math.max(this.meshInformation.indexCount,this.indexCount)}get reservedIndexCount(){return this.__reservedIndexRange}object;_geometry;get geometry(){return this._geometry}renderer;__instanceIndex=-1;__reservedVertexRange=0;__reservedIndexRange=0;__geometryIndex=-1;meshInformation;currentMeshLOD;pendingMeshLOD;constructor(e,t,i=e.geometry){this.__instanceIndex=-1,this.object=e,this._geometry=i,this.renderer=t,this.currentMeshLOD=i.userData?.LODS?.level,e[TS]=t,this.meshInformation=dr(e.geometry),Rr.all.push(this)}updateMeshInformation(){const e=dr(this.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.assertMirroringUnchanged(),this.renderer.updateInstance(this.object.matrixWorld,this.__instanceIndex))}_didWarnAboutMirroringChange=!1;assertMirroringUnchanged(){this._didWarnAboutMirroringChange||EC(this.object.matrixWorld)!==this.renderer.mirrored&&(this._didWarnAboutMirroringChange=!0,console.warn(`[Instancing] "${this.name}" changed its mirroring at runtime (world matrix determinant flipped sign). Instanced objects can not change mirroring - this object will render its backfaces. Disable instancing for it via Renderer.setInstanced(obj, false).`))}setMatrix(e){this.__instanceIndex<0||this.renderer.updateInstance(e,this.__instanceIndex)}setGeometry(e){if(this.__geometryIndex<0)return!1;if(this._geometry!==e){const n=this.__instanceIndex>=0;return n&&this.renderer.remove(this,!1),this._geometry=e,this.updateMeshInformation(),n?this.renderer.add(this):!0}this._geometry=e;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:((E()||gt)&&console.error(n),!1)}}add(){this.__instanceIndex>=0||(this.renderer.add(this),P.markAsInstancedRendered(this.object,!0))}remove(e){if(!(this.__instanceIndex<0)&&(this.renderer.remove(this,e),P.markAsInstancedRendered(this.object,!1),e)){const t=Rr.all.indexOf(this);t>=0&&Rr.all.splice(t,1)}}}class fo{get batchedMesh(){return this._batchedMesh}get mirrored(){return this._mirrored}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(),gt&&this._batchedMesh.boundingSphere){const i=fo.debugBoundsSphere.copy(this._batchedMesh.boundingSphere).applyMatrix4(this._batchedMesh.matrixWorld);B.DrawWireSphere(i.center,i.radius,65280)}}_context;_batchedMesh;_mirrored;_handles=[];_geometryIds=new WeakMap;_maxInstanceCount;_currentInstanceCount=0;_currentVertexCount=0;_currentIndexCount=0;_maxVertexCount;_maxIndexCount;static instanceMatrix=new c.Matrix4;static lodProjectionScreenMatrix=new c.Matrix4;static debugBoundsSphere=new c.Sphere;static debugLODColor=new c.Color;static lodSelectionResult={level:-1,primitiveIndex:0,screenCoverage:0,screenspaceVolume:new c.Vector3,centrality:1};canAdd(e,t,i){return this._maxVertexCount>1e7||this._mirrored!==i||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,r=!1){this.name=e,this.geometry=t,this.material=i,this._context=o,this._mirrored=r,this._maxInstanceCount=Math.max(2,n),gt&&(this._debugMaterial=F0(Em));const a=this.tryEstimateVertexCountSize(this._maxInstanceCount,[t],n);this._maxVertexCount=a.vertexCount,this._maxIndexCount=a.indexCount,this._batchedMesh=new c.BatchedMesh(this._maxInstanceCount,this._maxVertexCount,this._maxIndexCount,this._debugMaterial??this.material),this._batchedMesh.name=this.getBatchedMeshName(),this.applyBatchTransform(this._batchedMesh),this._batchedMesh[Cc]=!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),gt&&console.log(`Instanced renderer (${this.name}) created with ${this._maxInstanceCount} instances, ${this._maxVertexCount} max vertices and ${this._maxIndexCount} max indices for "${e}"`)}dispose(){gt&&console.warn("Dispose instanced renderer",this.name),this._context.scene.remove(this._batchedMesh),this._batchedMesh.dispose(),this._batchedMesh=null,this._handles=[]}addInstance(e,t){const i=new Rr(e,this,t);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(i)}catch(n){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()})
|
|
1087
|
+
`,h,i,l))),i.userData=i.userData||{},i.userData[cr]=i.userData[cr]||[],i.userData[cr].push(l)}await Promise.all(r).catch(a=>{console.error("Error while loading components",a)})}}}const L0="NEEDLE_gameobject_data",PA={Default:0,"Ignore Raycast":2},Gd=new Map,Om=8,Hd=31;function kA(s){if(typeof s=="number"&&isFinite(s))return s;if(typeof s=="string"&&s.length>0){const e=PA[s];if(e!==void 0)return e;let t=Gd.get(s);return t===void 0&&(t=Math.min(Om+Gd.size,Hd),Om+Gd.size>Hd&&console.warn(`[NEEDLE_gameobject_data] more than ${Hd-Om+1} named layers — "${s}" shares index ${Hd}`),Gd.set(s,t)),t}return 0}class MA{get name(){return L0}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[L0];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(kA(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 B0="NEEDLE_lighting_settings",Aa=x("debugenvlight");class OA{get name(){return B0}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[B0];if(i){Aa&&console.log('Loaded "'+this.name+'", src: "'+this.sourceId+'"',i);let n;if(e.scene.children.length===1){const o=e.scene.children[0];n=P.addComponent(o,ff,{},{callAwake:!1})}else{const o=new c.Object3D;o.name="LightSettings "+this.sourceId,e.scene.add(o),n=P.addComponent(o,ff,{},{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}}se.registerCallback(ae.ContextCreated,s=>{const e=s.context,t=P.findObjectOfType(ff,e);t?.sourceId&&(t.enabled=!0)});class ff extends T{ambientMode=Ya.Skybox;ambientLight;ambientTrilight;ambientIntensity=1;environmentReflectionSource=Ju.Skybox;_hasReflection=!1;_ambientLightObj;_hemisphereLightObj;awake(){if(this.sourceId){const t=this.environmentReflectionSource===Ju.Skybox?$n.Skybox:$n.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),Aa&&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*L.lerp(0,1.33,t)}onEnable(){if(Aa&&console.warn("💡🟡 >>> Enable lighting",this.sourceId,this.enabled,this),this.ambientMode==Ya.Flat){if(this.ambientLight&&!this._ambientLightObj){const e=this.calculateIntensityFactor(this.ambientLight);this._ambientLightObj=new c.AmbientLight(this.ambientLight,this.ambientIntensity*e),Aa&&console.log("Created ambient light",this.sourceId,this._ambientLightObj,this.ambientIntensity,e)}this._ambientLightObj&&this.gameObject.add(this._ambientLightObj)}else if(this.ambientMode===Ya.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),Aa&&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(){Aa&&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 A.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 EA 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 jo.createPrimitive("ShaderBall",{material:e})}}class RA{constructor(e,t,i,n){this.context=e,this.url=i,this.parser=n}context;url;parser;get name(){return"materialx-loading-helper"}mtlxLoader;async beforeRoot(){if(this.parser.json.extensions?.NEEDLE_materials_mtlx){const t=await A.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 kC=(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))(kC||{});const Un=x("debugcustomshader"),wa="NEEDLE_techniques_webgl";class TA{objectToWorldMatrix=new c.Matrix4;worldToObjectMatrix=new c.Matrix4;objectToWorld=new Array;worldToObject=new Array;updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),Zu(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),Zu(this.worldToObjectMatrix,this.worldToObject)}}class Me extends c.RawShaderMaterial{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);clone(){const e=super.clone();return MC(e),e}constructor(e,...t){super(...t),this.identifier=e,Un&&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)&&X.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}dispose(){super.dispose();const e=X.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&X.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 TA;get depthTextureUniform(){if(this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&X.Current.setRequireColor(!0),this.depthTextureUniform&&X.Current.setRequireDepth(!0)}onBeforeRender(e,t,i,n,o,r){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,o)}onUpdateUniforms(e,t){const i=X.Current;if(e&&(Me.viewProjection&&this.uniforms[this._viewProjectionName]&&(Me.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),Zu(Me.viewProjection,Me._viewProjectionValues)),Me.viewMatrix&&this.uniforms[this._viewMatrixName]&&(Me.viewMatrix.copy(e.matrixWorldInverse),Zu(Me.viewMatrix,Me._viewMatrixValues)),this.uniforms[Me._worldSpaceCameraPosName]&&Me._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=ie(n.gameObject,Me._mainLightPosition);this.uniforms._MainLightPosition={value:a.normalize()},Me._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:Me._mainLightColor};const l=n.intensity;Me._lightData.z=l,this.uniforms.unity_LightData={value:Me._lightData}}if(e&&(Me.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=Me._viewProjectionValues),Me.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=Me._viewMatrixValues),this.uniforms[Me._worldSpaceCameraPosName]&&(this.uniforms[Me._worldSpaceCameraPosName]={value:Me._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 AA{get name(){return wa}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){const t=this.parser.json.materials[e];if(!t)return Un&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[wa])return Un&&console.log(`Material ${e} does not use NEEDLE_techniques_webgl`),null;Un&&console.log(`Material ${e} uses NEEDLE_techniques_webgl`,t);const i=t.extensions[wa].technique;if(i<0)return console.debug(`Material ${e} does not have a valid technique index`),null;const n=this.parser.json.extensions[wa];if(!n)return Un?console.error("Missing shader data",this.parser.json.extensions):console.debug("Missing custom shader data in parser.json.extensions"),null;Un&&console.log(n);const o=n.techniques[i];return o?new Promise(async(r,a)=>{const l=await sO(n,o.program),h=l?.fragmentShader,d=l?.vertexShader;if(!h||!d)return a();Un&&console.log("loadMaterial",t,l);const u={},f=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 y in f){const b=y;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[wa]){const y=t.extensions[wa];if(y.technique===i){Un&&console.log(t.name,"Material Properties",y);for(const b in y.values){const w=y.values[b];if(typeof w=="string"){if(w.startsWith("/textures/")){const C=w.substring(10),k=Number.parseInt(C);if(k>=0){const O=await this.parser.getDependency("texture",k);O instanceof c.Texture&&(O.colorSpace=c.LinearSRGBColorSpace,O.needsUpdate=!0),u[b]={value:O};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 g=new Me(this.identifier,{name:t.name??"",uniforms:u,vertexShader:d,fragmentShader:h,lights:!1});switch(g.glslVersion=c.GLSL3,g.vertexShader=g.vertexShader.replace("#version 300 es",""),g.fragmentShader=g.fragmentShader.replace("#version 300 es",""),u._Cull?.value){case 0:g.side=c.DoubleSide;break;case 1:g.side=c.BackSide;break;case 2:g.side=c.FrontSide;break;default:g.side=c.FrontSide;break}switch(u._ZTest?.value){case 3:g.depthTest=!0,g.depthFunc=c.EqualDepth;break;case 6:g.depthTest=!0,g.depthFunc=c.NotEqualDepth;break;case 2:g.depthTest=!0,g.depthFunc=c.LessDepth;break;case 4:g.depthTest=!0,g.depthFunc=c.LessEqualDepth;break;case 5:g.depthTest=!0,g.depthFunc=c.GreaterDepth;break;case 7:g.depthTest=!0,g.depthFunc=c.GreaterEqualDepth;break;case 8:g.depthTest=!1,g.depthFunc=c.AlwaysDepth;break}g.transparent=m,m&&(g.depthWrite=!1),iO(u),g.onUpdateUniforms();for(const y in f){const b=y,w=f[y].type;u[b]?.value===void 0&&(w===kC.SAMPLER_2D?(u[b]={value:eO},console.warn("Missing/unassigned texture, fallback to white: "+b)):b==="unity_OrthoParams"||console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+b,f[y]))}Un&&console.log(g.uuid,u),MC(g),r(g)}):null}}function MC(s){if(s.uniforms){Un&&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 DA=x("debugextensions");let pf;const IA=Promise.resolve().then(()=>require("./vendor-CDN1hirK.umd.cjs")).then(s=>s.index$2).then(async s=>(pf=s.GLTFAnimationPointerExtension,pf)).catch(s=>{console.warn("Failed to import GLTFLoaderAnimationPointer. Please use @needle-tools/three-animationpointer for full KHR_animation support",s)}),Fr=new Array;function LA(s){Fr.includes(s)||Fr.push(s)}function BA(s){const e=Fr.indexOf(s);e>=0&&Fr.splice(e,1)}function I_(s){if(s instanceof V.GLTFLoader){const e=new D_;return s.register(t=>(e.parser=t,e)),e}return null}class FA{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 mf(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 MA(o)),s.register(o=>new CM(o)),s.register(o=>new $M(o,e.lightmaps,i)),s.register(o=>new OA(o,i,e)),s.register(o=>new AA(o,i)),s.register(o=>new bo(o,i)),s.register(o=>new re.NEEDLE_progressive(o)),s.register(o=>new wA(o)),s.register(o=>new Bf(o)),s.register(o=>new RA(e,s,t,o)),kS()&&s.register(o=>new Za(o)),await IA.catch(o=>{}),s.register(o=>{if(pf){const r=new pf(o);return r.setAnimationPointerResolver.bind(r)(new FA),r}else return(DA||E())&&console.error("Missing KHR_animation_pointer extension..."),{name:"KHR_animation_pointer_NOT_AVAILABLE"}});for(const o of Fr)o.onImport&&o.onImport(s,t,e)}function L_(s,e){for(const t of Fr)t.onExport&&t.onExport(s,e)}function OC(s,e,t){for(const i of Fr)i.onLoaded&&i.onLoaded(s,e,t)}const gt=x("debuginstancing"),jA=gt==="lods",Em=x("debugprogressive")==="colors"||jA;function ry(s,e,t,i){return s.lodsManager.manager?.trackLoadingPromise(e,t,i),i}function EC(s){return s.determinant()<0}class jr{static instance=new jr;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(h=>ry(i,"texture",h,re.NEEDLE_progressive.assignTextureLOD(h,0))):ry(i,"texture",l,re.NEEDLE_progressive.assignTextureLOD(l,0))}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 gt&&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.geometry,a=o.material;if(Array.isArray(a))return null;o.updateWorldMatrix(!0,!1);const l=EC(o.matrixWorld);for(const m of this.objs){if(!m.canAdd(r,a,l))continue;return m.addInstance(o,r)}let h=jr.getStartInstanceCount(e);(!h||h<0)&&(h=4);let d=e.name;d?.length||(d=Dw());const u=new fo(d,r,a,h,t,l);return this.objs.push(u),u.addInstance(o,r)}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[rh]||i.equals(a)===!1)&&(i.copy(a),e[rh]=!0),a};e.matrixWorld.multiplyMatrices=n}}class Rr{static all=[];get name(){return this.object.name}get isActive(){return this.__instanceIndex>=0}get vertexCount(){return this.geometry.attributes.position.count}get maxVertexCount(){return Math.max(this.meshInformation.vertexCount,this.vertexCount)}get reservedVertexCount(){return this.__reservedVertexRange}get indexCount(){return this.geometry.index?this.geometry.index.count:0}get maxIndexCount(){return Math.max(this.meshInformation.indexCount,this.indexCount)}get reservedIndexCount(){return this.__reservedIndexRange}object;_geometry;get geometry(){return this._geometry}renderer;__instanceIndex=-1;__reservedVertexRange=0;__reservedIndexRange=0;__geometryIndex=-1;meshInformation;currentMeshLOD;pendingMeshLOD;constructor(e,t,i=e.geometry){this.__instanceIndex=-1,this.object=e,this._geometry=i,this.renderer=t,this.currentMeshLOD=i.userData?.LODS?.level,e[TS]=t,this.meshInformation=dr(e.geometry),Rr.all.push(this)}updateMeshInformation(){const e=dr(this.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.assertMirroringUnchanged(),this.renderer.updateInstance(this.object.matrixWorld,this.__instanceIndex))}_didWarnAboutMirroringChange=!1;assertMirroringUnchanged(){this._didWarnAboutMirroringChange||EC(this.object.matrixWorld)!==this.renderer.mirrored&&(this._didWarnAboutMirroringChange=!0,console.warn(`[Instancing] "${this.name}" changed its mirroring at runtime (world matrix determinant flipped sign). Instanced objects can not change mirroring - this object will render its backfaces. Disable instancing for it via Renderer.setInstanced(obj, false).`))}setMatrix(e){this.__instanceIndex<0||this.renderer.updateInstance(e,this.__instanceIndex)}setGeometry(e){if(this.__geometryIndex<0)return!1;if(this._geometry!==e){const n=this.__instanceIndex>=0;return n&&this.renderer.remove(this,!1),this._geometry=e,this.updateMeshInformation(),n?this.renderer.add(this):!0}this._geometry=e;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:((E()||gt)&&console.error(n),!1)}}add(){this.__instanceIndex>=0||(this.renderer.add(this),P.markAsInstancedRendered(this.object,!0))}remove(e){if(!(this.__instanceIndex<0)&&(this.renderer.remove(this,e),P.markAsInstancedRendered(this.object,!1),e)){const t=Rr.all.indexOf(this);t>=0&&Rr.all.splice(t,1)}}}class fo{get batchedMesh(){return this._batchedMesh}get mirrored(){return this._mirrored}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(),gt&&this._batchedMesh.boundingSphere){const i=fo.debugBoundsSphere.copy(this._batchedMesh.boundingSphere).applyMatrix4(this._batchedMesh.matrixWorld);B.DrawWireSphere(i.center,i.radius,65280)}}_context;_batchedMesh;_mirrored;_handles=[];_geometryIds=new WeakMap;_maxInstanceCount;_currentInstanceCount=0;_currentVertexCount=0;_currentIndexCount=0;_maxVertexCount;_maxIndexCount;static instanceMatrix=new c.Matrix4;static lodProjectionScreenMatrix=new c.Matrix4;static debugBoundsSphere=new c.Sphere;static debugLODColor=new c.Color;static lodSelectionResult={level:-1,primitiveIndex:0,screenCoverage:0,screenspaceVolume:new c.Vector3,centrality:1};canAdd(e,t,i){return this._maxVertexCount>1e7||this._mirrored!==i||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,r=!1){this.name=e,this.geometry=t,this.material=i,this._context=o,this._mirrored=r,this._maxInstanceCount=Math.max(2,n),gt&&(this._debugMaterial=F0(Em));const a=this.tryEstimateVertexCountSize(this._maxInstanceCount,[t],n);this._maxVertexCount=a.vertexCount,this._maxIndexCount=a.indexCount,this._batchedMesh=new c.BatchedMesh(this._maxInstanceCount,this._maxVertexCount,this._maxIndexCount,this._debugMaterial??this.material),this._batchedMesh.name=this.getBatchedMeshName(),this.applyBatchTransform(this._batchedMesh),this._batchedMesh[Cc]=!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),gt&&console.log(`Instanced renderer (${this.name}) created with ${this._maxInstanceCount} instances, ${this._maxVertexCount} max vertices and ${this._maxIndexCount} max indices for "${e}"`)}dispose(){gt&&console.warn("Dispose instanced renderer",this.name),this._context.scene.remove(this._batchedMesh),this._batchedMesh.dispose(),this._batchedMesh=null,this._handles=[]}addInstance(e,t){const i=new Rr(e,this,t);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(i)}catch(n){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()})
|
|
1088
1088
|
`,n),E()){wl("Failed instancing mesh. See the browser console for details.");debugger}return null}return i}add(e){const t=e.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.setInstanceMatrix(t,e),this.markNeedsUpdate()}applyBatchTransform(e){this._mirrored&&e.scale.z!==-1&&(e.scale.z=-1,e.updateMatrixWorld())}setInstanceMatrix(e,t){if(!this._mirrored){this._batchedMesh.setMatrixAt(e,t);return}const i=fo.instanceMatrix.copy(t),n=i.elements;n[2]=-n[2],n[6]=-n[6],n[10]=-n[10],n[14]=-n[14],this._batchedMesh.setMatrixAt(e,i)}updateGeometry(e,t){return this.validateGeometry(e)?(this.mustGrow()&&this.grow(e),gt&&console.debug("[Instancing] UPDATE GEOMETRY at "+t,this._batchedMesh._geometryCount,e.name,dr(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.updateProgressiveMeshLODs(),this._batchedMesh.layers.enableAll(),this._needUpdateBounds&&this._batchedMesh[Cc]===!0&&(gt==="verbose"&&console.log("Update instancing bounds",this.name,this._batchedMesh.matrixWorldNeedsUpdate),this.updateBounds())};updateProgressiveMeshLODs(){const e=this._context.mainCamera;if(!e)return;fo.lodProjectionScreenMatrix.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse);const t=this._context.lodsManager?.targetTriangleDensity??2e5,i=this._handles.length;for(let n=0;n<i;n++){const o=this._handles[n];if(!o||o.__instanceIndex<0)continue;const r=this.calculateProgressiveMeshLOD(o,t);r<0||o.currentMeshLOD===r||o.pendingMeshLOD===r||this.assignProgressiveMeshLOD(o,r)}}assignProgressiveMeshLOD(e,t){const i=e.geometry;e.pendingMeshLOD=t;const n=re.NEEDLE_progressive.assignMeshLOD(e.object,t,{apply:o=>this.shouldApplyProgressiveMeshLOD(e,t)&&(i===o||e.setGeometry(o))?(e.object.geometry=o,e.currentMeshLOD=t,this.updateDebugLODColor(e),!0):!1});ry(this._context,"mesh",e.object,n).catch(o=>{(gt||E())&&console.warn(`Failed loading instanced mesh LOD ${t} for ${e.name}`,o)}).finally(()=>{e.pendingMeshLOD===t&&(e.pendingMeshLOD=void 0)})}shouldApplyProgressiveMeshLOD(e,t){if(e.__instanceIndex<0)return!1;if(e.pendingMeshLOD===t)return!0;const i=e.currentMeshLOD??e.geometry.userData?.LODS?.level??1/0;if(t>=i)return!1;const n=e.pendingMeshLOD;return typeof n=="number"&&t>=n}calculateProgressiveMeshLOD(e,t){e.object.matrixWorldNeedsUpdate&&e.object.updateWorldMatrix(!0,!1);const i=this._context.mainCamera;return i?re.calculateMeshLODLevel({geometry:e.geometry,matrixWorld:e.object.matrixWorld,camera:i,projectionScreenMatrix:fo.lodProjectionScreenMatrix,desiredDensity:t,canvasHeight:this._context.renderer.domElement.clientHeight||this._context.renderer.domElement.height,currentLevel:e.currentMeshLOD??-1,target:fo.lodSelectionResult}).level:-1}onAfterRender=()=>{this._batchedMesh.layers.disableAll()};validateGeometry(e){const t=this.geometry;for(const i in e.attributes)if(i!=="batchId"&&!t.hasAttribute(i))return E()&&console.warn(`BatchedMesh: Added geometry has extra "${i}" attribute. All geometries must have consistent attributes.`),!1;for(const i in t.attributes)if(i!=="batchId"&&!e.hasAttribute(i))return E()&&console.warn(`BatchedMesh: Added geometry missing "${i}". All geometries must have consistent attributes.`),!1;return!0}markNeedsUpdate(){gt==="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=dr(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(gt){const f=dr(e);console.warn(`[Instancing] Growing Buffer
|
|
1089
1089
|
Mesh: "${this.name}${e.name?.length?"/"+e.name:""}" (${f.vertexCount.toLocaleString()} vertices, ${f.indexCount.toLocaleString()} indices)
|
|
1090
1090
|
Max count ${this._maxInstanceCount.toLocaleString()} → ${o.toLocaleString()}
|
|
@@ -1137,7 +1137,7 @@ Texture:`,i),this.setLightmapDebugMaterial()):qd&&console.log("Use debuglightmap
|
|
|
1137
1137
|
gl_FragColor = lightMapTexel;
|
|
1138
1138
|
gl_FragColor.a = 1.;
|
|
1139
1139
|
}
|
|
1140
|
-
`,defines:{USE_LIGHTMAP:""}})}}var UA=Object.defineProperty,$s=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&UA(e,t,n),n};const Da=x("debugrenderer"),U0=x("debugskinnedmesh"),z0=x("noinstancing"),zA=x("wireframe");var RC=(s=>(s[s.Off=0]="Off",s[s.BlendProbes=1]="BlendProbes",s[s.BlendProbesAndSkybox=2]="BlendProbesAndSkybox",s[s.Simple=3]="Simple",s))(RC||{});class TC{path=null;asset=null;default}class NA{_renderer;_targets=[];_indexMapMaxIndex;_indexMap;_changed=!1;get changed(){return this._changed}set changed(e){e===!0&&Da&&console.warn("SharedMaterials have changed: "+this._renderer.name),this._changed=e}is(e){return this._renderer===e}constructor(e,t){this._renderer=e;const i=this.setMaterial.bind(this),n=this.getMaterial.bind(this),o=e.gameObject;if(this._targets=[],o)switch(o.type){case"Group":this._targets=[...o.children];break;case"SkinnedMesh":case"Mesh":this._targets.push(o);break}let r=!1,a,l=0;for(let h=0;h<this._targets.length;h++){const d=this._targets[h];if(!d)continue;const u=d.material;if(u){u.shadowSide=u.side;for(let f=0;f<t.length;f++){const m=t[f];if(!m){r=!0;continue}if(u.name===m.name){a===void 0&&(a=new Map),a.set(f,h),l=Math.max(l,f);break}}}}if(r){this._indexMapMaxIndex=l,this._indexMap=a;const h=`Renderer ${e.name} was initialized with missing materials - this may lead to unexpected behaviour when trying to access sharedMaterials by index.`;console.warn(h),ki()&&de("Found renderer with missing materials: please check the console for details.")}return new Proxy(this,{get(h,d){if(typeof d=="string"){const u=parseInt(d);if(!isNaN(u))return n(u)}return h[d]},set(h,d,u){return typeof d=="string"&&i(u,Number.parseInt(d)),Reflect.set(h,d,u)?(u instanceof c.Material&&(h.changed=!0),!0):!1}})}get length(){return this._indexMapMaxIndex!==void 0?this._indexMapMaxIndex+1:this._targets.length}*[Symbol.iterator](){for(let e=0;e<this.length;e++)yield this.getMaterial(e)}resolveIndex(e){const t=this._indexMap;return t&&t.has(e)?t.get(e):e}setMaterial(e,t){if(t=this.resolveIndex(t),t<0||t>=this._targets.length)return;const i=this._targets[t];!i||i.material===void 0||(i.material=e,this.changed=!0)}getMaterial(e){if(e=this.resolveIndex(e),e<0)return null;const t=this._targets;if(e>=t.length)return null;const i=t[e];return i?i.material:null}}const us=class Oc extends T{static setInstanced(e,t){const i=Th(e,Oc);return i.enableInstancing=t,i.setInstancingEnabled(t),i}static isInstanced(e){const t=Bs(e,Oc);return t?t.isInstancingActive:Ki.isUsingInstancing(e)}static setVisible(e,t){Qn(e,t)}receiveShadows=!1;shadowCastingMode=0;lightmapIndex=-1;lightmapScaleOffset=new c.Vector4(1,1,0,0);enableInstancing=void 0;renderOrder=void 0;allowOcclusionWhenDynamic=!0;probeAnchor;reflectionProbeUsage=0;_lightmaps;get sharedMesh(){if(this.gameObject.type==="Mesh")return this.gameObject;if(this.gameObject.type==="SkinnesMesh")return this.gameObject;if(this.gameObject.type==="Group")return this.gameObject.children[0]}_sharedMeshes=[];get sharedMeshes(){if(this.destroyed||!this.gameObject)return this._sharedMeshes;if(this._sharedMeshes.length=0,this.isMultiMaterialObject(this.gameObject))for(const e of this.gameObject.children)this.isOwnSubmesh(e)&&this._sharedMeshes.push(e);else this.isMeshOrSkinnedMesh(this.gameObject)&&this._sharedMeshes.push(this.gameObject);return this._sharedMeshes}get sharedMaterial(){return this.sharedMaterials?.[0]}set sharedMaterial(e){this.sharedMaterials[0]!==e&&(this.sharedMaterials[0]=e,this.applyLightmapping())}get material(){return this.sharedMaterials?.[0]}set material(e){this.sharedMaterial=e}_sharedMaterials;_originalMaterials;_probeAnchorLastFrame;set sharedMaterials(e){if(!this._originalMaterials)this._originalMaterials=e;else if(e){let t=!1;for(let i=0;i<this._sharedMaterials.length;i++){const n=i<e.length?e[i]:null;n&&n instanceof c.Material?this.sharedMaterials[i]=n:t||(t=!0,console.warn("Can not assign null as material: "+this.name,n))}}}get sharedMaterials(){if(this._originalMaterials===void 0)if(this.__didAwake)this._originalMaterials=[];else return null;return(!this._sharedMaterials||!this._sharedMaterials.is(this))&&(this._originalMaterials||(this._originalMaterials=[]),this._sharedMaterials=new NA(this,this._originalMaterials)),this._sharedMaterials}static get shouldSuppressInstancing(){return z0}_lightmapTextureOverride=void 0;get lightmap(){return this._lightmaps?.length?this._lightmaps[0].lightmap:null}set lightmap(e){if(this._lightmapTextureOverride=e,e===void 0&&(e=this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex)),this._lightmaps?.length)for(const t of this._lightmaps)t.lightmap=e}get hasLightmap(){const e=this.lightmap;return e!=null}allowProgressiveLoading=!0;_firstFrame=-1;registering(){this.enabled||this.setVisibility(!1)}awake(){if(this._firstFrame=this.context.time.frame,Da&&console.log("Renderer ",this.name,this),this.clearInstancingState(),this.probeAnchor&&Da&&this.probeAnchor.add(new c.AxesHelper(.2)),this._reflectionProbe=null,this.isMultiMaterialObject(this.gameObject)){for(const e of this.gameObject.children)this.context.addBeforeRenderListener(e,this.onBeforeRenderThree),e.layers.mask=this.gameObject.layers.mask;if(this.renderOrder!==void 0){let e=0;for(let t=0;t<this.gameObject.children.length;t++){const i=this.gameObject.children[t];if(!(!this.isMeshOrSkinnedMesh(i)||P.getComponent(i,Oc))){if(this.renderOrder.length<=e){console.warn("Incorrect renderOrder element count",this,this.renderOrder.length+" but expected "+this.gameObject.children.length,"Index: "+e,"ChildElement:",i);continue}i.renderOrder=this.renderOrder[e],e+=1}}}}else this.isMeshOrSkinnedMesh(this.gameObject)?(this.context.addBeforeRenderListener(this.gameObject,this.onBeforeRenderThree),this.renderOrder!==void 0&&this.renderOrder.length>0&&(this.gameObject.renderOrder=this.renderOrder[0])):this.context.addBeforeRenderListener(this.gameObject,this.onBeforeRenderThree);if(this._lightmaps=void 0,this.applyLightmapping(),zA)for(let e=0;e<this.sharedMaterials.length;e++){const t=this.sharedMaterials[e];t&&(t.wireframe=!0)}}applyLightmapping(){if(this.lightmapIndex>=0&&!this._lightmaps){const e=this._lightmapTextureOverride!==void 0?this._lightmapTextureOverride:this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex);if(e){this._lightmaps||(this._lightmaps=[]);const t=new B_(this);t.init(this.lightmapIndex,this.lightmapScaleOffset,e),this._lightmaps.push(t)}else Da&&console.warn(`[Renderer] No lightmaps found ${this.name} (${this.sourceId}, ${this.lightmapIndex})`)}}_isInstancingEnabled=!1;_handles=void 0;get isInstancingActive(){return this._handles!=null&&this._handles.length>0&&this._isInstancingEnabled}get instances(){if(!this._handles||this._handles.length<=0)return null;if(this._handlesTempArray.length=0,this._handles)for(const e of this._handles)this._handlesTempArray.push(e);return this._handlesTempArray}_handlesTempArray=[];setInstancingEnabled(e){if(this._isInstancingEnabled===e){if(!e||this._handles&&this._handles.length>0)return!0}else this._isInstancingEnabled=e;if(e){if(this.enableInstancing===void 0&&(this.enableInstancing=!0),this._handles===void 0||this._handles===null){if(this._handles=jr.instance.setup(this,this.gameObject,this.context,null,{rend:this,foundMeshes:0,useMatrixWorldAutoUpdate:this.useInstanceMatrixWorldAutoUpdate()}),this._handles)return P.markAsInstancedRendered(this.gameObject,!0),!0}else if(this._handles!==null){for(const t of this._handles)t.updateInstanceMatrix(!0),t.add();return P.markAsInstancedRendered(this.gameObject,!0),!0}}else{if(this._handles)for(const t of this._handles)t.remove(this.destroyed);return!0}return!1}clearInstancingState(){this._isInstancingEnabled=!1,this._handles=void 0}useInstanceMatrixWorldAutoUpdate(){return!0}start(){if(this.enableInstancing&&!z0&&(this.setInstancingEnabled(!0),Ki.markDirty(this.gameObject)),this.gameObject.frustumCulled=this.allowOcclusionWhenDynamic,this.isMultiMaterialObject(this.gameObject))for(let e=0;e<this.gameObject.children.length;e++){const t=this.gameObject.children[e];t.frustumCulled=this.allowOcclusionWhenDynamic}}onEnable(){this.sharedMeshes,this.setVisibility(!0),this._isInstancingEnabled||this.enableInstancing==!0||Array.isArray(this.enableInstancing)&&this.enableInstancing.some(t=>t)?this.__internalDidAwakeAndStart&&this.setInstancingEnabled(!0):this.enabled&&this.applyStencil(),this.updateReflectionProbe(),Ps.onEnabled.addEventListener(this.onReflectionProbeEnabled),Ps.onDisabled.addEventListener(this.onReflectionProbeDisabled)}onDisable(){this.setVisibility(!1),Ps.onEnabled.removeEventListener(this.onReflectionProbeEnabled),Ps.onDisabled.removeEventListener(this.onReflectionProbeDisabled),this._handles&&this._handles.length>0&&this.setInstancingEnabled(!1)}onDestroy(){if(this._handles=null,this.isMultiMaterialObject(this.gameObject))for(const e of this.gameObject.children)this.context.removeBeforeRenderListener(e,this.onBeforeRenderThree);else this.context.removeBeforeRenderListener(this.gameObject,this.onBeforeRenderThree)}onReflectionProbeEnabled=()=>{this.updateReflectionProbe()};onReflectionProbeDisabled=e=>{this._reflectionProbe===e&&(this._reflectionProbe.unapply(this.gameObject),this._reflectionProbe=null)};onBeforeRender(){if(this.gameObject){if((this._probeAnchorLastFrame!==this.probeAnchor||this._reflectionProbe?.activeAndEnabled===!1)&&(this._reflectionProbe?.unapply(this.gameObject),this.updateReflectionProbe()),Da==this.name&&this.gameObject instanceof c.Mesh){this.gameObject.geometry.computeBoundingSphere();const e=F(this.gameObject.geometry.boundingSphere.center).applyMatrix4(this.gameObject.matrixWorld);B.DrawWireSphere(e,this.gameObject.geometry.boundingSphere.radius,56831)}if(this.isMultiMaterialObject(this.gameObject)&&this.gameObject.children?.length>0)for(const e of this.gameObject.children)this.applySettings(e);else this.applySettings(this.gameObject);if(this.sharedMaterials?.changed&&(this.sharedMaterials.changed=!1,this.applyLightmapping()),this._handles?.length&&this.gameObject[rh]===!0){this.gameObject[rh]=!1;for(let t=this._handles.length-1;t>=0;t--)this._handles[t].updateInstanceMatrix();this.gameObject.matrixWorldNeedsUpdate=!1}if(this._handles&&this._handles.length<=0&&P.markAsInstancedRendered(this.gameObject,!1),this._isInstancingEnabled&&this._handles)for(let e=0;e<this._handles.length;e++){const t=this._handles[e];Qn(t.object,!1)}if(this.reflectionProbeUsage!==0&&this._reflectionProbe?this._reflectionProbe.apply(this.gameObject):this.reflectionProbeUsage===0&&this._reflectionProbe&&this._reflectionProbe.unapply(this.gameObject),this._sharedMaterials)for(const e of this._sharedMaterials)e&&"envMap"in e&&"envMapIntensity"in e&&!Ps.isUsingReflectionProbe(e)&&(e.envMap=this.context.scene.environment,e.envMapRotation=this.context.scene.environmentRotation);else Da&&console.warn("[Renderer] sharedMaterials not initialized yet: "+this.name)}}onBeforeRenderThree=(e,t,i,n,o,r)=>{if(o.envMapIntensity!==void 0){const a=this.hasLightmap?Math.PI:1,l=this.context.scene.environmentIntensity;o.envMapIntensity=Math.max(0,l*this.context.sceneLighting.environmentIntensity/a)}if(this._lightmaps)for(const a of this._lightmaps)a.updateLightmapUniforms(o),a.applyLightmap()};onAfterRender(){if(this._isInstancingEnabled&&this._handles)for(let e=0;e<this._handles.length;e++){const t=this._handles[e];Qn(t.object,!0)}this._reflectionProbe?.activeAndEnabled===!1&&this._reflectionProbe.unapply(this.gameObject),this.static&&this.gameObject.matrixAutoUpdate&&this.context.time.frame-this._firstFrame>=10&&(this.gameObject.matrixAutoUpdate=!1)}applyStencil(){bo.applyStencil(this)}applySettings(e){e.receiveShadow=this.receiveShadows,this.shadowCastingMode==1?e.castShadow=!0:e.castShadow=!1}_reflectionProbe=null;updateReflectionProbe(){this._reflectionProbe=null,this.reflectionProbeUsage!==0&&(this.startCoroutine(this._updateReflectionProbe(),Ce.LateUpdate),this._probeAnchorLastFrame=this.probeAnchor)}*_updateReflectionProbe(){const e=this.probeAnchor||this.gameObject,t=!!this.probeAnchor;this._reflectionProbe=Ps.get(e,this.context,t,this.probeAnchor)}setVisibility(e){if(!this.isMultiMaterialObject(this.gameObject))Qn(this.gameObject,e);else for(const t of this.gameObject.children)this.isOwnSubmesh(t)&&Qn(t,e)}isMultiMaterialObject(e){return e.type==="Group"}isMeshOrSkinnedMesh(e){return e.type==="Mesh"||e.type==="SkinnedMesh"}isOwnSubmesh(e){return this.isMeshOrSkinnedMesh(e)&&!Bs(e,Oc)}};$s([p()],us.prototype,"receiveShadows");$s([p()],us.prototype,"shadowCastingMode");$s([p()],us.prototype,"lightmapIndex");$s([p(c.Vector4)],us.prototype,"lightmapScaleOffset");$s([p()],us.prototype,"enableInstancing");$s([p()],us.prototype,"renderOrder");$s([p()],us.prototype,"allowOcclusionWhenDynamic");$s([p(c.Object3D)],us.prototype,"probeAnchor");$s([p()],us.prototype,"reflectionProbeUsage");let ti=us;class Vh extends ti{}class F_ extends Vh{_needUpdateBoundingSphere=!1;awake(){super.awake(),U0&&console.log('SkinnedMeshRenderer for "'+this.name+'"',this),this.allowOcclusionWhenDynamic=!1;for(const e of this.sharedMeshes)e.parent?.updateWorldMatrix(!1,!0),this.markBoundsDirty()}onAfterRender(){if(super.onAfterRender(),this._needUpdateBoundingSphere){for(const e of this.sharedMeshes)if(e instanceof c.SkinnedMesh){this._needUpdateBoundingSphere=!1;try{const t=e.geometry,i=re.getRaycastMesh(e);i&&(e.geometry=i),e.computeBoundingSphere(),e.geometry=t}catch(t){console.error(`Error updating bounding sphere for ${e.name}`,t)}}}if(U0){for(const e of this.sharedMeshes)if(e instanceof c.SkinnedMesh&&e.boundingSphere){const t=F(e.boundingSphere.center).applyMatrix4(e.matrixWorld);B.DrawWireSphere(t,e.boundingSphere.radius,"red")}}}markBoundsDirty(){this._needUpdateBoundingSphere=!0}}var gf=(s=>(s[s.Off=0]="Off",s[s.On=1]="On",s[s.TwoSided=2]="TwoSided",s[s.ShadowsOnly=3]="ShadowsOnly",s))(gf||{}),$A=Object.defineProperty,Tl=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&$A(e,t,n),n};const Xt=x("debugdroplistener");class VA extends CustomEvent{constructor(e){super("object-added",{detail:e})}}const WA="blob";class Vs extends T{dropArea;fitIntoVolume=!1;fitVolumeSize=new c.Vector3(1,1,1);placeAtHitPosition=!0;useNetworking=!1;onDropped=new Z;loadFromURL(e,t){return this.addFromUrl(e,{screenposition:new c.Vector2,point:t?.point,size:t?.size},!1)}forgetObjects(){this.removePreviouslyAddedObjects(!1)}awake(){for(const e of this.gameObject.children)this.dropArea&&e.contains(this.dropArea)||this._addedObjects.push(e)}onEnable(){this.context.renderer.domElement.addEventListener("dragover",this.onDrag),this.context.renderer.domElement.addEventListener("drop",this.onDrop),window.addEventListener("paste",this.handlePaste),this.context.connection.beginListen("droplistener",this.onNetworkEvent),E()&&this.dropArea&&(this.dropArea.getComponentInChildren(ti)||console.warn("[DropListener] The assigned DropArea does not seem to have a renderer/mesh. Drag and Drop events will not be detected."))}onDisable(){this.context.renderer.domElement.removeEventListener("dragover",this.onDrag),this.context.renderer.domElement.removeEventListener("drop",this.onDrop),window.removeEventListener("paste",this.handlePaste),this.context.connection.stopListen("droplistener",this.onNetworkEvent)}onNetworkEvent=e=>{if(!this.useNetworking){Xt&&console.debug("[DropListener] Ignoring networked event because networking is disabled",e);return}if(e.guid?.startsWith(this.guid)){const t=e.url;if(console.debug("[DropListener] Received networked event",e),t)if(Array.isArray(t))for(const i of t)this.addFromUrl(i,{screenposition:new c.Vector2,point:e.point,size:e.size},!0);else this.addFromUrl(t,{screenposition:new c.Vector2,point:e.point,size:e.size},!0)}};handlePaste=e=>{if(this.context.connection.allowEditing===!1||e.defaultPrevented)return;navigator.clipboard.readText().then(i=>{if(i&&(i.startsWith("http")||i.startsWith("https")||i.startsWith("blob"))){const o={screenposition:new c.Vector2(this.context.input.mousePosition.x,this.context.input.mousePosition.y)};this.testIfIsInDropArea(o)&&this.addFromUrl(i,o,!1)}}).catch(console.warn)};onDrag=e=>{Xt&&console.debug("DropListener Drag",e,this.context.connection.allowEditing),this.context.connection.allowEditing!==!1&&e.preventDefault()};onDrop=async e=>{if(Xt&&console.debug("DropListener Drop",e,this.context.connection.allowEditing),this.context.connection.allowEditing===!1||!e?.dataTransfer||e["droplistener:handled"])return;e.preventDefault();const t={screenposition:new c.Vector2(e.offsetX,e.offsetY)};if(this.dropArea&&this.testIfIsInDropArea(t)===!1)return;e["droplistener:handled"]=!0;const i=e.dataTransfer.items;if(!i)return;const n=[];for(const o in i){const r=i[o];if(r.kind==="file"){const a=r.getAsFile();if(!a)continue;n.push(a)}else r.kind==="string"&&r.type=="text/plain"&&r.getAsString(a=>{this.addFromUrl(a,t,!1)})}n.length>0&&await this.addFromFiles(n,t)};async addFromUrl(e,t,i){Xt&&console.log("dropped url",e);try{if(e.startsWith("https://github.com/")){const r=e.split("/"),a=r[3],l=r[4],h=r[6],d=r.slice(7).join("/");e=`https://raw.githubusercontent.com/${a}/${l}/${h}/${d}`}else e.startsWith("https://polyhaven.com/a")&&(e=GA(e));if(!e)return null;const n=e.toLowerCase();if(n.endsWith(".hdr")||n.endsWith(".hdri")||n.endsWith(".exr")||n.endsWith(".png")||n.endsWith(".jpg")||n.endsWith(".jpeg"))return console.warn(`Fileformat is not supported: ${n}`),null;this.removePreviouslyAddedObjects();const o=await yf.loadFileFromURL(new URL(e),{guid:this.guid,context:this.context,parent:this.gameObject,point:t.point,size:t.size});if(o&&this._addedObjects.length<=0)return t.url=e,this.onObjectLoaded(o,t,i)}catch{console.warn("String is not a valid URL",e)}return null}_abort=null;async addFromFiles(e,t){if(Xt&&console.log("Add files",e),!!Array.isArray(e)&&e.length){this.deleteDropEvent(),this.removePreviouslyAddedObjects(),Yc(WA,null),this._abort?.abort("New files dropped"),this._abort=new AbortController;for(const i of e){if(!i)continue;if(i.type.startsWith("image/")){Xt&&console.warn("Ignoring dropped image file",i.name,i.type);continue}else if(i.name.endsWith(".bin")){Xt&&console.warn("Ignoring dropped binary file",i.name,i.type);continue}console.debug("Load file "+i.name+" + "+i.type);const n=await yf.loadFile(i,this.context,{guid:this.guid});if(n){this.dispatchEvent(new CustomEvent("file-dropped",{detail:i})),t.file=i;const o=this.onObjectLoaded(n,t,!1);o&&this.context.connection.isConnected&&this.useNetworking&&(console.debug("Uploading dropped file to blob storage"),exports.BlobStorage.upload(i,{abort:this._abort?.signal}).then(r=>{r?.download_url&&this._addedObjects.includes(o)&&this.sendDropEvent(r.download_url,o,n.contentMD5)}).catch(console.warn));break}}}}_addedObjects=new Array;_addedModels=new Array;removePreviouslyAddedObjects(e=!0){if(e)for(const t of this._addedObjects)t.parent===this.gameObject&&t.destroy();this._addedObjects.length=0,this._addedModels.length=0}onObjectLoaded(e,t,i){const{model:n,contentMD5:o}=e;if(Xt&&console.log(`Dropped ${this.gameObject.name}`,n),!n?.scene)return console.warn("No object specified to add to scene",n),null;this.removePreviouslyAddedObjects();const r=n.scene;r.position.copy(this.gameObject.worldPosition);const a=Ve(this.gameObject);let l=new c.Vector3(0,0,0);a.x=Math.abs(a.x),a.y=Math.abs(a.y),a.z=Math.abs(a.z);let h=r.scale.clone();const d=new c.Box3().setFromCenterAndSize(new c.Vector3(0,this.fitVolumeSize.y*a.y*.5,0).add(this.gameObject.worldPosition),this.fitVolumeSize.clone().multiply(a));if(Xt&&B.DrawWireBox3(d,255,5),this.fitIntoVolume&&(Jw(r,d,{position:!this.placeAtHitPosition}),h=r.scale.clone().divide(a),l=r.worldPosition.clone().sub(this.gameObject.worldPosition).divide(a),Xt&&B.DrawSphere(l,.1,16711680,5)),this.gameObject.attach(r),r.position.copy(l),r.quaternion.identity(),r.scale.copy(h),Xt&&B.DrawArrow(this.gameObject.worldPosition,r.getWorldPosition(new c.Vector3),65280,5),this._addedObjects.push(r),this._addedModels.push(n),this.placeAtHitPosition&&t&&t.screenposition){r.visible=!1;const f=this.context.physics.raycast({screenPoint:this.context.input.convertScreenspaceToRaycastSpace(t.screenposition.clone())});if(r.visible=!0,f&&f.length>0)for(const m of f){const g=m.point.clone();Xt&&console.log("Place object at hit",m),ex(r,g);break}}exports.AnimationUtils.autoplayAnimations(n);const u=new VA({sender:this,gltf:n,model:n,object:r,contentMD5:o,dropped:t.file||(t.url?new URL(t.url):void 0)});return this.dispatchEvent(u),this.onDropped?.invoke(u.detail),r&&this.context.events.emit("scene-content-changed",{source:this,object:r}),!i&&t.url?.startsWith("http")&&this.context.connection.isConnected&&r&&this.sendDropEvent(t.url,r,o),r}async sendDropEvent(e,t,i){if(!this.useNetworking){Xt&&console.debug("[DropListener] Ignoring networked event because networking is disabled",e);return}if(this.context.connection.isConnected){console.debug('Sending drop event "'+t.name+'"',e);const n=pi([t]),o={name:t.name,guid:this.guid,url:e,point:t.worldPosition.clone(),size:n.getSize(new c.Vector3),contentMD5:i};this.context.connection.send("droplistener",o)}}deleteDropEvent(){this.context.connection.sendDeleteRemoteState(this.guid)}testIfIsInDropArea(e){const t=this.context.input.convertScreenspaceToRaycastSpace(e.screenposition.clone()),i=this.context.physics.raycast({screenPoint:t,recursive:!0,testObject:o=>!this._addedObjects.some(r=>r.contains(o))});if(!i.length)return E()&&console.log(`Dropped outside of drop area for DropListener "${this.name}".`),!1;const n=i[0];return!!(this.dropArea&&this.dropArea.contains(n.object))}}Tl([p(c.Object3D)],Vs.prototype,"dropArea");Tl([p()],Vs.prototype,"fitIntoVolume");Tl([p(c.Vector3)],Vs.prototype,"fitVolumeSize");Tl([p()],Vs.prototype,"placeAtHitPosition");Tl([p()],Vs.prototype,"useNetworking");Tl([p(Z)],Vs.prototype,"onDropped");function GA(s){if(!s.startsWith("https://polyhaven.com/"))return s;const e="https://dl.polyhaven.org/file/ph-assets/Models/gltf/4k/",n=new URL(s).pathname.split("/").pop(),o=`${e}${n}/${n}_4k.gltf`;return console.log("Resolved polyhaven asset url",s,"→",o),o}var yf;(s=>{async function e(i,n,o){const r=o.guid,a=new ot(r),l=new Blob([i],{type:i.type||T_(i.name)||void 0}),h=URL.createObjectURL(l),d=await Is().loadSync(n,h,i.name,a).catch(u=>(console.error(`Failed to load file "${i.name}" (${i.type}):`,u),null));return URL.revokeObjectURL(h),d?new Promise((u,f)=>{const m=new FileReader;m.readAsArrayBuffer(i),m.onloadend=async g=>{const v=m.result,_=exports.BlobStorage.hashMD5(v);return u({model:d,contentMD5:_})}}):(console.warn(`Failed to load "${i.name}" (${i.type})`),null)}s.loadFile=e;async function t(i,n){const o=new ot(n.guid),r=i.toString();Xt&&B.DrawWireSphere(n.point,.1,16711680,3);const a=exports.PreviewHelper.addPreview({guid:n.guid,parent:n.parent,position:n?.point,size:n?.size});try{const l=await Is().loadSync(n.context,r,r,o,d=>{a.onProgress(d.loaded/d.total)}).catch(d=>(console.warn(d),null));if(!l)return console.warn("Unsupported file type: "+i.toString()),null;let h="";try{const d=await fetch(r).then(u=>u.arrayBuffer());h=exports.BlobStorage.hashMD5(d)}catch(d){console.warn("Failed to compute content hash for "+r,d)}return{model:l,contentMD5:h}}finally{Xt?setTimeout(()=>exports.PreviewHelper.removePreview(n.guid),3e3):exports.PreviewHelper.removePreview(n.guid)}}s.loadFileFromURL=t})(yf||(yf={}));var HA=Object.defineProperty,j_=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&HA(e,t,n),n};const cp=class AC extends T{parent=null;object=null;limitCount=60;_currentCount=0;_startPosition=null;_startQuaternion=null;start(){if(this._currentCount=0,this._startPosition=null,this._startQuaternion=null,this.ensureParentGuid(),this.object||(this.object=this.gameObject),this.object){if(this.object===this.gameObject){const t=new ot(this.guid);this.object=P.instantiate(this.object,{idProvider:t,keepWorldPosition:!1}),P.getComponent(this.object,AC)?.destroy();let n=this.object.getComponentInChildren(vr);n||(n=this.object.addComponent(vr,{dragMode:R_.SnapToSurfaces}),n.guid=t.generateUUID());let o=P.getComponent(n.gameObject,Sn);o||(o=n.gameObject.addComponent(Sn),o.guid=t.generateUUID())}this.object.visible=!1;const e=this.gameObject.getComponent(vr);e&&(e.enabled=!1),this._startPosition=this.object.position?.clone()??new c.Vector3(0,0,0),this._startQuaternion=this.object.quaternion?.clone()??new c.Quaternion(0,0,0,1)}this.gameObject.getComponentInParent(Ji)||this.gameObject.addComponent(Ji)}onEnable(){this.startCoroutine(this.cloneLimitIntervalFn())}_forwardPointerEvents=new Map;onPointerEnter(e){e.used||this.object&&this.context.connection.allowEditing&&e.button===0&&this.context.input.setCursor("pointer")}onPointerExit(e){e.used||this.object&&this.context.connection.allowEditing&&e.button===0&&this.context.input.unsetCursor("pointer")}onPointerDown(e){if(e.used||!this.object||!this.context.connection.allowEditing||e.button!==0)return;const t=this.handleDuplication();if(t){const i=P.getComponent(t,vr);i?(i.onPointerDown(e),this._forwardPointerEvents.set(e.event.space,i)):E()&&console.warn(`Duplicated object (${t.name}) does not have DragControls`)}else this._currentCount>=this.limitCount?console.warn(`[Duplicatable] Limit of ${this.limitCount} objects created within a few seconds reached. Please wait a moment before creating more objects.`):console.warn("[Duplicatable] Could not duplicate object.")}onPointerUp(e){if(e.used)return;const t=this._forwardPointerEvents.get(e.event.space);t&&(t.onPointerUp(e),this._forwardPointerEvents.delete(e.event.space))}ensureParentGuid(){this.parent&&(this.parent.guid||this.parent.userData?.guid||(this.parent.guid=new ot(this.guid+"/parent").generateUUID()))}*cloneLimitIntervalFn(){for(;this.activeAndEnabled&&!this.destroyed;)this._currentCount>0?this._currentCount-=1:this._currentCount<0&&(this._currentCount=0),yield Hy(1)}handleDuplication(){if(!this.object||this.limitCount>0&&this._currentCount>=this.limitCount||this.object===this.gameObject)return null;if(P.isDestroyed(this.object))return this.object=null,null;this.object.matrixAutoUpdate===!1&&(this.object.updateMatrix(),E()&&(console.warn(`Object "${this.object.name}" has matrixAutoUpdate disabled. This can cause duplicated objects to have incorrect position/rotation/scale. Consider enabling matrixAutoUpdate or calling updateMatrix() before duplication.`),de("Duplicatable: Object has matrixAutoUpdate disabled"))),this.object.visible=!0,this._startPosition&&this.object.position.copy(this._startPosition),this._startQuaternion&&this.object.quaternion.copy(this._startQuaternion);const e=new hs;this.parent||(this.parent=this.gameObject.parent),this.ensureParentGuid(),this.parent&&(e.parent=this.parent.guid??this.parent.userData?.guid,e.keepWorldPosition=!0),e.position=this.worldPosition,e.rotation=this.worldQuaternion,e.context=this.context,this._currentCount+=1;const t=P.instantiateSynced(this.object,e);return console.assert(t!==this.object,"Duplicated object is original"),this.object.visible=!1,this._startPosition&&this.object.position.clone().copy(this._startPosition),this._startQuaternion&&this.object.quaternion.clone().copy(this._startQuaternion),t}};j_([p(c.Object3D)],cp.prototype,"parent");j_([p(c.Object3D)],cp.prototype,"object");j_([p()],cp.prototype,"limitCount");let U_=cp;var xs=(s=>(s[s.PointerEnter=0]="PointerEnter",s[s.PointerExit=1]="PointerExit",s[s.PointerDown=2]="PointerDown",s[s.PointerUp=3]="PointerUp",s[s.PointerClick=4]="PointerClick",s))(xs||{}),qA=Object.defineProperty,z_=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&qA(e,t,n),n};class N_{eventID;callback=new Z}z_([p()],N_.prototype,"eventID");z_([p(Z)],N_.prototype,"callback");class hp extends T{triggers=[];invoke(e){if(this.triggers)for(const t of this.triggers)t.eventID===e&&t.callback?.invoke()}hasTrigger(e){return this.triggers?.some(t=>t.eventID===e)??!1}shouldChangeCursor(){return this.hasTrigger(xs.PointerClick)||this.hasTrigger(xs.PointerDown)||this.hasTrigger(xs.PointerUp)}onPointerClick(e){this.invoke(xs.PointerClick)}onPointerEnter(e){this.shouldChangeCursor()&&this.context.input.setCursor("pointer"),this.invoke(xs.PointerEnter)}onPointerExit(e){this.shouldChangeCursor()&&this.context.input.unsetCursor("pointer"),this.invoke(xs.PointerExit)}onPointerDown(e){this.invoke(xs.PointerDown)}onPointerUp(e){this.invoke(xs.PointerUp)}}z_([p(N_)],hp.prototype,"triggers");class DC{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(e.constructor.name!=="InstancedMesh")return;const i=this.writer,n=i.extensionsUsed,o={};t.extensions=t.extensions||{},t.extensions[this.name]=o;let r=new c.Matrix4;const a=new Array,l=new Array,h=new Array;for(let m=0;m<e.count;m++){e.getMatrixAt(m,r);let g=new c.Vector3,v=new c.Quaternion,_=new c.Vector3;r.decompose(g,v,_),a.push(g.x,g.y,g.z),l.push(v.x,v.y,v.z,v.w),h.push(_.x,_.y,_.z)}const d=new Float32Array(a),u=new Float32Array(l),f=new Float32Array(h);o.attributes={TRANSLATION:i.processAccessor(new c.BufferAttribute(d,3)),ROTATION:i.processAccessor(new c.BufferAttribute(u,4)),SCALE:i.processAccessor(new c.BufferAttribute(f,3))},n[this.name]=!0}}class IC{writer;constructor(e){this.writer=e}writeNode(e){}}class XA extends IC{beforeWriteNode(e,t){B.isGizmo(e)&&(t.keep=!1)}}class LC extends IC{beforeWriteTexture(e,t){e.isRenderTargetTexture&&(t.newTexture=Yy(new oe(1,1,1,0)))}}function BC(s){const e=as.DontExport;return!(s.hideFlags&e)}function FC(s){return jC(s)}function jC(s,e=[]){let t=0;for(let i=0;i<s.children.length;t++){const n=s.children[i];if(!BC(n)){s.children.splice(i,1),n.parent=null;const o=t;e.push(()=>QA(n,s,o));continue}jC(n,e),i++}return e}function QA(s,e,t){s.parent=e,e.children.splice(Math.min(t,e.children.length),0,s)}var YA=Object.defineProperty,UC=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&YA(e,t,n),n};const Xd=x("debuggltfexport");class $_ extends At{sceneRoot}const V_=class Ia extends T{binary=!0;objects=[];ext;async exportNow(e,t){Xd&&console.log("Exporting objects as glTF",this.objects),e||(e="scene"),(!this.objects||this.objects.length<=0)&&(this.objects=[this.context.scene]);const i={binary:this.binary,pivot:Ia.calculateCenter(this.objects),...t},n=await this.export(this.objects,i).catch(o=>(console.error(o),!1));return n===!1?!1:(this.binary?e.endsWith(".glb")||(e+=".glb"):e.endsWith(".gltf")||(e+=".gltf"),this.binary?Ia.saveArrayBuffer(n,e):Ia.saveJson(n,e),!0)}async export(e,t){if(!e||e.length<=0){console.warn("No objects set to export");return}const i=new V.GLTFExporter;i.register(d=>new DC(d)),i.register(d=>new LC(d)),L_(i,this.context),Ia.filterTopmostParent(e);const n={trs:!1,onlyVisible:!0,truncateDrawRange:!1,binary:!0,maxTextureSize:1/0,embedImages:!0,includeCustomExtensions:!0,animations:t?.animations||Ia.collectAnimations(e),...t},o=new Array,r=new c.Object3D;t?.pivot&&r.position.sub(t.pivot),Xd&&console.log("EXPORT",e),e.forEach(d=>{d&&BC(d)&&(r.children.push(d),d.matrixAutoUpdate=!1,d.matrix.copy(d.matrixWorld),P.getComponentsInChildren(d,ti).forEach(u=>{P.isActiveInHierarchy(u.gameObject)&&u.setInstancingEnabled(!1)}),o.push(...FC(d)))});const a=new Eh(r);return t?.needleComponents&&(this.ext=new D_),this.ext&&(this.ext.registerExport(i),this.ext.context=a),new Promise((d,u)=>{Xd&&console.log("Starting glTF export.");try{i?.parse(r,f=>{l(),d(f)},f=>{l(),u(f)},n)}catch(f){console.error(f),l(),u(f)}finally{Xd&&console.log("Finished glTF export.")}});function l(){o.forEach(d=>d()),o.length=0,h()}function h(){e.forEach(d=>{d&&(d.matrixAutoUpdate=!0,P.getComponentsInChildren(d,ti).forEach(u=>{P.isActiveInHierarchy(u.gameObject)&&u.setInstancingEnabled(!1)}))})}}static saveArrayBuffer(e,t){this.save(new Blob([e],{type:"application/octet-stream"}),t)}static saveJson(e,t){this.save("data: text/json;charset=utf-8,"+encodeURIComponent(JSON.stringify(e)),t)}static save(e,t){const i=document.createElement("a");i.style.display="none",document.body.appendChild(i),typeof e=="string"?i.href=e:i.href=URL.createObjectURL(e),i.download=t,i.click(),i.remove()}static collectAnimations(e,t){t=t||[];for(const i of e)i&&i.traverseVisible(n=>{n.animations&&n.animations.length>0&&t.push(...n.animations)});return t}static calculateCenter(e,t){const i=t||new c.Vector3;return i.set(0,0,0),e.forEach(n=>{i.add(ie(n))}),i.divideScalar(e.length),i}static filterTopmostParent(e){if(!(e.length<=0))for(let t=0;t<e.length;t++){let i=e[t];if(!i){e.splice(t,1),t--;continue}for(;i.parent;){if(e.includes(i.parent)){e.splice(t,1),t--;break}i=i.parent}}}};UC([p()],V_.prototype,"binary");UC([p(c.Object3D)],V_.prototype,"objects");let W_=V_;function KA(){typeof globalThis!==void 0&&!("OffscreenCanvas"in globalThis)&&(globalThis.OffscreenCanvas=class{canvas;constructor(e,t){return this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=t,this.canvas.convertToBlob=(i,n)=>new Promise(o=>{this.canvas.toBlob(o,i,n)}),this.canvas}})}const ZA=x("debugprogress");function zC(s){s=s||new Date;const e=s.getMonth()+1,t=s.getDate(),i=s.getHours(),n=s.getMinutes(),o=s.getSeconds(),r=(e<10?"0":"")+e,a=(t<10?"0":"")+t,l=(i<10?"0":"")+i,h=(n<10?"0":"")+n,d=(o<10?"0":"")+o;return s.getFullYear()+r+a+"-"+l+h+d}class he{static start(e,t){typeof t=="string"&&(t={parentScope:t});const i=new JA(e,t);Ec.set(e,i)}static report(e,t){const i=Ec.get(e);if(!i){console.warn("Reporting progress for non-existing scope",e);return}typeof t=="string"&&(t={message:t,autoStep:!0}),i.report(t)}static end(e){const t=Ec.get(e);t&&(t.end(),Ec.delete(e))}}const Ec=new Map;class JA{scopeLabel;parentScope;childScopes=[];parentDepth=0;lastStep=0;lastAutoStepWeight=1;lastTotalSteps=0;onProgress;showLogs=!1;selfProgress=0;totalProgress=0;selfReports=0;totalReports=0;constructor(e,t){this.parentScope=t?.parentScope?Ec.get(t.parentScope):void 0,this.parentScope&&(this.parentScope.childScopes.push(this),this.parentDepth=this.parentScope.parentDepth+1),this.scopeLabel=" ".repeat(this.parentDepth*2)+e,this.showLogs=t?.logTimings??!!ZA,this.showLogs&&console.time(this.scopeLabel),this.onProgress=t?.onProgress}report(e,t=!1){if(e){if(e.totalSteps!==void 0&&(this.lastTotalSteps=e.totalSteps),e.currentStep!==void 0&&(this.lastStep=e.currentStep),e.autoStep!==void 0){if(e.currentStep===void 0){this.lastStep===void 0&&(this.lastStep=0);const n=typeof e.autoStep=="number"?e.autoStep:1;this.lastStep+=this.lastAutoStepWeight,this.lastAutoStepWeight=n,e.currentStep=this.lastStep}e.totalSteps=this.lastTotalSteps}e.progress!==void 0?this.selfProgress=e.progress:e.currentStep!==void 0&&e.totalSteps!==void 0&&(this.selfProgress=e.currentStep/e.totalSteps)}if(this.childScopes.length>0){let n=0,o=0;for(const a of this.childScopes)n+=a.selfProgress,o+=1;o>0&&(n/=o);const r=this.lastAutoStepWeight/(this.lastTotalSteps??1);this.totalProgress=this.selfProgress+n*r}else this.totalProgress=this.selfProgress;this.selfProgress=Math.min(1,this.selfProgress),this.totalProgress=Math.min(1,this.totalProgress);let i=(this.totalProgress*100).toFixed(3)+"%";this.childScopes.length>0&&(i+=" ("+(this.selfProgress*100).toFixed(3)+"% self)"),e?.message&&(i=e.message+" – "+i),this.lastStep!==void 0&&this.lastTotalSteps!==void 0&&(i="Step "+(this.lastStep+(this.lastAutoStepWeight!=1?"–"+(this.lastStep+this.lastAutoStepWeight):"")+"/"+this.lastTotalSteps)+" "+i),t?this.totalReports++:(this.selfReports++,this.totalReports++),this.showLogs&&console.timeLog(this.scopeLabel,i),this.onProgress&&this.onProgress(this.totalProgress),this.parentScope&&this.parentScope.report(void 0,!0)}end(){this.report({progress:1,autoStep:!0},!0),this.showLogs&&(console.timeLog(this.scopeLabel,"Total reports: "+this.totalReports,"Self reports: "+this.selfReports),console.timeEnd(this.scopeLabel));let e=!1;for(const t of this.childScopes)if(!(t.selfProgress>=1)){e=!0;break}e&&console.warn("Progress end with child scopes that are still running",this),this.onProgress=void 0}}const Le="</StageRoot/Materials";function eD(s,e,t){const i=new Map,n=v=>{const _=v.type___needle,y=i.get(_)||new Map;if(i.set(_,y),!y.has(v)){const b=`${_}${y.size?`_${y.size}`:""}`;y.set(v,b)}return y.get(v)},o=s.colorNode?Qd(s.colorNode):[],r=s.colorNode?`color3f inputs:diffuseColor.connect = ${Le}/${e}/${n(o.values().next().value)}.outputs:out>`:"",a=s.roughnessNode?Qd(s.roughnessNode):[],l=s.roughnessNode?`float inputs:roughness.connect = ${Le}/${e}/${n(a.values().next().value)}.outputs:out>`:"",h=s.normalNode?Qd(s.normalNode):[],d=s.normalNode?`float3 inputs:normal.connect = ${Le}/${e}/${n(h.values().next().value)}.outputs:out>`:"",u=s.metalnessNode?Qd(s.metalnessNode):[],f=s.metalnessNode?`float inputs:metallic.connect = ${Le}/${e}/${n(u.values().next().value)}.outputs:out>`:"",m=new Set([...o,...a,...h,...u]),g=nD(m,e,t,n);return console.debug(g),`
|
|
1140
|
+
`,defines:{USE_LIGHTMAP:""}})}}var UA=Object.defineProperty,$s=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&UA(e,t,n),n};const Da=x("debugrenderer"),U0=x("debugskinnedmesh"),z0=x("noinstancing"),zA=x("wireframe");var RC=(s=>(s[s.Off=0]="Off",s[s.BlendProbes=1]="BlendProbes",s[s.BlendProbesAndSkybox=2]="BlendProbesAndSkybox",s[s.Simple=3]="Simple",s))(RC||{});class TC{path=null;asset=null;default}class NA{_renderer;_targets=[];_indexMapMaxIndex;_indexMap;_changed=!1;get changed(){return this._changed}set changed(e){e===!0&&Da&&console.warn("SharedMaterials have changed: "+this._renderer.name),this._changed=e}is(e){return this._renderer===e}constructor(e,t){this._renderer=e;const i=this.setMaterial.bind(this),n=this.getMaterial.bind(this),o=e.gameObject;if(this._targets=[],o)switch(o.type){case"Group":this._targets=[...o.children];break;case"SkinnedMesh":case"Mesh":this._targets.push(o);break}let r=!1,a,l=0;for(let h=0;h<this._targets.length;h++){const d=this._targets[h];if(!d)continue;const u=d.material;if(u){u.shadowSide=u.side;for(let f=0;f<t.length;f++){const m=t[f];if(!m){r=!0;continue}if(u.name===m.name){a===void 0&&(a=new Map),a.set(f,h),l=Math.max(l,f);break}}}}if(r){this._indexMapMaxIndex=l,this._indexMap=a;const h=`Renderer ${e.name} was initialized with missing materials - this may lead to unexpected behaviour when trying to access sharedMaterials by index.`;console.warn(h),ki()&&de("Found renderer with missing materials: please check the console for details.")}return new Proxy(this,{get(h,d){if(typeof d=="string"){const u=parseInt(d);if(!isNaN(u))return n(u)}return h[d]},set(h,d,u){return typeof d=="string"&&i(u,Number.parseInt(d)),Reflect.set(h,d,u)?(u instanceof c.Material&&(h.changed=!0),!0):!1}})}get length(){return this._indexMapMaxIndex!==void 0?this._indexMapMaxIndex+1:this._targets.length}*[Symbol.iterator](){for(let e=0;e<this.length;e++)yield this.getMaterial(e)}resolveIndex(e){const t=this._indexMap;return t&&t.has(e)?t.get(e):e}setMaterial(e,t){if(t=this.resolveIndex(t),t<0||t>=this._targets.length)return;const i=this._targets[t];!i||i.material===void 0||(i.material=e,this.changed=!0)}getMaterial(e){if(e=this.resolveIndex(e),e<0)return null;const t=this._targets;if(e>=t.length)return null;const i=t[e];return i?i.material:null}}const us=class Oc extends T{static setInstanced(e,t){const i=Th(e,Oc);return i.enableInstancing=t,i.setInstancingEnabled(t),i}static isInstanced(e){const t=Bs(e,Oc);return t?t.isInstancingActive:Ki.isUsingInstancing(e)}static setVisible(e,t){Qn(e,t)}receiveShadows=!1;shadowCastingMode=0;lightmapIndex=-1;lightmapScaleOffset=new c.Vector4(1,1,0,0);enableInstancing=void 0;renderOrder=void 0;allowOcclusionWhenDynamic=!0;probeAnchor;reflectionProbeUsage=0;_lightmaps;get sharedMesh(){return this.sharedMeshes[0]}_sharedMeshes=[];get sharedMeshes(){if(this.destroyed||!this.gameObject)return this._sharedMeshes;if(this._sharedMeshes.length=0,this.isMultiMaterialObject(this.gameObject))for(const e of this.gameObject.children)this.isOwnSubmesh(e)&&this._sharedMeshes.push(e);else this.isMeshOrSkinnedMesh(this.gameObject)&&this._sharedMeshes.push(this.gameObject);return this._sharedMeshes}get sharedMaterial(){return this.sharedMaterials?.[0]}set sharedMaterial(e){this.sharedMaterials[0]!==e&&(this.sharedMaterials[0]=e,this.applyLightmapping())}get material(){return this.sharedMaterials?.[0]}set material(e){this.sharedMaterial=e}_sharedMaterials;_originalMaterials;_probeAnchorLastFrame;set sharedMaterials(e){if(!this._originalMaterials)this._originalMaterials=e;else if(e){let t=!1;for(let i=0;i<this._sharedMaterials.length;i++){const n=i<e.length?e[i]:null;n&&n instanceof c.Material?this.sharedMaterials[i]=n:t||(t=!0,console.warn("Can not assign null as material: "+this.name,n))}}}get sharedMaterials(){if(this._originalMaterials===void 0)if(this.__didAwake)this._originalMaterials=[];else return null;return(!this._sharedMaterials||!this._sharedMaterials.is(this))&&(this._originalMaterials||(this._originalMaterials=[]),this._sharedMaterials=new NA(this,this._originalMaterials)),this._sharedMaterials}static get shouldSuppressInstancing(){return z0}_lightmapTextureOverride=void 0;get lightmap(){return this._lightmaps?.length?this._lightmaps[0].lightmap:null}set lightmap(e){if(this._lightmapTextureOverride=e,e===void 0&&(e=this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex)),this._lightmaps?.length)for(const t of this._lightmaps)t.lightmap=e}get hasLightmap(){const e=this.lightmap;return e!=null}allowProgressiveLoading=!0;_firstFrame=-1;registering(){this.enabled||this.setVisibility(!1)}awake(){if(this._firstFrame=this.context.time.frame,Da&&console.log("Renderer ",this.name,this),this.clearInstancingState(),this.probeAnchor&&Da&&this.probeAnchor.add(new c.AxesHelper(.2)),this._reflectionProbe=null,this.isMultiMaterialObject(this.gameObject)){for(const e of this.gameObject.children)this.context.addBeforeRenderListener(e,this.onBeforeRenderThree),e.layers.mask=this.gameObject.layers.mask;if(this.renderOrder!==void 0){let e=0;for(let t=0;t<this.gameObject.children.length;t++){const i=this.gameObject.children[t];if(!(!this.isMeshOrSkinnedMesh(i)||P.getComponent(i,Oc))){if(this.renderOrder.length<=e){console.warn("Incorrect renderOrder element count",this,this.renderOrder.length+" but expected "+this.gameObject.children.length,"Index: "+e,"ChildElement:",i);continue}i.renderOrder=this.renderOrder[e],e+=1}}}}else this.isMeshOrSkinnedMesh(this.gameObject)?(this.context.addBeforeRenderListener(this.gameObject,this.onBeforeRenderThree),this.renderOrder!==void 0&&this.renderOrder.length>0&&(this.gameObject.renderOrder=this.renderOrder[0])):this.context.addBeforeRenderListener(this.gameObject,this.onBeforeRenderThree);if(this._lightmaps=void 0,this.applyLightmapping(),zA)for(let e=0;e<this.sharedMaterials.length;e++){const t=this.sharedMaterials[e];t&&(t.wireframe=!0)}}applyLightmapping(){if(this.lightmapIndex>=0&&!this._lightmaps){const e=this._lightmapTextureOverride!==void 0?this._lightmapTextureOverride:this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex);if(e){this._lightmaps||(this._lightmaps=[]);const t=new B_(this);t.init(this.lightmapIndex,this.lightmapScaleOffset,e),this._lightmaps.push(t)}else Da&&console.warn(`[Renderer] No lightmaps found ${this.name} (${this.sourceId}, ${this.lightmapIndex})`)}}_isInstancingEnabled=!1;_handles=void 0;get isInstancingActive(){return this._handles!=null&&this._handles.length>0&&this._isInstancingEnabled}get instances(){if(!this._handles||this._handles.length<=0)return null;if(this._handlesTempArray.length=0,this._handles)for(const e of this._handles)this._handlesTempArray.push(e);return this._handlesTempArray}_handlesTempArray=[];setInstancingEnabled(e){if(this._isInstancingEnabled===e){if(!e||this._handles&&this._handles.length>0)return!0}else this._isInstancingEnabled=e;if(e){if(this.enableInstancing===void 0&&(this.enableInstancing=!0),this._handles===void 0||this._handles===null){if(this._handles=jr.instance.setup(this,this.gameObject,this.context,null,{rend:this,foundMeshes:0,useMatrixWorldAutoUpdate:this.useInstanceMatrixWorldAutoUpdate()}),this._handles)return P.markAsInstancedRendered(this.gameObject,!0),!0}else if(this._handles!==null){for(const t of this._handles)t.updateInstanceMatrix(!0),t.add();return P.markAsInstancedRendered(this.gameObject,!0),!0}}else{if(this._handles)for(const t of this._handles)t.remove(this.destroyed);return!0}return!1}clearInstancingState(){this._isInstancingEnabled=!1,this._handles=void 0}useInstanceMatrixWorldAutoUpdate(){return!0}start(){if(this.enableInstancing&&!z0&&(this.setInstancingEnabled(!0),Ki.markDirty(this.gameObject)),this.gameObject.frustumCulled=this.allowOcclusionWhenDynamic,this.isMultiMaterialObject(this.gameObject))for(let e=0;e<this.gameObject.children.length;e++){const t=this.gameObject.children[e];t.frustumCulled=this.allowOcclusionWhenDynamic}}onEnable(){this.sharedMeshes,this.setVisibility(!0),this._isInstancingEnabled||this.enableInstancing==!0||Array.isArray(this.enableInstancing)&&this.enableInstancing.some(t=>t)?this.__internalDidAwakeAndStart&&this.setInstancingEnabled(!0):this.enabled&&this.applyStencil(),this.updateReflectionProbe(),Ps.onEnabled.addEventListener(this.onReflectionProbeEnabled),Ps.onDisabled.addEventListener(this.onReflectionProbeDisabled)}onDisable(){this.setVisibility(!1),Ps.onEnabled.removeEventListener(this.onReflectionProbeEnabled),Ps.onDisabled.removeEventListener(this.onReflectionProbeDisabled),this._handles&&this._handles.length>0&&this.setInstancingEnabled(!1)}onDestroy(){if(this._handles=null,this.isMultiMaterialObject(this.gameObject))for(const e of this.gameObject.children)this.context.removeBeforeRenderListener(e,this.onBeforeRenderThree);else this.context.removeBeforeRenderListener(this.gameObject,this.onBeforeRenderThree)}onReflectionProbeEnabled=()=>{this.updateReflectionProbe()};onReflectionProbeDisabled=e=>{this._reflectionProbe===e&&(this._reflectionProbe.unapply(this.gameObject),this._reflectionProbe=null)};onBeforeRender(){if(this.gameObject){if((this._probeAnchorLastFrame!==this.probeAnchor||this._reflectionProbe?.activeAndEnabled===!1)&&(this._reflectionProbe?.unapply(this.gameObject),this.updateReflectionProbe()),Da==this.name&&this.gameObject instanceof c.Mesh){this.gameObject.geometry.computeBoundingSphere();const e=F(this.gameObject.geometry.boundingSphere.center).applyMatrix4(this.gameObject.matrixWorld);B.DrawWireSphere(e,this.gameObject.geometry.boundingSphere.radius,56831)}if(this.isMultiMaterialObject(this.gameObject)&&this.gameObject.children?.length>0)for(const e of this.gameObject.children)this.applySettings(e);else this.applySettings(this.gameObject);if(this.sharedMaterials?.changed&&(this.sharedMaterials.changed=!1,this.applyLightmapping()),this._handles?.length&&this.gameObject[rh]===!0){this.gameObject[rh]=!1;for(let t=this._handles.length-1;t>=0;t--)this._handles[t].updateInstanceMatrix();this.gameObject.matrixWorldNeedsUpdate=!1}if(this._handles&&this._handles.length<=0&&P.markAsInstancedRendered(this.gameObject,!1),this._isInstancingEnabled&&this._handles)for(let e=0;e<this._handles.length;e++){const t=this._handles[e];Qn(t.object,!1)}if(this.reflectionProbeUsage!==0&&this._reflectionProbe?this._reflectionProbe.apply(this.gameObject):this.reflectionProbeUsage===0&&this._reflectionProbe&&this._reflectionProbe.unapply(this.gameObject),this._sharedMaterials)for(const e of this._sharedMaterials)e&&"envMap"in e&&"envMapIntensity"in e&&!Ps.isUsingReflectionProbe(e)&&(e.envMap=this.context.scene.environment,e.envMapRotation=this.context.scene.environmentRotation);else Da&&console.warn("[Renderer] sharedMaterials not initialized yet: "+this.name)}}onBeforeRenderThree=(e,t,i,n,o,r)=>{if(o.envMapIntensity!==void 0){const a=this.hasLightmap?Math.PI:1,l=this.context.scene.environmentIntensity;o.envMapIntensity=Math.max(0,l*this.context.sceneLighting.environmentIntensity/a)}if(this._lightmaps)for(const a of this._lightmaps)a.updateLightmapUniforms(o),a.applyLightmap()};onAfterRender(){if(this._isInstancingEnabled&&this._handles)for(let e=0;e<this._handles.length;e++){const t=this._handles[e];Qn(t.object,!0)}this._reflectionProbe?.activeAndEnabled===!1&&this._reflectionProbe.unapply(this.gameObject),this.static&&this.gameObject.matrixAutoUpdate&&this.context.time.frame-this._firstFrame>=10&&(this.gameObject.matrixAutoUpdate=!1)}applyStencil(){bo.applyStencil(this)}applySettings(e){e.receiveShadow=this.receiveShadows,this.shadowCastingMode==1?e.castShadow=!0:e.castShadow=!1}_reflectionProbe=null;updateReflectionProbe(){this._reflectionProbe=null,this.reflectionProbeUsage!==0&&(this.startCoroutine(this._updateReflectionProbe(),Ce.LateUpdate),this._probeAnchorLastFrame=this.probeAnchor)}*_updateReflectionProbe(){const e=this.probeAnchor||this.gameObject,t=!!this.probeAnchor;this._reflectionProbe=Ps.get(e,this.context,t,this.probeAnchor)}setVisibility(e){if(!this.isMultiMaterialObject(this.gameObject))Qn(this.gameObject,e);else for(const t of this.gameObject.children)this.isOwnSubmesh(t)&&Qn(t,e)}isMultiMaterialObject(e){return e.type==="Group"}isMeshOrSkinnedMesh(e){return e.type==="Mesh"||e.type==="SkinnedMesh"}isOwnSubmesh(e){return this.isMeshOrSkinnedMesh(e)&&!Bs(e,Oc)}};$s([p()],us.prototype,"receiveShadows");$s([p()],us.prototype,"shadowCastingMode");$s([p()],us.prototype,"lightmapIndex");$s([p(c.Vector4)],us.prototype,"lightmapScaleOffset");$s([p()],us.prototype,"enableInstancing");$s([p()],us.prototype,"renderOrder");$s([p()],us.prototype,"allowOcclusionWhenDynamic");$s([p(c.Object3D)],us.prototype,"probeAnchor");$s([p()],us.prototype,"reflectionProbeUsage");let ti=us;class Vh extends ti{}class F_ extends Vh{_needUpdateBoundingSphere=!1;awake(){super.awake(),U0&&console.log('SkinnedMeshRenderer for "'+this.name+'"',this),this.allowOcclusionWhenDynamic=!1;for(const e of this.sharedMeshes)e.parent?.updateWorldMatrix(!1,!0),this.markBoundsDirty()}onAfterRender(){if(super.onAfterRender(),this._needUpdateBoundingSphere){for(const e of this.sharedMeshes)if(e instanceof c.SkinnedMesh){this._needUpdateBoundingSphere=!1;try{const t=e.geometry,i=re.getRaycastMesh(e);i&&(e.geometry=i),e.computeBoundingSphere(),e.geometry=t}catch(t){console.error(`Error updating bounding sphere for ${e.name}`,t)}}}if(U0){for(const e of this.sharedMeshes)if(e instanceof c.SkinnedMesh&&e.boundingSphere){const t=F(e.boundingSphere.center).applyMatrix4(e.matrixWorld);B.DrawWireSphere(t,e.boundingSphere.radius,"red")}}}markBoundsDirty(){this._needUpdateBoundingSphere=!0}}var gf=(s=>(s[s.Off=0]="Off",s[s.On=1]="On",s[s.TwoSided=2]="TwoSided",s[s.ShadowsOnly=3]="ShadowsOnly",s))(gf||{}),$A=Object.defineProperty,Tl=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&$A(e,t,n),n};const Xt=x("debugdroplistener");class VA extends CustomEvent{constructor(e){super("object-added",{detail:e})}}const WA="blob";class Vs extends T{dropArea;fitIntoVolume=!1;fitVolumeSize=new c.Vector3(1,1,1);placeAtHitPosition=!0;useNetworking=!1;onDropped=new Z;loadFromURL(e,t){return this.addFromUrl(e,{screenposition:new c.Vector2,point:t?.point,size:t?.size},!1)}forgetObjects(){this.removePreviouslyAddedObjects(!1)}awake(){for(const e of this.gameObject.children)this.dropArea&&e.contains(this.dropArea)||this._addedObjects.push(e)}onEnable(){this.context.renderer.domElement.addEventListener("dragover",this.onDrag),this.context.renderer.domElement.addEventListener("drop",this.onDrop),window.addEventListener("paste",this.handlePaste),this.context.connection.beginListen("droplistener",this.onNetworkEvent),E()&&this.dropArea&&(this.dropArea.getComponentInChildren(ti)||console.warn("[DropListener] The assigned DropArea does not seem to have a renderer/mesh. Drag and Drop events will not be detected."))}onDisable(){this.context.renderer.domElement.removeEventListener("dragover",this.onDrag),this.context.renderer.domElement.removeEventListener("drop",this.onDrop),window.removeEventListener("paste",this.handlePaste),this.context.connection.stopListen("droplistener",this.onNetworkEvent)}onNetworkEvent=e=>{if(!this.useNetworking){Xt&&console.debug("[DropListener] Ignoring networked event because networking is disabled",e);return}if(e.guid?.startsWith(this.guid)){const t=e.url;if(console.debug("[DropListener] Received networked event",e),t)if(Array.isArray(t))for(const i of t)this.addFromUrl(i,{screenposition:new c.Vector2,point:e.point,size:e.size},!0);else this.addFromUrl(t,{screenposition:new c.Vector2,point:e.point,size:e.size},!0)}};handlePaste=e=>{if(this.context.connection.allowEditing===!1||e.defaultPrevented)return;navigator.clipboard.readText().then(i=>{if(i&&(i.startsWith("http")||i.startsWith("https")||i.startsWith("blob"))){const o={screenposition:new c.Vector2(this.context.input.mousePosition.x,this.context.input.mousePosition.y)};this.testIfIsInDropArea(o)&&this.addFromUrl(i,o,!1)}}).catch(console.warn)};onDrag=e=>{Xt&&console.debug("DropListener Drag",e,this.context.connection.allowEditing),this.context.connection.allowEditing!==!1&&e.preventDefault()};onDrop=async e=>{if(Xt&&console.debug("DropListener Drop",e,this.context.connection.allowEditing),this.context.connection.allowEditing===!1||!e?.dataTransfer||e["droplistener:handled"])return;e.preventDefault();const t={screenposition:new c.Vector2(e.offsetX,e.offsetY)};if(this.dropArea&&this.testIfIsInDropArea(t)===!1)return;e["droplistener:handled"]=!0;const i=e.dataTransfer.items;if(!i)return;const n=[];for(const o in i){const r=i[o];if(r.kind==="file"){const a=r.getAsFile();if(!a)continue;n.push(a)}else r.kind==="string"&&r.type=="text/plain"&&r.getAsString(a=>{this.addFromUrl(a,t,!1)})}n.length>0&&await this.addFromFiles(n,t)};async addFromUrl(e,t,i){Xt&&console.log("dropped url",e);try{if(e.startsWith("https://github.com/")){const r=e.split("/"),a=r[3],l=r[4],h=r[6],d=r.slice(7).join("/");e=`https://raw.githubusercontent.com/${a}/${l}/${h}/${d}`}else e.startsWith("https://polyhaven.com/a")&&(e=GA(e));if(!e)return null;const n=e.toLowerCase();if(n.endsWith(".hdr")||n.endsWith(".hdri")||n.endsWith(".exr")||n.endsWith(".png")||n.endsWith(".jpg")||n.endsWith(".jpeg"))return console.warn(`Fileformat is not supported: ${n}`),null;this.removePreviouslyAddedObjects();const o=await yf.loadFileFromURL(new URL(e),{guid:this.guid,context:this.context,parent:this.gameObject,point:t.point,size:t.size});if(o&&this._addedObjects.length<=0)return t.url=e,this.onObjectLoaded(o,t,i)}catch{console.warn("String is not a valid URL",e)}return null}_abort=null;async addFromFiles(e,t){if(Xt&&console.log("Add files",e),!!Array.isArray(e)&&e.length){this.deleteDropEvent(),this.removePreviouslyAddedObjects(),Yc(WA,null),this._abort?.abort("New files dropped"),this._abort=new AbortController;for(const i of e){if(!i)continue;if(i.type.startsWith("image/")){Xt&&console.warn("Ignoring dropped image file",i.name,i.type);continue}else if(i.name.endsWith(".bin")){Xt&&console.warn("Ignoring dropped binary file",i.name,i.type);continue}console.debug("Load file "+i.name+" + "+i.type);const n=await yf.loadFile(i,this.context,{guid:this.guid});if(n){this.dispatchEvent(new CustomEvent("file-dropped",{detail:i})),t.file=i;const o=this.onObjectLoaded(n,t,!1);o&&this.context.connection.isConnected&&this.useNetworking&&(console.debug("Uploading dropped file to blob storage"),exports.BlobStorage.upload(i,{abort:this._abort?.signal}).then(r=>{r?.download_url&&this._addedObjects.includes(o)&&this.sendDropEvent(r.download_url,o,n.contentMD5)}).catch(console.warn));break}}}}_addedObjects=new Array;_addedModels=new Array;removePreviouslyAddedObjects(e=!0){if(e)for(const t of this._addedObjects)t.parent===this.gameObject&&t.destroy();this._addedObjects.length=0,this._addedModels.length=0}onObjectLoaded(e,t,i){const{model:n,contentMD5:o}=e;if(Xt&&console.log(`Dropped ${this.gameObject.name}`,n),!n?.scene)return console.warn("No object specified to add to scene",n),null;this.removePreviouslyAddedObjects();const r=n.scene;r.position.copy(this.gameObject.worldPosition);const a=Ve(this.gameObject);let l=new c.Vector3(0,0,0);a.x=Math.abs(a.x),a.y=Math.abs(a.y),a.z=Math.abs(a.z);let h=r.scale.clone();const d=new c.Box3().setFromCenterAndSize(new c.Vector3(0,this.fitVolumeSize.y*a.y*.5,0).add(this.gameObject.worldPosition),this.fitVolumeSize.clone().multiply(a));if(Xt&&B.DrawWireBox3(d,255,5),this.fitIntoVolume&&(Jw(r,d,{position:!this.placeAtHitPosition}),h=r.scale.clone().divide(a),l=r.worldPosition.clone().sub(this.gameObject.worldPosition).divide(a),Xt&&B.DrawSphere(l,.1,16711680,5)),this.gameObject.attach(r),r.position.copy(l),r.quaternion.identity(),r.scale.copy(h),Xt&&B.DrawArrow(this.gameObject.worldPosition,r.getWorldPosition(new c.Vector3),65280,5),this._addedObjects.push(r),this._addedModels.push(n),this.placeAtHitPosition&&t&&t.screenposition){r.visible=!1;const f=this.context.physics.raycast({screenPoint:this.context.input.convertScreenspaceToRaycastSpace(t.screenposition.clone())});if(r.visible=!0,f&&f.length>0)for(const m of f){const g=m.point.clone();Xt&&console.log("Place object at hit",m),ex(r,g);break}}exports.AnimationUtils.autoplayAnimations(n);const u=new VA({sender:this,gltf:n,model:n,object:r,contentMD5:o,dropped:t.file||(t.url?new URL(t.url):void 0)});return this.dispatchEvent(u),this.onDropped?.invoke(u.detail),r&&this.context.events.emit("scene-content-changed",{source:this,object:r}),!i&&t.url?.startsWith("http")&&this.context.connection.isConnected&&r&&this.sendDropEvent(t.url,r,o),r}async sendDropEvent(e,t,i){if(!this.useNetworking){Xt&&console.debug("[DropListener] Ignoring networked event because networking is disabled",e);return}if(this.context.connection.isConnected){console.debug('Sending drop event "'+t.name+'"',e);const n=pi([t]),o={name:t.name,guid:this.guid,url:e,point:t.worldPosition.clone(),size:n.getSize(new c.Vector3),contentMD5:i};this.context.connection.send("droplistener",o)}}deleteDropEvent(){this.context.connection.sendDeleteRemoteState(this.guid)}testIfIsInDropArea(e){const t=this.context.input.convertScreenspaceToRaycastSpace(e.screenposition.clone()),i=this.context.physics.raycast({screenPoint:t,recursive:!0,testObject:o=>!this._addedObjects.some(r=>r.contains(o))});if(!i.length)return E()&&console.log(`Dropped outside of drop area for DropListener "${this.name}".`),!1;const n=i[0];return!!(this.dropArea&&this.dropArea.contains(n.object))}}Tl([p(c.Object3D)],Vs.prototype,"dropArea");Tl([p()],Vs.prototype,"fitIntoVolume");Tl([p(c.Vector3)],Vs.prototype,"fitVolumeSize");Tl([p()],Vs.prototype,"placeAtHitPosition");Tl([p()],Vs.prototype,"useNetworking");Tl([p(Z)],Vs.prototype,"onDropped");function GA(s){if(!s.startsWith("https://polyhaven.com/"))return s;const e="https://dl.polyhaven.org/file/ph-assets/Models/gltf/4k/",n=new URL(s).pathname.split("/").pop(),o=`${e}${n}/${n}_4k.gltf`;return console.log("Resolved polyhaven asset url",s,"→",o),o}var yf;(s=>{async function e(i,n,o){const r=o.guid,a=new ot(r),l=new Blob([i],{type:i.type||T_(i.name)||void 0}),h=URL.createObjectURL(l),d=await Is().loadSync(n,h,i.name,a).catch(u=>(console.error(`Failed to load file "${i.name}" (${i.type}):`,u),null));return URL.revokeObjectURL(h),d?new Promise((u,f)=>{const m=new FileReader;m.readAsArrayBuffer(i),m.onloadend=async g=>{const v=m.result,_=exports.BlobStorage.hashMD5(v);return u({model:d,contentMD5:_})}}):(console.warn(`Failed to load "${i.name}" (${i.type})`),null)}s.loadFile=e;async function t(i,n){const o=new ot(n.guid),r=i.toString();Xt&&B.DrawWireSphere(n.point,.1,16711680,3);const a=exports.PreviewHelper.addPreview({guid:n.guid,parent:n.parent,position:n?.point,size:n?.size});try{const l=await Is().loadSync(n.context,r,r,o,d=>{a.onProgress(d.loaded/d.total)}).catch(d=>(console.warn(d),null));if(!l)return console.warn("Unsupported file type: "+i.toString()),null;let h="";try{const d=await fetch(r).then(u=>u.arrayBuffer());h=exports.BlobStorage.hashMD5(d)}catch(d){console.warn("Failed to compute content hash for "+r,d)}return{model:l,contentMD5:h}}finally{Xt?setTimeout(()=>exports.PreviewHelper.removePreview(n.guid),3e3):exports.PreviewHelper.removePreview(n.guid)}}s.loadFileFromURL=t})(yf||(yf={}));var HA=Object.defineProperty,j_=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&HA(e,t,n),n};const cp=class AC extends T{parent=null;object=null;limitCount=60;_currentCount=0;_startPosition=null;_startQuaternion=null;start(){if(this._currentCount=0,this._startPosition=null,this._startQuaternion=null,this.ensureParentGuid(),this.object||(this.object=this.gameObject),this.object){if(this.object===this.gameObject){const t=new ot(this.guid);this.object=P.instantiate(this.object,{idProvider:t,keepWorldPosition:!1}),P.getComponent(this.object,AC)?.destroy();let n=this.object.getComponentInChildren(vr);n||(n=this.object.addComponent(vr,{dragMode:R_.SnapToSurfaces}),n.guid=t.generateUUID());let o=P.getComponent(n.gameObject,Sn);o||(o=n.gameObject.addComponent(Sn),o.guid=t.generateUUID())}this.object.visible=!1;const e=this.gameObject.getComponent(vr);e&&(e.enabled=!1),this._startPosition=this.object.position?.clone()??new c.Vector3(0,0,0),this._startQuaternion=this.object.quaternion?.clone()??new c.Quaternion(0,0,0,1)}this.gameObject.getComponentInParent(Ji)||this.gameObject.addComponent(Ji)}onEnable(){this.startCoroutine(this.cloneLimitIntervalFn())}_forwardPointerEvents=new Map;onPointerEnter(e){e.used||this.object&&this.context.connection.allowEditing&&e.button===0&&this.context.input.setCursor("pointer")}onPointerExit(e){e.used||this.object&&this.context.connection.allowEditing&&e.button===0&&this.context.input.unsetCursor("pointer")}onPointerDown(e){if(e.used||!this.object||!this.context.connection.allowEditing||e.button!==0)return;const t=this.handleDuplication();if(t){const i=P.getComponent(t,vr);i?(i.onPointerDown(e),this._forwardPointerEvents.set(e.event.space,i)):E()&&console.warn(`Duplicated object (${t.name}) does not have DragControls`)}else this._currentCount>=this.limitCount?console.warn(`[Duplicatable] Limit of ${this.limitCount} objects created within a few seconds reached. Please wait a moment before creating more objects.`):console.warn("[Duplicatable] Could not duplicate object.")}onPointerUp(e){if(e.used)return;const t=this._forwardPointerEvents.get(e.event.space);t&&(t.onPointerUp(e),this._forwardPointerEvents.delete(e.event.space))}ensureParentGuid(){this.parent&&(this.parent.guid||this.parent.userData?.guid||(this.parent.guid=new ot(this.guid+"/parent").generateUUID()))}*cloneLimitIntervalFn(){for(;this.activeAndEnabled&&!this.destroyed;)this._currentCount>0?this._currentCount-=1:this._currentCount<0&&(this._currentCount=0),yield Hy(1)}handleDuplication(){if(!this.object||this.limitCount>0&&this._currentCount>=this.limitCount||this.object===this.gameObject)return null;if(P.isDestroyed(this.object))return this.object=null,null;this.object.matrixAutoUpdate===!1&&(this.object.updateMatrix(),E()&&(console.warn(`Object "${this.object.name}" has matrixAutoUpdate disabled. This can cause duplicated objects to have incorrect position/rotation/scale. Consider enabling matrixAutoUpdate or calling updateMatrix() before duplication.`),de("Duplicatable: Object has matrixAutoUpdate disabled"))),this.object.visible=!0,this._startPosition&&this.object.position.copy(this._startPosition),this._startQuaternion&&this.object.quaternion.copy(this._startQuaternion);const e=new hs;this.parent||(this.parent=this.gameObject.parent),this.ensureParentGuid(),this.parent&&(e.parent=this.parent.guid??this.parent.userData?.guid,e.keepWorldPosition=!0),e.position=this.worldPosition,e.rotation=this.worldQuaternion,e.context=this.context,this._currentCount+=1;const t=P.instantiateSynced(this.object,e);return console.assert(t!==this.object,"Duplicated object is original"),this.object.visible=!1,this._startPosition&&this.object.position.clone().copy(this._startPosition),this._startQuaternion&&this.object.quaternion.clone().copy(this._startQuaternion),t}};j_([p(c.Object3D)],cp.prototype,"parent");j_([p(c.Object3D)],cp.prototype,"object");j_([p()],cp.prototype,"limitCount");let U_=cp;var xs=(s=>(s[s.PointerEnter=0]="PointerEnter",s[s.PointerExit=1]="PointerExit",s[s.PointerDown=2]="PointerDown",s[s.PointerUp=3]="PointerUp",s[s.PointerClick=4]="PointerClick",s))(xs||{}),qA=Object.defineProperty,z_=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&qA(e,t,n),n};class N_{eventID;callback=new Z}z_([p()],N_.prototype,"eventID");z_([p(Z)],N_.prototype,"callback");class hp extends T{triggers=[];invoke(e){if(this.triggers)for(const t of this.triggers)t.eventID===e&&t.callback?.invoke()}hasTrigger(e){return this.triggers?.some(t=>t.eventID===e)??!1}shouldChangeCursor(){return this.hasTrigger(xs.PointerClick)||this.hasTrigger(xs.PointerDown)||this.hasTrigger(xs.PointerUp)}onPointerClick(e){this.invoke(xs.PointerClick)}onPointerEnter(e){this.shouldChangeCursor()&&this.context.input.setCursor("pointer"),this.invoke(xs.PointerEnter)}onPointerExit(e){this.shouldChangeCursor()&&this.context.input.unsetCursor("pointer"),this.invoke(xs.PointerExit)}onPointerDown(e){this.invoke(xs.PointerDown)}onPointerUp(e){this.invoke(xs.PointerUp)}}z_([p(N_)],hp.prototype,"triggers");class DC{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(e.constructor.name!=="InstancedMesh")return;const i=this.writer,n=i.extensionsUsed,o={};t.extensions=t.extensions||{},t.extensions[this.name]=o;let r=new c.Matrix4;const a=new Array,l=new Array,h=new Array;for(let m=0;m<e.count;m++){e.getMatrixAt(m,r);let g=new c.Vector3,v=new c.Quaternion,_=new c.Vector3;r.decompose(g,v,_),a.push(g.x,g.y,g.z),l.push(v.x,v.y,v.z,v.w),h.push(_.x,_.y,_.z)}const d=new Float32Array(a),u=new Float32Array(l),f=new Float32Array(h);o.attributes={TRANSLATION:i.processAccessor(new c.BufferAttribute(d,3)),ROTATION:i.processAccessor(new c.BufferAttribute(u,4)),SCALE:i.processAccessor(new c.BufferAttribute(f,3))},n[this.name]=!0}}class IC{writer;constructor(e){this.writer=e}writeNode(e){}}class XA extends IC{beforeWriteNode(e,t){B.isGizmo(e)&&(t.keep=!1)}}class LC extends IC{beforeWriteTexture(e,t){e.isRenderTargetTexture&&(t.newTexture=Yy(new oe(1,1,1,0)))}}function BC(s){const e=as.DontExport;return!(s.hideFlags&e)}function FC(s){return jC(s)}function jC(s,e=[]){let t=0;for(let i=0;i<s.children.length;t++){const n=s.children[i];if(!BC(n)){s.children.splice(i,1),n.parent=null;const o=t;e.push(()=>QA(n,s,o));continue}jC(n,e),i++}return e}function QA(s,e,t){s.parent=e,e.children.splice(Math.min(t,e.children.length),0,s)}var YA=Object.defineProperty,UC=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&YA(e,t,n),n};const Xd=x("debuggltfexport");class $_ extends At{sceneRoot}const V_=class Ia extends T{binary=!0;objects=[];ext;async exportNow(e,t){Xd&&console.log("Exporting objects as glTF",this.objects),e||(e="scene"),(!this.objects||this.objects.length<=0)&&(this.objects=[this.context.scene]);const i={binary:this.binary,pivot:Ia.calculateCenter(this.objects),...t},n=await this.export(this.objects,i).catch(o=>(console.error(o),!1));return n===!1?!1:(this.binary?e.endsWith(".glb")||(e+=".glb"):e.endsWith(".gltf")||(e+=".gltf"),this.binary?Ia.saveArrayBuffer(n,e):Ia.saveJson(n,e),!0)}async export(e,t){if(!e||e.length<=0){console.warn("No objects set to export");return}const i=new V.GLTFExporter;i.register(d=>new DC(d)),i.register(d=>new LC(d)),L_(i,this.context),Ia.filterTopmostParent(e);const n={trs:!1,onlyVisible:!0,truncateDrawRange:!1,binary:!0,maxTextureSize:1/0,embedImages:!0,includeCustomExtensions:!0,animations:t?.animations||Ia.collectAnimations(e),...t},o=new Array,r=new c.Object3D;t?.pivot&&r.position.sub(t.pivot),Xd&&console.log("EXPORT",e),e.forEach(d=>{d&&BC(d)&&(r.children.push(d),d.matrixAutoUpdate=!1,d.matrix.copy(d.matrixWorld),P.getComponentsInChildren(d,ti).forEach(u=>{P.isActiveInHierarchy(u.gameObject)&&u.setInstancingEnabled(!1)}),o.push(...FC(d)))});const a=new Eh(r);return t?.needleComponents&&(this.ext=new D_),this.ext&&(this.ext.registerExport(i),this.ext.context=a),new Promise((d,u)=>{Xd&&console.log("Starting glTF export.");try{i?.parse(r,f=>{l(),d(f)},f=>{l(),u(f)},n)}catch(f){console.error(f),l(),u(f)}finally{Xd&&console.log("Finished glTF export.")}});function l(){o.forEach(d=>d()),o.length=0,h()}function h(){e.forEach(d=>{d&&(d.matrixAutoUpdate=!0,P.getComponentsInChildren(d,ti).forEach(u=>{P.isActiveInHierarchy(u.gameObject)&&u.setInstancingEnabled(!1)}))})}}static saveArrayBuffer(e,t){this.save(new Blob([e],{type:"application/octet-stream"}),t)}static saveJson(e,t){this.save("data: text/json;charset=utf-8,"+encodeURIComponent(JSON.stringify(e)),t)}static save(e,t){const i=document.createElement("a");i.style.display="none",document.body.appendChild(i),typeof e=="string"?i.href=e:i.href=URL.createObjectURL(e),i.download=t,i.click(),i.remove()}static collectAnimations(e,t){t=t||[];for(const i of e)i&&i.traverseVisible(n=>{n.animations&&n.animations.length>0&&t.push(...n.animations)});return t}static calculateCenter(e,t){const i=t||new c.Vector3;return i.set(0,0,0),e.forEach(n=>{i.add(ie(n))}),i.divideScalar(e.length),i}static filterTopmostParent(e){if(!(e.length<=0))for(let t=0;t<e.length;t++){let i=e[t];if(!i){e.splice(t,1),t--;continue}for(;i.parent;){if(e.includes(i.parent)){e.splice(t,1),t--;break}i=i.parent}}}};UC([p()],V_.prototype,"binary");UC([p(c.Object3D)],V_.prototype,"objects");let W_=V_;function KA(){typeof globalThis!==void 0&&!("OffscreenCanvas"in globalThis)&&(globalThis.OffscreenCanvas=class{canvas;constructor(e,t){return this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=t,this.canvas.convertToBlob=(i,n)=>new Promise(o=>{this.canvas.toBlob(o,i,n)}),this.canvas}})}const ZA=x("debugprogress");function zC(s){s=s||new Date;const e=s.getMonth()+1,t=s.getDate(),i=s.getHours(),n=s.getMinutes(),o=s.getSeconds(),r=(e<10?"0":"")+e,a=(t<10?"0":"")+t,l=(i<10?"0":"")+i,h=(n<10?"0":"")+n,d=(o<10?"0":"")+o;return s.getFullYear()+r+a+"-"+l+h+d}class he{static start(e,t){typeof t=="string"&&(t={parentScope:t});const i=new JA(e,t);Ec.set(e,i)}static report(e,t){const i=Ec.get(e);if(!i){console.warn("Reporting progress for non-existing scope",e);return}typeof t=="string"&&(t={message:t,autoStep:!0}),i.report(t)}static end(e){const t=Ec.get(e);t&&(t.end(),Ec.delete(e))}}const Ec=new Map;class JA{scopeLabel;parentScope;childScopes=[];parentDepth=0;lastStep=0;lastAutoStepWeight=1;lastTotalSteps=0;onProgress;showLogs=!1;selfProgress=0;totalProgress=0;selfReports=0;totalReports=0;constructor(e,t){this.parentScope=t?.parentScope?Ec.get(t.parentScope):void 0,this.parentScope&&(this.parentScope.childScopes.push(this),this.parentDepth=this.parentScope.parentDepth+1),this.scopeLabel=" ".repeat(this.parentDepth*2)+e,this.showLogs=t?.logTimings??!!ZA,this.showLogs&&console.time(this.scopeLabel),this.onProgress=t?.onProgress}report(e,t=!1){if(e){if(e.totalSteps!==void 0&&(this.lastTotalSteps=e.totalSteps),e.currentStep!==void 0&&(this.lastStep=e.currentStep),e.autoStep!==void 0){if(e.currentStep===void 0){this.lastStep===void 0&&(this.lastStep=0);const n=typeof e.autoStep=="number"?e.autoStep:1;this.lastStep+=this.lastAutoStepWeight,this.lastAutoStepWeight=n,e.currentStep=this.lastStep}e.totalSteps=this.lastTotalSteps}e.progress!==void 0?this.selfProgress=e.progress:e.currentStep!==void 0&&e.totalSteps!==void 0&&(this.selfProgress=e.currentStep/e.totalSteps)}if(this.childScopes.length>0){let n=0,o=0;for(const a of this.childScopes)n+=a.selfProgress,o+=1;o>0&&(n/=o);const r=this.lastAutoStepWeight/(this.lastTotalSteps??1);this.totalProgress=this.selfProgress+n*r}else this.totalProgress=this.selfProgress;this.selfProgress=Math.min(1,this.selfProgress),this.totalProgress=Math.min(1,this.totalProgress);let i=(this.totalProgress*100).toFixed(3)+"%";this.childScopes.length>0&&(i+=" ("+(this.selfProgress*100).toFixed(3)+"% self)"),e?.message&&(i=e.message+" – "+i),this.lastStep!==void 0&&this.lastTotalSteps!==void 0&&(i="Step "+(this.lastStep+(this.lastAutoStepWeight!=1?"–"+(this.lastStep+this.lastAutoStepWeight):"")+"/"+this.lastTotalSteps)+" "+i),t?this.totalReports++:(this.selfReports++,this.totalReports++),this.showLogs&&console.timeLog(this.scopeLabel,i),this.onProgress&&this.onProgress(this.totalProgress),this.parentScope&&this.parentScope.report(void 0,!0)}end(){this.report({progress:1,autoStep:!0},!0),this.showLogs&&(console.timeLog(this.scopeLabel,"Total reports: "+this.totalReports,"Self reports: "+this.selfReports),console.timeEnd(this.scopeLabel));let e=!1;for(const t of this.childScopes)if(!(t.selfProgress>=1)){e=!0;break}e&&console.warn("Progress end with child scopes that are still running",this),this.onProgress=void 0}}const Le="</StageRoot/Materials";function eD(s,e,t){const i=new Map,n=v=>{const _=v.type___needle,y=i.get(_)||new Map;if(i.set(_,y),!y.has(v)){const b=`${_}${y.size?`_${y.size}`:""}`;y.set(v,b)}return y.get(v)},o=s.colorNode?Qd(s.colorNode):[],r=s.colorNode?`color3f inputs:diffuseColor.connect = ${Le}/${e}/${n(o.values().next().value)}.outputs:out>`:"",a=s.roughnessNode?Qd(s.roughnessNode):[],l=s.roughnessNode?`float inputs:roughness.connect = ${Le}/${e}/${n(a.values().next().value)}.outputs:out>`:"",h=s.normalNode?Qd(s.normalNode):[],d=s.normalNode?`float3 inputs:normal.connect = ${Le}/${e}/${n(h.values().next().value)}.outputs:out>`:"",u=s.metalnessNode?Qd(s.metalnessNode):[],f=s.metalnessNode?`float inputs:metallic.connect = ${Le}/${e}/${n(u.values().next().value)}.outputs:out>`:"",m=new Set([...o,...a,...h,...u]),g=nD(m,e,t,n);return console.debug(g),`
|
|
1141
1141
|
|
|
1142
1142
|
def Material "${e}" ${s.name?`(
|
|
1143
1143
|
displayName = "${s.name}"
|
|
@@ -1525,7 +1525,7 @@ To allow joining a room without a query parameter you can set "requireRoomParame
|
|
|
1525
1525
|
Please choose one of the following options to fix this:
|
|
1526
1526
|
A) Set a room name in the SyncedRoom component
|
|
1527
1527
|
B) Set a room name in the URL parameter "?`+this.urlParameterName+`=my_room"
|
|
1528
|
-
C) Set "joinRandomRoom" to true`),!1):(hu&&console.log("Join "+this.roomName),this._userWantsToBeInARoom=!0,this.context.connection.joinRoom(this.roomName),!0))}_lastPingTime=0;_lastRoomTime=-1;_userWantsToBeInARoom=!1;update(){this.context.connection.isConnected&&(this.context.time.time-this._lastPingTime>3&&(this._lastPingTime=this.context.time.time,this.context.connection.sendPing()),this.context.connection.isInRoom&&(this._lastRoomTime=this.context.time.time)),this._lastRoomTime>0&&this.context.time.time-this._lastRoomTime>.3&&(this._lastRoomTime=-1,this.autoRejoin?this._userWantsToBeInARoom&&(console.log("Disconnected from networking backend - attempt reconnecting now"),this.tryJoinRoom()):E()&&console.warn("You are not connected to a room anymore (possibly because the tab was inactive for too long and the server kicked you?)"))}getViewOnlyUrl(){if(this.context.connection.isConnected&&this.context.connection.currentRoomViewId){const e=window.location.search,t=new URLSearchParams(e);return t.has(this.urlParameterName)&&t.delete(this.urlParameterName),t.set(Km,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}setRandomRoomUrlParameter(){const e=xh(),t=this.generateRoomName();x(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),Sy(t,e)}generateRoomName(){let e="";for(let t=0;t<6;t++)e+=Math.floor(Math.random()*10).toFixed(0);return e}_roomButton;_roomButtonIconJoin;_roomButtonIconLeave;createRoomButton(){if(this._roomButton)return this._roomButton;const e=document.createElement("button");return this._roomButton=e,e.classList.add("create-room-button"),e.setAttribute("priority","90"),e.onclick=()=>{if(this.context.connection.isInRoom)this.urlParameterName&&Yc(this.urlParameterName,null),this.context.connection.leaveRoom(),this._userWantsToBeInARoom=!1;else{if(this.urlParameterName){const t=x(this.urlParameterName);(!t||t===!0)&&(this._lastJoinedRoom?Yc(this.urlParameterName,this._lastJoinedRoom):this.setRandomRoomUrlParameter())}this.tryJoinRoom()}},this._roomButtonIconJoin=bt("group"),this._roomButtonIconLeave=bt("group_off"),this.updateRoomButtonState(),this.context.connection.beginListen(te.JoinedRoom,this.updateRoomButtonState),this.context.connection.beginListen(te.LeftRoom,this.updateRoomButtonState),e}updateRoomButtonState=()=>{this._roomButton&&(this.context.connection.isInRoom?(this._roomButton.title="Leave the networked room",this._roomButton.textContent="Leave Room",this._roomButtonIconJoin?.remove(),this._roomButton.prepend(this._roomButtonIconLeave)):(this._roomButton.title="Create or join a networked room",this._roomButton.textContent="Join Room",this._roomButtonIconLeave?.remove(),this._roomButton.prepend(this._roomButtonIconJoin)))};destroyRoomButton(){this.context.connection.stopListen(te.JoinedRoom,this.updateRoomButtonState),this.context.connection.stopListen(te.LeftRoom,this.updateRoomButtonState)}_viewOnlyButton;onEnableViewOnlyButton(){this.context.connection.isConnected?this.onCreateViewOnlyButton():(this.context.connection.stopListen(te.JoinedRoom,this.onCreateViewOnlyButton),this.context.connection.beginListen(te.JoinedRoom,this.onCreateViewOnlyButton))}onDisableViewOnlyButton(){this.context.connection.stopListen(te.JoinedRoom,this.onCreateViewOnlyButton),this._viewOnlyButton?.remove()}onCreateViewOnlyButton=()=>{if(!this._viewOnlyButton){const e=document.createElement("button");this._viewOnlyButton=e,e.classList.add("view-only-button"),e.setAttribute("priority","90"),e.onclick=()=>{const t=this.getViewOnlyUrl();t?.length?navigator.canShare({url:t})?navigator.share({url:t})?.catch(i=>{console.warn(i)}):(navigator.clipboard.writeText(t),Re("View only URL copied to clipboard")):de("Could not create view only URL")},e.title="Copy the view only URL: A page accessed by the view only URL can not be modified by visiting users.",e.textContent="Share View URL",e.prepend(bt("visibility"))}this.context.menu.appendChild(this._viewOnlyButton)}}Xo([p()],Rn.prototype,"roomName",2);Xo([p()],Rn.prototype,"urlParameterName",2);Xo([p()],Rn.prototype,"joinRandomRoom",2);Xo([p()],Rn.prototype,"requireRoomParameter",2);Xo([p()],Rn.prototype,"autoRejoin",2);Xo([p()],Rn.prototype,"createJoinButton",2);Xo([p()],Rn.prototype,"createViewOnlyButton",2);Xo([p()],Rn.prototype,"roomPrefix",1);var S2=Object.defineProperty,C2=Object.getOwnPropertyDescriptor,Hl=(s,e,t,i)=>{for(var n=i>1?void 0:i?C2(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&&S2(e,t,n),n};const P2="noVoip",k2=x("debugvoip");class Qs extends T{autoConnect=!0;runInBackground=!0;createMenuButton=!0;debug=!1;_volume=1;get volume(){return this._volume}set volume(e){if(Number.isNaN(e))return;const t=Math.max(0,Math.min(1,e));this._volume=t;for(const i of this._incomingStreams.values())i.volume=t}getAudioElement(e){return this._incomingStreams.get(e)}get incomingStreams(){return this._incomingStreams}speakingThreshold=.1;onSpeakingChanged=new Z;_speakingStates=new Map;_analysers=new Map;_sharedAudioContext;_lastSpeakingPollMs=0;_net;_menubutton;awake(){k2&&(this.debug=!0),this.debug&&(console.log("VOIP debugging: press 'v' to toggle incoming mute, 'c' to toggle connect/disconnect"),window.addEventListener("keydown",async e=>{switch(e.key.toLowerCase()){case"v":console.log("VOIP: toggle incoming mute → ",!this.isMuted),this.setMuted(!this.isMuted);break;case"c":this.isSending?this.disconnect():this.connect();break}}))}onEnable(){this._net||(this._net=rd.create(this)),this.debug&&(this._net.debug=!0),this._net.addEventListener(is.StreamReceived,this.onReceiveStream),this._net.addEventListener(is.StreamEnded,this.onStreamEnded),this._net.enable(),this.autoConnect&&this.context.connection.isConnected&&this.connect(),this.context.connection.beginListen(te.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(te.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.addEventListener("visibilitychange",this.onVisibilityChanged)}onDisable(){this._net&&(this._net.stopSendingStream(this._outputStream),this._net.removeEventListener(is.StreamReceived,this.onReceiveStream),this._net.removeEventListener(is.StreamEnded,this.onStreamEnded),this._net?.disable()),this.context.connection.stopListen(te.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(te.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.removeEventListener("visibilitychange",this.onVisibilityChanged);for(const e of[...this._analysers.keys()])this.cleanupAnalyser(e);this.closeSharedAudioContext()}onDestroy(){this._menubutton?.remove(),this._menubutton=void 0;for(const e of[...this._analysers.keys()])this.cleanupAnalyser(e);this.closeSharedAudioContext();for(const e of this._incomingStreams.values())Hi(e.srcObject);this._incomingStreams.clear(),this._speakingStates.clear()}_allowSending=!0;_outputStream=null;_connectInFlight;get isSending(){return this._outputStream!=null&&this._outputStream.active}connect(e){return this._connectInFlight?this._connectInFlight:(this._connectInFlight=this._connectImpl(e).finally(()=>{this._connectInFlight=void 0}),this._connectInFlight)}async _connectImpl(e){if(!this._net)return console.error("Cannot connect to voice chat - NetworkedStreams not initialized. Make sure the component is enabled before calling this method."),!1;if(this.context.connection.isConnected){if(!await exports.DeviceUtilities.microphonePermissionsGranted())return console.error("Cannot connect to voice chat - microphone permissions not granted"),this.updateButton(),!1}else return console.error("Cannot connect to voice chat - not connected to server"),this.updateButton(),!1;return this._allowSending=!0,this._net?.stopSendingStream(this._outputStream),Hi(this._outputStream),this._outputStream=await this.getAudioStream(e),this._outputStream?(this.debug&&console.log("VOIP: Got audio stream"),this._net?.startSendingStream(this._outputStream),this.updateButton(),!0):(this.updateButton(),await exports.DeviceUtilities.microphonePermissionsGranted()?console.error("VOIP: Could not get audio stream - please make sure to connect an audio device and grant microphone permissions"):wl("Microphone permissions not granted: Please grant microphone permissions to use voice chat"),(this.debug||E())&&console.log("VOIP: Failed to get audio stream"),!1)}disconnect(e){e?.remember&&(this._allowSending=!1),this._net?.stopSendingStream(this._outputStream),Hi(this._outputStream),this._outputStream=null,this.updateButton()}setMuted(e){for(const t of this._incomingStreams.values())t.muted=e}get isMuted(){if(this._incomingStreams.size===0)return!1;for(const e of this._incomingStreams.values())if(!e.muted)return!1;return!0}async updateButton(){if(this.createMenuButton){if(this._menubutton||(this._menubutton=document.createElement("button"),this._menubutton.addEventListener("click",()=>{this.isSending?this.disconnect({remember:!0}):this.connect(),exports.DeviceUtilities.microphonePermissionsGranted().then(e=>{e||de("<strong>Microphone permissions not granted</strong>. Please allow your browser to use the microphone to be able to talk. Click on the button on the left side of your browser's address bar to allow microphone permissions.")})})),this._menubutton){this.context.menu.appendChild(this._menubutton),this.activeAndEnabled?this._menubutton.style.display="":this._menubutton.style.display="none",this._menubutton.title=this.isSending?"Click to disable your microphone":"Click to enable your microphone";let e=(this.isSending,""),t=this.isSending?"mic":"mic_off";await exports.DeviceUtilities.microphonePermissionsGranted()||(e="No Permission",t="mic_off",this._menubutton.title="Microphone permissions not granted. Please allow your browser to use the microphone to be able to talk. This can usually be done in the addressbar of the webpage."),this._menubutton.innerText=e,this._menubutton.prepend(bt(t)),this.context.connection.isConnected==!1?this._menubutton.setAttribute("disabled",""):this._menubutton.removeAttribute("disabled")}}else this.activeAndEnabled||this._menubutton?.remove()}getFrequency(e){return this.unsupported_getfrequency||(this.unsupported_getfrequency=!0,E()&&de("VOIP: getFrequency is currently not supported"),console.warn("VOIP: getFrequency is currently not supported")),null}async getAudioStream(e){if(!navigator.mediaDevices.getUserMedia)return console.error("No getDisplayMedia support"),null;const t=async n=>await navigator.mediaDevices.getUserMedia({audio:n??!0,video:!1}).catch(o=>(console.warn("VOIP failed getting audio stream",o),null)),i=await t(e);if(!i)return null;if(exports.DeviceUtilities.isiOS()&&e?.deviceId===void 0){const o=(await navigator.mediaDevices.enumerateDevices()).find(r=>(r.kind==="audioinput"||r.kind==="audiooutput")&&!r.label.includes("iPhone"));if(o){const r=Object.assign({},e);r.deviceId=o.deviceId;const a=await t(r);if(a)return Hi(i),a}}return i}onJoinedRoom=async()=>{this.debug&&console.log("VOIP: Joined room"),await Ds(300),this.autoConnect&&!this.isSending&&this._allowSending&&this.connect()};onLeftRoom=()=>{this.debug&&console.log("VOIP: Left room"),this.disconnect();for(const e of this._incomingStreams.values())Hi(e.srcObject);this._incomingStreams.clear();for(const e of this._analysers.keys())this.cleanupAnalyser(e)};_incomingStreams=new Map;update(){if(!this.onSpeakingChanged||this.onSpeakingChanged.listenerCount<=0)return;const e=performance.now();if(!(e-this._lastSpeakingPollMs<100)){this._lastSpeakingPollMs=e;for(const[t,i]of this._analysers){i.analyser.getByteFrequencyData(i.data);let n=0;for(let l=0;l<i.data.length;l++)n+=i.data[l];const o=n/i.data.length/255,r=this._speakingStates.get(t)??!1,a=o>this.speakingThreshold;a!==r&&(this._speakingStates.set(t,a),this.onSpeakingChanged.invoke({userId:t,isSpeaking:a,volume:o}))}}}setupAnalyser(e,t,i){if(!this._analysers.has(e))try{this._sharedAudioContext||(this._sharedAudioContext=new AudioContext);const n=this._sharedAudioContext,o=n.createMediaStreamSource(i),r=n.createAnalyser();r.fftSize=256,o.connect(r);const a=new Uint8Array(r.frequencyBinCount);this._analysers.set(e,{source:o,analyser:r,data:a})}catch(n){this.debug&&console.warn("VOIP: Failed to create analyser for",e,n)}}cleanupAnalyser(e){const t=this._analysers.get(e);t&&(t.source.disconnect(),t.analyser.disconnect(),this._analysers.delete(e)),this._speakingStates.delete(e)}closeSharedAudioContext(){this._sharedAudioContext&&(this._sharedAudioContext.close(),this._sharedAudioContext=void 0)}onReceiveStream=e=>{const t=e.target.userId,i=e.stream;let n=this._incomingStreams.get(t);n||(n=new Audio,this._incomingStreams.set(t,n)),n.srcObject=i,n.volume=this._volume,n.setAttribute("autoplay","true"),this.setupAnalyser(t,n,i),wn.registerWaitForInteraction(()=>{n?.play().catch(o=>{console.error("VOIP: Failed to play audio",o)})})};onStreamEnded=e=>{const t=this._incomingStreams.get(e.userId);Hi(t?.srcObject),this._incomingStreams.delete(e.userId),this.cleanupAnalyser(e.userId)};onEnabledChanged=()=>{for(const e of this._incomingStreams){const t=e[1];t.muted=!this.enabled}};onVisibilityChanged=()=>{if(this.runInBackground)return;const e=document.visibilityState!=="visible";this.setMuted(e);const t=this._outputStream?.getAudioTracks();if(t)for(const i of t)i.enabled=!e}}Hl([p()],Qs.prototype,"autoConnect",2);Hl([p()],Qs.prototype,"runInBackground",2);Hl([p()],Qs.prototype,"createMenuButton",2);Hl([p()],Qs.prototype,"volume",1);Hl([p()],Qs.prototype,"speakingThreshold",2);Hl([p(Z)],Qs.prototype,"onSpeakingChanged",2);function M2(){const s=x("testwindowcount")||0;s&&s>0&&O2(s)}function O2(s){if(x("testwindow"))return null;const e=new URL(window.location.href);cg(e.searchParams,P2,1),cg(e.searchParams,"testwindow",1);const t=e.toString(),i=[];window.onbeforeunload=()=>{for(const l of i)l.close()};const n=.05,o=128;let r=0,a=0;for(let l=0;l<s;l++){r*o+o*.01>=window.innerWidth&&(a+=1,r=0);const h=r*(o*(1+n))+window.screenLeft,d=a*(o*(1+n))+window.screenTop+90+60*a;r+=1;const u=window.open(t,"test window "+l,`popup=yes width=${o} height=${o} top=${d} left=${h}`);if(!u){console.warn("Failed to open window");continue}i.push(u),u.onload=()=>{u.onbeforeunload=()=>{for(let f=0;f<i.length;f++){const m=i[f];m!==u&&m.close()}i.length=0}}}return i}class Rb extends T{awake(){M2()}}class Tb extends T{transformsPerFrame=10;interval=0;useFlatbuffers=!0;awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinary(uh,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new E2(this.context.connection.connectionId+"_simulatedTransform_"+e,this))}}builder=null;models=null;update(){if(this.context.connection.isConnected){if(this.useFlatbuffers){if(!this.context.connection.connectionId||this.context.time.frameCount%this.interval!==0)return;this.builder===null&&(this.builder=new ee.Builder(1024));const e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();const i=cC(this.context.connection.connectionId,this);this.context.connection.sendBinary(i)}}else if(this.models)for(let e=0;e<this.models.length;e++){const t=this.models[e];t.dontSave=!0,t.update(this,null),this.context.connection.send("TestSimulateUserData-"+e,t)}}}}class E2{guid;fast=!1;position;rotation;velocity=void 0;dontSave;isValid(){return this.fast!==void 0||this.position!==void 0||this.rotation!==void 0||this.velocity!==void 0}constructor(e,t){this.guid=e,this.position={x:0,y:0,z:0},this.rotation={x:0,y:0,z:0,w:0},this.update(t,null)}static temp=new c.Vector3;update(e,t){const i=e.worldPosition;this.position.x=i.x,this.position.y=i.y,this.position.z=i.z;const n=e.worldQuaternion;if(this.rotation.x=n.x,this.rotation.y=n.y,this.rotation.z=n.z,this.rotation.w=n.w,this.fast=!1,t){const o=t.getVelocity();this.velocity===void 0&&(this.velocity={x:0,y:0,z:0}),this.velocity.x=o.x,this.velocity.y=o.y,this.velocity.z=o.z}}}var R2=Object.defineProperty,Lp=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&R2(e,t,n),n};class ca extends T{isGizmo=!1;translationSnap=1;rotationSnapAngle=15;scaleSnap=.25;get control(){return this._control}_control;orbit;onEnable(){if(!(this.isGizmo&&!Oh)&&this.context.mainCamera&&(this._control||(this._control=new V.TransformControls(this.context.mainCamera,this.context.renderer.domElement),this._control.enabled=!0,this._control.getRaycaster().layers.set(2),this._control.size=1,("_root"in this._control?this._control._root:this._control).traverse(t=>{const i=t;if(i.layers.set(2),i){const n=i.material;n&&(n.opacity=.3)}}),this.orbit=P.getComponentInParent(this.context.mainCamera,ue)??void 0),this._control)){const e=this._control.getHelper();this.context.scene.add(e),this._control.attach(this.gameObject),this._control?.addEventListener("dragging-changed",this.onControlChangedEvent),window.addEventListener("keydown",this.windowKeyDownListener),window.addEventListener("keyup",this.windowKeyUpListener)}}onDisable(){this._control?.getHelper()?.removeFromParent(),this._control?.removeEventListener("dragging-changed",this.onControlChangedEvent),window.removeEventListener("keydown",this.windowKeyDownListener),window.removeEventListener("keyup",this.windowKeyUpListener)}enableSnapping(){this._control&&(this._control.setTranslationSnap(this.translationSnap),this._control.setRotationSnap(c.MathUtils.degToRad(this.rotationSnapAngle)),this._control.setScaleSnap(this.scaleSnap))}disableSnapping(){this._control&&(this._control.setTranslationSnap(null),this._control.setRotationSnap(null),this._control.setScaleSnap(null))}onControlChangedEvent=e=>{const t=this.orbit;if(t&&(t.enabled=!e.value),e.value){const i=this.gameObject.getComponentInParent(Sn);i&&(i.fastMode=!0,i.requestOwnership())}else{const i=this.gameObject.getComponentInParent(Sn);i&&(i.fastMode=!1)}};windowKeyDownListener=e=>{if(this.enabled&&this._control)switch(e.keyCode){case 81:this._control.setSpace(this._control.space==="local"?"world":"local");break;case 16:this.enableSnapping();break;case 87:this._control.setMode("translate");break;case 69:this._control.setMode("rotate");break;case 82:this._control.setMode("scale");break;case 187:case 107:this._control.setSize(this._control.size+.1);break;case 189:case 109:this._control.setSize(Math.max(this._control.size-.1,.1));break;case 88:this._control.showX=!this._control.showX;break;case 89:this._control.showY=!this._control.showY;break;case 90:this._control.showZ=!this._control.showZ;break;case 32:this._control.enabled=!this._control.enabled;break}};windowKeyUpListener=e=>{this.enabled&&e.keyCode===16&&this.disableSnapping()}}Lp([p()],ca.prototype,"isGizmo");Lp([p()],ca.prototype,"translationSnap");Lp([p()],ca.prototype,"rotationSnapAngle");Lp([p()],ca.prototype,"scaleSnap");var T2=Object.defineProperty,A2=Object.getOwnPropertyDescriptor,Bp=(s,e,t,i)=>{for(var n=i>1?void 0:i?A2(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&&T2(e,t,n),n};class Ab{texture=null;rect}Bp([p(c.Texture)],Ab.prototype,"texture",2);let ql=class extends Yh{set image(e){this.sprite||(this.sprite=new Ab),this.sprite.texture=e,this.onAfterCreated()}get image(){return this.sprite?this.sprite.texture:null}get sprite(){return this._sprite}set sprite(e){this._sprite!==e&&(this._sprite=e,this.onAfterCreated())}_sprite;pixelsPerUnitMultiplier=1;isBuiltinSprite(){const e=this.sprite;switch(e?.texture?.name){case"InputFieldBackground":case"UISprite":case"Background":case"Knob":return!0}const t=e?.texture?.image;return!!(!e?.texture?.name?.length&&Lc(t)&&t.width===32&&t.height===32)}onBeforeCreate(e){super.onBeforeCreate(e),this.isBuiltinSprite()&&(e.borderRadius=5/this.pixelsPerUnitMultiplier,this.sprite?.texture?.name==="Knob"&&(e.borderRadius=999))}onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture(this.sprite?.texture))}};Bp([p(Ab)],ql.prototype,"sprite",1);Bp([p()],ql.prototype,"pixelsPerUnitMultiplier",2);class Fp extends Yh{get mainTexture(){return this._mainTexture}set mainTexture(e){this._mainTexture!==e&&(this._mainTexture=e,this.onAfterCreated())}_mainTexture;onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),this.setTexture(this.mainTexture))}}Bp([p(c.Texture)],Fp.prototype,"mainTexture",1);var D2=Object.defineProperty,I2=Object.getOwnPropertyDescriptor,ji=(s,e,t,i)=>{for(var n=i>1?void 0:i?I2(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&&D2(e,t,n),n};const sr=x("debugbutton");class Qo{colorMultiplier;disabledColor;fadeDuration;highlightedColor;normalColor;pressedColor;selectedColor}ji([p()],Qo.prototype,"colorMultiplier",2);ji([p(oe)],Qo.prototype,"disabledColor",2);ji([p()],Qo.prototype,"fadeDuration",2);ji([p(oe)],Qo.prototype,"highlightedColor",2);ji([p(oe)],Qo.prototype,"normalColor",2);ji([p(oe)],Qo.prototype,"pressedColor",2);ji([p(oe)],Qo.prototype,"selectedColor",2);class L2{disabledTrigger;highlightedTrigger;normalTrigger;pressedTrigger;selectedTrigger}class Ys extends T{click(){this.onClick?.invoke()}onClick=new Z;_isHovered=0;onPointerEnter(e){const t=e.event.pointerType==="mouse"&&e.button===0;t&&(this._isHovered+=1),sr&&console.warn("Button Enter",t,this._isHovered,this.animationTriggers?.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.highlightedTrigger):this.transition===1&&this.colors&&this._image?.setState("hovered"),t&&this.context.input.setCursor("pointer"))}onPointerExit(){this._isHovered-=1,this._isHovered<0&&(this._isHovered=0),sr&&console.log("Button Exit",this._isHovered,this.animationTriggers?.highlightedTrigger,this.animator),this.interactable&&(this._isHovered>0||(this._isHovered=0,this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&this._image?.setState("normal"),this.context.input.unsetCursor("pointer")))}onPointerDown(e){sr&&console.log("Button Down",this.animationTriggers?.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&this._image?.setState("pressed"))}onPointerUp(e){sr&&console.warn("Button Up",this.animationTriggers?.highlightedTrigger,this.animator,this._isHovered),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this._isHovered?this.animationTriggers.highlightedTrigger:this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&this._image?.setState(this._isHovered?"hovered":"normal"))}onPointerClick(e){if(this.interactable&&!(e.button!==0&&e.event.pointerType===Lf.Mouse)&&(sr&&(console.warn("Button Click",this.onClick),Re("CLICKED button "+this.name+" at "+this.context.time.frameCount)),this.onClick&&this.onClick.listenerCount>0&&(this.onClick.invoke(),e.use(),this.context.accessibility.focus(this),sr))){const t=this.gameObject.worldPosition;t.add(this.gameObject.worldUp.multiplyScalar(1+Math.random()*.5)),B.DrawLabel(t,"CLICK:"+Date.now(),.1,1+Math.random()*.5)}}colors;transition;animationTriggers;animator;set interactable(e){this._interactable=e,this._image&&(this._image.setInteractable(e),e?this._image.setState("normal"):this._image.setState("disabled"))}get interactable(){return this._interactable}_interactable=!0;set_interactable(e){this.interactable=e}awake(){super.awake(),sr&&console.log(this),this._isInit=!1,this.init()}start(){this._image?.setInteractable(this.interactable),this.gameObject.getComponentInParent(fh)||this.gameObject.addComponent(Yf)}onEnable(){super.onEnable(),this.context.accessibility.updateElement(this,{role:"button",label:this.gameObject.name+" button",hidden:!1})}onDisable(){super.onDisable(),this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this),this._isHovered&&this.context.input.unsetCursor("pointer")}_requestedAnimatorTrigger;*setAnimatorTriggerAtEndOfFrame(e){this._requestedAnimatorTrigger=e,yield,yield,this._requestedAnimatorTrigger==e&&this.animator?.setTrigger(e)}_isInit=!1;_image;init(){this._isInit||(this._isInit=!0,this._image=P.getComponent(this.gameObject,ql),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){e.setInteractable(this.interactable);const t=this.getFinalColor(e.color,this.colors?.normalColor),i={state:"normal",attributes:{backgroundColor:t,backgroundOpacity:t.alpha}};e.setupState(i);const n=this.getFinalColor(e.color,this.colors?.highlightedColor),o={state:"hovered",attributes:{backgroundColor:n,backgroundOpacity:n.alpha}};e.setupState(o);const r=this.getFinalColor(e.color,this.colors?.pressedColor),a={state:"pressed",attributes:{backgroundColor:r,backgroundOpacity:r.alpha}};e.setupState(a);const l=this.getFinalColor(e.color,this.colors?.selectedColor),h={state:"selected",attributes:{backgroundColor:l,backgroundOpacity:l.alpha}};e.setupState(h);const d=this.getFinalColor(e.color,this.colors?.disabledColor),u={state:"disabled",attributes:{backgroundColor:d,backgroundOpacity:d.alpha}};e.setupState(u)}getFinalColor(e,t){return t?e.clone().multiply(t).convertLinearToSRGB():e.clone().convertLinearToSRGB()}}ji([p(Z)],Ys.prototype,"onClick",2);ji([p(Qo)],Ys.prototype,"colors",2);ji([p()],Ys.prototype,"transition",2);ji([p(L2)],Ys.prototype,"animationTriggers",2);ji([p(vt)],Ys.prototype,"animator",2);ji([p()],Ys.prototype,"interactable",1);var B2=Object.defineProperty,jp=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&B2(e,t,n),n};const ao=x("debuginputfield"),dd=class H extends T{get text(){return this.textComponent?.text??""}set text(e){this.textComponent&&(this.textComponent.text=e,this.placeholder&&(e.length>0?this.placeholder.gameObject.visible=!1:this.placeholder.gameObject.visible=!0))}get isFocused(){return H.active===this}textComponent;placeholder;onValueChanged;onEndEdit;static active=null;static activeTime=-1;static htmlField=null;static htmlFieldFocused=!1;inputEventFn;_iosEventFn;start(){ao&&console.log(this.name,this)}onEnable(){H.htmlField||(H.htmlField=document.createElement("input"),H.htmlField.style.width="0px",H.htmlField.style.height="0px",H.htmlField.style.padding="0px",H.htmlField.style.border="none",H.htmlField.style.overflow="hidden",H.htmlField.style.caretColor="transparent",H.htmlField.style.outline="none",H.htmlField.classList.add("ar"),H.htmlField.onfocus=()=>H.htmlFieldFocused=!0,H.htmlField.onblur=()=>H.htmlFieldFocused=!1,document.body.append(H.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),H.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&this.textComponent?.text.length&&P.setActive(this.placeholder.gameObject,!1),exports.DeviceUtilities.isiOS()&&(this._iosEventFn=this.processInputOniOS.bind(this),window.addEventListener("click",this._iosEventFn))}onDisable(){H.htmlField?.removeEventListener("keyup",this.inputEventFn),this.onDeselected(),this._iosEventFn&&window.removeEventListener("click",this._iosEventFn)}clear(){H.active===this&&H.htmlField?(H.htmlField.value="",this.setTextFromInputField()):(this.textComponent&&(this.textComponent.text=""),this.placeholder&&P.setActive(this.placeholder.gameObject,!0))}select(){this.onSelected()}deselect(){this.onDeselected()}onPointerEnter(e){e.event.pointerType==="mouse"&&e.button===0&&this.context.input.setCursor("text")}onPointerExit(e){this.context.input.unsetCursor("text")}onPointerClick(e){ao&&console.log("CLICK",e,H.active),H.activeTime=this.context.time.time,H.active!==this&&this.startCoroutine(this.activeLoop(),Ce.LateUpdate),this.selectInputField()}*activeLoop(){for(this.onSelected();H.active===this&&!(this.context.input.getPointerClicked(0)&&this.context.time.time-H.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){if(H.active!==this&&(ao&&console.log("Select",this.name,this,H.htmlField,this.context.isInXR,this.context.arOverlayElement,this.textComponent?.text,H.htmlField?.value),H.active?.onDeselected(),H.active=this,this.placeholder&&P.setActive(this.placeholder.gameObject,!1),H.htmlField)){if(H.htmlField.value=this.textComponent?.text||"",ao&&console.log("set input field value",H.htmlField.value),this.context.isInXR){const e=this.context.arOverlayElement;e&&e.append(H.htmlField)}this.selectInputField()}}onDeselected(){H.active===this&&(H.active=null,ao&&console.log("Deselect",this.name,this),H.htmlField&&(H.htmlField.blur(),document.body.append(H.htmlField)),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&P.setActive(this.placeholder.gameObject,!0),H.htmlField&&this.onEndEdit?.invoke(H.htmlField.value))}update(){H.active===this&&this.textComponent?.markDirty()}onInput(e){if(H.active===this){if(ao&&console.log(e.code,e,H.htmlField?.value,this.textComponent?.text),e.code==="Escape"||e.code==="Enter"){this.onDeselected();return}H.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&P.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){if(this.textComponent&&H.htmlField){const e=this.textComponent.text,t=H.htmlField.value,i=this.textComponent.text!==H.htmlField.value;this.textComponent.text=H.htmlField.value,i&&(ao&&console.log("[InputField] value changed:",t,e),this.onValueChanged?.invoke(t,e))}}selectInputField(){H.htmlField&&(ao&&console.log("Focus Inputfield",H.htmlFieldFocused,H.htmlField),H.htmlField.setSelectionRange(H.htmlField.value.length,H.htmlField.value.length),exports.DeviceUtilities.isiOS()?(H.htmlField.style.display="block",H.htmlField.focus({preventScroll:!0})):setTimeout(()=>H.htmlField?.focus(),1))}processInputOniOS(){const e=this.context.physics.raycast();if(!e.length)return;const i=e[0].object,n=g_(i);(n?.gameObject===this.gameObject||n?.gameObject.parent===this.gameObject)&&this.selectInputField()}};jp([p(Nt)],dd.prototype,"textComponent");jp([p(Nt)],dd.prototype,"placeholder");jp([p(Z)],dd.prototype,"onValueChanged");jp([p(Z)],dd.prototype,"onEndEdit");let Db=dd;var F2=Object.defineProperty,H1=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&F2(e,t,n),n};class ud extends T{id=null;keepAspect=!1;_object=null;onEnable(){if(this._object){this.gameObject.add(this._object);return}if(!this.id||!this.context.mainCamera)return;const e=document.getElementById(this.id);if(!e){console.warn('Could not find element with id "'+this.id+'"');return}e.style.display="block",e.style.visibility="hidden";const t=new V.InteractiveGroup;t.listenToPointerEvents(this.context.renderer,this.context.mainCamera),this.gameObject.add(t);const i=new V.HTMLMesh(e);t.add(i),i.visible=!1;const n=i.material;n.transparent=!0,setTimeout(()=>{i.visible=!0;const o=Of(this.gameObject).clone();Ph(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();const r=new c.Box3;r.setFromObject(t),this.setWorldRotation(o.x,o.y,o.z);const a=r.max.x-r.min.x,l=r.max.y-r.min.y;if(this.keepAspect){const d=a/l;a>l?i.scale.set(1/a,1/l/d,1):i.scale.set(1/a*d,1/l,1)}else i.scale.set(1/a,1/l,1);const h=this.gameObject.scale;i.scale.multiply(h)},1)}onDisable(){this._object?.removeFromParent()}}H1([p()],ud.prototype,"id");H1([p()],ud.prototype,"keepAspect");var j2=Object.defineProperty,Up=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&j2(e,t,n),n};const fd=class q1 extends T{target;invertForward=!1;keepUpDirection=!0;copyTargetRotation=!1;static flipYQuat=new c.Quaternion().setFromAxisAngle(new c.Vector3(0,1,0),Math.PI);onBeforeRender(){let e=this.target;if(e||(e=this.context.mainCamera,E()&&!this.__did_warn&&(this.__did_warn=!0,console.debug(`[LookAt] No target set on ${this.name}, using main camera as target.`))),!e)return;let t=this.copyTargetRotation;(this.context.isInVR||this.context.isInPassThrough)&&(t=!1),Ch(this.gameObject,e,this.keepUpDirection,t),this.invertForward&&this.gameObject.quaternion.multiply(q1.flipYQuat)}createBehaviours(e,t,i){if(t.uuid===this.gameObject.uuid){let n=t;if(this.keepUpDirection){const r=nt.createEmptyParent(t);n=r;const a=this.invertForward?-1:1;r.setMatrix(r.getMatrix().multiply(new c.Matrix4().makeRotationZ(Math.PI/2*a))),t.setMatrix(t.getMatrix().multiply(new c.Matrix4().makeRotationZ(-Math.PI/2*a)))}const o=new Dt("lookat "+this.name,jt.sceneStartTrigger(),pe.lookAtCameraAction(n,void 0,this.invertForward?qi.back:qi.forward,this.keepUpDirection?qi.up:qi.zero));e.addBehavior(o)}}};Up([p(c.Object3D)],fd.prototype,"target");Up([p()],fd.prototype,"invertForward");Up([p()],fd.prototype,"keepUpDirection");Up([p()],fd.prototype,"copyTargetRotation");let Ib=fd;var U2=Object.defineProperty,Lb=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&U2(e,t,n),n};class Xl extends T{url;mode=0;clickable=!0;async open(){if(!this.url){console.warn("OpenURL: URL is not set, can't open.",this);return}this._validateUrl();let e=this.url;switch(!e.startsWith("mailto:")&&e.includes("@")&&(e="mailto:"+e),this.mode){case 0:exports.DeviceUtilities.isSafari(),globalThis.open(e,"_blank");break;case 1:exports.DeviceUtilities.isSafari()&&exports.DeviceUtilities.isiOS()?globalThis.open(e,"_top"):globalThis.open(e,"_self");break;case 2:exports.DeviceUtilities.isSafari()?globalThis.open(e,"_top"):globalThis.open(e,"_new");break}}start(){this.gameObject.getComponentInParent(Ji)||this.gameObject.addComponent(Ji)}onPointerEnter(e){!e.used&&this.clickable&&this.context.input.setCursor("pointer")}onPointerExit(){this.clickable&&this.context.input.unsetCursor("pointer")}onPointerClick(e){this.clickable&&!e.used&&this.url?.length&&this.open()}_validateUrl(){this.url&&this.url.startsWith("www.")&&(E()&&console.warn("URL is not valid, adding https:// to the start of the URL",this.url),this.url="https://"+this.url)}}Lb([p()],Xl.prototype,"url");Lb([p()],Xl.prototype,"mode");Lb([p()],Xl.prototype,"clickable");If(s=>{const e=s.domElement.getAttribute("clickthrough");if(t(e)){const i=s.scene.addComponent(zp);ju(s.domElement,"clickthrough",()=>{const n=s.domElement.getAttribute("clickthrough");i.enabled=t(n)})}function t(i){return i!==null&&i!=="0"&&i!=="false"}});class zp extends T{_previousPointerEvents="all";onEnable(){this.context.input.addEventListener("pointerdown",this.onPointerEvent),this.context.input.addEventListener("pointermove",this.onPointerEvent,{queue:100}),window.addEventListener("touchstart",this.onTouchStart,{passive:!0}),window.addEventListener("touchend",this.onTouchEnd,{passive:!0}),this._previousPointerEvents=this.context.domElement.style.pointerEvents}onDisable(){this.context.input.removeEventListener("pointerdown",this.onPointerEvent),this.context.input.removeEventListener("pointermove",this.onPointerEvent),window.removeEventListener("touchstart",this.onTouchStart),window.removeEventListener("touchend",this.onTouchEnd),this.context.domElement.style.pointerEvents=this._previousPointerEvents}onPointerEnter(){}onPointerEvent=e=>{if(e.pointerId>0)return;e.intersections?.length<=0?this.context.domElement.style.pointerEvents="none":this.context.domElement.style.pointerEvents="all"};_touchDidHitAnything=!1;onTouchStart=e=>{const t=e.touches[0];if(!t)return;const i=t.clientX/window.innerWidth*2-1,n=-(t.clientY/window.innerHeight)*2+1;this.context.physics.raycast({screenPoint:new c.Vector2(i,n)}).length>0&&(this._touchDidHitAnything=!0)};onTouchEnd=e=>{const t=this._touchDidHitAnything;this._touchDidHitAnything=!1,setTimeout(()=>{t&&(this.context.domElement.style.pointerEvents="all")},100)}}var z2=Object.defineProperty,Np=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&z2(e,t,n),n};const N2=x("debugcursor");class ha extends T{static NAME="CursorFollow";damping=0;useFullPage=!0;keepDistance=!0;snapToSurface=!1;_distance=-1;updateDistance(e=!1){!e&&this.keepDistance&&this._distance!==-1||(this._distance=this.gameObject.worldPosition.distanceTo(this.context.mainCamera.worldPosition))}awake(){this._distance=-1}onEnable(){this._distance=-1,window.addEventListener("pointermove",this._onPointerMove)}onDisable(){window.removeEventListener("pointermove",this._onPointerMove)}_ndc_x=0;_ndc_y=0;_onPointerMove=e=>{if(!this.useFullPage)return;const t=e.clientX,i=e.clientY,n=this.context.domX,o=this.context.domY,r=this.context.domWidth,a=this.context.domHeight;this._ndc_x=(t-n)/r*2-1,this._ndc_y=-(i-o)/a*2+1};lateUpdate(){this.updateDistance();const e=this.useFullPage?this._ndc_x:this.context.input.mousePositionRC.x,t=this.useFullPage?this._ndc_y:this.context.input.mousePositionRC.y,i=this.context.mainCamera,n=i.worldPosition,o=F(e,t,1).unproject(i);o.sub(n).normalize();const r=F(o).multiplyScalar(this._distance).add(n);let a=r;if(this.damping>0){const l=this.gameObject.worldPosition;l.lerp(r,this.context.time.deltaTime/this.damping),this.gameObject.worldPosition=l,a=l}else this.gameObject.worldPosition=r;if(this.snapToSurface){Zm.origin=n,Zm.direction=o;const l=this.context.physics.raycastFromRay(Zm,{testObject:h=>h!==this.gameObject&&!this.gameObject.contains(h)});if(l?.length){const h=l[0];h&&(this.damping>0?this.gameObject.worldPosition=a.lerp(h.point,this.context.time.deltaTime/this.damping):this.gameObject.worldPosition=h.point,N2&&B.DrawLine(h.point,h.normal.add(h.point),65280))}}}}Np([p()],ha.prototype,"damping");Np([p()],ha.prototype,"useFullPage");Np([p()],ha.prototype,"keepDistance");Np([p()],ha.prototype,"snapToSurface");const Zm=new c.Ray;var $2=Object.defineProperty,V2=Object.getOwnPropertyDescriptor,Ql=(s,e,t,i)=>{for(var n=i>1?void 0:i?V2(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&&$2(e,t,n),n};exports.HoverAnimation=class extends T{type="linear";duration=.1;scaleFactor=1.1;hovered=null;idle=null;animation=null;start(){this.idle||(this.idle=exports.AnimationUtils.emptyClip()),(!this.hovered||!(this.hovered instanceof c.AnimationClip))&&(this.hovered=exports.AnimationUtils.createScaleClip({type:"linear",duration:this.duration||.1,scale:this.gameObject.scale,scaleFactor:this.scaleFactor||1.1})),this.animation??=this.gameObject.addComponent(Ut),this.animation.playAutomatically=!1,this.playIdle()}onEnable(){this.animation&&(this.animation.enabled=!0),this.playIdle()}onDisable(){this.animation&&(this.animation.enabled=!1),this.playIdle()}onPointerEnter(){this.playHover()}onPointerExit(){this.playIdle()}playIdle(){this.idle&&this.animation?.play(this.idle,{exclusive:!0,fadeDuration:.1,loop:!0})}playHover(){this.hovered&&this.animation?.play(this.hovered,{exclusive:!0,fadeDuration:.1,loop:!1,clampWhenFinished:!0})}};Ql([p()],exports.HoverAnimation.prototype,"type",2);Ql([p()],exports.HoverAnimation.prototype,"duration",2);Ql([p()],exports.HoverAnimation.prototype,"scaleFactor",2);Ql([p(c.AnimationClip)],exports.HoverAnimation.prototype,"hovered",2);Ql([p(c.AnimationClip)],exports.HoverAnimation.prototype,"idle",2);exports.HoverAnimation=Ql([Ly],exports.HoverAnimation);var W2=Object.defineProperty,da=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&W2(e,t,n),n};typeof window<"u"&&Promise.resolve().then(()=>require("./vendor-BJviq-Oq.umd.cjs")).then(s=>s.scrollTimeline);const bs=x("debugscroll");class gs extends T{target=null;damping=0;invert=!1;htmlSelector=null;mode="window";useTopWindowScroll=!0;changed=new Z;get currentValue(){return this._current_value}_current_value=0;_target_value=0;_appliedValue=-1;_needsUpdate=!1;_firstUpdate=!1;_scrollWindow=null;_wheelTarget=null;_crossOriginWarned=!1;_viewTimelineWarned=!1;awake(){this._firstUpdate=!0}onEnable(){this.rebindScrollListener(),this._appliedValue=-1,this._needsUpdate=!0}onDisable(){this._wheelTarget?.removeEventListener("wheel",this.updateCurrentScrollValue),this._wheelTarget=null}onValidate(e){e==="useTopWindowScroll"&&this._wheelTarget&&(this.rebindScrollListener(),this._needsUpdate=!0)}resolveScrollWindow(){if(!this.useTopWindowScroll)return window;const e=window.top;if(!e||e===window.self)return window;try{return e.document,e}catch{return this._crossOriginWarned||(this._crossOriginWarned=!0,(bs||E())&&console.warn("[ScrollFollow] useTopWindowScroll is enabled but the top-level window is cross-origin and cannot be read. Falling back to the local window. Supporting cross-origin embeds requires a postMessage scroll bridge from the host page.")),window}}rebindScrollListener(){const e=this.resolveScrollWindow();this._scrollWindow=e,e!==this._wheelTarget&&(this._wheelTarget?.removeEventListener("wheel",this.updateCurrentScrollValue),this._wheelTarget=e,e.addEventListener("wheel",this.updateCurrentScrollValue,{passive:!0}),this._lastSelectorValue=null,this._lastSelectorElement=null,bs&&console.debug(`[ScrollFollow] Scroll listener bound to ${e===window?"local window":"top-level window"}`,{scrollWindow:this._scrollWindow,isTopWindow:e===window}))}lateUpdate(){if(this.updateCurrentScrollValue(),this._target_value>=0&&(this.damping>0&&!this._firstUpdate?(this._current_value=L.lerp(this._current_value,this._target_value,this.context.time.deltaTime/this.damping),Math.abs(this._current_value-this._target_value)<.001&&(this._current_value=this._target_value)):this._current_value=this._target_value),this._needsUpdate||this._current_value!==this._appliedValue){this._appliedValue=this._current_value,this._needsUpdate=!1;let e=!1;if(this.changed.listenerCount>0){const t={type:"change",value:this._current_value,component:this,preventDefault:()=>{t.defaultPrevented=!0},defaultPrevented:!1};this.changed.invoke(t),e=t.defaultPrevented}if(!e){const t=this.invert?1-this._current_value:this._current_value;Array.isArray(this.target)?this.target.forEach(i=>i&&this.applyScroll(i,t)):this.target&&this.applyScroll(this.target,t),bs&&this.context.time.frame%30===0&&console.debug(`[ScrollFollow] ${this._current_value.toFixed(5)} — ${(this._target_value*100).toFixed(0)}%, targets [${Array.isArray(this.target)?this.target.length:1}]`)}this._firstUpdate=!1}}_lastSelectorValue=null;_lastSelectorElement=null;updateCurrentScrollValue=()=>{const e=this._scrollWindow??window,t=e.document,i=t.scrollingElement??t.documentElement;switch(this.mode){case"window":if(this.htmlSelector?.length){if(this.htmlSelector!==this._lastSelectorValue&&(this._lastSelectorElement=t.querySelector(this.htmlSelector),this._lastSelectorValue=this.htmlSelector),this._lastSelectorElement){const n=this._lastSelectorElement.getBoundingClientRect();this._target_value=-n.top/(n.height-e.innerHeight);break}}else{const n=i.scrollHeight-i.clientHeight;n<=0||(this._target_value=i.scrollTop/n)}break}(isNaN(this._target_value)||!isFinite(this._target_value))&&(this._target_value=-1),bs&&console.debug(`[ScrollFollow] Scroll value updated: ${this._target_value.toFixed(5)} (ScrollTop: ${i.scrollTop}, ScrollHeight: ${i.scrollHeight}, ClientHeight: ${i.clientHeight})`)};applyScroll(e,t){if(e)if(e instanceof ml)this.handleTimelineTarget(e,t),e.isPlaying&&e.pause(),e.evaluate();else if(e instanceof vt)e.setFloat("scroll",t);else if(e instanceof Ut)e.time=t*e.duration;else if(e instanceof Ei){if(!e.duration)return;e.time=t*e.duration}else if(e instanceof ln)e.position01=t;else if(e instanceof Lt)e.intensity=t;else if(e instanceof c.Object3D){const i=e;i["needle:scrollbounds"]===void 0&&(i["needle:scrollbounds"]=pi(e)||null);const n=i["needle:scrollbounds"];n&&(e.position.y=-n.min.y-t*(n.max.y-n.min.y))}else"scroll"in e&&(typeof e.scroll=="number"?e.scroll=t:typeof e.scroll=="function"&&e.scroll(t))}handleTimelineTarget(e,t){const i=this._scrollWindow??window,n=i.document,o=e.duration;let r=Jm.get(e);if(!r){r=[],Jm.set(e,r);let d=0;for(const f of e.foreachMarker("ScrollMarker")){const m=d++;if(f.element===void 0||f.needsUpdate===!0||f.element&&!f.element?.parentNode){f.needsUpdate=!1;try{if(f.element=X1(m,n),bs&&console.debug(`ScrollMarker #${m} (${f.time.toFixed(2)}) found`,f.element),!f.element){(bs||E())&&console.warn(`No HTML element found for ScrollMarker: ${f.name} (index ${m})`);continue}}catch(g){f.element=null,console.error("ScrollMarker selector is not valid: "+f.name+`
|
|
1528
|
+
C) Set "joinRandomRoom" to true`),!1):(hu&&console.log("Join "+this.roomName),this._userWantsToBeInARoom=!0,this.context.connection.joinRoom(this.roomName),!0))}_lastPingTime=0;_lastRoomTime=-1;_userWantsToBeInARoom=!1;update(){this.context.connection.isConnected&&(this.context.time.time-this._lastPingTime>3&&(this._lastPingTime=this.context.time.time,this.context.connection.sendPing()),this.context.connection.isInRoom&&(this._lastRoomTime=this.context.time.time)),this._lastRoomTime>0&&this.context.time.time-this._lastRoomTime>.3&&(this._lastRoomTime=-1,this.autoRejoin?this._userWantsToBeInARoom&&(console.log("Disconnected from networking backend - attempt reconnecting now"),this.tryJoinRoom()):E()&&console.warn("You are not connected to a room anymore (possibly because the tab was inactive for too long and the server kicked you?)"))}getViewOnlyUrl(){if(this.context.connection.isConnected&&this.context.connection.currentRoomViewId){const e=window.location.search,t=new URLSearchParams(e);return t.has(this.urlParameterName)&&t.delete(this.urlParameterName),t.set(Km,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}setRandomRoomUrlParameter(){const e=xh(),t=this.generateRoomName();x(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),Sy(t,e)}generateRoomName(){let e="";for(let t=0;t<6;t++)e+=Math.floor(Math.random()*10).toFixed(0);return e}_roomButton;_roomButtonIconJoin;_roomButtonIconLeave;createRoomButton(){if(this._roomButton)return this._roomButton;const e=document.createElement("button");return this._roomButton=e,e.classList.add("create-room-button"),e.setAttribute("priority","90"),e.onclick=()=>{if(this.context.connection.isInRoom)this.urlParameterName&&Yc(this.urlParameterName,null),this.context.connection.leaveRoom(),this._userWantsToBeInARoom=!1;else{if(this.urlParameterName){const t=x(this.urlParameterName);(!t||t===!0)&&(this._lastJoinedRoom?Yc(this.urlParameterName,this._lastJoinedRoom):this.setRandomRoomUrlParameter())}this.tryJoinRoom()}},this._roomButtonIconJoin=bt("group"),this._roomButtonIconLeave=bt("group_off"),this.updateRoomButtonState(),this.context.connection.beginListen(te.JoinedRoom,this.updateRoomButtonState),this.context.connection.beginListen(te.LeftRoom,this.updateRoomButtonState),e}updateRoomButtonState=()=>{this._roomButton&&(this.context.connection.isInRoom?(this._roomButton.title="Leave the networked room",this._roomButton.textContent="Leave Room",this._roomButtonIconJoin?.remove(),this._roomButton.prepend(this._roomButtonIconLeave)):(this._roomButton.title="Create or join a networked room",this._roomButton.textContent="Join Room",this._roomButtonIconLeave?.remove(),this._roomButton.prepend(this._roomButtonIconJoin)))};destroyRoomButton(){this.context.connection.stopListen(te.JoinedRoom,this.updateRoomButtonState),this.context.connection.stopListen(te.LeftRoom,this.updateRoomButtonState)}_viewOnlyButton;onEnableViewOnlyButton(){this.context.connection.isConnected?this.onCreateViewOnlyButton():(this.context.connection.stopListen(te.JoinedRoom,this.onCreateViewOnlyButton),this.context.connection.beginListen(te.JoinedRoom,this.onCreateViewOnlyButton))}onDisableViewOnlyButton(){this.context.connection.stopListen(te.JoinedRoom,this.onCreateViewOnlyButton),this._viewOnlyButton?.remove()}onCreateViewOnlyButton=()=>{if(!this._viewOnlyButton){const e=document.createElement("button");this._viewOnlyButton=e,e.classList.add("view-only-button"),e.setAttribute("priority","90"),e.onclick=()=>{const t=this.getViewOnlyUrl();t?.length?navigator.canShare({url:t})?navigator.share({url:t})?.catch(i=>{console.warn(i)}):(navigator.clipboard.writeText(t),Re("View only URL copied to clipboard")):de("Could not create view only URL")},e.title="Copy the view only URL: A page accessed by the view only URL can not be modified by visiting users.",e.textContent="Share View URL",e.prepend(bt("visibility"))}this.context.menu.appendChild(this._viewOnlyButton)}}Xo([p()],Rn.prototype,"roomName",2);Xo([p()],Rn.prototype,"urlParameterName",2);Xo([p()],Rn.prototype,"joinRandomRoom",2);Xo([p()],Rn.prototype,"requireRoomParameter",2);Xo([p()],Rn.prototype,"autoRejoin",2);Xo([p()],Rn.prototype,"createJoinButton",2);Xo([p()],Rn.prototype,"createViewOnlyButton",2);Xo([p()],Rn.prototype,"roomPrefix",1);var S2=Object.defineProperty,C2=Object.getOwnPropertyDescriptor,Hl=(s,e,t,i)=>{for(var n=i>1?void 0:i?C2(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&&S2(e,t,n),n};const P2="noVoip",k2=x("debugvoip");class Qs extends T{autoConnect=!0;runInBackground=!0;createMenuButton=!0;debug=!1;_volume=1;get volume(){return this._volume}set volume(e){if(Number.isNaN(e))return;const t=Math.max(0,Math.min(1,e));this._volume=t;for(const i of this._incomingStreams.values())i.volume=t}getAudioElement(e){return this._incomingStreams.get(e)}get incomingStreams(){return this._incomingStreams}speakingThreshold=.1;onSpeakingChanged=new Z;_speakingStates=new Map;_analysers=new Map;_sharedAudioContext;_lastSpeakingPollMs=0;_net;_menubutton;awake(){k2&&(this.debug=!0),this.debug&&(console.log("VOIP debugging: press 'v' to toggle incoming mute, 'c' to toggle connect/disconnect"),window.addEventListener("keydown",async e=>{switch(e.key.toLowerCase()){case"v":console.log("VOIP: toggle incoming mute → ",!this.isMuted),this.setMuted(!this.isMuted);break;case"c":this.isSending?this.disconnect():this.connect();break}}))}onEnable(){this._net||(this._net=rd.create(this)),this.debug&&(this._net.debug=!0),this._net.addEventListener(is.StreamReceived,this.onReceiveStream),this._net.addEventListener(is.StreamEnded,this.onStreamEnded),this._net.enable(),this.autoConnect&&this.context.connection.isConnected&&this.connect(),this.context.connection.beginListen(te.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(te.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.addEventListener("visibilitychange",this.onVisibilityChanged)}onDisable(){this._net&&(this._net.stopSendingStream(this._outputStream),this._net.removeEventListener(is.StreamReceived,this.onReceiveStream),this._net.removeEventListener(is.StreamEnded,this.onStreamEnded),this._net?.disable()),this.context.connection.stopListen(te.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(te.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.removeEventListener("visibilitychange",this.onVisibilityChanged);for(const e of[...this._analysers.keys()])this.cleanupAnalyser(e);this.closeSharedAudioContext()}onDestroy(){this._menubutton?.remove(),this._menubutton=void 0;for(const e of[...this._analysers.keys()])this.cleanupAnalyser(e);this.closeSharedAudioContext();for(const e of this._incomingStreams.values())Hi(e.srcObject);this._incomingStreams.clear(),this._speakingStates.clear()}_allowSending=!0;_outputStream=null;_connectInFlight;get isSending(){return this._outputStream!=null&&this._outputStream.active}connect(e){return this._connectInFlight?this._connectInFlight:(this._connectInFlight=this._connectImpl(e).finally(()=>{this._connectInFlight=void 0}),this._connectInFlight)}async _connectImpl(e){if(!this._net)return console.error("Cannot connect to voice chat - NetworkedStreams not initialized. Make sure the component is enabled before calling this method."),!1;if(this.context.connection.isConnected){if(!await exports.DeviceUtilities.microphonePermissionsGranted())return console.error("Cannot connect to voice chat - microphone permissions not granted"),this.updateButton(),!1}else return console.error("Cannot connect to voice chat - not connected to server"),this.updateButton(),!1;return this._allowSending=!0,this._net?.stopSendingStream(this._outputStream),Hi(this._outputStream),this._outputStream=await this.getAudioStream(e),this._outputStream?(this.debug&&console.log("VOIP: Got audio stream"),this._net?.startSendingStream(this._outputStream),this.updateButton(),!0):(this.updateButton(),await exports.DeviceUtilities.microphonePermissionsGranted()?console.error("VOIP: Could not get audio stream - please make sure to connect an audio device and grant microphone permissions"):wl("Microphone permissions not granted: Please grant microphone permissions to use voice chat"),(this.debug||E())&&console.log("VOIP: Failed to get audio stream"),!1)}disconnect(e){e?.remember&&(this._allowSending=!1),this._net?.stopSendingStream(this._outputStream),Hi(this._outputStream),this._outputStream=null,this.updateButton()}setMuted(e){for(const t of this._incomingStreams.values())t.muted=e}get isMuted(){if(this._incomingStreams.size===0)return!1;for(const e of this._incomingStreams.values())if(!e.muted)return!1;return!0}async updateButton(){if(this.createMenuButton){if(this._menubutton||(this._menubutton=document.createElement("button"),this._menubutton.addEventListener("click",()=>{this.isSending?this.disconnect({remember:!0}):this.connect(),exports.DeviceUtilities.microphonePermissionsGranted().then(e=>{e||de("<strong>Microphone permissions not granted</strong>. Please allow your browser to use the microphone to be able to talk. Click on the button on the left side of your browser's address bar to allow microphone permissions.")})})),this._menubutton){this.context.menu.appendChild(this._menubutton),this.activeAndEnabled?this._menubutton.style.display="":this._menubutton.style.display="none",this._menubutton.title=this.isSending?"Click to disable your microphone":"Click to enable your microphone";let e=(this.isSending,""),t=this.isSending?"mic":"mic_off";await exports.DeviceUtilities.microphonePermissionsGranted()||(e="No Permission",t="mic_off",this._menubutton.title="Microphone permissions not granted. Please allow your browser to use the microphone to be able to talk. This can usually be done in the addressbar of the webpage."),this._menubutton.innerText=e,this._menubutton.prepend(bt(t)),this.context.connection.isConnected==!1?this._menubutton.setAttribute("disabled",""):this._menubutton.removeAttribute("disabled")}}else this.activeAndEnabled||this._menubutton?.remove()}getFrequency(e){return this.unsupported_getfrequency||(this.unsupported_getfrequency=!0,E()&&de("VOIP: getFrequency is currently not supported"),console.warn("VOIP: getFrequency is currently not supported")),null}async getAudioStream(e){if(!navigator.mediaDevices.getUserMedia)return console.error("No getDisplayMedia support"),null;const t=async n=>await navigator.mediaDevices.getUserMedia({audio:n??!0,video:!1}).catch(o=>(console.warn("VOIP failed getting audio stream",o),null)),i=await t(e);if(!i)return null;if(exports.DeviceUtilities.isiOS()&&e?.deviceId===void 0){const o=(await navigator.mediaDevices.enumerateDevices()).find(r=>(r.kind==="audioinput"||r.kind==="audiooutput")&&!r.label.includes("iPhone"));if(o){const r=Object.assign({},e);r.deviceId=o.deviceId;const a=await t(r);if(a)return Hi(i),a}}return i}onJoinedRoom=async()=>{this.debug&&console.log("VOIP: Joined room"),await Ds(300),this.autoConnect&&!this.isSending&&this._allowSending&&this.connect()};onLeftRoom=()=>{this.debug&&console.log("VOIP: Left room"),this.disconnect();for(const e of this._incomingStreams.values())Hi(e.srcObject);this._incomingStreams.clear();for(const e of this._analysers.keys())this.cleanupAnalyser(e)};_incomingStreams=new Map;update(){if(!this.onSpeakingChanged||this.onSpeakingChanged.listenerCount<=0)return;const e=performance.now();if(!(e-this._lastSpeakingPollMs<100)){this._lastSpeakingPollMs=e;for(const[t,i]of this._analysers){i.analyser.getByteFrequencyData(i.data);let n=0;for(let l=0;l<i.data.length;l++)n+=i.data[l];const o=n/i.data.length/255,r=this._speakingStates.get(t)??!1,a=o>this.speakingThreshold;a!==r&&(this._speakingStates.set(t,a),this.onSpeakingChanged.invoke({userId:t,isSpeaking:a,volume:o}))}}}setupAnalyser(e,t,i){if(!this._analysers.has(e))try{this._sharedAudioContext||(this._sharedAudioContext=new AudioContext);const n=this._sharedAudioContext,o=n.createMediaStreamSource(i),r=n.createAnalyser();r.fftSize=256,o.connect(r);const a=new Uint8Array(r.frequencyBinCount);this._analysers.set(e,{source:o,analyser:r,data:a})}catch(n){this.debug&&console.warn("VOIP: Failed to create analyser for",e,n)}}cleanupAnalyser(e){const t=this._analysers.get(e);t&&(t.source.disconnect(),t.analyser.disconnect(),this._analysers.delete(e)),this._speakingStates.delete(e)}closeSharedAudioContext(){this._sharedAudioContext&&(this._sharedAudioContext.close(),this._sharedAudioContext=void 0)}onReceiveStream=e=>{const t=e.target.userId,i=e.stream;let n=this._incomingStreams.get(t);n||(n=new Audio,this._incomingStreams.set(t,n)),n.srcObject=i,n.volume=this._volume,n.setAttribute("autoplay","true"),this.setupAnalyser(t,n,i),wn.registerWaitForInteraction(()=>{n?.play().catch(o=>{console.error("VOIP: Failed to play audio",o)})})};onStreamEnded=e=>{const t=this._incomingStreams.get(e.userId);Hi(t?.srcObject),this._incomingStreams.delete(e.userId),this.cleanupAnalyser(e.userId)};onEnabledChanged=()=>{for(const e of this._incomingStreams){const t=e[1];t.muted=!this.enabled}};onVisibilityChanged=()=>{if(this.runInBackground)return;const e=document.visibilityState!=="visible";this.setMuted(e);const t=this._outputStream?.getAudioTracks();if(t)for(const i of t)i.enabled=!e}}Hl([p()],Qs.prototype,"autoConnect",2);Hl([p()],Qs.prototype,"runInBackground",2);Hl([p()],Qs.prototype,"createMenuButton",2);Hl([p()],Qs.prototype,"volume",1);Hl([p()],Qs.prototype,"speakingThreshold",2);Hl([p(Z)],Qs.prototype,"onSpeakingChanged",2);function M2(){const s=x("testwindowcount")||0;s&&s>0&&O2(s)}function O2(s){if(x("testwindow"))return null;const e=new URL(window.location.href);cg(e.searchParams,P2,1),cg(e.searchParams,"testwindow",1);const t=e.toString(),i=[];window.onbeforeunload=()=>{for(const l of i)l.close()};const n=.05,o=128;let r=0,a=0;for(let l=0;l<s;l++){r*o+o*.01>=window.innerWidth&&(a+=1,r=0);const h=r*(o*(1+n))+window.screenLeft,d=a*(o*(1+n))+window.screenTop+90+60*a;r+=1;const u=window.open(t,"test window "+l,`popup=yes width=${o} height=${o} top=${d} left=${h}`);if(!u){console.warn("Failed to open window");continue}i.push(u),u.onload=()=>{u.onbeforeunload=()=>{for(let f=0;f<i.length;f++){const m=i[f];m!==u&&m.close()}i.length=0}}}return i}class Rb extends T{awake(){M2()}}class Tb extends T{transformsPerFrame=10;interval=0;useFlatbuffers=!0;awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinary(uh,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new E2(this.context.connection.connectionId+"_simulatedTransform_"+e,this))}}builder=null;models=null;update(){if(this.context.connection.isConnected){if(this.useFlatbuffers){if(!this.context.connection.connectionId||this.context.time.frameCount%this.interval!==0)return;this.builder===null&&(this.builder=new ee.Builder(1024));const e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();const i=cC(this.context.connection.connectionId,this);this.context.connection.sendBinary(i)}}else if(this.models)for(let e=0;e<this.models.length;e++){const t=this.models[e];t.dontSave=!0,t.update(this,null),this.context.connection.send("TestSimulateUserData-"+e,t)}}}}class E2{guid;fast=!1;position;rotation;velocity=void 0;dontSave;isValid(){return this.fast!==void 0||this.position!==void 0||this.rotation!==void 0||this.velocity!==void 0}constructor(e,t){this.guid=e,this.position={x:0,y:0,z:0},this.rotation={x:0,y:0,z:0,w:0},this.update(t,null)}static temp=new c.Vector3;update(e,t){const i=e.worldPosition;this.position.x=i.x,this.position.y=i.y,this.position.z=i.z;const n=e.worldQuaternion;if(this.rotation.x=n.x,this.rotation.y=n.y,this.rotation.z=n.z,this.rotation.w=n.w,this.fast=!1,t){const o=t.getVelocity();this.velocity===void 0&&(this.velocity={x:0,y:0,z:0}),this.velocity.x=o.x,this.velocity.y=o.y,this.velocity.z=o.z}}}var R2=Object.defineProperty,Lp=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&R2(e,t,n),n};class ca extends T{isGizmo=!1;translationSnap=1;rotationSnapAngle=15;scaleSnap=.25;get control(){return this._control}_control;orbit;onEnable(){if(!(this.isGizmo&&!Oh)&&this.context.mainCamera&&(this._control||(this._control=new V.TransformControls(this.context.mainCamera,this.context.renderer.domElement),this._control.enabled=!0,this._control.getRaycaster().layers.set(2),this._control.size=1,("_root"in this._control?this._control._root:this._control).traverse(t=>{const i=t;if(i.layers.set(2),i){const n=i.material;n&&(n.opacity=.3)}}),this.orbit=P.getComponentInParent(this.context.mainCamera,ue)??void 0),this._control)){const e=this._control.getHelper();this.context.scene.add(e),this._control.attach(this.gameObject),this._control?.addEventListener("dragging-changed",this.onControlChangedEvent),window.addEventListener("keydown",this.windowKeyDownListener),window.addEventListener("keyup",this.windowKeyUpListener)}}onDisable(){this._control?.getHelper()?.removeFromParent(),this._control?.removeEventListener("dragging-changed",this.onControlChangedEvent),window.removeEventListener("keydown",this.windowKeyDownListener),window.removeEventListener("keyup",this.windowKeyUpListener)}enableSnapping(){this._control&&(this._control.setTranslationSnap(this.translationSnap),this._control.setRotationSnap(c.MathUtils.degToRad(this.rotationSnapAngle)),this._control.setScaleSnap(this.scaleSnap))}disableSnapping(){this._control&&(this._control.setTranslationSnap(null),this._control.setRotationSnap(null),this._control.setScaleSnap(null))}onControlChangedEvent=e=>{const t=this.orbit;if(t&&(t.enabled=!e.value),e.value){const i=this.gameObject.getComponentInParent(Sn);i&&(i.fastMode=!0,i.requestOwnership())}else{const i=this.gameObject.getComponentInParent(Sn);i&&(i.fastMode=!1)}};windowKeyDownListener=e=>{if(this.enabled&&this._control)switch(e.keyCode){case 81:this._control.setSpace(this._control.space==="local"?"world":"local");break;case 16:this.enableSnapping();break;case 87:this._control.setMode("translate");break;case 69:this._control.setMode("rotate");break;case 82:this._control.setMode("scale");break;case 187:case 107:this._control.setSize(this._control.size+.1);break;case 189:case 109:this._control.setSize(Math.max(this._control.size-.1,.1));break;case 88:this._control.showX=!this._control.showX;break;case 89:this._control.showY=!this._control.showY;break;case 90:this._control.showZ=!this._control.showZ;break;case 32:this._control.enabled=!this._control.enabled;break}};windowKeyUpListener=e=>{this.enabled&&e.keyCode===16&&this.disableSnapping()}}Lp([p()],ca.prototype,"isGizmo");Lp([p()],ca.prototype,"translationSnap");Lp([p()],ca.prototype,"rotationSnapAngle");Lp([p()],ca.prototype,"scaleSnap");var T2=Object.defineProperty,A2=Object.getOwnPropertyDescriptor,Bp=(s,e,t,i)=>{for(var n=i>1?void 0:i?A2(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&&T2(e,t,n),n};class Ab{texture=null;rect}Bp([p(c.Texture)],Ab.prototype,"texture",2);let ql=class extends Yh{set image(e){this.sprite||(this.sprite=new Ab),this.sprite.texture=e,this.onAfterCreated()}get image(){return this.sprite?this.sprite.texture:null}get sprite(){return this._sprite}set sprite(e){this._sprite!==e&&(this._sprite=e,this.onAfterCreated())}_sprite;pixelsPerUnitMultiplier=1;isBuiltinSprite(){const e=this.sprite;switch(e?.texture?.name){case"InputFieldBackground":case"UISprite":case"Background":case"Knob":return!0}const t=e?.texture?.image;return!!(!e?.texture?.name?.length&&Lc(t)&&t.width===32&&t.height===32)}onBeforeCreate(e){super.onBeforeCreate(e),this.isBuiltinSprite()&&(e.borderRadius=5/this.pixelsPerUnitMultiplier,this.sprite?.texture?.name==="Knob"&&(e.borderRadius=999))}onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture(this.sprite?.texture))}};Bp([p(Ab)],ql.prototype,"sprite",1);Bp([p()],ql.prototype,"pixelsPerUnitMultiplier",2);class Fp extends Yh{get mainTexture(){return this._mainTexture}set mainTexture(e){this._mainTexture!==e&&(this._mainTexture=e,this.onAfterCreated())}_mainTexture;onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),this.setTexture(this.mainTexture))}}Bp([p(c.Texture)],Fp.prototype,"mainTexture",1);var D2=Object.defineProperty,I2=Object.getOwnPropertyDescriptor,ji=(s,e,t,i)=>{for(var n=i>1?void 0:i?I2(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&&D2(e,t,n),n};const sr=x("debugbutton");class Qo{colorMultiplier;disabledColor;fadeDuration;highlightedColor;normalColor;pressedColor;selectedColor}ji([p()],Qo.prototype,"colorMultiplier",2);ji([p(oe)],Qo.prototype,"disabledColor",2);ji([p()],Qo.prototype,"fadeDuration",2);ji([p(oe)],Qo.prototype,"highlightedColor",2);ji([p(oe)],Qo.prototype,"normalColor",2);ji([p(oe)],Qo.prototype,"pressedColor",2);ji([p(oe)],Qo.prototype,"selectedColor",2);class L2{disabledTrigger;highlightedTrigger;normalTrigger;pressedTrigger;selectedTrigger}class Ys extends T{click(){this.onClick?.invoke()}onClick=new Z;_isHovered=0;onPointerEnter(e){const t=e.event.pointerType==="mouse"&&e.button===0;t&&(this._isHovered+=1),sr&&console.warn("Button Enter",t,this._isHovered,this.animationTriggers?.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.highlightedTrigger):this.transition===1&&this.colors&&this._image?.setState("hovered"),t&&this.context.input.setCursor("pointer"))}onPointerExit(){this._isHovered-=1,this._isHovered<0&&(this._isHovered=0),sr&&console.log("Button Exit",this._isHovered,this.animationTriggers?.highlightedTrigger,this.animator),this.interactable&&(this._isHovered>0||(this._isHovered=0,this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&this._image?.setState("normal"),this.context.input.unsetCursor("pointer")))}onPointerDown(e){sr&&console.log("Button Down",this.animationTriggers?.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&this._image?.setState("pressed"))}onPointerUp(e){sr&&console.warn("Button Up",this.animationTriggers?.highlightedTrigger,this.animator,this._isHovered),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this._isHovered?this.animationTriggers.highlightedTrigger:this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&this._image?.setState(this._isHovered?"hovered":"normal"))}onPointerClick(e){if(this.interactable&&!(e.button!==0&&e.event.pointerType===Lf.Mouse)&&(sr&&(console.warn("Button Click",this.onClick),Re("CLICKED button "+this.name+" at "+this.context.time.frameCount)),this.onClick&&this.onClick.listenerCount>0&&(this.onClick.invoke(),e.use(),this.context.accessibility.focus(this),sr))){const t=this.gameObject.worldPosition;t.add(this.gameObject.worldUp.multiplyScalar(1+Math.random()*.5)),B.DrawLabel(t,"CLICK:"+Date.now(),.1,1+Math.random()*.5)}}colors;transition;animationTriggers;animator;set interactable(e){this._interactable=e,this._image&&(this._image.setInteractable(e),e?this._image.setState("normal"):this._image.setState("disabled"))}get interactable(){return this._interactable}_interactable=!0;set_interactable(e){this.interactable=e}awake(){super.awake(),sr&&console.log(this),this._isInit=!1,this.init()}start(){this._image?.setInteractable(this.interactable),this.gameObject.getComponentInParent(fh)||this.gameObject.addComponent(Yf)}onEnable(){super.onEnable(),this.context.accessibility.updateElement(this,{role:"button",label:this.gameObject.name+" button",hidden:!1})}onDisable(){super.onDisable(),this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this),this._isHovered&&this.context.input.unsetCursor("pointer")}_requestedAnimatorTrigger;*setAnimatorTriggerAtEndOfFrame(e){this._requestedAnimatorTrigger=e,yield,yield,this._requestedAnimatorTrigger==e&&this.animator?.setTrigger(e)}_isInit=!1;_image;init(){this._isInit||(this._isInit=!0,this._image=P.getComponent(this.gameObject,ql),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){e.setInteractable(this.interactable);const t=this.getFinalColor(e.color,this.colors?.normalColor),i={state:"normal",attributes:{backgroundColor:t,backgroundOpacity:t.alpha}};e.setupState(i);const n=this.getFinalColor(e.color,this.colors?.highlightedColor),o={state:"hovered",attributes:{backgroundColor:n,backgroundOpacity:n.alpha}};e.setupState(o);const r=this.getFinalColor(e.color,this.colors?.pressedColor),a={state:"pressed",attributes:{backgroundColor:r,backgroundOpacity:r.alpha}};e.setupState(a);const l=this.getFinalColor(e.color,this.colors?.selectedColor),h={state:"selected",attributes:{backgroundColor:l,backgroundOpacity:l.alpha}};e.setupState(h);const d=this.getFinalColor(e.color,this.colors?.disabledColor),u={state:"disabled",attributes:{backgroundColor:d,backgroundOpacity:d.alpha}};e.setupState(u)}getFinalColor(e,t){return t?e.clone().multiply(t).convertLinearToSRGB():e.clone().convertLinearToSRGB()}}ji([p(Z)],Ys.prototype,"onClick",2);ji([p(Qo)],Ys.prototype,"colors",2);ji([p()],Ys.prototype,"transition",2);ji([p(L2)],Ys.prototype,"animationTriggers",2);ji([p(vt)],Ys.prototype,"animator",2);ji([p()],Ys.prototype,"interactable",1);var B2=Object.defineProperty,jp=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&B2(e,t,n),n};const ao=x("debuginputfield"),dd=class H extends T{get text(){return this.textComponent?.text??""}set text(e){this.textComponent&&(this.textComponent.text=e,this.placeholder&&(e.length>0?this.placeholder.gameObject.visible=!1:this.placeholder.gameObject.visible=!0))}get isFocused(){return H.active===this}textComponent;placeholder;onValueChanged;onEndEdit;static active=null;static activeTime=-1;static htmlField=null;static htmlFieldFocused=!1;inputEventFn;_iosEventFn;start(){ao&&console.log(this.name,this)}onEnable(){H.htmlField||(H.htmlField=document.createElement("input"),H.htmlField.style.width="0px",H.htmlField.style.height="0px",H.htmlField.style.padding="0px",H.htmlField.style.border="none",H.htmlField.style.overflow="hidden",H.htmlField.style.caretColor="transparent",H.htmlField.style.outline="none",H.htmlField.classList.add("ar"),H.htmlField.onfocus=()=>H.htmlFieldFocused=!0,H.htmlField.onblur=()=>H.htmlFieldFocused=!1,document.body.append(H.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),H.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&this.textComponent?.text.length&&P.setActive(this.placeholder.gameObject,!1),exports.DeviceUtilities.isiOS()&&(this._iosEventFn=this.processInputOniOS.bind(this),window.addEventListener("click",this._iosEventFn))}onDisable(){H.htmlField?.removeEventListener("keyup",this.inputEventFn),this.onDeselected(),this._iosEventFn&&window.removeEventListener("click",this._iosEventFn)}clear(){H.active===this&&H.htmlField?(H.htmlField.value="",this.setTextFromInputField()):(this.textComponent&&(this.textComponent.text=""),this.placeholder&&P.setActive(this.placeholder.gameObject,!0))}select(){this.onSelected()}deselect(){this.onDeselected()}onPointerEnter(e){e.event.pointerType==="mouse"&&e.button===0&&this.context.input.setCursor("text")}onPointerExit(e){this.context.input.unsetCursor("text")}onPointerClick(e){ao&&console.log("CLICK",e,H.active),H.activeTime=this.context.time.time,H.active!==this&&this.startCoroutine(this.activeLoop(),Ce.LateUpdate),this.selectInputField()}*activeLoop(){for(this.onSelected();H.active===this&&!(this.context.input.getPointerClicked(0)&&this.context.time.time-H.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){if(H.active!==this&&(ao&&console.log("Select",this.name,this,H.htmlField,this.context.isInXR,this.context.arOverlayElement,this.textComponent?.text,H.htmlField?.value),H.active?.onDeselected(),H.active=this,this.placeholder&&P.setActive(this.placeholder.gameObject,!1),H.htmlField)){if(H.htmlField.value=this.textComponent?.text||"",ao&&console.log("set input field value",H.htmlField.value),this.context.isInXR){const e=this.context.arOverlayElement;e&&e.append(H.htmlField)}this.selectInputField()}}onDeselected(){H.active===this&&(H.active=null,ao&&console.log("Deselect",this.name,this),H.htmlField&&(H.htmlField.blur(),document.body.append(H.htmlField)),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&P.setActive(this.placeholder.gameObject,!0),H.htmlField&&this.onEndEdit?.invoke(H.htmlField.value))}update(){H.active===this&&this.textComponent?.markDirty()}onInput(e){if(H.active===this){if(ao&&console.log(e.code,e,H.htmlField?.value,this.textComponent?.text),e.code==="Escape"||e.code==="Enter"){this.onDeselected();return}H.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&P.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){if(this.textComponent&&H.htmlField){const e=this.textComponent.text,t=H.htmlField.value,i=this.textComponent.text!==H.htmlField.value;this.textComponent.text=H.htmlField.value,i&&(ao&&console.log("[InputField] value changed:",t,e),this.onValueChanged?.invoke(t,e))}}selectInputField(){H.htmlField&&(ao&&console.log("Focus Inputfield",H.htmlFieldFocused,H.htmlField),H.htmlField.setSelectionRange(H.htmlField.value.length,H.htmlField.value.length),exports.DeviceUtilities.isiOS()?(H.htmlField.style.display="block",H.htmlField.focus({preventScroll:!0})):setTimeout(()=>H.htmlField?.focus(),1))}processInputOniOS(){const e=this.context.physics.raycast();if(!e.length)return;const i=e[0].object,n=g_(i);(n?.gameObject===this.gameObject||n?.gameObject.parent===this.gameObject)&&this.selectInputField()}};jp([p(Nt)],dd.prototype,"textComponent");jp([p(Nt)],dd.prototype,"placeholder");jp([p(Z)],dd.prototype,"onValueChanged");jp([p(Z)],dd.prototype,"onEndEdit");let Db=dd;var F2=Object.defineProperty,H1=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&F2(e,t,n),n};class ud extends T{id=null;keepAspect=!1;_object=null;onEnable(){if(this._object){this.gameObject.add(this._object);return}if(!this.id||!this.context.mainCamera)return;const e=document.getElementById(this.id);if(!e){console.warn('Could not find element with id "'+this.id+'"');return}e.style.display="block",e.style.visibility="hidden";const t=new V.InteractiveGroup;t.listenToPointerEvents(this.context.renderer,this.context.mainCamera),this.gameObject.add(t);const i=new V.HTMLMesh(e);t.add(i),i.visible=!1;const n=i.material;n.transparent=!0,setTimeout(()=>{i.visible=!0;const o=Of(this.gameObject).clone();Ph(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();const r=new c.Box3;r.setFromObject(t),this.setWorldRotation(o.x,o.y,o.z);const a=r.max.x-r.min.x,l=r.max.y-r.min.y;if(this.keepAspect){const d=a/l;a>l?i.scale.set(1/a,1/l/d,1):i.scale.set(1/a*d,1/l,1)}else i.scale.set(1/a,1/l,1);const h=this.gameObject.scale;i.scale.multiply(h)},1)}onDisable(){this._object?.removeFromParent()}}H1([p()],ud.prototype,"id");H1([p()],ud.prototype,"keepAspect");var j2=Object.defineProperty,Up=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&j2(e,t,n),n};const fd=class q1 extends T{target;invertForward=!1;keepUpDirection=!0;copyTargetRotation=!1;static flipYQuat=new c.Quaternion().setFromAxisAngle(new c.Vector3(0,1,0),Math.PI);onBeforeRender(){let e=this.target;if(e||(e=this.context.mainCamera,E()&&!this.__did_warn&&(this.__did_warn=!0,console.debug(`[LookAt] No target set on ${this.name}, using main camera as target.`))),!e)return;let t=this.copyTargetRotation;(this.context.isInVR||this.context.isInPassThrough)&&(t=!1),Ch(this.gameObject,e,this.keepUpDirection,t),this.invertForward&&this.gameObject.quaternion.multiply(q1.flipYQuat)}createBehaviours(e,t,i){if(t.uuid===this.gameObject.uuid){let n=t;if(this.keepUpDirection){const r=nt.createEmptyParent(t);n=r;const a=this.invertForward?-1:1;r.setMatrix(r.getMatrix().multiply(new c.Matrix4().makeRotationZ(Math.PI/2*a))),t.setMatrix(t.getMatrix().multiply(new c.Matrix4().makeRotationZ(-Math.PI/2*a)))}const o=new Dt("lookat "+this.name,jt.sceneStartTrigger(),pe.lookAtCameraAction(n,void 0,this.invertForward?qi.back:qi.forward,this.keepUpDirection?qi.up:qi.zero));e.addBehavior(o)}}};Up([p(c.Object3D)],fd.prototype,"target");Up([p()],fd.prototype,"invertForward");Up([p()],fd.prototype,"keepUpDirection");Up([p()],fd.prototype,"copyTargetRotation");let Ib=fd;var U2=Object.defineProperty,Lb=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&U2(e,t,n),n};class Xl extends T{url;mode=0;clickable=!0;async open(){if(!this.url){console.warn("OpenURL: URL is not set, can't open.",this);return}this._validateUrl();let e=this.url;switch(!e.startsWith("mailto:")&&e.includes("@")&&(e="mailto:"+e),this.mode){case 0:exports.DeviceUtilities.isSafari(),globalThis.open(e,"_blank");break;case 1:exports.DeviceUtilities.isSafari()&&exports.DeviceUtilities.isiOS()?globalThis.open(e,"_top"):globalThis.open(e,"_self");break;case 2:exports.DeviceUtilities.isSafari()?globalThis.open(e,"_top"):globalThis.open(e,"_new");break}}start(){this.gameObject.getComponentInParent(Ji)||this.gameObject.addComponent(Ji)}onPointerEnter(e){!e.used&&this.clickable&&this.context.input.setCursor("pointer")}onPointerExit(){this.clickable&&this.context.input.unsetCursor("pointer")}onPointerClick(e){this.clickable&&!e.used&&this.url?.length&&this.open()}_validateUrl(){this.url&&this.url.startsWith("www.")&&(E()&&console.warn("URL is not valid, adding https:// to the start of the URL",this.url),this.url="https://"+this.url)}}Lb([p()],Xl.prototype,"url");Lb([p()],Xl.prototype,"mode");Lb([p()],Xl.prototype,"clickable");If(s=>{const e=s.domElement.getAttribute("clickthrough");if(t(e)){const i=s.scene.addComponent(zp);ju(s.domElement,"clickthrough",()=>{const n=s.domElement.getAttribute("clickthrough");i.enabled=t(n)})}function t(i){return i!==null&&i!=="0"&&i!=="false"}});class zp extends T{_previousPointerEvents="all";onEnable(){this.context.input.addEventListener("pointerdown",this.onPointerEvent),this.context.input.addEventListener("pointermove",this.onPointerEvent,{queue:100}),window.addEventListener("touchstart",this.onTouchStart,{passive:!0}),window.addEventListener("touchend",this.onTouchEnd,{passive:!0}),this._previousPointerEvents=this.context.domElement.style.pointerEvents}onDisable(){this.context.input.removeEventListener("pointerdown",this.onPointerEvent),this.context.input.removeEventListener("pointermove",this.onPointerEvent),window.removeEventListener("touchstart",this.onTouchStart),window.removeEventListener("touchend",this.onTouchEnd),this.context.domElement.style.pointerEvents=this._previousPointerEvents}onPointerEnter(){}onPointerEvent=e=>{if(e.pointerId>0)return;e.intersections?.length<=0?this.context.domElement.style.pointerEvents="none":this.context.domElement.style.pointerEvents="all"};_touchDidHitAnything=!1;onTouchStart=e=>{const t=e.touches[0];if(!t)return;const i=t.clientX/window.innerWidth*2-1,n=-(t.clientY/window.innerHeight)*2+1;this.context.physics.raycast({screenPoint:new c.Vector2(i,n)}).length>0&&(this._touchDidHitAnything=!0)};onTouchEnd=e=>{const t=this._touchDidHitAnything;this._touchDidHitAnything=!1,setTimeout(()=>{t&&(this.context.domElement.style.pointerEvents="all")},100)}}var z2=Object.defineProperty,Np=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&z2(e,t,n),n};const N2=x("debugcursor");class ha extends T{static NAME="CursorFollow";damping=0;useFullPage=!0;keepDistance=!0;snapToSurface=!1;_distance=-1;updateDistance(e=!1){!e&&this.keepDistance&&this._distance!==-1||(this._distance=this.gameObject.worldPosition.distanceTo(this.context.mainCamera.worldPosition))}awake(){this._distance=-1}onEnable(){this._distance=-1,window.addEventListener("pointermove",this._onPointerMove)}onDisable(){window.removeEventListener("pointermove",this._onPointerMove)}_ndc_x=0;_ndc_y=0;_onPointerMove=e=>{if(!this.useFullPage)return;const t=e.clientX,i=e.clientY,n=this.context.domX,o=this.context.domY,r=this.context.domWidth,a=this.context.domHeight;this._ndc_x=(t-n)/r*2-1,this._ndc_y=-(i-o)/a*2+1};lateUpdate(){this.updateDistance();const e=this.useFullPage?this._ndc_x:this.context.input.mousePositionRC.x,t=this.useFullPage?this._ndc_y:this.context.input.mousePositionRC.y,i=this.context.mainCamera,n=i.worldPosition,o=F(e,t,1).unproject(i);o.sub(n).normalize();const r=F(o).multiplyScalar(this._distance).add(n);let a=r;if(this.damping>0){const l=this.gameObject.worldPosition;l.lerp(r,this.context.time.deltaTime/this.damping),this.gameObject.worldPosition=l,a=l}else this.gameObject.worldPosition=r;if(this.snapToSurface){Zm.origin=n,Zm.direction=o;const l=this.context.physics.raycastFromRay(Zm,{testObject:h=>h!==this.gameObject&&!this.gameObject.contains(h)});if(l?.length){const h=l[0];h&&(this.damping>0?this.gameObject.worldPosition=a.lerp(h.point,this.context.time.deltaTime/this.damping):this.gameObject.worldPosition=h.point,N2&&B.DrawLine(h.point,h.normal.add(h.point),65280))}}}}Np([p()],ha.prototype,"damping");Np([p()],ha.prototype,"useFullPage");Np([p()],ha.prototype,"keepDistance");Np([p()],ha.prototype,"snapToSurface");const Zm=new c.Ray;var $2=Object.defineProperty,V2=Object.getOwnPropertyDescriptor,Ql=(s,e,t,i)=>{for(var n=i>1?void 0:i?V2(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&&$2(e,t,n),n};exports.HoverAnimation=class extends T{type="linear";duration=.1;scaleFactor=1.1;hovered=null;idle=null;animation=null;start(){this.idle||(this.idle=exports.AnimationUtils.emptyClip()),(!this.hovered||!(this.hovered instanceof c.AnimationClip))&&(this.hovered=exports.AnimationUtils.createScaleClip({type:"linear",duration:this.duration||.1,scale:this.gameObject.scale,scaleFactor:this.scaleFactor||1.1})),this.animation??=this.gameObject.addComponent(Ut),this.animation.playAutomatically=!1,this.playIdle()}onEnable(){this.animation&&(this.animation.enabled=!0),this.playIdle()}onDisable(){this.animation&&(this.animation.enabled=!1),this.playIdle()}onPointerEnter(){this.playHover()}onPointerExit(){this.playIdle()}playIdle(){this.idle&&this.animation?.play(this.idle,{exclusive:!0,fadeDuration:.1,loop:!0})}playHover(){this.hovered&&this.animation?.play(this.hovered,{exclusive:!0,fadeDuration:.1,loop:!1,clampWhenFinished:!0})}};Ql([p()],exports.HoverAnimation.prototype,"type",2);Ql([p()],exports.HoverAnimation.prototype,"duration",2);Ql([p()],exports.HoverAnimation.prototype,"scaleFactor",2);Ql([p(c.AnimationClip)],exports.HoverAnimation.prototype,"hovered",2);Ql([p(c.AnimationClip)],exports.HoverAnimation.prototype,"idle",2);exports.HoverAnimation=Ql([Ly],exports.HoverAnimation);var W2=Object.defineProperty,da=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&W2(e,t,n),n};typeof window<"u"&&Promise.resolve().then(()=>require("./vendor-CDN1hirK.umd.cjs")).then(s=>s.scrollTimeline);const bs=x("debugscroll");class gs extends T{target=null;damping=0;invert=!1;htmlSelector=null;mode="window";useTopWindowScroll=!0;changed=new Z;get currentValue(){return this._current_value}_current_value=0;_target_value=0;_appliedValue=-1;_needsUpdate=!1;_firstUpdate=!1;_scrollWindow=null;_wheelTarget=null;_crossOriginWarned=!1;_viewTimelineWarned=!1;awake(){this._firstUpdate=!0}onEnable(){this.rebindScrollListener(),this._appliedValue=-1,this._needsUpdate=!0}onDisable(){this._wheelTarget?.removeEventListener("wheel",this.updateCurrentScrollValue),this._wheelTarget=null}onValidate(e){e==="useTopWindowScroll"&&this._wheelTarget&&(this.rebindScrollListener(),this._needsUpdate=!0)}resolveScrollWindow(){if(!this.useTopWindowScroll)return window;const e=window.top;if(!e||e===window.self)return window;try{return e.document,e}catch{return this._crossOriginWarned||(this._crossOriginWarned=!0,(bs||E())&&console.warn("[ScrollFollow] useTopWindowScroll is enabled but the top-level window is cross-origin and cannot be read. Falling back to the local window. Supporting cross-origin embeds requires a postMessage scroll bridge from the host page.")),window}}rebindScrollListener(){const e=this.resolveScrollWindow();this._scrollWindow=e,e!==this._wheelTarget&&(this._wheelTarget?.removeEventListener("wheel",this.updateCurrentScrollValue),this._wheelTarget=e,e.addEventListener("wheel",this.updateCurrentScrollValue,{passive:!0}),this._lastSelectorValue=null,this._lastSelectorElement=null,bs&&console.debug(`[ScrollFollow] Scroll listener bound to ${e===window?"local window":"top-level window"}`,{scrollWindow:this._scrollWindow,isTopWindow:e===window}))}lateUpdate(){if(this.updateCurrentScrollValue(),this._target_value>=0&&(this.damping>0&&!this._firstUpdate?(this._current_value=L.lerp(this._current_value,this._target_value,this.context.time.deltaTime/this.damping),Math.abs(this._current_value-this._target_value)<.001&&(this._current_value=this._target_value)):this._current_value=this._target_value),this._needsUpdate||this._current_value!==this._appliedValue){this._appliedValue=this._current_value,this._needsUpdate=!1;let e=!1;if(this.changed.listenerCount>0){const t={type:"change",value:this._current_value,component:this,preventDefault:()=>{t.defaultPrevented=!0},defaultPrevented:!1};this.changed.invoke(t),e=t.defaultPrevented}if(!e){const t=this.invert?1-this._current_value:this._current_value;Array.isArray(this.target)?this.target.forEach(i=>i&&this.applyScroll(i,t)):this.target&&this.applyScroll(this.target,t),bs&&this.context.time.frame%30===0&&console.debug(`[ScrollFollow] ${this._current_value.toFixed(5)} — ${(this._target_value*100).toFixed(0)}%, targets [${Array.isArray(this.target)?this.target.length:1}]`)}this._firstUpdate=!1}}_lastSelectorValue=null;_lastSelectorElement=null;updateCurrentScrollValue=()=>{const e=this._scrollWindow??window,t=e.document,i=t.scrollingElement??t.documentElement;switch(this.mode){case"window":if(this.htmlSelector?.length){if(this.htmlSelector!==this._lastSelectorValue&&(this._lastSelectorElement=t.querySelector(this.htmlSelector),this._lastSelectorValue=this.htmlSelector),this._lastSelectorElement){const n=this._lastSelectorElement.getBoundingClientRect();this._target_value=-n.top/(n.height-e.innerHeight);break}}else{const n=i.scrollHeight-i.clientHeight;n<=0||(this._target_value=i.scrollTop/n)}break}(isNaN(this._target_value)||!isFinite(this._target_value))&&(this._target_value=-1),bs&&console.debug(`[ScrollFollow] Scroll value updated: ${this._target_value.toFixed(5)} (ScrollTop: ${i.scrollTop}, ScrollHeight: ${i.scrollHeight}, ClientHeight: ${i.clientHeight})`)};applyScroll(e,t){if(e)if(e instanceof ml)this.handleTimelineTarget(e,t),e.isPlaying&&e.pause(),e.evaluate();else if(e instanceof vt)e.setFloat("scroll",t);else if(e instanceof Ut)e.time=t*e.duration;else if(e instanceof Ei){if(!e.duration)return;e.time=t*e.duration}else if(e instanceof ln)e.position01=t;else if(e instanceof Lt)e.intensity=t;else if(e instanceof c.Object3D){const i=e;i["needle:scrollbounds"]===void 0&&(i["needle:scrollbounds"]=pi(e)||null);const n=i["needle:scrollbounds"];n&&(e.position.y=-n.min.y-t*(n.max.y-n.min.y))}else"scroll"in e&&(typeof e.scroll=="number"?e.scroll=t:typeof e.scroll=="function"&&e.scroll(t))}handleTimelineTarget(e,t){const i=this._scrollWindow??window,n=i.document,o=e.duration;let r=Jm.get(e);if(!r){r=[],Jm.set(e,r);let d=0;for(const f of e.foreachMarker("ScrollMarker")){const m=d++;if(f.element===void 0||f.needsUpdate===!0||f.element&&!f.element?.parentNode){f.needsUpdate=!1;try{if(f.element=X1(m,n),bs&&console.debug(`ScrollMarker #${m} (${f.time.toFixed(2)}) found`,f.element),!f.element){(bs||E())&&console.warn(`No HTML element found for ScrollMarker: ${f.name} (index ${m})`);continue}}catch(g){f.element=null,console.error("ScrollMarker selector is not valid: "+f.name+`
|
|
1529
1529
|
`,g)}}f.element&&r.push(f)}r.length<=0&&n.querySelectorAll("[data-timeline-marker]").forEach(m=>{const g=m.getAttribute("data-timeline-marker"),v=parseFloat(g||"NaN");isNaN(v)?(E()||bs)&&console.warn('[ScrollFollow] data-timeline-marker attribute is not a valid number. Supported are numbers only (e.g. <div data-timeline-marker="0.5">)'):r.push({time:v,element:m})});const u=i.ViewTimeline;if(!u)!this._viewTimelineWarned&&(bs||E())&&(this._viewTimelineWarned=!0,console.warn("[ScrollFollow] ViewTimeline is not available on the target window — falling back to linear scroll. If this persists with useTopWindowScroll, the scroll-timeline polyfill must be present on the host page.")),Jm.delete(e),r.length=0;else for(const f of r)f.element&&(f.timeline=new u({subject:f.element,axis:"block"}))}Fn.length=0;let a=0;const l=1/60;let h=0;for(let d=0;d<r.length;d++){const u=r[d];if(!u.element)continue;const f=r[d+1],m=f?f.time-l:o;h+=1;const g=u.timeline;if(g){const v=G2(g),_=1-Math.abs(v-.5)*2,y=`marker${d}`;if(v>0&&v<=1){const b=u.time+(m-u.time)*v;Fn.push({name:y,time:b,weight:_}),a+=_}else d===0&&v<=0?(Fn.push({name:y,time:0,weight:1}),a+=1):d===r.length-1&&v>=1&&(Fn.push({name:y,time:o,weight:1}),a+=1)}}if(Fn.length<=0&&h<=0)e.time=t*o;else if(Fn.length>0){let d=Fn[0].time;if(Fn.length>1)for(const f of Fn){const m=f.weight/Math.max(1e-5,a),g=Math.abs(f.time-d);d+=g*m}this.damping<=0||this._firstUpdate?e.time=d:e.time=L.lerp(e.time,d,this.context.time.deltaTime/this.damping),Math.abs(e.time-d)>.001&&(this._needsUpdate=!0),bs&&this.context.time.frame%30===0&&console.log(`[ScrollFollow ] Timeline ${e.name}: ${d.toFixed(3)}`,Fn.map(f=>`[${f.name} ${(f.weight*100).toFixed(0)}%]`).join(", "))}}}da([p([T,c.Object3D])],gs.prototype,"target");da([p()],gs.prototype,"damping");da([p()],gs.prototype,"invert");da([p()],gs.prototype,"htmlSelector");da([p()],gs.prototype,"mode");da([je(),p()],gs.prototype,"useTopWindowScroll");da([p(Z)],gs.prototype,"changed");const Jm=new WeakMap,Fn=[],eg=new Array;let tg=!0;function X1(s,e){return tg?(tg=!1,eg.length=0,e.querySelectorAll("[data-timeline-marker]").forEach((i,n)=>{eg[n]=i}),tg=!1,X1(s,e)):eg[s]||null}function G2(s){if(!s.source)return 0;const e=s.currentTime,t=s.duration;let i=1;return(t.unit==="seconds"||t.unit==="percent")&&(i=t.value),e.unit==="seconds"?e.value/i:e.value/100}var Q1=Object.defineProperty,H2=Object.getOwnPropertyDescriptor,q2=(s,e,t)=>e in s?Q1(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,$p=(s,e,t,i)=>{for(var n=i>1?void 0:i?H2(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&&Q1(e,t,n),n},Bb=(s,e,t)=>q2(s,typeof e!="symbol"?e+"":e,t);const lo=x("debugviewbox"),X2=new oe(.5,.5,.5,.5);exports.ViewBox=class extends T{referenceFieldOfView=-1;get mode(){return this._mode}set mode(e){e!==this._mode&&(this._mode=e,e==="once"&&(this._applyCount=0),(lo||this.debug)&&console.debug("[ViewBox] Set mode:",e))}_mode="continuous";debug=!1;onEnable(){(lo||this.debug||E())&&console.debug("[ViewBox] Using camera fov:",this.referenceFieldOfView),exports.ViewBox.instances.push(this),this._applyCount=0,this.removeUpdateCallback(),this.context.pre_render_callbacks.push(this.internalUpdate)}onDisable(){(lo||this.debug)&&console.debug("[ViewBox] Disabled");const e=exports.ViewBox.instances.indexOf(this);e!==-1&&exports.ViewBox.instances.splice(e,1),this._projectedBoxElement?.remove(),this.removeUpdateCallback()}removeUpdateCallback(){const e=this.context.pre_render_callbacks.indexOf(this.internalUpdate);e!==-1&&this.context.pre_render_callbacks.splice(e,1)}_applyCount=0;internalUpdate=()=>{if(this.context.isInXR||this.destroyed||!this.activeAndEnabled)return;if(!(exports.ViewBox.instances[exports.ViewBox.instances.length-1]===this)){(lo||this.debug)&&B.DrawWireBox(this.gameObject.worldPosition,this.gameObject.worldScale,X2);return}(lo||this.debug)&&B.DrawWireBox(this.gameObject.worldPosition,this.gameObject.worldScale,14540032,0,!0,this.gameObject.worldQuaternion);const t=this.context.mainCamera;if(!t||!(t instanceof c.PerspectiveCamera))return;if((this.referenceFieldOfView===void 0||this.referenceFieldOfView===-1)&&(this.referenceFieldOfView=t.fov,console.debug("[ViewBox] No referenceFieldOfView set, using camera fov:",this.referenceFieldOfView)),this.referenceFieldOfView===void 0||this.referenceFieldOfView<=0){(lo||this.debug)&&console.warn("[ViewBox] No valid referenceFieldOfView set, cannot adjust box size:",this.referenceFieldOfView);return}if(this._applyCount>=1&&this.mode==="once")return;this._applyCount++;const i=this.context.domWidth,n=this.context.domHeight;let o=i,r=n,a=1,l=1;const h=this.context.focusRectSize;h&&(o=h.width,r=h.height,a=i/o,l=n/r),exports.ViewBox._tempProjectionMatrix.copy(t.projectionMatrix),exports.ViewBox._tempProjectionMatrixInverse.copy(t.projectionMatrixInverse);const d=t.view,u=t.zoom,f=t.aspect,m=t.fov;t.view=null,t.zoom=1,t.fov=this.referenceFieldOfView,t.updateProjectionMatrix();const g=this.gameObject.worldPosition,v=this.gameObject.worldScale,_=t.worldPosition,y=_.distanceTo(g),b=Math.max(v.x,v.y,v.z),w=F(_).sub(g);if(y<b){(this.debug||lo)&&console.warn("[ViewBox] Moving camera out of bounds",y,"<",b);const G=F(w);G.y*=1e-8,G.normalize();const Y=b-y,K=_.add(G.multiplyScalar(Y));t.worldPosition=K.lerp(_,1-this.context.time.deltaTime)}const C=F(g);t.worldToLocal(C),t.lookAt(g),t.updateMatrixWorld();const k=this.referenceFieldOfView*Math.PI/180,O=2*Math.tan(k/2)*y,D=O*t.aspect,I=this.projectBoxIntoCamera(t,1),j=I.maxX-I.minX,$=I.maxY-I.minY,R=this.fit(j*t.aspect,$,D/a,O/l)/(O*.5),U=F(g);U.project(t),this.context.focusRectSettings.offsetX=U.x,this.context.focusRectSettings.offsetY=U.y,this.context.focusRectSettings.zoom=R,this.context.focusRect||this.context.setCameraFocusRect(this.context.domElement),t.view=d,t.zoom=u,t.aspect=f,t.fov=m,t.projectionMatrix.copy(exports.ViewBox._tempProjectionMatrix),t.projectionMatrixInverse.copy(exports.ViewBox._tempProjectionMatrixInverse)};fit(e,t,i,n){const o=i/e,r=n/t;return Math.min(o,r)}projectBoxIntoCamera(e,t){const i=.5*t,n=[F(-i,-i,-i),F(i,-i,-i),F(-i,i,-i),F(i,i,-i),F(-i,-i,i),F(i,-i,i),F(-i,i,i),F(i,i,i)];let o=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY,a=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY;for(let h=0;h<n.length;h++){const d=n[h];d.applyMatrix4(this.gameObject.matrixWorld),d.project(e),d.x<o&&(o=d.x),d.x>r&&(r=d.x),d.y<a&&(a=d.y),d.y>l&&(l=d.y)}return lo&&(this._projectedBoxElement||(this._projectedBoxElement=document.createElement("div")),this._projectedBoxElement.parentElement!==this.context.domElement&&this.context.domElement.appendChild(this._projectedBoxElement),this._projectedBoxElement.style.position="fixed",this._projectedBoxElement.style.outline="2px dashed rgba(255,0,0,.5)",this._projectedBoxElement.style.left=(o*.5+.5)*this.context.domWidth+"px",this._projectedBoxElement.style.top=(-l*.5+.5)*this.context.domHeight+"px",this._projectedBoxElement.style.width=(r-o)*.5*this.context.domWidth+"px",this._projectedBoxElement.style.height=(l-a)*.5*this.context.domHeight+"px",this._projectedBoxElement.style.pointerEvents="none",this._projectedBoxElement.style.zIndex="1000"),{minX:o,maxX:r,minY:a,maxY:l}}_projectedBoxElement=null};Bb(exports.ViewBox,"instances",[]);Bb(exports.ViewBox,"_tempProjectionMatrix",new c.Matrix4);Bb(exports.ViewBox,"_tempProjectionMatrixInverse",new c.Matrix4);$p([p()],exports.ViewBox.prototype,"referenceFieldOfView",2);$p([p()],exports.ViewBox.prototype,"mode",1);$p([p()],exports.ViewBox.prototype,"debug",2);exports.ViewBox=$p([Ly],exports.ViewBox);var Q2=Object.defineProperty,Yl=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&Q2(e,t,n),n};class Ks extends T{get activeAndEnabled(){return!0}side="none";controller=!0;hands=!1;controlVisibility=!0;useGripSpace=!1;resetTransformAfterXRSession=!0;_startPosition=new c.Vector3;_startRotation=new c.Quaternion;_startScale=new c.Vector3;onEnterXR(e){this._startPosition.copy(this.gameObject.position),this._startRotation.copy(this.gameObject.quaternion),this._startScale.copy(this.gameObject.scale)}onUpdateXR(e){if(!this.enabled)return;const t=e.xr.getController(this.side);if(t){if(t.hand&&!this.hands){this.controlVisibility&&(this.gameObject.visible=!1);return}else if(!this.controller){this.controlVisibility&&(this.gameObject.visible=!1);return}this.controlVisibility&&(this.gameObject.visible=!0),this.useGripSpace||t.targetRayMode==="transient-pointer"?(this.gameObject.worldPosition=t.gripWorldPosition,this.gameObject.worldQuaternion=t.gripWorldQuaternion,this.gameObject.worldScale=F(t.xr.rigScale,t.xr.rigScale,t.xr.rigScale).multiply(this._startScale)):(this.gameObject.worldPosition=t.rayWorldPosition,this.gameObject.worldQuaternion=t.rayWorldQuaternion,this.gameObject.worldScale=F(t.xr.rigScale,t.xr.rigScale,t.xr.rigScale).multiply(this._startScale))}}onLeaveXR(e){this.resetTransformAfterXRSession&&(this.gameObject.position.copy(this._startPosition),this.gameObject.quaternion.copy(this._startRotation),this.gameObject.scale.copy(this._startScale))}}Yl([p()],Ks.prototype,"side");Yl([p()],Ks.prototype,"controller");Yl([p()],Ks.prototype,"hands");Yl([p()],Ks.prototype,"controlVisibility");Yl([p()],Ks.prototype,"useGripSpace");Yl([p()],Ks.prototype,"resetTransformAfterXRSession");function Y2(){if(typeof window>"u"||!exports.DeviceUtilities.isNeedleAppClip())return null;const s=window.NeedleGoNativeScreenshot;return typeof s=="function"?s:null}function Y1(s,e){const t=s.xr.getFrame();if(!t)return console.warn("No XRFrame available"),!1;const i=t.session.enabledFeatures;if(i&&!i.some(o=>o==="camera-access"))return console.error(`No camera feed available - please request the 'camera-access' feature before starting WebXR or add the ARCameraBackground component to your scene.
|
|
1530
1530
|
|
|
1531
1531
|
Example to request camera-access in global scope:
|
|
@@ -1857,4 +1857,4 @@ Needle Engine: finished loading `+i+`
|
|
|
1857
1857
|
---------------------------------
|
|
1858
1858
|
• `+r.passes.map(u=>u.name||u.constructor.name+"*").join(`
|
|
1859
1859
|
• `)+`
|
|
1860
|
-
`),si&&this._onCreateEffectsDebug(this._composer,o)}createPassForMergeableEffects(e,t,i,n){if(e.length>0){const o=new A.POSTPROCESSING.MODULE.EffectPass(i,...e);o.name=e.map(r=>r.name).join(", "),o.mainScene=n,o.enabled=!0,o.renderToScreen=!1,t.addPass(o),e.length=0}}handleDevicePixelRatio(){typeof this.context.devicePixelRatio=="number"&&this.context.requestSizeUpdate()}_menuEntry=null;_passIndices=null;_onCreateEffectsDebug(e,t){if(si==="passes"){const i=new A.POSTPROCESSING.MODULE.DepthEffect({blendFunction:A.POSTPROCESSING.MODULE.BlendFunction.NORMAL,inverted:!0});i.name="Depth Effect";const n=new A.POSTPROCESSING.MODULE.EffectPass(t,i);if(n.name="Depth Effect Pass",n.enabled=!1,e.passes.push(n),this._passIndices!==null){const r=[e.passes[0]];this._passIndices.length>0&&r.push(...this._passIndices.filter(a=>a!==0).map(a=>e.passes[a]).filter(a=>a)),r.length>0&&console.log("[PostProcessing] Passes (selected) →",r),e.passes.length=0;for(const a of r)a.enabled=!0,a.renderToScreen=!1,e.addPass(a)}const o=this.context.menu;if(o&&this._passIndices===null){this._menuEntry&&this._menuEntry.remove();const r=document.createElement("select");r.multiple=!0;const a=document.createElement("option");a.innerText="Final Output",a.value="-1",r.appendChild(a);for(const l of e.passes){const h=document.createElement("option");h.innerText=l.name,h.value=`${e.passes.indexOf(l)}`,h.title=l.name,r.appendChild(h)}o.appendChild(r),this._menuEntry=r,r.addEventListener("change",()=>{const l=Array.from(r.selectedOptions).map(h=>parseInt(h.value));l.length===1&&l[0]===-1?this._passIndices=null:this._passIndices=l,this.applyEffects(this.context)})}}}}const F3=Object.freeze(Object.defineProperty({__proto__:null,PostProcessingHandler:vl},Symbol.toStringTag,{value:"Module"}));class Wp{_name;_tracks=[];_currentTrack=null;_pendingSignals=[];_idProvider;constructor(e,t){this._name=e,this._idProvider=new ot(t??Date.now())}static create(e,t){return new Wp(e??"Timeline",t)}animationTrack(e,t){return this.commitInlineTracks(),this._currentTrack=this.pushTrack(e,we.Animation,t??null),this}audioTrack(e,t,i){return this.commitInlineTracks(),this._currentTrack=this.pushTrack(e,we.Audio,t??null),this._currentTrack.volume=i,this}activationTrack(e,t){return this.commitInlineTracks(),this._currentTrack=this.pushTrack(e,we.Activation,t??null),this}controlTrack(e){return this.commitInlineTracks(),this._currentTrack=this.pushTrack(e,we.Control,null),this}signalTrack(e,t){return this.commitInlineTracks(),this._currentTrack=this.pushTrack(e,we.Signal,t??null),this}markerTrack(e){return this.commitInlineTracks(),this._currentTrack=this.pushTrack(e,we.Marker,null),this}clip(e,t){if(!this._currentTrack)throw new Error("TimelineBuilder: .clip() must be called after a track method (e.g. .animationTrack())");this.commitInlineTracks();const i=this._currentTrack;switch(i.type){case we.Animation:{let n;if(e instanceof c.AnimationClip)n=e;else{const d=Array.isArray(e)?e:[e],u=i.outputs[0],f=u instanceof c.Object3D?u:u!=null&&"gameObject"in u?u.gameObject:void 0;n=dh(d,f)}const o=t??{},r=o.duration??n.duration,a=o.start??i.cursor,l=a+r,h={start:a,end:l,duration:r,timeScale:o.speed??1,clipIn:o.clipIn??0,easeInDuration:o.easeIn??0,easeOutDuration:o.easeOut??0,preExtrapolationMode:o.preExtrapolation??et.None,postExtrapolationMode:o.postExtrapolation??et.None,reversed:o.reversed,asset:{clip:n,loop:o.loop??!1,duration:n.duration,removeStartOffset:o.removeStartOffset??!1}};i.clips.push(h),i.cursor=l;break}case we.Audio:{const n=e,o=t??{},r=o.duration,a=o.start??i.cursor,l=a+r,h={start:a,end:l,duration:r,timeScale:o.speed??1,clipIn:0,easeInDuration:o.easeIn??0,easeOutDuration:o.easeOut??0,preExtrapolationMode:et.None,postExtrapolationMode:et.None,asset:{clip:n,loop:o.loop??!1,volume:o.volume??1}};i.clips.push(h),i.cursor=l;break}case we.Activation:{const n=e,o=n.start??i.cursor,r=o+n.duration,a={start:o,end:r,duration:n.duration,timeScale:1,clipIn:0,easeInDuration:n.easeIn??0,easeOutDuration:n.easeOut??0,preExtrapolationMode:et.None,postExtrapolationMode:et.None,asset:{}};i.clips.push(a),i.cursor=r;break}case we.Control:{const n=e,o=t??{},r=o.start??i.cursor,a=o.duration,l=r+a,h={start:r,end:l,duration:a,timeScale:1,clipIn:0,easeInDuration:0,easeOutDuration:0,preExtrapolationMode:et.None,postExtrapolationMode:et.None,asset:{sourceObject:n,controlActivation:o.controlActivation??!0,updateDirector:o.updateDirector??!0}};i.clips.push(h),i.cursor=l;break}default:throw new Error(`TimelineBuilder: .clip() is not supported on track type "${i.type}"`)}return this}marker(e,t,i){if(!this._currentTrack)throw new Error("TimelineBuilder: .marker() must be called after a track method");if(this._currentTrack.type!==we.Signal&&this._currentTrack.type!==we.Marker)throw new Error(`TimelineBuilder: .marker() is only supported on signal and marker tracks, not "${this._currentTrack.type}"`);const n={type:mh.Signal,time:e,retroActive:i?.retroActive??!1,emitOnce:i?.emitOnce??!1,asset:t};return this._currentTrack.markers.push(n),e>this._currentTrack.cursor&&(this._currentTrack.cursor=e),this}signal(e,t,i){if(!this._currentTrack)throw new Error("TimelineBuilder: .signal() must be called after a track method");if(this._currentTrack.type!==we.Signal&&this._currentTrack.type!==we.Marker)throw new Error(`TimelineBuilder: .signal() is only supported on signal and marker tracks, not "${this._currentTrack.type}"`);const n=this._idProvider.generateUUID(),o=this._tracks.indexOf(this._currentTrack),r={type:mh.Signal,time:e,retroActive:i?.retroActive??!1,emitOnce:i?.emitOnce??!1,asset:n};return this._currentTrack.markers.push(r),this._pendingSignals.push({trackIndex:o,guid:n,callback:t}),e>this._currentTrack.cursor&&(this._currentTrack.cursor=e),this}muted(e=!0){if(!this._currentTrack)throw new Error("TimelineBuilder: .muted() must be called after a track method");return this._currentTrack.muted=e,this}track(e,t,i,n){if(!this._currentTrack)throw new Error("TimelineBuilder: .track() must be called after .animationTrack()");if(this._currentTrack.type!==we.Animation)throw new Error("TimelineBuilder: .track() is only supported on animation tracks");return this._currentTrack.inlineTracks.push(u_(e,t,i,n)),this}build(){this.commitInlineTracks();const e=this._tracks.map(t=>{const i={name:t.name,type:t.type,muted:t.muted,outputs:t.outputs};return t.clips.length>0&&(i.clips=t.clips),t.markers.length>0&&(i.markers=t.markers),t.volume!==void 0&&(i.volume=t.volume),t.trackOffset!==void 0&&(i.trackOffset=t.trackOffset),i});return{name:this._name,tracks:e}}install(e){const t=this.build();if(this._pendingSignals.length>0){const i=e.gameObject;let n=P.getComponent(i,Lr);n||(n=P.addComponent(i,Lr)),n.events||(n.events=[]);for(const o of this._pendingSignals){const r=new Lh;r.guid=o.guid;const a=new Ml;a.signal=r,a.reaction=new Z([o.callback]),n.events.push(a);const l=t.tracks[o.trackIndex];l&&!l.outputs.includes(n)&&l.outputs.push(n)}}return e.playableAsset=t,t}pushTrack(e,t,i){const n={name:e,type:t,muted:!1,outputs:i?[i]:[],clips:[],markers:[],cursor:0,inlineTracks:[]};return this._tracks.push(n),n}commitInlineTracks(){if(!this._currentTrack||this._currentTrack.inlineTracks.length===0)return;const e=this._currentTrack,t=e.outputs[0],i=t instanceof c.Object3D?t:t!=null&&"gameObject"in t?t.gameObject:void 0,n=dh(e.inlineTracks,i),o=e.cursor,r=n.duration,a={start:o,end:o+r,duration:r,timeScale:1,clipIn:0,easeInDuration:0,easeOutDuration:0,preExtrapolationMode:et.None,postExtrapolationMode:et.None,asset:{clip:n,loop:!1,duration:n.duration,removeStartOffset:!1}};e.clips.push(a),e.cursor=o+r,e.inlineTracks=[]}}class hP{}const j3=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:pe,ActionCollection:JC,ActionModel:li,AlignmentConstraint:jh,Animation:Ut,AnimationBuilder:Hf,AnimationCurve:Zh,AnimationExtension:up,Animator:vt,AnimatorController:Jn,Antialiasing:ed,Attractor:$l,AudioExtension:qr,AudioListener:Ms,AudioSource:Ei,Avatar:Io,AvatarMarker:it,AxesHelper:Ol,AxisRotationConstraint:O_,BaseUIComponent:en,BasicIKConstraint:x_,BehaviorExtension:tb,BehaviorModel:Dt,BloomEffect:Ep,BoxCollider:np,BoxGizmo:Zr,BoxHelperComponent:At,Button:Ys,CallInfo:vi,Camera:Jt,CameraTargetReachedEvent:ph,Canvas:yl,CanvasGroup:Lo,CapsuleCollider:Fs,ChangeMaterialOnClick:X_,ChangeTransformOnClick:Xr,CharacterController:Gr,CharacterControllerInput:Ns,ChromaticAberration:td,ClickThrough:zp,ColorAdjustments:Go,ColorBySpeedModule:Nl,ColorOverLifetimeModule:kp,ContactShadows:Uh,CursorFollow:ha,CustomBranding:Yr,Deletable:k_,DeleteBox:Oo,DepthOfField:On,DeviceFlag:sp,DocumentExtension:cP,DragControls:vr,DragProfile:uf,DropListener:Vs,Duplicatable:U_,EffectWrapper:wh,EmissionModule:qs,EmphasizeOnClick:Al,EnvironmentScene:ip,EventList:Z,EventListEvent:f_,EventSystem:ei,EventTrigger:hp,FieldWithDefault:TC,FixedJoint:gb,FixedRotationAxesConstraint:vC,Fog:Fl,GaussianSplat:Kr,GltfExport:W_,GltfExportBox:$_,GrabPointPlaneConstraint:Nh,Gradient:ea,Graphic:Qh,GraphicRaycaster:Yf,GridHelper:jl,GridLayoutGroup:ab,GridSnapConstraint:op,GroundProjectedEnv:ds,GroupActionModel:wr,HideOnStart:Gi,HingeJoint:Kh,HorizontalLayoutGroup:rb,get HoverAnimation(){return exports.HoverAnimation},Image:ql,InheritVelocityModule:wb,InputField:Db,InstanceHandle:Rr,InstancingHandler:jr,Interactable:P_,KeepRotationConstraint:rp,KeepScaleConstraint:bC,Keyframe:ui,LODGroup:Sp,LODModel:Ul,Light:Lt,LimitVelocityOverLifetimeModule:pt,LogStats:C_,LookAt:Ib,LookAtConstraint:Vr,MainModule:$t,MaskableGraphic:Yh,MeshCollider:Uo,MeshRenderer:Vh,MinMaxCurve:Q,MinMaxGradient:ta,NeedleMenu:fs,NestedGltf:zl,Networking:bb,NoiseModule:ve,ObjectRaycaster:Ji,OffsetConstraint:Jr,OpenURL:Xl,OrbitControls:ue,Outline:Bl,Padding:Qr,ParticleBurst:wf,ParticleSubEmitter:xb,ParticleSystem:vh,ParticleSystemRenderer:rn,PhysicsExtension:ib,PixelationEffect:id,PlaneHeightLockConstraint:E_,PlayAnimationOnClick:_h,PlayAudioOnClick:Do,PlayableDirector:ml,PlayerColor:_l,PointerEventData:Ih,PostProcessingHandler:vl,PreliminaryAction:Dl,PreliminaryTrigger:Gh,RawImage:Fp,Rect:l1,RectTransform:Cn,ReflectionProbe:Ps,RegisteredAnimationInfo:Co,RemoteSkybox:v_,Renderer:ti,RendererLightmap:B_,Rigidbody:Xe,RotationBySpeedModule:on,RotationOverLifetimeModule:Mn,ScaleLimitConstraint:M_,SceneSwitcher:Ye,ScreenCapture:Ho,ScreenSpaceAmbientOcclusion:Xs,ScreenSpaceAmbientOcclusionN8:En,ScrollFollow:gs,SeeThrough:Ob,SetActiveOnClick:Q_,ShadowCatcher:ld,ShapeModule:vb,SharpeningEffect:sd,SignalAsset:Lh,SignalReceiver:Lr,SignalReceiverEvent:Ml,SignalTrackHandler:yh,Size:a1,SizeBySpeedModule:_i,SizeOverLifetimeModule:ia,SkinnedMeshRenderer:F_,SmoothFollow:Ap,SnapToSurfaceConstraint:ap,SpatialGrabRaycaster:Ir,SpatialHtml:ud,SpatialTrigger:Dp,SpatialTriggerReceiver:rs,SpectatorCamera:Ip,SphereCollider:El,SplineContainer:la,SplineData:ls,SplineWalker:ln,Sprite:Ws,SpriteData:nl,SpriteRenderer:gi,SpriteSheet:gl,SubEmitterSystem:xf,SyncedCamera:Eb,SyncedRoom:Rn,SyncedTransform:Sn,TapGestureTrigger:K_,TeleportTarget:yp,TestRunner:Rb,TestSimulateUserData:Tb,Text:Nt,TextBuilder:sb,TextExtension:bp,TextureSheetAnimationModule:Vt,TiltShiftEffect:ms,TimelineActivationTrack:Jf,TimelineAnimationTrack:gh,TimelineAudioTrack:Os,TimelineBuilder:Wp,TimelineControlTrack:ep,TimelineMarkerTrack:Zf,ToneMappingEffect:na,TrailModule:ze,TransformData:Fe,TransformGizmo:ca,TriggerBuilder:jt,TriggerModel:Eo,UIRaycastUtils:m_,UIRootComponent:qh,USDZExporter:os,USDZText:Va,USDZUIExtension:cb,UsageMarker:zh,VariantAction:q_,VelocityOverLifetimeModule:We,VerticalLayoutGroup:ob,VideoPlayer:ut,get ViewBox(){return exports.ViewBox},Vignette:ra,VisibilityAction:Hh,Voip:Qs,Volume:od,VolumeParameter:z,VolumeProfile:Mp,WebARCameraBackground:pd,WebARSessionRoot:Qi,WebXR:_p,WebXRImageTracking:Kl,WebXRImageTrackingModel:Zi,WebXRPlaneTracking:Js,WebXRTrackedImage:bl,XRControllerFollow:Ks,XRControllerModel:js,XRControllerMovement:Ti,XRFlag:_n,XRRig:Vp,XRState:Kt,__Ignore:hP},Symbol.toStringTag,{value:"Module"}));exports.SplineUtils=void 0;(s=>{function e(t,i=!1,n=.75){const o=new la,r=1-L.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 ls;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 U3 extends ee.WorkerBase{constructor(){super(new Worker(new URL("/generateMeshBVH.worker-Be19n6m6.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:Ha&&Ha.tagName.toUpperCase()==="SCRIPT"&&Ha.src||new URL("needle-engine.bundle-D3nBMgfk.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||"Could not load worker."}`))},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:f}=d,m=ee.MeshBVH.deserialize(u,t,{setIndex:!1}),g=Object.assign({setBoundingBox:!0},i);if(t.attributes.position.array=f,u.index)if(t.index)t.index.array=u.index;else{const v=new c.BufferAttribute(u.index,1,!1);t.setIndex(v)}g.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)))}).finally(()=>{e.onmessage=null,e.onerror=null})}}const z3=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:U3},Symbol.toStringTag,{value:"Module"}));exports.$componentName=Gu;exports.$physicsKey=qk;exports.ActionBuilder=pe;exports.ActionCollection=JC;exports.ActionModel=li;exports.Addressables=Lx;exports.AlignmentConstraint=jh;exports.AmbientMode=Ya;exports.Animation=Ut;exports.AnimationBuilder=Hf;exports.AnimationCurve=Zh;exports.AnimationExtension=up;exports.Animator=vt;exports.AnimatorConditionMode=hi;exports.AnimatorController=Jn;exports.AnimatorControllerBuilder=qf;exports.AnimatorControllerParameterType=br;exports.AnimatorStateInfo=Pc;exports.Antialiasing=ed;exports.Application=wn;exports.AssetDatabase=CS;exports.AssetReference=J;exports.Attractor=$l;exports.AudioClip=Yg;exports.AudioExtension=qr;exports.AudioListener=Ms;exports.AudioRolloffMode=hC;exports.AudioSource=Ei;exports.Avatar=Io;exports.AvatarMarker=it;exports.Axes=$a;exports.AxesHelper=Ol;exports.AxisRotationConstraint=O_;exports.BUILD_TIME=Zc;exports.BaseUIComponent=en;exports.BasicIKConstraint=x_;exports.BehaviorExtension=tb;exports.BehaviorModel=Dt;exports.BloomEffect=Ep;exports.BoxCollider=np;exports.BoxGizmo=Zr;exports.BoxHelperComponent=At;exports.Button=Ys;exports.ButtonsFactory=Xi;exports.CallDirection=B1;exports.CallInfo=vi;exports.Camera=Jt;exports.CameraTargetReachedEvent=ph;exports.Canvas=yl;exports.CanvasGroup=Lo;exports.CapsuleCollider=Fs;exports.ChangeMaterialOnClick=X_;exports.ChangeTransformOnClick=Xr;exports.CharacterController=Gr;exports.CharacterControllerInput=Ns;exports.ChromaticAberration=td;exports.CircularBuffer=Mi;exports.ClearFlags=Or;exports.ClickThrough=zp;exports.ClipExtrapolation=et;exports.Collider=Ii;exports.Collision=fx;exports.CollisionDetectionMode=Qf;exports.ColorAdjustments=Go;exports.ColorBySpeedModule=Nl;exports.ColorOverLifetimeModule=kp;exports.Component=sR;exports.Component$1=T;exports.ComponentLifecycleEvents=Rf;exports.Components=j3;exports.ConnectionEvents=qx;exports.ContactPoint=ux;exports.ContactShadows=Uh;exports.Context=X;exports.ContextArgs=dE;exports.ContextEvent=ae;exports.ContextRegistry=se;exports.CursorFollow=ha;exports.CustomBranding=Yr;exports.CustomShader=Me;exports.DefaultReflectionMode=Ju;exports.Deletable=k_;exports.DeleteBox=Oo;exports.DepthOfField=On;exports.DepthOfFieldMode=A1;exports.DeviceFlag=sp;exports.DirectorWrapMode=uC;exports.DisposableStore=Ou;exports.DocumentExtension=cP;exports.DragControls=vr;exports.DragMode=R_;exports.DragProfile=uf;exports.DropListener=Vs;exports.Duplicatable=U_;exports.EffectWrapper=wh;exports.EmissionModule=qs;exports.EmphasizeOnClick=Al;exports.EngineLoadingView=Tr;exports.EnvironmentScene=ip;exports.EventBus=Og;exports.EventList=Z;exports.EventListEvent=f_;exports.EventSystem=ei;exports.EventTrigger=hp;exports.FieldWithDefault=TC;exports.FileReference=qn;exports.FileReferenceSerializer=Fx;exports.FileSpawnModel=lA;exports.File_Event=xC;exports.FixedJoint=gb;exports.FixedRotationAxesConstraint=vC;exports.Fog=Fl;exports.FontStyle=bf;exports.FrameEvent=Ce;exports.GENERATOR=al;exports.GameObject=P;exports.GaussianSplat=Kr;exports.Gizmos=B;exports.GltfExport=W_;exports.GltfExportBox=$_;exports.GrabPointPlaneConstraint=Nh;exports.Gradient=ea;exports.Graphic=Qh;exports.GraphicRaycaster=Yf;exports.Graphics=To;exports.GridHelper=jl;exports.GridLayoutGroup=ab;exports.GridSnapConstraint=op;exports.GroundProjectedEnv=ds;exports.GroupActionModel=wr;exports.HideFlags=as;exports.HideOnStart=Gi;exports.HingeJoint=Kh;exports.HorizontalLayoutGroup=rb;exports.HorizontalWrapMode=f1;exports.HostData=gM;exports.Image=ql;exports.ImageReference=Hn;exports.ImageReferenceSerializer=Bx;exports.InheritVelocityModule=wb;exports.Input=Nx;exports.InputEventQueue=xo;exports.InputEvents=xe;exports.InputField=Db;exports.InstanceHandle=Rr;exports.InstancingHandler=jr;exports.InstancingUtil=Ki;exports.InstantiateEvent=wx;exports.InstantiateIdProvider=ot;exports.InstantiateOptions=hs;exports.Interactable=P_;exports.JoinedRoomResponse=QM;exports.KeepRotationConstraint=rp;exports.KeepScaleConstraint=bC;exports.KeyEventArgs=NM;exports.Keyframe=ui;exports.LODGroup=Sp;exports.LODModel=Ul;exports.LODsManager=$x;exports.LeftRoomResponse=YM;exports.Light=Lt;exports.LightData=tS;exports.LimitVelocityOverLifetimeModule=pt;exports.LoadingElementOptions=y3;exports.LogStats=C_;exports.LogType=Ci;exports.LookAt=Ib;exports.LookAtConstraint=Vr;exports.MODULES=A;exports.MainModule=$t;exports.MarkerType=mh;exports.MaskableGraphic=Yh;exports.MaterialPropertyBlock=As;exports.Mathf=L;exports.MeshCollider=Uo;exports.MeshRenderer=Vh;exports.MinMaxCurve=Q;exports.MinMaxGradient=ta;exports.NEEDLE_ENGINE_FEATURE_FLAGS=By;exports.NEKeyboardEvent=xc;exports.NEPointerEvent=Cs;exports.NEToneMappingMode=Ga;exports.NeedleButtonElement=eP;exports.NeedleEngineWebComponent=Ub;exports.NeedleMenu=fs;exports.NeedlePatchesKey=gu;exports.NeedleXRController=Jy;exports.NeedleXRSession=N;exports.NeedleXRSync=hS;exports.NeedleXRUtils=wS;exports.NestedGltf=zl;exports.NetworkConnection=th;exports.NetworkedStreamEvents=is;exports.NetworkedStreams=rd;exports.Networking=bb;exports.NewInstanceModel=Sx;exports.NoiseModule=ve;exports.ObjectRaycaster=Ji;exports.ObjectUtils=jo;exports.OffsetConstraint=Jr;exports.OneEuroFilter=pu;exports.OneEuroFilterXYZ=My;exports.OpenURL=Xl;exports.OrbitControls=ue;exports.Outline=Bl;exports.OwnershipEvent=Xx;exports.OwnershipModel=Qx;exports.PUBLIC_KEY=wo;exports.Padding=Qr;exports.ParticleBurst=wf;exports.ParticleSubEmitter=xb;exports.ParticleSystem=vh;exports.ParticleSystemBaseBehaviour=Wo;exports.ParticleSystemRenderer=rn;exports.ParticleSystemShapeType=vf;exports.PeerHandle=sl;exports.PeerNetworking=Hx;exports.Physics=pl;exports.PhysicsExtension=ib;exports.PhysicsMaterialCombine=mt;exports.PixelationEffect=id;exports.PlaneHeightLockConstraint=E_;exports.PlayAnimationOnClick=_h;exports.PlayAudioOnClick=Do;exports.PlayableDirector=ml;exports.PlayerColor=_l;exports.PlayerState=di;exports.PlayerStateEvent=i1;exports.PlayerSync=J_;exports.PlayerView=Yx;exports.PlayerViewManager=Kx;exports.PointerEventData=Ih;exports.PointerType=Lf;exports.PostProcessing=oS;exports.PostProcessingEffect=rt;exports.PostProcessingEffectOrder=dt;exports.PostProcessingHandler=vl;exports.Prefabs=ll;exports.PreliminaryAction=Dl;exports.PreliminaryTrigger=Gh;exports.PrimitiveType=xl;exports.Progress=he;exports.PromiseAllWithErrors=Py;exports.PromiseErrorResult=hg;exports.QualityLevel=E1;exports.RGBAColor=oe;exports.RapierPhysics=ol;exports.RawImage=Fp;exports.RaycastOptions=zr;exports.Rect=l1;exports.RectTransform=Cn;exports.ReflectionProbe=Ps;exports.ReflectionProbeUsage=RC;exports.RegisteredAnimationInfo=Co;exports.RemoteSkybox=v_;exports.RenderTexture=es;exports.RenderTextureSerializer=nC;exports.Renderer=ti;exports.RendererData=eS;exports.RendererLightmap=B_;exports.Rigidbody=Xe;exports.RigidbodyConstraints=qe;exports.RoomEvents=te;exports.RotationBySpeedModule=on;exports.RotationOverLifetimeModule=Mn;exports.ScaleLimitConstraint=M_;exports.SceneLightSettings=ff;exports.SceneSwitcher=Ye;exports.ScreenCapture=Ho;exports.ScreenSpaceAmbientOcclusion=Xs;exports.ScreenSpaceAmbientOcclusionN8=En;exports.ScreenSpaceAmbientOcclusionN8QualityMode=Sf;exports.ScrollFollow=gs;exports.SeeThrough=Ob;exports.SendQueue=yn;exports.SerializationContext=Eh;exports.SetActiveOnClick=Q_;exports.ShadowCastingMode=gf;exports.ShadowCatcher=ld;exports.ShapeModule=vb;exports.ShapeOverlapResult=px;exports.SharpeningEffect=sd;exports.SignalAsset=Lh;exports.SignalReceiver=Lr;exports.SignalReceiverEvent=Ml;exports.SignalTrackHandler=yh;exports.Size=a1;exports.SizeBySpeedModule=_i;exports.SizeOverLifetimeModule=ia;exports.SkinnedMeshRenderer=F_;exports.SmoothFollow=Ap;exports.SnapToSurfaceConstraint=ap;exports.SpatialGrabRaycaster=Ir;exports.SpatialHtml=ud;exports.SpatialTrigger=Dp;exports.SpatialTriggerReceiver=rs;exports.SpectatorCamera=Ip;exports.SphereCollider=El;exports.SphereIntersection=o_;exports.SplineContainer=la;exports.SplineData=ls;exports.SplineWalker=ln;exports.Sprite=Ws;exports.SpriteData=nl;exports.SpriteRenderer=gi;exports.SpriteSheet=gl;exports.StateMachineBehaviour=cR;exports.StreamEndedEvent=Mb;exports.StreamReceivedEvent=L1;exports.SubEmitterSystem=xf;exports.SyncedCamera=Eb;exports.SyncedRoom=Rn;exports.SyncedTransform=Sn;exports.TapGestureTrigger=K_;exports.TeleportTarget=yp;exports.TestRunner=Rb;exports.TestSimulateUserData=Tb;exports.Text=Nt;exports.TextAnchor=Je;exports.TextBuilder=sb;exports.TextExtension=bp;exports.TextureSheetAnimationModule=Vt;exports.TiltShiftEffect=ms;exports.Time=iS;exports.TimelineActivationTrack=Jf;exports.TimelineAnimationTrack=gh;exports.TimelineAudioTrack=Os;exports.TimelineBuilder=Wp;exports.TimelineControlTrack=ep;exports.TimelineMarkerTrack=Zf;exports.TimelineTrackHandler=Wr;exports.ToneMappingEffect=na;exports.TrackType=we;exports.TrailModule=ze;exports.TransformData=Fe;exports.TransformGizmo=ca;exports.TriggerBuilder=jt;exports.TriggerModel=Eo;exports.TypeStore=M;exports.UIRaycastUtils=m_;exports.UIRootComponent=qh;exports.USDDocument=G_;exports.USDObject=nt;exports.USDWriter=WC;exports.USDZExporter=GC;exports.USDZExporter$1=os;exports.USDZText=Va;exports.USDZUIExtension=cb;exports.UriSerializer=sC;exports.UsageMarker=zh;exports.UserJoinedOrLeftRoomModel=KM;exports.VERSION=Zt;exports.VariantAction=q_;exports.VelocityOverLifetimeModule=We;exports.VerticalLayoutGroup=ob;exports.VerticalWrapMode=u1;exports.VideoPlayer=ut;exports.ViewDevice=Ts;exports.Vignette=ra;exports.VisibilityAction=Hh;exports.Voip=Qs;exports.Volume=od;exports.VolumeParameter=z;exports.VolumeProfile=Mp;exports.WaitForFrames=FM;exports.WaitForPromise=zx;exports.WaitForSeconds=Hy;exports.Watch=Es;exports.WebARCameraBackground=pd;exports.WebARSessionRoot=Qi;exports.WebXR=_p;exports.WebXRButtonFactory=Ro;exports.WebXRImageTracking=Kl;exports.WebXRImageTrackingModel=Zi;exports.WebXRPlaneTracking=Js;exports.WebXRTrackedImage=bl;exports.XRControllerFollow=Ks;exports.XRControllerModel=js;exports.XRControllerMovement=Ti;exports.XRFlag=_n;exports.XRRig=Vp;exports.XRState=Kt;exports.XRStateFlag=Yn;exports.__Ignore=hP;exports.__Pekxq=Yi;exports.__internalNotifyObjectDestroyed=vE;exports.__internalStepGaussianSplatAdaptation=rS;exports._fncZ=ns;exports.activeInHierarchyFieldName=Zn;exports.adaptGaussianSplatQuality=Ky;exports.addAttributeChangeCallback=ju;exports.addComponent=ss;exports.addCustomExtensionPlugin=LA;exports.addNewComponent=kr;exports.addPatch=Tf;exports.apply=lh;exports.applyDef=aP;exports.applyGaussianSplatQuality=Tg;exports.applyHMRChanges=nR;exports.applyOver=lP;exports.applyPrototypeExtensions=DS;exports.beginListenDestroy=xx;exports.beginListenInstantiate=kx;exports.binaryIdentifierCasts=qy;exports.build_scene_functions=hE;exports.builtinComponentKeyName=cr;exports.calculateProgress01=jb;exports.clearMessages=NP;exports.compareAssociation=Ex;exports.copyTexture=Kw;exports.createDefSerializationContext=zb;exports.createMotion=eC;exports.debugNet=oi;exports.debugOwner=Oa;exports.decompressGpuTexture=QC;exports.deepClone=Sh;exports.delay=Ds;exports.delayForFrames=kf;exports.deserializeObject=Jc;exports.destroy=fi;exports.destroyComponentInstance=XS;exports.determineMimeTypeFromExtension=T_;exports.disposeObjectResources=Oe;exports.disposeStream=Hi;exports.editorGuidKeyName=Rs;exports.enableSpatialConsole=qa;exports.evaluateProjectDocument=rP;exports.exportAsGLTF=I3;exports.findByGuid=l_;exports.findObjectOfType=kl;exports.findObjectsOfType=YS;exports.findResourceUsers=r_;exports.fitCamera=aC;exports.fitObjectIntoVolume=Jw;exports.foreachComponent=xn;exports.foreachComponentEnumerator=c_;exports.forward=ak;exports.generateQRCode=yS;exports.generateSeed=Px;exports.getBoundingBox=pi;exports.getCameraController=Vw;exports.getComponent=Bs;exports.getComponentInChildren=Ah;exports.getComponentInParent=ch;exports.getComponents=Cl;exports.getComponentsInChildren=Pl;exports.getComponentsInParent=Gf;exports.getContextResetBehaviors=Ux;exports.getFormattedDate=zC;exports.getGaussianSplatQualityInfo=fO;exports.getIconElement=bt;exports.getIconTexture=Dg;exports.getLoader=Is;exports.getOrAddComponent=Th;exports.getParam=x;exports.getParentHierarchyPath=hk;exports.getPath=bP;exports.getPeerOptions=GM;exports.getPeerjsInstance=Gx;exports.getResourceUserCount=xE;exports.getSceneData=Jx;exports.getTempColor=qw;exports.getTempQuaternion=ci;exports.getTempVector=F;exports.getUrlParams=xh;exports.getVisibleInCustomShadowRendering=Zw;exports.getWorldDirection=Xw;exports.getWorldEuler=Ry;exports.getWorldPosition=ie;exports.getWorldQuaternion=Se;exports.getWorldRotation=Of;exports.getWorldScale=Ve;exports.hasPointerEventComponent=hf;exports.hideDebugConsole=sx;exports.imageToCanvas=YC;exports.initAddressableSerializers=jx;exports.initBuiltinSerializers=oC;exports.initEngine=O3;exports.initPhysics=J1;exports.initVolumeParameterSerializer=pC;exports.instantiate=Ls;exports.invokeLoadedImportPluginHooks=OC;exports.invokeXRSessionEnd=gS;exports.invokeXRSessionStart=mS;exports.isActiveInHierarchy=IS;exports.isActiveSelf=Sl;exports.isAndroidDevice=PP;exports.isAnimationAction=Yw;exports.isComponent=Af;exports.isDebugMode=pP;exports.isDesktop=wP;exports.isDestroyed=Ao;exports.isDevEnvironment=E;exports.isDisposable=JE;exports.isDisposed=bE;exports.isExporting=A3;exports.isGLTFModel=dx;exports.isHostedOnGlitch=Rw;exports.isHotReloadEnabled=Xg;exports.isHotReloading=tR;exports.isIPad=SP;exports.isIconElement=_S;exports.isLocalNetwork=ki;exports.isMacOS=MP;exports.isMobileDevice=xP;exports.isMozillaXR=kP;exports.isQuest=RP;exports.isResourceTrackingEnabled=kS;exports.isSafari=EP;exports.isTrackModel=mT;exports.isUsingInstancing=$f;exports.isiOS=OP;exports.isiPad=CP;exports.isolateChildrenDuring=Fg;exports.loadAsset=C1;exports.loadPMREM=Bh;exports.loadSync=db;exports.logHierarchy=$u;exports.lookAtInverse=JP;exports.lookAtObject=Ch;exports.lookAtScreenPoint=ek;exports.makeId=gP;exports.makeIdFromRandomWords=Dw;exports.makeNameSafe=Ri;exports.markAsInstancedRendered=LS;exports.maxGaussianSplatAdaptationLevel=hr;exports.microphonePermissionsGranted=TP;exports.nameof=fP;exports.nameofFactory=Tw;exports.needle=JM;exports.offBeforeXRSession=pS;exports.offXRSessionEnd=fS;exports.offXRSessionStart=t_;exports.on=eR;exports.onAfterRender=eM;exports.onBeforeRender=Jk;exports.onBeforeXRSession=ZO;exports.onClear=Kk;exports.onDestroy=Zk;exports.onInitialized=Uy;exports.onStart=If;exports.onSyncDestroy=mM;exports.onSyncInstantiate=Cx;exports.onUpdate=_x;exports.onXRSessionEnd=i_;exports.onXRSessionStart=jf;exports.originalComponentNameKey=ah;exports.parseSync=vp;exports.placeOnSurface=ex;exports.postprocessFBXMaterials=Dy;exports.prefix=QR;exports.pushState=Aw;exports.randomNumber=yP;exports.registerBinaryType=Xy;exports.registerComponent=zf;exports.registerComponentExtension=I_;exports.registerCustomEffectType=an;exports.registerExportExtensions=L_;exports.registerExtensions=mf;exports.registerHotReloadType=KS;exports.registerLoader=gx;exports.registerPrefabProvider=Mx;exports.registerPrototypeExtensions=a_;exports.registerType=Ly;exports.relativePathPrefix=Lw;exports.removeAttributeChangeCallback=Fw;exports.removeComponent=Wf;exports.removeCustomImportExtensionType=BA;exports.removePatch=Wk;exports.resolveGaussianSplatQuality=Ff;exports.resolveUrl=cs;exports.sUknx=kh;exports.sanitizeString=Iw;exports.saveImage=K1;exports.screenshot=Z2;exports.screenshot2=Fb;exports.sendDestroyed=$y;exports.serializable=p;exports.serializeObject=Ax;exports.serializeable=Qe;exports.setActive=Pr;exports.setAllowBalloonMessages=zw;exports.setAllowOverlayMessages=FP;exports.setAutoFitEnabled=zu;exports.setCameraController=fg;exports.setDestroyed=FS;exports.setDevEnvironment=HP;exports.setDisposable=OS;exports.setDontDestroy=Ea;exports.setOrAddParamsToUrl=cg;exports.setParam=mP;exports.setParamWithoutReload=Yc;exports.setPeerOptions=HM;exports.setPhysicsEngineFactory=SS;exports.setResourceTrackingEnabled=_E;exports.setState=Sy;exports.setVisibleInCustomShadowRendering=Ay;exports.setWorldEuler=Ty;exports.setWorldPosition=Oi;exports.setWorldPositionXYZ=Ar;exports.setWorldQuaternion=vn;exports.setWorldQuaternionXYZW=Ey;exports.setWorldRotation=Qw;exports.setWorldRotationXYZ=Ph;exports.setWorldScale=rl;exports.showBalloonError=wl;exports.showBalloonMessage=Re;exports.showBalloonWarning=de;exports.showDebugConsole=Iy;exports.slerp=Gw;exports.syncDestroy=Mh;exports.syncField=b_;exports.syncInstantiate=Vy;exports.textureToCanvas=dk;exports.toSourceId=Bw;exports.tryCastBinary=Vx;exports.tryDetermineMimetypeFromBinary=PC;exports.tryDetermineMimetypeFromURL=CC;exports.tryFindObject=Kc;exports.tryGetExtensionFromUrl=SC;exports.tryGetGuid=Wx;exports.unregisterHotReloadType=ZS;exports.unregisterPrefabProvider=_M;exports.unwatchWrite=Cy;exports.useForAutoFit=Ww;exports.validate=je;exports.watchWrite=Mf;
|
|
1860
|
+
`),si&&this._onCreateEffectsDebug(this._composer,o)}createPassForMergeableEffects(e,t,i,n){if(e.length>0){const o=new A.POSTPROCESSING.MODULE.EffectPass(i,...e);o.name=e.map(r=>r.name).join(", "),o.mainScene=n,o.enabled=!0,o.renderToScreen=!1,t.addPass(o),e.length=0}}handleDevicePixelRatio(){typeof this.context.devicePixelRatio=="number"&&this.context.requestSizeUpdate()}_menuEntry=null;_passIndices=null;_onCreateEffectsDebug(e,t){if(si==="passes"){const i=new A.POSTPROCESSING.MODULE.DepthEffect({blendFunction:A.POSTPROCESSING.MODULE.BlendFunction.NORMAL,inverted:!0});i.name="Depth Effect";const n=new A.POSTPROCESSING.MODULE.EffectPass(t,i);if(n.name="Depth Effect Pass",n.enabled=!1,e.passes.push(n),this._passIndices!==null){const r=[e.passes[0]];this._passIndices.length>0&&r.push(...this._passIndices.filter(a=>a!==0).map(a=>e.passes[a]).filter(a=>a)),r.length>0&&console.log("[PostProcessing] Passes (selected) →",r),e.passes.length=0;for(const a of r)a.enabled=!0,a.renderToScreen=!1,e.addPass(a)}const o=this.context.menu;if(o&&this._passIndices===null){this._menuEntry&&this._menuEntry.remove();const r=document.createElement("select");r.multiple=!0;const a=document.createElement("option");a.innerText="Final Output",a.value="-1",r.appendChild(a);for(const l of e.passes){const h=document.createElement("option");h.innerText=l.name,h.value=`${e.passes.indexOf(l)}`,h.title=l.name,r.appendChild(h)}o.appendChild(r),this._menuEntry=r,r.addEventListener("change",()=>{const l=Array.from(r.selectedOptions).map(h=>parseInt(h.value));l.length===1&&l[0]===-1?this._passIndices=null:this._passIndices=l,this.applyEffects(this.context)})}}}}const F3=Object.freeze(Object.defineProperty({__proto__:null,PostProcessingHandler:vl},Symbol.toStringTag,{value:"Module"}));class Wp{_name;_tracks=[];_currentTrack=null;_pendingSignals=[];_idProvider;constructor(e,t){this._name=e,this._idProvider=new ot(t??Date.now())}static create(e,t){return new Wp(e??"Timeline",t)}animationTrack(e,t){return this.commitInlineTracks(),this._currentTrack=this.pushTrack(e,we.Animation,t??null),this}audioTrack(e,t,i){return this.commitInlineTracks(),this._currentTrack=this.pushTrack(e,we.Audio,t??null),this._currentTrack.volume=i,this}activationTrack(e,t){return this.commitInlineTracks(),this._currentTrack=this.pushTrack(e,we.Activation,t??null),this}controlTrack(e){return this.commitInlineTracks(),this._currentTrack=this.pushTrack(e,we.Control,null),this}signalTrack(e,t){return this.commitInlineTracks(),this._currentTrack=this.pushTrack(e,we.Signal,t??null),this}markerTrack(e){return this.commitInlineTracks(),this._currentTrack=this.pushTrack(e,we.Marker,null),this}clip(e,t){if(!this._currentTrack)throw new Error("TimelineBuilder: .clip() must be called after a track method (e.g. .animationTrack())");this.commitInlineTracks();const i=this._currentTrack;switch(i.type){case we.Animation:{let n;if(e instanceof c.AnimationClip)n=e;else{const d=Array.isArray(e)?e:[e],u=i.outputs[0],f=u instanceof c.Object3D?u:u!=null&&"gameObject"in u?u.gameObject:void 0;n=dh(d,f)}const o=t??{},r=o.duration??n.duration,a=o.start??i.cursor,l=a+r,h={start:a,end:l,duration:r,timeScale:o.speed??1,clipIn:o.clipIn??0,easeInDuration:o.easeIn??0,easeOutDuration:o.easeOut??0,preExtrapolationMode:o.preExtrapolation??et.None,postExtrapolationMode:o.postExtrapolation??et.None,reversed:o.reversed,asset:{clip:n,loop:o.loop??!1,duration:n.duration,removeStartOffset:o.removeStartOffset??!1}};i.clips.push(h),i.cursor=l;break}case we.Audio:{const n=e,o=t??{},r=o.duration,a=o.start??i.cursor,l=a+r,h={start:a,end:l,duration:r,timeScale:o.speed??1,clipIn:0,easeInDuration:o.easeIn??0,easeOutDuration:o.easeOut??0,preExtrapolationMode:et.None,postExtrapolationMode:et.None,asset:{clip:n,loop:o.loop??!1,volume:o.volume??1}};i.clips.push(h),i.cursor=l;break}case we.Activation:{const n=e,o=n.start??i.cursor,r=o+n.duration,a={start:o,end:r,duration:n.duration,timeScale:1,clipIn:0,easeInDuration:n.easeIn??0,easeOutDuration:n.easeOut??0,preExtrapolationMode:et.None,postExtrapolationMode:et.None,asset:{}};i.clips.push(a),i.cursor=r;break}case we.Control:{const n=e,o=t??{},r=o.start??i.cursor,a=o.duration,l=r+a,h={start:r,end:l,duration:a,timeScale:1,clipIn:0,easeInDuration:0,easeOutDuration:0,preExtrapolationMode:et.None,postExtrapolationMode:et.None,asset:{sourceObject:n,controlActivation:o.controlActivation??!0,updateDirector:o.updateDirector??!0}};i.clips.push(h),i.cursor=l;break}default:throw new Error(`TimelineBuilder: .clip() is not supported on track type "${i.type}"`)}return this}marker(e,t,i){if(!this._currentTrack)throw new Error("TimelineBuilder: .marker() must be called after a track method");if(this._currentTrack.type!==we.Signal&&this._currentTrack.type!==we.Marker)throw new Error(`TimelineBuilder: .marker() is only supported on signal and marker tracks, not "${this._currentTrack.type}"`);const n={type:mh.Signal,time:e,retroActive:i?.retroActive??!1,emitOnce:i?.emitOnce??!1,asset:t};return this._currentTrack.markers.push(n),e>this._currentTrack.cursor&&(this._currentTrack.cursor=e),this}signal(e,t,i){if(!this._currentTrack)throw new Error("TimelineBuilder: .signal() must be called after a track method");if(this._currentTrack.type!==we.Signal&&this._currentTrack.type!==we.Marker)throw new Error(`TimelineBuilder: .signal() is only supported on signal and marker tracks, not "${this._currentTrack.type}"`);const n=this._idProvider.generateUUID(),o=this._tracks.indexOf(this._currentTrack),r={type:mh.Signal,time:e,retroActive:i?.retroActive??!1,emitOnce:i?.emitOnce??!1,asset:n};return this._currentTrack.markers.push(r),this._pendingSignals.push({trackIndex:o,guid:n,callback:t}),e>this._currentTrack.cursor&&(this._currentTrack.cursor=e),this}muted(e=!0){if(!this._currentTrack)throw new Error("TimelineBuilder: .muted() must be called after a track method");return this._currentTrack.muted=e,this}track(e,t,i,n){if(!this._currentTrack)throw new Error("TimelineBuilder: .track() must be called after .animationTrack()");if(this._currentTrack.type!==we.Animation)throw new Error("TimelineBuilder: .track() is only supported on animation tracks");return this._currentTrack.inlineTracks.push(u_(e,t,i,n)),this}build(){this.commitInlineTracks();const e=this._tracks.map(t=>{const i={name:t.name,type:t.type,muted:t.muted,outputs:t.outputs};return t.clips.length>0&&(i.clips=t.clips),t.markers.length>0&&(i.markers=t.markers),t.volume!==void 0&&(i.volume=t.volume),t.trackOffset!==void 0&&(i.trackOffset=t.trackOffset),i});return{name:this._name,tracks:e}}install(e){const t=this.build();if(this._pendingSignals.length>0){const i=e.gameObject;let n=P.getComponent(i,Lr);n||(n=P.addComponent(i,Lr)),n.events||(n.events=[]);for(const o of this._pendingSignals){const r=new Lh;r.guid=o.guid;const a=new Ml;a.signal=r,a.reaction=new Z([o.callback]),n.events.push(a);const l=t.tracks[o.trackIndex];l&&!l.outputs.includes(n)&&l.outputs.push(n)}}return e.playableAsset=t,t}pushTrack(e,t,i){const n={name:e,type:t,muted:!1,outputs:i?[i]:[],clips:[],markers:[],cursor:0,inlineTracks:[]};return this._tracks.push(n),n}commitInlineTracks(){if(!this._currentTrack||this._currentTrack.inlineTracks.length===0)return;const e=this._currentTrack,t=e.outputs[0],i=t instanceof c.Object3D?t:t!=null&&"gameObject"in t?t.gameObject:void 0,n=dh(e.inlineTracks,i),o=e.cursor,r=n.duration,a={start:o,end:o+r,duration:r,timeScale:1,clipIn:0,easeInDuration:0,easeOutDuration:0,preExtrapolationMode:et.None,postExtrapolationMode:et.None,asset:{clip:n,loop:!1,duration:n.duration,removeStartOffset:!1}};e.clips.push(a),e.cursor=o+r,e.inlineTracks=[]}}class hP{}const j3=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:pe,ActionCollection:JC,ActionModel:li,AlignmentConstraint:jh,Animation:Ut,AnimationBuilder:Hf,AnimationCurve:Zh,AnimationExtension:up,Animator:vt,AnimatorController:Jn,Antialiasing:ed,Attractor:$l,AudioExtension:qr,AudioListener:Ms,AudioSource:Ei,Avatar:Io,AvatarMarker:it,AxesHelper:Ol,AxisRotationConstraint:O_,BaseUIComponent:en,BasicIKConstraint:x_,BehaviorExtension:tb,BehaviorModel:Dt,BloomEffect:Ep,BoxCollider:np,BoxGizmo:Zr,BoxHelperComponent:At,Button:Ys,CallInfo:vi,Camera:Jt,CameraTargetReachedEvent:ph,Canvas:yl,CanvasGroup:Lo,CapsuleCollider:Fs,ChangeMaterialOnClick:X_,ChangeTransformOnClick:Xr,CharacterController:Gr,CharacterControllerInput:Ns,ChromaticAberration:td,ClickThrough:zp,ColorAdjustments:Go,ColorBySpeedModule:Nl,ColorOverLifetimeModule:kp,ContactShadows:Uh,CursorFollow:ha,CustomBranding:Yr,Deletable:k_,DeleteBox:Oo,DepthOfField:On,DeviceFlag:sp,DocumentExtension:cP,DragControls:vr,DragProfile:uf,DropListener:Vs,Duplicatable:U_,EffectWrapper:wh,EmissionModule:qs,EmphasizeOnClick:Al,EnvironmentScene:ip,EventList:Z,EventListEvent:f_,EventSystem:ei,EventTrigger:hp,FieldWithDefault:TC,FixedJoint:gb,FixedRotationAxesConstraint:vC,Fog:Fl,GaussianSplat:Kr,GltfExport:W_,GltfExportBox:$_,GrabPointPlaneConstraint:Nh,Gradient:ea,Graphic:Qh,GraphicRaycaster:Yf,GridHelper:jl,GridLayoutGroup:ab,GridSnapConstraint:op,GroundProjectedEnv:ds,GroupActionModel:wr,HideOnStart:Gi,HingeJoint:Kh,HorizontalLayoutGroup:rb,get HoverAnimation(){return exports.HoverAnimation},Image:ql,InheritVelocityModule:wb,InputField:Db,InstanceHandle:Rr,InstancingHandler:jr,Interactable:P_,KeepRotationConstraint:rp,KeepScaleConstraint:bC,Keyframe:ui,LODGroup:Sp,LODModel:Ul,Light:Lt,LimitVelocityOverLifetimeModule:pt,LogStats:C_,LookAt:Ib,LookAtConstraint:Vr,MainModule:$t,MaskableGraphic:Yh,MeshCollider:Uo,MeshRenderer:Vh,MinMaxCurve:Q,MinMaxGradient:ta,NeedleMenu:fs,NestedGltf:zl,Networking:bb,NoiseModule:ve,ObjectRaycaster:Ji,OffsetConstraint:Jr,OpenURL:Xl,OrbitControls:ue,Outline:Bl,Padding:Qr,ParticleBurst:wf,ParticleSubEmitter:xb,ParticleSystem:vh,ParticleSystemRenderer:rn,PhysicsExtension:ib,PixelationEffect:id,PlaneHeightLockConstraint:E_,PlayAnimationOnClick:_h,PlayAudioOnClick:Do,PlayableDirector:ml,PlayerColor:_l,PointerEventData:Ih,PostProcessingHandler:vl,PreliminaryAction:Dl,PreliminaryTrigger:Gh,RawImage:Fp,Rect:l1,RectTransform:Cn,ReflectionProbe:Ps,RegisteredAnimationInfo:Co,RemoteSkybox:v_,Renderer:ti,RendererLightmap:B_,Rigidbody:Xe,RotationBySpeedModule:on,RotationOverLifetimeModule:Mn,ScaleLimitConstraint:M_,SceneSwitcher:Ye,ScreenCapture:Ho,ScreenSpaceAmbientOcclusion:Xs,ScreenSpaceAmbientOcclusionN8:En,ScrollFollow:gs,SeeThrough:Ob,SetActiveOnClick:Q_,ShadowCatcher:ld,ShapeModule:vb,SharpeningEffect:sd,SignalAsset:Lh,SignalReceiver:Lr,SignalReceiverEvent:Ml,SignalTrackHandler:yh,Size:a1,SizeBySpeedModule:_i,SizeOverLifetimeModule:ia,SkinnedMeshRenderer:F_,SmoothFollow:Ap,SnapToSurfaceConstraint:ap,SpatialGrabRaycaster:Ir,SpatialHtml:ud,SpatialTrigger:Dp,SpatialTriggerReceiver:rs,SpectatorCamera:Ip,SphereCollider:El,SplineContainer:la,SplineData:ls,SplineWalker:ln,Sprite:Ws,SpriteData:nl,SpriteRenderer:gi,SpriteSheet:gl,SubEmitterSystem:xf,SyncedCamera:Eb,SyncedRoom:Rn,SyncedTransform:Sn,TapGestureTrigger:K_,TeleportTarget:yp,TestRunner:Rb,TestSimulateUserData:Tb,Text:Nt,TextBuilder:sb,TextExtension:bp,TextureSheetAnimationModule:Vt,TiltShiftEffect:ms,TimelineActivationTrack:Jf,TimelineAnimationTrack:gh,TimelineAudioTrack:Os,TimelineBuilder:Wp,TimelineControlTrack:ep,TimelineMarkerTrack:Zf,ToneMappingEffect:na,TrailModule:ze,TransformData:Fe,TransformGizmo:ca,TriggerBuilder:jt,TriggerModel:Eo,UIRaycastUtils:m_,UIRootComponent:qh,USDZExporter:os,USDZText:Va,USDZUIExtension:cb,UsageMarker:zh,VariantAction:q_,VelocityOverLifetimeModule:We,VerticalLayoutGroup:ob,VideoPlayer:ut,get ViewBox(){return exports.ViewBox},Vignette:ra,VisibilityAction:Hh,Voip:Qs,Volume:od,VolumeParameter:z,VolumeProfile:Mp,WebARCameraBackground:pd,WebARSessionRoot:Qi,WebXR:_p,WebXRImageTracking:Kl,WebXRImageTrackingModel:Zi,WebXRPlaneTracking:Js,WebXRTrackedImage:bl,XRControllerFollow:Ks,XRControllerModel:js,XRControllerMovement:Ti,XRFlag:_n,XRRig:Vp,XRState:Kt,__Ignore:hP},Symbol.toStringTag,{value:"Module"}));exports.SplineUtils=void 0;(s=>{function e(t,i=!1,n=.75){const o=new la,r=1-L.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 ls;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 U3 extends ee.WorkerBase{constructor(){super(new Worker(new URL("/generateMeshBVH.worker-Be19n6m6.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:Ha&&Ha.tagName.toUpperCase()==="SCRIPT"&&Ha.src||new URL("needle-engine.bundle-DOHf03pR.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||"Could not load worker."}`))},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:f}=d,m=ee.MeshBVH.deserialize(u,t,{setIndex:!1}),g=Object.assign({setBoundingBox:!0},i);if(t.attributes.position.array=f,u.index)if(t.index)t.index.array=u.index;else{const v=new c.BufferAttribute(u.index,1,!1);t.setIndex(v)}g.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)))}).finally(()=>{e.onmessage=null,e.onerror=null})}}const z3=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:U3},Symbol.toStringTag,{value:"Module"}));exports.$componentName=Gu;exports.$jVksoCHS=ns;exports.$physicsKey=qk;exports.ActionBuilder=pe;exports.ActionCollection=JC;exports.ActionModel=li;exports.Addressables=Lx;exports.AlignmentConstraint=jh;exports.AmbientMode=Ya;exports.Animation=Ut;exports.AnimationBuilder=Hf;exports.AnimationCurve=Zh;exports.AnimationExtension=up;exports.Animator=vt;exports.AnimatorConditionMode=hi;exports.AnimatorController=Jn;exports.AnimatorControllerBuilder=qf;exports.AnimatorControllerParameterType=br;exports.AnimatorStateInfo=Pc;exports.Antialiasing=ed;exports.Application=wn;exports.AssetDatabase=CS;exports.AssetReference=J;exports.Attractor=$l;exports.AudioClip=Yg;exports.AudioExtension=qr;exports.AudioListener=Ms;exports.AudioRolloffMode=hC;exports.AudioSource=Ei;exports.Avatar=Io;exports.AvatarMarker=it;exports.Axes=$a;exports.AxesHelper=Ol;exports.AxisRotationConstraint=O_;exports.BUILD_TIME=Zc;exports.BaseUIComponent=en;exports.BasicIKConstraint=x_;exports.BehaviorExtension=tb;exports.BehaviorModel=Dt;exports.BloomEffect=Ep;exports.BoxCollider=np;exports.BoxGizmo=Zr;exports.BoxHelperComponent=At;exports.Button=Ys;exports.ButtonsFactory=Xi;exports.CallDirection=B1;exports.CallInfo=vi;exports.Camera=Jt;exports.CameraTargetReachedEvent=ph;exports.Canvas=yl;exports.CanvasGroup=Lo;exports.CapsuleCollider=Fs;exports.ChangeMaterialOnClick=X_;exports.ChangeTransformOnClick=Xr;exports.CharacterController=Gr;exports.CharacterControllerInput=Ns;exports.ChromaticAberration=td;exports.CircularBuffer=Mi;exports.ClearFlags=Or;exports.ClickThrough=zp;exports.ClipExtrapolation=et;exports.Collider=Ii;exports.Collision=fx;exports.CollisionDetectionMode=Qf;exports.ColorAdjustments=Go;exports.ColorBySpeedModule=Nl;exports.ColorOverLifetimeModule=kp;exports.Component=sR;exports.Component$1=T;exports.ComponentLifecycleEvents=Rf;exports.Components=j3;exports.ConnectionEvents=qx;exports.ContactPoint=ux;exports.ContactShadows=Uh;exports.Context=X;exports.ContextArgs=dE;exports.ContextEvent=ae;exports.ContextRegistry=se;exports.CursorFollow=ha;exports.CustomBranding=Yr;exports.CustomShader=Me;exports.DefaultReflectionMode=Ju;exports.Deletable=k_;exports.DeleteBox=Oo;exports.DepthOfField=On;exports.DepthOfFieldMode=A1;exports.DeviceFlag=sp;exports.DirectorWrapMode=uC;exports.DisposableStore=Ou;exports.DocumentExtension=cP;exports.DragControls=vr;exports.DragMode=R_;exports.DragProfile=uf;exports.DropListener=Vs;exports.Duplicatable=U_;exports.EffectWrapper=wh;exports.EmissionModule=qs;exports.EmphasizeOnClick=Al;exports.EngineLoadingView=Tr;exports.EnvironmentScene=ip;exports.EventBus=Og;exports.EventList=Z;exports.EventListEvent=f_;exports.EventSystem=ei;exports.EventTrigger=hp;exports.FieldWithDefault=TC;exports.FileReference=qn;exports.FileReferenceSerializer=Fx;exports.FileSpawnModel=lA;exports.File_Event=xC;exports.FixedJoint=gb;exports.FixedRotationAxesConstraint=vC;exports.Fog=Fl;exports.FontStyle=bf;exports.FrameEvent=Ce;exports.GENERATOR=al;exports.GameObject=P;exports.GaussianSplat=Kr;exports.Gizmos=B;exports.GltfExport=W_;exports.GltfExportBox=$_;exports.GrabPointPlaneConstraint=Nh;exports.Gradient=ea;exports.Graphic=Qh;exports.GraphicRaycaster=Yf;exports.Graphics=To;exports.GridHelper=jl;exports.GridLayoutGroup=ab;exports.GridSnapConstraint=op;exports.GroundProjectedEnv=ds;exports.GroupActionModel=wr;exports.HideFlags=as;exports.HideOnStart=Gi;exports.HingeJoint=Kh;exports.HorizontalLayoutGroup=rb;exports.HorizontalWrapMode=f1;exports.HostData=gM;exports.Image=ql;exports.ImageReference=Hn;exports.ImageReferenceSerializer=Bx;exports.InheritVelocityModule=wb;exports.Input=Nx;exports.InputEventQueue=xo;exports.InputEvents=xe;exports.InputField=Db;exports.InstanceHandle=Rr;exports.InstancingHandler=jr;exports.InstancingUtil=Ki;exports.InstantiateEvent=wx;exports.InstantiateIdProvider=ot;exports.InstantiateOptions=hs;exports.Interactable=P_;exports.JoinedRoomResponse=QM;exports.KLnyx=Yi;exports.KeepRotationConstraint=rp;exports.KeepScaleConstraint=bC;exports.KeyEventArgs=NM;exports.Keyframe=ui;exports.LODGroup=Sp;exports.LODModel=Ul;exports.LODsManager=$x;exports.LeftRoomResponse=YM;exports.Light=Lt;exports.LightData=tS;exports.LimitVelocityOverLifetimeModule=pt;exports.LoadingElementOptions=y3;exports.LogStats=C_;exports.LogType=Ci;exports.LookAt=Ib;exports.LookAtConstraint=Vr;exports.MODULES=A;exports.MainModule=$t;exports.MarkerType=mh;exports.MaskableGraphic=Yh;exports.MaterialPropertyBlock=As;exports.Mathf=L;exports.MeshCollider=Uo;exports.MeshRenderer=Vh;exports.MinMaxCurve=Q;exports.MinMaxGradient=ta;exports.NEEDLE_ENGINE_FEATURE_FLAGS=By;exports.NEKeyboardEvent=xc;exports.NEPointerEvent=Cs;exports.NEToneMappingMode=Ga;exports.NeedleButtonElement=eP;exports.NeedleEngineWebComponent=Ub;exports.NeedleMenu=fs;exports.NeedlePatchesKey=gu;exports.NeedleXRController=Jy;exports.NeedleXRSession=N;exports.NeedleXRSync=hS;exports.NeedleXRUtils=wS;exports.NestedGltf=zl;exports.NetworkConnection=th;exports.NetworkedStreamEvents=is;exports.NetworkedStreams=rd;exports.Networking=bb;exports.NewInstanceModel=Sx;exports.NoiseModule=ve;exports.ObjectRaycaster=Ji;exports.ObjectUtils=jo;exports.OffsetConstraint=Jr;exports.OneEuroFilter=pu;exports.OneEuroFilterXYZ=My;exports.OpenURL=Xl;exports.OrbitControls=ue;exports.Outline=Bl;exports.OwnershipEvent=Xx;exports.OwnershipModel=Qx;exports.PUBLIC_KEY=wo;exports.Padding=Qr;exports.ParticleBurst=wf;exports.ParticleSubEmitter=xb;exports.ParticleSystem=vh;exports.ParticleSystemBaseBehaviour=Wo;exports.ParticleSystemRenderer=rn;exports.ParticleSystemShapeType=vf;exports.PeerHandle=sl;exports.PeerNetworking=Hx;exports.Physics=pl;exports.PhysicsExtension=ib;exports.PhysicsMaterialCombine=mt;exports.PixelationEffect=id;exports.PlaneHeightLockConstraint=E_;exports.PlayAnimationOnClick=_h;exports.PlayAudioOnClick=Do;exports.PlayableDirector=ml;exports.PlayerColor=_l;exports.PlayerState=di;exports.PlayerStateEvent=i1;exports.PlayerSync=J_;exports.PlayerView=Yx;exports.PlayerViewManager=Kx;exports.PointerEventData=Ih;exports.PointerType=Lf;exports.PostProcessing=oS;exports.PostProcessingEffect=rt;exports.PostProcessingEffectOrder=dt;exports.PostProcessingHandler=vl;exports.Prefabs=ll;exports.PreliminaryAction=Dl;exports.PreliminaryTrigger=Gh;exports.PrimitiveType=xl;exports.Progress=he;exports.PromiseAllWithErrors=Py;exports.PromiseErrorResult=hg;exports.QualityLevel=E1;exports.RGBAColor=oe;exports.RapierPhysics=ol;exports.RawImage=Fp;exports.RaycastOptions=zr;exports.Rect=l1;exports.RectTransform=Cn;exports.ReflectionProbe=Ps;exports.ReflectionProbeUsage=RC;exports.RegisteredAnimationInfo=Co;exports.RemoteSkybox=v_;exports.RenderTexture=es;exports.RenderTextureSerializer=nC;exports.Renderer=ti;exports.RendererData=eS;exports.RendererLightmap=B_;exports.Rigidbody=Xe;exports.RigidbodyConstraints=qe;exports.RoomEvents=te;exports.RotationBySpeedModule=on;exports.RotationOverLifetimeModule=Mn;exports.ScaleLimitConstraint=M_;exports.SceneLightSettings=ff;exports.SceneSwitcher=Ye;exports.ScreenCapture=Ho;exports.ScreenSpaceAmbientOcclusion=Xs;exports.ScreenSpaceAmbientOcclusionN8=En;exports.ScreenSpaceAmbientOcclusionN8QualityMode=Sf;exports.ScrollFollow=gs;exports.SeeThrough=Ob;exports.SendQueue=yn;exports.SerializationContext=Eh;exports.SetActiveOnClick=Q_;exports.ShadowCastingMode=gf;exports.ShadowCatcher=ld;exports.ShapeModule=vb;exports.ShapeOverlapResult=px;exports.SharpeningEffect=sd;exports.SignalAsset=Lh;exports.SignalReceiver=Lr;exports.SignalReceiverEvent=Ml;exports.SignalTrackHandler=yh;exports.Size=a1;exports.SizeBySpeedModule=_i;exports.SizeOverLifetimeModule=ia;exports.SkinnedMeshRenderer=F_;exports.SmoothFollow=Ap;exports.SnapToSurfaceConstraint=ap;exports.SpatialGrabRaycaster=Ir;exports.SpatialHtml=ud;exports.SpatialTrigger=Dp;exports.SpatialTriggerReceiver=rs;exports.SpectatorCamera=Ip;exports.SphereCollider=El;exports.SphereIntersection=o_;exports.SplineContainer=la;exports.SplineData=ls;exports.SplineWalker=ln;exports.Sprite=Ws;exports.SpriteData=nl;exports.SpriteRenderer=gi;exports.SpriteSheet=gl;exports.StateMachineBehaviour=cR;exports.StreamEndedEvent=Mb;exports.StreamReceivedEvent=L1;exports.SubEmitterSystem=xf;exports.SyncedCamera=Eb;exports.SyncedRoom=Rn;exports.SyncedTransform=Sn;exports.TapGestureTrigger=K_;exports.TeleportTarget=yp;exports.TestRunner=Rb;exports.TestSimulateUserData=Tb;exports.Text=Nt;exports.TextAnchor=Je;exports.TextBuilder=sb;exports.TextExtension=bp;exports.TextureSheetAnimationModule=Vt;exports.TiltShiftEffect=ms;exports.Time=iS;exports.TimelineActivationTrack=Jf;exports.TimelineAnimationTrack=gh;exports.TimelineAudioTrack=Os;exports.TimelineBuilder=Wp;exports.TimelineControlTrack=ep;exports.TimelineMarkerTrack=Zf;exports.TimelineTrackHandler=Wr;exports.ToneMappingEffect=na;exports.TrackType=we;exports.TrailModule=ze;exports.TransformData=Fe;exports.TransformGizmo=ca;exports.TriggerBuilder=jt;exports.TriggerModel=Eo;exports.TypeStore=M;exports.UIRaycastUtils=m_;exports.UIRootComponent=qh;exports.USDDocument=G_;exports.USDObject=nt;exports.USDWriter=WC;exports.USDZExporter=GC;exports.USDZExporter$1=os;exports.USDZText=Va;exports.USDZUIExtension=cb;exports.UriSerializer=sC;exports.UsageMarker=zh;exports.UserJoinedOrLeftRoomModel=KM;exports.VERSION=Zt;exports.VariantAction=q_;exports.VelocityOverLifetimeModule=We;exports.VerticalLayoutGroup=ob;exports.VerticalWrapMode=u1;exports.VideoPlayer=ut;exports.ViewDevice=Ts;exports.Vignette=ra;exports.VisibilityAction=Hh;exports.Voip=Qs;exports.Volume=od;exports.VolumeParameter=z;exports.VolumeProfile=Mp;exports.WaitForFrames=FM;exports.WaitForPromise=zx;exports.WaitForSeconds=Hy;exports.Watch=Es;exports.WebARCameraBackground=pd;exports.WebARSessionRoot=Qi;exports.WebXR=_p;exports.WebXRButtonFactory=Ro;exports.WebXRImageTracking=Kl;exports.WebXRImageTrackingModel=Zi;exports.WebXRPlaneTracking=Js;exports.WebXRTrackedImage=bl;exports.XRControllerFollow=Ks;exports.XRControllerModel=js;exports.XRControllerMovement=Ti;exports.XRFlag=_n;exports.XRRig=Vp;exports.XRState=Kt;exports.XRStateFlag=Yn;exports._$sHuA=kh;exports.__Ignore=hP;exports.__internalNotifyObjectDestroyed=vE;exports.__internalStepGaussianSplatAdaptation=rS;exports.activeInHierarchyFieldName=Zn;exports.adaptGaussianSplatQuality=Ky;exports.addAttributeChangeCallback=ju;exports.addComponent=ss;exports.addCustomExtensionPlugin=LA;exports.addNewComponent=kr;exports.addPatch=Tf;exports.apply=lh;exports.applyDef=aP;exports.applyGaussianSplatQuality=Tg;exports.applyHMRChanges=nR;exports.applyOver=lP;exports.applyPrototypeExtensions=DS;exports.beginListenDestroy=xx;exports.beginListenInstantiate=kx;exports.binaryIdentifierCasts=qy;exports.build_scene_functions=hE;exports.builtinComponentKeyName=cr;exports.calculateProgress01=jb;exports.clearMessages=NP;exports.compareAssociation=Ex;exports.copyTexture=Kw;exports.createDefSerializationContext=zb;exports.createMotion=eC;exports.debugNet=oi;exports.debugOwner=Oa;exports.decompressGpuTexture=QC;exports.deepClone=Sh;exports.delay=Ds;exports.delayForFrames=kf;exports.deserializeObject=Jc;exports.destroy=fi;exports.destroyComponentInstance=XS;exports.determineMimeTypeFromExtension=T_;exports.disposeObjectResources=Oe;exports.disposeStream=Hi;exports.editorGuidKeyName=Rs;exports.enableSpatialConsole=qa;exports.evaluateProjectDocument=rP;exports.exportAsGLTF=I3;exports.findByGuid=l_;exports.findObjectOfType=kl;exports.findObjectsOfType=YS;exports.findResourceUsers=r_;exports.fitCamera=aC;exports.fitObjectIntoVolume=Jw;exports.foreachComponent=xn;exports.foreachComponentEnumerator=c_;exports.forward=ak;exports.generateQRCode=yS;exports.generateSeed=Px;exports.getBoundingBox=pi;exports.getCameraController=Vw;exports.getComponent=Bs;exports.getComponentInChildren=Ah;exports.getComponentInParent=ch;exports.getComponents=Cl;exports.getComponentsInChildren=Pl;exports.getComponentsInParent=Gf;exports.getContextResetBehaviors=Ux;exports.getFormattedDate=zC;exports.getGaussianSplatQualityInfo=fO;exports.getIconElement=bt;exports.getIconTexture=Dg;exports.getLoader=Is;exports.getOrAddComponent=Th;exports.getParam=x;exports.getParentHierarchyPath=hk;exports.getPath=bP;exports.getPeerOptions=GM;exports.getPeerjsInstance=Gx;exports.getResourceUserCount=xE;exports.getSceneData=Jx;exports.getTempColor=qw;exports.getTempQuaternion=ci;exports.getTempVector=F;exports.getUrlParams=xh;exports.getVisibleInCustomShadowRendering=Zw;exports.getWorldDirection=Xw;exports.getWorldEuler=Ry;exports.getWorldPosition=ie;exports.getWorldQuaternion=Se;exports.getWorldRotation=Of;exports.getWorldScale=Ve;exports.hasPointerEventComponent=hf;exports.hideDebugConsole=sx;exports.imageToCanvas=YC;exports.initAddressableSerializers=jx;exports.initBuiltinSerializers=oC;exports.initEngine=O3;exports.initPhysics=J1;exports.initVolumeParameterSerializer=pC;exports.instantiate=Ls;exports.invokeLoadedImportPluginHooks=OC;exports.invokeXRSessionEnd=gS;exports.invokeXRSessionStart=mS;exports.isActiveInHierarchy=IS;exports.isActiveSelf=Sl;exports.isAndroidDevice=PP;exports.isAnimationAction=Yw;exports.isComponent=Af;exports.isDebugMode=pP;exports.isDesktop=wP;exports.isDestroyed=Ao;exports.isDevEnvironment=E;exports.isDisposable=JE;exports.isDisposed=bE;exports.isExporting=A3;exports.isGLTFModel=dx;exports.isHostedOnGlitch=Rw;exports.isHotReloadEnabled=Xg;exports.isHotReloading=tR;exports.isIPad=SP;exports.isIconElement=_S;exports.isLocalNetwork=ki;exports.isMacOS=MP;exports.isMobileDevice=xP;exports.isMozillaXR=kP;exports.isQuest=RP;exports.isResourceTrackingEnabled=kS;exports.isSafari=EP;exports.isTrackModel=mT;exports.isUsingInstancing=$f;exports.isiOS=OP;exports.isiPad=CP;exports.isolateChildrenDuring=Fg;exports.loadAsset=C1;exports.loadPMREM=Bh;exports.loadSync=db;exports.logHierarchy=$u;exports.lookAtInverse=JP;exports.lookAtObject=Ch;exports.lookAtScreenPoint=ek;exports.makeId=gP;exports.makeIdFromRandomWords=Dw;exports.makeNameSafe=Ri;exports.markAsInstancedRendered=LS;exports.maxGaussianSplatAdaptationLevel=hr;exports.microphonePermissionsGranted=TP;exports.nameof=fP;exports.nameofFactory=Tw;exports.needle=JM;exports.offBeforeXRSession=pS;exports.offXRSessionEnd=fS;exports.offXRSessionStart=t_;exports.on=eR;exports.onAfterRender=eM;exports.onBeforeRender=Jk;exports.onBeforeXRSession=ZO;exports.onClear=Kk;exports.onDestroy=Zk;exports.onInitialized=Uy;exports.onStart=If;exports.onSyncDestroy=mM;exports.onSyncInstantiate=Cx;exports.onUpdate=_x;exports.onXRSessionEnd=i_;exports.onXRSessionStart=jf;exports.originalComponentNameKey=ah;exports.parseSync=vp;exports.placeOnSurface=ex;exports.postprocessFBXMaterials=Dy;exports.prefix=QR;exports.pushState=Aw;exports.randomNumber=yP;exports.registerBinaryType=Xy;exports.registerComponent=zf;exports.registerComponentExtension=I_;exports.registerCustomEffectType=an;exports.registerExportExtensions=L_;exports.registerExtensions=mf;exports.registerHotReloadType=KS;exports.registerLoader=gx;exports.registerPrefabProvider=Mx;exports.registerPrototypeExtensions=a_;exports.registerType=Ly;exports.relativePathPrefix=Lw;exports.removeAttributeChangeCallback=Fw;exports.removeComponent=Wf;exports.removeCustomImportExtensionType=BA;exports.removePatch=Wk;exports.resolveGaussianSplatQuality=Ff;exports.resolveUrl=cs;exports.sanitizeString=Iw;exports.saveImage=K1;exports.screenshot=Z2;exports.screenshot2=Fb;exports.sendDestroyed=$y;exports.serializable=p;exports.serializeObject=Ax;exports.serializeable=Qe;exports.setActive=Pr;exports.setAllowBalloonMessages=zw;exports.setAllowOverlayMessages=FP;exports.setAutoFitEnabled=zu;exports.setCameraController=fg;exports.setDestroyed=FS;exports.setDevEnvironment=HP;exports.setDisposable=OS;exports.setDontDestroy=Ea;exports.setOrAddParamsToUrl=cg;exports.setParam=mP;exports.setParamWithoutReload=Yc;exports.setPeerOptions=HM;exports.setPhysicsEngineFactory=SS;exports.setResourceTrackingEnabled=_E;exports.setState=Sy;exports.setVisibleInCustomShadowRendering=Ay;exports.setWorldEuler=Ty;exports.setWorldPosition=Oi;exports.setWorldPositionXYZ=Ar;exports.setWorldQuaternion=vn;exports.setWorldQuaternionXYZW=Ey;exports.setWorldRotation=Qw;exports.setWorldRotationXYZ=Ph;exports.setWorldScale=rl;exports.showBalloonError=wl;exports.showBalloonMessage=Re;exports.showBalloonWarning=de;exports.showDebugConsole=Iy;exports.slerp=Gw;exports.syncDestroy=Mh;exports.syncField=b_;exports.syncInstantiate=Vy;exports.textureToCanvas=dk;exports.toSourceId=Bw;exports.tryCastBinary=Vx;exports.tryDetermineMimetypeFromBinary=PC;exports.tryDetermineMimetypeFromURL=CC;exports.tryFindObject=Kc;exports.tryGetExtensionFromUrl=SC;exports.tryGetGuid=Wx;exports.unregisterHotReloadType=ZS;exports.unregisterPrefabProvider=_M;exports.unwatchWrite=Cy;exports.useForAutoFit=Ww;exports.validate=je;exports.watchWrite=Mf;
|