@needle-tools/engine 4.17.0-next.36dcae2 → 4.17.0-next.4989636
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/components.needle.json +1 -1
- package/dist/gltf-progressive-BryRjllq.min.js +10 -0
- package/dist/gltf-progressive-Cl167Vjx.js +1537 -0
- package/dist/gltf-progressive-DJBMx-zB.umd.cjs +10 -0
- package/dist/gltf-progressive.worker-BqODMeeW.js +23 -0
- package/dist/needle-engine.bundle-BTIpdDE9.umd.cjs +1654 -0
- package/dist/{needle-engine.bundle-CQFEuAQB.js → needle-engine.bundle-CH2ZOagS.js} +35829 -35882
- package/dist/needle-engine.bundle-D5h7xxUH.min.js +1654 -0
- package/dist/needle-engine.d.ts +105 -39
- package/dist/needle-engine.js +608 -607
- package/dist/needle-engine.min.js +1 -1
- package/dist/needle-engine.umd.cjs +1 -1
- package/dist/three-examples.js +7815 -6828
- package/dist/three-examples.min.js +17 -15
- package/dist/three-examples.umd.cjs +17 -15
- package/dist/three.js +15994 -24892
- package/dist/three.min.js +214 -214
- package/dist/three.umd.cjs +208 -208
- package/dist/vendor-CntUvmJu.umd.cjs +1116 -0
- package/dist/{vendor-BPp9F5vR.min.js → vendor-DPbfJJ4d.min.js} +94 -94
- package/dist/{vendor-CQMI3jTS.js → vendor-vHLk8sXu.js} +8558 -8516
- package/lib/engine/analytics/index.js.map +1 -1
- package/lib/engine/codegen/register_types.d.ts +1 -1
- package/lib/engine/codegen/register_types.js +159 -157
- package/lib/engine/codegen/register_types.js.map +1 -1
- package/lib/engine/debug/debug.d.ts +1 -4
- package/lib/engine/debug/debug.js +1 -25
- package/lib/engine/debug/debug.js.map +1 -1
- package/lib/engine/debug/debug_environment.d.ts +4 -0
- package/lib/engine/debug/debug_environment.js +26 -0
- package/lib/engine/debug/debug_environment.js.map +1 -0
- package/lib/engine/debug/debug_overlay.js +2 -1
- package/lib/engine/debug/debug_overlay.js.map +1 -1
- package/lib/engine/debug/debug_spatial_console.js +1 -1
- package/lib/engine/debug/debug_spatial_console.js.map +1 -1
- package/lib/engine/engine_audio.js +0 -1
- package/lib/engine/engine_audio.js.map +1 -1
- package/lib/engine/engine_components.js +6 -3
- package/lib/engine/engine_components.js.map +1 -1
- package/lib/engine/engine_gltf_builtin_components.d.ts +0 -1
- package/lib/engine/engine_gltf_builtin_components.js +5 -4
- package/lib/engine/engine_gltf_builtin_components.js.map +1 -1
- package/lib/engine/engine_init.d.ts +10 -0
- package/lib/engine/engine_init.js +44 -0
- package/lib/engine/engine_init.js.map +1 -0
- package/lib/engine/engine_loaders.d.ts +2 -0
- package/lib/engine/engine_loaders.js +2 -1
- package/lib/engine/engine_loaders.js.map +1 -1
- package/lib/engine/engine_modules.d.ts +8 -0
- package/lib/engine/engine_modules.js +1 -0
- package/lib/engine/engine_modules.js.map +1 -1
- package/lib/engine/engine_networking.d.ts +2 -1
- package/lib/engine/engine_networking.js +3 -1
- package/lib/engine/engine_networking.js.map +1 -1
- package/lib/engine/engine_networking_blob.js +3 -3
- package/lib/engine/engine_networking_blob.js.map +1 -1
- package/lib/engine/engine_networking_peer.d.ts +2 -2
- package/lib/engine/engine_networking_peer.js +7 -6
- package/lib/engine/engine_networking_peer.js.map +1 -1
- package/lib/engine/engine_networking_streams.d.ts +2 -1
- package/lib/engine/engine_networking_streams.js +2 -2
- package/lib/engine/engine_networking_streams.js.map +1 -1
- package/lib/engine/engine_physics_rapier.d.ts +2 -0
- package/lib/engine/engine_physics_rapier.js +35 -4
- package/lib/engine/engine_physics_rapier.js.map +1 -1
- package/lib/engine/engine_shims.d.ts +1 -0
- package/lib/engine/engine_shims.js +20 -19
- package/lib/engine/engine_shims.js.map +1 -1
- package/lib/engine/engine_tonemapping.js +0 -1
- package/lib/engine/engine_tonemapping.js.map +1 -1
- package/lib/engine/engine_types.d.ts +8 -0
- package/lib/engine/engine_typestore.d.ts +11 -0
- package/lib/engine/engine_typestore.js +29 -0
- package/lib/engine/engine_typestore.js.map +1 -1
- package/lib/engine/extensions/NEEDLE_animator_controller_model.d.ts +1 -1
- package/lib/engine/js-extensions/Camera.d.ts +1 -1
- package/lib/engine/js-extensions/Camera.js +43 -37
- package/lib/engine/js-extensions/Camera.js.map +1 -1
- package/lib/engine/js-extensions/Layers.js +0 -1
- package/lib/engine/js-extensions/Layers.js.map +1 -1
- package/lib/engine/js-extensions/Object3D.d.ts +1 -0
- package/lib/engine/js-extensions/Object3D.js +173 -167
- package/lib/engine/js-extensions/Object3D.js.map +1 -1
- package/lib/engine/js-extensions/Vector.d.ts +1 -0
- package/lib/engine/js-extensions/Vector.js +10 -4
- package/lib/engine/js-extensions/Vector.js.map +1 -1
- package/lib/engine/js-extensions/index.d.ts +0 -3
- package/lib/engine/js-extensions/index.js +0 -2
- package/lib/engine/js-extensions/index.js.map +1 -1
- package/lib/engine/webcomponents/WebXRButtons.js +11 -13
- package/lib/engine/webcomponents/WebXRButtons.js.map +1 -1
- package/lib/engine/webcomponents/buttons.js +4 -4
- package/lib/engine/webcomponents/buttons.js.map +1 -1
- package/lib/engine/webcomponents/font-urls.d.ts +2 -0
- package/lib/engine/webcomponents/font-urls.js +8 -0
- package/lib/engine/webcomponents/font-urls.js.map +1 -0
- package/lib/engine/webcomponents/fonts.d.ts +2 -2
- package/lib/engine/webcomponents/fonts.js +12 -7
- package/lib/engine/webcomponents/fonts.js.map +1 -1
- package/lib/engine/webcomponents/init.d.ts +4 -0
- package/lib/engine/webcomponents/init.js +20 -0
- package/lib/engine/webcomponents/init.js.map +1 -0
- package/lib/engine/webcomponents/logo-element.js +2 -2
- package/lib/engine/webcomponents/logo-element.js.map +1 -1
- package/lib/engine/webcomponents/needle menu/menu-priority.d.ts +10 -0
- package/lib/engine/webcomponents/needle menu/menu-priority.js +21 -0
- package/lib/engine/webcomponents/needle menu/menu-priority.js.map +1 -0
- package/lib/engine/webcomponents/needle menu/needle-menu-spatial.d.ts +1 -1
- package/lib/engine/webcomponents/needle menu/needle-menu.d.ts +1 -1
- package/lib/engine/webcomponents/needle menu/needle-menu.js +7 -11
- package/lib/engine/webcomponents/needle menu/needle-menu.js.map +1 -1
- package/lib/engine/webcomponents/needle-button.js +0 -3
- package/lib/engine/webcomponents/needle-button.js.map +1 -1
- package/lib/engine/webcomponents/needle-engine.js +4 -10
- package/lib/engine/webcomponents/needle-engine.js.map +1 -1
- package/lib/engine/webcomponents/quicklook-handler.d.ts +29 -0
- package/lib/engine/webcomponents/quicklook-handler.js +21 -0
- package/lib/engine/webcomponents/quicklook-handler.js.map +1 -0
- package/lib/engine/xr/NeedleXRSession.d.ts +1 -0
- package/lib/engine/xr/NeedleXRSession.js +1 -0
- package/lib/engine/xr/NeedleXRSession.js.map +1 -1
- package/lib/engine-components/AnimationUtilsAutoplay.d.ts +1 -1
- package/lib/engine-components/AnimationUtilsAutoplay.js +29 -23
- package/lib/engine-components/AnimationUtilsAutoplay.js.map +1 -1
- package/lib/engine-components/Animator.d.ts +1 -1
- package/lib/engine-components/AnimatorController.d.ts +1 -1
- package/lib/engine-components/CameraUtils.d.ts +1 -1
- package/lib/engine-components/CameraUtils.js +79 -73
- package/lib/engine-components/CameraUtils.js.map +1 -1
- package/lib/engine-components/Collider.d.ts +2 -0
- package/lib/engine-components/Collider.js +25 -3
- package/lib/engine-components/Collider.js.map +1 -1
- package/lib/engine-components/LookAtConstraint.d.ts +34 -1
- package/lib/engine-components/LookAtConstraint.js +54 -1
- package/lib/engine-components/LookAtConstraint.js.map +1 -1
- package/lib/engine-components/Networking.d.ts +2 -1
- package/lib/engine-components/Networking.js +2 -1
- package/lib/engine-components/Networking.js.map +1 -1
- package/lib/engine-components/SceneSwitcher.d.ts +1 -0
- package/lib/engine-components/SceneSwitcher.js +3 -1
- package/lib/engine-components/SceneSwitcher.js.map +1 -1
- package/lib/engine-components/Skybox.d.ts +1 -0
- package/lib/engine-components/Skybox.js +4 -2
- package/lib/engine-components/Skybox.js.map +1 -1
- package/lib/engine-components/SyncedRoom.d.ts +1 -0
- package/lib/engine-components/SyncedRoom.js +1 -0
- package/lib/engine-components/SyncedRoom.js.map +1 -1
- package/lib/engine-components/api.d.ts +5 -8
- package/lib/engine-components/api.js +4 -7
- package/lib/engine-components/api.js.map +1 -1
- package/lib/engine-components/export/usdz/USDZExporter.js +8 -0
- package/lib/engine-components/export/usdz/USDZExporter.js.map +1 -1
- package/lib/engine-components/postprocessing/PostProcessingHandler.js +18 -5
- package/lib/engine-components/postprocessing/PostProcessingHandler.js.map +1 -1
- package/lib/engine-components/postprocessing/utils.js +7 -2
- package/lib/engine-components/postprocessing/utils.js.map +1 -1
- package/lib/engine-components/timeline/TimelineTracks.d.ts +1 -1
- package/lib/engine-components/timeline/TimelineTracks.js +4 -2
- package/lib/engine-components/timeline/TimelineTracks.js.map +1 -1
- package/lib/engine-components/web/ScrollFollow.d.ts +0 -8
- package/lib/engine-components/webxr/WebXR.d.ts +15 -2
- package/lib/engine-components/webxr/WebXR.js +15 -2
- package/lib/engine-components/webxr/WebXR.js.map +1 -1
- package/lib/needle-engine.d.ts +0 -1
- package/lib/needle-engine.js +2 -1
- package/lib/needle-engine.js.map +1 -1
- package/package.json +11 -3
- package/plugins/vite/ai.d.ts +11 -7
- package/plugins/vite/ai.js +21 -16
- package/plugins/vite/asap.js +42 -2
- package/plugins/vite/dependencies.js +110 -16
- package/plugins/vite/index.d.ts +1 -0
- package/plugins/vite/index.js +4 -0
- package/plugins/vite/treeshake.d.ts +11 -0
- package/plugins/vite/treeshake.js +216 -0
- package/src/engine/analytics/index.ts +1 -1
- package/src/engine/codegen/register_types.ts +159 -157
- package/src/engine/debug/debug.ts +1 -26
- package/src/engine/debug/debug_environment.ts +26 -0
- package/src/engine/debug/debug_overlay.ts +2 -1
- package/src/engine/debug/debug_spatial_console.ts +1 -1
- package/src/engine/engine_audio.ts +1 -2
- package/src/engine/engine_components.ts +6 -3
- package/src/engine/engine_gltf_builtin_components.ts +4 -5
- package/src/engine/engine_init.ts +45 -0
- package/src/engine/engine_loaders.ts +2 -1
- package/src/engine/engine_modules.ts +3 -0
- package/src/engine/engine_networking.ts +5 -1
- package/src/engine/engine_networking_blob.ts +3 -3
- package/src/engine/engine_networking_peer.ts +8 -6
- package/src/engine/engine_networking_streams.ts +4 -3
- package/src/engine/engine_physics_rapier.ts +37 -4
- package/src/engine/engine_shims.ts +22 -20
- package/src/engine/engine_tonemapping.ts +0 -1
- package/src/engine/engine_types.ts +9 -0
- package/src/engine/engine_typestore.ts +29 -0
- package/src/engine/extensions/NEEDLE_animator_controller_model.ts +1 -1
- package/src/engine/js-extensions/Camera.ts +40 -33
- package/src/engine/js-extensions/Layers.ts +1 -2
- package/src/engine/js-extensions/Object3D.ts +174 -170
- package/src/engine/js-extensions/Vector.ts +11 -4
- package/src/engine/js-extensions/index.ts +0 -3
- package/src/engine/webcomponents/WebXRButtons.ts +12 -13
- package/src/engine/webcomponents/buttons.ts +4 -4
- package/src/engine/webcomponents/font-urls.js +9 -0
- package/src/engine/webcomponents/fonts.ts +12 -7
- package/src/engine/webcomponents/init.ts +23 -0
- package/src/engine/webcomponents/logo-element.ts +2 -2
- package/src/engine/webcomponents/needle menu/menu-priority.ts +20 -0
- package/src/engine/webcomponents/needle menu/needle-menu.ts +8 -13
- package/src/engine/webcomponents/needle-button.ts +0 -3
- package/src/engine/webcomponents/needle-engine.ts +4 -13
- package/src/engine/webcomponents/quicklook-handler.ts +37 -0
- package/src/engine/xr/NeedleXRSession.ts +2 -1
- package/src/engine-components/AnimationUtilsAutoplay.ts +8 -3
- package/src/engine-components/AnimatorController.ts +1 -1
- package/src/engine-components/CameraUtils.ts +15 -8
- package/src/engine-components/Collider.ts +24 -3
- package/src/engine-components/LookAtConstraint.ts +46 -1
- package/src/engine-components/Networking.ts +3 -1
- package/src/engine-components/SceneSwitcher.ts +3 -1
- package/src/engine-components/Skybox.ts +4 -2
- package/src/engine-components/SyncedRoom.ts +2 -0
- package/src/engine-components/api.ts +5 -10
- package/src/engine-components/export/usdz/USDZExporter.ts +9 -0
- package/src/engine-components/postprocessing/PostProcessingHandler.ts +19 -7
- package/src/engine-components/postprocessing/utils.ts +7 -2
- package/src/engine-components/timeline/TimelineTracks.ts +6 -2
- package/src/engine-components/web/ScrollFollow.ts +0 -2
- package/src/engine-components/webxr/WebXR.ts +15 -2
- package/src/needle-engine.ts +2 -1
- package/dist/gltf-progressive-BBIL1q1j.umd.cjs +0 -4022
- package/dist/gltf-progressive-BbHl9z0v.js +0 -28272
- package/dist/gltf-progressive-Clq_N7Zx.min.js +0 -4022
- package/dist/gltf-progressive.worker-CCrD-Ycm.js +0 -3
- package/dist/needle-engine.bundle-CrqNZdEN.umd.cjs +0 -1657
- package/dist/needle-engine.bundle-DyVf6QdN.min.js +0 -1657
- package/dist/vendor-CipoooTV.umd.cjs +0 -1116
|
@@ -1,1657 +0,0 @@
|
|
|
1
|
-
"use strict";const re=require("./gltf-progressive-BBIL1q1j.umd.cjs"),c=require("./three.umd.cjs"),X=require("./three-examples.umd.cjs"),ae=require("./vendor-CipoooTV.umd.cjs"),ie=require("./three-mesh-ui-Chib781Y.umd.cjs"),Vx=require("./postprocessing-B2wb6pzI.umd.cjs");var _a=typeof document<"u"?document.currentScript:null;const wf=new Map;function yi(s=globalThis.location?.hostname){if(wf.has(s))return wf.get(s);const e=/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|localhost/.test(s);return wf.set(s,e),e===!0}function tv(){return window.location.hostname.includes("glitch.me")}const Hy=typeof window!==void 0?window.location.search.includes("debugcontext"):!1;var le=(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))(le||{});class ce{static get Current(){return globalThis["NeedleEngine.Context.Current"]}static set Current(e){globalThis["NeedleEngine.Context.Current"]=e}static get All(){return this.Registered}static Registered=[];static register(e){this.Registered.indexOf(e)===-1&&(Hy&&console.warn("Registering context"),this.Registered.push(e),this.dispatchCallback("ContextRegistered",e))}static unregister(e){const t=this.Registered.indexOf(e);t!==-1&&(Hy&&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 iv=()=>s=>s;function $x(s){return iv()(s)}function Wx(){return!!x("debug")}class _i{_factory;_cache=[];_maxSize;_index=0;constructor(e,t){this._factory=e,this._maxSize=t}get(){const e=this._index%this._maxSize;return this._index++,this._cache.length<=e&&(this._cache[e]=this._factory()),this._cache[e]}}let Ho=!1;const kp=new Array;typeof window<"u"&&setTimeout(()=>{if(Ho){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 kp){const r=new URL(e);r.searchParams.append(o,""),s[o]=r.toString().replace(/=$|=(?=&)/g,"")}console.log(`🌵 ?help: Debug Options for Needle Engine.
|
|
2
|
-
Append any of these parameters to the URL to enable specific debug options.
|
|
3
|
-
Example: ${i} will show an onscreen console window.`);const n=Ho===!0?"":` (containing "${Ho}")`;console.group("Available URL parameters:"+n);for(const o of Object.keys(s).sort())typeof Ho=="string"&&!o.toLowerCase().includes(Ho.toLowerCase())||(console.groupCollapsed(o),console.log("Reload with this flag enabled:"),console.log(s[o]),console.groupEnd());console.groupEnd()}},100);function Lc(){return new URLSearchParams(globalThis.location?.search)}function x(s){Ho&&!kp.includes(s)&&kp.push(s);const e=Lc();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}Ho=x("help");function Gx(s,e){const t=Lc();t.has(s)?t.set(s,e):t.append(s,e),document.location.search=t.toString()}function pc(s,e,t=!0){const i=Lc();i.has(s)?e===null?i.delete(s):i.set(s,e):e!==null&&i.append(s,e),t?nv(s,i):km(s,i)}function Rp(s,e,t){s.has(e)?s.set(e,t.toString()):s.append(e,t.toString())}function nv(s,e,t){window.history.pushState(t,s,"?"+e.toString())}function km(s,e,t){window.history.replaceState(t,s,"?"+e.toString())}function Hx(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 qx(s,e){return Math.floor(Math.random()*(e-s+1))+s}const qy=["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"],Xy=["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 sv(){const s=qy[Math.floor(Math.random()*qy.length)],e=Xy[Math.floor(Math.random()*Xy.length)];return s+"_"+e}function ov(s){return s=s.replace(/[^a-z0-9áéíóúñü \.,_-]/gim,""),s.trim()}function ka(s,e,t=!0,i=!1){if(e==null)return null;if(e.userData&&e.userData.guid===s)return e;if(e.guid==s)return e;if(i&&e.userData?.components){for(const n of e.userData.components)if(n.guid===s)return n}if(t){if(e.scenes)for(const n in e.scenes){const o=e.scenes[n],r=ka(s,o,t,i);if(r)return r}if(e.children)for(const n in e.children){const o=e.children[n],r=ka(s,o,t,i);if(r)return r}}}function Ic(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]=Ic(n,e)}return t}return s}function _s(s){return new Promise((e,t)=>{setTimeout(e,s)})}function jc(s,e){if(s<=0)return Promise.resolve();if(e||(e=ce.Current),!e)return Promise.reject("No context");const t=e.time.frameCount+s;return new Promise((i,n)=>{if(!e)return n("No context");const o=()=>{e.time.frameCount>=t&&(e.pre_update_callbacks.splice(e.pre_update_callbacks.indexOf(o),1),i())};e.pre_update_callbacks.push(o)})}const Eh=x("debugresolveurl"),rv="rel:";function Xx(s,e){return ws(s,e)}function ws(s,e){if(e===void 0)return Eh&&console.warn("getPath: uri is undefined, returning uri",e),e;if(e.startsWith("./"))return e;if(e.startsWith("http"))return Eh&&console.warn("getPath: uri is absolute, returning uri",e),e;if(s===void 0)return Eh&&console.warn("getPath: source is undefined, returning uri",e),e;e.startsWith(rv)&&(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 Eh&&console.log("source:",s,`changed uri
|
|
4
|
-
from`,e,`
|
|
5
|
-
to `,n,`
|
|
6
|
-
basePath: `+i),n}return e}function av(s){if(s)return s=s.trim(),s=s.split("?")[0]?.split("#")[0],s}class Qx{subscribeWrite(e){this.writeCallbacks.push(e)}unsubscribeWrite(e){const t=this.writeCallbacks.indexOf(e);t!==-1&&this.writeCallbacks.splice(t,1)}writeCallbacks=[];constructor(e,t){this._object=e,this._prop=t,this._wrapperProp=Symbol("$"+t),this.apply()}_applied=!1;_object;_prop;_wrapperProp;apply(){if(this._applied||!this._object)return;const e=this._object,t=this._prop;if(e[t]===void 0)return;this._applied=!0,e[this._wrapperProp]!==void 0&&console.warn("Watcher is being applied to an object that already has a wrapper property. This is not (yet) supported");const i=e[t];e[this._wrapperProp]=i,Object.defineProperty(e,t,{get:()=>e[this._wrapperProp],set:r=>{e[this._wrapperProp]=r;for(const a of this.writeCallbacks)a(r,this._prop)}})}revoke(){if(!this._applied||!this._object)return;this._applied=!1;const e=this._object,t=this._prop;Reflect.deleteProperty(e,t);const i=e[this._wrapperProp];e[t]=i,Reflect.deleteProperty(e,this._wrapperProp)}dispose(){this.revoke(),this.writeCallbacks.length=0,this._object=null}}class ms{_watches=[];constructor(e,t){if(Array.isArray(t))for(const i of t)this._watches.push(new ms(e,i));else this._watches.push(new Qx(e,t))}subscribeWrite(e){for(const t of this._watches)t.subscribeWrite(e)}unsubscribeWrite(e){for(const t of this._watches)t.unsubscribeWrite(e)}apply(){for(const e of this._watches)e.apply()}revoke(){for(const e of this._watches)e.revoke()}dispose(){for(const e of this._watches)e.dispose();this._watches.length=0}}const ta=Symbol("needle:watches");function cu(s,e){if(!s[ta])if(s instanceof c.Vector2)s[ta]=new ms(s,["x","y"]);else if(s instanceof c.Vector3)s[ta]=new ms(s,["x","y","z"]);else if(s instanceof c.Vector4||s instanceof c.Quaternion)s[ta]=new ms(s,["x","y","z","w"]);else return!1;return s[ta].subscribeWrite(e),!0}function Rm(s,e){if(!s)return;const t=s[ta];t&&t.unsubscribeWrite(e)}exports.DeviceUtilities=void 0;(s=>{let e;function t(){if(e!==void 0)return e;const Q=window.navigator.userAgent,_e=/Windows|MacOS|Mac OS/.test(Q),Xt=/Windows NT/.test(Q)&&/Edg/.test(Q)&&!/Win64/.test(Q);return e=_e&&!Xt&&!E()}s.isDesktop=t;let i;function n(){return i!==void 0?i:typeof window.orientation<"u"||navigator.userAgent.indexOf("IEMobile")!==-1?i=!0:i=/iPhone|iPad|iPod|Android|IEMobile/i.test(navigator.userAgent)}s.isMobileDevice=n;function o(){return a()}s.isIPad=o;let r;function a(){if(r!==void 0)return r;const Q=navigator.userAgent.toLowerCase();return r=/iPad/.test(navigator.userAgent)||Q.includes("macintosh")&&"ontouchend"in document}s.isiPad=a;let l;function h(){return l!==void 0?l:l=/Android/.test(navigator.userAgent)}s.isAndroidDevice=h;let d;function u(){return d!==void 0?d:d=/WebXRViewer\//i.test(navigator.userAgent)}s.isMozillaXR=u;let p;function m(){return p!==void 0?p:p=/NeedleAppClip\//i.test(navigator.userAgent)}s.isNeedleAppClip=m;let y;function _(){if(y!==void 0)return y;if(E()||a())return y=!1;const Q=navigator.userAgent.toLowerCase();return navigator.userAgentData?y=navigator.userAgentData.platform==="macOS":y=Q.includes("mac os x")||Q.includes("macintosh")}s.isMacOS=_;let g;function w(){return g!==void 0?g:g=a()&&"xr"in navigator&&V()}s.isVisionOS=w;let b;const v=["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"];function E(){return b!==void 0?b:b=v.includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}s.isiOS=E;let O;function M(){return O!==void 0||(O=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),O}s.isSafari=M;let D;function L(){return D!==void 0?D:D=navigator.userAgent.includes("OculusBrowser")}s.isQuest=L;let j;function V(){return j!==void 0||(j=document.createElement("a").relList.supports("ar")),j}s.supportsQuickLookAR=V;async function W(){try{return(await navigator.permissions.query({name:"microphone"})).state!=="denied"}catch(Q){return console.error("Error querying `microphone` permissions.",Q),!1}}s.microphonePermissionsGranted=W;let k;function N(){if(k!==void 0)return k;const Q=navigator.userAgent.match(/iPhone OS (\d+_\d+)/);if(Q&&(k=Q[1].replace("_",".")),!k){const _e=navigator.userAgent.match(/(?:\(Macintosh;|iPhone;|iPad;).*Version\/(\d+\.\d+)/);_e&&(k=_e[1])}return k||(k=null),k}s.getiOSVersion=N;let $;function ee(){if($!==void 0)return $;const Q=navigator.userAgent.match(/(?:CriOS|Chrome)\/(\d+\.\d+\.\d+\.\d+)/);return Q?$=Q[1].replace("_","."):$=null,$}s.getChromeVersion=ee;let J;function he(){if(J!==void 0)return J;const Q=navigator.userAgent.match(/Version\/(\d+\.\d+)/);return Q&&M()?J=Q[1]:J=null,J}s.getSafariVersion=he})(exports.DeviceUtilities||(exports.DeviceUtilities={}));function Yx(){return exports.DeviceUtilities.isDesktop()}function Kx(){return exports.DeviceUtilities.isMobileDevice()}function Zx(){return exports.DeviceUtilities.isiPad()}function Jx(){return exports.DeviceUtilities.isiPad()}function eS(){return exports.DeviceUtilities.isAndroidDevice()}function tS(){return exports.DeviceUtilities.isMozillaXR()}function iS(){return exports.DeviceUtilities.isMacOS()}function nS(){return exports.DeviceUtilities.isiOS()}function sS(){return exports.DeviceUtilities.isSafari()}function oS(){return exports.DeviceUtilities.isQuest()}async function rS(){return exports.DeviceUtilities.microphonePermissionsGranted()}const io=new WeakMap;function Em(s,e,t){if(!io.get(s)){const n=new MutationObserver(o=>{aS(s,o)});io.set(s,{observer:n,attributeChangedListeners:new Map}),n.observe(s,{attributes:!0})}const i=io.get(s).attributeChangedListeners;return i.has(e)||i.set(e,[]),i.get(e).push(t),()=>{Tm(s,e,t)}}function Tm(s,e,t){if(!io.get(s))return;const i=io.get(s).attributeChangedListeners;if(!i.has(e))return;const n=i.get(e),o=n.indexOf(t);o!==-1&&(n.splice(o,1),n.length<=0&&(i.delete(e),io.get(s)?.observer.disconnect(),io.delete(s)))}function aS(s,e){const t=io.get(s).attributeChangedListeners;for(const i of e)if(i.type==="attributes"){const n=i.attributeName,o=s.getAttribute(n);if(t.has(n))for(const r of t.get(n))r(o)}}class Ep{reason;constructor(e){this.reason=e}}async function Am(s){const e=await Promise.allSettled(s).catch(n=>[new Ep(n.message)]);let t=!1;const i=e.map(n=>"value"in n?n.value:(t=!0,new Ep(n.reason)));return{anyFailed:t,results:i}}const lS=x("debugdebug");let Dm=!1;(x("noerrors")||x("nooverlaymessages"))&&(Dm=!0);const xf="needle_engine_global_error_container";var gi=(s=>(s[s.Log=0]="Log",s[s.Warn=1]="Warn",s[s.Error=2]="Error",s))(gi||{});function lv(){return dv}const Tp=new Array;function cS(s){Tp.push(s)}let Sf=!1;function hS(...s){if(!Sf){Sf=!0;try{for(let e=0;e<Tp.length;e++)Tp[e](...s)}catch(e){console.error(e)}Sf=!1}}const cv=console.error,dS=function(...s){cv.apply(console,s),pS(s),Yo(2,s,{}),fS(...s)};function hv(s){Dm=!s,s?console.error=dS:console.error=cv}function uS(s){return hv(s)}let dv=0;function fS(...s){dv+=1,hS(...s)}function pS(s){if(Array.isArray(s))for(let e=0;e<s.length;e++){const t=s[e];typeof t=="string"&&t.startsWith("THREE.PropertyBinding: Trying to update node for track:")&&(s[e]="Some animated objects couldn't be found: see console for details")}}const Qy=new Set;function Yo(s,e,t={},i,n){if(Dm)return;if(t.once===!0){let a="";if(Array.isArray(e))for(let l=0;l<e.length;l++){let h=e[l];h instanceof Error&&(h=h.message),typeof h!="object"&&(l>0&&(a+=" "),a+=h)}else typeof e=="string"&&(a=e);if(Qy.has(a))return;Qy.add(a)}const o=ce.Current;let r=o?.domElement??document.querySelector("needle-engine");if(o?.isInAR&&(r=o.arOverlayElement),!!r){if(Array.isArray(e)){let a="";for(let l=0;l<e.length;l++){let h=e[l];h instanceof Error&&(h=h.message),typeof h!="object"&&(l>0&&(a+=" "),a+=h)}e=a}!e||e.length<=0||mS(s,r,e,t)}}const ha=new Map,Yy=.2;function mS(s,e,t,i={}){if(t==null)return;const n=_S(e);if(n.childElementCount>=20){const h=n.lastElementChild;Ky(h)}t.length>400&&(t=t.substring(0,400)+"...");const o=i.key??t;if(ha.has(o)){ha.get(o)?.update(t,i);return}const r=bS(s,t);n.prepend(r);const a=()=>{ha.delete(o),Ky(r)};let l=setTimeout(a,Math.max(Yy,i.duration??10)*1e3);ha.set(o,{update:(h,d)=>{h.length>400&&(h=h.substring(0,400)+"..."),r.innerHTML=h,d.duration&&(clearTimeout(l),l=setTimeout(a,Math.max(Yy,d.duration)*1e3))},removeFunction:a})}function gS(){lS&&console.log("Clearing messages");for(const s of ha.values())s?.removeFunction.call(s);ha.clear()}const yS=`
|
|
7
|
-
|
|
8
|
-
@import url('https://fonts.googleapis.com/css2?family=Roboto+Flex:opsz,wght@8..144,100..1000&display=swap');
|
|
9
|
-
|
|
10
|
-
div[data-needle_engine_debug_overlay] {
|
|
11
|
-
font-family: 'Roboto Flex', sans-serif;
|
|
12
|
-
font-weight: 400;
|
|
13
|
-
font-size: 16px;
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
div[data-needle_engine_debug_overlay] strong {
|
|
17
|
-
font-weight: 700;
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
div[data-needle_engine_debug_overlay] a {
|
|
21
|
-
color: white;
|
|
22
|
-
text-decoration: none;
|
|
23
|
-
border-bottom: 1px solid rgba(255, 255, 255, 0.3);
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
div[data-needle_engine_debug_overlay] a:hover {
|
|
27
|
-
text-decoration: none;
|
|
28
|
-
border: none;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
div[data-needle_engine_debug_overlay] .log strong {
|
|
32
|
-
color: rgba(200,200,200,.9);
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
div[data-needle_engine_debug_overlay] .warn strong {
|
|
36
|
-
color: rgba(255,255,230, 1);
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
div[data-needle_engine_debug_overlay] .error strong {
|
|
40
|
-
color: rgba(255,100,120, 1);
|
|
41
|
-
}
|
|
42
|
-
`;function _S(s){globalThis[xf]||(globalThis[xf]=new Map);const e=globalThis[xf];if(e.has(s))return e.get(s);{const t=document.createElement("div");e.set(s,t),t.setAttribute("data-needle_engine_debug_overlay",""),t.classList.add("debug-container"),t.style.cssText=`
|
|
43
|
-
position: absolute;
|
|
44
|
-
top: 0;
|
|
45
|
-
right: 5px;
|
|
46
|
-
padding-top: env(safe-area-inset-top, 0px);
|
|
47
|
-
max-width: 70%;
|
|
48
|
-
max-height: calc(100% - 105px);
|
|
49
|
-
z-index: 100000;
|
|
50
|
-
pointer-events: scroll;
|
|
51
|
-
display: flex;
|
|
52
|
-
align-items: end;
|
|
53
|
-
flex-direction: column;
|
|
54
|
-
color: white;
|
|
55
|
-
overflow: auto;
|
|
56
|
-
word-break: break-word;
|
|
57
|
-
`,exports.DeviceUtilities.isNeedleAppClip()&&(t.style.left="5px",t.style.right="unset");const i=document.querySelector('meta[name="viewport"]');i&&!i.getAttribute("content")?.includes("viewport-fit=")&&i.setAttribute("content",i.getAttribute("content")+",viewport-fit=cover"),s.shadowRoot?s.shadowRoot.appendChild(t):s.appendChild(t);const n=document.createElement("style");return n.innerHTML=yS,t.appendChild(n),t}}const uv=Symbol("logtype"),Dd=new Map;function Ky(s){s.remove();const e=s[uv],t=Dd.get(e)??[];t.push(s),Dd.set(e,t)}function bS(s,e){if(Dd.has(s)){const i=Dd.get(s);if(i.length>0){const n=i.pop();return n.innerHTML=e,n}}const t=document.createElement("div");switch(t.setAttribute("data-id","__needle_engine_debug_overlay"),t.style.marginRight="5px",t.style.padding=".5em",t.style.backgroundColor="rgba(0,0,0,.9)",t.style.marginTop="5px",t.style.marginBottom="3px",t.style.borderRadius="8px",t.style.pointerEvents="all",t.style.userSelect="text",t.style.maxWidth="250px",t.style.whiteSpace="pre-wrap",t.style["backdrop-filter"]="blur(10px)",t.style["-webkit-backdrop-filter"]="blur(10px)",t.style.backgroundColor="rgba(20,20,20,.8)",t.style.boxShadow="inset 0 0 80px rgba(0,0,0,.2), 0 0 5px rgba(0,0,0,.2)",t.style.border="1px solid rgba(160,160,160,.2)",t[uv]=s,s){case 0:t.classList.add("log"),t.style.color="rgba(200,200,200,.7)",t.style.backgroundColor="rgba(40,40,40,.7)";break;case 1:t.classList.add("warn"),t.style.color="rgb(255, 255, 150)",t.style.backgroundColor="rgba(50,50,20,.8)";break;case 2:t.classList.add("error"),t.style.color="rgb(255, 50, 50",t.style.backgroundColor="rgba(50,20,20,.8)";break}return t.title="Open the browser console (F12) for more information",t.innerHTML=e,t}class vS{random(e,t){return Array.isArray(e)?e.length<=0?null:e[Math.floor(Math.random()*e.length)]:e!==void 0&&t!==void 0?Math.random()*(t-e)+e:Math.random()}randomVector3(e,t=0,i=1){e.x=this.random(t,i),e.y=this.random(t,i),e.z=this.random(t,i)}clamp(e,t,i){return e<t?t:e>i?i:e}clamp01(e){return this.clamp(e,0,1)}lerp(e,t,i){return i=i<0?0:i,i=i>1?1:i,e+(t-e)*i}inverseLerp(e,t,i){return(i-e)/(t-e)}remap(e,t,i,n,o){return n+(o-n)*(e-t)/(i-t)}moveTowards(e,t,i){return e+=i,(i<0&&e<t||i>0&&e>t)&&(e=t),e}Rad2Deg=180/Math.PI;Deg2Rad=Math.PI/180;Epsilon=1e-5;toDegrees(e){return e*180/Math.PI}toRadians(e){return e*Math.PI/180}tan(e){return Math.tan(e)}gammaToLinear(e){return Math.pow(e,2.2)}linearToGamma(e){return Math.pow(e,1/2.2)}approximately(e,t,i=Number.EPSILON){for(const n of wS){const o=e[n],r=t[n];if(o===void 0||r===void 0)break;if(Math.abs(o-r)>i)return!1}return!0}easeInOutCubic(e){return e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2}}const wS=["x","y","z","w"],I=new vS;class Zy{y;s;alpha=0;constructor(e){this.setAlpha(e),this.y=null,this.s=null}setAlpha(e){if(e<=0||e>1)throw new Error;this.alpha=e}filter(e,t){t&&this.setAlpha(t);let i;return this.y?i=this.alpha*e+(1-this.alpha)*this.s:i=e,this.y=e,this.s=i,i}lastValue(){return this.y}reset(e){this.y=e,this.s=e}}class dd{freq;minCutOff;beta;dCutOff;x;dx;lasttime;constructor(e,t=1,i=0,n=1){if(e<=0||t<=0||n<=0)throw new Error;this.freq=e,this.minCutOff=t,this.beta=i,this.dCutOff=n,this.x=new Zy(this.alpha(this.minCutOff)),this.dx=new Zy(this.alpha(this.dCutOff)),this.lasttime=null}alpha(e){const t=1/this.freq;return 1/(1+1/(2*Math.PI*e)/t)}filter(e,t=null){this.lasttime&&t&&(this.freq=1/(t-this.lasttime)),this.lasttime=t;const i=this.x.lastValue(),n=i?(e-i)*this.freq:0,o=this.dx.filter(n,this.alpha(this.dCutOff)),r=this.minCutOff+this.beta*Math.abs(o);return this.x.filter(e,this.alpha(r))}reset(e){e!=null&&this.x.reset(e),this.x.alpha=this.alpha(this.minCutOff),this.dx.alpha=this.alpha(this.dCutOff),this.lasttime=null}}class Lm{x;y;z;constructor(e,t=1,i=0,n=1){this.x=new dd(e,t,i,n),this.y=new dd(e,t,i,n),this.z=new dd(e,t,i,n)}filter(e,t,i=null){t.x=this.x.filter(e.x,i),t.y=this.y.filter(e.y,i),t.z=this.z.filter(e.z,i)}reset(e){this.x.reset(e?.x),this.y.reset(e?.y),this.z.reset(e?.z)}}const ud="needle:cameraController";function fv(s){return s[ud]}function Ap(s,e,t){t?s[ud]=e:s[ud]===e&&(s[ud]=null)}const Dp="needle:autofit";function pv(s){return s[Dp]===void 0?!0:s[Dp]!==!1}function Ld(s,e){s[Dp]=e}let en;const xS={x:0,y:0,width:0,height:0},SS=x("debugfocusrect");function CS(s,e,t,i,n){s instanceof Element&&(SS&&s instanceof HTMLElement&&(s.style.outline="2px dashed rgba(255, 150, 0, .8)"),s=s.getBoundingClientRect()),en=n.domElement.getBoundingClientRect();const o=xS;o.x=s.x,o.y=s.y,o.width=s.width,o.height=s.height,o.x-=en.x,o.y-=en.y;const r=en.width,a=en.height,l=i.view,h=e.zoom;let d=l?.offsetX||0,u=l?.offsetY||0,p=en.width,m=en.height;p/=h,m/=h,d=p*(h-1)*.5,u=m*(h-1)*.5;const y=o.x+o.width*.5,_=o.y+o.height*.5,g=en.width*.5,w=en.height*.5,b=y-g,v=_-w;d-=b/h,u-=v/h,e.offsetX!==void 0&&(d+=e.offsetX*(en.width*.5)),e.offsetY!==void 0&&(u-=e.offsetY*(en.height*.5));const E=l?.offsetX||d,O=l?.offsetY||u;d=I.lerp(E,d,t),u=I.lerp(O,u,t);const M=l?.width||r,D=l?.height||a;p=I.lerp(M,p,t),m=I.lerp(D,m,t),i.setViewOffset(r,a,d,u,p,m),i.updateProjectionMatrix(),e.damping>0&&(e.damping*=1-t,e.damping<.01&&(e.damping=0),e.damping=Math.max(0,e.damping))}function PS(s,e,t){const i=s.length(),n=e.length(),o=I.lerp(i,n,t);return s.lerp(e,t).normalize().multiplyScalar(o)}const Cf=new c.Quaternion,mv=new c.Quaternion().setFromAxisAngle(new c.Vector3(0,1,0),Math.PI);function OS(s,e){s.lookAt(e),s.quaternion.multiply(mv)}function Bc(s,e,t=!0,i=!1){if(s===e)return;Cf.copy(s.quaternion);const n=Y(e),o=Y(s);if(i){if(dn(s,pe(e)),t){const r=o.y,a=o.sub(yv(s));a.y=r,s.lookAt(a),s.quaternion.multiply(mv)}Number.isNaN(s.quaternion.x)&&s.quaternion.copy(Cf);return}t&&(n.y=o.y),s.lookAt(n),Number.isNaN(s.quaternion.x)&&s.quaternion.copy(Cf)}function MS(s,e,t,i=1){if(t){const n=F(0,0,0),o=e.x/window.innerWidth*2-1,r=-(e.y/window.innerHeight)*2+1;n.set(o,r,0),n.unproject(t);const a=t.worldPosition,l=s.worldPosition.distanceTo(a),h=n.sub(a);h.multiplyScalar(i*3.6*l);const d=t.worldPosition.add(h);return s.lookAt(d),d}return null}const kS=new _i(()=>new c.Vector3,100);function F(s,e,t){const i=kS.get();return i.set(0,0,0),s instanceof c.Vector3?i.copy(s):Array.isArray(s)?i.set(s[0],s[1],s[2]):s instanceof DOMPointReadOnly?i.set(s.x,s.y,s.z):typeof s=="number"?(i.x=s,i.y=e!==void 0?e:i.x,i.z=t!==void 0?t:i.x):typeof s=="object"&&(i.x=s.x,i.y=s.y,i.z=s.z),i}const RS=new _i(()=>new c.Color,30);function gv(s){const e=RS.get();return s?e.copy(s):e.set(0,0,0),e}const ES=new _i(()=>new c.Quaternion,100);function ei(s,e,t,i){const n=ES.get();return n.identity(),s instanceof c.Quaternion?n.copy(s):s instanceof DOMPointReadOnly?n.set(s.x,s.y,s.z,s.w):typeof s=="number"&&e!==void 0&&t!==void 0&&i!==void 0?n.set(s,e,t,i):typeof s=="object"&&"x"in s&&"y"in s&&"z"in s&&"w"in s&&n.set(s.x,s.y,s.z,s.w),n}const Im=new _i(()=>new c.Vector3,100),Jy=Symbol("lastMatrixWorldUpdateKey");function Y(s,e=null,t=!0){const i=e??Im.get();return s?s.parent?(t&&s.updateWorldMatrix(!0,!1),s.matrixWorldNeedsUpdate&&s[Jy]!==Date.now()&&(s[Jy]=Date.now(),s.updateMatrixWorld()),i.setFromMatrixPosition(s.matrixWorld),i):i.copy(s.position):i.set(0,0,0)}function at(s,e){if(!s)return s;const t=Im.get();return e!==t&&t.copy(e),s.parent!==null&&s.parent.worldToLocal(t),s.position.set(t.x,t.y,t.z),s}function dr(s,e,t,i){const n=Im.get();return n.set(e,t,i),at(s,n),s}const Id=new _i(()=>new c.Quaternion,100),er=new c.Quaternion,Pf=new c.Quaternion;function pe(s,e=null){if(!s)return Id.get().identity();const t=e??Id.get();return s.parent?(s.getWorldQuaternion(t),t):t.copy(s.quaternion)}function dn(s,e){if(!s)return;e!==er&&er.copy(e);const t=er;s?.parent?.getWorldQuaternion(Pf),Pf.invert();const n=Pf.multiply(t);s.quaternion.set(n.x,n.y,n.z,n.w)}function jm(s,e,t,i,n){er.set(e,t,i,n),dn(s,er)}const TS=new _i(()=>new c.Vector3,100),AS=new c.Vector3;function je(s,e=null){return e||(e=TS.get()),s?s.parent?(s.getWorldScale(e),e):e.copy(s.scale):e.set(0,0,0)}function Ra(s,e){if(!s)return;if(!s.parent){s.scale.copy(e);return}const t=AS;s.parent.getWorldScale(t),s.scale.copy(e),s.scale.divide(t)}const DS=new c.Vector3,e_=new c.Quaternion;function LS(s){return pe(s,e_),DS.set(0,0,1).applyQuaternion(e_)}const IS=new _i(()=>new c.Vector3,100),t_=new c.Quaternion;function yv(s,e){return e||(e=IS.get().set(0,0,1)),pe(s,t_),e.applyQuaternion(t_)}const i_=new c.Euler,n_=new c.Euler,jS=new c.Vector3;function Bm(s){const e=Id.get();return s.getWorldQuaternion(e),n_.setFromQuaternion(e),n_}function Fm(s,e){const t=Id.get();dn(s,t.setFromEuler(e))}function hu(s){const e=Bm(s),t=jS;return t.set(e.x,e.y,e.z),t.x=I.toDegrees(t.x),t.y=I.toDegrees(t.y),t.z=I.toDegrees(t.z),t}function _v(s,e){Fc(s,e.x,e.y,e.z,!0)}function Fc(s,e,t,i,n=!0){n&&(e=I.toRadians(e),t=I.toRadians(t),i=I.toRadians(i)),i_.set(e,t,i),er.setFromEuler(i_),dn(s,er)}function jd(s,e=!0){s&&(e?(function t(i){console.groupCollapsed((i.name?i.name:"(no name : "+i.type+")")+" %o",i),i.children.forEach(t),console.groupEnd()})(s):s.traverse(function(t){for(var i="|___",n=t;n.parent!==null;)i=" "+i,n=n.parent;console.log(i+t.name+" <"+t.type+">")}))}function BS(s){let e=s?.name||"";if(!s)return e;let t=s.parent;for(;t;)e=t.name+"/"+e,t=t.parent;return e}function bv(s){if(s){const e=s;return e.blendMode!==void 0&&e.clampWhenFinished!==void 0&&e.enabled!==void 0&&e.fadeIn!==void 0&&e.getClip!==void 0}return!1}class Bd extends c.ShaderMaterial{static vertex=`
|
|
58
|
-
varying vec2 vUv;
|
|
59
|
-
void main(){
|
|
60
|
-
vUv = uv;
|
|
61
|
-
gl_Position = vec4(position.xy, 0., 1.0);
|
|
62
|
-
}`;constructor(){super({vertexShader:Bd.vertex,uniforms:{map:new c.Uniform$1(null),flipY:new c.Uniform$1(!0),writeDepth:new c.Uniform$1(!1),depthTexture:new c.Uniform$1(null)},fragmentShader:`
|
|
63
|
-
uniform sampler2D map;
|
|
64
|
-
uniform bool flipY;
|
|
65
|
-
uniform bool writeDepth;
|
|
66
|
-
uniform sampler2D depthTexture;
|
|
67
|
-
|
|
68
|
-
varying vec2 vUv;
|
|
69
|
-
|
|
70
|
-
void main(){
|
|
71
|
-
vec2 uv = vUv;
|
|
72
|
-
if (flipY) uv.y = 1.0 - uv.y;
|
|
73
|
-
gl_FragColor = texture2D(map, uv);
|
|
74
|
-
|
|
75
|
-
if (writeDepth) {
|
|
76
|
-
float depth = texture2D(depthTexture, uv).r;
|
|
77
|
-
gl_FragDepth = depth;
|
|
78
|
-
|
|
79
|
-
// float linearDepth = (depth - 0.99) * 100.0; // Enhance near 1.0 values
|
|
80
|
-
// gl_FragColor = vec4(linearDepth, linearDepth, linearDepth, 1.0);
|
|
81
|
-
}
|
|
82
|
-
}`})}reset(){this.uniforms.map.value=null,this.uniforms.flipY.value=!0,this.uniforms.writeDepth.value=!1,this.uniforms.depthTexture.value=null,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}}class ho{static planeGeometry=new c.PlaneGeometry(2,2,1,1);static renderer=new c.WebGLRenderer({antialias:!1,alpha:!0});static perspectiveCam=new c.PerspectiveCamera;static orthographicCam=new c.OrthographicCamera;static scene=new c.Scene;static blitMaterial=new Bd;static mesh=new c.Mesh(ho.planeGeometry,ho.blitMaterial);static copyTexture(e,t){t||(t=this.blitMaterial),this.blitMaterial.reset();const i=t||this.blitMaterial;i.uniforms.map.value=e,i.needsUpdate=!0,i.uniformsNeedUpdate=!0;const n=i.vertexShader;i.vertexShader=Bd.vertex;const o=this.mesh;o.material=i,o.frustumCulled=!1,this.scene.children.length=0,this.scene.add(o),this.renderer.setSize(e.image.width,e.image.height),this.renderer.clear(),this.renderer.render(this.scene,this.perspectiveCam);const r=new c.Texture(this.renderer.domElement);return r.name="Copy",r.needsUpdate=!0,i.vertexShader=n,r}static blit(e,t,i){const{renderer:n=this.renderer,blitMaterial:o=this.blitMaterial,flipY:r=!1,depthTexture:a=null,depthTest:l=!0,depthWrite:h=!0}=i||{};this.blitMaterial.reset(),o.uniforms.map&&(o.uniforms.map.value=e),o.uniforms.flipY&&(o.uniforms.flipY.value=r),a?(o.uniforms.writeDepth=new c.Uniform$1(!0),o.uniforms.depthTexture.value=a):(o.uniforms.writeDepth=new c.Uniform$1(!1),o.uniforms.depthTexture.value=null),o.needsUpdate=!0,o.uniformsNeedUpdate=!0;const d=this.mesh;d.material=o,d.frustumCulled=!1,this.scene.children.length=0,this.scene.add(d);const u=n.getRenderTarget(),p=n.getContext();l?p.enable(p.DEPTH_TEST):p.disable(p.DEPTH_TEST),n.state.buffers.depth.setMask(h),n.setClearColor(new c.Color(0,0,0),0),n.setRenderTarget(t),n.clear(),n.render(this.scene,this.perspectiveCam),n.setRenderTarget(u),p.enable(p.DEPTH_TEST),n.state.buffers.depth.setMask(!0)}static textureToCanvas(e,t=!1){if(!e)return null;(t===!0||e.isCompressedTexture===!0)&&(e=vv(e));const i=e.image;if(US(i)){const n=document.createElement("canvas");n.width=i.width,n.height=i.height;const o=n.getContext("2d");return o?(o.drawImage(i,0,0,i.width,i.height,0,0,n.width,n.height),n):(console.error("Failed getting canvas 2d context"),null)}return null}}function vv(s){return ho.copyTexture(s)}function FS(s,e=!1){return ho.textureToCanvas(s,e)}function US(s){return typeof HTMLImageElement<"u"&&s instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&s instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&s instanceof OffscreenCanvas||typeof ImageBitmap<"u"&&s instanceof ImageBitmap}function zS(s){const e=s.type;return e==="Mesh"||e==="SkinnedMesh"}function Um(s,e){e?s["needle:rendercustomshadow"]=!0:s["needle:rendercustomshadow"]=!1}function wv(s){if(s){if(s["needle:rendercustomshadow"]===!0)return!0;if(s["needle:rendercustomshadow"]==null)return!0}return!1}function ri(s,e=void 0,t=void 0,i=void 0){const n=i||new c.Box3;n.makeEmpty();const o=[];function r(l){let h=!0;if(l.visible&&pv(l)!==!1&&!(l.type==="TransformControlsGizmo"||l.type==="TransformControlsPlane")){if(l instanceof c.Box3Helper&&(h=!1),l instanceof c.GridHelper&&(h=!1),l instanceof X.GroundedSkybox&&(h=!1),l.isGizmo===!0&&(h=!1),l.material instanceof c.ShadowMaterial&&(h=!1),zS(l)||(h=!1),t&&l.layers.test(t)===!1&&(h=!1),h){if(e&&Array.isArray(e)&&e?.includes(l))return;if(typeof e=="function"&&e(l)===!0)return}if(l.isUI!==!0){if(h){const d=l.children;l.children=o;const u=l.position,p=l.scale;if(Number.isNaN(u.x)||Number.isNaN(u.y)||Number.isNaN(u.z)){console.warn(`Object "${l.name}" has NaN values in position or scale.... will ignore it`,u,p);return}l.geometry===null&&(l.geometry=void 0),n.expandByObject(l,!0),l.children=d}for(const d of l.children)r(d)}}}let a=!1;Array.isArray(s)||(s=[s]);for(const l of s)l&&(a=!0,l.updateMatrixWorld(),r(l));return a||console.warn("No objects to fit camera to..."),n}function xv(s,e,t){const i=ri([s],t?.ignore),n=new c.Vector3;i.getSize(n);const o=new c.Vector3;i.getCenter(o);const r=new c.Vector3;e.getSize(r);const a=new c.Vector3;e.getCenter(a);const l=new c.Vector3;l.set(r.x/n.x,r.y/n.y,r.z/n.z);const h=Math.min(l.x,l.y,l.z),d=t?.scale!==!1;if(d&&Ra(s,je(s).multiplyScalar(h)),t?.position!==!1){const u=new c.Vector3;i.getCenter(u),u.y=i.min.y;const p=new c.Vector3;e.getCenter(p),p.y=e.min.y;const m=p.clone().sub(u);d&&m.multiplyScalar(h),at(s,Y(s).add(m))}return{boundsBefore:i,scale:l}}function Sv(s,e){const t=ri([s]),i=new c.Vector3;t.getCenter(i),i.y=t.min.y;const n=e.clone().sub(i),o=Y(s);return at(s,o.add(n)),{offset:n,bounds:t}}function zm(s,e,t,i){if(Array.isArray(e)){let r=!0;for(let a=0;a<e.length;a++)zm(s,e[a],a,e)||(r=!1);return r}if(e.type==="MeshStandardMaterial"||e.type==="MeshBasicMaterial")return!1;if(e["material:fbx"]!=null)return!0;const n=new c.MeshStandardMaterial;n["material:fbx"]=e;const o=e;return o&&(o.map?n.color.set(1,1,1):n.color.copyLinearToSRGB(o.color),n.emissive.copyLinearToSRGB(o.emissive),n.emissiveIntensity=o.emissiveIntensity,n.opacity=o.opacity,n.displacementScale=o.displacementScale,n.transparent=o.transparent,n.bumpMap=o.bumpMap,n.aoMap=o.aoMap,n.map=o.map,n.displacementMap=o.displacementMap,n.emissiveMap=o.emissiveMap,n.normalMap=o.normalMap,n.envMap=o.envMap,n.alphaMap=o.alphaMap,n.metalness=o.reflectivity,n.vertexColors=o.vertexColors,o.shininess&&(n.roughness=1-Math.sqrt(o.shininess)/10),n.needsUpdate=!0),t===void 0?s.material=n:i[t]=n,!0}let Th=!1;cS((...s)=>{A()&&ce.Current?.isInXR&&(ba(!0),Cv("error",...s))});function ba(s){if(s){if(Th)return;Th=!0,VS()}else{if(!Th)return;Th=!1,$S()}}const Zl={log:void 0,warn:void 0,error:void 0};class NS{familyName="needle-xr";root=null;context=null;defaultFontSize=.06;constructor(){this.ensureFont()}onEnable(){this.context=ce.Current||ce.All[0],this.context.pre_render_callbacks.push(this.onBeforeRender)}onDisable(){this.context?.pre_render_callbacks.splice(this.context?.pre_render_callbacks.indexOf(this.onBeforeRender),1),this.root?.removeFromParent()}targetObject=new c.Object3D;userForwardViewPoint=new c.Vector3;oneEuroFilter=new Lm(90,.8);_lastElementRemoveTime=0;onBeforeRender=()=>{const e=this.context?.mainCamera;if(this.context&&e instanceof c.PerspectiveCamera){const t=this.getRoot();Number.isNaN(t.position.x)&&t.position.set(0,0,0),Number.isNaN(t.quaternion.x)&&t.quaternion.set(0,0,0,1),this.context.scene.add(this.targetObject);const i=this.context.xr?.rigScale??1,n=3.5*i,o=e.worldForward;o.y=0,o.normalize().multiplyScalar(n),this.userForwardViewPoint.copy(e.worldPosition).sub(o),this.targetObject.position.distanceTo(this.userForwardViewPoint)>2*i&&(this.targetObject.position.copy(this.userForwardViewPoint),Bc(this.targetObject,e,!0,!0),this.targetObject.rotateY(Math.PI)),this.oneEuroFilter.filter(this.targetObject.position,t.position,this.context.time.time);const a=this.context.time.deltaTime;if(t.quaternion.slerp(this.targetObject.quaternion,a*5),t.scale.setScalar(i),this.targetObject.removeFromParent(),this.context.scene.add(t),this.context.time.time-this._lastElementRemoveTime>.1){this._lastElementRemoveTime=this.context.time.time;const l=Date.now();for(let h=0;h<this._activeTexts.length;h++){const d=this._activeTexts[h];if(d instanceof ie.__webpack_exports__default.Text&&l-d._activatedTime>2e4){d.removeFromParent(),this._textBuffer.push(d),this._activeTexts.splice(h,1);break}}}}};addLog(e,t){const i=this.getRoot(),n=this.getText();let o=16777215,r=0;switch(e){case"log":o=16777215,r=0;break;case"warn":o=16772761,r=4465152;break;case"error":o=16755370,r=7798784;break}t.length>1e3&&(t=t.substring(0,1e3)+"...");const a=new Date().toISOString().split("T")[1].split(".")[0];n.textContent="["+a+"] "+t,n.visible=!0,n._activatedTime=Date.now(),i.add(n),this._activeTexts.push(n),this.context&&this.context.scene.add(i),n.set({backgroundColor:o,color:r}),ie.__webpack_exports__default.update()}ensureFont(){let e=ie.__webpack_exports__default.FontLibrary.getFontFamily(this.familyName);e||(e=ie.__webpack_exports__default.FontLibrary.addFontFamily(this.familyName),e.addVariant("normal","normal","https://cdn.needle.tools/static/fonts/msdf/arial/arial-msdf.json","https://cdn.needle.tools/static/fonts/msdf/arial/arial.png")?.addEventListener("ready",()=>{ie.__webpack_exports__default.update()}))}textOptions={fontSize:this.defaultFontSize,fontFamily:this.familyName,padding:.03,margin:.005,color:0,backgroundColor:16777215,backgroundOpacity:.4,borderRadius:.03,offset:.025};_textBuffer=[];_activeTexts=[];getText(){const e=this.getRoot();if(this._textBuffer.length>0){const i=this._textBuffer.pop();return i.visible=!0,setTimeout(()=>this.disableDepthTestRecursive(i),100),i}if(e.children.length>20&&this._activeTexts.length>0)return this._activeTexts.shift();const t=new ie.__webpack_exports__default.Text(this.textOptions);return setTimeout(()=>this.disableDepthTestRecursive(t),500),setTimeout(()=>this.disableDepthTestRecursive(t),1500),t}disableDepthTestRecursive(e,t=0){for(let n=0;n<e.children.length;n++){const o=e.children[n];o instanceof c.Object3D&&this.disableDepthTestRecursive(o,t+1)}e.renderOrder=10*t,e.layers.set(2);const i=e.material;i&&(i.depthWrite=!1,i.depthTest=!1,i.transparent=!0),t===0&&ie.__webpack_exports__default.update()}getRoot(){if(this.root)return this.root;const e=this.defaultFontSize,t={boxSizing:"border-box",fontFamily:this.familyName,width:"2.6",fontSize:e,color:0,lineHeight:1,backgroundColor:16777215,backgroundOpacity:0,whiteSpace:"pre-wrap",flexDirection:"column-reverse"};return this.root=new ie.__webpack_exports__default.Block(t),this.root}}let tr=null;function VS(){tr||(tr=new NS),tr.onEnable();for(const s in Zl){Zl[s]=console[s];let e=!1;console[s]=function(){if(Zl[s]?.apply(console,arguments),!e)try{e=!0,Cv(s,...arguments)}finally{e=!1}}}}function $S(){tr?.onDisable();for(const s in Zl)console[s]=Zl[s]}const bl=new Map;function Cv(s,...e){try{switch(bl.clear(),s){case"log":tr?.addLog("log",t());break;case"warn":tr?.addLog("warn",t());break;case"error":tr?.addLog("error",t());break}}catch(o){console.error("Error in spatial console",o)}finally{bl.clear()}function t(){let o="";for(let r=0;r<e.length;r++){const a=e[r];o+=i(a),r<e.length-1&&(o+=", ")}return o}function i(o,r=0){if(typeof o=="string")return'"'+o+'"';if(typeof o=="number"){if(o%1!==0){const l=o.toFixed(5),h=l.indexOf(".");let d=l.length-1;for(;d>h&&l[d]==="0";)d--;return l.substring(0,d+1)}return o.toString()}else if(Array.isArray(o)){let a="[";for(let l=0;l<o.length;l++){const h=o[l];a+=i(h,r+1),l<o.length-1&&(a+=", ")}return a+="]",a}else{if(o===null)return"null";if(o===void 0)return"undefined";if(typeof o=="function")return o.name+"()"}if(o instanceof c.Vector2)return`(${i(o.x)}, ${i(o.y)})`;if(o instanceof c.Vector3)return`(${i(o.x)}, ${i(o.y)}, ${i(o.z)})`;if(o instanceof c.Vector4)return`(${i(o.x)}, ${i(o.y)}, ${i(o.z)}, ${i(o.w)})`;if(o instanceof c.Quaternion)return`(${i(o.x)}, ${i(o.y)}, ${i(o.z)}, ${i(o.w)})`;if(o instanceof c.Material||o instanceof c.Texture)return o.name;if(o instanceof c.Matrix3)return`[${o.elements.join(", ")}]`;if(o instanceof c.Matrix4)return`[${o.elements.join(", ")}]`;if(o instanceof c.Layers)return o.mask.toString();if(typeof o=="object"){if(bl.has(o))return"*";let a=`{
|
|
83
|
-
`;a+=n(r);const l=Object.keys(o);let h="";for(let d=0;d<l.length;d++){const u=l[d],p=o[u];if(bl.has(p)){h+="";continue}bl.set(p,!0),h+=u+":"+i(p,r+1),d<l.length-1&&(h+=", "),h.length>=60&&(h+=`
|
|
84
|
-
`,h+=n(r),a+=h,h="")}return a+=h,a+=`
|
|
85
|
-
}`,a}return o}function n(o){let r="";for(let a=0;a<o;a++)r+=" ";return r}}const WS=x("nodevlogs");function Se(s,e){Yo(e?.type??gi.Log,s,e)}function fe(s,e){Se(s,{...e,type:gi.Warn})}function Uc(s,e){Se(s,{...e,type:gi.Error})}let Lp,Of;function A(){if(WS)return!1;if(Lp!==void 0)return Lp;if(Of!==void 0)return Of;let s=yi();return s||(s=window.location.hostname.endsWith(".local-credentialless.webcontainer.io")),Of=s,s}function GS(s){Lp=s}let Zt,Io=null,In=null,vl=!1,s_=null;const Pv="terminal",HS=x("console");HS&&Nm();const qS=Symbol("consoleParent");function Nm(){if(Zt){Zt.showSwitch();return}ZS()}function Ov(){Zt&&(Zt.hide(),Zt.hideSwitch())}function XS(){s_||(s_=setInterval(QS,500))}let o_=0;function QS(){const s=lv(),e=s!==o_;o_=s,e&&YS()}function YS(){Nm(),In&&(In.setAttribute("error","true"),In.innerText="🤬")}function KS(){In&&(In.removeAttribute("error"),In.innerText=Pv)}function ZS(s=!1){if(Zt!==void 0||vl)return;vl=!0;const e=document.createElement("script");e.onload=()=>{if(!globalThis.VConsole){console.warn("🌵 Debug console failed to load."),vl=!1,Zt=null;return}vl=!1,XS(),Zt=new VConsole({pluginOrder:["default","needle-console"]});const t=globalThis["needle:codegen_files"];if(t&&t.length>0&&Zt.addPlugin(JS()),Zt.addPlugin(nC()),Zt.addPlugin(sC()),Io=mC(),Io&&(Io[qS]=Io.parentElement,Io.style.position="absolute",Io.style.zIndex=Number.MAX_SAFE_INTEGER.toString()),Zt.setSwitchPosition(20,30),In=pC(),In){In.innerText=Pv,In.addEventListener("click",KS);const i=document.createElement("style"),n=40;i.innerHTML=`
|
|
86
|
-
#__vconsole .vc-switch {
|
|
87
|
-
border: 1px solid rgba(255, 255, 255, .1);
|
|
88
|
-
border-radius: 50%;
|
|
89
|
-
width: ${n}px;
|
|
90
|
-
height: ${n}px;
|
|
91
|
-
padding: 0;
|
|
92
|
-
line-height: ${n}px;
|
|
93
|
-
font-size: ${n*.4}px;
|
|
94
|
-
text-align: center;
|
|
95
|
-
background: #ffffff5c;
|
|
96
|
-
backdrop-filter: blur(16px);
|
|
97
|
-
-webkit-backdrop-filter: blur(16px);
|
|
98
|
-
user-select: none;
|
|
99
|
-
pointer-events: auto;
|
|
100
|
-
transition: transform .2s ease-in-out;
|
|
101
|
-
box-shadow: 0px 7px 0.5rem 0px rgb(0 0 0 / 6%), inset 0px 0px 1.3rem rgba(0,0,0,.05);
|
|
102
|
-
|
|
103
|
-
font-family: 'Material Symbols Outlined';
|
|
104
|
-
color: black;
|
|
105
|
-
font-size: 2.3em;
|
|
106
|
-
font-weight: 100;
|
|
107
|
-
}
|
|
108
|
-
#__vconsole .vc-switch:hover {
|
|
109
|
-
cursor: pointer;
|
|
110
|
-
transform: scale(1.1);
|
|
111
|
-
transition: transform .1s ease-in-out, background .1s linear;
|
|
112
|
-
background: rgba(245, 245, 245, .8);
|
|
113
|
-
outline: rgba(0, 0, 0, .05) 1px solid;
|
|
114
|
-
}
|
|
115
|
-
#__vconsole .vc-switch[error] {
|
|
116
|
-
background: rgba(255,0,0,.2);
|
|
117
|
-
animation: vconsole-notify 1s ease-in-out;
|
|
118
|
-
line-height: 35px;
|
|
119
|
-
}
|
|
120
|
-
@keyframes vconsole-notify {
|
|
121
|
-
from {
|
|
122
|
-
transform: scale(1, 1);
|
|
123
|
-
}
|
|
124
|
-
10% {
|
|
125
|
-
transform: scale(1.3, 1.3);
|
|
126
|
-
}
|
|
127
|
-
70% {
|
|
128
|
-
transform: scale(1.4, 1.4);
|
|
129
|
-
}
|
|
130
|
-
to {
|
|
131
|
-
transform: scale(1, 1);
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
#__vconsole .vc-panel {
|
|
135
|
-
font-family: monospace;
|
|
136
|
-
font-size: 11px;
|
|
137
|
-
}
|
|
138
|
-
#__vconsole .vc-plugin-box.vc-actived {
|
|
139
|
-
height: 100%;
|
|
140
|
-
}
|
|
141
|
-
#__vconsole .vc-mask {
|
|
142
|
-
overflow: hidden;
|
|
143
|
-
}
|
|
144
|
-
`,Io?.prepend(i),s===!0&&lv()<=0&&Ov(),console.log("🌵 Debug console has loaded")}},e.onerror=()=>{console.warn("🌵 Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),vl=!1,Zt=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.15.1/dist/vconsole.min.js",document.body.appendChild(e)}function JS(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("needle-console","🌵 Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+s._id+" iframe");return s.on("renderTab",function(t){const i=globalThis["needle:codegen_files"];if(!i||i.length===0)return;let n=globalThis["needle:codegen_files"][0];const o=n.indexOf("?");o>-1&&(n=n.substring(0,o));const a=location.protocol+"//"+location.host+location.pathname+"/"+n,l=encodeURIComponent(a);s.fullUrl="https://viewer.needle.tools?inspect&file="+l;var h='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(h)}),s.on("show",function(){const t=e();t&&t.src!==s.fullUrl&&(t.src=s.fullUrl)}),s.on("hide",function(){const t=e();t&&(t.src="")}),s.on("addTopBar",function(t){var i=new Array;i.push({name:"Open in new window ↗",onClick:function(n){window.open(s.fullUrl,"_blank"),Zt?.hide()}}),i.push({name:"Reload",onClick:function(n){const o=e();o&&(o.src=s.fullUrl)}}),i.push({name:"Fullscreen",onClick:function(n){const o=e();o.requestFullscreen?o.requestFullscreen():o.webkitRequestFullscreen instanceof Function&&o.webkitRequestFullscreen()}}),t(i)}),s}const Ip="padding: 10px; font-family: monospace;",r_="margin-bottom: 10px;",jo="margin-bottom: 10px; margin-top: 15px;",eC="width: 100%; border-collapse: collapse; border: 1px solid rgba(0,0,0,0.1); table-layout: fixed;",Mv="border: 1px solid rgba(0,0,0,0.1); padding: 5px;",tC=Mv,iC=Mv+" word-break: break-all;";function Rn(s,e=!1){e&&s.sort((i,n)=>(n.value?1:0)-(i.value?1:0));let t=`<table style='${eC}'>`;t+="<tbody>";for(const i of s){const n=typeof i.value=="boolean"?i.value?"✅":"❌":i.value;t+=`<tr><td style='${tC}'>${i.label}</td><td style='${iC}'>${n}</td></tr>`}return t+="</tbody></table>",t}function kv(){try{if(document.createElement("canvas").getContext("webgl2"))return"✅"}catch{}return"❌"}function nC(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("device-utilities","📱 Device Info");return s.on("renderTab",function(e){let t=`<div style='${Ip}'>`;const i=fC();t+=`<h3 style='${r_}'>Device: ${i}</h3>`,t+=Rn([{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+=Rn(n,!1)),t+="</div>",t+=`<div style='${Ip} margin-top: 20px;'>`,t+=`<h3 style='${r_}'>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:kv()}];t+=Rn(l,!1),t+="</div>",e(t)}),s}function sC(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("graphics-info","🎨 Graphics Info");return s.on("renderTab",async function(e){let t=`<div style='${Ip}'>`;const i=oC();i.length>0&&(t+=`<h3 style='${jo}'>General GPU Info</h3>`,t+=Rn(i,!1));const n=aC();n.length>0&&(t+=`<h3 style='${jo}'>WebGL</h3>`,t+=Rn(n,!1));const o=lC();o.length>0&&(t+=`<h3 style='${jo}'>WebGL 2 Features</h3>`,t+=Rn(o,!1));const r=cC();r.length>0&&(t+=`<h3 style='${jo}'>WebGL Limits</h3>`,t+=Rn(r,!1));const a=hC();a.length>0&&(t+=`<h3 style='${jo}'>Texture Formats</h3>`,t+=Rn(a,!1));const l=await dC();if(l.length>0&&(t+=`<h3 style='${jo}'>WebGPU</h3>`,t+=Rn(l,!1)),exports.DeviceUtilities.isSafari()){const h=uC();h.length>0&&(t+=`<h3 style='${jo}'>Safari GPU Info</h3>`,t+=Rn(h,!1))}t+="</div>",e(t)}),s}function oC(){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=Rv();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=rC(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 rC(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 aC(){const s=[],e=Rv();return e&&(s.push({label:"📊 WebGL Version",value:e.version}),s.push({label:"🎮 WebGL 2 Available",value:kv()})),s}function lC(){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 cC(){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 hC(){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 dC(){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 Rv(){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 uC(){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 fC(){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 pC(){const s=document.querySelector("#__vconsole .vc-switch");return s||null}function mC(){const s=document.querySelector("#__vconsole");return s||null}const Ev=x("debugdefines");yo('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";');yo('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";');yo('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";');yo('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";');yo('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.17.0-alpha.6";');yo('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');yo('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Wed Mar 25 2026 15:23:51 GMT+0000 (Coordinated Universal Time)";');yo('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const ii="4.17.0-alpha.6",Ea="undefined",mc="Wed Mar 25 2026 15:23:51 GMT+0000 (Coordinated Universal Time)";Ev&&console.log(`Engine version: ${ii} (generator: ${Ea})
|
|
145
|
-
Project built at ${mc}`);const no=NEEDLE_PUBLIC_KEY,jn="needle_isActiveInHierarchy",qo="builtin_components",Jl="needle_editor_guid";function yo(s){try{(0,eval)(s)}catch(e){Ev&&console.error(e)}}let Tv,a_=null;function un(){return Tv}function Vm(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}a_!==s&&(a_=s,Tv=new s)}function gC(s,e){if(typeof window!==void 0&&window.SPECTOR){console.log(window.SPECTOR);const t=new URLSearchParams(window.location.search);if(t.has("spector")){let i=function(){if(n>s.time.frame)return window.requestAnimationFrame(()=>i());const r=o.captureCanvas(e);r&&r instanceof Promise?r.then(()=>o.displayUI()):o.displayUI()};const n=Number.parseInt(t.get("spector")||"0")||0;console.log("Scheduled Spector capture at frame #"+n);const o=new window.SPECTOR.Spector;o.spyCanvases=!0,i();return}else A()&&console.debug("Spector available: Add '?spector=<frame>' to the URL to enable it and capture a frame.")}}function Av(s){const e=s;return!!(e.parser&&e.parser.json)}var du=(s=>(s[s.None=0]="None",s[s.DontExport=1]="DontExport",s))(du||{});const Dv=Symbol("component-name");function $m(s){return s&&s.isComponent}const yC=Symbol("object"),Mf=new _i(()=>new c.Vector3,20);class Lv{_point;_normal;_tangentVelocity;distance;impulse;friction;get point(){return Mf.get().set(this._point.x,this._point.y,this._point.z)}get normal(){return Mf.get().set(this._normal.x,this._normal.y,this._normal.z)}get tangentVelocity(){return Mf.get().set(this._tangentVelocity.x,this._tangentVelocity.y,this._tangentVelocity.z)}constructor(e,t,i,n,o,r){this._point=e,this.distance=t,this._normal=i,this.impulse=n,this.friction=o,this._tangentVelocity=r}}class Iv{contacts;constructor(e,t,i){this.me=e,this._collider=t,this._gameObject=t.gameObject,this.contacts=i}me;_collider;get collider(){return this._collider}_gameObject;get gameObject(){return this._gameObject}get rigidBody(){return this.collider?.attachedRigidbody}}class jv{object;collider;constructor(e,t){this.object=e,this.collider=t}}class Fd{constructor(e){this.context=e,this.root.style.cssText=`
|
|
146
|
-
position: absolute;
|
|
147
|
-
width: 1px; height: 1px;
|
|
148
|
-
padding: 0; margin: -1px;
|
|
149
|
-
overflow: hidden;
|
|
150
|
-
clip: rect(0, 0, 0, 0);
|
|
151
|
-
white-space: nowrap;
|
|
152
|
-
border: 0;
|
|
153
|
-
`,this.root.setAttribute("role","region"),this.root.setAttribute("aria-label","3D Needle Engine scene"),this.liveRegion.setAttribute("aria-live","polite"),this.liveRegion.setAttribute("aria-atomic","true"),this.liveRegion.setAttribute("role","status"),this.root.appendChild(this.liveRegion),this.enabled=!0}static _managers=new WeakMap;static get(e){return $m(e)?this._managers.get(e.context):this._managers.get(e)}_enabled;set enabled(e){e!==this._enabled&&(this._enabled=e,e?(Fd._managers.set(this.context,this),(this.context.domElement.shadowRoot||this.context.domElement).prepend(this.root)):this.root.remove())}clear(){this.root.childNodes.forEach(e=>e.remove()),this.root.appendChild(this.liveRegion)}dispose(){this.root.remove(),Fd._managers.delete(this.context)}root=document.createElement("div");liveRegion=document.createElement("div");treeElements=new WeakMap;updateElement(e,t){let i=this.treeElements.get(e);i||(i=document.createElement("div"),this.treeElements.set(e,i),this.root.appendChild(i),typeof t=="object"&&(t.role&&i.setAttribute("role",t.role),t.label&&i.setAttribute("aria-label",t.label),t.hidden!==void 0&&i.setAttribute("aria-hidden",String(t.hidden)),t.busy!==void 0&&i.setAttribute("aria-busy",String(t.busy))))}focus(e){const t=this.treeElements.get(e);t&&t.focus()}unfocus(e){const t=this.treeElements.get(e);t&&t.blur()}hover(e,t){const i=this.treeElements.get(e);this.liveRegion.textContent=t||i?.getAttribute("aria-label")||""}removeElement(e){this.treeElements.get(e)?.remove(),this.treeElements.delete(e)}set liveRegionMode(e){this.liveRegion.setAttribute("aria-live",e)}}const pi=Symbol("shadowDomOwner"),_C=x("debugpatch");function uu(s,e,t,i){const n=_C===e;if(!t&&!i)return;const o=e+"___needle";vC(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]=c_(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]=c_(l,s,e);else{const h=this[o];Bv(s,e,this,h,l),this[o]=l,Fv(s,e,this,h,l)}},get:function(){const l=this[o];return typeof l=="function"&&l[o]?l[o]:l}}))}function bC(s,e,t){const i=Wm(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 l_=Symbol("Needle:Patches:WrappedFunction");function c_(s,e,t){if(s[l_])return s;const i=function(...n){Bv(e,t,this,...n);const o=s.apply(this,n);return Fv(e,t,this,o,...n),o};return i[l_]=!0,i}const fd="Needle:Patches";function jp(){return globalThis[fd]||(globalThis[fd]=new WeakMap),globalThis[fd]}function Wm(s,e){const t=jp().get(s);return t?t.get(e):null}function vC(s,e,t,i){let n=jp().get(s);n||(n=new Map,jp().set(s,n));let o=n.get(e);o||(o=[],n.set(e,o)),o.push({prefix:t,postfix:i})}function Bv(s,e,t,...i){if(!t)return;const n=Wm(s,e);if(n)for(const o of n)o.prefix?.call(t,...i)}function Fv(s,e,t,i,...n){if(!t)return;const o=Wm(s,e);if(o)for(const r of o)r.postfix?.call(t,i,...n)}const Ta=[];function fu(s){Ta.indexOf(s)===-1&&Ta.push(s)}function wC(s){const e=Ta.indexOf(s);e!==-1&&Ta.splice(e,1)}const Aa=[];function Gm(s){Aa.indexOf(s)===-1&&Aa.push(s)}function xC(s){const e=Aa.indexOf(s);e!==-1&&Aa.splice(e,1)}function Uv(s){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-start",{detail:s}));for(let e=0;e<Ta.length;e++)Ta[e](s)}function zv(s){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-end",{detail:s}));for(let e=0;e<Aa.length;e++)Aa[e](s)}const ze=x("debuginput");var pu=(s=>(s.Mouse="mouse",s.Touch="touch",s.Controller="controller",s.Hand="hand",s))(pu||{}),Pe=(s=>(s.PointerDown="pointerdown",s.PointerUp="pointerup",s.PointerMove="pointermove",s.KeyDown="keydown",s.KeyUp="keyup",s.KeyPressed="keypress",s))(Pe||{});class ss 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(),ze&&console.warn("Stop propagation...",this.pointerId,this.pointerType)}}class Bl extends KeyboardEvent{source;constructor(e,t,i){super(e,i),this.source=t}stopImmediatePropagation(){super.stopImmediatePropagation(),this.source?.stopImmediatePropagation()}}class SC{key;keyType;source;constructor(e){this.key=e.key,this.keyType=e.type,this.source=e}}var ti=(s=>(s[s.Early=-100]="Early",s[s.Default=0]="Default",s[s.Late=100]="Late",s))(ti||{});class Nv{_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 Bl){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 ss){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,ze&&console.log("immediatePropagationStopped",e.type);break}else e.propagationStopped&&(t=!0,ze&&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":ze&&Se("Create Pointer down"),this.onDownButton(e.deviceIndex,e.button),this.onDown(e);break;case"pointermove":ze&&Se("Create Pointer move"),this.onMove(e);break;case"pointerup":ze&&Se("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:(ze&&console.warn("CanReceiveInput:False for",e.target),!1)}onContextMenu=e=>{this.canReceiveInput(e)};keysPressed={};onKeyDown=e=>{if(ze&&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 Bl("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 Bl("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 Bl("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);ze&&Se(`pointer down #${t}, identifier:${e.pointerId}`);const i=this.getAndUpdateSpatialObjectForScreenPosition(t,e.clientX,e.clientY),n=new ss("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 ss("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||(ze&&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 ss("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,ze&&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 ss("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 ss("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 ss("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||F(0,1,0).applyQuaternion(pe(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 ze&&!o&&console.log("Not in rect",t,i,n),o}onDown(e){const t=e.pointerId;if(this.getPointerPressed(t)){ze&&console.warn(`Received pointerDown event for pointerId that is already pressed: ${t}/${e.button}`,ze?e:"");return}if(ze&&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)){ze&&console.warn(`Received pointerUp for pointerId that is not pressed: ${t}/${e.button}`,ze?e:"");return}ze&&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]){ze&&fe("[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;ze&&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):(ze&&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 va=new c.Matrix4().makeRotationY(Math.PI),Li=new c.Quaternion().setFromAxisAngle(new c.Vector3(0,1,0),Math.PI),CC=x("debugwebxr");class PC{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",CC){const e=Zm(16733661);e.position.y+=.5,this.gameObject.add(e)}}}const Jn=x("debugwebxr"),Ah=x("debugcustomgesture"),OC="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",MC="generic-trigger",kC=new c.Quaternion().setFromEuler(new c.Euler(c.MathUtils.degToRad(0),c.MathUtils.degToRad(-90),c.MathUtils.degToRad(-90))),RC=new c.Vector3(.04,-.04,0);class Hm{xr;get context(){return this.xr.context}inputSource;index=0;emitEvents=!0;get connected(){return this._connected}_connected=!0;get isTracking(){return this._isTracking}_isTracking=!1;get gamepad(){return this.__gamepad??=this.inputSource.gamepad}__gamepad;get isHand(){return this.hand!=null}get hand(){return this.__hand??=this.inputSource.hand}__hand;get handObject(){return this.context.renderer.xr.getHand(this.index)}get profiles(){return this.inputSource.profiles}get layout(){return this._layout}get targetRayMode(){return this.inputSource.targetRayMode}get targetRaySpace(){return this.inputSource.targetRaySpace}get gripSpace(){return this.inputSource.gripSpace}get side(){return this.__side??=this.inputSource.handedness}__side=void 0;get isRight(){return this.side==="right"}get isLeft(){return this.side==="left"}get isStylus(){return this._isMxInk}getHitTestSource(){return this._hitTestSource||this._requestHitTestSource(),this._hitTestSource}get hasHitTestSource(){return this._hitTestSource}cancelHitTestSource(){this._hitTestSource&&(this._hitTestSource.cancel(),this._hitTestSource=void 0)}_hitTestSource=void 0;_hasSelectEvent=!1;get hasSelectEvent(){return this._hasSelectEvent}_isMxInk=!1;_isMetaQuestTouchController=!1;getHitTest(){return this.xr.getHitTest(this)}_handJointPoses=new Map;getHandJointPose(e,t){if(t=t||this.xr.frame,!this.hand||!t?.getJointPose||!this.xr.referenceSpace)return null;let i=this._handJointPoses?.get(e);return i||(i=t.getJointPose(e,this.xr.referenceSpace),i&&this._handJointPoses.set(e,i),i)}_gripMatrix=new c.Matrix4;_gripPosition=new c.Vector3;_gripQuaternion=new c.Quaternion;_linearVelocity=new c.Vector3;_rayPositionRaw=new c.Vector3;_rayRotationRaw=new c.Quaternion;_rayMatrix=new c.Matrix4;_rayPosition=new c.Vector3;_rayQuaternion=new c.Quaternion;get gripPosition(){return F(this._gripPosition)}get gripQuaternion(){return ei(this._gripQuaternion)}get gripMatrix(){return this._gripMatrix}get gripLinearVelocity(){return F(this._linearVelocity).applyQuaternion(Li)}get rayPosition(){return F(this._rayPosition)}get rayQuaternion(){return ei(this._rayQuaternion)}get gripWorldPosition(){return F(this._gripWorldPosition)}_gripWorldPosition=new c.Vector3;get gripWorldQuaternion(){return ei(this._gripWorldQuaternion)}_gripWorldQuaternion=new c.Quaternion;get rayWorldPosition(){return F(this._rayWorldPosition)}_rayWorldPosition=new c.Vector3;updateRayWorldPosition(){const e=this.xr.context.mainCamera?.parent;this._rayWorldPosition.copy(this._rayPositionRaw),e&&this._rayWorldPosition.applyMatrix4(e.matrixWorld)}get rayWorldQuaternion(){return ei(this._rayWorldQuaternion)}_rayWorldQuaternion=new c.Quaternion;get pinchPosition(){return F(this._pinchPosition)}_pinchPosition=new c.Vector3;updateRayWorldQuaternion(){const e=this.xr.context.mainCamera?.parent,t=e?pe(e):void 0;this._rayWorldQuaternion.copy(this._rayRotationRaw).multiply(Li),t&&this._rayWorldQuaternion.premultiply(t)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy(F(0,0,1).applyQuaternion(this.rayWorldQuaternion)),this._ray}_ray;_hand_wristDotUp=void 0;get handWristDotUp(){if(this._hand_wristDotUp!==void 0)return this._hand_wristDotUp;const e=this.handObject?.joints.wrist;if(e){const t=F(0,1,0).applyQuaternion(e.quaternion),i=F(0,1,0).dot(t);return this._hand_wristDotUp=i}}get isHandUpsideDown(){return this.handWristDotUp!==void 0?this.handWristDotUp<-.7:!1}get isTeleportGesture(){return this.isHandUpsideDown&&this.getGesture("pinch")?.isDown}get object(){return this._object}_object;_gripSpaceObject;_raySpaceObject;model=null;_debugAxesHelper=new c.AxesHelper(.15);_debugGripAxesHelper=new c.AxesHelper(.07);_debugRayAxesHelper=new c.AxesHelper(.07);async getModelUrl(){return this.getMotionController?.then(e=>e?.assetUrl||null)}constructor(e,t,i){this.xr=e,this.inputSource=t,this.index=i,this._object=new c.Object3D,this._object.name=`NeedleXRController_${i}`,Jn&&(this._object.add(this._debugAxesHelper),this._gripSpaceObject=new c.Object3D,this._raySpaceObject=new c.Object3D,this._gripSpaceObject.name=`NeedleXRController_${i}_gripSpace`,this._raySpaceObject.name=`NeedleXRController_${i}_raySpace`,this._gripSpaceObject.add(this._debugGripAxesHelper),this._raySpaceObject.add(this._debugRayAxesHelper),this.xr.context.scene.add(this._gripSpaceObject),this.xr.context.scene.add(this._raySpaceObject)),this.xr.context.scene.add(this._object),this._ray=new c.Ray,this.pointerInit={origin:this,pointerType:this.hand?"hand":"controller",deviceIndex:this.index,pointerId:-1,mode:this.inputSource.targetRayMode,ray:this._ray,device:this._object,buttonName:"none"},this.initialize(),this.subscribeEvents()}_hitTestSourcePromise=null;_requestHitTestSource(){return this._hitTestSourcePromise?this._hitTestSourcePromise:this.xr.mode==="immersive-ar"&&this.inputSource.targetRayMode==="tracked-pointer"&&this.xr.session.requestHitTestSourceForTransientInput?this._hitTestSourcePromise=this.xr.session.requestHitTestSourceForTransientInput({profile:this.inputSource.profiles[0],offsetRay:new XRRay})?.then(e=>(this._hitTestSourcePromise=null,this.connected?this._hitTestSource=e:(e.cancel(),null)))??null:null}onPointerHits=e=>{};onUpdate(e){this.onUpdateFrame(e),this.updateInputEvents(),this.onUpdateMove()}onRenderDebug(){B.DrawSphere(this.rayWorldPosition,.003),B.DrawDirection(this.rayWorldPosition,F(0,0,10).applyQuaternion(this.rayWorldQuaternion));const t=(this.inputSource.gripSpace?this.gripWorldPosition:this.object.worldPosition).sub(this.object.worldForward.multiplyScalar(.1)),i=this.inputSource.profiles.join(`
|
|
154
|
-
`);let n=`Controller[${this.index}] (${this.inputSource.targetRayMode}, ${this.side})
|
|
155
|
-
C:${this.connected?"x":"-"} T:${this.isTracking?"x":"-"} Hand:${this.inputSource.hand?"x":"-"} Pen: ${this._isMxInk?"x":"-"}`;if(this.inputSource.hand&&(n+=`
|
|
156
|
-
Pinch: ${this.getGesture("pinch")?.value.toFixed(3)}`),n+=`
|
|
157
|
-
`+i,n+=`
|
|
158
|
-
`+(this.inputSource.targetRaySpace?"Ray: x":"Ray: -")+(this.inputSource.gripSpace?" Grip: x":" Grip: -")+(this.inputSource.gamepad?` Gamepad: ${this.inputSource.gamepad.mapping}`:" Gamepad: -"),this.inputSource.gamepad){const o=this.inputSource.gamepad;let r="[btns "+o.buttons.length+"]: "+o.buttons.map(a=>a.value.toPrecision(1)).join(",");r+=`
|
|
159
|
-
[axes `+o.axes.length+"]: "+o.axes.map(a=>a.toPrecision(1)).join(","),n+=`
|
|
160
|
-
`+r}if(this._layout){n+=`
|
|
161
|
-
Layout: `;for(const o of Object.keys(this._layout.components||{})){const r=this.getStick(o),a=this._layout.components[o]?.gamepadIndices,l=a?Object.entries(a).map(h=>h[0][0].toUpperCase()+h[0].slice(1)+"="+h[1]).join(","):"";n+=`
|
|
162
|
-
${o}: ${this._layout.components[o]?.type} [${l}] (${r.x.toPrecision(2)},${r.y.toPrecision(2)})`}}B.DrawLabel(t,n,.006)}onUpdateFrame(e){if(this._handJointPoses.clear(),this._hand_wristDotUp=void 0,!this.xr.referenceSpace||!this.inputSource.gamepad?.connected){this._isTracking=!1;return}const t=e.getPose(this.inputSource.targetRaySpace,this.xr.referenceSpace);this._isTracking=t!=null;let i=null,n=null,o=null,r=null;if(t){const d=t.transform;this._rayMatrix.fromArray(d.matrix).premultiply(va),this._rayMatrix.decompose(this._rayPosition,this._rayQuaternion,F(1,1,1)),o=F(d.position),r=ei(d.orientation),this._rayPositionRaw.copy(o),this._rayRotationRaw.copy(r)}if(this.inputSource.gripSpace){const d=e.getPose(this.inputSource.gripSpace,this.xr.referenceSpace);if(d){const u=d.transform;if(i=F(u.position),n=ei(u.orientation),this._gripMatrix.fromArray(u.matrix).premultiply(va),this._gripMatrix.decompose(this._gripPosition,this._gripQuaternion,F(1,1,1)),"linearVelocity"in d&&d.linearVelocity){const p=d.linearVelocity;this._linearVelocity.set(p.x,p.y,p.z)}}}this.xr.context.mainCamera?.parent&&(this._object.parent!==this.xr.context.mainCamera?.parent&&this.xr.context.mainCamera.parent.add(this._object),this._gripSpaceObject!==void 0&&this._gripSpaceObject?.parent!==this.xr.context.mainCamera?.parent&&this.xr.context.mainCamera.parent.add(this._gripSpaceObject),this._raySpaceObject!==void 0&&this._raySpaceObject?.parent!==this.xr.context.mainCamera?.parent&&this.xr.context.mainCamera.parent.add(this._raySpaceObject));const a=this.hand;if(a){let d=!1;const u=a.get("wrist"),p=u&&this.getHandJointPose(u,e);if(p){d=!0;const _=p.transform.position,g=p.transform.orientation;this._object.position.set(_.x,_.y,_.z),this._object.quaternion.set(g.x,g.y,g.z,g.w).multiply(Li)}d||(this._object.position.copy(this._rayPosition),this._object.quaternion.copy(this._rayQuaternion).multiply(Li));const m=a.get("middle-finger-metacarpal"),y=m&&this.getHandJointPose(m,e);y&&(this._gripMatrix.fromArray(y.transform.matrix).premultiply(va),this._gripMatrix.decompose(this._gripPosition,this._gripQuaternion,F(1,1,1)),i=F().copy(y.transform.position),n=ei().copy(y.transform.orientation),n.multiply(kC),i.add(F(RC).applyQuaternion(n)))}else this.inputSource.gripSpace&&this.targetRayMode==="transient-pointer"&&i&&n?(this._object.position.copy(i),this._object.quaternion.copy(n).multiply(Li)):o&&r&&(this._object.position.copy(o),this._object.quaternion.copy(r).multiply(Li));Jn&&(o&&r&&(this._raySpaceObject?.position.copy(o),this._raySpaceObject?.quaternion.copy(r).multiply(Li)),i&&n&&(this._gripSpaceObject?.position.copy(i),this._gripSpaceObject?.quaternion.copy(n).multiply(Li)));const l=this.xr.context.mainCamera?.parent,h=l?pe(l):void 0;i&&n&&(this._gripWorldPosition.copy(i),l&&this._gripWorldPosition.applyMatrix4(l.matrixWorld),this._gripWorldQuaternion.copy(n),this._gripWorldQuaternion.multiply(Li),h&&this._gripWorldQuaternion.premultiply(h)),this.updateRayWorldPosition(),this.updateRayWorldQuaternion()}onDisconnected(){this._connected=!1,Jn&&console.warn("Controller disconnected",this.index);for(const e of this._object.children)this.xr.context.scene.attach(e);this._object?.removeFromParent(),this._debugAxesHelper?.removeFromParent(),this._debugGripAxesHelper?.removeFromParent(),this._debugRayAxesHelper?.removeFromParent(),this._gripSpaceObject?.removeFromParent(),this._raySpaceObject?.removeFromParent(),this.unsubscribeEvents(),this._hitTestSource&&(this._hitTestSource.cancel(),this._hitTestSource=void 0)}getButton(e){if(!this._layout)return;switch(e){case"primary-button":if(this.isLeft)e="x-button";else if(this.isRight)e="a-button";else return;break;case"primary":return this.hand?this.getGesture("pinch"):this.toNeedleGamepadButton(0,e);case"xr-standard-trigger":if(this.inputSource.gamepad)return this.toNeedleGamepadButton(0,e);break;case"xr-standard-squeeze":if(this.inputSource.gamepad)return this.toNeedleGamepadButton(1,e);break;case"xr-standard-thumbstick":if(this.inputSource.gamepad)return this.toNeedleGamepadButton(3,e);break}if(this._buttonMap.has(e))return this.toNeedleGamepadButton(this._buttonMap.get(e),e);const t=this._layout?.components[e];if(t?.gamepadIndices)switch(t.type){case"button":case"squeeze":if(this.inputSource.gamepad){const i=t.gamepadIndices.button;return this._buttonMap.set(e,i),this.toNeedleGamepadButton(i,e)}break;default:console.warn("Unsupported component type",t.type);break}this._buttonMap.set(e,void 0)}getGesture(e){const t=this.states[e];if(!t)return null;this.states[e]=t;const i=this._needleGamepadButtons[e]||new d_(void 0,e);return i.pressed=t.pressed,i.value=t.value,i.isDown=t.isDown,i.isUp=t.isUp,this._needleGamepadButtons[e]=i,i}getPointerId(e){if((e==="primary"||e==="pinch")&&(e=0),typeof e!="number"){const t=this._buttonMap.get(e);if(t===void 0)return;e=t}return this.index*10+e}_needleGamepadButtons={};toNeedleGamepadButton(e,t){if(!this.inputSource.gamepad?.buttons)return;const i=this.inputSource.gamepad?.buttons[e],n=this.states[e],o=this._needleGamepadButtons[e]||new d_(e,t);return i&&(o.pressed=i.pressed,o.value=i.value,o.touched=i.touched),n&&(o.isDown=n.isDown,o.isUp=n.isUp),this._needleGamepadButtons[e]=o,o}getStick(e){if(!this._layout)return{x:0,y:0,z:0};if(this.isHand)return{x:0,y:0,z:0};e==="primary"&&this._layout.components["xr-standard-thumbstick"]&&(e="xr-standard-thumbstick");const t=this._layout?.components[e];if(t?.gamepadIndices)switch(t.type){case"thumbstick":case"touchpad":if(this.inputSource.gamepad){const i=t.gamepadIndices.xAxis,n=t.gamepadIndices.yAxis;let o=this.inputSource.gamepad.axes[i]||0,r=this.inputSource.gamepad.axes[n]||0;o*=-1,r*=-1;const a=t.gamepadIndices.button,l=this.inputSource.gamepad?.buttons[a]?.value||0;return{x:o,y:r,z:l}}}return{x:0,y:0,z:0}}_buttonMap=new Map;_motioncontroller;_layout;getMotionController;initialize(){if(this._hasSelectEvent=this.profiles.includes("generic-hand-select")||this.profiles.some(e=>e.startsWith("generic-trigger")),this._isMetaQuestTouchController=this.profiles.includes("meta-quest-touch-plus")||this.profiles.includes("oculus-touch-v3"),this._isMxInk=this.profiles.includes("logitech-mx-ink"),!this._layout){if(this.inputSource.targetRayMode==="transient-pointer")return;const e=ae.fetchProfile(this.inputSource,OC,MC);this.getMotionController=e.then(t=>{if(!this.connected)return null;this._motioncontroller=new ae.MotionController(this.inputSource,t.profile,t.assetPath||"");const n=t.profile.layouts[this.inputSource.handedness];if(this._layout=n,this._layout){if(!this._layout.gamepad?.length){this._layout.gamepad=[];for(const o in this._layout.components){const r=this._layout.components[o];this._layout.gamepad[r.gamepadIndices.button]=o}}this.profiles.length>=1&&this.profiles[0]==="htc-vive-focus-plus"&&this.inputSource.gamepad&&this.inputSource.gamepad.axes.length===4&&!this._layout.components["xr-standard-thumbstick"]&&(this._layout.components["xr-standard-thumbstick"]={type:"thumbstick",gamepadIndices:{xAxis:2,yAxis:3}})}return this._motioncontroller}).catch(t=>(this.inputSource&&console.warn("Couldn't initialize motion controller profile for ",this.inputSource,t),null))}}emitPointerDownEvent=!0;emitPointerUpEvent=!0;emitPointerMoveEvent=!0;pointerMoveDistanceThreshold=.03;pointerMoveAngleThreshold=.05;subscribeEvents(){this.xr.session.addEventListener("selectstart",this.onSelectStart),this.xr.session.addEventListener("selectend",this.onSelectEnd),this.xr.session.addEventListener("squeezestart",this.onSequeezeStart),this.xr.session.addEventListener("squeezeend",this.onSequeezeEnd)}unsubscribeEvents(){this.xr.session.removeEventListener("selectstart",this.onSelectStart),this.xr.session.removeEventListener("selectend",this.onSelectEnd),this.xr.session.removeEventListener("squeezestart",this.onSequeezeStart),this.xr.session.removeEventListener("squeezeend",this.onSequeezeEnd)}_selectButtonIndex=void 0;_squeezeButtonIndex=void 0;onSelectStart=e=>{if(!this.emitPointerDownEvent||this.inputSource!==e.inputSource)return;this.onUpdateFrame(e.frame),this._hasSelectEvent=!0;const t=this._layout?.selectComponentId,i=this._layout?.components[t]?.gamepadIndices?.button;i!==void 0&&(this._selectButtonIndex=i),!Ah&&(Jn&&B.DrawDirection(this.rayWorldPosition,F(0,.01,1).applyQuaternion(this.rayWorldQuaternion),16711680,10),this.emitPointerEvent(Pe.PointerDown,this._selectButtonIndex||0,"xr-standard-trigger",!0,e))};onSelectEnd=e=>{this.emitPointerUpEvent&&(Ah||this.inputSource===e.inputSource&&this.emitPointerEvent(Pe.PointerUp,this._selectButtonIndex||0,"xr-standard-trigger",!0,e))};onSequeezeStart=e=>{this.emitPointerDownEvent&&this.inputSource===e.inputSource&&(this._squeezeButtonIndex=this._layout?.components["xr-standard-squeeze"]?.gamepadIndices?.button,this._squeezeButtonIndex!==void 0&&(Jn&&B.DrawDirection(this.rayWorldPosition,F(0,.01,1).applyQuaternion(this.rayWorldQuaternion),255,10),this.emitPointerEvent(Pe.PointerDown,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,e)))};onSequeezeEnd=e=>{this.emitPointerUpEvent&&this.inputSource===e.inputSource&&this._squeezeButtonIndex!==void 0&&this.emitPointerEvent(Pe.PointerUp,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,e)};states={};updateInputEvents(){if(this.gamepad?.buttons){for(let e=0;e<this.gamepad.buttons.length;e++){const t=this.gamepad.buttons[e],i=this.states[e]||new h_;let n=null;this._isMxInk&&(e===4||e===5)?(t.value>0&&!i.pressed?(n="pointerdown",i.isDown=!0,i.isUp=!1):t.value===0&&i.pressed?(n="pointerup",i.isDown=!1,i.isUp=!0):i.pressed&&(n="pointermove",i.isDown=!1,i.isUp=!1),i.pressed=t.value>0,i.value=t.value):(t.pressed&&!i.pressed?(n="pointerdown",i.isDown=!0,i.isUp=!1):!t.pressed&&i.pressed?(n="pointerup",i.isDown=!1,i.isUp=!0):(i.isDown=!1,i.isUp=!1),i.pressed=t.pressed,i.value=t.value),this.states[e]=i;const o=e!==this._selectButtonIndex&&e!==this._squeezeButtonIndex;if(n!=null&&o){let r=this._layout?.gamepad[e];this._isMxInk&&e===4&&(r="stylus-touch"),this._isMxInk&&e===5&&(r="stylus-tip"),(Jn||Ah)&&console.log("Emitting pointer event",n,e,r,t.value,this.gamepad,this._layout),this.emitPointerEvent(n,e,r??"none",!1,null,t.value)}}if(this._isMetaQuestTouchController){const e=this.gamepad.buttons.length-1,t=this.states[e];if(t&&t.isDown){const i=this.context.menu;i.spatialMenuIsVisible?i.setSpatialMenuVisible(!1):this.context.menu.setSpatialMenuVisible(!0)}}}if(this.hand){const e=this.handObject;if(e){const t=e.joints["index-finger-tip"],i=e.joints["thumb-tip"];if(t&&i){const n=t.position.distanceTo(i.position);this._pinchPosition.lerpVectors(t.position,i.position,.5);const o=this.xr.context.mainCamera?.parent;if(o&&this._pinchPosition.applyMatrix4(o.matrixWorld),n!==0){const l=this.states.pinch||new h_,h=(.02+.01)*1.5;l.value=1-(n-.02)/h;const d=n<.02-.01,u=n>.02+.01;d&&!l.pressed?(Ah&&console.log("pinch start",n),l.isDown=!0,l.isUp=!1,l.pressed=!0):u&&l.pressed?(l.isDown=!1,l.isUp=!0,l.pressed=!1):(l.isDown=!1,l.isUp=!1),this.states.pinch=l}}}}}_didMoveLastFrame=!1;_lastPointerMovePosition=new c.Vector3;_lastPointerMoveQuaternion=new c.Quaternion;onUpdateMove(){if(!this.emitPointerMoveEvent)return;let e=!1;if(this._lastPointerMovePosition.distanceTo(this.gripWorldPosition)>this.pointerMoveDistanceThreshold*this.xr.rigScale&&(e=!0),e||this._lastPointerMoveQuaternion.angleTo(this.gripWorldQuaternion)>this.pointerMoveAngleThreshold&&(e=!0),e){this._didMoveLastFrame=!0,this._lastPointerMovePosition.copy(this.gripWorldPosition),this._lastPointerMoveQuaternion.copy(this.gripWorldQuaternion),Jn&&B.DrawLabel(this.rayWorldPosition.add(this.object.worldForward.multiplyScalar(.1)),"move",.01);let i=this.xr.context.input.getFirstPressedButtonForPointer(this.index);i===void 0&&(i=0);const n=this.gamepad?.buttons[i]?.value;this.emitPointerEvent("pointermove",i,"none",!1,null,n)}else this._didMoveLastFrame=!1}pointerInit;emitPointerEvent(e,t,i,n,o=null,r){if(!this.emitEvents){Jn&&e!==Pe.PointerMove&&console.warn("Pointer events are disabled for this controller",this.index,e,t);return}if(this.xr.mode==="immersive-vr"||this.xr.isPassThrough){this.pointerInit.origin=this,this.pointerInit.pointerId=this.getPointerId(t),this.pointerInit.pointerType=this.hand?"hand":"controller",this.pointerInit.button=t,this.pointerInit.buttonName=i,this.pointerInit.isPrimary=n,this.pointerInit.mode=this.inputSource.targetRayMode,this.pointerInit.ray=this.ray,this.pointerInit.device=this.object,this.pointerInit.pressure=r,this.pointerInit.clientX=this._rayPosition.x/this.xr.rigScale,this.pointerInit.clientY=this._rayPosition.y/this.xr.rigScale,this.pointerInit.clientZ=this._rayPosition.z/this.xr.rigScale;const a=U.Current;U.Current=this.xr.context,Jn&&e!=="pointermove"&&console.warn("Pointer event",e,t,i,{...this.pointerInit}),this.xr.context.input.createInputEvent(new ss(e,o,this.pointerInit)),U.Current=a}}}class h_{isDown=!1;isUp=!1;pressed=!1;value=0}class d_{index;name;touched=!1;pressed=!1;value=0;isDown=!1;isUp=!1;constructor(e,t){this.index=e,this.name=t}}var Bp=(s=>(s.Visible="application-visible",s.Hidden="application-hidden",s.MuteChanged="application-mutechanged",s))(Bp||{});let gc=!1;const Ko=[];function vr(){if(gc)return;A()&&console.debug("[Needle Engine] User input registered: Media playback is now allowed."),gc=!0;const s=[...Ko];Ko.length=0,s.forEach(e=>e())}document.addEventListener("mousedown",vr);document.addEventListener("pointerup",vr);document.addEventListener("click",vr);document.addEventListener("dragstart",vr);document.addEventListener("touchend",vr);document.addEventListener("keydown",vr);typeof window<"u"&&"userActivation"in navigator&&navigator.userActivation?.isActive&&(A()&&console.debug("[Needle Engine] User input already active: Media playback is now allowed."),Ko.length=0,gc=!0);class fn extends EventTarget{static get userInteractionRegistered(){return gc}static registerWaitForAllowAudio=fn.registerWaitForInteraction;static registerWaitForInteraction(e){if(e!==null){if(gc){e();return}Ko.indexOf(e)===-1&&Ko.push(e)}}static unregisterWaitForInteraction(e){const t=Ko.indexOf(e);t!==-1&&Ko.splice(t,1)}_mute=!1;get muted(){return this._mute}set muted(e){e!==this._mute&&(this._mute=e,this.dispatchEvent(new Event("application-mutechanged")))}context;get hasFocus(){return document.hasFocus()}get isVisible(){return this._isVisible}_isVisible=!0;constructor(e){super(),this.context=e,window.addEventListener("visibilitychange",this.onVisiblityChanged.bind(this),!1)}onVisiblityChanged(e){switch(e.target.visibilityState){case"hidden":this._isVisible=!1,this.dispatchEvent(new Event("application-hidden"));break;case"visible":this._isVisible=!0,this.dispatchEvent(new Event("application-visible"));break}}}const wa=new Map,da=new Map;let u_=0;function xs(s,e,t){if(wa.has(e)||wa.set(e,new Array),wa.get(e).push({method:s,options:{once:!1,...t}}),u_<30){const i=da.get(e);i&&i?.length>100&&(u_+=1,console.warn(`You have ${i.length} methods registered for Event ${e}.
|
|
163
|
-
|
|
164
|
-
This might be a performance issue!
|
|
165
|
-
Consider unregistering the methods when they are not needed anymore!
|
|
166
|
-
|
|
167
|
-
To unregister you can call the function returned by your event hook (e.g.const unregister = onStart(...))
|
|
168
|
-
|
|
169
|
-
or by using the once option like onStart(()=>{}, { once:true }).
|
|
170
|
-
|
|
171
|
-
See https://engine.needle.tools/docs/scripting.html#special-lifecycle-hooks for more information.`))}}function _o(s,e){const t=da.get(e);if(t){for(let n=0;n<t.length;n++)if(t[n].method===s){t.splice(n,1);return}}const i=wa.get(e);if(i){for(let n=0;n<i.length;n++)if(i[n].method===s){i.splice(n,1);return}}}function xn(s,e){e===le.ContextCreated&&Fp.delete(s),Vv(s,e)}function Vv(s,e){e===ge.Start&&wa.get(le.ContextCreated)&&Vv(s,le.ContextCreated);const t=e===ge.Start||e===le.ContextCreated,i=da.get(e);i&&i.length>0&&p_(s,i,t);const n=wa.get(e);if(n&&n.length>0){const o=[...n];n.length=0,p_(s,o,t),o.length>0&&(da.has(e)||da.set(e,new Array),da.get(e).push(...o))}}const Dh=new Array,f_={context:null};function p_(s,e,t){Dh.length=0;for(let n=0;n<e.length;n++)Dh.push(e[n]);let i=Fp.get(s);for(let n=0;n<Dh.length;n++){const o=Dh[n];let r=!0;if(i&&i.has(o)&&(r=!1),r)try{f_.context=s,o.method?.call(f_,s)}catch(a){console.error("Error in lifecycle method",a)}if(o.options?.once){for(let a=0;a<e.length;a++)if(e[a]===o){e.splice(a,1);break}}else t&&(i||(i=new Set,Fp.set(s,i)),i.add(o))}}const Fp=new WeakMap,qm={};function Xm(s,e){qm[s]=e}function $v(s){const e=s.getBufferIdentifier(),t=qm[e];return t(s)}function Wv(s){return typeof s.guid=="function"?s.guid():null}let Qm;function EC(){return Qm}function TC(s){Qm=s}function Gv(s,e){return e||(e={}),e={...Qm,...e},s?new ae.$70d766613f57b014$export$2e2bcd8739ae039(s,e):new ae.$70d766613f57b014$export$2e2bcd8739ae039(e)}async function m_(){const s=await Promise.resolve().then(()=>require("./vendor-CipoooTV.umd.cjs")).then(e=>e.bundler);return console.log(s),s.default===void 0?s:s.default}class Hv{get isHost(){return this._host!==void 0}_host;_client;_clientData;constructor(){this.onEnable()}onEnable(){this.trySetupHost("HOST-5980e65c-8438-453e-8b35-f13c736dcd81")}async trySetupHost(e){const t=await m_(),i=new t(e);i.on("error",n=>{console.error(n),this._host=void 0,this.trySetupClient(e)}),i.on("open",n=>{this._host=new DC(i)})}async trySetupClient(e){const t=await m_();this._client=new t,this._client.on("error",i=>{console.error("Client error",i)}),this._client.on("open",i=>{console.log("client connected",i),this._clientData=this._client.connect(e,{metadata:{id:i}}),this._clientData.on("open",()=>{console.log("Connected to host")}),this._clientData.on("data",n=>{console.log("<<",n)})})}}class AC{_peer;constructor(e){this._peer=e}}class DC extends AC{get isHost(){return!0}_connections=[];constructor(e){super(e),console.log("I AM THE HOST"),this._peer?.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("BYE")}),setInterval(()=>{this.broadcast("HELLO")},2e3)}onConnection(e){console.log("host connection",e),e.on("open",()=>{this._connections.push(e),this.broadcastConnection(e)})}broadcastConnection(e){const t=this._connections.map(i=>i.metadata?.id).filter(i=>i!==void 0);this.broadcast({type:"connection-list",connections:t})}broadcast(e){if(e!=null){console.log(">>",e);for(const t in this._peer.connections){const i=this._peer.connections[t];if(i)if(Array.isArray(i))for(const n of i)n&&n.send(e);else console.warn(i)}}}}var ln=(s=>(s[s.OnConnection=0]="OnConnection",s[s.OnRoomJoin=1]="OnRoomJoin",s[s.Queued=2]="Queued",s[s.Immediate=3]="Immediate",s))(ln||{});const g_="https://urls.needle.tools/default-networking-backend/index";let ki="wss://networking-2.needle.tools/socket";const Yt=!!x("debugnet"),Fl=!!(Yt||x("debugowner")),Lh=x("debugnetbin");var qv=(s=>(s.ConnectionInfo="connection-start-info",s))(qv||{}),K=(s=>(s.Join="join-room",s.Leave="leave-room",s.JoinedRoom="joined-room",s.LeftRoom="left-room",s.UserJoinedRoom="user-joined-room",s.UserLeftRoom="user-left-room",s.RoomStateSent="room-state-sent",s))(K||{});class LC{room;viewId;allowEditing;inRoom}class IC{room}class jC{userId}var Xv=(s=>(s.RequestHasOwner="request-has-owner",s.ResponseHasOwner="response-has-owner",s.RequestIsOwner="request-is-owner",s.ResponseIsOwner="response-is-owner",s.RequestOwnership="request-ownership",s.GainedOwnership="gained-ownership",s.RemoveOwnership="remove-ownership",s.LostOwnership="lost-ownership",s.GainedOwnershipBroadcast="gained-ownership-broadcast",s.LostOwnershipBroadcast="lost-ownership-broadcast",s))(Xv||{});class Ym{guid;connection;get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}_hasOwnership=!1;_isOwned=void 0;_gainSubscription;_lostSubscription;_hasOwnerResponse;constructor(e,t){this.connection=e,this.guid=t,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),e.beginListen("lost-ownership",this._lostSubscription),e.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),e.beginListen("response-has-owner",this._hasOwnerResponse)}_isWaitingForOwnershipResponseCallback=null;updateIsOwned(){this.connection.send("request-has-owner",{guid:this.guid})}onHasOwnerResponse(e){e.guid===this.guid&&(this._isOwned=e.value)}requestOwnershipIfNotOwned(){return this._isWaitingForOwnershipResponseCallback!==null?this:(this._isWaitingForOwnershipResponseCallback=this.waitForHasOwnershipRequestResponse.bind(this),this.connection.beginListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this.connection.send("request-has-owner",{guid:this.guid}),this)}waitForHasOwnershipRequestResponse(e){e.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=e.value,e.value||(Fl&&console.log("request ownership",this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((e,t)=>{this.requestOwnership();let i=0;const n=()=>{if(i++>10)return t("Timeout");setTimeout(()=>{this.hasOwnership?e(this):n()},100)};n()})}requestOwnership(){return Fl&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),this}freeOwnership(){return this.connection.send("remove-ownership",{guid:this.guid}),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this}destroy(){this.connection.stopListen("gained-ownership",this._gainSubscription),this.connection.stopListen("lost-ownership",this._lostSubscription),this.connection.stopListen("response-has-owner",this._hasOwnerResponse),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null)}onGainedOwnership(e){e.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===e.owner?(Fl&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(Fl&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}}class Qv{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new Hv),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return Yt}get isConnected(){return this.connected}get currentRoomName(){return this._currentRoomName}get allowEditing(){return this._currentRoomAllowEditing}get currentRoomViewId(){return this._currentRoomViewId}getViewOnlyUrl(){if(this.currentRoomViewId===null)return null;const e=new URL(window.location.href);return e.searchParams.set("view",this.currentRoomViewId),e.href}get isInRoom(){return this._isInRoom}get currentLatency(){return this._currentDelay}get currentServerUrl(){return this._ws?.url??null}sendPing(){this.send("ping",{time:this.context.time.time})}userIsInRoom(e){return this._currentInRoom.indexOf(e)!==-1}_usersInRoomCopy=[];usersInRoom(e=null){e||(e=this._usersInRoomCopy),e.length=0;for(const t of this._currentInRoom)e.push(t);return e}joinRoom(e,t=!1){return e?e.length>1024?(console.error('Room name too long, can not join: "'+e+'". Max length is 1024 characters.'),!1):(this.isInRoom&&this.currentRoomName!==e&&console.warn("Needle Engine is already connected to a networking room. Connecting to multiple rooms is not supported"),this.connect(),Yt&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},ln.OnConnection),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}leaveRoom(e=null){return e||(e=this.currentRoomName),e?(this.send("leave-room",{room:e}),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}send(e,t=null,i=ln.Queued){if(t===null&&(t={}),i===ln.Queued){this._defaultMessagesBuffer.push({key:e,value:t});return}return this.sendWithWebsocket(e,t,i)}sendDeleteRemoteState(e){this.send("delete-state",{guid:e,dontSave:!0}),delete this._state[e]}sendDeleteRemoteStateAll(){this.send("delete-all-state"),this._state={}}sendBinary(e){Lh&&console.log("<< send binary",this.context.time.frame,e.length/1024+" KB"),this._ws?.send(e)}_defaultMessagesBuffer=[];_defaultMessagesBufferArray=[];sendBufferedMessagesNow(){if(!this._ws)return;this._defaultMessagesBufferArray.length=0;const e=Object.keys(this._defaultMessagesBuffer).length;for(const i in this._defaultMessagesBuffer){const n=this._defaultMessagesBuffer[i];if(e<=1){this.sendWithWebsocket(n.key,n.value,ln.Immediate);break}const o=this.toMessage(n.key,n.value);this._defaultMessagesBufferArray.push(o)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&Yt&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;const t=JSON.stringify(this._defaultMessagesBufferArray);this._ws?.send(t)}beginListen(e,t){return this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t),t}stopListening(e,t){return this.stopListen(e,t)}stopListen(e,t){if(!t||!this._listeners[e])return;const i=this._listeners[e].indexOf(t);i>=0&&this._listeners[e].splice(i,1)}beginListenBinary(e,t){return this._listenersBinary[e]||(this._listenersBinary[e]=[]),this._listenersBinary[e].push(t),t}stopListenBinary(e,t){if(!this._listenersBinary[e])return;const i=this._listenersBinary[e].indexOf(t);i>=0&&this._listenersBinary[e].splice(i,1)}netWebSocketUrlProvider;registerProvider(e){this.netWebSocketUrlProvider=e}async connect(e){if(this.connected&&e&&e!==ki)return Promise.reject("Can not connect to different server url. Please disconnect first.");if(this.connected)return Promise.resolve(!0);e&&console.debug("Connecting to user provided url "+e);const t=e||this.netWebSocketUrlProvider?.getWebsocketUrl();return t?ki=t:tv()&&(ki="wss://"+window.location.host+"/socket"),this.connectWebsocket()}disconnect(){this._ws?.close(),this._ws=void 0,ki=void 0,this._currentRoomAllowEditing=!0,this._currentRoomName=null,this._currentRoomViewId=null,this._isInRoom=!1,this._currentInRoom.length=0,this._state={},this._currentDelay=-1}_listeners={};_listenersBinary={};connected=!1;channelId;_connectionId=null;_ws;_waitingForSocket={};_isInRoom=!1;_currentRoomName=null;_currentRoomViewId=null;_currentRoomAllowEditing=!0;_currentInRoom=[];_state={};_currentDelay=-1;_connectingToWebsocketPromise=null;connectWebsocket(){return this._connectingToWebsocketPromise?this._connectingToWebsocketPromise:this._connectingToWebsocketPromise=new Promise(async(e,t)=>{let i=!1;const n=h=>{i||(i=!0,e(h))};if(ki===void 0&&(console.log("Fetch default backend url: "+g_),ki=await(await fetch(g_)).text()),ki===void 0){n(!1);return}console.debug(`Connecting to networking backend on
|
|
172
|
-
`+ki);const o=await Promise.resolve().then(()=>require("./vendor-CipoooTV.umd.cjs")).then(h=>h.index),r=o.default?.WebsocketBuilder??o.WebsocketBuilder,a=o.default?.ExponentialBackoff??o.ExponentialBackoff,l=new r(ki).withMaxRetries(10).withBackoff(new a(2e3,4)).onOpen(()=>{this._connectingToWebsocketPromise=null,this._ws=l,this.connected=!0,A()||Yt?console.log(`Connected to networking backend
|
|
173
|
-
`+ki):console.debug("Connected to networking backend",ki),n(!0),this.onSendQueued(ln.OnConnection)}).onClose(h=>{this._connectingToWebsocketPromise=null,this.connected=!1,this._isInRoom=!1,n(!1);let d="Websocket connection closed...";ki?.includes("/socket")||(d+=' Do you perhaps mean to connect to "/socket"?'),console.error(d)}).onError(h=>{console.error("Websocket connection failed..."),n(!1),ni.sendEvent(this.context,"networking",{event:"connection_error"})}).onRetry(()=>{console.log("Retry connecting to networking websocket")}).build();l.addEventListener(o.WebsocketEvent.message,(h,d)=>{this.onMessage(h,d)})})}onMessage(e,t){const i=t.data;try{if(typeof i!="string"){i.size&&this.handleIncomingBinaryMessage(i);return}const n=JSON.parse(i);if(Array.isArray(n))for(const o of n)this.handleIncomingStringMessage(o);else this.handleIncomingStringMessage(n);return}catch(n){Yt&&i==="pong"?console.log("<<",i):A()&&console.error("Failed to parse message",n)}}async handleIncomingBinaryMessage(e){Lh&&console.log("<< bin",this.context.time.frame);const t=await e.arrayBuffer();var i=new Uint8Array(t);const n=new ae.ByteBuffer(i),o=n.getBufferIdentifier(),r=this._listenersBinary[o],a=$v(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(Yt&&console.log("<<",e.key??e),e.key)switch(e.key){case"connection-start-info":if(e.data){const r=e.data;r&&(console.assert(r.id!==void 0&&r.id!==null&&r.id.length>0,"server did not send connection id",r.id),console.debug("Your id is: "+r.id,this.context.alias??""),this._connectionId=r.id,ni.sendEvent(this.context,"networking",{event:"connected"}))}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(Yt&&console.log(e),e){this._isInRoom=!0;const r=e;this._currentRoomName=r.room,this._currentRoomViewId=r.viewId,this._currentRoomAllowEditing=r.allowEditing??!0,this._currentInRoom.length=0,this._currentInRoom.push(...r.inRoom),(Lh||A())&&console.debug("Joined Needle Engine Room: "+r.room);const a=new URL(window.location.href);a.searchParams.has("room")&&a.searchParams.delete("room"),a.searchParams.set("view",this._currentRoomViewId),console.debug(`Room view id: ${this._currentRoomViewId}
|
|
174
|
-
${a.href}`)}this.onSendQueued(ln.OnRoomJoin),ni.sendEvent(this.context,"networking",{event:"joined_room",room:this._currentRoomName});break;case"left-room":const n=e;n.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentRoomAllowEditing=!0,this._currentInRoom.length=0,(Lh||A())&&console.debug("Left Needle Engine Room: "+n.room)),ni.sendEvent(this.context,"networking",{event:"left_room",room:n.room});break;case"user-joined-room":if(e.data){const r=e.data;this._currentInRoom.push(r.userId),Yt&&console.log(r.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){const r=e.data,a=this._currentInRoom.indexOf(r.userId);a>=0&&(Yt&&console.log(r.userId+" left","now in room:",this._currentInRoom),this._currentInRoom.splice(a,1)),r.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":Yt&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const o=e.data?.time;o&&(this._currentDelay=this.context.time.time-o),Yt&&console.log(`Current latency: ${(this._currentDelay*1e3).toFixed()} ms`,"Clients in room: "+this._currentInRoom?.length);break}const t=e.data;t&&(this._state[t.guid]=t);let i=this._listeners[e.key];if(i){i=[...i];for(const n of i)try{n(e.data)}catch(o){console.error('Error invoking callback for "'+e.key+'"',o)}}}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,i=ln.OnRoomJoin){if(!this._ws){const o=this._waitingForSocket[i]||[];o.push(()=>this.sendWithWebsocket(e,t,i)),this._waitingForSocket[i]=o;return}const n=JSON.stringify(this.toMessage(e,t));Yt&&console.log(">>",e),this._ws.send(n)}onSendQueued(e){const t=this._waitingForSocket[e];if(t){for(const i of t)i();t.length=0}}}const ec=x("debugwebxr");class kf{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=>{ec&&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||(ec&&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),ec&&console.log(`XRSync: ${i.type} ${i.handedness} added`,i.index)}}}class Yv{hasState(e){return e?this._states.has(e):!1}isTracking(e,t){if(!e)return;const i=this._states.get(e);return i?i.controllerStates.find(o=>o.handedness===t)?.isTracking||!1:void 0}getDeviceType(e,t){if(!e)return;const i=this._states.get(e);return i?i.controllerStates.find(o=>o.handedness===t)?.type||"unknown":void 0}context;constructor(e){this.context=e,this.context.connection.beginListen(K.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(K.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(K.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(K.UserLeftRoom,this.onOtherUserLeftRoom)}destroy(){this.context.connection.stopListen(K.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(K.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(K.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(K.UserLeftRoom,this.onOtherUserLeftRoom)}onJoinedRoom=()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(ec&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new kf(this.context.connection.connectionId,this.context)));for(const e of this.context.connection.usersInRoom())this._states.has(e)||this._states.set(e,new kf(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)||(ec&&console.log("XRSync: Remote user joined room",t),this._states.set(t,new kf(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 y_{_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 BC='<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>',FC=btoa(BC),UC="data:image/svg+xml;base64,"+FC,Da=UC,zC=`<?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(zC);const NC='<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>',VC=btoa(NC),$C="data:image/svg+xml;charset=utf-8;base64,"+VC,__=$C;var Va=(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))(Va||{});class bo{static createText(e,t){let i=null;const n=t?.font||GC(t?.familyFamily||null);n instanceof X.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 X.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=WC(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",HC(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 WC(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,y)=>{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[y]/s,d[y+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 Ih=new Map;function GC(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://cdn.needle.tools/static/fonts/facetype/Helvetiker_Regular_ascii.json";break}if(Ih.has(e)){const n=Ih.get(e);if(n)return n}const t=new X.FontLoader,i=new Promise((n,o)=>{t.load(e,r=>{Ih.set(e,r),n(r)},void 0,o)});return Ih.set(e,i),i}let Rf=!1,Ef=null;function HC(s,e){if(Ef===null){const t="https://cdn.needle.tools/static/models/shaderball.glb",i=new X.GLTFLoader,n=re.createLoaders(null);i.setDRACOLoader(n.dracoLoader),i.setKTX2Loader(n.ktx2Loader),Rf=!0,Ef=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),v_())).finally(()=>{Rf=!1})}if(Rf){const t=v_();t.name="ShaderBall-Placeholder";const i=t.children[0];i?.type==="Mesh"&&b_(i,e),s.add(t)}Ef.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(),b_(n,e)),s.add(i)})}function b_(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 v_(){return new c.Group().add(bo.createPrimitive("Sphere",{material:new c.MeshBasicMaterial({transparent:!0,opacity:.1})}))}class La{static _active=null;static get active(){return this._active}static _requestInFlight=!1;static async start(e,t){if(this._active)return console.error("Cannot start a new XR session while one is already active"),null;if(this._requestInFlight)return console.error("Cannot start a new XR session while a request is already in flight"),null;if("xr"in navigator&&navigator.xr){if(!t)return console.error("XRSessionInit must be provided"),null;this._requestInFlight=!0;const i=await navigator.xr.requestSession(e,t).catch(n=>{console.error("Failed to start temporary XR session:",n)});return i?(i.addEventListener("end",()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new La(e,t,i),this._active):(i.end(),null)):(this._requestInFlight=!1,null)}return null}static async handoff(){return this._active?this._active.handoff():null}static async stop(){this._requestInFlight=!1,this._active&&(await this._active.end(),await _s(100)),this._active=null}_session;_mode;_init;get isAR(){return this._mode==="immersive-ar"}get isVR(){return this._mode==="immersive-vr"}_renderer;_camera;_scene;constructor(e,t,i){this._mode=e,this._init=t,this._session=i,this._session.addEventListener("end",this.onEnd),this._renderer=new c.WebGLRenderer({alpha:!0,antialias:!0}),this._renderer.outputColorSpace="srgb",this._renderer.setPixelRatio(Math.min(2,window.devicePixelRatio)),this._renderer.setSize(window.innerWidth,window.innerHeight,!0),exports.DeviceUtilities.isNeedleAppClip()&&window.requestAnimationFrame(()=>{const n=Math.min(2,window.devicePixelRatio),o=Math.floor(window.innerWidth*n),r=Math.floor(window.innerHeight*n);this._renderer.domElement.width=o,this._renderer.domElement.height=r}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(i),this._renderer.xr.enabled=!0,this._camera=new c.PerspectiveCamera,this._scene=new c.Scene,this._scene.fog=new c.Fog(4473924,10,250),this._scene.add(this._camera),this.setupScene()}end(){return this._session?this._session.end():Promise.resolve()}async handoff(){if(!this._session)throw new Error("Cannot handoff a session that has already ended");const e={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,e}onEnd=()=>{this._session?.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()};_lastTime=0;_frames=0;onFrame=(e,t)=>{const i=e-this._lastTime;this.update(e,i),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera),this._lastTime=e,this._frames++};_roomFlyObjects=[];_logoObject=null;get _logoDistance(){return this.isAR?.3:5}get _logoScale(){return this.isAR?.04:1}update(e,t){const i=e*4e-4;for(let r=0;r<this._roomFlyObjects.length;r++){const a=this._roomFlyObjects[r];a.position.y+=Math.sin(i+r*.5)*.005,a.rotateY(.002)}const n=this._logoObject,o=this._renderer.xr.getCamera();if(n){const r=new c.Vector3;o.getWorldDirection(r);const a=o.position.clone().addScaledVector(r,this._logoDistance),l=this.isAR?.005:1e-5;n.position.lerp(a,this._frames<=2?1:t*l),n.lookAt(this._camera.position)}}async onBeforeHandoff(){await _s(1e3),this._scene.clear()}setupScene(){this._scene.background=new c.Color(0);let e=Da;if($n()){const d=document.querySelector("needle-engine");if(d){const u=d.getAttribute("logo-src");u?.length&&(e=u,A()&&console.debug("[XR] Using custom loading logo from license:",e))}}const t=this._logoObject=new c.Mesh(new c.PlaneGeometry(1,1,1,1),new c.MeshBasicMaterial({transparent:!0,side:2}));t.scale.multiplyScalar(this._logoScale*window.devicePixelRatio),t.renderOrder=1e3,t.material.opacity=0,this._scene.add(t);const i=document.createElement("canvas"),n=i.getContext("2d"),o=new Image,r=d=>{if(!n)return;t.material.opacity=1;const u=1024;i.width=u,i.height=u,n.imageSmoothingQuality="high";const p=u*.19,m=o.width/o.height;{const v=i.height-p*1.5,E=v*m,O=(i.width-E)/2;n.drawImage(o,O,0,E,v)}const y=u*.12,_="Loading...";n.shadowBlur=0,n.fillStyle=this.isAR?"white":"rgba(255,255,255,0.4)",n.font=`${y}px Arial`,n.shadowBlur=u*.02,n.shadowColor="rgba(0,0,0,0.5)",n.shadowOffsetX=0,n.shadowOffsetY=0;const g=n.measureText(_);n.fillText(_,i.width/2-g.width/2,i.height-p/4),n.font=`${y}px Arial`,n.fillText(_,i.width/2-g.width/2,i.height-p/4);const w=new c.TextureLoader().load(i.toDataURL());w.generateMipmaps=!0,w.colorSpace="srgb",w.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=w,t.material.needsUpdate=!0};o.onload=()=>r(),o.onerror=d=>{console.error("Failed to load temporary XR logo:",e,d),o.src=Da},o.crossOrigin="anonymous",o.src=e;const a=new c.DirectionalLight(16777215,1);a.position.set(0,20,0),a.castShadow=!1,this._scene.add(a);const l=new c.DirectionalLight(16777215,1);l.position.set(0,-1,0),l.castShadow=!1,this._scene.add(l);const h=new c.PointLight(16777215,1,100,1);if(h.position.set(0,2,0),h.castShadow=!1,h.distance=200,this._scene.add(h),this.isAR===!1)for(let u=0;u<100;u++){const p=new c.MeshStandardMaterial({color:2236962,metalness:1,roughness:.8}),m=Va.Sphere,y=bo.createPrimitive(m,{material:p});y.position.x=I.random(-50,50),y.position.y=I.random(-2,50),y.position.z=I.random(-50,50),y.rotation.x=I.random(0,Math.PI*2),y.rotation.y=I.random(0,Math.PI*2),y.rotation.z=I.random(0,Math.PI*2),y.scale.multiplyScalar(.5+Math.random()*10);const _=y.position.distanceTo(this._camera.position)-y.scale.x;_<10&&(y.position.z+=5,y.position.multiplyScalar(1+1/_)),this._roomFlyObjects.push(y),this._scene.add(y)}}}var yc;(s=>{const e=[];function t(){e?.length||A()&&console.warn("No USDZ exporters found – cannot export USDZ for QuickLook.");for(const o of e)o.exportAndOpen();return!0}s.exportAndOpen=t;function i(o){e.push(o)}s.registerExporter=i;function n(o){if(!e)return;const r=e.indexOf(o);r>=0&&e.splice(r,1)}s.unregisterExporter=n})(yc||(yc={}));const Ue=x("debugwebxr"),w_=x("stats");let Tf=0;function qC(s){let e=null;const t=s;return t.getAROverlayContainer?e=t.getAROverlayContainer():e=s,e}XC();async function XC(){let s="immersive-vr";try{if(exports.DeviceUtilities.isNeedleAppClip()?s="immersive-ar":await navigator.xr?.isSessionSupported("immersive-vr")||(s="immersive-ar"),!await navigator.xr?.isSessionSupported("immersive-ar")&&s==="immersive-ar")return}catch(e){console.debug("[NeedleXRSession:granted] Error while checking XR support:",e);return}if(x("debugasap")){let e=globalThis["needle:XRSession"];if(e instanceof Promise){delete globalThis["needle:XRSession"],ce.addContextCreatedCallback(async t=>{if(!e)return;ba(!0);const i=await e;if(i){const n=q.getDefaultSessionInit(s);q.setSession(s,i,n,t.context)}else console.error("[NeedleXRSession:granted] ASAP session was rejected");e=void 0});return}}if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent)){console.warn("WebXRViewer does not support addEventListener");return}navigator.xr?.addEventListener("sessiongranted",async()=>{const e=sessionStorage.getItem("needle_xr_session_mode"),t=sessionStorage.getItem("needle_xr_session_init")??null,i=t?JSON.parse(t):null;let n=null;if(Kv()&&(await La.start(e||s,i||q.getDefaultSessionInit(s)).catch(o=>console.warn("[NeedleXRSession:granted] TemporaryXRContext start failed:",o)),await KC(),n=await La.handoff()),n)q.setSession(n.mode,n.session,n.init,U.Current);else if(e&&t){console.log("[NeedleXRSession:granted] Restore last session");const o=JSON.parse(t);q.start(e,o).catch(r=>console.warn(r))}else q.start(s).catch(o=>console.warn("[NeedleXRSession:granted] failed:",o))},{once:!0})}}function QC(s,e){sessionStorage.setItem("needle_xr_session_mode",s),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(e))}function YC(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const Km=new Set;ce.registerCallback(le.ContextCreationStart,async s=>{Km.add(s.context)});ce.registerCallback(le.ContextCreated,async s=>{Km.delete(s.context);const e=s.context?.domElement.getAttribute("autostart")||null;ZC(e)});function Kv(){return Km.size>0}function KC(){return new Promise(s=>{const e=Date.now(),t=setInterval(()=>{(!Kv()||Date.now()-e>6e4)&&(clearInterval(t),s())},100)})}exports.DeviceUtilities.isDesktop()&&A()&&window.addEventListener("keydown",s=>{(s.key==="x"||s.key==="Escape")&&q.active&&q.stop()});function ZC(s){s&&s?.toLowerCase()==="ar"&&fn.registerWaitForInteraction(()=>{q.start("ar")})}const jh=Symbol("initial-fov"),Af=Symbol("initial-near");class q{static _sync=null;static getXRSync(e){return this._sync||(this._sync=new Yv(e)),this._sync}static get currentSessionRequest(){return this._currentSessionRequestMode}static _currentSessionRequestMode=null;static get active(){return this._activeSession}static get activeMode(){return this._activeSession?.mode??null}static get xrSystem(){return"xr"in navigator?navigator.xr:void 0}static isXRSupported(){return Promise.all([this.isVRSupported(),this.isARSupported()]).then(e=>e.some(t=>t)).catch(()=>!1)}static isVRSupported(){return this.isSessionSupported("immersive-vr")}static isARSupported(){return this.isSessionSupported("immersive-ar")}static isSessionSupported(e){return this.xrSystem?.isSessionSupported(e).catch(t=>(Ue&&console.error(t),!1))??Promise.resolve(!1)}static _currentSessionRequest;static _activeSession;static onSessionRequestStart(e){this._sessionRequestStartListeners.push(e)}static offSessionRequestStart(e){const t=this._sessionRequestStartListeners.indexOf(e);t>=0&&this._sessionRequestStartListeners.splice(t,1)}static _sessionRequestStartListeners=[];static onSessionRequestEnd(e){this._sessionRequestEndListeners.push(e)}static offSessionRequestEnd(e){const t=this._sessionRequestEndListeners.indexOf(e);t>=0&&this._sessionRequestEndListeners.splice(t,1)}static _sessionRequestEndListeners=[];static onXRSessionStart(e){this._xrStartListeners.push(e)}static offXRSessionStart(e){const t=this._xrStartListeners.indexOf(e);t>=0&&this._xrStartListeners.splice(t,1)}static _xrStartListeners=[];static onXRSessionEnd(e){this._xrEndListeners.push(e)}static offXRSessionEnd(e){const t=this._xrEndListeners.indexOf(e);t>=0&&this._xrEndListeners.splice(t,1)}static _xrEndListeners=[];static onControllerAdded(e){this._controllerAddedListeners.push(e)}static offControllerAdded(e){const t=this._controllerAddedListeners.indexOf(e);t>=0&&this._controllerAddedListeners.splice(t,1)}static _controllerAddedListeners=[];static onControllerRemoved(e){this._controllerRemovedListeners.push(e)}static offControllerRemoved(e){const t=this._controllerRemovedListeners.indexOf(e);t>=0&&this._controllerRemovedListeners.splice(t,1)}static _controllerRemovedListeners=[];static offerSession(e,t,i){return"xr"in navigator&&navigator.xr&&"offerSession"in navigator.xr?(typeof navigator.xr.offerSession=="function"&&(console.log("WebXR offerSession is available - requesting mode: "+e),t=="default"&&(t=this.getDefaultSessionInit(e)),navigator.xr.offerSession(e,{...t}).then(n=>q.setSession(e,n,t,i)).catch(n=>{console.log("XRSession offer rejected (perhaps because another call to offerSession was made or a call to requestSession was made)")})),!0):!1}static getDefaultSessionInit(e){switch(e){case"immersive-ar":const t=["anchors","local-floor","layers","dom-overlay","hit-test","unbounded"];return exports.DeviceUtilities.isVisionOS()||t.push("hand-tracking"),{optionalFeatures:t};case"immersive-vr":const i=["local-floor","bounded-floor","high-fixed-foveation-level","layers"];return exports.DeviceUtilities.isVisionOS()||i.push("hand-tracking"),{optionalFeatures:i};default:return console.warn("No default session init for mode",e),{}}}static async start(e,t,i){if(t||(t={}),exports.DeviceUtilities.isiOS()){const a=await this.isARSupported().catch(()=>!1);if(exports.DeviceUtilities.isVisionOS()&&!a&&(e==="ar"||e==="immersive-ar")&&(e="quicklook"),e==="quicklook")return ni.sendEvent(U.Current,"xr",{action:"quicklook_export",source:"NeedleXRSession.start"}),yc.exportAndOpen(),null;if(!a&&(e==="immersive-ar"||e==="ar")){this.invokeSessionRequestStart("immersive-ar",t);const l=new URL("https://appclip.apple.com/id?p=tools.needle.launch-app.Clip");l.searchParams.set("url",location.href);const h=l.toString();ni.sendEvent(U.Current,"xr",{action:"app_clip_launch",source:"NeedleXRSession.start",url:h});const d=window.top||window;try{console.debug("iOS device detected - opening Needle App Clip for AR experience",{mode:e,init:t,url:l}),d.location.href=h}catch(u){console.warn("Error navigating to AppClip "+h+`
|
|
175
|
-
`,u),window!==window.top?window.open(h,"_blank"):window.location.href=h}return setTimeout(()=>{this.invokeSessionRequestEnd("immersive-ar",t||{},null)},3e3),null}}if(e==="quicklook")return console.warn("QuickLook mode is only supported on iOS devices"),null;if(e=="ar"&&(e="immersive-ar"),A()&&x("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await La.start(e,t||q.getDefaultSessionInit(e)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(Ue||A())&&fe("A XRSession is already being requested"),this._currentSessionRequest.then(()=>this._activeSession);if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;if(i||(i=U.Current),i||(i=ce.All[0]),!i)throw new Error("No Needle Engine Context found");switch(e){case"immersive-ar":{if(await this.xrSystem?.isSessionSupported("immersive-ar")!==!0)return console.error(e+" is not supported by this browser."),null;const l=this.getDefaultSessionInit(e),h=qC(i.domElement);h&&!exports.DeviceUtilities.isQuest()&&(l.domOverlay={root:h},l.optionalFeatures.push("dom-overlay")),t={...l,...t}}break;case"immersive-vr":{if(await this.xrSystem?.isSessionSupported("immersive-vr")!==!0)return console.error(e+" is not supported by this browser."),null;t={...this.getDefaultSessionInit(e),...t}}break;default:console.warn("No default session init for mode",e);break}t.optionalFeatures??=[],t.requiredFeatures??=[],await La.stop();const n=e=="immersive-ar"?i.scripts_immersive_ar:i.scripts_immersive_vr;Ue?console.log(`%cRequesting ${e} session`,"font-weight:bold;",t,n):console.log(`%cRequesting ${e} session`,"font-weight:bold;");for(const a of n)a.onBeforeXR&&a.activeAndEnabled&&!a.destroyed&&a.onBeforeXR(e,t);this.invokeSessionRequestStart(e,t),Ue&&Se("Requesting "+e+" session ("+Date.now()+")"),ni.sendEvent(U.Current,"xr",{action:"session_request",mode:e,features:(t.requiredFeatures??[]).concat(t.optionalFeatures??[]).join(","),source:"NeedleXRSession.start"}),this._currentSessionRequest=navigator?.xr?.requestSession(e,t),this._currentSessionRequestMode=e;const o=await this._currentSessionRequest?.catch(a=>{console.error(a,"Code: "+a?.code),a?.code===9&&fe("Couldn't start XR session. Make sure you allow the required permissions."),console.log("If the specified XR configuration is not supported (e.g. entering AR doesnt work) - make sure you access the website on a secure connection (HTTPS) and your device has the required permissions (e.g. camera access)"),location.protocol==="http:"&&fe("XR requires a secure connection (HTTPS)")});return this._currentSessionRequest=void 0,this._currentSessionRequestMode=null,this.invokeSessionRequestEnd(e,t,o),o?this.setSession(e,o,t,i):(console.warn("XR Session request was rejected"),null)}static invokeSessionRequestStart(e,t){for(const i of this._sessionRequestStartListeners)i({mode:e,init:t})}static invokeSessionRequestEnd(e,t,i){for(const n of this._sessionRequestEndListeners)n({mode:e,init:t,newSession:i||null})}static setSession(e,t,i,n){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const o=e=="immersive-ar"?n.scripts_immersive_ar:n.scripts_immersive_vr;return this._activeSession=new q(e,t,n,{scripts:o,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:i}),t.addEventListener("end",this.onEnd),Ue?console.log(`%cStarted ${e} session`,"font-weight:bold;",o):console.log(`%cStarted ${e} session`,"font-weight:bold;"),this._activeSession}static $_stop_request=Symbol();static stop(){const e=this._activeSession;e&&(e[this.$_stop_request]===void 0?(Ue&&console.log("[NeedleXRSession] Stopping XR Session... (new)"),e[this.$_stop_request]=setTimeout(()=>{e.end()})):Ue&&console.warn("[NeedleXRSession] XR Session stop already requested"))}static onEnd=()=>{Ue&&console.log("XR Session ended"),this._activeSession=null};context;get sync(){return q._sync}get running(){return!this._ended&&this.session!=null}session;mode;get interactionMode(){return this.session.interactionMode}get visibilityState(){return this.session.visibilityState}get isVisibleBlurred(){return this.session.visibilityState==="visible-blurred"}get isSystemKeyboardSupported(){return this.session.isSystemKeyboardSupported}get environmentBlendMode(){return this.session.environmentBlendMode}get frame(){return this.context.xrFrame}controllers=[];get leftController(){return this.controllers.find(e=>e.side==="left")}get rightController(){return this.controllers.find(e=>e.side==="right")}getController(e){return typeof e=="number"?this.controllers[e]||null:this.controllers.find(t=>t.side===e)||null}get isPassThrough(){return!!(this.environmentBlendMode!=="opaque"&&this.interactionMode==="world-space"||this.mode==="immersive-ar"&&this.environmentBlendMode!=="opaque"&&this.controllers.some(e=>e.inputSource.targetRayMode==="tracked-pointer")||A()&&exports.DeviceUtilities.isDesktop()&&this.mode==="immersive-ar")}get isAR(){return this.mode==="immersive-ar"}get isVR(){return this.mode==="immersive-vr"}get isScreenBasedAR(){return this.isAR&&!this.isPassThrough}get posePosition(){return this._transformPosition}get poseOrientation(){return this._transformOrientation}get referenceSpace(){return this.context.renderer.xr.getReferenceSpace()}get viewerPose(){return this._viewerPose}get isTrackingImages(){if(this.frame&&"getImageTrackingResults"in this.frame&&typeof this.frame.getImageTrackingResults=="function")try{const e=this.frame.getImageTrackingResults();for(const t of e)if(t.trackingState==="tracked")return!0}catch{return!1}return!1}get rig(){const e=this._rigs[0]??null;return e?.gameObject&&ur(e.gameObject)||e?.isActive===!1?(this.updateActiveXRRig(),this._rigs[0]??null):e}_rigScale=1;_lastRigScaleUpdate=-1;get rigScale(){return this._rigs[0]?(this._lastRigScaleUpdate!==this.context.time.frame&&(this._lastRigScaleUpdate=this.context.time.frame,this._rigScale=this._rigs[0].gameObject.worldScale.x),this._rigScale):1}addRig(e){this._rigs.indexOf(e)>=0||(e.priority===void 0&&(e.priority=0),this._rigs.push(e),this.updateActiveXRRig())}removeRig(e){const t=this._rigs.indexOf(e);t!==-1&&(this._rigs.splice(t,1),this.updateActiveXRRig())}setRigActive(e){const t=this._rigs.indexOf(e),i=this._rigs[0];this._rigs.splice(t,1),this._rigs.unshift(e),e.priority=i?.priority??0,this.updateActiveXRRig()}getUserOffsetInRig(){const e=this.context.mainCamera?.position;if(!e||!this.rig)return F(0,0,0);const t=F(e);return t.x*=-1,t.z*=-1,t.applyQuaternion(ei(this.rig.gameObject.quaternion)),t}updateActiveXRRig(){const e=this._rigs[0]??null;this._defaultRig.gameObject.parent!==this.context.scene&&this.context.scene.add(this._defaultRig.gameObject),this._defaultRig.gameObject.visible=!0,this._rigs.includes(this._defaultRig)||this._rigs.push(this._defaultRig);let t=this._rigs[0];t&&t.priority===void 0&&(t.priority=0);for(let i=1;i<this._rigs.length;i++){const n=this._rigs[i];if(n.isActive){if(ur(n.gameObject)){this._rigs.splice(i,1),i--;continue}(!t||t.isActive===!1||n.priority!==void 0&&n.priority>t.priority)&&(t=n)}}if(e!==t){const i=this._rigs.indexOf(t);i>=0&&this._rigs.splice(i,1),this._rigs.unshift(t)}Ue&&(e===t?console.log("Updated Active XR Rig:",t,"prev:",e):console.log("Updated Active XRRig:",t," (the same as before)"))}_rigs=[];_viewerHitTestSource=null;getHitTest(e){if(e)return this.getControllerHitTest(e);if(!this._viewerHitTestSource)return null;const t=this._viewerHitTestSource,i=this.frame.getHitTestResults(t);if(i.length>0){const n=i[0];return this.convertHitTestResult(n)}return null}getControllerHitTest(e){const t=e.getHitTestSource();if(!t)return null;const i=this.frame.getHitTestResultsForTransientInput(t);for(const n of i)if(n.inputSource===e.inputSource)for(const o of n.results)return this.convertHitTestResult(o);return null}convertHitTestResult(e){const t=this.context.renderer.xr.getReferenceSpace(),i=t&&e.getPose(t);if(i){const n=F(i.transform.position),o=ei(i.transform.orientation),r=this.context.mainCamera;if(r?.parent!==this._cameraRenderParent&&n.applyMatrix4(va),r?.parent){n.applyMatrix4(r.parent.matrixWorld),o.multiply(Li);const a=pe(r.parent);a.premultiply(Li),o.premultiply(a)}return{hit:e,position:n,quaternion:o}}return null}convertSpace(e){const t=F(e.position);t.applyMatrix4(va);const i=ei(e.orientation);return i.premultiply(Li),{position:t,quaternion:i}}_defaultRig;_xr_scripts;_xr_update_scripts=[];_inactive_scripts=[];_controllerAdded;_controllerRemoved;_originalCameraWorldPosition;_originalCameraWorldRotation;_originalCameraWorldScale;_originalCameraParent;_mainCamera=null;constructor(e,t,i,n){QC(e,n.init),this.session=t,this.mode=e,this.context=i,(Ue||x("console"))&&ba(!0),this._xr_scripts=[...n.scripts],this._xr_update_scripts=this._xr_scripts.filter(o=>typeof o.onUpdateXR=="function"),this._controllerAdded=n.controller_added,this._controllerRemoved=n.controller_removed,xs(this.onBefore,ge.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),(n.init.optionalFeatures?.includes("hit-test")||n.init.requiredFeatures?.includes("hit-test"))&&t.requestReferenceSpace("viewer").then(o=>t.requestHitTestSource?.call(t,{space:o})?.then(r=>this._viewerHitTestSource=r).catch(r=>console.error(r))).catch(o=>console.error(o)),this.context.mainCamera&&(this._originalCameraWorldPosition=Y(this.context.mainCamera,new c.Vector3),this._originalCameraWorldRotation=pe(this.context.mainCamera,new c.Quaternion),this._originalCameraWorldScale=je(this.context.mainCamera,new c.Vector3),this._originalCameraParent=this.context.mainCamera.parent,this.context.mainCamera instanceof c.PerspectiveCamera&&(this.context.mainCamera[jh]=this.context.mainCamera.fov)),this._defaultRig=new PC,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let o=0;o<t.inputSources.length;o++){const r=t.inputSources[o];if(!r.handedness){console.warn("Input source in xr session has no handedness - ignoring",o);continue}this.onInputSourceAdded(r)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",o=>{for(const r of o.removed)this.disconnectInputSource(r);for(const r of o.added)this.onInputSourceAdded(r)}),this.context.xr=this,this.context.renderer.xr.setSession(this.session).then(this.onRendererSessionSet),"controllerAutoUpdate"in this.context.renderer.xr?(console.debug("Disabling three.js controllerAutoUpdate"),this.context.renderer.xr.controllerAutoUpdate=!1):Ue&&console.warn("controllerAutoUpdate is not available in three.js - cannot disable it"),exports.DeviceUtilities.isNeedleAppClip()&&window.requestAnimationFrame(()=>{const o=this.context.renderer.domElement,r=window.devicePixelRatio||1,a=o.width,l=o.height,h=Math.floor(window.innerWidth*r),d=Math.floor(window.innerHeight*r);(Math.abs(a-h)>2||Math.abs(l-d)>2)&&(o.width=h,o.height=d,console.debug("Applied DPR scaling for Needle AppClip XR session",r,o.width,o.height))})}onRendererSessionSet=()=>{this.running&&(this.context.renderer.xr.enabled=!0,this.context.renderer.xr.updateCamera(this.context.mainCamera),this.context.mainCameraComponent?.applyClearFlags())};onInputSourceAdded=e=>{if(e.targetRayMode==="screen")return;let t=0;for(let n=0;n<this.session.inputSources.length;n++)if(this.session.inputSources[n]===e){t=n;break}if(this.controllers.find(n=>n.inputSource===e)){console.debug("Controller already exists for input source",t);return}else if(this._newControllers.find(n=>n.inputSource===e)){console.debug("Controller already registered for input source",t);return}const i=new Hm(this,e,t);this._newControllers.push(i)};disconnectInputSource(e){const t=(o,r)=>{if(o.inputSource===e){Ue&&console.log("Disconnecting controller",o.index);const a=r.indexOf(o);a>=0&&r.splice(a,1),this.invokeControllerEvent(o,this._controllerRemoved,"removed");const l={xr:this,controller:o,change:"removed"};for(const h of this._xr_scripts)h.onXRControllerRemoved&&h.onXRControllerRemoved(l);o.onDisconnected()}},i=[...this.controllers];for(let o=i.length-1;o>=0;o--){const r=i[o];t(r,this.controllers)}const n=[...this._newControllers];for(let o=n.length-1;o>=0;o--){const r=n[o];t(r,this._newControllers)}}end(){this._ended||this.session.end().catch(e=>console.warn(e))}_ended=!1;_newControllers=[];onEnd=e=>{if(this._ended)return;this._ended=!0,console.debug("XR Session ended"),ni.sendEvent(U.Current,"xr",{action:"session_end",mode:this.mode,source:"NeedleXRSession.onEnd"}),YC(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,this.requestedCameraNearPlane=null,_o(this.onBefore,ge.LateUpdate);const t=this.context.pre_render_callbacks.indexOf(this.onBeforeRender);t>=0&&this.context.pre_render_callbacks.splice(t,1);const i=this.context.post_render_callbacks.indexOf(this.onAfterRender);i>=0&&this.context.post_render_callbacks.splice(i,1),this.context.xr=null,this.context.renderer.xr.enabled=!1,this.context.pre_update_oneshot_callbacks.push(()=>{this.context.mainCameraComponent?.applyClearFlags(),this.context.mainCameraComponent?.applyClippingPlane()}),zv({session:this});for(const o of q._xrEndListeners)o({xr:this});const n=[...this.controllers];for(let o=0;o<n.length;o++)this.disconnectInputSource(n[o].inputSource);this.controllers.length=0,this._newControllers.length=0;for(const o of this._xr_scripts)o?.onLeaveXR?.({xr:this});this.sync?.onExitXR(this),this.context.mainCamera&&(this._originalCameraParent?.add(this.context.mainCamera),this._originalCameraWorldPosition&&at(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&dn(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&Ra(this.context.mainCamera,this._originalCameraWorldScale),this.context.mainCamera instanceof c.PerspectiveCamera&&(this.context.mainCamera[jh]&&(this.context.mainCamera.fov=this.context.mainCamera[jh],this.context.mainCamera[jh]=0),this.context.mainCamera[Af]&&(this.context.mainCamera.near=this.context.mainCamera[Af],this.context.mainCamera[Af]=0))),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),ba(!1)};_didStart=!1;onBefore=e=>{const t=e.xrFrame;if(!t)return;this.context.xr=this,this.context.mainCameraComponent&&this.context.mainCameraComponent!==this._mainCamera&&(this._mainCamera=this.context.mainCameraComponent),this.rig?.isActive==!1&&(Ue&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig&&this._mainCamera?.gameObject&&this._mainCamera?.gameObject?.parent!==this.rig.gameObject&&this.rig.gameObject.add(this._mainCamera?.gameObject),this.internalUpdateState(),this.applyCustomForward();const i={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const n=[...this.context.new_scripts_xr];for(let o=0;o<n.length;o++){const r=this.context.new_scripts_xr[o];if(!r||r.destroyed||r.supportsXR?.(this.mode)==!1){this.context.new_scripts_xr.splice(o,1);continue}if(!r.activeAndEnabled){this.context.new_scripts_xr.splice(o,1),this.markInactive(r);continue}if(this.addScript(r)){this.invokeCallback_EnterXR(r);for(const a of this.controllers)this.invokeCallback_ControllerAdded(r,a)}}}}else{if(this._didStart=!0,this.mode==="immersive-vr"){const o=ri(this.context.scene.children);if(o){const r=o.getSize(F());if(r.length()>0){const a=this._defaultRig.gameObject;a.position.set(o.min.x+r.x*.5,o.min.y,o.max.z+r.z*.5+1.5);const l=o.getCenter(F());l.y=a.position.y,a.lookAt(l)}}}Uv({session:this}),vr();for(const o of q._xrStartListeners)o(i);const n=[...this._xr_scripts];Ue&&console.log("NeedleXRSession start, handle scripts:",n);for(const o of n){if(o.destroyed){this._script_to_remove.push(o);continue}if(!o.activeAndEnabled){this.markInactive(o);continue}this.invokeCallback_EnterXR(o);for(const r of this.controllers)this.invokeCallback_ControllerAdded(o,r)}}this.syncCameraCullingMask();for(const n of this.controllers)n.onUpdate(t);if(this._newControllers.length>0){const n=[...this._newControllers];this._newControllers.length=0;for(const o of n){if(!o.connected){console.warn("New controller is not connected",o);continue}this.controllers.push(o);for(const r of this._xr_scripts){if(r.destroyed){this._script_to_remove.push(r);continue}r.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(r,o)}}this.controllers.sort((o,r)=>o.index-r.index)}Ue&&this.context.time.frame%30===0&&this.controllers.length<=0&&this.session.inputSources.length>0&&(ba(!0),console.error("XRControllers are not added but inputSources are present"));for(const n of this._xr_update_scripts){if(n.destroyed===!0){this._script_to_remove.push(n);continue}if(n.activeAndEnabled===!1){this.markInactive(n);continue}n.onUpdateXR&&n.onUpdateXR(i)}if(this.handleInactiveScripts(),this._script_to_remove.length>0){const n=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const o of n)!o.destroyed&&this.running&&o.onLeaveXR?.(i),this.removeScript(o)}this.sync?.onUpdate(this),this.onRenderDebug()};onRenderDebug(){if(Ue)for(const e of this.controllers)e.onRenderDebug();if((Ue||w_)&&this.rig&&(Tf++,Tf>=20)){const e=this.rig.gameObject.worldPosition,t=this.rig.gameObject.worldForward;e.add(t.multiplyScalar(1.5));const i=this.rig.gameObject.worldUp;e.add(i.multiplyScalar(2.5));let n="";if(n+=`${this.context.time.smoothedFps.toFixed(0)} FPS`,n+=`, calls: ${this.context.renderer.info.render.calls}, tris: ${this.context.renderer.info.render.triangles.toLocaleString()}`,Ue||w_)for(const o of this.controllers)n+=`
|
|
176
|
-
${o.hand?"hand":"ctrl"} ${o.inputSource.handedness}[${o.index}] con:${o.connected} tr:${o.isTracking} hts:${o.hasHitTestSource?"yes":"no"}`;Tf=0,B.DrawLabel(e,n,void 0,1/60*20)}}onBeforeRender=()=>{this.context.mainCamera&&(this.updateFade(this.context.mainCamera),this.requestedCameraNearPlane!==null&&this.context.mainCamera instanceof c.PerspectiveCamera&&(this.context.mainCamera.near=this.requestedCameraNearPlane,this.requestedCameraNearPlane=null))};onAfterRender=()=>{if(this.onUpdateFade_PostRender(),exports.DeviceUtilities.isDesktop()||!this._renderOnceOnDevice){const e=this.context.renderer;if(e.xr.isPresenting&&this.context.mainCamera){this._renderOnceOnDevice=!0;const t=e.xr.enabled,i=e.getRenderTarget(),n=this.context.scene.background;e.xr.enabled=!1,e.setRenderTarget(null),this.isPassThrough&&(this.context.scene.background=null),this.context.composer?this.context.composer.render(this.context.time.deltaTime):e.render(this.context.scene,this.context.mainCamera),e.xr.enabled=t,e.setRenderTarget(i),this.context.scene.background=n}}};addScript(e){return this._xr_scripts.includes(e)?!1:(Ue&&console.log("Register new XRScript",e),this._xr_scripts.push(e),typeof e.onUpdateXR=="function"&&this._xr_update_scripts.push(e),!0)}markInactive(e){if(!(this._inactive_scripts.indexOf(e)>=0)){this.removeScript(e,!1),this._inactive_scripts.push(e);for(const t of this.controllers)this.invokeCallback_ControllerRemoved(e,t);this.invokeCallback_LeaveXR(e)}}handleInactiveScripts(){if(this._inactive_scripts.length>0)for(let e=this._inactive_scripts.length-1;e>=0;e--){const t=this._inactive_scripts[e];if(t.activeAndEnabled){this._inactive_scripts.splice(e,1),this.addScript(t),this.invokeCallback_EnterXR(t);for(const i of this.controllers)this.invokeCallback_ControllerAdded(t,i)}}}_script_to_remove=[];removeScript(e,t=!0){Ue&&console.log("Remove XRScript",e);const i=this._xr_scripts.indexOf(e);i>=0&&this._xr_scripts.splice(i,1);const n=this._xr_update_scripts.indexOf(e);if(n>=0&&this._xr_update_scripts.splice(n,1),t){const o=this._inactive_scripts.indexOf(e);o>=0&&this._inactive_scripts.splice(o,1)}}invokeCallback_EnterXR(e){e.onEnterXR&&e.onEnterXR({xr:this})}invokeCallback_ControllerAdded(e,t){e.onXRControllerAdded&&e.onXRControllerAdded({xr:this,controller:t,change:"added"})}invokeCallback_ControllerRemoved(e,t){e.onXRControllerRemoved&&e.onXRControllerRemoved({xr:this,controller:t,change:"removed"})}invokeCallback_LeaveXR(e){e.onLeaveXR&&!e.destroyed&&e.onLeaveXR({xr:this})}syncCameraCullingMask(){const e=this.context.xrCamera,t=this.context.mainCameraComponent?.cullingMask;if(e&&t!==void 0){for(const i of e.cameras)i.layers.mask=t;e.layers.mask=t}else if(e){for(const i of e.cameras)i.layers.enableAll();e.layers.enableAll()}}invokeControllerEvent(e,t,i){for(let n=t.length-1;n>=0;n--){const o=t[n];if(o)try{o({xr:this,controller:e,change:i})}catch(r){console.error(r)}}}_camera;_cameraRenderParent=new c.Object3D().rotateY(Math.PI);_previousCameraParent;_customforward=!0;originalCameraNearPlane;requestedCameraNearPlane=null;applyCustomForward(){if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,this._previousCameraParent?.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);{let e=.02;const t=.001;if(this.rig){const i=je(this.rig.gameObject);e*=i.x}this._camera instanceof c.PerspectiveCamera&&Math.abs(this._camera.near-e)>t&&(this.isAR?this.originalCameraNearPlane=this._camera.near:this._camera.near=e,Ue&&console.debug(`Setting camera near plane to ${e} (was ${this.originalCameraNearPlane}) to account for XR rendering scale`))}}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof c.PerspectiveCamera&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane,this.originalCameraNearPlane=void 0)}_viewerPose;_transformOrientation=new c.Quaternion;_transformPosition=new c.Vector3;internalUpdateState(){const e=this.context.renderer.xr.getReferenceSpace();if(!e){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(e),this._viewerPose){const t=this._viewerPose.transform;this._transformPosition.set(t.position.x,t.position.y,t.position.z),this._transformOrientation.set(t.orientation.x,t.orientation.y,t.orientation.z,t.orientation.w)}}_transition;get transition(){return this._transition||(this._transition=new y_),this._transition}fadeTransition(){return this._transition||(this._transition=new y_),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 Df=x("debugwebxr");class Zv{static tryFindAvatarObjects(e,t,i){if(i.head&&i.leftHand&&i.rightHand)return;const n=e.name.toLocaleLowerCase();!i.head&&n.includes("head")&&(Df&&console.log("FOUND AVATAR HEAD",e.name),i.head=new Z("",t,e)),n.includes("hand")&&(!i.leftHand&&n.includes("left")&&(Df&&console.log("FOUND AVATAR LEFT HAND",e.name),i.leftHand=new Z("",t,e)),!i.rightHand&&n.includes("right")&&(Df&&console.log("FOUND AVATAR RIGHT HAND",e.name),i.rightHand=new Z("",t,e)));for(let o=0;o<e.children.length;o++){if(i.head&&i.leftHand&&i.rightHand)return;const r=e.children[o];this.tryFindAvatarObjects(r,t,i)}}}class te extends c.Color{alpha=1;get isRGBAColor(){return!0}set a(e){this.alpha=e}get a(){return this.alpha}constructor(e,t,i,n){super(),typeof e=="number"&&typeof t=="number"&&typeof i=="number"?(this.set(e,t,i),this.alpha=typeof n=="number"?n:1):e!==void 0&&(this.set(e),this.alpha=1)}clone(){const e=super.clone();return e.alpha=this.alpha,e}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,"alpha"in e&&typeof e.alpha=="number"?this.alpha=e.alpha:typeof e.a=="number"&&(this.alpha=e.a),this}lerp(e,t){const i=e;return i.alpha!=null&&(this.alpha=I.lerp(this.alpha,i.alpha,t)),super.lerp(e,t)}lerpColors(e,t,i){const n=e,o=t;return n.alpha!=null&&o.alpha!=null&&(this.alpha=I.lerp(n.alpha,o.alpha,i)),super.lerpColors(e,t,i)}multiply(e){const t=e;return t.alpha!=null&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}fromArray(e,t=0){return this.alpha=e[t+3],super.fromArray(e,t)}static fromColorRepresentation(e){if(typeof e=="string"){if(e.trim()==="transparent")return new te(0,0,0,0);if(e.startsWith("#")&&e.length===9){const t=parseInt(e.slice(1,9),16),i=t>>24&255,n=t>>16&255,o=t>>8&255,r=t>>0&255;return new te(i/255,n/255,o/255,r/255)}else if(e.startsWith("#")){const t=parseInt(e.slice(1),16),i=t>>16&255,n=t>>8&255,o=t>>0&255;return new te(i/255,n/255,o/255,1)}else if(e.startsWith("rgba")){const t=e.slice(5,-1).split(",").map(Number);return new te(t[0]/255,t[1]/255,t[2]/255,t[3])}else if(e.startsWith("rgb")){const t=e.slice(4,-1).split(",").map(Number);return new te(t[0]/255,t[1]/255,t[2]/255,1)}}else if(Array.isArray(e)){if(e.length===4)return new te(e[0],e[1],e[2],e[3]);if(e.length===3)return new te(e[0],e[1],e[2],1);console.error("Invalid color array length. Expected 3 or 4, got "+e.length)}return new te(e)}}const Ot=new c.Vector3,x_=new c.Vector3,S_=new c.Quaternion,JC=x("debuggizmos"),tn=8947848,Lf=32;class B{constructor(){}static enabled=!0;static isGizmo(e){return e[Up]!==void 0}static setVisible(e){for(const t of Ri.timedObjectsBuffer)t.visible=e}static DrawLabel(e,t,i=.05,n=0,o,r,a){if(!B.enabled)return null;o||(o=tn);const l=q.active?.rigScale??1,h=Ri.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=tn,n=0,o=!0){if(!B.enabled)return;const r=Ri.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),Ot.set(t.x,t.y,t.z).multiplyScalar(999999999),a.setXYZ(1,e.x+Ot.x,e.y+Ot.y,e.z+Ot.z),a.needsUpdate=!0,r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1,rn(r.material,i)}static DrawDirection(e,t,i=tn,n=0,o=!0,r=1){if(!B.enabled)return;const a=Ri.getLine(n),l=a.geometry.getAttribute("position");l.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(Ot.set(0,0,-r),S_.set(t.x,t.y,t.z,t.w),Ot.applyQuaternion(S_)):(Ot.set(t.x,t.y,t.z),Ot.multiplyScalar(r)),l.setXYZ(1,e.x+Ot.x,e.y+Ot.y,e.z+Ot.z),l.needsUpdate=!0,a.material.depthTest=o,a.material.depthWrite=!1,rn(a.material,i)}static DrawLine(e,t,i=tn,n=0,o=!0){if(!B.enabled)return;const r=Ri.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),a.setXYZ(1,t.x,t.y,t.z),a.needsUpdate=!0,r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1,rn(r.material,i)}static DrawCircle(e,t,i,n=tn,o=0,r=!0){if(!B.enabled)return;const a=Ri.getCircle(o);a.position.set(e.x,e.y,e.z),a.scale.set(i,i,i),a.quaternion.setFromUnitVectors(this._up,Ot.set(t.x,t.y,t.z).normalize()),a.material.depthTest=r,a.material.depthWrite=!1,a.material.fog=!1,rn(a.material,n)}static DrawWireSphere(e,t,i=tn,n=0,o=!0){if(!B.enabled)return;const r=Ri.getSphere(t,n,!0);dr(r,e.x,e.y,e.z),r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1,rn(r.material,i)}static DrawSphere(e,t,i=tn,n=0,o=!0){if(!B.enabled)return;const r=Ri.getSphere(t,n,!1);dr(r,e.x,e.y,e.z),r.material.depthTest=o,r.material.depthWrite=!1,rn(r.material,i)}static DrawWireBox(e,t,i=tn,n=0,o=!0,r=void 0){if(!B.enabled)return;const a=Ri.getBox(n);a.position.set(e.x,e.y,e.z),a.scale.set(t.x,t.y,t.z),r?a.quaternion.copy(r):a.quaternion.identity(),a.material.depthTest=o,a.material.wireframe=!0,a.material.depthWrite=!1,a.material.fog=!1,rn(a.material,i)}static DrawWireBox3(e,t=tn,i=0,n=!0){if(!B.enabled)return;const o=Ri.getBox(i);o.position.copy(e.getCenter(Ot)),o.scale.copy(e.getSize(Ot)),o.material.depthTest=n,o.material.wireframe=!0,o.material.depthWrite=!1,o.material.fog=!1,rn(o.material,t)}static _up=new c.Vector3(0,1,0);static DrawArrow(e,t,i=tn,n=0,o=!0,r=!1){if(!B.enabled)return;const a=Ri.getArrowHead(n);a.position.set(t.x,t.y,t.z),a.quaternion.setFromUnitVectors(this._up.set(0,1,0),Ot.set(t.x,t.y,t.z).sub(x_.set(e.x,e.y,e.z)).normalize());const h=Ot.set(t.x,t.y,t.z).sub(x_.set(e.x,e.y,e.z)).length()*.1;a.scale.set(h,h,h),a.material.depthTest=o,a.material.wireframe=r,rn(a.material,i),this.DrawLine(e,t,i,n,o)}static DrawWireMesh(e){const t=Ri.getMesh(e.duration??0);"mesh"in e?(t.geometry=e.mesh.geometry,t.matrixWorld.copy(e.mesh.matrixWorld)):(t.geometry=e.geometry,t.matrixWorld.copy(e.matrix)),t.matrixAutoUpdate=!1,t.matrixWorldAutoUpdate=!1,t.material.depthTest=e.depthTest??!0,t.material.wireframe=!0,rn(t.material,e.color??tn)}}const e1=new c.BoxGeometry(1,1,1);function Zm(s=null){const e=new c.Color(s??14540253),t=new c.EdgesGeometry(e1);return new c.LineSegments(t,new c.LineBasicMaterial({color:e}))}function rn(s,e){if(Array.isArray(s)){for(const i of s)rn(i,e);return}const t=e instanceof te?e.a:1;s.color.set(e),s.opacity=t,s.transparent=t<1}const Up=Symbol("GizmoCache");class Ri{static familyName="needle-gizmos";static ensureFont(){let e=ie.__webpack_exports__default.FontLibrary.getFontFamily(this.familyName);e||(e=ie.__webpack_exports__default.FontLibrary.addFontFamily(this.familyName),e.addVariant("normal","normal","https://cdn.needle.tools/static/fonts/msdf/arial/arial-msdf.json","https://cdn.needle.tools/static/fonts/msdf/arial/arial.png")?.addEventListener("ready",()=>{ie.__webpack_exports__default.update()}))}static getTextLabel(e,t,i,n,o){this.ensureFont();let r=this.textLabelCache.pop(),a=1;o&&typeof o=="string"&&o?.length>=8&&o.startsWith("#")?(a=parseInt(o.substring(7),16)/255,o=o.substring(0,7),JC&&console.log(o,a)):typeof o=="object"&&o.a!==void 0&&(a=o.a);const l={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:i,color:n,lineHeight:1,backgroundColor:o??void 0,backgroundOpacity:a,textContent:t,borderRadius:.5*i,padding:.8*i,whiteSpace:"pre",offset:.05*i};if(r)r.set(l);else{r=new ie.__webpack_exports__Text(l);const h=this,d=r;d.setText=function(u){this.set({textContent:u}),h.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(U.Current,r,e,this.textLabelCache),r}static getBox(e){let t=this.boxesCache.pop();if(!t){const i=new c.BoxGeometry(1,1,1);t=new c.Mesh(i)}return this.registerTimedObject(U.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new c.Line;let i=t.geometry.getAttribute("position");i||(i=new c.BufferAttribute(new Float32Array(6),3),t.geometry.setAttribute("position",i))}return t.frustumCulled=!1,this.registerTimedObject(U.Current,t,e,this.linesCache),t}static getCircle(e){let t=this.circlesCache.pop();if(!t){t=new c.Line;let i=t.geometry.getAttribute("position");if(!i){i=new c.BufferAttribute(new Float32Array(Lf*3),3),t.geometry.setAttribute("position",i);const n=F(0,1,0),o=F(0,0,1),r=F(o);r.cross(n).normalize();const a=F(r),l=Math.PI*2/(Lf-1);for(let h=0;h<Lf+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[Up]=n,t.castShadow=!1,t.receiveShadow=!1,t.isGizmo=!0,this.timedObjectsBuffer.push(t),this.timesBuffer.push(U.Current.time.realtimeSinceStartup+i),e.scene.add(t)}static timedObjectsBuffer=new Array;static timesBuffer=new Array;static contextPostRenderCallbacks=new Map;static contextBeforeRenderCallbacks=new Map;static tmuiNeedsUpdate=!1;static onBeforeRender(e,t){this.tmuiNeedsUpdate&&(this.tmuiNeedsUpdate=!1,ie.__webpack_exports__default.update());for(let i=0;i<t.length;i++){const n=t[i];if(e.mainCamera&&n instanceof ie.__webpack_exports__default.MeshUIBaseElement){if(ur(n))continue;const o=e.isInVR,r=!1,a=!o;Bc(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(),ur(r)!=!0&&r[Up].push(r))}}}const Vt=x("debugphysics"),t1=x("debugworker"),C_=new c.Layers;class vo{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 Jm{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}}class Ia{static _raycasting=0;static get raycasting(){return this._raycasting>0}raycastPhysicsFast(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycast(e,t,{maxDistance:i,solid:n})??null}raycastPhysicsFastAndGetNormal(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycastAndGetNormal(e,t,{maxDistance:i,solid:n})??null}sphereOverlapPhysics(e,t){return this.context.physics.engine?.sphereOverlap(e,t)??null}context;engine;constructor(e){this.context=e}raycaster=new c.Raycaster;defaultRaycastOptions=new vo;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new c.Layers;sphere=new c.Sphere;sphereOverlap(e,t,i=!0,n=!1,o=null){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const r=this.sphereMask;r.enableAll(),r.disable(2);for(const a of this.context.scene.children)this.intersectSphere(a,e,t,r,this.sphereResults,i,n,o);return this.sphereResults.sort((a,l)=>a.distance-l.distance)}raycastFromRay(e,t=null){const i=t??this.defaultRaycastOptions;i.ray=e;const n=this.raycast(i);return i===this.defaultRaycastOptions&&(i.ray=void 0),n}raycast(e=null){Vt&&performance.mark("raycast.start"),e||(e=this.defaultRaycastOptions);const t=e.screenPoint??this.context.input.mousePositionRC,i=e.raycaster??this.raycaster;if(i.near=e.minDistance??0,i.far=e.maxDistance??1/0,i.params=this.defaultThresholds,e.lineThreshold===void 0&&(e.lineThreshold=-1),i.params.Line={threshold:e.lineThreshold},e.ray)i.ray.copy(e.ray);else{const a=e.cam??this.context.mainCamera;if(!a)return Vt&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const l=this.context.xrCamera;this.context.isInXR&&l instanceof c.ArrayCamera&&l.cameras.length>0?i.setFromCamera(t,l.cameras[0]):i.setFromCamera(t,a)}let n=e.targets;n||(n=this.targetBuffer,n.length=1,n[0]=this.context.scene);let o=e.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),o||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),o=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof c.Layers?i.layers.mask=e.layerMask.mask:i.layers.mask=e.layerMask:(i.layers.enableAll(),i.layers.disable(2)),Vt&&console.time("raycast"),o.length=0,Ia._raycasting++,this.intersect(this.raycaster,n,o,e),o.sort((a,l)=>a.distance-l.distance);const r=e.ignore;return r!==void 0&&r.length>0&&(o=o.filter(a=>!r.includes(a.object))),Ia._raycasting--,Vt&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",o?.length?[...o]:"nothing"),performance.mark("raycast.end"),performance.measure("raycast","raycast.start","raycast.end")),o}intersect(e,t,i,n){for(const o of t){if(!o||o.visible===!1||B.isGizmo(o)||n.lineThreshold!==void 0&&n.lineThreshold<0&&o instanceof c.Line)continue;let r=!0;const a=o,l=a.geometry;if(o.raycastAllowed===!1&&(r=!1),r&&n.testObject){const h=n.testObject?.(o);if(h===!1)continue;h==="continue in children"&&(r=!1)}else r&&(l&&P_(l)||(r=!1));if(r){const h=i.length,d=o.raycastPreference||"lod";let u=d!=="bounds";if(n.precise===!1&&(u=!1),l&&(u||=l.getAttribute("position")?.array?.length<64),a instanceof X.GroundedSkybox&&(u=!1),d==="lod"){const p=re.getRaycastMesh(o);p&&(a.geometry=p)}if(!u&&n1(a,e,i)||(n.useAcceleratedRaycast!==!1?Ud.runMeshBVHRaycast(e,a,i,this.context,n):e.intersectObject(a,!1,i)),a.geometry=l,Vt&&i.length!=h){const p=i[i.length-1];B.DrawWireSphere(p.point,.1,7798784,1,!1),B.DrawWireMesh({mesh:o,depthTest:!1,duration:.2,color:7798784})}}n.recursive!==!1&&this.intersect(e,o.children,i,n)}return i}tempBoundingBox=new c.Box3;intersectSphere(e,t,i,n,o,r,a,l){let h=e&&e.isMesh&&e.layers.test(n)&&!B.isGizmo(e);h&&=e.visible,h&&=!(e instanceof c.Line),h&&=!(e instanceof X.GroundedSkybox);const d=e,u=d.geometry;if(h&&l){const p=l(e);if(p===!1)return;p==="continue in children"&&(h=!1)}if(u&&P_(u)||(h=!1),h){if(a){const p=this.sphere;p.center.copy(t),p.radius=i;const m=o.length;if(Ud.runMeshBVHRaycast(this.sphere,d,o,this.context,{}),m!=o.length&&!r)return}else if(u.boundingBox||u.computeBoundingBox(),u.boundingBox){d.matrixWorldNeedsUpdate&&d.updateWorldMatrix(!1,!1);const p=this.tempBoundingBox.copy(u.boundingBox).applyMatrix4(d.matrixWorld),m=this.sphere;if(m.center.copy(t),m.radius=i,m.intersectsBox(p)){const y=Y(e),_=y.distanceTo(m.center),g=new Jm(e,_,y);if(o.push(g),!r)return}}}if(e.children)for(const p of e.children){const m=o.length;if(this.intersectSphere(p,t,i,n,o,r,a,l),m!=o.length&&!r)return}}}function P_(s){return!(s.index&&s.index.array.length<3)}const Bo=new c.Sphere,Bh=new c.Plane,i1=new c.Matrix3;function n1(s,e,t){const i=s._computeIntersections;if(!i)return!1;let n=s["_computeIntersections:Needle"];return n||(n=s["_computeIntersections:Needle"]=function(o,r,a){const l=this,h=l.geometry.boundingSphere;if(h){if(l instanceof X.GroundedSkybox){Bh.setFromNormalAndCoplanarPoint(F(0,1,0),F(0,-l.position.y,0)),Bh.applyMatrix4(l.matrixWorld,i1);const u=o.ray.intersectPlane(Bh,F());if(u){Bo.copy(h),Bo.applyMatrix4(l.matrixWorld);const m=F(u).sub(o.ray.origin).length(),y=Bo.radius*.5;m<y&&r.push({distance:m,point:u,object:l,normal:Bh.normal.clone()})}return}Bo.copy(h),Bo.applyMatrix4(l.matrixWorld);const d=o.ray.intersectSphere(Bo,F());if(d){const u=F(d).sub(o.ray.origin),p=u.length();if(p>Bo.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 Ud;(s=>{let e=0;function t(b,v,E,O,M){if(!v.geometry||!v.geometry.hasAttribute("position"))return!1;const D=v.geometry;if(v?.isSkinnedMesh){const L=v,j=L.bvhNeedsUpdate;if(!L.staticGenerator)l(),r&&(L.staticGenerator=new r(v),L.staticGenerator.applyWorldTransforms=!1,L.staticGeometry=L.staticGenerator.generate(),D.boundsTree=a?.call(L.staticGeometry),L.staticGeometryLastUpdate=performance.now()+Math.random()*200,L.bvhNeedsUpdate=!0);else if(D.boundsTree&&(L.autoUpdateMeshBvhInterval!==void 0&&L.autoUpdateMeshBvhInterval>=0||j===!0)){const V=performance.now(),W=V-L.staticGeometryLastUpdate,k=L.autoUpdateMeshBvhInterval??100;(j||W>k)&&(Vt&&console.warn(`Physics: updating skinned mesh bvh for ${v.name} after ${W.toFixed(2)}ms`),L.bvhNeedsUpdate=!1,L.staticGeometryLastUpdate=V,L.staticGenerator?.generate(L.staticGeometry),D.boundsTree.refit())}}else if(!D.boundsTree){d||w();let L=!0;if((O.xr||D[y]===!1||D.getAttribute("position")?.isInterleavedBufferAttribute||D.index&&D.index?.isInterleavedBufferAttribute||e>10)&&(L=!1),L&&p){if(D[m]===void 0){let j=null;if(g.length>0){const V=g.shift();V&&!V.running&&(j=V)}if(!j&&_.length<3)try{t1&&console.warn("[GenerateMeshBVHWorker] Creating worker with import.meta.url:",typeof document>"u"?require("url").pathToFileURL(__filename).href:_a&&_a.tagName.toUpperCase()==="SCRIPT"&&_a.src||new URL("needle-engine.bundle-CrqNZdEN.umd.cjs",document.baseURI).href),j=new p,_.push(j)}catch(V){V instanceof DOMException&&V.name==="SecurityError"?(console.warn("Failed to create MeshBVH worker, falling back to main thread generation. This can happen when running from file://, if the browser does not support workers or if the browser is blocking workers for other reasons."),console.debug(V),e+=10):(console.error("Failed to create MeshBVH worker. Please see below for more details:"),console.log(V)),e++}if(j!=null&&!j.running){const V=v.name;Vt&&console.log("<<<< worker start",V,j),D[m]="queued",performance.mark("bvh.create.start");const W=D.clone();try{j.generate(W).then(k=>{D[m]="done",D.boundsTree=k}).catch(k=>{D[m]="failed - "+k?.message,D[y]=!1,Vt&&console.error("Failed to generate mesh bvh on worker",k)}).finally(()=>{Vt&&console.log(">>>>> worker done",V,{hasBoundsTre:D.boundsTree!=null}),g.push(j),W.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch(k){console.error("Failed to generate mesh bvh on worker",k)}}else Vt&&console.warn("No worker available")}}else(!u||!L)&&(l(),o&&(performance.mark("bvh.create.start"),D.boundsTree=new o(D),performance.mark("bvh.create.end"),performance.measure("bvh.create","bvh.create.start","bvh.create.end")))}if(b instanceof c.Raycaster){const L=b,j=v.raycast;if(D.boundsTree)l(),n&&(v.acceleratedRaycast||(v.acceleratedRaycast=n.bind(v),Vt&&console.debug(`Physics: bind acceleratedRaycast fn to "${v.name}"`)),v.raycast=v.acceleratedRaycast);else if(Vt&&console.warn("No bounds tree found for mesh",v.name,{workerTask:D[m],hasAcceleratedRaycast:n!=null}),M.allowSlowRaycastFallback===!1&&(D.getAttribute("position")?.array?.length??0)>2e3)return Vt&&console.warn("Skipping raycast because no bounds tree is available and allowSlowRaycastFallback is false"),!1;const V=L.firstHitOnly;return L.firstHitOnly=!1,L.intersectObject(v,!1,E),L.firstHitOnly=V,v.raycast=j,!0}else if(b instanceof c.Sphere){const L=D.boundsTree;if(L){const j=b;if(h.copy(v.matrixWorld).invert(),j.applyMatrix4(h),L.intersectsSphere(j)){const W=Y(v),k=W.distanceTo(j.center),N=new Jm(v,k,W);E.push(N)}}return!0}return!1}s.runMeshBVHRaycast=t;let i=!1,n=null,o=null,r=null,a=null;function l(){i||(i=!0,Promise.resolve().then(()=>require("./vendor-CipoooTV.umd.cjs")).then(b=>b.index$1).then(b=>{n=b.acceleratedRaycast,o=b.MeshBVH,r=b.StaticGeometryGenerator,a=b.computeBoundsTree}).catch(b=>{(Vt||A())&&console.error("Failed to load BVH library...",b.message)}))}const h=new c.Matrix4;let d=!1,u=!1,p=null;const m=Symbol("Needle:MeshBVH-Worker"),y=Symbol("Needle:MeshBVH-CanUseWorker"),_=[],g=[];function w(){d=!0,u=!0,Promise.resolve().then(()=>oA).then(b=>{p=b.GenerateMeshBVHWorker}).catch(b=>{Vt||A()?console.warn("Failed to setup mesh bvh worker"):console.debug("Failed to setup mesh bvh worker",b)}).finally(()=>{u=!1})}})(Ud||(Ud={}));const O_=Symbol("gltf-loader-internal-usage-tracker"),s1=x("debugusers");class xa{get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(e){return xa._loadingProcesses>0}static _loadingProcesses=0;parser;_getDependency;_loadingId;_loadedObjects=new Set;constructor(e){this.parser=e,this._getDependency=this.parser.getDependency,this._loadingId=Date.now().toString()}beforeRoot(){xa._loadingProcesses++;const e=this,t=this._getDependency;return this.parser.getDependency=function(i,n){const o=t.call(this,i,n);return o.then(r=>(r&&(e._loadedObjects.add(r),r[O_]=e._loadingId),r)),o},null}afterRoot(e){xa._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[O_],t instanceof c.Object3D&&(t.parent||t instanceof c.Mesh&&setTimeout(()=>{s1&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}}class Jv{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:
|
|
177
|
-
`+i.src),e.preventDefault())}})}}const mu=x("trackresources");function e0(){return mu==="dispose"}let wr=!0;mu===0&&(wr=!1);function o1(s){wr=s}function t0(){return wr}const i0=Symbol("disposable");function n0(s,e){s&&(s[i0]=e,ir&&console.warn("Set disposable",e,s))}const s0=Symbol("disposed");function r1(s){return s[s0]===!0}function we(s){if(s){if(s[i0]===!1){ir&&console.warn("Object is marked as not disposable",s);return}if(typeof s=="object"&&(s[s0]=!0),s instanceof c.Scene)we(s.environment),we(s.background),we(s.customDepthMaterial),we(s.customDistanceMaterial);else if(s instanceof c.SkinnedMesh)we(s.geometry),we(s.material),we(s.skeleton),we(s.bindMatrix),we(s.bindMatrixInverse),we(s.customDepthMaterial),we(s.customDistanceMaterial),s.visible=!1;else if(s instanceof c.Mesh)we(s.geometry),we(s.material),we(s.customDepthMaterial),we(s.customDistanceMaterial),s.visible=!1;else if(s instanceof c.Object3D)s.visible=!1;else if(s instanceof c.BufferGeometry){Gr(s);for(const e of Object.keys(s.attributes)){const t=s.attributes[e];we(t)}}else if(s instanceof c.BufferAttribute||s instanceof c.InterleavedBufferAttribute)ir&&console.warn("BufferAttribute dispose not supported",s.count);else if(s instanceof Array)for(const e of s)e instanceof c.Material&&we(e);else if(s instanceof c.Material){Gr(s);for(const t of Object.keys(s)){const i=s[t];i instanceof c.Texture&&we(i)}const e=s.uniforms;if(e)for(const t of Object.keys(e)){const i=e[t];i instanceof c.Texture?we(i):i instanceof c.Uniform$1&&we(i.value)}}else s instanceof c.Texture?(Gr(s),Gr(s.source),s.source?.data instanceof ImageBitmap&&Gr(s.source.data)):s instanceof c.Skeleton?(Gr(s.boneTexture),s.boneTexture=null):s instanceof c.Bone||!(s instanceof c.Object3D)&&ir&&console.warn("Unknown object type",s)}}function Gr(s){s&&((ir||e0()||mu)&&console.warn("🧨 FREE",s),s instanceof ImageBitmap||"dispose"in s&&typeof s.dispose=="function"&&s.dispose())}function a1(s){}const l1=new Set;function eg(s,e,t=null,i){if(i||(i=l1,i.clear()),!s)return i;const n=s[_c];if(n)for(const o of n)i.has(o)||t?.call(null,o)!==!1&&(i.add(o),e&&eg(o,!0,t,i));return i}function c1(s){return s[Ul]}const ir=x("debugresourceusers")||x("debugmemory"),_c=Symbol("needle-resource-users"),Ul=Symbol("needle-resource-users-count");function Bt(s,e){uu(s,e,function(t,i){wr&&!Ia.raycasting&&(zd(_c,this,t,!1),zd(_c,this,i,!0))})}wr&&(Bt(c.Mesh.prototype,"material"),Bt(c.Mesh.prototype,"geometry"),Bt(c.Material.prototype,"map"),Bt(c.Material.prototype,"bumpMap"),Bt(c.Material.prototype,"alphaMap"),Bt(c.Material.prototype,"normalMap"),Bt(c.Material.prototype,"displacementMap"),Bt(c.Material.prototype,"roughnessMap"),Bt(c.Material.prototype,"metalnessMap"),Bt(c.Material.prototype,"emissiveMap"),Bt(c.Material.prototype,"specularMap"),Bt(c.Material.prototype,"envMap"),Bt(c.Material.prototype,"lightMap"),Bt(c.Material.prototype,"aoMap"),Bt(c.Material.prototype,"gradientMap"));function h1(s){if(wr===!1)return;const e=s[_c];if(e)for(const t of e)zd(_c,t,s,!1)}wr&&uu(c.Material.prototype,"dispose",function(){h1(this)});let zp=0;function zd(s,e,t,i){if(zp>0)return;if(Array.isArray(t)){for(const o of t)zd(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[Ul]||0;o+=1,t[Ul]=o,ir&&console.warn(`🟢 Added user of "${t.type}"`,e,t,o,"users:",n)}}else if(e&&n.has(e)){n.delete(e);let o=t[Ul]||0;o>0&&(o-=1,t[Ul]=o),ir&&console.warn(`🔴 Removed user of "${t.type}"`,e,t,o,"users:",n),o<=0&&(xa.isLoading(t)||(mu&&console.warn(`🔴 Removed all user of "${t.type}"`,t),e0()&&we(t)))}t[s]=n}try{uu(c.WebGLRenderer.prototype,"render",function(){zp++},function(){zp--})}catch(s){console.warn("Could not wrap WebGLRenderer.render",s)}const M_=x("debugcomponentevents");class gu{static eventListeners=new Map;static addComponentLifecylceEventListener(e,t){this.eventListeners.has(e)&&this.eventListeners.set(e,[]);let i=this.eventListeners.get(e);i||(i=[]),i.push(t),this.eventListeners.set(e,i),M_&&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(M_&&console.log("Dispatching event "+e,i),!!i)for(const n of i)n(t)}}const bc=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),o0=Symbol("isUsingInstancing"),r0=Symbol("instancingRenderer"),zl=Symbol("instancingAutoUpdateBounds");class Ni{static isUsingInstancing(e){return e[o0]===!0}static getRenderer(e){return e[r0]||null}setAutoUpdateBounds(e,t){const i=Ni.getRenderer(e);i&&(i[zl]=t)}static markDirty(e,t=!0){if(e&&(this.isUsingInstancing(e)&&(e[bc]=!0,e.matrixWorldNeedsUpdate=!0),t))for(const i of e.children)Ni.markDirty(i,!0)}}const tg={experimentalSmartHierarchyUpdate:!1};function tc(s,e){try{e||s()}catch(t){return console.error(t),!1}return!0}const Np=x("debugnewscripts"),d1=x("debughierarchy"),Ce=[];function u1(){return Ce.length>0}function Nd(s){if(Np&&console.log("Register new components",s.new_scripts.length,[...s.new_scripts],s.alias?"element: "+s.alias:s.hash,s),s.new_scripts_pre_setup_callbacks.length>0){for(const e of s.new_scripts_pre_setup_callbacks)e&&e();s.new_scripts_pre_setup_callbacks.length=0}if(!(s.new_scripts.length<=0)){Ce.length=0,s.new_scripts.length>0&&Ce.push(...s.new_scripts),s.new_scripts.length=0;for(let e=0;e<Ce.length;e++)try{const t=Ce[e];if(t.isComponent!==!0){(A()||Np)&&console.error(`Registered script is not a Needle Engine component.
|
|
178
|
-
The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
|
|
179
|
-
`,t),Ce.splice(e,1),e--;continue}if(t.destroyed)continue;if(!t.gameObject){console.warn(`Component can not be initialized: no GameObject assigned.
|
|
180
|
-
Did you add and remove a component in the same frame?`),Ce.splice(e,1),e--;continue}t.context=s,ic(t.gameObject),ig(t,s)}catch(t){console.error(t),as(Ce[e],s),Ce.splice(e,1),e--}for(let e=0;e<Ce.length;e++)try{const t=Ce[e];if(t.destroyed){as(Ce[e],s),Ce.splice(e,1),e--;continue}if(t.registering)try{t.registering()}catch(i){console.error(i)}t.__internalAwake!==void 0&&(t.gameObject||console.error("Calling awake for a component without a GameObject",t,t.gameObject),ic(t.gameObject),t.activeAndEnabled&&tc(t.__internalAwake.bind(t)))}catch(t){console.error(t),as(Ce[e],s),Ce.splice(e,1),e--}for(let e=0;e<Ce.length;e++)try{const t=Ce[e];if(t.destroyed||t.enabled===!1||(ic(t.gameObject),t.activeAndEnabled===!1))continue;t.__internalEnable!==void 0&&(t.enabled=!0,tc(t.__internalEnable.bind(t)))}catch(t){console.error(t),as(Ce[e],s),Ce.splice(e,1),e--}for(let e=0;e<Ce.length;e++)try{const t=Ce[e];if(t.destroyed||!t.gameObject)continue;s.new_script_start.push(t)}catch(t){console.error(t),as(Ce[e],s),Ce.splice(e,1),e--}Ce.length=0;for(const e of s.new_scripts_post_setup_callbacks)e&&e();s.new_scripts_post_setup_callbacks.length=0}}function f1(s){s&&(s.__internalDisable(!0),as(s,s.context))}function a0(s,e){for(let t=0;t<s.new_script_start.length;t++)try{const i=s.new_script_start[t];if(e!==void 0&&i.gameObject!==e||i.destroyed||i.activeAndEnabled===!1)continue;tc(i.__internalAwake.bind(i)),i.enabled&&(tc(i.__internalEnable.bind(i)),tc(i.__internalStart.bind(i)),s.new_script_start.splice(t,1),t--)}catch(i){console.error(i),as(s.new_script_start[t],s),s.new_script_start.splice(t,1),t--}}function ig(s,e){e.scripts.indexOf(s)===-1&&(e.scripts.push(s),s.earlyUpdate&&e.scripts_earlyUpdate.push(s),s.update&&e.scripts_update.push(s),s.lateUpdate&&e.scripts_lateUpdate.push(s),s.onBeforeRender&&e.scripts_onBeforeRender.push(s),s.onAfterRender&&e.scripts_onAfterRender.push(s),s.onPausedChanged&&e.scripts_pausedChanged.push(s),If(s,null)&&e.new_scripts_xr.push(s),If(s,"immersive-vr")&&e.scripts_immersive_vr.push(s),If(s,"immersive-ar")&&e.scripts_immersive_ar.push(s))}function as(s,e){Ei(s,e.new_scripts),Ei(s,e.new_script_start),Ei(s,e.scripts),Ei(s,e.scripts_earlyUpdate),Ei(s,e.scripts_update),Ei(s,e.scripts_lateUpdate),Ei(s,e.scripts_onBeforeRender),Ei(s,e.scripts_onAfterRender),Ei(s,e.scripts_pausedChanged),Ei(s,e.new_scripts_xr),Ei(s,e.scripts_immersive_vr),Ei(s,e.scripts_immersive_ar),e.stopAllCoroutinesFrom(s)}function Ei(s,e){const t=e.indexOf(s);t>=0&&e.splice(t,1)}function If(s,e){if(s){const t=s;if(t.onBeforeXR||t.onEnterXR||t.onUpdateXR||t.onLeaveXR||t.onXRControllerAdded||t.onXRControllerRemoved)return!(e!=null&&t.supportsXR?.(e)===!1)}return!1}let Vp=!0;function jf(){Vp=!0}function pd(s,e=!1){if(tg.experimentalSmartHierarchyUpdate){if(!e&&!Vp)return;Vp=!1}if(s||(s=ce.Current.scene),!s){console.trace("Invalid call - no current context.");return}const t=Ga(s);$p(s,t,!0)||(Np||A()?console.error(`Error updating hierarchy
|
|
181
|
-
Do you have circular references in your project? <a target="_blank" href="https://docs.needle.tools/circular-reference"> Click here for more information.`,s):console.error('Failed to update active state in hierarchy of "'+s.name+'"',s),console.warn(" ↑ this error might be caused by circular references. Please make sure you don't have files with circular references (e.g. one GLB 1 is loading GLB 2 which is then loading GLB 1 again)."))}function $p(s,e,t,i=0){if(i>1e3)return console.warn("Hierarchy is too deep (> 1000 level) - will abort updating active state"),!1;const n=Ga(s);if(e&&(e=n,e&&s.parent&&i===0)){const l=s.parent;e=l[jn],e===void 0&&(l instanceof c.Scene||(e=!0))}const r=s[jn]!==e;if(r){s[jn]=e,d1&&console.warn("ACTIVE CHANGE",{name:s.name,activeSelf:n,visible:s.visible,activeInHierarchy:e,changed:r,go:s});{const l=s.userData?.components;if(l)for(let h=l.length-1,d=-1;h>d;h--){const u=l[h];if(e){if(u?.enabled){try{u.__internalAwake()}catch(p){console.error(p)}u.enabled&&u.__internalEnable()}}else u&&u.__didAwake&&u.enabled&&(u.__didEnable=!1,u.onDisable())}}}const a=s.children;if(a){if(!r&&!e){let h=!0;for(let d=0,u=a.length;d<u;d++){const p=a[d];p[jn]!==!1&&$p(p,!1,t,i+1)===!1&&(h=!1)}return h}let l=!0;for(let h=0,d=a.length;h<d;h++)$p(a[h],e,t,i+1)===!1&&(l=!1);return l}return!0}function ic(s){if(!s){console.error("GO is null");return}let e=!0,t=!1,i=s;for(;i;){if(i.type==="Scene"&&(t=!0),!Ga(i)){e=!1;break}i=i.parent}s[jn]=e&&t}const md=new Map,l0=Symbol("prewarmFlag"),Wp=Symbol("waitingForPrewarm"),Gp=x("debugprewarm");function p1(s,e){if(!s||s[l0]===!0||s[Wp]===!0)return;md.has(e)||md.set(e,[]),s[Wp]=!0,md.get(e).push(s),Gp&&console.debug("register prewarm",s.name)}let k_=null,R_=null;function m1(s){if(!s)return;const e=md.get(s);if(!e?.length)return;const t=s.mainCamera;if(t){Gp&&console.log("prewarm",e.length,"objects",[...e]);const i=s.renderer;if(i.compile){const n=s.scene;i.compile(n,t),k_??=new c.WebGLCubeRenderTarget(64),R_??=new c.CubeCamera(.001,9999999,k_),R_.update(i,n);for(const o of e)o[l0]=!0,o[Wp]=!1;e.length=0,Gp&&console.log("prewarm done")}}}ce.registerCallback(le.ContextCreated,s=>{const e=s.context;f0(e),h0(e)});const Vd=x("debugcomponents"),E_="eff8ba80-635d-11ec-90d6-0242ac120003";class wt{get seed(){return this._seed}set seed(e){this._seed=e}_originalSeed;_seed;constructor(e){typeof e=="string"&&(e=wt.hash(e)),this._originalSeed=e,this._seed=e}reset(){this._seed=this._originalSeed}generateUUID(e){if(typeof e=="string")return ae.v5(e,E_);const t=this._seed;return this._seed-=1,ae.v5(t.toString(),E_)}initialize(e){typeof e=="string"?this._seed=wt.hash(e):this._seed=e}static createFromString(e){return new wt(this.hash(e))}static hash(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);return t}}var c0=(s=>(s.NewInstanceCreated="new-instance-created",s.InstanceDestroyed="instance-destroyed",s))(c0||{});class g1{guid;dontSave;constructor(e){this.guid=e}}function zc(s,e,t=!0,i){if(!s)return;const n=s;if(bi(s,t),!e){console.warn("Can not send destroy: No networking connection provided",s.guid);return}if(!e.isConnected){A()&&console.debug("Can not send destroy: not connected",s.guid);return}let o=s.guid;if(!o&&n.uuid&&(o=n.uuid),!o){console.warn("Can not send destroy: failed to find guid",s);return}ng(o,e,i)}function ng(s,e,t){const i=new g1(s);t?.saveInRoom===!1&&(i.dontSave=!0),e.send("instance-destroyed",i,ln.Queued)}function h0(s){s.connection.beginListen("instance-destroyed",e=>{Vd&&console.log("[Remote] Destroyed",s.scene,e);const t=hg(e.guid,s.scene);t&&bi(t)})}class y1{filename;hash;size;constructor(e,t,i){this.filename=e,this.hash=t,this.size=i}}class d0{guid;originalGuid;seed;visible;hostData;dontSave;parent;position;rotation;scale;preventCreation=void 0;deleteStateOnDisconnect;constructor(e,t){this.originalGuid=e,this.guid=t}}function sg(s,e,t,i){const n=s;if(!n.guid)return console.warn("Can not instantiate: No guid",n),null;if(e.context||(e.context=U.Current),!e.context)return console.error("Missing network instantiate options / reference to network connection in sync instantiate"),null;const o=e?{...e}:null,{instance:r,seed:a}=_1(n,e);if(r){const l=r;if(l.guid){Vd&&console.log("[Local] new instance","gameobject:",r?.guid);const h=new d0(n.guid,l.guid);h.seed=a,e.deleteOnDisconnect===!0&&(h.deleteStateOnDisconnect=!0),o&&(o.position&&(Array.isArray(o.position)?h.position={x:o.position[0],y:o.position[1],z:o.position[2]}:h.position={x:o.position.x,y:o.position.y,z:o.position.z}),o.rotation&&(o.rotation instanceof c.Euler?o.rotation=new c.Quaternion().setFromEuler(o.rotation):o.rotation instanceof Array&&(o.rotation=new c.Quaternion().fromArray(o.rotation)),h.rotation={x:o.rotation.x,y:o.rotation.y,z:o.rotation.z,w:o.rotation.w}),o.scale&&(Array.isArray(o.scale)?h.scale={x:o.scale[0],y:o.scale[1],z:o.scale[2]}:h.scale={x:o.scale.x,y:o.scale.y,z:o.scale.z})),h.position||(h.position={x:l.position.x,y:l.position.y,z:l.position.z}),h.rotation||(h.rotation={x:l.quaternion.x,y:l.quaternion.y,z:l.quaternion.z,w:l.quaternion.w}),h.scale||(h.scale={x:l.scale.x,y:l.scale.y,z:l.scale.z}),h.visible=n.visible,o?.parent&&(typeof o.parent=="string"?h.parent=o.parent:h.parent=o.parent.guid),h.hostData=t,i===!1&&(h.dontSave=!0),!e?.context?.connection&&A()&&console.debug("Object will be instantiated but it will not be synced: not connected",n.guid),e.context.connection.isInRoom&&ia.push(new WeakRef(l)),e?.context?.connection.send("new-instance-created",h)}else console.warn("Missing guid, can not send new instance event",l)}return r}function u0(){return Math.random()*9999999}const ia=new Array;function f0(s){s.connection.beginListen("new-instance-created",async e=>{const t=await b1(e.originalGuid,s.scene);if(e.preventCreation===!0)return;if(!t){console.warn("could not find object that was instantiated: "+e.guid);return}const i=new gn;e.position&&(i.position=new c.Vector3(e.position.x,e.position.y,e.position.z)),e.rotation&&(i.rotation=new c.Quaternion(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w)),e.scale&&(i.scale=new c.Vector3(e.scale.x,e.scale.y,e.scale.z)),i.parent=e.parent,e.seed&&(i.idProvider=new wt(e.seed)),i.visible=e.visible,i.context=s,Vd&&s.alias&&console.log("[Remote] instantiate in: "+s.alias);const n=uo(t,i);ia.push(new WeakRef(n)),n&&(e.parent==="scene"&&s.scene.add(n),Vd&&console.log("[Remote] new instance","gameobject:",n?.guid,t))}),s.connection.beginListen("left-room",()=>{ia.length>0&&console.debug(`Left networking room, cleaning up ${ia.length} instantiated objects`);for(const e of ia){const t=e.deref();t&&t.destroy()}ia.length=0})}function _1(s,e){const t=u0(),i=e??new gn;i.idProvider=new wt(t);const n=uo(s,i);return{seed:t,instance:n}}const p0={};function m0(s,e){p0[s]=e}async function b1(s,e){const t=p0[s];if(t!=null){const i=await t(s);if(i)return i}return g0(s,e)}function g0(s,e){if(e===null||!s)return null;if(e.guid===s)return e;if(e.children)for(const t of e.children){const i=g0(s,t);if(i)return i}return null}const Nc=x("gizmos"),rt=x("debugextension"),Bf=x("debugtypes");class v1{_types=new Map;_reverseTypes=new Map;constructor(){Bf&&console.warn("TypeStore: Created",this)}add(e,t){Bf&&console.warn("ADD TYPE",e);const i=this._types.get(e);i?Bf&&i!==t&&console.warn("Type name exists multiple times in your project and may lead to runtime errors:",e):(this._types.set(e,t),this._reverseTypes.set(t,e))}get(e){return this._types.get(e)||null}getKey(e){return this._reverseTypes.get(e)||null}}const w1=Symbol("BuiltInType"),P=new v1,og=function(s){P.get(s.name)||P.add(s.name,s)},rg=x("debugresolvedependencies"),x1=["/extensions/","extensions/"],S1=[{prefix:"/nodes/",dependencyName:"node"},{prefix:"/meshes/",dependencyName:"mesh"},{prefix:"/materials/",dependencyName:"material"},{prefix:"/textures/",dependencyName:"texture"},{prefix:"/animations/",dependencyName:"animation"},{prefix:"nodes/",dependencyName:"node"},{prefix:"meshes/",dependencyName:"mesh"},{prefix:"materials/",dependencyName:"material"},{prefix:"textures/",dependencyName:"texture"},{prefix:"animations/",dependencyName:"animation"}];async function ag(s,e){rg&&console.log(s,e);const t=[];Hp(S1,s,e,t);const i=await Promise.all(t);return typeof e=="string"&&i.length===1?i[0]:i}function y0(s,e){return!s||!e?!1:s["needle:identifier"]!=null&&e["needle:identifier"]!=null?s["needle:identifier"]===e["needle:identifier"]:!1}function C1(s,e){s["needle:identifier"]=e}function Hp(s,e,t,i){if(typeof t=="object"&&t!==void 0&&t!==null)for(const n of Object.keys(t)){const o=t[n];if(typeof o=="string"){const r=T_(e,o);if(r!=null)typeof r.then=="function"?i.push(r.then(a=>t[n]=a)):t[n]=r;else{const a=A_(s,e,o);if(a){i.push(a.then(l=>(t[n]=l,l)));continue}}}else if(Array.isArray(o))for(let r=0;r<o.length;r++){const a=o[r],l=T_(e,a);if(l!=null){typeof l.then=="function"?i.push(l.then(h=>o[r]=h)):o[r]=l;continue}for(const h of s){const d=_0(h.prefix,a);if(d>=0){rg&&console.log(h,d,h.dependencyName),i.push(e.getDependency(h.dependencyName,d).then(u=>o[r]=u));break}}typeof a=="object"&&Hp(s,e,a,i)}else typeof o=="object"&&Hp(s,e,o,i)}else if(typeof t=="string"){const n=A_(s,e,t);n&&i.push(n)}}function T_(s,e){if(s&&s.plugins&&typeof e=="string"){for(const t of x1)if(e.startsWith(t)){let i=e.substring(t.length);const n=i.indexOf("/");n>=0&&(i=i.substring(0,n));const o=s.plugins[i];if(rt&&console.log(i,o),typeof o?.resolve=="function"){const r=e.substring(t.length+i.length+1);return o.resolve(s,r)}break}}return null}function A_(s,e,t){for(const i of s){const n=_0(i.prefix,t);if(n>=0)return rg&&console.warn("GET DEPENDENCY",i,n,i.dependencyName),e.getDependency(i.dependencyName,n)}return null}function _0(s,e){if(typeof e=="string"&&e.startsWith(s)){const t=e.substring(s.length),i=Number.parseInt(t);if(i>=0)return i}return-1}const Ff="NEEDLE_persistent_assets";function P1(s){return s?.___persistentAsset===!0}class O1{get name(){return Ff}parser;constructor(e){this.parser=e}async afterRoot(e){if(!this.parser?.json?.extensions)return;const t=this.parser.json.extensions[Ff];if(!t)return;rt&&console.log(t);const i=new Array;for(const n of t?.assets){const o=ag(this.parser,n);o&&i.push(o)}await Promise.all(i)}resolve(e,t){const i=Number.parseInt(t);if(i>=0){rt&&console.log(t);const n=e.json.extensions[Ff];if(n){const o=n?.assets[i];if(o&&typeof o=="object"){o.___persistentAsset=!0;const r=o.__type;r&&P.get(r)}return o}}return null}}const En=x("debugserializer");class M1{register(e,t){if(this.typeMap.has(e)){const i=this.typeMap.get(e);if(i===t)return;En&&console.warn("Type: "+e+" is already registered",t,i)}En&&console.log("Register type serializer",t.name,t,e),this.typeMap.set(e,t)}typeMap=new Map;getSerializer(e){if(e)return this.typeMap.get(e)}getSerializerForConstructor(e,t=0){if(t>20)return;if(!e||!e.constructor){En&&console.log("invalid type");return}const i=e.name,n=this.getSerializer(e);if(n!==void 0)return En&&console.log("FOUND SERIALIZER",n?.name,e.name,e.constructor.name,"for type: "+i,n,e,this.typeMap),n;const o=Object.getPrototypeOf(e);if(o&&o!==e){const r=this.getSerializerForConstructor(o,++t);if(r){const a=o.constructor||o.prototype;En&&console.log("FOUND SERIALIZER(in constructor) "+a.constructor.name,a.name,a,r),this.register(a,r)}return r}En&&console.warn("No serializer found for "+i,e,e.name,e.constructor.name)}}const $d=new M1;class Hi{name;constructor(e,t){if(this.name=t,Array.isArray(e))for(const i of e)$d.register(i,this);else $d.register(e,this)}}class k1{isDevMode=yi();cache={};registerDefinedKeys(e,t){if(this.isDevMode&&this.cache[e]===void 0){this.cache[e]=Object.keys(t);const i=t;i.$serializedTypes&&Object.keys(i.$serializedTypes)&&this.cache[e].push(...Object.keys(i.$serializedTypes)),En&&console.log("registerDefinedKeys for "+e,this.cache[e],t)}}getDefinedKey(e,t){return this.cache[e]===void 0?!1:this.cache[e].includes(t)}}class lg{root;gltf;gltfId;object;target;nodeId;nodeToObject;objectToNode;context;path;type;serializable;implementationInformation;constructor(e){this.root=e}}function b0(s,e){const t=s.$serializedTypes;if(t===void 0)return null;const i={};for(const o in t){const r=s[o];if(r!=null&&typeof r=="object"){const a=$d.getSerializerForConstructor(r);if(a){i[o]=a.onSerialize(r,e);continue}}i[o]=r}function n(o){const r=P._types;for(const[a,l]of r)if(l===s.constructor)return a;return o.__name||o.constructor.name}return i.name=n(s),typeof s.guid=="string"&&(i.guid=s.guid),i}const gd=[];function v0(s,e){if(!s)return e;typeof s.$serializedTypes=="object"&&(e||(e={}),Object.assign(e,s.$serializedTypes));const t=Object.getPrototypeOf(s);return v0(t,e)}function Wd(s,e,t){if(!s)return!1;if(t.target=s,s.onBeforeDeserialize!==void 0){const n=s.onBeforeDeserialize(e,t);if(typeof n=="boolean")return n}const i=v0(s);if(e){if(typeof e.guid=="string"&&(s.guid=e.guid),i)for(const n in i){let o=function(l){const d=l.type;return d?qp(a,d,t,void 0,s[n]):qp(a,l,t,void 0,s[n])};const r=i[n],a=e[n];if(En&&console.log(n,a,s,r),!(s[n]!==void 0&&a===void 0)&&(t.type=void 0,t.path=n,t.serializable=r,!(s.onBeforeDeserializeMember!==void 0&&s.onBeforeDeserializeMember(n,a,t)===!0))){if(r===null)s[n]=a;else{if(Array.isArray(r))for(let l=0;l<r.length;l++){const h=r[l],d=o(h);if(d!==void 0||l===r.length-1){s[n]=d;break}}else s[n]=o(r);gd.length=0}s.onAfterDeserializeMember!==void 0&&s.onAfterDeserializeMember(n,a,t)}}T1(s,e)}return E1(s,e,t.implementationInformation),s.onAfterDeserialize!==void 0&&s.onAfterDeserialize(e,t),!0}const R1=x("noerrors");function E1(s,e,t){if(R1||!e||!yi()||!s||s.constructor&&s.constructor[w1]===!0)return;const i=s.constructor?.name,n=Object.getOwnPropertyNames(e);for(const o of n){if(o==="sourceId")continue;const r=s[o];if(r==null)continue;const a=e[o];if(t?.getDefinedKey(i,o)===!1){const l=o.charAt(0).toUpperCase()+o.slice(1);t.getDefinedKey(i,l)&&(Yo(gi.Warn,'<strong>Please rename</strong> "'+l+'" to "'+o+'" in '+i),console.warn('Please use lowercase for field: "'+l+'" in '+i,a,s));continue}if(a!=null){if(typeof a=="object"&&(r===void 0||!r.isObject3D)){if(typeof a.node=="number"||typeof a.guid=="string"){if(a.could_not_resolve)continue;if(!(r!==void 0&&Object.keys(r).length>1)){Yo(gi.Warn,`<strong>Missing serialization for object reference!</strong>
|
|
182
|
-
|
|
183
|
-
Please change to:
|
|
184
|
-
@serializable(Object3D)
|
|
185
|
-
${o}? : Object3D;
|
|
186
|
-
|
|
187
|
-
in ${i}.ts
|
|
188
|
-
<a href="https://docs.needle.tools/serializable" target="_blank">See documentation</a>`),console.warn(i,o,s[o],s);continue}}else if(!Array.isArray(r)){const l=r.constructor?.name;if(l==="Object"&&!r.constructor["did_warn:missing_serializable"]){r.constructor["did_warn:missing_serializable"]=!0;const h='You might be missing a @serializable(Type) decorator for field "'+o+'" in '+i+".ts";console.warn(h+`
|
|
189
|
-
${o}:`,a,l),Yo(gi.Warn,"Dev Warning: Are you missing a type in @serializable? Please check the browser console for details")}}}if(typeof r=="string"&&typeof a=="string"&&(a.endsWith(".gltf")||a.endsWith(".glb"))){Yo(gi.Warn,`<strong>Missing serialization for object reference!</strong>
|
|
190
|
-
|
|
191
|
-
Please change to:
|
|
192
|
-
@serializable(AssetReference)
|
|
193
|
-
${o}? : AssetReference;
|
|
194
|
-
|
|
195
|
-
in script ${i}.ts
|
|
196
|
-
<a href="https://docs.needle.tools/serializable" target="_blank">documentation</a>`),console.warn(i,o,s[o],s);continue}}}}function T1(s,e){for(const t of Object.keys(e)){const i=e[t];if(typeof i=="object"&&i!==null&&i!==void 0){const n=s[t];if(!n){En&&console.log(t,"is undefined on",s);continue}for(const o of Object.keys(i))if(n[o]===void 0&&D_(i[o])&&!D_(n)){const a=A1(n,o);if(a&&(a?.writable===void 0||a?.writable===!1)&&a.set===void 0){En&&console.warn('Property is not writable "'+o+'"',n,a,i[o],n[o]);continue}n[o]=i[o]}}}}function A1(s,e){for(;s;){const t=Object.getOwnPropertyDescriptor(s,e);if(t)return t;s=Object.getPrototypeOf(s)}}function D_(s){switch(typeof s){case"number":case"string":case"boolean":return!0}return!1}function qp(s,e,t,i,n){let o=typeof e=="function"&&e.prototype===void 0,r=e;if(o)try{if(r=e?.call(e,n),o=!1,r==null)return}catch(d){console.error("Error in callback",d,s)}if(t.type=r,!o&&n&&(n instanceof c.Material||n instanceof c.Mesh||n instanceof c.BufferGeometry||n instanceof c.AnimationClip))return n;if(i||(i={serializer:$d.getSerializerForConstructor(r)}),n&&typeof n=="object"&&P1(n)){if(n.__concreteInstance)return n.__concreteInstance;const d=n;if(!d.$serializedTypes&&r.prototype.$serializedTypes&&(d.$serializedTypes=r.prototype.$serializedTypes),d.$serializedTypes&&Wd(d,s,t),n&&r!==void 0)try{let u=null;i.serializer&&(u=i.serializer.onDeserialize(s,t)),u||(u=new r,rt&&console.log("Create concrete instance for persistent asset",n,"instance:",u),ja(u,n)),n.__concreteInstance=u,n=u}catch(u){console.error("Error creating instance or creating values on instance",u,n,r)}return n}if(Array.isArray(s)){const d=[];for(let u=0;u<s.length;u++){const p=s[u],m=qp(p,e,t,i,p);d.push(m)}return d}const a=i?.serializer;if(a)return a.onDeserialize(s,t);if(n instanceof c.Texture)return n;let l;if(s&&(s.isMaterial||s.isTexture||s.isObject3D||s instanceof c.AnimationClip))l=s;else{if(s===void 0)return;if(s===null&&(r===c.Material||r===c.Texture||r===c.Mesh||r===c.AnimationClip))return null;try{l=new r(...D1(s))}catch(d){console.error("Error creating "+t.path,t.target,d);return}}const h=l;return h.$serializedTypes&&Wd(h,s,t),l}function D1(s){if(gd.length=0,typeof s=="object"&&s!==null&&s!==void 0)for(const e of Object.keys(s))gd.push(s[e]);return gd}const Xp=Symbol("assigned component properties");function ja(s,e,t,i){if(e==null||s==null)return;s[Xp]=!0;const n=s.constructor?.name??"unknown";t?.registerDefinedKeys(n,s);for(const o of Object.keys(e)){const r=L1(s,o);if(typeof r?.value!="function"&&(!r||r.writable===!0||r.set!==void 0)){const a=e[o],l=s[o];s[o]=a,i?.onAssigned&&i.onAssigned(s,o,l,a)}}delete s[Xp]}function L1(s,e){let t;do t=Object.getOwnPropertyDescriptor(s,e);while(!t&&(s=Object.getPrototypeOf(s)));return t}const w0=Symbol("customVisibilityFlag");function ls(s,e){s.layers[w0]=e}const L_=Symbol("DidPatchLayers");function I1(){const s=c.Layers.prototype;if(s[L_])return;s[L_]=!0;const e=s.test;s.test=function(t){return this[w0]===!1?!1:e.call(this,t)}}I1();Object.defineProperty(c.PerspectiveCamera.prototype,"fov",{get:function(){return this._fov},set:function(s){const e=s!==this._fov;this._fov=s,e&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0});Object.defineProperty(c.PerspectiveCamera.prototype,"near",{get:function(){return this._near},set:function(s){const e=s!==this._near;this._near=s,e&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0});Object.defineProperty(c.PerspectiveCamera.prototype,"far",{get:function(){return this._far},set:function(s){const e=s!==this._far;this._far=s,e&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0});const x0=new Map;function S0(s,e){if(!s)return;if(!e){console.warn("No prototype found",s,s.prototype,s.constructor);return}const t=x0.get(e);t&&t.apply(s)}function C0(s){const e=j1(s.prototype);x0.set(s,e)}function j1(s){return new B1(s)}class B1{$symbol;extensions;descriptors;constructor(e){this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(e),this.descriptors=new Array;for(let t=0;t<this.extensions.length;t++){const i=this.extensions[t],n=Object.getOwnPropertyDescriptor(e,i);n&&this.descriptors.push(n)}}apply(e){if(!e[this.$symbol]){e[this.$symbol]=!0;for(let t=0;t<this.extensions.length;t++){const i=this.extensions[t],n=this.descriptors[t];n&&Object.defineProperty(e,i,n)}}}}const F1=x("debuggetcomponent"),I_=()=>F1||globalThis.NEEDLE_DEBUG_GETCOMPONENT===!0;function U1(s){return s==null||s.isObject3D?s:s.object&&s.object.isObject3D?s.object:s}function cg(s,e){if(!s||!s.userData.components)return e;const t=s.userData.components.indexOf(e);return t<0||(gu.dispatchComponentLifecycleEvent("removing-component",e),e.gameObject=null,s.userData.components.splice(t,1)),e}function Vc(s,e,t){const i=xr(s,e);return i||cn(s,e,t)}const P0=new wt("addComponentIdProvider");function nr(s,e,t=!0){s.userData||(s.userData={}),s.userData.components||(s.userData.components=[]),s.userData.components.push(e),e.gameObject=s,(e.guid===void 0||e.guid==="invalid")&&(e.guid=P0.generateUUID()),_u(s),Su(e,e.context);try{t&&e.__internalAwake&&(ic(s),e.activeAndEnabled&&e.__internalAwake()),gu.dispatchComponentLifecycleEvent("component-added",e)}catch(i){console.error(i)}return e}function cn(s,e,t,i){if(typeof e=="function"){const n=new e;t&&n.__internalNewInstanceCreated(t);let o=!0;return i?.callAwake!=null&&(o=i.callAwake),nr(s,n,o)}if(e.destroyed)return console.warn("Can not move/add a destroyed component",e),e;if(e.gameObject===s)return e;if(e.gameObject&&e.gameObject.userData?.components){const n=e.gameObject.userData.components.indexOf(e);e.gameObject.userData.components.splice(n,1)}if(s.userData||(s.userData={}),!s.userData.components)s.userData.components=[];else if(s.userData.components.includes(e))return e;return s.userData.components.push(e),e.gameObject=s,(e.guid===void 0||e.guid==="invalid")&&(e.guid=P0.generateUUID()),t&&e._internalInit(t),Su(e,e.context),e}function O0(s){if(s.gameObject&&s.gameObject.userData.components){const e=s.gameObject.userData.components.indexOf(s);s.gameObject.userData.components.splice(e,1)}s.__internalDisable&&s.__internalDisable(),as(s,s.context??U.Current),s.destroy(),s.gameObject=null}let j_=!1;function M0(s,e,t){if(s==null)return null;if(!s.isObject3D)return console.error("Object is not object3D"),null;if(!s?.userData?.components||(typeof e=="string"&&(j_||(j_=!0,console.warn(`Accessing components by name is not supported.
|
|
197
|
-
Please use the component type instead. This may keep working in local development but it will fail when bundling your application.
|
|
198
|
-
|
|
199
|
-
You can import other modules your main module to get access to types
|
|
200
|
-
or if you use npmdefs you can make types available globally using globalThis:
|
|
201
|
-
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis`,e))),I_()&&console.log("[onGetComponent] FIND",e),e==null))return null;for(let i=0;i<s.userData.components.length;i++){const n=s.userData.components[i];let o=Object.getPrototypeOf(n);for(;o;){if(o===e.prototype)if(I_()&&console.log("[onGetComponent] MATCH BY PROTOYPE",o),t)t.push(n);else return n;o=Object.getPrototypeOf(o)}}return t||null}function xr(s,e){const t=M0(s,e);return t?Array.isArray(t)?t[0]:t:null}function $c(s,e,t,i=!0){return t||(t=[]),i&&(t.length=0),M0(s,e,t),t}function Wc(s,e,t=!1){if(t===!1&&s[jn]===!1)return null;const i=xr(s,e);if(t===!1&&(i?.enabled===!1||i?.activeAndEnabled===!1))return null;if(i)return i;for(let n=0;n<s?.children?.length;n++){const o=Wc(s.children[n],e,t);if(o)return o}return null}function $a(s,e,t,i=!0){t||(t=[]),i&&(t.length=0),$c(s,e,t,!1);for(let n=0;n<s?.children?.length;n++)$a(s.children[n],e,t,!1);return t}function vc(s,e,t=!1){if(!s)return null;if(Array.isArray(s)){for(let n=0;n<s.length;n++){const o=U1(s[n]),r=vc(o,e,t);if(r)return r}return null}const i=xr(s,e);return i||(s.parent?vc(s.parent,e,t):null)}function yu(s,e,t,i=!0){return t||(t=[]),i&&(t.length=0),s?($c(s,e,t,!1),s.parent?yu(s.parent,e,t,!1):t):t}function Wa(s,e=void 0,t=!0){if(!s)return null;if(!e&&(e=U.Current,!e))return console.error("Can not search object without any needle context or scene!!!"),null;let i=e;if(i.isScene||(i=e?.scene),!i)return null;const n=Wc(i,s,t);return n||null}function k0(s,e,t=void 0){if(!s)return e??[];if(e||(e=[]),e.length=0,!t&&(t=U.Current,!t))return console.error("Can not search object without any needle context or scene!!!"),e;"scene"in t&&(t=t.scene);const i=t;return i&&$a(i,s,e,!1),e}function _u(s){s&&s.isObject3D===!0&&S0(s,c.Object3D)}if(tg.experimentalSmartHierarchyUpdate){const s=c.Object3D.prototype.add;c.Object3D.prototype.add=function(...i){return jf(),s.apply(this,i)};const e=c.Object3D.prototype.attach;c.Object3D.prototype.attach=function(...i){return jf(),e.apply(this,i)};const t=c.Object3D.prototype.remove;c.Object3D.prototype.remove=function(...i){return jf(),t.apply(this,i)}}c.Object3D.prototype.SetActive=function(s){this.visible=s};c.Object3D.prototype.setActive=function(s){this.visible=s};c.Object3D.prototype.destroy=function(){bi(this)};c.Object3D.prototype.addComponent=function(s,e){return cn(this,s,e)};c.Object3D.prototype.addNewComponent=function(s,e){return cn(this,s,e)};c.Object3D.prototype.removeComponent=function(s){return cg(this,s)};c.Object3D.prototype.getOrAddComponent=function(s,e){return Vc(this,s,e)};c.Object3D.prototype.getComponent=function(s){return xr(this,s)};c.Object3D.prototype.getComponents=function(s,e){return $c(this,s,e)};c.Object3D.prototype.getComponentInChildren=function(s,e=!1){return Wc(this,s,e)};c.Object3D.prototype.getComponentsInChildren=function(s,e){return $a(this,s,e)};c.Object3D.prototype.getComponentInParent=function(s,e=!1){return vc(this,s,e)};c.Object3D.prototype.getComponentsInParent=function(s,e){return yu(this,s,e)};Object.getOwnPropertyDescriptor(c.Object3D.prototype,"activeSelf")||Object.defineProperty(c.Object3D.prototype,"activeSelf",{get:function(){return Ga(this)},set:function(s){nc(this,s)}});Object.getOwnPropertyDescriptor(c.Object3D.prototype,"raycastAllowed")||Object.defineProperty(c.Object3D.prototype,"raycastAllowed",{get:function(){return this.userData&&this.userData.raycastAllowed!==!1},set:function(s){const e=this;e.userData||(e.userData={}),e.userData.raycastAllowed=s}});Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldPosition")||Object.defineProperty(c.Object3D.prototype,"worldPosition",{get:function(){return this instanceof X.TransformControlsGizmo?Y(this.object):Y(this)},set:function(s){at(this,s)}});Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldQuaternion")||Object.defineProperty(c.Object3D.prototype,"worldQuaternion",{get:function(){return this instanceof X.TransformControlsGizmo?pe(this.object):pe(this)},set:function(s){dn(this,s)}});Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldRotation")||Object.defineProperty(c.Object3D.prototype,"worldRotation",{get:function(){return hu(this)},set:function(s){_v(this,s)}});Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldScale")||Object.defineProperty(c.Object3D.prototype,"worldScale",{get:function(){return je(this)},set:function(s){Ra(this,s)}});const z1=new c.Matrix4,N1=new c.Vector3(0,0,0),V1=new c.Vector3(0,1,0);Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldForward")||Object.defineProperty(c.Object3D.prototype,"worldForward",{get:function(){return F().set(0,0,1).applyQuaternion(pe(this))},set:function(s){const e=ei().setFromRotationMatrix(z1.lookAt(N1.set(0,0,0),s,V1.set(0,1,0)));this.worldQuaternion=e}});Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldRight")||Object.defineProperty(c.Object3D.prototype,"worldRight",{get:function(){return F().set(1,0,0).applyQuaternion(pe(this))}});Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldUp")||Object.defineProperty(c.Object3D.prototype,"worldUp",{get:function(){return F().set(0,1,0).applyQuaternion(pe(this))}});Object.getOwnPropertyDescriptor(c.Object3D.prototype,"contains")||Object.defineProperty(c.Object3D.prototype,"contains",{value:function(s){if(!s)return!1;if(this===s)return!0;for(const e of this.children)if(e.contains(s))return!0;return!1}});C0(c.Object3D);const yd=x("debuggetcomponent"),sr=x("debuginstantiate");class gn{idProvider;parent;keepWorldPosition;position;rotation;scale;visible;context;components;clone(){const e=new gn;return e.idProvider=this.idProvider,e.parent=this.parent,e.keepWorldPosition=this.keepWorldPosition,e.position=Array.isArray(this.position)?[...this.position]:this.position?.clone(),e.rotation=Array.isArray(this.rotation)?[...this.rotation]:this.rotation?.clone(),e.scale=Array.isArray(this.scale)?[...this.scale]:this.scale?.clone(),e.visible=this.visible,e.context=this.context,e.components=this.components,e}cloneAssign(e){this.idProvider=e.idProvider,this.parent=e.parent,this.keepWorldPosition=e.keepWorldPosition,this.position=Array.isArray(e.position)?[...e.position]:e.position?.clone(),this.rotation=Array.isArray(e.rotation)?[...e.rotation]:e.rotation?.clone(),this.scale=Array.isArray(e.scale)?[...e.scale]:e.scale?.clone(),this.visible=e.visible,this.context=e.context,this.components=e.components}}function Ga(s){return s.visible}function nc(s,e){return typeof e=="number"&&(e=e>.5),s.visible=e,s.visible}function R0(s){return s[jn]||bu(s)}function E0(s,e){s[o0]=e}function bu(s){return Ni.isUsingInstancing(s)}function hg(s,e){return ka(s,e,!0,!0)}const T0=Symbol("isDestroyed");function ur(s){return s[T0]}function A0(s,e){s[T0]=e}const Qp=Symbol("isDontDestroy");function na(s,e=!0){s[Qp]=e}const _d=[],bd=[];function bi(s,e=!0,t=!1){_d.length=0,bd.length=0,Yp(s,e,!0);for(const i of _d)i.gameObject=null,i.context=null;for(const i of bd)A0(i,!0),t&&we(i);bd.length=0,_d.length=0}function Yp(s,e=!0,t=!0){if(s==null)return;const i=s;if(i.isComponent){if(i[Qp])return;_d.push(i);const r=i.gameObject;i.__internalDisable(),i.__internalDestroy(),i.gameObject=r;return}if(s[Qp])return;const n=s;yd&&console.log(n),bd.push(n);const o=n.userData?.components;if(o!=null&&Array.isArray(o)){let r=o.length;for(let a=0;a<o.length;a++){const l=o[a];Yp(l,e,!1),o.length<r&&(r=o.length,a--)}}if(e&&n.children)for(const r of n.children)Yp(r,e,!1);t&&n.removeFromParent()}function fr(s,e,t=!0){return D0(s,e,t)}function*vu(s,e,t=!1,i=999,n=0){if(s?.userData.components&&!(n>i)){for(const o of s.userData.components)e&&o?.isComponent===!0&&o instanceof e?yield o:yield o;if(t===!0)for(const o of s.children)yield*vu(o,e,!0,i,n+1)}}function D0(s,e,t,i=0){if(s){if(s.isObject3D,i>1e3){console.warn("Failed to iterate components: too many levels");return}if(s.userData?.components)for(let n=0;n<s.userData.components.length;n++){const o=s.userData.components[n];if(o?.isComponent===!0){const r=e(o);if(r!==void 0)return r}}if(t&&s.children){const n=i+1;for(let o=0;o<s.children.length;o++){const r=s.children[o];if(!r)continue;const a=D0(r,e,t,n);if(a!==void 0)return a}}}}function uo(s,e){if("isAssetReference"in s)return s.instantiate(e??void 0);let t=null;e!=null&&(e.x!==void 0?(t=new gn,t.position=e):t=e);let i=U.Current;t?.context&&(i=t.context),yd&&i.alias&&console.log("context",i.alias),t&&!t.idProvider&&(t.idProvider=new wt(Date.now()));const n=[],o={},r={},a=L0(i,s,t,n,o,r);a&&(G1(a,o),W1(r,o)),yd&&(jd(s,!0),jd(a,!0));const l={};if(t?.components!==!1){for(const h in n){const d=n[h],u=d.guid;t&&t.idProvider&&(d.guid=t.idProvider.generateUUID(),l[u]=d.guid,yd&&console.log(d.name,d.guid)),Su(d,i),d.__internalNewInstanceCreated&&d.__internalNewInstanceCreated()}for(const h in n){const d=n[h];d.resolveGuids&&d.resolveGuids(l),d.enabled!==!1&&(d.enabled=!0)}Nd(i)}return a}function L0(s,e,t,i,n,o){if(!e||e[pi])return null;const r=e.userData;e.userData={};const a=e.children;e.children=[];const l=e.clone(!1);if(_u(l),e.userData=r,e.children=a,n[e.uuid]={original:e,clone:l},sr&&console.log("ADD",e,l),e.type==="SkinnedMesh"&&(o[e.uuid]={original:e,clone:l}),t?.visible!==void 0&&(l.visible=t.visible),t?.idProvider){l.uuid=t.idProvider.generateUUID();const d=l;d&&(d.guid=l.uuid)}e.animations&&e.animations.length>0&&(l.animations=[...e.animations]);const h=e.parent;if(h&&h.add(l),t?.position)if(Array.isArray(t.position)){const d=new c.Vector3;d.fromArray(t.position),l.worldPosition=d}else l.worldPosition=t.position;else l.position.copy(e.position);if(t?.rotation){if(t.rotation instanceof c.Quaternion)l.worldQuaternion=t.rotation;else if(t.rotation instanceof c.Euler)l.worldQuaternion=ei().setFromEuler(t.rotation);else if(Array.isArray(t.rotation)){const d=new c.Euler;d.fromArray(t.rotation),l.worldQuaternion=ei().setFromEuler(d)}}else l.quaternion.copy(e.quaternion);if(t?.scale)if(Array.isArray(t.scale)){const d=new c.Vector3;d.fromArray(t.scale),t.scale=d}else l.scale.copy(t.scale);else l.scale.copy(e.scale);if(t?.parent&&t.parent!=="scene"){let d=null;if(typeof t.parent=="string"?d=ka(t.parent,s.scene,!0):d=t.parent,d){const u=t.keepWorldPosition===!0?d.attach:d.add;u?u.call(d,l):console.error("Invalid parent object",d,"received when instantiating:",e)}else console.warn("could not find parent:",t.parent)}for(const[d,u]of Object.entries(e.userData))d!=="components"&&(l.userData[d]=u);if(e.userData?.components){const d=e.userData.components,u=[];l.userData.components=u;for(let p=0;p<d.length;p++){const m=d[p],y=new m.constructor;$1(m,y),m[Jl]!==void 0&&(y[Jl]=m[Jl]),u.push(y),y.gameObject=l,i.push(y),n[m.guid]={original:m,clone:y},gu.dispatchComponentLifecycleEvent("component-added",y)}}t&&(t.position=void 0,t.rotation=void 0,t.scale=void 0,t.parent=void 0,t.visible=void 0);for(const d in e.children){const u=e.children[d],p=L0(s,u,t,i,n,o);p&&(n[p.uuid]={original:u,clone:p},l.add(p))}return l}function $1(s,e,t){ja(e,s,void 0,{})}function W1(s,e){for(const t in s){const i=s[t],n=i.original,o=n.skeleton,r=i.clone;if(!o){console.warn("Skinned mesh has no skeleton?",i);continue}const a=o.bones,l=r.skeleton.clone();r.skeleton=l,r.bindMatrix.clone().copy(n.bindMatrix),r.bindMatrixInverse.copy(n.bindMatrixInverse);const h=[];l.bones=h;for(let d=0;d<a.length;d++){const u=a[d],m=e[u.uuid].clone;h.push(m)}}for(const t in s){const i=s[t].clone;i.skeleton.update(),i.bind(i.skeleton,i.bindMatrix),i.updateMatrixWorld(!0)}}function G1(s,e){for(const t in e){const n=e[t].clone;if(n?.isObject3D&&n?.userData?.components)for(let o=0;o<n.userData.components.length;o++){const r=n.userData.components[o],a=Object.entries(r);for(const[l,h]of a)if(Array.isArray(h)){const d=[];r[l]=d;for(let u=0;u<h.length;u++){const p=h[u];if(typeof p!="object"){d.push(p);continue}const m=B_(r,l,p,e);m!==void 0?(sr&&console.log("Found new instance for",l,p,"->",m),d.push(m)):(sr&&console.warn("Could not find new instance for",l,p),d.push(p))}}else if(typeof h=="object"){const d=B_(r,l,h,e);d!==void 0?r[l]=d:sr&&console.warn("Could not find new instance for",l,h)}}}}function B_(s,e,t,i){if(t!=null)if(t.isComponent===!0){const n=t.gameObject;if(n){const o=n.uuid,r=i[o]?.clone;if(!r){sr&&console.log("reference did not change",e,s,t);return}const a=n.userData.components.indexOf(t);if(a>=0&&r.isObject3D)return sr&&console.log(e,o),r.userData.components[a];console.warn("could not find component",e,t)}}else if(t.isObject3D===!0){if(e==="gameObject")return;const n=t;if(n){const o=n.uuid,r=i[o]?.clone;if(r)return sr&&console.log(e,"old",t,"new",r),r}}else{if(t.isVector4||t.isVector3||t.isVector2||t.isQuaternion||t.isEuler)return t.clone();if(t.isColor===!0)return t.clone();if(t.isEventList===!0)return t.__internalOnInstantiate(i)}}exports.BlobStorage=void 0;(s=>{s.baseUrl="https://networking.needle.tools";function i(d){return ae.md5(new Uint8Array(d))}s.hashMD5=i;function n(d){const u=ae.md5(new Uint8Array(d),{encoding:"binary",asBytes:!0});return btoa(String.fromCharCode(...u))}s.hashMD5_Base64=n;function o(d){const u=new Uint8Array(d);return crypto.subtle.digest("SHA-256",u).then(m=>btoa(String.fromCharCode(...new Uint8Array(m))))}s.hashSha256=o;function r(d){const u=d.filesize/1024/1024;return $n()?u<50:u<5}s.canUpload=r;async function a(d,u){const p=s.baseUrl;if(p){if(!d.name)return console.error("Upload: file name is missing"),null}else return console.error("Blob storage base url is not set"),null;let m=null;d instanceof File?m=await d.arrayBuffer():m=d.data;const y=m.byteLength,_=y/1024/1024;if(_>50)return u?.silent!==!0&&fe(`File (${_.toFixed(1)}MB) is too large for uploading (see console for details)`),console.warn(`Your file is too large for uploading (${_.toFixed(1)}MB). Max allowed size is 50MB`),null;if(!$n()&&_>5)return u?.silent!==!0&&fe('File is too large for uploading. Please get a <a href="https://needle.tools/pricing" target="_blank">commercial license</a> to upload files larger than 5MB'),console.warn(`Your file is too large for uploading (${_.toFixed(1)}MB). Max size is 5MB for non-commercial users. Please get a commercial license at https://needle.tools/pricing for larger files (up to 50MB)`),null;if(y<1)return console.warn(`Your file is too small for uploading (${_.toFixed(1)}MB). Min size is 1 byte`),null;const g=n(m),w={filename:d.name,"Content-Md5":g,"Content-Type":d.type||"application/octet-stream",FileSize:y.toString(),"Content-Disposition":`attachment; filename="${d.name}"`,"x-amz-server-side-encryption":"AES256"},b=await fetch(p+"/api/needle/blob",{method:"POST",headers:w,signal:u?.abort}).then(v=>v.json()).catch(v=>(console.error(v),null));if(b==null)return console.warn("Upload failed..."),null;if("error"in b)return console.error(b.error),null;if("upload"in b&&b.upload){let v=function(M){return u?.onProgress?.call(null,{progress01:0,state:"inprogress"}),fetch(M,{method:"PUT",headers:w,body:m,signal:u?.abort}).then(L=>(u?.onProgress?.call(null,{progress01:1,state:"finished"}),L)).catch(L=>L)};console.debug("Uploading file",b.upload);let E=!1,O=null;for(let M=0;M<3;M++)try{if(E)break;if(u?.abort?.aborted)return console.debug("Aborted upload"),null;const D=await v(b.upload);D instanceof Error?(O=D,await _s(1e3*M)):D.ok&&(console.debug("File uploaded successfully"),E=!0)}catch(D){console.error(D)}if(!E)return console.error(O?.message||"Failed to upload file"),null}if("download"in b){const v=p+b.download;return console.debug("File found in blob storage",v),{key:b.key,success:!0,download_url:v}}return null}s.upload=a;function l(d){return`${s.baseUrl}/api/needle/blob/${d}`}s.getBlobUrlForKey=l;async function h(d,u){const p=new c.FileLoader;p.setResponseType("arraybuffer");const m=await p.loadAsync(d,y=>{u&&u.call(null,y)});return m instanceof ArrayBuffer?new Uint8Array(m):(console.error("Download failed, no arraybuffer returned"),null)}s.download=h})(exports.BlobStorage||(exports.BlobStorage={}));const Us=x("debugaddressables");class I0{_context;_assetReferences={};constructor(e){this._context=e,this._context.pre_update_callbacks.push(this.preUpdate)}dispose(){const e=this._context.pre_update_callbacks.indexOf(this.preUpdate);e>=0&&this._context.pre_update_callbacks.splice(e,1);for(const t in this._assetReferences)this._assetReferences[t]?.unload();this._assetReferences={}}preUpdate=()=>{};findAssetReference(e){return this._assetReferences[e]||null}registerAssetReference(e){return e.url&&(this._assetReferences[e.url]?console.warn("Asset reference already registered",e):this._assetReferences[e.url]=e),e}unregisterAssetReference(e){e.url&&delete this._assetReferences[e.url]}}const Uf=Symbol("assetReference");class Z{static getOrCreateFromUrl(e,t){if(!t&&(t=U.Current,!t))throw new Error('Context is required when sourceId is a string. When you call this method from a component you can call it with "getOrCreate(this, url)" where "this" is the component.');const i=t.addressables,n=i.findAssetReference(e);if(n)return n;const o=new Z(e,t.hash);return i.registerAssetReference(o),o}static getOrCreate(e,t,i){if(typeof e=="string"){if(!i&&(i=U.Current,!i))throw new Error('Context is required when sourceId is a string. When you call this method from a component you can call it with "getOrCreate(this, url)" where "this" is the component.')}else i=e.context,e=e.sourceId;const n=ws(e,t);Us&&console.log("GetOrCreate Addressable from",e,t,"FinalPath=",n);const o=i.addressables,r=o.findAssetReference(n);if(r)return r;const a=new Z(n,i.hash);return o.registerAssetReference(a),a}isAssetReference=!0;get rawAsset(){return this._rawAsset}get asset(){return this._glbRoot??(this._rawAsset?.scene||null)}set asset(e){e?this._rawAsset={animations:e.animations,scene:e,scenes:[e]}:this._rawAsset=null}get uri(){return this._url}get url(){return this._url}get urlName(){return this._urlName}get hasUrl(){return this._url!==void 0&&(this._url.startsWith("http")||this._url.startsWith("blob:")||this._url.startsWith("www.")||this._url.includes("/"))}_rawAsset=null;_glbRoot;_url;_urlName;_progressListeners=[];_isLoadingRawBinary=!1;_rawBinary;constructor(...e){typeof e[0]=="object"?"url"in e[0]?this._url=e[0].url:(this._url="",e[0].asset&&(this.asset=e[0].asset)):(this._url=e[0],e[2]instanceof c.Object3D&&(this.asset=e[2]));const t=this._url.lastIndexOf("/");if(t>=0){this._urlName=this._url.substring(t+1);const i=this._urlName.lastIndexOf(".");i>=0&&(this._urlName=this._urlName.substring(0,i))}else this._urlName=this._url;m0(this._url,this.onResolvePrefab.bind(this))}async onResolvePrefab(e){return e===this.url&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0||ur(this.asset)===!0}_loadingPromise=null;isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(Us&&console.log("Unload",this.asset),"scene"in this.asset&&this.asset.scene&&bi(this.asset.scene,!0,!0),bi(this.asset,!0,!0)),this.asset=null,this._rawBinary=void 0,this._glbRoot=null,this._loadingPromise=null,U.Current&&U.Current.addressables.unregisterAssetReference(this)}async preload(){if(!this.mustLoad||this._isLoadingRawBinary)return null;if(this._rawBinary!==void 0)return this._rawBinary;this._isLoadingRawBinary=!0,Us&&console.log("Preload",this.url);const e=await exports.BlobStorage.download(this.url,t=>{this.raiseProgressEvent(t)});return this._rawBinary=e?.buffer??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(e){if(Us&&console.log("[AssetReference] loadAssetAsync",this.url),!this.mustLoad)return this.asset?.parent&&console.warn(`[AssetReference] "${this.urlName}" is already loaded and parented to "${this.asset.parent.name||"scene"}". loadAssetAsync() returns the same shared instance — use .instantiate() to create a new copy.`),this.asset;if(e&&this._progressListeners.push(e),this._loadingPromise!==null)return this._loadingPromise.then(n=>this.asset);const t=U.Current;if(this._rawBinary){if(!(this._rawBinary instanceof ArrayBuffer))return console.error("[AssetReference] Failed loading – Invalid data. Must be of type ArrayBuffer. "+typeof this._rawBinary),null;this._loadingPromise=un().parseSync(t,this._rawBinary,this.url,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))}else Us&&console.log("Load async",this.url),this._loadingPromise=un().loadSync(t,this.url,this.url,null,n=>{this.raiseProgressEvent(n)});this._loadingPromise.finally(()=>this._loadingPromise=null);const i=await this._loadingPromise;return this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(i),i?(i[Uf]=this,this._glbRoot&&(this._glbRoot[Uf]=this),this.asset&&(this.asset[Uf]=this),Nd(t),i.scene!==void 0&&(this._rawAsset=i),this.asset):null}instantiate(e){return this.onInstantiate(e,!1)}instantiateSynced(e,t=!0){return this.onInstantiate(e,!0,t)}beginListenDownload(e){this._progressListeners.indexOf(e)<0&&this._progressListeners.push(e)}endListenDownload(e){const t=this._progressListeners.indexOf(e);t>=0&&this._progressListeners.splice(t,1)}raiseProgressEvent(e){for(const t of this._progressListeners)t(this,e)}static currentlyInstantiating=new Map;async onInstantiate(e,t=!1,i){const n=U.Current,o=new gn;if(e instanceof c.Object3D?o.parent=e:e&&(Object.assign(o,e),o.cloneAssign(e)),o.parent===void 0&&(o.parent=n.scene),this.mustLoad&&await this.loadAssetAsync(),Us&&console.log("Instantiate",this.url,"parent:",e),this.asset){Us&&console.log("Add to scene",this.asset);let r=Z.currentlyInstantiating.get(this.url);if(r!==void 0&&r>=1e4)return console.error("Recursive or too many instantiations of "+this.url+" in the same frame ("+r+")"),null;try{if(r===void 0&&(r=0),r+=1,Z.currentlyInstantiating.set(this.url,r),t){o.context=n;const a=this.asset;a.guid=this.url;const l=sg(a,o,void 0,i);if(l)return l}else{const a=uo(this.asset,o);if(a)return a}}finally{n.post_render_callbacks.push(()=>{r===void 0||r<0?r=0:r-=1,Z.currentlyInstantiating.set(this.url,r)})}}else Us&&console.warn("Failed to load asset",this.url);return null}tryGetActualGameObjectRoot(e){if(e&&e.scene){const t=e.scene;if(t.isGroup&&t.children.length===1&&t.children[0].name+"glb"===t.name){const i=t.children[0];return i.animations=t.animations,i}else return t}return null}}class H1 extends Hi{constructor(){super([Z],"AssetReferenceSerializer")}onSerialize(e,t){if(e&&e.uri!==void 0&&typeof e.uri=="string")return e.uri}onDeserialize(e,t){if(typeof e=="string")return t.context?t.gltfId?Z.getOrCreate(t.gltfId,e,t.context):(console.error("Missing source id"),null):(console.error("Missing context"),null);if(e instanceof c.Object3D){if(!t.context)return console.error("Missing context"),null;if(!t.gltfId)return console.error("Missing source id"),null;const i=e,n=t.context,o=i.guid??i.uuid,r=n.addressables.findAssetReference(o);if(r)return r;const a=new Z(o,void 0,i);return n.addressables.registerAssetReference(a),a}return null}}new H1;const q1=Promise.resolve(null);class or{static imageReferences=new Map;static getOrCreate(e){let t=or.imageReferences.get(e);return t||(t=new or(e),or.imageReferences.set(e,t)),t}constructor(e){this.url=e}url;_bitmap;_bitmapObject;dispose(){this._bitmapObject&&this._bitmapObject.close(),this._bitmap=void 0}createHTMLImage(){const e=new Image;return e.src=this.url,e}loader=null;createTexture(){return this.url?(this.loader||(this.loader=new c.TextureLoader),this.loader.setCrossOrigin("anonymous"),this.loader.loadAsync(this.url).then(e=>(e&&!e.name?.length&&(e.name=this.url.split("/").pop()??this.url),e))):(console.error("Can not load texture without url"),q1)}getBitmap(){return this._bitmap?this._bitmap:(this._bitmap=new Promise((e,t)=>{const i=document.createElement("img");i.addEventListener("load",()=>{this._bitmap=createImageBitmap(i).then(n=>(this._bitmapObject=n,e(n),n))}),i.addEventListener("error",n=>{console.error("Failed to load image:"+this.url,n),e(null)}),i.src=this.url}),this._bitmap)}}class j0 extends Hi{constructor(){super([or],"ImageReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const i=ws(t.gltfId,e);return or.getOrCreate(i)}}}new j0;class rr{static cache=new Map;static getOrCreate(e){let t=rr.cache.get(e);return t||(t=new rr(e),rr.cache.set(e,t)),t}async loadRaw(){return this.res||(this.res=fetch(this.url)),this.res.then(e=>e.blob())}async loadText(){return this.res||(this.res=fetch(this.url)),this.res.then(e=>e.text())}url;res;constructor(e){this.url=e}}class B0 extends Hi{constructor(){super([rr],"FileReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const i=ws(t.gltfId,e);return rr.getOrCreate(i)}}}new B0;class X1{context;mixers=[];constructor(e){this.context=e}onDestroy(){this.mixers.forEach(e=>e.stopAllAction()),this.mixers.length=0}registerAnimationMixer(e){if(!e){console.warn("AnimationsRegistry.registerAnimationMixer called with null or undefined mixer");return}this.mixers.includes(e)||this.mixers.push(e)}unregisterAnimationMixer(e){if(!e){console.warn("AnimationsRegistry.unregisterAnimationMixer called with null or undefined mixer");return}const t=this.mixers.indexOf(e);t!==-1&&this.mixers.splice(t,1)}}class Hn{static testIfRootCanAnimate(e,t){const i=e.getRoot();return i&&(i.userData.static||i.matrixAutoUpdate===!1||i.matrixWorldAutoUpdate===!1)?((t===!0||t===void 0&&A())&&console.warn(`AnimationUtils: The root object (${i.name||i.type}) of this AnimationAction has matrixAutoUpdate or matrixWorldAutoUpdate set to false. This may prevent the animation from working correctly. If the object is marked as static, try to change it to dynamic.`,{static:i.userData.static,name:i.userData.name,tag:i.userData.tag,matrixAutoUpdate:i.matrixAutoUpdate,matrixWorldAutoUpdate:i.matrixWorldAutoUpdate}),!1):!0}static tryGetActionsFromMixer(e){const t=e._actions;return t||null}static tryGetAnimationClipsFromObjectHierarchy(e,t){if(t||(t=new Array),e)e.animations&&t.push(...e.animations);else return t;if(e.children)for(const i of e.children)this.tryGetAnimationClipsFromObjectHierarchy(i,t);return t}static autoplayAnimations(e){if(!e||!e.animations)return console.debug("No animations found in file"),null;const t="scene"in e?e.scene:e,i=new Array;for(let o=0;o<e.animations.length;o++){const r=e.animations[o];if(!r.tracks||r.tracks.length<=0){console.warn("Animation has no tracks");continue}for(const a in r.tracks){const l=r.tracks[a],h=c.PropertyBinding.parseTrackName(l.name);let d=c.PropertyBinding.findNode(t,h.nodeName);if(!d){const p=l.__objectName??l.name.substring(0,l.name.indexOf("."));if(d=t.getObjectByProperty("uuid",p),!d)continue}let u=n(d)||n(t);if(!u){const p=P.get("Animation");if(u=t.addComponent(p),!u){console.error("Failed creating Animation component: No 'Animation' component found in TypeStore");break}}i.push(u),u.addClip&&u.addClip(r)}}return i;function n(o){if(!o)return null;const r=o.userData?.components;if(r&&r.length>0)for(let a=0;a<r.length;a++){const l=r[a];if(l.isAnimationComponent===!0)return l}return n(o.parent)}}static emptyClip(){return new c.AnimationClip("empty",0,[])}static createScaleClip(e){const t=e?.duration??.3;let i={x:1,y:1,z:1};e?.scale!==void 0&&(typeof e.scale=="number"?i={x:e.scale,y:e.scale,z:e.scale}:i=e.scale);const n=e?.type??"linear",o=e?.scaleFactor??1.2,r=new Array,a=new Array;switch(n){case"linear":r.push(0,t),a.push(i.x,i.y,i.z,i.x*o,i.y*o,i.z*o);break;case"spring":r.push(0,t*.3,t*.5,t*.7,t*.9,t),a.push(i.x,i.y,i.z,i.x*o,i.y*o,i.z*o,i.x*.9,i.y*.9,i.z*.9,i.x*1.05,i.y*1.05,i.z*1.05,i.x*.98,i.y*.98,i.z*.98,i.x,i.y,i.z);break}const l=new c.KeyframeTrack(".scale",r,a);return new c.AnimationClip("scale",r[r.length-1],[l])}}function*dg(s,e=null){const t=e?e.time:U.Current.time,i=t.time;for(;t.time-i<s;)yield}function*Q1(s){for(let e=0;e<s;e++)yield}function*F0(s){let e=!0;for(s.then(()=>e=!1),s.catch(()=>e=!1);e;)yield}const F_=x("debugexr")||x("debugpmrem");class wu{get name(){return"NEEDLE_pmrem"}parser;constructor(e){this.parser=e}loadTexture(e){const t=this.name,i=this.parser,o=i.json.textures[e];if(!o.extensions||!o.extensions[t])return null;const r=o.extensions[t],a=i.options.ktx2Loader;return a?(F_&&console.log("NEEDLE_pmrem.loadTexture",e,r),i.loadTextureImage(e,r.source,a).then(h=>(wu.postprocess(h),h.name="PMREM_"+h.name,F_&&console.log("NEEDLE_pmrem: loaded PMREM texture",h),h))):(console.warn("NEEDLE_pmrem: No KTX2Loader available on GLTFLoader — cannot load PMREM texture"),null)}static postprocess(e){return e.mapping=c.CubeUVReflectionMapping,e}}const U_="NEEDLE_lightmaps",Hr=x("debuglightmapsextension")||x("debuglightmaps");var Tn=(s=>(s[s.Lightmap=0]="Lightmap",s[s.Skybox=1]="Skybox",s[s.Reflection=2]="Reflection",s))(Tn||{});class Y1{get name(){return U_}parser;registry;source;constructor(e,t,i){this.parser=e,this.registry=t,this.source=i}afterRoot(e){const t=this.parser.json.extensions;if(t){const i=t[U_];if(i){const n=i.textures;return n?.length?(Hr&&console.log(i),new Promise(async(o,r)=>{const a=[];for(const h of n)if(h.pointer){Hr&&console.log(h);let d=null;if(h.pointer.startsWith("/textures/")||h.pointer.startsWith("textures/"))Hr&&console.log("Load texture from gltf",h.pointer),d=ag(this.parser,h.pointer).then(u=>this.resolveTexture(h,u));else if(typeof h.pointer=="string"){Hr&&console.log("Load texture from path",h.pointer);const u=ws(this.source,h.pointer),p=u.endsWith(".pmrem.ktx2");let m;u.endsWith(".exr")?m=new X.EXRLoader(this.parser.options.manager):u.endsWith(".hdr")?m=new X.RGBELoader(this.parser.options.manager):p?m=this.parser.options.ktx2Loader:m=new c.TextureLoader(this.parser.options.manager),d=m.loadAsync(u,void 0).then(y=>(p&&y&&wu.postprocess(y),this.resolveTexture(h,y)))}else h.pointer;d&&a.push(d)}const l=await Am(a);l?.anyFailed&&(A()||Hr)&&console.error("[NEEDLE_lightmaps]Error during extension loading:",l),o()})):null}}return null}resolveTexture(e,t){const i=t;Hr&&console.log("Light Texture loaded:",i),i?.isTexture&&(this.registry?(i.colorSpace=c.LinearSRGBColorSpace,this.registry.registerTexture(this.source,e.type,i,e.index)):console.log(Tn[e.type],e.pointer,i))}}const qr=!!x("debuglightmaps");class K1{context;map=new Map;clear(){this.map.clear()}constructor(e){this.context=e}registerTexture(e,t,i,n){qr&&console.log("Registering ",Tn[t]+' "'+e+'"',i),this.map.has(e)||this.map.set(e,new Map);const o=this.map.get(e),r=o?.get(t)??[];r.length<n&&(r.length=n+1),n0(i,!1),r[n]=i,o?.set(t,r)}tryGetLightmap(e,t=0){return this.tryGet(e,Tn.Lightmap,t)}tryGetSkybox(e){return qr&&console.log("[Get Skybox]",e,this.map),this.tryGet(e,Tn.Skybox,0)}tryGetReflection(e){return qr&&console.log("[Get Reflection]",e,this.map),this.tryGet(e,Tn.Reflection,0)}tryGet(e,t,i){if(!e)return qr&&console.warn("Missing source id"),null;const n=this.map.get(e);if(!n)return qr&&console.warn(`[Lighting] No ${Tn[t]} texture entry for`,e),null;const o=n.get(t);return o===void 0?(qr&&console.warn(`[Lighting] No ${Tn[t]} texture for`,e,"index",i),null):!o?.length||o.length<=i?null:o[i]}}c.ShaderChunk.lights_fragment_maps=c.ShaderChunk.lights_fragment_maps.replace("vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );",`
|
|
202
|
-
vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
|
|
203
|
-
// The range of RGBM lightmaps goes from 0 to 34.49 (5^2.2) in linear space, and from 0 to 5 in gamma space.
|
|
204
|
-
lightMapTexel.rgb *= lightMapTexel.a * 8.; // no idea where that "8" comes from... heuristically derived
|
|
205
|
-
lightMapTexel.a = 1.;
|
|
206
|
-
lightMapTexel = conv_sRGBToLinear(lightMapTexel);
|
|
207
|
-
`);c.ShaderChunk.lightmap_pars_fragment=`
|
|
208
|
-
#ifdef USE_LIGHTMAP
|
|
209
|
-
uniform sampler2D lightMap;
|
|
210
|
-
uniform float lightMapIntensity;
|
|
211
|
-
|
|
212
|
-
// took from threejs 05fc79cd52b79e8c3e8dec1e7dca72c5c39983a4
|
|
213
|
-
vec4 conv_sRGBToLinear( in vec4 value ) {
|
|
214
|
-
return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );
|
|
215
|
-
}
|
|
216
|
-
#endif
|
|
217
|
-
`;c.ShaderChunk.lights_fragment_begin=c.ShaderChunk.lights_fragment_begin.replace("irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );",`
|
|
218
|
-
#if defined(USE_LIGHTMAP)
|
|
219
|
-
irradiance += 0.;
|
|
220
|
-
#else
|
|
221
|
-
irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );
|
|
222
|
-
#endif`);const zf=x("debugprogressive"),Fh=new c.Box3,Uh=new c.Sphere;class Z1{static GLTF_PROGRESSIVE_LODSMANAGER_TYPE=re.LODsManager;context;_lodsManager;_settings={};get manager(){return this._lodsManager}get skinnedMeshAutoUpdateBoundsInterval(){return this._lodsManager?.skinnedMeshAutoUpdateBoundsInterval||this._settings.skinnedMeshAutoUpdateBoundsInterval||0}set skinnedMeshAutoUpdateBoundsInterval(e){this._settings.skinnedMeshAutoUpdateBoundsInterval=e,this.applySettings()}get targetTriangleDensity(){return this._lodsManager?.targetTriangleDensity||this._settings.targetTriangleDensity||2e5}set targetTriangleDensity(e){this._settings.targetTriangleDensity=e,this.applySettings()}constructor(e){this.context=e}applySettings(){if(this._lodsManager)for(const e in this._settings)this._lodsManager[e]=this._settings[e]}setRenderer(e){this._lodsManager?.disable(),re.LODsManager.removePlugin(this),re.LODsManager.addPlugin(this),re.LODsManager.debugDrawLine=B.DrawLine,this._lodsManager=re.LODsManager.get(e,{engine:"needle-engine"}),this.applySettings(),this._lodsManager.enable()}disable(){this._lodsManager?.disable(),re.LODsManager.removePlugin(this)}onAfterUpdatedLOD(e,t,i,n,o){zf&&this.onRenderDebug(i,n,o)}onRenderDebug(e,t,i){if(!t.geometry||!re.NEEDLE_progressive.hasLODLevelAvailable(t.geometry)&&!re.NEEDLE_progressive.hasLODLevelAvailable(t.material))return;const n=re.LODsManager.getObjectLODState(t);if(!n)return;let o=i.mesh_lod;const r=i.mesh_lod!=n.lastLodLevel_Mesh||i.texture_lod!=n.lastLodLevel_Texture;if(zf&&t.geometry.boundingSphere){const a=t.geometry.boundingSphere;Uh.copy(a),Uh.applyMatrix4(t.matrixWorld);const l=Uh.center,h=Uh.radius,d=["#76c43e","#bcc43e","#c4ac3e","#c4673e","#ff3e3e"];if(r)B.DrawWireSphere(l,h,d[o],.1);else{const u=t.geometry.index?.count??0,p=re.NEEDLE_progressive.getMeshLODExtension(t.geometry)?.lods;o=p?Math.min(p?.length-1,o):0;let m="";if(p&&n.lastScreenCoverage>0)for(let g=0;g<p.length;g++){const w=p[g].density,b=g==p.length-1;m+=w.toFixed(0)+">"+(w/n.lastScreenCoverage).toFixed(0)+(b?"":",")}const y=p?p[o]?.density:-1;let _="LOD "+i.mesh_lod+`
|
|
223
|
-
TEX `+i.texture_lod;if(zf=="density"&&(_+=`
|
|
224
|
-
`+u+` tris
|
|
225
|
-
`+(y/n.lastScreenCoverage).toFixed(0)+` dens
|
|
226
|
-
`+(n.lastScreenCoverage*100).toFixed(1)+`% cov
|
|
227
|
-
`+(n.lastCentrality*100).toFixed(1)+`% centr
|
|
228
|
-
`+(Fh.min.x.toFixed(2)+"-"+Fh.max.x.toFixed(2)+"x"+Fh.min.y.toFixed(2)+"-"+Fh.max.y.toFixed(2))+" scr"),n.lastScreenCoverage>.1){const g=e,w=g.worldForward,b=g.worldPosition,E=F(w).multiplyScalar(h*.7).add(l),O=E.distanceTo(b),M=d[Math.min(d.length-1,Math.max(0,o))]+"88",D=this.context.domHeight>0?screen.height/this.context.domHeight:1,L=e.isPerspectiveCamera?Math.tan(e.fov*Math.PI/180/2):1;B.DrawLabel(E,_,O*.012*D*L,void 0,16777215,M)}}}}}const J1=x("debugplayerview");var gs=(s=>(s.Browser="browser",s.Headset="headset",s.Handheld="handheld",s))(gs||{});class U0{userId;context;viewDevice="browser";get currentObject(){return this._object}set currentObject(e){this._object=e}get isConnected(){return this.context.connection.userIsInRoom(this.userId)}removed=!1;_object;constructor(e,t){this.userId=e,this.context=t}}class z0{context;playerViews=new Map;constructor(e){this.context=e}setPlayerView(e,t,i){let n=this.playerViews.get(e);n||(n=new U0(e,this.context),this.playerViews.set(e,n)),n.viewDevice=i,n.currentObject=t,n.removed=!1}getPlayerView(e){if(!e)return;if(!this.context.connection.userIsInRoom(e)){this.playerViews.delete(e);return}return this.playerViews.get(e)}removePlayerView(e,t){const i=this.playerViews.get(e);i?.viewDevice===t&&(J1&&console.log("REMOVE",e),i.removed=!0,this.playerViews.delete(e))}}new c.FileLoader;const Gc=new Uint8Array(4);Gc[0]=255;Gc[1]=255;Gc[2]=255;Gc[3]=255;const eP=new c.DataTexture(Gc,1,1,c.RGBAFormat);function ug(s,e=1){const t="alpha"in s,i=e*e,n=new Uint8Array(4*i),o=Math.floor(s.r*255),r=Math.floor(s.g*255),a=Math.floor(s.b*255);for(let h=0;h<i;h++){const d=h*4;n[d+0]=o,n[d+1]=r,n[d+2]=a,t?n[d+3]=Math.floor(s.alpha*255):n[d+3]=255}const l=new c.DataTexture(n,e,e);return l.needsUpdate=!0,l}function tP(s,e,t,i=1,n=3){const r=i*n,a=[s,e,t],l=a.length,h=new Uint8Array(4*l*r),d=new c.Color;for(let p=0;p<n;p++){const m=Math.floor(p/n*l),y=I.clamp(m+1,0,l-1),_=a[m],g=a[y],w=p/n*l%1;d.lerpColors(_,g,w);const b=Math.floor(d.r*255),v=Math.floor(d.g*255),E=Math.floor(d.b*255);for(let O=0;O<i;O++){const M=(p*i+O)*4;h[M+0]=b,h[M+1]=v,h[M+2]=E,h[M+3]=255}}const u=new c.DataTexture(h,i,n);return u.needsUpdate=!0,u}function Gd(s,e){const t=s.elements;e||(e=[]),e.length=0;for(let i=0;i<16;i+=4){const n=t[i],o=t[i+1],r=t[i+2],a=t[i+3],l=new c.Vector4(n,o,r,a);e.push(l)}return e}const Nf=[],z_=[];function iP(s,e){if(Nf.length===0)for(let t=0;t<27;t++)Nf.push(0);e||(e=Nf);for(let t=0;t<27;t++)z_[t]=e[t];e=z_,s.unity_SHAr={value:new c.Vector4(e[9],e[3],e[6],e[0])},s.unity_SHBr={value:new c.Vector4(e[12],e[15],e[18],e[21])},s.unity_SHAg={value:new c.Vector4(e[10],e[4],e[7],e[1])},s.unity_SHBg={value:new c.Vector4(e[13],e[16],e[19],e[22])},s.unity_SHAb={value:new c.Vector4(e[11],e[5],e[8],e[2])},s.unity_SHBb={value:new c.Vector4(e[14],e[17],e[20],e[23])},s.unity_SHC={value:new c.Vector4(e[24],e[25],e[26],1)}}class nP{vertexShader;fragmentShader;technique;constructor(e,t,i){this.vertexShader=e,this.fragmentShader=t,this.technique=i}}async function sP(s,e){if(!s)return console.error("Can not find technique: no shader data"),null;const t=s.programs[e],i=t.vertexShader,n=t.fragmentShader;if(i!==void 0&&n!==void 0){const o=s.shaders[i],r=s.shaders[n];if(o.uri&&r.uri||o.code&&r.code){if(!o.code&&o.uri&&await N_(o),!r.code&&r.uri&&await N_(r),!o.code||!r.code)return null;const a=s.techniques[e];return new nP(o.code,r.code,a)}}return console.error("Shader technique not found",e),null}async function N_(s){const e=s.uri;if(e)if(e.endsWith(".glsl")){const i=await new c.FileLoader().loadAsync(e);s.code=i.toString()}else s.code=oP(s.uri)}function oP(s){return decodeURIComponent(Array.prototype.map.call(atob(s),function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}const nn=x("debugenvlight");var Sa=(s=>(s[s.Skybox=0]="Skybox",s[s.Trilight=1]="Trilight",s[s.Flat=3]="Flat",s[s.Custom=4]="Custom",s))(Sa||{}),Hd=(s=>(s[s.Skybox=0]="Skybox",s[s.Custom=1]="Custom",s))(Hd||{});class N0{context;constructor(e){this.context=e,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}_currentLightSettingsId;_sceneLightSettings;get currentLightSettingsId(){return this._currentLightSettingsId}preUpdate(){const e=this.context.time;this._timevec4.x=e.time,this._timevec4.y=Math.sin(e.time),this._timevec4.z=Math.cos(e.time),this._timevec4.w=e.deltaTime}_timevec4=new c.Vector4;get timeVec4(){return this._timevec4}get environmentIntensity(){if(!this._sceneLightSettings||!this._currentLightSettingsId)return 1;const e=this._sceneLightSettings.get(this._currentLightSettingsId);return e?e.ambientIntensity:1}get sceneLightSettings(){return this._sceneLightSettings?.values()}enable(e){e instanceof Z&&(e=e.url);const t=this._sceneLightSettings?.get(e);return t?(nn&&console.log("Enable scene light settings",e,t),e!==this._currentLightSettingsId&&this._currentLightSettingsId&&this.disable(this._currentLightSettingsId),this._currentLightSettingsId=e,t.enabled=!0,!0):(nn&&console.warn("No light settings found for",e),!1)}disable(e){if(e instanceof Z&&(e=e.url),e==null)return!1;const t=this._sceneLightSettings?.get(e);return t?(nn&&console.log("Disable scene light settings",e,t),t.enabled=!1,!0):!1}enableCurrent(){return this._currentLightSettingsId?(this.enable(this._currentLightSettingsId),this._currentLightSettingsId??null):null}disableCurrent(){if(this._currentLightSettingsId){const e=this._currentLightSettingsId;return this.disable(this._currentLightSettingsId),e}return null}internalRegisterSceneLightSettings(e){const t=e.sourceId;if(!t){console.error("Missing source id for scene light settings, can not register:",e);return}nn&&console.log("Register "+e?.sourceId+" lighting",e),this._sceneLightSettings||(this._sceneLightSettings=new Map),this._sceneLightSettings.set(t,e)}internalUnregisterSceneLightSettings(e){const t=e.sourceId;if(!t){console.error("Missing source id for scene light settings, can not unregister:",e);return}nn&&console.log("Unregister "+e?.sourceId+" lighting",e),this._sceneLightSettings&&this._sceneLightSettings.delete(t)}internalRegisterReflection(e,t){nn&&console.log("Register reflection",e,t);const i=new V0(this.context,t,1);this._lighting[e]=i}internalGetReflection(e){return this._lighting[e]}__currentReflectionId=null;internalEnableReflection(e){this.__currentReflectionId=e;const t=this._sceneLightSettings?.get(e);switch(nn&&console.log("Enable reflection",e,t?Sa[t.ambientMode]:"Unknown ambient mode",t),t?.ambientMode){case 0:case 4:const i=this.internalGetReflection(e);if(i&&i.Source){nn&&console.log("Setting environment reflection",i);const n=this.context.scene,o=i.Source;return o.mapping!==c.CubeUVReflectionMapping&&(o.mapping=c.EquirectangularReflectionMapping),n.environment=o,n.environmentIntensity=this.environmentIntensity||1,o}else nn&&console.warn("Could not find reflection for source",e);break}if(t?.environmentReflectionSource===1)switch(t?.ambientMode){case 1:if(t.ambientTrilight){const i=t.ambientTrilight,n=tP(i[0],i[1],i[2],64,64);return n.colorSpace=c.SRGBColorSpace,n.mapping=c.EquirectangularReflectionMapping,this.context.scene.environment=n,n}else console.error("Missing ambient trilight",t.sourceId);case 3:if(t.ambientLight){const i=ug(t.ambientLight,64);return i.colorSpace=c.SRGBColorSpace,i.mapping=c.EquirectangularReflectionMapping,this.context.scene.environment=i,i}else console.error("Missing ambientlight",t.sourceId)}return null}internalDisableReflection(e){if(e&&e!==this.__currentReflectionId){nn&&console.log("Not disabling reflection for",e,"because it is not the current light settings id",this.__currentReflectionId);return}nn&&console.log("Disable reflection",e);const t=this.context.scene;t.environment=null}_lighting={}}class V0{get Source(){return this._source}_source;constructor(e,t,i=1){this._source=t,t.mapping!==c.CubeUVReflectionMapping&&(t.mapping=c.EquirectangularReflectionMapping)}}const V_=x("timescale");let Kp=1;typeof V_=="number"&&(Kp=V_);class $0{get time(){return this._time}set time(e){this._time=e}_time=0;get deltaTime(){return this._deltaTime}set deltaTime(e){this._deltaTime=e}_deltaTime=0;get deltaTimeUnscaled(){return this._deltaTimeUnscaled}_deltaTimeUnscaled=0;timeScale=1;get frame(){return this._frame}set frame(e){this._frame=e}_frame=0;get frameCount(){return this.frame}get realtimeSinceStartup(){return this.clock.elapsedTime}get fps(){return 1/this.deltaTime}get smoothedFps(){return this._smoothedFps}get smoothedDeltaTime(){return 1/this._smoothedFps}clock=new c.Clock;_smoothedFps=0;_smoothedDeltaTime=0;_fpsSamples=[];_fpsSampleIndex=0;constructor(){typeof Kp=="number"&&(this.timeScale=Kp)}update(){this.deltaTime=this.clock.getDelta(),this.deltaTime=Math.min(.1,this.deltaTime),this._deltaTimeUnscaled=this.deltaTime,this.deltaTime<=0&&(this.deltaTime=1e-12),this.deltaTime*=this.timeScale,this.frame+=1,this.time+=this.deltaTime,this._fpsSamples.length<60?this._fpsSamples.push(this.deltaTime):this._fpsSamples[this._fpsSampleIndex++%60]=this.deltaTime;let e=0;for(let t=0;t<this._fpsSamples.length;t++)e+=this._fpsSamples[t];this._smoothedDeltaTime=e/this._fpsSamples.length,this._smoothedFps=1/this._smoothedDeltaTime}}let $_=!1;function W0(s){$_||($_=!0,rP(),aP())}W0();function rP(){const s=`
|
|
229
|
-
float startCompression = 0.8;
|
|
230
|
-
float desaturation = 0.5;
|
|
231
|
-
// Patched tonemapping function
|
|
232
|
-
vec3 NeutralToneMapping( vec3 color ) {
|
|
233
|
-
color *= toneMappingExposure;
|
|
234
|
-
|
|
235
|
-
float d = 1. - startCompression;
|
|
236
|
-
// float peak = dot(color, vec3(0.299, 0.587, 0.114));
|
|
237
|
-
float peak = max(color.r, max(color.g, color.b));
|
|
238
|
-
if (peak < startCompression) return color;
|
|
239
|
-
float newPeak = 1. - d * d / (peak + d - startCompression);
|
|
240
|
-
float invPeak = 1. / peak;
|
|
241
|
-
|
|
242
|
-
float extraBrightness = dot(color * (1. - startCompression * invPeak), vec3(1, 1, 1));
|
|
243
|
-
|
|
244
|
-
color *= newPeak * invPeak;
|
|
245
|
-
float g = 1. - 3. / (desaturation * extraBrightness + 3.);
|
|
246
|
-
return mix(color, vec3(1, 1, 1), g);
|
|
247
|
-
}
|
|
248
|
-
`,e="vec3 NeutralToneMapping( vec3 color ) {",t=`return mix( color, vec3( newPeak ), g );
|
|
249
|
-
}`,i=c.ShaderChunk.tonemapping_pars_fragment.indexOf(e),n=c.ShaderChunk.tonemapping_pars_fragment.indexOf(t,i);if(i>=0&&n>=0){const o=c.ShaderChunk.tonemapping_pars_fragment.substring(i,n+t.length);c.ShaderChunk.tonemapping_pars_fragment=c.ShaderChunk.tonemapping_pars_fragment.replace(o,s)}else A()&&console.error("Couldn't find NeutralToneMapping in ShaderChunk.tonemapping_pars_fragment")}function aP(){const s=`
|
|
250
|
-
// 0: Default, 1: Golden, 2: Punchy
|
|
251
|
-
#define AGX_LOOK 0
|
|
252
|
-
|
|
253
|
-
vec3 userSlope = vec3(1.0);
|
|
254
|
-
vec3 userOffset = vec3(0.0);
|
|
255
|
-
vec3 userPower = vec3(1.0);
|
|
256
|
-
float userSaturation = 1.0;
|
|
257
|
-
|
|
258
|
-
// Mean error^2: 3.6705141e-06
|
|
259
|
-
vec3 _agxDefaultContrastApprox(vec3 x) {
|
|
260
|
-
vec3 x2 = x * x;
|
|
261
|
-
vec3 x4 = x2 * x2;
|
|
262
|
-
|
|
263
|
-
return + 15.5 * x4 * x2
|
|
264
|
-
- 40.14 * x4 * x
|
|
265
|
-
+ 31.96 * x4
|
|
266
|
-
- 6.868 * x2 * x
|
|
267
|
-
+ 0.4298 * x2
|
|
268
|
-
+ 0.1191 * x
|
|
269
|
-
- 0.00232;
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
vec3 _agx(vec3 val) {
|
|
273
|
-
const mat3 agx_mat = mat3(
|
|
274
|
-
0.842479062253094, 0.0423282422610123, 0.0423756549057051,
|
|
275
|
-
0.0784335999999992, 0.878468636469772, 0.0784336,
|
|
276
|
-
0.0792237451477643, 0.0791661274605434, 0.879142973793104);
|
|
277
|
-
|
|
278
|
-
const float min_ev = -12.47393;
|
|
279
|
-
const float max_ev = 4.026069;
|
|
280
|
-
|
|
281
|
-
// val = pow(val, vec3(2.2));
|
|
282
|
-
|
|
283
|
-
// Input transform (inset)
|
|
284
|
-
val = agx_mat * val;
|
|
285
|
-
|
|
286
|
-
// Log2 space encoding
|
|
287
|
-
val = clamp(log2(val), min_ev, max_ev);
|
|
288
|
-
val = (val - min_ev) / (max_ev - min_ev);
|
|
289
|
-
|
|
290
|
-
// Apply sigmoid function approximation
|
|
291
|
-
val = _agxDefaultContrastApprox(val);
|
|
292
|
-
|
|
293
|
-
return val;
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
vec3 _agxEotf(vec3 val) {
|
|
297
|
-
const mat3 agx_mat_inv = mat3(
|
|
298
|
-
1.19687900512017, -0.0528968517574562, -0.0529716355144438,
|
|
299
|
-
-0.0980208811401368, 1.15190312990417, -0.0980434501171241,
|
|
300
|
-
-0.0990297440797205, -0.0989611768448433, 1.15107367264116);
|
|
301
|
-
|
|
302
|
-
// Inverse input transform (outset)
|
|
303
|
-
val = agx_mat_inv * val;
|
|
304
|
-
|
|
305
|
-
// sRGB IEC 61966-2-1 2.2 Exponent Reference EOTF Display
|
|
306
|
-
// NOTE: We're linearizing the output here. Comment/adjust when
|
|
307
|
-
// *not* using a sRGB render target
|
|
308
|
-
val = pow(val, vec3(2.2));
|
|
309
|
-
|
|
310
|
-
return val;
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
vec3 _agxLook(vec3 val) {
|
|
314
|
-
const vec3 lw = vec3(0.2126, 0.7152, 0.0722);
|
|
315
|
-
float luma = dot(val, lw);
|
|
316
|
-
|
|
317
|
-
// Default
|
|
318
|
-
vec3 offset = vec3(0.0);
|
|
319
|
-
vec3 slope = vec3(1.0);
|
|
320
|
-
vec3 power = vec3(1.0);
|
|
321
|
-
float sat = 1.0;
|
|
322
|
-
|
|
323
|
-
#if AGX_LOOK == 1
|
|
324
|
-
// Golden
|
|
325
|
-
slope = vec3(1.0, 0.9, 0.5);
|
|
326
|
-
power = vec3(0.8);
|
|
327
|
-
sat = 0.8;
|
|
328
|
-
#elif AGX_LOOK == 2
|
|
329
|
-
// Punchy
|
|
330
|
-
slope = vec3(1.0);
|
|
331
|
-
power = vec3(1.35, 1.35, 1.35);
|
|
332
|
-
sat = 1.4;
|
|
333
|
-
#endif
|
|
334
|
-
|
|
335
|
-
// Needle
|
|
336
|
-
slope = vec3(1.05);
|
|
337
|
-
power = vec3(1.10, 1.10, 1.10);
|
|
338
|
-
sat = 1.15;
|
|
339
|
-
|
|
340
|
-
// User
|
|
341
|
-
// slope = userSlope;
|
|
342
|
-
// offset = userOffset;
|
|
343
|
-
// power = userPower;
|
|
344
|
-
// sat = userSaturation;
|
|
345
|
-
|
|
346
|
-
// ASC CDL
|
|
347
|
-
val = pow(val * slope + offset, power);
|
|
348
|
-
return luma + sat * (val - luma);
|
|
349
|
-
}
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
vec3 AgXToneMapping( vec3 color ) {
|
|
353
|
-
// apply AGX
|
|
354
|
-
color *= toneMappingExposure;
|
|
355
|
-
color = max(color, vec3(0.001)); // Prevent NaN
|
|
356
|
-
color = _agx(color);
|
|
357
|
-
color = _agxLook(color); // Optional
|
|
358
|
-
color = _agxEotf(color);
|
|
359
|
-
return color;
|
|
360
|
-
`,e="vec3 AgXToneMapping( vec3 color ) {",t="return color;",i=c.ShaderChunk.tonemapping_pars_fragment.indexOf(e),n=c.ShaderChunk.tonemapping_pars_fragment.indexOf(t,i);if(i>=0&&n>=0){const o=c.ShaderChunk.tonemapping_pars_fragment.substring(i,n+t.length);c.ShaderChunk.tonemapping_pars_fragment=c.ShaderChunk.tonemapping_pars_fragment.replace(o,s)}else A()&&console.error("Couldn't find AgXToneMapping in ShaderChunk.tonemapping_pars_fragment")}function G0(s){if(typeof s=="string")switch(s=s.toLowerCase(),s){case"none":return c.NoToneMapping;case"neutral":return c.NeutralToneMapping;case"aces":return c.ACESFilmicToneMapping;case"agx":return c.AgXToneMapping;case"khronos_neutral":return c.NeutralToneMapping;default:console.warn("[PostProcessing] Unknown tone mapping mode",s);return}}var sc;(s=>{function e(n){return n==="0"||n?.toLowerCase()==="false"}s.isFalsey=e;function t(n,o,r){const a=n.getAttribute(o);return e(a)?null:(r?.onAttribute?.call(null,a),a)}s.getAttributeValueIfNotFalsey=t;function i(n,o,r){const a=n.getAttribute(o);return a===null?null:e(a)?(r?.onAttribute?.call(null,a,!0),!1):(r?.onAttribute?.call(null,a,!1),a)}s.getAttributeAndCheckFalsey=i})(sc||(sc={}));async function H0(s){if(!globalThis.QRCode){const l="https://cdn.jsdelivr.net/gh/davidshimjs/qrcodejs@gh-pages/qrcode.min.js";let h=document.head.querySelector(`script[src="${l}"]`);h||(h=document.createElement("script"),h.src=l,document.head.appendChild(h)),await new Promise((d,u)=>{h.addEventListener("load",()=>{d(!0)})})}const e=globalThis.QRCode,t=s.domElement??document.createElement("div"),i=new e(t,{width:s.width??256,height:s.height??256,colorDark:"#000000",colorLight:"#ffffff",correctLevel:s.showLogo?e.CorrectionLevel.H:e.CorrectLevel.M,...s}),n=i?._oQRCode.moduleCount||0,o=i?._oDrawing?._elCanvas;let r=.25;n<40?r=Math.floor(n/4)/n:r=Math.floor(n/6)/n;const a=Math.floor(n/20)/n;try{const l=await lP(o,{showLogo:s.showLogo,logoSize:r,logoPadding:a}).catch(h=>{});l&&(t.innerHTML="",t.append(l))}catch{}if(s.showUrl!==!1&&s.text){const l=t.querySelector(".qr-code-link-label");let h=s.text.replace(/^(https?:\/\/)?(www\.)?/,"").replace(/\/+$/,"").replace(/\?+$/,"");if(h="Scan to visit "+h,l)l.textContent=h;else{const d=document.createElement("div");d.classList.add("qr-code-link-label"),s.text=h,d.textContent=s.text,d.addEventListener("click",u=>{u.stopImmediatePropagation()}),d.style.textAlign="center",d.style.fontSize="0.8em",d.style.marginTop="0.1em",d.style.color="#000000",d.style.fontFamily="'Roboto Flex', sans-serif",d.style.opacity="0.5",d.style.wordBreak="break-all",d.style.wordWrap="break-word",d.style.marginBottom="0.3em",t.style.width="calc(210px + 20px)",t.appendChild(d)}}return t}async function lP(s,e){if(!s)return;const t=8,i=20,n=e.logoPadding||1/32,o="transparent",r=0,a=new Image,l=document.querySelector("needle-engine");l||console.debug("[QR Code] No web component found");const h=$n();let d=null;if(d=sc.getAttributeAndCheckFalsey(l,"qrcode-logo-src"),h&&e.showLogo!==!0&&d===!1||(d||=sc.getAttributeAndCheckFalsey(l,"logo-src"),h&&e.showLogo!==!0&&d===!1)||(d||=sc.getAttributeAndCheckFalsey(l,"loading-logo-src",{onAttribute:()=>{A()?console.warn("[QR Code] 'loading-logo-src' is deprecated, please use 'logo-src' or 'qrcode-logo-src' instead."):console.debug("[QR Code] 'loading-logo-src' is deprecated.")}}),h&&e.showLogo!==!0&&d===!1)||(d&&!h&&(console.warn("[QR Code] Custom logo is only available with a commercial license. Using default Needle logo. Please get a commercial license at https://needle.tools/pricing."),d=null),d||=Da,!d))return;let u=!1;e.showLogo!==!1&&(a.src=d,u=await new Promise((v,E)=>{a.onload=()=>v(!0),a.onerror=O=>{const M=d!==Da?"'"+d+"'":null;console.error("[QR Code] Error loading logo image for QR code",M,A()?O:""),v(!1)}}));const p=document.createElement("canvas");p.width=s.width+t,p.height=s.height+t;const m=p.getContext("2d");if(!m)return;m.fillStyle="#ffffff",m.fillRect(0,0,p.width,p.height),m.drawImage(s,t/2,t/2),m.imageSmoothingEnabled=!0,m.imageSmoothingQuality="high",m.mozImageSmoothingEnabled=!0,m.webkitImageSmoothingEnabled=!0,m.globalCompositeOperation="lighten";const y=m.createLinearGradient(0,0,0,p.height);y.addColorStop(0,"rgb(45, 45, 45)"),y.addColorStop(1,"rgb(45, 45, 45)"),m.fillStyle=y,m.fillRect(0,0,p.width,p.height),m.globalCompositeOperation="source-over";let _=Math.min(s.width,s.height)*(e.logoSize||.25),g=_;if(u){const v=a.width/a.height;v>1?g=_/v:_=g*v;const E=n*s.width,O=Math.max(_,g),M=Math.round(O+E),D=Math.round(O+E),L=(p.width-O)/2,j=(p.height-O)/2;m.shadowColor=o,m.shadowBlur=i;const V=r,W=Math.round(L-E/2),k=Math.round(j-E/2);m.beginPath(),m.moveTo(W+V,k),m.lineTo(W+M-V,k),m.quadraticCurveTo(W+M,k,W+M,k+V),m.lineTo(W+M,k+D-V),m.quadraticCurveTo(W+M,k+D,W+M-V,k+D),m.lineTo(W+V,k+D),m.quadraticCurveTo(W,k+D,W,k+D-V),m.lineTo(W,k+V),m.quadraticCurveTo(W,k,W+V,k),m.fillStyle="#ffffff",m.closePath(),m.fill(),m.clip(),m.shadowColor="transparent";const N=(p.width-_)/2,$=(p.height-g)/2;m.drawImage(a,N,$,_,g)}const w=p.toDataURL("image/png"),b=document.createElement("img");return b.src=w,b.style.width="100%",b.style.height="auto",b}const Zp="Material Symbols Outlined";function vt(s){const e=document.createElement("span");return e.style.maxWidth="48px",e.style.maxHeight="48px",e.style.overflow="hidden",e.classList.add("material-symbols-outlined","notranslate"),e.setAttribute("translate","no"),e.innerText=s,e.style.visibility="hidden",e.style.userSelect="none",e.setAttribute("role","img"),e.setAttribute("aria-label",s+" icon"),e.setAttribute("aria-hidden","true"),fg(Zp).then(t=>{t?e.style.visibility="":s==="more_vert"?(e.style.visibility="",e.innerText="More"):e.style.display="none"}),e}function q0(s){return s.classList?.contains("material-symbols-outlined")||!1}const zh=new Map;async function Jp(s){if(await fg(Zp),zh.has(s))return zh.get(s);const e=document.createElement("canvas"),t=48;e.width=t,e.height=t;const i=e.getContext("2d");if(i){i.font=`${t}px '${Zp}'`,i.fillStyle="black",i.fillText(s,0,t);const n=e.toDataURL(),o=new c.Texture;return o.name=s+" icon",o.image=new Image,o.image.src=n,o.needsUpdate=!0,zh.set(s,o),o}return zh.set(s,null),null}const Vf=new Map;async function fg(s,e=5,t=0){document.fonts.check(`1em '${s}'`)||await document.fonts.ready;const n=Vf.get(s)||document.fonts.load(`1em '${s}'`).then(r=>r?.length>0).finally(()=>{Vf.delete(s)});return Vf.set(s,n),await n?!0:t<e?new Promise(r=>{setTimeout(()=>{r(fg(s,e,t+1))},1e3)}):!1}class Fi{static _instance;static get instance(){return this.getOrCreate()}static getOrCreate(){return this._instance||(this._instance=new Fi),this._instance}static create(){return new Fi}_fullscreenButton;get fullscreenButton(){return this._fullscreenButton}createFullscreenButton(e){if(this._fullscreenButton)return this._fullscreenButton;if(!document.fullscreenEnabled)return A()&&console.warn("NeedleMenu: Fullscreen button could not be created, device doesn't support the Fullscreen API"),null;const t=document.createElement("button");this._fullscreenButton=t,t.classList.add("fullscreen-button"),t.title="Click to enter fullscreen mode",oo.setElementPriority(t,3);const i=vt("fullscreen"),n=vt("fullscreen_exit");return t.appendChild(i),t.onclick=()=>{document.fullscreenElement?document.exitFullscreen():"webkitRequestFullscreen"in e.domElement&&typeof e.domElement.webkitRequestFullscreen=="function"?e.domElement.webkitRequestFullscreen():"requestFullscreen"in e.domElement&&e.domElement.requestFullscreen()},document.addEventListener("fullscreenchange",()=>{document.fullscreenElement?(i.remove(),t.appendChild(n),t.title="Click to enter fullscreen mode"):(n.remove(),t.appendChild(i),t.title="Click to exit fullscreen mode")}),globalThis.addEventListener("needle-xrsession-start",()=>{t.style.display="none"}),globalThis.addEventListener("needle-xrsession-end",()=>{t.style.display=""}),t}_muteButton;get muteButton(){return this._muteButton}createMuteButton(e){if(this._muteButton)return this._muteButton;const t=document.createElement("button");this._muteButton=t,t.classList.add("mute-button"),t.title="Click to mute/unmute";const i=vt("volume_off"),n=vt("volume_up");return oo.setElementPriority(t,1),e.application.muted?t.appendChild(i):t.appendChild(n),t.onclick=()=>{e.application.muted?(i.remove(),t.appendChild(n),e.application.muted=!1):(n.remove(),t.appendChild(i),e.application.muted=!0)},t}_qrButton;get qrButton(){return this._qrButton}_customQRButtonUrl;set qrButtonUrl(e){try{new URL(e),this._customQRButtonUrl=e}catch{console.warn(`[Needle] QR code button URL is not a valid URL '${e}'`)}}get qrButtonUrl(){return this._customQRButtonUrl||window.location.href}createQRCode(e){if(this._qrButton)return this._qrButton;const t=this,i=document.createElement("button");this._qrButton=i,i.innerText="QR Code",i.prepend(vt("qr_code")),i.title="Scan this QR code with your phone to open this page",this.hideElementDuringXRSession(i),oo.setElementPriority(this._qrButton,20);const n=document.createElement("div");n.style.cssText=`
|
|
361
|
-
position: fixed;
|
|
362
|
-
display: inline-block;
|
|
363
|
-
padding: 0.5rem;
|
|
364
|
-
background-color: white;
|
|
365
|
-
border-radius: 0.4rem;
|
|
366
|
-
cursor: pointer;
|
|
367
|
-
z-index: 1000;
|
|
368
|
-
box-shadow: 0 0 12px rgba(0, 0, 0, 0.2);
|
|
369
|
-
`;const o=document.createElement("div");o.classList.add("qr-code-container"),n.appendChild(o),i.addEventListener("click",()=>{if(n.parentNode)return a();A()&&window.location.href.includes("://localhost")&&fe("To access your website from another device in the same local network you have to use the IP address instead of localhost. The IP address is logged in your development server console when you start the server."),r()});async function r(){await l();const h=document.body.querySelector("needle-engine"),d=e?.anchorElement?.parentElement||h||document.body;d.appendChild(n);const u=o.getBoundingClientRect(),p=i.getBoundingClientRect();n.style.left=p.left+p.width*.5-u.width*.5+"px";const m=p.top<u.height,y="1.3rem";m?n.style.top=`calc(${p.bottom}px + ${n.style.padding} + 0.0rem)`:n.style.top=`calc(${p.top-u.height}px - ${n.style.padding} - ${y})`,n.style.opacity="0",n.style.pointerEvents="all",n.style.transition="opacity 0.2s ease-in-out",setTimeout(()=>{n.style.opacity="1",window.addEventListener("click",a,{once:!0})}),window.addEventListener("resize",a),window.addEventListener("scroll",a),document.fullscreenElement?document.fullscreenElement.appendChild(n):d.appendChild(n)}function a(){n.style.pointerEvents="none",n.style.transition="opacity 0.2s",n.style.opacity="0",setTimeout(()=>n.parentNode?.removeChild(n),500),window.removeEventListener("click",a),window.removeEventListener("resize",a),window.removeEventListener("scroll",a)}async function l(){const d=await H0({text:t.qrButtonUrl,width:200,height:200});o.innerHTML="",o.appendChild(d)}return i.addEventListener("pointerenter",()=>{l()},{once:!0}),i}hideElementDuringXRSession(e){fu(t=>{e["previous-display"]=e.style.display,e.style.display="none"}),Gm(t=>{e["previous-display"]!=null&&(e.style.display=e["previous-display"])})}}function qd(s,e){const t=e?.element||document.head,i=Array.from(t.querySelectorAll(`link[rel=stylesheet][href*='${s}']`));if(i.length<=0){const n=document.createElement("link");n.href=s,n.rel="stylesheet",t.appendChild(n),i.push(n)}if(e?.loadedCallback)for(let n=0;n<i.length;n++)e?.loadedCallback&&i[n].addEventListener("load",e.loadedCallback)}function X0(){qd("https://fonts.googleapis.com/css2?family=Roboto+Flex:opsz,wght@8..144,100..1000&display=swap")}const em="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,0,0&display=block",Xd="needle-logo-element";class Q0 extends HTMLElement{static get elementName(){return Xd}static create(){return document.createElement(Xd)}_didInitialize=!1;constructor(){super()}initializeDom(){this._root=this.attachShadow({mode:"closed"});const e=document.createElement("template");e.innerHTML=`<style>
|
|
370
|
-
:host {
|
|
371
|
-
position: relative;
|
|
372
|
-
min-width: fit-content;
|
|
373
|
-
/* height: 100%; can not have height 100% because of align-items: stretch; in the parent */
|
|
374
|
-
display: flex;
|
|
375
|
-
}
|
|
376
|
-
|
|
377
|
-
.wrapper {
|
|
378
|
-
position: relative;
|
|
379
|
-
display: grid;
|
|
380
|
-
grid-template-columns: auto auto;
|
|
381
|
-
padding: .1rem;
|
|
382
|
-
}
|
|
383
|
-
.wrapper:hover {
|
|
384
|
-
cursor: pointer;
|
|
385
|
-
}
|
|
386
|
-
img {
|
|
387
|
-
height: 100%;
|
|
388
|
-
align-self: end;
|
|
389
|
-
transition: transform 0.2s;
|
|
390
|
-
}
|
|
391
|
-
img.with-text {
|
|
392
|
-
width: 11.5ch;
|
|
393
|
-
&:hover {
|
|
394
|
-
transform: scale(1.02);
|
|
395
|
-
}
|
|
396
|
-
}
|
|
397
|
-
img.compact {
|
|
398
|
-
width: 1.7em;
|
|
399
|
-
&:hover {
|
|
400
|
-
transform: scale(1.1);
|
|
401
|
-
}
|
|
402
|
-
}
|
|
403
|
-
span {
|
|
404
|
-
font-size: 1rem;
|
|
405
|
-
white-space: nowrap;
|
|
406
|
-
}
|
|
407
|
-
</style>
|
|
408
|
-
<div class="wrapper">
|
|
409
|
-
<img class="logo with-text" src=${__} />
|
|
410
|
-
</div>
|
|
411
|
-
`,this._root.appendChild(e.content.cloneNode(!0)),this.wrapper=this._root.querySelector(".wrapper"),this._root.appendChild(this.wrapper),this.logoElement=this._root.querySelector("img.logo"),this.addEventListener("click",()=>{globalThis.open("https://needle.tools","_blank")})}ensureInitialized(){this._didInitialize||(this._didInitialize=!0,this.initializeDom())}connectedCallback(){this.ensureInitialized(),this.wrapper&&(this.wrapper.setAttribute("title","Made with Needle Engine"),this.setAttribute("aria-label","Needle Engine logo. Click to open the Needle Engine website."))}_root;wrapper;logoElement;setLogoVisible(e){this.ensureInitialized(),this.logoElement&&(this.logoElement.style.display=e?"block":"none")}setType(e){this.ensureInitialized(),this.logoElement&&(e==="full"?(this.logoElement.src=__,this.logoElement.classList.remove("with-text"),this.logoElement.classList.remove("compact")):(this.logoElement.src=Da,this.logoElement.classList.add("with-text"),this.logoElement.classList.add("compact")))}}customElements.get(Xd)||customElements.define(Xd,Q0);const $f=x("debugspatialmenu");class cP{_context;needleMenu;htmlButtonsMap=new Map;enabled=!0;constructor(e,t){this._context=e,this._context.pre_render_callbacks.push(this.preRender),this.needleMenu=t;const i=this.needleMenu.shadowRoot?.querySelector(".options");i?new MutationObserver(o=>{if(this.enabled&&!(this._context.isInXR==!1&&!$f))for(const r of o)r.type==="childList"&&(r.addedNodes.forEach(a=>{this.createButtonFromHTMLNode(a)}),r.removedNodes.forEach(a=>{const l=a,h=this.htmlButtonsMap.get(l);h&&(this.htmlButtonsMap.delete(l),h.remove(),ie.__webpack_exports__default.update())}))}).observe(i,{childList:!0}):console.error("Could not find options container in needle menu")}setEnabled(e){this.enabled=e,e||this.menu?.removeFromParent()}userRequestedMenu=!1;setDisplay(e){return this.enabled?(this.userRequestedMenu=e,!0):!1}onDestroy(){const e=this._context.pre_render_callbacks.indexOf(this.preRender);e>-1&&this._context.pre_render_callbacks.splice(e,1)}uiisDirty=!1;markDirty(){this.uiisDirty=!0}_showNeedleLogo;showNeedleLogo(e){this._showNeedleLogo=e}_wasInXR=!1;preRender=()=>{if(!this.enabled){this.menu?.removeFromParent();return}$f&&exports.DeviceUtilities.isDesktop()&&this.updateMenu();const e=this._context.xr;if(!(e?.running&&(e?.isPassThrough||e?.isVR))){this._wasInXR&&(this._wasInXR=!1,this.onExitXR());return}this._wasInXR||(this._wasInXR=!0,this.onEnterXR()),this.updateMenu()};onEnterXR(){const e=this.needleMenu.shadowRoot?.querySelector(".options");e&&e.childNodes.forEach(t=>{this.createButtonFromHTMLNode(t)})}onExitXR(){this.menu?.removeFromParent()}createButtonFromHTMLNode(e){const t=this.getMenu(),i=this.htmlButtonsMap.get(e);if(i){i.add();return}if(e instanceof HTMLButtonElement){const n=this.createButton(t,e);this.htmlButtonsMap.set(e,n),n.add()}else e instanceof HTMLSlotElement&&e.assignedNodes().forEach(n=>{this.createButtonFromHTMLNode(n)})}_menuTarget=new c.Object3D;positionFilter=new Lm(90,.5);updateMenu(){const e=this.getMenu();this.handleNeedleWatermark(),this._context.scene.add(e);const t=this._context.mainCamera,n=this._context.xr?.rigScale||1;if(t){const o=t.worldPosition,r=t.worldForward.multiplyScalar(-1),a=r.y>.6,l=r.y>.4,h=(e.visible?l:a)||this.userRequestedMenu,d=!e.visible&&h;e.visible=h||exports.DeviceUtilities.isDesktop()&&$f,r.multiplyScalar(3*n),o.add(r),d&&(e.position.copy(this._menuTarget.position),e.position.y+=.25,this._menuTarget.position.copy(e.position),this.positionFilter.reset(e.position),e.quaternion.copy(this._menuTarget.quaternion),this.markDirty());const p=this._menuTarget.position.distanceTo(o);(d||p>1.5*n)&&(this.ensureRenderOnTop(this.menu),this._menuTarget.position.copy(o),this._context.scene.add(this._menuTarget),Bc(this._menuTarget,this._context.mainCamera,!0,!0),this._menuTarget.removeFromParent()),this.positionFilter.filter(this._menuTarget.position,e.position,this._context.time.time),this.menu?.quaternion.slerp(this._menuTarget.quaternion,this._context.time.deltaTime*5),this.menu?.scale.setScalar(n)}this.uiisDirty&&(this.uiisDirty=!1,ie.__webpack_exports__default.update())}ensureRenderOnTop(e,t=0){e instanceof c.Mesh&&(e.material.depthTest=!1,e.material.depthWrite=!1),e.renderOrder=1e3+t*2;for(const i of e.children)this.ensureRenderOnTop(i,t+1)}familyName="Needle Spatial Menu";menu;get isVisible(){return this.menu?.visible}getMenu(){if(this.menu)return this.menu;this.ensureFont(),this.menu=new ie.__webpack_exports__default.Block({boxSizing:"border-box",fontFamily:this.familyName,height:"auto",fontSize:.1,color:0,lineHeight:1,backgroundColor:16777215,backgroundOpacity:.55,borderRadius:1,whiteSpace:"pre-wrap",flexDirection:"row",alignItems:"center",padding:new c.Vector4(0,.05,0,.05),borderColor:0,borderOpacity:.05,borderWidth:.005});const e=P.get("ObjectRaycaster");return e&&nr(this.menu,new e),this.menu}_poweredByNeedleElement;handleNeedleWatermark(){if(!this._poweredByNeedleElement){this._poweredByNeedleElement=new ie.__webpack_exports__default.Block({width:"auto",height:"auto",fontSize:.05,whiteSpace:"pre-wrap",flexDirection:"row",flexWrap:"wrap",justifyContent:"center",margin:.02,borderRadius:.02,padding:.02,backgroundColor:16777215,backgroundOpacity:1}),this._poweredByNeedleElement["needle:use_eventsystem"]=!0;const e=new W_(this._context,()=>globalThis.open("https://needle.tools","_self"));nr(this._poweredByNeedleElement,e);const t=new ie.__webpack_exports__default.Text({textContent:"Powered by",width:"auto",height:"auto"}),i=new ie.__webpack_exports__default.Text({textContent:"needle",width:"auto",height:"auto",fontSize:.07,margin:new c.Vector4(0,0,0,.02)});this._poweredByNeedleElement.add(t),this._poweredByNeedleElement.add(i),this.menu?.add(this._poweredByNeedleElement),this.markDirty(),new c.TextureLoader().load("https://cdn.needle.tools/static/branding/poweredbyneedle.webp",o=>{if(o){e.allowModifyUI=!1,t.removeFromParent(),i.removeFromParent();const r=o.image.width/o.image.height;this._poweredByNeedleElement?.set({backgroundImage:o,backgroundOpacity:1,width:.1*r,height:.1}),this.markDirty()}})}if(this.menu){const e=this.menu.children.indexOf(this._poweredByNeedleElement);if(!this._showNeedleLogo&&Vn())e>=0&&(this._poweredByNeedleElement.removeFromParent(),this.markDirty());else{this._poweredByNeedleElement.visible=!0,this.menu.add(this._poweredByNeedleElement);const t=this.menu.children.indexOf(this._poweredByNeedleElement);e!==t&&this.markDirty()}}}ensureFont(){let e=ie.__webpack_exports__default.FontLibrary.getFontFamily(this.familyName);e||(e=ie.__webpack_exports__default.FontLibrary.addFontFamily(this.familyName),e.addVariant("normal","normal","https://cdn.needle.tools/static/fonts/msdf/arial/arial-msdf.json","https://cdn.needle.tools/static/fonts/msdf/arial/arial.png")?.addEventListener("ready",()=>{this.markDirty()}))}createButton(e,t){const i=new ie.__webpack_exports__default.Block({width:"auto",height:"auto",whiteSpace:"pre-wrap",flexDirection:"row",flexWrap:"wrap",justifyContent:"center",backgroundColor:16777215,backgroundOpacity:0,padding:.02,margin:.01,borderRadius:.02,cursor:"pointer",fontSize:.05}),n=new ie.__webpack_exports__default.Text({textContent:"",width:"auto",justifyContent:"center",alignItems:"center",backgroundOpacity:0,backgroundColor:16777215,fontFamily:this.familyName,color:0,borderRadius:.02,padding:.01});i.add(n),i["needle:use_eventsystem"]=!0;const o=new W_(this._context,()=>t.click());return nr(i,o),new hP(this,e,t,i,n)}}class hP{menu;root;htmlbutton;spatialContainer;spatialText;spatialIcon;constructor(e,t,i,n,o){this.menu=e,this.root=t,this.htmlbutton=i,this.spatialContainer=n,this.spatialText=o,new MutationObserver(a=>{for(const l of a)l.type==="attributes"?l.attributeName==="style"&&this.updateVisible():l.type==="childList"&&this.updateText()}).observe(i,{attributes:!0,childList:!0}),this.updateText()}add(){this.spatialContainer.parent!=this.root&&(this.root.add(this.spatialContainer),this.menu.markDirty(),this.updateVisible(),this.updateText())}remove(){this.spatialContainer.parent&&(this.spatialContainer.removeFromParent(),this.menu.markDirty())}updateVisible(){const e=this.spatialContainer.visible;this.spatialContainer.visible=this.htmlbutton.style.display!=="none",e!==this.spatialContainer.visible&&this.menu.markDirty()}_lastText="";updateText(){let e="",t="";this.htmlbutton.childNodes.forEach(i=>{i.nodeType===Node.TEXT_NODE?e+=i.textContent:i instanceof HTMLElement&&q0(i)&&i.textContent&&(t=i.textContent)}),this._lastText!==e&&(this._lastText=e,this.spatialText.name=e,this.spatialText.set({textContent:e}),this.menu.markDirty()),e.length<=0?this.spatialText.parent&&(this.spatialText.removeFromParent(),this.menu.markDirty()):this.spatialText.parent||(this.spatialContainer.add(this.spatialText),this.menu.markDirty()),t&&this.createIcon(t)}_lastTexture;async createIcon(e){if(!this.spatialIcon){const i=await Jp(e);if(i&&!this.spatialIcon){const o=new ie.__webpack_exports__default.Block({width:.08,height:.08,backgroundColor:16777215,backgroundImage:i,backgroundOpacity:1,margin:new c.Vector4(0,.005,0,0)});this.spatialIcon=o,this.spatialContainer.add(o),this.menu.markDirty()}}if(e!=this._lastTexture){this._lastTexture=e;const i=await Jp(e);i&&(this.spatialIcon?.set({backgroundImage:i}),this.menu.markDirty())}const t=this.spatialContainer.children.indexOf(this.spatialIcon);t>0&&(this.spatialContainer.children.splice(t,1),this.spatialContainer.children.unshift(this.spatialIcon),this.menu.markDirty())}}class W_{isComponent=!0;enabled=!0;get activeAndEnabled(){return!0}__internalAwake(){}__internalEnable(){}__internalDisable(){}__internalStart(){}onEnable(){}onDisable(){}gameObject;allowModifyUI=!0;get element(){return this.gameObject}context;onclick;constructor(e,t){this.context=e,this.onclick=t}onPointerEnter(){this.context.input.setCursor("pointer"),this.allowModifyUI&&(this.element.set({backgroundOpacity:1}),ie.__webpack_exports__default.update())}onPointerExit(){this.context.input.unsetCursor("pointer"),this.allowModifyUI&&(this.element.set({backgroundOpacity:0}),ie.__webpack_exports__default.update())}onPointerDown(e){e.use()}onPointerUp(e){e.use()}onPointerClick(e){e.use(),this.onclick()}}const ua="needle-menu",fa=x("debugmenu"),G_=x("debugnoncommercial");let oo=class{static setElementPriority(e,t){e.setAttribute("priority",String(t))}static getElementPriority(e){const t=e.getAttribute("priority");if(t){const i=Number.parseFloat(t);if(!Number.isNaN(i))return i}}_context;_menu;_spatialMenu;constructor(e){this._menu=xu.getOrCreate(e.domElement,e),this._menu.ensureInitialized(),this._context=e,this._spatialMenu=new cP(e,this._menu),window.addEventListener("message",this.onPostMessage),fu(this.onStartXR)}onDestroy(){window.removeEventListener("message",this.onPostMessage),this._menu.remove(),this._spatialMenu.onDestroy()}onPostMessage=e=>{if(e.origin===globalThis.location.origin&&typeof e.data=="object"){const t=e.data,i=t.type;if(i==="needle:menu"){const n=t.button;if(n){if(!n.label)return console.error("NeedleMenu: buttoninfo.label is required");if(!n.onclick)return console.error("NeedleMenu: buttoninfo.onclick is required");const o=document.createElement("button");if(o.textContent=n.label,n.icon){const r=vt(n.icon);o.prepend(r)}n.priority&&o.setAttribute("priority",n.priority.toString()),o.onclick=()=>{if(n.onclick){const r=n.onclick.startsWith("http")||n.onclick.startsWith("www."),a=n.target||"_blank";r?globalThis.open(n.onclick,a):console.error("NeedleMenu: onclick is not a valid link",n.onclick)}},ni.sendEvent(this._context,"needle-menu",{action:"button_added_via_postmessage"}),this._menu.appendChild(o)}else fa&&console.error("NeedleMenu: unknown postMessage event",t)}else fa&&console.warn("NeedleMenu: unknown postMessage type",i,t)}};onStartXR=e=>{e.session.isScreenBasedAR&&(this._menu.previousParent=this._menu.parentNode,this._context.arOverlayElement.appendChild(this._menu),e.session.session.addEventListener("end",this.onExitXR),this._menu.closeFoldout())};onExitXR=()=>{this._menu.previousParent&&(this._menu.previousParent.appendChild(this._menu),delete this._menu.previousParent)};setPosition(e){this._menu.setPosition(e)}setVisible(e){this._menu.setVisible(e)}showNeedleLogo(e){this._menu.showNeedleLogo(e),this._spatialMenu?.showNeedleLogo(e)}get logoIsVisible(){return this._menu.logoIsVisible}showSpatialMenu(e){this._spatialMenu.setEnabled(e)}setSpatialMenuVisible(e){this._spatialMenu.setDisplay(e)}get spatialMenuIsVisible(){return this._spatialMenu.isVisible}showQRCodeButton(e){if(e==="desktop-only"&&(e=!exports.DeviceUtilities.isMobileDevice()),e){const t=Fi.getOrCreate().createQRCode();return t.style.display="",this._menu.appendChild(t),t}else{const t=Fi.getOrCreate().qrButton;return t&&(t.style.display="none"),t??null}}showAudioPlaybackOption(e){if(!e){this._muteButton?.remove();return}this._muteButton=Fi.getOrCreate().createMuteButton(this._context),this._menu.appendChild(this._muteButton)}_muteButton;showFullscreenOption(e){if(!e){this._fullscreenButton?.remove();return}this._fullscreenButton=Fi.getOrCreate().createFullscreenButton(this._context),this._fullscreenButton&&this._menu.appendChild(this._fullscreenButton)}_fullscreenButton;appendChild(e){return this._menu.appendChild(e)}};class xu extends HTMLElement{static create(){return document.createElement(ua)}static getOrCreate(e,t){let i=e.querySelector(ua);return!i&&e.shadowRoot&&(i=e.shadowRoot.querySelector(ua)),i||(i=window.document.body.querySelector(ua)),i||(i=xu.create(),e.shadowRoot?e.shadowRoot.appendChild(i):e.appendChild(i)),i._domElement=e,i._context=t,i}_domElement=null;_context=null;_didInitialize=!1;constructor(){super()}initializeDom(){const e=document.createElement("template");e.innerHTML=`<style>
|
|
412
|
-
|
|
413
|
-
/** Styling attributes that ensure the nested menu z-index does not cause it to overlay elements outside of <needle-engine> */
|
|
414
|
-
:host {
|
|
415
|
-
position: absolute;
|
|
416
|
-
width: 100%;
|
|
417
|
-
height: 100%;
|
|
418
|
-
z-index: 0;
|
|
419
|
-
top: 0;
|
|
420
|
-
pointer-events: none;
|
|
421
|
-
}
|
|
422
|
-
|
|
423
|
-
/** we put base styles in a layer to allow overrides more easily (e.g. the button.mode requested animation should override the base styles) */
|
|
424
|
-
@layer base {
|
|
425
|
-
|
|
426
|
-
#root {
|
|
427
|
-
position: absolute;
|
|
428
|
-
width: auto;
|
|
429
|
-
max-width: 95%;
|
|
430
|
-
left: 50%;
|
|
431
|
-
transform: translateX(-50%);
|
|
432
|
-
top: min(20px, 10vh);
|
|
433
|
-
padding: 0.3rem;
|
|
434
|
-
display: flex;
|
|
435
|
-
visibility: visible;
|
|
436
|
-
flex-direction: row-reverse; /* if we overflow this should be right aligned so the logo is always visible */
|
|
437
|
-
pointer-events: all;
|
|
438
|
-
z-index: 1000;
|
|
439
|
-
}
|
|
440
|
-
|
|
441
|
-
/** hide the menu if it's empty **/
|
|
442
|
-
#root.has-no-options.logo-hidden {
|
|
443
|
-
display: none;
|
|
444
|
-
}
|
|
445
|
-
|
|
446
|
-
/** using a div here because then we can change the class for placement **/
|
|
447
|
-
#root.bottom {
|
|
448
|
-
top: auto;
|
|
449
|
-
bottom: min(30px, 10vh);
|
|
450
|
-
}
|
|
451
|
-
#root.top {
|
|
452
|
-
top: calc(.7rem + env(safe-area-inset-top));
|
|
453
|
-
}
|
|
454
|
-
|
|
455
|
-
.wrapper {
|
|
456
|
-
position: relative;
|
|
457
|
-
display: flex;
|
|
458
|
-
flex-direction: row;
|
|
459
|
-
justify-content: center;
|
|
460
|
-
align-items: stretch;
|
|
461
|
-
gap: 0px;
|
|
462
|
-
padding: 0 0rem;
|
|
463
|
-
}
|
|
464
|
-
|
|
465
|
-
.wrapper > *, .options > button, .options > select, ::slotted(*) {
|
|
466
|
-
position: relative;
|
|
467
|
-
border: none;
|
|
468
|
-
border-radius: 0;
|
|
469
|
-
outline: 1px solid rgba(0,0,0,0);
|
|
470
|
-
display: flex;
|
|
471
|
-
justify-content: center;
|
|
472
|
-
align-items: center;
|
|
473
|
-
max-height: 2.3rem;
|
|
474
|
-
max-width: 100%;
|
|
475
|
-
|
|
476
|
-
/** basic font settings for all entries **/
|
|
477
|
-
font-size: 1rem;
|
|
478
|
-
font-family: 'Roboto Flex', sans-serif;
|
|
479
|
-
font-optical-sizing: auto;
|
|
480
|
-
font-weight: 400;
|
|
481
|
-
font-variation-settings: "wdth" 100;
|
|
482
|
-
color: rgb(20,20,20);
|
|
483
|
-
}
|
|
484
|
-
|
|
485
|
-
.options > select[multiple]:hover {
|
|
486
|
-
max-height: 300px;
|
|
487
|
-
}
|
|
488
|
-
|
|
489
|
-
.floating-panel-style {
|
|
490
|
-
background: rgba(255, 255, 255, .4);
|
|
491
|
-
outline: rgb(0 0 0 / 5%) 1px solid;
|
|
492
|
-
border: 1px solid rgba(255, 255, 255, .1);
|
|
493
|
-
box-shadow: 0px 7px 0.5rem 0px rgb(0 0 0 / 6%), inset 0px 0px 1.3rem rgba(0,0,0,.05);
|
|
494
|
-
border-radius: 1.5rem;
|
|
495
|
-
/**
|
|
496
|
-
* to make nested background filter work
|
|
497
|
-
* https://stackoverflow.com/questions/60997948/backdrop-filter-not-working-for-nested-elements-in-chrome
|
|
498
|
-
**/
|
|
499
|
-
&::before {
|
|
500
|
-
content: '';
|
|
501
|
-
position: absolute;
|
|
502
|
-
width: 100%;
|
|
503
|
-
height: 100%;
|
|
504
|
-
top: 0;
|
|
505
|
-
left: 0;
|
|
506
|
-
z-index: -1;
|
|
507
|
-
border-radius: 1.5rem;
|
|
508
|
-
-webkit-backdrop-filter: blur(8px);
|
|
509
|
-
backdrop-filter: blur(8px);
|
|
510
|
-
}
|
|
511
|
-
}
|
|
512
|
-
|
|
513
|
-
a {
|
|
514
|
-
color: inherit;
|
|
515
|
-
text-decoration: none;
|
|
516
|
-
}
|
|
517
|
-
|
|
518
|
-
.options {
|
|
519
|
-
display: flex;
|
|
520
|
-
flex-direction: row;
|
|
521
|
-
align-items: center;
|
|
522
|
-
}
|
|
523
|
-
|
|
524
|
-
.options > *, ::slotted(*) {
|
|
525
|
-
max-height: 2.25rem;
|
|
526
|
-
padding: .4rem .5rem;
|
|
527
|
-
}
|
|
528
|
-
|
|
529
|
-
:host .options > *, ::slotted(*) {
|
|
530
|
-
background: transparent;
|
|
531
|
-
border: none;
|
|
532
|
-
white-space: nowrap;
|
|
533
|
-
transition: all 0.1s linear .02s;
|
|
534
|
-
border-radius: 1.5rem;
|
|
535
|
-
user-select: none;
|
|
536
|
-
}
|
|
537
|
-
:host .options > *:hover, ::slotted(*:hover) {
|
|
538
|
-
cursor: pointer;
|
|
539
|
-
color: black;
|
|
540
|
-
background: rgba(245, 245, 245, .8);
|
|
541
|
-
box-shadow: inset 0 0 1rem rgba(0,0,30,.2);
|
|
542
|
-
outline: rgba(0,0,0,.1) 1px solid;
|
|
543
|
-
}
|
|
544
|
-
:host .options > *:active, ::slotted(*:active) {
|
|
545
|
-
background: rgba(255, 255, 255, .8);
|
|
546
|
-
box-shadow: inset 0px 1px 1px rgba(255,255,255,.5), inset 0 0 2rem rgba(0,0,30,.2), inset 0px 2px 4px rgba(0,0,20,.5);
|
|
547
|
-
transition: all 0.05s linear;
|
|
548
|
-
}
|
|
549
|
-
:host .options > *:focus, ::slotted(*:focus) {
|
|
550
|
-
outline: rgba(255,255,255,.5) 1px solid;
|
|
551
|
-
}
|
|
552
|
-
:host .options > *:focus-visible, ::slotted(*:focus-visible) {
|
|
553
|
-
outline: rgba(0,0,0,.5) 1px solid;
|
|
554
|
-
}
|
|
555
|
-
|
|
556
|
-
:host .options > *:disabled, ::slotted(*:disabled) {
|
|
557
|
-
background: rgba(0,0,0,.05);
|
|
558
|
-
color: rgba(60,60,60,.7);
|
|
559
|
-
pointer-events: none;
|
|
560
|
-
}
|
|
561
|
-
}
|
|
562
|
-
|
|
563
|
-
button, ::slotted(button) {
|
|
564
|
-
gap: 0.3rem;
|
|
565
|
-
}
|
|
566
|
-
|
|
567
|
-
/** XR button animation **/
|
|
568
|
-
|
|
569
|
-
:host button.this-mode-is-requested {
|
|
570
|
-
background: repeating-linear-gradient(to right, #fff 0%, #fff 40%, #aaffff 55%, #fff 80%);
|
|
571
|
-
background-size: 200% auto;
|
|
572
|
-
background-position: 0 100%;
|
|
573
|
-
animation: AnimationName .7s ease infinite forwards;
|
|
574
|
-
}
|
|
575
|
-
:host button.other-mode-is-requested {
|
|
576
|
-
opacity: .5;
|
|
577
|
-
}
|
|
578
|
-
|
|
579
|
-
@keyframes AnimationName {
|
|
580
|
-
0% {
|
|
581
|
-
background-position: 0% 0
|
|
582
|
-
}
|
|
583
|
-
100% {
|
|
584
|
-
background-position: -200% 0
|
|
585
|
-
}
|
|
586
|
-
}
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
.logo {
|
|
592
|
-
cursor: pointer;
|
|
593
|
-
padding-left: 0.5em;
|
|
594
|
-
padding-bottom: .02em;
|
|
595
|
-
margin-right: 0.6em;
|
|
596
|
-
}
|
|
597
|
-
.logo-hidden {
|
|
598
|
-
.logo {
|
|
599
|
-
display: none;
|
|
600
|
-
}
|
|
601
|
-
}
|
|
602
|
-
:host .has-options .logo {
|
|
603
|
-
border-left: 1px solid rgba(40,40,40,.4);
|
|
604
|
-
margin-left: 0.3em;
|
|
605
|
-
margin-right: 0.6em;
|
|
606
|
-
}
|
|
607
|
-
|
|
608
|
-
.logo > span {
|
|
609
|
-
white-space: nowrap;
|
|
610
|
-
}
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
/** COMPACT */
|
|
615
|
-
|
|
616
|
-
/** Hide the menu button normally **/
|
|
617
|
-
.compact-menu-button { display: none; }
|
|
618
|
-
|
|
619
|
-
/** Hide the compact only options when not in compact mode */
|
|
620
|
-
.options.compact-only { display: none; }
|
|
621
|
-
|
|
622
|
-
/** And show it when we're in compact mode **/
|
|
623
|
-
.compact .compact-menu-button {
|
|
624
|
-
position: relative;
|
|
625
|
-
display: block;
|
|
626
|
-
background: none;
|
|
627
|
-
border: none;
|
|
628
|
-
border-radius: 2rem;
|
|
629
|
-
|
|
630
|
-
margin: 0;
|
|
631
|
-
padding: 0 .3rem;
|
|
632
|
-
padding-top: .2rem;
|
|
633
|
-
|
|
634
|
-
z-index: 100;
|
|
635
|
-
|
|
636
|
-
color: #000;
|
|
637
|
-
|
|
638
|
-
&:hover {
|
|
639
|
-
background: rgba(255,255,255,.2);
|
|
640
|
-
cursor: pointer;
|
|
641
|
-
}
|
|
642
|
-
&:focus {
|
|
643
|
-
outline: 1px solid rgba(255,255,255,.5);
|
|
644
|
-
}
|
|
645
|
-
&:focus-visible {
|
|
646
|
-
outline: 1px solid rgba(0,0,0,.5);
|
|
647
|
-
}
|
|
648
|
-
& .expanded-click-area {
|
|
649
|
-
position: absolute;
|
|
650
|
-
left: 0;
|
|
651
|
-
right: 0;
|
|
652
|
-
top: 10%;
|
|
653
|
-
bottom: 10%;
|
|
654
|
-
transform: scale(1.8);
|
|
655
|
-
}
|
|
656
|
-
}
|
|
657
|
-
.has-no-options .compact-menu-button {
|
|
658
|
-
display: none;
|
|
659
|
-
}
|
|
660
|
-
.open .compact-menu-button {
|
|
661
|
-
background: rgba(255,255,255,.2);
|
|
662
|
-
}
|
|
663
|
-
.logo-visible .compact-menu-button {
|
|
664
|
-
margin-left: .2rem;
|
|
665
|
-
}
|
|
666
|
-
|
|
667
|
-
/** Open and hide menu **/
|
|
668
|
-
.compact .foldout {
|
|
669
|
-
display: none;
|
|
670
|
-
}
|
|
671
|
-
.open .options, .open .foldout {
|
|
672
|
-
display: flex;
|
|
673
|
-
justify-content: center;
|
|
674
|
-
}
|
|
675
|
-
.compact .wrapper {
|
|
676
|
-
padding: 0;
|
|
677
|
-
}
|
|
678
|
-
.compact .wrapper, .compact .options {
|
|
679
|
-
height: auto;
|
|
680
|
-
max-height: initial;
|
|
681
|
-
flex-direction: row;
|
|
682
|
-
gap: .12rem;
|
|
683
|
-
}
|
|
684
|
-
.compact .options {
|
|
685
|
-
flex-wrap: wrap;
|
|
686
|
-
gap: .3rem;
|
|
687
|
-
}
|
|
688
|
-
.compact .top .options {
|
|
689
|
-
height: auto;
|
|
690
|
-
flex-direction: row;
|
|
691
|
-
}
|
|
692
|
-
.compact .bottom .wrapper {
|
|
693
|
-
height: auto;
|
|
694
|
-
flex-direction: column;
|
|
695
|
-
}
|
|
696
|
-
|
|
697
|
-
.compact .foldout {
|
|
698
|
-
max-height: min(100ch, calc(100vh - 100px));
|
|
699
|
-
overflow: auto;
|
|
700
|
-
overflow-x: hidden;
|
|
701
|
-
align-items: center;
|
|
702
|
-
|
|
703
|
-
position: fixed;
|
|
704
|
-
bottom: calc(100% + 5px);
|
|
705
|
-
z-index: 100;
|
|
706
|
-
width: auto;
|
|
707
|
-
max-width: 90vw;
|
|
708
|
-
left: 50%;
|
|
709
|
-
transform: translateX(-50%);
|
|
710
|
-
padding: .2rem 1em;
|
|
711
|
-
|
|
712
|
-
}
|
|
713
|
-
.compact.logo-hidden .foldout {
|
|
714
|
-
/** for when there's no logo we want to center the foldout **/
|
|
715
|
-
min-width: 24ch;
|
|
716
|
-
}
|
|
717
|
-
|
|
718
|
-
.compact.top .foldout {
|
|
719
|
-
top: calc(100% + 5px);
|
|
720
|
-
bottom: auto;
|
|
721
|
-
}
|
|
722
|
-
|
|
723
|
-
::-webkit-scrollbar {
|
|
724
|
-
max-width: 7px;
|
|
725
|
-
background: rgba(100,100,100,.2);
|
|
726
|
-
border-radius: .2rem;
|
|
727
|
-
}
|
|
728
|
-
::-webkit-scrollbar-thumb {
|
|
729
|
-
background: rgba(255, 255, 255, .3);
|
|
730
|
-
border-radius: .2rem;
|
|
731
|
-
}
|
|
732
|
-
::-webkit-scrollbar-thumb:hover {
|
|
733
|
-
background: rgb(150,150,150);
|
|
734
|
-
}
|
|
735
|
-
|
|
736
|
-
.compact .options > *, .compact .options > ::slotted(*) {
|
|
737
|
-
font-size: 1.2em;
|
|
738
|
-
padding: .6em .5em;
|
|
739
|
-
width: 100%;
|
|
740
|
-
}
|
|
741
|
-
.compact.has-options .logo {
|
|
742
|
-
border: none;
|
|
743
|
-
padding-left: 0;
|
|
744
|
-
margin-bottom: .02em;
|
|
745
|
-
}
|
|
746
|
-
.compact .options.compact-only {
|
|
747
|
-
display: initial;
|
|
748
|
-
& > * {
|
|
749
|
-
min-height: 1em;
|
|
750
|
-
padding: .4em .4em;
|
|
751
|
-
}
|
|
752
|
-
}
|
|
753
|
-
.compact .options {
|
|
754
|
-
/** e.g. if we have a very wide menu item like a select with long option names we don't want to overflow **/
|
|
755
|
-
max-width: 100%;
|
|
756
|
-
|
|
757
|
-
& > button, & > select {
|
|
758
|
-
display: flex;
|
|
759
|
-
flex-basis: 100%;
|
|
760
|
-
min-height: 3rem;
|
|
761
|
-
min-width: 3rem;
|
|
762
|
-
}
|
|
763
|
-
& > button.row2 {
|
|
764
|
-
//border: 1px solid red !important;
|
|
765
|
-
display: flex;
|
|
766
|
-
flex: 1;
|
|
767
|
-
flex-basis: 30%;
|
|
768
|
-
}
|
|
769
|
-
}
|
|
770
|
-
|
|
771
|
-
/** If there's really not enough space then just hide all options **/
|
|
772
|
-
@media (max-width: 100px) or (max-height: 100px){
|
|
773
|
-
.foldout {
|
|
774
|
-
display: none !important;
|
|
775
|
-
}
|
|
776
|
-
.compact-menu-button {
|
|
777
|
-
display: none !important;
|
|
778
|
-
}
|
|
779
|
-
}
|
|
780
|
-
|
|
781
|
-
</style>
|
|
782
|
-
|
|
783
|
-
<div id="root" class="logo-hidden floating-panel-style bottom">
|
|
784
|
-
<div class="wrapper">
|
|
785
|
-
<div class="options compact-only" part="options">
|
|
786
|
-
</div>
|
|
787
|
-
<div class="foldout">
|
|
788
|
-
<div class="options main-container" part="options">
|
|
789
|
-
<slot></slot>
|
|
790
|
-
</div>
|
|
791
|
-
<div class="options" part="options">
|
|
792
|
-
<slot name="end"></slot>
|
|
793
|
-
</div>
|
|
794
|
-
</div>
|
|
795
|
-
<div style="user-select:none;" class="logo">
|
|
796
|
-
<span class="madewith notranslate" style="display:none;">powered by</span>
|
|
797
|
-
</div>
|
|
798
|
-
</div>
|
|
799
|
-
<button class="compact-menu-button">
|
|
800
|
-
<div class="expanded-click-area"></div>
|
|
801
|
-
</button>
|
|
802
|
-
</div>
|
|
803
|
-
`;const t=this.attachShadow({mode:"open"});X0(),qd(em,{loadedCallback:()=>{this.handleSizeChange()}}),qd(em,{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(vt("more_vert")),this.foldout=this.root?.querySelector(".foldout"),this.root?.appendChild(this.wrapper),this.wrapper.classList.add("wrapper");const n=Q0.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(()=>wP(d=>{if(d==!0&&$n()&&!G_){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)=>{fa&&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)&&!$n()){const p=r++;yi()&&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}),fa&&this.___insertDebugOptions()}ensureInitialized(){this._didInitialize||(this._didInitialize=!0,this.initializeDom())}_sizeChangeInterval;connectedCallback(){this.ensureInitialized(),window.addEventListener("resize",this.handleSizeChange),this.handleMenuVisible(),this._sizeChangeInterval=setInterval(()=>this.handleSizeChange(void 0,!1),5e3),setTimeout(()=>{this._domElement?.addEventListener("resize",this.handleSizeChange),this._domElement?.addEventListener("click",this.#t)},1)}disconnectedCallback(){window.removeEventListener("resize",this.handleSizeChange),clearInterval(this._sizeChangeInterval),this._domElement?.removeEventListener("resize",this.handleSizeChange),this._context?.domElement.removeEventListener("click",this.#t)}#t=e=>{if(!e.defaultPrevented&&e.target==this._domElement&&e instanceof PointerEvent&&e.button===0&&this.root.classList.contains("open")){const t=this.foldout.getBoundingClientRect(),i=e;i.clientX>t.left&&i.clientX<t.right&&i.clientY>t.top&&i.clientY<t.bottom||this.root.classList.toggle("open",!1)}};_userRequestedLogoVisible=void 0;showNeedleLogo(e){this._userRequestedLogoVisible=e,!(!e&&(!$n()||G_)&&(console.warn("[Needle Engine] You need a PRO license to hide the Needle Engine logo in production."),!yi()))&&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=>{ni.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=vt(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(){fa&&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 fa&&h!==a&&(a=h,Se(`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=oo.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(ua)||customElements.define(ua,xu);const Ne=x("debugcontext"),dP=x("stats"),uP=x("debugactive"),fP=x("debugframerate"),pP=x("debugcoroutine"),mP={};class gP{name;alias;hash;runInBackground;domElement;renderer;camera;scene}var ge=(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))(ge||{});function Su(s,e){if(!s)return;if(!s.isComponent){(A()||Ne)&&console.error(`Registered script is not a Needle Engine component.
|
|
804
|
-
The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
|
|
805
|
-
`,s);return}e||(e=U.Current,Ne&&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 ii}static get Current(){return ce.Current}static set Current(e){ce.Current=e}static get All(){return ce.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;accessibility;get isCreated(){return this._isCreated}get rootSourceId(){return this.rootSceneSourceIdentifiers[0]||void 0}_needsUpdateSize=!1;_isCreated=!1;_isCreating=!1;_isVisible=!1;_stats=dP?new X.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 fn(this),this.time=new $0,this.input=new Nv(this),this.physics=new Ia(this),this.connection=new Qv(this),this.assets=new Jv,this.sceneLighting=new N0(this),this.addressables=new I0(this),this.lightmaps=new K1(this),this.players=new z0(this),this.menu=new oo(this),this.lodsManager=new Z1(this),this.animations=new X1(this),this.accessibility=new Fd(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()),ce.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,Ne&&console.log("Using canvas from shadow root",t)):Ne&&console.warn("No canvas found in shadow root, creating new canvas. This may cause input events to not work correctly. To fix this, make sure to use the canvas provided by the Needle Engine Web Component (e.g. by using context.createNewRenderer() without parameters or passing the canvas from the shadow root explicitly).")}return Ne&&console.log("Using Renderer Parameters:",e,this.domElement),this.renderer=new c.WebGLRenderer(e),this.renderer.domElement.setAttribute("aria-label","3D rendering"),this.renderer.domElement.setAttribute("role","img"),this.renderer.debug.checkShaderErrors=A()||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(),gC(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=Ic(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(){ce.dispatchCallback(le.ContextClearing,this),xn(this,le.ContextClearing),bi(this.scene,!0,!0),this.scene=new c.Scene,this.addressables?.dispose(),this.lightmaps?.clear(),this.physics?.engine?.clearCaches(),this.lodsManager.disable(),this.accessibility?.clear(),this._onBeforeRenderListeners.clear(),this._onAfterRenderListeners.clear(),this.isManagedExternally||this.renderer&&(this.renderer.renderLists.dispose(),this.renderer.state.reset(),this.renderer.resetState()),ce.dispatchCallback(le.ContextCleared,this)}dispose(){this.internalOnDestroy(),this.accessibility.dispose()}onDestroy(){this.internalOnDestroy()}internalOnDestroy(){U.Current=this,ce.dispatchCallback(le.ContextDestroying,this),xn(this,le.ContextDestroying),this.clear(),this.renderer?.setAnimationLoop(null),this.renderer&&(this.renderer.setClearAlpha(0),this.renderer.clear(),this.isManagedExternally||(Ne&&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,ce.dispatchCallback(le.ContextDestroyed,this),xn(this,le.ContextDestroyed),ce.unregister(this),U.Current===this&&(U.Current=null)}registerCoroutineUpdate(e,t,i){return typeof t?.next!="function"?(console.error("Registered invalid coroutine function from "+e.name+`
|
|
806
|
-
Coroutine functions must be generators: "*myCoroutine() {...}"
|
|
807
|
-
Start a coroutine from a component by calling "this.startCoroutine(myCoroutine())"`),t):(this.coroutines[i]||(this.coroutines[i]=[]),this.coroutines[i].push({comp:e,main:t}),t)}unregisterCoroutineUpdate(e,t){if(!this.coroutines[t])return;const i=this.coroutines[t].findIndex(n=>n.main===e);i>=0&&this.coroutines[t].splice(i,1)}stopAllCoroutinesFrom(e){for(const t in this.coroutines){const i=this.coroutines[t];for(let n=i.length-1;n>=0;n--)i[n].comp===e&&i.splice(n,1)}}_cameraStack=[];setCurrentCamera(e){if(!e)return;if(e.threeCamera||e.buildCamera(),!e.threeCamera){console.warn("Camera component is missing camera",e);return}const t=this._cameraStack.indexOf(e);t>=0&&this._cameraStack.splice(t,1),this._cameraStack.push(e),this.mainCameraComponent=e;const i=e.threeCamera;i.isPerspectiveCamera&&this.updateAspect(i),this.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}removeCamera(e){if(!e)return;const t=this._cameraStack.indexOf(e);if(t>=0&&this._cameraStack.splice(t,1),this.mainCameraComponent===e&&(this.mainCameraComponent=void 0,this._cameraStack.length>0)){const i=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(i)}}_onBeforeRenderListeners=new Map;_onAfterRenderListeners=new Map;addBeforeRenderListener(e,t){if(!this._onBeforeRenderListeners.has(e.uuid)){const i=[];this._onBeforeRenderListeners.set(e.uuid,i),e.onBeforeRender=this._createRenderCallbackWrapper(i)}this._onBeforeRenderListeners.get(e.uuid).push(t)}removeBeforeRenderListener(e,t){if(this._onBeforeRenderListeners.has(e.uuid)){const i=this._onBeforeRenderListeners.get(e.uuid),n=i.indexOf(t);n>=0&&i.splice(n,1)}}addAfterRenderListener(e,t){if(!this._onAfterRenderListeners.has(e.uuid)){const i=[];this._onAfterRenderListeners.set(e.uuid,i),e.onAfterRender=this._createRenderCallbackWrapper(i)}this._onAfterRenderListeners.get(e.uuid)?.push(t)}removeAfterRenderListener(e,t){if(this._onAfterRenderListeners.has(e.uuid)){const i=this._onAfterRenderListeners.get(e.uuid),n=i.indexOf(t);n>=0&&i.splice(n,1)}}_createRenderCallbackWrapper(e){return(t,i,n,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;Ne&&console.log("Creating context",this.name,e);const i=globalThis["needle:dependencies:ready"];i instanceof Promise&&(Ne&&console.log("Waiting for dependencies to be ready"),await i.catch(d=>{if(Ne||A()){if(Uc("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 y=d.message.substring(p+1,m);y.length>3&&(u=y)}}console.error(`Needle Engine dependencies failed to load:
|
|
808
|
-
|
|
809
|
-
# Make sure you don't have circular imports in your scripts!
|
|
810
|
-
|
|
811
|
-
Possible solutions:
|
|
812
|
-
→ Replace @serializable(${u}) in your script with @serializable(Behaviour)
|
|
813
|
-
→ If you only need type information try importing the type only, e.g: import { type ${u} }
|
|
814
|
-
|
|
815
|
-
---`,d);return}console.error("Needle Engine dependencies failed to load",d)}}).then(()=>{Ne&&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 ce.dispatchCallback(le.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 Ne&&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;fr(this.scene,u=>{const p=u;if(p?.isCamera){if(ic(p.gameObject),!p.activeAndEnabled)return;if(p.tag==="MainCamera")return d=p,!0;d=p}}),d?this.setCurrentCamera(d):!ce.dispatchCallback(le.MissingCamera,this,{files:a})&&!this.mainCamera&&!this.isManagedExternally&&console.warn("Missing camera in main scene",this)}this.input.bindEvents(),U.Current=this,Nd(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)),Ne&&jd(this.scene,!0),this.targetFrameRate===void 0?(Ne&&console.warn("No target framerate set, using default",U.DefaultTargetFrameRate),this.targetFrameRate=U._defaultTargetFramerate):Ne&&console.log("Target framerate set to",this.targetFrameRate),this._dispatchReadyAfterFrame=!0;const l=ce.dispatchCallback(le.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),xn(this,le.ContextCreated),Ne&&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=un(),a=0;for(let l=0;l<n.length;l++){if(t.abortSignal?.aborted){Ne&&console.log("Aborting loading because of abort signal");break}if(e!==this._createId){Ne&&console.log("Aborting loading because create id changed",e,this._createId);break}const h=n[l];t?.onLoadingStart?.call(this,l,h),Ne&&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){Ne&&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)bi(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),bo.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),A()||Ne||u1())try{this.internalStep(e,t),this._renderlooperrors=0}catch(i){this._renderlooperrors+=1,(A()||Ne)&&(i instanceof Error||i instanceof TypeError)&&Se("Caught unhandled exception during render-loop - see console for details.",{type:gi.Error}),console.error("Frame #"+this.time.frame+`
|
|
816
|
-
`,i),this._renderlooperrors>=3&&(console.warn("Stopping render loop due to error"),this.renderer.setAnimationLoop(null),ni.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(),fP&&console.log("FPS",this.time.smoothedFps.toFixed(0)),Nd(this),pd(this.scene),a0(this),xn(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),xn(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),xn(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),xn(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),xn(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||(m1(this),this._currentFrameEvent=-1,X.nodeFrame.camera=this.mainCamera,X.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),xn(this,4),this.post_render_callbacks)for(const e in this.post_render_callbacks)this.post_render_callbacks[e]()}if(this._currentFrameEvent=-1,this.connection.sendBufferedMessagesNow(),this._stats){this._stats.end();const e=this.time.fps<20?50:150;if(this.time.frameCount%e===0||this.time.frameCount===1){const t=window.performance&&window.performance.memory?`${(window.performance.memory.usedJSHeapSize/1024/1024).toFixed(2)} MB`:"n/a";console.log(this.renderer.info.render.calls+" DrawCalls",`
|
|
817
|
-
Render:`,{shaders:this.renderer.info.programs?.length,...this.renderer.info.render},`
|
|
818
|
-
Memory:`,{usedMemory:t,...this.renderer.info.memory},`
|
|
819
|
-
Target Framerate: `+this.targetFrameRate)}}this._dispatchReadyAfterFrame&&(this._dispatchReadyAfterFrame=!1,this.domElement.dispatchEvent(new CustomEvent("ready")),ce.dispatchCallback(le.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&&W0(),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){uP&&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){pP&&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=F0(d);o.chained?.push(u);continue}}catch(o){console.error(o)}}function t(i){return!!(i&&i.next&&i.return)}}}function pg(s,e){return xs(s,le.ContextCreated,e),()=>_o(s,le.ContextCreated)}function yP(s,e){return xs(s,le.ContextClearing,e),()=>_o(s,le.ContextClearing)}function _P(s,e){return xs(s,le.ContextDestroying,e),()=>_o(s,le.ContextDestroying)}function Cu(s,e){return xs(s,ge.Start,e),()=>_o(s,ge.Start)}function Y0(s,e){return xs(s,ge.Update,e),()=>_o(s,ge.Update)}function bP(s,e){return xs(s,ge.OnBeforeRender,e),()=>_o(s,ge.OnBeforeRender)}function vP(s,e){return xs(s,ge.OnAfterRender,e),()=>_o(s,ge.OnAfterRender)}const bt=x("debuglicense"),K0=[];let hn="basic";bt&&console.log("License Type: "+hn);function Vn(){switch(hn){case"pro":case"enterprise":return!0}return!1}function Hc(){return hn==="indie"}function mg(){return hn==="edu"}function $n(){return Vn()||Hc()||mg()}function wP(s){if(Vn()||Hc()||mg())return s(!0);K0.push(s)}function Nh(s){for(const e of K0)try{e(s)}catch{}}var ni;(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()})}),pg((a=>e(a)),{once:!0});function e(a){if(!t(a)){bt&&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&&yi()){const d=(a.domElement?.getAttribute("src")||"")+ii+Ea+mc+no;window.sessionStorage.getItem("session_key")!==d&&(window.sessionStorage.setItem("session_key",d),n(a,"info",{src:a.domElement?.getAttribute("src")||"",version:ii,generator:Ea,build_time:mc,public_key:no}))}})}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")&&(hn==="pro"||hn==="enterprise")?(bt&&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)){bt&&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)){bt&&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=>{bt&&console.error("Failed to send telemetry",h)})}catch(l){bt&&console.error(l)}return Promise.resolve()}})(ni||(ni={}));ce.registerCallback(le.ContextRegistered,s=>{CP(s.context),SP(s.context),setTimeout(()=>OP(s.context),2e3)});let Qd,tm=!1,im="";async function xP(){if(Qd)return Qd;if(hn==="basic")try{const s="https://needle.tools/api/v1/needle-engine/check?location="+encodeURIComponent(window.location.href)+"&version="+ii+"&generator="+encodeURIComponent(Ea),e=await fetch(s,{method:"GET"}).catch(t=>{bt&&console.error("License check failed",t)});e?.status===200?(tm=!1,bt&&console.log("License check succeeded"),hn="pro",Nh(!0)):e?.status===403?(Nh(!1),tm=!0,im=await e.text()):(Nh(!1),bt&&console.log("License check failed with status "+e?.status))}catch(s){Nh(!1),bt&&console.error("License check failed",s)}else bt&&console.log('Runtime license check is skipped because license is already applied as "'+hn+'"')}Qd=xP();async function SP(s){function e(){const n=document.createElement("div");n.className="needle-forbidden",n.style.cssText=`
|
|
820
|
-
position: fixed;
|
|
821
|
-
top: 0;
|
|
822
|
-
left: 0;
|
|
823
|
-
width: 100%;
|
|
824
|
-
height: 100%;
|
|
825
|
-
pointer-events: all;
|
|
826
|
-
zIndex: 2147483647;
|
|
827
|
-
line-height: 1.5;
|
|
828
|
-
backdrop-filter: blur(15px);
|
|
829
|
-
-webkit-backdrop-filter: blur(15px);
|
|
830
|
-
`;const o=n.style.cssText,r=document.createElement("div");n.appendChild(r),r.style.cssText=`
|
|
831
|
-
position: absolute;
|
|
832
|
-
left: 0;
|
|
833
|
-
right: 0;
|
|
834
|
-
top:0;
|
|
835
|
-
bottom: 0;
|
|
836
|
-
padding: 10%;
|
|
837
|
-
color: white;
|
|
838
|
-
font-size: 20px;
|
|
839
|
-
font-family: sans-serif;
|
|
840
|
-
text-align: center;
|
|
841
|
-
pointer-events: all;
|
|
842
|
-
display: flex;
|
|
843
|
-
justify-content: center;
|
|
844
|
-
align-items: center;
|
|
845
|
-
background-color: rgba(0,0,0,.3);
|
|
846
|
-
text-shadow: 0 0 2px black;
|
|
847
|
-
`;const a=r.style.cssText,l=im?.length>1?im:"This web application has been paused.<br/>You might be in violation of the Needle Engine terms of use.<br/>Please contact the Needle support if you think this is a mistake.";return r.innerHTML=l,setInterval(()=>{r.innerHTML!==l&&(r.innerHTML=l),r.parentNode!==n&&n.appendChild(r),n.style.cssText!==o&&(n.style.cssText=o),r.style.cssText!==a&&(r.style.cssText=a)},500),n}let t=e();const i=t.style.cssText;setInterval(()=>{tm===!0&&(t.style.cssText!==i&&(t=e()),s.domElement.shadowRoot?t.parentNode!==s.domElement.shadowRoot&&s.domElement.shadowRoot?.appendChild(t):t.parentNode!=document.body&&document.body.appendChild(t))},500)}async function CP(s){try{if(!Vn()&&!Hc())return Wf(s)}catch(e){return bt&&console.log("License check failed",e),Wf(s)}bt&&Wf(s)}async function Wf(s){let e=!1;s.domElement.addEventListener("ready",()=>e=!0),await Qd?.catch(()=>{}),!(Vn()||Hc())&&($n()===!1&&PP(),e?nm(s):s.domElement.addEventListener("ready",()=>{nm(s)}))}function nm(s){const e=`
|
|
848
|
-
position: relative;
|
|
849
|
-
display: block;
|
|
850
|
-
background-size: 20px;
|
|
851
|
-
background-position: 10px 5px;
|
|
852
|
-
background-repeat:no-repeat;
|
|
853
|
-
background-image:url('${Z0}');
|
|
854
|
-
background-max-size: 40px;
|
|
855
|
-
padding: 10px;
|
|
856
|
-
padding-left: 30px;
|
|
857
|
-
`;if(hn==="edu")navigator.webdriver?console.log("This project is supported by Needle for Education – https://needle.tools"):console.log("%c This project is supported by Needle for Education – https://needle.tools",e);else return;const t=document.createElement("div");t.className="needle-non-commercial-use",t.innerHTML="Made with Needle for Education",s.domElement.shadowRoot?.appendChild(t);let i=`
|
|
858
|
-
position: absolute;
|
|
859
|
-
font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
|
|
860
|
-
font-size: 12px;
|
|
861
|
-
color: rgb(100, 100, 100);
|
|
862
|
-
/*mix-blend-mode: difference;*/
|
|
863
|
-
background-color: transparent;
|
|
864
|
-
z-index: 10000;
|
|
865
|
-
|
|
866
|
-
cursor: pointer;
|
|
867
|
-
user-select: none;
|
|
868
|
-
opacity: 0;
|
|
869
|
-
|
|
870
|
-
bottom: 6px;
|
|
871
|
-
right: 12px;
|
|
872
|
-
transform: translateY(0px);
|
|
873
|
-
transition: all .5s ease-in-out 1s;
|
|
874
|
-
`;t.style.cssText=i,t.addEventListener("click",()=>{window.open("https://needle.tools","_blank")});let n=t.style.cssText;setTimeout(()=>{i=i.replace("opacity: 0","opacity: 1"),i=i.replace("transform: translateY(10px)","transform: translateY(0)"),t.style.cssText=i,n=t.style.cssText},100);const o=setInterval(()=>{const r=s.domElement.shadowRoot||s.domElement;t.parentNode!==r&&r.appendChild(t),n!=t.style.cssText&&(t.style.cssText=i,n=t.style.cssText)},1e3);mg()&&setTimeout(()=>{clearInterval(o),t?.remove(),setTimeout(()=>{s.domElement.parentNode&&nm(s)},1e3*60*5)},2e4)}const Z0="data:image/webp;base64,UklGRrABAABXRUJQVlA4WAoAAAAQAAAAHwAAHwAAQUxQSKEAAAARN6CmbSM4WR7vdARON11EBDq3fLiNbVtVzpMCPlKAEzsx0Y/x+Ovuv4dn0EFE/ydAvz6YggXzgh5sVgXM/zOC/4sii7qgGvB5N7hmuQYwkvazWAu1JPW41FXSHq6pnaQWvqYH18Fc0j1hO/BFTtIeSBlJi5w6qIIO7IOrwhFsB2Yxukif0FTRLpXswHR8MxbslKe9VZsn/Ub5C7YFOpqSTABWUDgg6AAAAFAGAJ0BKiAAIAA+7VyoTqmkpCI3+qgBMB2JbACdMt69DwMIQBLhkTO6XwY00UEDK6cNIDnuNibPf0EgAP7Y1myuiQHLDsF/0h5unrGh6WAbv7aegg2ZMd3uRKfT/3SJztcaujYfTvMXspfCTmYcoO6a+vhC3ss4M8uM58t4siiu59I4aOl59e9Sr6xoxYlHf2v+NnBNpJYeJf8jABQAId/PXuBkLEFkiCucgSGEcfhvajql/j3reCGl0M5/9gQWy7ayNPs+wlvIxFnNfSlfuND4CZOCyxOHhRqOmHN4ULHo3tCSrUNvgAA=";let H_=0;async function PP(s){const e=Date.now();if(e-H_<2e3)return;H_=e;const t=`
|
|
875
|
-
position: relative;
|
|
876
|
-
display: block;
|
|
877
|
-
font-size: 18px;
|
|
878
|
-
background-size: 20px;
|
|
879
|
-
background-position: 10px 5px;
|
|
880
|
-
background-repeat:no-repeat;
|
|
881
|
-
background-image:url('${Z0}');
|
|
882
|
-
background-max-size: 40px;
|
|
883
|
-
margin-bottom: 5px;
|
|
884
|
-
margin-top: .3em;
|
|
885
|
-
margin-bottom: .5em;
|
|
886
|
-
padding: .2em;
|
|
887
|
-
padding-left: 25px;
|
|
888
|
-
border-radius: .5em;
|
|
889
|
-
border: 2px solid rgba(160,160,160,.3);
|
|
890
|
-
`,n=`Needle Engine — No license active, commercial use is not allowed. Visit https://needle.tools/pricing for more information and licensing options! v${ii}`;U.Current?.xr||navigator.webdriver?console.log(n):console.log("%c "+n,t)}async function OP(s){if(!window.crossOriginIsolated){if(!ni.isAllowed(s)){bt&&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:hn,url:t,hostname:window.location.hostname,pathname:window.location.pathname,version:ii,generator:Ea,build_time:mc,public_key:no},o=navigator.sendBeacon?.(e,JSON.stringify(n));bt&&console.debug("Sent beacon: "+o)}}catch(e){bt&&console.log("Failed to send non-commercial usage message to analytics backend",e)}}}const MP=x("debugdecoders");let Gf=null;function J0(){if(!Gf){const s=re.createLoaders(null);Gf={dracoLoader:s.dracoLoader,ktx2Loader:s.ktx2Loader,meshoptDecoder:s.meshoptDecoder}}return Gf}function q_(s){s!==void 0&&typeof s=="string"&&re.setDracoDecoderLocation(s)}function X_(s){if(s!==void 0&&typeof s=="string"&&s!=="js"){const e=J0();MP&&console.log("Setting draco decoder type to",s),e.dracoLoader.setDecoderConfig({type:s})}}function Q_(s){s!==void 0&&typeof s=="string"&&re.setKTX2TranscoderLocation(s)}function gg(s,e){const t=J0();return e.renderer?t.ktx2Loader.detectSupport(e.renderer):console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures will probably fail"),re.addDracoAndKTX2Loaders(s),s.dracoLoader||s.setDRACOLoader(t.dracoLoader),s.ktx2Loader||s.setKTX2Loader(t.ktx2Loader),s.meshoptDecoder||s.setMeshoptDecoder(t.meshoptDecoder),re.configureLoader(s,{progressive:!0}),s}const Be=function(s){return f(s)},f=function(s){if(s===void 0&&(s=null),!Array.isArray(s))s=Y_(s);else for(let e=0;e<s.length;e++){const t=s[e];s[e]=Y_(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 Y_(s){switch(s?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return s}const ro=x("debughotreload");let wc=!1;const oc=new Map;function kP(){return wc}function sm(){return globalThis.NEEDLE_HOT_RELOAD_ENABLED===!0}function ew(s){if(wc){ro&&console.warn("[Needle Engine] Hot reloading is in progress, not registering instance",s);return}ro&&console.log("[Needle Engine] Registering hot reload instance",s);const t=s.constructor.name;oc.has(t)?oc.get(t)?.push(s):oc.set(t,[s])}function tw(s){if(wc){ro&&console.warn("[Needle Engine] Hot reloading is in progress, not unregistering instance",s);return}ro&&console.log("[Needle Engine] Unregistering hot reload instance",s);const t=s.constructor.name,i=oc.get(t);if(!i)return;const n=i.indexOf(s);n!==-1&&i.splice(n,1)}let K_=!1;function RP(){if(ro||K_)return;K_=!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 EP(s){ro&&console.log("[HMR] Apply changes",s,Object.keys(s)),RP();for(const e of Object.keys(s))try{wc=!0;const t=P.get(e);if(!t){ro&&console.log("[HMR] Type not found: "+e);continue}const i=s[e],n=oc.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,y=m?p.activeAndEnabled:!0,_=m?p.context:void 0;try{if(m&&_&&as(p,_),m&&y&&(p.enabled=!1),u.onBeforeHotReloadFields&&u.onBeforeHotReloadFields()===!1)continue;for(const g in d)if(d[g].writable){if(u[g]===void 0)u[g]=h[g];else if(typeof u[g]=="function"&&!u[g].prototype){const b=u[g],v=b.name,E="bound ";if(v===E)continue;const O=b.name.substring(E.length),M=i.prototype[O];M&&(u[g]=M.bind(u))}}u.onAfterHotReloadFields&&u.onAfterHotReloadFields()}finally{m&&_&&ig(p,_),m&&y&&(p.enabled=!0)}}}}catch(t){if(ro)console.error(t);else return!1}finally{wc=!1,Yo(gi.Log,"Script changes applied (HMR)")}return!0}class S extends c.Object3D{guid;static isDestroyed(e){return ur(e)}static setActive(e,t,i=!0){e&&(nc(e,t),pd(e),t&&i&&a0(U.Current,e))}static isActiveSelf(e){return Ga(e)}static isActiveInHierarchy(e){return R0(e)}static markAsInstancedRendered(e,t){E0(e,t)}static isUsingInstancing(e){return bu(e)}static foreachComponent(e,t,i=!0){return fr(e,t,i)}static instantiateSynced(e,t){return e?sg(e,t):null}static instantiate(e,t=null){return"isAssetReference"in e,uo(e,t)}static destroySynced(e,t,i=!0){if(!e)return;const n=e;t=t??U.Current,zc(n,t.connection,i)}static destroy(e,t=!0){return bi(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),nc(e,!0),pd(e),i?S.foreachComponent(e,n=>{ig(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),nc(e,!1),pd(e),S.foreachComponent(e,t=>{f1(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 cn(e,t,i,{callAwake:n})}static addComponent(e,t,i,n){return cn(e,t,i,n)}static moveComponent(e,t){return cn(e,t)}static removeComponent(e){return cg(e.gameObject,e),e}static getOrAddComponent(e,t){return Vc(e,t)}static getComponent(e,t){return e===null?null:xr(e,t)}static getComponents(e,t,i=null){return e===null?i??[]:$c(e,t,i)}static findByGuid(e,t){return hg(e,t)}static findObjectOfType(e,t,i=!0){return Wa(e,t??U.Current,i)}static findObjectsOfType(e,t){const i=[];return k0(e,i,t),i}static getComponentInChildren(e,t,i=!1){return Wc(e,t,i)}static getComponentsInChildren(e,t,i=null){return $a(e,t,i??void 0)}static getComponentInParent(e,t){return vc(e,t)}static getComponentsInParent(e,t,i=null){return yu(e,t,i)}static getAllComponents(e){const t=e.userData?.components;return t?[...t]:[]}static*iterateComponents(e){const t=e?.userData?.components;if(t&&Array.isArray(t))for(let i=0;i<t.length;i++)yield t[i]}}class R{get isComponent(){return!0}get[Dv](){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[jn];return e===void 0?!0:e}set __isActiveInHierarchy(e){this.gameObject&&(this.gameObject[jn]=e)}gameObject;guid="invalid";sourceId;awake(){}onEnable(){}onDisable(){}onDestroy(){this.__destroyed=!0}startCoroutine(e,t=ge.Update){return this.context.registerCoroutineUpdate(this,e,t)}stopCoroutine(e,t=ge.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),sm()&&ew(this)}__internalNewInstanceCreated(e){return this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1,this._internalInit(e),this}_internalInit(e){if(typeof e=="object")for(const t of Object.keys(e)){const i=e[t];typeof i!="function"&&(this[t]=i)}}__internalAwake(){this.__didAwake||(this.__didAwake=!0,this.awake())}__internalStart(){this.__didStart||(this.__didStart=!0,this.start&&this.start())}__internalEnable(e){return this.__destroyed?(A()&&console.warn("[Needle Engine Dev] Trying to enable destroyed component"),!1):this.__didAwake?this.__didEnable?(e!==!0&&(this.__isEnabled=!0),!1):(this.__didEnable=!0,this.__isEnabled=!0,this.onEnable(),!0):!1}__internalDisable(e){if(this.__didAwake){if(!this.__didEnable){e!==!0&&(this.__isEnabled=!1);return}this.__didEnable=!1,this.__isEnabled=!1,this.onDisable()}}__internalDestroy(){this.__destroyed||(this.__destroyed=!0,this.__didAwake&&(this.onDestroy?.call(this),this.dispatchEvent(new CustomEvent("destroyed",{detail:this}))),O0(this),sm()&&tw(this))}get enabled(){return typeof this.__isEnabled=="boolean"?this.__isEnabled:!0}set enabled(e){if(this.__destroyed){A()&&console.warn(`[Needle Engine Dev] Trying to ${e?"enable":"disable"} destroyed component`);return}if(typeof e=="number"&&(e>=.5?e=!0:e=!1),!this.__didAwake){this.__isEnabled=e;return}e?this.__internalEnable():this.__internalDisable()}get worldPosition(){return Y(this.gameObject)}set worldPosition(e){at(this.gameObject,e)}setWorldPosition(e,t,i){dr(this.gameObject,e,t,i)}get worldQuaternion(){return pe(this.gameObject)}set worldQuaternion(e){dn(this.gameObject,e)}setWorldQuaternion(e,t,i,n){jm(this.gameObject,e,t,i,n)}get worldEuler(){return Bm(this.gameObject)}set worldEuler(e){Fm(this.gameObject,e)}get worldRotation(){return this.gameObject.worldRotation}set worldRotation(e){this.setWorldRotation(e.x,e.y,e.z,!0)}setWorldRotation(e,t,i,n=!0){Fc(this.gameObject,e,t,i,n)}static _forward=new c.Vector3;get forward(){return R._forward.set(0,0,-1).applyQuaternion(this.worldQuaternion)}static _right=new c.Vector3;get right(){return R._right.set(1,0,0).applyQuaternion(this.worldQuaternion)}static _up=new c.Vector3;get up(){return R._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 TP=Object.freeze(Object.defineProperty({__proto__:null,Behaviour:R,Component:R,GameObject:S},Symbol.toStringTag,{value:"Module"}));var AP=Object.defineProperty,iw=(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 qc extends R{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new c.Vector3}update(){if(!this.from||!this.to)return;const e=Y(this.from).clone(),t=Y(this.to).clone(),i=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),at(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(Y(this.to).clone()),this.gameObject.scale.set(this.width,this.width,i)}}iw([f(S)],qc.prototype,"from");iw([f(S)],qc.prototype,"to");var DP=Object.defineProperty,LP=Object.getOwnPropertyDescriptor,Sr=(s,e,t,i)=>{for(var n=i>1?void 0:i?LP(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&&DP(e,t,n),n};const zs=x("debuganimation");let nw=class{x;y};class Tt extends R{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){zs&&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,zs&&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){zs&&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){zs&&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(zs&&console.log("PLAY",e),this.ensureMixer(),!this.mixer){zs&&console.warn("Missing mixer",this);return}e===void 0&&(e=0);let i=e;if(typeof e=="number"){if(e>=this.animations.length){zs&&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(()=>Hn.testIfRootCanAnimate(e)),zs&&console.log("PLAY",e.getClip().name,e);const o=new IP(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)}}Sr([f()],Tt.prototype,"playAutomatically",2);Sr([f()],Tt.prototype,"randomStartTime",2);Sr([f(nw)],Tt.prototype,"minMaxSpeed",2);Sr([f(nw)],Tt.prototype,"minMaxOffsetNormalized",2);Sr([f()],Tt.prototype,"loop",2);Sr([f()],Tt.prototype,"clampWhenFinished",2);Sr([f(c.AnimationClip)],Tt.prototype,"clips",1);class IP{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 vd=Symbol("objectIsAnimatedData");function Z_(s,e,t){if(!s)return;if(s[vd]===void 0){if(!t)return;s[vd]=new Set}const i=s[vd];t?i.add(e):i.has(e)&&i.delete(e)}function jP(s){if(!s)return!1;const e=s[vd];return e!==void 0&&e.size>0}class BP{_context;get context(){return this._context??U.Current}get isStateMachineBehaviour(){return!0}}class Nl{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 sw(s,e){return{name:"Empty",isLooping:!1,guid:e?.generateUUID()??c.MathUtils.generateUUID(),index:-1,clip:new c.AnimationClip(s,0,[])}}var Zs=(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))(Zs||{}),yg=(s=>(s[s.Float=1]="Float",s[s.Int=3]="Int",s[s.Bool=4]="Bool",s[s.Trigger=9]="Trigger",s))(yg||{});const Ke=x("debuganimatorcontroller"),Vh=x("debugrootmotion");class Vi{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 wt(Date.now()).generateUUID(),parameters:[],layers:[{name:"Base Layer",stateMachine:{defaultState:0,states:i}}]};return new Vi(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){Ke&&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){Ke&&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 Nl(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;Ke&&console.warn("AnimatorController clone()",this.model);const e=Ic(this.model,(i,n,o)=>o==null?!0:!(o.type==="Object3D"||o.isObject3D===!0||bv(o)||o.tracks!==void 0||o instanceof Vi));return console.assert(e!==this.model),new Vi(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,Ke&&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()&&(Ke&&console.debug("REMOVE",i.name,o.getEffectiveWeight(),o.isRunning(),o.isScheduled()),this._activeStates.splice(t,1),t--)}}}setStartTransition(){this.model.layers.length>1&&(Ke||A())&&console.warn("Multiple layers are not supported yet "+this.animator?.name);for(const e of this.model.layers){const t=e.stateMachine;t.defaultState===void 0&&(Ke&&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===yg.Trigger&&p.value&&(p.value=!1)}if(i.clampWhenFinished=!0,Ke){const u=this.getState(o.destinationState,0);console.log(`Transition to ${o.destinationState} / ${u?.name}`,o,`
|
|
891
|
-
Timescale: `+i.timeScale,`
|
|
892
|
-
Normalized time: `+l.toFixed(3),`
|
|
893
|
-
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 Nl(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&&(Ke&&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 Nl(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):Ke&&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(()=>Hn.testIfRootCanAnimate(l)),this.rootMotionHandler&&this.rootMotionHandler.onStart(l),this._activeStates.includes(e)||this._activeStates.push(e),this._activeState.behaviours){const u=new Nl(e,i,d,this._speed);for(const p of this._activeState.behaviours)p.instance?.onStateEnter?.call(p.instance,this.animator,u,n)}}else Ke&&(e.__warned_no_motion||(e.__warned_no_motion=!0,console.warn("No action",e.motion,this)));Ke&&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 FP(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 Zs.If:return t.value===!0;case Zs.IfNot:return t.value===!1;case Zs.Greater:return t.value>e.threshold;case Zs.Less:return t.value<e.threshold;case Zs.Equals:return t.value===e.threshold;case Zs.NotEqual:return t.value!==e.threshold}return!1}createActions(e){Ke&&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||(Ke&&console.warn("No motion",o),o.motion=sw(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:(Ke||A())&&console.warn('Could not find clip for animator "'+this.animator?.gameObject?.name+'"',o.motion.clips.map(a=>a.node.name))}if(!o.motion.clip){Ke&&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(Ke||A())&&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,ja(l,r.properties),r.instance=l),Ke&&console.log("Created animator controller behaviour",o.name,r.typeName,r.properties,l)}else(Ke||A())&&console.warn("Could not find AnimatorBehaviour type: "+r.typeName)}}}}*enumerateActions(){if(this.model.layers)for(const e of this.model.layers){const t=e.stateMachine;for(let i=0;i<t.states.length;i++){const n=t.states[i];n?.motion&&(n.motion.action&&(yield n.motion.action),n.motion.action_loopback&&(yield n.motion.action_loopback))}}}rootMotionHandler}class J_{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 Je{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,Je.firstKeyframeRotation[this.cacheId]||(Je.firstKeyframeRotation[this.cacheId]=new c.Quaternion),o){const r=o.values;Je.firstKeyframeRotation[this.cacheId].set(r[0],r[1],r[2],r[3])}Je.spaceRotation[this.cacheId]||(Je.spaceRotation[this.cacheId]=new c.Quaternion),Je.effectiveSpaceRotation[this.cacheId]||(Je.effectiveSpaceRotation[this.cacheId]=new c.Quaternion),Je.clipOffsetRotation[this.cacheId]=new c.Quaternion,o&&Je.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;Je.lastObjRotation[this.cacheId]||(Je.lastObjRotation[this.cacheId]=this.root.quaternion.clone());const t=Je.lastObjRotation[this.cacheId];if(Je.spaceRotation[this.cacheId].copy(t),Vh){const i=new c.Euler().setFromQuaternion(t);console.log("START",this.clip.name,I.toDegrees(i.y),this.root.position.z)}}getClipRotationOffset(){return Je.clipOffsetRotation[this.cacheId]}_prevTime=0;handlePosition(e,t){if(t){const i=this.root;Vh&&i.add(new c.AxesHelper),Je.lastObjPosition[this.cacheId]||(Je.lastObjPosition[this.cacheId]=this.root.position.clone());const n=new c.Vector3,o=new c.Vector3;this.positionWrapper=new J_(t,(r,a)=>{const l=this.action.getEffectiveWeight();return Vh&&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(Vh){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 J_(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(Je.identityQuaternion,1-e),!0)}}class FP{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 Je(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 UP extends Hi{onSerialize(e,t){}onDeserialize(e,t){if(t.type===Vi&&e?.__type==="AnimatorController")return new Vi(e)}}new UP(Vi);var zP=Object.defineProperty,NP=Object.getOwnPropertyDescriptor,Pu=(s,e,t,i)=>{for(var n=i>1?void 0:i?NP(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&&zP(e,t,n),n};const Ti=x("debuganimator");class lt extends R{get isAnimationComponent(){return!0}applyRootMotion=!1;hasRootMotion=!1;keepAnimatorControllerStateOnDisable=!1;set runtimeAnimatorController(e){this._animatorController&&this._animatorController.model===e||(e?e instanceof Vi?(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 Vi(e.model)),this._animatorController=e,this._animatorController.bind(this)):(Ti&&console.log("Assign animator controller",e,this),this._animatorController=new Vi(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){Ti&&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 Ti&&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),Ti&&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 Ti&&console.log("getFloat",e,t),t}SetInteger(e,t){this.setInteger(e,t)}setInteger(e,t){this.runtimeAnimatorController?.getInteger(e)!==t&&(this._parametersAreDirty=!0),Ti&&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 Ti&&console.log("getInteger",e,t),t}SetTrigger(e){this.setTrigger(e)}setTrigger(e){this._parametersAreDirty=!0,Ti&&console.log("setTrigger",e),this.runtimeAnimatorController?.setTrigger(e)}ResetTrigger(e){this.resetTrigger(e)}resetTrigger(e){this._parametersAreDirty=!0,Ti&&console.log("resetTrigger",e),this.runtimeAnimatorController?.resetTrigger(e)}GetTrigger(e){this.getTrigger(e)}getTrigger(e){const t=this.runtimeAnimatorController?.getTrigger(e);return Ti&&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&&(Ti&&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(){Ti&&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,!jP(this.gameObject)&&this._animatorController&&this._animatorController.update(1)}}Pu([f()],lt.prototype,"applyRootMotion",2);Pu([f()],lt.prototype,"hasRootMotion",2);Pu([f()],lt.prototype,"keepAnimatorControllerStateOnDisable",2);Pu([f()],lt.prototype,"runtimeAnimatorController",1);const eb=Symbol("previous-visibility");class Bn 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(){Bn._userSet.clear();const e=eg(this.texture,!0,null,Bn._userSet);for(const t of e)t instanceof c.Mesh&&(t[eb]=t.visible,t.visible=!1)}onAfterRender(){for(const e of Bn._userSet)e instanceof c.Mesh&&(e.visible=e[eb]);Bn._userSet.clear()}}var VP=Object.defineProperty,$P=Object.getOwnPropertyDescriptor,Xc=(s,e,t,i)=>{for(var n=i>1?void 0:i?$P(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&&VP(e,t,n),n};const $h=x("debuggroundprojection");class Xn extends R{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 ms(this.context.scene,"background"),this._watcher.subscribeWrite(e=>{$h&&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 jc(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){$h&&console.log("Create/Update Ground Projection",e.name),this._projection?.removeFromParent();try{this._projection=new X.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",Um(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=ri(this.context.scene.children,[this._projection]),r=o.min.y;if(r<1/0){const a=F();a.x=o.min.x+(o.max.x-o.min.x)*.5;const l=je(this.gameObject).x;a.y=r+this._height*l-i,a.z=o.min.z+(o.max.z-o.min.z)*.5,at(this._projection,a)}$h&&B.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,$h&&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:WP,fragmentShader:GP}),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=ho.copyTexture(e,this._blurrynessShader),this._projection.material.depthTest=!0,this._projection.material.depthWrite=!1}}Xc([f()],Xn.prototype,"applyOnAwake",2);Xc([f()],Xn.prototype,"autoFit",2);Xc([f()],Xn.prototype,"radius",1);Xc([f()],Xn.prototype,"height",1);Xc([f()],Xn.prototype,"arBlending",1);const WP=`
|
|
894
|
-
varying vec2 vUv;
|
|
895
|
-
|
|
896
|
-
void main() {
|
|
897
|
-
vUv = uv;
|
|
898
|
-
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
|
|
899
|
-
}
|
|
900
|
-
`,GP=`
|
|
901
|
-
uniform sampler2D map;
|
|
902
|
-
uniform float blurriness;
|
|
903
|
-
uniform float alphaFactor;
|
|
904
|
-
uniform float blending;
|
|
905
|
-
varying vec2 vUv;
|
|
906
|
-
|
|
907
|
-
const float PI = 3.14159265359;
|
|
908
|
-
|
|
909
|
-
// Gaussian function
|
|
910
|
-
float gaussian(float x, float sigma) {
|
|
911
|
-
return exp(-(x * x) / (2.0 * sigma * sigma)) / (sqrt(2.0 * PI) * sigma);
|
|
912
|
-
}
|
|
913
|
-
|
|
914
|
-
// Custom smoothstep function for desired falloff
|
|
915
|
-
float customSmoothstep(float edge0, float edge1, float x) {
|
|
916
|
-
float t = clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0);
|
|
917
|
-
return t * t * (3.0 - 2.0 * t);
|
|
918
|
-
}
|
|
919
|
-
|
|
920
|
-
void main() {
|
|
921
|
-
vec2 center = vec2(0.0, 0.0);
|
|
922
|
-
vec2 pos = vUv;
|
|
923
|
-
pos.x = 0.0; // Only consider vertical distance
|
|
924
|
-
float distance = length(pos - center);
|
|
925
|
-
|
|
926
|
-
// Calculate blur amount based on custom falloff
|
|
927
|
-
float blurAmount = customSmoothstep(0.5, 1.0, distance * 2.0);
|
|
928
|
-
blurAmount = clamp(blurAmount, 0.0, 1.0); // Ensure blur amount is within valid range
|
|
929
|
-
|
|
930
|
-
// Gaussian blur
|
|
931
|
-
vec2 pixelSize = 1.0 / vec2(textureSize(map, 0));
|
|
932
|
-
vec4 color = vec4(0.0);
|
|
933
|
-
float totalWeight = 0.0;
|
|
934
|
-
int blurSize = int(60.0 * min(1.0, blurriness) * blurAmount); // Adjust blur size based on distance and blurriness
|
|
935
|
-
float lodLevel = log2(float(blurSize)) * 0.5; // Compute LOD level
|
|
936
|
-
|
|
937
|
-
for (int x = -blurSize; x <= blurSize; x++) {
|
|
938
|
-
for (int y = -blurSize; y <= blurSize; y++) {
|
|
939
|
-
vec2 offset = vec2(float(x), float(y)) * pixelSize * blurAmount;
|
|
940
|
-
float weight = gaussian(length(vec2(float(x), float(y))), 1000.0 * blurAmount); // Use a fixed sigma value
|
|
941
|
-
color += textureLod(map, vUv + offset, lodLevel) * weight;
|
|
942
|
-
totalWeight += weight;
|
|
943
|
-
}
|
|
944
|
-
}
|
|
945
|
-
|
|
946
|
-
color = totalWeight > 0.0 ? color / totalWeight : texture2D(map, vUv);
|
|
947
|
-
|
|
948
|
-
gl_FragColor = color;
|
|
949
|
-
|
|
950
|
-
float brightness = dot(gl_FragColor.rgb, vec3(0.299, 0.587, 0.114));
|
|
951
|
-
float stepFactor = blending - brightness * .1;
|
|
952
|
-
gl_FragColor.a = pow(1.0 - blending * customSmoothstep(0.35 * stepFactor, 0.45 * stepFactor, distance), 5.);
|
|
953
|
-
gl_FragColor.a *= alphaFactor;
|
|
954
|
-
// gl_FragColor.rgb = vec3(1.0);
|
|
955
|
-
|
|
956
|
-
// #include <tonemapping_fragment>
|
|
957
|
-
// #include <colorspace_fragment>
|
|
958
|
-
|
|
959
|
-
// Uncomment to visualize blur amount
|
|
960
|
-
// gl_FragColor = vec4(blurAmount, 0.0, 0.0, 1.0);
|
|
961
|
-
}
|
|
962
|
-
`;function ow(s){if(q.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=ri(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 y=r,_=2*Math.atan(Math.tan(y*Math.PI/360/2)*h)/Math.PI*360,g=a.y/(2*Math.atan(Math.PI*y/360)),w=a.x/(2*Math.atan(Math.PI*_/360)),b=o*Math.max(g,w)+a.z/2;s.maxZoom=b*10,s.minZoom=b*.01,s.debug===!0&&console.log("Fit camera to objects",{fitHeightDistance:g,fitWidthDistance:w,distance:b,verticalFov:y,horizontalFov:_});const v=.05,E=l.clone();if(E.y-=a.y*v,s.targetOffset&&(s.targetOffset.x!==void 0&&(E.x+=s.targetOffset.x),s.targetOffset.y!==void 0&&(E.y+=s.targetOffset.y),s.targetOffset.z!==void 0&&(E.z+=s.targetOffset.z)),s.relativeTargetOffset&&(s.relativeTargetOffset.x!==void 0&&(E.x+=s.relativeTargetOffset.x*a.x),s.relativeTargetOffset.y!==void 0&&(E.y+=s.relativeTargetOffset.y*a.y),s.relativeTargetOffset.z!==void 0&&(E.z+=s.relativeTargetOffset.z*a.z)),n==null||n=="auto"){const D=Wa(Xn),L=D?D.radius:0,j=Math.max(m.x,m.y,m.z,L);t instanceof c.PerspectiveCamera&&(t.near=b/100,t.far=j+b*10,t.updateProjectionMatrix()),D&&(s.maxZoom=Math.max(Math.min(s.maxZoom,L*.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 O=l.clone();s.fitDirection?O.sub(new c.Vector3().copy(s.fitDirection).multiplyScalar(1e6)):O.sub(t.worldPosition),i==="y"&&(O.y=0),O.normalize(),O.multiplyScalar(b),i==="y"&&(O.y+=-v*4*b);let M=l.clone().sub(O);return s.cameraOffset&&(s.cameraOffset.x!==void 0&&(M.x+=s.cameraOffset.x),s.cameraOffset.y!==void 0&&(M.y+=s.cameraOffset.y),s.cameraOffset.z!==void 0&&(M.z+=s.cameraOffset.z)),s.relativeCameraOffset&&(s.relativeCameraOffset.x!==void 0&&(M.x+=s.relativeCameraOffset.x*a.x),s.relativeCameraOffset.y!==void 0&&(M.y+=s.relativeCameraOffset.y*a.y),s.relativeCameraOffset.z!==void 0&&(M.z+=s.relativeCameraOffset.z*a.z)),t.parent&&(M=t.parent.worldToLocal(M)),s.debug&&(B.DrawWireBox3(u,16777011,10),B.DrawWireBox3(p,65280,10)),s.autoApply&&(t.position.copy(M),t.lookAt(E),r>0&&t instanceof c.PerspectiveCamera&&(t.fov=r,t.updateProjectionMatrix())),{camera:t,position:M,lookAt:E,fov:s.fov}}let ar=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 rw{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new ar).__init(this.bb_pos,this.bb)}rotation(e){return(e||new ar).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new ar).__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 cs{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedTransformModel(e,t){return(t||new cs).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+ae.SIZE_PREFIX_LENGTH),(t||new cs).__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 rw).__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)}}function Wh(s){const e=[],t={MODULE:void 0,MAYBEMODULE:null,ready(){return t.MODULE?Promise.resolve(t.MODULE):new Promise(i=>{e.push(i)})},async load(){if(t.MODULE)return t.MODULE;const i=await s();t.MODULE=i,t.MAYBEMODULE=i;for(const n of e)n(i);return e.length=0,i}};return t}const T={MaterialX:Wh(()=>Promise.resolve().then(()=>require("./materialx-D0XUnhBY.umd.cjs"))),RAPIER_PHYSICS:Wh(()=>Promise.resolve().then(()=>require("./rapier-DQltNJbN.umd.cjs"))),POSTPROCESSING:Wh(()=>Promise.resolve().then(()=>require("./postprocessing-B2wb6pzI.umd.cjs")).then(s=>s.index)),POSTPROCESSING_AO:Wh(()=>Promise.resolve().then(()=>require("./postprocessing-B2wb6pzI.umd.cjs")).then(s=>s.N8AO))};var st=(s=>(s[s.Average=0]="Average",s[s.Multiply=1]="Multiply",s[s.Minimum=2]="Minimum",s[s.Maximum=3]="Maximum",s))(st||{}),Ou=(s=>(s[s.Discrete=0]="Discrete",s[s.Continuous=1]="Continuous",s))(Ou||{}),Ve=(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))(Ve||{}),pa=(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))(pa||{});const St=function(s,e){return function(t,i,n){HP(t,i,n,s,e)}};function HP(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),Se("Invalid usage of validate decorator. Only fields can be validated. Property: "+e,{type:gi.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){A()&&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];cu(h,()=>{this.onValidate(o)})}Object.defineProperty(this,o,{set:function(h){if(this[Xp]===!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 qP=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 XP=Object.defineProperty,QP=Object.getOwnPropertyDescriptor,Si=(s,e,t,i)=>{for(var n=i>1?void 0:i?QP(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&&XP(e,t,n),n};class YP{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 ms(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 ms(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 ai=class wd extends R{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=Ve.None;isKinematic=!1;drag=0;angularDrag=1;detectCollisions=!0;sleepThreshold=.01;collisionDetectionMode=Ou.Discrete;get lockPositionX(){return(this.constraints&Ve.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&Ve.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&Ve.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&Ve.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&Ve.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&Ve.FreezeRotationZ)!==0}set lockPositionX(e){e?this.constraints|=Ve.FreezePositionX:this.constraints&=~Ve.FreezePositionX}set lockPositionY(e){e?this.constraints|=Ve.FreezePositionY:this.constraints&=~Ve.FreezePositionY}set lockPositionZ(e){e?this.constraints|=Ve.FreezePositionZ:this.constraints&=~Ve.FreezePositionZ}set lockRotationX(e){e?this.constraints|=Ve.FreezeRotationX:this.constraints&=~Ve.FreezeRotationX}set lockRotationY(e){e?this.constraints|=Ve.FreezeRotationY:this.constraints&=~Ve.FreezeRotationY}set lockRotationZ(e){e?this.constraints|=Ve.FreezeRotationZ:this.constraints&=~Ve.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 YP(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),ge.LateUpdate),A()&&(globalThis.NEEDLE_USE_RAPIER?T.RAPIER_PHYSICS.ready().then(async()=>{await jc(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;wd.tempPosition.setFromMatrixPosition(e);const t=wd.tempPosition.sub(this._lastPosition);this._lastPosition.copy(wd.tempPosition),this._smoothedVelocity.lerp(t,this.context.time.deltaTime/.1)}};Si([St()],ai.prototype,"autoMass",2);Si([f()],ai.prototype,"mass",1);Si([St(),f()],ai.prototype,"useGravity",2);Si([f(c.Vector3)],ai.prototype,"centerOfMass",2);Si([St(),f()],ai.prototype,"constraints",2);Si([St(),f()],ai.prototype,"isKinematic",2);Si([St(),f()],ai.prototype,"drag",2);Si([St(),f()],ai.prototype,"angularDrag",2);Si([St(),f()],ai.prototype,"detectCollisions",2);Si([St(),f()],ai.prototype,"sleepThreshold",2);Si([St(),f()],ai.prototype,"collisionDetectionMode",2);Si([St()],ai.prototype,"_gravityScale",2);Si([St()],ai.prototype,"dominanceGroup",2);let $e=ai;new c.Vector3;new c.Vector3;const Xs=x("debugsync"),xc="STRS";Xm(xc,cs.getRootAsSyncedTransformModel);const Sn=new ae.Builder;function aw(s,e,t=!0){Sn.clear();const i=Sn.createString(s);cs.startSyncedTransformModel(Sn),cs.addGuid(Sn,i),cs.addFast(Sn,t);const n=e.worldPosition,o=e.worldEuler,r=e.gameObject.scale;cs.addTransform(Sn,rw.createTransform(Sn,n.x,n.y,n.z,o.x,o.y,o.z,r.x,r.y,r.z));const a=cs.endSyncedTransformModel(Sn);return Sn.finish(a,xc),Sn.asUint8Array()}let om=0,rc=0;Y0(s=>{const t=s.connection.currentServerUrl?.includes("glitch")?10:40;rc=Math.floor(om/t),om=0,Xs&&rc>0&&console.log("Sync Transform Fast Interval",rc)});class pn extends R{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(){Xs&&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(){Xs&&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,$e),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new Ym(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(K.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(xc,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&ng(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(K.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(xc,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){Xs&&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){Ni.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)&&Fm(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){Xs&&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:(Xs&&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),Ni.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&&Ni.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&&(Xs&&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(om++,o&&rc>0&&this.context.time.frameCount%rc!==0)return;Xs&&console.debug("[SyncedTransform] Send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this._needsUpdate=!1;const r=aw(this.guid,this,!!o);this.context.connection.sendBinary(r)}}}class Qc{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 Qc(this.input,this.event);return Object.assign(e,this),e}Use(){this.use()}StopPropagation(){this.event.stopImmediatePropagation()}}function Yd(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 es=new Array;class hs{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?(es.length=0,e!==void 0&&e.length>0&&es.push(...e),es.push(...this.arguments),this.target(...this.arguments),es.length=0):this.target(...e);else if(this.methodName!=null){const t=this.target[this.methodName];typeof t=="function"?this.arguments?(es.length=0,e!==void 0&&e.length>0&&es.push(...e),es.push(...this.arguments),t.call(this.target,...es),es.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 KP=s=>/^[A-Z]*$/.test(s);class Mu extends Event{args}class ne{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 hs(l.clone,o.methodName,h,o.enabled))}else A()&&console.warn("Could not find target for event listener")}}}return new ne(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&&KP(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 ne(e)}constructor(e){if(this.methods=[],Array.isArray(e))for(const t of e)t instanceof hs?this.methods.push(t):typeof t=="function"&&this.methods.push(new hs(t));else typeof e=="function"&&this.methods.push(new hs(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 Mu(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 hs(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 ZP extends Hi{constructor(){super([c.Color,te],"ColorSerializer")}onDeserialize(e){if(e!=null)return e.a!==void 0?new te(e.r,e.g,e.b,e.a):e.alpha!==void 0?new te(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 JP=new ZP;class eO extends Hi{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 tO=new eO;class iO extends Hi{constructor(){super(c.Object3D,"ObjectSerializer")}onSerialize(e,t){if(t.objectToNode!==void 0&&e.uuid){const i=t.objectToNode[e.uuid];return rt&&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(Z))return;A()&&fe("Detected wrong usage of @serializable with Object3D or GameObject. Instead you should use AssetReference here! Please see the console for details.");const i=t.target?.constructor?.name;console.warn(`Wrong usage of @serializable detected in your script "${i}"
|
|
963
|
-
|
|
964
|
-
It looks like you used @serializable(Object3D) or @serializable(GameObject) for a prefab or scene reference which is exported to a separate glTF file.
|
|
965
|
-
|
|
966
|
-
To fix this please change your code to:
|
|
967
|
-
|
|
968
|
-
@serializable(AssetReference)
|
|
969
|
-
${t.path}! : AssetReference;
|
|
970
|
-
\0`)}return}if(e){if(e.node!==void 0&&t.nodeToObject){const i=t.nodeToObject[e.node];return rt&&console.log("Deserialized object reference?",e,i,t?.nodeToObject),i||console.warn("Did not find node: "+e.node,t.nodeToObject,t.object),i}else if(e.guid){if(!t.context){console.error("Missing context");return}let i;const n=t.gltf?.scene;return n&&(i=S.findByGuid(e.guid,n)),i||(i=S.findByGuid(e.guid,t.context.scene)),i?(i&&i.isComponent===!0&&(rt&&console.warn("Deserialized object reference is a component"),i=i.gameObject),rt&&console.log("Deserialized object reference?",e,i,t?.nodeToObject)):((A()||rt)&&console.warn("Could not resolve object reference",t.path,e,t.target,t.context.scene),e.could_not_resolve=!0),i}}}}const lw=new iO;class nO extends Hi{constructor(){super([R,R],"ComponentSerializer")}onSerialize(e,t){if(e?.guid)return{guid:e.guid}}onDeserialize(e,t){if(e?.guid){if(e.___persistentAsset){rt&&console.log("Skipping component deserialization because it's a persistent asset",e);return}const i=t.path;rt&&console.log(e.guid,t.root,t.object,t.target);let n=this.findObjectForGuid(e.guid,t.root);if(n||t.context&&(n=this.findObjectForGuid(e.guid,t.context?.scene),n))return n;(A()||rt)&&console.warn('Could not resolve component reference: "'+i+'" using guid '+e.guid,t.target),e.could_not_resolve=!0;return}}findObjectForGuid(e,t){if(t.guid===e)return t;const i=S.foreachComponent(t,n=>{if(n.guid===e)return n},!1);if(i!==void 0)return i;for(let n=0;n<t.children.length;n++){const o=t.children[n],r=this.findObjectForGuid(e,o);if(r)return r}}}const xd=new nO;class sO extends Hi{constructor(){super([ne])}onSerialize(e,t){console.log("TODO: SERIALIZE EVENT")}onDeserialize(e,t){if(typeof e=="function")return new ne([new hs(e,null,[],!0)]);if(e&&e.type==="EventList"){rt&&console.log("DESERIALIZE EVENT",e);const i=new Array;if(e.calls&&Array.isArray(e.calls))for(const r of e.calls){let a=function(d){if(typeof d=="object"){let u=lw.onDeserialize(d,t);if(u||(u=xd.onDeserialize(d,t)),u)return u}return d};rt&&console.log(r);let l=xd.findObjectForGuid(r.target,t.root);!l&&t.context?.scene&&(l=xd.findObjectForGuid(r.target,t.context?.scene));const h=r.method?.length>0;if(l&&h){const d=()=>{const p=r.method[0].toUpperCase()+r.method.slice(1);if(typeof l[p]=="function"){console.warn(`EventList method:
|
|
971
|
-
Could not find method ${r.method} on object ${l.name}. Please rename ${r.method} to ${p}?
|
|
972
|
-
`,l[p],`
|
|
973
|
-
in script: `,l),fe("EventList methods must start with lowercase letter, see console for details");return}else console.warn(`EventList method:
|
|
974
|
-
Could not find method ${r.method} on object ${l.name}`,l,typeof l[r.method])};if(typeof l[r.method]!="function"){let p=!1,m=l;for(;m;){const y=Object.getOwnPropertyDescriptor(m,r.method);if(y&&(y.writable===!0||y.set)){p=!0;break}m=Object.getPrototypeOf(m)}!p&&(A()||rt)&&d()}}if(l){let d=r.argument;if(d!==void 0?d=a(d):r.arguments!==void 0&&(d=r.arguments.map(a)),l[r.method]===void 0)console.warn(`EventList method not found: "${r.method}" on ${l?.name}`);else{d!==void 0&&!Array.isArray(d)&&(d=[d]);const p=new hs(l,r.method,d,r.enabled);i.push(p)}}else A()&&console.warn(`[Dev] EventList: Could not find event listener in scene (${t.object?.name})`,r)}const n=new ne(i);rt&&console.log(n);const o=t.target;return o!==void 0&&t.path!==void 0&&n.setEventTarget(t.path,o),n}}}const oO=new sO,Kd=new WeakMap,rO=c.Texture.prototype.clone;c.Texture.prototype.clone=function(){const s=rO.call(this);return Kd.has(s)||Kd.set(s,this),s};class cw extends Hi{constructor(){super([Bn,c.WebGLRenderTarget])}onSerialize(e,t){}onDeserialize(e,t){if(e instanceof c.Texture&&t.type===Bn){let i=e;Kd.has(i)&&(i=Kd.get(i)),i.isRenderTargetTexture=!0,i.flipY=!0,i.offset.y=1,i.repeat.y=-1,i.needsUpdate=!0,i.mipmaps=[],i instanceof c.CompressedTexture&&(i.isCompressedTexture=!1,i.format=c.RGBAFormat);const n=new Bn(i.image.width,i.image.height,{colorSpace:c.LinearSRGBColorSpace});return n.texture=i,n}}}new cw;class hw extends Hi{constructor(){super([URL])}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"&&e.length>0)return ws(t.gltfId,e)}}new hw;var aO=Object.defineProperty,lO=(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&&aO(e,t,n),n};class Sc extends R{awake(){Gt.createIfNoneExists(this.context)}onEnable(){Gt.get(this.context)?.register(this)}onDisable(){Gt.get(this.context)?.unregister(this)}}class $i extends Sc{targets=null;raycastHits=[];ignoreSkinnedMeshes=!1;start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??=new vo,e.targets=this.targets,e.results=this.raycastHits,e.useAcceleratedRaycast=!0;const t=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=n=>n instanceof c.SkinnedMesh?"continue in children":t?t(n):!0);const i=this.context.physics.raycast(e);return e.testObject=t,i}}lO([f()],$i.prototype,"ignoreSkinnedMeshes");class ku extends $i{constructor(){super(),this.ignoreSkinnedMeshes=!0}}class pr extends Sc{static allow=!0;performRaycast(e){if(!q.active||!pr.allow||!e?.ray)return null;const t=e.ray.origin;return this.context.physics.sphereOverlap(t,.015,!1,!0)}}class _g{static getObject(e){const t=e[pi];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(t&&(t.canvasGroup=void 0,t.graphic=void 0),e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;const i=this.tryFindCanvasGroup(e);if(i?.isCanvasGroup===!0&&(t&&(t.canvasGroup=i),i.blocksRaycasts===!1||i.interactable===!1))return!1;const n=fr(e,o=>{if(o.isGraphic===!0)return o},!1);return t&&n?.isGraphic===!0&&(t.graphic=n),!(n?.raycastTarget===!1||n?.layer===2)}static tryFindCanvasGroup(e){if(!e)return null;const t=fr(e,i=>{if(i.activeAndEnabled){const n=i;if(n.blocksRaycasts!==void 0&&n.interactable!==void 0)return n}},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}}function bg(s){const e=s[pi];return e||(s.parent?bg(s.parent):null)}function cO(s){return s.isUI===!0||typeof s[pi]=="object"}function Zd(s,e){if(!s)return;const t=s.material;if(t?.isMaterial===!0){const i=s.parent;i&&i.isText,t.side=e.doubleSided??!0?c.DoubleSide:c.FrontSide,t.shadowSide=e.doubleSided?c.DoubleSide:c.FrontSide,s.castShadow=e.castShadows?e.castShadows:!1,s.receiveShadow=e.receiveShadows?e.receiveShadows:!1}for(const i of s.children)Zd(i,e)}function sa(s,e,t){s[e]===void 0&&console.warn("Field",e,"is undefined on",s);const i=Proxy.revocable(s[e],{set(r,a,l,h){const d=r[a],u=Reflect.set(r,a,l,h);return t(l,d),u}}),n=i.revoke,o=s[e];return i.revoke=()=>{s[e]=o,n()},s[e]=i.proxy,i}const tb=Symbol("Scheduled action");function hO(s,e,t=ge.OnBeforeRender){let i=s[tb];i||(i=s[tb]={});const n=e.name;i[t]||(i[t]={});const o=i[t];if(o[n])return;function*a(){e?.call(s),o[n]=null}const l=s.startCoroutine(a(),t);o[n]=l}const Qs=x("debugeventsystem");var rm=(s=>(s.BeforeHandleInput="BeforeHandleInput",s.AfterHandleInput="AfterHandleInput",s))(rm||{});pg(s=>{Gt.createIfNoneExists(s)});class Gt extends R{static ensureUpdateMeshUI(e,t,i=!1){wl.update(e,t,i)}static markUIDirty(e){wl.markDirty()}static createIfNoneExists(e){e.scene.getComponent(Gt)||e.scene.addComponent(Gt)}static get(e){return this.createIfNoneExists(e),e.scene.getComponent(Gt)}static get instance(){return this.get(U.Current)}raycaster=[];register(e){e&&this.raycaster&&!this.raycaster.includes(e)&&this.raycaster?.push(e)}unregister(e){const t=this.raycaster?.indexOf(e);t!==void 0&&t!==-1&&this.raycaster?.splice(t,1)}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}awake(){this.gameObject!==this.context.scene&&(console.debug(`[Needle Engine] EventSystem is only allowed on the scene root. Disabling EventSystem on '${this.gameObject.name}'`),this.enabled=!1)}start(){this.context.scene.getComponent(Sc)||this.context.scene.addComponent($i)}onEnable(){this.context.input.addEventListener(Pe.PointerDown,this.onPointerEvent),this.context.input.addEventListener(Pe.PointerUp,this.onPointerEvent),this.context.input.addEventListener(Pe.PointerMove,this.onPointerEvent)}onDisable(){this.context.input.removeEventListener(Pe.PointerDown,this.onPointerEvent),this.context.input.removeEventListener(Pe.PointerUp,this.onPointerEvent),this.context.input.removeEventListener(Pe.PointerMove,this.onPointerEvent)}pressedByID=new Map;hoveredByID=new Map;onBeforeRender(){this.resetMeshUIStates()}onPointerEvent=e=>{if(e===void 0||e.propagationStopped||e.defaultPrevented||e.used)return;const t=new Qc(this.context.input,e);this._currentPointerEventName=e.type,t.inputSource=this.context.input,t.isClick=e.isClick,t.isDoubleClick=e.isDoubleClick,t.isDown=e.type==Pe.PointerDown,t.isUp=e.type==Pe.PointerUp,t.isPressed=this.context.input.getPointerPressed(e.pointerId);const i=new vo;e.hasRay?i.ray=e.ray:i.screenPoint=this.context.input.getPointerPositionRC(e.pointerId),i.allowSlowRaycastFallback=e.isClick||e.isDoubleClick;const n=this.performRaycast(i);if(Qs&&(t.isDown?console.log("DOWN",{id:t.pointerId,hits:n.length}):t.isUp&&console.log("UP",{id:t.pointerId,hits:n.length}),t.isClick&&console.log("CLICK",{id:t.pointerId,hits:n.length})),n){for(const r of n)r.event=e,e.intersections.push(r);e.origin.onPointerHits&&e.origin.onPointerHits({sender:this,event:e,hits:n})}Qs&&t.isClick&&Se("EventSystem: "+t.pointerId+" - "+this.context.time.frame+" - Up:"+t.isUp+", Down:"+t.isDown);const o={sender:this,args:t,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:o})),this.handleIntersections(n,t),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:o}))};_sortedHits=[];_testObjectsCache=new Map;_currentlyActiveRaycaster=null;_currentPointerEventName=null;shouldRaycastObject=e=>{const t=e&&"getComponent"in e?e.getComponent(Sc):null;if(t&&t!=this._currentlyActiveRaycaster)return!1;let i=null;if(cO(e)&&(i=e[pi]?.gameObject),this._testObjectsCache.has(e)||i&&this._testObjectsCache.has(i))return this._testObjectsCache.get(e)===!1?"continue in children":!0;{let o=Yd(e,this._currentPointerEventName);if(!o&&i&&(o=Yd(i,this._currentPointerEventName)),o){this._testObjectsCache.set(e,!0);for(const r of e.children)this.shouldRaycastObject_AddToYesCache(r);return!0}return this._testObjectsCache.set(e,!1),"continue in children"}};shouldRaycastObject_AddToYesCache(e){this._testObjectsCache.set(e,!0);for(const t of e.children)this.shouldRaycastObject_AddToYesCache(t)}performRaycast(e){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,e.testObject=this.shouldRaycastObject;for(const t of this.raycaster){if(!t.activeAndEnabled)continue;this._currentlyActiveRaycaster=t;const i=t.performRaycast(e);this._currentlyActiveRaycaster=null,i&&i.length>0&&this._sortedHits.push(...i)}return this._sortedHits.sort((t,i)=>t.distance-i.distance),this._sortedHits}assignHitInformation(e,t){t?(e.intersection=t,e.point=t.point,e.normal=t.normal,e.face=t.face,e.distance=t.distance,e.instanceId=t.instanceId):(e.intersection=void 0,e.point=void 0,e.normal=void 0,e.face=void 0,e.distance=void 0,e.instanceId=void 0)}handleIntersections(e,t){if(e?.length){e=this.sortCandidates(e);for(const n of e){if(t.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(t,n),this.handleEventOnObject(n.object,t))return!0}}this.assignHitInformation(t,e?.[0]),this.invokePointerCapture(t);const i=this.hoveredByID.get(t.pointerId);return i&&this.propagatePointerExit(i.obj,i.data,null),this.hoveredByID.delete(t.pointerId),t.isUp&&(this.pressedByID.get(t.pointerId)?.handlers.forEach(n=>this.invokeOnPointerUp(t,n)),this.pressedByID.delete(t.pointerId)),!1}_sortingBuffer=[];_noDepthTestingResults=[];sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){const i=e[t],n=i.object;if(n.material&&n.material.depthTest===!1){this._noDepthTestingResults.push(i);continue}this._sortingBuffer.push(i)}for(const t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}out={};handleEventOnObject(e,t){if(!this.testIsVisible(e))return t.isClick&&Qs&&console.log("not allowed",e),!1;if(t.pointerId===void 0)return Qs&&console.error("Event without pointer can't be handled",t),!1;t.object=e;const i=e.parent,n=t.isClick??!1;let o=null;if(i&&i.isUI){const d=(t.isPressed||t.isClick)??!1;if(i[pi]){const u=i[pi].gameObject;if(u){if(!_g.isInteractable(u,this.out))return!1;o=this.out.canvasGroup??null,this.handleMeshUIIntersection(e,d),e=u}}}n&&Qs&&console.log(this.context.time.frame,e);const r=this.hoveredByID.get(t.pointerId),a=r?.obj;a!==e&&a&&this.propagatePointerExit(a,r.data,e);const h=this.hoveredByID.get(t.pointerId);if(h?(h.obj=e,h.data=t):this.hoveredByID.set(t.pointerId,{obj:e,data:t}),t.isDown){const d=this.pressedByID.get(t.pointerId);d?(d.obj=e,d.data=t):this.pressedByID.set(t.pointerId,{obj:e,data:t,handlers:new Set})}return(o===null||o.interactable)&&this.handleMainInteraction(e,t,a??null),!0}propagate(e,t){for(;e;)S.foreachComponent(e,i=>{t(i)},!1),e=e.parent}handleMainInteraction(e,t,i){const n=this.pressedByID.get(t.pointerId),o=i!==e;let r=!0;switch(t.event.pointerType){case"mouse":case"touch":const a=this.context.input.getPointerPositionLastFrame(t.pointerId),l=this.context.input.getPointerPosition(t.pointerId);r=a&&!I.approximately(a,l);break}this.propagate(e,a=>{const l=a;l.interactable!==!1&&(!l.activeAndEnabled||!l.enabled||(l.onPointerEnter&&o&&this.handlePointerEnter(l,t),t.isDown&&l.onPointerDown&&(l.onPointerDown(t),n?.handlers.add(l),this.handlePointerCapture(t,l)),l.onPointerMove&&(r&&l.onPointerMove(t),this.handlePointerCapture(t,l)),t.isUp&&(l.onPointerUp&&(this.invokeOnPointerUp(t,l),n?.handlers.delete(l)),l.onPointerExit&&t.event?.pointerType===pu.Touch&&(this.handlePointerExit(l,t),this.hoveredByID.delete(t.pointerId))),t.isClick&&l.onPointerClick&&l.onPointerClick(t)))}),t.isUp&&(n?.handlers.forEach(a=>{this.invokeOnPointerUp(t,a)}),this.pressedByID.delete(t.pointerId))}propagatePointerExit(e,t,i){this.propagate(e,n=>{if(!n.gameObject||n.destroyed)return;const o=n;if(o.onPointerExit||o.onPointerEnter){if(i&&this.isChild(i,n.gameObject))return;this.handlePointerExit(o,t)}})}invokeOnPointerUp(e,t){t.onPointerUp?.call(t,e),this.releasePointerCapture(e,t)}handlePointerEnter(e,t){e.onPointerEnter&&this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!0)&&e.onPointerEnter(t),this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(e,t){e.onPointerExit&&this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!0)&&e.onPointerExit(t),this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(e,t,i,n){let o=e[i];if(n)return o&&o.includes(t)?!1:(o=o||[],o.push(t),e[i]=o,!0);{if(!o||!o.includes(t))return!1;const r=o.indexOf(t);return r!==-1&&o.splice(r,1),!0}}_capturedPointer={};handlePointerCapture(e,t){if(e.z__pointer_ctured){e.z__pointer_ctured=!1;const i=e.pointerId;if(t.onPointerMove){const n=this._capturedPointer[i]||[];n.push(t),this._capturedPointer[i]=n}else A()&&!t.z__warned_no_pointermove&&(t.z__warned_no_pointermove=!0,console.warn("PointerCapture was requested but the component doesn't implement onPointerMove. It will not receive any pointer events"))}else e.z__pointer_cture_rleased&&(e.z__pointer_cture_rleased=!1,this.releasePointerCapture(e,t))}releasePointerCapture(e,t){const i=e.pointerId;if(this._capturedPointer[i]){const n=this._capturedPointer[i].indexOf(t);n!==-1&&(this._capturedPointer[i].splice(n,1),Qs&&console.log("released pointer capture",i,t,this._capturedPointer))}}invokePointerCapture(e){if(e.event.type===Pe.PointerMove){const t=e.pointerId,i=this._capturedPointer[t];if(i){Qs&&console.log("Captured",t,i);for(let n=0;n<i.length;n++){const o=i[n];if(o.destroyed){i.splice(n,1),n--;continue}o.onPointerMove?.call(o,e)}}}}pointerEnterSymbol=Symbol("pointerEnter");pointerExitSymbol=Symbol("pointerExit");isChild(e,t){return!e||!t?!1:e===t?!0:e.parent?this.isChild(e.parent,t):!1}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}currentActiveMeshUIComponents=[];handleMeshUIIntersection(e,t){const i=wl.updateState(e,t);return i&&this.currentActiveMeshUIComponents.push(i),i!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&wl.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){const t=this.currentActiveMeshUIComponents[e];wl.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?S.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}}class wl{static lastSelected=null;static lastUpdateFrame=[];static needsUpdate=!1;static markDirty(){this.needsUpdate=!0}static update(e,t,i=!1){if(i){e.update();return}const n=t.time.frameCount;for(const o of this.lastUpdateFrame)if(o.context===t){if(n===o.frame)return;o.frame=n;let r=this.needsUpdate||n<1;o.nextUpdate<=n&&(r=!0),r&&(Qs&&console.log("Update threemeshui"),this.needsUpdate=!1,o.nextUpdate=n+60,e.update());return}this.lastUpdateFrame=[{context:t,frame:n,nextUpdate:n+60}],e.update(),this.needsUpdate=!1}static updateState(e,t){let i=null;if(e&&(i=this.findBlockOrTextInParent(e),i&&i!==this.lastSelected)){if(i.interactable===!1)return null;this.needsUpdate=!0}return i}static resetLastSelected(){const e=this.lastSelected;e&&(this.lastSelected=null,this.resetState(e))}static resetState(e){e&&(this.needsUpdate=!0)}static findBlockOrTextInParent(e){return e?e.isBlock||e.isText?e:this.findBlockOrTextInParent(e.parent):null}}var dO=Object.defineProperty,uO=Object.getOwnPropertyDescriptor,ye=(s,e,t,i)=>{for(var n=i>1?void 0:i?uO(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&&dO(e,t,n),n};const ut=x("debugorbit"),Hf=x("freecam"),fO=x("debugcamerafit"),Gh=x("smoothcam"),pO={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let qf;class Cc extends CustomEvent{constructor(e,t){super("target-reached",{detail:{controls:e,type:t}})}}class de extends R{get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){this.controls?.addEventListener("start",e)}autoTarget=!0;autoFit=!1;enableRotate=!0;autoRotate=!1;autoRotateSpeed=1;minAzimuthAngle=1/0;maxAzimuthAngle=1/0;minPolarAngle=0;maxPolarAngle=Math.PI;enableKeys=!1;enableDamping=!0;dampingFactor=.1;enableZoom=!0;minZoom=0;maxZoom=1/0;zoomSpeed=1;zoomToCursor=!1;enablePan=!0;lookAtTarget=null;lockLookAtTarget=!0;lookAtConstraint01=1;allowInterrupt=!0;middleClickToFocus=!0;doubleClickToFocus=!0;clickBackgroundToFitScene=2;get targetElement(){return this._controls?.domElement??this._targetElement}set targetElement(e){this._targetElement=e,this._controls&&this._controls.domElement!==e&&(this._controls.disconnect(),this._controls.domElement=e,this._controls.connect())}_targetElement=null;debugLog=!1;get targetLerpSpeed(){return 5}set targetLerpSpeed(e){this.targetLerpDuration=1/e}get targetLerpDuration(){return this._lookTargetLerpDuration}set targetLerpDuration(e){this._lookTargetLerpDuration=e}_lookTargetLerpDuration=1;targetBounds=null;rotateLeft(e){this._controls?._rotateLeft(e)}rotateUp(e){this._controls?._rotateUp(e)}pan(e,t){this._controls?._pan(e,t)}zoomIn(e){e>0?this._controls?._dollyIn(1-e):e<0&&this._controls?._dollyOut(1+e)}_controls=null;_cameraObject=null;_lookTargetLerpActive=!1;_lookTargetStartPosition=new c.Vector3;_lookTargetEndPosition=new c.Vector3;_lookTargetLerp01=0;_cameraLerpActive=!1;_cameraStartPosition=new c.Vector3;_cameraEndPosition=new c.Vector3;_cameraLerp01=0;_cameraLerpDuration=0;_fovLerpActive=!1;_fovLerpStartValue=0;_fovLerpEndValue=0;_fovLerp01=0;_fovLerpDuration=0;_inputs=0;_enableTime=0;_startedListeningToKeyEvents=!1;_eventSystem;_afterHandleInputFn;_camera=null;_syncedTransform;_didSetTarget=0;_didApplyLookAtTarget=!1;awake(){ut&&console.debug("OrbitControls",this),this._didSetTarget=0,this._didApplyLookAtTarget=!1,this._startedListeningToKeyEvents=!1,this.context.domElement.cameraControls===!1&&(this.enabled=!1)}start(){this._eventSystem=Gt.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(rm.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){this._controls?.dispose(),this._eventSystem?.removeEventListener(rm.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._didApplyLookAtTarget=!1,this._enableTime=this.context.time.time;const e=S.getComponent(this.gameObject,si);this._camera=e;let t=e?.threeCamera;if(!t&&this.gameObject instanceof c.PerspectiveCamera&&(t=this.gameObject),t&&Ap(t,this,!0),!this._controls&&t instanceof c.Object3D){this._cameraObject=t;const i=this.targetElement??this.context.renderer.domElement,n=t?.quaternion.clone();this._controls=new X.OrbitControls(t,i),t?.quaternion.copy(n),qf===void 0&&(qf={...this._controls.keys});const o=Y(t),r=this.gameObject.worldForward,l=o.clone().sub(r.multiplyScalar(2.5));this._controls.target.copy(l)}if(this._controls)if(Hf&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,exports.DeviceUtilities.isMobileDevice()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),this._controls.addEventListener("endMovement",this.onControlsChangeEnded),!this._startedListeningToKeyEvents&&this.enableKeys)this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(this.context.domElement);else try{this._controls.stopListenToKeyEvents()}catch{}this._syncedTransform=S.getComponent(this.gameObject,pn)??void 0,this.context.pre_render_callbacks.push(this.__onPreRender),this._activePointerEvents=[],this.context.input.addEventListener("pointerdown",this._onPointerDown,{queue:ti.Early}),this.context.input.addEventListener("pointerdown",this._onPointerDownLate,{queue:ti.Late}),this.context.input.addEventListener("pointerup",this._onPointerUp,{queue:ti.Early}),this.context.input.addEventListener("pointerup",this._onPointerUpLate,{queue:ti.Late})}onDisable(){if(this._camera?.threeCamera&&Ap(this._camera.threeCamera,this,!1),this._controls){this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted),this._controls.removeEventListener("endMovement",this.onControlsChangeEnded);try{this._controls.stopListenToKeyEvents()}catch{}this._startedListeningToKeyEvents=!1}this._activePointerEvents.length=0,this.context.input.removeEventListener("pointerdown",this._onPointerDown),this.context.input.removeEventListener("pointerdown",this._onPointerDownLate),this.context.input.removeEventListener("pointerup",this._onPointerUp),this.context.input.removeEventListener("pointerup",this._onPointerUpLate)}_activePointerEvents;_lastTimeClickOnBackground=-1;_clickOnBackgroundCount=0;_onPointerDown=e=>{this._activePointerEvents.push(e)};_onPointerDownLate=e=>{e.used&&this._controls&&(this._controls.enabled=!1)};_onPointerUp=e=>{for(let t=this._activePointerEvents.length-1;t>=0;t--){const i=this._activePointerEvents[t];if(i.pointerId===e.pointerId&&i.button===e.button){this._activePointerEvents.splice(t,1);break}}if(this.clickBackgroundToFitScene>0&&e.isClick&&e.button===0){if(e.hasRay||e.intersections.push(...this.context.physics.raycast()),e.intersections.length<=0){const t=this.context.time.time-this._lastTimeClickOnBackground;this._lastTimeClickOnBackground=this.context.time.time,this.clickBackgroundToFitScene<=1||t<this.clickBackgroundToFitScene*.15?(this._clickOnBackgroundCount+=1,this._clickOnBackgroundCount>=this.clickBackgroundToFitScene-1&&(this.autoRotate=!1,this.fitCamera({objects:this.context.scene,immediate:!1}))):this._clickOnBackgroundCount=0}ut&&console.log(this.clickBackgroundToFitScene,e.intersections.length,this._clickOnBackgroundCount)}};_onPointerUpLate=e=>{this.doubleClickToFocus&&e.isDoubleClick&&!e.used&&this.setTargetFromRaycast()};updateTargetNow(e){ut&&console.warn("OrbitControls: updateTargetNow is using raycasting to update the target immediately. This can be expensive and should be used with caution.",e);const t=new c.Ray(this._cameraObject?.worldPosition,this._cameraObject?.worldForward.multiplyScalar(-1)),i=this.context.physics.raycastFromRay(t,e),n=i.length>0?i[0]:void 0;n&&n.distance>this.minZoom&&n.distance<this.maxZoom?(ut&&B.DrawWireSphere(n.point,.1,16711680,2),this._controls?.target.copy(i[0].point)):ut&&console.log("OrbitControls: No hit found when updating target",{hits:[...i]})}_orbitStartAngle=0;_zoomStartDistance=0;onControlsChangeStarted=()=>{ut&&console.debug("OrbitControls: Change started"),this._controls&&(this._orbitStartAngle=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle(),this._zoomStartDistance=this._controls.getDistance()),this._syncedTransform&&this._syncedTransform.requestOwnership()};onControlsChangeEnded=()=>{if(ut&&console.debug("OrbitControls: Change ended",{autoTarget:this.autoTarget}),this._controls&&this.autoTarget){const t=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle()-this._orbitStartAngle;Math.abs(t)<.01?(ut&&console.debug("OrbitControls: Update target",{deltaAngle:t}),this.updateTargetNow({allowSlowRaycastFallback:!1})):ut&&console.debug("OrbitControls: No target update",{deltaAngle:t})}};_shouldDisable=!1;afterHandleInput(e){e.detail.args.pointerId===0&&(e.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!e.detail.args.isPressed||e.detail.args.isUp)&&(this._shouldDisable=!1))}onPausedChanged(e){this._controls&&e&&(this._controls.enabled=!1)}onBeforeRender(){if(!this._controls)return;if(this._cameraObject!==this.context.mainCamera){this._controls.enabled=!1;return}if(this._controls.enabled=!0,(this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2)||this.context.input.mouseWheelChanged||this.context.input.getPointerPressed(0)&&this.context.input.getPointerPositionDelta(0)?.length())&&(this._inputs+=1),this._inputs>0&&this.allowInterrupt&&(this.enableRotate&&(this.autoRotate=!1),this._cameraLerpActive=!1,this._lookTargetLerpActive=!1),this._inputs=0,this.autoTarget&&this._didSetTarget++===0){const t=S.getComponent(this.gameObject,si);if(t&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const i=Y(t.threeCamera),n=Math.max(.01,i.length()),o=new c.Vector3(0,0,-n).applyMatrix4(t.threeCamera.matrixWorld);ut&&B.DrawLine(i,o,5592575,10),this.setLookTargetPosition(o,!0)}if(!this.setLookTargetFromConstraint()){const i=new vo;i.screenPoint=new c.Vector2(0,0),i.lineThreshold=.1;const n=this.context.physics.raycast(i);n.length>0&&this.setLookTargetPosition(n[0].point,!0),fO&&console.log("OrbitControls hits",...n)}}if(this.middleClickToFocus&&this.context.input.getPointerClicked(1)&&this.setTargetFromRaycast(),this._lookTargetLerpActive||this._cameraLerpActive||this._fovLerpActive){if(this._cameraLerpActive&&this._cameraObject)if(this._cameraLerp01+=this.context.time.deltaTime/this._cameraLerpDuration,this._cameraLerp01>=1)this._cameraObject.position.copy(this._cameraEndPosition),this._cameraLerpActive=!1,this.dispatchEvent(new Cc(this,"camera"));else{const t=I.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,t)}if(this._lookTargetLerpActive)if(this._lookTargetLerp01+=this.context.time.deltaTime/this._lookTargetLerpDuration,this._lookTargetLerp01>=1)this.lerpLookTarget(this._lookTargetEndPosition,this._lookTargetEndPosition,1),this._lookTargetLerpActive=!1,this.dispatchEvent(new Cc(this,"lookat"));else{const t=I.easeInOutCubic(this._lookTargetLerp01);this.lerpLookTarget(this._lookTargetStartPosition,this._lookTargetEndPosition,t)}if(this._fovLerpActive&&this._cameraObject){const t=this._cameraObject;if(this._fovLerp01+=this.context.time.deltaTime/this._fovLerpDuration,this._fovLerp01>=1)t.fov=this._fovLerpEndValue,this._fovLerpActive=!1;else{const i=I.easeInOutCubic(this._fovLerp01);t.fov=I.lerp(this._fovLerpStartValue,this._fovLerpEndValue,i)}t.updateProjectionMatrix()}}if(this.targetBounds){const t=this._controls.target,i=this.targetBounds.worldPosition,n=F(this.targetBounds.worldScale).multiplyScalar(.5),o=F(i).sub(n),r=F(i).add(n),a=F(this._controls.target).clamp(o,r),l=.1;t.lerp(a,this.context.time.deltaTime/l),this._lookTargetLerpActive&&this._lookTargetEndPosition.lerp(a,this.context.time.deltaTime/(l*5)),ut&&B.DrawWireBox(i,n.multiplyScalar(2),16755200)}if(this._controls){this.debugLog&&(this._controls.domElement=this.context.renderer.domElement);const t=1/(this.context.focusRectSettings?.zoom||1);if(this._controls.enabled=!this._shouldDisable&&this._camera===this.context.mainCameraComponent&&!this.context.isInXR&&!this._activePointerEvents.some(i=>i.used),this._controls.keys=this.enableKeys?qf:pO,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,this._controls.zoomSpeed=this.zoomSpeed,this._controls.zoomToCursor=this.zoomToCursor,this._controls.enableDamping=this.enableDamping,this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._controls.panSpeed=t,this._controls.enableRotate=this.enableRotate,this._controls.minAzimuthAngle=this.minAzimuthAngle,this._controls.maxAzimuthAngle=this.maxAzimuthAngle,this._controls.minPolarAngle=this.minPolarAngle,this._controls.maxPolarAngle=this.maxPolarAngle,Hf||(this._camera?.threeCamera?.type==="PerspectiveCamera"?(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom,this._controls.minZoom=0,this._controls.maxZoom=1/0):(this._controls.minDistance=0,this._controls.maxDistance=1/0,this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom)),typeof Gh=="number"||Gh===!0){this._controls.enableDamping=!0;const i=typeof Gh=="number"?Gh:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,i))}this.allowInterrupt||(this._lookTargetLerpActive&&(this._controls.enablePan=!1),this._cameraLerpActive&&(this._controls.enableRotate=!1,this._controls.autoRotate=!1),(this._lookTargetLerpActive||this._cameraLerpActive)&&(this._controls.enableZoom=!1)),this.context.isInXR||(!Hf&&this.lookAtTarget&&!this._lookTargetLerpActive&&(this.lockLookAtTarget?this.setLookTargetFromConstraint(this.lookAtConstraint01):this._didApplyLookAtTarget||(this._didApplyLookAtTarget=!0,this.setLookTargetFromConstraint(1))),this._controls.update(this.context.time.deltaTime),ut&&B.DrawWireSphere(this._controls.target,.1,65280))}}__onPreRender=()=>{const e=this.context.pre_render_callbacks.indexOf(this.__onPreRender);e>=0&&this.context.pre_render_callbacks.splice(e,1),this.autoFit&&(this.autoFit=!1,this.fitCamera({centerCamera:"y",immediate:!0,objects:this.scene.children}))};setCameraAndLookTarget(e,t=!1){if(!e)return(A()||ut)&&console.warn("[OrbitControls] setCameraAndLookTarget target is null"),!1;if(!(e instanceof c.Object3D)&&!(e instanceof si))return(A()||ut)&&console.warn("[OrbitControls] setCameraAndLookTarget target is not an Object3D or Camera"),!1;e instanceof si&&(e=e.gameObject);const i=e.worldPosition,n=e.worldForward;e instanceof c.Camera&&(ut&&console.debug("[OrbitControls] setCameraAndLookTarget flip forward direction for camera"),n.multiplyScalar(-1));const o=new c.Ray(i,n);return ut&&B.DrawRay(o.origin,o.direction,16711680,10),this.setTargetFromRaycast(o,t)||this.setLookTargetPosition(o.at(2,F()),t),this.setCameraTargetPosition(i,t),!0}setCameraTargetPosition(e,t=!1){e&&(e instanceof c.Object3D&&(e=Y(e)),this._cameraEndPosition||(this._cameraEndPosition=new c.Vector3),this._cameraEndPosition.copy(e),t===!0?(this._cameraLerpActive=!1,this._cameraObject&&this._cameraObject.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy(this._cameraObject?.position),typeof t=="number"?this._cameraLerpDuration=t:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setFieldOfView(e,t=!1){if(!this._controls||typeof e!="number")return;const i=this._camera?.threeCamera;i&&(t===!0?i.fov=e:(this._fovLerpActive=!0,this._fovLerp01=0,this._fovLerpStartValue=i.fov,this._fovLerpEndValue=e,typeof t=="number"?this._fovLerpDuration=t:this._fovLerpDuration=this.targetLerpDuration))}setLookTargetPosition(e=null,t=!1){this._controls&&e&&(e instanceof c.Object3D&&(e=Y(e)),this._lookTargetEndPosition.copy(e),this._didSetTarget++,ut&&(console.warn("OrbitControls: setLookTargetPosition",e,t),B.DrawWireSphere(this._lookTargetEndPosition,.2,16711680,2)),t===!0?this.lerpLookTarget(this._lookTargetEndPosition,this._lookTargetEndPosition,1):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof t=="number"?this._lookTargetLerpDuration=t:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(e=1){return!this._controls||!this.lookAtTarget?!1:(this.lookAtTarget.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._controls.target,this._lookTargetEndPosition,e),!0)}lerpLookTarget(e,t,i){this._controls&&(i>=1?this._controls.target.copy(t):this._controls.target.lerpVectors(e,t,i),this.lookAtTarget&&this.lockLookAtTarget&&(this.lookAtTarget.worldPosition=this._controls.target))}setTargetFromRaycast(e,t=!1){if(!this.controls)return!1;const i=e?this.context.physics.raycastFromRay(e):this.context.physics.raycast();for(const n of i)if(n.distance>0&&S.isActiveInHierarchy(n.object)){const o=bg(n.object);if(o&&o.canvas?.screenspace)break;return this.setLookTargetPosition(n.point,t),!0}return!1}fitCamera(e,t){let i;if(Array.isArray(e)||e&&"type"in e?i=e:e&&typeof e=="object"&&!(e instanceof c.Object3D)&&!Array.isArray(e)&&(t=e,i=t.objects),i&&!Array.isArray(i)&&(i=[i]),(!Array.isArray(i)||i&&i.length<=0)&&(i=this.context.scene.children),!Array.isArray(i)||i.length<=0){console.warn("No objects to fit camera to...");return}const n=ow({objects:[...i],...t,autoApply:!1,context:this.context,camera:this._cameraObject,currentZoom:this._controls?.getDistance()||void 0,minZoom:this.minZoom,maxZoom:this.maxZoom});n&&(this.setLookTargetPosition(n.lookAt,t?.immediate||!1),this.setCameraTargetPosition(n.position,t?.immediate||!1),this.setFieldOfView(t?.fov,t?.immediate||!1),this.onBeforeRender())}_haveAttachedKeyboardEvents=!1}ye([f()],de.prototype,"autoTarget",2);ye([f()],de.prototype,"autoFit",2);ye([f()],de.prototype,"enableRotate",2);ye([f()],de.prototype,"autoRotate",2);ye([f()],de.prototype,"autoRotateSpeed",2);ye([f()],de.prototype,"minAzimuthAngle",2);ye([f()],de.prototype,"maxAzimuthAngle",2);ye([f()],de.prototype,"minPolarAngle",2);ye([f()],de.prototype,"maxPolarAngle",2);ye([f()],de.prototype,"enableKeys",2);ye([f()],de.prototype,"enableDamping",2);ye([f()],de.prototype,"dampingFactor",2);ye([f()],de.prototype,"enableZoom",2);ye([f()],de.prototype,"minZoom",2);ye([f()],de.prototype,"maxZoom",2);ye([f()],de.prototype,"zoomSpeed",2);ye([f()],de.prototype,"enablePan",2);ye([f(c.Object3D)],de.prototype,"lookAtTarget",2);ye([f()],de.prototype,"lockLookAtTarget",2);ye([f()],de.prototype,"lookAtConstraint01",2);ye([f()],de.prototype,"allowInterrupt",2);ye([f()],de.prototype,"middleClickToFocus",2);ye([f()],de.prototype,"doubleClickToFocus",2);ye([f()],de.prototype,"clickBackgroundToFitScene",2);ye([f()],de.prototype,"targetLerpDuration",1);ye([f(c.Object3D)],de.prototype,"targetBounds",2);var mO=Object.defineProperty,gO=Object.getOwnPropertyDescriptor,qt=(s,e,t,i)=>{for(var n=i>1?void 0:i?gO(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&&mO(e,t,n),n},lr=(s=>(s[s.None=0]="None",s[s.Skybox=1]="Skybox",s[s.SolidColor=2]="SolidColor",s[s.Uninitialized=4]="Uninitialized",s))(lr||{});const Ys=x("debugcam"),ib=x("debugscreenpointtoray"),At=class Vl extends R{get isCamera(){return!0}get aspect(){return this._cam instanceof c.PerspectiveCamera?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(e){this._cam instanceof c.PerspectiveCamera&&this._cam.aspect!==e&&(this._cam.aspect=e,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof c.PerspectiveCamera?this._cam.fov:this._fov}set fieldOfView(e){const t=this.fieldOfView!=e;if(this._fov=e,t&&this._cam&&this._cam instanceof c.PerspectiveCamera){if(this._fov===void 0){console.warn("Can not set undefined fov on PerspectiveCamera");return}this._cam.fov=this._fov,this._cam.updateProjectionMatrix()}}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(e){const t=this._nearClipPlane!=e;this._nearClipPlane=e,this._cam&&(t||this._cam.near!=e)&&(this._cam.near=e,this._cam.updateProjectionMatrix())}_nearClipPlane=.1;get farClipPlane(){return this._farClipPlane}set farClipPlane(e){const t=this._farClipPlane!=e;this._farClipPlane=e,this._cam&&(t||this._cam.far!=e)&&(this._cam.far=e,this._cam.updateProjectionMatrix())}_farClipPlane=1e3;applyClippingPlane(){this._cam&&(this._cam.near=this._nearClipPlane,this._cam.far=this._farClipPlane,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(e){if(typeof e=="string")switch(e){case"skybox":e=1;break;case"solidcolor":e=2;break;default:e=0;break}e!==this._clearFlags&&(this._clearFlags=e,this.applyClearFlagsIfIsActiveCamera())}orthographic=!1;orthographicSize=5;ARBackgroundAlpha=0;set cullingMask(e){this._cullingMask=e,this._cam&&(this._cam.layers.mask=e)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}_cullingMask=4294967295;set cullingLayer(e){this.cullingMask=(1<<e|0)>>>0}set backgroundBlurriness(e){e!==this._backgroundBlurriness&&(e===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(e,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}_backgroundBlurriness=void 0;set backgroundIntensity(e){e!==this._backgroundIntensity&&(e===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(e,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}_backgroundIntensity=void 0;set backgroundRotation(e){e!==this._backgroundRotation&&(e===void 0?this._backgroundRotation=void 0:this._backgroundRotation=e,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}_backgroundRotation=void 0;set environmentIntensity(e){this._environmentIntensity=e}get environmentIntensity(){return this._environmentIntensity}_environmentIntensity=void 0;get backgroundColor(){return this._backgroundColor??null}set backgroundColor(e){e&&(this._backgroundColor||(this._backgroundColor=new te(1,1,1,1)),this._backgroundColor.copy(e),(!("alpha"in e)||e.alpha===void 0)&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera())}set targetTexture(e){this._targetTexture=e}get targetTexture(){return this._targetTexture}_targetTexture=null;_backgroundColor;_fov;_cam=null;_clearFlags=2;_skybox;get cam(){return this.threeCamera}get threeCamera(){return this.activeAndEnabled&&this.buildCamera(),this._cam}static _origin=new c.Vector3;static _direction=new c.Vector3;screenPointToRay(e,t,i){const n=this.threeCamera,o=Vl._origin;o.set(e,t,-1),this.context.input.convertScreenspaceToRaycastSpace(o),ib&&console.log("screenPointToRay",e.toFixed(2),t.toFixed(2),"now:",o.x.toFixed(2),o.y.toFixed(2),"isInXR:"+this.context.isInXR),o.z=-1,o.unproject(n);const r=Vl._direction.set(o.x,o.y,o.z),a=Y(n);return r.sub(a),r.normalize(),i?(i.set(a,r),i):new c.Ray(a.clone(),r.clone())}_frustum;getFrustum(){return this._frustum||(this._frustum=new c.Frustum,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new c.Frustum),this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(e,t){return t&&this._projScreenMatrix.multiplyMatrices(this.threeCamera.projectionMatrix,this.threeCamera.matrixWorldInverse),e===this._projScreenMatrix?e:e.copy(this._projScreenMatrix)}_projScreenMatrix=new c.Matrix4;awake(){ib&&window.addEventListener("pointerdown",e=>{const t=e.clientX,i=e.clientY;console.log("touch",t.toFixed(2),i.toFixed(2));const n=this.screenPointToRay(t,i),o="#"+Math.floor(Math.random()*16777215).toString(16);B.DrawRay(n.origin,n.direction,o,10)})}onEnable(){Ys&&console.log(`Camera enabled: "${this.name}". ClearFlags=${lr[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),_O(this)),this.applyClearFlagsIfIsActiveCamera({applySkybox:!0})}onDisable(){this.context.removeCamera(this)}onLeaveXR(e){this.fieldOfView=this._fov}onBeforeRender(){if(this._cam&&(this._frustum&&this.updateFrustum(),this._clearFlags===2&&this.applyClearFlagsIfIsActiveCamera(),this._targetTexture)){this.context.isManagedExternally&&(this._warnedAboutExternalRenderer||(this._warnedAboutExternalRenderer=!0,console.warn("Rendering with external renderer is not supported yet. This may not work or throw errors. Please remove the the target texture from your camera: "+this.name,this.targetTexture))),this.context.composer;const e=this.context.renderer;if(e){const t=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,e),t?.applyClearFlags()}}}buildCamera(){if(this._cam)return;const e=this.gameObject.isCamera;let t=null;if(e?(t=this.gameObject,t?.layers.enableAll(),t instanceof c.PerspectiveCamera&&(this._fov=t.fov)):t=this.gameObject.children[0],t&&t.isCamera)t instanceof c.PerspectiveCamera&&(this._fov&&(t.fov=this._fov),t.near=this._nearClipPlane,t.far=this._farClipPlane,t.updateProjectionMatrix());else if(!this.orthographic)t=new c.PerspectiveCamera(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(t.fov=this.fieldOfView),this.gameObject.add(t);else{const i=this.orthographicSize*100;t=new c.OrthographicCamera(window.innerWidth/-i,window.innerWidth/i,window.innerHeight/i,window.innerHeight/-i,this._nearClipPlane,this._farClipPlane),this.gameObject.add(t)}this._cam=t,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(e){this.context.mainCameraComponent===this&&this.applyClearFlags(e)}applyClearFlags(e){if(!this._cam){Ys&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this.fieldOfView,Ys){const i=`[Camera] Apply ClearFlags: ${lr[this._clearFlags]} - "${this.name}"`;console.debug(i)}const t=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color");switch(this._clearFlags){case 0:return;case 1:if(Vl.backgroundShouldBeTransparent(this.context)&&(!this.ARBackgroundAlpha||this.ARBackgroundAlpha<.001)){this.context.scene.background=null,this.context.renderer.setClearColor(0,0);return}(!this.scene.background||!this._skybox||e?.applySkybox===!0)&&this.applySceneSkybox(),this._backgroundBlurriness!==void 0&&!this.context.domElement.getAttribute("background-blurriness")?this.context.scene.backgroundBlurriness=this._backgroundBlurriness:Ys&&console.warn(`Camera "${this.name}" has no background blurriness`),this._backgroundIntensity!==void 0&&!this.context.domElement.getAttribute("background-intensity")&&(this.context.scene.backgroundIntensity=this._backgroundIntensity),this._backgroundRotation!==void 0&&!this.context.domElement.getAttribute("background-rotation")?this.context.scene.backgroundRotation=this._backgroundRotation:Ys&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor&&!t){let i=this._backgroundColor.alpha;Vl.backgroundShouldBeTransparent(this.context)&&(i=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.xr?.isVR?this.context.renderer.setClearColor(gv(this._backgroundColor).convertLinearToSRGB()):this.context.renderer.setClearColor(this._backgroundColor,i)}else this._backgroundColor||Ys&&console.warn(`[Camera] has no background color "${this.name}" `);break;case 4:t||(this.context.scene.background=null,this.context.renderer.setClearColor(0,0));break}}applySceneSkybox(){this._skybox||(this._skybox=new yO(this)),this._skybox.apply()}static backgroundShouldBeTransparent(e){const t=e.renderer.xr?.getSession();if(!t)return!1;if(typeof t._transparent=="boolean")return t._transparent;const i=t.environmentBlendMode;Ys&&Se("Environment blend mode: "+i+" on "+navigator.userAgent);let n=i==="additive"||i==="alpha-blend";if(e.isInAR&&i==="opaque"){if(navigator.userAgent?.includes("OculusBrowser"))n=!0;else if(navigator.userAgent?.includes("Mozilla")&&navigator.userAgent?.includes("Mobile WebXRViewer/v2"))n=!0;else if(exports.DeviceUtilities.isNeedleAppClip())return!0}return t._transparent=n,n}};qt([f()],At.prototype,"aspect",1);qt([f()],At.prototype,"fieldOfView",1);qt([f()],At.prototype,"nearClipPlane",1);qt([f()],At.prototype,"farClipPlane",1);qt([f()],At.prototype,"clearFlags",1);qt([f()],At.prototype,"orthographic",2);qt([f()],At.prototype,"orthographicSize",2);qt([f()],At.prototype,"ARBackgroundAlpha",2);qt([f()],At.prototype,"cullingMask",1);qt([f()],At.prototype,"backgroundBlurriness",1);qt([f()],At.prototype,"backgroundIntensity",1);qt([f(c.Euler)],At.prototype,"backgroundRotation",1);qt([f()],At.prototype,"environmentIntensity",1);qt([f(te)],At.prototype,"backgroundColor",1);qt([f(Bn)],At.prototype,"targetTexture",1);let si=At;class yO{_camera;_skybox;get context(){return this._camera?.context}constructor(e){this._camera=e}apply(){if(this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),!this._skybox)this._did_log_failed_to_find_skybox||(this._did_log_failed_to_find_skybox=!0,console.warn(`Camera "${this._camera.name}" has no skybox texture. ${this._camera.sourceId}`));else if(this.context.scene.background!==this._skybox){const e=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color");Ys&&console.debug(`[Camera] Apply Skybox ${this._skybox?.name} ${e} - "${this._camera.name}"`),e?.length||(this._skybox.mapping!==c.CubeUVReflectionMapping&&(this._skybox.mapping=c.EquirectangularReflectionMapping),this.context.scene.background=this._skybox)}}}function _O(s){x("freecam")&&s.context.mainCameraComponent===s&&S.getOrAddComponent(s.gameObject,de)}class ds extends R{get listener(){return this._listener==null&&(this._listener=new c.AudioListener),this._listener}_listener=null;onEnable(){fn.registerWaitForInteraction(this.onInteraction),this.addListenerIfItExists()}onDisable(){fn.unregisterWaitForInteraction(this.onInteraction),this.removeListenerIfItExists()}onInteraction=()=>{this.destroyed||this.listener==null||this.addListenerIfItExists()};addListenerIfItExists(){const e=this._listener;if(!e||e?.parent)return;const t=this.context.mainCameraComponent||S.getComponentInParent(this.gameObject,si);t?.threeCamera?t.threeCamera.add(e):this.gameObject.add(e),e.filter?(e.gain.connect(e.filter),e.filter.connect(e.context.destination)):e.gain.connect(e.context.destination)}removeListenerIfItExists(){const e=this._listener;e&&(e.removeFromParent(),e.filter&&e.filter.disconnect(),e.gain&&e.gain.disconnect())}}var bO=Object.defineProperty,vO=Object.getOwnPropertyDescriptor,yn=(s,e,t,i)=>{for(var n=i>1?void 0:i?vO(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&&bO(e,t,n),n};const ft=x("debugaudio"),qi=class Ks extends R{static get userInteractionRegistered(){return fn.userInteractionRegistered}static registerWaitForAllowAudio(e){fn.registerWaitForInteraction(e)}clip="";playOnAwake=!1;preload=!0;playInBackground=!0;get isPlaying(){return this.sound?.isPlaying??!1}get duration(){return this.sound?.buffer?.duration}get time01(){const e=this.duration;return e&&this.sound?this.sound?.context.currentTime/e:0}set time01(e){const t=this.duration;t&&this.sound&&(this.time=e*t)}get time(){return this.sound?.source?this.sound.source?.context.currentTime-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;const t=this.isPlaying;this.stop(),this.sound.offset=e,t&&this.play()}}get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(e){this._loop=e,this.sound&&this.sound.setLoop(e)}get spatialBlend(){return this._spatialBlend}set spatialBlend(e){e!==this._spatialBlend&&(this._spatialBlend=e,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(e){this._minDistance!==e&&(this._minDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(e){this._maxDistance!==e&&(this._maxDistance=e,this._needUpdateSpatialDistanceSettings=!0)}_spatialBlend=0;_minDistance=1;_maxDistance=100;get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&!this.context.application.muted&&(ft&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}_volume=1;set pitch(e){this.sound&&this.sound.setPlaybackRate(e)}get pitch(){return this.sound?this.sound.getPlaybackRate():1}rollOffMode=0;_loop=!1;sound=null;helper=null;wasPlaying=!1;audioLoader=null;shouldPlay=!1;_lastClipStartedLoading=null;_audioElement=null;get Sound(){if(!this.sound&&Ks.userInteractionRegistered){let e=this.gameObject.getComponent(ds)??this.context.mainCamera.getComponent(ds)??Wa(ds,this.context,!1);!e&&this.context.mainCamera&&(e=this.context.mainCamera.addComponent(ds)),e?.listener?(this.sound=new c.PositionalAudio(e.listener),this.gameObject?.add(this.sound)):ft&&console.warn("No audio listener found in scene - can not play audio")}return this.sound}get ShouldPlay(){return this.shouldPlay}get audioContext(){return this.sound?.context}awake(){ft&&console.log("[AudioSource]",this),this.audioLoader=new c.AudioLoader,this.playOnAwake&&(this.shouldPlay=!0),this.preload&&typeof this.clip=="string"&&this.audioLoader.load(this.clip,this.createAudio,()=>{},console.error)}onEnable(){this.sound&&this.gameObject.add(this.sound),Ks.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():Ks.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(Bp.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(Bp.MuteChanged,this.onApplicationMuteChanged),this.pause()}onVisibilityChanged=()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||exports.DeviceUtilities.isMobileDevice())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":ft&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,Ks.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&Ks.userInteractionRegistered&&this.wasPlaying&&this.play();break}};onApplicationMuteChanged=()=>{this.context.application.muted?this.sound?.setVolume(0):this.sound?.setVolume(this.volume)};createAudio=e=>{if(this.destroyed){ft&&console.warn("AudioSource destroyed, not creating audio",this.name);return}ft&&console.log("AudioBuffer finished loading",e);const t=this.Sound;if(!t){ft&&console.warn("Failed getting sound?",this.name);return}t.isPlaying&&t.stop(),e&&t.setBuffer(e),t.loop=this._loop,this.context.application.muted?t.setVolume(0):t.setVolume(this.volume),t.autoplay=this.shouldPlay&&Ks.userInteractionRegistered,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),Ks.registerWaitForAllowAudio(this.__onAllowAudioCallback)};__onAllowAudioCallback=()=>{this.shouldPlay&&this.play()};applySpatialDistanceSettings(){const e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;const t=I.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(ft&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+t),e.setRefDistance(t),e.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:e.setDistanceModel("exponential");break;case 1:e.setDistanceModel("linear");break;case 2:console.warn("Custom rolloff for AudioSource is not supported: "+this.name);break}this.spatialBlend>0?ft&&!this.helper&&(this.helper=new X.PositionalAudioHelper(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}async onNewClip(e){if(e&&(this.clip=e),typeof e=="string")if(ft&&console.log(e),e.endsWith(".mp3")||e.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new c.AudioLoader),this.shouldPlay=!0,this._lastClipStartedLoading===e){ft&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=e,ft&&console.log("load audio",e);const t=await this.audioLoader.loadAsync(e).catch(console.error);if(this.destroyed)return;this._lastClipStartedLoading===e&&(this._lastClipStartedLoading=null),t&&this.createAudio(t)}else console.warn("Unsupported audio clip type",e);else this.shouldPlay=!0,this.createAudio()}play(e=void 0){!e&&this.clip&&(e=this.clip),e!==void 0&&typeof e!="string"&&!(e instanceof MediaStream)&&(A()&&console.warn("Called play on AudioSource with unknown argument type:",e+`
|
|
975
|
-
Using the assigned clip instead:`,this.clip),e=this.clip);let t=!this.sound||e&&e!==this.clip;if(typeof e=="string"&&!this.audioLoader&&(t=!0),(e instanceof MediaStream||typeof e=="string")&&(this.clip=e),t){this.shouldPlay=!0,this.onNewClip(e);return}if(this.shouldPlay=!0,this._hasEnded=!1,ft&&console.log("play",this.sound?.getVolume(),this.sound),this.sound&&!this.sound.isPlaying){const i=this.context.application.muted;i&&this.sound.setVolume(0),this.gameObject?.add(this.sound),this.clip instanceof MediaStream?(this.sound.setMediaStreamSource(this.clip),this._audioElement||(this._audioElement=document.createElement("audio"),this._audioElement.style.display="none"),this._audioElement.parentNode||this.context.domElement.shadowRoot?.append(this._audioElement),this._audioElement.srcObject=this.clip,this._audioElement.autoplay=!1):(this._audioElement&&this._audioElement.remove(),this.sound.play(i?.1:0))}}pause(){ft&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,this.sound.pause()),this._audioElement?.remove()}stop(){ft&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,ft&&console.log(this._lastContextTime),this.sound.stop()),this._audioElement?.remove()}_lastContextTime=0;_hasEnded=!0;_needUpdateSpatialDistanceSettings=!1;update(){this.helper&&(this.isPlaying&&this.helper.update(),this.helper.visible=this.isPlaying),this._needUpdateSpatialDistanceSettings&&this.applySpatialDistanceSettings(),this.sound&&!this.sound.isPlaying&&this.shouldPlay&&!this._hasEnded&&(this._hasEnded=!0,ft&&console.log("Audio clip ended",this.clip),this.dispatchEvent(new CustomEvent("ended",{detail:this})))}};yn([f(URL)],qi.prototype,"clip",2);yn([f()],qi.prototype,"playOnAwake",2);yn([f()],qi.prototype,"preload",2);yn([f()],qi.prototype,"playInBackground",2);yn([f()],qi.prototype,"loop",1);yn([f()],qi.prototype,"spatialBlend",1);yn([f()],qi.prototype,"minDistance",1);yn([f()],qi.prototype,"maxDistance",1);yn([f()],qi.prototype,"volume",1);yn([f()],qi.prototype,"pitch",1);yn([f()],qi.prototype,"rollOffMode",2);let vi=qi;const wO=x("debugavatar");class Oe extends R{static getAvatar(e){return e>=0&&e<Oe.instances.length?Oe.instances[e]:null}static instances=[];static onAvatarMarkerCreated(e){return Oe._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return Oe._onAvatarMarkerDestroyed.push(e),e}static _onNewAvatarMarkerAdded=[];static _onAvatarMarkerDestroyed=[];connectionId;avatar;awake(){Oe.instances.push(this),wO&&console.log(this);for(const e of Oe._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){Oe.instances.splice(Oe.instances.indexOf(this),1);for(const e of Oe._onAvatarMarkerDestroyed)e({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}}class cr{static Pois=[];static LastChangeTime=0;static Add(e,t,i=null){if(t){for(const n of this.Pois)if(n.obj===t)return;this.Pois.push({obj:t,avatar:i}),this.LastChangeTime=e.time.time}}static Remove(e,t){if(t){for(const i of this.Pois)if(i.obj===t){this.Pois.splice(this.Pois.indexOf(i),1),this.LastChangeTime=e?.time.time??U.Current?.time.time;return}}}}class xO{guid;position=new c.Vector3}class Pc extends R{set controlledTarget(e){this.target=e;const t=P.get("MoveRandom");if(t&&this.target){const i=S.getComponent(this.target,t);i&&i.destroy()}}target=null;avatar=null;_model=null;_targetModel=new xO;_currentTargetObject=null;_lastUpdateTime=0;_lookDuration=0;_lastPoiChangedTime=0;awake(){if(this.avatar=S.getComponentInParent(this.gameObject,Oe),this.avatar){const e=S.getComponentInParent(this.gameObject,Oe);this._model=new Ym(this.context.connection,this.guid),e?.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",e=>{this.target&&e&&e.guid===this.avatar?.guid&&at(this.target,e.position)})}update(){if((!this.context.connection.isConnected||this._model?.hasOwnership)&&(cr.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=cr.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){const t=Y(this._currentTargetObject);at(this.target,t),this.context.connection.isConnected&&this.avatar&&(this.context.connection.send("avatar-look-target-changed",this._targetModel),this._targetModel.guid=this.avatar.guid,this._targetModel.position.copy(t))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;const t=cr.Pois;if(t.length>0){const i=t[Math.floor(Math.random()*t.length)];if(i&&i.obj){if(i.avatar&&i.avatar===this.avatar)return;this._currentTargetObject=i.obj}}}}}const Ee=x("debugnetworkingstreams");var Fn=(s=>(s.Connected="peer-user-connected",s.StreamReceived="receive-stream",s.StreamEnded="call-ended",s.Disconnected="peer-user-disconnected",s.UserJoined="user-joined",s))(Fn||{});class vg{type="call-ended";userId;direction;constructor(e,t){this.userId=e,this.direction=t}}class dw{type="receive-stream";userId;stream;target;constructor(e,t,i){this.userId=e,this.stream=t,this.target=i}}class SO{guid;peerId;dontSave=!0;constructor(e,t){this.guid=e.id,this.peerId=t}}var uw=(s=>(s.Incoming="incoming",s.Outgoing="outgoing",s))(uw||{});class CO extends c.EventDispatcher{peerId;userId;direction;call;get stream(){return this._stream}_stream=null;_isDisposed=!1;close(){this._isDisposed||(this._isDisposed=!0,this.call.close(),Un(this._stream))}get isOpen(){return this.call.peerConnection?.connectionState==="connected"}get isOpening(){return this.call.peerConnection?.connectionState==="connecting"}get isClosed(){return!this.isOpen||this._isDisposed}constructor(e,t,i,n=null){super(),this.peerId=t.peer,this.userId=e,this.call=t,this.direction=i,this._stream=n,t.on("stream",o=>{if(Ee&&console.log("Receive stream",`
|
|
976
|
-
Audio:`,o.getAudioTracks(),`
|
|
977
|
-
Video:`,o.getVideoTracks()),this._stream=o,i==="incoming"){const r=new dw(e,o,this);this.dispatchEvent(r)}}),t.on("close",()=>{this.dispatchEvent(new vg(e,i))})}}function nb(s){return s=s.replace("a=fmtp:111 minptime=10;useinbandfec=1","a=fmtp:111 ptime=5;useinbandfec=1;stereo=1;maxplaybackrate=48000;maxaveragebitrat=128000;sprop-stereo=1"),s}class us extends c.EventDispatcher{static instances=new Map;static getOrCreate(e,t){if(us.instances.has(t))return us.instances.get(t);const i=new us(e,t);return us.instances.set(t,i),i}getMyPeerId(){if(this.context.connection.connectionId)return this.getPeerIdFromUserId(this.context.connection.connectionId)}getPeerIdFromUserId(e){return this.id+"-"+e}getUserIdFromPeerId(e){return e.substring(this.id.length+1)}makeCall(e,t){if(!t?.id){Ee?console.warn("Can not make a call: mediastream has no id or is undefined"):console.debug("Can not make a call: mediastream has no id or is undefined");return}const i={metadata:{userId:this.context.connection.connectionId,streamId:t.id},sdpTransform:o=>nb(o)},n=this._peer?.call(e,t,i);if(n){const o=this.registerCall(n,"outgoing",t);return Ee&&console.warn(`📞 CALL ${e}`,`
|
|
978
|
-
Outgoing:`,this._outgoingCalls,`
|
|
979
|
-
Incoming:`,this._incomingCalls),o}else Ee&&console.error("Failed to make call",e,t,this._peer)}closeAll(){for(const e of this._incomingCalls)e.close();for(const e of this._outgoingCalls)e.close();this.updateCalls()}updateCalls=()=>{for(let e=this._incomingCalls.length-1;e>=0;e--){const t=this._incomingCalls[e];t.isClosed&&!t.isOpening&&this._incomingCalls.splice(e,1)}for(let e=this._outgoingCalls.length-1;e>=0;e--){const t=this._outgoingCalls[e];let i=!1;t.isClosed&&!t.isOpening&&(t.stream?.active?Ee&&console.warn("!!! Stream is still active, don't remove call",t.userId,"Your id: "+this.context.connection.connectionId):(Ee&&console.warn("!!! Remove closed call",t.userId),i=!0)),this.context.connection.userIsInRoom(t.userId)===!1&&(Ee&&console.warn("!!! User is not in room anymore, remove call",t.userId),i=!0),i&&(t.close(),this._outgoingCalls.splice(e,1))}};get peer(){return this._peer}get incomingCalls(){return this._incomingCalls}id;context;_incomingCalls=[];_outgoingCalls=[];_peer;constructor(e,t){super(),this.context=e,this.id=t,this.setupPeer();const i=Object.getOwnPropertyDescriptor(navigator,"getUserMedia")?.writable;try{i?navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia:Ee&&console.warn("[PeerJs] getUserMedia is not writable")}catch(n){Ee&&console.error("[PeerJs] Error setting getUserMedia",n)}}_enabled=!1;_enabledPeer=!1;onConnectRoomFn=this.onConnectRoom.bind(this);enable(){this._enabled||(this._enabled=!0,this.context.connection.beginListen(K.JoinedRoom,this.onConnectRoomFn),this.subscribePeerEvents())}disable(){this._enabled&&(this._enabled=!1,this.context.connection.stopListen(K.JoinedRoom,this.onConnectRoomFn),this.unsubscribePeerEvents())}onConnectRoom(){this.setupPeer()}setupPeer(){if(this.context.connection.connectionId&&!this._enabledPeer){if(this._enabledPeer=!0,!this._peer){const e=this.getMyPeerId();e?this._peer=Gv(e):console.error("Failed to setup peerjs because we dont have a connection id",this.context.connection.connectionId)}this._enabled&&this.subscribePeerEvents()}}subscribePeerEvents(){this._peer&&(this._peer.on("open",this.onPeerConnect),this._peer.on("close",this.onPeerClose),this._peer.on("call",this.onPeerReceivingCall),this._peer.on("disconnected",this.onPeerDisconnected),this._peer.on("error",this.onPeerError))}unsubscribePeerEvents(){this._peer&&(this._peer.off("open",this.onPeerConnect),this._peer.off("close",this.onPeerClose),this._peer.off("call",this.onPeerReceivingCall),this._peer.off("disconnected",this.onPeerDisconnected),this._peer.off("error",this.onPeerError))}onPeerConnect=e=>{if(Ee&&console.log("PEER opened as",e),e===null){console.error("Peer connection failed",e);return}this.context.connection.send("peer-user-connected",new SO(this,e))};onPeerClose=()=>{Ee&&console.log("PEER closed"),this.updateCalls()};onPeerDisconnected=()=>{Ee&&console.log("PEER disconnected"),this.updateCalls()};onPeerError=e=>{Ee&&console.error("PEER error",e)};onPeerReceivingCall=e=>{e.answer(void 0,{sdpTransform:t=>nb(t)}),this.registerCall(e,"incoming",null)};registerCall(e,t,i){const n=e.metadata;(!n||!n.userId)&&console.error("Missing call metadata",e);const o=n.userId;t==="incoming"&&Ee?console.warn("← Receive call from",e.metadata,e.connectionId):Ee&&console.warn("→ Make call to",e.metadata);const r=t==="incoming"?this._incomingCalls:this._outgoingCalls,a=new CO(o,e,t,i);return r.push(a),e.on("error",l=>{console.error("Call error",l)}),e.on("close",()=>{Ee&&console.log("Call ended",e.metadata);const l=r.indexOf(a);l!==-1&&r.splice(l,1),a.close(),this.dispatchEvent(new vg(o,t))}),a.addEventListener("call-ended",l=>{this.dispatchEvent(l)}),t==="incoming"&&(a.addEventListener("receive-stream",l=>{this.dispatchEvent(l)}),e.on("stream",()=>{Ee&&console.log("Received stream for call",e.metadata);let l=0;const h=setInterval(()=>{const d=l===0;!a.isOpen&&d&&(Ee&&console.warn("Close call because stream is not active",e.metadata),l+=1,clearInterval(h),a.close())},2e3)})),a}}class Yc extends c.EventDispatcher{static create(e,t){const i=us.getOrCreate(e.context,t||e.context.connection.connectionId||e.guid);return new Yc(e.context,i)}context;peer;_sendingStreams=new Map;debug=!1;constructor(e,t){if(super(),$m(e)){const i=e;e=i.context,t=us.getOrCreate(i.context,i.guid)}else typeof t=="string"&&(t=us.getOrCreate(e,t));if(e){if(!(e instanceof U))throw new Error("Failed to create NetworkedStreams because context is not an instance of Context")}else throw new Error("Failed to create NetworkedStreams because context is undefined");if(!t)throw new Error("Failed to create NetworkedStreams because peer is undefined");this.context=e,this.peer=t,Ee&&(this.debug=!0)}startSendingStream(e){this._sendingStreams.has(e)?console.warn("Received start sending stream with stream that is already being sent"):(this._sendingStreams.set(e,[]),this.updateSendingCalls())}stopSendingStream(e){if(e){const t=this._sendingStreams.get(e);if(t){for(const i of t)i.close();t.length=0}this._sendingStreams.delete(e),t&&this.debug&&this.debugLogCurrentState()}this.updateSendingCalls()}_enabled=!1;get enabled(){return this._enabled}enable(){this._enabled||(this._enabled=!0,this.peer.enable(),this.peer.addEventListener("receive-stream",this.onCallStreamReceived),this.peer.addEventListener("call-ended",this.onCallEnded),this.context.connection.beginListen("peer-user-connected",this.onUserConnected),this.context.connection.beginListen(K.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(K.UserJoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(K.UserLeftRoom,this.onUserLeft),this.context.connection.beginListen(K.LeftRoom,this.onLeftRoom),this._tickIntervalId=setInterval(this.tick,5e3))}disable(){this._enabled&&(this._enabled=!1,this.peer.disable(),this.peer.removeEventListener("receive-stream",this.onCallStreamReceived),this.peer.removeEventListener("call-ended",this.onCallEnded),this.context.connection.stopListen("peer-user-connected",this.onUserConnected),this.context.connection.stopListen(K.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(K.UserJoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(K.UserLeftRoom,this.onUserLeft),this.context.connection.stopListen(K.LeftRoom,this.onLeftRoom),this._tickIntervalId!=null&&(clearInterval(this._tickIntervalId),this._tickIntervalId=void 0))}_tickIntervalId;tick=()=>{this.updateSendingCalls()};onJoinedRoom=e=>{this._sendingStreams.size>0&&(this.debug&&console.warn(`${e?.userId?`User ${e.userId}`:"You"} joined room`,e,this._sendingStreams.size),this.updateSendingCalls())};onLeftRoom=e=>{this.debug&&console.warn(`${e?.userId||"You"} left room`,e),this.stopCallsToUsersThatAreNotInTheRoomAnymore(),this.peer.closeAll()};onCallStreamReceived=e=>{this.debug&&console.log("Call with "+e.userId+" started"),this.dispatchEvent({type:"receive-stream",target:this,stream:e.stream,userId:e.userId}),this.debug&&this.debugLogCurrentState()};onCallEnded=e=>{this.debug&&console.log("Call with "+e.userId+" ended"),this.dispatchEvent(e),this.debug&&this.debugLogCurrentState()};onUserConnected=e=>{if(this.peer.id===e.guid){this.debug&&console.log("PEER USER CONNECTED",e.guid,e,this._sendingStreams.size);const t=this._sendingStreams.keys().next().value;if(!t)return;this.peer.makeCall(e.peerId,t)}else Ee&&console.log("Unknown user connected",e.guid,e.peerId)};onUserLeft=e=>{this.debug&&console.log("User left room: "+e.userId),this.stopCallsToUsersThatAreNotInTheRoomAnymore()};updateSendingCalls(){const e=this.context.connection.connectionId;for(const t of this._sendingStreams.keys()){const i=this._sendingStreams.get(t)||[];for(const n of this.context.connection.usersInRoom()){if(n===e)continue;const o=this.peer.getPeerIdFromUserId(n);if(i.find(a=>a.peerId===o&&a.direction==="outgoing"&&!a.isClosed&&a.stream?.active))Ee&&console.debug("Already have a call with user "+n+" / peer "+o);else{const a=this.peer.makeCall(o,t);a&&i.push(a)}}this._sendingStreams.set(t,i)}this.stopCallsToUsersThatAreNotInTheRoomAnymore()}stopCallsToUsersThatAreNotInTheRoomAnymore(){for(const e of this._sendingStreams.keys()){const t=this._sendingStreams.get(e);if(t)for(let i=t.length-1;i>=0;i--){const n=t[i];this.context.connection.userIsInRoom(n.userId)?Ee&&(this.context.connection.connectionId===n.userId?console.warn(`You are still in the room [${i}] ${n.userId}`):console.log(`User is still in room [${i}] ${n.userId}`)):(Ee&&console.log(`Remove call ${[i]} to user that is not in room anymore ${n.userId}`),n.close(),t.splice(i,1))}}this.peer.updateCalls(),this.debug&&this.debugLogCurrentState()}debugLogCurrentState(){console.warn(`You (${this.context.connection.connectionId}) are currently sending ${this._sendingStreams.size} and receiving ${this.peer.incomingCalls.length} calls (${this.peer.incomingCalls.map(e=>e.userId).join(", ")})`,this.peer.incomingCalls)}}function Un(s){if(s&&s instanceof MediaStream)for(const e of s.getTracks())e.stop()}var PO=Object.defineProperty,wg=(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&&PO(e,t,n),n};const OO="noVoip",MO=x("debugvoip");class wo extends R{autoConnect=!0;runInBackground=!0;createMenuButton=!0;debug=!1;_net;_menubutton;awake(){MO&&(this.debug=!0),this.debug&&(console.log("VOIP debugging: press 'v' to toggle mute or 'c' to toggle connect/disconnect"),window.addEventListener("keydown",async e=>{switch(e.key.toLowerCase()){case"v":console.log("MUTE?",!this.isMuted),this.setMuted(!this.isMuted);break;case"c":this.isSending?this.disconnect():this.connect();break}}),window.addEventListener("blur",()=>{console.log("VOIP: MUTE ON BLUR"),this.setMuted(!0)}),window.addEventListener("focus",()=>{console.log("VOIP: UNMUTE ON FOCUS"),this.setMuted(!1)}))}onEnable(){this._net||(this._net=Yc.create(this)),this.debug&&(this._net.debug=!0),this._net.addEventListener(Fn.StreamReceived,this.onReceiveStream),this._net.addEventListener(Fn.StreamEnded,this.onStreamEnded),this._net.enable(),this.autoConnect&&this.context.connection.isConnected&&this.connect(),this.context.connection.beginListen(K.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(K.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.addEventListener("visibilitychange",this.onVisibilityChanged)}onDisable(){this._net&&(this._net.stopSendingStream(this._outputStream),this._net.removeEventListener(Fn.StreamReceived,this.onReceiveStream),this._net.removeEventListener(Fn.StreamEnded,this.onStreamEnded),this._net?.disable()),this.context.connection.stopListen(K.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(K.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.removeEventListener("visibilitychange",this.onVisibilityChanged)}onDestroy(){this._menubutton?.remove(),this._menubutton=void 0}_allowSending=!0;_outputStream=null;get isSending(){return this._outputStream!=null&&this._outputStream.active}async connect(e){if(!this._net)return console.error("Cannot connect to voice chat - NetworkedStreams not initialized. Make sure the component is enabled before calling this method."),!1;if(this.context.connection.isConnected){if(!await exports.DeviceUtilities.microphonePermissionsGranted())return console.error("Cannot connect to voice chat - microphone permissions not granted"),this.updateButton(),!1}else return console.error("Cannot connect to voice chat - not connected to server"),this.updateButton(),!1;return this._allowSending=!0,this._net?.stopSendingStream(this._outputStream),Un(this._outputStream),this._outputStream=await this.getAudioStream(e),this._outputStream?(this.debug&&console.log("VOIP: Got audio stream"),this._net?.startSendingStream(this._outputStream),this.updateButton(),!0):(this.updateButton(),await exports.DeviceUtilities.microphonePermissionsGranted()?console.error("VOIP: Could not get audio stream - please make sure to connect an audio device and grant microphone permissions"):Uc("Microphone permissions not granted: Please grant microphone permissions to use voice chat"),(this.debug||A())&&console.log("VOIP: Failed to get audio stream"),!1)}disconnect(e){e?.remember&&(this._allowSending=!1),this._net?.stopSendingStream(this._outputStream),Un(this._outputStream),this._outputStream=null,this.updateButton()}setMuted(e){const t=this._outputStream?.getAudioTracks();if(t)for(const i of t)i.enabled=!e}get isMuted(){if(this._outputStream===null)return!1;const e=this._outputStream?.getAudioTracks();if(e){for(const t of e)if(!t.enabled)return!0}return!1}async updateButton(){if(this.createMenuButton){if(this._menubutton||(this._menubutton=document.createElement("button"),this._menubutton.addEventListener("click",()=>{this.isSending?this.disconnect({remember:!0}):this.connect(),exports.DeviceUtilities.microphonePermissionsGranted().then(e=>{e||fe("<strong>Microphone permissions not granted</strong>. Please allow your browser to use the microphone to be able to talk. Click on the button on the left side of your browser's address bar to allow microphone permissions.")})})),this._menubutton){this.context.menu.appendChild(this._menubutton),this.activeAndEnabled?this._menubutton.style.display="":this._menubutton.style.display="none",this._menubutton.title=this.isSending?"Click to disable your microphone":"Click to enable your microphone";let e=(this.isSending,""),t=this.isSending?"mic":"mic_off";await exports.DeviceUtilities.microphonePermissionsGranted()||(e="No Permission",t="mic_off",this._menubutton.title="Microphone permissions not granted. Please allow your browser to use the microphone to be able to talk. This can usually be done in the addressbar of the webpage."),this._menubutton.innerText=e,this._menubutton.prepend(vt(t)),this.context.connection.isConnected==!1?this._menubutton.setAttribute("disabled",""):this._menubutton.removeAttribute("disabled")}}else this.activeAndEnabled||this._menubutton?.remove()}getFrequency(e){return this.unsupported_getfrequency||(this.unsupported_getfrequency=!0,A()&&fe("VOIP: getFrequency is currently not supported"),console.warn("VOIP: getFrequency is currently not supported")),null}async getAudioStream(e){if(!navigator.mediaDevices.getUserMedia)return console.error("No getDisplayMedia support"),null;const t=async n=>await navigator.mediaDevices.getUserMedia({audio:n??!0,video:!1}).catch(o=>(console.warn("VOIP failed getting audio stream",o),null)),i=await t(e);if(!i)return null;if(exports.DeviceUtilities.isiOS()&&e?.deviceId===void 0){const o=(await navigator.mediaDevices.enumerateDevices()).find(r=>(r.kind==="audioinput"||r.kind==="audiooutput")&&!r.label.includes("iPhone"));if(o){const r=Object.assign({},e);return r.deviceId=o.deviceId,await t(r)}}return i}onJoinedRoom=async()=>{this.debug&&console.log("VOIP: Joined room"),await _s(300),this.autoConnect&&!this.isSending&&this._allowSending&&this.connect()};onLeftRoom=()=>{this.debug&&console.log("VOIP: Left room"),this.disconnect();for(const e of this._incomingStreams.values())Un(e.srcObject);this._incomingStreams.clear()};_incomingStreams=new Map;onReceiveStream=e=>{const t=e.target.userId,i=e.stream;let n=this._incomingStreams.get(t);n||(n=new Audio,this._incomingStreams.set(t,n)),n.srcObject=i,n.setAttribute("autoplay","true"),fn.registerWaitForInteraction(()=>{n?.play().catch(o=>{console.error("VOIP: Failed to play audio",o)})})};onStreamEnded=e=>{const t=this._incomingStreams.get(e.userId);Un(t?.srcObject),this._incomingStreams.delete(e.userId)};onEnabledChanged=()=>{for(const e of this._incomingStreams){const t=e[1];t.muted=!this.enabled}};onVisibilityChanged=()=>{if(this.runInBackground)return;const t=!(document.visibilityState==="visible");this.setMuted(t);for(const i of this._incomingStreams){const n=i[1];n.muted=t}}}wg([f()],wo.prototype,"autoConnect");wg([f()],wo.prototype,"runInBackground");wg([f()],wo.prototype,"createMenuButton");var kO=Object.defineProperty,fw=(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};const RO=x("debugmouth");class Kc extends R{idle=[];talking=[];marker=null;voip=null;lastMouthChangeTime=0;mouthChangeLength=0;awake(){setTimeout(()=>{this.voip=S.findObjectOfType(wo,this.context),this.marker||(this.marker=S.getComponentInParent(this.gameObject,Oe))},3e3)}update(){if(!this.voip||this.context.time.frameCount%10!==0)return;let e=this.marker?.connectionId??null;if(!e){RO&&(e=null);return}const t=this.voip.getFrequency(e)??0;this.updateLips(t)}updateLips(e){if(this.context.time.time-this.lastMouthChangeTime>this.mouthChangeLength){if(this.mouthChangeLength=.05+Math.random()*.1,this.talking&&this.talking.length>0&&e>30){this.lastMouthChangeTime=this.context.time.time;const t=Math.floor(Math.random()*this.talking.length);this.setMouthShapeActive(this.talking,t)}else if(this.idle.length>0&&this.context.time.time-this.lastMouthChangeTime>.5){this.lastMouthChangeTime=this.context.time.time;const t=Math.floor(Math.random()*this.idle.length);this.setMouthShapeActive(this.idle,t)}}}setMouthShapeActive(e,t){if(e){e!=this.idle?this.idle.map(i=>i.visible=!1):this.talking.map(i=>i.visible=!1);for(let i=0;i<e.length;i++){const n=e[i];n&&(n.visible=i===t)}}}}fw([f(c.Object3D)],Kc.prototype,"idle");fw([f(c.Object3D)],Kc.prototype,"talking");class xg extends R{voip=null;marker=null;_startPosition=null;awake(){this.voip=S.findObjectOfType(wo,this.context),this.marker=S.getComponentInParent(this.gameObject,Oe)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!==0)return;const e=this.marker.connectionId,t=this.voip.getFrequency(e);if(t==null)return;this._startPosition||(this._startPosition=this.gameObject.position.clone());const i=t/100;this.gameObject.position.y=this._startPosition.y+i*.07}}var EO=Object.defineProperty,TO=(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&&EO(e,t,n),n};const oa=x("debugxrflags"),pw=x("disablexrflags");pw&&console.warn("XRFlags are disabled");var Ln=(s=>(s[s.Never=0]="Never",s[s.Browser=1]="Browser",s[s.AR=2]="AR",s[s.VR=4]="VR",s[s.FirstPerson=8]="FirstPerson",s[s.ThirdPerson=16]="ThirdPerson",s[s.All=4294967295]="All",s))(Ln||{});class Wt{static Global=new Wt;Mask=17;Has(e){return(this.Mask&e)!==0}Set(e){oa&&console.warn("Set XR flag state to",e),this.Mask=e,ji.Apply()}Enable(e){this.Mask|=e,ji.Apply()}Disable(e){this.Mask&=~e,ji.Apply()}Toggle(e){this.Mask^=e,ji.Apply()}EnableAll(){this.Mask=-1,ji.Apply()}DisableAll(){this.Mask=0,ji.Apply()}}const mw=class ts extends R{static registry=[];static Apply(){for(const e of this.registry)e.UpdateVisible(Wt.Global)}static firstApply;static buffer=new Wt;visibleIn;awake(){ts.registry.push(this)}onEnable(){ts.firstApply?this.UpdateVisible(Wt.Global):(ts.firstApply=!0,ts.Apply())}onDestroy(){const e=ts.registry.indexOf(this);e>=0&&ts.registry.splice(e,1)}get isOn(){return this.gameObject.visible}UpdateVisible(e=null){if(pw)return;let t;const i=e;if(i&&typeof i=="number"&&(console.assert(typeof i=="number","XRFlag.UpdateVisible: state must be a number",i),oa&&console.log(i),ts.buffer.Mask=i,e=ts.buffer),e instanceof Wt?(oa&&console.warn(this.name,"use passed in mask",e.Mask,this.visibleIn),t=e.Has(this.visibleIn)):(oa&&console.log(this.name,"use global mask"),Wt.Global.Has(this.visibleIn)),t!==void 0)if(t)oa&&console.log(this.name,"is visible",this.gameObject.uuid),S.setActive(this.gameObject,!0);else{if(oa&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}};TO([f()],mw.prototype,"visibleIn");let ji=mw;var AO=Object.defineProperty,Ru=(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&&AO(e,t,n),n};class Cr extends R{eyes=[];lastBlinkTime=0;blinkLength=0;eyesOpen=!0;state=null;awake(){this.state=S.getComponentInParent(this.gameObject,ji)}update(){if(!this.gameObject||!this.gameObject.visible||!this.eyes||!Array.isArray(this.eyes)||this.eyes.length===0)return;if(this.context.time.time-this.lastBlinkTime>this.blinkLength){if(this.lastBlinkTime=this.context.time.time,this.state&&!this.state.isOn||!this.activeAndEnabled)return;if(this.eyesOpen=!this.eyesOpen,this.blinkLength=Math.random(),this.eyesOpen?(this.blinkLength*=3,this.blinkLength+=.5,Math.random()<.1&&(this.blinkLength=.1+Math.random()*.2)):(this.blinkLength*=Math.random()*.2,this.blinkLength+=.1),Math.random()<.1&&(this.blinkLength*=3),this.blinkLength=Math.max(.2,this.blinkLength),this.blinkLength=Math.min(3,this.blinkLength),this.eyes)for(const t of this.eyes)t&&(t.visible=this.eyesOpen)}}}Ru([f(c.Object3D)],Cr.prototype,"eyes");Ru([f()],Cr.prototype,"lastBlinkTime");Ru([f()],Cr.prototype,"blinkLength");Ru([f()],Cr.prototype,"eyesOpen");var DO=Object.defineProperty,Sg=(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&&DO(e,t,n),n};const Eu=class gw extends R{head=null;eyes=null;target=null;brain=null;awake(){this.brain||(this.brain=S.getComponentInParent(this.gameObject,Pc)),this.brain||(this.brain=S.addComponent(this.gameObject,Pc)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}vec=new c.Vector3;static forward=new c.Vector3(0,0,1);currentTargetPoint=new c.Vector3;update(){const e=this.target;if(e&&this.head){const t=this.eyes;if(t){const i=Y(e);this.currentTargetPoint.lerp(i,this.context.time.deltaTime/.1);const n=Y(this.head),o=this.vec.copy(this.currentTargetPoint).sub(n).normalize();if(o.length()<.1)return;const r=gw.forward;if(r.set(0,0,1),r.applyQuaternion(pe(this.head)),r.dot(o)>.45)for(let l=0;l<t.length;l++)t[l].lookAt(this.currentTargetPoint)}}}};Sg([f(c.Object3D)],Eu.prototype,"head");Sg([f(c.Object3D)],Eu.prototype,"eyes");Sg([f(c.Object3D)],Eu.prototype,"target");let Cg=Eu;var LO=Object.defineProperty,Pg=(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&&LO(e,t,n),n};class Ha extends R{length=1;depthTest=!0;isGizmo=!1;_axes=null;onEnable(){if(this.isGizmo&&!Nc)return;this._axes||(this._axes=new c.AxesHelper(this.length)),this._axes.layers.disableAll(),this._axes.layers.set(this.layer),this.gameObject.add(this._axes);const e=this._axes.material;e&&e.depthTest!==void 0&&(e.depthTest=this.depthTest)}onDisable(){this._axes&&this.gameObject.remove(this._axes)}}Pg([f()],Ha.prototype,"length");Pg([f()],Ha.prototype,"depthTest");Pg([f()],Ha.prototype,"isGizmo");class Og extends R{from;to;hint;desiredDistance=1;onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;const e=Y(this.to).clone(),t=Y(this.from).clone(),i=e.distanceTo(t),n=e.clone();n.sub(t);const o=t.clone();o.add(e),o.multiplyScalar(.5);const r=Y(this.hint).clone();r.sub(o);const a=new c.Vector3;a.crossVectors(r,n),a.crossVectors(n,a),a.normalize();const l=i*.5,h=Math.max(this.desiredDistance,l),d=Math.sqrt(h*h-l*l),u=a.clone();u.multiplyScalar(d),u.add(o),at(this.gameObject,u);const p=o.clone();p.sub(a),this.gameObject.lookAt(p)}}const IO=x("gizmos"),jO=x("debugboxhelper");class _t extends R{box=null;static testBox=new c.Box3;_lastMatrixUpdateFrame=-1;static _position=new c.Vector3;static _size=new c.Vector3(.01,.01,.01);static _emptyObjectSize=new c.Vector3(.01,.01,.01);isInBox(e){if(!e)return;if(this.box||(this.box=new c.Box3),ri([e],void 0,void 0,_t.testBox),_t.testBox.isEmpty()){const i=Y(e,_t._position);_t.testBox.setFromCenterAndSize(i,_t._emptyObjectSize)}this.updateBox();const t=this.box?.intersectsBox(_t.testBox);return t&&jO&&B.DrawWireBox3(_t.testBox,16711680,5),t}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){if(this.box||(this.box=new c.Box3),e||this.context.time.frameCount!=this._lastMatrixUpdateFrame){const t=this._lastMatrixUpdateFrame<0;this._lastMatrixUpdateFrame=this.context.time.frameCount;const i=t,n=Y(this.gameObject,_t._position,i),o=je(this.gameObject,_t._size);this.box.setFromCenterAndSize(n,o)}return this.box}_helper=null;_color=null;awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,t=!1){if(!(!IO&&!t)){if(this._helper){e&&this._color?.set(e),this.gameObject.add(this._helper);return}this._helper=Zm(e),this.gameObject.add(this._helper)}}}var BO=Object.defineProperty,li=(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&&BO(e,t,n),n};class Xi extends R{get isCollider(){return!0}attachedRigidbody=null;isTrigger=!1;sharedMaterial;membership=[0];filter;awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent($e))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent($e))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent($e))}onDisable(){this.context.physics.engine?.removeBody(this)}get body(){return this.context.physics.engine?.getBody(this)}updateProperties=()=>{this.context.physics.engine?.updateProperties(this)};updatePhysicsMaterial(){this.context.physics.engine?.updatePhysicsMaterial(this)}}li([f($e)],Xi.prototype,"attachedRigidbody");li([f()],Xi.prototype,"isTrigger");li([f()],Xi.prototype,"sharedMaterial");li([f()],Xi.prototype,"membership");li([f()],Xi.prototype,"filter");class qa extends Xi{radius=.5;center=new c.Vector3(0,0,0);onEnable(){super.onEnable(),this.context.physics.engine?.addSphereCollider(this),cu(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),Rm(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}}li([St(),f()],qa.prototype,"radius");li([f(c.Vector3)],qa.prototype,"center");const Mg=class yw extends Xi{static add(e,t){const i=cn(e,yw);return i.autoFit(),t?.rigidbody===!0&&cn(e,$e,{isKinematic:!1}),i}size=new c.Vector3(1,1,1);center=new c.Vector3(0,0,0);onEnable(){super.onEnable(),this.context.physics.engine?.addBoxCollider(this,this.size),cu(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),Rm(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}autoFit(e){const t=this.gameObject,i=t.position.clone(),n=t.quaternion.clone(),o=t.scale.clone(),r=t.parent;t.position.set(0,0,0),t.quaternion.set(0,0,0,1),t.scale.set(1,1,1),t.parent=null,t.updateMatrix();const a=ri([t]);t.position.copy(i),t.quaternion.copy(n),t.scale.copy(o),t.parent=r,e?.debug===!0&&B.DrawWireBox3(a,16768256,20),this.size=a.getSize(new c.Vector3)||new c.Vector3(1,1,1),this.center=a.getCenter(new c.Vector3)||new c.Vector3(0,0,0),this.size.length()<=0&&this.size.set(.01,.01,.01)}};li([St(),f(c.Vector3)],Mg.prototype,"size");li([f(c.Vector3)],Mg.prototype,"center");let Tu=Mg;class xo extends Xi{sharedMesh;convex=!1;onEnable(){if(super.onEnable(),!this.context.physics.engine)return;this.sharedMesh?.isMesh||(this.gameObject instanceof c.Mesh||this.gameObject instanceof c.Group)&&(this.sharedMesh=this.gameObject);const e=0;if(this.sharedMesh?.isMesh)this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex),re.NEEDLE_progressive.assignMeshLOD(this.sharedMesh,e).then(t=>{t&&this.activeAndEnabled&&this.context.physics.engine&&this.sharedMesh&&(this.context.physics.engine.removeBody(this),this.sharedMesh.geometry=t,this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex))});else{const t=this.sharedMesh;if(t?.isGroup){console.warn(`MeshCollider mesh is a group "${this.sharedMesh?.name||this.gameObject.name}", adding all children as colliders. This is currently not fully supported (colliders can not be removed from world again)`,this);const i=new Array;for(const n in t.children){const o=t.children[n];o.isMesh&&(this.context.physics.engine.addMeshCollider(this,o,this.convex),i.push(re.NEEDLE_progressive.assignMeshLOD(o,e)))}Promise.all(i).then(n=>{if(n.some(r=>r)==!1)return;this.context.physics.engine?.removeBody(this);const o=new c.Mesh;for(const r of n)r&&this.activeAndEnabled&&(o.geometry=r,this.context.physics.engine?.addMeshCollider(this,o,this.convex))})}else(A()||x("showcolliders"))&&console.warn(`[MeshCollider] A MeshCollider mesh is assigned to an unknown object on "${this.gameObject.name}", but it's neither a Mesh nor a Group. Please double check that you attached the collider component to the right object and report a bug otherwise!`,this)}}}li([f(c.Mesh)],xo.prototype,"sharedMesh");li([f()],xo.prototype,"convex");class bs extends Xi{center=new c.Vector3(0,0,0);radius=.5;height=2;onEnable(){super.onEnable(),this.context.physics.engine?.addCapsuleCollider(this,this.height,this.radius)}}li([f(c.Vector3)],bs.prototype,"center");li([f()],bs.prototype,"radius");li([f()],bs.prototype,"height");var FO=Object.defineProperty,Ss=(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&&FO(e,t,n),n};const sb=x("debugcharactercontroller");class Pr extends R{center=new c.Vector3(0,0,0);radius=.5;height=2;_rigidbody=null;get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent($e),this._rigidbody||(this._rigidbody=this.gameObject.addComponent($e)),this.rigidbody)}_activeGroundCollisions;awake(){this._activeGroundCollisions=new Set}onEnable(){const e=this.rigidbody;let t=this.gameObject.getComponent(bs);t||(t=this.gameObject.addComponent(bs)),t.center.copy(this.center),t.radius=this.radius,t.height=this.height;const i=new c.Vector3(0,0,1),n=new c.Vector3(1,0,0),o=new c.Vector3(0,1,0),r=this.gameObject.getWorldDirection(new c.Vector3);r.y=0;const a=n.dot(r)<0?-1:1,l=i.angleTo(r)*a;this.gameObject.setRotationFromAxisAngle(o,l),e.lockRotationX=!0,e.lockRotationY=!0,e.lockRotationZ=!0}move(e){this.gameObject.position.add(e)}onCollisionEnter(e){(e.contacts.length==0||e.contacts.some(t=>t.normal.y>.2))&&(this._activeGroundCollisions.add(e),sb&&console.log(`Collision(${this._activeGroundCollisions.size}): ${e.contacts.map(t=>t.normal.y.toFixed(2)).join(", ")} - ${this.isGrounded}`))}onCollisionExit(e){this._activeGroundCollisions.delete(e),sb&&console.log(`Collision(${this._activeGroundCollisions.size}) - ${this.isGrounded}`)}get isGrounded(){return this._activeGroundCollisions.size>0}_contactVelocity=new c.Vector3;get contactVelocity(){this._contactVelocity.set(0,0,0);for(const e of this._activeGroundCollisions){const t=this.context.physics.engine?.getLinearVelocity(e.collider);t&&(this._contactVelocity.x+=t.x,this._contactVelocity.y+=t.y,this._contactVelocity.z+=t.z)}return this._contactVelocity}}Ss([f(c.Vector3)],Pr.prototype,"center");Ss([f()],Pr.prototype,"radius");Ss([f()],Pr.prototype,"height");class Cs extends R{controller;movementSpeed=2;rotationSpeed=2;jumpForce=1;doubleJumpForce=2;animator;lookForward=!0;awake(){this._currentRotation=new c.Quaternion}update(){const e=this.context.input;e.isKeyPressed("KeyW")?this.moveInput.y+=1:e.isKeyPressed("KeyS")&&(this.moveInput.y-=1),e.isKeyPressed("KeyD")?this.lookInput.x+=1:e.isKeyPressed("KeyA")&&(this.lookInput.x-=1),this.jumpInput||=e.isKeyDown("Space")}move(e){this.moveInput.add(e)}look(e){this.lookInput.add(e)}jump(){this.jumpInput=!0}lookInput=new c.Vector2(0,0);moveInput=new c.Vector2(0,0);jumpInput=!1;onBeforeRender(){this.handleInput(this.moveInput,this.lookInput,this.jumpInput),this.lookInput.set(0,0),this.moveInput.set(0,0),this.jumpInput=!1}_currentSpeed=new c.Vector3(0,0,0);_currentAngularSpeed=new c.Vector3(0,0,0);_temp=new c.Vector3(0,0,0);_jumpCount=0;_currentRotation;handleInput(e,t,i){if(this.controller?.isGrounded&&(this._jumpCount=0,this.doubleJumpForce>0&&this.animator?.setBool("doubleJump",!1)),this._currentSpeed.z+=e.y*this.movementSpeed*this.context.time.deltaTime,this.animator?.setBool("running",e.length()>.01),this.animator?.setBool("jumping",this.controller?.isGrounded===!0&&i),this._temp.copy(this._currentSpeed),this._temp.applyQuaternion(this.gameObject.quaternion),this.controller?this.controller.move(this._temp):this.gameObject.position.add(this._temp),this._currentAngularSpeed.y+=I.toRadians(-t.x*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){const n=this.context.mainCameraComponent.forward;n.y=0,n.normalize(),this._currentRotation.setFromUnitVectors(new c.Vector3(0,0,1),n),this.gameObject.quaternion.slerp(this._currentRotation,this.context.time.deltaTime*10)}if(this.gameObject.rotateY(this._currentAngularSpeed.y),this._currentSpeed.multiplyScalar(1-this.context.time.deltaTime*10),this._currentAngularSpeed.y*=1-this.context.time.deltaTime*10,this.controller&&i&&this.jumpForce>0){let n=this.controller?.isGrounded;if(this.doubleJumpForce>0&&!this.controller?.isGrounded&&this._jumpCount===1&&(n=!0,this.animator?.setBool("doubleJump",!0)),n){this._jumpCount+=1;const o=this.controller.rigidbody,r=this._jumpCount===2?this.doubleJumpForce:this.jumpForce;o.applyImpulse(new c.Vector3(0,1,0).multiplyScalar(r))}}if(this.controller){const n=this.controller?.rigidbody.getVelocity().y;if(n<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new c.Ray),this._raycastOptions.ray.origin.copy(Y(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);const o=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);const r=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(o),(r.length&&r[0].distance>2||n<-10)&&this.animator?.setBool("falling",!0)}else this.animator?.setBool("falling",!1)}}_raycastOptions=new vo}Ss([f(Pr)],Cs.prototype,"controller");Ss([f()],Cs.prototype,"movementSpeed");Ss([f()],Cs.prototype,"rotationSpeed");Ss([f()],Cs.prototype,"jumpForce");Ss([f()],Cs.prototype,"doubleJumpForce");Ss([f(lt)],Cs.prototype,"animator");var UO=Object.defineProperty,Xa=(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&&UO(e,t,n),n};const xl=x("debugcontactshadows");Cu(s=>{const e=s.domElement.getAttribute("contactshadows")||s.domElement.getAttribute("contact-shadows");if(e!=null&&e!="0"&&e!="false"){console.debug("Auto-creating ContactShadows because of `contactshadows` attribute");const t=Zc.auto(s),i=parseFloat(e);isNaN(i)||(t.opacity=i,t.darkness=i)}});const Or=class $l extends R{static _instances=new Map;static auto(e,t){if(e||(e=U.Current),!e)throw new Error("No context provided and no current context set.");let i=this._instances.get(e);if(!i||i.destroyed){const n=new c.Object3D;n.name="ContactShadows",i=cn(n,$l,{autoFit:!1,occludeBelowGround:!1}),this._instances.set(e,i)}return e.scene.add(i.gameObject),i.fitShadows(t),i}autoFit=!1;darkness=.5;opacity=.5;blur=4;occludeBelowGround=!1;backfaceShadows=!0;minSize;manualUpdate=!1;set needsUpdate(e){this._needsUpdate=e}get needsUpdate(){return this._needsUpdate}_needsUpdate=!1;shadowsRoot=new c.Object3D;shadowCamera;shadowGroup=new c.Group;renderTarget;renderTargetBlur;plane;occluderMesh;blurPlane;planeMaterial;depthMaterial;horizontalBlurMaterial;verticalBlurMaterial;textureSize=512;fitShadows(e={}){xl&&console.warn("Fitting shadows to scene"),Ld(this.shadowsRoot,!1);const t=e.object||this.context.scene,i=ri(t,[this.shadowsRoot]),n=Math.max(1,this.blur/32),o=i.max.x-i.min.x,r=i.max.z-i.min.z;i.expandByVector(new c.Vector3(n*o,0,n*r)),xl&&B.DrawWireBox3(i,16776960,60),this.gameObject.parent&&i.applyMatrix4(this.gameObject.parent.matrixWorld.clone().invert());const a=i.min,l=Math.max(1e-5,(i.max.y-a.y)*.002);i.max.y+=l,this.shadowsRoot.position.set((a.x+i.max.x)/2,a.y-l,(a.z+i.max.z)/2),this.shadowsRoot.scale.set(i.max.x-a.x,i.max.y-a.y,i.max.z-a.z),e.positionOffset&&(e.positionOffset.x!==void 0&&(this.shadowsRoot.position.x+=e.positionOffset.x),e.positionOffset.y!==void 0&&(this.shadowsRoot.position.y+=e.positionOffset.y),e.positionOffset.z!==void 0&&(this.shadowsRoot.position.z+=e.positionOffset.z)),e.scaleFactor&&(e.scaleFactor.x!==void 0&&(this.shadowsRoot.scale.x*=e.scaleFactor.x),e.scaleFactor.y!==void 0&&(this.shadowsRoot.scale.y*=e.scaleFactor.y),e.scaleFactor.z!==void 0&&(this.shadowsRoot.scale.z*=e.scaleFactor.z)),this.applyMinSize(),this.shadowsRoot.matrixWorldNeedsUpdate=!0,xl&&console.log("Fitted shadows to scene",this.shadowsRoot.scale.clone())}awake(){$l._instances.set(this.context,this),this.shadowsRoot.hideFlags=du.DontExport,Ld(this.shadowsRoot,!1)}start(){xl&&console.log("Create ContactShadows on "+this.gameObject.name,this),this.gameObject.add(this.shadowsRoot),this.shadowsRoot.add(this.shadowGroup),this.renderTarget=new c.WebGLRenderTarget(this.textureSize,this.textureSize),this.renderTarget.texture.generateMipmaps=!1,this.renderTargetBlur=new c.WebGLRenderTarget(this.textureSize,this.textureSize),this.renderTargetBlur.texture.generateMipmaps=!1;const e=new c.PlaneGeometry(1,1).rotateX(Math.PI/2);this.gameObject instanceof c.Mesh&&(console.warn("ContactShadows can not be added to a Mesh. Please add it to a Group or an empty Object"),ls(this.gameObject,!1));const t=this.planeMaterial=new c.MeshBasicMaterial({map:this.renderTarget.texture,opacity:this.opacity,color:0,transparent:!0,depthWrite:!1,side:c.FrontSide});this.plane=new c.Mesh(e,t),this.plane.scale.y=-1,this.plane.layers.set(2),this.shadowsRoot.add(this.plane),this.plane&&(this.plane.renderOrder=1),this.occluderMesh=new c.Mesh(this.plane.geometry,new c.MeshBasicMaterial({depthWrite:!0,stencilWrite:!0,colorWrite:!1,side:c.BackSide})).translateY(-1e-4),this.occluderMesh.renderOrder=-100,this.occluderMesh.layers.set(2),this.shadowsRoot.add(this.occluderMesh),this.blurPlane=new c.Mesh(e),this.blurPlane.visible=!1,this.shadowGroup.add(this.blurPlane);const i=0,n=1;this.shadowCamera=new c.OrthographicCamera(-1/2,1/2,1/2,-1/2,i,n),this.shadowCamera.layers.enableAll(),this.shadowCamera.rotation.x=Math.PI/2,this.shadowCamera.matrixWorldAutoUpdate=!1,this.shadowGroup.add(this.shadowCamera),this.shadowCamera.updateMatrix(),this.depthMaterial=new c.MeshDepthMaterial,this.depthMaterial.userData.darkness={value:this.darkness},this.depthMaterial.blending=c.CustomBlending,this.depthMaterial.blendEquation=c.MaxEquation,this.depthMaterial.onBeforeCompile=o=>{this.depthMaterial&&(o.uniforms.darkness=this.depthMaterial.userData.darkness,o.fragmentShader=`
|
|
980
|
-
uniform float darkness;
|
|
981
|
-
${o.fragmentShader.replace("gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );","gl_FragColor = vec4( vec3( 1.0 ), ( 1.0 - fragCoordZ ) * darkness * opacity * (gl_FrontFacing ? 1.0 : 0.66) );")}
|
|
982
|
-
`)},this.depthMaterial.depthTest=!1,this.depthMaterial.depthWrite=!1,this.horizontalBlurMaterial=new c.ShaderMaterial(X.HorizontalBlurShader),this.horizontalBlurMaterial.depthTest=!1,this.verticalBlurMaterial=new c.ShaderMaterial(X.VerticalBlurShader),this.verticalBlurMaterial.depthTest=!1,this.shadowGroup.visible=!1,this.autoFit?this.fitShadows():this.applyMinSize()}onEnable(){this._needsUpdate=!0}onDestroy(){$l._instances.get(this.context)===this&&$l._instances.delete(this.context),this.renderTarget?.dispose(),this.renderTargetBlur?.dispose(),this.depthMaterial?.dispose(),this.horizontalBlurMaterial?.dispose(),this.verticalBlurMaterial?.dispose(),this.blurPlane?.geometry.dispose(),this.plane?.geometry.dispose(),this.occluderMesh?.geometry.dispose()}onBeforeRender(e){if(this.manualUpdate&&!this._needsUpdate)return;if(this._needsUpdate=!1,!this.renderTarget||!this.renderTargetBlur||!this.depthMaterial||!this.shadowCamera||!this.blurPlane||!this.shadowGroup||!this.plane||!this.horizontalBlurMaterial||!this.verticalBlurMaterial||!this.planeMaterial){xl&&console.error("ContactShadows: not initialized yet");return}this.depthMaterial.userData.darkness.value=this.darkness,this.planeMaterial.opacity=this.opacity;const t=this.context.scene,i=this.context.renderer,n=i.getRenderTarget();this.shadowGroup.visible=!0,this.occluderMesh&&(this.occluderMesh.visible=!1);const o=this.plane.visible;this.plane.visible=!1,this.gameObject instanceof c.Mesh&&ls(this.gameObject,!1);const r=t.background;t.background=null,t.overrideMaterial=this.depthMaterial,this.backfaceShadows?this.depthMaterial.side=c.DoubleSide:this.depthMaterial.side=c.FrontSide;const a=i.getClearAlpha();i.setClearAlpha(0);const l=i.xr.enabled;i.xr.enabled=!1;const h=this.context.scene.matrixWorldAutoUpdate;this.context.scene.matrixWorldAutoUpdate=!1;const d=i.renderLists.get(t,0),u=d.transparent;ob.length=0,d.transparent=ob,Xf.length=0;for(const m of d.opaque){if(!m.object.visible)continue;const y=m.material;let _=m.material.colorWrite==!1||y.wireframe===!0||wv(m.object)===!1;!_&&m.material.isLineMaterial&&(_=!0),!_&&m.material.isPointsMaterial&&(_=!0),_&&(Xf.push(m.object),m.object["needle:visible"]=m.object.visible,m.object.visible=!1)}this.shadowCamera.parent?this.shadowCamera.matrixWorld.multiplyMatrices(this.shadowCamera.parent.matrixWorld,this.shadowCamera.matrix):this.shadowCamera.matrixWorld.copy(this.shadowCamera.matrix),this.shadowCamera.matrixWorldInverse.copy(this.shadowCamera.matrixWorld).invert(),i.setRenderTarget(this.renderTarget),i.clear(),i.render(t,this.shadowCamera),d.transparent=u;for(const m of Xf)m["needle:visible"]!=null&&(m.visible=m["needle:visible"]);t.overrideMaterial=null;const p=Math.max(this.blur,.05);this.blurShadow(p*2),this.blurShadow(p*.5),this.shadowGroup.visible=!1,this.occluderMesh&&(this.occluderMesh.visible=this.occludeBelowGround),this.plane.visible=o,i.setRenderTarget(n),i.setClearAlpha(a),t.background=r,i.xr.enabled=l,this.context.scene.matrixWorldAutoUpdate=h}blurShadow(e){if(!this.blurPlane||!this.shadowCamera||!this.renderTarget||!this.renderTargetBlur||!this.horizontalBlurMaterial||!this.verticalBlurMaterial)return;this.blurPlane.visible=!0;const t=this.shadowsRoot.worldScale,i=(t.x+t.z)/2,n=t.z/i,o=t.x/i;this.blurPlane.material=this.horizontalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTarget.texture,this.horizontalBlurMaterial.uniforms.h.value=e*1/this.textureSize*n;const r=this.context.renderer,a=r.getRenderTarget();r.setRenderTarget(this.renderTargetBlur),r.render(this.blurPlane,this.shadowCamera),this.blurPlane.material=this.verticalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTargetBlur.texture,this.verticalBlurMaterial.uniforms.v.value=e*1/this.textureSize*o,r.setRenderTarget(this.renderTarget),r.render(this.blurPlane,this.shadowCamera),this.blurPlane.visible=!1,r.setRenderTarget(a)}applyMinSize(){this.minSize&&this.shadowsRoot.scale.set(Math.max(this.minSize.x||0,this.shadowsRoot.scale.x),Math.max(this.minSize.y||0,this.shadowsRoot.scale.y),Math.max(this.minSize.z||0,this.shadowsRoot.scale.z))}};Xa([f()],Or.prototype,"autoFit");Xa([f()],Or.prototype,"darkness");Xa([f()],Or.prototype,"opacity");Xa([f()],Or.prototype,"blur");Xa([f()],Or.prototype,"occludeBelowGround");Xa([f()],Or.prototype,"backfaceShadows");let Zc=Or;const ob=[],Xf=new Array,zO=x("logstats");class kg extends R{onEnable(){console.log(this),zO&&this.startCoroutine(this.run(),ge.OnAfterRender)}*run(){for(;this.enabled;){const e=this.context.renderer.info;console.log(e.memory,e.render,e.programs),yield}}}class Jc extends R{isUsed=!0;usedBy=null}class Rg extends R{}const rb=x("debugdeletable");class ao extends _t{static _instances=[];onEnable(){ao._instances.push(this)}onDisable(){const e=ao._instances.indexOf(this);e>=0&&ao._instances.splice(e,1)}}class Eg extends R{update(){for(const e of ao._instances){const t=this.gameObject;if(e.isInBox(t)===!0){const n=S.getComponentInParent(this.gameObject,Jc);if(n)rb&&console.warn("DeleteBox: Not deleting object with usage marker",this.guid,n);else{if(rb)try{if(e.box){const o=e.box,r=_t.testBox;B.DrawWireBox3(o,16711680,5),B.DrawWireBox3(r,255,5),console.log("DeleteBox: Destroying",this.gameObject,{deleteBoxArea:o,deletedObjectArea:r})}else console.log("DeleteBox: Destroying",this.gameObject)}catch{}zc(this.gameObject,this.context.connection)}}}}}var NO=Object.defineProperty,VO=(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&&NO(e,t,n),n};class Au extends R{visibleOn;onEnable(){this.apply()}apply(){this.test()||S.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:exports.DeviceUtilities.isMobileDevice()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}}VO([f()],Au.prototype,"visibleOn");var $O=Object.defineProperty,Mr=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&$O(e,t,n),n};const zn=x("debugdrag"),Qf=[];var Tg=(s=>(s[s.XZPlane=0]="XZPlane",s[s.Attached=1]="Attached",s[s.HitNormal=2]="HitNormal",s[s.DynamicViewAngle=3]="DynamicViewAngle",s[s.SnapToSurfaces=4]="SnapToSurfaces",s[s.None=5]="None",s))(Tg||{});const So=class Ai extends R{static get HasAnySelected(){return this._active>0}static _active=0;static get CurrentlySelected(){Qf.length=0;for(const e of this._instances)e._isDragging&&Qf.push(e);return Qf}static _instances=[];dragMode=3;snapGridResolution=0;keepRotation=!0;xrDragMode=1;xrKeepRotation=!1;xrDistanceDragFactor=1;showGizmo=!1;get draggedObject(){return this._targetObject}setTargetObject(e){this._targetObject=e;for(const i of this._dragHandlers.values())i.setTargetObject(e);const t="_rigidbody-was-kinematic";this._rigidbody?.[t]===!1&&(this._rigidbody.isKinematic=!1,this._rigidbody[t]=void 0),this._rigidbody=null,e&&(this._rigidbody=S.getComponentInChildren(e,$e),this._rigidbody?.isKinematic===!1&&(this._rigidbody.isKinematic=!0,this._rigidbody[t]=!1))}_rigidbody=null;_targetObject=null;_dragHelper=null;static lastHovered;_draggingRigidbodies=[];_potentialDragStartEvt=null;_dragHandlers=new Map;_totalMovement=new c.Vector3;_marker=null;_isDragging=!1;_didDrag=!1;awake(){this._potentialDragStartEvt=null,this._dragHandlers=new Map,this._totalMovement=new c.Vector3,this._marker=null,this._isDragging=!1,this._didDrag=!1,this._dragHelper=null,this._draggingRigidbodies=[]}start(){this.gameObject.getComponentInParent($i)||this.gameObject.addComponent($i)}onEnable(){Ai._instances.push(this),this.context.accessibility.updateElement(this,{role:"button",label:"Drag "+(this.gameObject.name||"object"),hidden:!1})}onDisable(){this.context.accessibility.updateElement(this,{hidden:!0}),Ai._instances=Ai._instances.filter(e=>e!==this)}onDestroy(){this.context.accessibility.removeElement(this)}allowEdit(e=null){return this.context.connection.allowEditing}onPointerEnter(e){if(!this.allowEdit(this.gameObject)||e.mode!=="screen"||(e.event.mode==="tracked-pointer"||e.event.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)return;const n=S.getComponentInParent(e.object,Ai);!n||n!==this||(Ai.lastHovered=e.object,this.context.domElement.style.cursor="pointer",this.context.accessibility.hover(this,`Draggable ${e.object?.name}`))}onPointerMove(e){(this._isDragging||this._potentialDragStartEvt!==null)&&e.use()}onPointerExit(e){this.allowEdit(this.gameObject)&&e.mode==="screen"&&Ai.lastHovered===e.object&&(this.context.domElement.style.cursor="auto")}onPointerDown(e){if(!(!this.allowEdit(this.gameObject)||e.used||(e.mode==="tracked-pointer"||e.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)&&(Ai.lastHovered=e.object,e.button===0)){this._dragHandlers.size===0&&(this._didDrag=!1,this._totalMovement.set(0,0,0),this._potentialDragStartEvt=e),this._targetObject||this.setTargetObject(this.gameObject),Ai._active+=1;const n=new Yf(this,this._targetObject);if(this._dragHandlers.set(e.event.space,n),n.onDragStart(e),this._dragHandlers.size===2){const o=this._dragHandlers.values(),r=o.next().value,a=o.next().value;if(r instanceof Yf&&a instanceof Yf){const l=new WO(this,this._targetObject,r,a);this._dragHandlers.set(this.gameObject,l),l.onDragStart(e)}else console.error("Attempting to construct a MultiTouchDragHandler with invalid DragPointerHandlers. This is likely a bug.",{a:r,b:a})}e.use(),this.context.accessibility.updateElement(this,{role:"button",label:"Dragging "+(this.gameObject.name||"object"),hidden:!1,busy:!0}),this.context.accessibility.focus(this)}}onPointerUp(e){if(zn&&B.DrawLabel(e.point??this.gameObject.worldPosition,"POINTERUP:"+e.pointerId+", "+e.button,.03,3),!this.allowEdit(this.gameObject)||e.button!==0)return;this._potentialDragStartEvt=null;const t=this._dragHandlers.get(e.event.space),i=this._dragHandlers.get(this.gameObject);i&&(i.handlerA===t||i.handlerB===t)&&(this._dragHandlers.delete(this.gameObject),i.onDragEnd(e)),t&&(Ai._active>0&&(Ai._active-=1),this.setTargetObject(null),t.onDragEnd&&t.onDragEnd(e),this._dragHandlers.delete(e.event.space),this._dragHandlers.size===0&&this.onLastDragEnd(e),e.use()),this.context.accessibility.unfocus(this),this.context.accessibility.updateElement(this,{busy:!1})}update(){for(const e of this._dragHandlers.values())e.collectMovementInfo&&e.collectMovementInfo(),e.getTotalMovement&&this._totalMovement.add(e.getTotalMovement());if(this._potentialDragStartEvt){if(!this._didDrag)if(this._totalMovement.length()>3e-4)this._didDrag=!0;else return;const e=this._potentialDragStartEvt;this._potentialDragStartEvt=null,this.onFirstDragStart(e)}for(const e of this._dragHandlers.values())e.onDragUpdate&&e.onDragUpdate(this._dragHandlers.size);this._dragHelper&&this._dragHelper.hasSelected&&this.onAnyDragUpdate()}onFirstDragStart(e){if(!e||!e.object)return;const t=S.getComponentInParent(e.object,Ai);if(!t||t!==this&&t._isDragging)return;const i=this._targetObject||this.gameObject;if(!i)return;this._isDragging=!0;const n=S.getComponentInChildren(i,pn);zn&&console.log("DRAG START",n,i),n&&(n.fastMode=!0,n?.requestOwnership()),this._marker=S.addComponent(i,Jc),this._draggingRigidbodies.length=0;const o=S.getComponentsInChildren(i,$e);o&&this._draggingRigidbodies.push(...o),i.matrixAutoUpdate===!1&&!globalThis["DragControls:MatrixWarningShown"]&&(globalThis["DragControls:MatrixWarningShown"]=!0,console.warn("Dragging an object with matrixAutoUpdate=false can lead to unexpected behavior. Consider enabling matrixAutoUpdate or updating the matrix manually during dragging."))}onAnyDragUpdate(){if(!this._dragHelper)return;this._dragHelper.showGizmo=this.showGizmo,this._dragHelper.onUpdate(this.context);for(const t of this._draggingRigidbodies)t.wakeUp(),t.resetVelocities(),t.resetForcesAndTorques();const e=this._targetObject||this.gameObject;Ni.markDirty(e)}onLastDragEnd(e){if(!this||!this._isDragging)return;this._isDragging=!1;for(const i of this._draggingRigidbodies)i.setVelocity(i.smoothedVelocity.multiplyScalar(this.context.time.deltaTime));if(this._draggingRigidbodies.length=0,this._targetObject=null,e?.object){const i=S.getComponentInChildren(e.object,pn);i&&(i.fastMode=!1)}if(this._marker&&this._marker.destroy(),!this._dragHelper)return;const t=this._dragHelper.selected;zn&&console.log("DRAG END",t,t?.visible),this._dragHelper.setSelected(null,this.context)}};Mr([f()],So.prototype,"dragMode");Mr([f()],So.prototype,"snapGridResolution");Mr([f()],So.prototype,"keepRotation");Mr([f()],So.prototype,"xrDragMode");Mr([f()],So.prototype,"xrKeepRotation");Mr([f()],So.prototype,"xrDistanceDragFactor");Mr([f()],So.prototype,"showGizmo");let Zo=So;class WO{handlerA;handlerB;context;settings;gameObject;_handlerAAttachmentPoint=new c.Vector3;_handlerBAttachmentPoint=new c.Vector3;_followObject;_manipulatorObject;_deviceMode;_followObjectStartWorldQuaternion=new c.Quaternion;constructor(e,t,i,n){this.context=e.context,this.settings=e,this.gameObject=t,this.handlerA=i,this.handlerB=n,this._followObject=new c.Object3D,this._manipulatorObject=new c.Object3D,this.context.scene.add(this._manipulatorObject);const o=q.active?.rig?.gameObject;if(!this.handlerA||!this.handlerB||!this.handlerA.hitPointInLocalSpace||!this.handlerB.hitPointInLocalSpace){console.error("Invalid: MultiTouchDragHandler needs two valid DragPointerHandlers with hitPointInLocalSpace set.");return}if(this._tempVec1.copy(this.handlerA.hitPointInLocalSpace),this._tempVec2.copy(this.handlerB.hitPointInLocalSpace),this.gameObject.localToWorld(this._tempVec1),this.gameObject.localToWorld(this._tempVec2),o&&(o.worldToLocal(this._tempVec1),o.worldToLocal(this._tempVec2)),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.02?(zn&&console.log("Finding alternative drag attachment points since initial distance is too low: "+this._initialDistance.toFixed(2)),this.handlerA.followObject.parent.getWorldPosition(this._tempVec1),this.handlerB.followObject.parent.getWorldPosition(this._tempVec2),this._handlerAAttachmentPoint.copy(this._tempVec1),this._handlerBAttachmentPoint.copy(this._tempVec2),this.gameObject.worldToLocal(this._handlerAAttachmentPoint),this.gameObject.worldToLocal(this._handlerBAttachmentPoint),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.001&&(console.warn("Not supported right now – controller drag points for multitouch are too close!"),this._initialDistance=1)):(this._handlerAAttachmentPoint.copy(this.handlerA.hitPointInLocalSpace),this._handlerBAttachmentPoint.copy(this.handlerB.hitPointInLocalSpace)),this._tempVec3.lerpVectors(this._tempVec1,this._tempVec2,.5),this._initialScale.copy(t.scale),zn){this._followObject.add(new c.AxesHelper(2)),this._manipulatorObject.add(new c.AxesHelper(5));const r=a=>`${a.x.toFixed(2)}, ${a.y.toFixed(2)}, ${a.z.toFixed(2)}`;B.DrawLine(this._tempVec1,this._tempVec2,65535,0,!1),B.DrawLabel(this._tempVec3,"A:B "+this._initialDistance.toFixed(2)+`
|
|
983
|
-
`+r(this._tempVec1)+`
|
|
984
|
-
`+r(this._tempVec2),.03,5)}}onDragStart(e){this.gameObject.add(this._followObject),this._followObject.matrixAutoUpdate=!1,this._followObject.matrix.identity(),this._deviceMode=e.mode,this._followObjectStartWorldQuaternion.copy(this._followObject.worldQuaternion),this.alignManipulator(),this._manipulatorObject.attach(this._followObject),this._manipulatorPosOffset.copy(this._followObject.position),this._manipulatorRotOffset.copy(this._followObject.quaternion),this._manipulatorScaleOffset.copy(this._followObject.scale)}onDragEnd(e){if(!this.handlerA||!this.handlerB){console.error("onDragEnd called on MultiTouchDragHandler without valid handlers. This is likely a bug.");return}this.handlerA.recenter(),this.handlerB.recenter(),this._manipulatorObject.removeFromParent(),this._followObject.removeFromParent(),this._manipulatorObject.destroy(),this._followObject.destroy()}_manipulatorPosOffset=new c.Vector3;_manipulatorRotOffset=new c.Quaternion;_manipulatorScaleOffset=new c.Vector3;_tempVec1=new c.Vector3;_tempVec2=new c.Vector3;_tempVec3=new c.Vector3;tempLookMatrix=new c.Matrix4;_initialScale=new c.Vector3;_initialDistance=0;alignManipulator(){if(!this.handlerA||!this.handlerB){console.error("alignManipulator called on MultiTouchDragHandler without valid handlers. This is likely a bug.",this);return}if(!this.handlerA.followObject||!this.handlerB.followObject){console.error("alignManipulator called on MultiTouchDragHandler without valid follow objects. This is likely a bug.",this.handlerA,this.handlerB);return}this._tempVec1.copy(this._handlerAAttachmentPoint),this._tempVec2.copy(this._handlerBAttachmentPoint),this.handlerA.followObject.localToWorld(this._tempVec1),this.handlerB.followObject.localToWorld(this._tempVec2),this._tempVec3.lerpVectors(this._tempVec1,this._tempVec2,.5),this._manipulatorObject.position.copy(this._tempVec3);const e=this.context.mainCamera;this.tempLookMatrix.lookAt(this._tempVec3,this._tempVec2,e.worldUp),this._manipulatorObject.quaternion.setFromRotationMatrix(this.tempLookMatrix);const t=this._tempVec1.distanceTo(this._tempVec2);this._manipulatorObject.scale.copy(this._initialScale).multiplyScalar(t/this._initialDistance),this._manipulatorObject.updateMatrix(),this._manipulatorObject.updateMatrixWorld(!0),zn&&(B.DrawLabel(this._tempVec3.clone().add(new c.Vector3(0,.2,0)),"A:B "+t.toFixed(2),.03),B.DrawLine(this._tempVec1,this._tempVec2,65280,0,!1))}onDragUpdate(){this.alignManipulator();const e=30,t=1;this._followObject.position.copy(this._manipulatorPosOffset),this._followObject.quaternion.copy(this._manipulatorRotOffset),this._followObject.scale.copy(this._manipulatorScaleOffset);const i=this.gameObject,n=this._followObject;if(!i){console.error("MultiTouchDragHandler has no dragged object. This is likely a bug.");return}n.updateMatrix(),n.updateMatrixWorld(!0);const r=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrKeepRotation:this.settings.keepRotation;if(this.settings.snapGridResolution>0){const u=this._followObject.worldPosition,p=this.settings.snapGridResolution;u.x=Math.round(u.x/p)*p,u.y=Math.round(u.y/p)*p,u.z=Math.round(u.z/p)*p,this._followObject.worldPosition=u,this._followObject.updateMatrix()}r&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const a=I.clamp01(this.context.time.deltaTime*e*t),l=i.worldPosition;l.lerp(n.worldPosition,a),i.worldPosition=l;const h=i.worldQuaternion;h.slerp(n.worldQuaternion,a),i.worldQuaternion=h;const d=i.worldScale;d.lerp(n.worldScale,a),i.worldScale=d,i.matrixAutoUpdate===!1&&i.updateMatrix()}setTargetObject(e){this.gameObject=e}}class Yf{getTotalMovement(){return this._totalMovement}get followObject(){return this._followObject}get hitPointInLocalSpace(){return this._hitPointInLocalSpace}context;gameObject;settings;_lastRig=void 0;_followObject;_totalMovement=new c.Vector3;_totalMovementAlongRayDirection=0;_grabStartDistance=0;_deviceMode;_followObjectStartPosition=new c.Vector3;_followObjectStartQuaternion=new c.Quaternion;_followObjectStartWorldQuaternion=new c.Quaternion;_lastDragPosRigSpace;_tempVec=new c.Vector3;_tempMat=new c.Matrix4;_hitPointInLocalSpace=new c.Vector3;_hitNormalInLocalSpace=new c.Vector3;_bottomCenter=new c.Vector3;_backCenter=new c.Vector3;_backBottomCenter=new c.Vector3;_bounds=new c.Box3;_dragPlane=new c.Plane(new c.Vector3(0,1,0));_draggedOverObject=null;_draggedOverObjectLastSetUp=null;_draggedOverObjectLastNormal=new c.Vector3;_draggedOverObjectDuration=0;setTargetObject(e){this.gameObject=e}constructor(e,t){this.settings=e,this.context=e.context,this.gameObject=t,this._followObject=new c.Object3D}recenter(){if(!this._followObject.parent){console.warn("Error: space follow object doesn't have parent but recenter() is called. This is likely a bug");return}if(!this.gameObject){console.warn("Error: space follow object doesn't have a gameObject");return}const e=this._followObject.parent;this.gameObject.add(this._followObject),this._followObject.matrixAutoUpdate=!1,this._followObject.position.set(0,0,0),this._followObject.quaternion.set(0,0,0,1),this._followObject.scale.set(1,1,1),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0),e.attach(this._followObject),this._followObjectStartPosition.copy(this._followObject.position),this._followObjectStartQuaternion.copy(this._followObject.quaternion),this._followObjectStartWorldQuaternion.copy(this._followObject.worldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);const t=this._hitPointInLocalSpace.clone();this.gameObject.localToWorld(t),this._grabStartDistance=t.distanceTo(e.worldPosition);const n=q.active?.rig?.gameObject?.worldScale.x||1;this._grabStartDistance/=n,this._totalMovementAlongRayDirection=0,this._lastDragPosRigSpace=void 0,zn&&(B.DrawLine(t,e.worldPosition,65280,.5,!1),B.DrawLabel(e.worldPosition.add(new c.Vector3(0,.1,0)),this._grabStartDistance.toFixed(2),.03,.5))}onDragStart(e){if(!this.gameObject){console.warn("Error: space follow object doesn't have a gameObject");return}if(e.event.space.add(this._followObject),this._lastDragPosRigSpace=void 0,e.point&&e.normal)this._hitPointInLocalSpace.copy(e.point),this.gameObject.worldToLocal(this._hitPointInLocalSpace),this._hitNormalInLocalSpace.copy(e.normal);else if(e){const _=e.event.space,g=_.worldPosition;this.gameObject.worldToLocal(g),this._hitPointInLocalSpace.copy(g);const w=_.worldUp;this._tempMat.copy(this.gameObject.matrixWorld).invert(),w.transformDirection(this._tempMat),this._hitNormalInLocalSpace.copy(w)}this.recenter(),this._totalMovement.set(0,0,0),this._deviceMode=e.mode;const i=this._followObject.parent.worldForward,o=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrDragMode:this.settings.dragMode,r=this._hitPointInLocalSpace.clone();switch(this.gameObject.localToWorld(r),o){case 0:const _=new c.Vector3(0,1,0);this.gameObject.parent&&_.transformDirection(this.gameObject.parent.matrixWorld.clone().invert()),this._dragPlane.setFromNormalAndCoplanarPoint(_,r);break;case 2:const g=this._hitNormalInLocalSpace.clone();g.transformDirection(this.gameObject.matrixWorld),this._dragPlane.setFromNormalAndCoplanarPoint(g,r);break;case 1:this._dragPlane.setFromNormalAndCoplanarPoint(i,r);break;case 3:this.setPlaneViewAligned(r,!0);break;case 4:this.setPlaneViewAligned(r,!1);break}const a=this.gameObject.parent,l=this.gameObject.position.clone(),h=this.gameObject.quaternion.clone(),d=this.gameObject.scale.clone(),u=this.gameObject.matrixWorld.clone();a&&a.remove(this.gameObject),this.gameObject.position.set(0,0,0),this.gameObject.quaternion.set(0,0,0,1),this.gameObject.scale.set(1,1,1);const p=ri([this.gameObject]);p.expandByPoint(this.gameObject.worldPosition);const m=new c.Vector3;p.getCenter(m);const y=new c.Vector3;p.getSize(y),this._bottomCenter.copy(m.clone().add(new c.Vector3(0,-y.y/2,0))),this._backCenter.copy(m.clone().add(new c.Vector3(0,0,y.z/2))),this._backBottomCenter.copy(m.clone().add(new c.Vector3(0,-y.y/2,y.z/2))),this._bounds.copy(p),a&&a.add(this.gameObject),this.gameObject.position.copy(l),this.gameObject.quaternion.copy(h),this.gameObject.scale.copy(d),this.gameObject.matrixWorld.copy(u),this._draggedOverObject=null,this._draggedOverObjectLastSetUp=null,this._draggedOverObjectLastNormal.set(0,1,0),this._draggedOverObjectDuration=0}collectMovementInfo(){if(!this._followObject.parent)return;const e=this._followObject.parent;this._followObject.updateMatrix();const t=e.worldPosition,i=q.active?.rig?.gameObject;i&&i.worldToLocal(t),(this._lastDragPosRigSpace===void 0||i!=this._lastRig)&&(this._lastDragPosRigSpace=t.clone(),this._lastRig=i),this._tempVec.copy(t).sub(this._lastDragPosRigSpace);const n=e.worldForward;if(i&&(this._tempMat.copy(i.matrixWorld).invert(),n.transformDirection(this._tempMat)),this._totalMovementAlongRayDirection+=n.dot(this._tempVec),this._tempVec.x=Math.abs(this._tempVec.x),this._tempVec.y=Math.abs(this._tempVec.y),this._tempVec.z=Math.abs(this._tempVec.z),this._totalMovement.add(this._tempVec),this._lastDragPosRigSpace.copy(t),zn){let o=t;i&&(o=o.clone(),o.transformDirection(i.matrixWorld)),B.DrawRay(o,n,255)}}onDragUpdate(e){if(e>1)return;const t=this.gameObject;if(!t||!this._followObject){console.warn("Warning: DragPointerHandler doesn't have a dragged object. This is likely a bug.");return}const i=this._followObject.parent;if(!i){console.warn("Warning: DragPointerHandler doesn't have a drag source. This is likely a bug.");return}this._followObject.updateMatrix();const n=i.worldPosition,o=i.worldForward,r=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer",a=r?this.settings.xrKeepRotation:this.settings.keepRotation,l=r?this.settings.xrDragMode:this.settings.dragMode;if(l===5)return;const h=10;a&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);let d=1,u=2;if(r&&this._grabStartDistance>.5){const b=1+this._totalMovementAlongRayDirection*(2*this.settings.xrDistanceDragFactor);d=Math.max(0,b),d=d*d*d}else this._grabStartDistance<=.5&&(u=3);this._followObject.position.copy(this._followObjectStartPosition),a||this._followObject.quaternion.copy(this._followObjectStartQuaternion),this._followObject.position.multiplyScalar(d),this._followObject.updateMatrix();const p=this._hasLastSurfaceHitPoint;this._hasLastSurfaceHitPoint=!1;const m=new c.Ray(n,o);if(l==4){const b=this.context.physics.raycastFromRay(m,{testObject:v=>v!==this.followObject&&v!==i&&v!==t});if(b.length>0){const v=b[0];if(this._draggedOverObject===v.object?this._draggedOverObjectDuration+=this.context.time.deltaTime:(this._draggedOverObject=v.object,this._draggedOverObjectDuration=0),v.face){this._hasLastSurfaceHitPoint=!0,this._lastSurfaceHitPoint.copy(v.point);const O=this._draggedOverObjectDuration>=.15,D=this._totalMovement.length()>=.001,L=F(v.normal||v.face.normal).applyQuaternion(v.object.worldQuaternion);if((O||D)&&(this._draggedOverObjectLastSetUp!==this._draggedOverObject||this._draggedOverObjectLastNormal.dot(L)<.999999||this.context.time.frame%60===0)){this._draggedOverObjectLastSetUp=this._draggedOverObject,this._draggedOverObjectLastNormal.copy(v.face.normal);const j=F(),V=F();this._bounds.getCenter(j),this._bounds.getSize(V),j.sub(V.multiplyScalar(.5).multiply(L)),this._hitPointInLocalSpace.copy(j),this._hitNormalInLocalSpace.copy(v.face.normal),this._bounds.getCenter(j),this._bounds.getSize(V),j.add(V.multiplyScalar(.5).multiply(v.face.normal));const W=F(this._hitPointInLocalSpace).add(j);this._followObject.localToWorld(W);const k=v.point;this._dragPlane.setFromNormalAndCoplanarPoint(L,k)}else if(!(O||D))return}}else p&&this.gameObject&&this.setPlaneViewAligned(this.gameObject.worldPosition,!1)}if(l!==1&&m.intersectPlane(this._dragPlane,this._tempVec)){this._followObject.worldPosition=this._tempVec,this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);const b=F(this._hitPointInLocalSpace);this._followObject.localToWorld(b),zn&&B.DrawLine(b,this._tempVec,65535,0,!1),this._followObject.worldPosition=this._tempVec.multiplyScalar(2).sub(b),this._followObject.updateMatrix(),this._followObject.updateMatrix()}if(this.settings.snapGridResolution>0){const b=this._followObject.worldPosition,v=this.settings.snapGridResolution;b.x=Math.round(b.x/v)*v,b.y=Math.round(b.y/v)*v,b.z=Math.round(b.z/v)*v,this._followObject.worldPosition=b,this._followObject.updateMatrix()}a&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const y=I.clamp01(this.context.time.deltaTime*h*u),_=I.clamp01(this.context.time.deltaTime*h*.5*u),g=t.worldPosition;g.lerp(this._followObject.worldPosition,y),t.worldPosition=g;const w=t.worldQuaternion;if(w.slerp(this._followObject.worldQuaternion,_),t.worldQuaternion=w,t.matrixAutoUpdate===!1&&t.updateMatrix(),zn){const b=this._hitPointInLocalSpace.clone();t.localToWorld(b),B.DrawSphere(b,.02,16711680);const v=this._hitNormalInLocalSpace.clone();v.applyQuaternion(w),B.DrawRay(b,v,16711680),B.DrawLabel(g.add(new c.Vector3(0,.25,0)),`Distance: ${this._totalMovement.length().toFixed(2)}
|
|
985
|
-
|
|
986
|
-
Along Ray: ${this._totalMovementAlongRayDirection.toFixed(2)}
|
|
987
|
-
|
|
988
|
-
Session: ${!!q.active}
|
|
989
|
-
|
|
990
|
-
Device: ${this._deviceMode}
|
|
991
|
-
|
|
992
|
-
`,.03);const E=this._bottomCenter.clone(),O=this._backCenter.clone(),M=this._backBottomCenter.clone();t.localToWorld(E),t.localToWorld(O),t.localToWorld(M),B.DrawSphere(E,.01,65280,0,!1),B.DrawSphere(O,.01,255,0,!1),B.DrawSphere(M,.01,16711935,0,!1),B.DrawLine(E,M,65535,0,!1),B.DrawLine(M,O,65535,0,!1)}}onDragEnd(e){console.assert(this._followObject.parent===e.event.space,"Drag end: _followObject is not parented to the space object"),this._followObject.removeFromParent(),this._followObject.destroy(),this._lastDragPosRigSpace=void 0}_hasLastSurfaceHitPoint=!1;_lastSurfaceHitPoint=new c.Vector3;setPlaneViewAligned(e,t){if(!this._followObject.parent)return!1;const i=this._followObject.parent.worldForward,n=F(0,1,0),o=i,r=n.angleTo(o),a=.5;return t&&(r>Math.PI/2+a||r<Math.PI/2-a)?this._dragPlane.setFromNormalAndCoplanarPoint(n,e):this._dragPlane.setFromNormalAndCoplanarPoint(i,e),!0}}class _w{showGizmo=!0;useViewAngle=!0;get hasSelected(){return this._selected!==null&&this._selected!==void 0}get selected(){return this._selected}_selected=null;_context=null;_camera;_cameraPlane=new c.Plane;_hasGroundPlane=!1;_groundPlane=new c.Plane;_groundOffset=new c.Vector3;_groundOffsetFactor=0;_groundDistance=0;_groundPlanePoint=new c.Vector3;_raycaster=new c.Raycaster;_cameraPlaneOffset=new c.Vector3;_intersection=new c.Vector3;_worldPosition=new c.Vector3;_inverseMatrix=new c.Matrix4;_rbs=[];_groundLine;_groundMarker;static geometry=new c.BufferGeometry().setFromPoints([new c.Vector3(0,0,0),new c.Vector3(0,-1,0)]);constructor(e){this._camera=e;const t=new c.Line(_w.geometry),i=t.material;i.color=new c.Color(.4,.4,.4),t.layers.set(2),t.name="line",t.scale.y=1,this._groundLine=t;const n=new c.SphereGeometry(.5,22,22),o=new c.MeshBasicMaterial({color:i.color}),r=new c.Mesh(n,o);r.visible=!1,r.layers.set(2),this._groundMarker=r}setSelected(e,t){if(this._selected&&t)for(const i of this._rbs)i.wakeUp(),i.setVelocity(0,0,0);if(this._selected&&cr.Remove(t,this._selected),this._selected=e,this._context=t,this._rbs.length=0,e?(t.scene.add(this._groundLine),t.scene.add(this._groundMarker)):(this._groundLine.removeFromParent(),this._groundMarker.removeFromParent()),this._selected){if(!t){console.error("DragHelper: no context");return}cr.Add(t,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this.onUpdateScreenSpacePlane()}}_groundOffsetVector=new c.Vector3(0,1,0);_requireUpdateGroundPlane=!0;_didDragOnGroundPlaneLastFrame=!1;onUpdate(e){this._selected}onUpdateWorldPosition(e,t,i){if(this._selected){if(i){const n=Y(this._selected);n.y=e.y,e=n}if(at(this._selected,e),at(this._groundLine,e),this._hasGroundPlane?this._groundLine.scale.y=this._groundDistance:this._groundLine.scale.y=1e3,this._groundLine.visible=this.showGizmo,this._groundMarker.visible=t!==null&&this.showGizmo,t){const n=Y(this._camera).distanceTo(t)*.01;this._groundMarker.scale.set(n,n,n),at(this._groundMarker,t)}}}onUpdateScreenSpacePlane(){if(!this._selected||!this._context)return;const e=this._context.input.getPointerPositionRC(0);e&&(this._raycaster.setFromCamera(e,this._camera),this._cameraPlane.setFromNormalAndCoplanarPoint(this._camera.getWorldDirection(this._cameraPlane.normal),this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld)),this._raycaster.ray.intersectPlane(this._cameraPlane,this._intersection)&&this._selected.parent&&(this._inverseMatrix.copy(this._selected.parent.matrixWorld).invert(),this._cameraPlaneOffset.copy(this._intersection).sub(this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld))))}onUpdateGroundPlane(){if(!this._selected||!this._context)return;const e=Y(this._selected),t=new c.Ray(F(0,.1,0).add(e),F(0,-1,0)),i=new vo;i.testObject=o=>o!==this._selected;const n=this._context.physics.raycastFromRay(t,i);for(let o=0;o<n.length;o++){const r=n[o];if(!r.face||this.contains(this._selected,r.object))continue;const a=F(0,1,0);this._groundPlane.setFromNormalAndCoplanarPoint(a,r.point);break}this._hasGroundPlane=!0,this._groundPlane.setFromNormalAndCoplanarPoint(t.direction.multiplyScalar(-1),t.origin),this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection),this._groundDistance=this._intersection.distanceTo(e),this._groundOffset.copy(this._intersection).sub(e)}contains(e,t){if(e===t)return!0;if(e.children){for(const i of e.children)if(this.contains(i,t))return!0}return!1}}var bw=(s=>(s.File_Spawned="file-spawned",s))(bw||{});class GO{guid;file_name;file_hash;file_size;position;scale;seed;sender;downloadUrl;parentGuid;boundsSize;constructor(e,t,i,n,o,r,a,l,h){this.seed=t,this.guid=i,this.file_name=n,this.file_hash=o,this.file_size=r,this.position=a,this.scale=l,this.sender=e,this.downloadUrl=h}}exports.PreviewHelper=void 0;(s=>{const e=new Map;function t(n){e.has(n.guid)&&i(n.guid);const o=new c.Object3D;e.set(n.guid,o);const r=new c.Object3D;r.position.y=-.5,o.add(r);const a=new c.Mesh(new c.BoxGeometry(1,1,1,1,1,1),new c.MeshBasicMaterial({color:14540253,wireframe:!0,transparent:!0,opacity:.3}));a.position.y=.5,r.add(a);const l=new c.Object3D;r.add(l);const h=new c.Mesh(new c.BoxGeometry(1,1,1,1,1,1),new c.MeshBasicMaterial({color:12307660,transparent:!0,opacity:.4}));h.position.y=.5,l.scale.y=.01,l.add(h);const d=new c.Mesh(new c.PlaneGeometry(1,1,1,1),new c.MeshBasicMaterial({color:34,transparent:!0,opacity:.05,depthTest:!1}));return d.rotateX(-Math.PI/2),d.position.y=.51,h.add(d),n.parent.add(o),o.rotateY(Math.PI/2),n.position&&o.position?.copy(n.position),n.size&&(o.worldScale=new c.Vector3().copy(n.size)),o.position.y=o.scale.y/2,{object:o,onProgress:u=>{l instanceof c.Object3D&&l.scale.set(1,u,1)}}}s.addPreview=t;function i(n){const o=e.get(n);o&&(e.delete(n),o.removeFromParent())}s.removePreview=i})(exports.PreviewHelper||(exports.PreviewHelper={}));const ma=[],Sd=[];exports.NeedleEngineModelLoader=void 0;(s=>{function e(i,n){const o={name:n?.name,priority:n?.priority??0,callback:i};return ma.push(o),ma.sort((r,a)=>r.priority===a.priority?0:r.priority>a.priority?-1:1),()=>{const r=ma.indexOf(o);r>=0&&ma.splice(r,1)}}s.onCreateCustomModelLoader=e;function t(i){return Sd.push(i),()=>{const n=Sd.indexOf(i);n>=0&&Sd.splice(n,1)}}s.onDetermineModelMimetype=t})(exports.NeedleEngineModelLoader||(exports.NeedleEngineModelLoader={}));const ke=x("debugfileformat");function vw(s){switch((s.split(".").pop()||s).toUpperCase()){case"GLTF":return"model/gltf+json";case"VRM":return"model/vrm";case"GLB":return"model/gltf-binary";case"FBX":return"model/fbx";case"USD":return"model/vnd.usd+zip";case"USDA":return"model/vnd.usda+zip";case"USDZ":return"model/vnd.usdz+zip";case"OBJ":return"model/obj";default:return null}}async function ww(s,e){const{useExtension:t=!0}=e;if(t){const o=s,r=new URL(o,globalThis.location.href);let a=null;const l=r.searchParams.get("filetype");switch(l&&(a=l.toUpperCase()),a?.length||(a=r.pathname.split(".").pop()?.toUpperCase()),ke&&console.warn(`[Needle Engine] Try to use file extension to determine type: '${a}'`),a){case"GLTF":return"model/gltf+json";case"VRM":return"model/vrm";case"GLB":return"model/gltf-binary";case"FBX":return"model/fbx";case"USD":return"model/vnd.usd+zip";case"USDA":return"model/vnd.usda+zip";case"USDZ":return"model/vnd.usdz+zip";case"OBJ":return"model/obj";case"MTLX":return"application/materialx+xml"}}const i=s;if(!s.startsWith("blob:")){const o=new URL(s,globalThis.location.href);o.searchParams.append("range","true"),s=o.toString()}const n=await fetch(s,{method:"GET",headers:{range:"bytes=0-32"}}).catch(o=>null);if(n?.ok){const o=await n.arrayBuffer(),r=xw(i,o,n);return ke&&console.log("[Needle Engine] Determined file type from header: "+r),r}return"unknown"}function xw(s,e,t){if(e.byteLength<4)return"unknown";const i=new Uint8Array(e);ke&&ke&&console.warn(`[Needle Engine] Trying to determine file type from binary data
|
|
993
|
-
`,'"'+new TextDecoder().decode(e)+`"
|
|
994
|
-
`,i);const n=new TextDecoder().decode(e).replace(/\s/g,"");if(n[0]==="{"&&n[1]==='"')return ke&&console.debug("GLTF detected"),"model/gltf+json";if(i[0]==103&&i[1]==108&&i[2]==84&&i[3]==70&&(i[4]==10||i[4]===2))return ke&&console.debug("GLTF .bin detected"),"model/gltf+json";if(i[0]==103&&i[1]==108&&i[2]==84&&i[3]==70&&i[4]==98)return ke&&console.debug("GLB detected"),"model/gltf-binary";if(i[0]==80&&i[1]==75&&i[2]==3&&i[3]==4)return ke&&console.debug("USDZ detected"),"model/vnd.usdz+zip";if(i[0]==80&&i[1]==88&&i[2]==82&&i[3]==45&&i[4]==85&&i[5]==83&&i[6]==68&&i[7]==67)return ke&&console.debug("Binary USD detected"),"model/vnd.usd";if(i[0]==35&&i[1]==117&&i[2]==115&&i[3]==100&&i[4]==97)return ke&&console.debug("ASCII USD detected"),"model/vnd.usda";if(i[0]==75&&i[1]==97&&i[2]==121&&i[3]==100&&i[4]==97&&i[5]==114&&i[6]==97&&i[7]==32)return ke&&console.debug("Binary FBX detected"),"model/fbx";if(i[0]==59&&i[1]==32&&i[2]==70&&i[3]==66&&i[4]==88&&i[5]==32)return ke&&console.debug("ASCII FBX detected"),"model/fbx";if(i[0]==35&&i[1]==32&&i[2]==66&&i[3]==108&&i[4]==101&&i[5]==110&&i[6]==100&&i[7]==101&&i[8]==114&&i[9]==32)return ke&&console.debug("OBJ detected"),"model/obj";if(i[0]==35&&i[1]==32&&i[2]==65&&i[3]==108&&i[4]==105&&i[5]==97&&i[6]==115&&i[7]==32&&i[8]==79&&i[9]==66&&i[10]==74)return ke&&console.debug("OBJ detected"),"model/obj";if(t.headers.has("content-type")){const o=t.headers.get("content-type");if(o?.startsWith("image/"))return ke&&console.debug("Image detected, not a model file"),"unsupported";switch(ke&&console.debug("Content-Type: "+o),o){case"model/gltf+json":case"model/gltf-binary":case"model/vrm":case"model/vnd.usdz+zip":case"model/vnd.usd+zip":case"model/vnd.usd":case"model/vnd.usda+zip":case"model/vnd.usda":case"model/vnd.usdc":case"model/fbx":case"model/vnd.autodesk.fbx":case"model/obj":case"application/materialx+xml":return o}}if(i[0]==118&&i[1]==32||i[0]==102&&i[1]==32)return ke&&console.debug("OBJ detected (the file has no header and starts with vertex or face)"),"obj";if(i[0]==35&&i[1]==32&&i[2]==70&&i[3]==105&&i[4]==108&&i[5]==101&&i[6]==32&&i[7]==101&&i[8]==120&&i[9]==112&&i[10]==111&&i[11]==114&&i[12]==116&&i[13]==101&&i[14]==100&&i[15]==32&&i[16]==98&&i[17]==121&&i[18]==32&&i[19]==90&&i[20]==66&&i[21]==114&&i[22]==117&&i[23]==115&&i[24]==104)return ke&&console.debug("OBJ detected (exported by ZBrush)"),"obj";if(i[0]==109&&i[1]==116&&i[2]==108&&i[3]==108&&i[4]==105&&i[5]==98)return ke&&console.debug("OBJ detected (mtllib)"),"obj";for(const o of Sd){const r=o({url:s,response:t,contentType:t.headers.get("content-type"),bytes:i});if(r)return ke&&console.debug(`Mimetype callback returned: ${r}`),r}if(A()||ke){const o=new TextDecoder().decode(e.slice(0,Math.min(e.byteLength,32)));ke&&console.warn(`Could not determine file type.
|
|
995
|
-
|
|
996
|
-
Consider registering a custom loader via the 'onCreateCustomModelLoader' callback: 'NeedleEngineModelLoader.onCreateCustomModelLoader(args => { })'
|
|
997
|
-
|
|
998
|
-
Content-Type: "${t.headers.get("content-type")}"
|
|
999
|
-
"Text: "${o}"
|
|
1000
|
-
Binary:`,i)}else ke&&console.debug("Could not determine file type from binary data");return"unknown"}const Kf=x("debugstencil");function HO(s,e){return(s&1<<e.layer)!=0}const qO=Symbol("stencils");class eo{get name(){return"NEEDLE_render_objects"}static stencils={};static applyStencil(e){if(!e)return;const t=e.sourceId;if(Kf&&console.log(t,eo.stencils),!t)return;const i=eo.stencils[t];if(i)for(let n=i.length-1;n>=0;n--){const o=i[n];if(HO(o.layer,e)){Kf&&console.log(o),setTimeout(()=>{yi()&&bu(e.gameObject)&&(fe("Stencil not supported on instanced objects"),console.warn("Stencil not supported on instanced objects",e))},500);for(let r=0;r<e.sharedMaterials.length;r++){let a=e.sharedMaterials[r];a&&(a=a.clone(),a[qO]=!0,a.stencilWrite=!0,a.stencilWriteMask=255,a.stencilFuncMask=255,a.stencilRef=o.value,a.stencilFunc=o.compareFunc,a.stencilZPass=o.passOp,a.stencilFail=o.failOp,a.stencilZFail=o.zFailOp,e.sharedMaterials[r]=a)}e.gameObject.renderOrder=o.event*1e3+o.index*50;break}}}parser;source;constructor(e,t){this.parser=e,this.source=t}afterRoot(e){const t=this.parser.json.extensions;if(t){const i=t[QO];if(i){Kf&&console.log(i);const n=i.stencil;if(n&&Array.isArray(n))for(const o of n){const r={...o};r.compareFunc=XO(r.compareFunc),r.passOp=Zf(r.passOp),r.failOp=Zf(r.failOp),r.zFailOp=Zf(r.zFailOp),eo.stencils[this.source]||(eo.stencils[this.source]=[]),eo.stencils[this.source].push(r)}}}return null}}function Zf(s){switch(s){case 0:return c.KeepStencilOp;case 1:return c.ZeroStencilOp;case 2:return c.ReplaceStencilOp;case 3:return c.IncrementStencilOp;case 4:return c.DecrementStencilOp;case 6:return c.IncrementWrapStencilOp;case 7:return c.DecrementWrapStencilOp;case 5:return c.InvertStencilOp}return 0}function XO(s){switch(s){case 1:return c.NeverStencilFunc;case 2:return c.LessStencilFunc;case 3:return c.EqualStencilFunc;case 4:return c.LessEqualStencilFunc;case 5:return c.GreaterStencilFunc;case 6:return c.NotEqualStencilFunc;case 7:return c.GreaterEqualStencilFunc;case 8:return c.AlwaysStencilFunc}return c.NeverStencilFunc}const QO="NEEDLE_render_objects";class YO{objectToBlock=new WeakMap;meshToOwners=new WeakMap;meshToOriginalCallbacks=new WeakMap;getBlock(e){return this.objectToBlock.get(e)}setBlock(e,t){this.objectToBlock.set(e,t)}deleteBlock(e){this.objectToBlock.delete(e)}isHooked(e,t){return this.meshToOwners.get(e)?.has(t)??!1}addHook(e,t){let i=this.meshToOwners.get(e);i||(i=new Set,this.meshToOwners.set(e,i)),i.add(t)}removeHook(e,t){const i=this.meshToOwners.get(e);i&&(i.delete(t),i.size===0&&this.meshToOwners.delete(e))}getOriginalCallbacks(e){return this.meshToOriginalCallbacks.get(e)}setOriginalCallbacks(e,t){this.meshToOriginalCallbacks.set(e,t)}}const fs=new YO;class ys{_overrides=[];_defines={};_object=null;get object(){return this._object}constructor(e=null){this._object=e}static get(e){let t=fs.getBlock(e);return t||(t=new ys(e),fs.setBlock(e,t),JO(e,t)),t}static hasOverrides(e){const t=fs.getBlock(e);return t?t.hasOverrides():!1}dispose(){this._object&&fs.deleteBlock(this._object),this._overrides=[],this._object=null}setOverride(e,t,i){const n=this._overrides.find(o=>o.name===e);n?(n.value=t,n.textureTransform=i):this._overrides.push({name:e,value:t,textureTransform:i})}getOverride(e){return this._overrides.find(t=>t.name===e)}removeOveride(e){const t=this._overrides.findIndex(i=>i.name===e);t>=0&&this._overrides.splice(t,1)}clearAllOverrides(){this._overrides=[]}get overrides(){return this._overrides}hasOverrides(){return this._overrides.length>0}setDefine(e,t){this._defines[e]=t}clearDefine(e){this._defines[e]=void 0}getDefines(){return this._defines}getCacheKey(){const e=[],t=Object.keys(this._defines).sort();for(const i of t){const n=this._defines[i];n!==void 0&&e.push(`d:${i}=${n}`)}for(const i of this._overrides){if(i.value===null)continue;let n="";if(i.value instanceof c.Texture){if(n=i.value.uuid||"texture",i.textureTransform){const o=i.textureTransform;o.offset&&(n+=`;to:${o.offset.x},${o.offset.y}`),o.repeat&&(n+=`;tr:${o.repeat.x},${o.repeat.y}`)}}else if(Array.isArray(i.value))n=i.value.join(",");else if(i.value&&typeof i.value=="object"&&"r"in i.value){const o=i.value;n=`${o.r},${o.g},${o.b},${o.a!==void 0?o.a:""}`}else if(i.value&&typeof i.value=="object"&&"x"in i.value){const o=i.value;n=`${o.x},${o.y}${o.z!==void 0?`,${o.z}`:""}${o.w!==void 0?`,${o.w}`:""}`}else n=String(i.value);e.push(`${i.name}=${n}`)}return e.join(";")}}const Cd=Symbol("originalValues"),Pd=Symbol("savedTextureTransforms");function Sw(s){let e=fs.getBlock(s);if(e)return{block:e,owner:s};if(s.parent&&s.parent.type==="Group"&&(e=fs.getBlock(s.parent),e))return{block:e,owner:s.parent}}const Ca=Symbol("beforeRenderingFlag"),am=new WeakMap,lm=new WeakMap,KO=function(s,e,t,i){const n=fs.getBlock(s);if(n&&n.hasOverrides()){const o=n.getOverride("transmission")?.value,r=n.getOverride("transparent")?.value;o!==void 0&&typeof o=="number"&&"transmission"in t&&o!==t.transmission&&(lm.set(this,t.transmission),t.transmission=o),r!==void 0&&typeof r=="boolean"&&r!==t.transparent&&(am.set(this,t.transparent),t.transparent=r)}},ZO=function(s,e,t,i){const n=am.get(s);n!==void 0&&(am.delete(s),t.transparent=n);const o=lm.get(s);o!==void 0&&(lm.delete(s),t.transmission=o)},ab=function(s,e,t,i,n,o){const r=this.material;if(!r)return;if(Array.isArray(r)){if(!r.includes(n))return}else if(r!==n)return;this[Ca]===void 0&&(this[Ca]=new WeakSet),this[Ca].add(n);const a=Sw(this);if(!a)return;const{block:l,owner:h}=a,d=l.overrides,u=n,p=l.getDefines(),m=Object.keys(p);if(m.length>0){u.defines||(u.defines={});for(const g of m){const w=p[g];w!==void 0&&(u.defines[g]=w)}}if(d.length===0&&m.length===0)return;let y=m.length>0;u[Cd]||(u[Cd]=[]);const _=u[Cd];for(const g of d){if(g.value===null)continue;const w=u[g.name],b=_.find(v=>v.name===g.name);if(b?b.value=w:_.push({name:g.name,value:w}),!y&&!!w!=!!g.value&&(y=!0),u[g.name]=g.value,g.textureTransform&&g.value instanceof c.Texture){const v=g.value;u[Pd]||(u[Pd]=[]),u[Pd].push({name:g.name,offsetX:v.offset.x,offsetY:v.offset.y,repeatX:v.repeat.x,repeatY:v.repeat.y});const E=g.textureTransform;E.offset&&v.offset.copy(E.offset),E.repeat&&v.repeat.copy(E.repeat)}}y&&(u.needsUpdate=!0),u._forceRefresh=!0},lb=function(s,e,t,i,n,o){if(this[Ca]===void 0||!this[Ca].has(n))return;this[Ca].delete(n);const r=Sw(this);if(!r)return;const{block:a,owner:l}=r,h=a.overrides,d=n,u=d[Cd],p=a.getDefines(),m=Object.keys(p);let y=!1;if(m.length>0&&d.defines){for(const g of m)delete d.defines[g];y=!0}if(h.length===0){y&&(d.needsUpdate=!0,d._forceRefresh=!0);return}if(!u)return;const _=d[Pd];if(_&&_.length>0){for(const g of _){const w=h.find(b=>b.name===g.name);w?.value instanceof c.Texture&&(w.value.offset.set(g.offsetX,g.offsetY),w.value.repeat.set(g.repeatX,g.repeatY))}_.length=0}for(const g of h){const w=u.find(b=>b.name===g.name);w&&(!y&&!!g.value!=!!w.value&&(y=!0),d[g.name]=w.value)}y&&(d.needsUpdate=!0),d._forceRefresh=!0};function JO(s,e){s.type==="Group"?s.children.forEach(t=>{(t.type==="Mesh"||t.type==="SkinnedMesh")&&cb(t,s,e)}):(s.type==="Mesh"||s.type==="SkinnedMesh")&&cb(s,s,e)}function cb(s,e,t){if(!fs.isHooked(s,e)){if(fs.addHook(s,e),s["needle:materialPropertyBlock"]=t,!s.onBeforeRender)s.onBeforeRender=ab;else{const i=s.onBeforeRender;s.onBeforeRender=function(n,o,r,a,l,h){i.call(this,n,o,r,a,l,h),ab.call(this,n,o,r,a,l,h)}}if(!s.onAfterRender)s.onAfterRender=lb;else{const i=s.onAfterRender;s.onAfterRender=function(n,o,r,a,l,h){lb.call(this,n,o,r,a,l,h),i.call(this,n,o,r,a,l,h)}}s.onBeforeRenderListPush=KO,s.onAfterRenderListPush=ZO}}const Hh=new Map;function Ag(s,e){if(Hh.has(s))return Hh.get(s);const t=new URL(s,window.location.href),i=eM(t,e);return Hh.set(s,i),i.finally(()=>{Hh.delete(s)}),i}async function eM(s,e){if(!s)return Promise.resolve(null);const t=s.pathname,i=s.toString().toLowerCase().includes("pmrem")||s.searchParams.get("pmrem")!=null,n=t.endsWith(".exr"),o=t.endsWith(".hdr"),r=t.endsWith(".ktx2");let a;if(n)a=new X.EXRLoader;else if(o)a=new X.RGBELoader;else if(r){const{ktx2Loader:u}=re.createLoaders(e);a=u}else a=new c.TextureLoader;const l=s.toString();return await a.loadAsync(l).then(u=>{if(u){const p=t.lastIndexOf("/");u.name=t.substring(p>=0?p+1:0),i?u.mapping=c.CubeUVReflectionMapping:u.mapping=c.EquirectangularRefractionMapping,a instanceof c.TextureLoader&&(u.colorSpace=c.SRGBColorSpace)}return u}).catch(u=>(console.warn("Failed to load texture from url:",s),null))}var tM=Object.defineProperty,iM=Object.getOwnPropertyDescriptor,Du=(s,e,t,i)=>{for(var n=i>1?void 0:i?iM(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&&tM(e,t,n),n};const Xr=x("debugreflectionprobe"),hb=x("noreflectionprobe");let Fo=null;const nM=Symbol("reflectionProbeKey"),eh=class an extends R{static _probes=new Map;static testBox=new c.Box3;static isUsingReflectionProbe(e){return!!e[nM]}static onEnabled=new ne;static onDisabled=new ne;static get(e,t,i,n){if(!e||e.isObject3D!==!0||hb)return null;const o=an._probes.get(t);if(o){for(const r of o)if(r.__didAwake||r.__internalAwake(),r.activeAndEnabled){if(n){if(r.gameObject===n)return r}else if(r.isInBox(e))return Xr&&console.log("Found reflection probe",e.name,r.name),r}}return Xr&&console.debug("Did not find reflection probe",e.name,i,e),null}_texture;_textureUrlInFlight;set texture(e){if(this._texture!==e){if(typeof e=="string"){Xr&&console.debug(`[ReflectionProbe] Loading reflection probe texture from URL: ${e}`),this._textureUrlInFlight=e;const t=ws(this.sourceId,e);Ag(t,this.context.renderer).then(i=>{this._textureUrlInFlight===e&&i&&(this._textureUrlInFlight=void 0,Xr&&console.debug(`[ReflectionProbe] Successfully loaded reflection probe texture: ${e}`),this.texture=i)});return}this.__didAwake&&(this._textureUrlInFlight=void 0),this._texture=e,Xr&&console.debug("[ReflectionProbe] Set reflection probe texture "+(e?.name||"(removed)")),e&&(e instanceof c.CubeTexture||e.mapping===c.CubeUVReflectionMapping||e.mapping!==c.EquirectangularReflectionMapping&&(e.mapping=c.EquirectangularReflectionMapping),e.colorSpace=c.LinearSRGBColorSpace,e.needsUpdate=!0)}}get texture(){return this._texture}intensity=1;center=new c.Vector3;size=new c.Vector3(1,1,1);__lightmapIntensityScale=!0;isInBox(e){return Fo??=new c.Box3,Fo.setFromCenterAndSize(this.gameObject.worldPosition.add(this.center),this.size),ri([e],void 0,void 0,an.testBox),an.testBox.isEmpty()?Fo.containsPoint(e.worldPosition):Fo?.intersectsBox(an.testBox)}constructor(){super(),an._probes.has(this.context)||an._probes.set(this.context,[]),an._probes.get(this.context)?.push(this)}awake(){this._texture&&(this._texture.mapping!==c.CubeUVReflectionMapping&&(this._texture.mapping=c.EquirectangularReflectionMapping),this._texture.colorSpace=c.LinearSRGBColorSpace,this._texture.needsUpdate=!0)}update(){Xr&&(Fo??=new c.Box3,Fo.setFromCenterAndSize(this.gameObject.worldPosition.add(this.center),this.size),B.DrawWireBox3(Fo,5592320))}onEnable(){an.onEnabled?.invoke(this)}onDisable(){an.onDisabled?.invoke(this)}start(){this._texture||console.warn(`[ReflectionProbe] Missing texture. Please assign a custom cubemap texture. To use reflection probes assign them to your renderer's "anchor" property.`)}onDestroy(){const e=an._probes.get(this.context);if(e){const t=e.indexOf(this);t>=0&&e.splice(t,1)}}apply(e){if(hb||!this.enabled||!this.texture)return;const t=ys.get(e);t.setOverride("envMap",this.texture),t.setOverride("envMapRotation",this.gameObject.rotation);let i=this.intensity;this.__lightmapIntensityScale&&t.getOverride("lightMap")&&(i/=Math.PI),t.setOverride("envMapIntensity",i)}unapply(e){const t=ys.get(e);t&&t.getOverride("envMap")?.value===this.texture&&t.removeOveride("envMap")}};Du([f([c.Texture,String])],eh.prototype,"texture",1);Du([f()],eh.prototype,"intensity",2);Du([f(c.Vector3)],eh.prototype,"center",2);Du([f(c.Vector3)],eh.prototype,"size",2);let os=eh;const Jf=x("debugexr");class sM{get name(){return"EXT_texture_exr"}parser;constructor(e){this.parser=e,Jf&&console.log(e)}loadTexture(e){const t=this.name,i=this.parser,o=i.json.textures[e];if(Jf&&console.log("EXT_texture_exr.loadTexture",e,o),!o.extensions||!o.extensions[t])return null;const r=o.extensions[t],a=new X.EXRLoader(i.options.manager);return Jf&&console.log("EXT_texture_exr.loadTexture",r),i.loadTextureImage(e,r.source,a)}}typeof window<"u"&&window.addEventListener("unhandledrejection",s=>{});const Cn=rt,qh="$___Export_Components",oM="NEEDLE_components";class rM{[qo]}class aM{node;nodeIndex;nodeDef;constructor(e,t,i){this.node=e,this.nodeIndex=t,this.nodeDef=i}}class Cw{get name(){return oM}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[qh]=i,!0)}afterSerializeUserData(e,t){if(e.type==="Scene"&&Cn&&console.log("DONE",JSON.stringify(t)),e[qh]===void 0)return;const i=e[qh];delete e[qh],i!==null&&(e.userData.components=i)}writeNode(e,t){const i=this.writer.json.nodes.length;Cn&&console.log(e.name,i,e.uuid);const n=new aM(e,i,t);this.exportContext[i]=n,this.objectToNodeMap[e.uuid]=i}afterParse(e){Cn&&console.log("AFTER",e);for(const t in this.exportContext){const i=this.exportContext[t],n=i.node,o=i.nodeDef,r=i.nodeIndex,a=n.userData?.components;if(!a||a.length<=0)continue;const l=new rM;o.extensions=o.extensions||{},o.extensions[this.name]=l,this.context.object=n,this.context.nodeId=r,this.context.objectToNode=this.objectToNodeMap;const h=[];for(const d of a){this.context.target=d;const u=un().writeBuiltinComponentData(d,this.context);u!==null&&h.push(u)}h.length>0&&(l[qo]=h,Cn&&console.log("DID WRITE",n,"nodeIndex",r,h))}}parser;nodeToObjectMap={};gltf=null;beforeRoot(){return Cn&&console.log("BEGIN LOAD"),this.nodeToObjectMap={},null}async afterRoot(e){this.gltf=e;const t=e.parser,i=t?.extensions;if(!i)return;const n=i[this.name];Cn&&console.log("After root",e,this.parser,i);const o=[];if(n===!0){const r=t.json.nodes;if(r){for(let a=0;a<r.length;a++){const l=await t.getDependency("node",a);this.nodeToObjectMap[a]=l}for(let a=0;a<r.length;a++){const l=r[a],h=a,d=l.extensions;if(!d)continue;const u=d[this.name];if(!u)continue;Cn&&console.log("NODE",l);const p=this.nodeToObjectMap[h];if(!p){console.error("Could not find object for node index: "+h,l,t);continue}_u(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[qo];if(o){const r=new Array;Cn&&console.log(i.name,o);for(const a in o){const l=o[a];if(Cn&&console.log("Serialized data",JSON.parse(JSON.stringify(l))),(l?.name==="MeshRenderer"||l?.name==="SkinnedMeshRenderer")&&!l.sharedMaterials){let h=!1;if("mesh"in t){const d=t.mesh;if(typeof d=="number"&&e.parser){const u=e.parser.json.meshes?.[d];u?.primitives&&(l.sharedMaterials=u.primitives.map(p=>"/materials/"+(p.material??0)),h=!0)}}!h&&(Cn||A())&&console.warn(`[NEEDLE_components] Component '${l.name}' on object '${i.name}' is not added to a mesh or failed to retrieve materials from glTF.`)}l&&this.parser&&r.push(ag(this.parser,l).catch(h=>console.error(`Error while resolving references (see console for details)
|
|
1001
|
-
`,h,i,l))),i.userData=i.userData||{},i.userData[qo]=i.userData[qo]||[],i.userData[qo].push(l)}await Promise.all(r).catch(a=>{console.error("Error while loading components",a)})}}}const db="NEEDLE_gameobject_data";class lM{get name(){return db}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[db];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 ub="NEEDLE_lighting_settings",ra=x("debugenvlight");class cM{get name(){return ub}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[ub];if(i){ra&&console.log('Loaded "'+this.name+'", src: "'+this.sourceId+'"',i);let n;if(e.scene.children.length===1){const o=e.scene.children[0];n=S.addComponent(o,Jd,{},{callAwake:!1})}else{const o=new c.Object3D;o.name="LightSettings "+this.sourceId,e.scene.add(o),n=S.addComponent(o,Jd,{},{callAwake:!1})}n.sourceId=this.sourceId,n.ambientIntensity=i.ambientIntensity,n.ambientLight=new c.Color().fromArray(i.ambientLight),Array.isArray(i.ambientTrilight)&&(n.ambientTrilight=i.ambientTrilight.map(o=>new c.Color().fromArray(o))),n.ambientMode=i.ambientMode,n.environmentReflectionSource=i.environmentReflectionSource}}return null}}ce.registerCallback(le.ContextCreated,s=>{const e=s.context,t=S.findObjectOfType(Jd,e);t?.sourceId&&(t.enabled=!0)});class Jd extends R{ambientMode=Sa.Skybox;ambientLight;ambientTrilight;ambientIntensity=1;environmentReflectionSource=Hd.Skybox;_hasReflection=!1;_ambientLightObj;_hemisphereLightObj;awake(){if(this.sourceId){const t=this.environmentReflectionSource===Hd.Skybox?Tn.Skybox:Tn.Reflection,i=this.context.lightmaps.tryGet(this.sourceId,t,0);this._hasReflection=i!=null,i&&this.context.sceneLighting.internalRegisterReflection(this.sourceId,i)}this.enabled=!1,this.context.sceneLighting.internalRegisterSceneLightSettings(this),ra&&window.addEventListener("keydown",t=>{this.destroyed||t.key==="l"&&(this.enabled=!this.enabled)});const e=this.gameObject.userData?.components;if(e){const t=e.indexOf(this);e.splice(t,1),e.push(this)}}onDestroy(){this.context.sceneLighting.internalUnregisterSceneLightSettings(this)}calculateIntensityFactor(e){const t=Math.max(e.r,e.g,e.b);return 2.2*I.lerp(0,1.33,t)}onEnable(){if(ra&&console.warn("💡🟡 >>> Enable lighting",this.sourceId,this.enabled,this),this.ambientMode==Sa.Flat){if(this.ambientLight&&!this._ambientLightObj){const e=this.calculateIntensityFactor(this.ambientLight);this._ambientLightObj=new c.AmbientLight(this.ambientLight,this.ambientIntensity*e),ra&&console.log("Created ambient light",this.sourceId,this._ambientLightObj,this.ambientIntensity,e)}this._ambientLightObj&&this.gameObject.add(this._ambientLightObj)}else if(this.ambientMode===Sa.Trilight){if(this.ambientTrilight){const e=this.ambientTrilight[0],t=this.ambientTrilight[this.ambientTrilight.length-1],i=this.calculateIntensityFactor(t);this._hemisphereLightObj=new c.HemisphereLight(t,e,this.ambientIntensity*i),this.gameObject.add(this._hemisphereLightObj),ra&&console.log("Created hemisphere ambient light",this.sourceId,this._hemisphereLightObj,this.ambientIntensity,i)}}else this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent();this.sourceId&&(this.context.domElement.getAttribute("environment-image")||this.context.sceneLighting.internalEnableReflection(this.sourceId))}onDisable(){ra&&console.warn("💡⚫ <<< Disable lighting:",this.sourceId,this),this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent(),this.sourceId&&this.context.sceneLighting.internalDisableReflection(this.sourceId)}}exports.MaterialX=void 0;(s=>{async function e(t,i){if(!t)throw new Error("URL or XML string is required to load a MaterialX material");const n=await T.MaterialX.load(),o=t.trimStart().startsWith("<"),r=o?t:await fetch(t).then(h=>h.text()).catch(console.error);if(!r)return console.warn("Failed to load MaterialX file from url",t),null;let a;if(i?.url||!o){const h=(i?.url||t).split("/");h.pop(),a=h.join("/")}const l=new c.TextureLoader;return n.Experimental_API.createMaterialXMaterial(r,i?.materialNameOrIndex??0,{getTexture:async h=>(!h.startsWith("http")&&!h.startsWith("data:")&&!h.startsWith("blob:")&&!h.startsWith("file:")&&a&&(h=a+"/"+h),l.loadAsync(h).catch(d=>{console.warn(`Failed to load texture for MaterialX material ${h}`,d)}))},{cacheKey:t})}s.loadFromUrl=e})(exports.MaterialX||(exports.MaterialX={}));class 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 bo.createPrimitive("ShaderBall",{material:e})}}class dM{constructor(e,t,i,n){this.context=e,this.loader=t,this.url=i,this.parser=n}get name(){return"materialx-loading-helper"}mtlxLoader;async beforeRoot(){if(this.parser.json.extensions?.NEEDLE_materials_mtlx){const t=await T.MaterialX.load();try{this.mtlxLoader=new t.MaterialXLoader(this.parser,{cacheKey:`${this.url}:materialx`,parameters:{precision:this.context.renderer?.capabilities.precision}},{getFrame:()=>this.context.time.frame,getTime:()=>this.context.time.time})}catch(i){console.error(i)}}}loadMaterial(e){return this.mtlxLoader?this.mtlxLoader.loadMaterial(e):null}}var Pw=(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))(Pw||{});const Mn=x("debugcustomshader"),Qr="NEEDLE_techniques_webgl";class uM{objectToWorldMatrix=new c.Matrix4;worldToObjectMatrix=new c.Matrix4;objectToWorld=new Array;worldToObject=new Array;updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),Gd(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),Gd(this.worldToObjectMatrix,this.worldToObject)}}class ve extends c.RawShaderMaterial{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);clone(){const e=super.clone();return Ow(e),e}constructor(e,...t){super(...t),this.identifier=e,Mn&&console.log(this),this.type="NEEDLE_CUSTOM_SHADER",this.uniforms[this._objToWorldName]||(this.uniforms[this._objToWorldName]={value:[]}),this.uniforms[this._worldToObjectName]||(this.uniforms[this._worldToObjectName]={value:[]}),this.uniforms[this._viewProjectionName]||(this.uniforms[this._viewProjectionName]={value:[]}),this.uniforms[this._sphericalHarmonicsName],(this.depthTextureUniform||this.opaqueTextureUniform)&&U.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}dispose(){super.dispose();const e=U.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&U.Current.pre_render_callbacks.splice(e,1)}_sphericalHarmonicsName="unity_SpecCube0";_objToWorldName="hlslcc_mtx4x4unity_ObjectToWorld";_worldToObjectName="hlslcc_mtx4x4unity_WorldToObject";static viewProjection=new c.Matrix4;static _viewProjectionValues=[];_viewProjectionName="hlslcc_mtx4x4unity_MatrixVP";static viewMatrix=new c.Matrix4;static _viewMatrixValues=[];_viewMatrixName="hlslcc_mtx4x4unity_MatrixV";static _worldSpaceCameraPosName="_WorldSpaceCameraPos";static _worldSpaceCameraPos=new c.Vector3;static _mainLightColor=new c.Vector4;static _mainLightPosition=new c.Vector3;static _lightData=new c.Vector4;_rendererData=new uM;get depthTextureUniform(){if(this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&U.Current.setRequireColor(!0),this.depthTextureUniform&&U.Current.setRequireDepth(!0)}onBeforeRender(e,t,i,n,o,r){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,o)}onUpdateUniforms(e,t){const i=U.Current;if(e&&(ve.viewProjection&&this.uniforms[this._viewProjectionName]&&(ve.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),Gd(ve.viewProjection,ve._viewProjectionValues)),ve.viewMatrix&&this.uniforms[this._viewMatrixName]&&(ve.viewMatrix.copy(e.matrixWorldInverse),Gd(ve.viewMatrix,ve._viewMatrixValues)),this.uniforms[ve._worldSpaceCameraPosName]&&ve._worldSpaceCameraPos.setFromMatrixPosition(e.matrixWorld)),this.uniforms._TimeParameters&&(this.uniforms._TimeParameters.value=i.sceneLighting.timeVec4),this.uniforms._Time){const a=this.uniforms._Time.value;a.x=i.sceneLighting.timeVec4.x/20,a.y=i.sceneLighting.timeVec4.x,a.z=i.sceneLighting.timeVec4.x*2,a.w=i.sceneLighting.timeVec4.x*3}if(this.uniforms._SinTime){const a=this.uniforms._SinTime.value;a.x=Math.sin(i.sceneLighting.timeVec4.x/8),a.y=Math.sin(i.sceneLighting.timeVec4.x/4),a.z=Math.sin(i.sceneLighting.timeVec4.x/2),a.w=Math.sin(i.sceneLighting.timeVec4.x)}if(this.uniforms._CosTime){const a=this.uniforms._CosTime.value;a.x=Math.cos(i.sceneLighting.timeVec4.x/8),a.y=Math.cos(i.sceneLighting.timeVec4.x/4),a.z=Math.cos(i.sceneLighting.timeVec4.x/2),a.w=Math.cos(i.sceneLighting.timeVec4.x)}if(this.uniforms.unity_DeltaTime){const a=this.uniforms.unity_DeltaTime.value;a.x=i.time.deltaTime,a.y=1/i.time.deltaTime,a.z=i.time.smoothedDeltaTime,a.w=1/i.time.smoothedDeltaTime}const n=i.mainLight;if(n){const a=Y(n.gameObject,ve._mainLightPosition);this.uniforms._MainLightPosition={value:a.normalize()},ve._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:ve._mainLightColor};const l=n.intensity;ve._lightData.z=l,this.uniforms.unity_LightData={value:ve._lightData}}if(e&&(ve.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=ve._viewProjectionValues),ve.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=ve._viewMatrixValues),this.uniforms[ve._worldSpaceCameraPosName]&&(this.uniforms[ve._worldSpaceCameraPosName]={value:ve._worldSpaceCameraPos}),i.mainCameraComponent)){if(this.uniforms._ProjectionParams){const a=this.uniforms._ProjectionParams.value;a.x=1,a.y=i.mainCameraComponent.nearClipPlane,a.z=i.mainCameraComponent.farClipPlane,a.w=1/a.z,this.uniforms._ProjectionParams.value=a}if(this.uniforms._ZBufferParams){const a=this.uniforms._ZBufferParams.value,l=i.mainCameraComponent;a.x=1-l.farClipPlane/l.nearClipPlane,a.y=l.farClipPlane/l.nearClipPlane,a.z=a.x/l.farClipPlane,a.w=a.y/l.farClipPlane,this.uniforms._ZBufferParams.value=a}if(this.uniforms._ScreenParams){const a=this.uniforms._ScreenParams.value;a.x=i.domWidth,a.y=i.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScreenParams.value=a}if(this.uniforms._ScaledScreenParams){const a=this.uniforms._ScaledScreenParams.value;a.x=i.domWidth,a.y=i.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScaledScreenParams.value=a}}const o=this.depthTextureUniform;o&&(o.value=i.depthTexture);const r=this.opaqueTextureUniform;if(r&&(r.value=i.opaqueColorTexture),t){const a=this._rendererData;a.updateFrom(t),this.uniforms[this._worldToObjectName].value=a.worldToObject,this.uniforms[this._objToWorldName].value=a.objectToWorld}this.uniformsNeedUpdate=!0}}class fM{get name(){return Qr}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){const t=this.parser.json.materials[e];if(!t)return Mn&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[Qr])return Mn&&console.log(`Material ${e} does not use NEEDLE_techniques_webgl`),null;Mn&&console.log(`Material ${e} uses NEEDLE_techniques_webgl`,t);const i=t.extensions[Qr].technique;if(i<0)return console.debug(`Material ${e} does not have a valid technique index`),null;const n=this.parser.json.extensions[Qr];if(!n)return Mn?console.error("Missing shader data",this.parser.json.extensions):console.debug("Missing custom shader data in parser.json.extensions"),null;Mn&&console.log(n);const o=n.techniques[i];return o?new Promise(async(r,a)=>{const l=await sP(n,o.program),h=l?.fragmentShader,d=l?.vertexShader;if(!h||!d)return a();Mn&&console.log("loadMaterial",t,l);const u={},p=o.uniforms;(d.includes("_Time")||h.includes("_Time"))&&(u._Time={value:new c.Vector4(0,0,0,0)}),(d.includes("_SinTime")||h.includes("_SinTime"))&&(u._SinTime={value:new c.Vector4(0,0,0,0)}),(d.includes("_CosTime")||h.includes("_CosTime"))&&(u._CosTime={value:new c.Vector4(0,0,0,0)}),(d.includes("unity_DeltaTime")||h.includes("unity_DeltaTime"))&&(u.unity_DeltaTime={value:new c.Vector4(0,0,0,0)});for(const w in p){const b=w;switch(b){case"_TimeParameters":const v=new c.Vector4;u[b]={value:v};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":u[b]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":u[b]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":u[b]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":u[b]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":u[b]={value:null};break}}let m=!1;if(t.extensions&&t.extensions[Qr]){const w=t.extensions[Qr];if(w.technique===i){Mn&&console.log(t.name,"Material Properties",w);for(const b in w.values){const v=w.values[b];if(typeof v=="string"){if(v.startsWith("/textures/")){const E=v.substring(10),O=Number.parseInt(E);if(O>=0){const M=await this.parser.getDependency("texture",O);M instanceof c.Texture&&(M.colorSpace=c.LinearSRGBColorSpace,M.needsUpdate=!0),u[b]={value:M};continue}}if(b==="alphaMode"){v==="BLEND"&&(m=!0);continue}}if(Array.isArray(v)&&v.length===4){u[b]={value:new c.Vector4(v[0],v[1],v[2],v[3])};continue}u[b]={value:v}}}}const y=new ve(this.identifier,{name:t.name??"",uniforms:u,vertexShader:d,fragmentShader:h,lights:!1});switch(y.glslVersion=c.GLSL3,y.vertexShader=y.vertexShader.replace("#version 300 es",""),y.fragmentShader=y.fragmentShader.replace("#version 300 es",""),u._Cull?.value){case 0:y.side=c.DoubleSide;break;case 1:y.side=c.BackSide;break;case 2:y.side=c.FrontSide;break;default:y.side=c.FrontSide;break}switch(u._ZTest?.value){case 3:y.depthTest=!0,y.depthFunc=c.EqualDepth;break;case 6:y.depthTest=!0,y.depthFunc=c.NotEqualDepth;break;case 2:y.depthTest=!0,y.depthFunc=c.LessDepth;break;case 4:y.depthTest=!0,y.depthFunc=c.LessEqualDepth;break;case 5:y.depthTest=!0,y.depthFunc=c.GreaterDepth;break;case 7:y.depthTest=!0,y.depthFunc=c.GreaterEqualDepth;break;case 8:y.depthTest=!1,y.depthFunc=c.AlwaysDepth;break}y.transparent=m,m&&(y.depthWrite=!1),iP(u),y.onUpdateUniforms();for(const w in p){const b=w,v=p[w].type;u[b]?.value===void 0&&(v===Pw.SAMPLER_2D?(u[b]={value:eP},console.warn("Missing/unassigned texture, fallback to white: "+b)):b==="unity_OrthoParams"||console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+b,p[w]))}Mn&&console.log(y.uuid,u),Ow(y),r(y)}):null}}function Ow(s){if(s.uniforms){Mn&&console.log("Uniforms:",s.uniforms);for(const t in s.uniforms)switch(e(t,t),t){case"_Color":e("color",t);break;case"_map":e("map",t);break}}function e(t,i){Object.getOwnPropertyDescriptor(s,t)||Object.defineProperty(s,t,{get:()=>s.uniforms[i].value,set:n=>{s.uniforms[i].value=n,s.needsUpdate=!0}})}}const pM=x("debugextensions");let eu;const mM=Promise.resolve().then(()=>require("./vendor-CipoooTV.umd.cjs")).then(s=>s.index$2).then(async s=>(eu=s.GLTFAnimationPointerExtension,eu)).catch(s=>{console.warn("Failed to import GLTFLoaderAnimationPointer. Please use @needle-tools/three-animationpointer for full KHR_animation support",s)}),mr=new Array;function gM(s){mr.includes(s)||mr.push(s)}function yM(s){const e=mr.indexOf(s);e>=0&&mr.splice(e,1)}function Dg(s){if(s instanceof X.GLTFLoader){const e=new Cw;return s.register(t=>(e.parser=t,e)),e}return null}class _M{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 tu(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 lM(o)),s.register(o=>new O1(o)),s.register(o=>new Y1(o,e.lightmaps,i)),s.register(o=>new cM(o,i,e)),s.register(o=>new fM(o,i)),s.register(o=>new eo(o,i)),s.register(o=>new re.NEEDLE_progressive(o)),s.register(o=>new sM(o)),s.register(o=>new wu(o)),s.register(o=>new dM(e,s,t,o)),t0()&&s.register(o=>new xa(o)),await mM.catch(o=>{}),s.register(o=>{if(eu){const r=new eu(o);return r.setAnimationPointerResolver.bind(r)(new _M),r}else return(pM||A())&&console.error("Missing KHR_animation_pointer extension..."),{name:"KHR_animation_pointer_NOT_AVAILABLE"}});for(const o of mr)o.onImport&&o.onImport(s,t,e)}function Lg(s,e){for(const t of mr)t.onExport&&t.onExport(s,e)}function Mw(s,e,t){for(const i of mr)i.onLoaded&&i.onLoaded(s,e,t)}const kt=x("debuginstancing");class gr{static instance=new gr;static getStartInstanceCount=e=>4;objs=[];setup(e,t,i,n,o,r=0){e.applySettings(t);const a=this.tryCreateOrAddInstance(t,i,o);if(a){n===null&&(n=[]),n.push(a);const l=a.object.material;Array.isArray(l)?l.forEach(u=>re.NEEDLE_progressive.assignTextureLOD(u,0)):re.NEEDLE_progressive.assignTextureLOD(l,0);const h=a.object,d=h.geometry;re.NEEDLE_progressive.assignMeshLOD(h,0).then(u=>{u&&d!=u&&a.setGeometry(u)})}else if(r<=0&&t.type!=="Mesh"){const l=r+1;for(const h of t.children)n=this.setup(e,h,i,n,o,l)}return r===0&&o.useMatrixWorldAutoUpdate&&n&&n.length>=0&&this.autoUpdateInstanceMatrix(t),n}tryCreateOrAddInstance(e,t,i){if(e.type==="Mesh"){const n=i.foundMeshes;if(i.foundMeshes+=1,!i.rend.enableInstancing)return null;if(i.rend.enableInstancing!==!0){if(n>=i.rend.enableInstancing.length)return kt&&console.error("Something is wrong with instance setup",e,i.rend.enableInstancing,n),null;if(!i.rend.enableInstancing[n])return null}const o=e,r=o.material;for(const u of this.objs){if(!u.canAdd(o.geometry,r))continue;return u.addInstance(o)}let a=gr.getStartInstanceCount(e);(!a||a<0)&&(a=4);let l=e.name;l?.length||(l=sv());const h=new bM(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[bc]||i.equals(a)===!1)&&(i.copy(a),e[bc]=!0),a};e.matrixWorld.multiplyMatrices=n}}class hr{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[r0]=t,this.meshInformation=Xo(e.geometry),hr.all.push(this)}updateMeshInformation(){const e=Xo(this.object.geometry),t=this.meshInformation.vertexCount,i=this.meshInformation.indexCount;return Object.assign(this.meshInformation,e),t!==this.meshInformation.vertexCount||i!==this.meshInformation.indexCount}updateInstanceMatrix(e=!1,t=!0){this.__instanceIndex<0||(t&&this.object.updateWorldMatrix(!0,e),this.renderer.updateInstance(this.object.matrixWorld,this.__instanceIndex))}setMatrix(e){this.__instanceIndex<0||this.renderer.updateInstance(e,this.__instanceIndex)}setGeometry(e){if(this.__geometryIndex<0)return!1;const t=this;if(this.vertexCount>this.__reservedVertexRange)return i(`Instancing: Can not update geometry (${this.name}), reserved vertex range is too small: ${this.__reservedVertexRange.toLocaleString()} < ${this.vertexCount.toLocaleString()} vertices for ${this.name}`);if(this.indexCount>this.__reservedIndexRange)return i(`Instancing: Can not update geometry (${this.name}), reserved index range is too small: ${this.__reservedIndexRange.toLocaleString()} < ${this.indexCount.toLocaleString()} indices for ${this.name}`);return this.renderer.updateGeometry(e,this.__geometryIndex);function i(n){return t.updateMeshInformation()&&(t.renderer.remove(t,!0),t.renderer.add(t))?!0:((A()||kt)&&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=hr.all.indexOf(this);t>=0&&hr.all.splice(t,1)}}}class bM{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(),kt&&this._batchedMesh.boundingSphere){const i=this._batchedMesh.boundingSphere;B.DrawWireSphere(i.center,i.radius,65280)}}_context;_batchedMesh;_handles=[];_geometryIds=new WeakMap;_maxInstanceCount;_currentInstanceCount=0;_currentVertexCount=0;_currentIndexCount=0;_maxVertexCount;_maxIndexCount;static nullMatrix=new c.Matrix4;canAdd(e,t){return this._maxVertexCount>1e7||t!==this.material||!this.validateGeometry(e)?!1:!!(!this.mustGrow(e)||this.allowResize)}_needUpdateBounds=!1;_debugMaterial=null;getBatchedMeshName(){return this.name?`${this.name} (BatchedMesh)`:"BatchedMesh"}constructor(e,t,i,n,o){this.name=e,this.geometry=t,this.material=i,this._context=o,this._maxInstanceCount=Math.max(2,n),kt&&(this._debugMaterial=fb());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[zl]=!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),kt&&console.log(`Instanced renderer (${this.name}) created with ${this._maxInstanceCount} instances, ${this._maxVertexCount} max vertices and ${this._maxIndexCount} max indices for "${e}"`)}dispose(){kt&&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 hr(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()})
|
|
1002
|
-
`,i),A()){Uc("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),kt&&console.debug("[Instancing] UPDATE GEOMETRY at "+t,this._batchedMesh._geometryCount,e.name,Xo(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[zl]===!0&&(kt==="verbose"&&console.log("Update instancing bounds",this.name,this._batchedMesh.matrixWorldNeedsUpdate),this.updateBounds())};onAfterRender=()=>{this._batchedMesh.layers.disableAll()};validateGeometry(e){const t=this.geometry;for(const i in t.attributes)if(i!=="batchId"&&!e.hasAttribute(i))return A()&&console.warn(`BatchedMesh: Added geometry missing "${i}". All geometries must have consistent attributes.`),!1;return!0}markNeedsUpdate(){kt==="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=Xo(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(kt){const p=Xo(e);console.warn(`[Instancing] Growing Buffer
|
|
1003
|
-
Mesh: "${this.name}${e.name?.length?"/"+e.name:""}" (${p.vertexCount.toLocaleString()} vertices, ${p.indexCount.toLocaleString()} indices)
|
|
1004
|
-
Max count ${this._maxInstanceCount.toLocaleString()} → ${o.toLocaleString()}
|
|
1005
|
-
Max vertex count ${this._maxVertexCount.toLocaleString()} -> ${l.toLocaleString()}
|
|
1006
|
-
Max index count ${this._maxIndexCount.toLocaleString()} -> ${h.toLocaleString()}`),this._debugMaterial=fb()}else A()&&console.debug(`[Instancing] Growing Buffer
|
|
1007
|
-
Mesh: "${this.name}${e.name?.length?"/"+e.name:""}"
|
|
1008
|
-
Max count ${this._maxInstanceCount} → ${o}
|
|
1009
|
-
Max vertex count ${this._maxVertexCount.toLocaleString()} -> ${l.toLocaleString()}
|
|
1010
|
-
Max index count ${this._maxIndexCount.toLocaleString()} -> ${h.toLocaleString()}`);this._maxVertexCount=l,this._maxIndexCount=h;const d=new c.BatchedMesh(o,this._maxVertexCount,this._maxIndexCount,this._debugMaterial??this.material);d.name=this.getBatchedMeshName(),d.layers=this._batchedMesh.layers,d.castShadow=this._batchedMesh.castShadow,d.receiveShadow=this._batchedMesh.receiveShadow,d.visible=this._batchedMesh.visible,d[zl]=this._batchedMesh[zl],d.matrixAutoUpdate=this._batchedMesh.matrixAutoUpdate,d.matrixWorldNeedsUpdate=this._batchedMesh.matrixWorldNeedsUpdate,d.matrixAutoUpdate=this._batchedMesh.matrixAutoUpdate,d.matrixWorld.copy(this._batchedMesh.matrixWorld),d.matrix.copy(this._batchedMesh.matrix),this._batchedMesh.dispose(),this._batchedMesh.removeFromParent(),this._geometryIds=new WeakMap,this._batchedMesh=d,this._maxInstanceCount=o;const u=[...this._handles];this._handles=[];for(const p of u){if(t!==this._growId){kt&&console.warn("[Instancing] Aborting grow since another grow happened in the meantime");return}p&&p.__instanceIndex>=0&&(this.addGeometry(p),this._handles[p.__instanceIndex]=p)}this._context.scene.add(d)}tryEstimateVertexCountSize(e,t,i=1){const n=new Map;for(const p of this._handles)if(p&&p.__instanceIndex>=0&&p.object.geometry){if(n.has(p.object.geometry)){const m=n.get(p.object.geometry);m.count+=1}else{const y={count:1,...Xo(p.object.geometry)};n.set(p.object.geometry,y)}if(t&&t?.length>0){const m=t.indexOf(p.object.geometry);m!==-1&&t.splice(m,1)}}let o=0,r=0,a=0;for(const[p,m]of n)a+=1,o+=m.vertexCount,r+=m.indexCount;let h=Math.ceil(o/Math.max(1,a))*a,u=Math.ceil(r/Math.max(1,a))*a;if(t)for(const p of t){const m=Xo(p);m!=null&&(h+=m.vertexCount*i,u+=m.indexCount*i)}return kt&&console.log(`[Instancing] Estimated size for new buffer ${this.name}
|
|
1011
|
-
Geometries: ${a} (New: ${t?.length||0})
|
|
1012
|
-
Instances: ${e}
|
|
1013
|
-
Estimated Vertices: ${h.toLocaleString()}
|
|
1014
|
-
Estimated Indices: ${u.toLocaleString()}`),{vertexCount:h,indexCount:u}}addGeometry(e){const i=e.object.geometry;if(!i)return;let n=this._geometryIds.get(i);n==null?(kt&&console.warn(`[Instancing] > ADD NEW GEOMETRY "${e.name} (${i.name}; ${i.uuid})"
|
|
1015
|
-
Current Instances: ${this._currentInstanceCount}
|
|
1016
|
-
Max Vertices: ${e.maxVertexCount.toLocaleString()}
|
|
1017
|
-
Max Indices: ${e.maxIndexCount.toLocaleString()}
|
|
1018
|
-
Max Triangles: ${(e.maxIndexCount/3).toLocaleString()}`),n=this._batchedMesh.addGeometry(i,e.maxVertexCount,e.maxIndexCount),this._geometryIds.set(i,n),this._currentVertexCount+=e.maxVertexCount,this._currentIndexCount+=e.maxIndexCount):kt==="verbose"&&console.log(`[Instancing] > ADD INSTANCE "${e.name}"
|
|
1019
|
-
GEOMETRY_ID=${n}
|
|
1020
|
-
${this._currentInstanceCount} instances`);const o=this._batchedMesh.addInstance(n);e.__geometryIndex=n,e.__instanceIndex=o,e.__reservedVertexRange=e.maxVertexCount,e.__reservedIndexRange=e.maxIndexCount,this._batchedMesh.setMatrixAt(o,e.object.matrixWorld),kt&&console.debug(`[Instancing] > ADDED INSTANCE "${e.name}"
|
|
1021
|
-
GEOMETRY_ID=${n}
|
|
1022
|
-
${this._currentInstanceCount} instances
|
|
1023
|
-
Index: ${e.__instanceIndex}
|
|
1024
|
-
Vertices: ${this._currentVertexCount.toLocaleString()}/${this._maxVertexCount.toLocaleString()},
|
|
1025
|
-
Indices: ${this._currentIndexCount.toLocaleString()}/${this._maxIndexCount.toLocaleString()}`)}removeGeometry(e,t){if(e.__instanceIndex<0){console.warn("Cannot remove geometry, instance index is invalid",e.name);return}kt&&console.debug(`[Instancing] < REMOVE INSTANCE "${e.name}" at [${e.__instanceIndex}]
|
|
1026
|
-
GEOMETRY_ID=${e.__geometryIndex}
|
|
1027
|
-
${this._currentInstanceCount} instances
|
|
1028
|
-
Index: ${e.__instanceIndex}`),this._batchedMesh.deleteInstance(e.__instanceIndex)}}function Xo(s){if(!s)return A()&&console.error("Cannot get mesh information from null geometry"),{vertexCount:0,indexCount:0};let e=s.attributes?.position?.count||0,t=s.index?s.index.count:0;const i=re.NEEDLE_progressive.getMeshLODExtension(s);if(i){const n=i.lods[0];let o=n.vertexCount,r=n.indexCount;const a=Math.min(200,Math.ceil(o*.05));o+=a,r+=20,e=Math.max(e,o),t=Math.max(t,r)}return e=Math.ceil(e),t=Math.ceil(t),{vertexCount:e,indexCount:t}}function fb(){const s=new c.MeshStandardMaterial({color:new c.Color(Math.random(),Math.random(),Math.random())});return s.emissive=s.color,s.emissiveIntensity=.3,x("wireframe")&&(s.wireframe=!0),s}const Xh=x("debuglightmaps"),pb=Symbol("lightmapKey");class Ig{get lightmap(){return this.lightmapTexture}set lightmap(e){e!==this.lightmapTexture&&(this.lightmapTexture=e,this.applyLightmap(),this.updatePropertyBlockTexture(),this.lightmapTexture&&re.NEEDLE_progressive.assignTextureLOD(this.lightmapTexture,0).then(t=>{t?.isTexture&&(this.lightmapTexture=t,this.updatePropertyBlockTexture())}))}lightmapIndex=-1;lightmapScaleOffset=new c.Vector4(1,1,0,0);renderer;_isApplied=!1;get context(){return this.renderer.context}get gameObject(){return this.renderer.gameObject}lightmapTexture=null;constructor(e){this.renderer=e}init(e,t,i){console.assert(this.gameObject!==void 0&&this.gameObject!==null,"Missing gameobject",this),this.lightmapIndex=e,!(this.lightmapIndex<0)&&(this.lightmapScaleOffset=t,this.lightmapTexture=i,re.NEEDLE_progressive.assignTextureLOD(i,0).then(n=>{n?.isTexture&&(this.lightmapTexture=n,this.updatePropertyBlockTexture())}),Xh=="show"?(console.log("Lightmap:",this.gameObject.name,e,`
|
|
1029
|
-
ScaleOffset:`,t,`
|
|
1030
|
-
Texture:`,i),this.setLightmapDebugMaterial()):Xh&&console.log("Use debuglightmaps=show to render lightmaps only in the scene."),this.applyLightmap())}updateLightmapUniforms(e){}applyLightmap(){if(this._isApplied)return;if(this.gameObject.type==="Object3D"){Xh&&console.warn("Can not add lightmap. Is this object missing a renderer?",this.gameObject.name);return}const e=this.gameObject;if(this.ensureLightmapUvs(e),this.lightmapIndex>=0&&this.lightmapTexture){this.lightmapTexture.channel=1;const t=this.lightmapScaleOffset;for(let i=0;i<this.renderer.sharedMaterials.length;i++){const n=this.renderer.sharedMaterials[i];if(!n||n.lightMap===void 0)continue;Xh&&console.log("Setting lightmap on material",n.name,"for renderer",this.renderer.name),ys.get(this.gameObject).setOverride("lightMap",this.lightmapTexture,{offset:new c.Vector2(t.z,1-t.y-t.w),repeat:new c.Vector2(t.x,t.y)}),n[pb]=!0}this._isApplied=!0}}updatePropertyBlockTexture(){if(!this._isApplied||!this.lightmapTexture)return;this.lightmapTexture.channel=1;const e=this.lightmapScaleOffset;ys.get(this.gameObject).setOverride("lightMap",this.lightmapTexture,{offset:new c.Vector2(e.z,1-e.y-e.w),repeat:new c.Vector2(e.x,e.y)})}onUnset(){for(let t=0;t<this.renderer.sharedMaterials.length;t++){const i=this.renderer.sharedMaterials[t];i&&delete i[pb]}const e=ys.get(this.gameObject);e&&e.removeOveride("lightMap")}ensureLightmapUvs(e){if(e instanceof c.Mesh)e.geometry.getAttribute("uv1")||e.geometry.setAttribute("uv1",e.geometry.getAttribute("uv"));else if(e instanceof c.Group)for(const t of e.children)this.ensureLightmapUvs(t)}setLightmapDebugMaterial(){const e=this.lightmapScaleOffset;this.gameObject.material=new c.ShaderMaterial({vertexShader:`
|
|
1031
|
-
varying vec2 vUv1;
|
|
1032
|
-
void main()
|
|
1033
|
-
{
|
|
1034
|
-
vUv1 = uv1;
|
|
1035
|
-
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
|
1036
|
-
}
|
|
1037
|
-
`,fragmentShader:`
|
|
1038
|
-
uniform sampler2D lightMap;
|
|
1039
|
-
uniform float lightMapIntensity;
|
|
1040
|
-
varying vec2 vUv1;
|
|
1041
|
-
|
|
1042
|
-
// took from threejs 05fc79cd52b79e8c3e8dec1e7dca72c5c39983a4
|
|
1043
|
-
vec4 conv_sRGBToLinear( in vec4 value ) {
|
|
1044
|
-
return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );
|
|
1045
|
-
}
|
|
1046
|
-
|
|
1047
|
-
void main() {
|
|
1048
|
-
vec2 lUv = vUv1.xy * vec2(${e.x.toFixed(6)}, ${e.y.toFixed(6)}) + vec2(${e.z.toFixed(6)}, ${(1-e.y-e.w).toFixed(6)});
|
|
1049
|
-
|
|
1050
|
-
vec4 lightMapTexel = texture2D( lightMap, lUv);
|
|
1051
|
-
gl_FragColor = lightMapTexel;
|
|
1052
|
-
gl_FragColor.a = 1.;
|
|
1053
|
-
}
|
|
1054
|
-
`,defines:{USE_LIGHTMAP:""}})}}var vM=Object.defineProperty,Ps=(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&&vM(e,t,n),n};const aa=x("debugrenderer"),mb=x("debugskinnedmesh"),gb=x("noinstancing"),wM=x("wireframe");class kw{path=null;asset=null;default}class xM{_renderer;_targets=[];_indexMapMaxIndex;_indexMap;_changed=!1;get changed(){return this._changed}set changed(e){e===!0&&aa&&console.warn("SharedMaterials have changed: "+this._renderer.name),this._changed=e}is(e){return this._renderer===e}constructor(e,t){this._renderer=e;const i=this.setMaterial.bind(this),n=this.getMaterial.bind(this),o=e.gameObject;if(this._targets=[],o)switch(o.type){case"Group":this._targets=[...o.children];break;case"SkinnedMesh":case"Mesh":this._targets.push(o);break}let r=!1,a,l=0;for(let h=0;h<this._targets.length;h++){const d=this._targets[h];if(!d)continue;const u=d.material;if(u){u.shadowSide=u.side;for(let p=0;p<t.length;p++){const m=t[p];if(!m){r=!0;continue}if(u.name===m.name){a===void 0&&(a=new Map),a.set(p,h),l=Math.max(l,p);break}}}}if(r){this._indexMapMaxIndex=l,this._indexMap=a;const h=`Renderer ${e.name} was initialized with missing materials - this may lead to unexpected behaviour when trying to access sharedMaterials by index.`;console.warn(h),yi()&&fe("Found renderer with missing materials: please check the console for details.")}return new Proxy(this,{get(h,d){if(typeof d=="string"){const u=parseInt(d);if(!isNaN(u))return n(u)}return h[d]},set(h,d,u){return typeof d=="string"&&i(u,Number.parseInt(d)),Reflect.set(h,d,u)?(u instanceof c.Material&&(h.changed=!0),!0):!1}})}get length(){return this._indexMapMaxIndex!==void 0?this._indexMapMaxIndex+1:this._targets.length}*[Symbol.iterator](){for(let e=0;e<this.length;e++)yield this.getMaterial(e)}resolveIndex(e){const t=this._indexMap;return t&&t.has(e)?t.get(e):e}setMaterial(e,t){if(t=this.resolveIndex(t),t<0||t>=this._targets.length)return;const i=this._targets[t];!i||i.material===void 0||(i.material=e,this.changed=!0)}getMaterial(e){if(e=this.resolveIndex(e),e<0)return null;const t=this._targets;if(e>=t.length)return null;const i=t[e];return i?i.material:null}}const Qn=class Od extends R{static setInstanced(e,t){const i=Vc(e,Od);return i.setInstancingEnabled(t),i}static isInstanced(e){const t=xr(e,Od);return t?t.isInstancingActive:Ni.isUsingInstancing(e)}static setVisible(e,t){ls(e,t)}receiveShadows=!1;shadowCastingMode=0;lightmapIndex=-1;lightmapScaleOffset=new c.Vector4(1,1,0,0);enableInstancing=void 0;renderOrder=void 0;allowOcclusionWhenDynamic=!0;probeAnchor;reflectionProbeUsage=0;_lightmaps;get sharedMesh(){if(this.gameObject.type==="Mesh")return this.gameObject;if(this.gameObject.type==="SkinnesMesh")return this.gameObject;if(this.gameObject.type==="Group")return this.gameObject.children[0]}_sharedMeshes=[];get sharedMeshes(){if(this.destroyed||!this.gameObject)return this._sharedMeshes;if(this._sharedMeshes.length=0,this.gameObject.type==="Group")for(const e of this.gameObject.children)(e.type==="Mesh"||e.type==="SkinnedMesh")&&this._sharedMeshes.push(e);else(this.gameObject.type==="Mesh"||this.gameObject.type==="SkinnedMesh")&&this._sharedMeshes.push(this.gameObject);return this._sharedMeshes}get sharedMaterial(){return this.sharedMaterials?.[0]}set sharedMaterial(e){this.sharedMaterials[0]!==e&&(this.sharedMaterials[0]=e,this.applyLightmapping())}get material(){return this.sharedMaterials?.[0]}set material(e){this.sharedMaterial=e}_sharedMaterials;_originalMaterials;_probeAnchorLastFrame;set sharedMaterials(e){if(!this._originalMaterials)this._originalMaterials=e;else if(e){let t=!1;for(let i=0;i<this._sharedMaterials.length;i++){const n=i<e.length?e[i]:null;n&&n instanceof c.Material?this.sharedMaterials[i]=n:t||(t=!0,console.warn("Can not assign null as material: "+this.name,n))}}}get sharedMaterials(){if(this._originalMaterials===void 0)if(this.__didAwake)this._originalMaterials=[];else return null;return(!this._sharedMaterials||!this._sharedMaterials.is(this))&&(this._originalMaterials||(this._originalMaterials=[]),this._sharedMaterials=new xM(this,this._originalMaterials)),this._sharedMaterials}static get shouldSuppressInstancing(){return gb}_lightmapTextureOverride=void 0;get lightmap(){return this._lightmaps?.length?this._lightmaps[0].lightmap:null}set lightmap(e){if(this._lightmapTextureOverride=e,e===void 0&&(e=this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex)),this._lightmaps?.length)for(const t of this._lightmaps)t.lightmap=e}get hasLightmap(){const e=this.lightmap;return e!=null}allowProgressiveLoading=!0;_firstFrame=-1;registering(){this.enabled||this.setVisibility(!1)}awake(){if(this._firstFrame=this.context.time.frame,aa&&console.log("Renderer ",this.name,this),this.clearInstancingState(),this.probeAnchor&&aa&&this.probeAnchor.add(new c.AxesHelper(.2)),this._reflectionProbe=null,this.isMultiMaterialObject(this.gameObject)){for(const e of this.gameObject.children)this.context.addBeforeRenderListener(e,this.onBeforeRenderThree),e.layers.mask=this.gameObject.layers.mask;if(this.renderOrder!==void 0){let e=0;for(let t=0;t<this.gameObject.children.length;t++){const i=this.gameObject.children[t];if(!(!this.isMeshOrSkinnedMesh(i)||S.getComponent(i,Od))){if(this.renderOrder.length<=e){console.warn("Incorrect renderOrder element count",this,this.renderOrder.length+" but expected "+this.gameObject.children.length,"Index: "+e,"ChildElement:",i);continue}i.renderOrder=this.renderOrder[e],e+=1}}}}else this.isMeshOrSkinnedMesh(this.gameObject)?(this.context.addBeforeRenderListener(this.gameObject,this.onBeforeRenderThree),this.renderOrder!==void 0&&this.renderOrder.length>0&&(this.gameObject.renderOrder=this.renderOrder[0])):this.context.addBeforeRenderListener(this.gameObject,this.onBeforeRenderThree);if(this._lightmaps=void 0,this.applyLightmapping(),wM)for(let e=0;e<this.sharedMaterials.length;e++){const t=this.sharedMaterials[e];t&&(t.wireframe=!0)}}applyLightmapping(){if(this.lightmapIndex>=0&&!this._lightmaps){const e=this._lightmapTextureOverride!==void 0?this._lightmapTextureOverride:this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex);if(e){this._lightmaps||(this._lightmaps=[]);const t=new Ig(this);t.init(this.lightmapIndex,this.lightmapScaleOffset,e),this._lightmaps.push(t)}else aa&&console.warn(`[Renderer] No lightmaps found ${this.name} (${this.sourceId}, ${this.lightmapIndex})`)}}_isInstancingEnabled=!1;_handles=void 0;get isInstancingActive(){return this._handles!=null&&this._handles.length>0&&this._isInstancingEnabled}get instances(){if(!this._handles||this._handles.length<=0)return null;if(this._handlesTempArray.length=0,this._handles)for(const e of this._handles)this._handlesTempArray.push(e);return this._handlesTempArray}_handlesTempArray=[];setInstancingEnabled(e){if(this._isInstancingEnabled===e)return e&&(this._handles===void 0||this._handles!=null&&this._handles.length>0);if(this._isInstancingEnabled=e,e){if(this.enableInstancing===void 0&&(this.enableInstancing=!0),this._handles===void 0){if(this._handles=gr.instance.setup(this,this.gameObject,this.context,null,{rend:this,foundMeshes:0,useMatrixWorldAutoUpdate:this.useInstanceMatrixWorldAutoUpdate()}),this._handles)return S.markAsInstancedRendered(this.gameObject,!0),!0}else if(this._handles!==null){for(const t of this._handles)t.updateInstanceMatrix(!0),t.add();return S.markAsInstancedRendered(this.gameObject,!0),!0}}else{if(this._handles)for(const t of this._handles)t.remove(this.destroyed);return!0}return!1}clearInstancingState(){this._isInstancingEnabled=!1,this._handles=void 0}useInstanceMatrixWorldAutoUpdate(){return!0}start(){if(this.enableInstancing&&!gb&&(this.setInstancingEnabled(!0),Ni.markDirty(this.gameObject)),this.gameObject.frustumCulled=this.allowOcclusionWhenDynamic,this.isMultiMaterialObject(this.gameObject))for(let e=0;e<this.gameObject.children.length;e++){const t=this.gameObject.children[e];t.frustumCulled=this.allowOcclusionWhenDynamic}}onEnable(){this.sharedMeshes,this.setVisibility(!0),this._isInstancingEnabled||this.enableInstancing==!0||Array.isArray(this.enableInstancing)&&this.enableInstancing.some(t=>t)?this.__internalDidAwakeAndStart&&this.setInstancingEnabled(!0):this.enabled&&this.applyStencil(),this.updateReflectionProbe(),os.onEnabled.addEventListener(this.onReflectionProbeEnabled),os.onDisabled.addEventListener(this.onReflectionProbeDisabled)}onDisable(){this.setVisibility(!1),os.onEnabled.removeEventListener(this.onReflectionProbeEnabled),os.onDisabled.removeEventListener(this.onReflectionProbeDisabled),this._handles&&this._handles.length>0&&this.setInstancingEnabled(!1)}onDestroy(){if(this._handles=null,this.isMultiMaterialObject(this.gameObject))for(const e of this.gameObject.children)this.context.removeBeforeRenderListener(e,this.onBeforeRenderThree);else this.context.removeBeforeRenderListener(this.gameObject,this.onBeforeRenderThree)}onReflectionProbeEnabled=()=>{this.updateReflectionProbe()};onReflectionProbeDisabled=e=>{this._reflectionProbe===e&&(this._reflectionProbe.unapply(this.gameObject),this._reflectionProbe=null)};onBeforeRender(){if(this.gameObject){if((this._probeAnchorLastFrame!==this.probeAnchor||this._reflectionProbe?.activeAndEnabled===!1)&&(this._reflectionProbe?.unapply(this.gameObject),this.updateReflectionProbe()),aa==this.name&&this.gameObject instanceof c.Mesh){this.gameObject.geometry.computeBoundingSphere();const e=F(this.gameObject.geometry.boundingSphere.center).applyMatrix4(this.gameObject.matrixWorld);B.DrawWireSphere(e,this.gameObject.geometry.boundingSphere.radius,56831)}if(this.isMultiMaterialObject(this.gameObject)&&this.gameObject.children?.length>0)for(const e of this.gameObject.children)this.applySettings(e);else this.applySettings(this.gameObject);if(this.sharedMaterials?.changed&&(this.sharedMaterials.changed=!1,this.applyLightmapping()),this._handles?.length&&this.gameObject[bc]===!0){this.gameObject[bc]=!1;for(let t=this._handles.length-1;t>=0;t--)this._handles[t].updateInstanceMatrix();this.gameObject.matrixWorldNeedsUpdate=!1}if(this._handles&&this._handles.length<=0&&S.markAsInstancedRendered(this.gameObject,!1),this._isInstancingEnabled&&this._handles)for(let e=0;e<this._handles.length;e++){const t=this._handles[e];ls(t.object,!1)}if(this.reflectionProbeUsage!==0&&this._reflectionProbe?this._reflectionProbe.apply(this.gameObject):this.reflectionProbeUsage===0&&this._reflectionProbe&&this._reflectionProbe.unapply(this.gameObject),this._sharedMaterials)for(const e of this._sharedMaterials)e&&"envMap"in e&&"envMapIntensity"in e&&!os.isUsingReflectionProbe(e)&&(e.envMap=this.context.scene.environment,e.envMapRotation=this.context.scene.environmentRotation);else aa&&console.warn("[Renderer] sharedMaterials not initialized yet: "+this.name)}}onBeforeRenderThree=(e,t,i,n,o,r)=>{if(o.envMapIntensity!==void 0){const a=this.hasLightmap?Math.PI:1,l=this.context.scene.environmentIntensity;o.envMapIntensity=Math.max(0,l*this.context.sceneLighting.environmentIntensity/a)}if(this._lightmaps)for(const a of this._lightmaps)a.updateLightmapUniforms(o),a.applyLightmap()};onAfterRender(){if(this._isInstancingEnabled&&this._handles)for(let e=0;e<this._handles.length;e++){const t=this._handles[e];ls(t.object,!0)}this._reflectionProbe?.activeAndEnabled===!1&&this._reflectionProbe.unapply(this.gameObject),this.static&&this.gameObject.matrixAutoUpdate&&this.context.time.frame-this._firstFrame>=10&&(this.gameObject.matrixAutoUpdate=!1)}applyStencil(){eo.applyStencil(this)}applySettings(e){e.receiveShadow=this.receiveShadows,this.shadowCastingMode==1?e.castShadow=!0:e.castShadow=!1}_reflectionProbe=null;updateReflectionProbe(){this._reflectionProbe=null,this.reflectionProbeUsage!==0&&(this.startCoroutine(this._updateReflectionProbe(),ge.LateUpdate),this._probeAnchorLastFrame=this.probeAnchor)}*_updateReflectionProbe(){const e=this.probeAnchor||this.gameObject,t=!!this.probeAnchor;this._reflectionProbe=os.get(e,this.context,t,this.probeAnchor)}setVisibility(e){if(!this.isMultiMaterialObject(this.gameObject))ls(this.gameObject,e);else for(const t of this.gameObject.children)this.isMeshOrSkinnedMesh(t)&&ls(t,e)}isMultiMaterialObject(e){return e.type==="Group"}isMeshOrSkinnedMesh(e){return e.type==="Mesh"||e.type==="SkinnedMesh"}};Ps([f()],Qn.prototype,"receiveShadows");Ps([f()],Qn.prototype,"shadowCastingMode");Ps([f()],Qn.prototype,"lightmapIndex");Ps([f(c.Vector4)],Qn.prototype,"lightmapScaleOffset");Ps([f()],Qn.prototype,"enableInstancing");Ps([f()],Qn.prototype,"renderOrder");Ps([f()],Qn.prototype,"allowOcclusionWhenDynamic");Ps([f(c.Object3D)],Qn.prototype,"probeAnchor");Ps([f()],Qn.prototype,"reflectionProbeUsage");let Ht=Qn;class th extends Ht{}class jg extends th{_needUpdateBoundingSphere=!1;awake(){super.awake(),mb&&console.log('SkinnedMeshRenderer for "'+this.name+'"',this),this.allowOcclusionWhenDynamic=!1;for(const e of this.sharedMeshes)e.parent?.updateWorldMatrix(!1,!0),this.markBoundsDirty()}onAfterRender(){if(super.onAfterRender(),this._needUpdateBoundingSphere){for(const e of this.sharedMeshes)if(e instanceof c.SkinnedMesh){this._needUpdateBoundingSphere=!1;try{const t=e.geometry,i=re.getRaycastMesh(e);i&&(e.geometry=i),e.computeBoundingSphere(),e.geometry=t}catch(t){console.error(`Error updating bounding sphere for ${e.name}`,t)}}}if(mb){for(const e of this.sharedMeshes)if(e instanceof c.SkinnedMesh&&e.boundingSphere){const t=F(e.boundingSphere.center).applyMatrix4(e.matrixWorld);B.DrawWireSphere(t,e.boundingSphere.radius,"red")}}}markBoundsDirty(){this._needUpdateBoundingSphere=!0}}var SM=Object.defineProperty,Qa=(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&&SM(e,t,n),n};const Rt=x("debugdroplistener");class CM extends CustomEvent{constructor(e){super("object-added",{detail:e})}}const PM="blob";class Os extends R{dropArea;fitIntoVolume=!1;fitVolumeSize=new c.Vector3(1,1,1);placeAtHitPosition=!0;useNetworking=!1;onDropped=new ne;loadFromURL(e,t){return this.addFromUrl(e,{screenposition:new c.Vector2,point:t?.point,size:t?.size},!1)}forgetObjects(){this.removePreviouslyAddedObjects(!1)}awake(){for(const e of this.gameObject.children)this.dropArea&&e.contains(this.dropArea)||this._addedObjects.push(e)}onEnable(){this.context.renderer.domElement.addEventListener("dragover",this.onDrag),this.context.renderer.domElement.addEventListener("drop",this.onDrop),window.addEventListener("paste",this.handlePaste),this.context.connection.beginListen("droplistener",this.onNetworkEvent),A()&&this.dropArea&&(this.dropArea.getComponentInChildren(Ht)||console.warn("[DropListener] The assigned DropArea does not seem to have a renderer/mesh. Drag and Drop events will not be detected."))}onDisable(){this.context.renderer.domElement.removeEventListener("dragover",this.onDrag),this.context.renderer.domElement.removeEventListener("drop",this.onDrop),window.removeEventListener("paste",this.handlePaste),this.context.connection.stopListen("droplistener",this.onNetworkEvent)}onNetworkEvent=e=>{if(!this.useNetworking){Rt&&console.debug("[DropListener] Ignoring networked event because networking is disabled",e);return}if(e.guid?.startsWith(this.guid)){const t=e.url;if(console.debug("[DropListener] Received networked event",e),t)if(Array.isArray(t))for(const i of t)this.addFromUrl(i,{screenposition:new c.Vector2,point:e.point,size:e.size},!0);else this.addFromUrl(t,{screenposition:new c.Vector2,point:e.point,size:e.size},!0)}};handlePaste=e=>{if(this.context.connection.allowEditing===!1||e.defaultPrevented)return;navigator.clipboard.readText().then(i=>{if(i&&(i.startsWith("http")||i.startsWith("https")||i.startsWith("blob"))){const o={screenposition:new c.Vector2(this.context.input.mousePosition.x,this.context.input.mousePosition.y)};this.testIfIsInDropArea(o)&&this.addFromUrl(i,o,!1)}}).catch(console.warn)};onDrag=e=>{Rt&&console.debug("DropListener Drag",e,this.context.connection.allowEditing),this.context.connection.allowEditing!==!1&&e.preventDefault()};onDrop=async e=>{if(Rt&&console.debug("DropListener Drop",e,this.context.connection.allowEditing),this.context.connection.allowEditing===!1||!e?.dataTransfer||e["droplistener:handled"])return;e.preventDefault();const t={screenposition:new c.Vector2(e.offsetX,e.offsetY)};if(this.dropArea&&this.testIfIsInDropArea(t)===!1)return;e["droplistener:handled"]=!0;const i=e.dataTransfer.items;if(!i)return;const n=[];for(const o in i){const r=i[o];if(r.kind==="file"){const a=r.getAsFile();if(!a)continue;n.push(a)}else r.kind==="string"&&r.type=="text/plain"&&r.getAsString(a=>{this.addFromUrl(a,t,!1)})}n.length>0&&await this.addFromFiles(n,t)};async addFromUrl(e,t,i){Rt&&console.log("dropped url",e);try{if(e.startsWith("https://github.com/")){const r=e.split("/"),a=r[3],l=r[4],h=r[6],d=r.slice(7).join("/");e=`https://raw.githubusercontent.com/${a}/${l}/${h}/${d}`}else e.startsWith("https://polyhaven.com/a")&&(e=OM(e));if(!e)return null;const n=e.toLowerCase();if(n.endsWith(".hdr")||n.endsWith(".hdri")||n.endsWith(".exr")||n.endsWith(".png")||n.endsWith(".jpg")||n.endsWith(".jpeg"))return console.warn(`Fileformat is not supported: ${n}`),null;this.removePreviouslyAddedObjects();const o=await iu.loadFileFromURL(new URL(e),{guid:this.guid,context:this.context,parent:this.gameObject,point:t.point,size:t.size});if(o&&this._addedObjects.length<=0)return t.url=e,this.onObjectLoaded(o,t,i)}catch{console.warn("String is not a valid URL",e)}return null}_abort=null;async addFromFiles(e,t){if(Rt&&console.log("Add files",e),!!Array.isArray(e)&&e.length){this.deleteDropEvent(),this.removePreviouslyAddedObjects(),pc(PM,null),this._abort?.abort("New files dropped"),this._abort=new AbortController;for(const i of e){if(!i)continue;if(i.type.startsWith("image/")){Rt&&console.warn("Ignoring dropped image file",i.name,i.type);continue}else if(i.name.endsWith(".bin")){Rt&&console.warn("Ignoring dropped binary file",i.name,i.type);continue}console.debug("Load file "+i.name+" + "+i.type);const n=await iu.loadFile(i,this.context,{guid:this.guid});if(n){this.dispatchEvent(new CustomEvent("file-dropped",{detail:i})),t.file=i;const o=this.onObjectLoaded(n,t,!1);o&&this.context.connection.isConnected&&this.useNetworking&&(console.debug("Uploading dropped file to blob storage"),exports.BlobStorage.upload(i,{abort:this._abort?.signal}).then(r=>{r?.download_url&&this._addedObjects.includes(o)&&this.sendDropEvent(r.download_url,o,n.contentMD5)}).catch(console.warn));break}}}}_addedObjects=new Array;_addedModels=new Array;removePreviouslyAddedObjects(e=!0){if(e)for(const t of this._addedObjects)t.parent===this.gameObject&&t.destroy();this._addedObjects.length=0,this._addedModels.length=0}onObjectLoaded(e,t,i){const{model:n,contentMD5:o}=e;if(Rt&&console.log(`Dropped ${this.gameObject.name}`,n),!n?.scene)return console.warn("No object specified to add to scene",n),null;this.removePreviouslyAddedObjects();const r=n.scene;r.position.copy(this.gameObject.worldPosition);const a=je(this.gameObject);let l=new c.Vector3(0,0,0);a.x=Math.abs(a.x),a.y=Math.abs(a.y),a.z=Math.abs(a.z);let h=r.scale.clone();const d=new c.Box3().setFromCenterAndSize(new c.Vector3(0,this.fitVolumeSize.y*a.y*.5,0).add(this.gameObject.worldPosition),this.fitVolumeSize.clone().multiply(a));if(Rt&&B.DrawWireBox3(d,255,5),this.fitIntoVolume&&(xv(r,d,{position:!this.placeAtHitPosition}),h=r.scale.clone().divide(a),l=r.worldPosition.clone().sub(this.gameObject.worldPosition).divide(a),Rt&&B.DrawSphere(l,.1,16711680,5)),this.gameObject.attach(r),r.position.copy(l),r.quaternion.identity(),r.scale.copy(h),Rt&&B.DrawArrow(this.gameObject.worldPosition,r.getWorldPosition(new c.Vector3),65280,5),this._addedObjects.push(r),this._addedModels.push(n),this.placeAtHitPosition&&t&&t.screenposition){r.visible=!1;const p=this.context.physics.raycast({screenPoint:this.context.input.convertScreenspaceToRaycastSpace(t.screenposition.clone())});if(r.visible=!0,p&&p.length>0)for(const m of p){const y=m.point.clone();Rt&&console.log("Place object at hit",m),Sv(r,y);break}}Hn.autoplayAnimations(n);const u=new CM({sender:this,gltf:n,model:n,object:r,contentMD5:o,dropped:t.file||(t.url?new URL(t.url):void 0)});return this.dispatchEvent(u),this.onDropped?.invoke(u.detail),!i&&t.url?.startsWith("http")&&this.context.connection.isConnected&&r&&this.sendDropEvent(t.url,r,o),r}async sendDropEvent(e,t,i){if(!this.useNetworking){Rt&&console.debug("[DropListener] Ignoring networked event because networking is disabled",e);return}if(this.context.connection.isConnected){console.debug('Sending drop event "'+t.name+'"',e);const n=ri([t]),o={name:t.name,guid:this.guid,url:e,point:t.worldPosition.clone(),size:n.getSize(new c.Vector3),contentMD5:i};this.context.connection.send("droplistener",o)}}deleteDropEvent(){this.context.connection.sendDeleteRemoteState(this.guid)}testIfIsInDropArea(e){const t=this.context.input.convertScreenspaceToRaycastSpace(e.screenposition.clone()),i=this.context.physics.raycast({screenPoint:t,recursive:!0,testObject:o=>!this._addedObjects.some(r=>r.contains(o))});if(!i.length)return A()&&console.log(`Dropped outside of drop area for DropListener "${this.name}".`),!1;const n=i[0];return!!(this.dropArea&&this.dropArea.contains(n.object))}}Qa([f(c.Object3D)],Os.prototype,"dropArea");Qa([f()],Os.prototype,"fitIntoVolume");Qa([f(c.Vector3)],Os.prototype,"fitVolumeSize");Qa([f()],Os.prototype,"placeAtHitPosition");Qa([f()],Os.prototype,"useNetworking");Qa([f(ne)],Os.prototype,"onDropped");function OM(s){if(!s.startsWith("https://polyhaven.com/"))return s;const e="https://dl.polyhaven.org/file/ph-assets/Models/gltf/4k/",n=new URL(s).pathname.split("/").pop(),o=`${e}${n}/${n}_4k.gltf`;return console.log("Resolved polyhaven asset url",s,"→",o),o}var iu;(s=>{async function e(i,n,o){const r=o.guid,a=new wt(r),l=new Blob([i],{type:i.type||vw(i.name)||void 0}),h=URL.createObjectURL(l),d=await un().loadSync(n,h,i.name,a).catch(u=>(console.error(`Failed to load file "${i.name}" (${i.type}):`,u),null));return URL.revokeObjectURL(h),d?new Promise((u,p)=>{const m=new FileReader;m.readAsArrayBuffer(i),m.onloadend=async y=>{const _=m.result,g=exports.BlobStorage.hashMD5(_);return u({model:d,contentMD5:g})}}):(console.warn(`Failed to load "${i.name}" (${i.type})`),null)}s.loadFile=e;async function t(i,n){return new Promise(async(o,r)=>{const a=new wt(n.guid),l=i.toString();Rt&&B.DrawWireSphere(n.point,.1,16711680,3);const h=exports.PreviewHelper.addPreview({guid:n.guid,parent:n.parent,position:n?.point,size:n?.size}),d=await un().loadSync(n.context,l,l,a,u=>{h.onProgress(u.loaded/u.total)}).catch(console.warn);if(d){const u=await fetch(l).then(m=>m.arrayBuffer()),p=exports.BlobStorage.hashMD5(u);Rt?setTimeout(()=>exports.PreviewHelper.removePreview(n.guid),3e3):exports.PreviewHelper.removePreview(n.guid),o({model:d,contentMD5:p})}else Rt?setTimeout(()=>exports.PreviewHelper.removePreview(n.guid),3e3):exports.PreviewHelper.removePreview(n.guid),console.warn("Unsupported file type: "+i.toString())})}s.loadFileFromURL=t})(iu||(iu={}));var MM=Object.defineProperty,Bg=(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&&MM(e,t,n),n};const Lu=class Rw extends R{parent=null;object=null;limitCount=60;_currentCount=0;_startPosition=null;_startQuaternion=null;start(){if(this._currentCount=0,this._startPosition=null,this._startQuaternion=null,this.object||(this.object=this.gameObject),this.object){if(this.object===this.gameObject){const t=new wt(this.guid);this.object=S.instantiate(this.object,{idProvider:t,keepWorldPosition:!1}),S.getComponent(this.object,Rw)?.destroy();let n=this.object.getComponentInChildren(Zo);n||(n=this.object.addComponent(Zo,{dragMode:Tg.SnapToSurfaces}),n.guid=t.generateUUID());let o=S.getComponent(n.gameObject,pn);o||(o=n.gameObject.addComponent(pn),o.guid=t.generateUUID())}this.object.visible=!1;const e=this.gameObject.getComponent(Zo);e&&(e.enabled=!1),this._startPosition=this.object.position?.clone()??new c.Vector3(0,0,0),this._startQuaternion=this.object.quaternion?.clone()??new c.Quaternion(0,0,0,1)}this.gameObject.getComponentInParent($i)||this.gameObject.addComponent($i)}onEnable(){this.startCoroutine(this.cloneLimitIntervalFn())}_forwardPointerEvents=new Map;onPointerEnter(e){e.used||this.object&&this.context.connection.allowEditing&&e.button===0&&this.context.input.setCursor("pointer")}onPointerExit(e){e.used||this.object&&this.context.connection.allowEditing&&e.button===0&&this.context.input.unsetCursor("pointer")}onPointerDown(e){if(e.used||!this.object||!this.context.connection.allowEditing||e.button!==0)return;const t=this.handleDuplication();if(t){const i=S.getComponent(t,Zo);i?(i.onPointerDown(e),this._forwardPointerEvents.set(e.event.space,i)):A()&&console.warn(`Duplicated object (${t.name}) does not have DragControls`)}else this._currentCount>=this.limitCount?console.warn(`[Duplicatable] Limit of ${this.limitCount} objects created within a few seconds reached. Please wait a moment before creating more objects.`):console.warn("[Duplicatable] Could not duplicate object.")}onPointerUp(e){if(e.used)return;const t=this._forwardPointerEvents.get(e.event.space);t&&(t.onPointerUp(e),this._forwardPointerEvents.delete(e.event.space))}*cloneLimitIntervalFn(){for(;this.activeAndEnabled&&!this.destroyed;)this._currentCount>0?this._currentCount-=1:this._currentCount<0&&(this._currentCount=0),yield dg(1)}handleDuplication(){if(!this.object||this.limitCount>0&&this._currentCount>=this.limitCount||this.object===this.gameObject)return null;if(S.isDestroyed(this.object))return this.object=null,null;this.object.matrixAutoUpdate===!1&&(this.object.updateMatrix(),A()&&(console.warn(`Object "${this.object.name}" has matrixAutoUpdate disabled. This can cause duplicated objects to have incorrect position/rotation/scale. Consider enabling matrixAutoUpdate or calling updateMatrix() before duplication.`),fe("Duplicatable: Object has matrixAutoUpdate disabled"))),this.object.visible=!0,this._startPosition&&this.object.position.copy(this._startPosition),this._startQuaternion&&this.object.quaternion.copy(this._startQuaternion);const e=new gn;this.parent||(this.parent=this.gameObject.parent),this.parent&&(e.parent=this.parent.guid??this.parent.userData?.guid,e.keepWorldPosition=!0),e.position=this.worldPosition,e.rotation=this.worldQuaternion,e.context=this.context,this._currentCount+=1;const t=S.instantiateSynced(this.object,e);return console.assert(t!==this.object,"Duplicated object is original"),this.object.visible=!1,this._startPosition&&this.object.position.clone().copy(this._startPosition),this._startQuaternion&&this.object.quaternion.clone().copy(this._startQuaternion),t}};Bg([f(c.Object3D)],Lu.prototype,"parent");Bg([f(c.Object3D)],Lu.prototype,"object");Bg([f()],Lu.prototype,"limitCount");let Fg=Lu;var is=(s=>(s[s.PointerEnter=0]="PointerEnter",s[s.PointerExit=1]="PointerExit",s[s.PointerDown=2]="PointerDown",s[s.PointerUp=3]="PointerUp",s[s.PointerClick=4]="PointerClick",s))(is||{}),kM=Object.defineProperty,Ug=(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&&kM(e,t,n),n};class zg{eventID;callback=new ne}Ug([f()],zg.prototype,"eventID");Ug([f(ne)],zg.prototype,"callback");class Iu extends R{triggers=[];invoke(e){if(this.triggers)for(const t of this.triggers)t.eventID===e&&t.callback?.invoke()}hasTrigger(e){return this.triggers?.some(t=>t.eventID===e)??!1}shouldChangeCursor(){return this.hasTrigger(is.PointerClick)||this.hasTrigger(is.PointerDown)||this.hasTrigger(is.PointerUp)}onPointerClick(e){this.invoke(is.PointerClick)}onPointerEnter(e){this.shouldChangeCursor()&&this.context.input.setCursor("pointer"),this.invoke(is.PointerEnter)}onPointerExit(e){this.shouldChangeCursor()&&this.context.input.unsetCursor("pointer"),this.invoke(is.PointerExit)}onPointerDown(e){this.invoke(is.PointerDown)}onPointerUp(e){this.invoke(is.PointerUp)}}Ug([f(zg)],Iu.prototype,"triggers");class Ew{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(e.constructor.name!=="InstancedMesh")return;const i=this.writer,n=i.extensionsUsed,o={};t.extensions=t.extensions||{},t.extensions[this.name]=o;let r=new c.Matrix4;const a=new Array,l=new Array,h=new Array;for(let m=0;m<e.count;m++){e.getMatrixAt(m,r);let y=new c.Vector3,_=new c.Quaternion,g=new c.Vector3;r.decompose(y,_,g),a.push(y.x,y.y,y.z),l.push(_.x,_.y,_.z,_.w),h.push(g.x,g.y,g.z)}const d=new Float32Array(a),u=new Float32Array(l),p=new Float32Array(h);o.attributes={TRANSLATION:i.processAccessor(new c.BufferAttribute(d,3)),ROTATION:i.processAccessor(new c.BufferAttribute(u,4)),SCALE:i.processAccessor(new c.BufferAttribute(p,3))},n[this.name]=!0}}class Tw{writer;constructor(e){this.writer=e}writeNode(e){}}class RM extends Tw{beforeWriteNode(e,t){B.isGizmo(e)&&(t.keep=!1)}}class Aw extends Tw{beforeWriteTexture(e,t){e.isRenderTargetTexture&&(t.newTexture=ug(new te(1,1,1,0)))}}function cm(s){const e=du.DontExport;return!(s.hideFlags&e)}var EM=Object.defineProperty,Dw=(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&&EM(e,t,n),n};const Qh=x("debuggltfexport");class Ng extends _t{sceneRoot}const Vg=class la extends R{binary=!0;objects=[];ext;async exportNow(e,t){Qh&&console.log("Exporting objects as glTF",this.objects),e||(e="scene"),(!this.objects||this.objects.length<=0)&&(this.objects=[this.context.scene]);const i={binary:this.binary,pivot:la.calculateCenter(this.objects),...t},n=await this.export(this.objects,i).catch(o=>(console.error(o),!1));return n===!1?!1:(this.binary?e.endsWith(".glb")||(e+=".glb"):e.endsWith(".gltf")||(e+=".gltf"),this.binary?la.saveArrayBuffer(n,e):la.saveJson(n,e),!0)}async export(e,t){if(!e||e.length<=0){console.warn("No objects set to export");return}const i=new X.GLTFExporter;i.register(h=>new Ew(h)),i.register(h=>new Aw(h)),Lg(i,this.context),la.filterTopmostParent(e);const n={trs:!1,onlyVisible:!0,truncateDrawRange:!1,binary:!0,maxTextureSize:1/0,embedImages:!0,includeCustomExtensions:!0,animations:t?.animations||la.collectAnimations(e),...t},o=new Array,r=new c.Object3D;t?.pivot&&r.position.sub(t.pivot),Qh&&console.log("EXPORT",e),e.forEach(h=>{h&&cm(h)&&(r.children.push(h),h.matrixAutoUpdate=!1,h.matrix.copy(h.matrixWorld),S.getComponentsInChildren(h,Ht).forEach(d=>{S.isActiveInHierarchy(d.gameObject)&&d.setInstancingEnabled(!1)}),h.traverse(d=>{if(!cm(d)){const u=d.parent;d.removeFromParent(),o.push(()=>{u&&u.add(d)})}}))});const a=new lg(r);return t?.needleComponents&&(this.ext=new Cw),this.ext&&(this.ext.registerExport(i),this.ext.context=a),new Promise((h,d)=>{Qh&&console.log("Starting glTF export.");try{i?.parse(r,u=>{l(),h(u)},u=>{l(),d(u)},n)}catch(u){console.error(u),d(u)}finally{o.forEach(u=>u()),Qh&&console.log("Finished glTF export.")}});function l(){e.forEach(h=>{h&&(h.matrixAutoUpdate=!0,S.getComponentsInChildren(h,Ht).forEach(d=>{S.isActiveInHierarchy(d.gameObject)&&d.setInstancingEnabled(!1)}))})}}static saveArrayBuffer(e,t){this.save(new Blob([e],{type:"application/octet-stream"}),t)}static saveJson(e,t){this.save("data: text/json;charset=utf-8,"+encodeURIComponent(JSON.stringify(e)),t)}static save(e,t){const i=document.createElement("a");i.style.display="none",document.body.appendChild(i),typeof e=="string"?i.href=e:i.href=URL.createObjectURL(e),i.download=t,i.click(),i.remove()}static collectAnimations(e,t){t=t||[];for(const i of e)i&&i.traverseVisible(n=>{n.animations&&n.animations.length>0&&t.push(...n.animations)});return t}static calculateCenter(e,t){const i=t||new c.Vector3;return i.set(0,0,0),e.forEach(n=>{i.add(Y(n))}),i.divideScalar(e.length),i}static filterTopmostParent(e){if(!(e.length<=0))for(let t=0;t<e.length;t++){let i=e[t];if(!i){e.splice(t,1),t--;continue}for(;i.parent;){if(e.includes(i.parent)){e.splice(t,1),t--;break}i=i.parent}}}};Dw([f()],Vg.prototype,"binary");Dw([f(c.Object3D)],Vg.prototype,"objects");let $g=Vg;typeof globalThis!==void 0&&!("OffscreenCanvas"in globalThis)&&(globalThis.OffscreenCanvas=class{canvas;constructor(e,t){return this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=t,this.canvas.convertToBlob=(i,n)=>new Promise(o=>{this.canvas.toBlob(o,i,n)}),this.canvas}});const TM=x("debugprogress");function Lw(s){s=s||new Date;const e=s.getMonth()+1,t=s.getDate(),i=s.getHours(),n=s.getMinutes(),o=s.getSeconds(),r=(e<10?"0":"")+e,a=(t<10?"0":"")+t,l=(i<10?"0":"")+i,h=(n<10?"0":"")+n,d=(o<10?"0":"")+o;return s.getFullYear()+r+a+"-"+l+h+d}class oe{static start(e,t){typeof t=="string"&&(t={parentScope:t});const i=new AM(e,t);Wl.set(e,i)}static report(e,t){const i=Wl.get(e);if(!i){console.warn("Reporting progress for non-existing scope",e);return}typeof t=="string"&&(t={message:t,autoStep:!0}),i.report(t)}static end(e){const t=Wl.get(e);t&&(t.end(),Wl.delete(e))}}const Wl=new Map;class AM{scopeLabel;parentScope;childScopes=[];parentDepth=0;lastStep=0;lastAutoStepWeight=1;lastTotalSteps=0;onProgress;showLogs=!1;selfProgress=0;totalProgress=0;selfReports=0;totalReports=0;constructor(e,t){this.parentScope=t?.parentScope?Wl.get(t.parentScope):void 0,this.parentScope&&(this.parentScope.childScopes.push(this),this.parentDepth=this.parentScope.parentDepth+1),this.scopeLabel=" ".repeat(this.parentDepth*2)+e,this.showLogs=t?.logTimings??!!TM,this.showLogs&&console.time(this.scopeLabel),this.onProgress=t?.onProgress}report(e,t=!1){if(e){if(e.totalSteps!==void 0&&(this.lastTotalSteps=e.totalSteps),e.currentStep!==void 0&&(this.lastStep=e.currentStep),e.autoStep!==void 0){if(e.currentStep===void 0){this.lastStep===void 0&&(this.lastStep=0);const n=typeof e.autoStep=="number"?e.autoStep:1;this.lastStep+=this.lastAutoStepWeight,this.lastAutoStepWeight=n,e.currentStep=this.lastStep}e.totalSteps=this.lastTotalSteps}e.progress!==void 0?this.selfProgress=e.progress:e.currentStep!==void 0&&e.totalSteps!==void 0&&(this.selfProgress=e.currentStep/e.totalSteps)}if(this.childScopes.length>0){let n=0,o=0;for(const a of this.childScopes)n+=a.selfProgress,o+=1;o>0&&(n/=o);const r=this.lastAutoStepWeight/(this.lastTotalSteps??1);this.totalProgress=this.selfProgress+n*r}else this.totalProgress=this.selfProgress;this.selfProgress=Math.min(1,this.selfProgress),this.totalProgress=Math.min(1,this.totalProgress);let i=(this.totalProgress*100).toFixed(3)+"%";this.childScopes.length>0&&(i+=" ("+(this.selfProgress*100).toFixed(3)+"% self)"),e?.message&&(i=e.message+" – "+i),this.lastStep!==void 0&&this.lastTotalSteps!==void 0&&(i="Step "+(this.lastStep+(this.lastAutoStepWeight!=1?"–"+(this.lastStep+this.lastAutoStepWeight):"")+"/"+this.lastTotalSteps)+" "+i),t?this.totalReports++:(this.selfReports++,this.totalReports++),this.showLogs&&console.timeLog(this.scopeLabel,i),this.onProgress&&this.onProgress(this.totalProgress),this.parentScope&&this.parentScope.report(void 0,!0)}end(){this.report({progress:1,autoStep:!0},!0),this.showLogs&&(console.timeLog(this.scopeLabel,"Total reports: "+this.totalReports,"Self reports: "+this.selfReports),console.timeEnd(this.scopeLabel));let e=!1;for(const t of this.childScopes)if(!(t.selfProgress>=1)){e=!0;break}e&&console.warn("Progress end with child scopes that are still running",this),this.onProgress=void 0}}const Re="</StageRoot/Materials";function DM(s,e,t){const i=new Map,n=_=>{const g=_.type___needle,w=i.get(g)||new Map;if(i.set(g,w),!w.has(_)){const b=`${g}${w.size?`_${w.size}`:""}`;w.set(_,b)}return w.get(_)},o=s.colorNode?Yh(s.colorNode):[],r=s.colorNode?`color3f inputs:diffuseColor.connect = ${Re}/${e}/${n(o.values().next().value)}.outputs:out>`:"",a=s.roughnessNode?Yh(s.roughnessNode):[],l=s.roughnessNode?`float inputs:roughness.connect = ${Re}/${e}/${n(a.values().next().value)}.outputs:out>`:"",h=s.normalNode?Yh(s.normalNode):[],d=s.normalNode?`float3 inputs:normal.connect = ${Re}/${e}/${n(h.values().next().value)}.outputs:out>`:"",u=s.metalnessNode?Yh(s.metalnessNode):[],p=s.metalnessNode?`float inputs:metallic.connect = ${Re}/${e}/${n(u.values().next().value)}.outputs:out>`:"",m=new Set([...o,...a,...h,...u]),y=jM(m,e,t,n);return console.debug(y),`
|
|
1055
|
-
|
|
1056
|
-
def Material "${e}" ${s.name?`(
|
|
1057
|
-
displayName = "${s.name}"
|
|
1058
|
-
)`:""}
|
|
1059
|
-
{
|
|
1060
|
-
token outputs:mtlx:surface.connect = ${Re}/${e}/N_mtlxsurface.outputs:surface>
|
|
1061
|
-
|
|
1062
|
-
def Shader "N_mtlxsurface"
|
|
1063
|
-
{
|
|
1064
|
-
uniform token info:id = "ND_UsdPreviewSurface_surfaceshader"
|
|
1065
|
-
${r}
|
|
1066
|
-
${l}
|
|
1067
|
-
${d}
|
|
1068
|
-
${p}
|
|
1069
|
-
token outputs:surface
|
|
1070
|
-
}
|
|
1071
|
-
|
|
1072
|
-
${y}
|
|
1073
|
-
|
|
1074
|
-
}`}function Yh(s){const e=g=>{if(g.nodeType)return g.nodeType;switch(g.type){case"TimerNode":return"float";case"TextureNode":return;case"ConvertNode":return g.convertTo;default:return}},t=g=>{const w=new Set,b=v=>{if(!(!v.isNode||w.has(v))){v.nodeType___needle||(v.nodeType___needle=e(v)),v.shaderNode?(v.type___needle="ShaderCallNodeInternal",v.shaderNodeLayoutName___needle=v.shaderNode.layout.name.slice(3)):v.type___needle=v.type,w.add(v);for(const E in v)v[E]?.isNode&&(b(v[E]),v.nodeType___needle||=v[E].nodeType___needle),Array.isArray(v[E])&&v[E].forEach(O=>{O.isNode&&(b(O),v.nodeType___needle||=O.nodeType___needle)})}};return b(g),w},i=g=>{if(g.type==="ConvertNode"){if(g.convertTo===g.node.nodeType___needle)return!0;if(g.node.type==="ConstNode"){if(g.convertTo==="vec4"&&g.node.value.isVector4)return!0;if(g.convertTo==="vec3"&&g.node.value.isVector3)return!0;if(g.convertTo==="vec2"&&g.node.value.isVector2)return!0;if(g.convertTo==="color"&&g.node.value.isColor)return!0;if(g.convertTo==="float"&&typeof g.node.value=="number")return!0}else if(g.node.type=="SplitNode"&&g.convertTo=="float"&&g.node.components.length===1)return!0}return!1},n=g=>{for(;o(g);)!g.node&&g.shaderNode?g=g.inputNodes[0]:g=g.node??g.aNode??g.bNode??g.cNode;return g},o=g=>{const w=["UniformNode","UniformGroupNode","ShaderNodeInternal"];return!g||i(g)||w.includes(g.type___needle)||g.type___needle===void 0},r=(g,w)=>{for(const b of w)for(const v in b){if(b[v]?.isNode&&b[v]===g)return{parent:b,label:v};if(Array.isArray(b[v])&&b[v].find(O=>O.isNode&&O===g))return{parent:b,label:v}}return null},a=(g,w)=>{if(g.shaderNode)g.inputNodes[0]=n(g.inputNodes[0]);else if(Array.isArray(g.nodes))for(let b=0;b<g.nodes.length;b++)g.nodes[b]&&o(g.nodes[b])&&(g.nodes[b]=n(g.nodes[b]));else w.forEach(b=>{g[b]&&o(g[b])&&(g[b]=n(g[b]))})},l=g=>{g.type==="MathNode"&&g.method==="mix"&&(g.cNode.nodeType___needle="float",g.cNode.type==="ConvertNode"&&(g.cNode.convertTo="float"))},h=(g,w)=>{w.label==="cNode"&&w.parent.type==="MathNode"&&w.parent.method==="mix"||(w.parent.type==="JoinNode"?g.nodeType___needle="float":g.nodeType___needle=w.parent.nodeType___needle)},d=g=>g?.type==="ConvertNode"&&g.nodeType___needle==="color"&&g.node.nodeType___needle==="vec4",u=(g,w)=>{g.convertTo="vec3",g.nodeType___needle="vec3";const b={type:"ConvertNode",convertTo:"color",node:g,isNode:!0,nodeType___needle:"color",type___needle:"ConvertNode"},v=r(g,w);return v?.parent&&(v.parent[v.label]=b),b},p=g=>g?.type==="ConvertNode"&&g.node.type==="TextureNode"&&g.nodeType___needle!==g.node.nodeType___needle,m=g=>{const w=new Set;for(let b of g)if(!o(b)){if(l(b),b.type=="SplitNode"){const v=r(b,g);if(b.components.length===1)b.nodeType___needle="float";else if(v)b.nodeType___needle=v.parent.nodeType___needle;else throw new Error("SplitNode without parent found, this should not happen")}if(a(b,["node","aNode","bNode","cNode"]),b.type=="ConstNode"&&b.nodeType==null&&h(b,r(b,g)),d(b)&&w.add(u(b,g)),p(b)){b.node.nodeType___needle=b.convertTo;const v=r(b,g);v?.parent&&(v.parent[v.label]=b.node),b=b.node}w.add(b)}return w},y=t(s);return m(y)}function LM(s,e){switch(e){case"float4":return s.isVector4?`(${s.x}, ${s.y}, ${s.z}, ${s.w})`:`(${s}, ${s}, ${s}, ${s})`;case"float3":return s.isVector3?`(${s.x}, ${s.y}, ${s.z})`:`(${s}, ${s}, ${s})`;case"float2":return s.isVector2?`(${s.x}, ${s.y})`:`(${s}, ${s})`;case"color3f":return s.isColor?`(${s.r}, ${s.g}, ${s.b})`:`(${s}, ${s}, ${s})`;default:return s.isVector4||s.isVector3||s.isVector2?`${s.x}`:s.isColor?`${s.r}`:`${s}`}}function IM(s,e,t,i){const n=" ",o=m=>({float:"float",vec2:"vector2",vec3:"vector3",vec4:"vector4",color:"color3"})[m]||"float",r=m=>({float:"float",vec2:"float2",vec3:"float3",vec4:"float4",color:"color3f"})[m]||"float",a=s.type___needle,l=s.nodeType___needle,h=o(l);let d=r(l),u="";const p=new Array;switch(a){case"UniformGroupNode":case"UniformNode":return"";case"TimerNode":u="time_float";break;case"ConstNode":u="constant_"+h,p.push(`${d} inputs:value = ${LM(s.value,d)}`);break;case"JoinNode":u="combine"+s.nodes.length+"_"+h;let m=1;for(const v of s.nodes)p.push(`float inputs:in${m++}.connect = ${Re}/${e}/${t(v)}.outputs:out>`);break;case"ConvertNode":u="convert_"+o(s.node.nodeType___needle)+"_"+h,s.node&&p.push(`${r(s.node.nodeType___needle)} inputs:in.connect = ${Re}/${e}/${t(s.node)}.outputs:out>`);break;case"MathNode":u=s.method+"_"+h,s.aNode&&!s.bNode&&p.push(`${r(s.aNode.nodeType___needle)} inputs:in.connect = ${Re}/${e}/${t(s.aNode)}.outputs:out>`),s.aNode&&s.bNode&&!s.cNode&&(p.push(`${r(s.aNode.nodeType___needle)} inputs:in1.connect = ${Re}/${e}/${t(s.aNode)}.outputs:out>`),p.push(`${r(s.bNode.nodeType___needle)} inputs:in2.connect = ${Re}/${e}/${t(s.bNode)}.outputs:out>`)),s.aNode&&s.bNode&&s.cNode&&s.method=="clamp"&&(p.push(`${r(s.aNode.nodeType___needle)} inputs:in.connect = ${Re}/${e}/${t(s.aNode)}.outputs:out>`),p.push(`${r(s.bNode.nodeType___needle)} inputs:low.connect = ${Re}/${e}/${t(s.bNode)}.outputs:out>`),p.push(`${r(s.cNode.nodeType___needle)} inputs:high.connect = ${Re}/${e}/${t(s.cNode)}.outputs:out>`)),s.aNode&&s.bNode&&s.cNode&&s.method=="mix"&&(p.push(`${r(s.aNode.nodeType___needle)} inputs:fg.connect = ${Re}/${e}/${t(s.bNode)}.outputs:out>`),p.push(`${r(s.bNode.nodeType___needle)} inputs:bg.connect = ${Re}/${e}/${t(s.aNode)}.outputs:out>`),p.push(`float inputs:mix.connect = ${Re}/${e}/${t(s.cNode)}.outputs:out>`));break;case"OperatorNode":let _="";switch(s.op){case"*":_="multiply";break;case"/":_="divide";break;case"+":_="add";break;case"-":_="subtract";break}if(u=_+"_"+h,s.aNode&&!s.bNode&&p.push(`${r(s.aNode.nodeType___needle)} inputs:in.connect = ${Re}/${e}/${t(s.aNode)}.outputs:out>`),s.aNode&&s.bNode){const v=r(s.aNode.nodeType___needle),E=r(s.bNode.nodeType___needle);(v==="color3f"&&E==="float"||E==="float"&&E==="color3f")&&(u=_+"_color3FA"),p.push(`${v} inputs:in1.connect = ${Re}/${e}/${t(s.aNode)}.outputs:out>`),p.push(`${E} inputs:in2.connect = ${Re}/${e}/${t(s.bNode)}.outputs:out>`)}break;case"TextureNode":s.uvNode?(u="tiledimage_"+h,p.push(`float2 inputs:texcoord.connect = ${Re}/${e}/${t(s.uvNode)}.outputs:out>`)):u="image_"+h;const g=s._value,w=Gg.includes(g.format),b=BM(g);p.push(`asset inputs:file = @textures/${b}.${w?"png":"jpg"}@`),i[b]={texture:g,scale:void 0};break;case"NormalMapNode":d="float3",u="normalmap",p.push(`${d} inputs:in.connect = ${Re}/${e}/${t(s.node)}.outputs:out>`);break;case"AttributeNode":u="geompropvalue_"+h,p.push('string inputs:geomprop = "st"');break;case"ShaderCallNodeInternal":u=s.shaderNodeLayoutName___needle+"_"+h,p.push(`${d} inputs:in.connect = ${Re}/${e}/${t(s.inputNodes[0])}.outputs:out>`);break;case"SplitNode":u="swizzle_"+o(s.node.nodeType___needle)+"_"+h,p.push(`${r(s.node.nodeType___needle)} inputs:in.connect = ${Re}/${e}/${t(s.node)}.outputs:out>`),p.push(`string inputs:channels = "${s.components}"`);break}return`
|
|
1075
|
-
${n}def Shader "${t(s)}"
|
|
1076
|
-
${n}{
|
|
1077
|
-
${n}uniform token info:id = "ND_${u}"
|
|
1078
|
-
${n}${d} outputs:out
|
|
1079
|
-
${n}${p.length>0?p.join(`
|
|
1080
|
-
`):""}
|
|
1081
|
-
${n}}
|
|
1082
|
-
`}function jM(s,e,t,i){let n="";for(const o of s)n+=IM(o,e,i,t);return n}function BM(s){return wi(s.name)+"_"+(s.source?.id??s.id)}function wi(s){return s=s.replace(/[^a-zA-Z0-9_]/g,""),s.match(/^[a-zA-Z_]/)||(s="_"+s),s}function Iw(s){return s=s.replace('"','\\"'),s}function jw(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 Bw(s){const e=jw(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 FM=new c.Vector3,UM=new c.Quaternion,zM=new c.Vector3(1,1,1);class qe{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||FM,t||UM,i||zM),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 qe(c.MathUtils.generateUUID(),e.name+"_empty_"+qe.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 qe(c.MathUtils.generateUUID(),"Empty_"+qe.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=wi(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 qe(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 Wg extends qe{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}
|
|
1083
|
-
`;const h=a;return`#usda 1.0
|
|
1084
|
-
(
|
|
1085
|
-
customLayerData = {
|
|
1086
|
-
string creator = "Needle Engine ${ii}"
|
|
1087
|
-
dictionary Needle = {
|
|
1088
|
-
bool animations = ${t?1:0}
|
|
1089
|
-
bool interactive = ${i?1:0}
|
|
1090
|
-
bool physics = ${n?1:0}
|
|
1091
|
-
bool quickLookCompatible = ${e.quickLookCompatible?1:0}
|
|
1092
|
-
}
|
|
1093
|
-
}
|
|
1094
|
-
defaultPrim = "${wi(this.name)}"
|
|
1095
|
-
metersPerUnit = 1
|
|
1096
|
-
upAxis = "Y"
|
|
1097
|
-
startTimeCode = ${o}
|
|
1098
|
-
endTimeCode = ${r}
|
|
1099
|
-
timeCodesPerSecond = 60
|
|
1100
|
-
framesPerSecond = 60
|
|
1101
|
-
doc = """Generated by Needle Engine USDZ Exporter ${ii}"""
|
|
1102
|
-
${h}
|
|
1103
|
-
)
|
|
1104
|
-
`}}const Yr=`
|
|
1105
|
-
`,zt="</StageRoot/Materials";class Fw{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+=Yr,this.str+=this.applyIndent(t)):this.str+=" "+t):this.str+=this.applyIndent(t),this.str+=Yr,this.indent+=1}closeBlock(e="}"){this.indent-=1,this.str+=this.applyIndent(e)+Yr}beginArray(e){e=this.applyIndent(e+" = ["),this.str+=e,this.str+=Yr,this.indent+=1}closeArray(){this.indent-=1,this.str+=this.applyIndent("]")+Yr}appendLine(e=""){e=this.applyIndent(e),this.str+=e,this.str+=Yr}toString(){return this.str}applyIndent(e){let t="";for(let i=0;i<this.indent;i++)t+=" ";return t+e}}class NM{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 Wg,this.output="",this.animations=[]}makeNameSafe(e){return wi(e)}}const yb=()=>({ar:{anchoring:{type:"plane"},planeAnchoring:{alignment:"horizontal"}},quickLookCompatible:!1,extensions:[],maxTextureSize:4096,exportInvisible:!1});let Uw=class{debug;pruneUnusedNodes;sceneAnchoringOptions=yb();extensions=[];keepObject;beforeWritingDocument;constructor(){this.debug=!1,this.pruneUnusedNodes=!0}async parse(e,t=yb()){t=Object.assign({},t),this.sceneAnchoringOptions=t;const i=new NM(e,this,t);this.extensions=i.extensions;const n=i.files,o="model.usda";n[o]=null,i.materials;const r=i.textures;oe.report("export-usdz","Invoking onBeforeBuildDocument"),await Md(i,"onBeforeBuildDocument"),oe.report("export-usdz","Done onBeforeBuildDocument"),oe.report("export-usdz","Reparent bones to common ancestor");const a=[],l=new Set;e?.traverse(w=>{if(!(!t.exportInvisible&&!w.visible)&&w instanceof c.SkinnedMesh){const b=w.skeleton.bones,v=jw(b);if(v){const E={object:w,originalParent:w.parent,newParent:v};a.push(E),l.add(E.object.uuid),E.newParent&&l.add(E.newParent.uuid),E.originalParent&&l.add(E.originalParent.uuid)}}});for(const w of a){const{object:b,originalParent:v,newParent:E}=w;E.add(b)}oe.report("export-usdz","Traversing hierarchy"),e&&zw(e,i.document,i,this.keepObject),oe.report("export-usdz","Invoking onAfterBuildDocument"),await Md(i,"onAfterBuildDocument");const d=i.extensions.find(w=>w.extensionName==="Behaviour")?.getAllTargetUuids()??new Set;if(this.pruneUnusedNodes){const w={allBehaviorTargets:d,debug:!1,boneReparentings:l,quickLookCompatible:i.quickLookCompatible};this.debug&&_b(i.document,"Hierarchy BEFORE pruning",w),Nw(i.document,w),this.debug&&_b(i.document,"Hierarchy AFTER pruning")}else this.debug&&console.log("Pruning of empty nodes is disabled. This may result in a larger USDZ file.");oe.report("export-usdz",{message:"Parsing document",autoStep:10}),await VM(i,t),oe.report("export-usdz","Invoking onAfterSerialize"),await Md(i,"onAfterSerialize");for(const w of a){const{object:b,originalParent:v,newParent:E}=w;v&&v.add(b)}i.exporter?.beforeWritingDocument?.();const p=i.document.buildHeader(i)+`
|
|
1106
|
-
`+i.output;this.debug&&console.debug(p),n[o]=X.strToU8(p),i.output="",oe.report("export-usdz",{message:"Exporting textures",autoStep:10}),oe.start("export-usdz-textures",{parentScope:"export-usdz",logTimings:!1});const m=new c.WebGLRenderer({antialias:!1,alpha:!0,premultipliedAlpha:!1,preserveDrawingBuffer:!0}),y=Object.keys(r).length;oe.report("export-usdz-textures",{totalSteps:y*3,currentStep:0});const _=async w=>{const b=r[w],v=b.texture,E=Gg.includes(v.format);let O={imageData:v.image};oe.report("export-usdz-textures",{message:"read back texture",autoStep:!0});const M=b.scale!==void 0&&b.scale.x!==1&&b.scale.y!==1&&b.scale.z!==1&&b.scale.w!==1;(v.isCompressedTexture||v.isRenderTargetTexture||M)&&(O=await $w(v,t.maxTextureSize,m,b.scale)),oe.report("export-usdz-textures",{message:"convert texture to canvas",autoStep:!0});const D=await WM(O.imageBitmap||O.imageData,t.maxTextureSize).catch(L=>{console.error("Error converting texture to canvas",v,L)});if(D){oe.report("export-usdz-textures",{message:"convert canvas to blob",autoStep:!0});const L=await D.convertToBlob({type:E?"image/png":"image/jpeg",quality:.95});n[`textures/${w}.${E?"png":"jpg"}`]=new Uint8Array(await L.arrayBuffer())}else console.warn("Can`t export texture: ",v)};for(const w in r)await _(w);m.dispose(),oe.end("export-usdz-textures");let g=0;for(const w in n){const b=n[w],v=34+w.length;g+=v;const E=g&63;if(E!==4){const O=64-E,M=new Uint8Array(O);n[w]=[b,{extra:{12345:M}}]}g=b.length}return oe.report("export-usdz","zip archive"),X.zipSync(n,{level:0})}};function zw(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=Jh(s),h=s instanceof c.SkinnedMesh?s:null;n=new qe(s.uuid,l,a,o,r,void 0,h,s.animations)}else if(s instanceof c.PerspectiveCamera||s instanceof c.OrthographicCamera){const l=Jh(s);n=new qe(s.uuid,l,a,void 0,void 0,s)}else{const l=Jh(s);n=new qe(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=Jh(s),h=new qe(s.uuid,l,{position:s.position,quaternion:s.quaternion,scale:s.scale});e&&e.add(h),e=h}for(const l of s.children)zw(l,e,t,i)}function _b(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 Nw(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=Nw(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 VM(s,e){oe.start("export-usdz-resources","export-usdz");const t=[];for(const h of s.document.children)Vw(h,s,t);const i=t.length;for(let h=0;h<i;h++)oe.report("export-usdz-resources",{totalSteps:i,currentStep:h}),await new Promise((d,u)=>{t[h](),d()});oe.end("export-usdz-resources");const n=new Fw,o=s.exporter.sceneAnchoringOptions.ar;n.beginBlock(`def Xform "${s.document.name}"`),n.beginBlock(`def Scope "Scenes" (
|
|
1107
|
-
kind = "sceneLibrary"
|
|
1108
|
-
)`),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);oe.start("export-usdz-xforms","export-usdz"),oe.report("export-usdz-xforms",{totalSteps:a,currentStep:1});for(const h of s.document.children)Gw(h,n,s);oe.end("export-usdz-xforms"),oe.report("export-usdz","invoke onAfterHierarchy"),await Md(s,"onAfterHierarchy",n),n.closeBlock(),n.closeBlock(),oe.report("export-usdz","Building materials");const l=YM(s.materials,s.textures,e.quickLookCompatible);n.appendLine(l),n.closeBlock(),oe.report("export-usdz","write to string"),s.output+=n.toString()}function Vw(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/"+hm(i,s.name)+".usda";if(!(o in e.files)){const r=()=>{const a=qM(i,s.skinnedMesh?.skeleton?.bones,e.quickLookCompatible);e.files[o]=HM(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)Vw(o,e,t)}async function Md(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 Kh=null,Ft=null,ep,Kr,Zh;async function $w(s,e=1/0,t=null,i=void 0){ep||(ep=new c.PlaneGeometry(2,2,1,1)),Kr||(Kr=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:`
|
|
1109
|
-
varying vec2 vUv;
|
|
1110
|
-
uniform bool flipY;
|
|
1111
|
-
void main(){
|
|
1112
|
-
vUv = uv;
|
|
1113
|
-
if (flipY)
|
|
1114
|
-
vUv.y = 1. - vUv.y;
|
|
1115
|
-
gl_Position = vec4(position.xy * 1.0,0.,.999999);
|
|
1116
|
-
}`,fragmentShader:`
|
|
1117
|
-
uniform sampler2D blitTexture;
|
|
1118
|
-
uniform vec4 scale;
|
|
1119
|
-
varying vec2 vUv;
|
|
1120
|
-
|
|
1121
|
-
void main(){
|
|
1122
|
-
gl_FragColor = vec4(vUv.xy, 0, 1);
|
|
1123
|
-
|
|
1124
|
-
#ifdef IS_SRGB
|
|
1125
|
-
gl_FragColor = sRGBTransferOETF( texture2D( blitTexture, vUv) );
|
|
1126
|
-
#else
|
|
1127
|
-
gl_FragColor = texture2D( blitTexture, vUv);
|
|
1128
|
-
#endif
|
|
1129
|
-
|
|
1130
|
-
gl_FragColor.rgba *= scale.rgba;
|
|
1131
|
-
}`}));const n=Kr.uniforms;n.blitTexture.value=s,n.flipY.value=!1,n.scale.value=new c.Vector4(1,1,1,1),i!==void 0&&n.scale.value.copy(i),Kr.defines.IS_SRGB=s.colorSpace==c.SRGBColorSpace,Kr.needsUpdate=!0,Zh||(Zh=new c.Mesh(ep,Kr),Zh.frustumCulled=!1);const o=new c.PerspectiveCamera,r=new c.Scene;r.add(Zh),t||(t=Kh=new c.WebGLRenderer({antialias:!1,alpha:!0,premultipliedAlpha:!1,preserveDrawingBuffer:!0}));const a=Math.min(s.image.width,e),l=Math.min(s.image.height,e);Ft&&(Ft.width!==a||Ft.height!==l)&&(Ft.dispose(),Ft=null),Ft||(Ft=new c.WebGLRenderTarget(a,l,{format:c.RGBAFormat,type:c.UnsignedByteType,minFilter:c.LinearFilter,magFilter:c.LinearFilter})),t.setRenderTarget(Ft),t.setSize(a,l),t.clear(),t.render(r,o),Kh&&(Kh.dispose(),Kh=null);const h=new Uint8ClampedArray(Ft.width*Ft.height*4);t.readRenderTargetPixels(Ft,0,0,Ft.width,Ft.height,h);const d=new ImageData(h,Ft.width,Ft.height,void 0),u=await createImageBitmap(d,{premultiplyAlpha:"none"});return{imageData:d,imageBitmap:u}}function $M(s){return typeof HTMLImageElement<"u"&&s instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&s instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&s instanceof OffscreenCanvas||typeof ImageBitmap<"u"&&s instanceof ImageBitmap}async function WM(s,e=4096){const t=e/Math.max(s.width,s.height),i=s.width*Math.min(1,t),n=s.height*Math.min(1,t),o=new OffscreenCanvas(i,n),r={premultiplyAlpha:"none"};s.width!==i&&(r.resizeWidth=i),s.height!==n&&(r.resizeHeight=n);const a=await createImageBitmap(s,r),l=o.getContext("bitmaprenderer");return l&&l.transferFromImageBitmap(a),o}async function Ww(s,e=void 0,t=!1,i=4096){if($M(s)){const n=i/Math.max(s.width,s.height),o=new OffscreenCanvas(s.width*Math.min(1,n),s.height*Math.min(1,n)),r=o.getContext("2d",{alpha:!0,premultipliedAlpha:!1});if(!r)throw new Error("Could not get canvas 2D context");if(t===!0&&(r.translate(0,o.height),r.scale(1,-1)),r.drawImage(s,0,0,o.width,o.height),e!==void 0){const a=e.x,l=e.y,h=e.z,d=e.w,u=r.getImageData(0,0,o.width,o.height),p=u.data;for(let m=0;m<p.length;m+=4)p[m+0]=p[m+0]*a,p[m+1]=p[m+1]*l,p[m+2]=p[m+2]*h,p[m+3]=p[m+3]*d;r.putImageData(u,0,0)}return o}else throw new Error("NeedleUSDZExporter: No valid image data found. Unable to process texture.")}const xe=7;function GM(){return`#usda 1.0
|
|
1132
|
-
(
|
|
1133
|
-
customLayerData = {
|
|
1134
|
-
string creator = "Needle Engine USDZExporter"
|
|
1135
|
-
}
|
|
1136
|
-
metersPerUnit = 1
|
|
1137
|
-
upAxis = "Y"
|
|
1138
|
-
)
|
|
1139
|
-
`}function HM(s,e){let t=GM();return t+=s,X.strToU8(t)}function Jh(s){return s.name.replace(/[-<>\(\)\[\]§$%&\/\\\=\?\,\;]/g,"")+"_"+s.id}function bb(s){return wi(s.name||"bone_"+s.uuid)}function hm(s,e){return wi(s.name||"Geometry")+"_"+s.id}function ju(s){return wi(s.name||"Material")+"_"+s.id}function Pa(s,e){let t=bb(s),i=s.parent;for(;i&&i!==e;)t=bb(i)+"/"+t,i=i.parent;return t}function Gw(s,e,t){if(s==null)return;oe.report("export-usdz-xforms",{message:"buildXform "+s.displayName||s.name,autoStep:!0});const i=s.transform,n=s.geometry,o=s.material,r=s.camera,a=s.name;if(s.animations)for(const m of s.animations)t.animations.push(m);const l=n&&n.isBufferGeometry&&n.attributes.skinIndex!==void 0&&n.attributes.skinIndex.count>0,h=l?"SkelRoot":"Xform",d=new Array,u=o&&o instanceof c.MeshBasicMaterial&&o.color&&o.color.r===1&&o.color.g===1&&o.color.b===1&&!o.map&&o.opacity===1&&n?.attributes.color;if(n?.attributes.color&&!u&&console.warn("NeedleUSDZExporter: Geometry has vertex colors. Vertex colors will only be shown in QuickLook for unlit materials with white color and no texture. Otherwise, they will be ignored.",s.displayName),e.appendLine(),n?(e.beginBlock(`def ${h} "${a}"`,"(",!1),t.quickLookCompatible&&o&&o.side===c.DoubleSide&&!l?e.appendLine(`prepend references = @./geometries/${hm(n)}.usda@</Geometry_doubleSided>`):e.appendLine(`prepend references = @./geometries/${hm(n)}.usda@</Geometry>`),u||d.push("MaterialBindingAPI"),l&&d.push("SkelBindingAPI")):r&&!t.quickLookCompatible?e.beginBlock(`def Camera "${a}"`,"(",!1):s.type!==void 0?e.beginBlock(`def ${s.type} "${a}"`):e.beginBlock(`def Xform "${a}"`,"(",!1),s.type===void 0&&(s.extraSchemas?.length&&d.push(...s.extraSchemas),d.length&&e.appendLine(`prepend apiSchemas = [${d.map(m=>`"${m}"`).join(", ")}]`)),s.displayName&&e.appendLine(`displayName = "${Iw(s.displayName)}"`),(r||s.type===void 0)&&(e.closeBlock(")"),e.beginBlock()),n&&o){if(!u){const m=ju(o);e.appendLine(`rel material:binding = </StageRoot/Materials/${m}>`)}!t.quickLookCompatible&&o.side===c.DoubleSide&&(e.beginBlock('over "Geometry" '),e.appendLine("uniform bool doubleSided = 1"),e.closeBlock())}let p=!1;if(l?(e.appendLine("rel skel:skeleton = <Rig>"),e.appendLine("rel skel:animationSource = <Rig/_anim>"),p=!1):s.type===void 0&&i&&(p=p||i.position!==null||i.quaternion!==null||i.scale!==null,i.position&&(s.needsTranslate=!0,e.appendLine(`double3 xformOp:translate = (${se(i.position.x)}, ${se(i.position.y)}, ${se(i.position.z)})`)),i.quaternion&&(s.needsOrient=!0,e.appendLine(`quatf xformOp:orient = (${se(i.quaternion.w)}, ${se(i.quaternion.x)}, ${se(i.quaternion.y)}, ${se(i.quaternion.z)})`)),i.scale&&(s.needsScale=!0,e.appendLine(`double3 xformOp:scale = (${se(i.scale.x)}, ${se(i.scale.y)}, ${se(i.scale.z)})`))),s.visibility!==void 0&&e.appendLine(`token visibility = "${s.visibility}"`),r&&!t.quickLookCompatible&&("isOrthographicCamera"in r&&r.isOrthographicCamera?(e.appendLine(`float2 clippingRange = (${r.near}, ${r.far})`),e.appendLine(`float horizontalAperture = ${((Math.abs(r.left)+Math.abs(r.right))*10).toPrecision(xe)}`),e.appendLine(`float verticalAperture = ${((Math.abs(r.top)+Math.abs(r.bottom))*10).toPrecision(xe)}`),e.appendLine('token projection = "orthographic"')):"isPerspectiveCamera"in r&&r.isPerspectiveCamera&&(e.appendLine(`float2 clippingRange = (${r.near.toPrecision(xe)}, ${r.far.toPrecision(xe)})`),e.appendLine(`float focalLength = ${r.getFocalLength().toPrecision(xe)}`),e.appendLine(`float focusDistance = ${r.focus.toPrecision(xe)}`),e.appendLine(`float horizontalAperture = ${r.getFilmWidth().toPrecision(xe)}`),e.appendLine('token projection = "perspective"'),e.appendLine(`float verticalAperture = ${r.getFilmHeight().toPrecision(xe)}`))),s.onSerialize&&s.onSerialize(e,t),s.type===void 0){const m=new Array;s.needsTranslate&&m.push('"xformOp:translate"'),s.needsOrient&&m.push('"xformOp:orient"'),s.needsScale&&m.push('"xformOp:scale"'),m.length&&e.appendLine(`uniform token[] xformOpOrder = [${m.join(", ")}]`)}if(s.children){e.appendLine();for(const m of s.children)Gw(m,e,t)}e.closeBlock()}function se(s){return Number.isInteger(s)?s.toString():s.toFixed(10)}function vb(s){const e=s.elements;return`( ${ed(e,0)}, ${ed(e,4)}, ${ed(e,8)}, ${ed(e,12)} )`}function ed(s,e){return`(${se(s[e+0])}, ${se(s[e+1])}, ${se(s[e+2])}, ${se(s[e+3])})`}function qM(s,e=[],t=!0){return`
|
|
1140
|
-
def "Geometry"
|
|
1141
|
-
${XM(s,e,t)}
|
|
1142
|
-
`}function XM(s,e=[],t=!0){const i="Geometry",n=s.attributes,o=n.position.count,r=e&&e.length>0,a=[],l=[];let h=new Array,d=n.skinIndex;if(r){const p=[];for(const g of e)a.push({bone:g,index:e.indexOf(g)}),p.push(g.uuid);let m=1e4;for(;p.length<e.length&&m-- >0;)for(const g of a){const w=g.bone.children;for(const b of w)p.indexOf(b.uuid)===-1&&e.indexOf(b)!==-1&&(a.push({bone:b,index:e.indexOf(b)}),p.push(b.uuid))}m<=0&&console.error("Failed to sort bones in skinned mesh",a,e,p);for(const g of Bw(e))a.push({bone:g,index:a.length});const y=a[0].bone.parent;a.sort((g,w)=>Pa(g.bone,y)>Pa(w.bone,y)?1:-1),a.map(g=>'"'+Pa(g.bone,y)+'"').join(", ");for(const g in a)l[a[g].index]=parseInt(g);const _=n.skinIndex;h=new Array;for(let g=0;g<_.count;g++){const w=_.getX(g),b=_.getY(g),v=_.getZ(g),E=_.getW(g);h.push(l[w],l[b],l[v],l[E])}d=new c.BufferAttribute(new Uint16Array(h),4)}const u=n.skinWeight&&n.skinIndex;return`
|
|
1143
|
-
{
|
|
1144
|
-
def Mesh "${i}" ${u?`(
|
|
1145
|
-
prepend apiSchemas = ["SkelBindingAPI"]
|
|
1146
|
-
)`:""}
|
|
1147
|
-
{
|
|
1148
|
-
int[] faceVertexCounts = [${tp(s)}]
|
|
1149
|
-
int[] faceVertexIndices = [${ip(s)}]
|
|
1150
|
-
${n.normal||t?`normal3f[] normals = [${kd(n.normal,o)}] (
|
|
1151
|
-
interpolation = "vertex"
|
|
1152
|
-
)`:""}
|
|
1153
|
-
point3f[] points = [${kd(n.position,o)}]
|
|
1154
|
-
${n.uv?`texCoord2f[] primvars:st = [${Hw(n.uv,o,!0)}] (
|
|
1155
|
-
interpolation = "vertex"
|
|
1156
|
-
)`:""}
|
|
1157
|
-
${n.uv1?np("st1",n.uv1):""}
|
|
1158
|
-
${n.uv2?np("st2",n.uv2):""}
|
|
1159
|
-
${n.uv3?np("st3",n.uv3):""}
|
|
1160
|
-
${u?`matrix4d primvars:skel:geomBindTransform = ( (1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1) ) (
|
|
1161
|
-
elementSize = 1
|
|
1162
|
-
interpolation = "constant"
|
|
1163
|
-
)`:""}
|
|
1164
|
-
${n.skinIndex?`int[] primvars:skel:jointIndices = [${wb(d,!0)}] (
|
|
1165
|
-
elementSize = 4
|
|
1166
|
-
interpolation = "vertex"
|
|
1167
|
-
)`:""}
|
|
1168
|
-
${n.skinWeight?`float[] primvars:skel:jointWeights = [${wb(n.skinWeight)}] (
|
|
1169
|
-
elementSize = 4
|
|
1170
|
-
interpolation = "vertex"
|
|
1171
|
-
)`:""}
|
|
1172
|
-
${n.color?`color3f[] primvars:displayColor = [${kd(n.color,o)}] (
|
|
1173
|
-
interpolation = "vertex"
|
|
1174
|
-
)`:""}
|
|
1175
|
-
uniform token subdivisionScheme = "none"
|
|
1176
|
-
}
|
|
1177
|
-
}
|
|
1178
|
-
${t?`
|
|
1179
|
-
# This is a workaround for QuickLook/RealityKit not supporting the doubleSided attribute. We're adding a second
|
|
1180
|
-
# geometry definition here, that uses the same mesh data but appends extra faces with reversed winding order.
|
|
1181
|
-
def "${i}_doubleSided" (
|
|
1182
|
-
prepend references = </Geometry>
|
|
1183
|
-
)
|
|
1184
|
-
{
|
|
1185
|
-
over "Geometry"
|
|
1186
|
-
{
|
|
1187
|
-
int[] faceVertexCounts = [${tp(s)+", "+tp(s)}]
|
|
1188
|
-
int[] faceVertexIndices = [${ip(s)+", "+ip(s,!0)}]
|
|
1189
|
-
}
|
|
1190
|
-
}
|
|
1191
|
-
`:""}
|
|
1192
|
-
`}function tp(s){const e=s.index!==null?s.index.count:s.attributes.position.count;return Array(Math.floor(e/3)).fill(3).join(", ")}function ip(s,e=!1){const t=s.index,i=[];if(t!==null)for(let n=0;n<t.count;n++){let o=n;e&&(o=n%3===0?n+2:n%3===2?n-2:n),i.push(t.getX(o))}else{const n=s.attributes.position.count;for(let o=0;o<n;o++){let r=o;e&&(r=o%3===0?o+2:o%3===2?o-2:o),i.push(r)}}return i.join(", ")}function np(s,e){const t=e.itemSize;switch(t){case 2:return`texCoord2f[] primvars:${s} = [${Hw(e,t,!0)}] (
|
|
1193
|
-
interpolation = "vertex"
|
|
1194
|
-
)`;case 3:return`texCoord3f[] primvars:${s} = [${kd(e,t)}] (
|
|
1195
|
-
interpolation = "vertex"
|
|
1196
|
-
)`;case 4:return`double4[] primvars:${s} = [${QM(e,t)}] (
|
|
1197
|
-
interpolation = "vertex"
|
|
1198
|
-
)`;default:return console.warn("USDZExporter: Attribute with "+t+" components are currently not supported. Results may be undefined for "+s+"."),""}}function kd(s,e){if(s===void 0)return console.warn("USDZExporter: A mesh attribute is missing and will be set with placeholder data. The result may look incorrect."),Array(e).fill("(0, 0, 1)").join(", ");const t=[];for(let i=0;i<s.count;i++){const n=s.getX(i),o=s.getY(i),r=s.getZ(i);t.push(`(${n.toPrecision(xe)}, ${o.toPrecision(xe)}, ${r.toPrecision(xe)})`)}return t.join(", ")}function QM(s,e){if(s===void 0)return console.warn("USDZExporter: Attribute is missing. Results may be undefined."),Array(e).fill("(0, 0, 0, 0)").join(", ");const t=[];for(let i=0;i<s.count;i++){const n=s.getX(i),o=s.getY(i),r=s.getZ(i)||0,a=s.getW(i)||0;t.push(`(${n.toPrecision(xe)}, ${o.toPrecision(xe)}, ${r.toPrecision(xe)}, ${a.toPrecision(xe)})`)}return t.join(", ")}function wb(s,e=!1){const t=[];for(let i=0;i<s.count;i++){const n=s.getX(i),o=s.getY(i),r=s.getZ(i),a=s.getW(i);t.push(`${e?n:n.toPrecision(xe)}`),t.push(`${e?o:o.toPrecision(xe)}`),t.push(`${e?r:r.toPrecision(xe)}`),t.push(`${e?a:a.toPrecision(xe)}`)}return t.join(", ")}function Hw(s,e,t=!1){if(s===void 0)return console.warn("USDZExporter: UVs missing."),Array(e).fill("(0, 0)").join(", ");const i=[];for(let n=0;n<s.count;n++){const o=s.getX(n);let r=s.getY(n);t&&(r=1-r),i.push(`(${o.toPrecision(xe)}, ${r.toPrecision(xe)})`)}return i.join(", ")}function YM(s,e,t=!1){const i=[];for(const n in s){const o=s[n];i.push(KM(o,e,t))}return`
|
|
1199
|
-
def "Materials"
|
|
1200
|
-
{
|
|
1201
|
-
${i.join("")}
|
|
1202
|
-
}`}function Di(s){return wi(s.name)+"_"+(s.source?.id??s.id)}function Ns(s,e,t,i,n,o,r=void 0,a=void 0){const l=Di(s),h=l+(a!==void 0&&a!==1?"_"+a:""),d=t&&a!==void 0&&a!==1,u=d?new c.Vector4(1,1,1,a):void 0;a===void 0&&(a=1),d&&(a=1),u&&u.w<=.05&&(u.w=.05),i[h]={texture:s,scale:u};const p=s.channel>0?"st"+s.channel:"st";o.add(s.channel);const m=Gg.includes(s.format),y={1e3:"repeat",1001:"clamp",1002:"mirror"},_=s.repeat.clone(),g=s.offset.clone(),w=s.rotation,b=Math.sin(w),v=Math.cos(w);g.y=1-g.y-_.y,t?(_.x===0&&(_.x=1e-4),_.y===0&&(_.y=1e-4),g.x=g.x/_.x,g.y=g.y/_.y,g.x+=b/_.x,g.y+=v-1):(g.x+=b*_.x,g.y+=(1-v)*_.y);const E=ju(n),O=_.x!=1||_.y!=1||g.x!=0||g.y!=0||w!=0,M=`${zt}/${E}/${"uvReader_"+p}.outputs:result>`,D=`${zt}/${E}/Transform2d_${e}.outputs:result>`,L=e!=="normal"&&r&&(r.r!==1||r.g!==1||r.b!==1||a!==1)||!1,j=e==="normal",V=n instanceof c.MeshStandardMaterial&&n.normalScale?n.normalScale.x*2:2,W=V.toFixed(xe),k=(-1*(V/2)).toFixed(xe),N=(1-V).toFixed(xe);return`
|
|
1203
|
-
${O?`def Shader "Transform2d_${e}" (
|
|
1204
|
-
sdrMetadata = {
|
|
1205
|
-
string role = "math"
|
|
1206
|
-
}
|
|
1207
|
-
)
|
|
1208
|
-
{
|
|
1209
|
-
uniform token info:id = "UsdTransform2d"
|
|
1210
|
-
float2 inputs:in.connect = ${M}
|
|
1211
|
-
float2 inputs:scale = ${Sb(_)}
|
|
1212
|
-
float2 inputs:translation = ${Sb(g)}
|
|
1213
|
-
float inputs:rotation = ${(w/Math.PI*180).toFixed(xe)}
|
|
1214
|
-
float2 outputs:result
|
|
1215
|
-
}
|
|
1216
|
-
`:""}
|
|
1217
|
-
def Shader "${l}_${e}"
|
|
1218
|
-
{
|
|
1219
|
-
uniform token info:id = "UsdUVTexture"
|
|
1220
|
-
asset inputs:file = @textures/${h}.${m?"png":"jpg"}@
|
|
1221
|
-
token inputs:sourceColorSpace = "${s.colorSpace==="srgb"?"sRGB":"raw"}"
|
|
1222
|
-
float2 inputs:st.connect = ${O?D:M}
|
|
1223
|
-
${L?`
|
|
1224
|
-
float4 inputs:scale = (${r?r.r+", "+r.g+", "+r.b:"1, 1, 1"}, ${a})
|
|
1225
|
-
`:""}
|
|
1226
|
-
${j?`
|
|
1227
|
-
float4 inputs:scale = (${W}, ${W}, ${W}, 1)
|
|
1228
|
-
float4 inputs:bias = (${k}, ${k}, ${N}, 0)
|
|
1229
|
-
`:""}
|
|
1230
|
-
token inputs:wrapS = "${y[s.wrapS]}"
|
|
1231
|
-
token inputs:wrapT = "${y[s.wrapT]}"
|
|
1232
|
-
float outputs:r
|
|
1233
|
-
float outputs:g
|
|
1234
|
-
float outputs:b
|
|
1235
|
-
float3 outputs:rgb
|
|
1236
|
-
${n.transparent||n.alphaTest>0?"float outputs:a":""}
|
|
1237
|
-
}`}function KM(s,e,t=!1){const i=ju(s);if(s.colorWrite===!1||s.userData?.isShadowCatcherMaterial||s.userData?.isLightBlendMaterial){const p=s.userData.isLightBlendMaterial||s.userData.isShadowCatcherMaterial?"ND_realitykit_shadowreceiver_surfaceshader":"ND_realitykit_occlusion_surfaceshader";return`
|
|
1238
|
-
|
|
1239
|
-
def Material "${i}" ${s.name?`(
|
|
1240
|
-
displayName = "${s.name}"
|
|
1241
|
-
)`:""}
|
|
1242
|
-
{
|
|
1243
|
-
token outputs:mtlx:surface.connect = ${zt}/${i}/Occlusion.outputs:out>
|
|
1244
|
-
|
|
1245
|
-
def Shader "Occlusion"
|
|
1246
|
-
{
|
|
1247
|
-
uniform token info:id = "${p}"
|
|
1248
|
-
token outputs:out
|
|
1249
|
-
}
|
|
1250
|
-
}`}const o=" ",r=[],a=[],l=new Set;if(s.isMeshPhysicalNodeMaterial===!0)return DM(s,i,e);let h=s.transparent||s.alphaTest?s.opacity:1,d=!1,u=!1;if(s instanceof c.MeshPhysicalMaterial&&s.transmission!==void 0&&(h*=1-s.transmission*(1-s.roughness*.5)),s.map?(r.push(`${o}color3f inputs:diffuseColor.connect = ${zt}/${i}/${Di(s.map)}_diffuse.outputs:rgb>`),s instanceof c.MeshBasicMaterial&&s.transparent&&s.alphaTest==0&&t?(r.push(`${o}float inputs:opacity.connect = ${zt}/${i}/${Di(s.map)}_diffuse.outputs:a>`),d=!0,r.push(`${o}float inputs:opacityThreshold = ${1e-10}`),u=!0):s.transparent?(r.push(`${o}float inputs:opacity.connect = ${zt}/${i}/${Di(s.map)}_diffuse.outputs:a>`),d=!0):s.alphaTest>0&&(r.push(`${o}float inputs:opacity.connect = ${zt}/${i}/${Di(s.map)}_diffuse.outputs:a>`),d=!0,r.push(`${o}float inputs:opacityThreshold = ${s.alphaTest}`),u=!0),a.push(Ns(s.map,"diffuse",t,e,s,l,s.color,h))):r.push(`${o}color3f inputs:diffuseColor = ${xb(s.color)}`),s.alphaHash&&t&&(u?console.warn("Opacity threshold for "+s.name+" was already connected. Skipping alphaHash opacity threshold."):(r.push(`${o}float inputs:opacityThreshold = 0.0000000001`),u=!0)),s.aoMap&&(r.push(`${o}float inputs:occlusion.connect = ${zt}/${i}/${Di(s.aoMap)}_occlusion.outputs:r>`),a.push(Ns(s.aoMap,"occlusion",t,e,s,l))),s.alphaMap?(r.push(`${o}float inputs:opacity.connect = ${zt}/${i}/${Di(s.alphaMap)}_opacity.outputs:r>`),r.push(`${o}float inputs:opacityThreshold = 0.0000000001`),d=!0,u=!0,a.push(Ns(s.alphaMap,"opacity",t,e,s,l,new c.Color(1,1,1),h))):(d?console.warn("Opacity for "+s.name+" was already connected. Skipping default opacity."):(r.push(`${o}float inputs:opacity = ${h}`),d=!0),s.alphaTest>0&&(u?console.warn("Opacity threshold for "+s.name+" was already connected. Skipping default opacity threshold."):(r.push(`${o}float inputs:opacityThreshold = ${s.alphaTest}`),u=!0))),s instanceof c.MeshStandardMaterial){if(s.emissiveMap){r.push(`${o}color3f inputs:emissiveColor.connect = ${zt}/${i}/${Di(s.emissiveMap)}_emissive.outputs:rgb>`);const p=s.emissive.clone();p.multiplyScalar(s.emissiveIntensity),a.push(Ns(s.emissiveMap,"emissive",t,e,s,l,p))}else if(s.emissive?.getHex()>0){const p=s.emissive.clone();p.multiplyScalar(s.emissiveIntensity),r.push(`${o}color3f inputs:emissiveColor = ${xb(p)}`)}s.normalMap&&(r.push(`${o}normal3f inputs:normal.connect = ${zt}/${i}/${Di(s.normalMap)}_normal.outputs:rgb>`),a.push(Ns(s.normalMap,"normal",t,e,s,l))),s.roughnessMap&&s.roughness===1?(r.push(`${o}float inputs:roughness.connect = ${zt}/${i}/${Di(s.roughnessMap)}_roughness.outputs:g>`),a.push(Ns(s.roughnessMap,"roughness",t,e,s,l))):r.push(`${o}float inputs:roughness = ${s.roughness!==void 0?s.roughness:1}`),s.metalnessMap&&s.metalness===1?(r.push(`${o}float inputs:metallic.connect = ${zt}/${i}/${Di(s.metalnessMap)}_metallic.outputs:b>`),a.push(Ns(s.metalnessMap,"metallic",t,e,s,l))):r.push(`${o}float inputs:metallic = ${s.metalness!==void 0?s.metalness:0}`)}return s instanceof c.MeshPhysicalMaterial&&(r.push(`${o}float inputs:clearcoat = ${s.clearcoat}`),r.push(`${o}float inputs:clearcoatRoughness = ${s.clearcoatRoughness}`),r.push(`${o}float inputs:ior = ${s.ior}`),!s.transparent&&!(s.alphaTest>0)&&s.transmissionMap&&(r.push(`${o}float inputs:opacity.connect = ${zt}/${i}/${Di(s.transmissionMap)}_transmission.outputs:r>`),a.push(Ns(s.transmissionMap,"transmission",t,e,s,l)))),l.size>2?console.warn("USDZExporter: Material "+s.name+" uses more than 2 UV channels. Currently, only UV0 and UV1 are supported."):l.size===2&&(!l.has(0)||!l.has(1))&&console.warn("USDZExporter: Material "+s.name+" uses UV channels other than 0 and 1. Currently, only UV0 and UV1 are supported."),`
|
|
1251
|
-
|
|
1252
|
-
def Material "${i}" ${s.name?`(
|
|
1253
|
-
displayName = "${Iw(s.name)}"
|
|
1254
|
-
)`:""}
|
|
1255
|
-
{
|
|
1256
|
-
token outputs:surface.connect = ${zt}/${i}/PreviewSurface.outputs:surface>
|
|
1257
|
-
|
|
1258
|
-
def Shader "PreviewSurface"
|
|
1259
|
-
{
|
|
1260
|
-
uniform token info:id = "UsdPreviewSurface"
|
|
1261
|
-
${r.join(`
|
|
1262
|
-
`)}
|
|
1263
|
-
int inputs:useSpecularWorkflow = ${s instanceof c.MeshBasicMaterial?"1":"0"}
|
|
1264
|
-
token outputs:surface
|
|
1265
|
-
}
|
|
1266
|
-
${a.length>0?`
|
|
1267
|
-
${l.has(0)?`
|
|
1268
|
-
def Shader "uvReader_st"
|
|
1269
|
-
{
|
|
1270
|
-
uniform token info:id = "UsdPrimvarReader_float2"
|
|
1271
|
-
string inputs:varname = "st"
|
|
1272
|
-
float2 inputs:fallback = (0.0, 0.0)
|
|
1273
|
-
float2 outputs:result
|
|
1274
|
-
}
|
|
1275
|
-
`:""}
|
|
1276
|
-
${l.has(1)?`
|
|
1277
|
-
def Shader "uvReader_st1"
|
|
1278
|
-
{
|
|
1279
|
-
uniform token info:id = "UsdPrimvarReader_float2"
|
|
1280
|
-
string inputs:varname = "st1"
|
|
1281
|
-
float2 inputs:fallback = (0.0, 0.0)
|
|
1282
|
-
float2 outputs:result
|
|
1283
|
-
}
|
|
1284
|
-
`:""}
|
|
1285
|
-
${a.join(`
|
|
1286
|
-
`)}`:""}
|
|
1287
|
-
}`}function xb(s){return`(${s.r}, ${s.g}, ${s.b})`}function Sb(s){return`(${s.x}, ${s.y})`}const Gg=[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 xt{static global_id=0;id;trigger;action;exclusive=!1;makeExclusive(e){return this.exclusive=e,this}constructor(e,t,i){this.id="Behavior_"+wi(e)+"_"+xt.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 Zr=new Set;function dm(s,e){let t="";if(Array.isArray(s)){Zr.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(Zr.has(o))continue;i+=o,Zr.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(Zr.has(r))continue;i+=r,Zr.add(r)}n+1<s.length&&(i+=", ")}i+=" ]",t=i,Zr.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 lo{static global_id=0;id;targetId;tokenId;type;distance;constructor(e,t){e&&(this.targetId=e),t?this.id=t:this.id="Trigger_"+lo.global_id++}writeTo(e,t){t.beginBlock(`def Preliminary_Trigger "${this.id}"`),this.targetId&&(typeof this.targetId!="string"&&(this.targetId=dm(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 Cb(s,e={direct:!0,indirect:!0}){const t=qe.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 Et{static __sceneStartTrigger;static sceneStartTrigger(){if(this.__sceneStartTrigger!==void 0)return this.__sceneStartTrigger;const e=new lo(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 lo(e);if(Array.isArray(e)&&e.length>1)for(const n of e)n instanceof qe&&Cb(n,t);else e instanceof qe&&Cb(e,t);return i.tokenId="TapGesture",i}static isTapTrigger(e){return e?.tokenId==="TapGesture"}static proximityToCameraTrigger(e,t){const i=new lo(e);return i.tokenId="ProximityToCamera",i.distance=t,i}}class Jo{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 Jt{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 Jt,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+="_"+Jt.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=dm(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=dm(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 Bi{x=0;y=0;z=0;constructor(e,t,i){this.x=e,this.y=t,this.z=i}static get up(){return new Bi(0,1,0)}static get right(){return new Bi(1,0,0)}static get forward(){return new Bi(0,0,1)}static get back(){return new Bi(0,0,-1)}static get zero(){return new Bi(0,0,0)}}class ue{static sequence(...e){return new Jo("Group_"+Jo.getId(),e).makeSequence()}static parallel(...e){return new Jo("Group_"+Jo.getId(),e).makeParallel()}static fadeAction(e,t,i){const n=new Jt(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 Jt(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),ue.sequence(o,d)}return o}static waitAction(e){const t=new Jt;return t.tokenId="Wait",t.duration=e,t.motionType=void 0,t}static lookAtCameraAction(e,t,i,n){const o=new Jt(e);return o.tokenId="LookAtCamera",o.duration=t===void 0?9999999999999:t,o.front=i??Bi.forward,o.up=n??Bi.up,o}static emphasize(e,t,i="bounce",n=1,o="basic"){const r=new Jt(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 Jt(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 Jt(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 Jt(e);return i.tokenId="Impulse",i.velocity=t,i}}class ZM{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 Hg extends ZM{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||qe.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=ue.fadeAction(this.object,0,!0),this._enableAction)}disable(){return this._disableAction?this._disableAction:(this._disableAction=ue.fadeAction(this.object,0,!1),this._disableAction)}}class qw{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 An=x("debugusdzanimation"),um=x("debugusdzanimationserialization");class so{_start;get start(){return this._start===void 0&&(this._start=this.ext.getStartTimeByClip(this.clip)),this._start}get duration(){return this.clip?.duration??Te.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||so.isDescendantOf(e,n))continue;if(!so.isDescendantOf(n,e)){for(;!so.isDescendantOf(n,e)&&n.parent;)n=n.parent;so.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 Te{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=Te.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,lt);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."),A()&&fe("[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 y=0,_=0;if(m<0?(y=e[0],_=y-Te.animationDurationPadding/2+1/60):m>=e.length?(y=e[e.length-1],_=y+Te.animationDurationPadding/2-1/60):(y=e[m],_=y),h){const g=h.evaluate(y);o.set(g[0],g[1],g[2])}if(d){const g=d.evaluate(y);r.set(g[0],g[1],g[2],g[3])}if(u){const g=u.evaluate(y);a.set(g[0],g[1],g[2])}if(this.useRootMotion&&l===this.root){const g=new c.Matrix4;g.compose(o,r,a),g.multiply(l.matrix),g.decompose(o,r,a)}yield{time:_,translation:o,rotation:r,scale:a,index:m}}}}class Bu{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:(Te.restPoseClipDuration+Te.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);An&&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 Te(null,u,null));let m=p[o];m||(m=new Te(e,u,t),p[o]=m),m.addTrack(h),r?.includes(u)||r?.push(u)}An&&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 Te(null,h,null);d[0]=p}let u=d[o];u||(An&&console.log("Adding padding clip for ",h,t,"at slot",o),u=new Te(e,h,t),d[o]=u)}const l=new so(this,e,t);if(this.rootAndClipToRegisteredAnimationMap.set(i,l),An&&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=Te.restPoseClipDuration);let u=this.lastClipEndTime+Te.animationDurationPadding,p=u+t.duration;const m=Math.round(u*60)/60,y=Math.round(p*60)/60;Math.abs(m-u)<.01&&(u=m),Math.abs(y-p)<.01&&(p=y),u=Math.ceil(u),p=u+t.duration,this.clipToStartTime.set(t,u),this.lastClipEndTime=p}}return l}onAfterHierarchy(e){An&&console.log("Animation clips per animation target node",this.dict)}onAfterBuildDocument(e){An&&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 Te(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;um&&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 JM(e,this);this.serializers.push(n),n.registerCallback(t)}}class JM{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)),um&&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 N=[];for(const[$,ee]of k){let J=`${$} : [`;const he=[];for(const Q of ee)he.push(`(${se(Q.x)}, ${se(Q.y)}, ${se(Q.z)})`);J=J.concat(he.join(", ")),J=J.concat("],"),N.push(J)}return N},a=function(k){const N=[];for(const[$,ee]of k){let J=`${$} : [`;const he=[];for(const Q of ee)he.push(`(${se(Q.w)}, ${se(Q.x)}, ${se(Q.y)}, ${se(Q.z)})`);J=J.concat(he.join(", ")),J=J.concat("],"),N.push(J)}return N},l=function(k){let N,$=!0;const ee=new Map;for(const[he,Q]of k){N===void 0&&(N=Q.length),N!==Q.length&&($=!1);let _e=0;for(const Xt of Q)_e++,Xt||(ee.has(he)||ee.set(he,[]),ee.get(he).push(_e))}An&&console.log("Bone count: ",k.size,"TransformData entries per bone: ",N,"Undefined bone entries: ",ee),console.assert($,"All bones should have the same number of TransformData entries",k),console.assert(ee.size===0,"All TransformData entries should be set",ee);const J=[];for(const[he,Q]of k)for(let _e=0;_e<Q.length;_e++){const Xt=Q[_e],Rh=i.getStartTimeByClip(Xt.clip);J.length<=_e&&J.push({pos:[],rot:[],scale:[],timeOffset:Rh});const Fs=J[_e];Fs.pos.push(...Xt.getSortedTimesArray(!0,!1,!1)),Fs.rot.push(...Xt.getSortedTimesArray(!1,!0,!1)),Fs.scale.push(...Xt.getSortedTimesArray(!1,!1,!0))}for(const he of J)he.pos.sort((Q,_e)=>Q-_e),he.rot.sort((Q,_e)=>Q-_e),he.scale.sort((Q,_e)=>Q-_e),he.pos=[...new Set(he.pos)],he.rot=[...new Set(he.rot)],he.scale=[...new Set(he.scale)];return J},h=function(k,N,$){const ee=new Map,J=new Map,he=new Map,Q=N.length;for(const _e of $){const Xt=k.get(_e);let Rh;Xt?console.assert(Xt.length===Q,"We should have the same number of TransformData entries for each bone",Xt,N):Rh=new Te(null,_e,null);for(let Fs=0;Fs<Q;Fs++){const vf=Xt?Xt[Fs]:Rh,Wr=N[Fs];for(const{time:yl,translation:_l}of vf.getValues(Wr.pos,!0,!1,!1)){const Ji=(yl+Wr.timeOffset)*60;ee.has(Ji)||ee.set(Ji,new Array),ee.get(Ji).push(_l.clone())}for(const{time:yl,rotation:_l}of vf.getValues(Wr.rot,!1,!0,!1)){const Ji=(yl+Wr.timeOffset)*60;J.has(Ji)||J.set(Ji,new Array),J.get(Ji).push(_l.clone())}for(const{time:yl,scale:_l}of vf.getValues(Wr.scale,!1,!1,!0)){const Ji=(yl+Wr.timeOffset)*60;he.has(Ji)||he.set(Ji,new Array),he.get(Ji).push(_l.clone())}}}return{position:ee.size==0?void 0:ee,quaternion:J.size==0?void 0:J,scale:he.size==0?void 0:he}},d=function(k){const N=[];for(const $ of k)N.push(`(${se($.x)}, ${se($.y)}, ${se($.z)})`);return N.join(", ")},u=function(k){const N=[];for(const $ of k)N.push(`(${se($.w)}, ${se($.x)}, ${se($.y)}, ${se($.z)})`);return N.join(", ")},p=function(k){const N=new Map;if(An){const $=new Array;for(const[ee,J]of o)$.push(ee.uuid+": "+J.length+" "+J.map(he=>he.clip?.uuid.substring(0,6)).join(" "));console.log(`getPerBoneTransformData
|
|
1288
|
-
`+$.join(`
|
|
1289
|
-
`))}for(const $ of k){const ee=o.get($);ee&&N.set($,ee)}return N},m=function(k){const N=p(k),$=l(N);return h(N,$,k)};const y=n.skinnedMesh.skeleton,_=new Array,g=[],w=[];for(const k of y.bones){g.push(k),w.push(k.uuid);const N=y.boneInverses[y.bones.indexOf(k)];_.push({bone:k,inverse:N})}let b=1e4;for(;w.length<y.bones.length&&b-- >0;)for(const k of g){const N=k.children;for(const $ of N)if(w.indexOf($.uuid)===-1&&y.bones.indexOf($)!==-1){g.push($),w.push($.uuid);const ee=y.boneInverses[y.bones.indexOf($)];_.push({bone:$,inverse:ee})}}b<=0&&console.error("Failed to sort bones in skinned mesh",n.skinnedMesh,y.bones,w);for(const k of Bw(y.bones))_.push({bone:k,inverse:k.matrixWorld.clone().invert()});const v=_[0].bone.parent;v||console.error("No bone parent found for skinned mesh during USDZ export",n.skinnedMesh),_.sort((k,N)=>Pa(k.bone,v)>Pa(N.bone,v)?1:-1);const E=t.quickLookCompatible,O=[],M=[],D=[],L=[];for(const{bone:k}of _){if(E){const N=k.scale;N.x==0&&(N.x=1e-5),N.y==0&&(N.y=1e-5),N.z==0&&(N.z=1e-5),O.push(new c.Matrix4().compose(k.position,k.quaternion,k.scale))}else O.push(k.matrix.clone());M.push(k.position),D.push(k.quaternion),L.push(k.scale)}const j=_.map(k=>'"'+Pa(k.bone,v)+'"').join(", "),V=_.map(k=>vb(k.inverse.clone().invert())).join(", ");e.beginBlock('def Skeleton "Rig"'),e.appendLine(`uniform matrix4d[] bindTransforms = [${V}]`),e.appendLine(`uniform token[] joints = [${j}]`),e.appendLine('uniform token purpose = "guide"'),e.appendLine(`uniform matrix4d[] restTransforms = [${O.map(k=>vb(k)).join(", ")}]`);const W=m(_.map(k=>k.bone));if(An){let k=1e7,N=0;for(const $ of W.position?.keys()??[])k=Math.min(k,$),N=Math.max(N,$);console.log("Time samples",k,N,W)}if(e.beginBlock('def SkelAnimation "_anim"'),e.appendLine(`uniform token[] joints = [${j}]`),e.appendLine(`quatf[] rotations = [${u(D)}]`),W&&W.quaternion){e.beginBlock("quatf[] rotations.timeSamples = {","");const k=a(W.quaternion);for(const N of k)e.appendLine(N);e.closeBlock()}if(e.appendLine(`half3[] scales = [${d(L)}]`),W&&W.scale){e.beginBlock("half3[] scales.timeSamples = {","");const k=r(W.scale);for(const N of k)e.appendLine(N);e.closeBlock()}if(e.appendLine(`float3[] translations = [${d(M)}]`),W&&W.position){e.beginBlock("float3[] translations.timeSamples = {","");const k=r(W.position);for(const N of k)e.appendLine(N);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 Te(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;um&&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 y=d[m];if(!y)continue;const _=n.getStartTimeByClip(y.clip),g=y.getSortedTimesArray(u==="position",u==="rotation",u==="scale");if(!g||g.length===0){console.error("got an animated object but no time values?",o,y);continue}const w=!y.clip,b=u==="position"&&(y.pos||w),v=u==="rotation"&&(y.rot||w),E=u==="scale"&&(y.scale||w);if(b||v||E){const O=y.clip?.name??"rest",M=y.getDuration();An&&console.log("Write .timeSamples:",O,_,M,d),e.appendLine("# "+O+": start="+l.format(_*Te.frameRate)+", length="+l.format(M*Te.frameRate)+", frames="+y.getFrames())}if(b)for(const{time:O,translation:M}of y.getValues(g,!0,!1,!1)){const L=`${l.format((_+O)*Te.frameRate)}: (${se(M.x)}, ${se(M.y)}, ${se(M.z)}),`;e.appendLine(L)}if(v)for(const{time:O,rotation:M}of y.getValues(g,!1,!0,!1)){const L=`${l.format((_+O)*Te.frameRate)}: (${se(M.w)}, ${se(M.x)}, ${se(M.y)}, ${se(M.z)}),`;e.appendLine(L)}if(E)for(const{time:O,scale:M}of y.getValues(g,!1,!1,!0)){const L=`${l.format((_+O)*Te.frameRate)}: (${se(M.x)}, ${se(M.y)}, ${se(M.z)}),`;e.appendLine(L)}}e.closeBlock()}}h(a,"position"),h(a,"rotation"),h(a,"scale")}}const ek=x("debugusdz");class kr{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)),wi(n)+"."+t}get extensionName(){return"Audio"}files=new Array;onExportObject(e,t,i){const n=S.getComponents(e,vi);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=kr.getName(o.clip),l=wi(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]){ek&&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 tk=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&&tk(e,t,n),n};const Pb=x("debugusdzbehaviours");class Rr extends R{object;target;duration=1;relativeMotion=!1;coroutine=null;targetPos=new c.Vector3;targetRot=new c.Quaternion;targetScale=new c.Vector3;onEnable(){this.context.accessibility.updateElement(this,{role:"button",label:"Move "+(this.object?.name||"object")+" to "+(this.target?.name||"target")+" on click",hidden:!1})}onDisable(){this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this)}onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}onPointerClick(e){const t=this.object?.getComponentsInChildren($e);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=Y(this.object).clone(),t=Y(this.target).clone(),i=pe(this.object).clone(),n=pe(this.target).clone(),o=je(this.object).clone(),r=je(this.target).clone(),a=e.distanceTo(t),l=i.angleTo(n),h=o.distanceTo(r);if(a<.01&&l<.01&&h<.01){at(this.object,t),dn(this.object,n),Ra(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),at(this.object,this.targetPos),dn(this.object,this.targetRot),Ra(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 xt("Move to "+this.target?.name,Et.tapTrigger(this.gameObject),ue.transformAction(this.object,this.target,this.duration,this.relativeMotion?"relative":"absolute"));e.addBehavior(t)}}}Ae([f(c.Object3D)],Rr.prototype,"object");Ae([f(c.Object3D)],Rr.prototype,"target");Ae([f()],Rr.prototype,"duration");Ae([f()],Rr.prototype,"relativeMotion");const Fu=class Ut extends R{materialToSwitch;variantMaterial;fadeDuration=0;start(){this._objectsWithThisMaterial=this.objectsWithThisMaterial,A()&&this._objectsWithThisMaterial.length<=0&&console.warn('ChangeMaterialOnClick: No objects found with material "'+this.materialToSwitch?.name+'"')}onEnable(){this.context.accessibility.updateElement(this,{role:"button",label:"Change material to "+(this.variantMaterial?.name||"unknown material"),hidden:!1})}onDisable(){this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this)}onPointerEnter(e){this.context.input.setCursor("pointer")}onPointerExit(e){this.context.input.unsetCursor("pointer")}onPointerClick(e){if(e.use(),!!this.variantMaterial)for(let t=0;t<this.objectsWithThisMaterial.length;t++){const i=this.objectsWithThisMaterial[t];i.material=this.variantMaterial}}_objectsWithThisMaterial=null;get objectsWithThisMaterial(){return this._objectsWithThisMaterial!=null?this._objectsWithThisMaterial:(this._objectsWithThisMaterial=[],this.variantMaterial&&this.materialToSwitch&&this.context.scene.traverse(e=>{if(e instanceof 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):y0(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=[],Ut._materialTriggersPerId={},Ut.variantSwitchIndex=0,this.materialToSwitch&&await re.NEEDLE_progressive.assignTextureLOD(this.materialToSwitch,0),this.variantMaterial&&await re.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&&(Ut._materialTriggersPerId[this.materialToSwitch.uuid]||(Ut._materialTriggersPerId[this.materialToSwitch.uuid]=[]),Ut._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(e,t){if(!this.materialToSwitch)return;const i=Ut._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 Ut._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(e,t,i){const n=[],o=Math.max(0,this.fadeDuration);n.push(ue.fadeAction([...this.targetModels,...i],o,!1)),n.push(ue.fadeAction(t,o,!0)),e.addBehavior(new xt("Select_"+this.selfModel.name,Et.tapTrigger(this.selfModel),ue.parallel(...n))),Ut._parallelStartHiddenActions.push(...t),Ut._startHiddenBehaviour||(Ut._startHiddenBehaviour=new xt("StartHidden_"+this.selfModel.name,Et.sceneStartTrigger(),ue.fadeAction(Ut._parallelStartHiddenActions,o,!1)),e.addBehavior(Ut._startHiddenBehaviour))}static getMaterialName(e){return wi(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_"+Ut.variantSwitchIndex+++"_"+Ut.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())&&qe.createEmptyParent(t),t.parent&&t.parent.add(i),e.push(i)}return e}};Ae([f(c.Material)],Fu.prototype,"materialToSwitch");Ae([f(c.Material)],Fu.prototype,"variantMaterial");Ae([f()],Fu.prototype,"fadeDuration");let qg=Fu;const ih=class Me extends R{target;toggleOnClick=!1;targetState=!0;hideSelf=!0;onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}onPointerClick(e){e.use(),!this.toggleOnClick&&this.hideSelf&&(this.gameObject.visible=!1),this.target&&(this.target.visible=this.toggleOnClick?!this.target.visible:this.targetState)}selfModel;selfModelClone;targetModel;toggleModel;createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t,this.selfModelClone=t.clone())}stateBeforeCreatingDocument=!1;targetStateBeforeCreatingDocument=!1;static clonedToggleIndex=0;static wasVisible=Symbol("usdz_SetActiveOnClick_wasVisible");static toggleClone=Symbol("clone for toggling");static reverseToggleClone=Symbol("clone for reverse toggling");beforeCreateDocument(){this.target&&(this.gameObject[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())&&Wg.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(ue.fadeAction(n,0,!1)),a.push(ue.fadeAction(this.toggleModel,0,!0)),a.push(ue.fadeAction(this.targetModel,0,o)),e.addBehavior(new xt("Toggle_"+n.name+"_ToggleTo"+(o?"On":"Off"),Et.tapTrigger(n),ue.parallel(...a)));const l=[];l.push(ue.fadeAction(this.toggleModel,0,!1)),l.push(ue.fadeAction(n,0,!0)),l.push(ue.fadeAction(this.targetModel,0,!o)),e.addBehavior(new xt("Toggle_"+n.name+"_ToggleTo"+(o?"Off":"On"),Et.tapTrigger(this.toggleModel),ue.parallel(...l)))}}else{const a=[];this.hideSelf&&a.push(ue.fadeAction(n,0,!1)),a.push(ue.fadeAction(this.targetModel,0,o)),e.addBehavior(new xt("Toggle_"+n.name+"_ToggleTo"+(o?"On":"Off"),Et.tapTrigger(n),a.length>1?ue.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),Ii.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]}};Ae([f(c.Object3D)],ih.prototype,"target");Ae([f()],ih.prototype,"toggleOnClick");Ae([f()],ih.prototype,"targetState");Ae([f()],ih.prototype,"hideSelf");let Xg=ih;class Ii extends R{static _fadeBehaviour;static _fadeObjects=[];static add(e,t){const i=Array.isArray(e)?e:[e];for(const n of i)Ii._fadeObjects.includes(n)||(console.log("adding hide on start",n),Ii._fadeObjects.push(n));Ii._fadeBehaviour===void 0&&(Ii._fadeBehaviour=new xt("HideOnStart",Et.sceneStartTrigger(),ue.fadeAction(Ii._fadeObjects,0,!1)),t.addBehavior(Ii._fadeBehaviour))}start(){S.setActive(this.gameObject,!1)}createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.wasVisible||Ii.add(t,e))}wasVisible=!1;beforeCreateDocument(){this.wasVisible=S.isActiveSelf(this.gameObject)}}class Ya extends R{target;duration=.5;motionType="bounce";onEnable(){this.context.accessibility.updateElement(this,{role:"button",label:"Emphasize "+this.target?.name+" on click",hidden:!1})}onDisable(){this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this)}beforeCreateDocument(){}createBehaviours(e,t,i){if(this.target&&t.uuid===this.gameObject.uuid){const n=new xt("emphasize "+this.name,Et.tapTrigger(this.gameObject),ue.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));e.addBehavior(n)}}afterCreateDocument(e,t){}}Ae([f()],Ya.prototype,"target");Ae([f()],Ya.prototype,"duration");Ae([f()],Ya.prototype,"motionType");class fo extends R{target;clip="";toggleOnClick=!1;trigger="tap";ensureAudioSource(){if(!this.target){const e=this.gameObject.addComponent(vi);e&&(this.target=e,e.spatialBlend=1,e.volume=1,e.loop=!1,e.preload=!0)}}onEnable(){this.context.accessibility.updateElement(this,{role:"button",label:"Play audio: "+(this.clip||this.target?.clip||"unknown clip"),hidden:!1})}onDisable(){this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this)}onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}onPointerClick(e){e.use(),!(!this.target?.clip&&!this.clip)&&(this.ensureAudioSource(),this.target&&(this.target.isPlaying&&this.toggleOnClick?this.target.stop():(!this.toggleOnClick&&this.target.isPlaying&&this.target.stop(),this.clip?this.target.play(this.clip):this.target.play())))}createBehaviours(e,t,i){if(!(!this.target&&!this.clip)&&t.uuid===this.gameObject.uuid){const n=this.clip?this.clip:this.target?this.target.clip:void 0;if(!n||typeof n!="string")return;const o=this.target?this.target.gameObject:this.gameObject;kr.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=ue.playAudioAction(o,h,"play",r,a);this.target&&this.target.loop&&(d=ue.sequence(d).makeLooping());const u=this.name?"_"+this.name:"";if(l&&this.trigger==="tap"){this.toggleOnClick&&(d.multiplePerformOperation="stop");const p=new xt("playAudio"+u,Et.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 xt("playAudioOnStart"+u,Et.sceneStartTrigger(),d);e.addBehavior(p)}}}}Ae([f(vi)],fo.prototype,"target");Ae([f(URL)],fo.prototype,"clip");Ae([f()],fo.prototype,"toggleOnClick");const Qg=class On extends R{animator;stateName;trigger="tap";animation;get target(){return this.animator?.gameObject||this.animation?.gameObject}onEnable(){this.context.accessibility.updateElement(this,{role:"button",label:"Plays animation "+(this.stateName||"")+" on "+(this.target?this.target.name:""),hidden:!1})}onDisable(){this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this)}onPointerEnter(){this.context.input.setCursor("pointer"),this.context.accessibility.hover(this,"Click to play animation "+(this.stateName||"")+" on "+(this.target?this.target.name:""))}onPointerExit(){this.context.input.unsetCursor("pointer")}onPointerClick(e){e.use(),this.target&&this.stateName&&(this.context.accessibility.focus(this),this.animator?.play(this.stateName,0,0,.1))}selfModel;stateAnimationModel;animationSequence=new Array;animationLoopAfterSequence=new Array;randomOffsetNormalized=0;createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t)}static animationActions=[];static rootsWithExclusivePlayback=new Set;afterSerialize(){if(On.rootsWithExclusivePlayback.size>1){const e='Multiple root objects targeted by more than one animation. To work around QuickLook bug FB13410767, animations will be set as "exclusive" and activating them will stop other animations being marked as exclusive.';A()&&fe(e),console.warn(e,...On.rootsWithExclusivePlayback)}On.animationActions=[],On.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 Bu);if(!n)return;const o=n.getClipCount(this.target)>1;o&&(A()&&console.warn("Setting exclusive playback for "+this.target.name+"@"+this.stateName+" because it has "+n.getClipCount(this.target)+" animations. This works around QuickLook bug FB13410767."),On.rootsWithExclusivePlayback.add(this.target));const r=this.name?this.name:"";i.traverse(a=>{if(a.uuid===this.target?.uuid){const l=On.getActionForSequences(i,a,this.animationSequence,this.animationLoopAfterSequence,this.randomOffsetNormalized),h=new xt(this.trigger+"_"+r+"_toPlayAnimation_"+this.stateName+"_on_"+this.target?.name,this.trigger=="tap"?Et.tapTrigger(this.selfModel):Et.sceneStartTrigger(),l);o&&h.makeExclusive(!0),e.addBehavior(h)}})}static getActionForSequences(e,t,i,n,o){const r=(l,h)=>{let d=On.animationActions.find(u=>u.affectedObjects==l&&u.start==h.start&&u.duration==h.duration&&u.animationSpeed==h.speed);return d||(d=ue.startAnimationAction(l,h),On.animationActions.push(d)),d},a=ue.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:ue.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(ue.waitAction(o)),a}static getAndRegisterAnimationSequences(e,t,i){if(!t)return;const n=t.getComponent(lt),o=t.getComponent(Tt);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 y=e.registerAnimation(t,o.clip);y&&(o.loop?a.push(y):r.push(y));let _=0;if(o.minMaxOffsetNormalized){const g=o.minMaxOffsetNormalized.x,w=o.minMaxOffsetNormalized.y;_=(o.clip?.duration||1)*(g+Math.random()*(w-g))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:_}}const l=n?.runtimeAnimatorController;let h=l?.findState(i),d=[],u=[];if(l&&h){const y=new Array;y.push(h);let _=!1;for(;y.length<100;){if(!h||h===null||!h.transitions||h.transitions.length===0){h.motion?.isLooping&&(_=!0);break}const g=h.transitions.find(b=>b.conditions.length===0),w=g?l.getState(g.destinationState,0):null;if(w&&y.includes(w)){h=w,_=!0;break}else if(g){if(h=w,!h)break;y.push(h)}else{_=h.motion?.isLooping??!1;break}}if(_&&h){const g=y.indexOf(h);d=y.slice(0,g),u=y.slice(g),Pb&&console.log("found loop from "+i,"states until loop",d,"states looping",u)}else d=y,u=[],Pb&&console.log("found no loop from "+i,"states",d);if(!u.length){const g=d[d.length-1],w=g.motion?.clip;if(w){let b;if(e.holdClipMap.has(w))b=e.holdClipMap.get(w);else{const v=g.name+"_hold";b=w.clone(),b.duration=1,b.name=v;const E=w.duration;b.tracks=w.tracks.map(O=>{const M=O.clone();M.times=new Float32Array([0,E]);const D=O.values.length,L=O.getValueSize(),j=O.values.slice(D-L,D);return M.values=new Float32Array(2*L),M.values.set(j,0),M.values.set(j,L),M}),b.name=v,e.holdClipMap.set(w,b)}if(b){const v={name:b.name,motion:{clip:b,isLooping:!1,name:b.name},speed:1,transitions:[],behaviours:[],hash:g.hash+1};u.push(v)}}}}if(d.length===1&&(!d[0].motion?.clip||d[0].motion?.clip.tracks?.length===0)){r=new Array;const y=e.registerAnimation(t,null);y&&r.push(y);return}if(d=d.filter(y=>y.motion?.clip&&y.motion?.clip.tracks?.length>0),u=u.filter(y=>y.motion?.clip&&y.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=(y,_)=>{if(!t)return;const g=e.registerAnimation(t,y.motion.clip??null);g?(g.speed=y.speed,_.push(g)):console.warn("Couldn't register animation for state "+y.name+" on "+n?.name)};if(d.length>0){r=new Array;for(const y of d)p(y,r)}if(u.length>0){a=new Array;for(const y of u)p(y,a)}let m=0;if(n&&l&&n.minMaxOffsetNormalized){const y=n.minMaxOffsetNormalized.x,_=n.minMaxOffsetNormalized.y;m=((d.length?d[0]:u.length?u[0]:null)?.motion.clip?.duration||1)*(y+Math.random()*(_-y))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:m}}createAnimation(e,t,i){if(!this.target||!this.animator&&!this.animation)return;const n=On.getAndRegisterAnimationSequences(e,this.target,this.stateName);n&&(this.animationSequence=n.animationSequence,this.animationLoopAfterSequence=n.animationLoopAfterSequence,this.randomOffsetNormalized=n.randomTimeOffset,this.stateAnimationModel=t)}};Ae([f(lt)],Qg.prototype,"animator");Ae([f()],Qg.prototype,"stateName");let Oc=Qg;class Ka extends R{getType(){}target;getDuration(){}}Ae([f(c.Object3D)],Ka.prototype,"target");class nh extends R{target}Ae([f(Ka)],nh.prototype,"target");class sh extends Ka{type=1;duration=1;getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}Ae([f()],sh.prototype,"type");Ae([f()],sh.prototype,"duration");class Yg extends nh{}const ik=100,nk=200,sk=300;class co{static _instance;static create(){return new co}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 Fi.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(vt("view_in_ar")),oo.setElementPriority(e,nk);let n=!1,o=null;return e.addEventListener("click",()=>{o=Wa(Wn),o||(n=!0,o=new Wn),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(vt("view_in_ar")),i.title="Click to start an AR session",i.addEventListener("click",()=>q.start(t,e)),oo.setElementPriority(i,sk),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(vt("panorama_photosphere")),i.title="Click to start a VR session",i.addEventListener("click",()=>q.start(t,e)),oo.setElementPriority(i,ik),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(vt("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&&Se("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 Fi.getOrCreate().createQRCode()}updateSessionSupported(e,t){if(!(t==="immersive-ar"&&exports.DeviceUtilities.isiOS()&&!exports.DeviceUtilities.isVisionOS())){if(!("xr"in navigator)){e.style.display="none";return}q.isSessionSupported(t).then(i=>{e.style.display=i?"":"none",A()&&!i&&console.log('[WebXR] "'+t+'" is not supported on this device. Make sure your server runs using HTTPS and you have a device connected that supports '+t)})}}hideElementDuringXRSession(e){fu(t=>{e["previous-display"]=e.style.display,e.style.setProperty("display","none","important")}),Gm(t=>{e["previous-display"]!=null&&(e.style.display=e["previous-display"])})}listenToXRSessionState(e,t){t&&(q.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"))}),q.onSessionRequestEnd(i=>{e.classList.remove("this-mode-is-requested"),e.classList.remove("other-mode-is-requested"),e.disabled=e["was-disabled"]}))}}var ok=Object.defineProperty,rk=Object.getOwnPropertyDescriptor,ct=(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 ac=x("debugspriterenderer"),ak=x("wireframe");class yr{static cache={};static getOrCreateGeometry(e){if(e.__cached_geometry)return e.__cached_geometry;if(e.guid&&yr.cache[e.guid])return ac&&console.log("Take cached geometry for sprite",e.guid),yr.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),ac&&console.log("Built sprite geometry",e,t),t}}class lk{x;y}function Xw(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 Ms=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(yr.getOrCreateGeometry(this),this.material)),this._mesh}_mesh;get material(){return this._material||(this.texture&&Xw(this.texture),this._material=new c.MeshBasicMaterial({map:this.texture,color:16777215,side:c.DoubleSide,transparent:!0})),this._material}_material;getGeometry(){return yr.getOrCreateGeometry(this)}};ct([f()],Ms.prototype,"guid",2);ct([f(c.Texture)],Ms.prototype,"texture",2);ct([Be()],Ms.prototype,"triangles",2);ct([Be()],Ms.prototype,"uv",2);ct([Be()],Ms.prototype,"vertices",2);const sp=Symbol("spriteOwner");class Ba{sprites;constructor(){this.sprites=[]}}ct([f(Ms)],Ba.prototype,"sprites",2);const Kg=class fm{static create(){const e=new fm;return e.spriteSheet=new Ba,e}constructor(){}clone(){const e=new fm;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 Ba,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&&(Xw(n),!i.__hasLoadedProgressive)){i.__hasLoadedProgressive=!0;const o=n;re.NEEDLE_progressive.assignTextureLOD(n,0).then(r=>{r instanceof c.Texture&&(i.texture=r,e?.map===o&&(e.map=r,e.needsUpdate=!0))})}}};ct([f(Ba)],Kg.prototype,"spriteSheet",2);ct([f()],Kg.prototype,"index",2);let Oa=Kg;class ci extends R{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=Oa.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);ac&&console.log("[SpriteSheet] Set index to "+t+" (was "+this.spriteIndex+")",e),this.spriteIndex=t}else e instanceof Ms?(this._spriteSheet||(this._spriteSheet=Oa.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=Oa.create(),ac&&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 ac&&console.warn("Sprite not found",this.spriteIndex,t.spriteSheet.sprites),!1;if(this._currentSprite)this._currentSprite.geometry=yr.getOrCreateGeometry(i),this._currentSprite.material.map=i.texture;else{const n=new c.MeshBasicMaterial({color:16777215,side:c.DoubleSide});if(ak&&(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[sp]!==void 0&&o[sp]!==this&&this.spriteFrames>1&&(o=i.texture=o.clone()),o[sp]=this,n.map=o}this.sharedMaterial=n,this._currentSprite=new c.Mesh(yr.getOrCreateGeometry(i),n),this._currentSprite.renderOrder=Math.round(this.renderOrder),re.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}}ct([f()],ci.prototype,"drawMode",2);ct([f(lk)],ci.prototype,"size",2);ct([f(te)],ci.prototype,"color",2);ct([f(c.Material)],ci.prototype,"sharedMaterial",2);ct([f()],ci.prototype,"transparent",2);ct([f()],ci.prototype,"cutoutThreshold",2);ct([f()],ci.prototype,"castShadows",2);ct([f()],ci.prototype,"renderOrder",2);ct([f()],ci.prototype,"toneMapped",2);ct([f(Oa)],ci.prototype,"sprite",1);const Ob=x("debugwebxr"),ck=new c.Matrix4().makeRotationY(Math.PI);class Ui extends R{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){Ob&&console.log("ENTER WEBXR: SessionRoot start..."),this._anchor=null,Ui._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=ri(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)bi(i);this._reticle.length=0,this._isPlacing=!0,this.context.input.addEventListener("pointerup",this.onPlaceScene,{queue:ti.Early})}onLeaveXR(){this.context.input.removeEventListener("pointerup",this.onPlaceScene,{queue:ti.Early}),this.onRevertSceneChanges(),this._anchor=null,Ui._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 nu(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=uo(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(Ob){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(F(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(q.active?.isTrackingImages){console.warn("Scene Placement is disabled while images are being tracked");return}let i=this._hits[0];if(e&&e.origin instanceof Hm){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),Ui._hasPlaced=!0,this.useXRAnchor&&this.onCreateAnchor(q.active,i),this.context.xr)for(const n of this.context.xr.controllers)n.cancelHitTestSource()};onSetScale(){if(!Ui._hasPlaced)return;const e=q.active?.rig?.gameObject;if(e){const t=q.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),A()&&fe("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=q.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(ck),t.matrix.premultiply(this._startOffset),t.matrix.decompose(t.position,t.quaternion,t.scale),i.add(t)}}class nu{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(nu.up,nu.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:ti.Early}),this.context.input.addEventListener("pointerdown",this.onPointerDownLate,{queue:ti.Late}),this.context.input.addEventListener("pointerup",this.onPointerUpEarly,{queue:ti.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:ti.Early}),this.context.input.removeEventListener("pointerdown",this.onPointerDownLate,{queue:ti.Late}),this.context.input.removeEventListener("pointerup",this.onPointerUpEarly,{queue:ti.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 to=x("debugautosync"),op=Symbol("syncerId");class hk{_syncers={};getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];const t=new dk(e);return t[op]=e.guid,this._syncers[t[op]]=t,t}removeSyncer(e){delete this._syncers[e[op]]}}const Zg=new hk;class dk{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||(to&&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];to&&console.log("SEND",this.comp.guid,this.networkingKey),e.send(this.networkingKey,{guid:this.comp.guid,property:t,data:i},ln.Queued),delete this.changedProperties[t]}};onHandleReceiving=e=>{if(to&&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 uk(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 lc=Symbol("AutoSyncHandler");function fk(s){if(s[lc])return s[lc];const e=Zg.getOrCreateSyncer(s);return e?.init(s),s[lc]=e,e}function pk(s){const e=s[lc];e&&(Zg.removeSyncer(e),e.destroy(),delete s[lc])}const Jg=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&&(A()||to)&&s!=null&&console.warn('syncField: no callback function found for property "'+i+'"','"'+s+'"');const r=e,a=r.__internalAwake;if(typeof a!="function"){(to||A())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+e?.constructor?.name+'" is not supported',e);return}to&&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){(A()||to)&&console.warn("Recursive call detected",i);return}u=!0;try{const y=uk(p,m);to&&console.log("SyncField assignment",i,"changed?",y,p,o),y&&o?.call(this,p,m)!==!1&&fk(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(){pk(this),h.call(this)}}};var mk=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&&mk(e,t,n),n};const Nt=x("debugplayersync"),zu=class Qw extends R{static async setupFrom(e,t){const i=Z.getOrCreateFromUrl(e);if(!i.asset){const r=await i.loadAssetAsync();r&&S.getOrAddComponent(r,zi)}const n=new Qw;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 ne)}onEnable(){this.context.connection.beginListen(K.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(K.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(K.LeftRoom,this.destroyInstance),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(K.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(K.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(K.LeftRoom,this.destroyInstance)}onJoinedRoom=()=>{Nt&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()};async getInstance(){if(this._localInstance)return this._localInstance;if(Nt&&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,zi);if(Nt&&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=>{Nt&&console.log("PlayerSync.destroyInstance",e),zc(e,this.context.connection,!0,{saveInRoom:!1})}),this._localInstance=void 0};watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=zi.all.length-1;t>=0;t--){const i=zi.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}};Uu([f()],zu.prototype,"autoSync");Uu([f(Z)],zu.prototype,"asset");Uu([f(ne)],zu.prototype,"onPlayerSpawned");let ey=zu;var Yw=(s=>(s.OwnerChanged="ownerChanged",s))(Yw||{});const pm=class gt extends R{static _all=[];static get all(){return gt._all}static _local=[];static get local(){return gt._local}static getFor(e){if(e instanceof c.Object3D)return S.getComponentInParent(e,gt);if(e instanceof R)return S.getComponentInParent(e.gameObject,gt)}static isLocalPlayer(e){return gt.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 ne;onFirstOwnerChangeEvent=new ne;hasOwner=!1;owner;dontDestroy=!1;get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(e,t){Nt&&console.log(`PlayerSync.onOwnerChange: ${t} → ${e} (me: ${this.context.connection.connectionId})`);const i=gt._local.indexOf(this);i>=0&>._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){gt._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),gt.dispatchEvent("ownerChanged",o)}awake(){gt.all.push(this),Nt&&console.log("Registered new PlayerState",this.guid,gt.all.length-1,gt.all),this.context.connection.beginListen(K.UserLeftRoom,this.onUserLeftRoom)}async start(){Nt&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await _s(300),this.context.connection.userIsInRoom(this.owner)==!1&&(Nt&&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||(Nt&&console.warn("PlayerState.start → owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?Nt&&console.warn("PlayerState.start → owner is still undefined but dontDestroy is set to true",this.name):(Nt&&console.warn(`PlayerState.start → owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):Nt&&console.log("PlayerState.start → owner is assigned",this.owner)},2e3))}doDestroy(){Nt&&console.log("PlayerSync.doDestroy → syncDestroy",this.name),zc(this.gameObject,this.context.connection,!0,{saveInRoom:!1})}onDestroy(){if(Nt&&console.warn("PlayerState.onDestroy",this.owner),this.context.connection.stopListen(K.UserLeftRoom,this.onUserLeftRoom),gt.all.splice(gt.all.indexOf(this),1),this.isLocalPlayer){const e=gt._local.indexOf(this);e>=0&>._local.splice(e,1)}}onUserLeftRoom=e=>{if(e.userId===this.owner){Nt&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}}};Uu([Jg(pm.prototype.onOwnerChange)],pm.prototype,"owner");let zi=pm;var gk=Object.defineProperty,Za=(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&&gk(e,t,n),n};class Yn extends R{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))}}Za([f()],Yn.prototype,"position");Za([f()],Yn.prototype,"showNeedleLogo");Za([f()],Yn.prototype,"showSpatialMenu");Za([f()],Yn.prototype,"createFullscreenButton");Za([f()],Yn.prototype,"createMuteButton");Za([f()],Yn.prototype,"createQRCodeButton");var yk=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&&yk(e,t,n),n};const Sl=x("debugwebxr"),Mb=new c.Quaternion().setFromAxisAngle(new c.Vector3(0,1,0),Math.PI);class po extends R{head;leftHand;rightHand;_leftHandMeshes;_rightHandMeshes;_syncTransforms;async onEnterXR(e){if(!this.activeAndEnabled)return;Sl&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const t=zi.getFor(this);if(t?.owner){const i=this.gameObject.addComponent(Oe);i.avatar=this.gameObject,i.connectionId=t.owner,this.context.players.setPlayerView(t.owner,this.head?.asset,gs.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(Oe);t&&t.destroy()}onUpdateXR(e){if(!this.activeAndEnabled)return;const t=zi.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,ji);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(Mb),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(Mb),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=>{ls(o,!n)})}}updateRemoteAvatarVisibility(){if(this.context.connection.isConnected){const e=zi.getFor(this);if(e&&e.isLocalPlayer==!1){const t=q.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,ji);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};Zv.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 Z("",this.sourceId,this.head));else{const e=new c.Object3D;e.name="Head";const t=bo.createPrimitive(Va.Cube);e.add(t),this.gameObject.add(e),this.head=new Z("",this.sourceId,e),Sl&&console.log("Create head",e)}if(this.rightHand)this.rightHand instanceof c.Object3D&&(this.rightHand=new Z("",this.sourceId,this.rightHand));else{const e=new c.Object3D;e.name="Right Hand",this.gameObject.add(e),this.rightHand=new Z("",this.sourceId,e),Sl&&console.log("Create right hand",e)}if(this.leftHand)this.leftHand instanceof c.Object3D&&(this.leftHand=new Z("",this.sourceId,this.leftHand));else{const e=new c.Object3D;e.name="Left Hand",this.gameObject.add(e),this.leftHand=new Z("",this.sourceId,e),Sl&&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)}),zi.isLocalPlayer(this.gameObject)&&(this._syncTransforms=S.getComponentsInChildren(this.gameObject,pn))}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 Am(a);Sl&&console.log("Avatar loaded results:",l)}}ty([f(Z)],po.prototype,"head");ty([f(Z)],po.prototype,"leftHand");ty([f(Z)],po.prototype,"rightHand");var _k=Object.defineProperty,Nu=(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&&_k(e,t,n),n};const Vs=x("debugwebxr"),$s=new Array;class vs extends R{createControllerModel=!0;createHandModel=!0;customLeftHand;customRightHand;static factory=new X.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&&na(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&&(na(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&&(na(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(q.active&&(Vs&&($s[0]=Date.now()),this.updateRendering(q.active),Vs)){const e=Date.now()-$s[0];$s.push(e),$s.length>=30&&($s[0]=0,$s.reduce((t,i)=>t+i,0)/$s.length,$s.length=0)}}updateRendering(e){for(let t=0;t<this._models.length;t++){const i=this._models[t];if(!i)continue;const n=i.controller;if(!n.connected){Vs&&console.warn("XRControllerModel.onUpdateXR: controller is not connected anymore",n.side,n.hand);continue}if(i.model&&!i.handmesh)i.model.matrixAutoUpdate=!1,i.model.matrix.copy(n.gripMatrix),i.model.visible=n.isTracking,e.rig?.gameObject.add(i.model);else if(n.inputSource.hand&&i.handmesh){const 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(va))}}}}async loadModel(e,t){if(!e.connected)return console.warn("XRControllerModel.onXRControllerAdded: controller is not connected anymore",e.side),null;const n=await Z.getOrCreate("",t).instantiate();return na(n),q.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||(Vs?B.DrawLabel(t.rayWorldPosition,"No hand found for index "+t.index,.05,5):console.warn("No hand found for index "+t.index));const o=new X.GLTFLoader;gg(o,i),await tu(o,i,this.sourceId??"",this.sourceId??"");const r=Dg(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;na(h);const d=new X.XRHandMeshModel(h,n,o.path,a,o,u=>{const p=r?.gltf;p?.scene.children?.length===0&&(p.scene.children[0]=u),r?.gltf&&un().createBuiltinComponents(e.context,e.sourceId||a,r.gltf,null,r),u.traverse(m=>{m.layers.set(2),q.active?.isPassThrough&&!l&&this.makeOccluder(m),m instanceof c.Mesh&&re.NEEDLE_progressive.assignMeshLOD(m,0)}),t.connected||(Vs&&B.DrawLabel(t.rayWorldPosition,"Hand is loaded but not connected anymore",.05,5),u.removeFromParent())});if(Vs&&h.add(new c.AxesHelper(.5)),t.inputSource.hand){Vs&&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 Vs&&B.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)}}}Nu([f()],vs.prototype,"createControllerModel");Nu([f()],vs.prototype,"createHandModel");Nu([f(Z)],vs.prototype,"customLeftHand");Nu([f(Z)],vs.prototype,"customRightHand");class Vu extends R{}var bk=Object.defineProperty,Co=(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&&bk(e,t,n),n};const rp=x("debugwebxr");class xi extends R{movementSpeed=1.5;rotationStep=30;useTeleport=!0;usePinchToTeleport=!0;useTeleportTarget=!1;useTeleportFade=!1;showRays=!0;showHits=!0;isXRMovementHandler=!0;xrSessionMode="immersive-vr";_didApplyRotation=!1;_didTeleport=!1;onUpdateXR(e){const t=e.xr.rig;if(!t?.gameObject||e.xr.isPassThrough)return;const i=e.xr.leftController,n=e.xr.rightController;i&&this.onHandleMovement(i,t.gameObject),n&&(this.onHandleRotation(n,t.gameObject),this.useTeleport&&this.onHandleTeleport(n,t.gameObject))}onLeaveXR(e){for(const t of this._lines)t.removeFromParent();for(const t of this._hitDiscs)t?.removeFromParent()}onBeforeRender(){this.context.xr?.running&&(this.showRays&&this.renderRays(this.context.xr),this.showHits&&this.renderHits(this.context.xr))}onHandleMovement(e,t){const i=e.getStick("xr-standard-thumbstick");if(i.x!=0||i.y!=0){const n=F(i.x,0,i.y);n.multiplyScalar(this.context.time.deltaTimeUnscaled*this.movementSpeed);const o=je(t);n.multiplyScalar(o.x),n.applyQuaternion(e.xr.poseOrientation),n.y=0,n.applyQuaternion(t.worldQuaternion),A()&&Number.isNaN(n.x)&&console.error("Stick movement resulted in NaN",{stick:i,vec:n}),t.position.add(n),t.updateWorldMatrix(!1,!1);for(const r of t.children)r.updateWorldMatrix(!1,!1)}}onHandleRotation(e,t){if(e._isMxInk)return;const 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=Y(this.context.mainCamera).clone();t.rotateY(o*I.toRadians(this.rotationStep));const l=Y(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 X.GroundedSkybox){const r=n.normal?.dot(F(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,F(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,Vu))return;const r=o.clone();if(rp&&B.DrawSphere(o,.025,16711680,5),this.context.mainCamera?.position){const l=this.context.xr?.getUserOffsetInRig();l&&(l.y=0,r.sub(l),rp&&B.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;rp&&(B.DrawWireSphere(h.point,.025*d,16711680),B.DrawLabel(F(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 y=h.normal.applyQuaternion(pe(h.object));n.quaternion.setFromUnitVectors(vk,y)}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 Yd(e)||e.isUI===!0?!0:e.isScene?!1:e.parent?this.isObjectWithInteractiveComponent(e.parent,t+1):!1}updateHitPointerPosition(e,t,i){const n=F(e.rayWorldPosition);n.add(F(0,0,i-.01).applyQuaternion(e.rayWorldQuaternion)),t.position.lerp(n,this.context.time.deltaTimeUnscaled/.05)}hitPointRaycastFilter=e=>e.type==="SkinnedMesh"?"continue in children":!0;createHitPointObject(){const e=new 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 X.Line2;e.layers.disableAll(),e.layers.enable(2);const t=new X.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 X.LineMaterial({color:16777215,vertexColors:!0,worldUnits:!0,linewidth:.004,transparent:!0,depthWrite:!1,blending:c.AdditiveBlending,dashed:!1});return e.material=o,e}}Co([f()],xi.prototype,"movementSpeed");Co([f()],xi.prototype,"rotationStep");Co([f()],xi.prototype,"useTeleport");Co([f()],xi.prototype,"usePinchToTeleport");Co([f()],xi.prototype,"useTeleportTarget");Co([f()],xi.prototype,"useTeleportFade");Co([f()],xi.prototype,"showRays");Co([f()],xi.prototype,"showHits");const vk=new c.Vector3(0,1,0);var wk=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&&wk(e,t,n),n};const Cl=x("debugwebxr"),xk=x("debugusdz"),it=class ca extends R{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(){q.getXRSync(this.context)}onEnable(){window.location.protocol!=="https:"&&fe('<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(Wn)||(Cl&&console.log("WebXR: Adding USDZExporter"),this._usdzExporter=S.addComponent(this.gameObject,Wn),this._usdzExporter.objectToExport=this.context.scene,this._usdzExporter.autoExportAnimations=!0,this._usdzExporter.autoExportAudioSources=!0))}),this.handleCreatingHTML(),this.handleOfferSession(),this.defaultAvatar===!0&&(Cl&&console.warn("WebXR: No default avatar set, using static default avatar"),this.defaultAvatar=new Z("https://cdn.needle.tools/static/avatars/DefaultAvatar.glb")),this.defaultAvatar&&(this._playerSync=this.gameObject.getOrAddComponent(ey),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 q.isVRSupported()&&this.createVRButton?q.offerSession("immersive-vr","default",this.context):this.createARButton&&await q.isARSupported()&&this.createARButton?q.offerSession("immersive-ar","default",this.context):!1}get session(){return q.active??null}get sessionMode(){return q.activeMode??null}get arSessionRoot(){return this._activeWebARSessionRoot}async enterVR(e){return q.start("immersive-vr",e,this.context)}async enterAR(e){return q.start("immersive-ar",e,this.context)}exitXR(){q.stop()}_exitXRMenuButton;_previousXRState=0;_spatialGrabRaycaster;_activeWebARSessionRoot=null;get isActiveWebXR(){return!ca.activeWebXRComponent||ca.activeWebXRComponent===this}onBeforeXR(e,t){if(!this.isActiveWebXR){console.warn(`WebXR: another WebXR component is already active (${ca.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}ca.activeWebXRComponent=this,e=="immersive-ar"&&this.useDepthSensing&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("depth-sensing"))}async onEnterXR(e){if(!this.isActiveWebXR)return;Cl&&console.log("WebXR onEnterXR"),this._previousXRState=Wt.Global.Mask;const t=e.xr.isVR;if(Wt.Global.Set(t?Ln.VR:Ln.AR),e.xr.isAR){let i=S.findObjectOfType(Ui,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,Ui),this._createdComponentsInSession.push(i)}else(Cl||A())&&console.warn("WebXR: No WebARSessionRoot found in scene and usePlacementReticle is disabled in WebXR component.");this._activeWebARSessionRoot=i,i&&(i.customReticle=this.customARPlacementReticle,i.arScale=this.arScale,i.arTouchTransform=this.usePlacementAdjustment,i.autoPlace=this.autoPlace,i.autoCenter=this.autoCenter,i.useXRAnchor=this.useXRAnchor)}this.useDefaultControls&&this.setDefaultMovementEnabled(!0),(this.showControllerModels||this.showHandModels)&&this.setDefaultControllerRenderingEnabled(!0),this.useSpatialGrab&&(this._spatialGrabRaycaster=S.findObjectOfType(pr)??void 0,this._spatialGrabRaycaster||(this._spatialGrabRaycaster=this.gameObject.addComponent(pr))),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){Wt.Global.Set(this._previousXRState),this._playerSync?.destroyInstance();for(const t of this._createdComponentsInSession)t.destroy();this._createdComponentsInSession.length=0,this._activeWebARSessionRoot=null,this.handleOfferSession(),jc(1).then(()=>ca.activeWebXRComponent=null)}}setDefaultMovementEnabled(e){let t=this.gameObject.getComponent(xi);return!t&&e&&(t=this.gameObject.addComponent(xi),this._createdComponentsInSession.push(t)),t&&(t.enabled=e),t}setDefaultControllerRenderingEnabled(e){let t=this.gameObject.getComponent(vs);return!t&&e&&(t=this.gameObject.addComponent(vs),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=>{Cl&&console.log("WebXR.onAvatarSpawned",e);let t=S.getComponentInChildren(e,po);t??=S.addComponent(e,po)};getButtonsContainer(){return this.getButtonsFactory()}getButtonsFactory(){return this._buttonFactory||(this._buttonFactory=co.getOrCreate()),this._buttonFactory}_buttonFactory;handleCreatingHTML(){if(this.createARButton||this.createVRButton||this.useQuicklookExport){if((exports.DeviceUtilities.isiOS()&&exports.DeviceUtilities.isSafari()||xk)&&this.useQuicklookExport){const e=S.findObjectOfType(Wn);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()&&q.isVRSupported().then(e=>{if(!e){const t=this.getButtonsFactory().createSendToQuestButton();this.addButton(t)}}),this.createQRCode){const e=Wa(Yn);if(e&&e.createQRCodeButton===!1)A()&&console.warn("WebXR: QRCode button is disabled in the Needle Menu component");else if(!exports.DeviceUtilities.isMobileDevice()){const t=Fi.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}};ht([f()],it.prototype,"createVRButton");ht([f()],it.prototype,"createARButton");ht([f()],it.prototype,"createSendToQuestButton");ht([f()],it.prototype,"createQRCode");ht([f()],it.prototype,"useDefaultControls");ht([f()],it.prototype,"showControllerModels");ht([f()],it.prototype,"showHandModels");ht([f()],it.prototype,"usePlacementReticle");ht([f(Z)],it.prototype,"customARPlacementReticle");ht([f()],it.prototype,"usePlacementAdjustment");ht([f()],it.prototype,"arScale");ht([f()],it.prototype,"useXRAnchor");ht([f()],it.prototype,"autoPlace");ht([f()],it.prototype,"autoCenter");ht([f()],it.prototype,"useQuicklookExport");ht([f()],it.prototype,"useDepthSensing");ht([f()],it.prototype,"useSpatialGrab");ht([f(Z)],it.prototype,"defaultAvatar");let $u=it;const td=x("debugusdzbehaviours");class iy{get extensionName(){return"Behaviour"}behaviours=[];addBehavior(e){this.behaviours.push(e)}addAudioClip(e){if(!e||typeof e!="string")return"";const i="audio/"+kr.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)}),td&&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=td;let a=`graph LR
|
|
1290
|
-
`,l="";function h(u){if(u instanceof Jo){r&&(a+=`subgraph Group_${u.id}
|
|
1291
|
-
`);for(const p of u.actions)r&&(a+=`${u.id}[${u.id}] -- ${u.type},loops:${u.loops} --> ${p.id}[${p.id}]
|
|
1292
|
-
`),h(p);r&&(a+=`end
|
|
1293
|
-
`)}else if(u instanceof Jt){u.tokenId==="StartAnimation"&&o.add(u);let p=u.tokenId;u.type!==void 0&&(p+=":"+u.type);const m=u.affectedObjects;if(m)if(Array.isArray(m))for(const _ of m)i.add(_),r&&(l+=`${u.id}[${u.id}
|
|
1294
|
-
${p}] -- ${p} --> ${_.uuid}(("${_.displayName||_.name||_.uuid}"))
|
|
1295
|
-
`);else typeof m=="object"?(i.add(m),r&&(l+=`${u.id}[${u.id}
|
|
1296
|
-
${p}] -- ${p} --> ${m.uuid}(("${m.displayName||m.name||m.uuid}"))
|
|
1297
|
-
`)):typeof m=="string"&&i.add({uuid:m});const y=u.xFormTarget;y&&(typeof y=="object"?(i.add(y),r&&(l+=`${u.id}[${u.id}
|
|
1298
|
-
${p}] -- ${p} --> ${y.uuid}(("${y.displayName||y.name||y.uuid}"))
|
|
1299
|
-
`)):typeof y=="string"&&i.add({uuid:y}))}}function d(u,p){if(Array.isArray(u))for(const m of u)d(m,p);else if(u instanceof lo){let m=u.tokenId;u.type!==void 0&&(m+=":"+u.type),typeof u.targetId=="object"&&(t.add(u.targetId),r&&(l+=`${u.targetId.uuid}(("${u.targetId.displayName}")) --> ${u.id}[${u.id}
|
|
1300
|
-
${m}]
|
|
1301
|
-
`)),r&&(a+=`${u.id}((${u.id})) -- ${m} --> ${p.id}[${p.tokenId||p.id}]
|
|
1302
|
-
`)}}for(const u of this.behaviours)r&&(a+=`subgraph ${u.id}
|
|
1303
|
-
`),h(u.action),d(u.trigger,u.action),r&&(a+=`end
|
|
1304
|
-
`);r&&(a+=`
|
|
1305
|
-
`+l),r&&(console.log("All USDZ behaviours",this.behaviours),this.behaviours.length&&(console.warn("The Mermaid graph can be pasted into https://massive-mermaid.glitch.me/ or https://mermaid.live/edit. It should be in your clipboard already!"),console.log(a),navigator.clipboard.writeText(a)));{let u=`gantt
|
|
1306
|
-
title Animations
|
|
1307
|
-
dateFormat X
|
|
1308
|
-
axisFormat %s
|
|
1309
|
-
`;const p=Array.from(o),m=new Set;for(const w of p)if(w.affectedObjects&&typeof w.affectedObjects!="string"){if(Array.isArray(w.affectedObjects))for(const b of w.affectedObjects)m.add(b);else m.add(w.affectedObjects);r&&(u+=`section ${w.animationName} (${w.id})
|
|
1310
|
-
`,u+=`${w.id} : ${w.start}, ${w.duration}s
|
|
1311
|
-
`)}r&&o.size&&console.log(u);const y=new Set;for(const w of m){w.getPath||console.error("USDZExporter: Animation target object has no getPath method. This is likely a bug",w);let b=w.getPath();b.startsWith("<")&&(b=b.substring(1)),b.endsWith(">")&&(b=b.substring(0,b.length-1)),y.add({path:b,obj:w})}const _=Array.from(y).sort((w,b)=>w.path.length-b.path.length),g=new Array;for(let w=0;w<_.length;w++)for(let b=w+1;b<_.length;b++)if(_[b].path.startsWith(_[w].path)){const v=_[b],E=_[w];g.push({child:v.obj.displayName+" ("+v.path+")",parent:E.obj.displayName+" ("+E.path+")"})}g.length&&console.warn("USDZExporter: There are overlapping PlayAnimation actions. This can lead to undefined runtime behaviour when playing multiple animations. Please restructure the hierarchy so that animations don't overlap.",{overlappingTargets:g,playAnimationActions:o})}for(const u of new Set([...t,...i]))if(Array.isArray(u))for(const p of u)n.add(p.uuid);else n.add(u.uuid);td&&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){td&&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 ny{get extensionName(){return"Physics"}onExportObject(e,t,i){const n=S.getComponents(e,$e).filter(l=>l.enabled),o=S.getComponents(e,Xi).filter(l=>l.enabled&&!l.isTrigger);let r=n.length>0?n[0]:null;const a=o.length>0?o[0]:null;a&&!r&&(r=new $e,r.isKinematic=!0),r&&t.addEventListener("serialize",(l,h)=>{if(r){if(l.appendLine(),l.beginBlock('def RealityKitComponent "RigidBody"',"{",!0),r.useGravity||l.appendLine("bool gravityEnabled = 0"),l.appendLine('uniform token info:id = "RealityKit.RigidBody"'),r.isKinematic&&l.appendLine('token motionType = "Kinematic"'),l.beginBlock('def RealityKitStruct "massFrame"',"{",!0),l.appendLine(`float m_mass = ${r.mass}`),l.beginBlock('def RealityKitStruct "m_pose"',"{",!0),l.appendLine(`float3 position = (${r.centerOfMass.x}, ${r.centerOfMass.y}, ${r.centerOfMass.z})`),l.closeBlock("}"),l.closeBlock("}"),o.length>0){const d=o[0];l.beginBlock('def RealityKitStruct "material"',"{",!0);const u=d.sharedMaterial;u&&u.dynamicFriction!==void 0&&l.appendLine(`double dynamicFriction = ${d.sharedMaterial?.dynamicFriction}`),u&&u.bounciness!==void 0&&l.appendLine(`double restitution = ${d.sharedMaterial?.bounciness}`),u&&u.staticFriction!==void 0&&l.appendLine(`double staticFriction = ${d.sharedMaterial?.staticFriction}`),l.closeBlock("}")}l.closeBlock("}")}}),a&&(t.addEventListener("serialize",(l,h)=>{l.beginBlock('def RealityKitComponent "Collider"',"{",!0),l.appendLine("uint group = 1"),l.appendLine('uniform token info:id = "RealityKit.Collider"'),l.appendLine("uint mask = 4294967295");const u=a.isTrigger?"Trigger":"Default";if(l.appendLine(`token type = "${u}"`),l.beginBlock('def RealityKitStruct "Shape"',"{",!0),a instanceof qa){const p=a;l.appendLine('token shapeType = "Sphere"'),l.appendLine(`float radius = ${p.radius}`)}else if(a instanceof Tu){const p=a;l.appendLine('token shapeType = "Box"'),l.appendLine(`float3 extent = (${p.size.x}, ${p.size.y}, ${p.size.z})`)}else if(a instanceof bs){const p=a;l.appendLine('token shapeType = "Capsule"'),l.appendLine(`float radius = ${p.radius}`),l.appendLine(`float height = ${p.height}`)}else if(a instanceof xo&&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");ie.__webpack_exports__Block.prototype.interactable={get(){return this.interactive},set(s){this.interactable=s}};class Wi extends R{isRoot(){return this.Root?.gameObject===this.gameObject}get canvas(){const e=this.Root;return e?.isCanvas?e:null}get Canvas(){return this.canvas}markDirty(){Gt.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(e){this._shadowComponent=e}_shadowComponent=null;_controlsChildLayout=!0;get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}_root=void 0;get Root(){return this._root===void 0&&(this._root=S.getComponentInParent(this.gameObject,oh)),this._root}_parentComponent=void 0;__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0,this}onEnable(){super.onEnable()}addShadowComponent(e,t){if(!e)return;this.removeShadowComponent();const i=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=S.getComponentInParent(i,Wi),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e[pi]=this,this.setShadowComponentOwner(e);let n=!1;if(this.Root?.gameObject===this.gameObject)this.gameObject.add(e);else{const o=this._parentComponent.shadowComponent;o&&(o?.add(e),n=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),Nc&&e.add(new c.AxesHelper(.5)),this.onAfterAddedToScene(),n&&ie.__webpack_exports__update(),Sk&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(e){if(e&&(e[pi]===void 0||e[pi]===this)&&(e[pi]=this,e.children))for(const t of e.children)this.setShadowComponentOwner(t)}traverseOwnedShadowComponents(e,t,i){if(e&&e[pi]===t){i(e);for(const n of e.children)this.traverseOwnedShadowComponents(n,t,i)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}}class oh extends Wi{awake(){super.awake()}}var Ck=Object.defineProperty,Pk=Object.getOwnPropertyDescriptor,rh=(s,e,t,i)=>{for(var n=i>1?void 0:i?Pk(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&&Ck(e,t,n),n};const ap=x("debugui"),lp=x("debuguilayout");class Kw{width;height}class Zw{x;y;width;height}const sn=new c.Vector3,Pl=new c.Matrix4,id=new c.Quaternion,Ja=class Jw extends Wi{get parent(){return this._parentRectTransform}get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}_anchoredPosition;get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new c.Vector2),this._anchoredPosition}set anchoredPosition(e){this._anchoredPosition=e}sizeDelta=new c.Vector2(100,100);pivot=new c.Vector2(.5,.5);anchorMin=new c.Vector2(0,0);anchorMax=new c.Vector2(1,1);minWidth;minHeight;get width(){let e=this.sizeDelta.x;if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const t=this._parentRectTransform.width,i=this.anchorMax.x-this.anchorMin.x;e=t*i,e+=this.sizeDelta.x}return this.minWidth!==void 0&&e<this.minWidth?this.minWidth:e}get height(){let e=this.sizeDelta.y;if(this.anchorMin.y!==this.anchorMax.y&&this._parentRectTransform){const t=this._parentRectTransform.height,i=this.anchorMax.y-this.anchorMin.y;e=t*i,e+=this.sizeDelta.y}return this.minHeight!==void 0&&e<this.minHeight?this.minHeight:e}lastMatrix;rectBlock;_transformNeedsUpdate=!1;_initialPosition;_parentRectTransform;_lastUpdateFrame=-1;awake(){super.awake(),this._lastUpdateFrame=-1,this._parentRectTransform=void 0,this.rectBlock=new c.Object3D,this.rectBlock.name=this.name,this.lastMatrix=new c.Matrix4,this._lastAnchoring=null,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,this._anchoredPosition||(this._anchoredPosition=new c.Vector2),sa(this,"_anchoredPosition",()=>{this.markDirty()}),sa(this,"sizeDelta",()=>{this.markDirty()}),sa(this,"pivot",()=>{this.markDirty()}),sa(this,"anchorMin",()=>{this.markDirty()}),sa(this,"anchorMax",()=>{this.markDirty()})}onEnable(){super.onEnable(),this.rectBlock||(this.rectBlock=new c.Object3D),this.lastMatrix||(this.lastMatrix=new c.Matrix4),this._lastAnchoring||(this._lastAnchoring=new c.Vector2),this._initialPosition||(this._initialPosition=new c.Vector3),this._anchoredPosition||(this._anchoredPosition=new c.Vector2),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,this.canvas?.registerTransform(this)}onDisable(){super.onDisable(),this.removeShadowComponent(),this.canvas?.unregisterTransform(this)}onParentRectTransformChanged(e){this._transformNeedsUpdate||this.onApplyTransform(lp?`${e.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(lp&&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,lp&&console.warn("RectTransform → ApplyTransform",this.name+" because "+e),this.isRoot()?this.Root.screenspace||(t.rotation.y=Math.PI):(t.matrix.identity(),t.matrixAutoUpdate=!1,sn.set(0,0,0),this.applyPivot(sn),t.matrix.setPosition(sn.x,sn.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(id.copy(this.gameObject.quaternion),id.x*=-1,id.z*=-1,Pl.makeRotationFromQuaternion(id),t.matrix.premultiply(Pl)),sn.set(0,0,0),this.applyAnchoring(sn),this.canvas?.screenspace?sn.z+=.1:sn.z+=.01,Pl.identity(),Pl.setPosition(sn.x,sn.y,sn.z),t.matrix.premultiply(Pl),t.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const i=!0;for(const n of vu(this.gameObject,Wi,i,1)){if(n===this||!n.activeAndEnabled)continue;const o=n;o.onParentRectTransformChanged&&o.onParentRectTransformChanged(this)}}_lastAnchoring;applyAnchoring(e){this._lastAnchoring||(this._lastAnchoring=new c.Vector2);const t=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=t.x,this.gameObject.position.y+=t.y,this._lastAnchoring.copy(this._anchoredPosition),e.x+=this._initialPosition.x-this.gameObject.position.x,e.y+=this._initialPosition.y-this.gameObject.position.y,e.z+=this._initialPosition.z-this.gameObject.position.z;const i=this._parentRectTransform;if(i){let n=0;const o=1-this.anchorMax.y-this.anchorMin.y;n-=i.height*.5*o,e.y+=n;let r=0;const a=1-this.anchorMax.x-this.anchorMin.x;r-=i.width*.5*a,e.x+=r}}applyPivot(e){if(this.pivot&&!this.isRoot()){const t=this.pivot.x-.5;e.x-=t*this.sizeDelta.x*this.gameObject.scale.x;const i=this.pivot.y-.5;e.y-=i*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){const e={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:0,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(e),e}ensureValidSize(e,t=1e-4){return e.width<=0&&(e.width=t),e.height<=0&&(e.height=1e-4),e}_createdBlocks=[];_createdTextBlocks=[];createNewBlock(e){e={...this.getBasicOptions(),...e},ap&&console.log(this.name,e);const t=new ie.__webpack_exports__Block(e);return this._createdBlocks.push(t),t}createNewText(e){ap&&console.log(e),e={...this.getBasicOptions(),...e},ap&&console.log(this.name,e);const t=new ie.__webpack_exports__Text(e);return this._createdTextBlocks.push(t),t}};rh([f(c.Vector2)],Ja.prototype,"anchoredPosition",1);rh([f(c.Vector2)],Ja.prototype,"sizeDelta",2);rh([f(c.Vector2)],Ja.prototype,"pivot",2);rh([f(c.Vector2)],Ja.prototype,"anchorMin",2);rh([f(c.Vector2)],Ja.prototype,"anchorMax",2);let mn=Ja;var Ok=Object.defineProperty,ex=(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 el extends R{effectColor;effectDistance}ex([f(te)],el.prototype,"effectColor");ex([f(c.Vector2)],el.prototype,"effectDistance");var Mk=Object.defineProperty,kk=Object.getOwnPropertyDescriptor,tx=(s,e,t,i)=>{for(var n=i>1?void 0:i?kk(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&&Mk(e,t,n),n};const Uo={backgroundColor:new c.Color(1,1,1),backgroundOpacity:1,borderColor:new c.Color(1,1,1),borderOpacity:1},sy=class Gl extends Wi{get isGraphic(){return!0}get color(){return this._color||(this._color=new te(1,1,1,1)),this._color}set color(e){(!this._color||this._color.r!==e.r||this._color.g!==e.g||this._color.b!==e.b||this._color.alpha!==e.alpha)&&(this._color||(this._color=new te(1,1,1,1)),this._color.copy(e),this.onColorChanged())}_alphaFactor=1;setAlphaFactor(e){this._alphaFactor=e,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}sRGBColor=new c.Color(1,0,1);onColorChanged(){if(this.uiObject){this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),Uo.backgroundColor=this.sRGBColor,Uo.backgroundOpacity=this._color.alpha;const e=this.uiObject._simpleState__activeStates?.[0];if(e){const t=this.uiObject._simpleState__states?.[e];t&&("backgroundColor"in t&&(Uo.backgroundColor=t.backgroundColor),"backgroundOpacity"in t&&(Uo.backgroundOpacity=t.backgroundOpacity))}Uo.backgroundOpacity*=this._alphaFactor,this.applyEffects(Uo,this._alphaFactor),this.uiObject.set(Uo),this.markDirty()}}get m_Color(){return this._color}raycastTarget=!0;uiObject=null;_color=null;_rect=null;_stateManager=null;get rectTransform(){if(this._rect||(this._rect=S.getComponent(this.gameObject,mn)),!this._rect)throw new Error("Not Supported: Make sure to add a RectTransform component before adding a UI Graphic component.");return this._rect}onParentRectTransformChanged(){this.uiObject?.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this._rect=null,this.uiObject=null,this._stateManager=null,this._color&&(this._color=this._color.clone()),this}setState(e){this.makePanel(),this.uiObject&&(this.uiObject.setState(e),this?.markDirty())}setupState(e){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new ie.SimpleStateBehavior(this.uiObject)),this.uiObject.setupState(e.state,e.attributes))}setOptions(e){this.makePanel(),this.uiObject&&this.uiObject.set(e)}awake(){super.awake(),this.makePanel(),sa(this,"_color",()=>hO(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(el);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(Gl.textureCache.has(e))e=Gl.textureCache.get(e);else if(!e.isRenderTargetTexture){const t=e.clone();t.colorSpace=c.LinearSRGBColorSpace,Gl.textureCache.set(e,t),e=t}this.setOptions({backgroundImage:e,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}),re.NEEDLE_progressive.assignTextureLOD(e,0).then(t=>{t instanceof c.Texture&&(e&&Gl.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)}};tx([f(te)],sy.prototype,"color",1);tx([f()],sy.prototype,"raycastTarget",2);let ah=sy;class lh extends ah{_flippedObject=!1;onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var Rk=Object.defineProperty,Ek=Object.getOwnPropertyDescriptor,ks=(s,e,t,i)=>{for(var n=i>1?void 0:i?Ek(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};const zo=x("debugtext");var Ze=(s=>(s[s.UpperLeft=0]="UpperLeft",s[s.UpperCenter=1]="UpperCenter",s[s.UpperRight=2]="UpperRight",s[s.MiddleLeft=3]="MiddleLeft",s[s.MiddleCenter=4]="MiddleCenter",s[s.MiddleRight=5]="MiddleRight",s[s.LowerLeft=6]="LowerLeft",s[s.LowerCenter=7]="LowerCenter",s[s.LowerRight=8]="LowerRight",s))(Ze||{}),ix=(s=>(s[s.Normal=0]="Normal",s[s.Bold=1]="Bold",s[s.Italic=2]="Italic",s[s.BoldAndItalic=3]="BoldAndItalic",s))(ix||{});class Dt extends ah{alignment=0;verticalOverflow=0;horizontalOverflow=0;lineSpacing=1;supportRichText=!1;font;fontStyle=0;setAlphaFactor(e){super.setAlphaFactor(e),this.uiObject?.set({fontOpacity:this.color.alpha*this.alphaFactor}),this.markDirty()}get text(){return this._text}set text(e){e!==this._text&&(this._text=e,this.feedText(this.text,this.supportRichText),this.markDirty(),this.context.accessibility.updateElement(this,{label:this.text}))}set_text(e){this.text=e}get fontSize(){return this._fontSize}set fontSize(e){this._fontSize=e,this.uiObject?.set({fontSize:e})}sRGBTextColor=new c.Color(1,0,1);onColorChanged(){this.sRGBTextColor.copy(this.color),this.sRGBTextColor.convertLinearToSRGB(),this.uiObject?.set({color:this.sRGBTextColor,fontOpacity:this.color.alpha})}onParentRectTransformChanged(){super.onParentRectTransformChanged(),this.uiObject&&this.updateOverflow()}onBeforeCanvasRender(e){this.updateOverflow()}updateOverflow(){const e=this.uiObject?._overflow;e&&(e._needsUpdate=!0)}onCreate(e){zo&&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,zo&&(e.backgroundColor=16750848,e.backgroundOpacity=.5);const t=this.rectTransform;e={...e,...this.getTextOpts()},this.getAlignment(e),zo&&(e.backgroundColor=Math.random()*16777215,e.backgroundOpacity=.1),this.uiObject=t.createNewText(e),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}_text="";_fontSize=12;_textMeshUi=null;getTextOpts(){const e=this.fontSize,t={color:this.color,fontOpacity:this.color.alpha,fontSize:e,fontKerning:"normal"};return this.setFont(t,this.fontStyle),t}onEnable(){super.onEnable(),this.context.accessibility.updateElement(this,{role:"text",label:this.text,hidden:!1}),this._didHandleTextRenderOnTop=!1,this.uiObject&&this.uiObject.addAfterUpdate(()=>{this.setShadowComponentOwner(this.uiObject),this.markDirty()}),setTimeout(()=>this.markDirty(),10),this.canvas?.registerEventReceiver(this)}onDisable(){super.onDisable(),this.canvas?.unregisterEventReceiver(this),this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){super.onDestroy(),this.context.accessibility.removeElement(this)}getAlignment(e){switch(e.flexDirection="column",this.alignment){case 0:case 3:case 6:e.textAlign="left";break;case 1:case 4:case 7:e.textAlign="center";break;case 2:case 5:case 8:e.textAlign="right";break}switch(this.alignment){default:case 0:case 1:case 2:e.alignItems="start";break;case 3:case 4:case 5:e.alignItems="center";break;case 6:case 7:case 8:e.alignItems="end";break}return e}feedText(e,t){if(zo&&console.log("feedText",this.uiObject,e,t),!!this.uiObject)if(this._textMeshUi||(this._textMeshUi=[]),this.uiObject.children.length=0,!t||e.length===0)this.uiObject.textContent=e;else{let i=this.getNextTag(e);if(i){if(i.startIndex>0){for(let r=this.uiObject.children.length-1;r>=0;r--){const a=this.uiObject.children[r];a.isUI&&(this.uiObject.remove(a),a.clear())}const o=new ie.__webpack_exports__Inline({textContent:e.substring(0,i.startIndex),color:"inherit"});this.uiObject.add(o)}}else{this.uiObject.textContent="",this.setOptions({textContent:e});return}const n=[];for(;i;){const o=this.getNextTag(e,i.endIndex),r={fontFamily:this.uiObject?.get("fontFamily"),color:"inherit",textContent:""};if(o){r.textContent=this.getText(e,i,o),this.handleTag(i,r,n);const a=new ie.__webpack_exports__Inline(r);this.uiObject?.add(a)}else{r.textContent=e.substring(i.endIndex),this.handleTag(i,r,n);const a=new ie.__webpack_exports__Inline(r);this.uiObject?.add(a)}i=o}}}_didHandleTextRenderOnTop=!1;handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const e=[],t=this.canvas,i={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let n=!1;if(this._textMeshUi)for(let o=0;o<this._textMeshUi.length;o++){if(e[o]===!0)continue;n=!0;const r=this._textMeshUi[o];r.textContent&&(Zd(r,i),e[o]=!0)}if(!n)break;yield}}handleTag(e,t,i){if(!e.isEndTag){if(e.type.includes("color")){const n=new cp(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 cp(e,{fontWeight:700});i.push(n)}else if(e.type=="i"){this.setFont(t,2);const n=new cp(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);zo&&console.log("Selected font family:"+n);let o=ie.__webpack_exports__FontLibrary.getFontFamily(n);switch(o||(o=ie.__webpack_exports__FontLibrary.addFontFamily(n)),e.fontFamily=o,t){default:case 0:e.fontWeight=400,e.fontStyle="normal";break;case 1:e.fontWeight=700,e.fontStyle="normal";break;case 2:e.fontWeight=400,e.fontStyle="italic";break;case 3:e.fontStyle="italic",e.fontWeight=400}let r=o.getVariant(e.fontWeight,e.fontStyle);if(!r){let a=n;a?.endsWith("-msdf.json")||(a+="-msdf.json");let l=n;l?.endsWith(".png")||(l+=".png"),r=o.addVariant(e.fontWeight,e.fontStyle,a,l),r?.addEventListener("ready",()=>{this.markDirty()})}}getFamilyNameWithCorrectSuffix(e,t){(e.startsWith("https:")||e.startsWith("http:"))&&(e=new URL(e).pathname);const i=e.lastIndexOf("-");if(i<0)return e;const n=e.substring(i+1)?.toLowerCase();if(Tk.includes(n))return zo&&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(zo&&console.log("Select font: ",e,ix[t],r,a,l),t){case 0:return a?l+"-Regular":l+"-regular";case 1:return a?l+"-Bold":l+"-bold";case 2:return a?l+"-Italic":l+"-italic";case 3:return a?l+"-BoldItalic":l+"-bolditalic";default:return e}}}ks([f()],Dt.prototype,"alignment",2);ks([f()],Dt.prototype,"verticalOverflow",2);ks([f()],Dt.prototype,"horizontalOverflow",2);ks([f()],Dt.prototype,"lineSpacing",2);ks([f()],Dt.prototype,"supportRichText",2);ks([f(URL)],Dt.prototype,"font",2);ks([f()],Dt.prototype,"fontStyle",2);ks([f()],Dt.prototype,"text",1);ks([f()],Dt.prototype,"fontSize",1);class cp{tag;previousValues;constructor(e,t){this.tag=e,this.previousValues=t}}const Tk=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class ga{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/${ju(this.material)}>`),t.closeBlock()}}class oy{static singleLine(e,t,i){const n=new ga("text_"+ga.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 ga("text_"+ga.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 Ak=new c.Matrix4().makeRotationY(Math.PI),Dk=new c.Matrix4().makeScale(-1,1,-1);class Wu{get extensionName(){return"text"}exportText(e,t,i){const n=S.getComponent(e,Dt);if(!n)return;const o=S.getComponent(e,mn);let r=100,a=100;o&&(r=o.width,a=o.height);const l=Ak.clone();o&&l.premultiply(Dk),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=oy.multiLine(p,r,a,"center","bottom","flowing");this.setTextAlignment(m,n.alignment),this.setOverflow(m,n),t.material&&(m.material=t.material),m.pointSize=this.convertToTextSize(n.fontSize),m.depth=.001,m.writeTo(void 0,d)})}convertToTextSize(e){return 1/.0502*144*e}setOverflow(e,t){t.horizontalOverflow?e.wrapMode="singleLine":e.wrapMode="flowing"}setTextAlignment(e,t){switch(t){case Ze.LowerLeft:case Ze.MiddleLeft:case Ze.UpperLeft:e.horizontalAlignment="left";break;case Ze.LowerCenter:case Ze.MiddleCenter:case Ze.UpperCenter:e.horizontalAlignment="center";break;case Ze.LowerRight:case Ze.MiddleRight:case Ze.UpperRight:e.horizontalAlignment="right";break}switch(t){case Ze.LowerLeft:case Ze.LowerCenter:case Ze.LowerRight:e.verticalAlignment="bottom";break;case Ze.MiddleLeft:case Ze.MiddleCenter:case Ze.MiddleRight:e.verticalAlignment="middle";break;case Ze.UpperLeft:case Ze.UpperCenter:case Ze.UpperRight:e.verticalAlignment="top";break}}}var Lk=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&&Lk(e,t,n),n};const kb=x("debuguilayout");class Er{left=0;right=0;top=0;bottom=0;get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}Qe([f()],Er.prototype,"left");Qe([f()],Er.prototype,"right");Qe([f()],Er.prototype,"top");Qe([f()],Er.prototype,"bottom");class Ci extends R{_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&&(kb&&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(){kb&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(mn);const e=this.gameObject.getComponentInParent(Fa);e&&e.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const e=this.gameObject.getComponentInParent(Fa);e&&e.unregisterLayoutGroup(this)}set m_Spacing(e){e!==this.spacing&&(this._needsUpdate=!0,this.spacing=e)}get m_Spacing(){return this.spacing}}Qe([f()],Ci.prototype,"childAlignment");Qe([f()],Ci.prototype,"reverseArrangement");Qe([f()],Ci.prototype,"spacing");Qe([f(Er)],Ci.prototype,"padding");Qe([f()],Ci.prototype,"minWidth");Qe([f()],Ci.prototype,"minHeight");Qe([f()],Ci.prototype,"flexibleHeight");Qe([f()],Ci.prototype,"flexibleWidth");Qe([f()],Ci.prototype,"preferredHeight");Qe([f()],Ci.prototype,"preferredWidth");class Po extends Ci{childControlHeight=!0;childControlWidth=!0;childForceExpandHeight=!1;childForceExpandWidth=!1;childScaleHeight=!1;childScaleWidth=!1;onCalculateLayout(e){const t=this.primaryAxis,i=e.width;let n=i;const o=e.height;let r=o;n-=this.padding.horizontal,r-=this.padding.vertical,t==="x"?this.padding.horizontal:this.padding.vertical;const a=t==="x",l=a?"y":"x",h=a?this.childControlWidth:this.childControlHeight,d=a?this.childControlHeight:this.childControlWidth,u=a?this.childForceExpandWidth:this.childForceExpandHeight,p=a?this.childForceExpandHeight:this.childForceExpandWidth,m=a?r:n,y=a?i:o,_=.5*(a?this.childAlignment%3:Math.floor(this.childAlignment/3));let g=0;a?g+=this.padding.left:g+=this.padding.top;let w=0,b=0;for(let D=0;D<this.gameObject.children.length;D++){const L=this.gameObject.children[D],j=S.getComponent(L,mn);j?.activeAndEnabled&&(b+=1,a?w+=j.width:w+=j.height)}let v=0;const E=this.spacing*(b-1);if(u||h){let D=0;a?D=n-=E:D=r-=E,b>0&&(v=D/b)}let O=0;O+=this.padding.left,O-=this.padding.right,_!==0&&(g=y-w,g*=_,g-=E*_,a?(g-=this.padding.right*_,g+=this.padding.left*(1-_),g<this.padding.left&&(g=this.padding.left)):(g-=this.padding.bottom*_,g+=this.padding.top*(1-_),g<this.padding.top&&(g=this.padding.top)));let M=1;for(let D=0;D<this.gameObject.children.length;D++){const L=this.gameObject.children[D],j=S.getComponent(L,mn);if(j?.activeAndEnabled){j.pivot?.set(.5,.5),j.anchorMin.set(0,1),j.anchorMax.set(0,1);const V=i*.5+O*.5;j.anchoredPosition.x!==V&&(j.anchoredPosition.x=V);const W=o*-.5;j.anchoredPosition.y!==W&&(j.anchoredPosition.y=W),p&&d&&j.sizeDelta[l]!==m&&(j.sizeDelta[l]=m),u&&h&&j.sizeDelta[t]!==v&&(j.sizeDelta[t]=v);const k=a?j.width:j.height,N=k*.5;if(g+=N,u){const ee=v*M-v*.5;ee>g&&(g=ee-v*.5+k+this.padding.left,g-=N)}let $=g;t==="y"&&($=-$),j.anchoredPosition[t]!==$&&(j.anchoredPosition[t]=$),g+=N,g+=this.spacing,M+=1}}}}Qe([f()],Po.prototype,"childControlHeight");Qe([f()],Po.prototype,"childControlWidth");Qe([f()],Po.prototype,"childForceExpandHeight");Qe([f()],Po.prototype,"childForceExpandWidth");Qe([f()],Po.prototype,"childScaleHeight");Qe([f()],Po.prototype,"childScaleWidth");class ry extends Po{get primaryAxis(){return"y"}}class ay extends Po{get primaryAxis(){return"x"}}class ly extends Ci{onCalculateLayout(){}}var Ik=Object.defineProperty,jk=Object.getOwnPropertyDescriptor,Kn=(s,e,t,i)=>{for(var n=i>1?void 0:i?jk(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&&Ik(e,t,n),n},nx=(s=>(s[s.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",s[s.ScreenSpaceCamera=1]="ScreenSpaceCamera",s[s.WorldSpace=2]="WorldSpace",s[s.Undefined=-1]="Undefined",s))(nx||{});const hp=x("debuguilayout"),Gi=class sx extends oh{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 sx||(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,hp&&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 jc(1).then(()=>{this.gameObject.visible=!0}))}onLeaveXR(e){this.screenspace&&(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!0)}onBeforeRenderRoutine=()=>{if(this.previousParent=this.gameObject.parent,(this.context.xr?.isVR||this.context.xr?.isPassThrough)&&this.screenspace){this.gameObject.visible=!1,this.gameObject.removeFromParent();return}this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),this.shadowComponent?.updateMatrixWorld(!0),this.shadowComponent?.updateWorldMatrix(!0,!0),this.invokeBeforeRenderEvents(),Gt.ensureUpdateMeshUI(ie.ThreeMeshUI,this.context))};onAfterRenderRoutine=()=>{if((this.context.xr?.isVR||this.context.xr?.isPassThrough)&&this.screenspace){this.previousParent?.add(this.gameObject);return}if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){this.screenspace?this.context.mainCamera?.add(this.gameObject):this.previousParent.add(this.gameObject);const e=this.context.renderer.autoClear,t=this.context.renderer.autoClearColor;this.context.renderer.autoClear=!1,this.context.renderer.autoClearColor=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),this.shadowComponent?.updateMatrixWorld(!0),this.invokeBeforeRenderEvents(),Gt.ensureUpdateMeshUI(ie.ThreeMeshUI,this.context,!0),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=e,this.context.renderer.autoClearColor=t,this.previousParent.add(this.gameObject)}this._lastMatrixWorld?.copy(this.gameObject.matrixWorld)};invokeBeforeRenderEvents(){for(const e of this._receivers)e.onBeforeCanvasRender?.(this)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new c.Matrix4);const e=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);hp&&e&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);for(const t of this._rectTransforms){e&&t.markDirty();let i=this._layoutGroups.get(t.gameObject);t.isDirty&&!i&&(i=t.gameObject.getComponentInParent(Ci)),(t.isDirty||i?.isDirty)&&(hp&&console.log("CANVAS UPDATE ### "+t.name+" ##################################### "+this.context.time.frame),i?.updateLayout(),t.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}_updateRenderSettingsRoutine;onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),ge.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),Zd(this.shadowComponent,this);for(const e of S.getComponentsInChildren(this.gameObject,Wi))Zd(e.shadowComponent,this)}}_activeRenderMode=-1;_lastWidth=-1;_lastHeight=-1;onUpdateRenderMode(e=!1){if(!e&&this._renderMode===this._activeRenderMode&&this._lastWidth===this.context.domWidth&&this._lastHeight===this.context.domHeight)return;this._activeRenderMode=this._renderMode;let t=this.context.mainCameraComponent,i=10;switch(t&&t.nearClipPlane>0&&t.farClipPlane>0&&(i=I.lerp(t.nearClipPlane,t.farClipPlane,.01)),this._renderMode===1&&(this.worldCamera&&(t=this.worldCamera),this.planeDistance>0&&(i=this.planeDistance)),this._renderMode){case 0:case 1:if(this._lastWidth=this.context.domWidth,this._lastHeight=this.context.domHeight,!t)return;const n=i+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-n,this.gameObject.quaternion.identity();const o=this.gameObject.getComponent(mn);let r=!1;o.sizeDelta.x!==this.context.domWidth&&(r=!0),o.sizeDelta.y!==this.context.domHeight&&(r=!0);const a=t.fieldOfView*Math.PI/180,l=2*Math.tan(a/2)*Math.abs(n);this.gameObject.scale.x=l/this.context.domHeight,this.gameObject.scale.y=l/this.context.domHeight,this.gameObject.scale.z=.01,r&&(o.sizeDelta.x=this.context.domWidth,o.sizeDelta.y=this.context.domHeight,o?.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};Kn([f()],Gi.prototype,"renderOnTop",1);Kn([f()],Gi.prototype,"depthWrite",1);Kn([f()],Gi.prototype,"doubleSided",1);Kn([f()],Gi.prototype,"castShadows",1);Kn([f()],Gi.prototype,"receiveShadows",1);Kn([f()],Gi.prototype,"renderMode",1);Kn([f(Gi)],Gi.prototype,"rootCanvas",1);Kn([f()],Gi.prototype,"scaleFactor",1);Kn([f(si)],Gi.prototype,"worldCamera",2);Kn([f()],Gi.prototype,"planeDistance",2);let Fa=Gi;var Bk=Object.defineProperty,Fk=Object.getOwnPropertyDescriptor,cy=(s,e,t,i)=>{for(var n=i>1?void 0:i?Fk(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&&Bk(e,t,n),n};class mo extends R{get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}get isCanvasGroup(){return!0}_alpha=1;interactable=!0;blocksRaycasts=!0;_isDirty=!1;markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),ge.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}_buffer=[];applyChangesNow(){this._buffer.length=0;for(const e of S.getComponentsInChildren(this.gameObject,Wi,this._buffer)){const t=e;t.setAlphaFactor&&t.setAlphaFactor(this._alpha)}}}cy([f()],mo.prototype,"alpha",1);cy([f()],mo.prototype,"interactable",2);cy([f()],mo.prototype,"blocksRaycasts",2);class hy{get extensionName(){return"tmui"}onExportObject(e,t,i){const n=S.getComponent(e,Fa);if(n&&n.enabled&&n.renderMode===nx.WorldSpace){const o=new Wu,r=S.getComponent(e,mn),a=S.getComponent(e,mo),l=new Array;if(r){if(!S.isActiveSelf(e)){const u=S.isActiveSelf(e);S.setActive(e,!0),r.onEnable(),r.updateTransform(),l.push(()=>{r.onDisable(),S.setActive(e,u)})}e.traverse(u=>{if(!S.isActiveInHierarchy(u)){const p=S.isActiveSelf(u);S.setActive(u,!0);const m=S.getComponent(u,Wi);m&&(m.onEnable(),l.push(()=>{m.onDisable()}));const y=S.getComponent(u,mn);y&&(y.onEnable(),y.updateTransform(),y.onApplyTransform(),l.push(()=>{y.onDisable()}));const _=S.getComponent(u,Dt);_&&(_.onEnable(),l.push(()=>{_.onDisable()})),l.push(()=>{S.setActive(u,p)})}}),r.width,r.height;const h=qe.createEmpty(),d=r.shadowComponent;if(t.add(h),d){const u=d.matrix;h.setMatrix(u);const p=new Map,m=new Map;p.set(d,h),m.set(d,a?a.alpha:1),d.traverse(y=>{if(y===d)return;const _=qe.createEmpty();_.setMatrix(y.matrix);const g=y.parent,w=!!g&&typeof g.textContent=="string"&&g.textContent.length>0;let b=m.get(g)||1;const v=S.getComponent(y,mo);if(v&&(b*=v.alpha),y instanceof c.Mesh&&w){const O=y[pi];O?o.exportText(O.gameObject,_,i):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",y)}if(y instanceof c.Mesh&&!w){const O=y.geometry.clone();O.scale(1,1,-1),this.flipWindingOrder(O),_.geometry=O;const M=new c.Color,D=y.material.opacity;M.copy(y.material.color),_.material=new c.MeshBasicMaterial({color:M,opacity:D*b,map:y.material.map,transparent:!0})}p.set(y,_),m.set(y,b);const E=p.get(g);if(!E){console.error("Error when exporting UI: shadow component parent not found!",y,y.parent);return}E.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 Hl=x("debugusdz");function Uk(s,e){const t=[],i=S.getComponentsInChildren(s,lt),n=S.getComponentsInChildren(s,Tt),o=new Array,r=new Array;if(e.injectImplicitBehaviours)for(const a of i){if(!a||!a.runtimeAnimatorController||!a.enabled)continue;const l=a.runtimeAnimatorController.activeState;if(!l||!l.motion||!l.motion.clip||l.motion.clip.tracks?.length<1||o.includes(a))continue;const h=new Oc;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;Hl&&console.log(a);const l=[];for(const h of a.runtimeAnimatorController.enumerateActions()){Hl&&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 Oc;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){Hl&&console.log(a);const l=[];for(const h of a.animations)l.includes(h)||l.push(h);t.push({root:a.gameObject,clips:l})}Hl&&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 zk(s,e){const t=S.getComponentsInChildren(s,vi),i=S.getComponentsInChildren(s,fo),n=new Array,o=new Array;Hl&&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 fo;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 Nk(s){return new xt("DisableAtStart",Et.sceneStartTrigger(),ue.fadeAction(s,0,!1))}function Rb(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 Vk=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&&Vk(e,t,n),n};const pt=x("debugusdz"),$k=x("debugusdzpruning");class Tr{callToAction;checkoutTitle;checkoutSubtitle;callToActionURL}Ct([f()],Tr.prototype,"callToAction");Ct([f()],Tr.prototype,"checkoutTitle");Ct([f()],Tr.prototype,"checkoutSubtitle");Ct([f()],Tr.prototype,"callToActionURL");const hi=class Go extends R{static beforeExport=new ne;static afterExport=new ne;static beforeLODExport=new ne;objectToExport=void 0;autoExportAnimations=!0;autoExportAudioSources=!0;exportFileName=void 0;customUsdzFile=void 0;customBranding;anchoringType="plane";maxTextureSize=2048;planeAnchoringAlignment="horizontal";interactive=!0;physics=!0;allowCreateQuicklookButton=!0;quickLookCompatible=!0;extensions=[];link;button;start(){pt&&(console.log("USDZExporter",this),console.log("Debug USDZ Mode. Press 'T' to export"),window.addEventListener("keydown",e=>{e.key==="t"&&this.exportAndOpen()})),this.objectToExport||(this.objectToExport=this.gameObject),!this.objectToExport?.children?.length&&!this.objectToExport?.isMesh&&(this.objectToExport=this.context.scene)}onEnable(){const e=exports.DeviceUtilities.supportsQuickLookAR(),t=exports.DeviceUtilities.isiOS()||exports.DeviceUtilities.isiPad();!this.button&&(pt||e||t)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=Rb(this.context,e),this.link.addEventListener("message",this.lastCallback)),pt&&Se("USDZ Exporter enabled: "+this.name),document.getElementById("open-in-ar")?.addEventListener("click",this.onClickedOpenInARElement),yc.registerExporter(this)}onDisable(){this.button?.remove(),this.link?.removeEventListener("message",this.lastCallback),pt&&Se("USDZ Exporter disabled: "+this.name),document.getElementById("open-in-ar")?.removeEventListener("click",this.onClickedOpenInARElement),yc.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+="-"+Lw(),Vn()||(e!==""&&(e+="-"),e+="MadeWithNeedle"),this.link||(this.link=Rb(this.context,exports.DeviceUtilities.supportsQuickLookAR())),this.customUsdzFile)return pt&&console.log("Exporting custom usdz",this.customUsdzFile),this.openInQuickLook(this.customUsdzFile,e),null;if(!this.objectToExport)return console.warn("No object to export",this),null;Go.beforeExport.invoke({exporter:this});const t=await this.export(this.objectToExport).finally(()=>{Go.afterExport.invoke({exporter:this})});return t?(pt&&console.log("USDZ generation done. Downloading as "+e),this.openInQuickLook(t,e),t):(console.error("USDZ generation failed. Please report a bug",this),null)}async export(e){if(!e)return console.warn("No object to export"),null;const t=this._currentExportTasks.get(e);if(t)return t;const i=this.internalExport(e);return i instanceof Promise?(this._currentExportTasks.set(e,i),i.then(n=>(this._currentExportTasks.delete(e),n)).catch(n=>(this._currentExportTasks.delete(e),console.error("Error during USDZ export – please report a bug!",n),null))):i}_currentExportTasks=new Map;_previousTimeScale=1;async internalExport(e){oe.start("export-usdz",{onProgress:O=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:O}}))}}),oe.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),oe.report("export-usdz",{message:"Load progressive textures",autoStep:5}),oe.start("export-usdz-textures","export-usdz");const t=S.getComponentsInChildren(e,ci);for(const O of t)O&&O.enabled&&O.updateSprite(!0);const i=S.getComponentsInChildren(e,Ht),n=new Array;let o=0;for(const O of i){for(const M of O.sharedMeshes)if(M){let D=0;const L={exporter:this,type:"mesh",object:O.gameObject,mesh:M};if(Go.beforeLODExport.invoke(L),L.overrideLevel!==void 0)if(L.overrideLevel===-1){pt&&console.warn("Skipping LOD export for mesh due to overrideLevel -1",O.gameObject,M);continue}else L.overrideLevel>=0&&(D=L.overrideLevel,pt&&console.log("Overriding LOD level for mesh export to level "+D+" "+M.name));const j=re.NEEDLE_progressive.assignMeshLOD(M,D);j instanceof Promise&&n.push(new Promise((V,W)=>{j.then(()=>{o++,oe.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:o,totalSteps:n.length}),V()}).catch(k=>W(k))}))}for(const M of O.sharedMaterials)if(M){let D=0;const L={exporter:this,type:"texture",object:O.gameObject,material:M};if(Go.beforeLODExport.invoke(L),L.overrideLevel!==void 0)if(L.overrideLevel===-1){pt&&console.warn("Skipping LOD assignment due to overrideLevel -1",O.gameObject,M);continue}else L.overrideLevel>=0&&(D=L.overrideLevel,pt&&console.log("Overriding LOD level for texture export to level "+D+" "+M.name));const j=re.NEEDLE_progressive.assignTextureLOD(M,D);j instanceof Promise&&n.push(new Promise((V,W)=>{j.then(()=>{o++,oe.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:o,totalSteps:n.length}),V()}).catch(k=>W(k))}))}}pt&&Se("Progressive Loading: "+n.length),await Promise.all(n),pt&&Se("Progressive Loading: done"),oe.end("export-usdz-textures");const r=Wt.Global.Mask;Wt.Global.Set(Ln.AR);const a=new Uw,l=new Bu(this.quickLookCompatible);let h;const d=[];this.interactive&&(d.push(new iy),d.push(new kr),globalThis.NEEDLE_USE_RAPIER&&S.getComponentsInChildren(e,$e).length>0&&(this.physics?(h=new ny,d.push(h)):A()&&console.warn("USDZExporter: Physics export is disabled, but there are active Rigidbody components in the scene. They will not be exported.")),d.push(new Wu),d.push(new hy));const u=[l,...d,...this.extensions],p={self:this,exporter:a,extensions:u,object:e};oe.report("export-usdz","Invoking before-export"),this.dispatchEvent(new CustomEvent("before-export",{detail:p})),this.applyWebARSessionRoot(),this._previousTimeScale=this.context.time.timeScale,this.context.time.timeScale=0,oe.report("export-usdz","auto export animations and audio sources");const m=new Array;this.autoExportAnimations&&m.push(...Uk(e,l)),u.find(O=>O.extensionName==="Audio")&&this.autoExportAudioSources&&m.push(...zk(e)),a.debug=pt,a.pruneUnusedNodes=!$k;const _=gr.instance.objs.map(O=>O.batchedMesh);a.keepObject=O=>{let M=!0;const D=S.getComponent(O,Ht);return D&&!D.enabled&&(M=!1),M&&_.includes(O)&&(M=!1),M&&S.getComponentInParent(O,Zc)&&(M=!1),M&&S.getComponentInParent(O,Xn)&&(M=!1),pt&&!M&&console.log("USDZExporter: Discarding object",O),M},a.beforeWritingDocument=()=>{if(A()&&l&&h){const O=l.animatedRoots;for(const M of O){const D=S.getComponentsInChildren(M,$e).filter(j=>j.enabled),L=S.getComponents(M,Xi).filter(j=>j.enabled&&!j.isTrigger);(D.length>0||L.length>0)&&console.error("An animated object has physics components in its child hierarchy. This can lead to undefined behaviour due to a bug in Apple's QuickLook (FB15925487). Remove the physics components from child objects or verify that you get the expected results.",M)}}};const g=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(O=>{O.visible||g.push(O)});const w=u.find(O=>O.extensionName==="Behaviour");this.interactive&&w&&g.length>0&&w.addBehavior(Nk(g));let b=!0;this.quickLookCompatible&&!this.interactive&&(b=!1),this.anchoringType!=="plane"&&this.anchoringType!=="none"&&this.anchoringType!=="image"&&this.anchoringType!=="face"&&(this.anchoringType="plane"),this.planeAnchoringAlignment!=="horizontal"&&this.planeAnchoringAlignment!=="vertical"&&this.planeAnchoringAlignment!=="any"&&(this.planeAnchoringAlignment="horizontal"),oe.report("export-usdz","Invoking exporter.parse");const v=await a.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:u,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:b}),E=new Blob([v],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,oe.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:p}));for(const O of m)S.destroy(O);return Wt.Global.Set(r),oe.end("export-usdz"),E}openInQuickLook(e,t){const i=e instanceof Blob?URL.createObjectURL(e):e,n=this.buildQuicklookOverlay();pt&&console.log("QuickLook Overlay",n);const o=n.callToAction?encodeURIComponent(n.callToAction):"",r=n.checkoutTitle?encodeURIComponent(n.checkoutTitle):"",a=n.checkoutSubtitle?encodeURIComponent(n.checkoutSubtitle):"";this.link.href=i+`#callToAction=${o}&checkoutTitle=${r}&checkoutSubtitle=${a}&callToActionURL=${n.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=t+".usdz",this.link.click()}download(e,t){Go.save(e,t)}static save(e,t){const i=document.createElement("a");i.style.display="none",document.body.appendChild(i),typeof e=="string"?i.href=e:i.href=URL.createObjectURL(e),i.download=t,i.click(),i.remove()}lastCallback;quicklookCallback(e){if(e?.data=="_apple_ar_quicklook_button_tapped"){pt&&fe("Quicklook closed via call to action button");var t=new CustomEvent("quicklook-button-tapped",{detail:this});if(this.dispatchEvent(t),!t.defaultPrevented){const i=new URLSearchParams(this.link.href);if(i){const n=i.get("callToActionURL");pt&&Se("Quicklook url: "+n),n&&(Vn()?globalThis.open(n,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",n))}}}}buildQuicklookOverlay(){const e={};return this.customBranding&&Object.assign(e,this.customBranding),Vn()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),e.callToAction="Close",e.checkoutTitle="🌵 Made with Needle",e.checkoutSubtitle="_"),(e.callToAction?.length||e.checkoutTitle?.length||e.checkoutSubtitle?.length)&&(e.callToAction?.length||(e.callToAction="\0"),e.checkoutTitle?.length||(e.checkoutTitle="\0"),e.checkoutSubtitle?.length||(e.checkoutSubtitle="\0")),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:e})),e}static invertForwardMatrix=new c.Matrix4().makeRotationY(Math.PI);static invertForwardQuaternion=new c.Quaternion().setFromEuler(new c.Euler(0,Math.PI,0));_rootSessionRootWasAppliedTo=null;_rootPositionBeforeExport=new c.Vector3;_rootRotationBeforeExport=new c.Quaternion;_rootScaleBeforeExport=new c.Vector3;getARScaleAndTarget(){if(!this.objectToExport)return{scale:1,_invertForward:!1,target:this.gameObject,sessionRoot:null};const e=S.findObjectOfType($u);let t=S.getComponentInParent(this.objectToExport,Ui);t||(t=S.getComponentInChildren(this.objectToExport,Ui));let i=1,n=!1;const o=this.objectToExport;return e?i=e.arScale:t&&(i=t.arScale,n=t.invertForward),{scale:1/i,_invertForward:n,target:o,sessionRoot:t?.gameObject??null}}applyWebARSessionRoot(){if(!this.objectToExport)return;const{scale:e,_invertForward:t,target:i,sessionRoot:n}=this.getARScaleAndTarget(),o=n?.matrixWorld.clone().invert();this._rootSessionRootWasAppliedTo=i,this._rootPositionBeforeExport.copy(i.position),this._rootRotationBeforeExport.copy(i.quaternion),this._rootScaleBeforeExport.copy(i.scale),i.scale.multiplyScalar(e),t&&i.quaternion.multiply(Go.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=co.getOrCreate().createQuicklookButton();return t.parentNode||this.context.menu.appendChild(t),t}};Ct([f(c.Object3D)],hi.prototype,"objectToExport");Ct([f()],hi.prototype,"autoExportAnimations");Ct([f()],hi.prototype,"autoExportAudioSources");Ct([f()],hi.prototype,"exportFileName");Ct([f(URL)],hi.prototype,"customUsdzFile");Ct([f(Tr)],hi.prototype,"customBranding");Ct([f()],hi.prototype,"anchoringType");Ct([f()],hi.prototype,"maxTextureSize");Ct([f()],hi.prototype,"planeAnchoringAlignment");Ct([f()],hi.prototype,"interactive");Ct([f()],hi.prototype,"physics");Ct([f()],hi.prototype,"allowCreateQuicklookButton");Ct([f()],hi.prototype,"quickLookCompatible");let Wn=hi;var Wk=Object.defineProperty,Gk=Object.getOwnPropertyDescriptor,dy=(s,e,t,i)=>{for(var n=Gk(e,t),o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&Wk(e,t,n),n};class tl extends R{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)}}dy([f()],tl.prototype,"near");dy([f()],tl.prototype,"far");dy([f(c.Color)],tl.prototype,"color");var Hk=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&&Hk(e,t,n),n};class Ar extends R{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!Nc||(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(),ge.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(;this._boxHelper;)this._boxHelper?.update(),yield}}uy([f()],Ar.prototype,"objectBounds");uy([f(c.Color)],Ar.prototype,"color");uy([f()],Ar.prototype,"isGizmo");var qk=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&&qk(e,t,n),n};class il extends R{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!Nc)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)}}fy([f()],il.prototype,"isGizmo");fy([f(c.Color)],il.prototype,"color0");fy([f(c.Color)],il.prototype,"color1");var Xk=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&&Xk(e,t,n),n};class my extends R{connectedBody;get rigidBody(){return this._rigidBody}_rigidBody=null;onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent($e)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.activeAndEnabled&&this.createJoint(this.rigidBody,this.connectedBody)}}py([f($e)],my.prototype,"connectedBody");class gy extends my{createJoint(e,t){this.context.physics.engine?.addFixedJoint(e,t)}}class ch extends my{anchor;axis;createJoint(e,t){this.axis&&this.anchor&&this.context.physics.engine?.addHingeJoint(e,t,this.anchor,this.axis)}}py([f(c.Vector3)],ch.prototype,"anchor");py([f(c.Vector3)],ch.prototype,"axis");var Qk=Object.defineProperty,Yk=Object.getOwnPropertyDescriptor,Pi=(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&&Qk(e,t,n),n};function Jr(s){return s*Math.PI/180}const Eb=300,Ws=x("debuglights");class Pt extends R{type=0;get range(){return this._range}set range(e){this._range=e,this.light&&(this.light.type==="SpotLight"||this.light.type==="PointLight")&&"distance"in this.light&&(this.light.distance=e)}_range=1;get spotAngle(){return this._spotAngle}set spotAngle(e){this._spotAngle=e,this.light&&this.light.type==="SpotLight"&&"angle"in this.light&&(this.light.angle=Jr(e/2))}_spotAngle=30;get innerSpotAngle(){return this._innerSpotAngle}set innerSpotAngle(e){if(this._innerSpotAngle=e,this.light&&this.light.type==="SpotLight"&&"penumbra"in this.light){const t=this.spotAngle,n=1-Jr(e/2)/Jr(t/2);this.light.penumbra=n}}_innerSpotAngle=10;set color(e){this._color=e,this.light!==void 0&&(this.light.color=e)}get color(){return this.light?this.light.color:this._color}_color=new c.Color(16777215);set shadowNearPlane(e){if(e!==this._shadowNearPlane&&(this._shadowNearPlane=e,this.light?.shadow?.camera!==void 0)){const t=this.light.shadow.camera;t.near=e}}get shadowNearPlane(){return this._shadowNearPlane}_shadowNearPlane=.1;set shadowBias(e){e!==this._shadowBias&&(this._shadowBias=e,this.light?.shadow?.bias!==void 0&&(this.light.shadow.bias=e,this.light.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}_shadowBias=0;set shadowNormalBias(e){e!==this._shadowNormalBias&&(this._shadowNormalBias=e,this.light?.shadow?.normalBias!==void 0&&(this.light.shadow.normalBias=e,this.light.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}_shadowNormalBias=0;_overrideShadowBiasSettings=!1;set shadows(e){this._shadows=e,this.light&&(this.light.castShadow=e!==0,this.updateShadowSoftHard())}get shadows(){return this._shadows}_shadows=1;lightmapBakeType=4;set intensity(e){this._intensity=e,this.light&&(this.light.intensity=e),Ws&&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),Ws&&console.log(this.name,this)}onEnable(){Ws&&console.log("ENABLE LIGHT",this.name),this.createLight(),!this.isBaked&&(this.light&&(this.light.visible=!0,this.light.intensity=this._intensity,Ws&&console.log("Set light intensity to "+this.light.intensity,this.name),this.selfIsLight||this.light.parent!==this.gameObject&&this.gameObject.add(this.light)),this.type===1&&this.startCoroutine(this.updateMainLightRoutine(),ge.LateUpdate))}onDisable(){Ws&&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,-Eb*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),dr(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Ws){const r=new c.DirectionalLightHelper(this.light,.2,this.color);this.context.scene.add(r)}break;case 0:const i=new c.SpotLight(this.color,this.intensity*Math.PI,this.range,Jr(this.spotAngle/2),1-Jr(this.innerSpotAngle/2)/Jr(this.spotAngle/2),2);i.position.set(0,0,0),i.rotation.set(0,0,0),this.light=i;const n=i.target;i.add(n),n.position.set(0,0,this.range),n.rotation.set(0,0,0);break;case 2:const o=new c.PointLight(this.color,this.intensity*Math.PI,this.range);this.light=o;break}if(this.light){if(this._intensity>=0?this.light.intensity=this._intensity:this._intensity=this.light.intensity,this.shadows!==0?this.light.castShadow=!0:this.light.castShadow=!1,this.light.shadow){this._shadowResolution!==void 0&&this._shadowResolution>4?(this.light.shadow.mapSize.width=this._shadowResolution,this.light.shadow.mapSize.height=this._shadowResolution):(this.light.shadow.mapSize.width=2048,this.light.shadow.mapSize.height=2048),Ws&&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=Eb*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,Ws&&this.context.scene.add(new c.CameraHelper(t))}this.isBaked?this.light.removeFromParent():e||this.gameObject.add(this.light)}}*updateMainLightRoutine(){for(;;){this.type===1&&((!this.context.mainLight||this.intensity>this.context.mainLight.intensity)&&(this.context.mainLight=this),yield);break}}static allowChangingRendererShadowMapType=!0;updateShadowSoftHard(){this.light&&this.light.shadow&&(this.shadows===2||(this.light.shadow.radius=1,this.light.shadow.blurSamples=1))}setDirectionalLight(e){e.add(e.target),e.target.position.set(0,0,-1)}}Pi([f()],Pt.prototype,"type",2);Pi([f()],Pt.prototype,"range",1);Pi([f()],Pt.prototype,"spotAngle",1);Pi([f()],Pt.prototype,"innerSpotAngle",1);Pi([f(c.Color)],Pt.prototype,"color",1);Pi([f()],Pt.prototype,"shadowNearPlane",1);Pi([f()],Pt.prototype,"shadowBias",1);Pi([f()],Pt.prototype,"shadowNormalBias",1);Pi([f()],Pt.prototype,"shadows",1);Pi([f()],Pt.prototype,"lightmapBakeType",2);Pi([f()],Pt.prototype,"intensity",1);Pi([f()],Pt.prototype,"shadowDistance",1);Pi([f()],Pt.prototype,"shadowResolution",1);new c.Vector3(0,0,0);var Kk=Object.defineProperty,Gu=(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};const dp=x("debuglods"),Zk=x("nolods");class nl{screenRelativeTransitionHeight;distance;renderers}Gu([f()],nl.prototype,"screenRelativeTransitionHeight");Gu([f()],nl.prototype,"distance");Gu([f(Ht)],nl.prototype,"renderers");class Jk{model;get renderers(){return this.model.renderers}constructor(e){this.model=e}}class Hu extends R{lodModels=[];_lods=[];_settings=[];_lodsHandler;start(){if(dp&&console.log("LODGROUP",this.name,this.lodModels,this),!Zk&&!this._lodsHandler&&this.gameObject&&this.lodModels&&Array.isArray(this.lodModels)){const e=[];for(const i of this.lodModels){const n=new Jk(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;dp&&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}dp&&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}}}}Gu([f(nl)],Hu.prototype,"lodModels");class yy extends R{}var eR=Object.defineProperty,_y=(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};const nd=x("debugnestedgltf");class sl extends R{filePath;loaded=new ne;loadAssetInParent=!0;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){return this.filePath?.preload()||null}async start(){if(this._isLoadingOrDoneLoading)return;nd&&console.log(this,this.guid);const e=this.gameObject.parent;if(e&&this.filePath){this._isLoadingOrDoneLoading=!0;const t=new gn;t.idProvider=new wt(this.hash(this.guid)),t.parent=this.loadAssetInParent!==!1?e:this.gameObject,this.gameObject.updateMatrix();const i=this.gameObject.matrix;nd&&console.log("Load nested:",this.filePath?.url??this.filePath,this.gameObject.position);const n=await this.filePath?.instantiate?.call(this.filePath,t);nd&&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})),nd&&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}}_y([f(Z)],sl.prototype,"filePath");_y([f(ne)],sl.prototype,"loaded");_y([f()],sl.prototype,"loadAssetInParent");var tR=Object.defineProperty,by=(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&&tR(e,t,n),n};const iR=x("debugnet"),qu=class mm extends R{url=null;urlParameterName=null;localhost=null;awake(){iR&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?mm.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=mm.IsLocalNetwork()&&t;if(n&&(i=t),e?.startsWith("/")){const o=n?i:window.location.origin;o?.endsWith("/")&&e.startsWith("/")&&(e=e.substring(1)),i=o+e}return i}static IsLocalNetwork(e=window.location.hostname){return yi(e)}};by([f()],qu.prototype,"url");by([f()],qu.prototype,"urlParameterName");by([f()],qu.prototype,"localhost");let vy=qu;var nR=Object.defineProperty,Xu=(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&&nR(e,t,n),n};class Dr extends R{referenceSpace;from;affectPosition=!1;affectRotation=!1;alignLookDirection=!1;levelLookDirection=!1;levelPosition=!1;positionOffset=new c.Vector3(0,0,0);rotationOffset=new c.Vector3(0,0,0);offset=new c.Vector3(0,0,0);update(){if(!this.from)return;var e=Y(this.from),t=pe(this.from);this.offset.copy(this.positionOffset);const i=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(i),e.add(this.offset),this.levelPosition&&this.referenceSpace){const a=new c.Plane(this.gameObject.up,0),l=Y(this.referenceSpace);a.setFromNormalAndCoplanarPoint(this.gameObject.up,l);const h=new c.Vector3(0,0,0);a.projectPoint(e,h),e.copy(h)}this.affectPosition&&at(this.gameObject,e);const n=new c.Euler(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),o=new c.Quaternion().setFromEuler(n);this.affectRotation&&dn(this.gameObject,t.multiply(o));const r=new c.Vector3;this.from.getWorldDirection(r).multiplyScalar(50),this.levelLookDirection&&(r.y=0),this.alignLookDirection&&this.gameObject.lookAt(r)}}Xu([f(S)],Dr.prototype,"referenceSpace");Xu([f(S)],Dr.prototype,"from");Xu([f(c.Vector3)],Dr.prototype,"positionOffset");Xu([f(c.Vector3)],Dr.prototype,"rotationOffset");var sR=Object.defineProperty,Oo=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&sR(e,t,n),n};class oi{time=0;value=0;inTangent=1/0;inWeight;outTangent=1/0;outWeight;weightedMode;constructor(e=0,t=0){this.time=e,this.value=t}}Oo([f()],oi.prototype,"time");Oo([f()],oi.prototype,"value");Oo([f()],oi.prototype,"inTangent");Oo([f()],oi.prototype,"inWeight");Oo([f()],oi.prototype,"outTangent");Oo([f()],oi.prototype,"outWeight");Oo([f()],oi.prototype,"weightedMode");const ox=class ql{static linearFromTo(e,t,i){const n=new ql,o=new oi;o.time=0,o.value=e;const r=new oi;return r.time=i,r.value=t,n.keys.push(o,r),n}static constant(e){const t=new ql,i=new oi;return i.time=0,i.value=e,t.keys.push(i),t}keys=[];clone(){const e=new ql;return e.keys=this.keys?.map(t=>{const i=new oi;return i.time=t.time,i.value=t.value,i.inTangent=t.inTangent,i.inWeight=t.inWeight,i.outTangent=t.outTangent,i.outWeight=t.outWeight,i.weightedMode=t.weightedMode,i})||[],e}get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(e){if(!this.keys||this.keys.length==0)return 0;if(this.keys.length===1)return this.keys[0].value;if(this.keys[0].time>=e)return this.keys[0].value;for(let t=0;t<this.keys.length;t++){const i=this.keys[t];if(i.time<=e)if(t+1<this.keys.length){const o=this.keys[t+1];if(o.time<e)continue;return!isFinite(i.outTangent)||!isFinite(o.inTangent)?i.value:ql.interpolateValue(e,i,o)}else return i.value}return this.keys[this.keys.length-1].value}static interpolateValue(e,t,i){const n=t.time,o=t.value,r=t.outTangent,a=i.time,l=i.value,h=i.inTangent,d=a-n,u=d*d,p=u*d,m=((r+h)*d-2*(l-o))/p,y=(3*(l-o)-(h+2*r)*d)/u,_=r,g=o,w=e-n,b=w*w,v=b*w;return m*v+y*b+_*w+g}};Oo([f(oi)],ox.prototype,"keys");let hh=ox;var oR=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&&oR(e,t,n),n};const sd=x("debugparticles");var rs=(s=>(s[s.Billboard=0]="Billboard",s[s.Stretch=1]="Stretch",s[s.HorizontalBillboard=2]="HorizontalBillboard",s[s.VerticalBillboard=3]="VerticalBillboard",s[s.Mesh=4]="Mesh",s))(rs||{});class Lr{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()],Lr.prototype,"alphaKeys");C([f()],Lr.prototype,"colorKeys");var Mc=(s=>(s[s.Local=0]="Local",s[s.World=1]="World",s[s.Custom=2]="Custom",s))(Mc||{}),su=(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))(su||{});const Rs=class Xl{static constant(e){const t=new Xl;return t.setConstant(e),t}static betweenTwoConstants(e,t){const i=new Xl;return i.setMinMaxConstant(e,t),i}static curve(e,t=1){const i=new Xl;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 Xl;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()],Rs.prototype,"mode");C([f()],Rs.prototype,"constant");C([f()],Rs.prototype,"constantMin");C([f()],Rs.prototype,"constantMax");C([f(hh)],Rs.prototype,"curve");C([f(hh)],Rs.prototype,"curveMin");C([f(hh)],Rs.prototype,"curveMax");C([f()],Rs.prototype,"curveMultiplier");let H=Rs;const Mo=class yt{static constant(e){const t=new yt;return t.constant(e),t}static betweenTwoColors(e,t){const i=new yt;return i.betweenTwoColors(e,t),i}constant(e){return this.mode=0,this.color=e,this}betweenTwoColors(e,t){return this.mode=2,this.colorMin=e,this.colorMax=t,this}mode=0;color;colorMin;colorMax;gradient;gradientMin;gradientMax;static _temp=new te(0,0,0,1);static _temp2=new te(0,0,0,1);evaluate(e,t){const i=t===void 0?Math.random():t;switch(this.mode){case 0:case"Color":return this.color;case 1:case"Gradient":return this.gradient.evaluate(e,yt._temp),yt._temp;case 2:case"TwoColors":return yt._temp.lerpColors(this.colorMin,this.colorMax,i);case 3:case"TwoGradients":return this.gradientMin.evaluate(e,yt._temp),this.gradientMax.evaluate(e,yt._temp2),yt._temp.lerp(yt._temp2,i);case 4:case"RandomColor":const o=Math.random();return this.gradientMin.evaluate(e,yt._temp),this.gradientMax.evaluate(e,yt._temp2),yt._temp.lerp(yt._temp2,o)}return yt._temp.set(16777215),yt._temp.alpha=1,yt._temp}};C([f()],Mo.prototype,"mode");C([f(te)],Mo.prototype,"color");C([f(te)],Mo.prototype,"colorMin");C([f(te)],Mo.prototype,"colorMax");C([f(Lr)],Mo.prototype,"gradient");C([f(Lr)],Mo.prototype,"gradientMin");C([f(Lr)],Mo.prototype,"gradientMax");let Ir=Mo;var gm=(s=>(s[s.Hierarchy=0]="Hierarchy",s[s.Local=1]="Local",s[s.Shape=2]="Shape",s))(gm||{});class Lt{cullingMode;duration;emitterVelocityMode;flipRotation;gravityModifier;gravityModifierMultiplier;loop;maxParticles;playOnAwake;prewarm;ringBufferLoopRange;ringBufferMode;scalingMode;simulationSpace;simulationSpeed;startColor;startDelay;startDelayMultiplier;startLifetime;startLifetimeMultiplier;startRotation;startRotationMultiplier;startRotation3D;startRotationX;startRotationXMultiplier;startRotationY;startRotationYMultiplier;startRotationZ;startRotationZMultiplier;startSize;startSize3D;startSizeMultiplier;startSizeX;startSizeXMultiplier;startSizeY;startSizeYMultiplier;startSizeZ;startSizeZMultiplier;startSpeed;startSpeedMultiplier;stopAction;useUnscaledTime}C([f(H)],Lt.prototype,"gravityModifier");C([f(Ir)],Lt.prototype,"startColor");C([f(H)],Lt.prototype,"startDelay");C([f(H)],Lt.prototype,"startLifetime");C([f(H)],Lt.prototype,"startRotation");C([f(H)],Lt.prototype,"startRotationX");C([f(H)],Lt.prototype,"startRotationY");C([f(H)],Lt.prototype,"startRotationZ");C([f(H)],Lt.prototype,"startSize");C([f(H)],Lt.prototype,"startSizeX");C([f(H)],Lt.prototype,"startSizeY");C([f(H)],Lt.prototype,"startSizeZ");C([f(H)],Lt.prototype,"startSpeed");class ou{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 Es{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()],Es.prototype,"enabled");C([f()],Es.prototype,"bursts");C([f(H)],Es.prototype,"rateOverTime");C([f()],Es.prototype,"rateOverTimeMultiplier");C([f(H)],Es.prototype,"rateOverDistance");C([f()],Es.prototype,"rateOverDistanceMultiplier");class Qu{enabled;color}C([f(Ir)],Qu.prototype,"color");class jr{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)],jr.prototype,"size");C([f(H)],jr.prototype,"x");C([f(H)],jr.prototype,"y");C([f(H)],jr.prototype,"z");const Ye=class Ql{get type(){return su[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 Ql}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(){sd&&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:sd&&B.DrawWireBox(this.position,this.scale,14540253,1),this._vector.x=Math.random()*this.scale.x-this.scale.x/2,this._vector.y=Math.random()*this.scale.y-this.scale.y/2,this._vector.z=Math.random()*this.scale.z-this.scale.z/2,this._vector.add(t);break;case 4:this.randomConePoint(this.position,this.angle,n,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 10:this.randomCirclePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 13:const o=this.meshRenderer;o?.destroyed==!1&&this.setMesh(o);const r=e.mesh=this._meshObj,a=e.mesh_geometry=this._meshGeometry;if(r&&a)switch(this.meshShapeType){case 0:{const l=a.getAttribute("position"),h=Math.floor(Math.random()*l.count);this._vector.fromBufferAttribute(l,h),this._vector.applyMatrix4(r.matrixWorld),e.mesh_normal=h}break;case 1:break;case 2:{const l=a.index;if(l){let h=Math.random(),d=Math.random();h+d>1&&(h=1-h,d=1-d);const u=Math.floor(Math.random()*(l.count/3));let p=u*3,m=u*3+1,y=u*3+2;p=l.getX(p),m=l.getX(m),y=l.getX(y);const _=a.getAttribute("position");this._triangle.a.fromBufferAttribute(_,p),this._triangle.b.fromBufferAttribute(_,m),this._triangle.c.fromBufferAttribute(_,y),this._vector.set(0,0,0).addScaledVector(this._triangle.a,h).addScaledVector(this._triangle.b,d).addScaledVector(this._triangle.c,1-(h+d)),this._vector.applyMatrix4(r.matrixWorld),e.mesh_normal=u}}break}break;default:this._vector.set(0,0,0),A()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",su[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)),sd&&B.DrawSphere(this._vector,.03,16711680,.5,!0)}_dir=new c.Vector3;getDirection(e,t){if(!this.enabled)return this._dir.set(0,0,1),this._dir;switch(this.shapeType){case 5:this._dir.set(0,0,1);break;case 4:this._dir.set(0,0,1);break;case 10:case 0:const i=t.x,n=t.y,o=t.z;this._dir.set(i,n,o),this.system?.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;case 13:const r=e.mesh,a=e.mesh_geometry;if(r&&a)switch(this.meshShapeType){case 0:{const l=a.getAttribute("normal"),h=e.mesh_normal;this._dir.fromBufferAttribute(l,h)}break;case 1:break;case 2:{const l=a.index;if(l){const h=e.mesh_normal,d=l.getX(h*3),u=l.getX(h*3+1),p=l.getX(h*3+2),m=a.getAttribute("position"),y=F(),_=F(),g=F();y.fromBufferAttribute(m,d),_.fromBufferAttribute(m,u),g.fromBufferAttribute(m,p),y.sub(_),g.sub(_),y.cross(g),this._dir.copy(y).multiplyScalar(-1);const w=pe(r);this._dir.applyQuaternion(w)}}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),sd&&(B.DrawSphere(t,.01,8925952,.5,!0),B.DrawDirection(t,this._dir,8925952,.5,!0)),this._dir}static _randomQuat=new c.Quaternion;static _tempVec=new c.Vector3;randomizePosition(e,t){if(t<=0)return;const i=Ql._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=Ql._randomQuat,n=Ql._tempVec;n.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),i.setFromAxisAngle(n,t*Math.random()*Math.PI),e.applyQuaternion(i)}spherizeDirection(e,t){if(t===0)return;const i=Math.random()*Math.PI*2,n=Math.acos(1-Math.random()*2),o=Math.sin(n)*Math.cos(i),r=Math.sin(n)*Math.sin(i),a=Math.cos(n),l=new c.Vector3(o,r,a);e.lerp(l,t)}randomSpherePoint(e,t,i,n,o){const r=Math.random(),a=Math.random(),l=2*Math.PI*r*(n/360),h=Math.acos(2*a-1),d=I.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,u=e.x+this.scale.x*(-d*Math.sin(h)*Math.cos(l)),p=e.y+this.scale.y*(d*Math.sin(h)*Math.sin(l)),m=e.z+this.scale.z*(d*Math.cos(h));o.x=u,o.y=p,o.z=m}randomCirclePoint(e,t,i,n,o){const r=Math.random(),a=2*Math.PI*r*(n/360),l=I.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,h=e.x+this.scale.x*l*Math.cos(a),d=e.y+this.scale.y*l*Math.sin(a),u=e.z;o.x=h,o.y=d,o.z=u}_loopTime=0;_loopDirection=1;randomConePoint(e,t,i,n,o,r,a){let l=0,h=0;switch(r){case 0:l=Math.random(),h=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:l=.5,h=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let d=2*Math.PI*l*(o/360);switch(r){case 2:case 1:d+=Math.PI+.5,d+=this._loopTime*Math.PI*2,d%=I.toRadians(o);break}const u=Math.acos(2*h-1),p=I.lerp(1,1-Math.pow(1-Math.random(),Math.PI),n)*i,m=e.x+-p*Math.sin(u)*Math.cos(d),y=e.y+p*Math.sin(u)*Math.sin(d),_=e.z;a.x=m*this.scale.x,a.y=y*this.scale.y,a.z=_*this.scale.z}};C([f()],Ye.prototype,"shapeType");C([f()],Ye.prototype,"enabled");C([f()],Ye.prototype,"alignToDirection");C([f()],Ye.prototype,"angle");C([f()],Ye.prototype,"arc");C([f()],Ye.prototype,"arcSpread");C([f()],Ye.prototype,"arcSpeedMultiplier");C([f()],Ye.prototype,"arcMode");C([f(c.Vector3)],Ye.prototype,"boxThickness");C([f(c.Vector3)],Ye.prototype,"position");C([f(c.Vector3)],Ye.prototype,"rotation");C([f(c.Vector3)],Ye.prototype,"scale");C([f()],Ye.prototype,"radius");C([f()],Ye.prototype,"radiusThickness");C([f()],Ye.prototype,"sphericalDirectionAmount");C([f()],Ye.prototype,"randomDirectionAmount");C([f()],Ye.prototype,"randomPositionAmount");C([f()],Ye.prototype,"meshShapeType");C([f(th)],Ye.prototype,"meshRenderer");let wy=Ye;class me{damping;enabled;frequency;octaveCount;octaveMultiplier;octaveScale;positionAmount;quality;remap;remapEnabled;remapMultiplier;remapX;remapXMultiplier;remapY;remapYMultiplier;remapZ;remapZMultiplier;scrollSpeedMultiplier;separateAxes;strengthMultiplier;strengthX;strengthXMultiplier;strengthY;strengthYMultiplier;strengthZ;strengthZMultiplier;_noise;_time=0;update(e){this._time+=e.time.deltaTime*this.scrollSpeedMultiplier}_temp=new c.Vector3;apply(e,t,i,n,o,r){if(!this.enabled)return;this._noise||(this._noise=ae.createNoise4D(()=>0));const a=this._temp.set(t.x,t.y,t.z).multiplyScalar(this.frequency),l=this._noise(a.x,a.y,a.z,this._time),h=this._noise(a.x,a.y,a.z,this._time+1e3*this.frequency),d=this._noise(a.x,a.y,a.z,this._time+2e3*this.frequency);this._temp.set(l,h,d).normalize();const u=o/r;let p=this.positionAmount.evaluate(u);this.separateAxes?(this._temp.x*=p*this.strengthXMultiplier,this._temp.y*=p*this.strengthYMultiplier,this._temp.z*=p*this.strengthZMultiplier):(this.strengthX&&(p*=this.strengthX.evaluate(u)*1.5),this._temp.multiplyScalar(p)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z}}C([f()],me.prototype,"damping");C([f()],me.prototype,"enabled");C([f()],me.prototype,"frequency");C([f()],me.prototype,"octaveCount");C([f()],me.prototype,"octaveMultiplier");C([f()],me.prototype,"octaveScale");C([f(H)],me.prototype,"positionAmount");C([f()],me.prototype,"quality");C([f(H)],me.prototype,"remap");C([f()],me.prototype,"remapEnabled");C([f()],me.prototype,"remapMultiplier");C([f(H)],me.prototype,"remapX");C([f()],me.prototype,"remapXMultiplier");C([f(H)],me.prototype,"remapY");C([f()],me.prototype,"remapYMultiplier");C([f(H)],me.prototype,"remapZ");C([f()],me.prototype,"remapZMultiplier");C([f()],me.prototype,"scrollSpeedMultiplier");C([f()],me.prototype,"separateAxes");C([f()],me.prototype,"strengthMultiplier");C([f(H)],me.prototype,"strengthX");C([f()],me.prototype,"strengthXMultiplier");C([f(H)],me.prototype,"strengthY");C([f()],me.prototype,"strengthYMultiplier");C([f(H)],me.prototype,"strengthZ");C([f()],me.prototype,"strengthZMultiplier");class De{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()],De.prototype,"enabled");C([f()],De.prototype,"attachRibbonToTransform");C([f(Ir)],De.prototype,"colorOverLifetime");C([f(Ir)],De.prototype,"colorOverTrail");C([f()],De.prototype,"dieWithParticles");C([f()],De.prototype,"inheritParticleColor");C([f(H)],De.prototype,"lifetime");C([f()],De.prototype,"lifetimeMultiplier");C([f()],De.prototype,"minVertexDistance");C([f()],De.prototype,"mode");C([f()],De.prototype,"ratio");C([f()],De.prototype,"ribbonCount");C([f()],De.prototype,"shadowBias");C([f()],De.prototype,"sizeAffectsLifetime");C([f()],De.prototype,"sizeAffectsWidth");C([f()],De.prototype,"splitSubEmitterRibbons");C([f()],De.prototype,"textureMode");C([f(H)],De.prototype,"widthOverTrail");C([f()],De.prototype,"widthOverTrailMultiplier");C([f()],De.prototype,"worldSpace");class Fe{enabled;space=0;orbitalX;orbitalY;orbitalZ;orbitalXMultiplier;orbitalYMultiplier;orbitalZMultiplier;orbitalOffsetX;orbitalOffsetY;orbitalOffsetZ;speedModifier;speedModifierMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_system;update(e){this._system=e}_temp=new c.Vector3;_temp2=new c.Vector3;_temp3=new c.Vector3;_hasOrbital=!1;_index=0;_orbitalMatrix=new c.Matrix4;init(e){this._index==0&&(e.debug=!0),this._index+=1,e.orbitx=this.orbitalX.evaluate(Math.random()),e.orbity=this.orbitalY.evaluate(Math.random()),e.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=e.orbitx!=0||e.orbity!=0||e.orbitz!=0}apply(e,t,i,n,o,r,a){if(!this.enabled)return;const l=r/a,h=this.speedModifier.evaluate(l)*this.speedModifierMultiplier,d=this.x.evaluate(l),u=this.y.evaluate(l),p=this.z.evaluate(l);if(this._temp.set(-d,u,p),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&this._system?.worldPos){const y=this._temp2.set(i.x,i.y,i.z),_=this.orbitalXMultiplier,g=this.orbitalYMultiplier,w=this.orbitalZMultiplier,b=h*Math.PI*2*10,v=Math.cos(b*_),E=Math.sin(b*_),O=Math.cos(b*g),M=Math.sin(b*g),D=Math.cos(b*w),L=Math.sin(b*w),j=y.x*(O*D)+y.y*(O*L)+y.z*-M,V=y.x*(E*M*D-v*L)+y.y*(E*M*L+v*D)+y.z*(E*O),W=y.x*(v*M*D+E*L)+y.y*(v*M*L-E*D)+y.z*(v*O),k=this._temp3.set(y.x-j,y.y-V,y.z-W);k.normalize(),k.multiplyScalar(.2/o*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),n.x+=k.x,n.y+=k.y,n.z+=k.z}n.x+=this._temp.x,n.y+=this._temp.y,n.z+=this._temp.z,n.x*=h,n.y*=h,n.z*=h}}C([f()],Fe.prototype,"enabled");C([f()],Fe.prototype,"space");C([f(H)],Fe.prototype,"orbitalX");C([f(H)],Fe.prototype,"orbitalY");C([f(H)],Fe.prototype,"orbitalZ");C([f()],Fe.prototype,"orbitalXMultiplier");C([f()],Fe.prototype,"orbitalYMultiplier");C([f()],Fe.prototype,"orbitalZMultiplier");C([f()],Fe.prototype,"orbitalOffsetX");C([f()],Fe.prototype,"orbitalOffsetY");C([f()],Fe.prototype,"orbitalOffsetZ");C([f(H)],Fe.prototype,"speedModifier");C([f()],Fe.prototype,"speedModifierMultiplier");C([f(H)],Fe.prototype,"x");C([f()],Fe.prototype,"xMultiplier");C([f(H)],Fe.prototype,"y");C([f()],Fe.prototype,"yMultiplier");C([f(H)],Fe.prototype,"z");C([f()],Fe.prototype,"zMultiplier");class It{animation;enabled;cycleCount;frameOverTime;frameOverTimeMultiplier;numTilesX;numTilesY;startFrame;startFrameMultiplier;rowMode;rowIndex;spriteCount;timeMode;sampleOnceAtStart(){if(this.timeMode===0)switch(this.frameOverTime.mode){case 0:case 3:case 2:case 1:return!0}return!1}getStartIndex(){return this.sampleOnceAtStart()?Math.random()*(this.numTilesX*this.numTilesY):0}evaluate(e){if(!this.sampleOnceAtStart())return this.getIndex(e)}getIndex(e){const t=this.numTilesX*this.numTilesY;e=e*this.cycleCount;let i=this.frameOverTime.evaluate(e%1);return i*=this.frameOverTimeMultiplier,i*=t,i=i%t,i=Math.floor(i),i}}C([f()],It.prototype,"animation");C([f()],It.prototype,"enabled");C([f()],It.prototype,"cycleCount");C([f(H)],It.prototype,"frameOverTime");C([f()],It.prototype,"frameOverTimeMultiplier");C([f()],It.prototype,"numTilesX");C([f()],It.prototype,"numTilesY");C([f(H)],It.prototype,"startFrame");C([f()],It.prototype,"startFrameMultiplier");C([f()],It.prototype,"rowMode");C([f()],It.prototype,"rowIndex");C([f()],It.prototype,"spriteCount");C([f()],It.prototype,"timeMode");class _n{enabled;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){return this.enabled?this.separateAxes?0:this.z.evaluate(e,t)*-1:0}}C([f()],_n.prototype,"enabled");C([f()],_n.prototype,"separateAxes");C([f(H)],_n.prototype,"x");C([f()],_n.prototype,"xMultiplier");C([f(H)],_n.prototype,"y");C([f()],_n.prototype,"yMultiplier");C([f(H)],_n.prototype,"z");C([f()],_n.prototype,"zMultiplier");class Qi{enabled;range;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){if(!this.enabled)return 0;if(!this.separateAxes){const i=I.lerp(this.range.x,this.range.y,t);return this.z.evaluate(i)*-1}return 0}}C([f()],Qi.prototype,"enabled");C([f()],Qi.prototype,"range");C([f()],Qi.prototype,"separateAxes");C([f(H)],Qi.prototype,"x");C([f()],Qi.prototype,"xMultiplier");C([f(H)],Qi.prototype,"y");C([f()],Qi.prototype,"yMultiplier");C([f(H)],Qi.prototype,"z");C([f()],Qi.prototype,"zMultiplier");class nt{enabled;dampen;drag;dragMultiplier;limit;limitMultiplier;separateAxes;limitX;limitXMultiplier;limitY;limitYMultiplier;limitZ;limitZMultiplier;multiplyDragByParticleSize=!1;multiplyDragByParticleVelocity=!1;space;_temp=new c.Vector3;_temp2=new c.Vector3;apply(e,t,i,n,o,r,a){if(this.enabled){const l=this.limit.evaluate(o)*this.limitMultiplier;if(t.length()>l){this._temp.copy(t).normalize().multiplyScalar(l);const d=this.dampen*.5;t.x=I.lerp(t.x,this._temp.x,d),t.y=I.lerp(t.y,this._temp.y,d),t.z=I.lerp(t.z,this._temp.z,d),i.x=I.lerp(i.x,this._temp.x,d),i.y=I.lerp(i.y,this._temp.y,d),i.z=I.lerp(i.z,this._temp.z,d)}}}}C([f()],nt.prototype,"enabled");C([f()],nt.prototype,"dampen");C([f(H)],nt.prototype,"drag");C([f()],nt.prototype,"dragMultiplier");C([f(H)],nt.prototype,"limit");C([f()],nt.prototype,"limitMultiplier");C([f()],nt.prototype,"separateAxes");C([f(H)],nt.prototype,"limitX");C([f()],nt.prototype,"limitXMultiplier");C([f(H)],nt.prototype,"limitY");C([f()],nt.prototype,"limitYMultiplier");C([f(H)],nt.prototype,"limitZ");C([f()],nt.prototype,"limitZMultiplier");C([f()],nt.prototype,"multiplyDragByParticleSize");C([f()],nt.prototype,"multiplyDragByParticleVelocity");C([f()],nt.prototype,"space");const dh=class rx{enabled;curve;curveMultiplier;mode;clone(){const e=new rx;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()],dh.prototype,"enabled");C([f(H)],dh.prototype,"curve");C([f()],dh.prototype,"curveMultiplier");C([f()],dh.prototype,"mode");let xy=dh;class di{enabled;range;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t,i,n){const o=e.length(),r=I.remap(o,this.range.x,this.range.y,0,1),a=this.size.evaluate(r,i);return n.x*=a,n.y*=a,n.z*=a,n}}C([f()],di.prototype,"enabled");C([f(c.Vector2)],di.prototype,"range");C([f()],di.prototype,"separateAxes");C([f(H)],di.prototype,"size");C([f()],di.prototype,"sizeMultiplier");C([f(H)],di.prototype,"x");C([f()],di.prototype,"xMultiplier");C([f(H)],di.prototype,"y");C([f()],di.prototype,"yMultiplier");C([f(H)],di.prototype,"z");C([f()],di.prototype,"zMultiplier");class ol{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()],ol.prototype,"enabled");C([f(c.Vector2)],ol.prototype,"range");C([f(Ir)],ol.prototype,"color");new c.Vector3(1,1,1);new c.Vector3(0,0,1);class Sy{constructor(e,t,i,n){this.system=e,this.particleSystem=t,this.subSystem=i,this.subParticleSystem=n,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const o=1e3;this._circularBuffer=new _i(()=>new ae.Matrix4,o)}type="NeedleParticleSubEmitter";emitterType;emitterProbability;q_=new c.Quaternion;v_=new c.Vector3;v2_=new c.Vector3;_emitterMatrix=new ae.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===ym.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===ym.Death){let n=e.life;if(e[ya]!==void 0&&(n=e[ya]),!(e.age+t*1.2>=n))return;const r=this.subSystem.main.maxParticles-this.subSystem.currentParticles;e.emissionState.waitEmiting=r}const i=new ae.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 rR=Object.defineProperty,Le=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&rR(e,t,n),n};const Js=x("debugparticles"),aR=x("noprogressive"),lR=x("debugprogressive");var ym=(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))(ym||{});class Yi extends R{renderMode;particleMaterial;trailMaterial;particleMesh;maxParticleSize;minParticleSize;velocityScale;cameraVelocityScale;lengthScale;start(){if(this.maxParticleSize!==.5&&this.minParticleSize!==0&&A()){const e=`ParticleSystem "${this.name}" has non-default min/max particle size. This may not render correctly. Please set min size to 0 and the max size to 0.5 and use the "StartSize" setting instead`;console.warn(e)}}get transparent(){return this.particleMaterial?.transparent??!1}getMaterial(e=!1){let t=e===!0&&this.trailMaterial?this.trailMaterial:this.particleMaterial;if(t){if(t.type==="MeshStandardMaterial"){Js&&console.debug("ParticleSystemRenderer.getMaterial: MeshStandardMaterial detected, converting to MeshBasicMaterial. See https://github.com/Alchemist0823/three.quarks/issues/101"),"map"in t&&t.map&&(t.map.colorSpace=c.LinearSRGBColorSpace,t.map.premultiplyAlpha=!1);const i=new c.MeshBasicMaterial;i.copy(t),e?this.trailMaterial=i:this.particleMaterial=i}t.map&&(t.map.colorSpace=c.LinearSRGBColorSpace,t.map.premultiplyAlpha=!1),e&&t.side===c.FrontSide&&(t=t.clone(),t.side=c.BackSide,e?this.trailMaterial=t:this.particleMaterial=t)}return t&&!aR&&t._didRequestTextureLOD===void 0&&(t._didRequestTextureLOD=0,lR&&console.log("Load material LOD",t.name),re.NEEDLE_progressive.assignTextureLOD(t,0)),t}getMesh(e){let t=null;if(!t&&(this.particleMesh instanceof c.Mesh&&(t=this.particleMesh.geometry),t===null)){t=new c.PlaneGeometry(1,1);const n=t.attributes.uv;for(let o=0;o<n.count;o++)n.setX(o,1-n.getX(o))}return new c.Mesh(t,this.getMaterial())}}Le([f()],Yi.prototype,"renderMode");Le([f(c.Material)],Yi.prototype,"particleMaterial");Le([f(c.Material)],Yi.prototype,"trailMaterial");Le([f()],Yi.prototype,"maxParticleSize");Le([f()],Yi.prototype,"minParticleSize");Le([f()],Yi.prototype,"velocityScale");Le([f()],Yi.prototype,"cameraVelocityScale");Le([f()],Yi.prototype,"lengthScale");class od{_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 Cy{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 cR extends Cy{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class hR extends Cy{_lastPosition=new c.Vector3;_lastDistance=0;update(){const e=Y(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(e),this._lastPosition.copy(e)}genValue(){if(!this.system.isPlaying||!this.system.emission.enabled||this.system.currentParticles>=this.system.maxParticles)return 0;let e=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){const n=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let r=this._lastDistance/this.system.deltaTime*n;Number.isFinite(r)||(r=0),e+=r}const t=this.system.emission.getBurst();t>0&&(e+=t/this.system.deltaTime);const i=this.system.maxParticles-this.system.currentParticles;return I.clamp(e,0,i/this.system.deltaTime)}}class dR extends Cy{genValue(){return this.system.isPlaying,0}}class ko{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 uR extends ko{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 Tb=Symbol("particleRotation");class fR extends ko{type="NeedleRotation";initialize(e){e[Tb]=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[Tb])*t:this.system.renderer.renderMode===rs.Billboard&&(e.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const n=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(i,n)*t}}}const Ab=Symbol("sizeLerpFactor"),pR=new c.Vector3;class mR extends ko{type="NeedleSize";_minSize=0;_maxSize=1;initialize(e){e[Ab]=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[Ab]).x);let o=1;this.system.renderer.renderMode!==rs.Mesh&&(o=this.system.worldScale.x/this.system.cameraScale);const r=F(e.startSize).multiplyScalar(n*o);if(e.size.set(r.x,r.y,r.z),this.system.localspace){const a=ax(this.system,pR);e.size.x*=a.x,e.size.y*=a.y,e.size.z*=a.z}}}const ya=Symbol("particleLife"),up=Symbol("trailLifetime"),Db=Symbol("trailStartLength"),fp=Symbol("trailWidthRandom");class gR extends ko{type="NeedleTrail";initialize(e){e instanceof ae.TrailParticle&&(e[ya]=e.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(e[up]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),e.life+=e[up]),e[Db]=e.length,e[fp]=Math.random())}update(e){if(this.system.trails?.enabled&&e instanceof ae.TrailParticle){const t=e,i=e.age/e[ya],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[fp]);d.x=u,d.y=u,d.z=u}l.size=this.system.trails.getWidth(d.x,i,h,t[fp]),l.color.copy(e.color),this.system.trails.getColor(l.color,i,h)}if(e.age>e[ya]){e.velocity.set(0,0,0);const r=(e.age-e[ya])/e[up];t.length=I.lerp(e[Db],0,r)}}}}const rd=Symbol("startVelocity"),Lb=Symbol("gravityModifier"),pp=Symbol("gravitySpeed"),ad=Symbol("velocity lerp factor"),_m=new c.Vector3;class yR extends ko{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[rd]?e[rd].copy(e.velocity):e[rd]=e.velocity.clone();const n=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());e[Lb]=n*t,e[pp]=n*t*.5,e[ad]=Math.random(),this.system.velocityOverLifetime?.init(e),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===Mc.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(e,t){const i=e[rd],n=e[Lb];if(n!==0){const u=n*e[pp];_m.copy(this._gravityDirection).multiplyScalar(u),e[pp]+=t*.05,i.add(_m)}e.velocity.copy(i);const o=e.age/e.life;this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyCurrent(e.velocity,o,e[ad]);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[ad],e.size));const l=this.system.colorBySpeed;l?.enabled&&l.evaluate(e.velocity,e[ad],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 Ib=Symbol("colorLerpFactor"),jb=new te(1,1,1,1),No=new te(1,1,1,1);class _R extends ko{type="NeedleColor";initialize(e){}_init(e){const t=this.system.renderer.particleMaterial;No.copy(this.system.main.startColor.evaluate(Math.random())),t?.color&&(jb.copy(t.color),No.multiply(jb)),No.convertLinearToSRGB(),e.startColor.set(No.r,No.g,No.b,No.alpha),e.color.copy(e.startColor),e[Ib]=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[Ib]);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 bR{system;emission;get anim(){return this.system.textureSheetAnimation}constructor(e){this.system=e,this.emission=new hR(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 od(this.system.main.startLifetime)}get startSpeed(){return new od(this.system.main.startSpeed)}get startRotation(){return new od(this.system.main.startRotation)}get startSize(){return new od(this.system.main.startSize)}startLength;get startColor(){return new ae.ConstantColor(new ae.Vector4(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new dR(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 ae.RenderMode.Trail;switch(this.system.renderer.renderMode){case rs.Billboard:return ae.RenderMode.BillBoard;case rs.Stretch:return ae.RenderMode.StretchedBillBoard;case rs.HorizontalBillboard:return ae.RenderMode.HorizontalBillBoard;case rs.VerticalBillboard:return ae.RenderMode.VerticalBillBoard;case rs.Mesh:return ae.RenderMode.Mesh}return ae.RenderMode.BillBoard}rendererEmitterSettings={startLength:new ae.ConstantValue(220),followLocalOrigin:!1};get speedFactor(){let e=this.system.main.simulationSpeed;return this.system.renderer?.renderMode===rs.Stretch&&(e*=this.system.renderer.velocityScale??1),e}flatWhiteTexture;clonedTexture={original:void 0,clone:void 0};get texture(){const e=this.material;if(e&&e.map){const t=e.map;if(this.clonedTexture.original!==t||!this.clonedTexture.clone){const i=t.clone();i.premultiplyAlpha=!1,i.colorSpace=c.LinearSRGBColorSpace,this.clonedTexture.original=t,this.clonedTexture.clone=i}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=ug(new te(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new cR(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===Mc.World}}class vR{burstParticleIndex=0;burstParticleCount=0;isBursting=!1;travelDistance=0;previousWorldPos;burstIndex=0;burstWaveIndex=0;time=0;waitEmiting=0}const jt=class Rd extends R{play(e=!1){e&&S.foreachComponent(this.gameObject,t=>{t instanceof Rd&&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 Rd&&t!==this&&t.pause(!1)},!0),this._isPlaying=!1}stop(e=!0,t=!1){e&&S.foreachComponent(this.gameObject,i=>{i instanceof Rd&&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 vR),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===Mc.World}get localspace(){return this.main.simulationSpace===Mc.Local}__worldQuaternion=new c.Quaternion;get worldQuaternion(){return this.__worldQuaternion}_worldQuaternionInverted=new c.Quaternion;get worldQuaternionInverted(){return this._worldQuaternionInverted}_worldScale=new c.Vector3;get worldScale(){return this._worldScale}_worldPositionFrame=-1;_worldPos=new c.Vector3;get worldPos(){return this._worldPositionFrame!==this.context.time.frame&&(this._worldPositionFrame=this.context.time.frame,Y(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}addBehaviour(e){return this._particleSystem?(e instanceof ko&&(e.system=this),Js&&console.debug("Add custom ParticleSystem Behaviour",e),this._particleSystem.addBehavior(e),!0):!1}removeBehaviour(e){if(!this._particleSystem)return!1;const t=this._particleSystem.behaviors,i=t.indexOf(e);return i!==-1&&((A()||Js)&&console.debug("Remove custom ParticleSystem Behaviour",i,e),t.splice(i,1)),!0}removeAllBehaviours(){return this._particleSystem?(this._particleSystem.behaviors.length=0,!0):!1}get behaviours(){return this._particleSystem?this._particleSystem.behaviors:null}get particleSystem(){return this._particleSystem??null}_renderer;_batchSystem;_particleSystem;_interface;_container;_time=0;_isPlaying=!0;_isUsedAsSubsystem=!1;_didPreWarm=!1;set bursts(e){for(let t=0;t<e.length;t++){const i=e[t];if(!(i instanceof ou)){const n=new ou;ja(n,i),e[t]=n}}this._bursts=e}_bursts;set subEmitterSystems(e){for(let t=0;t<e.length;t++){const i=e[t];if(!(i instanceof ru)){const n=new ru;ja(n,i),e[t]=n}}Js&&e.length>0&&console.log("SubEmitters: ",e,this),this._subEmitterSystems=e}_subEmitterSystems;onAfterDeserialize(e){if(this._subEmitterSystems&&Array.isArray(this._subEmitterSystems))for(const t of this._subEmitterSystems)t._deserialize(this.context,this.gameObject)}awake(){if(this._worldPositionFrame=-1,this._renderer=this.gameObject.getComponent(Yi),!this.main)throw new Error("Not Supported: ParticleSystem needs a serialized MainModule. Creating new particle systems at runtime is currently not supported.");this._container=new c.Object3D,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new ae.BatchedParticleRenderer,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new bR(this),this._particleSystem=new ae.ParticleSystem(this._interface),this._particleSystem.addBehavior(new mR(this)),this._particleSystem.addBehavior(new _R(this)),this._particleSystem.addBehavior(new uR(this)),this._particleSystem.addBehavior(new fR(this)),this._particleSystem.addBehavior(new yR(this)),this._particleSystem.addBehavior(new gR(this)),this._batchSystem.addSystem(this._particleSystem);const e=this._particleSystem.emitter;this.context.scene.add(e),this.inheritVelocity.system&&this.inheritVelocity.system!==this&&(this.inheritVelocity=this.inheritVelocity.clone()),this.inheritVelocity.awake(this),Js&&(console.log(this),this.gameObject.add(new c.AxesHelper(1)))}start(){this.addSubParticleSystems(),this.updateLayers(),this.renderer.particleMesh instanceof c.Mesh&&this._interface.renderMode==ae.RenderMode.Mesh&&re.NEEDLE_progressive.assignMeshLOD(this.renderer.particleMesh,0).then(e=>{e&&this.particleSystem&&this._interface.renderMode==ae.RenderMode.Mesh&&(this.particleSystem.instancingGeometry=e)})}onDestroy(){this._container?.removeFromParent(),this._batchSystem?.removeFromParent(),this._particleSystem?.emitter.removeFromParent(),this._particleSystem?.dispose()}onEnable(){this.main&&(this.inheritVelocity&&(this.inheritVelocity.system=this),this._batchSystem&&(this._batchSystem.visible=!0),this.playOnAwake&&this.play(),this._isPlaying=this.playOnAwake)}onDisable(){this._batchSystem&&(this._batchSystem.visible=!1)}onBeforeRender(){this.main&&(this._didPreWarm===!1&&this.main?.prewarm===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){if(!this.emission?.enabled||this.emission.rateOverTime.getMax()<=0)return;const t=1/60,i=this.main.duration,n=this.main.startLifetime.getMax(),r=Math.min(Math.max(i,n)/Math.max(.01,this.main.simulationSpeed),1e3),a=Math.ceil(r/t),l=Date.now();Js&&console.log(`Particles ${this.name} - Prewarm for ${a} frames (${r} sec). Duration: ${i}, Lifetime: ${n}`);for(let h=0;h<a&&!(this.currentParticles>=this.maxParticles);h++){const d=Date.now()-l;if(d>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${d}`);break}this.onUpdate(),this.onSimulate(t)}}_lastBatchesCount=-1;onSimulate(e){if(this._batchSystem){let t=this.context.time.frameCount%60===0;this._lastBatchesCount!==this._batchSystem.batches.length&&(this._lastBatchesCount=this._batchSystem.batches.length,t=!0),t&&this.updateLayers(),this._batchSystem.update(e)}this._time+=e,this._time>this.duration&&(this._time=0)}updateLayers(){if(this._batchSystem)for(let e=0;e<this._batchSystem.batches.length;e++){const t=this._batchSystem.batches[e];t.layers.disableAll();const i=this.layer;t.layers.mask=1<<i}}onUpdate(){if(this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const e=this.context.mainCamera;if(e){const n=je(e);this._cameraScale=n.x}const t=!this.worldspace,i=this.gameObject;if(pe(i,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),je(this.gameObject,this._worldScale),t&&this._container&&this.gameObject?.parent){const n=ax(this,_m);this._container.matrix.makeScale(n.x,n.y,n.z),this._container.matrix.makeRotationFromQuaternion(this.__worldQuaternion),this._container.matrix.setPosition(this.worldPos),this._container.matrix.scale(this.gameObject.scale)}this.emission.system=this,this._interface.update(),this.shape.onUpdate(this,this.context,this.main.simulationSpace,this.gameObject),this.noise.update(this.context),this.inheritVelocity?.update(this.context),this.velocityOverLifetime.update(this)}addSubParticleSystems(){if(this._subEmitterSystems&&this._particleSystem)for(const e of this._subEmitterSystems){e.particleSystem&&(e.particleSystem.__internalAwake?e.particleSystem.__internalAwake():A()&&console.warn("SubParticleSystem serialization issue(?)",e.particleSystem,e));const t=e.particleSystem?._particleSystem;if(t){e.particleSystem._isUsedAsSubsystem=!0;const i=new Sy(this,this._particleSystem,e.particleSystem,t);i.emitterType=e.type,i.emitterProbability=e.emitProbability,this._particleSystem.addBehavior(i)}else Js&&console.warn("Could not add SubParticleSystem",e,this)}}};Le([f(Qu)],jt.prototype,"colorOverLifetime");Le([f(Lt)],jt.prototype,"main");Le([f(Es)],jt.prototype,"emission");Le([f(jr)],jt.prototype,"sizeOverLifetime");Le([f(wy)],jt.prototype,"shape");Le([f(me)],jt.prototype,"noise");Le([f(De)],jt.prototype,"trails");Le([f(Fe)],jt.prototype,"velocityOverLifetime");Le([f(nt)],jt.prototype,"limitVelocityOverLifetime");Le([f(xy)],jt.prototype,"inheritVelocity");Le([f(ol)],jt.prototype,"colorBySpeed");Le([f(It)],jt.prototype,"textureSheetAnimation");Le([f(_n)],jt.prototype,"rotationOverLifetime");Le([f(Qi)],jt.prototype,"rotationBySpeed");Le([f(di)],jt.prototype,"sizeBySpeed");let kc=jt;class ru{particleSystem;emitProbability=1;properties;type;_deserialize(e,t){const i=this.particleSystem;if(i instanceof kc)return;let n="";i&&typeof i.guid=="string"&&(n=i.guid,this.particleSystem=S.findByGuid(n,t)),Js&&!(this.particleSystem instanceof kc)&&console.warn("Could not find particle system for sub emitter",n,t,this)}}function ax(s,e){if(e.set(1,1,1),s.gameObject.parent&&s.localspace)switch(s.main.scalingMode){case gm.Local:e=je(s.gameObject.parent,e),e.x=1/e.x,e.y=1/e.y,e.z=1/e.z;break;default:if(!s.unsupported_scaling_mode){s.unsupported_scaling_mode=!0;const t="ParticleSystem scale mode "+gm[s.main.scalingMode]+" is not supported";A()&&fe(t),console.warn(t,s.name,s)}e=je(s.gameObject,e);break}return e}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 rl extends R{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))})}}Py([f()],rl.prototype,"strength");Py([f()],rl.prototype,"radius");Py([f($e)],rl.prototype,"targets");class Ua extends R{_didAssignPlayerColor=!1;onEnable(){this.context.connection.beginListen(K.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(K.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield dg(.2),!this.tryAssignColor()););}tryAssignColor=()=>{const e=S.getComponentInParent(this.gameObject,zi);if(e&&e.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(e.owner),!0;const t=S.getComponentInParent(this.gameObject,Oe);return t?.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(t.connectionId),!0):!1};assignUserColor(e){const t=Ua.hashCode(e),i=Ua.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){const n=this.gameObject;this.assignColor(i,e,n)}else if(this.gameObject.children)for(const n of this.gameObject.children){const o=n;o.material&&o.material.color&&this.assignColor(i,e,o)}}assignColor(e,t,i){let n=i.material;n&&(n._playerMaterial!==t&&(n=n.clone(),n._playerMaterial=t,i.material=n),n.color=e)}static hashCode(e){var t=0,i,n;if(e.length===0)return t;for(i=0;i<e.length;i++)n=e.charCodeAt(i),t=(t<<5)-t+n,t|=0;return t}static colorFromHashCode(e){const t=(e&16711680)>>16,i=(e&65280)>>8,n=e&255;return new c.Color(t/255,i/255,n/255)}}const Yl=x("debugpost");let bm=null;function xR(s){bm=s}function lx(s){let e=s.gameObject;for(;e;){for(const t of vu(e))if(t.isPostProcessingManager===!0)return t;e=e.parent}return null}function SR(s){let e=lx(s);if(!e)if(bm){Yl&&console.warn("Adding postprocessing manager to the scene.");const t=s.scene;e=cn(t,bm)}else A()&&console.warn("No post processing manager found");return e}const et={AT_START:-1e4,NormalPass:0,DepthDownsamplingPass:10,SSAO:20,SMAA:30,TiltShift:40,DepthOfField:50,ChromaticAberration:60,Bloom:70,Vignette:80,Pixelation:90,ToneMapping:100,HueSaturation:110,BrightnessContrast:120,Sharpening:130,AT_END:1e4};let Ge=null;function CR(s){Yl==="verbose"&&console.debug("Before ordering effects",[...s]),Ge||(Ge=new Map,Ge.set(T.POSTPROCESSING.MODULE.NormalPass,et.NormalPass),Ge.set(T.POSTPROCESSING.MODULE.DepthDownsamplingPass,et.DepthDownsamplingPass),Ge.set(T.POSTPROCESSING.MODULE.SMAAEffect,et.SMAA),Ge.set(T.POSTPROCESSING.MODULE.SSAOEffect,et.SSAO),Ge.set(T.POSTPROCESSING_AO.MODULE.N8AOPostPass,et.SSAO),Ge.set(T.POSTPROCESSING_AO.MODULE.N8AOPass,et.SSAO),Ge.set(T.POSTPROCESSING.MODULE.TiltShiftEffect,et.TiltShift),Ge.set(T.POSTPROCESSING.MODULE.DepthOfFieldEffect,et.DepthOfField),Ge.set(T.POSTPROCESSING.MODULE.ChromaticAberrationEffect,et.ChromaticAberration),Ge.set(T.POSTPROCESSING.MODULE.BloomEffect,et.Bloom),Ge.set(T.POSTPROCESSING.MODULE.SelectiveBloomEffect,et.Bloom),Ge.set(T.POSTPROCESSING.MODULE.VignetteEffect,et.Vignette),Ge.set(T.POSTPROCESSING.MODULE.PixelationEffect,et.Pixelation),Ge.set(T.POSTPROCESSING.MODULE.ToneMappingEffect,et.ToneMapping),Ge.set(T.POSTPROCESSING.MODULE.HueSaturationEffect,et.HueSaturation),Ge.set(T.POSTPROCESSING.MODULE.BrightnessContrastEffect,et.BrightnessContrast)),s.sort((e,t)=>{const i=typeof e.priority=="number"?e.priority:Ge.get(e.effect.constructor)??Number.NEGATIVE_INFINITY,n=typeof t.priority=="number"?t.priority:Ge.get(t.effect.constructor)??Number.NEGATIVE_INFINITY;return i===Number.NEGATIVE_INFINITY?(Yl&&console.warn("Unknown effect found: ",e.constructor.name,e),1):n===Number.NEGATIVE_INFINITY?(Yl&&console.warn("Unknown effect found: ",t.constructor.name,t),-1):i-n}),Yl==="verbose"&&console.debug("After ordering effects",[...s])}var PR=Object.defineProperty,OR=Object.getOwnPropertyDescriptor,cx=(s,e,t,i)=>{for(var n=OR(e,t),o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&PR(e,t,n),n};const MR=x("debugpost");class z{isVolumeParameter=!0;constructor(e){e!==void 0&&this.initialize(e)}_isInitialized=!1;get isInitialized(){return this._isInitialized}initialize(e){e!==void 0&&(this._value=e,this._defaultValue=e,this._valueRaw=e,this._isInitialized=!0)}get overrideState(){return this._active}set overrideState(e){if(this._active===e)return;this._active=e;const t=e?this._valueRaw:this._defaultValue;this.processValue(t,!0)}_active=!0;get value(){return this._valueRaw}set value(e){this.isInitialized||this.initialize(e),this.processValue(e,!1)}_value;_valueRaw;set defaultValue(e){this._defaultValue=e}_defaultValue=void 0;__init(){this.processValue(this._valueRaw,!0)}valueProcessor;onValueChanged;processValue(e,t){if(e==null||!t&&this.testIfValueChanged(e)===!1)return;const i=this._value;MR&&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}}cx([f()],z.prototype,"overrideState");cx([f()],z.prototype,"value");class kR extends Hi{constructor(){super([z])}onSerialize(e,t){}onDeserialize(e,t){const i=t.target,n=t.path;let o;if(i&&n&&(o=i[n]),(typeof o!="object"||typeof o=="object"&&o.isVolumeParameter!==!0)&&(o=new z),typeof e=="object"&&"value"in e){const r=e.value;o.initialize(r),o.overrideState=e.overrideState}else o.value=e;return o}}new kR;var RR=Object.defineProperty,ER=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&RR(e,t,n),n};const mp=x("debugpost");class Xe extends R{get isPostProcessingEffect(){return!0}order=void 0;constructor(e=void 0){if(super(),e)for(const t of Object.keys(e)){const i=e[t],n=this[t];n instanceof z?n.initialize(i):n!==void 0&&(this[t]=i)}}active=!0;_manager=null;onEnable(){super.onEnable(),mp&&console.warn("Enable",this.constructor.name+(this.__internalDidAwakeAndStart?"":" (awake)")),this.__internalDidAwakeAndStart&&(this.active=!0),this.onEffectEnabled()}onDisable(){super.onDisable(),mp&&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=SR(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(){mp&&console.warn("DISPOSE",this),this._result&&(Array.isArray(this._result)?this._result.forEach(e=>e.dispose()):this._result.dispose()),this._result=void 0}initParameters(){const e=Object.keys(this);for(const t of e){const i=this[t];i instanceof z&&i.__init()}}onEditorModification(e){const t=e.propertyName;if(this[t]instanceof z){const i=e.value;return this[t].value=i,!0}}}ER([f()],Xe.prototype,"active");var TR=Object.defineProperty,AR=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&TR(e,t,n),n};const DR=x("debugpost"),vm={};function Ki(s,e){vm[s]=e}function LR(s){return s.__type in vm?vm[s.__type]:(DR&&s.__type&&console.warn("Unknown postprocessing type",s.__type,s),Xe)}class Yu{components=[];__init(e){this.components?.forEach(t=>{t.gameObject===void 0&&e.gameObject.addComponent(t),t.init()})}addEffect(e){this.components.push(e)}removeEffect(e){const t=this.components.indexOf(e);t>=0&&this.components.splice(t,1)}}AR([Be([s=>LR(s),Xe])],Yu.prototype,"components");var IR=Object.defineProperty,jR=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&IR(e,t,n),n};const BR=x("debugpost");class uh extends Xe{get typeName(){return"Antialiasing"}preset=new z(2);onCreateEffect(){const e=new T.POSTPROCESSING.MODULE.SMAAEffect({preset:this.preset?.value??T.POSTPROCESSING.MODULE.SMAAPreset.HIGH,edgeDetectionMode:T.POSTPROCESSING.MODULE.EdgeDetectionMode.LUMA});return this.preset.onValueChanged=t=>{BR&&console.log("Antialiasing preset changed to",t),e.applyPreset(t)},e}}jR([f(z)],uh.prototype,"preset");Ki("Antialiasing",uh);var FR=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&&FR(e,t,n),n};const Ku=class hx extends Xe{static useSelectiveBloom=!1;get typeName(){return"Bloom"}threshold=new z(.9);intensity=new z(1);scatter=new z(.7);selectiveBloom;init(){this.threshold.valueProcessor=e=>e,this.intensity.valueProcessor=e=>e,this.scatter.valueProcessor=e=>e}onCreateEffect(){let e;if(this.selectiveBloom==null&&(this.selectiveBloom=hx.useSelectiveBloom),this.selectiveBloom){const t=e=new T.POSTPROCESSING.MODULE.SelectiveBloomEffect(this.context.scene,this.context.mainCamera,{blendFunction:T.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});t.inverted=!0}else e=new T.POSTPROCESSING.MODULE.BloomEffect({blendFunction:T.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});return this.intensity.onValueChanged=t=>{e.intensity=t},this.threshold.onValueChanged=t=>{e.luminanceMaterial.threshold=Math.pow(t,2.2)},this.scatter.onValueChanged=t=>{e.luminancePass.enabled=!0,e.luminanceMaterial.smoothing=t,e.mipmapBlurPass&&(e.mipmapBlurPass.radius=c.MathUtils.lerp(.1,.9,t))},e}};Oy([f(z)],Ku.prototype,"threshold");Oy([f(z)],Ku.prototype,"intensity");Oy([f(z)],Ku.prototype,"scatter");let Zu=Ku;Ki("Bloom",Zu);var UR=Object.defineProperty,zR=(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&&UR(e,t,n),n};class fh extends Xe{get typeName(){return"ChromaticAberration"}intensity=new z(0);onCreateEffect(){const e=new T.POSTPROCESSING.MODULE.ChromaticAberrationEffect;return e.offset=new c.Vector2(0,0),e.radialModulation=!0,e.modulationOffset=.15,this.intensity.valueProcessor=t=>t*.02,this.intensity.onValueChanged=t=>{e.offset.x=-t,e.offset.y=t},e}}zR([f(z)],fh.prototype,"intensity");Ki("ChromaticAberration",fh);var Kl=(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))(Kl||{});const Bb=new Map;function gp(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 Bb.has(s)||(Bb.set(s,!0),console.warn("[Postprocessing] Unknown tone mapping mode",s)),c.NeutralToneMapping}}function NR(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 Ed(s){switch(s){case c.LinearToneMapping:return T.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR;case c.ACESFilmicToneMapping:return T.POSTPROCESSING.MODULE.ToneMappingMode.ACES_FILMIC;case c.AgXToneMapping:return T.POSTPROCESSING.MODULE.ToneMappingMode.AGX;case c.NeutralToneMapping:return T.POSTPROCESSING.MODULE.ToneMappingMode.NEUTRAL;case c.ReinhardToneMapping:return T.POSTPROCESSING.MODULE.ToneMappingMode.REINHARD;default:return T.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR}}var VR=Object.defineProperty,dx=(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&&VR(e,t,n),n};const yp=x("debugpost");class go extends Xe{get typeName(){return"ToneMapping"}mode=new z(void 0);exposure=new z(1);setMode(e){const t=Kl[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=lx(this);e&&super.onEffectEnabled(e)}_tonemappingEffect=null;onCreateEffect(){if(this.mode.isInitialized==!1){const i=NR(this.context.renderer.toneMapping);yp&&console.log("[PostProcessing] Initializing ToneMapping mode to renderer.toneMapping",this.context.renderer.toneMapping+" → "+i),this.mode.initialize(i)}this._tonemappingEffect?.dispose();const e=gp(this.mode.value),t=this._tonemappingEffect=new T.POSTPROCESSING.MODULE.ToneMappingEffect({mode:Ed(e)});return this.mode.onValueChanged=i=>{if(typeof i=="string")i=G0(i),t.mode=Ed(i);else{const n=gp(i);t.mode=Ed(n)}t.name="ToneMapping ("+Kl[i]+")",yp&&console.log("[PostProcessing] ToneMapping mode changed to",Kl[i],e,t.mode)},yp&&console.log("[PostProcessing] Use ToneMapping",Kl[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=gp(this.mode.value)),this.exposure.overrideState&&this.exposure.value!==void 0)){const e=Math.max(0,this.exposure.value);this.context.renderer.toneMappingExposure=e}}}dx([f(z)],go.prototype,"mode");dx([f(z)],go.prototype,"exposure");Ki("Tonemapping",go);var $R=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&&$R(e,t,n),n};class Ro extends Xe{get typeName(){return"ColorAdjustments"}remap=!0;postExposure=new z(1);contrast=new z(0);hueShift=new z(0);saturation=new z(0);init(){this.postExposure.valueProcessor=e=>(this.remap&&(e=Math.pow(2,e)),e),this.contrast.valueProcessor=e=>{if(!this.remap)return e;let t=1;return e>0?t=200:e<0&&(t=100),e/t},this.contrast.defaultValue=0,this.hueShift.valueProcessor=e=>this.remap?Math.PI*e/180:e,this.hueShift.defaultValue=0,this.saturation.valueProcessor=e=>this.remap?e<0?e/100:e/(100*Math.PI):e,this.saturation.defaultValue=0}onCreateEffect(){const e=[];let t=this.postprocessingContext?.components.find(o=>o instanceof go);t||(t=new go,this.postprocessingContext?.components.push(t)),this.postExposure.onValueChanged=o=>{this.postExposure.overrideState&&t?t.exposure.value=o:console.warn("[PostProcessing] PostExposure is set to override but no ToneMappingEffect found in the postprocessing stack. Please add a ToneMappingEffect to your postprocessing stack to use PostExposure.")};const i=new T.POSTPROCESSING.MODULE.BrightnessContrastEffect;this.contrast.onValueChanged=o=>i.contrast=o;const n=new T.POSTPROCESSING.MODULE.HueSaturationEffect;return this.hueShift.onValueChanged=o=>n.hue=o,this.saturation.onValueChanged=o=>n.saturation=o,e.push(i),e.push(n),e}}Ju([f(z)],Ro.prototype,"postExposure");Ju([f(z)],Ro.prototype,"contrast");Ju([f(z)],Ro.prototype,"hueShift");Ju([f(z)],Ro.prototype,"saturation");Ki("ColorAdjustments",Ro);var WR=Object.defineProperty,Br=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&WR(e,t,n),n};const GR=x("debugpost");class bn extends Xe{get typeName(){return"DepthOfField"}mode;focusDistance=new z(1);focalLength=new z(.2);aperture=new z(20);gaussianMaxRadius=new z;resolutionScale=new z(1/window.devicePixelRatio);bokehScale=new z;init(){this.focalLength.valueProcessor=t=>{const i=t/300;return I.lerp(2,.01,i)};const e=20;this.aperture.valueProcessor=t=>{const i=1-t/32;return I.lerp(1,e,i)}}onCreateEffect(){if(this.mode===0){GR&&console.warn("DepthOfField: Mode is set to Off");return}const e=new T.POSTPROCESSING.MODULE.DepthOfFieldEffect(this.context.mainCamera,{worldFocusRange:.2,focalLength:1,bokehScale:20,resolutionScale:this.resolutionScale.value});return this.focusDistance.onValueChanged=t=>{e.cocMaterial.worldFocusDistance=t},this.focalLength.onValueChanged=t=>e.cocMaterial.worldFocusRange=t,this.aperture.onValueChanged=t=>e.bokehScale=t,this.resolutionScale&&(this.resolutionScale.onValueChanged=t=>e.resolution.scale=t),[e]}unapply(){}}Br([f()],bn.prototype,"mode");Br([f(z)],bn.prototype,"focusDistance");Br([f(z)],bn.prototype,"focalLength");Br([f(z)],bn.prototype,"aperture");Br([f(z)],bn.prototype,"gaussianMaxRadius");Br([f(z)],bn.prototype,"resolutionScale");Br([f(z)],bn.prototype,"bokehScale");Ki("DepthOfField",bn);class Rc extends Xe{effect;constructor(e){super(),this.effect=e}get typeName(){return this.effect.constructor.name}onCreateEffect(){return this.effect}}var HR=Object.defineProperty,qR=(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};class ph extends Xe{get typeName(){return"PixelationEffect"}granularity=new z(10);onCreateEffect(){const e=new T.POSTPROCESSING.MODULE.PixelationEffect;return this.granularity.onValueChanged=t=>{e.granularity=t},e}}qR([f(z)],ph.prototype,"granularity");Ki("PixelationEffect",ph);var XR=Object.defineProperty,mh=(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&&XR(e,t,n),n};class Ts extends Xe{get typeName(){return"ScreenSpaceAmbientOcclusion"}intensity=new z(2);falloff=new z(1);samples=new z(9);color=new z(new c.Color(0,0,0));luminanceInfluence=new z(.7);onBeforeRender(){if(this._ssao&&this.context.mainCamera instanceof c.PerspectiveCamera){const e=this.context.mainCamera.far-this.context.mainCamera.near;this._ssao.ssaoMaterial.worldDistanceFalloff=e*.01,this._ssao.ssaoMaterial.worldDistanceThreshold=this.context.mainCamera.far}}_ssao;onCreateEffect(){const e=this.context.mainCamera,t=new T.POSTPROCESSING.MODULE.NormalPass(this.context.scene,e),i=new T.POSTPROCESSING.MODULE.DepthDownsamplingPass({normalBuffer:t.texture,resolutionScale:.5}),n=this._ssao=new T.POSTPROCESSING.MODULE.SSAOEffect(e,t.texture,{normalDepthBuffer:i.texture,worldDistanceThreshold:1,worldDistanceFalloff:1,worldProximityThreshold:.1,worldProximityFalloff:2,intensity:1,blendFunction:T.POSTPROCESSING.MODULE.BlendFunction.MULTIPLY,luminanceInfluence:.5});this.intensity.onValueChanged=r=>{n.intensity=r},this.falloff.onValueChanged=r=>{n.ssaoMaterial.radius=r*.1},this.samples.onValueChanged=r=>{n.ssaoMaterial.samples=r},this.color.onValueChanged=r=>{n.color||(n.color=new c.Color),n.color.copy(r)},this.luminanceInfluence.onValueChanged=r=>{n.luminanceInfluence=r};const o=new Array;return o.push(t),o.push(i),o.push(n),o}}mh([f(z)],Ts.prototype,"intensity");mh([f(z)],Ts.prototype,"falloff");mh([f(z)],Ts.prototype,"samples");mh([f(z)],Ts.prototype,"color");mh([f(z)],Ts.prototype,"luminanceInfluence");Ki("ScreenSpaceAmbientOcclusion",Ts);var QR=Object.defineProperty,Fr=(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 YR=x("debugN8AO");var wm=(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))(wm||{});class vn extends Xe{get typeName(){return"ScreenSpaceAmbientOcclusionN8"}get pass(){return this._ssao}gammaCorrection=!0;aoRadius=new z(1);falloff=new z(1);intensity=new z(1);color=new z(new c.Color(0,0,0));screenspaceRadius=!1;quality=2;_ssao;onValidate(){this._ssao&&(this._ssao.setQualityMode(wm[this.quality]),this._ssao.configuration.gammaCorrection=this.gammaCorrection,this._ssao.configuration.screenSpaceRadius=this.screenspaceRadius)}onCreateEffect(){const e=this.context.mainCamera,t=this.context.domWidth,i=this.context.domHeight,n=this._ssao=new T.POSTPROCESSING_AO.MODULE.N8AOPostPass(this.context.scene,e,t,i);n.name="SSAO_N8";const o=wm[this.quality];if(n.setQualityMode(o),n.configuration.transparencyAware=!1,n.configuration.halfRes=window.devicePixelRatio>1,n.effectCompositerQuad?.material){const a=n.effectCompositerQuad.material;a.fragmentShader=a.fragmentShader.replace(`if (depth == 1.0) {
|
|
1312
|
-
texel = vec4(0.0, 0.0, 0.0, 1.0);`,`if (depth == 1.0) {
|
|
1313
|
-
gl_FragColor = sceneTexel;
|
|
1314
|
-
return;`),a.needsUpdate=!0}const r=new c.WebGLRenderTarget(t,i);return n.configuration.beautyRenderTarget=r,n.configuration.autoRenderBeauty=!1,n.configuration.gammaCorrection=this.gammaCorrection,n.configuration.screenSpaceRadius=this.screenspaceRadius,YR&&(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}}Fr([St(),f()],vn.prototype,"gammaCorrection");Fr([f(z)],vn.prototype,"aoRadius");Fr([f(z)],vn.prototype,"falloff");Fr([f(z)],vn.prototype,"intensity");Fr([f(z)],vn.prototype,"color");Fr([St(),f()],vn.prototype,"screenspaceRadius");Fr([St(),f()],vn.prototype,"quality");Ki("ScreenSpaceAmbientOcclusionN8",vn);var KR=Object.defineProperty,ZR=Object.getOwnPropertyDescriptor,ux=(s,e,t,i)=>{for(var n=ZR(e,t),o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&KR(e,t,n),n};class gh extends Xe{get typeName(){return"Sharpening"}order=et.Sharpening;_effect;onCreateEffect(){return this._effect??=new(JR()),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}ux([f()],gh.prototype,"amount");ux([f()],gh.prototype,"radius");function JR(){const s=`
|
|
1315
|
-
void mainSupport() {
|
|
1316
|
-
vUv = uv;
|
|
1317
|
-
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
|
|
1318
|
-
}
|
|
1319
|
-
`,e=`
|
|
1320
|
-
uniform sampler2D tDiffuse;
|
|
1321
|
-
uniform float amount;
|
|
1322
|
-
uniform float radius;
|
|
1323
|
-
|
|
1324
|
-
void mainImage(const in vec4 inputColor, const in vec2 uv, out vec4 outputColor) {
|
|
1325
|
-
float tx = 1.0 / resolution.x;
|
|
1326
|
-
float ty = 1.0 / resolution.y;
|
|
1327
|
-
vec2 texelSize = vec2(tx, ty);
|
|
1328
|
-
|
|
1329
|
-
vec4 blurred = vec4(0.0);
|
|
1330
|
-
float total = 0.0;
|
|
1331
|
-
|
|
1332
|
-
for (float x = -radius; x <= radius; x++) {
|
|
1333
|
-
for (float y = -radius; y <= radius; y++) {
|
|
1334
|
-
vec2 offset = vec2(x, y) * texelSize;
|
|
1335
|
-
vec4 diffuse = texture2D(tDiffuse, uv + offset);
|
|
1336
|
-
float weight = exp(-length(offset) * amount);
|
|
1337
|
-
blurred += diffuse * weight;
|
|
1338
|
-
total += weight;
|
|
1339
|
-
}
|
|
1340
|
-
}
|
|
1341
|
-
|
|
1342
|
-
if (total > 0.0) {
|
|
1343
|
-
blurred /= total;
|
|
1344
|
-
}
|
|
1345
|
-
|
|
1346
|
-
// Calculate the sharpened color using inputColor
|
|
1347
|
-
vec4 sharp = inputColor + clamp(inputColor - blurred, 0.0, 1.0) * amount;
|
|
1348
|
-
// Keep original alpha
|
|
1349
|
-
sharp.a = inputColor.a;
|
|
1350
|
-
|
|
1351
|
-
// Ensure the sharp color does not go below 0 or above 1
|
|
1352
|
-
// This means: sharpening must happen AFTER tonemapping.
|
|
1353
|
-
sharp = clamp(sharp, 0.0, 1.0);
|
|
1354
|
-
|
|
1355
|
-
outputColor = sharp;
|
|
1356
|
-
}
|
|
1357
|
-
|
|
1358
|
-
`;class t extends T.POSTPROCESSING.MODULE.Effect{constructor(){super("Sharpening",e,{vertexShader:s,blendFunction:T.POSTPROCESSING.MODULE.BlendFunction.NORMAL,uniforms:new Map([["amount",new c.Uniform$1(1)],["radius",new c.Uniform$1(1)]]),attributes:Vx.EffectAttribute.CONVOLUTION})}}return t}var eE=Object.defineProperty,al=(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 Zn extends Xe{get typeName(){return"TiltShiftEffect"}offset=new z(0);rotation=new z(0);focusArea=new z(.4);feather=new z(.3);kernelSize=new z(2);resolutionScale=new z(1/window.devicePixelRatio);init(){this.offset.defaultValue=0,this.rotation.defaultValue=0,this.focusArea.defaultValue=.4,this.feather.defaultValue=.3,this.kernelSize.defaultValue=T.POSTPROCESSING.MODULE.KernelSize.MEDIUM,this.resolutionScale.defaultValue=1/window.devicePixelRatio}onCreateEffect(){const e=new T.POSTPROCESSING.MODULE.TiltShiftEffect({kernelSize:T.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}}al([f(z)],Zn.prototype,"offset");al([f(z)],Zn.prototype,"rotation");al([f(z)],Zn.prototype,"focusArea");al([f(z)],Zn.prototype,"feather");al([f(z)],Zn.prototype,"kernelSize");al([f(z)],Zn.prototype,"resolutionScale");Ki("TiltShiftEffect",Zn);var tE=Object.defineProperty,My=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&tE(e,t,n),n};class Ur extends Xe{get typeName(){return"Vignette"}color=new z({r:0,g:0,b:0,a:1});intensity=new z(0);center=new z({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 T.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}}My([f(z)],Ur.prototype,"color");My([f(z)],Ur.prototype,"intensity");My([f(z)],Ur.prototype,"center");Ki("Vignette",Ur);globalThis.NEEDLE_USE_POSTPROCESSING=globalThis.NEEDLE_USE_POSTPROCESSING!==void 0?globalThis.NEEDLE_USE_POSTPROCESSING:!0;const Qt=x("debugpost"),_p=Symbol("needle:postprocessing-handler"),Ol=Symbol("needle:previous-autoclear-state"),Ml=Symbol("needle:previous-tone-mapping");class za{_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(Qt&&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[_p]===this&&(delete t[_p],typeof t.renderer[Ol]=="boolean"&&(t.renderer.autoClear=t.renderer[Ol]),typeof t.renderer[Ml]=="number"&&(t.renderer.toneMapping=t.renderer[Ml])),this._composer?.removeAllPasses(),e&&this._composer?.dispose(),t.composer===this._composer&&(t.composer=null),this._adaptiveDPR_OverrideActive&&(this._adaptiveDPR_OverrideActive=!1,t.devicePixelRatio="auto"),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([T.POSTPROCESSING.load(),T.POSTPROCESSING_AO.load()]),e[_p]=this,Qt&&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 T.POSTPROCESSING.MODULE.Effect||d instanceof T.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:
|
|
1359
|
-
- 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&&fe("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}static _dprStep=.2;static _dprMinDelay=2;_adaptiveDPR_Enabled=!1;_adaptiveDPR_LastChangeTime=0;_adaptiveDPR_LastDecreaseTime=0;_adaptiveDPR_OverrideActive=!1;set adaptivePixelRatio(e){this._adaptiveDPR_Enabled=e,!e&&this._adaptiveDPR_OverrideActive&&(this._adaptiveDPR_OverrideActive=!1,this.context.devicePixelRatio="auto")}get adaptivePixelRatio(){return this._adaptiveDPR_Enabled}updateAdaptivePixelRatio(){if(!this._adaptiveDPR_Enabled||!this._isActive)return;if(!this._adaptiveDPR_OverrideActive&&this.context.devicePixelRatio!=="auto"){Qt&&console.debug(`[PostProcessing] Adaptive DPR skipped: devicePixelRatio is "${this.context.devicePixelRatio}", not "auto"`);return}const e=this.context.time,t=e.realtimeSinceStartup,i=t-this._adaptiveDPR_LastChangeTime;if(t<3||i<za._dprMinDelay)return;const n=Math.min(2,window.devicePixelRatio),o=this.context.renderer.getPixelRatio(),r=za._dprStep,a=1;if(e.smoothedFps<=50&&o>a){const l=Math.max(a,Math.round((o-r)*10)/10);l<o&&(this._adaptiveDPR_LastChangeTime=t,this._adaptiveDPR_LastDecreaseTime=t,!this._adaptiveDPR_OverrideActive&&(Qt||A())&&console.log(`[PostProcessing] Adaptively reducing pixel ratio for better performance (${o.toFixed(1)} → ${l}). Set context.devicePixelRatio to a fixed number to disable.`),this._adaptiveDPR_OverrideActive=!0,this.context.devicePixelRatio=l,Qt&&console.debug(`[PostProcessing] Reduced pixel ratio from ${o.toFixed(1)} to ${l}`))}else if(e.smoothedFps>=59&&i>1&&t-this._adaptiveDPR_LastDecreaseTime>10&&o<n){const l=Math.min(n,Math.round((o+r)*10)/10);l>o?(this._adaptiveDPR_LastChangeTime=t,this.context.devicePixelRatio=l,Qt&&console.debug(`[PostProcessing] Increased pixel ratio from ${o.toFixed(1)} to ${l}`)):this._adaptiveDPR_OverrideActive&&(this._adaptiveDPR_OverrideActive=!1,this._adaptiveDPR_LastChangeTime=t,this.context.devicePixelRatio="auto",Qt&&console.debug("[PostProcessing] Restored pixel ratio to auto"))}}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[Ol]=="boolean"&&(i.autoClear=i[Ol]),i[Ol]=i.autoClear,typeof i[Ml]=="number"&&(i.toneMapping=i[Ml]),i[Ml]=i.toneMapping,i.toneMapping!=c.NoToneMapping&&!this._effects.find(d=>d instanceof T.POSTPROCESSING.MODULE.ToneMappingEffect)){const d=new T.POSTPROCESSING.MODULE.ToneMappingEffect;d.name=`ToneMapping (${i.toneMapping})`,d.mode=Ed(i.toneMapping),this._effects.push({typeName:"ToneMapping",effect:d,priority:et.ToneMapping})}this._composer||(this._composer=new T.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 T.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,y)=>{if(u){if(this._multisampling<=0){l.call(a,d,u,p,m,y);return}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),Qt&&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,y),ho.blit(this._customInputBuffer.texture,u,{renderer:d,depthTexture:this._customInputBuffer.depthTexture,depthWrite:!0,depthTest:!0})}};try{CR(this._effects);let d=!1,u=null;for(let y=this._effects.length-1;y>=0;y--){const _=this._effects[y].effect;if(_ instanceof T.POSTPROCESSING.MODULE.ToneMappingEffect){if(d){Qt&&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(y,1);continue}u=_,d=!0}}const p=[];let m=!1;for(let y=0;y<this._effects.length;y++){const g=this._effects[y].effect;if(g instanceof T.POSTPROCESSING.MODULE.SMAAEffect?this._hasSmaaEffect=!0:g instanceof T.POSTPROCESSING.MODULE.NormalPass&&(this._anyPassHasNormal=!0),!(g instanceof T.POSTPROCESSING.MODULE.ToneMappingEffect&&u!==g))if(g instanceof T.POSTPROCESSING.MODULE.Effect){const w=g.getAttributes(),b=T.POSTPROCESSING.MODULE.EffectAttribute.CONVOLUTION;w&b&&(Qt&&console.log("[PostProcessing] Convolution effect: "+g.name),m&&(Qt&&console.log("[PostProcessing] → Merging effects ["+p.map(v=>v.name).join(", ")+"]"),this.createPassForMergeableEffects(p,r,o,n)),m=!0),p.push(g)}else g instanceof T.POSTPROCESSING.MODULE.Pass?(m=!1,this.createPassForMergeableEffects(p,r,o,n),g.renderToScreen=!1,r.addPass(g)):(m=!1,this.createPassForMergeableEffects(p,r,o,n),r.addPass(g))}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(),Qt&&console.log("[PostProcessing] Passes →",[...r.passes],`
|
|
1360
|
-
---------------------------------
|
|
1361
|
-
• `+r.passes.map(d=>d.name||d.constructor.name+"*").join(`
|
|
1362
|
-
• `)+`
|
|
1363
|
-
`),Qt&&this._onCreateEffectsDebug(this._composer,o)}createPassForMergeableEffects(e,t,i,n){if(e.length>0){const o=new T.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(Qt==="passes"){const i=new T.POSTPROCESSING.MODULE.DepthEffect({blendFunction:T.POSTPROCESSING.MODULE.BlendFunction.NORMAL,inverted:!0});i.name="Depth Effect";const n=new T.POSTPROCESSING.MODULE.EffectPass(t,i);if(n.name="Depth Effect Pass",n.enabled=!1,e.passes.push(n),this._passIndices!==null){const r=[e.passes[0]];this._passIndices.length>0&&r.push(...this._passIndices.filter(a=>a!==0).map(a=>e.passes[a]).filter(a=>a)),r.length>0&&console.log("[PostProcessing] Passes (selected) →",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 iE=Object.defineProperty,ky=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&iE(e,t,n),n};const Vo=x("debugpost");class zr extends R{get isPostProcessingManager(){return!0}get effects(){return this._activeEffects}get dirty(){return this._isDirty}set dirty(e){this._isDirty=e}sharedProfile;multisampling="auto";adaptiveResolution=!0;addEffect(e){let t=e;return t instanceof Xe||(t=new Rc(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 Xe?t=this._effects.indexOf(e):t=this._effects.findIndex(i=>i instanceof Rc&&i.effect===e),t!==-1)return this._effects.splice(t,1),this._isDirty=!0,e;if(e instanceof Xe){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(){Vo&&(console.log("PostprocessingManager Awake",this),console.log("Press P to toggle post processing"),window.addEventListener("keydown",e=>{e.key==="p"&&(this.enabled=!this.enabled,Se("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,(Vo||A())&&console.log(`[PostProcessing] multisampling is disabled because it's set to 'auto' on your PostprocessingManager/Volume component that also has an SMAA effect.
|
|
1364
|
-
|
|
1365
|
-
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),Vo&&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),Vo&&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._postprocessing.adaptivePixelRatio=this.adaptiveResolution,this._postprocessing.updateAdaptivePixelRatio(),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(Vo&&console.log(`Apply PostProcessing "${this.name||"unnamed"}"`),A()&&(this._lastApplyTime!==void 0&&Date.now()-this._lastApplyTime<100&&(this._rapidApplyCount++,this._rapidApplyCount===5&&console.warn("Detected rapid post processing modifications - this might be a bug",this)),this._lastApplyTime=Date.now()),this._isDirty=!1,this._activeEffects.length=0,this.sharedProfile?.components){const e=this.sharedProfile.components;for(const t of e)t.active&&t.enabled&&!this._activeEffects.includes(t)&&this._activeEffects.push(t)}for(const e of this._effects)e.active&&e.enabled&&!this._activeEffects.includes(e)&&this._activeEffects.push(e);this._activeEffects.length>0?(this._postprocessing||(this._postprocessing=new za(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)),Vo&&console.debug(`[PostProcessing] Set multisampling to ${this._postprocessing.multisampling} (Is Mobile: ${exports.DeviceUtilities.isMobileDevice()})`)):Vo&&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(!ld.has(i)){const r=new Array;ld.set(i,r);const a=Object.keys(o);for(const l of a)o[l]instanceof z&&r.push(l)}if(ld.has(i)){const r=n.toLowerCase(),a=ld.get(i);for(const l of a)if(l.toLowerCase()===r){const h=o[l];h instanceof z&&(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)}}ky([Be(Yu)],zr.prototype,"sharedProfile");ky([Be()],zr.prototype,"multisampling");ky([Be()],zr.prototype,"adaptiveResolution");const ld=new Map;xR(zr);async function Ry(s){const{NeedleEngineWebComponent:e}=await Promise.resolve().then(()=>XT);e.observedAttributes.includes(s)||e.observedAttributes.push(s)}var nE=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&&nE(e,t,n),n};const ot=x("debugsceneswitcher"),sE=x("sceneswitcher:clearscene"),Td="scene";Ry(Td);const Gs=Promise.resolve(!1);class We extends R{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 ne;sceneLoadingProgress=new ne;sceneLoaded=new ne;_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);ot&&console.log("SceneSwitcher",this)}async onEnable(){if(globalThis.addEventListener("popstate",this.onPopState),this.context.input.addEventListener(Pe.KeyDown,this.onInputKeyDown),this.context.input.addEventListener(Pe.PointerMove,this.onInputPointerMove),this.context.input.addEventListener(Pe.PointerUp,this.onInputPointerUp),this._engineElementOverserver||(this._engineElementOverserver=new MutationObserver(e=>{for(const t of e)if(t.type==="attributes"&&t.attributeName===Td){const i=this.context.domElement.getAttribute(Td);i!==null&&this.trySelectSceneFromValue(i)}})),this._engineElementOverserver.observe(this.context.domElement,{attributes:!0}),this._preloadScheduler||(this._preloadScheduler=new oE(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(Td);(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(Pe.KeyDown,this.onInputKeyDown),this.context.input.removeEventListener(Pe.PointerMove,this.onInputPointerMove),this.context.input.removeEventListener(Pe.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);ot&&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 Z(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(ot&&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=Z.getOrCreate(this.sourceId??"",e,this.context);return this.switchScene(n)}if(i)e=this.scenes?.indexOf(i);else return Gs}if(!this.scenes?.length)return Gs;if(e<0){if(this.clamp)return Gs;e=this.scenes.length-1}else if(e>=this.scenes.length){if(this.clamp)return Gs;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 Z)){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 Z(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){ot&&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&&bi(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{ot&&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(ot){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 ot&&console.warn("[SceneSwitcher] Adding loaded scene prevented:",e,n),!1;if(!e.asset)return ot&&console.warn("[SceneSwitcher] Failed loading scene:",e),!1;if(this._currentIndex===t){if(ot&&console.log("[SceneSwitcher] ADD",e.url),this._currentScene=e,sE){const a=this.context.mainCameraComponent?.gameObject||this.context.mainCamera;a?.removeFromParent();const l=this.gameObject.removeFromParent();bi(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=uo(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.CubeUVReflectionMapping&&(a.mapping=c.EquirectangularReflectionMapping),this.context.scene.background=a):ot&&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=Fb(e.url))),this.queryParameterName?.length)pc(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}ot&&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 Z)return t.preload()}return Gs}tryLoadFromQueryParam(){if(!this.queryParameterName?.length)return Gs;const e=x(this.queryParameterName);return typeof e=="boolean"?Gs: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:Fb(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 yi()&&console.warn('[SceneSwitcher] Can not find scene: "'+e+'"',this),Gs}_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)){ot&&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){ot&&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}}dt([f()],We.prototype,"autoLoadFirstScene");dt([f(Z)],We.prototype,"scenes");dt([f(Z)],We.prototype,"loadingScene");dt([f()],We.prototype,"queryParameterName");dt([f()],We.prototype,"useSceneName");dt([f()],We.prototype,"clamp");dt([f()],We.prototype,"useHistory");dt([f()],We.prototype,"useKeyboard");dt([f()],We.prototype,"useSwipe");dt([f()],We.prototype,"useSceneLighting");dt([f()],We.prototype,"useSceneBackground");dt([f()],We.prototype,"preloadNext");dt([f()],We.prototype,"preloadPrevious");dt([f()],We.prototype,"preloadConcurrent");dt([f()],We.prototype,"createMenuButtons");dt([f(ne)],We.prototype,"sceneLoadingStart");dt([f(ne)],We.prototype,"sceneLoadingProgress");dt([f(ne)],We.prototype,"sceneLoaded");function Fb(s){const t=s.split("/").pop()?.split(".").shift();return t?.length?t:s}class oE{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;ot&&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()&&(ot&&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];ot&&console.log("[SceneSwitcher] Schedule preload scene",{roomIndex:d,searchForward:l,lastRoom:t,currentIndex:this._switcher.currentIndex,tasks:this._loadTasks.length},u?.url),new rE(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 rE{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()&&(ot&&console.log("[SceneSwitcher] Preload start: "+this.asset.url,this.index),await this.asset.preload(),ot&&console.log("[SceneSwitcher] Preload finished: "+this.asset.url,this.index));const e=this.tasks.indexOf(this);e>=0&&this.tasks.splice(e,1)}}function aE(){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 lE(s){await aE(),s()}var cE=Object.defineProperty,hE=Object.getOwnPropertyDescriptor,Oi=(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&&cE(e,t,n),n};const He=x("debugvideo");var fx=(s=>(s[s.None=0]="None",s[s.AdjustHeight=1]="AdjustHeight",s[s.AdjustWidth=2]="AdjustWidth",s))(fx||{}),px=(s=>(s[s.VideoClip=0]="VideoClip",s[s.Url=1]="Url",s))(px||{}),mx=(s=>(s[s.CameraFarPlane=0]="CameraFarPlane",s[s.CameraNearPlane=1]="CameraNearPlane",s[s.RenderTexture=2]="RenderTexture",s[s.MaterialOverride=3]="MaterialOverride",s))(mx||{});class tt extends R{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=3;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&&A()&&console.warn("VideoAudioOutputMode.AudioSource is not yet implemented"),this._audioOutputMode=e,this.updateVideoElementSettings())}get audioOutputMode(){return this._audioOutputMode}_audioOutputMode=2;playInBackground=!0;_crossOrigin="anonymous";_videoElement=null;_videoTexture=null;_videoMaterial=null;_isPlaying=!1;wasPlaying=!1;preloadVideo(){He&&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,He&&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(){He&&console.log("VideoPlayer.onEnable",px[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(),lE(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[],x("videoscreenspace")&&window.addEventListener("keydown",e=>{e.key==="f"&&(this.screenspace=!this.screenspace)})}_playErrors=0;play(){if(this._videoElement||this.create(!1),!this._videoElement){He&&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}He&&console.log("Video Play()",this.clip,this._videoElement,this.time),this._videoElement.currentTime=this.time,this._videoElement.play().catch(e=>{this._playErrors++<10?console.error(e):this._playErrors===10&&console.error("Multiple errors playing video, further errors will be suppressed. Use 'debugvideo' param to see all errors."),He&&console.error("Error playing video",e,"CODE="+e.code,this.videoElement?.src,this),setTimeout(()=>{this._isPlaying&&!this.destroyed&&this.activeAndEnabled&&this.play()},1e3)}),He&&console.log("play",this._videoElement,this.time)}}stop(){this._isPlaying=!1,this.time=0,this._videoElement&&(this._videoElement.currentTime=0,this._videoElement.pause(),He&&console.log("STOP",this))}pause(){this.time=this._videoElement?.currentTime??0,this._isPlaying=!1,this._videoElement?.pause(),He&&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||(He&&console.warn("Create VideoElement",this),this._videoElement=this.createVideoElement(),this.context.domElement.shadowRoot.prepend(this._videoElement),this.updateVideoElementStyles()),typeof t=="string"?(He&&console.log("Set Video src",t),this._videoElement.src=t):(He&&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),He&&console.log("Video: handle playing done...",t,e),!0):(He&&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 dE(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),He&&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,mx[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)He&&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:He&&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=je(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):(He&&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=()=>{He&&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(),He&&console.log("HLS: loaded",this.clip))}}Oi([f()],tt.prototype,"playOnAwake",2);Oi([f()],tt.prototype,"aspectMode",2);Oi([f(URL)],tt.prototype,"clip",2);Oi([f()],tt.prototype,"source",2);Oi([f(URL)],tt.prototype,"url",1);Oi([f()],tt.prototype,"renderMode",2);Oi([f()],tt.prototype,"targetMaterialProperty",2);Oi([f(Ht)],tt.prototype,"targetMaterialRenderer",2);Oi([f(c.Texture)],tt.prototype,"targetTexture",2);Oi([f()],tt.prototype,"time",2);Oi([f()],tt.prototype,"playbackSpeed",1);Oi([f()],tt.prototype,"isLooping",1);Oi([f()],tt.prototype,"audioOutputMode",1);class dE{context;constructor(e){this.context=e,this._input=new uE(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=bo.createPrimitive(Va.Quad,{material:new fE(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 uE{_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 fE 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=`
|
|
1366
|
-
uniform sampler2D map;
|
|
1367
|
-
uniform float screenAspect;
|
|
1368
|
-
uniform vec4 offsetScale;
|
|
1369
|
-
varying vec2 vUv;
|
|
1370
|
-
|
|
1371
|
-
void main() {
|
|
1372
|
-
|
|
1373
|
-
gl_Position = vec4( position , 1.0 );
|
|
1374
|
-
vUv = uv;
|
|
1375
|
-
vUv.y = 1. - vUv.y;
|
|
1376
|
-
|
|
1377
|
-
// fit into screen
|
|
1378
|
-
ivec2 res = textureSize(map, 0);
|
|
1379
|
-
float videoAspect = float(res.x) / float(res.y);
|
|
1380
|
-
float aspect = videoAspect / screenAspect;
|
|
1381
|
-
if(aspect >= 1.0)
|
|
1382
|
-
{
|
|
1383
|
-
vUv.y = vUv.y * aspect;
|
|
1384
|
-
float offset = (1. - aspect) * .5;
|
|
1385
|
-
vUv.y = vUv.y + offset;
|
|
1386
|
-
}
|
|
1387
|
-
else
|
|
1388
|
-
{
|
|
1389
|
-
vUv.x = vUv.x / aspect;
|
|
1390
|
-
float offset = (1. - 1. / aspect) * .5;
|
|
1391
|
-
vUv.x = vUv.x + offset;
|
|
1392
|
-
}
|
|
1393
|
-
|
|
1394
|
-
vUv.x -= .5;
|
|
1395
|
-
vUv.y -= .5;
|
|
1396
|
-
|
|
1397
|
-
vUv.x *= offsetScale.z;
|
|
1398
|
-
vUv.y *= offsetScale.z;
|
|
1399
|
-
vUv.x += offsetScale.x;
|
|
1400
|
-
vUv.y += offsetScale.y;
|
|
1401
|
-
|
|
1402
|
-
vUv.x += .5;
|
|
1403
|
-
vUv.y += .5;
|
|
1404
|
-
}
|
|
1405
|
-
|
|
1406
|
-
`,this.fragmentShader=`
|
|
1407
|
-
uniform sampler2D map;
|
|
1408
|
-
varying vec2 vUv;
|
|
1409
|
-
void main() {
|
|
1410
|
-
if(vUv.x < 0. || vUv.x > 1. || vUv.y < 0. || vUv.y > 1.)
|
|
1411
|
-
gl_FragColor = vec4(0., 0., 0., 1.);
|
|
1412
|
-
else
|
|
1413
|
-
{
|
|
1414
|
-
vec4 texcolor = texture2D(map, vUv);
|
|
1415
|
-
gl_FragColor = texcolor;
|
|
1416
|
-
}
|
|
1417
|
-
}
|
|
1418
|
-
`}}var pE=Object.defineProperty,mE=Object.getOwnPropertyDescriptor,yh=(s,e,t,i)=>{for(var n=i>1?void 0:i?mE(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&&pE(e,t,n),n};const mt=x("debugscreensharing");var gx=(s=>(s[s.Screen=0]="Screen",s[s.Camera=1]="Camera",s[s.Canvas=2]="Canvas",s[s.Microphone=3]="Microphone",s))(gx||{});class Eo extends R{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=gx[this.device]),mt&&console.log("Screensharing",this.name,this),vi.registerWaitForAllowAudio(()=>{this._videoPlayer&&this._currentStream&&this._currentMode===2&&(this._videoPlayer.playInBackground=!0,this._videoPlayer.setVideo(this._currentStream))}),this._net=new Yc(this)}onEnable(){this._net?.enable(),this._net?.addEventListener(Fn.StreamReceived,this.onReceiveStream),this._net?.addEventListener(Fn.StreamEnded,this.onCallEnded),this.context.connection.beginListen(K.JoinedRoom,this.onJoinedRoom),this.autoConnect&&_s(1e3).then(()=>(this.enabled&&this.autoConnect&&!this.isReceiving&&!this.isSending&&this.context.connection.isInRoom&&this.share(),0))}onDisable(){this._net?.removeEventListener(Fn.StreamReceived,this.onReceiveStream),this._net?.removeEventListener(Fn.StreamEnded,this.onCallEnded),this.context.connection.stopListen(K.JoinedRoom,this.onJoinedRoom),this._net?.disable(),this.close()}onJoinedRoom=async()=>{await _s(1e3),this.autoConnect&&!this.isSending&&!this.isReceiving&&this.context.connection.isInRoom&&this.share()};_ensureVideoPlayer(){const e=new tt;e.aspectMode=fx.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"),A()&&fe("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,tt)??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):Un(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):Un(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&&(mt&&console.warn("Close current stream / disposing resources, stream was active?",this._currentStream.active),this._net?.stopSendingStream(this._currentStream),Un(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 vi,this._audioSource.spatialBlend=0,this._audioSource.volume=1,this.gameObject.addComponent(this._audioSource)),n||(mt&&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",()=>{mt&&console.log("Track ended",o),this.close()}),mt&&o.kind==="video"&&console.log(n?"Video →":"Video ←",o.getSettings())}onReceiveStream=e=>{e.stream?.active===!0&&this.setStream(e.stream,2)};onCallEnded=e=>{mt&&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");mt&&console.log(`Request camera. These are your kind:videoinput devices:
|
|
1419
|
-
`,i);let n=!1;for(const o of i)try{if(!this._requestOpen){mt&&console.log("Camera selection cancelled");break}if(o.kind!=="videoinput"){mt&&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){mt&&console.log("Skipping device due to options.deviceId: "+o.label+"; "+o.deviceId);continue}if(t?.deviceFilter&&t.deviceFilter(o)===!1){mt&&console.log("Skipping device due to options.deviceFilter: "+o.label+"; "+o.deviceId);continue}}else if(this.deviceFilter)if(this.deviceFilter(o)===!1){mt&&console.log("Skipping device due to ScreenShare.deviceFilter: "+o.label+"; "+o.deviceId);continue}else mt&&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){mt&&console.log("Skipping device due to ScreenShare.deviceName: "+o.label+"; "+o.deviceId);continue}else mt&&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),mt&&console.log("Selected camera",o)):(Un(l),mt&&console.log("Camera selection cancelled"));break}catch(r){if(r.message==="Failed to allocate videosource"||r.message==="Could not start video source"){fe("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&&A()&&(fe("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))}}yh([f()],Eo.prototype,"allowStartOnClick",2);yh([f()],Eo.prototype,"autoConnect",2);yh([f(tt)],Eo.prototype,"videoPlayer",1);yh([f()],Eo.prototype,"device",2);yh([f()],Eo.prototype,"deviceName",2);var gE=Object.defineProperty,ll=(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 yE=x("debugseethrough");let _E=0;class As extends R{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=_E++;onEnable(){this._needsUpdate=!0,this._renderer=null}onDisable(){}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(yE&&this.referencePoint){const i=this.gameObject.worldPosition;B.DrawArrow(F(i),i.sub(this._referencePointDir),t?16711680:65280),B.DrawWireSphere(this.referencePoint.worldPosition,.05,255)}t?this.updateAlpha(this.minAlpha,this.fadeDuration):this.updateAlpha(1,this.fadeDuration)}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(F(1,.5,1)).normalize()}updateAlpha(e,t=this.fadeDuration){this.overrideAlpha!==void 0&&this.overrideAlpha!==-1&&(e=this.overrideAlpha),this._renderer?.forEach(i=>{e<.9?i.gameObject.raycastAllowed=!1:i.gameObject.raycastAllowed=!0;const n=i.sharedMaterials;if(!n)return;const o=ys.get(i.gameObject),r=o.getOverride("opacity")?.value??n[0].opacity??1;let a=I.lerp(r,e,t<=0?1:this.context.time.deltaTime/t);a>=.99?a=1:a<=.01&&(a=0),o.setOverride("alphaHash",this.useAlphaHash),o.setOverride("opacity",a),o.setOverride("transparent",a>=.99999?!1:!this.useAlphaHash)})}}ll([f(c.Object3D)],As.prototype,"referencePoint");ll([f()],As.prototype,"fadeDuration");ll([f()],As.prototype,"minAlpha");ll([f()],As.prototype,"useAlphaHash");ll([f()],As.prototype,"overrideAlpha");ll([f()],As.prototype,"autoUpdate");var bE=Object.defineProperty,yx=(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};class _h extends R{mode=0;shadowColor=new te(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=bo.createPrimitive(Va.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;
|
|
1420
|
-
// diffuse-only lighting with overdrive to somewhat compensate
|
|
1421
|
-
// for the loss of indirect lighting and to make it more visible.
|
|
1422
|
-
vec3 direct = (reflectedLight.directDiffuse + reflectedLight.directSpecular) * 6.6;
|
|
1423
|
-
float max = max(direct.r, max(direct.g, direct.b));
|
|
1424
|
-
|
|
1425
|
-
// early out - we're simply returning direct lighting and some alpha based on it so it can
|
|
1426
|
-
// be blended onto the scene.
|
|
1427
|
-
gl_FragColor = vec4(direct, max);
|
|
1428
|
-
return;
|
|
1429
|
-
`)},e.userData.isLightBlendMaterial=!0}applyShadowMaterial(){if(this.targetMesh)if(this.targetMesh.material.type!=="ShadowMaterial"){const e=new c.ShadowMaterial;e.color=this.shadowColor,e.opacity=this.shadowColor.alpha,this.applyMaterialOptions(e),this.targetMesh.material=e,e.userData.isShadowCatcherMaterial=!0}else{const e=this.targetMesh.material;e.color=this.shadowColor,e.opacity=this.shadowColor.alpha,this.applyMaterialOptions(e),e.userData.isShadowCatcherMaterial=!0}}applyOccluderMaterial(){if(this.targetMesh){let e=this.targetMesh.material;if(!e){const t=new c.MeshBasicMaterial;this.targetMesh.material=t,e=t}e.depthWrite=!0,e.stencilWrite=!0,e.colorWrite=!1,this.gameObject.renderOrder=-100}}applyMaterialOptions(e){e&&(e.depthWrite=!1,e.stencilWrite=!1)}}yx([f()],_h.prototype,"mode");yx([f(te)],_h.prototype,"shadowColor");var vE=Object.defineProperty,bh=(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};const $t=x("debugskybox");Ry("background-image");Ry("environment-image");const Ub={studio:{url:"https://cdn.needle.tools/static/skybox/modelviewer-Neutral.pmrem4x4.ktx2?pmrem",url_low:"https://cdn.needle.tools/static/skybox/modelviewer-Neutral-small.pmrem4x4.ktx2?pmrem"},"blurred-skybox":{url:"https://cdn.needle.tools/static/skybox/blurred-skybox.pmrem4x4.ktx2?pmrem",url_low:"https://cdn.needle.tools/static/skybox/blurred-skybox-small.pmrem4x4.ktx2?pmrem"},"quicklook-ar":{url:"https://cdn.needle.tools/static/skybox/QuickLook-ARMode.pmrem4x4.ktx2?pmrem",url_low:"https://cdn.needle.tools/static/skybox/QuickLook-ARMode-small.pmrem4x4.ktx2?pmrem"},quicklook:{url:"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode.pmrem4x4.ktx2?pmrem",url_low:"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode-small.pmrem4x4.ktx2?pmrem"}};function zb(s,e,t,i,n){if(e==="transparent"||e?.startsWith("rgb")||e?.startsWith("#"))return console.warn(`Needle Engine: Invalid ${n} value (${e}). Did you mean to set background-color instead?`),null;const o=new ef;o.sourceId=av(e),o.allowDrop=!1,o.allowNetworking=!1,o.background=t,o.environment=i,S.addComponent(s.scene,o);const r=a=>{if($t&&console.log(n,"CHANGED TO",a),a){if(typeof a!="string"){console.warn("Invalid attribute value for "+n);return}o.setSkybox(a)}else if(o.sourceId&&(i&&(s.sceneLighting.internalEnableReflection(o.sourceId)||(s.scene.environment=null)),t)){const l=s.lightmaps.tryGetSkybox(o.sourceId);s.scene.background=l}};return Em(s.domElement,n,r),o.addEventListener("destroy",()=>{$t&&console.log("Destroyed attribute remote skybox",n),Tm(s.domElement,n,r)}),o.setSkybox(e)}const au=new Array;ce.registerCallback(le.ContextCreationStart,s=>{const e=s.context,t=e.domElement.getAttribute("background-image"),i=e.domElement.getAttribute("environment-image");if(t){$t&&console.log("Creating RemoteSkybox to load background "+t);const n=zb(e,t,!0,!1,"background-image");n&&au.push(n)}if(i){$t&&console.log("Creating RemoteSkybox to load environment "+i);const n=zb(e,i,!1,!0,"environment-image");n&&au.push(n)}});ce.registerCallback(le.ContextCreationStart,()=>Promise.all(au).finally(()=>{au.length=0}));const _r=class extends R{url="studio";allowDrop=!0;background=!0;environment=!0;allowNetworking=!0;_prevUrl;_prevLoadedEnvironment;_prevEnvironment=null;_prevBackground=null;onEnable(){this.setSkybox(this.url),this.registerDropEvents()}onDisable(){this.context.scene.environment===this._prevLoadedEnvironment&&(this.context.scene.environment=this._prevEnvironment,si.backgroundShouldBeTransparent(this.context)||(this.context.scene.background=this._prevBackground),this._prevLoadedEnvironment=void 0),this.unregisterDropEvents(),this.context.mainCameraComponent?.applyClearFlags()}urlChangedSyncField(){this.allowNetworking&&this.url&&(this.isRemoteTexture(this.url)?this.setSkybox(this.url):$t&&console.warn(`RemoteSkybox: Not setting skybox: ${this.url} is not a remote texture. If you want to set a local texture, set allowNetworking to false.`))}async setSkybox(e,t){if(!this.activeAndEnabled||(e=wE(e,this.environment,this.background),!e))return!1;if(t??=e,this.isValidTextureType(t)||console.warn('Potentially invalid skybox URL: "'+t+'" on '+(this.name||this.gameObject?.name||"context")),$t&&console.log("Set RemoteSkybox url: "+e),this._prevUrl===e&&this._prevLoadedEnvironment)return this.apply(),!0;this._prevLoadedEnvironment?.dispose(),this._prevLoadedEnvironment=void 0,this._prevUrl=e;const i=await Ag(e,this.context.renderer);return i?!this.enabled||this.destroyed?($t&&console.warn("RemoteSkybox: Component is disabled or destroyed"),!1):this._prevUrl!==e?($t&&console.warn("RemoteSkybox: URL changed while loading texture, aborting setSkybox"),!1):(this.url=e,this._prevLoadedEnvironment=i,this.apply(),!0):($t&&console.warn("RemoteSkybox: Failed to load texture from url",e),!1)}apply(){const e=this._prevLoadedEnvironment;if(e&&(e instanceof c.CubeTexture||e instanceof c.CompressedCubeTexture||e.mapping==c.CubeUVReflectionMapping||(e.mapping=c.EquirectangularRefractionMapping,e.needsUpdate=!0),!this.destroyed)){if(!this.context){console.warn("RemoteSkybox: Context is not available - can not apply skybox.");return}this.context.scene.background!==e&&(this._prevBackground=this.context.scene.background),this.context.scene.environment!==e&&(this._prevEnvironment=this.context.scene.environment),$t&&console.log("Set RemoteSkybox ("+(this.environment&&this.background?"environment and background":this.environment?"environment":this.background?"background":"none")+")",this.url,!si.backgroundShouldBeTransparent(this.context)),this.environment&&(this.context.scene.environment=e),this.background&&!si.backgroundShouldBeTransparent(this.context)&&(this.context.scene.background=e),this.context.mainCameraComponent?.backgroundBlurriness!==void 0&&(this.context.scene.backgroundBlurriness=this.context.mainCameraComponent.backgroundBlurriness)}}validProtocols=["file:","blob:","data:"];validTextureTypes=[".ktx2",".hdr",".exr",".jpg",".jpeg",".png"];isRemoteTexture(e){return e.startsWith("http://")||e.startsWith("https://")}isValidTextureType(e){for(const t of this.validTextureTypes)if(e.includes(t))return!0;for(const t of this.validProtocols)if(e.startsWith(t))return!0;return!1}registerDropEvents(){this.unregisterDropEvents(),this.context.domElement.addEventListener("dragover",this.onDragOverEvent),this.context.domElement.addEventListener("drop",this.onDrop)}unregisterDropEvents(){this.context.domElement.removeEventListener("dragover",this.onDragOverEvent),this.context.domElement.removeEventListener("drop",this.onDrop)}onDragOverEvent=e=>{if(this.allowDrop&&e.dataTransfer)for(const t of e.dataTransfer.types)(t==="text/uri-list"||t==="Files")&&e.preventDefault()};onDrop=e=>{if(this.allowDrop&&e.dataTransfer){for(const t of e.dataTransfer.types)if($t&&console.log(t),t==="text/uri-list"){const i=e.dataTransfer.getData(t);$t&&console.log(t,i);let n=new RegExp(/polyhaven.com\/asset_img\/.+?\/(?<name>.+)\.png/).exec(i)?.groups?.name;if(n||(n=new RegExp(/polyhaven\.com\/a\/(?<name>.+)/).exec(i)?.groups?.name),$t&&console.log(n),n){const o="https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/"+n+"_1k.exr";console.log(`[Remote Skybox] Setting skybox from url: ${o}`),e.preventDefault(),this.setSkybox(o);break}else if(this.isValidTextureType(i)){console.log("[Remote Skybox] Setting skybox from url: "+i),e.preventDefault(),this.setSkybox(i);break}else{console.warn(`[RemoteSkybox] Unknown url ${i}. If you want to load a skybox from a url, make sure it is a valid image url. Url must end with${this.validTextureTypes.join(", ")}.`);const o=new CustomEvent("dropped-unknown-url",{detail:{sender:this,event:e,url:i,apply:r=>{e.preventDefault(),this.setSkybox(r)}}});this.dispatchEvent(o)}}else if(t=="Files"){const i=e.dataTransfer.files.item(0);if($t&&console.log(t,i),!i)continue;if(!this.isValidTextureType(i.name)){console.warn(`[RemoteSkybox]: File "${i.name}" is not supported. Supported files are ${this.validTextureTypes.join(", ")}`);return}e.preventDefault(),this.setSkybox(i.name);break}}}};bh([Jg(_r.prototype.urlChangedSyncField),f(URL)],_r.prototype,"url");bh([f()],_r.prototype,"allowDrop");bh([f()],_r.prototype,"background");bh([f()],_r.prototype,"environment");bh([f()],_r.prototype,"allowNetworking");let ef=_r;function wE(s,e,t){if(s==null)return null;const i=e&&!t,n=Ub[s.toLowerCase()];return n?i?n.url_low:n.url:(typeof s=="string"&&s?.length&&(A()||$t)&&(s.includes("/")||s.includes(".")||console.warn(`RemoteSkybox: Unknown magic skybox name "${s}". Valid names are: ${Object.keys(Ub).map(r=>`"${r}"`).join(", ")}`)),s)}var xE=Object.defineProperty,tf=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&xE(e,t,n),n};const vh=class _x extends R{target=null;followFactor=.1;rotateFactor=.1;positionAxes=pa.All;flipForward=!1;static _invertForward=new c.Quaternion().setFromAxisAngle(new c.Vector3(0,1,0),Math.PI);_firstUpdate=!0;onBeforeRender(){this.updateNow(!1)}updateNow(e){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){const t=Y(this.target),i=this._firstUpdate||e?1:I.clamp01(this.context.time.deltaTime*this.followFactor),n=this.worldPosition;this.positionAxes&pa.X&&(n.x=I.lerp(n.x,t.x,i)),this.positionAxes&pa.Y&&(n.y=I.lerp(n.y,t.y,i)),this.positionAxes&pa.Z&&(n.z=I.lerp(n.z,t.z,i)),this.worldPosition=n}if(this.rotateFactor>0){const t=pe(this.target);this.flipForward&&t.premultiply(_x._invertForward);const i=this._firstUpdate||e?1:I.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(t,i)}this._firstUpdate=!1}}};tf([f(c.Object3D)],vh.prototype,"target");tf([f()],vh.prototype,"followFactor");tf([f()],vh.prototype,"rotateFactor");tf([f()],vh.prototype,"positionAxes");let nf=vh;var SE=Object.defineProperty,wh=(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 cc=x("debugspatialtrigger"),Nb=new c.Layers,Vb=new c.Layers;function CE(s,e){return Nb.mask=s,Vb.mask=e,Nb.test(Vb)}class Gn extends R{triggerMask=0;onEnter;onStay;onExit;start(){cc&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(const e of sf.triggers)CE(e.triggerMask,this.triggerMask)&&e.test(this.gameObject)&&this.currentIntersected.push(e);for(let e=this.lastIntersected.length-1;e>=0;e--){const t=this.lastIntersected[e];this.currentIntersected.indexOf(t)<0&&(this.onExitTrigger(t),this.lastIntersected.splice(e,1))}for(const e of this.currentIntersected)this.lastIntersected.indexOf(e)<0&&this.onEnterTrigger(e),this.onStayTrigger(e);this.lastIntersected.length=0,this.lastIntersected.push(...this.currentIntersected)}currentIntersected=[];lastIntersected=[];onEnterTrigger(e){cc&&console.log("ENTER TRIGGER",this.name,e.name,this,e),e.raiseOnEnterEvent(this),this.onEnter?.invoke()}onExitTrigger(e){cc&&console.log("EXIT TRIGGER",this.name,e.name),e.raiseOnExitEvent(this),this.onExit?.invoke()}onStayTrigger(e){e.raiseOnStayEvent(this),this.onStay?.invoke()}}wh([f()],Gn.prototype,"triggerMask");wh([f(ne)],Gn.prototype,"onEnter");wh([f(ne)],Gn.prototype,"onStay");wh([f(ne)],Gn.prototype,"onExit");const bx=class Ad extends R{static triggers=[];triggerMask;boxHelper;start(){cc&&console.log(this.name,this.triggerMask,this)}onEnable(){Ad.triggers.push(this),this.boxHelper||(this.boxHelper=S.addComponent(this.gameObject,_t),this.boxHelper?.showHelper(null,cc))}onDisable(){Ad.triggers.splice(Ad.triggers.indexOf(this),1)}test(e){return this.boxHelper?this.boxHelper.isInBox(e)??!1:!1}raiseOnEnterEvent(e){S.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof Gn&&t.onEnterTrigger(this)},!1)}raiseOnStayEvent(e){S.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof Gn&&t.onStayTrigger(this)},!1)}raiseOnExitEvent(e){S.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof Gn&&t.onExitTrigger(this)},!1)}};wh([f()],bx.prototype,"triggerMask");let sf=bx;var PE=Object.defineProperty,OE=(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 mi=x("debugspectator");class of extends R{cam=null;useKeys=!0;_mode=0;get mode(){return this._mode}set mode(e){this._mode=e}get isSpectating(){return this._handler?.currentTarget!==void 0}isSpectatingUser(e){return this.target?.userId===e}isFollowedBy(e){return this.followers?.includes(e)}get followers(){return this._networking.followers}stopSpectating(){if(this.context.isInXR){this.followSelf();return}this.target=void 0}get localId(){return this.context.connection.connectionId??"local"}set target(e){if(this._handler){const t=this._handler.currentTarget?.userId,i=this.context.players.getPlayerView(this.localId);e===void 0||this.context.isInXR===!1&&i?.currentObject===e.currentObject?this._handler.currentTarget!==void 0&&(this._handler.disable(),S.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(e,t)):this._handler.currentTarget!==e&&(this._handler.set(e),S.setActive(this.gameObject,!0),this.orbit&&(this.orbit.enabled=!1),this._networking.onSpectatedObjectChanged(e,t))}}get target(){return this._handler?.currentTarget}requestAllFollowMe(){this._networking.onRequestFollowMe()}get isSpectatingSelf(){return this.isSpectating&&this.target?.currentObject===this.context.players.getPlayerView(this.localId)?.currentObject}orbit=null;_handler;eventSub_WebXRRequestStartEvent=null;eventSub_WebXRStartEvent=null;eventSub_WebXREndEvent=null;_debug;_networking;awake(){if(this._debug=new RE(this.context,this),this._networking=new AE(this.context,this),this._networking.awake(),S.setActive(this.gameObject,!1),this.cam=S.getComponent(this.gameObject,si),!this.cam){console.warn("SpectatorCamera: Spectator camera needs camera component on the same object.",this);return}!this._handler&&this.cam&&(this._handler=new ME(this.context,this.cam,this)),this.orbit=S.getComponent(this.context.mainCamera,de)}onDestroy(){this.stopSpectating(),this._handler?.destroy(),this._networking?.destroy()}isSupportedPlatform(){const e=window.navigator.userAgent,t=/Windows NT/.test(e)&&/Edg/.test(e)&&!/Win64/.test(e);return exports.DeviceUtilities.isDesktop()&&!exports.DeviceUtilities.isMobileDevice()&&!t}onBeforeXR(e){this.isSupportedPlatform()&&S.setActive(this.gameObject,!0)}onEnterXR(e){this.isSupportedPlatform()&&(mi&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onLeaveXR(e){this.context.removeCamera(this.cam),S.setActive(this.gameObject,!1),this._handler?.set(void 0),this._handler?.disable(),this.isSpectatingSelf&&this.stopSpectating(),this.orbit&&(this.orbit.enabled=!0)}followSelf(){this.target=this.context.players.getPlayerView(this.context.connection.connectionId),this.target||(this.context.players.setPlayerView(this.localId,this.context.mainCamera,gs.Headset),this.target=this.context.players.getPlayerView(this.localId)),mi&&console.log("Follow self",this.target)}onAfterRender(){if(!this.cam)return;const e=this.context.renderer,t=e.xr.enabled;if(!e.xr.isPresenting&&!this._handler?.currentTarget)return;this._handler?.update(this._mode);const i=e.getRenderTarget();let n=null;const o=e.state;if(!i||i.isXRRenderTarget===!0){if(!e.state.bindFramebuffer||!o.bindXRFramebuffer)return;n=e._framebuffer,o.bindXRFramebuffer(null)}this.setAvatarFlagsBeforeRender();const r=this.context.mainCameraComponent;if(r){const h=r.backgroundColor;h&&e.setClearColor(h,h.alpha),this.cam.backgroundColor=h,this.cam.clearFlags=r.clearFlags,this.cam.nearClipPlane=r.nearClipPlane,this.cam.farClipPlane=r.farClipPlane}else e.setClearColor(new c.Color(1,1,1));e.setRenderTarget(null),e.xr.enabled=!1;const a=this.cam?.threeCamera;this.context.updateAspect(a);const l=e.xr.isPresenting;e.xr.isPresenting=!1,e.setSize(this.context.domWidth,this.context.domHeight),e.render(this.context.scene,a),e.xr.isPresenting=l,e.xr.enabled=t,i?e.setRenderTarget(i):o.bindXRFramebuffer&&o.bindXRFramebuffer(n),this.resetAvatarFlags()}setAvatarFlagsBeforeRender(){const e=this._mode===0;for(const t of Oe.instances)if(t.avatar&&"isLocalAvatar"in t.avatar&&"flags"in t.avatar){let i=Ln.All;this.isSpectatingSelf&&(i=e&&t.avatar.isLocalAvatar?Ln.FirstPerson:Ln.ThirdPerson);const n=t.avatar.flags;if(!n)continue;for(const o of n)o.UpdateVisible(i)}}resetAvatarFlags(){for(const e of Oe.instances)if(e.avatar&&"flags"in e.avatar){const t=e.avatar.flags;if(!t)continue;for(const i of t)"isLocalAvatar"in e.avatar&&e.avatar?.isLocalAvatar?i.UpdateVisible(Ln.FirstPerson):i.UpdateVisible(Ln.ThirdPerson)}}}OE([f()],of.prototype,"useKeys");class ME{context;cam;spectator;follow;target;view;currentObject;get currentTarget(){return this.view}constructor(e,t,i){this.context=e,this.cam=t,this.spectator=i}set(e){const t=e?.currentObject;if(!t){this.spectator.stopSpectating();return}t!==this.currentObject&&(this.currentObject=t,this.view=e,this.follow||(this.follow=S.addComponent(this.cam.gameObject,nf)),this.target||(this.target=new c.Object3D),t.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,mi&&console.log("FOLLOW",t),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){mi&&console.log("STOP FOLLOW",this.currentObject),this.view=void 0,this.currentObject=void 0,this.context.removeCamera(this.cam),this.follow&&(this.follow.enabled=!1)}destroy(){this.target?.removeFromParent(),this.follow&&S.destroy(this.follow)}update(e){if(this.currentTarget?.isConnected===!1||this.currentTarget?.removed===!0){mi&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&this.currentTarget?.currentObject!==this.currentObject&&(mi&&console.log("Target changed",this.currentObject,"to",this.currentTarget.currentObject),this.set(this.currentTarget));const t=this.context.mainCamera;if(t){const n=this.cam.threeCamera;(n.near!==t.near||n.far!==t.far)&&(n.near=t.near,n.far=t.far,n.updateProjectionMatrix())}const i=this.follow?.target;if(!(!i||!this.follow)){switch(e){case 0:this.view?.viewDevice!==gs.Browser?(this.follow.followFactor=5,this.follow.rotateFactor=5):(this.follow.followFactor=50,this.follow.rotateFactor=50),i.position.set(0,0,0);break;case 1:this.follow.followFactor=3,this.follow.rotateFactor=2,i.position.set(0,.5,1.5);break}this.follow.flipForward=!1,this.view?.viewDevice!==gs.Browser?i.quaternion.copy(kE):i.quaternion.identity()}}}const kE=new c.Quaternion().setFromAxisAngle(new c.Vector3(0,1,0),Math.PI);class RE{context;spectator;constructor(e,t){this.context=e,this.spectator=t,console.log("[Spectator Camera] Click other avatars or cameras to follow them. Press ESC to exit spectator mode."),this.context.domElement.addEventListener("keydown",n=>{if(!this.spectator.useKeys)return;n.key==="Escape"&&this.spectator.stopSpectating()});let i=0;this.context.input.addEventListener(Pe.PointerDown,n=>{i=this.context.time.time}),this.context.input.addEventListener(Pe.PointerUp,n=>{const o=this.context.time.time-i;o>1?this.spectator.stopSpectating():this.context.input.getPointerClicked(0)&&o<.3&&this.trySelectObject()})}trySelectObject(){const e=new vo;e.setMask(16777215);const t=this.context.physics.raycast(e);if(mi&&console.log(...t),t?.length)for(const i of t){if(i.distance<.2)continue;const n=i.object,o=zi.getFor(n);let r=o?.owner;if(r||(r=S.getComponentInParent(n,Oe)?.connectionId),r){const a=this.context.players.getPlayerView(r);this.spectator.target=a,mi&&console.log("spectate",r,o);break}}}}class EE{guid;dontSave=!0;targetUserId;stoppedFollowing;constructor(e,t,i){this.guid=e,this.targetUserId=t,this.stoppedFollowing=i}}class TE{guid;userId;constructor(e,t){this.guid=e.guid,this.userId=t}}class AE{followers=[];context;spectator;_followerEventMethod;_requestFollowMethod;_joinedRoomMethod;constructor(e,t){this.context=e,this.spectator=t,this._followerEventMethod=this.onFollowerEvent.bind(this),this._requestFollowMethod=this.onRequestFollowEvent.bind(this),this._joinedRoomMethod=this.onUserJoinedRoom.bind(this)}awake(){this.context.connection.beginListen("spectator-follower-changed",this._followerEventMethod),this.context.connection.beginListen("spectator-request-follow",this._requestFollowMethod),this.context.connection.beginListen(K.JoinedRoom,this._joinedRoomMethod),this.context.domElement.addEventListener("keydown",e=>{this.spectator.useKeys&&(e.key==="f"?this.onRequestFollowMe():e.key==="Escape"&&this.onRequestFollowMe(!0))})}destroy(){this.context.connection.stopListen("spectator-follower-changed",this._followerEventMethod),this.context.connection.stopListen("spectator-request-follow",this._requestFollowMethod),this.context.connection.stopListen(K.JoinedRoom,this._joinedRoomMethod)}onSpectatedObjectChanged(e,t){if(mi&&console.log(this.context.connection.connectionId,"onSpectatedObjectChanged",e,t),this.context.connection.connectionId){const i=e?.userId===void 0,n=i?t:e?.userId,o=new EE(this.context.connection.connectionId,n,i);this.context.connection.send("spectator-follower-changed",o)}}onRequestFollowMe(e=!1){if(mi&&console.log("Request follow",this.context.connection.connectionId),this.context.connection.connectionId){this.spectator.stopSpectating();const t=e?void 0:this.context.connection.connectionId,i=new TE(this.spectator,t);this.context.connection.send("spectator-request-follow",i)}}onUserJoinedRoom(){x("followme")&&this.onRequestFollowMe()}onFollowerEvent(e){const t=e.targetUserId,i=e.guid;if(mi&&console.log(e),t===this.context.connection.connectionId)if(e.stoppedFollowing){const n=this.followers.indexOf(i);n!==-1&&(this.followers.splice(n,1),this.removeDisconnectedFollowers(),console.log(i,"unfollows you",this.followers.length))}else this.followers.includes(i)||(this.followers.push(i),this.removeDisconnectedFollowers(),console.log(i,"follows you",this.followers.length))}removeDisconnectedFollowers(){for(let e=this.followers.length-1;e>=0;e--){const t=this.followers[e];this.context.connection.userIsInRoom(t)===!1&&this.followers.splice(e,1)}}_lastRequestFollowUser;onRequestFollowEvent(e){if(this._lastRequestFollowUser=e,e.userId===this.context.connection.connectionId)this.spectator.stopSpectating();else if(e.userId===void 0)this.spectator.stopSpectating();else{const t=this.context.players.getPlayerView(e.userId);if(t)this.spectator.target=t;else return mi&&console.warn("Could not find view",e.userId),this.enforceFollow(),!1}return!0}_enforceFollowInterval;enforceFollow(){this._enforceFollowInterval||(this._enforceFollowInterval=setInterval(()=>{this._lastRequestFollowUser===void 0||this._lastRequestFollowUser.userId&&this.spectator.isFollowedBy(this._lastRequestFollowUser.userId)?(clearInterval(this._enforceFollowInterval),this._enforceFollowInterval=void 0):(mi&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}}var DE=Object.defineProperty,LE=Object.getOwnPropertyDescriptor,cl=(s,e,t,i)=>{for(var n=i>1?void 0:i?LE(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&&DE(e,t,n),n};const $b=x("debugsplines");class qn{position=new c.Vector3;rotation=new c.Quaternion;tangentIn=new c.Vector3;tangentOut=new c.Vector3}cl([Be(c.Vector3)],qn.prototype,"position",2);cl([Be(c.Quaternion)],qn.prototype,"rotation",2);cl([Be(c.Vector3)],qn.prototype,"tangentIn",2);cl([Be(c.Vector3)],qn.prototype,"tangentOut",2);class Nr extends R{addKnot(e){if(e instanceof qn)this.spline.push(e),this._isDirty=!0;else{const t=new qn;t.position.copy(e.position),this.spline.push(t),this._isDirty=!0}return this}removeKnot(e){if(typeof e=="number")this.spline.splice(e,1),this._isDirty=!0;else{const t=this.spline.indexOf(e);t!==-1&&(this.spline.splice(t,1),this._isDirty=!0)}return this}getPointAt(e,t){if(!this.curve)return new c.Vector3;const i=this.curve.getPointAt(I.clamp01(e),t),n=this.gameObject.matrixWorld??void 0;return n&&i.applyMatrix4(n),i}markDirty(){this._isDirty=!0}getTangentAt(e,t){if(!this.curve)return t??new c.Vector3;const i=this.gameObject.worldQuaternion;return this.curve.getTangentAt(I.clamp01(e),t).applyQuaternion(i)}set closed(e){this._closed=e,this._isDirty=!0}get closed(){return this._closed}_closed=!1;spline=[];set debug(e){e&&!this._builtCurve&&this.buildCurve(),this._debugLine&&(this._debugLine.visible=e)}get curve(){return this._curve}get isDirty(){return this._isDirty}_isDirty=!1;_curve=null;_builtCurve=!1;_debugLine=null;awake(){$b&&(console.log(`[Spline] ${this.name}`,this),this.buildCurve())}update(){this._isDirty&&this.buildCurve(!0),this._debugLine&&this._debugLine.parent!==this.gameObject&&this.gameObject.add(this._debugLine)}buildCurve(e=!1){if(!(this._builtCurve&&!e)){if(this._builtCurve=!0,!this.spline){console.error("[Spline] Can not build curve, no spline data",this.name);return}this._isDirty=!1,this._curve=IE(this.spline,this.closed),this.buildDebugCurve()}}buildDebugCurve(){if($b&&this.spline&&this._curve){this._debugLine?.removeFromParent(),this._debugLine=null;const e=new c.LineBasicMaterial({color:6684927}),t=this.spline.length*10,i=this._curve.getPoints(t),n=new c.BufferGeometry().setFromPoints(i);this._debugLine=new c.Line(n,e),this.gameObject?.add(this._debugLine)}}}cl([Be()],Nr.prototype,"closed",1);cl([Be(qn)],Nr.prototype,"spline",2);function IE(s,e){const t=s.map(o=>new c.Vector3(-o.position.x,o.position.y,o.position.z));t.length===1&&t.push(t[0]);const i=s.reduce((o,r)=>o+Math.abs(r.tangentOut.x)+Math.abs(r.tangentOut.y)+Math.abs(r.tangentOut.z),0)/s.length,n=I.clamp(I.remap(i,0,.3,0,.5),0,1);return new c.CatmullRomCurve3(t,e,"catmullrom",n)}var jE=Object.defineProperty,BE=Object.getOwnPropertyDescriptor,To=(s,e,t,i)=>{for(var n=i>1?void 0:i?BE(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&&jE(e,t,n),n};class Zi extends R{spline=null;object=void 0;useLookAt=!0;lookAt=null;clamp=!1;get position01(){return this._position01}set position01(e){this._position01=e,this._needsUpdate=!0}reset(){this._position01=0}autoRun=!0;duration=10;pullStrength=1;_position01=0;_needsUpdate=!1;start(){this.object===void 0&&(this.object=this.gameObject),this.updateFromPosition()}onEnable(){window.addEventListener("pointerdown",this.onUserInput,{passive:!0}),this.context.domElement.addEventListener("wheel",this.onUserInput,{passive:!0})}onDisable(){window.removeEventListener("pointerdown",this.onUserInput),this.context.domElement.removeEventListener("wheel",this.onUserInput)}onUserInput=()=>{this.object?.contains(this.context.mainCamera)&&(this._needsUpdate=!1,this._performedUpdates+=999)};update(){this.autoRun&&(this._needsUpdate=!0,this._position01+=this.context.time.deltaTime/this.duration),this._needsUpdate&&(this._needsUpdate=!1,this.updateFromPosition())}updateFromPosition(){if(!this.spline||!this.spline.curve||!this.object)return;this.clamp?this._position01=I.clamp01(this._position01):this._position01=this._position01%1;const e=this._position01>=1?1:this._position01%1,t=this.spline.getPointAt(e);if(this.pullStrength>=1)this.object.worldPosition=t;else if(this._position01!==this._lastPosition01&&(this._performedUpdates=0),this._requiredUpdates=Math.round(100/this.pullStrength),this._performedUpdates<this._requiredUpdates){const i=this.object.worldPosition;this._performedUpdates++;const n=I.clamp01(this.pullStrength),o=this.object.worldPosition=i.lerp(t,n*(this.context.time.deltaTime/.3));this._lastPositionVector.copy(o),this._needsUpdate=!0}if(this.useLookAt)if(this.lookAt)this.object.lookAt(this.lookAt.worldPosition);else{const i=this.spline.getTangentAt(e);this.object.lookAt(t.add(i))}this._lastPosition01=this._position01}_lastPosition01=0;_requiredUpdates=0;_performedUpdates=0;_lastPositionVector=new c.Vector3}To([Be(Nr)],Zi.prototype,"spline",2);To([Be(c.Object3D)],Zi.prototype,"object",2);To([Be()],Zi.prototype,"useLookAt",2);To([Be(c.Object3D)],Zi.prototype,"lookAt",2);To([Be()],Zi.prototype,"clamp",2);To([Be()],Zi.prototype,"position01",1);To([Be()],Zi.prototype,"autoRun",2);To([Be()],Zi.prototype,"duration",2);class Dn{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedCameraModel(e,t){return(t||new Dn).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedCameraModel(e,t){return e.setPosition(e.position()+ae.SIZE_PREFIX_LENGTH),(t||new Dn).__init(e.readInt32(e.position())+e.position(),e)}userId(e){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}guid(e){const t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}dontSave(){const e=this.bb.__offset(this.bb_pos,8);return e?!!this.bb.readInt8(this.bb_pos+e):!1}pos(e){const t=this.bb.__offset(this.bb_pos,10);return t?(e||new ar).__init(this.bb_pos+t,this.bb):null}rot(e){const t=this.bb.__offset(this.bb_pos,12);return t?(e||new ar).__init(this.bb_pos+t,this.bb):null}static startSyncedCameraModel(e){e.startObject(5)}static addUserId(e,t){e.addFieldOffset(0,t,0)}static addGuid(e,t){e.addFieldOffset(1,t,0)}static addDontSave(e,t){e.addFieldInt8(2,+t,0)}static addPos(e,t){e.addFieldStruct(3,t,0)}static addRot(e,t){e.addFieldStruct(4,t,0)}static endSyncedCameraModel(e){return e.endObject()}static finishSyncedCameraModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedCameraModelBuffer(e,t){e.finish(t,void 0,!0)}}var FE=Object.defineProperty,UE=(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&&FE(e,t,n),n};const lu="SCAM";Xm(lu,Dn.getRootAsSyncedCameraModel);const ui=new ae.Builder;class zE{userId;guid;constructor(e,t){this.guid=t,this.userId=e}send(e,t){if(e){ui.clear();const i=ui.createString(this.guid),n=ui.createString(this.userId);Dn.startSyncedCameraModel(ui),Dn.addGuid(ui,i),Dn.addUserId(ui,n);const o=Y(e),r=hu(e);Dn.addPos(ui,ar.createVec3(ui,o.x,o.y,o.z)),Dn.addRot(ui,ar.createVec3(ui,r.x,r.y,r.z));const a=Dn.endSyncedCameraModel(ui);ui.finish(a,lu),t.sendBinary(ui.asUint8Array())}}}const vx=class xm extends R{static instances=[];getCameraObject(e){const t=this.userToCamMap[e];return t?this.remoteCams[t].obj:null}cameraPrefab=null;_lastWorldPosition;_lastWorldQuaternion;_model=null;_needsUpdate=!0;_lastUpdateTime=0;remoteCams={};userToCamMap={};_camTimeoutInSeconds=10;_receiveCallback=null;async awake(){this._lastWorldPosition=this.worldPosition.clone(),this._lastWorldQuaternion=this.worldQuaternion.clone(),this.cameraPrefab&&("uri"in this.cameraPrefab&&(this.cameraPrefab=await this.cameraPrefab.instantiate(this.gameObject)),this.cameraPrefab&&"isObject3D"in this.cameraPrefab&&(this.cameraPrefab.visible=!1))}onEnable(){this._receiveCallback=this.context.connection.beginListenBinary(lu,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(lu,this._receiveCallback)}update(){for(const n in this.remoteCams){const o=this.remoteCams[n],r=this.context.time.realtimeSinceStartup-o.lastUpdate;if(!o||r>this._camTimeoutInSeconds){A()&&console.log("Remote cam timeout",n),o?.obj&&S.destroy(o.obj),delete this.remoteCams[n],o&&delete this.userToCamMap[o.userId],xm.instances.push(o),this.context.players.removePlayerView(o.userId,gs.Browser);continue}}if(this.context.isInXR)return;const e=this.context.mainCamera;if(e===null){this.enabled=!1;return}if(!this.context.connection.isConnected||this.context.connection.connectionId===null)return;this._model===null&&(this._model=new zE(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));const t=Y(e),i=pe(e);(t.distanceTo(this._lastWorldPosition)>.001||i.angleTo(this._lastWorldQuaternion)>.01)&&(this._needsUpdate=!0),this._lastWorldPosition.copy(t),this._lastWorldQuaternion.copy(i),!((!this._needsUpdate||this.context.time.frameCount%2!==0)&&!(this.context.time.realtimeSinceStartup-this._lastUpdateTime>this._camTimeoutInSeconds*.5))&&(this._lastUpdateTime=this.context.time.realtimeSinceStartup,this._needsUpdate=!1,this._model.send(e,this.context.connection),this.context.isInXR||this.context.players.setPlayerView(this.context.connection.connectionId,e,gs.Browser))}onReceivedRemoteCameraInfoBin(e){const t=e.guid();if(!t)return;const i=e.userId();if(!i||!this.context.connection.userIsInRoom(i)||!this.cameraPrefab)return;let n=this.remoteCams[t];if(!n)if("isObject3D"in this.cameraPrefab){const l=new gn;l.context=this.context;const h=S.instantiate(this.cameraPrefab,l);n=this.remoteCams[t]={obj:h,lastUpdate:this.context.time.realtimeSinceStartup,userId:i},n.obj.visible=!0,this.gameObject.add(h),this.userToCamMap[i]=t,xm.instances.push(n);const d=S.getOrAddComponent(h,Oe);d.connectionId=i,d.avatar=h}else return;const o=n.obj;this.context.players.setPlayerView(i,o,gs.Browser),n.lastUpdate=this.context.time.realtimeSinceStartup,Ni.markDirty(o);const r=e.pos();r&&dr(o,r.x(),r.y(),r.z());const a=e.rot();a&&Fc(o,a.x(),a.y(),a.z())}};UE([f([c.Object3D,Z])],vx.prototype,"cameraPrefab");let Ey=vx;var NE=Object.defineProperty,VE=Object.getOwnPropertyDescriptor,Ao=(s,e,t,i)=>{for(var n=i>1?void 0:i?VE(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&&NE(e,t,n),n};const bp="view",vp=x("debugsyncedroom");class wn extends R{roomName="";urlParameterName="room";joinRandomRoom;requireRoomParameter=!1;autoRejoin=!0;createJoinButton=!0;createViewOnlyButton=!1;get currentRoomName(){const e=x(bp);return e||x(this.urlParameterName)}_lastJoinedRoom;set roomPrefix(e){this._roomPrefix=e}get roomPrefix(){return this._roomPrefix}_roomPrefix="";awake(){this.joinRandomRoom===void 0&&this.roomName?.length<=0&&(this.joinRandomRoom=!0),vp&&console.log(`SyncedRoom roomName:${this.roomName}, urlParamName:${this.urlParameterName}, joinRandomRoom:${this.joinRandomRoom}`)}onEnable(){const e=x(bp);if(e&&typeof e=="string"&&e.length>0){console.log("Join as viewer"),this.context.connection.joinRoom(e,!0);return}if(this.tryJoinRoom(),this.createJoinButton){const t=this.createRoomButton();this.context.menu.appendChild(t)}this.createViewOnlyButton&&this.onEnableViewOnlyButton()}onDisable(){this._roomButton?.remove(),this.onDisableViewOnlyButton(),this.roomName&&this.roomName.length>0&&this.context.connection.leaveRoom(this.roomName)}onDestroy(){this.destroyRoomButton()}tryJoinRandomRoom(){this.setRandomRoomUrlParameter(),this.tryJoinRoom()}tryJoinRoom(e=0){e===void 0&&(e=0);let t=!1;if(this.urlParameterName?.length>0){const i=x(this.urlParameterName);if(i&&(typeof i=="string"||typeof i=="number")){t=!0;const n=ov(i.toString());this.roomName=n}else if(this.joinRandomRoom&&(console.debug("No room name found in url, generating random one"),this.setRandomRoomUrlParameter(),e<1))return this.tryJoinRoom(e+1)}else this.joinRandomRoom&&(this.roomName===null||this.roomName===void 0||this.roomName.length<=0)&&(this.roomName=this.generateRoomName());return this.requireRoomParameter&&!t?((vp||A())&&console.warn('[SyncedRoom] Missing required room parameter "'+this.urlParameterName+`" in url - will not connect.
|
|
1430
|
-
To allow joining a room without a query parameter you can set "requireRoomParameter" to false.`),!1):(this.context.connection.isConnected||this.context.connection.connect(),this._lastJoinedRoom=this.roomName,this._roomPrefix&&(this.roomName=this._roomPrefix+this.roomName),this.roomName.length<=0?(console.warn(`[SyncedRoom] Room name is not set so we can not join a networked room.
|
|
1431
|
-
Please choose one of the following options to fix this:
|
|
1432
|
-
A) Set a room name in the SyncedRoom component
|
|
1433
|
-
B) Set a room name in the URL parameter "?`+this.urlParameterName+`=my_room"
|
|
1434
|
-
C) Set "joinRandomRoom" to true`),!1):(vp&&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()):A()&&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(bp,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}setRandomRoomUrlParameter(){const e=Lc(),t=this.generateRoomName();x(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),km(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&&pc(this.urlParameterName,null),this.context.connection.leaveRoom(),this._userWantsToBeInARoom=!1;else{if(this.urlParameterName){const t=x(this.urlParameterName);(!t||t===!0)&&(this._lastJoinedRoom?pc(this.urlParameterName,this._lastJoinedRoom):this.setRandomRoomUrlParameter())}this.tryJoinRoom()}},this._roomButtonIconJoin=vt("group"),this._roomButtonIconLeave=vt("group_off"),this.updateRoomButtonState(),this.context.connection.beginListen(K.JoinedRoom,this.updateRoomButtonState),this.context.connection.beginListen(K.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(K.JoinedRoom,this.updateRoomButtonState),this.context.connection.stopListen(K.LeftRoom,this.updateRoomButtonState)}_viewOnlyButton;onEnableViewOnlyButton(){this.context.connection.isConnected?this.onCreateViewOnlyButton():(this.context.connection.stopListen(K.JoinedRoom,this.onCreateViewOnlyButton),this.context.connection.beginListen(K.JoinedRoom,this.onCreateViewOnlyButton))}onDisableViewOnlyButton(){this.context.connection.stopListen(K.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),Se("View only URL copied to clipboard")):fe("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(vt("visibility"))}this.context.menu.appendChild(this._viewOnlyButton)}}Ao([f()],wn.prototype,"roomName",2);Ao([f()],wn.prototype,"urlParameterName",2);Ao([f()],wn.prototype,"joinRandomRoom",2);Ao([f()],wn.prototype,"requireRoomParameter",2);Ao([f()],wn.prototype,"autoRejoin",2);Ao([f()],wn.prototype,"createJoinButton",2);Ao([f()],wn.prototype,"createViewOnlyButton",2);Ao([f()],wn.prototype,"roomPrefix",1);function $E(){const s=x("testwindowcount")||0;s&&s>0&&WE(s)}function WE(s){if(x("testwindow"))return null;const e=new URL(window.location.href);Rp(e.searchParams,OO,1),Rp(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 Ty extends R{awake(){$E()}}class Ay extends R{transformsPerFrame=10;interval=0;useFlatbuffers=!0;awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinary(xc,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new GE(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 ae.Builder(1024));const e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();const i=aw(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 GE{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 HE=Object.defineProperty,rf=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&HE(e,t,n),n};const qE=x("debugsignals");class af{guid}rf([f()],af.prototype,"guid");class xh{signal;reaction}rf([f(af)],xh.prototype,"signal");rf([f(ne)],xh.prototype,"reaction");const wx=class ns extends R{static receivers={};static invoke(e){if(ns.receivers[e]){const t=ns.receivers[e];if(!t)return;for(const i of t)i.invoke(e)}}events;awake(){qE&&console.log("SignalReceiver awake",this)}onEnable(){if(this.events)for(const e of this.events)ns.receivers[e.signal.guid]||(ns.receivers[e.signal.guid]=[]),ns.receivers[e.signal.guid].push(this)}onDisable(){if(this.events){for(const e of this.events)if(ns.receivers[e.signal.guid]){const t=ns.receivers[e.signal.guid].indexOf(this);t>=0&&ns.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)}}};rf([f(xh)],wx.prototype,"events");let Sh=wx;var fi=(s=>(s.Activation="ActivationTrack",s.Animation="AnimationTrack",s.Audio="AudioTrack",s.Control="ControlTrack",s.Marker="MarkerTrack",s.Signal="SignalTrack",s))(fi||{}),kn=(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))(kn||{}),Dy=(s=>(s.Signal="SignalEmitter",s))(Dy||{});const Nn=x("debugtimeline");class hl{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 XE{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";Nn&&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),Nn&&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),Nn)){const a=new c.Euler().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",a)}}}}class Ec extends hl{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&&Z_(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";Nn&&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";Nn&&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,Nn&&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 XE(e);this._actionOffsets.push(t)}this.target&&(this._animator=S.getComponent(this.target,lt)??null,this._animator&&Z_(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,y=a<this.clips.length-1?this.models[a+1]:null;let _=u,g=!1;if(!_&&!n&&l.end<e&&m!==kn.None?(!y||y.start>e)&&(_=!0,n=!0):a==0&&!_&&!o&&l.start>e&&p!==kn.None&&(!y||y.start<e)&&(_=!0,g=!0,o=!0),_){let w=this.weight;w*=this.evaluateWeight(e,a,this.models,_),w*=this.director.weight;let b=u;if(g)switch(p){case kn.Hold:break;case kn.Loop:e+=l.start,b=!0;break;default:e+=l.start,b=!0;break}let v=this.getClipTime(e,l),E=0;const O=d.duration;if(g&&p===kn.Hold&&(v=0),b){if(d.loop)for(E+=Math.floor(v/(O+1e-6));v>O;)v-=O}else if(!u&&n)switch(m){case kn.Hold:v=this.getClipTime(l.end,l);break;case kn.Loop:v%=O;break;case kn.PingPong:const L=Math.floor(v/O)%2!==0;v%=O,L&&(v=O-v);break}l.reversed===!0?h.time=h.getClip().duration-v:h.time=v,h.timeScale=0;const M=Math.max(0,w);if(h.weight=M,r+=M,h.clampWhenFinished=!1,h.isRunning()||h.play(),this._useclipOffsets){const D=t==0?this._totalOffsetPosition:this._totalOffsetPosition2,L=t==0?this._totalOffsetRotation:this._totalOffsetRotation2;t<1&&(i=1-w),t+=1;const j=this._summedPos.set(0,0,0),V=this._tempPos.set(0,0,0),W=this._summedRot.identity(),k=this._tempRot.identity(),N=d.rotation;N&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp(N,w));const $=this._actionOffsets[a];if($.hasOffsets)for(let ee=0;ee<E;ee++)$.rootPositionOffset?V.copy($.rootPositionOffset):V.set(0,0,0),V.applyQuaternion(W),this._clipRotQuat&&V.applyQuaternion(this._clipRotQuat),$.rootQuaternionOffset&&(k.copy($.rootQuaternionOffset),W.multiply(k)),j.add(V);this._clipRotQuat&&L.multiply(this._clipRotQuat),L.multiply(W),d.position&&j.add(d.position),D.add(j)}}}if(this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,i),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,i)),this.__mixerError===void 0&&(Nn||A())&&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 QE=x("mutetimeline");class ps extends hl{models=[];listener;audio=[];audioContextTimeOffset=[];lastTime=0;audioSource;_audioLoader=null;getAudioFilePath(e){const t=this.director.sourceId;return ws(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(QE||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),vi.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,Nn&&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(){ps._audioBuffers.clear()}handleAudioLoading(e,t){this._audioLoader||(this._audioLoader=new c.AudioLoader);const i=this.getAudioFilePath(e.asset.clip);if(ps._audioBuffers.get(i)){const o=ps._audioBuffers.get(i);return o.then(r=>{r&&t.setBuffer(r)}),o}Nn&&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 ps._audioBuffers.set(i,n),n}}class lf extends hl{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 Tc extends hl{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(Nn&&console.log("Trigger signal",e,n.time,n),this.didTrigger[i]=!0,this.receivers?.length<=0)Sh.invoke(n.asset);else for(const l of this.receivers)l&&l.invoke(n.asset)}else n.emitOnce||(this.didTrigger[i]=!1)}}}class cf extends hl{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,br);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 YE=Object.defineProperty,xx=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&YE(e,t,n),n};const on=x("debugtimeline"),Ly=class Sm extends R{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:(on||yi())&&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(){on&&console.log(`[Timeline] Awake '${this.name}'`,this),this.rebuildGraph(),!this.isValid()&&(on||A())&&(on?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(){on&&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(){on&&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&&!vi.userInteractionRegistered&&this.waitForAudio;)await _s(200)}this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate(),ge.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 fi.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,on&&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 Ec||o.evaluate(i)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=Ic(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)):(on&&console.log("Resolved binding",n,"to",o),t.outputs[i]=o)}else if(n===null){if(t.outputs.splice(i,1),Sm.createTrackFunctions[t.type])continue;t.type!==fi.Audio&&t.type!==fi.Control&&t.type!==fi.Marker&&t.type!==fi.Signal&&console.warn("Missing binding",n,t.name,t.type,this.name,this.playableAsset.name)}}if(t.type===fi.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):(on&&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(ds,this.context);for(const t of this.playableAsset.tracks){const i=t.type,n=Sm.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===fi.Animation){if(!t.clips||t.clips.length<=0){on&&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,lt);l&&(r=l)}const a=r?.gameObject?.animations;if(a){const l=new Ec;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)),on&&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 lt&&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 y=l.mixer.clipAction(m);l.actions.push(y),l.models.push(d)}this._animationTracks.push(l)}}}else if(t.type===fi.Audio){if(!t.clips||t.clips.length<=0)continue;const o=new ps;o.director=this,o.track=t,o.audioSource=t.outputs.find(r=>r instanceof vi),this._audioTracks.push(o),e||(e=this.context.mainCameraComponent?.gameObject.addComponent(ds)),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===fi.Marker){if(t.markers){const o=new Tc;o.director=this,o.track=t;const r=new lf;r.director=this,r.track=t;for(const a of t.markers)a.type===Dy.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,Sh);a&&(o.receivers.push(a),this._signalTracks.push(o))}r!==null&&r.models.length>0&&this._markerTracks.push(r)}}else if(t.type===fi.Signal){const o=new Tc;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===fi.Control){const o=new cf;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)}};xx([f()],Ly.prototype,"playOnAwake");xx([f()],Ly.prototype,"extrapolationMode");let br=Ly;var KE=Object.defineProperty,hf=(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};class Vr extends R{isGizmo=!1;translationSnap=1;rotationSnapAngle=15;scaleSnap=.25;get control(){return this._control}_control;orbit;onEnable(){if(!(this.isGizmo&&!Nc)&&this.context.mainCamera&&(this._control||(this._control=new X.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(pn);i&&(i.fastMode=!0,i.requestOwnership())}else{const i=this.gameObject.getComponentInParent(pn);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()}}hf([f()],Vr.prototype,"isGizmo");hf([f()],Vr.prototype,"translationSnap");hf([f()],Vr.prototype,"rotationSnapAngle");hf([f()],Vr.prototype,"scaleSnap");var ZE=Object.defineProperty,JE=Object.getOwnPropertyDescriptor,df=(s,e,t,i)=>{for(var n=i>1?void 0:i?JE(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&&ZE(e,t,n),n};class Iy{texture=null;rect}df([f(c.Texture)],Iy.prototype,"texture",2);let dl=class extends lh{set image(e){this.sprite||(this.sprite=new Iy),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))}};df([f(Iy)],dl.prototype,"sprite",1);df([f()],dl.prototype,"pixelsPerUnitMultiplier",2);class uf extends lh{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))}}df([f(c.Texture)],uf.prototype,"mainTexture",1);var eT=Object.defineProperty,tT=Object.getOwnPropertyDescriptor,Mi=(s,e,t,i)=>{for(var n=i>1?void 0:i?tT(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&&eT(e,t,n),n};const $o=x("debugbutton");class Do{colorMultiplier;disabledColor;fadeDuration;highlightedColor;normalColor;pressedColor;selectedColor}Mi([f()],Do.prototype,"colorMultiplier",2);Mi([f(te)],Do.prototype,"disabledColor",2);Mi([f()],Do.prototype,"fadeDuration",2);Mi([f(te)],Do.prototype,"highlightedColor",2);Mi([f(te)],Do.prototype,"normalColor",2);Mi([f(te)],Do.prototype,"pressedColor",2);Mi([f(te)],Do.prototype,"selectedColor",2);class iT{disabledTrigger;highlightedTrigger;normalTrigger;pressedTrigger;selectedTrigger}class Ds extends R{click(){this.onClick?.invoke()}onClick=new ne;_isHovered=0;onPointerEnter(e){const t=e.event.pointerType==="mouse"&&e.button===0;t&&(this._isHovered+=1),$o&&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),$o&&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){$o&&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){$o&&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===pu.Mouse)&&($o&&(console.warn("Button Click",this.onClick),Se("CLICKED button "+this.name+" at "+this.context.time.frameCount)),this.onClick&&this.onClick.listenerCount>0&&(this.onClick.invoke(),e.use(),this.context.accessibility.focus(this),$o))){const t=this.gameObject.worldPosition;t.add(this.gameObject.worldUp.multiplyScalar(1+Math.random()*.5)),B.DrawLabel(t,"CLICK:"+Date.now(),.1,1+Math.random()*.5)}}colors;transition;animationTriggers;animator;set interactable(e){this._interactable=e,this._image&&(this._image.setInteractable(e),e?this._image.setState("normal"):this._image.setState("disabled"))}get interactable(){return this._interactable}_interactable=!0;set_interactable(e){this.interactable=e}awake(){super.awake(),$o&&console.log(this),this._isInit=!1,this.init()}start(){this._image?.setInteractable(this.interactable),this.gameObject.getComponentInParent(Sc)||this.gameObject.addComponent(ku)}onEnable(){super.onEnable(),this.context.accessibility.updateElement(this,{role:"button",label:this.gameObject.name+" button",hidden:!1})}onDisable(){super.onDisable(),this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this),this._isHovered&&this.context.input.unsetCursor("pointer")}_requestedAnimatorTrigger;*setAnimatorTriggerAtEndOfFrame(e){this._requestedAnimatorTrigger=e,yield,yield,this._requestedAnimatorTrigger==e&&this.animator?.setTrigger(e)}_isInit=!1;_image;init(){this._isInit||(this._isInit=!0,this._image=S.getComponent(this.gameObject,dl),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()}}Mi([f(ne)],Ds.prototype,"onClick",2);Mi([f(Do)],Ds.prototype,"colors",2);Mi([f()],Ds.prototype,"transition",2);Mi([f(iT)],Ds.prototype,"animationTriggers",2);Mi([f(lt)],Ds.prototype,"animator",2);Mi([f()],Ds.prototype,"interactable",1);var nT=Object.defineProperty,ff=(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&&nT(e,t,n),n};const Hs=x("debuginputfield"),Ch=class G extends R{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 G.active===this}textComponent;placeholder;onValueChanged;onEndEdit;static active=null;static activeTime=-1;static htmlField=null;static htmlFieldFocused=!1;inputEventFn;_iosEventFn;start(){Hs&&console.log(this.name,this)}onEnable(){G.htmlField||(G.htmlField=document.createElement("input"),G.htmlField.style.width="0px",G.htmlField.style.height="0px",G.htmlField.style.padding="0px",G.htmlField.style.border="none",G.htmlField.style.overflow="hidden",G.htmlField.style.caretColor="transparent",G.htmlField.style.outline="none",G.htmlField.classList.add("ar"),G.htmlField.onfocus=()=>G.htmlFieldFocused=!0,G.htmlField.onblur=()=>G.htmlFieldFocused=!1,document.body.append(G.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),G.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(){G.htmlField?.removeEventListener("keyup",this.inputEventFn),this.onDeselected(),this._iosEventFn&&window.removeEventListener("click",this._iosEventFn)}clear(){G.active===this&&G.htmlField?(G.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){Hs&&console.log("CLICK",e,G.active),G.activeTime=this.context.time.time,G.active!==this&&this.startCoroutine(this.activeLoop(),ge.LateUpdate),this.selectInputField()}*activeLoop(){for(this.onSelected();G.active===this&&!(this.context.input.getPointerClicked(0)&&this.context.time.time-G.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){if(G.active!==this&&(Hs&&console.log("Select",this.name,this,G.htmlField,this.context.isInXR,this.context.arOverlayElement,this.textComponent?.text,G.htmlField?.value),G.active?.onDeselected(),G.active=this,this.placeholder&&S.setActive(this.placeholder.gameObject,!1),G.htmlField)){if(G.htmlField.value=this.textComponent?.text||"",Hs&&console.log("set input field value",G.htmlField.value),this.context.isInXR){const e=this.context.arOverlayElement;e&&e.append(G.htmlField)}this.selectInputField()}}onDeselected(){G.active===this&&(G.active=null,Hs&&console.log("Deselect",this.name,this),G.htmlField&&(G.htmlField.blur(),document.body.append(G.htmlField)),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&S.setActive(this.placeholder.gameObject,!0),G.htmlField&&this.onEndEdit?.invoke(G.htmlField.value))}update(){G.active===this&&this.textComponent?.markDirty()}onInput(e){if(G.active===this){if(Hs&&console.log(e.code,e,G.htmlField?.value,this.textComponent?.text),e.code==="Escape"||e.code==="Enter"){this.onDeselected();return}G.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&S.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){if(this.textComponent&&G.htmlField){const e=this.textComponent.text,t=G.htmlField.value,i=this.textComponent.text!==G.htmlField.value;this.textComponent.text=G.htmlField.value,i&&(Hs&&console.log("[InputField] value changed:",t,e),this.onValueChanged?.invoke(t,e))}}selectInputField(){G.htmlField&&(Hs&&console.log("Focus Inputfield",G.htmlFieldFocused,G.htmlField),G.htmlField.setSelectionRange(G.htmlField.value.length,G.htmlField.value.length),exports.DeviceUtilities.isiOS()?(G.htmlField.style.display="block",G.htmlField.focus({preventScroll:!0})):setTimeout(()=>G.htmlField?.focus(),1))}processInputOniOS(){const e=this.context.physics.raycast();if(!e.length)return;const i=e[0].object,n=bg(i);(n?.gameObject===this.gameObject||n?.gameObject.parent===this.gameObject)&&this.selectInputField()}};ff([f(Dt)],Ch.prototype,"textComponent");ff([f(Dt)],Ch.prototype,"placeholder");ff([f(ne)],Ch.prototype,"onValueChanged");ff([f(ne)],Ch.prototype,"onEndEdit");let jy=Ch;var sT=Object.defineProperty,Sx=(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&&sT(e,t,n),n};class Ph extends R{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 X.InteractiveGroup;t.listenToPointerEvents(this.context.renderer,this.context.mainCamera),this.gameObject.add(t);const i=new X.HTMLMesh(e);t.add(i),i.visible=!1;const n=i.material;n.transparent=!0,setTimeout(()=>{i.visible=!0;const o=hu(this.gameObject).clone();Fc(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()}}Sx([f()],Ph.prototype,"id");Sx([f()],Ph.prototype,"keepAspect");const oT={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]}]},rT={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 pf 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"?oT:rT,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 aT=Object.defineProperty,mf=(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 Oh=class Cx extends R{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,A()&&!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),Bc(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=qe.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 xt("lookat "+this.name,Et.sceneStartTrigger(),ue.lookAtCameraAction(n,void 0,this.invertForward?Bi.back:Bi.forward,this.keepUpDirection?Bi.up:Bi.zero));e.addBehavior(o)}}};mf([f(c.Object3D)],Oh.prototype,"target");mf([f()],Oh.prototype,"invertForward");mf([f()],Oh.prototype,"keepUpDirection");mf([f()],Oh.prototype,"copyTargetRotation");let By=Oh;var lT=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&&lT(e,t,n),n};class ul extends R{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($i)||this.gameObject.addComponent($i)}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.")&&(A()&&console.warn("URL is not valid, adding https:// to the start of the URL",this.url),this.url="https://"+this.url)}}Fy([f()],ul.prototype,"url");Fy([f()],ul.prototype,"mode");Fy([f()],ul.prototype,"clickable");Cu(s=>{const e=s.domElement.getAttribute("clickthrough");if(t(e)){const i=s.scene.addComponent(gf);Em(s.domElement,"clickthrough",()=>{const n=s.domElement.getAttribute("clickthrough");i.enabled=t(n)})}function t(i){return i!==null&&i!=="0"&&i!=="false"}});class gf extends R{_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 cT=Object.defineProperty,yf=(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 hT=x("debugcursor");class $r extends R{static NAME="CursorFollow";damping=0;useFullPage=!0;keepDistance=!0;snapToSurface=!1;_distance=-1;updateDistance(e=!1){!e&&this.keepDistance&&this._distance!==-1||(this._distance=this.gameObject.worldPosition.distanceTo(this.context.mainCamera.worldPosition))}awake(){this._distance=-1}onEnable(){this._distance=-1,window.addEventListener("pointermove",this._onPointerMove)}onDisable(){window.removeEventListener("pointermove",this._onPointerMove)}_ndc_x=0;_ndc_y=0;_onPointerMove=e=>{if(!this.useFullPage)return;const t=e.clientX,i=e.clientY,n=this.context.domX,o=this.context.domY,r=this.context.domWidth,a=this.context.domHeight;this._ndc_x=(t-n)/r*2-1,this._ndc_y=-(i-o)/a*2+1};lateUpdate(){this.updateDistance();const e=this.useFullPage?this._ndc_x:this.context.input.mousePositionRC.x,t=this.useFullPage?this._ndc_y:this.context.input.mousePositionRC.y,i=this.context.mainCamera,n=i.worldPosition,o=F(e,t,1).unproject(i);o.sub(n).normalize();const r=F(o).multiplyScalar(this._distance).add(n);let a=r;if(this.damping>0){const l=this.gameObject.worldPosition;l.lerp(r,this.context.time.deltaTime/this.damping),this.gameObject.worldPosition=l,a=l}else this.gameObject.worldPosition=r;if(this.snapToSurface){wp.origin=a,wp.direction=o.multiplyScalar(-1);const l=this.context.physics.raycastFromRay(wp);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,hT&&B.DrawLine(h.point,h.normal.add(h.point),65280)}}}}yf([f()],$r.prototype,"damping");yf([f()],$r.prototype,"useFullPage");yf([f()],$r.prototype,"keepDistance");yf([f()],$r.prototype,"snapToSurface");const wp=new c.Ray;var dT=Object.defineProperty,uT=Object.getOwnPropertyDescriptor,fl=(s,e,t,i)=>{for(var n=i>1?void 0:i?uT(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&&dT(e,t,n),n};exports.HoverAnimation=class extends R{type="linear";duration=.1;scaleFactor=1.1;hovered=null;idle=null;animation=null;start(){this.idle||(this.idle=Hn.emptyClip()),(!this.hovered||!(this.hovered instanceof c.AnimationClip))&&(this.hovered=Hn.createScaleClip({type:"linear",duration:this.duration||.1,scale:this.gameObject.scale,scaleFactor:this.scaleFactor||1.1})),this.animation??=this.gameObject.addComponent(Tt),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})}};fl([f()],exports.HoverAnimation.prototype,"type",2);fl([f()],exports.HoverAnimation.prototype,"duration",2);fl([f()],exports.HoverAnimation.prototype,"scaleFactor",2);fl([f(c.AnimationClip)],exports.HoverAnimation.prototype,"hovered",2);fl([f(c.AnimationClip)],exports.HoverAnimation.prototype,"idle",2);exports.HoverAnimation=fl([og],exports.HoverAnimation);var fT=Object.defineProperty,pl=(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&&fT(e,t,n),n};const kl=x("debugscroll");class Ls extends R{target=null;damping=0;invert=!1;htmlSelector=null;mode="window";changed=new ne;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),kl&&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 br)this.handleTimelineTarget(e,t),e.isPlaying&&e.pause(),e.evaluate();else if(e instanceof lt)e.setFloat("scroll",t);else if(e instanceof Tt)e.time=t*e.duration;else if(e instanceof vi){if(!e.duration)return;e.time=t*e.duration}else if(e instanceof Zi)e.position01=t;else if(e instanceof Pt)e.intensity=t;else if(e instanceof c.Object3D){const i=e;i["needle:scrollbounds"]===void 0&&(i["needle:scrollbounds"]=ri(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=Wb.get(e);if(!n){n=[],Wb.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=Px(d),kl&&console.debug(`ScrollMarker #${d} (${h.time.toFixed(2)}) found`,h.element),!h.element){(kl||A())&&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+`
|
|
1435
|
-
`,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)?(A()||kl)&&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"}))}Pn.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=pT(p),y=1-Math.abs(m-.5)*2,_=`marker${l}`;if(m>0&&m<=1){const g=h.time+(u-h.time)*m;Pn.push({name:_,time:g,weight:y}),o+=y}else l===0&&m<=0?(Pn.push({name:_,time:0,weight:1}),o+=1):l===n.length-1&&m>=1&&(Pn.push({name:_,time:i,weight:1}),o+=1)}}if(Pn.length<=0&&a<=0)e.time=t*i;else if(Pn.length>0){let l=Pn[0].time;if(Pn.length>1)for(const d of Pn){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),kl&&this.context.time.frame%30===0&&console.log(`[ScrollFollow ] Timeline ${e.name}: ${l.toFixed(3)}`,Pn.map(d=>`[${d.name} ${(d.weight*100).toFixed(0)}%]`).join(", "))}}}pl([f([R,c.Object3D])],Ls.prototype,"target");pl([f()],Ls.prototype,"damping");pl([f()],Ls.prototype,"invert");pl([f()],Ls.prototype,"htmlSelector");pl([f()],Ls.prototype,"mode");pl([f(ne)],Ls.prototype,"changed");const Wb=new WeakMap,Pn=[],xp=new Array;let Sp=!0;function Px(s){return Sp?(Sp=!1,xp.length=0,document.querySelectorAll("[data-timeline-marker]").forEach((t,i)=>{xp[i]=t}),Sp=!1,Px(s)):xp[s]||null}function pT(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 Ox=Object.defineProperty,mT=Object.getOwnPropertyDescriptor,gT=(s,e,t)=>e in s?Ox(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,_f=(s,e,t,i)=>{for(var n=i>1?void 0:i?mT(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&&Ox(e,t,n),n},Uy=(s,e,t)=>gT(s,typeof e!="symbol"?e+"":e,t);const qs=x("debugviewbox"),yT=new te(.5,.5,.5,.5);exports.ViewBox=class extends R{referenceFieldOfView=-1;get mode(){return this._mode}set mode(e){e!==this._mode&&(this._mode=e,e==="once"&&(this._applyCount=0),(qs||this.debug)&&console.debug("[ViewBox] Set mode:",e))}_mode="continuous";debug=!1;onEnable(){(qs||this.debug||A())&&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(){(qs||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)){(qs||this.debug)&&B.DrawWireBox(this.gameObject.worldPosition,this.gameObject.worldScale,yT);return}(qs||this.debug)&&B.DrawWireBox(this.gameObject.worldPosition,this.gameObject.worldScale,14540032,0,!0,this.gameObject.worldQuaternion);const t=this.context.mainCamera;if(!t||!(t instanceof c.PerspectiveCamera))return;if((this.referenceFieldOfView===void 0||this.referenceFieldOfView===-1)&&(this.referenceFieldOfView=t.fov,console.debug("[ViewBox] No referenceFieldOfView set, using camera fov:",this.referenceFieldOfView)),this.referenceFieldOfView===void 0||this.referenceFieldOfView<=0){(qs||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 y=this.gameObject.worldPosition,_=this.gameObject.worldScale,g=t.worldPosition,w=g.distanceTo(y),b=Math.max(_.x,_.y,_.z),v=F(g).sub(y);if(w<b){(this.debug||qs)&&console.warn("[ViewBox] Moving camera out of bounds",w,"<",b);const $=F(v);$.y*=1e-8,$.normalize();const ee=b-w,J=g.add($.multiplyScalar(ee));t.worldPosition=J.lerp(g,1-this.context.time.deltaTime)}const E=F(y);t.worldToLocal(E),t.lookAt(y),t.updateMatrixWorld();const O=this.referenceFieldOfView*Math.PI/180,M=2*Math.tan(O/2)*w,D=M*t.aspect,L=this.projectBoxIntoCamera(t,1),j=L.maxX-L.minX,V=L.maxY-L.minY,k=this.fit(j*t.aspect,V,D/a,M/l)/(M*.5),N=F(y);N.project(t),this.context.focusRectSettings.offsetX=N.x,this.context.focusRectSettings.offsetY=N.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=[F(-i,-i,-i),F(i,-i,-i),F(-i,i,-i),F(i,i,-i),F(-i,-i,i),F(i,-i,i),F(-i,i,i),F(i,i,i)];let o=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY,a=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY;for(let h=0;h<n.length;h++){const d=n[h];d.applyMatrix4(this.gameObject.matrixWorld),d.project(e),d.x<o&&(o=d.x),d.x>r&&(r=d.x),d.y<a&&(a=d.y),d.y>l&&(l=d.y)}return qs&&(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};Uy(exports.ViewBox,"instances",[]);Uy(exports.ViewBox,"_tempProjectionMatrix",new c.Matrix4);Uy(exports.ViewBox,"_tempProjectionMatrixInverse",new c.Matrix4);_f([f()],exports.ViewBox.prototype,"referenceFieldOfView",2);_f([f()],exports.ViewBox.prototype,"mode",1);_f([f()],exports.ViewBox.prototype,"debug",2);exports.ViewBox=_f([og],exports.ViewBox);var _T=Object.defineProperty,ml=(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&&_T(e,t,n),n};class Is extends R{get activeAndEnabled(){return!0}side="none";controller=!0;hands=!1;controlVisibility=!0;useGripSpace=!1;resetTransformAfterXRSession=!0;_startPosition=new c.Vector3;_startRotation=new c.Quaternion;_startScale=new c.Vector3;onEnterXR(e){this._startPosition.copy(this.gameObject.position),this._startRotation.copy(this.gameObject.quaternion),this._startScale.copy(this.gameObject.scale)}onUpdateXR(e){if(!this.enabled)return;const t=e.xr.getController(this.side);if(t){if(t.hand&&!this.hands){this.controlVisibility&&(this.gameObject.visible=!1);return}else if(!this.controller){this.controlVisibility&&(this.gameObject.visible=!1);return}this.controlVisibility&&(this.gameObject.visible=!0),this.useGripSpace||t.targetRayMode==="transient-pointer"?(this.gameObject.worldPosition=t.gripWorldPosition,this.gameObject.worldQuaternion=t.gripWorldQuaternion,this.gameObject.worldScale=F(t.xr.rigScale,t.xr.rigScale,t.xr.rigScale).multiply(this._startScale)):(this.gameObject.worldPosition=t.rayWorldPosition,this.gameObject.worldQuaternion=t.rayWorldQuaternion,this.gameObject.worldScale=F(t.xr.rigScale,t.xr.rigScale,t.xr.rigScale).multiply(this._startScale))}}onLeaveXR(e){this.resetTransformAfterXRSession&&(this.gameObject.position.copy(this._startPosition),this.gameObject.quaternion.copy(this._startRotation),this.gameObject.scale.copy(this._startScale))}}ml([f()],Is.prototype,"side");ml([f()],Is.prototype,"controller");ml([f()],Is.prototype,"hands");ml([f()],Is.prototype,"controlVisibility");ml([f()],Is.prototype,"useGripSpace");ml([f()],Is.prototype,"resetTransformAfterXRSession");function Mx(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.
|
|
1436
|
-
|
|
1437
|
-
Example to request camera-access in global scope:
|
|
1438
|
-
NeedleXRSession.onSessionRequestStart(evt => {
|
|
1439
|
-
evt.init.optionalFeatures = evt.init.optionalFeatures || [];
|
|
1440
|
-
evt.init.optionalFeatures.push('camera-access');
|
|
1441
|
-
});
|
|
1442
|
-
`),A()&&Uc("No camera feed available - please request the 'camera-access' feature before starting WebXR or add the ARCameraBackground component to your scene"),!1;const n=t.getViewerPose(s.xr.getReferenceSpace());if(n)for(const o of n.views)if("camera"in o&&o.camera){let r=s.xr.getBinding();if(r||(r=new XRWebGLBinding(t.session,s.getContext())),r){let a=null;if("getCameraImage"in r){bT(s,e);const l=s.properties.get(e);if(l)return a=r.getCameraImage(o.camera),l.__webglTexture=a,!0;console.warn("No texture properties found for target texture")}}else console.error(o.camera,s.xr)}else console.error("NO CAMERA IN VIEW");else console.error(s.xr.getReferenceSpace(),t);return!1}const Gb=new WeakMap;function bT(s,e){const t=Gb.get(e)||new WeakSet;if(t.has(s))return;t.add(s),Gb.set(e,t),console.debug("Initialize texture for camera feed");const i=new c.MeshBasicMaterial,n=new c.PlaneGeometry,o=new c.Scene;o.add(new c.Mesh(n,i));const r=new c.PerspectiveCamera;i.map=e,s.render(o,r)}function vT(s,e,t,i="image/webp",n){return zy({context:s,width:e,height:t,mimeType:i,camera:n})}function zy(s){s||(s={});const{transparent:e=!1}=s;let{mimeType:t,context:i,width:n,height:o,camera:r}=s;if(!i&&(i=ce.Current,!i))return console.error("Can not save screenshot: No needle-engine context found or provided."),null;if(!r&&(r=i.mainCamera,!r))return console.error("No camera found"),null;const a=i.renderer,l=a.xr.enabled&&a.xr.isPresenting;if(l&&i.currentFrameEvent!=ge.EarlyUpdate)return console.warn("Screenshot: defer to access XR frame"),new Promise(D=>{xs(L=>{const j=zy(s);D(j)},ge.EarlyUpdate,{once:!0})});const h=a.domElement,d=h.width,u=h.height;n||(n=d),o||(o=u);const p=n,m=o;let y=window.devicePixelRatio||1,_=1;i.devicePixelRatio==="auto"||i.devicePixelRatio==="manual"?_=1:_=i.devicePixelRatio/window.devicePixelRatio,y*=_,n/=y,o/=y,n=Math.floor(n),o=Math.floor(o),a.xr.isPresenting&&a.xr.getFrame();const g=a.xr.enabled;a.xr.enabled=!1,a.xr.isPresenting=!1,h.style.width=`${n}px`,h.style.height=`${o}px`;const w=a.getRenderTarget(),b=a.getClearColor(new c.Color),v=a.getClearAlpha(),E=i.scene.background,O="aspect"in r?r.aspect:null;try{const M=s.render_events!==!1,D=new Array;M&&($a(i.scene,Ht,D),D.forEach(k=>{if(k?.onBeforeRender(),k.isInstancingActive&&k.instances)for(let N=0;N<k.instances?.length;N++){const $=k.instances[N];ls($.object,!0)}})),e&&(i.scene.background=null,a.setClearColor(0,0)),s.background&&(i.scene.background=null,a.setClearColor(s.background),s.background instanceof te&&a.setClearAlpha(s.background.a)),e&&a.setClearAlpha(0),a.setSize(n,o,!1),"cam"in r&&(r=r.threeCamera),r instanceof c.PerspectiveCamera&&(r.aspect=n/o,r.updateProjectionMatrix());const L="type"in s&&s.type==="texture";let j=null;L&&(j=new c.WebGLRenderTarget(n,o,{wrapS:c.MirroredRepeatWrapping,wrapT:c.MirroredRepeatWrapping,format:1023}),a.setRenderTarget(j));let V=h;if(l?(j&&console.error('Taking XR screenshots with { type: "texture" } is currently not supported.'),V=exports.InternalScreenshotUtils.compositeWithCameraImage({width:p,height:m,scene:i.scene,camera:r,renderer:a})):i.renderNow(r||null),r instanceof c.PerspectiveCamera&&O!=null&&(r.aspect=O,r.updateProjectionMatrix()),M&&D.forEach(k=>k.onAfterRender()),!t&&"download_filename"in s&&s.download_filename)switch(s.download_filename.split(".").pop()?.toLowerCase()){case"png":t="image/png";break;case"jpg":case"jpeg":t="image/jpeg";break;case"webp":t="image/webp";break}if(e&&s.trim===!0){const k=wT(V);k&&(V=k)}if("type"in s){if(s.type==="texture")return j?(s.target&&(s.target.image=j?.texture.image,s.target.needsUpdate=!0),j.texture.offset.set(0,-1),j.texture.needsUpdate=!0,j.texture):(console.error("No target texture found"),null);if(s.type==="blob")return new Promise((N,$)=>{V.toBlob(ee=>{N(ee)},t)});if(s.type==="share")return new Promise((N,$)=>{V.toBlob(ee=>{if(ee&&"share"in navigator){let J="file_type"in s&&s.file_type||t;t||(J="image/png");const he=J?.split("/")[1]||"png",Q=new File([ee],"filename"in s?s.filename||`screenshot.${he}`:`screenshot.${he}`,{type:J});return navigator.share({title:"title"in s?s.title:void 0,text:"text"in s?s.text:void 0,url:"url"in s?s.url:void 0,files:[Q]}).catch(_e=>{console.warn("User cancelled share",_e.message)}).finally(()=>{N({blob:ee,shared:!0})})}return{blob:ee,shared:!1}},t)})}const W=V.toDataURL(t);if("download_filename"in s&&s.download_filename){let k=s.download_filename;if(exports.DeviceUtilities.isMobileDevice()&&typeof window<"u"){const N=k+"_screenshots",$=k.split("."),ee=$.pop()?.toLowerCase();let J=0;localStorage.getItem(N)&&(J=parseInt(sessionStorage.getItem(N)||"0")),J>0&&(k=`${$.join()}-${J}.${ee}`),J+=1,sessionStorage.setItem(N,J.toString())}kx(W,k)}return W}finally{a.setRenderTarget(w),i.scene.background=E,a.setSize(d,u,!1),a.setClearColor(b,v),O!=null&&r instanceof c.PerspectiveCamera&&(r.aspect=O,r.updateProjectionMatrix()),a.xr.enabled=g,a.xr.isPresenting=l,l||i.updateSize(!0)}return null}function wT(s){if(!("document"in globalThis))return null;const e=document.createElement("canvas");e.width=s.width,e.height=s.height;const t=e.getContext("2d");if(!t)return null;t.drawImage(s,0,0);const i=e.width,n=e.height,r=t.getImageData(0,0,i,n).data;let a=n,l=i,h=0,d=0;for(let _=0;_<n;_++)for(let g=0;g<i;g++){const w=(_*i+g)*4;r[w+3]!==0&&(g<l&&(l=g),g>d&&(d=g),_<a&&(a=_),_>h&&(h=_))}const u=d-l+1,p=h-a+1,m=document.createElement("canvas"),y=m.getContext("2d");return y?(m.width=u,m.height=p,y.drawImage(e,l,a,u,p,0,0,u,p),m):null}let Rl=null;function kx(s,e){if(s){if(!s.startsWith("data:image")){console.error("Can not save image: Data url is not an image",s);return}Rl||(Rl=document.createElement("a")),Rl.href=s,Rl.download=e,Rl.click()}}exports.InternalScreenshotUtils=void 0;(s=>{let e=null,t=null,i=null,n=null,o=null;function r(h){const{renderer:d,width:u,height:p}=h,m=d.xr.enabled,y=d.getRenderTarget(),_=d.autoClear,g=u,w=p,b=u/p;(!i||i.width!==g||i.height!==w)&&(i??=new c.WebGLRenderTarget(g,w,{colorSpace:c.SRGBColorSpace}),i.width=g,i.height=w,i.samples=4,i.texture.repeat.y=-1,i.texture.offset.y=1),(!o||o.width!==g||o.height!==w)&&(o=document.createElement("canvas"),o.width=g,o.height=w,o.style.position="fixed",o.style.top="0px",o.style.right="0px",o.style.width="300px",o.style.height=`${300/b}px`,o.style.zIndex="1000",o.style.pointerEvents="none",o.style.opacity="1.0",o.style.willChange="contents"),e||(e=l({defines:{DECODE_VIDEO_TEXTURE:!0}})),t||(t=l()),n||(n=new c.Texture),d.xr.updateCamera(h.camera),d.xr.enabled=!1,d.autoClear=!1,d.clear(),d.setSize(g,w),d.setRenderTarget(i),Mx(h.renderer,n)||console.error("Could not update texture from XR frame");const E=S.findObjectOfType(Mh);return E?E.setTexture(n):(e.setTexture(n),d.render(e,h.camera)),d.clearDepth(),d.setSize(g,w),d.render(h.scene,h.camera),d.setRenderTarget(null),t.setTexture(i.texture),d.render(t,h.camera),o.getContext("2d",{alpha:!1}).drawImage(d.domElement,0,0,o.width,o.height),d.setRenderTarget(y),d.xr.enabled=m,d.autoClear=_,o}s.compositeWithCameraImage=r;const a=`
|
|
1443
|
-
uniform sampler2D t2D;
|
|
1444
|
-
varying vec2 vUv;
|
|
1445
|
-
|
|
1446
|
-
void main() {
|
|
1447
|
-
|
|
1448
|
-
vec4 texColor = texture2D( t2D, vUv );
|
|
1449
|
-
|
|
1450
|
-
#ifdef DECODE_VIDEO_TEXTURE
|
|
1451
|
-
|
|
1452
|
-
// inline sRGB decode (TODO: Remove this code when https://crbug.com/1256340 is solved)
|
|
1453
|
-
texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );
|
|
1454
|
-
|
|
1455
|
-
#endif
|
|
1456
|
-
|
|
1457
|
-
gl_FragColor = texColor;
|
|
1458
|
-
#include <tonemapping_fragment>
|
|
1459
|
-
#include <colorspace_fragment>
|
|
1460
|
-
}
|
|
1461
|
-
`;function l(h){const d=h?.material||new c.ShaderMaterial({name:"BackgroundMaterial",uniforms:c.UniformsUtils.clone(c.ShaderLib.background.uniforms),vertexShader:c.ShaderLib.background.vertexShader,fragmentShader:a,defines:h?.defines,side:c.FrontSide,depthTest:!1,depthWrite:!1,fog:!1});Object.defineProperty(d,"map",{get:function(){return this.threeTexture}});const u=new c.Mesh(new c.PlaneGeometry(2,2),d);return Ld(u,!1),u.geometry.deleteAttribute("normal"),u.renderOrder=-1e6,u.setTexture=function(p){d.uniforms.t2D.value=p},u}s.makeFullscreenPlane=l})(exports.InternalScreenshotUtils||(exports.InternalScreenshotUtils={}));var xT=Object.defineProperty,ST=(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&&xT(e,t,n),n};const Hb=x("debugarcamera");class Mh extends R{onBeforeXR(e,t){e==="immersive-ar"&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("camera-access"),Hb&&console.warn("Requesting camera-access"))}onEnterXR(e){e.xr.mode==="immersive-ar"&&(this.backgroundPlane&&(this.context.scene.add(this.backgroundPlane),this.backgroundPlane.visible=!1),this.backgroundPlane&&this.context.scene.add(this.backgroundPlane),this.context.pre_render_callbacks.push(this.preRender))}onLeaveXR(e){this.backgroundPlane&&this.backgroundPlane.removeFromParent();const t=this.context.pre_render_callbacks.indexOf(this.preRender);t>=0&&this.context.pre_render_callbacks.splice(t,1)}backgroundTint=new te(1,1,1,1);get background(){return this.backgroundPlane}backgroundPlane;threeTexture;forceTextureInitialization=(function(){const e=new c.MeshBasicMaterial,t=new c.PlaneGeometry,i=new c.Scene;i.add(new c.Mesh(t,e));const n=new c.PerspectiveCamera;return function(r,a){e.map=a,r.render(i,n),Hb&&console.warn("Force texture initialization")}})();preRender=()=>{if(!this||!this.gameObject)return;if(this.context.renderer.xr.getFrame()){if(!this.threeTexture&&this.context.renderer&&(this.threeTexture=new c.Texture,this.forceTextureInitialization(this.context.renderer,this.threeTexture)),this.backgroundPlane===void 0){const i=this.backgroundTint;this.backgroundPlane=exports.InternalScreenshotUtils.makeFullscreenPlane({material:new c.ShaderMaterial({name:"BackgroundMaterial",uniforms:{...c.UniformsUtils.clone(c.ShaderLib.background.uniforms),tint:{value:new c.Vector4(i.r,i.g,i.b,i.a)}},vertexShader:c.ShaderLib.background.vertexShader,fragmentShader:CT,side:c.DoubleSide,depthTest:!1,depthWrite:!1,fog:!1})})}this.backgroundPlane.parent!==this.scene&&this.scene.add(this.backgroundPlane),this.backgroundPlane.material instanceof c.ShaderMaterial&&this.backgroundPlane.material.uniforms.tint.value.set(this.backgroundTint.r,this.backgroundTint.g,this.backgroundTint.b,this.backgroundTint.a),this.updateFromFrame()}};onBeforeRender(e){this.updateFromFrame()}updateFromFrame(){this.threeTexture&&this.context.xr?.mode==="immersive-ar"&&(Mx(this.context.renderer,this.threeTexture),this.setTexture(this.threeTexture))}setTexture(e){this.backgroundPlane&&(this.threeTexture=e,this.backgroundPlane.setTexture(this.threeTexture),this.backgroundPlane.visible=!0)}}ST([f(te)],Mh.prototype,"backgroundTint");const CT=`
|
|
1462
|
-
uniform sampler2D t2D;
|
|
1463
|
-
uniform vec4 tint;
|
|
1464
|
-
|
|
1465
|
-
varying vec2 vUv;
|
|
1466
|
-
|
|
1467
|
-
void main() {
|
|
1468
|
-
|
|
1469
|
-
vec4 texColor = texture2D( t2D, vUv );
|
|
1470
|
-
texColor.w = 1.0;
|
|
1471
|
-
|
|
1472
|
-
// inline sRGB decode
|
|
1473
|
-
texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );
|
|
1474
|
-
|
|
1475
|
-
gl_FragColor = texColor * tint;
|
|
1476
|
-
|
|
1477
|
-
#include <tonemapping_fragment>
|
|
1478
|
-
#include <colorspace_fragment>
|
|
1479
|
-
}
|
|
1480
|
-
`;var PT=Object.defineProperty,Lo=(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&&PT(e,t,n),n};const hc=x("debugimagetracking");class Na{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 _i(()=>new c.Vector3,20);static _rotationBuffer=new _i(()=>new c.Quaternion,20);_position;_rotation;ensureTransformData(){if(!this._position){this._position=Na._positionBuffer.get(),this._rotation=Na._rotationBuffer.get();const e=this._pose.transform,t=q.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 js{constructor(e){this.image=e.url,this.widthInMeters=e.widthInMeters,e.object instanceof c.Object3D?this.object=new Z({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}}Lo([f(URL)],js.prototype,"image");Lo([f()],js.prototype,"widthInMeters");Lo([f(Z)],js.prototype,"object");Lo([f()],js.prototype,"createObjectInstance");Lo([f()],js.prototype,"imageDoesNotMove");Lo([f()],js.prototype,"hideWhenTrackingIsLost");class OT{constructor(e,t){this.exporter=e,this.component=t,hc&&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&&(hc||A())&&(fe("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=dc.get(t.image),r=await(await(await Ww(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 kh extends R{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),qb(e.image)),t&&this.setPrimaryImage(e)}trackedImages=[];smooth=!0;trackedImageIndexMap=new Map;get supported(){return this._supported}_supported=!0;awake(){if(hc&&console.log(this),!!this.trackedImages)for(const e of this.trackedImages)e.image&&qb(e.image)}onEnable(){Wn.beforeExport.addEventListener(this.onBeforeUSDZExport)}onDisable(){Wn.beforeExport.removeEventListener(this.onBeforeUSDZExport)}onBeforeUSDZExport=e=>{this.activeAndEnabled&&this.trackedImages?.length&&e.exporter.extensions.push(new OT(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=dc.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()&&fe(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 Na(this,h,r.image,r.measuredSize,a,d);this.currentImages.push(u)}else hc&&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,fe(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(hc&&Se(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=q.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))}}}}Lo([f(js)],kh.prototype,"trackedImages");Lo([f()],kh.prototype,"smooth");const dc=new Map,cd=new Map;async function qb(s){if(dc.has(s))return cd.has(s)?cd.get(s):Promise.resolve(!0);const e=new Promise(t=>{dc.set(s,null);const i=document.createElement("img");i.src=s,i.addEventListener("load",async()=>{const n=await createImageBitmap(i);dc.set(s,n),t(!0)})});return cd.set(s,e),e.finally(()=>{cd.delete(s)}),e}var MT=Object.defineProperty,gl=(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&&MT(e,t,n),n};const Wo=x("debugplanetracking");class Bs extends R{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),Wo){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),B.DrawLabel(this.center.add(this.labelOffset),(u.xrData.semanticLabel||"plane").toUpperCase()+`
|
|
1481
|
-
`+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),Wo&&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()):Wo&&console.warn("No normals helper found for mesh",i.mesh)}),bi(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 y=this.createGeometry(l);if(p.mesh instanceof c.Mesh)p.mesh.geometry.dispose(),p.mesh.geometry=y,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=y,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()}Wo&&(console.log("Plane updated, id="+p.id,p),p.mesh.traverse(_=>{if(!(_ instanceof c.Mesh))return;const g=_.userData.normalsHelper;g&&g.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;Wo?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 Z("","",p)}if(!this.dataTemplate.asset)this.dataTemplate.loadAssetAsync();else{const p=S.instantiate(this.dataTemplate.asset);if(p.name="xr-tracked-plane",u=p,Um(p,!1),p instanceof c.Mesh)we(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&&(we(_.geometry),_.geometry=this.createGeometry(l),this.makeOccluder(_,_.material,this.occluder&&!this.dataTemplate));const m=p.getComponent(xo);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 y={id:this._dataId++,xrData:l,timestamp:l.lastChangedTime,mesh:p,collider:m};o.set(l,y),Wo&&console.log("New plane detected, id="+y.id,y,{hasCollider:!!m,isGroup:p instanceof c.Group});try{const _=new CustomEvent("plane-tracking",{detail:{type:"plane-added",context:y}});this.dispatchEvent(_)}catch(_){console.error(_)}}}u&&(d?(u.visible=!0,u.matrix.fromArray(d.transform.matrix),u.matrix.premultiply(this._flipForwardMatrix)):u.visible=!1,Wo&&u.traverse(p=>{if(p instanceof c.Mesh)if(p.userData.normalsHelper)p.userData.normalsHelper.update();else{const m=new X.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}}gl([f(Z)],Bs.prototype,"dataTemplate");gl([f()],Bs.prototype,"occluder");gl([f()],Bs.prototype,"initiateRoomCaptureIfNoData");gl([f()],Bs.prototype,"usePlaneData");gl([f()],Bs.prototype,"useMeshData");gl([f()],Bs.prototype,"runInVR");var kT=Object.defineProperty,RT=(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&&kT(e,t,n),n};const Xb=x("debugwebxr");class bf extends R{priority=0;get isActive(){return this.activeAndEnabled&&this.gameObject.visible}setAsActiveXRRig(){q.active?.setRigActive(this)}setPriority(e){this.priority=e}awake(){if(Xb){const e=new c.Object3D;e.position.y+=.5,this.gameObject.add(e);const t=e.addNewComponent(Ar);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),Xb&&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)}}RT([f()],bf.prototype,"priority");class ET extends R{toggleKey="KeyP";update(){this.context.input.isKeyDown(this.toggleKey)&&this.context.domElement.classList.toggle("presentation-mode")}}P.add("AlignmentConstraint",qc);P.add("Animation",Tt);P.add("Animator",lt);P.add("AudioListener",ds);P.add("AudioSource",vi);P.add("Avatar_Brain_LookAt",Pc);P.add("Avatar_MouthShapes",Kc);P.add("Avatar_MustacheShake",xg);P.add("AvatarBlink_Simple",Cr);P.add("AvatarEyeLook_Rotation",Cg);P.add("AxesHelper",Ha);P.add("BasicIKConstraint",Og);P.add("BoxHelperComponent",_t);P.add("Camera",si);P.add("CharacterController",Pr);P.add("CharacterControllerInput",Cs);P.add("SphereCollider",qa);P.add("BoxCollider",Tu);P.add("MeshCollider",xo);P.add("CapsuleCollider",bs);P.add("ContactShadows",Zc);P.add("LogStats",kg);P.add("DeleteBox",ao);P.add("Deletable",Eg);P.add("DeviceFlag",Au);P.add("DragControls",Zo);P.add("DropListener",Os);P.add("Duplicatable",Fg);P.add("EventListEvent",Mu);P.add("EventTrigger",Iu);P.add("GltfExportBox",Ng);P.add("GltfExport",$g);P.add("VariantAction",Hg);P.add("ChangeTransformOnClick",Rr);P.add("ChangeMaterialOnClick",qg);P.add("SetActiveOnClick",Xg);P.add("HideOnStart",Ii);P.add("EmphasizeOnClick",Ya);P.add("PlayAudioOnClick",fo);P.add("PlayAnimationOnClick",Oc);P.add("PreliminaryAction",Ka);P.add("PreliminaryTrigger",nh);P.add("VisibilityAction",sh);P.add("TapGestureTrigger",Yg);P.add("USDZExporter",Wn);P.add("Fog",tl);P.add("BoxGizmo",Ar);P.add("GridHelper",il);P.add("GroundProjectedEnv",Xn);P.add("UsageMarker",Jc);P.add("Interactable",Rg);P.add("FixedJoint",gy);P.add("HingeJoint",ch);P.add("Light",Pt);P.add("LODGroup",Hu);P.add("LookAtConstraint",yy);P.add("NeedleMenu",Yn);P.add("NestedGltf",sl);P.add("Networking",vy);P.add("OffsetConstraint",Dr);P.add("CameraTargetReachedEvent",Cc);P.add("OrbitControls",de);P.add("ParticleSystemRenderer",Yi);P.add("ParticleSystem",kc);P.add("Attractor",rl);P.add("PlayerColor",Ua);P.add("Antialiasing",uh);P.add("BloomEffect",Zu);P.add("ChromaticAberration",fh);P.add("ColorAdjustments",Ro);P.add("DepthOfField",bn);P.add("EffectWrapper",Rc);P.add("PixelationEffect",ph);P.add("ScreenSpaceAmbientOcclusion",Ts);P.add("ScreenSpaceAmbientOcclusionN8",vn);P.add("SharpeningEffect",gh);P.add("TiltShiftEffect",Zn);P.add("ToneMappingEffect",go);P.add("Vignette",Ur);P.add("Volume",zr);P.add("ReflectionProbe",os);P.add("Renderer",Ht);P.add("MeshRenderer",th);P.add("SkinnedMeshRenderer",jg);P.add("Rigidbody",$e);P.add("SceneSwitcher",We);P.add("ScreenCapture",Eo);P.add("SeeThrough",As);P.add("ShadowCatcher",_h);P.add("RemoteSkybox",ef);P.add("SmoothFollow",nf);P.add("SpatialTriggerReceiver",Gn);P.add("SpatialTrigger",sf);P.add("SpectatorCamera",of);P.add("SplineContainer",Nr);P.add("SplineWalker",Zi);P.add("SpriteRenderer",ci);P.add("SyncedCamera",Ey);P.add("SyncedRoom",wn);P.add("SyncedTransform",pn);P.add("TestRunner",Ty);P.add("TestSimulateUserData",Ay);P.add("PlayableDirector",br);P.add("SignalReceiver",Sh);P.add("AnimationTrackHandler",Ec);P.add("AudioTrackHandler",ps);P.add("MarkerTrackHandler",lf);P.add("SignalTrackHandler",Tc);P.add("ControlTrackHandler",cf);P.add("TransformGizmo",Vr);P.add("BaseUIComponent",Wi);P.add("UIRootComponent",oh);P.add("Button",Ds);P.add("Canvas",Fa);P.add("CanvasGroup",mo);P.add("EventSystem",Gt);P.add("Graphic",ah);P.add("MaskableGraphic",lh);P.add("Image",dl);P.add("RawImage",uf);P.add("InputField",jy);P.add("VerticalLayoutGroup",ry);P.add("HorizontalLayoutGroup",ay);P.add("GridLayoutGroup",ly);P.add("Outline",el);P.add("ObjectRaycaster",$i);P.add("GraphicRaycaster",ku);P.add("SpatialGrabRaycaster",pr);P.add("RectTransform",mn);P.add("SpatialHtml",Ph);P.add("Text",Dt);P.add("EnvironmentScene",pf);P.add("LookAt",By);P.add("OpenURL",ul);P.add("VideoPlayer",tt);P.add("Voip",wo);P.add("ClickThrough",gf);P.add("CursorFollow",$r);P.add("HoverAnimation",exports.HoverAnimation);P.add("ScrollFollow",Ls);P.add("ViewBox",exports.ViewBox);P.add("Avatar",po);P.add("XRControllerFollow",Is);P.add("XRControllerModel",vs);P.add("XRControllerMovement",xi);P.add("TeleportTarget",Vu);P.add("WebARCameraBackground",Mh);P.add("WebARSessionRoot",Ui);P.add("WebXR",$u);P.add("AvatarMarker",Oe);P.add("WebXRImageTracking",kh);P.add("WebXRPlaneTracking",Bs);P.add("XRRig",bf);P.add("XRFlag",ji);P.add("PlayerSync",ey);P.add("PlayerState",zi);P.add("PresentationMode",ET);const uc=rt,TT=x("debugtypestore");TT&&console.log(P);function AT(s,e){const i=b0(s,e);return i!==void 0?i:null}const DT=new k1,Cp=Symbol("deserialize-queue");async function LT(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 wt(i));const a=e.indexOf("?");e=a===-1?e:e.substring(0,a);const l=new lg(t.scene);l.gltfId=e,l.context=s,l.gltf=t,l.nodeToObject=n?.nodeToObjectMap,l.implementationInformation=DT;let h=s[Cp];if(h||(h=s[Cp]=[]),t.scenes)for(const d of t.scenes)await Om(l,d,h,o,0);if(t.children)for(const d of t.children)await Om(l,d,h,o,0);s.new_scripts_pre_setup_callbacks.push(()=>{const d=s[Cp];if(d){for(const u of d)IT(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 Cm=Symbol("original-component-name"),ea=new Map;function Pm(s,e,t,i){if(e===null||!s)return;const n=s.guid,o=s.guid;o?.length&&(ea.has(o)||(uc&&console.log('Creating InstanceIdProvider with key "'+o+'" for object '+s.name),ea.set(o,new wt(o))));const r=o&&ea.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?ea.has(l)||(uc&&console.log('Creating InstanceIdProvider with key "'+l+'" for component '+a[Cm]),ea.set(l,new wt(l))):uc&&console.warn("Can not create IdProvider: component "+a[Cm]+" has no guid",a.guid);const h=ea.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 El=[];async function Om(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,ja(h,a,s.implementationInformation),h.context=s.context,"guid"in a&&(h[Jl]=a.guid),h[Cm]=a.name,nr(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 uc&&console.debug("unknown component: "+a.name),El.includes(a.name)||El.push(a.name)}catch(l){console.error(a.name+" - "+l.message,l)}}if(e.children)for(const r of e.children)await Om(s,r,t,i,n+1);if(El.length>0&&n===0){const r=El.join(", ");console.warn(`Unknown components in scene: ${r}`),El.length=0,yi()&&Se(`<strong>Unknown components in scene</strong>:
|
|
1482
|
-
|
|
1483
|
-
${r}
|
|
1484
|
-
|
|
1485
|
-
This could mean you forgot to add a npmdef to your ExportInfo
|
|
1486
|
-
<a href="https://engine.needle.tools/docs/project_structure.html#creating-and-installing-a-npmdef" target="_blank">documentation</a>`,{type:gi.Warn})}}function IT(s,e){const{instance:t,compData:i,obj:n}=s;e.object=n,e.target=t,Wd(t,i,e),uc&&console.debug("add "+i.name,i,t)}class Rx{createBuiltinComponents(e,t,i,n,o){return LT(e,t,i,n,o)}writeBuiltinComponentData(e,t){return AT(e,t)}parseSync(e,t,i,n){return Ax(e,t,i,n)}loadSync(e,t,i,n,o){return Ny(e,t,i,n,o)}}Vm(Rx);const Ex=x("printGltf")||x("printgltf"),jT=x("debugfileformat");async function Tx(s,e,t){const i=await ww(s,{useExtension:!0})||"unknown";jT&&console.debug(`Determined file type: '${i}' for url '${s}'`,{registeredModelLoaderCallbacks:ma});for(const n of ma){const{callback:o}=n,r=o({context:e,url:s,mimetype:i});if(r instanceof Promise&&await r,r)return console.debug(`Using custom loader (${n.name||"unnamed"}) for ${i} at '${s}'`),r}switch(i){case"unsupported":return null;default:case"unknown":{console.warn(`Unknown file type (${i}). Needle Engine will fallback to the GLTFLoader - To support more model formats please create a Needle loader plugin.
|
|
1487
|
-
Use import { NeedleEngineModelLoader } from "@needle-tools/engine" namespace to register your loader.`,s);const n=new X.GLTFLoader;return await tu(n,e,s,t),n}case"model/fbx":case"model/vnd.autodesk.fbx":return new X.FBXLoader;case"model/obj":return new X.OBJLoader;case"model/vnd.usdz+zip":case"model/vnd.usd+zip":case"model/vnd.usda+zip":return console.warn(i.toUpperCase()+" files are not supported."),null;case"model/gltf+json":case"model/gltf-binary":case"model/vrm":{const n=new X.GLTFLoader;return await tu(n,e,s,t),n}case"application/materialx+xml":return new hM}}function BT(s,e){return Ny(e?.context||U.Current,s,s,e?.seed||null,e?.onprogress)}async function Ax(s,e,t,i){typeof t!="string"&&(console.warn("Parse gltf binary without path, this might lead to errors in resolving extensions. Please provide the source path of the gltf/glb file",t,typeof t),t=""),Ex&&console.log("Parse glTF",t);const n=await Tx(t,s,t);if(!n)return;const{componentsExtension:o}=Dx(n,s);if(n instanceof X.OBJLoader){typeof e!="string"&&(e=new TextDecoder().decode(e));const a=n.parse(e);return await fc(n,s,t,a,i,o)}if(!(n instanceof X.GLTFLoader)){if(!("parse"in n)||typeof n.parse!="function"){console.error("Loader does not support parse");return}const a=n.parse(e,t);return await fc(n,s,t,a,i,o)}return new Promise((a,l)=>{try{let h=t.split("?")[0].trimEnd();const d=h.split("/");d.length>0&&d[d.length-1]!==""&&d.pop(),h=d.join("/"),h.endsWith("/")||(h+="/"),n.resourcePath=h,n.parse(e,"",async u=>{const p=await fc(n,s,t,u,i,o);a(p)},u=>{console.error('Loading asset at "'+t+`" failed
|
|
1488
|
-
`,u),a(void 0)})}catch(h){console.error(h),l(h)}})}async function Ny(s,e,t,i,n){UT(e);const o=await Tx(e,s,t);if(!o)return;const{componentsExtension:r}=Dx(o,s);if(!(o instanceof X.GLTFLoader)){const a=await o.loadAsync(e,n);return await fc(o,s,e,a,i,r)}return new Promise((a,l)=>{try{o.load(e,async h=>{const d=await fc(o,s,t,h,i,r);a(d)},h=>{n?.call(o,h)},h=>{console.error('Loading asset at "'+e+`" failed
|
|
1489
|
-
`,h),a(void 0)})}catch(h){console.error(h),l(h)}})}function Dx(s,e){const t=Dg(s);return s instanceof X.GLTFLoader&&gg(s,e),{componentsExtension:t}}async function fc(s,e,t,i,n,o){if(Ex&&console.warn("Loaded",t,i),i==null)return console.error(`Loaded model is null '${t}' - please make sure the loader is registered correctly`),{scene:new c.Object3D,animations:[],scenes:[]};if(typeof i!="object")return console.error(`Loaded model is not an object '${t}' - please make sure the loader is registered correctly`),{scene:new c.Object3D,animations:[],scenes:[]};if(i instanceof c.Object3D)i={scene:i,animations:i.animations,scenes:[i]};else if(i instanceof c.BufferGeometry){const r=new c.MeshStandardMaterial({color:new c.Color(14540253)}),a=new c.Mesh(i,r);i={scene:a,animations:[],scenes:[a]}}else Array.isArray(i.scenes)===!1&&console.error(`[Needle Engine] The loaded model object does not have a scenes property '${t}' - please make sure the loader is registered correctly and three.js is not imported multiple times.`);return t.includes("?")&&(t=t.split("?")[0]),zT(s,i),Av(i)&&(Mw(t,i,e),await un().createBuiltinComponents(e,t,i,n,o||void 0)),await FT(i.scene,e,e.mainCamera),i}async function FT(s,e,t){t||(t=e.mainCamera);try{t?await e.renderer.compileAsync(s,t,e.scene).catch(i=>{console.warn(i.message)}):p1(s,e)}catch(i){console.warn(i?.message||i)}}function UT(s){if(new URL(s,window.location.href).href.startsWith("file://")){const t=`Hi - it looks like you are trying to load a local file which will not work. You need to use a webserver to serve your files.
|
|
1490
|
-
Please refer to the documentation on <a href="https://fwd.needle.tools/needle-engine/docs/local-server">https://docs.needle.tools</a> or ask for help in our <a href="https://discord.needle.tools">discord community</a>`;Se(t),console.warn(t)}}function zT(s,e){if("scenes"in e){for(const t of e.scenes)if(t&&!t.animations?.length)for(const i of e.animations)t.animations.includes(i)||t.animations.push(i)}if(s instanceof X.FBXLoader||s instanceof X.OBJLoader){let t=e;t instanceof c.Object3D||(t=e.scene||e.scenes.find(i=>i)),t.traverse(i=>{const n=i;n?.isMesh&&zm(n,n.material)})}}const Tl=x("debugoverlay"),Lx="ar",NT="quit-ar";class VT{get ARContainer(){return this.arContainer}arContainer=null;currentSession=null;_createdAROnlyElements=[];_reparentedObjects=[];contentElement=null;originalDomOverlayParent=null;requestEndAR=()=>{this.onRequestedEndAR()};onBegin(e,t,i){if(this.currentSession=i,this.arContainer=t,exports.DeviceUtilities.isMozillaXR()||exports.DeviceUtilities.isNeedleAppClip()){const n=e.domElement.children;for(let o=0;o<n?.length;o++){const r=n[o];if(!r||r===this.arContainer)return;this._reparentedObjects.push({el:r,previousParent:r.parentElement}),this.arContainer?.appendChild(r)}t?(this.originalDomOverlayParent=t.parentNode,this.originalDomOverlayParent&&(console.log("Reparent DOM Overlay to body",t,t.style.display),t.style.display="",t.style.visibility="",document.body.appendChild(t))):console.warn("WebXRViewer: No DOM Overlay found")}this.ensureQuitARButton(this.arContainer)}onEnd(e){for(const t of this._createdAROnlyElements)t.remove&&t.remove();for(const t of this._reparentedObjects){const i=t.el;t.previousParent?.appendChild(i)}this._reparentedObjects.length=0,exports.DeviceUtilities.isMozillaXR()&&setTimeout(()=>{const t=e.renderer.domElement;t&&e.domElement.shadowRoot?.prepend(t);const i=document.querySelectorAll("*");for(var n=0;n<i.length;n++){const o=i[n];o&&o._displayChanged!==void 0&&o._displayWas!==void 0&&(o.style.display=o._displayWas)}},10)}createOverlayContainer(e){if(this.contentElement)return this.contentElement;Tl&&console.log("Setup overlay container");const t=e.shadowRoot.querySelector(".content");this.contentElement=t;const i=e.shadowRoot.querySelector(".overlay-content");return i&&t.appendChild(i),Tl&&!exports.DeviceUtilities.isMobileDevice()&&this.ensureQuitARButton(t),t}onRequestedEndAR(){this.currentSession&&(this.currentSession.end(),this.currentSession=null)}ensureQuitARButton(e){const t=document.createElement("slot");if(t.style.display="contents",t.style.padding="10px",t.setAttribute("name","quit-ar"),this.appendElement(t,e),this._createdAROnlyElements.push(t),t.style.pointerEvents="auto",exports.DeviceUtilities.isNeedleAppClip()){globalThis.NEEDLE_ENGINE_APPCLIP_DISABLE_MENU=!0;const a=document.querySelector('meta[name="viewport"]');a&&!a.getAttribute("content")?.includes("viewport-fit=")&&a.setAttribute("content",a.getAttribute("content")+",viewport-fit=cover")}const i=document.querySelector(`.${NT}`);if(i){i.addEventListener("click",this.requestEndAR),Tl&&i.addEventListener("click",()=>console.log("Clicked quit-ar button"));return}t.addEventListener("click",this.requestEndAR),Tl&&t.addEventListener("click",()=>console.log("Clicked fallback close button"));const n=document.createElement("div");n.style.cssText=`
|
|
1491
|
-
position: fixed;
|
|
1492
|
-
top: 0;
|
|
1493
|
-
right: 0;
|
|
1494
|
-
z-index: 600;
|
|
1495
|
-
pointer-events: all;
|
|
1496
|
-
padding-top: env(safe-area-inset-top, 0px);
|
|
1497
|
-
padding-right: calc(env(safe-area-inset-right, 0px) + 10px);
|
|
1498
|
-
`,this.appendElement(n,t);var o=document.createElementNS("http://www.w3.org/2000/svg","svg");o.classList.add("quit-ar-button"),o.setAttribute("width","40px"),o.setAttribute("height","40px"),o.style.cssText=`
|
|
1499
|
-
background: rgba(255, 255, 255, .4);
|
|
1500
|
-
-webkit-backdrop-filter: blur(8px);
|
|
1501
|
-
backdrop-filter: blur(8px);
|
|
1502
|
-
border-radius: 50%;
|
|
1503
|
-
box-shadow: 0 0 5px rgba(0,0,0,.3);
|
|
1504
|
-
outline: 1px solid rgba(255, 255, 255, .6);
|
|
1505
|
-
display: flex;
|
|
1506
|
-
justify-content: center;
|
|
1507
|
-
align-items: center;
|
|
1508
|
-
`,n.appendChild(o);var r=document.createElementNS("http://www.w3.org/2000/svg","path");r.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),r.setAttribute("stroke","#000000"),r.setAttribute("stroke-width","2px"),r.style.cssText=`
|
|
1509
|
-
/**filter: drop-shadow(0 0px 1.2px rgba(0,0,0,.7));**/
|
|
1510
|
-
`,o.appendChild(r),Tl&&console.log("Created fallback close button",o,e)}appendElement(e,t){return t.shadowRoot?t.shadowRoot.appendChild(e):t.appendChild(e)}}const Qo=x("debugloading"),Al=x("debugloadingrendering");x("debuglicense");class $T{className;additionalClasses}let Dl=0,Qb;function Vy(s){Qo&&console.log(s.progress.loaded.toFixed(0)+"/"+s.progress.total.toFixed(0),s);const e=s.count,t=s.progress.total;t===0||t===void 0?(Qb!==s.name&&(Dl=0),Qb=s.name,Dl+=(1-Dl)*.001,Qo&&fe("Loading "+s.name+" did not report total size")):Dl=s.progress.loaded/t;const i=s.index/e+Dl/e;return I.clamp01(i)}class Ac{static LoadingContainerClassName="loading";loadingProgress=0;_element;_progress=0;_allowCustomLoadingElement=!0;_loadingElement;_loadingTextContainer=null;_loadingBar=null;_loadingBarFinishedColor=null;_messageContainer=null;_loadingElementOptions;constructor(e,t){this._element=e,this._loadingElementOptions=t}async onLoadingBegin(e){const t=this._element.shadowRoot||this._element;if(Qo&&console.warn("Begin Loading"),!this._loadingElement){for(let i=0;i<t.children.length;i++){const n=t.children[i];if(n.classList.contains(Ac.LoadingContainerClassName)){if(!this._allowCustomLoadingElement){Qo&&console.warn("Remove custom loading container"),t.removeChild(n);continue}this._loadingElement=this.createLoadingElement(n)}}this._loadingElement||(this._loadingElement=this.createLoadingElement())}this._progress=0,this.loadingProgress=0,this._loadingElement.style.display="flex",t.appendChild(this._loadingElement),this.smoothProgressLoop(),this.setMessage(e??"")}onLoadingUpdate(e,t){if(!this._loadingElement?.parentNode)return;let i=0;typeof e=="number"?i=e:("index"in e&&(i=Vy(e)),!t&&"name"in e&&this.setMessage("loading "+e.name)),this.loadingProgress=i,t&&this.setMessage(t),this.updateDisplay()}onLoadingFinished(){Qo&&console.warn("Finished Loading"),Al||(this.loadingProgress=1,this.onDoneLoading())}setMessage(e){this._messageContainer&&(this._messageContainer.innerText=e)}_progressLoop;smoothProgressLoop(){if(this._progressLoop)return;let e=1/12;Al&&(e=1/500,typeof Al=="number"&&(e*=Al)),this._progressLoop=setInterval(()=>{this.loadingProgress>=.95&&!Al&&(e=.9),this._progress=I.lerp(this._progress,this.loadingProgress,e*this.loadingProgress),this.updateDisplay()},e)}onDoneLoading(){if(this._loadingElement){Qo&&console.log("Hiding loading element");const e=this._loadingElement;e.animate([{opacity:1},{opacity:0}],{duration:200,easing:"ease-in-out"}).addEventListener("finish",()=>{e.style.display="none",e.remove()})}this._progressLoop&&clearInterval(this._progressLoop),this._progressLoop=null}updateDisplay(){const e=this._progress,t=(e*100).toFixed(0)+"%";this._loadingBar&&(this._loadingBar.style.width=e*100+"%",e>=1&&this._loadingBarFinishedColor&&(this._loadingBar.style.background=this._loadingBarFinishedColor)),this._loadingTextContainer&&(this._loadingTextContainer.textContent=t)}createLoadingElement(e){Qo&&!e&&console.log("Creating loading element"),this._loadingElement=e||document.createElement("div");let t=this._element.getAttribute("loading-style");(!t||t==="auto")&&(window.matchMedia("(prefers-color-scheme: dark)").matches?t="dark":t="light");const i=Vn();if(!e){this._loadingElement.style.position="absolute",this._loadingElement.style.width="100%",this._loadingElement.style.height="100%",this._loadingElement.style.left="0",this._loadingElement.style.top="0",this._loadingElement.style.overflow="hidden";const y=this._element.getAttribute("loading-background");y?this._loadingElement.style.background=y:this._loadingElement.style.backgroundColor="transparent",this._loadingElement.style.display="flex",this._loadingElement.style.alignItems="center",this._loadingElement.style.justifyContent="center",this._loadingElement.style.zIndex="0",this._loadingElement.style.flexDirection="column",this._loadingElement.style.pointerEvents="none",this._loadingElement.style.color="white",this._loadingElement.style.fontFamily='system-ui, Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"',this._loadingElement.style.fontSize="1rem",t==="light"?this._loadingElement.style.color="rgba(0,0,0,.6)":this._loadingElement.style.color="rgba(255,255,255,.3)"}const n=this._loadingElementOptions?.className??Ac.LoadingContainerClassName;if(this._loadingElement.classList.add(n),this._loadingElementOptions?.additionalClasses)for(const y of this._loadingElementOptions.additionalClasses)this._loadingElement.classList.add(y);const o=document.createElement("div");o.style.cssText=`
|
|
1511
|
-
position: relative;
|
|
1512
|
-
display: flex;
|
|
1513
|
-
flex-direction: column;
|
|
1514
|
-
align-items: center;
|
|
1515
|
-
justify-content: center;
|
|
1516
|
-
width: 100%;
|
|
1517
|
-
height: 100%;
|
|
1518
|
-
pointer-events: none;
|
|
1519
|
-
`,this._loadingElement.appendChild(o);const r=this._element.getAttribute("poster");if(r!==null&&r!=="0"){const y=document.createElement("div"),_=r?.length?"0px":"50px";y.style.cssText=`
|
|
1520
|
-
position: absolute;
|
|
1521
|
-
left: 0;
|
|
1522
|
-
top: 0;
|
|
1523
|
-
bottom: 0;
|
|
1524
|
-
right: 0;
|
|
1525
|
-
z-index: -1;
|
|
1526
|
-
overflow: hidden;
|
|
1527
|
-
|
|
1528
|
-
margin: -${_};
|
|
1529
|
-
background: url('${r?.length?r:"/include/poster.webp"}') center center no-repeat;
|
|
1530
|
-
background-size: cover;
|
|
1531
|
-
filter: blur(${_});
|
|
1532
|
-
`,this._loadingElement.appendChild(y)}const a=document.createElement("img"),l="80%",h="15%",d=".2s";if(a.style.userSelect="none",a.style.objectFit="contain",a.style.transform="translateY(30px)",a.style.opacity="0.0000001",a.style.transition=`transform 1s ease-out ${d}, opacity .3s ease-in-out ${d}`,a.src=Da,i&&this._element){const y=this._element.getAttribute("logo-src");y&&(a.src=y,setTimeout(()=>{a.style.opacity="1",a.style.transform="translateY(0px)"},1))}a.style.width=`${l}`,a.style.height=`min(1000px, max(${h}, 50px))`,o.appendChild(a);const u=document.createElement("div");u.style.cssText=`
|
|
1533
|
-
display: flex;
|
|
1534
|
-
flex-direction: column;
|
|
1535
|
-
align-items: center;
|
|
1536
|
-
justify-content: center;
|
|
1537
|
-
width: 100%;
|
|
1538
|
-
opacity: 0;
|
|
1539
|
-
transition: opacity 1s ease-in-out 4s;
|
|
1540
|
-
`,setTimeout(()=>{u.style.opacity="1"},1),this._loadingElement.appendChild(u);const p=document.createElement("div"),m=100;return p.style.display="flex",p.style.width=m+"%",p.style.height="5px",p.style.position="absolute",p.style.left="0",p.style.top="0px",p.style.opacity="0",p.style.transition="opacity 1s ease-in-out",p.style.backgroundColor="rgba(240,240,240,.5)",setTimeout(()=>{p.style.opacity="1"},1),this._loadingElement.appendChild(p),this._loadingBar=document.createElement("div"),p.appendChild(this._loadingBar),this._loadingBar.style.backgroundAttachment="fixed",this._loadingBar.style.background="#c4c4c4ab",this._loadingBarFinishedColor="#ddddddab",this._loadingBar.style.width="0%",this._loadingBar.style.height="100%",this._loadingElement}}Vm(Rx);const be=x("debugwebcomponent"),Yb="needle-engine",Ix="vr",jx="desktop",WT=[Lx,Ix,jx],Ll="ar-session-active",Il="desktop-session-active",GT=["src","hash","camera-controls","dracoDecoderPath","dracoDecoderType","ktx2DecoderPath","public-key","version","tone-mapping","tone-mapping-exposure","background-blurriness","background-color","environment-intensity","focus-rect","loadstart","progress","loadfinished"];class $y extends HTMLElement{static get observedAttributes(){return GT}get loadingProgress01(){return this._loadingProgress01}get loadingFinished(){return this.loadingProgress01>.999}get cameraControls(){const e=this.getAttribute("camera-controls");return e==null?null:!(e===null||e==="False"||e==="false"||e==="0"||e==="none")}set cameraControls(e){e===null?this.removeAttribute("camera-controls"):this.setAttribute("camera-controls",e?"true":"false")}getContext(){return new Promise((e,t)=>{if(this._context&&this.loadingFinished)e(this._context);else{const i=()=>{this.removeEventListener("loadfinished",i),this._context&&this.loadingFinished&&e(this._context)};this.addEventListener("loadfinished",i)}})}get context(){return this._context}_context;_overlay_ar;_loadingProgress01=0;_loadingView;_previousSrc=null;_didFullyLoad=!1;_didInitialize=!1;constructor(){super(),this.attachShadow({mode:"open",delegatesFocus:!0});const e=document.createElement("template");e.innerHTML=`<style>
|
|
1541
|
-
@import url('https://fonts.googleapis.com/css2?family=Roboto+Flex:opsz,wght@8..144,100..1000&display=swap');
|
|
1542
|
-
|
|
1543
|
-
:host {
|
|
1544
|
-
position: absolute;
|
|
1545
|
-
display: block;
|
|
1546
|
-
width: max(600px, 100%);
|
|
1547
|
-
height: max(300px, 100%);
|
|
1548
|
-
touch-action: none;
|
|
1549
|
-
|
|
1550
|
-
-webkit-tap-highlight-color: transparent;
|
|
1551
|
-
}
|
|
1552
|
-
|
|
1553
|
-
@media (max-width: 600px) {
|
|
1554
|
-
:host {
|
|
1555
|
-
width: 100%;
|
|
1556
|
-
}
|
|
1557
|
-
}
|
|
1558
|
-
@media (max-height: 300px) {
|
|
1559
|
-
:host {
|
|
1560
|
-
height: 100%;
|
|
1561
|
-
}
|
|
1562
|
-
}
|
|
1563
|
-
|
|
1564
|
-
:host > div.canvas-wrapper {
|
|
1565
|
-
width: 100%;
|
|
1566
|
-
height: 100%;
|
|
1567
|
-
}
|
|
1568
|
-
|
|
1569
|
-
:host canvas {
|
|
1570
|
-
position: absolute;
|
|
1571
|
-
user-select: none;
|
|
1572
|
-
-webkit-user-select: none;
|
|
1573
|
-
|
|
1574
|
-
/** allow touch panning but no pinch zoom **/
|
|
1575
|
-
/** but this doesnt work yet:
|
|
1576
|
-
* touch-action: pan-x, pan-y;
|
|
1577
|
-
**/
|
|
1578
|
-
|
|
1579
|
-
-webkit-touch-callout: none;
|
|
1580
|
-
-webkit-user-drag: none;
|
|
1581
|
-
-webkit-user-modify: none;
|
|
1582
|
-
|
|
1583
|
-
left: 0;
|
|
1584
|
-
top: 0;
|
|
1585
|
-
}
|
|
1586
|
-
:host .content {
|
|
1587
|
-
position: absolute;
|
|
1588
|
-
top: 0;
|
|
1589
|
-
width: 100%;
|
|
1590
|
-
height: 100%;
|
|
1591
|
-
visibility: visible;
|
|
1592
|
-
z-index: 500; /* < must be less than the webxr buttons element */
|
|
1593
|
-
pointer-events: none;
|
|
1594
|
-
}
|
|
1595
|
-
:host .overlay-content {
|
|
1596
|
-
position: absolute;
|
|
1597
|
-
user-select: auto;
|
|
1598
|
-
pointer-events: all;
|
|
1599
|
-
}
|
|
1600
|
-
:host slot[name="quit-ar"]:hover {
|
|
1601
|
-
cursor: pointer;
|
|
1602
|
-
}
|
|
1603
|
-
:host .quit-ar-button {
|
|
1604
|
-
position: absolute;
|
|
1605
|
-
/** top: env(titlebar-area-y); this doesnt work **/
|
|
1606
|
-
top: 60px; /** camera access needs a bit more space **/
|
|
1607
|
-
right: 20px;
|
|
1608
|
-
z-index: 9999;
|
|
1609
|
-
}
|
|
1610
|
-
</style>
|
|
1611
|
-
<div class="canvas-wrapper"> <!-- this wrapper is necessary for WebXR https://github.com/meta-quest/immersive-web-emulator/issues/55 -->
|
|
1612
|
-
<canvas data-needle-engine-version=${ii}></canvas>
|
|
1613
|
-
</div>
|
|
1614
|
-
<div class="content">
|
|
1615
|
-
<slot class="overlay-content" style="display: contents;"></slot>
|
|
1616
|
-
</div>
|
|
1617
|
-
`,this.shadowRoot.appendChild(e.content.cloneNode(!0)),this.addEventListener("ready",this.onReady),this.addEventListener("error",this.onError)}ensureInitialized(){this._didInitialize||(this._didInitialize=!0,this.initializeDom())}initializeDom(){X0(),this.setAttribute("role","application"),this.setAttribute("aria-label","Needle Engine 3D scene")}connectedCallback(){if(be&&console.log("<needle-engine> connected"),this.ensureInitialized(),this.setPublicKey(),this.setVersion(),(this.getAttribute("tabindex")===null||this.getAttribute("tabindex")===void 0)&&this.setAttribute("tabindex","0"),this._overlay_ar=new VT,this.getOrCreateContext(),this.addEventListener("xr-session-started",this.onXRSessionStarted),this.onSetupDesktop(),!this.getAttribute("src")){const t=globalThis["needle:codegen_files"];be&&console.log('src is null, trying to load from globalThis["needle:codegen_files"]',t),t&&(be&&console.log('globalThis["needle:codegen_files"]',t),this.setAttribute("src",t))}be&&console.log("src",this.getAttribute("src"));const e=this._loadId;setTimeout(()=>{this.isConnected!==!1&&e===this._loadId&&this.onLoad()},1)}disconnectedCallback(){this.removeEventListener("xr-session-started",this.onXRSessionStarted),this._didFullyLoad=!1;const e=this.getAttribute("keep-alive"),t=e==null||e?.length>0&&e!=="true"&&e!=="1";be&&console.warn('<needle-engine> disconnected, keep-alive: "'+e+'"',typeof e,"Dispose=",t),t?(be&&console.warn("<needle-engine> dispose"),this._context?.dispose(),this._context=null,this._lastSourceFiles=null,this._loadId+=1):be&&console.warn("<needle-engine> is not disposed because keep-alive is set")}connectedMoveCallback(){}attributeChangedCallback(e,t,i){switch(be&&console.log("attributeChangedCallback",e,t,i),e){case"src":be&&console.warn(`<needle-engine src>
|
|
1618
|
-
changed from "`,t,'" to "',i,'"'),this.onLoad();break;case"hash":this._context&&(this._context.hash=i);break;case"loadstart":case"progress":case"loadfinished":typeof i=="string"&&i.length>0&&(be&&console.log(e+" attribute changed",i),this.registerEventFromAttribute(e,i));break;case"dracoDecoderPath":be&&console.log("dracoDecoderPath",i),q_(i);break;case"dracoDecoderType":i==="wasm"||i==="js"?(be&&console.log("dracoDecoderType",i),X_(i)):console.error("Invalid dracoDecoderType",i,"expected js or wasm");break;case"ktx2DecoderPath":be&&console.log("ktx2DecoderPath",i),Q_(i);break;case"tonemapping":case"tone-mapping":case"tone-mapping-exposure":case"background-blurriness":case"background-color":case"environment-intensity":{this.applyAttributes();break}case"public-key":{i!=no&&this.setPublicKey();break}case"version":{i!=ii&&this.setVersion();break}case"focus-rect":{const n=this.getAttribute("focus-rect");if(n){const o=this.getOrCreateContext();if(n===null)o.setCameraFocusRect(null);else if(typeof n=="string"&&n.length>0){const r=document.querySelector(n);r||console.warn(`No element found for focus-rect selector: ${n}`),o.setCameraFocusRect(r instanceof HTMLElement?r:null)}else n instanceof HTMLElement?o.setCameraFocusRect(n):console.warn("Invalid focus-rect value. Expected a CSS selector string or an HTMLElement.",n)}}break}}get toneMapping(){return this.getAttribute("tonemapping")||this.getAttribute("tone-mapping")}_loadId=0;_abortController=null;_lastSourceFiles=null;_createContextPromise=null;getOrCreateContext(){return this._context||(be&&console.warn("Create new context"),this._context=new U({domElement:this})),this._context}async onLoad(){if(!this.isConnected)return;const e=this.getOrCreateContext(),t=this.getSourceFiles();if(!this.checkIfSourceHasChanged(t,this._lastSourceFiles))return;this._abortController&&(be&&console.warn("Abort previous loading process"),this._abortController.abort(),this._abortController=null),this._lastSourceFiles=t;const i=++this._loadId;if((t==null||t.length<=0)&&(be&&console.warn("Clear scene",t),e.clear(),i!==this._loadId))return;const n=this.getAttribute("alias");this.classList.add("loading");const o=$n();this.ensureLoadStartIsRegistered();let r=this.dispatchEvent(new CustomEvent("loadstart",{detail:{context:e,alias:n},cancelable:!0}));if(o){const _=this.getAttribute("hide-loading-overlay");_!=null&&_!=="0"&&(r=!1)}r===!1&&!o&&(A()||(r=!0),console.warn("Needle Engine: You need a commercial license to override the default loading view. Visit https://needle.tools/pricing"),A()&&fe('You need a <a target="_blank" href="https://needle.tools/pricing">commercial license</a> to override the default loading view. This will not work in production.')),!this._loadingView&&r&&(this._loadingView=new Ac(this)),r&&(this._didFullyLoad!==!0?this._loadingView?.onLoadingBegin("begin load"):setTimeout(()=>{this._loadingView&&this._loadingProgress01<.3&&this._loadId===i&&this._loadingView.onLoadingBegin("begin load")},300)),be&&console.warn(`--------------
|
|
1619
|
-
Needle Engine: Begin loading `+i+`
|
|
1620
|
-
`,t),this.onBeforeBeginLoading();const a=[],l={context:this._context,name:"",progress:{},index:0,count:t.length,totalProgress01:this._loadingProgress01},h=new CustomEvent("progress",{detail:l}),d=new Array,u=new AbortController;this._abortController=u;const p={files:t,abortSignal:u.signal,onLoadingProgress:_=>{if(be&&console.debug("Loading progress: ",_),u.signal.aborted)return;const g=_.index;!d[g]&&_.name&&(d[g]=HT(_.name)),_.name=d[g],r&&this._loadingView?.onLoadingUpdate(_),l.name=_.name,l.progress=_.progress,this._loadingProgress01=Vy(_),l.totalProgress01=this._loadingProgress01,this.dispatchEvent(h)},onLoadingFinished:(_,g,w)=>{be&&console.debug(`Finished loading "${g}" (aborted? ${u.signal.aborted})`),!u.signal.aborted&&w&&a.push({src:g,file:w})}};qT(this);const m=this.getAttribute("hash");m!=null&&(e.hash=m),e.alias=n,this._createContextPromise=e.create(p);const y=await this._createContextPromise;if(this.applyAttributes(),be&&console.warn(`--------------
|
|
1621
|
-
Needle Engine: finished loading `+i+`
|
|
1622
|
-
`,t,`Aborted? ${u.signal.aborted}`),u.signal.aborted){console.log("Loading finished but aborted...");return}if(this._loadId!==i){console.log("Load id changed during loading process");return}this._loadingProgress01=1,r&&y&&this._loadingView?.onLoadingUpdate(1,"creating scene"),this._didFullyLoad=!0,this.classList.remove("loading"),this.classList.add("loading-finished"),this.dispatchEvent(new CustomEvent("loadfinished",{detail:{context:this._context,src:n,loadedFiles:a}}))}applyAttributes(){const e=this.getOrCreateContext();if(e.renderer){const o=G0(this.toneMapping);o!==void 0&&(e.renderer.toneMapping=o);const r=this.getAttribute("tone-mapping-exposure");if(r!=null){const a=parseFloat(r);isNaN(a)||(e.renderer.toneMappingExposure=a)}}const t=this.getAttribute("background-blurriness");if(t!=null){const o=parseFloat(t);isNaN(o)||(e.scene.backgroundBlurriness=o)}const i=this.getAttribute("environment-intensity");if(i!=null){const o=parseFloat(i);isNaN(o)||(e.scene.environmentIntensity=o)}const n=this.getAttribute("background-color");if(e.renderer)if(typeof n=="string"&&n.length>0){const o=te.fromColorRepresentation(n);be&&console.debug("<needle-engine> background-color changed, str:",n,"→",o),e.renderer.setClearColor(o,o.alpha),e.scene.background=null}else this.getAttribute("background-image")&&this.setAttribute("background-image",this.getAttribute("background-image"))}onXRSessionStarted=()=>{const e=this.getOrCreateContext(),t=e.xrSessionMode;t==="immersive-ar"?this.onEnterAR(e.xrSession):t==="immersive-vr"&&this.onEnterVR(e.xrSession),e.xrSession?.addEventListener("end",()=>{this.dispatchEvent(new CustomEvent("xr-session-ended",{detail:{session:e.xrSession,context:this._context,sessionMode:t}})),t==="immersive-ar"?this.onExitAR(e.xrSession):t==="immersive-vr"&&this.onExitVR(e.xrSession)})};onReady=()=>this._loadingView?.onLoadingFinished();onError=()=>this._loadingView?.setMessage("Loading failed!");getSourceFiles(){const e=this.getAttribute("src");if(!e)return[];let t;Array.isArray(e)?t=e:e.startsWith("[")&&e.endsWith("]")?t=JSON.parse(e):e.includes(",")?t=e.split(","):t=[e];for(let i=t.length-1;i>=0;i--){const n=t[i];(n==="null"||n==="undefined"||n?.length<=0)&&t.splice(i,1)}return t}checkIfSourceHasChanged(e,t){if(e?.length!==t?.length||e==null&&t!==null||e!==null&&t==null)return!0;if(e!==null&&t!==null){for(let i=0;i<e?.length;i++)if(e[i]!==t[i])return!0}return!1}_previouslyRegisteredMap=new Map;ensureLoadStartIsRegistered(){const e=this.getAttribute("loadstart");e&&this.registerEventFromAttribute("loadstart",e)}registerEventFromAttribute(e,t){const i=this._previouslyRegisteredMap.get(e);if(i&&(this._previouslyRegisteredMap.delete(e),this.removeEventListener(e,i)),typeof t=="string"&&t.length>0)try{const n=(0,eval)(t);typeof n=="function"&&(this._previouslyRegisteredMap.set(e,n),this.addEventListener(e,o=>n?.call(globalThis,this.getOrCreateContext(),o)))}catch(n){console.error("Error registering event "+e+'="'+t+`" failed with the following error:
|
|
1623
|
-
`,n)}}setPublicKey(){no&&no.length>0&&this.setAttribute("public-key",no)}setVersion(){ii.length>0&&this.setAttribute("version",ii)}getAROverlayContainer(){return this._overlay_ar.createOverlayContainer(this)}getVROverlayContainer(){for(let e=0;e<this.children.length;e++){const t=this.children[e];if(t.classList.contains("vr"))return t}return null}onEnterAR(e){const t=this.getOrCreateContext();this.onSetupAR();const i=this.getAROverlayContainer();this._overlay_ar.onBegin(t,i,e),this.dispatchEvent(new CustomEvent("enter-ar",{detail:{session:e,context:t,htmlContainer:this._overlay_ar?.ARContainer}}))}onExitAR(e){const t=this.getOrCreateContext();this._overlay_ar.onEnd(t),this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-ar",{detail:{session:e,context:t,htmlContainer:this._overlay_ar?.ARContainer}}))}onEnterVR(e){const t=this.getOrCreateContext();this.onSetupVR(),this.dispatchEvent(new CustomEvent("enter-vr",{detail:{session:e,context:t}}))}onExitVR(e){const t=this.getOrCreateContext();this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-vr",{detail:{session:e,context:t}}))}onSetupAR(){this.classList.add(Ll),this.classList.remove(Il);const e=this.getAROverlayContainer();be&&console.warn("onSetupAR:",e),e&&(e.classList.add(Ll),e.classList.remove(Il)),this.foreachHtmlElement(t=>this.setupElementsForMode(t,Lx))}onSetupVR(){this.classList.remove(Ll),this.classList.remove(Il),this.foreachHtmlElement(e=>this.setupElementsForMode(e,Ix))}onSetupDesktop(){this.classList.remove(Ll),this.classList.add(Il);const e=this.getAROverlayContainer();e&&(e.classList.remove(Ll),e.classList.add(Il)),this.foreachHtmlElement(t=>this.setupElementsForMode(t,jx))}setupElementsForMode(e,t,i=null){if(e===this._context?.renderer?.domElement||e.id==="VRButton"||e.id==="ARButton")return;if(e.classList.contains(t))e.style.visibility="visible",e.style.display==="none"&&(e.style.display="block");else for(const o of WT)e.classList.contains(o)&&(e.style.visibility="hidden",e.style.display="none")}foreachHtmlElement(e){for(let t=0;t<this.children.length;t++){const i=this.children[t];i.style&&e(i)}}onBeforeBeginLoading(){const e=this.getAttribute("dracoDecoderPath");e&&(be&&console.log("using custom draco decoder path",e),q_(e));const t=this.getAttribute("dracoDecoderType");t&&(be&&console.log("using custom draco decoder type",t),X_(t));const i=this.getAttribute("ktx2DecoderPath");i&&(be&&console.log("using custom ktx2 decoder path",i),Q_(i))}setAttribute(e,t){super.setAttribute(e,typeof t=="string"?t:String(t))}getAttribute(e){return super.getAttribute(e)}addEventListener(e,t,i){return super.addEventListener(e,t,i)}}typeof window<"u"&&!window.customElements.get(Yb)&&window.customElements.define(Yb,$y);function HT(s){if(s.startsWith("blob:"))return"blob";const e=s.split("/");let t=e[e.length-1];const i=t.indexOf("?");i>0&&(t=t.substring(0,i));const n=t.indexOf("=");n>0&&(t=t.substring(n));const o=t.split(".").pop(),a=o?["glb","gltf","usdz","usd","fbx","obj","mtl"].indexOf(o.toLowerCase()):-1;if(o&&a>=0&&(t=t.substring(0,t.length-o.length-1)),t=decodeURIComponent(t),t.length>3){let l="",h=!1;const d=["(",")","[","]","{","}",":",";",",",".","!","?"];for(let u=0;u<t.length;u++){let p=t[u];(p==="_"||p==="-")&&(p=" "),!(p===" "&&l.length<=0||d.includes(p)||(l.length===0&&(p=p.toUpperCase()),h&&p===" "))&&(h&&(p=p.toUpperCase()),h=!1,l+=p,p===" "&&(h=!0))}return A()&&t!==l&&console.debug('Generated display name: "'+t+'" → "'+l+'"'),l.trim()}return t}function qT(s){Cu(e=>{const t=s.getAttribute("loading-blur");if(t!==null&&t!=="0"&&e.domElement===s){const i=e.lodsManager.manager?.awaitLoading({frames:5,signal:AbortSignal.timeout(1e4),maxPromisesPerObject:1}).catch(r=>{});let n="20px";t.endsWith("px")&&(n=t);const o=170;if(e.scene.background===null){const r=s,a=e.renderer.domElement,l=a.style.filter,h=a.style.overflow;a.style.filter+=`blur(${n})`,r.style.overflow="hidden",i?.then(()=>{const d=a.animate([{filter:"blur(0px)"}],{duration:o,easing:"ease-in"});d.onfinish=()=>{a.style.filter=l,r.style.overflow=h}})}else{const r=document.createElement("div");e.domElement.prepend(r),r.style.cssText="position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 10; pointer-events: none",r.style.backdropFilter=`blur(${n})`,i?.then(()=>{const a=r.animate([{backdropFilter:"blur(0px)",opacity:0}],{duration:o,easing:"ease-in"});a.onfinish=()=>{r.remove()}})}}},{once:!0})}const XT=Object.freeze(Object.defineProperty({__proto__:null,NeedleEngineWebComponent:$y},Symbol.toStringTag,{value:"Module"}));function QT(){fn.registerWaitForInteraction(()=>{const s=c.AudioContext.getContext();s.addEventListener("statechange",()=>{setTimeout(()=>{const e=s.state;(e==="suspended"||e==="interrupted")&&s.resume().then(()=>{console.log("AudioContext resumed successfully")}).catch(t=>{console.log("Failed to resume AudioContext: "+t)})},500)})})}setTimeout(QT,1e3);const Ie=x("debugphysics"),Pp=x("debugcolliderplacement"),Op=x("debugcollisions"),YT=x("showcolliders"),hd=x("debugraycasts"),Kt=Symbol("needle component"),Mt=Symbol("physics body"),Kb=Symbol("rigidbody");globalThis.NEEDLE_USE_RAPIER=globalThis.NEEDLE_USE_RAPIER!==void 0?globalThis.NEEDLE_USE_RAPIER:!0;Ie&&console.log("Use Rapier",!0,globalThis.NEEDLE_USE_RAPIER);ce.registerCallback(le.ContextCreationStart,s=>{Ie&&console.log("Register rapier physics backend"),s.context.physics.engine=new Ma(s.context)});class Ma{debugRenderColliders=!1;debugRenderRaycasts=!1;removeBody(e){if(Ie&&console.log("REMOVE BODY",e?.name,e[Mt]),!e)return;this.validate();const t=e[Mt];if(e[Mt]=null,t&&this.world){const i=this.objects.findIndex(n=>n===e);if(i>=0){const n=this.bodies[i];if(this.bodies.splice(i,1),this.objects.splice(i,1),n instanceof T.RAPIER_PHYSICS.MODULE.Collider){const o=n;this.world?.removeCollider(o,!0);const r=o.parent();r&&r.numColliders()<=0&&(r[Kt]||this.world?.removeRigidBody(r))}else n instanceof T.RAPIER_PHYSICS.MODULE.RigidBody&&(n.numColliders()<=0?this.world?.removeRigidBody(n):A()&&(n.did_log_removing||setTimeout(()=>{n.numColliders()>0&&(n.did_log_removing=!0,console.warn("RapierPhysics: removing rigidbody with colliders from the physics world is not possible right now, please remove the colliders first"))},1)))}}}updateBody(e,t,i){if(this.validate(),!!this.enabled&&!(e.destroyed||!e.gameObject)&&!(!t&&!i))if(e.isCollider===!0)console.warn("TODO: implement updating collider position");else{const n=e,o=n[Mt];o&&this.syncPhysicsBody(n.gameObject,o,t,i)}}updateProperties(e){if(this.validate(),e.isCollider){const t=e,i=t[Mt];i&&(this.internalUpdateColliderProperties(t,i),t.sharedMaterial&&this.updatePhysicsMaterial(t))}else{const t=e,i=this.internal_getRigidbody(t);i&&this.internalUpdateRigidbodyProperties(t,i)}}addForce(e,t,i){this.validate();const n=this.internal_getRigidbody(e);n?n.addForce(t,i):this._isInitialized&&console.warn("Physics Body doesn't exist: can not apply force (does your object with the Rigidbody have a collider?)")}addImpulse(e,t,i){this.validate();const n=this.internal_getRigidbody(e);n?n.applyImpulse(t,i):this._isInitialized&&console.warn("Physics Body doesn't exist: can not apply impulse (does your object with the Rigidbody have a collider?)")}getLinearVelocity(e){this.validate();const t=this.internal_getRigidbody(e);return t?t.linvel():null}getAngularVelocity(e){this.validate();const t=this.internal_getRigidbody(e);return t?t.angvel():null}resetForces(e,t){this.validate(),this.internal_getRigidbody(e)?.resetForces(t)}resetTorques(e,t){this.validate(),this.internal_getRigidbody(e)?.resetTorques(t)}applyImpulse(e,t,i){this.validate();const n=this.internal_getRigidbody(e);n?n.applyImpulse(t,i):this._isInitialized&&console.warn("Rigidbody doesn't exist: can not apply impulse (does your object with the Rigidbody have a collider?)")}wakeup(e){this.validate();const t=this.internal_getRigidbody(e);t?t.wakeUp():this._isInitialized&&console.warn("Rigidbody doesn't exist: can not wake up (does your object with the Rigidbody have a collider?)")}isSleeping(e){return this.validate(),this.internal_getRigidbody(e)?.isSleeping()}setAngularVelocity(e,t,i){this.validate();const n=this.internal_getRigidbody(e);n?n.setAngvel(t,i):this._isInitialized&&console.warn("Rigidbody doesn't exist: can not set angular velocity (does your object with the Rigidbody have a collider?)")}setLinearVelocity(e,t,i){this.validate();const n=this.internal_getRigidbody(e);n?n.setLinvel(t,i):this._isInitialized&&console.warn("Rigidbody doesn't exist: can not set linear velocity (does your object with the Rigidbody have a collider?)")}context;_initializePromise;_isInitialized=!1;constructor(e){this.context=e}get isInitialized(){return this._isInitialized}async initialize(){return this._initializePromise||(this._initializePromise=this.internalInitialization()),this._initializePromise}async internalInitialization(){return x("__nophysics")?(console.warn("Physics are disabled"),!1):(Ie&&console.log("Initialize rapier physics engine"),this._hasCreatedWorld?(console.error("Invalid call to create physics world: world is already created"),!0):(this._hasCreatedWorld=!0,T.RAPIER_PHYSICS.MAYBEMODULE==null&&(Ie&&console.trace("Loading rapier physics engine"),await(await T.RAPIER_PHYSICS.load()).init()),Ie&&console.log("Physics engine initialized, creating world..."),this._world=new T.RAPIER_PHYSICS.MODULE.World(this._gravity),this.rapierRay=new T.RAPIER_PHYSICS.MODULE.Ray({x:0,y:0,z:0},{x:0,y:0,z:1}),this.enabled=!0,this._isInitialized=!0,Ie&&console.log("Physics world created"),!0))}validate(){this._isInitialized||Ie&&(this._lastWarnTime=this._lastWarnTime??0,Date.now()-this._lastWarnTime>1e3&&(this._lastWarnTime=Date.now(),console.warn("Physics engine is not initialized")))}rapierRay;raycastVectorsBuffer=new _i(()=>new c.Vector3,10);raycast(e,t,i){if(!this._isInitialized)return console.log("Physics engine is not initialized"),null;let n=i?.maxDistance,o=i?.solid;n===void 0&&(n=1/0),o===void 0&&(o=!0);const r=this.getPhysicsRay(this.rapierRay,e,t);if(!r)return null;(this.debugRenderRaycasts||hd)&&B.DrawRay(r.origin,r.dir,255,1);const a=this.world?.castRay(r,n,o,i?.queryFilterFlags,i?.filterGroups,void 0,void 0,l=>{const h=l[Kt];return i?.filterPredicate?i.filterPredicate(h):i?.useIgnoreRaycastLayer!==!1?!h?.gameObject.layers.isEnabled(2):!0});if(a){const l=r.pointAt(a.timeOfImpact),h=this.raycastVectorsBuffer.get();return h.set(l.x,l.y,l.z),{point:h,collider:a.collider[Kt]}}return null}raycastAndGetNormal(e,t,i){if(!this._isInitialized)return null;let n=i?.maxDistance,o=i?.solid;n===void 0&&(n=1/0),o===void 0&&(o=!0);const r=this.getPhysicsRay(this.rapierRay,e,t);if(!r)return null;(this.debugRenderRaycasts||hd)&&B.DrawRay(r.origin,r.dir,255,1);const a=this.world?.castRayAndGetNormal(r,n,o,i?.queryFilterFlags,i?.filterGroups,void 0,void 0,l=>{const h=l[Kt];return i?.filterPredicate?i.filterPredicate(h):i?.useIgnoreRaycastLayer!==!1?!h?.gameObject.layers.isEnabled(2):!0});if(a){const l=r.pointAt(a.timeOfImpact),h=a.normal,d=this.raycastVectorsBuffer.get(),u=this.raycastVectorsBuffer.get();return d.set(l.x,l.y,l.z),u.set(h.x,h.y,h.z),{point:d,normal:u,collider:a.collider[Kt]}}return null}getPhysicsRay(e,t,i){const n=this.context?.mainCamera;if(t===void 0){const a=this.context?.input.getPointerPosition(0);if(a)t=a;else return null}if(t.z===void 0){if(!n)return console.error("Can not perform raycast from 2d point - no main camera found"),null;const a=this.raycastVectorsBuffer.get();a.x=t.x,a.y=t.y,a.z=0,(a.x>1||a.y>1||a.y<-1||a.x<-1)&&(Ie&&console.warn("Converting screenspace to raycast space",a),this.context?.input.convertScreenspaceToRaycastSpace(a)),a.unproject(n),t=a}const o=t;e.origin.x=o.x,e.origin.y=o.y,e.origin.z=o.z;const r=this.raycastVectorsBuffer.get();if(i)r.set(i.x,i.y,i.z);else{if(!n)return console.error("Can not perform raycast - no camera found"),null;r.set(e.origin.x,e.origin.y,e.origin.z);const a=Y(n);r.sub(a)}return r.normalize(),e.dir.x=r.x,e.dir.y=r.y,e.dir.z=r.z,e}rapierSphere=null;rapierBox=null;rapierColliderArray=[];rapierIdentityRotation={x:0,y:0,z:0,w:1};rapierForwardVector={x:0,y:0,z:1};sphereOverlap(e,t){return this.rapierSphere??=new T.RAPIER_PHYSICS.MODULE.Ball(t),this.rapierSphere.radius=t,(this.debugRenderRaycasts||hd)&&B.DrawWireSphere(e,t,3359999,1),this.shapeOverlap(e,this.rapierIdentityRotation,this.rapierSphere)}boxOverlap(e,t,i=null){return i===null&&(i=this.rapierIdentityRotation),this.rapierBox??=new T.RAPIER_PHYSICS.MODULE.Cuboid(1,1,1),this.rapierBox.halfExtents.x=t.x*.5,this.rapierBox.halfExtents.y=t.y*.5,this.rapierBox.halfExtents.z=t.z*.5,(this.debugRenderRaycasts||hd)&&B.DrawWireBox(e,t,3359999,1,!0,i),this.shapeOverlap(e,i,this.rapierBox)}shapeOverlap(e,t,i){return this.rapierColliderArray.length=0,this._isInitialized?this.world?(this.world.intersectionsWithShape(e,t,i,n=>{const o=n[Kt],r=new jv(o.gameObject,o);return this.rapierColliderArray.push(r),!0},void 0,void 0,void 0,void 0,n=>n.isSensor()?!1:n[Kt].gameObject.layers.isEnabled(2)==!1),this.rapierColliderArray):this.rapierColliderArray:this.rapierColliderArray}enabled=!1;get world(){return this._world}_tempPosition=new c.Vector3;_tempQuaternion=new c.Quaternion;_tempScale=new c.Vector3;_tempMatrix=new c.Matrix4;static _didLoadPhysicsEngine=!1;_isUpdatingPhysicsWorld=!1;get isUpdating(){return this._isUpdatingPhysicsWorld}_world;_hasCreatedWorld=!1;eventQueue;collisionHandler;objects=[];bodies=[];_meshCache=new Map;_gravity={x:0,y:-9.81,z:0};get gravity(){return this.world?.gravity??this._gravity}set gravity(e){this.world?this.world.gravity=e:this._gravity=e}clearCaches(){this._meshCache.clear(),this.eventQueue?.raw&&this.eventQueue?.free(),this.world?.bodies&&this.world?.free()}async addBoxCollider(e,t){if(this._isInitialized||await this.initialize(),!e.activeAndEnabled)return;if(!this.enabled){Ie&&console.warn("Physics are disabled");return}const i=e.gameObject,n=je(i,this._tempPosition).multiply(t);n.multiplyScalar(.5),n.x<0&&(n.x=Math.abs(n.x)),n.y<0&&(n.y=Math.abs(n.y)),n.z<0&&(n.z=Math.abs(n.z));const o=1e-7;n.x<o&&(n.x=o),n.y<o&&(n.y=o),n.z<o&&(n.z=o);const r=T.RAPIER_PHYSICS.MODULE.ColliderDesc.cuboid(n.x,n.y,n.z);this.createCollider(e,r)}async addSphereCollider(e){if(this._isInitialized||await this.initialize(),!e.activeAndEnabled)return;if(!this.enabled){Ie&&console.warn("Physics are disabled");return}const t=T.RAPIER_PHYSICS.MODULE.ColliderDesc.ball(.5);this.createCollider(e,t),this.updateProperties(e)}async addCapsuleCollider(e,t,i){if(this._isInitialized||await this.initialize(),!e.activeAndEnabled)return;if(!this.enabled){Ie&&console.warn("Physics are disabled");return}const o=e.gameObject.worldScale;o.x=Math.abs(o.x),o.y=Math.abs(o.y);const r=i*o.x;t=Math.max(t,r);const a=I.clamp(t*.5*o.y-i*o.x,0,Number.MAX_SAFE_INTEGER),l=T.RAPIER_PHYSICS.MODULE.ColliderDesc.capsule(a,r);this.createCollider(e,l)}async addMeshCollider(e,t,i,n){let o=t.geometry;if(!o){Ie&&console.warn("Missing mesh geometry",t.name);return}o.index?.array?.length||(console.warn(`Your MeshCollider is missing vertices or indices in the assined mesh "${t.name}". Consider providing an indexed geometry.`),o=X.mergeVertices(o));let r=null;const a=o.getAttribute("position");if(a instanceof c.InterleavedBufferAttribute){const u=a.count;r=new Float32Array(u*3);for(let p=0;p<u;p++){const m=a.getX(p),y=a.getY(p),_=a.getZ(p);r[p*3]=m,r[p*3+1]=y,r[p*3+2]=_}}else r=a.array;if(await this.initialize(),!this.enabled){Ie&&console.warn("Physics are disabled");return}if(!e.activeAndEnabled)return;const l=o.index?.array,h=e.gameObject.worldScale.clone();if(n&&h.multiply(n),Math.abs(h.x-1)>1e-4||Math.abs(h.y-1)>1e-4||Math.abs(h.z-1)>1e-4){const u=`${o.uuid}_${h.x}_${h.y}_${h.z}_${i}`;if(this._meshCache.has(u))Ie&&console.warn("Use cached mesh collider"),r=this._meshCache.get(u);else{(Ie||A())&&console.debug(`[Performance] Your MeshCollider "${e.name}" is scaled: consider applying the scale to the collider mesh instead (${h.x}, ${h.y}, ${h.z})`);const p=new Float32Array(r.length);for(let m=0;m<r.length;m+=3)p[m]=r[m]*h.x,p[m+1]=r[m+1]*h.y,p[m+2]=r[m+2]*h.z;r=p,this._meshCache.set(u,p)}}const d=i?T.RAPIER_PHYSICS.MODULE.ColliderDesc.convexHull(r):T.RAPIER_PHYSICS.MODULE.ColliderDesc.trimesh(r,l);d&&this.createCollider(e,d)}updatePhysicsMaterial(e){if(!e)return;const t=e.sharedMaterial,i=e[Mt];if(i&&t){if(t.bounciness!==void 0&&i.setRestitution(t.bounciness),t.bounceCombine!==void 0)switch(t.bounceCombine){case st.Average:i.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case st.Maximum:i.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case st.Minimum:i.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case st.Multiply:i.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(t.dynamicFriction!==void 0&&i.setFriction(t.dynamicFriction),t.frictionCombine!==void 0)switch(t.frictionCombine){case st.Average:i.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case st.Maximum:i.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case st.Minimum:i.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case st.Multiply:i.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}}}getBody(e){return e?e[Mt]:null}getComponent(e){return e?e[Kt]:null}createCollider(e,t){if(!this.world)throw new Error("Physics world not initialized");const i=this._tempMatrix;let n;e.attachedRigidbody?n=this.getRigidbody(e,this._tempMatrix):(Ie&&console.log("Create collider without rigidbody",e.name),i.makeRotationFromQuaternion(pe(e.gameObject)),i.setPosition(Y(e.gameObject))),i.decompose(this._tempPosition,this._tempQuaternion,this._tempScale),this.tryApplyCenter(e,this._tempPosition),t.setTranslation(this._tempPosition.x,this._tempPosition.y,this._tempPosition.z),t.setRotation(this._tempQuaternion),t.setSensor(e.isTrigger);const o=e.sharedMaterial;if(o){if(o.bounciness!==void 0&&t.setRestitution(o.bounciness),o.bounceCombine!==void 0)switch(o.bounceCombine){case st.Average:t.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case st.Maximum:t.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case st.Minimum:t.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case st.Multiply:t.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(o.dynamicFriction!==void 0&&t.setFriction(o.dynamicFriction),o.frictionCombine!==void 0)switch(o.frictionCombine){case st.Average:t.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case st.Maximum:t.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case st.Minimum:t.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case st.Multiply:t.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}}e.attachedRigidbody?.autoMass===!1&&(t.setDensity(1e-6),t.setMass(1e-6));try{const r=this.world.createCollider(t,n);return r[Kt]=e,e[Mt]=r,r.setActiveEvents(T.RAPIER_PHYSICS.MODULE.ActiveEvents.COLLISION_EVENTS),r.setActiveCollisionTypes(T.RAPIER_PHYSICS.MODULE.ActiveCollisionTypes.ALL),this.objects.push(e),this.bodies.push(r),this.updateColliderCollisionGroups(e),Ie&&console.log("Created collider",e.name,r),r}catch(r){return console.error('Error creating collider "'+e.name+`"
|
|
1624
|
-
Error:`,r),null}}updateColliderCollisionGroups(e){const t=e[Mt],i=e.membership;let n=0;if(i==null)n=65535;else for(let a=0;a<i.length;a++){const l=i[a];l>31?console.error(`Rapier only supports 32 layers, layer ${l} is not supported`):n|=1<<Math.floor(l)}const o=e.filter;let r=0;if(o==null)r=65535;else for(let a=0;a<o.length;a++){const l=o[a];l>31?console.error(`Rapier only supports 32 layers, layer ${l} is not supported`):r|=1<<Math.floor(l)}t.setCollisionGroups(n<<16|r)}getRigidbody(e,t){if(!this.world)throw new Error("Physics world not initialized");let i=null;if(e.attachedRigidbody){const n=e.attachedRigidbody;if(i=n[Mt],!i){const o=n.isKinematic&&!Pp;Ie&&console.log("Create rigidbody",o);const r=o?T.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased():T.RAPIER_PHYSICS.MODULE.RigidBodyDesc.dynamic(),a=Y(e.attachedRigidbody.gameObject);r.setTranslation(a.x,a.y,a.z),r.setRotation(pe(e.attachedRigidbody.gameObject)),r.centerOfMass=new T.RAPIER_PHYSICS.MODULE.Vector3(n.centerOfMass.x,n.centerOfMass.y,n.centerOfMass.z),i=this.world.createRigidBody(r),this.bodies.push(i),this.objects.push(n)}i[Kt]=n,n[Mt]=i,this.internalUpdateRigidbodyProperties(n,i),this.getRigidbodyRelativeMatrix(e.gameObject,n.gameObject,t),e[Kb]=i}else{const n=T.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased(),o=Y(e.gameObject);n.setTranslation(o.x,o.y,o.z),n.setRotation(pe(e.gameObject)),i=this.world.createRigidBody(n),t.identity(),i[Kt]=null}return i}internal_getRigidbody(e){return e.isCollider===!0?e[Kb]:e[Mt]}internalUpdateColliderProperties(e,t){const i=t.shape;let n=!1;switch(i.type){case T.RAPIER_PHYSICS.MODULE.ShapeType.Ball:{const p=i,m=e,y=e.gameObject,_=je(y,this._tempPosition),g=Math.abs(m.radius*_.x);n=p.radius!==g,p.radius=g,n&&t.setShape(p);break}case T.RAPIER_PHYSICS.MODULE.ShapeType.Cuboid:const o=i,r=e,a=e.gameObject,l=je(a,this._tempPosition),h=Math.abs(r.size.x*.5*l.x),d=Math.abs(r.size.y*.5*l.y),u=Math.abs(r.size.z*.5*l.z);n=o.halfExtents.x!==h||o.halfExtents.y!==d||o.halfExtents.z!==u,o.halfExtents.x=h,o.halfExtents.y=d,o.halfExtents.z=u,n&&t.setShape(o);break}if(n){const o=e.attachedRigidbody;o?.autoMass&&this.getBody(o)?.recomputeMassPropertiesFromColliders()}this.updateColliderCollisionGroups(e),e.isTrigger!==t.isSensor()&&t.setSensor(e.isTrigger)}internalUpdateRigidbodyProperties(e,t){if(t.enableCcd(e.collisionDetectionMode!==Ou.Discrete),t.setLinearDamping(e.drag),t.setAngularDamping(e.angularDrag),t.setGravityScale(e.useGravity?e.gravityScale:0,!0),e.dominanceGroup<=127&&e.dominanceGroup>=-127?t.setDominanceGroup(Math.floor(e.dominanceGroup)):t.setDominanceGroup(0),e.autoMass){t.setAdditionalMass(0,!1);for(let i=0;i<t.numColliders();i++)t.collider(i).setDensity(1);t.recomputeMassPropertiesFromColliders()}else{t.setAdditionalMass(e.mass,!1);for(let i=0;i<t.numColliders();i++)t.collider(i).setDensity(1e-7);t.recomputeMassPropertiesFromColliders()}t.setEnabledRotations(!e.lockRotationX,!e.lockRotationY,!e.lockRotationZ,!1),t.setEnabledTranslations(!e.lockPositionX,!e.lockPositionY,!e.lockPositionZ,!1),e.isKinematic?t.setBodyType(T.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased,!1):t.setBodyType(T.RAPIER_PHYSICS.MODULE.RigidBodyType.Dynamic,!1)}lines;step(e){if(this.world&&this.enabled){if(this._isUpdatingPhysicsWorld=!0,this.eventQueue||(this.eventQueue=new T.RAPIER_PHYSICS.MODULE.EventQueue(!1)),e===void 0||e<=0){this._isUpdatingPhysicsWorld=!1;return}else if(e!==void 0){const t=I.lerp(this.world.timestep,e,.8);this.world.timestep=t}try{this.world.step(this.eventQueue)}catch(t){console.warn("Error running physics step",{timestep:this.world.timestep},t)}this._isUpdatingPhysicsWorld=!1}}postStep(){this.world&&this.enabled&&(this._isUpdatingPhysicsWorld=!0,this.syncObjects(),this._isUpdatingPhysicsWorld=!1,this.eventQueue&&!this.collisionHandler&&(this.collisionHandler=new KT(this.world,this.eventQueue)),this.collisionHandler&&(this.collisionHandler.handleCollisionEvents(),this.collisionHandler.update()),this.updateDebugRendering(this.world))}updateDebugRendering(e){if(Ie||Pp||YT||this.debugRenderColliders===!0){if(!this.lines){const i=new c.LineBasicMaterial({color:7855479,fog:!1}),n=new c.BufferGeometry;this.lines=new c.LineSegments(n,i),this.lines.layers.disableAll(),this.lines.layers.enable(2)}this.lines.parent!==this.context?.scene&&this.context?.scene.add(this.lines);const t=e.debugRender();this.lines.geometry.setAttribute("position",new c.BufferAttribute(t.vertices,3)),this.lines.geometry.setAttribute("color",new c.BufferAttribute(t.colors,4)),(this.context.time.frame%30===0||this.lines.geometry.boundingSphere?.radius===0)&&this.lines.geometry.computeBoundingSphere()}else this.lines&&this.context?.scene.remove(this.lines)}syncObjects(){if(!Pp)for(let e=0;e<this.bodies.length;e++){const t=this.objects[e],i=this.bodies[e],n=t;if(n?.isCollider===!0&&!n.attachedRigidbody){const l=i.parent();l?this.syncPhysicsBody(t.gameObject,l,!0,!0):this.syncPhysicsBody(t.gameObject,i,!0,!0);continue}const o=i.translation(),r=i.rotation();if(Number.isNaN(o.x)||Number.isNaN(r.x)){!n.__COLLIDER_NAN&&A()&&(console.warn("Collider has NaN values",n.name,n.gameObject,i),n.__COLLIDER_NAN=!0);continue}const a=t.center;if(a&&a.isVector3){this._tempQuaternion.set(r.x,r.y,r.z,r.w);const l=this._tempPosition.copy(a).applyQuaternion(this._tempQuaternion),h=je(t.gameObject);l.multiply(h),o.x-=l.x,o.y-=l.y,o.z-=l.z}dr(t.gameObject,o.x,o.y,o.z),jm(t.gameObject,r.x,r.y,r.z,r.w)}}syncPhysicsBody(e,t,i,n){if(t instanceof T.RAPIER_PHYSICS.MODULE.RigidBody){const o=Y(e,this._tempPosition),r=pe(e,this._tempQuaternion);switch(t.bodyType()){case T.RAPIER_PHYSICS.MODULE.RigidBodyType.Fixed:case T.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased:case T.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicVelocityBased:i&&t.setNextKinematicTranslation(o),n&&t.setNextKinematicRotation(r);break;default:i&&t.setTranslation(o,!1),n&&t.setRotation(r,!1);break}}else if(t instanceof T.RAPIER_PHYSICS.MODULE.Collider){e.matrixWorldNeedsUpdate&&e.updateWorldMatrix(!0,!1),e.matrixWorld.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const o=this._tempPosition,r=this._tempQuaternion,a=t[Kt];if(this.tryApplyCenter(a,o),i){const l=t.translation();(l.x!==o.x||l.y!==o.y||l.z!==o.z)&&t.setTranslation(o)}if(n){const l=t.rotation();(l.x!==r.x||l.y!==r.y||l.z!==r.z||l.w!==r.w)&&t.setRotation(r)}}}_tempCenterPos=new c.Vector3;_tempCenterVec=new c.Vector3;_tempCenterQuaternion=new c.Quaternion;tryApplyCenter(e,t){const i=e.center;i&&e.gameObject&&(i.x!==0||i.y!==0||i.z!==0)&&(this._tempCenterPos.x=i.x,this._tempCenterPos.y=i.y,this._tempCenterPos.z=i.z,je(e.gameObject,this._tempCenterVec),this._tempCenterPos.multiply(this._tempCenterVec),e.attachedRigidbody?this._tempCenterPos.applyQuaternion(e.gameObject.quaternion):(pe(e.gameObject,this._tempCenterQuaternion),this._tempCenterPos.applyQuaternion(this._tempCenterQuaternion)),t.x+=this._tempCenterPos.x,t.y+=this._tempCenterPos.y,t.z+=this._tempCenterPos.z)}static _matricesBuffer=[];getRigidbodyRelativeMatrix(e,t,i,n){if(n===void 0&&(n=Ma._matricesBuffer,n.length=0),e===t){const o=je(e,this._tempPosition);i.makeScale(o.x,o.y,o.z);for(let r=n.length-1;r>=0;r--)i.multiply(n[r]);return i}return n.push(e.matrix),e.parent&&this.getRigidbodyRelativeMatrix(e.parent,t,i,n),i}static centerConnectionPos={x:0,y:0,z:0};static centerConnectionRot={x:0,y:0,z:0,w:1};addFixedJoint(e,t){if(!this.world){console.error("Physics world not initialized");return}const i=e[Mt],n=t[Mt];this.calculateJointRelativeMatrices(e.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const o=T.RAPIER_PHYSICS.MODULE.JointData.fixed(Ma.centerConnectionPos,Ma.centerConnectionRot,this._tempPosition,this._tempQuaternion),r=this.world.createImpulseJoint(o,i,n,!0);Ie&&console.log("ADD FIXED JOINT",r)}addHingeJoint(e,t,i,n){if(!this.world){console.error("Physics world not initialized");return}const o=e[Mt],r=t[Mt];this.calculateJointRelativeMatrices(e.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const a=T.RAPIER_PHYSICS.MODULE.JointData.revolute(i,this._tempPosition,n),l=this.world.createImpulseJoint(a,o,r,!0);Ie&&console.log("ADD HINGE JOINT",l)}calculateJointRelativeMatrices(e,t,i){e.updateWorldMatrix(!0,!1),t.updateWorldMatrix(!0,!1);const n=e.matrixWorld,o=t.matrixWorld;n.elements[0]=1,n.elements[5]=1,n.elements[10]=1,o.elements[0]=1,o.elements[5]=1,o.elements[10]=1,i.copy(o).premultiply(n.invert()).invert()}}class KT{world;eventQueue;constructor(e,t){this.world=e,this.eventQueue=t}activeCollisions=[];activeCollisionsStay=[];activeTriggers=[];handleCollisionEvents(){this.eventQueue&&this.world&&this.eventQueue.drainCollisionEvents((e,t,i)=>{const n=this.world.getCollider(e),o=this.world.getCollider(t);if(!n||!o)return;const r=n[Kt],a=o[Kt];Op&&console.log("EVT",r.name,a.name,i,n,o),r&&a&&(i?(this.onCollisionStarted(r,n,a,o),this.onCollisionStarted(a,o,r,n)):(this.onCollisionEnded(r,a),this.onCollisionEnded(a,r)))})}update(){this.onHandleCollisionStay()}onCollisionStarted(e,t,i,n){let o=null;if(e.isTrigger||i.isTrigger)fr(e.gameObject,r=>{r.onTriggerEnter&&!r.destroyed&&r.onTriggerEnter(i),this.activeTriggers.push({collider:e,component:r,otherCollider:i})});else{const r=e.gameObject;this.world.contactPair(t,n,(a,l)=>{fr(r,h=>{if(h.destroyed)return;const d=h.onCollisionEnter||h.onCollisionStay||h.onCollisionExit;if(d||Op){if(!o){const u=[],p=a.normal();i instanceof xo&&i.convex&&(p.x=-p.x,p.y=-p.y,p.z=-p.z);for(let m=0;m<a.numSolverContacts();m++){const y=a.solverContactPoint(m),_=a.contactImpulse(m);if(y){const g=a.contactDist(m),w=a.solverContactFriction(m),b=a.solverContactTangentVelocity(m),v=new Lv(y,g,p,_,w,b);u.push(v),Op&&B.DrawDirection(y,p,16711680,3,!0)}}o=new Iv(r,i,u)}if(d){const u={collider:e,component:h,collision:o};this.activeCollisions.push(u),h.onCollisionStay&&this.activeCollisionsStay.push(u),h.onCollisionEnter?.call(h,o)}}})})}}onHandleCollisionStay(){for(const e of this.activeCollisionsStay){const t=e.component;if(!t.destroyed&&t.activeAndEnabled&&t.onCollisionStay){if(e.collision.collider.destroyed)continue;const i=e.collision;t.onCollisionStay(i)}}for(const e of this.activeTriggers){const t=e.component;if(!t.destroyed&&t.activeAndEnabled&&t.onTriggerStay){const i=e.otherCollider;if(i.destroyed)continue;t.onTriggerStay(i)}}}onCollisionEnded(e,t){if(!(e.destroyed||t.destroyed)){for(let i=0;i<this.activeCollisions.length;i++){const n=this.activeCollisions[i],o=n.collider;if(o.destroyed||n.collision.collider.destroyed){this.activeCollisions.splice(i,1),i--;continue}if(o===e&&n.collision.collider===t){const r=n.component;if(this.activeCollisions.splice(i,1),i--,r.activeAndEnabled&&r.onCollisionExit){const a=n.collision;r.onCollisionExit(a)}}}for(let i=0;i<this.activeCollisionsStay.length;i++){const n=this.activeCollisionsStay[i],o=n.collider;if(o.destroyed||n.collision.collider.destroyed){this.activeCollisionsStay.splice(i,1),i--;continue}if(o===e&&n.collision.collider===t){const r=n.component;if(this.activeCollisionsStay.splice(i,1),i--,r.activeAndEnabled&&r.onCollisionExit){const a=n.collision;r.onCollisionExit(a)}}}for(let i=0;i<this.activeTriggers.length;i++){const n=this.activeTriggers[i],o=n.collider;if(o.destroyed||n.otherCollider.destroyed){this.activeTriggers.splice(i,1),i--;continue}if(o===e&&n.otherCollider===t){const r=n.component;if(this.activeTriggers.splice(i,1),i--,r.activeAndEnabled&&r.onTriggerExit){const a=n.otherCollider;r.onTriggerExit(a)}}}}}}let Mm=0;function Zb(s){s?Mm++:Mm--}function ZT(){return Mm>0}const JT={binary:!0,animations:!0};async function eA(s){if(!s.context)throw new Error("No context provided to exportAsGLTF");s.scene||(s.scene=s.context.scene);const e={...JT,...s},{context:t}=e,i=new X.GLTFExporter;i.register(a=>new Ew(a)),i.register(a=>new RM(a)),i.register(a=>new Aw(a)),Lg(i,e.context);const n={binary:e.binary,animations:iA(t,e.scene,[])},o=new tA;console.debug("Exporting GLTF",n),o.onBeforeExport(e),Zb(!0);const r=await i.parseAsync(e.scene,n).catch(a=>(console.error(a),null));if(Zb(!1),o.onAfterExport(e),!r)throw new Error("Failed to export GLTF");if(e.downloadAs!=null){let a=null;if(r instanceof ArrayBuffer?a=new Blob([r],{type:"application/octet-stream"}):console.error("Can not download GLTF as a blob",r),a){const l=URL.createObjectURL(a),h=document.createElement("a");h.href=l;let d=e.downloadAs;!d.endsWith(".glb")&&!d.endsWith(".gltf")&&(d+=e.binary?".glb":".gltf"),h.download=d,h.click()}}return r}const Jb=Symbol("needle:weight");class tA{_undo=[];onBeforeExport(e){e.context.animations.mixers.forEach(t=>{const i=Hn.tryGetActionsFromMixer(t);if(i)for(let n=0;n<i.length;n++){const o=i[n];o[Jb]=o.weight,o.weight=0,this._undo.push(()=>{o.weight=o[Jb]})}t.update(0)}),e.context.scene.traverse(t=>{if(!cm(t)){const i=t.parent;i&&(t.removeFromParent(),this._undo.push(()=>i.add(t)))}})}onAfterExport(e){this._undo.forEach(t=>t()),this._undo.length=0}}function iA(s,e,t){s.animations.mixers.forEach(n=>{const o=Hn.tryGetActionsFromMixer(n);if(o)for(let r=0;r<o.length;r++){const l=o[r].getClip();t.push(l)}}),Array.isArray(e)||(e=[e]);for(const n of e)Hn.tryGetAnimationClipsFromObjectHierarchy(n,t);const i=new Set(t);return Array.from(i)}const ev="needle-button",Mp=A();class Bx extends HTMLElement{static observedAttributes=["ar","vr","quicklook","qrcode"];constructor(){super(),this.removeEventListener("click",this.#a),this.addEventListener("click",this.#a)}attributeChangedCallback(e,t,i){this.#l()}#t;#n;#s;#e;#i;#r;#o;#l(){if(this.#e?.remove(),this.getAttribute("ar")!=null)this.#i??=new co,this.#e=this.#i.createARButton(),this.setAttribute("aria-label","Enter augmented reality mode");else if(this.getAttribute("vr")!=null)this.#i??=new co,this.#e=this.#i.createVRButton(),this.setAttribute("aria-label","Enter virtual reality mode");else if(this.getAttribute("quicklook")!=null)this.#i??=new co,this.#e=this.#i.createQuicklookButton(),this.setAttribute("aria-label","View in AR with Apple Quick Look");else if(this.getAttribute("qrcode")!=null)this.#r??=new Fi,this.#e=this.#r.createQRCode({anchorElement:this}),this.setAttribute("aria-label","Share application with QR code");else{Mp?console.warn("No button type specified for <needle-button>. Use either ar, vr or quicklook attribute."):console.debug("No button type specified for <needle-button>. Use either ar, vr or quicklook attribute."),this.setAttribute("aria-label","Needle Button with no specified type");return}this.#t??=this.attachShadow({mode:"open"}),this.#n??=document.createElement("slot"),this.#s??=document.createElement("style"),this.#s.innerHTML=`
|
|
1625
|
-
button {
|
|
1626
|
-
all: unset;
|
|
1627
|
-
}
|
|
1628
|
-
`,this.getAttribute("unstyled")!=null||(this.#s.innerHTML+=`
|
|
1629
|
-
:host {
|
|
1630
|
-
display: inline-flex;
|
|
1631
|
-
align-items: center;
|
|
1632
|
-
justify-content: center;
|
|
1633
|
-
width: fit-content;
|
|
1634
|
-
|
|
1635
|
-
padding: 0.4rem .5rem;
|
|
1636
|
-
border-radius: 100vw;
|
|
1637
|
-
|
|
1638
|
-
background: rgba(245, 245, 245, .8);
|
|
1639
|
-
backdrop-filter: blur(10px);
|
|
1640
|
-
|
|
1641
|
-
cursor: pointer;
|
|
1642
|
-
color: black;
|
|
1643
|
-
outline: rgba(0,0,0,.05) 1px solid;
|
|
1644
|
-
|
|
1645
|
-
transition: all .2s;
|
|
1646
|
-
}
|
|
1647
|
-
:host(:hover) {
|
|
1648
|
-
background: rgba(255, 255, 255, 1);
|
|
1649
|
-
transition: background .2s;
|
|
1650
|
-
}
|
|
1651
|
-
slot {
|
|
1652
|
-
display: flex;
|
|
1653
|
-
align-items: center;
|
|
1654
|
-
justify-content: center;
|
|
1655
|
-
gap: .5rem;
|
|
1656
|
-
}
|
|
1657
|
-
`),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),qd(em,{element:this.#t}),this.#o?.disconnect(),this.#o??=new MutationObserver(()=>this.#c()),this.#o.observe(this.#e,{attributes:!0}),Mp&&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=>{Mp&&console.log("Needle Button clicked",{defaultPrevented:e.defaultPrevented,hasButton:!!this.#e}),!e.defaultPrevented&&this.#e&&this.#e.click()}}typeof window<"u"&&!window.customElements.get(ev)&&window.customElements.define(ev,Bx);const jl=x("debugavatar");class Wy{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 Fx{avatarRegistryUrl=null;async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let i=null;if(typeof t=="string"){if(i=await this.loadAvatar(e,t),!i){const o=new gn;i=S.instantiate(ka(t,e.scene),o)}}else i=t;if(!i)return null;const n=this.findAvatar(i);return n.isValid?(jl&&console.log("[Custom Avatar] valid config",t,jl?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,jl?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(jl&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const n=await fetch("./"+t);let o=null;if(n.ok){const a=await n.blob();a&&(o=await a.arrayBuffer())}return o?(await un().parseSync(e,o,null,0))?.scene??null:null}const i=new X.GLTFLoader;return gg(i,e),new Promise((n,o)=>{const r=this.avatarRegistryUrl+"/"+t;i.load(r,async a=>{await un().createBuiltinComponents(e,r,a,null,void 0),n(a.scene)},a=>{jl&&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 Wy(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 Ux{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}class zx{}const nA=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:ue,ActionCollection:qw,ActionModel:Jt,AlignmentConstraint:qc,Animation:Tt,AnimationCurve:hh,AnimationExtension:Bu,AnimationTrackHandler:Ec,Animator:lt,AnimatorController:Vi,Antialiasing:uh,Attractor:rl,AudioExtension:kr,AudioListener:ds,AudioSource:vi,AudioTrackHandler:ps,Avatar:po,AvatarBlink_Simple:Cr,AvatarEyeLook_Rotation:Cg,AvatarLoader:Fx,AvatarMarker:Oe,AvatarModel:Wy,Avatar_Brain_LookAt:Pc,Avatar_MouthShapes:Kc,Avatar_MustacheShake:xg,Avatar_POI:cr,AxesHelper:Ha,BaseUIComponent:Wi,BasicIKConstraint:Og,BehaviorExtension:iy,BehaviorModel:xt,BloomEffect:Zu,BoxCollider:Tu,BoxGizmo:Ar,BoxHelperComponent:_t,Button:Ds,CallInfo:hs,Camera:si,CameraTargetReachedEvent:Cc,Canvas:Fa,CanvasGroup:mo,CapsuleCollider:bs,ChangeMaterialOnClick:qg,ChangeTransformOnClick:Rr,CharacterController:Pr,CharacterControllerInput:Cs,ChromaticAberration:fh,ClickThrough:gf,ColorAdjustments:Ro,ColorBySpeedModule:ol,ColorOverLifetimeModule:Qu,ContactShadows:Zc,ControlTrackHandler:cf,CursorFollow:$r,CustomBranding:Tr,Deletable:Eg,DeleteBox:ao,DepthOfField:bn,DeviceFlag:Au,DocumentExtension:Ux,DragControls:Zo,DropListener:Os,Duplicatable:Fg,EffectWrapper:Rc,EmissionModule:Es,EmphasizeOnClick:Ya,EnvironmentScene:pf,EventList:ne,EventListEvent:Mu,EventSystem:Gt,EventTrigger:Iu,FieldWithDefault:kw,FixedJoint:gy,Fog:tl,GltfExport:$g,GltfExportBox:Ng,Gradient:Lr,Graphic:ah,GraphicRaycaster:ku,GridHelper:il,GridLayoutGroup:ly,GroundProjectedEnv:Xn,GroupActionModel:Jo,HideOnStart:Ii,HingeJoint:ch,HorizontalLayoutGroup:ay,get HoverAnimation(){return exports.HoverAnimation},Image:dl,InheritVelocityModule:xy,InputField:jy,InstanceHandle:hr,InstancingHandler:gr,Interactable:Rg,Keyframe:oi,LODGroup:Hu,LODModel:nl,Light:Pt,LimitVelocityOverLifetimeModule:nt,LogStats:kg,LookAt:By,LookAtConstraint:yy,MainModule:Lt,MarkerTrackHandler:lf,MaskableGraphic:lh,MeshCollider:xo,MeshRenderer:th,MinMaxCurve:H,MinMaxGradient:Ir,NeedleMenu:Yn,NestedGltf:sl,Networking:vy,NoiseModule:me,ObjectRaycaster:$i,OffsetConstraint:Dr,OpenURL:ul,OrbitControls:de,Outline:el,Padding:Er,ParticleBurst:ou,ParticleSubEmitter:Sy,ParticleSystem:kc,ParticleSystemRenderer:Yi,PhysicsExtension:ny,PixelationEffect:ph,PlayAnimationOnClick:Oc,PlayAudioOnClick:fo,PlayableDirector:br,PlayerColor:Ua,PointerEventData:Qc,PostProcessingHandler:za,PreliminaryAction:Ka,PreliminaryTrigger:nh,RawImage:uf,Rect:Zw,RectTransform:mn,ReflectionProbe:os,RegisteredAnimationInfo:so,RemoteSkybox:ef,Renderer:Ht,RendererLightmap:Ig,Rigidbody:$e,RotationBySpeedModule:Qi,RotationOverLifetimeModule:_n,SceneSwitcher:We,ScreenCapture:Eo,ScreenSpaceAmbientOcclusion:Ts,ScreenSpaceAmbientOcclusionN8:vn,ScrollFollow:Ls,SeeThrough:As,SetActiveOnClick:Xg,ShadowCatcher:_h,ShapeModule:wy,SharpeningEffect:gh,SignalAsset:af,SignalReceiver:Sh,SignalReceiverEvent:xh,SignalTrackHandler:Tc,Size:Kw,SizeBySpeedModule:di,SizeOverLifetimeModule:jr,SkinnedMeshRenderer:jg,SmoothFollow:nf,SpatialGrabRaycaster:pr,SpatialHtml:Ph,SpatialTrigger:sf,SpatialTriggerReceiver:Gn,SpectatorCamera:of,SphereCollider:qa,SplineContainer:Nr,SplineData:qn,SplineWalker:Zi,Sprite:Ms,SpriteData:Oa,SpriteRenderer:ci,SpriteSheet:Ba,SubEmitterSystem:ru,SyncedCamera:Ey,SyncedRoom:wn,SyncedTransform:pn,TapGestureTrigger:Yg,TeleportTarget:Vu,TestRunner:Ty,TestSimulateUserData:Ay,Text:Dt,TextBuilder:oy,TextExtension:Wu,TextureSheetAnimationModule:It,TiltShiftEffect:Zn,ToneMappingEffect:go,TrailModule:De,TransformData:Te,TransformGizmo:Vr,TriggerBuilder:Et,TriggerModel:lo,UIRaycastUtils:_g,UIRootComponent:oh,USDZExporter:Wn,USDZText:ga,USDZUIExtension:hy,UsageMarker:Jc,VariantAction:Hg,VelocityOverLifetimeModule:Fe,VerticalLayoutGroup:ry,VideoPlayer:tt,get ViewBox(){return exports.ViewBox},Vignette:Ur,VisibilityAction:sh,Voip:wo,Volume:zr,VolumeParameter:z,VolumeProfile:Yu,WebARCameraBackground:Mh,WebARSessionRoot:Ui,WebXR:$u,WebXRImageTracking:kh,WebXRImageTrackingModel:js,WebXRPlaneTracking:Bs,WebXRTrackedImage:Na,XRControllerFollow:Is,XRControllerModel:vs,XRControllerMovement:xi,XRFlag:ji,XRRig:bf,XRState:Wt,__Ignore:zx},Symbol.toStringTag,{value:"Module"})),Dc=x("debugmissingcamera");ce.registerCallback(le.MissingCamera,s=>{Dc&&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 si;if(i.sourceId=s.files?.[0]?.src??"unknown",i.fieldOfView=35,s.context.domElement.getAttribute("transparent")!=null)i.clearFlags=lr.Uninitialized;else if(s.context.domElement.getAttribute("background-image")?.length||s.context.lightmaps.tryGetSkybox(i.sourceId))i.clearFlags=lr.Skybox;else{if(i.clearFlags=lr.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 pf("neutral");e.environment=a.fromScene(l,.025).texture}}const o=nr(t,i,!0);return t.position.x=0,t.position.y=1,t.position.z=2,s.context.domElement?.cameraControls!=!1&&Nx(s.context,o),o});ce.registerCallback(le.ContextCreated,s=>{if(!s.context.mainCamera){Dc&&console.log("Will not auto-fit because a default camera exists");return}if(s.context.domElement?.cameraControls==!0){if(fv(s.context.mainCamera)?.isCameraController==!0){Dc&&console.log("Will not auto-fit because a camera controller exists");return}Nx(s.context)}});function Nx(s,e){e=e??s.mainCameraComponent;const t=e?.gameObject;if(Dc&&console.log("Creating default camera controls",e?.name),t){const i=Vc(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,Dc&&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")}ce.registerCallback(le.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 Tt&&n.playAutomatically||n instanceof lt||n instanceof br&&n.playOnAwake===!0)return!0;if(n instanceof Tt)return n.playAutomatically=!0,!0;if(n instanceof br)return n.playOnAwake=!0,!0}},!0)!==!0&&Hn.autoplayAnimations(t.file)});exports.SplineUtils=void 0;(s=>{function e(t,i=!1,n=.75){const o=new Nr,r=1-I.clamp(n,0,1);return t.forEach((a,l)=>{const h=new c.Vector3;l<t.length-1?h.subVectors(t[l+1],a).normalize().multiplyScalar(r):i&&t.length>1&&h.subVectors(t[0],a).normalize().multiplyScalar(r);const d=new qn;d.position.copy(a),d.tangentIn.copy(h),d.tangentOut.copy(h),o.addKnot(d)}),o.closed=i,o}s.createFromPoints=e})(exports.SplineUtils||(exports.SplineUtils={}));class sA extends ae.WorkerBase{constructor(){super(new Worker(new URL("/generateMeshBVH.worker-DiCnZlf3.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:_a&&_a.tagName.toUpperCase()==="SCRIPT"&&_a.src||new URL("needle-engine.bundle-CrqNZdEN.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=ae.MeshBVH.deserialize(u,t,{setIndex:!1}),y=Object.assign({setBoundingBox:!0},i);if(t.attributes.position.array=p,u.index)if(t.index)t.index.array=u.index;else{const _=new c.BufferAttribute(u.index,1,!1);t.setIndex(_)}y.setBoundingBox&&(t.boundingBox=m.getBoundingBox(new c.Box3)),i.onProgress&&i.onProgress(d.progress),n(m),e.onmessage=null}else i.onProgress&&i.onProgress(d.progress)};const r=t.index?t.index.array:null,a=t.attributes.position.array,l=[a];r&&l.push(r),e.postMessage({index:r,position:a,options:{...i,onProgress:null,includedProgressCallback:!!i.onProgress,groups:[...t.groups]}},l.map(h=>h.buffer).filter(h=>typeof SharedArrayBuffer>"u"||!(h instanceof SharedArrayBuffer)))})}}const oA=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:sA},Symbol.toStringTag,{value:"Module"}));exports.$componentName=Dv;exports.$physicsKey=yC;exports.ActionBuilder=ue;exports.ActionCollection=qw;exports.ActionModel=Jt;exports.Addressables=I0;exports.AlignmentConstraint=qc;exports.AmbientMode=Sa;exports.Animation=Tt;exports.AnimationCurve=hh;exports.AnimationExtension=Bu;exports.AnimationTrackHandler=Ec;exports.AnimationUtils=Hn;exports.Animator=lt;exports.AnimatorConditionMode=Zs;exports.AnimatorController=Vi;exports.AnimatorControllerParameterType=yg;exports.AnimatorStateInfo=Nl;exports.Antialiasing=uh;exports.Application=fn;exports.AssetDatabase=Jv;exports.AssetReference=Z;exports.Attractor=rl;exports.AudioExtension=kr;exports.AudioListener=ds;exports.AudioSource=vi;exports.AudioTrackHandler=ps;exports.Avatar=po;exports.AvatarBlink_Simple=Cr;exports.AvatarEyeLook_Rotation=Cg;exports.AvatarLoader=Fx;exports.AvatarMarker=Oe;exports.AvatarModel=Wy;exports.Avatar_Brain_LookAt=Pc;exports.Avatar_MouthShapes=Kc;exports.Avatar_MustacheShake=xg;exports.Avatar_POI=cr;exports.Axes=pa;exports.AxesHelper=Ha;exports.BUILD_TIME=mc;exports.BaseUIComponent=Wi;exports.BasicIKConstraint=Og;exports.BehaviorExtension=iy;exports.BehaviorModel=xt;exports.BloomEffect=Zu;exports.BoxCollider=Tu;exports.BoxGizmo=Ar;exports.BoxHelperComponent=_t;exports.Button=Ds;exports.ButtonsFactory=Fi;exports.CallDirection=uw;exports.CallInfo=hs;exports.Camera=si;exports.CameraTargetReachedEvent=Cc;exports.Canvas=Fa;exports.CanvasGroup=mo;exports.CapsuleCollider=bs;exports.ChangeMaterialOnClick=qg;exports.ChangeTransformOnClick=Rr;exports.CharacterController=Pr;exports.CharacterControllerInput=Cs;exports.ChromaticAberration=fh;exports.CircularBuffer=_i;exports.ClearFlags=lr;exports.ClickThrough=gf;exports.ClipExtrapolation=kn;exports.Collider=Xi;exports.Collision=Iv;exports.CollisionDetectionMode=Ou;exports.ColorAdjustments=Ro;exports.ColorBySpeedModule=ol;exports.ColorOverLifetimeModule=Qu;exports.Component=TP;exports.Component$1=R;exports.ComponentLifecycleEvents=gu;exports.Components=nA;exports.ConnectionEvents=qv;exports.ContactPoint=Lv;exports.ContactShadows=Zc;exports.Context=U;exports.ContextArgs=gP;exports.ContextEvent=le;exports.ContextRegistry=ce;exports.ControlTrackHandler=cf;exports.CursorFollow=$r;exports.CustomBranding=Tr;exports.CustomShader=ve;exports.DefaultReflectionMode=Hd;exports.Deletable=Eg;exports.DeleteBox=ao;exports.DepthOfField=bn;exports.DeviceFlag=Au;exports.DocumentExtension=Ux;exports.DragControls=Zo;exports.DragMode=Tg;exports.DropListener=Os;exports.Duplicatable=Fg;exports.EffectWrapper=Rc;exports.EmissionModule=Es;exports.EmphasizeOnClick=Ya;exports.EngineLoadingView=Ac;exports.EnvironmentScene=pf;exports.EventList=ne;exports.EventListEvent=Mu;exports.EventSystem=Gt;exports.EventTrigger=Iu;exports.FieldWithDefault=kw;exports.FileReference=rr;exports.FileReferenceSerializer=B0;exports.FileSpawnModel=GO;exports.File_Event=bw;exports.FixedJoint=gy;exports.Fog=tl;exports.FrameEvent=ge;exports.GENERATOR=Ea;exports.GameObject=S;exports.Gizmos=B;exports.GltfExport=$g;exports.GltfExportBox=Ng;exports.Gradient=Lr;exports.Graphic=ah;exports.GraphicRaycaster=ku;exports.Graphics=ho;exports.GridHelper=il;exports.GridLayoutGroup=ly;exports.GroundProjectedEnv=Xn;exports.GroupActionModel=Jo;exports.HideFlags=du;exports.HideOnStart=Ii;exports.HingeJoint=ch;exports.HorizontalLayoutGroup=ay;exports.HostData=y1;exports.Image=dl;exports.ImageReference=or;exports.ImageReferenceSerializer=j0;exports.InheritVelocityModule=xy;exports.Input=Nv;exports.InputEventQueue=ti;exports.InputEvents=Pe;exports.InputField=jy;exports.InstanceHandle=hr;exports.InstancingHandler=gr;exports.InstancingUtil=Ni;exports.InstantiateEvent=c0;exports.InstantiateIdProvider=wt;exports.InstantiateOptions=gn;exports.Interactable=Rg;exports.JoinedRoomResponse=LC;exports.KeyEventArgs=SC;exports.Keyframe=oi;exports.LODGroup=Hu;exports.LODModel=nl;exports.LeftRoomResponse=IC;exports.Light=Pt;exports.LightData=V0;exports.LimitVelocityOverLifetimeModule=nt;exports.LoadingElementOptions=$T;exports.LogStats=kg;exports.LogType=gi;exports.LookAt=By;exports.LookAtConstraint=yy;exports.MODULES=T;exports.MainModule=Lt;exports.MarkerTrackHandler=lf;exports.MarkerType=Dy;exports.MaskableGraphic=lh;exports.MaterialPropertyBlock=ys;exports.Mathf=I;exports.MeshCollider=xo;exports.MeshRenderer=th;exports.MinMaxCurve=H;exports.MinMaxGradient=Ir;exports.NEEDLE_ENGINE_FEATURE_FLAGS=tg;exports.NEKeyboardEvent=Bl;exports.NEPointerEvent=ss;exports.NeedleButtonElement=Bx;exports.NeedleEngineWebComponent=$y;exports.NeedleMenu=Yn;exports.NeedlePatchesKey=fd;exports.NeedleXRController=Hm;exports.NeedleXRSession=q;exports.NeedleXRSync=Yv;exports.NeedleXRUtils=Zv;exports.NestedGltf=sl;exports.NetworkConnection=Qv;exports.NetworkedStreamEvents=Fn;exports.NetworkedStreams=Yc;exports.Networking=vy;exports.NewInstanceModel=d0;exports.NoiseModule=me;exports.ObjectRaycaster=$i;exports.ObjectUtils=bo;exports.OffsetConstraint=Dr;exports.OneEuroFilter=dd;exports.OneEuroFilterXYZ=Lm;exports.OpenURL=ul;exports.OrbitControls=de;exports.Outline=el;exports.OwnershipEvent=Xv;exports.OwnershipModel=Ym;exports.PUBLIC_KEY=no;exports.Padding=Er;exports.ParticleBurst=ou;exports.ParticleSubEmitter=Sy;exports.ParticleSystem=kc;exports.ParticleSystemBaseBehaviour=ko;exports.ParticleSystemRenderer=Yi;exports.ParticleSystemShapeType=su;exports.PeerHandle=us;exports.PeerNetworking=Hv;exports.Physics=Ia;exports.PhysicsExtension=ny;exports.PhysicsMaterialCombine=st;exports.PixelationEffect=ph;exports.PlayAnimationOnClick=Oc;exports.PlayAudioOnClick=fo;exports.PlayableDirector=br;exports.PlayerColor=Ua;exports.PlayerState=zi;exports.PlayerStateEvent=Yw;exports.PlayerSync=ey;exports.PlayerView=U0;exports.PlayerViewManager=z0;exports.PointerEventData=Qc;exports.PointerType=pu;exports.PostProcessingEffect=Xe;exports.PostProcessingEffectOrder=et;exports.PostProcessingHandler=za;exports.PreliminaryAction=Ka;exports.PreliminaryTrigger=nh;exports.PrimitiveType=Va;exports.Progress=oe;exports.PromiseAllWithErrors=Am;exports.PromiseErrorResult=Ep;exports.RGBAColor=te;exports.RapierPhysics=Ma;exports.RawImage=uf;exports.RaycastOptions=vo;exports.Rect=Zw;exports.RectTransform=mn;exports.ReflectionProbe=os;exports.RegisteredAnimationInfo=so;exports.RemoteSkybox=ef;exports.RenderTexture=Bn;exports.RenderTextureSerializer=cw;exports.Renderer=Ht;exports.RendererData=N0;exports.RendererLightmap=Ig;exports.Rigidbody=$e;exports.RigidbodyConstraints=Ve;exports.RoomEvents=K;exports.RotationBySpeedModule=Qi;exports.RotationOverLifetimeModule=_n;exports.SceneLightSettings=Jd;exports.SceneSwitcher=We;exports.ScreenCapture=Eo;exports.ScreenSpaceAmbientOcclusion=Ts;exports.ScreenSpaceAmbientOcclusionN8=vn;exports.ScrollFollow=Ls;exports.SeeThrough=As;exports.SendQueue=ln;exports.SerializationContext=lg;exports.SetActiveOnClick=Xg;exports.ShadowCatcher=_h;exports.ShapeModule=wy;exports.ShapeOverlapResult=jv;exports.SharpeningEffect=gh;exports.SignalAsset=af;exports.SignalReceiver=Sh;exports.SignalReceiverEvent=xh;exports.SignalTrackHandler=Tc;exports.Size=Kw;exports.SizeBySpeedModule=di;exports.SizeOverLifetimeModule=jr;exports.SkinnedMeshRenderer=jg;exports.SmoothFollow=nf;exports.SpatialGrabRaycaster=pr;exports.SpatialHtml=Ph;exports.SpatialTrigger=sf;exports.SpatialTriggerReceiver=Gn;exports.SpectatorCamera=of;exports.SphereCollider=qa;exports.SphereIntersection=Jm;exports.SplineContainer=Nr;exports.SplineData=qn;exports.SplineWalker=Zi;exports.Sprite=Ms;exports.SpriteData=Oa;exports.SpriteRenderer=ci;exports.SpriteSheet=Ba;exports.StateMachineBehaviour=BP;exports.StreamEndedEvent=vg;exports.StreamReceivedEvent=dw;exports.SubEmitterSystem=ru;exports.SyncedCamera=Ey;exports.SyncedRoom=wn;exports.SyncedTransform=pn;exports.TapGestureTrigger=Yg;exports.TeleportTarget=Vu;exports.TestRunner=Ty;exports.TestSimulateUserData=Ay;exports.Text=Dt;exports.TextBuilder=oy;exports.TextExtension=Wu;exports.TextureSheetAnimationModule=It;exports.TiltShiftEffect=Zn;exports.Time=$0;exports.ToneMappingEffect=go;exports.TrackHandler=hl;exports.TrackType=fi;exports.TrailModule=De;exports.TransformData=Te;exports.TransformGizmo=Vr;exports.TriggerBuilder=Et;exports.TriggerModel=lo;exports.TypeStore=P;exports.UIRaycastUtils=_g;exports.UIRootComponent=oh;exports.USDDocument=Wg;exports.USDObject=qe;exports.USDWriter=Fw;exports.USDZExporter=Uw;exports.USDZExporter$1=Wn;exports.USDZText=ga;exports.USDZUIExtension=hy;exports.UriSerializer=hw;exports.UsageMarker=Jc;exports.UserJoinedOrLeftRoomModel=jC;exports.VERSION=ii;exports.VariantAction=Hg;exports.VelocityOverLifetimeModule=Fe;exports.VerticalLayoutGroup=ry;exports.VideoPlayer=tt;exports.ViewDevice=gs;exports.Vignette=Ur;exports.VisibilityAction=sh;exports.Voip=wo;exports.Volume=zr;exports.VolumeParameter=z;exports.VolumeProfile=Yu;exports.WaitForFrames=Q1;exports.WaitForPromise=F0;exports.WaitForSeconds=dg;exports.Watch=ms;exports.WebARCameraBackground=Mh;exports.WebARSessionRoot=Ui;exports.WebXR=$u;exports.WebXRButtonFactory=co;exports.WebXRImageTracking=kh;exports.WebXRImageTrackingModel=js;exports.WebXRPlaneTracking=Bs;exports.WebXRTrackedImage=Na;exports.XRControllerFollow=Is;exports.XRControllerModel=vs;exports.XRControllerMovement=xi;exports.XRFlag=ji;exports.XRRig=bf;exports.XRState=Wt;exports.XRStateFlag=Ln;exports.__Ignore=zx;exports.__internalNotifyObjectDestroyed=a1;exports.activeInHierarchyFieldName=jn;exports.addAttributeChangeCallback=Em;exports.addComponent=cn;exports.addCustomExtensionPlugin=gM;exports.addNewComponent=nr;exports.addPatch=uu;exports.apply=_u;exports.applyHMRChanges=EP;exports.applyPrototypeExtensions=S0;exports.beginListenDestroy=h0;exports.beginListenInstantiate=f0;exports.binaryIdentifierCasts=qm;exports.build_scene_functions=mP;exports.builtinComponentKeyName=qo;exports.calculateProgress01=Vy;exports.clearMessages=gS;exports.colorSerializer=JP;exports.compareAssociation=y0;exports.componentSerializer=xd;exports.copyTexture=vv;exports.createMotion=sw;exports.debugNet=Yt;exports.debugOwner=Fl;exports.decompressGpuTexture=$w;exports.deepClone=Ic;exports.delay=_s;exports.delayForFrames=jc;exports.deserializeObject=Wd;exports.destroy=bi;exports.destroyComponentInstance=O0;exports.determineMimeTypeFromExtension=vw;exports.disposeObjectResources=we;exports.disposeStream=Un;exports.editorGuidKeyName=Jl;exports.enableSpatialConsole=ba;exports.euler=tO;exports.eventListSerializer=oO;exports.exportAsGLTF=eA;exports.findByGuid=hg;exports.findObjectOfType=Wa;exports.findObjectsOfType=k0;exports.findResourceUsers=eg;exports.fitCamera=ow;exports.fitObjectIntoVolume=xv;exports.foreachComponent=fr;exports.foreachComponentEnumerator=vu;exports.forward=LS;exports.generateQRCode=H0;exports.generateSeed=u0;exports.getBoundingBox=ri;exports.getCameraController=fv;exports.getComponent=xr;exports.getComponentInChildren=Wc;exports.getComponentInParent=vc;exports.getComponents=$c;exports.getComponentsInChildren=$a;exports.getComponentsInParent=yu;exports.getFormattedDate=Lw;exports.getIconElement=vt;exports.getIconTexture=Jp;exports.getLoader=un;exports.getOrAddComponent=Vc;exports.getParam=x;exports.getParentHierarchyPath=BS;exports.getPath=Xx;exports.getPeerOptions=EC;exports.getPeerjsInstance=Gv;exports.getResourceUserCount=c1;exports.getTempColor=gv;exports.getTempQuaternion=ei;exports.getTempVector=F;exports.getUrlParams=Lc;exports.getVisibleInCustomShadowRendering=wv;exports.getWorldDirection=yv;exports.getWorldEuler=Bm;exports.getWorldPosition=Y;exports.getWorldQuaternion=pe;exports.getWorldRotation=hu;exports.getWorldScale=je;exports.hasCommercialLicense=$n;exports.hasIndieLicense=Hc;exports.hasPointerEventComponent=Yd;exports.hasProLicense=Vn;exports.hideDebugConsole=Ov;exports.imageToCanvas=Ww;exports.instantiate=uo;exports.invokeLoadedImportPluginHooks=Mw;exports.invokeXRSessionEnd=zv;exports.invokeXRSessionStart=Uv;exports.isActiveInHierarchy=R0;exports.isActiveSelf=Ga;exports.isAndroidDevice=eS;exports.isAnimationAction=bv;exports.isComponent=$m;exports.isDebugMode=Wx;exports.isDesktop=Yx;exports.isDestroyed=ur;exports.isDevEnvironment=A;exports.isDisposed=r1;exports.isExporting=ZT;exports.isGLTFModel=Av;exports.isHostedOnGlitch=tv;exports.isHotReloadEnabled=sm;exports.isHotReloading=kP;exports.isIPad=Zx;exports.isIconElement=q0;exports.isLocalNetwork=yi;exports.isMacOS=iS;exports.isMobileDevice=Kx;exports.isMozillaXR=tS;exports.isQuest=oS;exports.isResourceTrackingEnabled=t0;exports.isSafari=sS;exports.isUsingInstancing=bu;exports.isiOS=nS;exports.isiPad=Jx;exports.loadAsset=BT;exports.loadPMREM=Ag;exports.loadSync=Ny;exports.logHierarchy=jd;exports.lookAtInverse=OS;exports.lookAtObject=Bc;exports.lookAtScreenPoint=MS;exports.makeId=Hx;exports.makeIdFromRandomWords=sv;exports.makeNameSafe=wi;exports.markAsInstancedRendered=E0;exports.microphonePermissionsGranted=rS;exports.nameof=$x;exports.nameofFactory=iv;exports.objectSerializer=lw;exports.offXRSessionEnd=xC;exports.offXRSessionStart=wC;exports.onAfterRender=vP;exports.onBeforeRender=bP;exports.onClear=yP;exports.onDestroy=_P;exports.onInitialized=pg;exports.onStart=Cu;exports.onUpdate=Y0;exports.onXRSessionEnd=Gm;exports.onXRSessionStart=fu;exports.parseSync=Ax;exports.placeOnSurface=Sv;exports.postprocessFBXMaterials=zm;exports.prefix=qP;exports.pushState=nv;exports.randomNumber=qx;exports.registerBinaryType=Xm;exports.registerComponent=Su;exports.registerComponentExtension=Dg;exports.registerCustomEffectType=Ki;exports.registerExportExtensions=Lg;exports.registerExtensions=tu;exports.registerHotReloadType=ew;exports.registerLoader=Vm;exports.registerPrefabProvider=m0;exports.registerPrototypeExtensions=C0;exports.registerType=og;exports.relativePathPrefix=rv;exports.removeAttributeChangeCallback=Tm;exports.removeComponent=cg;exports.removeCustomImportExtensionType=yM;exports.removePatch=bC;exports.resolveUrl=ws;exports.sanitizeString=ov;exports.saveImage=kx;exports.screenshot=vT;exports.screenshot2=zy;exports.sendDestroyed=ng;exports.serializable=f;exports.serializeObject=b0;exports.serializeable=Be;exports.setActive=nc;exports.setAllowBalloonMessages=hv;exports.setAllowOverlayMessages=uS;exports.setAutoFitEnabled=Ld;exports.setCameraController=Ap;exports.setDestroyed=A0;exports.setDevEnvironment=GS;exports.setDisposable=n0;exports.setDontDestroy=na;exports.setOrAddParamsToUrl=Rp;exports.setParam=Gx;exports.setParamWithoutReload=pc;exports.setPeerOptions=TC;exports.setResourceTrackingEnabled=o1;exports.setState=km;exports.setVisibleInCustomShadowRendering=Um;exports.setWorldEuler=Fm;exports.setWorldPosition=at;exports.setWorldPositionXYZ=dr;exports.setWorldQuaternion=dn;exports.setWorldQuaternionXYZW=jm;exports.setWorldRotation=_v;exports.setWorldRotationXYZ=Fc;exports.setWorldScale=Ra;exports.showBalloonError=Uc;exports.showBalloonMessage=Se;exports.showBalloonWarning=fe;exports.showDebugConsole=Nm;exports.slerp=PS;exports.syncDestroy=zc;exports.syncField=Jg;exports.syncInstantiate=sg;exports.textureToCanvas=FS;exports.toSourceId=av;exports.tryCastBinary=$v;exports.tryDetermineMimetypeFromBinary=xw;exports.tryDetermineMimetypeFromURL=ww;exports.tryFindObject=ka;exports.tryGetGuid=Wv;exports.unregisterHotReloadType=tw;exports.unwatchWrite=Rm;exports.useForAutoFit=pv;exports.validate=St;exports.watchWrite=cu;
|