@needle-tools/engine 4.13.1-beta → 4.13.1-next.9fc3e64
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 +6 -0
- package/components.needle.json +1 -1
- package/dist/gltf-progressive-CaUGGjVL.umd.cjs +10 -0
- package/dist/gltf-progressive-Dbi_Tfhb.js +1528 -0
- package/dist/gltf-progressive-DuAR0MQR.min.js +10 -0
- package/dist/{needle-engine.bundle-CGtsEhyJ.js → needle-engine.bundle-BZRE5G6O.js} +335 -312
- package/dist/{needle-engine.bundle-fbFZTOKP.umd.cjs → needle-engine.bundle-Dqrh7aWw.umd.cjs} +29 -29
- package/dist/{needle-engine.bundle-6774fXoY.min.js → needle-engine.bundle-DwybonUg.min.js} +47 -47
- package/dist/needle-engine.d.ts +446 -39
- package/dist/needle-engine.js +3 -3
- package/dist/needle-engine.min.js +1 -1
- package/dist/needle-engine.umd.cjs +1 -1
- package/lib/engine/engine_context.js +12 -2
- package/lib/engine/engine_context.js.map +1 -1
- package/lib/engine/engine_physics.d.ts +2 -0
- package/lib/engine/engine_physics.js +2 -0
- package/lib/engine/engine_physics.js.map +1 -1
- package/lib/engine/engine_physics_rapier.d.ts +2 -0
- package/lib/engine/engine_physics_rapier.js +2 -0
- package/lib/engine/engine_physics_rapier.js.map +1 -1
- package/lib/engine/engine_utils.d.ts +1 -0
- package/lib/engine/engine_utils.js +1 -0
- package/lib/engine/engine_utils.js.map +1 -1
- package/lib/engine/engine_utils_screenshot.d.ts +171 -14
- package/lib/engine/engine_utils_screenshot.js +65 -0
- package/lib/engine/engine_utils_screenshot.js.map +1 -1
- package/lib/engine/engine_utils_screenshot.xr.d.ts +1 -1
- package/lib/engine/engine_utils_screenshot.xr.js +1 -1
- package/lib/engine/extensions/NEEDLE_techniques_webgl.js +3 -0
- package/lib/engine/extensions/NEEDLE_techniques_webgl.js.map +1 -1
- package/lib/engine/xr/NeedleXRSession.d.ts +5 -0
- package/lib/engine/xr/NeedleXRSession.js +5 -0
- package/lib/engine/xr/NeedleXRSession.js.map +1 -1
- package/lib/engine-components/ContactShadows.d.ts +2 -0
- package/lib/engine-components/ContactShadows.js +2 -0
- package/lib/engine-components/ContactShadows.js.map +1 -1
- package/lib/engine-components/EventList.js +2 -2
- package/lib/engine-components/EventList.js.map +1 -1
- package/lib/engine-components/Renderer.d.ts +4 -3
- package/lib/engine-components/Renderer.js +4 -3
- package/lib/engine-components/Renderer.js.map +1 -1
- package/lib/engine-components/RigidBody.d.ts +57 -5
- package/lib/engine-components/RigidBody.js +57 -5
- package/lib/engine-components/RigidBody.js.map +1 -1
- package/lib/engine-components/ScreenCapture.d.ts +1 -0
- package/lib/engine-components/ScreenCapture.js +1 -0
- package/lib/engine-components/ScreenCapture.js.map +1 -1
- package/lib/engine-components/SeeThrough.d.ts +70 -5
- package/lib/engine-components/SeeThrough.js +70 -5
- package/lib/engine-components/SeeThrough.js.map +1 -1
- package/lib/engine-components/ShadowCatcher.d.ts +56 -4
- package/lib/engine-components/ShadowCatcher.js +56 -4
- package/lib/engine-components/ShadowCatcher.js.map +1 -1
- package/lib/engine-components/Skybox.d.ts +43 -7
- package/lib/engine-components/Skybox.js +43 -7
- package/lib/engine-components/Skybox.js.map +1 -1
- package/lib/engine-components/VideoPlayer.d.ts +1 -1
- package/lib/engine-components/VideoPlayer.js +7 -1
- package/lib/engine-components/VideoPlayer.js.map +1 -1
- package/lib/engine-components/timeline/PlayableDirector.d.ts +4 -0
- package/lib/engine-components/timeline/PlayableDirector.js +4 -0
- package/lib/engine-components/timeline/PlayableDirector.js.map +1 -1
- package/lib/engine-components/timeline/TimelineModels.d.ts +14 -0
- package/lib/engine-components/timeline/TimelineModels.js +4 -0
- package/lib/engine-components/timeline/TimelineModels.js.map +1 -1
- package/lib/engine-components/utils/OpenURL.d.ts +1 -0
- package/lib/engine-components/utils/OpenURL.js +1 -0
- package/lib/engine-components/utils/OpenURL.js.map +1 -1
- package/lib/engine-components/web/CursorFollow.d.ts +1 -0
- package/lib/engine-components/web/CursorFollow.js +1 -0
- package/lib/engine-components/web/CursorFollow.js.map +1 -1
- package/lib/engine-components/web/ScrollFollow.d.ts +1 -0
- package/lib/engine-components/web/ScrollFollow.js +1 -0
- package/lib/engine-components/web/ScrollFollow.js.map +1 -1
- package/lib/engine-components/webxr/WebARCameraBackground.d.ts +9 -0
- package/lib/engine-components/webxr/WebARCameraBackground.js +9 -0
- package/lib/engine-components/webxr/WebARCameraBackground.js.map +1 -1
- package/lib/engine-components/webxr/WebXR.d.ts +1 -0
- package/lib/engine-components/webxr/WebXR.js +1 -0
- package/lib/engine-components/webxr/WebXR.js.map +1 -1
- package/package.json +3 -3
- package/plugins/vite/build-pipeline.js +16 -2
- package/src/engine/engine_context.ts +17 -3
- package/src/engine/engine_physics.ts +4 -0
- package/src/engine/engine_physics_rapier.ts +8 -4
- package/src/engine/engine_utils.ts +1 -0
- package/src/engine/engine_utils_screenshot.ts +241 -17
- package/src/engine/engine_utils_screenshot.xr.ts +1 -1
- package/src/engine/extensions/NEEDLE_techniques_webgl.ts +3 -0
- package/src/engine/xr/NeedleXRSession.ts +5 -0
- package/src/engine-components/ContactShadows.ts +6 -1
- package/src/engine-components/EventList.ts +2 -2
- package/src/engine-components/Renderer.ts +14 -13
- package/src/engine-components/RigidBody.ts +64 -8
- package/src/engine-components/ScreenCapture.ts +1 -0
- package/src/engine-components/SeeThrough.ts +76 -9
- package/src/engine-components/ShadowCatcher.ts +61 -6
- package/src/engine-components/Skybox.ts +48 -12
- package/src/engine-components/VideoPlayer.ts +7 -1
- package/src/engine-components/timeline/PlayableDirector.ts +5 -1
- package/src/engine-components/timeline/SignalAsset.ts +1 -1
- package/src/engine-components/timeline/TimelineModels.ts +18 -2
- package/src/engine-components/utils/OpenURL.ts +1 -0
- package/src/engine-components/web/CursorFollow.ts +1 -0
- package/src/engine-components/web/ScrollFollow.ts +1 -0
- package/src/engine-components/webxr/WebARCameraBackground.ts +12 -3
- package/src/engine-components/webxr/WebXR.ts +1 -0
- package/dist/gltf-progressive-BURrJW0U.umd.cjs +0 -8
- package/dist/gltf-progressive-DHLDFNvQ.min.js +0 -8
- package/dist/gltf-progressive-eiJCrjLb.js +0 -1400
- package/src/include/three/DragControls.js +0 -232
package/dist/{needle-engine.bundle-fbFZTOKP.umd.cjs → needle-engine.bundle-Dqrh7aWw.umd.cjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";const c=require("./three-BW2s1Yl-.umd.cjs"),se=require("./gltf-progressive-
|
|
1
|
+
"use strict";const c=require("./three-BW2s1Yl-.umd.cjs"),se=require("./gltf-progressive-CaUGGjVL.umd.cjs"),q=require("./three-examples-Bpfu6ke_.umd.cjs"),re=require("./vendor-COVQl0b8.umd.cjs"),te=require("./three-mesh-ui-BU55xDxJ.umd.cjs"),Ox=require("./postprocessing-CI2TjWpu.umd.cjs");var ua=typeof document<"u"?document.currentScript:null;const df=new Map;function pi(s=globalThis.location?.hostname){if(df.has(s))return df.get(s);const e=/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|localhost/.test(s);return df.set(s,e),e===!0}function Bb(){return window.location.hostname.includes("glitch.me")}const Dy=typeof window!==void 0?window.location.search.includes("debugcontext"):!1;var ae=(s=>(s.ContextRegistered="ContextRegistered",s.ContextCreationStart="ContextCreationStart",s.ContextCreated="ContextCreated",s.ContextFirstFrameRendered="ContextFirstFrameRendered",s.ContextDestroying="ContextDestroying",s.ContextDestroyed="ContextDestroyed",s.MissingCamera="MissingCamera",s.ContextClearing="ContextClearing",s.ContextCleared="ContextCleared",s))(ae||{});class le{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&&(Dy&&console.warn("Registering context"),this.Registered.push(e),this.dispatchCallback("ContextRegistered",e))}static unregister(e){const t=this.Registered.indexOf(e);t!==-1&&(Dy&&console.warn("Unregistering context"),this.Registered.splice(t,1))}static _callbacks={};static registerCallback(e,t){this._callbacks[e]||(this._callbacks[e]=[]),this._callbacks[e].push(t)}static unregisterCallback(e,t){if(!this._callbacks[e])return;const i=this._callbacks[e].indexOf(t);i!==-1&&this._callbacks[e].splice(i,1)}static dispatchCallback(e,t,i){if(!this._callbacks[e])return!0;const n={event:e,context:t};if(i)for(const r in i)n[r]=i[r];const o=new Array;return this._callbacks[e].forEach(r=>{const a=r(n);a instanceof Promise&&o.push(a)}),Promise.all(o)}static addContextCreatedCallback(e){this.registerCallback("ContextCreated",e)}static addContextDestroyedCallback(e){this.registerCallback("ContextDestroyed",e)}}const Ub=()=>s=>s;function kx(s){return Ub()(s)}function Ex(){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 zo=!1;const vp=new Array;typeof window<"u"&&setTimeout(()=>{if(zo){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 vp){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=zo===!0?"":` (containing "${zo}")`;console.group("Available URL parameters:"+n);for(const o of Object.keys(s).sort())typeof zo=="string"&&!o.toLowerCase().includes(zo.toLowerCase())||(console.groupCollapsed(o),console.log("Reload with this flag enabled:"),console.log(s[o]),console.groupEnd());console.groupEnd()}},100);function Tc(){return new URLSearchParams(globalThis.location?.search)}function x(s){zo&&!vp.includes(s)&&vp.push(s);const e=Tc();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}zo=x("help");function Rx(s,e){const t=Tc();t.has(s)?t.set(s,e):t.append(s,e),document.location.search=t.toString()}function dc(s,e,t=!0){const i=Tc();i.has(s)?e===null?i.delete(s):i.set(s,e):e!==null&&i.append(s,e),t?Fb(s,i):ym(s,i)}function wp(s,e,t){s.has(e)?s.set(e,t.toString()):s.append(e,t.toString())}function Fb(s,e,t){window.history.pushState(t,s,"?"+e.toString())}function ym(s,e,t){window.history.replaceState(t,s,"?"+e.toString())}function Tx(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 Ax(s,e){return Math.floor(Math.random()*(e-s+1))+s}const Ly=["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"],Iy=["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 zb(){const s=Ly[Math.floor(Math.random()*Ly.length)],e=Iy[Math.floor(Math.random()*Iy.length)];return s+"_"+e}function Nb(s){return s=s.replace(/[^a-z0-9áéíóúñü \.,_-]/gim,""),s.trim()}function xa(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=xa(s,o,t,i);if(r)return r}if(e.children)for(const n in e.children){const o=e.children[n],r=xa(s,o,t,i);if(r)return r}}}function Ac(s,e){if(s!=null&&typeof s=="object"){let t;Array.isArray(s)?t=[]:(t=Object.create(s),Object.assign(t,s));for(const i of Object.keys(s)){const n=s[i];e&&!e(s,i,n)?t[i]=n:n?.clone!==void 0&&typeof n.clone=="function"?t[i]=n.clone():t[i]=Ac(n,e)}return t}return s}function fs(s){return new Promise((e,t)=>{setTimeout(e,s)})}function Dc(s,e){if(s<=0)return Promise.resolve();if(e||(e=le.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 Oh=x("debugresolveurl"),Vb="rel:";function Dx(s,e){return ho(s,e)}function ho(s,e){if(e===void 0)return Oh&&console.warn("getPath: uri is undefined, returning uri",e),e;if(e.startsWith("./"))return e;if(e.startsWith("http"))return Oh&&console.warn("getPath: uri is absolute, returning uri",e),e;if(s===void 0)return Oh&&console.warn("getPath: source is undefined, returning uri",e),e;e.startsWith(Vb)&&(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 Oh&&console.log("source:",s,`changed uri
|
|
4
4
|
from`,e,`
|
|
@@ -141,7 +141,7 @@ void main(){
|
|
|
141
141
|
#__vconsole .vc-mask {
|
|
142
142
|
overflow: hidden;
|
|
143
143
|
}
|
|
144
|
-
`,Ro?.prepend(i),s===!0&&Wb()<=0&&lv(),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.":"")),ml=!1,Yt=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.15.1/dist/vconsole.min.js",document.body.appendChild(e)}function US(){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"),Yt?.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 Op="padding: 10px; font-family: monospace;",Hy="margin-bottom: 10px;",To="margin-bottom: 10px; margin-top: 15px;",FS="width: 100%; border-collapse: collapse; border: 1px solid rgba(0,0,0,0.1); table-layout: fixed;",cv="border: 1px solid rgba(0,0,0,0.1); padding: 5px;",zS=cv,NS=cv+" word-break: break-all;";function Mn(s,e=!1){e&&s.sort((i,n)=>(n.value?1:0)-(i.value?1:0));let t=`<table style='${FS}'>`;t+="<tbody>";for(const i of s){const n=typeof i.value=="boolean"?i.value?"✅":"❌":i.value;t+=`<tr><td style='${zS}'>${i.label}</td><td style='${NS}'>${n}</td></tr>`}return t+="</tbody></table>",t}function hv(){try{if(document.createElement("canvas").getContext("webgl2"))return"✅"}catch{}return"❌"}function VS(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("device-utilities","📱 Device Info");return s.on("renderTab",function(e){let t=`<div style='${Op}'>`;const i=ZS();t+=`<h3 style='${Hy}'>Device: ${i}</h3>`,t+=Mn([{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+=Mn(n,!1)),t+="</div>",t+=`<div style='${Op} margin-top: 20px;'>`,t+=`<h3 style='${Hy}'>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:hv()}];t+=Mn(l,!1),t+="</div>",e(t)}),s}function $S(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("graphics-info","🎨 Graphics Info");return s.on("renderTab",async function(e){let t=`<div style='${Op}'>`;const i=WS();i.length>0&&(t+=`<h3 style='${To}'>General GPU Info</h3>`,t+=Mn(i,!1));const n=GS();n.length>0&&(t+=`<h3 style='${To}'>WebGL</h3>`,t+=Mn(n,!1));const o=qS();o.length>0&&(t+=`<h3 style='${To}'>WebGL 2 Features</h3>`,t+=Mn(o,!1));const r=XS();r.length>0&&(t+=`<h3 style='${To}'>WebGL Limits</h3>`,t+=Mn(r,!1));const a=QS();a.length>0&&(t+=`<h3 style='${To}'>Texture Formats</h3>`,t+=Mn(a,!1));const l=await YS();if(l.length>0&&(t+=`<h3 style='${To}'>WebGPU</h3>`,t+=Mn(l,!1)),exports.DeviceUtilities.isSafari()){const h=KS();h.length>0&&(t+=`<h3 style='${To}'>Safari GPU Info</h3>`,t+=Mn(h,!1))}t+="</div>",e(t)}),s}function WS(){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=dv();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=HS(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 HS(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 GS(){const s=[],e=dv();return e&&(s.push({label:"📊 WebGL Version",value:e.version}),s.push({label:"🎮 WebGL 2 Available",value:hv()})),s}function qS(){const s=[];try{const t=document.createElement("canvas").getContext("webgl2");if(!t)return s;s.push({label:"Float Color Buffer",value:t.getExtension("EXT_color_buffer_float")?"✅":"❌"}),s.push({label:"Anisotropic Filtering",value:t.getExtension("EXT_texture_filter_anisotropic")?"✅":"❌"}),s.push({label:"Float Texture Linear",value:t.getExtension("OES_texture_float_linear")?"✅":"❌"}),s.push({label:"S3TC Compression",value:t.getExtension("WEBGL_compressed_texture_s3tc")?"✅":"❌"}),s.push({label:"ETC Compression",value:t.getExtension("WEBGL_compressed_texture_etc")?"✅":"❌"}),s.push({label:"PVRTC Compression",value:t.getExtension("WEBGL_compressed_texture_pvrtc")?"✅":"❌"}),s.push({label:"ASTC Compression",value:t.getExtension("WEBGL_compressed_texture_astc")?"✅":"❌"})}catch{}return s}function XS(){const s=[];try{const e=document.createElement("canvas"),t=e.getContext("webgl2")||e.getContext("webgl");if(!t)return s;const i=t instanceof WebGL2RenderingContext;s.push({label:"📏 Max Texture Size",value:t.getParameter(t.MAX_TEXTURE_SIZE).toString()}),s.push({label:"🎨 Max Renderbuffer Size",value:t.getParameter(t.MAX_RENDERBUFFER_SIZE).toString()}),s.push({label:"🔗 Max Vertex Attribs",value:t.getParameter(t.MAX_VERTEX_ATTRIBS).toString()}),s.push({label:"🎯 Max Texture Units",value:t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS).toString()}),i&&(s.push({label:"⚡ Max Samples",value:t.getParameter(t.MAX_SAMPLES).toString()}),s.push({label:"🔄 Max Uniform Buffer Bindings",value:t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS).toString()}),s.push({label:"📐 Max 3D Texture Size",value:t.getParameter(t.MAX_3D_TEXTURE_SIZE).toString()}))}catch{}return s}function QS(){const s=[];try{document.createElement("canvas").getContext("webgl")&&(s.push({label:"WebGL 1 RGBA",value:"✅"}),s.push({label:"WebGL 1 RGB",value:"✅"}));const n=document.createElement("canvas").getContext("webgl2");n&&(s.push({label:"WebGL 2 RGBA32F",value:n.getExtension("EXT_color_buffer_float")?"✅":"❌"}),s.push({label:"WebGL 2 RGB32F",value:n.getExtension("EXT_color_buffer_float")?"✅":"❌"}),s.push({label:"WebGL 2 R11F_G11F_B10F",value:"✅"}),s.push({label:"WebGL 2 RGB565",value:"✅"}),s.push({label:"WebGL 2 RGB5_A1",value:"✅"}),s.push({label:"WebGL 2 RGBA4444",value:"✅"}))}catch{}return s}async function YS(){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 dv(){try{const s=document.createElement("canvas"),e=s.getContext("webgl2")||s.getContext("webgl");if(!e)return null;const t=e.getExtension("WEBGL_debug_renderer_info"),i=t?e.getParameter(t.UNMASKED_RENDERER_WEBGL):e.getParameter(e.RENDERER),n=t?e.getParameter(t.UNMASKED_VENDOR_WEBGL):e.getParameter(e.VENDOR),o=e.getParameter(e.VERSION);let r;if(i&&i.includes("ANGLE")){const a=i.match(/ANGLE \(([^)]+)\)/);a&&(r=a[1])}return{renderer:i,vendor:n,version:o,angle:r}}catch{return null}}function KS(){const s=[];try{const t=document.createElement("canvas").getContext("webgl");if(t){const i=t.getExtension("WEBGL_debug_renderer_info");if(i){const n=t.getParameter(i.UNMASKED_RENDERER_WEBGL);n&&n.includes("Apple")&&s.push({label:"🍎 Apple GPU",value:n})}}}catch{}try{const t=document.createElement("canvas").getContext("webgl");t&&(t.getSupportedExtensions()||[]).includes("WEBGL_compressed_texture_pvrtc")&&s.push({label:"🗜️ PVRTC Support",value:"✅"})}catch{}return s}function ZS(){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 JS(){const s=document.querySelector("#__vconsole .vc-switch");return s||null}function eC(){const s=document.querySelector("#__vconsole");return s||null}const uv=x("debugdefines");uo('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";');uo('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";');uo('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";');uo('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";');uo('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.13.1-beta";');uo('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');uo('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Thu Feb 12 2026 16:37:41 GMT+0000 (Coordinated Universal Time)";');uo('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const fi="4.13.1-beta",Ca="undefined",uc="Thu Feb 12 2026 16:37:41 GMT+0000 (Coordinated Universal Time)";uv&&console.log(`Engine version: ${fi} (generator: ${Ca})
|
|
144
|
+
`,Ro?.prepend(i),s===!0&&Wb()<=0&&lv(),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.":"")),ml=!1,Yt=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.15.1/dist/vconsole.min.js",document.body.appendChild(e)}function US(){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"),Yt?.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 Op="padding: 10px; font-family: monospace;",Hy="margin-bottom: 10px;",To="margin-bottom: 10px; margin-top: 15px;",FS="width: 100%; border-collapse: collapse; border: 1px solid rgba(0,0,0,0.1); table-layout: fixed;",cv="border: 1px solid rgba(0,0,0,0.1); padding: 5px;",zS=cv,NS=cv+" word-break: break-all;";function Mn(s,e=!1){e&&s.sort((i,n)=>(n.value?1:0)-(i.value?1:0));let t=`<table style='${FS}'>`;t+="<tbody>";for(const i of s){const n=typeof i.value=="boolean"?i.value?"✅":"❌":i.value;t+=`<tr><td style='${zS}'>${i.label}</td><td style='${NS}'>${n}</td></tr>`}return t+="</tbody></table>",t}function hv(){try{if(document.createElement("canvas").getContext("webgl2"))return"✅"}catch{}return"❌"}function VS(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("device-utilities","📱 Device Info");return s.on("renderTab",function(e){let t=`<div style='${Op}'>`;const i=ZS();t+=`<h3 style='${Hy}'>Device: ${i}</h3>`,t+=Mn([{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+=Mn(n,!1)),t+="</div>",t+=`<div style='${Op} margin-top: 20px;'>`,t+=`<h3 style='${Hy}'>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:hv()}];t+=Mn(l,!1),t+="</div>",e(t)}),s}function $S(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("graphics-info","🎨 Graphics Info");return s.on("renderTab",async function(e){let t=`<div style='${Op}'>`;const i=WS();i.length>0&&(t+=`<h3 style='${To}'>General GPU Info</h3>`,t+=Mn(i,!1));const n=GS();n.length>0&&(t+=`<h3 style='${To}'>WebGL</h3>`,t+=Mn(n,!1));const o=qS();o.length>0&&(t+=`<h3 style='${To}'>WebGL 2 Features</h3>`,t+=Mn(o,!1));const r=XS();r.length>0&&(t+=`<h3 style='${To}'>WebGL Limits</h3>`,t+=Mn(r,!1));const a=QS();a.length>0&&(t+=`<h3 style='${To}'>Texture Formats</h3>`,t+=Mn(a,!1));const l=await YS();if(l.length>0&&(t+=`<h3 style='${To}'>WebGPU</h3>`,t+=Mn(l,!1)),exports.DeviceUtilities.isSafari()){const h=KS();h.length>0&&(t+=`<h3 style='${To}'>Safari GPU Info</h3>`,t+=Mn(h,!1))}t+="</div>",e(t)}),s}function WS(){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=dv();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=HS(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 HS(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 GS(){const s=[],e=dv();return e&&(s.push({label:"📊 WebGL Version",value:e.version}),s.push({label:"🎮 WebGL 2 Available",value:hv()})),s}function qS(){const s=[];try{const t=document.createElement("canvas").getContext("webgl2");if(!t)return s;s.push({label:"Float Color Buffer",value:t.getExtension("EXT_color_buffer_float")?"✅":"❌"}),s.push({label:"Anisotropic Filtering",value:t.getExtension("EXT_texture_filter_anisotropic")?"✅":"❌"}),s.push({label:"Float Texture Linear",value:t.getExtension("OES_texture_float_linear")?"✅":"❌"}),s.push({label:"S3TC Compression",value:t.getExtension("WEBGL_compressed_texture_s3tc")?"✅":"❌"}),s.push({label:"ETC Compression",value:t.getExtension("WEBGL_compressed_texture_etc")?"✅":"❌"}),s.push({label:"PVRTC Compression",value:t.getExtension("WEBGL_compressed_texture_pvrtc")?"✅":"❌"}),s.push({label:"ASTC Compression",value:t.getExtension("WEBGL_compressed_texture_astc")?"✅":"❌"})}catch{}return s}function XS(){const s=[];try{const e=document.createElement("canvas"),t=e.getContext("webgl2")||e.getContext("webgl");if(!t)return s;const i=t instanceof WebGL2RenderingContext;s.push({label:"📏 Max Texture Size",value:t.getParameter(t.MAX_TEXTURE_SIZE).toString()}),s.push({label:"🎨 Max Renderbuffer Size",value:t.getParameter(t.MAX_RENDERBUFFER_SIZE).toString()}),s.push({label:"🔗 Max Vertex Attribs",value:t.getParameter(t.MAX_VERTEX_ATTRIBS).toString()}),s.push({label:"🎯 Max Texture Units",value:t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS).toString()}),i&&(s.push({label:"⚡ Max Samples",value:t.getParameter(t.MAX_SAMPLES).toString()}),s.push({label:"🔄 Max Uniform Buffer Bindings",value:t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS).toString()}),s.push({label:"📐 Max 3D Texture Size",value:t.getParameter(t.MAX_3D_TEXTURE_SIZE).toString()}))}catch{}return s}function QS(){const s=[];try{document.createElement("canvas").getContext("webgl")&&(s.push({label:"WebGL 1 RGBA",value:"✅"}),s.push({label:"WebGL 1 RGB",value:"✅"}));const n=document.createElement("canvas").getContext("webgl2");n&&(s.push({label:"WebGL 2 RGBA32F",value:n.getExtension("EXT_color_buffer_float")?"✅":"❌"}),s.push({label:"WebGL 2 RGB32F",value:n.getExtension("EXT_color_buffer_float")?"✅":"❌"}),s.push({label:"WebGL 2 R11F_G11F_B10F",value:"✅"}),s.push({label:"WebGL 2 RGB565",value:"✅"}),s.push({label:"WebGL 2 RGB5_A1",value:"✅"}),s.push({label:"WebGL 2 RGBA4444",value:"✅"}))}catch{}return s}async function YS(){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 dv(){try{const s=document.createElement("canvas"),e=s.getContext("webgl2")||s.getContext("webgl");if(!e)return null;const t=e.getExtension("WEBGL_debug_renderer_info"),i=t?e.getParameter(t.UNMASKED_RENDERER_WEBGL):e.getParameter(e.RENDERER),n=t?e.getParameter(t.UNMASKED_VENDOR_WEBGL):e.getParameter(e.VENDOR),o=e.getParameter(e.VERSION);let r;if(i&&i.includes("ANGLE")){const a=i.match(/ANGLE \(([^)]+)\)/);a&&(r=a[1])}return{renderer:i,vendor:n,version:o,angle:r}}catch{return null}}function KS(){const s=[];try{const t=document.createElement("canvas").getContext("webgl");if(t){const i=t.getExtension("WEBGL_debug_renderer_info");if(i){const n=t.getParameter(i.UNMASKED_RENDERER_WEBGL);n&&n.includes("Apple")&&s.push({label:"🍎 Apple GPU",value:n})}}}catch{}try{const t=document.createElement("canvas").getContext("webgl");t&&(t.getSupportedExtensions()||[]).includes("WEBGL_compressed_texture_pvrtc")&&s.push({label:"🗜️ PVRTC Support",value:"✅"})}catch{}return s}function ZS(){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 JS(){const s=document.querySelector("#__vconsole .vc-switch");return s||null}function eC(){const s=document.querySelector("#__vconsole");return s||null}const uv=x("debugdefines");uo('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";');uo('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";');uo('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";');uo('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";');uo('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.13.1";');uo('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');uo('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Mon Feb 16 2026 14:46:26 GMT+0000 (Coordinated Universal Time)";');uo('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const fi="4.13.1",Ca="undefined",uc="Mon Feb 16 2026 14:46:26 GMT+0000 (Coordinated Universal Time)";uv&&console.log(`Engine version: ${fi} (generator: ${Ca})
|
|
145
145
|
Project built at ${uc}`);const Ks=NEEDLE_PUBLIC_KEY,ds="needle_isActiveInHierarchy",No="builtin_components",Ql="needle_editor_guid";function uo(s){try{(0,eval)(s)}catch(e){uv&&console.error(e)}}let fv,Gy=null;function cn(){return fv}function Tm(s){if(s==null){console.warn("Oh no: someone tried registering a non-existend gltf-loader. When you see this log it might mean that needle-engine is being imported multiple times. Please check your project setup.");return}Gy!==s&&(Gy=s,fv=new s)}function tC(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 T()&&console.debug("Spector available: Add '?spector=<frame>' to the URL to enable it and capture a frame.")}}const hi=Symbol("shadowDomOwner"),iC=x("debugpatch");function nu(s,e,t,i){const n=iC===e;if(!t&&!i)return;const o=e+"___needle";sC(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]=Xy(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]=Xy(l,s,e);else{const h=this[o];pv(s,e,this,h,l),this[o]=l,mv(s,e,this,h,l)}},get:function(){const l=this[o];return typeof l=="function"&&l[o]?l[o]:l}}))}function nC(s,e,t){const i=Am(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 qy=Symbol("Needle:Patches:WrappedFunction");function Xy(s,e,t){if(s[qy])return s;const i=function(...n){pv(e,t,this,...n);const o=s.apply(this,n);return mv(e,t,this,o,...n),o};return i[qy]=!0,i}const ld="Needle:Patches";function kp(){return globalThis[ld]||(globalThis[ld]=new WeakMap),globalThis[ld]}function Am(s,e){const t=kp().get(s);return t?t.get(e):null}function sC(s,e,t,i){let n=kp().get(s);n||(n=new Map,kp().set(s,n));let o=n.get(e);o||(o=[],n.set(e,o)),o.push({prefix:t,postfix:i})}function pv(s,e,t,...i){if(!t)return;const n=Am(s,e);if(n)for(const o of n)o.prefix?.call(t,...i)}function mv(s,e,t,i,...n){if(!t)return;const o=Am(s,e);if(o)for(const r of o)r.postfix?.call(t,i,...n)}const Pa=[];function su(s){Pa.indexOf(s)===-1&&Pa.push(s)}function oC(s){const e=Pa.indexOf(s);e!==-1&&Pa.splice(e,1)}const Ma=[];function Dm(s){Ma.indexOf(s)===-1&&Ma.push(s)}function rC(s){const e=Ma.indexOf(s);e!==-1&&Ma.splice(e,1)}function gv(s){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-start",{detail:s}));for(let e=0;e<Pa.length;e++)Pa[e](s)}function yv(s){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-end",{detail:s}));for(let e=0;e<Ma.length;e++)Ma[e](s)}const Be=x("debuginput");var ou=(s=>(s.Mouse="mouse",s.Touch="touch",s.Controller="controller",s.Hand="hand",s))(ou||{}),Ce=(s=>(s.PointerDown="pointerdown",s.PointerUp="pointerup",s.PointerMove="pointermove",s.KeyDown="keydown",s.KeyUp="keyup",s.KeyPressed="keypress",s))(Ce||{});class ts extends PointerEvent{clientZ;deviceIndex;origin;source;mode;get isSpatial(){return this.mode!="screen"}get ray(){return this._ray||(this._ray=new c.Ray(this.space.worldPosition.clone(),this.space.worldForward.clone())),this._ray}set ray(e){this._ray=e}get hasRay(){return this._ray!==void 0}_ray;space;isClick=!1;isDoubleClick=!1;get used(){return this._used}_used=!1;use(){this._used=!0}get pointerId(){return this._pointerid}_pointerid;get pointerType(){return this._pointerType}_pointerType;buttonName=void 0;get type(){return this._type}_type;metadata={};intersections=new Array;constructor(e,t,i){super(e,i),this.clientZ=i.clientZ,this._pointerid=i.pointerId,this._pointerType=i.pointerType,this._type=e,this.deviceIndex=i.deviceIndex,this.origin=i.origin,this.source=t,this.mode=i.mode,this._ray=i.ray,this.space=i.device,this.buttonName=i.buttonName}_immediatePropagationStopped=!1;get immediatePropagationStopped(){return this._immediatePropagationStopped}_propagationStopped=!1;get propagationStopped(){return this._immediatePropagationStopped||this._propagationStopped}stopImmediatePropagation(){this._immediatePropagationStopped=!0,super.stopImmediatePropagation(),this.source?.stopImmediatePropagation()}stopPropagation(){this._propagationStopped=!0,super.stopPropagation(),this.source?.stopPropagation(),Be&&console.warn("Stop propagation...",this.pointerId,this.pointerType)}}class Al extends KeyboardEvent{source;constructor(e,t,i){super(e,i),this.source=t}stopImmediatePropagation(){super.stopImmediatePropagation(),this.source?.stopImmediatePropagation()}}class aC{key;keyType;source;constructor(e){this.key=e.key,this.keyType=e.type,this.source=e}}var Jt=(s=>(s[s.Early=-100]="Early",s[s.Default=0]="Default",s[s.Late=100]="Late",s))(Jt||{});class _v{_eventListeners={};addEventListener(e,t,i){if(this._eventListeners[e]||(this._eventListeners[e]=[]),!t||typeof t!="function"){console.error("Invalid call to addEventListener: callback is required and must be a function!");return}i?i={...i}:i={};let n=0;i?.queue!=null&&(n=i.queue);const o=this._eventListeners[e],r=o.find(a=>a.priority===n);r?r.listeners.push({callback:t,options:i}):(o.push({priority:n,listeners:[{callback:t,options:i}]}),o.sort((a,l)=>a.priority-l.priority))}removeEventListener(e,t,i){if(!this._eventListeners[e]||!t)return;const n=this._eventListeners[e];if(i?.queue!=null){const o=n.find(a=>a.priority===i.queue);if(!o)return;const r=o.listeners.findIndex(a=>a.callback===t);r>=0&&o.listeners.splice(r,1)}else for(const o of n){const r=o.listeners.findIndex(a=>a.callback===t);r>=0&&o.listeners.splice(r,1)}}dispatchEvent(e){let t=!1;if(e instanceof Al){const i=this._eventListeners[e.type];if(i)for(const n of i)for(let o=0;o<n.listeners.length;o++){const r=n.listeners[o];if(r.options?.signal?.aborted){n.listeners.splice(o,1),o--;continue}r.options.once&&(n.listeners.splice(o,1),o--),r.callback(e)}}if(e instanceof ts){const i=this._eventListeners[e.type];if(i)for(const n of i){if(t)break;for(let o=0;o<n.listeners.length;o++){const r=n.listeners[o];if(r.options?.signal?.aborted){n.listeners.splice(o,1),o--;continue}if(e.immediatePropagationStopped){t=!0,Be&&console.log("immediatePropagationStopped",e.type);break}else e.propagationStopped&&(t=!0,Be&&console.log("propagationStopped",e.type));r.options.once&&(n.listeners.splice(o,1),o--),r.callback(e)}}}}_doubleClickTimeThreshold=.2;_longPressTimeThreshold=1;get mousePosition(){return this._pointerPositions[0]}get mousePositionRC(){return this._pointerPositionsRC[0]}get mouseDown(){return this._pointerDown[0]}get mouseUp(){return this._pointerUp[0]}get mouseClick(){return this._pointerClick[0]}get mouseDoubleClick(){return this._pointerDoubleClick[0]}get mousePressed(){return this._pointerPressed[0]}get mouseWheelChanged(){return this.getMouseWheelChanged(0)}get click(){return this._pointerClick[0]}get doubleClick(){return this._pointerDoubleClick[0]}getGamepad(e=0){return typeof navigator<"u"&&"getGamepads"in navigator&&navigator.getGamepads()[e]||null}_setCursorTypes=[];setCursorPointer(){this.setCursor("pointer")}setCursorNormal(){this.unsetCursor("pointer")}setCursor(e){this._setCursorTypes.push(e),this._setCursorTypes.length>10&&this._setCursorTypes.shift(),this.updateCursor()}unsetCursor(e){for(let t=this._setCursorTypes.length-1;t>=0;t--)if(this._setCursorTypes[t]===e){this._setCursorTypes.splice(t,1),this.updateCursor();break}}updateCursor(){this._setCursorTypes?.length==0?this.context.domElement.style.cursor="default":this.context.domElement.style.cursor=this._setCursorTypes[this._setCursorTypes.length-1]}getIsPointerIdInUse(e){for(const t of this._pointerEventsPressed)if(t.pointerId===e&&t.used)return!0;return!1}getPointerPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&e++;return e}getPointerPosition(e){return e>=this._pointerPositions.length?null:this._pointerPositions[e]}getPointerPositionLastFrame(e){return e>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[e]}getPointerPositionDelta(e){return e>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[e]}getPointerPositionRC(e){return e>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[e]}getPointerDown(e){return e>=this._pointerDown.length?!1:this._pointerDown[e]}getPointerUp(e){return e>=this._pointerUp.length?!1:this._pointerUp[e]}getPointerPressed(e){return e>=this._pointerPressed.length?!1:this._pointerPressed[e]}getPointerClicked(e){return e>=this._pointerClick.length?!1:this._pointerClick[e]}getPointerDoubleClicked(e){return e>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[e]}getPointerDownTime(e){return e>=this._pointerDownTime.length?-1:this._pointerDownTime[e]}getPointerUpTime(e){return e>=this._pointerUpTime.length?-1:this._pointerUpTime[e]}getPointerLongPress(e){return e>=this._pointerDownTime.length?!1:this.getPointerPressed(e)&&this.context.time.time-this._pointerDownTime[e]>this._longPressTimeThreshold}getIsMouse(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="mouse"}getIsTouch(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="touch"}getTouchesPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&this.getIsTouch(t)&&e++;return e}getMouseWheelChanged(e=0){return e>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[e]}getMouseWheelDeltaY(e=0){return e>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[e]}getPointerEvent(e){if(!(e>=this._pointerEvent.length))return this._pointerEvent[e]??void 0}*foreachPointerId(e){for(let t=0;t<this._pointerTypes.length;t++)if(this._pointerIsActive(t)){if(e!==void 0){const i=this._pointerTypes[t];if(Array.isArray(e)){let n=!1;for(const o of e)if(i===o){n=!0;break}if(!n)continue}else if(e!==i)continue}yield t}}*foreachTouchId(){for(let e=0;e<this._pointerTypes.length;e++)this._pointerTypes[e]==="touch"&&this._pointerIsActive[e]&&(yield e)}_pointerIsActive(e){return e<0?!1:this._pointerPressed[e]||this._pointerDown[e]||this._pointerUp[e]}context;_pointerDown=[!1];_pointerUp=[!1];_pointerClick=[!1];_pointerDoubleClick=[!1];_pointerPressed=[!1];_pointerPositions=[new c.Vector2];_pointerPositionsLastFrame=[new c.Vector2];_pointerPositionsDelta=[new c.Vector2];_pointerPositionsRC=[new c.Vector2];_pointerPositionDown=[new c.Vector3];_pointerDownTime=[];_pointerUpTime=[];_pointerUpTimestamp=[];_pointerIds=[];_pointerTypes=[""];_mouseWheelChanged=[!1];_mouseWheelDeltaY=[0];_pointerEvent=[];_pointerEventsPressed=[];_pointerSpace=[];_pressedStack=new Map;onDownButton(e,t){let i=this._pressedStack.get(e);i||(i=[],this._pressedStack.set(e,i)),i.push(t)}onReleaseButton(e,t){const i=this._pressedStack.get(e);if(!i)return;const n=i.indexOf(t);n>=0&&i.splice(n,1)}getFirstPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[0]}getLatestPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[t.length-1]}getKeyDown(e){if(e!==void 0)return this.isKeyDown(e);for(const t in this.keysPressed){const i=this.keysPressed[t];if(i.startFrame===this.context.time.frameCount)return i.key}return null}getKeyPressed(e){if(e!==void 0)return this.isKeyPressed(e);for(const t in this.keysPressed){const i=this.keysPressed[t];if(i.pressed)return i.key}return null}getKeyUp(e){if(e!==void 0)return this.isKeyUp(e);for(const t in this.keysPressed){const i=this.keysPressed[t];return i.pressed===!1&&i.frame===this.context.time.frameCount}return null}isKeyDown(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const n of t)if(this.isKeyDown(n))return!0;return!1}const i=this.keysPressed[e];return i?i.startFrame===this.context.time.frameCount&&i.pressed:!1}isKeyUp(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const n of t)if(this.isKeyUp(n))return!0;return!1}const i=this.keysPressed[e];return i?i.frame===this.context.time.frameCount&&i.pressed===!1:!1}isKeyPressed(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const n of t)if(this.isKeyPressed(n))return!0;return!1}const i=this.keysPressed[e];return i&&i.pressed||!1}getCodeForCommonKeyName(e){if(e.length===1){if(e>="0"&&e<="9")return["Digit"+e];if(e>="a"&&e<="z")return["Key"+e.toUpperCase()];if(e==" ")return["Space"]}switch(e){case"shift":case"Shift":return["ShiftLeft","ShiftRight"];case"control":case"Control":return["ControlLeft","ControlRight"];case"alt":case"Alt":return["AltLeft","AltRight"]}return null}createInputEvent(e){switch(e.type){case"pointerdown":Be&&we("Create Pointer down"),this.onDownButton(e.deviceIndex,e.button),this.onDown(e);break;case"pointermove":Be&&we("Create Pointer move"),this.onMove(e);break;case"pointerup":Be&&we("Create Pointer up"),this.onUp(e),this.onReleaseButton(e.deviceIndex,e.button);break}}convertScreenspaceToRaycastSpace(e){return e.x=(e.x-this.context.domX)/this.context.domWidth*2-1,e.y=-((e.y-this.context.domY)/this.context.domHeight)*2+1,e}constructor(e){this.context=e,this.context.post_render_callbacks.push(this.onEndOfFrame)}_htmlEventSource;bindEvents(){this.unbindEvents(),this._htmlEventSource=this.context.renderer.domElement,window.addEventListener("contextmenu",this.onContextMenu),this._htmlEventSource.addEventListener("pointerdown",this.onPointerDown,{passive:!0}),window.addEventListener("pointermove",this.onPointerMove,{passive:!0,capture:!0}),window.addEventListener("pointerup",this.onPointerUp,{passive:!0}),window.addEventListener("pointercancel",this.onPointerCancel,{passive:!0}),window.addEventListener("touchstart",this.onTouchStart,{passive:!0}),window.addEventListener("touchmove",this.onTouchMove,{passive:!0}),window.addEventListener("touchend",this.onTouchEnd,{passive:!0}),this._htmlEventSource.addEventListener("wheel",this.onMouseWheel,{passive:!0}),window.addEventListener("wheel",this.onWheelWindow,{passive:!0}),window.addEventListener("keydown",this.onKeyDown,!1),window.addEventListener("keypress",this.onKeyPressed,!1),window.addEventListener("keyup",this.onKeyUp,!1),window.addEventListener("blur",this.onLostFocus)}unbindEvents(){for(const e in this._eventListeners)this._eventListeners[e].length=0;window.removeEventListener("contextmenu",this.onContextMenu),this._htmlEventSource?.removeEventListener("pointerdown",this.onPointerDown),window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("pointercancel",this.onPointerCancel),window.removeEventListener("touchstart",this.onTouchStart),window.removeEventListener("touchmove",this.onTouchMove),window.removeEventListener("touchend",this.onTouchEnd),this._htmlEventSource?.removeEventListener("wheel",this.onMouseWheel,!1),window.removeEventListener("wheel",this.onWheelWindow,!1),window.removeEventListener("keydown",this.onKeyDown,!1),window.removeEventListener("keypress",this.onKeyPressed,!1),window.removeEventListener("keyup",this.onKeyUp,!1),window.removeEventListener("blur",this.onLostFocus)}dispose(){const e=this.context.post_render_callbacks.indexOf(this.onEndOfFrame);e>=0&&this.context.post_render_callbacks.splice(e,1),this.unbindEvents()}onLostFocus=()=>{for(const e in this.keysPressed)this.keysPressed[e].pressed=!1};_receivedPointerMoveEventsThisFrame=new Array;onEndOfFrame=()=>{this._receivedPointerMoveEventsThisFrame.length=0;for(let e=0;e<this._pointerUp.length;e++)this._pointerUp[e]=!1;for(let e=0;e<this._pointerDown.length;e++)this._pointerDown[e]=!1;for(let e=0;e<this._pointerClick.length;e++)this._pointerClick[e]=!1;for(let e=0;e<this._pointerDoubleClick.length;e++)this._pointerDoubleClick[e]=!1;for(const e of this._pointerPositionsDelta)e.set(0,0);for(let e=0;e<this._mouseWheelChanged.length;e++)this._mouseWheelChanged[e]=!1;for(let e=0;e<this._mouseWheelDeltaY.length;e++)this._mouseWheelDeltaY[e]=0};canReceiveInput(e){return e.target===this.context.renderer?.domElement||e.target===this.context.domElement||this.context.isInAR||this.context.isInAR&&e.target===document.body&&exports.DeviceUtilities.isMozillaXR()?!0:(Be&&console.warn("CanReceiveInput:False for",e.target),!1)}onContextMenu=e=>{this.canReceiveInput(e)};keysPressed={};onKeyDown=e=>{if(Be&&console.log(`key down ${e.code}, ${this.context.application.hasFocus}`,e),!this.context.application.hasFocus)return;const t=this.keysPressed[e.code];if(t&&t.pressed)return;this.keysPressed[e.code]={pressed:!0,frame:this.context.time.frameCount+1,startFrame:this.context.time.frameCount+1,key:e.key,code:e.code};const i=new Al("keydown",e,e);this.onDispatchEvent(i)};onKeyPressed=e=>{if(!this.context.application.hasFocus)return;const t=this.keysPressed[e.code];if(!t)return;t.pressed=!0,t.frame=this.context.time.frameCount+1;const i=new Al("keypress",e,e);this.onDispatchEvent(i)};onKeyUp=e=>{if(!this.context.application.hasFocus)return;const t=this.keysPressed[e.code];if(!t)return;t.pressed=!1,t.frame=this.context.time.frameCount+1;const i=new Al("keyup",e,e);this.onDispatchEvent(i)};onWheelWindow=e=>{document.pointerLockElement&&this.onMouseWheel(e)};onMouseWheel=e=>{if(this.canReceiveInput(e)===!1)return;this._mouseWheelDeltaY.length<=0&&this._mouseWheelDeltaY.push(0),this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0;const t=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=t+e.deltaY};onPointerDown=e=>{if(this.context.isInAR||this.canReceiveInput(e)===!1)return;e.target instanceof HTMLElement&&e.target.setPointerCapture(e.pointerId);const t=this.getPointerId(e);Be&&we(`pointer down #${t}, identifier:${e.pointerId}`);const i=this.getAndUpdateSpatialObjectForScreenPosition(t,e.clientX,e.clientY),n=new ts("pointerdown",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:t,button:e.button,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,buttonName:this.getButtonName(e),device:i,pressure:e.pressure});this.onDown(n)};onPointerMove=e=>{if(this.context.isInAR||this._receivedPointerMoveEventsThisFrame.includes(e.pointerId))return;this._receivedPointerMoveEventsThisFrame.push(e.pointerId);let t=e.button;e.pointerType==="mouse"&&(t=this.getFirstPressedButtonForPointer(0)??0);const i=this.getPointerId(e,t);t===-1&&(t=i);const n=this.getAndUpdateSpatialObjectForScreenPosition(i,e.clientX,e.clientY),o=new ts("pointermove",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:i,button:t,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,buttonName:this.getButtonName(e),device:n,pressure:e.pressure});this.onMove(o)};onPointerCancel=e=>{this.context.isInAR||(Be&&console.log("Pointer cancel",e),this.onPointerUp(e))};onPointerUp=e=>{if(this.context.isInAR)return;e.target instanceof HTMLElement&&e.target.releasePointerCapture(e.pointerId);const t=this.getPointerId(e),i=new ts("pointerup",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:t,button:e.button,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,buttonName:this.getButtonName(e),device:this.getAndUpdateSpatialObjectForScreenPosition(t,e.clientX,e.clientY),pressure:e.pressure});this.onUp(i),this._pointerIds[t]=-1,Be&&console.log("ID="+t,"PointerId="+e.pointerId,"ALL:",[...this._pointerIds])};getPointerId(e,t){return e.pointerType==="mouse"?0+(t??e.button):this.getPointerIndex(e.pointerId)}getButtonName(e){const t=e.button;if(e.pointerType==="mouse")switch(t){case 0:return"left";case 1:return"middle";case 2:return"right"}return"unknown"}onTouchStart=e=>{if(this.context.isInAR)for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t],n=this.getPointerIndex(i.identifier),o=this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),r=new ts("pointerdown",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:o,pressure:i.force});this.onDown(r)}};onTouchMove=e=>{if(this.context.isInAR)for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t],n=this.getPointerIndex(i.identifier),o=this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),r=new ts("pointermove",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:o,pressure:i.force});this.onMove(r)}};onTouchEnd=e=>{if(this.context.isInAR)for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t],n=this.getPointerIndex(i.identifier),o=new ts("pointerup",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),pressure:i.force});this.onUp(o),this._pointerIds[n]=-1}};tempNearPlaneVector=new c.Vector3;tempFarPlaneVector=new c.Vector3;tempLookMatrix=new c.Matrix4;getAndUpdateSpatialObjectForScreenPosition(e,t,i){let n=this._pointerSpace[e];n||(n=new c.Object3D,this._pointerSpace[e]=n),this._pointerSpace[e]=n;const o=this.context.mainCamera;if(o){const r=this.tempNearPlaneVector.set(t,i,-1);this.convertScreenspaceToRaycastSpace(r);const a=this.tempFarPlaneVector.set(r.x,r.y,1);r.unproject(o),a.unproject(o);const l=o.worldUp||B(0,1,0).applyQuaternion(fe(o));this.tempLookMatrix.lookAt(a,r,l),n.position.set(r.x,r.y,r.z),n.quaternion.setFromRotationMatrix(this.tempLookMatrix)}return n}isInRect(e){if(this.context.isInXR)return!0;const t=this.context.domElement.getBoundingClientRect(),i=e.clientX,n=e.clientY,o=i>=t.x&&i<=t.right&&n>=t.y&&n<=t.bottom;return Be&&!o&&console.log("Not in rect",t,i,n),o}onDown(e){const t=e.pointerId;if(this.getPointerPressed(t)){Be&&console.warn(`Received pointerDown event for pointerId that is already pressed: ${t}/${e.button}`,Be?e:"");return}if(Be&&console.log(e.pointerType,"DOWN",t,e.button),!!this.isInRect(e)){for(this.setPointerState(t,this._pointerPressed,!0),this.setPointerState(t,this._pointerDown,!0),this.setPointerStateT(t,this._pointerEvent,e.source);t>=this._pointerTypes.length;)this._pointerTypes.push(e.pointerType);for(this._pointerTypes[t]=e.pointerType;t>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new c.Vector3);for(this._pointerPositionDown[t].set(e.clientX,e.clientY,e.clientZ??0);t>=this._pointerPositions.length;)this._pointerPositions.push(new c.Vector2);this._pointerPositions[t].set(e.clientX,e.clientY),t>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[t]=this.context.time.realtimeSinceStartup,this.updatePointerPosition(e),this._pointerEventsPressed.push(e),this.onDispatchEvent(e)}}onMove(e){const t=e.pointerId,i=this.getPointerPressed(t);i===!1&&!this.isInRect(e)||e.pointerType==="touch"&&!i||(this.updatePointerPosition(e),this.setPointerStateT(t,this._pointerEvent,e.source),this.onDispatchEvent(e))}onUp(e){const t=e.pointerId;if(!this.getPointerPressed(t)){Be&&console.warn(`Received pointerUp for pointerId that is not pressed: ${t}/${e.button}`,Be?e:"");return}Be&&console.log(e.pointerType,"UP",t),this.setPointerState(t,this._pointerPressed,!1),this.setPointerStateT(t,this._pointerEvent,e.source),this.setPointerState(t,this._pointerUp,!0),this.updatePointerPosition(e);for(let l=this._pointerEventsPressed.length-1;l>=0;l--)if(this._pointerEventsPressed[l].pointerId===t){this._pointerEventsPressed.splice(l,1);break}if(!this._pointerPositionDown[t]){Be&&ue("[Received pointer up event without matching down event for button: "+t),console.warn("Received pointer up event without matching down event for button: "+t);return}const n=this._pointerUpTime[t],o=this._pointerDownTime[t],r=this.context.time.realtimeSinceStartup,a=r-o;if(t>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),this._pointerUpTime[t]=r,a<1){let l=e.clientX-this._pointerPositionDown[t].x,h=e.clientY-this._pointerPositionDown[t].y,d=0;if(e.isSpatial&&e.clientZ!=null&&(d=e.clientZ-this._pointerPositionDown[t].z,l*=200,h*=200,d*=200),Math.abs(l)<5&&Math.abs(h)<5&&Math.abs(d)<5){this.setPointerState(t,this._pointerClick,!0),e.isClick=!0;const u=r-n;Be&&console.log("CLICK",t,l,h,d,u),u<this._doubleClickTimeThreshold&&u>0&&(this.setPointerState(t,this._pointerDoubleClick,!0),e.isDoubleClick=!0)}}this.onDispatchEvent(e)}updatePointerPosition(e){const t=e.pointerId;for(;t>=this._pointerPositions.length;)this._pointerPositions.push(new c.Vector2);for(;t>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new c.Vector2);for(;t>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new c.Vector2);const i=this._pointerPositionsLastFrame[t];i.copy(this._pointerPositions[t]);const n=this._pointerPositionsDelta[t];let o=e.clientX-i.x,r=e.clientY-i.y;if(e.source instanceof MouseEvent||e.source instanceof TouchEvent){const d=e.source;o===0&&d.movementX!==0&&(o=d.movementX||0),r===0&&d.movementY!==0&&(r=d.movementY||0)}n.x+=o,n.y+=r,this._pointerPositions[t].x=e.clientX,this._pointerPositions[t].y=e.clientY;const a=e.clientX,l=e.clientY;for(;t>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new c.Vector2);const h=this._pointerPositionsRC[t];h.set(a,l),this.convertScreenspaceToRaycastSpace(h)}getPointerIndex(e){let t=-1;for(let i=0;i<this._pointerIds.length;i++){if(this._pointerIds[i]===e)return i;t===-1&&this._pointerIds[i]===-1&&(t=i)}return t!==-1?(this._pointerIds[t]=e,t):(Be&&console.log("PUSH pointerId:",e),this._pointerIds.push(e),this._pointerIds.length-1)}setPointerState(e,t,i){t[e]=i}setPointerStateT(e,t,i){return t[e]=i,i}onDispatchEvent(e){const t=U.Current;try{U.Current=this.context,this.dispatchEvent(e)}finally{U.Current=t}}}const pa=new c.Matrix4().makeRotationY(Math.PI),Ai=new c.Quaternion().setFromAxisAngle(new c.Vector3(0,1,0),Math.PI),lC=x("debugwebxr");class cC{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",lC){const e=zm(16733661);e.position.y+=.5,this.gameObject.add(e)}}}const Xn=x("debugwebxr"),Eh=x("debugcustomgesture"),hC="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",dC="generic-trigger",uC=new c.Quaternion().setFromEuler(new c.Euler(c.MathUtils.degToRad(0),c.MathUtils.degToRad(-90),c.MathUtils.degToRad(-90))),fC=new c.Vector3(.04,-.04,0);class Lm{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 B(this._gripPosition)}get gripQuaternion(){return Zt(this._gripQuaternion)}get gripMatrix(){return this._gripMatrix}get gripLinearVelocity(){return B(this._linearVelocity).applyQuaternion(Ai)}get rayPosition(){return B(this._rayPosition)}get rayQuaternion(){return Zt(this._rayQuaternion)}get gripWorldPosition(){return B(this._gripWorldPosition)}_gripWorldPosition=new c.Vector3;get gripWorldQuaternion(){return Zt(this._gripWorldQuaternion)}_gripWorldQuaternion=new c.Quaternion;get rayWorldPosition(){return B(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 Zt(this._rayWorldQuaternion)}_rayWorldQuaternion=new c.Quaternion;get pinchPosition(){return B(this._pinchPosition)}_pinchPosition=new c.Vector3;updateRayWorldQuaternion(){const e=this.xr.context.mainCamera?.parent,t=e?fe(e):void 0;this._rayWorldQuaternion.copy(this._rayRotationRaw).multiply(Ai),t&&this._rayWorldQuaternion.premultiply(t)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy(B(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=B(0,1,0).applyQuaternion(e.quaternion),i=B(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}`,Xn&&(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(){j.DrawSphere(this.rayWorldPosition,.003),j.DrawDirection(this.rayWorldPosition,B(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(`
|
|
146
146
|
`);let n=`Controller[${this.index}] (${this.inputSource.targetRayMode}, ${this.side})
|
|
147
147
|
C:${this.connected?"x":"-"} T:${this.isTracking?"x":"-"} Hand:${this.inputSource.hand?"x":"-"} Pen: ${this._isMxInk?"x":"-"}`;if(this.inputSource.hand&&(n+=`
|
|
@@ -165,7 +165,7 @@ See https://engine.needle.tools/docs/scripting.html#special-lifecycle-hooks for
|
|
|
165
165
|
`+Mi):console.debug("Connected to networking backend",Mi),n(!0),this.onSendQueued(sn.OnConnection)}).onClose(h=>{this._connectingToWebsocketPromise=null,this.connected=!1,this._isInRoom=!1,n(!1);let d="Websocket connection closed...";Mi?.includes("/socket")||(d+=' Do you perhaps mean to connect to "/socket"?'),console.error(d)}).onError(h=>{console.error("Websocket connection failed..."),n(!1),ei.sendEvent(this.context,"networking",{event:"connection_error"})}).onRetry(()=>{console.log("Retry connecting to networking websocket")}).build();l.addEventListener(o.WebsocketEvent.message,(h,d)=>{this.onMessage(h,d)})})}onMessage(e,t){const i=t.data;try{if(typeof i!="string"){i.size&&this.handleIncomingBinaryMessage(i);return}const n=JSON.parse(i);if(Array.isArray(n))for(const o of n)this.handleIncomingStringMessage(o);else this.handleIncomingStringMessage(n);return}catch(n){Xt&&i==="pong"?console.log("<<",i):T()&&console.error("Failed to parse message",n)}}async handleIncomingBinaryMessage(e){Th&&console.log("<< bin",this.context.time.frame);const t=await e.arrayBuffer();var i=new Uint8Array(t);const n=new re.ByteBuffer(i),o=n.getBufferIdentifier(),r=this._listenersBinary[o],a=vv(n),l=wv(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(Xt&&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,ei.sendEvent(this.context,"networking",{event:"connected"}))}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(Xt&&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),(Th||T())&&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}
|
|
166
166
|
${a.href}`)}this.onSendQueued(sn.OnRoomJoin),ei.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,(Th||T())&&console.debug("Left Needle Engine Room: "+n.room)),ei.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),Xt&&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&&(Xt&&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":Xt&&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),Xt&&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=sn.OnRoomJoin){if(!this._ws){const o=this._waitingForSocket[i]||[];o.push(()=>this.sendWithWebsocket(e,t,i)),this._waitingForSocket[i]=o;return}const n=JSON.stringify(this.toMessage(e,t));Xt&&console.log(">>",e),this._ws.send(n)}onSendQueued(e){const t=this._waitingForSocket[e];if(t){for(const i of t)i();t.length=0}}}const Yl=x("debugwebxr");class yf{controllerStates=[];userId;context;userStateEvtName;constructor(e,t){this.userId=e,this.context=t,this.userStateEvtName="xr-sync-user-state-"+e,this.context.connection.beginListen(this.userStateEvtName,this.onReceivedControllerState)}dispose(){this.context.connection.stopListen(this.userStateEvtName,this.onReceivedControllerState)}onReceivedControllerState=e=>{Yl&&console.log(`XRSync: Received change for ${this.userId}: ${e.type} ${e.handedness}; tracked=${e.isTracking}`);let t=!1;for(let i=0;i<this.controllerStates.length;i++)if(this.controllerStates[i].index===e.index){this.controllerStates[i]=e,t=!0;break}t||this.controllerStates.push(e)};update(e){if(this.context.connection.isConnected!=!1){for(let t=this.controllerStates.length-1;t>=0;t--){const i=this.controllerStates[t];let n=!1;for(let o=0;o<e.controllers.length;o++)e.controllers[o].index===i.index&&(n=!0);n||(Yl&&console.log(`XRSync: ${i.type} ${i.handedness} removed`,i.index),this.controllerStates.splice(t,1),this.sendControllerRemoved(i))}for(const t of e.controllers)this.updateControllerStates(t)}}onExitXR(e){for(const t of this.controllerStates)this.sendControllerRemoved(t);this.controllerStates.length=0}sendControllerRemoved(e){e.isTracking=!1,e.guid="",this.context.connection.send(this.userStateEvtName,e),this.context.connection.sendDeleteRemoteState(e.guid)}updateControllerStates(e){const t=this.controllerStates.find(i=>i.index===e.index);if(t){let i=!1;i||=t.isTracking!=e.isTracking,i&&(t.isTracking=e.isTracking,this.context.connection.send(this.userStateEvtName,t))}else{const i={guid:this.userId+"-"+e.index,isTracking:e.isTracking,handedness:e.side,index:e.index,type:e.hand?"hand":"controller"};this.controllerStates.push(i),this.context.connection.send(this.userStateEvtName,i),Yl&&console.log(`XRSync: ${i.type} ${i.handedness} added`,i.index)}}}class Ov{hasState(e){return e?this._states.has(e):!1}isTracking(e,t){if(!e)return;const i=this._states.get(e);return i?i.controllerStates.find(o=>o.handedness===t)?.isTracking||!1:void 0}getDeviceType(e,t){if(!e)return;const i=this._states.get(e);return i?i.controllerStates.find(o=>o.handedness===t)?.type||"unknown":void 0}context;constructor(e){this.context=e,this.context.connection.beginListen(Y.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Y.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(Y.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(Y.UserLeftRoom,this.onOtherUserLeftRoom)}destroy(){this.context.connection.stopListen(Y.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Y.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(Y.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(Y.UserLeftRoom,this.onOtherUserLeftRoom)}onJoinedRoom=()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(Yl&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new yf(this.context.connection.connectionId,this.context)));for(const e of this.context.connection.usersInRoom())this._states.has(e)||this._states.set(e,new yf(e,this.context))}};onLeftRoom=()=>{this.context.connection.connectionId&&(this._states.has(this.context.connection.connectionId)||(this._states.get(this.context.connection.connectionId)?.dispose(),this._states.delete(this.context.connection.connectionId)))};onOtherUserJoinedRoom=e=>{const t=e.userId;this._states.has(t)||(Yl&&console.log("XRSync: Remote user joined room",t),this._states.set(t,new yf(t,this.context)))};onOtherUserLeftRoom=e=>{const t=e.userId;this._states.has(t)||(this._states.get(t)?.dispose(),this._states.delete(t))};_states=new Map;onUpdate(e){this.context.connection.isConnected&&this.context.connection.connectionId&&this._states.get(this.context.connection.connectionId)?.update(e)}onExitXR(e){this.context.connection.isConnected&&this.context.connection.connectionId&&this._states.get(this.context.connection.connectionId)?.onExitXR(e)}}class i_{_fadeToColorQuad;_fadeToColorMaterial;constructor(){this._fadeToColorMaterial=new c.MeshBasicMaterial({color:0,transparent:!0,depthTest:!1,fog:!1,side:c.DoubleSide}),this._fadeToColorQuad=new c.Mesh(new c.PlaneGeometry(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(e,t){const i=this._fadeToColorQuad,n=this._fadeToColorMaterial;i.parent!==e&&n.opacity>0?e.add(i):n.opacity===0&&i.removeFromParent(),i.layers.set(2),i.material=this._fadeToColorMaterial,i.position.z=-1,i.renderOrder=1/0;const o=this._requestedFadeValue;n.opacity=I.lerp(n.opacity,o,t/.03),Math.abs(n.opacity-o)<=.01&&this._transitionResolve&&(this._transitionResolve(),this._transitionResolve=null,this._transitionPromise=null,this._requestedFadeValue=0)}remove(){this._fadeToColorQuad.removeFromParent()}fadeTransition(){if(this._transitionPromise)return this._transitionPromise;this._requestedFadeValue=1;const e=new Promise(t=>{this._transitionResolve=t});return this._transitionPromise=e,e}_requestedFadeValue=0;_transitionPromise=null;_transitionResolve=null}const wC='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 160 187.74"><defs><linearGradient id="a" x1="89.64" y1="184.81" x2="90.48" y2="21.85" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#62d399"/><stop offset=".51" stop-color="#acd842"/><stop offset=".9" stop-color="#d7db0a"/></linearGradient><linearGradient id="b" x1="69.68" y1="178.9" x2="68.08" y2="16.77" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#0ba398"/><stop offset=".5" stop-color="#4ca352"/><stop offset="1" stop-color="#76a30a"/></linearGradient><linearGradient id="c" x1="36.6" y1="152.17" x2="34.7" y2="84.19" gradientUnits="userSpaceOnUse"><stop offset=".19" stop-color="#36a382"/><stop offset=".54" stop-color="#49a459"/><stop offset="1" stop-color="#76a30b"/></linearGradient><linearGradient id="d" x1="15.82" y1="153.24" x2="18" y2="90.86" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#267880"/><stop offset=".51" stop-color="#457a5c"/><stop offset="1" stop-color="#717516"/></linearGradient><linearGradient id="e" x1="135.08" y1="135.43" x2="148.93" y2="63.47" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#b0d939"/><stop offset="1" stop-color="#eadb04"/></linearGradient><linearGradient id="f" x1="-4163.25" y1="2285.12" x2="-4160.81" y2="2215.34" gradientTransform="rotate(20 4088.49 13316.712)" gradientUnits="userSpaceOnUse"><stop offset=".17" stop-color="#74af52"/><stop offset=".48" stop-color="#99be32"/><stop offset="1" stop-color="#c0c40a"/></linearGradient><symbol id="g" viewBox="0 0 160 187.74"><path style="fill:url(#a)" d="M79.32 36.98v150.76L95 174.54l6.59-156.31-22.27 18.75z"/><path style="fill:url(#b)" d="M79.32 36.98 57.05 18.23l6.59 156.31 15.68 13.2V36.98z"/><path style="fill:url(#c)" d="m25.19 104.83 8.63 49.04 12.5-14.95-2.46-56.42-18.67 22.33z"/><path style="fill:url(#d)" d="M25.19 104.83 0 90.24l16.97 53.86 16.85 9.77-8.63-49.04z"/><path style="fill:#9c3" d="M43.86 82.5 18.69 67.98 0 90.24l25.18 14.59L43.86 82.5z"/><path style="fill:url(#e)" d="m134.82 78.69-9.97 56.5 15.58-9.04L160 64.1l-25.18 14.59z"/><path style="fill:url(#f)" d="m134.82 78.69-18.68-22.33-2.86 65 11.57 13.83 9.97-56.5z"/><path style="fill:#ffe113" d="m160 64.1-18.69-22.26-25.17 14.52 18.67 22.33L160 64.1z"/><path style="fill:#f3e600" d="M101.59 18.23 79.32 0 57.05 18.23l22.27 18.75 22.27-18.75z"/></symbol></defs><use width="160" height="187.74" xlink:href="#g"/></svg>',xC=btoa(wC),SC="data:image/svg+xml;base64,"+xC,Oa=SC,CC=`<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'> <svg clip-rule="evenodd" fill-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2" version="1.1" viewBox="0 0 1014 282" xml:space="preserve" xmlns="http://www.w3.org/2000/svg"> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m665.95 132.73v44.88l-10.56-8.4c-0.8-0.64-1.2-1.44-1.2-2.4v-32.4c0-6.48-4.12-9.72-12.36-9.72-2.16 0-4.18 0.4-6.06 1.2s-3.54 1.8-4.98 3-2.56 2.5-3.36 3.9-1.2 2.7-1.2 3.9v40.92l-10.68-8.4c-0.72-0.64-1.08-1.44-1.08-2.4v-53.76l10.92 8.52c0.32 0.24 0.56 0.44 0.72 0.6s0.36 0.32 0.6 0.48c0.96-1.2 2.14-2.28 3.54-3.24s2.92-1.76 4.56-2.4 3.34-1.14 5.1-1.5 3.44-0.54 5.04-0.54c1.44 0 2.92 0.04 4.44 0.12s2.84 0.28 3.96 0.6c4.56 1.12 7.8 3.12 9.72 6s2.88 6.56 2.88 11.04z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m732.38 146.05c0 0.88 0.02 1.5 0.06 1.86s-0.02 0.98-0.18 1.86h-7.08c-2.08 0-4.44-0.02-7.08-0.06s-5.36-0.06-8.16-0.06h-22.08c0 2.88 0.56 5.36 1.68 7.44s2.6 3.8 4.44 5.16 3.94 2.36 6.3 3 4.74 0.96 7.14 0.96c3.04 0 5.9-0.76 8.58-2.28s4.94-3.52 6.78-6c0.64 0.56 1.54 1.48 2.7 2.76s2.94 3.2 5.34 5.76c-2.8 3.36-6.22 6.02-10.26 7.98s-8.42 2.94-13.14 2.94-8.92-0.64-12.84-1.92-7.32-3.24-10.2-5.88-5.12-5.98-6.72-10.02-2.4-8.82-2.4-14.34c0-4.96 0.66-9.42 1.98-13.38s3.22-7.32 5.7-10.08 5.44-4.9 8.88-6.42 7.32-2.28 11.64-2.28c5.76 0 10.52 0.88 14.28 2.64s6.72 4.16 8.88 7.2 3.66 6.54 4.5 10.5 1.26 8.18 1.26 12.66zm-29.4-22.8c-2.16 0.16-4.16 0.72-6 1.68s-3.42 2.2-4.74 3.72-2.36 3.28-3.12 5.28-1.14 4.12-1.14 6.36h33.12c0-2-0.22-4.06-0.66-6.18s-1.3-4.02-2.58-5.7-3.1-3.02-5.46-4.02-5.5-1.38-9.42-1.14z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m795.93 146.05c0 0.88 0.02 1.5 0.06 1.86s-0.02 0.98-0.18 1.86h-7.08c-2.08 0-4.44-0.02-7.08-0.06s-5.36-0.06-8.16-0.06h-22.08c0 2.88 0.56 5.36 1.68 7.44s2.6 3.8 4.44 5.16 3.94 2.36 6.3 3 4.74 0.96 7.14 0.96c3.04 0 5.9-0.76 8.58-2.28s4.94-3.52 6.78-6c0.64 0.56 1.54 1.48 2.7 2.76s2.94 3.2 5.34 5.76c-2.8 3.36-6.22 6.02-10.26 7.98s-8.42 2.94-13.14 2.94-8.92-0.64-12.84-1.92-7.32-3.24-10.2-5.88-5.12-5.98-6.72-10.02-2.4-8.82-2.4-14.34c0-4.96 0.66-9.42 1.98-13.38s3.22-7.32 5.7-10.08 5.44-4.9 8.88-6.42 7.32-2.28 11.64-2.28c5.76 0 10.52 0.88 14.28 2.64s6.72 4.16 8.88 7.2 3.66 6.54 4.5 10.5 1.26 8.18 1.26 12.66zm-29.4-22.8c-2.16 0.16-4.16 0.72-6 1.68s-3.42 2.2-4.74 3.72-2.36 3.28-3.12 5.28-1.14 4.12-1.14 6.36h33.12c0-2-0.22-4.06-0.66-6.18s-1.3-4.02-2.58-5.7-3.1-3.02-5.46-4.02-5.5-1.38-9.42-1.14z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m858.57 97.21c0.64 0.48 0.96 1.16 0.96 2.04v74.88c-0.08 1.04-0.12 2.12-0.12 3.24-1.84-1.52-3.56-2.92-5.16-4.2-1.36-1.12-2.66-2.18-3.9-3.18s-2.06-1.66-2.46-1.98c-1.76 2.48-4.26 4.44-7.5 5.88s-7.02 2.16-11.34 2.16c-3.84 0-7.4-0.7-10.68-2.1s-6.14-3.44-8.58-6.12-4.34-5.94-5.7-9.78-2.04-8.16-2.04-12.96c0-4.32 0.78-8.34 2.34-12.06s3.6-6.92 6.12-9.6 5.38-4.78 8.58-6.3 6.48-2.28 9.84-2.28c2.56 0 4.82 0.22 6.78 0.66s3.68 1.06 5.16 1.86 2.78 1.74 3.9 2.82 2.16 2.22 3.12 3.42v-35.04l10.68 8.64zm-27.96 67.92c3.6 0 6.52-0.68 8.76-2.04s3.98-3.06 5.22-5.1 2.1-4.22 2.58-6.54 0.72-4.44 0.72-6.36v-1.2c0-1.12-0.22-2.7-0.66-4.74s-1.28-4.06-2.52-6.06-3-3.7-5.28-5.1-5.22-2.02-8.82-1.86c-3.44 0-6.26 0.74-8.46 2.22s-3.96 3.26-5.28 5.34-2.24 4.2-2.76 6.36-0.78 3.92-0.78 5.28c0 1.84 0.24 3.92 0.72 6.24s1.36 4.48 2.64 6.48 3.04 3.68 5.28 5.04 5.12 2.04 8.64 2.04z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m882.81 97.09c0.64 0.48 0.96 1.12 0.96 1.92l-0.12 41.04v37.08l-10.56-8.4c-0.72-0.64-1.08-1.44-1.08-2.4v-77.88l10.8 8.64z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m950.36 146.05c0 0.88 0.02 1.5 0.06 1.86s-0.02 0.98-0.18 1.86h-7.08c-2.08 0-4.44-0.02-7.08-0.06s-5.36-0.06-8.16-0.06h-22.08c0 2.88 0.56 5.36 1.68 7.44s2.6 3.8 4.44 5.16 3.94 2.36 6.3 3 4.74 0.96 7.14 0.96c3.04 0 5.9-0.76 8.58-2.28s4.94-3.52 6.78-6c0.64 0.56 1.54 1.48 2.7 2.76s2.94 3.2 5.34 5.76c-2.8 3.36-6.22 6.02-10.26 7.98s-8.42 2.94-13.14 2.94-8.92-0.64-12.84-1.92-7.32-3.24-10.2-5.88-5.12-5.98-6.72-10.02-2.4-8.82-2.4-14.34c0-4.96 0.66-9.42 1.98-13.38s3.22-7.32 5.7-10.08 5.44-4.9 8.88-6.42 7.32-2.28 11.64-2.28c5.76 0 10.52 0.88 14.28 2.64s6.72 4.16 8.88 7.2 3.66 6.54 4.5 10.5 1.26 8.18 1.26 12.66zm-29.4-22.8c-2.16 0.16-4.16 0.72-6 1.68s-3.42 2.2-4.74 3.72-2.36 3.28-3.12 5.28-1.14 4.12-1.14 6.36h33.12c0-2-0.22-4.06-0.66-6.18s-1.3-4.02-2.58-5.7-3.1-3.02-5.46-4.02-5.5-1.38-9.42-1.14z" fill-rule="nonzero"/> </g> <g transform="matrix(1.8559 0 0 .7642 45.348 36.475)"> <g transform="translate(2.7114)"> <path d="m3.935 173.02c-0.331 0-0.497-0.402-0.497-1.207v-51.002c0-0.738 0.138-1.107 0.414-1.107h1.781c0.277 0 0.415 0.335 0.415 1.006v5.935c0 0.336 0.027 0.553 0.083 0.654 0.055 0.101 0.151-0.017 0.289-0.352 0.912-1.744 1.754-3.236 2.527-4.477 0.773-1.24 1.554-2.179 2.341-2.816s1.65-0.956 2.588-0.956c1.685 0 3.011 0.922 3.977 2.766 0.967 1.845 1.602 3.84 1.905 5.986 0.056 0.268 0.139 0.369 0.249 0.302s0.221-0.235 0.331-0.503c0.939-1.811 1.802-3.353 2.589-4.628 0.787-1.274 1.581-2.246 2.382-2.917s1.671-1.006 2.61-1.006c2.016 0 3.569 1.392 4.66 4.175 1.09 2.783 1.636 6.421 1.636 10.915v37.925c0 0.871-0.18 1.307-0.539 1.307h-1.739c-0.138 0-0.249-0.1-0.332-0.301-0.083-0.202-0.124-0.503-0.124-0.906v-36.315c0-3.555-0.338-6.321-1.015-8.3-0.676-1.978-1.76-2.967-3.251-2.967-0.884 0-1.726 0.386-2.527 1.157s-1.519 1.727-2.154 2.867-1.201 2.213-1.699 3.219c-0.248 0.469-0.421 0.905-0.517 1.308-0.097 0.402-0.145 0.972-0.145 1.71v37.221c0 0.871-0.166 1.307-0.497 1.307h-1.74c-0.166 0-0.29-0.1-0.373-0.301-0.083-0.202-0.124-0.503-0.124-0.906v-36.315c0-3.555-0.332-6.321-0.994-8.3-0.663-1.978-1.754-2.967-3.273-2.967-1.242 0-2.375 0.704-3.396 2.112-1.022 1.409-2.223 3.555-3.604 6.439v39.031c0 0.805-0.18 1.207-0.539 1.207h-1.698z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m53.642 166.28c-1.077 2.549-2.237 4.477-3.479 5.785-1.243 1.307-2.61 1.961-4.101 1.961-2.154 0-3.853-1.324-5.095-3.973-1.243-2.649-1.864-6.187-1.864-10.613 0-3.488 0.4-6.489 1.201-9.004s1.988-4.51 3.562-5.985c1.574-1.476 3.521-2.414 5.841-2.817l3.686-0.704c0.221-0.067 0.394-0.218 0.518-0.453 0.124-0.234 0.187-0.587 0.187-1.056v-2.917c0-3.89-0.504-6.975-1.512-9.255s-2.354-3.42-4.039-3.42c-1.298 0-2.472 0.72-3.521 2.162s-2.002 3.572-2.858 6.388c-0.083 0.268-0.159 0.453-0.228 0.554-0.069 0.1-0.172 0.083-0.311-0.051l-1.698-1.71c-0.083-0.134-0.138-0.285-0.166-0.453-0.027-0.167 0.014-0.452 0.125-0.855 0.856-3.353 2.009-6.052 3.459-8.098 1.449-2.045 3.224-3.068 5.322-3.068 1.74 0 3.211 0.687 4.412 2.062s2.112 3.37 2.734 5.986c0.621 2.615 0.932 5.7 0.932 9.255v35.712c0 0.536-0.035 0.888-0.104 1.056s-0.2 0.251-0.393 0.251h-1.533c-0.166 0-0.29-0.117-0.373-0.352-0.083-0.234-0.124-0.553-0.124-0.955l-0.083-5.231c-0.055-0.939-0.221-1.006-0.497-0.202zm0.456-19.314c0-1.14-0.194-1.643-0.58-1.509l-3.107 0.603c-1.436 0.202-2.686 0.638-3.749 1.308-1.063 0.671-1.953 1.543-2.671 2.616s-1.257 2.33-1.616 3.772-0.538 3.102-0.538 4.98c0 3.152 0.455 5.616 1.367 7.393 0.911 1.778 2.14 2.666 3.686 2.666 0.939 0 1.85-0.419 2.734-1.257s1.671-1.895 2.361-3.169c0.663-1.408 1.181-2.85 1.553-4.326 0.373-1.475 0.56-2.883 0.56-4.225v-8.852z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m79.034 173.02c-0.166 0-0.297-0.117-0.394-0.352-0.096-0.234-0.145-0.553-0.145-0.955v-4.628c0-0.536-0.041-0.838-0.124-0.905s-0.207 0.1-0.373 0.503c-0.276 0.67-0.69 1.593-1.242 2.766-0.553 1.174-1.271 2.23-2.154 3.169-0.884 0.939-1.961 1.408-3.231 1.408-1.74 0-3.314-0.989-4.722-2.967-1.409-1.979-2.534-4.963-3.376-8.953-0.843-3.991-1.264-8.937-1.264-14.838 0-5.701 0.415-10.68 1.243-14.939s1.988-7.595 3.479-10.009c1.492-2.415 3.204-3.622 5.137-3.622 1.436 0 2.616 0.57 3.541 1.71 0.926 1.14 1.719 2.381 2.382 3.722 0.249 0.47 0.414 0.637 0.497 0.503s0.125-0.536 0.125-1.207v-23.841c0-0.805 0.151-1.208 0.455-1.208h1.864c0.276 0 0.414 0.369 0.414 1.107v72.128c0 0.537-0.041 0.905-0.124 1.107-0.083 0.201-0.235 0.301-0.455 0.301h-1.533zm-0.621-42.049c-0.939-2.213-1.885-3.94-2.838-5.181s-2.009-1.861-3.169-1.861c-1.463 0-2.768 0.889-3.914 2.666s-2.044 4.376-2.693 7.796-0.973 7.578-0.973 12.474c0 5.097 0.338 9.272 1.015 12.524 0.676 3.253 1.567 5.651 2.672 7.193 1.104 1.543 2.305 2.314 3.603 2.314 1.188 0 2.258-0.704 3.211-2.113 0.952-1.408 1.705-3.118 2.257-5.13s0.829-3.957 0.829-5.835v-24.847z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m89.514 149.38c0 3.42 0.345 6.606 1.035 9.557 0.691 2.951 1.609 5.315 2.755 7.092s2.437 2.666 3.873 2.666c1.519 0 2.837-0.738 3.956-2.213 1.118-1.476 2.064-3.655 2.837-6.539 0.083-0.336 0.166-0.52 0.249-0.554 0.083-0.033 0.179 0.017 0.29 0.151l1.408 1.912c0.221 0.268 0.235 0.67 0.041 1.207-0.69 2.548-1.47 4.661-2.34 6.337-0.87 1.677-1.857 2.935-2.962 3.773-1.104 0.838-2.319 1.257-3.645 1.257-2.043 0-3.838-1.14-5.385-3.42-1.546-2.28-2.761-5.482-3.645-9.607-0.884-4.124-1.325-8.836-1.325-14.134 0-5.901 0.455-10.931 1.367-15.089 0.911-4.158 2.14-7.377 3.686-9.658 1.547-2.28 3.3-3.42 5.261-3.42 1.988 0 3.714 1.073 5.178 3.219 1.463 2.146 2.595 5.231 3.396 9.255s1.201 8.886 1.201 14.587c0 0.469-0.02 0.939-0.062 1.408-0.041 0.469-0.214 0.704-0.517 0.704h-16.362c-0.083 0-0.152 0.151-0.207 0.453-0.056 0.302-0.083 0.654-0.083 1.056zm13.752-6.237c0.304 0 0.497-0.1 0.58-0.302 0.083-0.201 0.124-0.57 0.124-1.106 0-3.219-0.283-6.187-0.849-8.903s-1.367-4.896-2.402-6.539c-1.036-1.643-2.272-2.464-3.708-2.464-1.629 0-2.996 0.955-4.101 2.867-1.104 1.911-1.94 4.342-2.506 7.293s-0.849 6.002-0.849 9.154h13.711z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m148.54 119.7c0.165 0 0.283 0.117 0.352 0.352s0.076 0.52 0.02 0.855l-6.254 50.902c-0.028 0.47-0.104 0.788-0.228 0.956s-0.297 0.251-0.518 0.251h-1.615c-0.442 0-0.718-0.402-0.829-1.207l-5.26-40.138c-0.111-0.604-0.201-0.905-0.27-0.905s-0.131 0.301-0.186 0.905l-5.012 40.138c-0.028 0.47-0.097 0.788-0.207 0.956-0.111 0.168-0.277 0.251-0.497 0.251h-1.74c-0.442 0-0.718-0.402-0.829-1.207l-6.503-50.801c-0.055-0.403-0.048-0.721 0.021-0.956s0.2-0.352 0.393-0.352h1.823c0.166 0 0.297 0.067 0.393 0.201 0.097 0.134 0.159 0.403 0.187 0.805l5.302 41.848c0.083 0.671 0.179 0.989 0.29 0.956 0.11-0.034 0.207-0.386 0.29-1.056l5.219-41.949c0.055-0.268 0.124-0.47 0.207-0.604s0.193-0.201 0.331-0.201h1.533c0.138 0 0.262 0.067 0.373 0.201 0.11 0.134 0.179 0.403 0.207 0.805l5.468 41.848c0.083 0.671 0.179 0.989 0.29 0.956 0.11-0.034 0.207-0.386 0.29-1.056l5.053-41.849c0.055-0.335 0.138-0.57 0.249-0.704 0.11-0.134 0.234-0.201 0.373-0.201h1.284z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m156.49 171.51c0 0.604-0.042 1.006-0.125 1.208-0.082 0.201-0.262 0.301-0.538 0.301h-1.533c-0.221 0-0.366-0.083-0.435-0.251s-0.103-0.486-0.103-0.956v-50.902c0-0.805 0.152-1.207 0.456-1.207h1.822c0.304 0 0.456 0.402 0.456 1.207v50.6zm0.165-63.979c0 1.207-0.207 1.811-0.621 1.811h-1.905c-0.221 0-0.366-0.135-0.435-0.403s-0.104-0.67-0.104-1.207v-7.847c0-1.006 0.18-1.509 0.539-1.509h1.988c0.359 0 0.538 0.47 0.538 1.409v7.746z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m168.3 124.83c-0.221 0-0.331 0.269-0.331 0.805v33.801c0 3.42 0.221 5.667 0.663 6.74 0.441 1.073 1.09 1.609 1.946 1.609h3.024c0.138 0 0.242 0.084 0.311 0.252 0.069 0.167 0.103 0.419 0.103 0.754v2.716c0 0.537-0.138 0.906-0.414 1.107-0.248 0.067-0.614 0.134-1.098 0.201-0.483 0.067-0.959 0.118-1.429 0.151-0.469 0.034-0.828 0.05-1.077 0.05-1.712 0-2.934-0.955-3.665-2.867-0.732-1.911-1.098-5.013-1.098-9.305v-35.108c0-0.604-0.124-0.906-0.373-0.906h-3.521c-0.248 0-0.373-0.268-0.373-0.804v-3.521c0-0.537 0.111-0.805 0.332-0.805h3.686c0.166 0 0.263-0.268 0.29-0.805l0.415-16.095c0-0.805 0.124-1.207 0.372-1.207h1.492c0.303 0 0.455 0.436 0.455 1.307v15.995c0 0.537 0.097 0.805 0.29 0.805h5.468c0.221 0 0.331 0.268 0.331 0.805v3.521c0 0.536-0.124 0.804-0.373 0.804h-5.426z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m179.4 173.02c-0.331 0-0.497-0.402-0.497-1.207v-72.329c0-0.738 0.138-1.107 0.414-1.107h1.782c0.276 0 0.414 0.336 0.414 1.006v27.162c0 0.335 0.034 0.536 0.103 0.603s0.159-0.033 0.27-0.302c0.994-1.81 1.898-3.319 2.713-4.526 0.814-1.208 1.629-2.113 2.444-2.717 0.814-0.603 1.691-0.905 2.63-0.905 2.182 0 3.839 1.375 4.971 4.125 1.132 2.749 1.698 6.404 1.698 10.965v37.925c0 0.871-0.166 1.307-0.497 1.307h-1.74c-0.165 0-0.29-0.1-0.373-0.301-0.082-0.202-0.124-0.503-0.124-0.906v-36.315c0-3.555-0.366-6.321-1.097-8.3-0.732-1.978-1.899-2.967-3.501-2.967-0.883 0-1.705 0.318-2.464 0.956-0.76 0.637-1.526 1.576-2.299 2.816-0.773 1.241-1.643 2.834-2.61 4.779v39.031c0 0.805-0.179 1.207-0.538 1.207h-1.699z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> </g> <g transform="matrix(.80638 0 0 .80638 452.53 65.421)" fill-rule="nonzero"> <path d="m79.32 36.98v150.76l15.68-13.2 6.59-156.31-22.27 18.75z" fill="url(#f)"/> <path d="m79.32 36.98-22.27-18.75 6.59 156.31 15.68 13.2v-150.76z" fill="url(#e)"/> <path d="m25.19 104.83 8.63 49.04 12.5-14.95-2.46-56.42-18.67 22.33z" fill="url(#d)"/> <path d="m25.19 104.83-25.19-14.59 16.97 53.86 16.85 9.77-8.63-49.04z" fill="url(#c)"/> <path d="M43.86,82.5L18.69,67.98L0,90.24L25.18,104.83L43.86,82.5Z" fill="#9c3"/> <path d="m134.82 78.69-9.97 56.5 15.58-9.04 19.57-62.05-25.18 14.59z" fill="url(#b)"/> <path d="m134.82 78.69-18.68-22.33-2.86 65 11.57 13.83 9.97-56.5z" fill="url(#a)"/> <path d="m160 64.1-18.69-22.26-25.17 14.52 18.67 22.33 25.19-14.59z" fill="#ffe113"/> <path d="M101.59,18.23L79.32,0L57.05,18.23L79.32,36.98L101.59,18.23Z" fill="#f3e600"/> </g> <defs> <linearGradient id="f" x2="1" gradientTransform="matrix(.84 -162.96 162.96 .84 89.64 184.81)" gradientUnits="userSpaceOnUse"><stop stop-color="#62d399" offset="0"/><stop stop-color="#acd842" offset=".51"/><stop stop-color="#d7db0a" offset=".9"/><stop stop-color="#d7db0a" offset="1"/></linearGradient> <linearGradient id="e" x2="1" gradientTransform="matrix(-1.6,-162.13,162.13,-1.6,69.68,178.9)" gradientUnits="userSpaceOnUse"><stop stop-color="#0ba398" offset="0"/><stop stop-color="#4ca352" offset=".5"/><stop stop-color="#76a30a" offset="1"/></linearGradient> <linearGradient id="d" x2="1" gradientTransform="matrix(-1.9,-67.98,67.98,-1.9,36.6,152.17)" gradientUnits="userSpaceOnUse"><stop stop-color="#36a382" offset="0"/><stop stop-color="#36a382" offset=".19"/><stop stop-color="#49a459" offset=".54"/><stop stop-color="#76a30b" offset="1"/></linearGradient> <linearGradient id="c" x2="1" gradientTransform="matrix(2.18,-62.38,62.38,2.18,15.82,153.24)" gradientUnits="userSpaceOnUse"><stop stop-color="#267880" offset="0"/><stop stop-color="#457a5c" offset=".51"/><stop stop-color="#717516" offset="1"/></linearGradient> <linearGradient id="b" x2="1" gradientTransform="matrix(13.85,-71.96,71.96,13.85,135.08,135.43)" gradientUnits="userSpaceOnUse"><stop stop-color="#b0d939" offset="0"/><stop stop-color="#eadb04" offset="1"/></linearGradient> <linearGradient id="a" x2="1" gradientTransform="matrix(26.159 -64.737 64.737 26.159 107.42 128.14)" gradientUnits="userSpaceOnUse"><stop stop-color="#74af52" offset="0"/><stop stop-color="#74af52" offset=".17"/><stop stop-color="#99be32" offset=".48"/><stop stop-color="#c0c40a" offset="1"/></linearGradient> </defs> </svg>`;btoa(CC);const PC='<svg viewBox="0 0 509 154" xmlns="http://www.w3.org/2000/svg" xml:space="preserve" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2"><path d="M665.95 132.73v44.88l-10.56-8.4c-.8-.64-1.2-1.44-1.2-2.4v-32.4c0-6.48-4.12-9.72-12.36-9.72-2.16 0-4.18.4-6.06 1.2-1.88.8-3.54 1.8-4.98 3-1.44 1.2-2.56 2.5-3.36 3.9-.8 1.4-1.2 2.7-1.2 3.9v40.92l-10.68-8.4c-.72-.64-1.08-1.44-1.08-2.4v-53.76l10.92 8.52c.32.24.56.44.72.6.16.16.36.32.6.48.96-1.2 2.14-2.28 3.54-3.24 1.4-.96 2.92-1.76 4.56-2.4 1.64-.64 3.34-1.14 5.1-1.5 1.76-.36 3.44-.54 5.04-.54 1.44 0 2.92.04 4.44.12 1.52.08 2.84.28 3.96.6 4.56 1.12 7.8 3.12 9.72 6 1.92 2.88 2.88 6.56 2.88 11.04ZM732.38 146.05c0 .88.02 1.5.06 1.86.04.36-.02.98-.18 1.86h-7.08c-2.08 0-4.44-.02-7.08-.06-2.64-.04-5.36-.06-8.16-.06h-22.08c0 2.88.56 5.36 1.68 7.44 1.12 2.08 2.6 3.8 4.44 5.16 1.84 1.36 3.94 2.36 6.3 3 2.36.64 4.74.96 7.14.96 3.04 0 5.9-.76 8.58-2.28 2.68-1.52 4.94-3.52 6.78-6 .64.56 1.54 1.48 2.7 2.76 1.16 1.28 2.94 3.2 5.34 5.76-2.8 3.36-6.22 6.02-10.26 7.98-4.04 1.96-8.42 2.94-13.14 2.94-4.72 0-8.92-.64-12.84-1.92-3.92-1.28-7.32-3.24-10.2-5.88-2.88-2.64-5.12-5.98-6.72-10.02-1.6-4.04-2.4-8.82-2.4-14.34 0-4.96.66-9.42 1.98-13.38 1.32-3.96 3.22-7.32 5.7-10.08s5.44-4.9 8.88-6.42c3.44-1.52 7.32-2.28 11.64-2.28 5.76 0 10.52.88 14.28 2.64 3.76 1.76 6.72 4.16 8.88 7.2 2.16 3.04 3.66 6.54 4.5 10.5.84 3.96 1.26 8.18 1.26 12.66Zm-29.4-22.8c-2.16.16-4.16.72-6 1.68-1.84.96-3.42 2.2-4.74 3.72-1.32 1.52-2.36 3.28-3.12 5.28-.76 2-1.14 4.12-1.14 6.36h33.12c0-2-.22-4.06-.66-6.18-.44-2.12-1.3-4.02-2.58-5.7-1.28-1.68-3.1-3.02-5.46-4.02-2.36-1-5.5-1.38-9.42-1.14ZM795.93 146.05c0 .88.02 1.5.06 1.86.04.36-.02.98-.18 1.86h-7.08c-2.08 0-4.44-.02-7.08-.06-2.64-.04-5.36-.06-8.16-.06h-22.08c0 2.88.56 5.36 1.68 7.44 1.12 2.08 2.6 3.8 4.44 5.16 1.84 1.36 3.94 2.36 6.3 3 2.36.64 4.74.96 7.14.96 3.04 0 5.9-.76 8.58-2.28 2.68-1.52 4.94-3.52 6.78-6 .64.56 1.54 1.48 2.7 2.76 1.16 1.28 2.94 3.2 5.34 5.76-2.8 3.36-6.22 6.02-10.26 7.98-4.04 1.96-8.42 2.94-13.14 2.94-4.72 0-8.92-.64-12.84-1.92-3.92-1.28-7.32-3.24-10.2-5.88-2.88-2.64-5.12-5.98-6.72-10.02-1.6-4.04-2.4-8.82-2.4-14.34 0-4.96.66-9.42 1.98-13.38 1.32-3.96 3.22-7.32 5.7-10.08s5.44-4.9 8.88-6.42c3.44-1.52 7.32-2.28 11.64-2.28 5.76 0 10.52.88 14.28 2.64 3.76 1.76 6.72 4.16 8.88 7.2 2.16 3.04 3.66 6.54 4.5 10.5.84 3.96 1.26 8.18 1.26 12.66Zm-29.4-22.8c-2.16.16-4.16.72-6 1.68-1.84.96-3.42 2.2-4.74 3.72-1.32 1.52-2.36 3.28-3.12 5.28-.76 2-1.14 4.12-1.14 6.36h33.12c0-2-.22-4.06-.66-6.18-.44-2.12-1.3-4.02-2.58-5.7-1.28-1.68-3.1-3.02-5.46-4.02-2.36-1-5.5-1.38-9.42-1.14ZM858.57 97.21c.64.48.96 1.16.96 2.04v74.88c-.08 1.04-.12 2.12-.12 3.24-1.84-1.52-3.56-2.92-5.16-4.2-1.36-1.12-2.66-2.18-3.9-3.18-1.24-1-2.06-1.66-2.46-1.98-1.76 2.48-4.26 4.44-7.5 5.88-3.24 1.44-7.02 2.16-11.34 2.16-3.84 0-7.4-.7-10.68-2.1-3.28-1.4-6.14-3.44-8.58-6.12-2.44-2.68-4.34-5.94-5.7-9.78-1.36-3.84-2.04-8.16-2.04-12.96 0-4.32.78-8.34 2.34-12.06 1.56-3.72 3.6-6.92 6.12-9.6 2.52-2.68 5.38-4.78 8.58-6.3 3.2-1.52 6.48-2.28 9.84-2.28 2.56 0 4.82.22 6.78.66 1.96.44 3.68 1.06 5.16 1.86s2.78 1.74 3.9 2.82a35.92 35.92 0 0 1 3.12 3.42V88.57l10.68 8.64Zm-27.96 67.92c3.6 0 6.52-.68 8.76-2.04 2.24-1.36 3.98-3.06 5.22-5.1a20.5 20.5 0 0 0 2.58-6.54c.48-2.32.72-4.44.72-6.36v-1.2c0-1.12-.22-2.7-.66-4.74-.44-2.04-1.28-4.06-2.52-6.06s-3-3.7-5.28-5.1c-2.28-1.4-5.22-2.02-8.82-1.86-3.44 0-6.26.74-8.46 2.22-2.2 1.48-3.96 3.26-5.28 5.34-1.32 2.08-2.24 4.2-2.76 6.36-.52 2.16-.78 3.92-.78 5.28 0 1.84.24 3.92.72 6.24.48 2.32 1.36 4.48 2.64 6.48s3.04 3.68 5.28 5.04c2.24 1.36 5.12 2.04 8.64 2.04ZM882.81 97.09c.64.48.96 1.12.96 1.92l-.12 41.04v37.08l-10.56-8.4c-.72-.64-1.08-1.44-1.08-2.4V88.45l10.8 8.64ZM950.36 146.05c0 .88.02 1.5.06 1.86.04.36-.02.98-.18 1.86h-7.08c-2.08 0-4.44-.02-7.08-.06-2.64-.04-5.36-.06-8.16-.06h-22.08c0 2.88.56 5.36 1.68 7.44 1.12 2.08 2.6 3.8 4.44 5.16 1.84 1.36 3.94 2.36 6.3 3 2.36.64 4.74.96 7.14.96 3.04 0 5.9-.76 8.58-2.28 2.68-1.52 4.94-3.52 6.78-6 .64.56 1.54 1.48 2.7 2.76 1.16 1.28 2.94 3.2 5.34 5.76-2.8 3.36-6.22 6.02-10.26 7.98-4.04 1.96-8.42 2.94-13.14 2.94-4.72 0-8.92-.64-12.84-1.92-3.92-1.28-7.32-3.24-10.2-5.88-2.88-2.64-5.12-5.98-6.72-10.02-1.6-4.04-2.4-8.82-2.4-14.34 0-4.96.66-9.42 1.98-13.38 1.32-3.96 3.22-7.32 5.7-10.08s5.44-4.9 8.88-6.42c3.44-1.52 7.32-2.28 11.64-2.28 5.76 0 10.52.88 14.28 2.64 3.76 1.76 6.72 4.16 8.88 7.2 2.16 3.04 3.66 6.54 4.5 10.5.84 3.96 1.26 8.18 1.26 12.66Zm-29.4-22.8c-2.16.16-4.16.72-6 1.68-1.84.96-3.42 2.2-4.74 3.72-1.32 1.52-2.36 3.28-3.12 5.28-.76 2-1.14 4.12-1.14 6.36h33.12c0-2-.22-4.06-.66-6.18-.44-2.12-1.3-4.02-2.58-5.7-1.28-1.68-3.1-3.02-5.46-4.02-2.36-1-5.5-1.38-9.42-1.14Z" style="fill-rule:nonzero" transform="translate(-452.406 -63.709) scale(1.00797)"/><path d="M79.32 36.98v150.76L95 174.54l6.59-156.31-22.27 18.75Z" style="fill:url(#a);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="M79.32 36.98 57.05 18.23l6.59 156.31 15.68 13.2V36.98Z" style="fill:url(#b);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="m25.19 104.83 8.63 49.04 12.5-14.95-2.46-56.42-18.67 22.33Z" style="fill:url(#c);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="M25.19 104.83 0 90.24l16.97 53.86 16.85 9.77-8.63-49.04Z" style="fill:url(#d);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="M43.86 82.5 18.69 67.98 0 90.24l25.18 14.59L43.86 82.5Z" style="fill:#9c3;fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="m134.82 78.69-9.97 56.5 15.58-9.04L160 64.1l-25.18 14.59Z" style="fill:url(#e);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="m134.82 78.69-18.68-22.33-2.86 65 11.57 13.83 9.97-56.5Z" style="fill:url(#f);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="m160 64.1-18.69-22.26-25.17 14.52 18.67 22.33L160 64.1Z" style="fill:#ffe113;fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="M101.59 18.23 79.32 0 57.05 18.23l22.27 18.75 22.27-18.75Z" style="fill:#f3e600;fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><defs><linearGradient id="a" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="matrix(.84 -162.96 162.96 .84 89.64 184.81)"><stop offset="0" style="stop-color:#62d399;stop-opacity:1"/><stop offset=".51" style="stop-color:#acd842;stop-opacity:1"/><stop offset=".9" style="stop-color:#d7db0a;stop-opacity:1"/><stop offset="1" style="stop-color:#d7db0a;stop-opacity:1"/></linearGradient><linearGradient id="b" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="rotate(-90.565 123.412 54.953) scale(162.14)"><stop offset="0" style="stop-color:#0ba398;stop-opacity:1"/><stop offset=".5" style="stop-color:#4ca352;stop-opacity:1"/><stop offset="1" style="stop-color:#76a30a;stop-opacity:1"/></linearGradient><linearGradient id="c" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="scale(-68) rotate(88.4 .881 -1.396)"><stop offset="0" style="stop-color:#36a382;stop-opacity:1"/><stop offset=".19" style="stop-color:#36a382;stop-opacity:1"/><stop offset=".54" style="stop-color:#49a459;stop-opacity:1"/><stop offset="1" style="stop-color:#76a30b;stop-opacity:1"/></linearGradient><linearGradient id="d" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="rotate(-88 87.255 68.431) scale(62.42)"><stop offset="0" style="stop-color:#267880;stop-opacity:1"/><stop offset=".51" style="stop-color:#457a5c;stop-opacity:1"/><stop offset="1" style="stop-color:#717516;stop-opacity:1"/></linearGradient><linearGradient id="e" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="rotate(-79.1 149.53 -14.065) scale(73.28)"><stop offset="0" style="stop-color:#b0d939;stop-opacity:1"/><stop offset="1" style="stop-color:#eadb04;stop-opacity:1"/></linearGradient><linearGradient id="f" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="rotate(-67.997 148.705 -15.558) scale(69.8226)"><stop offset="0" style="stop-color:#74af52;stop-opacity:1"/><stop offset=".17" style="stop-color:#74af52;stop-opacity:1"/><stop offset=".48" style="stop-color:#99be32;stop-opacity:1"/><stop offset="1" style="stop-color:#c0c40a;stop-opacity:1"/></linearGradient></defs></svg>',MC=btoa(PC),OC="data:image/svg+xml;charset=utf-8;base64,"+MC,n_=OC;var ja=(s=>(s[s.Quad=0]="Quad",s[s.Cube=1]="Cube",s[s.Sphere=2]="Sphere",s[s.Cylinder=3]="Cylinder",s[s.RoundedCube=10]="RoundedCube",s))(ja||{});class po{static createText(e,t){let i=null;const n=t?.font||EC(t?.familyFamily||null);n instanceof q.Font?i=this.#t(e,n,t):i==null&&(i=new c.BufferGeometry);const o=t?.color||16777215,r=new c.Mesh(i,t?.material??new c.MeshStandardMaterial({color:o}));return this.applyDefaultObjectOptions(r,t),n instanceof Promise?n.then(a=>{r.geometry=this.#t(e,a,t),t?.onGeometry&&t.onGeometry(r)}):t?.onGeometry&&t.onGeometry(r),r}static#t(e,t,i){const n=i?.depth||.1;return new q.TextGeometry(e,{font:t,size:1,depth:n,height:n,bevelEnabled:i?.bevel||!1,bevelThickness:.01,bevelOffset:.01,bevelSize:.01})}static createOccluder(e){const t=new c.MeshBasicMaterial({colorWrite:!1,depthWrite:!0,side:c.DoubleSide});return this.createPrimitive(e,{material:t})}static createPrimitive(e,t){let i;const n=t?.color||16777215;switch(e){case"Quad":case 0:{const o=new c.PlaneGeometry(1,1,1,1),r=t?.material??new c.MeshStandardMaterial({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new c.Mesh(o,r),i.name="Quad"}break;case"Cube":case 1:{const o=new c.BoxGeometry(1,1,1),r=t?.material??new c.MeshStandardMaterial({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new c.Mesh(o,r),i.name="Cube"}break;case 10:case"RoundedCube":{const o=kC(1,1,1,.1,2),r=t?.material??new c.MeshStandardMaterial({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new c.Mesh(o,r),i.name="RoundedCube"}break;case"Sphere":case 2:{const o=new c.SphereGeometry(.5,16,16),r=t?.material??new c.MeshStandardMaterial({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new c.Mesh(o,r),i.name="Sphere"}break;case"Cylinder":case 3:{const o=new c.CylinderGeometry(.5,.5,1,32),r=t?.material??new c.MeshStandardMaterial({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new c.Mesh(o,r),i.name="Cylinder"}break;case"ShaderBall":i=new c.Group,i.name="ShaderBall",RC(i,t);break}return this.applyDefaultObjectOptions(i,t),i}static createSprite(e){const i=new c.SpriteMaterial({color:16777215});e?.texture&&"map"in i&&(i.map=e.texture);const n=new c.Sprite(i);return this.applyDefaultObjectOptions(n,e),n}static applyDefaultObjectOptions(e,t){e.receiveShadow=!0,e.castShadow=!0,t?.name&&(e.name=t.name),t?.position&&(Array.isArray(t.position)?e.position.set(t.position[0],t.position[1],t.position[2]):e.position.set(t.position.x||0,t.position.y||0,t.position.z||0)),t?.rotation&&(Array.isArray(t.rotation)?e.rotation.set(t.rotation[0],t.rotation[1],t.rotation[2]):e.rotation.set(t.rotation.x||0,t.rotation.y||0,t.rotation.z||0)),t?.scale&&(typeof t.scale=="number"?e.scale.set(t.scale,t.scale,t.scale):Array.isArray(t.scale)?e.scale.set(t.scale[0],t.scale[1],t.scale[2]):e.scale.set(t.scale.x||1,t.scale.y||1,t.scale.z||1)),t?.receiveShadow!=null&&(e.receiveShadow=t.receiveShadow),t?.castShadow!=null&&(e.castShadow=t.castShadow),t?.parent&&t.parent.add(e)}}function kC(s,e,t,i,n){const o=new c.Shape,r=1e-5,a=i-r;o.absarc(r,r,r,-Math.PI/2,-Math.PI,!0),o.absarc(r,e-a*2,r,Math.PI,Math.PI/2,!0),o.absarc(s-a*2,e-a*2,r,Math.PI/2,0,!0),o.absarc(s-a*2,r,r,0,-Math.PI/2,!0);const l=new c.ExtrudeGeometry(o,{bevelEnabled:!0,bevelSegments:n*2,steps:1,bevelSize:a,bevelThickness:i,curveSegments:n,UVGenerator:{generateTopUV:(h,d)=>{const u=[];for(let p=0;p<d.length;p+=3)u.push(new c.Vector2(d[p]/s,d[p+1]/e));return u},generateSideWallUV:(h,d,u,p,m,g)=>{const _=[];return _.push(new c.Vector2(d[u]/s,d[u+1]/e)),_.push(new c.Vector2(d[p]/s,d[p+1]/e)),_.push(new c.Vector2(d[m]/s,d[m+1]/e)),_.push(new c.Vector2(d[g]/s,d[g+1]/e)),_}}});return l.scale(1,1,1-i),l.center(),l.index||l.setIndex(Array.from({length:l.attributes.position.count},(h,d)=>d)),l.computeVertexNormals(),l}const Ah=new Map;function EC(s){let e="";switch(s){default:case"OpenSans":e="https://cdn.needle.tools/static/fonts/facetype/Open Sans_Regular_ascii.json";break;case"Helvetiker":e="https://raw.githubusercontent.com/mrdoob/three.js/master/examples/fonts/helvetiker_regular.typeface.json";break}if(Ah.has(e)){const n=Ah.get(e);if(n)return n}const t=new q.FontLoader,i=new Promise((n,o)=>{t.load(e,r=>{Ah.set(e,r),n(r)},void 0,o)});return Ah.set(e,i),i}let _f=!1,bf=null;function RC(s,e){if(bf===null){const t="https://cdn.needle.tools/static/models/shaderball.glb",i=new q.GLTFLoader,n=se.createLoaders(null);i.setDRACOLoader(n.dracoLoader),i.setKTX2Loader(n.ktx2Loader),_f=!0,bf=i.loadAsync(t).then(o=>{const r=o.scene;return r.position.y-=.5,r}).catch(o=>(console.warn("Failed to load shaderball mesh: "+o.message),o_())).finally(()=>{_f=!1})}if(_f){const t=o_();t.name="ShaderBall-Placeholder";const i=t.children[0];i?.type==="Mesh"&&s_(i,e),s.add(t)}bf.then(t=>{s.children.forEach(o=>{o.name==="ShaderBall-Placeholder"&&s.remove(o)});const i=t.clone(),n=i.children[0];n?.type==="Mesh"&&(n.geometry.attributes.tangent||n.geometry.computeTangents(),s_(n,e)),s.add(i)})}function s_(s,e){if(e?.color||e?.material||e?.texture){const i=e?.material??s.material?.clone()??new c.MeshStandardMaterial;e.color&&"color"in i&&i.color instanceof c.Color&&i.color.set(e.color),e?.texture&&"map"in i&&(i.map=e.texture),s.material=i}}function o_(){return new c.Group().add(po.createPrimitive("Sphere",{material:new c.MeshBasicMaterial({transparent:!0,opacity:.1})}))}class ka{static _active=null;static get active(){return this._active}static _requestInFlight=!1;static async start(e,t){if(this._active)return console.error("Cannot start a new XR session while one is already active"),null;if(this._requestInFlight)return console.error("Cannot start a new XR session while a request is already in flight"),null;if("xr"in navigator&&navigator.xr){if(!t)return console.error("XRSessionInit must be provided"),null;this._requestInFlight=!0;const i=await navigator.xr.requestSession(e,t).catch(n=>{console.error("Failed to start temporary XR session:",n)});return i?(i.addEventListener("end",()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new ka(e,t,i),this._active):(i.end(),null)):(this._requestInFlight=!1,null)}return null}static async handoff(){return this._active?this._active.handoff():null}static async stop(){this._requestInFlight=!1,this._active&&(await this._active.end(),await fs(100)),this._active=null}_session;_mode;_init;get isAR(){return this._mode==="immersive-ar"}get isVR(){return this._mode==="immersive-vr"}_renderer;_camera;_scene;constructor(e,t,i){this._mode=e,this._init=t,this._session=i,this._session.addEventListener("end",this.onEnd),this._renderer=new c.WebGLRenderer({alpha:!0,antialias:!0}),this._renderer.outputColorSpace="srgb",this._renderer.setPixelRatio(Math.min(2,window.devicePixelRatio)),this._renderer.setSize(window.innerWidth,window.innerHeight,!0),exports.DeviceUtilities.isNeedleAppClip()&&window.requestAnimationFrame(()=>{const n=Math.min(2,window.devicePixelRatio),o=Math.floor(window.innerWidth*n),r=Math.floor(window.innerHeight*n);this._renderer.domElement.width=o,this._renderer.domElement.height=r}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(i),this._renderer.xr.enabled=!0,this._camera=new c.PerspectiveCamera,this._scene=new c.Scene,this._scene.fog=new c.Fog(4473924,10,250),this._scene.add(this._camera),this.setupScene()}end(){return this._session?this._session.end():Promise.resolve()}async handoff(){if(!this._session)throw new Error("Cannot handoff a session that has already ended");const e={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,e}onEnd=()=>{this._session?.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()};_lastTime=0;_frames=0;onFrame=(e,t)=>{const i=e-this._lastTime;this.update(e,i),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera),this._lastTime=e,this._frames++};_roomFlyObjects=[];_logoObject=null;get _logoDistance(){return this.isAR?.3:5}get _logoScale(){return this.isAR?.04:1}update(e,t){const i=e*4e-4;for(let r=0;r<this._roomFlyObjects.length;r++){const a=this._roomFlyObjects[r];a.position.y+=Math.sin(i+r*.5)*.005,a.rotateY(.002)}const n=this._logoObject,o=this._renderer.xr.getCamera();if(n){const r=new c.Vector3;o.getWorldDirection(r);const a=o.position.clone().addScaledVector(r,this._logoDistance),l=this.isAR?.005:1e-5;n.position.lerp(a,this._frames<=2?1:t*l),n.lookAt(this._camera.position)}}async onBeforeHandoff(){await fs(1e3),this._scene.clear()}setupScene(){this._scene.background=new c.Color(0);let e=Oa;if(Fn()){const d=document.querySelector("needle-engine");if(d){const u=d.getAttribute("logo-src");u?.length&&(e=u,T()&&console.debug("[XR] Using custom loading logo from license:",e))}}const t=this._logoObject=new c.Mesh(new c.PlaneGeometry(1,1,1,1),new c.MeshBasicMaterial({transparent:!0,side:2}));t.scale.multiplyScalar(this._logoScale*window.devicePixelRatio),t.renderOrder=1e3,t.material.opacity=0,this._scene.add(t);const i=document.createElement("canvas"),n=i.getContext("2d"),o=new Image,r=d=>{if(!n)return;t.material.opacity=1;const u=1024;i.width=u,i.height=u,n.imageSmoothingQuality="high";const p=u*.19,m=o.width/o.height;{const w=i.height-p*1.5,R=w*m,M=(i.width-R)/2;n.drawImage(o,M,0,R,w)}const g=u*.12,_="Loading...";n.shadowBlur=0,n.fillStyle=this.isAR?"white":"rgba(255,255,255,0.4)",n.font=`${g}px Arial`,n.shadowBlur=u*.02,n.shadowColor="rgba(0,0,0,0.5)",n.shadowOffsetX=0,n.shadowOffsetY=0;const y=n.measureText(_);n.fillText(_,i.width/2-y.width/2,i.height-p/4),n.font=`${g}px Arial`,n.fillText(_,i.width/2-y.width/2,i.height-p/4);const v=new c.TextureLoader().load(i.toDataURL());v.generateMipmaps=!0,v.colorSpace="srgb",v.anisotropy=4;const b=i.width/i.height;t.scale.x=this._logoScale*b*window.devicePixelRatio,t.scale.y=this._logoScale*window.devicePixelRatio,t.material.map=v,t.material.needsUpdate=!0};o.onload=()=>r(),o.onerror=d=>{console.error("Failed to load temporary XR logo:",e,d),o.src=Oa},o.crossOrigin="anonymous",o.src=e;const a=new c.DirectionalLight(16777215,1);a.position.set(0,20,0),a.castShadow=!1,this._scene.add(a);const l=new c.DirectionalLight(16777215,1);l.position.set(0,-1,0),l.castShadow=!1,this._scene.add(l);const h=new c.PointLight(16777215,1,100,1);if(h.position.set(0,2,0),h.castShadow=!1,h.distance=200,this._scene.add(h),this.isAR===!1)for(let u=0;u<100;u++){const p=new c.MeshStandardMaterial({color:2236962,metalness:1,roughness:.8}),m=ja.Sphere,g=po.createPrimitive(m,{material:p});g.position.x=I.random(-50,50),g.position.y=I.random(-2,50),g.position.z=I.random(-50,50),g.rotation.x=I.random(0,Math.PI*2),g.rotation.y=I.random(0,Math.PI*2),g.rotation.z=I.random(0,Math.PI*2),g.scale.multiplyScalar(.5+Math.random()*10);const _=g.position.distanceTo(this._camera.position)-g.scale.x;_<10&&(g.position.z+=5,g.position.multiplyScalar(1+1/_)),this._roomFlyObjects.push(g),this._scene.add(g)}}}var pc;(s=>{const e=[];function t(){e?.length||T()&&console.warn("No USDZ exporters found – cannot export USDZ for QuickLook.");for(const o of e)o.exportAndOpen();return!0}s.exportAndOpen=t;function i(o){e.push(o)}s.registerExporter=i;function n(o){if(!e)return;const r=e.indexOf(o);r>=0&&e.splice(r,1)}s.unregisterExporter=n})(pc||(pc={}));const je=x("debugwebxr"),r_=x("stats");let vf=0;function TC(s){let e=null;const t=s;return t.getAROverlayContainer?e=t.getAROverlayContainer():e=s,e}AC();async function AC(){let s="immersive-vr";try{if(exports.DeviceUtilities.isNeedleAppClip()?s="immersive-ar":await navigator.xr?.isSessionSupported("immersive-vr")||(s="immersive-ar"),!await navigator.xr?.isSessionSupported("immersive-ar")&&s==="immersive-ar")return}catch(e){console.debug("[NeedleXRSession:granted] Error while checking XR support:",e);return}if(x("debugasap")){let e=globalThis["needle:XRSession"];if(e instanceof Promise){delete globalThis["needle:XRSession"],le.addContextCreatedCallback(async t=>{if(!e)return;fa(!0);const i=await e;if(i){const n=G.getDefaultSessionInit(s);G.setSession(s,i,n,t.context)}else console.error("[NeedleXRSession:granted] ASAP session was rejected");e=void 0});return}}if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent)){console.warn("WebXRViewer does not support addEventListener");return}navigator.xr?.addEventListener("sessiongranted",async()=>{const e=sessionStorage.getItem("needle_xr_session_mode"),t=sessionStorage.getItem("needle_xr_session_init")??null,i=t?JSON.parse(t):null;let n=null;if(kv()&&(await ka.start(e||s,i||G.getDefaultSessionInit(s)).catch(o=>console.warn("[NeedleXRSession:granted] TemporaryXRContext start failed:",o)),await IC(),n=await ka.handoff()),n)G.setSession(n.mode,n.session,n.init,U.Current);else if(e&&t){console.log("[NeedleXRSession:granted] Restore last session");const o=JSON.parse(t);G.start(e,o).catch(r=>console.warn(r))}else G.start(s).catch(o=>console.warn("[NeedleXRSession:granted] failed:",o))},{once:!0})}}function DC(s,e){sessionStorage.setItem("needle_xr_session_mode",s),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(e))}function LC(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const Fm=new Set;le.registerCallback(ae.ContextCreationStart,async s=>{Fm.add(s.context)});le.registerCallback(ae.ContextCreated,async s=>{Fm.delete(s.context);const e=s.context?.domElement.getAttribute("autostart")||null;jC(e)});function kv(){return Fm.size>0}function IC(){return new Promise(s=>{const e=Date.now(),t=setInterval(()=>{(!kv()||Date.now()-e>6e4)&&(clearInterval(t),s())},100)})}exports.DeviceUtilities.isDesktop()&&T()&&window.addEventListener("keydown",s=>{(s.key==="x"||s.key==="Escape")&&G.active&&G.stop()});function jC(s){s&&s?.toLowerCase()==="ar"&&hn.registerWaitForInteraction(()=>{G.start("ar")})}const Dh=Symbol("initial-fov");class G{static _sync=null;static getXRSync(e){return this._sync||(this._sync=new Ov(e)),this._sync}static get currentSessionRequest(){return this._currentSessionRequestMode}static _currentSessionRequestMode=null;static get active(){return this._activeSession}static get activeMode(){return this._activeSession?.mode??null}static get xrSystem(){return"xr"in navigator?navigator.xr:void 0}static isXRSupported(){return Promise.all([this.isVRSupported(),this.isARSupported()]).then(e=>e.some(t=>t)).catch(()=>!1)}static isVRSupported(){return this.isSessionSupported("immersive-vr")}static isARSupported(){return this.isSessionSupported("immersive-ar")}static isSessionSupported(e){return this.xrSystem?.isSessionSupported(e).catch(t=>(je&&console.error(t),!1))??Promise.resolve(!1)}static _currentSessionRequest;static _activeSession;static onSessionRequestStart(e){this._sessionRequestStartListeners.push(e)}static offSessionRequestStart(e){const t=this._sessionRequestStartListeners.indexOf(e);t>=0&&this._sessionRequestStartListeners.splice(t,1)}static _sessionRequestStartListeners=[];static onSessionRequestEnd(e){this._sessionRequestEndListeners.push(e)}static offSessionRequestEnd(e){const t=this._sessionRequestEndListeners.indexOf(e);t>=0&&this._sessionRequestEndListeners.splice(t,1)}static _sessionRequestEndListeners=[];static onXRSessionStart(e){this._xrStartListeners.push(e)}static offXRSessionStart(e){const t=this._xrStartListeners.indexOf(e);t>=0&&this._xrStartListeners.splice(t,1)}static _xrStartListeners=[];static onXRSessionEnd(e){this._xrEndListeners.push(e)}static offXRSessionEnd(e){const t=this._xrEndListeners.indexOf(e);t>=0&&this._xrEndListeners.splice(t,1)}static _xrEndListeners=[];static onControllerAdded(e){this._controllerAddedListeners.push(e)}static offControllerAdded(e){const t=this._controllerAddedListeners.indexOf(e);t>=0&&this._controllerAddedListeners.splice(t,1)}static _controllerAddedListeners=[];static onControllerRemoved(e){this._controllerRemovedListeners.push(e)}static offControllerRemoved(e){const t=this._controllerRemovedListeners.indexOf(e);t>=0&&this._controllerRemovedListeners.splice(t,1)}static _controllerRemovedListeners=[];static offerSession(e,t,i){return"xr"in navigator&&navigator.xr&&"offerSession"in navigator.xr?(typeof navigator.xr.offerSession=="function"&&(console.log("WebXR offerSession is available - requesting mode: "+e),t=="default"&&(t=this.getDefaultSessionInit(e)),navigator.xr.offerSession(e,{...t}).then(n=>G.setSession(e,n,t,i)).catch(n=>{console.log("XRSession offer rejected (perhaps because another call to offerSession was made or a call to requestSession was made)")})),!0):!1}static getDefaultSessionInit(e){switch(e){case"immersive-ar":const t=["anchors","local-floor","layers","dom-overlay","hit-test","unbounded"];return exports.DeviceUtilities.isVisionOS()||t.push("hand-tracking"),{optionalFeatures:t};case"immersive-vr":const i=["local-floor","bounded-floor","high-fixed-foveation-level","layers"];return exports.DeviceUtilities.isVisionOS()||i.push("hand-tracking"),{optionalFeatures:i};default:return console.warn("No default session init for mode",e),{}}}static async start(e,t,i){if(t||(t={}),exports.DeviceUtilities.isiOS()){const a=await this.isARSupported().catch(()=>!1);if(exports.DeviceUtilities.isVisionOS()&&!a&&(e==="ar"||e==="immersive-ar")&&(e="quicklook"),e==="quicklook")return ei.sendEvent(U.Current,"xr",{action:"quicklook_export",source:"NeedleXRSession.start"}),pc.exportAndOpen(),null;if(!a&&(e==="immersive-ar"||e==="ar")){this.invokeSessionRequestStart("immersive-ar",t);const l=new URL("https://appclip.apple.com/id?p=tools.needle.launch-app.Clip");l.searchParams.set("url",location.href);const h=l.toString();ei.sendEvent(U.Current,"xr",{action:"app_clip_launch",source:"NeedleXRSession.start",url:h});const d=window.top||window;try{console.debug("iOS device detected - opening Needle App Clip for AR experience",{mode:e,init:t,url:l}),d.location.href=h}catch(u){console.warn("Error navigating to AppClip "+h+`
|
|
167
167
|
`,u),window!==window.top?window.open(h,"_blank"):window.location.href=h}return setTimeout(()=>{this.invokeSessionRequestEnd("immersive-ar",t||{},null)},3e3),null}}if(e==="quicklook")return console.warn("QuickLook mode is only supported on iOS devices"),null;if(e=="ar"&&(e="immersive-ar"),T()&&x("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await ka.start(e,t||G.getDefaultSessionInit(e)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(je||T())&&ue("A XRSession is already being requested"),this._currentSessionRequest.then(()=>this._activeSession);if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;if(i||(i=U.Current),i||(i=le.All[0]),!i)throw new Error("No Needle Engine Context found");switch(e){case"immersive-ar":{if(await this.xrSystem?.isSessionSupported("immersive-ar")!==!0)return console.error(e+" is not supported by this browser."),null;const l=this.getDefaultSessionInit(e),h=TC(i.domElement);h&&!exports.DeviceUtilities.isQuest()&&(l.domOverlay={root:h},l.optionalFeatures.push("dom-overlay")),t={...l,...t}}break;case"immersive-vr":{if(await this.xrSystem?.isSessionSupported("immersive-vr")!==!0)return console.error(e+" is not supported by this browser."),null;t={...this.getDefaultSessionInit(e),...t}}break;default:console.warn("No default session init for mode",e);break}t.optionalFeatures??=[],t.requiredFeatures??=[],await ka.stop();const n=e=="immersive-ar"?i.scripts_immersive_ar:i.scripts_immersive_vr;je?console.log(`%cRequesting ${e} session`,"font-weight:bold;",t,n):console.log(`%cRequesting ${e} session`,"font-weight:bold;");for(const a of n)a.onBeforeXR&&a.activeAndEnabled&&!a.destroyed&&a.onBeforeXR(e,t);this.invokeSessionRequestStart(e,t),je&&we("Requesting "+e+" session ("+Date.now()+")"),ei.sendEvent(U.Current,"xr",{action:"session_request",mode:e,features:(t.requiredFeatures??[]).concat(t.optionalFeatures??[]).join(","),source:"NeedleXRSession.start"}),this._currentSessionRequest=navigator?.xr?.requestSession(e,t),this._currentSessionRequestMode=e;const o=await this._currentSessionRequest?.catch(a=>{console.error(a,"Code: "+a?.code),a?.code===9&&ue("Couldn't start XR session. Make sure you allow the required permissions."),console.log("If the specified XR configuration is not supported (e.g. entering AR doesnt work) - make sure you access the website on a secure connection (HTTPS) and your device has the required permissions (e.g. camera access)"),location.protocol==="http:"&&ue("XR requires a secure connection (HTTPS)")});return this._currentSessionRequest=void 0,this._currentSessionRequestMode=null,this.invokeSessionRequestEnd(e,t,o),o?this.setSession(e,o,t,i):(console.warn("XR Session request was rejected"),null)}static invokeSessionRequestStart(e,t){for(const i of this._sessionRequestStartListeners)i({mode:e,init:t})}static invokeSessionRequestEnd(e,t,i){for(const n of this._sessionRequestEndListeners)n({mode:e,init:t,newSession:i||null})}static setSession(e,t,i,n){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const o=e=="immersive-ar"?n.scripts_immersive_ar:n.scripts_immersive_vr;return this._activeSession=new G(e,t,n,{scripts:o,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:i}),t.addEventListener("end",this.onEnd),je?console.log(`%cStarted ${e} session`,"font-weight:bold;",o):console.log(`%cStarted ${e} session`,"font-weight:bold;"),this._activeSession}static $_stop_request=Symbol();static stop(){const e=this._activeSession;e&&(e[this.$_stop_request]===void 0?(je&&console.log("[NeedleXRSession] Stopping XR Session... (new)"),e[this.$_stop_request]=setTimeout(()=>{e.end()})):je&&console.warn("[NeedleXRSession] XR Session stop already requested"))}static onEnd=()=>{je&&console.log("XR Session ended"),this._activeSession=null};context;get sync(){return G._sync}get running(){return!this._ended&&this.session!=null}session;mode;get interactionMode(){return this.session.interactionMode}get visibilityState(){return this.session.visibilityState}get isVisibleBlurred(){return this.session.visibilityState==="visible-blurred"}get isSystemKeyboardSupported(){return this.session.isSystemKeyboardSupported}get environmentBlendMode(){return this.session.environmentBlendMode}get frame(){return this.context.xrFrame}controllers=[];get leftController(){return this.controllers.find(e=>e.side==="left")}get rightController(){return this.controllers.find(e=>e.side==="right")}getController(e){return typeof e=="number"?this.controllers[e]||null:this.controllers.find(t=>t.side===e)||null}get isPassThrough(){return!!(this.environmentBlendMode!=="opaque"&&this.interactionMode==="world-space"||this.mode==="immersive-ar"&&this.environmentBlendMode!=="opaque"&&this.controllers.some(e=>e.inputSource.targetRayMode==="tracked-pointer")||T()&&exports.DeviceUtilities.isDesktop()&&this.mode==="immersive-ar")}get isAR(){return this.mode==="immersive-ar"}get isVR(){return this.mode==="immersive-vr"}get isScreenBasedAR(){return this.isAR&&!this.isPassThrough}get posePosition(){return this._transformPosition}get poseOrientation(){return this._transformOrientation}get referenceSpace(){return this.context.renderer.xr.getReferenceSpace()}get viewerPose(){return this._viewerPose}get isTrackingImages(){if(this.frame&&"getImageTrackingResults"in this.frame&&typeof this.frame.getImageTrackingResults=="function")try{const e=this.frame.getImageTrackingResults();for(const t of e)if(t.trackingState==="tracked")return!0}catch{return!1}return!1}get rig(){const e=this._rigs[0]??null;return e?.gameObject&&ar(e.gameObject)||e?.isActive===!1?(this.updateActiveXRRig(),this._rigs[0]??null):e}_rigScale=1;_lastRigScaleUpdate=-1;get rigScale(){return this._rigs[0]?(this._lastRigScaleUpdate!==this.context.time.frame&&(this._lastRigScaleUpdate=this.context.time.frame,this._rigScale=this._rigs[0].gameObject.worldScale.x),this._rigScale):1}addRig(e){this._rigs.indexOf(e)>=0||(e.priority===void 0&&(e.priority=0),this._rigs.push(e),this.updateActiveXRRig())}removeRig(e){const t=this._rigs.indexOf(e);t!==-1&&(this._rigs.splice(t,1),this.updateActiveXRRig())}setRigActive(e){const t=this._rigs.indexOf(e),i=this._rigs[0];this._rigs.splice(t,1),this._rigs.unshift(e),e.priority=i?.priority??0,this.updateActiveXRRig()}getUserOffsetInRig(){const e=this.context.mainCamera?.position;if(!e||!this.rig)return B(0,0,0);const t=B(e);return t.x*=-1,t.z*=-1,t.applyQuaternion(Zt(this.rig.gameObject.quaternion)),t}updateActiveXRRig(){const e=this._rigs[0]??null;this._defaultRig.gameObject.parent!==this.context.scene&&this.context.scene.add(this._defaultRig.gameObject),this._defaultRig.gameObject.visible=!0,this._rigs.includes(this._defaultRig)||this._rigs.push(this._defaultRig);let t=this._rigs[0];t&&t.priority===void 0&&(t.priority=0);for(let i=1;i<this._rigs.length;i++){const n=this._rigs[i];if(n.isActive){if(ar(n.gameObject)){this._rigs.splice(i,1),i--;continue}(!t||t.isActive===!1||n.priority!==void 0&&n.priority>t.priority)&&(t=n)}}if(e!==t){const i=this._rigs.indexOf(t);i>=0&&this._rigs.splice(i,1),this._rigs.unshift(t)}je&&(e===t?console.log("Updated Active XR Rig:",t,"prev:",e):console.log("Updated Active XRRig:",t," (the same as before)"))}_rigs=[];_viewerHitTestSource=null;getHitTest(e){if(e)return this.getControllerHitTest(e);if(!this._viewerHitTestSource)return null;const t=this._viewerHitTestSource,i=this.frame.getHitTestResults(t);if(i.length>0){const n=i[0];return this.convertHitTestResult(n)}return null}getControllerHitTest(e){const t=e.getHitTestSource();if(!t)return null;const i=this.frame.getHitTestResultsForTransientInput(t);for(const n of i)if(n.inputSource===e.inputSource)for(const o of n.results)return this.convertHitTestResult(o);return null}convertHitTestResult(e){const t=this.context.renderer.xr.getReferenceSpace(),i=t&&e.getPose(t);if(i){const n=B(i.transform.position),o=Zt(i.transform.orientation),r=this.context.mainCamera;if(r?.parent!==this._cameraRenderParent&&n.applyMatrix4(pa),r?.parent){n.applyMatrix4(r.parent.matrixWorld),o.multiply(Ai);const a=fe(r.parent);a.premultiply(Ai),o.premultiply(a)}return{hit:e,position:n,quaternion:o}}return null}convertSpace(e){const t=B(e.position);t.applyMatrix4(pa);const i=Zt(e.orientation);return i.premultiply(Ai),{position:t,quaternion:i}}_defaultRig;_xr_scripts;_xr_update_scripts=[];_inactive_scripts=[];_controllerAdded;_controllerRemoved;_originalCameraWorldPosition;_originalCameraWorldRotation;_originalCameraWorldScale;_originalCameraParent;_mainCamera=null;constructor(e,t,i,n){DC(e,n.init),this.session=t,this.mode=e,this.context=i,(je||x("console"))&&fa(!0),this._xr_scripts=[...n.scripts],this._xr_update_scripts=this._xr_scripts.filter(o=>typeof o.onUpdateXR=="function"),this._controllerAdded=n.controller_added,this._controllerRemoved=n.controller_removed,gs(this.onBefore,me.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),(n.init.optionalFeatures?.includes("hit-test")||n.init.requiredFeatures?.includes("hit-test"))&&t.requestReferenceSpace("viewer").then(o=>t.requestHitTestSource?.call(t,{space:o})?.then(r=>this._viewerHitTestSource=r).catch(r=>console.error(r))).catch(o=>console.error(o)),this.context.mainCamera&&(this._originalCameraWorldPosition=Q(this.context.mainCamera,new c.Vector3),this._originalCameraWorldRotation=fe(this.context.mainCamera,new c.Quaternion),this._originalCameraWorldScale=Le(this.context.mainCamera,new c.Vector3),this._originalCameraParent=this.context.mainCamera.parent,this.context.mainCamera instanceof c.PerspectiveCamera&&(this.context.mainCamera[Dh]=this.context.mainCamera.fov)),this._defaultRig=new cC,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let o=0;o<t.inputSources.length;o++){const r=t.inputSources[o];if(!r.handedness){console.warn("Input source in xr session has no handedness - ignoring",o);continue}this.onInputSourceAdded(r)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",o=>{for(const r of o.removed)this.disconnectInputSource(r);for(const r of o.added)this.onInputSourceAdded(r)}),this.context.xr=this,this.context.renderer.xr.setSession(this.session).then(this.onRendererSessionSet),"controllerAutoUpdate"in this.context.renderer.xr?(console.debug("Disabling three.js controllerAutoUpdate"),this.context.renderer.xr.controllerAutoUpdate=!1):je&&console.warn("controllerAutoUpdate is not available in three.js - cannot disable it"),exports.DeviceUtilities.isNeedleAppClip()&&window.requestAnimationFrame(()=>{const o=this.context.renderer.domElement,r=window.devicePixelRatio||1,a=o.width,l=o.height,h=Math.floor(window.innerWidth*r),d=Math.floor(window.innerHeight*r);(Math.abs(a-h)>2||Math.abs(l-d)>2)&&(o.width=h,o.height=d,console.debug("Applied DPR scaling for Needle AppClip XR session",r,o.width,o.height))})}onRendererSessionSet=()=>{this.running&&(this.context.renderer.xr.enabled=!0,this.context.renderer.xr.updateCamera(this.context.mainCamera),this.context.mainCameraComponent?.applyClearFlags())};onInputSourceAdded=e=>{if(e.targetRayMode==="screen")return;let t=0;for(let n=0;n<this.session.inputSources.length;n++)if(this.session.inputSources[n]===e){t=n;break}if(this.controllers.find(n=>n.inputSource===e)){console.debug("Controller already exists for input source",t);return}else if(this._newControllers.find(n=>n.inputSource===e)){console.debug("Controller already registered for input source",t);return}const i=new Lm(this,e,t);this._newControllers.push(i)};disconnectInputSource(e){const t=(o,r)=>{if(o.inputSource===e){je&&console.log("Disconnecting controller",o.index);const a=r.indexOf(o);a>=0&&r.splice(a,1),this.invokeControllerEvent(o,this._controllerRemoved,"removed");const l={xr:this,controller:o,change:"removed"};for(const h of this._xr_scripts)h.onXRControllerRemoved&&h.onXRControllerRemoved(l);o.onDisconnected()}},i=[...this.controllers];for(let o=i.length-1;o>=0;o--){const r=i[o];t(r,this.controllers)}const n=[...this._newControllers];for(let o=n.length-1;o>=0;o--){const r=n[o];t(r,this._newControllers)}}end(){this._ended||this.session.end().catch(e=>console.warn(e))}_ended=!1;_newControllers=[];onEnd=e=>{if(this._ended)return;this._ended=!0,console.debug("XR Session ended"),ei.sendEvent(U.Current,"xr",{action:"session_end",mode:this.mode,source:"NeedleXRSession.onEnd"}),LC(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,this.requestedCameraNearPlane=null,fo(this.onBefore,me.LateUpdate);const t=this.context.pre_render_callbacks.indexOf(this.onBeforeRender);t>=0&&this.context.pre_render_callbacks.splice(t,1);const i=this.context.post_render_callbacks.indexOf(this.onAfterRender);i>=0&&this.context.post_render_callbacks.splice(i,1),this.context.xr=null,this.context.renderer.xr.enabled=!1,this.context.pre_update_oneshot_callbacks.push(()=>{this.context.mainCameraComponent?.applyClearFlags(),this.context.mainCameraComponent?.applyClippingPlane()}),yv({session:this});for(const o of G._xrEndListeners)o({xr:this});const n=[...this.controllers];for(let o=0;o<n.length;o++)this.disconnectInputSource(n[o].inputSource);this.controllers.length=0,this._newControllers.length=0;for(const o of this._xr_scripts)o?.onLeaveXR?.({xr:this});this.sync?.onExitXR(this),this.context.mainCamera&&(this._originalCameraParent?.add(this.context.mainCamera),this._originalCameraWorldPosition&&rt(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&ln(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&Sa(this.context.mainCamera,this._originalCameraWorldScale),this.context.mainCamera instanceof c.PerspectiveCamera&&this.context.mainCamera[Dh]&&(this.context.mainCamera.fov=this.context.mainCamera[Dh],this.context.mainCamera[Dh]=0)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),fa(!1)};_didStart=!1;onBefore=e=>{const t=e.xrFrame;if(!t)return;this.context.xr=this,this.context.mainCameraComponent&&this.context.mainCameraComponent!==this._mainCamera&&(this._mainCamera=this.context.mainCameraComponent),this.rig?.isActive==!1&&(je&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig&&this._mainCamera?.gameObject&&this._mainCamera?.gameObject?.parent!==this.rig.gameObject&&this.rig.gameObject.add(this._mainCamera?.gameObject),this.internalUpdateState(),this.applyCustomForward();const i={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const n=[...this.context.new_scripts_xr];for(let o=0;o<n.length;o++){const r=this.context.new_scripts_xr[o];if(!r||r.destroyed||r.supportsXR?.(this.mode)==!1){this.context.new_scripts_xr.splice(o,1);continue}if(!r.activeAndEnabled){this.context.new_scripts_xr.splice(o,1),this.markInactive(r);continue}if(this.addScript(r)){this.invokeCallback_EnterXR(r);for(const a of this.controllers)this.invokeCallback_ControllerAdded(r,a)}}}}else{if(this._didStart=!0,this.mode==="immersive-vr"){const o=Wt(this.context.scene.children);if(o){const r=o.getSize(B());if(r.length()>0){const a=this._defaultRig.gameObject;a.position.set(o.min.x+r.x*.5,o.min.y,o.max.z+r.z*.5+1.5);const l=o.getCenter(B());l.y=a.position.y,a.lookAt(l)}}}gv({session:this}),mr();for(const o of G._xrStartListeners)o(i);const n=[...this._xr_scripts];je&&console.log("NeedleXRSession start, handle scripts:",n);for(const o of n){if(o.destroyed){this._script_to_remove.push(o);continue}if(!o.activeAndEnabled){this.markInactive(o);continue}this.invokeCallback_EnterXR(o);for(const r of this.controllers)this.invokeCallback_ControllerAdded(o,r)}}this.syncCameraCullingMask();for(const n of this.controllers)n.onUpdate(t);if(this._newControllers.length>0){const n=[...this._newControllers];this._newControllers.length=0;for(const o of n){if(!o.connected){console.warn("New controller is not connected",o);continue}this.controllers.push(o);for(const r of this._xr_scripts){if(r.destroyed){this._script_to_remove.push(r);continue}r.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(r,o)}}this.controllers.sort((o,r)=>o.index-r.index)}je&&this.context.time.frame%30===0&&this.controllers.length<=0&&this.session.inputSources.length>0&&(fa(!0),console.error("XRControllers are not added but inputSources are present"));for(const n of this._xr_update_scripts){if(n.destroyed===!0){this._script_to_remove.push(n);continue}if(n.activeAndEnabled===!1){this.markInactive(n);continue}n.onUpdateXR&&n.onUpdateXR(i)}if(this.handleInactiveScripts(),this._script_to_remove.length>0){const n=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const o of n)!o.destroyed&&this.running&&o.onLeaveXR?.(i),this.removeScript(o)}this.sync?.onUpdate(this),this.onRenderDebug()};onRenderDebug(){if(je)for(const e of this.controllers)e.onRenderDebug();if((je||r_)&&this.rig&&(vf++,vf>=20)){const e=this.rig.gameObject.worldPosition,t=this.rig.gameObject.worldForward;e.add(t.multiplyScalar(1.5));const i=this.rig.gameObject.worldUp;e.add(i.multiplyScalar(2.5));let n="";if(n+=`${this.context.time.smoothedFps.toFixed(0)} FPS`,n+=`, calls: ${this.context.renderer.info.render.calls}, tris: ${this.context.renderer.info.render.triangles.toLocaleString()}`,je||r_)for(const o of this.controllers)n+=`
|
|
168
|
-
${o.hand?"hand":"ctrl"} ${o.inputSource.handedness}[${o.index}] con:${o.connected} tr:${o.isTracking} hts:${o.hasHitTestSource?"yes":"no"}`;vf=0,j.DrawLabel(e,n,void 0,1/60*20)}}onBeforeRender=()=>{this.context.mainCamera&&(this.updateFade(this.context.mainCamera),this.requestedCameraNearPlane!==null&&this.context.mainCamera instanceof c.PerspectiveCamera&&(this.context.mainCamera.near=this.requestedCameraNearPlane,this.requestedCameraNearPlane=null))};onAfterRender=()=>{if(this.onUpdateFade_PostRender(),exports.DeviceUtilities.isDesktop()||!this._renderOnceOnDevice){const e=this.context.renderer;if(e.xr.isPresenting&&this.context.mainCamera){this._renderOnceOnDevice=!0;const t=e.xr.enabled,i=e.getRenderTarget(),n=this.context.scene.background;e.xr.enabled=!1,e.setRenderTarget(null),this.isPassThrough&&(this.context.scene.background=null),this.context.composer?this.context.composer.render(this.context.time.deltaTime):e.render(this.context.scene,this.context.mainCamera),e.xr.enabled=t,e.setRenderTarget(i),this.context.scene.background=n}}};addScript(e){return this._xr_scripts.includes(e)?!1:(je&&console.log("Register new XRScript",e),this._xr_scripts.push(e),typeof e.onUpdateXR=="function"&&this._xr_update_scripts.push(e),!0)}markInactive(e){if(!(this._inactive_scripts.indexOf(e)>=0)){this.removeScript(e,!1),this._inactive_scripts.push(e);for(const t of this.controllers)this.invokeCallback_ControllerRemoved(e,t);this.invokeCallback_LeaveXR(e)}}handleInactiveScripts(){if(this._inactive_scripts.length>0)for(let e=this._inactive_scripts.length-1;e>=0;e--){const t=this._inactive_scripts[e];if(t.activeAndEnabled){this._inactive_scripts.splice(e,1),this.addScript(t),this.invokeCallback_EnterXR(t);for(const i of this.controllers)this.invokeCallback_ControllerAdded(t,i)}}}_script_to_remove=[];removeScript(e,t=!0){je&&console.log("Remove XRScript",e);const i=this._xr_scripts.indexOf(e);i>=0&&this._xr_scripts.splice(i,1);const n=this._xr_update_scripts.indexOf(e);if(n>=0&&this._xr_update_scripts.splice(n,1),t){const o=this._inactive_scripts.indexOf(e);o>=0&&this._inactive_scripts.splice(o,1)}}invokeCallback_EnterXR(e){e.onEnterXR&&e.onEnterXR({xr:this})}invokeCallback_ControllerAdded(e,t){e.onXRControllerAdded&&e.onXRControllerAdded({xr:this,controller:t,change:"added"})}invokeCallback_ControllerRemoved(e,t){e.onXRControllerRemoved&&e.onXRControllerRemoved({xr:this,controller:t,change:"removed"})}invokeCallback_LeaveXR(e){e.onLeaveXR&&!e.destroyed&&e.onLeaveXR({xr:this})}syncCameraCullingMask(){const e=this.context.xrCamera,t=this.context.mainCameraComponent?.cullingMask;if(e&&t!==void 0){for(const i of e.cameras)i.layers.mask=t;e.layers.mask=t}else if(e){for(const i of e.cameras)i.layers.enableAll();e.layers.enableAll()}}invokeControllerEvent(e,t,i){for(let n=t.length-1;n>=0;n--){const o=t[n];if(o)try{o({xr:this,controller:e,change:i})}catch(r){console.error(r)}}}_camera;_cameraRenderParent=new c.Object3D().rotateY(Math.PI);_previousCameraParent;_customforward=!0;originalCameraNearPlane;requestedCameraNearPlane=null;applyCustomForward(){if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,this._previousCameraParent?.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);{let e=.02;const t=.001;if(this.rig){const i=Le(this.rig.gameObject);e*=i.x}this._camera instanceof c.PerspectiveCamera&&Math.abs(this._camera.near-e)>t&&(this.isAR?this.originalCameraNearPlane=this._camera.near:this._camera.near=e,je&&console.debug(`Setting camera near plane to ${e} (was ${this.originalCameraNearPlane}) to account for XR rendering scale`))}}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof c.PerspectiveCamera&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane,this.originalCameraNearPlane=void 0)}_viewerPose;_transformOrientation=new c.Quaternion;_transformPosition=new c.Vector3;internalUpdateState(){const e=this.context.renderer.xr.getReferenceSpace();if(!e){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(e),this._viewerPose){const t=this._viewerPose.transform;this._transformPosition.set(t.position.x,t.position.y,t.position.z),this._transformOrientation.set(t.orientation.x,t.orientation.y,t.orientation.z,t.orientation.w)}}_transition;get transition(){return this._transition||(this._transition=new i_),this._transition}fadeTransition(){return this._transition||(this._transition=new i_),this._transition.fadeTransition()}updateFade(e){this._transition&&e instanceof c.PerspectiveCamera&&this._transition.update(e,this.context.time.deltaTime)}onUpdateFade_PostRender(){this._transition?.remove()}}const wf=x("debugwebxr");class Ev{static tryFindAvatarObjects(e,t,i){if(i.head&&i.leftHand&&i.rightHand)return;const n=e.name.toLocaleLowerCase();!i.head&&n.includes("head")&&(wf&&console.log("FOUND AVATAR HEAD",e.name),i.head=new K("",t,e)),n.includes("hand")&&(!i.leftHand&&n.includes("left")&&(wf&&console.log("FOUND AVATAR LEFT HAND",e.name),i.leftHand=new K("",t,e)),!i.rightHand&&n.includes("right")&&(wf&&console.log("FOUND AVATAR RIGHT HAND",e.name),i.rightHand=new K("",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 ee extends c.Color{alpha=1;get isRGBAColor(){return!0}set a(e){this.alpha=e}get a(){return this.alpha}constructor(e,t,i,n){super(),typeof e=="number"&&typeof t=="number"&&typeof i=="number"?(this.set(e,t,i),this.alpha=typeof n=="number"?n:1):e!==void 0&&(this.set(e),this.alpha=1)}clone(){const e=super.clone();return e.alpha=this.alpha,e}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,"alpha"in e&&typeof e.alpha=="number"?this.alpha=e.alpha:typeof e.a=="number"&&(this.alpha=e.a),this}lerp(e,t){const i=e;return i.alpha!=null&&(this.alpha=I.lerp(this.alpha,i.alpha,t)),super.lerp(e,t)}lerpColors(e,t,i){const n=e,o=t;return n.alpha!=null&&o.alpha!=null&&(this.alpha=I.lerp(n.alpha,o.alpha,i)),super.lerpColors(e,t,i)}multiply(e){const t=e;return t.alpha!=null&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}fromArray(e,t=0){return this.alpha=e[t+3],super.fromArray(e,t)}static fromColorRepresentation(e){if(typeof e=="string"){if(e.trim()==="transparent")return new ee(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 ee(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 ee(i/255,n/255,o/255,1)}else if(e.startsWith("rgba")){const t=e.slice(5,-1).split(",").map(Number);return new ee(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 ee(t[0]/255,t[1]/255,t[2]/255,1)}}else if(Array.isArray(e)){if(e.length===4)return new ee(e[0],e[1],e[2],e[3]);if(e.length===3)return new ee(e[0],e[1],e[2],1);console.error("Invalid color array length. Expected 3 or 4, got "+e.length)}return new ee(e)}}const St=new c.Vector3,a_=new c.Vector3,l_=new c.Quaternion,BC=x("debuggizmos"),Zi=8947848,xf=32;class j{constructor(){}static enabled=!0;static isGizmo(e){return e[Tp]!==void 0}static setVisible(e){for(const t of Oi.timedObjectsBuffer)t.visible=e}static DrawLabel(e,t,i=.05,n=0,o,r,a){if(!j.enabled)return null;o||(o=Zi);const l=G.active?.rigScale??1,h=Oi.getTextLabel(n,t,i*l,o,r);return a instanceof c.Object3D&&a.add(h),h.position.x=e.x,h.position.y=e.y,h.position.z=e.z,h}static DrawRay(e,t,i=Zi,n=0,o=!0){if(!j.enabled)return;const r=Oi.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),St.set(t.x,t.y,t.z).multiplyScalar(999999999),a.setXYZ(1,e.x+St.x,e.y+St.y,e.z+St.z),a.needsUpdate=!0,r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1,nn(r.material,i)}static DrawDirection(e,t,i=Zi,n=0,o=!0,r=1){if(!j.enabled)return;const a=Oi.getLine(n),l=a.geometry.getAttribute("position");l.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(St.set(0,0,-r),l_.set(t.x,t.y,t.z,t.w),St.applyQuaternion(l_)):(St.set(t.x,t.y,t.z),St.multiplyScalar(r)),l.setXYZ(1,e.x+St.x,e.y+St.y,e.z+St.z),l.needsUpdate=!0,a.material.depthTest=o,a.material.depthWrite=!1,nn(a.material,i)}static DrawLine(e,t,i=Zi,n=0,o=!0){if(!j.enabled)return;const r=Oi.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,nn(r.material,i)}static DrawCircle(e,t,i,n=Zi,o=0,r=!0){if(!j.enabled)return;const a=Oi.getCircle(o);a.position.set(e.x,e.y,e.z),a.scale.set(i,i,i),a.quaternion.setFromUnitVectors(this._up,St.set(t.x,t.y,t.z).normalize()),a.material.depthTest=r,a.material.depthWrite=!1,a.material.fog=!1,nn(a.material,n)}static DrawWireSphere(e,t,i=Zi,n=0,o=!0){if(!j.enabled)return;const r=Oi.getSphere(t,n,!0);rr(r,e.x,e.y,e.z),r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1,nn(r.material,i)}static DrawSphere(e,t,i=Zi,n=0,o=!0){if(!j.enabled)return;const r=Oi.getSphere(t,n,!1);rr(r,e.x,e.y,e.z),r.material.depthTest=o,r.material.depthWrite=!1,nn(r.material,i)}static DrawWireBox(e,t,i=Zi,n=0,o=!0,r=void 0){if(!j.enabled)return;const a=Oi.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,nn(a.material,i)}static DrawWireBox3(e,t=Zi,i=0,n=!0){if(!j.enabled)return;const o=Oi.getBox(i);o.position.copy(e.getCenter(St)),o.scale.copy(e.getSize(St)),o.material.depthTest=n,o.material.wireframe=!0,o.material.depthWrite=!1,o.material.fog=!1,nn(o.material,t)}static _up=new c.Vector3(0,1,0);static DrawArrow(e,t,i=Zi,n=0,o=!0,r=!1){if(!j.enabled)return;const a=Oi.getArrowHead(n);a.position.set(t.x,t.y,t.z),a.quaternion.setFromUnitVectors(this._up.set(0,1,0),St.set(t.x,t.y,t.z).sub(a_.set(e.x,e.y,e.z)).normalize());const h=St.set(t.x,t.y,t.z).sub(a_.set(e.x,e.y,e.z)).length()*.1;a.scale.set(h,h,h),a.material.depthTest=o,a.material.wireframe=r,nn(a.material,i),this.DrawLine(e,t,i,n,o)}static DrawWireMesh(e){const t=Oi.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,nn(t.material,e.color??Zi)}}const UC=new c.BoxGeometry(1,1,1);function zm(s=null){const e=new c.Color(s??14540253),t=new c.EdgesGeometry(UC);return new c.LineSegments(t,new c.LineBasicMaterial({color:e}))}function nn(s,e){if(Array.isArray(s)){for(const i of s)nn(i,e);return}const t=e instanceof ee?e.a:1;s.color.set(e),s.opacity=t,s.transparent=t<1}const Tp=Symbol("GizmoCache");class Oi{static familyName="needle-gizmos";static ensureFont(){let e=te.__webpack_exports__default.FontLibrary.getFontFamily(this.familyName);e||(e=te.__webpack_exports__default.FontLibrary.addFontFamily(this.familyName),e.addVariant("normal","normal","https://uploads.needle.tools/include/font-msdf.json","https://uploads.needle.tools/include/font.png")?.addEventListener("ready",()=>{te.__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),BC&&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 te.__webpack_exports__Text(l);const h=this,d=r;d.setText=function(u){this.set({textContent:u}),h.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(U.Current,r,e,this.textLabelCache),r}static getBox(e){let t=this.boxesCache.pop();if(!t){const i=new c.BoxGeometry(1,1,1);t=new c.Mesh(i)}return this.registerTimedObject(U.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new c.Line;let i=t.geometry.getAttribute("position");i||(i=new c.BufferAttribute(new Float32Array(6),3),t.geometry.setAttribute("position",i))}return t.frustumCulled=!1,this.registerTimedObject(U.Current,t,e,this.linesCache),t}static getCircle(e){let t=this.circlesCache.pop();if(!t){t=new c.Line;let i=t.geometry.getAttribute("position");if(!i){i=new c.BufferAttribute(new Float32Array(xf*3),3),t.geometry.setAttribute("position",i);const n=B(0,1,0),o=B(0,0,1),r=B(o);r.cross(n).normalize();const a=B(r),l=Math.PI*2/(xf-1);for(let h=0;h<xf+1;h++){const d=l*h;n.copy(a).multiplyScalar(Math.cos(d)*1),r.copy(o).multiplyScalar(Math.sin(d)*1);const u=n.add(r);i.setXYZ(h,u.x,u.y,u.z)}}}return t.frustumCulled=!1,this.registerTimedObject(U.Current,t,e,this.circlesCache),t}static getSphere(e,t,i){let n=this.spheresCache.pop();return n||(n=new c.Mesh(new c.SphereGeometry(1,8,8))),n.scale.set(e,e,e),n.material.wireframe=i,this.registerTimedObject(U.Current,n,t,this.spheresCache),n}static getArrowHead(e){let t=this.arrowHeadsCache.pop();return t||(t=new c.Mesh(new c.CylinderGeometry(0,.5,1,8))),this.registerTimedObject(U.Current,t,e,this.arrowHeadsCache),t}static getMesh(e){let t=this.mesh.pop();return t||(t=new c.Mesh,t.material=new c.MeshBasicMaterial),this.registerTimedObject(U.Current,t,e,this.mesh),t}static linesCache=[];static circlesCache=[];static spheresCache=[];static boxesCache=[];static arrowHeadsCache=[];static mesh=[];static textLabelCache=[];static registerTimedObject(e,t,i,n){if(!e){console.error("No Needle Engine context available. Did you call a Gizmos function in global scope?");return}const o=this.contextBeforeRenderCallbacks.get(e),r=this.contextPostRenderCallbacks.get(e);if(o){if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==o){const a=e.pre_render_callbacks.indexOf(o);a>=0&&e.pre_render_callbacks.splice(a,1),e.pre_render_callbacks.push(o)}}else{const a=()=>{this.onBeforeRender(e,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(e,a),e.pre_render_callbacks.push(a)}if(r){if(e.post_render_callbacks[e.post_render_callbacks.length-1]!==r){const a=e.post_render_callbacks.indexOf(r);a>=0&&e.post_render_callbacks.splice(a,1),e.post_render_callbacks.push(r)}}else{const a=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,a),e.post_render_callbacks.push(a)}t.traverse(a=>{a.layers.disableAll(),a.layers.enable(2)}),t.renderOrder=999999,t[Tp]=n,t.castShadow=!1,t.receiveShadow=!1,t.isGizmo=!0,this.timedObjectsBuffer.push(t),this.timesBuffer.push(U.Current.time.realtimeSinceStartup+i),e.scene.add(t)}static timedObjectsBuffer=new Array;static timesBuffer=new Array;static contextPostRenderCallbacks=new Map;static contextBeforeRenderCallbacks=new Map;static tmuiNeedsUpdate=!1;static onBeforeRender(e,t){this.tmuiNeedsUpdate&&(this.tmuiNeedsUpdate=!1,te.__webpack_exports__default.update());for(let i=0;i<t.length;i++){const n=t[i];if(e.mainCamera&&n instanceof te.__webpack_exports__default.MeshUIBaseElement){if(ar(n))continue;const o=e.isInVR,r=!1,a=!o;Lc(n,e.mainCamera,r,a)}}}static onPostRender(e,t,i){const n=e.time.realtimeSinceStartup;for(let o=t.length-1;o>=0;o--){const r=t[o];n>=i[o]-1e-6&&(t.splice(o,1),i.splice(o,1),r.removeFromParent(),ar(r)!=!0&&r[Tp].push(r))}}}const zt=x("debugphysics"),FC=x("debugworker"),c_=new c.Layers;class mo{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){c_.set(e),this.layerMask=c_}setMask(e){this.layerMask||(this.layerMask=new c.Layers);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}class Nm{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}}class Ea{static _raycasting=0;static get raycasting(){return this._raycasting>0}raycastPhysicsFast(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycast(e,t,{maxDistance:i,solid:n})??null}raycastPhysicsFastAndGetNormal(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycastAndGetNormal(e,t,{maxDistance:i,solid:n})??null}sphereOverlapPhysics(e,t){return this.context.physics.engine?.sphereOverlap(e,t)??null}context;engine;constructor(e){this.context=e}raycaster=new c.Raycaster;defaultRaycastOptions=new mo;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){zt&&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 zt&&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)),zt&&console.time("raycast"),o.length=0,Ea._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))),Ea._raycasting--,zt&&(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||j.isGizmo(o)||n.lineThreshold!==void 0&&n.lineThreshold<0&&o instanceof c.Line)continue;let r=!0;const a=o,l=a.geometry;if(o.raycastAllowed===!1&&(r=!1),r&&n.testObject){const h=n.testObject?.(o);if(h===!1)continue;h==="continue in children"&&(r=!1)}else r&&(l&&h_(l)||(r=!1));if(r){const h=i.length,d=o.raycastPreference||"lod";let u=d!=="bounds";if(n.precise===!1&&(u=!1),l&&(u||=l.getAttribute("position")?.array?.length<64),a instanceof q.GroundedSkybox&&(u=!1),d==="lod"){const p=se.getRaycastMesh(o);p&&(a.geometry=p)}if(!u&&NC(a,e,i)||(n.useAcceleratedRaycast!==!1?Td.runMeshBVHRaycast(e,a,i,this.context,n):e.intersectObject(a,!1,i)),a.geometry=l,zt&&i.length!=h){const p=i[i.length-1];j.DrawWireSphere(p.point,.1,7798784,1,!1),j.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)&&!j.isGizmo(e);h&&=e.visible,h&&=!(e instanceof c.Line),h&&=!(e instanceof q.GroundedSkybox);const d=e,u=d.geometry;if(h&&l){const p=l(e);if(p===!1)return;p==="continue in children"&&(h=!1)}if(u&&h_(u)||(h=!1),h){if(a){const p=this.sphere;p.center.copy(t),p.radius=i;const m=o.length;if(Td.runMeshBVHRaycast(this.sphere,d,o,this.context,{}),m!=o.length&&!r)return}else if(u.boundingBox||u.computeBoundingBox(),u.boundingBox){d.matrixWorldNeedsUpdate&&d.updateWorldMatrix(!1,!1);const p=this.tempBoundingBox.copy(u.boundingBox).applyMatrix4(d.matrixWorld),m=this.sphere;if(m.center.copy(t),m.radius=i,m.intersectsBox(p)){const g=Q(e),_=g.distanceTo(m.center),y=new Nm(e,_,g);if(o.push(y),!r)return}}}if(e.children)for(const p of e.children){const m=o.length;if(this.intersectSphere(p,t,i,n,o,r,a,l),m!=o.length&&!r)return}}}function h_(s){return!(s.index&&s.index.array.length<3)}const Ao=new c.Sphere,Lh=new c.Plane,zC=new c.Matrix3;function NC(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 q.GroundedSkybox){Lh.setFromNormalAndCoplanarPoint(B(0,1,0),B(0,-l.position.y,0)),Lh.applyMatrix4(l.matrixWorld,zC);const u=o.ray.intersectPlane(Lh,B());if(u){Ao.copy(h),Ao.applyMatrix4(l.matrixWorld);const m=B(u).sub(o.ray.origin).length(),g=Ao.radius*.5;m<g&&r.push({distance:m,point:u,object:l,normal:Lh.normal.clone()})}return}Ao.copy(h),Ao.applyMatrix4(l.matrixWorld);const d=o.ray.intersectSphere(Ao,B());if(d){const u=B(d).sub(o.ray.origin),p=u.length();if(p>Ao.radius){const m=u.clone().normalize();r.push({distance:p,point:d,object:l,normal:m})}}}}),s._computeIntersections=n,e.intersectObject(s,!1,t),s._computeIntersections=i,!0}var Td;(s=>{let e=0;function t(b,w,R,M,O){if(!w.geometry||!w.geometry.hasAttribute("position"))return!1;const A=w.geometry;if(w?.isSkinnedMesh){const D=w,L=D.bvhNeedsUpdate;if(!D.staticGenerator)l(),r&&(D.staticGenerator=new r(w),D.staticGenerator.applyWorldTransforms=!1,D.staticGeometry=D.staticGenerator.generate(),A.boundsTree=a?.call(D.staticGeometry),D.staticGeometryLastUpdate=performance.now()+Math.random()*200,D.bvhNeedsUpdate=!0);else if(A.boundsTree&&(D.autoUpdateMeshBvhInterval!==void 0&&D.autoUpdateMeshBvhInterval>=0||L===!0)){const N=performance.now(),$=N-D.staticGeometryLastUpdate,k=D.autoUpdateMeshBvhInterval??100;(L||$>k)&&(zt&&console.warn(`Physics: updating skinned mesh bvh for ${w.name} after ${$.toFixed(2)}ms`),D.bvhNeedsUpdate=!1,D.staticGeometryLastUpdate=N,D.staticGenerator?.generate(D.staticGeometry),A.boundsTree.refit())}}else if(!A.boundsTree){d||v();let D=!0;if((M.xr||A[g]===!1||A.getAttribute("position")?.isInterleavedBufferAttribute||A.index&&A.index?.isInterleavedBufferAttribute||e>10)&&(D=!1),D&&p){if(A[m]===void 0){let L=null;if(y.length>0){const N=y.shift();N&&!N.running&&(L=N)}if(!L&&_.length<3)try{FC&&console.warn("[GenerateMeshBVHWorker] Creating worker with import.meta.url:",typeof document>"u"?require("url").pathToFileURL(__filename).href:ua&&ua.tagName.toUpperCase()==="SCRIPT"&&ua.src||new URL("needle-engine.bundle-fbFZTOKP.umd.cjs",document.baseURI).href),L=new p,_.push(L)}catch(N){N instanceof DOMException&&N.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(N),e+=10):(console.error("Failed to create MeshBVH worker. Please see below for more details:"),console.log(N)),e++}if(L!=null&&!L.running){const N=w.name;zt&&console.log("<<<< worker start",N,L),A[m]="queued",performance.mark("bvh.create.start");const $=A.clone();try{L.generate($).then(k=>{A[m]="done",A.boundsTree=k}).catch(k=>{A[m]="failed - "+k?.message,A[g]=!1,zt&&console.error("Failed to generate mesh bvh on worker",k)}).finally(()=>{zt&&console.log(">>>>> worker done",N,{hasBoundsTre:A.boundsTree!=null}),y.push(L),$.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch(k){console.error("Failed to generate mesh bvh on worker",k)}}else zt&&console.warn("No worker available")}}else(!u||!D)&&(l(),o&&(performance.mark("bvh.create.start"),A.boundsTree=new o(A),performance.mark("bvh.create.end"),performance.measure("bvh.create","bvh.create.start","bvh.create.end")))}if(b instanceof c.Raycaster){const D=b,L=w.raycast;if(A.boundsTree)l(),n&&(w.acceleratedRaycast||(w.acceleratedRaycast=n.bind(w),zt&&console.debug(`Physics: bind acceleratedRaycast fn to "${w.name}"`)),w.raycast=w.acceleratedRaycast);else if(zt&&console.warn("No bounds tree found for mesh",w.name,{workerTask:A[m],hasAcceleratedRaycast:n!=null}),O.allowSlowRaycastFallback===!1&&(A.getAttribute("position")?.array?.length??0)>2e3)return zt&&console.warn("Skipping raycast because no bounds tree is available and allowSlowRaycastFallback is false"),!1;const N=D.firstHitOnly;return D.firstHitOnly=!1,D.intersectObject(w,!1,R),D.firstHitOnly=N,w.raycast=L,!0}else if(b instanceof c.Sphere){const D=A.boundsTree;if(D){const L=b;if(h.copy(w.matrixWorld).invert(),L.applyMatrix4(h),D.intersectsSphere(L)){const $=Q(w),k=$.distanceTo(L.center),z=new Nm(w,k,$);R.push(z)}}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-COVQl0b8.umd.cjs")).then(b=>b.index$1).then(b=>{n=b.acceleratedRaycast,o=b.MeshBVH,r=b.StaticGeometryGenerator,a=b.computeBoundsTree}).catch(b=>{(zt||T())&&console.error("Failed to load BVH library...",b.message)}))}const h=new c.Matrix4;let d=!1,u=!1,p=null;const m=Symbol("Needle:MeshBVH-Worker"),g=Symbol("Needle:MeshBVH-CanUseWorker"),_=[],y=[];function v(){d=!0,u=!0,Promise.resolve().then(()=>VT).then(b=>{p=b.GenerateMeshBVHWorker}).catch(b=>{zt||T()?console.warn("Failed to setup mesh bvh worker"):console.debug("Failed to setup mesh bvh worker",b)}).finally(()=>{u=!1})}})(Td||(Td={}));const d_=Symbol("gltf-loader-internal-usage-tracker"),VC=x("debugusers");class ga{get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(e){return ga._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(){ga._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[d_]=e._loadingId),r)),o},null}afterRoot(e){ga._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[d_],t instanceof c.Object3D&&(t.parent||t instanceof c.Mesh&&setTimeout(()=>{VC&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}}class Rv{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:
|
|
168
|
+
${o.hand?"hand":"ctrl"} ${o.inputSource.handedness}[${o.index}] con:${o.connected} tr:${o.isTracking} hts:${o.hasHitTestSource?"yes":"no"}`;vf=0,j.DrawLabel(e,n,void 0,1/60*20)}}onBeforeRender=()=>{this.context.mainCamera&&(this.updateFade(this.context.mainCamera),this.requestedCameraNearPlane!==null&&this.context.mainCamera instanceof c.PerspectiveCamera&&(this.context.mainCamera.near=this.requestedCameraNearPlane,this.requestedCameraNearPlane=null))};onAfterRender=()=>{if(this.onUpdateFade_PostRender(),exports.DeviceUtilities.isDesktop()||!this._renderOnceOnDevice){const e=this.context.renderer;if(e.xr.isPresenting&&this.context.mainCamera){this._renderOnceOnDevice=!0;const t=e.xr.enabled,i=e.getRenderTarget(),n=this.context.scene.background;e.xr.enabled=!1,e.setRenderTarget(null),this.isPassThrough&&(this.context.scene.background=null),this.context.composer?this.context.composer.render(this.context.time.deltaTime):e.render(this.context.scene,this.context.mainCamera),e.xr.enabled=t,e.setRenderTarget(i),this.context.scene.background=n}}};addScript(e){return this._xr_scripts.includes(e)?!1:(je&&console.log("Register new XRScript",e),this._xr_scripts.push(e),typeof e.onUpdateXR=="function"&&this._xr_update_scripts.push(e),!0)}markInactive(e){if(!(this._inactive_scripts.indexOf(e)>=0)){this.removeScript(e,!1),this._inactive_scripts.push(e);for(const t of this.controllers)this.invokeCallback_ControllerRemoved(e,t);this.invokeCallback_LeaveXR(e)}}handleInactiveScripts(){if(this._inactive_scripts.length>0)for(let e=this._inactive_scripts.length-1;e>=0;e--){const t=this._inactive_scripts[e];if(t.activeAndEnabled){this._inactive_scripts.splice(e,1),this.addScript(t),this.invokeCallback_EnterXR(t);for(const i of this.controllers)this.invokeCallback_ControllerAdded(t,i)}}}_script_to_remove=[];removeScript(e,t=!0){je&&console.log("Remove XRScript",e);const i=this._xr_scripts.indexOf(e);i>=0&&this._xr_scripts.splice(i,1);const n=this._xr_update_scripts.indexOf(e);if(n>=0&&this._xr_update_scripts.splice(n,1),t){const o=this._inactive_scripts.indexOf(e);o>=0&&this._inactive_scripts.splice(o,1)}}invokeCallback_EnterXR(e){e.onEnterXR&&e.onEnterXR({xr:this})}invokeCallback_ControllerAdded(e,t){e.onXRControllerAdded&&e.onXRControllerAdded({xr:this,controller:t,change:"added"})}invokeCallback_ControllerRemoved(e,t){e.onXRControllerRemoved&&e.onXRControllerRemoved({xr:this,controller:t,change:"removed"})}invokeCallback_LeaveXR(e){e.onLeaveXR&&!e.destroyed&&e.onLeaveXR({xr:this})}syncCameraCullingMask(){const e=this.context.xrCamera,t=this.context.mainCameraComponent?.cullingMask;if(e&&t!==void 0){for(const i of e.cameras)i.layers.mask=t;e.layers.mask=t}else if(e){for(const i of e.cameras)i.layers.enableAll();e.layers.enableAll()}}invokeControllerEvent(e,t,i){for(let n=t.length-1;n>=0;n--){const o=t[n];if(o)try{o({xr:this,controller:e,change:i})}catch(r){console.error(r)}}}_camera;_cameraRenderParent=new c.Object3D().rotateY(Math.PI);_previousCameraParent;_customforward=!0;originalCameraNearPlane;requestedCameraNearPlane=null;applyCustomForward(){if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,this._previousCameraParent?.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);{let e=.02;const t=.001;if(this.rig){const i=Le(this.rig.gameObject);e*=i.x}this._camera instanceof c.PerspectiveCamera&&Math.abs(this._camera.near-e)>t&&(this.isAR?this.originalCameraNearPlane=this._camera.near:this._camera.near=e,je&&console.debug(`Setting camera near plane to ${e} (was ${this.originalCameraNearPlane}) to account for XR rendering scale`))}}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof c.PerspectiveCamera&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane,this.originalCameraNearPlane=void 0)}_viewerPose;_transformOrientation=new c.Quaternion;_transformPosition=new c.Vector3;internalUpdateState(){const e=this.context.renderer.xr.getReferenceSpace();if(!e){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(e),this._viewerPose){const t=this._viewerPose.transform;this._transformPosition.set(t.position.x,t.position.y,t.position.z),this._transformOrientation.set(t.orientation.x,t.orientation.y,t.orientation.z,t.orientation.w)}}_transition;get transition(){return this._transition||(this._transition=new i_),this._transition}fadeTransition(){return this._transition||(this._transition=new i_),this._transition.fadeTransition()}updateFade(e){this._transition&&e instanceof c.PerspectiveCamera&&this._transition.update(e,this.context.time.deltaTime)}onUpdateFade_PostRender(){this._transition?.remove()}}const wf=x("debugwebxr");class Ev{static tryFindAvatarObjects(e,t,i){if(i.head&&i.leftHand&&i.rightHand)return;const n=e.name.toLocaleLowerCase();!i.head&&n.includes("head")&&(wf&&console.log("FOUND AVATAR HEAD",e.name),i.head=new K("",t,e)),n.includes("hand")&&(!i.leftHand&&n.includes("left")&&(wf&&console.log("FOUND AVATAR LEFT HAND",e.name),i.leftHand=new K("",t,e)),!i.rightHand&&n.includes("right")&&(wf&&console.log("FOUND AVATAR RIGHT HAND",e.name),i.rightHand=new K("",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 ee extends c.Color{alpha=1;get isRGBAColor(){return!0}set a(e){this.alpha=e}get a(){return this.alpha}constructor(e,t,i,n){super(),typeof e=="number"&&typeof t=="number"&&typeof i=="number"?(this.set(e,t,i),this.alpha=typeof n=="number"?n:1):e!==void 0&&(this.set(e),this.alpha=1)}clone(){const e=super.clone();return e.alpha=this.alpha,e}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,"alpha"in e&&typeof e.alpha=="number"?this.alpha=e.alpha:typeof e.a=="number"&&(this.alpha=e.a),this}lerp(e,t){const i=e;return i.alpha!=null&&(this.alpha=I.lerp(this.alpha,i.alpha,t)),super.lerp(e,t)}lerpColors(e,t,i){const n=e,o=t;return n.alpha!=null&&o.alpha!=null&&(this.alpha=I.lerp(n.alpha,o.alpha,i)),super.lerpColors(e,t,i)}multiply(e){const t=e;return t.alpha!=null&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}fromArray(e,t=0){return this.alpha=e[t+3],super.fromArray(e,t)}static fromColorRepresentation(e){if(typeof e=="string"){if(e.trim()==="transparent")return new ee(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 ee(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 ee(i/255,n/255,o/255,1)}else if(e.startsWith("rgba")){const t=e.slice(5,-1).split(",").map(Number);return new ee(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 ee(t[0]/255,t[1]/255,t[2]/255,1)}}else if(Array.isArray(e)){if(e.length===4)return new ee(e[0],e[1],e[2],e[3]);if(e.length===3)return new ee(e[0],e[1],e[2],1);console.error("Invalid color array length. Expected 3 or 4, got "+e.length)}return new ee(e)}}const St=new c.Vector3,a_=new c.Vector3,l_=new c.Quaternion,BC=x("debuggizmos"),Zi=8947848,xf=32;class j{constructor(){}static enabled=!0;static isGizmo(e){return e[Tp]!==void 0}static setVisible(e){for(const t of Oi.timedObjectsBuffer)t.visible=e}static DrawLabel(e,t,i=.05,n=0,o,r,a){if(!j.enabled)return null;o||(o=Zi);const l=G.active?.rigScale??1,h=Oi.getTextLabel(n,t,i*l,o,r);return a instanceof c.Object3D&&a.add(h),h.position.x=e.x,h.position.y=e.y,h.position.z=e.z,h}static DrawRay(e,t,i=Zi,n=0,o=!0){if(!j.enabled)return;const r=Oi.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),St.set(t.x,t.y,t.z).multiplyScalar(999999999),a.setXYZ(1,e.x+St.x,e.y+St.y,e.z+St.z),a.needsUpdate=!0,r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1,nn(r.material,i)}static DrawDirection(e,t,i=Zi,n=0,o=!0,r=1){if(!j.enabled)return;const a=Oi.getLine(n),l=a.geometry.getAttribute("position");l.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(St.set(0,0,-r),l_.set(t.x,t.y,t.z,t.w),St.applyQuaternion(l_)):(St.set(t.x,t.y,t.z),St.multiplyScalar(r)),l.setXYZ(1,e.x+St.x,e.y+St.y,e.z+St.z),l.needsUpdate=!0,a.material.depthTest=o,a.material.depthWrite=!1,nn(a.material,i)}static DrawLine(e,t,i=Zi,n=0,o=!0){if(!j.enabled)return;const r=Oi.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,nn(r.material,i)}static DrawCircle(e,t,i,n=Zi,o=0,r=!0){if(!j.enabled)return;const a=Oi.getCircle(o);a.position.set(e.x,e.y,e.z),a.scale.set(i,i,i),a.quaternion.setFromUnitVectors(this._up,St.set(t.x,t.y,t.z).normalize()),a.material.depthTest=r,a.material.depthWrite=!1,a.material.fog=!1,nn(a.material,n)}static DrawWireSphere(e,t,i=Zi,n=0,o=!0){if(!j.enabled)return;const r=Oi.getSphere(t,n,!0);rr(r,e.x,e.y,e.z),r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1,nn(r.material,i)}static DrawSphere(e,t,i=Zi,n=0,o=!0){if(!j.enabled)return;const r=Oi.getSphere(t,n,!1);rr(r,e.x,e.y,e.z),r.material.depthTest=o,r.material.depthWrite=!1,nn(r.material,i)}static DrawWireBox(e,t,i=Zi,n=0,o=!0,r=void 0){if(!j.enabled)return;const a=Oi.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,nn(a.material,i)}static DrawWireBox3(e,t=Zi,i=0,n=!0){if(!j.enabled)return;const o=Oi.getBox(i);o.position.copy(e.getCenter(St)),o.scale.copy(e.getSize(St)),o.material.depthTest=n,o.material.wireframe=!0,o.material.depthWrite=!1,o.material.fog=!1,nn(o.material,t)}static _up=new c.Vector3(0,1,0);static DrawArrow(e,t,i=Zi,n=0,o=!0,r=!1){if(!j.enabled)return;const a=Oi.getArrowHead(n);a.position.set(t.x,t.y,t.z),a.quaternion.setFromUnitVectors(this._up.set(0,1,0),St.set(t.x,t.y,t.z).sub(a_.set(e.x,e.y,e.z)).normalize());const h=St.set(t.x,t.y,t.z).sub(a_.set(e.x,e.y,e.z)).length()*.1;a.scale.set(h,h,h),a.material.depthTest=o,a.material.wireframe=r,nn(a.material,i),this.DrawLine(e,t,i,n,o)}static DrawWireMesh(e){const t=Oi.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,nn(t.material,e.color??Zi)}}const UC=new c.BoxGeometry(1,1,1);function zm(s=null){const e=new c.Color(s??14540253),t=new c.EdgesGeometry(UC);return new c.LineSegments(t,new c.LineBasicMaterial({color:e}))}function nn(s,e){if(Array.isArray(s)){for(const i of s)nn(i,e);return}const t=e instanceof ee?e.a:1;s.color.set(e),s.opacity=t,s.transparent=t<1}const Tp=Symbol("GizmoCache");class Oi{static familyName="needle-gizmos";static ensureFont(){let e=te.__webpack_exports__default.FontLibrary.getFontFamily(this.familyName);e||(e=te.__webpack_exports__default.FontLibrary.addFontFamily(this.familyName),e.addVariant("normal","normal","https://uploads.needle.tools/include/font-msdf.json","https://uploads.needle.tools/include/font.png")?.addEventListener("ready",()=>{te.__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),BC&&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 te.__webpack_exports__Text(l);const h=this,d=r;d.setText=function(u){this.set({textContent:u}),h.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(U.Current,r,e,this.textLabelCache),r}static getBox(e){let t=this.boxesCache.pop();if(!t){const i=new c.BoxGeometry(1,1,1);t=new c.Mesh(i)}return this.registerTimedObject(U.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new c.Line;let i=t.geometry.getAttribute("position");i||(i=new c.BufferAttribute(new Float32Array(6),3),t.geometry.setAttribute("position",i))}return t.frustumCulled=!1,this.registerTimedObject(U.Current,t,e,this.linesCache),t}static getCircle(e){let t=this.circlesCache.pop();if(!t){t=new c.Line;let i=t.geometry.getAttribute("position");if(!i){i=new c.BufferAttribute(new Float32Array(xf*3),3),t.geometry.setAttribute("position",i);const n=B(0,1,0),o=B(0,0,1),r=B(o);r.cross(n).normalize();const a=B(r),l=Math.PI*2/(xf-1);for(let h=0;h<xf+1;h++){const d=l*h;n.copy(a).multiplyScalar(Math.cos(d)*1),r.copy(o).multiplyScalar(Math.sin(d)*1);const u=n.add(r);i.setXYZ(h,u.x,u.y,u.z)}}}return t.frustumCulled=!1,this.registerTimedObject(U.Current,t,e,this.circlesCache),t}static getSphere(e,t,i){let n=this.spheresCache.pop();return n||(n=new c.Mesh(new c.SphereGeometry(1,8,8))),n.scale.set(e,e,e),n.material.wireframe=i,this.registerTimedObject(U.Current,n,t,this.spheresCache),n}static getArrowHead(e){let t=this.arrowHeadsCache.pop();return t||(t=new c.Mesh(new c.CylinderGeometry(0,.5,1,8))),this.registerTimedObject(U.Current,t,e,this.arrowHeadsCache),t}static getMesh(e){let t=this.mesh.pop();return t||(t=new c.Mesh,t.material=new c.MeshBasicMaterial),this.registerTimedObject(U.Current,t,e,this.mesh),t}static linesCache=[];static circlesCache=[];static spheresCache=[];static boxesCache=[];static arrowHeadsCache=[];static mesh=[];static textLabelCache=[];static registerTimedObject(e,t,i,n){if(!e){console.error("No Needle Engine context available. Did you call a Gizmos function in global scope?");return}const o=this.contextBeforeRenderCallbacks.get(e),r=this.contextPostRenderCallbacks.get(e);if(o){if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==o){const a=e.pre_render_callbacks.indexOf(o);a>=0&&e.pre_render_callbacks.splice(a,1),e.pre_render_callbacks.push(o)}}else{const a=()=>{this.onBeforeRender(e,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(e,a),e.pre_render_callbacks.push(a)}if(r){if(e.post_render_callbacks[e.post_render_callbacks.length-1]!==r){const a=e.post_render_callbacks.indexOf(r);a>=0&&e.post_render_callbacks.splice(a,1),e.post_render_callbacks.push(r)}}else{const a=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,a),e.post_render_callbacks.push(a)}t.traverse(a=>{a.layers.disableAll(),a.layers.enable(2)}),t.renderOrder=999999,t[Tp]=n,t.castShadow=!1,t.receiveShadow=!1,t.isGizmo=!0,this.timedObjectsBuffer.push(t),this.timesBuffer.push(U.Current.time.realtimeSinceStartup+i),e.scene.add(t)}static timedObjectsBuffer=new Array;static timesBuffer=new Array;static contextPostRenderCallbacks=new Map;static contextBeforeRenderCallbacks=new Map;static tmuiNeedsUpdate=!1;static onBeforeRender(e,t){this.tmuiNeedsUpdate&&(this.tmuiNeedsUpdate=!1,te.__webpack_exports__default.update());for(let i=0;i<t.length;i++){const n=t[i];if(e.mainCamera&&n instanceof te.__webpack_exports__default.MeshUIBaseElement){if(ar(n))continue;const o=e.isInVR,r=!1,a=!o;Lc(n,e.mainCamera,r,a)}}}static onPostRender(e,t,i){const n=e.time.realtimeSinceStartup;for(let o=t.length-1;o>=0;o--){const r=t[o];n>=i[o]-1e-6&&(t.splice(o,1),i.splice(o,1),r.removeFromParent(),ar(r)!=!0&&r[Tp].push(r))}}}const zt=x("debugphysics"),FC=x("debugworker"),c_=new c.Layers;class mo{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){c_.set(e),this.layerMask=c_}setMask(e){this.layerMask||(this.layerMask=new c.Layers);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}class Nm{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}}class Ea{static _raycasting=0;static get raycasting(){return this._raycasting>0}raycastPhysicsFast(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycast(e,t,{maxDistance:i,solid:n})??null}raycastPhysicsFastAndGetNormal(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycastAndGetNormal(e,t,{maxDistance:i,solid:n})??null}sphereOverlapPhysics(e,t){return this.context.physics.engine?.sphereOverlap(e,t)??null}context;engine;constructor(e){this.context=e}raycaster=new c.Raycaster;defaultRaycastOptions=new mo;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){zt&&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 zt&&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)),zt&&console.time("raycast"),o.length=0,Ea._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))),Ea._raycasting--,zt&&(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||j.isGizmo(o)||n.lineThreshold!==void 0&&n.lineThreshold<0&&o instanceof c.Line)continue;let r=!0;const a=o,l=a.geometry;if(o.raycastAllowed===!1&&(r=!1),r&&n.testObject){const h=n.testObject?.(o);if(h===!1)continue;h==="continue in children"&&(r=!1)}else r&&(l&&h_(l)||(r=!1));if(r){const h=i.length,d=o.raycastPreference||"lod";let u=d!=="bounds";if(n.precise===!1&&(u=!1),l&&(u||=l.getAttribute("position")?.array?.length<64),a instanceof q.GroundedSkybox&&(u=!1),d==="lod"){const p=se.getRaycastMesh(o);p&&(a.geometry=p)}if(!u&&NC(a,e,i)||(n.useAcceleratedRaycast!==!1?Td.runMeshBVHRaycast(e,a,i,this.context,n):e.intersectObject(a,!1,i)),a.geometry=l,zt&&i.length!=h){const p=i[i.length-1];j.DrawWireSphere(p.point,.1,7798784,1,!1),j.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)&&!j.isGizmo(e);h&&=e.visible,h&&=!(e instanceof c.Line),h&&=!(e instanceof q.GroundedSkybox);const d=e,u=d.geometry;if(h&&l){const p=l(e);if(p===!1)return;p==="continue in children"&&(h=!1)}if(u&&h_(u)||(h=!1),h){if(a){const p=this.sphere;p.center.copy(t),p.radius=i;const m=o.length;if(Td.runMeshBVHRaycast(this.sphere,d,o,this.context,{}),m!=o.length&&!r)return}else if(u.boundingBox||u.computeBoundingBox(),u.boundingBox){d.matrixWorldNeedsUpdate&&d.updateWorldMatrix(!1,!1);const p=this.tempBoundingBox.copy(u.boundingBox).applyMatrix4(d.matrixWorld),m=this.sphere;if(m.center.copy(t),m.radius=i,m.intersectsBox(p)){const g=Q(e),_=g.distanceTo(m.center),y=new Nm(e,_,g);if(o.push(y),!r)return}}}if(e.children)for(const p of e.children){const m=o.length;if(this.intersectSphere(p,t,i,n,o,r,a,l),m!=o.length&&!r)return}}}function h_(s){return!(s.index&&s.index.array.length<3)}const Ao=new c.Sphere,Lh=new c.Plane,zC=new c.Matrix3;function NC(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 q.GroundedSkybox){Lh.setFromNormalAndCoplanarPoint(B(0,1,0),B(0,-l.position.y,0)),Lh.applyMatrix4(l.matrixWorld,zC);const u=o.ray.intersectPlane(Lh,B());if(u){Ao.copy(h),Ao.applyMatrix4(l.matrixWorld);const m=B(u).sub(o.ray.origin).length(),g=Ao.radius*.5;m<g&&r.push({distance:m,point:u,object:l,normal:Lh.normal.clone()})}return}Ao.copy(h),Ao.applyMatrix4(l.matrixWorld);const d=o.ray.intersectSphere(Ao,B());if(d){const u=B(d).sub(o.ray.origin),p=u.length();if(p>Ao.radius){const m=u.clone().normalize();r.push({distance:p,point:d,object:l,normal:m})}}}}),s._computeIntersections=n,e.intersectObject(s,!1,t),s._computeIntersections=i,!0}var Td;(s=>{let e=0;function t(b,w,R,M,O){if(!w.geometry||!w.geometry.hasAttribute("position"))return!1;const A=w.geometry;if(w?.isSkinnedMesh){const D=w,L=D.bvhNeedsUpdate;if(!D.staticGenerator)l(),r&&(D.staticGenerator=new r(w),D.staticGenerator.applyWorldTransforms=!1,D.staticGeometry=D.staticGenerator.generate(),A.boundsTree=a?.call(D.staticGeometry),D.staticGeometryLastUpdate=performance.now()+Math.random()*200,D.bvhNeedsUpdate=!0);else if(A.boundsTree&&(D.autoUpdateMeshBvhInterval!==void 0&&D.autoUpdateMeshBvhInterval>=0||L===!0)){const N=performance.now(),$=N-D.staticGeometryLastUpdate,k=D.autoUpdateMeshBvhInterval??100;(L||$>k)&&(zt&&console.warn(`Physics: updating skinned mesh bvh for ${w.name} after ${$.toFixed(2)}ms`),D.bvhNeedsUpdate=!1,D.staticGeometryLastUpdate=N,D.staticGenerator?.generate(D.staticGeometry),A.boundsTree.refit())}}else if(!A.boundsTree){d||v();let D=!0;if((M.xr||A[g]===!1||A.getAttribute("position")?.isInterleavedBufferAttribute||A.index&&A.index?.isInterleavedBufferAttribute||e>10)&&(D=!1),D&&p){if(A[m]===void 0){let L=null;if(y.length>0){const N=y.shift();N&&!N.running&&(L=N)}if(!L&&_.length<3)try{FC&&console.warn("[GenerateMeshBVHWorker] Creating worker with import.meta.url:",typeof document>"u"?require("url").pathToFileURL(__filename).href:ua&&ua.tagName.toUpperCase()==="SCRIPT"&&ua.src||new URL("needle-engine.bundle-Dqrh7aWw.umd.cjs",document.baseURI).href),L=new p,_.push(L)}catch(N){N instanceof DOMException&&N.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(N),e+=10):(console.error("Failed to create MeshBVH worker. Please see below for more details:"),console.log(N)),e++}if(L!=null&&!L.running){const N=w.name;zt&&console.log("<<<< worker start",N,L),A[m]="queued",performance.mark("bvh.create.start");const $=A.clone();try{L.generate($).then(k=>{A[m]="done",A.boundsTree=k}).catch(k=>{A[m]="failed - "+k?.message,A[g]=!1,zt&&console.error("Failed to generate mesh bvh on worker",k)}).finally(()=>{zt&&console.log(">>>>> worker done",N,{hasBoundsTre:A.boundsTree!=null}),y.push(L),$.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch(k){console.error("Failed to generate mesh bvh on worker",k)}}else zt&&console.warn("No worker available")}}else(!u||!D)&&(l(),o&&(performance.mark("bvh.create.start"),A.boundsTree=new o(A),performance.mark("bvh.create.end"),performance.measure("bvh.create","bvh.create.start","bvh.create.end")))}if(b instanceof c.Raycaster){const D=b,L=w.raycast;if(A.boundsTree)l(),n&&(w.acceleratedRaycast||(w.acceleratedRaycast=n.bind(w),zt&&console.debug(`Physics: bind acceleratedRaycast fn to "${w.name}"`)),w.raycast=w.acceleratedRaycast);else if(zt&&console.warn("No bounds tree found for mesh",w.name,{workerTask:A[m],hasAcceleratedRaycast:n!=null}),O.allowSlowRaycastFallback===!1&&(A.getAttribute("position")?.array?.length??0)>2e3)return zt&&console.warn("Skipping raycast because no bounds tree is available and allowSlowRaycastFallback is false"),!1;const N=D.firstHitOnly;return D.firstHitOnly=!1,D.intersectObject(w,!1,R),D.firstHitOnly=N,w.raycast=L,!0}else if(b instanceof c.Sphere){const D=A.boundsTree;if(D){const L=b;if(h.copy(w.matrixWorld).invert(),L.applyMatrix4(h),D.intersectsSphere(L)){const $=Q(w),k=$.distanceTo(L.center),z=new Nm(w,k,$);R.push(z)}}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-COVQl0b8.umd.cjs")).then(b=>b.index$1).then(b=>{n=b.acceleratedRaycast,o=b.MeshBVH,r=b.StaticGeometryGenerator,a=b.computeBoundsTree}).catch(b=>{(zt||T())&&console.error("Failed to load BVH library...",b.message)}))}const h=new c.Matrix4;let d=!1,u=!1,p=null;const m=Symbol("Needle:MeshBVH-Worker"),g=Symbol("Needle:MeshBVH-CanUseWorker"),_=[],y=[];function v(){d=!0,u=!0,Promise.resolve().then(()=>VT).then(b=>{p=b.GenerateMeshBVHWorker}).catch(b=>{zt||T()?console.warn("Failed to setup mesh bvh worker"):console.debug("Failed to setup mesh bvh worker",b)}).finally(()=>{u=!1})}})(Td||(Td={}));const d_=Symbol("gltf-loader-internal-usage-tracker"),VC=x("debugusers");class ga{get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(e){return ga._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(){ga._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[d_]=e._loadingId),r)),o},null}afterRoot(e){ga._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[d_],t instanceof c.Object3D&&(t.parent||t instanceof c.Mesh&&setTimeout(()=>{VC&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}}class Rv{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:
|
|
169
169
|
`+i.src),e.preventDefault())}})}}const ru=x("trackresources");function Tv(){return ru==="dispose"}let gr=!0;ru===0&&(gr=!1);function $C(s){gr=s}function Av(){return gr}const Dv=Symbol("disposable");function Lv(s,e){s&&(s[Dv]=e,Ko&&console.warn("Set disposable",e,s))}const Iv=Symbol("disposed");function WC(s){return s[Iv]===!0}function be(s){if(s){if(s[Dv]===!1){Ko&&console.warn("Object is marked as not disposable",s);return}if(typeof s=="object"&&(s[Iv]=!0),s instanceof c.Scene)be(s.environment),be(s.background),be(s.customDepthMaterial),be(s.customDistanceMaterial);else if(s instanceof c.SkinnedMesh)be(s.geometry),be(s.material),be(s.skeleton),be(s.bindMatrix),be(s.bindMatrixInverse),be(s.customDepthMaterial),be(s.customDistanceMaterial),s.visible=!1;else if(s instanceof c.Mesh)be(s.geometry),be(s.material),be(s.customDepthMaterial),be(s.customDistanceMaterial),s.visible=!1;else if(s instanceof c.Object3D)s.visible=!1;else if(s instanceof c.BufferGeometry){zr(s);for(const e of Object.keys(s.attributes)){const t=s.attributes[e];be(t)}}else if(s instanceof c.BufferAttribute||s instanceof c.InterleavedBufferAttribute)Ko&&console.warn("BufferAttribute dispose not supported",s.count);else if(s instanceof Array)for(const e of s)e instanceof c.Material&&be(e);else if(s instanceof c.Material){zr(s);for(const t of Object.keys(s)){const i=s[t];i instanceof c.Texture&&be(i)}const e=s.uniforms;if(e)for(const t of Object.keys(e)){const i=e[t];i instanceof c.Texture?be(i):i instanceof c.Uniform$1&&be(i.value)}}else s instanceof c.Texture?(zr(s),zr(s.source),s.source?.data instanceof ImageBitmap&&zr(s.source.data)):s instanceof c.Skeleton?(zr(s.boneTexture),s.boneTexture=null):s instanceof c.Bone||!(s instanceof c.Object3D)&&Ko&&console.warn("Unknown object type",s)}}function zr(s){s&&((Ko||Tv()||ru)&&console.warn("🧨 FREE",s),s instanceof ImageBitmap||"dispose"in s&&typeof s.dispose=="function"&&s.dispose())}function HC(s){}const GC=new Set;function Vm(s,e,t=null,i){if(i||(i=GC,i.clear()),!s)return i;const n=s[mc];if(n)for(const o of n)i.has(o)||t?.call(null,o)!==!1&&(i.add(o),e&&Vm(o,!0,t,i));return i}function qC(s){return s[Ll]}const Ko=x("debugresourceusers")||x("debugmemory"),mc=Symbol("needle-resource-users"),Ll=Symbol("needle-resource-users-count");function It(s,e){nu(s,e,function(t,i){gr&&!Ea.raycasting&&(Ad(mc,this,t,!1),Ad(mc,this,i,!0))})}gr&&(It(c.Mesh.prototype,"material"),It(c.Mesh.prototype,"geometry"),It(c.Material.prototype,"map"),It(c.Material.prototype,"bumpMap"),It(c.Material.prototype,"alphaMap"),It(c.Material.prototype,"normalMap"),It(c.Material.prototype,"displacementMap"),It(c.Material.prototype,"roughnessMap"),It(c.Material.prototype,"metalnessMap"),It(c.Material.prototype,"emissiveMap"),It(c.Material.prototype,"specularMap"),It(c.Material.prototype,"envMap"),It(c.Material.prototype,"lightMap"),It(c.Material.prototype,"aoMap"),It(c.Material.prototype,"gradientMap"));function XC(s){if(gr===!1)return;const e=s[mc];if(e)for(const t of e)Ad(mc,t,s,!1)}gr&&nu(c.Material.prototype,"dispose",function(){XC(this)});let Ap=0;function Ad(s,e,t,i){if(Ap>0)return;if(Array.isArray(t)){for(const o of t)Ad(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[Ll]||0;o+=1,t[Ll]=o,Ko&&console.warn(`🟢 Added user of "${t.type}"`,e,t,o,"users:",n)}}else if(e&&n.has(e)){n.delete(e);let o=t[Ll]||0;o>0&&(o-=1,t[Ll]=o),Ko&&console.warn(`🔴 Removed user of "${t.type}"`,e,t,o,"users:",n),o<=0&&(ga.isLoading(t)||(ru&&console.warn(`🔴 Removed all user of "${t.type}"`,t),Tv()&&be(t)))}t[s]=n}try{nu(c.WebGLRenderer.prototype,"render",function(){Ap++},function(){Ap--})}catch(s){console.warn("Could not wrap WebGLRenderer.render",s)}const u_=x("debugcomponentevents");class au{static eventListeners=new Map;static addComponentLifecylceEventListener(e,t){this.eventListeners.has(e)&&this.eventListeners.set(e,[]);let i=this.eventListeners.get(e);i||(i=[]),i.push(t),this.eventListeners.set(e,i),u_&&console.log("Added event listener for "+e,this.eventListeners)}static removeComponentLifecylceEventListener(e,t){const i=this.eventListeners.get(e);if(!i)return;const n=i.indexOf(t);n<0||i.splice(n,1)}static dispatchComponentLifecycleEvent(e,t){const i=this.eventListeners.get(e);if(u_&&console.log("Dispatching event "+e,i),!!i)for(const n of i)n(t)}}const gc=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),jv=Symbol("isUsingInstancing"),Bv=Symbol("instancingRenderer"),Il=Symbol("instancingAutoUpdateBounds");class Fi{static isUsingInstancing(e){return e[jv]===!0}static getRenderer(e){return e[Bv]||null}setAutoUpdateBounds(e,t){const i=Fi.getRenderer(e);i&&(i[Il]=t)}static markDirty(e,t=!0){if(e&&(this.isUsingInstancing(e)&&(e[gc]=!0,e.matrixWorldNeedsUpdate=!0),t))for(const i of e.children)Fi.markDirty(i,!0)}}exports.NEEDLE_ENGINE_FEATURE_FLAGS=void 0;(s=>{s.experimentalSmartHierarchyUpdate=!1})(exports.NEEDLE_ENGINE_FEATURE_FLAGS||(exports.NEEDLE_ENGINE_FEATURE_FLAGS={}));function ya(s,e){try{e||s()}catch(t){return console.error(t),!1}return!0}const Dp=x("debugnewscripts"),QC=x("debughierarchy"),Se=[];function YC(){return Se.length>0}function Dd(s){if(Dp&&console.log("Register new components",s.new_scripts.length,[...s.new_scripts],s.alias?"element: "+s.alias:s.hash,s),s.new_scripts_pre_setup_callbacks.length>0){for(const e of s.new_scripts_pre_setup_callbacks)e&&e();s.new_scripts_pre_setup_callbacks.length=0}if(!(s.new_scripts.length<=0)){Se.length=0,s.new_scripts.length>0&&Se.push(...s.new_scripts),s.new_scripts.length=0;for(let e=0;e<Se.length;e++)try{const t=Se[e];if(t.isComponent!==!0){(T()||Dp)&&console.error(`Registered script is not a Needle Engine component.
|
|
170
170
|
The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
|
|
171
171
|
`,t),Se.splice(e,1),e--;continue}if(t.destroyed)continue;if(!t.gameObject){console.warn(`Component can not be initialized: no GameObject assigned.
|
|
@@ -796,11 +796,11 @@ vec3 AgXToneMapping( vec3 color ) {
|
|
|
796
796
|
<div class="expanded-click-area"></div>
|
|
797
797
|
</button>
|
|
798
798
|
</div>
|
|
799
|
-
`;const t=this.attachShadow({mode:"open"});M0(),Fd(Hp,{loadedCallback:()=>{this.handleSizeChange()}}),Fd(Hp,{element:t});const i=e.content.cloneNode(!0);t?.appendChild(i),this.root=t.querySelector("#root"),this.wrapper=this.root?.querySelector(".wrapper"),this.options=this.root?.querySelector(".options.main-container"),this.optionsCompactMode=this.root?.querySelector(".options.compact-only"),this.logoContainer=this.root?.querySelector(".logo"),this.compactMenuButton=this.root?.querySelector(".compact-menu-button"),this.compactMenuButton.append(yt("more_vert")),this.foldout=this.root?.querySelector(".foldout"),this.root?.appendChild(this.wrapper),this.wrapper.classList.add("wrapper");const n=O0.create();n.setType("compact"),n.style.minHeight="1rem",this.logoContainer.append(n),this.logoContainer.addEventListener("click",()=>{globalThis.open("https://needle.tools","_blank")});try{window.requestAnimationFrame(()=>rP(d=>{if(d==!0&&Fn()&&!E_){let u=this._userRequestedLogoVisible;u===void 0&&(u=!1),this.___onSetLogoVisible(u)}else this.___onSetLogoVisible(!0)}))}catch(d){console.error("[Needle Menu] License check failed.",d)}this.compactMenuButton.addEventListener("click",d=>{d.preventDefault(),this.root.classList.toggle("open")});let o=this._context;setTimeout(()=>o=this._context);let r=0;const a=(d,u)=>{aa&&console.log("Set menu visible",u),o?.isInAR&&o.arOverlayElement?d!=o.arOverlayElement&&o.arOverlayElement.appendChild(this):this.parentNode!=this._domElement?.shadowRoot&&this._domElement?.shadowRoot?.appendChild(this),this.style.display=u?"flex":"none",this.style.visibility="visible",this.style.opacity="1"};let l=!1;new MutationObserver(d=>{if(!l)try{l=!0,this.onChangeDetected(d);const u=this?.parentNode;if((this.style.display!="flex"||this.style.visibility!="visible"||this.style.opacity!="1"||u!=this._domElement?.shadowRoot)&&!Fn()){const p=r++;pi()&&this._userRequestedMenuVisible===!1?(p===0&&a(u,this._userRequestedMenuVisible),p===1&&console.warn("Needle Menu Warning: You need a PRO license to hide the Needle Engine menu → The menu will be visible in your deployed website if you don't have a PRO license. See https://needle.tools/pricing for details.")):p===0?a(u,!0):setTimeout(()=>a(u,!0),5)}}finally{l=!1}}).observe(this.root,{childList:!0,subtree:!0,attributes:!0}),aa&&this.___insertDebugOptions()}_sizeChangeInterval;connectedCallback(){window.addEventListener("resize",this.handleSizeChange),this.handleMenuVisible(),this._sizeChangeInterval=setInterval(()=>this.handleSizeChange(void 0,!1),5e3),setTimeout(()=>{this._domElement?.addEventListener("resize",this.handleSizeChange),this._domElement?.addEventListener("click",this.#t)},1)}disconnectedCallback(){window.removeEventListener("resize",this.handleSizeChange),clearInterval(this._sizeChangeInterval),this._domElement?.removeEventListener("resize",this.handleSizeChange),this._context?.domElement.removeEventListener("click",this.#t)}#t=e=>{if(!e.defaultPrevented&&e.target==this._domElement&&e instanceof PointerEvent&&e.button===0&&this.root.classList.contains("open")){const t=this.foldout.getBoundingClientRect(),i=e;i.clientX>t.left&&i.clientX<t.right&&i.clientY>t.top&&i.clientY<t.bottom||this.root.classList.toggle("open",!1)}};_userRequestedLogoVisible=void 0;showNeedleLogo(e){this._userRequestedLogoVisible=e,!(!e&&(!Fn()||E_)&&(console.warn("[Needle Engine] You need a PRO license to hide the Needle Engine logo in production."),!pi()))&&this.___onSetLogoVisible(e)}get logoIsVisible(){return!this.root.classList.contains("logo-hidden")}___onSetLogoVisible(e){this.logoContainer.style.display="",this.logoContainer.style.opacity="1",this.logoContainer.style.visibility="visible",e?(this.root.classList.remove("logo-hidden"),this.root.classList.add("logo-visible")):(this.root.classList.remove("logo-visible"),this.root.classList.add("logo-hidden"))}setPosition(e){if(e!=="top"&&e!=="bottom")return console.error("NeedleMenu.setPosition: invalid position",e);this.root.classList.remove("top","bottom"),this.root.classList.add(e)}_userRequestedMenuVisible=void 0;setVisible(e){this._userRequestedMenuVisible=e,this.style.display=e?"flex":"none"}closeFoldout(){this.root.classList.remove("open")}root;wrapper;options;optionsCompactMode;logoContainer;compactMenuButton;foldout;trackedElements=new WeakSet;trackElement(e){this.trackedElements.has(e)||(this.trackedElements.add(e),e.addEventListener("click",t=>{ei.sendEvent(this._context,"needle-menu",{action:"button_clicked",element:t.target instanceof Node?t.target.nodeName:e.nodeName,label:e.textContent,title:e instanceof HTMLElement?e.title:void 0,pointerid:t instanceof PointerEvent?t.pointerId:void 0})}))}append(...e){for(const t of e)if(typeof t=="string"){const i=document.createTextNode(t);this.trackElement(i),this.options.appendChild(i)}else this.trackElement(t),this.options.appendChild(t)}appendChild(e){if(!(e instanceof Node)){const i=document.createElement("button");if(i.textContent=e.label,i.onclick=e.onClick,i.setAttribute("priority",e.priority?.toString()??"0"),e.title&&(i.title=e.title),e.icon){const n=yt(e.icon);e.iconSide==="right"?i.appendChild(n):i.prepend(n)}e.class&&i.classList.add(e.class),e=i}return this.trackElement(e),this.options.appendChild(e)}prepend(...e){for(const t of e)if(typeof t=="string"){const i=document.createTextNode(t);this.trackElement(i),this.options.prepend(i)}else this.trackElement(t),this.options.prepend(t)}_isHandlingChange=!1;_pauseMutationObserverOptionsContainer=!1;onChangeDetected(e){if(!this._isHandlingChange){this._isHandlingChange=!0;try{this.handleMenuVisible();for(const t of e)t.target==this.options&&(this._pauseMutationObserverOptionsContainer||this.onOptionsChildrenChanged(t))}finally{this._isHandlingChange=!1}}}onOptionsChildrenChanged(e){if(this.root.classList.toggle("has-options",this.hasAnyVisibleOptions),this.root.classList.toggle("has-no-options",!this.hasAnyVisibleOptions),this.handleSizeChange(void 0,!0),e.type==="childList"&&e.addedNodes.length>0){const t=Array.from(this.options.children);t.sort((n,o)=>{const r=parseInt(n.getAttribute("priority")||"0"),a=parseInt(o.getAttribute("priority")||"0");return r-a});let i=!1;for(let n=0;n<t.length;n++){const o=this.options.children[n],r=t[n];if(o!==r){i=!0;break}}if(i)for(const n of t)this.options.appendChild(n)}}_didSort=new Map;handleMenuVisible(){aa&&console.log("Update VisibleState: Any Content?",this.hasAnyContent),this.hasAnyContent?this.root.style.display="":this.root.style.display="none",this.root.classList.toggle("has-options",this.hasAnyVisibleOptions),this.root.classList.toggle("has-no-options",!this.hasAnyVisibleOptions)}get hasAnyContent(){return!!(this.logoContainer.style.display!="none"||this.hasAnyVisibleOptions)}get hasAnyVisibleOptions(){for(let e=0;e<this.options.children.length;e++){const t=this.options.children[e];if(t.tagName==="SLOT"){const n=t.assignedNodes();for(const o of n)if(o instanceof HTMLElement&&o.style.display!="none")return!0}else if(t.style.display!="none")return!0}return!1}_lastAvailableWidthChange=0;_timeoutHandleSize=0;_timeoutHandleCompactItems=0;handleSizeChange=(e,t)=>{if(!this._domElement)return;const i=this._domElement.clientWidth;if(i<100){clearTimeout(this._timeoutHandleSize),this.root.classList.add("compact"),this.foldout.classList.add("floating-panel-style");return}const o=i-20;if(!t&&Math.abs(o-this._lastAvailableWidthChange)<1)return;this._lastAvailableWidthChange=o,clearTimeout(this._timeoutHandleSize),this._timeoutHandleSize=setTimeout(()=>{const h=l();h<0?(this.root.classList.add("compact"),this.foldout.classList.add("floating-panel-style")):h>0&&(this.root.classList.remove("compact"),this.foldout.classList.remove("floating-panel-style"),l()<0&&(this.root.classList.add("compact"),this.foldout.classList.add("floating-panel-style"))),this._pauseMutationObserverOptionsContainer=!0,this.updateCompactFoldoutItem(),window.requestAnimationFrame(()=>this._pauseMutationObserverOptionsContainer=!1)},150);const r=()=>{let h=0;return h+=this.options.getBoundingClientRect().width,h+=this.optionsCompactMode.getBoundingClientRect().width,h+=10*this.options.childElementCount,h+=this.logoContainer.style.display!="none"?this.logoContainer.getBoundingClientRect().width:0,h};let a=-1;const l=()=>{const h=o-r();return aa&&h!==a&&(a=h,we(`Menu space left: ${h.toFixed(0)}px`)),h}};updateCompactFoldoutItem(){if(this.root.classList.contains("compact")){let e=null,t=-1e7;const i=n=>{if(n instanceof HTMLElement){const o=Js.getElementPriority(n);if(o!==void 0&&o>=t){const r=window.getComputedStyle(n);if(r.display==="none"||r.visibility==="hidden"||r.opacity==="0")return;e=n,t=o}}};for(let n=0;n<this.options.children.length;n++)i(this.options.children.item(n));for(let n=0;n<this.optionsCompactMode.children.length;n++)i(this.optionsCompactMode.children.item(n));if(e&&!this.optionsCompactMode.contains(e)){this.optionsCompactMode.childNodes.forEach(o=>{this.options.appendChild(o)});const n=e;this.optionsCompactMode.appendChild(n)}else e||this.optionsCompactMode.childNodes.forEach(n=>{this.options.appendChild(n)})}else this.optionsCompactMode.childNodes.forEach(e=>{this.options.appendChild(e)})}___insertDebugOptions(){window.addEventListener("keydown",i=>{i.key==="p"&&this.setPosition(this.root.classList.contains("top")?"bottom":"top")});const e=document.createElement("button");e.textContent="Hide Buttons",e.onclick=()=>{const i=new Array(this.options.children.length);for(let n=0;n<this.options.children.length;n++)i[n]=this.options.children[n];for(const n of i)this.options.removeChild(n);setTimeout(()=>{for(const n of i)this.options.appendChild(n)},1e3)},this.appendChild(e);const t=document.createElement("button");t.textContent="Toggle Logo",t.addEventListener("click",()=>{this.logoContainer.style.display=this.logoContainer.style.display==="none"?"":"none"}),this.appendChild(t)}}customElements.get(Vo)||customElements.define(Vo,uu);const $e=x("debugcontext"),Y1=x("stats"),K1=x("debugactive"),Z1=x("debugframerate"),J1=x("debugcoroutine"),eP={};class tP{name;alias;hash;runInBackground;domElement;renderer;camera;scene}var me=(s=>(s[s.Start=-1]="Start",s[s.EarlyUpdate=0]="EarlyUpdate",s[s.Update=1]="Update",s[s.LateUpdate=2]="LateUpdate",s[s.OnBeforeRender=3]="OnBeforeRender",s[s.OnAfterRender=4]="OnAfterRender",s[s.PrePhysicsStep=9]="PrePhysicsStep",s[s.PostPhysicsStep=10]="PostPhysicsStep",s[s.Undefined=-1]="Undefined",s))(me||{});function fu(s,e){if(!s)return;if(!s.isComponent){(T()||$e)&&console.error(`Registered script is not a Needle Engine component.
|
|
799
|
+
`;const t=this.attachShadow({mode:"open"});M0(),Fd(Hp,{loadedCallback:()=>{this.handleSizeChange()}}),Fd(Hp,{element:t});const i=e.content.cloneNode(!0);t?.appendChild(i),this.root=t.querySelector("#root"),this.wrapper=this.root?.querySelector(".wrapper"),this.options=this.root?.querySelector(".options.main-container"),this.optionsCompactMode=this.root?.querySelector(".options.compact-only"),this.logoContainer=this.root?.querySelector(".logo"),this.compactMenuButton=this.root?.querySelector(".compact-menu-button"),this.compactMenuButton.append(yt("more_vert")),this.foldout=this.root?.querySelector(".foldout"),this.root?.appendChild(this.wrapper),this.wrapper.classList.add("wrapper");const n=O0.create();n.setType("compact"),n.style.minHeight="1rem",this.logoContainer.append(n),this.logoContainer.addEventListener("click",()=>{globalThis.open("https://needle.tools","_blank")});try{window.requestAnimationFrame(()=>rP(d=>{if(d==!0&&Fn()&&!E_){let u=this._userRequestedLogoVisible;u===void 0&&(u=!1),this.___onSetLogoVisible(u)}else this.___onSetLogoVisible(!0)}))}catch(d){console.error("[Needle Menu] License check failed.",d)}this.compactMenuButton.addEventListener("click",d=>{d.preventDefault(),this.root.classList.toggle("open")});let o=this._context;setTimeout(()=>o=this._context);let r=0;const a=(d,u)=>{aa&&console.log("Set menu visible",u),o?.isInAR&&o.arOverlayElement?d!=o.arOverlayElement&&o.arOverlayElement.appendChild(this):this.parentNode!=this._domElement?.shadowRoot&&this._domElement?.shadowRoot?.appendChild(this),this.style.display=u?"flex":"none",this.style.visibility="visible",this.style.opacity="1"};let l=!1;new MutationObserver(d=>{if(!l)try{l=!0,this.onChangeDetected(d);const u=this?.parentNode;if((this.style.display!="flex"||this.style.visibility!="visible"||this.style.opacity!="1"||u!=this._domElement?.shadowRoot)&&!Fn()){const p=r++;pi()&&this._userRequestedMenuVisible===!1?(p===0&&a(u,this._userRequestedMenuVisible),p===1&&console.warn("Needle Menu Warning: You need a PRO license to hide the Needle Engine menu → The menu will be visible in your deployed website if you don't have a PRO license. See https://needle.tools/pricing for details.")):p===0?a(u,!0):setTimeout(()=>a(u,!0),5)}}finally{l=!1}}).observe(this.root,{childList:!0,subtree:!0,attributes:!0}),aa&&this.___insertDebugOptions()}_sizeChangeInterval;connectedCallback(){window.addEventListener("resize",this.handleSizeChange),this.handleMenuVisible(),this._sizeChangeInterval=setInterval(()=>this.handleSizeChange(void 0,!1),5e3),setTimeout(()=>{this._domElement?.addEventListener("resize",this.handleSizeChange),this._domElement?.addEventListener("click",this.#t)},1)}disconnectedCallback(){window.removeEventListener("resize",this.handleSizeChange),clearInterval(this._sizeChangeInterval),this._domElement?.removeEventListener("resize",this.handleSizeChange),this._context?.domElement.removeEventListener("click",this.#t)}#t=e=>{if(!e.defaultPrevented&&e.target==this._domElement&&e instanceof PointerEvent&&e.button===0&&this.root.classList.contains("open")){const t=this.foldout.getBoundingClientRect(),i=e;i.clientX>t.left&&i.clientX<t.right&&i.clientY>t.top&&i.clientY<t.bottom||this.root.classList.toggle("open",!1)}};_userRequestedLogoVisible=void 0;showNeedleLogo(e){this._userRequestedLogoVisible=e,!(!e&&(!Fn()||E_)&&(console.warn("[Needle Engine] You need a PRO license to hide the Needle Engine logo in production."),!pi()))&&this.___onSetLogoVisible(e)}get logoIsVisible(){return!this.root.classList.contains("logo-hidden")}___onSetLogoVisible(e){this.logoContainer.style.display="",this.logoContainer.style.opacity="1",this.logoContainer.style.visibility="visible",e?(this.root.classList.remove("logo-hidden"),this.root.classList.add("logo-visible")):(this.root.classList.remove("logo-visible"),this.root.classList.add("logo-hidden"))}setPosition(e){if(e!=="top"&&e!=="bottom")return console.error("NeedleMenu.setPosition: invalid position",e);this.root.classList.remove("top","bottom"),this.root.classList.add(e)}_userRequestedMenuVisible=void 0;setVisible(e){this._userRequestedMenuVisible=e,this.style.display=e?"flex":"none"}closeFoldout(){this.root.classList.remove("open")}root;wrapper;options;optionsCompactMode;logoContainer;compactMenuButton;foldout;trackedElements=new WeakSet;trackElement(e){this.trackedElements.has(e)||(this.trackedElements.add(e),e.addEventListener("click",t=>{ei.sendEvent(this._context,"needle-menu",{action:"button_clicked",element:t.target instanceof Node?t.target.nodeName:e.nodeName,label:e.textContent,title:e instanceof HTMLElement?e.title:void 0,pointerid:t instanceof PointerEvent?t.pointerId:void 0})}))}append(...e){for(const t of e)if(typeof t=="string"){const i=document.createTextNode(t);this.trackElement(i),this.options.appendChild(i)}else this.trackElement(t),this.options.appendChild(t)}appendChild(e){if(!(e instanceof Node)){const i=document.createElement("button");if(i.textContent=e.label,i.onclick=e.onClick,i.setAttribute("priority",e.priority?.toString()??"0"),e.title&&(i.title=e.title),e.icon){const n=yt(e.icon);e.iconSide==="right"?i.appendChild(n):i.prepend(n)}e.class&&i.classList.add(e.class),e=i}return this.trackElement(e),this.options.appendChild(e)}prepend(...e){for(const t of e)if(typeof t=="string"){const i=document.createTextNode(t);this.trackElement(i),this.options.prepend(i)}else this.trackElement(t),this.options.prepend(t)}_isHandlingChange=!1;_pauseMutationObserverOptionsContainer=!1;onChangeDetected(e){if(!this._isHandlingChange){this._isHandlingChange=!0;try{this.handleMenuVisible();for(const t of e)t.target==this.options&&(this._pauseMutationObserverOptionsContainer||this.onOptionsChildrenChanged(t))}finally{this._isHandlingChange=!1}}}onOptionsChildrenChanged(e){if(this.root.classList.toggle("has-options",this.hasAnyVisibleOptions),this.root.classList.toggle("has-no-options",!this.hasAnyVisibleOptions),this.handleSizeChange(void 0,!0),e.type==="childList"&&e.addedNodes.length>0){const t=Array.from(this.options.children);t.sort((n,o)=>{const r=parseInt(n.getAttribute("priority")||"0"),a=parseInt(o.getAttribute("priority")||"0");return r-a});let i=!1;for(let n=0;n<t.length;n++){const o=this.options.children[n],r=t[n];if(o!==r){i=!0;break}}if(i)for(const n of t)this.options.appendChild(n)}}_didSort=new Map;handleMenuVisible(){aa&&console.log("Update VisibleState: Any Content?",this.hasAnyContent),this.hasAnyContent?this.root.style.display="":this.root.style.display="none",this.root.classList.toggle("has-options",this.hasAnyVisibleOptions),this.root.classList.toggle("has-no-options",!this.hasAnyVisibleOptions)}get hasAnyContent(){return!!(this.logoContainer.style.display!="none"||this.hasAnyVisibleOptions)}get hasAnyVisibleOptions(){for(let e=0;e<this.options.children.length;e++){const t=this.options.children[e];if(t.tagName==="SLOT"){const n=t.assignedNodes();for(const o of n)if(o instanceof HTMLElement&&o.style.display!="none")return!0}else if(t.style.display!="none")return!0}return!1}_lastAvailableWidthChange=0;_timeoutHandleSize=0;_timeoutHandleCompactItems=0;handleSizeChange=(e,t)=>{if(!this._domElement)return;const i=this._domElement.clientWidth;if(i<100){clearTimeout(this._timeoutHandleSize),this.root.classList.add("compact"),this.foldout.classList.add("floating-panel-style");return}const o=i-20;if(!t&&Math.abs(o-this._lastAvailableWidthChange)<1)return;this._lastAvailableWidthChange=o,clearTimeout(this._timeoutHandleSize),this._timeoutHandleSize=setTimeout(()=>{const h=l();h<0?(this.root.classList.add("compact"),this.foldout.classList.add("floating-panel-style")):h>0&&(this.root.classList.remove("compact"),this.foldout.classList.remove("floating-panel-style"),l()<0&&(this.root.classList.add("compact"),this.foldout.classList.add("floating-panel-style"))),this._pauseMutationObserverOptionsContainer=!0,this.updateCompactFoldoutItem(),window.requestAnimationFrame(()=>this._pauseMutationObserverOptionsContainer=!1)},150);const r=()=>{let h=0;return h+=this.options.getBoundingClientRect().width,h+=this.optionsCompactMode.getBoundingClientRect().width,h+=10*this.options.childElementCount,h+=this.logoContainer.style.display!="none"?this.logoContainer.getBoundingClientRect().width:0,h};let a=-1;const l=()=>{const h=o-r();return aa&&h!==a&&(a=h,we(`Menu space left: ${h.toFixed(0)}px`)),h}};updateCompactFoldoutItem(){if(this.root.classList.contains("compact")){let e=null,t=-1e7;const i=n=>{if(n instanceof HTMLElement){const o=Js.getElementPriority(n);if(o!==void 0&&o>=t){const r=window.getComputedStyle(n);if(r.display==="none"||r.visibility==="hidden"||r.opacity==="0")return;e=n,t=o}}};for(let n=0;n<this.options.children.length;n++)i(this.options.children.item(n));for(let n=0;n<this.optionsCompactMode.children.length;n++)i(this.optionsCompactMode.children.item(n));if(e&&!this.optionsCompactMode.contains(e)){this.optionsCompactMode.childNodes.forEach(o=>{this.options.appendChild(o)});const n=e;this.optionsCompactMode.appendChild(n)}else e||this.optionsCompactMode.childNodes.forEach(n=>{this.options.appendChild(n)})}else this.optionsCompactMode.childNodes.forEach(e=>{this.options.appendChild(e)})}___insertDebugOptions(){window.addEventListener("keydown",i=>{i.key==="p"&&this.setPosition(this.root.classList.contains("top")?"bottom":"top")});const e=document.createElement("button");e.textContent="Hide Buttons",e.onclick=()=>{const i=new Array(this.options.children.length);for(let n=0;n<this.options.children.length;n++)i[n]=this.options.children[n];for(const n of i)this.options.removeChild(n);setTimeout(()=>{for(const n of i)this.options.appendChild(n)},1e3)},this.appendChild(e);const t=document.createElement("button");t.textContent="Toggle Logo",t.addEventListener("click",()=>{this.logoContainer.style.display=this.logoContainer.style.display==="none"?"":"none"}),this.appendChild(t)}}customElements.get(Vo)||customElements.define(Vo,uu);const We=x("debugcontext"),Y1=x("stats"),K1=x("debugactive"),Z1=x("debugframerate"),J1=x("debugcoroutine"),eP={};class tP{name;alias;hash;runInBackground;domElement;renderer;camera;scene}var me=(s=>(s[s.Start=-1]="Start",s[s.EarlyUpdate=0]="EarlyUpdate",s[s.Update=1]="Update",s[s.LateUpdate=2]="LateUpdate",s[s.OnBeforeRender=3]="OnBeforeRender",s[s.OnAfterRender=4]="OnAfterRender",s[s.PrePhysicsStep=9]="PrePhysicsStep",s[s.PostPhysicsStep=10]="PostPhysicsStep",s[s.Undefined=-1]="Undefined",s))(me||{});function fu(s,e){if(!s)return;if(!s.isComponent){(T()||We)&&console.error(`Registered script is not a Needle Engine component.
|
|
800
800
|
The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
|
|
801
|
-
`,s);return}e||(e=U.Current
|
|
801
|
+
`,s);return}e||(e=U.Current,We&&console.warn("> Registering component without context"));const t=e?.new_scripts;t.includes(s)||t.push(s)}class U{static _defaultTargetFramerate={value:90,toString(){return this.value}};static get DefaultTargetFrameRate(){return U._defaultTargetFramerate.value}static set DefaultTargetFrameRate(e){U._defaultTargetFramerate.value=e}static _defaultWebglRendererParameters={antialias:!0,alpha:!1,powerPreference:exports.DeviceUtilities.isiOS()||exports.DeviceUtilities.isMacOS()?"default":"high-performance",stencil:!0};static get DefaultWebGLRendererParameters(){return U._defaultWebglRendererParameters}get version(){return fi}static get Current(){return le.Current}static set Current(e){le.Current=e}static get All(){return le.All}name;alias;isManagedExternally=!1;isPaused=!1;runInBackground=!1;targetFrameRate;physicsSteps=1;hash;domElement;appendHTMLElement(e){return this.domElement.shadowRoot?this.domElement.shadowRoot.appendChild(e):this.domElement.appendChild(e)}get resolutionScaleFactor(){return this._resolutionScaleFactor}set resolutionScaleFactor(e){if(e!==this._resolutionScaleFactor&&typeof e=="number"){if(e<=0){console.error("Invalid resolution scale factor",e);return}this._resolutionScaleFactor=e,this.updateSize()}}_resolutionScaleFactor=1;_boundingClientRectFrame=-1;_boundingClientRect=null;_domX;_domY;calculateBoundingClientRect(){if(this.xr){this._domX=0,this._domY=0;return}this._boundingClientRectFrame!==this.time.frame&&(this._boundingClientRectFrame=this.time.frame,this._boundingClientRect=this.domElement.getBoundingClientRect(),this._domX=this._boundingClientRect.x,this._domY=this._boundingClientRect.y)}get domWidth(){return this.isInAR?window.innerWidth:this.domElement.clientWidth}get domHeight(){return this.isInAR?window.innerHeight:this.domElement.clientHeight}get domX(){return this.calculateBoundingClientRect(),this._domX}get domY(){return this.calculateBoundingClientRect(),this._domY}get isInXR(){return this.renderer?.xr?.isPresenting||!1}xr=null;get xrSessionMode(){return this.xr?.mode}get isInVR(){return this.xrSessionMode==="immersive-vr"}get isInAR(){return this.xrSessionMode==="immersive-ar"}get isInPassThrough(){return this.xr?this.xr.isPassThrough:!1}get xrSession(){return this.renderer?.xr?.getSession()}get xrFrame(){return this._xrFrame}get xrCamera(){return this.renderer.xr.isPresenting?this.renderer?.xr?.getCamera():void 0}_xrFrame=null;get arOverlayElement(){const e=this.domElement;return typeof e.getAROverlayContainer=="function"?e.getAROverlayContainer():this.domElement}get currentFrameEvent(){return this._currentFrameEvent}_currentFrameEvent=-1;scene;renderer;composer=null;scripts=[];scripts_pausedChanged=[];scripts_earlyUpdate=[];scripts_update=[];scripts_lateUpdate=[];scripts_onBeforeRender=[];scripts_onAfterRender=[];scripts_WithCorroutines=[];scripts_immersive_vr=[];scripts_immersive_ar=[];coroutines={};post_setup_callbacks=[];pre_update_callbacks=[];pre_render_callbacks=[];post_render_callbacks=[];pre_update_oneshot_callbacks=[];new_scripts=[];new_script_start=[];new_scripts_pre_setup_callbacks=[];new_scripts_post_setup_callbacks=[];new_scripts_xr=[];mainCameraComponent=void 0;get mainCamera(){if(this._mainCamera)return this._mainCamera;if(this.mainCameraComponent){const e=this.mainCameraComponent;return e.threeCamera||e.buildCamera(),e.threeCamera}return this._fallbackCamera||(this._fallbackCamera=new c.PerspectiveCamera(75,this.domWidth/this.domHeight,.1,1e3)),this._fallbackCamera}set mainCamera(e){this._mainCamera=e}_mainCamera=null;_fallbackCamera=null;application;animations;time;input;physics;connection;assets;mainLight=null;get rendererData(){return this.sceneLighting}sceneLighting;addressables;lightmaps;players;lodsManager;menu;get isCreated(){return this._isCreated}get rootSourceId(){return this.rootSceneSourceIdentifiers[0]||void 0}_needsUpdateSize=!1;_isCreated=!1;_isCreating=!1;_isVisible=!1;_stats=Y1?new q.Stats:null;constructor(e){this.name=e?.name||"",this.alias=e?.alias,this.domElement=e?.domElement||document.body,this.hash=e?.hash,e?.renderer&&(this.renderer=e.renderer,this.isManagedExternally=!0),e?.runInBackground!==void 0&&(this.runInBackground=e.runInBackground),e?.scene?this.scene=e.scene:this.scene=new c.Scene,e?.camera&&(this._mainCamera=e.camera),this.application=new hn(this),this.time=new w0,this.input=new _v(this),this.physics=new Ea(this),this.connection=new Mv(this),this.assets=new Rv,this.sceneLighting=new b0(this),this.addressables=new f0(this),this.lightmaps=new j1(this),this.players=new _0(this),this.menu=new Js(this),this.lodsManager=new B1(this),this.animations=new D1(this);const t=()=>this._needsUpdateSize=!0;window.addEventListener("resize",t),this._disposeCallbacks.push(()=>window.removeEventListener("resize",t));const i=new ResizeObserver(n=>this._needsUpdateSize=!0);i.observe(this.domElement),this._disposeCallbacks.push(()=>i.disconnect()),this._intersectionObserver=new IntersectionObserver(n=>{this._isVisible=n[0].isIntersecting}),this._disposeCallbacks.push(()=>this._intersectionObserver?.disconnect()),le.register(this)}createNewRenderer(e){if(this.renderer?.dispose(),e={...U.DefaultWebGLRendererParameters,...e},!e.canvas){const t=this.domElement?.shadowRoot?.querySelector("canvas");t&&(e.canvas=t,We&&console.log("Using canvas from shadow root",t))}return We&&console.log("Using Renderer Parameters:",e,this.domElement),this.renderer=new c.WebGLRenderer(e),this.renderer.debug.checkShaderErrors=T()||x("checkshadererrors")===!0,this.renderer.toneMappingExposure=1,this.renderer.toneMapping=c.NoToneMapping,this.renderer.setClearColor(new c.Color("lightgrey"),0),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=c.PCFSoftShadowMap$1,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputColorSpace=c.SRGBColorSpace,this.renderer.nodes={library:new c.BasicNodeLibrary,modelViewMatrix:null,modelNormalViewMatrix:null},this.lodsManager.setRenderer(this.renderer),this.input.bindEvents(),tC(this,this.renderer.domElement),this.renderer}_intersectionObserver=null;internalOnUpdateVisible(){this._intersectionObserver?.disconnect(),this._intersectionObserver?.observe(this.domElement)}_disposeCallbacks=[];requestSizeUpdate(){this._needsUpdateSize=!0}maxRenderResolution;get devicePixelRatio(){return this._devicePixelRatio}set devicePixelRatio(e){e!==this._devicePixelRatio&&(this._devicePixelRatio=e,this._needsUpdateSize=!0)}_devicePixelRatio="auto";updateSize(e=!1){if(e||!this.isManagedExternally&&this.renderer.xr?.isPresenting===!1){this._needsUpdateSize=!1;const t=this.resolutionScaleFactor;let i=this.domWidth*t,n=this.domHeight*t;this.maxRenderResolution&&(this.maxRenderResolution.x=Math.max(1,this.maxRenderResolution.x),i=Math.min(this.maxRenderResolution.x,i),this.maxRenderResolution.y=Math.max(1,this.maxRenderResolution.y),n=Math.min(this.maxRenderResolution.y,n));const o=this.mainCamera;this.updateAspect(o),this.renderer.setSize(i,n,!0),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%";const r=typeof this.devicePixelRatio=="number"?this.devicePixelRatio:this.devicePixelRatio==="auto"?Math.min(2,window.devicePixelRatio):void 0;r!==void 0&&this.renderer.setPixelRatio(r),this.composer&&(this.composer.setSize?.call(this.composer,i,n),r!==void 0&&"setPixelRatio"in this.composer&&typeof this.composer.setPixelRatio=="function"&&this.composer.setPixelRatio?.call(this.composer,window.devicePixelRatio))}}updateAspect(e,t,i){if(!e)return;t===void 0&&(t=this.domWidth),i===void 0&&(i=this.domHeight);const n=t/i;if(e.isPerspectiveCamera){const o=e,r=o.aspect;o.aspect=n,r!==o.aspect&&e.updateProjectionMatrix()}else if(e.isOrthographicCamera){const o=e,r=o.top-o.bottom,l=r*n/2,h=r/2;(o.left!=-l||o.top!=h)&&(o.left=-l,o.right=l,o.top=h,o.bottom=-h,e.updateProjectionMatrix())}}recreate(){this.clear(),this.create(this._originalCreationArgs)}_originalCreationArgs;async onCreate(e){return this.create(e)}async create(e){try{this._isCreating=!0,e!==this._originalCreationArgs&&(this._originalCreationArgs=Ac(e)),window.addEventListener("unhandledrejection",this.onUnhandledRejection);const t=await this.internalOnCreate(e);return this._isCreated=t,t}finally{window.removeEventListener("unhandledrejection",this.onUnhandledRejection),this._isCreating=!1}}onUnhandledRejection=e=>{this.onError(e.reason)};onError(e){this.domElement.dispatchEvent(new CustomEvent("error",{detail:e}))}clear(){le.dispatchCallback(ae.ContextClearing,this),bn(this,ae.ContextClearing),gi(this.scene,!0,!0),this.scene=new c.Scene,this.addressables?.dispose(),this.lightmaps?.clear(),this.physics?.engine?.clearCaches(),this.lodsManager.disable(),this._onBeforeRenderListeners.clear(),this._onAfterRenderListeners.clear(),this.isManagedExternally||this.renderer&&(this.renderer.renderLists.dispose(),this.renderer.state.reset(),this.renderer.resetState()),le.dispatchCallback(ae.ContextCleared,this)}dispose(){this.internalOnDestroy()}onDestroy(){this.internalOnDestroy()}internalOnDestroy(){U.Current=this,le.dispatchCallback(ae.ContextDestroying,this),bn(this,ae.ContextDestroying),this.clear(),this.renderer?.setAnimationLoop(null),this.renderer&&(this.renderer.setClearAlpha(0),this.renderer.clear(),this.isManagedExternally||(We&&console.log("Disposing renderer"),this.renderer.dispose())),this.scene=null,this.renderer=null,this.input.dispose(),this.menu.onDestroy(),this.animations.onDestroy();for(const e of this._disposeCallbacks)try{e()}catch(t){console.error("Error in on dispose callback:",t,e)}this.domElement?.parentElement&&this.domElement.parentElement.removeChild(this.domElement),this._isCreated=!1,le.dispatchCallback(ae.ContextDestroyed,this),bn(this,ae.ContextDestroyed),le.unregister(this),U.Current===this&&(U.Current=null)}registerCoroutineUpdate(e,t,i){return typeof t?.next!="function"?(console.error("Registered invalid coroutine function from "+e.name+`
|
|
802
802
|
Coroutine functions must be generators: "*myCoroutine() {...}"
|
|
803
|
-
Start a coroutine from a component by calling "this.startCoroutine(myCoroutine())"`),t):(this.coroutines[i]||(this.coroutines[i]=[]),this.coroutines[i].push({comp:e,main:t}),t)}unregisterCoroutineUpdate(e,t){if(!this.coroutines[t])return;const i=this.coroutines[t].findIndex(n=>n.main===e);i>=0&&this.coroutines[t].splice(i,1)}stopAllCoroutinesFrom(e){for(const t in this.coroutines){const i=this.coroutines[t];for(let n=i.length-1;n>=0;n--)i[n].comp===e&&i.splice(n,1)}}_cameraStack=[];setCurrentCamera(e){if(!e)return;if(e.threeCamera||e.buildCamera(),!e.threeCamera){console.warn("Camera component is missing camera",e);return}const t=this._cameraStack.indexOf(e);t>=0&&this._cameraStack.splice(t,1),this._cameraStack.push(e),this.mainCameraComponent=e;const i=e.threeCamera;i.isPerspectiveCamera&&this.updateAspect(i),this.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}removeCamera(e){if(!e)return;const t=this._cameraStack.indexOf(e);if(t>=0&&this._cameraStack.splice(t,1),this.mainCameraComponent===e&&(this.mainCameraComponent=void 0,this._cameraStack.length>0)){const i=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(i)}}_onBeforeRenderListeners=new Map;_onAfterRenderListeners=new Map;addBeforeRenderListener(e,t){if(!this._onBeforeRenderListeners.has(e.uuid)){const i=[];this._onBeforeRenderListeners.set(e.uuid,i),e.onBeforeRender=this._createRenderCallbackWrapper(i)}this._onBeforeRenderListeners.get(e.uuid).push(t)}removeBeforeRenderListener(e,t){if(this._onBeforeRenderListeners.has(e.uuid)){const i=this._onBeforeRenderListeners.get(e.uuid),n=i.indexOf(t);n>=0&&i.splice(n,1)}}addAfterRenderListener(e,t){if(!this._onAfterRenderListeners.has(e.uuid)){const i=[];this._onAfterRenderListeners.set(e.uuid,i),e.onAfterRender=this._createRenderCallbackWrapper(i)}this._onAfterRenderListeners.get(e.uuid)?.push(t)}removeAfterRenderListener(e,t){if(this._onAfterRenderListeners.has(e.uuid)){const i=this._onAfterRenderListeners.get(e.uuid),n=i.indexOf(t);n>=0&&i.splice(n,1)}}_createRenderCallbackWrapper(e){return(t,i,n,o,r,a)=>{for(let l=0;l<e.length;l++){const h=e[l];h(t,i,n,o,r,a)}}}_requireDepthTexture=!1;_requireColorTexture=!1;_renderTarget;_isRendering=!1;get isRendering(){return this._isRendering}setRequireDepth(e){this._requireDepthTexture=e}setRequireColor(e){this._requireColorTexture=e}get depthTexture(){return this._renderTarget?.depthTexture||null}get opaqueColorTexture(){return this._renderTarget?.texture||null}get isVisibleToUser(){if(this.isInXR)return!0;if(!this._isVisible)return!1;if(!this._needsVisibleUpdate&&this._lastStyleComputedResult!==void 0)return this._lastStyleComputedResult;this._needsVisibleUpdate=!1;const e=getComputedStyle(this.domElement);return this._lastStyleComputedResult=e.visibility!=="hidden"&&e.display!=="none"&&e.opacity!=="0",this._lastStyleComputedResult}_needsVisibleUpdate=!0;_lastStyleComputedResult=void 0;_createId=0;async internalOnCreate(e){const t=++this._createId
|
|
803
|
+
Start a coroutine from a component by calling "this.startCoroutine(myCoroutine())"`),t):(this.coroutines[i]||(this.coroutines[i]=[]),this.coroutines[i].push({comp:e,main:t}),t)}unregisterCoroutineUpdate(e,t){if(!this.coroutines[t])return;const i=this.coroutines[t].findIndex(n=>n.main===e);i>=0&&this.coroutines[t].splice(i,1)}stopAllCoroutinesFrom(e){for(const t in this.coroutines){const i=this.coroutines[t];for(let n=i.length-1;n>=0;n--)i[n].comp===e&&i.splice(n,1)}}_cameraStack=[];setCurrentCamera(e){if(!e)return;if(e.threeCamera||e.buildCamera(),!e.threeCamera){console.warn("Camera component is missing camera",e);return}const t=this._cameraStack.indexOf(e);t>=0&&this._cameraStack.splice(t,1),this._cameraStack.push(e),this.mainCameraComponent=e;const i=e.threeCamera;i.isPerspectiveCamera&&this.updateAspect(i),this.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}removeCamera(e){if(!e)return;const t=this._cameraStack.indexOf(e);if(t>=0&&this._cameraStack.splice(t,1),this.mainCameraComponent===e&&(this.mainCameraComponent=void 0,this._cameraStack.length>0)){const i=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(i)}}_onBeforeRenderListeners=new Map;_onAfterRenderListeners=new Map;addBeforeRenderListener(e,t){if(!this._onBeforeRenderListeners.has(e.uuid)){const i=[];this._onBeforeRenderListeners.set(e.uuid,i),e.onBeforeRender=this._createRenderCallbackWrapper(i)}this._onBeforeRenderListeners.get(e.uuid).push(t)}removeBeforeRenderListener(e,t){if(this._onBeforeRenderListeners.has(e.uuid)){const i=this._onBeforeRenderListeners.get(e.uuid),n=i.indexOf(t);n>=0&&i.splice(n,1)}}addAfterRenderListener(e,t){if(!this._onAfterRenderListeners.has(e.uuid)){const i=[];this._onAfterRenderListeners.set(e.uuid,i),e.onAfterRender=this._createRenderCallbackWrapper(i)}this._onAfterRenderListeners.get(e.uuid)?.push(t)}removeAfterRenderListener(e,t){if(this._onAfterRenderListeners.has(e.uuid)){const i=this._onAfterRenderListeners.get(e.uuid),n=i.indexOf(t);n>=0&&i.splice(n,1)}}_createRenderCallbackWrapper(e){return(t,i,n,o,r,a)=>{for(let l=0;l<e.length;l++){const h=e[l];h(t,i,n,o,r,a)}}}_requireDepthTexture=!1;_requireColorTexture=!1;_renderTarget;_isRendering=!1;get isRendering(){return this._isRendering}setRequireDepth(e){this._requireDepthTexture=e}setRequireColor(e){this._requireColorTexture=e}get depthTexture(){return this._renderTarget?.depthTexture||null}get opaqueColorTexture(){return this._renderTarget?.texture||null}get isVisibleToUser(){if(this.isInXR)return!0;if(!this._isVisible)return!1;if(!this._needsVisibleUpdate&&this._lastStyleComputedResult!==void 0)return this._lastStyleComputedResult;this._needsVisibleUpdate=!1;const e=getComputedStyle(this.domElement);return this._lastStyleComputedResult=e.visibility!=="hidden"&&e.display!=="none"&&e.opacity!=="0",this._lastStyleComputedResult}_needsVisibleUpdate=!0;_lastStyleComputedResult=void 0;_createId=0;async internalOnCreate(e){const t=++this._createId;We&&console.log("Creating context",this.name,e);const i=globalThis["needle:dependencies:ready"];i instanceof Promise&&(We&&console.log("Waiting for dependencies to be ready"),await i.catch(d=>{if(We||T()){if(jc("Needle Engine dependencies failed to load. Please check the console for more details"),d instanceof ReferenceError){let u="YourComponentName";const p=d.message.indexOf("'");if(p>0){const m=d.message.indexOf("'",p+1);if(m>0){const g=d.message.substring(p+1,m);g.length>3&&(u=g)}}console.error(`Needle Engine dependencies failed to load:
|
|
804
804
|
|
|
805
805
|
# Make sure you don't have circular imports in your scripts!
|
|
806
806
|
|
|
@@ -808,11 +808,11 @@ Possible solutions:
|
|
|
808
808
|
→ Replace @serializable(${u}) in your script with @serializable(Behaviour)
|
|
809
809
|
→ If you only need type information try importing the type only, e.g: import { type ${u} }
|
|
810
810
|
|
|
811
|
-
---`,d);return}console.error("Needle Engine dependencies failed to load",d)}}).then(()=>{
|
|
812
|
-
`,i),this._renderlooperrors>=3&&(console.warn("Stopping render loop due to error"),this.renderer.setAnimationLoop(null),ei.sendError(U.Current,"renderloop",i instanceof Error?i:new Error(String(i)))),this.domElement.dispatchEvent(new CustomEvent("error",{detail:i}))}else this.internalStep(e,t)}updatePhysics(e){this.internalUpdatePhysics(e)}setCameraFocusRect(e,t){const i=this._focusRect;if(this._focusRect=e,t&&Object.assign(this.focusRectSettings,t),t?.damping===void 0&&i){let n=i;i instanceof HTMLElement&&(n=i.getBoundingClientRect()),n&&"top"in n&&n.bottom>=-100&&n.right>=-100&&n.top<=window.innerHeight+100&&n.left<=window.innerWidth+100&&(this.focusRectSettings.damping=.2)}}get focusRect(){return this._focusRect}get focusRectSize(){const e=this._focusRect;if(e&&(e instanceof DOMRect||"width"in e&&"height"in e&&"x"in e&&"y"in e))return{x:e.x,y:e.y,width:e.width,height:e.height};if(e instanceof HTMLElement){const t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}return null}focusRectSettings={damping:0,zoom:1,offsetX:0,offsetY:0};_focusRect=null;_lastTimestamp=0;_accumulatedTime=0;_dispatchReadyAfterFrame=!1;internalStep(e,t){this.internalOnBeforeRender(e,t)!==!1&&(this.internalOnRender(),this.internalOnAfterRender())}internalOnBeforeRender(e,t){this.renderer.info.autoReset=!!t,this.renderer.info.autoReset===!1&&this.renderer.info.reset(),this._needsVisibleUpdate=!0;const i=t!==null&&this._xrFrame===null;if(this._xrFrame=t,i&&this.domElement.dispatchEvent(new CustomEvent("xr-session-started",{detail:{context:this,session:this.xrSession,frame:t}})),this._currentFrameEvent=-1,this.isManagedExternally===!1&&this.isInXR===!1&&this.targetFrameRate!==void 0){this._lastTimestamp===0&&(this._lastTimestamp=e),this._accumulatedTime+=(e-this._lastTimestamp)/1e3,this._lastTimestamp=e;let n=this.targetFrameRate;if(typeof n=="object"&&(n=n.value),this._accumulatedTime<1/(n+1))return!1;this._accumulatedTime=0}if(this._stats?.begin(),U.Current=this,this.onHandlePaused())return!1;for(U.Current=this,this.time.update(),Z1&&console.log("FPS",this.time.smoothedFps.toFixed(0)),Dd(this),cd(this.scene),Uv(this),bn(this,-1);this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);const n=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(n)}if(this.pre_update_oneshot_callbacks){for(const n in this.pre_update_oneshot_callbacks)this.pre_update_oneshot_callbacks[n]();this.pre_update_oneshot_callbacks.length=0}if(this.pre_update_callbacks)for(const n in this.pre_update_callbacks)this.pre_update_callbacks[n]();this._currentFrameEvent=0;for(let n=0;n<this.scripts_earlyUpdate.length;n++){const o=this.scripts_earlyUpdate[n];o.activeAndEnabled&&o.earlyUpdate!==void 0&&(U.Current=this,o.earlyUpdate())}this.executeCoroutines(0),bn(this,0),this._currentFrameEvent=1;for(let n=0;n<this.scripts_update.length;n++){const o=this.scripts_update[n];o.activeAndEnabled&&o.update!==void 0&&(U.Current=this,o.update())}this.executeCoroutines(1),bn(this,1),this._currentFrameEvent=2;for(let n=0;n<this.scripts_lateUpdate.length;n++){const o=this.scripts_lateUpdate[n];o.activeAndEnabled&&o.lateUpdate!==void 0&&(U.Current=this,o.lateUpdate())}if(this.executeCoroutines(2),bn(this,2),this.physicsSteps===void 0&&(this.physicsSteps=1),this.physics.engine&&this.physicsSteps>0&&this.internalUpdatePhysics(this.physicsSteps),this.isVisibleToUser||this.runInBackground){this._currentFrameEvent=3;for(let n=0;n<this.scripts_onBeforeRender.length;n++){const o=this.scripts_onBeforeRender[n];o.activeAndEnabled&&o.onBeforeRender!==void 0&&(U.Current=this,o.onBeforeRender(t))}if(this.executeCoroutines(3),bn(this,3),this._needsUpdateSize&&this.updateSize(),this.pre_render_callbacks)for(const n in this.pre_render_callbacks)this.pre_render_callbacks[n](t);if(this._focusRect&&this.mainCamera instanceof c.PerspectiveCamera){const n=this.focusRectSettings,o=n.damping>0?this.time.deltaTime/n.damping:1;cS(this._focusRect,this.focusRectSettings,o,this.mainCamera,this.renderer)}}return!0}internalUpdatePhysics(e){if(!this.physics.engine)return!1;const t=e,i=this.time.deltaTime/t;for(let n=0;n<t;n++)this._currentFrameEvent=9,this.executeCoroutines(9),this.physics.engine.step(i),this._currentFrameEvent=10,this.executeCoroutines(10);return this.physics.engine.postStep(),!0}internalOnRender(){this.isManagedExternally||(e1(this),this._currentFrameEvent=-1,q.nodeFrame.camera=this.mainCamera,q.nodeFrame.update(),this.renderNow(),this._currentFrameEvent=4)}internalOnAfterRender(){if(this.isVisibleToUser||this.runInBackground){for(let e=0;e<this.scripts_onAfterRender.length;e++){const t=this.scripts_onAfterRender[e];t.activeAndEnabled&&t.onAfterRender!==void 0&&(U.Current=this,t.onAfterRender())}if(this.executeCoroutines(4),bn(this,4),this.post_render_callbacks)for(const e in this.post_render_callbacks)this.post_render_callbacks[e]()}if(this._currentFrameEvent=-1,this.connection.sendBufferedMessagesNow(),this._stats){this._stats.end();const e=this.time.fps<20?50:150;this.time.frameCount%e===0&&console.log(this.renderer.info.render.calls+" DrawCalls",`
|
|
813
|
-
Render:`,{
|
|
814
|
-
Memory:`,{
|
|
815
|
-
Target Framerate: `+this.targetFrameRate)}this._dispatchReadyAfterFrame&&(this._dispatchReadyAfterFrame=!1,this.domElement.dispatchEvent(new CustomEvent("ready")),le.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&&x0(),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){K1&&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&&(U.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){J1&&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=g0(d);o.chained?.push(u);continue}}catch(o){console.error(o)}}function t(i){return!!(i&&i.next&&i.return)}}}function tg(s,e){return gs(s,ae.ContextCreated,e),()=>fo(s,ae.ContextCreated)}function iP(s,e){return gs(s,ae.ContextClearing,e),()=>fo(s,ae.ContextClearing)}function nP(s,e){return gs(s,ae.ContextDestroying,e),()=>fo(s,ae.ContextDestroying)}function pu(s,e){return gs(s,me.Start,e),()=>fo(s,me.Start)}function k0(s,e){return gs(s,me.Update,e),()=>fo(s,me.Update)}function sP(s,e){return gs(s,me.OnBeforeRender,e),()=>fo(s,me.OnBeforeRender)}function oP(s,e){return gs(s,me.OnAfterRender,e),()=>fo(s,me.OnAfterRender)}const gt=x("debuglicense"),E0=[];let rn="basic";gt&&console.log("License Type: "+rn);function Un(){switch(rn){case"pro":case"enterprise":return!0}return!1}function $c(){return rn==="indie"}function ig(){return rn==="edu"}function Fn(){return Un()||$c()||ig()}function rP(s){if(Un()||$c()||ig())return s(!0);E0.push(s)}function Uh(s){for(const e of E0)try{e(s)}catch{}}var ei;(s=>{window.addEventListener("error",a=>{o(U.Current,"unhandled_error",a)}),window.addEventListener("unhandledrejection",a=>{o(U.Current,"unhandled_promise_rejection",{message:a.reason?.message,stack:a.reason?.stack,timestamp:Date.now()})}),tg((a=>e(a)),{once:!0});function e(a){if(!t(a)){gt&&console.debug("Telemetry is disabled via no-telemetry attribute");return}return r({site_id:"dabb8317376f",type:"pageview",pathname:window.location.pathname,hostname:window.location.hostname,page_title:document.title,referrer:document.referrer,user_agent:navigator.userAgent,querystring:window.location.search,language:navigator.language,screenWidth:window.screen.width,screenHeight:window.screen.height,event_name:"page_view"}).then(l=>{if(l instanceof Response&&l.ok&&pi()){const d=(a.domElement?.getAttribute("src")||"")+fi+Ca+uc+Ks;window.sessionStorage.getItem("session_key")!==d&&(window.sessionStorage.setItem("session_key",d),n(a,"info",{src:a.domElement?.getAttribute("src")||"",version:fi,generator:Ca,build_time:uc,public_key:Ks}))}})}function t(a){let l=a?.domElement;if(l||(l=document.querySelector("needle-engine")),!l&&!a)return!1;const h=l?.getAttribute("no-telemetry");return(h===""||h==="true"||h==="1")&&(rn==="pro"||rn==="enterprise")?(gt&&console.debug("Telemetry is disabled via no-telemetry attribute"),!1):!0}s.isAllowed=t;const i="dabb8317376f";async function n(a,l,h){if(!t(a)){gt&&console.debug("Telemetry is disabled");return}const d={site_id:i,type:"custom_event",pathname:window.location.pathname,event_name:l,properties:h?JSON.stringify(h):void 0};return r(d)}s.sendEvent=n;async function o(a,l,h){if(!t(a)){gt&&console.debug("Telemetry is disabled");return}h instanceof ErrorEvent?h={message:h.message,stack:h.error?.stack,filename:h.filename,lineno:h.lineno,colno:h.colno,timestamp:h.timeStamp||Date.now()}:h instanceof Error&&(h={message:h.message,stack:h.stack,timestamp:Date.now()});const d={site_id:i,type:"error",event_name:l||"error",properties:JSON.stringify({error_name:l,message:h.message,stack:h.stack,filename:h.filename,lineno:h.lineno,colno:h.colno,timestamp:h.timestamp})};return r(d)}s.sendError=o;function r(a){try{return fetch("https://needle.tools/api/v1/rum/t",{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json"},keepalive:!0,mode:"cors",priority:"low"}).catch(h=>{gt&&console.error("Failed to send telemetry",h)})}catch(l){gt&&console.error(l)}return Promise.resolve()}})(ei||(ei={}));le.registerCallback(ae.ContextRegistered,s=>{cP(s.context),lP(s.context),setTimeout(()=>dP(s.context),2e3)});let Nd,Gp=!1,qp="";async function aP(){if(Nd)return Nd;if(rn==="basic")try{const s="https://needle.tools/api/v1/needle-engine/check?location="+encodeURIComponent(window.location.href)+"&version="+fi+"&generator="+encodeURIComponent(Ca),e=await fetch(s,{method:"GET"}).catch(t=>{gt&&console.error("License check failed",t)});e?.status===200?(Gp=!1,gt&&console.log("License check succeeded"),rn="pro",Uh(!0)):e?.status===403?(Uh(!1),Gp=!0,qp=await e.text()):(Uh(!1),gt&&console.log("License check failed with status "+e?.status))}catch(s){Uh(!1),gt&&console.error("License check failed",s)}else gt&&console.log('Runtime license check is skipped because license is already applied as "'+rn+'"')}Nd=aP();async function lP(s){function e(){const n=document.createElement("div");n.className="needle-forbidden",n.style.cssText=`
|
|
811
|
+
---`,d);return}console.error("Needle Engine dependencies failed to load",d)}}).then(()=>{We&&console.log("Needle Engine dependencies are ready")})),this.clear();const n=this.renderer,o=!n||n.isDisposed===!0;this.isManagedExternally===!1&&o?this.createNewRenderer():this.lodsManager.setRenderer(this.renderer),this.renderer?.setAnimationLoop(null),U.Current=this,await le.dispatchCallback(ae.ContextCreationStart,this);let r=!0,a;try{U.Current=this,e?a=await this.internalLoadInitialContent(t,e):a=[]}catch(d){console.error(d),r=!1}if(!r)return this.onError("Failed to load initial content"),!1;if(t!==this._createId||e?.abortSignal?.aborted)return!1;if(this.internalOnUpdateVisible(),!this.renderer)return We&&console.warn("Context has no renderer (perhaps it was disconnected?",this.domElement.isConnected),!1;!this.isManagedExternally&&!this.domElement.shadowRoot&&this.domElement.prepend(this.renderer.domElement),U.Current=this,U.Current=this;for(let d=0;d<this.new_scripts.length;d++){const u=this.new_scripts[d];if(u.gameObject!==void 0&&u.gameObject!==null){u.gameObject.userData===void 0&&(u.gameObject.userData={}),u.gameObject.userData.components===void 0&&(u.gameObject.userData.components=[]);const p=u.gameObject.userData.components;p.includes(u)||p.push(u)}}if(this.post_setup_callbacks)for(let d=0;d<this.post_setup_callbacks.length;d++)U.Current=this,await this.post_setup_callbacks[d](this);if(!this._mainCamera){U.Current=this;let d=null;lr(this.scene,u=>{const p=u;if(p?.isCamera){if(Kl(p.gameObject),!p.activeAndEnabled)return;if(p.tag==="MainCamera")return d=p,!0;d=p}}),d?this.setCurrentCamera(d):!le.dispatchCallback(ae.MissingCamera,this,{files:a})&&!this.mainCamera&&!this.isManagedExternally&&console.warn("Missing camera in main scene",this)}this.input.bindEvents(),U.Current=this,Dd(this),this.physics.engine&&(this.physics.engine?.step(0),this.physics.engine?.postStep()),!this.isManagedExternally&&this.composer&&this.mainCamera,this._needsUpdateSize=!0,this._stats&&(this._stats.showPanel(0),this._stats.dom.style.position="absolute",this.domElement.shadowRoot?.appendChild(this._stats.dom)),We&&Ed(this.scene,!0),this.targetFrameRate===void 0?(We&&console.warn("No target framerate set, using default",U.DefaultTargetFrameRate),this.targetFrameRate=U._defaultTargetFramerate):We&&console.log("Target framerate set to",this.targetFrameRate),this._dispatchReadyAfterFrame=!0;const l=le.dispatchCallback(ae.ContextCreated,this,{files:a});if(l){const d=this.domElement;"internalSetLoadingMessage"in d&&typeof d.internalSetLoadingMessage=="function"&&d?.internalSetLoadingMessage("finish loading"),await l}if(e?.abortSignal?.aborted)return!1;const h=this.rootSourceId;return h&&this.sceneLighting.enable(h),bn(this,ae.ContextCreated),We&&console.log("Context Created...",this.renderer,this.renderer.domElement),this._isCreating=!1,!this.isManagedExternally&&!e?.abortSignal?.aborted&&this.restartRenderLoop(),!0}rootSceneSourceIdentifiers=[];async internalLoadInitialContent(e,t){this.rootSceneSourceIdentifiers.length=0;const i=new Array;if(t.files.length===0)return i;const n=[...t.files];this.rootSceneSourceIdentifiers.push(...n);const o={name:"",progress:null,index:0,count:n.length},r=cn(),a=0;for(let l=0;l<n.length;l++){if(t.abortSignal?.aborted){We&&console.log("Aborting loading because of abort signal");break}if(e!==this._createId){We&&console.log("Aborting loading because create id changed",e,this._createId);break}const h=n[l];t?.onLoadingStart?.call(this,l,h),We&&console.log("Context Load "+h);const d=await r.loadSync(this,h,h,a,u=>{t.abortSignal?.aborted||(o.name=h,o.progress=u,o.index=l,o.count=n.length,t.onLoadingProgress?.call(this,o))});t?.onLoadingFinished?.call(this,l,h,d??null),d?i.push({src:h,file:d}):console.warn("Could not load file: "+h)}if(e!==this._createId||t.abortSignal?.aborted){We&&console.log("Aborting loading because create id changed or abort signal was set",e,this._createId);for(const l of i)if(l&&l.file)for(const h of l.file.scenes)gi(h,!0,!0)}else{let l=!1;for(const h of i)h&&h.file&&(h.file.scene?(l=!0,this.scene.add(h.file.scene)):console.warn("No scene found in loaded file"));if(!l){for(const h of i)if(h&&h.file&&"parser"in h.file){let d=0;if(!Array.isArray(h.file.parser.json.materials))continue;for(let u=0;u<h.file.parser.json.materials.length;u++){const p=await h.file.parser.getDependency("material",u),m=new c.Object3D;m.position.x=u*1.1,m.position.y=d,this.scene.add(m),po.createPrimitive("ShaderBall",{parent:m,material:p})}d+=1}}}return i}restartRenderLoop(){return this.renderer?this._isCreating?(console.warn("Can not start render loop while creating context"),!1):(this.renderer.setAnimationLoop((e,t)=>{this.isManagedExternally||this.update(e,t)}),!0):(console.error("Can not start render loop without renderer"),!1)}_renderlooperrors=0;update(e,t){if(t===void 0&&(t=null),T()||We||YC())try{this.internalStep(e,t),this._renderlooperrors=0}catch(i){this._renderlooperrors+=1,(T()||We)&&(i instanceof Error||i instanceof TypeError)&&we("Caught unhandled exception during render-loop - see console for details.",ui.Error),console.error("Frame #"+this.time.frame+`
|
|
812
|
+
`,i),this._renderlooperrors>=3&&(console.warn("Stopping render loop due to error"),this.renderer.setAnimationLoop(null),ei.sendError(U.Current,"renderloop",i instanceof Error?i:new Error(String(i)))),this.domElement.dispatchEvent(new CustomEvent("error",{detail:i}))}else this.internalStep(e,t)}updatePhysics(e){this.internalUpdatePhysics(e)}setCameraFocusRect(e,t){const i=this._focusRect;if(this._focusRect=e,t&&Object.assign(this.focusRectSettings,t),t?.damping===void 0&&i){let n=i;i instanceof HTMLElement&&(n=i.getBoundingClientRect()),n&&"top"in n&&n.bottom>=-100&&n.right>=-100&&n.top<=window.innerHeight+100&&n.left<=window.innerWidth+100&&(this.focusRectSettings.damping=.2)}}get focusRect(){return this._focusRect}get focusRectSize(){const e=this._focusRect;if(e&&(e instanceof DOMRect||"width"in e&&"height"in e&&"x"in e&&"y"in e))return{x:e.x,y:e.y,width:e.width,height:e.height};if(e instanceof HTMLElement){const t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}return null}focusRectSettings={damping:0,zoom:1,offsetX:0,offsetY:0};_focusRect=null;_lastTimestamp=0;_accumulatedTime=0;_dispatchReadyAfterFrame=!1;internalStep(e,t){this.internalOnBeforeRender(e,t)!==!1&&(this.internalOnRender(),this.internalOnAfterRender())}internalOnBeforeRender(e,t){this.renderer.info.autoReset=!!t,this.renderer.info.autoReset===!1&&this.renderer.info.reset(),this._needsVisibleUpdate=!0;const i=t!==null&&this._xrFrame===null;if(this._xrFrame=t,i&&this.domElement.dispatchEvent(new CustomEvent("xr-session-started",{detail:{context:this,session:this.xrSession,frame:t}})),this._currentFrameEvent=-1,this.isManagedExternally===!1&&this.isInXR===!1&&this.targetFrameRate!==void 0){this._lastTimestamp===0&&(this._lastTimestamp=e),this._accumulatedTime+=(e-this._lastTimestamp)/1e3,this._lastTimestamp=e;let n=this.targetFrameRate;if(typeof n=="object"&&(n=n.value),this._accumulatedTime<1/(n+1))return!1;this._accumulatedTime=0}if(this._stats?.begin(),U.Current=this,this.onHandlePaused())return!1;for(U.Current=this,this.time.update(),Z1&&console.log("FPS",this.time.smoothedFps.toFixed(0)),Dd(this),cd(this.scene),Uv(this),bn(this,-1);this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);const n=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(n)}if(this.pre_update_oneshot_callbacks){for(const n in this.pre_update_oneshot_callbacks)this.pre_update_oneshot_callbacks[n]();this.pre_update_oneshot_callbacks.length=0}if(this.pre_update_callbacks)for(const n in this.pre_update_callbacks)this.pre_update_callbacks[n]();this._currentFrameEvent=0;for(let n=0;n<this.scripts_earlyUpdate.length;n++){const o=this.scripts_earlyUpdate[n];o.activeAndEnabled&&o.earlyUpdate!==void 0&&(U.Current=this,o.earlyUpdate())}this.executeCoroutines(0),bn(this,0),this._currentFrameEvent=1;for(let n=0;n<this.scripts_update.length;n++){const o=this.scripts_update[n];o.activeAndEnabled&&o.update!==void 0&&(U.Current=this,o.update())}this.executeCoroutines(1),bn(this,1),this._currentFrameEvent=2;for(let n=0;n<this.scripts_lateUpdate.length;n++){const o=this.scripts_lateUpdate[n];o.activeAndEnabled&&o.lateUpdate!==void 0&&(U.Current=this,o.lateUpdate())}if(this.executeCoroutines(2),bn(this,2),this.physicsSteps===void 0&&(this.physicsSteps=1),this.physics.engine&&this.physicsSteps>0&&this.internalUpdatePhysics(this.physicsSteps),this.isVisibleToUser||this.runInBackground){this._currentFrameEvent=3;for(let n=0;n<this.scripts_onBeforeRender.length;n++){const o=this.scripts_onBeforeRender[n];o.activeAndEnabled&&o.onBeforeRender!==void 0&&(U.Current=this,o.onBeforeRender(t))}if(this.executeCoroutines(3),bn(this,3),this._needsUpdateSize&&this.updateSize(),this.pre_render_callbacks)for(const n in this.pre_render_callbacks)this.pre_render_callbacks[n](t);if(this._focusRect&&this.mainCamera instanceof c.PerspectiveCamera){const n=this.focusRectSettings,o=n.damping>0?this.time.deltaTime/n.damping:1;cS(this._focusRect,this.focusRectSettings,o,this.mainCamera,this.renderer)}}return!0}internalUpdatePhysics(e){if(!this.physics.engine)return!1;const t=e,i=this.time.deltaTime/t;for(let n=0;n<t;n++)this._currentFrameEvent=9,this.executeCoroutines(9),this.physics.engine.step(i),this._currentFrameEvent=10,this.executeCoroutines(10);return this.physics.engine.postStep(),!0}internalOnRender(){this.isManagedExternally||(e1(this),this._currentFrameEvent=-1,q.nodeFrame.camera=this.mainCamera,q.nodeFrame.update(),this.renderNow(),this._currentFrameEvent=4)}internalOnAfterRender(){if(this.isVisibleToUser||this.runInBackground){for(let e=0;e<this.scripts_onAfterRender.length;e++){const t=this.scripts_onAfterRender[e];t.activeAndEnabled&&t.onAfterRender!==void 0&&(U.Current=this,t.onAfterRender())}if(this.executeCoroutines(4),bn(this,4),this.post_render_callbacks)for(const e in this.post_render_callbacks)this.post_render_callbacks[e]()}if(this._currentFrameEvent=-1,this.connection.sendBufferedMessagesNow(),this._stats){this._stats.end();const e=this.time.fps<20?50:150;if(this.time.frameCount%e===0||this.time.frameCount===1){const t=window.performance&&window.performance.memory?`${(window.performance.memory.usedJSHeapSize/1024/1024).toFixed(2)} MB`:"n/a";console.log(this.renderer.info.render.calls+" DrawCalls",`
|
|
813
|
+
Render:`,{shaders:this.renderer.info.programs?.length,...this.renderer.info.render},`
|
|
814
|
+
Memory:`,{usedMemory:t,...this.renderer.info.memory},`
|
|
815
|
+
Target Framerate: `+this.targetFrameRate)}}this._dispatchReadyAfterFrame&&(this._dispatchReadyAfterFrame=!1,this.domElement.dispatchEvent(new CustomEvent("ready")),le.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&&x0(),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){K1&&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&&(U.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){J1&&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=g0(d);o.chained?.push(u);continue}}catch(o){console.error(o)}}function t(i){return!!(i&&i.next&&i.return)}}}function tg(s,e){return gs(s,ae.ContextCreated,e),()=>fo(s,ae.ContextCreated)}function iP(s,e){return gs(s,ae.ContextClearing,e),()=>fo(s,ae.ContextClearing)}function nP(s,e){return gs(s,ae.ContextDestroying,e),()=>fo(s,ae.ContextDestroying)}function pu(s,e){return gs(s,me.Start,e),()=>fo(s,me.Start)}function k0(s,e){return gs(s,me.Update,e),()=>fo(s,me.Update)}function sP(s,e){return gs(s,me.OnBeforeRender,e),()=>fo(s,me.OnBeforeRender)}function oP(s,e){return gs(s,me.OnAfterRender,e),()=>fo(s,me.OnAfterRender)}const gt=x("debuglicense"),E0=[];let rn="basic";gt&&console.log("License Type: "+rn);function Un(){switch(rn){case"pro":case"enterprise":return!0}return!1}function $c(){return rn==="indie"}function ig(){return rn==="edu"}function Fn(){return Un()||$c()||ig()}function rP(s){if(Un()||$c()||ig())return s(!0);E0.push(s)}function Uh(s){for(const e of E0)try{e(s)}catch{}}var ei;(s=>{window.addEventListener("error",a=>{o(U.Current,"unhandled_error",a)}),window.addEventListener("unhandledrejection",a=>{o(U.Current,"unhandled_promise_rejection",{message:a.reason?.message,stack:a.reason?.stack,timestamp:Date.now()})}),tg((a=>e(a)),{once:!0});function e(a){if(!t(a)){gt&&console.debug("Telemetry is disabled via no-telemetry attribute");return}return r({site_id:"dabb8317376f",type:"pageview",pathname:window.location.pathname,hostname:window.location.hostname,page_title:document.title,referrer:document.referrer,user_agent:navigator.userAgent,querystring:window.location.search,language:navigator.language,screenWidth:window.screen.width,screenHeight:window.screen.height,event_name:"page_view"}).then(l=>{if(l instanceof Response&&l.ok&&pi()){const d=(a.domElement?.getAttribute("src")||"")+fi+Ca+uc+Ks;window.sessionStorage.getItem("session_key")!==d&&(window.sessionStorage.setItem("session_key",d),n(a,"info",{src:a.domElement?.getAttribute("src")||"",version:fi,generator:Ca,build_time:uc,public_key:Ks}))}})}function t(a){let l=a?.domElement;if(l||(l=document.querySelector("needle-engine")),!l&&!a)return!1;const h=l?.getAttribute("no-telemetry");return(h===""||h==="true"||h==="1")&&(rn==="pro"||rn==="enterprise")?(gt&&console.debug("Telemetry is disabled via no-telemetry attribute"),!1):!0}s.isAllowed=t;const i="dabb8317376f";async function n(a,l,h){if(!t(a)){gt&&console.debug("Telemetry is disabled");return}const d={site_id:i,type:"custom_event",pathname:window.location.pathname,event_name:l,properties:h?JSON.stringify(h):void 0};return r(d)}s.sendEvent=n;async function o(a,l,h){if(!t(a)){gt&&console.debug("Telemetry is disabled");return}h instanceof ErrorEvent?h={message:h.message,stack:h.error?.stack,filename:h.filename,lineno:h.lineno,colno:h.colno,timestamp:h.timeStamp||Date.now()}:h instanceof Error&&(h={message:h.message,stack:h.stack,timestamp:Date.now()});const d={site_id:i,type:"error",event_name:l||"error",properties:JSON.stringify({error_name:l,message:h.message,stack:h.stack,filename:h.filename,lineno:h.lineno,colno:h.colno,timestamp:h.timestamp})};return r(d)}s.sendError=o;function r(a){try{return fetch("https://needle.tools/api/v1/rum/t",{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json"},keepalive:!0,mode:"cors",priority:"low"}).catch(h=>{gt&&console.error("Failed to send telemetry",h)})}catch(l){gt&&console.error(l)}return Promise.resolve()}})(ei||(ei={}));le.registerCallback(ae.ContextRegistered,s=>{cP(s.context),lP(s.context),setTimeout(()=>dP(s.context),2e3)});let Nd,Gp=!1,qp="";async function aP(){if(Nd)return Nd;if(rn==="basic")try{const s="https://needle.tools/api/v1/needle-engine/check?location="+encodeURIComponent(window.location.href)+"&version="+fi+"&generator="+encodeURIComponent(Ca),e=await fetch(s,{method:"GET"}).catch(t=>{gt&&console.error("License check failed",t)});e?.status===200?(Gp=!1,gt&&console.log("License check succeeded"),rn="pro",Uh(!0)):e?.status===403?(Uh(!1),Gp=!0,qp=await e.text()):(Uh(!1),gt&&console.log("License check failed with status "+e?.status))}catch(s){Uh(!1),gt&&console.error("License check failed",s)}else gt&&console.log('Runtime license check is skipped because license is already applied as "'+rn+'"')}Nd=aP();async function lP(s){function e(){const n=document.createElement("div");n.className="needle-forbidden",n.style.cssText=`
|
|
816
816
|
position: fixed;
|
|
817
817
|
top: 0;
|
|
818
818
|
left: 0;
|
|
@@ -883,10 +883,10 @@ Target Framerate: `+this.targetFrameRate)}this._dispatchReadyAfterFrame&&(this._
|
|
|
883
883
|
padding-left: 25px;
|
|
884
884
|
border-radius: .5em;
|
|
885
885
|
border: 2px solid rgba(160,160,160,.3);
|
|
886
|
-
`,n=`Needle Engine — No license active, commercial use is not allowed. Visit https://needle.tools/pricing for more information and licensing options! v${fi}`;U.Current?.xr?console.log(n):console.log("%c "+n,t)}async function dP(s){if(!window.crossOriginIsolated){if(!ei.isAllowed(s)){gt&&console.debug("Telemetry is disabled via no-telemetry attribute");return}try{const e="https://needle.tools/api/v1/needle-engine/ping";if(e){const t=window.location.href.split("?")[0],n={license:rn,url:t,hostname:window.location.hostname,pathname:window.location.pathname,version:fi,generator:Ca,build_time:uc,public_key:Ks},o=navigator.sendBeacon?.(e,JSON.stringify(n));gt&&console.debug("Sent beacon: "+o)}}catch(e){gt&&console.log("Failed to send non-commercial usage message to analytics backend",e)}}}const uP=x("debugdecoders");let Df=null;function T0(){if(!Df){const s=se.createLoaders(null);Df={dracoLoader:s.dracoLoader,ktx2Loader:s.ktx2Loader,meshoptDecoder:s.meshoptDecoder}}return Df}function T_(s){s!==void 0&&typeof s=="string"&&se.setDracoDecoderLocation(s)}function A_(s){if(s!==void 0&&typeof s=="string"&&s!=="js"){const e=T0();uP&&console.log("Setting draco decoder type to",s),e.dracoLoader.setDecoderConfig({type:s})}}function D_(s){s!==void 0&&typeof s=="string"&&se.setKTX2TranscoderLocation(s)}function ng(s,e){const t=T0();return e.renderer?t.ktx2Loader.detectSupport(e.renderer):console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures will probably fail"),se.addDracoAndKTX2Loaders(s),s.dracoLoader||s.setDRACOLoader(t.dracoLoader),s.ktx2Loader||s.setKTX2Loader(t.ktx2Loader),s.meshoptDecoder||s.setMeshoptDecoder(t.meshoptDecoder),se.configureLoader(s,{progressive:!0}),s}const ze=function(s){return f(s)},f=function(s){if(s===void 0&&(s=null),!Array.isArray(s))s=L_(s);else for(let e=0;e<s.length;e++){const t=s[e];s[e]=L_(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 L_(s){switch(s?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return s}const eo=x("debughotreload");let _c=!1;const ec=new Map;function fP(){return _c}function Qp(){return globalThis.NEEDLE_HOT_RELOAD_ENABLED===!0}function A0(s){if(_c){eo&&console.warn("[Needle Engine] Hot reloading is in progress, not registering instance",s);return}eo&&console.log("[Needle Engine] Registering hot reload instance",s);const t=s.constructor.name;ec.has(t)?ec.get(t)?.push(s):ec.set(t,[s])}function D0(s){if(_c){eo&&console.warn("[Needle Engine] Hot reloading is in progress, not unregistering instance",s);return}eo&&console.log("[Needle Engine] Unregistering hot reload instance",s);const t=s.constructor.name,i=ec.get(t);if(!i)return;const n=i.indexOf(s);n!==-1&&i.splice(n,1)}let I_=!1;function pP(){if(eo||I_)return;I_=!0;const s=console.error;console.error=(...e)=>{if(e.length){const t=e[0];if(typeof t=="string"&&t.includes("[hmr] Failed to reload ")){console.log("[Needle Engine] Hot reloading failed"),window.location.reload();return}}s.apply(console,e)}}function mP(s){eo&&console.log("[HMR] Apply changes",s,Object.keys(s)),pP();for(const e of Object.keys(s))try{_c=!0;const t=P.get(e);if(!t){eo&&console.log("[HMR] Type not found: "+e);continue}const i=s[e],n=ec.get(i.name);let o="[Needle Engine] Updating type: "+e;const r=n?.length??-1;r>0?o+=" x"+r:o+=" (No instances registered)",console.log(o);const a=Object.getOwnPropertyNames(t.prototype),l=Object.getOwnPropertyDescriptors(i.prototype);for(const h in l)l[h].writable&&(t.prototype[h]=s[e].prototype[h]);for(const h of a)l[h]||delete t.prototype[h];if(n){const h=new i,d=Object.getOwnPropertyDescriptors(h);for(const u of n){const p=u,m=p.isComponent===!0,g=m?p.activeAndEnabled:!0,_=m?p.context:void 0;try{if(m&&_&&ns(p,_),m&&g&&(p.enabled=!1),u.onBeforeHotReloadFields&&u.onBeforeHotReloadFields()===!1)continue;for(const y in d)if(d[y].writable){if(u[y]===void 0)u[y]=h[y];else if(typeof u[y]=="function"&&!u[y].prototype){const b=u[y],w=b.name,R="bound ";if(w===R)continue;const M=b.name.substring(R.length),O=i.prototype[M];O&&(u[y]=O.bind(u))}}u.onAfterHotReloadFields&&u.onAfterHotReloadFields()}finally{m&&_&&$m(p,_),m&&g&&(p.enabled=!0)}}}}catch(t){if(eo)console.error(t);else return!1}finally{_c=!1,Ho(ui.Log,"Script changes applied (HMR)")}return!0}class S extends c.Object3D{guid;static isDestroyed(e){return ar(e)}static setActive(e,t,i=!0){e&&(Zl(e,t),cd(e),t&&i&&Uv(U.Current,e))}static isActiveSelf(e){return Fa(e)}static isActiveInHierarchy(e){return a0(e)}static markAsInstancedRendered(e,t){l0(e,t)}static isUsingInstancing(e){return hu(e)}static foreachComponent(e,t,i=!0){return lr(e,t,i)}static instantiateSynced(e,t){return e?Hm(e,t):null}static instantiate(e,t=null){return"isAssetReference"in e,oo(e,t)}static destroySynced(e,t,i=!0){if(!e)return;const n=e;t=t??U.Current,Bc(n,t.connection,i)}static destroy(e,t=!0){return gi(e,t)}static add(e,t,i){if(!(!e||!t)){if(e===t){console.warn("Can not add object to self",e);return}i||(i=U.Current),t.add(e),Zl(e,!0),cd(e),i?S.foreachComponent(e,n=>{$m(n,i),!n.__internalDidAwakeAndStart&&i.new_script_start.includes(n)===!1&&i.new_script_start.push(n)},!0):console.warn("Missing context")}}static remove(e){e&&(e.parent?.remove(e),Zl(e,!1),cd(e),S.foreachComponent(e,t=>{KC(t)},!0))}static invokeOnChildren(e,t,...i){this.invoke(e,t,!0,i)}static invoke(e,t,i=!1,...n){e&&this.foreachComponent(e,o=>{const r=o[t];r&&typeof r=="function"&&r?.call(o,...n)},i)}static addNewComponent(e,t,i,n=!0){return on(e,t,i,{callAwake:n})}static addComponent(e,t,i,n){return on(e,t,i,n)}static moveComponent(e,t){return on(e,t)}static removeComponent(e){return Ym(e.gameObject,e),e}static getOrAddComponent(e,t){return Fc(e,t)}static getComponent(e,t){return e===null?null:yr(e,t)}static getComponents(e,t,i=null){return e===null?i??[]:zc(e,t,i)}static findByGuid(e,t){return Km(e,t)}static findObjectOfType(e,t,i=!0){return Ua(e,t??U.Current,i)}static findObjectsOfType(e,t){const i=[];return r0(e,i,t),i}static getComponentInChildren(e,t,i=!1){return Nc(e,t,i)}static getComponentsInChildren(e,t,i=null){return Ba(e,t,i??void 0)}static getComponentInParent(e,t){return yc(e,t)}static getComponentsInParent(e,t,i=null){return lu(e,t,i)}static getAllComponents(e){const t=e.userData?.components;return t?[...t]:[]}static*iterateComponents(e){const t=e?.userData?.components;if(t&&Array.isArray(t))for(let i=0;i<t.length;i++)yield t[i]}}const gP=Symbol("component-name");class E{get isComponent(){return!0}get[gP](){return P.getKey(this.constructor)||void 0}__context;get context(){return this.__context??U.Current}set context(e){this.__context=e}get scene(){return this.context.scene}get layer(){return this.gameObject?.userData?.layer}get name(){return this.gameObject?.name?this.gameObject.name:this.gameObject?.userData.name}__name;set name(e){this.gameObject?(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.name=e,this.__name=e):this.__name=e}get tag(){return this.gameObject?.userData.tag}set tag(e){this.gameObject&&(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.tag=e)}get static(){return this.gameObject?.userData.static}set static(e){this.gameObject&&(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.static=e)}get activeAndEnabled(){return!(this.destroyed||this.__isEnabled===!1||!this.__isActiveInHierarchy)}get __isActive(){return this.gameObject.visible}get __isActiveInHierarchy(){if(!this.gameObject)return!1;const e=this.gameObject[ds];return e===void 0?!0:e}set __isActiveInHierarchy(e){this.gameObject&&(this.gameObject[ds]=e)}gameObject;guid="invalid";sourceId;awake(){}onEnable(){}onDisable(){}onDestroy(){this.__destroyed=!0}startCoroutine(e,t=me.Update){return this.context.registerCoroutineUpdate(this,e,t)}stopCoroutine(e,t=me.Update){this.context.unregisterCoroutineUpdate(e,t)}get destroyed(){return this.__destroyed}destroy(){this.__destroyed||this.__internalDestroy()}__didAwake=!1;__didStart=!1;__didEnable=!1;__isEnabled=void 0;__destroyed=!1;get __internalDidAwakeAndStart(){return this.__didAwake&&this.__didStart}constructor(e){this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1,this._internalInit(e),Qp()&&A0(this)}__internalNewInstanceCreated(e){return this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1,this._internalInit(e),this}_internalInit(e){if(typeof e=="object")for(const t of Object.keys(e)){const i=e[t];typeof i!="function"&&(this[t]=i)}}__internalAwake(){this.__didAwake||(this.__didAwake=!0,this.awake())}__internalStart(){this.__didStart||(this.__didStart=!0,this.start&&this.start())}__internalEnable(e){return this.__destroyed?(T()&&console.warn("[Needle Engine Dev] Trying to enable destroyed component"),!1):this.__didAwake?this.__didEnable?(e!==!0&&(this.__isEnabled=!0),!1):(this.__didEnable=!0,this.__isEnabled=!0,this.onEnable(),!0):!1}__internalDisable(e){if(this.__didAwake){if(!this.__didEnable){e!==!0&&(this.__isEnabled=!1);return}this.__didEnable=!1,this.__isEnabled=!1,this.onDisable()}}__internalDestroy(){this.__destroyed||(this.__destroyed=!0,this.__didAwake&&(this.onDestroy?.call(this),this.dispatchEvent(new CustomEvent("destroyed",{detail:this}))),s0(this),Qp()&&D0(this))}get enabled(){return typeof this.__isEnabled=="boolean"?this.__isEnabled:!0}set enabled(e){if(this.__destroyed){T()&&console.warn(`[Needle Engine Dev] Trying to ${e?"enable":"disable"} destroyed component`);return}if(typeof e=="number"&&(e>=.5?e=!0:e=!1),!this.__didAwake){this.__isEnabled=e;return}e?this.__internalEnable():this.__internalDisable()}get worldPosition(){return Q(this.gameObject)}set worldPosition(e){rt(this.gameObject,e)}setWorldPosition(e,t,i){rr(this.gameObject,e,t,i)}get worldQuaternion(){return fe(this.gameObject)}set worldQuaternion(e){ln(this.gameObject,e)}setWorldQuaternion(e,t,i,n){Pm(this.gameObject,e,t,i,n)}get worldEuler(){return Mm(this.gameObject)}set worldEuler(e){Om(this.gameObject,e)}get worldRotation(){return this.gameObject.worldRotation}set worldRotation(e){this.setWorldRotation(e.x,e.y,e.z,!0)}setWorldRotation(e,t,i,n=!0){Ic(this.gameObject,e,t,i,n)}static _forward=new c.Vector3;get forward(){return E._forward.set(0,0,-1).applyQuaternion(this.worldQuaternion)}static _right=new c.Vector3;get right(){return E._right.set(1,0,0).applyQuaternion(this.worldQuaternion)}static _up=new c.Vector3;get up(){return E._up.set(0,1,0).applyQuaternion(this.worldQuaternion)}_eventListeners=new Map;addEventListener(e,t){this._eventListeners[e]=this._eventListeners[e]||[],this._eventListeners[e].push(t)}removeEventListener(e,t){if(!this._eventListeners[e])return;const i=this._eventListeners[e].indexOf(t);i>=0&&this._eventListeners[e].splice(i,1)}dispatchEvent(e){if(!e||!this._eventListeners[e.type])return!1;const t=this._eventListeners[e.type];for(let i=0;i<t.length;i++)t[i](e);return!1}}const yP=Object.freeze(Object.defineProperty({__proto__:null,Behaviour:E,Component:E,GameObject:S},Symbol.toStringTag,{value:"Module"}));var _P=Object.defineProperty,L0=(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&&_P(e,t,n),n};class Wc extends E{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new c.Vector3}update(){if(!this.from||!this.to)return;const e=Q(this.from).clone(),t=Q(this.to).clone(),i=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),rt(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(Q(this.to).clone()),this.gameObject.scale.set(this.width,this.width,i)}}L0([f(S)],Wc.prototype,"from");L0([f(S)],Wc.prototype,"to");var bP=Object.defineProperty,vP=Object.getOwnPropertyDescriptor,_r=(s,e,t,i)=>{for(var n=i>1?void 0:i?vP(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&&bP(e,t,n),n};const Ls=x("debuganimation");let I0=class{x;y};class Et extends E{get isAnimationComponent(){return!0}addClip(e){this.animations||(this.animations=[]),this.animations.includes(e)||this.animations.push(e)}playAutomatically=!0;randomStartTime=!1;minMaxSpeed;minMaxOffsetNormalized;loop=!0;clampWhenFinished=!1;get time(){if(this.actions){for(const e of this.actions)if(e.isRunning())return e.time}return 0}set time(e){if(this.actions)for(const t of this.actions)t.time=e}get duration(){if(this.actions){for(const e of this.actions)if(e.isRunning())return e.getClip().duration}return 0}_tempAnimationClipBeforeGameObjectExisted=null;get clip(){return this.animations?.length?this.animations[0]:null}set clip(e){if(!this.__didAwake){Ls&&console.warn("Assign clip during serialization",e),this._tempAnimationClipBeforeGameObjectExisted=e;return}e&&(this.gameObject.animations||(this.gameObject.animations=[]),!this.animations.includes(e)&&(this.animations.length>0?this.animations.splice(0,0,e):this.animations.push(e)))}set clips(e){this.animations=e}_tempAnimationsArray;set animations(e){e==null||!Array.isArray(e)||(this.gameObject?this.gameObject.animations=e:this._tempAnimationsArray=e)}get animations(){return this.gameObject?.animations||this._tempAnimationsArray||[]}mixer=void 0;get actions(){return this._actions}set actions(e){this._actions=e}_actions;_handles;awake(){this.mixer=void 0,Ls&&console.log("Animation Awake",this.name,this),this._tempAnimationsArray&&(this.animations=this._tempAnimationsArray,this._tempAnimationsArray=void 0),this._tempAnimationClipBeforeGameObjectExisted&&(this.clip=this._tempAnimationClipBeforeGameObjectExisted,this._tempAnimationClipBeforeGameObjectExisted=null),this.actions=[],this._handles=[]}onEnable(){if(this.playAutomatically&&this.animations?.length>0){const e=Math.floor(Math.random()*this.animations.length),t=this.animations[e];this.play(e,{exclusive:!0,fadeDuration:0,startTime:this.randomStartTime?Math.random()*t.duration:0,loop:this.loop,clampWhenFinished:this.clampWhenFinished})}}update(){this.mixer&&(this.mixer.update(this.context.time.deltaTime),this._handles.forEach(e=>e.update()))}onDisable(){this.mixer&&this.mixer.stopAllAction()}onDestroy(){this.context.animations.unregisterAnimationMixer(this.mixer)}getAction(e){return this.actions?.find(t=>t.getClip().name===e)||null}get isPlaying(){if(this.actions){for(let e=0;e<this.actions.length;e++)if(this.actions[e].isRunning())return!0}return!1}stopAll(e){if(this.actions)for(const t of this.actions)e?.fadeDuration?t.fadeOut(e.fadeDuration):t.stop()}stop(e,t){if(e===void 0){this.stopAll();return}else if(typeof e=="number"){if(e>=this.animations.length){Ls&&console.log("No animation at index",e);return}e=this.animations[e]}else typeof e=="string"&&(e=this.animations.find(n=>n.name===e));if(!e){console.error("Could not find clip",e);return}const i=this.actions.find(n=>n.getClip()===e);if(!i){console.error("Could not find action",e);return}t?.fadeDuration?i.fadeOut(t.fadeDuration):i.stop()}pause(e,t=!1){if(e===void 0){for(const n of this.actions)n.paused=!t;return}else if(typeof e=="number"){if(e>=this.animations.length){Ls&&console.log("No animation at index",e);return}e=this.animations[e]}else typeof e=="string"&&(e=this.animations.find(n=>n.name===e));if(!e){console.error("Could not find clip",e);return}const i=this.actions.find(n=>n.getClip()===e);if(!i){console.error("Could not find action",e);return}i.paused=!t}resume(){for(const e of this.actions)e.paused=!1}play(e=0,t){if(Ls&&console.log("PLAY",e),this.ensureMixer(),!this.mixer){Ls&&console.warn("Missing mixer",this);return}e===void 0&&(e=0);let i=e;if(typeof e=="number"){if(e>=this.animations.length){Ls&&console.log("No animation at index",e);return}i=this.animations[e]}else typeof e=="string"&&(i=this.animations.find(o=>o.name===e));if(!i){console.error("Could not find clip",e);return}t||(t={});for(const o of this.actions)if(o.getClip()===i)return this.internalOnPlay(o,t);if(!i.tracks){console.warn("Clip is no AnimationClip",i);return}const n=this.mixer.clipAction(i);return this.actions.push(n),this.internalOnPlay(n,t)}internalOnPlay(e,t){var i=this.actions.find(r=>r===e);if(i===e&&i.isRunning()&&i.time<i.getClip().duration){const r=this.tryFindHandle(e);if(i.paused&&(i.paused=!1),r)return r.waitForFinish()}if(t.loop===void 0&&(t.loop=this.loop),t.clampWhenFinished===void 0&&(t.clampWhenFinished=this.clampWhenFinished),t.minMaxOffsetNormalized===void 0&&this.randomStartTime&&(t.minMaxOffsetNormalized=this.minMaxOffsetNormalized),t.minMaxSpeed===void 0&&(t.minMaxSpeed=this.minMaxSpeed),t?.exclusive??!0)for(const r of this.actions)r!=i&&(t.fadeDuration?r.fadeOut(t.fadeDuration):r.stop());if(t?.fadeDuration&&e.fadeIn(t.fadeDuration),e.enabled=!0,t?.startTime!=null)e.time=t.startTime;else if(t?.minMaxOffsetNormalized&&t.minMaxOffsetNormalized.x!=0&&t.minMaxOffsetNormalized.y!=0){const r=e.getClip();e.time=I.lerp(t.minMaxOffsetNormalized.x,t.minMaxOffsetNormalized.y,Math.random())*r.duration}else e.time>=e.getClip().duration&&(e.time=0);t?.minMaxSpeed?e.timeScale=I.lerp(t.minMaxSpeed.x,t.minMaxSpeed.y,Math.random()):e.timeScale=t?.speed??1,t?.loop!=null?e.loop=t.loop?c.LoopRepeat:c.LoopOnce:e.loop=c.LoopOnce,t?.clampWhenFinished&&(e.clampWhenFinished=!0),e.paused=!1,e.play(),window.requestAnimationFrame(()=>Nn.testIfRootCanAnimate(e)),Ls&&console.log("PLAY",e.getClip().name,e);const o=new wP(e,this.mixer,t,r=>{this._handles.splice(this._handles.indexOf(o),1)});return this._handles.push(o),o.waitForFinish()}tryFindHandle(e){for(const t of this._handles)if(t.action===e)return t}ensureMixer(){if(!this.mixer){const e="animationMixer";this.gameObject[e]&&(this.mixer=this.gameObject[e]),(!this.mixer||!this.mixer.clipAction)&&(this.mixer=new c.AnimationMixer(this.gameObject),this.gameObject[e]=this.mixer)}this.context.animations.registerAnimationMixer(this.mixer)}}_r([f()],Et.prototype,"playAutomatically",2);_r([f()],Et.prototype,"randomStartTime",2);_r([f(I0)],Et.prototype,"minMaxSpeed",2);_r([f(I0)],Et.prototype,"minMaxOffsetNormalized",2);_r([f()],Et.prototype,"loop",2);_r([f()],Et.prototype,"clampWhenFinished",2);_r([f(c.AnimationClip)],Et.prototype,"clips",1);class wP{mixer;action;promise=null;_options;_resolveCallback=null;_resolvedOrRejectedCallback;constructor(e,t,i,n){this.action=e,this.mixer=t,this._resolvedOrRejectedCallback=n,this._options=i}waitForFinish(){return this.promise?this.promise:(this.promise=new Promise(e=>{this._resolveCallback=e}),this.mixer.addEventListener("finished",this.onFinished),this.promise)}update(){this._options&&this._options.endTime!==void 0&&this.action.time>this._options.endTime&&(this._options.loop===!0?this.action.time=this._options.startTime??0:(this.action.time=this._options.endTime,this.action.timeScale=0,this.onResolve()))}onResolve(){this.dispose(),this._resolvedOrRejectedCallback?.call(this,this),this._resolveCallback?.call(this,this.action)}onFinished=e=>{e.action===this.action&&this.onResolve()};dispose(){this.mixer.removeEventListener("finished",this.onFinished)}}const md=Symbol("objectIsAnimatedData");function j_(s,e,t){if(!s)return;if(s[md]===void 0){if(!t)return;s[md]=new Set}const i=s[md];t?i.add(e):i.has(e)&&i.delete(e)}function xP(s){if(!s)return!1;const e=s[md];return e!==void 0&&e.size>0}class SP{_context;get context(){return this._context??U.Current}get isStateMachineBehaviour(){return!0}}class jl{name;nameHash;normalizedTime;length;speed;action;hasTransitions;constructor(e,t,i,n){this.name=e.name,this.nameHash=e.hash,this.normalizedTime=t,this.length=i,this.speed=n,this.action=e.motion.action||null,this.hasTransitions=e.transitions?.length>0||!1}}function j0(s,e){return{name:"Empty",isLooping:!1,guid:e?.generateUUID()??c.MathUtils.generateUUID(),index:-1,clip:new c.AnimationClip(s,0,[])}}var Gs=(s=>(s[s.If=1]="If",s[s.IfNot=2]="IfNot",s[s.Greater=3]="Greater",s[s.Less=4]="Less",s[s.Equals=6]="Equals",s[s.NotEqual=7]="NotEqual",s))(Gs||{}),sg=(s=>(s[s.Float=1]="Float",s[s.Int=3]="Int",s[s.Bool=4]="Bool",s[s.Trigger=9]="Trigger",s))(sg||{});const Xe=x("debuganimatorcontroller"),Fh=x("debugrootmotion");class zi{static createFromClips(e,t={looping:!1,autoTransition:!0,transitionDuration:0}){const i=[];for(let r=0;r<e.length;r++){const a=e[r],l=[];if(t.autoTransition!==!1){const d=t.transitionDuration??0,u=d/a.duration;let p=r;(t.autoTransition===void 0||t.autoTransition===!0)&&(p=(r+1)%e.length),l.push({exitTime:1-u,offset:0,duration:d,hasExitTime:!0,destinationState:p,conditions:[]})}const h={name:a.name,hash:r,motion:{name:a.name,clip:a,isLooping:t?.looping??!1},transitions:l,behaviours:[]};i.push(h)}const n={name:"AnimatorController",guid:new _t(Date.now()).generateUUID(),parameters:[],layers:[{name:"Base Layer",stateMachine:{defaultState:0,states:i}}]};return new zi(n)}play(e,t=-1,i=Number.NEGATIVE_INFINITY,n=0){if(t<0)t=0;else if(t>=this.model.layers.length){console.warn("invalid layer");return}const r=this.model.layers[t].stateMachine;for(const a of r.states)if(a.name===e||a.hash===e){Xe&&console.log("transition to ",a),this.transitionTo(a,n,i);return}console.warn("Could not find "+e+" to play")}reset(){this.setStartTransition()}setBool(e,t){const i=typeof e=="string"?"name":"hash";return this.model?.parameters?.filter(n=>n[i]===e).forEach(n=>n.value=t)}getBool(e){const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.find(i=>i[t]===e)?.value??!1}setFloat(e,t){const i=typeof e=="string"?"name":"hash",n=this.model?.parameters?.filter(o=>o[i]===e);return n.forEach(o=>o.value=t),n?.length>0}getFloat(e){const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.find(i=>i[t]===e)?.value??0}setInteger(e,t){const i=typeof e=="string"?"name":"hash";return this.model?.parameters?.filter(n=>n[i]===e).forEach(n=>n.value=t)}getInteger(e){const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.find(i=>i[t]===e)?.value??0}setTrigger(e){Xe&&console.log("SET TRIGGER",e);const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.filter(i=>i[t]===e).forEach(i=>i.value=!0)}resetTrigger(e){const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.filter(i=>i[t]===e).forEach(i=>i.value=!1)}getTrigger(e){const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.find(i=>i[t]===e)?.value??!1}isInTransition(){return this._activeStates.length>1}setSpeed(e){this._speed=e}_speed=1;FindState(e){return this.findState(e)}findState(e){if(!e)return null;if(Array.isArray(this.model.layers)){for(const t of this.model.layers)for(const i of t.stateMachine.states)if(i.name===e||i.hash==e)return i}return null}getCurrentStateInfo(){if(!this._activeState)return null;const e=this._activeState.motion.action;if(!e)return null;const t=this._activeState.motion.clip.duration,i=t<=0?0:Math.abs(e.time/t);return new jl(this._activeState,i,t,this._speed)}get currentAction(){if(!this._activeState)return null;const e=this._activeState.motion.action;return e||null}normalizedStartOffset=0;animator;model;get context(){return this.animator?.context}get mixer(){return this._mixer}dispose(){if(this._mixer.stopAllAction(),this.animator){this._mixer.uncacheRoot(this.animator.gameObject);for(const e of this._activeStates)e.motion.clip&&this.mixer.uncacheAction(e.motion.clip,this.animator.gameObject)}this.context?.animations.unregisterAnimationMixer(this._mixer)}bind(e){e?this.animator!==e&&(this._mixer&&(this._mixer.stopAllAction(),this.context?.animations.unregisterAnimationMixer(this._mixer)),this.animator=e,this._mixer=new c.AnimationMixer(this.animator.gameObject),this.context?.animations.registerAnimationMixer(this._mixer),this.createActions(this.animator)):console.error("AnimatorController.bind: animator is null")}clone(){if(typeof this.model=="string")return console.warn("AnimatorController has not been resolved, can not create model from string",this.model),null;Xe&&console.warn("AnimatorController clone()",this.model);const e=Ac(this.model,(i,n,o)=>o==null?!0:!(o.type==="Object3D"||o.isObject3D===!0||tv(o)||o.tracks!==void 0||o instanceof zi));return console.assert(e!==this.model),new zi(e)}update(e){if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates(e);const t=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&this.rootMotionHandler?.onBeforeUpdate(e),this._mixer.update(t),this.animator.applyRootMotion&&this.rootMotionHandler?.onAfterUpdate(e)}_mixer;_activeState;get activeState(){return this._activeState}constructor(e){this.model=e,Xe&&console.log(this)}_activeStates=[];updateActiveStates(e){for(let t=0;t<this._activeStates.length;t++){const i=this._activeStates[t],n=i.motion;if(!n.action)this._activeStates.splice(t,1),t--;else{const o=n.action;o.weight=e,o.getEffectiveWeight()<=0&&!o.isRunning()&&(Xe&&console.debug("REMOVE",i.name,o.getEffectiveWeight(),o.isRunning(),o.isScheduled()),this._activeStates.splice(t,1),t--)}}}setStartTransition(){this.model.layers.length>1&&(Xe||T())&&console.warn("Multiple layers are not supported yet "+this.animator?.name);for(const e of this.model.layers){const t=e.stateMachine;t.defaultState===void 0&&(Xe&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",e),t.defaultState=0);const i=t.states[t.defaultState];this.transitionTo(i,0,this.normalizedStartOffset);break}}evaluateTransitions(){let e=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;e=!0}const t=this._activeState,i=t.motion.action;for(const o of t.transitions){if(!o.hasExitTime&&o.conditions.length<=0)continue;let r=!0;for(const a of o.conditions)if(!this.evaluateCondition(a)){r=!1;break}if(r)if(i){const a=t.motion.clip.duration,l=a<=0?1:Math.abs(i.time/a);let h=o.exitTime;i.timeScale<0&&(h=1-h);let d=!1;if(o.hasExitTime?i.timeScale>0?d=l>=o.exitTime:i.timeScale<0&&(d=1-l>=o.exitTime):d=!0,d){for(const u of o.conditions){const p=this.model.parameters.find(m=>m.name===u.parameter);p?.type===sg.Trigger&&p.value&&(p.value=!1)}if(i.clampWhenFinished=!0,Xe){const u=this.getState(o.destinationState,0);console.log(`Transition to ${o.destinationState} / ${u?.name}`,o,`
|
|
886
|
+
`,n=`Needle Engine — No license active, commercial use is not allowed. Visit https://needle.tools/pricing for more information and licensing options! v${fi}`;U.Current?.xr?console.log(n):console.log("%c "+n,t)}async function dP(s){if(!window.crossOriginIsolated){if(!ei.isAllowed(s)){gt&&console.debug("Telemetry is disabled via no-telemetry attribute");return}try{const e="https://needle.tools/api/v1/needle-engine/ping";if(e){const t=window.location.href.split("?")[0],n={license:rn,url:t,hostname:window.location.hostname,pathname:window.location.pathname,version:fi,generator:Ca,build_time:uc,public_key:Ks},o=navigator.sendBeacon?.(e,JSON.stringify(n));gt&&console.debug("Sent beacon: "+o)}}catch(e){gt&&console.log("Failed to send non-commercial usage message to analytics backend",e)}}}const uP=x("debugdecoders");let Df=null;function T0(){if(!Df){const s=se.createLoaders(null);Df={dracoLoader:s.dracoLoader,ktx2Loader:s.ktx2Loader,meshoptDecoder:s.meshoptDecoder}}return Df}function T_(s){s!==void 0&&typeof s=="string"&&se.setDracoDecoderLocation(s)}function A_(s){if(s!==void 0&&typeof s=="string"&&s!=="js"){const e=T0();uP&&console.log("Setting draco decoder type to",s),e.dracoLoader.setDecoderConfig({type:s})}}function D_(s){s!==void 0&&typeof s=="string"&&se.setKTX2TranscoderLocation(s)}function ng(s,e){const t=T0();return e.renderer?t.ktx2Loader.detectSupport(e.renderer):console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures will probably fail"),se.addDracoAndKTX2Loaders(s),s.dracoLoader||s.setDRACOLoader(t.dracoLoader),s.ktx2Loader||s.setKTX2Loader(t.ktx2Loader),s.meshoptDecoder||s.setMeshoptDecoder(t.meshoptDecoder),se.configureLoader(s,{progressive:!0}),s}const ze=function(s){return f(s)},f=function(s){if(s===void 0&&(s=null),!Array.isArray(s))s=L_(s);else for(let e=0;e<s.length;e++){const t=s[e];s[e]=L_(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 L_(s){switch(s?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return s}const eo=x("debughotreload");let _c=!1;const ec=new Map;function fP(){return _c}function Qp(){return globalThis.NEEDLE_HOT_RELOAD_ENABLED===!0}function A0(s){if(_c){eo&&console.warn("[Needle Engine] Hot reloading is in progress, not registering instance",s);return}eo&&console.log("[Needle Engine] Registering hot reload instance",s);const t=s.constructor.name;ec.has(t)?ec.get(t)?.push(s):ec.set(t,[s])}function D0(s){if(_c){eo&&console.warn("[Needle Engine] Hot reloading is in progress, not unregistering instance",s);return}eo&&console.log("[Needle Engine] Unregistering hot reload instance",s);const t=s.constructor.name,i=ec.get(t);if(!i)return;const n=i.indexOf(s);n!==-1&&i.splice(n,1)}let I_=!1;function pP(){if(eo||I_)return;I_=!0;const s=console.error;console.error=(...e)=>{if(e.length){const t=e[0];if(typeof t=="string"&&t.includes("[hmr] Failed to reload ")){console.log("[Needle Engine] Hot reloading failed"),window.location.reload();return}}s.apply(console,e)}}function mP(s){eo&&console.log("[HMR] Apply changes",s,Object.keys(s)),pP();for(const e of Object.keys(s))try{_c=!0;const t=P.get(e);if(!t){eo&&console.log("[HMR] Type not found: "+e);continue}const i=s[e],n=ec.get(i.name);let o="[Needle Engine] Updating type: "+e;const r=n?.length??-1;r>0?o+=" x"+r:o+=" (No instances registered)",console.log(o);const a=Object.getOwnPropertyNames(t.prototype),l=Object.getOwnPropertyDescriptors(i.prototype);for(const h in l)l[h].writable&&(t.prototype[h]=s[e].prototype[h]);for(const h of a)l[h]||delete t.prototype[h];if(n){const h=new i,d=Object.getOwnPropertyDescriptors(h);for(const u of n){const p=u,m=p.isComponent===!0,g=m?p.activeAndEnabled:!0,_=m?p.context:void 0;try{if(m&&_&&ns(p,_),m&&g&&(p.enabled=!1),u.onBeforeHotReloadFields&&u.onBeforeHotReloadFields()===!1)continue;for(const y in d)if(d[y].writable){if(u[y]===void 0)u[y]=h[y];else if(typeof u[y]=="function"&&!u[y].prototype){const b=u[y],w=b.name,R="bound ";if(w===R)continue;const M=b.name.substring(R.length),O=i.prototype[M];O&&(u[y]=O.bind(u))}}u.onAfterHotReloadFields&&u.onAfterHotReloadFields()}finally{m&&_&&$m(p,_),m&&g&&(p.enabled=!0)}}}}catch(t){if(eo)console.error(t);else return!1}finally{_c=!1,Ho(ui.Log,"Script changes applied (HMR)")}return!0}class S extends c.Object3D{guid;static isDestroyed(e){return ar(e)}static setActive(e,t,i=!0){e&&(Zl(e,t),cd(e),t&&i&&Uv(U.Current,e))}static isActiveSelf(e){return Fa(e)}static isActiveInHierarchy(e){return a0(e)}static markAsInstancedRendered(e,t){l0(e,t)}static isUsingInstancing(e){return hu(e)}static foreachComponent(e,t,i=!0){return lr(e,t,i)}static instantiateSynced(e,t){return e?Hm(e,t):null}static instantiate(e,t=null){return"isAssetReference"in e,oo(e,t)}static destroySynced(e,t,i=!0){if(!e)return;const n=e;t=t??U.Current,Bc(n,t.connection,i)}static destroy(e,t=!0){return gi(e,t)}static add(e,t,i){if(!(!e||!t)){if(e===t){console.warn("Can not add object to self",e);return}i||(i=U.Current),t.add(e),Zl(e,!0),cd(e),i?S.foreachComponent(e,n=>{$m(n,i),!n.__internalDidAwakeAndStart&&i.new_script_start.includes(n)===!1&&i.new_script_start.push(n)},!0):console.warn("Missing context")}}static remove(e){e&&(e.parent?.remove(e),Zl(e,!1),cd(e),S.foreachComponent(e,t=>{KC(t)},!0))}static invokeOnChildren(e,t,...i){this.invoke(e,t,!0,i)}static invoke(e,t,i=!1,...n){e&&this.foreachComponent(e,o=>{const r=o[t];r&&typeof r=="function"&&r?.call(o,...n)},i)}static addNewComponent(e,t,i,n=!0){return on(e,t,i,{callAwake:n})}static addComponent(e,t,i,n){return on(e,t,i,n)}static moveComponent(e,t){return on(e,t)}static removeComponent(e){return Ym(e.gameObject,e),e}static getOrAddComponent(e,t){return Fc(e,t)}static getComponent(e,t){return e===null?null:yr(e,t)}static getComponents(e,t,i=null){return e===null?i??[]:zc(e,t,i)}static findByGuid(e,t){return Km(e,t)}static findObjectOfType(e,t,i=!0){return Ua(e,t??U.Current,i)}static findObjectsOfType(e,t){const i=[];return r0(e,i,t),i}static getComponentInChildren(e,t,i=!1){return Nc(e,t,i)}static getComponentsInChildren(e,t,i=null){return Ba(e,t,i??void 0)}static getComponentInParent(e,t){return yc(e,t)}static getComponentsInParent(e,t,i=null){return lu(e,t,i)}static getAllComponents(e){const t=e.userData?.components;return t?[...t]:[]}static*iterateComponents(e){const t=e?.userData?.components;if(t&&Array.isArray(t))for(let i=0;i<t.length;i++)yield t[i]}}const gP=Symbol("component-name");class E{get isComponent(){return!0}get[gP](){return P.getKey(this.constructor)||void 0}__context;get context(){return this.__context??U.Current}set context(e){this.__context=e}get scene(){return this.context.scene}get layer(){return this.gameObject?.userData?.layer}get name(){return this.gameObject?.name?this.gameObject.name:this.gameObject?.userData.name}__name;set name(e){this.gameObject?(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.name=e,this.__name=e):this.__name=e}get tag(){return this.gameObject?.userData.tag}set tag(e){this.gameObject&&(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.tag=e)}get static(){return this.gameObject?.userData.static}set static(e){this.gameObject&&(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.static=e)}get activeAndEnabled(){return!(this.destroyed||this.__isEnabled===!1||!this.__isActiveInHierarchy)}get __isActive(){return this.gameObject.visible}get __isActiveInHierarchy(){if(!this.gameObject)return!1;const e=this.gameObject[ds];return e===void 0?!0:e}set __isActiveInHierarchy(e){this.gameObject&&(this.gameObject[ds]=e)}gameObject;guid="invalid";sourceId;awake(){}onEnable(){}onDisable(){}onDestroy(){this.__destroyed=!0}startCoroutine(e,t=me.Update){return this.context.registerCoroutineUpdate(this,e,t)}stopCoroutine(e,t=me.Update){this.context.unregisterCoroutineUpdate(e,t)}get destroyed(){return this.__destroyed}destroy(){this.__destroyed||this.__internalDestroy()}__didAwake=!1;__didStart=!1;__didEnable=!1;__isEnabled=void 0;__destroyed=!1;get __internalDidAwakeAndStart(){return this.__didAwake&&this.__didStart}constructor(e){this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1,this._internalInit(e),Qp()&&A0(this)}__internalNewInstanceCreated(e){return this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1,this._internalInit(e),this}_internalInit(e){if(typeof e=="object")for(const t of Object.keys(e)){const i=e[t];typeof i!="function"&&(this[t]=i)}}__internalAwake(){this.__didAwake||(this.__didAwake=!0,this.awake())}__internalStart(){this.__didStart||(this.__didStart=!0,this.start&&this.start())}__internalEnable(e){return this.__destroyed?(T()&&console.warn("[Needle Engine Dev] Trying to enable destroyed component"),!1):this.__didAwake?this.__didEnable?(e!==!0&&(this.__isEnabled=!0),!1):(this.__didEnable=!0,this.__isEnabled=!0,this.onEnable(),!0):!1}__internalDisable(e){if(this.__didAwake){if(!this.__didEnable){e!==!0&&(this.__isEnabled=!1);return}this.__didEnable=!1,this.__isEnabled=!1,this.onDisable()}}__internalDestroy(){this.__destroyed||(this.__destroyed=!0,this.__didAwake&&(this.onDestroy?.call(this),this.dispatchEvent(new CustomEvent("destroyed",{detail:this}))),s0(this),Qp()&&D0(this))}get enabled(){return typeof this.__isEnabled=="boolean"?this.__isEnabled:!0}set enabled(e){if(this.__destroyed){T()&&console.warn(`[Needle Engine Dev] Trying to ${e?"enable":"disable"} destroyed component`);return}if(typeof e=="number"&&(e>=.5?e=!0:e=!1),!this.__didAwake){this.__isEnabled=e;return}e?this.__internalEnable():this.__internalDisable()}get worldPosition(){return Q(this.gameObject)}set worldPosition(e){rt(this.gameObject,e)}setWorldPosition(e,t,i){rr(this.gameObject,e,t,i)}get worldQuaternion(){return fe(this.gameObject)}set worldQuaternion(e){ln(this.gameObject,e)}setWorldQuaternion(e,t,i,n){Pm(this.gameObject,e,t,i,n)}get worldEuler(){return Mm(this.gameObject)}set worldEuler(e){Om(this.gameObject,e)}get worldRotation(){return this.gameObject.worldRotation}set worldRotation(e){this.setWorldRotation(e.x,e.y,e.z,!0)}setWorldRotation(e,t,i,n=!0){Ic(this.gameObject,e,t,i,n)}static _forward=new c.Vector3;get forward(){return E._forward.set(0,0,-1).applyQuaternion(this.worldQuaternion)}static _right=new c.Vector3;get right(){return E._right.set(1,0,0).applyQuaternion(this.worldQuaternion)}static _up=new c.Vector3;get up(){return E._up.set(0,1,0).applyQuaternion(this.worldQuaternion)}_eventListeners=new Map;addEventListener(e,t){this._eventListeners[e]=this._eventListeners[e]||[],this._eventListeners[e].push(t)}removeEventListener(e,t){if(!this._eventListeners[e])return;const i=this._eventListeners[e].indexOf(t);i>=0&&this._eventListeners[e].splice(i,1)}dispatchEvent(e){if(!e||!this._eventListeners[e.type])return!1;const t=this._eventListeners[e.type];for(let i=0;i<t.length;i++)t[i](e);return!1}}const yP=Object.freeze(Object.defineProperty({__proto__:null,Behaviour:E,Component:E,GameObject:S},Symbol.toStringTag,{value:"Module"}));var _P=Object.defineProperty,L0=(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&&_P(e,t,n),n};class Wc extends E{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new c.Vector3}update(){if(!this.from||!this.to)return;const e=Q(this.from).clone(),t=Q(this.to).clone(),i=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),rt(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(Q(this.to).clone()),this.gameObject.scale.set(this.width,this.width,i)}}L0([f(S)],Wc.prototype,"from");L0([f(S)],Wc.prototype,"to");var bP=Object.defineProperty,vP=Object.getOwnPropertyDescriptor,_r=(s,e,t,i)=>{for(var n=i>1?void 0:i?vP(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&&bP(e,t,n),n};const Ls=x("debuganimation");let I0=class{x;y};class Et extends E{get isAnimationComponent(){return!0}addClip(e){this.animations||(this.animations=[]),this.animations.includes(e)||this.animations.push(e)}playAutomatically=!0;randomStartTime=!1;minMaxSpeed;minMaxOffsetNormalized;loop=!0;clampWhenFinished=!1;get time(){if(this.actions){for(const e of this.actions)if(e.isRunning())return e.time}return 0}set time(e){if(this.actions)for(const t of this.actions)t.time=e}get duration(){if(this.actions){for(const e of this.actions)if(e.isRunning())return e.getClip().duration}return 0}_tempAnimationClipBeforeGameObjectExisted=null;get clip(){return this.animations?.length?this.animations[0]:null}set clip(e){if(!this.__didAwake){Ls&&console.warn("Assign clip during serialization",e),this._tempAnimationClipBeforeGameObjectExisted=e;return}e&&(this.gameObject.animations||(this.gameObject.animations=[]),!this.animations.includes(e)&&(this.animations.length>0?this.animations.splice(0,0,e):this.animations.push(e)))}set clips(e){this.animations=e}_tempAnimationsArray;set animations(e){e==null||!Array.isArray(e)||(this.gameObject?this.gameObject.animations=e:this._tempAnimationsArray=e)}get animations(){return this.gameObject?.animations||this._tempAnimationsArray||[]}mixer=void 0;get actions(){return this._actions}set actions(e){this._actions=e}_actions;_handles;awake(){this.mixer=void 0,Ls&&console.log("Animation Awake",this.name,this),this._tempAnimationsArray&&(this.animations=this._tempAnimationsArray,this._tempAnimationsArray=void 0),this._tempAnimationClipBeforeGameObjectExisted&&(this.clip=this._tempAnimationClipBeforeGameObjectExisted,this._tempAnimationClipBeforeGameObjectExisted=null),this.actions=[],this._handles=[]}onEnable(){if(this.playAutomatically&&this.animations?.length>0){const e=Math.floor(Math.random()*this.animations.length),t=this.animations[e];this.play(e,{exclusive:!0,fadeDuration:0,startTime:this.randomStartTime?Math.random()*t.duration:0,loop:this.loop,clampWhenFinished:this.clampWhenFinished})}}update(){this.mixer&&(this.mixer.update(this.context.time.deltaTime),this._handles.forEach(e=>e.update()))}onDisable(){this.mixer&&this.mixer.stopAllAction()}onDestroy(){this.context.animations.unregisterAnimationMixer(this.mixer)}getAction(e){return this.actions?.find(t=>t.getClip().name===e)||null}get isPlaying(){if(this.actions){for(let e=0;e<this.actions.length;e++)if(this.actions[e].isRunning())return!0}return!1}stopAll(e){if(this.actions)for(const t of this.actions)e?.fadeDuration?t.fadeOut(e.fadeDuration):t.stop()}stop(e,t){if(e===void 0){this.stopAll();return}else if(typeof e=="number"){if(e>=this.animations.length){Ls&&console.log("No animation at index",e);return}e=this.animations[e]}else typeof e=="string"&&(e=this.animations.find(n=>n.name===e));if(!e){console.error("Could not find clip",e);return}const i=this.actions.find(n=>n.getClip()===e);if(!i){console.error("Could not find action",e);return}t?.fadeDuration?i.fadeOut(t.fadeDuration):i.stop()}pause(e,t=!1){if(e===void 0){for(const n of this.actions)n.paused=!t;return}else if(typeof e=="number"){if(e>=this.animations.length){Ls&&console.log("No animation at index",e);return}e=this.animations[e]}else typeof e=="string"&&(e=this.animations.find(n=>n.name===e));if(!e){console.error("Could not find clip",e);return}const i=this.actions.find(n=>n.getClip()===e);if(!i){console.error("Could not find action",e);return}i.paused=!t}resume(){for(const e of this.actions)e.paused=!1}play(e=0,t){if(Ls&&console.log("PLAY",e),this.ensureMixer(),!this.mixer){Ls&&console.warn("Missing mixer",this);return}e===void 0&&(e=0);let i=e;if(typeof e=="number"){if(e>=this.animations.length){Ls&&console.log("No animation at index",e);return}i=this.animations[e]}else typeof e=="string"&&(i=this.animations.find(o=>o.name===e));if(!i){console.error("Could not find clip",e);return}t||(t={});for(const o of this.actions)if(o.getClip()===i)return this.internalOnPlay(o,t);if(!i.tracks){console.warn("Clip is no AnimationClip",i);return}const n=this.mixer.clipAction(i);return this.actions.push(n),this.internalOnPlay(n,t)}internalOnPlay(e,t){var i=this.actions.find(r=>r===e);if(i===e&&i.isRunning()&&i.time<i.getClip().duration){const r=this.tryFindHandle(e);if(i.paused&&(i.paused=!1),r)return r.waitForFinish()}if(t.loop===void 0&&(t.loop=this.loop),t.clampWhenFinished===void 0&&(t.clampWhenFinished=this.clampWhenFinished),t.minMaxOffsetNormalized===void 0&&this.randomStartTime&&(t.minMaxOffsetNormalized=this.minMaxOffsetNormalized),t.minMaxSpeed===void 0&&(t.minMaxSpeed=this.minMaxSpeed),t?.exclusive??!0)for(const r of this.actions)r!=i&&(t.fadeDuration?r.fadeOut(t.fadeDuration):r.stop());if(t?.fadeDuration&&e.fadeIn(t.fadeDuration),e.enabled=!0,t?.startTime!=null)e.time=t.startTime;else if(t?.minMaxOffsetNormalized&&t.minMaxOffsetNormalized.x!=0&&t.minMaxOffsetNormalized.y!=0){const r=e.getClip();e.time=I.lerp(t.minMaxOffsetNormalized.x,t.minMaxOffsetNormalized.y,Math.random())*r.duration}else e.time>=e.getClip().duration&&(e.time=0);t?.minMaxSpeed?e.timeScale=I.lerp(t.minMaxSpeed.x,t.minMaxSpeed.y,Math.random()):e.timeScale=t?.speed??1,t?.loop!=null?e.loop=t.loop?c.LoopRepeat:c.LoopOnce:e.loop=c.LoopOnce,t?.clampWhenFinished&&(e.clampWhenFinished=!0),e.paused=!1,e.play(),window.requestAnimationFrame(()=>Nn.testIfRootCanAnimate(e)),Ls&&console.log("PLAY",e.getClip().name,e);const o=new wP(e,this.mixer,t,r=>{this._handles.splice(this._handles.indexOf(o),1)});return this._handles.push(o),o.waitForFinish()}tryFindHandle(e){for(const t of this._handles)if(t.action===e)return t}ensureMixer(){if(!this.mixer){const e="animationMixer";this.gameObject[e]&&(this.mixer=this.gameObject[e]),(!this.mixer||!this.mixer.clipAction)&&(this.mixer=new c.AnimationMixer(this.gameObject),this.gameObject[e]=this.mixer)}this.context.animations.registerAnimationMixer(this.mixer)}}_r([f()],Et.prototype,"playAutomatically",2);_r([f()],Et.prototype,"randomStartTime",2);_r([f(I0)],Et.prototype,"minMaxSpeed",2);_r([f(I0)],Et.prototype,"minMaxOffsetNormalized",2);_r([f()],Et.prototype,"loop",2);_r([f()],Et.prototype,"clampWhenFinished",2);_r([f(c.AnimationClip)],Et.prototype,"clips",1);class wP{mixer;action;promise=null;_options;_resolveCallback=null;_resolvedOrRejectedCallback;constructor(e,t,i,n){this.action=e,this.mixer=t,this._resolvedOrRejectedCallback=n,this._options=i}waitForFinish(){return this.promise?this.promise:(this.promise=new Promise(e=>{this._resolveCallback=e}),this.mixer.addEventListener("finished",this.onFinished),this.promise)}update(){this._options&&this._options.endTime!==void 0&&this.action.time>this._options.endTime&&(this._options.loop===!0?this.action.time=this._options.startTime??0:(this.action.time=this._options.endTime,this.action.timeScale=0,this.onResolve()))}onResolve(){this.dispose(),this._resolvedOrRejectedCallback?.call(this,this),this._resolveCallback?.call(this,this.action)}onFinished=e=>{e.action===this.action&&this.onResolve()};dispose(){this.mixer.removeEventListener("finished",this.onFinished)}}const md=Symbol("objectIsAnimatedData");function j_(s,e,t){if(!s)return;if(s[md]===void 0){if(!t)return;s[md]=new Set}const i=s[md];t?i.add(e):i.has(e)&&i.delete(e)}function xP(s){if(!s)return!1;const e=s[md];return e!==void 0&&e.size>0}class SP{_context;get context(){return this._context??U.Current}get isStateMachineBehaviour(){return!0}}class jl{name;nameHash;normalizedTime;length;speed;action;hasTransitions;constructor(e,t,i,n){this.name=e.name,this.nameHash=e.hash,this.normalizedTime=t,this.length=i,this.speed=n,this.action=e.motion.action||null,this.hasTransitions=e.transitions?.length>0||!1}}function j0(s,e){return{name:"Empty",isLooping:!1,guid:e?.generateUUID()??c.MathUtils.generateUUID(),index:-1,clip:new c.AnimationClip(s,0,[])}}var Gs=(s=>(s[s.If=1]="If",s[s.IfNot=2]="IfNot",s[s.Greater=3]="Greater",s[s.Less=4]="Less",s[s.Equals=6]="Equals",s[s.NotEqual=7]="NotEqual",s))(Gs||{}),sg=(s=>(s[s.Float=1]="Float",s[s.Int=3]="Int",s[s.Bool=4]="Bool",s[s.Trigger=9]="Trigger",s))(sg||{});const Qe=x("debuganimatorcontroller"),Fh=x("debugrootmotion");class zi{static createFromClips(e,t={looping:!1,autoTransition:!0,transitionDuration:0}){const i=[];for(let r=0;r<e.length;r++){const a=e[r],l=[];if(t.autoTransition!==!1){const d=t.transitionDuration??0,u=d/a.duration;let p=r;(t.autoTransition===void 0||t.autoTransition===!0)&&(p=(r+1)%e.length),l.push({exitTime:1-u,offset:0,duration:d,hasExitTime:!0,destinationState:p,conditions:[]})}const h={name:a.name,hash:r,motion:{name:a.name,clip:a,isLooping:t?.looping??!1},transitions:l,behaviours:[]};i.push(h)}const n={name:"AnimatorController",guid:new _t(Date.now()).generateUUID(),parameters:[],layers:[{name:"Base Layer",stateMachine:{defaultState:0,states:i}}]};return new zi(n)}play(e,t=-1,i=Number.NEGATIVE_INFINITY,n=0){if(t<0)t=0;else if(t>=this.model.layers.length){console.warn("invalid layer");return}const r=this.model.layers[t].stateMachine;for(const a of r.states)if(a.name===e||a.hash===e){Qe&&console.log("transition to ",a),this.transitionTo(a,n,i);return}console.warn("Could not find "+e+" to play")}reset(){this.setStartTransition()}setBool(e,t){const i=typeof e=="string"?"name":"hash";return this.model?.parameters?.filter(n=>n[i]===e).forEach(n=>n.value=t)}getBool(e){const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.find(i=>i[t]===e)?.value??!1}setFloat(e,t){const i=typeof e=="string"?"name":"hash",n=this.model?.parameters?.filter(o=>o[i]===e);return n.forEach(o=>o.value=t),n?.length>0}getFloat(e){const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.find(i=>i[t]===e)?.value??0}setInteger(e,t){const i=typeof e=="string"?"name":"hash";return this.model?.parameters?.filter(n=>n[i]===e).forEach(n=>n.value=t)}getInteger(e){const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.find(i=>i[t]===e)?.value??0}setTrigger(e){Qe&&console.log("SET TRIGGER",e);const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.filter(i=>i[t]===e).forEach(i=>i.value=!0)}resetTrigger(e){const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.filter(i=>i[t]===e).forEach(i=>i.value=!1)}getTrigger(e){const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.find(i=>i[t]===e)?.value??!1}isInTransition(){return this._activeStates.length>1}setSpeed(e){this._speed=e}_speed=1;FindState(e){return this.findState(e)}findState(e){if(!e)return null;if(Array.isArray(this.model.layers)){for(const t of this.model.layers)for(const i of t.stateMachine.states)if(i.name===e||i.hash==e)return i}return null}getCurrentStateInfo(){if(!this._activeState)return null;const e=this._activeState.motion.action;if(!e)return null;const t=this._activeState.motion.clip.duration,i=t<=0?0:Math.abs(e.time/t);return new jl(this._activeState,i,t,this._speed)}get currentAction(){if(!this._activeState)return null;const e=this._activeState.motion.action;return e||null}normalizedStartOffset=0;animator;model;get context(){return this.animator?.context}get mixer(){return this._mixer}dispose(){if(this._mixer.stopAllAction(),this.animator){this._mixer.uncacheRoot(this.animator.gameObject);for(const e of this._activeStates)e.motion.clip&&this.mixer.uncacheAction(e.motion.clip,this.animator.gameObject)}this.context?.animations.unregisterAnimationMixer(this._mixer)}bind(e){e?this.animator!==e&&(this._mixer&&(this._mixer.stopAllAction(),this.context?.animations.unregisterAnimationMixer(this._mixer)),this.animator=e,this._mixer=new c.AnimationMixer(this.animator.gameObject),this.context?.animations.registerAnimationMixer(this._mixer),this.createActions(this.animator)):console.error("AnimatorController.bind: animator is null")}clone(){if(typeof this.model=="string")return console.warn("AnimatorController has not been resolved, can not create model from string",this.model),null;Qe&&console.warn("AnimatorController clone()",this.model);const e=Ac(this.model,(i,n,o)=>o==null?!0:!(o.type==="Object3D"||o.isObject3D===!0||tv(o)||o.tracks!==void 0||o instanceof zi));return console.assert(e!==this.model),new zi(e)}update(e){if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates(e);const t=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&this.rootMotionHandler?.onBeforeUpdate(e),this._mixer.update(t),this.animator.applyRootMotion&&this.rootMotionHandler?.onAfterUpdate(e)}_mixer;_activeState;get activeState(){return this._activeState}constructor(e){this.model=e,Qe&&console.log(this)}_activeStates=[];updateActiveStates(e){for(let t=0;t<this._activeStates.length;t++){const i=this._activeStates[t],n=i.motion;if(!n.action)this._activeStates.splice(t,1),t--;else{const o=n.action;o.weight=e,o.getEffectiveWeight()<=0&&!o.isRunning()&&(Qe&&console.debug("REMOVE",i.name,o.getEffectiveWeight(),o.isRunning(),o.isScheduled()),this._activeStates.splice(t,1),t--)}}}setStartTransition(){this.model.layers.length>1&&(Qe||T())&&console.warn("Multiple layers are not supported yet "+this.animator?.name);for(const e of this.model.layers){const t=e.stateMachine;t.defaultState===void 0&&(Qe&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",e),t.defaultState=0);const i=t.states[t.defaultState];this.transitionTo(i,0,this.normalizedStartOffset);break}}evaluateTransitions(){let e=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;e=!0}const t=this._activeState,i=t.motion.action;for(const o of t.transitions){if(!o.hasExitTime&&o.conditions.length<=0)continue;let r=!0;for(const a of o.conditions)if(!this.evaluateCondition(a)){r=!1;break}if(r)if(i){const a=t.motion.clip.duration,l=a<=0?1:Math.abs(i.time/a);let h=o.exitTime;i.timeScale<0&&(h=1-h);let d=!1;if(o.hasExitTime?i.timeScale>0?d=l>=o.exitTime:i.timeScale<0&&(d=1-l>=o.exitTime):d=!0,d){for(const u of o.conditions){const p=this.model.parameters.find(m=>m.name===u.parameter);p?.type===sg.Trigger&&p.value&&(p.value=!1)}if(i.clampWhenFinished=!0,Qe){const u=this.getState(o.destinationState,0);console.log(`Transition to ${o.destinationState} / ${u?.name}`,o,`
|
|
887
887
|
Timescale: `+i.timeScale,`
|
|
888
888
|
Normalized time: `+l.toFixed(3),`
|
|
889
|
-
Exit Time: `+h,o.hasExitTime)}this.transitionTo(o.destinationState,o.duration,o.offset);return}}else{this.transitionTo(o.destinationState,o.duration,o.offset);return}}i&&this.setTimescale(i,t);let n=!1;if(t.motion.isLooping&&i&&(i.time>=i.getClip().duration?(n=!0,i.reset(),i.time=0,i.play()):i.time<=0&&i.timeScale<0&&(n=!0,i.reset(),i.time=i.getClip().duration,i.play())),!n&&t&&!e&&i&&this.animator&&t.behaviours){const o=i?.getClip().duration,r=i.time/o,a=new jl(this._activeState,r,o,this._speed);for(const l of t.behaviours)l.instance&&l.instance.onStateUpdate?.call(l.instance,this.animator,a,0)}}setTimescale(e,t){let i=t.speed??1;t.speedParameter&&(i*=this.getFloat(t.speedParameter)),i!==void 0&&(e.timeScale=i*this._speed)}getState(e,t){return typeof e=="number"&&(e==-1&&(e=this.model.layers[t].stateMachine.defaultState,e===void 0&&(Xe&&console.warn("AnimatorController default state is undefined: ",this.model,"Layer: "+t),e=0)),e=this.model.layers[t].stateMachine.states[e]),e}_heldActions=[];releaseHeldActions(e){for(const t of this._heldActions)t.fadeOut(e);this._heldActions.length=0}transitionTo(e,t,i){if(!this.animator)return;const n=0;if(e=this.getState(e,n),!e?.motion||!e.motion.clip||!(e.motion.clip instanceof c.AnimationClip))return;const o=this._activeState===e;if(o){const d=e.motion;if(!d.action_loopback&&d.clip){const u=this.rootMotionHandler?this.animator.gameObject.matrix.clone():null;this._mixer.uncacheAction(d.clip,this.animator.gameObject),u&&u.decompose(this.animator.gameObject.position,this.animator.gameObject.quaternion,this.animator.gameObject.scale),d.action_loopback=this.createAction(d.clip)}}if(this._activeState?.behaviours&&this._activeState.motion.action){const d=this._activeState?.motion.clip.duration,u=this._activeState.motion.action.time/d,p=new jl(this._activeState,u,d,this._speed);for(const m of this._activeState.behaviours)m.instance?.onStateExit?.call(m.instance,this.animator,p,n)}const r=this._activeState?.motion.action;o&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=r);const a=this._activeState;this._activeState=e;const l=e.motion?.action,h=e.motion.clip;if(h?.duration<=0&&h.tracks.length<=0?r&&this._heldActions.push(r):r&&(r.fadeOut(t),this.releaseHeldActions(t)),l){if(i=Math.max(0,Math.min(1,i)),e.cycleOffsetParameter){let u=this.getFloat(e.cycleOffsetParameter);typeof u=="number"?(u<0&&(u+=1),i+=u,i%=1):Xe&&console.warn("AnimatorController cycle offset parameter is not a number",e.cycleOffsetParameter)}else typeof e.cycleOffset=="number"&&(i+=e.cycleOffset,i%=1);l.isRunning()&&l.stop(),l.reset(),l.enabled=!0,this.setTimescale(l,e);const d=e.motion.clip.duration;if(l.time=o?0:i*d,l.timeScale<0&&(l.time=d-l.time),l.clampWhenFinished=!0,l.setLoop(c.LoopOnce,0),t>0?l.fadeIn(t):l.weight=1,l.play(),window.requestAnimationFrame(()=>Nn.testIfRootCanAnimate(l)),this.rootMotionHandler&&this.rootMotionHandler.onStart(l),this._activeStates.includes(e)||this._activeStates.push(e),this._activeState.behaviours){const u=new jl(e,i,d,this._speed);for(const p of this._activeState.behaviours)p.instance?.onStateEnter?.call(p.instance,this.animator,u,n)}}else Xe&&(e.__warned_no_motion||(e.__warned_no_motion=!0,console.warn("No action",e.motion,this)));Xe&&console.log("TRANSITION FROM "+a?.name+" TO "+e.name,t,r,l,l?.getEffectiveTimeScale(),l?.getEffectiveWeight(),l?.isRunning(),l?.isScheduled(),l?.paused)}createAction(e){if(this._mixer.existingAction(e)&&this._mixer.uncacheAction(e,this.animator?.gameObject),this.animator?.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new CP(this));const i=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,i,e)}else return this._mixer.clipAction(e)}evaluateCondition(e){const t=this.model.parameters.find(i=>i.name===e.parameter);if(!t)return!1;switch(e.mode){case Gs.If:return t.value===!0;case Gs.IfNot:return t.value===!1;case Gs.Greater:return t.value>e.threshold;case Gs.Less:return t.value<e.threshold;case Gs.Equals:return t.value===e.threshold;case Gs.NotEqual:return t.value!==e.threshold}return!1}createActions(e){Xe&&console.log("AnimatorController createActions",this.model);for(const t of this.model.layers){const i=t.stateMachine;for(let n=0;n<i.states.length;n++){const o=i.states[n];o.transitions||(o.transitions=[]);for(const r of o.transitions)r.conditions||(r.conditions=[]);if(o.motion||(Xe&&console.warn("No motion",o),o.motion=j0(o.name)),this.animator&&o.motion.clips){const r=o.motion.clips?.find(a=>a.node.name===this.animator?.gameObject?.name);r?o.motion.clip=r.clip:(Xe||T())&&console.warn('Could not find clip for animator "'+this.animator?.gameObject?.name+'"',o.motion.clips.map(a=>a.node.name))}if(!o.motion.clip){Xe&&console.warn("No clip assigned to state",o);const r=new c.AnimationClip(void 0,void 0,[]);o.motion.clip=r}if(o.motion?.clip){const r=o.motion.clip;if(r instanceof c.AnimationClip){const a=this.createAction(r);o.motion.action=a}else(Xe||T())&&console.warn("No valid animationclip assigned",o)}if(o.behaviours&&Array.isArray(o.behaviours))for(const r of o.behaviours){if(!r?.typeName)continue;const a=P.get(r.typeName);if(a){const l=new a;l.isStateMachineBehaviour&&(l._context=this.context??void 0,Ra(l,r.properties),r.instance=l),Xe&&console.log("Created animator controller behaviour",o.name,r.typeName,r.properties,l)}else(Xe||T())&&console.warn("Could not find AnimatorBehaviour type: "+r.typeName)}}}}*enumerateActions(){if(this.model.layers)for(const e of this.model.layers){const t=e.stateMachine;for(let i=0;i<t.states.length;i++){const n=t.states[i];n?.motion&&(n.motion.action&&(yield n.motion.action),n.motion.action_loopback&&(yield n.motion.action_loopback))}}}rootMotionHandler}class B_{track;createdInterpolant;originalEvaluate;customEvaluate;constructor(e,t){this.track=e;const i=e,n=i.createInterpolant.bind(e);i.createInterpolant=()=>(i.createInterpolant=n,this.createdInterpolant=n(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=o=>{if(!this.originalEvaluate)return;const r=this.originalEvaluate(o);return t(o,r)},this.createdInterpolant.evaluate=this.customEvaluate,this.createdInterpolant)}dispose(){this.createdInterpolant&&this.originalEvaluate&&(this.createdInterpolant.evaluate=this.originalEvaluate),this.track=void 0,this.createdInterpolant=null,this.originalEvaluate=void 0,this.customEvaluate=void 0}}class Ye{static lastObjPosition={};static lastObjRotation={};static firstKeyframeRotation={};static spaceRotation={};static effectiveSpaceRotation={};static clipOffsetRotation={};set action(e){this._action=e}get action(){return this._action}get cacheId(){return this.root.uuid}_action;root;clip;positionWrapper=null;rotationWrapper=null;context;positionChange=new c.Vector3;rotationChange=new c.Quaternion;constructor(e,t,i,n,o){if(this.context=e,this.root=t,this.clip=i,Ye.firstKeyframeRotation[this.cacheId]||(Ye.firstKeyframeRotation[this.cacheId]=new c.Quaternion),o){const r=o.values;Ye.firstKeyframeRotation[this.cacheId].set(r[0],r[1],r[2],r[3])}Ye.spaceRotation[this.cacheId]||(Ye.spaceRotation[this.cacheId]=new c.Quaternion),Ye.effectiveSpaceRotation[this.cacheId]||(Ye.effectiveSpaceRotation[this.cacheId]=new c.Quaternion),Ye.clipOffsetRotation[this.cacheId]=new c.Quaternion,o&&Ye.clipOffsetRotation[this.cacheId].set(o.values[0],o.values[1],o.values[2],o.values[3]).invert(),this.handlePosition(i,n),this.handleRotation(i,o)}onStart(e){if(e.getClip()!==this.clip)return;Ye.lastObjRotation[this.cacheId]||(Ye.lastObjRotation[this.cacheId]=this.root.quaternion.clone());const t=Ye.lastObjRotation[this.cacheId];if(Ye.spaceRotation[this.cacheId].copy(t),Fh){const i=new c.Euler().setFromQuaternion(t);console.log("START",this.clip.name,I.toDegrees(i.y),this.root.position.z)}}getClipRotationOffset(){return Ye.clipOffsetRotation[this.cacheId]}_prevTime=0;handlePosition(e,t){if(t){const i=this.root;Fh&&i.add(new c.AxesHelper),Ye.lastObjPosition[this.cacheId]||(Ye.lastObjPosition[this.cacheId]=this.root.position.clone());const n=new c.Vector3,o=new c.Vector3;this.positionWrapper=new B_(t,(r,a)=>{const l=this.action.getEffectiveWeight();return Fh&&i.position.length()>8&&i.position.set(0,i.position.y,0),r>this._prevTime&&(n.set(a[0],a[1],a[2]),n.sub(o),n.multiplyScalar(l),n.applyQuaternion(this.getClipRotationOffset()),n.applyQuaternion(i.quaternion),this.positionChange.copy(n)),o.fromArray(a),this._prevTime=r,a[0]=0,a[1]=0,a[2]=0,a})}}static identityQuaternion=new c.Quaternion;handleRotation(e,t){if(t){if(Fh){const r=t.values,a=new c.Euler().setFromQuaternion(new c.Quaternion(r[0],r[1],r[2],r[3]));console.log(e.name,t.name,"FIRST ROTATION IN TRACK",I.toDegrees(a.y));const l=t.values.length-4,h=new c.Quaternion().set(r[l],r[l+1],r[l+2],r[l+3]),d=new c.Euler().setFromQuaternion(h);console.log(e.name,t.name,"LAST ROTATION IN TRACK",I.toDegrees(d.y))}let i=0;const n=new c.Quaternion,o=new c.Quaternion;this.rotationWrapper=new B_(t,(r,a)=>(r>i&&(o.set(a[0],a[1],a[2],a[3]),n.invert(),o.multiply(n),this.rotationChange.copy(o)),n.fromArray(a),i=r,a[0]=0,a[1]=0,a[2]=0,a[3]=1,a))}}onBeforeUpdate(e){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(e){return!this.action||(e*=this.action.getEffectiveWeight(),e<=0)?!1:(this.positionChange.multiplyScalar(e),this.rotationChange.slerp(Ye.identityQuaternion,1-e),!0)}}class CP{controller;handler=[];root;basePosition=new c.Vector3;baseQuaternion=new c.Quaternion;baseRotation=new c.Euler;constructor(e){this.controller=e}createClip(e,t,i){this.root=t,t&&"name"in t&&t.name;const n=this.findRootTrack(i,".position"),o=this.findRootTrack(i,".quaternion"),r=new Ye(this.controller.context,t,i,n,o);this.handler.push(r);const a=e.clipAction(i);return r.action=a,a}onStart(e){for(const t of this.handler)t.onStart(e)}onBeforeUpdate(e){this.basePosition.copy(this.root.position),this.baseQuaternion.copy(this.root.quaternion);for(const t of this.handler)t.onBeforeUpdate(e)}summedPosition=new c.Vector3;summedRotation=new c.Quaternion;onAfterUpdate(e){if(!(e<=0)){this.root.position.copy(this.basePosition),this.root.quaternion.copy(this.baseQuaternion),this.summedPosition.set(0,0,0),this.summedRotation.set(0,0,0,1);for(const t of this.handler)t.onAfterUpdate(e)&&(this.summedPosition.add(t.positionChange),this.summedRotation.multiply(t.rotationChange));this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation)}}findRootTrack(e,t){const i=e.tracks;if(!i)return null;for(const n of i)if(n.name.endsWith(t))return n;return null}}class PP extends $i{onSerialize(e,t){}onDeserialize(e,t){if(t.type===zi&&e?.__type==="AnimatorController")return new zi(e)}}new PP(zi);var MP=Object.defineProperty,OP=Object.getOwnPropertyDescriptor,mu=(s,e,t,i)=>{for(var n=i>1?void 0:i?OP(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&&MP(e,t,n),n};const Ei=x("debuganimator");class at extends E{get isAnimationComponent(){return!0}applyRootMotion=!1;hasRootMotion=!1;keepAnimatorControllerStateOnDisable=!1;set runtimeAnimatorController(e){this._animatorController&&this._animatorController.model===e||(e?e instanceof zi?(e.animator&&e.animator!==this&&(console.warn("AnimatorController can not be bound to multiple animators",e.model?.name),e.model||console.error("AnimatorController has no model"),e=new zi(e.model)),this._animatorController=e,this._animatorController.bind(this)):(Ei&&console.log("Assign animator controller",e,this),this._animatorController=new zi(e),this.__didAwake&&this._animatorController.bind(this)):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}getCurrentStateInfo(){return this.runtimeAnimatorController?.getCurrentStateInfo()}get currentAction(){return this.runtimeAnimatorController?.currentAction||null}get parametersAreDirty(){return this._parametersAreDirty}_parametersAreDirty=!1;get isDirty(){return this._isDirty}_isDirty=!1;Play(e,t=-1,i=Number.NEGATIVE_INFINITY,n=0){this.play(e,t,i,n)}play(e,t=-1,i=Number.NEGATIVE_INFINITY,n=0){this.runtimeAnimatorController?.play(e,t,i,n),this._isDirty=!0}Reset(){this.reset()}reset(){this._animatorController?.reset(),this._isDirty=!0}SetBool(e,t){this.setBool(e,t)}setBool(e,t){Ei&&console.log("setBool",e,t),this.runtimeAnimatorController?.getBool(e)!==t&&(this._parametersAreDirty=!0),this.runtimeAnimatorController?.setBool(e,t)}GetBool(e){return this.getBool(e)}getBool(e){const t=this.runtimeAnimatorController?.getBool(e)??!1;return Ei&&console.log("getBool",e,t),t}toggleBool(e){this.setBool(e,!this.getBool(e))}SetFloat(e,t){this.setFloat(e,t)}setFloat(e,t){this.runtimeAnimatorController?.getFloat(e)!==t&&(this._parametersAreDirty=!0),Ei&&console.log("setFloat",e,t),this.runtimeAnimatorController?.setFloat(e,t)}GetFloat(e){return this.getFloat(e)}getFloat(e){const t=this.runtimeAnimatorController?.getFloat(e)??-1;return Ei&&console.log("getFloat",e,t),t}SetInteger(e,t){this.setInteger(e,t)}setInteger(e,t){this.runtimeAnimatorController?.getInteger(e)!==t&&(this._parametersAreDirty=!0),Ei&&console.log("setInteger",e,t),this.runtimeAnimatorController?.setInteger(e,t)}GetInteger(e){return this.getInteger(e)}getInteger(e){const t=this.runtimeAnimatorController?.getInteger(e)??-1;return Ei&&console.log("getInteger",e,t),t}SetTrigger(e){this.setTrigger(e)}setTrigger(e){this._parametersAreDirty=!0,Ei&&console.log("setTrigger",e),this.runtimeAnimatorController?.setTrigger(e)}ResetTrigger(e){this.resetTrigger(e)}resetTrigger(e){this._parametersAreDirty=!0,Ei&&console.log("resetTrigger",e),this.runtimeAnimatorController?.resetTrigger(e)}GetTrigger(e){this.getTrigger(e)}getTrigger(e){const t=this.runtimeAnimatorController?.getTrigger(e);return Ei&&console.log("getTrigger",e,t),t}IsInTransition(){return this.isInTransition()}isInTransition(){return this.runtimeAnimatorController?.isInTransition()??!1}SetSpeed(e){return this.setSpeed(e)}setSpeed(e){e!==this._speed&&(Ei&&console.log("setSpeed",e),this._speed=e,this._animatorController?.animator==this&&this._animatorController.setSpeed(e))}set minMaxSpeed(e){this._speed=I.lerp(e.x,e.y,Math.random()),this._animatorController?.animator==this&&this._animatorController.setSpeed(this._speed)}set minMaxOffsetNormalized(e){this._normalizedStartOffset=I.lerp(e.x,e.y,Math.random()),this.runtimeAnimatorController?.animator==this&&(this.runtimeAnimatorController.normalizedStartOffset=this._normalizedStartOffset)}_speed=1;_normalizedStartOffset=0;_animatorController=null;awake(){Ei&&console.log("ANIMATOR",this.name,this),this.gameObject&&this.initializeRuntimeAnimatorController()}_initializeWithRuntimeAnimatorController;initializeRuntimeAnimatorController(e=!1){const t=e||this.runtimeAnimatorController!==this._initializeWithRuntimeAnimatorController;if(this.runtimeAnimatorController&&t){const i=this.runtimeAnimatorController.clone();this._initializeWithRuntimeAnimatorController=i,i?(console.assert(this.runtimeAnimatorController!==i),this.runtimeAnimatorController=i,console.assert(this.runtimeAnimatorController===i),this.runtimeAnimatorController.bind(this),this.runtimeAnimatorController.setSpeed(this._speed),this.runtimeAnimatorController.normalizedStartOffset=this._normalizedStartOffset):console.warn("Could not clone animator controller",this.runtimeAnimatorController)}}onDisable(){this.keepAnimatorControllerStateOnDisable||this._animatorController?.reset()}onBeforeRender(){this._isDirty=!1,this._parametersAreDirty=!1,!xP(this.gameObject)&&this._animatorController&&this._animatorController.update(1)}}mu([f()],at.prototype,"applyRootMotion",2);mu([f()],at.prototype,"hasRootMotion",2);mu([f()],at.prototype,"keepAnimatorControllerStateOnDisable",2);mu([f()],at.prototype,"runtimeAnimatorController",1);const U_=Symbol("previous-visibility");class Dn extends c.WebGLRenderTarget{render(e,t,i){if("addPass"in i)this._unsupported_effectcomposer_warning||(console.warn("RenderTexture.render() does not yet support EffectComposer"),this._unsupported_effectcomposer_warning=!0);else if(i instanceof c.WebGLRenderer){this.onBeforeRender();const o=i.getRenderTarget(),r=i.xr.enabled;i.xr.enabled=!1,i.setRenderTarget(this),i.clear(!0,!0,!0),i.render(e,t),i.setRenderTarget(o),i.xr.enabled=r,this.onAfterRender()}}static _userSet=new Set;onBeforeRender(){Dn._userSet.clear();const e=Vm(this.texture,!0,null,Dn._userSet);for(const t of e)t instanceof c.Mesh&&(t[U_]=t.visible,t.visible=!1)}onAfterRender(){for(const e of Dn._userSet)e instanceof c.Mesh&&(e.visible=e[U_]);Dn._userSet.clear()}}var kP=Object.defineProperty,EP=Object.getOwnPropertyDescriptor,Hc=(s,e,t,i)=>{for(var n=i>1?void 0:i?EP(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&&kP(e,t,n),n};const zh=x("debuggroundprojection");class $n extends E{applyOnAwake=!1;autoFit=!0;set radius(e){this._radius=e,this._projection&&this.updateProjection()}get radius(){return this._radius}_radius=50;set height(e){this._height=e,this._projection&&this.updateProjection()}get height(){return this._height}_height=3;set arBlending(e){this._arblending=e,this._needsTextureUpdate=!0}get arBlending(){return this._arblending}_arblending=0;_lastBackground;_lastRadius;_lastHeight;_projection;_watcher;awake(){this.applyOnAwake&&this.updateAndCreate()}onEnable(){this.context.time.frameCount>0&&this.applyOnAwake&&this.updateAndCreate(),this._watcher||(this._watcher=new hs(this.context.scene,"background"),this._watcher.subscribeWrite(e=>{zh&&console.log("Background changed",this.context.scene.background),this._needsTextureUpdate=!0}))}onDisable(){this._watcher?.revoke(),this._projection?.removeFromParent()}onEnterXR(){this.activeAndEnabled&&(this._needsTextureUpdate=!0,this.updateProjection())}async onLeaveXR(){this.activeAndEnabled&&(await Dc(1),this.updateProjection())}onBeforeRender(){this._projection&&this.scene.backgroundRotation&&this._projection.rotation.copy(this.scene.backgroundRotation),this.context.scene.backgroundBlurriness!==void 0&&this._lastBlurriness!=this.context.scene.backgroundBlurriness&&this.context.scene.backgroundBlurriness>.001?this.updateProjection():this._needsTextureUpdate&&this.context.scene.background instanceof c.Texture&&this.updateBlurriness(this.context.scene.background,this.context.scene.backgroundBlurriness)}updateAndCreate(){this.updateProjection(),this._watcher?.apply()}_needsTextureUpdate=!1;updateProjection(){if(!this.context.scene.background){this._projection?.removeFromParent();return}const e=this.context.scene.background;if(!(e instanceof c.Texture)){this._projection?.removeFromParent();return}if((this.context.xr?.isPassThrough||this.context.xr?.isAR)&&this.arBlending===0){this._projection?.removeFromParent();return}if(!this.gameObject||this.destroyed)return;let t=!0;const i=0,n=e!==this._lastBackground||this._height!==this._lastHeight||this._radius!==this._lastRadius;if(!this._projection||n){zh&&console.log("Create/Update Ground Projection",e.name),this._projection?.removeFromParent();try{this._projection=new q.GroundedSkybox(e,this._height,this._radius,64)}catch(o){console.error("Error creating three GroundProjection",o);return}this._projection.position.y=this._height-i,this._projection.name="GroundProjection",km(this._projection,!1)}else t=!1;if(this._projection.parent||this.gameObject.add(this._projection),this.autoFit&&t){this._projection.updateWorldMatrix(!0,!0);const o=Wt(this.context.scene.children,[this._projection]),r=o.min.y;if(r<1/0){const a=B();a.x=o.min.x+(o.max.x-o.min.x)*.5;const l=Le(this.gameObject).x;a.y=r+this._height*l-i,a.z=o.min.z+(o.max.z-o.min.z)*.5,rt(this._projection,a)}zh&&j.DrawWireBox3(o,65280,5)}this.context.scene.backgroundBlurriness>.001&&this._needsTextureUpdate&&this.updateBlurriness(e,this.context.scene.backgroundBlurriness),this._lastBackground=e,this._lastHeight=this._height,this._lastRadius=this._radius,this._needsTextureUpdate=!1}_blurrynessShader=null;_lastBlurriness=-1;updateBlurriness(e,t){if(this._projection){if(!e)return}else return;this._needsTextureUpdate=!1,zh&&console.log("Update Blurriness",t),this._blurrynessShader??=new c.ShaderMaterial({name:"GroundProjectionBlurriness",uniforms:{map:{value:e},blurriness:{value:t},blending:{value:0},alphaFactor:{value:1}},vertexShader:RP,fragmentShader:TP}),this._blurrynessShader.depthWrite=!1,this._blurrynessShader.uniforms.map.value=e,this._blurrynessShader.uniforms.blurriness.value=t,this._lastBlurriness=t,e.needsUpdate=!0;const i=this._projection.material.transparent;this._projection.material.transparent=(this.context.xr?.isAR===!0&&this.arBlending>1e-6)??!1,this._projection.material.transparent?this._blurrynessShader.uniforms.blending.value=this.arBlending:this._blurrynessShader.uniforms.blending.value=0,this.context.isInPassThrough?this._blurrynessShader.uniforms.alphaFactor.value=.95:this._blurrynessShader.uniforms.alphaFactor.value=1,i!==this._projection.material.transparent&&(this._projection.material.needsUpdate=!0),this._projection.material.map=so.copyTexture(e,this._blurrynessShader),this._projection.material.depthTest=!0,this._projection.material.depthWrite=!1}}Hc([f()],$n.prototype,"applyOnAwake",2);Hc([f()],$n.prototype,"autoFit",2);Hc([f()],$n.prototype,"radius",1);Hc([f()],$n.prototype,"height",1);Hc([f()],$n.prototype,"arBlending",1);const RP=`
|
|
889
|
+
Exit Time: `+h,o.hasExitTime)}this.transitionTo(o.destinationState,o.duration,o.offset);return}}else{this.transitionTo(o.destinationState,o.duration,o.offset);return}}i&&this.setTimescale(i,t);let n=!1;if(t.motion.isLooping&&i&&(i.time>=i.getClip().duration?(n=!0,i.reset(),i.time=0,i.play()):i.time<=0&&i.timeScale<0&&(n=!0,i.reset(),i.time=i.getClip().duration,i.play())),!n&&t&&!e&&i&&this.animator&&t.behaviours){const o=i?.getClip().duration,r=i.time/o,a=new jl(this._activeState,r,o,this._speed);for(const l of t.behaviours)l.instance&&l.instance.onStateUpdate?.call(l.instance,this.animator,a,0)}}setTimescale(e,t){let i=t.speed??1;t.speedParameter&&(i*=this.getFloat(t.speedParameter)),i!==void 0&&(e.timeScale=i*this._speed)}getState(e,t){return typeof e=="number"&&(e==-1&&(e=this.model.layers[t].stateMachine.defaultState,e===void 0&&(Qe&&console.warn("AnimatorController default state is undefined: ",this.model,"Layer: "+t),e=0)),e=this.model.layers[t].stateMachine.states[e]),e}_heldActions=[];releaseHeldActions(e){for(const t of this._heldActions)t.fadeOut(e);this._heldActions.length=0}transitionTo(e,t,i){if(!this.animator)return;const n=0;if(e=this.getState(e,n),!e?.motion||!e.motion.clip||!(e.motion.clip instanceof c.AnimationClip))return;const o=this._activeState===e;if(o){const d=e.motion;if(!d.action_loopback&&d.clip){const u=this.rootMotionHandler?this.animator.gameObject.matrix.clone():null;this._mixer.uncacheAction(d.clip,this.animator.gameObject),u&&u.decompose(this.animator.gameObject.position,this.animator.gameObject.quaternion,this.animator.gameObject.scale),d.action_loopback=this.createAction(d.clip)}}if(this._activeState?.behaviours&&this._activeState.motion.action){const d=this._activeState?.motion.clip.duration,u=this._activeState.motion.action.time/d,p=new jl(this._activeState,u,d,this._speed);for(const m of this._activeState.behaviours)m.instance?.onStateExit?.call(m.instance,this.animator,p,n)}const r=this._activeState?.motion.action;o&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=r);const a=this._activeState;this._activeState=e;const l=e.motion?.action,h=e.motion.clip;if(h?.duration<=0&&h.tracks.length<=0?r&&this._heldActions.push(r):r&&(r.fadeOut(t),this.releaseHeldActions(t)),l){if(i=Math.max(0,Math.min(1,i)),e.cycleOffsetParameter){let u=this.getFloat(e.cycleOffsetParameter);typeof u=="number"?(u<0&&(u+=1),i+=u,i%=1):Qe&&console.warn("AnimatorController cycle offset parameter is not a number",e.cycleOffsetParameter)}else typeof e.cycleOffset=="number"&&(i+=e.cycleOffset,i%=1);l.isRunning()&&l.stop(),l.reset(),l.enabled=!0,this.setTimescale(l,e);const d=e.motion.clip.duration;if(l.time=o?0:i*d,l.timeScale<0&&(l.time=d-l.time),l.clampWhenFinished=!0,l.setLoop(c.LoopOnce,0),t>0?l.fadeIn(t):l.weight=1,l.play(),window.requestAnimationFrame(()=>Nn.testIfRootCanAnimate(l)),this.rootMotionHandler&&this.rootMotionHandler.onStart(l),this._activeStates.includes(e)||this._activeStates.push(e),this._activeState.behaviours){const u=new jl(e,i,d,this._speed);for(const p of this._activeState.behaviours)p.instance?.onStateEnter?.call(p.instance,this.animator,u,n)}}else Qe&&(e.__warned_no_motion||(e.__warned_no_motion=!0,console.warn("No action",e.motion,this)));Qe&&console.log("TRANSITION FROM "+a?.name+" TO "+e.name,t,r,l,l?.getEffectiveTimeScale(),l?.getEffectiveWeight(),l?.isRunning(),l?.isScheduled(),l?.paused)}createAction(e){if(this._mixer.existingAction(e)&&this._mixer.uncacheAction(e,this.animator?.gameObject),this.animator?.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new CP(this));const i=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,i,e)}else return this._mixer.clipAction(e)}evaluateCondition(e){const t=this.model.parameters.find(i=>i.name===e.parameter);if(!t)return!1;switch(e.mode){case Gs.If:return t.value===!0;case Gs.IfNot:return t.value===!1;case Gs.Greater:return t.value>e.threshold;case Gs.Less:return t.value<e.threshold;case Gs.Equals:return t.value===e.threshold;case Gs.NotEqual:return t.value!==e.threshold}return!1}createActions(e){Qe&&console.log("AnimatorController createActions",this.model);for(const t of this.model.layers){const i=t.stateMachine;for(let n=0;n<i.states.length;n++){const o=i.states[n];o.transitions||(o.transitions=[]);for(const r of o.transitions)r.conditions||(r.conditions=[]);if(o.motion||(Qe&&console.warn("No motion",o),o.motion=j0(o.name)),this.animator&&o.motion.clips){const r=o.motion.clips?.find(a=>a.node.name===this.animator?.gameObject?.name);r?o.motion.clip=r.clip:(Qe||T())&&console.warn('Could not find clip for animator "'+this.animator?.gameObject?.name+'"',o.motion.clips.map(a=>a.node.name))}if(!o.motion.clip){Qe&&console.warn("No clip assigned to state",o);const r=new c.AnimationClip(void 0,void 0,[]);o.motion.clip=r}if(o.motion?.clip){const r=o.motion.clip;if(r instanceof c.AnimationClip){const a=this.createAction(r);o.motion.action=a}else(Qe||T())&&console.warn("No valid animationclip assigned",o)}if(o.behaviours&&Array.isArray(o.behaviours))for(const r of o.behaviours){if(!r?.typeName)continue;const a=P.get(r.typeName);if(a){const l=new a;l.isStateMachineBehaviour&&(l._context=this.context??void 0,Ra(l,r.properties),r.instance=l),Qe&&console.log("Created animator controller behaviour",o.name,r.typeName,r.properties,l)}else(Qe||T())&&console.warn("Could not find AnimatorBehaviour type: "+r.typeName)}}}}*enumerateActions(){if(this.model.layers)for(const e of this.model.layers){const t=e.stateMachine;for(let i=0;i<t.states.length;i++){const n=t.states[i];n?.motion&&(n.motion.action&&(yield n.motion.action),n.motion.action_loopback&&(yield n.motion.action_loopback))}}}rootMotionHandler}class B_{track;createdInterpolant;originalEvaluate;customEvaluate;constructor(e,t){this.track=e;const i=e,n=i.createInterpolant.bind(e);i.createInterpolant=()=>(i.createInterpolant=n,this.createdInterpolant=n(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=o=>{if(!this.originalEvaluate)return;const r=this.originalEvaluate(o);return t(o,r)},this.createdInterpolant.evaluate=this.customEvaluate,this.createdInterpolant)}dispose(){this.createdInterpolant&&this.originalEvaluate&&(this.createdInterpolant.evaluate=this.originalEvaluate),this.track=void 0,this.createdInterpolant=null,this.originalEvaluate=void 0,this.customEvaluate=void 0}}class Ke{static lastObjPosition={};static lastObjRotation={};static firstKeyframeRotation={};static spaceRotation={};static effectiveSpaceRotation={};static clipOffsetRotation={};set action(e){this._action=e}get action(){return this._action}get cacheId(){return this.root.uuid}_action;root;clip;positionWrapper=null;rotationWrapper=null;context;positionChange=new c.Vector3;rotationChange=new c.Quaternion;constructor(e,t,i,n,o){if(this.context=e,this.root=t,this.clip=i,Ke.firstKeyframeRotation[this.cacheId]||(Ke.firstKeyframeRotation[this.cacheId]=new c.Quaternion),o){const r=o.values;Ke.firstKeyframeRotation[this.cacheId].set(r[0],r[1],r[2],r[3])}Ke.spaceRotation[this.cacheId]||(Ke.spaceRotation[this.cacheId]=new c.Quaternion),Ke.effectiveSpaceRotation[this.cacheId]||(Ke.effectiveSpaceRotation[this.cacheId]=new c.Quaternion),Ke.clipOffsetRotation[this.cacheId]=new c.Quaternion,o&&Ke.clipOffsetRotation[this.cacheId].set(o.values[0],o.values[1],o.values[2],o.values[3]).invert(),this.handlePosition(i,n),this.handleRotation(i,o)}onStart(e){if(e.getClip()!==this.clip)return;Ke.lastObjRotation[this.cacheId]||(Ke.lastObjRotation[this.cacheId]=this.root.quaternion.clone());const t=Ke.lastObjRotation[this.cacheId];if(Ke.spaceRotation[this.cacheId].copy(t),Fh){const i=new c.Euler().setFromQuaternion(t);console.log("START",this.clip.name,I.toDegrees(i.y),this.root.position.z)}}getClipRotationOffset(){return Ke.clipOffsetRotation[this.cacheId]}_prevTime=0;handlePosition(e,t){if(t){const i=this.root;Fh&&i.add(new c.AxesHelper),Ke.lastObjPosition[this.cacheId]||(Ke.lastObjPosition[this.cacheId]=this.root.position.clone());const n=new c.Vector3,o=new c.Vector3;this.positionWrapper=new B_(t,(r,a)=>{const l=this.action.getEffectiveWeight();return Fh&&i.position.length()>8&&i.position.set(0,i.position.y,0),r>this._prevTime&&(n.set(a[0],a[1],a[2]),n.sub(o),n.multiplyScalar(l),n.applyQuaternion(this.getClipRotationOffset()),n.applyQuaternion(i.quaternion),this.positionChange.copy(n)),o.fromArray(a),this._prevTime=r,a[0]=0,a[1]=0,a[2]=0,a})}}static identityQuaternion=new c.Quaternion;handleRotation(e,t){if(t){if(Fh){const r=t.values,a=new c.Euler().setFromQuaternion(new c.Quaternion(r[0],r[1],r[2],r[3]));console.log(e.name,t.name,"FIRST ROTATION IN TRACK",I.toDegrees(a.y));const l=t.values.length-4,h=new c.Quaternion().set(r[l],r[l+1],r[l+2],r[l+3]),d=new c.Euler().setFromQuaternion(h);console.log(e.name,t.name,"LAST ROTATION IN TRACK",I.toDegrees(d.y))}let i=0;const n=new c.Quaternion,o=new c.Quaternion;this.rotationWrapper=new B_(t,(r,a)=>(r>i&&(o.set(a[0],a[1],a[2],a[3]),n.invert(),o.multiply(n),this.rotationChange.copy(o)),n.fromArray(a),i=r,a[0]=0,a[1]=0,a[2]=0,a[3]=1,a))}}onBeforeUpdate(e){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(e){return!this.action||(e*=this.action.getEffectiveWeight(),e<=0)?!1:(this.positionChange.multiplyScalar(e),this.rotationChange.slerp(Ke.identityQuaternion,1-e),!0)}}class CP{controller;handler=[];root;basePosition=new c.Vector3;baseQuaternion=new c.Quaternion;baseRotation=new c.Euler;constructor(e){this.controller=e}createClip(e,t,i){this.root=t,t&&"name"in t&&t.name;const n=this.findRootTrack(i,".position"),o=this.findRootTrack(i,".quaternion"),r=new Ke(this.controller.context,t,i,n,o);this.handler.push(r);const a=e.clipAction(i);return r.action=a,a}onStart(e){for(const t of this.handler)t.onStart(e)}onBeforeUpdate(e){this.basePosition.copy(this.root.position),this.baseQuaternion.copy(this.root.quaternion);for(const t of this.handler)t.onBeforeUpdate(e)}summedPosition=new c.Vector3;summedRotation=new c.Quaternion;onAfterUpdate(e){if(!(e<=0)){this.root.position.copy(this.basePosition),this.root.quaternion.copy(this.baseQuaternion),this.summedPosition.set(0,0,0),this.summedRotation.set(0,0,0,1);for(const t of this.handler)t.onAfterUpdate(e)&&(this.summedPosition.add(t.positionChange),this.summedRotation.multiply(t.rotationChange));this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation)}}findRootTrack(e,t){const i=e.tracks;if(!i)return null;for(const n of i)if(n.name.endsWith(t))return n;return null}}class PP extends $i{onSerialize(e,t){}onDeserialize(e,t){if(t.type===zi&&e?.__type==="AnimatorController")return new zi(e)}}new PP(zi);var MP=Object.defineProperty,OP=Object.getOwnPropertyDescriptor,mu=(s,e,t,i)=>{for(var n=i>1?void 0:i?OP(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&&MP(e,t,n),n};const Ei=x("debuganimator");class at extends E{get isAnimationComponent(){return!0}applyRootMotion=!1;hasRootMotion=!1;keepAnimatorControllerStateOnDisable=!1;set runtimeAnimatorController(e){this._animatorController&&this._animatorController.model===e||(e?e instanceof zi?(e.animator&&e.animator!==this&&(console.warn("AnimatorController can not be bound to multiple animators",e.model?.name),e.model||console.error("AnimatorController has no model"),e=new zi(e.model)),this._animatorController=e,this._animatorController.bind(this)):(Ei&&console.log("Assign animator controller",e,this),this._animatorController=new zi(e),this.__didAwake&&this._animatorController.bind(this)):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}getCurrentStateInfo(){return this.runtimeAnimatorController?.getCurrentStateInfo()}get currentAction(){return this.runtimeAnimatorController?.currentAction||null}get parametersAreDirty(){return this._parametersAreDirty}_parametersAreDirty=!1;get isDirty(){return this._isDirty}_isDirty=!1;Play(e,t=-1,i=Number.NEGATIVE_INFINITY,n=0){this.play(e,t,i,n)}play(e,t=-1,i=Number.NEGATIVE_INFINITY,n=0){this.runtimeAnimatorController?.play(e,t,i,n),this._isDirty=!0}Reset(){this.reset()}reset(){this._animatorController?.reset(),this._isDirty=!0}SetBool(e,t){this.setBool(e,t)}setBool(e,t){Ei&&console.log("setBool",e,t),this.runtimeAnimatorController?.getBool(e)!==t&&(this._parametersAreDirty=!0),this.runtimeAnimatorController?.setBool(e,t)}GetBool(e){return this.getBool(e)}getBool(e){const t=this.runtimeAnimatorController?.getBool(e)??!1;return Ei&&console.log("getBool",e,t),t}toggleBool(e){this.setBool(e,!this.getBool(e))}SetFloat(e,t){this.setFloat(e,t)}setFloat(e,t){this.runtimeAnimatorController?.getFloat(e)!==t&&(this._parametersAreDirty=!0),Ei&&console.log("setFloat",e,t),this.runtimeAnimatorController?.setFloat(e,t)}GetFloat(e){return this.getFloat(e)}getFloat(e){const t=this.runtimeAnimatorController?.getFloat(e)??-1;return Ei&&console.log("getFloat",e,t),t}SetInteger(e,t){this.setInteger(e,t)}setInteger(e,t){this.runtimeAnimatorController?.getInteger(e)!==t&&(this._parametersAreDirty=!0),Ei&&console.log("setInteger",e,t),this.runtimeAnimatorController?.setInteger(e,t)}GetInteger(e){return this.getInteger(e)}getInteger(e){const t=this.runtimeAnimatorController?.getInteger(e)??-1;return Ei&&console.log("getInteger",e,t),t}SetTrigger(e){this.setTrigger(e)}setTrigger(e){this._parametersAreDirty=!0,Ei&&console.log("setTrigger",e),this.runtimeAnimatorController?.setTrigger(e)}ResetTrigger(e){this.resetTrigger(e)}resetTrigger(e){this._parametersAreDirty=!0,Ei&&console.log("resetTrigger",e),this.runtimeAnimatorController?.resetTrigger(e)}GetTrigger(e){this.getTrigger(e)}getTrigger(e){const t=this.runtimeAnimatorController?.getTrigger(e);return Ei&&console.log("getTrigger",e,t),t}IsInTransition(){return this.isInTransition()}isInTransition(){return this.runtimeAnimatorController?.isInTransition()??!1}SetSpeed(e){return this.setSpeed(e)}setSpeed(e){e!==this._speed&&(Ei&&console.log("setSpeed",e),this._speed=e,this._animatorController?.animator==this&&this._animatorController.setSpeed(e))}set minMaxSpeed(e){this._speed=I.lerp(e.x,e.y,Math.random()),this._animatorController?.animator==this&&this._animatorController.setSpeed(this._speed)}set minMaxOffsetNormalized(e){this._normalizedStartOffset=I.lerp(e.x,e.y,Math.random()),this.runtimeAnimatorController?.animator==this&&(this.runtimeAnimatorController.normalizedStartOffset=this._normalizedStartOffset)}_speed=1;_normalizedStartOffset=0;_animatorController=null;awake(){Ei&&console.log("ANIMATOR",this.name,this),this.gameObject&&this.initializeRuntimeAnimatorController()}_initializeWithRuntimeAnimatorController;initializeRuntimeAnimatorController(e=!1){const t=e||this.runtimeAnimatorController!==this._initializeWithRuntimeAnimatorController;if(this.runtimeAnimatorController&&t){const i=this.runtimeAnimatorController.clone();this._initializeWithRuntimeAnimatorController=i,i?(console.assert(this.runtimeAnimatorController!==i),this.runtimeAnimatorController=i,console.assert(this.runtimeAnimatorController===i),this.runtimeAnimatorController.bind(this),this.runtimeAnimatorController.setSpeed(this._speed),this.runtimeAnimatorController.normalizedStartOffset=this._normalizedStartOffset):console.warn("Could not clone animator controller",this.runtimeAnimatorController)}}onDisable(){this.keepAnimatorControllerStateOnDisable||this._animatorController?.reset()}onBeforeRender(){this._isDirty=!1,this._parametersAreDirty=!1,!xP(this.gameObject)&&this._animatorController&&this._animatorController.update(1)}}mu([f()],at.prototype,"applyRootMotion",2);mu([f()],at.prototype,"hasRootMotion",2);mu([f()],at.prototype,"keepAnimatorControllerStateOnDisable",2);mu([f()],at.prototype,"runtimeAnimatorController",1);const U_=Symbol("previous-visibility");class Dn extends c.WebGLRenderTarget{render(e,t,i){if("addPass"in i)this._unsupported_effectcomposer_warning||(console.warn("RenderTexture.render() does not yet support EffectComposer"),this._unsupported_effectcomposer_warning=!0);else if(i instanceof c.WebGLRenderer){this.onBeforeRender();const o=i.getRenderTarget(),r=i.xr.enabled;i.xr.enabled=!1,i.setRenderTarget(this),i.clear(!0,!0,!0),i.render(e,t),i.setRenderTarget(o),i.xr.enabled=r,this.onAfterRender()}}static _userSet=new Set;onBeforeRender(){Dn._userSet.clear();const e=Vm(this.texture,!0,null,Dn._userSet);for(const t of e)t instanceof c.Mesh&&(t[U_]=t.visible,t.visible=!1)}onAfterRender(){for(const e of Dn._userSet)e instanceof c.Mesh&&(e.visible=e[U_]);Dn._userSet.clear()}}var kP=Object.defineProperty,EP=Object.getOwnPropertyDescriptor,Hc=(s,e,t,i)=>{for(var n=i>1?void 0:i?EP(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&&kP(e,t,n),n};const zh=x("debuggroundprojection");class $n extends E{applyOnAwake=!1;autoFit=!0;set radius(e){this._radius=e,this._projection&&this.updateProjection()}get radius(){return this._radius}_radius=50;set height(e){this._height=e,this._projection&&this.updateProjection()}get height(){return this._height}_height=3;set arBlending(e){this._arblending=e,this._needsTextureUpdate=!0}get arBlending(){return this._arblending}_arblending=0;_lastBackground;_lastRadius;_lastHeight;_projection;_watcher;awake(){this.applyOnAwake&&this.updateAndCreate()}onEnable(){this.context.time.frameCount>0&&this.applyOnAwake&&this.updateAndCreate(),this._watcher||(this._watcher=new hs(this.context.scene,"background"),this._watcher.subscribeWrite(e=>{zh&&console.log("Background changed",this.context.scene.background),this._needsTextureUpdate=!0}))}onDisable(){this._watcher?.revoke(),this._projection?.removeFromParent()}onEnterXR(){this.activeAndEnabled&&(this._needsTextureUpdate=!0,this.updateProjection())}async onLeaveXR(){this.activeAndEnabled&&(await Dc(1),this.updateProjection())}onBeforeRender(){this._projection&&this.scene.backgroundRotation&&this._projection.rotation.copy(this.scene.backgroundRotation),this.context.scene.backgroundBlurriness!==void 0&&this._lastBlurriness!=this.context.scene.backgroundBlurriness&&this.context.scene.backgroundBlurriness>.001?this.updateProjection():this._needsTextureUpdate&&this.context.scene.background instanceof c.Texture&&this.updateBlurriness(this.context.scene.background,this.context.scene.backgroundBlurriness)}updateAndCreate(){this.updateProjection(),this._watcher?.apply()}_needsTextureUpdate=!1;updateProjection(){if(!this.context.scene.background){this._projection?.removeFromParent();return}const e=this.context.scene.background;if(!(e instanceof c.Texture)){this._projection?.removeFromParent();return}if((this.context.xr?.isPassThrough||this.context.xr?.isAR)&&this.arBlending===0){this._projection?.removeFromParent();return}if(!this.gameObject||this.destroyed)return;let t=!0;const i=0,n=e!==this._lastBackground||this._height!==this._lastHeight||this._radius!==this._lastRadius;if(!this._projection||n){zh&&console.log("Create/Update Ground Projection",e.name),this._projection?.removeFromParent();try{this._projection=new q.GroundedSkybox(e,this._height,this._radius,64)}catch(o){console.error("Error creating three GroundProjection",o);return}this._projection.position.y=this._height-i,this._projection.name="GroundProjection",km(this._projection,!1)}else t=!1;if(this._projection.parent||this.gameObject.add(this._projection),this.autoFit&&t){this._projection.updateWorldMatrix(!0,!0);const o=Wt(this.context.scene.children,[this._projection]),r=o.min.y;if(r<1/0){const a=B();a.x=o.min.x+(o.max.x-o.min.x)*.5;const l=Le(this.gameObject).x;a.y=r+this._height*l-i,a.z=o.min.z+(o.max.z-o.min.z)*.5,rt(this._projection,a)}zh&&j.DrawWireBox3(o,65280,5)}this.context.scene.backgroundBlurriness>.001&&this._needsTextureUpdate&&this.updateBlurriness(e,this.context.scene.backgroundBlurriness),this._lastBackground=e,this._lastHeight=this._height,this._lastRadius=this._radius,this._needsTextureUpdate=!1}_blurrynessShader=null;_lastBlurriness=-1;updateBlurriness(e,t){if(this._projection){if(!e)return}else return;this._needsTextureUpdate=!1,zh&&console.log("Update Blurriness",t),this._blurrynessShader??=new c.ShaderMaterial({name:"GroundProjectionBlurriness",uniforms:{map:{value:e},blurriness:{value:t},blending:{value:0},alphaFactor:{value:1}},vertexShader:RP,fragmentShader:TP}),this._blurrynessShader.depthWrite=!1,this._blurrynessShader.uniforms.map.value=e,this._blurrynessShader.uniforms.blurriness.value=t,this._lastBlurriness=t,e.needsUpdate=!0;const i=this._projection.material.transparent;this._projection.material.transparent=(this.context.xr?.isAR===!0&&this.arBlending>1e-6)??!1,this._projection.material.transparent?this._blurrynessShader.uniforms.blending.value=this.arBlending:this._blurrynessShader.uniforms.blending.value=0,this.context.isInPassThrough?this._blurrynessShader.uniforms.alphaFactor.value=.95:this._blurrynessShader.uniforms.alphaFactor.value=1,i!==this._projection.material.transparent&&(this._projection.material.needsUpdate=!0),this._projection.material.map=so.copyTexture(e,this._blurrynessShader),this._projection.material.depthTest=!0,this._projection.material.depthWrite=!1}}Hc([f()],$n.prototype,"applyOnAwake",2);Hc([f()],$n.prototype,"autoFit",2);Hc([f()],$n.prototype,"radius",1);Hc([f()],$n.prototype,"height",1);Hc([f()],$n.prototype,"arBlending",1);const RP=`
|
|
890
890
|
varying vec2 vUv;
|
|
891
891
|
|
|
892
892
|
void main() {
|
|
@@ -955,7 +955,7 @@ Exit Time: `+h,o.hasExitTime)}this.transitionTo(o.destinationState,o.duration,o.
|
|
|
955
955
|
// Uncomment to visualize blur amount
|
|
956
956
|
// gl_FragColor = vec4(blurAmount, 0.0, 0.0, 1.0);
|
|
957
957
|
}
|
|
958
|
-
`;function B0(s){if(G.active)return console.warn("[OrbitControls] Can not fit camera while XR session is active"),null;const e=U.Current;if(!e)return console.warn("[OrbitControls] No context found"),null;const t=s?.camera||e.mainCamera;if(!t)return console.warn("No camera or controls found to fit camera to objects..."),null;s||(s={}),s.autoApply=s.autoApply!==!1,s.minZoom||=0,s.maxZoom||=1/0;const{centerCamera:i,cameraNearFar:n="auto",fitOffset:o=1.1,fov:r=t instanceof c.PerspectiveCamera?t?.fov:-1}=s,a=new c.Vector3,l=new c.Vector3,h=t instanceof c.PerspectiveCamera?t.aspect:1,d=s.objects||e.scene,u=Wt(d,void 0,t?.layers),p=u.clone();u.getCenter(l);const m=new c.Vector3;if(u.getSize(m),t instanceof c.PerspectiveCamera&&t.updateProjectionMatrix(),t.updateMatrixWorld(),u.applyMatrix4(t.matrixWorldInverse),u.getSize(a),u.setFromCenterAndSize(l,a),Number.isNaN(a.x)||Number.isNaN(a.y)||Number.isNaN(a.z))return console.warn("Camera fit size resultet in NaN",t,u),null;if(a.length()<=1e-10)return console.warn("Camera fit size is zero",u),null;const g=r,_=2*Math.atan(Math.tan(g*Math.PI/360/2)*h)/Math.PI*360,y=a.y/(2*Math.atan(Math.PI*g/360)),v=a.x/(2*Math.atan(Math.PI*_/360)),b=o*Math.max(y,v)+a.z/2;s.maxZoom=b*10,s.minZoom=b*.01,s.debug===!0&&console.log("Fit camera to objects",{fitHeightDistance:y,fitWidthDistance:v,distance:b,verticalFov:g,horizontalFov:_});const w=.05,R=l.clone();if(R.y-=a.y*w,s.targetOffset&&(s.targetOffset.x!==void 0&&(R.x+=s.targetOffset.x),s.targetOffset.y!==void 0&&(R.y+=s.targetOffset.y),s.targetOffset.z!==void 0&&(R.z+=s.targetOffset.z)),s.relativeTargetOffset&&(s.relativeTargetOffset.x!==void 0&&(R.x+=s.relativeTargetOffset.x*a.x),s.relativeTargetOffset.y!==void 0&&(R.y+=s.relativeTargetOffset.y*a.y),s.relativeTargetOffset.z!==void 0&&(R.z+=s.relativeTargetOffset.z*a.z)),n==null||n=="auto"){const A=Ua($n),D=A?A.radius:0,L=Math.max(m.x,m.y,m.z,D);t instanceof c.PerspectiveCamera&&(t.near=b/100,t.far=L+b*10,t.updateProjectionMatrix()),A&&(s.maxZoom=Math.max(Math.min(s.maxZoom,D*.5),b))}s.currentZoom!==void 0&&(s.currentZoom<s.minZoom&&(s.minZoom=s.currentZoom*.9),s.currentZoom>s.maxZoom&&(s.maxZoom=s.currentZoom*1.1));const M=l.clone();s.fitDirection?M.sub(new c.Vector3().copy(s.fitDirection).multiplyScalar(1e6)):M.sub(t.worldPosition),i==="y"&&(M.y=0),M.normalize(),M.multiplyScalar(b),i==="y"&&(M.y+=-w*4*b);let O=l.clone().sub(M);return s.cameraOffset&&(s.cameraOffset.x!==void 0&&(O.x+=s.cameraOffset.x),s.cameraOffset.y!==void 0&&(O.y+=s.cameraOffset.y),s.cameraOffset.z!==void 0&&(O.z+=s.cameraOffset.z)),s.relativeCameraOffset&&(s.relativeCameraOffset.x!==void 0&&(O.x+=s.relativeCameraOffset.x*a.x),s.relativeCameraOffset.y!==void 0&&(O.y+=s.relativeCameraOffset.y*a.y),s.relativeCameraOffset.z!==void 0&&(O.z+=s.relativeCameraOffset.z*a.z)),t.parent&&(O=t.parent.worldToLocal(O)),s.debug&&(j.DrawWireBox3(u,16777011,10),j.DrawWireBox3(p,65280,10)),s.autoApply&&(t.position.copy(O),t.lookAt(R),r>0&&t instanceof c.PerspectiveCamera&&(t.fov=r,t.updateProjectionMatrix())),{camera:t,position:O,lookAt:R,fov:s.fov}}var AP=Object.defineProperty,og=(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&&AP(e,t,n),n};class br extends E{constraintActive=!0;locked=!1;sources=[];setConstraintPosition(e){const t=this.sources[0];t&&(t.worldPosition=e)}}og([f()],br.prototype,"constraintActive");og([f()],br.prototype,"locked");og([f(c.Object3D)],br.prototype,"sources");let ir=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}static sizeOf(){return 12}static createVec3(e,t,i,n){return e.prep(4,12),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}};class U0{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new ir).__init(this.bb_pos,this.bb)}rotation(e){return(e||new ir).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new ir).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,i,n,o,r,a,l,h,d){return e.prep(4,36),e.prep(4,12),e.writeFloat32(d),e.writeFloat32(h),e.writeFloat32(l),e.prep(4,12),e.writeFloat32(a),e.writeFloat32(r),e.writeFloat32(o),e.prep(4,12),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}}class os{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedTransformModel(e,t){return(t||new os).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+re.SIZE_PREFIX_LENGTH),(t||new os).__init(e.readInt32(e.position())+e.position(),e)}guid(e){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}fast(){const e=this.bb.__offset(this.bb_pos,6);return e?!!this.bb.readInt8(this.bb_pos+e):!1}transform(e){const t=this.bb.__offset(this.bb_pos,8);return t?(e||new U0).__init(this.bb_pos+t,this.bb):null}dontSave(){const e=this.bb.__offset(this.bb_pos,10);return e?!!this.bb.readInt8(this.bb_pos+e):!1}static startSyncedTransformModel(e){e.startObject(4)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addFast(e,t){e.addFieldInt8(1,+t,0)}static addTransform(e,t){e.addFieldStruct(2,t,0)}static addDontSave(e,t){e.addFieldInt8(3,+t,0)}static endSyncedTransformModel(e){return e.endObject()}static finishSyncedTransformModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedTransformModelBuffer(e,t){e.finish(t,void 0,!0)}}exports.MODULES=void 0;(s=>{(e=>{e.MAYBEMODULE=null;const t=[];function i(){return e.MODULE?Promise.resolve(e.MODULE):new Promise(o=>{t.push(o)})}e.ready=i;async function n(){if(e.MODULE)return e.MODULE;const o=await Promise.resolve().then(()=>require("./materialx-BF23AVE8.umd.cjs"));return e.MODULE=o,e.MAYBEMODULE=o,t.forEach(r=>r(o)),t.length=0,o}e.load=n})(s.MaterialX||(s.MaterialX={})),(e=>{e.MAYBEMODULE=null;const t=[];function i(){return e.MODULE?Promise.resolve(e.MODULE):new Promise(o=>{t.push(o)})}e.ready=i;async function n(){if(e.MODULE)return e.MODULE;const o=await Promise.resolve().then(()=>require("./rapier-DQltNJbN.umd.cjs"));return e.MODULE=o,e.MAYBEMODULE=o,t.forEach(r=>r(o)),t.length=0,o}e.load=n})(s.RAPIER_PHYSICS||(s.RAPIER_PHYSICS={})),(e=>{e.MAYBEMODULE=null;const t=[];function i(){return e.MODULE?Promise.resolve(e.MODULE):new Promise(o=>{t.push(o)})}e.ready=i;async function n(){if(e.MODULE)return e.MODULE;const o=await Promise.resolve().then(()=>require("./postprocessing-CI2TjWpu.umd.cjs")).then(r=>r.index);return e.MODULE=o,e.MAYBEMODULE=o,t.forEach(r=>r(o)),t.length=0,o}e.load=n})(s.POSTPROCESSING||(s.POSTPROCESSING={})),(e=>{e.MAYBEMODULE=null;const t=[];function i(){return e.MODULE?Promise.resolve(e.MODULE):new Promise(o=>{t.push(o)})}e.ready=i;async function n(){if(e.MODULE)return e.MODULE;const o=await Promise.resolve().then(()=>require("./postprocessing-CI2TjWpu.umd.cjs")).then(r=>r.N8AO);return e.MODULE=o,e.MAYBEMODULE=o,t.forEach(r=>r(o)),t.length=0,o}e.load=n})(s.POSTPROCESSING_AO||(s.POSTPROCESSING_AO={}))})(exports.MODULES||(exports.MODULES={}));var it=(s=>(s[s.Average=0]="Average",s[s.Multiply=1]="Multiply",s[s.Minimum=2]="Minimum",s[s.Maximum=3]="Maximum",s))(it||{}),gu=(s=>(s[s.Discrete=0]="Discrete",s[s.Continuous=1]="Continuous",s))(gu||{}),Ue=(s=>(s[s.None=0]="None",s[s.FreezePositionX=2]="FreezePositionX",s[s.FreezePositionY=4]="FreezePositionY",s[s.FreezePositionZ=8]="FreezePositionZ",s[s.FreezePosition=14]="FreezePosition",s[s.FreezeRotationX=16]="FreezeRotationX",s[s.FreezeRotationY=32]="FreezeRotationY",s[s.FreezeRotationZ=64]="FreezeRotationZ",s[s.FreezeRotation=112]="FreezeRotation",s[s.FreezeAll=126]="FreezeAll",s))(Ue||{}),la=(s=>(s[s.None=0]="None",s[s.X=2]="X",s[s.Y=4]="Y",s[s.Z=8]="Z",s[s.All=-1]="All",s))(la||{});const vt=function(s,e){return function(t,i,n){DP(t,i,n,s,e)}};function DP(s,e,t,i,n){if(!n&&!i&&!s.onValidate)return;if(t!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",s,e,t),we("Invalid usage of validate decorator. Only fields can be validated. Property: "+e,ui.Error);return}let o="";if(typeof e=="string"?o=e:o=e.name,s.__internalAwake){const r=Symbol(o),a=s.__internalAwake;s.__internalAwake=function(){if(!this.onValidate){T()&&console.warn('Usage of @validate decorate detected but there is no onValidate method in your class: "'+s.constructor?.name+'"');return}if(this[r]===void 0){this[r]=this[o];const l=this[o];if(l instanceof c.Vector2||l instanceof c.Vector3||l instanceof c.Vector4||l instanceof c.Quaternion){const h=this[o];tu(h,()=>{this.onValidate(o)})}Object.defineProperty(this,o,{set:function(h){if(this[Fp]===!0)this[r]=h;else{i?.call(this,h);const d=this[r];this[r]=h,this.onValidate?.call(this,o,d)}},get:function(){return n?.call(this),this[r]}})}a.call(this)}}}const LP=function(s){return function(e,t,i){let n="";typeof t=="string"?n=t:n=t.name;const o=s.prototype,r=Object.getOwnPropertyDescriptor(o,n);if(!r?.value){console.warn("Can not apply prefix: type does not have method named",t,s);return}const a=r.value,l=e[n];Object.defineProperty(o,n,{value:function(...h){const d=l?.call(this,...h);if(d instanceof Promise){d.then(u=>{if(u!==!1)return a.call(this,...h)});return}if(d!==!1)return a.call(this,...h)}})}};var IP=Object.defineProperty,jP=Object.getOwnPropertyDescriptor,wi=(s,e,t,i)=>{for(var n=i>1?void 0:i?jP(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&&IP(e,t,n),n};class BP{get isDirty(){return this.positionChanged||this.rotationChanged}positionChanged=!1;rotationChanged=!1;position;quaternion;_positionKeys=["x","y","z"];_quaternionKeys=["_x","_y","_z","_w"];reset(e=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,e){if(this.position)for(const t of this._positionKeys)delete this.position[t];if(this.quaternion)for(const t of this._quaternionKeys)delete this.quaternion[t]}}syncValues(){for(const e of this._positionKeys)this.position[e]=this.obj.position[e];for(const e of this._quaternionKeys)this.quaternion[e]=this.obj.quaternion[e]}mute=!1;applyValues(){if(this.positionChanged&&this.position)for(const e of this._positionKeys){const t=this.position[e];t!==void 0&&(this.obj.position[e]=t)}if(this.rotationChanged&&this.quaternion)for(const e of this._quaternionKeys){const t=this.quaternion[e];t!==void 0&&(this.obj.quaternion[e]=t)}}context;obj;_positionWatch;_rotationWatch;constructor(e,t){this.context=t,this.obj=e}start(e,t){this.reset(),e&&(this._positionWatch||(this._positionWatch=new hs(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((o,r)=>{if(this.context.physics.engine?.isUpdating||this.mute)return;const a=this.position[r];Math.abs(a-o)<1e-5||(this.position[r]=o,this.positionChanged=!0)})),t&&(this._rotationWatch||(this._rotationWatch=new hs(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((o,r)=>{if(this.context.physics.engine?.isUpdating||this.mute)return;const a=this.quaternion[r];Math.abs(a-o)<1e-5||(this.quaternion[r]=o,this.rotationChanged=!0)}));const i=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),n=new c.Matrix4;this.obj.matrixWorld.multiplyMatrices=(o,r)=>(this.context.physics.engine?.isUpdating||this.mute||n.equals(o)||(this.positionChanged=!0,this.rotationChanged=!0,n.copy(o)),i(o,r))}stop(){this._positionWatch?.revoke(),this._rotationWatch?.revoke()}}const ni=class gd extends E{get isRigidbody(){return!0}autoMass=!0;set mass(e){e!==this._mass&&(this._mass=e,this._propertiesChanged=!0,this.__didAwake&&(this.autoMass=!1))}get mass(){return this.autoMass?this.context.physics.engine?.getBody(this)?.mass()??-1:this._mass}_mass=0;useGravity=!0;centerOfMass=new c.Vector3(0,0,0);constraints=Ue.None;isKinematic=!1;drag=0;angularDrag=1;detectCollisions=!0;sleepThreshold=.01;collisionDetectionMode=gu.Discrete;get lockPositionX(){return(this.constraints&Ue.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&Ue.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&Ue.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&Ue.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&Ue.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&Ue.FreezeRotationZ)!==0}set lockPositionX(e){e?this.constraints|=Ue.FreezePositionX:this.constraints&=~Ue.FreezePositionX}set lockPositionY(e){e?this.constraints|=Ue.FreezePositionY:this.constraints&=~Ue.FreezePositionY}set lockPositionZ(e){e?this.constraints|=Ue.FreezePositionZ:this.constraints&=~Ue.FreezePositionZ}set lockRotationX(e){e?this.constraints|=Ue.FreezeRotationX:this.constraints&=~Ue.FreezeRotationX}set lockRotationY(e){e?this.constraints|=Ue.FreezeRotationY:this.constraints&=~Ue.FreezeRotationY}set lockRotationZ(e){e?this.constraints|=Ue.FreezeRotationZ:this.constraints&=~Ue.FreezeRotationZ}set gravityScale(e){this._gravityScale=e}get gravityScale(){return this._gravityScale}_gravityScale=1;dominanceGroup=0;static tempPosition=new c.Vector3;_propertiesChanged=!1;_currentVelocity=new c.Vector3;_smoothedVelocity=new c.Vector3;_smoothedVelocityGetter=new c.Vector3;_lastPosition=new c.Vector3;_watch;awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new BP(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),me.LateUpdate),T()&&(globalThis.NEEDLE_USE_RAPIER?exports.MODULES.RAPIER_PHYSICS.ready().then(async()=>{await Dc(3),this.context.physics.engine?.getBody(this)||console.warn(`Rigidbody could not be created. Ensure "${this.name}" has a Collider component.`)}):console.warn("Rigidbody could not be created: Rapier physics are explicitly disabled."))}onDisable(){this._watch?.stop(),this.context.physics.engine?.removeBody(this)}onDestroy(){this.context.physics.engine?.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){for(;;)this._propertiesChanged&&(this._propertiesChanged=!1,this.context.physics.engine?.updateProperties(this)),this._watch?.isDirty?(this._watch.mute=!0,this._watch.applyValues(),this.context.physics.engine?.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):this._watch?.syncValues(),this.captureVelocity(),yield}teleport(e,t=!0){this._watch?.reset(!0),t?this.gameObject.position.set(e.x,e.y,e.z):this.setWorldPosition(e.x,e.y,e.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(e=!0){this.context.physics.engine?.resetForces(this,e)}resetTorques(e=!0){this.context.physics.engine?.resetTorques(this,e)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){this.context.physics.engine?.wakeup(this)}get isSleeping(){return this.context.physics.engine?.isSleeping(this)}updateProperties(){return this._propertiesChanged=!1,this.context.physics.engine?.updateProperties(this)}applyForce(e,t,i=!0){this._propertiesChanged&&this.updateProperties(),this.context.physics.engine?.addForce(this,e,i)}applyImpulse(e,t=!0){this._propertiesChanged&&this.updateProperties(),this.context.physics.engine?.applyImpulse(this,e,t)}setForce(e,t,i,n=!0){this.context.physics.engine?.resetForces(this,n),typeof e=="number"?(t??=0,i??=0,this.context.physics.engine?.addForce(this,{x:e,y:t,z:i},n)):this.context.physics.engine?.addForce(this,e,n)}getVelocity(){const e=this.context.physics.engine?.getLinearVelocity(this);return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(e,t,i,n=!0){if(e instanceof c.Vector3){const o=e;this.context.physics.engine?.setLinearVelocity(this,o,n);return}t===void 0||i===void 0||this.context.physics.engine?.setLinearVelocity(this,{x:e,y:t,z:i},n)}getAngularVelocity(){const e=this.context.physics.engine?.getAngularVelocity(this);return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setAngularVelocity(e,t,i,n=!0){if(typeof e=="object"){const o=e;this.context.physics.engine?.setAngularVelocity(this,o,n);return}if(t===void 0||i===void 0||typeof t=="boolean"){console.warn("setAngularVelocity expects either a Vec3 or 3 numbers");return}this.context.physics.engine?.setAngularVelocity(this,{x:e,y:t,z:i},n)}setTorque(e,t,i){typeof e=="number"?this.setAngularVelocity(e,t,i):this.setAngularVelocity(e)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(e=null){}captureVelocity(){const e=this.gameObject.matrixWorld;gd.tempPosition.setFromMatrixPosition(e);const t=gd.tempPosition.sub(this._lastPosition);this._lastPosition.copy(gd.tempPosition),this._smoothedVelocity.lerp(t,this.context.time.deltaTime/.1)}};wi([vt()],ni.prototype,"autoMass",2);wi([f()],ni.prototype,"mass",1);wi([vt(),f()],ni.prototype,"useGravity",2);wi([f(c.Vector3)],ni.prototype,"centerOfMass",2);wi([vt(),f()],ni.prototype,"constraints",2);wi([vt(),f()],ni.prototype,"isKinematic",2);wi([vt(),f()],ni.prototype,"drag",2);wi([vt(),f()],ni.prototype,"angularDrag",2);wi([vt(),f()],ni.prototype,"detectCollisions",2);wi([vt(),f()],ni.prototype,"sleepThreshold",2);wi([vt(),f()],ni.prototype,"collisionDetectionMode",2);wi([vt()],ni.prototype,"_gravityScale",2);wi([vt()],ni.prototype,"dominanceGroup",2);let Fe=ni;new c.Vector3;new c.Vector3;const Vs=x("debugsync"),bc="STRS";jm(bc,os.getRootAsSyncedTransformModel);const vn=new re.Builder;function F0(s,e,t=!0){vn.clear();const i=vn.createString(s);os.startSyncedTransformModel(vn),os.addGuid(vn,i),os.addFast(vn,t);const n=e.worldPosition,o=e.worldEuler,r=e.gameObject.scale;os.addTransform(vn,U0.createTransform(vn,n.x,n.y,n.z,o.x,o.y,o.z,r.x,r.y,r.z));const a=os.endSyncedTransformModel(vn);return vn.finish(a,bc),vn.asUint8Array()}let Yp=0,tc=0;k0(s=>{const t=s.connection.currentServerUrl?.includes("glitch")?10:40;tc=Math.floor(Yp/t),Yp=0,Vs&&tc>0&&console.log("Sync Transform Fast Interval",tc)});class dn extends E{overridePhysics=!0;interpolatePosition=!0;interpolateRotation=!0;fastMode=!1;syncDestroy=!1;_model=null;_needsUpdate=!0;rb=null;_wasKinematic=!1;_receivedDataBefore=!1;_targetPosition;_targetRotation;_receivedFastUpdate=!1;_shouldRequestOwnership=!1;requestOwnership(){Vs&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}freeOwnership(){this._model?.freeOwnership()}hasOwnership(){return this._model?.hasOwnership??void 0}isOwned(){return this._model?.isOwned}joinedRoomCallback=null;receivedDataCallback=null;awake(){Vs&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new c.Vector3,this._targetRotation=new c.Quaternion,this.lastPosition=new c.Vector3,this.lastRotation=new c.Quaternion,this.lastScale=new c.Vector3,this.rb=S.getComponentInChildren(this.gameObject,Fe),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new Um(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(Y.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(bc,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&Wm(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(Y.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(bc,this.receivedDataCallback)}tryGetLastState(){const e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}tempEuler=new c.Euler;onReceivedData(e){if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){Vs&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,e),this.receivedUpdate=!0,this._receivedFastUpdate=e.fast();const t=e.transform();if(t){Fi.markDirty(this.gameObject,!0);const i=t.position();i&&(this.interpolatePosition&&this._targetPosition?.set(i.x(),i.y(),i.z()),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(i.x(),i.y(),i.z()));const n=t.rotation();n&&(this.tempEuler.set(n.x(),n.y(),n.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&Om(this.gameObject,this.tempEuler));const o=t.scale();o&&this.gameObject.scale.set(o.x(),o.y(),o.z())}this._receivedDataBefore=!0}}onEnable(){this.lastPosition.copy(this.worldPosition),this.lastRotation.copy(this.worldQuaternion),this.lastScale.copy(this.gameObject.scale),this._needsUpdate=!0,this._model&&this._model.updateIsOwned()}onDisable(){this._model&&this._model.freeOwnership()}receivedUpdate=!1;lastPosition;lastRotation;lastScale;onBeforeRender(){if(!this.activeAndEnabled||!this.context.connection.isConnected)return;if(!this.context.connection.isInRoom||!this._model){Vs&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());const e=this.worldPosition,t=this.worldQuaternion,i=this.gameObject.scale;if(this._model.isOwned&&!this.receivedUpdate){const r=this._model.hasOwnership||this.fastMode?1e-4:.001;(e.distanceTo(this.lastPosition)>r||t.angleTo(this.lastRotation)>r||i.distanceTo(this.lastScale)>r)&&(this._model.hasOwnership?this._needsUpdate=!0:(Vs&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastPosition),this.worldPosition=this.lastPosition,e.copy(this.lastPosition),this.worldQuaternion=this.lastRotation,t.copy(this.lastRotation),this.gameObject.scale.copy(this.lastScale),Fi.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const r=this._receivedFastUpdate||this.fastMode?.5:.3;let a=!1;if(this.interpolatePosition&&this._targetPosition){const l=this.worldPosition;l.lerp(this._targetPosition,r),this.worldPosition=l,a=!0}if(this.interpolateRotation&&this._targetRotation){const l=this.worldQuaternion;l.slerp(this._targetRotation,r),this.worldQuaternion=l,a=!0}a&&Fi.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastPosition.copy(e),this.lastRotation.copy(t),this.lastScale.copy(i),!this._model||!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership)return;this.rb&&this.overridePhysics&&this._wasKinematic!==void 0&&(Vs&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic);const n=10,o=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%n===0||o)){if(Yp++,o&&tc>0&&this.context.time.frameCount%tc!==0)return;Vs&&console.debug("[SyncedTransform] Send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this._needsUpdate=!1;const r=F0(this.guid,this,!!o);this.context.connection.sendBinary(r)}}}class Gc{event;get deviceIndex(){return this.event.deviceIndex}get pointerId(){return this.event.pointerId}button;buttonName;get pressure(){return this.event.pressure}get used(){return this._used}_used=!1;use(){this._used||(this._used=!0,this.event.use())}_propagationStopped=!1;get propagationStopped(){return this._propagationStopped}stopPropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}stopImmediatePropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}z__pointer_ctured=!1;setPointerCapture(){this.z__pointer_ctured=!0}z__pointer_cture_rleased=!1;releasePointerCapture(){this.z__pointer_cture_rleased=!0}inputSource;get mode(){return this.event.mode}object;point;normal;face;distance;instanceId;intersection;isDown;isUp;isPressed;isClick;isDoubleClick;input;constructor(e,t){this.event=t,this.input=e,this.button=t.button}clone(){const e=new Gc(this.input,this.event);return Object.assign(e,this),e}Use(){this.use()}StopPropagation(){this.event.stopImmediatePropagation()}}function Vd(s,e){return S.foreachComponent(s,i=>{if(!i.enabled)return;const n=i;if(e)switch(e){case"pointerdown":if(n.onPointerDown)return!0;break;case"pointerup":if(n.onPointerUp||n.onPointerClick)return!0;break;case"pointermove":if(n.onPointerEnter||n.onPointerExit||n.onPointerMove)return!0;break}else if(n.onPointerDown||n.onPointerUp||n.onPointerEnter||n.onPointerExit||n.onPointerClick)return!0},!1)===!0}const Qn=new Array;class rs{enabled=!0;target;methodName;arguments;get canClone(){return this.target instanceof Object}constructor(e,t,i,n){this.target=e,this.methodName=t||null,this.arguments=i,n!=null&&(this.enabled=n)}invoke(...e){if(this.enabled!==!1){if(typeof this.target=="function")this.arguments?(Qn.length=0,e!==void 0&&e.length>0&&Qn.push(...e),Qn.push(...this.arguments),this.target(...this.arguments),Qn.length=0):this.target(...e);else if(this.methodName!=null){const t=this.target[this.methodName];typeof t=="function"?this.arguments?(Qn.length=0,e!==void 0&&e.length>0&&Qn.push(...e),Qn.push(...this.arguments),t.call(this.target,...Qn),Qn.length=0):t.call(this.target,...e):this.arguments?e!==void 0&&e.length>0?this.target[this.methodName]=e[0]:this.target[this.methodName]=this.arguments[0]:this.target[this.methodName]=e[0]}}}}const UP=s=>/^[A-Z]*$/.test(s);class yu extends Event{args}class oe{isEventList=!0;__internalOnInstantiate(e){const t=new Array;for(let n=0;n<this.methods.length;n++){const o=this.methods[n];if(!(o.target instanceof Function)){const r=o.target;let a=r?.uuid;if(r&&(a=r.guid),a){const l=e[a];if(l){const h=o.arguments?.map(d=>d instanceof Object&&d.uuid?e[d.uuid]:d?.isComponent?e[d.guid]:d);t.push(new rs(l.clone,o.methodName,h,o.enabled))}else T()&&console.warn("Could not find target for event listener")}}}return new oe(t)}target;key;setEventTarget(e,t){if(this.key=e,this.target=t,this.key!==void 0){let i="",n=!1;for(const o of this.key)n&&UP(o)&&(i+="-"),n=!0,i+=o.toLowerCase();this.key=i}}get listenerCount(){return this.methods?.length??0}get isInvoking(){return this._isInvoking}_isInvoking=!1;methods=[];_methodsCopy=[];static from(...e){return new oe(e)}constructor(e){if(this.methods=[],Array.isArray(e))for(const t of e)t instanceof rs?this.methods.push(t):typeof t=="function"&&this.methods.push(new rs(t));else typeof e=="function"&&this.methods.push(new rs(e))}invoke(...e){if(this._isInvoking)return console.warn("Circular event invocation detected. Please check your event listeners for circular references.",this),!1;if(this.methods?.length<=0)return!1;this._isInvoking=!0;try{this._methodsCopy.length=0,this._methodsCopy.push(...this.methods);for(const t of this._methodsCopy)t.invoke(...e);if(typeof this.target=="object"&&typeof this.key=="string"){const t=this.target.dispatchEvent;if(typeof t=="function"){const i=new yu(this.key);i.args=e,t.call(this.target,i)}}}finally{this._isInvoking=!1,this._methodsCopy.length=0}return!0}addEventListener(e){return this.methods.push(new rs(e)),e}removeEventListener(e){if(e)for(let t=this.methods.length-1;t>=0;t--)this.methods[t].target===e&&(this.methods[t].enabled=!1,this.methods.splice(t,1))}removeAllEventListeners(){this.methods.length=0}}class FP extends $i{constructor(){super([c.Color,ee],"ColorSerializer")}onDeserialize(e){if(e!=null)return e.a!==void 0?new ee(e.r,e.g,e.b,e.a):e.alpha!==void 0?new ee(e.r,e.g,e.b,e.alpha):new c.Color(e.r,e.g,e.b)}onSerialize(e){if(e!=null)return e.a!==void 0?{r:e.r,g:e.g,b:e.b,a:e.a}:{r:e.r,g:e.g,b:e.b}}}const zP=new FP;class NP extends $i{constructor(){super([c.Euler],"EulerSerializer")}onDeserialize(e,t){if(e!=null){if(e.order)return new c.Euler(e.x,e.y,e.z,e.order);if(e.x!=null)return new c.Euler(e.x,e.y,e.z)}}onSerialize(e,t){return{x:e.x,y:e.y,z:e.z,order:e.order}}}const VP=new NP;class $P extends $i{constructor(){super(c.Object3D,"ObjectSerializer")}onSerialize(e,t){if(t.objectToNode!==void 0&&e.uuid){const i=t.objectToNode[e.uuid];return ot&&console.log(i,e.name,e.uuid),{node:i}}}onDeserialize(e,t){if(typeof e=="string"){if(e.endsWith(".glb")||e.endsWith(".gltf")){if(t.serializable instanceof Array&&t.serializable.includes(K))return;T()&&ue("Detected wrong usage of @serializable with Object3D or GameObject. Instead you should use AssetReference here! Please see the console for details.");const i=t.target?.constructor?.name;console.warn(`Wrong usage of @serializable detected in your script "${i}"
|
|
958
|
+
`;function B0(s){if(G.active)return console.warn("[OrbitControls] Can not fit camera while XR session is active"),null;const e=U.Current;if(!e)return console.warn("[OrbitControls] No context found"),null;const t=s?.camera||e.mainCamera;if(!t)return console.warn("No camera or controls found to fit camera to objects..."),null;s||(s={}),s.autoApply=s.autoApply!==!1,s.minZoom||=0,s.maxZoom||=1/0;const{centerCamera:i,cameraNearFar:n="auto",fitOffset:o=1.1,fov:r=t instanceof c.PerspectiveCamera?t?.fov:-1}=s,a=new c.Vector3,l=new c.Vector3,h=t instanceof c.PerspectiveCamera?t.aspect:1,d=s.objects||e.scene,u=Wt(d,void 0,t?.layers),p=u.clone();u.getCenter(l);const m=new c.Vector3;if(u.getSize(m),t instanceof c.PerspectiveCamera&&t.updateProjectionMatrix(),t.updateMatrixWorld(),u.applyMatrix4(t.matrixWorldInverse),u.getSize(a),u.setFromCenterAndSize(l,a),Number.isNaN(a.x)||Number.isNaN(a.y)||Number.isNaN(a.z))return console.warn("Camera fit size resultet in NaN",t,u),null;if(a.length()<=1e-10)return console.warn("Camera fit size is zero",u),null;const g=r,_=2*Math.atan(Math.tan(g*Math.PI/360/2)*h)/Math.PI*360,y=a.y/(2*Math.atan(Math.PI*g/360)),v=a.x/(2*Math.atan(Math.PI*_/360)),b=o*Math.max(y,v)+a.z/2;s.maxZoom=b*10,s.minZoom=b*.01,s.debug===!0&&console.log("Fit camera to objects",{fitHeightDistance:y,fitWidthDistance:v,distance:b,verticalFov:g,horizontalFov:_});const w=.05,R=l.clone();if(R.y-=a.y*w,s.targetOffset&&(s.targetOffset.x!==void 0&&(R.x+=s.targetOffset.x),s.targetOffset.y!==void 0&&(R.y+=s.targetOffset.y),s.targetOffset.z!==void 0&&(R.z+=s.targetOffset.z)),s.relativeTargetOffset&&(s.relativeTargetOffset.x!==void 0&&(R.x+=s.relativeTargetOffset.x*a.x),s.relativeTargetOffset.y!==void 0&&(R.y+=s.relativeTargetOffset.y*a.y),s.relativeTargetOffset.z!==void 0&&(R.z+=s.relativeTargetOffset.z*a.z)),n==null||n=="auto"){const A=Ua($n),D=A?A.radius:0,L=Math.max(m.x,m.y,m.z,D);t instanceof c.PerspectiveCamera&&(t.near=b/100,t.far=L+b*10,t.updateProjectionMatrix()),A&&(s.maxZoom=Math.max(Math.min(s.maxZoom,D*.5),b))}s.currentZoom!==void 0&&(s.currentZoom<s.minZoom&&(s.minZoom=s.currentZoom*.9),s.currentZoom>s.maxZoom&&(s.maxZoom=s.currentZoom*1.1));const M=l.clone();s.fitDirection?M.sub(new c.Vector3().copy(s.fitDirection).multiplyScalar(1e6)):M.sub(t.worldPosition),i==="y"&&(M.y=0),M.normalize(),M.multiplyScalar(b),i==="y"&&(M.y+=-w*4*b);let O=l.clone().sub(M);return s.cameraOffset&&(s.cameraOffset.x!==void 0&&(O.x+=s.cameraOffset.x),s.cameraOffset.y!==void 0&&(O.y+=s.cameraOffset.y),s.cameraOffset.z!==void 0&&(O.z+=s.cameraOffset.z)),s.relativeCameraOffset&&(s.relativeCameraOffset.x!==void 0&&(O.x+=s.relativeCameraOffset.x*a.x),s.relativeCameraOffset.y!==void 0&&(O.y+=s.relativeCameraOffset.y*a.y),s.relativeCameraOffset.z!==void 0&&(O.z+=s.relativeCameraOffset.z*a.z)),t.parent&&(O=t.parent.worldToLocal(O)),s.debug&&(j.DrawWireBox3(u,16777011,10),j.DrawWireBox3(p,65280,10)),s.autoApply&&(t.position.copy(O),t.lookAt(R),r>0&&t instanceof c.PerspectiveCamera&&(t.fov=r,t.updateProjectionMatrix())),{camera:t,position:O,lookAt:R,fov:s.fov}}var AP=Object.defineProperty,og=(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&&AP(e,t,n),n};class br extends E{constraintActive=!0;locked=!1;sources=[];setConstraintPosition(e){const t=this.sources[0];t&&(t.worldPosition=e)}}og([f()],br.prototype,"constraintActive");og([f()],br.prototype,"locked");og([f(c.Object3D)],br.prototype,"sources");let ir=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}static sizeOf(){return 12}static createVec3(e,t,i,n){return e.prep(4,12),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}};class U0{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new ir).__init(this.bb_pos,this.bb)}rotation(e){return(e||new ir).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new ir).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,i,n,o,r,a,l,h,d){return e.prep(4,36),e.prep(4,12),e.writeFloat32(d),e.writeFloat32(h),e.writeFloat32(l),e.prep(4,12),e.writeFloat32(a),e.writeFloat32(r),e.writeFloat32(o),e.prep(4,12),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}}class os{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedTransformModel(e,t){return(t||new os).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+re.SIZE_PREFIX_LENGTH),(t||new os).__init(e.readInt32(e.position())+e.position(),e)}guid(e){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}fast(){const e=this.bb.__offset(this.bb_pos,6);return e?!!this.bb.readInt8(this.bb_pos+e):!1}transform(e){const t=this.bb.__offset(this.bb_pos,8);return t?(e||new U0).__init(this.bb_pos+t,this.bb):null}dontSave(){const e=this.bb.__offset(this.bb_pos,10);return e?!!this.bb.readInt8(this.bb_pos+e):!1}static startSyncedTransformModel(e){e.startObject(4)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addFast(e,t){e.addFieldInt8(1,+t,0)}static addTransform(e,t){e.addFieldStruct(2,t,0)}static addDontSave(e,t){e.addFieldInt8(3,+t,0)}static endSyncedTransformModel(e){return e.endObject()}static finishSyncedTransformModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedTransformModelBuffer(e,t){e.finish(t,void 0,!0)}}exports.MODULES=void 0;(s=>{(e=>{e.MAYBEMODULE=null;const t=[];function i(){return e.MODULE?Promise.resolve(e.MODULE):new Promise(o=>{t.push(o)})}e.ready=i;async function n(){if(e.MODULE)return e.MODULE;const o=await Promise.resolve().then(()=>require("./materialx-BF23AVE8.umd.cjs"));return e.MODULE=o,e.MAYBEMODULE=o,t.forEach(r=>r(o)),t.length=0,o}e.load=n})(s.MaterialX||(s.MaterialX={})),(e=>{e.MAYBEMODULE=null;const t=[];function i(){return e.MODULE?Promise.resolve(e.MODULE):new Promise(o=>{t.push(o)})}e.ready=i;async function n(){if(e.MODULE)return e.MODULE;const o=await Promise.resolve().then(()=>require("./rapier-DQltNJbN.umd.cjs"));return e.MODULE=o,e.MAYBEMODULE=o,t.forEach(r=>r(o)),t.length=0,o}e.load=n})(s.RAPIER_PHYSICS||(s.RAPIER_PHYSICS={})),(e=>{e.MAYBEMODULE=null;const t=[];function i(){return e.MODULE?Promise.resolve(e.MODULE):new Promise(o=>{t.push(o)})}e.ready=i;async function n(){if(e.MODULE)return e.MODULE;const o=await Promise.resolve().then(()=>require("./postprocessing-CI2TjWpu.umd.cjs")).then(r=>r.index);return e.MODULE=o,e.MAYBEMODULE=o,t.forEach(r=>r(o)),t.length=0,o}e.load=n})(s.POSTPROCESSING||(s.POSTPROCESSING={})),(e=>{e.MAYBEMODULE=null;const t=[];function i(){return e.MODULE?Promise.resolve(e.MODULE):new Promise(o=>{t.push(o)})}e.ready=i;async function n(){if(e.MODULE)return e.MODULE;const o=await Promise.resolve().then(()=>require("./postprocessing-CI2TjWpu.umd.cjs")).then(r=>r.N8AO);return e.MODULE=o,e.MAYBEMODULE=o,t.forEach(r=>r(o)),t.length=0,o}e.load=n})(s.POSTPROCESSING_AO||(s.POSTPROCESSING_AO={}))})(exports.MODULES||(exports.MODULES={}));var it=(s=>(s[s.Average=0]="Average",s[s.Multiply=1]="Multiply",s[s.Minimum=2]="Minimum",s[s.Maximum=3]="Maximum",s))(it||{}),gu=(s=>(s[s.Discrete=0]="Discrete",s[s.Continuous=1]="Continuous",s))(gu||{}),Ue=(s=>(s[s.None=0]="None",s[s.FreezePositionX=2]="FreezePositionX",s[s.FreezePositionY=4]="FreezePositionY",s[s.FreezePositionZ=8]="FreezePositionZ",s[s.FreezePosition=14]="FreezePosition",s[s.FreezeRotationX=16]="FreezeRotationX",s[s.FreezeRotationY=32]="FreezeRotationY",s[s.FreezeRotationZ=64]="FreezeRotationZ",s[s.FreezeRotation=112]="FreezeRotation",s[s.FreezeAll=126]="FreezeAll",s))(Ue||{}),la=(s=>(s[s.None=0]="None",s[s.X=2]="X",s[s.Y=4]="Y",s[s.Z=8]="Z",s[s.All=-1]="All",s))(la||{});const vt=function(s,e){return function(t,i,n){DP(t,i,n,s,e)}};function DP(s,e,t,i,n){if(!n&&!i&&!s.onValidate)return;if(t!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",s,e,t),we("Invalid usage of validate decorator. Only fields can be validated. Property: "+e,ui.Error);return}let o="";if(typeof e=="string"?o=e:o=e.name,s.__internalAwake){const r=Symbol(o),a=s.__internalAwake;s.__internalAwake=function(){if(!this.onValidate){T()&&console.warn('Usage of @validate decorate detected but there is no onValidate method in your class: "'+s.constructor?.name+'"');return}if(this[r]===void 0){this[r]=this[o];const l=this[o];if(l instanceof c.Vector2||l instanceof c.Vector3||l instanceof c.Vector4||l instanceof c.Quaternion){const h=this[o];tu(h,()=>{this.onValidate(o)})}Object.defineProperty(this,o,{set:function(h){if(this[Fp]===!0)this[r]=h;else{i?.call(this,h);const d=this[r];this[r]=h,this.onValidate?.call(this,o,d)}},get:function(){return n?.call(this),this[r]}})}a.call(this)}}}const LP=function(s){return function(e,t,i){let n="";typeof t=="string"?n=t:n=t.name;const o=s.prototype,r=Object.getOwnPropertyDescriptor(o,n);if(!r?.value){console.warn("Can not apply prefix: type does not have method named",t,s);return}const a=r.value,l=e[n];Object.defineProperty(o,n,{value:function(...h){const d=l?.call(this,...h);if(d instanceof Promise){d.then(u=>{if(u!==!1)return a.call(this,...h)});return}if(d!==!1)return a.call(this,...h)}})}};var IP=Object.defineProperty,jP=Object.getOwnPropertyDescriptor,wi=(s,e,t,i)=>{for(var n=i>1?void 0:i?jP(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&&IP(e,t,n),n};class BP{get isDirty(){return this.positionChanged||this.rotationChanged}positionChanged=!1;rotationChanged=!1;position;quaternion;_positionKeys=["x","y","z"];_quaternionKeys=["_x","_y","_z","_w"];reset(e=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,e){if(this.position)for(const t of this._positionKeys)delete this.position[t];if(this.quaternion)for(const t of this._quaternionKeys)delete this.quaternion[t]}}syncValues(){for(const e of this._positionKeys)this.position[e]=this.obj.position[e];for(const e of this._quaternionKeys)this.quaternion[e]=this.obj.quaternion[e]}mute=!1;applyValues(){if(this.positionChanged&&this.position)for(const e of this._positionKeys){const t=this.position[e];t!==void 0&&(this.obj.position[e]=t)}if(this.rotationChanged&&this.quaternion)for(const e of this._quaternionKeys){const t=this.quaternion[e];t!==void 0&&(this.obj.quaternion[e]=t)}}context;obj;_positionWatch;_rotationWatch;constructor(e,t){this.context=t,this.obj=e}start(e,t){this.reset(),e&&(this._positionWatch||(this._positionWatch=new hs(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((o,r)=>{if(this.context.physics.engine?.isUpdating||this.mute)return;const a=this.position[r];Math.abs(a-o)<1e-5||(this.position[r]=o,this.positionChanged=!0)})),t&&(this._rotationWatch||(this._rotationWatch=new hs(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((o,r)=>{if(this.context.physics.engine?.isUpdating||this.mute)return;const a=this.quaternion[r];Math.abs(a-o)<1e-5||(this.quaternion[r]=o,this.rotationChanged=!0)}));const i=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),n=new c.Matrix4;this.obj.matrixWorld.multiplyMatrices=(o,r)=>(this.context.physics.engine?.isUpdating||this.mute||n.equals(o)||(this.positionChanged=!0,this.rotationChanged=!0,n.copy(o)),i(o,r))}stop(){this._positionWatch?.revoke(),this._rotationWatch?.revoke()}}const ni=class gd extends E{get isRigidbody(){return!0}autoMass=!0;set mass(e){e!==this._mass&&(this._mass=e,this._propertiesChanged=!0,this.__didAwake&&(this.autoMass=!1))}get mass(){return this.autoMass?this.context.physics.engine?.getBody(this)?.mass()??-1:this._mass}_mass=0;useGravity=!0;centerOfMass=new c.Vector3(0,0,0);constraints=Ue.None;isKinematic=!1;drag=0;angularDrag=1;detectCollisions=!0;sleepThreshold=.01;collisionDetectionMode=gu.Discrete;get lockPositionX(){return(this.constraints&Ue.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&Ue.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&Ue.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&Ue.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&Ue.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&Ue.FreezeRotationZ)!==0}set lockPositionX(e){e?this.constraints|=Ue.FreezePositionX:this.constraints&=~Ue.FreezePositionX}set lockPositionY(e){e?this.constraints|=Ue.FreezePositionY:this.constraints&=~Ue.FreezePositionY}set lockPositionZ(e){e?this.constraints|=Ue.FreezePositionZ:this.constraints&=~Ue.FreezePositionZ}set lockRotationX(e){e?this.constraints|=Ue.FreezeRotationX:this.constraints&=~Ue.FreezeRotationX}set lockRotationY(e){e?this.constraints|=Ue.FreezeRotationY:this.constraints&=~Ue.FreezeRotationY}set lockRotationZ(e){e?this.constraints|=Ue.FreezeRotationZ:this.constraints&=~Ue.FreezeRotationZ}set gravityScale(e){this._gravityScale=e}get gravityScale(){return this._gravityScale}_gravityScale=1;dominanceGroup=0;static tempPosition=new c.Vector3;_propertiesChanged=!1;_currentVelocity=new c.Vector3;_smoothedVelocity=new c.Vector3;_smoothedVelocityGetter=new c.Vector3;_lastPosition=new c.Vector3;_watch;awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new BP(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),me.LateUpdate),T()&&(globalThis.NEEDLE_USE_RAPIER?exports.MODULES.RAPIER_PHYSICS.ready().then(async()=>{await Dc(3),this.context.physics.engine?.getBody(this)||console.warn(`Rigidbody could not be created. Ensure "${this.name}" has a Collider component.`)}):console.warn("Rigidbody could not be created: Rapier physics are explicitly disabled."))}onDisable(){this._watch?.stop(),this.context.physics.engine?.removeBody(this)}onDestroy(){this.context.physics.engine?.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){for(;;)this._propertiesChanged&&(this._propertiesChanged=!1,this.context.physics.engine?.updateProperties(this)),this._watch?.isDirty?(this._watch.mute=!0,this._watch.applyValues(),this.context.physics.engine?.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):this._watch?.syncValues(),this.captureVelocity(),yield}teleport(e,t=!0){this._watch?.reset(!0),t?this.gameObject.position.set(e.x,e.y,e.z):this.setWorldPosition(e.x,e.y,e.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(e=!0){this.context.physics.engine?.resetForces(this,e)}resetTorques(e=!0){this.context.physics.engine?.resetTorques(this,e)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){this.context.physics.engine?.wakeup(this)}get isSleeping(){return this.context.physics.engine?.isSleeping(this)}updateProperties(){return this._propertiesChanged=!1,this.context.physics.engine?.updateProperties(this)}applyForce(e,t,i=!0){this._propertiesChanged&&this.updateProperties(),this.context.physics.engine?.addForce(this,e,i)}applyImpulse(e,t=!0){this._propertiesChanged&&this.updateProperties(),this.context.physics.engine?.applyImpulse(this,e,t)}setForce(e,t,i,n=!0){this.context.physics.engine?.resetForces(this,n),typeof e=="number"?(t??=0,i??=0,this.context.physics.engine?.addForce(this,{x:e,y:t,z:i},n)):this.context.physics.engine?.addForce(this,e,n)}getVelocity(){const e=this.context.physics.engine?.getLinearVelocity(this);return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(e,t,i,n=!0){if(e instanceof c.Vector3){const o=e;this.context.physics.engine?.setLinearVelocity(this,o,n);return}t===void 0||i===void 0||this.context.physics.engine?.setLinearVelocity(this,{x:e,y:t,z:i},n)}getAngularVelocity(){const e=this.context.physics.engine?.getAngularVelocity(this);return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setAngularVelocity(e,t,i,n=!0){if(typeof e=="object"){const o=e;this.context.physics.engine?.setAngularVelocity(this,o,n);return}if(t===void 0||i===void 0||typeof t=="boolean"){console.warn("setAngularVelocity expects either a Vec3 or 3 numbers");return}this.context.physics.engine?.setAngularVelocity(this,{x:e,y:t,z:i},n)}setTorque(e,t,i){typeof e=="number"?this.setAngularVelocity(e,t,i):this.setAngularVelocity(e)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(e=null){}captureVelocity(){const e=this.gameObject.matrixWorld;gd.tempPosition.setFromMatrixPosition(e);const t=gd.tempPosition.sub(this._lastPosition);this._lastPosition.copy(gd.tempPosition),this._smoothedVelocity.lerp(t,this.context.time.deltaTime/.1)}};wi([vt()],ni.prototype,"autoMass",2);wi([f()],ni.prototype,"mass",1);wi([vt(),f()],ni.prototype,"useGravity",2);wi([f(c.Vector3)],ni.prototype,"centerOfMass",2);wi([vt(),f()],ni.prototype,"constraints",2);wi([vt(),f()],ni.prototype,"isKinematic",2);wi([vt(),f()],ni.prototype,"drag",2);wi([vt(),f()],ni.prototype,"angularDrag",2);wi([vt(),f()],ni.prototype,"detectCollisions",2);wi([vt(),f()],ni.prototype,"sleepThreshold",2);wi([vt(),f()],ni.prototype,"collisionDetectionMode",2);wi([vt()],ni.prototype,"_gravityScale",2);wi([vt()],ni.prototype,"dominanceGroup",2);let Fe=ni;new c.Vector3;new c.Vector3;const Vs=x("debugsync"),bc="STRS";jm(bc,os.getRootAsSyncedTransformModel);const vn=new re.Builder;function F0(s,e,t=!0){vn.clear();const i=vn.createString(s);os.startSyncedTransformModel(vn),os.addGuid(vn,i),os.addFast(vn,t);const n=e.worldPosition,o=e.worldEuler,r=e.gameObject.scale;os.addTransform(vn,U0.createTransform(vn,n.x,n.y,n.z,o.x,o.y,o.z,r.x,r.y,r.z));const a=os.endSyncedTransformModel(vn);return vn.finish(a,bc),vn.asUint8Array()}let Yp=0,tc=0;k0(s=>{const t=s.connection.currentServerUrl?.includes("glitch")?10:40;tc=Math.floor(Yp/t),Yp=0,Vs&&tc>0&&console.log("Sync Transform Fast Interval",tc)});class dn extends E{overridePhysics=!0;interpolatePosition=!0;interpolateRotation=!0;fastMode=!1;syncDestroy=!1;_model=null;_needsUpdate=!0;rb=null;_wasKinematic=!1;_receivedDataBefore=!1;_targetPosition;_targetRotation;_receivedFastUpdate=!1;_shouldRequestOwnership=!1;requestOwnership(){Vs&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}freeOwnership(){this._model?.freeOwnership()}hasOwnership(){return this._model?.hasOwnership??void 0}isOwned(){return this._model?.isOwned}joinedRoomCallback=null;receivedDataCallback=null;awake(){Vs&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new c.Vector3,this._targetRotation=new c.Quaternion,this.lastPosition=new c.Vector3,this.lastRotation=new c.Quaternion,this.lastScale=new c.Vector3,this.rb=S.getComponentInChildren(this.gameObject,Fe),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new Um(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(Y.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(bc,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&Wm(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(Y.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(bc,this.receivedDataCallback)}tryGetLastState(){const e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}tempEuler=new c.Euler;onReceivedData(e){if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){Vs&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,e),this.receivedUpdate=!0,this._receivedFastUpdate=e.fast();const t=e.transform();if(t){Fi.markDirty(this.gameObject,!0);const i=t.position();i&&(this.interpolatePosition&&this._targetPosition?.set(i.x(),i.y(),i.z()),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(i.x(),i.y(),i.z()));const n=t.rotation();n&&(this.tempEuler.set(n.x(),n.y(),n.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&Om(this.gameObject,this.tempEuler));const o=t.scale();o&&this.gameObject.scale.set(o.x(),o.y(),o.z())}this._receivedDataBefore=!0}}onEnable(){this.lastPosition.copy(this.worldPosition),this.lastRotation.copy(this.worldQuaternion),this.lastScale.copy(this.gameObject.scale),this._needsUpdate=!0,this._model&&this._model.updateIsOwned()}onDisable(){this._model&&this._model.freeOwnership()}receivedUpdate=!1;lastPosition;lastRotation;lastScale;onBeforeRender(){if(!this.activeAndEnabled||!this.context.connection.isConnected)return;if(!this.context.connection.isInRoom||!this._model){Vs&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());const e=this.worldPosition,t=this.worldQuaternion,i=this.gameObject.scale;if(this._model.isOwned&&!this.receivedUpdate){const r=this._model.hasOwnership||this.fastMode?1e-4:.001;(e.distanceTo(this.lastPosition)>r||t.angleTo(this.lastRotation)>r||i.distanceTo(this.lastScale)>r)&&(this._model.hasOwnership?this._needsUpdate=!0:(Vs&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastPosition),this.worldPosition=this.lastPosition,e.copy(this.lastPosition),this.worldQuaternion=this.lastRotation,t.copy(this.lastRotation),this.gameObject.scale.copy(this.lastScale),Fi.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const r=this._receivedFastUpdate||this.fastMode?.5:.3;let a=!1;if(this.interpolatePosition&&this._targetPosition){const l=this.worldPosition;l.lerp(this._targetPosition,r),this.worldPosition=l,a=!0}if(this.interpolateRotation&&this._targetRotation){const l=this.worldQuaternion;l.slerp(this._targetRotation,r),this.worldQuaternion=l,a=!0}a&&Fi.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastPosition.copy(e),this.lastRotation.copy(t),this.lastScale.copy(i),!this._model||!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership)return;this.rb&&this.overridePhysics&&this._wasKinematic!==void 0&&(Vs&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic);const n=10,o=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%n===0||o)){if(Yp++,o&&tc>0&&this.context.time.frameCount%tc!==0)return;Vs&&console.debug("[SyncedTransform] Send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this._needsUpdate=!1;const r=F0(this.guid,this,!!o);this.context.connection.sendBinary(r)}}}class Gc{event;get deviceIndex(){return this.event.deviceIndex}get pointerId(){return this.event.pointerId}button;buttonName;get pressure(){return this.event.pressure}get used(){return this._used}_used=!1;use(){this._used||(this._used=!0,this.event.use())}_propagationStopped=!1;get propagationStopped(){return this._propagationStopped}stopPropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}stopImmediatePropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}z__pointer_ctured=!1;setPointerCapture(){this.z__pointer_ctured=!0}z__pointer_cture_rleased=!1;releasePointerCapture(){this.z__pointer_cture_rleased=!0}inputSource;get mode(){return this.event.mode}object;point;normal;face;distance;instanceId;intersection;isDown;isUp;isPressed;isClick;isDoubleClick;input;constructor(e,t){this.event=t,this.input=e,this.button=t.button}clone(){const e=new Gc(this.input,this.event);return Object.assign(e,this),e}Use(){this.use()}StopPropagation(){this.event.stopImmediatePropagation()}}function Vd(s,e){return S.foreachComponent(s,i=>{if(!i.enabled)return;const n=i;if(e)switch(e){case"pointerdown":if(n.onPointerDown)return!0;break;case"pointerup":if(n.onPointerUp||n.onPointerClick)return!0;break;case"pointermove":if(n.onPointerEnter||n.onPointerExit||n.onPointerMove)return!0;break}else if(n.onPointerDown||n.onPointerUp||n.onPointerEnter||n.onPointerExit||n.onPointerClick)return!0},!1)===!0}const Qn=new Array;class rs{enabled=!0;target;methodName;arguments;get canClone(){return this.target instanceof Object}constructor(e,t,i,n){this.target=e,this.methodName=t||null,this.arguments=i,n!=null&&(this.enabled=n)}invoke(...e){if(this.enabled!==!1){if(typeof this.target=="function")this.arguments?(Qn.length=0,e!==void 0&&e.length>0&&Qn.push(...e),Qn.push(...this.arguments),this.target(...this.arguments),Qn.length=0):this.target(...e);else if(this.methodName!=null){const t=this.target[this.methodName];typeof t=="function"?this.arguments?(Qn.length=0,e!==void 0&&e.length>0&&Qn.push(...e),Qn.push(...this.arguments),t.call(this.target,...Qn),Qn.length=0):t.call(this.target,...e):this.arguments?e!==void 0&&e.length>0?this.target[this.methodName]=e[0]:this.target[this.methodName]=this.arguments[0]:this.target[this.methodName]=e[0]}}}}const UP=s=>/^[A-Z]*$/.test(s);class yu extends Event{args}class oe{isEventList=!0;__internalOnInstantiate(e){const t=new Array;for(let n=0;n<this.methods.length;n++){const o=this.methods[n];if(!(o.target instanceof Function)){const r=o.target;let a=r?.uuid;if(r&&(a=r.guid),a){const l=e[a];if(l){const h=o.arguments?.map(d=>d instanceof Object&&d.uuid?e[d.uuid].clone:d?.isComponent?e[d.guid].clone:d);t.push(new rs(l.clone,o.methodName,h,o.enabled))}else T()&&console.warn("Could not find target for event listener")}}}return new oe(t)}target;key;setEventTarget(e,t){if(this.key=e,this.target=t,this.key!==void 0){let i="",n=!1;for(const o of this.key)n&&UP(o)&&(i+="-"),n=!0,i+=o.toLowerCase();this.key=i}}get listenerCount(){return this.methods?.length??0}get isInvoking(){return this._isInvoking}_isInvoking=!1;methods=[];_methodsCopy=[];static from(...e){return new oe(e)}constructor(e){if(this.methods=[],Array.isArray(e))for(const t of e)t instanceof rs?this.methods.push(t):typeof t=="function"&&this.methods.push(new rs(t));else typeof e=="function"&&this.methods.push(new rs(e))}invoke(...e){if(this._isInvoking)return console.warn("Circular event invocation detected. Please check your event listeners for circular references.",this),!1;if(this.methods?.length<=0)return!1;this._isInvoking=!0;try{this._methodsCopy.length=0,this._methodsCopy.push(...this.methods);for(const t of this._methodsCopy)t.invoke(...e);if(typeof this.target=="object"&&typeof this.key=="string"){const t=this.target.dispatchEvent;if(typeof t=="function"){const i=new yu(this.key);i.args=e,t.call(this.target,i)}}}finally{this._isInvoking=!1,this._methodsCopy.length=0}return!0}addEventListener(e){return this.methods.push(new rs(e)),e}removeEventListener(e){if(e)for(let t=this.methods.length-1;t>=0;t--)this.methods[t].target===e&&(this.methods[t].enabled=!1,this.methods.splice(t,1))}removeAllEventListeners(){this.methods.length=0}}class FP extends $i{constructor(){super([c.Color,ee],"ColorSerializer")}onDeserialize(e){if(e!=null)return e.a!==void 0?new ee(e.r,e.g,e.b,e.a):e.alpha!==void 0?new ee(e.r,e.g,e.b,e.alpha):new c.Color(e.r,e.g,e.b)}onSerialize(e){if(e!=null)return e.a!==void 0?{r:e.r,g:e.g,b:e.b,a:e.a}:{r:e.r,g:e.g,b:e.b}}}const zP=new FP;class NP extends $i{constructor(){super([c.Euler],"EulerSerializer")}onDeserialize(e,t){if(e!=null){if(e.order)return new c.Euler(e.x,e.y,e.z,e.order);if(e.x!=null)return new c.Euler(e.x,e.y,e.z)}}onSerialize(e,t){return{x:e.x,y:e.y,z:e.z,order:e.order}}}const VP=new NP;class $P extends $i{constructor(){super(c.Object3D,"ObjectSerializer")}onSerialize(e,t){if(t.objectToNode!==void 0&&e.uuid){const i=t.objectToNode[e.uuid];return ot&&console.log(i,e.name,e.uuid),{node:i}}}onDeserialize(e,t){if(typeof e=="string"){if(e.endsWith(".glb")||e.endsWith(".gltf")){if(t.serializable instanceof Array&&t.serializable.includes(K))return;T()&&ue("Detected wrong usage of @serializable with Object3D or GameObject. Instead you should use AssetReference here! Please see the console for details.");const i=t.target?.constructor?.name;console.warn(`Wrong usage of @serializable detected in your script "${i}"
|
|
959
959
|
|
|
960
960
|
It looks like you used @serializable(Object3D) or @serializable(GameObject) for a prefab or scene reference which is exported to a separate glTF file.
|
|
961
961
|
|
|
@@ -997,7 +997,7 @@ Binary:`,i)}else console.debug("Could not determine file type from binary data")
|
|
|
997
997
|
`,n.uuid,`
|
|
998
998
|
`,o?.copy.uuid,`
|
|
999
999
|
`,e.name)}const h=n.clone();h.version=n.version,o?(o.copy=h,o.material=n,o.originalVersion=n.version):(o={material:n,copy:h,originalVersion:n.version},t.push(o)),h[Vf]=this,h[G_]=n,$r&&console.log("Set reflection",e.name,e.guid)}o&&o.copy&&(o.copy.onBeforeCompile=n.onBeforeCompile);const l=o?.copy;"envMap"in l&&l.envMap!==this.texture&&(l.envMap=this.texture,l.needsUpdate=!0),e.sharedMaterials[i]=l}}onUnset(e){const t=Zn._rendererMaterialsCache.get(e);if(t)for(let i=0;i<t.length;i++){const n=t[i];e.sharedMaterials[i]=n.material}}};rw([f(c.Vector3)],vg.prototype,"center");rw([f(c.Vector3)],vg.prototype,"size");let xc=vg;const $f=x("debugexr");class FM{get name(){return"EXT_texture_exr"}parser;constructor(e){this.parser=e,$f&&console.log(e)}loadTexture(e){const t=this.name,i=this.parser,o=i.json.textures[e];if($f&&console.log("EXT_texture_exr.loadTexture",e,o),!o.extensions||!o.extensions[t])return null;const r=o.extensions[t],a=new q.EXRLoader(i.options.manager);return $f&&console.log("EXT_texture_exr.loadTexture",r),i.loadTextureImage(e,r.source,a)}}typeof window<"u"&&window.addEventListener("unhandledrejection",s=>{});const wn=ot,Vh="$___Export_Components",zM="NEEDLE_components";class NM{[No]}class VM{node;nodeIndex;nodeDef;constructor(e,t,i){this.node=e,this.nodeIndex=t,this.nodeDef=i}}class aw{get name(){return zM}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[Vh]=i,!0)}afterSerializeUserData(e,t){if(e.type==="Scene"&&wn&&console.log("DONE",JSON.stringify(t)),e[Vh]===void 0)return;const i=e[Vh];delete e[Vh],i!==null&&(e.userData.components=i)}writeNode(e,t){const i=this.writer.json.nodes.length;wn&&console.log(e.name,i,e.uuid);const n=new VM(e,i,t);this.exportContext[i]=n,this.objectToNodeMap[e.uuid]=i}afterParse(e){wn&&console.log("AFTER",e);for(const t in this.exportContext){const i=this.exportContext[t],n=i.node,o=i.nodeDef,r=i.nodeIndex,a=n.userData?.components;if(!a||a.length<=0)continue;const l=new NM;o.extensions=o.extensions||{},o.extensions[this.name]=l,this.context.object=n,this.context.nodeId=r,this.context.objectToNode=this.objectToNodeMap;const h=[];for(const d of a){this.context.target=d;const u=cn().writeBuiltinComponentData(d,this.context);u!==null&&h.push(u)}h.length>0&&(l[No]=h,wn&&console.log("DID WRITE",n,"nodeIndex",r,h))}}parser;nodeToObjectMap={};gltf=null;beforeRoot(){return wn&&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];wn&&console.log("After root",e,this.parser,i);const o=[];if(n===!0){const r=t.json.nodes;if(r){for(let a=0;a<r.length;a++){const l=await t.getDependency("node",a);this.nodeToObjectMap[a]=l}for(let a=0;a<r.length;a++){const l=r[a],h=a,d=l.extensions;if(!d)continue;const u=d[this.name];if(!u)continue;wn&&console.log("NODE",l);const p=this.nodeToObjectMap[h];if(!p){console.error("Could not find object for node index: "+h,l,t);continue}cu(p),o.push(this.createComponents(e,l,p,u))}}}await Promise.all(o);for(const r of t.associations.keys()){const a=t.associations.get(r);if(a?.materials!=null){const l="/materials/"+a.materials;c1(r,l)}}}async createComponents(e,t,i,n){if(!n)return;const o=n[No];if(o){const r=new Array;wn&&console.log(i.name,o);for(const a in o){const l=o[a];if(wn&&console.log("Serialized data",JSON.parse(JSON.stringify(l))),(l?.name==="MeshRenderer"||l?.name==="SkinnedMeshRenderer")&&!l.sharedMaterials){let h=!1;if("mesh"in t){const d=t.mesh;if(typeof d=="number"&&e.parser){const u=e.parser.json.meshes?.[d];u?.primitives&&(l.sharedMaterials=u.primitives.map(p=>"/materials/"+(p.material??0)),h=!0)}}!h&&(wn||T())&&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(Xm(this.parser,l).catch(h=>console.error(`Error while resolving references (see console for details)
|
|
1000
|
-
`,h,i,l))),i.userData=i.userData||{},i.userData[No]=i.userData[No]||[],i.userData[No].push(l)}await Promise.all(r).catch(a=>{console.error("Error while loading components",a)})}}}const q_="NEEDLE_gameobject_data";class $M{get name(){return q_}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[q_];if(o){const r=this.findAndApplyExtensionData(i,o);t.push(r)}}}return Promise.all(t).then(()=>null)}async findAndApplyExtensionData(e,t){const i=await this.parser.getDependency("node",e);i&&this.applyExtensionData(i,t)}applyExtensionData(e,t){t.layers===void 0&&(t.layers=0),e.userData.layer=t.layers,e.layers.disableAll(),e.layers.set(t.layers),e.userData.tag=t.tag??"none",e.hideFlags=0,e.userData.static=t.static??!1,e.visible=t.activeSelf??!0,e.guid=t.guid}}const X_="NEEDLE_lighting_settings",ia=x("debugenvlight");class WM{get name(){return X_}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[X_];if(i){ia&&console.log('Loaded "'+this.name+'", src: "'+this.sourceId+'"',i);let n;if(e.scene.children.length===1){const o=e.scene.children[0];n=S.addComponent(o,Hd,{},{callAwake:!1})}else{const o=new c.Object3D;o.name="LightSettings "+this.sourceId,e.scene.add(o),n=S.addComponent(o,Hd,{},{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}}le.registerCallback(ae.ContextCreated,s=>{const e=s.context,t=S.findObjectOfType(Hd,e);t?.sourceId&&(t.enabled=!0)});class Hd extends E{ambientMode=_a.Skybox;ambientLight;ambientTrilight;ambientIntensity=1;environmentReflectionSource=Ud.Skybox;_hasReflection=!1;_ambientLightObj;_hemisphereLightObj;awake(){if(this.sourceId){const t=this.environmentReflectionSource===Ud.Skybox?kn.Skybox:kn.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),ia&&window.addEventListener("keydown",t=>{this.destroyed||t.key==="l"&&(this.enabled=!this.enabled)});const e=this.gameObject.userData?.components;if(e){const t=e.indexOf(this);e.splice(t,1),e.push(this)}}onDestroy(){this.context.sceneLighting.internalUnregisterSceneLightSettings(this)}calculateIntensityFactor(e){const t=Math.max(e.r,e.g,e.b);return 2.2*I.lerp(0,1.33,t)}onEnable(){if(ia&&console.warn("💡🟡 >>> Enable lighting",this.sourceId,this.enabled,this),this.ambientMode==_a.Flat){if(this.ambientLight&&!this._ambientLightObj){const e=this.calculateIntensityFactor(this.ambientLight);this._ambientLightObj=new c.AmbientLight(this.ambientLight,this.ambientIntensity*e),ia&&console.log("Created ambient light",this.sourceId,this._ambientLightObj,this.ambientIntensity,e)}this._ambientLightObj&&this.gameObject.add(this._ambientLightObj)}else if(this.ambientMode===_a.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),ia&&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(){ia&&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 exports.MODULES.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 HM 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 po.createPrimitive("ShaderBall",{material:e})}}class GM{constructor(e,t,i,n){this.context=e,this.loader=t,this.url=i,this.parser=n}get name(){return"materialx-loading-helper"}mtlxLoader;async beforeRoot(){if(this.parser.json.extensions?.NEEDLE_materials_mtlx){const t=await exports.MODULES.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 lw=(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))(lw||{});const Cn=x("debugcustomshader"),Wr="NEEDLE_techniques_webgl";class qM{objectToWorldMatrix=new c.Matrix4;worldToObjectMatrix=new c.Matrix4;objectToWorld=new Array;worldToObject=new Array;updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),Bd(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),Bd(this.worldToObjectMatrix,this.worldToObject)}}class _e extends c.RawShaderMaterial{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);clone(){const e=super.clone();return cw(e),e}constructor(e,...t){super(...t),this.identifier=e,Cn&&console.log(this),this.type="NEEDLE_CUSTOM_SHADER",this.uniforms[this._objToWorldName]||(this.uniforms[this._objToWorldName]={value:[]}),this.uniforms[this._worldToObjectName]||(this.uniforms[this._worldToObjectName]={value:[]}),this.uniforms[this._viewProjectionName]||(this.uniforms[this._viewProjectionName]={value:[]}),this.uniforms[this._sphericalHarmonicsName],(this.depthTextureUniform||this.opaqueTextureUniform)&&U.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}dispose(){super.dispose();const e=U.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&U.Current.pre_render_callbacks.splice(e,1)}_sphericalHarmonicsName="unity_SpecCube0";_objToWorldName="hlslcc_mtx4x4unity_ObjectToWorld";_worldToObjectName="hlslcc_mtx4x4unity_WorldToObject";static viewProjection=new c.Matrix4;static _viewProjectionValues=[];_viewProjectionName="hlslcc_mtx4x4unity_MatrixVP";static viewMatrix=new c.Matrix4;static _viewMatrixValues=[];_viewMatrixName="hlslcc_mtx4x4unity_MatrixV";static _worldSpaceCameraPosName="_WorldSpaceCameraPos";static _worldSpaceCameraPos=new c.Vector3;static _mainLightColor=new c.Vector4;static _mainLightPosition=new c.Vector3;static _lightData=new c.Vector4;_rendererData=new qM;get depthTextureUniform(){if(this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&U.Current.setRequireColor(!0),this.depthTextureUniform&&U.Current.setRequireDepth(!0)}onBeforeRender(e,t,i,n,o,r){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,o)}onUpdateUniforms(e,t){const i=U.Current;if(e&&(_e.viewProjection&&this.uniforms[this._viewProjectionName]&&(_e.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),Bd(_e.viewProjection,_e._viewProjectionValues)),_e.viewMatrix&&this.uniforms[this._viewMatrixName]&&(_e.viewMatrix.copy(e.matrixWorldInverse),Bd(_e.viewMatrix,_e._viewMatrixValues)),this.uniforms[_e._worldSpaceCameraPosName]&&_e._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=Q(n.gameObject,_e._mainLightPosition);this.uniforms._MainLightPosition={value:a.normalize()},_e._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:_e._mainLightColor};const l=n.intensity;_e._lightData.z=l,this.uniforms.unity_LightData={value:_e._lightData}}if(e&&(_e.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=_e._viewProjectionValues),_e.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=_e._viewMatrixValues),this.uniforms[_e._worldSpaceCameraPosName]&&(this.uniforms[_e._worldSpaceCameraPosName]={value:_e._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 XM{get name(){return Wr}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){const t=this.parser.json.materials[e];if(!t)return Cn&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[Wr])return Cn&&console.log(`Material ${e} does not use NEEDLE_techniques_webgl`),null;Cn&&console.log(`Material ${e} uses NEEDLE_techniques_webgl`,t);const i=t.extensions[Wr].technique;if(i<0)return console.debug(`Material ${e} does not have a valid technique index`),null;const n=this.parser.json.extensions[Wr];if(!n)return Cn?console.error("Missing shader data",this.parser.json.extensions):console.debug("Missing custom shader data in parser.json.extensions"),null;Cn&&console.log(n);const o=n.techniques[i];return o?new Promise(async(r,a)=>{const l=await $1(n,o.program),h=l?.fragmentShader,d=l?.vertexShader;if(!h||!d)return a();Cn&&console.log("loadMaterial",t,l);const u={},p=o.uniforms;(d.includes("_Time")||h.includes("_Time"))&&(u._Time={value:new c.Vector4(0,0,0,0)}),(d.includes("_SinTime")||h.includes("_SinTime"))&&(u._SinTime={value:new c.Vector4(0,0,0,0)}),(d.includes("_CosTime")||h.includes("_CosTime"))&&(u._CosTime={value:new c.Vector4(0,0,0,0)}),(d.includes("unity_DeltaTime")||h.includes("unity_DeltaTime"))&&(u.unity_DeltaTime={value:new c.Vector4(0,0,0,0)});for(const v in p){const b=v;switch(b){case"_TimeParameters":const w=new c.Vector4;u[b]={value:w};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":u[b]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":u[b]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":u[b]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":u[b]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":u[b]={value:null};break}}let m=!1;if(t.extensions&&t.extensions[Wr]){const v=t.extensions[Wr];if(v.technique===i){Cn&&console.log(t.name,"Material Properties",v);for(const b in v.values){const w=v.values[b];if(typeof w=="string"){if(w.startsWith("/textures/")){const R=w.substring(10),M=Number.parseInt(R);if(M>=0){const O=await this.parser.getDependency("texture",M);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 _e(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),N1(u),g.onUpdateUniforms();for(const v in p){const b=v,w=p[v].type;u[b]?.value===void 0&&(w===lw.SAMPLER_2D?(u[b]={value:F1},console.warn("Missing/unassigned texture, fallback to white: "+b)):b==="unity_OrthoParams"||console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+b,p[v]))}Cn&&console.log(g.uuid,u),cw(g),r(g)}):null}}function cw(s){if(s.uniforms){Cn&&console.log("Uniforms:",s.uniforms);for(const t in s.uniforms)e(t,t),t==="_Color"&&e("color",t)}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 QM=x("debugextensions");let Gd;const YM=Promise.resolve().then(()=>require("./vendor-COVQl0b8.umd.cjs")).then(s=>s.index$2).then(async s=>(Gd=s.GLTFAnimationPointerExtension,Gd)).catch(s=>{console.warn("Failed to import GLTFLoaderAnimationPointer. Please use @needle-tools/three-animationpointer for full KHR_animation support",s)}),hr=new Array;function KM(s){hr.includes(s)||hr.push(s)}function ZM(s){const e=hr.indexOf(s);e>=0&&hr.splice(e,1)}function wg(s){if(s instanceof q.GLTFLoader){const e=new aw;return s.register(t=>(e.parser=t,e)),e}return null}class JM{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 qd(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 $M(o)),s.register(o=>new d1(o)),s.register(o=>new I1(o,e.lightmaps,i)),s.register(o=>new WM(o,i,e)),s.register(o=>new XM(o,i)),s.register(o=>new Xs(o,i)),s.register(o=>new se.NEEDLE_progressive(o)),s.register(o=>new FM(o)),s.register(o=>new GM(e,s,t,o)),Av()&&s.register(o=>new ga(o)),await YM.catch(o=>{}),s.register(o=>{if(Gd){const r=new Gd(o);return r.setAnimationPointerResolver.bind(r)(new JM),r}else return(QM||T())&&console.error("Missing KHR_animation_pointer extension..."),{name:"KHR_animation_pointer_NOT_AVAILABLE"}});for(const o of hr)o.onImport&&o.onImport(s,t,e)}function xg(s,e){for(const t of hr)t.onExport&&t.onExport(s,e)}function hw(s,e,t){for(const i of hr)i.onLoaded&&i.onLoaded(s,e,t)}const Mt=x("debuginstancing");class dr{static instance=new dr;static getStartInstanceCount=e=>4;objs=[];setup(e,t,i,n,o,r=0){e.applySettings(t);const a=this.tryCreateOrAddInstance(t,i,o);if(a){n===null&&(n=[]),n.push(a);const l=a.object.material;Array.isArray(l)?l.forEach(u=>se.NEEDLE_progressive.assignTextureLOD(u,0)):se.NEEDLE_progressive.assignTextureLOD(l,0);const h=a.object,d=h.geometry;se.NEEDLE_progressive.assignMeshLOD(h,0).then(u=>{u&&d!=u&&a.setGeometry(u)})}else if(r<=0&&t.type!=="Mesh"){const l=r+1;for(const h of t.children)n=this.setup(e,h,i,n,o,l)}return r===0&&o.useMatrixWorldAutoUpdate&&n&&n.length>=0&&this.autoUpdateInstanceMatrix(t),n}tryCreateOrAddInstance(e,t,i){if(e.type==="Mesh"){const n=i.foundMeshes;if(i.foundMeshes+=1,!i.rend.enableInstancing)return null;if(i.rend.enableInstancing!==!0){if(n>=i.rend.enableInstancing.length)return Mt&&console.error("Something is wrong with instance setup",e,i.rend.enableInstancing,n),null;if(!i.rend.enableInstancing[n])return null}const o=e,r=o.material;for(const u of this.objs){if(!u.canAdd(o.geometry,r))continue;return u.addInstance(o)}let a=dr.getStartInstanceCount(e);(!a||a<0)&&(a=4);let l=e.name;l?.length||(l=zb());const h=new eO(l,o.geometry,r,a,t);return this.objs.push(h),h.addInstance(o)}return null}autoUpdateInstanceMatrix(e){const t=e.matrixWorld.multiplyMatrices.bind(e.matrixWorld),i=e.matrixWorld.clone(),n=(o,r)=>{const a=t(o,r);return(e[gc]||i.equals(a)===!1)&&(i.copy(a),e[gc]=!0),a};e.matrixWorld.multiplyMatrices=n}}class or{static all=[];get name(){return this.object.name}get isActive(){return this.__instanceIndex>=0}get vertexCount(){return this.object.geometry.attributes.position.count}get maxVertexCount(){return Math.max(this.meshInformation.vertexCount,this.vertexCount)}get reservedVertexCount(){return this.__reservedVertexRange}get indexCount(){return this.object.geometry.index?this.object.geometry.index.count:0}get maxIndexCount(){return Math.max(this.meshInformation.indexCount,this.indexCount)}get reservedIndexCount(){return this.__reservedIndexRange}object;renderer;__instanceIndex=-1;__reservedVertexRange=0;__reservedIndexRange=0;__geometryIndex=-1;meshInformation;constructor(e,t){this.__instanceIndex=-1,this.object=e,this.renderer=t,e[Bv]=t,this.meshInformation=$o(e.geometry),or.all.push(this)}updateMeshInformation(){const e=$o(this.object.geometry),t=this.meshInformation.vertexCount,i=this.meshInformation.indexCount;return Object.assign(this.meshInformation,e),t!==this.meshInformation.vertexCount||i!==this.meshInformation.indexCount}updateInstanceMatrix(e=!1,t=!0){this.__instanceIndex<0||(t&&this.object.updateWorldMatrix(!0,e),this.renderer.updateInstance(this.object.matrixWorld,this.__instanceIndex))}setMatrix(e){this.__instanceIndex<0||this.renderer.updateInstance(e,this.__instanceIndex)}setGeometry(e){if(this.__geometryIndex<0)return!1;const t=this;if(this.vertexCount>this.__reservedVertexRange)return i(`Instancing: Can not update geometry (${this.name}), reserved vertex range is too small: ${this.__reservedVertexRange.toLocaleString()} < ${this.vertexCount.toLocaleString()} vertices for ${this.name}`);if(this.indexCount>this.__reservedIndexRange)return i(`Instancing: Can not update geometry (${this.name}), reserved index range is too small: ${this.__reservedIndexRange.toLocaleString()} < ${this.indexCount.toLocaleString()} indices for ${this.name}`);return this.renderer.updateGeometry(e,this.__geometryIndex);function i(n){return t.updateMeshInformation()&&(t.renderer.remove(t,!0),t.renderer.add(t))?!0:((T()||Mt)&&console.error(n),!1)}}add(){this.__instanceIndex>=0||(this.renderer.add(this),S.markAsInstancedRendered(this.object,!0))}remove(e){if(!(this.__instanceIndex<0)&&(this.renderer.remove(this,e),S.markAsInstancedRendered(this.object,!1),e)){const t=or.all.indexOf(this);t>=0&&or.all.splice(t,1)}}}class eO{get batchedMesh(){return this._batchedMesh}get visible(){return this._batchedMesh.visible}set visible(e){this._batchedMesh.visible=e}get castShadow(){return this._batchedMesh.castShadow}set castShadow(e){this._batchedMesh.castShadow=e}set receiveShadow(e){this._batchedMesh.receiveShadow=e}allowResize=!0;name="";geometry;material;get count(){return this._currentInstanceCount}updateBounds(e=!0,t=!0){if(this._needUpdateBounds=!1,e&&this._batchedMesh.computeBoundingBox(),t&&this._batchedMesh.computeBoundingSphere(),Mt&&this._batchedMesh.boundingSphere){const i=this._batchedMesh.boundingSphere;j.DrawWireSphere(i.center,i.radius,65280)}}_context;_batchedMesh;_handles=[];_geometryIds=new WeakMap;_maxInstanceCount;_currentInstanceCount=0;_currentVertexCount=0;_currentIndexCount=0;_maxVertexCount;_maxIndexCount;static nullMatrix=new c.Matrix4;canAdd(e,t){return this._maxVertexCount>1e7||t!==this.material||!this.validateGeometry(e)?!1:!!(!this.mustGrow(e)||this.allowResize)}_needUpdateBounds=!1;_debugMaterial=null;getBatchedMeshName(){return this.name?`${this.name} (BatchedMesh)`:"BatchedMesh"}constructor(e,t,i,n,o){this.name=e,this.geometry=t,this.material=i,this._context=o,this._maxInstanceCount=Math.max(2,n),Mt&&(this._debugMaterial=Q_());const r=this.tryEstimateVertexCountSize(this._maxInstanceCount,[t],n);this._maxVertexCount=r.vertexCount,this._maxIndexCount=r.indexCount,this._batchedMesh=new c.BatchedMesh(this._maxInstanceCount,this._maxVertexCount,this._maxIndexCount,this._debugMaterial??this.material),this._batchedMesh.name=this.getBatchedMeshName(),this._batchedMesh[Il]=!0,this._batchedMesh.visible=!0,this._context.scene.add(this._batchedMesh),i instanceof c.RawShaderMaterial&&(i.defines.USE_INSTANCING=!0,i.needsUpdate=!0),o.pre_render_callbacks.push(this.onBeforeRender),o.post_render_callbacks.push(this.onAfterRender),Mt&&console.log(`Instanced renderer (${this.name}) created with ${this._maxInstanceCount} instances, ${this._maxVertexCount} max vertices and ${this._maxIndexCount} max indices for "${e}"`)}dispose(){Mt&&console.warn("Dispose instanced renderer",this.name),this._context.scene.remove(this._batchedMesh),this._batchedMesh.dispose(),this._batchedMesh=null,this._handles=[]}addInstance(e){const t=new or(e,this);e.castShadow===!0&&this._batchedMesh.castShadow===!1&&(this._batchedMesh.castShadow=!0),e.receiveShadow===!0&&this._batchedMesh.receiveShadow===!1&&(this._batchedMesh.receiveShadow=!0);try{this.add(t)}catch(i){if(console.error(`Failed adding mesh to instancing (object name: "${e.name}", instances: ${this._currentInstanceCount.toLocaleString()}/${this._maxInstanceCount.toLocaleString()}, vertices: ${this._currentVertexCount.toLocaleString()}/${this._maxVertexCount.toLocaleString()}, indices: ${this._currentIndexCount.toLocaleString()}/${this._maxIndexCount.toLocaleString()})
|
|
1000
|
+
`,h,i,l))),i.userData=i.userData||{},i.userData[No]=i.userData[No]||[],i.userData[No].push(l)}await Promise.all(r).catch(a=>{console.error("Error while loading components",a)})}}}const q_="NEEDLE_gameobject_data";class $M{get name(){return q_}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[q_];if(o){const r=this.findAndApplyExtensionData(i,o);t.push(r)}}}return Promise.all(t).then(()=>null)}async findAndApplyExtensionData(e,t){const i=await this.parser.getDependency("node",e);i&&this.applyExtensionData(i,t)}applyExtensionData(e,t){t.layers===void 0&&(t.layers=0),e.userData.layer=t.layers,e.layers.disableAll(),e.layers.set(t.layers),e.userData.tag=t.tag??"none",e.hideFlags=0,e.userData.static=t.static??!1,e.visible=t.activeSelf??!0,e.guid=t.guid}}const X_="NEEDLE_lighting_settings",ia=x("debugenvlight");class WM{get name(){return X_}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[X_];if(i){ia&&console.log('Loaded "'+this.name+'", src: "'+this.sourceId+'"',i);let n;if(e.scene.children.length===1){const o=e.scene.children[0];n=S.addComponent(o,Hd,{},{callAwake:!1})}else{const o=new c.Object3D;o.name="LightSettings "+this.sourceId,e.scene.add(o),n=S.addComponent(o,Hd,{},{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}}le.registerCallback(ae.ContextCreated,s=>{const e=s.context,t=S.findObjectOfType(Hd,e);t?.sourceId&&(t.enabled=!0)});class Hd extends E{ambientMode=_a.Skybox;ambientLight;ambientTrilight;ambientIntensity=1;environmentReflectionSource=Ud.Skybox;_hasReflection=!1;_ambientLightObj;_hemisphereLightObj;awake(){if(this.sourceId){const t=this.environmentReflectionSource===Ud.Skybox?kn.Skybox:kn.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),ia&&window.addEventListener("keydown",t=>{this.destroyed||t.key==="l"&&(this.enabled=!this.enabled)});const e=this.gameObject.userData?.components;if(e){const t=e.indexOf(this);e.splice(t,1),e.push(this)}}onDestroy(){this.context.sceneLighting.internalUnregisterSceneLightSettings(this)}calculateIntensityFactor(e){const t=Math.max(e.r,e.g,e.b);return 2.2*I.lerp(0,1.33,t)}onEnable(){if(ia&&console.warn("💡🟡 >>> Enable lighting",this.sourceId,this.enabled,this),this.ambientMode==_a.Flat){if(this.ambientLight&&!this._ambientLightObj){const e=this.calculateIntensityFactor(this.ambientLight);this._ambientLightObj=new c.AmbientLight(this.ambientLight,this.ambientIntensity*e),ia&&console.log("Created ambient light",this.sourceId,this._ambientLightObj,this.ambientIntensity,e)}this._ambientLightObj&&this.gameObject.add(this._ambientLightObj)}else if(this.ambientMode===_a.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),ia&&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(){ia&&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 exports.MODULES.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 HM 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 po.createPrimitive("ShaderBall",{material:e})}}class GM{constructor(e,t,i,n){this.context=e,this.loader=t,this.url=i,this.parser=n}get name(){return"materialx-loading-helper"}mtlxLoader;async beforeRoot(){if(this.parser.json.extensions?.NEEDLE_materials_mtlx){const t=await exports.MODULES.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 lw=(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))(lw||{});const Cn=x("debugcustomshader"),Wr="NEEDLE_techniques_webgl";class qM{objectToWorldMatrix=new c.Matrix4;worldToObjectMatrix=new c.Matrix4;objectToWorld=new Array;worldToObject=new Array;updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),Bd(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),Bd(this.worldToObjectMatrix,this.worldToObject)}}class _e extends c.RawShaderMaterial{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);clone(){const e=super.clone();return cw(e),e}constructor(e,...t){super(...t),this.identifier=e,Cn&&console.log(this),this.type="NEEDLE_CUSTOM_SHADER",this.uniforms[this._objToWorldName]||(this.uniforms[this._objToWorldName]={value:[]}),this.uniforms[this._worldToObjectName]||(this.uniforms[this._worldToObjectName]={value:[]}),this.uniforms[this._viewProjectionName]||(this.uniforms[this._viewProjectionName]={value:[]}),this.uniforms[this._sphericalHarmonicsName],(this.depthTextureUniform||this.opaqueTextureUniform)&&U.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}dispose(){super.dispose();const e=U.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&U.Current.pre_render_callbacks.splice(e,1)}_sphericalHarmonicsName="unity_SpecCube0";_objToWorldName="hlslcc_mtx4x4unity_ObjectToWorld";_worldToObjectName="hlslcc_mtx4x4unity_WorldToObject";static viewProjection=new c.Matrix4;static _viewProjectionValues=[];_viewProjectionName="hlslcc_mtx4x4unity_MatrixVP";static viewMatrix=new c.Matrix4;static _viewMatrixValues=[];_viewMatrixName="hlslcc_mtx4x4unity_MatrixV";static _worldSpaceCameraPosName="_WorldSpaceCameraPos";static _worldSpaceCameraPos=new c.Vector3;static _mainLightColor=new c.Vector4;static _mainLightPosition=new c.Vector3;static _lightData=new c.Vector4;_rendererData=new qM;get depthTextureUniform(){if(this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&U.Current.setRequireColor(!0),this.depthTextureUniform&&U.Current.setRequireDepth(!0)}onBeforeRender(e,t,i,n,o,r){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,o)}onUpdateUniforms(e,t){const i=U.Current;if(e&&(_e.viewProjection&&this.uniforms[this._viewProjectionName]&&(_e.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),Bd(_e.viewProjection,_e._viewProjectionValues)),_e.viewMatrix&&this.uniforms[this._viewMatrixName]&&(_e.viewMatrix.copy(e.matrixWorldInverse),Bd(_e.viewMatrix,_e._viewMatrixValues)),this.uniforms[_e._worldSpaceCameraPosName]&&_e._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=Q(n.gameObject,_e._mainLightPosition);this.uniforms._MainLightPosition={value:a.normalize()},_e._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:_e._mainLightColor};const l=n.intensity;_e._lightData.z=l,this.uniforms.unity_LightData={value:_e._lightData}}if(e&&(_e.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=_e._viewProjectionValues),_e.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=_e._viewMatrixValues),this.uniforms[_e._worldSpaceCameraPosName]&&(this.uniforms[_e._worldSpaceCameraPosName]={value:_e._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 XM{get name(){return Wr}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){const t=this.parser.json.materials[e];if(!t)return Cn&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[Wr])return Cn&&console.log(`Material ${e} does not use NEEDLE_techniques_webgl`),null;Cn&&console.log(`Material ${e} uses NEEDLE_techniques_webgl`,t);const i=t.extensions[Wr].technique;if(i<0)return console.debug(`Material ${e} does not have a valid technique index`),null;const n=this.parser.json.extensions[Wr];if(!n)return Cn?console.error("Missing shader data",this.parser.json.extensions):console.debug("Missing custom shader data in parser.json.extensions"),null;Cn&&console.log(n);const o=n.techniques[i];return o?new Promise(async(r,a)=>{const l=await $1(n,o.program),h=l?.fragmentShader,d=l?.vertexShader;if(!h||!d)return a();Cn&&console.log("loadMaterial",t,l);const u={},p=o.uniforms;(d.includes("_Time")||h.includes("_Time"))&&(u._Time={value:new c.Vector4(0,0,0,0)}),(d.includes("_SinTime")||h.includes("_SinTime"))&&(u._SinTime={value:new c.Vector4(0,0,0,0)}),(d.includes("_CosTime")||h.includes("_CosTime"))&&(u._CosTime={value:new c.Vector4(0,0,0,0)}),(d.includes("unity_DeltaTime")||h.includes("unity_DeltaTime"))&&(u.unity_DeltaTime={value:new c.Vector4(0,0,0,0)});for(const v in p){const b=v;switch(b){case"_TimeParameters":const w=new c.Vector4;u[b]={value:w};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":u[b]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":u[b]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":u[b]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":u[b]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":u[b]={value:null};break}}let m=!1;if(t.extensions&&t.extensions[Wr]){const v=t.extensions[Wr];if(v.technique===i){Cn&&console.log(t.name,"Material Properties",v);for(const b in v.values){const w=v.values[b];if(typeof w=="string"){if(w.startsWith("/textures/")){const R=w.substring(10),M=Number.parseInt(R);if(M>=0){const O=await this.parser.getDependency("texture",M);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 _e(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),N1(u),g.onUpdateUniforms();for(const v in p){const b=v,w=p[v].type;u[b]?.value===void 0&&(w===lw.SAMPLER_2D?(u[b]={value:F1},console.warn("Missing/unassigned texture, fallback to white: "+b)):b==="unity_OrthoParams"||console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+b,p[v]))}Cn&&console.log(g.uuid,u),cw(g),r(g)}):null}}function cw(s){if(s.uniforms){Cn&&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 QM=x("debugextensions");let Gd;const YM=Promise.resolve().then(()=>require("./vendor-COVQl0b8.umd.cjs")).then(s=>s.index$2).then(async s=>(Gd=s.GLTFAnimationPointerExtension,Gd)).catch(s=>{console.warn("Failed to import GLTFLoaderAnimationPointer. Please use @needle-tools/three-animationpointer for full KHR_animation support",s)}),hr=new Array;function KM(s){hr.includes(s)||hr.push(s)}function ZM(s){const e=hr.indexOf(s);e>=0&&hr.splice(e,1)}function wg(s){if(s instanceof q.GLTFLoader){const e=new aw;return s.register(t=>(e.parser=t,e)),e}return null}class JM{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 qd(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 $M(o)),s.register(o=>new d1(o)),s.register(o=>new I1(o,e.lightmaps,i)),s.register(o=>new WM(o,i,e)),s.register(o=>new XM(o,i)),s.register(o=>new Xs(o,i)),s.register(o=>new se.NEEDLE_progressive(o)),s.register(o=>new FM(o)),s.register(o=>new GM(e,s,t,o)),Av()&&s.register(o=>new ga(o)),await YM.catch(o=>{}),s.register(o=>{if(Gd){const r=new Gd(o);return r.setAnimationPointerResolver.bind(r)(new JM),r}else return(QM||T())&&console.error("Missing KHR_animation_pointer extension..."),{name:"KHR_animation_pointer_NOT_AVAILABLE"}});for(const o of hr)o.onImport&&o.onImport(s,t,e)}function xg(s,e){for(const t of hr)t.onExport&&t.onExport(s,e)}function hw(s,e,t){for(const i of hr)i.onLoaded&&i.onLoaded(s,e,t)}const Mt=x("debuginstancing");class dr{static instance=new dr;static getStartInstanceCount=e=>4;objs=[];setup(e,t,i,n,o,r=0){e.applySettings(t);const a=this.tryCreateOrAddInstance(t,i,o);if(a){n===null&&(n=[]),n.push(a);const l=a.object.material;Array.isArray(l)?l.forEach(u=>se.NEEDLE_progressive.assignTextureLOD(u,0)):se.NEEDLE_progressive.assignTextureLOD(l,0);const h=a.object,d=h.geometry;se.NEEDLE_progressive.assignMeshLOD(h,0).then(u=>{u&&d!=u&&a.setGeometry(u)})}else if(r<=0&&t.type!=="Mesh"){const l=r+1;for(const h of t.children)n=this.setup(e,h,i,n,o,l)}return r===0&&o.useMatrixWorldAutoUpdate&&n&&n.length>=0&&this.autoUpdateInstanceMatrix(t),n}tryCreateOrAddInstance(e,t,i){if(e.type==="Mesh"){const n=i.foundMeshes;if(i.foundMeshes+=1,!i.rend.enableInstancing)return null;if(i.rend.enableInstancing!==!0){if(n>=i.rend.enableInstancing.length)return Mt&&console.error("Something is wrong with instance setup",e,i.rend.enableInstancing,n),null;if(!i.rend.enableInstancing[n])return null}const o=e,r=o.material;for(const u of this.objs){if(!u.canAdd(o.geometry,r))continue;return u.addInstance(o)}let a=dr.getStartInstanceCount(e);(!a||a<0)&&(a=4);let l=e.name;l?.length||(l=zb());const h=new eO(l,o.geometry,r,a,t);return this.objs.push(h),h.addInstance(o)}return null}autoUpdateInstanceMatrix(e){const t=e.matrixWorld.multiplyMatrices.bind(e.matrixWorld),i=e.matrixWorld.clone(),n=(o,r)=>{const a=t(o,r);return(e[gc]||i.equals(a)===!1)&&(i.copy(a),e[gc]=!0),a};e.matrixWorld.multiplyMatrices=n}}class or{static all=[];get name(){return this.object.name}get isActive(){return this.__instanceIndex>=0}get vertexCount(){return this.object.geometry.attributes.position.count}get maxVertexCount(){return Math.max(this.meshInformation.vertexCount,this.vertexCount)}get reservedVertexCount(){return this.__reservedVertexRange}get indexCount(){return this.object.geometry.index?this.object.geometry.index.count:0}get maxIndexCount(){return Math.max(this.meshInformation.indexCount,this.indexCount)}get reservedIndexCount(){return this.__reservedIndexRange}object;renderer;__instanceIndex=-1;__reservedVertexRange=0;__reservedIndexRange=0;__geometryIndex=-1;meshInformation;constructor(e,t){this.__instanceIndex=-1,this.object=e,this.renderer=t,e[Bv]=t,this.meshInformation=$o(e.geometry),or.all.push(this)}updateMeshInformation(){const e=$o(this.object.geometry),t=this.meshInformation.vertexCount,i=this.meshInformation.indexCount;return Object.assign(this.meshInformation,e),t!==this.meshInformation.vertexCount||i!==this.meshInformation.indexCount}updateInstanceMatrix(e=!1,t=!0){this.__instanceIndex<0||(t&&this.object.updateWorldMatrix(!0,e),this.renderer.updateInstance(this.object.matrixWorld,this.__instanceIndex))}setMatrix(e){this.__instanceIndex<0||this.renderer.updateInstance(e,this.__instanceIndex)}setGeometry(e){if(this.__geometryIndex<0)return!1;const t=this;if(this.vertexCount>this.__reservedVertexRange)return i(`Instancing: Can not update geometry (${this.name}), reserved vertex range is too small: ${this.__reservedVertexRange.toLocaleString()} < ${this.vertexCount.toLocaleString()} vertices for ${this.name}`);if(this.indexCount>this.__reservedIndexRange)return i(`Instancing: Can not update geometry (${this.name}), reserved index range is too small: ${this.__reservedIndexRange.toLocaleString()} < ${this.indexCount.toLocaleString()} indices for ${this.name}`);return this.renderer.updateGeometry(e,this.__geometryIndex);function i(n){return t.updateMeshInformation()&&(t.renderer.remove(t,!0),t.renderer.add(t))?!0:((T()||Mt)&&console.error(n),!1)}}add(){this.__instanceIndex>=0||(this.renderer.add(this),S.markAsInstancedRendered(this.object,!0))}remove(e){if(!(this.__instanceIndex<0)&&(this.renderer.remove(this,e),S.markAsInstancedRendered(this.object,!1),e)){const t=or.all.indexOf(this);t>=0&&or.all.splice(t,1)}}}class eO{get batchedMesh(){return this._batchedMesh}get visible(){return this._batchedMesh.visible}set visible(e){this._batchedMesh.visible=e}get castShadow(){return this._batchedMesh.castShadow}set castShadow(e){this._batchedMesh.castShadow=e}set receiveShadow(e){this._batchedMesh.receiveShadow=e}allowResize=!0;name="";geometry;material;get count(){return this._currentInstanceCount}updateBounds(e=!0,t=!0){if(this._needUpdateBounds=!1,e&&this._batchedMesh.computeBoundingBox(),t&&this._batchedMesh.computeBoundingSphere(),Mt&&this._batchedMesh.boundingSphere){const i=this._batchedMesh.boundingSphere;j.DrawWireSphere(i.center,i.radius,65280)}}_context;_batchedMesh;_handles=[];_geometryIds=new WeakMap;_maxInstanceCount;_currentInstanceCount=0;_currentVertexCount=0;_currentIndexCount=0;_maxVertexCount;_maxIndexCount;static nullMatrix=new c.Matrix4;canAdd(e,t){return this._maxVertexCount>1e7||t!==this.material||!this.validateGeometry(e)?!1:!!(!this.mustGrow(e)||this.allowResize)}_needUpdateBounds=!1;_debugMaterial=null;getBatchedMeshName(){return this.name?`${this.name} (BatchedMesh)`:"BatchedMesh"}constructor(e,t,i,n,o){this.name=e,this.geometry=t,this.material=i,this._context=o,this._maxInstanceCount=Math.max(2,n),Mt&&(this._debugMaterial=Q_());const r=this.tryEstimateVertexCountSize(this._maxInstanceCount,[t],n);this._maxVertexCount=r.vertexCount,this._maxIndexCount=r.indexCount,this._batchedMesh=new c.BatchedMesh(this._maxInstanceCount,this._maxVertexCount,this._maxIndexCount,this._debugMaterial??this.material),this._batchedMesh.name=this.getBatchedMeshName(),this._batchedMesh[Il]=!0,this._batchedMesh.visible=!0,this._context.scene.add(this._batchedMesh),i instanceof c.RawShaderMaterial&&(i.defines.USE_INSTANCING=!0,i.needsUpdate=!0),o.pre_render_callbacks.push(this.onBeforeRender),o.post_render_callbacks.push(this.onAfterRender),Mt&&console.log(`Instanced renderer (${this.name}) created with ${this._maxInstanceCount} instances, ${this._maxVertexCount} max vertices and ${this._maxIndexCount} max indices for "${e}"`)}dispose(){Mt&&console.warn("Dispose instanced renderer",this.name),this._context.scene.remove(this._batchedMesh),this._batchedMesh.dispose(),this._batchedMesh=null,this._handles=[]}addInstance(e){const t=new or(e,this);e.castShadow===!0&&this._batchedMesh.castShadow===!1&&(this._batchedMesh.castShadow=!0),e.receiveShadow===!0&&this._batchedMesh.receiveShadow===!1&&(this._batchedMesh.receiveShadow=!0);try{this.add(t)}catch(i){if(console.error(`Failed adding mesh to instancing (object name: "${e.name}", instances: ${this._currentInstanceCount.toLocaleString()}/${this._maxInstanceCount.toLocaleString()}, vertices: ${this._currentVertexCount.toLocaleString()}/${this._maxVertexCount.toLocaleString()}, indices: ${this._currentIndexCount.toLocaleString()}/${this._maxIndexCount.toLocaleString()})
|
|
1001
1001
|
`,i),T()){jc("Failed instancing mesh. See the browser console for details.");debugger}return null}return t}add(e){const t=e.object.geometry;if(!t||!t.attributes)return console.error("Cannot add object to instancing without geometry",e.name),!1;if(this._currentInstanceCount+1>this._maxInstanceCount||this.mustGrow(t))if(this.allowResize)this.grow(t);else return console.error("Cannot add instance, max count reached",this.name,this.count,this._maxInstanceCount),!1;return e.object.updateWorldMatrix(!0,!0),this.addGeometry(e),this._handles[e.__instanceIndex]=e,this._currentInstanceCount+=1,this.markNeedsUpdate(),this._currentInstanceCount>0&&(this._batchedMesh.visible=!0),!0}remove(e,t){e&&(e.__instanceIndex<0||this._handles[e.__instanceIndex]!=e||this._currentInstanceCount<=0||(this.removeGeometry(e,t),this._handles[e.__instanceIndex]=null,e.__instanceIndex=-1,this._currentInstanceCount>0&&(this._currentInstanceCount-=1),this._currentInstanceCount<=0&&(this._batchedMesh.visible=!1),this.markNeedsUpdate()))}updateInstance(e,t){this._batchedMesh.setMatrixAt(t,e),this.markNeedsUpdate()}updateGeometry(e,t){return this.validateGeometry(e)?(this.mustGrow()&&this.grow(e),Mt&&console.debug("[Instancing] UPDATE GEOMETRY at "+t,this._batchedMesh._geometryCount,e.name,$o(e),e.attributes.position.count,e.index?e.index.count:0),this._batchedMesh.setGeometryAt(t,e),this._geometryIds.set(e,t),this.markNeedsUpdate(),!0):!1}onBeforeRender=()=>{this._batchedMesh.layers.enableAll(),this._needUpdateBounds&&this._batchedMesh[Il]===!0&&(Mt==="verbose"&&console.log("Update instancing bounds",this.name,this._batchedMesh.matrixWorldNeedsUpdate),this.updateBounds())};onAfterRender=()=>{this._batchedMesh.layers.disableAll()};validateGeometry(e){const t=this.geometry;for(const i in t.attributes)if(i!=="batchId"&&!e.hasAttribute(i))return T()&&console.warn(`BatchedMesh: Added geometry missing "${i}". All geometries must have consistent attributes.`),!1;return!0}markNeedsUpdate(){Mt==="verbose"&&console.warn("Marking instanced mesh dirty",this.name),this._needUpdateBounds=!0}mustGrow(e){if(this.count>=this._maxInstanceCount)return!0;if(!e||!e.attributes||this._geometryIds.has(e))return!1;const i=$o(e),n=i.vertexCount,o=i.indexCount;return this._currentVertexCount+n>this._maxVertexCount||this._currentIndexCount+o>this._maxIndexCount}_growId=0;grow(e){const t=++this._growId,o=this.count>=this._maxInstanceCount?Math.ceil(this._maxInstanceCount*2):this._maxInstanceCount,r=this.tryEstimateVertexCountSize(o,[e]),a=1.25,l=Math.max(this._maxVertexCount,Math.ceil(r.vertexCount*a)),h=Math.max(this._maxIndexCount,Math.ceil(r.indexCount*a));if(Mt){const p=$o(e);console.warn(`[Instancing] Growing Buffer
|
|
1002
1002
|
Mesh: "${this.name}${e.name?.length?"/"+e.name:""}" (${p.vertexCount.toLocaleString()} vertices, ${p.indexCount.toLocaleString()} indices)
|
|
1003
1003
|
Max count ${this._maxInstanceCount.toLocaleString()} → ${o.toLocaleString()}
|
|
@@ -1080,7 +1080,7 @@ Texture:`,i),this.setLightmapDebugMaterial()):Hr&&console.log("Use debuglightmap
|
|
|
1080
1080
|
${n}${p.length>0?p.join(`
|
|
1081
1081
|
`):""}
|
|
1082
1082
|
${n}}
|
|
1083
|
-
`}function yO(s,e,t,i){let n="";for(const o of s)n+=gO(o,e,i,t);return n}function _O(s){return bi(s.name)+"_"+(s.source?.id??s.id)}function bi(s){return s=s.replace(/[^a-zA-Z0-9_]/g,""),s.match(/^[a-zA-Z_]/)||(s="_"+s),s}function _w(s){return s=s.replace('"','\\"'),s}function bw(s){if(s.length===0)return null;const e=s.map(i=>{const n=new Array;for(;i.parent;)n.unshift(i.parent),i=i.parent;return n});return e[0].findLast(i=>e.every(n=>n.includes(i)))||null}function vw(s){const e=bw(s),t=new Set;for(const i of s){let n=i.parent;for(;n&&n!==e;)s.includes(n)||t.add(n),n=n.parent}return t}const bO=new c.Vector3,vO=new c.Quaternion,wO=new c.Vector3(1,1,1);class
|
|
1083
|
+
`}function yO(s,e,t,i){let n="";for(const o of s)n+=gO(o,e,i,t);return n}function _O(s){return bi(s.name)+"_"+(s.source?.id??s.id)}function bi(s){return s=s.replace(/[^a-zA-Z0-9_]/g,""),s.match(/^[a-zA-Z_]/)||(s="_"+s),s}function _w(s){return s=s.replace('"','\\"'),s}function bw(s){if(s.length===0)return null;const e=s.map(i=>{const n=new Array;for(;i.parent;)n.unshift(i.parent),i=i.parent;return n});return e[0].findLast(i=>e.every(n=>n.includes(i)))||null}function vw(s){const e=bw(s),t=new Set;for(const i of s){let n=i.parent;for(;n&&n!==e;)s.includes(n)||t.add(n),n=n.parent}return t}const bO=new c.Vector3,vO=new c.Quaternion,wO=new c.Vector3(1,1,1);class He{static USDObject_export_id=0;uuid;name;type;extraSchemas=[];displayName;visibility;getMatrix(){if(!this.transform)return new c.Matrix4;const{position:e,quaternion:t,scale:i}=this.transform,n=new c.Matrix4;return n.compose(e||bO,t||vO,i||wO),n}setMatrix(e){if(!e||!(e instanceof c.Matrix4)){this.transform=null;return}const t=new c.Vector3,i=new c.Quaternion,n=new c.Vector3;e.decompose(t,i,n),this.transform={position:t,quaternion:i,scale:n}}get matrix(){return this.getMatrix()}set matrix(e){this.setMatrix(e)}transform=null;_isDynamic;get isDynamic(){return this._isDynamic}set isDynamic(e){this._isDynamic=e}geometry;material;camera;parent;skinnedMesh;children=[];animations;_eventListeners;needsTranslate=!1;needsOrient=!1;needsScale=!1;static createEmptyParent(e){const t=new He(c.MathUtils.generateUUID(),e.name+"_empty_"+He.USDObject_export_id++,e.transform),i=e.parent;return i&&i.add(t),t.add(e),t.isDynamic=!0,e.transform=null,t}static createEmpty(){const e=new He(c.MathUtils.generateUUID(),"Empty_"+He.USDObject_export_id++);return e.isDynamic=!0,e}constructor(e,t,i=null,n=null,o=null,r=null,a=null,l=null){this.uuid=e,this.name=bi(t),this.displayName=t,i?this.transform={position:i.position?.clone()||null,quaternion:i.quaternion?.clone()||null,scale:i.scale?.clone()||null}:this.transform=null,this.geometry=n,this.material=o,this.camera=r,this.parent=null,this.children=[],this._eventListeners={},this._isDynamic=!1,this.skinnedMesh=a,this.animations=l}is(e){return e?this.uuid===e.uuid:!1}isEmpty(){return!this.geometry}clone(){const e=new He(c.MathUtils.generateUUID(),this.name,this.transform,this.geometry,this.material);return e.isDynamic=this.isDynamic,e}deepClone(){const e=this.clone();for(const t of this.children)t&&e.add(t.deepClone());return e}getPath(){let e=this.parent,t=this.name;for(;e;)t=(e.parent?e.name:e.name+"/Scenes/Scene")+"/"+t,e=e.parent;return"</"+t+">"}add(e){e.parent&&e.parent.remove(e),e.parent=this,this.children.push(e)}remove(e){const t=this.children.indexOf(e);t>=0&&(e.parent===this&&(e.parent=null),this.children.splice(t,1))}addEventListener(e,t){this._eventListeners[e]||(this._eventListeners[e]=[]),this._eventListeners[e].push(t)}removeEventListener(e,t){if(!this._eventListeners[e])return;const i=this._eventListeners[e].indexOf(t);i>=0&&this._eventListeners[e].splice(i,1)}onSerialize(e,t){const i=this._eventListeners.serialize;i&&i.forEach(n=>n(e,t))}}class Ag extends He{stageLength;get isDocumentRoot(){return!0}get isDynamic(){return!1}constructor(){super(void 0,"StageRoot",null,null,null,null),this.children=[],this.stageLength=200}add(e){e.parent=this,this.children.push(e)}remove(e){const t=this.children.indexOf(e);t>=0&&(e.parent===this&&(e.parent=null),this.children.splice(t,1))}traverse(e,t=null){if(t!==null?e(t):t=this,t.children)for(const i of t.children)this.traverse(e,i)}findById(e){let t=!1;function i(n){if(!t){if(n.uuid===e)return t=!0,n;if(n.children)for(const o of n.children){if(!o)continue;const r=i(o);if(r)return r}}}return i(this)}buildHeader(e){const t=e.extensions?.find(d=>d?.extensionName==="animation"),i=e.extensions?.find(d=>d?.extensionName==="Behaviour"),n=e.extensions?.find(d=>d?.extensionName==="Physics"),o=t?.getStartTimeCode()??0,r=t?.getEndTimeCode()??0;let a="";const l=t?.registeredClips;if(l)for(const d of l)a+=` # Animation: ${d.name}, start=${t.getStartTimeByClip(d)*60}, length=${d.duration*60}
|
|
1084
1084
|
`;const h=a;return`#usda 1.0
|
|
1085
1085
|
(
|
|
1086
1086
|
customLayerData = {
|
|
@@ -1104,7 +1104,7 @@ ${h}
|
|
|
1104
1104
|
)
|
|
1105
1105
|
`}}const Gr=`
|
|
1106
1106
|
`,Ut="</StageRoot/Materials";class ww{str;indent;constructor(){this.str="",this.indent=0}clear(){this.str="",this.indent=0}beginBlock(e=void 0,t="{",i=!0){e!==void 0?(e=this.applyIndent(e),this.str+=e,i?(this.str+=Gr,this.str+=this.applyIndent(t)):this.str+=" "+t):this.str+=this.applyIndent(t),this.str+=Gr,this.indent+=1}closeBlock(e="}"){this.indent-=1,this.str+=this.applyIndent(e)+Gr}beginArray(e){e=this.applyIndent(e+" = ["),this.str+=e,this.str+=Gr,this.indent+=1}closeArray(){this.indent-=1,this.str+=this.applyIndent("]")+Gr}appendLine(e=""){e=this.applyIndent(e),this.str+=e,this.str+=Gr}toString(){return this.str}applyIndent(e){let t="";for(let i=0;i<this.indent;i++)t+=" ";return t+e}}class xO{root;exporter;extensions=[];quickLookCompatible;exportInvisible;materials;textures;files;document;output;animations;constructor(e,t,i){this.root=e||void 0,this.exporter=t,this.quickLookCompatible=i.quickLookCompatible,this.exportInvisible=i.exportInvisible,i.extensions&&(this.extensions=i.extensions),this.materials=new Map,this.textures={},this.files={},this.document=new Ag,this.output="",this.animations=[]}makeNameSafe(e){return bi(e)}}const Z_=()=>({ar:{anchoring:{type:"plane"},planeAnchoring:{alignment:"horizontal"}},quickLookCompatible:!1,extensions:[],maxTextureSize:4096,exportInvisible:!1});let xw=class{debug;pruneUnusedNodes;sceneAnchoringOptions=Z_();extensions=[];keepObject;beforeWritingDocument;constructor(){this.debug=!1,this.pruneUnusedNodes=!0}async parse(e,t=Z_()){t=Object.assign({},t),this.sceneAnchoringOptions=t;const i=new xO(e,this,t);this.extensions=i.extensions;const n=i.files,o="model.usda";n[o]=null,i.materials;const r=i.textures;ne.report("export-usdz","Invoking onBeforeBuildDocument"),await vd(i,"onBeforeBuildDocument"),ne.report("export-usdz","Done onBeforeBuildDocument"),ne.report("export-usdz","Reparent bones to common ancestor");const a=[],l=new Set;e?.traverse(v=>{if(!(!t.exportInvisible&&!v.visible)&&v instanceof c.SkinnedMesh){const b=v.skeleton.bones,w=bw(b);if(w){const R={object:v,originalParent:v.parent,newParent:w};a.push(R),l.add(R.object.uuid),R.newParent&&l.add(R.newParent.uuid),R.originalParent&&l.add(R.originalParent.uuid)}}});for(const v of a){const{object:b,originalParent:w,newParent:R}=v;R.add(b)}ne.report("export-usdz","Traversing hierarchy"),e&&Sw(e,i.document,i,this.keepObject),ne.report("export-usdz","Invoking onAfterBuildDocument"),await vd(i,"onAfterBuildDocument");const d=i.extensions.find(v=>v.extensionName==="Behaviour")?.getAllTargetUuids()??new Set;if(this.pruneUnusedNodes){const v={allBehaviorTargets:d,debug:!1,boneReparentings:l,quickLookCompatible:i.quickLookCompatible};this.debug&&J_(i.document,"Hierarchy BEFORE pruning",v),Cw(i.document,v),this.debug&&J_(i.document,"Hierarchy AFTER pruning")}else this.debug&&console.log("Pruning of empty nodes is disabled. This may result in a larger USDZ file.");ne.report("export-usdz",{message:"Parsing document",autoStep:10}),await SO(i,t),ne.report("export-usdz","Invoking onAfterSerialize"),await vd(i,"onAfterSerialize");for(const v of a){const{object:b,originalParent:w,newParent:R}=v;w&&w.add(b)}i.exporter?.beforeWritingDocument?.();const p=i.document.buildHeader(i)+`
|
|
1107
|
-
`+i.output;this.debug&&console.debug(p),n[o]=q.strToU8(p),i.output="",ne.report("export-usdz",{message:"Exporting textures",autoStep:10}),ne.start("export-usdz-textures",{parentScope:"export-usdz",logTimings:!1});const m=new c.WebGLRenderer({antialias:!1,alpha:!0,premultipliedAlpha:!1,preserveDrawingBuffer:!0}),g=Object.keys(r).length;ne.report("export-usdz-textures",{totalSteps:g*3,currentStep:0});const _=async v=>{const b=r[v],w=b.texture,R=Dg.includes(w.format);let M={imageData:w.image};ne.report("export-usdz-textures",{message:"read back texture",autoStep:!0});const O=b.scale!==void 0&&b.scale.x!==1&&b.scale.y!==1&&b.scale.z!==1&&b.scale.w!==1;(w.isCompressedTexture||w.isRenderTargetTexture||O)&&(M=await Mw(w,t.maxTextureSize,m,b.scale)),ne.report("export-usdz-textures",{message:"convert texture to canvas",autoStep:!0});const A=await PO(M.imageBitmap||M.imageData,t.maxTextureSize).catch(D=>{console.error("Error converting texture to canvas",w,D)});if(A){ne.report("export-usdz-textures",{message:"convert canvas to blob",autoStep:!0});const D=await A.convertToBlob({type:R?"image/png":"image/jpeg",quality:.95});n[`textures/${v}.${R?"png":"jpg"}`]=new Uint8Array(await D.arrayBuffer())}else console.warn("Can`t export texture: ",w)};for(const v in r)await _(v);m.dispose(),ne.end("export-usdz-textures");let y=0;for(const v in n){const b=n[v],w=34+v.length;y+=w;const R=y&63;if(R!==4){const M=64-R,O=new Uint8Array(M);n[v]=[b,{extra:{12345:O}}]}y=b.length}return ne.report("export-usdz","zip archive"),q.zipSync(n,{level:0})}};function Sw(s,e,t,i){if(!t.exportInvisible&&!s.visible)return;let n,o,r;const a={position:s.position,quaternion:s.quaternion,scale:s.scale};if(s.position.x===0&&s.position.y===0&&s.position.z===0&&(a.position=null),s.quaternion.x===0&&s.quaternion.y===0&&s.quaternion.z===0&&s.quaternion.w===1&&(a.quaternion=null),s.scale.x===1&&s.scale.y===1&&s.scale.z===1&&(a.scale=null),(s instanceof c.Mesh||s instanceof c.SkinnedMesh)&&(o=s.geometry,r=s.material),i&&!i(s)&&(o=void 0,r=void 0),(s instanceof c.Mesh||s instanceof c.SkinnedMesh)&&r&&typeof r=="object"&&(r instanceof c.MeshStandardMaterial||r instanceof c.MeshBasicMaterial||r.isMeshPhysicalNodeMaterial||r instanceof c.Material&&r.type==="MeshLineMaterial")){const l=qh(s),h=s instanceof c.SkinnedMesh?s:null;n=new
|
|
1107
|
+
`+i.output;this.debug&&console.debug(p),n[o]=q.strToU8(p),i.output="",ne.report("export-usdz",{message:"Exporting textures",autoStep:10}),ne.start("export-usdz-textures",{parentScope:"export-usdz",logTimings:!1});const m=new c.WebGLRenderer({antialias:!1,alpha:!0,premultipliedAlpha:!1,preserveDrawingBuffer:!0}),g=Object.keys(r).length;ne.report("export-usdz-textures",{totalSteps:g*3,currentStep:0});const _=async v=>{const b=r[v],w=b.texture,R=Dg.includes(w.format);let M={imageData:w.image};ne.report("export-usdz-textures",{message:"read back texture",autoStep:!0});const O=b.scale!==void 0&&b.scale.x!==1&&b.scale.y!==1&&b.scale.z!==1&&b.scale.w!==1;(w.isCompressedTexture||w.isRenderTargetTexture||O)&&(M=await Mw(w,t.maxTextureSize,m,b.scale)),ne.report("export-usdz-textures",{message:"convert texture to canvas",autoStep:!0});const A=await PO(M.imageBitmap||M.imageData,t.maxTextureSize).catch(D=>{console.error("Error converting texture to canvas",w,D)});if(A){ne.report("export-usdz-textures",{message:"convert canvas to blob",autoStep:!0});const D=await A.convertToBlob({type:R?"image/png":"image/jpeg",quality:.95});n[`textures/${v}.${R?"png":"jpg"}`]=new Uint8Array(await D.arrayBuffer())}else console.warn("Can`t export texture: ",w)};for(const v in r)await _(v);m.dispose(),ne.end("export-usdz-textures");let y=0;for(const v in n){const b=n[v],w=34+v.length;y+=w;const R=y&63;if(R!==4){const M=64-R,O=new Uint8Array(M);n[v]=[b,{extra:{12345:O}}]}y=b.length}return ne.report("export-usdz","zip archive"),q.zipSync(n,{level:0})}};function Sw(s,e,t,i){if(!t.exportInvisible&&!s.visible)return;let n,o,r;const a={position:s.position,quaternion:s.quaternion,scale:s.scale};if(s.position.x===0&&s.position.y===0&&s.position.z===0&&(a.position=null),s.quaternion.x===0&&s.quaternion.y===0&&s.quaternion.z===0&&s.quaternion.w===1&&(a.quaternion=null),s.scale.x===1&&s.scale.y===1&&s.scale.z===1&&(a.scale=null),(s instanceof c.Mesh||s instanceof c.SkinnedMesh)&&(o=s.geometry,r=s.material),i&&!i(s)&&(o=void 0,r=void 0),(s instanceof c.Mesh||s instanceof c.SkinnedMesh)&&r&&typeof r=="object"&&(r instanceof c.MeshStandardMaterial||r instanceof c.MeshBasicMaterial||r.isMeshPhysicalNodeMaterial||r instanceof c.Material&&r.type==="MeshLineMaterial")){const l=qh(s),h=s instanceof c.SkinnedMesh?s:null;n=new He(s.uuid,l,a,o,r,void 0,h,s.animations)}else if(s instanceof c.PerspectiveCamera||s instanceof c.OrthographicCamera){const l=qh(s);n=new He(s.uuid,l,a,void 0,void 0,s)}else{const l=qh(s);n=new He(s.uuid,l,a,void 0,void 0,void 0,void 0,s.animations)}if(n){if(n.displayName=s.userData?.name||s.name,n.visibility=s.visible?void 0:"invisible",e&&e.add(n),e=n,t.extensions)for(const l of t.extensions)l.onExportObject&&l.onExportObject.call(l,s,n,t)}else{const l=qh(s),h=new He(s.uuid,l,{position:s.position,quaternion:s.quaternion,scale:s.scale});e&&e.add(h),e=h}for(const l of s.children)Sw(l,e,t,i)}function J_(s,e,...t){const i={};let n=0;function o(r,a){n++;let l=r.displayName||r.name;l+=" ("+r.uuid+")",(r.geometry||r.material||r.camera||r.skinnedMesh)&&(l+=" ("+(r.geometry?"geo, ":"")+(r.material?"mat, ":"")+(r.camera?"cam, ":"")+(r.skinnedMesh?"skin, ":"")+")"),a[l]={};const d={object:r};r.material&&(d.mat=!0),r.geometry&&(d.geo=!0),r.camera&&(d.cam=!0),r.skinnedMesh&&(d.skin=!0),a[l]._self=d;for(const u of r.children)u&&o(u,a[l])}o(s,i),console.log(e+" ("+n+" nodes)",i,...t)}function Cw(s,e){let t=!0;const i=new Array,n=new Array;if(s.children.length===0)t=!0;else{const h=[...s.children];for(const d of h)if(d){const u=Cw(d,e);e.debug&&(u?i.push(d):n.push(d)),t=t&&u}}const o=e.allBehaviorTargets.has(s.uuid),r=s.geometry||s.material||s.camera&&!e.quickLookCompatible||s.skinnedMesh||!1,a=e.boneReparentings.has(s.uuid),l=t&&!o&&!r&&!a;return l?(e.debug&&console.log("Pruned object:",(s.displayName||s.name)+" ("+s.uuid+")",{isVisible:r,isBehaviorSourceOrTarget:o,allChildsWerePruned:t,isBoneReparenting:a,object:s,prunedChilds:i,keptChilds:n}),s.parent?.remove(s)):e.debug&&console.log("Kept object:",(s.displayName||s.name)+" ("+s.uuid+")",{isVisible:r,isBehaviorSourceOrTarget:o,allChildsWerePruned:t,isBoneReparenting:a,object:s,prunedChilds:i,keptChilds:n}),l}async function SO(s,e){ne.start("export-usdz-resources","export-usdz");const t=[];for(const h of s.document.children)Pw(h,s,t);const i=t.length;for(let h=0;h<i;h++)ne.report("export-usdz-resources",{totalSteps:i,currentStep:h}),await new Promise((d,u)=>{t[h](),d()});ne.end("export-usdz-resources");const n=new ww,o=s.exporter.sceneAnchoringOptions.ar;n.beginBlock(`def Xform "${s.document.name}"`),n.beginBlock(`def Scope "Scenes" (
|
|
1108
1108
|
kind = "sceneLibrary"
|
|
1109
1109
|
)`),n.beginBlock('def Xform "Scene"',"(",!1),n.appendLine('apiSchemas = ["Preliminary_AnchoringAPI"]'),n.appendLine("customData = {"),n.appendLine(" bool preliminary_collidesWithEnvironment = 0"),n.appendLine(' string sceneName = "Scene"'),n.appendLine("}"),n.appendLine('sceneName = "Scene"'),n.closeBlock(")"),n.beginBlock(),n.appendLine(`token preliminary:anchoring:type = "${o.anchoring.type}"`),o.anchoring.type==="plane"&&n.appendLine(`token preliminary:planeAnchoring:alignment = "${o.planeAnchoring.alignment}"`),o.anchoring.type==="image"&&n.appendLine(`rel preliminary:imageAnchoring:referenceImage = </${s.document.name}/Scenes/Scene/AnchoringReferenceImage>`),n.appendLine();const r=h=>{if(!h)return 0;let d=1;for(const u of h.children)d+=r(u);return d},a=r(s.document);ne.start("export-usdz-xforms","export-usdz"),ne.report("export-usdz-xforms",{totalSteps:a,currentStep:1});for(const h of s.document.children)kw(h,n,s);ne.end("export-usdz-xforms"),ne.report("export-usdz","invoke onAfterHierarchy"),await vd(s,"onAfterHierarchy",n),n.closeBlock(),n.closeBlock(),ne.report("export-usdz","Building materials");const l=TO(s.materials,s.textures,e.quickLookCompatible);n.appendLine(l),n.closeBlock(),ne.report("export-usdz","write to string"),s.output+=n.toString()}function Pw(s,e,t){if(!s)return;const i=s.geometry,n=s.material;if(i)if(n&&("isMeshStandardMaterial"in n&&n.isMeshStandardMaterial||"isMeshBasicMaterial"in n&&n.isMeshBasicMaterial||n.type==="MeshLineMaterial")){const o="geometries/"+Jp(i,s.name)+".usda";if(!(o in e.files)){const r=()=>{const a=kO(i,s.skinnedMesh?.skeleton?.bones,e.quickLookCompatible);e.files[o]=OO(a)};t.push(r)}}else console.warn("NeedleUSDZExporter: Unsupported material type (USDZ only supports MeshStandardMaterial)",n?.name);n&&e.materials.get(n.uuid)===void 0&&(e.materials[n.uuid]=n);for(const o of s.children)Pw(o,e,t)}async function vd(s,e,t=null){if(s.extensions){for(const i of s.extensions)if(i&&typeof i[e]=="function"){const o=i[e].call(i,s,t);o instanceof Promise&&await o}}}let Hh=null,jt=null,Gf,qr,Gh;async function Mw(s,e=1/0,t=null,i=void 0){Gf||(Gf=new c.PlaneGeometry(2,2,1,1)),qr||(qr=new c.ShaderMaterial({uniforms:{blitTexture:new c.Uniform$1(s),flipY:new c.Uniform$1(!1),scale:new c.Uniform$1(new c.Vector4(1,1,1,1))},vertexShader:`
|
|
1110
1110
|
varying vec2 vUv;
|
|
@@ -1285,9 +1285,9 @@ ${l.has(1)?`
|
|
|
1285
1285
|
`:""}
|
|
1286
1286
|
${a.join(`
|
|
1287
1287
|
`)}`:""}
|
|
1288
|
-
}`}function nb(s){return`(${s.r}, ${s.g}, ${s.b})`}function sb(s){return`(${s.x}, ${s.y})`}const Dg=[1023,33777,33778,33779,35842,35843,37496,37808,37809,37810,37811,37812,37813,37814,37815,37816,37817,37818,37819,37820,37821,36492];x("debugusdz");class bt{static global_id=0;id;trigger;action;exclusive=!1;makeExclusive(e){return this.exclusive=e,this}constructor(e,t,i){this.id="Behavior_"+bi(e)+"_"+bt.global_id++,this.trigger=t,this.action=i}writeTo(e,t,i){if(!this.trigger||!this.action)return;i.beginBlock(`def Preliminary_Behavior "${this.id}"`);let n="";if(Array.isArray(this.trigger)){n="[";for(let o=0;o<this.trigger.length;o++){const r=this.trigger[o];n+="<"+r.id+">",o+1<this.trigger.length&&(n+=", ")}n+="]"}else n=`<${this.trigger.id}>`;if(i.appendLine(`rel triggers = ${n}`),i.appendLine(`rel actions = <${this.action.id}>`),i.appendLine(`uniform bool exclusive = ${this.exclusive?1:0}`),i.appendLine(),Array.isArray(this.trigger))for(const o of this.trigger)o.writeTo(t,i),i.appendLine();else this.trigger.writeTo(t,i);i.appendLine(),this.action.writeTo(t,i),i.closeBlock()}}const Xr=new Set;function em(s,e){let t="";if(Array.isArray(s)){Xr.clear();let i="[ ";for(let n=0;n<s.length;n++){let o=s[n];if(!o){console.warn("Invalid target object in behavior",s+". Is the object exported?");continue}if(typeof o=="string"){if(Xr.has(o))continue;i+=o,Xr.add(o)}else if(typeof o=="object"){if(o.isObject3D&&(o=e.findById(o.uuid),!o)){console.warn("Invalid target object in behavior",s+". Is the object exported?");continue}const r=o.getPath?.call(o);if(Xr.has(r))continue;i+=r,Xr.add(r)}n+1<s.length&&(i+=", ")}i+=" ]",t=i,Xr.clear()}else if(typeof s=="object"){const i=s;if(i.isObject3D&&(s=e.findById(i.uuid)),!s)throw console.error("Invalid target object in behavior, the target object is likely missing from USDZ export. Is the object exported?",i),new Error(`Invalid target object in behavior, the target object is likely missing from USDZ export. Please report a bug. uuid: ${i.uuid}.`);t=s.getPath?.call(s)}return t}class io{static global_id=0;id;targetId;tokenId;type;distance;constructor(e,t){e&&(this.targetId=e),t?this.id=t:this.id="Trigger_"+io.global_id++}writeTo(e,t){t.beginBlock(`def Preliminary_Trigger "${this.id}"`),this.targetId&&(typeof this.targetId!="string"&&(this.targetId=em(this.targetId,e)),t.appendLine("rel affectedObjects = "+this.targetId)),this.tokenId&&t.appendLine(`token info:id = "${this.tokenId}"`),this.type&&t.appendLine(`token type = "${this.type}"`),typeof this.distance=="number"&&t.appendLine(`double distance = ${this.distance}`),t.closeBlock()}}function ob(s,e={direct:!0,indirect:!0}){const t=We.createEmpty();t.name="InputTarget_"+t.name,t.displayName=void 0,t.type="RealityKitComponent",t.onSerialize=i=>{i.appendLine("bool allowsDirectInput = "+(e.direct?1:0)),i.appendLine("bool allowsIndirectInput = "+(e.indirect?1:0)),i.appendLine('uniform token info:id = "RealityKit.InputTarget"')},s.add(t)}class kt{static __sceneStartTrigger;static sceneStartTrigger(){if(this.__sceneStartTrigger!==void 0)return this.__sceneStartTrigger;const e=new io(void 0,"SceneStart");return e.tokenId="SceneTransition",e.type="enter",this.__sceneStartTrigger=e,e}static tapTrigger(e,t={direct:!0,indirect:!0}){const i=new io(e);if(Array.isArray(e)&&e.length>1)for(const n of e)n instanceof We&&ob(n,t);else e instanceof We&&ob(e,t);return i.tokenId="TapGesture",i}static isTapTrigger(e){return e?.tokenId==="TapGesture"}static proximityToCameraTrigger(e,t){const i=new io(e);return i.tokenId="ProximityToCamera",i.distance=t,i}}class Xo{static global_id=0;static getId(){return this.global_id++}id;actions;loops=0;performCount=1;type="serial";multiplePerformOperation=void 0;constructor(e,t){this.id=e,this.actions=t}addAction(e){return this.actions.push(e),this}makeParallel(){return this.type="parallel",this}makeSequence(){return this.type="serial",this}makeLooping(){return this.loops=1,this.performCount=0,this}makeRepeat(e){return this.performCount=e,this}writeTo(e,t){t.beginBlock(`def Preliminary_Action "${this.id}"`),t.beginArray("rel actions");for(const i of this.actions){if(!i)continue;const n=i===this.actions[this.actions.length-1];t.appendLine("<"+i.id+">"+(n?"":", "))}t.closeArray(),t.appendLine(),t.appendLine('token info:id = "Group"'),t.appendLine(`bool loops = ${this.loops}`),t.appendLine(`int performCount = ${this.loops>0?0:Math.max(0,this.performCount)}`),t.appendLine(`token type = "${this.type}"`),typeof this.multiplePerformOperation=="string"&&t.appendLine(`token multiplePerformOperation = "${this.multiplePerformOperation}"`),t.appendLine();for(const i of this.actions)i&&(i.writeTo(e,t),t.appendLine());t.closeBlock()}}class Kt{static global_id=0;id;tokenId;affectedObjects;easeType;motionType=void 0;duration;moveDistance;style;type;front;up;start;animationSpeed;reversed;pingPong;xFormTarget;audio;gain;auralMode;multiplePerformOperation;velocity;comment;animationName;clone(){const e=new Kt,t=e.id;return Object.assign(e,this),e.id=t,e}constructor(e,t){e&&(this.affectedObjects=e),t?this.id=t:this.id="Action",this.id+="_"+Kt.global_id++}writeTo(e,t){t.beginBlock(`def Preliminary_Action "${this.id}"`),this.comment&&t.appendLine(`# ${this.comment}`),this.affectedObjects&&(typeof this.affectedObjects!="string"&&(this.affectedObjects=em(this.affectedObjects,e)),t.appendLine("rel affectedObjects = "+this.affectedObjects)),typeof this.duration=="number"&&(typeof this.animationSpeed=="number"&&this.animationSpeed!==1?t.appendLine(`double duration = ${this.duration/this.animationSpeed} `):t.appendLine(`double duration = ${this.duration} `)),this.easeType&&t.appendLine(`token easeType = "${this.easeType}"`),this.tokenId&&t.appendLine(`token info:id = "${this.tokenId}"`),this.tokenId==="ChangeScene"&&t.appendLine("rel scene = </StageRoot/Scenes/Scene>"),this.motionType!==void 0&&t.appendLine(`token motionType = "${this.motionType}"`),typeof this.moveDistance=="number"&&t.appendLine(`double moveDistance = ${this.moveDistance} `),this.style&&t.appendLine(`token style = "${this.style}"`),this.type&&t.appendLine(`token type = "${this.type}"`),this.front&&t.appendLine(`vector3d front = (${this.front.x}, ${this.front.y}, ${this.front.z})`),this.up&&t.appendLine(`vector3d upVector = (${this.up.x}, ${this.up.y}, ${this.up.z})`),typeof this.start=="number"&&t.appendLine(`double start = ${this.start} `),typeof this.animationSpeed=="number"&&t.appendLine(`double animationSpeed = ${this.animationSpeed.toFixed(2)} `),typeof this.reversed=="boolean"&&t.appendLine(`bool reversed = ${this.reversed}`),typeof this.pingPong=="boolean"&&t.appendLine(`bool reverses = ${this.pingPong}`),this.xFormTarget&&(typeof this.xFormTarget!="string"&&(this.xFormTarget=em(this.xFormTarget,e)),t.appendLine(`rel xformTarget = ${this.xFormTarget}`)),typeof this.audio=="string"&&t.appendLine(`asset audio = @${this.audio}@`),typeof this.gain=="number"&&t.appendLine(`double gain = ${this.gain}`),typeof this.auralMode=="string"&&t.appendLine(`token auralMode = "${this.auralMode}"`),typeof this.multiplePerformOperation=="string"&&t.appendLine(`token multiplePerformOperation = "${this.multiplePerformOperation}"`),typeof this.velocity=="object"&&t.appendLine(`vector3d velocity = (${this.velocity.x}, ${this.velocity.y}, ${this.velocity.z})`),t.closeBlock()}}class Ii{x=0;y=0;z=0;constructor(e,t,i){this.x=e,this.y=t,this.z=i}static get up(){return new Ii(0,1,0)}static get right(){return new Ii(1,0,0)}static get forward(){return new Ii(0,0,1)}static get back(){return new Ii(0,0,-1)}static get zero(){return new Ii(0,0,0)}}class he{static sequence(...e){return new Xo("Group_"+Xo.getId(),e).makeSequence()}static parallel(...e){return new Xo("Group_"+Xo.getId(),e).makeParallel()}static fadeAction(e,t,i){const n=new Kt(e);return n.tokenId="Visibility",n.type=i?"show":"hide",n.duration=t,n.style="basic",n.motionType="none",n.moveDistance=0,n.easeType="none",n}static startAnimationAction(e,t,i=!1,n=!1){const o=new Kt(e);o.tokenId="StartAnimation";const r=t.start,a=t.duration,l=t.speed,h=t.clipName;if(o.comment=`Animation: ${h}, start=${r*60}, length=${a*60}, end=${(r+a)*60}`,o.animationName=h,o.start=r,o.duration=a,o.animationSpeed=l,o.reversed=i,o.pingPong=n,o.multiplePerformOperation="allow",i&&(o.start-=a),n){o.pingPong=!1;const d=o.clone();return d.reversed=!i,d.start=o.start,d.reversed&&(d.start-=a),he.sequence(o,d)}return o}static waitAction(e){const t=new Kt;return t.tokenId="Wait",t.duration=e,t.motionType=void 0,t}static lookAtCameraAction(e,t,i,n){const o=new Kt(e);return o.tokenId="LookAtCamera",o.duration=t===void 0?9999999999999:t,o.front=i??Ii.forward,o.up=n??Ii.up,o}static emphasize(e,t,i="bounce",n=1,o="basic"){const r=new Kt(e);return r.tokenId="Emphasize",r.duration=t,r.style=o??"basic",r.motionType=i,r.moveDistance=n,r}static transformAction(e,t,i,n,o="inout"){const r=new Kt(e);return r.tokenId="Transform",r.duration=i,r.duration=Math.max(1e-6,i),r.type=n,r.easeType=i>0?o:"none",Array.isArray(t)&&console.error("Transform target must not be an array",t),r.xFormTarget=t,r}static playAudioAction(e,t,i="play",n=1,o="spatial"){const r=new Kt(e);return r.tokenId="Audio",r.type=i,r.audio=t,r.gain=n,r.auralMode=o,r.multiplePerformOperation="allow",r}static impulseAction(e,t){const i=new Kt(e);return i.tokenId="Impulse",i.velocity=t,i}}class DO{get id(){return this.object.uuid}object;model;constructor(e){this.object=e}apply(e){if(!this.model&&(this.model=e.findById(this.object.uuid),!this.model)){console.error("could not find model with id "+this.object.uuid);return}this.onApply(e)}}class Lg extends DO{constructor(e,t,i,n){super(e),this.matrix=t,this.material=i,this.geometry=n}matrix;material;geometry;onApply(e){const t=this.model;if(!t)return;t.parent?.isDynamic||We.createEmptyParent(t);const i=t.clone();this.matrix&&i.setMatrix(this.matrix),this.material&&(i.material=this.material),this.geometry&&(i.geometry=this.geometry),t.parent?.add(i)}_enableAction;_disableAction;enable(){return this._enableAction?this._enableAction:(this._enableAction=he.fadeAction(this.object,0,!0),this._enableAction)}disable(){return this._disableAction?this._disableAction:(this._disableAction=he.fadeAction(this.object,0,!1),this._disableAction)}}class Rw{actions;sortedActions;constructor(e){this.actions=[...e]}organize(){this.sortedActions={};for(const e of this.actions){const t=e.id;this.sortedActions[t]||(this.sortedActions[t]=[]),this.sortedActions[t].push(e)}}getActions(e){return this.sortedActions||this.organize(),this.sortedActions[e.uuid]}}const En=x("debugusdzanimation"),tm=x("debugusdzanimationserialization");class Zs{_start;get start(){return this._start===void 0&&(this._start=this.ext.getStartTimeByClip(this.clip)),this._start}get duration(){return this.clip?.duration??Ee.restPoseClipDuration}get nearestAnimatedRoot(){return this._nearestAnimatedRoot}get clipName(){return this.clip?.name??"rest"}ext;root;_nearestAnimatedRoot=void 0;clip;speed;constructor(e,t,i){this.ext=e,this.root=t,this.clip=i,this._nearestAnimatedRoot=this.getNearestAnimatedRoot()}static isDescendantOf(e,t){let i=t;if(!i||!e)return!1;for(;i;){if(!i)return!1;if(i===e)return!0;i=i.parent}return!1}getNearestAnimatedRoot(){let e;try{for(const t of this.clip?.tracks??[]){const i=c.PropertyBinding.parseTrackName(t.name);let n=c.PropertyBinding.findNode(this.root,i.nodeName);if(n)if(!e)e=n;else{if(n===e||Zs.isDescendantOf(e,n))continue;if(!Zs.isDescendantOf(n,e)){for(;!Zs.isDescendantOf(n,e)&&n.parent;)n=n.parent;Zs.isDescendantOf(n,e)||console.error("USDZExporter: Animation clip targets multiple roots that are not parent/child. Please report a bug",this.root,this.clip,e,n)}e=n}}}catch(t){console.error("USDZExporter: Exception when trying to find nearest animated root. Please report a bug",t),e=void 0}return e}}class Ee{clip;pos;rot;scale;root;target;duration=0;useRootMotion=!1;static frameRate=60;static animationDurationPadding=6/60;static restPoseClipDuration=6/60;constructor(e,t,i){if(this.root=e,this.target=t,this.clip=i,i?this.duration=i.duration:this.duration=Ee.restPoseClipDuration,i&&i.tracks){const o=Math.max(...i.tracks.map(r=>r.times[r.times.length-1]));o!==this.duration&&(console.warn("USDZExporter: Animation clip duration does not match the maximum time value in the tracks.",i,o,this.duration),this.duration=o)}const n=S.getComponent(e,at);n&&(this.useRootMotion=n.applyRootMotion)}addTrack(e){if(!this.clip){console.error("This is a rest clip but you're trying to add tracks to it – this is likely a bug");return}e.name.endsWith("position")?this.pos=e:e.name.endsWith("quaternion")?this.rot=e:e.name.endsWith("scale")?this.scale=e:(e.name.endsWith("activeSelf")?console.warn("[USDZ] Animation of enabled/disabled state is not supported for USDZ export and will NOT be exported: "+e.name+" on "+(this.root?.name??this.target.name)+". Animate scale 0/1 instead."):console.warn("[USDZ] Animation track type not supported for USDZ export and will NOT be exported: "+e.name+" on "+(this.root?.name??this.target.name)+". Only .position, .rotation, .scale are supported."),T()&&ue("[USDZ] Some animations can't be exported. See console for details."))}getFrames(){return this.clip?Math.max(this.pos?.times?.length??0,this.rot?.times?.length??0,this.scale?.times?.length??0):2}getDuration(){return this.duration}getSortedTimesArray(e=!0,t=!0,i=!0){if(!this.clip)return[0,this.duration];const n=this.pos?.times,o=this.rot?.times,r=this.scale?.times,a=[];if(e&&n)for(const l of n)a.push(l);if(t&&o)for(const l of o)a.push(l);if(i&&r)for(const l of r)a.push(l);return a.includes(0)||a.push(0),a.sort((l,h)=>l-h),[...new Set(a)]}*getValues(e,t=!0,i=!0,n=!0){const o=new c.Vector3,r=new c.Quaternion,a=new c.Vector3(1,1,1),l=this.target,h=t?this.pos?.createInterpolant():void 0,d=i?this.rot?.createInterpolant():void 0,u=n?this.scale?.createInterpolant():void 0;h||o.set(l.position.x,l.position.y,l.position.z),d||r.set(l.quaternion.x,l.quaternion.y,l.quaternion.z,l.quaternion.w),u||a.set(l.scale.x,l.scale.y,l.scale.z),h&&h.valueSize!==3&&(h.valueSize=3),d&&d.valueSize!==4&&(d.valueSize=4),u&&u.valueSize!==3&&(u.valueSize=3);const p=0;for(let m=0-p;m<e.length+p;m++){let g=0,_=0;if(m<0?(g=e[0],_=g-Ee.animationDurationPadding/2+1/60):m>=e.length?(g=e[e.length-1],_=g+Ee.animationDurationPadding/2-1/60):(g=e[m],_=g),h){const y=h.evaluate(g);o.set(y[0],y[1],y[2])}if(d){const y=d.evaluate(g);r.set(y[0],y[1],y[2],y[3])}if(u){const y=u.evaluate(g);a.set(y[0],y[1],y[2])}if(this.useRootMotion&&l===this.root){const y=new c.Matrix4;y.compose(o,r,a),y.multiply(l.matrix),y.decompose(o,r,a)}yield{time:_,translation:o,rotation:r,scale:a,index:m}}}}class Ou{get extensionName(){return"animation"}get animationData(){return this.dict}get registeredClips(){return this.clipToStartTime.keys()}get animatedRoots(){return this.rootTargetMap.keys()}get holdClipMap(){return this.clipToHoldClip}dict=new Map;rootTargetMap=new Map;rootAndClipToRegisteredAnimationMap=new Map;rootToRegisteredClip=new Map;lastClipEndTime=0;clipToStartTime=new Map;clipToHoldClip=new Map;serializers=[];injectRestPoses=!1;injectImplicitBehaviours=!1;constructor(e){this.injectRestPoses=e,this.injectImplicitBehaviours=e}getStartTimeCode(){return!this.injectRestPoses||this.rootAndClipToRegisteredAnimationMap.size===0?0:(Ee.restPoseClipDuration+Ee.animationDurationPadding)*60}getEndTimeCode(){let e=0;for(const[t,i]of this.rootAndClipToRegisteredAnimationMap){const n=i.start+i.duration;n>e&&(e=n)}return e*60}getClipCount(e){return this.rootToRegisteredClip.get(e)?.length??0??0}getStartTimeByClip(e){return e?this.clipToStartTime.has(e)?this.clipToStartTime.get(e):(console.error("USDZExporter: Missing start time for clip – please report a bug.",e),0):0}registerAnimation(e,t){if(!e)return null;this.rootTargetMap.has(e)||this.rootTargetMap.set(e,[]);const i=e.uuid+(t?.uuid??"-rest");if(this.rootAndClipToRegisteredAnimationMap.has(i))return this.rootAndClipToRegisteredAnimationMap.get(i);En&&console.log("registerAnimation",e,t);const n=this.injectRestPoses?1:0,o=(this.rootToRegisteredClip.get(e)?.length??0)+n,r=this.rootTargetMap.get(e),a=new Set(r);if(t&&t.tracks)for(const h of t.tracks){const d=c.PropertyBinding.parseTrackName(h.name),u=c.PropertyBinding.findNode(e,d.nodeName);if(!u){console.warn("no object found for track",h.name,"using "+e.name+" instead");continue}this.dict.has(u)||this.dict.set(u,[]);const p=this.dict.get(u);if(!p){console.warn("no transform data found for target ",u,"at slot "+o+", this is likely a bug");continue}a.delete(u),this.injectRestPoses&&!p[0]&&(console.log("Injecting rest pose",u,t,"at slot",o),p[0]=new Ee(null,u,null));let m=p[o];m||(m=new Ee(e,u,t),p[o]=m),m.addTrack(h),r?.includes(u)||r?.push(u)}En&&console.log("Unregistered nodes for this clip",a,"clip",t,"at slot",o,"for root",e,"targets",r);for(const h of a){const d=this.dict.get(h);if(!d)continue;if(this.injectRestPoses&&!d[0]){console.warn("Adding rest pose for ",h,t,"at slot",o,"This is likely a bug, should have been added earlier.");const p=new Ee(null,h,null);d[0]=p}let u=d[o];u||(En&&console.log("Adding padding clip for ",h,t,"at slot",o),u=new Ee(e,h,t),d[o]=u)}const l=new Zs(this,e,t);if(this.rootAndClipToRegisteredAnimationMap.set(i,l),En&&console.log({root:e,clip:t,info:l}),t){const h=this.rootToRegisteredClip.get(e);if(h?h.push(t):this.rootToRegisteredClip.set(e,[t]),!this.clipToStartTime.get(t)){this.lastClipEndTime==null&&(this.lastClipEndTime=Ee.restPoseClipDuration);let u=this.lastClipEndTime+Ee.animationDurationPadding,p=u+t.duration;const m=Math.round(u*60)/60,g=Math.round(p*60)/60;Math.abs(m-u)<.01&&(u=m),Math.abs(g-p)<.01&&(p=g),u=Math.ceil(u),p=u+t.duration,this.clipToStartTime.set(t,u),this.lastClipEndTime=p}}return l}onAfterHierarchy(e){En&&console.log("Animation clips per animation target node",this.dict)}onAfterBuildDocument(e){En&&console.log("Animation data",{dict:this.dict,rootTargetMap:this.rootTargetMap,rootToRegisteredClip:this.rootToRegisteredClip});for(const t of this.rootTargetMap.keys()){const i=this.rootTargetMap.get(t);if(!i)continue;let n;const o=[];for(const r of i){const a=this.dict.get(r);if(!a){console.error("No data found for target on USDZ export – please report a bug!",r);continue}n===void 0&&(n=a?.length),n!==a?.length&&console.error("Different array lengths for targets – please report a bug!",a);for(let l=0;l<a.length;l++){let h=a[l];if(!h){const u=l-(this.injectRestPoses?1:0);a[l]=new Ee(null,r,this.rootToRegisteredClip.get(t)[u]),h=a[l]}const d=h.getDuration();if(o[l]===void 0)o[l]=d;else if(o[l]!==d){console.error("Error during UDSZ export: Encountered different animation durations for animated targets. Please report a bug!",{datas:a,target:r}),o[l]=d;continue}}}}for(const t of this.serializers){const i=t.model?.parent,n=i?.isDynamic===!0;tm&&console.log(n,t.model?.parent),n&&t.registerCallback(i)}}onExportObject(e,t,i){S.foreachComponent(e,o=>{const r=o;typeof r.createAnimation=="function"&&r.createAnimation(this,t,i)},!1);const n=new LO(e,this);this.serializers.push(n),n.registerCallback(t)}}class LO{model=void 0;object;animationData;ext;callback;constructor(e,t){this.object=e,this.animationData=t.animationData,this.ext=t}registerCallback(e){this.model&&this.callback&&this.model.removeEventListener("serialize",this.callback),this.callback||(this.callback=this.onSerialize.bind(this)),tm&&console.log("REPARENT",e),this.model=e,this.callback&&this.model.addEventListener("serialize",this.callback)}skinnedMeshExport(e,t,i){const n=this.model,o=this.animationData;if(n&&n.skinnedMesh){let r=function(k){const z=[];for(const[V,J]of k){let Z=`${V} : [`;const ce=[];for(const X of J)ce.push(`(${ie(X.x)}, ${ie(X.y)}, ${ie(X.z)})`);Z=Z.concat(ce.join(", ")),Z=Z.concat("],"),z.push(Z)}return z},a=function(k){const z=[];for(const[V,J]of k){let Z=`${V} : [`;const ce=[];for(const X of J)ce.push(`(${ie(X.w)}, ${ie(X.x)}, ${ie(X.y)}, ${ie(X.z)})`);Z=Z.concat(ce.join(", ")),Z=Z.concat("],"),z.push(Z)}return z},l=function(k){let z,V=!0;const J=new Map;for(const[ce,X]of k){z===void 0&&(z=X.length),z!==X.length&&(V=!1);let ge=0;for(const qt of X)ge++,qt||(J.has(ce)||J.set(ce,[]),J.get(ce).push(ge))}En&&console.log("Bone count: ",k.size,"TransformData entries per bone: ",z,"Undefined bone entries: ",J),console.assert(V,"All bones should have the same number of TransformData entries",k),console.assert(J.size===0,"All TransformData entries should be set",J);const Z=[];for(const[ce,X]of k)for(let ge=0;ge<X.length;ge++){const qt=X[ge],Mh=i.getStartTimeByClip(qt.clip);Z.length<=ge&&Z.push({pos:[],rot:[],scale:[],timeOffset:Mh});const As=Z[ge];As.pos.push(...qt.getSortedTimesArray(!0,!1,!1)),As.rot.push(...qt.getSortedTimesArray(!1,!0,!1)),As.scale.push(...qt.getSortedTimesArray(!1,!1,!0))}for(const ce of Z)ce.pos.sort((X,ge)=>X-ge),ce.rot.sort((X,ge)=>X-ge),ce.scale.sort((X,ge)=>X-ge),ce.pos=[...new Set(ce.pos)],ce.rot=[...new Set(ce.rot)],ce.scale=[...new Set(ce.scale)];return Z},h=function(k,z,V){const J=new Map,Z=new Map,ce=new Map,X=z.length;for(const ge of V){const qt=k.get(ge);let Mh;qt?console.assert(qt.length===X,"We should have the same number of TransformData entries for each bone",qt,z):Mh=new Ee(null,ge,null);for(let As=0;As<X;As++){const hf=qt?qt[As]:Mh,Fr=z[As];for(const{time:ul,translation:fl}of hf.getValues(Fr.pos,!0,!1,!1)){const Yi=(ul+Fr.timeOffset)*60;J.has(Yi)||J.set(Yi,new Array),J.get(Yi).push(fl.clone())}for(const{time:ul,rotation:fl}of hf.getValues(Fr.rot,!1,!0,!1)){const Yi=(ul+Fr.timeOffset)*60;Z.has(Yi)||Z.set(Yi,new Array),Z.get(Yi).push(fl.clone())}for(const{time:ul,scale:fl}of hf.getValues(Fr.scale,!1,!1,!0)){const Yi=(ul+Fr.timeOffset)*60;ce.has(Yi)||ce.set(Yi,new Array),ce.get(Yi).push(fl.clone())}}}return{position:J.size==0?void 0:J,quaternion:Z.size==0?void 0:Z,scale:ce.size==0?void 0:ce}},d=function(k){const z=[];for(const V of k)z.push(`(${ie(V.x)}, ${ie(V.y)}, ${ie(V.z)})`);return z.join(", ")},u=function(k){const z=[];for(const V of k)z.push(`(${ie(V.w)}, ${ie(V.x)}, ${ie(V.y)}, ${ie(V.z)})`);return z.join(", ")},p=function(k){const z=new Map;if(En){const V=new Array;for(const[J,Z]of o)V.push(J.uuid+": "+Z.length+" "+Z.map(ce=>ce.clip?.uuid.substring(0,6)).join(" "));console.log(`getPerBoneTransformData
|
|
1288
|
+
}`}function nb(s){return`(${s.r}, ${s.g}, ${s.b})`}function sb(s){return`(${s.x}, ${s.y})`}const Dg=[1023,33777,33778,33779,35842,35843,37496,37808,37809,37810,37811,37812,37813,37814,37815,37816,37817,37818,37819,37820,37821,36492];x("debugusdz");class bt{static global_id=0;id;trigger;action;exclusive=!1;makeExclusive(e){return this.exclusive=e,this}constructor(e,t,i){this.id="Behavior_"+bi(e)+"_"+bt.global_id++,this.trigger=t,this.action=i}writeTo(e,t,i){if(!this.trigger||!this.action)return;i.beginBlock(`def Preliminary_Behavior "${this.id}"`);let n="";if(Array.isArray(this.trigger)){n="[";for(let o=0;o<this.trigger.length;o++){const r=this.trigger[o];n+="<"+r.id+">",o+1<this.trigger.length&&(n+=", ")}n+="]"}else n=`<${this.trigger.id}>`;if(i.appendLine(`rel triggers = ${n}`),i.appendLine(`rel actions = <${this.action.id}>`),i.appendLine(`uniform bool exclusive = ${this.exclusive?1:0}`),i.appendLine(),Array.isArray(this.trigger))for(const o of this.trigger)o.writeTo(t,i),i.appendLine();else this.trigger.writeTo(t,i);i.appendLine(),this.action.writeTo(t,i),i.closeBlock()}}const Xr=new Set;function em(s,e){let t="";if(Array.isArray(s)){Xr.clear();let i="[ ";for(let n=0;n<s.length;n++){let o=s[n];if(!o){console.warn("Invalid target object in behavior",s+". Is the object exported?");continue}if(typeof o=="string"){if(Xr.has(o))continue;i+=o,Xr.add(o)}else if(typeof o=="object"){if(o.isObject3D&&(o=e.findById(o.uuid),!o)){console.warn("Invalid target object in behavior",s+". Is the object exported?");continue}const r=o.getPath?.call(o);if(Xr.has(r))continue;i+=r,Xr.add(r)}n+1<s.length&&(i+=", ")}i+=" ]",t=i,Xr.clear()}else if(typeof s=="object"){const i=s;if(i.isObject3D&&(s=e.findById(i.uuid)),!s)throw console.error("Invalid target object in behavior, the target object is likely missing from USDZ export. Is the object exported?",i),new Error(`Invalid target object in behavior, the target object is likely missing from USDZ export. Please report a bug. uuid: ${i.uuid}.`);t=s.getPath?.call(s)}return t}class io{static global_id=0;id;targetId;tokenId;type;distance;constructor(e,t){e&&(this.targetId=e),t?this.id=t:this.id="Trigger_"+io.global_id++}writeTo(e,t){t.beginBlock(`def Preliminary_Trigger "${this.id}"`),this.targetId&&(typeof this.targetId!="string"&&(this.targetId=em(this.targetId,e)),t.appendLine("rel affectedObjects = "+this.targetId)),this.tokenId&&t.appendLine(`token info:id = "${this.tokenId}"`),this.type&&t.appendLine(`token type = "${this.type}"`),typeof this.distance=="number"&&t.appendLine(`double distance = ${this.distance}`),t.closeBlock()}}function ob(s,e={direct:!0,indirect:!0}){const t=He.createEmpty();t.name="InputTarget_"+t.name,t.displayName=void 0,t.type="RealityKitComponent",t.onSerialize=i=>{i.appendLine("bool allowsDirectInput = "+(e.direct?1:0)),i.appendLine("bool allowsIndirectInput = "+(e.indirect?1:0)),i.appendLine('uniform token info:id = "RealityKit.InputTarget"')},s.add(t)}class kt{static __sceneStartTrigger;static sceneStartTrigger(){if(this.__sceneStartTrigger!==void 0)return this.__sceneStartTrigger;const e=new io(void 0,"SceneStart");return e.tokenId="SceneTransition",e.type="enter",this.__sceneStartTrigger=e,e}static tapTrigger(e,t={direct:!0,indirect:!0}){const i=new io(e);if(Array.isArray(e)&&e.length>1)for(const n of e)n instanceof He&&ob(n,t);else e instanceof He&&ob(e,t);return i.tokenId="TapGesture",i}static isTapTrigger(e){return e?.tokenId==="TapGesture"}static proximityToCameraTrigger(e,t){const i=new io(e);return i.tokenId="ProximityToCamera",i.distance=t,i}}class Xo{static global_id=0;static getId(){return this.global_id++}id;actions;loops=0;performCount=1;type="serial";multiplePerformOperation=void 0;constructor(e,t){this.id=e,this.actions=t}addAction(e){return this.actions.push(e),this}makeParallel(){return this.type="parallel",this}makeSequence(){return this.type="serial",this}makeLooping(){return this.loops=1,this.performCount=0,this}makeRepeat(e){return this.performCount=e,this}writeTo(e,t){t.beginBlock(`def Preliminary_Action "${this.id}"`),t.beginArray("rel actions");for(const i of this.actions){if(!i)continue;const n=i===this.actions[this.actions.length-1];t.appendLine("<"+i.id+">"+(n?"":", "))}t.closeArray(),t.appendLine(),t.appendLine('token info:id = "Group"'),t.appendLine(`bool loops = ${this.loops}`),t.appendLine(`int performCount = ${this.loops>0?0:Math.max(0,this.performCount)}`),t.appendLine(`token type = "${this.type}"`),typeof this.multiplePerformOperation=="string"&&t.appendLine(`token multiplePerformOperation = "${this.multiplePerformOperation}"`),t.appendLine();for(const i of this.actions)i&&(i.writeTo(e,t),t.appendLine());t.closeBlock()}}class Kt{static global_id=0;id;tokenId;affectedObjects;easeType;motionType=void 0;duration;moveDistance;style;type;front;up;start;animationSpeed;reversed;pingPong;xFormTarget;audio;gain;auralMode;multiplePerformOperation;velocity;comment;animationName;clone(){const e=new Kt,t=e.id;return Object.assign(e,this),e.id=t,e}constructor(e,t){e&&(this.affectedObjects=e),t?this.id=t:this.id="Action",this.id+="_"+Kt.global_id++}writeTo(e,t){t.beginBlock(`def Preliminary_Action "${this.id}"`),this.comment&&t.appendLine(`# ${this.comment}`),this.affectedObjects&&(typeof this.affectedObjects!="string"&&(this.affectedObjects=em(this.affectedObjects,e)),t.appendLine("rel affectedObjects = "+this.affectedObjects)),typeof this.duration=="number"&&(typeof this.animationSpeed=="number"&&this.animationSpeed!==1?t.appendLine(`double duration = ${this.duration/this.animationSpeed} `):t.appendLine(`double duration = ${this.duration} `)),this.easeType&&t.appendLine(`token easeType = "${this.easeType}"`),this.tokenId&&t.appendLine(`token info:id = "${this.tokenId}"`),this.tokenId==="ChangeScene"&&t.appendLine("rel scene = </StageRoot/Scenes/Scene>"),this.motionType!==void 0&&t.appendLine(`token motionType = "${this.motionType}"`),typeof this.moveDistance=="number"&&t.appendLine(`double moveDistance = ${this.moveDistance} `),this.style&&t.appendLine(`token style = "${this.style}"`),this.type&&t.appendLine(`token type = "${this.type}"`),this.front&&t.appendLine(`vector3d front = (${this.front.x}, ${this.front.y}, ${this.front.z})`),this.up&&t.appendLine(`vector3d upVector = (${this.up.x}, ${this.up.y}, ${this.up.z})`),typeof this.start=="number"&&t.appendLine(`double start = ${this.start} `),typeof this.animationSpeed=="number"&&t.appendLine(`double animationSpeed = ${this.animationSpeed.toFixed(2)} `),typeof this.reversed=="boolean"&&t.appendLine(`bool reversed = ${this.reversed}`),typeof this.pingPong=="boolean"&&t.appendLine(`bool reverses = ${this.pingPong}`),this.xFormTarget&&(typeof this.xFormTarget!="string"&&(this.xFormTarget=em(this.xFormTarget,e)),t.appendLine(`rel xformTarget = ${this.xFormTarget}`)),typeof this.audio=="string"&&t.appendLine(`asset audio = @${this.audio}@`),typeof this.gain=="number"&&t.appendLine(`double gain = ${this.gain}`),typeof this.auralMode=="string"&&t.appendLine(`token auralMode = "${this.auralMode}"`),typeof this.multiplePerformOperation=="string"&&t.appendLine(`token multiplePerformOperation = "${this.multiplePerformOperation}"`),typeof this.velocity=="object"&&t.appendLine(`vector3d velocity = (${this.velocity.x}, ${this.velocity.y}, ${this.velocity.z})`),t.closeBlock()}}class Ii{x=0;y=0;z=0;constructor(e,t,i){this.x=e,this.y=t,this.z=i}static get up(){return new Ii(0,1,0)}static get right(){return new Ii(1,0,0)}static get forward(){return new Ii(0,0,1)}static get back(){return new Ii(0,0,-1)}static get zero(){return new Ii(0,0,0)}}class he{static sequence(...e){return new Xo("Group_"+Xo.getId(),e).makeSequence()}static parallel(...e){return new Xo("Group_"+Xo.getId(),e).makeParallel()}static fadeAction(e,t,i){const n=new Kt(e);return n.tokenId="Visibility",n.type=i?"show":"hide",n.duration=t,n.style="basic",n.motionType="none",n.moveDistance=0,n.easeType="none",n}static startAnimationAction(e,t,i=!1,n=!1){const o=new Kt(e);o.tokenId="StartAnimation";const r=t.start,a=t.duration,l=t.speed,h=t.clipName;if(o.comment=`Animation: ${h}, start=${r*60}, length=${a*60}, end=${(r+a)*60}`,o.animationName=h,o.start=r,o.duration=a,o.animationSpeed=l,o.reversed=i,o.pingPong=n,o.multiplePerformOperation="allow",i&&(o.start-=a),n){o.pingPong=!1;const d=o.clone();return d.reversed=!i,d.start=o.start,d.reversed&&(d.start-=a),he.sequence(o,d)}return o}static waitAction(e){const t=new Kt;return t.tokenId="Wait",t.duration=e,t.motionType=void 0,t}static lookAtCameraAction(e,t,i,n){const o=new Kt(e);return o.tokenId="LookAtCamera",o.duration=t===void 0?9999999999999:t,o.front=i??Ii.forward,o.up=n??Ii.up,o}static emphasize(e,t,i="bounce",n=1,o="basic"){const r=new Kt(e);return r.tokenId="Emphasize",r.duration=t,r.style=o??"basic",r.motionType=i,r.moveDistance=n,r}static transformAction(e,t,i,n,o="inout"){const r=new Kt(e);return r.tokenId="Transform",r.duration=i,r.duration=Math.max(1e-6,i),r.type=n,r.easeType=i>0?o:"none",Array.isArray(t)&&console.error("Transform target must not be an array",t),r.xFormTarget=t,r}static playAudioAction(e,t,i="play",n=1,o="spatial"){const r=new Kt(e);return r.tokenId="Audio",r.type=i,r.audio=t,r.gain=n,r.auralMode=o,r.multiplePerformOperation="allow",r}static impulseAction(e,t){const i=new Kt(e);return i.tokenId="Impulse",i.velocity=t,i}}class DO{get id(){return this.object.uuid}object;model;constructor(e){this.object=e}apply(e){if(!this.model&&(this.model=e.findById(this.object.uuid),!this.model)){console.error("could not find model with id "+this.object.uuid);return}this.onApply(e)}}class Lg extends DO{constructor(e,t,i,n){super(e),this.matrix=t,this.material=i,this.geometry=n}matrix;material;geometry;onApply(e){const t=this.model;if(!t)return;t.parent?.isDynamic||He.createEmptyParent(t);const i=t.clone();this.matrix&&i.setMatrix(this.matrix),this.material&&(i.material=this.material),this.geometry&&(i.geometry=this.geometry),t.parent?.add(i)}_enableAction;_disableAction;enable(){return this._enableAction?this._enableAction:(this._enableAction=he.fadeAction(this.object,0,!0),this._enableAction)}disable(){return this._disableAction?this._disableAction:(this._disableAction=he.fadeAction(this.object,0,!1),this._disableAction)}}class Rw{actions;sortedActions;constructor(e){this.actions=[...e]}organize(){this.sortedActions={};for(const e of this.actions){const t=e.id;this.sortedActions[t]||(this.sortedActions[t]=[]),this.sortedActions[t].push(e)}}getActions(e){return this.sortedActions||this.organize(),this.sortedActions[e.uuid]}}const En=x("debugusdzanimation"),tm=x("debugusdzanimationserialization");class Zs{_start;get start(){return this._start===void 0&&(this._start=this.ext.getStartTimeByClip(this.clip)),this._start}get duration(){return this.clip?.duration??Ee.restPoseClipDuration}get nearestAnimatedRoot(){return this._nearestAnimatedRoot}get clipName(){return this.clip?.name??"rest"}ext;root;_nearestAnimatedRoot=void 0;clip;speed;constructor(e,t,i){this.ext=e,this.root=t,this.clip=i,this._nearestAnimatedRoot=this.getNearestAnimatedRoot()}static isDescendantOf(e,t){let i=t;if(!i||!e)return!1;for(;i;){if(!i)return!1;if(i===e)return!0;i=i.parent}return!1}getNearestAnimatedRoot(){let e;try{for(const t of this.clip?.tracks??[]){const i=c.PropertyBinding.parseTrackName(t.name);let n=c.PropertyBinding.findNode(this.root,i.nodeName);if(n)if(!e)e=n;else{if(n===e||Zs.isDescendantOf(e,n))continue;if(!Zs.isDescendantOf(n,e)){for(;!Zs.isDescendantOf(n,e)&&n.parent;)n=n.parent;Zs.isDescendantOf(n,e)||console.error("USDZExporter: Animation clip targets multiple roots that are not parent/child. Please report a bug",this.root,this.clip,e,n)}e=n}}}catch(t){console.error("USDZExporter: Exception when trying to find nearest animated root. Please report a bug",t),e=void 0}return e}}class Ee{clip;pos;rot;scale;root;target;duration=0;useRootMotion=!1;static frameRate=60;static animationDurationPadding=6/60;static restPoseClipDuration=6/60;constructor(e,t,i){if(this.root=e,this.target=t,this.clip=i,i?this.duration=i.duration:this.duration=Ee.restPoseClipDuration,i&&i.tracks){const o=Math.max(...i.tracks.map(r=>r.times[r.times.length-1]));o!==this.duration&&(console.warn("USDZExporter: Animation clip duration does not match the maximum time value in the tracks.",i,o,this.duration),this.duration=o)}const n=S.getComponent(e,at);n&&(this.useRootMotion=n.applyRootMotion)}addTrack(e){if(!this.clip){console.error("This is a rest clip but you're trying to add tracks to it – this is likely a bug");return}e.name.endsWith("position")?this.pos=e:e.name.endsWith("quaternion")?this.rot=e:e.name.endsWith("scale")?this.scale=e:(e.name.endsWith("activeSelf")?console.warn("[USDZ] Animation of enabled/disabled state is not supported for USDZ export and will NOT be exported: "+e.name+" on "+(this.root?.name??this.target.name)+". Animate scale 0/1 instead."):console.warn("[USDZ] Animation track type not supported for USDZ export and will NOT be exported: "+e.name+" on "+(this.root?.name??this.target.name)+". Only .position, .rotation, .scale are supported."),T()&&ue("[USDZ] Some animations can't be exported. See console for details."))}getFrames(){return this.clip?Math.max(this.pos?.times?.length??0,this.rot?.times?.length??0,this.scale?.times?.length??0):2}getDuration(){return this.duration}getSortedTimesArray(e=!0,t=!0,i=!0){if(!this.clip)return[0,this.duration];const n=this.pos?.times,o=this.rot?.times,r=this.scale?.times,a=[];if(e&&n)for(const l of n)a.push(l);if(t&&o)for(const l of o)a.push(l);if(i&&r)for(const l of r)a.push(l);return a.includes(0)||a.push(0),a.sort((l,h)=>l-h),[...new Set(a)]}*getValues(e,t=!0,i=!0,n=!0){const o=new c.Vector3,r=new c.Quaternion,a=new c.Vector3(1,1,1),l=this.target,h=t?this.pos?.createInterpolant():void 0,d=i?this.rot?.createInterpolant():void 0,u=n?this.scale?.createInterpolant():void 0;h||o.set(l.position.x,l.position.y,l.position.z),d||r.set(l.quaternion.x,l.quaternion.y,l.quaternion.z,l.quaternion.w),u||a.set(l.scale.x,l.scale.y,l.scale.z),h&&h.valueSize!==3&&(h.valueSize=3),d&&d.valueSize!==4&&(d.valueSize=4),u&&u.valueSize!==3&&(u.valueSize=3);const p=0;for(let m=0-p;m<e.length+p;m++){let g=0,_=0;if(m<0?(g=e[0],_=g-Ee.animationDurationPadding/2+1/60):m>=e.length?(g=e[e.length-1],_=g+Ee.animationDurationPadding/2-1/60):(g=e[m],_=g),h){const y=h.evaluate(g);o.set(y[0],y[1],y[2])}if(d){const y=d.evaluate(g);r.set(y[0],y[1],y[2],y[3])}if(u){const y=u.evaluate(g);a.set(y[0],y[1],y[2])}if(this.useRootMotion&&l===this.root){const y=new c.Matrix4;y.compose(o,r,a),y.multiply(l.matrix),y.decompose(o,r,a)}yield{time:_,translation:o,rotation:r,scale:a,index:m}}}}class Ou{get extensionName(){return"animation"}get animationData(){return this.dict}get registeredClips(){return this.clipToStartTime.keys()}get animatedRoots(){return this.rootTargetMap.keys()}get holdClipMap(){return this.clipToHoldClip}dict=new Map;rootTargetMap=new Map;rootAndClipToRegisteredAnimationMap=new Map;rootToRegisteredClip=new Map;lastClipEndTime=0;clipToStartTime=new Map;clipToHoldClip=new Map;serializers=[];injectRestPoses=!1;injectImplicitBehaviours=!1;constructor(e){this.injectRestPoses=e,this.injectImplicitBehaviours=e}getStartTimeCode(){return!this.injectRestPoses||this.rootAndClipToRegisteredAnimationMap.size===0?0:(Ee.restPoseClipDuration+Ee.animationDurationPadding)*60}getEndTimeCode(){let e=0;for(const[t,i]of this.rootAndClipToRegisteredAnimationMap){const n=i.start+i.duration;n>e&&(e=n)}return e*60}getClipCount(e){return this.rootToRegisteredClip.get(e)?.length??0??0}getStartTimeByClip(e){return e?this.clipToStartTime.has(e)?this.clipToStartTime.get(e):(console.error("USDZExporter: Missing start time for clip – please report a bug.",e),0):0}registerAnimation(e,t){if(!e)return null;this.rootTargetMap.has(e)||this.rootTargetMap.set(e,[]);const i=e.uuid+(t?.uuid??"-rest");if(this.rootAndClipToRegisteredAnimationMap.has(i))return this.rootAndClipToRegisteredAnimationMap.get(i);En&&console.log("registerAnimation",e,t);const n=this.injectRestPoses?1:0,o=(this.rootToRegisteredClip.get(e)?.length??0)+n,r=this.rootTargetMap.get(e),a=new Set(r);if(t&&t.tracks)for(const h of t.tracks){const d=c.PropertyBinding.parseTrackName(h.name),u=c.PropertyBinding.findNode(e,d.nodeName);if(!u){console.warn("no object found for track",h.name,"using "+e.name+" instead");continue}this.dict.has(u)||this.dict.set(u,[]);const p=this.dict.get(u);if(!p){console.warn("no transform data found for target ",u,"at slot "+o+", this is likely a bug");continue}a.delete(u),this.injectRestPoses&&!p[0]&&(console.log("Injecting rest pose",u,t,"at slot",o),p[0]=new Ee(null,u,null));let m=p[o];m||(m=new Ee(e,u,t),p[o]=m),m.addTrack(h),r?.includes(u)||r?.push(u)}En&&console.log("Unregistered nodes for this clip",a,"clip",t,"at slot",o,"for root",e,"targets",r);for(const h of a){const d=this.dict.get(h);if(!d)continue;if(this.injectRestPoses&&!d[0]){console.warn("Adding rest pose for ",h,t,"at slot",o,"This is likely a bug, should have been added earlier.");const p=new Ee(null,h,null);d[0]=p}let u=d[o];u||(En&&console.log("Adding padding clip for ",h,t,"at slot",o),u=new Ee(e,h,t),d[o]=u)}const l=new Zs(this,e,t);if(this.rootAndClipToRegisteredAnimationMap.set(i,l),En&&console.log({root:e,clip:t,info:l}),t){const h=this.rootToRegisteredClip.get(e);if(h?h.push(t):this.rootToRegisteredClip.set(e,[t]),!this.clipToStartTime.get(t)){this.lastClipEndTime==null&&(this.lastClipEndTime=Ee.restPoseClipDuration);let u=this.lastClipEndTime+Ee.animationDurationPadding,p=u+t.duration;const m=Math.round(u*60)/60,g=Math.round(p*60)/60;Math.abs(m-u)<.01&&(u=m),Math.abs(g-p)<.01&&(p=g),u=Math.ceil(u),p=u+t.duration,this.clipToStartTime.set(t,u),this.lastClipEndTime=p}}return l}onAfterHierarchy(e){En&&console.log("Animation clips per animation target node",this.dict)}onAfterBuildDocument(e){En&&console.log("Animation data",{dict:this.dict,rootTargetMap:this.rootTargetMap,rootToRegisteredClip:this.rootToRegisteredClip});for(const t of this.rootTargetMap.keys()){const i=this.rootTargetMap.get(t);if(!i)continue;let n;const o=[];for(const r of i){const a=this.dict.get(r);if(!a){console.error("No data found for target on USDZ export – please report a bug!",r);continue}n===void 0&&(n=a?.length),n!==a?.length&&console.error("Different array lengths for targets – please report a bug!",a);for(let l=0;l<a.length;l++){let h=a[l];if(!h){const u=l-(this.injectRestPoses?1:0);a[l]=new Ee(null,r,this.rootToRegisteredClip.get(t)[u]),h=a[l]}const d=h.getDuration();if(o[l]===void 0)o[l]=d;else if(o[l]!==d){console.error("Error during UDSZ export: Encountered different animation durations for animated targets. Please report a bug!",{datas:a,target:r}),o[l]=d;continue}}}}for(const t of this.serializers){const i=t.model?.parent,n=i?.isDynamic===!0;tm&&console.log(n,t.model?.parent),n&&t.registerCallback(i)}}onExportObject(e,t,i){S.foreachComponent(e,o=>{const r=o;typeof r.createAnimation=="function"&&r.createAnimation(this,t,i)},!1);const n=new LO(e,this);this.serializers.push(n),n.registerCallback(t)}}class LO{model=void 0;object;animationData;ext;callback;constructor(e,t){this.object=e,this.animationData=t.animationData,this.ext=t}registerCallback(e){this.model&&this.callback&&this.model.removeEventListener("serialize",this.callback),this.callback||(this.callback=this.onSerialize.bind(this)),tm&&console.log("REPARENT",e),this.model=e,this.callback&&this.model.addEventListener("serialize",this.callback)}skinnedMeshExport(e,t,i){const n=this.model,o=this.animationData;if(n&&n.skinnedMesh){let r=function(k){const z=[];for(const[V,J]of k){let Z=`${V} : [`;const ce=[];for(const X of J)ce.push(`(${ie(X.x)}, ${ie(X.y)}, ${ie(X.z)})`);Z=Z.concat(ce.join(", ")),Z=Z.concat("],"),z.push(Z)}return z},a=function(k){const z=[];for(const[V,J]of k){let Z=`${V} : [`;const ce=[];for(const X of J)ce.push(`(${ie(X.w)}, ${ie(X.x)}, ${ie(X.y)}, ${ie(X.z)})`);Z=Z.concat(ce.join(", ")),Z=Z.concat("],"),z.push(Z)}return z},l=function(k){let z,V=!0;const J=new Map;for(const[ce,X]of k){z===void 0&&(z=X.length),z!==X.length&&(V=!1);let ge=0;for(const qt of X)ge++,qt||(J.has(ce)||J.set(ce,[]),J.get(ce).push(ge))}En&&console.log("Bone count: ",k.size,"TransformData entries per bone: ",z,"Undefined bone entries: ",J),console.assert(V,"All bones should have the same number of TransformData entries",k),console.assert(J.size===0,"All TransformData entries should be set",J);const Z=[];for(const[ce,X]of k)for(let ge=0;ge<X.length;ge++){const qt=X[ge],Mh=i.getStartTimeByClip(qt.clip);Z.length<=ge&&Z.push({pos:[],rot:[],scale:[],timeOffset:Mh});const As=Z[ge];As.pos.push(...qt.getSortedTimesArray(!0,!1,!1)),As.rot.push(...qt.getSortedTimesArray(!1,!0,!1)),As.scale.push(...qt.getSortedTimesArray(!1,!1,!0))}for(const ce of Z)ce.pos.sort((X,ge)=>X-ge),ce.rot.sort((X,ge)=>X-ge),ce.scale.sort((X,ge)=>X-ge),ce.pos=[...new Set(ce.pos)],ce.rot=[...new Set(ce.rot)],ce.scale=[...new Set(ce.scale)];return Z},h=function(k,z,V){const J=new Map,Z=new Map,ce=new Map,X=z.length;for(const ge of V){const qt=k.get(ge);let Mh;qt?console.assert(qt.length===X,"We should have the same number of TransformData entries for each bone",qt,z):Mh=new Ee(null,ge,null);for(let As=0;As<X;As++){const hf=qt?qt[As]:Mh,Fr=z[As];for(const{time:ul,translation:fl}of hf.getValues(Fr.pos,!0,!1,!1)){const Yi=(ul+Fr.timeOffset)*60;J.has(Yi)||J.set(Yi,new Array),J.get(Yi).push(fl.clone())}for(const{time:ul,rotation:fl}of hf.getValues(Fr.rot,!1,!0,!1)){const Yi=(ul+Fr.timeOffset)*60;Z.has(Yi)||Z.set(Yi,new Array),Z.get(Yi).push(fl.clone())}for(const{time:ul,scale:fl}of hf.getValues(Fr.scale,!1,!1,!0)){const Yi=(ul+Fr.timeOffset)*60;ce.has(Yi)||ce.set(Yi,new Array),ce.get(Yi).push(fl.clone())}}}return{position:J.size==0?void 0:J,quaternion:Z.size==0?void 0:Z,scale:ce.size==0?void 0:ce}},d=function(k){const z=[];for(const V of k)z.push(`(${ie(V.x)}, ${ie(V.y)}, ${ie(V.z)})`);return z.join(", ")},u=function(k){const z=[];for(const V of k)z.push(`(${ie(V.w)}, ${ie(V.x)}, ${ie(V.y)}, ${ie(V.z)})`);return z.join(", ")},p=function(k){const z=new Map;if(En){const V=new Array;for(const[J,Z]of o)V.push(J.uuid+": "+Z.length+" "+Z.map(ce=>ce.clip?.uuid.substring(0,6)).join(" "));console.log(`getPerBoneTransformData
|
|
1289
1289
|
`+V.join(`
|
|
1290
|
-
`))}for(const V of k){const J=o.get(V);J&&z.set(V,J)}return z},m=function(k){const z=p(k),V=l(z);return h(z,V,k)};const g=n.skinnedMesh.skeleton,_=new Array,y=[],v=[];for(const k of g.bones){y.push(k),v.push(k.uuid);const z=g.boneInverses[g.bones.indexOf(k)];_.push({bone:k,inverse:z})}let b=1e4;for(;v.length<g.bones.length&&b-- >0;)for(const k of y){const z=k.children;for(const V of z)if(v.indexOf(V.uuid)===-1&&g.bones.indexOf(V)!==-1){y.push(V),v.push(V.uuid);const J=g.boneInverses[g.bones.indexOf(V)];_.push({bone:V,inverse:J})}}b<=0&&console.error("Failed to sort bones in skinned mesh",n.skinnedMesh,g.bones,v);for(const k of vw(g.bones))_.push({bone:k,inverse:k.matrixWorld.clone().invert()});const w=_[0].bone.parent;w||console.error("No bone parent found for skinned mesh during USDZ export",n.skinnedMesh),_.sort((k,z)=>ba(k.bone,w)>ba(z.bone,w)?1:-1);const R=t.quickLookCompatible,M=[],O=[],A=[],D=[];for(const{bone:k}of _){if(R){const z=k.scale;z.x==0&&(z.x=1e-5),z.y==0&&(z.y=1e-5),z.z==0&&(z.z=1e-5),M.push(new c.Matrix4().compose(k.position,k.quaternion,k.scale))}else M.push(k.matrix.clone());O.push(k.position),A.push(k.quaternion),D.push(k.scale)}const L=_.map(k=>'"'+ba(k.bone,w)+'"').join(", "),N=_.map(k=>tb(k.inverse.clone().invert())).join(", ");e.beginBlock('def Skeleton "Rig"'),e.appendLine(`uniform matrix4d[] bindTransforms = [${N}]`),e.appendLine(`uniform token[] joints = [${L}]`),e.appendLine('uniform token purpose = "guide"'),e.appendLine(`uniform matrix4d[] restTransforms = [${M.map(k=>tb(k)).join(", ")}]`);const $=m(_.map(k=>k.bone));if(En){let k=1e7,z=0;for(const V of $.position?.keys()??[])k=Math.min(k,V),z=Math.max(z,V);console.log("Time samples",k,z,$)}if(e.beginBlock('def SkelAnimation "_anim"'),e.appendLine(`uniform token[] joints = [${L}]`),e.appendLine(`quatf[] rotations = [${u(A)}]`),$&&$.quaternion){e.beginBlock("quatf[] rotations.timeSamples = {","");const k=a($.quaternion);for(const z of k)e.appendLine(z);e.closeBlock()}if(e.appendLine(`half3[] scales = [${d(D)}]`),$&&$.scale){e.beginBlock("half3[] scales.timeSamples = {","");const k=r($.scale);for(const z of k)e.appendLine(z);e.closeBlock()}if(e.appendLine(`float3[] translations = [${d(O)}]`),$&&$.position){e.beginBlock("float3[] translations.timeSamples = {","");const k=r($.position);for(const z of k)e.appendLine(z);e.closeBlock()}e.closeBlock(),e.closeBlock()}}onSerialize(e,t){if(!this.model)return;const i=this.animationData.get(this.object);if(i)for(let d=0;d<i.length;d++)i[d]===void 0&&(i[d]=new Ee(null,this.object,null));const n=this.ext;this.skinnedMeshExport(e,t,n);const o=this.object,r=this.model,a=this.animationData.get(o);if(!a||o.isSkinnedMesh)return;tm&&console.log("SERIALIZE",this.model.name,this.object.type,a);const l=Intl.NumberFormat("en-US",{maximumFractionDigits:3,minimumFractionDigits:0,useGrouping:!1});function h(d,u){if(d.some(m=>m&&{position:m.pos,rotation:m.rot,scale:m.scale}[u])){switch(u){case"position":r.needsTranslate=!0,e.beginBlock("double3 xformOp:translate.timeSamples = {","");break;case"rotation":r.needsOrient=!0,e.beginBlock("quatf xformOp:orient.timeSamples = {","");break;case"scale":r.needsScale=!0,e.beginBlock("double3 xformOp:scale.timeSamples = {","");break}for(let m=0;m<d.length;m++){const g=d[m];if(!g)continue;const _=n.getStartTimeByClip(g.clip),y=g.getSortedTimesArray(u==="position",u==="rotation",u==="scale");if(!y||y.length===0){console.error("got an animated object but no time values?",o,g);continue}const v=!g.clip,b=u==="position"&&(g.pos||v),w=u==="rotation"&&(g.rot||v),R=u==="scale"&&(g.scale||v);if(b||w||R){const M=g.clip?.name??"rest",O=g.getDuration();En&&console.log("Write .timeSamples:",M,_,O,d),e.appendLine("# "+M+": start="+l.format(_*Ee.frameRate)+", length="+l.format(O*Ee.frameRate)+", frames="+g.getFrames())}if(b)for(const{time:M,translation:O}of g.getValues(y,!0,!1,!1)){const D=`${l.format((_+M)*Ee.frameRate)}: (${ie(O.x)}, ${ie(O.y)}, ${ie(O.z)}),`;e.appendLine(D)}if(w)for(const{time:M,rotation:O}of g.getValues(y,!1,!0,!1)){const D=`${l.format((_+M)*Ee.frameRate)}: (${ie(O.w)}, ${ie(O.x)}, ${ie(O.y)}, ${ie(O.z)}),`;e.appendLine(D)}if(R)for(const{time:M,scale:O}of g.getValues(y,!1,!1,!0)){const D=`${l.format((_+M)*Ee.frameRate)}: (${ie(O.x)}, ${ie(O.y)}, ${ie(O.z)}),`;e.appendLine(D)}}e.closeBlock()}}h(a,"position"),h(a,"rotation"),h(a,"scale")}}const IO=x("debugusdz");class Cr{static getName(e){const t=e.split(".").pop();let n=e.split(".").slice(0,-1).join(".").split("/").pop()?.replace(".","_");return n||(n="Audio_"+Math.random().toString(36).substring(2,15)),bi(n)+"."+t}get extensionName(){return"Audio"}files=new Array;onExportObject(e,t,i){const n=S.getComponents(e,_i);if(n.length)for(const o of n){if(!o.clip||typeof o.clip!="string"||!o.playOnAwake)continue;const r=o.clip.split("/").pop()||"Audio",a=Cr.getName(o.clip),l=bi(a);if(!this.files.some(h=>h.path===o.clip)){this.files.push({path:o.clip,name:a});const h=a.toLowerCase();i.quickLookCompatible&&!h.endsWith(".mp3")&&!h.endsWith(".wav")&&!h.endsWith(".m4a")&&console.error("Audio file "+o.clip+" from "+o.name+" is not an MP3 or WAV file. QuickLook may not support playing it.")}i.quickLookCompatible||t.addEventListener("serialize",(h,d)=>{h.appendLine(),h.beginBlock(`def SpatialAudio "${l}"`,"(",!1),h.appendLine(`displayName = "${r}"`),h.closeBlock(")"),h.beginBlock(),h.appendLine(`uniform asset filePath = @audio/${a}@`),h.appendLine(`uniform token auralMode = "${o.spatialBlend>0?"spatial":"nonSpatial"}"`),h.appendLine(`uniform token playbackMode = "${o.loop?"loopFromStage":"onceFromStart"}"`),h.appendLine(`uniform float gain = ${o.volume}`),h.closeBlock()})}}async onAfterSerialize(e){for(const t of this.files){const i="audio/"+t.name;if(e.files[i]){IO&&console.warn("Audio file with name "+i+" already exists in the context. Skipping.");continue}const r=await(await(await fetch(t.path)).blob()).arrayBuffer(),a=new Uint8Array(r);e.files[i]=a}}}var jO=Object.defineProperty,Re=(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&&jO(e,t,n),n};const rb=x("debugusdzbehaviours");function Zc(s){s&&(s.getComponentInParent(Ta)||(T()&&console.debug('Raycaster on "'+s.name+'" was automatically added, because no raycaster was found in the parent hierarchy.'),s.addComponent(yi)))}class Pr extends E{object;target;duration=1;relativeMotion=!1;coroutine=null;targetPos=new c.Vector3;targetRot=new c.Quaternion;targetScale=new c.Vector3;start(){Zc(this.gameObject)}onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}onPointerClick(e){const t=this.object?.getComponentsInChildren(Fe);if(t)for(const i of t)i.resetVelocities(),i.resetForcesAndTorques();e.use(),this.coroutine&&this.stopCoroutine(this.coroutine),this.relativeMotion?this.coroutine=this.startCoroutine(this.moveRelative()):this.coroutine=this.startCoroutine(this.moveToTarget())}*moveToTarget(){if(!this.target||!this.object)return;const e=Q(this.object).clone(),t=Q(this.target).clone(),i=fe(this.object).clone(),n=fe(this.target).clone(),o=Le(this.object).clone(),r=Le(this.target).clone(),a=e.distanceTo(t),l=i.angleTo(n),h=o.distanceTo(r);if(a<.01&&l<.01&&h<.01){rt(this.object,t),ln(this.object,n),Sa(this.object,r),this.coroutine=null;return}let d=0,u=0;for(;d<1;)d+=this.context.time.deltaTime/this.duration,d>1&&(d=1),u=d<.5?4*d*d*d:1-Math.pow(-2*d+2,3)/2,this.targetPos.lerpVectors(e,t,u),this.targetRot.slerpQuaternions(i,n,u),this.targetScale.lerpVectors(o,r,u),rt(this.object,this.targetPos),ln(this.object,this.targetRot),Sa(this.object,this.targetScale),yield;this.coroutine=null}*moveRelative(){if(!this.target||!this.object)return;const e=this.object.position.clone(),t=this.object.quaternion.clone(),i=this.object.scale.clone(),n=this.target.position.clone(),o=this.target.quaternion.clone(),r=this.target.scale.clone();n.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(n),this.targetRot.copy(this.object.quaternion).multiply(o),this.targetScale.copy(this.object.scale).multiply(r);let a=0,l=0;for(;a<1;)a+=this.context.time.deltaTime/this.duration,a>1&&(a=1),l=a<.5?4*a*a*a:1-Math.pow(-2*a+2,3)/2,this.object.position.lerpVectors(e,this.targetPos,l),this.object.quaternion.slerpQuaternions(t,this.targetRot,l),this.object.scale.lerpVectors(i,this.targetScale,l),yield;this.coroutine=null}beforeCreateDocument(e){if(this.target&&this.object&&this.gameObject){const t=new bt("Move to "+this.target?.name,kt.tapTrigger(this.gameObject),he.transformAction(this.object,this.target,this.duration,this.relativeMotion?"relative":"absolute"));e.addBehavior(t)}}}Re([f(c.Object3D)],Pr.prototype,"object");Re([f(c.Object3D)],Pr.prototype,"target");Re([f()],Pr.prototype,"duration");Re([f()],Pr.prototype,"relativeMotion");const ku=class Bt extends E{materialToSwitch;variantMaterial;fadeDuration=0;start(){this._objectsWithThisMaterial=this.objectsWithThisMaterial,Zc(this.gameObject),T()&&this._objectsWithThisMaterial.length<=0&&console.warn('ChangeMaterialOnClick: No objects found with material "'+this.materialToSwitch?.name+'"')}onPointerEnter(e){this.context.input.setCursor("pointer")}onPointerExit(e){this.context.input.unsetCursor("pointer")}onPointerClick(e){if(e.use(),!!this.variantMaterial)for(let t=0;t<this.objectsWithThisMaterial.length;t++){const i=this.objectsWithThisMaterial[t];i.material=this.variantMaterial}}_objectsWithThisMaterial=null;get objectsWithThisMaterial(){return this._objectsWithThisMaterial!=null?this._objectsWithThisMaterial:(this._objectsWithThisMaterial=[],this.variantMaterial&&this.materialToSwitch&&this.context.scene.traverse(e=>{if(e instanceof c.Mesh)if(Array.isArray(e.material)){for(const t of e.material)if(t===this.materialToSwitch){this.objectsWithThisMaterial.push(e);break}}else e.material===this.materialToSwitch?this.objectsWithThisMaterial.push(e):Qv(e.material,this.materialToSwitch)&&this.objectsWithThisMaterial.push(e)}),this._objectsWithThisMaterial)}selfModel;targetModels;static _materialTriggersPerId={};static _startHiddenBehaviour=null;static _parallelStartHiddenActions=[];async beforeCreateDocument(e,t){this.targetModels=[],Bt._materialTriggersPerId={},Bt.variantSwitchIndex=0,this.materialToSwitch&&await se.NEEDLE_progressive.assignTextureLOD(this.materialToSwitch,0),this.variantMaterial&&await se.NEEDLE_progressive.assignTextureLOD(this.variantMaterial,0)}createBehaviours(e,t,i){this.objectsWithThisMaterial.find(o=>o.uuid===t.uuid)&&this.targetModels.push(t),this.gameObject.uuid===t.uuid&&(this.selfModel=t,this.materialToSwitch&&(Bt._materialTriggersPerId[this.materialToSwitch.uuid]||(Bt._materialTriggersPerId[this.materialToSwitch.uuid]=[]),Bt._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(e,t){if(!this.materialToSwitch)return;const i=Bt._materialTriggersPerId[this.materialToSwitch.uuid];if(i){const n={};for(const o of i){const r=o.createVariants();r&&r.length>0&&(n[o.selfModel.uuid]=r)}for(const o of i){const r=[];for(const a in n)a!==o.selfModel.uuid&&r.push(...n[a]);o.createAndAttachBehaviors(e,n[o.selfModel.uuid],r)}}delete Bt._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(e,t,i){const n=[],o=Math.max(0,this.fadeDuration);n.push(he.fadeAction([...this.targetModels,...i],o,!1)),n.push(he.fadeAction(t,o,!0)),e.addBehavior(new bt("Select_"+this.selfModel.name,kt.tapTrigger(this.selfModel),he.parallel(...n))),Bt._parallelStartHiddenActions.push(...t),Bt._startHiddenBehaviour||(Bt._startHiddenBehaviour=new bt("StartHidden_"+this.selfModel.name,kt.sceneStartTrigger(),he.fadeAction(Bt._parallelStartHiddenActions,o,!1)),e.addBehavior(Bt._startHiddenBehaviour))}static getMaterialName(e){return bi(e.name||"Material")+"_"+e.id}static variantSwitchIndex=0;createVariants(){if(!this.variantMaterial)return null;const e=[];for(const t of this.targetModels){const i=t.clone();i.name+="_Variant_"+Bt.variantSwitchIndex+++"_"+Bt.getMaterialName(this.variantMaterial),i.displayName=i.displayName+": Variant with material "+this.variantMaterial.name,i.material=this.variantMaterial,i.geometry=t.geometry,i.transform=t.transform,(!t.parent||!t.parent.isEmpty())&&We.createEmptyParent(t),t.parent&&t.parent.add(i),e.push(i)}return e}};Re([f(c.Material)],ku.prototype,"materialToSwitch");Re([f(c.Material)],ku.prototype,"variantMaterial");Re([f()],ku.prototype,"fadeDuration");let Ig=ku;const Jc=class Me extends E{target;toggleOnClick=!1;targetState=!0;hideSelf=!0;start(){Zc(this.gameObject)}onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}onPointerClick(e){e.use(),!this.toggleOnClick&&this.hideSelf&&(this.gameObject.visible=!1),this.target&&(this.target.visible=this.toggleOnClick?!this.target.visible:this.targetState)}selfModel;selfModelClone;targetModel;toggleModel;createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t,this.selfModelClone=t.clone())}stateBeforeCreatingDocument=!1;targetStateBeforeCreatingDocument=!1;static clonedToggleIndex=0;static wasVisible=Symbol("usdz_SetActiveOnClick_wasVisible");static toggleClone=Symbol("clone for toggling");static reverseToggleClone=Symbol("clone for reverse toggling");beforeCreateDocument(){this.target&&(this.gameObject[Me.wasVisible]===void 0&&(this.gameObject[Me.wasVisible]=this.gameObject.activeSelf),this.target[Me.wasVisible]===void 0&&(this.target[Me.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[Me.wasVisible],this.targetStateBeforeCreatingDocument=this.target[Me.wasVisible],this.gameObject.visible=!0,this.target.visible=!0)}afterCreateDocument(e,t){if(!this.target)return;this.targetModel=t.document.findById(this.target.uuid);const i=this.selfModel;if(this.selfModel&&this.targetModel){let n=this.selfModel,o=this.targetState;if(this.toggleOnClick)if(o=!this.targetStateBeforeCreatingDocument,!this.selfModelClone.geometry)(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&Ag.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[Me.toggleClone]){const l=this.selfModelClone.clone();l.setMatrix(new c.Matrix4),l.name+="_toggle"+Me.clonedToggleIndex++,i.add(l),this.gameObject[Me.toggleClone]=l,console.warn("USDZExport: Toggle "+this.gameObject.name+" doesn't have geometry. It will be deep cloned and nested behaviours will likely not work.")}const a=this.gameObject[Me.toggleClone];if(!this.gameObject[Me.reverseToggleClone]){const l=this.selfModelClone.clone();l.setMatrix(new c.Matrix4),l.name+="_toggleReverse"+Me.clonedToggleIndex++,i.add(l),this.gameObject[Me.reverseToggleClone]=l}this.toggleModel=this.gameObject[Me.reverseToggleClone],(!this.toggleModel.geometry||!a.geometry)&&console.error("triggers without childs and without geometry won't work!",this,i.geometry),n=a,i.geometry=null,i.material=null}if(this.toggleModel){if(this.toggleOnClick){const a=[];a.push(he.fadeAction(n,0,!1)),a.push(he.fadeAction(this.toggleModel,0,!0)),a.push(he.fadeAction(this.targetModel,0,o)),e.addBehavior(new bt("Toggle_"+n.name+"_ToggleTo"+(o?"On":"Off"),kt.tapTrigger(n),he.parallel(...a)));const l=[];l.push(he.fadeAction(this.toggleModel,0,!1)),l.push(he.fadeAction(n,0,!0)),l.push(he.fadeAction(this.targetModel,0,!o)),e.addBehavior(new bt("Toggle_"+n.name+"_ToggleTo"+(o?"Off":"On"),kt.tapTrigger(this.toggleModel),he.parallel(...l)))}}else{const a=[];this.hideSelf&&a.push(he.fadeAction(n,0,!1)),a.push(he.fadeAction(this.targetModel,0,o)),e.addBehavior(new bt("Toggle_"+n.name+"_ToggleTo"+(o?"On":"Off"),kt.tapTrigger(n),a.length>1?he.parallel(...a):a[0]))}const r=new Array;this.targetStateBeforeCreatingDocument||r.push(this.targetModel),this.stateBeforeCreatingDocument||r.push(i),this.toggleModel&&r.push(this.toggleModel),Di.add(r,e)}}afterSerialize(e,t){this.gameObject[Me.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[Me.wasVisible],delete this.gameObject[Me.wasVisible]),this.target&&this.target[Me.wasVisible]!==void 0&&(this.target.visible=this.target[Me.wasVisible],delete this.target[Me.wasVisible]),delete this.gameObject[Me.toggleClone],delete this.gameObject[Me.reverseToggleClone]}};Re([f(c.Object3D)],Jc.prototype,"target");Re([f()],Jc.prototype,"toggleOnClick");Re([f()],Jc.prototype,"targetState");Re([f()],Jc.prototype,"hideSelf");let jg=Jc;class Di extends E{static _fadeBehaviour;static _fadeObjects=[];static add(e,t){const i=Array.isArray(e)?e:[e];for(const n of i)Di._fadeObjects.includes(n)||(console.log("adding hide on start",n),Di._fadeObjects.push(n));Di._fadeBehaviour===void 0&&(Di._fadeBehaviour=new bt("HideOnStart",kt.sceneStartTrigger(),he.fadeAction(Di._fadeObjects,0,!1)),t.addBehavior(Di._fadeBehaviour))}start(){S.setActive(this.gameObject,!1)}createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.wasVisible||Di.add(t,e))}wasVisible=!1;beforeCreateDocument(){this.wasVisible=S.isActiveSelf(this.gameObject)}}class Wa extends E{target;duration=.5;motionType="bounce";beforeCreateDocument(){}createBehaviours(e,t,i){if(this.target&&t.uuid===this.gameObject.uuid){const n=new bt("emphasize "+this.name,kt.tapTrigger(this.gameObject),he.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));e.addBehavior(n)}}afterCreateDocument(e,t){}}Re([f()],Wa.prototype,"target");Re([f()],Wa.prototype,"duration");Re([f()],Wa.prototype,"motionType");class ro extends E{target;clip="";toggleOnClick=!1;trigger="tap";start(){Zc(this.gameObject)}ensureAudioSource(){if(!this.target){const e=this.gameObject.addComponent(_i);e&&(this.target=e,e.spatialBlend=1,e.volume=1,e.loop=!1,e.preload=!0)}}onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}onPointerClick(e){e.use(),!(!this.target?.clip&&!this.clip)&&(this.ensureAudioSource(),this.target&&(this.target.isPlaying&&this.toggleOnClick?this.target.stop():(!this.toggleOnClick&&this.target.isPlaying&&this.target.stop(),this.clip?this.target.play(this.clip):this.target.play())))}createBehaviours(e,t,i){if(!(!this.target&&!this.clip)&&t.uuid===this.gameObject.uuid){const n=this.clip?this.clip:this.target?this.target.clip:void 0;if(!n||typeof n!="string")return;const o=this.target?this.target.gameObject:this.gameObject;Cr.getName(n);const r=this.target?this.target.volume:1,a=this.target&&this.target.spatialBlend==0?"nonSpatial":"spatial";let l=!1;this.gameObject.traverse(p=>{p instanceof c.Mesh&&p.visible&&(l=!0)}),l=!0;const h=e.addAudioClip(n);let d=he.playAudioAction(o,h,"play",r,a);this.target&&this.target.loop&&(d=he.sequence(d).makeLooping());const u=this.name?"_"+this.name:"";if(l&&this.trigger==="tap"){this.toggleOnClick&&(d.multiplePerformOperation="stop");const p=new bt("playAudio"+u,kt.tapTrigger(t),d);e.addBehavior(p)}if(this.target&&this.target.playOnAwake&&this.target.enabled)if(l&&this.trigger==="tap")console.warn("USDZExport: Audio sources that are played on tap can't also auto-play at scene start due to a QuickLook bug.");else{const p=new bt("playAudioOnStart"+u,kt.sceneStartTrigger(),d);e.addBehavior(p)}}}}Re([f(_i)],ro.prototype,"target");Re([f(URL)],ro.prototype,"clip");Re([f()],ro.prototype,"toggleOnClick");const Bg=class Sn extends E{animator;stateName;trigger="tap";animation;get target(){return this.animator?.gameObject||this.animation?.gameObject}start(){Zc(this.gameObject)}onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}onPointerClick(e){e.use(),this.target&&this.stateName&&this.animator?.play(this.stateName,0,0,.1)}selfModel;stateAnimationModel;animationSequence=new Array;animationLoopAfterSequence=new Array;randomOffsetNormalized=0;createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t)}static animationActions=[];static rootsWithExclusivePlayback=new Set;afterSerialize(){if(Sn.rootsWithExclusivePlayback.size>1){const e='Multiple root objects targeted by more than one animation. To work around QuickLook bug FB13410767, animations will be set as "exclusive" and activating them will stop other animations being marked as exclusive.';T()&&ue(e),console.warn(e,...Sn.rootsWithExclusivePlayback)}Sn.animationActions=[],Sn.rootsWithExclusivePlayback=new Set}afterCreateDocument(e,t){if(this.animationSequence===void 0&&this.animationLoopAfterSequence===void 0||!this.stateAnimationModel||!this.target)return;const i=t.document,n=t.extensions.find(a=>a instanceof Ou);if(!n)return;const o=n.getClipCount(this.target)>1;o&&(T()&&console.warn("Setting exclusive playback for "+this.target.name+"@"+this.stateName+" because it has "+n.getClipCount(this.target)+" animations. This works around QuickLook bug FB13410767."),Sn.rootsWithExclusivePlayback.add(this.target));const r=this.name?this.name:"";i.traverse(a=>{if(a.uuid===this.target?.uuid){const l=Sn.getActionForSequences(i,a,this.animationSequence,this.animationLoopAfterSequence,this.randomOffsetNormalized),h=new bt(this.trigger+"_"+r+"_toPlayAnimation_"+this.stateName+"_on_"+this.target?.name,this.trigger=="tap"?kt.tapTrigger(this.selfModel):kt.sceneStartTrigger(),l);o&&h.makeExclusive(!0),e.addBehavior(h)}})}static getActionForSequences(e,t,i,n,o){const r=(l,h)=>{let d=Sn.animationActions.find(u=>u.affectedObjects==l&&u.start==h.start&&u.duration==h.duration&&u.animationSpeed==h.speed);return d||(d=he.startAnimationAction(l,h),Sn.animationActions.push(d)),d},a=he.sequence();if(i&&i.length>0)for(const l of i)a.addAction(r(t,l));if(n&&n.length>0){const l=a.actions.length==0?a:he.sequence();for(const h of n)l.addAction(r(t,h));l.makeLooping(),a!==l&&a.addAction(l)}return o&&o>0&&a.actions.unshift(he.waitAction(o)),a}static getAndRegisterAnimationSequences(e,t,i){if(!t)return;const n=t.getComponent(at),o=t.getComponent(Et);if(!n&&!o)return;if(n&&!i)throw new Error("PlayAnimationOnClick: No stateName specified for animator "+n.name+" on "+t.name);let r=[],a=[];if(o){const g=e.registerAnimation(t,o.clip);g&&(o.loop?a.push(g):r.push(g));let _=0;if(o.minMaxOffsetNormalized){const y=o.minMaxOffsetNormalized.x,v=o.minMaxOffsetNormalized.y;_=(o.clip?.duration||1)*(y+Math.random()*(v-y))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:_}}const l=n?.runtimeAnimatorController;let h=l?.findState(i),d=[],u=[];if(l&&h){const g=new Array;g.push(h);let _=!1;for(;g.length<100;){if(!h||h===null||!h.transitions||h.transitions.length===0){h.motion?.isLooping&&(_=!0);break}const y=h.transitions.find(b=>b.conditions.length===0),v=y?l.getState(y.destinationState,0):null;if(v&&g.includes(v)){h=v,_=!0;break}else if(y){if(h=v,!h)break;g.push(h)}else{_=h.motion?.isLooping??!1;break}}if(_&&h){const y=g.indexOf(h);d=g.slice(0,y),u=g.slice(y),rb&&console.log("found loop from "+i,"states until loop",d,"states looping",u)}else d=g,u=[],rb&&console.log("found no loop from "+i,"states",d);if(!u.length){const y=d[d.length-1],v=y.motion?.clip;if(v){let b;if(e.holdClipMap.has(v))b=e.holdClipMap.get(v);else{const w=y.name+"_hold";b=v.clone(),b.duration=1,b.name=w;const R=v.duration;b.tracks=v.tracks.map(M=>{const O=M.clone();O.times=new Float32Array([0,R]);const A=M.values.length,D=M.getValueSize(),L=M.values.slice(A-D,A);return O.values=new Float32Array(2*D),O.values.set(L,0),O.values.set(L,D),O}),b.name=w,e.holdClipMap.set(v,b)}if(b){const w={name:b.name,motion:{clip:b,isLooping:!1,name:b.name},speed:1,transitions:[],behaviours:[],hash:y.hash+1};u.push(w)}}}}if(d.length===1&&(!d[0].motion?.clip||d[0].motion?.clip.tracks?.length===0)){r=new Array;const g=e.registerAnimation(t,null);g&&r.push(g);return}if(d=d.filter(g=>g.motion?.clip&&g.motion?.clip.tracks?.length>0),u=u.filter(g=>g.motion?.clip&&g.motion?.clip.tracks?.length>0),d.length===0&&u.length===0){console.warn("No clips found for state "+i+" on "+n?.name+", can't export animation data");return}const p=(g,_)=>{if(!t)return;const y=e.registerAnimation(t,g.motion.clip??null);y?(y.speed=g.speed,_.push(y)):console.warn("Couldn't register animation for state "+g.name+" on "+n?.name)};if(d.length>0){r=new Array;for(const g of d)p(g,r)}if(u.length>0){a=new Array;for(const g of u)p(g,a)}let m=0;if(n&&l&&n.minMaxOffsetNormalized){const g=n.minMaxOffsetNormalized.x,_=n.minMaxOffsetNormalized.y;m=((d.length?d[0]:u.length?u[0]:null)?.motion.clip?.duration||1)*(g+Math.random()*(_-g))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:m}}createAnimation(e,t,i){if(!this.target||!this.animator&&!this.animation)return;const n=Sn.getAndRegisterAnimationSequences(e,this.target,this.stateName);n&&(this.animationSequence=n.animationSequence,this.animationLoopAfterSequence=n.animationLoopAfterSequence,this.randomOffsetNormalized=n.randomTimeOffset,this.stateAnimationModel=t)}};Re([f(at)],Bg.prototype,"animator");Re([f()],Bg.prototype,"stateName");let Sc=Bg;class Ha extends E{getType(){}target;getDuration(){}}Re([f(c.Object3D)],Ha.prototype,"target");class eh extends E{target}Re([f(Ha)],eh.prototype,"target");class th extends Ha{type=1;duration=1;getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}Re([f()],th.prototype,"type");Re([f()],th.prototype,"duration");class Ug extends eh{}const BO=100,UO=200,FO=300;class no{static _instance;static create(){return new no}static getOrCreate(){return this._instance||(this._instance=this.create()),this._instance}get isSecureConnection(){return window.location.protocol==="https:"}get quicklookButton(){return this._quicklookButton}_quicklookButton;get arButton(){return this._arButton}_arButton;get vrButton(){return this._vrButton}_vrButton;get sendToQuestButton(){return this._sendToQuestButton}_sendToQuestButton;get qrButton(){return ji.getOrCreate().createQRCode()}createQuicklookButton(){if(this._quicklookButton)return this._quicklookButton;const e=document.createElement("button");this._quicklookButton=e,e.dataset.needle="quicklook-button";const t=exports.DeviceUtilities.supportsQuickLookAR();let i="View in AR";exports.DeviceUtilities.isVisionOS()?i="View in AR":(t||exports.DeviceUtilities.isiOS())&&(i="Open in Quicklook"),e.innerText=i,e.prepend(yt("view_in_ar")),Js.setElementPriority(e,UO);let n=!1,o=null;return e.addEventListener("click",()=>{o=Ua(an),o||(n=!0,o=new an),n&&(o.objectToExport=U.Current.scene),o?(e.classList.add("this-mode-is-requested"),o.exportAndOpen().then(()=>{e.classList.remove("this-mode-is-requested")}).catch(r=>{e.classList.remove("this-mode-is-requested"),console.error(r)})):console.warn("No USDZExporter component found in the scene")}),this.hideElementDuringXRSession(e),e}createARButton(e){if(this._arButton)return this._arButton;const t="immersive-ar",i=document.createElement("button");return this._arButton=i,i.classList.add("webxr-button"),i.dataset.needle="webxr-ar-button",i.innerText="Enter AR",i.prepend(yt("view_in_ar")),i.title="Click to start an AR session",i.addEventListener("click",()=>G.start(t,e)),Js.setElementPriority(i,FO),this.updateSessionSupported(i,t),this.listenToXRSessionState(i,t),this.hideElementDuringXRSession(i),this.isSecureConnection||(i.disabled=!0,i.title="WebXR requires a secure connection (HTTPS)"),exports.DeviceUtilities.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>this.updateSessionSupported(i,t)),i}createVRButton(e){if(this._vrButton)return this._vrButton;const t="immersive-vr",i=document.createElement("button");return this._vrButton=i,i.classList.add("webxr-button"),i.dataset.needle="webxr-vr-button",i.innerText="Enter VR",i.prepend(yt("panorama_photosphere")),i.title="Click to start a VR session",i.addEventListener("click",()=>G.start(t,e)),Js.setElementPriority(i,BO),this.updateSessionSupported(i,t),this.listenToXRSessionState(i,t),this.hideElementDuringXRSession(i),this.isSecureConnection||(i.disabled=!0,i.title="WebXR requires a secure connection (HTTPS)"),exports.DeviceUtilities.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>this.updateSessionSupported(i,t)),i}createSendToQuestButton(){if(this._sendToQuestButton)return this._sendToQuestButton;const e="https://oculus.com/open_url/?url=",t=document.createElement("button");return this._sendToQuestButton=t,t.dataset.needle="webxr-sendtoquest-button",t.innerText="Open on Quest",t.prepend(yt("share_windows")),t.title="Click to send this page to the Oculus Browser on your Quest",t.addEventListener("click",()=>{const i=encodeURIComponent(window.location.href),n=e+i;window.open(n)==null&&we("This page doesn't allow popups. Please paste "+n+" into your browser.")}),this.listenToXRSessionState(t),this.hideElementDuringXRSession(t),exports.DeviceUtilities.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>{navigator.xr?.isSessionSupported("immersive-vr")?t.style.display="none":t.style.display=""}),t}createQRCode(){return ji.getOrCreate().createQRCode()}updateSessionSupported(e,t){if(!(t==="immersive-ar"&&exports.DeviceUtilities.isiOS()&&!exports.DeviceUtilities.isVisionOS())){if(!("xr"in navigator)){e.style.display="none";return}G.isSessionSupported(t).then(i=>{e.style.display=i?"":"none",T()&&!i&&console.log('[WebXR] "'+t+'" is not supported on this device. Make sure your server runs using HTTPS and you have a device connected that supports '+t)})}}hideElementDuringXRSession(e){su(t=>{e["previous-display"]=e.style.display,e.style.setProperty("display","none","important")}),Dm(t=>{e["previous-display"]!=null&&(e.style.display=e["previous-display"])})}listenToXRSessionState(e,t){t&&(G.onSessionRequestStart(i=>{i.mode===t?e.classList.add("this-mode-is-requested"):(e["was-disabled"]=e.disabled,e.disabled=!0,e.classList.add("other-mode-is-requested"))}),G.onSessionRequestEnd(i=>{e.classList.remove("this-mode-is-requested"),e.classList.remove("other-mode-is-requested"),e.disabled=e["was-disabled"]}))}}var zO=Object.defineProperty,NO=Object.getOwnPropertyDescriptor,lt=(s,e,t,i)=>{for(var n=i>1?void 0:i?NO(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&&zO(e,t,n),n};const nc=x("debugspriterenderer"),VO=x("wireframe");class ur{static cache={};static getOrCreateGeometry(e){if(e.__cached_geometry)return e.__cached_geometry;if(e.guid&&ur.cache[e.guid])return nc&&console.log("Take cached geometry for sprite",e.guid),ur.cache[e.guid];const t=new c.BufferGeometry;e.__cached_geometry=t;const i=new Float32Array(e.triangles.length*3),n=new Float32Array(e.triangles.length*2);for(let o=0;o<e.triangles.length;o+=1){const r=e.triangles[o];i[o*3]=-e.vertices[r].x,i[o*3+1]=e.vertices[r].y,i[o*3+2]=0;const a=e.uv[r];n[o*2]=a.x,n[o*2+1]=1-a.y}return t.setAttribute("position",new c.BufferAttribute(i,3)),t.setAttribute("uv",new c.BufferAttribute(n,2)),e.guid&&(this.cache[e.guid]=t),nc&&console.log("Built sprite geometry",e,t),t}}class $O{x;y}function Tw(s){s&&(s.colorSpace!=c.SRGBColorSpace&&(s.colorSpace=c.SRGBColorSpace,s.needsUpdate=!0),s.minFilter==c.NearestFilter&&s.magFilter==c.NearestFilter&&(s.anisotropy=1,s.needsUpdate=!0))}let ws=class{constructor(e){e&&(this.texture=e,this.triangles=[0,1,2,0,2,3],this.uv=[{x:0,y:0},{x:1,y:0},{x:1,y:1},{x:0,y:1}],this.vertices=[{x:-.5,y:-.5},{x:.5,y:-.5},{x:.5,y:.5},{x:-.5,y:.5}])}guid;texture;triangles;uv;vertices;__cached_geometry;get mesh(){return this._mesh||(this._mesh=new c.Mesh(ur.getOrCreateGeometry(this),this.material)),this._mesh}_mesh;get material(){return this._material||(this.texture&&Tw(this.texture),this._material=new c.MeshBasicMaterial({map:this.texture,color:16777215,side:c.DoubleSide,transparent:!0})),this._material}_material;getGeometry(){return ur.getOrCreateGeometry(this)}};lt([f()],ws.prototype,"guid",2);lt([f(c.Texture)],ws.prototype,"texture",2);lt([ze()],ws.prototype,"triangles",2);lt([ze()],ws.prototype,"uv",2);lt([ze()],ws.prototype,"vertices",2);const Yf=Symbol("spriteOwner");class Aa{sprites;constructor(){this.sprites=[]}}lt([f(ws)],Aa.prototype,"sprites",2);const Fg=class im{static create(){const e=new im;return e.spriteSheet=new Aa,e}constructor(){}clone(){const e=new im;return e.index=this.index,e.spriteSheet=this.spriteSheet,e}set sprite(e){e&&(this.spriteSheet?((this.index===null||this.index===void 0)&&(this.index=0),this.spriteSheet.sprites[this.index]=e):(this.spriteSheet=new Aa,this.spriteSheet.sprites=[e],this.index=0))}get sprite(){if(this.spriteSheet)return this.spriteSheet.sprites[this.index]}spriteSheet;index=0;update(e){if(!this.spriteSheet)return;const t=this.index;if(t<0||t>=this.spriteSheet.sprites.length)return;const i=this.spriteSheet.sprites[t],n=i?.texture;if(n&&(Tw(n),!i.__hasLoadedProgressive)){i.__hasLoadedProgressive=!0;const o=n;se.NEEDLE_progressive.assignTextureLOD(n,0).then(r=>{r instanceof c.Texture&&(i.texture=r,e?.map===o&&(e.map=r,e.needsUpdate=!0))})}}};lt([f(Aa)],Fg.prototype,"spriteSheet",2);lt([f()],Fg.prototype,"index",2);let va=Fg;class oi extends E{drawMode=0;size={x:1,y:1};color;sharedMaterial;transparent=!0;cutoutThreshold=0;castShadows=!1;renderOrder=0;toneMapped=!0;set texture(e){if(!this._spriteSheet)return;const t=this._spriteSheet.spriteSheet?.sprites[this.spriteIndex];t&&(t.texture=e,this.updateSprite())}addSprite(e,t=!1){if(this._spriteSheet||(this._spriteSheet=va.create()),!this._spriteSheet.spriteSheet)return-1;this._spriteSheet.spriteSheet?.sprites.push(e);const i=this._spriteSheet.spriteSheet?.sprites.length-1;return t&&(this.spriteIndex=i),i}get sprite(){return this._spriteSheet}set sprite(e){if(e!==this._spriteSheet)if(typeof e=="number"){const t=Math.round(e);nc&&console.log("[SpriteSheet] Set index to "+t+" (was "+this.spriteIndex+")",e),this.spriteIndex=t}else e instanceof ws?(this._spriteSheet||(this._spriteSheet=va.create()),this._spriteSheet.sprite!=e&&(this._spriteSheet.sprite=e),this.updateSprite()):e!=this._spriteSheet&&(this._spriteSheet=e,this.updateSprite())}set spriteIndex(e){this._spriteSheet&&(this._spriteSheet.index=e,this.updateSprite())}get spriteIndex(){return this._spriteSheet?.index??0}get spriteFrames(){return this._spriteSheet?.spriteSheet?.sprites.length??0}_spriteSheet;_currentSprite;awake(){this._currentSprite=void 0,this._spriteSheet?this._spriteSheet=this._spriteSheet.clone():this._spriteSheet=va.create(),nc&&console.log("Awake",this.name,this,this.sprite)}start(){this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(e=!1){if(!this.__didAwake&&!e)return!1;const t=this._spriteSheet;if(!t?.spriteSheet?.sprites)return console.warn("SpriteRenderer has no data or spritesheet assigned..."),!1;const i=t.spriteSheet.sprites[this.spriteIndex];if(!i)return nc&&console.warn("Sprite not found",this.spriteIndex,t.spriteSheet.sprites),!1;if(this._currentSprite)this._currentSprite.geometry=ur.getOrCreateGeometry(i),this._currentSprite.material.map=i.texture;else{const n=new c.MeshBasicMaterial({color:16777215,side:c.DoubleSide});if(VO&&(n.wireframe=!0),this.color&&(n.color||(n.color=new c.Color),n.color.copy(this.color),n.opacity=this.color.alpha),n.transparent=!0,n.toneMapped=this.toneMapped,n.depthWrite=!1,i.texture&&!n.wireframe){let o=i.texture;o[Yf]!==void 0&&o[Yf]!==this&&this.spriteFrames>1&&(o=i.texture=o.clone()),o[Yf]=this,n.map=o}this.sharedMaterial=n,this._currentSprite=new c.Mesh(ur.getOrCreateGeometry(i),n),this._currentSprite.renderOrder=Math.round(this.renderOrder),se.NEEDLE_progressive.assignTextureLOD(n,0)}return this._currentSprite.parent!==this.gameObject&&(this.drawMode===2&&this._currentSprite.scale.set(this.size.x,this.size.y,1),this.gameObject&&this.gameObject.add(this._currentSprite)),this._currentSprite&&this._currentSprite.layers.set(this.layer),this.sharedMaterial&&(this.sharedMaterial.alphaTest=this.cutoutThreshold,this.sharedMaterial.transparent=this.transparent),this._currentSprite.castShadow=this.castShadows,t?.update(this.sharedMaterial),!0}}lt([f()],oi.prototype,"drawMode",2);lt([f($O)],oi.prototype,"size",2);lt([f(ee)],oi.prototype,"color",2);lt([f(c.Material)],oi.prototype,"sharedMaterial",2);lt([f()],oi.prototype,"transparent",2);lt([f()],oi.prototype,"cutoutThreshold",2);lt([f()],oi.prototype,"castShadows",2);lt([f()],oi.prototype,"renderOrder",2);lt([f()],oi.prototype,"toneMapped",2);lt([f(va)],oi.prototype,"sprite",1);const ab=x("debugwebxr"),WO=new c.Matrix4().makeRotationY(Math.PI);class Bi extends E{static _eventListeners={};static onPlaced(e){const t="placed";return this._eventListeners[t]||(this._eventListeners[t]=[]),this._eventListeners[t].push(e),()=>{const i=this._eventListeners[t].indexOf(e);i>=0&&this._eventListeners[t].splice(i,1)}}static _hasPlaced=!1;static get hasPlaced(){return this._hasPlaced}get arScale(){return this._arScale}set arScale(e){this._arScale=Math.max(1e-6,e),this.onSetScale()}_arScale=1;invertForward=!1;customReticle;arTouchTransform=!0;autoPlace=!1;autoCenter=!1;useXRAnchor=!1;_isPlacing=!0;_startOffset=new c.Matrix4;_createdPlacementObject=null;_reparentedComponents=[];_placementScene=new c.Scene;_reticle=[];_hits=[];_placementStartTime=-1;_rigPlacementMatrix;_anchor=null;userInput;onEnable(){this.customReticle?.preload()}supportsXR(e){return e==="immersive-ar"}onEnterXR(e){ab&&console.log("ENTER WEBXR: SessionRoot start..."),this._anchor=null,Bi._hasPlaced=!1,this.gameObject.updateMatrixWorld(),this._startOffset.copy(this.gameObject.matrixWorld);const t=new c.Object3D;this._createdPlacementObject=t,t.name="AR Session Root",this._placementScene.name="AR Placement Scene",this._placementScene.children.length=0;for(let i=this.context.scene.children.length-1;i>=0;i--){const n=this.context.scene.children[i];this._placementScene.add(n)}if(this.context.scene.add(t),this.autoCenter){const i=Wt(this._placementScene.children),n=i.getCenter(new c.Vector3),o=i.getSize(new c.Vector3),r=new c.Matrix4;r.makeTranslation(n.x,n.y-o.y*.5,n.z),this._startOffset.multiply(r)}this._reparentedComponents.length=0,this._reparentedComponents.push({comp:this,originalObject:this.gameObject}),S.addComponent(t,this);for(const i of this._reticle)gi(i);this._reticle.length=0,this._isPlacing=!0,this.context.input.addEventListener("pointerup",this.onPlaceScene,{queue:Jt.Early})}onLeaveXR(){this.context.input.removeEventListener("pointerup",this.onPlaceScene,{queue:Jt.Early}),this.onRevertSceneChanges(),this._anchor=null,Bi._hasPlaced=!1,this._rigPlacementMatrix=void 0}onUpdateXR(e){if(e.xr.isTrackingImages){for(const t of this._reticle)t.visible=!1;return}if(this._isPlacing){const t=e.xr.rig?.gameObject;t&&t.parent!==this.context.scene&&this.context.scene.add(t);let i=!1;if(e.xr.isPassThrough&&e.xr.controllers.length>0&&!this.autoPlace)for(const n of e.xr.controllers){const o=n.getHitTest();o&&(i=!0,this.updateReticleAndHits(e.xr,n.index,o,e.xr.rigScale))}if(!i){const n=e.xr.getHitTest();n&&this.updateReticleAndHits(e.xr,0,n,e.xr.rigScale)}}else{if(this._anchor&&e.xr.referenceSpace){const t=e.xr.frame.getPose(this._anchor.anchorSpace,e.xr.referenceSpace);if(t&&this.context.time.frame%20===0){const i=e.xr.convertSpace(t.transform),n=this._reticle[0];n&&(n.position.copy(i.position),n.quaternion.copy(i.quaternion),this.onApplyPose(n))}}if(this.arTouchTransform?(this.userInput||(this.userInput=new Qd(this.context)),this.userInput?.enable()):this.userInput?.disable(),this.arTouchTransform&&this.userInput?.hasChanged){if(e.xr.rig){const t=e.xr.rig.gameObject;this.userInput.applyMatrixTo(t.matrix,!0),t.matrix.decompose(t.position,t.quaternion,t.scale),this.userInput.factor=t.scale.x}this.userInput.reset()}}}updateReticleAndHits(e,t,i,n){this._hits[t]=i.hit;let o=this._reticle[t];if(!o){if(this.customReticle)if(this.customReticle.asset)o=oo(this.customReticle.asset);else{this.customReticle.loadAssetAsync();return}else o=new c.Mesh(new c.RingGeometry(.07,.09,32).rotateX(-Math.PI/2),new c.MeshBasicMaterial({side:c.DoubleSide,depthTest:!1,depthWrite:!1,transparent:!0,opacity:1,color:15658734})),o.name="AR Placement Reticle";if(ab){const r=new c.AxesHelper(1);r.position.y+=.01,o.add(r)}this._reticle[t]=o,o.matrixAutoUpdate=!1,o.visible=!1}if(o.lastPos=o.lastPos||i.position.clone(),o.lastQuat=o.lastQuat||i.quaternion.clone(),o.position.copy(o.lastPos.lerp(i.position,this.context.time.deltaTime/.1)),o.lastPos.copy(o.position),o.quaternion.copy(o.lastQuat.slerp(i.quaternion,this.context.time.deltaTime/.05)),o.lastQuat.copy(o.quaternion),o.scale.set(n,n,n),this.customReticle&&this.applyViewBasedTransform(o),o.updateMatrix(),o.visible=!0,o.parent!==this.context.scene&&this.context.scene.add(o),this._placementStartTime<0&&(this._placementStartTime=this.context.time.realtimeSinceStartup),this.autoPlace)if(this.upVec.set(0,1,0).applyQuaternion(o.quaternion),this.upVec.dot(B(0,1,0))>.9){let a=o["autoplace:timer"]||0;a>=1?(o.visible=!1,this.onPlaceScene(null)):(a+=this.context.time.deltaTime,o["autoplace:timer"]=a)}else o["autoplace:timer"]=0}onPlaceScene=e=>{if(this._isPlacing==!1||e?.used)return;let t=this._reticle[0];if(!t){console.warn("No reticle to place...");return}if(!t.visible&&!this.autoPlace){console.warn("Reticle is not visible (can not place)");return}if(G.active?.isTrackingImages){console.warn("Scene Placement is disabled while images are being tracked");return}let i=this._hits[0];if(e&&e.origin instanceof Lm){const n=this._reticle[e.origin.index];n&&(t=n,i=this._hits[e.origin.index])}if(e&&(e.stopImmediatePropagation(),e.stopPropagation(),e.use()),this._isPlacing=!1,this.context.input.removeEventListener("pointerup",this.onPlaceScene),this.onRevertSceneChanges(),t.position.copy(t.lastPos),t.quaternion.copy(t.lastQuat),this.onApplyPose(t),Bi._hasPlaced=!0,this.useXRAnchor&&this.onCreateAnchor(G.active,i),this.context.xr)for(const n of this.context.xr.controllers)n.cancelHitTestSource()};onSetScale(){if(!Bi._hasPlaced)return;const e=G.active?.rig?.gameObject;if(e){const t=G.active?.rigScale||1,i=1/this._arScale*t,n=new c.Matrix4().makeScale(i,i,i).invert();e.matrix.premultiply(n),e.matrix.decompose(e.position,e.quaternion,e.scale)}}onRevertSceneChanges(){for(const e of this._reticle)e&&(e.visible=!1,e?.removeFromParent());this._reticle.length=0;for(let e=this._placementScene.children.length-1;e>=0;e--){const t=this._placementScene.children[e];this.context.scene.add(t)}this._createdPlacementObject?.removeFromParent();for(const e of this._reparentedComponents)S.addComponent(e.originalObject,e.comp)}async onCreateAnchor(e,t){if(t.createAnchor===void 0){console.warn("Hit does not support creating an anchor",t),T()&&ue("Hit does not support creating an anchor");return}else{const i=await t.createAnchor(e.viewerPose.transform);e.running&&i&&(this._anchor=i)}}upVec=new c.Vector3(0,1,0);lookPoint=new c.Vector3;worldUpVec=new c.Vector3(0,1,0);applyViewBasedTransform(e){const t=this.context.mainCamera,i=e,n=t.worldPosition,o=i.worldPosition;this.upVec.set(0,1,0).applyQuaternion(e.quaternion);const r=t.worldPosition;r&&e.position.clone().sub(r).angleTo(this.upVec)<Math.PI/2&&this.upVec.negate();const a=this.upVec.angleTo(this.worldUpVec)*180/Math.PI,l=30;a>l&&a<180-l||a<-l&&a>-180+l?(this.lookPoint.copy(e.position).add(this.upVec),this.lookPoint.y=e.position.y,e.lookAt(this.lookPoint)):(n.y=o.y,e.lookAt(n))}onApplyPose(e){const t=G.active?.rig?.gameObject;if(!t){console.warn("No rig object to place");return}const i=t.parent||this.context.scene;this._rigPlacementMatrix?this._rigPlacementMatrix?.decompose(t.position,t.quaternion,t.scale):this._rigPlacementMatrix=t.matrix.clone(),this.applyViewBasedTransform(e),e.updateMatrix(),this.context.scene.add(e),e.attach(t),e.removeFromParent(),t.scale.set(this.arScale,this.arScale,this.arScale),t.position.multiplyScalar(this.arScale),t.updateMatrix(),this.invertForward&&t.matrix.premultiply(WO),t.matrix.premultiply(this._startOffset),t.matrix.decompose(t.position,t.quaternion,t.scale),i.add(t)}}class Qd{static up=new c.Vector3(0,1,0);static zero=new c.Vector3(0,0,0);static one=new c.Vector3(1,1,1);oneFingerDrag=!0;twoFingerRotate=!0;twoFingerScale=!0;factor=1;context;offset;plane;_scale=1;_hasChanged=!1;get scale(){return this._scale}constructor(e){this.context=e,this.offset=new c.Matrix4,this.plane=new c.Plane,this.plane.setFromNormalAndCoplanarPoint(Qd.up,Qd.zero)}_enabled=!1;reset(){this._scale=1,this.offset.identity(),this._hasChanged=!0}get hasChanged(){return this._hasChanged}applyMatrixTo(e,t){this._hasChanged=!1,t?(this.offset.invert(),e.premultiply(this.offset)):e.multiply(this.offset)}currentlyUsedPointerIds=new Set;currentlyUnusedPointerIds=new Set;get isActive(){return this.currentlyUsedPointerIds.size<=0&&this.currentlyUnusedPointerIds.size>0}enable(){this._enabled||(this._enabled=!0,this.context.input.addEventListener("pointerdown",this.onPointerDownEarly,{queue:Jt.Early}),this.context.input.addEventListener("pointerdown",this.onPointerDownLate,{queue:Jt.Late}),this.context.input.addEventListener("pointerup",this.onPointerUpEarly,{queue:Jt.Early}),window.addEventListener("touchstart",this.touchStart,{passive:!1}),window.addEventListener("touchmove",this.touchMove,{passive:!1}),window.addEventListener("touchend",this.touchEnd,{passive:!1}))}disable(){this._enabled&&(this._enabled=!1,this.context.input.removeEventListener("pointerdown",this.onPointerDownEarly,{queue:Jt.Early}),this.context.input.removeEventListener("pointerdown",this.onPointerDownLate,{queue:Jt.Late}),this.context.input.removeEventListener("pointerup",this.onPointerUpEarly,{queue:Jt.Early}),window.removeEventListener("touchstart",this.touchStart),window.removeEventListener("touchmove",this.touchMove),window.removeEventListener("touchend",this.touchEnd))}onPointerDownEarly=e=>{this.isActive&&e.stopPropagation()};onPointerDownLate=e=>{e.used?this.currentlyUsedPointerIds.add(e.pointerId):this.currentlyUsedPointerIds.size<=0&&this.currentlyUnusedPointerIds.add(e.pointerId)};onPointerUpEarly=e=>{this.currentlyUsedPointerIds.delete(e.pointerId),this.currentlyUnusedPointerIds.delete(e.pointerId)};prev=new Map;_didMultitouch=!1;touchStart=e=>{if(!e.defaultPrevented)for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t],n=exports.DeviceUtilities.isAndroidDevice()&&i.clientY<window.innerHeight*.1;this.prev.has(i.identifier)||this.prev.set(i.identifier,{ignore:n,x:0,z:0,screenx:0,screeny:0});const o=this.prev.get(i.identifier);if(o){const r=this.getPositionOnPlane(i.clientX,i.clientY);o.x=r.x,o.z=r.z,o.screenx=i.clientX,o.screeny=i.clientY}}};touchEnd=e=>{e.touches.length<=0&&(this._didMultitouch=!1);for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t];this.prev.delete(i.identifier)}};touchMove=e=>{if(!e.defaultPrevented&&this.isActive){if(e.touches.length===1){if(this._didMultitouch)return;const t=e.touches[0],i=this.prev.get(t.identifier);if(!i||i.ignore)return;const n=this.getPositionOnPlane(t.clientX,t.clientY),o=n.x-i.x,r=n.z-i.z;if(o===0&&r===0)return;this.oneFingerDrag&&this.addMovement(o,r),i.x=n.x,i.z=n.z,i.screenx=t.clientX,i.screeny=t.clientY;return}else if(e.touches.length===2){this._didMultitouch=!0;const t=e.touches[0],i=e.touches[1],n=this.prev.get(t.identifier),o=this.prev.get(i.identifier);if(!n||!o)return;if(this.twoFingerRotate){const r=Math.atan2(t.clientY-i.clientY,t.clientX-i.clientX),a=Math.atan2(n.screeny-o.screeny,n.screenx-o.screenx),l=r-a;Math.abs(l)>.001&&this.addRotation(l)}if(this.twoFingerScale){const r=t.clientX-i.clientX,a=t.clientY-i.clientY,l=Math.sqrt(r*r+a*a),h=n.screenx-o.screenx,d=n.screeny-o.screeny,u=Math.sqrt(h*h+d*d),p=l-u;Math.abs(p)>2&&this.addScale(p)}n.screenx=t.clientX,n.screeny=t.clientY,o.screenx=i.clientX,o.screeny=i.clientY}}};_raycaster=new c.Raycaster;_intersection=new c.Vector3;_screenPos=new c.Vector3;getPositionOnPlane(e,t){const i=this.context.mainCamera;return this._screenPos.x=e/window.innerWidth*2-1,this._screenPos.y=-(t/window.innerHeight)*2+1,this._screenPos.z=1,this._screenPos.unproject(i),this._raycaster.set(i.position,this._screenPos.sub(i.position)),this._raycaster.ray.intersectPlane(this.plane,this._intersection),this._intersection}addMovement(e,t){e/=this._scale,t/=this._scale,e*=this.factor,t*=this.factor,this.offset.elements[12]+=e,this.offset.elements[14]+=t,(e!==0||t!==0)&&(this._hasChanged=!0)}_tempMatrix=new c.Matrix4;addScale(e){e/=window.innerWidth,e*=-1,this._scale*=1+e,this._tempMatrix.makeScale(1-e,1-e,1-e),this.offset.premultiply(this._tempMatrix),e!==0&&(this._hasChanged=!0)}addRotation(e){e*=-1,this._tempMatrix.makeRotationY(e),this.offset.premultiply(this._tempMatrix),e!==0&&(this._hasChanged=!0)}}const Qs=x("debugautosync"),Kf=Symbol("syncerId");class HO{_syncers={};getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];const t=new GO(e);return t[Kf]=e.guid,this._syncers[t[Kf]]=t,t}removeSyncer(e){delete this._syncers[e[Kf]]}}const zg=new HO;class GO{comp;constructor(e){this.comp=e}hasChanges=!1;changedProperties={};get networkingKey(){return this.comp.guid}_isReceiving=!1;_isInit=!1;init(e){if(this._isInit)return;this._isInit=!0,this.comp=e,this.comp.context.post_render_callbacks.push(this.onHandleSending),this.comp.context.connection.beginListen(this.networkingKey,this.onHandleReceiving);const t=this.comp.context.connection.tryGetState(this.comp.guid);t&&this.onHandleReceiving(t)}destroy(){this._isInit&&(this.comp.context.post_render_callbacks.splice(this.comp.context.post_render_callbacks.indexOf(this.onHandleSending),1),this.comp.context.connection.stopListen(this.networkingKey,this.onHandleReceiving),this.comp=null,this._isInit=!1)}notifyChanged(e,t){this._isReceiving||(Qs&&console.log("Property changed: "+e,t),this.hasChanges=!0,this.changedProperties[e]=t)}onHandleSending=()=>{if(!this.hasChanges)return;this.hasChanges=!1;const e=this.comp.context.connection;if(!e||!e.isConnected||!e.isInRoom){for(const t in this.changedProperties)delete this.changedProperties[t];return}for(const t in this.changedProperties){const i=this.changedProperties[t];Qs&&console.log("SEND",this.comp.guid,this.networkingKey),e.send(this.networkingKey,{guid:this.comp.guid,property:t,data:i},sn.Queued),delete this.changedProperties[t]}};onHandleReceiving=e=>{if(Qs&&console.log("SYNCFIELD RECEIVE",this.comp.name,this.comp.guid,e),!!this._isInit&&this.comp&&e.guid===this.comp.guid)try{this._isReceiving=!0,this.comp[e.property]=e.data}catch(t){console.error(t)}finally{this._isReceiving=!1}}}function qO(s,e){let t=e!==s;return!t&&s&&e&&(Array.isArray(s)&&Array.isArray(e)||typeof s=="object"&&typeof e=="object")&&(t=!0),t}const sc=Symbol("AutoSyncHandler");function XO(s){if(s[sc])return s[sc];const e=zg.getOrCreateSyncer(s);return e?.init(s),s[sc]=e,e}function QO(s){const e=s[sc];e&&(zg.removeSyncer(e),e.destroy(),delete s[sc])}const Ng=function(s=null){return function(e,t){let i="";typeof t=="string"?i=t:i=t.name;let n=null,o;typeof s=="string"?o=e[s]:typeof s=="function"&&(o=s),o==null&&(T()||Qs)&&s!=null&&console.warn('syncField: no callback function found for property "'+i+'"','"'+s+'"');const r=e,a=r.__internalAwake;if(typeof a!="function"){(Qs||T())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+e?.constructor?.name+'" is not supported',e);return}Qs&&console.log(i);const l=Symbol(i);r.__internalAwake=function(){if(this[l]!==void 0)return;if(this[l]=this[i],n=zg.getOrCreateSyncer(this),Object.getOwnPropertyDescriptor(this,i)?.set===void 0){let u=!1;Object.defineProperty(this,i,{set:function(p){const m=this[l];if(this[l]=p,u){(T()||Qs)&&console.warn("Recursive call detected",i);return}u=!0;try{const g=qO(p,m);Qs&&console.log("SyncField assignment",i,"changed?",g,p,o),g&&o?.call(this,p,m)!==!1&&XO(this)?.notifyChanged(i,p)}finally{u=!1}},get:function(){return this[l]},configurable:!0,enumerable:!0})}n?.init(this),a.call(this)};const h=r.__internalDestroy;r.__internalDestroy=function(){QO(this),h.call(this)}}};var YO=Object.defineProperty,Eu=(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&&YO(e,t,n),n};const Ft=x("debugplayersync"),Ru=class Aw extends E{static async setupFrom(e,t){const i=K.getOrCreateFromUrl(e);if(!i.asset){const r=await i.loadAssetAsync();r&&S.getOrAddComponent(r,Ui)}const n=new Aw;n._internalInit(t),n.asset=i;const o=new c.Object3D;return o.guid=e,S.addComponent(o,n),n}autoSync=!0;asset;onPlayerSpawned;_localInstance;awake(){this.watchTabVisible(),this.onPlayerSpawned||(this.onPlayerSpawned=new oe)}onEnable(){this.context.connection.beginListen(Y.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(Y.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Y.LeftRoom,this.destroyInstance),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(Y.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(Y.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Y.LeftRoom,this.destroyInstance)}onJoinedRoom=()=>{Ft&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()};async getInstance(){if(this._localInstance)return this._localInstance;if(Ft&&console.log("PlayerSync.createInstance",this.asset?.url),!this.asset?.asset&&!this.asset?.url)return console.error('PlayerSync: can not create an instance because "asset" is not set and or has no URL!'),null;this.gameObject.guid||console.warn("PlayerSync: gameObject has no guid! This might cause issues with syncing the player state."),this._localInstance=this.asset?.instantiateSynced({parent:this.gameObject,deleteOnDisconnect:!0},!0);const e=await this._localInstance;if(e){const t=S.getComponentsInChildren(e,Ui);if(Ft&&console.log(`PlayerSync.createInstance: found ${t?.length} PlayerState components. Owner: ${this.context.connection.connectionId}`),t?.length){for(const i of t)i.owner=this.context.connection.connectionId;this.onPlayerSpawned?.invoke(e)}else this._localInstance=void 0,console.error("<strong>Failed finding PlayerState on "+this.asset?.url+"</strong>: please make sure the asset has a PlayerState component!"),S.destroySynced(e)}else this._localInstance=void 0,console.warn("PlayerSync: failed instantiating asset!");return this._localInstance}destroyInstance=()=>{this._localInstance?.then(e=>{Ft&&console.log("PlayerSync.destroyInstance",e),Bc(e,this.context.connection,!0,{saveInRoom:!1})}),this._localInstance=void 0};watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=Ui.all.length-1;t>=0;t--){const i=Ui.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}};Eu([f()],Ru.prototype,"autoSync");Eu([f(K)],Ru.prototype,"asset");Eu([f(oe)],Ru.prototype,"onPlayerSpawned");let Vg=Ru;var Dw=(s=>(s.OwnerChanged="ownerChanged",s))(Dw||{});const nm=class pt extends E{static _all=[];static get all(){return pt._all}static _local=[];static get local(){return pt._local}static getFor(e){if(e instanceof c.Object3D)return S.getComponentInParent(e,pt);if(e instanceof E)return S.getComponentInParent(e.gameObject,pt)}static isLocalPlayer(e){return pt.getFor(e)?.isLocalPlayer??!1}static _callbacks={};static addEventListener(e,t){return this._callbacks[e]||(this._callbacks[e]=[]),this._callbacks[e].push(t),t}static removeEventListener(e,t){if(!this._callbacks[e])return;const i=this._callbacks[e].indexOf(t);i>=0&&this._callbacks[e].splice(i,1)}static dispatchEvent(e,t){if(this._callbacks[e])for(const i of this._callbacks[e])i(t)}onOwnerChangeEvent=new oe;onFirstOwnerChangeEvent=new oe;hasOwner=!1;owner;dontDestroy=!1;get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(e,t){Ft&&console.log(`PlayerSync.onOwnerChange: ${t} → ${e} (me: ${this.context.connection.connectionId})`);const i=pt._local.indexOf(this);i>=0&&pt._local.splice(i,1);const n={playerState:this,oldValue:t,newValue:e};if(this.hasOwner||(this.hasOwner=!0,this.onFirstOwnerChangeEvent?.invoke(n)),this.onOwnerChangeEvent?.invoke(n),this.owner===this.context.connection.connectionId){pt._local.push(this);const r=new CustomEvent("local-owner-changed",{detail:n});this.dispatchEvent(r)}const o=new CustomEvent("owner-changed",{detail:n});this.dispatchEvent(o),pt.dispatchEvent("ownerChanged",o)}awake(){pt.all.push(this),Ft&&console.log("Registered new PlayerState",this.guid,pt.all.length-1,pt.all),this.context.connection.beginListen(Y.UserLeftRoom,this.onUserLeftRoom)}async start(){Ft&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await fs(300),this.context.connection.userIsInRoom(this.owner)==!1&&(Ft&&console.log(`PlayerSync.start → doDestroy "${this.name}" because user "${this.owner}" is not in room anymore...`,"Currently in room:",...this.context.connection.usersInRoom()),this.doDestroy())):this.owner||(Ft&&console.warn("PlayerState.start → owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?Ft&&console.warn("PlayerState.start → owner is still undefined but dontDestroy is set to true",this.name):(Ft&&console.warn(`PlayerState.start → owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):Ft&&console.log("PlayerState.start → owner is assigned",this.owner)},2e3))}doDestroy(){Ft&&console.log("PlayerSync.doDestroy → syncDestroy",this.name),Bc(this.gameObject,this.context.connection,!0,{saveInRoom:!1})}onDestroy(){if(Ft&&console.warn("PlayerState.onDestroy",this.owner),this.context.connection.stopListen(Y.UserLeftRoom,this.onUserLeftRoom),pt.all.splice(pt.all.indexOf(this),1),this.isLocalPlayer){const e=pt._local.indexOf(this);e>=0&&pt._local.splice(e,1)}}onUserLeftRoom=e=>{if(e.userId===this.owner){Ft&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}}};Eu([Ng(nm.prototype.onOwnerChange)],nm.prototype,"owner");let Ui=nm;var KO=Object.defineProperty,Ga=(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&&KO(e,t,n),n};class Hn extends E{position="bottom";showNeedleLogo=!1;showSpatialMenu;createFullscreenButton;createMuteButton;createQRCodeButton;onEnable(){this.applyOptions()}applyOptions(){this.context.menu.setPosition(this.position),this.context.menu.showNeedleLogo(this.showNeedleLogo),this.createFullscreenButton===!0&&this.context.menu.showFullscreenOption(!0),this.createMuteButton===!0&&this.context.menu.showAudioPlaybackOption(!0),this.showSpatialMenu===!0&&this.context.menu.showSpatialMenu(this.showSpatialMenu),this.createQRCodeButton===!0&&(exports.DeviceUtilities.isMobileDevice()||this.context.menu.showQRCodeButton(!0))}}Ga([f()],Hn.prototype,"position");Ga([f()],Hn.prototype,"showNeedleLogo");Ga([f()],Hn.prototype,"showSpatialMenu");Ga([f()],Hn.prototype,"createFullscreenButton");Ga([f()],Hn.prototype,"createMuteButton");Ga([f()],Hn.prototype,"createQRCodeButton");var ZO=Object.defineProperty,$g=(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&&ZO(e,t,n),n};const _l=x("debugwebxr"),lb=new c.Quaternion().setFromAxisAngle(new c.Vector3(0,1,0),Math.PI);class ao extends E{head;leftHand;rightHand;_leftHandMeshes;_rightHandMeshes;_syncTransforms;async onEnterXR(e){if(!this.activeAndEnabled)return;_l&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const t=Ui.getFor(this);if(t?.owner){const i=this.gameObject.addComponent(Pe);i.avatar=this.gameObject,i.connectionId=t.owner,this.context.players.setPlayerView(t.owner,this.head?.asset,us.Headset)}else this.context.connection.isConnected?console.error("No player state found for avatar",this):t&&!this.context.connection.isConnected&&(t.dontDestroy=!0)}onLeaveXR(e){const t=this.gameObject.getComponent(Pe);t&&t.destroy()}onUpdateXR(e){if(!this.activeAndEnabled)return;const t=Ui.isLocalPlayer(this);if(!t)return;const i=e.xr;if(i.rig&&i.rig.gameObject!==this.gameObject.parent&&(this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),this.gameObject.scale.set(1,1,1),i.rig.gameObject.add(this.gameObject)),this._syncTransforms&&t)for(const l of this._syncTransforms)l.fastMode=!0,l.isOwned()||l.requestOwnership();if(this.head&&this.context.mainCamera){const l=this.head.asset;if(l.position.copy(this.context.mainCamera.position),l.position.x*=-1,l.position.z*=-1,l.quaternion.copy(this.context.mainCamera.quaternion),l.quaternion.x*=-1,this.context.time.frameCount%10===0&&this.head.asset){const h=S.getComponentsInChildren(this.head.asset,Li);for(const d of h)d.enabled=!1,d.gameObject.visible=!1}}const n=e.xr.leftController,o=this.leftHand?.asset;n&&o?(o.position.copy(n.gripPosition),o.quaternion.copy(n.gripQuaternion),o.quaternion.multiply(lb),o.visible=n.isTracking,this.updateHandVisibility(n,o,this._leftHandMeshes)):o&&o.visible&&(o.visible=!1);const r=e.xr.rightController,a=this.rightHand?.asset;r&&a?(a.position.copy(r.gripPosition),a.quaternion.copy(r.gripQuaternion),a.quaternion.multiply(lb),a.visible=r.isTracking,this.updateHandVisibility(r,a,this._rightHandMeshes)):a&&a.visible&&(a.visible=!1)}onBeforeRender(){this.context.xr&&this.context.time.frame%10===0&&this.updateRemoteAvatarVisibility()}updateHandVisibility(e,t,i){if(i){const n=e.model&&e.model.visible&&e.model!==t;i.forEach(o=>{ss(o,!n)})}}updateRemoteAvatarVisibility(){if(this.context.connection.isConnected){const e=Ui.getFor(this);if(e&&e.isLocalPlayer==!1){const t=G.getXRSync(this.context);if(t&&t.hasState(e.owner)){this.tryFindAvatarObjectsIfMissing();const i=this.leftHand?.asset;i&&(i.visible=t?.isTracking(e.owner,"left")??!1);const n=this.rightHand?.asset;n&&(n.visible=t?.isTracking(e.owner,"right")??!1)}if(this.head?.asset){const i=S.getComponentsInChildren(this.head.asset,Li);for(const n of i)n.enabled=!1,n.gameObject.visible=!0}}}}tryFindAvatarObjectsIfMissing(){if(!this.head||!this.leftHand||!this.rightHand){const e={head:this.head,leftHand:this.leftHand,rightHand:this.rightHand};Ev.tryFindAvatarObjects(this.gameObject,this.sourceId||"",e),e.head&&(this.head=e.head),e.leftHand&&(this.leftHand=e.leftHand),e.rightHand&&(this.rightHand=e.rightHand)}}async prepareAvatar(){if(this.tryFindAvatarObjectsIfMissing(),this.head)this.head instanceof c.Object3D&&(this.head=new K("",this.sourceId,this.head));else{const e=new c.Object3D;e.name="Head";const t=po.createPrimitive(ja.Cube);e.add(t),this.gameObject.add(e),this.head=new K("",this.sourceId,e),_l&&console.log("Create head",e)}if(this.rightHand)this.rightHand instanceof c.Object3D&&(this.rightHand=new K("",this.sourceId,this.rightHand));else{const e=new c.Object3D;e.name="Right Hand",this.gameObject.add(e),this.rightHand=new K("",this.sourceId,e),_l&&console.log("Create right hand",e)}if(this.leftHand)this.leftHand instanceof c.Object3D&&(this.leftHand=new K("",this.sourceId,this.leftHand));else{const e=new c.Object3D;e.name="Left Hand",this.gameObject.add(e),this.leftHand=new K("",this.sourceId,e),_l&&console.log("Create left hand",e)}await this.loadAvatarObjects(this.head,this.leftHand,this.rightHand),this._leftHandMeshes=[],this.leftHand.asset?.traverse(e=>{e?.isMesh&&this._leftHandMeshes.push(e)}),this._rightHandMeshes=[],this.rightHand.asset?.traverse(e=>{e?.isMesh&&this._rightHandMeshes.push(e)}),Ui.isLocalPlayer(this.gameObject)&&(this._syncTransforms=S.getComponentsInChildren(this.gameObject,dn))}async loadAvatarObjects(e,t,i){const n=e.loadAssetAsync(),o=t.loadAssetAsync(),r=i.loadAssetAsync(),a=new Array;n&&a.push(n),o&&a.push(o),r&&a.push(r);const l=await wm(a);_l&&console.log("Avatar loaded results:",l)}}$g([f(K)],ao.prototype,"head");$g([f(K)],ao.prototype,"leftHand");$g([f(K)],ao.prototype,"rightHand");var JO=Object.defineProperty,Tu=(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&&JO(e,t,n),n};const js=x("debugwebxr"),Bs=new Array;class ms extends E{createControllerModel=!0;createHandModel=!0;customLeftHand;customRightHand;static factory=new q.XRControllerModelFactory;supportsXR(e){return e==="immersive-vr"||e==="immersive-ar"}_models=new Array;async onXRControllerAdded(e){if(!(e.xr.isVR||e.xr.isPassThrough))return;console.debug("XR Controller Added",e.controller.side,e.controller.index);const{controller:i}=e;if(this.createControllerModel||this.createHandModel){if(i.hand){if(this.createHandModel){const n=await this.loadHandModel(this,i);if(!n||!i.connected||!i.isHand){n?.handObject&&Jr(n.handObject,!1),n?.handObject?.destroy();return}this._models.push({controller:i,model:n.handObject,handmesh:n.handmesh}),this._models.sort((o,r)=>o.controller.index-r.controller.index),this.scene.add(n.handObject),i.model=n.handObject}}else if(this.createControllerModel){const n=await i.getModelUrl();if(n){const o=await this.loadModel(i,n);if(!o||!i.connected||i.isHand)return;this._models.push({controller:i,model:o}),this._models.sort((r,a)=>r.controller.index-a.controller.index),this.scene.add(o),o.traverse(r=>{r.layers.set(2),r.matrixAutoUpdate=!1,r.updateMatrix()}),i.model=o}else i.targetRayMode!=="transient-pointer"&&console.warn("XRControllerModel: no model found for "+i.side)}}}onXRControllerRemoved(e){console.debug("XR Controller Removed",e.controller.side,e.controller.index);const t=this._models.findIndex(n=>n.controller===e.controller),i=this._models[t];i&&(this._models.splice(t,1),i.model&&(Jr(i.model,!1),i.model.destroy(),i.model=void 0))}onBeforeXR(e,t){this.createHandModel&&(this.customLeftHand||this.customRightHand)&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.includes("hand-tracking")||t.optionalFeatures.push("hand-tracking"))}onLeaveXR(e){for(const t of this._models)t&&(t.model&&(Jr(t.model,!1),t.model.destroy(),t.model=void 0),t.controller.model===t.model&&(t.controller.model=null));this._models.length=0}onBeforeRender(){if(G.active&&(js&&(Bs[0]=Date.now()),this.updateRendering(G.active),js)){const e=Date.now()-Bs[0];Bs.push(e),Bs.length>=30&&(Bs[0]=0,Bs.reduce((t,i)=>t+i,0)/Bs.length,Bs.length=0)}}updateRendering(e){for(let t=0;t<this._models.length;t++){const i=this._models[t];if(!i)continue;const n=i.controller;if(!n.connected){js&&console.warn("XRControllerModel.onUpdateXR: controller is not connected anymore",n.side,n.hand);continue}if(i.model&&!i.handmesh)i.model.matrixAutoUpdate=!1,i.model.matrix.copy(n.gripMatrix),i.model.visible=n.isTracking,e.rig?.gameObject.add(i.model);else if(n.inputSource.hand&&i.handmesh){const o=e.referenceSpace,r=this.context.renderer.xr.getHand(n.index);if(o&&e.frame.getJointPose){for(const a of n.inputSource.hand.values()){const l=r.joints[a.jointName];if(l){const h=n.getHandJointPose(a);if(h){const d=h.transform.position,u=h.transform.orientation;l.position.copy(d),l.quaternion.copy(u),l.matrixAutoUpdate=!1}l.visible=h!=null}}i.model&&(i.model.visible=n.isTracking,i.model.visible&&i.model.parent!==e.rig?.gameObject&&e.rig?.gameObject.add(i.model)),i.model?.visible&&(i.handmesh?.updateMesh(),i.model.matrixAutoUpdate=!1,i.model.matrix.identity(),i.model.applyMatrix4(pa))}}}}async loadModel(e,t){if(!e.connected)return console.warn("XRControllerModel.onXRControllerAdded: controller is not connected anymore",e.side),null;const n=await K.getOrCreate("",t).instantiate();return Jr(n),G.active?.isPassThrough&&n.traverseVisible(o=>{this.makeOccluder(o)}),n}async loadHandModel(e,t){const i=this.context,n=i.renderer.xr.getHand(t.index);n||(js?j.DrawLabel(t.rayWorldPosition,"No hand found for index "+t.index,.05,5):console.warn("No hand found for index "+t.index));const o=new q.GLTFLoader;ng(o,i),await qd(o,i,this.sourceId??"",this.sourceId??"");const r=wg(o);let a="";const l=t.side==="left"?this.customLeftHand:this.customRightHand;l?(a=l.url.split(".").slice(0,-1).join("."),o.setPath("")):(a=t.inputSource.handedness==="left"?"left":"right",o.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/"));const h=new c.Object3D;Jr(h);const d=new q.XRHandMeshModel(h,n,o.path,a,o,u=>{const p=r?.gltf;p?.scene.children?.length===0&&(p.scene.children[0]=u),r?.gltf&&cn().createBuiltinComponents(e.context,e.sourceId||a,r.gltf,null,r),u.traverse(m=>{m.layers.set(2),G.active?.isPassThrough&&!l&&this.makeOccluder(m),m instanceof c.Mesh&&se.NEEDLE_progressive.assignMeshLOD(m,0)}),t.connected||(js&&j.DrawLabel(t.rayWorldPosition,"Hand is loaded but not connected anymore",.05,5),u.removeFromParent())});if(js&&h.add(new c.AxesHelper(.5)),t.inputSource.hand){js&&console.log(t.inputSource.hand);for(const u of t.inputSource.hand.values())if(n.joints[u.jointName]===void 0){const p=new c.Group;p.matrixAutoUpdate=!1,p.visible=!0,n.joints[u.jointName]=p,n.add(p)}}else js&&j.DrawLabel(t.rayWorldPosition,"No inputSource.hand found for index "+t.index,.05,5);return{handObject:h,handmesh:d}}makeOccluder(e){if(e instanceof c.Mesh){let t=e.material;t instanceof c.Material&&(t=e.material=t.clone(),t.depthWrite=!0,t.depthTest=!0,t.colorWrite=!1,e.receiveShadow=!1,e.renderOrder=-100)}}}Tu([f()],ms.prototype,"createControllerModel");Tu([f()],ms.prototype,"createHandModel");Tu([f(K)],ms.prototype,"customLeftHand");Tu([f(K)],ms.prototype,"customRightHand");class Au extends E{}var ek=Object.defineProperty,bo=(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&&ek(e,t,n),n};const Zf=x("debugwebxr");class vi extends E{movementSpeed=1.5;rotationStep=30;useTeleport=!0;usePinchToTeleport=!0;useTeleportTarget=!1;useTeleportFade=!1;showRays=!0;showHits=!0;isXRMovementHandler=!0;xrSessionMode="immersive-vr";_didApplyRotation=!1;_didTeleport=!1;onUpdateXR(e){const t=e.xr.rig;if(!t?.gameObject||e.xr.isPassThrough)return;const i=e.xr.leftController,n=e.xr.rightController;i&&this.onHandleMovement(i,t.gameObject),n&&(this.onHandleRotation(n,t.gameObject),this.useTeleport&&this.onHandleTeleport(n,t.gameObject))}onLeaveXR(e){for(const t of this._lines)t.removeFromParent();for(const t of this._hitDiscs)t?.removeFromParent()}onBeforeRender(){this.context.xr?.running&&(this.showRays&&this.renderRays(this.context.xr),this.showHits&&this.renderHits(this.context.xr))}onHandleMovement(e,t){const i=e.getStick("xr-standard-thumbstick");if(i.x!=0||i.y!=0){const n=B(i.x,0,i.y);n.multiplyScalar(this.context.time.deltaTimeUnscaled*this.movementSpeed);const o=Le(t);n.multiplyScalar(o.x),n.applyQuaternion(e.xr.poseOrientation),n.y=0,n.applyQuaternion(t.worldQuaternion),T()&&Number.isNaN(n.x)&&console.error("Stick movement resulted in NaN",{stick:i,vec:n}),t.position.add(n),t.updateWorldMatrix(!1,!1);for(const r of t.children)r.updateWorldMatrix(!1,!1)}}onHandleRotation(e,t){if(e._isMxInk)return;const n=e.getStick("xr-standard-thumbstick").x;if(this._didApplyRotation)Math.abs(n)<.3&&(this._didApplyRotation=!1);else if(Math.abs(n)>.5){this._didApplyRotation=!0;const o=n>0?1:-1,r=Q(this.context.mainCamera).clone();t.rotateY(o*I.toRadians(this.rotationStep));const l=Q(this.context.mainCamera).clone().sub(r);l.y=0,t.position.sub(l)}}_teleportBuffer=new Array;onHandleTeleport(e,t){let i=0;if(e.hand&&this.usePinchToTeleport&&e.isTeleportGesture){const n=e.getPointerId("primary");if(n!=null&&this.context.input.getIsPointerIdInUse(n))return;const o=e.getGesture("pinch");o&&(i=o.value)}else i=e.getStick("xr-standard-thumbstick")?.y;if(this._didTeleport)i>=0&&i<.4?this._didTeleport=!1:i<0&&i>-.4&&(this._didTeleport=!1);else if(i>.8){this._didTeleport=!0;const n=this.context.physics.raycastFromRay(e.ray)[0];if(n&&n.object instanceof q.GroundedSkybox){const r=n.normal?.dot(B(0,1,0));if(r!==void 0&&r<.4)return}let o=n?.point;if(!o&&!this.useTeleportTarget){this._plane||(this._plane=new c.Plane(new c.Vector3(0,1,0),0));const r=t.worldPosition;this._plane.setFromNormalAndCoplanarPoint(new c.Vector3(0,1,0),r);const a=e.ray;o=r.clone(),this._plane.intersectLine(new c.Line3(a.origin,B(a.direction).multiplyScalar(1e4).add(a.origin)),o),o.distanceTo(r)>t.scale.x*10&&(o=null)}if(o){if(this.useTeleportTarget&&!S.getComponentInParent(n.object,Au))return;const r=o.clone();if(Zf&&j.DrawSphere(o,.025,16711680,5),this.context.mainCamera?.position){const l=this.context.xr?.getUserOffsetInRig();l&&(l.y=0,r.sub(l),Zf&&j.DrawWireSphere(l.add(r),.025,65280,5))}this._teleportBuffer.push(t.matrix.clone()),this._teleportBuffer.length>10&&this._teleportBuffer.shift(),this.useTeleportFade?e.xr.fadeTransition()?.then(()=>{t.worldPosition=r}):t.worldPosition=r}}else if(i<-.8&&(this._didTeleport=!0,this._teleportBuffer.length>0)){const n=this._teleportBuffer.pop();n&&n.decompose(t.position,t.quaternion,t.scale)}}_plane=null;_lines=[];_hitDiscs=[];_hitDistances=[];_lastHitDistances=[];renderRays(e){for(let t=0;t<this._lines.length;t++){const i=this._lines[t];i&&(i.visible=!1)}for(let t=0;t<e.controllers.length;t++){const i=e.controllers[t];let n=this._lines[t];if(!i.connected||!i.isTracking||!i.ray||i.targetRayMode==="transient-pointer"||!i.hasSelectEvent){n&&(n.visible=!1);continue}n||(n=this.createRayLineObject(),n.scale.z=.5,this._lines[t]=n),i.updateRayWorldPosition(),i.updateRayWorldQuaternion();const o=i.rayWorldPosition,r=i.rayWorldQuaternion;n.position.copy(o),n.quaternion.copy(r);const a=e.rigScale,l=this.usePinchToTeleport&&i.isTeleportGesture,h=this._lastHitDistances[t],d=this._hitDistances[t]!=null,u=h??a;n.scale.set(a,a,u),n.visible=!0,n.layers.disableAll(),n.layers.enable(2);let p=n.material.opacity;l?p=1:this.showHits&&u<e.rigScale*.5?p=0:i.getButton("primary")?.pressed?p=.5:p=d?.2:.1,n.material.opacity=I.lerp(n.material.opacity,p,this.context.time.deltaTimeUnscaled/.1),n.parent!==this.context.scene&&this.context.scene.add(n)}}renderHits(e){for(const t of this._hitDiscs){if(!t)continue;const i=t.controller;if(!i||!i.connected||!i.isTracking){t.visible=!1;continue}}for(let t=0;t<e.controllers.length;t++){const i=e.controllers[t];if(!i.connected||!i.isTracking||!i.ray||!i.hasSelectEvent)continue;let n=this._hitDiscs[t],o=!0;const r=i.getPointerId("primary");r!=null&&this.context.input.getIsPointerIdInUse(r)&&(n&&(n.visible=!1),this._hitDistances[t]=null,this._lastHitDistances[t]=0,o=!1);const a=this.context.time.smoothedFps>=59?1:10;if((this.context.time.frame+i.index)%a!==0&&(o=!1),!o){const d=this._hitDiscs[t];d&&d.visible&&d.hit&&this.updateHitPointerPosition(i,d,d.hit.distance);continue}const l=this.context.physics.raycastFromRay(i.ray,{testObject:this.hitPointRaycastFilter,precise:!1});let h=l.find(d=>this.usePinchToTeleport&&i.isTeleportGesture?!0:this.isObjectWithInteractiveComponent(d.object));if(h||(h=l[0]),n&&(n.controller=i,n.hit=h),this._hitDistances[t]=h?.distance||null,h){this._lastHitDistances[t]=h.distance;const d=e.rigScale??1;Zf&&(j.DrawWireSphere(h.point,.025*d,16711680),j.DrawLabel(B(0,.2,0).add(h.point),h.object.name,.02,0)),n||(n=this.createHitPointObject(),this._hitDiscs[t]=n),n.hit=h,n.visible=h.distance>d*.05;let u=.01*(d+h.distance);const p=i.getButton("primary")?.pressed;p&&(u*=1.1),n.scale.set(u,u,u),n.layers.set(2);let m=n.material.opacity;if(p?m=1:m=h.distance<.15*d?.2:.6,n.material.opacity=I.lerp(n.material.opacity,m,this.context.time.deltaTimeUnscaled/.1),n.visible){if(h.normal){this.updateHitPointerPosition(i,n,h.distance);const g=h.normal.applyQuaternion(fe(h.object));n.quaternion.setFromUnitVectors(tk,g)}else this.updateHitPointerPosition(i,n,h.distance);n.parent!==this.context.scene&&this.context.scene.add(n)}}else this._hitDiscs[t]&&(this._hitDiscs[t].visible=!1)}}isObjectWithInteractiveComponent(e,t=0){return Vd(e)||e.isUI===!0?!0:e.isScene?!1:e.parent?this.isObjectWithInteractiveComponent(e.parent,t+1):!1}updateHitPointerPosition(e,t,i){const n=B(e.rayWorldPosition);n.add(B(0,0,i-.01).applyQuaternion(e.rayWorldQuaternion)),t.position.lerp(n,this.context.time.deltaTimeUnscaled/.05)}hitPointRaycastFilter=e=>e.type==="SkinnedMesh"?"continue in children":!0;createHitPointObject(){const e=new c.Mesh(new c.SphereGeometry(.3,6,6),new c.MeshBasicMaterial({color:15658734,opacity:.7,transparent:!0,depthTest:!1,depthWrite:!1,side:c.DoubleSide}));return e.layers.disableAll(),e.layers.enable(2),e}createRayLineObject(){const e=new q.Line2;e.layers.disableAll(),e.layers.enable(2);const t=new q.LineGeometry;e.geometry=t;const i=new Float32Array(9);i.set([0,0,.02,0,0,.4,0,0,1]),t.setPositions(i);const n=new Float32Array(9);n.set([1,1,1,.1,.1,.1,0,0,0]),t.setColors(n);const o=new q.LineMaterial({color:16777215,vertexColors:!0,worldUnits:!0,linewidth:.004,transparent:!0,depthWrite:!1,blending:c.AdditiveBlending,dashed:!1});return e.material=o,e}}bo([f()],vi.prototype,"movementSpeed");bo([f()],vi.prototype,"rotationStep");bo([f()],vi.prototype,"useTeleport");bo([f()],vi.prototype,"usePinchToTeleport");bo([f()],vi.prototype,"useTeleportTarget");bo([f()],vi.prototype,"useTeleportFade");bo([f()],vi.prototype,"showRays");bo([f()],vi.prototype,"showHits");const tk=new c.Vector3(0,1,0);var ik=Object.defineProperty,ct=(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&&ik(e,t,n),n};const bl=x("debugwebxr"),nk=x("debugusdz"),Je=class oa extends E{createVRButton=!0;createARButton=!0;createSendToQuestButton=!0;createQRCode=!0;useDefaultControls=!0;showControllerModels=!0;showHandModels=!0;usePlacementReticle=!0;customARPlacementReticle;usePlacementAdjustment=!0;arScale=1;useXRAnchor=!1;autoPlace=!1;autoCenter=!1;useQuicklookExport=!1;useDepthSensing=!1;useSpatialGrab=!0;defaultAvatar;_playerSync;_createdComponentsInSession=[];_usdzExporter;static activeWebXRComponent=null;awake(){G.getXRSync(this.context)}onEnable(){window.location.protocol!=="https:"&&ue('<a href="https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API" target="_blank">WebXR</a> only works on secure connections (https).'),navigator.xr?.isSessionSupported("immersive-ar").catch(()=>!1).then(e=>{const t=exports.DeviceUtilities.isVisionOS()&&!e;(this.useQuicklookExport||t)&&(S.findObjectOfType(an)||(bl&&console.log("WebXR: Adding USDZExporter"),this._usdzExporter=S.addComponent(this.gameObject,an),this._usdzExporter.objectToExport=this.context.scene,this._usdzExporter.autoExportAnimations=!0,this._usdzExporter.autoExportAudioSources=!0))}),this.handleCreatingHTML(),this.handleOfferSession(),this.defaultAvatar===!0&&(bl&&console.warn("WebXR: No default avatar set, using static default avatar"),this.defaultAvatar=new K("https://cdn.needle.tools/static/avatars/DefaultAvatar.glb")),this.defaultAvatar&&(this._playerSync=this.gameObject.getOrAddComponent(Vg),this._playerSync.autoSync=!1),this._playerSync&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,this._playerSync.onPlayerSpawned?.removeEventListener(this.onAvatarSpawned),this._playerSync.onPlayerSpawned?.addEventListener(this.onAvatarSpawned))}onDisable(){this._usdzExporter?.destroy(),this.removeButtons()}async handleOfferSession(){return this.createVRButton&&await G.isVRSupported()&&this.createVRButton?G.offerSession("immersive-vr","default",this.context):this.createARButton&&await G.isARSupported()&&this.createARButton?G.offerSession("immersive-ar","default",this.context):!1}get session(){return G.active??null}get sessionMode(){return G.activeMode??null}get arSessionRoot(){return this._activeWebARSessionRoot}async enterVR(e){return G.start("immersive-vr",e,this.context)}async enterAR(e){return G.start("immersive-ar",e,this.context)}exitXR(){G.stop()}_exitXRMenuButton;_previousXRState=0;_spatialGrabRaycaster;_activeWebARSessionRoot=null;get isActiveWebXR(){return!oa.activeWebXRComponent||oa.activeWebXRComponent===this}onBeforeXR(e,t){if(!this.isActiveWebXR){console.warn(`WebXR: another WebXR component is already active (${oa.activeWebXRComponent?.name}). This is ignored: ${this.name}`);return}if(this.activeAndEnabled===!1||this.destroyed){console.debug("[WebXR] onBeforeXR called on disabled or destroyed component");return}oa.activeWebXRComponent=this,e=="immersive-ar"&&this.useDepthSensing&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("depth-sensing"))}async onEnterXR(e){if(!this.isActiveWebXR)return;bl&&console.log("WebXR onEnterXR"),this._previousXRState=Vt.Global.Mask;const t=e.xr.isVR;if(Vt.Global.Set(t?Tn.VR:Tn.AR),e.xr.isAR){let i=S.findObjectOfType(Bi,this.context,!1);if(!i)if(this.usePlacementReticle){const n=new c.Object3D;for(const o of this.context.scene.children)n.add(o);this.context.scene.add(n),i=S.addComponent(n,Bi),this._createdComponentsInSession.push(i)}else(bl||T())&&console.warn("WebXR: No WebARSessionRoot found in scene and usePlacementReticle is disabled in WebXR component.");this._activeWebARSessionRoot=i,i&&(i.customReticle=this.customARPlacementReticle,i.arScale=this.arScale,i.arTouchTransform=this.usePlacementAdjustment,i.autoPlace=this.autoPlace,i.autoCenter=this.autoCenter,i.useXRAnchor=this.useXRAnchor)}this.useDefaultControls&&this.setDefaultMovementEnabled(!0),(this.showControllerModels||this.showHandModels)&&this.setDefaultControllerRenderingEnabled(!0),this.useSpatialGrab&&(this._spatialGrabRaycaster=S.findObjectOfType(cr)??void 0,this._spatialGrabRaycaster||(this._spatialGrabRaycaster=this.gameObject.addComponent(cr))),this.createLocalAvatar(e.xr),e.xr.isScreenBasedAR||(this._exitXRMenuButton=this.context.menu.appendChild({label:"Quit XR",onClick:()=>this.exitXR(),icon:"exit_to_app",priority:2e4}))}onUpdateXR(e){this.isActiveWebXR&&this._spatialGrabRaycaster&&(this._spatialGrabRaycaster.enabled=this.useSpatialGrab)}onLeaveXR(e){if(this._exitXRMenuButton?.remove(),!!this.isActiveWebXR){Vt.Global.Set(this._previousXRState),this._playerSync?.destroyInstance();for(const t of this._createdComponentsInSession)t.destroy();this._createdComponentsInSession.length=0,this._activeWebARSessionRoot=null,this.handleOfferSession(),Dc(1).then(()=>oa.activeWebXRComponent=null)}}setDefaultMovementEnabled(e){let t=this.gameObject.getComponent(vi);return!t&&e&&(t=this.gameObject.addComponent(vi),this._createdComponentsInSession.push(t)),t&&(t.enabled=e),t}setDefaultControllerRenderingEnabled(e){let t=this.gameObject.getComponent(ms);return!t&&e&&(t=this.gameObject.addComponent(ms),this._createdComponentsInSession.push(t),t.createControllerModel=this.showControllerModels,t.createHandModel==this.showHandModels),t&&(t.enabled=e),t}async createLocalAvatar(e){this._playerSync&&e.running&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,await this._playerSync.getInstance())}onAvatarSpawned=e=>{bl&&console.log("WebXR.onAvatarSpawned",e);let t=S.getComponentInChildren(e,ao);t??=S.addComponent(e,ao)};getButtonsContainer(){return this.getButtonsFactory()}getButtonsFactory(){return this._buttonFactory||(this._buttonFactory=no.getOrCreate()),this._buttonFactory}_buttonFactory;handleCreatingHTML(){if(this.createARButton||this.createVRButton||this.useQuicklookExport){if((exports.DeviceUtilities.isiOS()&&exports.DeviceUtilities.isSafari()||nk)&&this.useQuicklookExport){const e=S.findObjectOfType(an);if(!e||e&&e.allowCreateQuicklookButton){const t=this.getButtonsFactory().createQuicklookButton();this.addButton(t)}}if(this.createARButton){const e=this.getButtonsFactory().createARButton();this.addButton(e)}if(this.createVRButton){const e=this.getButtonsFactory().createVRButton();this.addButton(e)}}if(this.createSendToQuestButton&&!exports.DeviceUtilities.isQuest()&&G.isVRSupported().then(e=>{if(!e){const t=this.getButtonsFactory().createSendToQuestButton();this.addButton(t)}}),this.createQRCode){const e=Ua(Hn);if(e&&e.createQRCodeButton===!1)T()&&console.warn("WebXR: QRCode button is disabled in the Needle Menu component");else if(!exports.DeviceUtilities.isMobileDevice()){const t=ji.getOrCreate().createQRCode();this.addButton(t)}}}_buttons=[];addButton(e){this._buttons.push(e),this.context.menu.appendChild(e)}removeButtons(){for(const e of this._buttons)e.remove();this._buttons.length=0}};ct([f()],Je.prototype,"createVRButton");ct([f()],Je.prototype,"createARButton");ct([f()],Je.prototype,"createSendToQuestButton");ct([f()],Je.prototype,"createQRCode");ct([f()],Je.prototype,"useDefaultControls");ct([f()],Je.prototype,"showControllerModels");ct([f()],Je.prototype,"showHandModels");ct([f()],Je.prototype,"usePlacementReticle");ct([f(K)],Je.prototype,"customARPlacementReticle");ct([f()],Je.prototype,"usePlacementAdjustment");ct([f()],Je.prototype,"arScale");ct([f()],Je.prototype,"useXRAnchor");ct([f()],Je.prototype,"autoPlace");ct([f()],Je.prototype,"autoCenter");ct([f()],Je.prototype,"useQuicklookExport");ct([f()],Je.prototype,"useDepthSensing");ct([f()],Je.prototype,"useSpatialGrab");ct([f(K)],Je.prototype,"defaultAvatar");let Du=Je;const Qh=x("debugusdzbehaviours");class Wg{get extensionName(){return"Behaviour"}behaviours=[];addBehavior(e){this.behaviours.push(e)}addAudioClip(e){if(!e||typeof e!="string")return"";const i="audio/"+Cr.getName(e);return this.audioClips.push({clipUrl:e,filesKey:i}),i}behaviourComponents=[];behaviourComponentsCopy=[];audioClips=[];audioClipsCopy=[];targetUuids=new Set;getAllTargetUuids(){return this.targetUuids}onBeforeBuildDocument(e){if(!e.root)return Promise.resolve();const t=[];return e.root.traverse(i=>{S.foreachComponent(i,n=>{const o=n;if(typeof o.createBehaviours=="function"||typeof o.beforeCreateDocument=="function"||typeof o.afterCreateDocument=="function"||typeof o.afterSerialize=="function"){this.behaviourComponents.push(o);const r=o.beforeCreateDocument?.call(o,this,e);r instanceof Promise&&t.push(r)}},!1)}),Qh&&console.log("onBeforeBuildDocument: all components",this.behaviourComponents),Promise.all(t)}onExportObject(e,t,i){for(const n of this.behaviourComponents)n.createBehaviours?.call(n,this,t,i)}onAfterBuildDocument(e){for(const u of this.behaviourComponents)typeof u.afterCreateDocument=="function"&&u.afterCreateDocument(this,e);this.behaviourComponentsCopy=this.behaviourComponents.slice(),this.behaviourComponents.length=0,this.audioClipsCopy=this.audioClips.slice(),this.audioClips.length=0;const t=new Set,i=new Set,n=new Set,o=new Set,r=Qh;let a=`graph LR
|
|
1290
|
+
`))}for(const V of k){const J=o.get(V);J&&z.set(V,J)}return z},m=function(k){const z=p(k),V=l(z);return h(z,V,k)};const g=n.skinnedMesh.skeleton,_=new Array,y=[],v=[];for(const k of g.bones){y.push(k),v.push(k.uuid);const z=g.boneInverses[g.bones.indexOf(k)];_.push({bone:k,inverse:z})}let b=1e4;for(;v.length<g.bones.length&&b-- >0;)for(const k of y){const z=k.children;for(const V of z)if(v.indexOf(V.uuid)===-1&&g.bones.indexOf(V)!==-1){y.push(V),v.push(V.uuid);const J=g.boneInverses[g.bones.indexOf(V)];_.push({bone:V,inverse:J})}}b<=0&&console.error("Failed to sort bones in skinned mesh",n.skinnedMesh,g.bones,v);for(const k of vw(g.bones))_.push({bone:k,inverse:k.matrixWorld.clone().invert()});const w=_[0].bone.parent;w||console.error("No bone parent found for skinned mesh during USDZ export",n.skinnedMesh),_.sort((k,z)=>ba(k.bone,w)>ba(z.bone,w)?1:-1);const R=t.quickLookCompatible,M=[],O=[],A=[],D=[];for(const{bone:k}of _){if(R){const z=k.scale;z.x==0&&(z.x=1e-5),z.y==0&&(z.y=1e-5),z.z==0&&(z.z=1e-5),M.push(new c.Matrix4().compose(k.position,k.quaternion,k.scale))}else M.push(k.matrix.clone());O.push(k.position),A.push(k.quaternion),D.push(k.scale)}const L=_.map(k=>'"'+ba(k.bone,w)+'"').join(", "),N=_.map(k=>tb(k.inverse.clone().invert())).join(", ");e.beginBlock('def Skeleton "Rig"'),e.appendLine(`uniform matrix4d[] bindTransforms = [${N}]`),e.appendLine(`uniform token[] joints = [${L}]`),e.appendLine('uniform token purpose = "guide"'),e.appendLine(`uniform matrix4d[] restTransforms = [${M.map(k=>tb(k)).join(", ")}]`);const $=m(_.map(k=>k.bone));if(En){let k=1e7,z=0;for(const V of $.position?.keys()??[])k=Math.min(k,V),z=Math.max(z,V);console.log("Time samples",k,z,$)}if(e.beginBlock('def SkelAnimation "_anim"'),e.appendLine(`uniform token[] joints = [${L}]`),e.appendLine(`quatf[] rotations = [${u(A)}]`),$&&$.quaternion){e.beginBlock("quatf[] rotations.timeSamples = {","");const k=a($.quaternion);for(const z of k)e.appendLine(z);e.closeBlock()}if(e.appendLine(`half3[] scales = [${d(D)}]`),$&&$.scale){e.beginBlock("half3[] scales.timeSamples = {","");const k=r($.scale);for(const z of k)e.appendLine(z);e.closeBlock()}if(e.appendLine(`float3[] translations = [${d(O)}]`),$&&$.position){e.beginBlock("float3[] translations.timeSamples = {","");const k=r($.position);for(const z of k)e.appendLine(z);e.closeBlock()}e.closeBlock(),e.closeBlock()}}onSerialize(e,t){if(!this.model)return;const i=this.animationData.get(this.object);if(i)for(let d=0;d<i.length;d++)i[d]===void 0&&(i[d]=new Ee(null,this.object,null));const n=this.ext;this.skinnedMeshExport(e,t,n);const o=this.object,r=this.model,a=this.animationData.get(o);if(!a||o.isSkinnedMesh)return;tm&&console.log("SERIALIZE",this.model.name,this.object.type,a);const l=Intl.NumberFormat("en-US",{maximumFractionDigits:3,minimumFractionDigits:0,useGrouping:!1});function h(d,u){if(d.some(m=>m&&{position:m.pos,rotation:m.rot,scale:m.scale}[u])){switch(u){case"position":r.needsTranslate=!0,e.beginBlock("double3 xformOp:translate.timeSamples = {","");break;case"rotation":r.needsOrient=!0,e.beginBlock("quatf xformOp:orient.timeSamples = {","");break;case"scale":r.needsScale=!0,e.beginBlock("double3 xformOp:scale.timeSamples = {","");break}for(let m=0;m<d.length;m++){const g=d[m];if(!g)continue;const _=n.getStartTimeByClip(g.clip),y=g.getSortedTimesArray(u==="position",u==="rotation",u==="scale");if(!y||y.length===0){console.error("got an animated object but no time values?",o,g);continue}const v=!g.clip,b=u==="position"&&(g.pos||v),w=u==="rotation"&&(g.rot||v),R=u==="scale"&&(g.scale||v);if(b||w||R){const M=g.clip?.name??"rest",O=g.getDuration();En&&console.log("Write .timeSamples:",M,_,O,d),e.appendLine("# "+M+": start="+l.format(_*Ee.frameRate)+", length="+l.format(O*Ee.frameRate)+", frames="+g.getFrames())}if(b)for(const{time:M,translation:O}of g.getValues(y,!0,!1,!1)){const D=`${l.format((_+M)*Ee.frameRate)}: (${ie(O.x)}, ${ie(O.y)}, ${ie(O.z)}),`;e.appendLine(D)}if(w)for(const{time:M,rotation:O}of g.getValues(y,!1,!0,!1)){const D=`${l.format((_+M)*Ee.frameRate)}: (${ie(O.w)}, ${ie(O.x)}, ${ie(O.y)}, ${ie(O.z)}),`;e.appendLine(D)}if(R)for(const{time:M,scale:O}of g.getValues(y,!1,!1,!0)){const D=`${l.format((_+M)*Ee.frameRate)}: (${ie(O.x)}, ${ie(O.y)}, ${ie(O.z)}),`;e.appendLine(D)}}e.closeBlock()}}h(a,"position"),h(a,"rotation"),h(a,"scale")}}const IO=x("debugusdz");class Cr{static getName(e){const t=e.split(".").pop();let n=e.split(".").slice(0,-1).join(".").split("/").pop()?.replace(".","_");return n||(n="Audio_"+Math.random().toString(36).substring(2,15)),bi(n)+"."+t}get extensionName(){return"Audio"}files=new Array;onExportObject(e,t,i){const n=S.getComponents(e,_i);if(n.length)for(const o of n){if(!o.clip||typeof o.clip!="string"||!o.playOnAwake)continue;const r=o.clip.split("/").pop()||"Audio",a=Cr.getName(o.clip),l=bi(a);if(!this.files.some(h=>h.path===o.clip)){this.files.push({path:o.clip,name:a});const h=a.toLowerCase();i.quickLookCompatible&&!h.endsWith(".mp3")&&!h.endsWith(".wav")&&!h.endsWith(".m4a")&&console.error("Audio file "+o.clip+" from "+o.name+" is not an MP3 or WAV file. QuickLook may not support playing it.")}i.quickLookCompatible||t.addEventListener("serialize",(h,d)=>{h.appendLine(),h.beginBlock(`def SpatialAudio "${l}"`,"(",!1),h.appendLine(`displayName = "${r}"`),h.closeBlock(")"),h.beginBlock(),h.appendLine(`uniform asset filePath = @audio/${a}@`),h.appendLine(`uniform token auralMode = "${o.spatialBlend>0?"spatial":"nonSpatial"}"`),h.appendLine(`uniform token playbackMode = "${o.loop?"loopFromStage":"onceFromStart"}"`),h.appendLine(`uniform float gain = ${o.volume}`),h.closeBlock()})}}async onAfterSerialize(e){for(const t of this.files){const i="audio/"+t.name;if(e.files[i]){IO&&console.warn("Audio file with name "+i+" already exists in the context. Skipping.");continue}const r=await(await(await fetch(t.path)).blob()).arrayBuffer(),a=new Uint8Array(r);e.files[i]=a}}}var jO=Object.defineProperty,Re=(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&&jO(e,t,n),n};const rb=x("debugusdzbehaviours");function Zc(s){s&&(s.getComponentInParent(Ta)||(T()&&console.debug('Raycaster on "'+s.name+'" was automatically added, because no raycaster was found in the parent hierarchy.'),s.addComponent(yi)))}class Pr extends E{object;target;duration=1;relativeMotion=!1;coroutine=null;targetPos=new c.Vector3;targetRot=new c.Quaternion;targetScale=new c.Vector3;start(){Zc(this.gameObject)}onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}onPointerClick(e){const t=this.object?.getComponentsInChildren(Fe);if(t)for(const i of t)i.resetVelocities(),i.resetForcesAndTorques();e.use(),this.coroutine&&this.stopCoroutine(this.coroutine),this.relativeMotion?this.coroutine=this.startCoroutine(this.moveRelative()):this.coroutine=this.startCoroutine(this.moveToTarget())}*moveToTarget(){if(!this.target||!this.object)return;const e=Q(this.object).clone(),t=Q(this.target).clone(),i=fe(this.object).clone(),n=fe(this.target).clone(),o=Le(this.object).clone(),r=Le(this.target).clone(),a=e.distanceTo(t),l=i.angleTo(n),h=o.distanceTo(r);if(a<.01&&l<.01&&h<.01){rt(this.object,t),ln(this.object,n),Sa(this.object,r),this.coroutine=null;return}let d=0,u=0;for(;d<1;)d+=this.context.time.deltaTime/this.duration,d>1&&(d=1),u=d<.5?4*d*d*d:1-Math.pow(-2*d+2,3)/2,this.targetPos.lerpVectors(e,t,u),this.targetRot.slerpQuaternions(i,n,u),this.targetScale.lerpVectors(o,r,u),rt(this.object,this.targetPos),ln(this.object,this.targetRot),Sa(this.object,this.targetScale),yield;this.coroutine=null}*moveRelative(){if(!this.target||!this.object)return;const e=this.object.position.clone(),t=this.object.quaternion.clone(),i=this.object.scale.clone(),n=this.target.position.clone(),o=this.target.quaternion.clone(),r=this.target.scale.clone();n.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(n),this.targetRot.copy(this.object.quaternion).multiply(o),this.targetScale.copy(this.object.scale).multiply(r);let a=0,l=0;for(;a<1;)a+=this.context.time.deltaTime/this.duration,a>1&&(a=1),l=a<.5?4*a*a*a:1-Math.pow(-2*a+2,3)/2,this.object.position.lerpVectors(e,this.targetPos,l),this.object.quaternion.slerpQuaternions(t,this.targetRot,l),this.object.scale.lerpVectors(i,this.targetScale,l),yield;this.coroutine=null}beforeCreateDocument(e){if(this.target&&this.object&&this.gameObject){const t=new bt("Move to "+this.target?.name,kt.tapTrigger(this.gameObject),he.transformAction(this.object,this.target,this.duration,this.relativeMotion?"relative":"absolute"));e.addBehavior(t)}}}Re([f(c.Object3D)],Pr.prototype,"object");Re([f(c.Object3D)],Pr.prototype,"target");Re([f()],Pr.prototype,"duration");Re([f()],Pr.prototype,"relativeMotion");const ku=class Bt extends E{materialToSwitch;variantMaterial;fadeDuration=0;start(){this._objectsWithThisMaterial=this.objectsWithThisMaterial,Zc(this.gameObject),T()&&this._objectsWithThisMaterial.length<=0&&console.warn('ChangeMaterialOnClick: No objects found with material "'+this.materialToSwitch?.name+'"')}onPointerEnter(e){this.context.input.setCursor("pointer")}onPointerExit(e){this.context.input.unsetCursor("pointer")}onPointerClick(e){if(e.use(),!!this.variantMaterial)for(let t=0;t<this.objectsWithThisMaterial.length;t++){const i=this.objectsWithThisMaterial[t];i.material=this.variantMaterial}}_objectsWithThisMaterial=null;get objectsWithThisMaterial(){return this._objectsWithThisMaterial!=null?this._objectsWithThisMaterial:(this._objectsWithThisMaterial=[],this.variantMaterial&&this.materialToSwitch&&this.context.scene.traverse(e=>{if(e instanceof c.Mesh)if(Array.isArray(e.material)){for(const t of e.material)if(t===this.materialToSwitch){this.objectsWithThisMaterial.push(e);break}}else e.material===this.materialToSwitch?this.objectsWithThisMaterial.push(e):Qv(e.material,this.materialToSwitch)&&this.objectsWithThisMaterial.push(e)}),this._objectsWithThisMaterial)}selfModel;targetModels;static _materialTriggersPerId={};static _startHiddenBehaviour=null;static _parallelStartHiddenActions=[];async beforeCreateDocument(e,t){this.targetModels=[],Bt._materialTriggersPerId={},Bt.variantSwitchIndex=0,this.materialToSwitch&&await se.NEEDLE_progressive.assignTextureLOD(this.materialToSwitch,0),this.variantMaterial&&await se.NEEDLE_progressive.assignTextureLOD(this.variantMaterial,0)}createBehaviours(e,t,i){this.objectsWithThisMaterial.find(o=>o.uuid===t.uuid)&&this.targetModels.push(t),this.gameObject.uuid===t.uuid&&(this.selfModel=t,this.materialToSwitch&&(Bt._materialTriggersPerId[this.materialToSwitch.uuid]||(Bt._materialTriggersPerId[this.materialToSwitch.uuid]=[]),Bt._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(e,t){if(!this.materialToSwitch)return;const i=Bt._materialTriggersPerId[this.materialToSwitch.uuid];if(i){const n={};for(const o of i){const r=o.createVariants();r&&r.length>0&&(n[o.selfModel.uuid]=r)}for(const o of i){const r=[];for(const a in n)a!==o.selfModel.uuid&&r.push(...n[a]);o.createAndAttachBehaviors(e,n[o.selfModel.uuid],r)}}delete Bt._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(e,t,i){const n=[],o=Math.max(0,this.fadeDuration);n.push(he.fadeAction([...this.targetModels,...i],o,!1)),n.push(he.fadeAction(t,o,!0)),e.addBehavior(new bt("Select_"+this.selfModel.name,kt.tapTrigger(this.selfModel),he.parallel(...n))),Bt._parallelStartHiddenActions.push(...t),Bt._startHiddenBehaviour||(Bt._startHiddenBehaviour=new bt("StartHidden_"+this.selfModel.name,kt.sceneStartTrigger(),he.fadeAction(Bt._parallelStartHiddenActions,o,!1)),e.addBehavior(Bt._startHiddenBehaviour))}static getMaterialName(e){return bi(e.name||"Material")+"_"+e.id}static variantSwitchIndex=0;createVariants(){if(!this.variantMaterial)return null;const e=[];for(const t of this.targetModels){const i=t.clone();i.name+="_Variant_"+Bt.variantSwitchIndex+++"_"+Bt.getMaterialName(this.variantMaterial),i.displayName=i.displayName+": Variant with material "+this.variantMaterial.name,i.material=this.variantMaterial,i.geometry=t.geometry,i.transform=t.transform,(!t.parent||!t.parent.isEmpty())&&He.createEmptyParent(t),t.parent&&t.parent.add(i),e.push(i)}return e}};Re([f(c.Material)],ku.prototype,"materialToSwitch");Re([f(c.Material)],ku.prototype,"variantMaterial");Re([f()],ku.prototype,"fadeDuration");let Ig=ku;const Jc=class Me extends E{target;toggleOnClick=!1;targetState=!0;hideSelf=!0;start(){Zc(this.gameObject)}onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}onPointerClick(e){e.use(),!this.toggleOnClick&&this.hideSelf&&(this.gameObject.visible=!1),this.target&&(this.target.visible=this.toggleOnClick?!this.target.visible:this.targetState)}selfModel;selfModelClone;targetModel;toggleModel;createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t,this.selfModelClone=t.clone())}stateBeforeCreatingDocument=!1;targetStateBeforeCreatingDocument=!1;static clonedToggleIndex=0;static wasVisible=Symbol("usdz_SetActiveOnClick_wasVisible");static toggleClone=Symbol("clone for toggling");static reverseToggleClone=Symbol("clone for reverse toggling");beforeCreateDocument(){this.target&&(this.gameObject[Me.wasVisible]===void 0&&(this.gameObject[Me.wasVisible]=this.gameObject.activeSelf),this.target[Me.wasVisible]===void 0&&(this.target[Me.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[Me.wasVisible],this.targetStateBeforeCreatingDocument=this.target[Me.wasVisible],this.gameObject.visible=!0,this.target.visible=!0)}afterCreateDocument(e,t){if(!this.target)return;this.targetModel=t.document.findById(this.target.uuid);const i=this.selfModel;if(this.selfModel&&this.targetModel){let n=this.selfModel,o=this.targetState;if(this.toggleOnClick)if(o=!this.targetStateBeforeCreatingDocument,!this.selfModelClone.geometry)(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&Ag.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[Me.toggleClone]){const l=this.selfModelClone.clone();l.setMatrix(new c.Matrix4),l.name+="_toggle"+Me.clonedToggleIndex++,i.add(l),this.gameObject[Me.toggleClone]=l,console.warn("USDZExport: Toggle "+this.gameObject.name+" doesn't have geometry. It will be deep cloned and nested behaviours will likely not work.")}const a=this.gameObject[Me.toggleClone];if(!this.gameObject[Me.reverseToggleClone]){const l=this.selfModelClone.clone();l.setMatrix(new c.Matrix4),l.name+="_toggleReverse"+Me.clonedToggleIndex++,i.add(l),this.gameObject[Me.reverseToggleClone]=l}this.toggleModel=this.gameObject[Me.reverseToggleClone],(!this.toggleModel.geometry||!a.geometry)&&console.error("triggers without childs and without geometry won't work!",this,i.geometry),n=a,i.geometry=null,i.material=null}if(this.toggleModel){if(this.toggleOnClick){const a=[];a.push(he.fadeAction(n,0,!1)),a.push(he.fadeAction(this.toggleModel,0,!0)),a.push(he.fadeAction(this.targetModel,0,o)),e.addBehavior(new bt("Toggle_"+n.name+"_ToggleTo"+(o?"On":"Off"),kt.tapTrigger(n),he.parallel(...a)));const l=[];l.push(he.fadeAction(this.toggleModel,0,!1)),l.push(he.fadeAction(n,0,!0)),l.push(he.fadeAction(this.targetModel,0,!o)),e.addBehavior(new bt("Toggle_"+n.name+"_ToggleTo"+(o?"Off":"On"),kt.tapTrigger(this.toggleModel),he.parallel(...l)))}}else{const a=[];this.hideSelf&&a.push(he.fadeAction(n,0,!1)),a.push(he.fadeAction(this.targetModel,0,o)),e.addBehavior(new bt("Toggle_"+n.name+"_ToggleTo"+(o?"On":"Off"),kt.tapTrigger(n),a.length>1?he.parallel(...a):a[0]))}const r=new Array;this.targetStateBeforeCreatingDocument||r.push(this.targetModel),this.stateBeforeCreatingDocument||r.push(i),this.toggleModel&&r.push(this.toggleModel),Di.add(r,e)}}afterSerialize(e,t){this.gameObject[Me.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[Me.wasVisible],delete this.gameObject[Me.wasVisible]),this.target&&this.target[Me.wasVisible]!==void 0&&(this.target.visible=this.target[Me.wasVisible],delete this.target[Me.wasVisible]),delete this.gameObject[Me.toggleClone],delete this.gameObject[Me.reverseToggleClone]}};Re([f(c.Object3D)],Jc.prototype,"target");Re([f()],Jc.prototype,"toggleOnClick");Re([f()],Jc.prototype,"targetState");Re([f()],Jc.prototype,"hideSelf");let jg=Jc;class Di extends E{static _fadeBehaviour;static _fadeObjects=[];static add(e,t){const i=Array.isArray(e)?e:[e];for(const n of i)Di._fadeObjects.includes(n)||(console.log("adding hide on start",n),Di._fadeObjects.push(n));Di._fadeBehaviour===void 0&&(Di._fadeBehaviour=new bt("HideOnStart",kt.sceneStartTrigger(),he.fadeAction(Di._fadeObjects,0,!1)),t.addBehavior(Di._fadeBehaviour))}start(){S.setActive(this.gameObject,!1)}createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.wasVisible||Di.add(t,e))}wasVisible=!1;beforeCreateDocument(){this.wasVisible=S.isActiveSelf(this.gameObject)}}class Wa extends E{target;duration=.5;motionType="bounce";beforeCreateDocument(){}createBehaviours(e,t,i){if(this.target&&t.uuid===this.gameObject.uuid){const n=new bt("emphasize "+this.name,kt.tapTrigger(this.gameObject),he.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));e.addBehavior(n)}}afterCreateDocument(e,t){}}Re([f()],Wa.prototype,"target");Re([f()],Wa.prototype,"duration");Re([f()],Wa.prototype,"motionType");class ro extends E{target;clip="";toggleOnClick=!1;trigger="tap";start(){Zc(this.gameObject)}ensureAudioSource(){if(!this.target){const e=this.gameObject.addComponent(_i);e&&(this.target=e,e.spatialBlend=1,e.volume=1,e.loop=!1,e.preload=!0)}}onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}onPointerClick(e){e.use(),!(!this.target?.clip&&!this.clip)&&(this.ensureAudioSource(),this.target&&(this.target.isPlaying&&this.toggleOnClick?this.target.stop():(!this.toggleOnClick&&this.target.isPlaying&&this.target.stop(),this.clip?this.target.play(this.clip):this.target.play())))}createBehaviours(e,t,i){if(!(!this.target&&!this.clip)&&t.uuid===this.gameObject.uuid){const n=this.clip?this.clip:this.target?this.target.clip:void 0;if(!n||typeof n!="string")return;const o=this.target?this.target.gameObject:this.gameObject;Cr.getName(n);const r=this.target?this.target.volume:1,a=this.target&&this.target.spatialBlend==0?"nonSpatial":"spatial";let l=!1;this.gameObject.traverse(p=>{p instanceof c.Mesh&&p.visible&&(l=!0)}),l=!0;const h=e.addAudioClip(n);let d=he.playAudioAction(o,h,"play",r,a);this.target&&this.target.loop&&(d=he.sequence(d).makeLooping());const u=this.name?"_"+this.name:"";if(l&&this.trigger==="tap"){this.toggleOnClick&&(d.multiplePerformOperation="stop");const p=new bt("playAudio"+u,kt.tapTrigger(t),d);e.addBehavior(p)}if(this.target&&this.target.playOnAwake&&this.target.enabled)if(l&&this.trigger==="tap")console.warn("USDZExport: Audio sources that are played on tap can't also auto-play at scene start due to a QuickLook bug.");else{const p=new bt("playAudioOnStart"+u,kt.sceneStartTrigger(),d);e.addBehavior(p)}}}}Re([f(_i)],ro.prototype,"target");Re([f(URL)],ro.prototype,"clip");Re([f()],ro.prototype,"toggleOnClick");const Bg=class Sn extends E{animator;stateName;trigger="tap";animation;get target(){return this.animator?.gameObject||this.animation?.gameObject}start(){Zc(this.gameObject)}onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}onPointerClick(e){e.use(),this.target&&this.stateName&&this.animator?.play(this.stateName,0,0,.1)}selfModel;stateAnimationModel;animationSequence=new Array;animationLoopAfterSequence=new Array;randomOffsetNormalized=0;createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t)}static animationActions=[];static rootsWithExclusivePlayback=new Set;afterSerialize(){if(Sn.rootsWithExclusivePlayback.size>1){const e='Multiple root objects targeted by more than one animation. To work around QuickLook bug FB13410767, animations will be set as "exclusive" and activating them will stop other animations being marked as exclusive.';T()&&ue(e),console.warn(e,...Sn.rootsWithExclusivePlayback)}Sn.animationActions=[],Sn.rootsWithExclusivePlayback=new Set}afterCreateDocument(e,t){if(this.animationSequence===void 0&&this.animationLoopAfterSequence===void 0||!this.stateAnimationModel||!this.target)return;const i=t.document,n=t.extensions.find(a=>a instanceof Ou);if(!n)return;const o=n.getClipCount(this.target)>1;o&&(T()&&console.warn("Setting exclusive playback for "+this.target.name+"@"+this.stateName+" because it has "+n.getClipCount(this.target)+" animations. This works around QuickLook bug FB13410767."),Sn.rootsWithExclusivePlayback.add(this.target));const r=this.name?this.name:"";i.traverse(a=>{if(a.uuid===this.target?.uuid){const l=Sn.getActionForSequences(i,a,this.animationSequence,this.animationLoopAfterSequence,this.randomOffsetNormalized),h=new bt(this.trigger+"_"+r+"_toPlayAnimation_"+this.stateName+"_on_"+this.target?.name,this.trigger=="tap"?kt.tapTrigger(this.selfModel):kt.sceneStartTrigger(),l);o&&h.makeExclusive(!0),e.addBehavior(h)}})}static getActionForSequences(e,t,i,n,o){const r=(l,h)=>{let d=Sn.animationActions.find(u=>u.affectedObjects==l&&u.start==h.start&&u.duration==h.duration&&u.animationSpeed==h.speed);return d||(d=he.startAnimationAction(l,h),Sn.animationActions.push(d)),d},a=he.sequence();if(i&&i.length>0)for(const l of i)a.addAction(r(t,l));if(n&&n.length>0){const l=a.actions.length==0?a:he.sequence();for(const h of n)l.addAction(r(t,h));l.makeLooping(),a!==l&&a.addAction(l)}return o&&o>0&&a.actions.unshift(he.waitAction(o)),a}static getAndRegisterAnimationSequences(e,t,i){if(!t)return;const n=t.getComponent(at),o=t.getComponent(Et);if(!n&&!o)return;if(n&&!i)throw new Error("PlayAnimationOnClick: No stateName specified for animator "+n.name+" on "+t.name);let r=[],a=[];if(o){const g=e.registerAnimation(t,o.clip);g&&(o.loop?a.push(g):r.push(g));let _=0;if(o.minMaxOffsetNormalized){const y=o.minMaxOffsetNormalized.x,v=o.minMaxOffsetNormalized.y;_=(o.clip?.duration||1)*(y+Math.random()*(v-y))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:_}}const l=n?.runtimeAnimatorController;let h=l?.findState(i),d=[],u=[];if(l&&h){const g=new Array;g.push(h);let _=!1;for(;g.length<100;){if(!h||h===null||!h.transitions||h.transitions.length===0){h.motion?.isLooping&&(_=!0);break}const y=h.transitions.find(b=>b.conditions.length===0),v=y?l.getState(y.destinationState,0):null;if(v&&g.includes(v)){h=v,_=!0;break}else if(y){if(h=v,!h)break;g.push(h)}else{_=h.motion?.isLooping??!1;break}}if(_&&h){const y=g.indexOf(h);d=g.slice(0,y),u=g.slice(y),rb&&console.log("found loop from "+i,"states until loop",d,"states looping",u)}else d=g,u=[],rb&&console.log("found no loop from "+i,"states",d);if(!u.length){const y=d[d.length-1],v=y.motion?.clip;if(v){let b;if(e.holdClipMap.has(v))b=e.holdClipMap.get(v);else{const w=y.name+"_hold";b=v.clone(),b.duration=1,b.name=w;const R=v.duration;b.tracks=v.tracks.map(M=>{const O=M.clone();O.times=new Float32Array([0,R]);const A=M.values.length,D=M.getValueSize(),L=M.values.slice(A-D,A);return O.values=new Float32Array(2*D),O.values.set(L,0),O.values.set(L,D),O}),b.name=w,e.holdClipMap.set(v,b)}if(b){const w={name:b.name,motion:{clip:b,isLooping:!1,name:b.name},speed:1,transitions:[],behaviours:[],hash:y.hash+1};u.push(w)}}}}if(d.length===1&&(!d[0].motion?.clip||d[0].motion?.clip.tracks?.length===0)){r=new Array;const g=e.registerAnimation(t,null);g&&r.push(g);return}if(d=d.filter(g=>g.motion?.clip&&g.motion?.clip.tracks?.length>0),u=u.filter(g=>g.motion?.clip&&g.motion?.clip.tracks?.length>0),d.length===0&&u.length===0){console.warn("No clips found for state "+i+" on "+n?.name+", can't export animation data");return}const p=(g,_)=>{if(!t)return;const y=e.registerAnimation(t,g.motion.clip??null);y?(y.speed=g.speed,_.push(y)):console.warn("Couldn't register animation for state "+g.name+" on "+n?.name)};if(d.length>0){r=new Array;for(const g of d)p(g,r)}if(u.length>0){a=new Array;for(const g of u)p(g,a)}let m=0;if(n&&l&&n.minMaxOffsetNormalized){const g=n.minMaxOffsetNormalized.x,_=n.minMaxOffsetNormalized.y;m=((d.length?d[0]:u.length?u[0]:null)?.motion.clip?.duration||1)*(g+Math.random()*(_-g))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:m}}createAnimation(e,t,i){if(!this.target||!this.animator&&!this.animation)return;const n=Sn.getAndRegisterAnimationSequences(e,this.target,this.stateName);n&&(this.animationSequence=n.animationSequence,this.animationLoopAfterSequence=n.animationLoopAfterSequence,this.randomOffsetNormalized=n.randomTimeOffset,this.stateAnimationModel=t)}};Re([f(at)],Bg.prototype,"animator");Re([f()],Bg.prototype,"stateName");let Sc=Bg;class Ha extends E{getType(){}target;getDuration(){}}Re([f(c.Object3D)],Ha.prototype,"target");class eh extends E{target}Re([f(Ha)],eh.prototype,"target");class th extends Ha{type=1;duration=1;getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}Re([f()],th.prototype,"type");Re([f()],th.prototype,"duration");class Ug extends eh{}const BO=100,UO=200,FO=300;class no{static _instance;static create(){return new no}static getOrCreate(){return this._instance||(this._instance=this.create()),this._instance}get isSecureConnection(){return window.location.protocol==="https:"}get quicklookButton(){return this._quicklookButton}_quicklookButton;get arButton(){return this._arButton}_arButton;get vrButton(){return this._vrButton}_vrButton;get sendToQuestButton(){return this._sendToQuestButton}_sendToQuestButton;get qrButton(){return ji.getOrCreate().createQRCode()}createQuicklookButton(){if(this._quicklookButton)return this._quicklookButton;const e=document.createElement("button");this._quicklookButton=e,e.dataset.needle="quicklook-button";const t=exports.DeviceUtilities.supportsQuickLookAR();let i="View in AR";exports.DeviceUtilities.isVisionOS()?i="View in AR":(t||exports.DeviceUtilities.isiOS())&&(i="Open in Quicklook"),e.innerText=i,e.prepend(yt("view_in_ar")),Js.setElementPriority(e,UO);let n=!1,o=null;return e.addEventListener("click",()=>{o=Ua(an),o||(n=!0,o=new an),n&&(o.objectToExport=U.Current.scene),o?(e.classList.add("this-mode-is-requested"),o.exportAndOpen().then(()=>{e.classList.remove("this-mode-is-requested")}).catch(r=>{e.classList.remove("this-mode-is-requested"),console.error(r)})):console.warn("No USDZExporter component found in the scene")}),this.hideElementDuringXRSession(e),e}createARButton(e){if(this._arButton)return this._arButton;const t="immersive-ar",i=document.createElement("button");return this._arButton=i,i.classList.add("webxr-button"),i.dataset.needle="webxr-ar-button",i.innerText="Enter AR",i.prepend(yt("view_in_ar")),i.title="Click to start an AR session",i.addEventListener("click",()=>G.start(t,e)),Js.setElementPriority(i,FO),this.updateSessionSupported(i,t),this.listenToXRSessionState(i,t),this.hideElementDuringXRSession(i),this.isSecureConnection||(i.disabled=!0,i.title="WebXR requires a secure connection (HTTPS)"),exports.DeviceUtilities.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>this.updateSessionSupported(i,t)),i}createVRButton(e){if(this._vrButton)return this._vrButton;const t="immersive-vr",i=document.createElement("button");return this._vrButton=i,i.classList.add("webxr-button"),i.dataset.needle="webxr-vr-button",i.innerText="Enter VR",i.prepend(yt("panorama_photosphere")),i.title="Click to start a VR session",i.addEventListener("click",()=>G.start(t,e)),Js.setElementPriority(i,BO),this.updateSessionSupported(i,t),this.listenToXRSessionState(i,t),this.hideElementDuringXRSession(i),this.isSecureConnection||(i.disabled=!0,i.title="WebXR requires a secure connection (HTTPS)"),exports.DeviceUtilities.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>this.updateSessionSupported(i,t)),i}createSendToQuestButton(){if(this._sendToQuestButton)return this._sendToQuestButton;const e="https://oculus.com/open_url/?url=",t=document.createElement("button");return this._sendToQuestButton=t,t.dataset.needle="webxr-sendtoquest-button",t.innerText="Open on Quest",t.prepend(yt("share_windows")),t.title="Click to send this page to the Oculus Browser on your Quest",t.addEventListener("click",()=>{const i=encodeURIComponent(window.location.href),n=e+i;window.open(n)==null&&we("This page doesn't allow popups. Please paste "+n+" into your browser.")}),this.listenToXRSessionState(t),this.hideElementDuringXRSession(t),exports.DeviceUtilities.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>{navigator.xr?.isSessionSupported("immersive-vr")?t.style.display="none":t.style.display=""}),t}createQRCode(){return ji.getOrCreate().createQRCode()}updateSessionSupported(e,t){if(!(t==="immersive-ar"&&exports.DeviceUtilities.isiOS()&&!exports.DeviceUtilities.isVisionOS())){if(!("xr"in navigator)){e.style.display="none";return}G.isSessionSupported(t).then(i=>{e.style.display=i?"":"none",T()&&!i&&console.log('[WebXR] "'+t+'" is not supported on this device. Make sure your server runs using HTTPS and you have a device connected that supports '+t)})}}hideElementDuringXRSession(e){su(t=>{e["previous-display"]=e.style.display,e.style.setProperty("display","none","important")}),Dm(t=>{e["previous-display"]!=null&&(e.style.display=e["previous-display"])})}listenToXRSessionState(e,t){t&&(G.onSessionRequestStart(i=>{i.mode===t?e.classList.add("this-mode-is-requested"):(e["was-disabled"]=e.disabled,e.disabled=!0,e.classList.add("other-mode-is-requested"))}),G.onSessionRequestEnd(i=>{e.classList.remove("this-mode-is-requested"),e.classList.remove("other-mode-is-requested"),e.disabled=e["was-disabled"]}))}}var zO=Object.defineProperty,NO=Object.getOwnPropertyDescriptor,lt=(s,e,t,i)=>{for(var n=i>1?void 0:i?NO(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&&zO(e,t,n),n};const nc=x("debugspriterenderer"),VO=x("wireframe");class ur{static cache={};static getOrCreateGeometry(e){if(e.__cached_geometry)return e.__cached_geometry;if(e.guid&&ur.cache[e.guid])return nc&&console.log("Take cached geometry for sprite",e.guid),ur.cache[e.guid];const t=new c.BufferGeometry;e.__cached_geometry=t;const i=new Float32Array(e.triangles.length*3),n=new Float32Array(e.triangles.length*2);for(let o=0;o<e.triangles.length;o+=1){const r=e.triangles[o];i[o*3]=-e.vertices[r].x,i[o*3+1]=e.vertices[r].y,i[o*3+2]=0;const a=e.uv[r];n[o*2]=a.x,n[o*2+1]=1-a.y}return t.setAttribute("position",new c.BufferAttribute(i,3)),t.setAttribute("uv",new c.BufferAttribute(n,2)),e.guid&&(this.cache[e.guid]=t),nc&&console.log("Built sprite geometry",e,t),t}}class $O{x;y}function Tw(s){s&&(s.colorSpace!=c.SRGBColorSpace&&(s.colorSpace=c.SRGBColorSpace,s.needsUpdate=!0),s.minFilter==c.NearestFilter&&s.magFilter==c.NearestFilter&&(s.anisotropy=1,s.needsUpdate=!0))}let ws=class{constructor(e){e&&(this.texture=e,this.triangles=[0,1,2,0,2,3],this.uv=[{x:0,y:0},{x:1,y:0},{x:1,y:1},{x:0,y:1}],this.vertices=[{x:-.5,y:-.5},{x:.5,y:-.5},{x:.5,y:.5},{x:-.5,y:.5}])}guid;texture;triangles;uv;vertices;__cached_geometry;get mesh(){return this._mesh||(this._mesh=new c.Mesh(ur.getOrCreateGeometry(this),this.material)),this._mesh}_mesh;get material(){return this._material||(this.texture&&Tw(this.texture),this._material=new c.MeshBasicMaterial({map:this.texture,color:16777215,side:c.DoubleSide,transparent:!0})),this._material}_material;getGeometry(){return ur.getOrCreateGeometry(this)}};lt([f()],ws.prototype,"guid",2);lt([f(c.Texture)],ws.prototype,"texture",2);lt([ze()],ws.prototype,"triangles",2);lt([ze()],ws.prototype,"uv",2);lt([ze()],ws.prototype,"vertices",2);const Yf=Symbol("spriteOwner");class Aa{sprites;constructor(){this.sprites=[]}}lt([f(ws)],Aa.prototype,"sprites",2);const Fg=class im{static create(){const e=new im;return e.spriteSheet=new Aa,e}constructor(){}clone(){const e=new im;return e.index=this.index,e.spriteSheet=this.spriteSheet,e}set sprite(e){e&&(this.spriteSheet?((this.index===null||this.index===void 0)&&(this.index=0),this.spriteSheet.sprites[this.index]=e):(this.spriteSheet=new Aa,this.spriteSheet.sprites=[e],this.index=0))}get sprite(){if(this.spriteSheet)return this.spriteSheet.sprites[this.index]}spriteSheet;index=0;update(e){if(!this.spriteSheet)return;const t=this.index;if(t<0||t>=this.spriteSheet.sprites.length)return;const i=this.spriteSheet.sprites[t],n=i?.texture;if(n&&(Tw(n),!i.__hasLoadedProgressive)){i.__hasLoadedProgressive=!0;const o=n;se.NEEDLE_progressive.assignTextureLOD(n,0).then(r=>{r instanceof c.Texture&&(i.texture=r,e?.map===o&&(e.map=r,e.needsUpdate=!0))})}}};lt([f(Aa)],Fg.prototype,"spriteSheet",2);lt([f()],Fg.prototype,"index",2);let va=Fg;class oi extends E{drawMode=0;size={x:1,y:1};color;sharedMaterial;transparent=!0;cutoutThreshold=0;castShadows=!1;renderOrder=0;toneMapped=!0;set texture(e){if(!this._spriteSheet)return;const t=this._spriteSheet.spriteSheet?.sprites[this.spriteIndex];t&&(t.texture=e,this.updateSprite())}addSprite(e,t=!1){if(this._spriteSheet||(this._spriteSheet=va.create()),!this._spriteSheet.spriteSheet)return-1;this._spriteSheet.spriteSheet?.sprites.push(e);const i=this._spriteSheet.spriteSheet?.sprites.length-1;return t&&(this.spriteIndex=i),i}get sprite(){return this._spriteSheet}set sprite(e){if(e!==this._spriteSheet)if(typeof e=="number"){const t=Math.round(e);nc&&console.log("[SpriteSheet] Set index to "+t+" (was "+this.spriteIndex+")",e),this.spriteIndex=t}else e instanceof ws?(this._spriteSheet||(this._spriteSheet=va.create()),this._spriteSheet.sprite!=e&&(this._spriteSheet.sprite=e),this.updateSprite()):e!=this._spriteSheet&&(this._spriteSheet=e,this.updateSprite())}set spriteIndex(e){this._spriteSheet&&(this._spriteSheet.index=e,this.updateSprite())}get spriteIndex(){return this._spriteSheet?.index??0}get spriteFrames(){return this._spriteSheet?.spriteSheet?.sprites.length??0}_spriteSheet;_currentSprite;awake(){this._currentSprite=void 0,this._spriteSheet?this._spriteSheet=this._spriteSheet.clone():this._spriteSheet=va.create(),nc&&console.log("Awake",this.name,this,this.sprite)}start(){this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(e=!1){if(!this.__didAwake&&!e)return!1;const t=this._spriteSheet;if(!t?.spriteSheet?.sprites)return console.warn("SpriteRenderer has no data or spritesheet assigned..."),!1;const i=t.spriteSheet.sprites[this.spriteIndex];if(!i)return nc&&console.warn("Sprite not found",this.spriteIndex,t.spriteSheet.sprites),!1;if(this._currentSprite)this._currentSprite.geometry=ur.getOrCreateGeometry(i),this._currentSprite.material.map=i.texture;else{const n=new c.MeshBasicMaterial({color:16777215,side:c.DoubleSide});if(VO&&(n.wireframe=!0),this.color&&(n.color||(n.color=new c.Color),n.color.copy(this.color),n.opacity=this.color.alpha),n.transparent=!0,n.toneMapped=this.toneMapped,n.depthWrite=!1,i.texture&&!n.wireframe){let o=i.texture;o[Yf]!==void 0&&o[Yf]!==this&&this.spriteFrames>1&&(o=i.texture=o.clone()),o[Yf]=this,n.map=o}this.sharedMaterial=n,this._currentSprite=new c.Mesh(ur.getOrCreateGeometry(i),n),this._currentSprite.renderOrder=Math.round(this.renderOrder),se.NEEDLE_progressive.assignTextureLOD(n,0)}return this._currentSprite.parent!==this.gameObject&&(this.drawMode===2&&this._currentSprite.scale.set(this.size.x,this.size.y,1),this.gameObject&&this.gameObject.add(this._currentSprite)),this._currentSprite&&this._currentSprite.layers.set(this.layer),this.sharedMaterial&&(this.sharedMaterial.alphaTest=this.cutoutThreshold,this.sharedMaterial.transparent=this.transparent),this._currentSprite.castShadow=this.castShadows,t?.update(this.sharedMaterial),!0}}lt([f()],oi.prototype,"drawMode",2);lt([f($O)],oi.prototype,"size",2);lt([f(ee)],oi.prototype,"color",2);lt([f(c.Material)],oi.prototype,"sharedMaterial",2);lt([f()],oi.prototype,"transparent",2);lt([f()],oi.prototype,"cutoutThreshold",2);lt([f()],oi.prototype,"castShadows",2);lt([f()],oi.prototype,"renderOrder",2);lt([f()],oi.prototype,"toneMapped",2);lt([f(va)],oi.prototype,"sprite",1);const ab=x("debugwebxr"),WO=new c.Matrix4().makeRotationY(Math.PI);class Bi extends E{static _eventListeners={};static onPlaced(e){const t="placed";return this._eventListeners[t]||(this._eventListeners[t]=[]),this._eventListeners[t].push(e),()=>{const i=this._eventListeners[t].indexOf(e);i>=0&&this._eventListeners[t].splice(i,1)}}static _hasPlaced=!1;static get hasPlaced(){return this._hasPlaced}get arScale(){return this._arScale}set arScale(e){this._arScale=Math.max(1e-6,e),this.onSetScale()}_arScale=1;invertForward=!1;customReticle;arTouchTransform=!0;autoPlace=!1;autoCenter=!1;useXRAnchor=!1;_isPlacing=!0;_startOffset=new c.Matrix4;_createdPlacementObject=null;_reparentedComponents=[];_placementScene=new c.Scene;_reticle=[];_hits=[];_placementStartTime=-1;_rigPlacementMatrix;_anchor=null;userInput;onEnable(){this.customReticle?.preload()}supportsXR(e){return e==="immersive-ar"}onEnterXR(e){ab&&console.log("ENTER WEBXR: SessionRoot start..."),this._anchor=null,Bi._hasPlaced=!1,this.gameObject.updateMatrixWorld(),this._startOffset.copy(this.gameObject.matrixWorld);const t=new c.Object3D;this._createdPlacementObject=t,t.name="AR Session Root",this._placementScene.name="AR Placement Scene",this._placementScene.children.length=0;for(let i=this.context.scene.children.length-1;i>=0;i--){const n=this.context.scene.children[i];this._placementScene.add(n)}if(this.context.scene.add(t),this.autoCenter){const i=Wt(this._placementScene.children),n=i.getCenter(new c.Vector3),o=i.getSize(new c.Vector3),r=new c.Matrix4;r.makeTranslation(n.x,n.y-o.y*.5,n.z),this._startOffset.multiply(r)}this._reparentedComponents.length=0,this._reparentedComponents.push({comp:this,originalObject:this.gameObject}),S.addComponent(t,this);for(const i of this._reticle)gi(i);this._reticle.length=0,this._isPlacing=!0,this.context.input.addEventListener("pointerup",this.onPlaceScene,{queue:Jt.Early})}onLeaveXR(){this.context.input.removeEventListener("pointerup",this.onPlaceScene,{queue:Jt.Early}),this.onRevertSceneChanges(),this._anchor=null,Bi._hasPlaced=!1,this._rigPlacementMatrix=void 0}onUpdateXR(e){if(e.xr.isTrackingImages){for(const t of this._reticle)t.visible=!1;return}if(this._isPlacing){const t=e.xr.rig?.gameObject;t&&t.parent!==this.context.scene&&this.context.scene.add(t);let i=!1;if(e.xr.isPassThrough&&e.xr.controllers.length>0&&!this.autoPlace)for(const n of e.xr.controllers){const o=n.getHitTest();o&&(i=!0,this.updateReticleAndHits(e.xr,n.index,o,e.xr.rigScale))}if(!i){const n=e.xr.getHitTest();n&&this.updateReticleAndHits(e.xr,0,n,e.xr.rigScale)}}else{if(this._anchor&&e.xr.referenceSpace){const t=e.xr.frame.getPose(this._anchor.anchorSpace,e.xr.referenceSpace);if(t&&this.context.time.frame%20===0){const i=e.xr.convertSpace(t.transform),n=this._reticle[0];n&&(n.position.copy(i.position),n.quaternion.copy(i.quaternion),this.onApplyPose(n))}}if(this.arTouchTransform?(this.userInput||(this.userInput=new Qd(this.context)),this.userInput?.enable()):this.userInput?.disable(),this.arTouchTransform&&this.userInput?.hasChanged){if(e.xr.rig){const t=e.xr.rig.gameObject;this.userInput.applyMatrixTo(t.matrix,!0),t.matrix.decompose(t.position,t.quaternion,t.scale),this.userInput.factor=t.scale.x}this.userInput.reset()}}}updateReticleAndHits(e,t,i,n){this._hits[t]=i.hit;let o=this._reticle[t];if(!o){if(this.customReticle)if(this.customReticle.asset)o=oo(this.customReticle.asset);else{this.customReticle.loadAssetAsync();return}else o=new c.Mesh(new c.RingGeometry(.07,.09,32).rotateX(-Math.PI/2),new c.MeshBasicMaterial({side:c.DoubleSide,depthTest:!1,depthWrite:!1,transparent:!0,opacity:1,color:15658734})),o.name="AR Placement Reticle";if(ab){const r=new c.AxesHelper(1);r.position.y+=.01,o.add(r)}this._reticle[t]=o,o.matrixAutoUpdate=!1,o.visible=!1}if(o.lastPos=o.lastPos||i.position.clone(),o.lastQuat=o.lastQuat||i.quaternion.clone(),o.position.copy(o.lastPos.lerp(i.position,this.context.time.deltaTime/.1)),o.lastPos.copy(o.position),o.quaternion.copy(o.lastQuat.slerp(i.quaternion,this.context.time.deltaTime/.05)),o.lastQuat.copy(o.quaternion),o.scale.set(n,n,n),this.customReticle&&this.applyViewBasedTransform(o),o.updateMatrix(),o.visible=!0,o.parent!==this.context.scene&&this.context.scene.add(o),this._placementStartTime<0&&(this._placementStartTime=this.context.time.realtimeSinceStartup),this.autoPlace)if(this.upVec.set(0,1,0).applyQuaternion(o.quaternion),this.upVec.dot(B(0,1,0))>.9){let a=o["autoplace:timer"]||0;a>=1?(o.visible=!1,this.onPlaceScene(null)):(a+=this.context.time.deltaTime,o["autoplace:timer"]=a)}else o["autoplace:timer"]=0}onPlaceScene=e=>{if(this._isPlacing==!1||e?.used)return;let t=this._reticle[0];if(!t){console.warn("No reticle to place...");return}if(!t.visible&&!this.autoPlace){console.warn("Reticle is not visible (can not place)");return}if(G.active?.isTrackingImages){console.warn("Scene Placement is disabled while images are being tracked");return}let i=this._hits[0];if(e&&e.origin instanceof Lm){const n=this._reticle[e.origin.index];n&&(t=n,i=this._hits[e.origin.index])}if(e&&(e.stopImmediatePropagation(),e.stopPropagation(),e.use()),this._isPlacing=!1,this.context.input.removeEventListener("pointerup",this.onPlaceScene),this.onRevertSceneChanges(),t.position.copy(t.lastPos),t.quaternion.copy(t.lastQuat),this.onApplyPose(t),Bi._hasPlaced=!0,this.useXRAnchor&&this.onCreateAnchor(G.active,i),this.context.xr)for(const n of this.context.xr.controllers)n.cancelHitTestSource()};onSetScale(){if(!Bi._hasPlaced)return;const e=G.active?.rig?.gameObject;if(e){const t=G.active?.rigScale||1,i=1/this._arScale*t,n=new c.Matrix4().makeScale(i,i,i).invert();e.matrix.premultiply(n),e.matrix.decompose(e.position,e.quaternion,e.scale)}}onRevertSceneChanges(){for(const e of this._reticle)e&&(e.visible=!1,e?.removeFromParent());this._reticle.length=0;for(let e=this._placementScene.children.length-1;e>=0;e--){const t=this._placementScene.children[e];this.context.scene.add(t)}this._createdPlacementObject?.removeFromParent();for(const e of this._reparentedComponents)S.addComponent(e.originalObject,e.comp)}async onCreateAnchor(e,t){if(t.createAnchor===void 0){console.warn("Hit does not support creating an anchor",t),T()&&ue("Hit does not support creating an anchor");return}else{const i=await t.createAnchor(e.viewerPose.transform);e.running&&i&&(this._anchor=i)}}upVec=new c.Vector3(0,1,0);lookPoint=new c.Vector3;worldUpVec=new c.Vector3(0,1,0);applyViewBasedTransform(e){const t=this.context.mainCamera,i=e,n=t.worldPosition,o=i.worldPosition;this.upVec.set(0,1,0).applyQuaternion(e.quaternion);const r=t.worldPosition;r&&e.position.clone().sub(r).angleTo(this.upVec)<Math.PI/2&&this.upVec.negate();const a=this.upVec.angleTo(this.worldUpVec)*180/Math.PI,l=30;a>l&&a<180-l||a<-l&&a>-180+l?(this.lookPoint.copy(e.position).add(this.upVec),this.lookPoint.y=e.position.y,e.lookAt(this.lookPoint)):(n.y=o.y,e.lookAt(n))}onApplyPose(e){const t=G.active?.rig?.gameObject;if(!t){console.warn("No rig object to place");return}const i=t.parent||this.context.scene;this._rigPlacementMatrix?this._rigPlacementMatrix?.decompose(t.position,t.quaternion,t.scale):this._rigPlacementMatrix=t.matrix.clone(),this.applyViewBasedTransform(e),e.updateMatrix(),this.context.scene.add(e),e.attach(t),e.removeFromParent(),t.scale.set(this.arScale,this.arScale,this.arScale),t.position.multiplyScalar(this.arScale),t.updateMatrix(),this.invertForward&&t.matrix.premultiply(WO),t.matrix.premultiply(this._startOffset),t.matrix.decompose(t.position,t.quaternion,t.scale),i.add(t)}}class Qd{static up=new c.Vector3(0,1,0);static zero=new c.Vector3(0,0,0);static one=new c.Vector3(1,1,1);oneFingerDrag=!0;twoFingerRotate=!0;twoFingerScale=!0;factor=1;context;offset;plane;_scale=1;_hasChanged=!1;get scale(){return this._scale}constructor(e){this.context=e,this.offset=new c.Matrix4,this.plane=new c.Plane,this.plane.setFromNormalAndCoplanarPoint(Qd.up,Qd.zero)}_enabled=!1;reset(){this._scale=1,this.offset.identity(),this._hasChanged=!0}get hasChanged(){return this._hasChanged}applyMatrixTo(e,t){this._hasChanged=!1,t?(this.offset.invert(),e.premultiply(this.offset)):e.multiply(this.offset)}currentlyUsedPointerIds=new Set;currentlyUnusedPointerIds=new Set;get isActive(){return this.currentlyUsedPointerIds.size<=0&&this.currentlyUnusedPointerIds.size>0}enable(){this._enabled||(this._enabled=!0,this.context.input.addEventListener("pointerdown",this.onPointerDownEarly,{queue:Jt.Early}),this.context.input.addEventListener("pointerdown",this.onPointerDownLate,{queue:Jt.Late}),this.context.input.addEventListener("pointerup",this.onPointerUpEarly,{queue:Jt.Early}),window.addEventListener("touchstart",this.touchStart,{passive:!1}),window.addEventListener("touchmove",this.touchMove,{passive:!1}),window.addEventListener("touchend",this.touchEnd,{passive:!1}))}disable(){this._enabled&&(this._enabled=!1,this.context.input.removeEventListener("pointerdown",this.onPointerDownEarly,{queue:Jt.Early}),this.context.input.removeEventListener("pointerdown",this.onPointerDownLate,{queue:Jt.Late}),this.context.input.removeEventListener("pointerup",this.onPointerUpEarly,{queue:Jt.Early}),window.removeEventListener("touchstart",this.touchStart),window.removeEventListener("touchmove",this.touchMove),window.removeEventListener("touchend",this.touchEnd))}onPointerDownEarly=e=>{this.isActive&&e.stopPropagation()};onPointerDownLate=e=>{e.used?this.currentlyUsedPointerIds.add(e.pointerId):this.currentlyUsedPointerIds.size<=0&&this.currentlyUnusedPointerIds.add(e.pointerId)};onPointerUpEarly=e=>{this.currentlyUsedPointerIds.delete(e.pointerId),this.currentlyUnusedPointerIds.delete(e.pointerId)};prev=new Map;_didMultitouch=!1;touchStart=e=>{if(!e.defaultPrevented)for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t],n=exports.DeviceUtilities.isAndroidDevice()&&i.clientY<window.innerHeight*.1;this.prev.has(i.identifier)||this.prev.set(i.identifier,{ignore:n,x:0,z:0,screenx:0,screeny:0});const o=this.prev.get(i.identifier);if(o){const r=this.getPositionOnPlane(i.clientX,i.clientY);o.x=r.x,o.z=r.z,o.screenx=i.clientX,o.screeny=i.clientY}}};touchEnd=e=>{e.touches.length<=0&&(this._didMultitouch=!1);for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t];this.prev.delete(i.identifier)}};touchMove=e=>{if(!e.defaultPrevented&&this.isActive){if(e.touches.length===1){if(this._didMultitouch)return;const t=e.touches[0],i=this.prev.get(t.identifier);if(!i||i.ignore)return;const n=this.getPositionOnPlane(t.clientX,t.clientY),o=n.x-i.x,r=n.z-i.z;if(o===0&&r===0)return;this.oneFingerDrag&&this.addMovement(o,r),i.x=n.x,i.z=n.z,i.screenx=t.clientX,i.screeny=t.clientY;return}else if(e.touches.length===2){this._didMultitouch=!0;const t=e.touches[0],i=e.touches[1],n=this.prev.get(t.identifier),o=this.prev.get(i.identifier);if(!n||!o)return;if(this.twoFingerRotate){const r=Math.atan2(t.clientY-i.clientY,t.clientX-i.clientX),a=Math.atan2(n.screeny-o.screeny,n.screenx-o.screenx),l=r-a;Math.abs(l)>.001&&this.addRotation(l)}if(this.twoFingerScale){const r=t.clientX-i.clientX,a=t.clientY-i.clientY,l=Math.sqrt(r*r+a*a),h=n.screenx-o.screenx,d=n.screeny-o.screeny,u=Math.sqrt(h*h+d*d),p=l-u;Math.abs(p)>2&&this.addScale(p)}n.screenx=t.clientX,n.screeny=t.clientY,o.screenx=i.clientX,o.screeny=i.clientY}}};_raycaster=new c.Raycaster;_intersection=new c.Vector3;_screenPos=new c.Vector3;getPositionOnPlane(e,t){const i=this.context.mainCamera;return this._screenPos.x=e/window.innerWidth*2-1,this._screenPos.y=-(t/window.innerHeight)*2+1,this._screenPos.z=1,this._screenPos.unproject(i),this._raycaster.set(i.position,this._screenPos.sub(i.position)),this._raycaster.ray.intersectPlane(this.plane,this._intersection),this._intersection}addMovement(e,t){e/=this._scale,t/=this._scale,e*=this.factor,t*=this.factor,this.offset.elements[12]+=e,this.offset.elements[14]+=t,(e!==0||t!==0)&&(this._hasChanged=!0)}_tempMatrix=new c.Matrix4;addScale(e){e/=window.innerWidth,e*=-1,this._scale*=1+e,this._tempMatrix.makeScale(1-e,1-e,1-e),this.offset.premultiply(this._tempMatrix),e!==0&&(this._hasChanged=!0)}addRotation(e){e*=-1,this._tempMatrix.makeRotationY(e),this.offset.premultiply(this._tempMatrix),e!==0&&(this._hasChanged=!0)}}const Qs=x("debugautosync"),Kf=Symbol("syncerId");class HO{_syncers={};getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];const t=new GO(e);return t[Kf]=e.guid,this._syncers[t[Kf]]=t,t}removeSyncer(e){delete this._syncers[e[Kf]]}}const zg=new HO;class GO{comp;constructor(e){this.comp=e}hasChanges=!1;changedProperties={};get networkingKey(){return this.comp.guid}_isReceiving=!1;_isInit=!1;init(e){if(this._isInit)return;this._isInit=!0,this.comp=e,this.comp.context.post_render_callbacks.push(this.onHandleSending),this.comp.context.connection.beginListen(this.networkingKey,this.onHandleReceiving);const t=this.comp.context.connection.tryGetState(this.comp.guid);t&&this.onHandleReceiving(t)}destroy(){this._isInit&&(this.comp.context.post_render_callbacks.splice(this.comp.context.post_render_callbacks.indexOf(this.onHandleSending),1),this.comp.context.connection.stopListen(this.networkingKey,this.onHandleReceiving),this.comp=null,this._isInit=!1)}notifyChanged(e,t){this._isReceiving||(Qs&&console.log("Property changed: "+e,t),this.hasChanges=!0,this.changedProperties[e]=t)}onHandleSending=()=>{if(!this.hasChanges)return;this.hasChanges=!1;const e=this.comp.context.connection;if(!e||!e.isConnected||!e.isInRoom){for(const t in this.changedProperties)delete this.changedProperties[t];return}for(const t in this.changedProperties){const i=this.changedProperties[t];Qs&&console.log("SEND",this.comp.guid,this.networkingKey),e.send(this.networkingKey,{guid:this.comp.guid,property:t,data:i},sn.Queued),delete this.changedProperties[t]}};onHandleReceiving=e=>{if(Qs&&console.log("SYNCFIELD RECEIVE",this.comp.name,this.comp.guid,e),!!this._isInit&&this.comp&&e.guid===this.comp.guid)try{this._isReceiving=!0,this.comp[e.property]=e.data}catch(t){console.error(t)}finally{this._isReceiving=!1}}}function qO(s,e){let t=e!==s;return!t&&s&&e&&(Array.isArray(s)&&Array.isArray(e)||typeof s=="object"&&typeof e=="object")&&(t=!0),t}const sc=Symbol("AutoSyncHandler");function XO(s){if(s[sc])return s[sc];const e=zg.getOrCreateSyncer(s);return e?.init(s),s[sc]=e,e}function QO(s){const e=s[sc];e&&(zg.removeSyncer(e),e.destroy(),delete s[sc])}const Ng=function(s=null){return function(e,t){let i="";typeof t=="string"?i=t:i=t.name;let n=null,o;typeof s=="string"?o=e[s]:typeof s=="function"&&(o=s),o==null&&(T()||Qs)&&s!=null&&console.warn('syncField: no callback function found for property "'+i+'"','"'+s+'"');const r=e,a=r.__internalAwake;if(typeof a!="function"){(Qs||T())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+e?.constructor?.name+'" is not supported',e);return}Qs&&console.log(i);const l=Symbol(i);r.__internalAwake=function(){if(this[l]!==void 0)return;if(this[l]=this[i],n=zg.getOrCreateSyncer(this),Object.getOwnPropertyDescriptor(this,i)?.set===void 0){let u=!1;Object.defineProperty(this,i,{set:function(p){const m=this[l];if(this[l]=p,u){(T()||Qs)&&console.warn("Recursive call detected",i);return}u=!0;try{const g=qO(p,m);Qs&&console.log("SyncField assignment",i,"changed?",g,p,o),g&&o?.call(this,p,m)!==!1&&XO(this)?.notifyChanged(i,p)}finally{u=!1}},get:function(){return this[l]},configurable:!0,enumerable:!0})}n?.init(this),a.call(this)};const h=r.__internalDestroy;r.__internalDestroy=function(){QO(this),h.call(this)}}};var YO=Object.defineProperty,Eu=(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&&YO(e,t,n),n};const Ft=x("debugplayersync"),Ru=class Aw extends E{static async setupFrom(e,t){const i=K.getOrCreateFromUrl(e);if(!i.asset){const r=await i.loadAssetAsync();r&&S.getOrAddComponent(r,Ui)}const n=new Aw;n._internalInit(t),n.asset=i;const o=new c.Object3D;return o.guid=e,S.addComponent(o,n),n}autoSync=!0;asset;onPlayerSpawned;_localInstance;awake(){this.watchTabVisible(),this.onPlayerSpawned||(this.onPlayerSpawned=new oe)}onEnable(){this.context.connection.beginListen(Y.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(Y.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Y.LeftRoom,this.destroyInstance),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(Y.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(Y.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Y.LeftRoom,this.destroyInstance)}onJoinedRoom=()=>{Ft&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()};async getInstance(){if(this._localInstance)return this._localInstance;if(Ft&&console.log("PlayerSync.createInstance",this.asset?.url),!this.asset?.asset&&!this.asset?.url)return console.error('PlayerSync: can not create an instance because "asset" is not set and or has no URL!'),null;this.gameObject.guid||console.warn("PlayerSync: gameObject has no guid! This might cause issues with syncing the player state."),this._localInstance=this.asset?.instantiateSynced({parent:this.gameObject,deleteOnDisconnect:!0},!0);const e=await this._localInstance;if(e){const t=S.getComponentsInChildren(e,Ui);if(Ft&&console.log(`PlayerSync.createInstance: found ${t?.length} PlayerState components. Owner: ${this.context.connection.connectionId}`),t?.length){for(const i of t)i.owner=this.context.connection.connectionId;this.onPlayerSpawned?.invoke(e)}else this._localInstance=void 0,console.error("<strong>Failed finding PlayerState on "+this.asset?.url+"</strong>: please make sure the asset has a PlayerState component!"),S.destroySynced(e)}else this._localInstance=void 0,console.warn("PlayerSync: failed instantiating asset!");return this._localInstance}destroyInstance=()=>{this._localInstance?.then(e=>{Ft&&console.log("PlayerSync.destroyInstance",e),Bc(e,this.context.connection,!0,{saveInRoom:!1})}),this._localInstance=void 0};watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=Ui.all.length-1;t>=0;t--){const i=Ui.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}};Eu([f()],Ru.prototype,"autoSync");Eu([f(K)],Ru.prototype,"asset");Eu([f(oe)],Ru.prototype,"onPlayerSpawned");let Vg=Ru;var Dw=(s=>(s.OwnerChanged="ownerChanged",s))(Dw||{});const nm=class pt extends E{static _all=[];static get all(){return pt._all}static _local=[];static get local(){return pt._local}static getFor(e){if(e instanceof c.Object3D)return S.getComponentInParent(e,pt);if(e instanceof E)return S.getComponentInParent(e.gameObject,pt)}static isLocalPlayer(e){return pt.getFor(e)?.isLocalPlayer??!1}static _callbacks={};static addEventListener(e,t){return this._callbacks[e]||(this._callbacks[e]=[]),this._callbacks[e].push(t),t}static removeEventListener(e,t){if(!this._callbacks[e])return;const i=this._callbacks[e].indexOf(t);i>=0&&this._callbacks[e].splice(i,1)}static dispatchEvent(e,t){if(this._callbacks[e])for(const i of this._callbacks[e])i(t)}onOwnerChangeEvent=new oe;onFirstOwnerChangeEvent=new oe;hasOwner=!1;owner;dontDestroy=!1;get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(e,t){Ft&&console.log(`PlayerSync.onOwnerChange: ${t} → ${e} (me: ${this.context.connection.connectionId})`);const i=pt._local.indexOf(this);i>=0&&pt._local.splice(i,1);const n={playerState:this,oldValue:t,newValue:e};if(this.hasOwner||(this.hasOwner=!0,this.onFirstOwnerChangeEvent?.invoke(n)),this.onOwnerChangeEvent?.invoke(n),this.owner===this.context.connection.connectionId){pt._local.push(this);const r=new CustomEvent("local-owner-changed",{detail:n});this.dispatchEvent(r)}const o=new CustomEvent("owner-changed",{detail:n});this.dispatchEvent(o),pt.dispatchEvent("ownerChanged",o)}awake(){pt.all.push(this),Ft&&console.log("Registered new PlayerState",this.guid,pt.all.length-1,pt.all),this.context.connection.beginListen(Y.UserLeftRoom,this.onUserLeftRoom)}async start(){Ft&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await fs(300),this.context.connection.userIsInRoom(this.owner)==!1&&(Ft&&console.log(`PlayerSync.start → doDestroy "${this.name}" because user "${this.owner}" is not in room anymore...`,"Currently in room:",...this.context.connection.usersInRoom()),this.doDestroy())):this.owner||(Ft&&console.warn("PlayerState.start → owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?Ft&&console.warn("PlayerState.start → owner is still undefined but dontDestroy is set to true",this.name):(Ft&&console.warn(`PlayerState.start → owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):Ft&&console.log("PlayerState.start → owner is assigned",this.owner)},2e3))}doDestroy(){Ft&&console.log("PlayerSync.doDestroy → syncDestroy",this.name),Bc(this.gameObject,this.context.connection,!0,{saveInRoom:!1})}onDestroy(){if(Ft&&console.warn("PlayerState.onDestroy",this.owner),this.context.connection.stopListen(Y.UserLeftRoom,this.onUserLeftRoom),pt.all.splice(pt.all.indexOf(this),1),this.isLocalPlayer){const e=pt._local.indexOf(this);e>=0&&pt._local.splice(e,1)}}onUserLeftRoom=e=>{if(e.userId===this.owner){Ft&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}}};Eu([Ng(nm.prototype.onOwnerChange)],nm.prototype,"owner");let Ui=nm;var KO=Object.defineProperty,Ga=(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&&KO(e,t,n),n};class Hn extends E{position="bottom";showNeedleLogo=!1;showSpatialMenu;createFullscreenButton;createMuteButton;createQRCodeButton;onEnable(){this.applyOptions()}applyOptions(){this.context.menu.setPosition(this.position),this.context.menu.showNeedleLogo(this.showNeedleLogo),this.createFullscreenButton===!0&&this.context.menu.showFullscreenOption(!0),this.createMuteButton===!0&&this.context.menu.showAudioPlaybackOption(!0),this.showSpatialMenu===!0&&this.context.menu.showSpatialMenu(this.showSpatialMenu),this.createQRCodeButton===!0&&(exports.DeviceUtilities.isMobileDevice()||this.context.menu.showQRCodeButton(!0))}}Ga([f()],Hn.prototype,"position");Ga([f()],Hn.prototype,"showNeedleLogo");Ga([f()],Hn.prototype,"showSpatialMenu");Ga([f()],Hn.prototype,"createFullscreenButton");Ga([f()],Hn.prototype,"createMuteButton");Ga([f()],Hn.prototype,"createQRCodeButton");var ZO=Object.defineProperty,$g=(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&&ZO(e,t,n),n};const _l=x("debugwebxr"),lb=new c.Quaternion().setFromAxisAngle(new c.Vector3(0,1,0),Math.PI);class ao extends E{head;leftHand;rightHand;_leftHandMeshes;_rightHandMeshes;_syncTransforms;async onEnterXR(e){if(!this.activeAndEnabled)return;_l&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const t=Ui.getFor(this);if(t?.owner){const i=this.gameObject.addComponent(Pe);i.avatar=this.gameObject,i.connectionId=t.owner,this.context.players.setPlayerView(t.owner,this.head?.asset,us.Headset)}else this.context.connection.isConnected?console.error("No player state found for avatar",this):t&&!this.context.connection.isConnected&&(t.dontDestroy=!0)}onLeaveXR(e){const t=this.gameObject.getComponent(Pe);t&&t.destroy()}onUpdateXR(e){if(!this.activeAndEnabled)return;const t=Ui.isLocalPlayer(this);if(!t)return;const i=e.xr;if(i.rig&&i.rig.gameObject!==this.gameObject.parent&&(this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),this.gameObject.scale.set(1,1,1),i.rig.gameObject.add(this.gameObject)),this._syncTransforms&&t)for(const l of this._syncTransforms)l.fastMode=!0,l.isOwned()||l.requestOwnership();if(this.head&&this.context.mainCamera){const l=this.head.asset;if(l.position.copy(this.context.mainCamera.position),l.position.x*=-1,l.position.z*=-1,l.quaternion.copy(this.context.mainCamera.quaternion),l.quaternion.x*=-1,this.context.time.frameCount%10===0&&this.head.asset){const h=S.getComponentsInChildren(this.head.asset,Li);for(const d of h)d.enabled=!1,d.gameObject.visible=!1}}const n=e.xr.leftController,o=this.leftHand?.asset;n&&o?(o.position.copy(n.gripPosition),o.quaternion.copy(n.gripQuaternion),o.quaternion.multiply(lb),o.visible=n.isTracking,this.updateHandVisibility(n,o,this._leftHandMeshes)):o&&o.visible&&(o.visible=!1);const r=e.xr.rightController,a=this.rightHand?.asset;r&&a?(a.position.copy(r.gripPosition),a.quaternion.copy(r.gripQuaternion),a.quaternion.multiply(lb),a.visible=r.isTracking,this.updateHandVisibility(r,a,this._rightHandMeshes)):a&&a.visible&&(a.visible=!1)}onBeforeRender(){this.context.xr&&this.context.time.frame%10===0&&this.updateRemoteAvatarVisibility()}updateHandVisibility(e,t,i){if(i){const n=e.model&&e.model.visible&&e.model!==t;i.forEach(o=>{ss(o,!n)})}}updateRemoteAvatarVisibility(){if(this.context.connection.isConnected){const e=Ui.getFor(this);if(e&&e.isLocalPlayer==!1){const t=G.getXRSync(this.context);if(t&&t.hasState(e.owner)){this.tryFindAvatarObjectsIfMissing();const i=this.leftHand?.asset;i&&(i.visible=t?.isTracking(e.owner,"left")??!1);const n=this.rightHand?.asset;n&&(n.visible=t?.isTracking(e.owner,"right")??!1)}if(this.head?.asset){const i=S.getComponentsInChildren(this.head.asset,Li);for(const n of i)n.enabled=!1,n.gameObject.visible=!0}}}}tryFindAvatarObjectsIfMissing(){if(!this.head||!this.leftHand||!this.rightHand){const e={head:this.head,leftHand:this.leftHand,rightHand:this.rightHand};Ev.tryFindAvatarObjects(this.gameObject,this.sourceId||"",e),e.head&&(this.head=e.head),e.leftHand&&(this.leftHand=e.leftHand),e.rightHand&&(this.rightHand=e.rightHand)}}async prepareAvatar(){if(this.tryFindAvatarObjectsIfMissing(),this.head)this.head instanceof c.Object3D&&(this.head=new K("",this.sourceId,this.head));else{const e=new c.Object3D;e.name="Head";const t=po.createPrimitive(ja.Cube);e.add(t),this.gameObject.add(e),this.head=new K("",this.sourceId,e),_l&&console.log("Create head",e)}if(this.rightHand)this.rightHand instanceof c.Object3D&&(this.rightHand=new K("",this.sourceId,this.rightHand));else{const e=new c.Object3D;e.name="Right Hand",this.gameObject.add(e),this.rightHand=new K("",this.sourceId,e),_l&&console.log("Create right hand",e)}if(this.leftHand)this.leftHand instanceof c.Object3D&&(this.leftHand=new K("",this.sourceId,this.leftHand));else{const e=new c.Object3D;e.name="Left Hand",this.gameObject.add(e),this.leftHand=new K("",this.sourceId,e),_l&&console.log("Create left hand",e)}await this.loadAvatarObjects(this.head,this.leftHand,this.rightHand),this._leftHandMeshes=[],this.leftHand.asset?.traverse(e=>{e?.isMesh&&this._leftHandMeshes.push(e)}),this._rightHandMeshes=[],this.rightHand.asset?.traverse(e=>{e?.isMesh&&this._rightHandMeshes.push(e)}),Ui.isLocalPlayer(this.gameObject)&&(this._syncTransforms=S.getComponentsInChildren(this.gameObject,dn))}async loadAvatarObjects(e,t,i){const n=e.loadAssetAsync(),o=t.loadAssetAsync(),r=i.loadAssetAsync(),a=new Array;n&&a.push(n),o&&a.push(o),r&&a.push(r);const l=await wm(a);_l&&console.log("Avatar loaded results:",l)}}$g([f(K)],ao.prototype,"head");$g([f(K)],ao.prototype,"leftHand");$g([f(K)],ao.prototype,"rightHand");var JO=Object.defineProperty,Tu=(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&&JO(e,t,n),n};const js=x("debugwebxr"),Bs=new Array;class ms extends E{createControllerModel=!0;createHandModel=!0;customLeftHand;customRightHand;static factory=new q.XRControllerModelFactory;supportsXR(e){return e==="immersive-vr"||e==="immersive-ar"}_models=new Array;async onXRControllerAdded(e){if(!(e.xr.isVR||e.xr.isPassThrough))return;console.debug("XR Controller Added",e.controller.side,e.controller.index);const{controller:i}=e;if(this.createControllerModel||this.createHandModel){if(i.hand){if(this.createHandModel){const n=await this.loadHandModel(this,i);if(!n||!i.connected||!i.isHand){n?.handObject&&Jr(n.handObject,!1),n?.handObject?.destroy();return}this._models.push({controller:i,model:n.handObject,handmesh:n.handmesh}),this._models.sort((o,r)=>o.controller.index-r.controller.index),this.scene.add(n.handObject),i.model=n.handObject}}else if(this.createControllerModel){const n=await i.getModelUrl();if(n){const o=await this.loadModel(i,n);if(!o||!i.connected||i.isHand)return;this._models.push({controller:i,model:o}),this._models.sort((r,a)=>r.controller.index-a.controller.index),this.scene.add(o),o.traverse(r=>{r.layers.set(2),r.matrixAutoUpdate=!1,r.updateMatrix()}),i.model=o}else i.targetRayMode!=="transient-pointer"&&console.warn("XRControllerModel: no model found for "+i.side)}}}onXRControllerRemoved(e){console.debug("XR Controller Removed",e.controller.side,e.controller.index);const t=this._models.findIndex(n=>n.controller===e.controller),i=this._models[t];i&&(this._models.splice(t,1),i.model&&(Jr(i.model,!1),i.model.destroy(),i.model=void 0))}onBeforeXR(e,t){this.createHandModel&&(this.customLeftHand||this.customRightHand)&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.includes("hand-tracking")||t.optionalFeatures.push("hand-tracking"))}onLeaveXR(e){for(const t of this._models)t&&(t.model&&(Jr(t.model,!1),t.model.destroy(),t.model=void 0),t.controller.model===t.model&&(t.controller.model=null));this._models.length=0}onBeforeRender(){if(G.active&&(js&&(Bs[0]=Date.now()),this.updateRendering(G.active),js)){const e=Date.now()-Bs[0];Bs.push(e),Bs.length>=30&&(Bs[0]=0,Bs.reduce((t,i)=>t+i,0)/Bs.length,Bs.length=0)}}updateRendering(e){for(let t=0;t<this._models.length;t++){const i=this._models[t];if(!i)continue;const n=i.controller;if(!n.connected){js&&console.warn("XRControllerModel.onUpdateXR: controller is not connected anymore",n.side,n.hand);continue}if(i.model&&!i.handmesh)i.model.matrixAutoUpdate=!1,i.model.matrix.copy(n.gripMatrix),i.model.visible=n.isTracking,e.rig?.gameObject.add(i.model);else if(n.inputSource.hand&&i.handmesh){const o=e.referenceSpace,r=this.context.renderer.xr.getHand(n.index);if(o&&e.frame.getJointPose){for(const a of n.inputSource.hand.values()){const l=r.joints[a.jointName];if(l){const h=n.getHandJointPose(a);if(h){const d=h.transform.position,u=h.transform.orientation;l.position.copy(d),l.quaternion.copy(u),l.matrixAutoUpdate=!1}l.visible=h!=null}}i.model&&(i.model.visible=n.isTracking,i.model.visible&&i.model.parent!==e.rig?.gameObject&&e.rig?.gameObject.add(i.model)),i.model?.visible&&(i.handmesh?.updateMesh(),i.model.matrixAutoUpdate=!1,i.model.matrix.identity(),i.model.applyMatrix4(pa))}}}}async loadModel(e,t){if(!e.connected)return console.warn("XRControllerModel.onXRControllerAdded: controller is not connected anymore",e.side),null;const n=await K.getOrCreate("",t).instantiate();return Jr(n),G.active?.isPassThrough&&n.traverseVisible(o=>{this.makeOccluder(o)}),n}async loadHandModel(e,t){const i=this.context,n=i.renderer.xr.getHand(t.index);n||(js?j.DrawLabel(t.rayWorldPosition,"No hand found for index "+t.index,.05,5):console.warn("No hand found for index "+t.index));const o=new q.GLTFLoader;ng(o,i),await qd(o,i,this.sourceId??"",this.sourceId??"");const r=wg(o);let a="";const l=t.side==="left"?this.customLeftHand:this.customRightHand;l?(a=l.url.split(".").slice(0,-1).join("."),o.setPath("")):(a=t.inputSource.handedness==="left"?"left":"right",o.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/"));const h=new c.Object3D;Jr(h);const d=new q.XRHandMeshModel(h,n,o.path,a,o,u=>{const p=r?.gltf;p?.scene.children?.length===0&&(p.scene.children[0]=u),r?.gltf&&cn().createBuiltinComponents(e.context,e.sourceId||a,r.gltf,null,r),u.traverse(m=>{m.layers.set(2),G.active?.isPassThrough&&!l&&this.makeOccluder(m),m instanceof c.Mesh&&se.NEEDLE_progressive.assignMeshLOD(m,0)}),t.connected||(js&&j.DrawLabel(t.rayWorldPosition,"Hand is loaded but not connected anymore",.05,5),u.removeFromParent())});if(js&&h.add(new c.AxesHelper(.5)),t.inputSource.hand){js&&console.log(t.inputSource.hand);for(const u of t.inputSource.hand.values())if(n.joints[u.jointName]===void 0){const p=new c.Group;p.matrixAutoUpdate=!1,p.visible=!0,n.joints[u.jointName]=p,n.add(p)}}else js&&j.DrawLabel(t.rayWorldPosition,"No inputSource.hand found for index "+t.index,.05,5);return{handObject:h,handmesh:d}}makeOccluder(e){if(e instanceof c.Mesh){let t=e.material;t instanceof c.Material&&(t=e.material=t.clone(),t.depthWrite=!0,t.depthTest=!0,t.colorWrite=!1,e.receiveShadow=!1,e.renderOrder=-100)}}}Tu([f()],ms.prototype,"createControllerModel");Tu([f()],ms.prototype,"createHandModel");Tu([f(K)],ms.prototype,"customLeftHand");Tu([f(K)],ms.prototype,"customRightHand");class Au extends E{}var ek=Object.defineProperty,bo=(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&&ek(e,t,n),n};const Zf=x("debugwebxr");class vi extends E{movementSpeed=1.5;rotationStep=30;useTeleport=!0;usePinchToTeleport=!0;useTeleportTarget=!1;useTeleportFade=!1;showRays=!0;showHits=!0;isXRMovementHandler=!0;xrSessionMode="immersive-vr";_didApplyRotation=!1;_didTeleport=!1;onUpdateXR(e){const t=e.xr.rig;if(!t?.gameObject||e.xr.isPassThrough)return;const i=e.xr.leftController,n=e.xr.rightController;i&&this.onHandleMovement(i,t.gameObject),n&&(this.onHandleRotation(n,t.gameObject),this.useTeleport&&this.onHandleTeleport(n,t.gameObject))}onLeaveXR(e){for(const t of this._lines)t.removeFromParent();for(const t of this._hitDiscs)t?.removeFromParent()}onBeforeRender(){this.context.xr?.running&&(this.showRays&&this.renderRays(this.context.xr),this.showHits&&this.renderHits(this.context.xr))}onHandleMovement(e,t){const i=e.getStick("xr-standard-thumbstick");if(i.x!=0||i.y!=0){const n=B(i.x,0,i.y);n.multiplyScalar(this.context.time.deltaTimeUnscaled*this.movementSpeed);const o=Le(t);n.multiplyScalar(o.x),n.applyQuaternion(e.xr.poseOrientation),n.y=0,n.applyQuaternion(t.worldQuaternion),T()&&Number.isNaN(n.x)&&console.error("Stick movement resulted in NaN",{stick:i,vec:n}),t.position.add(n),t.updateWorldMatrix(!1,!1);for(const r of t.children)r.updateWorldMatrix(!1,!1)}}onHandleRotation(e,t){if(e._isMxInk)return;const n=e.getStick("xr-standard-thumbstick").x;if(this._didApplyRotation)Math.abs(n)<.3&&(this._didApplyRotation=!1);else if(Math.abs(n)>.5){this._didApplyRotation=!0;const o=n>0?1:-1,r=Q(this.context.mainCamera).clone();t.rotateY(o*I.toRadians(this.rotationStep));const l=Q(this.context.mainCamera).clone().sub(r);l.y=0,t.position.sub(l)}}_teleportBuffer=new Array;onHandleTeleport(e,t){let i=0;if(e.hand&&this.usePinchToTeleport&&e.isTeleportGesture){const n=e.getPointerId("primary");if(n!=null&&this.context.input.getIsPointerIdInUse(n))return;const o=e.getGesture("pinch");o&&(i=o.value)}else i=e.getStick("xr-standard-thumbstick")?.y;if(this._didTeleport)i>=0&&i<.4?this._didTeleport=!1:i<0&&i>-.4&&(this._didTeleport=!1);else if(i>.8){this._didTeleport=!0;const n=this.context.physics.raycastFromRay(e.ray)[0];if(n&&n.object instanceof q.GroundedSkybox){const r=n.normal?.dot(B(0,1,0));if(r!==void 0&&r<.4)return}let o=n?.point;if(!o&&!this.useTeleportTarget){this._plane||(this._plane=new c.Plane(new c.Vector3(0,1,0),0));const r=t.worldPosition;this._plane.setFromNormalAndCoplanarPoint(new c.Vector3(0,1,0),r);const a=e.ray;o=r.clone(),this._plane.intersectLine(new c.Line3(a.origin,B(a.direction).multiplyScalar(1e4).add(a.origin)),o),o.distanceTo(r)>t.scale.x*10&&(o=null)}if(o){if(this.useTeleportTarget&&!S.getComponentInParent(n.object,Au))return;const r=o.clone();if(Zf&&j.DrawSphere(o,.025,16711680,5),this.context.mainCamera?.position){const l=this.context.xr?.getUserOffsetInRig();l&&(l.y=0,r.sub(l),Zf&&j.DrawWireSphere(l.add(r),.025,65280,5))}this._teleportBuffer.push(t.matrix.clone()),this._teleportBuffer.length>10&&this._teleportBuffer.shift(),this.useTeleportFade?e.xr.fadeTransition()?.then(()=>{t.worldPosition=r}):t.worldPosition=r}}else if(i<-.8&&(this._didTeleport=!0,this._teleportBuffer.length>0)){const n=this._teleportBuffer.pop();n&&n.decompose(t.position,t.quaternion,t.scale)}}_plane=null;_lines=[];_hitDiscs=[];_hitDistances=[];_lastHitDistances=[];renderRays(e){for(let t=0;t<this._lines.length;t++){const i=this._lines[t];i&&(i.visible=!1)}for(let t=0;t<e.controllers.length;t++){const i=e.controllers[t];let n=this._lines[t];if(!i.connected||!i.isTracking||!i.ray||i.targetRayMode==="transient-pointer"||!i.hasSelectEvent){n&&(n.visible=!1);continue}n||(n=this.createRayLineObject(),n.scale.z=.5,this._lines[t]=n),i.updateRayWorldPosition(),i.updateRayWorldQuaternion();const o=i.rayWorldPosition,r=i.rayWorldQuaternion;n.position.copy(o),n.quaternion.copy(r);const a=e.rigScale,l=this.usePinchToTeleport&&i.isTeleportGesture,h=this._lastHitDistances[t],d=this._hitDistances[t]!=null,u=h??a;n.scale.set(a,a,u),n.visible=!0,n.layers.disableAll(),n.layers.enable(2);let p=n.material.opacity;l?p=1:this.showHits&&u<e.rigScale*.5?p=0:i.getButton("primary")?.pressed?p=.5:p=d?.2:.1,n.material.opacity=I.lerp(n.material.opacity,p,this.context.time.deltaTimeUnscaled/.1),n.parent!==this.context.scene&&this.context.scene.add(n)}}renderHits(e){for(const t of this._hitDiscs){if(!t)continue;const i=t.controller;if(!i||!i.connected||!i.isTracking){t.visible=!1;continue}}for(let t=0;t<e.controllers.length;t++){const i=e.controllers[t];if(!i.connected||!i.isTracking||!i.ray||!i.hasSelectEvent)continue;let n=this._hitDiscs[t],o=!0;const r=i.getPointerId("primary");r!=null&&this.context.input.getIsPointerIdInUse(r)&&(n&&(n.visible=!1),this._hitDistances[t]=null,this._lastHitDistances[t]=0,o=!1);const a=this.context.time.smoothedFps>=59?1:10;if((this.context.time.frame+i.index)%a!==0&&(o=!1),!o){const d=this._hitDiscs[t];d&&d.visible&&d.hit&&this.updateHitPointerPosition(i,d,d.hit.distance);continue}const l=this.context.physics.raycastFromRay(i.ray,{testObject:this.hitPointRaycastFilter,precise:!1});let h=l.find(d=>this.usePinchToTeleport&&i.isTeleportGesture?!0:this.isObjectWithInteractiveComponent(d.object));if(h||(h=l[0]),n&&(n.controller=i,n.hit=h),this._hitDistances[t]=h?.distance||null,h){this._lastHitDistances[t]=h.distance;const d=e.rigScale??1;Zf&&(j.DrawWireSphere(h.point,.025*d,16711680),j.DrawLabel(B(0,.2,0).add(h.point),h.object.name,.02,0)),n||(n=this.createHitPointObject(),this._hitDiscs[t]=n),n.hit=h,n.visible=h.distance>d*.05;let u=.01*(d+h.distance);const p=i.getButton("primary")?.pressed;p&&(u*=1.1),n.scale.set(u,u,u),n.layers.set(2);let m=n.material.opacity;if(p?m=1:m=h.distance<.15*d?.2:.6,n.material.opacity=I.lerp(n.material.opacity,m,this.context.time.deltaTimeUnscaled/.1),n.visible){if(h.normal){this.updateHitPointerPosition(i,n,h.distance);const g=h.normal.applyQuaternion(fe(h.object));n.quaternion.setFromUnitVectors(tk,g)}else this.updateHitPointerPosition(i,n,h.distance);n.parent!==this.context.scene&&this.context.scene.add(n)}}else this._hitDiscs[t]&&(this._hitDiscs[t].visible=!1)}}isObjectWithInteractiveComponent(e,t=0){return Vd(e)||e.isUI===!0?!0:e.isScene?!1:e.parent?this.isObjectWithInteractiveComponent(e.parent,t+1):!1}updateHitPointerPosition(e,t,i){const n=B(e.rayWorldPosition);n.add(B(0,0,i-.01).applyQuaternion(e.rayWorldQuaternion)),t.position.lerp(n,this.context.time.deltaTimeUnscaled/.05)}hitPointRaycastFilter=e=>e.type==="SkinnedMesh"?"continue in children":!0;createHitPointObject(){const e=new c.Mesh(new c.SphereGeometry(.3,6,6),new c.MeshBasicMaterial({color:15658734,opacity:.7,transparent:!0,depthTest:!1,depthWrite:!1,side:c.DoubleSide}));return e.layers.disableAll(),e.layers.enable(2),e}createRayLineObject(){const e=new q.Line2;e.layers.disableAll(),e.layers.enable(2);const t=new q.LineGeometry;e.geometry=t;const i=new Float32Array(9);i.set([0,0,.02,0,0,.4,0,0,1]),t.setPositions(i);const n=new Float32Array(9);n.set([1,1,1,.1,.1,.1,0,0,0]),t.setColors(n);const o=new q.LineMaterial({color:16777215,vertexColors:!0,worldUnits:!0,linewidth:.004,transparent:!0,depthWrite:!1,blending:c.AdditiveBlending,dashed:!1});return e.material=o,e}}bo([f()],vi.prototype,"movementSpeed");bo([f()],vi.prototype,"rotationStep");bo([f()],vi.prototype,"useTeleport");bo([f()],vi.prototype,"usePinchToTeleport");bo([f()],vi.prototype,"useTeleportTarget");bo([f()],vi.prototype,"useTeleportFade");bo([f()],vi.prototype,"showRays");bo([f()],vi.prototype,"showHits");const tk=new c.Vector3(0,1,0);var ik=Object.defineProperty,ct=(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&&ik(e,t,n),n};const bl=x("debugwebxr"),nk=x("debugusdz"),et=class oa extends E{createVRButton=!0;createARButton=!0;createSendToQuestButton=!0;createQRCode=!0;useDefaultControls=!0;showControllerModels=!0;showHandModels=!0;usePlacementReticle=!0;customARPlacementReticle;usePlacementAdjustment=!0;arScale=1;useXRAnchor=!1;autoPlace=!1;autoCenter=!1;useQuicklookExport=!1;useDepthSensing=!1;useSpatialGrab=!0;defaultAvatar;_playerSync;_createdComponentsInSession=[];_usdzExporter;static activeWebXRComponent=null;awake(){G.getXRSync(this.context)}onEnable(){window.location.protocol!=="https:"&&ue('<a href="https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API" target="_blank">WebXR</a> only works on secure connections (https).'),navigator.xr?.isSessionSupported("immersive-ar").catch(()=>!1).then(e=>{const t=exports.DeviceUtilities.isVisionOS()&&!e;(this.useQuicklookExport||t)&&(S.findObjectOfType(an)||(bl&&console.log("WebXR: Adding USDZExporter"),this._usdzExporter=S.addComponent(this.gameObject,an),this._usdzExporter.objectToExport=this.context.scene,this._usdzExporter.autoExportAnimations=!0,this._usdzExporter.autoExportAudioSources=!0))}),this.handleCreatingHTML(),this.handleOfferSession(),this.defaultAvatar===!0&&(bl&&console.warn("WebXR: No default avatar set, using static default avatar"),this.defaultAvatar=new K("https://cdn.needle.tools/static/avatars/DefaultAvatar.glb")),this.defaultAvatar&&(this._playerSync=this.gameObject.getOrAddComponent(Vg),this._playerSync.autoSync=!1),this._playerSync&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,this._playerSync.onPlayerSpawned?.removeEventListener(this.onAvatarSpawned),this._playerSync.onPlayerSpawned?.addEventListener(this.onAvatarSpawned))}onDisable(){this._usdzExporter?.destroy(),this.removeButtons()}async handleOfferSession(){return this.createVRButton&&await G.isVRSupported()&&this.createVRButton?G.offerSession("immersive-vr","default",this.context):this.createARButton&&await G.isARSupported()&&this.createARButton?G.offerSession("immersive-ar","default",this.context):!1}get session(){return G.active??null}get sessionMode(){return G.activeMode??null}get arSessionRoot(){return this._activeWebARSessionRoot}async enterVR(e){return G.start("immersive-vr",e,this.context)}async enterAR(e){return G.start("immersive-ar",e,this.context)}exitXR(){G.stop()}_exitXRMenuButton;_previousXRState=0;_spatialGrabRaycaster;_activeWebARSessionRoot=null;get isActiveWebXR(){return!oa.activeWebXRComponent||oa.activeWebXRComponent===this}onBeforeXR(e,t){if(!this.isActiveWebXR){console.warn(`WebXR: another WebXR component is already active (${oa.activeWebXRComponent?.name}). This is ignored: ${this.name}`);return}if(this.activeAndEnabled===!1||this.destroyed){console.debug("[WebXR] onBeforeXR called on disabled or destroyed component");return}oa.activeWebXRComponent=this,e=="immersive-ar"&&this.useDepthSensing&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("depth-sensing"))}async onEnterXR(e){if(!this.isActiveWebXR)return;bl&&console.log("WebXR onEnterXR"),this._previousXRState=Vt.Global.Mask;const t=e.xr.isVR;if(Vt.Global.Set(t?Tn.VR:Tn.AR),e.xr.isAR){let i=S.findObjectOfType(Bi,this.context,!1);if(!i)if(this.usePlacementReticle){const n=new c.Object3D;for(const o of this.context.scene.children)n.add(o);this.context.scene.add(n),i=S.addComponent(n,Bi),this._createdComponentsInSession.push(i)}else(bl||T())&&console.warn("WebXR: No WebARSessionRoot found in scene and usePlacementReticle is disabled in WebXR component.");this._activeWebARSessionRoot=i,i&&(i.customReticle=this.customARPlacementReticle,i.arScale=this.arScale,i.arTouchTransform=this.usePlacementAdjustment,i.autoPlace=this.autoPlace,i.autoCenter=this.autoCenter,i.useXRAnchor=this.useXRAnchor)}this.useDefaultControls&&this.setDefaultMovementEnabled(!0),(this.showControllerModels||this.showHandModels)&&this.setDefaultControllerRenderingEnabled(!0),this.useSpatialGrab&&(this._spatialGrabRaycaster=S.findObjectOfType(cr)??void 0,this._spatialGrabRaycaster||(this._spatialGrabRaycaster=this.gameObject.addComponent(cr))),this.createLocalAvatar(e.xr),e.xr.isScreenBasedAR||(this._exitXRMenuButton=this.context.menu.appendChild({label:"Quit XR",onClick:()=>this.exitXR(),icon:"exit_to_app",priority:2e4}))}onUpdateXR(e){this.isActiveWebXR&&this._spatialGrabRaycaster&&(this._spatialGrabRaycaster.enabled=this.useSpatialGrab)}onLeaveXR(e){if(this._exitXRMenuButton?.remove(),!!this.isActiveWebXR){Vt.Global.Set(this._previousXRState),this._playerSync?.destroyInstance();for(const t of this._createdComponentsInSession)t.destroy();this._createdComponentsInSession.length=0,this._activeWebARSessionRoot=null,this.handleOfferSession(),Dc(1).then(()=>oa.activeWebXRComponent=null)}}setDefaultMovementEnabled(e){let t=this.gameObject.getComponent(vi);return!t&&e&&(t=this.gameObject.addComponent(vi),this._createdComponentsInSession.push(t)),t&&(t.enabled=e),t}setDefaultControllerRenderingEnabled(e){let t=this.gameObject.getComponent(ms);return!t&&e&&(t=this.gameObject.addComponent(ms),this._createdComponentsInSession.push(t),t.createControllerModel=this.showControllerModels,t.createHandModel==this.showHandModels),t&&(t.enabled=e),t}async createLocalAvatar(e){this._playerSync&&e.running&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,await this._playerSync.getInstance())}onAvatarSpawned=e=>{bl&&console.log("WebXR.onAvatarSpawned",e);let t=S.getComponentInChildren(e,ao);t??=S.addComponent(e,ao)};getButtonsContainer(){return this.getButtonsFactory()}getButtonsFactory(){return this._buttonFactory||(this._buttonFactory=no.getOrCreate()),this._buttonFactory}_buttonFactory;handleCreatingHTML(){if(this.createARButton||this.createVRButton||this.useQuicklookExport){if((exports.DeviceUtilities.isiOS()&&exports.DeviceUtilities.isSafari()||nk)&&this.useQuicklookExport){const e=S.findObjectOfType(an);if(!e||e&&e.allowCreateQuicklookButton){const t=this.getButtonsFactory().createQuicklookButton();this.addButton(t)}}if(this.createARButton){const e=this.getButtonsFactory().createARButton();this.addButton(e)}if(this.createVRButton){const e=this.getButtonsFactory().createVRButton();this.addButton(e)}}if(this.createSendToQuestButton&&!exports.DeviceUtilities.isQuest()&&G.isVRSupported().then(e=>{if(!e){const t=this.getButtonsFactory().createSendToQuestButton();this.addButton(t)}}),this.createQRCode){const e=Ua(Hn);if(e&&e.createQRCodeButton===!1)T()&&console.warn("WebXR: QRCode button is disabled in the Needle Menu component");else if(!exports.DeviceUtilities.isMobileDevice()){const t=ji.getOrCreate().createQRCode();this.addButton(t)}}}_buttons=[];addButton(e){this._buttons.push(e),this.context.menu.appendChild(e)}removeButtons(){for(const e of this._buttons)e.remove();this._buttons.length=0}};ct([f()],et.prototype,"createVRButton");ct([f()],et.prototype,"createARButton");ct([f()],et.prototype,"createSendToQuestButton");ct([f()],et.prototype,"createQRCode");ct([f()],et.prototype,"useDefaultControls");ct([f()],et.prototype,"showControllerModels");ct([f()],et.prototype,"showHandModels");ct([f()],et.prototype,"usePlacementReticle");ct([f(K)],et.prototype,"customARPlacementReticle");ct([f()],et.prototype,"usePlacementAdjustment");ct([f()],et.prototype,"arScale");ct([f()],et.prototype,"useXRAnchor");ct([f()],et.prototype,"autoPlace");ct([f()],et.prototype,"autoCenter");ct([f()],et.prototype,"useQuicklookExport");ct([f()],et.prototype,"useDepthSensing");ct([f()],et.prototype,"useSpatialGrab");ct([f(K)],et.prototype,"defaultAvatar");let Du=et;const Qh=x("debugusdzbehaviours");class Wg{get extensionName(){return"Behaviour"}behaviours=[];addBehavior(e){this.behaviours.push(e)}addAudioClip(e){if(!e||typeof e!="string")return"";const i="audio/"+Cr.getName(e);return this.audioClips.push({clipUrl:e,filesKey:i}),i}behaviourComponents=[];behaviourComponentsCopy=[];audioClips=[];audioClipsCopy=[];targetUuids=new Set;getAllTargetUuids(){return this.targetUuids}onBeforeBuildDocument(e){if(!e.root)return Promise.resolve();const t=[];return e.root.traverse(i=>{S.foreachComponent(i,n=>{const o=n;if(typeof o.createBehaviours=="function"||typeof o.beforeCreateDocument=="function"||typeof o.afterCreateDocument=="function"||typeof o.afterSerialize=="function"){this.behaviourComponents.push(o);const r=o.beforeCreateDocument?.call(o,this,e);r instanceof Promise&&t.push(r)}},!1)}),Qh&&console.log("onBeforeBuildDocument: all components",this.behaviourComponents),Promise.all(t)}onExportObject(e,t,i){for(const n of this.behaviourComponents)n.createBehaviours?.call(n,this,t,i)}onAfterBuildDocument(e){for(const u of this.behaviourComponents)typeof u.afterCreateDocument=="function"&&u.afterCreateDocument(this,e);this.behaviourComponentsCopy=this.behaviourComponents.slice(),this.behaviourComponents.length=0,this.audioClipsCopy=this.audioClips.slice(),this.audioClips.length=0;const t=new Set,i=new Set,n=new Set,o=new Set,r=Qh;let a=`graph LR
|
|
1291
1291
|
`,l="";function h(u){if(u instanceof Xo){r&&(a+=`subgraph Group_${u.id}
|
|
1292
1292
|
`);for(const p of u.actions)r&&(a+=`${u.id}[${u.id}] -- ${u.type},loops:${u.loops} --> ${p.id}[${p.id}]
|
|
1293
1293
|
`),h(p);r&&(a+=`end
|
|
@@ -1309,7 +1309,7 @@ dateFormat X
|
|
|
1309
1309
|
axisFormat %s
|
|
1310
1310
|
`;const p=Array.from(o),m=new Set;for(const v of p)if(v.affectedObjects&&typeof v.affectedObjects!="string"){if(Array.isArray(v.affectedObjects))for(const b of v.affectedObjects)m.add(b);else m.add(v.affectedObjects);r&&(u+=`section ${v.animationName} (${v.id})
|
|
1311
1311
|
`,u+=`${v.id} : ${v.start}, ${v.duration}s
|
|
1312
|
-
`)}r&&o.size&&console.log(u);const g=new Set;for(const v of m){v.getPath||console.error("USDZExporter: Animation target object has no getPath method. This is likely a bug",v);let b=v.getPath();b.startsWith("<")&&(b=b.substring(1)),b.endsWith(">")&&(b=b.substring(0,b.length-1)),g.add({path:b,obj:v})}const _=Array.from(g).sort((v,b)=>v.path.length-b.path.length),y=new Array;for(let v=0;v<_.length;v++)for(let b=v+1;b<_.length;b++)if(_[b].path.startsWith(_[v].path)){const w=_[b],R=_[v];y.push({child:w.obj.displayName+" ("+w.path+")",parent:R.obj.displayName+" ("+R.path+")"})}y.length&&console.warn("USDZExporter: There are overlapping PlayAnimation actions. This can lead to undefined runtime behaviour when playing multiple animations. Please restructure the hierarchy so that animations don't overlap.",{overlappingTargets:y,playAnimationActions:o})}for(const u of new Set([...t,...i]))if(Array.isArray(u))for(const p of u)n.add(p.uuid);else n.add(u.uuid);Qh&&console.log("All Behavior trigger sources and action targets",t,i,n),this.targetUuids=new Set(n)}onAfterHierarchy(e,t){if(this.behaviours?.length){t.beginBlock('def Scope "Behaviors"');for(const i of this.behaviours)i.writeTo(this,e.document,t);t.closeBlock()}}async onAfterSerialize(e){Qh&&console.log("onAfterSerialize behaviours",this.behaviourComponentsCopy);for(const t of this.behaviourComponentsCopy)typeof t.afterSerialize=="function"&&(t.afterSerialize.constructor.name==="AsyncFunction"?await t.afterSerialize(this,e):t.afterSerialize(this,e));for(const{clipUrl:t,filesKey:i}of this.audioClipsCopy){if(e.files[i])return;const r=await(await(await fetch(t)).blob()).arrayBuffer(),a=new Uint8Array(r);e.files[i]=a}this.behaviourComponentsCopy.length=0,this.audioClipsCopy.length=0}}class Hg{get extensionName(){return"Physics"}onExportObject(e,t,i){const n=S.getComponents(e,Fe).filter(l=>l.enabled),o=S.getComponents(e,Hi).filter(l=>l.enabled&&!l.isTrigger);let r=n.length>0?n[0]:null;const a=o.length>0?o[0]:null;a&&!r&&(r=new Fe,r.isKinematic=!0),r&&t.addEventListener("serialize",(l,h)=>{if(r){if(l.appendLine(),l.beginBlock('def RealityKitComponent "RigidBody"',"{",!0),r.useGravity||l.appendLine("bool gravityEnabled = 0"),l.appendLine('uniform token info:id = "RealityKit.RigidBody"'),r.isKinematic&&l.appendLine('token motionType = "Kinematic"'),l.beginBlock('def RealityKitStruct "massFrame"',"{",!0),l.appendLine(`float m_mass = ${r.mass}`),l.beginBlock('def RealityKitStruct "m_pose"',"{",!0),l.appendLine(`float3 position = (${r.centerOfMass.x}, ${r.centerOfMass.y}, ${r.centerOfMass.z})`),l.closeBlock("}"),l.closeBlock("}"),o.length>0){const d=o[0];l.beginBlock('def RealityKitStruct "material"',"{",!0);const u=d.sharedMaterial;u&&u.dynamicFriction!==void 0&&l.appendLine(`double dynamicFriction = ${d.sharedMaterial?.dynamicFriction}`),u&&u.bounciness!==void 0&&l.appendLine(`double restitution = ${d.sharedMaterial?.bounciness}`),u&&u.staticFriction!==void 0&&l.appendLine(`double staticFriction = ${d.sharedMaterial?.staticFriction}`),l.closeBlock("}")}l.closeBlock("}")}}),a&&(t.addEventListener("serialize",(l,h)=>{l.beginBlock('def RealityKitComponent "Collider"',"{",!0),l.appendLine("uint group = 1"),l.appendLine('uniform token info:id = "RealityKit.Collider"'),l.appendLine("uint mask = 4294967295");const u=a.isTrigger?"Trigger":"Default";if(l.appendLine(`token type = "${u}"`),l.beginBlock('def RealityKitStruct "Shape"',"{",!0),a instanceof Na){const p=a;l.appendLine('token shapeType = "Sphere"'),l.appendLine(`float radius = ${p.radius}`)}else if(a instanceof xu){const p=a;l.appendLine('token shapeType = "Box"'),l.appendLine(`float3 extent = (${p.size.x}, ${p.size.y}, ${p.size.z})`)}else if(a instanceof ps){const p=a;l.appendLine('token shapeType = "Capsule"'),l.appendLine(`float radius = ${p.radius}`),l.appendLine(`float height = ${p.height}`)}else if(a instanceof yo&&a.sharedMesh?.geometry){const p=a.sharedMesh.geometry;p.boundingBox||p.computeBoundingBox();const m=a.sharedMesh.geometry.boundingBox;m&&(l.appendLine('token shapeType = "Box"'),l.appendLine(`float3 extent = (${m.max.x-m.min.x}, ${m.max.y-m.min.y}, ${m.max.z-m.min.z})`),console.log("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. MeshCollider will be exported as Box",a))}else console.warn("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. Ignoring collider:",a);l.beginBlock('def RealityKitStruct "pose"',"{",!0),l.closeBlock("}"),l.closeBlock("}"),l.closeBlock("}")}),o.length>1&&console.log("WARNING: Multiple colliders detected. visionOS / iOS can only support objects with a single collider, only exporting the first collider: ",a))}}const sk=x("debugshadowcomponents");te.__webpack_exports__Block.prototype.interactable={get(){return this.interactive},set(s){this.interactable=s}};class Ni extends E{isRoot(){return this.Root?.gameObject===this.gameObject}get canvas(){const e=this.Root;return e?.isCanvas?e:null}get Canvas(){return this.canvas}markDirty(){$t.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(e){this._shadowComponent=e}_shadowComponent=null;_controlsChildLayout=!0;get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}_root=void 0;get Root(){return this._root===void 0&&(this._root=S.getComponentInParent(this.gameObject,ih)),this._root}_parentComponent=void 0;__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0,this}onEnable(){super.onEnable()}addShadowComponent(e,t){if(!e)return;this.removeShadowComponent();const i=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=S.getComponentInParent(i,Ni),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e[hi]=this,this.setShadowComponentOwner(e);let n=!1;if(this.Root?.gameObject===this.gameObject)this.gameObject.add(e);else{const o=this._parentComponent.shadowComponent;o&&(o?.add(e),n=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),Uc&&e.add(new c.AxesHelper(.5)),this.onAfterAddedToScene(),n&&te.__webpack_exports__update(),sk&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(e){if(e&&(e[hi]===void 0||e[hi]===this)&&(e[hi]=this,e.children))for(const t of e.children)this.setShadowComponentOwner(t)}traverseOwnedShadowComponents(e,t,i){if(e&&e[hi]===t){i(e);for(const n of e.children)this.traverseOwnedShadowComponents(n,t,i)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}}class ih extends Ni{awake(){super.awake()}}var ok=Object.defineProperty,rk=Object.getOwnPropertyDescriptor,nh=(s,e,t,i)=>{for(var n=i>1?void 0:i?rk(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&&ok(e,t,n),n};const Jf=x("debugui"),ep=x("debuguilayout");class Lw{width;height}class Iw{x;y;width;height}const en=new c.Vector3,vl=new c.Matrix4,Yh=new c.Quaternion,qa=class jw extends Ni{get parent(){return this._parentRectTransform}get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}_anchoredPosition;get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new c.Vector2),this._anchoredPosition}set anchoredPosition(e){this._anchoredPosition=e}sizeDelta=new c.Vector2(100,100);pivot=new c.Vector2(.5,.5);anchorMin=new c.Vector2(0,0);anchorMax=new c.Vector2(1,1);minWidth;minHeight;get width(){let e=this.sizeDelta.x;if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const t=this._parentRectTransform.width,i=this.anchorMax.x-this.anchorMin.x;e=t*i,e+=this.sizeDelta.x}return this.minWidth!==void 0&&e<this.minWidth?this.minWidth:e}get height(){let e=this.sizeDelta.y;if(this.anchorMin.y!==this.anchorMax.y&&this._parentRectTransform){const t=this._parentRectTransform.height,i=this.anchorMax.y-this.anchorMin.y;e=t*i,e+=this.sizeDelta.y}return this.minHeight!==void 0&&e<this.minHeight?this.minHeight:e}lastMatrix;rectBlock;_transformNeedsUpdate=!1;_initialPosition;_parentRectTransform;_lastUpdateFrame=-1;awake(){super.awake(),this._lastUpdateFrame=-1,this._parentRectTransform=void 0,this.rectBlock=new c.Object3D,this.rectBlock.name=this.name,this.lastMatrix=new c.Matrix4,this._lastAnchoring=null,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,this._anchoredPosition||(this._anchoredPosition=new c.Vector2),ea(this,"_anchoredPosition",()=>{this.markDirty()}),ea(this,"sizeDelta",()=>{this.markDirty()}),ea(this,"pivot",()=>{this.markDirty()}),ea(this,"anchorMin",()=>{this.markDirty()}),ea(this,"anchorMax",()=>{this.markDirty()})}onEnable(){super.onEnable(),this.rectBlock||(this.rectBlock=new c.Object3D),this.lastMatrix||(this.lastMatrix=new c.Matrix4),this._lastAnchoring||(this._lastAnchoring=new c.Vector2),this._initialPosition||(this._initialPosition=new c.Vector3),this._anchoredPosition||(this._anchoredPosition=new c.Vector2),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,this.canvas?.registerTransform(this)}onDisable(){super.onDisable(),this.removeShadowComponent(),this.canvas?.unregisterTransform(this)}onParentRectTransformChanged(e){this._transformNeedsUpdate||this.onApplyTransform(ep?`${e.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(ep&&console.warn("RectTransform markDirty()",this.name),this._transformNeedsUpdate=!0,this._lastUpdateFrame=-1)}updateTransform(){(this._transformNeedsUpdate||!this.lastMatrix.equals(this.gameObject.matrix))&&this.canUpdate()&&this.onApplyTransform(this._transformNeedsUpdate?"Marked dirty":"Matrix changed")}canUpdate(){return this._transformNeedsUpdate&&this.activeAndEnabled&&this._lastUpdateFrame!==this.context.time.frame}onApplyTransform(e){if(this.context.time.frameCount===this._lastUpdateFrame)return;this._lastUpdateFrame=this.context.time.frameCount;const t=this.shadowComponent;if(!t)return;this.gameObject.parent?this._parentRectTransform=S.getComponentInParent(this.gameObject.parent,jw):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,ep&&console.warn("RectTransform → ApplyTransform",this.name+" because "+e),this.isRoot()?this.Root.screenspace||(t.rotation.y=Math.PI):(t.matrix.identity(),t.matrixAutoUpdate=!1,en.set(0,0,0),this.applyPivot(en),t.matrix.setPosition(en.x,en.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(Yh.copy(this.gameObject.quaternion),Yh.x*=-1,Yh.z*=-1,vl.makeRotationFromQuaternion(Yh),t.matrix.premultiply(vl)),en.set(0,0,0),this.applyAnchoring(en),this.canvas?.screenspace?en.z+=.1:en.z+=.01,vl.identity(),vl.setPosition(en.x,en.y,en.z),t.matrix.premultiply(vl),t.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const i=!0;for(const n of du(this.gameObject,Ni,i,1)){if(n===this||!n.activeAndEnabled)continue;const o=n;o.onParentRectTransformChanged&&o.onParentRectTransformChanged(this)}}_lastAnchoring;applyAnchoring(e){this._lastAnchoring||(this._lastAnchoring=new c.Vector2);const t=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=t.x,this.gameObject.position.y+=t.y,this._lastAnchoring.copy(this._anchoredPosition),e.x+=this._initialPosition.x-this.gameObject.position.x,e.y+=this._initialPosition.y-this.gameObject.position.y,e.z+=this._initialPosition.z-this.gameObject.position.z;const i=this._parentRectTransform;if(i){let n=0;const o=1-this.anchorMax.y-this.anchorMin.y;n-=i.height*.5*o,e.y+=n;let r=0;const a=1-this.anchorMax.x-this.anchorMin.x;r-=i.width*.5*a,e.x+=r}}applyPivot(e){if(this.pivot&&!this.isRoot()){const t=this.pivot.x-.5;e.x-=t*this.sizeDelta.x*this.gameObject.scale.x;const i=this.pivot.y-.5;e.y-=i*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){const e={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:0,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(e),e}ensureValidSize(e,t=1e-4){return e.width<=0&&(e.width=t),e.height<=0&&(e.height=1e-4),e}_createdBlocks=[];_createdTextBlocks=[];createNewBlock(e){e={...this.getBasicOptions(),...e},Jf&&console.log(this.name,e);const t=new te.__webpack_exports__Block(e);return this._createdBlocks.push(t),t}createNewText(e){Jf&&console.log(e),e={...this.getBasicOptions(),...e},Jf&&console.log(this.name,e);const t=new te.__webpack_exports__Text(e);return this._createdTextBlocks.push(t),t}};nh([f(c.Vector2)],qa.prototype,"anchoredPosition",1);nh([f(c.Vector2)],qa.prototype,"sizeDelta",2);nh([f(c.Vector2)],qa.prototype,"pivot",2);nh([f(c.Vector2)],qa.prototype,"anchorMin",2);nh([f(c.Vector2)],qa.prototype,"anchorMax",2);let un=qa;var ak=Object.defineProperty,Bw=(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&&ak(e,t,n),n};class Xa extends E{effectColor;effectDistance}Bw([f(ee)],Xa.prototype,"effectColor");Bw([f(c.Vector2)],Xa.prototype,"effectDistance");var lk=Object.defineProperty,ck=Object.getOwnPropertyDescriptor,Uw=(s,e,t,i)=>{for(var n=i>1?void 0:i?ck(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&lk(e,t,n),n};const Do={backgroundColor:new c.Color(1,1,1),backgroundOpacity:1,borderColor:new c.Color(1,1,1),borderOpacity:1},Gg=class zl extends Ni{get isGraphic(){return!0}get color(){return this._color||(this._color=new ee(1,1,1,1)),this._color}set color(e){(!this._color||this._color.r!==e.r||this._color.g!==e.g||this._color.b!==e.b||this._color.alpha!==e.alpha)&&(this._color||(this._color=new ee(1,1,1,1)),this._color.copy(e),this.onColorChanged())}_alphaFactor=1;setAlphaFactor(e){this._alphaFactor=e,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}sRGBColor=new c.Color(1,0,1);onColorChanged(){if(this.uiObject){this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),Do.backgroundColor=this.sRGBColor,Do.backgroundOpacity=this._color.alpha;const e=this.uiObject._simpleState__activeStates?.[0];if(e){const t=this.uiObject._simpleState__states?.[e];t&&("backgroundColor"in t&&(Do.backgroundColor=t.backgroundColor),"backgroundOpacity"in t&&(Do.backgroundOpacity=t.backgroundOpacity))}Do.backgroundOpacity*=this._alphaFactor,this.applyEffects(Do,this._alphaFactor),this.uiObject.set(Do),this.markDirty()}}get m_Color(){return this._color}raycastTarget=!0;uiObject=null;_color=null;_rect=null;_stateManager=null;get rectTransform(){if(this._rect||(this._rect=S.getComponent(this.gameObject,un)),!this._rect)throw new Error("Not Supported: Make sure to add a RectTransform component before adding a UI Graphic component.");return this._rect}onParentRectTransformChanged(){this.uiObject?.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this._rect=null,this.uiObject=null,this._stateManager=null,this._color&&(this._color=this._color.clone()),this}setState(e){this.makePanel(),this.uiObject&&(this.uiObject.setState(e),this?.markDirty())}setupState(e){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new te.SimpleStateBehavior(this.uiObject)),this.uiObject.setupState(e.state,e.attributes))}setOptions(e){this.makePanel(),this.uiObject&&this.uiObject.set(e)}awake(){super.awake(),this.makePanel(),ea(this,"_color",()=>KP(this,this.onColorChanged))}onEnable(){super.onEnable(),this.uiObject&&(this.rectTransform.shadowComponent?.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}_currentlyCreatingPanel=!1;makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;const t={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:.015};this.onBeforeCreate(t),this.applyEffects(t),this.onCreate(t),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated(),this.onColorChanged()}onBeforeCreate(e){}onCreate(e){this.uiObject=this.rectTransform.createNewBlock(e),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(e,t=1){const i=this.gameObject?.getComponent(Xa);i&&(i.effectDistance&&(e.borderWidth=Math.max(Math.abs(i.effectDistance.x),Math.abs(i.effectDistance.y))),i.effectColor&&(e.borderColor=i.effectColor,e.borderOpacity=i.effectColor.alpha*t))}static textureCache=new Map;async setTexture(e){if(this.setOptions({backgroundOpacity:0}),e){if(zl.textureCache.has(e))e=zl.textureCache.get(e);else if(!e.isRenderTargetTexture){const t=e.clone();t.colorSpace=c.LinearSRGBColorSpace,zl.textureCache.set(e,t),e=t}this.setOptions({backgroundImage:e,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}),se.NEEDLE_progressive.assignTextureLOD(e,0).then(t=>{t instanceof c.Texture&&(e&&zl.textureCache.set(e,t),this.setOptions({backgroundImage:t}),this.markDirty())})}else this.setOptions({backgroundImage:void 0,borderRadius:0,backgroundOpacity:this.color.alpha});this.markDirty()}onAfterAddedToScene(){super.onAfterAddedToScene(),this.shadowComponent&&(this.shadowComponent.offset=this.shadowComponent.position.z)}};Uw([f(ee)],Gg.prototype,"color",1);Uw([f()],Gg.prototype,"raycastTarget",2);let sh=Gg;class oh extends sh{_flippedObject=!1;onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var hk=Object.defineProperty,dk=Object.getOwnPropertyDescriptor,xs=(s,e,t,i)=>{for(var n=i>1?void 0:i?dk(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&hk(e,t,n),n};const Lo=x("debugtext");var Qe=(s=>(s[s.UpperLeft=0]="UpperLeft",s[s.UpperCenter=1]="UpperCenter",s[s.UpperRight=2]="UpperRight",s[s.MiddleLeft=3]="MiddleLeft",s[s.MiddleCenter=4]="MiddleCenter",s[s.MiddleRight=5]="MiddleRight",s[s.LowerLeft=6]="LowerLeft",s[s.LowerCenter=7]="LowerCenter",s[s.LowerRight=8]="LowerRight",s))(Qe||{}),Fw=(s=>(s[s.Normal=0]="Normal",s[s.Bold=1]="Bold",s[s.Italic=2]="Italic",s[s.BoldAndItalic=3]="BoldAndItalic",s))(Fw||{});class Tt extends sh{alignment=0;verticalOverflow=0;horizontalOverflow=0;lineSpacing=1;supportRichText=!1;font;fontStyle=0;setAlphaFactor(e){super.setAlphaFactor(e),this.uiObject?.set({fontOpacity:this.color.alpha*this.alphaFactor}),this.markDirty()}get text(){return this._text}set text(e){e!==this._text&&(this._text=e,this.feedText(this.text,this.supportRichText),this.markDirty())}set_text(e){this.text=e}get fontSize(){return this._fontSize}set fontSize(e){this._fontSize=e,this.uiObject?.set({fontSize:e})}sRGBTextColor=new c.Color(1,0,1);onColorChanged(){this.sRGBTextColor.copy(this.color),this.sRGBTextColor.convertLinearToSRGB(),this.uiObject?.set({color:this.sRGBTextColor,fontOpacity:this.color.alpha})}onParentRectTransformChanged(){super.onParentRectTransformChanged(),this.uiObject&&this.updateOverflow()}onBeforeCanvasRender(e){this.updateOverflow()}updateOverflow(){const e=this.uiObject?._overflow;e&&(e._needsUpdate=!0)}onCreate(e){Lo&&console.log(this),this.horizontalOverflow==1&&(e.whiteSpace="pre"),this.verticalOverflow==0&&(this.context.renderer.localClippingEnabled=!0,e.overflow="hidden"),this.horizontalOverflow==1&&this.verticalOverflow==0,e.lineHeight=this.lineSpacing,delete e.backgroundOpacity,delete e.backgroundColor,Lo&&(e.backgroundColor=16750848,e.backgroundOpacity=.5);const t=this.rectTransform;e={...e,...this.getTextOpts()},this.getAlignment(e),Lo&&(e.backgroundColor=Math.random()*16777215,e.backgroundOpacity=.1),this.uiObject=t.createNewText(e),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}_text="";_fontSize=12;_textMeshUi=null;getTextOpts(){const e=this.fontSize,t={color:this.color,fontOpacity:this.color.alpha,fontSize:e,fontKerning:"normal"};return this.setFont(t,this.fontStyle),t}onEnable(){super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&this.uiObject.addAfterUpdate(()=>{this.setShadowComponentOwner(this.uiObject),this.markDirty()}),setTimeout(()=>this.markDirty(),10),this.canvas?.registerEventReceiver(this)}onDisable(){super.onDisable(),this.canvas?.unregisterEventReceiver(this)}getAlignment(e){switch(e.flexDirection="column",this.alignment){case 0:case 3:case 6:e.textAlign="left";break;case 1:case 4:case 7:e.textAlign="center";break;case 2:case 5:case 8:e.textAlign="right";break}switch(this.alignment){default:case 0:case 1:case 2:e.alignItems="start";break;case 3:case 4:case 5:e.alignItems="center";break;case 6:case 7:case 8:e.alignItems="end";break}return e}feedText(e,t){if(Lo&&console.log("feedText",this.uiObject,e,t),!!this.uiObject)if(this._textMeshUi||(this._textMeshUi=[]),this.uiObject.children.length=0,!t||e.length===0)this.uiObject.textContent=e;else{let i=this.getNextTag(e);if(i){if(i.startIndex>0){for(let r=this.uiObject.children.length-1;r>=0;r--){const a=this.uiObject.children[r];a.isUI&&(this.uiObject.remove(a),a.clear())}const o=new te.__webpack_exports__Inline({textContent:e.substring(0,i.startIndex),color:"inherit"});this.uiObject.add(o)}}else{this.uiObject.textContent="",this.setOptions({textContent:e});return}const n=[];for(;i;){const o=this.getNextTag(e,i.endIndex),r={fontFamily:this.uiObject?.get("fontFamily"),color:"inherit",textContent:""};if(o){r.textContent=this.getText(e,i,o),this.handleTag(i,r,n);const a=new te.__webpack_exports__Inline(r);this.uiObject?.add(a)}else{r.textContent=e.substring(i.endIndex),this.handleTag(i,r,n);const a=new te.__webpack_exports__Inline(r);this.uiObject?.add(a)}i=o}}}_didHandleTextRenderOnTop=!1;handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const e=[],t=this.canvas,i={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let n=!1;if(this._textMeshUi)for(let o=0;o<this._textMeshUi.length;o++){if(e[o]===!0)continue;n=!0;const r=this._textMeshUi[o];r.textContent&&(Wd(r,i),e[o]=!0)}if(!n)break;yield}}handleTag(e,t,i){if(!e.isEndTag){if(e.type.includes("color")){const n=new tp(e,{color:t.color});if(i.push(n),e.type.length>6){const o=parseInt("0x"+e.type.substring(7));t.color=o}else t.color=new c.Color(1,1,1)}else if(e.type=="b"){this.setFont(t,1);const n=new tp(e,{fontWeight:700});i.push(n)}else if(e.type=="i"){this.setFont(t,2);const n=new tp(e,{fontStyle:"italic"});i.push(n)}}}getText(e,t,i){return e.substring(t.endIndex,i.startIndex)}getNextTag(e,t=0){const i=e.indexOf("<",t),n=e.indexOf(">",i);if(i>=0&&n>=0){const o=e.substring(i+1,n);return{type:o,startIndex:i,endIndex:n+1,isEndTag:o.startsWith("/")}}return null}setFont(e,t){if(!this.font)return;const i=this.font,n=this.getFamilyNameWithCorrectSuffix(i,t);Lo&&console.log("Selected font family:"+n);let o=te.__webpack_exports__FontLibrary.getFontFamily(n);switch(o||(o=te.__webpack_exports__FontLibrary.addFontFamily(n)),e.fontFamily=o,t){default:case 0:e.fontWeight=400,e.fontStyle="normal";break;case 1:e.fontWeight=700,e.fontStyle="normal";break;case 2:e.fontWeight=400,e.fontStyle="italic";break;case 3:e.fontStyle="italic",e.fontWeight=400}let r=o.getVariant(e.fontWeight,e.fontStyle);if(!r){let a=n;a?.endsWith("-msdf.json")||(a+="-msdf.json");let l=n;l?.endsWith(".png")||(l+=".png"),r=o.addVariant(e.fontWeight,e.fontStyle,a,l),r?.addEventListener("ready",()=>{this.markDirty()})}}getFamilyNameWithCorrectSuffix(e,t){(e.startsWith("https:")||e.startsWith("http:"))&&(e=new URL(e).pathname);const i=e.lastIndexOf("-");if(i<0)return e;const n=e.substring(i+1)?.toLowerCase();if(uk.includes(n))return Lo&&console.warn("Unsupported font style: "+n),e;const o=e.lastIndexOf("/");let r=e;o>=0&&(r=r.substring(o+1));const a=r[0]===r[0].toUpperCase(),l=e.substring(0,i>o?i:e.length);switch(Lo&&console.log("Select font: ",e,Fw[t],r,a,l),t){case 0:return a?l+"-Regular":l+"-regular";case 1:return a?l+"-Bold":l+"-bold";case 2:return a?l+"-Italic":l+"-italic";case 3:return a?l+"-BoldItalic":l+"-bolditalic";default:return e}}}xs([f()],Tt.prototype,"alignment",2);xs([f()],Tt.prototype,"verticalOverflow",2);xs([f()],Tt.prototype,"horizontalOverflow",2);xs([f()],Tt.prototype,"lineSpacing",2);xs([f()],Tt.prototype,"supportRichText",2);xs([f(URL)],Tt.prototype,"font",2);xs([f()],Tt.prototype,"fontStyle",2);xs([f()],Tt.prototype,"text",1);xs([f()],Tt.prototype,"fontSize",1);class tp{tag;previousValues;constructor(e,t){this.tag=e,this.previousValues=t}}const uk=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class ha{static global_id=0;static getId(){return this.global_id++}id;content="";font=[];pointSize=144;width;height;depth;wrapMode;horizontalAlignment;verticalAlignment;material;setDepth(e){return this.depth=e,this}setPointSize(e){return this.pointSize=e,this}setHorizontalAlignment(e){return this.horizontalAlignment=e,this}setVerticalAlignment(e){return this.verticalAlignment=e,this}constructor(e){this.id=e}writeTo(e,t){t.beginBlock(`def Preliminary_Text "${this.id}"`,"(",!1),t.appendLine('prepend apiSchemas = ["MaterialBindingAPI"]'),t.closeBlock(")"),t.beginBlock(),this.content&&t.appendLine(`string content = "${this.content}"`),(!this.font||this.font.length<=0)&&(this.font||=[],this.font?.push("sans-serif"));const i=this.font.map(n=>`"${n}"`).join(", ");t.appendLine(`string[] font = [ ${i} ]`),t.appendLine(`double pointSize = ${this.pointSize}`),typeof this.width=="number"&&t.appendLine(`double width = ${this.width}`),typeof this.height=="number"&&t.appendLine(`double height = ${this.height}`),typeof this.depth=="number"&&t.appendLine(`double depth = ${this.depth}`),this.wrapMode&&t.appendLine(`token wrapMode = "${this.wrapMode}"`),this.horizontalAlignment&&t.appendLine(`token horizontalAlignment = "${this.horizontalAlignment}"`),this.verticalAlignment&&t.appendLine(`token verticalAlignment = "${this.verticalAlignment}"`),this.material!==void 0&&t.appendLine(`rel material:binding = </StageRoot/Materials/${Mu(this.material)}>`),t.closeBlock()}}class qg{static singleLine(e,t,i){const n=new ha("text_"+ha.getId());return n.content=e,t&&(n.pointSize=t),i&&(n.depth=i),n}static multiLine(e,t,i,n,o,r){const a=new ha("text_"+ha.getId());return a.content=e,a.width=t,a.height=i,a.horizontalAlignment=n,a.verticalAlignment=o,r!==void 0&&(a.wrapMode=r),a}}const fk=new c.Matrix4().makeRotationY(Math.PI),pk=new c.Matrix4().makeScale(-1,1,-1);class Lu{get extensionName(){return"text"}exportText(e,t,i){const n=S.getComponent(e,Tt);if(!n)return;const o=S.getComponent(e,un);let r=100,a=100;o&&(r=o.width,a=o.height);const l=fk.clone();o&&l.premultiply(pk),t.setMatrix(l);const h=n.color.clone();t.material=new c.MeshStandardMaterial({color:h,emissive:h}),t.addEventListener("serialize",(d,u)=>{let p=n.text;p=p.replace(/\r/g,""),p=p.replace(/\n/g,"\\n");const m=qg.multiLine(p,r,a,"center","bottom","flowing");this.setTextAlignment(m,n.alignment),this.setOverflow(m,n),t.material&&(m.material=t.material),m.pointSize=this.convertToTextSize(n.fontSize),m.depth=.001,m.writeTo(void 0,d)})}convertToTextSize(e){return 1/.0502*144*e}setOverflow(e,t){t.horizontalOverflow?e.wrapMode="singleLine":e.wrapMode="flowing"}setTextAlignment(e,t){switch(t){case Qe.LowerLeft:case Qe.MiddleLeft:case Qe.UpperLeft:e.horizontalAlignment="left";break;case Qe.LowerCenter:case Qe.MiddleCenter:case Qe.UpperCenter:e.horizontalAlignment="center";break;case Qe.LowerRight:case Qe.MiddleRight:case Qe.UpperRight:e.horizontalAlignment="right";break}switch(t){case Qe.LowerLeft:case Qe.LowerCenter:case Qe.LowerRight:e.verticalAlignment="bottom";break;case Qe.MiddleLeft:case Qe.MiddleCenter:case Qe.MiddleRight:e.verticalAlignment="middle";break;case Qe.UpperLeft:case Qe.UpperCenter:case Qe.UpperRight:e.verticalAlignment="top";break}}}var mk=Object.defineProperty,Ge=(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&&mk(e,t,n),n};const cb=x("debuguilayout");class Mr{left=0;right=0;top=0;bottom=0;get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}Ge([f()],Mr.prototype,"left");Ge([f()],Mr.prototype,"right");Ge([f()],Mr.prototype,"top");Ge([f()],Mr.prototype,"bottom");class xi extends E{_rectTransform=null;get rectTransform(){return this._rectTransform}onParentRectTransformChanged(e){this._needsUpdate=!0}_needsUpdate=!1;get isDirty(){return this._needsUpdate}get isLayoutGroup(){return!0}updateLayout(){this._rectTransform&&(cb&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}childAlignment=0;reverseArrangement=!1;spacing=0;padding;minWidth=0;minHeight=0;flexibleHeight=0;flexibleWidth=0;preferredHeight=0;preferredWidth=0;start(){this._needsUpdate=!0}onEnable(){cb&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(un);const e=this.gameObject.getComponentInParent(Da);e&&e.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const e=this.gameObject.getComponentInParent(Da);e&&e.unregisterLayoutGroup(this)}set m_Spacing(e){e!==this.spacing&&(this._needsUpdate=!0,this.spacing=e)}get m_Spacing(){return this.spacing}}Ge([f()],xi.prototype,"childAlignment");Ge([f()],xi.prototype,"reverseArrangement");Ge([f()],xi.prototype,"spacing");Ge([f(Mr)],xi.prototype,"padding");Ge([f()],xi.prototype,"minWidth");Ge([f()],xi.prototype,"minHeight");Ge([f()],xi.prototype,"flexibleHeight");Ge([f()],xi.prototype,"flexibleWidth");Ge([f()],xi.prototype,"preferredHeight");Ge([f()],xi.prototype,"preferredWidth");class vo extends xi{childControlHeight=!0;childControlWidth=!0;childForceExpandHeight=!1;childForceExpandWidth=!1;childScaleHeight=!1;childScaleWidth=!1;onCalculateLayout(e){const t=this.primaryAxis,i=e.width;let n=i;const o=e.height;let r=o;n-=this.padding.horizontal,r-=this.padding.vertical,t==="x"?this.padding.horizontal:this.padding.vertical;const a=t==="x",l=a?"y":"x",h=a?this.childControlWidth:this.childControlHeight,d=a?this.childControlHeight:this.childControlWidth,u=a?this.childForceExpandWidth:this.childForceExpandHeight,p=a?this.childForceExpandHeight:this.childForceExpandWidth,m=a?r:n,g=a?i:o,_=.5*(a?this.childAlignment%3:Math.floor(this.childAlignment/3));let y=0;a?y+=this.padding.left:y+=this.padding.top;let v=0,b=0;for(let A=0;A<this.gameObject.children.length;A++){const D=this.gameObject.children[A],L=S.getComponent(D,un);L?.activeAndEnabled&&(b+=1,a?v+=L.width:v+=L.height)}let w=0;const R=this.spacing*(b-1);if(u||h){let A=0;a?A=n-=R:A=r-=R,b>0&&(w=A/b)}let M=0;M+=this.padding.left,M-=this.padding.right,_!==0&&(y=g-v,y*=_,y-=R*_,a?(y-=this.padding.right*_,y+=this.padding.left*(1-_),y<this.padding.left&&(y=this.padding.left)):(y-=this.padding.bottom*_,y+=this.padding.top*(1-_),y<this.padding.top&&(y=this.padding.top)));let O=1;for(let A=0;A<this.gameObject.children.length;A++){const D=this.gameObject.children[A],L=S.getComponent(D,un);if(L?.activeAndEnabled){L.pivot?.set(.5,.5),L.anchorMin.set(0,1),L.anchorMax.set(0,1);const N=i*.5+M*.5;L.anchoredPosition.x!==N&&(L.anchoredPosition.x=N);const $=o*-.5;L.anchoredPosition.y!==$&&(L.anchoredPosition.y=$),p&&d&&L.sizeDelta[l]!==m&&(L.sizeDelta[l]=m),u&&h&&L.sizeDelta[t]!==w&&(L.sizeDelta[t]=w);const k=a?L.width:L.height,z=k*.5;if(y+=z,u){const J=w*O-w*.5;J>y&&(y=J-w*.5+k+this.padding.left,y-=z)}let V=y;t==="y"&&(V=-V),L.anchoredPosition[t]!==V&&(L.anchoredPosition[t]=V),y+=z,y+=this.spacing,O+=1}}}}Ge([f()],vo.prototype,"childControlHeight");Ge([f()],vo.prototype,"childControlWidth");Ge([f()],vo.prototype,"childForceExpandHeight");Ge([f()],vo.prototype,"childForceExpandWidth");Ge([f()],vo.prototype,"childScaleHeight");Ge([f()],vo.prototype,"childScaleWidth");class Xg extends vo{get primaryAxis(){return"y"}}class Qg extends vo{get primaryAxis(){return"x"}}class Yg extends xi{onCalculateLayout(){}}var gk=Object.defineProperty,yk=Object.getOwnPropertyDescriptor,Gn=(s,e,t,i)=>{for(var n=i>1?void 0:i?yk(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&&gk(e,t,n),n},zw=(s=>(s[s.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",s[s.ScreenSpaceCamera=1]="ScreenSpaceCamera",s[s.WorldSpace=2]="WorldSpace",s[s.Undefined=-1]="Undefined",s))(zw||{});const ip=x("debuguilayout"),Vi=class Nw extends ih{get isCanvas(){return!0}get screenspace(){return this.renderMode!==2}set renderOnTop(e){e!==this._renderOnTop&&(this._renderOnTop=e,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop!==void 0?this._renderOnTop:!!(this.screenspace&&this._renderMode===0)}_renderOnTop;set depthWrite(e){this._depthWrite!==e&&(this._depthWrite=e,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}_depthWrite=!1;set doubleSided(e){this._doubleSided!==e&&(this._doubleSided=e,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}_doubleSided=!0;set castShadows(e){this._castShadows!==e&&(this._castShadows=e,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}_castShadows=!1;set receiveShadows(e){this._receiveShadows!==e&&(this._receiveShadows=e,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}_receiveShadows=!1;get renderMode(){return this._renderMode}set renderMode(e){this._renderMode!==e&&(this._renderMode=e,this.onRenderSettingsChanged())}_renderMode=-1;_rootCanvas;set rootCanvas(e){this._rootCanvas instanceof Nw||(this._rootCanvas=e)}get rootCanvas(){return this._rootCanvas}_scaleFactor=1;get scaleFactor(){return this._scaleFactor}set scaleFactor(e){this._scaleFactor=e}worldCamera;planeDistance=-1;awake(){this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,ip&&console.log("Canvas.Awake()",this.previousParent?.name+"/"+this.gameObject.name),super.awake()}start(){this.applyRenderSettings()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new c.Matrix4,this.applyRenderSettings(),document.addEventListener("resize",this._boundRenderSettingsChanged),this.context.pre_render_callbacks.push(this.onBeforeRenderRoutine),this.context.post_render_callbacks.push(this.onAfterRenderRoutine)}onDisable(){super.onDisable(),document.removeEventListener("resize",this._boundRenderSettingsChanged);const e=this.context.pre_render_callbacks.indexOf(this.onBeforeRenderRoutine);e!==-1&&this.context.pre_render_callbacks.splice(e,1);const t=this.context.post_render_callbacks.indexOf(this.onAfterRenderRoutine);t!==-1&&this.context.post_render_callbacks.splice(t,1)}_boundRenderSettingsChanged=this.onRenderSettingsChanged.bind(this);previousParent=null;_lastMatrixWorld=null;_rectTransforms=[];registerTransform(e){this._rectTransforms.push(e)}unregisterTransform(e){const t=this._rectTransforms.indexOf(e);t!==-1&&this._rectTransforms.splice(t,1)}_layoutGroups=new Map;registerLayoutGroup(e){const t=e.gameObject;this._layoutGroups.set(t,e)}unregisterLayoutGroup(e){const t=e.gameObject;this._layoutGroups.delete(t)}_receivers=[];registerEventReceiver(e){this._receivers.push(e)}unregisterEventReceiver(e){const t=this._receivers.indexOf(e);t!==-1&&this._receivers.splice(t,1)}async onEnterXR(e){this.screenspace?(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!1):(this.gameObject.visible=!1,await Dc(1).then(()=>{this.gameObject.visible=!0}))}onLeaveXR(e){this.screenspace&&(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!0)}onBeforeRenderRoutine=()=>{if(this.previousParent=this.gameObject.parent,(this.context.xr?.isVR||this.context.xr?.isPassThrough)&&this.screenspace){this.gameObject.visible=!1,this.gameObject.removeFromParent();return}this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),this.shadowComponent?.updateMatrixWorld(!0),this.shadowComponent?.updateWorldMatrix(!0,!0),this.invokeBeforeRenderEvents(),$t.ensureUpdateMeshUI(te.ThreeMeshUI,this.context))};onAfterRenderRoutine=()=>{if((this.context.xr?.isVR||this.context.xr?.isPassThrough)&&this.screenspace){this.previousParent?.add(this.gameObject);return}if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){this.screenspace?this.context.mainCamera?.add(this.gameObject):this.previousParent.add(this.gameObject);const e=this.context.renderer.autoClear,t=this.context.renderer.autoClearColor;this.context.renderer.autoClear=!1,this.context.renderer.autoClearColor=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),this.shadowComponent?.updateMatrixWorld(!0),this.invokeBeforeRenderEvents(),$t.ensureUpdateMeshUI(te.ThreeMeshUI,this.context,!0),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=e,this.context.renderer.autoClearColor=t,this.previousParent.add(this.gameObject)}this._lastMatrixWorld?.copy(this.gameObject.matrixWorld)};invokeBeforeRenderEvents(){for(const e of this._receivers)e.onBeforeCanvasRender?.(this)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new c.Matrix4);const e=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);ip&&e&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);for(const t of this._rectTransforms){e&&t.markDirty();let i=this._layoutGroups.get(t.gameObject);t.isDirty&&!i&&(i=t.gameObject.getComponentInParent(xi)),(t.isDirty||i?.isDirty)&&(ip&&console.log("CANVAS UPDATE ### "+t.name+" ##################################### "+this.context.time.frame),i?.updateLayout(),t.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}_updateRenderSettingsRoutine;onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),me.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),Wd(this.shadowComponent,this);for(const e of S.getComponentsInChildren(this.gameObject,Ni))Wd(e.shadowComponent,this)}}_activeRenderMode=-1;_lastWidth=-1;_lastHeight=-1;onUpdateRenderMode(e=!1){if(!e&&this._renderMode===this._activeRenderMode&&this._lastWidth===this.context.domWidth&&this._lastHeight===this.context.domHeight)return;this._activeRenderMode=this._renderMode;let t=this.context.mainCameraComponent,i=10;switch(t&&t.nearClipPlane>0&&t.farClipPlane>0&&(i=I.lerp(t.nearClipPlane,t.farClipPlane,.01)),this._renderMode===1&&(this.worldCamera&&(t=this.worldCamera),this.planeDistance>0&&(i=this.planeDistance)),this._renderMode){case 0:case 1:if(this._lastWidth=this.context.domWidth,this._lastHeight=this.context.domHeight,!t)return;const n=i+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-n,this.gameObject.quaternion.identity();const o=this.gameObject.getComponent(un);let r=!1;o.sizeDelta.x!==this.context.domWidth&&(r=!0),o.sizeDelta.y!==this.context.domHeight&&(r=!0);const a=t.fieldOfView*Math.PI/180,l=2*Math.tan(a/2)*Math.abs(n);this.gameObject.scale.x=l/this.context.domHeight,this.gameObject.scale.y=l/this.context.domHeight,this.gameObject.scale.z=.01,r&&(o.sizeDelta.x=this.context.domWidth,o.sizeDelta.y=this.context.domHeight,o?.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};Gn([f()],Vi.prototype,"renderOnTop",1);Gn([f()],Vi.prototype,"depthWrite",1);Gn([f()],Vi.prototype,"doubleSided",1);Gn([f()],Vi.prototype,"castShadows",1);Gn([f()],Vi.prototype,"receiveShadows",1);Gn([f()],Vi.prototype,"renderMode",1);Gn([f(Vi)],Vi.prototype,"rootCanvas",1);Gn([f()],Vi.prototype,"scaleFactor",1);Gn([f(ti)],Vi.prototype,"worldCamera",2);Gn([f()],Vi.prototype,"planeDistance",2);let Da=Vi;var _k=Object.defineProperty,bk=Object.getOwnPropertyDescriptor,Kg=(s,e,t,i)=>{for(var n=i>1?void 0:i?bk(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&&_k(e,t,n),n};class lo extends E{get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}get isCanvasGroup(){return!0}_alpha=1;interactable=!0;blocksRaycasts=!0;_isDirty=!1;markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),me.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}_buffer=[];applyChangesNow(){this._buffer.length=0;for(const e of S.getComponentsInChildren(this.gameObject,Ni,this._buffer)){const t=e;t.setAlphaFactor&&t.setAlphaFactor(this._alpha)}}}Kg([f()],lo.prototype,"alpha",1);Kg([f()],lo.prototype,"interactable",2);Kg([f()],lo.prototype,"blocksRaycasts",2);class Zg{get extensionName(){return"tmui"}onExportObject(e,t,i){const n=S.getComponent(e,Da);if(n&&n.enabled&&n.renderMode===zw.WorldSpace){const o=new Lu,r=S.getComponent(e,un),a=S.getComponent(e,lo),l=new Array;if(r){if(!S.isActiveSelf(e)){const u=S.isActiveSelf(e);S.setActive(e,!0),r.onEnable(),r.updateTransform(),l.push(()=>{r.onDisable(),S.setActive(e,u)})}e.traverse(u=>{if(!S.isActiveInHierarchy(u)){const p=S.isActiveSelf(u);S.setActive(u,!0);const m=S.getComponent(u,Ni);m&&(m.onEnable(),l.push(()=>{m.onDisable()}));const g=S.getComponent(u,un);g&&(g.onEnable(),g.updateTransform(),g.onApplyTransform(),l.push(()=>{g.onDisable()}));const _=S.getComponent(u,Tt);_&&(_.onEnable(),l.push(()=>{_.onDisable()})),l.push(()=>{S.setActive(u,p)})}}),r.width,r.height;const h=We.createEmpty(),d=r.shadowComponent;if(t.add(h),d){const u=d.matrix;h.setMatrix(u);const p=new Map,m=new Map;p.set(d,h),m.set(d,a?a.alpha:1),d.traverse(g=>{if(g===d)return;const _=We.createEmpty();_.setMatrix(g.matrix);const y=g.parent,v=!!y&&typeof y.textContent=="string"&&y.textContent.length>0;let b=m.get(y)||1;const w=S.getComponent(g,lo);if(w&&(b*=w.alpha),g instanceof c.Mesh&&v){const M=g[hi];M?o.exportText(M.gameObject,_,i):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",g)}if(g instanceof c.Mesh&&!v){const M=g.geometry.clone();M.scale(1,1,-1),this.flipWindingOrder(M),_.geometry=M;const O=new c.Color,A=g.material.opacity;O.copy(g.material.color),_.material=new c.MeshBasicMaterial({color:O,opacity:A*b,map:g.material.map,transparent:!0})}p.set(g,_),m.set(g,b);const R=p.get(y);if(!R){console.error("Error when exporting UI: shadow component parent not found!",g,g.parent);return}R.add(_)})}}for(const h of l)h()}}flipWindingOrder(e){const t=e.index.array;for(let i=0,n=t.length/3;i<n;i++){const o=t[i*3];t[i*3]=t[i*3+2],t[i*3+2]=o}e.index.needsUpdate=!0}}const Nl=x("debugusdz");function vk(s,e){const t=[],i=S.getComponentsInChildren(s,at),n=S.getComponentsInChildren(s,Et),o=new Array,r=new Array;if(e.injectImplicitBehaviours)for(const a of i){if(!a||!a.runtimeAnimatorController||!a.enabled)continue;const l=a.runtimeAnimatorController.activeState;if(!l||!l.motion||!l.motion.clip||l.motion.clip.tracks?.length<1||o.includes(a))continue;const h=new Sc;h.animator=a,h.stateName=l.name,h.trigger="start",h.name="PlayAnimationOnClick_implicitAtStart_"+h.stateName;const d=new c.Object3D;S.addComponent(d,h),r.push(d),o.push(a),s.add(d)}else for(const a of i){if(!a||!a.runtimeAnimatorController||!a.enabled)continue;Nl&&console.log(a);const l=[];for(const h of a.runtimeAnimatorController.enumerateActions()){Nl&&console.log(h);const d=h.getClip();l.includes(d)||l.push(d)}t.push({root:a.gameObject,clips:l})}if(e.injectImplicitBehaviours)for(const a of n){if(!a||!a.clip||!a.enabled||!a.playAutomatically||o.includes(a))continue;const l=new Sc;l.animation=a,l.stateName=a.clip.name,l.trigger="start",l.name="PlayAnimationOnClick_implicitAtStart_"+l.stateName;const h=new c.Object3D;S.addComponent(h,l),r.push(h),o.push(a),s.add(h)}else for(const a of n){Nl&&console.log(a);const l=[];for(const h of a.animations)l.includes(h)||l.push(h);t.push({root:a.gameObject,clips:l})}Nl&&t?.length>0&&console.log("USDZ Animation Clips without behaviours",t);for(const a of t)for(const l of a.clips)e.registerAnimation(a.root,l);return r}function wk(s,e){const t=S.getComponentsInChildren(s,_i),i=S.getComponentsInChildren(s,ro),n=new Array,o=new Array;Nl&&console.log({audioSources:t,playAudioOnClicks:i});for(const r of i){if(!r.target)continue;const a=t.indexOf(r.target);a>-1&&t.splice(a,1)}for(const r of t){if(!r||!r.clip||r.volume<=0||n.includes(r))continue;const a=new ro;a.target=r,a.name="PlayAudioOnClick_implicitAtStart_",a.trigger="start";const l=new c.Object3D;S.addComponent(l,a),console.log("implicit PlayAudioOnStart",l,a),o.push(l),n.push(r),s.add(l)}return o}function xk(s){return new bt("DisableAtStart",kt.sceneStartTrigger(),he.fadeAction(s,0,!1))}function hb(s,e){const t=s.domElement.shadowRoot.querySelector("link[rel='ar']");if(t)return t;const i=document.createElement("div");i.classList.add("menu"),i.classList.add("quicklook-menu"),i.style.display="none",i.style.visibility="hidden";const n=document.createElement("button");n.id="open-in-ar",e?(n.innerText="View in AR",n.title="View this scene in AR. The scene will be exported to USDZ and opened with Apple's QuickLook."):(n.innerText="View in AR",n.title="Download this scene for AR. Open the downloaded USDZ file to view it in AR using Apple's QuickLook."),i.appendChild(n);const o=document.createElement("a");o.id="needle-usdz-link",o.style.display="none",o.rel="ar",o.href="",o.target="_blank",i.appendChild(o);const r=document.createElement("img");return r.id="button",o.appendChild(r),s.domElement.shadowRoot.appendChild(i),o}var Sk=Object.defineProperty,wt=(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&&Sk(e,t,n),n};const ut=x("debugusdz"),Ck=x("debugusdzpruning");class Or{callToAction;checkoutTitle;checkoutSubtitle;callToActionURL}wt([f()],Or.prototype,"callToAction");wt([f()],Or.prototype,"checkoutTitle");wt([f()],Or.prototype,"checkoutSubtitle");wt([f()],Or.prototype,"callToActionURL");const ri=class Fo extends E{static beforeExport=new oe;static afterExport=new oe;static beforeLODExport=new oe;objectToExport=void 0;autoExportAnimations=!0;autoExportAudioSources=!0;exportFileName=void 0;customUsdzFile=void 0;customBranding;anchoringType="plane";maxTextureSize=2048;planeAnchoringAlignment="horizontal";interactive=!0;physics=!0;allowCreateQuicklookButton=!0;quickLookCompatible=!0;extensions=[];link;button;start(){ut&&(console.log("USDZExporter",this),console.log("Debug USDZ Mode. Press 'T' to export"),window.addEventListener("keydown",e=>{e.key==="t"&&this.exportAndOpen()})),this.objectToExport||(this.objectToExport=this.gameObject),!this.objectToExport?.children?.length&&!this.objectToExport?.isMesh&&(this.objectToExport=this.context.scene)}onEnable(){const e=exports.DeviceUtilities.supportsQuickLookAR(),t=exports.DeviceUtilities.isiOS()||exports.DeviceUtilities.isiPad();!this.button&&(ut||e||t)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=hb(this.context,e),this.link.addEventListener("message",this.lastCallback)),ut&&we("USDZ Exporter enabled: "+this.name),document.getElementById("open-in-ar")?.addEventListener("click",this.onClickedOpenInARElement),pc.registerExporter(this)}onDisable(){this.button?.remove(),this.link?.removeEventListener("message",this.lastCallback),ut&&we("USDZ Exporter disabled: "+this.name),document.getElementById("open-in-ar")?.removeEventListener("click",this.onClickedOpenInARElement),pc.unregisterExporter(this)}onClickedOpenInARElement=e=>{e.preventDefault(),this.exportAndOpen()};async exportAsync(){return this.exportAndOpen()}async exportAndOpen(){let e=this.exportFileName??this.objectToExport?.name??this.name;if(e+="-"+yw(),Un()||(e!==""&&(e+="-"),e+="MadeWithNeedle"),this.link||(this.link=hb(this.context,exports.DeviceUtilities.supportsQuickLookAR())),this.customUsdzFile)return ut&&console.log("Exporting custom usdz",this.customUsdzFile),this.openInQuickLook(this.customUsdzFile,e),null;if(!this.objectToExport)return console.warn("No object to export",this),null;Fo.beforeExport.invoke({exporter:this});const t=await this.export(this.objectToExport).finally(()=>{Fo.afterExport.invoke({exporter:this})});return t?(ut&&console.log("USDZ generation done. Downloading as "+e),this.openInQuickLook(t,e),t):(console.error("USDZ generation failed. Please report a bug",this),null)}async export(e){if(!e)return console.warn("No object to export"),null;const t=this._currentExportTasks.get(e);if(t)return t;const i=this.internalExport(e);return i instanceof Promise?(this._currentExportTasks.set(e,i),i.then(n=>(this._currentExportTasks.delete(e),n)).catch(n=>(this._currentExportTasks.delete(e),console.error("Error during USDZ export – please report a bug!",n),null))):i}_currentExportTasks=new Map;_previousTimeScale=1;async internalExport(e){ne.start("export-usdz",{onProgress:M=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:M}}))}}),ne.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),ne.report("export-usdz",{message:"Load progressive textures",autoStep:5}),ne.start("export-usdz-textures","export-usdz");const t=S.getComponentsInChildren(e,oi);for(const M of t)M&&M.enabled&&M.updateSprite(!0);const i=S.getComponentsInChildren(e,Ht),n=new Array;let o=0;for(const M of i){for(const O of M.sharedMeshes)if(O){let A=0;const D={exporter:this,type:"mesh",object:M.gameObject,mesh:O};if(Fo.beforeLODExport.invoke(D),D.overrideLevel!==void 0)if(D.overrideLevel===-1){ut&&console.warn("Skipping LOD export for mesh due to overrideLevel -1",M.gameObject,O);continue}else D.overrideLevel>=0&&(A=D.overrideLevel,ut&&console.log("Overriding LOD level for mesh export to level "+A+" "+O.name));const L=se.NEEDLE_progressive.assignMeshLOD(O,A);L instanceof Promise&&n.push(new Promise((N,$)=>{L.then(()=>{o++,ne.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:o,totalSteps:n.length}),N()}).catch(k=>$(k))}))}for(const O of M.sharedMaterials)if(O){let A=0;const D={exporter:this,type:"texture",object:M.gameObject,material:O};if(Fo.beforeLODExport.invoke(D),D.overrideLevel!==void 0)if(D.overrideLevel===-1){ut&&console.warn("Skipping LOD assignment due to overrideLevel -1",M.gameObject,O);continue}else D.overrideLevel>=0&&(A=D.overrideLevel,ut&&console.log("Overriding LOD level for texture export to level "+A+" "+O.name));const L=se.NEEDLE_progressive.assignTextureLOD(O,A);L instanceof Promise&&n.push(new Promise((N,$)=>{L.then(()=>{o++,ne.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:o,totalSteps:n.length}),N()}).catch(k=>$(k))}))}}ut&&we("Progressive Loading: "+n.length),await Promise.all(n),ut&&we("Progressive Loading: done"),ne.end("export-usdz-textures");const r=Vt.Global.Mask;Vt.Global.Set(Tn.AR);const a=new xw,l=new Ou(this.quickLookCompatible);let h;const d=[];this.interactive&&(d.push(new Wg),d.push(new Cr),globalThis.NEEDLE_USE_RAPIER&&S.getComponentsInChildren(e,Fe).length>0&&(this.physics?(h=new Hg,d.push(h)):T()&&console.warn("USDZExporter: Physics export is disabled, but there are active Rigidbody components in the scene. They will not be exported.")),d.push(new Lu),d.push(new Zg));const u=[l,...d,...this.extensions],p={self:this,exporter:a,extensions:u,object:e};ne.report("export-usdz","Invoking before-export"),this.dispatchEvent(new CustomEvent("before-export",{detail:p})),this.applyWebARSessionRoot(),this._previousTimeScale=this.context.time.timeScale,this.context.time.timeScale=0,ne.report("export-usdz","auto export animations and audio sources");const m=new Array;this.autoExportAnimations&&m.push(...vk(e,l)),u.find(M=>M.extensionName==="Audio")&&this.autoExportAudioSources&&m.push(...wk(e)),a.debug=ut,a.pruneUnusedNodes=!Ck;const _=dr.instance.objs.map(M=>M.batchedMesh);a.keepObject=M=>{let O=!0;const A=S.getComponent(M,Ht);return A&&!A.enabled&&(O=!1),O&&_.includes(M)&&(O=!1),O&&S.getComponentInParent(M,Qc)&&(O=!1),O&&S.getComponentInParent(M,$n)&&(O=!1),ut&&!O&&console.log("USDZExporter: Discarding object",M),O},a.beforeWritingDocument=()=>{if(T()&&l&&h){const M=l.animatedRoots;for(const O of M){const A=S.getComponentsInChildren(O,Fe).filter(L=>L.enabled),D=S.getComponents(O,Hi).filter(L=>L.enabled&&!L.isTrigger);(A.length>0||D.length>0)&&console.error("An animated object has physics components in its child hierarchy. This can lead to undefined behaviour due to a bug in Apple's QuickLook (FB15925487). Remove the physics components from child objects or verify that you get the expected results.",O)}}};const y=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(M=>{M.visible||y.push(M)});const v=u.find(M=>M.extensionName==="Behaviour");this.interactive&&v&&y.length>0&&v.addBehavior(xk(y));let b=!0;this.quickLookCompatible&&!this.interactive&&(b=!1),this.anchoringType!=="plane"&&this.anchoringType!=="none"&&this.anchoringType!=="image"&&this.anchoringType!=="face"&&(this.anchoringType="plane"),this.planeAnchoringAlignment!=="horizontal"&&this.planeAnchoringAlignment!=="vertical"&&this.planeAnchoringAlignment!=="any"&&(this.planeAnchoringAlignment="horizontal"),ne.report("export-usdz","Invoking exporter.parse");const w=await a.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:u,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:b}),R=new Blob([w],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,ne.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:p}));for(const M of m)S.destroy(M);return Vt.Global.Set(r),ne.end("export-usdz"),R}openInQuickLook(e,t){const i=e instanceof Blob?URL.createObjectURL(e):e,n=this.buildQuicklookOverlay();ut&&console.log("QuickLook Overlay",n);const o=n.callToAction?encodeURIComponent(n.callToAction):"",r=n.checkoutTitle?encodeURIComponent(n.checkoutTitle):"",a=n.checkoutSubtitle?encodeURIComponent(n.checkoutSubtitle):"";this.link.href=i+`#callToAction=${o}&checkoutTitle=${r}&checkoutSubtitle=${a}&callToActionURL=${n.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=t+".usdz",this.link.click()}download(e,t){Fo.save(e,t)}static save(e,t){const i=document.createElement("a");i.style.display="none",document.body.appendChild(i),typeof e=="string"?i.href=e:i.href=URL.createObjectURL(e),i.download=t,i.click(),i.remove()}lastCallback;quicklookCallback(e){if(e?.data=="_apple_ar_quicklook_button_tapped"){ut&&ue("Quicklook closed via call to action button");var t=new CustomEvent("quicklook-button-tapped",{detail:this});if(this.dispatchEvent(t),!t.defaultPrevented){const i=new URLSearchParams(this.link.href);if(i){const n=i.get("callToActionURL");ut&&we("Quicklook url: "+n),n&&(Un()?globalThis.open(n,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",n))}}}}buildQuicklookOverlay(){const e={};return this.customBranding&&Object.assign(e,this.customBranding),Un()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),e.callToAction="Close",e.checkoutTitle="🌵 Made with Needle",e.checkoutSubtitle="_"),(e.callToAction?.length||e.checkoutTitle?.length||e.checkoutSubtitle?.length)&&(e.callToAction?.length||(e.callToAction="\0"),e.checkoutTitle?.length||(e.checkoutTitle="\0"),e.checkoutSubtitle?.length||(e.checkoutSubtitle="\0")),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:e})),e}static invertForwardMatrix=new c.Matrix4().makeRotationY(Math.PI);static invertForwardQuaternion=new c.Quaternion().setFromEuler(new c.Euler(0,Math.PI,0));_rootSessionRootWasAppliedTo=null;_rootPositionBeforeExport=new c.Vector3;_rootRotationBeforeExport=new c.Quaternion;_rootScaleBeforeExport=new c.Vector3;getARScaleAndTarget(){if(!this.objectToExport)return{scale:1,_invertForward:!1,target:this.gameObject,sessionRoot:null};const e=S.findObjectOfType(Du);let t=S.getComponentInParent(this.objectToExport,Bi);t||(t=S.getComponentInChildren(this.objectToExport,Bi));let i=1,n=!1;const o=this.objectToExport;return e?i=e.arScale:t&&(i=t.arScale,n=t.invertForward),{scale:1/i,_invertForward:n,target:o,sessionRoot:t?.gameObject??null}}applyWebARSessionRoot(){if(!this.objectToExport)return;const{scale:e,_invertForward:t,target:i,sessionRoot:n}=this.getARScaleAndTarget(),o=n?.matrixWorld.clone().invert();this._rootSessionRootWasAppliedTo=i,this._rootPositionBeforeExport.copy(i.position),this._rootRotationBeforeExport.copy(i.quaternion),this._rootScaleBeforeExport.copy(i.scale),i.scale.multiplyScalar(e),t&&i.quaternion.multiply(Fo.invertForwardQuaternion),i.updateMatrix(),i.updateMatrixWorld(!0),n&&o&&i.matrix.premultiply(o)}revertWebARSessionRoot(){if(!this.objectToExport||!this._rootSessionRootWasAppliedTo)return;const e=this._rootSessionRootWasAppliedTo;e.position.copy(this._rootPositionBeforeExport),e.quaternion.copy(this._rootRotationBeforeExport),e.scale.copy(this._rootScaleBeforeExport),e.updateMatrix(),e.updateMatrixWorld(!0),this._rootSessionRootWasAppliedTo=null}createQuicklookButton(){const t=no.getOrCreate().createQuicklookButton();return t.parentNode||this.context.menu.appendChild(t),t}};wt([f(c.Object3D)],ri.prototype,"objectToExport");wt([f()],ri.prototype,"autoExportAnimations");wt([f()],ri.prototype,"autoExportAudioSources");wt([f()],ri.prototype,"exportFileName");wt([f(URL)],ri.prototype,"customUsdzFile");wt([f(Or)],ri.prototype,"customBranding");wt([f()],ri.prototype,"anchoringType");wt([f()],ri.prototype,"maxTextureSize");wt([f()],ri.prototype,"planeAnchoringAlignment");wt([f()],ri.prototype,"interactive");wt([f()],ri.prototype,"physics");wt([f()],ri.prototype,"allowCreateQuicklookButton");wt([f()],ri.prototype,"quickLookCompatible");let an=ri;var Pk=Object.defineProperty,Mk=Object.getOwnPropertyDescriptor,Jg=(s,e,t,i)=>{for(var n=Mk(e,t),o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&Pk(e,t,n),n};class Qa extends E{get fog(){return this._fog||(this._fog=new c.Fog(0,0,50)),this._fog}get mode(){return 1}set near(e){this.fog.near=e}get near(){return this.fog.near}set far(e){this.fog.far=e}get far(){return this.fog.far}set color(e){this.fog.color.copy(e)}get color(){return this.fog.color}_fog;onEnable(){this.scene.fog=this.fog}onDisable(){this.scene.fog===this._fog&&(this.scene.fog=null)}}Jg([f()],Qa.prototype,"near");Jg([f()],Qa.prototype,"far");Jg([f(c.Color)],Qa.prototype,"color");var Ok=Object.defineProperty,ey=(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&&Ok(e,t,n),n};class kr extends E{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!Uc||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new c.BoxHelper(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=zm(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),me.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(;this._boxHelper;)this._boxHelper?.update(),yield}}ey([f()],kr.prototype,"objectBounds");ey([f(c.Color)],kr.prototype,"color");ey([f()],kr.prototype,"isGizmo");var kk=Object.defineProperty,ty=(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&&kk(e,t,n),n};class Ya extends E{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!Uc)return;const e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new c.GridHelper(e,t,this.color0??new c.Color(.4,.4,.4),this.color1??new c.Color(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset)),this.gridHelper&&this.gameObject.add(this.gridHelper)}onDisable(){this.gridHelper&&(this.gameObject.remove(this.gridHelper),this.gridHelper=null)}}ty([f()],Ya.prototype,"isGizmo");ty([f(c.Color)],Ya.prototype,"color0");ty([f(c.Color)],Ya.prototype,"color1");var Ek=Object.defineProperty,iy=(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&&Ek(e,t,n),n};class ny extends E{connectedBody;get rigidBody(){return this._rigidBody}_rigidBody=null;onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(Fe)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.activeAndEnabled&&this.createJoint(this.rigidBody,this.connectedBody)}}iy([f(Fe)],ny.prototype,"connectedBody");class sy extends ny{createJoint(e,t){this.context.physics.engine?.addFixedJoint(e,t)}}class rh extends ny{anchor;axis;createJoint(e,t){this.axis&&this.anchor&&this.context.physics.engine?.addHingeJoint(e,t,this.anchor,this.axis)}}iy([f(c.Vector3)],rh.prototype,"anchor");iy([f(c.Vector3)],rh.prototype,"axis");var Rk=Object.defineProperty,Tk=Object.getOwnPropertyDescriptor,Si=(s,e,t,i)=>{for(var n=i>1?void 0:i?Tk(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&&Rk(e,t,n),n};function Qr(s){return s*Math.PI/180}const db=300,Us=x("debuglights");class xt extends E{type=0;get range(){return this._range}set range(e){this._range=e,this.light&&(this.light.type==="SpotLight"||this.light.type==="PointLight")&&"distance"in this.light&&(this.light.distance=e)}_range=1;get spotAngle(){return this._spotAngle}set spotAngle(e){this._spotAngle=e,this.light&&this.light.type==="SpotLight"&&"angle"in this.light&&(this.light.angle=Qr(e/2))}_spotAngle=30;get innerSpotAngle(){return this._innerSpotAngle}set innerSpotAngle(e){if(this._innerSpotAngle=e,this.light&&this.light.type==="SpotLight"&&"penumbra"in this.light){const t=this.spotAngle,n=1-Qr(e/2)/Qr(t/2);this.light.penumbra=n}}_innerSpotAngle=10;set color(e){this._color=e,this.light!==void 0&&(this.light.color=e)}get color(){return this.light?this.light.color:this._color}_color=new c.Color(16777215);set shadowNearPlane(e){if(e!==this._shadowNearPlane&&(this._shadowNearPlane=e,this.light?.shadow?.camera!==void 0)){const t=this.light.shadow.camera;t.near=e}}get shadowNearPlane(){return this._shadowNearPlane}_shadowNearPlane=.1;set shadowBias(e){e!==this._shadowBias&&(this._shadowBias=e,this.light?.shadow?.bias!==void 0&&(this.light.shadow.bias=e,this.light.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}_shadowBias=0;set shadowNormalBias(e){e!==this._shadowNormalBias&&(this._shadowNormalBias=e,this.light?.shadow?.normalBias!==void 0&&(this.light.shadow.normalBias=e,this.light.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}_shadowNormalBias=0;_overrideShadowBiasSettings=!1;set shadows(e){this._shadows=e,this.light&&(this.light.castShadow=e!==0,this.updateShadowSoftHard())}get shadows(){return this._shadows}_shadows=1;lightmapBakeType=4;set intensity(e){this._intensity=e,this.light&&(this.light.intensity=e),Us&&console.log("Set light intensity to "+this._intensity,e,this)}get intensity(){return this._intensity}_intensity=-1;get shadowDistance(){const e=this.light;return e?.shadow?e.shadow.camera.far:-1}set shadowDistance(e){this._shadowDistance=e;const t=this.light;if(t?.shadow){const i=t.shadow.camera;i.far=e,i.updateProjectionMatrix()}}_shadowDistance;shadowWidth;shadowHeight;get shadowResolution(){const e=this.light;return e?.shadow?e.shadow.mapSize.x:-1}set shadowResolution(e){if(e===this._shadowResolution)return;this._shadowResolution=e;const t=this.light;t?.shadow&&(t.shadow.mapSize.set(e,e),t.shadow.needsUpdate=!0)}_shadowResolution=void 0;get isBaked(){return this.lightmapBakeType===2}get selfIsLight(){if(this.gameObject.isLight===!0)return!0;switch(this.gameObject.type){case"SpotLight":case"PointLight":case"DirectionalLight":return!0}return!1}light=void 0;getWorldPosition(e){return this.light?this.type===1?this.light.getWorldPosition(e).multiplyScalar(1):this.light.getWorldPosition(e):e}awake(){this.color=new c.Color(this.color??16777215),Us&&console.log(this.name,this)}onEnable(){Us&&console.log("ENABLE LIGHT",this.name),this.createLight(),!this.isBaked&&(this.light&&(this.light.visible=!0,this.light.intensity=this._intensity,Us&&console.log("Set light intensity to "+this.light.intensity,this.name),this.selfIsLight||this.light.parent!==this.gameObject&&this.gameObject.add(this.light)),this.type===1&&this.startCoroutine(this.updateMainLightRoutine(),me.LateUpdate))}onDisable(){Us&&console.log("DISABLE LIGHT",this.name),this.light&&(this.selfIsLight?this.light.intensity=0:this.light.visible=!1)}createLight(){const e=this.selfIsLight;if(e&&!this.light)this.light=this.gameObject,this.light.name=this.name,this._intensity=this.light.intensity,this.type===1&&this.setDirectionalLight(this.light);else if(!this.light)switch(this.type){case 1:const t=new c.DirectionalLight(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-db*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),rr(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Us){const r=new c.DirectionalLightHelper(this.light,.2,this.color);this.context.scene.add(r)}break;case 0:const i=new c.SpotLight(this.color,this.intensity*Math.PI,this.range,Qr(this.spotAngle/2),1-Qr(this.innerSpotAngle/2)/Qr(this.spotAngle/2),2);i.position.set(0,0,0),i.rotation.set(0,0,0),this.light=i;const n=i.target;i.add(n),n.position.set(0,0,this.range),n.rotation.set(0,0,0);break;case 2:const o=new c.PointLight(this.color,this.intensity*Math.PI,this.range);this.light=o;break}if(this.light){if(this._intensity>=0?this.light.intensity=this._intensity:this._intensity=this.light.intensity,this.shadows!==0?this.light.castShadow=!0:this.light.castShadow=!1,this.light.shadow){this._shadowResolution!==void 0&&this._shadowResolution>4?(this.light.shadow.mapSize.width=this._shadowResolution,this.light.shadow.mapSize.height=this._shadowResolution):(this.light.shadow.mapSize.width=2048,this.light.shadow.mapSize.height=2048),Us&&console.log("Override shadow bias?",this._overrideShadowBiasSettings,this.shadowBias,this.shadowNormalBias),this.light.shadow.bias=this.shadowBias,this.light.shadow.normalBias=this.shadowNormalBias,this.updateShadowSoftHard();const t=this.light.shadow.camera;if(t.near=this.shadowNearPlane,this._shadowDistance!==void 0&&typeof this._shadowDistance=="number"?t.far=this._shadowDistance:t.far=db*Math.abs(this.gameObject.scale.z),this.gameObject.scale.set(1,1,1),this.shadowWidth!==void 0)t.left=-this.shadowWidth/2,t.right=this.shadowWidth/2;else{const i=this.gameObject.scale.x;t.left*=i,t.right*=i}if(this.shadowHeight!==void 0)t.top=this.shadowHeight/2,t.bottom=-this.shadowHeight/2;else{const i=this.gameObject.scale.y;t.top*=i,t.bottom*=i}this.light.shadow.needsUpdate=!0,Us&&this.context.scene.add(new c.CameraHelper(t))}this.isBaked?this.light.removeFromParent():e||this.gameObject.add(this.light)}}*updateMainLightRoutine(){for(;;){this.type===1&&((!this.context.mainLight||this.intensity>this.context.mainLight.intensity)&&(this.context.mainLight=this),yield);break}}static allowChangingRendererShadowMapType=!0;updateShadowSoftHard(){this.light&&this.light.shadow&&(this.shadows===2||(this.light.shadow.radius=1,this.light.shadow.blurSamples=1))}setDirectionalLight(e){e.add(e.target),e.target.position.set(0,0,-1)}}Si([f()],xt.prototype,"type",2);Si([f()],xt.prototype,"range",1);Si([f()],xt.prototype,"spotAngle",1);Si([f()],xt.prototype,"innerSpotAngle",1);Si([f(c.Color)],xt.prototype,"color",1);Si([f()],xt.prototype,"shadowNearPlane",1);Si([f()],xt.prototype,"shadowBias",1);Si([f()],xt.prototype,"shadowNormalBias",1);Si([f()],xt.prototype,"shadows",1);Si([f()],xt.prototype,"lightmapBakeType",2);Si([f()],xt.prototype,"intensity",1);Si([f()],xt.prototype,"shadowDistance",1);Si([f()],xt.prototype,"shadowResolution",1);new c.Vector3(0,0,0);var Ak=Object.defineProperty,Iu=(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&&Ak(e,t,n),n};const np=x("debuglods"),Dk=x("nolods");class Ka{screenRelativeTransitionHeight;distance;renderers}Iu([f()],Ka.prototype,"screenRelativeTransitionHeight");Iu([f()],Ka.prototype,"distance");Iu([f(Ht)],Ka.prototype,"renderers");class Lk{model;get renderers(){return this.model.renderers}constructor(e){this.model=e}}class ju extends E{lodModels=[];_lods=[];_settings=[];_lodsHandler;start(){if(np&&console.log("LODGROUP",this.name,this.lodModels,this),!Dk&&!this._lodsHandler&&this.gameObject&&this.lodModels&&Array.isArray(this.lodModels)){const e=[];for(const i of this.lodModels){const n=new Lk(i);this._lods.push(n);for(const o of n.renderers)e.includes(o)||e.push(o)}this._lodsHandler=new Array;for(let i=0;i<e.length;i++){const n=new c.LOD;this._lodsHandler.push(n),this.gameObject.add(n)}const t=new c.Object3D;t.name="Cull "+this.name;for(let i=0;i<e.length;i++){const n=e[i],o=this._lodsHandler[i],r=n.gameObject;np&&console.log(i,r.name);for(const a of this._lods){const l=a.model.distance;let h=null;if(a.renderers.includes(n)?h=r:h=t,h.type==="Group"){console.warn(`LODGroup ${this.name}: Group or MultiMaterial object's are not supported as LOD object: ${h.name}`);continue}np&&console.log("LEVEL",h.name,l),o.autoUpdate=!1,this.onAddLodLevel(o,h,a.model.distance)}}}}onAfterRender(){if(!this.gameObject||!this._lodsHandler)return;const e=this.context.mainCamera;if(e)for(const t of this._lodsHandler){t.update(e);const i=t.getCurrentLevel(),n=t.levels[i];t.layers.mask=n.object.layers.mask}}onAddLodLevel(e,t,i){if(t===this.gameObject){console.warn("LODGroup component must be on parent object and not mesh directly at the moment",t.name,t);return}e.addLevel(t,i*this._distanceFactor,.01);const n={lod:e,levelIndex:e.levels.length-1,distance:i};this._settings.push(n)}_distanceFactor=1;distanceFactor(e){if(e!==this._distanceFactor){this._distanceFactor=e;for(const t of this._settings){const i=t.lod.levels[t.levelIndex];i.distance=t.distance*e}}}}Iu([f(Ka)],ju.prototype,"lodModels");var Ik=Object.defineProperty,oy=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&Ik(e,t,n),n};const Kh=x("debugnestedgltf");class Za extends E{filePath;loaded=new oe;loadAssetInParent=!0;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){return this.filePath?.preload()||null}async start(){if(this._isLoadingOrDoneLoading)return;Kh&&console.log(this,this.guid);const e=this.gameObject.parent;if(e&&this.filePath){this._isLoadingOrDoneLoading=!0;const t=new fn;t.idProvider=new _t(this.hash(this.guid)),t.parent=this.loadAssetInParent!==!1?e:this.gameObject,this.gameObject.updateMatrix();const i=this.gameObject.matrix;Kh&&console.log("Load nested:",this.filePath?.url??this.filePath,this.gameObject.position);const n=await this.filePath?.instantiate?.call(this.filePath,t);Kh&&console.log("Nested loaded:",this.filePath?.url??this.filePath,n),n&&this.loadAssetInParent!==!1&&(n.matrixAutoUpdate=!1,n.matrix.identity(),n.applyMatrix4(i),n.matrixAutoUpdate=!0,n.layers.disableAll(),n.layers.set(this.layer),this.loaded.invoke({component:this,instance:n,asset:this.filePath})),Kh&&console.log("Nested loading done:",this.filePath?.url??this.filePath,n)}}onDestroy(){this.filePath?.unload()}hash(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);return t}}oy([f(K)],Za.prototype,"filePath");oy([f(oe)],Za.prototype,"loaded");oy([f()],Za.prototype,"loadAssetInParent");var jk=Object.defineProperty,ry=(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&&jk(e,t,n),n};const Bk=x("debugnet"),Bu=class sm extends E{url=null;urlParameterName=null;localhost=null;awake(){Bk&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?sm.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const o=x(this.urlParameterName);o&&typeof o=="string"&&(e=o)}if(!e)return null;const i=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return i?.groups?i?.groups.socket_prefix?e:"wss://"+i?.groups.url:null}static GetUrl(e,t){let i=e;const n=sm.IsLocalNetwork()&&t;if(n&&(i=t),e?.startsWith("/")){const o=n?i:window.location.origin;o?.endsWith("/")&&e.startsWith("/")&&(e=e.substring(1)),i=o+e}return i}static IsLocalNetwork(e=window.location.hostname){return pi(e)}};ry([f()],Bu.prototype,"url");ry([f()],Bu.prototype,"urlParameterName");ry([f()],Bu.prototype,"localhost");let ay=Bu;var Uk=Object.defineProperty,Uu=(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&&Uk(e,t,n),n};class Er extends E{referenceSpace;from;affectPosition=!1;affectRotation=!1;alignLookDirection=!1;levelLookDirection=!1;levelPosition=!1;positionOffset=new c.Vector3(0,0,0);rotationOffset=new c.Vector3(0,0,0);offset=new c.Vector3(0,0,0);update(){if(!this.from)return;var e=Q(this.from),t=fe(this.from);this.offset.copy(this.positionOffset);const i=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(i),e.add(this.offset),this.levelPosition&&this.referenceSpace){const a=new c.Plane(this.gameObject.up,0),l=Q(this.referenceSpace);a.setFromNormalAndCoplanarPoint(this.gameObject.up,l);const h=new c.Vector3(0,0,0);a.projectPoint(e,h),e.copy(h)}this.affectPosition&&rt(this.gameObject,e);const n=new c.Euler(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),o=new c.Quaternion().setFromEuler(n);this.affectRotation&&ln(this.gameObject,t.multiply(o));const r=new c.Vector3;this.from.getWorldDirection(r).multiplyScalar(50),this.levelLookDirection&&(r.y=0),this.alignLookDirection&&this.gameObject.lookAt(r)}}Uu([f(S)],Er.prototype,"referenceSpace");Uu([f(S)],Er.prototype,"from");Uu([f(c.Vector3)],Er.prototype,"positionOffset");Uu([f(c.Vector3)],Er.prototype,"rotationOffset");var Fk=Object.defineProperty,wo=(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&&Fk(e,t,n),n};class ii{time=0;value=0;inTangent=1/0;inWeight;outTangent=1/0;outWeight;weightedMode;constructor(e=0,t=0){this.time=e,this.value=t}}wo([f()],ii.prototype,"time");wo([f()],ii.prototype,"value");wo([f()],ii.prototype,"inTangent");wo([f()],ii.prototype,"inWeight");wo([f()],ii.prototype,"outTangent");wo([f()],ii.prototype,"outWeight");wo([f()],ii.prototype,"weightedMode");const Vw=class Vl{static linearFromTo(e,t,i){const n=new Vl,o=new ii;o.time=0,o.value=e;const r=new ii;return r.time=i,r.value=t,n.keys.push(o,r),n}static constant(e){const t=new Vl,i=new ii;return i.time=0,i.value=e,t.keys.push(i),t}keys=[];clone(){const e=new Vl;return e.keys=this.keys?.map(t=>{const i=new ii;return i.time=t.time,i.value=t.value,i.inTangent=t.inTangent,i.inWeight=t.inWeight,i.outTangent=t.outTangent,i.outWeight=t.outWeight,i.weightedMode=t.weightedMode,i})||[],e}get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(e){if(!this.keys||this.keys.length==0)return 0;if(this.keys.length===1)return this.keys[0].value;if(this.keys[0].time>=e)return this.keys[0].value;for(let t=0;t<this.keys.length;t++){const i=this.keys[t];if(i.time<=e)if(t+1<this.keys.length){const o=this.keys[t+1];if(o.time<e)continue;return!isFinite(i.outTangent)||!isFinite(o.inTangent)?i.value:Vl.interpolateValue(e,i,o)}else return i.value}return this.keys[this.keys.length-1].value}static interpolateValue(e,t,i){const n=t.time,o=t.value,r=t.outTangent,a=i.time,l=i.value,h=i.inTangent,d=a-n,u=d*d,p=u*d,m=((r+h)*d-2*(l-o))/p,g=(3*(l-o)-(h+2*r)*d)/u,_=r,y=o,v=e-n,b=v*v,w=b*v;return m*w+g*b+_*v+y}};wo([f(ii)],Vw.prototype,"keys");let ah=Vw;var zk=Object.defineProperty,C=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&zk(e,t,n),n};const Zh=x("debugparticles");var is=(s=>(s[s.Billboard=0]="Billboard",s[s.Stretch=1]="Stretch",s[s.HorizontalBillboard=2]="HorizontalBillboard",s[s.VerticalBillboard=3]="VerticalBillboard",s[s.Mesh=4]="Mesh",s))(is||{});class Rr{alphaKeys=[];colorKeys=[];get duration(){return 1}evaluate(e,t){let i,n=0,o=null,r=0;for(let a=0;a<this.alphaKeys.length;a++){const l=this.alphaKeys[a];(l.time<e||!i)&&(i=l,n=a)}for(let a=0;a<this.colorKeys.length;a++){const l=this.colorKeys[a];(l.time<e||!o)&&(o=l,r=a)}if(o)if(r+1<this.colorKeys.length){const l=this.colorKeys[r+1],h=I.remap(e,o.time,l.time,0,1);t.r=I.lerp(o.color.r,l.color.r,h),t.g=I.lerp(o.color.g,l.color.g,h),t.b=I.lerp(o.color.b,l.color.b,h)}else t.r=o.color.r,t.g=o.color.g,t.b=o.color.b;if(i)if(n+1<this.alphaKeys.length){const l=this.alphaKeys[n+1],h=I.remap(e,i.time,l.time,0,1);t.alpha=I.lerp(i.alpha,l.alpha,h)}else t.alpha=i.alpha;return t}}C([f()],Rr.prototype,"alphaKeys");C([f()],Rr.prototype,"colorKeys");var Cc=(s=>(s[s.Local=0]="Local",s[s.World=1]="World",s[s.Custom=2]="Custom",s))(Cc||{}),Yd=(s=>(s[s.Sphere=0]="Sphere",s[s.SphereShell=1]="SphereShell",s[s.Hemisphere=2]="Hemisphere",s[s.HemisphereShell=3]="HemisphereShell",s[s.Cone=4]="Cone",s[s.Box=5]="Box",s[s.Mesh=6]="Mesh",s[s.ConeShell=7]="ConeShell",s[s.ConeVolume=8]="ConeVolume",s[s.ConeVolumeShell=9]="ConeVolumeShell",s[s.Circle=10]="Circle",s[s.CircleEdge=11]="CircleEdge",s[s.SingleSidedEdge=12]="SingleSidedEdge",s[s.MeshRenderer=13]="MeshRenderer",s[s.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",s[s.BoxShell=15]="BoxShell",s[s.BoxEdge=16]="BoxEdge",s[s.Donut=17]="Donut",s[s.Rectangle=18]="Rectangle",s[s.Sprite=19]="Sprite",s[s.SpriteRenderer=20]="SpriteRenderer",s))(Yd||{});const Ss=class $l{static constant(e){const t=new $l;return t.setConstant(e),t}static betweenTwoConstants(e,t){const i=new $l;return i.setMinMaxConstant(e,t),i}static curve(e,t=1){const i=new $l;return i.setCurve(e,t),i}setConstant(e){this.mode=0,this.constant=e}setMinMaxConstant(e,t){this.mode=3,this.constantMin=e,this.constantMax=t}setCurve(e,t=1){this.mode=1,this.curve=e,this.curveMultiplier=t}mode="Constant";constant;constantMin;constantMax;curve;curveMin;curveMax;curveMultiplier;clone(){const e=new $l;return e.mode=this.mode,e.constant=this.constant,e.constantMin=this.constantMin,e.constantMax=this.constantMax,e.curve=this.curve?.clone(),e.curveMin=this.curveMin?.clone(),e.curveMax=this.curveMax?.clone(),e.curveMultiplier=this.curveMultiplier,e}evaluate(e,t){const i=t===void 0?Math.random():t;switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return e=I.clamp01(e),this.curve.evaluate(e)*this.curveMultiplier;case 2:case"TwoCurves":const n=e*this.curveMin.duration,o=e*this.curveMax.duration;return I.lerp(this.curveMin.evaluate(n),this.curveMax.evaluate(o),i%1)*this.curveMultiplier;case 3:case"TwoConstants":return I.lerp(this.constantMin,this.constantMax,i%1);default:this.curveMax.evaluate(e)*this.curveMultiplier;break}return 0}getMax(){switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return this.getMaxFromCurve(this.curve)*this.curveMultiplier;case 2:case"TwoCurves":return Math.max(this.getMaxFromCurve(this.curveMin),this.getMaxFromCurve(this.curveMax))*this.curveMultiplier;case 3:case"TwoConstants":return Math.max(this.constantMin,this.constantMax);default:return 0}}getMaxFromCurve(e){if(!e)return 0;let t=Number.MIN_VALUE;for(let i=0;i<e.keys.length;i++){const n=e.keys[i];n.value>t&&(t=n.value)}return t}};C([f()],Ss.prototype,"mode");C([f()],Ss.prototype,"constant");C([f()],Ss.prototype,"constantMin");C([f()],Ss.prototype,"constantMax");C([f(ah)],Ss.prototype,"curve");C([f(ah)],Ss.prototype,"curveMin");C([f(ah)],Ss.prototype,"curveMax");C([f()],Ss.prototype,"curveMultiplier");let H=Ss;const xo=class mt{static constant(e){const t=new mt;return t.constant(e),t}static betweenTwoColors(e,t){const i=new mt;return i.betweenTwoColors(e,t),i}constant(e){return this.mode=0,this.color=e,this}betweenTwoColors(e,t){return this.mode=2,this.colorMin=e,this.colorMax=t,this}mode=0;color;colorMin;colorMax;gradient;gradientMin;gradientMax;static _temp=new ee(0,0,0,1);static _temp2=new ee(0,0,0,1);evaluate(e,t){const i=t===void 0?Math.random():t;switch(this.mode){case 0:case"Color":return this.color;case 1:case"Gradient":return this.gradient.evaluate(e,mt._temp),mt._temp;case 2:case"TwoColors":return mt._temp.lerpColors(this.colorMin,this.colorMax,i);case 3:case"TwoGradients":return this.gradientMin.evaluate(e,mt._temp),this.gradientMax.evaluate(e,mt._temp2),mt._temp.lerp(mt._temp2,i);case 4:case"RandomColor":const o=Math.random();return this.gradientMin.evaluate(e,mt._temp),this.gradientMax.evaluate(e,mt._temp2),mt._temp.lerp(mt._temp2,o)}return mt._temp.set(16777215),mt._temp.alpha=1,mt._temp}};C([f()],xo.prototype,"mode");C([f(ee)],xo.prototype,"color");C([f(ee)],xo.prototype,"colorMin");C([f(ee)],xo.prototype,"colorMax");C([f(Rr)],xo.prototype,"gradient");C([f(Rr)],xo.prototype,"gradientMin");C([f(Rr)],xo.prototype,"gradientMax");let Tr=xo;var om=(s=>(s[s.Hierarchy=0]="Hierarchy",s[s.Local=1]="Local",s[s.Shape=2]="Shape",s))(om||{});class At{cullingMode;duration;emitterVelocityMode;flipRotation;gravityModifier;gravityModifierMultiplier;loop;maxParticles;playOnAwake;prewarm;ringBufferLoopRange;ringBufferMode;scalingMode;simulationSpace;simulationSpeed;startColor;startDelay;startDelayMultiplier;startLifetime;startLifetimeMultiplier;startRotation;startRotationMultiplier;startRotation3D;startRotationX;startRotationXMultiplier;startRotationY;startRotationYMultiplier;startRotationZ;startRotationZMultiplier;startSize;startSize3D;startSizeMultiplier;startSizeX;startSizeXMultiplier;startSizeY;startSizeYMultiplier;startSizeZ;startSizeZMultiplier;startSpeed;startSpeedMultiplier;stopAction;useUnscaledTime}C([f(H)],At.prototype,"gravityModifier");C([f(Tr)],At.prototype,"startColor");C([f(H)],At.prototype,"startDelay");C([f(H)],At.prototype,"startLifetime");C([f(H)],At.prototype,"startRotation");C([f(H)],At.prototype,"startRotationX");C([f(H)],At.prototype,"startRotationY");C([f(H)],At.prototype,"startRotationZ");C([f(H)],At.prototype,"startSize");C([f(H)],At.prototype,"startSizeX");C([f(H)],At.prototype,"startSizeY");C([f(H)],At.prototype,"startSizeZ");C([f(H)],At.prototype,"startSpeed");class Kd{cycleCount;maxCount;minCount;probability;repeatInterval;time;count;_performed=0;reset(){this._performed=0}run(e){if(e<=this.time)return 0;let t=0;if(this.cycleCount===0||this._performed<this.cycleCount){const i=this.time+this.repeatInterval*this._performed;if(e>=i&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:t=this.count.constant;break;case 3:t=I.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:t=this.count.curve.evaluate(Math.random());break;case 2:const n=Math.random();t=I.lerp(this.count.curveMin.evaluate(n),this.count.curveMax.evaluate(n),Math.random());break}}return t}}class Cs{enabled;get burstCount(){return this.bursts?.length??0}bursts;rateOverTime;rateOverTimeMultiplier;rateOverDistance;rateOverDistanceMultiplier;system;reset(){this.bursts?.forEach(e=>e.reset())}getBurst(){let e=0;if(this.burstCount>0)for(let t=0;t<this.burstCount;t++){const i=this.bursts[t];this.system.main.loop&&i.time>=this.system.time&&i.reset(),e+=Math.round(i.run(this.system.time))}return e}}C([f()],Cs.prototype,"enabled");C([f()],Cs.prototype,"bursts");C([f(H)],Cs.prototype,"rateOverTime");C([f()],Cs.prototype,"rateOverTimeMultiplier");C([f(H)],Cs.prototype,"rateOverDistance");C([f()],Cs.prototype,"rateOverDistanceMultiplier");class Fu{enabled;color}C([f(Tr)],Fu.prototype,"color");class Ar{enabled;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_time=0;_temp=new c.Vector3;evaluate(e,t,i){if(t||(t=this._temp),!this.enabled)return t.x=t.y=t.z=1,t;if(this.separateAxes)t.x=this.x.evaluate(e,i)*this.xMultiplier,t.y=this.y.evaluate(e,i)*this.yMultiplier,t.z=this.z.evaluate(e,i)*this.zMultiplier;else{const n=this.size.evaluate(e,i)*this.sizeMultiplier;t.x=n}return t}}C([f(H)],Ar.prototype,"size");C([f(H)],Ar.prototype,"x");C([f(H)],Ar.prototype,"y");C([f(H)],Ar.prototype,"z");const qe=class Wl{get type(){return Yd[this.shapeType]}initialize(e){this.onInitialize(e),e.position.x=this._vector.x,e.position.y=this._vector.y,e.position.z=this._vector.z}toJSON(){return this}clone(){return new Wl}shapeType=5;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcSpread;arcSpeedMultiplier;arcMode;boxThickness;position;rotation;_rotation=new c.Euler;scale;radius;radiusThickness;sphericalDirectionAmount;randomDirectionAmount;randomPositionAmount;meshShapeType;meshRenderer;_meshObj;_meshGeometry;setMesh(e){this.meshRenderer=e,e?(this._meshObj=e.sharedMeshes[Math.floor(Math.random()*e.sharedMeshes.length)],this._meshGeometry=this._meshObj.geometry):(this._meshObj=void 0,this._meshGeometry=void 0)}system;_space;_worldSpaceMatrix=new c.Matrix4;_worldSpaceMatrixInverse=new c.Matrix4;constructor(){Zh&&console.log(this)}update(e,t){}onUpdate(e,t,i,n){this.system=e,this._space=i,i===1&&(this._worldSpaceMatrix.copy(n.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}applyRotation(e){const t=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return t&&(this._rotation.x=I.toRadians(this.rotation.x),this._rotation.y=I.toRadians(this.rotation.y),this._rotation.z=I.toRadians(this.rotation.z),this._rotation.order="ZYX",e.applyEuler(this._rotation)),t}_vector=new c.Vector3(0,0,0);_temp=new c.Vector3(0,0,0);_triangle=new c.Triangle;onInitialize(e){this._vector.set(0,0,0),e.mesh=void 0,e.mesh_geometry=void 0;const t=this._temp.copy(this.position),i=this._space===1;i&&t.applyQuaternion(this.system.worldQuaternion);let n=this.radius;if(i&&(n*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:Zh&&j.DrawWireBox(this.position,this.scale,14540253,1),this._vector.x=Math.random()*this.scale.x-this.scale.x/2,this._vector.y=Math.random()*this.scale.y-this.scale.y/2,this._vector.z=Math.random()*this.scale.z-this.scale.z/2,this._vector.add(t);break;case 4:this.randomConePoint(this.position,this.angle,n,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 10:this.randomCirclePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 13:const o=this.meshRenderer;o?.destroyed==!1&&this.setMesh(o);const r=e.mesh=this._meshObj,a=e.mesh_geometry=this._meshGeometry;if(r&&a)switch(this.meshShapeType){case 0:{const l=a.getAttribute("position"),h=Math.floor(Math.random()*l.count);this._vector.fromBufferAttribute(l,h),this._vector.applyMatrix4(r.matrixWorld),e.mesh_normal=h}break;case 1:break;case 2:{const l=a.index;if(l){let h=Math.random(),d=Math.random();h+d>1&&(h=1-h,d=1-d);const u=Math.floor(Math.random()*(l.count/3));let p=u*3,m=u*3+1,g=u*3+2;p=l.getX(p),m=l.getX(m),g=l.getX(g);const _=a.getAttribute("position");this._triangle.a.fromBufferAttribute(_,p),this._triangle.b.fromBufferAttribute(_,m),this._triangle.c.fromBufferAttribute(_,g),this._vector.set(0,0,0).addScaledVector(this._triangle.a,h).addScaledVector(this._triangle.b,d).addScaledVector(this._triangle.c,1-(h+d)),this._vector.applyMatrix4(r.matrixWorld),e.mesh_normal=u}}break}break;default:this._vector.set(0,0,0),T()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",Yd[this.shapeType]),globalThis.__particlesystem_shapetype_unsupported=!0);break}this.randomizePosition(this._vector,this.randomPositionAmount)}this.applyRotation(this._vector),i&&(this._vector.applyQuaternion(this.system.worldQuaternion),this._vector.add(this.system.worldPos)),Zh&&j.DrawSphere(this._vector,.03,16711680,.5,!0)}_dir=new c.Vector3;getDirection(e,t){if(!this.enabled)return this._dir.set(0,0,1),this._dir;switch(this.shapeType){case 5:this._dir.set(0,0,1);break;case 4:this._dir.set(0,0,1);break;case 10:case 0:const i=t.x,n=t.y,o=t.z;this._dir.set(i,n,o),this.system?.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;case 13:const r=e.mesh,a=e.mesh_geometry;if(r&&a)switch(this.meshShapeType){case 0:{const l=a.getAttribute("normal"),h=e.mesh_normal;this._dir.fromBufferAttribute(l,h)}break;case 1:break;case 2:{const l=a.index;if(l){const h=e.mesh_normal,d=l.getX(h*3),u=l.getX(h*3+1),p=l.getX(h*3+2),m=a.getAttribute("position"),g=B(),_=B(),y=B();g.fromBufferAttribute(m,d),_.fromBufferAttribute(m,u),y.fromBufferAttribute(m,p),g.sub(_),y.sub(_),g.cross(y),this._dir.copy(g).multiplyScalar(-1);const v=fe(r);this._dir.applyQuaternion(v)}}break}break;default:this._dir.set(0,0,1);break}return this._space===1&&this._dir.applyQuaternion(this.system.worldQuaternion),this.applyRotation(this._dir),this._dir.normalize(),this.spherizeDirection(this._dir,this.sphericalDirectionAmount),this.randomizeDirection(this._dir,this.randomDirectionAmount),Zh&&(j.DrawSphere(t,.01,8925952,.5,!0),j.DrawDirection(t,this._dir,8925952,.5,!0)),this._dir}static _randomQuat=new c.Quaternion;static _tempVec=new c.Vector3;randomizePosition(e,t){if(t<=0)return;const i=Wl._tempVec;i.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),i.x*=t*this.scale.x,i.y*=t*this.scale.y,i.z*=t*this.scale.z,e.add(i)}randomizeDirection(e,t){if(t===0)return;const i=Wl._randomQuat,n=Wl._tempVec;n.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),i.setFromAxisAngle(n,t*Math.random()*Math.PI),e.applyQuaternion(i)}spherizeDirection(e,t){if(t===0)return;const i=Math.random()*Math.PI*2,n=Math.acos(1-Math.random()*2),o=Math.sin(n)*Math.cos(i),r=Math.sin(n)*Math.sin(i),a=Math.cos(n),l=new c.Vector3(o,r,a);e.lerp(l,t)}randomSpherePoint(e,t,i,n,o){const r=Math.random(),a=Math.random(),l=2*Math.PI*r*(n/360),h=Math.acos(2*a-1),d=I.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,u=e.x+this.scale.x*(-d*Math.sin(h)*Math.cos(l)),p=e.y+this.scale.y*(d*Math.sin(h)*Math.sin(l)),m=e.z+this.scale.z*(d*Math.cos(h));o.x=u,o.y=p,o.z=m}randomCirclePoint(e,t,i,n,o){const r=Math.random(),a=2*Math.PI*r*(n/360),l=I.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,h=e.x+this.scale.x*l*Math.cos(a),d=e.y+this.scale.y*l*Math.sin(a),u=e.z;o.x=h,o.y=d,o.z=u}_loopTime=0;_loopDirection=1;randomConePoint(e,t,i,n,o,r,a){let l=0,h=0;switch(r){case 0:l=Math.random(),h=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:l=.5,h=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let d=2*Math.PI*l*(o/360);switch(r){case 2:case 1:d+=Math.PI+.5,d+=this._loopTime*Math.PI*2,d%=I.toRadians(o);break}const u=Math.acos(2*h-1),p=I.lerp(1,1-Math.pow(1-Math.random(),Math.PI),n)*i,m=e.x+-p*Math.sin(u)*Math.cos(d),g=e.y+p*Math.sin(u)*Math.sin(d),_=e.z;a.x=m*this.scale.x,a.y=g*this.scale.y,a.z=_*this.scale.z}};C([f()],qe.prototype,"shapeType");C([f()],qe.prototype,"enabled");C([f()],qe.prototype,"alignToDirection");C([f()],qe.prototype,"angle");C([f()],qe.prototype,"arc");C([f()],qe.prototype,"arcSpread");C([f()],qe.prototype,"arcSpeedMultiplier");C([f()],qe.prototype,"arcMode");C([f(c.Vector3)],qe.prototype,"boxThickness");C([f(c.Vector3)],qe.prototype,"position");C([f(c.Vector3)],qe.prototype,"rotation");C([f(c.Vector3)],qe.prototype,"scale");C([f()],qe.prototype,"radius");C([f()],qe.prototype,"radiusThickness");C([f()],qe.prototype,"sphericalDirectionAmount");C([f()],qe.prototype,"randomDirectionAmount");C([f()],qe.prototype,"randomPositionAmount");C([f()],qe.prototype,"meshShapeType");C([f(Kc)],qe.prototype,"meshRenderer");let ly=qe;class pe{damping;enabled;frequency;octaveCount;octaveMultiplier;octaveScale;positionAmount;quality;remap;remapEnabled;remapMultiplier;remapX;remapXMultiplier;remapY;remapYMultiplier;remapZ;remapZMultiplier;scrollSpeedMultiplier;separateAxes;strengthMultiplier;strengthX;strengthXMultiplier;strengthY;strengthYMultiplier;strengthZ;strengthZMultiplier;_noise;_time=0;update(e){this._time+=e.time.deltaTime*this.scrollSpeedMultiplier}_temp=new c.Vector3;apply(e,t,i,n,o,r){if(!this.enabled)return;this._noise||(this._noise=re.createNoise4D(()=>0));const a=this._temp.set(t.x,t.y,t.z).multiplyScalar(this.frequency),l=this._noise(a.x,a.y,a.z,this._time),h=this._noise(a.x,a.y,a.z,this._time+1e3*this.frequency),d=this._noise(a.x,a.y,a.z,this._time+2e3*this.frequency);this._temp.set(l,h,d).normalize();const u=o/r;let p=this.positionAmount.evaluate(u);this.separateAxes?(this._temp.x*=p*this.strengthXMultiplier,this._temp.y*=p*this.strengthYMultiplier,this._temp.z*=p*this.strengthZMultiplier):(this.strengthX&&(p*=this.strengthX.evaluate(u)*1.5),this._temp.multiplyScalar(p)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z}}C([f()],pe.prototype,"damping");C([f()],pe.prototype,"enabled");C([f()],pe.prototype,"frequency");C([f()],pe.prototype,"octaveCount");C([f()],pe.prototype,"octaveMultiplier");C([f()],pe.prototype,"octaveScale");C([f(H)],pe.prototype,"positionAmount");C([f()],pe.prototype,"quality");C([f(H)],pe.prototype,"remap");C([f()],pe.prototype,"remapEnabled");C([f()],pe.prototype,"remapMultiplier");C([f(H)],pe.prototype,"remapX");C([f()],pe.prototype,"remapXMultiplier");C([f(H)],pe.prototype,"remapY");C([f()],pe.prototype,"remapYMultiplier");C([f(H)],pe.prototype,"remapZ");C([f()],pe.prototype,"remapZMultiplier");C([f()],pe.prototype,"scrollSpeedMultiplier");C([f()],pe.prototype,"separateAxes");C([f()],pe.prototype,"strengthMultiplier");C([f(H)],pe.prototype,"strengthX");C([f()],pe.prototype,"strengthXMultiplier");C([f(H)],pe.prototype,"strengthY");C([f()],pe.prototype,"strengthYMultiplier");C([f(H)],pe.prototype,"strengthZ");C([f()],pe.prototype,"strengthZMultiplier");class Te{enabled;attachRibbonToTransform=!1;colorOverLifetime;colorOverTrail;dieWithParticles=!0;inheritParticleColor=!0;lifetime;lifetimeMultiplier;minVertexDistance=.2;mode=0;ratio=1;ribbonCount=1;shadowBias=0;sizeAffectsLifetime=!1;sizeAffectsWidth=!1;splitSubEmitterRibbons=!1;textureMode=0;widthOverTrail;widthOverTrailMultiplier;worldSpace=!1;getWidth(e,t,i,n){const o=this.widthOverTrail.evaluate(i,n);return e*=o,e}getColor(e,t,i){const n=this.colorOverTrail.evaluate(i),o=this.colorOverLifetime.evaluate(t);e.x*=n.r*o.r,e.y*=n.g*o.g,e.z*=n.b*o.b,"alpha"in n&&"alpha"in o&&(e.w*=n.alpha*o.alpha)}}C([f()],Te.prototype,"enabled");C([f()],Te.prototype,"attachRibbonToTransform");C([f(Tr)],Te.prototype,"colorOverLifetime");C([f(Tr)],Te.prototype,"colorOverTrail");C([f()],Te.prototype,"dieWithParticles");C([f()],Te.prototype,"inheritParticleColor");C([f(H)],Te.prototype,"lifetime");C([f()],Te.prototype,"lifetimeMultiplier");C([f()],Te.prototype,"minVertexDistance");C([f()],Te.prototype,"mode");C([f()],Te.prototype,"ratio");C([f()],Te.prototype,"ribbonCount");C([f()],Te.prototype,"shadowBias");C([f()],Te.prototype,"sizeAffectsLifetime");C([f()],Te.prototype,"sizeAffectsWidth");C([f()],Te.prototype,"splitSubEmitterRibbons");C([f()],Te.prototype,"textureMode");C([f(H)],Te.prototype,"widthOverTrail");C([f()],Te.prototype,"widthOverTrailMultiplier");C([f()],Te.prototype,"worldSpace");class Ie{enabled;space=0;orbitalX;orbitalY;orbitalZ;orbitalXMultiplier;orbitalYMultiplier;orbitalZMultiplier;orbitalOffsetX;orbitalOffsetY;orbitalOffsetZ;speedModifier;speedModifierMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_system;update(e){this._system=e}_temp=new c.Vector3;_temp2=new c.Vector3;_temp3=new c.Vector3;_hasOrbital=!1;_index=0;_orbitalMatrix=new c.Matrix4;init(e){this._index==0&&(e.debug=!0),this._index+=1,e.orbitx=this.orbitalX.evaluate(Math.random()),e.orbity=this.orbitalY.evaluate(Math.random()),e.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=e.orbitx!=0||e.orbity!=0||e.orbitz!=0}apply(e,t,i,n,o,r,a){if(!this.enabled)return;const l=r/a,h=this.speedModifier.evaluate(l)*this.speedModifierMultiplier,d=this.x.evaluate(l),u=this.y.evaluate(l),p=this.z.evaluate(l);if(this._temp.set(-d,u,p),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&this._system?.worldPos){const g=this._temp2.set(i.x,i.y,i.z),_=this.orbitalXMultiplier,y=this.orbitalYMultiplier,v=this.orbitalZMultiplier,b=h*Math.PI*2*10,w=Math.cos(b*_),R=Math.sin(b*_),M=Math.cos(b*y),O=Math.sin(b*y),A=Math.cos(b*v),D=Math.sin(b*v),L=g.x*(M*A)+g.y*(M*D)+g.z*-O,N=g.x*(R*O*A-w*D)+g.y*(R*O*D+w*A)+g.z*(R*M),$=g.x*(w*O*A+R*D)+g.y*(w*O*D-R*A)+g.z*(w*M),k=this._temp3.set(g.x-L,g.y-N,g.z-$);k.normalize(),k.multiplyScalar(.2/o*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),n.x+=k.x,n.y+=k.y,n.z+=k.z}n.x+=this._temp.x,n.y+=this._temp.y,n.z+=this._temp.z,n.x*=h,n.y*=h,n.z*=h}}C([f()],Ie.prototype,"enabled");C([f()],Ie.prototype,"space");C([f(H)],Ie.prototype,"orbitalX");C([f(H)],Ie.prototype,"orbitalY");C([f(H)],Ie.prototype,"orbitalZ");C([f()],Ie.prototype,"orbitalXMultiplier");C([f()],Ie.prototype,"orbitalYMultiplier");C([f()],Ie.prototype,"orbitalZMultiplier");C([f()],Ie.prototype,"orbitalOffsetX");C([f()],Ie.prototype,"orbitalOffsetY");C([f()],Ie.prototype,"orbitalOffsetZ");C([f(H)],Ie.prototype,"speedModifier");C([f()],Ie.prototype,"speedModifierMultiplier");C([f(H)],Ie.prototype,"x");C([f()],Ie.prototype,"xMultiplier");C([f(H)],Ie.prototype,"y");C([f()],Ie.prototype,"yMultiplier");C([f(H)],Ie.prototype,"z");C([f()],Ie.prototype,"zMultiplier");class Dt{animation;enabled;cycleCount;frameOverTime;frameOverTimeMultiplier;numTilesX;numTilesY;startFrame;startFrameMultiplier;rowMode;rowIndex;spriteCount;timeMode;sampleOnceAtStart(){if(this.timeMode===0)switch(this.frameOverTime.mode){case 0:case 3:case 2:case 1:return!0}return!1}getStartIndex(){return this.sampleOnceAtStart()?Math.random()*(this.numTilesX*this.numTilesY):0}evaluate(e){if(!this.sampleOnceAtStart())return this.getIndex(e)}getIndex(e){const t=this.numTilesX*this.numTilesY;e=e*this.cycleCount;let i=this.frameOverTime.evaluate(e%1);return i*=this.frameOverTimeMultiplier,i*=t,i=i%t,i=Math.floor(i),i}}C([f()],Dt.prototype,"animation");C([f()],Dt.prototype,"enabled");C([f()],Dt.prototype,"cycleCount");C([f(H)],Dt.prototype,"frameOverTime");C([f()],Dt.prototype,"frameOverTimeMultiplier");C([f()],Dt.prototype,"numTilesX");C([f()],Dt.prototype,"numTilesY");C([f(H)],Dt.prototype,"startFrame");C([f()],Dt.prototype,"startFrameMultiplier");C([f()],Dt.prototype,"rowMode");C([f()],Dt.prototype,"rowIndex");C([f()],Dt.prototype,"spriteCount");C([f()],Dt.prototype,"timeMode");class mn{enabled;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){return this.enabled?this.separateAxes?0:this.z.evaluate(e,t)*-1:0}}C([f()],mn.prototype,"enabled");C([f()],mn.prototype,"separateAxes");C([f(H)],mn.prototype,"x");C([f()],mn.prototype,"xMultiplier");C([f(H)],mn.prototype,"y");C([f()],mn.prototype,"yMultiplier");C([f(H)],mn.prototype,"z");C([f()],mn.prototype,"zMultiplier");class Gi{enabled;range;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){if(!this.enabled)return 0;if(!this.separateAxes){const i=I.lerp(this.range.x,this.range.y,t);return this.z.evaluate(i)*-1}return 0}}C([f()],Gi.prototype,"enabled");C([f()],Gi.prototype,"range");C([f()],Gi.prototype,"separateAxes");C([f(H)],Gi.prototype,"x");C([f()],Gi.prototype,"xMultiplier");C([f(H)],Gi.prototype,"y");C([f()],Gi.prototype,"yMultiplier");C([f(H)],Gi.prototype,"z");C([f()],Gi.prototype,"zMultiplier");class et{enabled;dampen;drag;dragMultiplier;limit;limitMultiplier;separateAxes;limitX;limitXMultiplier;limitY;limitYMultiplier;limitZ;limitZMultiplier;multiplyDragByParticleSize=!1;multiplyDragByParticleVelocity=!1;space;_temp=new c.Vector3;_temp2=new c.Vector3;apply(e,t,i,n,o,r,a){if(this.enabled){const l=this.limit.evaluate(o)*this.limitMultiplier;if(t.length()>l){this._temp.copy(t).normalize().multiplyScalar(l);const d=this.dampen*.5;t.x=I.lerp(t.x,this._temp.x,d),t.y=I.lerp(t.y,this._temp.y,d),t.z=I.lerp(t.z,this._temp.z,d),i.x=I.lerp(i.x,this._temp.x,d),i.y=I.lerp(i.y,this._temp.y,d),i.z=I.lerp(i.z,this._temp.z,d)}}}}C([f()],et.prototype,"enabled");C([f()],et.prototype,"dampen");C([f(H)],et.prototype,"drag");C([f()],et.prototype,"dragMultiplier");C([f(H)],et.prototype,"limit");C([f()],et.prototype,"limitMultiplier");C([f()],et.prototype,"separateAxes");C([f(H)],et.prototype,"limitX");C([f()],et.prototype,"limitXMultiplier");C([f(H)],et.prototype,"limitY");C([f()],et.prototype,"limitYMultiplier");C([f(H)],et.prototype,"limitZ");C([f()],et.prototype,"limitZMultiplier");C([f()],et.prototype,"multiplyDragByParticleSize");C([f()],et.prototype,"multiplyDragByParticleVelocity");C([f()],et.prototype,"space");const lh=class $w{enabled;curve;curveMultiplier;mode;clone(){const e=new $w;return e.enabled=this.enabled,e.curve=this.curve?.clone(),e.curveMultiplier=this.curveMultiplier,e.mode=this.mode,e}system;get _lastWorldPosition(){return this.system._iv_lastWorldPosition||(this.system._iv_lastWorldPosition=new c.Vector3),this.system._iv_lastWorldPosition}get _velocity(){return this.system._iv_velocity||(this.system._iv_velocity=new c.Vector3),this.system._iv_velocity}_temp=new c.Vector3;_firstUpdate=!0;awake(e){this.system=e,this.reset()}reset(){this._firstUpdate=!0}update(e){this.enabled&&this.system.worldspace!==!1&&(this._firstUpdate?(this._firstUpdate=!1,this._velocity.set(0,0,0),this._lastWorldPosition.copy(this.system.worldPos)):this._lastWorldPosition&&(this._velocity.copy(this.system.worldPos).sub(this._lastWorldPosition).multiplyScalar(1/this.system.deltaTime),this._lastWorldPosition.copy(this.system.worldPos)))}applyInitial(e){if(this.enabled&&this.system.worldspace!==!1&&this.mode===0){const t=this.curve.evaluate(Math.random(),Math.random());this._temp.copy(this._velocity).multiplyScalar(t),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}_frames=0;applyCurrent(e,t,i){if(this.enabled&&this.system&&this.system.worldspace!==!1&&this.mode===1){const n=this.curve.evaluate(t,i);this._temp.copy(this._velocity).multiplyScalar(n),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}};C([f()],lh.prototype,"enabled");C([f(H)],lh.prototype,"curve");C([f()],lh.prototype,"curveMultiplier");C([f()],lh.prototype,"mode");let cy=lh;class ai{enabled;range;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t,i,n){const o=e.length(),r=I.remap(o,this.range.x,this.range.y,0,1),a=this.size.evaluate(r,i);return n.x*=a,n.y*=a,n.z*=a,n}}C([f()],ai.prototype,"enabled");C([f(c.Vector2)],ai.prototype,"range");C([f()],ai.prototype,"separateAxes");C([f(H)],ai.prototype,"size");C([f()],ai.prototype,"sizeMultiplier");C([f(H)],ai.prototype,"x");C([f()],ai.prototype,"xMultiplier");C([f(H)],ai.prototype,"y");C([f()],ai.prototype,"yMultiplier");C([f(H)],ai.prototype,"z");C([f()],ai.prototype,"zMultiplier");class Ja{enabled;range;color;evaluate(e,t,i){const n=e.length(),o=I.remap(n,this.range.x,this.range.y,0,1),r=this.color.evaluate(o,t);i.x*=r.r,i.y*=r.g,i.z*=r.b,"alpha"in r&&(i.w*=r.alpha)}}C([f()],Ja.prototype,"enabled");C([f(c.Vector2)],Ja.prototype,"range");C([f(Tr)],Ja.prototype,"color");new c.Vector3(1,1,1);new c.Vector3(0,0,1);class hy{constructor(e,t,i,n){this.system=e,this.particleSystem=t,this.subSystem=i,this.subParticleSystem=n,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const o=1e3;this._circularBuffer=new mi(()=>new re.Matrix4,o)}type="NeedleParticleSubEmitter";emitterType;emitterProbability;q_=new c.Quaternion;v_=new c.Vector3;v2_=new c.Vector3;_emitterMatrix=new re.Matrix4;_circularBuffer;clone(){throw new Error("Method not implemented.")}initialize(e){e.emissionState={burstIndex:0,burstWaveIndex:0,time:0,waitEmiting:0},this._emitterMatrix.copy(this.subSystem.matrixWorld).invert().premultiply(this.system.matrixWorld),this._emitterMatrix.setPosition(0,0,0),this.emitterType===rm.Birth&&this.run(e)}update(e,t){this.run(e)}frameUpdate(e){}toJSON(){}reset(){}run(e){if(this.subSystem.currentParticles>=this.subSystem.main.maxParticles||!this.subParticleSystem||!e.emissionState||this.emitterProbability&&Math.random()>this.emitterProbability)return;const t=this.system.deltaTime;if(this.emitterType===rm.Death){let n=e.life;if(e[da]!==void 0&&(n=e[da]),!(e.age+t*1.2>=n))return;const r=this.subSystem.main.maxParticles-this.subSystem.currentParticles;e.emissionState.waitEmiting=r}const i=new re.Matrix4;i.set(1,0,0,e.position.x,0,1,0,e.position.y,0,0,1,e.position.z,0,0,0,1),this.particleSystem.worldSpace||i.multiplyMatrices(this._emitterMatrix,i),this.subParticleSystem.emit(t,e.emissionState,i)}}var Nk=Object.defineProperty,Ae=(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&&Nk(e,t,n),n};const qs=x("debugparticles"),Vk=x("noprogressive"),$k=x("debugprogressive");var rm=(s=>(s[s.Birth=0]="Birth",s[s.Collision=1]="Collision",s[s.Death=2]="Death",s[s.Trigger=3]="Trigger",s[s.Manual=4]="Manual",s))(rm||{});class qi extends E{renderMode;particleMaterial;trailMaterial;particleMesh;maxParticleSize;minParticleSize;velocityScale;cameraVelocityScale;lengthScale;start(){if(this.maxParticleSize!==.5&&this.minParticleSize!==0&&T()){const e=`ParticleSystem "${this.name}" has non-default min/max particle size. This may not render correctly. Please set min size to 0 and the max size to 0.5 and use the "StartSize" setting instead`;console.warn(e)}}get transparent(){return this.particleMaterial?.transparent??!1}getMaterial(e=!1){let t=e===!0&&this.trailMaterial?this.trailMaterial:this.particleMaterial;if(t){if(t.type==="MeshStandardMaterial"){qs&&console.debug("ParticleSystemRenderer.getMaterial: MeshStandardMaterial detected, converting to MeshBasicMaterial. See https://github.com/Alchemist0823/three.quarks/issues/101"),"map"in t&&t.map&&(t.map.colorSpace=c.LinearSRGBColorSpace,t.map.premultiplyAlpha=!1);const i=new c.MeshBasicMaterial;i.copy(t),e?this.trailMaterial=i:this.particleMaterial=i}t.map&&(t.map.colorSpace=c.LinearSRGBColorSpace,t.map.premultiplyAlpha=!1),e&&t.side===c.FrontSide&&(t=t.clone(),t.side=c.BackSide,e?this.trailMaterial=t:this.particleMaterial=t)}return t&&!Vk&&t._didRequestTextureLOD===void 0&&(t._didRequestTextureLOD=0,$k&&console.log("Load material LOD",t.name),se.NEEDLE_progressive.assignTextureLOD(t,0)),t}getMesh(e){let t=null;if(!t&&(this.particleMesh instanceof c.Mesh&&(t=this.particleMesh.geometry),t===null)){t=new c.PlaneGeometry(1,1);const n=t.attributes.uv;for(let o=0;o<n.count;o++)n.setX(o,1-n.getX(o))}return new c.Mesh(t,this.getMaterial())}}Ae([f()],qi.prototype,"renderMode");Ae([f(c.Material)],qi.prototype,"particleMaterial");Ae([f(c.Material)],qi.prototype,"trailMaterial");Ae([f()],qi.prototype,"maxParticleSize");Ae([f()],qi.prototype,"minParticleSize");Ae([f()],qi.prototype,"velocityScale");Ae([f()],qi.prototype,"cameraVelocityScale");Ae([f()],qi.prototype,"lengthScale");class Jh{_curve;_factor;constructor(e,t=1){this._curve=e,this._factor=t}type="function";startGen(e){}genValue(e,t){return this._curve.evaluate(t,Math.random())*this._factor}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}}class dy{type="value";toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}startGen(e){}system;constructor(e){this.system=e}}class Wk extends dy{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class Hk extends dy{_lastPosition=new c.Vector3;_lastDistance=0;update(){const e=Q(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(e),this._lastPosition.copy(e)}genValue(){if(!this.system.isPlaying||!this.system.emission.enabled||this.system.currentParticles>=this.system.maxParticles)return 0;let e=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){const n=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let r=this._lastDistance/this.system.deltaTime*n;Number.isFinite(r)||(r=0),e+=r}const t=this.system.emission.getBurst();t>0&&(e+=t/this.system.deltaTime);const i=this.system.maxParticles-this.system.currentParticles;return I.clamp(e,0,i/this.system.deltaTime)}}class Gk extends dy{genValue(){return this.system.isPlaying,0}}class So{system;get context(){return this.system.context}constructor(e){this.type=Object.getPrototypeOf(this).constructor.name||"ParticleSystemBaseBehaviour",e&&(this.system=e)}type;initialize(e){}update(e,t){}frameUpdate(e){}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}reset(){}}class qk extends So{type="NeedleTextureSheet";update(e,t){const i=this.system.textureSheetAnimation;if(i.enabled){const n=e.age/e.life,o=i.evaluate(n);o!==void 0&&(e.uvTile=o)}}}const ub=Symbol("particleRotation");class Xk extends So{type="NeedleRotation";initialize(e){e[ub]=Math.random()}update(e,t){if(e.rotation===void 0)return;const i=e.age/e.life;if(typeof e.rotation=="number"&&(this.system.rotationOverLifetime.enabled?e.rotation+=this.system.rotationOverLifetime.evaluate(i,e[ub])*t:this.system.renderer.renderMode===is.Billboard&&(e.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const n=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(i,n)*t}}}const fb=Symbol("sizeLerpFactor"),Qk=new c.Vector3;class Yk extends So{type="NeedleSize";_minSize=0;_maxSize=1;initialize(e){e[fb]=Math.random(),this._minSize=this.system.renderer.minParticleSize,this._maxSize=this.system.renderer.maxParticleSize}update(e,t){const i=e.age/e.life;let n=1;this.system.sizeOverLifetime.enabled&&(n*=this.system.sizeOverLifetime.evaluate(i,void 0,e[fb]).x);let o=1;this.system.renderer.renderMode!==is.Mesh&&(o=this.system.worldScale.x/this.system.cameraScale);const r=B(e.startSize).multiplyScalar(n*o);if(e.size.set(r.x,r.y,r.z),this.system.localspace){const a=Ww(this.system,Qk);e.size.x*=a.x,e.size.y*=a.y,e.size.z*=a.z}}}const da=Symbol("particleLife"),sp=Symbol("trailLifetime"),pb=Symbol("trailStartLength"),op=Symbol("trailWidthRandom");class Kk extends So{type="NeedleTrail";initialize(e){e instanceof re.TrailParticle&&(e[da]=e.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(e[sp]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),e.life+=e[sp]),e[pb]=e.length,e[op]=Math.random())}update(e){if(this.system.trails?.enabled&&e instanceof re.TrailParticle){const t=e,i=e.age/e[da],n=e.previous.values(),o=e.previous.length;for(let r=0;r<o;r++){const l=n.next().value,h=1-r/(o-1),d=e.size;if(d.x<=0&&!this.system.trails.sizeAffectsWidth){const u=20*this.system.trails.widthOverTrail.evaluate(.5,t[op]);d.x=u,d.y=u,d.z=u}l.size=this.system.trails.getWidth(d.x,i,h,t[op]),l.color.copy(e.color),this.system.trails.getColor(l.color,i,h)}if(e.age>e[da]){e.velocity.set(0,0,0);const r=(e.age-e[da])/e[sp];t.length=I.lerp(e[pb],0,r)}}}}const ed=Symbol("startVelocity"),mb=Symbol("gravityModifier"),rp=Symbol("gravitySpeed"),td=Symbol("velocity lerp factor"),am=new c.Vector3;class Zk extends So{type="NeedleVelocity";_gravityDirection=new c.Vector3;initialize(e){const t=this.system.main.simulationSpeed;e.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random());const i=this.system.shape.getDirection(e,e.position);e.velocity.x=i.x*e.startSpeed,e.velocity.y=i.y*e.startSpeed,e.velocity.z=i.z*e.startSpeed,this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyInitial(e.velocity),e[ed]?e[ed].copy(e.velocity):e[ed]=e.velocity.clone();const n=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());e[mb]=n*t,e[rp]=n*t*.5,e[td]=Math.random(),this.system.velocityOverLifetime?.init(e),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===Cc.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(e,t){const i=e[ed],n=e[mb];if(n!==0){const u=n*e[rp];am.copy(this._gravityDirection).multiplyScalar(u),e[rp]+=t*.05,i.add(am)}e.velocity.copy(i);const o=e.age/e.life;this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyCurrent(e.velocity,o,e[td]);const r=this.system.noise;r.enabled&&r.apply(0,e.position,e.velocity,t,e.age,e.life);const a=this.system.sizeBySpeed;a?.enabled&&(e.size=a.evaluate(e.velocity,o,e[td],e.size));const l=this.system.colorBySpeed;l?.enabled&&l.evaluate(e.velocity,e[td],e.color);const h=this.system.velocityOverLifetime;h.enabled&&h.apply(e,0,e.position,e.velocity,t,e.age,e.life);const d=this.system.limitVelocityOverLifetime;if(d.enabled&&d.apply(e.position,i,e.velocity,e.size,o,t,1),this.system.worldspace){const u=this.system.worldScale;e.velocity.x*=u.x,e.velocity.y*=u.y,e.velocity.z*=u.z}}}const gb=Symbol("colorLerpFactor"),yb=new ee(1,1,1,1),Io=new ee(1,1,1,1);class Jk extends So{type="NeedleColor";initialize(e){}_init(e){const t=this.system.renderer.particleMaterial;Io.copy(this.system.main.startColor.evaluate(Math.random())),t?.color&&(yb.copy(t.color),Io.multiply(yb)),Io.convertLinearToSRGB(),e.startColor.set(Io.r,Io.g,Io.b,Io.alpha),e.color.copy(e.startColor),e[gb]=Math.random()}update(e,t){if(e.age===0&&this._init(e),this.system.colorOverLifetime.enabled){const i=e.age/e.life,n=this.system.colorOverLifetime.color.evaluate(i,e[gb]);e.color.set(n.r,n.g,n.b,"alpha"in n?n.alpha:1).multiply(e.startColor)}else e.color.copy(e.startColor)}}class eE{system;emission;get anim(){return this.system.textureSheetAnimation}constructor(e){this.system=e,this.emission=new Hk(this.system)}get prewarm(){return!1}get material(){return this.system.renderer.getMaterial(this.system.trails.enabled)}get layers(){return this.system.gameObject.layers}update(){this.emission.update()}autoDestroy;get looping(){return this.system.main.loop}get duration(){return this.system.duration}get shape(){return this.system.shape}get startLife(){return new Jh(this.system.main.startLifetime)}get startSpeed(){return new Jh(this.system.main.startSpeed)}get startRotation(){return new Jh(this.system.main.startRotation)}get startSize(){return new Jh(this.system.main.startSize)}startLength;get startColor(){return new re.ConstantColor(new re.Vector4(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new Gk(this.system)}emissionBursts;onlyUsedByOther;behaviors=[];get instancingGeometry(){return this.system.renderer.getMesh(this.system.renderer.renderMode).geometry}get renderMode(){if(this.system.trails.enabled===!0)return re.RenderMode.Trail;switch(this.system.renderer.renderMode){case is.Billboard:return re.RenderMode.BillBoard;case is.Stretch:return re.RenderMode.StretchedBillBoard;case is.HorizontalBillboard:return re.RenderMode.HorizontalBillBoard;case is.VerticalBillboard:return re.RenderMode.VerticalBillBoard;case is.Mesh:return re.RenderMode.Mesh}return re.RenderMode.BillBoard}rendererEmitterSettings={startLength:new re.ConstantValue(220),followLocalOrigin:!1};get speedFactor(){let e=this.system.main.simulationSpeed;return this.system.renderer?.renderMode===is.Stretch&&(e*=this.system.renderer.velocityScale??1),e}flatWhiteTexture;clonedTexture={original:void 0,clone:void 0};get texture(){const e=this.material;if(e&&e.map){const t=e.map;if(this.clonedTexture.original!==t||!this.clonedTexture.clone){const i=t.clone();i.premultiplyAlpha=!1,i.colorSpace=c.LinearSRGBColorSpace,this.clonedTexture.original=t,this.clonedTexture.clone=i}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=Jm(new ee(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new Wk(this.system)}get uTileCount(){return this.anim.enabled?this.anim?.numTilesX:void 0}get vTileCount(){return this.anim.enabled?this.anim?.numTilesY:void 0}get renderOrder(){return 1}get blending(){return this.system.renderer.particleMaterial?.blending??c.NormalBlending}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===Cc.World}}class tE{burstParticleIndex=0;burstParticleCount=0;isBursting=!1;travelDistance=0;previousWorldPos;burstIndex=0;burstWaveIndex=0;time=0;waitEmiting=0}const Lt=class xd extends E{play(e=!1){e&&S.foreachComponent(this.gameObject,t=>{t instanceof xd&&t!==this&&t.play(!1)},!0),this._isPlaying=!0,this._particleSystem&&(this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1),this.emission?.reset()}pause(e=!0){e&&S.foreachComponent(this.gameObject,t=>{t instanceof xd&&t!==this&&t.pause(!1)},!0),this._isPlaying=!1}stop(e=!0,t=!1){e&&S.foreachComponent(this.gameObject,i=>{i instanceof xd&&i!==this&&i.stop(!1,t)},!0),this._isPlaying=!1,this._time=0,t&&this.reset()}reset(){this._time=0,this._particleSystem&&(this._particleSystem.particleNum=0,this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1,this.emission?.reset())}_state;emit(e){if(this._particleSystem){this.onUpdate(),e=Math.min(e,this.maxParticles-this.currentParticles),this._state||(this._state=new tE),this._state.waitEmiting=e,this._state.time=0;const t=this._particleSystem.emitEnded;this._particleSystem.emitEnded=!1,this._particleSystem.emit(this.deltaTime,this._state,this._particleSystem.emitter.matrixWorld),this._particleSystem.emitEnded=t}}get playOnAwake(){return this.main.playOnAwake}set playOnAwake(e){this.main.playOnAwake=e}colorOverLifetime;main;emission;sizeOverLifetime;shape;noise;trails;velocityOverLifetime;limitVelocityOverLifetime;inheritVelocity;colorBySpeed;textureSheetAnimation;rotationOverLifetime;rotationBySpeed;sizeBySpeed;get renderer(){return this._renderer}get isPlaying(){return this._isPlaying}get currentParticles(){return this._particleSystem?.particleNum??0}get maxParticles(){return this.main.maxParticles}get time(){return this._time}get duration(){return this.main.duration}get deltaTime(){return this.context.time.deltaTime*this.main.simulationSpeed}get scale(){return this.gameObject.scale.x}get cameraScale(){return this._cameraScale}_cameraScale=1;get container(){return this._container}get worldspace(){return this.main.simulationSpace===Cc.World}get localspace(){return this.main.simulationSpace===Cc.Local}__worldQuaternion=new c.Quaternion;get worldQuaternion(){return this.__worldQuaternion}_worldQuaternionInverted=new c.Quaternion;get worldQuaternionInverted(){return this._worldQuaternionInverted}_worldScale=new c.Vector3;get worldScale(){return this._worldScale}_worldPositionFrame=-1;_worldPos=new c.Vector3;get worldPos(){return this._worldPositionFrame!==this.context.time.frame&&(this._worldPositionFrame=this.context.time.frame,Q(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}addBehaviour(e){return this._particleSystem?(e instanceof So&&(e.system=this),qs&&console.debug("Add custom ParticleSystem Behaviour",e),this._particleSystem.addBehavior(e),!0):!1}removeBehaviour(e){if(!this._particleSystem)return!1;const t=this._particleSystem.behaviors,i=t.indexOf(e);return i!==-1&&((T()||qs)&&console.debug("Remove custom ParticleSystem Behaviour",i,e),t.splice(i,1)),!0}removeAllBehaviours(){return this._particleSystem?(this._particleSystem.behaviors.length=0,!0):!1}get behaviours(){return this._particleSystem?this._particleSystem.behaviors:null}get particleSystem(){return this._particleSystem??null}_renderer;_batchSystem;_particleSystem;_interface;_container;_time=0;_isPlaying=!0;_isUsedAsSubsystem=!1;_didPreWarm=!1;set bursts(e){for(let t=0;t<e.length;t++){const i=e[t];if(!(i instanceof Kd)){const n=new Kd;Ra(n,i),e[t]=n}}this._bursts=e}_bursts;set subEmitterSystems(e){for(let t=0;t<e.length;t++){const i=e[t];if(!(i instanceof Zd)){const n=new Zd;Ra(n,i),e[t]=n}}qs&&e.length>0&&console.log("SubEmitters: ",e,this),this._subEmitterSystems=e}_subEmitterSystems;onAfterDeserialize(e){if(this._subEmitterSystems&&Array.isArray(this._subEmitterSystems))for(const t of this._subEmitterSystems)t._deserialize(this.context,this.gameObject)}awake(){if(this._worldPositionFrame=-1,this._renderer=this.gameObject.getComponent(qi),!this.main)throw new Error("Not Supported: ParticleSystem needs a serialized MainModule. Creating new particle systems at runtime is currently not supported.");this._container=new c.Object3D,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new re.BatchedParticleRenderer,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new eE(this),this._particleSystem=new re.ParticleSystem(this._interface),this._particleSystem.addBehavior(new Yk(this)),this._particleSystem.addBehavior(new Jk(this)),this._particleSystem.addBehavior(new qk(this)),this._particleSystem.addBehavior(new Xk(this)),this._particleSystem.addBehavior(new Zk(this)),this._particleSystem.addBehavior(new Kk(this)),this._batchSystem.addSystem(this._particleSystem);const e=this._particleSystem.emitter;this.context.scene.add(e),this.inheritVelocity.system&&this.inheritVelocity.system!==this&&(this.inheritVelocity=this.inheritVelocity.clone()),this.inheritVelocity.awake(this),qs&&(console.log(this),this.gameObject.add(new c.AxesHelper(1)))}start(){this.addSubParticleSystems(),this.updateLayers(),this.renderer.particleMesh instanceof c.Mesh&&this._interface.renderMode==re.RenderMode.Mesh&&se.NEEDLE_progressive.assignMeshLOD(this.renderer.particleMesh,0).then(e=>{e&&this.particleSystem&&this._interface.renderMode==re.RenderMode.Mesh&&(this.particleSystem.instancingGeometry=e)})}onDestroy(){this._container?.removeFromParent(),this._batchSystem?.removeFromParent(),this._particleSystem?.emitter.removeFromParent(),this._particleSystem?.dispose()}onEnable(){this.main&&(this.inheritVelocity&&(this.inheritVelocity.system=this),this._batchSystem&&(this._batchSystem.visible=!0),this.playOnAwake&&this.play(),this._isPlaying=this.playOnAwake)}onDisable(){this._batchSystem&&(this._batchSystem.visible=!1)}onBeforeRender(){this.main&&(this._didPreWarm===!1&&this.main?.prewarm===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){if(!this.emission?.enabled||this.emission.rateOverTime.getMax()<=0)return;const t=1/60,i=this.main.duration,n=this.main.startLifetime.getMax(),r=Math.min(Math.max(i,n)/Math.max(.01,this.main.simulationSpeed),1e3),a=Math.ceil(r/t),l=Date.now();qs&&console.log(`Particles ${this.name} - Prewarm for ${a} frames (${r} sec). Duration: ${i}, Lifetime: ${n}`);for(let h=0;h<a&&!(this.currentParticles>=this.maxParticles);h++){const d=Date.now()-l;if(d>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${d}`);break}this.onUpdate(),this.onSimulate(t)}}_lastBatchesCount=-1;onSimulate(e){if(this._batchSystem){let t=this.context.time.frameCount%60===0;this._lastBatchesCount!==this._batchSystem.batches.length&&(this._lastBatchesCount=this._batchSystem.batches.length,t=!0),t&&this.updateLayers(),this._batchSystem.update(e)}this._time+=e,this._time>this.duration&&(this._time=0)}updateLayers(){if(this._batchSystem)for(let e=0;e<this._batchSystem.batches.length;e++){const t=this._batchSystem.batches[e];t.layers.disableAll();const i=this.layer;t.layers.mask=1<<i}}onUpdate(){if(this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const e=this.context.mainCamera;if(e){const n=Le(e);this._cameraScale=n.x}const t=!this.worldspace,i=this.gameObject;if(fe(i,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),Le(this.gameObject,this._worldScale),t&&this._container&&this.gameObject?.parent){const n=Ww(this,am);this._container.matrix.makeScale(n.x,n.y,n.z),this._container.matrix.makeRotationFromQuaternion(this.__worldQuaternion),this._container.matrix.setPosition(this.worldPos),this._container.matrix.scale(this.gameObject.scale)}this.emission.system=this,this._interface.update(),this.shape.onUpdate(this,this.context,this.main.simulationSpace,this.gameObject),this.noise.update(this.context),this.inheritVelocity?.update(this.context),this.velocityOverLifetime.update(this)}addSubParticleSystems(){if(this._subEmitterSystems&&this._particleSystem)for(const e of this._subEmitterSystems){e.particleSystem&&(e.particleSystem.__internalAwake?e.particleSystem.__internalAwake():T()&&console.warn("SubParticleSystem serialization issue(?)",e.particleSystem,e));const t=e.particleSystem?._particleSystem;if(t){e.particleSystem._isUsedAsSubsystem=!0;const i=new hy(this,this._particleSystem,e.particleSystem,t);i.emitterType=e.type,i.emitterProbability=e.emitProbability,this._particleSystem.addBehavior(i)}else qs&&console.warn("Could not add SubParticleSystem",e,this)}}};Ae([f(Fu)],Lt.prototype,"colorOverLifetime");Ae([f(At)],Lt.prototype,"main");Ae([f(Cs)],Lt.prototype,"emission");Ae([f(Ar)],Lt.prototype,"sizeOverLifetime");Ae([f(ly)],Lt.prototype,"shape");Ae([f(pe)],Lt.prototype,"noise");Ae([f(Te)],Lt.prototype,"trails");Ae([f(Ie)],Lt.prototype,"velocityOverLifetime");Ae([f(et)],Lt.prototype,"limitVelocityOverLifetime");Ae([f(cy)],Lt.prototype,"inheritVelocity");Ae([f(Ja)],Lt.prototype,"colorBySpeed");Ae([f(Dt)],Lt.prototype,"textureSheetAnimation");Ae([f(mn)],Lt.prototype,"rotationOverLifetime");Ae([f(Gi)],Lt.prototype,"rotationBySpeed");Ae([f(ai)],Lt.prototype,"sizeBySpeed");let Pc=Lt;class Zd{particleSystem;emitProbability=1;properties;type;_deserialize(e,t){const i=this.particleSystem;if(i instanceof Pc)return;let n="";i&&typeof i.guid=="string"&&(n=i.guid,this.particleSystem=S.findByGuid(n,t)),qs&&!(this.particleSystem instanceof Pc)&&console.warn("Could not find particle system for sub emitter",n,t,this)}}function Ww(s,e){if(e.set(1,1,1),s.gameObject.parent&&s.localspace)switch(s.main.scalingMode){case om.Local:e=Le(s.gameObject.parent,e),e.x=1/e.x,e.y=1/e.y,e.z=1/e.z;break;default:if(!s.unsupported_scaling_mode){s.unsupported_scaling_mode=!0;const t="ParticleSystem scale mode "+om[s.main.scalingMode]+" is not supported";T()&&ue(t),console.warn(t,s.name,s)}e=Le(s.gameObject,e);break}return e}var iE=Object.defineProperty,uy=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&iE(e,t,n),n};class el extends E{strength=1;radius=2;targets=[];update(){const e=this.gameObject.worldPosition,t=-this.strength*this.context.time.deltaTime;this.targets?.forEach(i=>{if(!i)return;const n=i.gameObject.worldPosition.sub(e),o=n.length();if(o>this.radius)return;let r=t;o>1?r/=o*o:r/=Math.max(.05,o),i.applyImpulse(n.multiplyScalar(r))})}}uy([f()],el.prototype,"strength");uy([f()],el.prototype,"radius");uy([f(Fe)],el.prototype,"targets");class La extends E{_didAssignPlayerColor=!1;onEnable(){this.context.connection.beginListen(Y.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(Y.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield Zm(.2),!this.tryAssignColor()););}tryAssignColor=()=>{const e=S.getComponentInParent(this.gameObject,Ui);if(e&&e.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(e.owner),!0;const t=S.getComponentInParent(this.gameObject,Pe);return t?.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(t.connectionId),!0):!1};assignUserColor(e){const t=La.hashCode(e),i=La.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){const n=this.gameObject;this.assignColor(i,e,n)}else if(this.gameObject.children)for(const n of this.gameObject.children){const o=n;o.material&&o.material.color&&this.assignColor(i,e,o)}}assignColor(e,t,i){let n=i.material;n&&(n._playerMaterial!==t&&(n=n.clone(),n._playerMaterial=t,i.material=n),n.color=e)}static hashCode(e){var t=0,i,n;if(e.length===0)return t;for(i=0;i<e.length;i++)n=e.charCodeAt(i),t=(t<<5)-t+n,t|=0;return t}static colorFromHashCode(e){const t=(e&16711680)>>16,i=(e&65280)>>8,n=e&255;return new c.Color(t/255,i/255,n/255)}}const Hl=x("debugpost");let lm=null;function nE(s){lm=s}function Hw(s){let e=s.gameObject;for(;e;){for(const t of du(e))if(t.isPostProcessingManager===!0)return t;e=e.parent}return null}function sE(s){let e=Hw(s);if(!e)if(lm){Hl&&console.warn("Adding postprocessing manager to the scene.");const t=s.scene;e=on(t,lm)}else T()&&console.warn("No post processing manager found");return e}const Ke={AT_START:-1e4,NormalPass:0,DepthDownsamplingPass:10,SSAO:20,SMAA:30,TiltShift:40,DepthOfField:50,ChromaticAberration:60,Bloom:70,Vignette:80,Pixelation:90,ToneMapping:100,HueSaturation:110,BrightnessContrast:120,Sharpening:130,AT_END:1e4};let Ve=null;function oE(s){Hl==="verbose"&&console.debug("Before ordering effects",[...s]),Ve||(Ve=new Map,Ve.set(exports.MODULES.POSTPROCESSING.MODULE.NormalPass,Ke.NormalPass),Ve.set(exports.MODULES.POSTPROCESSING.MODULE.DepthDownsamplingPass,Ke.DepthDownsamplingPass),Ve.set(exports.MODULES.POSTPROCESSING.MODULE.SMAAEffect,Ke.SMAA),Ve.set(exports.MODULES.POSTPROCESSING.MODULE.SSAOEffect,Ke.SSAO),Ve.set(exports.MODULES.POSTPROCESSING_AO.MODULE.N8AOPostPass,Ke.SSAO),Ve.set(exports.MODULES.POSTPROCESSING_AO.MODULE.N8AOPass,Ke.SSAO),Ve.set(exports.MODULES.POSTPROCESSING.MODULE.TiltShiftEffect,Ke.TiltShift),Ve.set(exports.MODULES.POSTPROCESSING.MODULE.DepthOfFieldEffect,Ke.DepthOfField),Ve.set(exports.MODULES.POSTPROCESSING.MODULE.ChromaticAberrationEffect,Ke.ChromaticAberration),Ve.set(exports.MODULES.POSTPROCESSING.MODULE.BloomEffect,Ke.Bloom),Ve.set(exports.MODULES.POSTPROCESSING.MODULE.SelectiveBloomEffect,Ke.Bloom),Ve.set(exports.MODULES.POSTPROCESSING.MODULE.VignetteEffect,Ke.Vignette),Ve.set(exports.MODULES.POSTPROCESSING.MODULE.PixelationEffect,Ke.Pixelation),Ve.set(exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect,Ke.ToneMapping),Ve.set(exports.MODULES.POSTPROCESSING.MODULE.HueSaturationEffect,Ke.HueSaturation),Ve.set(exports.MODULES.POSTPROCESSING.MODULE.BrightnessContrastEffect,Ke.BrightnessContrast)),s.sort((e,t)=>{const i=typeof e.priority=="number"?e.priority:Ve.get(e.effect.constructor)??Number.NEGATIVE_INFINITY,n=typeof t.priority=="number"?t.priority:Ve.get(t.effect.constructor)??Number.NEGATIVE_INFINITY;return i===Number.NEGATIVE_INFINITY?(Hl&&console.warn("Unknown effect found: ",e.constructor.name,e),1):n===Number.NEGATIVE_INFINITY?(Hl&&console.warn("Unknown effect found: ",t.constructor.name,t),-1):i-n}),Hl==="verbose"&&console.debug("After ordering effects",[...s])}var rE=Object.defineProperty,aE=Object.getOwnPropertyDescriptor,Gw=(s,e,t,i)=>{for(var n=aE(e,t),o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&rE(e,t,n),n};const lE=x("debugpost");class F{isVolumeParameter=!0;constructor(e){e!==void 0&&this.initialize(e)}_isInitialized=!1;get isInitialized(){return this._isInitialized}initialize(e){e!==void 0&&(this._value=e,this._defaultValue=e,this._valueRaw=e,this._isInitialized=!0)}get overrideState(){return this._active}set overrideState(e){if(this._active===e)return;this._active=e;const t=e?this._valueRaw:this._defaultValue;this.processValue(t,!0)}_active=!0;get value(){return this._valueRaw}set value(e){this.isInitialized||this.initialize(e),this.processValue(e,!1)}_value;_valueRaw;set defaultValue(e){this._defaultValue=e}_defaultValue=void 0;__init(){this.processValue(this._valueRaw,!0)}valueProcessor;onValueChanged;processValue(e,t){if(e==null||!t&&this.testIfValueChanged(e)===!1)return;const i=this._value;lE&&typeof i=="number"&&typeof e=="number"&&(i?.toFixed(4),e?.toFixed(4)),!this._active&&this._defaultValue!==void 0?(this._value=this._defaultValue,e=this._defaultValue,this._valueRaw=e):(this._valueRaw=e,this._active&&this.valueProcessor&&(e=this.valueProcessor(e)),this._value=e),this.onValueChanged&&this.onValueChanged(e,i,this)}testIfValueChanged(e){return this._valueRaw!==e}}Gw([f()],F.prototype,"overrideState");Gw([f()],F.prototype,"value");class cE extends $i{constructor(){super([F])}onSerialize(e,t){}onDeserialize(e,t){const i=t.target,n=t.path;let o;if(i&&n&&(o=i[n]),(typeof o!="object"||typeof o=="object"&&o.isVolumeParameter!==!0)&&(o=new F),typeof e=="object"&&"value"in e){const r=e.value;o.initialize(r),o.overrideState=e.overrideState}else o.value=e;return o}}new cE;var hE=Object.defineProperty,dE=(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&&hE(e,t,n),n};const ap=x("debugpost");class He extends E{get isPostProcessingEffect(){return!0}order=void 0;constructor(e=void 0){if(super(),e)for(const t of Object.keys(e)){const i=e[t],n=this[t];n instanceof F?n.initialize(i):n!==void 0&&(this[t]=i)}}active=!0;_manager=null;onEnable(){super.onEnable(),ap&&console.warn("Enable",this.constructor.name+(this.__internalDidAwakeAndStart?"":" (awake)")),this.__internalDidAwakeAndStart&&(this.active=!0),this.onEffectEnabled()}onDisable(){super.onDisable(),ap&&console.warn("Disable",this.constructor.name),this._manager?.removeEffect(this),this.active=!1}onEffectEnabled(e){e&&e.isPostProcessingManager===!0?this._manager=e:this._manager||(this._manager=sE(this)),this._manager.addEffect(this),this._manager.dirty=!0}init(){}_result;_postprocessingContext=null;get postprocessingContext(){return this._postprocessingContext}apply(e){return this._postprocessingContext=e,this._result||(this.initParameters(),this._result=this.onCreateEffect?.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){ap&&console.warn("DISPOSE",this),this._result&&(Array.isArray(this._result)?this._result.forEach(e=>e.dispose()):this._result.dispose()),this._result=void 0}initParameters(){const e=Object.keys(this);for(const t of e){const i=this[t];i instanceof F&&i.__init()}}onEditorModification(e){const t=e.propertyName;if(this[t]instanceof F){const i=e.value;return this[t].value=i,!0}}}dE([f()],He.prototype,"active");var uE=Object.defineProperty,fE=(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&&uE(e,t,n),n};const pE=x("debugpost"),cm={};function Xi(s,e){cm[s]=e}function mE(s){return s.__type in cm?cm[s.__type]:(pE&&s.__type&&console.warn("Unknown postprocessing type",s.__type,s),He)}class zu{components=[];__init(e){this.components?.forEach(t=>{t.gameObject===void 0&&e.gameObject.addComponent(t),t.init()})}addEffect(e){this.components.push(e)}removeEffect(e){const t=this.components.indexOf(e);t>=0&&this.components.splice(t,1)}}fE([ze([s=>mE(s),He])],zu.prototype,"components");var gE=Object.defineProperty,yE=(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&&gE(e,t,n),n};const _E=x("debugpost");class ch extends He{get typeName(){return"Antialiasing"}preset=new F(2);onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.SMAAEffect({preset:this.preset?.value??exports.MODULES.POSTPROCESSING.MODULE.SMAAPreset.HIGH,edgeDetectionMode:exports.MODULES.POSTPROCESSING.MODULE.EdgeDetectionMode.LUMA});return this.preset.onValueChanged=t=>{_E&&console.log("Antialiasing preset changed to",t),e.applyPreset(t)},e}}yE([f(F)],ch.prototype,"preset");Xi("Antialiasing",ch);var bE=Object.defineProperty,fy=(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&&bE(e,t,n),n};const Nu=class qw extends He{static useSelectiveBloom=!1;get typeName(){return"Bloom"}threshold=new F(.9);intensity=new F(1);scatter=new F(.7);selectiveBloom;init(){this.threshold.valueProcessor=e=>e,this.intensity.valueProcessor=e=>e,this.scatter.valueProcessor=e=>e}onCreateEffect(){let e;if(this.selectiveBloom==null&&(this.selectiveBloom=qw.useSelectiveBloom),this.selectiveBloom){const t=e=new exports.MODULES.POSTPROCESSING.MODULE.SelectiveBloomEffect(this.context.scene,this.context.mainCamera,{blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});t.inverted=!0}else e=new exports.MODULES.POSTPROCESSING.MODULE.BloomEffect({blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});return this.intensity.onValueChanged=t=>{e.intensity=t},this.threshold.onValueChanged=t=>{e.luminanceMaterial.threshold=Math.pow(t,2.2)},this.scatter.onValueChanged=t=>{e.luminancePass.enabled=!0,e.luminanceMaterial.smoothing=t,e.mipmapBlurPass&&(e.mipmapBlurPass.radius=c.MathUtils.lerp(.1,.9,t))},e}};fy([f(F)],Nu.prototype,"threshold");fy([f(F)],Nu.prototype,"intensity");fy([f(F)],Nu.prototype,"scatter");let Vu=Nu;Xi("Bloom",Vu);var vE=Object.defineProperty,wE=(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&&vE(e,t,n),n};class hh extends He{get typeName(){return"ChromaticAberration"}intensity=new F(0);onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.ChromaticAberrationEffect;return e.offset=new c.Vector2(0,0),e.radialModulation=!0,e.modulationOffset=.15,this.intensity.valueProcessor=t=>t*.02,this.intensity.onValueChanged=t=>{e.offset.x=-t,e.offset.y=t},e}}wE([f(F)],hh.prototype,"intensity");Xi("ChromaticAberration",hh);var Gl=(s=>(s[s.None=0]="None",s[s.Neutral=1]="Neutral",s[s.ACES=2]="ACES",s[s.AgX=3]="AgX",s[s.KhronosNeutral=4]="KhronosNeutral",s))(Gl||{});const _b=new Map;function lp(s){switch(s){case 0:return c.LinearToneMapping;case 1:return c.ReinhardToneMapping;case 2:return c.ACESFilmicToneMapping;case 3:return c.AgXToneMapping;case 4:return c.NeutralToneMapping;default:return _b.has(s)||(_b.set(s,!0),console.warn("[Postprocessing] Unknown tone mapping mode",s)),c.NeutralToneMapping}}function xE(s){switch(s){case c.LinearToneMapping:return 0;case c.ACESFilmicToneMapping:return 2;case c.AgXToneMapping:return 3;case c.NeutralToneMapping:return 1;case c.ReinhardToneMapping:return 1;default:return 0}}function Sd(s){switch(s){case c.LinearToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR;case c.ACESFilmicToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.ACES_FILMIC;case c.AgXToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.AGX;case c.NeutralToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.NEUTRAL;case c.ReinhardToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.REINHARD;default:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR}}var SE=Object.defineProperty,Xw=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&SE(e,t,n),n};const cp=x("debugpost");class co extends He{get typeName(){return"ToneMapping"}mode=new F(void 0);exposure=new F(1);setMode(e){const t=Gl[e];return t===void 0?(console.error("[PostProcessing] Invalid ToneMapping mode",e),this):(this.mode.value=t,this)}get isToneMapping(){return!0}onEffectEnabled(){const e=Hw(this);e&&super.onEffectEnabled(e)}_tonemappingEffect=null;onCreateEffect(){if(this.mode.isInitialized==!1){const i=xE(this.context.renderer.toneMapping);cp&&console.log("[PostProcessing] Initializing ToneMapping mode to renderer.toneMapping",this.context.renderer.toneMapping+" → "+i),this.mode.initialize(i)}this._tonemappingEffect?.dispose();const e=lp(this.mode.value),t=this._tonemappingEffect=new exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect({mode:Sd(e)});return this.mode.onValueChanged=i=>{if(typeof i=="string")i=S0(i),t.mode=Sd(i);else{const n=lp(i);t.mode=Sd(n)}t.name="ToneMapping ("+Gl[i]+")",cp&&console.log("[PostProcessing] ToneMapping mode changed to",Gl[i],e,t.mode)},cp&&console.log("[PostProcessing] Use ToneMapping",Gl[this.mode.value],e,t.mode,"renderer.tonemapping: "+this.context.renderer.toneMapping),t}onBeforeRender(){if(this._tonemappingEffect&&this.postprocessingContext?.handler.getEffectIsActive(this._tonemappingEffect)&&(this.mode.overrideState&&(this.context.renderer.toneMapping=lp(this.mode.value)),this.exposure.overrideState&&this.exposure.value!==void 0)){const e=Math.max(0,this.exposure.value);this.context.renderer.toneMappingExposure=e}}}Xw([f(F)],co.prototype,"mode");Xw([f(F)],co.prototype,"exposure");Xi("Tonemapping",co);var CE=Object.defineProperty,$u=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&CE(e,t,n),n};class Co extends He{get typeName(){return"ColorAdjustments"}remap=!0;postExposure=new F(1);contrast=new F(0);hueShift=new F(0);saturation=new F(0);init(){this.postExposure.valueProcessor=e=>(this.remap&&(e=Math.pow(2,e)),e),this.contrast.valueProcessor=e=>{if(!this.remap)return e;let t=1;return e>0?t=200:e<0&&(t=100),e/t},this.contrast.defaultValue=0,this.hueShift.valueProcessor=e=>this.remap?Math.PI*e/180:e,this.hueShift.defaultValue=0,this.saturation.valueProcessor=e=>this.remap?e<0?e/100:e/(100*Math.PI):e,this.saturation.defaultValue=0}onCreateEffect(){const e=[];let t=this.postprocessingContext?.components.find(o=>o instanceof co);t||(t=new co,this.postprocessingContext?.components.push(t)),this.postExposure.onValueChanged=o=>{this.postExposure.overrideState&&t?t.exposure.value=o:console.warn("[PostProcessing] PostExposure is set to override but no ToneMappingEffect found in the postprocessing stack. Please add a ToneMappingEffect to your postprocessing stack to use PostExposure.")};const i=new exports.MODULES.POSTPROCESSING.MODULE.BrightnessContrastEffect;this.contrast.onValueChanged=o=>i.contrast=o;const n=new exports.MODULES.POSTPROCESSING.MODULE.HueSaturationEffect;return this.hueShift.onValueChanged=o=>n.hue=o,this.saturation.onValueChanged=o=>n.saturation=o,e.push(i),e.push(n),e}}$u([f(F)],Co.prototype,"postExposure");$u([f(F)],Co.prototype,"contrast");$u([f(F)],Co.prototype,"hueShift");$u([f(F)],Co.prototype,"saturation");Xi("ColorAdjustments",Co);var PE=Object.defineProperty,Dr=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&PE(e,t,n),n};const ME=x("debugpost");class gn extends He{get typeName(){return"DepthOfField"}mode;focusDistance=new F(1);focalLength=new F(.2);aperture=new F(20);gaussianMaxRadius=new F;resolutionScale=new F(1/window.devicePixelRatio);bokehScale=new F;init(){this.focalLength.valueProcessor=t=>{const i=t/300;return I.lerp(2,.01,i)};const e=20;this.aperture.valueProcessor=t=>{const i=1-t/32;return I.lerp(1,e,i)}}onCreateEffect(){if(this.mode===0){ME&&console.warn("DepthOfField: Mode is set to Off");return}const e=new exports.MODULES.POSTPROCESSING.MODULE.DepthOfFieldEffect(this.context.mainCamera,{worldFocusRange:.2,focalLength:1,bokehScale:20,resolutionScale:this.resolutionScale.value});return this.focusDistance.onValueChanged=t=>{e.cocMaterial.worldFocusDistance=t},this.focalLength.onValueChanged=t=>e.cocMaterial.worldFocusRange=t,this.aperture.onValueChanged=t=>e.bokehScale=t,this.resolutionScale&&(this.resolutionScale.onValueChanged=t=>e.resolution.scale=t),[e]}unapply(){}}Dr([f()],gn.prototype,"mode");Dr([f(F)],gn.prototype,"focusDistance");Dr([f(F)],gn.prototype,"focalLength");Dr([f(F)],gn.prototype,"aperture");Dr([f(F)],gn.prototype,"gaussianMaxRadius");Dr([f(F)],gn.prototype,"resolutionScale");Dr([f(F)],gn.prototype,"bokehScale");Xi("DepthOfField",gn);class Mc extends He{effect;constructor(e){super(),this.effect=e}get typeName(){return this.effect.constructor.name}onCreateEffect(){return this.effect}}var OE=Object.defineProperty,kE=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&OE(e,t,n),n};class dh extends He{get typeName(){return"PixelationEffect"}granularity=new F(10);onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.PixelationEffect;return this.granularity.onValueChanged=t=>{e.granularity=t},e}}kE([f(F)],dh.prototype,"granularity");Xi("PixelationEffect",dh);var EE=Object.defineProperty,uh=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&EE(e,t,n),n};class Ps extends He{get typeName(){return"ScreenSpaceAmbientOcclusion"}intensity=new F(2);falloff=new F(1);samples=new F(9);color=new F(new c.Color(0,0,0));luminanceInfluence=new F(.7);onBeforeRender(){if(this._ssao&&this.context.mainCamera instanceof c.PerspectiveCamera){const e=this.context.mainCamera.far-this.context.mainCamera.near;this._ssao.ssaoMaterial.worldDistanceFalloff=e*.01,this._ssao.ssaoMaterial.worldDistanceThreshold=this.context.mainCamera.far}}_ssao;onCreateEffect(){const e=this.context.mainCamera,t=new exports.MODULES.POSTPROCESSING.MODULE.NormalPass(this.context.scene,e),i=new exports.MODULES.POSTPROCESSING.MODULE.DepthDownsamplingPass({normalBuffer:t.texture,resolutionScale:.5}),n=this._ssao=new exports.MODULES.POSTPROCESSING.MODULE.SSAOEffect(e,t.texture,{normalDepthBuffer:i.texture,worldDistanceThreshold:1,worldDistanceFalloff:1,worldProximityThreshold:.1,worldProximityFalloff:2,intensity:1,blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.MULTIPLY,luminanceInfluence:.5});this.intensity.onValueChanged=r=>{n.intensity=r},this.falloff.onValueChanged=r=>{n.ssaoMaterial.radius=r*.1},this.samples.onValueChanged=r=>{n.ssaoMaterial.samples=r},this.color.onValueChanged=r=>{n.color||(n.color=new c.Color),n.color.copy(r)},this.luminanceInfluence.onValueChanged=r=>{n.luminanceInfluence=r};const o=new Array;return o.push(t),o.push(i),o.push(n),o}}uh([f(F)],Ps.prototype,"intensity");uh([f(F)],Ps.prototype,"falloff");uh([f(F)],Ps.prototype,"samples");uh([f(F)],Ps.prototype,"color");uh([f(F)],Ps.prototype,"luminanceInfluence");Xi("ScreenSpaceAmbientOcclusion",Ps);var RE=Object.defineProperty,Lr=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&RE(e,t,n),n};const TE=x("debugN8AO");var hm=(s=>(s[s.Performance=0]="Performance",s[s.Low=1]="Low",s[s.Medium=2]="Medium",s[s.High=3]="High",s[s.Ultra=4]="Ultra",s))(hm||{});class yn extends He{get typeName(){return"ScreenSpaceAmbientOcclusionN8"}get pass(){return this._ssao}gammaCorrection=!0;aoRadius=new F(1);falloff=new F(1);intensity=new F(1);color=new F(new c.Color(0,0,0));screenspaceRadius=!1;quality=2;_ssao;onValidate(){this._ssao&&(this._ssao.setQualityMode(hm[this.quality]),this._ssao.configuration.gammaCorrection=this.gammaCorrection,this._ssao.configuration.screenSpaceRadius=this.screenspaceRadius)}onCreateEffect(){const e=this.context.mainCamera,t=this.context.domWidth,i=this.context.domHeight,n=this._ssao=new exports.MODULES.POSTPROCESSING_AO.MODULE.N8AOPostPass(this.context.scene,e,t,i);n.name="SSAO_N8";const o=hm[this.quality];n.setQualityMode(o),n.configuration.transparencyAware=!1;const r=new c.WebGLRenderTarget(t,i);return n.configuration.beautyRenderTarget=r,n.configuration.autoRenderBeauty=!1,n.configuration.gammaCorrection=this.gammaCorrection,n.configuration.screenSpaceRadius=this.screenspaceRadius,TE&&(n.enableDebugMode(),console.log(n),setInterval(()=>{console.log("SSAO",n.lastTime)},1e3),setInterval(()=>{console.log("SSAO",n.enabled,{ssao:n,autoRenderBeauty:n.configuration.autoRenderBeauty})},4e3)),this.intensity.onValueChanged=a=>{n.configuration.intensity=a},this.falloff.onValueChanged=a=>{n.configuration.distanceFalloff=a},this.aoRadius.onValueChanged=a=>{n.configuration.aoRadius=a},this.color.onValueChanged=a=>{n.color||(n.color=new c.Color),n.configuration.color.copy(a)},n}}Lr([vt(),f()],yn.prototype,"gammaCorrection");Lr([f(F)],yn.prototype,"aoRadius");Lr([f(F)],yn.prototype,"falloff");Lr([f(F)],yn.prototype,"intensity");Lr([f(F)],yn.prototype,"color");Lr([vt(),f()],yn.prototype,"screenspaceRadius");Lr([vt(),f()],yn.prototype,"quality");Xi("ScreenSpaceAmbientOcclusionN8",yn);var AE=Object.defineProperty,DE=Object.getOwnPropertyDescriptor,Qw=(s,e,t,i)=>{for(var n=DE(e,t),o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&AE(e,t,n),n};class fh extends He{get typeName(){return"Sharpening"}order=Ke.Sharpening;_effect;onCreateEffect(){return this._effect??=new(LE()),this.effect}get effect(){return this._effect}set amount(e){this._amount=e,this._effect&&(this._effect.uniforms.get("amount").value=e)}get amount(){return this._effect?this._effect.uniforms.get("amount").value:this._amount}_amount=1;set radius(e){this._radius=e,this._effect&&(this._effect.uniforms.get("radius").value=e)}get radius(){return this._effect?this._effect.uniforms.get("radius").value:this._radius}_radius=1}Qw([f()],fh.prototype,"amount");Qw([f()],fh.prototype,"radius");function LE(){const s=`
|
|
1312
|
+
`)}r&&o.size&&console.log(u);const g=new Set;for(const v of m){v.getPath||console.error("USDZExporter: Animation target object has no getPath method. This is likely a bug",v);let b=v.getPath();b.startsWith("<")&&(b=b.substring(1)),b.endsWith(">")&&(b=b.substring(0,b.length-1)),g.add({path:b,obj:v})}const _=Array.from(g).sort((v,b)=>v.path.length-b.path.length),y=new Array;for(let v=0;v<_.length;v++)for(let b=v+1;b<_.length;b++)if(_[b].path.startsWith(_[v].path)){const w=_[b],R=_[v];y.push({child:w.obj.displayName+" ("+w.path+")",parent:R.obj.displayName+" ("+R.path+")"})}y.length&&console.warn("USDZExporter: There are overlapping PlayAnimation actions. This can lead to undefined runtime behaviour when playing multiple animations. Please restructure the hierarchy so that animations don't overlap.",{overlappingTargets:y,playAnimationActions:o})}for(const u of new Set([...t,...i]))if(Array.isArray(u))for(const p of u)n.add(p.uuid);else n.add(u.uuid);Qh&&console.log("All Behavior trigger sources and action targets",t,i,n),this.targetUuids=new Set(n)}onAfterHierarchy(e,t){if(this.behaviours?.length){t.beginBlock('def Scope "Behaviors"');for(const i of this.behaviours)i.writeTo(this,e.document,t);t.closeBlock()}}async onAfterSerialize(e){Qh&&console.log("onAfterSerialize behaviours",this.behaviourComponentsCopy);for(const t of this.behaviourComponentsCopy)typeof t.afterSerialize=="function"&&(t.afterSerialize.constructor.name==="AsyncFunction"?await t.afterSerialize(this,e):t.afterSerialize(this,e));for(const{clipUrl:t,filesKey:i}of this.audioClipsCopy){if(e.files[i])return;const r=await(await(await fetch(t)).blob()).arrayBuffer(),a=new Uint8Array(r);e.files[i]=a}this.behaviourComponentsCopy.length=0,this.audioClipsCopy.length=0}}class Hg{get extensionName(){return"Physics"}onExportObject(e,t,i){const n=S.getComponents(e,Fe).filter(l=>l.enabled),o=S.getComponents(e,Hi).filter(l=>l.enabled&&!l.isTrigger);let r=n.length>0?n[0]:null;const a=o.length>0?o[0]:null;a&&!r&&(r=new Fe,r.isKinematic=!0),r&&t.addEventListener("serialize",(l,h)=>{if(r){if(l.appendLine(),l.beginBlock('def RealityKitComponent "RigidBody"',"{",!0),r.useGravity||l.appendLine("bool gravityEnabled = 0"),l.appendLine('uniform token info:id = "RealityKit.RigidBody"'),r.isKinematic&&l.appendLine('token motionType = "Kinematic"'),l.beginBlock('def RealityKitStruct "massFrame"',"{",!0),l.appendLine(`float m_mass = ${r.mass}`),l.beginBlock('def RealityKitStruct "m_pose"',"{",!0),l.appendLine(`float3 position = (${r.centerOfMass.x}, ${r.centerOfMass.y}, ${r.centerOfMass.z})`),l.closeBlock("}"),l.closeBlock("}"),o.length>0){const d=o[0];l.beginBlock('def RealityKitStruct "material"',"{",!0);const u=d.sharedMaterial;u&&u.dynamicFriction!==void 0&&l.appendLine(`double dynamicFriction = ${d.sharedMaterial?.dynamicFriction}`),u&&u.bounciness!==void 0&&l.appendLine(`double restitution = ${d.sharedMaterial?.bounciness}`),u&&u.staticFriction!==void 0&&l.appendLine(`double staticFriction = ${d.sharedMaterial?.staticFriction}`),l.closeBlock("}")}l.closeBlock("}")}}),a&&(t.addEventListener("serialize",(l,h)=>{l.beginBlock('def RealityKitComponent "Collider"',"{",!0),l.appendLine("uint group = 1"),l.appendLine('uniform token info:id = "RealityKit.Collider"'),l.appendLine("uint mask = 4294967295");const u=a.isTrigger?"Trigger":"Default";if(l.appendLine(`token type = "${u}"`),l.beginBlock('def RealityKitStruct "Shape"',"{",!0),a instanceof Na){const p=a;l.appendLine('token shapeType = "Sphere"'),l.appendLine(`float radius = ${p.radius}`)}else if(a instanceof xu){const p=a;l.appendLine('token shapeType = "Box"'),l.appendLine(`float3 extent = (${p.size.x}, ${p.size.y}, ${p.size.z})`)}else if(a instanceof ps){const p=a;l.appendLine('token shapeType = "Capsule"'),l.appendLine(`float radius = ${p.radius}`),l.appendLine(`float height = ${p.height}`)}else if(a instanceof yo&&a.sharedMesh?.geometry){const p=a.sharedMesh.geometry;p.boundingBox||p.computeBoundingBox();const m=a.sharedMesh.geometry.boundingBox;m&&(l.appendLine('token shapeType = "Box"'),l.appendLine(`float3 extent = (${m.max.x-m.min.x}, ${m.max.y-m.min.y}, ${m.max.z-m.min.z})`),console.log("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. MeshCollider will be exported as Box",a))}else console.warn("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. Ignoring collider:",a);l.beginBlock('def RealityKitStruct "pose"',"{",!0),l.closeBlock("}"),l.closeBlock("}"),l.closeBlock("}")}),o.length>1&&console.log("WARNING: Multiple colliders detected. visionOS / iOS can only support objects with a single collider, only exporting the first collider: ",a))}}const sk=x("debugshadowcomponents");te.__webpack_exports__Block.prototype.interactable={get(){return this.interactive},set(s){this.interactable=s}};class Ni extends E{isRoot(){return this.Root?.gameObject===this.gameObject}get canvas(){const e=this.Root;return e?.isCanvas?e:null}get Canvas(){return this.canvas}markDirty(){$t.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(e){this._shadowComponent=e}_shadowComponent=null;_controlsChildLayout=!0;get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}_root=void 0;get Root(){return this._root===void 0&&(this._root=S.getComponentInParent(this.gameObject,ih)),this._root}_parentComponent=void 0;__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0,this}onEnable(){super.onEnable()}addShadowComponent(e,t){if(!e)return;this.removeShadowComponent();const i=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=S.getComponentInParent(i,Ni),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e[hi]=this,this.setShadowComponentOwner(e);let n=!1;if(this.Root?.gameObject===this.gameObject)this.gameObject.add(e);else{const o=this._parentComponent.shadowComponent;o&&(o?.add(e),n=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),Uc&&e.add(new c.AxesHelper(.5)),this.onAfterAddedToScene(),n&&te.__webpack_exports__update(),sk&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(e){if(e&&(e[hi]===void 0||e[hi]===this)&&(e[hi]=this,e.children))for(const t of e.children)this.setShadowComponentOwner(t)}traverseOwnedShadowComponents(e,t,i){if(e&&e[hi]===t){i(e);for(const n of e.children)this.traverseOwnedShadowComponents(n,t,i)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}}class ih extends Ni{awake(){super.awake()}}var ok=Object.defineProperty,rk=Object.getOwnPropertyDescriptor,nh=(s,e,t,i)=>{for(var n=i>1?void 0:i?rk(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&&ok(e,t,n),n};const Jf=x("debugui"),ep=x("debuguilayout");class Lw{width;height}class Iw{x;y;width;height}const en=new c.Vector3,vl=new c.Matrix4,Yh=new c.Quaternion,qa=class jw extends Ni{get parent(){return this._parentRectTransform}get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}_anchoredPosition;get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new c.Vector2),this._anchoredPosition}set anchoredPosition(e){this._anchoredPosition=e}sizeDelta=new c.Vector2(100,100);pivot=new c.Vector2(.5,.5);anchorMin=new c.Vector2(0,0);anchorMax=new c.Vector2(1,1);minWidth;minHeight;get width(){let e=this.sizeDelta.x;if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const t=this._parentRectTransform.width,i=this.anchorMax.x-this.anchorMin.x;e=t*i,e+=this.sizeDelta.x}return this.minWidth!==void 0&&e<this.minWidth?this.minWidth:e}get height(){let e=this.sizeDelta.y;if(this.anchorMin.y!==this.anchorMax.y&&this._parentRectTransform){const t=this._parentRectTransform.height,i=this.anchorMax.y-this.anchorMin.y;e=t*i,e+=this.sizeDelta.y}return this.minHeight!==void 0&&e<this.minHeight?this.minHeight:e}lastMatrix;rectBlock;_transformNeedsUpdate=!1;_initialPosition;_parentRectTransform;_lastUpdateFrame=-1;awake(){super.awake(),this._lastUpdateFrame=-1,this._parentRectTransform=void 0,this.rectBlock=new c.Object3D,this.rectBlock.name=this.name,this.lastMatrix=new c.Matrix4,this._lastAnchoring=null,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,this._anchoredPosition||(this._anchoredPosition=new c.Vector2),ea(this,"_anchoredPosition",()=>{this.markDirty()}),ea(this,"sizeDelta",()=>{this.markDirty()}),ea(this,"pivot",()=>{this.markDirty()}),ea(this,"anchorMin",()=>{this.markDirty()}),ea(this,"anchorMax",()=>{this.markDirty()})}onEnable(){super.onEnable(),this.rectBlock||(this.rectBlock=new c.Object3D),this.lastMatrix||(this.lastMatrix=new c.Matrix4),this._lastAnchoring||(this._lastAnchoring=new c.Vector2),this._initialPosition||(this._initialPosition=new c.Vector3),this._anchoredPosition||(this._anchoredPosition=new c.Vector2),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,this.canvas?.registerTransform(this)}onDisable(){super.onDisable(),this.removeShadowComponent(),this.canvas?.unregisterTransform(this)}onParentRectTransformChanged(e){this._transformNeedsUpdate||this.onApplyTransform(ep?`${e.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(ep&&console.warn("RectTransform markDirty()",this.name),this._transformNeedsUpdate=!0,this._lastUpdateFrame=-1)}updateTransform(){(this._transformNeedsUpdate||!this.lastMatrix.equals(this.gameObject.matrix))&&this.canUpdate()&&this.onApplyTransform(this._transformNeedsUpdate?"Marked dirty":"Matrix changed")}canUpdate(){return this._transformNeedsUpdate&&this.activeAndEnabled&&this._lastUpdateFrame!==this.context.time.frame}onApplyTransform(e){if(this.context.time.frameCount===this._lastUpdateFrame)return;this._lastUpdateFrame=this.context.time.frameCount;const t=this.shadowComponent;if(!t)return;this.gameObject.parent?this._parentRectTransform=S.getComponentInParent(this.gameObject.parent,jw):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,ep&&console.warn("RectTransform → ApplyTransform",this.name+" because "+e),this.isRoot()?this.Root.screenspace||(t.rotation.y=Math.PI):(t.matrix.identity(),t.matrixAutoUpdate=!1,en.set(0,0,0),this.applyPivot(en),t.matrix.setPosition(en.x,en.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(Yh.copy(this.gameObject.quaternion),Yh.x*=-1,Yh.z*=-1,vl.makeRotationFromQuaternion(Yh),t.matrix.premultiply(vl)),en.set(0,0,0),this.applyAnchoring(en),this.canvas?.screenspace?en.z+=.1:en.z+=.01,vl.identity(),vl.setPosition(en.x,en.y,en.z),t.matrix.premultiply(vl),t.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const i=!0;for(const n of du(this.gameObject,Ni,i,1)){if(n===this||!n.activeAndEnabled)continue;const o=n;o.onParentRectTransformChanged&&o.onParentRectTransformChanged(this)}}_lastAnchoring;applyAnchoring(e){this._lastAnchoring||(this._lastAnchoring=new c.Vector2);const t=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=t.x,this.gameObject.position.y+=t.y,this._lastAnchoring.copy(this._anchoredPosition),e.x+=this._initialPosition.x-this.gameObject.position.x,e.y+=this._initialPosition.y-this.gameObject.position.y,e.z+=this._initialPosition.z-this.gameObject.position.z;const i=this._parentRectTransform;if(i){let n=0;const o=1-this.anchorMax.y-this.anchorMin.y;n-=i.height*.5*o,e.y+=n;let r=0;const a=1-this.anchorMax.x-this.anchorMin.x;r-=i.width*.5*a,e.x+=r}}applyPivot(e){if(this.pivot&&!this.isRoot()){const t=this.pivot.x-.5;e.x-=t*this.sizeDelta.x*this.gameObject.scale.x;const i=this.pivot.y-.5;e.y-=i*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){const e={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:0,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(e),e}ensureValidSize(e,t=1e-4){return e.width<=0&&(e.width=t),e.height<=0&&(e.height=1e-4),e}_createdBlocks=[];_createdTextBlocks=[];createNewBlock(e){e={...this.getBasicOptions(),...e},Jf&&console.log(this.name,e);const t=new te.__webpack_exports__Block(e);return this._createdBlocks.push(t),t}createNewText(e){Jf&&console.log(e),e={...this.getBasicOptions(),...e},Jf&&console.log(this.name,e);const t=new te.__webpack_exports__Text(e);return this._createdTextBlocks.push(t),t}};nh([f(c.Vector2)],qa.prototype,"anchoredPosition",1);nh([f(c.Vector2)],qa.prototype,"sizeDelta",2);nh([f(c.Vector2)],qa.prototype,"pivot",2);nh([f(c.Vector2)],qa.prototype,"anchorMin",2);nh([f(c.Vector2)],qa.prototype,"anchorMax",2);let un=qa;var ak=Object.defineProperty,Bw=(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&&ak(e,t,n),n};class Xa extends E{effectColor;effectDistance}Bw([f(ee)],Xa.prototype,"effectColor");Bw([f(c.Vector2)],Xa.prototype,"effectDistance");var lk=Object.defineProperty,ck=Object.getOwnPropertyDescriptor,Uw=(s,e,t,i)=>{for(var n=i>1?void 0:i?ck(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&lk(e,t,n),n};const Do={backgroundColor:new c.Color(1,1,1),backgroundOpacity:1,borderColor:new c.Color(1,1,1),borderOpacity:1},Gg=class zl extends Ni{get isGraphic(){return!0}get color(){return this._color||(this._color=new ee(1,1,1,1)),this._color}set color(e){(!this._color||this._color.r!==e.r||this._color.g!==e.g||this._color.b!==e.b||this._color.alpha!==e.alpha)&&(this._color||(this._color=new ee(1,1,1,1)),this._color.copy(e),this.onColorChanged())}_alphaFactor=1;setAlphaFactor(e){this._alphaFactor=e,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}sRGBColor=new c.Color(1,0,1);onColorChanged(){if(this.uiObject){this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),Do.backgroundColor=this.sRGBColor,Do.backgroundOpacity=this._color.alpha;const e=this.uiObject._simpleState__activeStates?.[0];if(e){const t=this.uiObject._simpleState__states?.[e];t&&("backgroundColor"in t&&(Do.backgroundColor=t.backgroundColor),"backgroundOpacity"in t&&(Do.backgroundOpacity=t.backgroundOpacity))}Do.backgroundOpacity*=this._alphaFactor,this.applyEffects(Do,this._alphaFactor),this.uiObject.set(Do),this.markDirty()}}get m_Color(){return this._color}raycastTarget=!0;uiObject=null;_color=null;_rect=null;_stateManager=null;get rectTransform(){if(this._rect||(this._rect=S.getComponent(this.gameObject,un)),!this._rect)throw new Error("Not Supported: Make sure to add a RectTransform component before adding a UI Graphic component.");return this._rect}onParentRectTransformChanged(){this.uiObject?.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this._rect=null,this.uiObject=null,this._stateManager=null,this._color&&(this._color=this._color.clone()),this}setState(e){this.makePanel(),this.uiObject&&(this.uiObject.setState(e),this?.markDirty())}setupState(e){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new te.SimpleStateBehavior(this.uiObject)),this.uiObject.setupState(e.state,e.attributes))}setOptions(e){this.makePanel(),this.uiObject&&this.uiObject.set(e)}awake(){super.awake(),this.makePanel(),ea(this,"_color",()=>KP(this,this.onColorChanged))}onEnable(){super.onEnable(),this.uiObject&&(this.rectTransform.shadowComponent?.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}_currentlyCreatingPanel=!1;makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;const t={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:.015};this.onBeforeCreate(t),this.applyEffects(t),this.onCreate(t),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated(),this.onColorChanged()}onBeforeCreate(e){}onCreate(e){this.uiObject=this.rectTransform.createNewBlock(e),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(e,t=1){const i=this.gameObject?.getComponent(Xa);i&&(i.effectDistance&&(e.borderWidth=Math.max(Math.abs(i.effectDistance.x),Math.abs(i.effectDistance.y))),i.effectColor&&(e.borderColor=i.effectColor,e.borderOpacity=i.effectColor.alpha*t))}static textureCache=new Map;async setTexture(e){if(this.setOptions({backgroundOpacity:0}),e){if(zl.textureCache.has(e))e=zl.textureCache.get(e);else if(!e.isRenderTargetTexture){const t=e.clone();t.colorSpace=c.LinearSRGBColorSpace,zl.textureCache.set(e,t),e=t}this.setOptions({backgroundImage:e,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}),se.NEEDLE_progressive.assignTextureLOD(e,0).then(t=>{t instanceof c.Texture&&(e&&zl.textureCache.set(e,t),this.setOptions({backgroundImage:t}),this.markDirty())})}else this.setOptions({backgroundImage:void 0,borderRadius:0,backgroundOpacity:this.color.alpha});this.markDirty()}onAfterAddedToScene(){super.onAfterAddedToScene(),this.shadowComponent&&(this.shadowComponent.offset=this.shadowComponent.position.z)}};Uw([f(ee)],Gg.prototype,"color",1);Uw([f()],Gg.prototype,"raycastTarget",2);let sh=Gg;class oh extends sh{_flippedObject=!1;onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var hk=Object.defineProperty,dk=Object.getOwnPropertyDescriptor,xs=(s,e,t,i)=>{for(var n=i>1?void 0:i?dk(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&hk(e,t,n),n};const Lo=x("debugtext");var Ye=(s=>(s[s.UpperLeft=0]="UpperLeft",s[s.UpperCenter=1]="UpperCenter",s[s.UpperRight=2]="UpperRight",s[s.MiddleLeft=3]="MiddleLeft",s[s.MiddleCenter=4]="MiddleCenter",s[s.MiddleRight=5]="MiddleRight",s[s.LowerLeft=6]="LowerLeft",s[s.LowerCenter=7]="LowerCenter",s[s.LowerRight=8]="LowerRight",s))(Ye||{}),Fw=(s=>(s[s.Normal=0]="Normal",s[s.Bold=1]="Bold",s[s.Italic=2]="Italic",s[s.BoldAndItalic=3]="BoldAndItalic",s))(Fw||{});class Tt extends sh{alignment=0;verticalOverflow=0;horizontalOverflow=0;lineSpacing=1;supportRichText=!1;font;fontStyle=0;setAlphaFactor(e){super.setAlphaFactor(e),this.uiObject?.set({fontOpacity:this.color.alpha*this.alphaFactor}),this.markDirty()}get text(){return this._text}set text(e){e!==this._text&&(this._text=e,this.feedText(this.text,this.supportRichText),this.markDirty())}set_text(e){this.text=e}get fontSize(){return this._fontSize}set fontSize(e){this._fontSize=e,this.uiObject?.set({fontSize:e})}sRGBTextColor=new c.Color(1,0,1);onColorChanged(){this.sRGBTextColor.copy(this.color),this.sRGBTextColor.convertLinearToSRGB(),this.uiObject?.set({color:this.sRGBTextColor,fontOpacity:this.color.alpha})}onParentRectTransformChanged(){super.onParentRectTransformChanged(),this.uiObject&&this.updateOverflow()}onBeforeCanvasRender(e){this.updateOverflow()}updateOverflow(){const e=this.uiObject?._overflow;e&&(e._needsUpdate=!0)}onCreate(e){Lo&&console.log(this),this.horizontalOverflow==1&&(e.whiteSpace="pre"),this.verticalOverflow==0&&(this.context.renderer.localClippingEnabled=!0,e.overflow="hidden"),this.horizontalOverflow==1&&this.verticalOverflow==0,e.lineHeight=this.lineSpacing,delete e.backgroundOpacity,delete e.backgroundColor,Lo&&(e.backgroundColor=16750848,e.backgroundOpacity=.5);const t=this.rectTransform;e={...e,...this.getTextOpts()},this.getAlignment(e),Lo&&(e.backgroundColor=Math.random()*16777215,e.backgroundOpacity=.1),this.uiObject=t.createNewText(e),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}_text="";_fontSize=12;_textMeshUi=null;getTextOpts(){const e=this.fontSize,t={color:this.color,fontOpacity:this.color.alpha,fontSize:e,fontKerning:"normal"};return this.setFont(t,this.fontStyle),t}onEnable(){super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&this.uiObject.addAfterUpdate(()=>{this.setShadowComponentOwner(this.uiObject),this.markDirty()}),setTimeout(()=>this.markDirty(),10),this.canvas?.registerEventReceiver(this)}onDisable(){super.onDisable(),this.canvas?.unregisterEventReceiver(this)}getAlignment(e){switch(e.flexDirection="column",this.alignment){case 0:case 3:case 6:e.textAlign="left";break;case 1:case 4:case 7:e.textAlign="center";break;case 2:case 5:case 8:e.textAlign="right";break}switch(this.alignment){default:case 0:case 1:case 2:e.alignItems="start";break;case 3:case 4:case 5:e.alignItems="center";break;case 6:case 7:case 8:e.alignItems="end";break}return e}feedText(e,t){if(Lo&&console.log("feedText",this.uiObject,e,t),!!this.uiObject)if(this._textMeshUi||(this._textMeshUi=[]),this.uiObject.children.length=0,!t||e.length===0)this.uiObject.textContent=e;else{let i=this.getNextTag(e);if(i){if(i.startIndex>0){for(let r=this.uiObject.children.length-1;r>=0;r--){const a=this.uiObject.children[r];a.isUI&&(this.uiObject.remove(a),a.clear())}const o=new te.__webpack_exports__Inline({textContent:e.substring(0,i.startIndex),color:"inherit"});this.uiObject.add(o)}}else{this.uiObject.textContent="",this.setOptions({textContent:e});return}const n=[];for(;i;){const o=this.getNextTag(e,i.endIndex),r={fontFamily:this.uiObject?.get("fontFamily"),color:"inherit",textContent:""};if(o){r.textContent=this.getText(e,i,o),this.handleTag(i,r,n);const a=new te.__webpack_exports__Inline(r);this.uiObject?.add(a)}else{r.textContent=e.substring(i.endIndex),this.handleTag(i,r,n);const a=new te.__webpack_exports__Inline(r);this.uiObject?.add(a)}i=o}}}_didHandleTextRenderOnTop=!1;handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const e=[],t=this.canvas,i={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let n=!1;if(this._textMeshUi)for(let o=0;o<this._textMeshUi.length;o++){if(e[o]===!0)continue;n=!0;const r=this._textMeshUi[o];r.textContent&&(Wd(r,i),e[o]=!0)}if(!n)break;yield}}handleTag(e,t,i){if(!e.isEndTag){if(e.type.includes("color")){const n=new tp(e,{color:t.color});if(i.push(n),e.type.length>6){const o=parseInt("0x"+e.type.substring(7));t.color=o}else t.color=new c.Color(1,1,1)}else if(e.type=="b"){this.setFont(t,1);const n=new tp(e,{fontWeight:700});i.push(n)}else if(e.type=="i"){this.setFont(t,2);const n=new tp(e,{fontStyle:"italic"});i.push(n)}}}getText(e,t,i){return e.substring(t.endIndex,i.startIndex)}getNextTag(e,t=0){const i=e.indexOf("<",t),n=e.indexOf(">",i);if(i>=0&&n>=0){const o=e.substring(i+1,n);return{type:o,startIndex:i,endIndex:n+1,isEndTag:o.startsWith("/")}}return null}setFont(e,t){if(!this.font)return;const i=this.font,n=this.getFamilyNameWithCorrectSuffix(i,t);Lo&&console.log("Selected font family:"+n);let o=te.__webpack_exports__FontLibrary.getFontFamily(n);switch(o||(o=te.__webpack_exports__FontLibrary.addFontFamily(n)),e.fontFamily=o,t){default:case 0:e.fontWeight=400,e.fontStyle="normal";break;case 1:e.fontWeight=700,e.fontStyle="normal";break;case 2:e.fontWeight=400,e.fontStyle="italic";break;case 3:e.fontStyle="italic",e.fontWeight=400}let r=o.getVariant(e.fontWeight,e.fontStyle);if(!r){let a=n;a?.endsWith("-msdf.json")||(a+="-msdf.json");let l=n;l?.endsWith(".png")||(l+=".png"),r=o.addVariant(e.fontWeight,e.fontStyle,a,l),r?.addEventListener("ready",()=>{this.markDirty()})}}getFamilyNameWithCorrectSuffix(e,t){(e.startsWith("https:")||e.startsWith("http:"))&&(e=new URL(e).pathname);const i=e.lastIndexOf("-");if(i<0)return e;const n=e.substring(i+1)?.toLowerCase();if(uk.includes(n))return Lo&&console.warn("Unsupported font style: "+n),e;const o=e.lastIndexOf("/");let r=e;o>=0&&(r=r.substring(o+1));const a=r[0]===r[0].toUpperCase(),l=e.substring(0,i>o?i:e.length);switch(Lo&&console.log("Select font: ",e,Fw[t],r,a,l),t){case 0:return a?l+"-Regular":l+"-regular";case 1:return a?l+"-Bold":l+"-bold";case 2:return a?l+"-Italic":l+"-italic";case 3:return a?l+"-BoldItalic":l+"-bolditalic";default:return e}}}xs([f()],Tt.prototype,"alignment",2);xs([f()],Tt.prototype,"verticalOverflow",2);xs([f()],Tt.prototype,"horizontalOverflow",2);xs([f()],Tt.prototype,"lineSpacing",2);xs([f()],Tt.prototype,"supportRichText",2);xs([f(URL)],Tt.prototype,"font",2);xs([f()],Tt.prototype,"fontStyle",2);xs([f()],Tt.prototype,"text",1);xs([f()],Tt.prototype,"fontSize",1);class tp{tag;previousValues;constructor(e,t){this.tag=e,this.previousValues=t}}const uk=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class ha{static global_id=0;static getId(){return this.global_id++}id;content="";font=[];pointSize=144;width;height;depth;wrapMode;horizontalAlignment;verticalAlignment;material;setDepth(e){return this.depth=e,this}setPointSize(e){return this.pointSize=e,this}setHorizontalAlignment(e){return this.horizontalAlignment=e,this}setVerticalAlignment(e){return this.verticalAlignment=e,this}constructor(e){this.id=e}writeTo(e,t){t.beginBlock(`def Preliminary_Text "${this.id}"`,"(",!1),t.appendLine('prepend apiSchemas = ["MaterialBindingAPI"]'),t.closeBlock(")"),t.beginBlock(),this.content&&t.appendLine(`string content = "${this.content}"`),(!this.font||this.font.length<=0)&&(this.font||=[],this.font?.push("sans-serif"));const i=this.font.map(n=>`"${n}"`).join(", ");t.appendLine(`string[] font = [ ${i} ]`),t.appendLine(`double pointSize = ${this.pointSize}`),typeof this.width=="number"&&t.appendLine(`double width = ${this.width}`),typeof this.height=="number"&&t.appendLine(`double height = ${this.height}`),typeof this.depth=="number"&&t.appendLine(`double depth = ${this.depth}`),this.wrapMode&&t.appendLine(`token wrapMode = "${this.wrapMode}"`),this.horizontalAlignment&&t.appendLine(`token horizontalAlignment = "${this.horizontalAlignment}"`),this.verticalAlignment&&t.appendLine(`token verticalAlignment = "${this.verticalAlignment}"`),this.material!==void 0&&t.appendLine(`rel material:binding = </StageRoot/Materials/${Mu(this.material)}>`),t.closeBlock()}}class qg{static singleLine(e,t,i){const n=new ha("text_"+ha.getId());return n.content=e,t&&(n.pointSize=t),i&&(n.depth=i),n}static multiLine(e,t,i,n,o,r){const a=new ha("text_"+ha.getId());return a.content=e,a.width=t,a.height=i,a.horizontalAlignment=n,a.verticalAlignment=o,r!==void 0&&(a.wrapMode=r),a}}const fk=new c.Matrix4().makeRotationY(Math.PI),pk=new c.Matrix4().makeScale(-1,1,-1);class Lu{get extensionName(){return"text"}exportText(e,t,i){const n=S.getComponent(e,Tt);if(!n)return;const o=S.getComponent(e,un);let r=100,a=100;o&&(r=o.width,a=o.height);const l=fk.clone();o&&l.premultiply(pk),t.setMatrix(l);const h=n.color.clone();t.material=new c.MeshStandardMaterial({color:h,emissive:h}),t.addEventListener("serialize",(d,u)=>{let p=n.text;p=p.replace(/\r/g,""),p=p.replace(/\n/g,"\\n");const m=qg.multiLine(p,r,a,"center","bottom","flowing");this.setTextAlignment(m,n.alignment),this.setOverflow(m,n),t.material&&(m.material=t.material),m.pointSize=this.convertToTextSize(n.fontSize),m.depth=.001,m.writeTo(void 0,d)})}convertToTextSize(e){return 1/.0502*144*e}setOverflow(e,t){t.horizontalOverflow?e.wrapMode="singleLine":e.wrapMode="flowing"}setTextAlignment(e,t){switch(t){case Ye.LowerLeft:case Ye.MiddleLeft:case Ye.UpperLeft:e.horizontalAlignment="left";break;case Ye.LowerCenter:case Ye.MiddleCenter:case Ye.UpperCenter:e.horizontalAlignment="center";break;case Ye.LowerRight:case Ye.MiddleRight:case Ye.UpperRight:e.horizontalAlignment="right";break}switch(t){case Ye.LowerLeft:case Ye.LowerCenter:case Ye.LowerRight:e.verticalAlignment="bottom";break;case Ye.MiddleLeft:case Ye.MiddleCenter:case Ye.MiddleRight:e.verticalAlignment="middle";break;case Ye.UpperLeft:case Ye.UpperCenter:case Ye.UpperRight:e.verticalAlignment="top";break}}}var mk=Object.defineProperty,qe=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&mk(e,t,n),n};const cb=x("debuguilayout");class Mr{left=0;right=0;top=0;bottom=0;get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}qe([f()],Mr.prototype,"left");qe([f()],Mr.prototype,"right");qe([f()],Mr.prototype,"top");qe([f()],Mr.prototype,"bottom");class xi extends E{_rectTransform=null;get rectTransform(){return this._rectTransform}onParentRectTransformChanged(e){this._needsUpdate=!0}_needsUpdate=!1;get isDirty(){return this._needsUpdate}get isLayoutGroup(){return!0}updateLayout(){this._rectTransform&&(cb&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}childAlignment=0;reverseArrangement=!1;spacing=0;padding;minWidth=0;minHeight=0;flexibleHeight=0;flexibleWidth=0;preferredHeight=0;preferredWidth=0;start(){this._needsUpdate=!0}onEnable(){cb&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(un);const e=this.gameObject.getComponentInParent(Da);e&&e.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const e=this.gameObject.getComponentInParent(Da);e&&e.unregisterLayoutGroup(this)}set m_Spacing(e){e!==this.spacing&&(this._needsUpdate=!0,this.spacing=e)}get m_Spacing(){return this.spacing}}qe([f()],xi.prototype,"childAlignment");qe([f()],xi.prototype,"reverseArrangement");qe([f()],xi.prototype,"spacing");qe([f(Mr)],xi.prototype,"padding");qe([f()],xi.prototype,"minWidth");qe([f()],xi.prototype,"minHeight");qe([f()],xi.prototype,"flexibleHeight");qe([f()],xi.prototype,"flexibleWidth");qe([f()],xi.prototype,"preferredHeight");qe([f()],xi.prototype,"preferredWidth");class vo extends xi{childControlHeight=!0;childControlWidth=!0;childForceExpandHeight=!1;childForceExpandWidth=!1;childScaleHeight=!1;childScaleWidth=!1;onCalculateLayout(e){const t=this.primaryAxis,i=e.width;let n=i;const o=e.height;let r=o;n-=this.padding.horizontal,r-=this.padding.vertical,t==="x"?this.padding.horizontal:this.padding.vertical;const a=t==="x",l=a?"y":"x",h=a?this.childControlWidth:this.childControlHeight,d=a?this.childControlHeight:this.childControlWidth,u=a?this.childForceExpandWidth:this.childForceExpandHeight,p=a?this.childForceExpandHeight:this.childForceExpandWidth,m=a?r:n,g=a?i:o,_=.5*(a?this.childAlignment%3:Math.floor(this.childAlignment/3));let y=0;a?y+=this.padding.left:y+=this.padding.top;let v=0,b=0;for(let A=0;A<this.gameObject.children.length;A++){const D=this.gameObject.children[A],L=S.getComponent(D,un);L?.activeAndEnabled&&(b+=1,a?v+=L.width:v+=L.height)}let w=0;const R=this.spacing*(b-1);if(u||h){let A=0;a?A=n-=R:A=r-=R,b>0&&(w=A/b)}let M=0;M+=this.padding.left,M-=this.padding.right,_!==0&&(y=g-v,y*=_,y-=R*_,a?(y-=this.padding.right*_,y+=this.padding.left*(1-_),y<this.padding.left&&(y=this.padding.left)):(y-=this.padding.bottom*_,y+=this.padding.top*(1-_),y<this.padding.top&&(y=this.padding.top)));let O=1;for(let A=0;A<this.gameObject.children.length;A++){const D=this.gameObject.children[A],L=S.getComponent(D,un);if(L?.activeAndEnabled){L.pivot?.set(.5,.5),L.anchorMin.set(0,1),L.anchorMax.set(0,1);const N=i*.5+M*.5;L.anchoredPosition.x!==N&&(L.anchoredPosition.x=N);const $=o*-.5;L.anchoredPosition.y!==$&&(L.anchoredPosition.y=$),p&&d&&L.sizeDelta[l]!==m&&(L.sizeDelta[l]=m),u&&h&&L.sizeDelta[t]!==w&&(L.sizeDelta[t]=w);const k=a?L.width:L.height,z=k*.5;if(y+=z,u){const J=w*O-w*.5;J>y&&(y=J-w*.5+k+this.padding.left,y-=z)}let V=y;t==="y"&&(V=-V),L.anchoredPosition[t]!==V&&(L.anchoredPosition[t]=V),y+=z,y+=this.spacing,O+=1}}}}qe([f()],vo.prototype,"childControlHeight");qe([f()],vo.prototype,"childControlWidth");qe([f()],vo.prototype,"childForceExpandHeight");qe([f()],vo.prototype,"childForceExpandWidth");qe([f()],vo.prototype,"childScaleHeight");qe([f()],vo.prototype,"childScaleWidth");class Xg extends vo{get primaryAxis(){return"y"}}class Qg extends vo{get primaryAxis(){return"x"}}class Yg extends xi{onCalculateLayout(){}}var gk=Object.defineProperty,yk=Object.getOwnPropertyDescriptor,Gn=(s,e,t,i)=>{for(var n=i>1?void 0:i?yk(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&&gk(e,t,n),n},zw=(s=>(s[s.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",s[s.ScreenSpaceCamera=1]="ScreenSpaceCamera",s[s.WorldSpace=2]="WorldSpace",s[s.Undefined=-1]="Undefined",s))(zw||{});const ip=x("debuguilayout"),Vi=class Nw extends ih{get isCanvas(){return!0}get screenspace(){return this.renderMode!==2}set renderOnTop(e){e!==this._renderOnTop&&(this._renderOnTop=e,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop!==void 0?this._renderOnTop:!!(this.screenspace&&this._renderMode===0)}_renderOnTop;set depthWrite(e){this._depthWrite!==e&&(this._depthWrite=e,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}_depthWrite=!1;set doubleSided(e){this._doubleSided!==e&&(this._doubleSided=e,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}_doubleSided=!0;set castShadows(e){this._castShadows!==e&&(this._castShadows=e,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}_castShadows=!1;set receiveShadows(e){this._receiveShadows!==e&&(this._receiveShadows=e,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}_receiveShadows=!1;get renderMode(){return this._renderMode}set renderMode(e){this._renderMode!==e&&(this._renderMode=e,this.onRenderSettingsChanged())}_renderMode=-1;_rootCanvas;set rootCanvas(e){this._rootCanvas instanceof Nw||(this._rootCanvas=e)}get rootCanvas(){return this._rootCanvas}_scaleFactor=1;get scaleFactor(){return this._scaleFactor}set scaleFactor(e){this._scaleFactor=e}worldCamera;planeDistance=-1;awake(){this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,ip&&console.log("Canvas.Awake()",this.previousParent?.name+"/"+this.gameObject.name),super.awake()}start(){this.applyRenderSettings()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new c.Matrix4,this.applyRenderSettings(),document.addEventListener("resize",this._boundRenderSettingsChanged),this.context.pre_render_callbacks.push(this.onBeforeRenderRoutine),this.context.post_render_callbacks.push(this.onAfterRenderRoutine)}onDisable(){super.onDisable(),document.removeEventListener("resize",this._boundRenderSettingsChanged);const e=this.context.pre_render_callbacks.indexOf(this.onBeforeRenderRoutine);e!==-1&&this.context.pre_render_callbacks.splice(e,1);const t=this.context.post_render_callbacks.indexOf(this.onAfterRenderRoutine);t!==-1&&this.context.post_render_callbacks.splice(t,1)}_boundRenderSettingsChanged=this.onRenderSettingsChanged.bind(this);previousParent=null;_lastMatrixWorld=null;_rectTransforms=[];registerTransform(e){this._rectTransforms.push(e)}unregisterTransform(e){const t=this._rectTransforms.indexOf(e);t!==-1&&this._rectTransforms.splice(t,1)}_layoutGroups=new Map;registerLayoutGroup(e){const t=e.gameObject;this._layoutGroups.set(t,e)}unregisterLayoutGroup(e){const t=e.gameObject;this._layoutGroups.delete(t)}_receivers=[];registerEventReceiver(e){this._receivers.push(e)}unregisterEventReceiver(e){const t=this._receivers.indexOf(e);t!==-1&&this._receivers.splice(t,1)}async onEnterXR(e){this.screenspace?(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!1):(this.gameObject.visible=!1,await Dc(1).then(()=>{this.gameObject.visible=!0}))}onLeaveXR(e){this.screenspace&&(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!0)}onBeforeRenderRoutine=()=>{if(this.previousParent=this.gameObject.parent,(this.context.xr?.isVR||this.context.xr?.isPassThrough)&&this.screenspace){this.gameObject.visible=!1,this.gameObject.removeFromParent();return}this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),this.shadowComponent?.updateMatrixWorld(!0),this.shadowComponent?.updateWorldMatrix(!0,!0),this.invokeBeforeRenderEvents(),$t.ensureUpdateMeshUI(te.ThreeMeshUI,this.context))};onAfterRenderRoutine=()=>{if((this.context.xr?.isVR||this.context.xr?.isPassThrough)&&this.screenspace){this.previousParent?.add(this.gameObject);return}if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){this.screenspace?this.context.mainCamera?.add(this.gameObject):this.previousParent.add(this.gameObject);const e=this.context.renderer.autoClear,t=this.context.renderer.autoClearColor;this.context.renderer.autoClear=!1,this.context.renderer.autoClearColor=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),this.shadowComponent?.updateMatrixWorld(!0),this.invokeBeforeRenderEvents(),$t.ensureUpdateMeshUI(te.ThreeMeshUI,this.context,!0),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=e,this.context.renderer.autoClearColor=t,this.previousParent.add(this.gameObject)}this._lastMatrixWorld?.copy(this.gameObject.matrixWorld)};invokeBeforeRenderEvents(){for(const e of this._receivers)e.onBeforeCanvasRender?.(this)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new c.Matrix4);const e=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);ip&&e&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);for(const t of this._rectTransforms){e&&t.markDirty();let i=this._layoutGroups.get(t.gameObject);t.isDirty&&!i&&(i=t.gameObject.getComponentInParent(xi)),(t.isDirty||i?.isDirty)&&(ip&&console.log("CANVAS UPDATE ### "+t.name+" ##################################### "+this.context.time.frame),i?.updateLayout(),t.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}_updateRenderSettingsRoutine;onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),me.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),Wd(this.shadowComponent,this);for(const e of S.getComponentsInChildren(this.gameObject,Ni))Wd(e.shadowComponent,this)}}_activeRenderMode=-1;_lastWidth=-1;_lastHeight=-1;onUpdateRenderMode(e=!1){if(!e&&this._renderMode===this._activeRenderMode&&this._lastWidth===this.context.domWidth&&this._lastHeight===this.context.domHeight)return;this._activeRenderMode=this._renderMode;let t=this.context.mainCameraComponent,i=10;switch(t&&t.nearClipPlane>0&&t.farClipPlane>0&&(i=I.lerp(t.nearClipPlane,t.farClipPlane,.01)),this._renderMode===1&&(this.worldCamera&&(t=this.worldCamera),this.planeDistance>0&&(i=this.planeDistance)),this._renderMode){case 0:case 1:if(this._lastWidth=this.context.domWidth,this._lastHeight=this.context.domHeight,!t)return;const n=i+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-n,this.gameObject.quaternion.identity();const o=this.gameObject.getComponent(un);let r=!1;o.sizeDelta.x!==this.context.domWidth&&(r=!0),o.sizeDelta.y!==this.context.domHeight&&(r=!0);const a=t.fieldOfView*Math.PI/180,l=2*Math.tan(a/2)*Math.abs(n);this.gameObject.scale.x=l/this.context.domHeight,this.gameObject.scale.y=l/this.context.domHeight,this.gameObject.scale.z=.01,r&&(o.sizeDelta.x=this.context.domWidth,o.sizeDelta.y=this.context.domHeight,o?.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};Gn([f()],Vi.prototype,"renderOnTop",1);Gn([f()],Vi.prototype,"depthWrite",1);Gn([f()],Vi.prototype,"doubleSided",1);Gn([f()],Vi.prototype,"castShadows",1);Gn([f()],Vi.prototype,"receiveShadows",1);Gn([f()],Vi.prototype,"renderMode",1);Gn([f(Vi)],Vi.prototype,"rootCanvas",1);Gn([f()],Vi.prototype,"scaleFactor",1);Gn([f(ti)],Vi.prototype,"worldCamera",2);Gn([f()],Vi.prototype,"planeDistance",2);let Da=Vi;var _k=Object.defineProperty,bk=Object.getOwnPropertyDescriptor,Kg=(s,e,t,i)=>{for(var n=i>1?void 0:i?bk(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&&_k(e,t,n),n};class lo extends E{get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}get isCanvasGroup(){return!0}_alpha=1;interactable=!0;blocksRaycasts=!0;_isDirty=!1;markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),me.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}_buffer=[];applyChangesNow(){this._buffer.length=0;for(const e of S.getComponentsInChildren(this.gameObject,Ni,this._buffer)){const t=e;t.setAlphaFactor&&t.setAlphaFactor(this._alpha)}}}Kg([f()],lo.prototype,"alpha",1);Kg([f()],lo.prototype,"interactable",2);Kg([f()],lo.prototype,"blocksRaycasts",2);class Zg{get extensionName(){return"tmui"}onExportObject(e,t,i){const n=S.getComponent(e,Da);if(n&&n.enabled&&n.renderMode===zw.WorldSpace){const o=new Lu,r=S.getComponent(e,un),a=S.getComponent(e,lo),l=new Array;if(r){if(!S.isActiveSelf(e)){const u=S.isActiveSelf(e);S.setActive(e,!0),r.onEnable(),r.updateTransform(),l.push(()=>{r.onDisable(),S.setActive(e,u)})}e.traverse(u=>{if(!S.isActiveInHierarchy(u)){const p=S.isActiveSelf(u);S.setActive(u,!0);const m=S.getComponent(u,Ni);m&&(m.onEnable(),l.push(()=>{m.onDisable()}));const g=S.getComponent(u,un);g&&(g.onEnable(),g.updateTransform(),g.onApplyTransform(),l.push(()=>{g.onDisable()}));const _=S.getComponent(u,Tt);_&&(_.onEnable(),l.push(()=>{_.onDisable()})),l.push(()=>{S.setActive(u,p)})}}),r.width,r.height;const h=He.createEmpty(),d=r.shadowComponent;if(t.add(h),d){const u=d.matrix;h.setMatrix(u);const p=new Map,m=new Map;p.set(d,h),m.set(d,a?a.alpha:1),d.traverse(g=>{if(g===d)return;const _=He.createEmpty();_.setMatrix(g.matrix);const y=g.parent,v=!!y&&typeof y.textContent=="string"&&y.textContent.length>0;let b=m.get(y)||1;const w=S.getComponent(g,lo);if(w&&(b*=w.alpha),g instanceof c.Mesh&&v){const M=g[hi];M?o.exportText(M.gameObject,_,i):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",g)}if(g instanceof c.Mesh&&!v){const M=g.geometry.clone();M.scale(1,1,-1),this.flipWindingOrder(M),_.geometry=M;const O=new c.Color,A=g.material.opacity;O.copy(g.material.color),_.material=new c.MeshBasicMaterial({color:O,opacity:A*b,map:g.material.map,transparent:!0})}p.set(g,_),m.set(g,b);const R=p.get(y);if(!R){console.error("Error when exporting UI: shadow component parent not found!",g,g.parent);return}R.add(_)})}}for(const h of l)h()}}flipWindingOrder(e){const t=e.index.array;for(let i=0,n=t.length/3;i<n;i++){const o=t[i*3];t[i*3]=t[i*3+2],t[i*3+2]=o}e.index.needsUpdate=!0}}const Nl=x("debugusdz");function vk(s,e){const t=[],i=S.getComponentsInChildren(s,at),n=S.getComponentsInChildren(s,Et),o=new Array,r=new Array;if(e.injectImplicitBehaviours)for(const a of i){if(!a||!a.runtimeAnimatorController||!a.enabled)continue;const l=a.runtimeAnimatorController.activeState;if(!l||!l.motion||!l.motion.clip||l.motion.clip.tracks?.length<1||o.includes(a))continue;const h=new Sc;h.animator=a,h.stateName=l.name,h.trigger="start",h.name="PlayAnimationOnClick_implicitAtStart_"+h.stateName;const d=new c.Object3D;S.addComponent(d,h),r.push(d),o.push(a),s.add(d)}else for(const a of i){if(!a||!a.runtimeAnimatorController||!a.enabled)continue;Nl&&console.log(a);const l=[];for(const h of a.runtimeAnimatorController.enumerateActions()){Nl&&console.log(h);const d=h.getClip();l.includes(d)||l.push(d)}t.push({root:a.gameObject,clips:l})}if(e.injectImplicitBehaviours)for(const a of n){if(!a||!a.clip||!a.enabled||!a.playAutomatically||o.includes(a))continue;const l=new Sc;l.animation=a,l.stateName=a.clip.name,l.trigger="start",l.name="PlayAnimationOnClick_implicitAtStart_"+l.stateName;const h=new c.Object3D;S.addComponent(h,l),r.push(h),o.push(a),s.add(h)}else for(const a of n){Nl&&console.log(a);const l=[];for(const h of a.animations)l.includes(h)||l.push(h);t.push({root:a.gameObject,clips:l})}Nl&&t?.length>0&&console.log("USDZ Animation Clips without behaviours",t);for(const a of t)for(const l of a.clips)e.registerAnimation(a.root,l);return r}function wk(s,e){const t=S.getComponentsInChildren(s,_i),i=S.getComponentsInChildren(s,ro),n=new Array,o=new Array;Nl&&console.log({audioSources:t,playAudioOnClicks:i});for(const r of i){if(!r.target)continue;const a=t.indexOf(r.target);a>-1&&t.splice(a,1)}for(const r of t){if(!r||!r.clip||r.volume<=0||n.includes(r))continue;const a=new ro;a.target=r,a.name="PlayAudioOnClick_implicitAtStart_",a.trigger="start";const l=new c.Object3D;S.addComponent(l,a),console.log("implicit PlayAudioOnStart",l,a),o.push(l),n.push(r),s.add(l)}return o}function xk(s){return new bt("DisableAtStart",kt.sceneStartTrigger(),he.fadeAction(s,0,!1))}function hb(s,e){const t=s.domElement.shadowRoot.querySelector("link[rel='ar']");if(t)return t;const i=document.createElement("div");i.classList.add("menu"),i.classList.add("quicklook-menu"),i.style.display="none",i.style.visibility="hidden";const n=document.createElement("button");n.id="open-in-ar",e?(n.innerText="View in AR",n.title="View this scene in AR. The scene will be exported to USDZ and opened with Apple's QuickLook."):(n.innerText="View in AR",n.title="Download this scene for AR. Open the downloaded USDZ file to view it in AR using Apple's QuickLook."),i.appendChild(n);const o=document.createElement("a");o.id="needle-usdz-link",o.style.display="none",o.rel="ar",o.href="",o.target="_blank",i.appendChild(o);const r=document.createElement("img");return r.id="button",o.appendChild(r),s.domElement.shadowRoot.appendChild(i),o}var Sk=Object.defineProperty,wt=(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&&Sk(e,t,n),n};const ut=x("debugusdz"),Ck=x("debugusdzpruning");class Or{callToAction;checkoutTitle;checkoutSubtitle;callToActionURL}wt([f()],Or.prototype,"callToAction");wt([f()],Or.prototype,"checkoutTitle");wt([f()],Or.prototype,"checkoutSubtitle");wt([f()],Or.prototype,"callToActionURL");const ri=class Fo extends E{static beforeExport=new oe;static afterExport=new oe;static beforeLODExport=new oe;objectToExport=void 0;autoExportAnimations=!0;autoExportAudioSources=!0;exportFileName=void 0;customUsdzFile=void 0;customBranding;anchoringType="plane";maxTextureSize=2048;planeAnchoringAlignment="horizontal";interactive=!0;physics=!0;allowCreateQuicklookButton=!0;quickLookCompatible=!0;extensions=[];link;button;start(){ut&&(console.log("USDZExporter",this),console.log("Debug USDZ Mode. Press 'T' to export"),window.addEventListener("keydown",e=>{e.key==="t"&&this.exportAndOpen()})),this.objectToExport||(this.objectToExport=this.gameObject),!this.objectToExport?.children?.length&&!this.objectToExport?.isMesh&&(this.objectToExport=this.context.scene)}onEnable(){const e=exports.DeviceUtilities.supportsQuickLookAR(),t=exports.DeviceUtilities.isiOS()||exports.DeviceUtilities.isiPad();!this.button&&(ut||e||t)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=hb(this.context,e),this.link.addEventListener("message",this.lastCallback)),ut&&we("USDZ Exporter enabled: "+this.name),document.getElementById("open-in-ar")?.addEventListener("click",this.onClickedOpenInARElement),pc.registerExporter(this)}onDisable(){this.button?.remove(),this.link?.removeEventListener("message",this.lastCallback),ut&&we("USDZ Exporter disabled: "+this.name),document.getElementById("open-in-ar")?.removeEventListener("click",this.onClickedOpenInARElement),pc.unregisterExporter(this)}onClickedOpenInARElement=e=>{e.preventDefault(),this.exportAndOpen()};async exportAsync(){return this.exportAndOpen()}async exportAndOpen(){let e=this.exportFileName??this.objectToExport?.name??this.name;if(e+="-"+yw(),Un()||(e!==""&&(e+="-"),e+="MadeWithNeedle"),this.link||(this.link=hb(this.context,exports.DeviceUtilities.supportsQuickLookAR())),this.customUsdzFile)return ut&&console.log("Exporting custom usdz",this.customUsdzFile),this.openInQuickLook(this.customUsdzFile,e),null;if(!this.objectToExport)return console.warn("No object to export",this),null;Fo.beforeExport.invoke({exporter:this});const t=await this.export(this.objectToExport).finally(()=>{Fo.afterExport.invoke({exporter:this})});return t?(ut&&console.log("USDZ generation done. Downloading as "+e),this.openInQuickLook(t,e),t):(console.error("USDZ generation failed. Please report a bug",this),null)}async export(e){if(!e)return console.warn("No object to export"),null;const t=this._currentExportTasks.get(e);if(t)return t;const i=this.internalExport(e);return i instanceof Promise?(this._currentExportTasks.set(e,i),i.then(n=>(this._currentExportTasks.delete(e),n)).catch(n=>(this._currentExportTasks.delete(e),console.error("Error during USDZ export – please report a bug!",n),null))):i}_currentExportTasks=new Map;_previousTimeScale=1;async internalExport(e){ne.start("export-usdz",{onProgress:M=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:M}}))}}),ne.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),ne.report("export-usdz",{message:"Load progressive textures",autoStep:5}),ne.start("export-usdz-textures","export-usdz");const t=S.getComponentsInChildren(e,oi);for(const M of t)M&&M.enabled&&M.updateSprite(!0);const i=S.getComponentsInChildren(e,Ht),n=new Array;let o=0;for(const M of i){for(const O of M.sharedMeshes)if(O){let A=0;const D={exporter:this,type:"mesh",object:M.gameObject,mesh:O};if(Fo.beforeLODExport.invoke(D),D.overrideLevel!==void 0)if(D.overrideLevel===-1){ut&&console.warn("Skipping LOD export for mesh due to overrideLevel -1",M.gameObject,O);continue}else D.overrideLevel>=0&&(A=D.overrideLevel,ut&&console.log("Overriding LOD level for mesh export to level "+A+" "+O.name));const L=se.NEEDLE_progressive.assignMeshLOD(O,A);L instanceof Promise&&n.push(new Promise((N,$)=>{L.then(()=>{o++,ne.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:o,totalSteps:n.length}),N()}).catch(k=>$(k))}))}for(const O of M.sharedMaterials)if(O){let A=0;const D={exporter:this,type:"texture",object:M.gameObject,material:O};if(Fo.beforeLODExport.invoke(D),D.overrideLevel!==void 0)if(D.overrideLevel===-1){ut&&console.warn("Skipping LOD assignment due to overrideLevel -1",M.gameObject,O);continue}else D.overrideLevel>=0&&(A=D.overrideLevel,ut&&console.log("Overriding LOD level for texture export to level "+A+" "+O.name));const L=se.NEEDLE_progressive.assignTextureLOD(O,A);L instanceof Promise&&n.push(new Promise((N,$)=>{L.then(()=>{o++,ne.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:o,totalSteps:n.length}),N()}).catch(k=>$(k))}))}}ut&&we("Progressive Loading: "+n.length),await Promise.all(n),ut&&we("Progressive Loading: done"),ne.end("export-usdz-textures");const r=Vt.Global.Mask;Vt.Global.Set(Tn.AR);const a=new xw,l=new Ou(this.quickLookCompatible);let h;const d=[];this.interactive&&(d.push(new Wg),d.push(new Cr),globalThis.NEEDLE_USE_RAPIER&&S.getComponentsInChildren(e,Fe).length>0&&(this.physics?(h=new Hg,d.push(h)):T()&&console.warn("USDZExporter: Physics export is disabled, but there are active Rigidbody components in the scene. They will not be exported.")),d.push(new Lu),d.push(new Zg));const u=[l,...d,...this.extensions],p={self:this,exporter:a,extensions:u,object:e};ne.report("export-usdz","Invoking before-export"),this.dispatchEvent(new CustomEvent("before-export",{detail:p})),this.applyWebARSessionRoot(),this._previousTimeScale=this.context.time.timeScale,this.context.time.timeScale=0,ne.report("export-usdz","auto export animations and audio sources");const m=new Array;this.autoExportAnimations&&m.push(...vk(e,l)),u.find(M=>M.extensionName==="Audio")&&this.autoExportAudioSources&&m.push(...wk(e)),a.debug=ut,a.pruneUnusedNodes=!Ck;const _=dr.instance.objs.map(M=>M.batchedMesh);a.keepObject=M=>{let O=!0;const A=S.getComponent(M,Ht);return A&&!A.enabled&&(O=!1),O&&_.includes(M)&&(O=!1),O&&S.getComponentInParent(M,Qc)&&(O=!1),O&&S.getComponentInParent(M,$n)&&(O=!1),ut&&!O&&console.log("USDZExporter: Discarding object",M),O},a.beforeWritingDocument=()=>{if(T()&&l&&h){const M=l.animatedRoots;for(const O of M){const A=S.getComponentsInChildren(O,Fe).filter(L=>L.enabled),D=S.getComponents(O,Hi).filter(L=>L.enabled&&!L.isTrigger);(A.length>0||D.length>0)&&console.error("An animated object has physics components in its child hierarchy. This can lead to undefined behaviour due to a bug in Apple's QuickLook (FB15925487). Remove the physics components from child objects or verify that you get the expected results.",O)}}};const y=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(M=>{M.visible||y.push(M)});const v=u.find(M=>M.extensionName==="Behaviour");this.interactive&&v&&y.length>0&&v.addBehavior(xk(y));let b=!0;this.quickLookCompatible&&!this.interactive&&(b=!1),this.anchoringType!=="plane"&&this.anchoringType!=="none"&&this.anchoringType!=="image"&&this.anchoringType!=="face"&&(this.anchoringType="plane"),this.planeAnchoringAlignment!=="horizontal"&&this.planeAnchoringAlignment!=="vertical"&&this.planeAnchoringAlignment!=="any"&&(this.planeAnchoringAlignment="horizontal"),ne.report("export-usdz","Invoking exporter.parse");const w=await a.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:u,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:b}),R=new Blob([w],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,ne.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:p}));for(const M of m)S.destroy(M);return Vt.Global.Set(r),ne.end("export-usdz"),R}openInQuickLook(e,t){const i=e instanceof Blob?URL.createObjectURL(e):e,n=this.buildQuicklookOverlay();ut&&console.log("QuickLook Overlay",n);const o=n.callToAction?encodeURIComponent(n.callToAction):"",r=n.checkoutTitle?encodeURIComponent(n.checkoutTitle):"",a=n.checkoutSubtitle?encodeURIComponent(n.checkoutSubtitle):"";this.link.href=i+`#callToAction=${o}&checkoutTitle=${r}&checkoutSubtitle=${a}&callToActionURL=${n.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=t+".usdz",this.link.click()}download(e,t){Fo.save(e,t)}static save(e,t){const i=document.createElement("a");i.style.display="none",document.body.appendChild(i),typeof e=="string"?i.href=e:i.href=URL.createObjectURL(e),i.download=t,i.click(),i.remove()}lastCallback;quicklookCallback(e){if(e?.data=="_apple_ar_quicklook_button_tapped"){ut&&ue("Quicklook closed via call to action button");var t=new CustomEvent("quicklook-button-tapped",{detail:this});if(this.dispatchEvent(t),!t.defaultPrevented){const i=new URLSearchParams(this.link.href);if(i){const n=i.get("callToActionURL");ut&&we("Quicklook url: "+n),n&&(Un()?globalThis.open(n,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",n))}}}}buildQuicklookOverlay(){const e={};return this.customBranding&&Object.assign(e,this.customBranding),Un()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),e.callToAction="Close",e.checkoutTitle="🌵 Made with Needle",e.checkoutSubtitle="_"),(e.callToAction?.length||e.checkoutTitle?.length||e.checkoutSubtitle?.length)&&(e.callToAction?.length||(e.callToAction="\0"),e.checkoutTitle?.length||(e.checkoutTitle="\0"),e.checkoutSubtitle?.length||(e.checkoutSubtitle="\0")),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:e})),e}static invertForwardMatrix=new c.Matrix4().makeRotationY(Math.PI);static invertForwardQuaternion=new c.Quaternion().setFromEuler(new c.Euler(0,Math.PI,0));_rootSessionRootWasAppliedTo=null;_rootPositionBeforeExport=new c.Vector3;_rootRotationBeforeExport=new c.Quaternion;_rootScaleBeforeExport=new c.Vector3;getARScaleAndTarget(){if(!this.objectToExport)return{scale:1,_invertForward:!1,target:this.gameObject,sessionRoot:null};const e=S.findObjectOfType(Du);let t=S.getComponentInParent(this.objectToExport,Bi);t||(t=S.getComponentInChildren(this.objectToExport,Bi));let i=1,n=!1;const o=this.objectToExport;return e?i=e.arScale:t&&(i=t.arScale,n=t.invertForward),{scale:1/i,_invertForward:n,target:o,sessionRoot:t?.gameObject??null}}applyWebARSessionRoot(){if(!this.objectToExport)return;const{scale:e,_invertForward:t,target:i,sessionRoot:n}=this.getARScaleAndTarget(),o=n?.matrixWorld.clone().invert();this._rootSessionRootWasAppliedTo=i,this._rootPositionBeforeExport.copy(i.position),this._rootRotationBeforeExport.copy(i.quaternion),this._rootScaleBeforeExport.copy(i.scale),i.scale.multiplyScalar(e),t&&i.quaternion.multiply(Fo.invertForwardQuaternion),i.updateMatrix(),i.updateMatrixWorld(!0),n&&o&&i.matrix.premultiply(o)}revertWebARSessionRoot(){if(!this.objectToExport||!this._rootSessionRootWasAppliedTo)return;const e=this._rootSessionRootWasAppliedTo;e.position.copy(this._rootPositionBeforeExport),e.quaternion.copy(this._rootRotationBeforeExport),e.scale.copy(this._rootScaleBeforeExport),e.updateMatrix(),e.updateMatrixWorld(!0),this._rootSessionRootWasAppliedTo=null}createQuicklookButton(){const t=no.getOrCreate().createQuicklookButton();return t.parentNode||this.context.menu.appendChild(t),t}};wt([f(c.Object3D)],ri.prototype,"objectToExport");wt([f()],ri.prototype,"autoExportAnimations");wt([f()],ri.prototype,"autoExportAudioSources");wt([f()],ri.prototype,"exportFileName");wt([f(URL)],ri.prototype,"customUsdzFile");wt([f(Or)],ri.prototype,"customBranding");wt([f()],ri.prototype,"anchoringType");wt([f()],ri.prototype,"maxTextureSize");wt([f()],ri.prototype,"planeAnchoringAlignment");wt([f()],ri.prototype,"interactive");wt([f()],ri.prototype,"physics");wt([f()],ri.prototype,"allowCreateQuicklookButton");wt([f()],ri.prototype,"quickLookCompatible");let an=ri;var Pk=Object.defineProperty,Mk=Object.getOwnPropertyDescriptor,Jg=(s,e,t,i)=>{for(var n=Mk(e,t),o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&Pk(e,t,n),n};class Qa extends E{get fog(){return this._fog||(this._fog=new c.Fog(0,0,50)),this._fog}get mode(){return 1}set near(e){this.fog.near=e}get near(){return this.fog.near}set far(e){this.fog.far=e}get far(){return this.fog.far}set color(e){this.fog.color.copy(e)}get color(){return this.fog.color}_fog;onEnable(){this.scene.fog=this.fog}onDisable(){this.scene.fog===this._fog&&(this.scene.fog=null)}}Jg([f()],Qa.prototype,"near");Jg([f()],Qa.prototype,"far");Jg([f(c.Color)],Qa.prototype,"color");var Ok=Object.defineProperty,ey=(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&&Ok(e,t,n),n};class kr extends E{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!Uc||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new c.BoxHelper(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=zm(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),me.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(;this._boxHelper;)this._boxHelper?.update(),yield}}ey([f()],kr.prototype,"objectBounds");ey([f(c.Color)],kr.prototype,"color");ey([f()],kr.prototype,"isGizmo");var kk=Object.defineProperty,ty=(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&&kk(e,t,n),n};class Ya extends E{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!Uc)return;const e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new c.GridHelper(e,t,this.color0??new c.Color(.4,.4,.4),this.color1??new c.Color(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset)),this.gridHelper&&this.gameObject.add(this.gridHelper)}onDisable(){this.gridHelper&&(this.gameObject.remove(this.gridHelper),this.gridHelper=null)}}ty([f()],Ya.prototype,"isGizmo");ty([f(c.Color)],Ya.prototype,"color0");ty([f(c.Color)],Ya.prototype,"color1");var Ek=Object.defineProperty,iy=(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&&Ek(e,t,n),n};class ny extends E{connectedBody;get rigidBody(){return this._rigidBody}_rigidBody=null;onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(Fe)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.activeAndEnabled&&this.createJoint(this.rigidBody,this.connectedBody)}}iy([f(Fe)],ny.prototype,"connectedBody");class sy extends ny{createJoint(e,t){this.context.physics.engine?.addFixedJoint(e,t)}}class rh extends ny{anchor;axis;createJoint(e,t){this.axis&&this.anchor&&this.context.physics.engine?.addHingeJoint(e,t,this.anchor,this.axis)}}iy([f(c.Vector3)],rh.prototype,"anchor");iy([f(c.Vector3)],rh.prototype,"axis");var Rk=Object.defineProperty,Tk=Object.getOwnPropertyDescriptor,Si=(s,e,t,i)=>{for(var n=i>1?void 0:i?Tk(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&&Rk(e,t,n),n};function Qr(s){return s*Math.PI/180}const db=300,Us=x("debuglights");class xt extends E{type=0;get range(){return this._range}set range(e){this._range=e,this.light&&(this.light.type==="SpotLight"||this.light.type==="PointLight")&&"distance"in this.light&&(this.light.distance=e)}_range=1;get spotAngle(){return this._spotAngle}set spotAngle(e){this._spotAngle=e,this.light&&this.light.type==="SpotLight"&&"angle"in this.light&&(this.light.angle=Qr(e/2))}_spotAngle=30;get innerSpotAngle(){return this._innerSpotAngle}set innerSpotAngle(e){if(this._innerSpotAngle=e,this.light&&this.light.type==="SpotLight"&&"penumbra"in this.light){const t=this.spotAngle,n=1-Qr(e/2)/Qr(t/2);this.light.penumbra=n}}_innerSpotAngle=10;set color(e){this._color=e,this.light!==void 0&&(this.light.color=e)}get color(){return this.light?this.light.color:this._color}_color=new c.Color(16777215);set shadowNearPlane(e){if(e!==this._shadowNearPlane&&(this._shadowNearPlane=e,this.light?.shadow?.camera!==void 0)){const t=this.light.shadow.camera;t.near=e}}get shadowNearPlane(){return this._shadowNearPlane}_shadowNearPlane=.1;set shadowBias(e){e!==this._shadowBias&&(this._shadowBias=e,this.light?.shadow?.bias!==void 0&&(this.light.shadow.bias=e,this.light.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}_shadowBias=0;set shadowNormalBias(e){e!==this._shadowNormalBias&&(this._shadowNormalBias=e,this.light?.shadow?.normalBias!==void 0&&(this.light.shadow.normalBias=e,this.light.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}_shadowNormalBias=0;_overrideShadowBiasSettings=!1;set shadows(e){this._shadows=e,this.light&&(this.light.castShadow=e!==0,this.updateShadowSoftHard())}get shadows(){return this._shadows}_shadows=1;lightmapBakeType=4;set intensity(e){this._intensity=e,this.light&&(this.light.intensity=e),Us&&console.log("Set light intensity to "+this._intensity,e,this)}get intensity(){return this._intensity}_intensity=-1;get shadowDistance(){const e=this.light;return e?.shadow?e.shadow.camera.far:-1}set shadowDistance(e){this._shadowDistance=e;const t=this.light;if(t?.shadow){const i=t.shadow.camera;i.far=e,i.updateProjectionMatrix()}}_shadowDistance;shadowWidth;shadowHeight;get shadowResolution(){const e=this.light;return e?.shadow?e.shadow.mapSize.x:-1}set shadowResolution(e){if(e===this._shadowResolution)return;this._shadowResolution=e;const t=this.light;t?.shadow&&(t.shadow.mapSize.set(e,e),t.shadow.needsUpdate=!0)}_shadowResolution=void 0;get isBaked(){return this.lightmapBakeType===2}get selfIsLight(){if(this.gameObject.isLight===!0)return!0;switch(this.gameObject.type){case"SpotLight":case"PointLight":case"DirectionalLight":return!0}return!1}light=void 0;getWorldPosition(e){return this.light?this.type===1?this.light.getWorldPosition(e).multiplyScalar(1):this.light.getWorldPosition(e):e}awake(){this.color=new c.Color(this.color??16777215),Us&&console.log(this.name,this)}onEnable(){Us&&console.log("ENABLE LIGHT",this.name),this.createLight(),!this.isBaked&&(this.light&&(this.light.visible=!0,this.light.intensity=this._intensity,Us&&console.log("Set light intensity to "+this.light.intensity,this.name),this.selfIsLight||this.light.parent!==this.gameObject&&this.gameObject.add(this.light)),this.type===1&&this.startCoroutine(this.updateMainLightRoutine(),me.LateUpdate))}onDisable(){Us&&console.log("DISABLE LIGHT",this.name),this.light&&(this.selfIsLight?this.light.intensity=0:this.light.visible=!1)}createLight(){const e=this.selfIsLight;if(e&&!this.light)this.light=this.gameObject,this.light.name=this.name,this._intensity=this.light.intensity,this.type===1&&this.setDirectionalLight(this.light);else if(!this.light)switch(this.type){case 1:const t=new c.DirectionalLight(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-db*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),rr(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Us){const r=new c.DirectionalLightHelper(this.light,.2,this.color);this.context.scene.add(r)}break;case 0:const i=new c.SpotLight(this.color,this.intensity*Math.PI,this.range,Qr(this.spotAngle/2),1-Qr(this.innerSpotAngle/2)/Qr(this.spotAngle/2),2);i.position.set(0,0,0),i.rotation.set(0,0,0),this.light=i;const n=i.target;i.add(n),n.position.set(0,0,this.range),n.rotation.set(0,0,0);break;case 2:const o=new c.PointLight(this.color,this.intensity*Math.PI,this.range);this.light=o;break}if(this.light){if(this._intensity>=0?this.light.intensity=this._intensity:this._intensity=this.light.intensity,this.shadows!==0?this.light.castShadow=!0:this.light.castShadow=!1,this.light.shadow){this._shadowResolution!==void 0&&this._shadowResolution>4?(this.light.shadow.mapSize.width=this._shadowResolution,this.light.shadow.mapSize.height=this._shadowResolution):(this.light.shadow.mapSize.width=2048,this.light.shadow.mapSize.height=2048),Us&&console.log("Override shadow bias?",this._overrideShadowBiasSettings,this.shadowBias,this.shadowNormalBias),this.light.shadow.bias=this.shadowBias,this.light.shadow.normalBias=this.shadowNormalBias,this.updateShadowSoftHard();const t=this.light.shadow.camera;if(t.near=this.shadowNearPlane,this._shadowDistance!==void 0&&typeof this._shadowDistance=="number"?t.far=this._shadowDistance:t.far=db*Math.abs(this.gameObject.scale.z),this.gameObject.scale.set(1,1,1),this.shadowWidth!==void 0)t.left=-this.shadowWidth/2,t.right=this.shadowWidth/2;else{const i=this.gameObject.scale.x;t.left*=i,t.right*=i}if(this.shadowHeight!==void 0)t.top=this.shadowHeight/2,t.bottom=-this.shadowHeight/2;else{const i=this.gameObject.scale.y;t.top*=i,t.bottom*=i}this.light.shadow.needsUpdate=!0,Us&&this.context.scene.add(new c.CameraHelper(t))}this.isBaked?this.light.removeFromParent():e||this.gameObject.add(this.light)}}*updateMainLightRoutine(){for(;;){this.type===1&&((!this.context.mainLight||this.intensity>this.context.mainLight.intensity)&&(this.context.mainLight=this),yield);break}}static allowChangingRendererShadowMapType=!0;updateShadowSoftHard(){this.light&&this.light.shadow&&(this.shadows===2||(this.light.shadow.radius=1,this.light.shadow.blurSamples=1))}setDirectionalLight(e){e.add(e.target),e.target.position.set(0,0,-1)}}Si([f()],xt.prototype,"type",2);Si([f()],xt.prototype,"range",1);Si([f()],xt.prototype,"spotAngle",1);Si([f()],xt.prototype,"innerSpotAngle",1);Si([f(c.Color)],xt.prototype,"color",1);Si([f()],xt.prototype,"shadowNearPlane",1);Si([f()],xt.prototype,"shadowBias",1);Si([f()],xt.prototype,"shadowNormalBias",1);Si([f()],xt.prototype,"shadows",1);Si([f()],xt.prototype,"lightmapBakeType",2);Si([f()],xt.prototype,"intensity",1);Si([f()],xt.prototype,"shadowDistance",1);Si([f()],xt.prototype,"shadowResolution",1);new c.Vector3(0,0,0);var Ak=Object.defineProperty,Iu=(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&&Ak(e,t,n),n};const np=x("debuglods"),Dk=x("nolods");class Ka{screenRelativeTransitionHeight;distance;renderers}Iu([f()],Ka.prototype,"screenRelativeTransitionHeight");Iu([f()],Ka.prototype,"distance");Iu([f(Ht)],Ka.prototype,"renderers");class Lk{model;get renderers(){return this.model.renderers}constructor(e){this.model=e}}class ju extends E{lodModels=[];_lods=[];_settings=[];_lodsHandler;start(){if(np&&console.log("LODGROUP",this.name,this.lodModels,this),!Dk&&!this._lodsHandler&&this.gameObject&&this.lodModels&&Array.isArray(this.lodModels)){const e=[];for(const i of this.lodModels){const n=new Lk(i);this._lods.push(n);for(const o of n.renderers)e.includes(o)||e.push(o)}this._lodsHandler=new Array;for(let i=0;i<e.length;i++){const n=new c.LOD;this._lodsHandler.push(n),this.gameObject.add(n)}const t=new c.Object3D;t.name="Cull "+this.name;for(let i=0;i<e.length;i++){const n=e[i],o=this._lodsHandler[i],r=n.gameObject;np&&console.log(i,r.name);for(const a of this._lods){const l=a.model.distance;let h=null;if(a.renderers.includes(n)?h=r:h=t,h.type==="Group"){console.warn(`LODGroup ${this.name}: Group or MultiMaterial object's are not supported as LOD object: ${h.name}`);continue}np&&console.log("LEVEL",h.name,l),o.autoUpdate=!1,this.onAddLodLevel(o,h,a.model.distance)}}}}onAfterRender(){if(!this.gameObject||!this._lodsHandler)return;const e=this.context.mainCamera;if(e)for(const t of this._lodsHandler){t.update(e);const i=t.getCurrentLevel(),n=t.levels[i];t.layers.mask=n.object.layers.mask}}onAddLodLevel(e,t,i){if(t===this.gameObject){console.warn("LODGroup component must be on parent object and not mesh directly at the moment",t.name,t);return}e.addLevel(t,i*this._distanceFactor,.01);const n={lod:e,levelIndex:e.levels.length-1,distance:i};this._settings.push(n)}_distanceFactor=1;distanceFactor(e){if(e!==this._distanceFactor){this._distanceFactor=e;for(const t of this._settings){const i=t.lod.levels[t.levelIndex];i.distance=t.distance*e}}}}Iu([f(Ka)],ju.prototype,"lodModels");var Ik=Object.defineProperty,oy=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&Ik(e,t,n),n};const Kh=x("debugnestedgltf");class Za extends E{filePath;loaded=new oe;loadAssetInParent=!0;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){return this.filePath?.preload()||null}async start(){if(this._isLoadingOrDoneLoading)return;Kh&&console.log(this,this.guid);const e=this.gameObject.parent;if(e&&this.filePath){this._isLoadingOrDoneLoading=!0;const t=new fn;t.idProvider=new _t(this.hash(this.guid)),t.parent=this.loadAssetInParent!==!1?e:this.gameObject,this.gameObject.updateMatrix();const i=this.gameObject.matrix;Kh&&console.log("Load nested:",this.filePath?.url??this.filePath,this.gameObject.position);const n=await this.filePath?.instantiate?.call(this.filePath,t);Kh&&console.log("Nested loaded:",this.filePath?.url??this.filePath,n),n&&this.loadAssetInParent!==!1&&(n.matrixAutoUpdate=!1,n.matrix.identity(),n.applyMatrix4(i),n.matrixAutoUpdate=!0,n.layers.disableAll(),n.layers.set(this.layer),this.loaded.invoke({component:this,instance:n,asset:this.filePath})),Kh&&console.log("Nested loading done:",this.filePath?.url??this.filePath,n)}}onDestroy(){this.filePath?.unload()}hash(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);return t}}oy([f(K)],Za.prototype,"filePath");oy([f(oe)],Za.prototype,"loaded");oy([f()],Za.prototype,"loadAssetInParent");var jk=Object.defineProperty,ry=(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&&jk(e,t,n),n};const Bk=x("debugnet"),Bu=class sm extends E{url=null;urlParameterName=null;localhost=null;awake(){Bk&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?sm.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const o=x(this.urlParameterName);o&&typeof o=="string"&&(e=o)}if(!e)return null;const i=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return i?.groups?i?.groups.socket_prefix?e:"wss://"+i?.groups.url:null}static GetUrl(e,t){let i=e;const n=sm.IsLocalNetwork()&&t;if(n&&(i=t),e?.startsWith("/")){const o=n?i:window.location.origin;o?.endsWith("/")&&e.startsWith("/")&&(e=e.substring(1)),i=o+e}return i}static IsLocalNetwork(e=window.location.hostname){return pi(e)}};ry([f()],Bu.prototype,"url");ry([f()],Bu.prototype,"urlParameterName");ry([f()],Bu.prototype,"localhost");let ay=Bu;var Uk=Object.defineProperty,Uu=(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&&Uk(e,t,n),n};class Er extends E{referenceSpace;from;affectPosition=!1;affectRotation=!1;alignLookDirection=!1;levelLookDirection=!1;levelPosition=!1;positionOffset=new c.Vector3(0,0,0);rotationOffset=new c.Vector3(0,0,0);offset=new c.Vector3(0,0,0);update(){if(!this.from)return;var e=Q(this.from),t=fe(this.from);this.offset.copy(this.positionOffset);const i=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(i),e.add(this.offset),this.levelPosition&&this.referenceSpace){const a=new c.Plane(this.gameObject.up,0),l=Q(this.referenceSpace);a.setFromNormalAndCoplanarPoint(this.gameObject.up,l);const h=new c.Vector3(0,0,0);a.projectPoint(e,h),e.copy(h)}this.affectPosition&&rt(this.gameObject,e);const n=new c.Euler(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),o=new c.Quaternion().setFromEuler(n);this.affectRotation&&ln(this.gameObject,t.multiply(o));const r=new c.Vector3;this.from.getWorldDirection(r).multiplyScalar(50),this.levelLookDirection&&(r.y=0),this.alignLookDirection&&this.gameObject.lookAt(r)}}Uu([f(S)],Er.prototype,"referenceSpace");Uu([f(S)],Er.prototype,"from");Uu([f(c.Vector3)],Er.prototype,"positionOffset");Uu([f(c.Vector3)],Er.prototype,"rotationOffset");var Fk=Object.defineProperty,wo=(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&&Fk(e,t,n),n};class ii{time=0;value=0;inTangent=1/0;inWeight;outTangent=1/0;outWeight;weightedMode;constructor(e=0,t=0){this.time=e,this.value=t}}wo([f()],ii.prototype,"time");wo([f()],ii.prototype,"value");wo([f()],ii.prototype,"inTangent");wo([f()],ii.prototype,"inWeight");wo([f()],ii.prototype,"outTangent");wo([f()],ii.prototype,"outWeight");wo([f()],ii.prototype,"weightedMode");const Vw=class Vl{static linearFromTo(e,t,i){const n=new Vl,o=new ii;o.time=0,o.value=e;const r=new ii;return r.time=i,r.value=t,n.keys.push(o,r),n}static constant(e){const t=new Vl,i=new ii;return i.time=0,i.value=e,t.keys.push(i),t}keys=[];clone(){const e=new Vl;return e.keys=this.keys?.map(t=>{const i=new ii;return i.time=t.time,i.value=t.value,i.inTangent=t.inTangent,i.inWeight=t.inWeight,i.outTangent=t.outTangent,i.outWeight=t.outWeight,i.weightedMode=t.weightedMode,i})||[],e}get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(e){if(!this.keys||this.keys.length==0)return 0;if(this.keys.length===1)return this.keys[0].value;if(this.keys[0].time>=e)return this.keys[0].value;for(let t=0;t<this.keys.length;t++){const i=this.keys[t];if(i.time<=e)if(t+1<this.keys.length){const o=this.keys[t+1];if(o.time<e)continue;return!isFinite(i.outTangent)||!isFinite(o.inTangent)?i.value:Vl.interpolateValue(e,i,o)}else return i.value}return this.keys[this.keys.length-1].value}static interpolateValue(e,t,i){const n=t.time,o=t.value,r=t.outTangent,a=i.time,l=i.value,h=i.inTangent,d=a-n,u=d*d,p=u*d,m=((r+h)*d-2*(l-o))/p,g=(3*(l-o)-(h+2*r)*d)/u,_=r,y=o,v=e-n,b=v*v,w=b*v;return m*w+g*b+_*v+y}};wo([f(ii)],Vw.prototype,"keys");let ah=Vw;var zk=Object.defineProperty,C=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&zk(e,t,n),n};const Zh=x("debugparticles");var is=(s=>(s[s.Billboard=0]="Billboard",s[s.Stretch=1]="Stretch",s[s.HorizontalBillboard=2]="HorizontalBillboard",s[s.VerticalBillboard=3]="VerticalBillboard",s[s.Mesh=4]="Mesh",s))(is||{});class Rr{alphaKeys=[];colorKeys=[];get duration(){return 1}evaluate(e,t){let i,n=0,o=null,r=0;for(let a=0;a<this.alphaKeys.length;a++){const l=this.alphaKeys[a];(l.time<e||!i)&&(i=l,n=a)}for(let a=0;a<this.colorKeys.length;a++){const l=this.colorKeys[a];(l.time<e||!o)&&(o=l,r=a)}if(o)if(r+1<this.colorKeys.length){const l=this.colorKeys[r+1],h=I.remap(e,o.time,l.time,0,1);t.r=I.lerp(o.color.r,l.color.r,h),t.g=I.lerp(o.color.g,l.color.g,h),t.b=I.lerp(o.color.b,l.color.b,h)}else t.r=o.color.r,t.g=o.color.g,t.b=o.color.b;if(i)if(n+1<this.alphaKeys.length){const l=this.alphaKeys[n+1],h=I.remap(e,i.time,l.time,0,1);t.alpha=I.lerp(i.alpha,l.alpha,h)}else t.alpha=i.alpha;return t}}C([f()],Rr.prototype,"alphaKeys");C([f()],Rr.prototype,"colorKeys");var Cc=(s=>(s[s.Local=0]="Local",s[s.World=1]="World",s[s.Custom=2]="Custom",s))(Cc||{}),Yd=(s=>(s[s.Sphere=0]="Sphere",s[s.SphereShell=1]="SphereShell",s[s.Hemisphere=2]="Hemisphere",s[s.HemisphereShell=3]="HemisphereShell",s[s.Cone=4]="Cone",s[s.Box=5]="Box",s[s.Mesh=6]="Mesh",s[s.ConeShell=7]="ConeShell",s[s.ConeVolume=8]="ConeVolume",s[s.ConeVolumeShell=9]="ConeVolumeShell",s[s.Circle=10]="Circle",s[s.CircleEdge=11]="CircleEdge",s[s.SingleSidedEdge=12]="SingleSidedEdge",s[s.MeshRenderer=13]="MeshRenderer",s[s.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",s[s.BoxShell=15]="BoxShell",s[s.BoxEdge=16]="BoxEdge",s[s.Donut=17]="Donut",s[s.Rectangle=18]="Rectangle",s[s.Sprite=19]="Sprite",s[s.SpriteRenderer=20]="SpriteRenderer",s))(Yd||{});const Ss=class $l{static constant(e){const t=new $l;return t.setConstant(e),t}static betweenTwoConstants(e,t){const i=new $l;return i.setMinMaxConstant(e,t),i}static curve(e,t=1){const i=new $l;return i.setCurve(e,t),i}setConstant(e){this.mode=0,this.constant=e}setMinMaxConstant(e,t){this.mode=3,this.constantMin=e,this.constantMax=t}setCurve(e,t=1){this.mode=1,this.curve=e,this.curveMultiplier=t}mode="Constant";constant;constantMin;constantMax;curve;curveMin;curveMax;curveMultiplier;clone(){const e=new $l;return e.mode=this.mode,e.constant=this.constant,e.constantMin=this.constantMin,e.constantMax=this.constantMax,e.curve=this.curve?.clone(),e.curveMin=this.curveMin?.clone(),e.curveMax=this.curveMax?.clone(),e.curveMultiplier=this.curveMultiplier,e}evaluate(e,t){const i=t===void 0?Math.random():t;switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return e=I.clamp01(e),this.curve.evaluate(e)*this.curveMultiplier;case 2:case"TwoCurves":const n=e*this.curveMin.duration,o=e*this.curveMax.duration;return I.lerp(this.curveMin.evaluate(n),this.curveMax.evaluate(o),i%1)*this.curveMultiplier;case 3:case"TwoConstants":return I.lerp(this.constantMin,this.constantMax,i%1);default:this.curveMax.evaluate(e)*this.curveMultiplier;break}return 0}getMax(){switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return this.getMaxFromCurve(this.curve)*this.curveMultiplier;case 2:case"TwoCurves":return Math.max(this.getMaxFromCurve(this.curveMin),this.getMaxFromCurve(this.curveMax))*this.curveMultiplier;case 3:case"TwoConstants":return Math.max(this.constantMin,this.constantMax);default:return 0}}getMaxFromCurve(e){if(!e)return 0;let t=Number.MIN_VALUE;for(let i=0;i<e.keys.length;i++){const n=e.keys[i];n.value>t&&(t=n.value)}return t}};C([f()],Ss.prototype,"mode");C([f()],Ss.prototype,"constant");C([f()],Ss.prototype,"constantMin");C([f()],Ss.prototype,"constantMax");C([f(ah)],Ss.prototype,"curve");C([f(ah)],Ss.prototype,"curveMin");C([f(ah)],Ss.prototype,"curveMax");C([f()],Ss.prototype,"curveMultiplier");let H=Ss;const xo=class mt{static constant(e){const t=new mt;return t.constant(e),t}static betweenTwoColors(e,t){const i=new mt;return i.betweenTwoColors(e,t),i}constant(e){return this.mode=0,this.color=e,this}betweenTwoColors(e,t){return this.mode=2,this.colorMin=e,this.colorMax=t,this}mode=0;color;colorMin;colorMax;gradient;gradientMin;gradientMax;static _temp=new ee(0,0,0,1);static _temp2=new ee(0,0,0,1);evaluate(e,t){const i=t===void 0?Math.random():t;switch(this.mode){case 0:case"Color":return this.color;case 1:case"Gradient":return this.gradient.evaluate(e,mt._temp),mt._temp;case 2:case"TwoColors":return mt._temp.lerpColors(this.colorMin,this.colorMax,i);case 3:case"TwoGradients":return this.gradientMin.evaluate(e,mt._temp),this.gradientMax.evaluate(e,mt._temp2),mt._temp.lerp(mt._temp2,i);case 4:case"RandomColor":const o=Math.random();return this.gradientMin.evaluate(e,mt._temp),this.gradientMax.evaluate(e,mt._temp2),mt._temp.lerp(mt._temp2,o)}return mt._temp.set(16777215),mt._temp.alpha=1,mt._temp}};C([f()],xo.prototype,"mode");C([f(ee)],xo.prototype,"color");C([f(ee)],xo.prototype,"colorMin");C([f(ee)],xo.prototype,"colorMax");C([f(Rr)],xo.prototype,"gradient");C([f(Rr)],xo.prototype,"gradientMin");C([f(Rr)],xo.prototype,"gradientMax");let Tr=xo;var om=(s=>(s[s.Hierarchy=0]="Hierarchy",s[s.Local=1]="Local",s[s.Shape=2]="Shape",s))(om||{});class At{cullingMode;duration;emitterVelocityMode;flipRotation;gravityModifier;gravityModifierMultiplier;loop;maxParticles;playOnAwake;prewarm;ringBufferLoopRange;ringBufferMode;scalingMode;simulationSpace;simulationSpeed;startColor;startDelay;startDelayMultiplier;startLifetime;startLifetimeMultiplier;startRotation;startRotationMultiplier;startRotation3D;startRotationX;startRotationXMultiplier;startRotationY;startRotationYMultiplier;startRotationZ;startRotationZMultiplier;startSize;startSize3D;startSizeMultiplier;startSizeX;startSizeXMultiplier;startSizeY;startSizeYMultiplier;startSizeZ;startSizeZMultiplier;startSpeed;startSpeedMultiplier;stopAction;useUnscaledTime}C([f(H)],At.prototype,"gravityModifier");C([f(Tr)],At.prototype,"startColor");C([f(H)],At.prototype,"startDelay");C([f(H)],At.prototype,"startLifetime");C([f(H)],At.prototype,"startRotation");C([f(H)],At.prototype,"startRotationX");C([f(H)],At.prototype,"startRotationY");C([f(H)],At.prototype,"startRotationZ");C([f(H)],At.prototype,"startSize");C([f(H)],At.prototype,"startSizeX");C([f(H)],At.prototype,"startSizeY");C([f(H)],At.prototype,"startSizeZ");C([f(H)],At.prototype,"startSpeed");class Kd{cycleCount;maxCount;minCount;probability;repeatInterval;time;count;_performed=0;reset(){this._performed=0}run(e){if(e<=this.time)return 0;let t=0;if(this.cycleCount===0||this._performed<this.cycleCount){const i=this.time+this.repeatInterval*this._performed;if(e>=i&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:t=this.count.constant;break;case 3:t=I.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:t=this.count.curve.evaluate(Math.random());break;case 2:const n=Math.random();t=I.lerp(this.count.curveMin.evaluate(n),this.count.curveMax.evaluate(n),Math.random());break}}return t}}class Cs{enabled;get burstCount(){return this.bursts?.length??0}bursts;rateOverTime;rateOverTimeMultiplier;rateOverDistance;rateOverDistanceMultiplier;system;reset(){this.bursts?.forEach(e=>e.reset())}getBurst(){let e=0;if(this.burstCount>0)for(let t=0;t<this.burstCount;t++){const i=this.bursts[t];this.system.main.loop&&i.time>=this.system.time&&i.reset(),e+=Math.round(i.run(this.system.time))}return e}}C([f()],Cs.prototype,"enabled");C([f()],Cs.prototype,"bursts");C([f(H)],Cs.prototype,"rateOverTime");C([f()],Cs.prototype,"rateOverTimeMultiplier");C([f(H)],Cs.prototype,"rateOverDistance");C([f()],Cs.prototype,"rateOverDistanceMultiplier");class Fu{enabled;color}C([f(Tr)],Fu.prototype,"color");class Ar{enabled;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_time=0;_temp=new c.Vector3;evaluate(e,t,i){if(t||(t=this._temp),!this.enabled)return t.x=t.y=t.z=1,t;if(this.separateAxes)t.x=this.x.evaluate(e,i)*this.xMultiplier,t.y=this.y.evaluate(e,i)*this.yMultiplier,t.z=this.z.evaluate(e,i)*this.zMultiplier;else{const n=this.size.evaluate(e,i)*this.sizeMultiplier;t.x=n}return t}}C([f(H)],Ar.prototype,"size");C([f(H)],Ar.prototype,"x");C([f(H)],Ar.prototype,"y");C([f(H)],Ar.prototype,"z");const Xe=class Wl{get type(){return Yd[this.shapeType]}initialize(e){this.onInitialize(e),e.position.x=this._vector.x,e.position.y=this._vector.y,e.position.z=this._vector.z}toJSON(){return this}clone(){return new Wl}shapeType=5;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcSpread;arcSpeedMultiplier;arcMode;boxThickness;position;rotation;_rotation=new c.Euler;scale;radius;radiusThickness;sphericalDirectionAmount;randomDirectionAmount;randomPositionAmount;meshShapeType;meshRenderer;_meshObj;_meshGeometry;setMesh(e){this.meshRenderer=e,e?(this._meshObj=e.sharedMeshes[Math.floor(Math.random()*e.sharedMeshes.length)],this._meshGeometry=this._meshObj.geometry):(this._meshObj=void 0,this._meshGeometry=void 0)}system;_space;_worldSpaceMatrix=new c.Matrix4;_worldSpaceMatrixInverse=new c.Matrix4;constructor(){Zh&&console.log(this)}update(e,t){}onUpdate(e,t,i,n){this.system=e,this._space=i,i===1&&(this._worldSpaceMatrix.copy(n.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}applyRotation(e){const t=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return t&&(this._rotation.x=I.toRadians(this.rotation.x),this._rotation.y=I.toRadians(this.rotation.y),this._rotation.z=I.toRadians(this.rotation.z),this._rotation.order="ZYX",e.applyEuler(this._rotation)),t}_vector=new c.Vector3(0,0,0);_temp=new c.Vector3(0,0,0);_triangle=new c.Triangle;onInitialize(e){this._vector.set(0,0,0),e.mesh=void 0,e.mesh_geometry=void 0;const t=this._temp.copy(this.position),i=this._space===1;i&&t.applyQuaternion(this.system.worldQuaternion);let n=this.radius;if(i&&(n*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:Zh&&j.DrawWireBox(this.position,this.scale,14540253,1),this._vector.x=Math.random()*this.scale.x-this.scale.x/2,this._vector.y=Math.random()*this.scale.y-this.scale.y/2,this._vector.z=Math.random()*this.scale.z-this.scale.z/2,this._vector.add(t);break;case 4:this.randomConePoint(this.position,this.angle,n,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 10:this.randomCirclePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 13:const o=this.meshRenderer;o?.destroyed==!1&&this.setMesh(o);const r=e.mesh=this._meshObj,a=e.mesh_geometry=this._meshGeometry;if(r&&a)switch(this.meshShapeType){case 0:{const l=a.getAttribute("position"),h=Math.floor(Math.random()*l.count);this._vector.fromBufferAttribute(l,h),this._vector.applyMatrix4(r.matrixWorld),e.mesh_normal=h}break;case 1:break;case 2:{const l=a.index;if(l){let h=Math.random(),d=Math.random();h+d>1&&(h=1-h,d=1-d);const u=Math.floor(Math.random()*(l.count/3));let p=u*3,m=u*3+1,g=u*3+2;p=l.getX(p),m=l.getX(m),g=l.getX(g);const _=a.getAttribute("position");this._triangle.a.fromBufferAttribute(_,p),this._triangle.b.fromBufferAttribute(_,m),this._triangle.c.fromBufferAttribute(_,g),this._vector.set(0,0,0).addScaledVector(this._triangle.a,h).addScaledVector(this._triangle.b,d).addScaledVector(this._triangle.c,1-(h+d)),this._vector.applyMatrix4(r.matrixWorld),e.mesh_normal=u}}break}break;default:this._vector.set(0,0,0),T()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",Yd[this.shapeType]),globalThis.__particlesystem_shapetype_unsupported=!0);break}this.randomizePosition(this._vector,this.randomPositionAmount)}this.applyRotation(this._vector),i&&(this._vector.applyQuaternion(this.system.worldQuaternion),this._vector.add(this.system.worldPos)),Zh&&j.DrawSphere(this._vector,.03,16711680,.5,!0)}_dir=new c.Vector3;getDirection(e,t){if(!this.enabled)return this._dir.set(0,0,1),this._dir;switch(this.shapeType){case 5:this._dir.set(0,0,1);break;case 4:this._dir.set(0,0,1);break;case 10:case 0:const i=t.x,n=t.y,o=t.z;this._dir.set(i,n,o),this.system?.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;case 13:const r=e.mesh,a=e.mesh_geometry;if(r&&a)switch(this.meshShapeType){case 0:{const l=a.getAttribute("normal"),h=e.mesh_normal;this._dir.fromBufferAttribute(l,h)}break;case 1:break;case 2:{const l=a.index;if(l){const h=e.mesh_normal,d=l.getX(h*3),u=l.getX(h*3+1),p=l.getX(h*3+2),m=a.getAttribute("position"),g=B(),_=B(),y=B();g.fromBufferAttribute(m,d),_.fromBufferAttribute(m,u),y.fromBufferAttribute(m,p),g.sub(_),y.sub(_),g.cross(y),this._dir.copy(g).multiplyScalar(-1);const v=fe(r);this._dir.applyQuaternion(v)}}break}break;default:this._dir.set(0,0,1);break}return this._space===1&&this._dir.applyQuaternion(this.system.worldQuaternion),this.applyRotation(this._dir),this._dir.normalize(),this.spherizeDirection(this._dir,this.sphericalDirectionAmount),this.randomizeDirection(this._dir,this.randomDirectionAmount),Zh&&(j.DrawSphere(t,.01,8925952,.5,!0),j.DrawDirection(t,this._dir,8925952,.5,!0)),this._dir}static _randomQuat=new c.Quaternion;static _tempVec=new c.Vector3;randomizePosition(e,t){if(t<=0)return;const i=Wl._tempVec;i.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),i.x*=t*this.scale.x,i.y*=t*this.scale.y,i.z*=t*this.scale.z,e.add(i)}randomizeDirection(e,t){if(t===0)return;const i=Wl._randomQuat,n=Wl._tempVec;n.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),i.setFromAxisAngle(n,t*Math.random()*Math.PI),e.applyQuaternion(i)}spherizeDirection(e,t){if(t===0)return;const i=Math.random()*Math.PI*2,n=Math.acos(1-Math.random()*2),o=Math.sin(n)*Math.cos(i),r=Math.sin(n)*Math.sin(i),a=Math.cos(n),l=new c.Vector3(o,r,a);e.lerp(l,t)}randomSpherePoint(e,t,i,n,o){const r=Math.random(),a=Math.random(),l=2*Math.PI*r*(n/360),h=Math.acos(2*a-1),d=I.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,u=e.x+this.scale.x*(-d*Math.sin(h)*Math.cos(l)),p=e.y+this.scale.y*(d*Math.sin(h)*Math.sin(l)),m=e.z+this.scale.z*(d*Math.cos(h));o.x=u,o.y=p,o.z=m}randomCirclePoint(e,t,i,n,o){const r=Math.random(),a=2*Math.PI*r*(n/360),l=I.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,h=e.x+this.scale.x*l*Math.cos(a),d=e.y+this.scale.y*l*Math.sin(a),u=e.z;o.x=h,o.y=d,o.z=u}_loopTime=0;_loopDirection=1;randomConePoint(e,t,i,n,o,r,a){let l=0,h=0;switch(r){case 0:l=Math.random(),h=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:l=.5,h=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let d=2*Math.PI*l*(o/360);switch(r){case 2:case 1:d+=Math.PI+.5,d+=this._loopTime*Math.PI*2,d%=I.toRadians(o);break}const u=Math.acos(2*h-1),p=I.lerp(1,1-Math.pow(1-Math.random(),Math.PI),n)*i,m=e.x+-p*Math.sin(u)*Math.cos(d),g=e.y+p*Math.sin(u)*Math.sin(d),_=e.z;a.x=m*this.scale.x,a.y=g*this.scale.y,a.z=_*this.scale.z}};C([f()],Xe.prototype,"shapeType");C([f()],Xe.prototype,"enabled");C([f()],Xe.prototype,"alignToDirection");C([f()],Xe.prototype,"angle");C([f()],Xe.prototype,"arc");C([f()],Xe.prototype,"arcSpread");C([f()],Xe.prototype,"arcSpeedMultiplier");C([f()],Xe.prototype,"arcMode");C([f(c.Vector3)],Xe.prototype,"boxThickness");C([f(c.Vector3)],Xe.prototype,"position");C([f(c.Vector3)],Xe.prototype,"rotation");C([f(c.Vector3)],Xe.prototype,"scale");C([f()],Xe.prototype,"radius");C([f()],Xe.prototype,"radiusThickness");C([f()],Xe.prototype,"sphericalDirectionAmount");C([f()],Xe.prototype,"randomDirectionAmount");C([f()],Xe.prototype,"randomPositionAmount");C([f()],Xe.prototype,"meshShapeType");C([f(Kc)],Xe.prototype,"meshRenderer");let ly=Xe;class pe{damping;enabled;frequency;octaveCount;octaveMultiplier;octaveScale;positionAmount;quality;remap;remapEnabled;remapMultiplier;remapX;remapXMultiplier;remapY;remapYMultiplier;remapZ;remapZMultiplier;scrollSpeedMultiplier;separateAxes;strengthMultiplier;strengthX;strengthXMultiplier;strengthY;strengthYMultiplier;strengthZ;strengthZMultiplier;_noise;_time=0;update(e){this._time+=e.time.deltaTime*this.scrollSpeedMultiplier}_temp=new c.Vector3;apply(e,t,i,n,o,r){if(!this.enabled)return;this._noise||(this._noise=re.createNoise4D(()=>0));const a=this._temp.set(t.x,t.y,t.z).multiplyScalar(this.frequency),l=this._noise(a.x,a.y,a.z,this._time),h=this._noise(a.x,a.y,a.z,this._time+1e3*this.frequency),d=this._noise(a.x,a.y,a.z,this._time+2e3*this.frequency);this._temp.set(l,h,d).normalize();const u=o/r;let p=this.positionAmount.evaluate(u);this.separateAxes?(this._temp.x*=p*this.strengthXMultiplier,this._temp.y*=p*this.strengthYMultiplier,this._temp.z*=p*this.strengthZMultiplier):(this.strengthX&&(p*=this.strengthX.evaluate(u)*1.5),this._temp.multiplyScalar(p)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z}}C([f()],pe.prototype,"damping");C([f()],pe.prototype,"enabled");C([f()],pe.prototype,"frequency");C([f()],pe.prototype,"octaveCount");C([f()],pe.prototype,"octaveMultiplier");C([f()],pe.prototype,"octaveScale");C([f(H)],pe.prototype,"positionAmount");C([f()],pe.prototype,"quality");C([f(H)],pe.prototype,"remap");C([f()],pe.prototype,"remapEnabled");C([f()],pe.prototype,"remapMultiplier");C([f(H)],pe.prototype,"remapX");C([f()],pe.prototype,"remapXMultiplier");C([f(H)],pe.prototype,"remapY");C([f()],pe.prototype,"remapYMultiplier");C([f(H)],pe.prototype,"remapZ");C([f()],pe.prototype,"remapZMultiplier");C([f()],pe.prototype,"scrollSpeedMultiplier");C([f()],pe.prototype,"separateAxes");C([f()],pe.prototype,"strengthMultiplier");C([f(H)],pe.prototype,"strengthX");C([f()],pe.prototype,"strengthXMultiplier");C([f(H)],pe.prototype,"strengthY");C([f()],pe.prototype,"strengthYMultiplier");C([f(H)],pe.prototype,"strengthZ");C([f()],pe.prototype,"strengthZMultiplier");class Te{enabled;attachRibbonToTransform=!1;colorOverLifetime;colorOverTrail;dieWithParticles=!0;inheritParticleColor=!0;lifetime;lifetimeMultiplier;minVertexDistance=.2;mode=0;ratio=1;ribbonCount=1;shadowBias=0;sizeAffectsLifetime=!1;sizeAffectsWidth=!1;splitSubEmitterRibbons=!1;textureMode=0;widthOverTrail;widthOverTrailMultiplier;worldSpace=!1;getWidth(e,t,i,n){const o=this.widthOverTrail.evaluate(i,n);return e*=o,e}getColor(e,t,i){const n=this.colorOverTrail.evaluate(i),o=this.colorOverLifetime.evaluate(t);e.x*=n.r*o.r,e.y*=n.g*o.g,e.z*=n.b*o.b,"alpha"in n&&"alpha"in o&&(e.w*=n.alpha*o.alpha)}}C([f()],Te.prototype,"enabled");C([f()],Te.prototype,"attachRibbonToTransform");C([f(Tr)],Te.prototype,"colorOverLifetime");C([f(Tr)],Te.prototype,"colorOverTrail");C([f()],Te.prototype,"dieWithParticles");C([f()],Te.prototype,"inheritParticleColor");C([f(H)],Te.prototype,"lifetime");C([f()],Te.prototype,"lifetimeMultiplier");C([f()],Te.prototype,"minVertexDistance");C([f()],Te.prototype,"mode");C([f()],Te.prototype,"ratio");C([f()],Te.prototype,"ribbonCount");C([f()],Te.prototype,"shadowBias");C([f()],Te.prototype,"sizeAffectsLifetime");C([f()],Te.prototype,"sizeAffectsWidth");C([f()],Te.prototype,"splitSubEmitterRibbons");C([f()],Te.prototype,"textureMode");C([f(H)],Te.prototype,"widthOverTrail");C([f()],Te.prototype,"widthOverTrailMultiplier");C([f()],Te.prototype,"worldSpace");class Ie{enabled;space=0;orbitalX;orbitalY;orbitalZ;orbitalXMultiplier;orbitalYMultiplier;orbitalZMultiplier;orbitalOffsetX;orbitalOffsetY;orbitalOffsetZ;speedModifier;speedModifierMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_system;update(e){this._system=e}_temp=new c.Vector3;_temp2=new c.Vector3;_temp3=new c.Vector3;_hasOrbital=!1;_index=0;_orbitalMatrix=new c.Matrix4;init(e){this._index==0&&(e.debug=!0),this._index+=1,e.orbitx=this.orbitalX.evaluate(Math.random()),e.orbity=this.orbitalY.evaluate(Math.random()),e.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=e.orbitx!=0||e.orbity!=0||e.orbitz!=0}apply(e,t,i,n,o,r,a){if(!this.enabled)return;const l=r/a,h=this.speedModifier.evaluate(l)*this.speedModifierMultiplier,d=this.x.evaluate(l),u=this.y.evaluate(l),p=this.z.evaluate(l);if(this._temp.set(-d,u,p),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&this._system?.worldPos){const g=this._temp2.set(i.x,i.y,i.z),_=this.orbitalXMultiplier,y=this.orbitalYMultiplier,v=this.orbitalZMultiplier,b=h*Math.PI*2*10,w=Math.cos(b*_),R=Math.sin(b*_),M=Math.cos(b*y),O=Math.sin(b*y),A=Math.cos(b*v),D=Math.sin(b*v),L=g.x*(M*A)+g.y*(M*D)+g.z*-O,N=g.x*(R*O*A-w*D)+g.y*(R*O*D+w*A)+g.z*(R*M),$=g.x*(w*O*A+R*D)+g.y*(w*O*D-R*A)+g.z*(w*M),k=this._temp3.set(g.x-L,g.y-N,g.z-$);k.normalize(),k.multiplyScalar(.2/o*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),n.x+=k.x,n.y+=k.y,n.z+=k.z}n.x+=this._temp.x,n.y+=this._temp.y,n.z+=this._temp.z,n.x*=h,n.y*=h,n.z*=h}}C([f()],Ie.prototype,"enabled");C([f()],Ie.prototype,"space");C([f(H)],Ie.prototype,"orbitalX");C([f(H)],Ie.prototype,"orbitalY");C([f(H)],Ie.prototype,"orbitalZ");C([f()],Ie.prototype,"orbitalXMultiplier");C([f()],Ie.prototype,"orbitalYMultiplier");C([f()],Ie.prototype,"orbitalZMultiplier");C([f()],Ie.prototype,"orbitalOffsetX");C([f()],Ie.prototype,"orbitalOffsetY");C([f()],Ie.prototype,"orbitalOffsetZ");C([f(H)],Ie.prototype,"speedModifier");C([f()],Ie.prototype,"speedModifierMultiplier");C([f(H)],Ie.prototype,"x");C([f()],Ie.prototype,"xMultiplier");C([f(H)],Ie.prototype,"y");C([f()],Ie.prototype,"yMultiplier");C([f(H)],Ie.prototype,"z");C([f()],Ie.prototype,"zMultiplier");class Dt{animation;enabled;cycleCount;frameOverTime;frameOverTimeMultiplier;numTilesX;numTilesY;startFrame;startFrameMultiplier;rowMode;rowIndex;spriteCount;timeMode;sampleOnceAtStart(){if(this.timeMode===0)switch(this.frameOverTime.mode){case 0:case 3:case 2:case 1:return!0}return!1}getStartIndex(){return this.sampleOnceAtStart()?Math.random()*(this.numTilesX*this.numTilesY):0}evaluate(e){if(!this.sampleOnceAtStart())return this.getIndex(e)}getIndex(e){const t=this.numTilesX*this.numTilesY;e=e*this.cycleCount;let i=this.frameOverTime.evaluate(e%1);return i*=this.frameOverTimeMultiplier,i*=t,i=i%t,i=Math.floor(i),i}}C([f()],Dt.prototype,"animation");C([f()],Dt.prototype,"enabled");C([f()],Dt.prototype,"cycleCount");C([f(H)],Dt.prototype,"frameOverTime");C([f()],Dt.prototype,"frameOverTimeMultiplier");C([f()],Dt.prototype,"numTilesX");C([f()],Dt.prototype,"numTilesY");C([f(H)],Dt.prototype,"startFrame");C([f()],Dt.prototype,"startFrameMultiplier");C([f()],Dt.prototype,"rowMode");C([f()],Dt.prototype,"rowIndex");C([f()],Dt.prototype,"spriteCount");C([f()],Dt.prototype,"timeMode");class mn{enabled;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){return this.enabled?this.separateAxes?0:this.z.evaluate(e,t)*-1:0}}C([f()],mn.prototype,"enabled");C([f()],mn.prototype,"separateAxes");C([f(H)],mn.prototype,"x");C([f()],mn.prototype,"xMultiplier");C([f(H)],mn.prototype,"y");C([f()],mn.prototype,"yMultiplier");C([f(H)],mn.prototype,"z");C([f()],mn.prototype,"zMultiplier");class Gi{enabled;range;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){if(!this.enabled)return 0;if(!this.separateAxes){const i=I.lerp(this.range.x,this.range.y,t);return this.z.evaluate(i)*-1}return 0}}C([f()],Gi.prototype,"enabled");C([f()],Gi.prototype,"range");C([f()],Gi.prototype,"separateAxes");C([f(H)],Gi.prototype,"x");C([f()],Gi.prototype,"xMultiplier");C([f(H)],Gi.prototype,"y");C([f()],Gi.prototype,"yMultiplier");C([f(H)],Gi.prototype,"z");C([f()],Gi.prototype,"zMultiplier");class tt{enabled;dampen;drag;dragMultiplier;limit;limitMultiplier;separateAxes;limitX;limitXMultiplier;limitY;limitYMultiplier;limitZ;limitZMultiplier;multiplyDragByParticleSize=!1;multiplyDragByParticleVelocity=!1;space;_temp=new c.Vector3;_temp2=new c.Vector3;apply(e,t,i,n,o,r,a){if(this.enabled){const l=this.limit.evaluate(o)*this.limitMultiplier;if(t.length()>l){this._temp.copy(t).normalize().multiplyScalar(l);const d=this.dampen*.5;t.x=I.lerp(t.x,this._temp.x,d),t.y=I.lerp(t.y,this._temp.y,d),t.z=I.lerp(t.z,this._temp.z,d),i.x=I.lerp(i.x,this._temp.x,d),i.y=I.lerp(i.y,this._temp.y,d),i.z=I.lerp(i.z,this._temp.z,d)}}}}C([f()],tt.prototype,"enabled");C([f()],tt.prototype,"dampen");C([f(H)],tt.prototype,"drag");C([f()],tt.prototype,"dragMultiplier");C([f(H)],tt.prototype,"limit");C([f()],tt.prototype,"limitMultiplier");C([f()],tt.prototype,"separateAxes");C([f(H)],tt.prototype,"limitX");C([f()],tt.prototype,"limitXMultiplier");C([f(H)],tt.prototype,"limitY");C([f()],tt.prototype,"limitYMultiplier");C([f(H)],tt.prototype,"limitZ");C([f()],tt.prototype,"limitZMultiplier");C([f()],tt.prototype,"multiplyDragByParticleSize");C([f()],tt.prototype,"multiplyDragByParticleVelocity");C([f()],tt.prototype,"space");const lh=class $w{enabled;curve;curveMultiplier;mode;clone(){const e=new $w;return e.enabled=this.enabled,e.curve=this.curve?.clone(),e.curveMultiplier=this.curveMultiplier,e.mode=this.mode,e}system;get _lastWorldPosition(){return this.system._iv_lastWorldPosition||(this.system._iv_lastWorldPosition=new c.Vector3),this.system._iv_lastWorldPosition}get _velocity(){return this.system._iv_velocity||(this.system._iv_velocity=new c.Vector3),this.system._iv_velocity}_temp=new c.Vector3;_firstUpdate=!0;awake(e){this.system=e,this.reset()}reset(){this._firstUpdate=!0}update(e){this.enabled&&this.system.worldspace!==!1&&(this._firstUpdate?(this._firstUpdate=!1,this._velocity.set(0,0,0),this._lastWorldPosition.copy(this.system.worldPos)):this._lastWorldPosition&&(this._velocity.copy(this.system.worldPos).sub(this._lastWorldPosition).multiplyScalar(1/this.system.deltaTime),this._lastWorldPosition.copy(this.system.worldPos)))}applyInitial(e){if(this.enabled&&this.system.worldspace!==!1&&this.mode===0){const t=this.curve.evaluate(Math.random(),Math.random());this._temp.copy(this._velocity).multiplyScalar(t),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}_frames=0;applyCurrent(e,t,i){if(this.enabled&&this.system&&this.system.worldspace!==!1&&this.mode===1){const n=this.curve.evaluate(t,i);this._temp.copy(this._velocity).multiplyScalar(n),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}};C([f()],lh.prototype,"enabled");C([f(H)],lh.prototype,"curve");C([f()],lh.prototype,"curveMultiplier");C([f()],lh.prototype,"mode");let cy=lh;class ai{enabled;range;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t,i,n){const o=e.length(),r=I.remap(o,this.range.x,this.range.y,0,1),a=this.size.evaluate(r,i);return n.x*=a,n.y*=a,n.z*=a,n}}C([f()],ai.prototype,"enabled");C([f(c.Vector2)],ai.prototype,"range");C([f()],ai.prototype,"separateAxes");C([f(H)],ai.prototype,"size");C([f()],ai.prototype,"sizeMultiplier");C([f(H)],ai.prototype,"x");C([f()],ai.prototype,"xMultiplier");C([f(H)],ai.prototype,"y");C([f()],ai.prototype,"yMultiplier");C([f(H)],ai.prototype,"z");C([f()],ai.prototype,"zMultiplier");class Ja{enabled;range;color;evaluate(e,t,i){const n=e.length(),o=I.remap(n,this.range.x,this.range.y,0,1),r=this.color.evaluate(o,t);i.x*=r.r,i.y*=r.g,i.z*=r.b,"alpha"in r&&(i.w*=r.alpha)}}C([f()],Ja.prototype,"enabled");C([f(c.Vector2)],Ja.prototype,"range");C([f(Tr)],Ja.prototype,"color");new c.Vector3(1,1,1);new c.Vector3(0,0,1);class hy{constructor(e,t,i,n){this.system=e,this.particleSystem=t,this.subSystem=i,this.subParticleSystem=n,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const o=1e3;this._circularBuffer=new mi(()=>new re.Matrix4,o)}type="NeedleParticleSubEmitter";emitterType;emitterProbability;q_=new c.Quaternion;v_=new c.Vector3;v2_=new c.Vector3;_emitterMatrix=new re.Matrix4;_circularBuffer;clone(){throw new Error("Method not implemented.")}initialize(e){e.emissionState={burstIndex:0,burstWaveIndex:0,time:0,waitEmiting:0},this._emitterMatrix.copy(this.subSystem.matrixWorld).invert().premultiply(this.system.matrixWorld),this._emitterMatrix.setPosition(0,0,0),this.emitterType===rm.Birth&&this.run(e)}update(e,t){this.run(e)}frameUpdate(e){}toJSON(){}reset(){}run(e){if(this.subSystem.currentParticles>=this.subSystem.main.maxParticles||!this.subParticleSystem||!e.emissionState||this.emitterProbability&&Math.random()>this.emitterProbability)return;const t=this.system.deltaTime;if(this.emitterType===rm.Death){let n=e.life;if(e[da]!==void 0&&(n=e[da]),!(e.age+t*1.2>=n))return;const r=this.subSystem.main.maxParticles-this.subSystem.currentParticles;e.emissionState.waitEmiting=r}const i=new re.Matrix4;i.set(1,0,0,e.position.x,0,1,0,e.position.y,0,0,1,e.position.z,0,0,0,1),this.particleSystem.worldSpace||i.multiplyMatrices(this._emitterMatrix,i),this.subParticleSystem.emit(t,e.emissionState,i)}}var Nk=Object.defineProperty,Ae=(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&&Nk(e,t,n),n};const qs=x("debugparticles"),Vk=x("noprogressive"),$k=x("debugprogressive");var rm=(s=>(s[s.Birth=0]="Birth",s[s.Collision=1]="Collision",s[s.Death=2]="Death",s[s.Trigger=3]="Trigger",s[s.Manual=4]="Manual",s))(rm||{});class qi extends E{renderMode;particleMaterial;trailMaterial;particleMesh;maxParticleSize;minParticleSize;velocityScale;cameraVelocityScale;lengthScale;start(){if(this.maxParticleSize!==.5&&this.minParticleSize!==0&&T()){const e=`ParticleSystem "${this.name}" has non-default min/max particle size. This may not render correctly. Please set min size to 0 and the max size to 0.5 and use the "StartSize" setting instead`;console.warn(e)}}get transparent(){return this.particleMaterial?.transparent??!1}getMaterial(e=!1){let t=e===!0&&this.trailMaterial?this.trailMaterial:this.particleMaterial;if(t){if(t.type==="MeshStandardMaterial"){qs&&console.debug("ParticleSystemRenderer.getMaterial: MeshStandardMaterial detected, converting to MeshBasicMaterial. See https://github.com/Alchemist0823/three.quarks/issues/101"),"map"in t&&t.map&&(t.map.colorSpace=c.LinearSRGBColorSpace,t.map.premultiplyAlpha=!1);const i=new c.MeshBasicMaterial;i.copy(t),e?this.trailMaterial=i:this.particleMaterial=i}t.map&&(t.map.colorSpace=c.LinearSRGBColorSpace,t.map.premultiplyAlpha=!1),e&&t.side===c.FrontSide&&(t=t.clone(),t.side=c.BackSide,e?this.trailMaterial=t:this.particleMaterial=t)}return t&&!Vk&&t._didRequestTextureLOD===void 0&&(t._didRequestTextureLOD=0,$k&&console.log("Load material LOD",t.name),se.NEEDLE_progressive.assignTextureLOD(t,0)),t}getMesh(e){let t=null;if(!t&&(this.particleMesh instanceof c.Mesh&&(t=this.particleMesh.geometry),t===null)){t=new c.PlaneGeometry(1,1);const n=t.attributes.uv;for(let o=0;o<n.count;o++)n.setX(o,1-n.getX(o))}return new c.Mesh(t,this.getMaterial())}}Ae([f()],qi.prototype,"renderMode");Ae([f(c.Material)],qi.prototype,"particleMaterial");Ae([f(c.Material)],qi.prototype,"trailMaterial");Ae([f()],qi.prototype,"maxParticleSize");Ae([f()],qi.prototype,"minParticleSize");Ae([f()],qi.prototype,"velocityScale");Ae([f()],qi.prototype,"cameraVelocityScale");Ae([f()],qi.prototype,"lengthScale");class Jh{_curve;_factor;constructor(e,t=1){this._curve=e,this._factor=t}type="function";startGen(e){}genValue(e,t){return this._curve.evaluate(t,Math.random())*this._factor}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}}class dy{type="value";toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}startGen(e){}system;constructor(e){this.system=e}}class Wk extends dy{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class Hk extends dy{_lastPosition=new c.Vector3;_lastDistance=0;update(){const e=Q(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(e),this._lastPosition.copy(e)}genValue(){if(!this.system.isPlaying||!this.system.emission.enabled||this.system.currentParticles>=this.system.maxParticles)return 0;let e=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){const n=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let r=this._lastDistance/this.system.deltaTime*n;Number.isFinite(r)||(r=0),e+=r}const t=this.system.emission.getBurst();t>0&&(e+=t/this.system.deltaTime);const i=this.system.maxParticles-this.system.currentParticles;return I.clamp(e,0,i/this.system.deltaTime)}}class Gk extends dy{genValue(){return this.system.isPlaying,0}}class So{system;get context(){return this.system.context}constructor(e){this.type=Object.getPrototypeOf(this).constructor.name||"ParticleSystemBaseBehaviour",e&&(this.system=e)}type;initialize(e){}update(e,t){}frameUpdate(e){}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}reset(){}}class qk extends So{type="NeedleTextureSheet";update(e,t){const i=this.system.textureSheetAnimation;if(i.enabled){const n=e.age/e.life,o=i.evaluate(n);o!==void 0&&(e.uvTile=o)}}}const ub=Symbol("particleRotation");class Xk extends So{type="NeedleRotation";initialize(e){e[ub]=Math.random()}update(e,t){if(e.rotation===void 0)return;const i=e.age/e.life;if(typeof e.rotation=="number"&&(this.system.rotationOverLifetime.enabled?e.rotation+=this.system.rotationOverLifetime.evaluate(i,e[ub])*t:this.system.renderer.renderMode===is.Billboard&&(e.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const n=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(i,n)*t}}}const fb=Symbol("sizeLerpFactor"),Qk=new c.Vector3;class Yk extends So{type="NeedleSize";_minSize=0;_maxSize=1;initialize(e){e[fb]=Math.random(),this._minSize=this.system.renderer.minParticleSize,this._maxSize=this.system.renderer.maxParticleSize}update(e,t){const i=e.age/e.life;let n=1;this.system.sizeOverLifetime.enabled&&(n*=this.system.sizeOverLifetime.evaluate(i,void 0,e[fb]).x);let o=1;this.system.renderer.renderMode!==is.Mesh&&(o=this.system.worldScale.x/this.system.cameraScale);const r=B(e.startSize).multiplyScalar(n*o);if(e.size.set(r.x,r.y,r.z),this.system.localspace){const a=Ww(this.system,Qk);e.size.x*=a.x,e.size.y*=a.y,e.size.z*=a.z}}}const da=Symbol("particleLife"),sp=Symbol("trailLifetime"),pb=Symbol("trailStartLength"),op=Symbol("trailWidthRandom");class Kk extends So{type="NeedleTrail";initialize(e){e instanceof re.TrailParticle&&(e[da]=e.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(e[sp]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),e.life+=e[sp]),e[pb]=e.length,e[op]=Math.random())}update(e){if(this.system.trails?.enabled&&e instanceof re.TrailParticle){const t=e,i=e.age/e[da],n=e.previous.values(),o=e.previous.length;for(let r=0;r<o;r++){const l=n.next().value,h=1-r/(o-1),d=e.size;if(d.x<=0&&!this.system.trails.sizeAffectsWidth){const u=20*this.system.trails.widthOverTrail.evaluate(.5,t[op]);d.x=u,d.y=u,d.z=u}l.size=this.system.trails.getWidth(d.x,i,h,t[op]),l.color.copy(e.color),this.system.trails.getColor(l.color,i,h)}if(e.age>e[da]){e.velocity.set(0,0,0);const r=(e.age-e[da])/e[sp];t.length=I.lerp(e[pb],0,r)}}}}const ed=Symbol("startVelocity"),mb=Symbol("gravityModifier"),rp=Symbol("gravitySpeed"),td=Symbol("velocity lerp factor"),am=new c.Vector3;class Zk extends So{type="NeedleVelocity";_gravityDirection=new c.Vector3;initialize(e){const t=this.system.main.simulationSpeed;e.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random());const i=this.system.shape.getDirection(e,e.position);e.velocity.x=i.x*e.startSpeed,e.velocity.y=i.y*e.startSpeed,e.velocity.z=i.z*e.startSpeed,this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyInitial(e.velocity),e[ed]?e[ed].copy(e.velocity):e[ed]=e.velocity.clone();const n=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());e[mb]=n*t,e[rp]=n*t*.5,e[td]=Math.random(),this.system.velocityOverLifetime?.init(e),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===Cc.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(e,t){const i=e[ed],n=e[mb];if(n!==0){const u=n*e[rp];am.copy(this._gravityDirection).multiplyScalar(u),e[rp]+=t*.05,i.add(am)}e.velocity.copy(i);const o=e.age/e.life;this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyCurrent(e.velocity,o,e[td]);const r=this.system.noise;r.enabled&&r.apply(0,e.position,e.velocity,t,e.age,e.life);const a=this.system.sizeBySpeed;a?.enabled&&(e.size=a.evaluate(e.velocity,o,e[td],e.size));const l=this.system.colorBySpeed;l?.enabled&&l.evaluate(e.velocity,e[td],e.color);const h=this.system.velocityOverLifetime;h.enabled&&h.apply(e,0,e.position,e.velocity,t,e.age,e.life);const d=this.system.limitVelocityOverLifetime;if(d.enabled&&d.apply(e.position,i,e.velocity,e.size,o,t,1),this.system.worldspace){const u=this.system.worldScale;e.velocity.x*=u.x,e.velocity.y*=u.y,e.velocity.z*=u.z}}}const gb=Symbol("colorLerpFactor"),yb=new ee(1,1,1,1),Io=new ee(1,1,1,1);class Jk extends So{type="NeedleColor";initialize(e){}_init(e){const t=this.system.renderer.particleMaterial;Io.copy(this.system.main.startColor.evaluate(Math.random())),t?.color&&(yb.copy(t.color),Io.multiply(yb)),Io.convertLinearToSRGB(),e.startColor.set(Io.r,Io.g,Io.b,Io.alpha),e.color.copy(e.startColor),e[gb]=Math.random()}update(e,t){if(e.age===0&&this._init(e),this.system.colorOverLifetime.enabled){const i=e.age/e.life,n=this.system.colorOverLifetime.color.evaluate(i,e[gb]);e.color.set(n.r,n.g,n.b,"alpha"in n?n.alpha:1).multiply(e.startColor)}else e.color.copy(e.startColor)}}class eE{system;emission;get anim(){return this.system.textureSheetAnimation}constructor(e){this.system=e,this.emission=new Hk(this.system)}get prewarm(){return!1}get material(){return this.system.renderer.getMaterial(this.system.trails.enabled)}get layers(){return this.system.gameObject.layers}update(){this.emission.update()}autoDestroy;get looping(){return this.system.main.loop}get duration(){return this.system.duration}get shape(){return this.system.shape}get startLife(){return new Jh(this.system.main.startLifetime)}get startSpeed(){return new Jh(this.system.main.startSpeed)}get startRotation(){return new Jh(this.system.main.startRotation)}get startSize(){return new Jh(this.system.main.startSize)}startLength;get startColor(){return new re.ConstantColor(new re.Vector4(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new Gk(this.system)}emissionBursts;onlyUsedByOther;behaviors=[];get instancingGeometry(){return this.system.renderer.getMesh(this.system.renderer.renderMode).geometry}get renderMode(){if(this.system.trails.enabled===!0)return re.RenderMode.Trail;switch(this.system.renderer.renderMode){case is.Billboard:return re.RenderMode.BillBoard;case is.Stretch:return re.RenderMode.StretchedBillBoard;case is.HorizontalBillboard:return re.RenderMode.HorizontalBillBoard;case is.VerticalBillboard:return re.RenderMode.VerticalBillBoard;case is.Mesh:return re.RenderMode.Mesh}return re.RenderMode.BillBoard}rendererEmitterSettings={startLength:new re.ConstantValue(220),followLocalOrigin:!1};get speedFactor(){let e=this.system.main.simulationSpeed;return this.system.renderer?.renderMode===is.Stretch&&(e*=this.system.renderer.velocityScale??1),e}flatWhiteTexture;clonedTexture={original:void 0,clone:void 0};get texture(){const e=this.material;if(e&&e.map){const t=e.map;if(this.clonedTexture.original!==t||!this.clonedTexture.clone){const i=t.clone();i.premultiplyAlpha=!1,i.colorSpace=c.LinearSRGBColorSpace,this.clonedTexture.original=t,this.clonedTexture.clone=i}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=Jm(new ee(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new Wk(this.system)}get uTileCount(){return this.anim.enabled?this.anim?.numTilesX:void 0}get vTileCount(){return this.anim.enabled?this.anim?.numTilesY:void 0}get renderOrder(){return 1}get blending(){return this.system.renderer.particleMaterial?.blending??c.NormalBlending}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===Cc.World}}class tE{burstParticleIndex=0;burstParticleCount=0;isBursting=!1;travelDistance=0;previousWorldPos;burstIndex=0;burstWaveIndex=0;time=0;waitEmiting=0}const Lt=class xd extends E{play(e=!1){e&&S.foreachComponent(this.gameObject,t=>{t instanceof xd&&t!==this&&t.play(!1)},!0),this._isPlaying=!0,this._particleSystem&&(this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1),this.emission?.reset()}pause(e=!0){e&&S.foreachComponent(this.gameObject,t=>{t instanceof xd&&t!==this&&t.pause(!1)},!0),this._isPlaying=!1}stop(e=!0,t=!1){e&&S.foreachComponent(this.gameObject,i=>{i instanceof xd&&i!==this&&i.stop(!1,t)},!0),this._isPlaying=!1,this._time=0,t&&this.reset()}reset(){this._time=0,this._particleSystem&&(this._particleSystem.particleNum=0,this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1,this.emission?.reset())}_state;emit(e){if(this._particleSystem){this.onUpdate(),e=Math.min(e,this.maxParticles-this.currentParticles),this._state||(this._state=new tE),this._state.waitEmiting=e,this._state.time=0;const t=this._particleSystem.emitEnded;this._particleSystem.emitEnded=!1,this._particleSystem.emit(this.deltaTime,this._state,this._particleSystem.emitter.matrixWorld),this._particleSystem.emitEnded=t}}get playOnAwake(){return this.main.playOnAwake}set playOnAwake(e){this.main.playOnAwake=e}colorOverLifetime;main;emission;sizeOverLifetime;shape;noise;trails;velocityOverLifetime;limitVelocityOverLifetime;inheritVelocity;colorBySpeed;textureSheetAnimation;rotationOverLifetime;rotationBySpeed;sizeBySpeed;get renderer(){return this._renderer}get isPlaying(){return this._isPlaying}get currentParticles(){return this._particleSystem?.particleNum??0}get maxParticles(){return this.main.maxParticles}get time(){return this._time}get duration(){return this.main.duration}get deltaTime(){return this.context.time.deltaTime*this.main.simulationSpeed}get scale(){return this.gameObject.scale.x}get cameraScale(){return this._cameraScale}_cameraScale=1;get container(){return this._container}get worldspace(){return this.main.simulationSpace===Cc.World}get localspace(){return this.main.simulationSpace===Cc.Local}__worldQuaternion=new c.Quaternion;get worldQuaternion(){return this.__worldQuaternion}_worldQuaternionInverted=new c.Quaternion;get worldQuaternionInverted(){return this._worldQuaternionInverted}_worldScale=new c.Vector3;get worldScale(){return this._worldScale}_worldPositionFrame=-1;_worldPos=new c.Vector3;get worldPos(){return this._worldPositionFrame!==this.context.time.frame&&(this._worldPositionFrame=this.context.time.frame,Q(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}addBehaviour(e){return this._particleSystem?(e instanceof So&&(e.system=this),qs&&console.debug("Add custom ParticleSystem Behaviour",e),this._particleSystem.addBehavior(e),!0):!1}removeBehaviour(e){if(!this._particleSystem)return!1;const t=this._particleSystem.behaviors,i=t.indexOf(e);return i!==-1&&((T()||qs)&&console.debug("Remove custom ParticleSystem Behaviour",i,e),t.splice(i,1)),!0}removeAllBehaviours(){return this._particleSystem?(this._particleSystem.behaviors.length=0,!0):!1}get behaviours(){return this._particleSystem?this._particleSystem.behaviors:null}get particleSystem(){return this._particleSystem??null}_renderer;_batchSystem;_particleSystem;_interface;_container;_time=0;_isPlaying=!0;_isUsedAsSubsystem=!1;_didPreWarm=!1;set bursts(e){for(let t=0;t<e.length;t++){const i=e[t];if(!(i instanceof Kd)){const n=new Kd;Ra(n,i),e[t]=n}}this._bursts=e}_bursts;set subEmitterSystems(e){for(let t=0;t<e.length;t++){const i=e[t];if(!(i instanceof Zd)){const n=new Zd;Ra(n,i),e[t]=n}}qs&&e.length>0&&console.log("SubEmitters: ",e,this),this._subEmitterSystems=e}_subEmitterSystems;onAfterDeserialize(e){if(this._subEmitterSystems&&Array.isArray(this._subEmitterSystems))for(const t of this._subEmitterSystems)t._deserialize(this.context,this.gameObject)}awake(){if(this._worldPositionFrame=-1,this._renderer=this.gameObject.getComponent(qi),!this.main)throw new Error("Not Supported: ParticleSystem needs a serialized MainModule. Creating new particle systems at runtime is currently not supported.");this._container=new c.Object3D,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new re.BatchedParticleRenderer,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new eE(this),this._particleSystem=new re.ParticleSystem(this._interface),this._particleSystem.addBehavior(new Yk(this)),this._particleSystem.addBehavior(new Jk(this)),this._particleSystem.addBehavior(new qk(this)),this._particleSystem.addBehavior(new Xk(this)),this._particleSystem.addBehavior(new Zk(this)),this._particleSystem.addBehavior(new Kk(this)),this._batchSystem.addSystem(this._particleSystem);const e=this._particleSystem.emitter;this.context.scene.add(e),this.inheritVelocity.system&&this.inheritVelocity.system!==this&&(this.inheritVelocity=this.inheritVelocity.clone()),this.inheritVelocity.awake(this),qs&&(console.log(this),this.gameObject.add(new c.AxesHelper(1)))}start(){this.addSubParticleSystems(),this.updateLayers(),this.renderer.particleMesh instanceof c.Mesh&&this._interface.renderMode==re.RenderMode.Mesh&&se.NEEDLE_progressive.assignMeshLOD(this.renderer.particleMesh,0).then(e=>{e&&this.particleSystem&&this._interface.renderMode==re.RenderMode.Mesh&&(this.particleSystem.instancingGeometry=e)})}onDestroy(){this._container?.removeFromParent(),this._batchSystem?.removeFromParent(),this._particleSystem?.emitter.removeFromParent(),this._particleSystem?.dispose()}onEnable(){this.main&&(this.inheritVelocity&&(this.inheritVelocity.system=this),this._batchSystem&&(this._batchSystem.visible=!0),this.playOnAwake&&this.play(),this._isPlaying=this.playOnAwake)}onDisable(){this._batchSystem&&(this._batchSystem.visible=!1)}onBeforeRender(){this.main&&(this._didPreWarm===!1&&this.main?.prewarm===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){if(!this.emission?.enabled||this.emission.rateOverTime.getMax()<=0)return;const t=1/60,i=this.main.duration,n=this.main.startLifetime.getMax(),r=Math.min(Math.max(i,n)/Math.max(.01,this.main.simulationSpeed),1e3),a=Math.ceil(r/t),l=Date.now();qs&&console.log(`Particles ${this.name} - Prewarm for ${a} frames (${r} sec). Duration: ${i}, Lifetime: ${n}`);for(let h=0;h<a&&!(this.currentParticles>=this.maxParticles);h++){const d=Date.now()-l;if(d>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${d}`);break}this.onUpdate(),this.onSimulate(t)}}_lastBatchesCount=-1;onSimulate(e){if(this._batchSystem){let t=this.context.time.frameCount%60===0;this._lastBatchesCount!==this._batchSystem.batches.length&&(this._lastBatchesCount=this._batchSystem.batches.length,t=!0),t&&this.updateLayers(),this._batchSystem.update(e)}this._time+=e,this._time>this.duration&&(this._time=0)}updateLayers(){if(this._batchSystem)for(let e=0;e<this._batchSystem.batches.length;e++){const t=this._batchSystem.batches[e];t.layers.disableAll();const i=this.layer;t.layers.mask=1<<i}}onUpdate(){if(this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const e=this.context.mainCamera;if(e){const n=Le(e);this._cameraScale=n.x}const t=!this.worldspace,i=this.gameObject;if(fe(i,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),Le(this.gameObject,this._worldScale),t&&this._container&&this.gameObject?.parent){const n=Ww(this,am);this._container.matrix.makeScale(n.x,n.y,n.z),this._container.matrix.makeRotationFromQuaternion(this.__worldQuaternion),this._container.matrix.setPosition(this.worldPos),this._container.matrix.scale(this.gameObject.scale)}this.emission.system=this,this._interface.update(),this.shape.onUpdate(this,this.context,this.main.simulationSpace,this.gameObject),this.noise.update(this.context),this.inheritVelocity?.update(this.context),this.velocityOverLifetime.update(this)}addSubParticleSystems(){if(this._subEmitterSystems&&this._particleSystem)for(const e of this._subEmitterSystems){e.particleSystem&&(e.particleSystem.__internalAwake?e.particleSystem.__internalAwake():T()&&console.warn("SubParticleSystem serialization issue(?)",e.particleSystem,e));const t=e.particleSystem?._particleSystem;if(t){e.particleSystem._isUsedAsSubsystem=!0;const i=new hy(this,this._particleSystem,e.particleSystem,t);i.emitterType=e.type,i.emitterProbability=e.emitProbability,this._particleSystem.addBehavior(i)}else qs&&console.warn("Could not add SubParticleSystem",e,this)}}};Ae([f(Fu)],Lt.prototype,"colorOverLifetime");Ae([f(At)],Lt.prototype,"main");Ae([f(Cs)],Lt.prototype,"emission");Ae([f(Ar)],Lt.prototype,"sizeOverLifetime");Ae([f(ly)],Lt.prototype,"shape");Ae([f(pe)],Lt.prototype,"noise");Ae([f(Te)],Lt.prototype,"trails");Ae([f(Ie)],Lt.prototype,"velocityOverLifetime");Ae([f(tt)],Lt.prototype,"limitVelocityOverLifetime");Ae([f(cy)],Lt.prototype,"inheritVelocity");Ae([f(Ja)],Lt.prototype,"colorBySpeed");Ae([f(Dt)],Lt.prototype,"textureSheetAnimation");Ae([f(mn)],Lt.prototype,"rotationOverLifetime");Ae([f(Gi)],Lt.prototype,"rotationBySpeed");Ae([f(ai)],Lt.prototype,"sizeBySpeed");let Pc=Lt;class Zd{particleSystem;emitProbability=1;properties;type;_deserialize(e,t){const i=this.particleSystem;if(i instanceof Pc)return;let n="";i&&typeof i.guid=="string"&&(n=i.guid,this.particleSystem=S.findByGuid(n,t)),qs&&!(this.particleSystem instanceof Pc)&&console.warn("Could not find particle system for sub emitter",n,t,this)}}function Ww(s,e){if(e.set(1,1,1),s.gameObject.parent&&s.localspace)switch(s.main.scalingMode){case om.Local:e=Le(s.gameObject.parent,e),e.x=1/e.x,e.y=1/e.y,e.z=1/e.z;break;default:if(!s.unsupported_scaling_mode){s.unsupported_scaling_mode=!0;const t="ParticleSystem scale mode "+om[s.main.scalingMode]+" is not supported";T()&&ue(t),console.warn(t,s.name,s)}e=Le(s.gameObject,e);break}return e}var iE=Object.defineProperty,uy=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&iE(e,t,n),n};class el extends E{strength=1;radius=2;targets=[];update(){const e=this.gameObject.worldPosition,t=-this.strength*this.context.time.deltaTime;this.targets?.forEach(i=>{if(!i)return;const n=i.gameObject.worldPosition.sub(e),o=n.length();if(o>this.radius)return;let r=t;o>1?r/=o*o:r/=Math.max(.05,o),i.applyImpulse(n.multiplyScalar(r))})}}uy([f()],el.prototype,"strength");uy([f()],el.prototype,"radius");uy([f(Fe)],el.prototype,"targets");class La extends E{_didAssignPlayerColor=!1;onEnable(){this.context.connection.beginListen(Y.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(Y.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield Zm(.2),!this.tryAssignColor()););}tryAssignColor=()=>{const e=S.getComponentInParent(this.gameObject,Ui);if(e&&e.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(e.owner),!0;const t=S.getComponentInParent(this.gameObject,Pe);return t?.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(t.connectionId),!0):!1};assignUserColor(e){const t=La.hashCode(e),i=La.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){const n=this.gameObject;this.assignColor(i,e,n)}else if(this.gameObject.children)for(const n of this.gameObject.children){const o=n;o.material&&o.material.color&&this.assignColor(i,e,o)}}assignColor(e,t,i){let n=i.material;n&&(n._playerMaterial!==t&&(n=n.clone(),n._playerMaterial=t,i.material=n),n.color=e)}static hashCode(e){var t=0,i,n;if(e.length===0)return t;for(i=0;i<e.length;i++)n=e.charCodeAt(i),t=(t<<5)-t+n,t|=0;return t}static colorFromHashCode(e){const t=(e&16711680)>>16,i=(e&65280)>>8,n=e&255;return new c.Color(t/255,i/255,n/255)}}const Hl=x("debugpost");let lm=null;function nE(s){lm=s}function Hw(s){let e=s.gameObject;for(;e;){for(const t of du(e))if(t.isPostProcessingManager===!0)return t;e=e.parent}return null}function sE(s){let e=Hw(s);if(!e)if(lm){Hl&&console.warn("Adding postprocessing manager to the scene.");const t=s.scene;e=on(t,lm)}else T()&&console.warn("No post processing manager found");return e}const Ze={AT_START:-1e4,NormalPass:0,DepthDownsamplingPass:10,SSAO:20,SMAA:30,TiltShift:40,DepthOfField:50,ChromaticAberration:60,Bloom:70,Vignette:80,Pixelation:90,ToneMapping:100,HueSaturation:110,BrightnessContrast:120,Sharpening:130,AT_END:1e4};let Ve=null;function oE(s){Hl==="verbose"&&console.debug("Before ordering effects",[...s]),Ve||(Ve=new Map,Ve.set(exports.MODULES.POSTPROCESSING.MODULE.NormalPass,Ze.NormalPass),Ve.set(exports.MODULES.POSTPROCESSING.MODULE.DepthDownsamplingPass,Ze.DepthDownsamplingPass),Ve.set(exports.MODULES.POSTPROCESSING.MODULE.SMAAEffect,Ze.SMAA),Ve.set(exports.MODULES.POSTPROCESSING.MODULE.SSAOEffect,Ze.SSAO),Ve.set(exports.MODULES.POSTPROCESSING_AO.MODULE.N8AOPostPass,Ze.SSAO),Ve.set(exports.MODULES.POSTPROCESSING_AO.MODULE.N8AOPass,Ze.SSAO),Ve.set(exports.MODULES.POSTPROCESSING.MODULE.TiltShiftEffect,Ze.TiltShift),Ve.set(exports.MODULES.POSTPROCESSING.MODULE.DepthOfFieldEffect,Ze.DepthOfField),Ve.set(exports.MODULES.POSTPROCESSING.MODULE.ChromaticAberrationEffect,Ze.ChromaticAberration),Ve.set(exports.MODULES.POSTPROCESSING.MODULE.BloomEffect,Ze.Bloom),Ve.set(exports.MODULES.POSTPROCESSING.MODULE.SelectiveBloomEffect,Ze.Bloom),Ve.set(exports.MODULES.POSTPROCESSING.MODULE.VignetteEffect,Ze.Vignette),Ve.set(exports.MODULES.POSTPROCESSING.MODULE.PixelationEffect,Ze.Pixelation),Ve.set(exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect,Ze.ToneMapping),Ve.set(exports.MODULES.POSTPROCESSING.MODULE.HueSaturationEffect,Ze.HueSaturation),Ve.set(exports.MODULES.POSTPROCESSING.MODULE.BrightnessContrastEffect,Ze.BrightnessContrast)),s.sort((e,t)=>{const i=typeof e.priority=="number"?e.priority:Ve.get(e.effect.constructor)??Number.NEGATIVE_INFINITY,n=typeof t.priority=="number"?t.priority:Ve.get(t.effect.constructor)??Number.NEGATIVE_INFINITY;return i===Number.NEGATIVE_INFINITY?(Hl&&console.warn("Unknown effect found: ",e.constructor.name,e),1):n===Number.NEGATIVE_INFINITY?(Hl&&console.warn("Unknown effect found: ",t.constructor.name,t),-1):i-n}),Hl==="verbose"&&console.debug("After ordering effects",[...s])}var rE=Object.defineProperty,aE=Object.getOwnPropertyDescriptor,Gw=(s,e,t,i)=>{for(var n=aE(e,t),o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&rE(e,t,n),n};const lE=x("debugpost");class F{isVolumeParameter=!0;constructor(e){e!==void 0&&this.initialize(e)}_isInitialized=!1;get isInitialized(){return this._isInitialized}initialize(e){e!==void 0&&(this._value=e,this._defaultValue=e,this._valueRaw=e,this._isInitialized=!0)}get overrideState(){return this._active}set overrideState(e){if(this._active===e)return;this._active=e;const t=e?this._valueRaw:this._defaultValue;this.processValue(t,!0)}_active=!0;get value(){return this._valueRaw}set value(e){this.isInitialized||this.initialize(e),this.processValue(e,!1)}_value;_valueRaw;set defaultValue(e){this._defaultValue=e}_defaultValue=void 0;__init(){this.processValue(this._valueRaw,!0)}valueProcessor;onValueChanged;processValue(e,t){if(e==null||!t&&this.testIfValueChanged(e)===!1)return;const i=this._value;lE&&typeof i=="number"&&typeof e=="number"&&(i?.toFixed(4),e?.toFixed(4)),!this._active&&this._defaultValue!==void 0?(this._value=this._defaultValue,e=this._defaultValue,this._valueRaw=e):(this._valueRaw=e,this._active&&this.valueProcessor&&(e=this.valueProcessor(e)),this._value=e),this.onValueChanged&&this.onValueChanged(e,i,this)}testIfValueChanged(e){return this._valueRaw!==e}}Gw([f()],F.prototype,"overrideState");Gw([f()],F.prototype,"value");class cE extends $i{constructor(){super([F])}onSerialize(e,t){}onDeserialize(e,t){const i=t.target,n=t.path;let o;if(i&&n&&(o=i[n]),(typeof o!="object"||typeof o=="object"&&o.isVolumeParameter!==!0)&&(o=new F),typeof e=="object"&&"value"in e){const r=e.value;o.initialize(r),o.overrideState=e.overrideState}else o.value=e;return o}}new cE;var hE=Object.defineProperty,dE=(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&&hE(e,t,n),n};const ap=x("debugpost");class Ge extends E{get isPostProcessingEffect(){return!0}order=void 0;constructor(e=void 0){if(super(),e)for(const t of Object.keys(e)){const i=e[t],n=this[t];n instanceof F?n.initialize(i):n!==void 0&&(this[t]=i)}}active=!0;_manager=null;onEnable(){super.onEnable(),ap&&console.warn("Enable",this.constructor.name+(this.__internalDidAwakeAndStart?"":" (awake)")),this.__internalDidAwakeAndStart&&(this.active=!0),this.onEffectEnabled()}onDisable(){super.onDisable(),ap&&console.warn("Disable",this.constructor.name),this._manager?.removeEffect(this),this.active=!1}onEffectEnabled(e){e&&e.isPostProcessingManager===!0?this._manager=e:this._manager||(this._manager=sE(this)),this._manager.addEffect(this),this._manager.dirty=!0}init(){}_result;_postprocessingContext=null;get postprocessingContext(){return this._postprocessingContext}apply(e){return this._postprocessingContext=e,this._result||(this.initParameters(),this._result=this.onCreateEffect?.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){ap&&console.warn("DISPOSE",this),this._result&&(Array.isArray(this._result)?this._result.forEach(e=>e.dispose()):this._result.dispose()),this._result=void 0}initParameters(){const e=Object.keys(this);for(const t of e){const i=this[t];i instanceof F&&i.__init()}}onEditorModification(e){const t=e.propertyName;if(this[t]instanceof F){const i=e.value;return this[t].value=i,!0}}}dE([f()],Ge.prototype,"active");var uE=Object.defineProperty,fE=(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&&uE(e,t,n),n};const pE=x("debugpost"),cm={};function Xi(s,e){cm[s]=e}function mE(s){return s.__type in cm?cm[s.__type]:(pE&&s.__type&&console.warn("Unknown postprocessing type",s.__type,s),Ge)}class zu{components=[];__init(e){this.components?.forEach(t=>{t.gameObject===void 0&&e.gameObject.addComponent(t),t.init()})}addEffect(e){this.components.push(e)}removeEffect(e){const t=this.components.indexOf(e);t>=0&&this.components.splice(t,1)}}fE([ze([s=>mE(s),Ge])],zu.prototype,"components");var gE=Object.defineProperty,yE=(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&&gE(e,t,n),n};const _E=x("debugpost");class ch extends Ge{get typeName(){return"Antialiasing"}preset=new F(2);onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.SMAAEffect({preset:this.preset?.value??exports.MODULES.POSTPROCESSING.MODULE.SMAAPreset.HIGH,edgeDetectionMode:exports.MODULES.POSTPROCESSING.MODULE.EdgeDetectionMode.LUMA});return this.preset.onValueChanged=t=>{_E&&console.log("Antialiasing preset changed to",t),e.applyPreset(t)},e}}yE([f(F)],ch.prototype,"preset");Xi("Antialiasing",ch);var bE=Object.defineProperty,fy=(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&&bE(e,t,n),n};const Nu=class qw extends Ge{static useSelectiveBloom=!1;get typeName(){return"Bloom"}threshold=new F(.9);intensity=new F(1);scatter=new F(.7);selectiveBloom;init(){this.threshold.valueProcessor=e=>e,this.intensity.valueProcessor=e=>e,this.scatter.valueProcessor=e=>e}onCreateEffect(){let e;if(this.selectiveBloom==null&&(this.selectiveBloom=qw.useSelectiveBloom),this.selectiveBloom){const t=e=new exports.MODULES.POSTPROCESSING.MODULE.SelectiveBloomEffect(this.context.scene,this.context.mainCamera,{blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});t.inverted=!0}else e=new exports.MODULES.POSTPROCESSING.MODULE.BloomEffect({blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});return this.intensity.onValueChanged=t=>{e.intensity=t},this.threshold.onValueChanged=t=>{e.luminanceMaterial.threshold=Math.pow(t,2.2)},this.scatter.onValueChanged=t=>{e.luminancePass.enabled=!0,e.luminanceMaterial.smoothing=t,e.mipmapBlurPass&&(e.mipmapBlurPass.radius=c.MathUtils.lerp(.1,.9,t))},e}};fy([f(F)],Nu.prototype,"threshold");fy([f(F)],Nu.prototype,"intensity");fy([f(F)],Nu.prototype,"scatter");let Vu=Nu;Xi("Bloom",Vu);var vE=Object.defineProperty,wE=(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&&vE(e,t,n),n};class hh extends Ge{get typeName(){return"ChromaticAberration"}intensity=new F(0);onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.ChromaticAberrationEffect;return e.offset=new c.Vector2(0,0),e.radialModulation=!0,e.modulationOffset=.15,this.intensity.valueProcessor=t=>t*.02,this.intensity.onValueChanged=t=>{e.offset.x=-t,e.offset.y=t},e}}wE([f(F)],hh.prototype,"intensity");Xi("ChromaticAberration",hh);var Gl=(s=>(s[s.None=0]="None",s[s.Neutral=1]="Neutral",s[s.ACES=2]="ACES",s[s.AgX=3]="AgX",s[s.KhronosNeutral=4]="KhronosNeutral",s))(Gl||{});const _b=new Map;function lp(s){switch(s){case 0:return c.LinearToneMapping;case 1:return c.ReinhardToneMapping;case 2:return c.ACESFilmicToneMapping;case 3:return c.AgXToneMapping;case 4:return c.NeutralToneMapping;default:return _b.has(s)||(_b.set(s,!0),console.warn("[Postprocessing] Unknown tone mapping mode",s)),c.NeutralToneMapping}}function xE(s){switch(s){case c.LinearToneMapping:return 0;case c.ACESFilmicToneMapping:return 2;case c.AgXToneMapping:return 3;case c.NeutralToneMapping:return 1;case c.ReinhardToneMapping:return 1;default:return 0}}function Sd(s){switch(s){case c.LinearToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR;case c.ACESFilmicToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.ACES_FILMIC;case c.AgXToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.AGX;case c.NeutralToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.NEUTRAL;case c.ReinhardToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.REINHARD;default:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR}}var SE=Object.defineProperty,Xw=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&SE(e,t,n),n};const cp=x("debugpost");class co extends Ge{get typeName(){return"ToneMapping"}mode=new F(void 0);exposure=new F(1);setMode(e){const t=Gl[e];return t===void 0?(console.error("[PostProcessing] Invalid ToneMapping mode",e),this):(this.mode.value=t,this)}get isToneMapping(){return!0}onEffectEnabled(){const e=Hw(this);e&&super.onEffectEnabled(e)}_tonemappingEffect=null;onCreateEffect(){if(this.mode.isInitialized==!1){const i=xE(this.context.renderer.toneMapping);cp&&console.log("[PostProcessing] Initializing ToneMapping mode to renderer.toneMapping",this.context.renderer.toneMapping+" → "+i),this.mode.initialize(i)}this._tonemappingEffect?.dispose();const e=lp(this.mode.value),t=this._tonemappingEffect=new exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect({mode:Sd(e)});return this.mode.onValueChanged=i=>{if(typeof i=="string")i=S0(i),t.mode=Sd(i);else{const n=lp(i);t.mode=Sd(n)}t.name="ToneMapping ("+Gl[i]+")",cp&&console.log("[PostProcessing] ToneMapping mode changed to",Gl[i],e,t.mode)},cp&&console.log("[PostProcessing] Use ToneMapping",Gl[this.mode.value],e,t.mode,"renderer.tonemapping: "+this.context.renderer.toneMapping),t}onBeforeRender(){if(this._tonemappingEffect&&this.postprocessingContext?.handler.getEffectIsActive(this._tonemappingEffect)&&(this.mode.overrideState&&(this.context.renderer.toneMapping=lp(this.mode.value)),this.exposure.overrideState&&this.exposure.value!==void 0)){const e=Math.max(0,this.exposure.value);this.context.renderer.toneMappingExposure=e}}}Xw([f(F)],co.prototype,"mode");Xw([f(F)],co.prototype,"exposure");Xi("Tonemapping",co);var CE=Object.defineProperty,$u=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&CE(e,t,n),n};class Co extends Ge{get typeName(){return"ColorAdjustments"}remap=!0;postExposure=new F(1);contrast=new F(0);hueShift=new F(0);saturation=new F(0);init(){this.postExposure.valueProcessor=e=>(this.remap&&(e=Math.pow(2,e)),e),this.contrast.valueProcessor=e=>{if(!this.remap)return e;let t=1;return e>0?t=200:e<0&&(t=100),e/t},this.contrast.defaultValue=0,this.hueShift.valueProcessor=e=>this.remap?Math.PI*e/180:e,this.hueShift.defaultValue=0,this.saturation.valueProcessor=e=>this.remap?e<0?e/100:e/(100*Math.PI):e,this.saturation.defaultValue=0}onCreateEffect(){const e=[];let t=this.postprocessingContext?.components.find(o=>o instanceof co);t||(t=new co,this.postprocessingContext?.components.push(t)),this.postExposure.onValueChanged=o=>{this.postExposure.overrideState&&t?t.exposure.value=o:console.warn("[PostProcessing] PostExposure is set to override but no ToneMappingEffect found in the postprocessing stack. Please add a ToneMappingEffect to your postprocessing stack to use PostExposure.")};const i=new exports.MODULES.POSTPROCESSING.MODULE.BrightnessContrastEffect;this.contrast.onValueChanged=o=>i.contrast=o;const n=new exports.MODULES.POSTPROCESSING.MODULE.HueSaturationEffect;return this.hueShift.onValueChanged=o=>n.hue=o,this.saturation.onValueChanged=o=>n.saturation=o,e.push(i),e.push(n),e}}$u([f(F)],Co.prototype,"postExposure");$u([f(F)],Co.prototype,"contrast");$u([f(F)],Co.prototype,"hueShift");$u([f(F)],Co.prototype,"saturation");Xi("ColorAdjustments",Co);var PE=Object.defineProperty,Dr=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&PE(e,t,n),n};const ME=x("debugpost");class gn extends Ge{get typeName(){return"DepthOfField"}mode;focusDistance=new F(1);focalLength=new F(.2);aperture=new F(20);gaussianMaxRadius=new F;resolutionScale=new F(1/window.devicePixelRatio);bokehScale=new F;init(){this.focalLength.valueProcessor=t=>{const i=t/300;return I.lerp(2,.01,i)};const e=20;this.aperture.valueProcessor=t=>{const i=1-t/32;return I.lerp(1,e,i)}}onCreateEffect(){if(this.mode===0){ME&&console.warn("DepthOfField: Mode is set to Off");return}const e=new exports.MODULES.POSTPROCESSING.MODULE.DepthOfFieldEffect(this.context.mainCamera,{worldFocusRange:.2,focalLength:1,bokehScale:20,resolutionScale:this.resolutionScale.value});return this.focusDistance.onValueChanged=t=>{e.cocMaterial.worldFocusDistance=t},this.focalLength.onValueChanged=t=>e.cocMaterial.worldFocusRange=t,this.aperture.onValueChanged=t=>e.bokehScale=t,this.resolutionScale&&(this.resolutionScale.onValueChanged=t=>e.resolution.scale=t),[e]}unapply(){}}Dr([f()],gn.prototype,"mode");Dr([f(F)],gn.prototype,"focusDistance");Dr([f(F)],gn.prototype,"focalLength");Dr([f(F)],gn.prototype,"aperture");Dr([f(F)],gn.prototype,"gaussianMaxRadius");Dr([f(F)],gn.prototype,"resolutionScale");Dr([f(F)],gn.prototype,"bokehScale");Xi("DepthOfField",gn);class Mc extends Ge{effect;constructor(e){super(),this.effect=e}get typeName(){return this.effect.constructor.name}onCreateEffect(){return this.effect}}var OE=Object.defineProperty,kE=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&OE(e,t,n),n};class dh extends Ge{get typeName(){return"PixelationEffect"}granularity=new F(10);onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.PixelationEffect;return this.granularity.onValueChanged=t=>{e.granularity=t},e}}kE([f(F)],dh.prototype,"granularity");Xi("PixelationEffect",dh);var EE=Object.defineProperty,uh=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&EE(e,t,n),n};class Ps extends Ge{get typeName(){return"ScreenSpaceAmbientOcclusion"}intensity=new F(2);falloff=new F(1);samples=new F(9);color=new F(new c.Color(0,0,0));luminanceInfluence=new F(.7);onBeforeRender(){if(this._ssao&&this.context.mainCamera instanceof c.PerspectiveCamera){const e=this.context.mainCamera.far-this.context.mainCamera.near;this._ssao.ssaoMaterial.worldDistanceFalloff=e*.01,this._ssao.ssaoMaterial.worldDistanceThreshold=this.context.mainCamera.far}}_ssao;onCreateEffect(){const e=this.context.mainCamera,t=new exports.MODULES.POSTPROCESSING.MODULE.NormalPass(this.context.scene,e),i=new exports.MODULES.POSTPROCESSING.MODULE.DepthDownsamplingPass({normalBuffer:t.texture,resolutionScale:.5}),n=this._ssao=new exports.MODULES.POSTPROCESSING.MODULE.SSAOEffect(e,t.texture,{normalDepthBuffer:i.texture,worldDistanceThreshold:1,worldDistanceFalloff:1,worldProximityThreshold:.1,worldProximityFalloff:2,intensity:1,blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.MULTIPLY,luminanceInfluence:.5});this.intensity.onValueChanged=r=>{n.intensity=r},this.falloff.onValueChanged=r=>{n.ssaoMaterial.radius=r*.1},this.samples.onValueChanged=r=>{n.ssaoMaterial.samples=r},this.color.onValueChanged=r=>{n.color||(n.color=new c.Color),n.color.copy(r)},this.luminanceInfluence.onValueChanged=r=>{n.luminanceInfluence=r};const o=new Array;return o.push(t),o.push(i),o.push(n),o}}uh([f(F)],Ps.prototype,"intensity");uh([f(F)],Ps.prototype,"falloff");uh([f(F)],Ps.prototype,"samples");uh([f(F)],Ps.prototype,"color");uh([f(F)],Ps.prototype,"luminanceInfluence");Xi("ScreenSpaceAmbientOcclusion",Ps);var RE=Object.defineProperty,Lr=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&RE(e,t,n),n};const TE=x("debugN8AO");var hm=(s=>(s[s.Performance=0]="Performance",s[s.Low=1]="Low",s[s.Medium=2]="Medium",s[s.High=3]="High",s[s.Ultra=4]="Ultra",s))(hm||{});class yn extends Ge{get typeName(){return"ScreenSpaceAmbientOcclusionN8"}get pass(){return this._ssao}gammaCorrection=!0;aoRadius=new F(1);falloff=new F(1);intensity=new F(1);color=new F(new c.Color(0,0,0));screenspaceRadius=!1;quality=2;_ssao;onValidate(){this._ssao&&(this._ssao.setQualityMode(hm[this.quality]),this._ssao.configuration.gammaCorrection=this.gammaCorrection,this._ssao.configuration.screenSpaceRadius=this.screenspaceRadius)}onCreateEffect(){const e=this.context.mainCamera,t=this.context.domWidth,i=this.context.domHeight,n=this._ssao=new exports.MODULES.POSTPROCESSING_AO.MODULE.N8AOPostPass(this.context.scene,e,t,i);n.name="SSAO_N8";const o=hm[this.quality];n.setQualityMode(o),n.configuration.transparencyAware=!1;const r=new c.WebGLRenderTarget(t,i);return n.configuration.beautyRenderTarget=r,n.configuration.autoRenderBeauty=!1,n.configuration.gammaCorrection=this.gammaCorrection,n.configuration.screenSpaceRadius=this.screenspaceRadius,TE&&(n.enableDebugMode(),console.log(n),setInterval(()=>{console.log("SSAO",n.lastTime)},1e3),setInterval(()=>{console.log("SSAO",n.enabled,{ssao:n,autoRenderBeauty:n.configuration.autoRenderBeauty})},4e3)),this.intensity.onValueChanged=a=>{n.configuration.intensity=a},this.falloff.onValueChanged=a=>{n.configuration.distanceFalloff=a},this.aoRadius.onValueChanged=a=>{n.configuration.aoRadius=a},this.color.onValueChanged=a=>{n.color||(n.color=new c.Color),n.configuration.color.copy(a)},n}}Lr([vt(),f()],yn.prototype,"gammaCorrection");Lr([f(F)],yn.prototype,"aoRadius");Lr([f(F)],yn.prototype,"falloff");Lr([f(F)],yn.prototype,"intensity");Lr([f(F)],yn.prototype,"color");Lr([vt(),f()],yn.prototype,"screenspaceRadius");Lr([vt(),f()],yn.prototype,"quality");Xi("ScreenSpaceAmbientOcclusionN8",yn);var AE=Object.defineProperty,DE=Object.getOwnPropertyDescriptor,Qw=(s,e,t,i)=>{for(var n=DE(e,t),o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&AE(e,t,n),n};class fh extends Ge{get typeName(){return"Sharpening"}order=Ze.Sharpening;_effect;onCreateEffect(){return this._effect??=new(LE()),this.effect}get effect(){return this._effect}set amount(e){this._amount=e,this._effect&&(this._effect.uniforms.get("amount").value=e)}get amount(){return this._effect?this._effect.uniforms.get("amount").value:this._amount}_amount=1;set radius(e){this._radius=e,this._effect&&(this._effect.uniforms.get("radius").value=e)}get radius(){return this._effect?this._effect.uniforms.get("radius").value:this._radius}_radius=1}Qw([f()],fh.prototype,"amount");Qw([f()],fh.prototype,"radius");function LE(){const s=`
|
|
1313
1313
|
void mainSupport() {
|
|
1314
1314
|
vUv = uv;
|
|
1315
1315
|
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
|
|
@@ -1353,14 +1353,14 @@ axisFormat %s
|
|
|
1353
1353
|
outputColor = sharp;
|
|
1354
1354
|
}
|
|
1355
1355
|
|
|
1356
|
-
`;class t extends exports.MODULES.POSTPROCESSING.MODULE.Effect{constructor(){super("Sharpening",e,{vertexShader:s,blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.NORMAL,uniforms:new Map([["amount",new c.Uniform$1(1)],["radius",new c.Uniform$1(1)]]),attributes:Ox.EffectAttribute.CONVOLUTION})}}return t}var IE=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&&IE(e,t,n),n};class qn extends
|
|
1357
|
-
- If you create custom effect try creating it like this: 'new NEEDLE_ENGINE_MODULES.POSTPROCESSING.MODULE.Effect(...)' instead of 'new Effect(...)'`),!0):!1};if(!e.mainCameraComponent){console.error("No camera in scene found or available yet - can not create postprocessing effects");return}const a=o.apply(i);if(!a)continue;const l=o.typeName||o.constructor.name;if(Array.isArray(a))for(const h of a)r(l,h)&&this._effects.push({effect:h,typeName:o.typeName,priority:o.order});else{if(!r(l,a))continue;this._effects.push({effect:a,typeName:o.typeName,priority:o.order})}}}else o.active&&ue("Volume component is not a VolumeComponent: "+o.__type)}this.applyEffects(e)}_anyPassHasDepth=!1;_anyPassHasNormal=!1;_hasSmaaEffect=!1;get anyPassHasDepth(){return this._anyPassHasDepth}get anyPassHasNormal(){return this._anyPassHasNormal}get hasSmaaEffect(){return this._hasSmaaEffect}_customInputBuffer=null;_customInputBufferId=0;_multisampling=0;set multisampling(e){this._multisampling=e}get multisampling(){return this._multisampling}applyEffects(e){if(this._anyPassHasDepth=!1,this._anyPassHasNormal=!1,this._hasSmaaEffect=!1,this._effects.length<=0)return;const t=e.mainCameraComponent,i=e.renderer,n=e.scene,o=t.threeCamera;if(typeof i[wl]=="boolean"&&(i.autoClear=i[wl]),i[wl]=i.autoClear,typeof i[xl]=="number"&&(i.toneMapping=i[xl]),i[xl]=i.toneMapping,i.toneMapping!=c.NoToneMapping&&!this._effects.find(d=>d instanceof exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect)){const d=new exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect;d.name=`ToneMapping (${i.toneMapping})`,d.mode=Sd(i.toneMapping),this._effects.push({typeName:"ToneMapping",effect:d,priority:
|
|
1356
|
+
`;class t extends exports.MODULES.POSTPROCESSING.MODULE.Effect{constructor(){super("Sharpening",e,{vertexShader:s,blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.NORMAL,uniforms:new Map([["amount",new c.Uniform$1(1)],["radius",new c.Uniform$1(1)]]),attributes:Ox.EffectAttribute.CONVOLUTION})}}return t}var IE=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&&IE(e,t,n),n};class qn extends Ge{get typeName(){return"TiltShiftEffect"}offset=new F(0);rotation=new F(0);focusArea=new F(.4);feather=new F(.3);kernelSize=new F(2);resolutionScale=new F(1/window.devicePixelRatio);init(){this.offset.defaultValue=0,this.rotation.defaultValue=0,this.focusArea.defaultValue=.4,this.feather.defaultValue=.3,this.kernelSize.defaultValue=exports.MODULES.POSTPROCESSING.MODULE.KernelSize.MEDIUM,this.resolutionScale.defaultValue=1/window.devicePixelRatio}onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.TiltShiftEffect({kernelSize:exports.MODULES.POSTPROCESSING.MODULE.KernelSize.VERY_LARGE,offset:this.offset.value,rotation:this.rotation.value,focusArea:this.focusArea.value,feather:this.feather.value});return this.offset.onValueChanged=t=>e.offset=t,this.rotation.onValueChanged=t=>e.rotation=t,this.focusArea.onValueChanged=t=>e.focusArea=t,this.feather.onValueChanged=t=>e.feather=t,this.kernelSize.onValueChanged=t=>e.blurPass.kernelSize=t,this.resolutionScale.onValueChanged=t=>e.resolution.scale=t/window.devicePixelRatio,e}}tl([f(F)],qn.prototype,"offset");tl([f(F)],qn.prototype,"rotation");tl([f(F)],qn.prototype,"focusArea");tl([f(F)],qn.prototype,"feather");tl([f(F)],qn.prototype,"kernelSize");tl([f(F)],qn.prototype,"resolutionScale");Xi("TiltShiftEffect",qn);var jE=Object.defineProperty,py=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&jE(e,t,n),n};class Ir extends Ge{get typeName(){return"Vignette"}color=new F({r:0,g:0,b:0,a:1});intensity=new F(0);center=new F({x:.5,y:.5});init(){this.color.defaultValue={r:0,g:0,b:0,a:1},this.intensity.defaultValue=0,this.center.defaultValue={x:.5,y:.5}}onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.VignetteEffect;return this.intensity.onValueChanged=t=>{e.offset=t,this.updateDarkness(e)},this.color.onValueChanged=t=>{this.updateDarkness(e)},e}updateDarkness(e){const t=this.intensity.value;e.darkness=t}}py([f(F)],Ir.prototype,"color");py([f(F)],Ir.prototype,"intensity");py([f(F)],Ir.prototype,"center");Xi("Vignette",Ir);globalThis.NEEDLE_USE_POSTPROCESSING=globalThis.NEEDLE_USE_POSTPROCESSING!==void 0?globalThis.NEEDLE_USE_POSTPROCESSING:!0;const Yn=x("debugpost"),hp=Symbol("needle:postprocessing-handler"),wl=Symbol("needle:previous-autoclear-state"),xl=Symbol("needle:previous-tone-mapping");class my{_composer=null;_lastVolumeComponents;_effects=[];getEffectIsActive(e){return e?this._isActive&&this._effects.some(t=>t.effect===e):!1}get isActive(){return this._isActive}get composer(){return this._composer}_isActive=!1;context;constructor(e){this.context=e}apply(e){return this._isActive=!0,this.onApply(this.context,e)}unapply(e=!0){if(Yn&&console.log("Unapplying postprocessing effects"),this._isActive=!1,this._lastVolumeComponents){for(const n of this._lastVolumeComponents)n.unapply();this._lastVolumeComponents.length=0}const t=this.context;t[hp]===this&&(delete t[hp],typeof t.renderer[wl]=="boolean"&&(t.renderer.autoClear=t.renderer[wl]),typeof t.renderer[xl]=="number"&&(t.renderer.toneMapping=t.renderer[xl])),this._composer?.removeAllPasses(),e&&this._composer?.dispose(),t.composer===this._composer&&(t.composer=null),this.handleDevicePixelRatio()}dispose(){this.unapply(!0);for(const e of this._effects)e.effect.dispose();this._effects.length=0,this._composer=null}async onApply(e,t){if(!t)return;await Promise.all([exports.MODULES.POSTPROCESSING.load(),exports.MODULES.POSTPROCESSING_AO.load()]),e[hp]=this,Yn&&console.log("Apply Postprocessing Effects",t),this._lastVolumeComponents=[...t],this._effects.length=0;const i={handler:this,components:this._lastVolumeComponents};for(let n=0;n<this._lastVolumeComponents.length;n++){const o=this._lastVolumeComponents[n];if(o.context=e,o.apply){if(o.active){let r=function(h,d){return d?(d instanceof exports.MODULES.POSTPROCESSING.MODULE.Effect||d instanceof exports.MODULES.POSTPROCESSING.MODULE.Pass||console.warn(`PostprocessingEffect ${h} created neither Effect nor Pass - this might be caused by a bundler error or false import. Below you find some possible solutions:
|
|
1357
|
+
- If you create custom effect try creating it like this: 'new NEEDLE_ENGINE_MODULES.POSTPROCESSING.MODULE.Effect(...)' instead of 'new Effect(...)'`),!0):!1};if(!e.mainCameraComponent){console.error("No camera in scene found or available yet - can not create postprocessing effects");return}const a=o.apply(i);if(!a)continue;const l=o.typeName||o.constructor.name;if(Array.isArray(a))for(const h of a)r(l,h)&&this._effects.push({effect:h,typeName:o.typeName,priority:o.order});else{if(!r(l,a))continue;this._effects.push({effect:a,typeName:o.typeName,priority:o.order})}}}else o.active&&ue("Volume component is not a VolumeComponent: "+o.__type)}this.applyEffects(e)}_anyPassHasDepth=!1;_anyPassHasNormal=!1;_hasSmaaEffect=!1;get anyPassHasDepth(){return this._anyPassHasDepth}get anyPassHasNormal(){return this._anyPassHasNormal}get hasSmaaEffect(){return this._hasSmaaEffect}_customInputBuffer=null;_customInputBufferId=0;_multisampling=0;set multisampling(e){this._multisampling=e}get multisampling(){return this._multisampling}applyEffects(e){if(this._anyPassHasDepth=!1,this._anyPassHasNormal=!1,this._hasSmaaEffect=!1,this._effects.length<=0)return;const t=e.mainCameraComponent,i=e.renderer,n=e.scene,o=t.threeCamera;if(typeof i[wl]=="boolean"&&(i.autoClear=i[wl]),i[wl]=i.autoClear,typeof i[xl]=="number"&&(i.toneMapping=i[xl]),i[xl]=i.toneMapping,i.toneMapping!=c.NoToneMapping&&!this._effects.find(d=>d instanceof exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect)){const d=new exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect;d.name=`ToneMapping (${i.toneMapping})`,d.mode=Sd(i.toneMapping),this._effects.push({typeName:"ToneMapping",effect:d,priority:Ze.ToneMapping})}this._composer||(this._composer=new exports.MODULES.POSTPROCESSING.MODULE.EffectComposer(i,{frameBufferType:c.HalfFloatType,stencilBuffer:!0})),e.composer&&e.composer!==this._composer&&console.warn("There's already an active EffectComposer in your scene: replacing it with a new one. This might cause unexpected behaviour. Make sure to only use one PostprocessingManager/Volume in your scene."),e.composer=this._composer;const r=e.composer;r.setMainCamera(o),r.setRenderer(i),r.setMainScene(n),r.autoRenderToScreen=!0,r.multisampling=0;for(const d of r.passes)d.dispose();r.removeAllPasses();const a=new exports.MODULES.POSTPROCESSING.MODULE.RenderPass(n,o);a.name="RenderPass",a.mainScene=n,r.addPass(a);const l=a.render;this._customInputBuffer?.dispose(),this._customInputBuffer=null,a.render=(d,u,p,m,g)=>{u&&(u.samples=0,p&&(p.samples=0),(!this._customInputBuffer||this._customInputBuffer.width!==u.width||this._customInputBuffer.height!==u.height||this._customInputBuffer.samples!==this._multisampling||this._customInputBuffer.texture.format!==u.texture.format||this._customInputBuffer.texture.type!==c.HalfFloatType)&&(this._customInputBuffer?.dispose(),this._customInputBuffer=new c.WebGLRenderTarget(u.width,u.height,{format:u.texture.format,type:c.HalfFloatType,depthBuffer:u.depthBuffer,depthTexture:u.depthTexture?new c.DepthTexture(u.width,u.height):void 0,stencilBuffer:u.stencilBuffer,samples:Math.max(0,this._multisampling),minFilter:u.texture.minFilter??c.LinearFilter,magFilter:u.texture.magFilter??c.LinearFilter,generateMipmaps:u.texture.generateMipmaps}),this._customInputBufferId++,this._customInputBuffer.texture.name=`CustomInputBuffer-${this._customInputBufferId}`,this._customInputBuffer.depthTexture&&u.depthTexture&&(this._customInputBuffer.depthTexture.format=u.depthTexture.format,this._customInputBuffer.depthTexture.type=u.depthTexture.type),this._customInputBuffer.samples>0&&(this._customInputBuffer.ignoreDepthForMultisampleCopy=!1),Yn&&console.warn(`[PostProcessing] Input buffer created with size ${this._customInputBuffer.width}x${this._customInputBuffer.height} and samples ${this._customInputBuffer.samples}`)),l.call(a,d,this._customInputBuffer,p,m,g),so.blit(this._customInputBuffer.texture,u,{renderer:d,depthTexture:this._customInputBuffer.depthTexture,depthWrite:!0,depthTest:!0}))};try{oE(this._effects);let d=!1,u=null;for(let g=this._effects.length-1;g>=0;g--){const _=this._effects[g].effect;if(_ instanceof exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect){if(d){Yn&&console.warn(`[PostProcessing] Found multiple tonemapping effects in the scene: ${_.name} and ${u?.name}. Only the last one added will be used.`),this._effects.splice(g,1);continue}u=_,d=!0}}const p=[];let m=!1;for(let g=0;g<this._effects.length;g++){const y=this._effects[g].effect;if(y instanceof exports.MODULES.POSTPROCESSING.MODULE.SMAAEffect?this._hasSmaaEffect=!0:y instanceof exports.MODULES.POSTPROCESSING.MODULE.NormalPass&&(this._anyPassHasNormal=!0),!(y instanceof exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect&&u!==y))if(y instanceof exports.MODULES.POSTPROCESSING.MODULE.Effect){const v=y.getAttributes(),b=exports.MODULES.POSTPROCESSING.MODULE.EffectAttribute.CONVOLUTION;v&b&&(Yn&&console.log("[PostProcessing] Convolution effect: "+y.name),m&&(Yn&&console.log("[PostProcessing] → Merging effects ["+p.map(w=>w.name).join(", ")+"]"),this.createPassForMergeableEffects(p,r,o,n)),m=!0),p.push(y)}else y instanceof exports.MODULES.POSTPROCESSING.MODULE.Pass?(m=!1,this.createPassForMergeableEffects(p,r,o,n),y.renderToScreen=!1,r.addPass(y)):(m=!1,this.createPassForMergeableEffects(p,r,o,n),r.addPass(y))}this.createPassForMergeableEffects(p,r,o,n)}catch(d){console.error("Error while applying postprocessing effects",d),r.passes.forEach(u=>u.dispose()),r.removeAllPasses()}let h=!1;for(let d=r.passes.length-1;d>=0;d--){const u=r.passes[d];let p=!1,m=!1;u.enabled&&(h||(p=!0,m=!0),h=!0),u.renderToScreen=m,u?.configuration!==void 0?u.configuration.gammaCorrection=p:"autosetGamma"in u&&(u.autosetGamma=p),this._anyPassHasDepth||=u.needsDepthTexture}this.handleDevicePixelRatio(),Yn&&console.log("[PostProcessing] Passes →",[...r.passes],`
|
|
1358
1358
|
---------------------------------
|
|
1359
1359
|
• `+r.passes.map(d=>d.name||d.constructor.name+"*").join(`
|
|
1360
1360
|
• `)+`
|
|
1361
|
-
`),Yn&&this._onCreateEffectsDebug(this._composer,o)}createPassForMergeableEffects(e,t,i,n){if(e.length>0){const o=new exports.MODULES.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(Yn==="passes"){const i=new exports.MODULES.POSTPROCESSING.MODULE.DepthEffect({blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.NORMAL,inverted:!0});i.name="Depth Effect";const n=new exports.MODULES.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)})}}}}var BE=Object.defineProperty,Yw=(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&&BE(e,t,n),n};const jo=x("debugpost");class il extends E{get isPostProcessingManager(){return!0}get effects(){return this._activeEffects}get dirty(){return this._isDirty}set dirty(e){this._isDirty=e}sharedProfile;multisampling="auto";addEffect(e){let t=e;return t instanceof
|
|
1361
|
+
`),Yn&&this._onCreateEffectsDebug(this._composer,o)}createPassForMergeableEffects(e,t,i,n){if(e.length>0){const o=new exports.MODULES.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(Yn==="passes"){const i=new exports.MODULES.POSTPROCESSING.MODULE.DepthEffect({blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.NORMAL,inverted:!0});i.name="Depth Effect";const n=new exports.MODULES.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)})}}}}var BE=Object.defineProperty,Yw=(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&&BE(e,t,n),n};const jo=x("debugpost");class il extends E{get isPostProcessingManager(){return!0}get effects(){return this._activeEffects}get dirty(){return this._isDirty}set dirty(e){this._isDirty=e}sharedProfile;multisampling="auto";addEffect(e){let t=e;return t instanceof Ge||(t=new Mc(t),typeof e.order=="number"&&(t.order=e.order)),t.gameObject===void 0&&this.gameObject.addComponent(t),this._effects.includes(t)||(this._effects.push(t),this._isDirty=!0),e}removeEffect(e){let t=-1;if(e instanceof Ge?t=this._effects.indexOf(e):t=this._effects.findIndex(i=>i instanceof Mc&&i.effect===e),t!==-1)return this._effects.splice(t,1),this._isDirty=!0,e;if(e instanceof Ge){const i=this.sharedProfile?.components?.indexOf(e);i!==void 0&&i!==-1&&(this._isDirty=!0,this.sharedProfile?.components?.splice(i,1))}return e}_postprocessing;_activeEffects=[];_effects=[];markDirty(){this._isDirty=!0}awake(){jo&&(console.log("PostprocessingManager Awake",this),console.log("Press P to toggle post processing"),window.addEventListener("keydown",e=>{e.key==="p"&&(this.enabled=!this.enabled,we("Toggle PostProcessing "+this.name+": Enabled="+this.enabled),this.markDirty())})),this.sharedProfile?.__init(this)}_componentEnabledTime=-1;_multisampleAutoChangeTime=0;_multisampleAutoDecreaseTime=0;onEnable(){this._componentEnabledTime=this.context.time.realtimeSinceStartup,this._isDirty=!0}onDisable(){this._postprocessing?.unapply(),this._isDirty=!1}onBeforeRender(){if(!this.context.isInXR&&(this.context.mainCamera&&this._isDirty&&this.apply(),this.context.composer&&this._postprocessing&&this._postprocessing.composer===this.context.composer)){if(this.context.renderer.getContext().isContextLost()&&this.context.renderer.forceContextRestore(),this.context.composer.getRenderer()!==this.context.renderer&&this.context.composer.setRenderer(this.context.renderer),this.context.composer.setMainScene(this.context.scene),this.multisampling==="auto")if(this._postprocessing&&this._postprocessing.hasSmaaEffect)this._postprocessing.multisampling!==0&&(this._postprocessing.multisampling=0,(jo||T())&&console.log(`[PostProcessing] multisampling is disabled because it's set to 'auto' on your PostprocessingManager/Volume component that also has an SMAA effect.
|
|
1362
1362
|
|
|
1363
|
-
If you need multisampling consider changing 'auto' to a fixed value (e.g. 4).`));else{const e=this.context.time.realtimeSinceStartup-this._multisampleAutoChangeTime;if(this.context.time.realtimeSinceStartup-this._componentEnabledTime>2&&e>.5){const t=this._postprocessing.multisampling;if(this._postprocessing.multisampling>0&&this.context.time.smoothedFps<=50){this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup,this._multisampleAutoDecreaseTime=this.context.time.realtimeSinceStartup;let i=this._postprocessing.multisampling*.5;i=Math.floor(i),i!=this._postprocessing.multisampling&&(this._postprocessing.multisampling=i),jo&&console.debug(`[PostProcessing] Reduced multisampling from ${t} to ${this._postprocessing.multisampling}`)}else if(e>1&&this.context.time.smoothedFps>=59&&this._postprocessing.multisampling<this.context.renderer.capabilities.maxSamples&&this.context.time.realtimeSinceStartup-this._multisampleAutoDecreaseTime>10){this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup;let i=this._postprocessing.multisampling<=0?1:this._postprocessing.multisampling*2;i=Math.floor(i),i!==this._postprocessing.multisampling&&(this._postprocessing.multisampling=i),jo&&console.debug(`[PostProcessing] Increased multisampling from ${t} to ${this._postprocessing.multisampling}`)}}}else{const e=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples));e!==this._postprocessing.multisampling&&(this._postprocessing.multisampling=e)}if(this.context.mainCamera){const e=this.context.composer.passes;for(const t of e)if(t.mainCamera&&t.mainCamera!==this.context.mainCamera){this.context.composer.setMainCamera(this.context.mainCamera);break}}}}onDestroy(){this._postprocessing?.dispose()}_lastApplyTime;_rapidApplyCount=0;_isDirty=!1;apply(){if(jo&&console.log(`Apply PostProcessing "${this.name||"unnamed"}"`),T()&&(this._lastApplyTime!==void 0&&Date.now()-this._lastApplyTime<100&&(this._rapidApplyCount++,this._rapidApplyCount===5&&console.warn("Detected rapid post processing modifications - this might be a bug",this)),this._lastApplyTime=Date.now()),this._isDirty=!1,this._activeEffects.length=0,this.sharedProfile?.components){const e=this.sharedProfile.components;for(const t of e)t.active&&t.enabled&&!this._activeEffects.includes(t)&&this._activeEffects.push(t)}for(const e of this._effects)e.active&&e.enabled&&!this._activeEffects.includes(e)&&this._activeEffects.push(e);this._activeEffects.length>0?(this._postprocessing||(this._postprocessing=new my(this.context)),this._postprocessing.apply(this._activeEffects)?.then(()=>{this.activeAndEnabled&&(this._applyPostQueue(),this._postprocessing?(this.multisampling==="auto"?this._postprocessing.multisampling=exports.DeviceUtilities.isMobileDevice()?2:4:this._postprocessing.multisampling=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples)),jo&&console.debug(`[PostProcessing] Set multisampling to ${this._postprocessing.multisampling} (Is Mobile: ${exports.DeviceUtilities.isMobileDevice()})`)):jo&&console.warn("[PostProcessing] No composer found"))})):this._postprocessing?.unapply(!1)}_applyPostQueue(){if(this._modificationQueue){for(const e of this._modificationQueue.values())this.onEditorModification(e);this._modificationQueue.clear()}}onEditorModification(e){if(e.propertyName.startsWith("postprocessing.")){if(!this._postprocessing)return this._modificationQueue||(this._modificationQueue=new Map),this._modificationQueue.set(e.propertyName,e),!0;if(!this._activeEffects?.length)return;const t=e.propertyName.split(".");if(t.length===3||t.length===4){const i=t[1],n=t[2];for(const o of this._activeEffects)if(o.typeName?.toLowerCase()===i.toLowerCase()){if(n==="active"){o.active=e.value,this.scheduleRecreate();return}if(!id.has(i)){const r=new Array;id.set(i,r);const a=Object.keys(o);for(const l of a)o[l]instanceof F&&r.push(l)}if(id.has(i)){const r=n.toLowerCase(),a=id.get(i);for(const l of a)if(l.toLowerCase()===r){const h=o[l];h instanceof F&&(t.length===4&&t[3]==="active"?(h.overrideState=e.value,this.scheduleRecreate()):h&&h.value!==void 0&&(h.value=e.value));return}}console.warn("Unknown modification",n);return}}return!0}return!1}_modificationQueue;_recreateId=-1;scheduleRecreate(){const e=++this._recreateId;setTimeout(()=>{e===this._recreateId&&(this.onDisable(),this.onEnable())},200)}}Yw([ze(zu)],il.prototype,"sharedProfile");Yw([ze()],il.prototype,"multisampling");const id=new Map;nE(il);async function gy(s){const{NeedleEngineWebComponent:e}=await Promise.resolve().then(()=>RT);e.observedAttributes.includes(s)||e.observedAttributes.push(s)}var UE=Object.defineProperty,ht=(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&&UE(e,t,n),n};const nt=x("debugsceneswitcher"),FE=x("sceneswitcher:clearscene"),Cd="scene";gy(Cd);const Fs=Promise.resolve(!1);class Ne extends E{autoLoadFirstScene=!0;scenes=[];loadingScene;queryParameterName="scene";useSceneName=!0;clamp=!0;useHistory=!0;useKeyboard=!0;useSwipe=!0;useSceneLighting=!0;useSceneBackground=!0;preloadNext=1;preloadPrevious=1;preloadConcurrent=2;createMenuButtons=!1;get currentIndex(){return this._currentIndex}get currentLoadingProgress(){return this._currentLoadingProgress}get currentlyLoadingScene(){return this._currentlyLoadingScene}get currentlyLoadedScene(){return this._currentScene}sceneLoadingStart=new oe;sceneLoadingProgress=new oe;sceneLoaded=new oe;_currentIndex=-1;_currentScene=void 0;_currentSceneAsset=void 0;_engineElementOverserver=void 0;_preloadScheduler;_menuButtons;__lastSwitchScene;__lastSwitchScenePromise;awake(){this._currentScene=void 0,this._lastLoadingScene=void 0,this.__lastSwitchScenePromise=void 0,this.scenes===void 0&&(this.scenes=[]);for(const e of this.scenes)e&&!e.hasUrl&&e.asset instanceof c.Object3D?S.remove(e.asset):e instanceof c.Object3D&&S.remove(e);nt&&console.log("SceneSwitcher",this)}async onEnable(){if(globalThis.addEventListener("popstate",this.onPopState),this.context.input.addEventListener(Ce.KeyDown,this.onInputKeyDown),this.context.input.addEventListener(Ce.PointerMove,this.onInputPointerMove),this.context.input.addEventListener(Ce.PointerUp,this.onInputPointerUp),this._engineElementOverserver||(this._engineElementOverserver=new MutationObserver(e=>{for(const t of e)if(t.type==="attributes"&&t.attributeName===Cd){const i=this.context.domElement.getAttribute(Cd);i!==null&&this.trySelectSceneFromValue(i)}})),this._engineElementOverserver.observe(this.context.domElement,{attributes:!0}),this._preloadScheduler||(this._preloadScheduler=new zE(this)),this._preloadScheduler.maxLoadAhead=this.preloadNext,this._preloadScheduler.maxLoadBehind=this.preloadPrevious,this._preloadScheduler.maxConcurrent=this.preloadConcurrent,this._preloadScheduler.begin(2e3),this.autoLoadFirstScene&&this._currentIndex===-1&&!await this.tryLoadFromQueryParam()){const e=this.context.domElement.getAttribute(Cd);(e===null||!await this.trySelectSceneFromValue(e))&&this._currentIndex===-1&&this.select(0)}this.createMenuButtons&&(this._menuButtons??=[],this._menuButtons.push(this.context.menu.appendChild({label:"Previous",icon:"arrow_back_ios",onClick:()=>this.selectPrev(),priority:-1005,class:"row2"})),this._menuButtons.push(this.context.menu.appendChild({label:"Next",icon:"arrow_forward_ios",iconSide:"right",onClick:()=>this.selectNext(),priority:-1e3,class:"row2"})))}onDisable(){if(globalThis.removeEventListener("popstate",this.onPopState),this.context.input.removeEventListener(Ce.KeyDown,this.onInputKeyDown),this.context.input.removeEventListener(Ce.PointerMove,this.onInputPointerMove),this.context.input.removeEventListener(Ce.PointerUp,this.onInputPointerUp),this._preloadScheduler?.stop(),this._menuButtons){for(const e of this._menuButtons)e.remove();this._menuButtons=void 0}}onPopState=async e=>{if(!this.useHistory)return;const t=this.useHistory;try{this.useHistory=!1;let i=!1;if(this.queryParameterName&&(i=await this.tryLoadFromQueryParam()),!i){const n=e?.state;if(n&&n.startsWith(this.guid)){const o=n.substr(this.guid.length+2);nt&&console.log("PopState",o),await this.trySelectSceneFromValue(o)}}}finally{this.useHistory=t}};normalizedSwipeThresholdX=.1;_didSwipe=!1;onInputPointerMove=e=>{if(this.useSwipe&&!this._didSwipe&&e.button===0&&e.pointerType==="touch"&&this.context.input.getPointerPressedCount()===1){const t=this.context.input.getPointerPositionDelta(e.button);if(t){const i=t.x/this.context.domWidth;i>=this.normalizedSwipeThresholdX?(this._didSwipe=!0,this.selectPrev()):i<=-this.normalizedSwipeThresholdX&&(this._didSwipe=!0,this.selectNext())}}};onInputPointerUp=e=>{e.button===0&&(this._didSwipe=!1)};onInputKeyDown=e=>{if(!this.useKeyboard||!this.scenes)return;const t=e.key.toLowerCase();if(!t)return;const i=parseInt(t)-1;if(i>=0){this.trySelectSceneFromValue(i);return}switch(t){case"arrowright":case"d":this.selectNext();break;case"arrowleft":case"a":this.selectPrev();break}};addScene(e){if(typeof e=="string"){let t=this.context.addressables.findAssetReference(e);return t||(t=new K(e),this.context.addressables.registerAssetReference(t)),this.scenes.push(t),t}return this.scenes.push(e),e}selectNext(){return this.select(this._currentIndex+1)}selectPrev(){return this.select(this._currentIndex-1)}select(e){if(nt&&console.log("[SceneSwitcher] select",e),typeof e=="object"&&console.warn('[SceneSwitcher] Switching to "'+e+'" might not work. Please either use an index or a AssetReference (not a scene reference)'),typeof e=="string"){const i=this.scenes?.find(n=>n.url===e);if(!i){const n=K.getOrCreate(this.sourceId??"",e,this.context);return this.switchScene(n)}if(i)e=this.scenes?.indexOf(i);else return Fs}if(!this.scenes?.length)return Fs;if(e<0){if(this.clamp)return Fs;e=this.scenes.length-1}else if(e>=this.scenes.length){if(this.clamp)return Fs;e=0}const t=this.scenes[e];return this.switchScene(t)}unload(){return this.__lastSwitchScene=void 0,this.__lastSwitchScenePromise=void 0,this.__unloadCurrentScene()}async reload(){if(this.__lastSwitchScene){const e=this.__lastSwitchScene;return this.__lastSwitchScene=void 0,this.switchScene(e)}return!1}async switchScene(e){if(!(e instanceof K)){const i=typeof e;if(i==="string")return this.select(e);if(i==="number")return this.select(e);if(e&&e instanceof c.Object3D){const n=this.scenes?.indexOf(e);e=new K(e.name,void 0,e),n>=0&&(this.scenes[n]=e)}else return console.warn(`[SceneSwitcher] Can't switch to scene of type ${i}`),!1}return e.url===this.sourceId?(console.warn("[SceneSwitcher] Can't load own scene - prevent recursive loading",this.sourceId),!1):this.__lastSwitchScene===e&&this.__lastSwitchScenePromise?this.__lastSwitchScenePromise:(this.__lastSwitchScene=e,this.__lastSwitchScenePromise=this.__internalSwitchScene(e),await this.__lastSwitchScenePromise)}async __unloadCurrentScene(){const e=this._currentScene;if(this._currentScene=void 0,e){nt&&console.log("[SceneSwitcher] UNLOAD",e.url,"HasURL?: "+e.hasUrl);const t=this.tryGetSceneEventListener(e.asset);if(t?.sceneClosing){const i=t.sceneClosing();i instanceof Promise&&await i}e.hasUrl?(e.unload(),this._currentSceneAsset&&gi(this._currentSceneAsset,!0,!1)):S.remove(this._currentSceneAsset)}}_currentlyLoadingScene;async __internalSwitchScene(e){await this.__unloadCurrentScene();const t=this._currentIndex=this.scenes?.indexOf(e)??-1;try{nt&&console.debug(`${Date.now()} [SceneSwitcher] Loading scene start: ${e.url} (index: ${t})`),this._currentlyLoadingScene=e,this._currentLoadingProgress=new ProgressEvent("progress",{loaded:0,total:1});const i=new CustomEvent("loadscene-start",{detail:{scene:e,switcher:this,index:t}});this.dispatchEvent(i),this.sceneLoadingStart?.invoke(i.detail),await this.onStartLoading(),await e.loadAssetAsync((o,r)=>{if(nt){const a=r.loaded/r.total,l="["+"=".repeat(Math.floor(a*20))+"-".repeat(20-Math.floor(a*20))+"]";console.debug(`${Date.now()} [SceneSwitcher] Loading scene progress: ${(a*100).toFixed(1)} % ${l}`,e.url)}this._currentLoadingProgress=r,this.dispatchEvent(r),this.sceneLoadingProgress?.invoke(r)}).catch(console.error),await this.onEndLoading();const n=new CustomEvent("loadscene-finished",{detail:{scene:e,switcher:this,index:t}});if(this.dispatchEvent(n),this._currentLoadingProgress=void 0,this._currentlyLoadingScene=void 0,n.defaultPrevented)return nt&&console.warn("[SceneSwitcher] Adding loaded scene prevented:",e,n),!1;if(!e.asset)return nt&&console.warn("[SceneSwitcher] Failed loading scene:",e),!1;if(this._currentIndex===t){if(nt&&console.log("[SceneSwitcher] ADD",e.url),this._currentScene=e,FE){const a=this.context.mainCameraComponent?.gameObject||this.context.mainCamera;a?.removeFromParent();const l=this.gameObject.removeFromParent();gi(this.context.scene,!0,!0),this.context.scene=new c.Scene,this.context.scene.add(l),a&&this.context.scene.add(a)}if(e.asset.parent?this._currentSceneAsset=oo(e.asset,{parent:this.gameObject}):(this._currentSceneAsset=e.asset,S.add(e.asset,this.gameObject)),this.useSceneLighting&&this.context.sceneLighting.enable(e),this.useSceneBackground){const a=this.context.lightmaps.tryGetSkybox(e.url);a?(a.mapping=c.EquirectangularReflectionMapping,this.context.scene.background=a):nt&&console.warn("[SceneSwitcher] Can't find skybox for scene "+e.url)}if(this.useHistory&&t>=0){let a=t.toString();if(this.useSceneName&&(e instanceof c.Object3D?a=e.name:e.url&&(a=bb(e.url))),this.queryParameterName?.length)dc(this.queryParameterName,a,this.useHistory);else{const l=history.state,h=this.guid+"::"+t;l!==h&&history.pushState(h,"unused",location.href)}}const o=this.tryGetSceneEventListener(e.asset);if(o?.sceneOpened){const a=o.sceneOpened(this);a instanceof Promise&&await a}nt&&console.debug(`${Date.now()} [SceneSwitcher] Loading scene finished: ${e.url} (index: ${t})`);const r=new CustomEvent("scene-opened",{detail:{scene:e,switcher:this,index:t}});return this.dispatchEvent(r),this.sceneLoaded?.invoke(this),!0}}catch(i){console.error(i)}return!1}preload(e){if(e>=0&&e<this.scenes.length){const t=this.scenes[e];if(t instanceof K)return t.preload()}return Fs}tryLoadFromQueryParam(){if(!this.queryParameterName?.length)return Fs;const e=x(this.queryParameterName);return typeof e=="boolean"?Fs:this.trySelectSceneFromValue(e)}trySelectSceneFromValue(e){if(typeof e=="string"){const t=parseInt(e);if(t>=0&&t<this.scenes.length)return this.select(t);{const i=e.toLowerCase();for(let n=0;n<this.scenes.length;n++){const o=this.scenes[n];if(!o)continue;if((o instanceof c.Object3D?o.name:bb(o.url)).toLowerCase().includes(i))return this.select(n)}}}else if(typeof e=="number"&&e>=0&&e<this.scenes.length)return this.select(e);return pi()&&console.warn('[SceneSwitcher] Can not find scene: "'+e+'"',this),Fs}_lastLoadingScene=void 0;_loadingScenePromise=void 0;_isCurrentlyLoading=!1;_currentLoadingProgress=void 0;async onStartLoading(){if(this._isCurrentlyLoading=!0,this.loadingScene&&(this._lastLoadingScene!==this.loadingScene&&(this._loadingScenePromise=void 0),this._lastLoadingScene=this.loadingScene,this._loadingScenePromise||(this._loadingScenePromise=this.loadingScene?.loadAssetAsync().then(e=>e!=null)),await this._loadingScenePromise,this._isCurrentlyLoading&&this.loadingScene?.asset)){nt&&console.log("Add loading scene",this.loadingScene.url,this.loadingScene.asset);const e=this.loadingScene.asset;S.add(e,this.gameObject);const t=this.tryGetSceneEventListener(e);if(t?.sceneOpened){const i=t.sceneOpened(this);i instanceof Promise&&await i}}if(this._isCurrentlyLoading){const e=this.tryGetSceneEventListener(this.gameObject);if(e&&e.sceneOpened){const t=e.sceneOpened(this);t instanceof Promise&&await t}}}async onEndLoading(){if(this._isCurrentlyLoading=!1,this.loadingScene?.asset){nt&&console.log("Remove loading scene",this.loadingScene.url);const e=this.loadingScene.asset,t=this.tryGetSceneEventListener(e);if(typeof t?.sceneClosing=="function"){const i=t.sceneClosing();i instanceof Promise&&await i}S.remove(e)}if(!this._isCurrentlyLoading){const e=this.tryGetSceneEventListener(this.gameObject);if(e&&e.sceneClosing){const t=e.sceneClosing();t instanceof Promise&&await t}}}tryGetSceneEventListener(e,t=0){if(!e)return null;const i=S.foreachComponent(e,n=>{const o=n;if(o.sceneClosing||o.sceneOpened)return o});if(t===0&&!i&&e.children.length)for(const n of e.children){const o=this.tryGetSceneEventListener(n,t+1);if(o)return o}return i||null}}ht([f()],Ne.prototype,"autoLoadFirstScene");ht([f(K)],Ne.prototype,"scenes");ht([f(K)],Ne.prototype,"loadingScene");ht([f()],Ne.prototype,"queryParameterName");ht([f()],Ne.prototype,"useSceneName");ht([f()],Ne.prototype,"clamp");ht([f()],Ne.prototype,"useHistory");ht([f()],Ne.prototype,"useKeyboard");ht([f()],Ne.prototype,"useSwipe");ht([f()],Ne.prototype,"useSceneLighting");ht([f()],Ne.prototype,"useSceneBackground");ht([f()],Ne.prototype,"preloadNext");ht([f()],Ne.prototype,"preloadPrevious");ht([f()],Ne.prototype,"preloadConcurrent");ht([f()],Ne.prototype,"createMenuButtons");ht([f(oe)],Ne.prototype,"sceneLoadingStart");ht([f(oe)],Ne.prototype,"sceneLoadingProgress");ht([f(oe)],Ne.prototype,"sceneLoaded");function bb(s){const t=s.split("/").pop()?.split(".").shift();return t?.length?t:s}class zE{maxLoadAhead;maxLoadBehind;maxConcurrent;_isRunning=!1;_switcher;_loadTasks=[];_maxConcurrentLoads=1;constructor(e,t=1,i=1,n=2){this._switcher=e,this.maxLoadAhead=t,this.maxLoadBehind=i,this.maxConcurrent=n}begin(e){if(this._isRunning)return;nt&&console.log("[SceneSwitcher] Preload scheduled",{delay:e}),this._isRunning=!0;let t=-10,i,n;const o=this._switcher.scenes,r=Date.now()+e,a=setInterval(()=>{if(this.allLoaded()&&(nt&&console.log("[SceneSwitcher] All scenes (pre-)loaded"),this.stop()),!this._isRunning){clearInterval(a);return}if(Date.now()<r||this.canLoadNewScene()===!1)return;(t===-10||t!==this._switcher.currentIndex)&&(t=this._switcher.currentIndex,n=0,i=0);const l=n%2===0;l&&(i+=1),n+=1;const h=l?this.maxLoadAhead:this.maxLoadBehind;if(i>h)return;const d=l?t+i:t-i;if(!(d<0)&&!(d<0||d>=o.length)&&!this._loadTasks.some(u=>u.index===d)){const u=o[d];nt&&console.log("[SceneSwitcher] Schedule preload scene",{roomIndex:d,searchForward:l,lastRoom:t,currentIndex:this._switcher.currentIndex,tasks:this._loadTasks.length},u?.url),new NE(d,u,this._loadTasks)}},200)}stop(){this._isRunning=!1}canLoadNewScene(){return this._loadTasks.length<this._maxConcurrentLoads}allLoaded(){if(this._switcher.scenes){for(const e of this._switcher.scenes)if(e?.isLoaded&&e.isLoaded()===!1)return!1}return!0}}class NE{index;asset;tasks;constructor(e,t,i){this.index=e,this.asset=t,this.tasks=i,i.push(this),this.awaitLoading()}async awaitLoading(){this.asset&&!this.asset.isLoaded()&&(nt&&console.log("[SceneSwitcher] Preload start: "+this.asset.url,this.index),await this.asset.preload(),nt&&console.log("[SceneSwitcher] Preload finished: "+this.asset.url,this.index));const e=this.tasks.indexOf(this);e>=0&&this.tasks.splice(e,1)}}function VE(){return new Promise((s,e)=>{const i=()=>{i!=null&&(document.removeEventListener("pointerdown",i),document.removeEventListener("click",i),document.removeEventListener("dragstart",i),document.removeEventListener("touchstart",i),s())};document.addEventListener("pointerdown",i),document.addEventListener("click",i),document.addEventListener("dragstart",i),document.addEventListener("touchstart",i)})}async function $E(s){await VE(),s()}var WE=Object.defineProperty,HE=Object.getOwnPropertyDescriptor,Ci=(s,e,t,i)=>{for(var n=i>1?void 0:i?HE(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&&WE(e,t,n),n};const tt=x("debugvideo");var Kw=(s=>(s[s.None=0]="None",s[s.AdjustHeight=1]="AdjustHeight",s[s.AdjustWidth=2]="AdjustWidth",s))(Kw||{}),Zw=(s=>(s[s.VideoClip=0]="VideoClip",s[s.Url=1]="Url",s))(Zw||{}),Jw=(s=>(s[s.CameraFarPlane=0]="CameraFarPlane",s[s.CameraNearPlane=1]="CameraNearPlane",s[s.RenderTexture=2]="RenderTexture",s[s.MaterialOverride=3]="MaterialOverride",s))(Jw||{});class Ze extends E{playOnAwake=!0;aspectMode=0;clip=null;source=1;get url(){return this._url}set url(e){const i=this._url!==e;this.__didAwake?i&&this.setClipURL(e??""):this._url=e}_url=null;renderMode;targetMaterialProperty;targetMaterialRenderer;targetTexture;time=0;_playbackSpeed=1;get playbackSpeed(){return this._videoElement?.playbackRate??this._playbackSpeed}set playbackSpeed(e){this._playbackSpeed=e,this._videoElement&&(this._videoElement.playbackRate=e)}_isLooping=!1;get isLooping(){return this._videoElement?.loop??this._isLooping}set isLooping(e){this._isLooping=e,this._videoElement&&(this._videoElement.loop=e)}get currentTime(){return this._videoElement?.currentTime??this.time}set currentTime(e){this._videoElement?this._videoElement.currentTime=e:this.time=e}get isPlaying(){const e=this._videoElement;if(e){if(e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>e.HAVE_CURRENT_DATA)return!0;if(e.srcObject&&e.srcObject.active)return!0}return!1}get crossOrigin(){return this._videoElement?.crossOrigin??this._crossOrigin}set crossOrigin(e){this._crossOrigin=e,this._videoElement&&(e!==null?this._videoElement.setAttribute("crossorigin",e):this._videoElement.removeAttribute("crossorigin"))}get videoMaterial(){return!this._videoMaterial&&!this.create(!1)?null:this._videoMaterial}get videoTexture(){return!this._videoTexture&&!this.create(!1)?null:this._videoTexture}get videoElement(){return!this._videoElement&&!this.create(!1)?null:this._videoElement}requestPictureInPicture(){return this._videoElement?this._videoElement.requestPictureInPicture():null}get muted(){return this._videoElement?.muted??this._muted}set muted(e){this._muted=e,this._videoElement&&(this._videoElement.muted=e)}_muted=!1;get currentVideo(){return this.clip}set audioOutputMode(e){e!==this._audioOutputMode&&(e===1&&T()&&console.warn("VideoAudioOutputMode.AudioSource is not yet implemented"),this._audioOutputMode=e,this.updateVideoElementSettings())}get audioOutputMode(){return this._audioOutputMode}_audioOutputMode=2;playInBackground=!0;_crossOrigin="anonymous";_videoElement=null;_videoTexture=null;_videoMaterial=null;_isPlaying=!1;wasPlaying=!1;preloadVideo(){tt&&console.log("Video Preload: "+this.name,this.clip),this.create(!1)}preload(){this.preloadVideo()}setVideo(e){this.clip=e,this.source=0,this._videoElement?(this._videoElement.srcObject=e,this._isPlaying&&this.play(),this.updateAspect()):this.create(this.playOnAwake)}setClipURL(e){this._url!==e&&(this._url=e,this.source=1,tt&&console.log("set url",e),this._videoElement?e.endsWith(".m3u8")||e.includes(".m3u")?this.ensureM3UCanBePlayed():(this._videoElement.src=e,this._isPlaying&&(this.stop(),this.play())):this.create(this.playOnAwake))}onEnable(){tt&&console.log("VideoPlayer.onEnable",Zw[this.source],this.clip,this.url,this),window.addEventListener("visibilitychange",this.visibilityChanged),this.playOnAwake===!0?this.create(!0):this.preloadVideo(),this.screenspace?this._overlay?.start():this._overlay?.stop()}onDisable(){window.removeEventListener("visibilitychange",this.visibilityChanged),this._overlay?.stop(),this.pause()}visibilityChanged=e=>{switch(document.visibilityState){case"hidden":this.playInBackground||(this.wasPlaying=this._isPlaying,this.pause());break;case"visible":this.wasPlaying&&!this._isPlaying&&this.play();break}};onDestroy(){this._videoElement&&(this.videoElement?.remove(),this._videoElement=null),this._videoTexture&&(this._videoTexture.dispose(),this._videoTexture=null)}_receivedInput=!1;constructor(){super(),$E(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[],x("videoscreenspace")&&window.addEventListener("keydown",e=>{e.key==="f"&&(this.screenspace=!this.screenspace)})}play(){if(this._videoElement||this.create(!1),!this._videoElement){tt&&console.warn("Can not play: no video element found",this);return}if(!(this._isPlaying&&!this._videoElement?.ended&&!this._videoElement?.paused)){if(this._isPlaying=!0,this._receivedInput||(this._videoElement.muted=!0),this.handleBeginPlaying(!1),this.shouldUseM3U){this.ensureM3UCanBePlayed();return}tt&&console.log("Video Play()",this.clip,this._videoElement,this.time),this._videoElement.currentTime=this.time,this._videoElement.play().catch(e=>{console.log(e),tt&&console.error("Error playing video",e,"CODE="+e.code,this.videoElement?.src,this),setTimeout(()=>{this._isPlaying&&!this.destroyed&&this.activeAndEnabled&&this.play()},1e3)}),tt&&console.log("play",this._videoElement,this.time)}}stop(){this._isPlaying=!1,this.time=0,this._videoElement&&(this._videoElement.currentTime=0,this._videoElement.pause(),tt&&console.log("STOP",this))}pause(){this.time=this._videoElement?.currentTime??0,this._isPlaying=!1,this._videoElement?.pause(),tt&&console.log("PAUSE",this,this.currentTime)}create(e){let t;switch(this.source){case 0:t=this.clip;break;case 1:t=this.url,!t?.length&&typeof this.clip=="string"&&(t=this.clip);break}return t?(this._videoElement||(tt&&console.warn("Create VideoElement",this),this._videoElement=this.createVideoElement(),this.context.domElement.shadowRoot.prepend(this._videoElement),this.updateVideoElementStyles()),typeof t=="string"?(tt&&console.log("Set Video src",t),this._videoElement.src=t):(tt&&console.log("Set Video srcObject",t),this._videoElement.srcObject=t),this._videoTexture||(this._videoTexture=new c.VideoTexture(this._videoElement)),this._videoTexture.flipY=!1,this._videoTexture.colorSpace=c.SRGBColorSpace,e&&this.handleBeginPlaying(e),tt&&console.log("Video: handle playing done...",t,e),!0):(tt&&console.warn("No video source set",this),!1)}updateAspect(){this.aspectMode!==0&&this.startCoroutine(this.updateAspectImpl())}_overlay=null;get screenspace(){return this._overlay?.enabled??!1}set screenspace(e){if(e){if(!this._videoTexture)return;this._overlay||(this._overlay=new GE(this.context)),this._overlay.add(this._videoTexture)}else this._overlay?.remove(this._videoTexture);this._overlay&&(this._overlay.enabled=e)}_targetObjects;createVideoElement(){const e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),tt&&console.log("created video element",e),e}handleBeginPlaying(e){if(!this.activeAndEnabled||!this._videoElement)return;this._targetObjects.length=0;let t=this.gameObject;switch(this.renderMode){case 3:t=this.targetMaterialRenderer?.gameObject,t||(t=S.getComponent(this.gameObject,Ht)?.gameObject);break;case 2:console.error("VideoPlayer renderTexture not implemented yet. Please use material override instead");return}if(!t){console.error("Missing target for video material renderer",this.name,Jw[this.renderMode],this);return}const i=t.material;if(i){this._targetObjects.push(t),i!==this._videoMaterial&&(this._videoMaterial=i.clone(),t.material=this._videoMaterial);const n="map",o=this._videoMaterial;if(!this.targetMaterialProperty)o[n]=this._videoTexture;else switch(this.targetMaterialProperty){default:o[n]=this._videoTexture;break}}else{console.warn("Can not play video, no material found, this might be a multimaterial case which is not supported yet");return}this.updateVideoElementSettings(),this.updateVideoElementStyles(),e&&(this.shouldUseM3U&&this.ensureM3UCanBePlayed(),this.play())}updateVideoElementSettings(){if(!this._videoElement)return;this._videoElement.loop=this._isLooping,this._videoElement.currentTime=this.currentTime,this._videoElement.playbackRate=this._playbackSpeed,this._videoElement.playsInline=!0;let e=!this._receivedInput||this.audioOutputMode===0;!e&&this._muted&&(e=!0),this._videoElement.muted=e,this.playOnAwake&&(this._videoElement.autoplay=!0)}updateVideoElementStyles(){this._videoElement&&(this._videoElement.style.userSelect="none",this._videoElement.style.visibility="hidden",this._videoElement.style.display="none",this.updateAspect())}_updateAspectRoutineId=-1;*updateAspectImpl(){const e=++this._updateAspectRoutineId,t=void 0,i=this.clip;for(;e===this._updateAspectRoutineId&&this.aspectMode!==0&&this.clip&&i===this.clip&&this._isPlaying;){if(!i||typeof i=="string")return;let n;for(const o of i.getVideoTracks()){const r=o.getSettings();if(r&&r.width&&r.height){n=r.width/r.height;break}else n=this.context.renderer.domElement.clientWidth/this.context.renderer.domElement.clientHeight}if(n===void 0){for(let o=0;o<10;o++)yield;if(!this.isPlaying)break;continue}if(t===n){yield;continue}for(const o of this._targetObjects){let r=1;if(o.parent){const a=Le(o.parent);r=a.x/a.y}switch(this.aspectMode){case 1:o.scale.y=1/n*o.scale.x*r;break;case 2:o.scale.x=n*o.scale.y*r;break}}for(let o=0;o<3;o++)yield}}get shouldUseM3U(){return this.url!=null&&(this.url.endsWith(".m3u8")||this.url.endsWith(".m3u"))&&this.source===1}ensureM3UCanBePlayed(){if(!this.shouldUseM3U)return;let e=document.head.querySelector("script[data-hls_library]");e?globalThis.Hls?this.onHlsAvailable():e.addEventListener("load",this.onHlsAvailable):(tt&&console.log("HLS: load script"),e=document.createElement("script"),e.dataset.hls_library="hls.js",e.src="https://cdn.jsdelivr.net/npm/hls.js@1",e.addEventListener("load",this.onHlsAvailable),document.head.append(e))}_hls;onHlsAvailable=()=>{tt&&console.log("HLS: available",this.clip),!(!this.shouldUseM3U||!this.url)&&(this._hls||(this._hls=new Hls),this.videoElement.autoplay=!0,this._hls.loadSource(this.url),this._hls.attachMedia(this.videoElement),this._videoElement?.play(),tt&&console.log("HLS: loaded",this.clip))}}Ci([f()],Ze.prototype,"playOnAwake",2);Ci([f()],Ze.prototype,"aspectMode",2);Ci([f(URL)],Ze.prototype,"clip",2);Ci([f()],Ze.prototype,"source",2);Ci([f(URL)],Ze.prototype,"url",1);Ci([f()],Ze.prototype,"renderMode",2);Ci([f()],Ze.prototype,"targetMaterialProperty",2);Ci([f(Ht)],Ze.prototype,"targetMaterialRenderer",2);Ci([f(c.Texture)],Ze.prototype,"targetTexture",2);Ci([f()],Ze.prototype,"time",2);Ci([f()],Ze.prototype,"playbackSpeed",1);Ci([f()],Ze.prototype,"isLooping",1);Ci([f()],Ze.prototype,"audioOutputMode",1);class GE{context;constructor(e){this.context=e,this._input=new qE(this)}get enabled(){return this._isInScreenspaceMode}set enabled(e){e?this.start():this.stop()}add(e){this._videos.indexOf(e)===-1&&this._videos.push(e)}remove(e){if(!e)return;const t=this._videos.indexOf(e);t>=0&&this._videos.splice(t,1)}start(){if(this._isInScreenspaceMode||this._videos.length<0)return;const e=this._videos[this._videos.length-1];if(!e)return;if(this._isInScreenspaceMode=!0,!this._screenspaceModeQuad){if(this._screenspaceModeQuad=po.createPrimitive(ja.Quad,{material:new XE(e)}),!this._screenspaceModeQuad)return;this._screenspaceModeQuad.geometry.scale(2,2,2)}const t=this._screenspaceModeQuad;this.context.scene.add(t),this.updateScreenspaceMaterialUniforms();const i=t.material;i?.reset(),this._input?.enable(i)}stop(){this._isInScreenspaceMode=!1,this._screenspaceModeQuad&&(this._input?.disable(),this._screenspaceModeQuad.removeFromParent())}updateScreenspaceMaterialUniforms(){const e=this._screenspaceModeQuad?.material;e&&(e.screenAspect=this.context.domElement.clientWidth/this.context.domElement.clientHeight)}_videos=[];_screenspaceModeQuad;_isInScreenspaceMode=!1;_input}class qE{_onResizeScreenFn;_onKeyUpFn;_onMouseWheelFn;context;overlay;constructor(e){this.overlay=e,this.context=e.context}_material;enable(e){this._material=e,window.addEventListener("resize",this._onResizeScreenFn=()=>{this.overlay.updateScreenspaceMaterialUniforms()}),window.addEventListener("keyup",this._onKeyUpFn=n=>{n.key==="Escape"&&this.overlay.stop()}),window.addEventListener("wheel",this._onMouseWheelFn=n=>{this.overlay.enabled&&(e.zoom+=n.deltaY*5e-4,n.preventDefault())},{passive:!1});const t=new c.Vector2;window.addEventListener("mousemove",n=>{if(this.overlay.enabled&&this.context.input.getPointerPressed(0)){const o=new c.Vector2(n.movementX,n.movementY);o.x/=this.context.domElement.clientWidth,o.y/=this.context.domElement.clientHeight,t.set(o.x,o.y),t.multiplyScalar(e.zoom/-this.context.time.deltaTime*.01),e.offset=e.offset.add(t)}}),window.addEventListener("pointermove",n=>{this.overlay.enabled&&this.context.input.getPointerPressed(0)&&this.context.input.getTouchesPressedCount()===1&&(t.set(n.movementX,n.movementY),t.multiplyScalar(e.zoom*-this.context.time.deltaTime*.05),e.offset=e.offset.add(t))});let i=0;window.addEventListener("touchstart",n=>{if(n.touches.length<2){this.context.time.time-i<.3&&this.overlay.stop(),i=this.context.time.time;return}this._isPinching=!0,this._lastPinch=0}),window.addEventListener("touchmove",n=>{if(!this._isPinching||!this._material)return;const o=n.touches[0],r=n.touches[1],a=o.clientX-r.clientX,l=o.clientY-r.clientY,h=Math.sqrt(a*a+l*l);if(this._lastPinch!==0){const d=h-this._lastPinch;this._material.zoom-=d*.004}this._lastPinch=h}),window.addEventListener("touchend",()=>{this._isPinching=!1})}_isPinching=!1;_lastPinch=0;disable(){this._onResizeScreenFn&&(window.removeEventListener("resize",this._onResizeScreenFn),this._onResizeScreenFn=void 0),this._onKeyUpFn&&(window.removeEventListener("keyup",this._onKeyUpFn),this._onKeyUpFn=void 0),this._onMouseWheelFn&&(window.removeEventListener("wheel",this._onMouseWheelFn),this._onMouseWheelFn=void 0)}}class XE extends c.ShaderMaterial{set screenAspect(e){this.uniforms.screenAspect.value=e,this.needsUpdate=!0}set offset(e){const t=this.uniforms.offsetScale.value;t.x=e.x,t.y=e.y,this.uniforms.offsetScale.value=t,this.needsUpdate=!0}_offset=new c.Vector2;get offset(){const e=this.uniforms.offsetScale.value;return this._offset.set(e.x,e.y),this._offset}set zoom(e){const t=this.uniforms.offsetScale.value;e<.001&&(e=.001),t.z=e,this.needsUpdate=!0}get zoom(){return this.uniforms.offsetScale.value.z}reset(){this.offset=this.offset.set(0,0),this.zoom=1,this.needsUpdate=!0}constructor(e){super(),this.uniforms={map:{value:e},screenAspect:{value:1},offsetScale:{value:new c.Vector4(0,0,1,1)}},this.vertexShader=`
|
|
1363
|
+
If you need multisampling consider changing 'auto' to a fixed value (e.g. 4).`));else{const e=this.context.time.realtimeSinceStartup-this._multisampleAutoChangeTime;if(this.context.time.realtimeSinceStartup-this._componentEnabledTime>2&&e>.5){const t=this._postprocessing.multisampling;if(this._postprocessing.multisampling>0&&this.context.time.smoothedFps<=50){this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup,this._multisampleAutoDecreaseTime=this.context.time.realtimeSinceStartup;let i=this._postprocessing.multisampling*.5;i=Math.floor(i),i!=this._postprocessing.multisampling&&(this._postprocessing.multisampling=i),jo&&console.debug(`[PostProcessing] Reduced multisampling from ${t} to ${this._postprocessing.multisampling}`)}else if(e>1&&this.context.time.smoothedFps>=59&&this._postprocessing.multisampling<this.context.renderer.capabilities.maxSamples&&this.context.time.realtimeSinceStartup-this._multisampleAutoDecreaseTime>10){this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup;let i=this._postprocessing.multisampling<=0?1:this._postprocessing.multisampling*2;i=Math.floor(i),i!==this._postprocessing.multisampling&&(this._postprocessing.multisampling=i),jo&&console.debug(`[PostProcessing] Increased multisampling from ${t} to ${this._postprocessing.multisampling}`)}}}else{const e=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples));e!==this._postprocessing.multisampling&&(this._postprocessing.multisampling=e)}if(this.context.mainCamera){const e=this.context.composer.passes;for(const t of e)if(t.mainCamera&&t.mainCamera!==this.context.mainCamera){this.context.composer.setMainCamera(this.context.mainCamera);break}}}}onDestroy(){this._postprocessing?.dispose()}_lastApplyTime;_rapidApplyCount=0;_isDirty=!1;apply(){if(jo&&console.log(`Apply PostProcessing "${this.name||"unnamed"}"`),T()&&(this._lastApplyTime!==void 0&&Date.now()-this._lastApplyTime<100&&(this._rapidApplyCount++,this._rapidApplyCount===5&&console.warn("Detected rapid post processing modifications - this might be a bug",this)),this._lastApplyTime=Date.now()),this._isDirty=!1,this._activeEffects.length=0,this.sharedProfile?.components){const e=this.sharedProfile.components;for(const t of e)t.active&&t.enabled&&!this._activeEffects.includes(t)&&this._activeEffects.push(t)}for(const e of this._effects)e.active&&e.enabled&&!this._activeEffects.includes(e)&&this._activeEffects.push(e);this._activeEffects.length>0?(this._postprocessing||(this._postprocessing=new my(this.context)),this._postprocessing.apply(this._activeEffects)?.then(()=>{this.activeAndEnabled&&(this._applyPostQueue(),this._postprocessing?(this.multisampling==="auto"?this._postprocessing.multisampling=exports.DeviceUtilities.isMobileDevice()?2:4:this._postprocessing.multisampling=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples)),jo&&console.debug(`[PostProcessing] Set multisampling to ${this._postprocessing.multisampling} (Is Mobile: ${exports.DeviceUtilities.isMobileDevice()})`)):jo&&console.warn("[PostProcessing] No composer found"))})):this._postprocessing?.unapply(!1)}_applyPostQueue(){if(this._modificationQueue){for(const e of this._modificationQueue.values())this.onEditorModification(e);this._modificationQueue.clear()}}onEditorModification(e){if(e.propertyName.startsWith("postprocessing.")){if(!this._postprocessing)return this._modificationQueue||(this._modificationQueue=new Map),this._modificationQueue.set(e.propertyName,e),!0;if(!this._activeEffects?.length)return;const t=e.propertyName.split(".");if(t.length===3||t.length===4){const i=t[1],n=t[2];for(const o of this._activeEffects)if(o.typeName?.toLowerCase()===i.toLowerCase()){if(n==="active"){o.active=e.value,this.scheduleRecreate();return}if(!id.has(i)){const r=new Array;id.set(i,r);const a=Object.keys(o);for(const l of a)o[l]instanceof F&&r.push(l)}if(id.has(i)){const r=n.toLowerCase(),a=id.get(i);for(const l of a)if(l.toLowerCase()===r){const h=o[l];h instanceof F&&(t.length===4&&t[3]==="active"?(h.overrideState=e.value,this.scheduleRecreate()):h&&h.value!==void 0&&(h.value=e.value));return}}console.warn("Unknown modification",n);return}}return!0}return!1}_modificationQueue;_recreateId=-1;scheduleRecreate(){const e=++this._recreateId;setTimeout(()=>{e===this._recreateId&&(this.onDisable(),this.onEnable())},200)}}Yw([ze(zu)],il.prototype,"sharedProfile");Yw([ze()],il.prototype,"multisampling");const id=new Map;nE(il);async function gy(s){const{NeedleEngineWebComponent:e}=await Promise.resolve().then(()=>RT);e.observedAttributes.includes(s)||e.observedAttributes.push(s)}var UE=Object.defineProperty,ht=(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&&UE(e,t,n),n};const nt=x("debugsceneswitcher"),FE=x("sceneswitcher:clearscene"),Cd="scene";gy(Cd);const Fs=Promise.resolve(!1);class Ne extends E{autoLoadFirstScene=!0;scenes=[];loadingScene;queryParameterName="scene";useSceneName=!0;clamp=!0;useHistory=!0;useKeyboard=!0;useSwipe=!0;useSceneLighting=!0;useSceneBackground=!0;preloadNext=1;preloadPrevious=1;preloadConcurrent=2;createMenuButtons=!1;get currentIndex(){return this._currentIndex}get currentLoadingProgress(){return this._currentLoadingProgress}get currentlyLoadingScene(){return this._currentlyLoadingScene}get currentlyLoadedScene(){return this._currentScene}sceneLoadingStart=new oe;sceneLoadingProgress=new oe;sceneLoaded=new oe;_currentIndex=-1;_currentScene=void 0;_currentSceneAsset=void 0;_engineElementOverserver=void 0;_preloadScheduler;_menuButtons;__lastSwitchScene;__lastSwitchScenePromise;awake(){this._currentScene=void 0,this._lastLoadingScene=void 0,this.__lastSwitchScenePromise=void 0,this.scenes===void 0&&(this.scenes=[]);for(const e of this.scenes)e&&!e.hasUrl&&e.asset instanceof c.Object3D?S.remove(e.asset):e instanceof c.Object3D&&S.remove(e);nt&&console.log("SceneSwitcher",this)}async onEnable(){if(globalThis.addEventListener("popstate",this.onPopState),this.context.input.addEventListener(Ce.KeyDown,this.onInputKeyDown),this.context.input.addEventListener(Ce.PointerMove,this.onInputPointerMove),this.context.input.addEventListener(Ce.PointerUp,this.onInputPointerUp),this._engineElementOverserver||(this._engineElementOverserver=new MutationObserver(e=>{for(const t of e)if(t.type==="attributes"&&t.attributeName===Cd){const i=this.context.domElement.getAttribute(Cd);i!==null&&this.trySelectSceneFromValue(i)}})),this._engineElementOverserver.observe(this.context.domElement,{attributes:!0}),this._preloadScheduler||(this._preloadScheduler=new zE(this)),this._preloadScheduler.maxLoadAhead=this.preloadNext,this._preloadScheduler.maxLoadBehind=this.preloadPrevious,this._preloadScheduler.maxConcurrent=this.preloadConcurrent,this._preloadScheduler.begin(2e3),this.autoLoadFirstScene&&this._currentIndex===-1&&!await this.tryLoadFromQueryParam()){const e=this.context.domElement.getAttribute(Cd);(e===null||!await this.trySelectSceneFromValue(e))&&this._currentIndex===-1&&this.select(0)}this.createMenuButtons&&(this._menuButtons??=[],this._menuButtons.push(this.context.menu.appendChild({label:"Previous",icon:"arrow_back_ios",onClick:()=>this.selectPrev(),priority:-1005,class:"row2"})),this._menuButtons.push(this.context.menu.appendChild({label:"Next",icon:"arrow_forward_ios",iconSide:"right",onClick:()=>this.selectNext(),priority:-1e3,class:"row2"})))}onDisable(){if(globalThis.removeEventListener("popstate",this.onPopState),this.context.input.removeEventListener(Ce.KeyDown,this.onInputKeyDown),this.context.input.removeEventListener(Ce.PointerMove,this.onInputPointerMove),this.context.input.removeEventListener(Ce.PointerUp,this.onInputPointerUp),this._preloadScheduler?.stop(),this._menuButtons){for(const e of this._menuButtons)e.remove();this._menuButtons=void 0}}onPopState=async e=>{if(!this.useHistory)return;const t=this.useHistory;try{this.useHistory=!1;let i=!1;if(this.queryParameterName&&(i=await this.tryLoadFromQueryParam()),!i){const n=e?.state;if(n&&n.startsWith(this.guid)){const o=n.substr(this.guid.length+2);nt&&console.log("PopState",o),await this.trySelectSceneFromValue(o)}}}finally{this.useHistory=t}};normalizedSwipeThresholdX=.1;_didSwipe=!1;onInputPointerMove=e=>{if(this.useSwipe&&!this._didSwipe&&e.button===0&&e.pointerType==="touch"&&this.context.input.getPointerPressedCount()===1){const t=this.context.input.getPointerPositionDelta(e.button);if(t){const i=t.x/this.context.domWidth;i>=this.normalizedSwipeThresholdX?(this._didSwipe=!0,this.selectPrev()):i<=-this.normalizedSwipeThresholdX&&(this._didSwipe=!0,this.selectNext())}}};onInputPointerUp=e=>{e.button===0&&(this._didSwipe=!1)};onInputKeyDown=e=>{if(!this.useKeyboard||!this.scenes)return;const t=e.key.toLowerCase();if(!t)return;const i=parseInt(t)-1;if(i>=0){this.trySelectSceneFromValue(i);return}switch(t){case"arrowright":case"d":this.selectNext();break;case"arrowleft":case"a":this.selectPrev();break}};addScene(e){if(typeof e=="string"){let t=this.context.addressables.findAssetReference(e);return t||(t=new K(e),this.context.addressables.registerAssetReference(t)),this.scenes.push(t),t}return this.scenes.push(e),e}selectNext(){return this.select(this._currentIndex+1)}selectPrev(){return this.select(this._currentIndex-1)}select(e){if(nt&&console.log("[SceneSwitcher] select",e),typeof e=="object"&&console.warn('[SceneSwitcher] Switching to "'+e+'" might not work. Please either use an index or a AssetReference (not a scene reference)'),typeof e=="string"){const i=this.scenes?.find(n=>n.url===e);if(!i){const n=K.getOrCreate(this.sourceId??"",e,this.context);return this.switchScene(n)}if(i)e=this.scenes?.indexOf(i);else return Fs}if(!this.scenes?.length)return Fs;if(e<0){if(this.clamp)return Fs;e=this.scenes.length-1}else if(e>=this.scenes.length){if(this.clamp)return Fs;e=0}const t=this.scenes[e];return this.switchScene(t)}unload(){return this.__lastSwitchScene=void 0,this.__lastSwitchScenePromise=void 0,this.__unloadCurrentScene()}async reload(){if(this.__lastSwitchScene){const e=this.__lastSwitchScene;return this.__lastSwitchScene=void 0,this.switchScene(e)}return!1}async switchScene(e){if(!(e instanceof K)){const i=typeof e;if(i==="string")return this.select(e);if(i==="number")return this.select(e);if(e&&e instanceof c.Object3D){const n=this.scenes?.indexOf(e);e=new K(e.name,void 0,e),n>=0&&(this.scenes[n]=e)}else return console.warn(`[SceneSwitcher] Can't switch to scene of type ${i}`),!1}return e.url===this.sourceId?(console.warn("[SceneSwitcher] Can't load own scene - prevent recursive loading",this.sourceId),!1):this.__lastSwitchScene===e&&this.__lastSwitchScenePromise?this.__lastSwitchScenePromise:(this.__lastSwitchScene=e,this.__lastSwitchScenePromise=this.__internalSwitchScene(e),await this.__lastSwitchScenePromise)}async __unloadCurrentScene(){const e=this._currentScene;if(this._currentScene=void 0,e){nt&&console.log("[SceneSwitcher] UNLOAD",e.url,"HasURL?: "+e.hasUrl);const t=this.tryGetSceneEventListener(e.asset);if(t?.sceneClosing){const i=t.sceneClosing();i instanceof Promise&&await i}e.hasUrl?(e.unload(),this._currentSceneAsset&&gi(this._currentSceneAsset,!0,!1)):S.remove(this._currentSceneAsset)}}_currentlyLoadingScene;async __internalSwitchScene(e){await this.__unloadCurrentScene();const t=this._currentIndex=this.scenes?.indexOf(e)??-1;try{nt&&console.debug(`${Date.now()} [SceneSwitcher] Loading scene start: ${e.url} (index: ${t})`),this._currentlyLoadingScene=e,this._currentLoadingProgress=new ProgressEvent("progress",{loaded:0,total:1});const i=new CustomEvent("loadscene-start",{detail:{scene:e,switcher:this,index:t}});this.dispatchEvent(i),this.sceneLoadingStart?.invoke(i.detail),await this.onStartLoading(),await e.loadAssetAsync((o,r)=>{if(nt){const a=r.loaded/r.total,l="["+"=".repeat(Math.floor(a*20))+"-".repeat(20-Math.floor(a*20))+"]";console.debug(`${Date.now()} [SceneSwitcher] Loading scene progress: ${(a*100).toFixed(1)} % ${l}`,e.url)}this._currentLoadingProgress=r,this.dispatchEvent(r),this.sceneLoadingProgress?.invoke(r)}).catch(console.error),await this.onEndLoading();const n=new CustomEvent("loadscene-finished",{detail:{scene:e,switcher:this,index:t}});if(this.dispatchEvent(n),this._currentLoadingProgress=void 0,this._currentlyLoadingScene=void 0,n.defaultPrevented)return nt&&console.warn("[SceneSwitcher] Adding loaded scene prevented:",e,n),!1;if(!e.asset)return nt&&console.warn("[SceneSwitcher] Failed loading scene:",e),!1;if(this._currentIndex===t){if(nt&&console.log("[SceneSwitcher] ADD",e.url),this._currentScene=e,FE){const a=this.context.mainCameraComponent?.gameObject||this.context.mainCamera;a?.removeFromParent();const l=this.gameObject.removeFromParent();gi(this.context.scene,!0,!0),this.context.scene=new c.Scene,this.context.scene.add(l),a&&this.context.scene.add(a)}if(e.asset.parent?this._currentSceneAsset=oo(e.asset,{parent:this.gameObject}):(this._currentSceneAsset=e.asset,S.add(e.asset,this.gameObject)),this.useSceneLighting&&this.context.sceneLighting.enable(e),this.useSceneBackground){const a=this.context.lightmaps.tryGetSkybox(e.url);a?(a.mapping=c.EquirectangularReflectionMapping,this.context.scene.background=a):nt&&console.warn("[SceneSwitcher] Can't find skybox for scene "+e.url)}if(this.useHistory&&t>=0){let a=t.toString();if(this.useSceneName&&(e instanceof c.Object3D?a=e.name:e.url&&(a=bb(e.url))),this.queryParameterName?.length)dc(this.queryParameterName,a,this.useHistory);else{const l=history.state,h=this.guid+"::"+t;l!==h&&history.pushState(h,"unused",location.href)}}const o=this.tryGetSceneEventListener(e.asset);if(o?.sceneOpened){const a=o.sceneOpened(this);a instanceof Promise&&await a}nt&&console.debug(`${Date.now()} [SceneSwitcher] Loading scene finished: ${e.url} (index: ${t})`);const r=new CustomEvent("scene-opened",{detail:{scene:e,switcher:this,index:t}});return this.dispatchEvent(r),this.sceneLoaded?.invoke(this),!0}}catch(i){console.error(i)}return!1}preload(e){if(e>=0&&e<this.scenes.length){const t=this.scenes[e];if(t instanceof K)return t.preload()}return Fs}tryLoadFromQueryParam(){if(!this.queryParameterName?.length)return Fs;const e=x(this.queryParameterName);return typeof e=="boolean"?Fs:this.trySelectSceneFromValue(e)}trySelectSceneFromValue(e){if(typeof e=="string"){const t=parseInt(e);if(t>=0&&t<this.scenes.length)return this.select(t);{const i=e.toLowerCase();for(let n=0;n<this.scenes.length;n++){const o=this.scenes[n];if(!o)continue;if((o instanceof c.Object3D?o.name:bb(o.url)).toLowerCase().includes(i))return this.select(n)}}}else if(typeof e=="number"&&e>=0&&e<this.scenes.length)return this.select(e);return pi()&&console.warn('[SceneSwitcher] Can not find scene: "'+e+'"',this),Fs}_lastLoadingScene=void 0;_loadingScenePromise=void 0;_isCurrentlyLoading=!1;_currentLoadingProgress=void 0;async onStartLoading(){if(this._isCurrentlyLoading=!0,this.loadingScene&&(this._lastLoadingScene!==this.loadingScene&&(this._loadingScenePromise=void 0),this._lastLoadingScene=this.loadingScene,this._loadingScenePromise||(this._loadingScenePromise=this.loadingScene?.loadAssetAsync().then(e=>e!=null)),await this._loadingScenePromise,this._isCurrentlyLoading&&this.loadingScene?.asset)){nt&&console.log("Add loading scene",this.loadingScene.url,this.loadingScene.asset);const e=this.loadingScene.asset;S.add(e,this.gameObject);const t=this.tryGetSceneEventListener(e);if(t?.sceneOpened){const i=t.sceneOpened(this);i instanceof Promise&&await i}}if(this._isCurrentlyLoading){const e=this.tryGetSceneEventListener(this.gameObject);if(e&&e.sceneOpened){const t=e.sceneOpened(this);t instanceof Promise&&await t}}}async onEndLoading(){if(this._isCurrentlyLoading=!1,this.loadingScene?.asset){nt&&console.log("Remove loading scene",this.loadingScene.url);const e=this.loadingScene.asset,t=this.tryGetSceneEventListener(e);if(typeof t?.sceneClosing=="function"){const i=t.sceneClosing();i instanceof Promise&&await i}S.remove(e)}if(!this._isCurrentlyLoading){const e=this.tryGetSceneEventListener(this.gameObject);if(e&&e.sceneClosing){const t=e.sceneClosing();t instanceof Promise&&await t}}}tryGetSceneEventListener(e,t=0){if(!e)return null;const i=S.foreachComponent(e,n=>{const o=n;if(o.sceneClosing||o.sceneOpened)return o});if(t===0&&!i&&e.children.length)for(const n of e.children){const o=this.tryGetSceneEventListener(n,t+1);if(o)return o}return i||null}}ht([f()],Ne.prototype,"autoLoadFirstScene");ht([f(K)],Ne.prototype,"scenes");ht([f(K)],Ne.prototype,"loadingScene");ht([f()],Ne.prototype,"queryParameterName");ht([f()],Ne.prototype,"useSceneName");ht([f()],Ne.prototype,"clamp");ht([f()],Ne.prototype,"useHistory");ht([f()],Ne.prototype,"useKeyboard");ht([f()],Ne.prototype,"useSwipe");ht([f()],Ne.prototype,"useSceneLighting");ht([f()],Ne.prototype,"useSceneBackground");ht([f()],Ne.prototype,"preloadNext");ht([f()],Ne.prototype,"preloadPrevious");ht([f()],Ne.prototype,"preloadConcurrent");ht([f()],Ne.prototype,"createMenuButtons");ht([f(oe)],Ne.prototype,"sceneLoadingStart");ht([f(oe)],Ne.prototype,"sceneLoadingProgress");ht([f(oe)],Ne.prototype,"sceneLoaded");function bb(s){const t=s.split("/").pop()?.split(".").shift();return t?.length?t:s}class zE{maxLoadAhead;maxLoadBehind;maxConcurrent;_isRunning=!1;_switcher;_loadTasks=[];_maxConcurrentLoads=1;constructor(e,t=1,i=1,n=2){this._switcher=e,this.maxLoadAhead=t,this.maxLoadBehind=i,this.maxConcurrent=n}begin(e){if(this._isRunning)return;nt&&console.log("[SceneSwitcher] Preload scheduled",{delay:e}),this._isRunning=!0;let t=-10,i,n;const o=this._switcher.scenes,r=Date.now()+e,a=setInterval(()=>{if(this.allLoaded()&&(nt&&console.log("[SceneSwitcher] All scenes (pre-)loaded"),this.stop()),!this._isRunning){clearInterval(a);return}if(Date.now()<r||this.canLoadNewScene()===!1)return;(t===-10||t!==this._switcher.currentIndex)&&(t=this._switcher.currentIndex,n=0,i=0);const l=n%2===0;l&&(i+=1),n+=1;const h=l?this.maxLoadAhead:this.maxLoadBehind;if(i>h)return;const d=l?t+i:t-i;if(!(d<0)&&!(d<0||d>=o.length)&&!this._loadTasks.some(u=>u.index===d)){const u=o[d];nt&&console.log("[SceneSwitcher] Schedule preload scene",{roomIndex:d,searchForward:l,lastRoom:t,currentIndex:this._switcher.currentIndex,tasks:this._loadTasks.length},u?.url),new NE(d,u,this._loadTasks)}},200)}stop(){this._isRunning=!1}canLoadNewScene(){return this._loadTasks.length<this._maxConcurrentLoads}allLoaded(){if(this._switcher.scenes){for(const e of this._switcher.scenes)if(e?.isLoaded&&e.isLoaded()===!1)return!1}return!0}}class NE{index;asset;tasks;constructor(e,t,i){this.index=e,this.asset=t,this.tasks=i,i.push(this),this.awaitLoading()}async awaitLoading(){this.asset&&!this.asset.isLoaded()&&(nt&&console.log("[SceneSwitcher] Preload start: "+this.asset.url,this.index),await this.asset.preload(),nt&&console.log("[SceneSwitcher] Preload finished: "+this.asset.url,this.index));const e=this.tasks.indexOf(this);e>=0&&this.tasks.splice(e,1)}}function VE(){return new Promise((s,e)=>{const i=()=>{i!=null&&(document.removeEventListener("pointerdown",i),document.removeEventListener("click",i),document.removeEventListener("dragstart",i),document.removeEventListener("touchstart",i),s())};document.addEventListener("pointerdown",i),document.addEventListener("click",i),document.addEventListener("dragstart",i),document.addEventListener("touchstart",i)})}async function $E(s){await VE(),s()}var WE=Object.defineProperty,HE=Object.getOwnPropertyDescriptor,Ci=(s,e,t,i)=>{for(var n=i>1?void 0:i?HE(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&&WE(e,t,n),n};const $e=x("debugvideo");var Kw=(s=>(s[s.None=0]="None",s[s.AdjustHeight=1]="AdjustHeight",s[s.AdjustWidth=2]="AdjustWidth",s))(Kw||{}),Zw=(s=>(s[s.VideoClip=0]="VideoClip",s[s.Url=1]="Url",s))(Zw||{}),Jw=(s=>(s[s.CameraFarPlane=0]="CameraFarPlane",s[s.CameraNearPlane=1]="CameraNearPlane",s[s.RenderTexture=2]="RenderTexture",s[s.MaterialOverride=3]="MaterialOverride",s))(Jw||{});class Je extends E{playOnAwake=!0;aspectMode=0;clip=null;source=1;get url(){return this._url}set url(e){const i=this._url!==e;this.__didAwake?i&&this.setClipURL(e??""):this._url=e}_url=null;renderMode;targetMaterialProperty;targetMaterialRenderer;targetTexture;time=0;_playbackSpeed=1;get playbackSpeed(){return this._videoElement?.playbackRate??this._playbackSpeed}set playbackSpeed(e){this._playbackSpeed=e,this._videoElement&&(this._videoElement.playbackRate=e)}_isLooping=!1;get isLooping(){return this._videoElement?.loop??this._isLooping}set isLooping(e){this._isLooping=e,this._videoElement&&(this._videoElement.loop=e)}get currentTime(){return this._videoElement?.currentTime??this.time}set currentTime(e){this._videoElement?this._videoElement.currentTime=e:this.time=e}get isPlaying(){const e=this._videoElement;if(e){if(e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>e.HAVE_CURRENT_DATA)return!0;if(e.srcObject&&e.srcObject.active)return!0}return!1}get crossOrigin(){return this._videoElement?.crossOrigin??this._crossOrigin}set crossOrigin(e){this._crossOrigin=e,this._videoElement&&(e!==null?this._videoElement.setAttribute("crossorigin",e):this._videoElement.removeAttribute("crossorigin"))}get videoMaterial(){return!this._videoMaterial&&!this.create(!1)?null:this._videoMaterial}get videoTexture(){return!this._videoTexture&&!this.create(!1)?null:this._videoTexture}get videoElement(){return!this._videoElement&&!this.create(!1)?null:this._videoElement}requestPictureInPicture(){return this._videoElement?this._videoElement.requestPictureInPicture():null}get muted(){return this._videoElement?.muted??this._muted}set muted(e){this._muted=e,this._videoElement&&(this._videoElement.muted=e)}_muted=!1;get currentVideo(){return this.clip}set audioOutputMode(e){e!==this._audioOutputMode&&(e===1&&T()&&console.warn("VideoAudioOutputMode.AudioSource is not yet implemented"),this._audioOutputMode=e,this.updateVideoElementSettings())}get audioOutputMode(){return this._audioOutputMode}_audioOutputMode=2;playInBackground=!0;_crossOrigin="anonymous";_videoElement=null;_videoTexture=null;_videoMaterial=null;_isPlaying=!1;wasPlaying=!1;preloadVideo(){$e&&console.log("Video Preload: "+this.name,this.clip),this.create(!1)}preload(){this.preloadVideo()}setVideo(e){this.clip=e,this.source=0,this._videoElement?(this._videoElement.srcObject=e,this._isPlaying&&this.play(),this.updateAspect()):this.create(this.playOnAwake)}setClipURL(e){this._url!==e&&(this._url=e,this.source=1,$e&&console.log("set url",e),this._videoElement?e.endsWith(".m3u8")||e.includes(".m3u")?this.ensureM3UCanBePlayed():(this._videoElement.src=e,this._isPlaying&&(this.stop(),this.play())):this.create(this.playOnAwake))}onEnable(){$e&&console.log("VideoPlayer.onEnable",Zw[this.source],this.clip,this.url,this),window.addEventListener("visibilitychange",this.visibilityChanged),this.playOnAwake===!0?this.create(!0):this.preloadVideo(),this.screenspace?this._overlay?.start():this._overlay?.stop()}onDisable(){window.removeEventListener("visibilitychange",this.visibilityChanged),this._overlay?.stop(),this.pause()}visibilityChanged=e=>{switch(document.visibilityState){case"hidden":this.playInBackground||(this.wasPlaying=this._isPlaying,this.pause());break;case"visible":this.wasPlaying&&!this._isPlaying&&this.play();break}};onDestroy(){this._videoElement&&(this.videoElement?.remove(),this._videoElement=null),this._videoTexture&&(this._videoTexture.dispose(),this._videoTexture=null)}_receivedInput=!1;constructor(){super(),$E(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[],x("videoscreenspace")&&window.addEventListener("keydown",e=>{e.key==="f"&&(this.screenspace=!this.screenspace)})}play(){if(this._videoElement||this.create(!1),!this._videoElement){$e&&console.warn("Can not play: no video element found",this);return}if(!(this._isPlaying&&!this._videoElement?.ended&&!this._videoElement?.paused)){if(this._isPlaying=!0,this._receivedInput||(this._videoElement.muted=!0),this.handleBeginPlaying(!1),this.shouldUseM3U){this.ensureM3UCanBePlayed();return}$e&&console.log("Video Play()",this.clip,this._videoElement,this.time),this._videoElement.currentTime=this.time,this._videoElement.play().catch(e=>{console.log(e),$e&&console.error("Error playing video",e,"CODE="+e.code,this.videoElement?.src,this),setTimeout(()=>{this._isPlaying&&!this.destroyed&&this.activeAndEnabled&&this.play()},1e3)}),$e&&console.log("play",this._videoElement,this.time)}}stop(){this._isPlaying=!1,this.time=0,this._videoElement&&(this._videoElement.currentTime=0,this._videoElement.pause(),$e&&console.log("STOP",this))}pause(){this.time=this._videoElement?.currentTime??0,this._isPlaying=!1,this._videoElement?.pause(),$e&&console.log("PAUSE",this,this.currentTime)}create(e){let t;switch(this.source){case 0:t=this.clip;break;case 1:t=this.url,!t?.length&&typeof this.clip=="string"&&(t=this.clip);break}return t?(this._videoElement||($e&&console.warn("Create VideoElement",this),this._videoElement=this.createVideoElement(),this.context.domElement.shadowRoot.prepend(this._videoElement),this.updateVideoElementStyles()),typeof t=="string"?($e&&console.log("Set Video src",t),this._videoElement.src=t):($e&&console.log("Set Video srcObject",t),this._videoElement.srcObject=t),this._videoTexture||(this._videoTexture=new c.VideoTexture(this._videoElement)),this._videoTexture.flipY=!1,this._videoTexture.colorSpace=c.SRGBColorSpace,e&&this.handleBeginPlaying(e),$e&&console.log("Video: handle playing done...",t,e),!0):($e&&console.warn("No video source set",this),!1)}updateAspect(){this.aspectMode!==0&&this.startCoroutine(this.updateAspectImpl())}_overlay=null;get screenspace(){return this._overlay?.enabled??!1}set screenspace(e){if(e){if(!this._videoTexture)return;this._overlay||(this._overlay=new GE(this.context)),this._overlay.add(this._videoTexture)}else this._overlay?.remove(this._videoTexture);this._overlay&&(this._overlay.enabled=e)}_targetObjects;createVideoElement(){const e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),$e&&console.log("created video element",e),e}handleBeginPlaying(e){if(!this.activeAndEnabled||!this._videoElement)return;this._targetObjects.length=0;let t=this.gameObject;switch(this.renderMode){case 3:t=this.targetMaterialRenderer?.gameObject,t||(t=S.getComponent(this.gameObject,Ht)?.gameObject);break;case 2:console.error("VideoPlayer renderTexture not implemented yet. Please use material override instead");return}if(!t){console.error("Missing target for video material renderer",this.name,Jw[this.renderMode],this);return}const i=t.material;if(i){this._targetObjects.push(t),i!==this._videoMaterial&&(this._videoMaterial=i.clone(),t.material=this._videoMaterial);const n="map",o=this._videoMaterial;if(!this.targetMaterialProperty)$e&&o[n]===void 0&&console.warn(`The target material does not have a '${n}' property, video might not render correctly.`),o[n]=this._videoTexture;else switch(this.targetMaterialProperty){default:$e&&o[this.targetMaterialProperty]===void 0&&console.warn(`The target material does not have a '${this.targetMaterialProperty}' property, video might not render correctly.`),o[n]=this._videoTexture;break}}else{console.warn("Can not play video, no material found, this might be a multimaterial case which is not supported yet");return}this.updateVideoElementSettings(),this.updateVideoElementStyles(),e&&(this.shouldUseM3U&&this.ensureM3UCanBePlayed(),this.play())}updateVideoElementSettings(){if(!this._videoElement)return;this._videoElement.loop=this._isLooping,this._videoElement.currentTime=this.currentTime,this._videoElement.playbackRate=this._playbackSpeed,this._videoElement.playsInline=!0;let e=!this._receivedInput||this.audioOutputMode===0;!e&&this._muted&&(e=!0),this._videoElement.muted=e,this.playOnAwake&&(this._videoElement.autoplay=!0)}updateVideoElementStyles(){this._videoElement&&(this._videoElement.style.userSelect="none",this._videoElement.style.visibility="hidden",this._videoElement.style.display="none",this.updateAspect())}_updateAspectRoutineId=-1;*updateAspectImpl(){const e=++this._updateAspectRoutineId,t=void 0,i=this.clip;for(;e===this._updateAspectRoutineId&&this.aspectMode!==0&&this.clip&&i===this.clip&&this._isPlaying;){if(!i||typeof i=="string")return;let n;for(const o of i.getVideoTracks()){const r=o.getSettings();if(r&&r.width&&r.height){n=r.width/r.height;break}else n=this.context.renderer.domElement.clientWidth/this.context.renderer.domElement.clientHeight}if(n===void 0){for(let o=0;o<10;o++)yield;if(!this.isPlaying)break;continue}if(t===n){yield;continue}for(const o of this._targetObjects){let r=1;if(o.parent){const a=Le(o.parent);r=a.x/a.y}switch(this.aspectMode){case 1:o.scale.y=1/n*o.scale.x*r;break;case 2:o.scale.x=n*o.scale.y*r;break}}for(let o=0;o<3;o++)yield}}get shouldUseM3U(){return this.url!=null&&(this.url.endsWith(".m3u8")||this.url.endsWith(".m3u"))&&this.source===1}ensureM3UCanBePlayed(){if(!this.shouldUseM3U)return;let e=document.head.querySelector("script[data-hls_library]");e?globalThis.Hls?this.onHlsAvailable():e.addEventListener("load",this.onHlsAvailable):($e&&console.log("HLS: load script"),e=document.createElement("script"),e.dataset.hls_library="hls.js",e.src="https://cdn.jsdelivr.net/npm/hls.js@1",e.addEventListener("load",this.onHlsAvailable),document.head.append(e))}_hls;onHlsAvailable=()=>{$e&&console.log("HLS: available",this.clip),!(!this.shouldUseM3U||!this.url)&&(this._hls||(this._hls=new Hls),this.videoElement.autoplay=!0,this._hls.loadSource(this.url),this._hls.attachMedia(this.videoElement),this._videoElement?.play(),$e&&console.log("HLS: loaded",this.clip))}}Ci([f()],Je.prototype,"playOnAwake",2);Ci([f()],Je.prototype,"aspectMode",2);Ci([f(URL)],Je.prototype,"clip",2);Ci([f()],Je.prototype,"source",2);Ci([f(URL)],Je.prototype,"url",1);Ci([f()],Je.prototype,"renderMode",2);Ci([f()],Je.prototype,"targetMaterialProperty",2);Ci([f(Ht)],Je.prototype,"targetMaterialRenderer",2);Ci([f(c.Texture)],Je.prototype,"targetTexture",2);Ci([f()],Je.prototype,"time",2);Ci([f()],Je.prototype,"playbackSpeed",1);Ci([f()],Je.prototype,"isLooping",1);Ci([f()],Je.prototype,"audioOutputMode",1);class GE{context;constructor(e){this.context=e,this._input=new qE(this)}get enabled(){return this._isInScreenspaceMode}set enabled(e){e?this.start():this.stop()}add(e){this._videos.indexOf(e)===-1&&this._videos.push(e)}remove(e){if(!e)return;const t=this._videos.indexOf(e);t>=0&&this._videos.splice(t,1)}start(){if(this._isInScreenspaceMode||this._videos.length<0)return;const e=this._videos[this._videos.length-1];if(!e)return;if(this._isInScreenspaceMode=!0,!this._screenspaceModeQuad){if(this._screenspaceModeQuad=po.createPrimitive(ja.Quad,{material:new XE(e)}),!this._screenspaceModeQuad)return;this._screenspaceModeQuad.geometry.scale(2,2,2)}const t=this._screenspaceModeQuad;this.context.scene.add(t),this.updateScreenspaceMaterialUniforms();const i=t.material;i?.reset(),this._input?.enable(i)}stop(){this._isInScreenspaceMode=!1,this._screenspaceModeQuad&&(this._input?.disable(),this._screenspaceModeQuad.removeFromParent())}updateScreenspaceMaterialUniforms(){const e=this._screenspaceModeQuad?.material;e&&(e.screenAspect=this.context.domElement.clientWidth/this.context.domElement.clientHeight)}_videos=[];_screenspaceModeQuad;_isInScreenspaceMode=!1;_input}class qE{_onResizeScreenFn;_onKeyUpFn;_onMouseWheelFn;context;overlay;constructor(e){this.overlay=e,this.context=e.context}_material;enable(e){this._material=e,window.addEventListener("resize",this._onResizeScreenFn=()=>{this.overlay.updateScreenspaceMaterialUniforms()}),window.addEventListener("keyup",this._onKeyUpFn=n=>{n.key==="Escape"&&this.overlay.stop()}),window.addEventListener("wheel",this._onMouseWheelFn=n=>{this.overlay.enabled&&(e.zoom+=n.deltaY*5e-4,n.preventDefault())},{passive:!1});const t=new c.Vector2;window.addEventListener("mousemove",n=>{if(this.overlay.enabled&&this.context.input.getPointerPressed(0)){const o=new c.Vector2(n.movementX,n.movementY);o.x/=this.context.domElement.clientWidth,o.y/=this.context.domElement.clientHeight,t.set(o.x,o.y),t.multiplyScalar(e.zoom/-this.context.time.deltaTime*.01),e.offset=e.offset.add(t)}}),window.addEventListener("pointermove",n=>{this.overlay.enabled&&this.context.input.getPointerPressed(0)&&this.context.input.getTouchesPressedCount()===1&&(t.set(n.movementX,n.movementY),t.multiplyScalar(e.zoom*-this.context.time.deltaTime*.05),e.offset=e.offset.add(t))});let i=0;window.addEventListener("touchstart",n=>{if(n.touches.length<2){this.context.time.time-i<.3&&this.overlay.stop(),i=this.context.time.time;return}this._isPinching=!0,this._lastPinch=0}),window.addEventListener("touchmove",n=>{if(!this._isPinching||!this._material)return;const o=n.touches[0],r=n.touches[1],a=o.clientX-r.clientX,l=o.clientY-r.clientY,h=Math.sqrt(a*a+l*l);if(this._lastPinch!==0){const d=h-this._lastPinch;this._material.zoom-=d*.004}this._lastPinch=h}),window.addEventListener("touchend",()=>{this._isPinching=!1})}_isPinching=!1;_lastPinch=0;disable(){this._onResizeScreenFn&&(window.removeEventListener("resize",this._onResizeScreenFn),this._onResizeScreenFn=void 0),this._onKeyUpFn&&(window.removeEventListener("keyup",this._onKeyUpFn),this._onKeyUpFn=void 0),this._onMouseWheelFn&&(window.removeEventListener("wheel",this._onMouseWheelFn),this._onMouseWheelFn=void 0)}}class XE extends c.ShaderMaterial{set screenAspect(e){this.uniforms.screenAspect.value=e,this.needsUpdate=!0}set offset(e){const t=this.uniforms.offsetScale.value;t.x=e.x,t.y=e.y,this.uniforms.offsetScale.value=t,this.needsUpdate=!0}_offset=new c.Vector2;get offset(){const e=this.uniforms.offsetScale.value;return this._offset.set(e.x,e.y),this._offset}set zoom(e){const t=this.uniforms.offsetScale.value;e<.001&&(e=.001),t.z=e,this.needsUpdate=!0}get zoom(){return this.uniforms.offsetScale.value.z}reset(){this.offset=this.offset.set(0,0),this.zoom=1,this.needsUpdate=!0}constructor(e){super(),this.uniforms={map:{value:e},screenAspect:{value:1},offsetScale:{value:new c.Vector4(0,0,1,1)}},this.vertexShader=`
|
|
1364
1364
|
uniform sampler2D map;
|
|
1365
1365
|
uniform float screenAspect;
|
|
1366
1366
|
uniform vec4 offsetScale;
|
|
@@ -1413,8 +1413,8 @@ If you need multisampling consider changing 'auto' to a fixed value (e.g. 4).`))
|
|
|
1413
1413
|
gl_FragColor = texcolor;
|
|
1414
1414
|
}
|
|
1415
1415
|
}
|
|
1416
|
-
`}}var QE=Object.defineProperty,YE=Object.getOwnPropertyDescriptor,ph=(s,e,t,i)=>{for(var n=i>1?void 0:i?YE(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&&QE(e,t,n),n};const ft=x("debugscreensharing");var ex=(s=>(s[s.Screen=0]="Screen",s[s.Camera=1]="Camera",s[s.Canvas=2]="Canvas",s[s.Microphone=3]="Microphone",s))(ex||{});class Po extends E{allowStartOnClick=!0;onPointerEnter(){this.context.connection.allowEditing!=!1&&this.allowStartOnClick&&this.context.input.setCursor("pointer")}onPointerExit(){this.context.connection.allowEditing!=!1&&this.allowStartOnClick&&this.context.input.unsetCursor("pointer")}onPointerClick(e){if(this.context.connection.allowEditing!=!1&&this.allowStartOnClick&&!(e&&e.pointerId!==0)){if(this.isReceiving&&this.videoPlayer?.isPlaying){this.videoPlayer&&(this.videoPlayer.screenspace=!this.videoPlayer.screenspace);return}if(this.isSending){this.close();return}this.share()}}autoConnect=!1;set videoPlayer(e){this._videoPlayer&&(this.isSending||this.isReceiving)&&this._videoPlayer.stop(),this._videoPlayer=e,this._videoPlayer&&this._currentStream&&(this.isSending||this.isReceiving)&&this._videoPlayer.setVideo(this._currentStream)}get videoPlayer(){return this._videoPlayer}_videoPlayer;_audioSource;get screenspace(){return this.videoPlayer?.screenspace??!1}set screenspace(e){this.videoPlayer&&(this.videoPlayer.screenspace=e)}device="Screen";deviceName;deviceFilter;get currentScream(){return this._currentStream}get currentMode(){return this._currentMode}get isSending(){return this._currentStream?.active&&this._currentMode===1}get isReceiving(){if(this._currentMode===2){if(!this._currentStream||this._currentStream.active===!1)return!1;const e=this._currentStream.getTracks();for(const t of e)if(t.readyState==="live")return!0}return!1}get requiresVideoPlayer(){return this.device!=="Microphone"}_net;_requestOpen=!1;_currentStream=null;_currentMode=0;awake(){typeof this.device=="number"&&(this.device=ex[this.device]),ft&&console.log("Screensharing",this.name,this),_i.registerWaitForAllowAudio(()=>{this._videoPlayer&&this._currentStream&&this._currentMode===2&&(this._videoPlayer.playInBackground=!0,this._videoPlayer.setVideo(this._currentStream))}),this._net=new qc(this)}onEnable(){this._net?.enable(),this._net?.addEventListener(Ln.StreamReceived,this.onReceiveStream),this._net?.addEventListener(Ln.StreamEnded,this.onCallEnded),this.context.connection.beginListen(Y.JoinedRoom,this.onJoinedRoom),this.autoConnect&&fs(1e3).then(()=>(this.enabled&&this.autoConnect&&!this.isReceiving&&!this.isSending&&this.context.connection.isInRoom&&this.share(),0))}onDisable(){this._net?.removeEventListener(Ln.StreamReceived,this.onReceiveStream),this._net?.removeEventListener(Ln.StreamEnded,this.onCallEnded),this.context.connection.stopListen(Y.JoinedRoom,this.onJoinedRoom),this._net?.disable(),this.close()}onJoinedRoom=async()=>{await fs(1e3),this.autoConnect&&!this.isSending&&!this.isReceiving&&this.context.connection.isInRoom&&this.share()};_ensureVideoPlayer(){const e=new
|
|
1417
|
-
`,i);let n=!1;for(const o of i)try{if(!this._requestOpen){ft&&console.log("Camera selection cancelled");break}if(o.kind!=="videoinput"){ft&&console.log("Skipping non-video device",o);continue}const r=o.deviceId;if(t?.deviceId!=null||t?.deviceFilter!=null){if(t?.deviceId!==void 0&&r!==t.deviceId){ft&&console.log("Skipping device due to options.deviceId: "+o.label+"; "+o.deviceId);continue}if(t?.deviceFilter&&t.deviceFilter(o)===!1){ft&&console.log("Skipping device due to options.deviceFilter: "+o.label+"; "+o.deviceId);continue}}else if(this.deviceFilter)if(this.deviceFilter(o)===!1){ft&&console.log("Skipping device due to ScreenShare.deviceFilter: "+o.label+"; "+o.deviceId);continue}else ft&&console.log("Selected device by filter",o);else if(this.deviceName){const h=o.label.toLowerCase(),d=this.deviceName.toLowerCase(),u=h.includes(d),p=o.deviceId===this.deviceName;if(!u&&!p){ft&&console.log("Skipping device due to ScreenShare.deviceName: "+o.label+"; "+o.deviceId);continue}else ft&&console.log("Selected device by name",o)}e.video!==!1&&((typeof e.video>"u"||typeof e.video=="boolean")&&(e.video={}),e.video.deviceId=r),n=!0;const l=await navigator.mediaDevices.getUserMedia(e).catch(h=>(console.error("Failed to get user media",h),null));if(l===null)continue;this._requestOpen?(this.setStream(l,1),ft&&console.log("Selected camera",o)):(In(l),ft&&console.log("Camera selection cancelled"));break}catch(r){if(r.message==="Failed to allocate videosource"||r.message==="Could not start video source"){ue("Failed to start video: Try another camera (Code "+r.code+")"),console.warn(r);continue}else console.error("Failed to get user media",r.message,r.code,r)}!n&&T()&&(ue("No camera found for sharing. Please connect a camera (see console for more information)"),console.warn("No camera found for sharing. Please connect a camera",i,this.deviceName,"Using deviceFilter? "+this.deviceFilter!=null,"Using options? "+t!=null,"Using deviceName? "+this.deviceName!=null,"Using options.deviceId? "+t?.deviceId!=null,"Using options.deviceFilter? "+t?.deviceFilter!=null))}}ph([f()],Po.prototype,"allowStartOnClick",2);ph([f()],Po.prototype,"autoConnect",2);ph([f(
|
|
1416
|
+
`}}var QE=Object.defineProperty,YE=Object.getOwnPropertyDescriptor,ph=(s,e,t,i)=>{for(var n=i>1?void 0:i?YE(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&&QE(e,t,n),n};const ft=x("debugscreensharing");var ex=(s=>(s[s.Screen=0]="Screen",s[s.Camera=1]="Camera",s[s.Canvas=2]="Canvas",s[s.Microphone=3]="Microphone",s))(ex||{});class Po extends E{allowStartOnClick=!0;onPointerEnter(){this.context.connection.allowEditing!=!1&&this.allowStartOnClick&&this.context.input.setCursor("pointer")}onPointerExit(){this.context.connection.allowEditing!=!1&&this.allowStartOnClick&&this.context.input.unsetCursor("pointer")}onPointerClick(e){if(this.context.connection.allowEditing!=!1&&this.allowStartOnClick&&!(e&&e.pointerId!==0)){if(this.isReceiving&&this.videoPlayer?.isPlaying){this.videoPlayer&&(this.videoPlayer.screenspace=!this.videoPlayer.screenspace);return}if(this.isSending){this.close();return}this.share()}}autoConnect=!1;set videoPlayer(e){this._videoPlayer&&(this.isSending||this.isReceiving)&&this._videoPlayer.stop(),this._videoPlayer=e,this._videoPlayer&&this._currentStream&&(this.isSending||this.isReceiving)&&this._videoPlayer.setVideo(this._currentStream)}get videoPlayer(){return this._videoPlayer}_videoPlayer;_audioSource;get screenspace(){return this.videoPlayer?.screenspace??!1}set screenspace(e){this.videoPlayer&&(this.videoPlayer.screenspace=e)}device="Screen";deviceName;deviceFilter;get currentScream(){return this._currentStream}get currentMode(){return this._currentMode}get isSending(){return this._currentStream?.active&&this._currentMode===1}get isReceiving(){if(this._currentMode===2){if(!this._currentStream||this._currentStream.active===!1)return!1;const e=this._currentStream.getTracks();for(const t of e)if(t.readyState==="live")return!0}return!1}get requiresVideoPlayer(){return this.device!=="Microphone"}_net;_requestOpen=!1;_currentStream=null;_currentMode=0;awake(){typeof this.device=="number"&&(this.device=ex[this.device]),ft&&console.log("Screensharing",this.name,this),_i.registerWaitForAllowAudio(()=>{this._videoPlayer&&this._currentStream&&this._currentMode===2&&(this._videoPlayer.playInBackground=!0,this._videoPlayer.setVideo(this._currentStream))}),this._net=new qc(this)}onEnable(){this._net?.enable(),this._net?.addEventListener(Ln.StreamReceived,this.onReceiveStream),this._net?.addEventListener(Ln.StreamEnded,this.onCallEnded),this.context.connection.beginListen(Y.JoinedRoom,this.onJoinedRoom),this.autoConnect&&fs(1e3).then(()=>(this.enabled&&this.autoConnect&&!this.isReceiving&&!this.isSending&&this.context.connection.isInRoom&&this.share(),0))}onDisable(){this._net?.removeEventListener(Ln.StreamReceived,this.onReceiveStream),this._net?.removeEventListener(Ln.StreamEnded,this.onCallEnded),this.context.connection.stopListen(Y.JoinedRoom,this.onJoinedRoom),this._net?.disable(),this.close()}onJoinedRoom=async()=>{await fs(1e3),this.autoConnect&&!this.isSending&&!this.isReceiving&&this.context.connection.isInRoom&&this.share()};_ensureVideoPlayer(){const e=new Je;e.aspectMode=Kw.AdjustWidth,S.addComponent(this.gameObject,e),this._videoPlayer=e}_activeShareRequest=null;async share(e){return this._activeShareRequest?this._activeShareRequest:(this._activeShareRequest=this.internalShare(e),this._activeShareRequest.then(()=>this._activeShareRequest=null))}async internalShare(e){if(this.context.connection.isInRoom===!1){console.warn("Can not start screensharing: requires network connection"),T()&&ue("Can not start screensharing: requires network connection. Add a SyncedRoom component or join a room first.");return}if(e?.device&&(this.device=e.device),!this.videoPlayer&&this.requiresVideoPlayer&&(this._videoPlayer||(this._videoPlayer=S.getComponent(this.gameObject,Je)??void 0),this.videoPlayer||this._ensureVideoPlayer(),!this.videoPlayer)){console.warn("Can not share video without a videoPlayer assigned");return}this._requestOpen=!0;try{const t=e?.constraints??{echoCancellation:!0,autoGainControl:!1},i={video:t,audio:t},n=i.video;switch(n!==void 0&&typeof n!="boolean"&&(n.width||(n.width={max:1920}),n.height||(n.height={max:1920}),n.aspectRatio||(n.aspectRatio={ideal:1.7777777778}),n.frameRate||(n.frameRate={ideal:24}),n.facingMode||(n.facingMode={ideal:"user"})),this.device){case"Camera":this.tryShareUserCamera(i,e);break;case"Screen":{if(!navigator.mediaDevices.getDisplayMedia){console.error("No getDisplayMedia support");return}const a=await navigator.mediaDevices.getDisplayMedia(i);this._requestOpen?this.setStream(a,1):In(a)}break;case"Canvas":const r=this.context.renderer.domElement.captureStream(0);this.setStream(r,1);break;case"Microphone":{if(!navigator.mediaDevices.getUserMedia){console.error("No getDisplayMedia support");return}i.video=!1;const a=await navigator.mediaDevices.getUserMedia(i);this._requestOpen?this.setStream(a,1):In(a)}break;default:console.error("Can not start screen sharing: Unknown device type",this.device)}}catch(t){if(t.name==="NotAllowedError"){console.log("Selection cancelled"),this._requestOpen=!1;return}console.error("Error opening video",t)}}close(){this._requestOpen=!1,this._currentStream&&(ft&&console.warn("Close current stream / disposing resources, stream was active?",this._currentStream.active),this._net?.stopSendingStream(this._currentStream),In(this._currentStream),this._currentMode=0,this._currentStream=null)}setStream(e,t){if(e===this._currentStream||(this.close(),!e))return;this._currentStream=e,this._requestOpen=!0,this._currentMode=t;const i=this.device!=="Microphone",n=t===1;i?(this._videoPlayer||this._ensureVideoPlayer(),this._videoPlayer?this._videoPlayer.setVideo(e):console.error("No video player assigned for video stream")):(this._audioSource||(this._audioSource=new _i,this._audioSource.spatialBlend=0,this._audioSource.volume=1,this.gameObject.addComponent(this._audioSource)),n||(ft&&console.log("PLAY",e.getAudioTracks()),this._audioSource.volume=1,this._audioSource?.play(e))),n&&this._net?.startSendingStream(e),n&&(this._videoPlayer&&(this._videoPlayer.muted=!0),this._audioSource?.stop());for(const o of e.getTracks())o.addEventListener("ended",()=>{ft&&console.log("Track ended",o),this.close()}),ft&&o.kind==="video"&&console.log(n?"Video →":"Video ←",o.getSettings())}onReceiveStream=e=>{e.stream?.active===!0&&this.setStream(e.stream,2)};onCallEnded=e=>{ft&&console.log("CALL ENDED",this.isReceiving,this?.screenspace),this.isReceiving&&(this.screenspace=!1)};async tryShareUserCamera(e,t){const i=(await navigator.mediaDevices.enumerateDevices()).filter(o=>o.kind==="videoinput");ft&&console.log(`Request camera. These are your kind:videoinput devices:
|
|
1417
|
+
`,i);let n=!1;for(const o of i)try{if(!this._requestOpen){ft&&console.log("Camera selection cancelled");break}if(o.kind!=="videoinput"){ft&&console.log("Skipping non-video device",o);continue}const r=o.deviceId;if(t?.deviceId!=null||t?.deviceFilter!=null){if(t?.deviceId!==void 0&&r!==t.deviceId){ft&&console.log("Skipping device due to options.deviceId: "+o.label+"; "+o.deviceId);continue}if(t?.deviceFilter&&t.deviceFilter(o)===!1){ft&&console.log("Skipping device due to options.deviceFilter: "+o.label+"; "+o.deviceId);continue}}else if(this.deviceFilter)if(this.deviceFilter(o)===!1){ft&&console.log("Skipping device due to ScreenShare.deviceFilter: "+o.label+"; "+o.deviceId);continue}else ft&&console.log("Selected device by filter",o);else if(this.deviceName){const h=o.label.toLowerCase(),d=this.deviceName.toLowerCase(),u=h.includes(d),p=o.deviceId===this.deviceName;if(!u&&!p){ft&&console.log("Skipping device due to ScreenShare.deviceName: "+o.label+"; "+o.deviceId);continue}else ft&&console.log("Selected device by name",o)}e.video!==!1&&((typeof e.video>"u"||typeof e.video=="boolean")&&(e.video={}),e.video.deviceId=r),n=!0;const l=await navigator.mediaDevices.getUserMedia(e).catch(h=>(console.error("Failed to get user media",h),null));if(l===null)continue;this._requestOpen?(this.setStream(l,1),ft&&console.log("Selected camera",o)):(In(l),ft&&console.log("Camera selection cancelled"));break}catch(r){if(r.message==="Failed to allocate videosource"||r.message==="Could not start video source"){ue("Failed to start video: Try another camera (Code "+r.code+")"),console.warn(r);continue}else console.error("Failed to get user media",r.message,r.code,r)}!n&&T()&&(ue("No camera found for sharing. Please connect a camera (see console for more information)"),console.warn("No camera found for sharing. Please connect a camera",i,this.deviceName,"Using deviceFilter? "+this.deviceFilter!=null,"Using options? "+t!=null,"Using deviceName? "+this.deviceName!=null,"Using options.deviceId? "+t?.deviceId!=null,"Using options.deviceFilter? "+t?.deviceFilter!=null))}}ph([f()],Po.prototype,"allowStartOnClick",2);ph([f()],Po.prototype,"autoConnect",2);ph([f(Je)],Po.prototype,"videoPlayer",1);ph([f()],Po.prototype,"device",2);ph([f()],Po.prototype,"deviceName",2);var KE=Object.defineProperty,nl=(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&&KE(e,t,n),n};const ZE=x("debugseethrough");let JE=0;class Ms extends E{referencePoint=null;fadeDuration=.05;minAlpha=0;useAlphaHash=!0;set needsUpdate(e){this._needsUpdate=e}get needsUpdate(){return this._needsUpdate}overrideAlpha=-1;autoUpdate=!0;_referencePointVector=new c.Vector3;_referencePointDir=new c.Vector3;_distance=0;_renderer=null;_needsUpdate=!0;_id=JE++;onEnable(){this._needsUpdate=!0,this._renderer=null,oc.components.push(this)}onDisable(){this._renderer?.forEach(t=>{const i=this.rendererMaterialsOriginal.get(t);for(let n=0;n<t.sharedMaterials.length;n++)t.sharedMaterials[n]&&i&&i[n]&&(t.sharedMaterials[n]=i[n]);this.rendererMaterials.delete(t),this.rendererMaterialsOriginal.delete(t)});const e=oc.components.indexOf(this);e!==-1&&oc.components.splice(e,1)}update(){if(this._needsUpdate?(this._needsUpdate=!1,this._renderer=this.gameObject.getComponentsInChildren(Ht),this.updateDirection()):this.autoUpdate&&(this.context.time.frame+this._id)%20===0&&this.updateDirection(),!this.autoUpdate||!this.referencePoint)return;const t=this._referencePointDir.dot(this.context.mainCamera.worldForward)>.2;if(ZE&&this.referencePoint){const i=this.gameObject.worldPosition;j.DrawArrow(B(i),i.sub(this._referencePointDir),t?16711680:65280),j.DrawWireSphere(this.referencePoint.worldPosition,.05,255)}t?this.updateAlpha(this.minAlpha,this.fadeDuration):this.updateAlpha(1,this.fadeDuration)}rendererMaterials=new WeakMap;rendererMaterialsOriginal=new WeakMap;updateDirection(){this.referencePoint??=this.context.scene,this._referencePointVector.copy(this.gameObject.worldPosition.sub(this.referencePoint.worldPosition)),this._distance=this._referencePointVector.length(),this._referencePointDir.copy(this._referencePointVector).multiply(B(1,.5,1)).normalize()}updateAlpha(e,t=this.fadeDuration){this.overrideAlpha!==void 0&&this.overrideAlpha!==-1&&(e=this.overrideAlpha),this._renderer?.forEach(i=>{if(e<.9?i.gameObject.raycastAllowed=!1:i.gameObject.raycastAllowed=!0,!this.rendererMaterials.has(i)){const o=new Array,r=new Array;for(let a=0;a<i.sharedMaterials.length;a++){const l=i.sharedMaterials[a];if(!l)continue;o.push(l);const h=l.clone();h.userData=l.userData||{},h.userData.seeThrough={initial:{opacity:h.opacity,transparent:h.transparent,alphaHash:h.alphaHash}},r.push(h),i.sharedMaterials[a]=h}this.rendererMaterials.set(i,r),this.rendererMaterialsOriginal.set(i,o)}const n=i.hasLightmap?i.sharedMaterials:this.rendererMaterials.get(i);if(n)for(const o of n){if(!o)continue;let r=I.lerp(o.opacity,e,t<=0?1:this.context.time.deltaTime/t);r>=.99?r=1:r<=.01&&(r=0);const a=o.transparent,l=o.alphaHash,h=o.opacity;if(o.alphaHash=this.useAlphaHash,o.userData&&"seeThrough"in o.userData){const d=o.userData.seeThrough.initial;o.opacity=d.opacity*r,o.transparent=o.opacity>=1?d.transparent:!this.useAlphaHash}else o.transparent=o.opacity>=1?!1:!this.useAlphaHash;(a!==o.transparent||l!==o.alphaHash||o.opacity!==h)&&(o.needsUpdate=!0)}})}}nl([f(c.Object3D)],Ms.prototype,"referencePoint");nl([f()],Ms.prototype,"fadeDuration");nl([f()],Ms.prototype,"minAlpha");nl([f()],Ms.prototype,"useAlphaHash");nl([f()],Ms.prototype,"overrideAlpha");nl([f()],Ms.prototype,"autoUpdate");class oc{static components=[];get extensionName(){return"SeeThrough"}}const vb=new oc;an.beforeExport.addEventListener(s=>{oc.components.length!==0&&s.exporter.extensions.includes(vb)===!1&&s.exporter.extensions.push(vb)});var eR=Object.defineProperty,tx=(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&&eR(e,t,n),n};class mh extends E{mode=0;shadowColor=new ee(0,0,0,1);targetMesh;start(){if(this.gameObject instanceof c.Mesh)this.gameObject instanceof c.Mesh&&this.gameObject.material&&(this.gameObject.material=this.gameObject.material.clone(),this.targetMesh=this.gameObject,this.targetMesh.receiveShadow=!0);else{const e=po.createPrimitive(ja.Quad,{name:"ShadowCatcher",material:new c.MeshStandardMaterial({color:10066329,roughness:1,metalness:0,transparent:!0})});e.receiveShadow=!0,e.geometry.rotateX(-Math.PI/2),this.gameObject.add(e),this.targetMesh=e}if(!this.targetMesh){console.warn("ShadowCatcher: no mesh to apply shadow catching to. Groups are currently not supported.");return}switch(this.targetMesh.layers.set(2),this.mode){case 0:this.applyShadowMaterial();break;case 1:this.applyLightBlendMaterial();break;case 2:this.applyOccluderMaterial();break}}applyLightBlendMaterial(){if(!this.targetMesh)return;const e=this.targetMesh.material;e.blending=c.AdditiveBlending,this.applyMaterialOptions(e),e.onBeforeCompile=t=>{t.fragmentShader=t.fragmentShader.replace("vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;",`vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
|
|
1418
1418
|
// diffuse-only lighting with overdrive to somewhat compensate
|
|
1419
1419
|
// for the loss of indirect lighting and to make it more visible.
|
|
1420
1420
|
vec3 direct = (reflectedLight.directDiffuse + reflectedLight.directSpecular) * 6.6;
|
|
@@ -1429,7 +1429,7 @@ To allow joining a room without a query parameter you can set "requireRoomParame
|
|
|
1429
1429
|
Please choose one of the following options to fix this:
|
|
1430
1430
|
A) Set a room name in the SyncedRoom component
|
|
1431
1431
|
B) Set a room name in the URL parameter "?`+this.urlParameterName+`=my_room"
|
|
1432
|
-
C) Set "joinRandomRoom" to true`),!1):(up&&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()):T()&&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(dp,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}setRandomRoomUrlParameter(){const e=Tc(),t=this.generateRoomName();x(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),ym(t,e)}generateRoomName(){let e="";for(let t=0;t<6;t++)e+=Math.floor(Math.random()*10).toFixed(0);return e}_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&&dc(this.urlParameterName,null),this.context.connection.leaveRoom(),this._userWantsToBeInARoom=!1;else{if(this.urlParameterName){const t=x(this.urlParameterName);(!t||t===!0)&&(this._lastJoinedRoom?dc(this.urlParameterName,this._lastJoinedRoom):this.setRandomRoomUrlParameter())}this.tryJoinRoom()}},this._roomButtonIconJoin=yt("group"),this._roomButtonIconLeave=yt("group_off"),this.updateRoomButtonState(),this.context.connection.beginListen(Y.JoinedRoom,this.updateRoomButtonState),this.context.connection.beginListen(Y.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(Y.JoinedRoom,this.updateRoomButtonState),this.context.connection.stopListen(Y.LeftRoom,this.updateRoomButtonState)}_viewOnlyButton;onEnableViewOnlyButton(){this.context.connection.isConnected?this.onCreateViewOnlyButton():(this.context.connection.stopListen(Y.JoinedRoom,this.onCreateViewOnlyButton),this.context.connection.beginListen(Y.JoinedRoom,this.onCreateViewOnlyButton))}onDisableViewOnlyButton(){this.context.connection.stopListen(Y.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),we("View only URL copied to clipboard")):ue("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(yt("visibility"))}this.context.menu.appendChild(this._viewOnlyButton)}}Oo([f()],_n.prototype,"roomName",2);Oo([f()],_n.prototype,"urlParameterName",2);Oo([f()],_n.prototype,"joinRandomRoom",2);Oo([f()],_n.prototype,"requireRoomParameter",2);Oo([f()],_n.prototype,"autoRejoin",2);Oo([f()],_n.prototype,"createJoinButton",2);Oo([f()],_n.prototype,"createViewOnlyButton",2);Oo([f()],_n.prototype,"roomPrefix",1);function PR(){const s=x("testwindowcount")||0;s&&s>0&&MR(s)}function MR(s){if(x("testwindow"))return null;const e=new URL(window.location.href);wp(e.searchParams,pM,1),wp(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 p=0;p<i.length;p++){const m=i[p];m!==u&&m.close()}i.length=0}}}return i}class _y extends E{awake(){PR()}}class by extends E{transformsPerFrame=10;interval=0;useFlatbuffers=!0;awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinary(bc,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new OR(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 re.Builder(1024));const e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();const i=F0(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 OR{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 kR=Object.defineProperty,Qu=(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&&kR(e,t,n),n};const ER=x("debugsignals");class Yu{guid}Qu([f()],Yu.prototype,"guid");class bh{signal;reaction}Qu([f(Yu)],bh.prototype,"signal");Qu([f(oe)],bh.prototype,"reaction");const rx=class es extends E{static receivers={};static invoke(e){if(es.receivers[e]){const t=es.receivers[e];if(!t)return;for(const i of t)i.invoke(e)}}events;awake(){ER&&console.log("SignalReceiver awake",this)}onEnable(){if(this.events)for(const e of this.events)es.receivers[e.signal.guid]||(es.receivers[e.signal.guid]=[]),es.receivers[e.signal.guid].push(this)}onDisable(){if(this.events){for(const e of this.events)if(es.receivers[e.signal.guid]){const t=es.receivers[e.signal.guid].indexOf(this);t>=0&&es.receivers[e.signal.guid].splice(t,1)}}}invoke(e){if(!this.events||!Array.isArray(this.events))return;const t=typeof e=="object"?e.guid:e;for(const i of this.events)if(i.signal.guid===t)try{if(i.reaction){if(!i.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",i,this);continue}}else{console.warn("Missing reaction for signal",i,this);continue}i.reaction.invoke()}catch(n){console.error(n)}}};Qu([f(bh)],rx.prototype,"events");let vh=rx;var ci=(s=>(s.Activation="ActivationTrack",s.Animation="AnimationTrack",s.Audio="AudioTrack",s.Control="ControlTrack",s.Marker="MarkerTrack",s.Signal="SignalTrack",s))(ci||{}),Pn=(s=>(s[s.None=0]="None",s[s.Hold=1]="Hold",s[s.Loop=2]="Loop",s[s.PingPong=3]="PingPong",s[s.Continue=4]="Continue",s))(Pn||{}),vy=(s=>(s.Signal="SignalEmitter",s))(vy||{});const Bn=x("debugtimeline");class ol{director;track;get muted(){return this.track.muted}set muted(e){e!==this.track.muted&&(this.track.muted=e,this.onMuteChanged?.call(this))}*forEachClip(e=!1){if(this.track?.clips)if(e)for(let t=this.track.clips.length-1;t>=0;t--)yield this.track.clips[t];else for(const t of this.track.clips)yield t}getClipTime(e,t){return t.clipIn+(e-t.start)*t.timeScale}getClipTimeNormalized(e,t){return(e-t.start)/t.duration}evaluateWeight(e,t,i,n=!0){if(t<0||t>=i.length)return 0;const o=i[t];if(n||e>=o.start&&e<=o.end){let r=1;if(o.easeInDuration>0){const a=Math.min((e-o.start)/o.easeInDuration,1);r*=a}if(o.easeOutDuration>0){const a=Math.min((o.end-e)/o.easeOutDuration,1);r*=a}return r}return 0}}class RR{clip;rootPositionOffset;rootQuaternionOffset;get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}rootStartPosition;rootEndPosition;rootStartQuaternion;rootEndQuaternion;constructor(e){const t=e.getClip();this.clip=t;const i=e.getRoot(),n=i.name+".position",o=i.name+".quaternion";Bn&&console.log(t.name,t.tracks,n);for(const r of t.tracks)if(!(r.times.length<=0)){if(r.name.endsWith(n))this.rootStartPosition=new c.Vector3().fromArray(r.values,0),this.rootEndPosition=new c.Vector3().fromArray(r.values,r.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),Bn&&console.log(this.rootPositionOffset);else if(r.name.endsWith(o)&&(this.rootStartQuaternion=new c.Quaternion().fromArray(r.values,0),this.rootEndQuaternion=new c.Quaternion().fromArray(r.values,r.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),Bn)){const a=new c.Euler().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",a)}}}}class Oc extends ol{models=[];trackOffset;target;mixer;clips=[];actions=[];weight=1;_actionOffsets=[];_didBind=!1;_animator=null;onDisable(){this.mixer?.stopAllAction()}onDestroy(){this.director.context.animations.unregisterAnimationMixer(this.mixer)}onStateChanged(){this._animator&&j_(this._animator.gameObject,this,this.director.enabled&&this.director.weight>0)}createHooks(e,t){if(t.tracks?.length<=0){console.warn("No tracks in AnimationClip",t);return}let i=!1,n=!1;const o=t.tracks.find(r=>r.name.includes(".position")||r.name.includes(".quaternion"))?.name.split(".");if(o){const r=o[o.length-2],a=r+".position",l=r+".quaternion";for(const h of t.tracks)!i&&h.name.endsWith(a)?(i=!0,this.createPositionInterpolant(t,e,h)):!n&&h.name.endsWith(l)&&(n=!0,this.createRotationInterpolant(t,e,h))}if(!i||!n){const r=this.mixer?.getRoot(),a=t.tracks[0],l=a.name.lastIndexOf("."),h=a.name.substring(0,l),d=h.substring(h.lastIndexOf(".")+1),u=r.getObjectByName(d);if(u)if(i){if(!n){const p=t.tracks[0].name.substring(0,l)+".quaternion";Bn&&console.warn("Create quaternion track",d,u);const m=new c.QuaternionKeyframeTrack(p,[0,t.duration],[0,0,0,1,0,0,0,1]);t.tracks.push(m),this.createRotationInterpolant(t,e,m)}}else{const p=h+".position";Bn&&console.warn("Create position track",d,u);const m=new c.VectorKeyframeTrack(p,[0,t.duration],[0,0,0,0,0,0]);t.tracks.push(m),this.createPositionInterpolant(t,e,m)}}}bind(){if(!this._didBind){this._didBind=!0,Bn&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(const e of this.actions){const t=new RR(e);this._actionOffsets.push(t)}this.target&&(this._animator=S.getComponent(this.target,at)??null,this._animator&&j_(this._animator.gameObject,this,!0));for(const e of this.models){const t=e.asset,i=t.position,n=t.rotation;i&&i.x!==void 0&&(i.isVector3||(t.position=new c.Vector3(i.x,i.y,i.z)),n.isQuaternion||(t.rotation=new c.Quaternion(n.x,n.y,n.z,n.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){const e=this.trackOffset.position;e&&(e.isVector3||(this.trackOffset.position=new c.Vector3(e.x,e.y,e.z)));const t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new c.Quaternion(t.x,t.y,t.z,t.w)))}}_useclipOffsets=!0;_totalOffsetPosition=new c.Vector3;_totalOffsetRotation=new c.Quaternion;_totalOffsetPosition2=new c.Vector3;_totalOffsetRotation2=new c.Quaternion;_summedPos=new c.Vector3;_tempPos=new c.Vector3;_summedRot=new c.Quaternion;_tempRot=new c.Quaternion;_clipRotQuat=new c.Quaternion;evaluate(e){if(this.track.muted||!this.mixer)return;this.bind(),this._totalOffsetPosition.set(0,0,0),this._totalOffsetRotation.set(0,0,0,1),this._totalOffsetPosition2.set(0,0,0),this._totalOffsetRotation2.set(0,0,0,1);let t=0,i=0,n=!1,o=!1,r=0;for(let a=0;a<this.clips.length;a++){const l=this.models[a],h=this.actions[a],d=l.asset;h.weight=0;const u=e>=l.start&&e<=l.end,p=l.preExtrapolationMode,m=l.postExtrapolationMode,g=a<this.clips.length-1?this.models[a+1]:null;let _=u,y=!1;if(!_&&!n&&l.end<e&&m!==Pn.None?(!g||g.start>e)&&(_=!0,n=!0):a==0&&!_&&!o&&l.start>e&&p!==Pn.None&&(!g||g.start<e)&&(_=!0,y=!0,o=!0),_){let v=this.weight;v*=this.evaluateWeight(e,a,this.models,_),v*=this.director.weight;let b=u;if(y)switch(p){case Pn.Hold:break;case Pn.Loop:e+=l.start,b=!0;break;default:e+=l.start,b=!0;break}let w=this.getClipTime(e,l),R=0;const M=d.duration;if(y&&p===Pn.Hold&&(w=0),b){if(d.loop)for(R+=Math.floor(w/(M+1e-6));w>M;)w-=M}else if(!u&&n)switch(m){case Pn.Hold:w=this.getClipTime(l.end,l);break;case Pn.Loop:w%=M;break;case Pn.PingPong:const D=Math.floor(w/M)%2!==0;w%=M,D&&(w=M-w);break}l.reversed===!0?h.time=h.getClip().duration-w:h.time=w,h.timeScale=0;const O=Math.max(0,v);if(h.weight=O,r+=O,h.clampWhenFinished=!1,h.isRunning()||h.play(),this._useclipOffsets){const A=t==0?this._totalOffsetPosition:this._totalOffsetPosition2,D=t==0?this._totalOffsetRotation:this._totalOffsetRotation2;t<1&&(i=1-v),t+=1;const L=this._summedPos.set(0,0,0),N=this._tempPos.set(0,0,0),$=this._summedRot.identity(),k=this._tempRot.identity(),z=d.rotation;z&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp(z,v));const V=this._actionOffsets[a];if(V.hasOffsets)for(let J=0;J<R;J++)V.rootPositionOffset?N.copy(V.rootPositionOffset):N.set(0,0,0),N.applyQuaternion($),this._clipRotQuat&&N.applyQuaternion(this._clipRotQuat),V.rootQuaternionOffset&&(k.copy(V.rootQuaternionOffset),$.multiply(k)),L.add(N);this._clipRotQuat&&D.multiply(this._clipRotQuat),D.multiply($),d.position&&L.add(d.position),A.add(L)}}}if(this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,i),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,i)),this.__mixerError===void 0&&(Bn||T())&&this._animator?.runtimeAnimatorController?.mixer&&this.mixer!==this._animator?.runtimeAnimatorController?.mixer&&(this.__mixerError=!0,console.error("AnimationTrack mixer is not shared with the animator controller - this might result in the timeline to not animate properly. Please report a bug to the Needle Engine team!",this)),this._animator?.runtimeAnimatorController){const a=Math.max(0,1-r);this._animator?.runtimeAnimatorController?.update(a)}else this.mixer.update(e)}createRotationInterpolant(e,t,i){const n=i.createInterpolant.bind(i),o=new c.Quaternion;this.ensureTrackOffsets();const r=this.trackOffset?.rotation;i.createInterpolant=()=>{const a=n(),l=a.evaluate.bind(a);return a.evaluate=h=>{const d=l(h);if(o.set(d[0],d[1],d[2],d[3]),o.premultiply(this._totalOffsetRotation),r&&o.premultiply(r),this.director.animationCallbackReceivers)for(const u of this.director.animationCallbackReceivers)u?.onTimelineRotation?.call(u,this.director,this.target,h,o);return d[0]=o.x,d[1]=o.y,d[2]=o.z,d[3]=o.w,d},a}}createPositionInterpolant(e,t,i){const n=i.createInterpolant.bind(i),o=new c.Vector3;this.ensureTrackOffsets();const r=this.trackOffset?.rotation,a=this.trackOffset?.position;let l;i.createInterpolant=()=>{const h=n(),d=h.evaluate.bind(h);return h.evaluate=u=>{const p=d(u);if(o.set(p[0],p[1],p[2]),t.removeStartOffset&&(l===void 0?(l=null,l=this._actionOffsets.find(m=>m.clip===e)?.rootStartPosition?.clone()):l?.isVector3&&o.sub(l)),o.applyQuaternion(this._totalOffsetRotation),o.add(this._totalOffsetPosition),r&&o.applyQuaternion(r),a&&(o.x-=a.x,o.y+=a.y,o.z+=a.z),this.director.animationCallbackReceivers)for(const m of this.director.animationCallbackReceivers)m?.onTimelinePosition?.call(m,this.director,this.target,u,o);return p[0]=o.x,p[1]=o.y,p[2]=o.z,p},h}}}const TR=x("mutetimeline");class cs extends ol{models=[];listener;audio=[];audioContextTimeOffset=[];lastTime=0;audioSource;_audioLoader=null;getAudioFilePath(e){const t=this.director.sourceId;return ho(t,e)}onAllowAudioChanged(e){for(let t=0;t<this.models.length;t++){const i=this.models[t];this.audio[t].setVolume(e?i.asset.volume:0)}}addModel(e){const t=new c.Audio(this.listener);this.audio.push(t);const i=e;i._didTriggerPlay=!1,this.models.push(i)}onDisable(){for(const e of this.audio)e.isPlaying&&e.stop();for(const e of this.models)e._didTriggerPlay=!1}onDestroy(){for(const e of this.audio)e.source&&e?.disconnect();this.audio.length=0}onMuteChanged(){if(this.muted)for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t?.isPlaying&&t.stop()}}stop(){for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t?.isPlaying&&t.stop()}for(const e of this.models)e._didTriggerPlay=!1}_playableDirectorResumed=!1;onPauseChanged(){for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t?.isPlaying&&t.stop()}this._playableDirectorResumed=this.director.isPlaying}evaluate(e){if(TR||this.track.muted||this.director.speed<0)return;const t=this.director.context.application.muted,i=this._playableDirectorResumed;this._playableDirectorResumed=!1;const n=t?.1:0;for(let o=0;o<this.models.length;o++){const r=this.models[o],a=this.audio[o],l=r.asset;if((!a||!a.buffer)&&this.isInTimeRange(r,e-1,e+1)&&this.handleAudioLoading(r,a),_i.userInteractionRegistered!==!1&&!(a===null||!a.buffer))if(a.playbackRate=this.director.context.time.timeScale*this.director.speed,a.loop=l.loop,e>=r.start&&e<=r.end&&e<this.director.duration){if(!a.isPlaying||!this.director.isPlaying)(i||!r._didTriggerPlay&&this.lastTime<e)&&(r.duration*r.timeScale>.3?a.offset=r.clipIn+(e-r.start)*r.timeScale:a.offset=0,Bn&&console.log("Timeline Audio ("+this.track.name+") play with offset "+a.offset+" - "+r.asset.clip),a.play(n),r._didTriggerPlay=!0);else{const d=r.clipIn+(e-r.start)*r.timeScale,u=a.context.currentTime-a._startedAt+a.offset;Math.abs(d-u)>.3&&(a.offset=d,a.stop(),a.play(n))}let h=l.volume;if(this.track.volume!==void 0&&(h*=this.track.volume),t&&(h=0),r.easeInDuration>0){const d=Math.min((e-r.start)/r.easeInDuration,1);h*=d}if(r.easeOutDuration>0){const d=Math.min((r.end-e)/r.easeOutDuration,1);h*=d}a.setVolume(h*this.director.weight)}else r._didTriggerPlay=!1,this.director.isPlaying&&a.isPlaying&&a.stop()}this.lastTime=e}loadAudio(e,t=0,i=0){let n=null;const o=e-i,r=e+t;for(const a of this.models)if(this.isInTimeRange(a,o,r)){const l=this.audio[this.models.indexOf(a)],h=this.handleAudioLoading(a,l);h!==null&&(n===null&&(n=[]),n.push(h))}return n!==null?Promise.all(n):null}isInTimeRange(e,t,i){return t<=e.start&&i>=e.end||t>=e.start&&t<=e.end||i>=e.start&&i<=e.end}static _audioBuffers=new Map;static dispose(){cs._audioBuffers.clear()}handleAudioLoading(e,t){this._audioLoader||(this._audioLoader=new c.AudioLoader);const i=this.getAudioFilePath(e.asset.clip);if(cs._audioBuffers.get(i)){const o=cs._audioBuffers.get(i);return o.then(r=>{r&&t.setBuffer(r)}),o}Bn&&console.warn("LOAD audio track",i,this.director.sourceId);const n=new Promise((o,r)=>{this._audioLoader.load(i,a=>{t.setBuffer(a),o(a)},void 0,a=>{console.error("Error loading audio",a),o(null)})});return cs._audioBuffers.set(i,n),n}}class Ku extends ol{models=[];needsSorting=!0;*foreachMarker(e=null){this.needsSorting&&this.sort();for(const t of this.models)t&&t.type===e&&(yield t)}onEnable(){this.needsSorting=!0}evaluate(e){this.needsSorting&&this.sort()}sort(){this.needsSorting=!1,this.models.sort((e,t)=>e.time-t.time)}}class kc extends ol{models=[];didTrigger=[];receivers=[];evaluate(e){if(this.track.muted)return;const t=this.director.context.time.deltaTime*1.5;for(let i=0;i<this.models.length;i++){const n=this.models[i],o=this.didTrigger[i],r=n.time-e;let a=!1;if(n.retroActive)a=r<=1e-6;else{const l=Math.abs(r);(l===0||l>=1e-5&&l<t)&&(a=!0)}if(a){if(!o)if(Bn&&console.log("Trigger signal",e,n.time,n),this.didTrigger[i]=!0,this.receivers?.length<=0)vh.invoke(n.asset);else for(const l of this.receivers)l&&l.invoke(n.asset)}else n.emitOnce||(this.didTrigger[i]=!1)}}}class Zu extends ol{models=[];timelines=[];resolveSourceObjects(e){for(let t=this.models.length-1;t>=0;t--){const n=this.models[t].asset;if(!n.sourceObject||typeof n.sourceObject!="object"){console.log("no source object, removing model",t,n),this.models.splice(t,1);continue}else{const o=S.getComponent(n.sourceObject,pr);this.timelines.push(o),o&&n.updateDirector&&(o.playOnAwake=!1)}}}_previousActiveModel=null;evaluate(e){this._previousActiveModel=null;for(let t=0;t<this.models.length;t++){const i=this.models[t],n=i.asset;if(e>=i.start&&e<=i.end){this._previousActiveModel=i;const o=this.getClipTime(e,i);if(n.controlActivation){const r=n.sourceObject;r.visible=!0}if(n.updateDirector){const r=this.timelines[t];r&&(r.isPlaying&&r.pause(),r.time=o,r.evaluate())}}else{const o=this._previousActiveModel?.asset;if(n.controlActivation){const r=n.sourceObject;o?.sourceObject!==r&&(r.visible=!1)}}}}}var AR=Object.defineProperty,ax=(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&&AR(e,t,n),n};const tn=x("debugtimeline"),wy=class um extends E{static createTrackFunctions={};static registerCreateTrack(e,t){this.createTrackFunctions[e]=t}playableAsset;playOnAwake;extrapolationMode=1;get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(e){typeof e=="number"&&!Number.isNaN(e)?this._time=e:(tn||pi())&&console.error("INVALID TIMELINE.TIME VALUE",e,this.name)}get duration(){return this._duration}set duration(e){this._duration=e}get weight(){return this._weight}set weight(e){this._weight=e}get speed(){return this._speed}set speed(e){this._speed=e}waitForAudio=!0;_visibilityChangeEvt;_clonedPlayableAsset=!1;_speed=1;awake(){tn&&console.log(`[Timeline] Awake '${this.name}'`,this),this.rebuildGraph(),!this.isValid()&&(tn||T())&&(tn?console.warn("PlayableDirector is not valid","Asset?",this.playableAsset,"Tracks:",this.playableAsset?.tracks,"IsArray?",Array.isArray(this.playableAsset?.tracks),this):this.playableAsset?.tracks?.length?console.warn("PlayableDirector is not valid"):console.warn("PlayableDirector has no tracks"))}onEnable(){tn&&console.log("[Timeline] OnEnable",this.name,this.playOnAwake);for(const e of this._audioTracks)e.onEnable?.();for(const e of this._customTracks)e.onEnable?.();for(const e of this._animationTracks)e.onEnable?.();this.playOnAwake&&this.play(),this._visibilityChangeEvt||(this._visibilityChangeEvt=()=>{switch(document.visibilityState){case"hidden":this.setAudioTracksAllowPlaying(!1);break;case"visible":this.setAudioTracksAllowPlaying(!0);break}}),window.addEventListener("visibilitychange",this._visibilityChangeEvt)}onDisable(){tn&&console.log("[Timeline] OnDisable",this.name),this.stop();for(const e of this._audioTracks)e.onDisable?.();for(const e of this._customTracks)e.onDisable?.();for(const e of this._animationTracks)e.onDisable?.();this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){for(const e of this._allTracks)for(const t of e)t.onDestroy?.()}rebuildGraph(){this.isValid()&&(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}async play(){if(!this.isValid())return;const e=this._isPaused==!0;if(this._isPaused=!1,!this._isPlaying){if(this._isPlaying=!0,e&&this.invokePauseChangedMethodsOnTracks(),this.waitForAudio){const t=[];for(const i of this._audioTracks){const n=i.loadAudio(this._time,1,0);n&&t.push(n)}if(t.length>0&&(await Promise.all(t),!this._isPlaying))return;for(;this._audioTracks.length>0&&this._isPlaying&&!_i.userInteractionRegistered&&this.waitForAudio;)await fs(200)}this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate(),me.LateUpdate)}}pause(){this.isValid()&&(this._isPlaying=!1,!this._isPaused&&(this._isPaused=!0,this.internalEvaluate(),this.invokePauseChangedMethodsOnTracks(),this.invokeStateChangedMethodsOnTracks()))}stop(){this._isStopping=!0;for(const i of this._audioTracks)i.stop();const e=this._isPaused==!0,t=this._isPlaying;this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.internalEvaluate(),e&&this.invokePauseChangedMethodsOnTracks()),this._isPlaying=!1,this._isPaused=!1,e&&!t&&this.invokePauseChangedMethodsOnTracks(),t&&this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine&&this.stopCoroutine(this._internalUpdateRoutine),this._internalUpdateRoutine=null,this._isStopping=!1}evaluate(){this.internalEvaluate(!0)}isValid(){return this.playableAsset&&this.playableAsset.tracks&&Array.isArray(this.playableAsset.tracks)}*forEachTrack(){for(const e of this._allTracks)for(const t of e)yield t}get animationTracks(){return this._animationTracks}get audioTracks(){return this._audioTracks}get signalTracks(){return this._signalTracks}get markerTracks(){return this._markerTracks}*foreachMarker(e=null){for(const t of this._markerTracks)for(const i of t.foreachMarker(e))yield i}_guidsMap;resolveGuids(e){this._guidsMap=e}_isPlaying=!1;_internalUpdateRoutine;_isPaused=!1;_isStopping=!1;_time=0;_duration=0;_weight=1;_animationTracks=[];_audioTracks=[];_signalTracks=[];_markerTracks=[];_controlTracks=[];_customTracks=[];_tracksArray=[];get _allTracks(){return this._tracksArray.length=0,this._tracksArray.push(this._animationTracks),this._tracksArray.push(this._audioTracks),this._tracksArray.push(this._signalTracks),this._tracksArray.push(this._markerTracks),this._tracksArray.push(this._controlTracks),this._tracksArray.push(this._customTracks),this._tracksArray}invokePauseChangedMethodsOnTracks(){for(const e of this.forEachTrack())e.onPauseChanged?.call(e)}invokeStateChangedMethodsOnTracks(){for(const e of this.forEachTrack())e.onStateChanged?.call(e,this._isPlaying)}*internalUpdate(){for(;this._isPlaying&&this.activeAndEnabled;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime*this.speed,this.internalEvaluate()),yield}internalEvaluate(e=!1){if(!this.isValid())return;let t=this._time;switch(this.extrapolationMode){case 0:this._speed>0?t=Math.min(t,this._duration):this._speed<0&&(t=Math.max(t,0)),this._time=t;break;case 1:t%=this._duration,this._time=t;break;case 2:if(t>this._duration){this.stop();return}break}const i=this._time;for(const n of this.playableAsset.tracks)if(!n.muted)switch(n.type){case ci.Activation:if(!e&&!this._isPlaying)continue;for(let o=0;o<n.outputs.length;o++){const r=n.outputs[o];if(typeof r=="object"){let a=!1;if(n.clips)for(const h of n.clips)h.start<=i&&i<=h.end&&(a=!0);const l=r;l.visible!==void 0&&l.visible!==a&&(l.visible=a,tn&&console.warn(this.name,"set ActivationTrack-"+o,l.name,a,i))}}break}for(const n of this._allTracks)for(const o of n)this._isStopping&&o instanceof Oc||o.evaluate(i)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=Ac(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;const e=this.findRoot(this.gameObject);for(const t of this.playableAsset.tracks){for(let i=t.outputs.length-1;i>=0;i--){let n=t.outputs[i];if(typeof n=="string"){this._guidsMap&&this._guidsMap[n]&&(n=this._guidsMap[n]);const o=S.findByGuid(n,e);o===null||typeof o!="object"?(t.outputs.splice(i,1),console.warn("Failed to resolve binding",n,t.name,t.type)):(tn&&console.log("Resolved binding",n,"to",o),t.outputs[i]=o)}else if(n===null){if(t.outputs.splice(i,1),um.createTrackFunctions[t.type])continue;t.type!==ci.Audio&&t.type!==ci.Control&&t.type!==ci.Marker&&t.type!==ci.Signal&&console.warn("Missing binding",n,t.name,t.type,this.name,this.playableAsset.name)}}if(t.type===ci.Control&&t.clips)for(let i=0;i<t.clips.length;i++){const n=t.clips[i];let o=n.asset.sourceObject;if(typeof o=="string"){this._guidsMap&&this._guidsMap[o]&&(o=this._guidsMap[o]);const r=S.findByGuid(o,e);r===null||typeof r!="object"?console.warn("Failed to resolve sourceObject binding",o,t.name,n):(tn&&console.log("Resolved binding",o,"to",r),n.asset.sourceObject=r)}}}}findRoot(e){return e.parent?this.findRoot(e.parent):e}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const e of this.playableAsset.tracks)if(e.muted!==!0){if(e.clips)for(const t of e.clips)t.end>this._duration&&(this._duration=t.end);if(e.markers)for(const t of e.markers)t.time>this._duration&&(this._duration=t.time+.001)}}}setupAndCreateTrackHandlers(){if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let e=S.findObjectOfType(as,this.context);for(const t of this.playableAsset.tracks){const i=t.type,n=um.createTrackFunctions[i];if(n!=null){const o=n(this,t);if(typeof o.evaluate=="function"){o.director=this,o.track=t,this._customTracks.push(o);continue}}if(t.type===ci.Animation){if(!t.clips||t.clips.length<=0){tn&&console.warn("Animation track has no clips",t);continue}for(let o=t.outputs.length-1;o>=0;o--){let r=t.outputs[o];if(r instanceof c.Object3D){const l=S.getOrAddComponent(r,at);l&&(r=l)}const a=r?.gameObject?.animations;if(a){const l=new Oc;l.trackOffset=t.trackOffset,l.director=this,l.track=t;for(let h=0;h<t.clips.length;h++){const d=t.clips[h],u=d.asset;if(!u){console.error(`Timeline ${this.name}: clip #${h} on track "${t.name}" has no animation data`);continue}const p=u.clip;let m=p;if((typeof m=="string"||typeof m=="number")&&(m=a.find(_=>_.name===p)),tn&&console.log(u,p,"→",m),!m){console.warn("Could not find animationClip for model",d,t.name,this.name,this.playableAsset?.name,a,r);continue}r instanceof at&&r.runtimeAnimatorController&&(r.__internalDidAwakeAndStart||r.initializeRuntimeAnimatorController(),r.runtimeAnimatorController.mixer||r.runtimeAnimatorController.bind(r),l.mixer=r.runtimeAnimatorController.mixer),l.mixer||(l.mixer=new c.AnimationMixer(r.gameObject),this.context.animations.registerAnimationMixer(l.mixer)),l.clips.push(m),l.mixer.uncacheAction(m),l.createHooks(d.asset,m);const g=l.mixer.clipAction(m);l.actions.push(g),l.models.push(d)}this._animationTracks.push(l)}}}else if(t.type===ci.Audio){if(!t.clips||t.clips.length<=0)continue;const o=new cs;o.director=this,o.track=t,o.audioSource=t.outputs.find(r=>r instanceof _i),this._audioTracks.push(o),e||(e=this.context.mainCameraComponent?.gameObject.addComponent(as)),o.listener=e.listener;for(let r=0;r<t.clips.length;r++){const a=t.clips[r];o.addModel(a)}}else if(t.type===ci.Marker){if(t.markers){const o=new kc;o.director=this,o.track=t;const r=new Ku;r.director=this,r.track=t;for(const a of t.markers)a.type===vy.Signal?(o.models.push(a),o.didTrigger.push(!1)):r.models.push(a);if(o!==null&&o.models.length>0){const a=S.getComponent(this.gameObject,vh);a&&(o.receivers.push(a),this._signalTracks.push(o))}r!==null&&r.models.length>0&&this._markerTracks.push(r)}}else if(t.type===ci.Signal){const o=new kc;if(o.director=this,o.track=t,t.markers)for(const r of t.markers)o.models.push(r),o.didTrigger.push(!1);for(const r of t.outputs)o.receivers.push(r);this._signalTracks.push(o)}else if(t.type===ci.Control){const o=new Zu;if(o.director=this,o.track=t,t.clips)for(const r of t.clips)o.models.push(r);o.resolveSourceObjects(this.context),this._controlTracks.push(o)}}}setAudioTracksAllowPlaying(e){for(const t of this._audioTracks)t.onAllowAudioChanged(e)}animationCallbackReceivers=[];registerAnimationCallback(e){this.animationCallbackReceivers.push(e)}unregisterAnimationCallback(e){const t=this.animationCallbackReceivers.indexOf(e);t!==-1&&this.animationCallbackReceivers.splice(t,1)}};ax([f()],wy.prototype,"playOnAwake");ax([f()],wy.prototype,"extrapolationMode");let pr=wy;var DR=Object.defineProperty,Ju=(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&&DR(e,t,n),n};class Br extends E{isGizmo=!1;translationSnap=1;rotationSnapAngle=15;scaleSnap=.25;get control(){return this._control}_control;orbit;onEnable(){if(!(this.isGizmo&&!Uc)&&this.context.mainCamera&&(this._control||(this._control=new q.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=S.getComponentInParent(this.context.mainCamera,de)??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(dn);i&&(i.fastMode=!0,i.requestOwnership())}else{const i=this.gameObject.getComponentInParent(dn);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()}}Ju([f()],Br.prototype,"isGizmo");Ju([f()],Br.prototype,"translationSnap");Ju([f()],Br.prototype,"rotationSnapAngle");Ju([f()],Br.prototype,"scaleSnap");var LR=Object.defineProperty,IR=Object.getOwnPropertyDescriptor,ef=(s,e,t,i)=>{for(var n=i>1?void 0:i?IR(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&&LR(e,t,n),n};class xy{texture=null;rect}ef([f(c.Texture)],xy.prototype,"texture",2);let rl=class extends oh{set image(e){this.sprite||(this.sprite=new xy),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}return!e?.texture?.name?.length&&e?.texture?.image?.width===32&&e?.texture?.image?.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))}};ef([f(xy)],rl.prototype,"sprite",1);ef([f()],rl.prototype,"pixelsPerUnitMultiplier",2);class tf extends oh{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))}}ef([f(c.Texture)],tf.prototype,"mainTexture",1);var jR=Object.defineProperty,BR=Object.getOwnPropertyDescriptor,Pi=(s,e,t,i)=>{for(var n=i>1?void 0:i?BR(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&&jR(e,t,n),n};const Bo=x("debugbutton");class ko{colorMultiplier;disabledColor;fadeDuration;highlightedColor;normalColor;pressedColor;selectedColor}Pi([f()],ko.prototype,"colorMultiplier",2);Pi([f(ee)],ko.prototype,"disabledColor",2);Pi([f()],ko.prototype,"fadeDuration",2);Pi([f(ee)],ko.prototype,"highlightedColor",2);Pi([f(ee)],ko.prototype,"normalColor",2);Pi([f(ee)],ko.prototype,"pressedColor",2);Pi([f(ee)],ko.prototype,"selectedColor",2);class UR{disabledTrigger;highlightedTrigger;normalTrigger;pressedTrigger;selectedTrigger}class Os extends E{click(){this.onClick?.invoke()}onClick=new oe;_isHovered=0;onPointerEnter(e){const t=e.event.pointerType==="mouse"&&e.button===0;t&&(this._isHovered+=1),Bo&&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),Bo&&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){Bo&&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){Bo&&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===ou.Mouse)&&(Bo&&(console.warn("Button Click",this.onClick),we("CLICKED button "+this.name+" at "+this.context.time.frameCount)),this.onClick&&this.onClick.listenerCount>0&&(this.onClick.invoke(),e.use(),Bo))){const t=this.gameObject.worldPosition;t.add(this.gameObject.worldUp.multiplyScalar(1+Math.random()*.5)),j.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(),Bo&&console.log(this),this._isInit=!1,this.init()}start(){this._image?.setInteractable(this.interactable),this.gameObject.getComponentInParent(Ta)||this.gameObject.addComponent(_u)}onEnable(){super.onEnable()}onDestroy(){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=S.getComponent(this.gameObject,rl),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()}}Pi([f(oe)],Os.prototype,"onClick",2);Pi([f(ko)],Os.prototype,"colors",2);Pi([f()],Os.prototype,"transition",2);Pi([f(UR)],Os.prototype,"animationTriggers",2);Pi([f(at)],Os.prototype,"animator",2);Pi([f()],Os.prototype,"interactable",1);var FR=Object.defineProperty,nf=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&FR(e,t,n),n};const zs=x("debuginputfield"),wh=class W extends E{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 W.active===this}textComponent;placeholder;onValueChanged;onEndEdit;static active=null;static activeTime=-1;static htmlField=null;static htmlFieldFocused=!1;inputEventFn;_iosEventFn;start(){zs&&console.log(this.name,this)}onEnable(){W.htmlField||(W.htmlField=document.createElement("input"),W.htmlField.style.width="0px",W.htmlField.style.height="0px",W.htmlField.style.padding="0px",W.htmlField.style.border="none",W.htmlField.style.overflow="hidden",W.htmlField.style.caretColor="transparent",W.htmlField.style.outline="none",W.htmlField.classList.add("ar"),W.htmlField.onfocus=()=>W.htmlFieldFocused=!0,W.htmlField.onblur=()=>W.htmlFieldFocused=!1,document.body.append(W.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),W.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&this.textComponent?.text.length&&S.setActive(this.placeholder.gameObject,!1),exports.DeviceUtilities.isiOS()&&(this._iosEventFn=this.processInputOniOS.bind(this),window.addEventListener("click",this._iosEventFn))}onDisable(){W.htmlField?.removeEventListener("keyup",this.inputEventFn),this.onDeselected(),this._iosEventFn&&window.removeEventListener("click",this._iosEventFn)}clear(){W.active===this&&W.htmlField?(W.htmlField.value="",this.setTextFromInputField()):(this.textComponent&&(this.textComponent.text=""),this.placeholder&&S.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){zs&&console.log("CLICK",e,W.active),W.activeTime=this.context.time.time,W.active!==this&&this.startCoroutine(this.activeLoop(),me.LateUpdate),this.selectInputField()}*activeLoop(){for(this.onSelected();W.active===this&&!(this.context.input.getPointerClicked(0)&&this.context.time.time-W.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){if(W.active!==this&&(zs&&console.log("Select",this.name,this,W.htmlField,this.context.isInXR,this.context.arOverlayElement,this.textComponent?.text,W.htmlField?.value),W.active?.onDeselected(),W.active=this,this.placeholder&&S.setActive(this.placeholder.gameObject,!1),W.htmlField)){if(W.htmlField.value=this.textComponent?.text||"",zs&&console.log("set input field value",W.htmlField.value),this.context.isInXR){const e=this.context.arOverlayElement;e&&e.append(W.htmlField)}this.selectInputField()}}onDeselected(){W.active===this&&(W.active=null,zs&&console.log("Deselect",this.name,this),W.htmlField&&(W.htmlField.blur(),document.body.append(W.htmlField)),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&S.setActive(this.placeholder.gameObject,!0),W.htmlField&&this.onEndEdit?.invoke(W.htmlField.value))}update(){W.active===this&&this.textComponent?.markDirty()}onInput(e){if(W.active===this){if(zs&&console.log(e.code,e,W.htmlField?.value,this.textComponent?.text),e.code==="Escape"||e.code==="Enter"){this.onDeselected();return}W.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&S.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){if(this.textComponent&&W.htmlField){const e=this.textComponent.text,t=W.htmlField.value,i=this.textComponent.text!==W.htmlField.value;this.textComponent.text=W.htmlField.value,i&&(zs&&console.log("[InputField] value changed:",t,e),this.onValueChanged?.invoke(t,e))}}selectInputField(){W.htmlField&&(zs&&console.log("Focus Inputfield",W.htmlFieldFocused,W.htmlField),W.htmlField.setSelectionRange(W.htmlField.value.length,W.htmlField.value.length),exports.DeviceUtilities.isiOS()?(W.htmlField.style.display="block",W.htmlField.focus({preventScroll:!0})):setTimeout(()=>W.htmlField?.focus(),1))}processInputOniOS(){const e=this.context.physics.raycast();if(!e.length)return;const i=e[0].object,n=ag(i);(n?.gameObject===this.gameObject||n?.gameObject.parent===this.gameObject)&&this.selectInputField()}};nf([f(Tt)],wh.prototype,"textComponent");nf([f(Tt)],wh.prototype,"placeholder");nf([f(oe)],wh.prototype,"onValueChanged");nf([f(oe)],wh.prototype,"onEndEdit");let Sy=wh;var zR=Object.defineProperty,lx=(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&&zR(e,t,n),n};class xh extends E{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 q.InteractiveGroup;t.listenToPointerEvents(this.context.renderer,this.context.mainCamera),this.gameObject.add(t);const i=new q.HTMLMesh(e);t.add(i),i.visible=!1;const n=i.material;n.transparent=!0,setTimeout(()=>{i.visible=!0;const o=iu(this.gameObject).clone();Ic(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()}}lx([f()],xh.prototype,"id");lx([f()],xh.prototype,"keepAspect");const NR={topLight:{intensity:500,position:[.418,16.199,.3]},room:{position:[-.757,13.219,.717],scale:[31.713,28.305,28.591]},boxes:[{position:[-10.906,2.009,1.846],rotation:-.195,scale:[2.328,7.905,4.651]},{position:[-5.607,-.754,-.758],rotation:.994,scale:[1.97,1.534,3.955]},{position:[6.167,.857,7.803],rotation:.561,scale:[3.927,6.285,3.687]},{position:[-2.017,.018,6.124],rotation:.333,scale:[2.002,4.566,2.064]},{position:[2.291,-.756,-2.621],rotation:-.286,scale:[1.546,1.552,1.496]},{position:[-2.193,-.369,-5.547],rotation:.516,scale:[3.875,3.487,2.986]}],lights:[{intensity:50,position:[-16.116,14.37,8.208],scale:[.1,2.428,2.739]},{intensity:50,position:[-16.109,18.021,-8.207],scale:[.1,2.425,2.751]},{intensity:17,position:[14.904,12.198,-1.832],scale:[.15,4.265,6.331]},{intensity:43,position:[-.462,8.89,14.52],scale:[4.38,5.441,.088]},{intensity:20,position:[3.235,11.486,-12.541],scale:[2.5,2,.1]},{intensity:100,position:[0,20,0],scale:[1,.1,1]}]},VR={topLight:{intensity:400,position:[.5,14,.5]},room:{position:[0,13.2,0],scale:[31.5,28.5,31.5]},boxes:[{position:[-10.906,-1,1.846],rotation:-.195,scale:[2.328,7.905,4.651]},{position:[-5.607,-.754,-.758],rotation:.994,scale:[1.97,1.534,3.955]},{position:[6.167,-.16,7.803],rotation:.561,scale:[3.927,6.285,3.687]},{position:[-2.017,.018,6.124],rotation:.333,scale:[2.002,4.566,2.064]},{position:[2.291,-.756,-2.621],rotation:-.286,scale:[1.546,1.552,1.496]},{position:[-2.193,-.369,-5.547],rotation:.516,scale:[3.875,3.487,2.986]}],lights:[{intensity:80,position:[-14,10,8],scale:[.1,2.5,2.5]},{intensity:80,position:[-14,14,-4],scale:[.1,2.5,2.5]},{intensity:23,position:[14,12,0],scale:[.1,5,5]},{intensity:16,position:[0,9,14],scale:[5,5,.1]},{intensity:80,position:[7,8,-14],scale:[2.5,2.5,.1]},{intensity:80,position:[-7,16,-14],scale:[2.5,2.5,.1]},{intensity:1,position:[0,20,0],scale:[.1,.1,.1]}]};class sf extends c.Scene{constructor(e){super(),this.position.y=-3.5;const t=new c.BoxGeometry;t.deleteAttribute("uv");const i=new c.MeshStandardMaterial({metalness:0,side:c.BackSide}),n=new c.MeshStandardMaterial({metalness:0}),o=e=="legacy"?NR:VR,r=new c.PointLight(16777215,o.topLight.intensity,28,2);r.position.set(...o.topLight.position),this.add(r);const a=new c.Mesh(t,i);a.position.set(...o.room.position),a.scale.set(...o.room.scale),this.add(a);for(const l of o.boxes){const h=new c.Mesh(t,n);h.position.set(...l.position),h.rotation.set(0,l.rotation,0),h.scale.set(...l.scale),this.add(h)}for(const l of o.lights){const h=new c.Mesh(t,this.createAreaLightMaterial(l.intensity));h.position.set(...l.position),h.scale.set(...l.scale),this.add(h)}}createAreaLightMaterial(e){const t=new c.MeshBasicMaterial;return t.color.setScalar(e),t}}var $R=Object.defineProperty,of=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&$R(e,t,n),n};const Sh=class cx extends E{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,T()&&!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),Lc(this.gameObject,e,this.keepUpDirection,t),this.invertForward&&this.gameObject.quaternion.multiply(cx.flipYQuat)}createBehaviours(e,t,i){if(t.uuid===this.gameObject.uuid){let n=t;if(this.keepUpDirection){const r=We.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 bt("lookat "+this.name,kt.sceneStartTrigger(),he.lookAtCameraAction(n,void 0,this.invertForward?Ii.back:Ii.forward,this.keepUpDirection?Ii.up:Ii.zero));e.addBehavior(o)}}};of([f(c.Object3D)],Sh.prototype,"target");of([f()],Sh.prototype,"invertForward");of([f()],Sh.prototype,"keepUpDirection");of([f()],Sh.prototype,"copyTargetRotation");let Cy=Sh;var WR=Object.defineProperty,Py=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&WR(e,t,n),n};class al extends E{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(yi)||this.gameObject.addComponent(yi)}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.")&&(T()&&console.warn("URL is not valid, adding https:// to the start of the URL",this.url),this.url="https://"+this.url)}}Py([f()],al.prototype,"url");Py([f()],al.prototype,"mode");Py([f()],al.prototype,"clickable");pu(s=>{const e=s.domElement.getAttribute("clickthrough");if(t(e)){const i=s.scene.addComponent(rf);bm(s.domElement,"clickthrough",()=>{const n=s.domElement.getAttribute("clickthrough");i.enabled=t(n)})}function t(i){return i!==null&&i!=="0"&&i!=="false"}});class rf extends E{_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 HR=Object.defineProperty,af=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&HR(e,t,n),n};const GR=x("debugcursor");class Ur extends E{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=B(e,t,1).unproject(i);o.sub(n).normalize();const r=B(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){fp.origin=a,fp.direction=o.multiplyScalar(-1);const l=this.context.physics.raycastFromRay(fp);if(l?.length){const h=l[0];this.damping>0?this.gameObject.worldPosition=a.lerp(h.point,this.context.time.deltaTime/this.damping):this.gameObject.worldPosition=h.point,GR&&j.DrawLine(h.point,h.normal.add(h.point),65280)}}}}af([f()],Ur.prototype,"damping");af([f()],Ur.prototype,"useFullPage");af([f()],Ur.prototype,"keepDistance");af([f()],Ur.prototype,"snapToSurface");const fp=new c.Ray;var qR=Object.defineProperty,XR=Object.getOwnPropertyDescriptor,ll=(s,e,t,i)=>{for(var n=i>1?void 0:i?XR(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&&qR(e,t,n),n};exports.HoverAnimation=class extends E{type="linear";duration=.1;scaleFactor=1.1;hovered=null;idle=null;animation=null;start(){this.idle||(this.idle=Nn.emptyClip()),(!this.hovered||!(this.hovered instanceof c.AnimationClip))&&(this.hovered=Nn.createScaleClip({type:"linear",duration:this.duration||.1,scale:this.gameObject.scale,scaleFactor:this.scaleFactor||1.1})),this.animation??=this.gameObject.addComponent(Et),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})}};ll([f()],exports.HoverAnimation.prototype,"type",2);ll([f()],exports.HoverAnimation.prototype,"duration",2);ll([f()],exports.HoverAnimation.prototype,"scaleFactor",2);ll([f(c.AnimationClip)],exports.HoverAnimation.prototype,"hovered",2);ll([f(c.AnimationClip)],exports.HoverAnimation.prototype,"idle",2);exports.HoverAnimation=ll([Gm],exports.HoverAnimation);var QR=Object.defineProperty,cl=(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&&QR(e,t,n),n};const Sl=x("debugscroll");class ks extends E{target=null;damping=0;invert=!1;htmlSelector=null;mode="window";changed=new oe;get currentValue(){return this._current_value}_current_value=0;_target_value=0;_appliedValue=-1;_needsUpdate=!1;_firstUpdate=!1;awake(){this._firstUpdate=!0}onEnable(){window.addEventListener("wheel",this.updateCurrentScrollValue,{passive:!0}),this._appliedValue=-1,this._needsUpdate=!0}onDisable(){window.removeEventListener("wheel",this.updateCurrentScrollValue)}lateUpdate(){if(this.updateCurrentScrollValue(),this._target_value>=0&&(this.damping>0&&!this._firstUpdate?(this._current_value=I.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),Sl&&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=()=>{switch(this.mode){case"window":if(this.htmlSelector?.length){if(this.htmlSelector!==this._lastSelectorValue&&(this._lastSelectorElement=document.querySelector(this.htmlSelector),this._lastSelectorValue=this.htmlSelector),this._lastSelectorElement){const e=this._lastSelectorElement.getBoundingClientRect();this._target_value=-e.top/(e.height-window.innerHeight);break}}else if(!(window.document.body.scrollHeight<=window.innerHeight)){const e=window.document.body.scrollHeight-window.innerHeight;this._target_value=window.scrollY/(e||1)}break}(isNaN(this._target_value)||!isFinite(this._target_value))&&(this._target_value=-1)};applyScroll(e,t){if(e)if(e instanceof pr)this.handleTimelineTarget(e,t),e.isPlaying&&e.pause(),e.evaluate();else if(e instanceof at)e.setFloat("scroll",t);else if(e instanceof Et)e.time=t*e.duration;else if(e instanceof _i){if(!e.duration)return;e.time=t*e.duration}else if(e instanceof Qi)e.position01=t;else if(e instanceof xt)e.intensity=t;else if(e instanceof c.Object3D){const i=e;i["needle:scrollbounds"]===void 0&&(i["needle:scrollbounds"]=Wt(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=e.duration;let n=Mb.get(e);if(!n){n=[],Mb.set(e,n);let l=0;for(const h of e.foreachMarker("ScrollMarker")){const d=l++;if(h.element===void 0||h.needsUpdate===!0||h.element&&!h.element?.parentNode){h.needsUpdate=!1;try{if(h.element=hx(d),Sl&&console.debug(`ScrollMarker #${d} (${h.time.toFixed(2)}) found`,h.element),!h.element){(Sl||T())&&console.warn(`No HTML element found for ScrollMarker: ${h.name} (index ${d})`);continue}}catch(u){h.element=null,console.error("ScrollMarker selector is not valid: "+h.name+`
|
|
1432
|
+
C) Set "joinRandomRoom" to true`),!1):(up&&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()):T()&&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(dp,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}setRandomRoomUrlParameter(){const e=Tc(),t=this.generateRoomName();x(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),ym(t,e)}generateRoomName(){let e="";for(let t=0;t<6;t++)e+=Math.floor(Math.random()*10).toFixed(0);return e}_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&&dc(this.urlParameterName,null),this.context.connection.leaveRoom(),this._userWantsToBeInARoom=!1;else{if(this.urlParameterName){const t=x(this.urlParameterName);(!t||t===!0)&&(this._lastJoinedRoom?dc(this.urlParameterName,this._lastJoinedRoom):this.setRandomRoomUrlParameter())}this.tryJoinRoom()}},this._roomButtonIconJoin=yt("group"),this._roomButtonIconLeave=yt("group_off"),this.updateRoomButtonState(),this.context.connection.beginListen(Y.JoinedRoom,this.updateRoomButtonState),this.context.connection.beginListen(Y.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(Y.JoinedRoom,this.updateRoomButtonState),this.context.connection.stopListen(Y.LeftRoom,this.updateRoomButtonState)}_viewOnlyButton;onEnableViewOnlyButton(){this.context.connection.isConnected?this.onCreateViewOnlyButton():(this.context.connection.stopListen(Y.JoinedRoom,this.onCreateViewOnlyButton),this.context.connection.beginListen(Y.JoinedRoom,this.onCreateViewOnlyButton))}onDisableViewOnlyButton(){this.context.connection.stopListen(Y.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),we("View only URL copied to clipboard")):ue("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(yt("visibility"))}this.context.menu.appendChild(this._viewOnlyButton)}}Oo([f()],_n.prototype,"roomName",2);Oo([f()],_n.prototype,"urlParameterName",2);Oo([f()],_n.prototype,"joinRandomRoom",2);Oo([f()],_n.prototype,"requireRoomParameter",2);Oo([f()],_n.prototype,"autoRejoin",2);Oo([f()],_n.prototype,"createJoinButton",2);Oo([f()],_n.prototype,"createViewOnlyButton",2);Oo([f()],_n.prototype,"roomPrefix",1);function PR(){const s=x("testwindowcount")||0;s&&s>0&&MR(s)}function MR(s){if(x("testwindow"))return null;const e=new URL(window.location.href);wp(e.searchParams,pM,1),wp(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 p=0;p<i.length;p++){const m=i[p];m!==u&&m.close()}i.length=0}}}return i}class _y extends E{awake(){PR()}}class by extends E{transformsPerFrame=10;interval=0;useFlatbuffers=!0;awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinary(bc,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new OR(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 re.Builder(1024));const e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();const i=F0(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 OR{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 kR=Object.defineProperty,Qu=(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&&kR(e,t,n),n};const ER=x("debugsignals");class Yu{guid}Qu([f()],Yu.prototype,"guid");class bh{signal;reaction}Qu([f(Yu)],bh.prototype,"signal");Qu([f(oe)],bh.prototype,"reaction");const rx=class es extends E{static receivers={};static invoke(e){if(es.receivers[e]){const t=es.receivers[e];if(!t)return;for(const i of t)i.invoke(e)}}events;awake(){ER&&console.log("SignalReceiver awake",this)}onEnable(){if(this.events)for(const e of this.events)es.receivers[e.signal.guid]||(es.receivers[e.signal.guid]=[]),es.receivers[e.signal.guid].push(this)}onDisable(){if(this.events){for(const e of this.events)if(es.receivers[e.signal.guid]){const t=es.receivers[e.signal.guid].indexOf(this);t>=0&&es.receivers[e.signal.guid].splice(t,1)}}}invoke(e){if(!this.events||!Array.isArray(this.events))return;const t=typeof e=="object"?e.guid:e;for(const i of this.events)if(i.signal.guid===t)try{if(i.reaction){if(!i.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",i,this);continue}}else{console.warn("Missing reaction for signal",i,this);continue}i.reaction.invoke()}catch(n){console.error(n)}}};Qu([f(bh)],rx.prototype,"events");let vh=rx;var ci=(s=>(s.Activation="ActivationTrack",s.Animation="AnimationTrack",s.Audio="AudioTrack",s.Control="ControlTrack",s.Marker="MarkerTrack",s.Signal="SignalTrack",s))(ci||{}),Pn=(s=>(s[s.None=0]="None",s[s.Hold=1]="Hold",s[s.Loop=2]="Loop",s[s.PingPong=3]="PingPong",s[s.Continue=4]="Continue",s))(Pn||{}),vy=(s=>(s.Signal="SignalEmitter",s))(vy||{});const Bn=x("debugtimeline");class ol{director;track;get muted(){return this.track.muted}set muted(e){e!==this.track.muted&&(this.track.muted=e,this.onMuteChanged?.call(this))}*forEachClip(e=!1){if(this.track?.clips)if(e)for(let t=this.track.clips.length-1;t>=0;t--)yield this.track.clips[t];else for(const t of this.track.clips)yield t}getClipTime(e,t){return t.clipIn+(e-t.start)*t.timeScale}getClipTimeNormalized(e,t){return(e-t.start)/t.duration}evaluateWeight(e,t,i,n=!0){if(t<0||t>=i.length)return 0;const o=i[t];if(n||e>=o.start&&e<=o.end){let r=1;if(o.easeInDuration>0){const a=Math.min((e-o.start)/o.easeInDuration,1);r*=a}if(o.easeOutDuration>0){const a=Math.min((o.end-e)/o.easeOutDuration,1);r*=a}return r}return 0}}class RR{clip;rootPositionOffset;rootQuaternionOffset;get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}rootStartPosition;rootEndPosition;rootStartQuaternion;rootEndQuaternion;constructor(e){const t=e.getClip();this.clip=t;const i=e.getRoot(),n=i.name+".position",o=i.name+".quaternion";Bn&&console.log(t.name,t.tracks,n);for(const r of t.tracks)if(!(r.times.length<=0)){if(r.name.endsWith(n))this.rootStartPosition=new c.Vector3().fromArray(r.values,0),this.rootEndPosition=new c.Vector3().fromArray(r.values,r.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),Bn&&console.log(this.rootPositionOffset);else if(r.name.endsWith(o)&&(this.rootStartQuaternion=new c.Quaternion().fromArray(r.values,0),this.rootEndQuaternion=new c.Quaternion().fromArray(r.values,r.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),Bn)){const a=new c.Euler().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",a)}}}}class Oc extends ol{models=[];trackOffset;target;mixer;clips=[];actions=[];weight=1;_actionOffsets=[];_didBind=!1;_animator=null;onDisable(){this.mixer?.stopAllAction()}onDestroy(){this.director.context.animations.unregisterAnimationMixer(this.mixer)}onStateChanged(){this._animator&&j_(this._animator.gameObject,this,this.director.enabled&&this.director.weight>0)}createHooks(e,t){if(t.tracks?.length<=0){console.warn("No tracks in AnimationClip",t);return}let i=!1,n=!1;const o=t.tracks.find(r=>r.name.includes(".position")||r.name.includes(".quaternion"))?.name.split(".");if(o){const r=o[o.length-2],a=r+".position",l=r+".quaternion";for(const h of t.tracks)!i&&h.name.endsWith(a)?(i=!0,this.createPositionInterpolant(t,e,h)):!n&&h.name.endsWith(l)&&(n=!0,this.createRotationInterpolant(t,e,h))}if(!i||!n){const r=this.mixer?.getRoot(),a=t.tracks[0],l=a.name.lastIndexOf("."),h=a.name.substring(0,l),d=h.substring(h.lastIndexOf(".")+1),u=r.getObjectByName(d);if(u)if(i){if(!n){const p=t.tracks[0].name.substring(0,l)+".quaternion";Bn&&console.warn("Create quaternion track",d,u);const m=new c.QuaternionKeyframeTrack(p,[0,t.duration],[0,0,0,1,0,0,0,1]);t.tracks.push(m),this.createRotationInterpolant(t,e,m)}}else{const p=h+".position";Bn&&console.warn("Create position track",d,u);const m=new c.VectorKeyframeTrack(p,[0,t.duration],[0,0,0,0,0,0]);t.tracks.push(m),this.createPositionInterpolant(t,e,m)}}}bind(){if(!this._didBind){this._didBind=!0,Bn&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(const e of this.actions){const t=new RR(e);this._actionOffsets.push(t)}this.target&&(this._animator=S.getComponent(this.target,at)??null,this._animator&&j_(this._animator.gameObject,this,!0));for(const e of this.models){const t=e.asset,i=t.position,n=t.rotation;i&&i.x!==void 0&&(i.isVector3||(t.position=new c.Vector3(i.x,i.y,i.z)),n.isQuaternion||(t.rotation=new c.Quaternion(n.x,n.y,n.z,n.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){const e=this.trackOffset.position;e&&(e.isVector3||(this.trackOffset.position=new c.Vector3(e.x,e.y,e.z)));const t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new c.Quaternion(t.x,t.y,t.z,t.w)))}}_useclipOffsets=!0;_totalOffsetPosition=new c.Vector3;_totalOffsetRotation=new c.Quaternion;_totalOffsetPosition2=new c.Vector3;_totalOffsetRotation2=new c.Quaternion;_summedPos=new c.Vector3;_tempPos=new c.Vector3;_summedRot=new c.Quaternion;_tempRot=new c.Quaternion;_clipRotQuat=new c.Quaternion;evaluate(e){if(this.track.muted||!this.mixer)return;this.bind(),this._totalOffsetPosition.set(0,0,0),this._totalOffsetRotation.set(0,0,0,1),this._totalOffsetPosition2.set(0,0,0),this._totalOffsetRotation2.set(0,0,0,1);let t=0,i=0,n=!1,o=!1,r=0;for(let a=0;a<this.clips.length;a++){const l=this.models[a],h=this.actions[a],d=l.asset;h.weight=0;const u=e>=l.start&&e<=l.end,p=l.preExtrapolationMode,m=l.postExtrapolationMode,g=a<this.clips.length-1?this.models[a+1]:null;let _=u,y=!1;if(!_&&!n&&l.end<e&&m!==Pn.None?(!g||g.start>e)&&(_=!0,n=!0):a==0&&!_&&!o&&l.start>e&&p!==Pn.None&&(!g||g.start<e)&&(_=!0,y=!0,o=!0),_){let v=this.weight;v*=this.evaluateWeight(e,a,this.models,_),v*=this.director.weight;let b=u;if(y)switch(p){case Pn.Hold:break;case Pn.Loop:e+=l.start,b=!0;break;default:e+=l.start,b=!0;break}let w=this.getClipTime(e,l),R=0;const M=d.duration;if(y&&p===Pn.Hold&&(w=0),b){if(d.loop)for(R+=Math.floor(w/(M+1e-6));w>M;)w-=M}else if(!u&&n)switch(m){case Pn.Hold:w=this.getClipTime(l.end,l);break;case Pn.Loop:w%=M;break;case Pn.PingPong:const D=Math.floor(w/M)%2!==0;w%=M,D&&(w=M-w);break}l.reversed===!0?h.time=h.getClip().duration-w:h.time=w,h.timeScale=0;const O=Math.max(0,v);if(h.weight=O,r+=O,h.clampWhenFinished=!1,h.isRunning()||h.play(),this._useclipOffsets){const A=t==0?this._totalOffsetPosition:this._totalOffsetPosition2,D=t==0?this._totalOffsetRotation:this._totalOffsetRotation2;t<1&&(i=1-v),t+=1;const L=this._summedPos.set(0,0,0),N=this._tempPos.set(0,0,0),$=this._summedRot.identity(),k=this._tempRot.identity(),z=d.rotation;z&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp(z,v));const V=this._actionOffsets[a];if(V.hasOffsets)for(let J=0;J<R;J++)V.rootPositionOffset?N.copy(V.rootPositionOffset):N.set(0,0,0),N.applyQuaternion($),this._clipRotQuat&&N.applyQuaternion(this._clipRotQuat),V.rootQuaternionOffset&&(k.copy(V.rootQuaternionOffset),$.multiply(k)),L.add(N);this._clipRotQuat&&D.multiply(this._clipRotQuat),D.multiply($),d.position&&L.add(d.position),A.add(L)}}}if(this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,i),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,i)),this.__mixerError===void 0&&(Bn||T())&&this._animator?.runtimeAnimatorController?.mixer&&this.mixer!==this._animator?.runtimeAnimatorController?.mixer&&(this.__mixerError=!0,console.error("AnimationTrack mixer is not shared with the animator controller - this might result in the timeline to not animate properly. Please report a bug to the Needle Engine team!",this)),this._animator?.runtimeAnimatorController){const a=Math.max(0,1-r);this._animator?.runtimeAnimatorController?.update(a)}else this.mixer.update(e)}createRotationInterpolant(e,t,i){const n=i.createInterpolant.bind(i),o=new c.Quaternion;this.ensureTrackOffsets();const r=this.trackOffset?.rotation;i.createInterpolant=()=>{const a=n(),l=a.evaluate.bind(a);return a.evaluate=h=>{const d=l(h);if(o.set(d[0],d[1],d[2],d[3]),o.premultiply(this._totalOffsetRotation),r&&o.premultiply(r),this.director.animationCallbackReceivers)for(const u of this.director.animationCallbackReceivers)u?.onTimelineRotation?.call(u,this.director,this.target,h,o);return d[0]=o.x,d[1]=o.y,d[2]=o.z,d[3]=o.w,d},a}}createPositionInterpolant(e,t,i){const n=i.createInterpolant.bind(i),o=new c.Vector3;this.ensureTrackOffsets();const r=this.trackOffset?.rotation,a=this.trackOffset?.position;let l;i.createInterpolant=()=>{const h=n(),d=h.evaluate.bind(h);return h.evaluate=u=>{const p=d(u);if(o.set(p[0],p[1],p[2]),t.removeStartOffset&&(l===void 0?(l=null,l=this._actionOffsets.find(m=>m.clip===e)?.rootStartPosition?.clone()):l?.isVector3&&o.sub(l)),o.applyQuaternion(this._totalOffsetRotation),o.add(this._totalOffsetPosition),r&&o.applyQuaternion(r),a&&(o.x-=a.x,o.y+=a.y,o.z+=a.z),this.director.animationCallbackReceivers)for(const m of this.director.animationCallbackReceivers)m?.onTimelinePosition?.call(m,this.director,this.target,u,o);return p[0]=o.x,p[1]=o.y,p[2]=o.z,p},h}}}const TR=x("mutetimeline");class cs extends ol{models=[];listener;audio=[];audioContextTimeOffset=[];lastTime=0;audioSource;_audioLoader=null;getAudioFilePath(e){const t=this.director.sourceId;return ho(t,e)}onAllowAudioChanged(e){for(let t=0;t<this.models.length;t++){const i=this.models[t];this.audio[t].setVolume(e?i.asset.volume:0)}}addModel(e){const t=new c.Audio(this.listener);this.audio.push(t);const i=e;i._didTriggerPlay=!1,this.models.push(i)}onDisable(){for(const e of this.audio)e.isPlaying&&e.stop();for(const e of this.models)e._didTriggerPlay=!1}onDestroy(){for(const e of this.audio)e.source&&e?.disconnect();this.audio.length=0}onMuteChanged(){if(this.muted)for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t?.isPlaying&&t.stop()}}stop(){for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t?.isPlaying&&t.stop()}for(const e of this.models)e._didTriggerPlay=!1}_playableDirectorResumed=!1;onPauseChanged(){for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t?.isPlaying&&t.stop()}this._playableDirectorResumed=this.director.isPlaying}evaluate(e){if(TR||this.track.muted||this.director.speed<0)return;const t=this.director.context.application.muted,i=this._playableDirectorResumed;this._playableDirectorResumed=!1;const n=t?.1:0;for(let o=0;o<this.models.length;o++){const r=this.models[o],a=this.audio[o],l=r.asset;if((!a||!a.buffer)&&this.isInTimeRange(r,e-1,e+1)&&this.handleAudioLoading(r,a),_i.userInteractionRegistered!==!1&&!(a===null||!a.buffer))if(a.playbackRate=this.director.context.time.timeScale*this.director.speed,a.loop=l.loop,e>=r.start&&e<=r.end&&e<this.director.duration){if(!a.isPlaying||!this.director.isPlaying)(i||!r._didTriggerPlay&&this.lastTime<e)&&(r.duration*r.timeScale>.3?a.offset=r.clipIn+(e-r.start)*r.timeScale:a.offset=0,Bn&&console.log("Timeline Audio ("+this.track.name+") play with offset "+a.offset+" - "+r.asset.clip),a.play(n),r._didTriggerPlay=!0);else{const d=r.clipIn+(e-r.start)*r.timeScale,u=a.context.currentTime-a._startedAt+a.offset;Math.abs(d-u)>.3&&(a.offset=d,a.stop(),a.play(n))}let h=l.volume;if(this.track.volume!==void 0&&(h*=this.track.volume),t&&(h=0),r.easeInDuration>0){const d=Math.min((e-r.start)/r.easeInDuration,1);h*=d}if(r.easeOutDuration>0){const d=Math.min((r.end-e)/r.easeOutDuration,1);h*=d}a.setVolume(h*this.director.weight)}else r._didTriggerPlay=!1,this.director.isPlaying&&a.isPlaying&&a.stop()}this.lastTime=e}loadAudio(e,t=0,i=0){let n=null;const o=e-i,r=e+t;for(const a of this.models)if(this.isInTimeRange(a,o,r)){const l=this.audio[this.models.indexOf(a)],h=this.handleAudioLoading(a,l);h!==null&&(n===null&&(n=[]),n.push(h))}return n!==null?Promise.all(n):null}isInTimeRange(e,t,i){return t<=e.start&&i>=e.end||t>=e.start&&t<=e.end||i>=e.start&&i<=e.end}static _audioBuffers=new Map;static dispose(){cs._audioBuffers.clear()}handleAudioLoading(e,t){this._audioLoader||(this._audioLoader=new c.AudioLoader);const i=this.getAudioFilePath(e.asset.clip);if(cs._audioBuffers.get(i)){const o=cs._audioBuffers.get(i);return o.then(r=>{r&&t.setBuffer(r)}),o}Bn&&console.warn("LOAD audio track",i,this.director.sourceId);const n=new Promise((o,r)=>{this._audioLoader.load(i,a=>{t.setBuffer(a),o(a)},void 0,a=>{console.error("Error loading audio",a),o(null)})});return cs._audioBuffers.set(i,n),n}}class Ku extends ol{models=[];needsSorting=!0;*foreachMarker(e=null){this.needsSorting&&this.sort();for(const t of this.models)t&&t.type===e&&(yield t)}onEnable(){this.needsSorting=!0}evaluate(e){this.needsSorting&&this.sort()}sort(){this.needsSorting=!1,this.models.sort((e,t)=>e.time-t.time)}}class kc extends ol{models=[];didTrigger=[];receivers=[];evaluate(e){if(this.track.muted)return;const t=this.director.context.time.deltaTime*1.5;for(let i=0;i<this.models.length;i++){const n=this.models[i],o=this.didTrigger[i],r=n.time-e;let a=!1;if(n.retroActive)a=r<=1e-6;else{const l=Math.abs(r);(l===0||l>=1e-5&&l<t)&&(a=!0)}if(a){if(!o)if(Bn&&console.log("Trigger signal",e,n.time,n),this.didTrigger[i]=!0,this.receivers?.length<=0)vh.invoke(n.asset);else for(const l of this.receivers)l&&l.invoke(n.asset)}else n.emitOnce||(this.didTrigger[i]=!1)}}}class Zu extends ol{models=[];timelines=[];resolveSourceObjects(e){for(let t=this.models.length-1;t>=0;t--){const n=this.models[t].asset;if(!n.sourceObject||typeof n.sourceObject!="object"){console.log("no source object, removing model",t,n),this.models.splice(t,1);continue}else{const o=S.getComponent(n.sourceObject,pr);this.timelines.push(o),o&&n.updateDirector&&(o.playOnAwake=!1)}}}_previousActiveModel=null;evaluate(e){this._previousActiveModel=null;for(let t=0;t<this.models.length;t++){const i=this.models[t],n=i.asset;if(e>=i.start&&e<=i.end){this._previousActiveModel=i;const o=this.getClipTime(e,i);if(n.controlActivation){const r=n.sourceObject;r.visible=!0}if(n.updateDirector){const r=this.timelines[t];r&&(r.isPlaying&&r.pause(),r.time=o,r.evaluate())}}else{const o=this._previousActiveModel?.asset;if(n.controlActivation){const r=n.sourceObject;o?.sourceObject!==r&&(r.visible=!1)}}}}}var AR=Object.defineProperty,ax=(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&&AR(e,t,n),n};const tn=x("debugtimeline"),wy=class um extends E{static createTrackFunctions={};static registerCreateTrack(e,t){this.createTrackFunctions[e]=t}playableAsset;playOnAwake;extrapolationMode=1;get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(e){typeof e=="number"&&!Number.isNaN(e)?this._time=e:(tn||pi())&&console.error("INVALID TIMELINE.TIME VALUE",e,this.name)}get duration(){return this._duration}set duration(e){this._duration=e}get weight(){return this._weight}set weight(e){this._weight=e}get speed(){return this._speed}set speed(e){this._speed=e}waitForAudio=!0;_visibilityChangeEvt;_clonedPlayableAsset=!1;_speed=1;awake(){tn&&console.log(`[Timeline] Awake '${this.name}'`,this),this.rebuildGraph(),!this.isValid()&&(tn||T())&&(tn?console.warn("PlayableDirector is not valid","Asset?",this.playableAsset,"Tracks:",this.playableAsset?.tracks,"IsArray?",Array.isArray(this.playableAsset?.tracks),this):this.playableAsset?.tracks?.length?console.warn("PlayableDirector is not valid"):console.warn("PlayableDirector has no tracks"))}onEnable(){tn&&console.log("[Timeline] OnEnable",this.name,this.playOnAwake);for(const e of this._audioTracks)e.onEnable?.();for(const e of this._customTracks)e.onEnable?.();for(const e of this._animationTracks)e.onEnable?.();this.playOnAwake&&this.play(),this._visibilityChangeEvt||(this._visibilityChangeEvt=()=>{switch(document.visibilityState){case"hidden":this.setAudioTracksAllowPlaying(!1);break;case"visible":this.setAudioTracksAllowPlaying(!0);break}}),window.addEventListener("visibilitychange",this._visibilityChangeEvt)}onDisable(){tn&&console.log("[Timeline] OnDisable",this.name),this.stop();for(const e of this._audioTracks)e.onDisable?.();for(const e of this._customTracks)e.onDisable?.();for(const e of this._animationTracks)e.onDisable?.();this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){for(const e of this._allTracks)for(const t of e)t.onDestroy?.()}rebuildGraph(){this.isValid()&&(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}async play(){if(!this.isValid())return;const e=this._isPaused==!0;if(this._isPaused=!1,!this._isPlaying){if(this._isPlaying=!0,e&&this.invokePauseChangedMethodsOnTracks(),this.waitForAudio){const t=[];for(const i of this._audioTracks){const n=i.loadAudio(this._time,1,0);n&&t.push(n)}if(t.length>0&&(await Promise.all(t),!this._isPlaying))return;for(;this._audioTracks.length>0&&this._isPlaying&&!_i.userInteractionRegistered&&this.waitForAudio;)await fs(200)}this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate(),me.LateUpdate)}}pause(){this.isValid()&&(this._isPlaying=!1,!this._isPaused&&(this._isPaused=!0,this.internalEvaluate(),this.invokePauseChangedMethodsOnTracks(),this.invokeStateChangedMethodsOnTracks()))}stop(){this._isStopping=!0;for(const i of this._audioTracks)i.stop();const e=this._isPaused==!0,t=this._isPlaying;this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.internalEvaluate(),e&&this.invokePauseChangedMethodsOnTracks()),this._isPlaying=!1,this._isPaused=!1,e&&!t&&this.invokePauseChangedMethodsOnTracks(),t&&this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine&&this.stopCoroutine(this._internalUpdateRoutine),this._internalUpdateRoutine=null,this._isStopping=!1}evaluate(){this.internalEvaluate(!0)}isValid(){return this.playableAsset&&this.playableAsset.tracks&&Array.isArray(this.playableAsset.tracks)}*forEachTrack(){for(const e of this._allTracks)for(const t of e)yield t}get animationTracks(){return this._animationTracks}get audioTracks(){return this._audioTracks}get signalTracks(){return this._signalTracks}get markerTracks(){return this._markerTracks}*foreachMarker(e=null){for(const t of this._markerTracks)for(const i of t.foreachMarker(e))yield i}_guidsMap;resolveGuids(e){this._guidsMap=e}_isPlaying=!1;_internalUpdateRoutine;_isPaused=!1;_isStopping=!1;_time=0;_duration=0;_weight=1;_animationTracks=[];_audioTracks=[];_signalTracks=[];_markerTracks=[];_controlTracks=[];_customTracks=[];_tracksArray=[];get _allTracks(){return this._tracksArray.length=0,this._tracksArray.push(this._animationTracks),this._tracksArray.push(this._audioTracks),this._tracksArray.push(this._signalTracks),this._tracksArray.push(this._markerTracks),this._tracksArray.push(this._controlTracks),this._tracksArray.push(this._customTracks),this._tracksArray}invokePauseChangedMethodsOnTracks(){for(const e of this.forEachTrack())e.onPauseChanged?.call(e)}invokeStateChangedMethodsOnTracks(){for(const e of this.forEachTrack())e.onStateChanged?.call(e,this._isPlaying)}*internalUpdate(){for(;this._isPlaying&&this.activeAndEnabled;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime*this.speed,this.internalEvaluate()),yield}internalEvaluate(e=!1){if(!this.isValid())return;let t=this._time;switch(this.extrapolationMode){case 0:this._speed>0?t=Math.min(t,this._duration):this._speed<0&&(t=Math.max(t,0)),this._time=t;break;case 1:t%=this._duration,this._time=t;break;case 2:if(t>this._duration){this.stop();return}break}const i=this._time;for(const n of this.playableAsset.tracks)if(!n.muted)switch(n.type){case ci.Activation:if(!e&&!this._isPlaying)continue;for(let o=0;o<n.outputs.length;o++){const r=n.outputs[o];if(typeof r=="object"){let a=!1;if(n.clips)for(const h of n.clips)h.start<=i&&i<=h.end&&(a=!0);const l=r;l.visible!==void 0&&l.visible!==a&&(l.visible=a,tn&&console.warn(this.name,"set ActivationTrack-"+o,l.name,a,i))}}break}for(const n of this._allTracks)for(const o of n)this._isStopping&&o instanceof Oc||o.evaluate(i)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=Ac(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;const e=this.findRoot(this.gameObject);for(const t of this.playableAsset.tracks){for(let i=t.outputs.length-1;i>=0;i--){let n=t.outputs[i];if(typeof n=="string"){this._guidsMap&&this._guidsMap[n]&&(n=this._guidsMap[n]);const o=S.findByGuid(n,e);o===null||typeof o!="object"?(t.outputs.splice(i,1),console.warn("Failed to resolve binding",n,t.name,t.type)):(tn&&console.log("Resolved binding",n,"to",o),t.outputs[i]=o)}else if(n===null){if(t.outputs.splice(i,1),um.createTrackFunctions[t.type])continue;t.type!==ci.Audio&&t.type!==ci.Control&&t.type!==ci.Marker&&t.type!==ci.Signal&&console.warn("Missing binding",n,t.name,t.type,this.name,this.playableAsset.name)}}if(t.type===ci.Control&&t.clips)for(let i=0;i<t.clips.length;i++){const n=t.clips[i];let o=n.asset.sourceObject;if(typeof o=="string"){this._guidsMap&&this._guidsMap[o]&&(o=this._guidsMap[o]);const r=S.findByGuid(o,e);r===null||typeof r!="object"?console.warn("Failed to resolve sourceObject binding",o,t.name,n):(tn&&console.log("Resolved binding",o,"to",r),n.asset.sourceObject=r)}}}}findRoot(e){return e.parent?this.findRoot(e.parent):e}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const e of this.playableAsset.tracks)if(e.muted!==!0){if(e.clips)for(const t of e.clips)t.end>this._duration&&(this._duration=t.end);if(e.markers)for(const t of e.markers)t.time>this._duration&&(this._duration=t.time+.001)}}}setupAndCreateTrackHandlers(){if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let e=S.findObjectOfType(as,this.context);for(const t of this.playableAsset.tracks){const i=t.type,n=um.createTrackFunctions[i];if(n!=null){const o=n(this,t);if(typeof o.evaluate=="function"){o.director=this,o.track=t,this._customTracks.push(o);continue}}if(t.type===ci.Animation){if(!t.clips||t.clips.length<=0){tn&&console.warn("Animation track has no clips",t);continue}for(let o=t.outputs.length-1;o>=0;o--){let r=t.outputs[o];if(r instanceof c.Object3D){const l=S.getOrAddComponent(r,at);l&&(r=l)}const a=r?.gameObject?.animations;if(a){const l=new Oc;l.trackOffset=t.trackOffset,l.director=this,l.track=t;for(let h=0;h<t.clips.length;h++){const d=t.clips[h],u=d.asset;if(!u){console.error(`Timeline ${this.name}: clip #${h} on track "${t.name}" has no animation data`);continue}const p=u.clip;let m=p;if((typeof m=="string"||typeof m=="number")&&(m=a.find(_=>_.name===p)),tn&&console.log(u,p,"→",m),!m){console.warn("Could not find animationClip for model",d,t.name,this.name,this.playableAsset?.name,a,r);continue}r instanceof at&&r.runtimeAnimatorController&&(r.__internalDidAwakeAndStart||r.initializeRuntimeAnimatorController(),r.runtimeAnimatorController.mixer||r.runtimeAnimatorController.bind(r),l.mixer=r.runtimeAnimatorController.mixer),l.mixer||(l.mixer=new c.AnimationMixer(r.gameObject),this.context.animations.registerAnimationMixer(l.mixer)),l.clips.push(m),l.mixer.uncacheAction(m),l.createHooks(d.asset,m);const g=l.mixer.clipAction(m);l.actions.push(g),l.models.push(d)}this._animationTracks.push(l)}}}else if(t.type===ci.Audio){if(!t.clips||t.clips.length<=0)continue;const o=new cs;o.director=this,o.track=t,o.audioSource=t.outputs.find(r=>r instanceof _i),this._audioTracks.push(o),e||(e=this.context.mainCameraComponent?.gameObject.addComponent(as)),o.listener=e.listener;for(let r=0;r<t.clips.length;r++){const a=t.clips[r];o.addModel(a)}}else if(t.type===ci.Marker){if(t.markers){const o=new kc;o.director=this,o.track=t;const r=new Ku;r.director=this,r.track=t;for(const a of t.markers)a.type===vy.Signal?(o.models.push(a),o.didTrigger.push(!1)):r.models.push(a);if(o!==null&&o.models.length>0){const a=S.getComponent(this.gameObject,vh);a&&(o.receivers.push(a),this._signalTracks.push(o))}r!==null&&r.models.length>0&&this._markerTracks.push(r)}}else if(t.type===ci.Signal){const o=new kc;if(o.director=this,o.track=t,t.markers)for(const r of t.markers)o.models.push(r),o.didTrigger.push(!1);for(const r of t.outputs)o.receivers.push(r);this._signalTracks.push(o)}else if(t.type===ci.Control){const o=new Zu;if(o.director=this,o.track=t,t.clips)for(const r of t.clips)o.models.push(r);o.resolveSourceObjects(this.context),this._controlTracks.push(o)}}}setAudioTracksAllowPlaying(e){for(const t of this._audioTracks)t.onAllowAudioChanged(e)}animationCallbackReceivers=[];registerAnimationCallback(e){this.animationCallbackReceivers.push(e)}unregisterAnimationCallback(e){const t=this.animationCallbackReceivers.indexOf(e);t!==-1&&this.animationCallbackReceivers.splice(t,1)}};ax([f()],wy.prototype,"playOnAwake");ax([f()],wy.prototype,"extrapolationMode");let pr=wy;var DR=Object.defineProperty,Ju=(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&&DR(e,t,n),n};class Br extends E{isGizmo=!1;translationSnap=1;rotationSnapAngle=15;scaleSnap=.25;get control(){return this._control}_control;orbit;onEnable(){if(!(this.isGizmo&&!Uc)&&this.context.mainCamera&&(this._control||(this._control=new q.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=S.getComponentInParent(this.context.mainCamera,de)??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(dn);i&&(i.fastMode=!0,i.requestOwnership())}else{const i=this.gameObject.getComponentInParent(dn);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()}}Ju([f()],Br.prototype,"isGizmo");Ju([f()],Br.prototype,"translationSnap");Ju([f()],Br.prototype,"rotationSnapAngle");Ju([f()],Br.prototype,"scaleSnap");var LR=Object.defineProperty,IR=Object.getOwnPropertyDescriptor,ef=(s,e,t,i)=>{for(var n=i>1?void 0:i?IR(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&&LR(e,t,n),n};class xy{texture=null;rect}ef([f(c.Texture)],xy.prototype,"texture",2);let rl=class extends oh{set image(e){this.sprite||(this.sprite=new xy),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}return!e?.texture?.name?.length&&e?.texture?.image?.width===32&&e?.texture?.image?.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))}};ef([f(xy)],rl.prototype,"sprite",1);ef([f()],rl.prototype,"pixelsPerUnitMultiplier",2);class tf extends oh{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))}}ef([f(c.Texture)],tf.prototype,"mainTexture",1);var jR=Object.defineProperty,BR=Object.getOwnPropertyDescriptor,Pi=(s,e,t,i)=>{for(var n=i>1?void 0:i?BR(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&&jR(e,t,n),n};const Bo=x("debugbutton");class ko{colorMultiplier;disabledColor;fadeDuration;highlightedColor;normalColor;pressedColor;selectedColor}Pi([f()],ko.prototype,"colorMultiplier",2);Pi([f(ee)],ko.prototype,"disabledColor",2);Pi([f()],ko.prototype,"fadeDuration",2);Pi([f(ee)],ko.prototype,"highlightedColor",2);Pi([f(ee)],ko.prototype,"normalColor",2);Pi([f(ee)],ko.prototype,"pressedColor",2);Pi([f(ee)],ko.prototype,"selectedColor",2);class UR{disabledTrigger;highlightedTrigger;normalTrigger;pressedTrigger;selectedTrigger}class Os extends E{click(){this.onClick?.invoke()}onClick=new oe;_isHovered=0;onPointerEnter(e){const t=e.event.pointerType==="mouse"&&e.button===0;t&&(this._isHovered+=1),Bo&&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),Bo&&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){Bo&&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){Bo&&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===ou.Mouse)&&(Bo&&(console.warn("Button Click",this.onClick),we("CLICKED button "+this.name+" at "+this.context.time.frameCount)),this.onClick&&this.onClick.listenerCount>0&&(this.onClick.invoke(),e.use(),Bo))){const t=this.gameObject.worldPosition;t.add(this.gameObject.worldUp.multiplyScalar(1+Math.random()*.5)),j.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(),Bo&&console.log(this),this._isInit=!1,this.init()}start(){this._image?.setInteractable(this.interactable),this.gameObject.getComponentInParent(Ta)||this.gameObject.addComponent(_u)}onEnable(){super.onEnable()}onDestroy(){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=S.getComponent(this.gameObject,rl),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()}}Pi([f(oe)],Os.prototype,"onClick",2);Pi([f(ko)],Os.prototype,"colors",2);Pi([f()],Os.prototype,"transition",2);Pi([f(UR)],Os.prototype,"animationTriggers",2);Pi([f(at)],Os.prototype,"animator",2);Pi([f()],Os.prototype,"interactable",1);var FR=Object.defineProperty,nf=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&FR(e,t,n),n};const zs=x("debuginputfield"),wh=class W extends E{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 W.active===this}textComponent;placeholder;onValueChanged;onEndEdit;static active=null;static activeTime=-1;static htmlField=null;static htmlFieldFocused=!1;inputEventFn;_iosEventFn;start(){zs&&console.log(this.name,this)}onEnable(){W.htmlField||(W.htmlField=document.createElement("input"),W.htmlField.style.width="0px",W.htmlField.style.height="0px",W.htmlField.style.padding="0px",W.htmlField.style.border="none",W.htmlField.style.overflow="hidden",W.htmlField.style.caretColor="transparent",W.htmlField.style.outline="none",W.htmlField.classList.add("ar"),W.htmlField.onfocus=()=>W.htmlFieldFocused=!0,W.htmlField.onblur=()=>W.htmlFieldFocused=!1,document.body.append(W.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),W.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&this.textComponent?.text.length&&S.setActive(this.placeholder.gameObject,!1),exports.DeviceUtilities.isiOS()&&(this._iosEventFn=this.processInputOniOS.bind(this),window.addEventListener("click",this._iosEventFn))}onDisable(){W.htmlField?.removeEventListener("keyup",this.inputEventFn),this.onDeselected(),this._iosEventFn&&window.removeEventListener("click",this._iosEventFn)}clear(){W.active===this&&W.htmlField?(W.htmlField.value="",this.setTextFromInputField()):(this.textComponent&&(this.textComponent.text=""),this.placeholder&&S.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){zs&&console.log("CLICK",e,W.active),W.activeTime=this.context.time.time,W.active!==this&&this.startCoroutine(this.activeLoop(),me.LateUpdate),this.selectInputField()}*activeLoop(){for(this.onSelected();W.active===this&&!(this.context.input.getPointerClicked(0)&&this.context.time.time-W.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){if(W.active!==this&&(zs&&console.log("Select",this.name,this,W.htmlField,this.context.isInXR,this.context.arOverlayElement,this.textComponent?.text,W.htmlField?.value),W.active?.onDeselected(),W.active=this,this.placeholder&&S.setActive(this.placeholder.gameObject,!1),W.htmlField)){if(W.htmlField.value=this.textComponent?.text||"",zs&&console.log("set input field value",W.htmlField.value),this.context.isInXR){const e=this.context.arOverlayElement;e&&e.append(W.htmlField)}this.selectInputField()}}onDeselected(){W.active===this&&(W.active=null,zs&&console.log("Deselect",this.name,this),W.htmlField&&(W.htmlField.blur(),document.body.append(W.htmlField)),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&S.setActive(this.placeholder.gameObject,!0),W.htmlField&&this.onEndEdit?.invoke(W.htmlField.value))}update(){W.active===this&&this.textComponent?.markDirty()}onInput(e){if(W.active===this){if(zs&&console.log(e.code,e,W.htmlField?.value,this.textComponent?.text),e.code==="Escape"||e.code==="Enter"){this.onDeselected();return}W.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&S.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){if(this.textComponent&&W.htmlField){const e=this.textComponent.text,t=W.htmlField.value,i=this.textComponent.text!==W.htmlField.value;this.textComponent.text=W.htmlField.value,i&&(zs&&console.log("[InputField] value changed:",t,e),this.onValueChanged?.invoke(t,e))}}selectInputField(){W.htmlField&&(zs&&console.log("Focus Inputfield",W.htmlFieldFocused,W.htmlField),W.htmlField.setSelectionRange(W.htmlField.value.length,W.htmlField.value.length),exports.DeviceUtilities.isiOS()?(W.htmlField.style.display="block",W.htmlField.focus({preventScroll:!0})):setTimeout(()=>W.htmlField?.focus(),1))}processInputOniOS(){const e=this.context.physics.raycast();if(!e.length)return;const i=e[0].object,n=ag(i);(n?.gameObject===this.gameObject||n?.gameObject.parent===this.gameObject)&&this.selectInputField()}};nf([f(Tt)],wh.prototype,"textComponent");nf([f(Tt)],wh.prototype,"placeholder");nf([f(oe)],wh.prototype,"onValueChanged");nf([f(oe)],wh.prototype,"onEndEdit");let Sy=wh;var zR=Object.defineProperty,lx=(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&&zR(e,t,n),n};class xh extends E{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 q.InteractiveGroup;t.listenToPointerEvents(this.context.renderer,this.context.mainCamera),this.gameObject.add(t);const i=new q.HTMLMesh(e);t.add(i),i.visible=!1;const n=i.material;n.transparent=!0,setTimeout(()=>{i.visible=!0;const o=iu(this.gameObject).clone();Ic(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()}}lx([f()],xh.prototype,"id");lx([f()],xh.prototype,"keepAspect");const NR={topLight:{intensity:500,position:[.418,16.199,.3]},room:{position:[-.757,13.219,.717],scale:[31.713,28.305,28.591]},boxes:[{position:[-10.906,2.009,1.846],rotation:-.195,scale:[2.328,7.905,4.651]},{position:[-5.607,-.754,-.758],rotation:.994,scale:[1.97,1.534,3.955]},{position:[6.167,.857,7.803],rotation:.561,scale:[3.927,6.285,3.687]},{position:[-2.017,.018,6.124],rotation:.333,scale:[2.002,4.566,2.064]},{position:[2.291,-.756,-2.621],rotation:-.286,scale:[1.546,1.552,1.496]},{position:[-2.193,-.369,-5.547],rotation:.516,scale:[3.875,3.487,2.986]}],lights:[{intensity:50,position:[-16.116,14.37,8.208],scale:[.1,2.428,2.739]},{intensity:50,position:[-16.109,18.021,-8.207],scale:[.1,2.425,2.751]},{intensity:17,position:[14.904,12.198,-1.832],scale:[.15,4.265,6.331]},{intensity:43,position:[-.462,8.89,14.52],scale:[4.38,5.441,.088]},{intensity:20,position:[3.235,11.486,-12.541],scale:[2.5,2,.1]},{intensity:100,position:[0,20,0],scale:[1,.1,1]}]},VR={topLight:{intensity:400,position:[.5,14,.5]},room:{position:[0,13.2,0],scale:[31.5,28.5,31.5]},boxes:[{position:[-10.906,-1,1.846],rotation:-.195,scale:[2.328,7.905,4.651]},{position:[-5.607,-.754,-.758],rotation:.994,scale:[1.97,1.534,3.955]},{position:[6.167,-.16,7.803],rotation:.561,scale:[3.927,6.285,3.687]},{position:[-2.017,.018,6.124],rotation:.333,scale:[2.002,4.566,2.064]},{position:[2.291,-.756,-2.621],rotation:-.286,scale:[1.546,1.552,1.496]},{position:[-2.193,-.369,-5.547],rotation:.516,scale:[3.875,3.487,2.986]}],lights:[{intensity:80,position:[-14,10,8],scale:[.1,2.5,2.5]},{intensity:80,position:[-14,14,-4],scale:[.1,2.5,2.5]},{intensity:23,position:[14,12,0],scale:[.1,5,5]},{intensity:16,position:[0,9,14],scale:[5,5,.1]},{intensity:80,position:[7,8,-14],scale:[2.5,2.5,.1]},{intensity:80,position:[-7,16,-14],scale:[2.5,2.5,.1]},{intensity:1,position:[0,20,0],scale:[.1,.1,.1]}]};class sf extends c.Scene{constructor(e){super(),this.position.y=-3.5;const t=new c.BoxGeometry;t.deleteAttribute("uv");const i=new c.MeshStandardMaterial({metalness:0,side:c.BackSide}),n=new c.MeshStandardMaterial({metalness:0}),o=e=="legacy"?NR:VR,r=new c.PointLight(16777215,o.topLight.intensity,28,2);r.position.set(...o.topLight.position),this.add(r);const a=new c.Mesh(t,i);a.position.set(...o.room.position),a.scale.set(...o.room.scale),this.add(a);for(const l of o.boxes){const h=new c.Mesh(t,n);h.position.set(...l.position),h.rotation.set(0,l.rotation,0),h.scale.set(...l.scale),this.add(h)}for(const l of o.lights){const h=new c.Mesh(t,this.createAreaLightMaterial(l.intensity));h.position.set(...l.position),h.scale.set(...l.scale),this.add(h)}}createAreaLightMaterial(e){const t=new c.MeshBasicMaterial;return t.color.setScalar(e),t}}var $R=Object.defineProperty,of=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&$R(e,t,n),n};const Sh=class cx extends E{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,T()&&!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),Lc(this.gameObject,e,this.keepUpDirection,t),this.invertForward&&this.gameObject.quaternion.multiply(cx.flipYQuat)}createBehaviours(e,t,i){if(t.uuid===this.gameObject.uuid){let n=t;if(this.keepUpDirection){const r=He.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 bt("lookat "+this.name,kt.sceneStartTrigger(),he.lookAtCameraAction(n,void 0,this.invertForward?Ii.back:Ii.forward,this.keepUpDirection?Ii.up:Ii.zero));e.addBehavior(o)}}};of([f(c.Object3D)],Sh.prototype,"target");of([f()],Sh.prototype,"invertForward");of([f()],Sh.prototype,"keepUpDirection");of([f()],Sh.prototype,"copyTargetRotation");let Cy=Sh;var WR=Object.defineProperty,Py=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&WR(e,t,n),n};class al extends E{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(yi)||this.gameObject.addComponent(yi)}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.")&&(T()&&console.warn("URL is not valid, adding https:// to the start of the URL",this.url),this.url="https://"+this.url)}}Py([f()],al.prototype,"url");Py([f()],al.prototype,"mode");Py([f()],al.prototype,"clickable");pu(s=>{const e=s.domElement.getAttribute("clickthrough");if(t(e)){const i=s.scene.addComponent(rf);bm(s.domElement,"clickthrough",()=>{const n=s.domElement.getAttribute("clickthrough");i.enabled=t(n)})}function t(i){return i!==null&&i!=="0"&&i!=="false"}});class rf extends E{_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 HR=Object.defineProperty,af=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&HR(e,t,n),n};const GR=x("debugcursor");class Ur extends E{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=B(e,t,1).unproject(i);o.sub(n).normalize();const r=B(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){fp.origin=a,fp.direction=o.multiplyScalar(-1);const l=this.context.physics.raycastFromRay(fp);if(l?.length){const h=l[0];this.damping>0?this.gameObject.worldPosition=a.lerp(h.point,this.context.time.deltaTime/this.damping):this.gameObject.worldPosition=h.point,GR&&j.DrawLine(h.point,h.normal.add(h.point),65280)}}}}af([f()],Ur.prototype,"damping");af([f()],Ur.prototype,"useFullPage");af([f()],Ur.prototype,"keepDistance");af([f()],Ur.prototype,"snapToSurface");const fp=new c.Ray;var qR=Object.defineProperty,XR=Object.getOwnPropertyDescriptor,ll=(s,e,t,i)=>{for(var n=i>1?void 0:i?XR(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&&qR(e,t,n),n};exports.HoverAnimation=class extends E{type="linear";duration=.1;scaleFactor=1.1;hovered=null;idle=null;animation=null;start(){this.idle||(this.idle=Nn.emptyClip()),(!this.hovered||!(this.hovered instanceof c.AnimationClip))&&(this.hovered=Nn.createScaleClip({type:"linear",duration:this.duration||.1,scale:this.gameObject.scale,scaleFactor:this.scaleFactor||1.1})),this.animation??=this.gameObject.addComponent(Et),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})}};ll([f()],exports.HoverAnimation.prototype,"type",2);ll([f()],exports.HoverAnimation.prototype,"duration",2);ll([f()],exports.HoverAnimation.prototype,"scaleFactor",2);ll([f(c.AnimationClip)],exports.HoverAnimation.prototype,"hovered",2);ll([f(c.AnimationClip)],exports.HoverAnimation.prototype,"idle",2);exports.HoverAnimation=ll([Gm],exports.HoverAnimation);var QR=Object.defineProperty,cl=(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&&QR(e,t,n),n};const Sl=x("debugscroll");class ks extends E{target=null;damping=0;invert=!1;htmlSelector=null;mode="window";changed=new oe;get currentValue(){return this._current_value}_current_value=0;_target_value=0;_appliedValue=-1;_needsUpdate=!1;_firstUpdate=!1;awake(){this._firstUpdate=!0}onEnable(){window.addEventListener("wheel",this.updateCurrentScrollValue,{passive:!0}),this._appliedValue=-1,this._needsUpdate=!0}onDisable(){window.removeEventListener("wheel",this.updateCurrentScrollValue)}lateUpdate(){if(this.updateCurrentScrollValue(),this._target_value>=0&&(this.damping>0&&!this._firstUpdate?(this._current_value=I.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),Sl&&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=()=>{switch(this.mode){case"window":if(this.htmlSelector?.length){if(this.htmlSelector!==this._lastSelectorValue&&(this._lastSelectorElement=document.querySelector(this.htmlSelector),this._lastSelectorValue=this.htmlSelector),this._lastSelectorElement){const e=this._lastSelectorElement.getBoundingClientRect();this._target_value=-e.top/(e.height-window.innerHeight);break}}else if(!(window.document.body.scrollHeight<=window.innerHeight)){const e=window.document.body.scrollHeight-window.innerHeight;this._target_value=window.scrollY/(e||1)}break}(isNaN(this._target_value)||!isFinite(this._target_value))&&(this._target_value=-1)};applyScroll(e,t){if(e)if(e instanceof pr)this.handleTimelineTarget(e,t),e.isPlaying&&e.pause(),e.evaluate();else if(e instanceof at)e.setFloat("scroll",t);else if(e instanceof Et)e.time=t*e.duration;else if(e instanceof _i){if(!e.duration)return;e.time=t*e.duration}else if(e instanceof Qi)e.position01=t;else if(e instanceof xt)e.intensity=t;else if(e instanceof c.Object3D){const i=e;i["needle:scrollbounds"]===void 0&&(i["needle:scrollbounds"]=Wt(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=e.duration;let n=Mb.get(e);if(!n){n=[],Mb.set(e,n);let l=0;for(const h of e.foreachMarker("ScrollMarker")){const d=l++;if(h.element===void 0||h.needsUpdate===!0||h.element&&!h.element?.parentNode){h.needsUpdate=!1;try{if(h.element=hx(d),Sl&&console.debug(`ScrollMarker #${d} (${h.time.toFixed(2)}) found`,h.element),!h.element){(Sl||T())&&console.warn(`No HTML element found for ScrollMarker: ${h.name} (index ${d})`);continue}}catch(u){h.element=null,console.error("ScrollMarker selector is not valid: "+h.name+`
|
|
1433
1433
|
`,u)}}h.element&&n.push(h)}n.length<=0&&document.querySelectorAll("[data-timeline-marker]").forEach(d=>{const u=d.getAttribute("data-timeline-marker"),p=parseFloat(u||"NaN");isNaN(p)?(T()||Sl)&&console.warn('[ScrollFollow] data-timeline-marker attribute is not a valid number. Supported are numbers only (e.g. <div data-timeline-marker="0.5">)'):n.push({time:p,element:d})});for(const h of n)h.element&&(h.timeline=new ViewTimeline({subject:h.element,axis:"block"}))}xn.length=0;let o=0;const r=1/60;let a=0;for(let l=0;l<n.length;l++){const h=n[l];if(!h.element)continue;const d=n[l+1],u=d?d.time-r:i;a+=1;const p=h.timeline;if(p){const m=YR(p),g=1-Math.abs(m-.5)*2,_=`marker${l}`;if(m>0&&m<=1){const y=h.time+(u-h.time)*m;xn.push({name:_,time:y,weight:g}),o+=g}else l===0&&m<=0?(xn.push({name:_,time:0,weight:1}),o+=1):l===n.length-1&&m>=1&&(xn.push({name:_,time:i,weight:1}),o+=1)}}if(xn.length<=0&&a<=0)e.time=t*i;else if(xn.length>0){let l=xn[0].time;if(xn.length>1)for(const d of xn){const u=d.weight/Math.max(1e-5,o),p=Math.abs(d.time-l);l+=p*u}this.damping<=0||this._firstUpdate?e.time=l:e.time=I.lerp(e.time,l,this.context.time.deltaTime/this.damping),Math.abs(e.time-l)>.001&&(this._needsUpdate=!0),Sl&&this.context.time.frame%30===0&&console.log(`[ScrollFollow ] Timeline ${e.name}: ${l.toFixed(3)}`,xn.map(d=>`[${d.name} ${(d.weight*100).toFixed(0)}%]`).join(", "))}}}cl([f([E,c.Object3D])],ks.prototype,"target");cl([f()],ks.prototype,"damping");cl([f()],ks.prototype,"invert");cl([f()],ks.prototype,"htmlSelector");cl([f()],ks.prototype,"mode");cl([f(oe)],ks.prototype,"changed");const Mb=new WeakMap,xn=[],pp=new Array;let mp=!0;function hx(s){return mp?(mp=!1,pp.length=0,document.querySelectorAll("[data-timeline-marker]").forEach((t,i)=>{pp[i]=t}),mp=!1,hx(s)):pp[s]||null}function YR(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 dx=Object.defineProperty,KR=Object.getOwnPropertyDescriptor,ZR=(s,e,t)=>e in s?dx(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,lf=(s,e,t,i)=>{for(var n=i>1?void 0:i?KR(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&&dx(e,t,n),n},My=(s,e,t)=>ZR(s,typeof e!="symbol"?e+"":e,t);const Ns=x("debugviewbox"),JR=new ee(.5,.5,.5,.5);exports.ViewBox=class extends E{referenceFieldOfView=-1;get mode(){return this._mode}set mode(e){e!==this._mode&&(this._mode=e,e==="once"&&(this._applyCount=0),(Ns||this.debug)&&console.debug("[ViewBox] Set mode:",e))}_mode="continuous";debug=!1;onEnable(){(Ns||this.debug||T())&&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(){(Ns||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)){(Ns||this.debug)&&j.DrawWireBox(this.gameObject.worldPosition,this.gameObject.worldScale,JR);return}(Ns||this.debug)&&j.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){(Ns||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,p=t.aspect,m=t.fov;t.view=null,t.zoom=1,t.fov=this.referenceFieldOfView,t.updateProjectionMatrix();const g=this.gameObject.worldPosition,_=this.gameObject.worldScale,y=t.worldPosition,v=y.distanceTo(g),b=Math.max(_.x,_.y,_.z),w=B(y).sub(g);if(v<b){(this.debug||Ns)&&console.warn("[ViewBox] Moving camera out of bounds",v,"<",b);const V=B(w);V.y*=1e-8,V.normalize();const J=b-v,Z=y.add(V.multiplyScalar(J));t.worldPosition=Z.lerp(y,1-this.context.time.deltaTime)}const R=B(g);t.worldToLocal(R),t.lookAt(g),t.updateMatrixWorld();const M=this.referenceFieldOfView*Math.PI/180,O=2*Math.tan(M/2)*v,A=O*t.aspect,D=this.projectBoxIntoCamera(t,1),L=D.maxX-D.minX,N=D.maxY-D.minY,k=this.fit(L*t.aspect,N,A/a,O/l)/(O*.5),z=B(g);z.project(t),this.context.focusRectSettings.offsetX=z.x,this.context.focusRectSettings.offsetY=z.y,this.context.focusRectSettings.zoom=k,this.context.focusRect||this.context.setCameraFocusRect(this.context.domElement),t.view=d,t.zoom=u,t.aspect=p,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=[B(-i,-i,-i),B(i,-i,-i),B(-i,i,-i),B(i,i,-i),B(-i,-i,i),B(i,-i,i),B(-i,i,i),B(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 Ns&&(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};My(exports.ViewBox,"instances",[]);My(exports.ViewBox,"_tempProjectionMatrix",new c.Matrix4);My(exports.ViewBox,"_tempProjectionMatrixInverse",new c.Matrix4);lf([f()],exports.ViewBox.prototype,"referenceFieldOfView",2);lf([f()],exports.ViewBox.prototype,"mode",1);lf([f()],exports.ViewBox.prototype,"debug",2);exports.ViewBox=lf([Gm],exports.ViewBox);var eT=Object.defineProperty,hl=(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&&eT(e,t,n),n};class Es extends E{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=B(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=B(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))}}hl([f()],Es.prototype,"side");hl([f()],Es.prototype,"controller");hl([f()],Es.prototype,"hands");hl([f()],Es.prototype,"controlVisibility");hl([f()],Es.prototype,"useGripSpace");hl([f()],Es.prototype,"resetTransformAfterXRSession");function ux(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.
|
|
1434
1434
|
|
|
1435
1435
|
Example to request camera-access in global scope:
|
|
@@ -1476,7 +1476,7 @@ void main() {
|
|
|
1476
1476
|
#include <colorspace_fragment>
|
|
1477
1477
|
}
|
|
1478
1478
|
`;var aT=Object.defineProperty,Eo=(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&&aT(e,t,n),n};const ac=x("debugimagetracking");class Ia{get url(){return this._trackedImage.image??""}get widthInMeters(){return this._trackedImage.widthInMeters??void 0}get bitmap(){return this._bitmap}get model(){return this._trackedImage}measuredSize;state;getPosition(e){return this.ensureTransformData(),e.copy(this._position),e}getQuaternion(e){return this.ensureTransformData(),e.copy(this._rotation),e}applyToObject(e,t=void 0){this.ensureTransformData();const i=e.position.distanceToSquared(this._position)/.05+e.quaternion.angleTo(this._rotation)/.05;t&&(t*=Math.max(1,i)),t===void 0||t>=1?(e.position.copy(this._position),e.quaternion.copy(this._rotation)):(t=Math.max(0,Math.min(1,t)),e.position.lerp(this._position,t),e.quaternion.slerp(this._rotation,t))}static _positionBuffer=new mi(()=>new c.Vector3,20);static _rotationBuffer=new mi(()=>new c.Quaternion,20);_position;_rotation;ensureTransformData(){if(!this._position){this._position=Ia._positionBuffer.get(),this._rotation=Ia._rotationBuffer.get();const e=this._pose.transform,t=G.active.convertSpace(e);this._position.copy(t?.position),this._rotation.copy(t?.quaternion)}}_trackingComponent;_trackedImage;_bitmap;_pose;constructor(e,t,i,n,o,r){this._trackingComponent=e,this._trackedImage=t,this._bitmap=i,this.measuredSize=n,this.state=o,this._pose=r}}class Rs{constructor(e){this.image=e.url,this.widthInMeters=e.widthInMeters,e.object instanceof c.Object3D?this.object=new K({asset:e.object}):this.object=e.object,e.createObjectInstance!==void 0&&(this.createObjectInstance=e.createObjectInstance),e.imageDoesNotMove!==void 0&&(this.imageDoesNotMove=e.imageDoesNotMove),e.hideWhenTrackingIsLost!==void 0&&(this.hideWhenTrackingIsLost=e.hideWhenTrackingIsLost)}image;widthInMeters=.25;object;createObjectInstance=!1;imageDoesNotMove=!1;hideWhenTrackingIsLost=!0;getNameFromUrl(){if(this.image){const e=this.image.split("/");return e[e.length-1]}return null}}Eo([f(URL)],Rs.prototype,"image");Eo([f()],Rs.prototype,"widthInMeters");Eo([f(K)],Rs.prototype,"object");Eo([f()],Rs.prototype,"createObjectInstance");Eo([f()],Rs.prototype,"imageDoesNotMove");Eo([f()],Rs.prototype,"hideWhenTrackingIsLost");class lT{constructor(e,t){this.exporter=e,this.component=t,ac&&console.log(this),this.exporter.anchoringType="image"}isImageTrackingExtension=!0;get extensionName(){return"image-tracking"}shouldExport=!0;filename=null;imageModel=null;onBeforeBuildDocument(e){const t=this.exporter.extensions.filter(i=>{const n=i;return n.isImageTrackingExtension&&n.component.activeAndEnabled&&n.component.trackedImages?.length>0}).indexOf(this);this.shouldExport=t===0,this.shouldExport&&this.component.trackedImages?.length>1&&(ac||T())&&(ue("USDZ: Only one tracked image is supported."),console.warn("USDZ: Only one tracked image is supported. Will choose the first one in the trackedImages list"))}onAfterHierarchy(e,t){if(!this.shouldExport)return;const i=exports.DeviceUtilities.getiOSVersion(),r=(i?parseInt(i.split(".")[0]):18)>=18?1:100;t.beginBlock('def Preliminary_ReferenceImage "AnchoringReferenceImage"'),t.appendLine("uniform asset image = @image_tracking/"+this.filename+"@"),t.appendLine("uniform double physicalWidth = "+(this.imageModel.widthInMeters*r).toFixed(8)),t.closeBlock()}async onAfterSerialize(e){if(!this.shouldExport)return;const t=this.imageModel,i=lc.get(t.image),r=await(await(await Ow(i)).convertToBlob({type:"image/png"})).arrayBuffer();e.files["image_tracking/"+this.filename]=new Uint8Array(r)}onExportObject(e,t,i){if(!this.shouldExport)return;const n=this.component;if(!n||!n.trackedImages?.length||!n.activeAndEnabled)return;const o=n.trackedImages[0];if(o.object?.asset===e){this.imageModel=o,this.filename=o.getNameFromUrl()||"marker.png";const{scale:r,target:a}=this.exporter.getARScaleAndTarget();let l=e;const h=new c.Matrix4;if(e!==a)for(;l&&l.parent&&l.parent!==a;)l=l.parent,h.premultiply(l.matrix);const d=h.clone().invert();t.setMatrix(d.scale(new c.Vector3(r,r,r)))}}}class Ph extends E{setPrimaryImage(e){const t=this.trackedImages.indexOf(e);if(t>=0){const i=this.trackedImages[0];i!==e&&(this.trackedImages[0]=e,this.trackedImages[t]=i)}else console.warn(`[WebXRImageTracking] Can not set primary: image not found in 'trackedImages' array ${e.image}`)}addImage(e,t=!1){this.trackedImages.includes(e)||(this.trackedImages.push(e),Eb(e.image)),t&&this.setPrimaryImage(e)}trackedImages=[];smooth=!0;trackedImageIndexMap=new Map;get supported(){return this._supported}_supported=!0;awake(){if(ac&&console.log(this),!!this.trackedImages)for(const e of this.trackedImages)e.image&&Eb(e.image)}onEnable(){an.beforeExport.addEventListener(this.onBeforeUSDZExport)}onDisable(){an.beforeExport.removeEventListener(this.onBeforeUSDZExport)}onBeforeUSDZExport=e=>{this.activeAndEnabled&&this.trackedImages?.length&&e.exporter.extensions.push(new lT(e.exporter,this))};onBeforeXR(e,t){if(this.trackedImages){t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.includes("image-tracking")||t.optionalFeatures.push("image-tracking"),t.trackedImages||(t.trackedImages=[]);for(const i of this.trackedImages)if(i.image?.length&&i.widthInMeters>0){const n=lc.get(i.image);n&&(this.trackedImageIndexMap.set(t.trackedImages.length,i),t.trackedImages.push({image:n,widthInMeters:i.widthInMeters}))}}}onEnterXR(e){if(this.trackedImages){for(const t of this.trackedImages)if(t.object?.asset){const i=t.object.asset;i.userData||(i.userData={});const n={visible:i.visible,parent:i.parent,matrix:i.matrix.clone()};i.userData["image-tracking"]=n}}for(const t of this.imageToObjectMap.values())t.frames=0}onLeaveXR(e){if(!this.supported&&exports.DeviceUtilities.isAndroidDevice()&&ue(this.webXRIncubationsWarning),this.trackedImages){for(const t of this.trackedImages)if(t.object?.asset){const i=t.object.asset;if(i.userData){const n=i.userData["image-tracking"];n&&(i.visible=n.visible,n.parent?.add(i),i.matrix.copy(n.matrix),i.matrix.decompose(i.position,i.quaternion,i.scale)),delete i.userData["image-tracking"]}}}}imageToObjectMap=new Map;currentImages=[];webXRIncubationsWarning=`Image tracking is currently not supported on this device. On Chrome for Android, you can enable the <a target="_blank" href="#" onclick="() => console.log('I')">chrome://flags/#webxr-incubations</a> flag.`;onUpdateXR(e){this.currentImages.length=0;const t=e.xr.frame;if(!t)return;if("getImageTrackingResults"in t){if(e.xr.session.enabledFeatures?.includes("image-tracking")===!1)return;if(t.session&&typeof t.getImageTrackingResults=="function"){const n=t.getImageTrackingResults();if(n.length>0){const o=this.context.renderer.xr.getReferenceSpace();if(o){for(const r of n){const a=r.trackingState,l=r.index,h=this.trackedImageIndexMap.get(l);if(h){const d=t.getPose(r.imageSpace,o),u=new Ia(this,h,r.image,r.measuredSize,a,d);this.currentImages.push(u)}else ac&&console.warn("No tracked image for index",l)}if(this.currentImages.length>0)try{this.dispatchEvent(new CustomEvent("image-tracking",{detail:this.currentImages})),this.onImageTrackingUpdate(this.currentImages)}catch(r){console.error(r)}}}}}else{this.didPrintWarning||(this.didPrintWarning=!0,console.log(this.webXRIncubationsWarning)),this._supported=!1,ue(this.webXRIncubationsWarning);return}const i=1e3;for(const[n,o]of this.imageToObjectMap){if(!o.object||!n||n.hideWhenTrackingIsLost===!1)continue;let r=!1;for(const a of this.currentImages)if(a.model===n){const l=Date.now()-o.lastTrackingTime;if(ac&&we(n.image+", State: "+a.state+(n.imageDoesNotMove?" (static)":"")+(l<=i?" (hysteresis)":"")),n.imageDoesNotMove||a.state==="tracked"||l<=i){r=!0;break}}r||S.setActive(o.object,!1)}}onImageTrackingUpdate=e=>{const t=G.active;if(t)for(const i of e){const n=i.model,o=i.state==="tracked";if(!n.object)continue;let r=this.imageToObjectMap.get(n);if(r===void 0)r={object:null,frames:0,lastTrackingTime:Date.now()},this.imageToObjectMap.set(n,r),n.object.loadAssetAsync().then(a=>{if(n.createObjectInstance&&a&&(a=S.instantiate(a)),a){r.object=a;for(const l of a.getComponentsInChildren(Ht))l.setInstancingEnabled(!1);t.rig?(t.rig.gameObject.add(a),i.applyToObject(a),a.activeSelf||S.setActive(a,!0)):console.warn("XRImageTracking: missing XRRig")}});else{if(r.frames++,o&&(r.lastTrackingTime=Date.now()),n.imageDoesNotMove&&r.frames>10||!r.object)continue;t.rig&&(t.rig.gameObject.add(r.object),i.applyToObject(r.object,this.smooth?this.context.time.deltaTimeUnscaled*3:void 0),r.object.activeSelf||S.setActive(r.object,!0))}}}}Eo([f(Rs)],Ph.prototype,"trackedImages");Eo([f()],Ph.prototype,"smooth");const lc=new Map,sd=new Map;async function Eb(s){if(lc.has(s))return sd.has(s)?sd.get(s):Promise.resolve(!0);const e=new Promise(t=>{lc.set(s,null);const i=document.createElement("img");i.src=s,i.addEventListener("load",async()=>{const n=await createImageBitmap(i);lc.set(s,n),t(!0)})});return sd.set(s,e),e.finally(()=>{sd.delete(s)}),e}var cT=Object.defineProperty,dl=(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&&cT(e,t,n),n};const Uo=x("debugplanetracking");class Ts extends E{dataTemplate;occluder=!0;initiateRoomCaptureIfNoData=!0;usePlaneData=!0;useMeshData=!0;runInVR=!0;get trackedPlanes(){return this._allPlanes.values()}get trackedMeshes(){return this._allMeshes.values()}onBeforeXR(e,t){e==="immersive-vr"&&!this.runInVR||(t.optionalFeatures=t.optionalFeatures||[],this.usePlaneData&&!t.optionalFeatures.includes("plane-detection")&&t.optionalFeatures.push("plane-detection"),this.useMeshData&&!t.optionalFeatures.includes("mesh-detection")&&t.optionalFeatures.push("mesh-detection"))}onEnterXR(e){for(const t of this._allPlanes.keys())this.removeData(t,this._allPlanes);for(const t of this._allMeshes.keys())this.removeData(t,this._allMeshes)}onLeaveXR(e){for(const t of this._allPlanes.keys())this.removeData(t,this._allPlanes);for(const t of this._allMeshes.keys())this.removeData(t,this._allMeshes)}onUpdateXR(e){if(!this.runInVR&&e.xr.isVR)return;const t=e.xr.rig;if(!t){console.warn("No XR rig found, cannot parent tracked planes to it");return}const i=e.xr.frame;if(!this.context.renderer.xr.getReferenceSpace())return;const r=i.detectedPlanes,a=i.detectedMeshes,l=r!==void 0&&r.size>0,h=a!==void 0&&a.size>0;if(this.initiateRoomCaptureIfNoData&&(!l&&!h&&this.firstTimeNoPlanesDetected<-10&&(this.firstTimeNoPlanesDetected=Date.now()),(l||h)&&(this.firstTimeNoPlanesDetected=-1),this.firstTimeNoPlanesDetected>0&&Date.now()-this.firstTimeNoPlanesDetected>2500&&"initiateRoomCapture"in i.session&&(i.session.initiateRoomCapture(),this.firstTimeNoPlanesDetected=-1)),r!==void 0&&this.processFrameData(e.xr,t.gameObject,i,r,this._allPlanes),a!==void 0&&this.processFrameData(e.xr,t.gameObject,i,a,this._allMeshes),Uo){const d=this.context.mainCameraComponent.gameObject.worldPosition;for(const u of this._allPlanes.values())!u.mesh||!u.mesh.visible||(this.bounds.makeEmpty(),u.mesh.traverse(p=>{p instanceof c.Mesh&&this.bounds.expandByObject(p)}),this.bounds.getCenter(this.center),this.labelOffset.copy(d).sub(this.center).normalize().multiplyScalar(.1),j.DrawLabel(this.center.add(this.labelOffset),(u.xrData.semanticLabel||"plane").toUpperCase()+`
|
|
1479
|
-
`+u.xrData.lastChangedTime.toFixed(2),.02))}}bounds=new c.Box3;center=new c.Vector3;labelOffset=new c.Vector3;removeData(e,t){const i=t.get(e);if(!i)return;t.delete(e),Uo&&console.log("Plane no longer tracked, id="+i.id),i.mesh&&(i.mesh.removeFromParent(),i.mesh.traverse(o=>{const r=o.userData.normalsHelper;r?(r.dispose(),r.removeFromParent()):Uo&&console.warn("No normals helper found for mesh",i.mesh)}),gi(i.mesh,!0,!0));const n=new CustomEvent("plane-tracking",{detail:{type:"plane-removed",context:i}});this.dispatchEvent(n)}_dataId=1;_allPlanes=new Map;_allMeshes=new Map;firstTimeNoPlanesDetected=-100;makeOccluder=(e,t,i=!1)=>{if(t){if(t instanceof Array){for(const n of t)this.makeOccluder(e,n,i);return}!i&&!t.name.toLowerCase().includes("occlu")||(t.colorWrite=!1,t.depthTest=!0,t.depthWrite=!0,t.transparent=!1,t.polygonOffset=!0,t.polygonOffsetFactor=1,t.polygonOffsetUnits=.1,e.renderOrder=-1e3)}};processFrameData(e,t,i,n,o){const a=this.context.renderer.xr.getReferenceSpace();if(a){for(const l of o.keys())n.has(l)||this.removeData(l,o);for(const l of n){const h="planeSpace"in l?l.planeSpace:"meshSpace"in l?l.meshSpace:void 0;if(!h)continue;const d=i.getPose(h,a);let u;if(o.has(l)){const p=o.get(l);if(u=p.mesh,p.timestamp<l.lastChangedTime){if(p.timestamp=l.lastChangedTime,p.mesh){const g=this.createGeometry(l);if(p.mesh instanceof c.Mesh)p.mesh.geometry.dispose(),p.mesh.geometry=g,this.makeOccluder(p.mesh,p.mesh.material);else if(p.mesh instanceof c.Group)for(const _ of p.mesh.children)_ instanceof c.Mesh&&(_.geometry.dispose(),_.geometry=g,this.makeOccluder(_,_.material));if(p.collider){const _=p.mesh;p.collider.sharedMesh=_,p.collider.convex=this.checkIfContextShouldBeConvex(_,p.xrData),p.collider.onDisable(),p.collider.onEnable()}Uo&&(console.log("Plane updated, id="+p.id,p),p.mesh.traverse(_=>{if(!(_ instanceof c.Mesh))return;const y=_.userData.normalsHelper;y&&y.update()}))}const m=new CustomEvent("plane-tracking",{detail:{type:"plane-updated",context:p}});this.dispatchEvent(m)}}else{if(!this.dataTemplate){const p=new c.Mesh;Uo?p.material=new c.MeshNormalMaterial:this.occluder?(p.material=new c.MeshBasicMaterial,this.makeOccluder(p,p.material,!0)):p.material=new c.MeshBasicMaterial({wireframe:!0,opacity:.5,transparent:!0,color:3355443}),this.dataTemplate=new K("","",p)}if(!this.dataTemplate.asset)this.dataTemplate.loadAssetAsync();else{const p=S.instantiate(this.dataTemplate.asset);if(p.name="xr-tracked-plane",u=p,km(p,!1),p instanceof c.Mesh)be(p.geometry),p.geometry=this.createGeometry(l),this.makeOccluder(p,p.material,this.occluder&&!this.dataTemplate);else if(p instanceof c.Group)for(const _ of p.children)_ instanceof c.Mesh&&(be(_.geometry),_.geometry=this.createGeometry(l),this.makeOccluder(_,_.material,this.occluder&&!this.dataTemplate));const m=p.getComponent(yo);if(m){const _=p;m.sharedMesh=_,m.convex=this.checkIfContextShouldBeConvex(_,l),m.onDisable(),m.onEnable()}p.matrixAutoUpdate=!1,p.matrixWorldNeedsUpdate=!0,t.add(p);const g={id:this._dataId++,xrData:l,timestamp:l.lastChangedTime,mesh:p,collider:m};o.set(l,g),Uo&&console.log("New plane detected, id="+g.id,g,{hasCollider:!!m,isGroup:p instanceof c.Group});try{const _=new CustomEvent("plane-tracking",{detail:{type:"plane-added",context:g}});this.dispatchEvent(_)}catch(_){console.error(_)}}}u&&(d?(u.visible=!0,u.matrix.fromArray(d.transform.matrix),u.matrix.premultiply(this._flipForwardMatrix)):u.visible=!1,Uo&&u.traverse(p=>{if(p instanceof c.Mesh)if(p.userData.normalsHelper)p.userData.normalsHelper.update();else{const m=new q.VertexNormalsHelper(p,.05,255);m.layers.disableAll(),m.layers.set(2),this.context.scene.add(m),p.userData.normalsHelper=m}}))}}}_flipForwardMatrix=new c.Matrix4().makeRotationY(Math.PI);checkIfContextShouldBeConvex(e,t){if(!e)return!0;if(e){const i=new c.Box3;i.expandByObject(e);const n=new c.Vector3;i.getSize(n);let o=!0;return n.x>2&&n.y>2&&n.z>1.5&&(o=!1),o&&"semanticLabel"in t&&t.semanticLabel==="wall"&&(o=!0),o}return!0}createGeometry(e){return"polygon"in e?this.createPlaneGeometry(e.polygon):"vertices"in e&&"indices"in e?this.createMeshGeometry(e.vertices,e.indices):new c.BufferGeometry}_verticesCache=new Map;createMeshGeometry(e,t){const i=e.toString()+"_"+t.toString();if(this._verticesCache.has(i))return this._verticesCache.get(i);const n=new c.BufferGeometry;n.setIndex(new c.BufferAttribute(t,1)),n.setAttribute("position",new c.BufferAttribute(e,3));const o=Array();for(let r=0;r<e.length;r+=3)o.push(e[r],e[r+2]);return n.setAttribute("uv",new c.BufferAttribute(e,3)),n.computeVertexNormals(),this._verticesCache.set(i,n),n}createPlaneGeometry(e){const t=new c.BufferGeometry,i=[],n=[];e.forEach(p=>{i.push(p.x,p.y,p.z),n.push(p.x,p.z)});const o=new c.Vector3(i[0],i[1],i[2]),r=new c.Vector3(i[3],i[4],i[5]),a=new c.Vector3(i[6],i[7],i[8]),l=new c.Vector3,h=new c.Vector3;l.subVectors(r,o),h.subVectors(a,o),l.cross(h),l.normalize();const d=[];for(let p=0;p<i.length/3;p++)d.push(l.x,l.y,l.z);const u=[];for(let p=2;p<e.length;++p)u.push(0,p-1,p);return t.setAttribute("position",new c.BufferAttribute(new Float32Array(i),3)),t.setAttribute("uv",new c.BufferAttribute(new Float32Array(n),2)),t.setAttribute("normal",new c.BufferAttribute(new Float32Array(d),3)),t.setIndex(u),t.computeBoundingBox(),t.computeBoundingSphere(),t}}dl([f(K)],Ts.prototype,"dataTemplate");dl([f()],Ts.prototype,"occluder");dl([f()],Ts.prototype,"initiateRoomCaptureIfNoData");dl([f()],Ts.prototype,"usePlaneData");dl([f()],Ts.prototype,"useMeshData");dl([f()],Ts.prototype,"runInVR");var hT=Object.defineProperty,dT=(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&&hT(e,t,n),n};const Rb=x("debugwebxr");class cf extends E{priority=0;get isActive(){return this.activeAndEnabled&&this.gameObject.visible}setAsActiveXRRig(){G.active?.setRigActive(this)}setPriority(e){this.priority=e}awake(){if(Rb){const e=new c.Object3D;e.position.y+=.5,this.gameObject.add(e);const t=e.addNewComponent(kr);t&&(t.isGizmo=!1);const i=new c.AxesHelper(.5);this.gameObject.add(i)}}isXRRig(){return!0}supportsXR(e){return!0}_startScale;onEnterXR(e){this._startScale=this.gameObject.scale.clone(),e.xr.addRig(this),Rb&&console.log("WebXR: add Rig",this.name,this.priority)}onLeaveXR(e){e.xr.removeRig(this),this._startScale&&this.gameObject&&this.gameObject.scale.copy(this._startScale)}}dT([f()],cf.prototype,"priority");class uT extends E{toggleKey="KeyP";update(){this.context.input.isKeyDown(this.toggleKey)&&this.context.domElement.classList.toggle("presentation-mode")}}P.add("AlignmentConstraint",Wc);P.add("Animation",Et);P.add("Animator",at);P.add("AudioListener",as);P.add("AudioSource",_i);P.add("Avatar_Brain_LookAt",wc);P.add("Avatar_MouthShapes",Xc);P.add("Avatar_MustacheShake",hg);P.add("AvatarBlink_Simple",vr);P.add("AvatarEyeLook_Rotation",ug);P.add("AxesHelper",za);P.add("BasicIKConstraint",pg);P.add("BoxHelperComponent",st);P.add("Camera",ti);P.add("CharacterController",wr);P.add("CharacterControllerInput",_s);P.add("SphereCollider",Na);P.add("BoxCollider",xu);P.add("MeshCollider",yo);P.add("CapsuleCollider",ps);P.add("ContactShadows",Qc);P.add("LogStats",gg);P.add("DeleteBox",to);P.add("Deletable",_g);P.add("DeviceFlag",Su);P.add("DragControls",qo);P.add("DropListener",vs);P.add("Duplicatable",Mg);P.add("EventListEvent",yu);P.add("EventTrigger",Pu);P.add("GltfExportBox",Eg);P.add("GltfExport",Tg);P.add("VariantAction",Lg);P.add("ChangeTransformOnClick",Pr);P.add("ChangeMaterialOnClick",Ig);P.add("SetActiveOnClick",jg);P.add("HideOnStart",Di);P.add("EmphasizeOnClick",Wa);P.add("PlayAudioOnClick",ro);P.add("PlayAnimationOnClick",Sc);P.add("PreliminaryAction",Ha);P.add("PreliminaryTrigger",eh);P.add("VisibilityAction",th);P.add("TapGestureTrigger",Ug);P.add("USDZExporter",an);P.add("Fog",Qa);P.add("BoxGizmo",kr);P.add("GridHelper",Ya);P.add("GroundProjectedEnv",$n);P.add("UsageMarker",Yc);P.add("Interactable",yg);P.add("FixedJoint",sy);P.add("HingeJoint",rh);P.add("Light",xt);P.add("LODGroup",ju);P.add("LookAtConstraint",br);P.add("NeedleMenu",Hn);P.add("NestedGltf",Za);P.add("Networking",ay);P.add("OffsetConstraint",Er);P.add("CameraTargetReachedEvent",vc);P.add("OrbitControls",de);P.add("ParticleSystemRenderer",qi);P.add("ParticleSystem",Pc);P.add("Attractor",el);P.add("PlayerColor",La);P.add("Antialiasing",ch);P.add("BloomEffect",Vu);P.add("ChromaticAberration",hh);P.add("ColorAdjustments",Co);P.add("DepthOfField",gn);P.add("EffectWrapper",Mc);P.add("PixelationEffect",dh);P.add("ScreenSpaceAmbientOcclusion",Ps);P.add("ScreenSpaceAmbientOcclusionN8",yn);P.add("SharpeningEffect",fh);P.add("TiltShiftEffect",qn);P.add("ToneMappingEffect",co);P.add("Vignette",Ir);P.add("Volume",il);P.add("ReflectionProbe",xc);P.add("Renderer",Ht);P.add("MeshRenderer",Kc);P.add("SkinnedMeshRenderer",Cg);P.add("Rigidbody",Fe);P.add("SceneSwitcher",Ne);P.add("ScreenCapture",Po);P.add("SeeThrough",Ms);P.add("ShadowCatcher",mh);P.add("RemoteSkybox",Wu);P.add("SmoothFollow",Gu);P.add("SpatialTriggerReceiver",zn);P.add("SpatialTrigger",qu);P.add("SpectatorCamera",Xu);P.add("SplineContainer",jr);P.add("SplineWalker",Qi);P.add("SpriteRenderer",oi);P.add("SyncedCamera",yy);P.add("SyncedRoom",_n);P.add("SyncedTransform",dn);P.add("TestRunner",_y);P.add("TestSimulateUserData",by);P.add("PlayableDirector",pr);P.add("SignalReceiver",vh);P.add("AnimationTrackHandler",Oc);P.add("AudioTrackHandler",cs);P.add("MarkerTrackHandler",Ku);P.add("SignalTrackHandler",kc);P.add("ControlTrackHandler",Zu);P.add("TransformGizmo",Br);P.add("BaseUIComponent",Ni);P.add("UIRootComponent",ih);P.add("Button",Os);P.add("Canvas",Da);P.add("CanvasGroup",lo);P.add("EventSystem",$t);P.add("Graphic",sh);P.add("MaskableGraphic",oh);P.add("Image",rl);P.add("RawImage",tf);P.add("InputField",Sy);P.add("VerticalLayoutGroup",Xg);P.add("HorizontalLayoutGroup",Qg);P.add("GridLayoutGroup",Yg);P.add("Outline",Xa);P.add("ObjectRaycaster",yi);P.add("GraphicRaycaster",_u);P.add("SpatialGrabRaycaster",cr);P.add("RectTransform",un);P.add("SpatialHtml",xh);P.add("Text",Tt);P.add("EnvironmentScene",sf);P.add("LookAt",Cy);P.add("OpenURL",al);P.add("VideoPlayer",Ze);P.add("Voip",go);P.add("ClickThrough",rf);P.add("CursorFollow",Ur);P.add("HoverAnimation",exports.HoverAnimation);P.add("ScrollFollow",ks);P.add("ViewBox",exports.ViewBox);P.add("Avatar",ao);P.add("XRControllerFollow",Es);P.add("XRControllerModel",ms);P.add("XRControllerMovement",vi);P.add("TeleportTarget",Au);P.add("WebARCameraBackground",Ch);P.add("WebARSessionRoot",Bi);P.add("WebXR",Du);P.add("AvatarMarker",Pe);P.add("WebXRImageTracking",Ph);P.add("WebXRPlaneTracking",Ts);P.add("XRRig",cf);P.add("XRFlag",Li);P.add("PlayerSync",Vg);P.add("PlayerState",Ui);P.add("PresentationMode",uT);const cc=ot,fT=x("debugtypestore");fT&&console.log(P);function pT(s,e){const i=Kv(s,e);return i!==void 0?i:null}const mT=new f1,gp=Symbol("deserialize-queue");async function gT(s,e,t,i=null,n){if(!t){console.debug("Can not create component instances: gltf is null");return}const o=[];let r=i;typeof r=="number"&&(r=new _t(i));const a=e.indexOf("?");e=a===-1?e:e.substring(0,a);const l=new Qm(t.scene);l.gltfId=e,l.context=s,l.gltf=t,l.nodeToObject=n?.nodeToObjectMap,l.implementationInformation=mT;let h=s[gp];if(h||(h=s[gp]=[]),t.scenes)for(const d of t.scenes)await mm(l,d,h,o,0);if(t.children)for(const d of t.children)await mm(l,d,h,o,0);s.new_scripts_pre_setup_callbacks.push(()=>{const d=s[gp];if(d){for(const u of d)yT(u,l);d.length=0}if(r){const u={},p=[];pm(t,r,u,p);for(const m of t.scenes)pm(m,r,u,p);for(const m of p)m.resolveGuids(u)}})}const fm=Symbol("original-component-name"),Yr=new Map;function pm(s,e,t,i){if(e===null||!s)return;const n=s.guid,o=s.guid;o?.length&&(Yr.has(o)||(cc&&console.log('Creating InstanceIdProvider with key "'+o+'" for object '+s.name),Yr.set(o,new _t(o))));const r=o&&Yr.get(o)||e;if(s.guid=r.generateUUID(),n&&n!=="invalid"&&(t[n]=s.guid),s&&s.userData&&s.userData.components)for(const a of s.userData.components){if(a===null)continue;const l=a.guid;l?Yr.has(l)||(cc&&console.log('Creating InstanceIdProvider with key "'+l+'" for component '+a[fm]),Yr.set(l,new _t(l))):cc&&console.warn("Can not create IdProvider: component "+a[fm]+" has no guid",a.guid);const h=Yr.get(l)||e,d=a.guid;a.guid=h.generateUUID(),d&&d!=="invalid"&&(t[d]=a.guid),a.resolveGuids&&i.push(a)}if(s.children)for(const a of s.children)pm(a,e,t,i)}const Pl=[];async function mm(s,e,t,i,n){if(!e)return;const o=e.userData;if(o){const r=o.builtin_components;if(r&&r.length>0)for(const a of r)try{if(a===null)continue;const l=P.get(a.name);if(l!=null){const h=new l;h.sourceId=s.gltfId,Ra(h,a,s.implementationInformation),h.context=s.context,"guid"in a&&(h[Ql]=a.guid),h[fm]=a.name,Zo(e,h,!1),t.push({instance:h,compData:a,obj:e}),h.isCamera&&s.context&&s.context.mainCamera===null&&h.tag==="MainCamera"&&s.context.setCurrentCamera(h),s.context?.physics?.engine?.isInitialized===!1&&(h.isCollider||h.isRigidbody)&&s.context?.physics.engine?.initialize()}else cc&&console.debug("unknown component: "+a.name),Pl.includes(a.name)||Pl.push(a.name)}catch(l){console.error(a.name+" - "+l.message,l)}}if(e.children)for(const r of e.children)await mm(s,r,t,i,n+1);if(Pl.length>0&&n===0){const r=Pl.join(", ");console.warn(`Unknown components in scene: ${r}`),Pl.length=0,pi()&&we(`<strong>Unknown components in scene</strong>:
|
|
1479
|
+
`+u.xrData.lastChangedTime.toFixed(2),.02))}}bounds=new c.Box3;center=new c.Vector3;labelOffset=new c.Vector3;removeData(e,t){const i=t.get(e);if(!i)return;t.delete(e),Uo&&console.log("Plane no longer tracked, id="+i.id),i.mesh&&(i.mesh.removeFromParent(),i.mesh.traverse(o=>{const r=o.userData.normalsHelper;r?(r.dispose(),r.removeFromParent()):Uo&&console.warn("No normals helper found for mesh",i.mesh)}),gi(i.mesh,!0,!0));const n=new CustomEvent("plane-tracking",{detail:{type:"plane-removed",context:i}});this.dispatchEvent(n)}_dataId=1;_allPlanes=new Map;_allMeshes=new Map;firstTimeNoPlanesDetected=-100;makeOccluder=(e,t,i=!1)=>{if(t){if(t instanceof Array){for(const n of t)this.makeOccluder(e,n,i);return}!i&&!t.name.toLowerCase().includes("occlu")||(t.colorWrite=!1,t.depthTest=!0,t.depthWrite=!0,t.transparent=!1,t.polygonOffset=!0,t.polygonOffsetFactor=1,t.polygonOffsetUnits=.1,e.renderOrder=-1e3)}};processFrameData(e,t,i,n,o){const a=this.context.renderer.xr.getReferenceSpace();if(a){for(const l of o.keys())n.has(l)||this.removeData(l,o);for(const l of n){const h="planeSpace"in l?l.planeSpace:"meshSpace"in l?l.meshSpace:void 0;if(!h)continue;const d=i.getPose(h,a);let u;if(o.has(l)){const p=o.get(l);if(u=p.mesh,p.timestamp<l.lastChangedTime){if(p.timestamp=l.lastChangedTime,p.mesh){const g=this.createGeometry(l);if(p.mesh instanceof c.Mesh)p.mesh.geometry.dispose(),p.mesh.geometry=g,this.makeOccluder(p.mesh,p.mesh.material);else if(p.mesh instanceof c.Group)for(const _ of p.mesh.children)_ instanceof c.Mesh&&(_.geometry.dispose(),_.geometry=g,this.makeOccluder(_,_.material));if(p.collider){const _=p.mesh;p.collider.sharedMesh=_,p.collider.convex=this.checkIfContextShouldBeConvex(_,p.xrData),p.collider.onDisable(),p.collider.onEnable()}Uo&&(console.log("Plane updated, id="+p.id,p),p.mesh.traverse(_=>{if(!(_ instanceof c.Mesh))return;const y=_.userData.normalsHelper;y&&y.update()}))}const m=new CustomEvent("plane-tracking",{detail:{type:"plane-updated",context:p}});this.dispatchEvent(m)}}else{if(!this.dataTemplate){const p=new c.Mesh;Uo?p.material=new c.MeshNormalMaterial:this.occluder?(p.material=new c.MeshBasicMaterial,this.makeOccluder(p,p.material,!0)):p.material=new c.MeshBasicMaterial({wireframe:!0,opacity:.5,transparent:!0,color:3355443}),this.dataTemplate=new K("","",p)}if(!this.dataTemplate.asset)this.dataTemplate.loadAssetAsync();else{const p=S.instantiate(this.dataTemplate.asset);if(p.name="xr-tracked-plane",u=p,km(p,!1),p instanceof c.Mesh)be(p.geometry),p.geometry=this.createGeometry(l),this.makeOccluder(p,p.material,this.occluder&&!this.dataTemplate);else if(p instanceof c.Group)for(const _ of p.children)_ instanceof c.Mesh&&(be(_.geometry),_.geometry=this.createGeometry(l),this.makeOccluder(_,_.material,this.occluder&&!this.dataTemplate));const m=p.getComponent(yo);if(m){const _=p;m.sharedMesh=_,m.convex=this.checkIfContextShouldBeConvex(_,l),m.onDisable(),m.onEnable()}p.matrixAutoUpdate=!1,p.matrixWorldNeedsUpdate=!0,t.add(p);const g={id:this._dataId++,xrData:l,timestamp:l.lastChangedTime,mesh:p,collider:m};o.set(l,g),Uo&&console.log("New plane detected, id="+g.id,g,{hasCollider:!!m,isGroup:p instanceof c.Group});try{const _=new CustomEvent("plane-tracking",{detail:{type:"plane-added",context:g}});this.dispatchEvent(_)}catch(_){console.error(_)}}}u&&(d?(u.visible=!0,u.matrix.fromArray(d.transform.matrix),u.matrix.premultiply(this._flipForwardMatrix)):u.visible=!1,Uo&&u.traverse(p=>{if(p instanceof c.Mesh)if(p.userData.normalsHelper)p.userData.normalsHelper.update();else{const m=new q.VertexNormalsHelper(p,.05,255);m.layers.disableAll(),m.layers.set(2),this.context.scene.add(m),p.userData.normalsHelper=m}}))}}}_flipForwardMatrix=new c.Matrix4().makeRotationY(Math.PI);checkIfContextShouldBeConvex(e,t){if(!e)return!0;if(e){const i=new c.Box3;i.expandByObject(e);const n=new c.Vector3;i.getSize(n);let o=!0;return n.x>2&&n.y>2&&n.z>1.5&&(o=!1),o&&"semanticLabel"in t&&t.semanticLabel==="wall"&&(o=!0),o}return!0}createGeometry(e){return"polygon"in e?this.createPlaneGeometry(e.polygon):"vertices"in e&&"indices"in e?this.createMeshGeometry(e.vertices,e.indices):new c.BufferGeometry}_verticesCache=new Map;createMeshGeometry(e,t){const i=e.toString()+"_"+t.toString();if(this._verticesCache.has(i))return this._verticesCache.get(i);const n=new c.BufferGeometry;n.setIndex(new c.BufferAttribute(t,1)),n.setAttribute("position",new c.BufferAttribute(e,3));const o=Array();for(let r=0;r<e.length;r+=3)o.push(e[r],e[r+2]);return n.setAttribute("uv",new c.BufferAttribute(e,3)),n.computeVertexNormals(),this._verticesCache.set(i,n),n}createPlaneGeometry(e){const t=new c.BufferGeometry,i=[],n=[];e.forEach(p=>{i.push(p.x,p.y,p.z),n.push(p.x,p.z)});const o=new c.Vector3(i[0],i[1],i[2]),r=new c.Vector3(i[3],i[4],i[5]),a=new c.Vector3(i[6],i[7],i[8]),l=new c.Vector3,h=new c.Vector3;l.subVectors(r,o),h.subVectors(a,o),l.cross(h),l.normalize();const d=[];for(let p=0;p<i.length/3;p++)d.push(l.x,l.y,l.z);const u=[];for(let p=2;p<e.length;++p)u.push(0,p-1,p);return t.setAttribute("position",new c.BufferAttribute(new Float32Array(i),3)),t.setAttribute("uv",new c.BufferAttribute(new Float32Array(n),2)),t.setAttribute("normal",new c.BufferAttribute(new Float32Array(d),3)),t.setIndex(u),t.computeBoundingBox(),t.computeBoundingSphere(),t}}dl([f(K)],Ts.prototype,"dataTemplate");dl([f()],Ts.prototype,"occluder");dl([f()],Ts.prototype,"initiateRoomCaptureIfNoData");dl([f()],Ts.prototype,"usePlaneData");dl([f()],Ts.prototype,"useMeshData");dl([f()],Ts.prototype,"runInVR");var hT=Object.defineProperty,dT=(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&&hT(e,t,n),n};const Rb=x("debugwebxr");class cf extends E{priority=0;get isActive(){return this.activeAndEnabled&&this.gameObject.visible}setAsActiveXRRig(){G.active?.setRigActive(this)}setPriority(e){this.priority=e}awake(){if(Rb){const e=new c.Object3D;e.position.y+=.5,this.gameObject.add(e);const t=e.addNewComponent(kr);t&&(t.isGizmo=!1);const i=new c.AxesHelper(.5);this.gameObject.add(i)}}isXRRig(){return!0}supportsXR(e){return!0}_startScale;onEnterXR(e){this._startScale=this.gameObject.scale.clone(),e.xr.addRig(this),Rb&&console.log("WebXR: add Rig",this.name,this.priority)}onLeaveXR(e){e.xr.removeRig(this),this._startScale&&this.gameObject&&this.gameObject.scale.copy(this._startScale)}}dT([f()],cf.prototype,"priority");class uT extends E{toggleKey="KeyP";update(){this.context.input.isKeyDown(this.toggleKey)&&this.context.domElement.classList.toggle("presentation-mode")}}P.add("AlignmentConstraint",Wc);P.add("Animation",Et);P.add("Animator",at);P.add("AudioListener",as);P.add("AudioSource",_i);P.add("Avatar_Brain_LookAt",wc);P.add("Avatar_MouthShapes",Xc);P.add("Avatar_MustacheShake",hg);P.add("AvatarBlink_Simple",vr);P.add("AvatarEyeLook_Rotation",ug);P.add("AxesHelper",za);P.add("BasicIKConstraint",pg);P.add("BoxHelperComponent",st);P.add("Camera",ti);P.add("CharacterController",wr);P.add("CharacterControllerInput",_s);P.add("SphereCollider",Na);P.add("BoxCollider",xu);P.add("MeshCollider",yo);P.add("CapsuleCollider",ps);P.add("ContactShadows",Qc);P.add("LogStats",gg);P.add("DeleteBox",to);P.add("Deletable",_g);P.add("DeviceFlag",Su);P.add("DragControls",qo);P.add("DropListener",vs);P.add("Duplicatable",Mg);P.add("EventListEvent",yu);P.add("EventTrigger",Pu);P.add("GltfExportBox",Eg);P.add("GltfExport",Tg);P.add("VariantAction",Lg);P.add("ChangeTransformOnClick",Pr);P.add("ChangeMaterialOnClick",Ig);P.add("SetActiveOnClick",jg);P.add("HideOnStart",Di);P.add("EmphasizeOnClick",Wa);P.add("PlayAudioOnClick",ro);P.add("PlayAnimationOnClick",Sc);P.add("PreliminaryAction",Ha);P.add("PreliminaryTrigger",eh);P.add("VisibilityAction",th);P.add("TapGestureTrigger",Ug);P.add("USDZExporter",an);P.add("Fog",Qa);P.add("BoxGizmo",kr);P.add("GridHelper",Ya);P.add("GroundProjectedEnv",$n);P.add("UsageMarker",Yc);P.add("Interactable",yg);P.add("FixedJoint",sy);P.add("HingeJoint",rh);P.add("Light",xt);P.add("LODGroup",ju);P.add("LookAtConstraint",br);P.add("NeedleMenu",Hn);P.add("NestedGltf",Za);P.add("Networking",ay);P.add("OffsetConstraint",Er);P.add("CameraTargetReachedEvent",vc);P.add("OrbitControls",de);P.add("ParticleSystemRenderer",qi);P.add("ParticleSystem",Pc);P.add("Attractor",el);P.add("PlayerColor",La);P.add("Antialiasing",ch);P.add("BloomEffect",Vu);P.add("ChromaticAberration",hh);P.add("ColorAdjustments",Co);P.add("DepthOfField",gn);P.add("EffectWrapper",Mc);P.add("PixelationEffect",dh);P.add("ScreenSpaceAmbientOcclusion",Ps);P.add("ScreenSpaceAmbientOcclusionN8",yn);P.add("SharpeningEffect",fh);P.add("TiltShiftEffect",qn);P.add("ToneMappingEffect",co);P.add("Vignette",Ir);P.add("Volume",il);P.add("ReflectionProbe",xc);P.add("Renderer",Ht);P.add("MeshRenderer",Kc);P.add("SkinnedMeshRenderer",Cg);P.add("Rigidbody",Fe);P.add("SceneSwitcher",Ne);P.add("ScreenCapture",Po);P.add("SeeThrough",Ms);P.add("ShadowCatcher",mh);P.add("RemoteSkybox",Wu);P.add("SmoothFollow",Gu);P.add("SpatialTriggerReceiver",zn);P.add("SpatialTrigger",qu);P.add("SpectatorCamera",Xu);P.add("SplineContainer",jr);P.add("SplineWalker",Qi);P.add("SpriteRenderer",oi);P.add("SyncedCamera",yy);P.add("SyncedRoom",_n);P.add("SyncedTransform",dn);P.add("TestRunner",_y);P.add("TestSimulateUserData",by);P.add("PlayableDirector",pr);P.add("SignalReceiver",vh);P.add("AnimationTrackHandler",Oc);P.add("AudioTrackHandler",cs);P.add("MarkerTrackHandler",Ku);P.add("SignalTrackHandler",kc);P.add("ControlTrackHandler",Zu);P.add("TransformGizmo",Br);P.add("BaseUIComponent",Ni);P.add("UIRootComponent",ih);P.add("Button",Os);P.add("Canvas",Da);P.add("CanvasGroup",lo);P.add("EventSystem",$t);P.add("Graphic",sh);P.add("MaskableGraphic",oh);P.add("Image",rl);P.add("RawImage",tf);P.add("InputField",Sy);P.add("VerticalLayoutGroup",Xg);P.add("HorizontalLayoutGroup",Qg);P.add("GridLayoutGroup",Yg);P.add("Outline",Xa);P.add("ObjectRaycaster",yi);P.add("GraphicRaycaster",_u);P.add("SpatialGrabRaycaster",cr);P.add("RectTransform",un);P.add("SpatialHtml",xh);P.add("Text",Tt);P.add("EnvironmentScene",sf);P.add("LookAt",Cy);P.add("OpenURL",al);P.add("VideoPlayer",Je);P.add("Voip",go);P.add("ClickThrough",rf);P.add("CursorFollow",Ur);P.add("HoverAnimation",exports.HoverAnimation);P.add("ScrollFollow",ks);P.add("ViewBox",exports.ViewBox);P.add("Avatar",ao);P.add("XRControllerFollow",Es);P.add("XRControllerModel",ms);P.add("XRControllerMovement",vi);P.add("TeleportTarget",Au);P.add("WebARCameraBackground",Ch);P.add("WebARSessionRoot",Bi);P.add("WebXR",Du);P.add("AvatarMarker",Pe);P.add("WebXRImageTracking",Ph);P.add("WebXRPlaneTracking",Ts);P.add("XRRig",cf);P.add("XRFlag",Li);P.add("PlayerSync",Vg);P.add("PlayerState",Ui);P.add("PresentationMode",uT);const cc=ot,fT=x("debugtypestore");fT&&console.log(P);function pT(s,e){const i=Kv(s,e);return i!==void 0?i:null}const mT=new f1,gp=Symbol("deserialize-queue");async function gT(s,e,t,i=null,n){if(!t){console.debug("Can not create component instances: gltf is null");return}const o=[];let r=i;typeof r=="number"&&(r=new _t(i));const a=e.indexOf("?");e=a===-1?e:e.substring(0,a);const l=new Qm(t.scene);l.gltfId=e,l.context=s,l.gltf=t,l.nodeToObject=n?.nodeToObjectMap,l.implementationInformation=mT;let h=s[gp];if(h||(h=s[gp]=[]),t.scenes)for(const d of t.scenes)await mm(l,d,h,o,0);if(t.children)for(const d of t.children)await mm(l,d,h,o,0);s.new_scripts_pre_setup_callbacks.push(()=>{const d=s[gp];if(d){for(const u of d)yT(u,l);d.length=0}if(r){const u={},p=[];pm(t,r,u,p);for(const m of t.scenes)pm(m,r,u,p);for(const m of p)m.resolveGuids(u)}})}const fm=Symbol("original-component-name"),Yr=new Map;function pm(s,e,t,i){if(e===null||!s)return;const n=s.guid,o=s.guid;o?.length&&(Yr.has(o)||(cc&&console.log('Creating InstanceIdProvider with key "'+o+'" for object '+s.name),Yr.set(o,new _t(o))));const r=o&&Yr.get(o)||e;if(s.guid=r.generateUUID(),n&&n!=="invalid"&&(t[n]=s.guid),s&&s.userData&&s.userData.components)for(const a of s.userData.components){if(a===null)continue;const l=a.guid;l?Yr.has(l)||(cc&&console.log('Creating InstanceIdProvider with key "'+l+'" for component '+a[fm]),Yr.set(l,new _t(l))):cc&&console.warn("Can not create IdProvider: component "+a[fm]+" has no guid",a.guid);const h=Yr.get(l)||e,d=a.guid;a.guid=h.generateUUID(),d&&d!=="invalid"&&(t[d]=a.guid),a.resolveGuids&&i.push(a)}if(s.children)for(const a of s.children)pm(a,e,t,i)}const Pl=[];async function mm(s,e,t,i,n){if(!e)return;const o=e.userData;if(o){const r=o.builtin_components;if(r&&r.length>0)for(const a of r)try{if(a===null)continue;const l=P.get(a.name);if(l!=null){const h=new l;h.sourceId=s.gltfId,Ra(h,a,s.implementationInformation),h.context=s.context,"guid"in a&&(h[Ql]=a.guid),h[fm]=a.name,Zo(e,h,!1),t.push({instance:h,compData:a,obj:e}),h.isCamera&&s.context&&s.context.mainCamera===null&&h.tag==="MainCamera"&&s.context.setCurrentCamera(h),s.context?.physics?.engine?.isInitialized===!1&&(h.isCollider||h.isRigidbody)&&s.context?.physics.engine?.initialize()}else cc&&console.debug("unknown component: "+a.name),Pl.includes(a.name)||Pl.push(a.name)}catch(l){console.error(a.name+" - "+l.message,l)}}if(e.children)for(const r of e.children)await mm(s,r,t,i,n+1);if(Pl.length>0&&n===0){const r=Pl.join(", ");console.warn(`Unknown components in scene: ${r}`),Pl.length=0,pi()&&we(`<strong>Unknown components in scene</strong>:
|
|
1480
1480
|
|
|
1481
1481
|
${r}
|
|
1482
1482
|
|
|
@@ -1650,4 +1650,4 @@ Error:`,r),null}}updateColliderCollisionGroups(e){const t=e[Pt],i=e.membership;l
|
|
|
1650
1650
|
justify-content: center;
|
|
1651
1651
|
gap: .5rem;
|
|
1652
1652
|
}
|
|
1653
|
-
`),this.#n.innerHTML=this.#e.innerHTML,this.#n.style.cssText="display: flex; align-items: center; justify-content: center;",this.#e.innerHTML=this.#n.outerHTML,this.#t.innerHTML=this.#e.outerHTML,this.#t.prepend(this.#s),Fd(Hp,{element:this.#t}),this.#o?.disconnect(),this.#o??=new MutationObserver(()=>this.#c()),this.#o.observe(this.#e,{attributes:!0}),bp&&console.log("Needle Button updated",this)}#c(){this.#e&&(this.#e.style.display==="none"?this.style.display="none":this.style.display==="none"&&(this.style.display=""))}#a=e=>{bp&&console.log("Needle Button clicked",{defaultPrevented:e.defaultPrevented,hasButton:!!this.#e}),!e.defaultPrevented&&this.#e&&this.#e.click()}}typeof window<"u"&&!window.customElements.get(jb)&&window.customElements.define(jb,xx);const Tl=x("debugavatar");class Ty{root;head;leftHand;rigthHand;get isValid(){return this.head!==null&&this.head!==void 0}constructor(e,t,i,n){this.root=e,this.head=t,this.leftHand=i,this.rigthHand=n,this.root?.traverse(o=>o.layers.set(2))}}class Sx{avatarRegistryUrl=null;async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let i=null;if(typeof t=="string"){if(i=await this.loadAvatar(e,t),!i){const o=new fn;i=S.instantiate(xa(t,e.scene),o)}}else i=t;if(!i)return null;const n=this.findAvatar(i);return n.isValid?(Tl&&console.log("[Custom Avatar] valid config",t,Tl?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,Tl?n:""),null)}async loadAvatar(e,t){if(console.assert(t!=null&&typeof t=="string","Avatar id must not be null"),t.length<=0||!t)return null;if(Tl&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const n=await fetch("./"+t);let o=null;if(n.ok){const a=await n.blob();a&&(o=await a.arrayBuffer())}return o?(await cn().parseSync(e,o,null,0))?.scene??null:null}const i=new q.GLTFLoader;return ng(i,e),new Promise((n,o)=>{const r=this.avatarRegistryUrl+"/"+t;i.load(r,async a=>{await cn().createBuiltinComponents(e,r,a,null,void 0),n(a.scene)},a=>{Tl&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),n(null)})})}cacheModel(e,t){}findAvatar(e){const t=e;let i=t;i.children.length==1&&(i=e.children[0]);let n=this.findAvatarPart(i,["head"]);const o=this.findAvatarPart(i,["left","hand"]),r=this.findAvatarPart(i,["right","hand"]);if(!n){n=t;const l=new c.Vector3;new c.Box3().setFromObject(n).getSize(l);const h=Math.max(l.x,l.y,l.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+h+" meters! Should be < 0.3m"),h>.3&&n.scale.multiplyScalar(1/h*.3)}return new Ty(t,n,o,r)}findAvatarPart(e,t){const i=e.name.toLowerCase();let n=!0;for(const o of t){if(!n)break;i.indexOf(o)===-1&&(n=!1)}if(n)return e;if(e.children)for(const o of e.children){const r=this.findAvatarPart(o,t);if(r)return r}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}class Cx{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}class Px{}const zT=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:he,ActionCollection:Rw,ActionModel:Kt,AlignmentConstraint:Wc,Animation:Et,AnimationCurve:ah,AnimationExtension:Ou,AnimationTrackHandler:Oc,Animator:at,AnimatorController:zi,Antialiasing:ch,Attractor:el,AudioExtension:Cr,AudioListener:as,AudioSource:_i,AudioTrackHandler:cs,Avatar:ao,AvatarBlink_Simple:vr,AvatarEyeLook_Rotation:ug,AvatarLoader:Sx,AvatarMarker:Pe,AvatarModel:Ty,Avatar_Brain_LookAt:wc,Avatar_MouthShapes:Xc,Avatar_MustacheShake:hg,Avatar_POI:sr,AxesHelper:za,BaseUIComponent:Ni,BasicIKConstraint:pg,BehaviorExtension:Wg,BehaviorModel:bt,BloomEffect:Vu,BoxCollider:xu,BoxGizmo:kr,BoxHelperComponent:st,Button:Os,CallInfo:rs,Camera:ti,CameraTargetReachedEvent:vc,Canvas:Da,CanvasGroup:lo,CapsuleCollider:ps,ChangeMaterialOnClick:Ig,ChangeTransformOnClick:Pr,CharacterController:wr,CharacterControllerInput:_s,ChromaticAberration:hh,ClickThrough:rf,ColorAdjustments:Co,ColorBySpeedModule:Ja,ColorOverLifetimeModule:Fu,ContactShadows:Qc,ControlTrackHandler:Zu,CursorFollow:Ur,CustomBranding:Or,Deletable:_g,DeleteBox:to,DepthOfField:gn,DeviceFlag:Su,DocumentExtension:Cx,DragControls:qo,DropListener:vs,Duplicatable:Mg,EffectWrapper:Mc,EmissionModule:Cs,EmphasizeOnClick:Wa,EnvironmentScene:sf,EventList:oe,EventListEvent:yu,EventSystem:$t,EventTrigger:Pu,FieldWithDefault:dw,FixedJoint:sy,Fog:Qa,GltfExport:Tg,GltfExportBox:Eg,Gradient:Rr,Graphic:sh,GraphicRaycaster:_u,GridHelper:Ya,GridLayoutGroup:Yg,GroundProjectedEnv:$n,GroupActionModel:Xo,HideOnStart:Di,HingeJoint:rh,HorizontalLayoutGroup:Qg,get HoverAnimation(){return exports.HoverAnimation},Image:rl,InheritVelocityModule:cy,InputField:Sy,InstanceHandle:or,InstancingHandler:dr,Interactable:yg,Keyframe:ii,LODGroup:ju,LODModel:Ka,Light:xt,LimitVelocityOverLifetimeModule:et,LogStats:gg,LookAt:Cy,LookAtConstraint:br,MainModule:At,MarkerTrackHandler:Ku,MaskableGraphic:oh,MeshCollider:yo,MeshRenderer:Kc,MinMaxCurve:H,MinMaxGradient:Tr,NeedleMenu:Hn,NestedGltf:Za,Networking:ay,NoiseModule:pe,ObjectRaycaster:yi,OffsetConstraint:Er,OpenURL:al,OrbitControls:de,Outline:Xa,Padding:Mr,ParticleBurst:Kd,ParticleSubEmitter:hy,ParticleSystem:Pc,ParticleSystemRenderer:qi,PhysicsExtension:Hg,PixelationEffect:dh,PlayAnimationOnClick:Sc,PlayAudioOnClick:ro,PlayableDirector:pr,PlayerColor:La,PointerEventData:Gc,PostProcessingHandler:my,PreliminaryAction:Ha,PreliminaryTrigger:eh,RawImage:tf,Rect:Iw,RectTransform:un,ReflectionProbe:xc,RegisteredAnimationInfo:Zs,RemoteSkybox:Wu,Renderer:Ht,RendererLightmap:Sg,Rigidbody:Fe,RotationBySpeedModule:Gi,RotationOverLifetimeModule:mn,SceneSwitcher:Ne,ScreenCapture:Po,ScreenSpaceAmbientOcclusion:Ps,ScreenSpaceAmbientOcclusionN8:yn,ScrollFollow:ks,SeeThrough:Ms,SetActiveOnClick:jg,ShadowCatcher:mh,ShapeModule:ly,SharpeningEffect:fh,SignalAsset:Yu,SignalReceiver:vh,SignalReceiverEvent:bh,SignalTrackHandler:kc,Size:Lw,SizeBySpeedModule:ai,SizeOverLifetimeModule:Ar,SkinnedMeshRenderer:Cg,SmoothFollow:Gu,SpatialGrabRaycaster:cr,SpatialHtml:xh,SpatialTrigger:qu,SpatialTriggerReceiver:zn,SpectatorCamera:Xu,SphereCollider:Na,SplineContainer:jr,SplineData:Vn,SplineWalker:Qi,Sprite:ws,SpriteData:va,SpriteRenderer:oi,SpriteSheet:Aa,SubEmitterSystem:Zd,SyncedCamera:yy,SyncedRoom:_n,SyncedTransform:dn,TapGestureTrigger:Ug,TeleportTarget:Au,TestRunner:_y,TestSimulateUserData:by,Text:Tt,TextBuilder:qg,TextExtension:Lu,TextureSheetAnimationModule:Dt,TiltShiftEffect:qn,ToneMappingEffect:co,TrailModule:Te,TransformData:Ee,TransformGizmo:Br,TriggerBuilder:kt,TriggerModel:io,UIRaycastUtils:rg,UIRootComponent:ih,USDZExporter:an,USDZText:ha,USDZUIExtension:Zg,UsageMarker:Yc,VariantAction:Lg,VelocityOverLifetimeModule:Ie,VerticalLayoutGroup:Xg,VideoPlayer:Ze,get ViewBox(){return exports.ViewBox},Vignette:Ir,VisibilityAction:th,Voip:go,Volume:il,VolumeParameter:F,VolumeProfile:zu,WebARCameraBackground:Ch,WebARSessionRoot:Bi,WebXR:Du,WebXRImageTracking:Ph,WebXRImageTrackingModel:Rs,WebXRPlaneTracking:Ts,WebXRTrackedImage:Ia,XRControllerFollow:Es,XRControllerModel:ms,XRControllerMovement:vi,XRFlag:Li,XRRig:cf,XRState:Vt,__Ignore:Px},Symbol.toStringTag,{value:"Module"})),Rc=x("debugmissingcamera");le.registerCallback(ae.MissingCamera,s=>{Rc&&console.warn("Creating missing camera");const e=s.context.scene,t=new c.PerspectiveCamera;t.name="Default Fallback Camera",e.add(t);const i=new ti;if(i.sourceId=s.files?.[0]?.src??"unknown",i.fieldOfView=35,s.context.domElement.getAttribute("transparent")!=null)i.clearFlags=nr.Uninitialized;else if(s.context.domElement.getAttribute("background-image")?.length||s.context.lightmaps.tryGetSkybox(i.sourceId))i.clearFlags=nr.Skybox;else{if(i.clearFlags=nr.SolidColor,!s.context.domElement.getAttribute("background-color")){let a="#efefef";typeof window!==void 0&&window.matchMedia("(prefers-color-scheme: dark)").matches&&(a="#1f1f1f"),e.background=new c.Color(a)}if(!e.environment){const a=new c.PMREMGenerator$1(s.context.renderer),l=new sf("neutral");e.environment=a.fromScene(l,.025).texture}}const o=Zo(t,i,!0);return t.position.x=0,t.position.y=1,t.position.z=2,s.context.domElement?.cameraControls!=!1&&Mx(s.context,o),o});le.registerCallback(ae.ContextCreated,s=>{if(!s.context.mainCamera){Rc&&console.log("Will not auto-fit because a default camera exists");return}if(s.context.domElement?.cameraControls==!0){if(Qb(s.context.mainCamera)?.isCameraController==!0){Rc&&console.log("Will not auto-fit because a camera controller exists");return}Mx(s.context)}});function Mx(s,e){e=e??s.mainCameraComponent;const t=e?.gameObject;if(Rc&&console.log("Creating default camera controls",e?.name),t){const i=Fc(t,de);i.sourceId=e?.sourceId??"unknown";const n=s.domElement.getAttribute("auto-rotate");i.autoRotate=n!="0"&&n?.toLowerCase()!="false";const o=Number.parseFloat(n||".5");i.autoRotateSpeed=isNaN(o)?.5:o,Rc&&console.log("Auto-rotate",i.autoRotate,"speed:",i.autoRotateSpeed);const r=s.domElement.getAttribute("auto-fit");i.autoFit=r!=="0"&&r?.toLowerCase()!="false",i.autoTarget=!0}else console.warn("Missing camera object, can not add orbit controls")}le.registerCallback(ae.ContextCreated,s=>{const e=s.context.domElement.getAttribute("autoplay");if(e!==void 0&&(e===""||e==="true"||e==="1")&&s.files)for(const t of s.files)S.foreachComponent(t.file.scene,n=>{if(n.enabled!==!1){if(n instanceof Et&&n.playAutomatically||n instanceof at||n instanceof pr&&n.playOnAwake===!0)return!0;if(n instanceof Et)return n.playAutomatically=!0,!0;if(n instanceof pr)return n.playOnAwake=!0,!0}},!0)!==!0&&Nn.autoplayAnimations(t.file)});exports.SplineUtils=void 0;(s=>{function e(t,i=!1,n=.75){const o=new jr,r=1-I.clamp(n,0,1);return t.forEach((a,l)=>{const h=new c.Vector3;l<t.length-1?h.subVectors(t[l+1],a).normalize().multiplyScalar(r):i&&t.length>1&&h.subVectors(t[0],a).normalize().multiplyScalar(r);const d=new Vn;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 NT extends re.WorkerBase{constructor(){super(new Worker(new URL("/generateMeshBVH.worker-iyfPIK6R.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:ua&&ua.tagName.toUpperCase()==="SCRIPT"&&ua.src||new URL("needle-engine.bundle-fbFZTOKP.umd.cjs",document.baseURI).href),{type:"module"})),this.name="GenerateMeshBVHWorker"}runTask(e,t,i={}){return new Promise((n,o)=>{if(t.getAttribute("position").isInterleavedBufferAttribute||t.index&&t.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");e.onerror=h=>{o(new Error(`[GenerateMeshBVHWorker] ${h.message||"Unknown error. Please check the server console. If you're using vite try adding 'three-mesh-bvh' to 'optimizeDeps.exclude' in your vite.config.js"}`))},e.onmessage=h=>{const{data:d}=h;if(d.error)o(new Error(d.error)),e.onmessage=null;else if(d.serialized){const{serialized:u,position:p}=d,m=re.MeshBVH.deserialize(u,t,{setIndex:!1}),g=Object.assign({setBoundingBox:!0},i);if(t.attributes.position.array=p,u.index)if(t.index)t.index.array=u.index;else{const _=new c.BufferAttribute(u.index,1,!1);t.setIndex(_)}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)))})}}const VT=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:NT},Symbol.toStringTag,{value:"Module"}));exports.$physicsKey=hM;exports.ActionBuilder=he;exports.ActionCollection=Rw;exports.ActionModel=Kt;exports.Addressables=f0;exports.AlignmentConstraint=Wc;exports.AmbientMode=_a;exports.Animation=Et;exports.AnimationCurve=ah;exports.AnimationExtension=Ou;exports.AnimationTrackHandler=Oc;exports.AnimationUtils=Nn;exports.Animator=at;exports.AnimatorConditionMode=Gs;exports.AnimatorController=zi;exports.AnimatorControllerParameterType=sg;exports.AnimatorStateInfo=jl;exports.Antialiasing=ch;exports.Application=hn;exports.AssetDatabase=Rv;exports.AssetReference=K;exports.Attractor=el;exports.AudioExtension=Cr;exports.AudioListener=as;exports.AudioSource=_i;exports.AudioTrackHandler=cs;exports.Avatar=ao;exports.AvatarBlink_Simple=vr;exports.AvatarEyeLook_Rotation=ug;exports.AvatarLoader=Sx;exports.AvatarMarker=Pe;exports.AvatarModel=Ty;exports.Avatar_Brain_LookAt=wc;exports.Avatar_MouthShapes=Xc;exports.Avatar_MustacheShake=hg;exports.Avatar_POI=sr;exports.Axes=la;exports.AxesHelper=za;exports.BUILD_TIME=uc;exports.BaseUIComponent=Ni;exports.BasicIKConstraint=pg;exports.BehaviorExtension=Wg;exports.BehaviorModel=bt;exports.BloomEffect=Vu;exports.BoxCollider=xu;exports.BoxGizmo=kr;exports.BoxHelperComponent=st;exports.Button=Os;exports.ButtonsFactory=ji;exports.CallDirection=Q0;exports.CallInfo=rs;exports.Camera=ti;exports.CameraTargetReachedEvent=vc;exports.Canvas=Da;exports.CanvasGroup=lo;exports.CapsuleCollider=ps;exports.ChangeMaterialOnClick=Ig;exports.ChangeTransformOnClick=Pr;exports.CharacterController=wr;exports.CharacterControllerInput=_s;exports.ChromaticAberration=hh;exports.CircularBuffer=mi;exports.ClearFlags=nr;exports.ClickThrough=rf;exports.ClipExtrapolation=Pn;exports.Collider=Hi;exports.Collision=G0;exports.CollisionDetectionMode=gu;exports.ColorAdjustments=Co;exports.ColorBySpeedModule=Ja;exports.ColorOverLifetimeModule=Fu;exports.Component=yP;exports.Component$1=E;exports.ComponentLifecycleEvents=au;exports.Components=zT;exports.ConnectionEvents=Cv;exports.ContactPoint=H0;exports.ContactShadows=Qc;exports.Context=U;exports.ContextArgs=tP;exports.ContextEvent=ae;exports.ContextRegistry=le;exports.ControlTrackHandler=Zu;exports.CursorFollow=Ur;exports.CustomBranding=Or;exports.CustomShader=_e;exports.DefaultReflectionMode=Ud;exports.Deletable=_g;exports.DeleteBox=to;exports.DepthOfField=gn;exports.DeviceFlag=Su;exports.DocumentExtension=Cx;exports.DragControls=qo;exports.DragMode=bg;exports.DropListener=vs;exports.Duplicatable=Mg;exports.EffectWrapper=Mc;exports.EmissionModule=Cs;exports.EmphasizeOnClick=Wa;exports.EngineLoadingView=Ec;exports.EnvironmentScene=sf;exports.EventList=oe;exports.EventListEvent=yu;exports.EventSystem=$t;exports.EventTrigger=Pu;exports.FieldWithDefault=dw;exports.FileReference=tr;exports.FileReferenceSerializer=m0;exports.FileSpawnModel=DM;exports.File_Event=iw;exports.FixedJoint=sy;exports.Fog=Qa;exports.FrameEvent=me;exports.GENERATOR=Ca;exports.GameObject=S;exports.Gizmos=j;exports.GltfExport=Tg;exports.GltfExportBox=Eg;exports.Gradient=Rr;exports.Graphic=sh;exports.GraphicRaycaster=_u;exports.Graphics=so;exports.GridHelper=Ya;exports.GridLayoutGroup=Yg;exports.GroundProjectedEnv=$n;exports.GroupActionModel=Xo;exports.HideFlags=bu;exports.HideOnStart=Di;exports.HingeJoint=rh;exports.HorizontalLayoutGroup=Qg;exports.HostData=i1;exports.Image=rl;exports.ImageReference=er;exports.ImageReferenceSerializer=p0;exports.InheritVelocityModule=cy;exports.Input=_v;exports.InputEventQueue=Jt;exports.InputEvents=Ce;exports.InputField=Sy;exports.InstanceHandle=or;exports.InstancingHandler=dr;exports.InstancingUtil=Fi;exports.InstantiateEvent=Nv;exports.InstantiateIdProvider=_t;exports.InstantiateOptions=fn;exports.Interactable=yg;exports.JoinedRoomResponse=_C;exports.KeyEventArgs=aC;exports.Keyframe=ii;exports.LODGroup=ju;exports.LODModel=Ka;exports.LeftRoomResponse=bC;exports.Light=xt;exports.LightData=v0;exports.LimitVelocityOverLifetimeModule=et;exports.LoadingElementOptions=PT;exports.LogStats=gg;exports.LogType=ui;exports.LookAt=Cy;exports.LookAtConstraint=br;exports.MainModule=At;exports.MarkerTrackHandler=Ku;exports.MarkerType=vy;exports.MaskableGraphic=oh;exports.Mathf=I;exports.MeshCollider=yo;exports.MeshRenderer=Kc;exports.MinMaxCurve=H;exports.MinMaxGradient=Tr;exports.NEKeyboardEvent=Al;exports.NEPointerEvent=ts;exports.NeedleButtonElement=xx;exports.NeedleEngineWebComponent=Ry;exports.NeedleMenu=Hn;exports.NeedlePatchesKey=ld;exports.NeedleXRController=Lm;exports.NeedleXRSession=G;exports.NeedleXRSync=Ov;exports.NeedleXRUtils=Ev;exports.NestedGltf=Za;exports.NetworkConnection=Mv;exports.NetworkedStreamEvents=Ln;exports.NetworkedStreams=qc;exports.Networking=ay;exports.NewInstanceModel=$v;exports.NoiseModule=pe;exports.ObjectRaycaster=yi;exports.ObjectUtils=po;exports.OffsetConstraint=Er;exports.OneEuroFilter=rd;exports.OneEuroFilterXYZ=Sm;exports.OpenURL=al;exports.OrbitControls=de;exports.Outline=Xa;exports.OwnershipEvent=Pv;exports.OwnershipModel=Um;exports.PUBLIC_KEY=Ks;exports.Padding=Mr;exports.ParticleBurst=Kd;exports.ParticleSubEmitter=hy;exports.ParticleSystem=Pc;exports.ParticleSystemBaseBehaviour=So;exports.ParticleSystemRenderer=qi;exports.ParticleSystemShapeType=Yd;exports.PeerHandle=ls;exports.PeerNetworking=Sv;exports.Physics=Ea;exports.PhysicsExtension=Hg;exports.PhysicsMaterialCombine=it;exports.PixelationEffect=dh;exports.PlayAnimationOnClick=Sc;exports.PlayAudioOnClick=ro;exports.PlayableDirector=pr;exports.PlayerColor=La;exports.PlayerState=Ui;exports.PlayerStateEvent=Dw;exports.PlayerSync=Vg;exports.PlayerView=y0;exports.PlayerViewManager=_0;exports.PointerEventData=Gc;exports.PointerType=ou;exports.PostProcessingEffect=He;exports.PostProcessingEffectOrder=Ke;exports.PostProcessingHandler=my;exports.PreliminaryAction=Ha;exports.PreliminaryTrigger=eh;exports.PrimitiveType=ja;exports.Progress=ne;exports.PromiseAllWithErrors=wm;exports.PromiseErrorResult=xp;exports.RGBAColor=ee;exports.RapierPhysics=wa;exports.RawImage=tf;exports.RaycastOptions=mo;exports.Rect=Iw;exports.RectTransform=un;exports.ReflectionProbe=xc;exports.RegisteredAnimationInfo=Zs;exports.RemoteSkybox=Wu;exports.RenderTexture=Dn;exports.RenderTextureSerializer=N0;exports.Renderer=Ht;exports.RendererData=b0;exports.RendererLightmap=Sg;exports.Rigidbody=Fe;exports.RigidbodyConstraints=Ue;exports.RoomEvents=Y;exports.RotationBySpeedModule=Gi;exports.RotationOverLifetimeModule=mn;exports.SceneLightSettings=Hd;exports.SceneSwitcher=Ne;exports.ScreenCapture=Po;exports.ScreenSpaceAmbientOcclusion=Ps;exports.ScreenSpaceAmbientOcclusionN8=yn;exports.ScrollFollow=ks;exports.SeeThrough=Ms;exports.SendQueue=sn;exports.SerializationContext=Qm;exports.SetActiveOnClick=jg;exports.ShadowCatcher=mh;exports.ShapeModule=ly;exports.ShapeOverlapResult=q0;exports.SharpeningEffect=fh;exports.SignalAsset=Yu;exports.SignalReceiver=vh;exports.SignalReceiverEvent=bh;exports.SignalTrackHandler=kc;exports.Size=Lw;exports.SizeBySpeedModule=ai;exports.SizeOverLifetimeModule=Ar;exports.SkinnedMeshRenderer=Cg;exports.SmoothFollow=Gu;exports.SpatialGrabRaycaster=cr;exports.SpatialHtml=xh;exports.SpatialTrigger=qu;exports.SpatialTriggerReceiver=zn;exports.SpectatorCamera=Xu;exports.SphereCollider=Na;exports.SphereIntersection=Nm;exports.SplineContainer=jr;exports.SplineData=Vn;exports.SplineWalker=Qi;exports.Sprite=ws;exports.SpriteData=va;exports.SpriteRenderer=oi;exports.SpriteSheet=Aa;exports.StateMachineBehaviour=SP;exports.StreamEndedEvent=lg;exports.StreamReceivedEvent=X0;exports.SubEmitterSystem=Zd;exports.SyncedCamera=yy;exports.SyncedRoom=_n;exports.SyncedTransform=dn;exports.TapGestureTrigger=Ug;exports.TeleportTarget=Au;exports.TestRunner=_y;exports.TestSceneUtils=LT;exports.TestSimulateUserData=by;exports.Text=Tt;exports.TextBuilder=qg;exports.TextExtension=Lu;exports.TextureSheetAnimationModule=Dt;exports.TiltShiftEffect=qn;exports.Time=w0;exports.ToneMappingEffect=co;exports.TrackHandler=ol;exports.TrackType=ci;exports.TrailModule=Te;exports.TransformData=Ee;exports.TransformGizmo=Br;exports.TriggerBuilder=kt;exports.TriggerModel=io;exports.TypeStore=P;exports.UIRaycastUtils=rg;exports.UIRootComponent=ih;exports.USDDocument=Ag;exports.USDObject=We;exports.USDWriter=ww;exports.USDZExporter=xw;exports.USDZExporter$1=an;exports.USDZText=ha;exports.USDZUIExtension=Zg;exports.UriSerializer=V0;exports.UsageMarker=Yc;exports.UserJoinedOrLeftRoomModel=vC;exports.VERSION=fi;exports.VariantAction=Lg;exports.VelocityOverLifetimeModule=Ie;exports.VerticalLayoutGroup=Xg;exports.VideoPlayer=Ze;exports.ViewDevice=us;exports.Vignette=Ir;exports.VisibilityAction=th;exports.Voip=go;exports.Volume=il;exports.VolumeParameter=F;exports.VolumeProfile=zu;exports.WaitForFrames=L1;exports.WaitForPromise=g0;exports.WaitForSeconds=Zm;exports.Watch=hs;exports.WebARCameraBackground=Ch;exports.WebARSessionRoot=Bi;exports.WebXR=Du;exports.WebXRButtonFactory=no;exports.WebXRImageTracking=Ph;exports.WebXRImageTrackingModel=Rs;exports.WebXRPlaneTracking=Ts;exports.WebXRTrackedImage=Ia;exports.XRControllerFollow=Es;exports.XRControllerModel=ms;exports.XRControllerMovement=vi;exports.XRFlag=Li;exports.XRRig=cf;exports.XRState=Vt;exports.XRStateFlag=Tn;exports.__Ignore=Px;exports.__internalNotifyObjectDestroyed=HC;exports.activeInHierarchyFieldName=ds;exports.addAttributeChangeCallback=bm;exports.addComponent=on;exports.addCustomExtensionPlugin=KM;exports.addNewComponent=Zo;exports.addPatch=nu;exports.apply=cu;exports.applyHMRChanges=mP;exports.applyPrototypeExtensions=t0;exports.beginListenDestroy=Vv;exports.beginListenInstantiate=Hv;exports.binaryIdentifierCasts=Im;exports.build_scene_functions=eP;exports.builtinComponentKeyName=No;exports.calculateProgress01=Ey;exports.clearMessages=tS;exports.colorSerializer=zP;exports.compareAssociation=Qv;exports.componentSerializer=yd;exports.copyTexture=iv;exports.createMotion=j0;exports.debugNet=Xt;exports.debugOwner=Dl;exports.decompressGpuTexture=Mw;exports.deepClone=Ac;exports.delay=fs;exports.delayForFrames=Dc;exports.deserializeObject=jd;exports.destroy=gi;exports.destroyComponentInstance=s0;exports.determineMimeTypeFromExtension=nw;exports.disposeObjectResources=be;exports.disposeStream=In;exports.editorGuidKeyName=Ql;exports.enableSpatialConsole=fa;exports.euler=VP;exports.eventListSerializer=GP;exports.exportAsGLTF=BT;exports.findByGuid=Km;exports.findObjectOfType=Ua;exports.findObjectsOfType=r0;exports.findResourceUsers=Vm;exports.fitCamera=B0;exports.fitObjectIntoVolume=sv;exports.foreachComponent=lr;exports.foreachComponentEnumerator=du;exports.forward=bS;exports.generateQRCode=C0;exports.generateSeed=Wv;exports.getBoundingBox=Wt;exports.getCameraController=Qb;exports.getComponent=yr;exports.getComponentInChildren=Nc;exports.getComponentInParent=yc;exports.getComponents=zc;exports.getComponentsInChildren=Ba;exports.getComponentsInParent=lu;exports.getFormattedDate=yw;exports.getIconElement=yt;exports.getIconTexture=Wp;exports.getLoader=cn;exports.getOrAddComponent=Fc;exports.getParam=x;exports.getParentHierarchyPath=xS;exports.getPath=Dx;exports.getPeerOptions=pC;exports.getPeerjsInstance=xv;exports.getResourceUserCount=qC;exports.getTempColor=Zb;exports.getTempQuaternion=Zt;exports.getTempVector=B;exports.getUrlParams=Tc;exports.getVisibleInCustomShadowRendering=nv;exports.getWorldDirection=Jb;exports.getWorldEuler=Mm;exports.getWorldPosition=Q;exports.getWorldQuaternion=fe;exports.getWorldRotation=iu;exports.getWorldScale=Le;exports.hasCommercialLicense=Fn;exports.hasIndieLicense=$c;exports.hasPointerEventComponent=Vd;exports.hasProLicense=Un;exports.hideDebugConsole=lv;exports.imageToCanvas=Ow;exports.instantiate=oo;exports.invokeLoadedImportPluginHooks=hw;exports.invokeXRSessionEnd=yv;exports.invokeXRSessionStart=gv;exports.isActiveInHierarchy=a0;exports.isActiveSelf=Fa;exports.isAndroidDevice=Fx;exports.isAnimationAction=tv;exports.isComponent=W0;exports.isDebugMode=Ex;exports.isDesktop=Ix;exports.isDestroyed=ar;exports.isDevEnvironment=T;exports.isDisposed=WC;exports.isExporting=IT;exports.isGLTFModel=$0;exports.isHostedOnGlitch=Bb;exports.isHotReloadEnabled=Qp;exports.isHotReloading=fP;exports.isIPad=Bx;exports.isIconElement=P0;exports.isLocalNetwork=pi;exports.isMacOS=Nx;exports.isMobileDevice=jx;exports.isMozillaXR=zx;exports.isQuest=Wx;exports.isResourceTrackingEnabled=Av;exports.isSafari=$x;exports.isUsingInstancing=hu;exports.isiOS=Vx;exports.isiPad=Ux;exports.loadAsset=bT;exports.loadPMREM=ix;exports.loadSync=ky;exports.logHierarchy=Ed;exports.lookAtInverse=dS;exports.lookAtObject=Lc;exports.lookAtScreenPoint=uS;exports.makeId=Tx;exports.makeIdFromRandomWords=zb;exports.makeNameSafe=bi;exports.markAsInstancedRendered=l0;exports.microphonePermissionsGranted=Hx;exports.nameof=kx;exports.nameofFactory=Ub;exports.objectSerializer=z0;exports.offXRSessionEnd=rC;exports.offXRSessionStart=oC;exports.onAfterRender=oP;exports.onBeforeRender=sP;exports.onClear=iP;exports.onDestroy=nP;exports.onInitialized=tg;exports.onStart=pu;exports.onUpdate=k0;exports.onXRSessionEnd=Dm;exports.onXRSessionStart=su;exports.parseSync=yx;exports.placeOnSurface=ov;exports.postprocessFBXMaterials=Em;exports.prefix=LP;exports.pushState=Fb;exports.randomNumber=Ax;exports.registerBinaryType=jm;exports.registerComponent=fu;exports.registerComponentExtension=wg;exports.registerCustomEffectType=Xi;exports.registerExportExtensions=xg;exports.registerExtensions=qd;exports.registerHotReloadType=A0;exports.registerLoader=Tm;exports.registerPrefabProvider=qv;exports.registerPrototypeExtensions=i0;exports.registerType=Gm;exports.relativePathPrefix=Vb;exports.removeAttributeChangeCallback=vm;exports.removeComponent=Ym;exports.removeCustomImportExtensionType=ZM;exports.removePatch=nC;exports.resolveUrl=ho;exports.sanitizeString=Nb;exports.saveImage=fx;exports.screenshot=iT;exports.screenshot2=Oy;exports.sendDestroyed=Wm;exports.serializable=f;exports.serializeObject=Kv;exports.serializeable=ze;exports.setActive=Zl;exports.setAllowBalloonMessages=Gb;exports.setAllowOverlayMessages=Kx;exports.setAutoFitEnabled=Od;exports.setCameraController=Cp;exports.setDestroyed=h0;exports.setDevEnvironment=RS;exports.setDisposable=Lv;exports.setDontDestroy=Jr;exports.setOrAddParamsToUrl=wp;exports.setParam=Rx;exports.setParamWithoutReload=dc;exports.setPeerOptions=mC;exports.setResourceTrackingEnabled=$C;exports.setState=ym;exports.setVisibleInCustomShadowRendering=km;exports.setWorldEuler=Om;exports.setWorldPosition=rt;exports.setWorldPositionXYZ=rr;exports.setWorldQuaternion=ln;exports.setWorldQuaternionXYZW=Pm;exports.setWorldRotation=ev;exports.setWorldRotationXYZ=Ic;exports.setWorldScale=Sa;exports.showBalloonError=jc;exports.showBalloonMessage=we;exports.showBalloonWarning=ue;exports.showDebugConsole=Rm;exports.slerp=hS;exports.syncDestroy=Bc;exports.syncField=Ng;exports.syncInstantiate=Hm;exports.textureToCanvas=SS;exports.toSourceId=$b;exports.tryCastBinary=vv;exports.tryDetermineMimetypeFromBinary=ow;exports.tryDetermineMimetypeFromURL=sw;exports.tryFindObject=xa;exports.tryGetGuid=wv;exports.unregisterHotReloadType=D0;exports.unwatchWrite=_m;exports.useForAutoFit=Yb;exports.validate=vt;exports.watchWrite=tu;
|
|
1653
|
+
`),this.#n.innerHTML=this.#e.innerHTML,this.#n.style.cssText="display: flex; align-items: center; justify-content: center;",this.#e.innerHTML=this.#n.outerHTML,this.#t.innerHTML=this.#e.outerHTML,this.#t.prepend(this.#s),Fd(Hp,{element:this.#t}),this.#o?.disconnect(),this.#o??=new MutationObserver(()=>this.#c()),this.#o.observe(this.#e,{attributes:!0}),bp&&console.log("Needle Button updated",this)}#c(){this.#e&&(this.#e.style.display==="none"?this.style.display="none":this.style.display==="none"&&(this.style.display=""))}#a=e=>{bp&&console.log("Needle Button clicked",{defaultPrevented:e.defaultPrevented,hasButton:!!this.#e}),!e.defaultPrevented&&this.#e&&this.#e.click()}}typeof window<"u"&&!window.customElements.get(jb)&&window.customElements.define(jb,xx);const Tl=x("debugavatar");class Ty{root;head;leftHand;rigthHand;get isValid(){return this.head!==null&&this.head!==void 0}constructor(e,t,i,n){this.root=e,this.head=t,this.leftHand=i,this.rigthHand=n,this.root?.traverse(o=>o.layers.set(2))}}class Sx{avatarRegistryUrl=null;async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let i=null;if(typeof t=="string"){if(i=await this.loadAvatar(e,t),!i){const o=new fn;i=S.instantiate(xa(t,e.scene),o)}}else i=t;if(!i)return null;const n=this.findAvatar(i);return n.isValid?(Tl&&console.log("[Custom Avatar] valid config",t,Tl?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,Tl?n:""),null)}async loadAvatar(e,t){if(console.assert(t!=null&&typeof t=="string","Avatar id must not be null"),t.length<=0||!t)return null;if(Tl&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const n=await fetch("./"+t);let o=null;if(n.ok){const a=await n.blob();a&&(o=await a.arrayBuffer())}return o?(await cn().parseSync(e,o,null,0))?.scene??null:null}const i=new q.GLTFLoader;return ng(i,e),new Promise((n,o)=>{const r=this.avatarRegistryUrl+"/"+t;i.load(r,async a=>{await cn().createBuiltinComponents(e,r,a,null,void 0),n(a.scene)},a=>{Tl&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),n(null)})})}cacheModel(e,t){}findAvatar(e){const t=e;let i=t;i.children.length==1&&(i=e.children[0]);let n=this.findAvatarPart(i,["head"]);const o=this.findAvatarPart(i,["left","hand"]),r=this.findAvatarPart(i,["right","hand"]);if(!n){n=t;const l=new c.Vector3;new c.Box3().setFromObject(n).getSize(l);const h=Math.max(l.x,l.y,l.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+h+" meters! Should be < 0.3m"),h>.3&&n.scale.multiplyScalar(1/h*.3)}return new Ty(t,n,o,r)}findAvatarPart(e,t){const i=e.name.toLowerCase();let n=!0;for(const o of t){if(!n)break;i.indexOf(o)===-1&&(n=!1)}if(n)return e;if(e.children)for(const o of e.children){const r=this.findAvatarPart(o,t);if(r)return r}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}class Cx{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}class Px{}const zT=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:he,ActionCollection:Rw,ActionModel:Kt,AlignmentConstraint:Wc,Animation:Et,AnimationCurve:ah,AnimationExtension:Ou,AnimationTrackHandler:Oc,Animator:at,AnimatorController:zi,Antialiasing:ch,Attractor:el,AudioExtension:Cr,AudioListener:as,AudioSource:_i,AudioTrackHandler:cs,Avatar:ao,AvatarBlink_Simple:vr,AvatarEyeLook_Rotation:ug,AvatarLoader:Sx,AvatarMarker:Pe,AvatarModel:Ty,Avatar_Brain_LookAt:wc,Avatar_MouthShapes:Xc,Avatar_MustacheShake:hg,Avatar_POI:sr,AxesHelper:za,BaseUIComponent:Ni,BasicIKConstraint:pg,BehaviorExtension:Wg,BehaviorModel:bt,BloomEffect:Vu,BoxCollider:xu,BoxGizmo:kr,BoxHelperComponent:st,Button:Os,CallInfo:rs,Camera:ti,CameraTargetReachedEvent:vc,Canvas:Da,CanvasGroup:lo,CapsuleCollider:ps,ChangeMaterialOnClick:Ig,ChangeTransformOnClick:Pr,CharacterController:wr,CharacterControllerInput:_s,ChromaticAberration:hh,ClickThrough:rf,ColorAdjustments:Co,ColorBySpeedModule:Ja,ColorOverLifetimeModule:Fu,ContactShadows:Qc,ControlTrackHandler:Zu,CursorFollow:Ur,CustomBranding:Or,Deletable:_g,DeleteBox:to,DepthOfField:gn,DeviceFlag:Su,DocumentExtension:Cx,DragControls:qo,DropListener:vs,Duplicatable:Mg,EffectWrapper:Mc,EmissionModule:Cs,EmphasizeOnClick:Wa,EnvironmentScene:sf,EventList:oe,EventListEvent:yu,EventSystem:$t,EventTrigger:Pu,FieldWithDefault:dw,FixedJoint:sy,Fog:Qa,GltfExport:Tg,GltfExportBox:Eg,Gradient:Rr,Graphic:sh,GraphicRaycaster:_u,GridHelper:Ya,GridLayoutGroup:Yg,GroundProjectedEnv:$n,GroupActionModel:Xo,HideOnStart:Di,HingeJoint:rh,HorizontalLayoutGroup:Qg,get HoverAnimation(){return exports.HoverAnimation},Image:rl,InheritVelocityModule:cy,InputField:Sy,InstanceHandle:or,InstancingHandler:dr,Interactable:yg,Keyframe:ii,LODGroup:ju,LODModel:Ka,Light:xt,LimitVelocityOverLifetimeModule:tt,LogStats:gg,LookAt:Cy,LookAtConstraint:br,MainModule:At,MarkerTrackHandler:Ku,MaskableGraphic:oh,MeshCollider:yo,MeshRenderer:Kc,MinMaxCurve:H,MinMaxGradient:Tr,NeedleMenu:Hn,NestedGltf:Za,Networking:ay,NoiseModule:pe,ObjectRaycaster:yi,OffsetConstraint:Er,OpenURL:al,OrbitControls:de,Outline:Xa,Padding:Mr,ParticleBurst:Kd,ParticleSubEmitter:hy,ParticleSystem:Pc,ParticleSystemRenderer:qi,PhysicsExtension:Hg,PixelationEffect:dh,PlayAnimationOnClick:Sc,PlayAudioOnClick:ro,PlayableDirector:pr,PlayerColor:La,PointerEventData:Gc,PostProcessingHandler:my,PreliminaryAction:Ha,PreliminaryTrigger:eh,RawImage:tf,Rect:Iw,RectTransform:un,ReflectionProbe:xc,RegisteredAnimationInfo:Zs,RemoteSkybox:Wu,Renderer:Ht,RendererLightmap:Sg,Rigidbody:Fe,RotationBySpeedModule:Gi,RotationOverLifetimeModule:mn,SceneSwitcher:Ne,ScreenCapture:Po,ScreenSpaceAmbientOcclusion:Ps,ScreenSpaceAmbientOcclusionN8:yn,ScrollFollow:ks,SeeThrough:Ms,SetActiveOnClick:jg,ShadowCatcher:mh,ShapeModule:ly,SharpeningEffect:fh,SignalAsset:Yu,SignalReceiver:vh,SignalReceiverEvent:bh,SignalTrackHandler:kc,Size:Lw,SizeBySpeedModule:ai,SizeOverLifetimeModule:Ar,SkinnedMeshRenderer:Cg,SmoothFollow:Gu,SpatialGrabRaycaster:cr,SpatialHtml:xh,SpatialTrigger:qu,SpatialTriggerReceiver:zn,SpectatorCamera:Xu,SphereCollider:Na,SplineContainer:jr,SplineData:Vn,SplineWalker:Qi,Sprite:ws,SpriteData:va,SpriteRenderer:oi,SpriteSheet:Aa,SubEmitterSystem:Zd,SyncedCamera:yy,SyncedRoom:_n,SyncedTransform:dn,TapGestureTrigger:Ug,TeleportTarget:Au,TestRunner:_y,TestSimulateUserData:by,Text:Tt,TextBuilder:qg,TextExtension:Lu,TextureSheetAnimationModule:Dt,TiltShiftEffect:qn,ToneMappingEffect:co,TrailModule:Te,TransformData:Ee,TransformGizmo:Br,TriggerBuilder:kt,TriggerModel:io,UIRaycastUtils:rg,UIRootComponent:ih,USDZExporter:an,USDZText:ha,USDZUIExtension:Zg,UsageMarker:Yc,VariantAction:Lg,VelocityOverLifetimeModule:Ie,VerticalLayoutGroup:Xg,VideoPlayer:Je,get ViewBox(){return exports.ViewBox},Vignette:Ir,VisibilityAction:th,Voip:go,Volume:il,VolumeParameter:F,VolumeProfile:zu,WebARCameraBackground:Ch,WebARSessionRoot:Bi,WebXR:Du,WebXRImageTracking:Ph,WebXRImageTrackingModel:Rs,WebXRPlaneTracking:Ts,WebXRTrackedImage:Ia,XRControllerFollow:Es,XRControllerModel:ms,XRControllerMovement:vi,XRFlag:Li,XRRig:cf,XRState:Vt,__Ignore:Px},Symbol.toStringTag,{value:"Module"})),Rc=x("debugmissingcamera");le.registerCallback(ae.MissingCamera,s=>{Rc&&console.warn("Creating missing camera");const e=s.context.scene,t=new c.PerspectiveCamera;t.name="Default Fallback Camera",e.add(t);const i=new ti;if(i.sourceId=s.files?.[0]?.src??"unknown",i.fieldOfView=35,s.context.domElement.getAttribute("transparent")!=null)i.clearFlags=nr.Uninitialized;else if(s.context.domElement.getAttribute("background-image")?.length||s.context.lightmaps.tryGetSkybox(i.sourceId))i.clearFlags=nr.Skybox;else{if(i.clearFlags=nr.SolidColor,!s.context.domElement.getAttribute("background-color")){let a="#efefef";typeof window!==void 0&&window.matchMedia("(prefers-color-scheme: dark)").matches&&(a="#1f1f1f"),e.background=new c.Color(a)}if(!e.environment){const a=new c.PMREMGenerator$1(s.context.renderer),l=new sf("neutral");e.environment=a.fromScene(l,.025).texture}}const o=Zo(t,i,!0);return t.position.x=0,t.position.y=1,t.position.z=2,s.context.domElement?.cameraControls!=!1&&Mx(s.context,o),o});le.registerCallback(ae.ContextCreated,s=>{if(!s.context.mainCamera){Rc&&console.log("Will not auto-fit because a default camera exists");return}if(s.context.domElement?.cameraControls==!0){if(Qb(s.context.mainCamera)?.isCameraController==!0){Rc&&console.log("Will not auto-fit because a camera controller exists");return}Mx(s.context)}});function Mx(s,e){e=e??s.mainCameraComponent;const t=e?.gameObject;if(Rc&&console.log("Creating default camera controls",e?.name),t){const i=Fc(t,de);i.sourceId=e?.sourceId??"unknown";const n=s.domElement.getAttribute("auto-rotate");i.autoRotate=n!="0"&&n?.toLowerCase()!="false";const o=Number.parseFloat(n||".5");i.autoRotateSpeed=isNaN(o)?.5:o,Rc&&console.log("Auto-rotate",i.autoRotate,"speed:",i.autoRotateSpeed);const r=s.domElement.getAttribute("auto-fit");i.autoFit=r!=="0"&&r?.toLowerCase()!="false",i.autoTarget=!0}else console.warn("Missing camera object, can not add orbit controls")}le.registerCallback(ae.ContextCreated,s=>{const e=s.context.domElement.getAttribute("autoplay");if(e!==void 0&&(e===""||e==="true"||e==="1")&&s.files)for(const t of s.files)S.foreachComponent(t.file.scene,n=>{if(n.enabled!==!1){if(n instanceof Et&&n.playAutomatically||n instanceof at||n instanceof pr&&n.playOnAwake===!0)return!0;if(n instanceof Et)return n.playAutomatically=!0,!0;if(n instanceof pr)return n.playOnAwake=!0,!0}},!0)!==!0&&Nn.autoplayAnimations(t.file)});exports.SplineUtils=void 0;(s=>{function e(t,i=!1,n=.75){const o=new jr,r=1-I.clamp(n,0,1);return t.forEach((a,l)=>{const h=new c.Vector3;l<t.length-1?h.subVectors(t[l+1],a).normalize().multiplyScalar(r):i&&t.length>1&&h.subVectors(t[0],a).normalize().multiplyScalar(r);const d=new Vn;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 NT extends re.WorkerBase{constructor(){super(new Worker(new URL("/generateMeshBVH.worker-iyfPIK6R.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:ua&&ua.tagName.toUpperCase()==="SCRIPT"&&ua.src||new URL("needle-engine.bundle-Dqrh7aWw.umd.cjs",document.baseURI).href),{type:"module"})),this.name="GenerateMeshBVHWorker"}runTask(e,t,i={}){return new Promise((n,o)=>{if(t.getAttribute("position").isInterleavedBufferAttribute||t.index&&t.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");e.onerror=h=>{o(new Error(`[GenerateMeshBVHWorker] ${h.message||"Unknown error. Please check the server console. If you're using vite try adding 'three-mesh-bvh' to 'optimizeDeps.exclude' in your vite.config.js"}`))},e.onmessage=h=>{const{data:d}=h;if(d.error)o(new Error(d.error)),e.onmessage=null;else if(d.serialized){const{serialized:u,position:p}=d,m=re.MeshBVH.deserialize(u,t,{setIndex:!1}),g=Object.assign({setBoundingBox:!0},i);if(t.attributes.position.array=p,u.index)if(t.index)t.index.array=u.index;else{const _=new c.BufferAttribute(u.index,1,!1);t.setIndex(_)}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)))})}}const VT=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:NT},Symbol.toStringTag,{value:"Module"}));exports.$physicsKey=hM;exports.ActionBuilder=he;exports.ActionCollection=Rw;exports.ActionModel=Kt;exports.Addressables=f0;exports.AlignmentConstraint=Wc;exports.AmbientMode=_a;exports.Animation=Et;exports.AnimationCurve=ah;exports.AnimationExtension=Ou;exports.AnimationTrackHandler=Oc;exports.AnimationUtils=Nn;exports.Animator=at;exports.AnimatorConditionMode=Gs;exports.AnimatorController=zi;exports.AnimatorControllerParameterType=sg;exports.AnimatorStateInfo=jl;exports.Antialiasing=ch;exports.Application=hn;exports.AssetDatabase=Rv;exports.AssetReference=K;exports.Attractor=el;exports.AudioExtension=Cr;exports.AudioListener=as;exports.AudioSource=_i;exports.AudioTrackHandler=cs;exports.Avatar=ao;exports.AvatarBlink_Simple=vr;exports.AvatarEyeLook_Rotation=ug;exports.AvatarLoader=Sx;exports.AvatarMarker=Pe;exports.AvatarModel=Ty;exports.Avatar_Brain_LookAt=wc;exports.Avatar_MouthShapes=Xc;exports.Avatar_MustacheShake=hg;exports.Avatar_POI=sr;exports.Axes=la;exports.AxesHelper=za;exports.BUILD_TIME=uc;exports.BaseUIComponent=Ni;exports.BasicIKConstraint=pg;exports.BehaviorExtension=Wg;exports.BehaviorModel=bt;exports.BloomEffect=Vu;exports.BoxCollider=xu;exports.BoxGizmo=kr;exports.BoxHelperComponent=st;exports.Button=Os;exports.ButtonsFactory=ji;exports.CallDirection=Q0;exports.CallInfo=rs;exports.Camera=ti;exports.CameraTargetReachedEvent=vc;exports.Canvas=Da;exports.CanvasGroup=lo;exports.CapsuleCollider=ps;exports.ChangeMaterialOnClick=Ig;exports.ChangeTransformOnClick=Pr;exports.CharacterController=wr;exports.CharacterControllerInput=_s;exports.ChromaticAberration=hh;exports.CircularBuffer=mi;exports.ClearFlags=nr;exports.ClickThrough=rf;exports.ClipExtrapolation=Pn;exports.Collider=Hi;exports.Collision=G0;exports.CollisionDetectionMode=gu;exports.ColorAdjustments=Co;exports.ColorBySpeedModule=Ja;exports.ColorOverLifetimeModule=Fu;exports.Component=yP;exports.Component$1=E;exports.ComponentLifecycleEvents=au;exports.Components=zT;exports.ConnectionEvents=Cv;exports.ContactPoint=H0;exports.ContactShadows=Qc;exports.Context=U;exports.ContextArgs=tP;exports.ContextEvent=ae;exports.ContextRegistry=le;exports.ControlTrackHandler=Zu;exports.CursorFollow=Ur;exports.CustomBranding=Or;exports.CustomShader=_e;exports.DefaultReflectionMode=Ud;exports.Deletable=_g;exports.DeleteBox=to;exports.DepthOfField=gn;exports.DeviceFlag=Su;exports.DocumentExtension=Cx;exports.DragControls=qo;exports.DragMode=bg;exports.DropListener=vs;exports.Duplicatable=Mg;exports.EffectWrapper=Mc;exports.EmissionModule=Cs;exports.EmphasizeOnClick=Wa;exports.EngineLoadingView=Ec;exports.EnvironmentScene=sf;exports.EventList=oe;exports.EventListEvent=yu;exports.EventSystem=$t;exports.EventTrigger=Pu;exports.FieldWithDefault=dw;exports.FileReference=tr;exports.FileReferenceSerializer=m0;exports.FileSpawnModel=DM;exports.File_Event=iw;exports.FixedJoint=sy;exports.Fog=Qa;exports.FrameEvent=me;exports.GENERATOR=Ca;exports.GameObject=S;exports.Gizmos=j;exports.GltfExport=Tg;exports.GltfExportBox=Eg;exports.Gradient=Rr;exports.Graphic=sh;exports.GraphicRaycaster=_u;exports.Graphics=so;exports.GridHelper=Ya;exports.GridLayoutGroup=Yg;exports.GroundProjectedEnv=$n;exports.GroupActionModel=Xo;exports.HideFlags=bu;exports.HideOnStart=Di;exports.HingeJoint=rh;exports.HorizontalLayoutGroup=Qg;exports.HostData=i1;exports.Image=rl;exports.ImageReference=er;exports.ImageReferenceSerializer=p0;exports.InheritVelocityModule=cy;exports.Input=_v;exports.InputEventQueue=Jt;exports.InputEvents=Ce;exports.InputField=Sy;exports.InstanceHandle=or;exports.InstancingHandler=dr;exports.InstancingUtil=Fi;exports.InstantiateEvent=Nv;exports.InstantiateIdProvider=_t;exports.InstantiateOptions=fn;exports.Interactable=yg;exports.JoinedRoomResponse=_C;exports.KeyEventArgs=aC;exports.Keyframe=ii;exports.LODGroup=ju;exports.LODModel=Ka;exports.LeftRoomResponse=bC;exports.Light=xt;exports.LightData=v0;exports.LimitVelocityOverLifetimeModule=tt;exports.LoadingElementOptions=PT;exports.LogStats=gg;exports.LogType=ui;exports.LookAt=Cy;exports.LookAtConstraint=br;exports.MainModule=At;exports.MarkerTrackHandler=Ku;exports.MarkerType=vy;exports.MaskableGraphic=oh;exports.Mathf=I;exports.MeshCollider=yo;exports.MeshRenderer=Kc;exports.MinMaxCurve=H;exports.MinMaxGradient=Tr;exports.NEKeyboardEvent=Al;exports.NEPointerEvent=ts;exports.NeedleButtonElement=xx;exports.NeedleEngineWebComponent=Ry;exports.NeedleMenu=Hn;exports.NeedlePatchesKey=ld;exports.NeedleXRController=Lm;exports.NeedleXRSession=G;exports.NeedleXRSync=Ov;exports.NeedleXRUtils=Ev;exports.NestedGltf=Za;exports.NetworkConnection=Mv;exports.NetworkedStreamEvents=Ln;exports.NetworkedStreams=qc;exports.Networking=ay;exports.NewInstanceModel=$v;exports.NoiseModule=pe;exports.ObjectRaycaster=yi;exports.ObjectUtils=po;exports.OffsetConstraint=Er;exports.OneEuroFilter=rd;exports.OneEuroFilterXYZ=Sm;exports.OpenURL=al;exports.OrbitControls=de;exports.Outline=Xa;exports.OwnershipEvent=Pv;exports.OwnershipModel=Um;exports.PUBLIC_KEY=Ks;exports.Padding=Mr;exports.ParticleBurst=Kd;exports.ParticleSubEmitter=hy;exports.ParticleSystem=Pc;exports.ParticleSystemBaseBehaviour=So;exports.ParticleSystemRenderer=qi;exports.ParticleSystemShapeType=Yd;exports.PeerHandle=ls;exports.PeerNetworking=Sv;exports.Physics=Ea;exports.PhysicsExtension=Hg;exports.PhysicsMaterialCombine=it;exports.PixelationEffect=dh;exports.PlayAnimationOnClick=Sc;exports.PlayAudioOnClick=ro;exports.PlayableDirector=pr;exports.PlayerColor=La;exports.PlayerState=Ui;exports.PlayerStateEvent=Dw;exports.PlayerSync=Vg;exports.PlayerView=y0;exports.PlayerViewManager=_0;exports.PointerEventData=Gc;exports.PointerType=ou;exports.PostProcessingEffect=Ge;exports.PostProcessingEffectOrder=Ze;exports.PostProcessingHandler=my;exports.PreliminaryAction=Ha;exports.PreliminaryTrigger=eh;exports.PrimitiveType=ja;exports.Progress=ne;exports.PromiseAllWithErrors=wm;exports.PromiseErrorResult=xp;exports.RGBAColor=ee;exports.RapierPhysics=wa;exports.RawImage=tf;exports.RaycastOptions=mo;exports.Rect=Iw;exports.RectTransform=un;exports.ReflectionProbe=xc;exports.RegisteredAnimationInfo=Zs;exports.RemoteSkybox=Wu;exports.RenderTexture=Dn;exports.RenderTextureSerializer=N0;exports.Renderer=Ht;exports.RendererData=b0;exports.RendererLightmap=Sg;exports.Rigidbody=Fe;exports.RigidbodyConstraints=Ue;exports.RoomEvents=Y;exports.RotationBySpeedModule=Gi;exports.RotationOverLifetimeModule=mn;exports.SceneLightSettings=Hd;exports.SceneSwitcher=Ne;exports.ScreenCapture=Po;exports.ScreenSpaceAmbientOcclusion=Ps;exports.ScreenSpaceAmbientOcclusionN8=yn;exports.ScrollFollow=ks;exports.SeeThrough=Ms;exports.SendQueue=sn;exports.SerializationContext=Qm;exports.SetActiveOnClick=jg;exports.ShadowCatcher=mh;exports.ShapeModule=ly;exports.ShapeOverlapResult=q0;exports.SharpeningEffect=fh;exports.SignalAsset=Yu;exports.SignalReceiver=vh;exports.SignalReceiverEvent=bh;exports.SignalTrackHandler=kc;exports.Size=Lw;exports.SizeBySpeedModule=ai;exports.SizeOverLifetimeModule=Ar;exports.SkinnedMeshRenderer=Cg;exports.SmoothFollow=Gu;exports.SpatialGrabRaycaster=cr;exports.SpatialHtml=xh;exports.SpatialTrigger=qu;exports.SpatialTriggerReceiver=zn;exports.SpectatorCamera=Xu;exports.SphereCollider=Na;exports.SphereIntersection=Nm;exports.SplineContainer=jr;exports.SplineData=Vn;exports.SplineWalker=Qi;exports.Sprite=ws;exports.SpriteData=va;exports.SpriteRenderer=oi;exports.SpriteSheet=Aa;exports.StateMachineBehaviour=SP;exports.StreamEndedEvent=lg;exports.StreamReceivedEvent=X0;exports.SubEmitterSystem=Zd;exports.SyncedCamera=yy;exports.SyncedRoom=_n;exports.SyncedTransform=dn;exports.TapGestureTrigger=Ug;exports.TeleportTarget=Au;exports.TestRunner=_y;exports.TestSceneUtils=LT;exports.TestSimulateUserData=by;exports.Text=Tt;exports.TextBuilder=qg;exports.TextExtension=Lu;exports.TextureSheetAnimationModule=Dt;exports.TiltShiftEffect=qn;exports.Time=w0;exports.ToneMappingEffect=co;exports.TrackHandler=ol;exports.TrackType=ci;exports.TrailModule=Te;exports.TransformData=Ee;exports.TransformGizmo=Br;exports.TriggerBuilder=kt;exports.TriggerModel=io;exports.TypeStore=P;exports.UIRaycastUtils=rg;exports.UIRootComponent=ih;exports.USDDocument=Ag;exports.USDObject=He;exports.USDWriter=ww;exports.USDZExporter=xw;exports.USDZExporter$1=an;exports.USDZText=ha;exports.USDZUIExtension=Zg;exports.UriSerializer=V0;exports.UsageMarker=Yc;exports.UserJoinedOrLeftRoomModel=vC;exports.VERSION=fi;exports.VariantAction=Lg;exports.VelocityOverLifetimeModule=Ie;exports.VerticalLayoutGroup=Xg;exports.VideoPlayer=Je;exports.ViewDevice=us;exports.Vignette=Ir;exports.VisibilityAction=th;exports.Voip=go;exports.Volume=il;exports.VolumeParameter=F;exports.VolumeProfile=zu;exports.WaitForFrames=L1;exports.WaitForPromise=g0;exports.WaitForSeconds=Zm;exports.Watch=hs;exports.WebARCameraBackground=Ch;exports.WebARSessionRoot=Bi;exports.WebXR=Du;exports.WebXRButtonFactory=no;exports.WebXRImageTracking=Ph;exports.WebXRImageTrackingModel=Rs;exports.WebXRPlaneTracking=Ts;exports.WebXRTrackedImage=Ia;exports.XRControllerFollow=Es;exports.XRControllerModel=ms;exports.XRControllerMovement=vi;exports.XRFlag=Li;exports.XRRig=cf;exports.XRState=Vt;exports.XRStateFlag=Tn;exports.__Ignore=Px;exports.__internalNotifyObjectDestroyed=HC;exports.activeInHierarchyFieldName=ds;exports.addAttributeChangeCallback=bm;exports.addComponent=on;exports.addCustomExtensionPlugin=KM;exports.addNewComponent=Zo;exports.addPatch=nu;exports.apply=cu;exports.applyHMRChanges=mP;exports.applyPrototypeExtensions=t0;exports.beginListenDestroy=Vv;exports.beginListenInstantiate=Hv;exports.binaryIdentifierCasts=Im;exports.build_scene_functions=eP;exports.builtinComponentKeyName=No;exports.calculateProgress01=Ey;exports.clearMessages=tS;exports.colorSerializer=zP;exports.compareAssociation=Qv;exports.componentSerializer=yd;exports.copyTexture=iv;exports.createMotion=j0;exports.debugNet=Xt;exports.debugOwner=Dl;exports.decompressGpuTexture=Mw;exports.deepClone=Ac;exports.delay=fs;exports.delayForFrames=Dc;exports.deserializeObject=jd;exports.destroy=gi;exports.destroyComponentInstance=s0;exports.determineMimeTypeFromExtension=nw;exports.disposeObjectResources=be;exports.disposeStream=In;exports.editorGuidKeyName=Ql;exports.enableSpatialConsole=fa;exports.euler=VP;exports.eventListSerializer=GP;exports.exportAsGLTF=BT;exports.findByGuid=Km;exports.findObjectOfType=Ua;exports.findObjectsOfType=r0;exports.findResourceUsers=Vm;exports.fitCamera=B0;exports.fitObjectIntoVolume=sv;exports.foreachComponent=lr;exports.foreachComponentEnumerator=du;exports.forward=bS;exports.generateQRCode=C0;exports.generateSeed=Wv;exports.getBoundingBox=Wt;exports.getCameraController=Qb;exports.getComponent=yr;exports.getComponentInChildren=Nc;exports.getComponentInParent=yc;exports.getComponents=zc;exports.getComponentsInChildren=Ba;exports.getComponentsInParent=lu;exports.getFormattedDate=yw;exports.getIconElement=yt;exports.getIconTexture=Wp;exports.getLoader=cn;exports.getOrAddComponent=Fc;exports.getParam=x;exports.getParentHierarchyPath=xS;exports.getPath=Dx;exports.getPeerOptions=pC;exports.getPeerjsInstance=xv;exports.getResourceUserCount=qC;exports.getTempColor=Zb;exports.getTempQuaternion=Zt;exports.getTempVector=B;exports.getUrlParams=Tc;exports.getVisibleInCustomShadowRendering=nv;exports.getWorldDirection=Jb;exports.getWorldEuler=Mm;exports.getWorldPosition=Q;exports.getWorldQuaternion=fe;exports.getWorldRotation=iu;exports.getWorldScale=Le;exports.hasCommercialLicense=Fn;exports.hasIndieLicense=$c;exports.hasPointerEventComponent=Vd;exports.hasProLicense=Un;exports.hideDebugConsole=lv;exports.imageToCanvas=Ow;exports.instantiate=oo;exports.invokeLoadedImportPluginHooks=hw;exports.invokeXRSessionEnd=yv;exports.invokeXRSessionStart=gv;exports.isActiveInHierarchy=a0;exports.isActiveSelf=Fa;exports.isAndroidDevice=Fx;exports.isAnimationAction=tv;exports.isComponent=W0;exports.isDebugMode=Ex;exports.isDesktop=Ix;exports.isDestroyed=ar;exports.isDevEnvironment=T;exports.isDisposed=WC;exports.isExporting=IT;exports.isGLTFModel=$0;exports.isHostedOnGlitch=Bb;exports.isHotReloadEnabled=Qp;exports.isHotReloading=fP;exports.isIPad=Bx;exports.isIconElement=P0;exports.isLocalNetwork=pi;exports.isMacOS=Nx;exports.isMobileDevice=jx;exports.isMozillaXR=zx;exports.isQuest=Wx;exports.isResourceTrackingEnabled=Av;exports.isSafari=$x;exports.isUsingInstancing=hu;exports.isiOS=Vx;exports.isiPad=Ux;exports.loadAsset=bT;exports.loadPMREM=ix;exports.loadSync=ky;exports.logHierarchy=Ed;exports.lookAtInverse=dS;exports.lookAtObject=Lc;exports.lookAtScreenPoint=uS;exports.makeId=Tx;exports.makeIdFromRandomWords=zb;exports.makeNameSafe=bi;exports.markAsInstancedRendered=l0;exports.microphonePermissionsGranted=Hx;exports.nameof=kx;exports.nameofFactory=Ub;exports.objectSerializer=z0;exports.offXRSessionEnd=rC;exports.offXRSessionStart=oC;exports.onAfterRender=oP;exports.onBeforeRender=sP;exports.onClear=iP;exports.onDestroy=nP;exports.onInitialized=tg;exports.onStart=pu;exports.onUpdate=k0;exports.onXRSessionEnd=Dm;exports.onXRSessionStart=su;exports.parseSync=yx;exports.placeOnSurface=ov;exports.postprocessFBXMaterials=Em;exports.prefix=LP;exports.pushState=Fb;exports.randomNumber=Ax;exports.registerBinaryType=jm;exports.registerComponent=fu;exports.registerComponentExtension=wg;exports.registerCustomEffectType=Xi;exports.registerExportExtensions=xg;exports.registerExtensions=qd;exports.registerHotReloadType=A0;exports.registerLoader=Tm;exports.registerPrefabProvider=qv;exports.registerPrototypeExtensions=i0;exports.registerType=Gm;exports.relativePathPrefix=Vb;exports.removeAttributeChangeCallback=vm;exports.removeComponent=Ym;exports.removeCustomImportExtensionType=ZM;exports.removePatch=nC;exports.resolveUrl=ho;exports.sanitizeString=Nb;exports.saveImage=fx;exports.screenshot=iT;exports.screenshot2=Oy;exports.sendDestroyed=Wm;exports.serializable=f;exports.serializeObject=Kv;exports.serializeable=ze;exports.setActive=Zl;exports.setAllowBalloonMessages=Gb;exports.setAllowOverlayMessages=Kx;exports.setAutoFitEnabled=Od;exports.setCameraController=Cp;exports.setDestroyed=h0;exports.setDevEnvironment=RS;exports.setDisposable=Lv;exports.setDontDestroy=Jr;exports.setOrAddParamsToUrl=wp;exports.setParam=Rx;exports.setParamWithoutReload=dc;exports.setPeerOptions=mC;exports.setResourceTrackingEnabled=$C;exports.setState=ym;exports.setVisibleInCustomShadowRendering=km;exports.setWorldEuler=Om;exports.setWorldPosition=rt;exports.setWorldPositionXYZ=rr;exports.setWorldQuaternion=ln;exports.setWorldQuaternionXYZW=Pm;exports.setWorldRotation=ev;exports.setWorldRotationXYZ=Ic;exports.setWorldScale=Sa;exports.showBalloonError=jc;exports.showBalloonMessage=we;exports.showBalloonWarning=ue;exports.showDebugConsole=Rm;exports.slerp=hS;exports.syncDestroy=Bc;exports.syncField=Ng;exports.syncInstantiate=Hm;exports.textureToCanvas=SS;exports.toSourceId=$b;exports.tryCastBinary=vv;exports.tryDetermineMimetypeFromBinary=ow;exports.tryDetermineMimetypeFromURL=sw;exports.tryFindObject=xa;exports.tryGetGuid=wv;exports.unregisterHotReloadType=D0;exports.unwatchWrite=_m;exports.useForAutoFit=Yb;exports.validate=vt;exports.watchWrite=tu;
|