@needle-tools/engine 4.4.0-alpha.2 → 4.4.0-alpha.3

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.
Files changed (26) hide show
  1. package/CHANGELOG.md +1 -1
  2. package/dist/needle-engine.bundle.js +826 -770
  3. package/dist/needle-engine.bundle.light.js +564 -508
  4. package/dist/needle-engine.bundle.light.min.js +37 -33
  5. package/dist/needle-engine.bundle.light.umd.cjs +66 -62
  6. package/dist/needle-engine.bundle.min.js +60 -56
  7. package/dist/needle-engine.bundle.umd.cjs +67 -63
  8. package/lib/engine/webcomponents/needle menu/needle-menu.js +4 -0
  9. package/lib/engine/webcomponents/needle menu/needle-menu.js.map +1 -1
  10. package/lib/engine-components/Camera.d.ts +1 -1
  11. package/lib/engine-components/Camera.js +13 -0
  12. package/lib/engine-components/Camera.js.map +1 -1
  13. package/lib/engine-components/CameraUtils.js +2 -1
  14. package/lib/engine-components/CameraUtils.js.map +1 -1
  15. package/lib/engine-components/postprocessing/Effects/Tonemapping.js +1 -1
  16. package/lib/engine-components/postprocessing/Effects/Tonemapping.js.map +1 -1
  17. package/lib/engine-components/postprocessing/PostProcessingHandler.d.ts +2 -0
  18. package/lib/engine-components/postprocessing/PostProcessingHandler.js +68 -4
  19. package/lib/engine-components/postprocessing/PostProcessingHandler.js.map +1 -1
  20. package/package.json +1 -1
  21. package/plugins/common/license.js +14 -5
  22. package/src/engine/webcomponents/needle menu/needle-menu.ts +4 -0
  23. package/src/engine-components/Camera.ts +16 -1
  24. package/src/engine-components/CameraUtils.ts +3 -2
  25. package/src/engine-components/postprocessing/Effects/Tonemapping.ts +2 -2
  26. package/src/engine-components/postprocessing/PostProcessingHandler.ts +77 -4
@@ -3,7 +3,7 @@ Append any of these parameters to the URL to enable specific debug options.
3
3
  Example: ${n} will show an onscreen console window.`);const o=ar===!0?"":` (containing "${ar}")`;console.group("Available URL parameters:"+o);for(const r of Object.keys(s).sort())typeof ar=="string"&&!r.toLowerCase().includes(ar.toLowerCase())||(console.groupCollapsed(r),console.log("Reload with this flag enabled:"),console.log(s[r]),console.groupEnd());console.groupEnd()}},100);function Ql(){var s;return new URLSearchParams((s=globalThis.location)==null?void 0:s.search)}function C(s){ar&&!Sm.includes(s)&&Sm.push(s);const t=Ql();if(t.has(s)){const i=t.get(s);if(i){const n=Number(i);return isNaN(n)?i:n}else return!0}return!1}ar=C("help");function yO(s,t){const i=Ql();i.has(s)?i.set(s,t):i.append(s,t),document.location.search=i.toString()}function Yl(s,t,i=!0){const n=Ql();n.has(s)?t===null?n.delete(s):n.set(s,t):t!==null&&n.append(s,t),i?Sv(s,n):Om(s,n)}function Cm(s,t,i){s.has(t)?s.set(t,i.toString()):s.append(t,i.toString())}function Sv(s,t,i){window.history.pushState(i,s,"?"+t.toString())}function Om(s,t,i){window.history.replaceState(i,s,"?"+t.toString())}function vO(s){for(var t="",i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=i.length,o=0;o<s;o++)t+=i.charAt(Math.floor(Math.random()*n));return t}function bO(s,t){return Math.floor(Math.random()*(t-s+1))+s}const Cv=["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"],Ov=["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 Pv(){const s=Cv[Math.floor(Math.random()*Cv.length)],t=Ov[Math.floor(Math.random()*Ov.length)];return s+"_"+t}function kv(s){return s=s.replace(/[^a-z0-9áéíóúñü \.,_-]/gim,""),s.trim()}function ba(s,t,i=!0,n=!1){var o;if(t==null)return null;if(t.userData&&t.userData.guid===s||t.guid==s)return t;if(n&&(o=t.userData)!=null&&o.components){for(const r of t.userData.components)if(r.guid===s)return r}if(i){if(t.scenes)for(const r in t.scenes){const l=t.scenes[r],c=ba(s,l,i,n);if(c)return c}if(t.children)for(const r in t.children){const l=t.children[r],c=ba(s,l,i,n);if(c)return c}}}function Zl(s,t){if(s!=null&&typeof s=="object"){let i;Array.isArray(s)?i=[]:(i=Object.create(s),Object.assign(i,s));for(const n of Object.keys(s)){const o=s[n];t&&!t(s,n,o)?i[n]=o:o?.clone!==void 0&&typeof o.clone=="function"?i[n]=o.clone():i[n]=Zl(o,t)}return i}return s}function fs(s){return new Promise((t,i)=>{setTimeout(t,s)})}function Kl(s,t){if(s<=0)return Promise.resolve();if(t||(t=ue.Current),!t)return Promise.reject("No context");const i=t.time.frameCount+s;return new Promise((n,o)=>{if(!t)return o("No context");const r=()=>{t.time.frameCount>=i&&(t.pre_update_callbacks.splice(t.pre_update_callbacks.indexOf(r),1),n())};t.pre_update_callbacks.push(r)})}const pd=C("debugresolveurl"),Mv="rel:";function _O(s,t){return lo(s,t)}function lo(s,t){if(t===void 0)return pd&&console.warn("getPath: uri is undefined, returning uri",t),t;if(t.startsWith("./"))return t;if(t.startsWith("http"))return pd&&console.warn("getPath: uri is absolute, returning uri",t),t;if(s===void 0)return pd&&console.warn("getPath: source is undefined, returning uri",t),t;t.startsWith(Mv)&&(t=t.substring(4));const i=s.lastIndexOf("/");if(i>=0){const n=s.substring(0,i+1);for(;n.endsWith("/")&&t.startsWith("/");)t=t.substring(1);const o=n+t;return pd&&console.log("source:",s,`changed uri
4
4
  from`,t,`
5
5
  to `,o,`
6
- basePath: `+n),o}return t}class wO{constructor(t,i){a(this,"writeCallbacks",[]),a(this,"_applied",!1),a(this,"_object"),a(this,"_prop"),a(this,"_wrapperProp"),this._object=t,this._prop=i,this._wrapperProp=Symbol("$"+i),this.apply()}subscribeWrite(t){this.writeCallbacks.push(t)}unsubscribeWrite(t){const i=this.writeCallbacks.indexOf(t);i!==-1&&this.writeCallbacks.splice(i,1)}apply(){if(this._applied||!this._object)return;const t=this._object,i=this._prop;if(t[i]===void 0)return;this._applied=!0,t[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 n=t[i];t[this._wrapperProp]=n,Object.defineProperty(t,i,{get:()=>t[this._wrapperProp],set:o=>{t[this._wrapperProp]=o;for(const r of this.writeCallbacks)r(o,this._prop)}})}revoke(){if(!this._applied||!this._object)return;this._applied=!1;const t=this._object,i=this._prop;Reflect.deleteProperty(t,i);const n=t[this._wrapperProp];t[i]=n,Reflect.deleteProperty(t,this._wrapperProp)}dispose(){this.revoke(),this.writeCallbacks.length=0,this._object=null}}class eo{constructor(t,i){if(a(this,"_watches",[]),Array.isArray(i))for(const n of i)this._watches.push(new eo(t,n));else this._watches.push(new wO(t,i))}subscribeWrite(t){for(const i of this._watches)i.subscribeWrite(t)}unsubscribeWrite(t){for(const i of this._watches)i.unsubscribeWrite(t)}apply(){for(const t of this._watches)t.apply()}revoke(){for(const t of this._watches)t.revoke()}dispose(){for(const t of this._watches)t.dispose();this._watches.length=0}}const _a=Symbol("needle:watches");function md(s,t){if(!s[_a])if(s instanceof re)s[_a]=new eo(s,["x","y"]);else if(s instanceof x)s[_a]=new eo(s,["x","y","z"]);else if(s instanceof fe||s instanceof V)s[_a]=new eo(s,["x","y","z","w"]);else return!1;return s[_a].subscribeWrite(t),!0}function Pm(s,t){if(!s)return;const i=s[_a];i&&i.unsubscribeWrite(t)}var X;(s=>{let t;function i(){if(t!==void 0)return t;const z=window.navigator.userAgent,H=/Windows|MacOS|Mac OS/.test(z),ie=/Windows NT/.test(z)&&/Edg/.test(z)&&!/Win64/.test(z);return t=H&&!ie&&!_()}s.isDesktop=i;let n;function o(){return n!==void 0?n:typeof window.orientation<"u"||navigator.userAgent.indexOf("IEMobile")!==-1?n=!0:n=/iPhone|iPad|iPod|Android|IEMobile/i.test(navigator.userAgent)}s.isMobileDevice=o;function r(){return c()}s.isIPad=r;let l;function c(){return l!==void 0?l:l=/iPad/.test(navigator.userAgent)}s.isiPad=c;let h;function d(){return h!==void 0?h:h=/Android/.test(navigator.userAgent)}s.isAndroidDevice=d;let u;function p(){return u!==void 0?u:u=/WebXRViewer\//i.test(navigator.userAgent)}s.isMozillaXR=p;let g;function y(){if(g!==void 0)return g;if(navigator.userAgentData)return g=navigator.userAgentData.platform==="macOS";{const z=navigator.userAgent.toLowerCase();return g=z.includes("mac os x")||z.includes("macintosh")}}s.isMacOS=y;let f;function v(){return f!==void 0?f:f=y()&&"xr"in navigator}s.isVisionOS=v;let b;const w=["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"];function _(){return b!==void 0?b:b=w.includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}s.isiOS=_;let S;function R(){return S!==void 0||(S=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),S}s.isSafari=R;let M;function T(){return M!==void 0?M:M=navigator.userAgent.includes("OculusBrowser")}s.isQuest=T;let j;function L(){return j!==void 0||(j=document.createElement("a").relList.supports("ar")),j}s.supportsQuickLookAR=L;async function U(){try{return(await navigator.permissions.query({name:"microphone"})).state!=="denied"}catch(z){return console.error("Error querying `microphone` permissions.",z),!1}}s.microphonePermissionsGranted=U;let B;function Q(){if(B!==void 0)return B;const z=navigator.userAgent.match(/iPhone OS (\d+_\d+)/);if(z&&(B=z[1].replace("_",".")),!B){const H=navigator.userAgent.match(/(?:\(Macintosh;|iPhone;|iPad;).*Version\/(\d+\.\d+)/);H&&(B=H[1])}return B||(B=null),B}s.getiOSVersion=Q;let $;function E(){if($!==void 0)return $;const z=navigator.userAgent.match(/(?:CriOS|Chrome)\/(\d+\.\d+\.\d+\.\d+)/);return z?$=z[1].replace("_","."):$=null,$}s.getChromeVersion=E})(X||(X={}));function xO(){return X.isDesktop()}function SO(){return X.isMobileDevice()}function CO(){return X.isiPad()}function OO(){return X.isiPad()}function PO(){return X.isAndroidDevice()}function kO(){return X.isMozillaXR()}function MO(){return X.isMacOS()}function RO(){return X.isiOS()}function TO(){return X.isSafari()}function EO(){return X.isQuest()}async function AO(){return X.microphonePermissionsGranted()}const IO=/ip=(?<ip>.+?)\n/s;async function jO(){const s=await(await fetch("https://www.cloudflare.com/cdn-cgi/trace")).text(),t=IO.exec(s);return t?t[1]:null}async function LO(){const s=await fetch("https://api.db-ip.com/v2/free/self").catch(()=>null);return s?(await s.json()).ipAddress:void 0}async function DO(){const s=await fetch("https://api.db-ip.com/v2/free/self").catch(()=>null);return s?await s.json():void 0}const co=new WeakMap;function Rv(s,t,i){if(!co.get(s)){const o=new MutationObserver(r=>{BO(s,r)});co.set(s,{observer:o,attributeChangedListeners:new Map}),o.observe(s,{attributes:!0})}const n=co.get(s).attributeChangedListeners;n.has(t)||n.set(t,[]),n.get(t).push(i)}function Tv(s,t,i){if(!co.get(s))return;const n=co.get(s).attributeChangedListeners;if(!n.has(t))return;const o=n.get(t),r=o.indexOf(i);if(r!==-1&&(o.splice(r,1),o.length<=0)){n.delete(t);const l=co.get(s);l?.observer.disconnect(),co.delete(s)}}function BO(s,t){const i=co.get(s).attributeChangedListeners;for(const n of t)if(n.type==="attributes"){const o=n.attributeName,r=s.getAttribute(o);if(i.has(o))for(const l of i.get(o))l(r)}}class km{constructor(t){a(this,"reason"),this.reason=t}}async function Mm(s){const t=await Promise.allSettled(s).catch(o=>[new km(o.message)]);let i=!1;const n=t.map(o=>"value"in o?o.value:(i=!0,new km(o.reason)));return{anyFailed:i,results:n}}async function Ev(s){if(!globalThis.QRCode){const n="https://cdn.rawgit.com/davidshimjs/qrcodejs/gh-pages/qrcode.min.js";let o=document.head.querySelector(`script[src="${n}"]`);o||(o=document.createElement("script"),o.src=n,document.head.appendChild(o)),await new Promise((r,l)=>{o.addEventListener("load",()=>{r(!0)})})}const t=globalThis.QRCode,i=s.domElement??document.createElement("div");return new t(i,{width:s.width??256,height:s.height??256,colorDark:"#000000",colorLight:"#ffffff",correctLevel:t.CorrectLevel.M,...s}),i}const Av=C("debugdebug");let Jl=!1;(C("noerrors")||C("nooverlaymessages"))&&(Jl=!0);const Rm="needle_engine_global_error_container";var Oi=(s=>(s[s.Log=0]="Log",s[s.Warn=1]="Warn",s[s.Error=2]="Error",s))(Oi||{});function Tm(){return Dv}const Em=new Array;function FO(s){Em.push(s)}let Am=!1;function zO(...s){if(!Am){Am=!0;try{for(let t=0;t<Em.length;t++)Em[t](...s)}catch(t){console.error(t)}Am=!1}}const Iv=console.error,jv=function(...s){Iv.apply(console,s),WO(s),zs(2,s),Im(...s)};function Lv(s){Jl=!s,s?console.error=jv:console.error=Iv}function UO(s){return Lv(s)}function NO(){Jl||(Av&&console.warn("Patch console",window.location.hostname),console.error=jv,window.addEventListener("error",s=>{if(!s)return;const t=s.error;if(t===void 0){Gt()&&console.warn("Received unknown error",s,s.target);return}zs(2,t,s.filename,s.lineno),Im(s)},!0),window.addEventListener("unhandledrejection",s=>{Jl||s&&(s.reason?zs(2,s.reason.message,s.reason.stack):zs(2,"unhandled rejection"),Im(s))}))}let Dv=0;function Im(...s){Dv+=1,zO(...s)}function WO(s){if(Array.isArray(s))for(let t=0;t<s.length;t++){const i=s[t];typeof i=="string"&&i.startsWith("THREE.PropertyBinding: Trying to update node for track:")&&(s[t]="Some animated objects couldn't be found: see console for details")}}function zs(s,t,i,n){if(Jl)return;const o=ue.Current,r=o?.domElement??document.querySelector("needle-engine");if(r){if(Array.isArray(t)){let l="";for(let c=0;c<t.length;c++){let h=t[c];h instanceof Error&&(h=h.message),typeof h!="object"&&(c>0&&(l+=" "),l+=h)}t=l}!t||t.length<=0||VO(s,r,t)}}const ec=new Map;function VO(s,t,i){if(i==null)return;const n=qO(t);if(n.childElementCount>=20){const c=n.lastElementChild;Fv(c)}i.length>400&&(i=i.substring(0,400)+"...");const o=i;if(ec.has(o))return;const r=GO(s,i);n.prepend(r);const l=()=>{ec.delete(o),Fv(r)};ec.set(o,l),setTimeout(l,1e4)}function HO(){Av&&console.log("Clearing messages");for(const s of ec.values())s?.call(s);ec.clear()}const $O=`
6
+ basePath: `+n),o}return t}class wO{constructor(t,i){a(this,"writeCallbacks",[]),a(this,"_applied",!1),a(this,"_object"),a(this,"_prop"),a(this,"_wrapperProp"),this._object=t,this._prop=i,this._wrapperProp=Symbol("$"+i),this.apply()}subscribeWrite(t){this.writeCallbacks.push(t)}unsubscribeWrite(t){const i=this.writeCallbacks.indexOf(t);i!==-1&&this.writeCallbacks.splice(i,1)}apply(){if(this._applied||!this._object)return;const t=this._object,i=this._prop;if(t[i]===void 0)return;this._applied=!0,t[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 n=t[i];t[this._wrapperProp]=n,Object.defineProperty(t,i,{get:()=>t[this._wrapperProp],set:o=>{t[this._wrapperProp]=o;for(const r of this.writeCallbacks)r(o,this._prop)}})}revoke(){if(!this._applied||!this._object)return;this._applied=!1;const t=this._object,i=this._prop;Reflect.deleteProperty(t,i);const n=t[this._wrapperProp];t[i]=n,Reflect.deleteProperty(t,this._wrapperProp)}dispose(){this.revoke(),this.writeCallbacks.length=0,this._object=null}}class eo{constructor(t,i){if(a(this,"_watches",[]),Array.isArray(i))for(const n of i)this._watches.push(new eo(t,n));else this._watches.push(new wO(t,i))}subscribeWrite(t){for(const i of this._watches)i.subscribeWrite(t)}unsubscribeWrite(t){for(const i of this._watches)i.unsubscribeWrite(t)}apply(){for(const t of this._watches)t.apply()}revoke(){for(const t of this._watches)t.revoke()}dispose(){for(const t of this._watches)t.dispose();this._watches.length=0}}const _a=Symbol("needle:watches");function md(s,t){if(!s[_a])if(s instanceof re)s[_a]=new eo(s,["x","y"]);else if(s instanceof x)s[_a]=new eo(s,["x","y","z"]);else if(s instanceof fe||s instanceof V)s[_a]=new eo(s,["x","y","z","w"]);else return!1;return s[_a].subscribeWrite(t),!0}function Pm(s,t){if(!s)return;const i=s[_a];i&&i.unsubscribeWrite(t)}var X;(s=>{let t;function i(){if(t!==void 0)return t;const z=window.navigator.userAgent,H=/Windows|MacOS|Mac OS/.test(z),ie=/Windows NT/.test(z)&&/Edg/.test(z)&&!/Win64/.test(z);return t=H&&!ie&&!_()}s.isDesktop=i;let n;function o(){return n!==void 0?n:typeof window.orientation<"u"||navigator.userAgent.indexOf("IEMobile")!==-1?n=!0:n=/iPhone|iPad|iPod|Android|IEMobile/i.test(navigator.userAgent)}s.isMobileDevice=o;function r(){return c()}s.isIPad=r;let l;function c(){return l!==void 0?l:l=/iPad/.test(navigator.userAgent)}s.isiPad=c;let h;function d(){return h!==void 0?h:h=/Android/.test(navigator.userAgent)}s.isAndroidDevice=d;let u;function p(){return u!==void 0?u:u=/WebXRViewer\//i.test(navigator.userAgent)}s.isMozillaXR=p;let g;function y(){if(g!==void 0)return g;if(navigator.userAgentData)return g=navigator.userAgentData.platform==="macOS";{const z=navigator.userAgent.toLowerCase();return g=z.includes("mac os x")||z.includes("macintosh")}}s.isMacOS=y;let f;function v(){return f!==void 0?f:f=y()&&"xr"in navigator}s.isVisionOS=v;let b;const w=["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"];function _(){return b!==void 0?b:b=w.includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}s.isiOS=_;let S;function R(){return S!==void 0||(S=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),S}s.isSafari=R;let M;function T(){return M!==void 0?M:M=navigator.userAgent.includes("OculusBrowser")}s.isQuest=T;let L;function D(){return L!==void 0||(L=document.createElement("a").relList.supports("ar")),L}s.supportsQuickLookAR=D;async function U(){try{return(await navigator.permissions.query({name:"microphone"})).state!=="denied"}catch(z){return console.error("Error querying `microphone` permissions.",z),!1}}s.microphonePermissionsGranted=U;let B;function Q(){if(B!==void 0)return B;const z=navigator.userAgent.match(/iPhone OS (\d+_\d+)/);if(z&&(B=z[1].replace("_",".")),!B){const H=navigator.userAgent.match(/(?:\(Macintosh;|iPhone;|iPad;).*Version\/(\d+\.\d+)/);H&&(B=H[1])}return B||(B=null),B}s.getiOSVersion=Q;let $;function E(){if($!==void 0)return $;const z=navigator.userAgent.match(/(?:CriOS|Chrome)\/(\d+\.\d+\.\d+\.\d+)/);return z?$=z[1].replace("_","."):$=null,$}s.getChromeVersion=E})(X||(X={}));function xO(){return X.isDesktop()}function SO(){return X.isMobileDevice()}function CO(){return X.isiPad()}function OO(){return X.isiPad()}function PO(){return X.isAndroidDevice()}function kO(){return X.isMozillaXR()}function MO(){return X.isMacOS()}function RO(){return X.isiOS()}function TO(){return X.isSafari()}function EO(){return X.isQuest()}async function AO(){return X.microphonePermissionsGranted()}const IO=/ip=(?<ip>.+?)\n/s;async function jO(){const s=await(await fetch("https://www.cloudflare.com/cdn-cgi/trace")).text(),t=IO.exec(s);return t?t[1]:null}async function LO(){const s=await fetch("https://api.db-ip.com/v2/free/self").catch(()=>null);return s?(await s.json()).ipAddress:void 0}async function DO(){const s=await fetch("https://api.db-ip.com/v2/free/self").catch(()=>null);return s?await s.json():void 0}const co=new WeakMap;function Rv(s,t,i){if(!co.get(s)){const o=new MutationObserver(r=>{BO(s,r)});co.set(s,{observer:o,attributeChangedListeners:new Map}),o.observe(s,{attributes:!0})}const n=co.get(s).attributeChangedListeners;n.has(t)||n.set(t,[]),n.get(t).push(i)}function Tv(s,t,i){if(!co.get(s))return;const n=co.get(s).attributeChangedListeners;if(!n.has(t))return;const o=n.get(t),r=o.indexOf(i);if(r!==-1&&(o.splice(r,1),o.length<=0)){n.delete(t);const l=co.get(s);l?.observer.disconnect(),co.delete(s)}}function BO(s,t){const i=co.get(s).attributeChangedListeners;for(const n of t)if(n.type==="attributes"){const o=n.attributeName,r=s.getAttribute(o);if(i.has(o))for(const l of i.get(o))l(r)}}class km{constructor(t){a(this,"reason"),this.reason=t}}async function Mm(s){const t=await Promise.allSettled(s).catch(o=>[new km(o.message)]);let i=!1;const n=t.map(o=>"value"in o?o.value:(i=!0,new km(o.reason)));return{anyFailed:i,results:n}}async function Ev(s){if(!globalThis.QRCode){const n="https://cdn.rawgit.com/davidshimjs/qrcodejs/gh-pages/qrcode.min.js";let o=document.head.querySelector(`script[src="${n}"]`);o||(o=document.createElement("script"),o.src=n,document.head.appendChild(o)),await new Promise((r,l)=>{o.addEventListener("load",()=>{r(!0)})})}const t=globalThis.QRCode,i=s.domElement??document.createElement("div");return new t(i,{width:s.width??256,height:s.height??256,colorDark:"#000000",colorLight:"#ffffff",correctLevel:t.CorrectLevel.M,...s}),i}const Av=C("debugdebug");let Jl=!1;(C("noerrors")||C("nooverlaymessages"))&&(Jl=!0);const Rm="needle_engine_global_error_container";var Oi=(s=>(s[s.Log=0]="Log",s[s.Warn=1]="Warn",s[s.Error=2]="Error",s))(Oi||{});function Tm(){return Dv}const Em=new Array;function FO(s){Em.push(s)}let Am=!1;function zO(...s){if(!Am){Am=!0;try{for(let t=0;t<Em.length;t++)Em[t](...s)}catch(t){console.error(t)}Am=!1}}const Iv=console.error,jv=function(...s){Iv.apply(console,s),WO(s),zs(2,s),Im(...s)};function Lv(s){Jl=!s,s?console.error=jv:console.error=Iv}function UO(s){return Lv(s)}function NO(){Jl||(Av&&console.warn("Patch console",window.location.hostname),console.error=jv,window.addEventListener("error",s=>{if(!s)return;const t=s.error;if(t===void 0){Gt()&&console.warn("Received unknown error",s,s.target);return}zs(2,t,s.filename,s.lineno),Im(s)},!0),window.addEventListener("unhandledrejection",s=>{Jl||s&&(s.reason?zs(2,s.reason.message,s.reason.stack):zs(2,"unhandled rejection"),Im(s))}))}let Dv=0;function Im(...s){Dv+=1,zO(...s)}function WO(s){if(Array.isArray(s))for(let t=0;t<s.length;t++){const i=s[t];typeof i=="string"&&i.startsWith("THREE.PropertyBinding: Trying to update node for track:")&&(s[t]="Some animated objects couldn't be found: see console for details")}}function zs(s,t,i,n){if(Jl)return;const o=ue.Current,r=o?.domElement??document.querySelector("needle-engine");if(r){if(Array.isArray(t)){let l="";for(let c=0;c<t.length;c++){let h=t[c];h instanceof Error&&(h=h.message),typeof h!="object"&&(c>0&&(l+=" "),l+=h)}t=l}!t||t.length<=0||VO(s,r,t)}}const ec=new Map;function VO(s,t,i){if(i==null)return;const n=qO(t);if(n.childElementCount>=20){const c=n.lastElementChild;Fv(c)}i.length>400&&(i=i.substring(0,400)+"...");const o=i;if(ec.has(o))return;const r=GO(s,i);n.prepend(r);const l=()=>{ec.delete(o),Fv(r)};ec.set(o,l),setTimeout(l,1e4)}function HO(){Av&&console.log("Clearing messages");for(const s of ec.values())s?.call(s);ec.clear()}const $O=`
7
7
 
8
8
  @import url('https://fonts.googleapis.com/css2?family=Roboto+Flex:opsz,wght@8..144,100..1000&display=swap');
9
9
 
@@ -130,7 +130,7 @@ Open this page to get the console: `+t.toString())}const s=X.isMobileDevice()||X
130
130
  #__vconsole .vc-mask {
131
131
  overflow: hidden;
132
132
  }
133
- `,qi?.prepend(n),s===!0&&Tm()<=0&&nb(),console.log("\u{1F335} Debug console has loaded")}},t.onerror=()=>{console.warn("\u{1F335} Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),ac=!1,ri=null},t.src="https://unpkg.com/vconsole@latest/dist/vconsole.min.js",document.body.appendChild(t)}function wP(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("needle-console","\u{1F335} Inspect glTF"),t=()=>document.querySelector("#__vc_plug_"+s._id+" iframe");return s.on("renderTab",function(i){const n=globalThis["needle:codegen_files"];if(!n||n.length===0)return;let o=globalThis["needle:codegen_files"][0];const r=o.indexOf("?");r>-1&&(o=o.substring(0,r));const l=location.protocol+"//"+location.host+location.pathname+"/"+o,c=encodeURIComponent(l);s.fullUrl="https://viewer.needle.tools?inspect&file="+c;var h='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';i(h)}),s.on("show",function(){const i=t();i&&i.src!==s.fullUrl&&(i.src=s.fullUrl)}),s.on("hide",function(){const i=t();i&&(i.src="")}),s.on("addTopBar",function(i){var n=new Array;n.push({name:"Open in new window \u2197",onClick:function(o){window.open(s.fullUrl,"_blank"),ri?.hide()}}),n.push({name:"Reload",onClick:function(o){const r=t();r&&(r.src=s.fullUrl)}}),n.push({name:"Fullscreen",onClick:function(o){const r=t();r.requestFullscreen?r.requestFullscreen():r.webkitRequestFullscreen instanceof Function&&r.webkitRequestFullscreen()}}),i(n)}),s}function xP(){return document.querySelector("#__vconsole .vc-switch")||null}function SP(){return document.querySelector("#__vconsole")||null}const lb=C("debugdefines");ho('if(!globalThis[""4.4.0-alpha.2""]) globalThis[""4.4.0-alpha.2""] = "0.0.0";'),ho('if(!globalThis[""undefined""]) globalThis[""undefined""] = "unknown";'),ho('if(!globalThis[""Fri Mar 21 2025 18:59:09 GMT+0100 (Central European Standard Time)""]) globalThis[""Fri Mar 21 2025 18:59:09 GMT+0100 (Central European Standard Time)""] = "unknown";'),ho('if(!globalThis[""npk_0b7230d0d7c94c5ef23003726b2e2ccfc5ec0f20d26de8f0bda29e63698f9006""]) globalThis[""npk_0b7230d0d7c94c5ef23003726b2e2ccfc5ec0f20d26de8f0bda29e63698f9006""] = "unknown";'),ho('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.4.0-alpha.2";'),ho('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),ho('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Fri Mar 21 2025 18:59:09 GMT+0100 (Central European Standard Time)";'),ho('globalThis["__NEEDLE_PUBLIC_KEY__"] = "npk_0b7230d0d7c94c5ef23003726b2e2ccfc5ec0f20d26de8f0bda29e63698f9006";');const bs="4.4.0-alpha.2",xd="undefined",Ym="Fri Mar 21 2025 18:59:09 GMT+0100 (Central European Standard Time)";lb&&console.log(`Engine version: ${bs} (generator: ${xd})
133
+ `,qi?.prepend(n),s===!0&&Tm()<=0&&nb(),console.log("\u{1F335} Debug console has loaded")}},t.onerror=()=>{console.warn("\u{1F335} Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),ac=!1,ri=null},t.src="https://unpkg.com/vconsole@latest/dist/vconsole.min.js",document.body.appendChild(t)}function wP(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("needle-console","\u{1F335} Inspect glTF"),t=()=>document.querySelector("#__vc_plug_"+s._id+" iframe");return s.on("renderTab",function(i){const n=globalThis["needle:codegen_files"];if(!n||n.length===0)return;let o=globalThis["needle:codegen_files"][0];const r=o.indexOf("?");r>-1&&(o=o.substring(0,r));const l=location.protocol+"//"+location.host+location.pathname+"/"+o,c=encodeURIComponent(l);s.fullUrl="https://viewer.needle.tools?inspect&file="+c;var h='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';i(h)}),s.on("show",function(){const i=t();i&&i.src!==s.fullUrl&&(i.src=s.fullUrl)}),s.on("hide",function(){const i=t();i&&(i.src="")}),s.on("addTopBar",function(i){var n=new Array;n.push({name:"Open in new window \u2197",onClick:function(o){window.open(s.fullUrl,"_blank"),ri?.hide()}}),n.push({name:"Reload",onClick:function(o){const r=t();r&&(r.src=s.fullUrl)}}),n.push({name:"Fullscreen",onClick:function(o){const r=t();r.requestFullscreen?r.requestFullscreen():r.webkitRequestFullscreen instanceof Function&&r.webkitRequestFullscreen()}}),i(n)}),s}function xP(){return document.querySelector("#__vconsole .vc-switch")||null}function SP(){return document.querySelector("#__vconsole")||null}const lb=C("debugdefines");ho('if(!globalThis[""4.4.0-alpha.3""]) globalThis[""4.4.0-alpha.3""] = "0.0.0";'),ho('if(!globalThis[""undefined""]) globalThis[""undefined""] = "unknown";'),ho('if(!globalThis[""Tue Mar 25 2025 17:30:07 GMT+0100 (Central European Standard Time)""]) globalThis[""Tue Mar 25 2025 17:30:07 GMT+0100 (Central European Standard Time)""] = "unknown";'),ho('if(!globalThis[""npk_0b7230d0d7c94c5ef23003726b2e2ccfc5ec0f20d26de8f0bda29e63698f9006""]) globalThis[""npk_0b7230d0d7c94c5ef23003726b2e2ccfc5ec0f20d26de8f0bda29e63698f9006""] = "unknown";'),ho('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.4.0-alpha.3";'),ho('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),ho('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Tue Mar 25 2025 17:30:07 GMT+0100 (Central European Standard Time)";'),ho('globalThis["__NEEDLE_PUBLIC_KEY__"] = "npk_0b7230d0d7c94c5ef23003726b2e2ccfc5ec0f20d26de8f0bda29e63698f9006";');const bs="4.4.0-alpha.3",xd="undefined",Ym="Tue Mar 25 2025 17:30:07 GMT+0100 (Central European Standard Time)";lb&&console.log(`Engine version: ${bs} (generator: ${xd})
134
134
  Project built at ${Ym}`);const cc="npk_0b7230d0d7c94c5ef23003726b2e2ccfc5ec0f20d26de8f0bda29e63698f9006",_n="needle_isActiveInHierarchy",dr="builtin_components",hc="needle_editor_guid";function ho(s){try{(0,eval)(s)}catch(t){lb&&console.error(t)}}const CP='<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>',OP=btoa(CP),PP="data:image/svg+xml;base64,"+OP,kP=PP,MP=`<?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(MP);const RP='<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>',TP=btoa(RP),EP="data:image/svg+xml;charset=utf-8;base64,"+TP,AP=EP,IP=C("debugpatch");function Sd(s,t,i,n){const o=IP===t;if(!i&&!n)return;const r=t+"___needle";LP(s,t,i,n);const l=Object.getOwnPropertyDescriptor(s,t),c=s[t];o&&console.log("Patch",s.constructor.name,t,l,c),l?(o&&console.log("Apply patch with existing descriptor",s.constructor.name,t,l),typeof l.value=="function"&&(s[t]=hb(l.value,s,t))):(o&&console.log("Create patch with new property",s.constructor.name,t,l),Object.defineProperty(s,t,{set:function(h){if(typeof h=="function")this[r]=hb(h,s,t);else{const d=this[r];db(s,t,this,d,h),this[r]=h,ub(s,t,this,d,h)}},get:function(){const h=this[r];return typeof h=="function"&&h[r]?h[r]:h}}))}function jP(s,t,i){const n=Km(s,t);if(n)for(let o=n.length-1;o>=0;o--){const r=n[o];r.prefix===i&&(r.prefix=null),r.postfix===i&&(r.postfix=null),!r.prefix&&!r.postfix&&n.splice(o,1)}}const cb=Symbol("Needle:Patches:WrappedFunction");function hb(s,t,i){if(s[cb])return s;const n=function(...o){db(t,i,this,...o);const r=s.apply(this,o);return ub(t,i,this,r,...o),r};return n[cb]=!0,n}const Cd="Needle:Patches";function Zm(){return globalThis[Cd]||(globalThis[Cd]=new WeakMap),globalThis[Cd]}function Km(s,t){const i=Zm().get(s);return i?i.get(t):null}function LP(s,t,i,n){let o=Zm().get(s);o||(o=new Map,Zm().set(s,o));let r=o.get(t);r||(r=[],o.set(t,r)),r.push({prefix:i,postfix:n})}function db(s,t,i,...n){var o;if(!i)return;const r=Km(s,t);if(r)for(const l of r)(o=l.prefix)==null||o.call(i,...n)}function ub(s,t,i,n,...o){var r;if(!i)return;const l=Km(s,t);if(l)for(const c of l)(r=c.postfix)==null||r.call(i,n,...o)}const xa=[];function Od(s){xa.indexOf(s)===-1&&xa.push(s)}function DP(s){const t=xa.indexOf(s);t!==-1&&xa.splice(t,1)}const Sa=[];function Jm(s){Sa.indexOf(s)===-1&&Sa.push(s)}function BP(s){const t=Sa.indexOf(s);t!==-1&&Sa.splice(t,1)}function pb(s){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-start",{detail:s}));for(let t=0;t<xa.length;t++)xa[t](s)}function mb(s){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-end",{detail:s}));for(let t=0;t<Sa.length;t++)Sa[t](s)}const dt=C("debuginput");var Pd=(s=>(s.Mouse="mouse",s.Touch="touch",s.Controller="controller",s.Hand="hand",s))(Pd||{}),Be=(s=>(s.PointerDown="pointerdown",s.PointerUp="pointerup",s.PointerMove="pointermove",s.KeyDown="keydown",s.KeyUp="keyup",s.KeyPressed="keypress",s))(Be||{});class wn extends PointerEvent{constructor(t,i,n){super(t,n),a(this,"clientZ"),a(this,"deviceIndex"),a(this,"origin"),a(this,"source"),a(this,"mode"),a(this,"_ray"),a(this,"space"),a(this,"isClick",!1),a(this,"isDoubleClick",!1),a(this,"_used",!1),a(this,"_pointerid"),a(this,"_pointerType"),a(this,"_type"),a(this,"metadata",{}),a(this,"intersections",new Array),a(this,"_immediatePropagationStopped",!1),a(this,"_propagationStopped",!1),this.clientZ=n.clientZ,this._pointerid=n.pointerId,this._pointerType=n.pointerType,this._type=t,this.deviceIndex=n.deviceIndex,this.origin=n.origin,this.source=i,this.mode=n.mode,this._ray=n.ray,this.space=n.device}get isSpatial(){return this.mode!="screen"}get ray(){return this._ray||(this._ray=new no(this.space.worldPosition.clone(),this.space.worldForward.clone())),this._ray}set ray(t){this._ray=t}get hasRay(){return this._ray!==void 0}get used(){return this._used}use(){this._used=!0}get pointerId(){return this._pointerid}get pointerType(){return this._pointerType}get type(){return this._type}get immediatePropagationStopped(){return this._immediatePropagationStopped}get propagationStopped(){return this._immediatePropagationStopped||this._propagationStopped}stopImmediatePropagation(){var t;this._immediatePropagationStopped=!0,super.stopImmediatePropagation(),(t=this.source)==null||t.stopImmediatePropagation()}stopPropagation(){var t;this._propagationStopped=!0,super.stopPropagation(),(t=this.source)==null||t.stopPropagation(),dt&&console.warn("Stop propagation...",this.pointerId,this.pointerType)}}class dc extends KeyboardEvent{constructor(t,i,n){super(t,n),a(this,"source"),this.source=i}stopImmediatePropagation(){var t;super.stopImmediatePropagation(),(t=this.source)==null||t.stopImmediatePropagation()}}class FP{constructor(t){a(this,"key"),a(this,"keyType"),a(this,"source"),this.key=t.key,this.keyType=t.type,this.source=t}}var ai=(s=>(s[s.Early=-100]="Early",s[s.Default=0]="Default",s[s.Late=100]="Late",s))(ai||{});class gb{constructor(t){a(this,"_eventListeners",{}),a(this,"_doubleClickTimeThreshold",.2),a(this,"_longPressTimeThreshold",1),a(this,"_setCursorTypes",[]),a(this,"context"),a(this,"_pointerDown",[!1]),a(this,"_pointerUp",[!1]),a(this,"_pointerClick",[!1]),a(this,"_pointerDoubleClick",[!1]),a(this,"_pointerPressed",[!1]),a(this,"_pointerPositions",[new re]),a(this,"_pointerPositionsLastFrame",[new re]),a(this,"_pointerPositionsDelta",[new re]),a(this,"_pointerPositionsRC",[new re]),a(this,"_pointerPositionDown",[new x]),a(this,"_pointerDownTime",[]),a(this,"_pointerUpTime",[]),a(this,"_pointerUpTimestamp",[]),a(this,"_pointerIds",[]),a(this,"_pointerTypes",[""]),a(this,"_mouseWheelChanged",[!1]),a(this,"_mouseWheelDeltaY",[0]),a(this,"_pointerEvent",[]),a(this,"_pointerEventsPressed",[]),a(this,"_pointerSpace",[]),a(this,"_pressedStack",new Map),a(this,"_htmlEventSource"),a(this,"onLostFocus",()=>{for(const i in this.keysPressed)this.keysPressed[i].pressed=!1}),a(this,"_receivedPointerMoveEventsThisFrame",new Array),a(this,"onEndOfFrame",()=>{this._receivedPointerMoveEventsThisFrame.length=0;for(let i=0;i<this._pointerUp.length;i++)this._pointerUp[i]=!1;for(let i=0;i<this._pointerDown.length;i++)this._pointerDown[i]=!1;for(let i=0;i<this._pointerClick.length;i++)this._pointerClick[i]=!1;for(let i=0;i<this._pointerDoubleClick.length;i++)this._pointerDoubleClick[i]=!1;for(const i of this._pointerPositionsDelta)i.set(0,0);for(let i=0;i<this._mouseWheelChanged.length;i++)this._mouseWheelChanged[i]=!1;for(let i=0;i<this._mouseWheelDeltaY.length;i++)this._mouseWheelDeltaY[i]=0}),a(this,"onContextMenu",i=>{this.canReceiveInput(i)!==!1&&i instanceof PointerEvent&&i.pointerType}),a(this,"keysPressed",{}),a(this,"onKeyDown",i=>{if(dt&&console.log(`key down ${i.code}, ${this.context.application.hasFocus}`,i),!this.context.application.hasFocus)return;const n=this.keysPressed[i.code];if(n&&n.pressed)return;this.keysPressed[i.code]={pressed:!0,frame:this.context.time.frameCount+1,startFrame:this.context.time.frameCount+1,key:i.key,code:i.code};const o=new dc("keydown",i,i);this.onDispatchEvent(o)}),a(this,"onKeyPressed",i=>{if(!this.context.application.hasFocus)return;const n=this.keysPressed[i.code];if(!n)return;n.pressed=!0,n.frame=this.context.time.frameCount+1;const o=new dc("keypress",i,i);this.onDispatchEvent(o)}),a(this,"onKeyUp",i=>{if(!this.context.application.hasFocus)return;const n=this.keysPressed[i.code];if(!n)return;n.pressed=!1,n.frame=this.context.time.frameCount+1;const o=new dc("keyup",i,i);this.onDispatchEvent(o)}),a(this,"onWheelWindow",i=>{document.pointerLockElement&&this.onMouseWheel(i)}),a(this,"onMouseWheel",i=>{if(this.canReceiveInput(i)===!1)return;this._mouseWheelDeltaY.length<=0&&this._mouseWheelDeltaY.push(0),this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0;const n=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=n+i.deltaY}),a(this,"onPointerDown",i=>{if(this.context.isInAR||this.canReceiveInput(i)===!1)return;i.target instanceof HTMLElement&&i.target.setPointerCapture(i.pointerId);const n=this.getPointerId(i);dt&&De(`pointer down #${n}, identifier:${i.pointerId}`);const o=this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),r=new wn("pointerdown",i,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:i.button,clientX:i.clientX,clientY:i.clientY,pointerType:i.pointerType,buttonName:this.getButtonName(i),device:o,pressure:i.pressure});this.onDown(r)}),a(this,"onPointerMove",i=>{if(this.context.isInAR||this._receivedPointerMoveEventsThisFrame.includes(i.pointerId))return;this._receivedPointerMoveEventsThisFrame.push(i.pointerId);let n=i.button;i.pointerType==="mouse"&&(n=this.getFirstPressedButtonForPointer(0)??0);const o=this.getPointerId(i,n);n===-1&&(n=o);const r=this.getAndUpdateSpatialObjectForScreenPosition(o,i.clientX,i.clientY),l=new wn("pointermove",i,{origin:this,mode:"screen",deviceIndex:0,pointerId:o,button:n,clientX:i.clientX,clientY:i.clientY,pointerType:i.pointerType,buttonName:this.getButtonName(i),device:r,pressure:i.pressure});this.onMove(l)}),a(this,"onPointerCancel",i=>{this.context.isInAR||(dt&&console.log("Pointer cancel",i),this.onPointerUp(i))}),a(this,"onPointerUp",i=>{if(this.context.isInAR)return;i.target instanceof HTMLElement&&i.target.releasePointerCapture(i.pointerId);const n=this.getPointerId(i),o=new wn("pointerup",i,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:i.button,clientX:i.clientX,clientY:i.clientY,pointerType:i.pointerType,buttonName:this.getButtonName(i),device:this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),pressure:i.pressure});this.onUp(o),this._pointerIds[n]=-1,dt&&console.log("ID="+n,"PointerId="+i.pointerId,"ALL:",[...this._pointerIds])}),a(this,"onTouchStart",i=>{if(this.context.isInAR)for(let n=0;n<i.changedTouches.length;n++){const o=i.changedTouches[n],r=this.getPointerIndex(o.identifier),l=this.getAndUpdateSpatialObjectForScreenPosition(r,o.clientX,o.clientY),c=new wn("pointerdown",i,{origin:this,mode:"screen",deviceIndex:0,pointerId:r,button:0,clientX:o.clientX,clientY:o.clientY,pointerType:"touch",buttonName:"unknown",device:l,pressure:o.force});this.onDown(c)}}),a(this,"onTouchMove",i=>{if(this.context.isInAR)for(let n=0;n<i.changedTouches.length;n++){const o=i.changedTouches[n],r=this.getPointerIndex(o.identifier),l=this.getAndUpdateSpatialObjectForScreenPosition(r,o.clientX,o.clientY),c=new wn("pointermove",i,{origin:this,mode:"screen",deviceIndex:0,pointerId:r,button:0,clientX:o.clientX,clientY:o.clientY,pointerType:"touch",buttonName:"unknown",device:l,pressure:o.force});this.onMove(c)}}),a(this,"onTouchEnd",i=>{if(this.context.isInAR)for(let n=0;n<i.changedTouches.length;n++){const o=i.changedTouches[n],r=this.getPointerIndex(o.identifier),l=new wn("pointerup",i,{origin:this,mode:"screen",deviceIndex:0,pointerId:r,button:0,clientX:o.clientX,clientY:o.clientY,pointerType:"touch",buttonName:"unknown",device:this.getAndUpdateSpatialObjectForScreenPosition(r,o.clientX,o.clientY),pressure:o.force});this.onUp(l),this._pointerIds[r]=-1}}),a(this,"tempNearPlaneVector",new x),a(this,"tempFarPlaneVector",new x),a(this,"tempLookMatrix",new ne),this.context=t,this.context.post_render_callbacks.push(this.onEndOfFrame)}addEventListener(t,i,n){if(this._eventListeners[t]||(this._eventListeners[t]=[]),!i||typeof i!="function"){console.error("Invalid call to addEventListener: callback is required and must be a function!");return}n?n={...n}:n={};let o=0;n?.queue!=null&&(o=n.queue);const r=this._eventListeners[t],l=r.find(c=>c.priority===o);l?l.listeners.push({callback:i,options:n}):(r.push({priority:o,listeners:[{callback:i,options:n}]}),r.sort((c,h)=>c.priority-h.priority))}removeEventListener(t,i,n){if(!this._eventListeners[t]||!i)return;const o=this._eventListeners[t];if(n?.queue!=null){const r=o.find(c=>c.priority===n.queue);if(!r)return;const l=r.listeners.findIndex(c=>c.callback===i);l>=0&&r.listeners.splice(l,1)}else for(const r of o){const l=r.listeners.findIndex(c=>c.callback===i);l>=0&&r.listeners.splice(l,1)}}dispatchEvent(t){var i,n,o,r;let l=!1;if(t instanceof dc){const c=this._eventListeners[t.type];if(c)for(const h of c)for(let d=0;d<h.listeners.length;d++){const u=h.listeners[d];if((n=(i=u.options)==null?void 0:i.signal)!=null&&n.aborted){h.listeners.splice(d,1),d--;continue}u.options.once&&(h.listeners.splice(d,1),d--),u.callback(t)}}if(t instanceof wn){const c=this._eventListeners[t.type];if(c)for(const h of c){if(l)break;for(let d=0;d<h.listeners.length;d++){const u=h.listeners[d];if((r=(o=u.options)==null?void 0:o.signal)!=null&&r.aborted){h.listeners.splice(d,1),d--;continue}if(t.immediatePropagationStopped){l=!0,dt&&console.log("immediatePropagationStopped",t.type);break}else t.propagationStopped&&(l=!0,dt&&console.log("propagationStopped",t.type));u.options.once&&(h.listeners.splice(d,1),d--),u.callback(t)}}}}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]}setCursorPointer(){this.setCursor("pointer")}setCursorNormal(){this.unsetCursor("pointer")}setCursor(t){this._setCursorTypes.push(t),this._setCursorTypes.length>10&&this._setCursorTypes.shift(),this.updateCursor()}unsetCursor(t){for(let i=this._setCursorTypes.length-1;i>=0;i--)if(this._setCursorTypes[i]===t){this._setCursorTypes.splice(i,1),this.updateCursor();break}}updateCursor(){var t;((t=this._setCursorTypes)==null?void 0:t.length)==0?this.context.domElement.style.cursor="default":this.context.domElement.style.cursor=this._setCursorTypes[this._setCursorTypes.length-1]}getIsPointerIdInUse(t){for(const i of this._pointerEventsPressed)if(i.pointerId===t&&i.used)return!0;return!1}getPointerPressedCount(){let t=0;for(let i=0;i<this._pointerPressed.length;i++)this._pointerPressed[i]&&t++;return t}getPointerPosition(t){return t>=this._pointerPositions.length?null:this._pointerPositions[t]}getPointerPositionLastFrame(t){return t>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[t]}getPointerPositionDelta(t){return t>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[t]}getPointerPositionRC(t){return t>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[t]}getPointerDown(t){return t>=this._pointerDown.length?!1:this._pointerDown[t]}getPointerUp(t){return t>=this._pointerUp.length?!1:this._pointerUp[t]}getPointerPressed(t){return t>=this._pointerPressed.length?!1:this._pointerPressed[t]}getPointerClicked(t){return t>=this._pointerClick.length?!1:this._pointerClick[t]}getPointerDoubleClicked(t){return t>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[t]}getPointerDownTime(t){return t>=this._pointerDownTime.length?-1:this._pointerDownTime[t]}getPointerUpTime(t){return t>=this._pointerUpTime.length?-1:this._pointerUpTime[t]}getPointerLongPress(t){return t>=this._pointerDownTime.length?!1:this.getPointerPressed(t)&&this.context.time.time-this._pointerDownTime[t]>this._longPressTimeThreshold}getIsMouse(t){return t<0||t>=this._pointerTypes.length?!1:this._pointerTypes[t]==="mouse"}getIsTouch(t){return t<0||t>=this._pointerTypes.length?!1:this._pointerTypes[t]==="touch"}getTouchesPressedCount(){let t=0;for(let i=0;i<this._pointerPressed.length;i++)this._pointerPressed[i]&&this.getIsTouch(i)&&t++;return t}getMouseWheelChanged(t=0){return t>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[t]}getMouseWheelDeltaY(t=0){return t>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[t]}getPointerEvent(t){if(!(t>=this._pointerEvent.length))return this._pointerEvent[t]??void 0}*foreachPointerId(t){for(let i=0;i<this._pointerTypes.length;i++)if(this._pointerIsActive(i)){if(t!==void 0){const n=this._pointerTypes[i];if(Array.isArray(t)){let o=!1;for(const r of t)if(n===r){o=!0;break}if(!o)continue}else if(t!==n)continue}yield i}}*foreachTouchId(){for(let t=0;t<this._pointerTypes.length;t++)this._pointerTypes[t]==="touch"&&this._pointerIsActive[t]&&(yield t)}_pointerIsActive(t){return t<0?!1:this._pointerPressed[t]||this._pointerDown[t]||this._pointerUp[t]}onDownButton(t,i){let n=this._pressedStack.get(t);n||(n=[],this._pressedStack.set(t,n)),n.push(i)}onReleaseButton(t,i){const n=this._pressedStack.get(t);if(!n)return;const o=n.indexOf(i);o>=0&&n.splice(o,1)}getFirstPressedButtonForPointer(t){const i=this._pressedStack.get(t);if(i)return i[0]}getLatestPressedButtonForPointer(t){const i=this._pressedStack.get(t);if(i)return i[i.length-1]}getKeyDown(){for(const t in this.keysPressed){const i=this.keysPressed[t];if(i.startFrame===this.context.time.frameCount)return i.key}return null}getKeyPressed(){for(const t in this.keysPressed){const i=this.keysPressed[t];if(i.pressed)return i.key}return null}isKeyDown(t){var i;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const n=this.getCodeForCommonKeyName(t);if(n!==null){for(const o of n)if(this.isKeyDown(o))return!0;return!1}return((i=this.keysPressed[t])==null?void 0:i.startFrame)===this.context.time.frameCount&&this.keysPressed[t].pressed}isKeyUp(t){var i;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const n=this.getCodeForCommonKeyName(t);if(n!==null){for(const o of n)if(this.isKeyUp(o))return!0;return!1}return((i=this.keysPressed[t])==null?void 0:i.frame)===this.context.time.frameCount&&!this.keysPressed[t].pressed}isKeyPressed(t){var i;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const n=this.getCodeForCommonKeyName(t);if(n!==null){for(const o of n)if(this.isKeyPressed(o))return!0;return!1}return(i=this.keysPressed[t])==null?void 0:i.pressed}getCodeForCommonKeyName(t){if(t.length===1){if(t>="0"&&t<="9")return["Digit"+t];if(t>="a"&&t<="z")return["Key"+t.toUpperCase()];if(t==" ")return["Space"]}switch(t){case"shift":case"Shift":return["ShiftLeft","ShiftRight"];case"control":case"Control":return["ControlLeft","ControlRight"];case"alt":case"Alt":return["AltLeft","AltRight"]}return null}createInputEvent(t){switch(t.type){case"pointerdown":dt&&De("Create Pointer down"),this.onDownButton(t.deviceIndex,t.button),this.onDown(t);break;case"pointermove":dt&&De("Create Pointer move"),this.onMove(t);break;case"pointerup":dt&&De("Create Pointer up"),this.onUp(t),this.onReleaseButton(t.deviceIndex,t.button);break}}convertScreenspaceToRaycastSpace(t){return t.x=(t.x-this.context.domX)/this.context.domWidth*2-1,t.y=-((t.y-this.context.domY)/this.context.domHeight)*2+1,t}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(){var t,i;window.removeEventListener("contextmenu",this.onContextMenu),(t=this._htmlEventSource)==null||t.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),(i=this._htmlEventSource)==null||i.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 t=this.context.post_render_callbacks.indexOf(this.onEndOfFrame);t>=0&&this.context.post_render_callbacks.splice(t,1),this.unbindEvents()}canReceiveInput(t){var i;return t.target===((i=this.context.renderer)==null?void 0:i.domElement)||t.target===this.context.domElement||this.context.isInAR||this.context.isInAR&&t.target===document.body&&X.isMozillaXR()?!0:(dt&&console.warn("CanReceiveInput:False for",t.target),!1)}getPointerId(t,i){return t.pointerType==="mouse"?0+(i??t.button):this.getPointerIndex(t.pointerId)}getButtonName(t){const i=t.button;if(t.pointerType==="mouse")switch(i){case 0:return"left";case 1:return"middle";case 2:return"right"}return"unknown"}getAndUpdateSpatialObjectForScreenPosition(t,i,n){let o=this._pointerSpace[t];o||(o=new I,this._pointerSpace[t]=o),this._pointerSpace[t]=o;const r=this.context.mainCamera;if(r){const l=this.tempNearPlaneVector.set(i,n,-1);this.convertScreenspaceToRaycastSpace(l);const c=this.tempFarPlaneVector.set(l.x,l.y,1);l.unproject(r),c.unproject(r);const h=r.worldUp||G(0,1,0).applyQuaternion(Ce(r));this.tempLookMatrix.lookAt(c,l,h),o.position.set(l.x,l.y,l.z),o.quaternion.setFromRotationMatrix(this.tempLookMatrix)}return o}isInRect(t){if(this.context.isInXR)return!0;const i=this.context.domElement.getBoundingClientRect(),n=t.clientX,o=t.clientY,r=n>=i.x&&n<=i.right&&o>=i.y&&o<=i.bottom;return dt&&!r&&console.log("Not in rect",i,n,o),r}onDown(t){const i=t.pointerId;if(this.getPointerPressed(i)&&console.warn(`Received pointerDown for pointerId that is already pressed: ${i}`,dt?t:""),dt&&console.log(t.pointerType,"DOWN",i),!!this.isInRect(t)){for(this.setPointerState(i,this._pointerPressed,!0),this.setPointerState(i,this._pointerDown,!0),this.setPointerStateT(i,this._pointerEvent,t.source);i>=this._pointerTypes.length;)this._pointerTypes.push(t.pointerType);for(this._pointerTypes[i]=t.pointerType;i>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new x);for(this._pointerPositionDown[i].set(t.clientX,t.clientY,t.clientZ??0);i>=this._pointerPositions.length;)this._pointerPositions.push(new re);this._pointerPositions[i].set(t.clientX,t.clientY),i>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[i]=this.context.time.realtimeSinceStartup,this.updatePointerPosition(t),this._pointerEventsPressed.push(t),this.onDispatchEvent(t)}}onMove(t){const i=t.pointerId,n=this.getPointerPressed(i);n===!1&&!this.isInRect(t)||t.pointerType==="touch"&&!n||(this.updatePointerPosition(t),this.setPointerStateT(i,this._pointerEvent,t.source),this.onDispatchEvent(t))}onUp(t){const i=t.pointerId;if(!this.getPointerPressed(i)){dt&&console.log(t.pointerType,"UP",i,"was not down");return}dt&&console.log(t.pointerType,"UP",i),this.setPointerState(i,this._pointerPressed,!1),this.setPointerStateT(i,this._pointerEvent,t.source),this.setPointerState(i,this._pointerUp,!0),this.updatePointerPosition(t);for(let c=this._pointerEventsPressed.length-1;c>=0;c--)if(this._pointerEventsPressed[c].pointerId===i){this._pointerEventsPressed.splice(c,1);break}if(!this._pointerPositionDown[i]){dt&&we("Received pointer up event without matching down event for button: "+i),console.warn("Received pointer up event without matching down event for button: "+i);return}const n=this._pointerUpTime[i],o=this._pointerDownTime[i],r=this.context.time.realtimeSinceStartup,l=r-o;if(i>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),this._pointerUpTime[i]=r,l<1){let c=t.clientX-this._pointerPositionDown[i].x,h=t.clientY-this._pointerPositionDown[i].y,d=0;if(t.isSpatial&&t.clientZ!=null&&(d=t.clientZ-this._pointerPositionDown[i].z,c*=200,h*=200,d*=200),Math.abs(c)<5&&Math.abs(h)<5&&Math.abs(d)<5){this.setPointerState(i,this._pointerClick,!0),t.isClick=!0;const u=r-n;dt&&console.log("CLICK",i,c,h,d,u),u<this._doubleClickTimeThreshold&&u>0&&(this.setPointerState(i,this._pointerDoubleClick,!0),t.isDoubleClick=!0)}}this.onDispatchEvent(t)}updatePointerPosition(t){const i=t.pointerId;for(;i>=this._pointerPositions.length;)this._pointerPositions.push(new re);for(;i>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new re);for(;i>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new re);const n=this._pointerPositionsLastFrame[i];n.copy(this._pointerPositions[i]);const o=this._pointerPositionsDelta[i];let r=t.clientX-n.x,l=t.clientY-n.y;if(t.source instanceof MouseEvent||t.source instanceof TouchEvent){const u=t.source;r===0&&u.movementX!==0&&(r=u.movementX||0),l===0&&u.movementY!==0&&(l=u.movementY||0)}o.x+=r,o.y+=l,this._pointerPositions[i].x=t.clientX,this._pointerPositions[i].y=t.clientY;const c=t.clientX,h=t.clientY;for(;i>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new re);const d=this._pointerPositionsRC[i];d.set(c,h),this.convertScreenspaceToRaycastSpace(d)}getPointerIndex(t){let i=-1;for(let n=0;n<this._pointerIds.length;n++){if(this._pointerIds[n]===t)return n;i===-1&&this._pointerIds[n]===-1&&(i=n)}return i!==-1?(this._pointerIds[i]=t,i):(dt&&console.log("PUSH pointerId:",t),this._pointerIds.push(t),this._pointerIds.length-1)}setPointerState(t,i,n){i[t]=n}setPointerStateT(t,i,n){return i[t]=n,n}onDispatchEvent(t){const i=ee.Current;try{ee.Current=this.context,this.dispatchEvent(t)}finally{ee.Current=i}}}const Ca=new ne().makeRotationY(Math.PI),Gi=new V().setFromAxisAngle(new x(0,1,0),Math.PI),zP=C("debugwebxr");class UP{constructor(){if(a(this,"priority",-1e5),a(this,"gameObject"),this.gameObject=new I,this.gameObject.name="Implicit XR Rig",zP){const t=gg(16733661);t.position.y+=.5,this.gameObject.add(t)}}isXRRig(){return!0}get isActive(){return this.gameObject.visible}}const xn=C("debugwebxr"),kd=C("debugcustomgesture"),NP="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",WP="generic-trigger",VP=new V().setFromEuler(new Bt(mn.degToRad(0),mn.degToRad(-90),mn.degToRad(-90))),HP=new x(.04,-.04,0);class eg{constructor(t,i,n){a(this,"xr"),a(this,"inputSource"),a(this,"index",0),a(this,"emitEvents",!0),a(this,"_connected",!0),a(this,"_isTracking",!1),a(this,"__gamepad"),a(this,"__hand"),a(this,"__side"),a(this,"_hitTestSource"),a(this,"_hasSelectEvent",!1),a(this,"_isMxInk",!1),a(this,"_isMetaQuestTouchController",!1),a(this,"_handJointPoses",new Map),a(this,"_gripMatrix",new ne),a(this,"_gripPosition",new x),a(this,"_gripQuaternion",new V),a(this,"_linearVelocity",new x),a(this,"_rayPositionRaw",new x),a(this,"_rayRotationRaw",new V),a(this,"_rayMatrix",new ne),a(this,"_rayPosition",new x),a(this,"_rayQuaternion",new V),a(this,"_gripWorldPosition",new x),a(this,"_gripWorldQuaternion",new V),a(this,"_rayWorldPosition",new x),a(this,"_rayWorldQuaternion",new V),a(this,"_pinchPosition",new x),a(this,"_ray"),a(this,"_hand_wristDotUp"),a(this,"_object"),a(this,"_gripSpaceObject"),a(this,"_raySpaceObject"),a(this,"model",null),a(this,"_debugAxesHelper",new xi(.15)),a(this,"_debugGripAxesHelper",new xi(.07)),a(this,"_debugRayAxesHelper",new xi(.07)),a(this,"_hitTestSourcePromise",null),a(this,"onPointerHits",o=>{}),a(this,"_needleGamepadButtons",{}),a(this,"_buttonMap",new Map),a(this,"_motioncontroller"),a(this,"_layout"),a(this,"getMotionController"),a(this,"emitPointerDownEvent",!0),a(this,"emitPointerUpEvent",!0),a(this,"emitPointerMoveEvent",!0),a(this,"pointerMoveDistanceThreshold",.03),a(this,"pointerMoveAngleThreshold",.05),a(this,"_selectButtonIndex"),a(this,"_squeezeButtonIndex"),a(this,"onSelectStart",o=>{var r,l,c,h;if(!this.emitPointerDownEvent||this.inputSource!==o.inputSource)return;this.onUpdateFrame(o.frame),this._hasSelectEvent=!0;const d=(r=this._layout)==null?void 0:r.selectComponentId,u=(h=(c=(l=this._layout)==null?void 0:l.components[d])==null?void 0:c.gamepadIndices)==null?void 0:h.button;u!==void 0&&(this._selectButtonIndex=u),!kd&&(xn&&q.DrawDirection(this.rayWorldPosition,G(0,.01,1).applyQuaternion(this.rayWorldQuaternion),16711680,10),this.emitPointerEvent(Be.PointerDown,this._selectButtonIndex||0,"xr-standard-trigger",!0,o))}),a(this,"onSelectEnd",o=>{this.emitPointerUpEvent&&(kd||this.inputSource===o.inputSource&&this.emitPointerEvent(Be.PointerUp,this._selectButtonIndex||0,"xr-standard-trigger",!0,o))}),a(this,"onSequeezeStart",o=>{var r,l,c;this.emitPointerDownEvent&&this.inputSource===o.inputSource&&(this._squeezeButtonIndex=(c=(l=(r=this._layout)==null?void 0:r.components["xr-standard-squeeze"])==null?void 0:l.gamepadIndices)==null?void 0:c.button,this._squeezeButtonIndex!==void 0&&(xn&&q.DrawDirection(this.rayWorldPosition,G(0,.01,1).applyQuaternion(this.rayWorldQuaternion),255,10),this.emitPointerEvent(Be.PointerDown,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,o)))}),a(this,"onSequeezeEnd",o=>{this.emitPointerUpEvent&&this.inputSource===o.inputSource&&this._squeezeButtonIndex!==void 0&&this.emitPointerEvent(Be.PointerUp,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,o)}),a(this,"states",{}),a(this,"_didMoveLastFrame",!1),a(this,"_lastPointerMovePosition",new x),a(this,"_lastPointerMoveQuaternion",new V),a(this,"pointerInit"),this.xr=t,this.inputSource=i,this.index=n,this._object=new I,this._object.name=`NeedleXRController_${n}`,xn&&(this._object.add(this._debugAxesHelper),this._gripSpaceObject=new I,this._raySpaceObject=new I,this._gripSpaceObject.name=`NeedleXRController_${n}_gripSpace`,this._raySpaceObject.name=`NeedleXRController_${n}_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 no,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()}get context(){return this.xr.context}get connected(){return this._connected}get isTracking(){return this._isTracking}get gamepad(){return this.__gamepad??(this.__gamepad=this.inputSource.gamepad)}get isHand(){return this.hand!=null}get hand(){return this.__hand??(this.__hand=this.inputSource.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.__side=this.inputSource.handedness)}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)}get hasSelectEvent(){return this._hasSelectEvent}getHitTest(){return this.xr.getHitTest(this)}getHandJointPose(t,i){var n;if(i=i||this.xr.frame,!this.hand||!(i!=null&&i.getJointPose)||!this.xr.referenceSpace)return null;let o=(n=this._handJointPoses)==null?void 0:n.get(t);return o||(o=i.getJointPose(t,this.xr.referenceSpace),o&&this._handJointPoses.set(t,o),o)}get gripPosition(){return G(this._gripPosition)}get gripQuaternion(){return ys(this._gripQuaternion)}get gripMatrix(){return this._gripMatrix}get gripLinearVelocity(){return G(this._linearVelocity).applyQuaternion(Gi)}get rayPosition(){return G(this._rayPosition)}get rayQuaternion(){return ys(this._rayQuaternion)}get gripWorldPosition(){return G(this._gripWorldPosition)}get gripWorldQuaternion(){return ys(this._gripWorldQuaternion)}get rayWorldPosition(){return G(this._rayWorldPosition)}updateRayWorldPosition(){var t;const i=(t=this.xr.context.mainCamera)==null?void 0:t.parent;this._rayWorldPosition.copy(this._rayPositionRaw),i&&this._rayWorldPosition.applyMatrix4(i.matrixWorld)}get rayWorldQuaternion(){return ys(this._rayWorldQuaternion)}get pinchPosition(){return G(this._pinchPosition)}updateRayWorldQuaternion(){var t;const i=(t=this.xr.context.mainCamera)==null?void 0:t.parent,n=i?Ce(i):void 0;this._rayWorldQuaternion.copy(this._rayRotationRaw).multiply(Gi),n&&this._rayWorldQuaternion.premultiply(n)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy(G(0,0,1).applyQuaternion(this.rayWorldQuaternion)),this._ray}get handWristDotUp(){var t;if(this._hand_wristDotUp!==void 0)return this._hand_wristDotUp;const i=(t=this.handObject)==null?void 0:t.joints.wrist;if(i){const n=G(0,1,0).applyQuaternion(i.quaternion),o=G(0,1,0).dot(n);return this._hand_wristDotUp=o}}get isHandUpsideDown(){return this.handWristDotUp!==void 0?this.handWristDotUp<-.7:!1}get isTeleportGesture(){var t;return this.isHandUpsideDown&&((t=this.getGesture("pinch"))==null?void 0:t.isDown)}get object(){return this._object}async getModelUrl(){var t;return(t=this.getMotionController)==null?void 0:t.then(i=>i?.assetUrl||null)}_requestHitTestSource(){var t;return this._hitTestSourcePromise?this._hitTestSourcePromise:this.xr.mode==="immersive-ar"&&this.inputSource.targetRayMode==="tracked-pointer"&&this.xr.session.requestHitTestSourceForTransientInput?this._hitTestSourcePromise=((t=this.xr.session.requestHitTestSourceForTransientInput({profile:this.inputSource.profiles[0],offsetRay:new XRRay}))==null?void 0:t.then(i=>(this._hitTestSourcePromise=null,this.connected?this._hitTestSource=i:(i.cancel(),null))))??null:null}onUpdate(t){performance.mark("NeedleXRController onUpdate start"),this.onUpdateFrame(t),this.updateInputEvents(),this.onUpdateMove(),performance.mark("NeedleXRController onUpdate end"),performance.measure("NeedleXRController onUpdate","NeedleXRController onUpdate start","NeedleXRController onUpdate end")}onRenderDebug(){var t;q.DrawSphere(this.rayWorldPosition,.003),q.DrawDirection(this.rayWorldPosition,G(0,0,10).applyQuaternion(this.rayWorldQuaternion));const i=(this.inputSource.gripSpace?this.gripWorldPosition:this.object.worldPosition).sub(this.object.worldForward.multiplyScalar(.1)),n=this.inputSource.profiles.join(`
135
135
  `);let o=`Controller[${this.index}] (${this.inputSource.targetRayMode}, ${this.side})
136
136
  C:${this.connected?"x":"-"} T:${this.isTracking?"x":"-"} Hand:${this.inputSource.hand?"x":"-"} Pen: ${this._isMxInk?"x":"-"}`;if(this.inputSource.hand&&(o+=`
@@ -138,7 +138,7 @@ Pinch: ${(t=this.getGesture("pinch"))==null?void 0:t.value.toFixed(3)}`),o+=`
138
138
  `+n,o+=`
139
139
  `+(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 r=this.inputSource.gamepad;let l="[btns "+r.buttons.length+"]: "+r.buttons.map(c=>c.value.toPrecision(1)).join(",");l+=`
140
140
  [axes `+r.axes.length+"]: "+r.axes.map(c=>c.toPrecision(1)).join(","),o+=`
141
- `+l}q.DrawLabel(i,o,.006)}onUpdateFrame(t){var i,n,o,r,l,c,h,d,u,p,g;if(this._handJointPoses.clear(),this._hand_wristDotUp=void 0,!this.xr.referenceSpace){this._isTracking=!1;return}const y=t.getPose(this.inputSource.targetRaySpace,this.xr.referenceSpace);this._isTracking=y!=null;let f=null,v=null,b=null,w=null;if(y){const M=y.transform;this._rayMatrix.fromArray(M.matrix).premultiply(Ca),this._rayMatrix.decompose(this._rayPosition,this._rayQuaternion,G(1,1,1)),b=G(M.position),w=ys(M.orientation),this._rayPositionRaw.copy(b),this._rayRotationRaw.copy(w)}if(this.inputSource.gripSpace){const M=t.getPose(this.inputSource.gripSpace,this.xr.referenceSpace);if(M){const T=M.transform;if(f=G(T.position),v=ys(T.orientation),this._gripMatrix.fromArray(T.matrix).premultiply(Ca),this._gripMatrix.decompose(this._gripPosition,this._gripQuaternion,G(1,1,1)),"linearVelocity"in M&&M.linearVelocity){const j=M.linearVelocity;this._linearVelocity.set(j.x,j.y,j.z)}}}(i=this.xr.context.mainCamera)!=null&&i.parent&&(this._object.parent!==((n=this.xr.context.mainCamera)==null?void 0:n.parent)&&this.xr.context.mainCamera.parent.add(this._object),this._gripSpaceObject!==void 0&&((o=this._gripSpaceObject)==null?void 0:o.parent)!==((r=this.xr.context.mainCamera)==null?void 0:r.parent)&&this.xr.context.mainCamera.parent.add(this._gripSpaceObject),this._raySpaceObject!==void 0&&((l=this._raySpaceObject)==null?void 0:l.parent)!==((c=this.xr.context.mainCamera)==null?void 0:c.parent)&&this.xr.context.mainCamera.parent.add(this._raySpaceObject));const _=this.hand;if(_){let M=!1;const T=_.get("wrist"),j=T&&this.getHandJointPose(T,t);if(j){M=!0;const B=j.transform.position,Q=j.transform.orientation;this._object.position.set(B.x,B.y,B.z),this._object.quaternion.set(Q.x,Q.y,Q.z,Q.w).multiply(Gi)}M||(this._object.position.copy(this._rayPosition),this._object.quaternion.copy(this._rayQuaternion).multiply(Gi));const L=_.get("middle-finger-metacarpal"),U=L&&this.getHandJointPose(L,t);U&&(this._gripMatrix.fromArray(U.transform.matrix).premultiply(Ca),this._gripMatrix.decompose(this._gripPosition,this._gripQuaternion,G(1,1,1)),f=G().copy(U.transform.position),v=ys().copy(U.transform.orientation),v.multiply(VP),f.add(G(HP).applyQuaternion(v)))}else this.inputSource.gripSpace&&this.targetRayMode==="transient-pointer"&&f&&v?(this._object.position.copy(f),this._object.quaternion.copy(v).multiply(Gi)):b&&w&&(this._object.position.copy(b),this._object.quaternion.copy(w).multiply(Gi));xn&&(b&&w&&((h=this._raySpaceObject)==null||h.position.copy(b),(d=this._raySpaceObject)==null||d.quaternion.copy(w).multiply(Gi)),f&&v&&((u=this._gripSpaceObject)==null||u.position.copy(f),(p=this._gripSpaceObject)==null||p.quaternion.copy(v).multiply(Gi)));const S=(g=this.xr.context.mainCamera)==null?void 0:g.parent,R=S?Ce(S):void 0;f&&v&&(this._gripWorldPosition.copy(f),S&&this._gripWorldPosition.applyMatrix4(S.matrixWorld),this._gripWorldQuaternion.copy(v),this._gripWorldQuaternion.multiply(Gi),R&&this._gripWorldQuaternion.premultiply(R)),this.updateRayWorldPosition(),this.updateRayWorldQuaternion()}onDisconnected(){var t,i,n,o,r,l;this._connected=!1,xn&&console.warn("Controller disconnected",this.index);for(const c of this._object.children)this.xr.context.scene.attach(c);(t=this._object)==null||t.removeFromParent(),(i=this._debugAxesHelper)==null||i.removeFromParent(),(n=this._debugGripAxesHelper)==null||n.removeFromParent(),(o=this._debugRayAxesHelper)==null||o.removeFromParent(),(r=this._gripSpaceObject)==null||r.removeFromParent(),(l=this._raySpaceObject)==null||l.removeFromParent(),this.unsubscribeEvents(),this._hitTestSource&&(this._hitTestSource.cancel(),this._hitTestSource=void 0)}getButton(t){var i;if(!this._layout)return;switch(t){case"primary-button":if(this.isLeft)t="x-button";else if(this.isRight)t="a-button";else return;break;case"primary":return this.hand?this.getGesture("pinch"):this.toNeedleGamepadButton(0,t)}if(this._buttonMap.has(t))return this.toNeedleGamepadButton(this._buttonMap.get(t),t);const n=(i=this._layout)==null?void 0:i.components[t];if(n!=null&&n.gamepadIndices)switch(n.type){case"button":case"squeeze":if(this.inputSource.gamepad){const o=n.gamepadIndices.button;return this._buttonMap.set(t,o),this.toNeedleGamepadButton(o,t)}break;default:console.warn("Unsupported component type",n.type);break}this._buttonMap.set(t,void 0)}getGesture(t){const i=this.states[t];if(!i)return null;this.states[t]=i;const n=this._needleGamepadButtons[t]||new yb(void 0,t);return n.pressed=i.pressed,n.value=i.value,n.isDown=i.isDown,n.isUp=i.isUp,this._needleGamepadButtons[t]=n,n}getPointerId(t){if((t==="primary"||t==="pinch")&&(t=0),typeof t!="number"){const i=this._buttonMap.get(t);if(i===void 0)return;t=i}return this.index*10+t}toNeedleGamepadButton(t,i){var n,o;if(!((n=this.inputSource.gamepad)!=null&&n.buttons))return;const r=(o=this.inputSource.gamepad)==null?void 0:o.buttons[t],l=this.states[t],c=this._needleGamepadButtons[t]||new yb(t,i);return r&&(c.pressed=r.pressed,c.value=r.value,c.touched=r.touched),l&&(c.isDown=l.isDown,c.isUp=l.isUp),this._needleGamepadButtons[t]=c,c}getStick(t){var i,n,o,r,l,c,h,d,u;if(!this._layout)return{x:0,y:0,z:0};if(t==="primary"){const g=((i=this.inputSource.gamepad)==null?void 0:i.axes[0])||0,y=((n=this.inputSource.gamepad)==null?void 0:n.axes[1])||0,f=((r=(o=this.inputSource.gamepad)==null?void 0:o.buttons[3])==null?void 0:r.value)||0;return{x:g,y,z:f}}const p=(l=this._layout)==null?void 0:l.components[t];if(p!=null&&p.gamepadIndices)switch(p.type){case"thumbstick":if(this.inputSource.gamepad){const g=p.gamepadIndices.xAxis,y=p.gamepadIndices.yAxis;let f=(c=this.inputSource.gamepad)==null?void 0:c.axes[g],v=(h=this.inputSource.gamepad)==null?void 0:h.axes[y];f*=-1,v*=-1;const b=p.gamepadIndices.button,w=(u=(d=this.inputSource.gamepad)==null?void 0:d.buttons[b])==null?void 0:u.value;return{x:f,y:v,z:w}}}return{x:0,y:0,z:0}}initialize(){if(this._hasSelectEvent=this.profiles.includes("generic-hand-select")||this.profiles.some(t=>t.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 t=tO(this.inputSource,NP,WP);this.getMotionController=t.then(i=>{var n;if(!this.connected)return null;this._motioncontroller=new iO(this.inputSource,i.profile,i.assetPath||"");const o=i.profile.layouts[this.inputSource.handedness];if(this._layout=o,this._layout&&!((n=this._layout.gamepad)!=null&&n.length)){this._layout.gamepad=[];for(const r in this._layout.components){const l=this._layout.components[r];this._layout.gamepad[l.gamepadIndices.button]=r}}return this._motioncontroller}).catch(i=>(this.inputSource&&console.warn("Couldn't initialize motion controller profile for ",this.inputSource,i),null))}}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)}updateInputEvents(){var t,i,n;if((t=this.gamepad)!=null&&t.buttons){for(let o=0;o<this.gamepad.buttons.length;o++){const r=this.gamepad.buttons[o],l=this.states[o]||new fb;let c=null;this._isMxInk&&(o===4||o===5)?(r.value>0&&!l.pressed?(c="pointerdown",l.isDown=!0,l.isUp=!1):r.value===0&&l.pressed?(c="pointerup",l.isDown=!1,l.isUp=!0):l.pressed&&(c="pointermove",l.isDown=!1,l.isUp=!1),l.pressed=r.value>0,l.value=r.value):(r.pressed&&!l.pressed?(c="pointerdown",l.isDown=!0,l.isUp=!1):!r.pressed&&l.pressed?(c="pointerup",l.isDown=!1,l.isUp=!0):(l.isDown=!1,l.isUp=!1),l.pressed=r.pressed,l.value=r.value),this.states[o]=l;const h=o!==this._selectButtonIndex&&o!==this._squeezeButtonIndex;if(c!=null&&h){let d=(i=this._layout)==null?void 0:i.gamepad[o];this._isMxInk&&o===4&&(d="stylus-touch"),this._isMxInk&&o===5&&(d="stylus-tip"),(xn||kd)&&console.log("Emitting pointer event",c,o,d,r.value,this.gamepad,this._layout),this.emitPointerEvent(c,o,d??"none",!1,null,r.value)}}if(this._isMetaQuestTouchController){const o=this.gamepad.buttons.length-1,r=this.states[o];if(r&&r.isDown){const l=this.context.menu;l.spatialMenuIsVisible?l.setSpatialMenuVisible(!1):this.context.menu.setSpatialMenuVisible(!0)}}}if(this.hand){const o=this.handObject;if(o){const r=o.joints["index-finger-tip"],l=o.joints["thumb-tip"];if(r&&l){const c=r.position.distanceTo(l.position);this._pinchPosition.lerpVectors(r.position,l.position,.5);const h=(n=this.xr.context.mainCamera)==null?void 0:n.parent;if(h&&this._pinchPosition.applyMatrix4(h.matrixWorld),c!==0){const d=this.states.pinch||new fb,u=(.02+.01)*1.5;d.value=1-(c-.02)/u;const p=c<.02-.01,g=c>.02+.01;p&&!d.pressed?(kd&&console.log("pinch start",c),d.isDown=!0,d.isUp=!1,d.pressed=!0):g&&d.pressed?(d.isDown=!1,d.isUp=!0,d.pressed=!1):(d.isDown=!1,d.isUp=!1),this.states.pinch=d}}}}}onUpdateMove(){var t,i;if(!this.emitPointerMoveEvent)return;let n=!1;if(this._lastPointerMovePosition.distanceTo(this.gripWorldPosition)>this.pointerMoveDistanceThreshold*this.xr.rigScale&&(n=!0),n||this._lastPointerMoveQuaternion.angleTo(this.gripWorldQuaternion)>this.pointerMoveAngleThreshold&&(n=!0),n){this._didMoveLastFrame=!0,this._lastPointerMovePosition.copy(this.gripWorldPosition),this._lastPointerMoveQuaternion.copy(this.gripWorldQuaternion),xn&&q.DrawLabel(this.rayWorldPosition.add(this.object.worldForward.multiplyScalar(.1)),"move",.01);let o=this.xr.context.input.getFirstPressedButtonForPointer(this.index);o===void 0&&(o=0);const r=(i=(t=this.gamepad)==null?void 0:t.buttons[o])==null?void 0:i.value;this.emitPointerEvent("pointermove",o,"none",!1,null,r)}else this._didMoveLastFrame=!1}emitPointerEvent(t,i,n,o,r=null,l){if(!this.emitEvents){xn&&t!==Be.PointerMove&&console.warn("Pointer events are disabled for this controller",this.index,t,i);return}if(this.xr.mode==="immersive-vr"||this.xr.isPassThrough){this.pointerInit.origin=this,this.pointerInit.pointerId=this.getPointerId(i),this.pointerInit.pointerType=this.hand?"hand":"controller",this.pointerInit.button=i,this.pointerInit.buttonName=n,this.pointerInit.isPrimary=o,this.pointerInit.mode=this.inputSource.targetRayMode,this.pointerInit.ray=this.ray,this.pointerInit.device=this.object,this.pointerInit.pressure=l,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 c=ee.Current;ee.Current=this.xr.context,xn&&t!=="pointermove"&&console.warn("Pointer event",t,i,n,{...this.pointerInit}),this.xr.context.input.createInputEvent(new wn(t,r,this.pointerInit)),ee.Current=c}}}class fb{constructor(){a(this,"isDown",!1),a(this,"isUp",!1),a(this,"pressed",!1),a(this,"value",0)}}class yb{constructor(t,i){a(this,"index"),a(this,"name"),a(this,"touched",!1),a(this,"pressed",!1),a(this,"value",0),a(this,"isDown",!1),a(this,"isUp",!1),this.index=t,this.name=i}}const Oa=new Map,Pa=new Map;let vb=0;function Sn(s,t,i){if(Oa.has(t)||Oa.set(t,new Array),Oa.get(t).push({method:s,options:{once:!1,...i}}),vb<30){const n=Pa.get(t);n&&n?.length>100&&(vb+=1,console.warn(`You have ${n.length} methods registered for Event ${t}.
141
+ `+l}q.DrawLabel(i,o,.006)}onUpdateFrame(t){var i,n,o,r,l,c,h,d,u,p,g;if(this._handJointPoses.clear(),this._hand_wristDotUp=void 0,!this.xr.referenceSpace){this._isTracking=!1;return}const y=t.getPose(this.inputSource.targetRaySpace,this.xr.referenceSpace);this._isTracking=y!=null;let f=null,v=null,b=null,w=null;if(y){const M=y.transform;this._rayMatrix.fromArray(M.matrix).premultiply(Ca),this._rayMatrix.decompose(this._rayPosition,this._rayQuaternion,G(1,1,1)),b=G(M.position),w=ys(M.orientation),this._rayPositionRaw.copy(b),this._rayRotationRaw.copy(w)}if(this.inputSource.gripSpace){const M=t.getPose(this.inputSource.gripSpace,this.xr.referenceSpace);if(M){const T=M.transform;if(f=G(T.position),v=ys(T.orientation),this._gripMatrix.fromArray(T.matrix).premultiply(Ca),this._gripMatrix.decompose(this._gripPosition,this._gripQuaternion,G(1,1,1)),"linearVelocity"in M&&M.linearVelocity){const L=M.linearVelocity;this._linearVelocity.set(L.x,L.y,L.z)}}}(i=this.xr.context.mainCamera)!=null&&i.parent&&(this._object.parent!==((n=this.xr.context.mainCamera)==null?void 0:n.parent)&&this.xr.context.mainCamera.parent.add(this._object),this._gripSpaceObject!==void 0&&((o=this._gripSpaceObject)==null?void 0:o.parent)!==((r=this.xr.context.mainCamera)==null?void 0:r.parent)&&this.xr.context.mainCamera.parent.add(this._gripSpaceObject),this._raySpaceObject!==void 0&&((l=this._raySpaceObject)==null?void 0:l.parent)!==((c=this.xr.context.mainCamera)==null?void 0:c.parent)&&this.xr.context.mainCamera.parent.add(this._raySpaceObject));const _=this.hand;if(_){let M=!1;const T=_.get("wrist"),L=T&&this.getHandJointPose(T,t);if(L){M=!0;const B=L.transform.position,Q=L.transform.orientation;this._object.position.set(B.x,B.y,B.z),this._object.quaternion.set(Q.x,Q.y,Q.z,Q.w).multiply(Gi)}M||(this._object.position.copy(this._rayPosition),this._object.quaternion.copy(this._rayQuaternion).multiply(Gi));const D=_.get("middle-finger-metacarpal"),U=D&&this.getHandJointPose(D,t);U&&(this._gripMatrix.fromArray(U.transform.matrix).premultiply(Ca),this._gripMatrix.decompose(this._gripPosition,this._gripQuaternion,G(1,1,1)),f=G().copy(U.transform.position),v=ys().copy(U.transform.orientation),v.multiply(VP),f.add(G(HP).applyQuaternion(v)))}else this.inputSource.gripSpace&&this.targetRayMode==="transient-pointer"&&f&&v?(this._object.position.copy(f),this._object.quaternion.copy(v).multiply(Gi)):b&&w&&(this._object.position.copy(b),this._object.quaternion.copy(w).multiply(Gi));xn&&(b&&w&&((h=this._raySpaceObject)==null||h.position.copy(b),(d=this._raySpaceObject)==null||d.quaternion.copy(w).multiply(Gi)),f&&v&&((u=this._gripSpaceObject)==null||u.position.copy(f),(p=this._gripSpaceObject)==null||p.quaternion.copy(v).multiply(Gi)));const S=(g=this.xr.context.mainCamera)==null?void 0:g.parent,R=S?Ce(S):void 0;f&&v&&(this._gripWorldPosition.copy(f),S&&this._gripWorldPosition.applyMatrix4(S.matrixWorld),this._gripWorldQuaternion.copy(v),this._gripWorldQuaternion.multiply(Gi),R&&this._gripWorldQuaternion.premultiply(R)),this.updateRayWorldPosition(),this.updateRayWorldQuaternion()}onDisconnected(){var t,i,n,o,r,l;this._connected=!1,xn&&console.warn("Controller disconnected",this.index);for(const c of this._object.children)this.xr.context.scene.attach(c);(t=this._object)==null||t.removeFromParent(),(i=this._debugAxesHelper)==null||i.removeFromParent(),(n=this._debugGripAxesHelper)==null||n.removeFromParent(),(o=this._debugRayAxesHelper)==null||o.removeFromParent(),(r=this._gripSpaceObject)==null||r.removeFromParent(),(l=this._raySpaceObject)==null||l.removeFromParent(),this.unsubscribeEvents(),this._hitTestSource&&(this._hitTestSource.cancel(),this._hitTestSource=void 0)}getButton(t){var i;if(!this._layout)return;switch(t){case"primary-button":if(this.isLeft)t="x-button";else if(this.isRight)t="a-button";else return;break;case"primary":return this.hand?this.getGesture("pinch"):this.toNeedleGamepadButton(0,t)}if(this._buttonMap.has(t))return this.toNeedleGamepadButton(this._buttonMap.get(t),t);const n=(i=this._layout)==null?void 0:i.components[t];if(n!=null&&n.gamepadIndices)switch(n.type){case"button":case"squeeze":if(this.inputSource.gamepad){const o=n.gamepadIndices.button;return this._buttonMap.set(t,o),this.toNeedleGamepadButton(o,t)}break;default:console.warn("Unsupported component type",n.type);break}this._buttonMap.set(t,void 0)}getGesture(t){const i=this.states[t];if(!i)return null;this.states[t]=i;const n=this._needleGamepadButtons[t]||new yb(void 0,t);return n.pressed=i.pressed,n.value=i.value,n.isDown=i.isDown,n.isUp=i.isUp,this._needleGamepadButtons[t]=n,n}getPointerId(t){if((t==="primary"||t==="pinch")&&(t=0),typeof t!="number"){const i=this._buttonMap.get(t);if(i===void 0)return;t=i}return this.index*10+t}toNeedleGamepadButton(t,i){var n,o;if(!((n=this.inputSource.gamepad)!=null&&n.buttons))return;const r=(o=this.inputSource.gamepad)==null?void 0:o.buttons[t],l=this.states[t],c=this._needleGamepadButtons[t]||new yb(t,i);return r&&(c.pressed=r.pressed,c.value=r.value,c.touched=r.touched),l&&(c.isDown=l.isDown,c.isUp=l.isUp),this._needleGamepadButtons[t]=c,c}getStick(t){var i,n,o,r,l,c,h,d,u;if(!this._layout)return{x:0,y:0,z:0};if(t==="primary"){const g=((i=this.inputSource.gamepad)==null?void 0:i.axes[0])||0,y=((n=this.inputSource.gamepad)==null?void 0:n.axes[1])||0,f=((r=(o=this.inputSource.gamepad)==null?void 0:o.buttons[3])==null?void 0:r.value)||0;return{x:g,y,z:f}}const p=(l=this._layout)==null?void 0:l.components[t];if(p!=null&&p.gamepadIndices)switch(p.type){case"thumbstick":if(this.inputSource.gamepad){const g=p.gamepadIndices.xAxis,y=p.gamepadIndices.yAxis;let f=(c=this.inputSource.gamepad)==null?void 0:c.axes[g],v=(h=this.inputSource.gamepad)==null?void 0:h.axes[y];f*=-1,v*=-1;const b=p.gamepadIndices.button,w=(u=(d=this.inputSource.gamepad)==null?void 0:d.buttons[b])==null?void 0:u.value;return{x:f,y:v,z:w}}}return{x:0,y:0,z:0}}initialize(){if(this._hasSelectEvent=this.profiles.includes("generic-hand-select")||this.profiles.some(t=>t.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 t=tO(this.inputSource,NP,WP);this.getMotionController=t.then(i=>{var n;if(!this.connected)return null;this._motioncontroller=new iO(this.inputSource,i.profile,i.assetPath||"");const o=i.profile.layouts[this.inputSource.handedness];if(this._layout=o,this._layout&&!((n=this._layout.gamepad)!=null&&n.length)){this._layout.gamepad=[];for(const r in this._layout.components){const l=this._layout.components[r];this._layout.gamepad[l.gamepadIndices.button]=r}}return this._motioncontroller}).catch(i=>(this.inputSource&&console.warn("Couldn't initialize motion controller profile for ",this.inputSource,i),null))}}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)}updateInputEvents(){var t,i,n;if((t=this.gamepad)!=null&&t.buttons){for(let o=0;o<this.gamepad.buttons.length;o++){const r=this.gamepad.buttons[o],l=this.states[o]||new fb;let c=null;this._isMxInk&&(o===4||o===5)?(r.value>0&&!l.pressed?(c="pointerdown",l.isDown=!0,l.isUp=!1):r.value===0&&l.pressed?(c="pointerup",l.isDown=!1,l.isUp=!0):l.pressed&&(c="pointermove",l.isDown=!1,l.isUp=!1),l.pressed=r.value>0,l.value=r.value):(r.pressed&&!l.pressed?(c="pointerdown",l.isDown=!0,l.isUp=!1):!r.pressed&&l.pressed?(c="pointerup",l.isDown=!1,l.isUp=!0):(l.isDown=!1,l.isUp=!1),l.pressed=r.pressed,l.value=r.value),this.states[o]=l;const h=o!==this._selectButtonIndex&&o!==this._squeezeButtonIndex;if(c!=null&&h){let d=(i=this._layout)==null?void 0:i.gamepad[o];this._isMxInk&&o===4&&(d="stylus-touch"),this._isMxInk&&o===5&&(d="stylus-tip"),(xn||kd)&&console.log("Emitting pointer event",c,o,d,r.value,this.gamepad,this._layout),this.emitPointerEvent(c,o,d??"none",!1,null,r.value)}}if(this._isMetaQuestTouchController){const o=this.gamepad.buttons.length-1,r=this.states[o];if(r&&r.isDown){const l=this.context.menu;l.spatialMenuIsVisible?l.setSpatialMenuVisible(!1):this.context.menu.setSpatialMenuVisible(!0)}}}if(this.hand){const o=this.handObject;if(o){const r=o.joints["index-finger-tip"],l=o.joints["thumb-tip"];if(r&&l){const c=r.position.distanceTo(l.position);this._pinchPosition.lerpVectors(r.position,l.position,.5);const h=(n=this.xr.context.mainCamera)==null?void 0:n.parent;if(h&&this._pinchPosition.applyMatrix4(h.matrixWorld),c!==0){const d=this.states.pinch||new fb,u=(.02+.01)*1.5;d.value=1-(c-.02)/u;const p=c<.02-.01,g=c>.02+.01;p&&!d.pressed?(kd&&console.log("pinch start",c),d.isDown=!0,d.isUp=!1,d.pressed=!0):g&&d.pressed?(d.isDown=!1,d.isUp=!0,d.pressed=!1):(d.isDown=!1,d.isUp=!1),this.states.pinch=d}}}}}onUpdateMove(){var t,i;if(!this.emitPointerMoveEvent)return;let n=!1;if(this._lastPointerMovePosition.distanceTo(this.gripWorldPosition)>this.pointerMoveDistanceThreshold*this.xr.rigScale&&(n=!0),n||this._lastPointerMoveQuaternion.angleTo(this.gripWorldQuaternion)>this.pointerMoveAngleThreshold&&(n=!0),n){this._didMoveLastFrame=!0,this._lastPointerMovePosition.copy(this.gripWorldPosition),this._lastPointerMoveQuaternion.copy(this.gripWorldQuaternion),xn&&q.DrawLabel(this.rayWorldPosition.add(this.object.worldForward.multiplyScalar(.1)),"move",.01);let o=this.xr.context.input.getFirstPressedButtonForPointer(this.index);o===void 0&&(o=0);const r=(i=(t=this.gamepad)==null?void 0:t.buttons[o])==null?void 0:i.value;this.emitPointerEvent("pointermove",o,"none",!1,null,r)}else this._didMoveLastFrame=!1}emitPointerEvent(t,i,n,o,r=null,l){if(!this.emitEvents){xn&&t!==Be.PointerMove&&console.warn("Pointer events are disabled for this controller",this.index,t,i);return}if(this.xr.mode==="immersive-vr"||this.xr.isPassThrough){this.pointerInit.origin=this,this.pointerInit.pointerId=this.getPointerId(i),this.pointerInit.pointerType=this.hand?"hand":"controller",this.pointerInit.button=i,this.pointerInit.buttonName=n,this.pointerInit.isPrimary=o,this.pointerInit.mode=this.inputSource.targetRayMode,this.pointerInit.ray=this.ray,this.pointerInit.device=this.object,this.pointerInit.pressure=l,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 c=ee.Current;ee.Current=this.xr.context,xn&&t!=="pointermove"&&console.warn("Pointer event",t,i,n,{...this.pointerInit}),this.xr.context.input.createInputEvent(new wn(t,r,this.pointerInit)),ee.Current=c}}}class fb{constructor(){a(this,"isDown",!1),a(this,"isUp",!1),a(this,"pressed",!1),a(this,"value",0)}}class yb{constructor(t,i){a(this,"index"),a(this,"name"),a(this,"touched",!1),a(this,"pressed",!1),a(this,"value",0),a(this,"isDown",!1),a(this,"isUp",!1),this.index=t,this.name=i}}const Oa=new Map,Pa=new Map;let vb=0;function Sn(s,t,i){if(Oa.has(t)||Oa.set(t,new Array),Oa.get(t).push({method:s,options:{once:!1,...i}}),vb<30){const n=Pa.get(t);n&&n?.length>100&&(vb+=1,console.warn(`You have ${n.length} methods registered for Event ${t}.
142
142
 
143
143
  This might be a performance issue!
144
144
  Consider unregistering the methods when they are not needed anymore!
@@ -151,7 +151,7 @@ See https://engine.needle.tools/docs/scripting.html#special-lifecycle-hooks for
151
151
  `+Pi);const c=await import("./vendor.light.min.js").then(p=>p.j),h=((n=c.default)==null?void 0:n.WebsocketBuilder)??c.WebsocketBuilder,d=((o=c.default)==null?void 0:o.ExponentialBackoff)??c.ExponentialBackoff,u=new h(Pi).withMaxRetries(10).withBackoff(new d(2e3,4)).onOpen(()=>{this._connectingToWebsocketPromise=null,this._ws=u,this.connected=!0,F()||li?console.log(`\u229E Connected to networking backend
152
152
  `+Pi):console.debug("\u229E Connected to networking backend",Pi),l(!0),this.onSendQueued(_s.OnConnection)}).onClose(p=>{this._connectingToWebsocketPromise=null,this.connected=!1,this._isInRoom=!1,l(!1);let g="Websocket connection closed...";Pi!=null&&Pi.includes("/socket")||(g+=' Do you perhaps mean to connect to "/socket"?'),console.error(g)}).onError(p=>{console.error("\u22A0 Websocket connection failed..."),l(!1)}).onRetry(()=>{console.log("\u2192 Retry connecting to networking websocket")}).build();u.addEventListener(c.WebsocketEvent.message,(p,g)=>{this.onMessage(p,g)})})}onMessage(t,i){const n=i.data;try{if(typeof n!="string"){n.size&&this.handleIncomingBinaryMessage(n);return}const o=JSON.parse(n);if(Array.isArray(o))for(const r of o)this.handleIncomingStringMessage(r);else this.handleIncomingStringMessage(o);return}catch(o){li&&n==="pong"?console.log("<<",n):F()&&console.error("Failed to parse message",o)}}async handleIncomingBinaryMessage(t){og&&console.log("<< bin",this.context.time.frame);const i=await t.arrayBuffer();var n=new Uint8Array(i);const o=new sO(n),r=o.getBufferIdentifier(),l=this._listenersBinary[r],c=xb(o),h=Sb(c);if(h&&typeof h=="string"&&(this._state[h]=c),!l)return;const d=c??o;for(const u of l)u(d)}handleIncomingStringMessage(t){var i,n;if(li&&console.log("<<",t.key??t),t.key)switch(t.key){case"connection-start-info":if(t.data){const c=t.data;c&&(console.assert(c.id!==void 0&&c.id!==null&&c.id.length>0,"server did not send connection id",c.id),console.debug("Your id is: "+c.id,this.context.alias??""),this._connectionId=c.id)}else console.warn("Expected connection id in "+t.key);break;case"joined-room":if(li&&console.log(t),t){this._isInRoom=!0;const c=t;this._currentRoomName=c.room,this._currentRoomViewId=c.viewId,this._currentRoomAllowEditing=c.allowEditing??!0,this._currentInRoom.length=0,this._currentInRoom.push(...c.inRoom),(og||F())&&console.debug("Joined Needle Engine Room: "+c.room);const h=new URL(window.location.href);h.searchParams.has("room")&&h.searchParams.delete("room"),h.searchParams.set("view",this._currentRoomViewId),console.debug(`Room view id: ${this._currentRoomViewId}
153
153
  ${h.href}`)}this.onSendQueued(_s.OnRoomJoin);break;case"left-room":t.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentInRoom.length=0);break;case"user-joined-room":if(t.data){const c=t.data;this._currentInRoom.push(c.userId),li&&console.log(c.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(t.data){const c=t.data,h=this._currentInRoom.indexOf(c.userId);h>=0&&(li&&console.log(c.userId+" left","now in room:",this._currentInRoom),this._currentInRoom.splice(h,1)),c.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":li&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const l=(i=t.data)==null?void 0:i.time;l&&(this._currentDelay=this.context.time.time-l),li&&console.log("Current latency: "+this._currentDelay.toFixed(4)+" sec","Clients in room: "+((n=this._currentInRoom)==null?void 0:n.length));break}const o=t.data;o&&(this._state[o.guid]=o);let r=this._listeners[t.key];if(r){r=[...r];for(const l of r)try{l(t.data)}catch(c){console.error('Error invoking callback for "'+t.key+'"',c)}}}toMessage(t,i){return{key:t,data:i}}sendWithWebsocket(t,i,n=_s.OnRoomJoin){if(!this._ws){const r=this._waitingForSocket[n]||[];r.push(()=>this.sendWithWebsocket(t,i,n)),this._waitingForSocket[n]=r;return}const o=JSON.stringify(this.toMessage(t,i));li&&console.log(">>",t),this._ws.send(o)}onSendQueued(t){const i=this._waitingForSocket[t];if(i){for(const n of i)n();i.length=0}}}const pc=C("debugwebxr");class ag{constructor(t,i){a(this,"controllerStates",[]),a(this,"userId"),a(this,"context"),a(this,"userStateEvtName"),a(this,"onReceivedControllerState",n=>{pc&&console.log(`XRSync: Received change for ${this.userId}: ${n.type} ${n.handedness}; tracked=${n.isTracking}`);let o=!1;for(let r=0;r<this.controllerStates.length;r++)if(this.controllerStates[r].index===n.index){this.controllerStates[r]=n,o=!0;break}o||this.controllerStates.push(n)}),this.userId=t,this.context=i,this.userStateEvtName="xr-sync-user-state-"+t,this.context.connection.beginListen(this.userStateEvtName,this.onReceivedControllerState)}dispose(){this.context.connection.stopListen(this.userStateEvtName,this.onReceivedControllerState)}update(t){if(this.context.connection.isConnected!=!1){for(let i=this.controllerStates.length-1;i>=0;i--){const n=this.controllerStates[i];let o=!1;for(let r=0;r<t.controllers.length;r++)t.controllers[r].index===n.index&&(o=!0);o||(pc&&console.log(`XRSync: ${n.type} ${n.handedness} removed`,n.index),this.controllerStates.splice(i,1),this.sendControllerRemoved(n))}for(const i of t.controllers)this.updateControllerStates(i)}}onExitXR(t){for(const i of this.controllerStates)this.sendControllerRemoved(i);this.controllerStates.length=0}sendControllerRemoved(t){t.isTracking=!1,t.guid="",this.context.connection.send(this.userStateEvtName,t),this.context.connection.sendDeleteRemoteState(t.guid)}updateControllerStates(t){const i=this.controllerStates.find(n=>n.index===t.index);if(i){let n=!1;n||(n=i.isTracking!=t.isTracking),n&&(i.isTracking=t.isTracking,this.context.connection.send(this.userStateEvtName,i))}else{const n={guid:this.userId+"-"+t.index,isTracking:t.isTracking,handedness:t.side,index:t.index,type:t.hand?"hand":"controller"};this.controllerStates.push(n),this.context.connection.send(this.userStateEvtName,n),pc&&console.log(`XRSync: ${n.type} ${n.handedness} added`,n.index)}}}class Eb{constructor(t){a(this,"context"),a(this,"onJoinedRoom",()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(pc&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new ag(this.context.connection.connectionId,this.context)));for(const i of this.context.connection.usersInRoom())this._states.has(i)||this._states.set(i,new ag(i,this.context))}}),a(this,"onLeftRoom",()=>{if(this.context.connection.connectionId&&!this._states.has(this.context.connection.connectionId)){const i=this._states.get(this.context.connection.connectionId);i?.dispose(),this._states.delete(this.context.connection.connectionId)}}),a(this,"onOtherUserJoinedRoom",i=>{const n=i.userId;this._states.has(n)||(pc&&console.log("XRSync: Remote user joined room",n),this._states.set(n,new ag(n,this.context)))}),a(this,"onOtherUserLeftRoom",i=>{const n=i.userId;if(!this._states.has(n)){const o=this._states.get(n);o?.dispose(),this._states.delete(n)}}),a(this,"_states",new Map),this.context=t,this.context.connection.beginListen(se.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(se.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(se.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(se.UserLeftRoom,this.onOtherUserLeftRoom)}hasState(t){return t?this._states.has(t):!1}isTracking(t,i){if(!t)return;const n=this._states.get(t);if(!n)return;const o=n.controllerStates.find(r=>r.handedness===i);return o?.isTracking||!1}getDeviceType(t,i){if(!t)return;const n=this._states.get(t);if(!n)return;const o=n.controllerStates.find(r=>r.handedness===i);return o?.type||"unknown"}destroy(){this.context.connection.stopListen(se.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(se.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(se.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(se.UserLeftRoom,this.onOtherUserLeftRoom)}onUpdate(t){if(this.context.connection.isConnected&&this.context.connection.connectionId){const i=this._states.get(this.context.connection.connectionId);i?.update(t)}}onExitXR(t){if(this.context.connection.isConnected&&this.context.connection.connectionId){const i=this._states.get(this.context.connection.connectionId);i?.onExitXR(t)}}}class Ab{constructor(){a(this,"_fadeToColorQuad"),a(this,"_fadeToColorMaterial"),a(this,"_requestedFadeValue",0),a(this,"_transitionPromise",null),a(this,"_transitionResolve",null),this._fadeToColorMaterial=new Re({color:0,transparent:!0,depthTest:!1,fog:!1,side:Si}),this._fadeToColorQuad=new Y(new Fs(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(t,i){const n=this._fadeToColorQuad,o=this._fadeToColorMaterial;n.parent!==t&&o.opacity>0?t.add(n):o.opacity===0&&n.removeFromParent(),n.layers.set(2),n.material=this._fadeToColorMaterial,n.position.z=-1,n.renderOrder=1/0;const r=this._requestedFadeValue;o.opacity=W.lerp(o.opacity,r,i/.03),Math.abs(o.opacity-r)<=.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 t=new Promise(i=>{this._transitionResolve=i});return this._transitionPromise=t,t}}var ur=(s=>(s[s.Quad=0]="Quad",s[s.Cube=1]="Cube",s[s.Sphere=2]="Sphere",s[s.RoundedCube=10]="RoundedCube",s))(ur||{}),Rd,lg;class po{static createText(t,i){let n=null;const o=i?.font||JP(i?.familyFamily||null);o instanceof LC?n=pa(this,Rd,lg).call(this,t,o,i):n==null&&(n=new gn);const r=i?.color||16777215,l=new Y(n,i?.material??new ni({color:r}));return this.applyDefaultObjectOptions(l,i),o instanceof Promise?o.then(c=>{l.geometry=pa(this,Rd,lg).call(this,t,c,i),i!=null&&i.onGeometry&&i.onGeometry(l)}):i!=null&&i.onGeometry&&i.onGeometry(l),l}static createOccluder(t){const i=new Re({colorWrite:!1,depthWrite:!0,side:Si});return this.createPrimitive(t,{material:i})}static createPrimitive(t,i){let n;const o=i?.color||16777215;switch(t){case"Quad":case 0:{const r=new Fs(1,1,1,1),l=i?.material??new ni({color:o});i!=null&&i.texture&&"map"in l&&(l.map=i.texture),n=new Y(r,l),n.name="Quad"}break;case"Cube":case 1:{const r=new ql(1,1,1),l=i?.material??new ni({color:o});i!=null&&i.texture&&"map"in l&&(l.map=i.texture),n=new Y(r,l),n.name="Cube"}break;case 10:case"RoundedCube":{const r=KP(1,1,1,.1,2),l=i?.material??new ni({color:o});i!=null&&i.texture&&"map"in l&&(l.map=i.texture),n=new Y(r,l),n.name="RoundedCube"}break;case"Sphere":case 2:{const r=new nd(.5,16,16),l=i?.material??new ni({color:o});i!=null&&i.texture&&"map"in l&&(l.map=i.texture),n=new Y(r,l),n.name="Sphere"}break;case"ShaderBall":n=new oo,n.name="ShaderBall",e2(n,i);break}return this.applyDefaultObjectOptions(n,i),n}static createSprite(t){const i=new fS({color:16777215});t!=null&&t.texture&&"map"in i&&(i.map=t.texture);const n=new yS(i);return this.applyDefaultObjectOptions(n,t),n}static applyDefaultObjectOptions(t,i){t.receiveShadow=!0,t.castShadow=!0,i!=null&&i.name&&(t.name=i.name),i!=null&&i.position&&(Array.isArray(i.position)?t.position.set(i.position[0],i.position[1],i.position[2]):t.position.set(i.position.x,i.position.y,i.position.z)),i!=null&&i.rotation&&(Array.isArray(i.rotation)?t.rotation.set(i.rotation[0],i.rotation[1],i.rotation[2]):t.rotation.set(i.rotation.x,i.rotation.y,i.rotation.z)),i!=null&&i.scale&&(typeof i.scale=="number"?t.scale.set(i.scale,i.scale,i.scale):Array.isArray(i.scale)?t.scale.set(i.scale[0],i.scale[1],i.scale[2]):t.scale.set(i.scale.x,i.scale.y,i.scale.z)),i?.receiveShadow!=null&&(t.receiveShadow=i.receiveShadow),i?.castShadow!=null&&(t.castShadow=i.castShadow),i!=null&&i.parent&&i.parent.add(t)}}Rd=new WeakSet,lg=function(s,t,i){const n=i?.depth||.1;return new DC(s,{font:t,size:1,depth:n,height:n,bevelEnabled:i?.bevel||!1,bevelThickness:.01,bevelOffset:.01,bevelSize:.01})},Wi(po,Rd);function KP(s,t,i,n,o){const r=new vS,l=1e-5,c=n-l;r.absarc(l,l,l,-Math.PI/2,-Math.PI,!0),r.absarc(l,t-c*2,l,Math.PI,Math.PI/2,!0),r.absarc(s-c*2,t-c*2,l,Math.PI/2,0,!0),r.absarc(s-c*2,l,l,0,-Math.PI/2,!0);const h=new bS(r,{bevelEnabled:!0,bevelSegments:o*2,steps:1,bevelSize:c,bevelThickness:n,curveSegments:o});return h.scale(1,1,1-n),h.center(),h.computeVertexNormals(),h}const Td=new Map;function JP(s){let t="";switch(s){default:case"OpenSans":t="https://cdn.needle.tools/static/fonts/facetype/Open Sans_Regular_ascii.json";break;case"Helvetiker":t="https://raw.githubusercontent.com/mrdoob/three.js/master/examples/fonts/helvetiker_regular.typeface.json";break}if(Td.has(t)){const o=Td.get(t);if(o)return o}const i=new BC,n=new Promise((o,r)=>{i.load(t,l=>{Td.set(t,l),o(l)},void 0,r)});return Td.set(t,n),n}let cg=!1,hg=null;function e2(s,t){if(hg===null){const i="https://cdn.needle.tools/static/models/shaderball.glb",n=new rr,o=gm(null);n.setDRACOLoader(o.dracoLoader),n.setKTX2Loader(o.ktx2Loader),cg=!0,hg=n.loadAsync(i).then(r=>{const l=r.scene;return l.position.y-=.5,l}).catch(r=>(console.warn("Failed to load shaderball mesh: "+r.message),jb())).finally(()=>{cg=!1})}if(cg){const i=jb();i.name="ShaderBall-Placeholder";const n=i.children[0];n?.type==="Mesh"&&Ib(n,t),s.add(i)}hg.then(i=>{s.children.forEach(r=>{r.name==="ShaderBall-Placeholder"&&s.remove(r)});const n=i.clone(),o=n.children[0];o?.type==="Mesh"&&Ib(o,t),s.add(n)})}function Ib(s,t){var i;if(t?.color||t?.material||t?.texture){const n=t?.material??((i=s.material)==null?void 0:i.clone())??new ni;t.color&&"color"in n&&n.color instanceof ae&&n.color.set(t.color),t!=null&&t.texture&&"map"in n&&(n.map=t.texture),s.material=n}}function jb(){return new oo().add(po.createPrimitive("Sphere",{material:new Re({transparent:!0,opacity:.1})}))}const Lb=class{constructor(s,t,i){a(this,"_session"),a(this,"_mode"),a(this,"_init"),a(this,"_renderer"),a(this,"_camera"),a(this,"_scene"),a(this,"onEnd",()=>{var n;(n=this._session)==null||n.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()}),a(this,"_lastTime",0),a(this,"onFrame",(n,o)=>{const r=n-this._lastTime;this.update(n,r),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera)}),a(this,"_objects",[]),this._mode=s,this._init=t,this._session=i,this._session.addEventListener("end",this.onEnd),this._renderer=new sr({alpha:!0}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(i),this._renderer.xr.enabled=!0,this._camera=new _e,this._scene=new Vi,this._scene.fog=new Vy(4473924,10,250),this._scene.add(this._camera),this.setupScene()}static get active(){return this._active}static async start(s,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(s,t);return i.addEventListener("end",()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new Lb(s,t,i),this._active):(i.end(),null)}return null}static async handoff(){return this._active?this._active.handoff():null}static async stop(){this._requestInFlight=!1,this._active&&(await this._active.end(),await fs(100)),this._active=null}get isAR(){return this._mode==="immersive-ar"}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 s={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,s}async onBeforeHandoff(){await fs(1e3),this._scene.clear()}setupScene(){this._scene.background=new ae(0),this._scene.add(new sm(5,10,1118481,1118481));const s=new nm(16777215,1);s.position.set(0,20,0),s.castShadow=!1,this._scene.add(s);const t=new nm(16777215,1);t.position.set(0,-1,0),t.castShadow=!1,this._scene.add(t);const i=new Hy(16777215,1,100,1);i.position.set(0,2,0),i.castShadow=!1,i.distance=200,this._scene.add(i);const n=50;for(let o=0;o<100;o++){const r=new ni({color:2236962,metalness:1,roughness:.8});this.isAR&&(r.emissive=new ae(Math.random(),Math.random(),Math.random()),r.emissiveIntensity=Math.random());const l=W.random(0,1)>.5?ur.Sphere:ur.Cube,c=po.createPrimitive(l,{material:r});c.position.x=W.random(-n,n),c.position.y=W.random(-2,n),c.position.z=W.random(-n,n),c.rotation.x=W.random(0,Math.PI*2),c.rotation.y=W.random(0,Math.PI*2),c.rotation.z=W.random(0,Math.PI*2),c.scale.multiplyScalar(.5+Math.random()*10);const h=c.position.distanceTo(this._camera.position)-c.scale.x;h<1&&c.position.multiplyScalar(1+1/h),this._objects.push(c),this._scene.add(c)}}update(s,t){const i=s*4e-4;for(let n=0;n<this._objects.length;n++){const o=this._objects[n];o.position.y+=Math.sin(i+n*.5)*.005,o.rotateY(.002)}}};let ka=Lb;a(ka,"_active",null),a(ka,"_requestInFlight",!1);var mc;(s=>{const t=[];function i(){if(!(t!=null&&t.length))return!1;for(const r of t)r.exportAndOpen();return!0}s.exportAndOpen=i;function n(r){t.push(r)}s.registerExporter=n;function o(r){if(!t)return;const l=t.indexOf(r);l>=0&&t.splice(l,1)}s.unregisterExporter=o})(mc||(mc={}));const Db="NeedleXRSession onStart",Bb="NeedleXRSession onEnd",yt=C("debugwebxr"),Fb=C("stats");let dg=0;function t2(s){let t=null;const i=s;return i.getAROverlayContainer?t=i.getAROverlayContainer():t=s,t}i2();async function i2(){var s;if(C("debugasap")){let t=globalThis["needle:XRSession"];if(t instanceof Promise){delete globalThis["needle:XRSession"],ue.addContextCreatedCallback(async i=>{if(!t)return;hr(!0);const n=await t;if(n){const o=J.getDefaultSessionInit("immersive-vr");J.setSession("immersive-vr",n,o,i.context)}else console.error("NeedleXRSession: ASAP session was rejected");t=void 0});return}}if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent)){console.warn("WebXRViewer does not support addEventListener");return}(s=navigator.xr)==null||s.addEventListener("sessiongranted",async()=>{hr(!0),console.log("Received Session Granted..."),await fs(100);const t=sessionStorage.getItem("needle_xr_session_mode"),i=sessionStorage.getItem("needle_xr_session_init")??null,n=i?JSON.parse(i):null;let o=null;if(zb()&&(await ka.start(t||"immersive-vr",n||J.getDefaultSessionInit("immersive-vr")),await o2(),o=await ka.handoff()),o)J.setSession(o.mode,o.session,o.init,ee.Current);else if(t&&i){console.log("Session Granted: Restore last session");const r=JSON.parse(i);J.start(t,r).catch(l=>console.warn(l))}else J.start("immersive-vr").catch(r=>console.warn("Session Granted failed:",r))},{once:!0})}}function s2(s,t){sessionStorage.setItem("needle_xr_session_mode",s),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(t))}function n2(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const ug=new Set;ue.registerCallback(ge.ContextCreationStart,async s=>{ug.add(s.context)}),ue.registerCallback(ge.ContextCreated,async s=>{ug.delete(s.context)});function zb(){return ug.size>0}function o2(){return new Promise(s=>{const t=Date.now(),i=setInterval(()=>{(!zb()||Date.now()-t>6e4)&&(clearInterval(i),s())},100)})}X.isDesktop()&&F()&&window.addEventListener("keydown",s=>{(s.key==="x"||s.key==="Escape")&&J.active&&J.stop()});const mo=class{constructor(s,t,i,n){a(this,"context"),a(this,"session"),a(this,"mode"),a(this,"controllers",[]),a(this,"_rigScale",1),a(this,"_lastRigScaleUpdate",-1),a(this,"_rigs",[]),a(this,"_viewerHitTestSource",null),a(this,"_defaultRig"),a(this,"_xr_scripts"),a(this,"_xr_update_scripts",[]),a(this,"_inactive_scripts",[]),a(this,"_controllerAdded"),a(this,"_controllerRemoved"),a(this,"_originalCameraWorldPosition"),a(this,"_originalCameraWorldRotation"),a(this,"_originalCameraWorldScale"),a(this,"_originalCameraParent"),a(this,"_mainCamera",null),a(this,"onRendererSessionSet",()=>{var l;this.running&&(this.context.renderer.xr.enabled=!0,this.context.renderer.xr.updateCamera(this.context.mainCamera),(l=this.context.mainCameraComponent)==null||l.applyClearFlags())}),a(this,"onInputSourceAdded",l=>{if(l.targetRayMode==="screen")return;let c=0;for(let d=0;d<this.session.inputSources.length;d++)if(this.session.inputSources[d]===l){c=d;break}if(this.controllers.find(d=>d.inputSource===l)){console.debug("Controller already exists for input source",c);return}else if(this._newControllers.find(d=>d.inputSource===l)){console.debug("Controller already registered for input source",c);return}const h=new eg(this,l,c);this._newControllers.push(h)}),a(this,"_ended",!1),a(this,"_newControllers",[]),a(this,"onEnd",l=>{var c,h,d;if(this._ended)return;this._ended=!0,console.debug("XR Session ended"),n2(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,uo(this.onBefore,Me.LateUpdate);const u=this.context.pre_render_callbacks.indexOf(this.onBeforeRender);u>=0&&this.context.pre_render_callbacks.splice(u,1);const p=this.context.post_render_callbacks.indexOf(this.onAfterRender);p>=0&&this.context.post_render_callbacks.splice(p,1),this.context.xr=null,this.context.renderer.xr.enabled=!1,this.context.pre_update_oneshot_callbacks.push(()=>{var y,f;(y=this.context.mainCameraComponent)==null||y.applyClearFlags(),(f=this.context.mainCameraComponent)==null||f.applyClippingPlane()}),mb({session:this});for(const y of mo._xrEndListeners)y({xr:this});const g=[...this.controllers];for(let y=0;y<g.length;y++)this.disconnectInputSource(g[y].inputSource);this._newControllers.length=0,this.controllers.length=0;for(const y of this._xr_scripts)(c=y?.onLeaveXR)==null||c.call(y,{xr:this});(h=this.sync)==null||h.onExitXR(this),this.context.mainCamera&&((d=this._originalCameraParent)==null||d.add(this.context.mainCamera),this._originalCameraWorldPosition&&ht(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&Hi(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&wa(this.context.mainCamera,this._originalCameraWorldScale)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),hr(!1),performance.mark(Bb),performance.measure("NeedleXRSession",Db,Bb)}),a(this,"_didStart",!1),a(this,"onBefore",l=>{var c,h,d,u,p,g,y,f;const v=l.xrFrame;if(!v)return;performance.mark("NeedleXRSession onBefore start"),this.context.xr=this,this.context.mainCameraComponent&&this.context.mainCameraComponent!==this._mainCamera&&(this._mainCamera=this.context.mainCameraComponent),((c=this.rig)==null?void 0:c.isActive)==!1&&(yt&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig&&(h=this._mainCamera)!=null&&h.gameObject&&((u=(d=this._mainCamera)==null?void 0:d.gameObject)==null?void 0:u.parent)!==this.rig.gameObject&&this.rig.gameObject.add((p=this._mainCamera)==null?void 0:p.gameObject),this.internalUpdateState(),this.applyCustomForward();const b={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const w=[...this.context.new_scripts_xr];for(let _=0;_<w.length;_++){const S=this.context.new_scripts_xr[_];if(!S||S.destroyed||((g=S.supportsXR)==null?void 0:g.call(S,this.mode))==!1){this.context.new_scripts_xr.splice(_,1);continue}if(!S.activeAndEnabled){this.context.new_scripts_xr.splice(_,1),this.markInactive(S);continue}if(this.addScript(S)){this.invokeCallback_EnterXR(S);for(const R of this.controllers)this.invokeCallback_ControllerAdded(S,R)}}}}else{if(this._didStart=!0,this.mode==="immersive-vr"){const _=oi(this.context.scene.children);if(_){const S=_.getSize(G());if(S.length()>0){const R=this._defaultRig.gameObject;R.position.set(_.min.x+S.x*.5,_.min.y,_.max.z+S.z*.5+1.5);const M=_.getCenter(G());M.y=R.position.y,R.lookAt(M)}}}pb({session:this});for(const _ of mo._xrStartListeners)_(b);const w=[...this._xr_scripts];yt&&console.log("NeedleXRSession start, handle scripts:",w);for(const _ of w){if(_.destroyed){this._script_to_remove.push(_);continue}if(!_.activeAndEnabled){this.markInactive(_);continue}this.invokeCallback_EnterXR(_);for(const S of this.controllers)this.invokeCallback_ControllerAdded(_,S)}}this.syncCameraCullingMask();for(const w of this.controllers)w.onUpdate(v);if(this._newControllers.length>0){const w=[...this._newControllers];this._newControllers.length=0;for(const _ of w){if(!_.connected){console.warn("New controller is not connected",_);continue}this.controllers.push(_);for(const S of this._xr_scripts){if(S.destroyed){this._script_to_remove.push(S);continue}S.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(S,_)}}this.controllers.sort((_,S)=>_.index-S.index)}yt&&this.context.time.frame%30===0&&this.controllers.length<=0&&this.session.inputSources.length>0&&(hr(!0),console.error("XRControllers are not added but inputSources are present")),performance.mark("NeedleXRSession update scripts start");for(const w of this._xr_update_scripts){if(w.destroyed===!0){this._script_to_remove.push(w);continue}if(w.activeAndEnabled===!1){this.markInactive(w);continue}w.onUpdateXR&&w.onUpdateXR(b)}if(performance.mark("NeedleXRSession update scripts end"),performance.measure("NeedleXRSession update scripts","NeedleXRSession update scripts start","NeedleXRSession update scripts end"),this.handleInactiveScripts(),this._script_to_remove.length>0){const w=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const _ of w)!_.destroyed&&this.running&&((y=_.onLeaveXR)==null||y.call(_,b)),this.removeScript(_)}(f=this.sync)==null||f.onUpdate(this),this.onRenderDebug(),performance.mark("NeedleXRSession onBefore end"),performance.measure("NE XR frame","NeedleXRSession onBefore start","NeedleXRSession onBefore end")}),a(this,"onBeforeRender",()=>{this.context.mainCamera&&this.updateFade(this.context.mainCamera)}),a(this,"onAfterRender",()=>{if(this.onUpdateFade_PostRender(),X.isDesktop()||!this._renderOnceOnDevice){const l=this.context.renderer;if(l.xr.isPresenting&&this.context.mainCamera){this._renderOnceOnDevice=!0;const c=l.xr.enabled,h=l.getRenderTarget(),d=this.context.scene.background;l.xr.enabled=!1,l.setRenderTarget(null),this.isPassThrough&&(this.context.scene.background=null),this.context.composer?this.context.composer.render(this.context.time.deltaTime):l.render(this.context.scene,this.context.mainCamera),l.xr.enabled=c,l.setRenderTarget(h),this.context.scene.background=d}}}),a(this,"_script_to_remove",[]),a(this,"_camera"),a(this,"_cameraRenderParent",new I().rotateY(Math.PI)),a(this,"_previousCameraParent"),a(this,"_customforward",!0),a(this,"originalCameraNearPlane"),a(this,"_viewerPose"),a(this,"_transformOrientation",new V),a(this,"_transformPosition",new x),a(this,"_transition");var o,r;performance.mark(Db),s2(s,n.init),this.session=t,this.mode=s,this.context=i,(yt||C("console"))&&hr(!0),this._xr_scripts=[...n.scripts],this._xr_update_scripts=this._xr_scripts.filter(l=>typeof l.onUpdateXR=="function"),this._controllerAdded=n.controller_added,this._controllerRemoved=n.controller_removed,Sn(this.onBefore,Me.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),((o=n.init.optionalFeatures)!=null&&o.includes("hit-test")||(r=n.init.requiredFeatures)!=null&&r.includes("hit-test"))&&t.requestReferenceSpace("viewer").then(l=>{var c,h;return(h=(c=t.requestHitTestSource)==null?void 0:c.call(t,{space:l}))==null?void 0:h.then(d=>this._viewerHitTestSource=d).catch(d=>console.error(d))}).catch(l=>console.error(l)),this.context.mainCamera&&(this._originalCameraWorldPosition=te(this.context.mainCamera,new x),this._originalCameraWorldRotation=Ce(this.context.mainCamera,new V),this._originalCameraWorldScale=Ye(this.context.mainCamera,new x),this._originalCameraParent=this.context.mainCamera.parent),this._defaultRig=new UP,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let l=0;l<t.inputSources.length;l++){const c=t.inputSources[l];if(!c.handedness){console.warn("Input source in xr session has no handedness - ignoring",l);continue}this.onInputSourceAdded(c)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",l=>{for(const c of l.removed)this.disconnectInputSource(c);for(const c of l.added)this.onInputSourceAdded(c)}),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):yt&&console.warn("controllerAutoUpdate is not available in three.js - cannot disable it")}static getXRSync(s){return this._sync||(this._sync=new Eb(s)),this._sync}static get currentSessionRequest(){return this._currentSessionRequestMode}static get active(){return this._activeSession}static get activeMode(){var s;return((s=this._activeSession)==null?void 0:s.mode)??null}static get xrSystem(){return"xr"in navigator?navigator.xr:void 0}static isXRSupported(){return Promise.all([this.isVRSupported(),this.isARSupported()]).then(s=>s.some(t=>t)).catch(()=>!1)}static isVRSupported(){return this.isSessionSupported("immersive-vr")}static isARSupported(){return this.isSessionSupported("immersive-ar")}static isSessionSupported(s){var t;return((t=this.xrSystem)==null?void 0:t.isSessionSupported(s).catch(i=>(yt&&console.error(i),!1)))??Promise.resolve(!1)}static onSessionRequestStart(s){this._sessionRequestStartListeners.push(s)}static offSessionRequestStart(s){const t=this._sessionRequestStartListeners.indexOf(s);t>=0&&this._sessionRequestStartListeners.splice(t,1)}static onSessionRequestEnd(s){this._sessionRequestEndListeners.push(s)}static offSessionRequestEnd(s){const t=this._sessionRequestEndListeners.indexOf(s);t>=0&&this._sessionRequestEndListeners.splice(t,1)}static onXRSessionStart(s){this._xrStartListeners.push(s)}static offXRSessionStart(s){const t=this._xrStartListeners.indexOf(s);t>=0&&this._xrStartListeners.splice(t,1)}static onXRSessionEnd(s){this._xrEndListeners.push(s)}static offXRSessionEnd(s){const t=this._xrEndListeners.indexOf(s);t>=0&&this._xrEndListeners.splice(t,1)}static onControllerAdded(s){this._controllerAddedListeners.push(s)}static offControllerAdded(s){const t=this._controllerAddedListeners.indexOf(s);t>=0&&this._controllerAddedListeners.splice(t,1)}static onControllerRemoved(s){this._controllerRemovedListeners.push(s)}static offControllerRemoved(s){const t=this._controllerRemovedListeners.indexOf(s);t>=0&&this._controllerRemovedListeners.splice(t,1)}static offerSession(s,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: "+s),t=="default"&&(t=this.getDefaultSessionInit(s)),navigator.xr.offerSession(s,{...t}).then(n=>mo.setSession(s,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(s){switch(s){case"immersive-ar":const t=["anchors","local-floor","layers","dom-overlay","hit-test","unbounded"];return X.isVisionOS()||t.push("hand-tracking"),{optionalFeatures:t};case"immersive-vr":const i=["local-floor","bounded-floor","high-fixed-foveation-level","layers"];return X.isVisionOS()||i.push("hand-tracking"),{optionalFeatures:i};default:return console.warn("No default session init for mode",s),{}}}static async start(s,t,i){var n,o,r,l;if(X.isiOS()){if(s==="ar")if(await this.isARSupported())s="immersive-ar";else return mc.exportAndOpen(),null}else s=="ar"&&(s="immersive-ar");if(F()&&C("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await ka.start(s,t||mo.getDefaultSessionInit(s)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(yt||F())&&we("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=ee.Current),i||(i=ue.All[0]),!i)throw new Error("No Needle Engine Context found");switch(performance.mark("NeedleXRSession start"),t||(t={}),s){case"immersive-ar":{if(await((n=this.xrSystem)==null?void 0:n.isSessionSupported("immersive-ar"))!==!0)return console.error(s+" is not supported by this browser."),null;const u=this.getDefaultSessionInit(s),p=t2(i.domElement);p&&!X.isQuest()&&(u.domOverlay={root:p},u.optionalFeatures.push("dom-overlay")),t={...u,...t}}break;case"immersive-vr":{if(await((o=this.xrSystem)==null?void 0:o.isSessionSupported("immersive-vr"))!==!0)return console.error(s+" is not supported by this browser."),null;t={...this.getDefaultSessionInit(s),...t}}break;default:console.warn("No default session init for mode",s);break}t.optionalFeatures??(t.optionalFeatures=[]),t.requiredFeatures??(t.requiredFeatures=[]),await ka.stop();const c=s=="immersive-ar"?i.scripts_immersive_ar:i.scripts_immersive_vr;yt?console.log(`%cRequesting ${s} session`,"font-weight:bold;",t,c):console.log(`%cRequesting ${s} session`,"font-weight:bold;");for(const u of c)u.onBeforeXR&&u.onBeforeXR(s,t);for(const u of this._sessionRequestStartListeners)u({mode:s,init:t});yt&&De("Requesting "+s+" session ("+Date.now()+")"),this._currentSessionRequest=(r=navigator.xr)==null?void 0:r.requestSession(s,t),this._currentSessionRequestMode=s;const h=await((l=this._currentSessionRequest)==null?void 0:l.catch(u=>{console.error(u,"Code: "+u.code),u.code===9&&we("Make sure your device has the required permissions (e.g. camera access)"),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:"&&we("XR requires a secure connection (HTTPS)")}));this._currentSessionRequest=void 0,this._currentSessionRequestMode=null;for(const u of this._sessionRequestEndListeners)u({mode:s,init:t,newSession:h||null});if(!h)return console.warn("XR Session request was rejected"),null;const d=this.setSession(s,h,t,i);return performance.mark("NeedleXRSession end"),performance.measure("NeedleXRSession Startup","NeedleXRSession start","NeedleXRSession end"),d}static setSession(s,t,i,n){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const o=s=="immersive-ar"?n.scripts_immersive_ar:n.scripts_immersive_vr;return this._activeSession=new mo(s,t,n,{scripts:o,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:i}),t.addEventListener("end",this.onEnd),yt?console.log(`%cStarted ${s} session`,"font-weight:bold;",o):console.log(`%cStarted ${s} session`,"font-weight:bold;"),this._activeSession}static stop(){var s;(s=this._activeSession)==null||s.end()}get sync(){return mo._sync}get running(){return!this._ended&&this.session!=null}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}get leftController(){return this.controllers.find(s=>s.side==="left")}get rightController(){return this.controllers.find(s=>s.side==="right")}getController(s){return typeof s=="number"?this.controllers[s]||null:this.controllers.find(t=>t.side===s)||null}get isPassThrough(){return!!(this.environmentBlendMode!=="opaque"&&this.interactionMode==="world-space"||this.mode==="immersive-ar"&&this.environmentBlendMode!=="opaque"&&this.controllers.some(s=>s.inputSource.targetRayMode==="tracked-pointer")||F()&&X.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 s=this.frame.getImageTrackingResults();for(const t of s)if(t.trackingState==="tracked")return!0}catch{return!1}return!1}get rig(){const s=this._rigs[0]??null;return s!=null&&s.gameObject&&vr(s.gameObject)||s?.isActive===!1?(this.updateActiveXRRig(),this._rigs[0]??null):s}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(s){this._rigs.indexOf(s)>=0||(s.priority===void 0&&(s.priority=0),this._rigs.push(s),this.updateActiveXRRig())}removeRig(s){const t=this._rigs.indexOf(s);t!==-1&&(this._rigs.splice(t,1),this.updateActiveXRRig())}setRigActive(s){const t=this._rigs.indexOf(s),i=this._rigs[0];this._rigs.splice(t,1),this._rigs.unshift(s),s.priority=i?.priority??0,this.updateActiveXRRig()}getUserOffsetInRig(){var s;const t=(s=this.context.mainCamera)==null?void 0:s.position;if(!t||!this.rig)return G(0,0,0);const i=G(t);return i.x*=-1,i.z*=-1,i.applyQuaternion(ys(this.rig.gameObject.quaternion)),i}updateActiveXRRig(){const s=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(vr(n.gameObject)){this._rigs.splice(i,1),i--;continue}(!t||t.isActive===!1||n.priority!==void 0&&n.priority>t.priority)&&(t=n)}}if(s!==t){const i=this._rigs.indexOf(t);i>=0&&this._rigs.splice(i,1),this._rigs.unshift(t)}yt&&(s===t?console.log("Updated Active XR Rig:",t,"prev:",s):console.log("Updated Active XRRig:",t," (the same as before)"))}getHitTest(s){if(s)return this.getControllerHitTest(s);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(s){const t=s.getHitTestSource();if(!t)return null;const i=this.frame.getHitTestResultsForTransientInput(t);for(const n of i)if(n.inputSource===s.inputSource)for(const o of n.results)return this.convertHitTestResult(o);return null}convertHitTestResult(s){const t=this.context.renderer.xr.getReferenceSpace(),i=t&&s.getPose(t);if(i){const n=G(i.transform.position),o=ys(i.transform.orientation),r=this.context.mainCamera;if(r?.parent!==this._cameraRenderParent&&n.applyMatrix4(Ca),r!=null&&r.parent){n.applyMatrix4(r.parent.matrixWorld),o.multiply(Gi);const l=Ce(r.parent);l.premultiply(Gi),o.premultiply(l)}return{hit:s,position:n,quaternion:o}}return null}convertSpace(s){const t=G(s.position);t.applyMatrix4(Ca);const i=ys(s.orientation);return i.premultiply(Gi),{position:t,quaternion:i}}disconnectInputSource(s){const t=(i,n,o)=>{if(i.inputSource===s){yt&&console.log("Disconnecting controller",i.index),this.controllers.splice(o,1),this.invokeControllerEvent(i,this._controllerRemoved,"removed");const r={xr:this,controller:i,change:"removed"};for(const l of this._xr_scripts)l.onXRControllerRemoved&&l.onXRControllerRemoved(r);i.onDisconnected()}};for(let i=this.controllers.length-1;i>=0;i--){const n=this.controllers[i];t(n,this.controllers,i)}for(let i=this._newControllers.length-1;i>=0;i--){const n=this._newControllers[i];t(n,this._newControllers,i)}}end(){this._ended||this.session.end().catch(s=>console.warn(s))}onRenderDebug(){if(yt)for(const s of this.controllers)s.onRenderDebug();if((yt||Fb)&&this.rig&&(dg++,dg>=20)){const s=this.rig.gameObject.worldPosition,t=this.rig.gameObject.worldForward;s.add(t.multiplyScalar(1.5));const i=this.rig.gameObject.worldUp;s.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()}`,yt||Fb)for(const o of this.controllers)n+=`
154
- ${o.hand?"hand":"ctrl"} ${o.inputSource.handedness}[${o.index}] con:${o.connected} tr:${o.isTracking} hts:${o.hasHitTestSource?"yes":"no"}`;dg=0,q.DrawLabel(s,n,void 0,1/60*20)}}addScript(s){return this._xr_scripts.includes(s)?!1:(yt&&console.log("Register new XRScript",s),this._xr_scripts.push(s),typeof s.onUpdateXR=="function"&&this._xr_update_scripts.push(s),!0)}markInactive(s){if(!(this._inactive_scripts.indexOf(s)>=0)){this.removeScript(s,!1),this._inactive_scripts.push(s);for(const t of this.controllers)this.invokeCallback_ControllerRemoved(s,t);this.invokeCallback_LeaveXR(s)}}handleInactiveScripts(){if(this._inactive_scripts.length>0)for(let s=this._inactive_scripts.length-1;s>=0;s--){const t=this._inactive_scripts[s];if(t.activeAndEnabled){this._inactive_scripts.splice(s,1),this.addScript(t),this.invokeCallback_EnterXR(t);for(const i of this.controllers)this.invokeCallback_ControllerAdded(t,i)}}}removeScript(s,t=!0){yt&&console.log("Remove XRScript",s);const i=this._xr_scripts.indexOf(s);i>=0&&this._xr_scripts.splice(i,1);const n=this._xr_update_scripts.indexOf(s);if(n>=0&&this._xr_update_scripts.splice(n,1),t){const o=this._inactive_scripts.indexOf(s);o>=0&&this._inactive_scripts.splice(o,1)}}invokeCallback_EnterXR(s){s.onEnterXR&&s.onEnterXR({xr:this})}invokeCallback_ControllerAdded(s,t){s.onXRControllerAdded&&s.onXRControllerAdded({xr:this,controller:t,change:"added"})}invokeCallback_ControllerRemoved(s,t){s.onXRControllerRemoved&&s.onXRControllerRemoved({xr:this,controller:t,change:"removed"})}invokeCallback_LeaveXR(s){s.onLeaveXR&&!s.destroyed&&s.onLeaveXR({xr:this})}syncCameraCullingMask(){var s;const t=this.context.xrCamera,i=(s=this.context.mainCameraComponent)==null?void 0:s.cullingMask;if(t&&i!==void 0){for(const n of t.cameras)n.layers.mask=i;t.layers.mask=i}else if(t){for(const n of t.cameras)n.layers.enableAll();t.layers.enableAll()}}invokeControllerEvent(s,t,i){for(let n=t.length-1;n>=0;n--){const o=t[n];if(o)try{o({xr:this,controller:s,change:i})}catch(r){console.error(r)}}}applyCustomForward(){var s;if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,(s=this._previousCameraParent)==null||s.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);let t=.02;if(this.rig){const i=Ye(this.rig.gameObject);t*=i.x}this._camera instanceof _e&&this._camera.near>t&&(this.originalCameraNearPlane=this._camera.near,this._camera.near=t)}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof _e&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane)}internalUpdateState(){const s=this.context.renderer.xr.getReferenceSpace();if(!s){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(s),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)}}get transition(){return this._transition||(this._transition=new Ab),this._transition}fadeTransition(){return this._transition||(this._transition=new Ab),this._transition.fadeTransition()}updateFade(s){this._transition&&s instanceof _e&&this._transition.update(s,this.context.time.deltaTime)}onUpdateFade_PostRender(){var s;(s=this._transition)==null||s.remove()}};let J=mo;a(J,"_sync",null),a(J,"_currentSessionRequestMode",null),a(J,"_currentSessionRequest"),a(J,"_activeSession"),a(J,"_sessionRequestStartListeners",[]),a(J,"_sessionRequestEndListeners",[]),a(J,"_xrStartListeners",[]),a(J,"_xrEndListeners",[]),a(J,"_controllerAddedListeners",[]),a(J,"_controllerRemovedListeners",[]),a(J,"onEnd",()=>{yt&&console.log("XR Session ended"),mo._activeSession=null});const pg=C("debugwebxr");class Ub{static tryFindAvatarObjects(t,i,n){if(n.head&&n.leftHand&&n.rightHand)return;const o=t.name.toLocaleLowerCase();!n.head&&o.includes("head")&&(pg&&console.log("FOUND AVATAR HEAD",t.name),n.head=new le("",i,t)),o.includes("hand")&&(!n.leftHand&&o.includes("left")&&(pg&&console.log("FOUND AVATAR LEFT HAND",t.name),n.leftHand=new le("",i,t)),!n.rightHand&&o.includes("right")&&(pg&&console.log("FOUND AVATAR RIGHT HAND",t.name),n.rightHand=new le("",i,t)));for(let r=0;r<t.children.length;r++){if(n.head&&n.leftHand&&n.rightHand)return;const l=t.children[r];this.tryFindAvatarObjects(l,i,n)}}}const Ft=new x,Nb=new x,Wb=new V,r2=C("debuggizmos"),ws=8947848,mg=32,xs=class{constructor(){}static isGizmo(s){return s[fg]!==void 0}static setVisible(s){for(const t of Ae.timedObjectsBuffer)t.visible=s}static DrawLabel(s,t,i=.05,n=0,o,r,l){var c;if(!xs.enabled)return null;o||(o=ws);const h=((c=J.active)==null?void 0:c.rigScale)??1,d=Ae.getTextLabel(n,t,i*h,o,r);return l instanceof I&&l.add(d),d.position.x=s.x,d.position.y=s.y,d.position.z=s.z,d}static DrawRay(s,t,i=ws,n=0,o=!0){if(!xs.enabled)return;const r=Ae.getLine(n),l=r.geometry.getAttribute("position");l.setXYZ(0,s.x,s.y,s.z),Ft.set(t.x,t.y,t.z).multiplyScalar(999999999),l.setXYZ(1,s.x+Ft.x,s.y+Ft.y,s.z+Ft.z),l.needsUpdate=!0,r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1}static DrawDirection(s,t,i=ws,n=0,o=!0,r=1){if(!xs.enabled)return;const l=Ae.getLine(n),c=l.geometry.getAttribute("position");c.setXYZ(0,s.x,s.y,s.z),t.w!==void 0?(Ft.set(0,0,-r),Wb.set(t.x,t.y,t.z,t.w),Ft.applyQuaternion(Wb)):(Ft.set(t.x,t.y,t.z),Ft.multiplyScalar(r)),c.setXYZ(1,s.x+Ft.x,s.y+Ft.y,s.z+Ft.z),c.needsUpdate=!0,l.material.color.set(i),l.material.depthTest=o,l.material.depthWrite=!1}static DrawLine(s,t,i=ws,n=0,o=!0){if(!xs.enabled)return;const r=Ae.getLine(n),l=r.geometry.getAttribute("position");l.setXYZ(0,s.x,s.y,s.z),l.setXYZ(1,t.x,t.y,t.z),l.needsUpdate=!0,r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1}static DrawCircle(s,t,i,n=ws,o=0,r=!0){if(!xs.enabled)return;const l=Ae.getCircle(o);l.position.set(s.x,s.y,s.z),l.scale.set(i,i,i),l.quaternion.setFromUnitVectors(this._up,Ft.set(t.x,t.y,t.z).normalize()),l.material.color.set(n),l.material.depthTest=r,l.material.depthWrite=!1,l.material.fog=!1}static DrawWireSphere(s,t,i=ws,n=0,o=!0){if(!xs.enabled)return;const r=Ae.getSphere(t,n,!0);lr(r,s.x,s.y,s.z),r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1}static DrawSphere(s,t,i=ws,n=0,o=!0){if(!xs.enabled)return;const r=Ae.getSphere(t,n,!1);lr(r,s.x,s.y,s.z),r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1}static DrawWireBox(s,t,i=ws,n=0,o=!0){if(!xs.enabled)return;const r=Ae.getBox(n);r.position.set(s.x,s.y,s.z),r.scale.set(t.x,t.y,t.z),r.material.color.set(i),r.material.depthTest=o,r.material.wireframe=!0,r.material.depthWrite=!1,r.material.fog=!1}static DrawWireBox3(s,t=ws,i=0,n=!0){if(!xs.enabled)return;const o=Ae.getBox(i);o.position.copy(s.getCenter(Ft)),o.scale.copy(s.getSize(Ft)),o.material.color.set(t),o.material.depthTest=n,o.material.wireframe=!0,o.material.depthWrite=!1,o.material.fog=!1}static DrawArrow(s,t,i=ws,n=0,o=!0,r=!1){if(!xs.enabled)return;const l=Ae.getArrowHead(n);l.position.set(t.x,t.y,t.z),l.quaternion.setFromUnitVectors(this._up.set(0,1,0),Ft.set(t.x,t.y,t.z).sub(Nb.set(s.x,s.y,s.z)).normalize());const c=Ft.set(t.x,t.y,t.z).sub(Nb.set(s.x,s.y,s.z)).length()*.1;l.scale.set(c,c,c),l.material.color.set(i),l.material.depthTest=o,l.material.wireframe=r,this.DrawLine(s,t,i,n,o)}static DrawWireMesh(s){const t=Ae.getMesh(s.duration??0);"mesh"in s?(t.geometry=s.mesh.geometry,t.matrix.copy(s.mesh.matrixWorld)):(t.geometry=s.geometry,t.matrix.copy(s.matrix)),t.matrixAutoUpdate=!1,t.matrixWorldAutoUpdate=!1,t.material.color.set(s.color??ws),t.material.depthTest=s.depthTest??!0,t.material.wireframe=!0}};let q=xs;a(q,"enabled",!0),a(q,"_up",new x(0,1,0));const a2=new ql(1,1,1);function gg(s=null){const t=new ae(s??14540253),i=new wS(a2);return new $y(i,new qy({color:t}))}const fg=Symbol("GizmoCache");class Ae{static ensureFont(){let t=Te.FontLibrary.getFontFamily(this.familyName);if(!t){t=Te.FontLibrary.addFontFamily(this.familyName);const i=t.addVariant("normal","normal","https://uploads.needle.tools/include/font-msdf.json","https://uploads.needle.tools/include/font.png");i?.addEventListener("ready",()=>{Te.update()})}}static getTextLabel(t,i,n,o,r){this.ensureFont();let l=this.textLabelCache.pop(),c=1;r&&typeof r=="string"&&r?.length>=8&&r.startsWith("#")?(c=parseInt(r.substring(7),16)/255,r=r.substring(0,7),r2&&console.log(r,c)):typeof r=="object"&&r.a!==void 0&&(c=r.a);const h={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:n,color:o,lineHeight:1,backgroundColor:r??void 0,backgroundOpacity:c,textContent:i,borderRadius:.5*n,padding:.8*n,whiteSpace:"pre",offset:.05*n};if(l)l.set(h);else{l=new mv(h);const d=this,u=l;u.setText=function(p){this.set({textContent:p}),d.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(ee.Current,l,t,this.textLabelCache),l}static getBox(t){let i=this.boxesCache.pop();if(!i){const n=new ql(1,1,1);i=new Y(n)}return this.registerTimedObject(ee.Current,i,t,this.boxesCache),i}static getLine(t){let i=this.linesCache.pop();if(!i){i=new Gl;let n=i.geometry.getAttribute("position");n||(n=new ft(new Float32Array(2*3),3),i.geometry.setAttribute("position",n))}return i.frustumCulled=!1,this.registerTimedObject(ee.Current,i,t,this.linesCache),i}static getCircle(t){let i=this.circlesCache.pop();if(!i){i=new Gl;let n=i.geometry.getAttribute("position");if(!n){n=new ft(new Float32Array(mg*3),3),i.geometry.setAttribute("position",n);const o=G(0,1,0),r=G(0,0,1),l=G(r);l.cross(o).normalize();const c=G(l),h=Math.PI*2/(mg-1);for(let d=0;d<mg+1;d++){const u=h*d;o.copy(c).multiplyScalar(Math.cos(u)*1),l.copy(r).multiplyScalar(Math.sin(u)*1);const p=o.add(l);n.setXYZ(d,p.x,p.y,p.z)}}}return i.frustumCulled=!1,this.registerTimedObject(ee.Current,i,t,this.circlesCache),i}static getSphere(t,i,n){let o=this.spheresCache.pop();return o||(o=new Y(new nd(1,8,8))),o.scale.set(t,t,t),o.material.wireframe=n,this.registerTimedObject(ee.Current,o,i,this.spheresCache),o}static getArrowHead(t){let i=this.arrowHeadsCache.pop();return i||(i=new Y(new _S(0,.5,1,8))),this.registerTimedObject(ee.Current,i,t,this.arrowHeadsCache),i}static getMesh(t){let i=this.mesh.pop();return i||(i=new Y,i.material=new Re),this.registerTimedObject(ee.Current,i,t,this.mesh),i}static registerTimedObject(t,i,n,o){if(!t){console.error("No Needle Engine context available. Did you call a Gizmos function in global scope?");return}const r=this.contextBeforeRenderCallbacks.get(t),l=this.contextPostRenderCallbacks.get(t);if(r){if(t.pre_render_callbacks[t.pre_render_callbacks.length-1]!==r){const c=t.pre_render_callbacks.indexOf(r);c>=0&&t.pre_render_callbacks.splice(c,1),t.pre_render_callbacks.push(r)}}else{const c=()=>{this.onBeforeRender(t,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(t,c),t.pre_render_callbacks.push(c)}if(l){if(t.post_render_callbacks[t.post_render_callbacks.length-1]!==l){const c=t.post_render_callbacks.indexOf(l);c>=0&&t.post_render_callbacks.splice(c,1),t.post_render_callbacks.push(l)}}else{const c=()=>{this.onPostRender(t,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(t,c),t.post_render_callbacks.push(c)}i.traverse(c=>{c.layers.disableAll(),c.layers.enable(2)}),i.renderOrder=999999,i[fg]=o,i.castShadow=!1,i.receiveShadow=!1,i.isGizmo=!0,this.timedObjectsBuffer.push(i),this.timesBuffer.push(ee.Current.time.realtimeSinceStartup+n),t.scene.add(i)}static onBeforeRender(t,i){this.tmuiNeedsUpdate&&(this.tmuiNeedsUpdate=!1,Te.update());for(let n=0;n<i.length;n++){const o=i[n];if(t.mainCamera&&o instanceof Te.MeshUIBaseElement){if(vr(o))continue;const r=t.isInVR,l=!1,c=!r;tc(o,t.mainCamera,l,c)}}}static onPostRender(t,i,n){const o=t.time.realtimeSinceStartup;for(let r=i.length-1;r>=0;r--){const l=i[r];o>=n[r]-1e-6&&(i.splice(r,1),n.splice(r,1),l.removeFromParent(),vr(l)!=!0&&l[fg].push(l))}}}a(Ae,"familyName","needle-gizmos"),a(Ae,"linesCache",[]),a(Ae,"circlesCache",[]),a(Ae,"spheresCache",[]),a(Ae,"boxesCache",[]),a(Ae,"arrowHeadsCache",[]),a(Ae,"mesh",[]),a(Ae,"textLabelCache",[]),a(Ae,"timedObjectsBuffer",new Array),a(Ae,"timesBuffer",new Array),a(Ae,"contextPostRenderCallbacks",new Map),a(Ae,"contextBeforeRenderCallbacks",new Map),a(Ae,"tmuiNeedsUpdate",!1);const ki=C("debugphysics"),Vb=new so;class Ws{constructor(){a(this,"ray"),a(this,"cam"),a(this,"screenPoint"),a(this,"raycaster"),a(this,"results"),a(this,"targets"),a(this,"recursive",!0),a(this,"minDistance"),a(this,"maxDistance"),a(this,"lineThreshold"),a(this,"layerMask"),a(this,"ignore"),a(this,"testObject"),a(this,"useAcceleratedRaycast")}screenPointFromOffset(t,i){this.screenPoint===void 0&&(this.screenPoint=new re),this.screenPoint.x=t/window.innerWidth*2-1,this.screenPoint.y=-(i/window.innerHeight)*2+1}setLayer(t){Vb.set(t),this.layerMask=Vb}setMask(t){this.layerMask||(this.layerMask=new so);const i=this.layerMask;i?i.mask=t:this.layerMask=t}}a(Ws,"AllLayers",4294967295);class yg{constructor(t,i,n){a(this,"distance"),a(this,"point"),a(this,"object"),this.object=t,this.distance=i,this.point=n}}const vg=class{constructor(s){a(this,"context"),a(this,"engine"),a(this,"raycaster",new rd),a(this,"defaultRaycastOptions",new Ws),a(this,"targetBuffer",new Array(1)),a(this,"defaultThresholds",{Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}}),a(this,"sphereResults",new Array),a(this,"sphereMask",new so),a(this,"sphere",new od),a(this,"tempBoundingBox",new wi),this.context=s}static get raycasting(){return this._raycasting>0}raycastPhysicsFast(s,t=void 0,i=1/0,n=!0){var o;return((o=this.context.physics.engine)==null?void 0:o.raycast(s,t,{maxDistance:i,solid:n}))??null}raycastPhysicsFastAndGetNormal(s,t=void 0,i=1/0,n=!0){var o;return((o=this.context.physics.engine)==null?void 0:o.raycastAndGetNormal(s,t,{maxDistance:i,solid:n}))??null}sphereOverlapPhysics(s,t){var i;return((i=this.context.physics.engine)==null?void 0:i.sphereOverlap(s,t))??null}sphereOverlap(s,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 l of this.context.scene.children)this.intersectSphere(l,s,t,r,this.sphereResults,i,n,o);return this.sphereResults.sort((l,c)=>l.distance-c.distance)}raycastFromRay(s,t=null){const i=t??this.defaultRaycastOptions;i.ray=s;const n=this.raycast(i);return i===this.defaultRaycastOptions&&(i.ray=void 0),n}raycast(s=null){ki&&performance.mark("raycast.start"),s||(s=this.defaultRaycastOptions);const t=s.screenPoint??this.context.input.mousePositionRC,i=s.raycaster??this.raycaster;if(i.near=s.minDistance??0,i.far=s.maxDistance??1/0,i.params=this.defaultThresholds,s.lineThreshold===void 0&&(s.lineThreshold=-1),i.params.Line={threshold:s.lineThreshold},s.ray)i.ray.copy(s.ray);else{const l=s.cam??this.context.mainCamera;if(!l)return ki&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const c=this.context.xrCamera;this.context.isInXR&&c instanceof xS&&c.cameras.length>0?i.setFromCamera(t,c.cameras[0]):i.setFromCamera(t,l)}let n=s.targets;n||(n=this.targetBuffer,n.length=1,n[0]=this.context.scene);let o=s.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),o||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),o=this.defaultRaycastOptions.results),s.layerMask!==void 0?s.layerMask instanceof so?i.layers.mask=s.layerMask.mask:i.layers.mask=s.layerMask:(i.layers.enableAll(),i.layers.disable(2)),ki&&console.time("raycast"),o.length=0,vg._raycasting++,this.intersect(this.raycaster,n,o,s),o.sort((l,c)=>l.distance-c.distance);const r=s.ignore;return r!==void 0&&r.length>0&&(o=o.filter(l=>!r.includes(l.object))),vg._raycasting--,ki&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",o!=null&&o.length?[...o]:"nothing"),performance.mark("raycast.end"),performance.measure("raycast","raycast.start","raycast.end")),o}intersect(s,t,i,n){var o,r,l;for(const c of t){if(!c||c.visible===!1||q.isGizmo(c)||n.lineThreshold!==void 0&&n.lineThreshold<0&&c instanceof Gl)continue;let h=!0;const d=c,u=d.geometry;if(n.testObject){const p=(o=n.testObject)==null?void 0:o.call(n,c);if(p===!1)continue;p==="continue in children"&&(h=!1)}if(h&&(u&&Hb(u)||(h=!1)),h){const p=sv(c);p&&(d.geometry=p);const g=i.length;let y=!0;if(n.precise===!1&&(y=!1),y||(y=((l=(r=u.getAttribute("position"))==null?void 0:r.array)==null?void 0:l.length)<64),d instanceof va&&(y=!1),!y&&c2(d,s,i)||(n.useAcceleratedRaycast!==!1?Id.runMeshBVHRaycast(s,d,i,this.context):s.intersectObject(d,!1,i)),ki&&i.length!=g){const f=i[i.length-1],v=p?8969557:7798784;q.DrawWireSphere(f.point,.1,v,1,!1),q.DrawWireMesh({mesh:c,depthTest:!1,duration:.2,color:v})}d.geometry=u}n.recursive!==!1&&this.intersect(s,c.children,i,n)}return i}intersectSphere(s,t,i,n,o,r,l,c){let h=s&&s.isMesh&&s.layers.test(n)&&!q.isGizmo(s);h&&(h=s.visible),h&&(h=!(s instanceof Gl)),h&&(h=!(s instanceof va));const d=s,u=d.geometry;if(h&&c){const p=c(s);if(p===!1)return;p==="continue in children"&&(h=!1)}if(u&&Hb(u)||(h=!1),h){if(l){const p=this.sphere;p.center.copy(t),p.radius=i;const g=o.length;if(Id.runMeshBVHRaycast(this.sphere,d,o,this.context),g!=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),g=this.sphere;if(g.center.copy(t),g.radius=i,g.intersectsBox(p)){const y=te(s),f=y.distanceTo(g.center),v=new yg(s,f,y);if(o.push(v),!r)return}}}if(s.children)for(const p of s.children){const g=o.length;if(this.intersectSphere(p,t,i,n,o,r,l,c),g!=o.length&&!r)return}}};let Ed=vg;a(Ed,"_raycasting",0);function Hb(s){return!(s.index&&s.index.array.length<3)}const pr=new od,Ad=new nr,l2=new Wy;function c2(s,t,i){const n=s._computeIntersections;if(!n)return!1;let o=s["_computeIntersections:Needle"];return o||(o=s["_computeIntersections:Needle"]=function(r,l,c){const h=this,d=h.geometry.boundingSphere;if(d){if(h instanceof va){Ad.setFromNormalAndCoplanarPoint(G(0,1,0),G(0,-h.position.y,0)),Ad.applyMatrix4(h.matrixWorld,l2);const p=r.ray.intersectPlane(Ad,G());if(p){pr.copy(d),pr.applyMatrix4(h.matrixWorld);const g=G(p).sub(r.ray.origin).length(),y=pr.radius*.5;g<y&&l.push({distance:g,point:p,object:h,normal:Ad.normal.clone()})}return}pr.copy(d),pr.applyMatrix4(h.matrixWorld);const u=r.ray.intersectSphere(pr,G());if(u){const p=G(u).sub(r.ray.origin),g=p.length();if(g>pr.radius){const y=p.clone().normalize();l.push({distance:g,point:u,object:h,normal:y})}}}}),s._computeIntersections=o,t.intersectObject(s,!1,i),s._computeIntersections=n,!0}var Id;(s=>{function t(w,_,S,R){var M,T,j;if(!_.geometry||!_.geometry.hasAttribute("position"))return!1;const L=_.geometry;if(_!=null&&_.isSkinnedMesh){const U=_,B=U.bvhNeedsUpdate;if(!U.staticGenerator)c(),r&&(U.staticGenerator=new r(_),U.staticGenerator.applyWorldTransforms=!1,U.staticGeometry=U.staticGenerator.generate(),L.boundsTree=l?.call(U.staticGeometry),U.staticGeometryLastUpdate=performance.now()+Math.random()*200,U.autoUpdateMeshBVH===void 0&&(U.autoUpdateMeshBVH=!1));else if(L.boundsTree&&(U.autoUpdateMeshBVH===!0||B===!0)){const Q=performance.now(),$=Q-U.staticGeometryLastUpdate;(B||$>100)&&(U.bvhNeedsUpdate=!1,U.staticGeometryLastUpdate=Q,(M=U.staticGenerator)==null||M.generate(U.staticGeometry),L.boundsTree.refit())}}else if(!L.boundsTree){d||b();let U=!0;if((R.xr||L[y]===!1||(T=L.getAttribute("position"))!=null&&T.isInterleavedBufferAttribute||L.index&&(j=L.index)!=null&&j.isInterleavedBufferAttribute)&&(U=!1),U&&p){if(L[g]===void 0){let B=null;if(v.length>0){const Q=v.shift();Q&&!Q.running&&(B=Q)}if(!B&&f.length<3&&(B=new p,f.push(B)),B!=null&&!B.running){const Q=_.name;ki&&console.log("<<<< worker start",Q,B),L[g]="queued",performance.mark("bvh.create.start");const $=L.clone();try{B.generate($).then(E=>{L[g]="done",L.boundsTree=E}).catch(E=>{L[g]="failed - "+E?.message,L[y]=!1,ki&&console.error("Failed to generate mesh bvh on worker",E)}).finally(()=>{ki&&console.log(">>>>> worker done",Q,{hasBoundsTre:L.boundsTree!=null}),v.push(B),$.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch(E){console.error("Failed to generate mesh bvh on worker",E)}}else ki&&console.warn("No worker available")}}else(!u||!U)&&(c(),o&&(performance.mark("bvh.create.start"),L.boundsTree=new o(L),performance.mark("bvh.create.end"),performance.measure("bvh.create","bvh.create.start","bvh.create.end")))}if(w instanceof rd){const U=w,B=_.raycast;L.boundsTree?(c(),n&&(_.acceleratedRaycast||(_.acceleratedRaycast=n.bind(_),ki&&console.debug(`Physics: bind acceleratedRaycast fn to "${_.name}"`)),_.raycast=_.acceleratedRaycast)):ki&&console.warn("No bounds tree found for mesh",_.name,{workerTask:L[g],hasAcceleratedRaycast:n!=null});const Q=U.firstHitOnly;return U.firstHitOnly=!1,U.intersectObject(_,!1,S),U.firstHitOnly=Q,_.raycast=B,!0}else if(w instanceof od){const U=L.boundsTree;if(U){const B=w;if(h.copy(_.matrixWorld).invert(),B.applyMatrix4(h),U.intersectsSphere(B)){const Q=te(_),$=Q.distanceTo(B.center),E=new yg(_,$,Q);S.push(E)}}return!0}return!1}s.runMeshBVHRaycast=t;let i=!1,n=null,o=null,r=null,l=null;function c(){i||(i=!0,import("./vendor.light.min.js").then(w=>w.k).then(w=>{n=w.acceleratedRaycast,o=w.MeshBVH,r=w.StaticGeometryGenerator,l=w.computeBoundsTree}).catch(w=>{(ki||F())&&console.error("Failed to load BVH library...",w.message)}))}const h=new ne;let d=!1,u=!1,p=null;const g=Symbol("Needle:MeshBVH-Worker"),y=Symbol("Needle:MeshBVH-CanUseWorker"),f=[],v=[];function b(){d=!0,u=!0,Promise.resolve().then(()=>Yj).then(w=>{p=w.GenerateMeshBVHWorker}).catch(w=>{(ki||F())&&console.warn("Failed to setup mesh bvh worker")}).finally(()=>{u=!1})}})(Id||(Id={}));const $b=Symbol("gltf-loader-internal-usage-tracker"),h2=C("debugusers"),jd=class{constructor(s){a(this,"parser"),a(this,"_getDependency"),a(this,"_loadingId"),a(this,"_loadedObjects",new Set),this.parser=s,this._getDependency=this.parser.getDependency,this._loadingId=Date.now().toString()}get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(s){return jd._loadingProcesses>0}beforeRoot(){jd._loadingProcesses++;const s=this,t=this._getDependency;return this.parser.getDependency=function(i,n){const o=t.call(this,i,n);return o.then(r=>(r&&(s._loadedObjects.add(r),r[$b]=s._loadingId),r)),o},null}afterRoot(s){jd._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[$b],t instanceof I&&(t.parent||t instanceof Y&&setTimeout(()=>{h2&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}};let bg=jd;a(bg,"_loadingProcesses",0);class qb{constructor(){window.addEventListener("unhandledrejection",t=>{var i;if(t.defaultPrevented)return;const n=(i=t?.reason)==null?void 0:i.path;if(n){const o=n[0];o&&o.tagName==="IMG"&&(console.warn(`Could not load image:
154
+ ${o.hand?"hand":"ctrl"} ${o.inputSource.handedness}[${o.index}] con:${o.connected} tr:${o.isTracking} hts:${o.hasHitTestSource?"yes":"no"}`;dg=0,q.DrawLabel(s,n,void 0,1/60*20)}}addScript(s){return this._xr_scripts.includes(s)?!1:(yt&&console.log("Register new XRScript",s),this._xr_scripts.push(s),typeof s.onUpdateXR=="function"&&this._xr_update_scripts.push(s),!0)}markInactive(s){if(!(this._inactive_scripts.indexOf(s)>=0)){this.removeScript(s,!1),this._inactive_scripts.push(s);for(const t of this.controllers)this.invokeCallback_ControllerRemoved(s,t);this.invokeCallback_LeaveXR(s)}}handleInactiveScripts(){if(this._inactive_scripts.length>0)for(let s=this._inactive_scripts.length-1;s>=0;s--){const t=this._inactive_scripts[s];if(t.activeAndEnabled){this._inactive_scripts.splice(s,1),this.addScript(t),this.invokeCallback_EnterXR(t);for(const i of this.controllers)this.invokeCallback_ControllerAdded(t,i)}}}removeScript(s,t=!0){yt&&console.log("Remove XRScript",s);const i=this._xr_scripts.indexOf(s);i>=0&&this._xr_scripts.splice(i,1);const n=this._xr_update_scripts.indexOf(s);if(n>=0&&this._xr_update_scripts.splice(n,1),t){const o=this._inactive_scripts.indexOf(s);o>=0&&this._inactive_scripts.splice(o,1)}}invokeCallback_EnterXR(s){s.onEnterXR&&s.onEnterXR({xr:this})}invokeCallback_ControllerAdded(s,t){s.onXRControllerAdded&&s.onXRControllerAdded({xr:this,controller:t,change:"added"})}invokeCallback_ControllerRemoved(s,t){s.onXRControllerRemoved&&s.onXRControllerRemoved({xr:this,controller:t,change:"removed"})}invokeCallback_LeaveXR(s){s.onLeaveXR&&!s.destroyed&&s.onLeaveXR({xr:this})}syncCameraCullingMask(){var s;const t=this.context.xrCamera,i=(s=this.context.mainCameraComponent)==null?void 0:s.cullingMask;if(t&&i!==void 0){for(const n of t.cameras)n.layers.mask=i;t.layers.mask=i}else if(t){for(const n of t.cameras)n.layers.enableAll();t.layers.enableAll()}}invokeControllerEvent(s,t,i){for(let n=t.length-1;n>=0;n--){const o=t[n];if(o)try{o({xr:this,controller:s,change:i})}catch(r){console.error(r)}}}applyCustomForward(){var s;if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,(s=this._previousCameraParent)==null||s.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);let t=.02;if(this.rig){const i=Ye(this.rig.gameObject);t*=i.x}this._camera instanceof _e&&this._camera.near>t&&(this.originalCameraNearPlane=this._camera.near,this._camera.near=t)}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof _e&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane)}internalUpdateState(){const s=this.context.renderer.xr.getReferenceSpace();if(!s){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(s),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)}}get transition(){return this._transition||(this._transition=new Ab),this._transition}fadeTransition(){return this._transition||(this._transition=new Ab),this._transition.fadeTransition()}updateFade(s){this._transition&&s instanceof _e&&this._transition.update(s,this.context.time.deltaTime)}onUpdateFade_PostRender(){var s;(s=this._transition)==null||s.remove()}};let J=mo;a(J,"_sync",null),a(J,"_currentSessionRequestMode",null),a(J,"_currentSessionRequest"),a(J,"_activeSession"),a(J,"_sessionRequestStartListeners",[]),a(J,"_sessionRequestEndListeners",[]),a(J,"_xrStartListeners",[]),a(J,"_xrEndListeners",[]),a(J,"_controllerAddedListeners",[]),a(J,"_controllerRemovedListeners",[]),a(J,"onEnd",()=>{yt&&console.log("XR Session ended"),mo._activeSession=null});const pg=C("debugwebxr");class Ub{static tryFindAvatarObjects(t,i,n){if(n.head&&n.leftHand&&n.rightHand)return;const o=t.name.toLocaleLowerCase();!n.head&&o.includes("head")&&(pg&&console.log("FOUND AVATAR HEAD",t.name),n.head=new le("",i,t)),o.includes("hand")&&(!n.leftHand&&o.includes("left")&&(pg&&console.log("FOUND AVATAR LEFT HAND",t.name),n.leftHand=new le("",i,t)),!n.rightHand&&o.includes("right")&&(pg&&console.log("FOUND AVATAR RIGHT HAND",t.name),n.rightHand=new le("",i,t)));for(let r=0;r<t.children.length;r++){if(n.head&&n.leftHand&&n.rightHand)return;const l=t.children[r];this.tryFindAvatarObjects(l,i,n)}}}const Ft=new x,Nb=new x,Wb=new V,r2=C("debuggizmos"),ws=8947848,mg=32,xs=class{constructor(){}static isGizmo(s){return s[fg]!==void 0}static setVisible(s){for(const t of Ae.timedObjectsBuffer)t.visible=s}static DrawLabel(s,t,i=.05,n=0,o,r,l){var c;if(!xs.enabled)return null;o||(o=ws);const h=((c=J.active)==null?void 0:c.rigScale)??1,d=Ae.getTextLabel(n,t,i*h,o,r);return l instanceof I&&l.add(d),d.position.x=s.x,d.position.y=s.y,d.position.z=s.z,d}static DrawRay(s,t,i=ws,n=0,o=!0){if(!xs.enabled)return;const r=Ae.getLine(n),l=r.geometry.getAttribute("position");l.setXYZ(0,s.x,s.y,s.z),Ft.set(t.x,t.y,t.z).multiplyScalar(999999999),l.setXYZ(1,s.x+Ft.x,s.y+Ft.y,s.z+Ft.z),l.needsUpdate=!0,r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1}static DrawDirection(s,t,i=ws,n=0,o=!0,r=1){if(!xs.enabled)return;const l=Ae.getLine(n),c=l.geometry.getAttribute("position");c.setXYZ(0,s.x,s.y,s.z),t.w!==void 0?(Ft.set(0,0,-r),Wb.set(t.x,t.y,t.z,t.w),Ft.applyQuaternion(Wb)):(Ft.set(t.x,t.y,t.z),Ft.multiplyScalar(r)),c.setXYZ(1,s.x+Ft.x,s.y+Ft.y,s.z+Ft.z),c.needsUpdate=!0,l.material.color.set(i),l.material.depthTest=o,l.material.depthWrite=!1}static DrawLine(s,t,i=ws,n=0,o=!0){if(!xs.enabled)return;const r=Ae.getLine(n),l=r.geometry.getAttribute("position");l.setXYZ(0,s.x,s.y,s.z),l.setXYZ(1,t.x,t.y,t.z),l.needsUpdate=!0,r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1}static DrawCircle(s,t,i,n=ws,o=0,r=!0){if(!xs.enabled)return;const l=Ae.getCircle(o);l.position.set(s.x,s.y,s.z),l.scale.set(i,i,i),l.quaternion.setFromUnitVectors(this._up,Ft.set(t.x,t.y,t.z).normalize()),l.material.color.set(n),l.material.depthTest=r,l.material.depthWrite=!1,l.material.fog=!1}static DrawWireSphere(s,t,i=ws,n=0,o=!0){if(!xs.enabled)return;const r=Ae.getSphere(t,n,!0);lr(r,s.x,s.y,s.z),r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1}static DrawSphere(s,t,i=ws,n=0,o=!0){if(!xs.enabled)return;const r=Ae.getSphere(t,n,!1);lr(r,s.x,s.y,s.z),r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1}static DrawWireBox(s,t,i=ws,n=0,o=!0){if(!xs.enabled)return;const r=Ae.getBox(n);r.position.set(s.x,s.y,s.z),r.scale.set(t.x,t.y,t.z),r.material.color.set(i),r.material.depthTest=o,r.material.wireframe=!0,r.material.depthWrite=!1,r.material.fog=!1}static DrawWireBox3(s,t=ws,i=0,n=!0){if(!xs.enabled)return;const o=Ae.getBox(i);o.position.copy(s.getCenter(Ft)),o.scale.copy(s.getSize(Ft)),o.material.color.set(t),o.material.depthTest=n,o.material.wireframe=!0,o.material.depthWrite=!1,o.material.fog=!1}static DrawArrow(s,t,i=ws,n=0,o=!0,r=!1){if(!xs.enabled)return;const l=Ae.getArrowHead(n);l.position.set(t.x,t.y,t.z),l.quaternion.setFromUnitVectors(this._up.set(0,1,0),Ft.set(t.x,t.y,t.z).sub(Nb.set(s.x,s.y,s.z)).normalize());const c=Ft.set(t.x,t.y,t.z).sub(Nb.set(s.x,s.y,s.z)).length()*.1;l.scale.set(c,c,c),l.material.color.set(i),l.material.depthTest=o,l.material.wireframe=r,this.DrawLine(s,t,i,n,o)}static DrawWireMesh(s){const t=Ae.getMesh(s.duration??0);"mesh"in s?(t.geometry=s.mesh.geometry,t.matrix.copy(s.mesh.matrixWorld)):(t.geometry=s.geometry,t.matrix.copy(s.matrix)),t.matrixAutoUpdate=!1,t.matrixWorldAutoUpdate=!1,t.material.color.set(s.color??ws),t.material.depthTest=s.depthTest??!0,t.material.wireframe=!0}};let q=xs;a(q,"enabled",!0),a(q,"_up",new x(0,1,0));const a2=new ql(1,1,1);function gg(s=null){const t=new ae(s??14540253),i=new wS(a2);return new $y(i,new qy({color:t}))}const fg=Symbol("GizmoCache");class Ae{static ensureFont(){let t=Te.FontLibrary.getFontFamily(this.familyName);if(!t){t=Te.FontLibrary.addFontFamily(this.familyName);const i=t.addVariant("normal","normal","https://uploads.needle.tools/include/font-msdf.json","https://uploads.needle.tools/include/font.png");i?.addEventListener("ready",()=>{Te.update()})}}static getTextLabel(t,i,n,o,r){this.ensureFont();let l=this.textLabelCache.pop(),c=1;r&&typeof r=="string"&&r?.length>=8&&r.startsWith("#")?(c=parseInt(r.substring(7),16)/255,r=r.substring(0,7),r2&&console.log(r,c)):typeof r=="object"&&r.a!==void 0&&(c=r.a);const h={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:n,color:o,lineHeight:1,backgroundColor:r??void 0,backgroundOpacity:c,textContent:i,borderRadius:.5*n,padding:.8*n,whiteSpace:"pre",offset:.05*n};if(l)l.set(h);else{l=new mv(h);const d=this,u=l;u.setText=function(p){this.set({textContent:p}),d.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(ee.Current,l,t,this.textLabelCache),l}static getBox(t){let i=this.boxesCache.pop();if(!i){const n=new ql(1,1,1);i=new Y(n)}return this.registerTimedObject(ee.Current,i,t,this.boxesCache),i}static getLine(t){let i=this.linesCache.pop();if(!i){i=new Gl;let n=i.geometry.getAttribute("position");n||(n=new ft(new Float32Array(2*3),3),i.geometry.setAttribute("position",n))}return i.frustumCulled=!1,this.registerTimedObject(ee.Current,i,t,this.linesCache),i}static getCircle(t){let i=this.circlesCache.pop();if(!i){i=new Gl;let n=i.geometry.getAttribute("position");if(!n){n=new ft(new Float32Array(mg*3),3),i.geometry.setAttribute("position",n);const o=G(0,1,0),r=G(0,0,1),l=G(r);l.cross(o).normalize();const c=G(l),h=Math.PI*2/(mg-1);for(let d=0;d<mg+1;d++){const u=h*d;o.copy(c).multiplyScalar(Math.cos(u)*1),l.copy(r).multiplyScalar(Math.sin(u)*1);const p=o.add(l);n.setXYZ(d,p.x,p.y,p.z)}}}return i.frustumCulled=!1,this.registerTimedObject(ee.Current,i,t,this.circlesCache),i}static getSphere(t,i,n){let o=this.spheresCache.pop();return o||(o=new Y(new nd(1,8,8))),o.scale.set(t,t,t),o.material.wireframe=n,this.registerTimedObject(ee.Current,o,i,this.spheresCache),o}static getArrowHead(t){let i=this.arrowHeadsCache.pop();return i||(i=new Y(new _S(0,.5,1,8))),this.registerTimedObject(ee.Current,i,t,this.arrowHeadsCache),i}static getMesh(t){let i=this.mesh.pop();return i||(i=new Y,i.material=new Re),this.registerTimedObject(ee.Current,i,t,this.mesh),i}static registerTimedObject(t,i,n,o){if(!t){console.error("No Needle Engine context available. Did you call a Gizmos function in global scope?");return}const r=this.contextBeforeRenderCallbacks.get(t),l=this.contextPostRenderCallbacks.get(t);if(r){if(t.pre_render_callbacks[t.pre_render_callbacks.length-1]!==r){const c=t.pre_render_callbacks.indexOf(r);c>=0&&t.pre_render_callbacks.splice(c,1),t.pre_render_callbacks.push(r)}}else{const c=()=>{this.onBeforeRender(t,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(t,c),t.pre_render_callbacks.push(c)}if(l){if(t.post_render_callbacks[t.post_render_callbacks.length-1]!==l){const c=t.post_render_callbacks.indexOf(l);c>=0&&t.post_render_callbacks.splice(c,1),t.post_render_callbacks.push(l)}}else{const c=()=>{this.onPostRender(t,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(t,c),t.post_render_callbacks.push(c)}i.traverse(c=>{c.layers.disableAll(),c.layers.enable(2)}),i.renderOrder=999999,i[fg]=o,i.castShadow=!1,i.receiveShadow=!1,i.isGizmo=!0,this.timedObjectsBuffer.push(i),this.timesBuffer.push(ee.Current.time.realtimeSinceStartup+n),t.scene.add(i)}static onBeforeRender(t,i){this.tmuiNeedsUpdate&&(this.tmuiNeedsUpdate=!1,Te.update());for(let n=0;n<i.length;n++){const o=i[n];if(t.mainCamera&&o instanceof Te.MeshUIBaseElement){if(vr(o))continue;const r=t.isInVR,l=!1,c=!r;tc(o,t.mainCamera,l,c)}}}static onPostRender(t,i,n){const o=t.time.realtimeSinceStartup;for(let r=i.length-1;r>=0;r--){const l=i[r];o>=n[r]-1e-6&&(i.splice(r,1),n.splice(r,1),l.removeFromParent(),vr(l)!=!0&&l[fg].push(l))}}}a(Ae,"familyName","needle-gizmos"),a(Ae,"linesCache",[]),a(Ae,"circlesCache",[]),a(Ae,"spheresCache",[]),a(Ae,"boxesCache",[]),a(Ae,"arrowHeadsCache",[]),a(Ae,"mesh",[]),a(Ae,"textLabelCache",[]),a(Ae,"timedObjectsBuffer",new Array),a(Ae,"timesBuffer",new Array),a(Ae,"contextPostRenderCallbacks",new Map),a(Ae,"contextBeforeRenderCallbacks",new Map),a(Ae,"tmuiNeedsUpdate",!1);const ki=C("debugphysics"),Vb=new so;class Ws{constructor(){a(this,"ray"),a(this,"cam"),a(this,"screenPoint"),a(this,"raycaster"),a(this,"results"),a(this,"targets"),a(this,"recursive",!0),a(this,"minDistance"),a(this,"maxDistance"),a(this,"lineThreshold"),a(this,"layerMask"),a(this,"ignore"),a(this,"testObject"),a(this,"useAcceleratedRaycast")}screenPointFromOffset(t,i){this.screenPoint===void 0&&(this.screenPoint=new re),this.screenPoint.x=t/window.innerWidth*2-1,this.screenPoint.y=-(i/window.innerHeight)*2+1}setLayer(t){Vb.set(t),this.layerMask=Vb}setMask(t){this.layerMask||(this.layerMask=new so);const i=this.layerMask;i?i.mask=t:this.layerMask=t}}a(Ws,"AllLayers",4294967295);class yg{constructor(t,i,n){a(this,"distance"),a(this,"point"),a(this,"object"),this.object=t,this.distance=i,this.point=n}}const vg=class{constructor(s){a(this,"context"),a(this,"engine"),a(this,"raycaster",new rd),a(this,"defaultRaycastOptions",new Ws),a(this,"targetBuffer",new Array(1)),a(this,"defaultThresholds",{Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}}),a(this,"sphereResults",new Array),a(this,"sphereMask",new so),a(this,"sphere",new od),a(this,"tempBoundingBox",new wi),this.context=s}static get raycasting(){return this._raycasting>0}raycastPhysicsFast(s,t=void 0,i=1/0,n=!0){var o;return((o=this.context.physics.engine)==null?void 0:o.raycast(s,t,{maxDistance:i,solid:n}))??null}raycastPhysicsFastAndGetNormal(s,t=void 0,i=1/0,n=!0){var o;return((o=this.context.physics.engine)==null?void 0:o.raycastAndGetNormal(s,t,{maxDistance:i,solid:n}))??null}sphereOverlapPhysics(s,t){var i;return((i=this.context.physics.engine)==null?void 0:i.sphereOverlap(s,t))??null}sphereOverlap(s,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 l of this.context.scene.children)this.intersectSphere(l,s,t,r,this.sphereResults,i,n,o);return this.sphereResults.sort((l,c)=>l.distance-c.distance)}raycastFromRay(s,t=null){const i=t??this.defaultRaycastOptions;i.ray=s;const n=this.raycast(i);return i===this.defaultRaycastOptions&&(i.ray=void 0),n}raycast(s=null){ki&&performance.mark("raycast.start"),s||(s=this.defaultRaycastOptions);const t=s.screenPoint??this.context.input.mousePositionRC,i=s.raycaster??this.raycaster;if(i.near=s.minDistance??0,i.far=s.maxDistance??1/0,i.params=this.defaultThresholds,s.lineThreshold===void 0&&(s.lineThreshold=-1),i.params.Line={threshold:s.lineThreshold},s.ray)i.ray.copy(s.ray);else{const l=s.cam??this.context.mainCamera;if(!l)return ki&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const c=this.context.xrCamera;this.context.isInXR&&c instanceof xS&&c.cameras.length>0?i.setFromCamera(t,c.cameras[0]):i.setFromCamera(t,l)}let n=s.targets;n||(n=this.targetBuffer,n.length=1,n[0]=this.context.scene);let o=s.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),o||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),o=this.defaultRaycastOptions.results),s.layerMask!==void 0?s.layerMask instanceof so?i.layers.mask=s.layerMask.mask:i.layers.mask=s.layerMask:(i.layers.enableAll(),i.layers.disable(2)),ki&&console.time("raycast"),o.length=0,vg._raycasting++,this.intersect(this.raycaster,n,o,s),o.sort((l,c)=>l.distance-c.distance);const r=s.ignore;return r!==void 0&&r.length>0&&(o=o.filter(l=>!r.includes(l.object))),vg._raycasting--,ki&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",o!=null&&o.length?[...o]:"nothing"),performance.mark("raycast.end"),performance.measure("raycast","raycast.start","raycast.end")),o}intersect(s,t,i,n){var o,r,l;for(const c of t){if(!c||c.visible===!1||q.isGizmo(c)||n.lineThreshold!==void 0&&n.lineThreshold<0&&c instanceof Gl)continue;let h=!0;const d=c,u=d.geometry;if(n.testObject){const p=(o=n.testObject)==null?void 0:o.call(n,c);if(p===!1)continue;p==="continue in children"&&(h=!1)}if(h&&(u&&Hb(u)||(h=!1)),h){const p=sv(c);p&&(d.geometry=p);const g=i.length;let y=!0;if(n.precise===!1&&(y=!1),y||(y=((l=(r=u.getAttribute("position"))==null?void 0:r.array)==null?void 0:l.length)<64),d instanceof va&&(y=!1),!y&&c2(d,s,i)||(n.useAcceleratedRaycast!==!1?Id.runMeshBVHRaycast(s,d,i,this.context):s.intersectObject(d,!1,i)),ki&&i.length!=g){const f=i[i.length-1],v=p?8969557:7798784;q.DrawWireSphere(f.point,.1,v,1,!1),q.DrawWireMesh({mesh:c,depthTest:!1,duration:.2,color:v})}d.geometry=u}n.recursive!==!1&&this.intersect(s,c.children,i,n)}return i}intersectSphere(s,t,i,n,o,r,l,c){let h=s&&s.isMesh&&s.layers.test(n)&&!q.isGizmo(s);h&&(h=s.visible),h&&(h=!(s instanceof Gl)),h&&(h=!(s instanceof va));const d=s,u=d.geometry;if(h&&c){const p=c(s);if(p===!1)return;p==="continue in children"&&(h=!1)}if(u&&Hb(u)||(h=!1),h){if(l){const p=this.sphere;p.center.copy(t),p.radius=i;const g=o.length;if(Id.runMeshBVHRaycast(this.sphere,d,o,this.context),g!=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),g=this.sphere;if(g.center.copy(t),g.radius=i,g.intersectsBox(p)){const y=te(s),f=y.distanceTo(g.center),v=new yg(s,f,y);if(o.push(v),!r)return}}}if(s.children)for(const p of s.children){const g=o.length;if(this.intersectSphere(p,t,i,n,o,r,l,c),g!=o.length&&!r)return}}};let Ed=vg;a(Ed,"_raycasting",0);function Hb(s){return!(s.index&&s.index.array.length<3)}const pr=new od,Ad=new nr,l2=new Wy;function c2(s,t,i){const n=s._computeIntersections;if(!n)return!1;let o=s["_computeIntersections:Needle"];return o||(o=s["_computeIntersections:Needle"]=function(r,l,c){const h=this,d=h.geometry.boundingSphere;if(d){if(h instanceof va){Ad.setFromNormalAndCoplanarPoint(G(0,1,0),G(0,-h.position.y,0)),Ad.applyMatrix4(h.matrixWorld,l2);const p=r.ray.intersectPlane(Ad,G());if(p){pr.copy(d),pr.applyMatrix4(h.matrixWorld);const g=G(p).sub(r.ray.origin).length(),y=pr.radius*.5;g<y&&l.push({distance:g,point:p,object:h,normal:Ad.normal.clone()})}return}pr.copy(d),pr.applyMatrix4(h.matrixWorld);const u=r.ray.intersectSphere(pr,G());if(u){const p=G(u).sub(r.ray.origin),g=p.length();if(g>pr.radius){const y=p.clone().normalize();l.push({distance:g,point:u,object:h,normal:y})}}}}),s._computeIntersections=o,t.intersectObject(s,!1,i),s._computeIntersections=n,!0}var Id;(s=>{function t(w,_,S,R){var M,T,L;if(!_.geometry||!_.geometry.hasAttribute("position"))return!1;const D=_.geometry;if(_!=null&&_.isSkinnedMesh){const U=_,B=U.bvhNeedsUpdate;if(!U.staticGenerator)c(),r&&(U.staticGenerator=new r(_),U.staticGenerator.applyWorldTransforms=!1,U.staticGeometry=U.staticGenerator.generate(),D.boundsTree=l?.call(U.staticGeometry),U.staticGeometryLastUpdate=performance.now()+Math.random()*200,U.autoUpdateMeshBVH===void 0&&(U.autoUpdateMeshBVH=!1));else if(D.boundsTree&&(U.autoUpdateMeshBVH===!0||B===!0)){const Q=performance.now(),$=Q-U.staticGeometryLastUpdate;(B||$>100)&&(U.bvhNeedsUpdate=!1,U.staticGeometryLastUpdate=Q,(M=U.staticGenerator)==null||M.generate(U.staticGeometry),D.boundsTree.refit())}}else if(!D.boundsTree){d||b();let U=!0;if((R.xr||D[y]===!1||(T=D.getAttribute("position"))!=null&&T.isInterleavedBufferAttribute||D.index&&(L=D.index)!=null&&L.isInterleavedBufferAttribute)&&(U=!1),U&&p){if(D[g]===void 0){let B=null;if(v.length>0){const Q=v.shift();Q&&!Q.running&&(B=Q)}if(!B&&f.length<3&&(B=new p,f.push(B)),B!=null&&!B.running){const Q=_.name;ki&&console.log("<<<< worker start",Q,B),D[g]="queued",performance.mark("bvh.create.start");const $=D.clone();try{B.generate($).then(E=>{D[g]="done",D.boundsTree=E}).catch(E=>{D[g]="failed - "+E?.message,D[y]=!1,ki&&console.error("Failed to generate mesh bvh on worker",E)}).finally(()=>{ki&&console.log(">>>>> worker done",Q,{hasBoundsTre:D.boundsTree!=null}),v.push(B),$.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch(E){console.error("Failed to generate mesh bvh on worker",E)}}else ki&&console.warn("No worker available")}}else(!u||!U)&&(c(),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(w instanceof rd){const U=w,B=_.raycast;D.boundsTree?(c(),n&&(_.acceleratedRaycast||(_.acceleratedRaycast=n.bind(_),ki&&console.debug(`Physics: bind acceleratedRaycast fn to "${_.name}"`)),_.raycast=_.acceleratedRaycast)):ki&&console.warn("No bounds tree found for mesh",_.name,{workerTask:D[g],hasAcceleratedRaycast:n!=null});const Q=U.firstHitOnly;return U.firstHitOnly=!1,U.intersectObject(_,!1,S),U.firstHitOnly=Q,_.raycast=B,!0}else if(w instanceof od){const U=D.boundsTree;if(U){const B=w;if(h.copy(_.matrixWorld).invert(),B.applyMatrix4(h),U.intersectsSphere(B)){const Q=te(_),$=Q.distanceTo(B.center),E=new yg(_,$,Q);S.push(E)}}return!0}return!1}s.runMeshBVHRaycast=t;let i=!1,n=null,o=null,r=null,l=null;function c(){i||(i=!0,import("./vendor.light.min.js").then(w=>w.k).then(w=>{n=w.acceleratedRaycast,o=w.MeshBVH,r=w.StaticGeometryGenerator,l=w.computeBoundsTree}).catch(w=>{(ki||F())&&console.error("Failed to load BVH library...",w.message)}))}const h=new ne;let d=!1,u=!1,p=null;const g=Symbol("Needle:MeshBVH-Worker"),y=Symbol("Needle:MeshBVH-CanUseWorker"),f=[],v=[];function b(){d=!0,u=!0,Promise.resolve().then(()=>Zj).then(w=>{p=w.GenerateMeshBVHWorker}).catch(w=>{(ki||F())&&console.warn("Failed to setup mesh bvh worker")}).finally(()=>{u=!1})}})(Id||(Id={}));const $b=Symbol("gltf-loader-internal-usage-tracker"),h2=C("debugusers"),jd=class{constructor(s){a(this,"parser"),a(this,"_getDependency"),a(this,"_loadingId"),a(this,"_loadedObjects",new Set),this.parser=s,this._getDependency=this.parser.getDependency,this._loadingId=Date.now().toString()}get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(s){return jd._loadingProcesses>0}beforeRoot(){jd._loadingProcesses++;const s=this,t=this._getDependency;return this.parser.getDependency=function(i,n){const o=t.call(this,i,n);return o.then(r=>(r&&(s._loadedObjects.add(r),r[$b]=s._loadingId),r)),o},null}afterRoot(s){jd._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[$b],t instanceof I&&(t.parent||t instanceof Y&&setTimeout(()=>{h2&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}};let bg=jd;a(bg,"_loadingProcesses",0);class qb{constructor(){window.addEventListener("unhandledrejection",t=>{var i;if(t.defaultPrevented)return;const n=(i=t?.reason)==null?void 0:i.path;if(n){const o=n[0];o&&o.tagName==="IMG"&&(console.warn(`Could not load image:
155
155
  `+o.src),t.preventDefault())}})}}const Ld=C("trackresources");function Gb(){return Ld==="dispose"}let mr=!0;Ld===0&&(mr=!1);function d2(s){mr=s}function Xb(){return mr}const Qb=Symbol("disposable");function _g(s,t){s&&(s[Qb]=t,gr&&console.warn("Set disposable",t,s))}const Yb=Symbol("disposed");function u2(s){return s[Yb]===!0}function Ee(s){var t;if(s){if(s[Qb]===!1){gr&&console.warn("Object is marked as not disposable",s);return}if(s[Yb]=!0,s instanceof Vi)Ee(s.environment),Ee(s.background),Ee(s.customDepthMaterial),Ee(s.customDistanceMaterial);else if(s instanceof fn)Ee(s.geometry),Ee(s.material),Ee(s.skeleton),Ee(s.bindMatrix),Ee(s.bindMatrixInverse),Ee(s.customDepthMaterial),Ee(s.customDistanceMaterial),s.geometry=null,s.material=null,s.visible=!1;else if(s instanceof Y)Ee(s.geometry),Ee(s.material),Ee(s.customDepthMaterial),Ee(s.customDistanceMaterial),s.geometry=null,s.material=null,s.visible=!1;else if(s instanceof gn){Ma(s);for(const i of Object.keys(s.attributes)){const n=s.attributes[i];Ee(n)}}else if(s instanceof ft||s instanceof Gy)gr&&console.warn("BufferAttribute dispose not supported",s.count);else if(s instanceof Array)for(const i of s)i instanceof ke&&Ee(i);else if(s instanceof ke){Ma(s);for(const n of Object.keys(s)){const o=s[n];o instanceof Le&&(Ee(o),s[n]=null)}const i=s.uniforms;if(i)for(const n of Object.keys(i)){const o=i[n];o instanceof Le?(Ee(o),i[n]=null):o instanceof io&&(Ee(o.value),o.value=null)}}else s instanceof Le?(Ma(s),Ma(s.source),((t=s.source)==null?void 0:t.data)instanceof ImageBitmap&&Ma(s.source.data)):s instanceof SS?(Ma(s.boneTexture),s.boneTexture=null):s instanceof CS||!(s instanceof I)&&gr&&console.warn("Unknown object type",s)}}function Ma(s){s&&((gr||Gb()||Ld)&&console.warn("\u{1F9E8} FREE",s),s instanceof ImageBitmap?s.close():s instanceof OS?s.data=null:s.dispose())}function Zb(s){(s instanceof Y||s instanceof fn)&&(s.material=null,s.geometry=null)}const p2=new Set;function wg(s,t,i=null,n){if(n||(n=p2,n.clear()),!s)return n;const o=s[gc];if(o)for(const r of o)n.has(r)||i?.call(null,r)!==!1&&(n.add(r),t&&wg(r,!0,i,n));return n}function m2(s){return s[fc]}const gr=C("debugresourceusers")||C("debugmemory"),gc=Symbol("needle-resource-users"),fc=Symbol("needle-resource-users-count");function Xt(s,t){Sd(s,t,function(i,n){mr&&!Ed.raycasting&&(Dd(gc,this,i,!1),Dd(gc,this,n,!0))})}mr&&(Xt(Y.prototype,"material"),Xt(Y.prototype,"geometry"),Xt(ke.prototype,"map"),Xt(ke.prototype,"bumpMap"),Xt(ke.prototype,"alphaMap"),Xt(ke.prototype,"normalMap"),Xt(ke.prototype,"displacementMap"),Xt(ke.prototype,"roughnessMap"),Xt(ke.prototype,"metalnessMap"),Xt(ke.prototype,"emissiveMap"),Xt(ke.prototype,"specularMap"),Xt(ke.prototype,"envMap"),Xt(ke.prototype,"lightMap"),Xt(ke.prototype,"aoMap"),Xt(ke.prototype,"gradientMap"));function g2(s){if(mr===!1)return;const t=s[gc];if(t)for(const i of t)Dd(gc,i,s,!1)}mr&&Sd(ke.prototype,"dispose",function(){g2(this)});let xg=0;function Dd(s,t,i,n){if(xg>0)return;if(Array.isArray(i)){for(const r of i)Dd(s,t,r,n);return}if(!i)return;let o=i[s];if(o||(o=new Set),n){if(t&&!o.has(t)){o.add(t);let r=i[fc]||0;r+=1,i[fc]=r,gr&&console.warn(`\u{1F7E2} Added user of "${i.type}"`,t,i,r,"users:",o)}}else if(t&&o.has(t)){o.delete(t);let r=i[fc]||0;r>0&&(r-=1,i[fc]=r),gr&&console.warn(`\u{1F534} Removed user of "${i.type}"`,t,i,r,"users:",o),r<=0&&(bg.isLoading(i)||(Ld&&console.warn(`\u{1F534} Removed all user of "${i.type}"`,i),Gb()&&Ee(i)))}i[s]=o}try{Sd(sr.prototype,"render",function(){xg++},function(){xg--})}catch(s){console.warn("Could not wrap WebGLRenderer.render",s)}const Kb=C("debugcomponentevents");class yc{static addComponentLifecylceEventListener(t,i){this.eventListeners.has(t)&&this.eventListeners.set(t,[]);let n=this.eventListeners.get(t);n||(n=[]),n.push(i),this.eventListeners.set(t,n),Kb&&console.log("Added event listener for "+t,this.eventListeners)}static removeComponentLifecylceEventListener(t,i){const n=this.eventListeners.get(t);if(!n)return;const o=n.indexOf(i);o<0||n.splice(o,1)}static dispatchComponentLifecycleEvent(t,i){const n=this.eventListeners.get(t);if(Kb&&console.log("Dispatching event "+t,n),!!n)for(const o of n)o(i)}}a(yc,"eventListeners",new Map);const vc=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),Jb=Symbol("isUsingInstancing"),e_=Symbol("instancingRenderer"),bc=Symbol("instancingAutoUpdateBounds");class as{static isUsingInstancing(t){return t[Jb]===!0}static getRenderer(t){return t[e_]||null}setAutoUpdateBounds(t,i){const n=as.getRenderer(t);n&&(n[bc]=i)}static markDirty(t,i=!0){if(t&&(this.isUsingInstancing(t)&&(t[vc]=!0,t.matrixWorldNeedsUpdate=!0),i))for(const n of t.children)as.markDirty(n,!0)}}function Ra(s,t){try{t?s(t):s()}catch(i){return console.error(i),!1}return!0}const Sg=C("debugnewscripts"),f2=C("debughierarchy"),Fe=[];function y2(){return Fe.length>0}function Bd(s){if(Sg&&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 t of s.new_scripts_pre_setup_callbacks)t&&t();s.new_scripts_pre_setup_callbacks.length=0}if(!(s.new_scripts.length<=0)){Fe.length=0,s.new_scripts.length>0&&Fe.push(...s.new_scripts),s.new_scripts.length=0;for(let t=0;t<Fe.length;t++)try{const i=Fe[t];if(i.isComponent!==!0){(F()||Sg)&&console.error(`Registered script is not a Needle Engine component.
156
156
  The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
157
157
  `,i),Fe.splice(t,1),t--;continue}if(i.destroyed)continue;if(!i.gameObject){console.warn(`Component can not be initialized: no GameObject assigned.
@@ -176,7 +176,7 @@ Please use the component type instead. This may keep working in local developmen
176
176
 
177
177
  You can import other modules your main module to get access to types
178
178
  or if you use npmdefs you can make types available globally using globalThis:
179
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis`,t))),O_()&&console.log("[onGetComponent] FIND",t),t==null))return null;for(let o=0;o<s.userData.components.length;o++){const r=s.userData.components[o];let l=Object.getPrototypeOf(r);for(;l;){if(l===t.prototype)if(O_()&&console.log("[onGetComponent] MATCH BY PROTOYPE",l),i)i.push(r);else return r;l=Object.getPrototypeOf(l)}}return i||null}function yr(s,t){const i=R_(s,t);return i?Array.isArray(i)?i[0]:i:null}function Cc(s,t,i,n=!0){return i||(i=[]),n&&(i.length=0),R_(s,t,i),i}function Oc(s,t,i){var n;const o=yr(s,t);if(i===!1&&o?.enabled===!1)return null;if(o)return o;for(let r=0;r<((n=s?.children)==null?void 0:n.length);r++){const l=Oc(s.children[r],t);if(l)return l}return null}function Aa(s,t,i,n=!0){var o;i||(i=[]),n&&(i.length=0),Cc(s,t,i,!1);for(let r=0;r<((o=s?.children)==null?void 0:o.length);r++)Aa(s.children[r],t,i,!1);return i}function Pc(s,t){if(!s)return null;if(Array.isArray(s)){for(let n=0;n<s.length;n++){const o=q2(s[n]),r=Pc(o,t);if(r)return r}return null}return yr(s,t)||(s.parent?Pc(s.parent,t):null)}function Hd(s,t,i,n=!0){return i||(i=[]),n&&(i.length=0),s?(Cc(s,t,i,!1),s.parent?Hd(s.parent,t,i,!1):i):i}function kc(s,t=void 0,i=!0){if(!s)return null;if(!t&&(t=ee.Current,!t))return console.error("Can not search object without any needle context or scene!!!"),null;let n=t;if(n.isScene||(n=t?.scene),!n)return null;for(const o in n.children){const r=n.children[o];if(i===!1&&r[_n]===!1)continue;const l=Oc(r,s);if(l)return l}return null}function T_(s,t,i=void 0){if(!s)return t??[];if(t||(t=[]),t.length=0,!i&&(i=ee.Current,!i))return console.error("Can not search object without any needle context or scene!!!"),t;"scene"in i&&(i=i.scene);const n=i;if(!n)return t;for(const o in n.children){const r=n.children[o];Aa(r,s,t,!1)}return t}function $d(s){s&&s.isObject3D===!0&&S_(s,I)}I.prototype.SetActive=function(s){this.visible=s},I.prototype.setActive=function(s){this.visible=s},I.prototype.destroy=function(){Ri(this)},I.prototype.addComponent=function(s,t){return Mi(this,s,t)},I.prototype.addNewComponent=function(s,t){return Mi(this,s,t)},I.prototype.removeComponent=function(s){return Ug(this,s)},I.prototype.getOrAddComponent=function(s,t){return Sc(this,s,t)},I.prototype.getComponent=function(s){return yr(this,s)},I.prototype.getComponents=function(s,t){return Cc(this,s,t)},I.prototype.getComponentInChildren=function(s){return Oc(this,s)},I.prototype.getComponentsInChildren=function(s,t){return Aa(this,s,t)},I.prototype.getComponentInParent=function(s){return Pc(this,s)},I.prototype.getComponentsInParent=function(s,t){return Hd(this,s,t)},Object.getOwnPropertyDescriptor(I.prototype,"activeSelf")||Object.defineProperty(I.prototype,"activeSelf",{get:function(){return Ia(this)},set:function(s){Mc(this,s)}}),Object.getOwnPropertyDescriptor(I.prototype,"worldPosition")||Object.defineProperty(I.prototype,"worldPosition",{get:function(){return this instanceof nv?te(this.object):te(this)},set:function(s){ht(this,s)}}),Object.getOwnPropertyDescriptor(I.prototype,"worldQuaternion")||Object.defineProperty(I.prototype,"worldQuaternion",{get:function(){return this instanceof nv?Ce(this.object):Ce(this)},set:function(s){Hi(this,s)}}),Object.getOwnPropertyDescriptor(I.prototype,"worldRotation")||Object.defineProperty(I.prototype,"worldRotation",{get:function(){return ic(this)},set:function(s){Vm(this,s)}}),Object.getOwnPropertyDescriptor(I.prototype,"worldScale")||Object.defineProperty(I.prototype,"worldScale",{get:function(){return Ye(this)},set:function(s){wa(this,s)}}),Object.getOwnPropertyDescriptor(I.prototype,"worldForward")||Object.defineProperty(I.prototype,"worldForward",{get:function(){return G().set(0,0,1).applyQuaternion(Ce(this))}}),Object.getOwnPropertyDescriptor(I.prototype,"worldRight")||Object.defineProperty(I.prototype,"worldRight",{get:function(){return G().set(1,0,0).applyQuaternion(Ce(this))}}),Object.getOwnPropertyDescriptor(I.prototype,"worldUp")||Object.defineProperty(I.prototype,"worldUp",{get:function(){return G().set(0,1,0).applyQuaternion(Ce(this))}}),C_(I);class xe extends ae{constructor(t,i,n,o){var r=(...l)=>{super(...l),a(this,"alpha",1)};i!=null&&n!=null?(r(t,i,n),this.alpha=o):(r(t),this.alpha=1)}get isRGBAColor(){return!0}set a(t){this.alpha=t}get a(){return this.alpha}clone(){const t=super.clone();return t.alpha=this.alpha,t}copy(t){return this.r=t.r,this.g=t.g,this.b=t.b,"alpha"in t&&typeof t.alpha=="number"?this.alpha=t.alpha:typeof t.a=="number"&&(this.alpha=t.a),this}lerp(t,i){const n=t;return n.alpha!=null&&(this.alpha=W.lerp(this.alpha,n.alpha,i)),super.lerp(t,i)}lerpColors(t,i,n){const o=t,r=i;return o.alpha!=null&&r.alpha!=null&&(this.alpha=W.lerp(o.alpha,r.alpha,n)),super.lerpColors(t,i,n)}multiply(t){const i=t;return i.alpha!=null&&(this.alpha=this.alpha*i.alpha),super.multiply(t)}fromArray(t,i=0){return this.alpha=t[i+3],super.fromArray(t,i)}}const qd=C("debuggetcomponent"),Gd=C("debuginstantiate");class Ds{constructor(){a(this,"idProvider"),a(this,"parent"),a(this,"keepWorldPosition"),a(this,"position"),a(this,"rotation"),a(this,"scale"),a(this,"visible"),a(this,"context"),a(this,"components")}clone(){var t,i,n;const o=new Ds;return o.idProvider=this.idProvider,o.parent=this.parent,o.keepWorldPosition=this.keepWorldPosition,o.position=(t=this.position)==null?void 0:t.clone(),o.rotation=(i=this.rotation)==null?void 0:i.clone(),o.scale=(n=this.scale)==null?void 0:n.clone(),o.visible=this.visible,o.context=this.context,o.components=this.components,o}cloneAssign(t){var i,n,o;this.idProvider=t.idProvider,this.parent=t.parent,this.keepWorldPosition=t.keepWorldPosition,this.position=(i=t.position)==null?void 0:i.clone(),this.rotation=(n=t.rotation)==null?void 0:n.clone(),this.scale=(o=t.scale)==null?void 0:o.clone(),this.visible=t.visible,this.context=t.context,this.components=t.components}}function Ia(s){return s.visible}function Mc(s,t){return typeof t=="number"&&(t=t>.5),s.visible=t,s.visible}function E_(s){return s[_n]||Xd(s)}function A_(s,t){s[Jb]=t}function Xd(s){return as.isUsingInstancing(s)}function Ng(s,t){return ba(s,t,!0,!0)}const I_=Symbol("isDestroyed");function vr(s){return s[I_]}function j_(s,t){s[I_]=t}const Wg=Symbol("isDontDestroy");function ja(s,t=!0){s[Wg]=t}const Qd=[],Yd=[];function Ri(s,t=!0,i=!1){Qd.length=0,Yd.length=0,Vg(s,t,!0);for(const n of Qd)n.gameObject=null,n.context=null;for(const n of Yd)j_(n,!0),i&&Ee(n),Zb(n);Yd.length=0,Qd.length=0}function Vg(s,t=!0,i=!0){var n;if(s==null)return;const o=s;if(o.isComponent){if(o[Wg])return;Qd.push(o);const c=o.gameObject;o.__internalDisable(),o.__internalDestroy(),o.gameObject=c;return}if(s[Wg])return;const r=s;qd&&console.log(r),Yd.push(r);const l=(n=r.userData)==null?void 0:n.components;if(l!=null&&Array.isArray(l)){let c=l.length;for(let h=0;h<l.length;h++){const d=l[h];Vg(d,t,!1),l.length<c&&(c=l.length,h--)}}if(t&&r.children)for(const c of r.children)Vg(c,t,!1);i&&r.removeFromParent()}function br(s,t,i=!0){return L_(s,t,i)}function*Zd(s,t,i=!1,n=999,o=0){if(s!=null&&s.userData.components&&!(o>n)){for(const r of s.userData.components)t&&r?.isComponent===!0&&r instanceof t?yield r:yield r;if(i===!0)for(const r of s.children)yield*Zd(r,t,!0,n,o+1)}}function L_(s,t,i,n=0){var o;if(s){if(s.isObject3D,n>1e3){console.warn("Failed to iterate components: too many levels");return}if((o=s.userData)!=null&&o.components)for(let r=0;r<s.userData.components.length;r++){const l=s.userData.components[r];if(l?.isComponent===!0){const c=t(l);if(c!==void 0)return c}}if(i&&s.children){const r=n+1;for(let l=0;l<s.children.length;l++){const c=s.children[l];if(!c)continue;const h=L_(c,t,i,r);if(h!==void 0)return h}}}}function La(s,t){if("isAssetReference"in s)return s.instantiate(t??void 0);let i=null;t!=null&&(t.x!==void 0?(i=new Ds,i.position=t):i=t);let n=ee.Current;i!=null&&i.context&&(n=i.context),qd&&n.alias&&console.log("context",n.alias),i&&!i.idProvider&&(i.idProvider=new Dt(Date.now()));const o=[],r={},l={},c=D_(n,s,i,o,r,l);c&&(X2(r),G2(l,r)),qd&&(_d(s,!0),_d(c,!0));const h={};if(i?.components!==!1){for(const d in o){const u=o[d],p=u.guid;i&&i.idProvider&&(u.guid=i.idProvider.generateUUID(),h[p]=u.guid,qd&&console.log(u.name,u.guid)),pu(u,n),u.__internalNewInstanceCreated&&u.__internalNewInstanceCreated()}for(const d in o){const u=o[d];u.resolveGuids&&u.resolveGuids(h),u.enabled!==!1&&(u.enabled=!0)}Bd(n)}return c}function D_(s,t,i,n,o,r){var l;if(!t)return null;const c=t.userData;t.userData={};const h=t.children;t.children=[];const d=t.clone(!1);if($d(d),t.userData=c,t.children=h,o[t.uuid]={original:t,clone:d},Gd&&console.log("ADD",t,d),t.type==="SkinnedMesh"&&(r[t.uuid]={original:t,clone:d}),i?.visible!==void 0&&(d.visible=i.visible),i!=null&&i.idProvider){d.uuid=i.idProvider.generateUUID();const p=d;p&&(p.guid=d.uuid)}t.animations&&t.animations.length>0&&(d.animations=[...t.animations]);const u=t.parent;if(u&&u.add(d),i!=null&&i.position?ht(d,i.position):d.position.copy(t.position),i!=null&&i.rotation?Hi(d,i.rotation):d.quaternion.copy(t.quaternion),i!=null&&i.scale?d.scale.copy(i.scale):d.scale.copy(t.scale),i!=null&&i.parent&&i.parent!=="scene"){let p=null;if(typeof i.parent=="string"?p=ba(i.parent,s.scene,!0):p=i.parent,p){const g=i.keepWorldPosition===!0?p.attach:p.add;g?g.call(p,d):console.error("Invalid parent object",p,"received when instantiating:",t)}else console.warn("could not find parent:",i.parent)}for(const[p,g]of Object.entries(t.userData))p!=="components"&&(d.userData[p]=g);if((l=t.userData)!=null&&l.components){const p=t.userData.components,g=[];d.userData.components=g;for(let y=0;y<p.length;y++){const f=p[y],v=new f.constructor;Ea(v,f),f[hc]!==void 0&&(v[hc]=f[hc]),g.push(v),v.gameObject=d,n.push(v),o[f.guid]={original:f,clone:v},yc.dispatchComponentLifecycleEvent("component-added",v)}}i&&(i.position=void 0,i.rotation=void 0,i.scale=void 0,i.parent=void 0);for(const p in t.children){const g=t.children[p],y=D_(s,g,i,n,o,r);y&&d.add(y)}return d}function G2(s,t){for(const i in s){const n=s[i],o=n.original,r=o.skeleton,l=n.clone;if(!r){console.warn("Skinned mesh has no skeleton?",n);continue}const c=r.bones,h=l.skeleton.clone();l.skeleton=h,l.bindMatrix.clone().copy(o.bindMatrix),l.bindMatrixInverse.copy(o.bindMatrixInverse);const d=[];h.bones=d;for(let u=0;u<c.length;u++){const p=c[u],g=t[p.uuid].clone;d.push(g)}}for(const i in s){const n=s[i].clone;n.skeleton.update(),n.bind(n.skeleton,n.bindMatrix),n.updateMatrixWorld(!0)}}function X2(s){var t;for(const i in s){const n=s[i].clone;if(n!=null&&n.isObject3D&&(t=n?.userData)!=null&&t.components)for(let o=0;o<n.userData.components.length;o++){const r=n.userData.components[o],l=Object.entries(r);for(const[c,h]of l)if(Array.isArray(h)){const d=[];r[c]=d;for(let u=0;u<h.length;u++){const p=h[u];if(typeof p!="object"){d.push(p);continue}const g=B_(r,c,p,s);g!==void 0?d.push(g):d.push(p)}}else if(typeof h=="object"){const d=B_(r,c,h,s);d!==void 0&&(r[c]=d)}}}}function B_(s,t,i,n){var o,r;if(i!=null)if(i.isComponent===!0){const l=i.gameObject;if(l){const c=l.uuid,h=(o=n[c])==null?void 0:o.clone;if(!h){Gd&&console.log("reference did not change",t,s,i);return}const d=l.userData.components.indexOf(i);if(d>=0&&h.isObject3D)return Gd&&console.log(t,c),h.userData.components[d];console.warn("could not find component",t,i)}}else if(i.isObject3D===!0){if(t==="gameObject")return;const l=i;if(l){const c=l.uuid,h=(r=n[c])==null?void 0:r.clone;if(h)return Gd&&console.log(t,"old",i,"new",h),h}}else{if(i.isVector4||i.isVector3||i.isVector2||i.isQuaternion||i.isEuler||i.isColor===!0)return i.clone();if(i.isEventList===!0)return i.__internalOnInstantiate(n)}}var _r;(s=>{s.baseUrl="https://networking.needle.tools";function t(h){return dv(new Uint8Array(h))}s.hashMD5=t;function i(h){const d=dv(new Uint8Array(h),{encoding:"binary",asBytes:!0});return btoa(String.fromCharCode(...d))}s.hashMD5_Base64=i;function n(h){const d=new Uint8Array(h);return crypto.subtle.digest("SHA-256",d).then(u=>btoa(String.fromCharCode(...new Uint8Array(u))))}s.hashSha256=n;function o(h){const d=h.filesize/1024/1024;return Cs()?d<50:d<5}s.canUpload=o;async function r(h,d){var u;const p=s.baseUrl;if(p){if(!h.name)return console.error("Upload: file name is missing"),null}else return console.error("Blob storage base url is not set"),null;let g=null;h instanceof File?g=await h.arrayBuffer():g=h.data;const y=g.byteLength,f=y/1024/1024;if(f>50)return d?.silent!==!0&&we(`File (${f.toFixed(1)}MB) is too large for uploading (see console for details)`),console.warn(`Your file is too large for uploading (${f.toFixed(1)}MB). Max allowed size is 50MB`),null;if(!Cs()&&f>5)return d?.silent!==!0&&we('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 (${f.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 (${f.toFixed(1)}MB). Min size is 1 byte`),null;const v=i(g),b={filename:h.name,"Content-Md5":v,"Content-Type":h.type||"application/octet-stream",FileSize:y.toString(),"Content-Disposition":`attachment; filename="${h.name}"`,"x-amz-server-side-encryption":"AES256"},w=await fetch(p+"/api/needle/blob",{method:"POST",headers:b,signal:d?.abort}).then(_=>_.json()).catch(_=>(console.error(_),null));if(w==null)return console.warn("Upload failed..."),null;if("error"in w)return console.error(w.error),null;if("upload"in w&&w.upload){let _=function(M){var T;return(T=d?.onProgress)==null||T.call(null,{progress01:0,state:"inprogress"}),fetch(M,{method:"PUT",headers:b,body:g,signal:d?.abort}).then(j=>{var L;return(L=d?.onProgress)==null||L.call(null,{progress01:1,state:"finished"}),j}).catch(j=>j)};console.debug("Uploading file",w.upload);let S=!1,R=null;for(let M=0;M<3;M++)try{if(S)break;if((u=d?.abort)!=null&&u.aborted)return console.debug("Aborted upload"),null;const T=await _(w.upload);T instanceof Error?(R=T,await fs(1e3*M)):T.ok&&(console.debug("File uploaded successfully"),S=!0)}catch(T){console.error(T)}if(!S)return console.error(R?.message||"Failed to upload file"),null}if("download"in w){const _=p+w.download;return console.debug("File found in blob storage",_),{key:w.key,success:!0,download_url:_}}return null}s.upload=r;function l(h){return`${s.baseUrl}/api/needle/blob/${h}`}s.getBlobUrlForKey=l;async function c(h,d){var u;const p=await fetch(h),g=(u=p.body)==null?void 0:u.getReader(),y=p.headers.get("Content-Length"),f=y?parseInt(y):0;if(!g)return null;let v=0;const b=[];for(;;){const{done:S,value:R}=await g.read();if(R&&(b.push(R),v+=R.length,d?.call(null,new ProgressEvent("progress",{loaded:v,total:f}))),S)break}const w=new Uint8Array(v);let _=0;for(const S of b)w.set(S,_),_+=S.length;return w}s.download=c})(_r||(_r={}));const go=C("debugaddressables");class F_{constructor(t){a(this,"_context"),a(this,"_assetReferences",{}),a(this,"preUpdate",()=>{}),this._context=t,this._context.pre_update_callbacks.push(this.preUpdate)}dispose(){const t=this._context.pre_update_callbacks.indexOf(this.preUpdate);t>=0&&this._context.pre_update_callbacks.splice(t,1);for(const i in this._assetReferences){const n=this._assetReferences[i];n?.unload()}this._assetReferences={}}findAssetReference(t){return this._assetReferences[t]||null}registerAssetReference(t){return t.url&&(this._assetReferences[t.url]?console.warn("Asset reference already registered",t):this._assetReferences[t.url]=t),t}unregisterAssetReference(t){t.url&&delete this._assetReferences[t.url]}}const Hg=Symbol("assetReference"),Da=class{constructor(s,t,i=null){a(this,"_loading"),a(this,"_asset"),a(this,"_glbRoot"),a(this,"_url"),a(this,"_urlName"),a(this,"_progressListeners",[]),a(this,"_hash"),a(this,"_hashedUri"),a(this,"_isLoadingRawBinary",!1),a(this,"_rawBinary"),this._url=s;const n=s.lastIndexOf("/");if(n>=0){this._urlName=s.substring(n+1);const o=this._urlName.lastIndexOf(".");o>=0&&(this._urlName=this._urlName.substring(0,o))}else this._urlName=s;this._hash=t,s.includes("?v=")?this._hashedUri=s:this._hashedUri=t?s+"?v="+t:s,i!==null&&(this.asset=i),d_(this._url,this.onResolvePrefab.bind(this))}static getOrCreateFromUrl(s,t){if(!t&&(t=ee.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(s);if(n)return n;const o=new Da(s,t.hash);return i.registerAssetReference(o),o}static getOrCreate(s,t,i){if(typeof s=="string"){if(!i&&(i=ee.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=s.context,s=s.sourceId;const n=lo(s,t);go&&console.log("GetOrCreate Addressable from",s,t,"FinalPath=",n);const o=i.addressables,r=o.findAssetReference(n);if(r)return r;const l=new Da(n,i.hash);return o.registerAssetReference(l),l}get isAssetReference(){return!0}get asset(){return this._glbRoot??this._asset}set asset(s){this._asset=s}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("/"))}get rawAsset(){return this._asset}async onResolvePrefab(s){return s===this.url&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0||vr(this.asset)===!0}isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(go&&console.log("Unload",this.asset),"scene"in this.asset&&this.asset.scene&&Ri(this.asset.scene,!0,!0),Ri(this.asset,!0,!0)),this.asset=null,this._rawBinary=void 0,this._glbRoot=null,this._loading=void 0,ee.Current&&ee.Current.addressables.unregisterAssetReference(this)}async preload(){if(!this.mustLoad||this._isLoadingRawBinary)return null;if(this._rawBinary!==void 0)return this._rawBinary;this._isLoadingRawBinary=!0,go&&console.log("Preload",this._hashedUri);const s=await _r.download(this._hashedUri,t=>{this.raiseProgressEvent(t)});return this._rawBinary=s?.buffer??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(s){if(go&&console.log("loadAssetAsync",this.url),!this.mustLoad)return this.asset;if(s&&this._progressListeners.push(s),this._loading!==void 0)return this._loading.then(n=>this.asset);const t=ee.Current;if(this._rawBinary){if(!(this._rawBinary instanceof ArrayBuffer))return console.error("Invalid raw binary data",this._rawBinary),null;this._loading=gs().parseSync(t,this._rawBinary,this.url,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))}else go&&console.log("Load async",this.url),this._loading=gs().loadSync(t,this._hashedUri,this.url,null,n=>{this.raiseProgressEvent(n)});const i=await this._loading;return this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(i),this._loading=void 0,i?(i[Hg]=this,this._glbRoot&&(this._glbRoot[Hg]=this),this.asset&&(this.asset[Hg]=this),Bd(t),i.scene!==void 0&&(this.asset=i),this.asset):null}async instantiate(s){return this.onInstantiate(s,!1)}async instantiateSynced(s,t=!0){return this.onInstantiate(s,!0,t)}beginListenDownload(s){this._progressListeners.indexOf(s)<0&&this._progressListeners.push(s)}endListenDownload(s){const t=this._progressListeners.indexOf(s);t>=0&&this._progressListeners.splice(t,1)}raiseProgressEvent(s){for(const t of this._progressListeners)t(this,s)}async onInstantiate(s,t=!1,i){const n=ee.Current,o=new Ds;if(s instanceof I?o.parent=s:s&&(Object.assign(o,s),o.cloneAssign(s)),o.parent||(o.parent=n.scene),this.mustLoad&&await this.loadAssetAsync(),go&&console.log("Instantiate",this.url,"parent:",s),this.asset){go&&console.log("Add to scene",this.asset);let r=Da.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,Da.currentlyInstantiating.set(this.url,r),t){o.context=n;const l=this.asset;l.guid=this.url;const c=Eg(l,o,void 0,i);if(c)return c}else{const l=La(this.asset,o);if(l)return l}}finally{n.post_render_callbacks.push(()=>{r===void 0||r<0?r=0:r-=1,Da.currentlyInstantiating.set(this.url,r)})}}else go&&console.warn("Failed to load asset",this.url);return null}tryGetActualGameObjectRoot(s){if(s&&s.scene){const t=s.scene;return t.isGroup&&t.children.length===1&&t.children[0].name+"glb"===t.name?t.children[0]:t}return null}};let le=Da;a(le,"currentlyInstantiating",new Map);class Q2 extends Qi{constructor(){super([le],"AssetReferenceSerializer")}onSerialize(t,i){if(t&&t.uri!==void 0&&typeof t.uri=="string")return t.uri}onDeserialize(t,i){if(typeof t=="string")return i.context?i.gltfId?le.getOrCreate(i.gltfId,t,i.context):(console.error("Missing source id"),null):(console.error("Missing context"),null);if(t instanceof I){if(!i.context)return console.error("Missing context"),null;if(!i.gltfId)return console.error("Missing source id"),null;const n=t,o=i.context,r=n.guid??n.uuid,l=o.addressables.findAssetReference(r);if(l)return l;const c=new le(r,void 0,n);return o.addressables.registerAssetReference(c),c}return null}}new Q2;const Y2=Promise.resolve(null),Kd=class{constructor(s){a(this,"url"),a(this,"_bitmap"),a(this,"_bitmapObject"),a(this,"loader",null),this.url=s}static getOrCreate(s){let t=Kd.imageReferences.get(s);return t||(t=new Kd(s),Kd.imageReferences.set(s,t)),t}dispose(){this._bitmapObject&&this._bitmapObject.close(),this._bitmap=void 0}createHTMLImage(){const s=new Image;return s.src=this.url,s}createTexture(){return this.url?(this.loader||(this.loader=new ma),this.loader.setCrossOrigin("anonymous"),this.loader.loadAsync(this.url).then(s=>{var t;return s&&!((t=s.name)!=null&&t.length)&&(s.name=this.url.split("/").pop()??this.url),s})):(console.error("Can not load texture without url"),Y2)}getBitmap(){return this._bitmap?this._bitmap:(this._bitmap=new Promise((s,t)=>{const i=document.createElement("img");i.addEventListener("load",()=>{this._bitmap=createImageBitmap(i).then(n=>(this._bitmapObject=n,s(n),n))}),i.addEventListener("error",n=>{console.error("Failed to load image:"+this.url,n),s(null)}),i.src=this.url}),this._bitmap)}};let Jd=Kd;a(Jd,"imageReferences",new Map);class z_ extends Qi{constructor(){super([Jd],"ImageReferenceSerializer")}onSerialize(t,i){return null}onDeserialize(t,i){if(typeof t=="string"){const n=lo(i.gltfId,t);return Jd.getOrCreate(n)}}}new z_;const eu=class{constructor(s){a(this,"url"),a(this,"res"),this.url=s}static getOrCreate(s){let t=eu.cache.get(s);return t||(t=new eu(s),eu.cache.set(s,t)),t}async loadRaw(){return this.res||(this.res=fetch(this.url)),this.res.then(s=>s.blob())}async loadText(){return this.res||(this.res=fetch(this.url)),this.res.then(s=>s.text())}};let tu=eu;a(tu,"cache",new Map);class U_ extends Qi{constructor(){super([tu],"FileReferenceSerializer")}onSerialize(t,i){return null}onDeserialize(t,i){if(typeof t=="string"){const n=lo(i.gltfId,t);return tu.getOrCreate(n)}}}new U_;class Z2{constructor(t){a(this,"context"),a(this,"mixers",[]),this.context=t}onDestroy(){this.mixers.forEach(t=>t.stopAllAction()),this.mixers.length=0}registerAnimationMixer(t){if(!t){console.warn("AnimationsRegistry.registerAnimationMixer called with null or undefined mixer");return}this.mixers.includes(t)||this.mixers.push(t)}unregisterAnimationMixer(t){if(!t){console.warn("AnimationsRegistry.unregisterAnimationMixer called with null or undefined mixer");return}const i=this.mixers.indexOf(t);i!==-1&&this.mixers.splice(i,1)}}class Ba{static tryGetActionsFromMixer(t){return t._actions||null}static tryGetAnimationClipsFromObjectHierarchy(t,i){if(i||(i=new Array),t)t.animations&&i.push(...t.animations);else return i;if(t.children)for(const n of t.children)this.tryGetAnimationClipsFromObjectHierarchy(n,i);return i}static assignAnimationsFromFile(t,i){if(!t||!t.animations){console.debug("No animations found in file");return}for(let o=0;o<t.animations.length;o++){const r=t.animations[o];if(!r.tracks||r.tracks.length<=0){console.warn("Animation has no tracks");continue}for(const l in r.tracks){const c=r.tracks[l],h=ga.parseTrackName(c.name);let d=ga.findNode(t.scene,h.nodeName);if(!d){const p=c.__objectName??c.name.substring(0,c.name.indexOf("."));if(d=t.scene.getObjectByProperty("uuid",p),!d)continue}let u=n(d);if(!u){if(!(i!=null&&i.createAnimationComponent)){console.warn("No AnimationComponent found in parent hierarchy of object and no 'createAnimationComponent' callback was provided in options.");continue}u=i.createAnimationComponent(t.scene,r)}u.addClip&&u.addClip(r)}}function n(o){var r;if(!o)return null;const l=(r=o.userData)==null?void 0:r.components;if(l&&l.length>0){for(let c=0;c<l.length;c++)if(l[c].isAnimationComponent===!0)return o}return n(o.parent)}}}var iu=(s=>(s.Visible="application-visible",s.Hidden="application-hidden",s.MuteChanged="application-mutechanged",s))(iu||{});let su=!1;const Fa=[];function wr(){if(su)return;F()&&console.debug("User interaction registered: audio can now be played"),su=!0;const s=[...Fa];Fa.length=0,s.forEach(t=>t())}document.addEventListener("mousedown",wr),document.addEventListener("pointerup",wr),document.addEventListener("click",wr),document.addEventListener("dragstart",wr),document.addEventListener("touchend",wr),document.addEventListener("keydown",wr),J.onXRSessionStart(()=>{wr()});const N_=class extends EventTarget{constructor(s){super(),a(this,"_mute",!1),a(this,"context"),a(this,"_isVisible",!0),this.context=s,window.addEventListener("visibilitychange",this.onVisiblityChanged.bind(this),!1)}static get userInteractionRegistered(){return su}static registerWaitForInteraction(s){if(s!==null){if(su){s();return}Fa.indexOf(s)===-1&&Fa.push(s)}}static unregisterWaitForInteraction(s){const t=Fa.indexOf(s);t!==-1&&Fa.splice(t,1)}get muted(){return this._mute}set muted(s){s!==this._mute&&(this._mute=s,this.dispatchEvent(new Event("application-mutechanged")))}get hasFocus(){return document.hasFocus()}get isVisible(){return this._isVisible}onVisiblityChanged(s){switch(s.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}}};let Pn=N_;a(Pn,"registerWaitForAllowAudio",N_.registerWaitForInteraction);function*$g(s,t=null){const i=t?t.time:ee.Current.time,n=i.time;for(;i.time-n<s;)yield}function*K2(s){for(let t=0;t<s;t++)yield}function*W_(s){let t=!0;for(s.then(()=>t=!1),s.catch(()=>t=!1);t;)yield}const V_="NEEDLE_lightmaps",Rc=C("debuglightmapsextension")||C("debuglightmaps");var fo=(s=>(s[s.Lightmap=0]="Lightmap",s[s.Skybox=1]="Skybox",s[s.Reflection=2]="Reflection",s))(fo||{});class J2{constructor(t,i,n){a(this,"parser"),a(this,"registry"),a(this,"source"),this.parser=t,this.registry=i,this.source=n}get name(){return V_}afterRoot(t){const i=this.parser.json.extensions;if(i){const n=i[V_];if(n){const o=n.textures;return o!=null&&o.length?(Rc&&console.log(n),new Promise(async(r,l)=>{const c=[];for(const d of o)if(d.pointer){Rc&&console.log(d);let u=null;if(d.pointer.startsWith("/textures/"))Rc&&console.log("Load texture from gltf",d.pointer),u=jg(this.parser,d.pointer).then(p=>this.resolveTexture(d,p));else if(typeof d.pointer=="string"){Rc&&console.log("Load texture from path",d.pointer);const p=lo(this.source,d.pointer);let g;p.endsWith(".exr")?g=new ud(this.parser.options.manager):p.endsWith(".hdr")?g=new fm(this.parser.options.manager):g=new ma(this.parser.options.manager),u=g.loadAsync(p,void 0).then(y=>this.resolveTexture(d,y))}else d.pointer;u&&c.push(u)}const h=await Mm(c);h!=null&&h.anyFailed&&F()&&console.error("Failed to load lightmap extension",h),r()})):null}}return null}resolveTexture(t,i){const n=i;Rc&&console.log("Lightmap loaded:",n),n!=null&&n.isTexture&&(this.registry?(n.colorSpace=or,this.registry.registerTexture(this.source,t.type,n,t.index)):console.log(fo[t.type],t.pointer,n))}}const H_=!!C("debuglightmaps");class ek{constructor(t){a(this,"_context"),a(this,"_lightmaps",new Map),this._context=t}clear(){this._lightmaps.clear()}registerTexture(t,i,n,o){H_&&console.log("Registering ",fo[i]+' "'+t+'"',n),this._lightmaps.has(t)||this._lightmaps.set(t,new Map);const r=this._lightmaps.get(t),l=r?.get(i)??[];l.length<o&&(l.length=o+1),l[o]=n,r?.set(i,l)}tryGetLightmap(t,i=0){return this.tryGet(t,fo.Lightmap,i)}tryGetSkybox(t){return this.tryGet(t,fo.Skybox,0)}tryGetReflection(t){return this.tryGet(t,fo.Reflection,0)}tryGet(t,i,n){if(!t)return H_&&console.warn("Missing source id"),null;const o=this._lightmaps.get(t);if(!o)return null;const r=o.get(i);return r===void 0||!(r!=null&&r.length)||r.length<=n?null:r[n]}}qt.lights_fragment_maps=qt.lights_fragment_maps.replace("vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );",`
179
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis`,t))),O_()&&console.log("[onGetComponent] FIND",t),t==null))return null;for(let o=0;o<s.userData.components.length;o++){const r=s.userData.components[o];let l=Object.getPrototypeOf(r);for(;l;){if(l===t.prototype)if(O_()&&console.log("[onGetComponent] MATCH BY PROTOYPE",l),i)i.push(r);else return r;l=Object.getPrototypeOf(l)}}return i||null}function yr(s,t){const i=R_(s,t);return i?Array.isArray(i)?i[0]:i:null}function Cc(s,t,i,n=!0){return i||(i=[]),n&&(i.length=0),R_(s,t,i),i}function Oc(s,t,i){var n;const o=yr(s,t);if(i===!1&&o?.enabled===!1)return null;if(o)return o;for(let r=0;r<((n=s?.children)==null?void 0:n.length);r++){const l=Oc(s.children[r],t);if(l)return l}return null}function Aa(s,t,i,n=!0){var o;i||(i=[]),n&&(i.length=0),Cc(s,t,i,!1);for(let r=0;r<((o=s?.children)==null?void 0:o.length);r++)Aa(s.children[r],t,i,!1);return i}function Pc(s,t){if(!s)return null;if(Array.isArray(s)){for(let n=0;n<s.length;n++){const o=q2(s[n]),r=Pc(o,t);if(r)return r}return null}return yr(s,t)||(s.parent?Pc(s.parent,t):null)}function Hd(s,t,i,n=!0){return i||(i=[]),n&&(i.length=0),s?(Cc(s,t,i,!1),s.parent?Hd(s.parent,t,i,!1):i):i}function kc(s,t=void 0,i=!0){if(!s)return null;if(!t&&(t=ee.Current,!t))return console.error("Can not search object without any needle context or scene!!!"),null;let n=t;if(n.isScene||(n=t?.scene),!n)return null;for(const o in n.children){const r=n.children[o];if(i===!1&&r[_n]===!1)continue;const l=Oc(r,s);if(l)return l}return null}function T_(s,t,i=void 0){if(!s)return t??[];if(t||(t=[]),t.length=0,!i&&(i=ee.Current,!i))return console.error("Can not search object without any needle context or scene!!!"),t;"scene"in i&&(i=i.scene);const n=i;if(!n)return t;for(const o in n.children){const r=n.children[o];Aa(r,s,t,!1)}return t}function $d(s){s&&s.isObject3D===!0&&S_(s,I)}I.prototype.SetActive=function(s){this.visible=s},I.prototype.setActive=function(s){this.visible=s},I.prototype.destroy=function(){Ri(this)},I.prototype.addComponent=function(s,t){return Mi(this,s,t)},I.prototype.addNewComponent=function(s,t){return Mi(this,s,t)},I.prototype.removeComponent=function(s){return Ug(this,s)},I.prototype.getOrAddComponent=function(s,t){return Sc(this,s,t)},I.prototype.getComponent=function(s){return yr(this,s)},I.prototype.getComponents=function(s,t){return Cc(this,s,t)},I.prototype.getComponentInChildren=function(s){return Oc(this,s)},I.prototype.getComponentsInChildren=function(s,t){return Aa(this,s,t)},I.prototype.getComponentInParent=function(s){return Pc(this,s)},I.prototype.getComponentsInParent=function(s,t){return Hd(this,s,t)},Object.getOwnPropertyDescriptor(I.prototype,"activeSelf")||Object.defineProperty(I.prototype,"activeSelf",{get:function(){return Ia(this)},set:function(s){Mc(this,s)}}),Object.getOwnPropertyDescriptor(I.prototype,"worldPosition")||Object.defineProperty(I.prototype,"worldPosition",{get:function(){return this instanceof nv?te(this.object):te(this)},set:function(s){ht(this,s)}}),Object.getOwnPropertyDescriptor(I.prototype,"worldQuaternion")||Object.defineProperty(I.prototype,"worldQuaternion",{get:function(){return this instanceof nv?Ce(this.object):Ce(this)},set:function(s){Hi(this,s)}}),Object.getOwnPropertyDescriptor(I.prototype,"worldRotation")||Object.defineProperty(I.prototype,"worldRotation",{get:function(){return ic(this)},set:function(s){Vm(this,s)}}),Object.getOwnPropertyDescriptor(I.prototype,"worldScale")||Object.defineProperty(I.prototype,"worldScale",{get:function(){return Ye(this)},set:function(s){wa(this,s)}}),Object.getOwnPropertyDescriptor(I.prototype,"worldForward")||Object.defineProperty(I.prototype,"worldForward",{get:function(){return G().set(0,0,1).applyQuaternion(Ce(this))}}),Object.getOwnPropertyDescriptor(I.prototype,"worldRight")||Object.defineProperty(I.prototype,"worldRight",{get:function(){return G().set(1,0,0).applyQuaternion(Ce(this))}}),Object.getOwnPropertyDescriptor(I.prototype,"worldUp")||Object.defineProperty(I.prototype,"worldUp",{get:function(){return G().set(0,1,0).applyQuaternion(Ce(this))}}),C_(I);class xe extends ae{constructor(t,i,n,o){var r=(...l)=>{super(...l),a(this,"alpha",1)};i!=null&&n!=null?(r(t,i,n),this.alpha=o):(r(t),this.alpha=1)}get isRGBAColor(){return!0}set a(t){this.alpha=t}get a(){return this.alpha}clone(){const t=super.clone();return t.alpha=this.alpha,t}copy(t){return this.r=t.r,this.g=t.g,this.b=t.b,"alpha"in t&&typeof t.alpha=="number"?this.alpha=t.alpha:typeof t.a=="number"&&(this.alpha=t.a),this}lerp(t,i){const n=t;return n.alpha!=null&&(this.alpha=W.lerp(this.alpha,n.alpha,i)),super.lerp(t,i)}lerpColors(t,i,n){const o=t,r=i;return o.alpha!=null&&r.alpha!=null&&(this.alpha=W.lerp(o.alpha,r.alpha,n)),super.lerpColors(t,i,n)}multiply(t){const i=t;return i.alpha!=null&&(this.alpha=this.alpha*i.alpha),super.multiply(t)}fromArray(t,i=0){return this.alpha=t[i+3],super.fromArray(t,i)}}const qd=C("debuggetcomponent"),Gd=C("debuginstantiate");class Ds{constructor(){a(this,"idProvider"),a(this,"parent"),a(this,"keepWorldPosition"),a(this,"position"),a(this,"rotation"),a(this,"scale"),a(this,"visible"),a(this,"context"),a(this,"components")}clone(){var t,i,n;const o=new Ds;return o.idProvider=this.idProvider,o.parent=this.parent,o.keepWorldPosition=this.keepWorldPosition,o.position=(t=this.position)==null?void 0:t.clone(),o.rotation=(i=this.rotation)==null?void 0:i.clone(),o.scale=(n=this.scale)==null?void 0:n.clone(),o.visible=this.visible,o.context=this.context,o.components=this.components,o}cloneAssign(t){var i,n,o;this.idProvider=t.idProvider,this.parent=t.parent,this.keepWorldPosition=t.keepWorldPosition,this.position=(i=t.position)==null?void 0:i.clone(),this.rotation=(n=t.rotation)==null?void 0:n.clone(),this.scale=(o=t.scale)==null?void 0:o.clone(),this.visible=t.visible,this.context=t.context,this.components=t.components}}function Ia(s){return s.visible}function Mc(s,t){return typeof t=="number"&&(t=t>.5),s.visible=t,s.visible}function E_(s){return s[_n]||Xd(s)}function A_(s,t){s[Jb]=t}function Xd(s){return as.isUsingInstancing(s)}function Ng(s,t){return ba(s,t,!0,!0)}const I_=Symbol("isDestroyed");function vr(s){return s[I_]}function j_(s,t){s[I_]=t}const Wg=Symbol("isDontDestroy");function ja(s,t=!0){s[Wg]=t}const Qd=[],Yd=[];function Ri(s,t=!0,i=!1){Qd.length=0,Yd.length=0,Vg(s,t,!0);for(const n of Qd)n.gameObject=null,n.context=null;for(const n of Yd)j_(n,!0),i&&Ee(n),Zb(n);Yd.length=0,Qd.length=0}function Vg(s,t=!0,i=!0){var n;if(s==null)return;const o=s;if(o.isComponent){if(o[Wg])return;Qd.push(o);const c=o.gameObject;o.__internalDisable(),o.__internalDestroy(),o.gameObject=c;return}if(s[Wg])return;const r=s;qd&&console.log(r),Yd.push(r);const l=(n=r.userData)==null?void 0:n.components;if(l!=null&&Array.isArray(l)){let c=l.length;for(let h=0;h<l.length;h++){const d=l[h];Vg(d,t,!1),l.length<c&&(c=l.length,h--)}}if(t&&r.children)for(const c of r.children)Vg(c,t,!1);i&&r.removeFromParent()}function br(s,t,i=!0){return L_(s,t,i)}function*Zd(s,t,i=!1,n=999,o=0){if(s!=null&&s.userData.components&&!(o>n)){for(const r of s.userData.components)t&&r?.isComponent===!0&&r instanceof t?yield r:yield r;if(i===!0)for(const r of s.children)yield*Zd(r,t,!0,n,o+1)}}function L_(s,t,i,n=0){var o;if(s){if(s.isObject3D,n>1e3){console.warn("Failed to iterate components: too many levels");return}if((o=s.userData)!=null&&o.components)for(let r=0;r<s.userData.components.length;r++){const l=s.userData.components[r];if(l?.isComponent===!0){const c=t(l);if(c!==void 0)return c}}if(i&&s.children){const r=n+1;for(let l=0;l<s.children.length;l++){const c=s.children[l];if(!c)continue;const h=L_(c,t,i,r);if(h!==void 0)return h}}}}function La(s,t){if("isAssetReference"in s)return s.instantiate(t??void 0);let i=null;t!=null&&(t.x!==void 0?(i=new Ds,i.position=t):i=t);let n=ee.Current;i!=null&&i.context&&(n=i.context),qd&&n.alias&&console.log("context",n.alias),i&&!i.idProvider&&(i.idProvider=new Dt(Date.now()));const o=[],r={},l={},c=D_(n,s,i,o,r,l);c&&(X2(r),G2(l,r)),qd&&(_d(s,!0),_d(c,!0));const h={};if(i?.components!==!1){for(const d in o){const u=o[d],p=u.guid;i&&i.idProvider&&(u.guid=i.idProvider.generateUUID(),h[p]=u.guid,qd&&console.log(u.name,u.guid)),pu(u,n),u.__internalNewInstanceCreated&&u.__internalNewInstanceCreated()}for(const d in o){const u=o[d];u.resolveGuids&&u.resolveGuids(h),u.enabled!==!1&&(u.enabled=!0)}Bd(n)}return c}function D_(s,t,i,n,o,r){var l;if(!t)return null;const c=t.userData;t.userData={};const h=t.children;t.children=[];const d=t.clone(!1);if($d(d),t.userData=c,t.children=h,o[t.uuid]={original:t,clone:d},Gd&&console.log("ADD",t,d),t.type==="SkinnedMesh"&&(r[t.uuid]={original:t,clone:d}),i?.visible!==void 0&&(d.visible=i.visible),i!=null&&i.idProvider){d.uuid=i.idProvider.generateUUID();const p=d;p&&(p.guid=d.uuid)}t.animations&&t.animations.length>0&&(d.animations=[...t.animations]);const u=t.parent;if(u&&u.add(d),i!=null&&i.position?ht(d,i.position):d.position.copy(t.position),i!=null&&i.rotation?Hi(d,i.rotation):d.quaternion.copy(t.quaternion),i!=null&&i.scale?d.scale.copy(i.scale):d.scale.copy(t.scale),i!=null&&i.parent&&i.parent!=="scene"){let p=null;if(typeof i.parent=="string"?p=ba(i.parent,s.scene,!0):p=i.parent,p){const g=i.keepWorldPosition===!0?p.attach:p.add;g?g.call(p,d):console.error("Invalid parent object",p,"received when instantiating:",t)}else console.warn("could not find parent:",i.parent)}for(const[p,g]of Object.entries(t.userData))p!=="components"&&(d.userData[p]=g);if((l=t.userData)!=null&&l.components){const p=t.userData.components,g=[];d.userData.components=g;for(let y=0;y<p.length;y++){const f=p[y],v=new f.constructor;Ea(v,f),f[hc]!==void 0&&(v[hc]=f[hc]),g.push(v),v.gameObject=d,n.push(v),o[f.guid]={original:f,clone:v},yc.dispatchComponentLifecycleEvent("component-added",v)}}i&&(i.position=void 0,i.rotation=void 0,i.scale=void 0,i.parent=void 0);for(const p in t.children){const g=t.children[p],y=D_(s,g,i,n,o,r);y&&d.add(y)}return d}function G2(s,t){for(const i in s){const n=s[i],o=n.original,r=o.skeleton,l=n.clone;if(!r){console.warn("Skinned mesh has no skeleton?",n);continue}const c=r.bones,h=l.skeleton.clone();l.skeleton=h,l.bindMatrix.clone().copy(o.bindMatrix),l.bindMatrixInverse.copy(o.bindMatrixInverse);const d=[];h.bones=d;for(let u=0;u<c.length;u++){const p=c[u],g=t[p.uuid].clone;d.push(g)}}for(const i in s){const n=s[i].clone;n.skeleton.update(),n.bind(n.skeleton,n.bindMatrix),n.updateMatrixWorld(!0)}}function X2(s){var t;for(const i in s){const n=s[i].clone;if(n!=null&&n.isObject3D&&(t=n?.userData)!=null&&t.components)for(let o=0;o<n.userData.components.length;o++){const r=n.userData.components[o],l=Object.entries(r);for(const[c,h]of l)if(Array.isArray(h)){const d=[];r[c]=d;for(let u=0;u<h.length;u++){const p=h[u];if(typeof p!="object"){d.push(p);continue}const g=B_(r,c,p,s);g!==void 0?d.push(g):d.push(p)}}else if(typeof h=="object"){const d=B_(r,c,h,s);d!==void 0&&(r[c]=d)}}}}function B_(s,t,i,n){var o,r;if(i!=null)if(i.isComponent===!0){const l=i.gameObject;if(l){const c=l.uuid,h=(o=n[c])==null?void 0:o.clone;if(!h){Gd&&console.log("reference did not change",t,s,i);return}const d=l.userData.components.indexOf(i);if(d>=0&&h.isObject3D)return Gd&&console.log(t,c),h.userData.components[d];console.warn("could not find component",t,i)}}else if(i.isObject3D===!0){if(t==="gameObject")return;const l=i;if(l){const c=l.uuid,h=(r=n[c])==null?void 0:r.clone;if(h)return Gd&&console.log(t,"old",i,"new",h),h}}else{if(i.isVector4||i.isVector3||i.isVector2||i.isQuaternion||i.isEuler||i.isColor===!0)return i.clone();if(i.isEventList===!0)return i.__internalOnInstantiate(n)}}var _r;(s=>{s.baseUrl="https://networking.needle.tools";function t(h){return dv(new Uint8Array(h))}s.hashMD5=t;function i(h){const d=dv(new Uint8Array(h),{encoding:"binary",asBytes:!0});return btoa(String.fromCharCode(...d))}s.hashMD5_Base64=i;function n(h){const d=new Uint8Array(h);return crypto.subtle.digest("SHA-256",d).then(u=>btoa(String.fromCharCode(...new Uint8Array(u))))}s.hashSha256=n;function o(h){const d=h.filesize/1024/1024;return Cs()?d<50:d<5}s.canUpload=o;async function r(h,d){var u;const p=s.baseUrl;if(p){if(!h.name)return console.error("Upload: file name is missing"),null}else return console.error("Blob storage base url is not set"),null;let g=null;h instanceof File?g=await h.arrayBuffer():g=h.data;const y=g.byteLength,f=y/1024/1024;if(f>50)return d?.silent!==!0&&we(`File (${f.toFixed(1)}MB) is too large for uploading (see console for details)`),console.warn(`Your file is too large for uploading (${f.toFixed(1)}MB). Max allowed size is 50MB`),null;if(!Cs()&&f>5)return d?.silent!==!0&&we('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 (${f.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 (${f.toFixed(1)}MB). Min size is 1 byte`),null;const v=i(g),b={filename:h.name,"Content-Md5":v,"Content-Type":h.type||"application/octet-stream",FileSize:y.toString(),"Content-Disposition":`attachment; filename="${h.name}"`,"x-amz-server-side-encryption":"AES256"},w=await fetch(p+"/api/needle/blob",{method:"POST",headers:b,signal:d?.abort}).then(_=>_.json()).catch(_=>(console.error(_),null));if(w==null)return console.warn("Upload failed..."),null;if("error"in w)return console.error(w.error),null;if("upload"in w&&w.upload){let _=function(M){var T;return(T=d?.onProgress)==null||T.call(null,{progress01:0,state:"inprogress"}),fetch(M,{method:"PUT",headers:b,body:g,signal:d?.abort}).then(L=>{var D;return(D=d?.onProgress)==null||D.call(null,{progress01:1,state:"finished"}),L}).catch(L=>L)};console.debug("Uploading file",w.upload);let S=!1,R=null;for(let M=0;M<3;M++)try{if(S)break;if((u=d?.abort)!=null&&u.aborted)return console.debug("Aborted upload"),null;const T=await _(w.upload);T instanceof Error?(R=T,await fs(1e3*M)):T.ok&&(console.debug("File uploaded successfully"),S=!0)}catch(T){console.error(T)}if(!S)return console.error(R?.message||"Failed to upload file"),null}if("download"in w){const _=p+w.download;return console.debug("File found in blob storage",_),{key:w.key,success:!0,download_url:_}}return null}s.upload=r;function l(h){return`${s.baseUrl}/api/needle/blob/${h}`}s.getBlobUrlForKey=l;async function c(h,d){var u;const p=await fetch(h),g=(u=p.body)==null?void 0:u.getReader(),y=p.headers.get("Content-Length"),f=y?parseInt(y):0;if(!g)return null;let v=0;const b=[];for(;;){const{done:S,value:R}=await g.read();if(R&&(b.push(R),v+=R.length,d?.call(null,new ProgressEvent("progress",{loaded:v,total:f}))),S)break}const w=new Uint8Array(v);let _=0;for(const S of b)w.set(S,_),_+=S.length;return w}s.download=c})(_r||(_r={}));const go=C("debugaddressables");class F_{constructor(t){a(this,"_context"),a(this,"_assetReferences",{}),a(this,"preUpdate",()=>{}),this._context=t,this._context.pre_update_callbacks.push(this.preUpdate)}dispose(){const t=this._context.pre_update_callbacks.indexOf(this.preUpdate);t>=0&&this._context.pre_update_callbacks.splice(t,1);for(const i in this._assetReferences){const n=this._assetReferences[i];n?.unload()}this._assetReferences={}}findAssetReference(t){return this._assetReferences[t]||null}registerAssetReference(t){return t.url&&(this._assetReferences[t.url]?console.warn("Asset reference already registered",t):this._assetReferences[t.url]=t),t}unregisterAssetReference(t){t.url&&delete this._assetReferences[t.url]}}const Hg=Symbol("assetReference"),Da=class{constructor(s,t,i=null){a(this,"_loading"),a(this,"_asset"),a(this,"_glbRoot"),a(this,"_url"),a(this,"_urlName"),a(this,"_progressListeners",[]),a(this,"_hash"),a(this,"_hashedUri"),a(this,"_isLoadingRawBinary",!1),a(this,"_rawBinary"),this._url=s;const n=s.lastIndexOf("/");if(n>=0){this._urlName=s.substring(n+1);const o=this._urlName.lastIndexOf(".");o>=0&&(this._urlName=this._urlName.substring(0,o))}else this._urlName=s;this._hash=t,s.includes("?v=")?this._hashedUri=s:this._hashedUri=t?s+"?v="+t:s,i!==null&&(this.asset=i),d_(this._url,this.onResolvePrefab.bind(this))}static getOrCreateFromUrl(s,t){if(!t&&(t=ee.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(s);if(n)return n;const o=new Da(s,t.hash);return i.registerAssetReference(o),o}static getOrCreate(s,t,i){if(typeof s=="string"){if(!i&&(i=ee.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=s.context,s=s.sourceId;const n=lo(s,t);go&&console.log("GetOrCreate Addressable from",s,t,"FinalPath=",n);const o=i.addressables,r=o.findAssetReference(n);if(r)return r;const l=new Da(n,i.hash);return o.registerAssetReference(l),l}get isAssetReference(){return!0}get asset(){return this._glbRoot??this._asset}set asset(s){this._asset=s}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("/"))}get rawAsset(){return this._asset}async onResolvePrefab(s){return s===this.url&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0||vr(this.asset)===!0}isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(go&&console.log("Unload",this.asset),"scene"in this.asset&&this.asset.scene&&Ri(this.asset.scene,!0,!0),Ri(this.asset,!0,!0)),this.asset=null,this._rawBinary=void 0,this._glbRoot=null,this._loading=void 0,ee.Current&&ee.Current.addressables.unregisterAssetReference(this)}async preload(){if(!this.mustLoad||this._isLoadingRawBinary)return null;if(this._rawBinary!==void 0)return this._rawBinary;this._isLoadingRawBinary=!0,go&&console.log("Preload",this._hashedUri);const s=await _r.download(this._hashedUri,t=>{this.raiseProgressEvent(t)});return this._rawBinary=s?.buffer??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(s){if(go&&console.log("loadAssetAsync",this.url),!this.mustLoad)return this.asset;if(s&&this._progressListeners.push(s),this._loading!==void 0)return this._loading.then(n=>this.asset);const t=ee.Current;if(this._rawBinary){if(!(this._rawBinary instanceof ArrayBuffer))return console.error("Invalid raw binary data",this._rawBinary),null;this._loading=gs().parseSync(t,this._rawBinary,this.url,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))}else go&&console.log("Load async",this.url),this._loading=gs().loadSync(t,this._hashedUri,this.url,null,n=>{this.raiseProgressEvent(n)});const i=await this._loading;return this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(i),this._loading=void 0,i?(i[Hg]=this,this._glbRoot&&(this._glbRoot[Hg]=this),this.asset&&(this.asset[Hg]=this),Bd(t),i.scene!==void 0&&(this.asset=i),this.asset):null}async instantiate(s){return this.onInstantiate(s,!1)}async instantiateSynced(s,t=!0){return this.onInstantiate(s,!0,t)}beginListenDownload(s){this._progressListeners.indexOf(s)<0&&this._progressListeners.push(s)}endListenDownload(s){const t=this._progressListeners.indexOf(s);t>=0&&this._progressListeners.splice(t,1)}raiseProgressEvent(s){for(const t of this._progressListeners)t(this,s)}async onInstantiate(s,t=!1,i){const n=ee.Current,o=new Ds;if(s instanceof I?o.parent=s:s&&(Object.assign(o,s),o.cloneAssign(s)),o.parent||(o.parent=n.scene),this.mustLoad&&await this.loadAssetAsync(),go&&console.log("Instantiate",this.url,"parent:",s),this.asset){go&&console.log("Add to scene",this.asset);let r=Da.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,Da.currentlyInstantiating.set(this.url,r),t){o.context=n;const l=this.asset;l.guid=this.url;const c=Eg(l,o,void 0,i);if(c)return c}else{const l=La(this.asset,o);if(l)return l}}finally{n.post_render_callbacks.push(()=>{r===void 0||r<0?r=0:r-=1,Da.currentlyInstantiating.set(this.url,r)})}}else go&&console.warn("Failed to load asset",this.url);return null}tryGetActualGameObjectRoot(s){if(s&&s.scene){const t=s.scene;return t.isGroup&&t.children.length===1&&t.children[0].name+"glb"===t.name?t.children[0]:t}return null}};let le=Da;a(le,"currentlyInstantiating",new Map);class Q2 extends Qi{constructor(){super([le],"AssetReferenceSerializer")}onSerialize(t,i){if(t&&t.uri!==void 0&&typeof t.uri=="string")return t.uri}onDeserialize(t,i){if(typeof t=="string")return i.context?i.gltfId?le.getOrCreate(i.gltfId,t,i.context):(console.error("Missing source id"),null):(console.error("Missing context"),null);if(t instanceof I){if(!i.context)return console.error("Missing context"),null;if(!i.gltfId)return console.error("Missing source id"),null;const n=t,o=i.context,r=n.guid??n.uuid,l=o.addressables.findAssetReference(r);if(l)return l;const c=new le(r,void 0,n);return o.addressables.registerAssetReference(c),c}return null}}new Q2;const Y2=Promise.resolve(null),Kd=class{constructor(s){a(this,"url"),a(this,"_bitmap"),a(this,"_bitmapObject"),a(this,"loader",null),this.url=s}static getOrCreate(s){let t=Kd.imageReferences.get(s);return t||(t=new Kd(s),Kd.imageReferences.set(s,t)),t}dispose(){this._bitmapObject&&this._bitmapObject.close(),this._bitmap=void 0}createHTMLImage(){const s=new Image;return s.src=this.url,s}createTexture(){return this.url?(this.loader||(this.loader=new ma),this.loader.setCrossOrigin("anonymous"),this.loader.loadAsync(this.url).then(s=>{var t;return s&&!((t=s.name)!=null&&t.length)&&(s.name=this.url.split("/").pop()??this.url),s})):(console.error("Can not load texture without url"),Y2)}getBitmap(){return this._bitmap?this._bitmap:(this._bitmap=new Promise((s,t)=>{const i=document.createElement("img");i.addEventListener("load",()=>{this._bitmap=createImageBitmap(i).then(n=>(this._bitmapObject=n,s(n),n))}),i.addEventListener("error",n=>{console.error("Failed to load image:"+this.url,n),s(null)}),i.src=this.url}),this._bitmap)}};let Jd=Kd;a(Jd,"imageReferences",new Map);class z_ extends Qi{constructor(){super([Jd],"ImageReferenceSerializer")}onSerialize(t,i){return null}onDeserialize(t,i){if(typeof t=="string"){const n=lo(i.gltfId,t);return Jd.getOrCreate(n)}}}new z_;const eu=class{constructor(s){a(this,"url"),a(this,"res"),this.url=s}static getOrCreate(s){let t=eu.cache.get(s);return t||(t=new eu(s),eu.cache.set(s,t)),t}async loadRaw(){return this.res||(this.res=fetch(this.url)),this.res.then(s=>s.blob())}async loadText(){return this.res||(this.res=fetch(this.url)),this.res.then(s=>s.text())}};let tu=eu;a(tu,"cache",new Map);class U_ extends Qi{constructor(){super([tu],"FileReferenceSerializer")}onSerialize(t,i){return null}onDeserialize(t,i){if(typeof t=="string"){const n=lo(i.gltfId,t);return tu.getOrCreate(n)}}}new U_;class Z2{constructor(t){a(this,"context"),a(this,"mixers",[]),this.context=t}onDestroy(){this.mixers.forEach(t=>t.stopAllAction()),this.mixers.length=0}registerAnimationMixer(t){if(!t){console.warn("AnimationsRegistry.registerAnimationMixer called with null or undefined mixer");return}this.mixers.includes(t)||this.mixers.push(t)}unregisterAnimationMixer(t){if(!t){console.warn("AnimationsRegistry.unregisterAnimationMixer called with null or undefined mixer");return}const i=this.mixers.indexOf(t);i!==-1&&this.mixers.splice(i,1)}}class Ba{static tryGetActionsFromMixer(t){return t._actions||null}static tryGetAnimationClipsFromObjectHierarchy(t,i){if(i||(i=new Array),t)t.animations&&i.push(...t.animations);else return i;if(t.children)for(const n of t.children)this.tryGetAnimationClipsFromObjectHierarchy(n,i);return i}static assignAnimationsFromFile(t,i){if(!t||!t.animations){console.debug("No animations found in file");return}for(let o=0;o<t.animations.length;o++){const r=t.animations[o];if(!r.tracks||r.tracks.length<=0){console.warn("Animation has no tracks");continue}for(const l in r.tracks){const c=r.tracks[l],h=ga.parseTrackName(c.name);let d=ga.findNode(t.scene,h.nodeName);if(!d){const p=c.__objectName??c.name.substring(0,c.name.indexOf("."));if(d=t.scene.getObjectByProperty("uuid",p),!d)continue}let u=n(d);if(!u){if(!(i!=null&&i.createAnimationComponent)){console.warn("No AnimationComponent found in parent hierarchy of object and no 'createAnimationComponent' callback was provided in options.");continue}u=i.createAnimationComponent(t.scene,r)}u.addClip&&u.addClip(r)}}function n(o){var r;if(!o)return null;const l=(r=o.userData)==null?void 0:r.components;if(l&&l.length>0){for(let c=0;c<l.length;c++)if(l[c].isAnimationComponent===!0)return o}return n(o.parent)}}}var iu=(s=>(s.Visible="application-visible",s.Hidden="application-hidden",s.MuteChanged="application-mutechanged",s))(iu||{});let su=!1;const Fa=[];function wr(){if(su)return;F()&&console.debug("User interaction registered: audio can now be played"),su=!0;const s=[...Fa];Fa.length=0,s.forEach(t=>t())}document.addEventListener("mousedown",wr),document.addEventListener("pointerup",wr),document.addEventListener("click",wr),document.addEventListener("dragstart",wr),document.addEventListener("touchend",wr),document.addEventListener("keydown",wr),J.onXRSessionStart(()=>{wr()});const N_=class extends EventTarget{constructor(s){super(),a(this,"_mute",!1),a(this,"context"),a(this,"_isVisible",!0),this.context=s,window.addEventListener("visibilitychange",this.onVisiblityChanged.bind(this),!1)}static get userInteractionRegistered(){return su}static registerWaitForInteraction(s){if(s!==null){if(su){s();return}Fa.indexOf(s)===-1&&Fa.push(s)}}static unregisterWaitForInteraction(s){const t=Fa.indexOf(s);t!==-1&&Fa.splice(t,1)}get muted(){return this._mute}set muted(s){s!==this._mute&&(this._mute=s,this.dispatchEvent(new Event("application-mutechanged")))}get hasFocus(){return document.hasFocus()}get isVisible(){return this._isVisible}onVisiblityChanged(s){switch(s.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}}};let Pn=N_;a(Pn,"registerWaitForAllowAudio",N_.registerWaitForInteraction);function*$g(s,t=null){const i=t?t.time:ee.Current.time,n=i.time;for(;i.time-n<s;)yield}function*K2(s){for(let t=0;t<s;t++)yield}function*W_(s){let t=!0;for(s.then(()=>t=!1),s.catch(()=>t=!1);t;)yield}const V_="NEEDLE_lightmaps",Rc=C("debuglightmapsextension")||C("debuglightmaps");var fo=(s=>(s[s.Lightmap=0]="Lightmap",s[s.Skybox=1]="Skybox",s[s.Reflection=2]="Reflection",s))(fo||{});class J2{constructor(t,i,n){a(this,"parser"),a(this,"registry"),a(this,"source"),this.parser=t,this.registry=i,this.source=n}get name(){return V_}afterRoot(t){const i=this.parser.json.extensions;if(i){const n=i[V_];if(n){const o=n.textures;return o!=null&&o.length?(Rc&&console.log(n),new Promise(async(r,l)=>{const c=[];for(const d of o)if(d.pointer){Rc&&console.log(d);let u=null;if(d.pointer.startsWith("/textures/"))Rc&&console.log("Load texture from gltf",d.pointer),u=jg(this.parser,d.pointer).then(p=>this.resolveTexture(d,p));else if(typeof d.pointer=="string"){Rc&&console.log("Load texture from path",d.pointer);const p=lo(this.source,d.pointer);let g;p.endsWith(".exr")?g=new ud(this.parser.options.manager):p.endsWith(".hdr")?g=new fm(this.parser.options.manager):g=new ma(this.parser.options.manager),u=g.loadAsync(p,void 0).then(y=>this.resolveTexture(d,y))}else d.pointer;u&&c.push(u)}const h=await Mm(c);h!=null&&h.anyFailed&&F()&&console.error("Failed to load lightmap extension",h),r()})):null}}return null}resolveTexture(t,i){const n=i;Rc&&console.log("Lightmap loaded:",n),n!=null&&n.isTexture&&(this.registry?(n.colorSpace=or,this.registry.registerTexture(this.source,t.type,n,t.index)):console.log(fo[t.type],t.pointer,n))}}const H_=!!C("debuglightmaps");class ek{constructor(t){a(this,"_context"),a(this,"_lightmaps",new Map),this._context=t}clear(){this._lightmaps.clear()}registerTexture(t,i,n,o){H_&&console.log("Registering ",fo[i]+' "'+t+'"',n),this._lightmaps.has(t)||this._lightmaps.set(t,new Map);const r=this._lightmaps.get(t),l=r?.get(i)??[];l.length<o&&(l.length=o+1),l[o]=n,r?.set(i,l)}tryGetLightmap(t,i=0){return this.tryGet(t,fo.Lightmap,i)}tryGetSkybox(t){return this.tryGet(t,fo.Skybox,0)}tryGetReflection(t){return this.tryGet(t,fo.Reflection,0)}tryGet(t,i,n){if(!t)return H_&&console.warn("Missing source id"),null;const o=this._lightmaps.get(t);if(!o)return null;const r=o.get(i);return r===void 0||!(r!=null&&r.length)||r.length<=n?null:r[n]}}qt.lights_fragment_maps=qt.lights_fragment_maps.replace("vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );",`
180
180
  vec2 lUv = vLightMapUv.xy * lightmapScaleOffset.xy + vec2(lightmapScaleOffset.z, (1. - (lightmapScaleOffset.y + lightmapScaleOffset.w)));
181
181
  vec4 lightMapTexel = texture2D( lightMap, lUv);
182
182
  // 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.
@@ -205,7 +205,7 @@ TEX `+n.texture_lod;if(qg=="density"&&(_+=`
205
205
  `+(w/c.lastScreenCoverage).toFixed(0)+` dens
206
206
  `+(c.lastScreenCoverage*100).toFixed(1)+`% cov
207
207
  `+(c.lastCentrality*100).toFixed(1)+`% centr
208
- `+(nu.min.x.toFixed(2)+"-"+nu.max.x.toFixed(2)+"x"+nu.min.y.toFixed(2)+"-"+nu.max.y.toFixed(2))+" scr"),c.lastScreenCoverage>.1){const S=t,R=S.worldForward,M=S.worldPosition,T=G(R).multiplyScalar(g*.7).add(p),j=T.distanceTo(M),L=y[Math.min(y.length-1,Math.max(0,h))]+"88",U=this.context.domHeight>0?screen.height/this.context.domHeight:1,B=t.isPerspectiveCamera?Math.tan(t.fov*Math.PI/180/2):1;q.DrawLabel(T,_,j*.012*U*B,void 0,16777215,L)}}}}}const ik=C("debugplayerview");var yo=(s=>(s.Browser="browser",s.Headset="headset",s.Handheld="handheld",s))(yo||{});class $_{constructor(t,i){a(this,"userId"),a(this,"context"),a(this,"viewDevice","browser"),a(this,"removed",!1),a(this,"_object"),this.userId=t,this.context=i}get currentObject(){return this._object}set currentObject(t){this._object=t}get isConnected(){return this.context.connection.userIsInRoom(this.userId)}}class q_{constructor(t){a(this,"context"),a(this,"playerViews",new Map),this.context=t}setPlayerView(t,i,n){let o=this.playerViews.get(t);o||(o=new $_(t,this.context),this.playerViews.set(t,o)),o.viewDevice=n,o.currentObject=i,o.removed=!1}getPlayerView(t){if(!!t){if(!this.context.connection.userIsInRoom(t)){this.playerViews.delete(t);return}return this.playerViews.get(t)}}removePlayerView(t,i){const n=this.playerViews.get(t);n?.viewDevice===i&&(ik&&console.log("REMOVE",t),n.removed=!0,this.playerViews.delete(t))}}new Xy;const Tc=new Uint8Array(4);Tc[0]=255,Tc[1]=255,Tc[2]=255,Tc[3]=255;const sk=new om(Tc,1,1,ad);function Gg(s,t=1){const i="alpha"in s,n=t*t,o=new Uint8Array(4*n),r=Math.floor(s.r*255),l=Math.floor(s.g*255),c=Math.floor(s.b*255);for(let d=0;d<n;d++){const u=d*4;o[u+0]=r,o[u+1]=l,o[u+2]=c,i?o[u+3]=Math.floor(s.alpha*255):o[u+3]=255}const h=new om(o,t,t);return h.needsUpdate=!0,h}function nk(s,t,i,n=1,o=3){const r=n*o,l=[s,t,i],c=l.length,h=new Uint8Array(4*c*r),d=new ae;for(let p=0;p<o;p++){const g=Math.floor(p/o*c),y=W.clamp(g+1,0,c-1),f=l[g],v=l[y],b=p/o*c%1;d.lerpColors(f,v,b);const w=Math.floor(d.r*255),_=Math.floor(d.g*255),S=Math.floor(d.b*255);for(let R=0;R<n;R++){const M=(p*n+R)*4;h[M+0]=w,h[M+1]=_,h[M+2]=S,h[M+3]=255}}const u=new om(h,n,o);return u.needsUpdate=!0,u}function ru(s,t){const i=s.elements;t||(t=[]),t.length=0;for(let n=0;n<16;n+=4){const o=i[n],r=i[n+1],l=i[n+2],c=i[n+3],h=new fe(o,r,l,c);t.push(h)}return t}const Xg=[],G_=[];function ok(s,t){if(Xg.length===0)for(let i=0;i<27;i++)Xg.push(0);t||(t=Xg);for(let i=0;i<27;i++)G_[i]=t[i];t=G_,s.unity_SHAr={value:new fe(t[9],t[3],t[6],t[0])},s.unity_SHBr={value:new fe(t[12],t[15],t[18],t[21])},s.unity_SHAg={value:new fe(t[10],t[4],t[7],t[1])},s.unity_SHBg={value:new fe(t[13],t[16],t[19],t[22])},s.unity_SHAb={value:new fe(t[11],t[5],t[8],t[2])},s.unity_SHBb={value:new fe(t[14],t[17],t[20],t[23])},s.unity_SHC={value:new fe(t[24],t[25],t[26],1)}}class rk{constructor(t,i,n){a(this,"vertexShader"),a(this,"fragmentShader"),a(this,"technique"),this.vertexShader=t,this.fragmentShader=i,this.technique=n}}async function ak(s,t){if(!s)return console.error("Can not find technique: no shader data"),null;const i=s.programs[t],n=i.vertexShader,o=i.fragmentShader;if(n!==void 0&&o!==void 0){const r=s.shaders[n],l=s.shaders[o];if(r.uri&&l.uri||r.code&&l.code){if(!r.code&&r.uri&&await X_(r),!l.code&&l.uri&&await X_(l),!r.code||!l.code)return null;const c=s.techniques[t];return new rk(r.code,l.code,c)}}return console.error("Shader technique not found",t),null}async function X_(s){const t=s.uri;if(t)if(t.endsWith(".glsl")){const i=await new Xy().loadAsync(t);s.code=i.toString()}else s.code=lk(s.uri)}function lk(s){return decodeURIComponent(Array.prototype.map.call(atob(s),function(t){return"%"+("00"+t.charCodeAt(0).toString(16)).slice(-2)}).join(""))}const Ss=C("debugenvlight");var za=(s=>(s[s.Skybox=0]="Skybox",s[s.Trilight=1]="Trilight",s[s.Flat=3]="Flat",s[s.Custom=4]="Custom",s))(za||{}),au=(s=>(s[s.Skybox=0]="Skybox",s[s.Custom=1]="Custom",s))(au||{});class Q_{constructor(t){a(this,"context"),a(this,"_currentLightSettingsId"),a(this,"_sceneLightSettings"),a(this,"_timevec4",new fe),a(this,"__currentReflectionId",null),a(this,"_lighting",{}),this.context=t,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}preUpdate(){const t=this.context.time;this._timevec4.x=t.time,this._timevec4.y=Math.sin(t.time),this._timevec4.z=Math.cos(t.time),this._timevec4.w=t.deltaTime}get timeVec4(){return this._timevec4}get environmentIntensity(){if(!this._sceneLightSettings||!this._currentLightSettingsId)return 1;const t=this._sceneLightSettings.get(this._currentLightSettingsId);return t?t.ambientIntensity:1}get sceneLightSettings(){var t;return(t=this._sceneLightSettings)==null?void 0:t.values()}enable(t){var i;t instanceof le&&(t=t.url);const n=(i=this._sceneLightSettings)==null?void 0:i.get(t);return n?(Ss&&console.log("Enable scene light settings",t,n),t!==this._currentLightSettingsId&&this._currentLightSettingsId&&this.disable(this._currentLightSettingsId),this._currentLightSettingsId=t,n.enabled=!0,!0):(Ss&&console.warn("No light settings found for",t),!1)}disable(t){var i;if(t instanceof le&&(t=t.url),t==null)return!1;const n=(i=this._sceneLightSettings)==null?void 0:i.get(t);return n?(Ss&&console.log("Disable scene light settings",t,n),n.enabled=!1,!0):!1}disableCurrent(){if(this._currentLightSettingsId){const t=this._currentLightSettingsId;return this.disable(this._currentLightSettingsId),t}return null}internalRegisterSceneLightSettings(t){const i=t.sourceId;if(!i){console.error("Missing source id for scene light settings, can not register:",t);return}Ss&&console.log("Register "+t?.sourceId+" lighting",t),this._sceneLightSettings||(this._sceneLightSettings=new Map),this._sceneLightSettings.set(i,t)}internalUnregisterSceneLightSettings(t){const i=t.sourceId;if(!i){console.error("Missing source id for scene light settings, can not unregister:",t);return}Ss&&console.log("Unregister "+t?.sourceId+" lighting",t),this._sceneLightSettings&&this._sceneLightSettings.delete(i)}internalRegisterReflection(t,i){Ss&&console.log("Register reflection",t,i);const n=new Y_(this.context,i,1);this._lighting[t]=n}internalGetReflection(t){return this._lighting[t]}internalEnableReflection(t){var i;this.__currentReflectionId=t;const n=(i=this._sceneLightSettings)==null?void 0:i.get(t);switch(Ss&&console.log("Enable reflection",t,n?za[n.ambientMode]:"Unknown ambient mode",n),n?.ambientMode){case 0:case 4:const o=this.internalGetReflection(t);if(o&&o.Source){Ss&&console.log("Setting environment reflection",o);const r=this.context.scene,l=o.Source;l.mapping=yn,r.environment=l;return}else Ss&&console.warn("Could not find reflection for source",t);break}if(n?.environmentReflectionSource===1)switch(n?.ambientMode){case 1:if(n.ambientTrilight){const o=n.ambientTrilight,r=nk(o[0],o[1],o[2],64,64);r.colorSpace=ms,r.mapping=yn,this.context.scene.environment=r}else console.error("Missing ambient trilight",n.sourceId);return;case 3:if(n.ambientLight){const o=Gg(n.ambientLight,64);o.colorSpace=ms,o.mapping=yn,this.context.scene.environment=o}else console.error("Missing ambientlight",n.sourceId);return;default:return}}internalDisableReflection(t){if(t&&t!==this.__currentReflectionId){Ss&&console.log("Not disabling reflection for",t,"because it is not the current light settings id",this.__currentReflectionId);return}Ss&&console.log("Disable reflection",t);const i=this.context.scene;i.environment=null}}class Y_{constructor(t,i,n=1){a(this,"_source"),this._source=i,i.mapping=yn}get Source(){return this._source}}const Z_=C("timescale");let Qg=1;typeof Z_=="number"&&(Qg=Z_);class K_{constructor(){a(this,"_time",0),a(this,"_deltaTime",0),a(this,"_deltaTimeUnscaled",0),a(this,"timeScale",1),a(this,"_frame",0),a(this,"clock",new RS),a(this,"_smoothedFps",0),a(this,"_smoothedDeltaTime",0),a(this,"_fpsSamples",[]),a(this,"_fpsSampleIndex",0),typeof Qg=="number"&&(this.timeScale=Qg)}get time(){return this._time}set time(t){this._time=t}get deltaTime(){return this._deltaTime}set deltaTime(t){this._deltaTime=t}get deltaTimeUnscaled(){return this._deltaTimeUnscaled}get frame(){return this._frame}set frame(t){this._frame=t}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}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 t=0;for(let i=0;i<this._fpsSamples.length;i++)t+=this._fpsSamples[i];this._smoothedDeltaTime=t/this._fpsSamples.length,this._smoothedFps=1/this._smoothedDeltaTime}}let J_=!1;function ew(s){J_||(J_=!0,ck(),hk())}ew();function ck(){const s=`
208
+ `+(nu.min.x.toFixed(2)+"-"+nu.max.x.toFixed(2)+"x"+nu.min.y.toFixed(2)+"-"+nu.max.y.toFixed(2))+" scr"),c.lastScreenCoverage>.1){const S=t,R=S.worldForward,M=S.worldPosition,T=G(R).multiplyScalar(g*.7).add(p),L=T.distanceTo(M),D=y[Math.min(y.length-1,Math.max(0,h))]+"88",U=this.context.domHeight>0?screen.height/this.context.domHeight:1,B=t.isPerspectiveCamera?Math.tan(t.fov*Math.PI/180/2):1;q.DrawLabel(T,_,L*.012*U*B,void 0,16777215,D)}}}}}const ik=C("debugplayerview");var yo=(s=>(s.Browser="browser",s.Headset="headset",s.Handheld="handheld",s))(yo||{});class $_{constructor(t,i){a(this,"userId"),a(this,"context"),a(this,"viewDevice","browser"),a(this,"removed",!1),a(this,"_object"),this.userId=t,this.context=i}get currentObject(){return this._object}set currentObject(t){this._object=t}get isConnected(){return this.context.connection.userIsInRoom(this.userId)}}class q_{constructor(t){a(this,"context"),a(this,"playerViews",new Map),this.context=t}setPlayerView(t,i,n){let o=this.playerViews.get(t);o||(o=new $_(t,this.context),this.playerViews.set(t,o)),o.viewDevice=n,o.currentObject=i,o.removed=!1}getPlayerView(t){if(!!t){if(!this.context.connection.userIsInRoom(t)){this.playerViews.delete(t);return}return this.playerViews.get(t)}}removePlayerView(t,i){const n=this.playerViews.get(t);n?.viewDevice===i&&(ik&&console.log("REMOVE",t),n.removed=!0,this.playerViews.delete(t))}}new Xy;const Tc=new Uint8Array(4);Tc[0]=255,Tc[1]=255,Tc[2]=255,Tc[3]=255;const sk=new om(Tc,1,1,ad);function Gg(s,t=1){const i="alpha"in s,n=t*t,o=new Uint8Array(4*n),r=Math.floor(s.r*255),l=Math.floor(s.g*255),c=Math.floor(s.b*255);for(let d=0;d<n;d++){const u=d*4;o[u+0]=r,o[u+1]=l,o[u+2]=c,i?o[u+3]=Math.floor(s.alpha*255):o[u+3]=255}const h=new om(o,t,t);return h.needsUpdate=!0,h}function nk(s,t,i,n=1,o=3){const r=n*o,l=[s,t,i],c=l.length,h=new Uint8Array(4*c*r),d=new ae;for(let p=0;p<o;p++){const g=Math.floor(p/o*c),y=W.clamp(g+1,0,c-1),f=l[g],v=l[y],b=p/o*c%1;d.lerpColors(f,v,b);const w=Math.floor(d.r*255),_=Math.floor(d.g*255),S=Math.floor(d.b*255);for(let R=0;R<n;R++){const M=(p*n+R)*4;h[M+0]=w,h[M+1]=_,h[M+2]=S,h[M+3]=255}}const u=new om(h,n,o);return u.needsUpdate=!0,u}function ru(s,t){const i=s.elements;t||(t=[]),t.length=0;for(let n=0;n<16;n+=4){const o=i[n],r=i[n+1],l=i[n+2],c=i[n+3],h=new fe(o,r,l,c);t.push(h)}return t}const Xg=[],G_=[];function ok(s,t){if(Xg.length===0)for(let i=0;i<27;i++)Xg.push(0);t||(t=Xg);for(let i=0;i<27;i++)G_[i]=t[i];t=G_,s.unity_SHAr={value:new fe(t[9],t[3],t[6],t[0])},s.unity_SHBr={value:new fe(t[12],t[15],t[18],t[21])},s.unity_SHAg={value:new fe(t[10],t[4],t[7],t[1])},s.unity_SHBg={value:new fe(t[13],t[16],t[19],t[22])},s.unity_SHAb={value:new fe(t[11],t[5],t[8],t[2])},s.unity_SHBb={value:new fe(t[14],t[17],t[20],t[23])},s.unity_SHC={value:new fe(t[24],t[25],t[26],1)}}class rk{constructor(t,i,n){a(this,"vertexShader"),a(this,"fragmentShader"),a(this,"technique"),this.vertexShader=t,this.fragmentShader=i,this.technique=n}}async function ak(s,t){if(!s)return console.error("Can not find technique: no shader data"),null;const i=s.programs[t],n=i.vertexShader,o=i.fragmentShader;if(n!==void 0&&o!==void 0){const r=s.shaders[n],l=s.shaders[o];if(r.uri&&l.uri||r.code&&l.code){if(!r.code&&r.uri&&await X_(r),!l.code&&l.uri&&await X_(l),!r.code||!l.code)return null;const c=s.techniques[t];return new rk(r.code,l.code,c)}}return console.error("Shader technique not found",t),null}async function X_(s){const t=s.uri;if(t)if(t.endsWith(".glsl")){const i=await new Xy().loadAsync(t);s.code=i.toString()}else s.code=lk(s.uri)}function lk(s){return decodeURIComponent(Array.prototype.map.call(atob(s),function(t){return"%"+("00"+t.charCodeAt(0).toString(16)).slice(-2)}).join(""))}const Ss=C("debugenvlight");var za=(s=>(s[s.Skybox=0]="Skybox",s[s.Trilight=1]="Trilight",s[s.Flat=3]="Flat",s[s.Custom=4]="Custom",s))(za||{}),au=(s=>(s[s.Skybox=0]="Skybox",s[s.Custom=1]="Custom",s))(au||{});class Q_{constructor(t){a(this,"context"),a(this,"_currentLightSettingsId"),a(this,"_sceneLightSettings"),a(this,"_timevec4",new fe),a(this,"__currentReflectionId",null),a(this,"_lighting",{}),this.context=t,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}preUpdate(){const t=this.context.time;this._timevec4.x=t.time,this._timevec4.y=Math.sin(t.time),this._timevec4.z=Math.cos(t.time),this._timevec4.w=t.deltaTime}get timeVec4(){return this._timevec4}get environmentIntensity(){if(!this._sceneLightSettings||!this._currentLightSettingsId)return 1;const t=this._sceneLightSettings.get(this._currentLightSettingsId);return t?t.ambientIntensity:1}get sceneLightSettings(){var t;return(t=this._sceneLightSettings)==null?void 0:t.values()}enable(t){var i;t instanceof le&&(t=t.url);const n=(i=this._sceneLightSettings)==null?void 0:i.get(t);return n?(Ss&&console.log("Enable scene light settings",t,n),t!==this._currentLightSettingsId&&this._currentLightSettingsId&&this.disable(this._currentLightSettingsId),this._currentLightSettingsId=t,n.enabled=!0,!0):(Ss&&console.warn("No light settings found for",t),!1)}disable(t){var i;if(t instanceof le&&(t=t.url),t==null)return!1;const n=(i=this._sceneLightSettings)==null?void 0:i.get(t);return n?(Ss&&console.log("Disable scene light settings",t,n),n.enabled=!1,!0):!1}disableCurrent(){if(this._currentLightSettingsId){const t=this._currentLightSettingsId;return this.disable(this._currentLightSettingsId),t}return null}internalRegisterSceneLightSettings(t){const i=t.sourceId;if(!i){console.error("Missing source id for scene light settings, can not register:",t);return}Ss&&console.log("Register "+t?.sourceId+" lighting",t),this._sceneLightSettings||(this._sceneLightSettings=new Map),this._sceneLightSettings.set(i,t)}internalUnregisterSceneLightSettings(t){const i=t.sourceId;if(!i){console.error("Missing source id for scene light settings, can not unregister:",t);return}Ss&&console.log("Unregister "+t?.sourceId+" lighting",t),this._sceneLightSettings&&this._sceneLightSettings.delete(i)}internalRegisterReflection(t,i){Ss&&console.log("Register reflection",t,i);const n=new Y_(this.context,i,1);this._lighting[t]=n}internalGetReflection(t){return this._lighting[t]}internalEnableReflection(t){var i;this.__currentReflectionId=t;const n=(i=this._sceneLightSettings)==null?void 0:i.get(t);switch(Ss&&console.log("Enable reflection",t,n?za[n.ambientMode]:"Unknown ambient mode",n),n?.ambientMode){case 0:case 4:const o=this.internalGetReflection(t);if(o&&o.Source){Ss&&console.log("Setting environment reflection",o);const r=this.context.scene,l=o.Source;l.mapping=yn,r.environment=l;return}else Ss&&console.warn("Could not find reflection for source",t);break}if(n?.environmentReflectionSource===1)switch(n?.ambientMode){case 1:if(n.ambientTrilight){const o=n.ambientTrilight,r=nk(o[0],o[1],o[2],64,64);r.colorSpace=ms,r.mapping=yn,this.context.scene.environment=r}else console.error("Missing ambient trilight",n.sourceId);return;case 3:if(n.ambientLight){const o=Gg(n.ambientLight,64);o.colorSpace=ms,o.mapping=yn,this.context.scene.environment=o}else console.error("Missing ambientlight",n.sourceId);return;default:return}}internalDisableReflection(t){if(t&&t!==this.__currentReflectionId){Ss&&console.log("Not disabling reflection for",t,"because it is not the current light settings id",this.__currentReflectionId);return}Ss&&console.log("Disable reflection",t);const i=this.context.scene;i.environment=null}}class Y_{constructor(t,i,n=1){a(this,"_source"),this._source=i,i.mapping=yn}get Source(){return this._source}}const Z_=C("timescale");let Qg=1;typeof Z_=="number"&&(Qg=Z_);class K_{constructor(){a(this,"_time",0),a(this,"_deltaTime",0),a(this,"_deltaTimeUnscaled",0),a(this,"timeScale",1),a(this,"_frame",0),a(this,"clock",new RS),a(this,"_smoothedFps",0),a(this,"_smoothedDeltaTime",0),a(this,"_fpsSamples",[]),a(this,"_fpsSampleIndex",0),typeof Qg=="number"&&(this.timeScale=Qg)}get time(){return this._time}set time(t){this._time=t}get deltaTime(){return this._deltaTime}set deltaTime(t){this._deltaTime=t}get deltaTimeUnscaled(){return this._deltaTimeUnscaled}get frame(){return this._frame}set frame(t){this._frame=t}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}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 t=0;for(let i=0;i<this._fpsSamples.length;i++)t+=this._fpsSamples[i];this._smoothedDeltaTime=t/this._fpsSamples.length,this._smoothedFps=1/this._smoothedDeltaTime}}let J_=!1;function ew(s){J_||(J_=!0,ck(),hk())}ew();function ck(){const s=`
209
209
  float startCompression = 0.8;
210
210
  float desaturation = 0.5;
211
211
  // Patched tonemapping function
@@ -438,6 +438,10 @@ vec3 AgXToneMapping( vec3 color ) {
438
438
  color: rgb(20,20,20);
439
439
  }
440
440
 
441
+ .options > select[multiple]:hover {
442
+ max-height: 300px;
443
+ }
444
+
441
445
  .floating-panel-style {
442
446
  background: rgba(255, 255, 255, .4);
443
447
  outline: rgb(0 0 0 / 5%) 1px solid;
@@ -908,7 +912,7 @@ Exit Time: `+u,l.hasExitTime)}this.transitionTo(l.destinationState,l.duration,l.
908
912
  // Uncomment to visualize blur amount
909
913
  // gl_FragColor = vec4(blurAmount, 0.0, 0.0, 1.0);
910
914
  }
911
- `;var Gk=Object.defineProperty,Xk=Object.getOwnPropertyDescriptor,hf=(s,t,i,n)=>{for(var o=n>1?void 0:n?Xk(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&Gk(t,i,o),o};class Mr extends A{constructor(){super(...arguments),a(this,"constraintActive",!0),a(this,"locked",!1),a(this,"sources",[])}}hf([m()],Mr.prototype,"constraintActive",2),hf([m()],Mr.prototype,"locked",2),hf([m(I)],Mr.prototype,"sources",2);function Cw(s,t){return Sn(s,ge.ContextCreated,t),()=>uo(s,ge.ContextCreated)}function Qk(s,t){return Sn(s,ge.ContextClearing,t),()=>uo(s,ge.ContextClearing)}function Yk(s,t){return Sn(s,ge.ContextDestroying,t),()=>uo(s,ge.ContextDestroying)}function Ow(s,t){return Sn(s,Me.Start,t),()=>uo(s,Me.Start)}function Pw(s,t){return Sn(s,Me.Update,t),()=>uo(s,Me.Update)}function Zk(s,t){return Sn(s,Me.OnBeforeRender,t),()=>uo(s,Me.OnBeforeRender)}function Kk(s,t){return Sn(s,Me.OnAfterRender,t),()=>uo(s,Me.OnAfterRender)}let Rr=class{constructor(){a(this,"bb",null),a(this,"bb_pos",0)}__init(s,t){return this.bb_pos=s,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(s,t,i,n){return s.prep(4,12),s.writeFloat32(n),s.writeFloat32(i),s.writeFloat32(t),s.offset()}};class kw{constructor(){a(this,"bb",null),a(this,"bb_pos",0)}__init(t,i){return this.bb_pos=t,this.bb=i,this}position(t){return(t||new Rr).__init(this.bb_pos,this.bb)}rotation(t){return(t||new Rr).__init(this.bb_pos+12,this.bb)}scale(t){return(t||new Rr).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(t,i,n,o,r,l,c,h,d,u){return t.prep(4,36),t.prep(4,12),t.writeFloat32(u),t.writeFloat32(d),t.writeFloat32(h),t.prep(4,12),t.writeFloat32(c),t.writeFloat32(l),t.writeFloat32(r),t.prep(4,12),t.writeFloat32(o),t.writeFloat32(n),t.writeFloat32(i),t.offset()}}class to{constructor(){a(this,"bb",null),a(this,"bb_pos",0)}__init(t,i){return this.bb_pos=t,this.bb=i,this}static getRootAsSyncedTransformModel(t,i){return(i||new to).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSyncedTransformModel(t,i){return t.setPosition(t.position()+uv),(i||new to).__init(t.readInt32(t.position())+t.position(),t)}guid(t){const i=this.bb.__offset(this.bb_pos,4);return i?this.bb.__string(this.bb_pos+i,t):null}fast(){const t=this.bb.__offset(this.bb_pos,6);return t?!!this.bb.readInt8(this.bb_pos+t):!1}transform(t){const i=this.bb.__offset(this.bb_pos,8);return i?(t||new kw).__init(this.bb_pos+i,this.bb):null}dontSave(){const t=this.bb.__offset(this.bb_pos,10);return t?!!this.bb.readInt8(this.bb_pos+t):!1}static startSyncedTransformModel(t){t.startObject(4)}static addGuid(t,i){t.addFieldOffset(0,i,0)}static addFast(t,i){t.addFieldInt8(1,+i,0)}static addTransform(t,i){t.addFieldStruct(2,i,0)}static addDontSave(t,i){t.addFieldInt8(3,+i,0)}static endSyncedTransformModel(t){return t.endObject()}static finishSyncedTransformModelBuffer(t,i){t.finish(i)}static finishSizePrefixedSyncedTransformModelBuffer(t,i){t.finish(i,void 0,!0)}}var D;(s=>{(t=>{t.MAYBEMODULE=null;const i=[];function n(){return t.MODULE?Promise.resolve(t.MODULE):new Promise(r=>{i.push(r)})}t.ready=n;async function o(){if(t.MODULE)return t.MODULE;const r=await import("./rapier.light.min.js");return t.MODULE=r,t.MAYBEMODULE=r,i.forEach(l=>l(r)),i.length=0,r}t.load=o})(s.RAPIER_PHYSICS||(s.RAPIER_PHYSICS={})),(t=>{t.MAYBEMODULE=null;const i=[];function n(){return t.MODULE?Promise.resolve(t.MODULE):new Promise(r=>{i.push(r)})}t.ready=n;async function o(){if(t.MODULE)return t.MODULE;const r=await import("./postprocessing.light.min.js").then(l=>l.i);return t.MODULE=r,t.MAYBEMODULE=r,i.forEach(l=>l(r)),i.length=0,r}t.load=o})(s.POSTPROCESSING||(s.POSTPROCESSING={})),(t=>{t.MAYBEMODULE=null;const i=[];function n(){return t.MODULE?Promise.resolve(t.MODULE):new Promise(r=>{i.push(r)})}t.ready=n;async function o(){if(t.MODULE)return t.MODULE;const r=await import("./postprocessing.light.min.js").then(l=>l.N);return t.MODULE=r,t.MAYBEMODULE=r,i.forEach(l=>l(r)),i.length=0,r}t.load=o})(s.POSTPROCESSING_AO||(s.POSTPROCESSING_AO={}))})(D||(D={}));var _t=(s=>(s[s.Average=0]="Average",s[s.Multiply=1]="Multiply",s[s.Minimum=2]="Minimum",s[s.Maximum=3]="Maximum",s))(_t||{}),wu=(s=>(s[s.Discrete=0]="Discrete",s[s.Continuous=1]="Continuous",s))(wu||{}),st=(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))(st||{}),Na=(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))(Na||{});const kt=function(s,t){return function(i,n,o){Jk(i,n,o,s,t)}};function Jk(s,t,i,n,o){if(!o&&!n&&!s.onValidate)return;if(i!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",s,t,i),De("Invalid usage of validate decorator. Only fields can be validated. Property: "+t,Oi.Error);return}let r="";if(typeof t=="string"?r=t:r=t.name,s.__internalAwake){const l=Symbol(r),c=s.__internalAwake;s.__internalAwake=function(){var h;if(!this.onValidate){F()&&console.warn('Usage of @validate decorate detected but there is no onValidate method in your class: "'+((h=s.constructor)==null?void 0:h.name)+'"');return}if(this[l]===void 0){this[l]=this[r];const d=this[r];if(d instanceof re||d instanceof x||d instanceof fe||d instanceof V){const u=this[r];md(u,()=>{this.onValidate(r)})}Object.defineProperty(this,r,{set:function(u){var p;if(this[zg]===!0)this[l]=u;else{n?.call(this,u);const g=this[l];this[l]=u,(p=this.onValidate)==null||p.call(this,r,g)}},get:function(){return o?.call(this),this[l]}})}c.call(this)}}}const eM=function(s){return function(t,i,n){let o="";typeof i=="string"?o=i:o=i.name;const r=s.prototype,l=Object.getOwnPropertyDescriptor(r,o);if(!(l!=null&&l.value)){console.warn("Can not apply prefix: type does not have method named",i,s);return}const c=l.value,h=t[o];Object.defineProperty(r,o,{value:function(...d){const u=h?.call(this,...d);if(u instanceof Promise){u.then(p=>{if(p!==!1)return c.call(this,...d)});return}if(u!==!1)return c.call(this,...d)}})}};var tM=Object.defineProperty,iM=Object.getOwnPropertyDescriptor,Ti=(s,t,i,n)=>{for(var o=n>1?void 0:n?iM(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&tM(t,i,o),o};class sM{constructor(t,i){a(this,"positionChanged",!1),a(this,"rotationChanged",!1),a(this,"position"),a(this,"quaternion"),a(this,"_positionKeys",["x","y","z"]),a(this,"_quaternionKeys",["_x","_y","_z","_w"]),a(this,"mute",!1),a(this,"context"),a(this,"obj"),a(this,"_positionWatch"),a(this,"_rotationWatch"),this.context=i,this.obj=t}get isDirty(){return this.positionChanged||this.rotationChanged}reset(t=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,t){if(this.position)for(const i of this._positionKeys)delete this.position[i];if(this.quaternion)for(const i of this._quaternionKeys)delete this.quaternion[i]}}syncValues(){for(const t of this._positionKeys)this.position[t]=this.obj.position[t];for(const t of this._quaternionKeys)this.quaternion[t]=this.obj.quaternion[t]}applyValues(){if(this.positionChanged&&this.position)for(const t of this._positionKeys){const i=this.position[t];i!==void 0&&(this.obj.position[t]=i)}if(this.rotationChanged&&this.quaternion)for(const t of this._quaternionKeys){const i=this.quaternion[t];i!==void 0&&(this.obj.quaternion[t]=i)}}start(t,i){this.reset(),t&&(this._positionWatch||(this._positionWatch=new eo(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((r,l)=>{var c;if((c=this.context.physics.engine)!=null&&c.isUpdating||this.mute)return;const h=this.position[l];Math.abs(h-r)<1e-5||(this.position[l]=r,this.positionChanged=!0)})),i&&(this._rotationWatch||(this._rotationWatch=new eo(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((r,l)=>{var c;if((c=this.context.physics.engine)!=null&&c.isUpdating||this.mute)return;const h=this.quaternion[l];Math.abs(h-r)<1e-5||(this.quaternion[l]=r,this.rotationChanged=!0)}));const n=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),o=new ne;this.obj.matrixWorld.multiplyMatrices=(r,l)=>{var c;return(c=this.context.physics.engine)!=null&&c.isUpdating||this.mute||o.equals(r)||(this.positionChanged=!0,this.rotationChanged=!0,o.copy(r)),n(r,l)}}stop(){var t,i;(t=this._positionWatch)==null||t.revoke(),(i=this._rotationWatch)==null||i.revoke()}}var df;const xu=(df=class extends A{constructor(){super(...arguments),a(this,"autoMass",!0),a(this,"_mass",0),a(this,"useGravity",!0),a(this,"centerOfMass",new x(0,0,0)),a(this,"constraints",st.None),a(this,"isKinematic",!1),a(this,"drag",0),a(this,"angularDrag",1),a(this,"detectCollisions",!0),a(this,"sleepThreshold",.01),a(this,"collisionDetectionMode",wu.Discrete),a(this,"_gravityScale",1),a(this,"dominanceGroup",0),a(this,"_propertiesChanged",!1),a(this,"_currentVelocity",new x),a(this,"_smoothedVelocity",new x),a(this,"_smoothedVelocityGetter",new x),a(this,"_lastPosition",new x),a(this,"_watch")}get isRigidbody(){return!0}set mass(s){s!==this._mass&&(this._mass=s,this._propertiesChanged=!0,this.__didAwake&&(this.autoMass=!1))}get mass(){var s,t;return this.autoMass?((t=(s=this.context.physics.engine)==null?void 0:s.getBody(this))==null?void 0:t.mass())??-1:this._mass}get lockPositionX(){return(this.constraints&st.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&st.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&st.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&st.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&st.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&st.FreezeRotationZ)!==0}set lockPositionX(s){s?this.constraints|=st.FreezePositionX:this.constraints&=~st.FreezePositionX}set lockPositionY(s){s?this.constraints|=st.FreezePositionY:this.constraints&=~st.FreezePositionY}set lockPositionZ(s){s?this.constraints|=st.FreezePositionZ:this.constraints&=~st.FreezePositionZ}set lockRotationX(s){s?this.constraints|=st.FreezeRotationX:this.constraints&=~st.FreezeRotationX}set lockRotationY(s){s?this.constraints|=st.FreezeRotationY:this.constraints&=~st.FreezeRotationY}set lockRotationZ(s){s?this.constraints|=st.FreezeRotationZ:this.constraints&=~st.FreezeRotationZ}set gravityScale(s){this._gravityScale=s}get gravityScale(){return this._gravityScale}awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new sM(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),Me.LateUpdate),F()&&(globalThis.false?D.RAPIER_PHYSICS.ready().then(async()=>{var s;await Kl(3),(s=this.context.physics.engine)!=null&&s.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(){var s,t;(s=this._watch)==null||s.stop(),(t=this.context.physics.engine)==null||t.removeBody(this)}onDestroy(){var s;(s=this.context.physics.engine)==null||s.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){for(var s,t,i,n;;)this._propertiesChanged&&(this._propertiesChanged=!1,(s=this.context.physics.engine)==null||s.updateProperties(this)),(t=this._watch)!=null&&t.isDirty?(this._watch.mute=!0,this._watch.applyValues(),(i=this.context.physics.engine)==null||i.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):(n=this._watch)==null||n.syncValues(),this.captureVelocity(),yield}teleport(s,t=!0){var i;(i=this._watch)==null||i.reset(!0),t?this.gameObject.position.set(s.x,s.y,s.z):this.setWorldPosition(s.x,s.y,s.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(s=!0){var t;(t=this.context.physics.engine)==null||t.resetForces(this,s)}resetTorques(s=!0){var t;(t=this.context.physics.engine)==null||t.resetTorques(this,s)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){var s;(s=this.context.physics.engine)==null||s.wakeup(this)}get isSleeping(){var s;return(s=this.context.physics.engine)==null?void 0:s.isSleeping(this)}updateProperties(){var s;return this._propertiesChanged=!1,(s=this.context.physics.engine)==null?void 0:s.updateProperties(this)}applyForce(s,t,i=!0){var n;this._propertiesChanged&&this.updateProperties(),(n=this.context.physics.engine)==null||n.addForce(this,s,i)}applyImpulse(s,t=!0){var i;this._propertiesChanged&&this.updateProperties(),(i=this.context.physics.engine)==null||i.applyImpulse(this,s,t)}setForce(s,t,i,n=!0){var o,r,l;(o=this.context.physics.engine)==null||o.resetForces(this,n),typeof s=="number"?(t??(t=0),i??(i=0),(r=this.context.physics.engine)==null||r.addForce(this,{x:s,y:t,z:i},n)):(l=this.context.physics.engine)==null||l.addForce(this,s,n)}getVelocity(){var s;const t=(s=this.context.physics.engine)==null?void 0:s.getLinearVelocity(this);return t?(this._currentVelocity.x=t.x,this._currentVelocity.y=t.y,this._currentVelocity.z=t.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(s,t,i,n=!0){var o,r;if(s instanceof x){const l=s;(o=this.context.physics.engine)==null||o.setLinearVelocity(this,l,n);return}t===void 0||i===void 0||(r=this.context.physics.engine)==null||r.setLinearVelocity(this,{x:s,y:t,z:i},n)}getAngularVelocity(){var s;const t=(s=this.context.physics.engine)==null?void 0:s.getAngularVelocity(this);return t?(this._currentVelocity.x=t.x,this._currentVelocity.y=t.y,this._currentVelocity.z=t.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setAngularVelocity(s,t,i,n=!0){var o,r;if(typeof s=="object"){const l=s;(o=this.context.physics.engine)==null||o.setAngularVelocity(this,l,n);return}if(t===void 0||i===void 0||typeof t=="boolean"){console.warn("setAngularVelocity expects either a Vec3 or 3 numbers");return}(r=this.context.physics.engine)==null||r.setAngularVelocity(this,{x:s,y:t,z:i},n)}setTorque(s,t,i){typeof s=="number"?this.setAngularVelocity(s,t,i):this.setAngularVelocity(s)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(s=null){}captureVelocity(){const s=this.gameObject.matrixWorld;xu.tempPosition.setFromMatrixPosition(s);const t=xu.tempPosition.sub(this._lastPosition);this._lastPosition.copy(xu.tempPosition),this._smoothedVelocity.lerp(t,this.context.time.deltaTime/.1)}},a(df,"tempPosition",new x),df);let ye=xu;Ti([kt()],ye.prototype,"autoMass",2),Ti([m()],ye.prototype,"mass",1),Ti([kt(),m()],ye.prototype,"useGravity",2),Ti([m(x)],ye.prototype,"centerOfMass",2),Ti([kt(),m()],ye.prototype,"constraints",2),Ti([kt(),m()],ye.prototype,"isKinematic",2),Ti([kt(),m()],ye.prototype,"drag",2),Ti([kt(),m()],ye.prototype,"angularDrag",2),Ti([kt(),m()],ye.prototype,"detectCollisions",2),Ti([kt(),m()],ye.prototype,"sleepThreshold",2),Ti([kt(),m()],ye.prototype,"collisionDetectionMode",2),Ti([kt()],ye.prototype,"_gravityScale",2),Ti([kt()],ye.prototype,"dominanceGroup",2),new x,new x;const xo=C("debugsync"),zc="STRS";sg(zc,to.getRootAsSyncedTransformModel);const $s=new vm;function Mw(s,t,i=!0){$s.clear();const n=$s.createString(s);to.startSyncedTransformModel($s),to.addGuid($s,n),to.addFast($s,i);const o=t.worldPosition,r=t.worldEuler,l=t.gameObject.scale;to.addTransform($s,kw.createTransform($s,o.x,o.y,o.z,r.x,r.y,r.z,l.x,l.y,l.z));const c=to.endSyncedTransformModel($s);return $s.finish(c,zc),$s.asUint8Array()}let uf=0,Uc=0;Pw(s=>{var t;const i=(t=s.connection.currentServerUrl)!=null&&t.includes("glitch")?10:40;Uc=Math.floor(uf/i),uf=0,xo&&Uc>0&&console.log("Sync Transform Fast Interval",Uc)});class qs extends A{constructor(){super(...arguments),a(this,"overridePhysics",!0),a(this,"interpolatePosition",!0),a(this,"interpolateRotation",!0),a(this,"fastMode",!1),a(this,"syncDestroy",!1),a(this,"_model",null),a(this,"_needsUpdate",!0),a(this,"rb",null),a(this,"_wasKinematic",!1),a(this,"_receivedDataBefore",!1),a(this,"_targetPosition"),a(this,"_targetRotation"),a(this,"_receivedFastUpdate",!1),a(this,"_shouldRequestOwnership",!1),a(this,"joinedRoomCallback",null),a(this,"receivedDataCallback",null),a(this,"tempEuler",new Bt),a(this,"receivedUpdate",!1),a(this,"lastWorldPos"),a(this,"lastWorldRotation")}requestOwnership(){xo&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}hasOwnership(){var t;return((t=this._model)==null?void 0:t.hasOwnership)??void 0}isOwned(){var t;return(t=this._model)==null?void 0:t.isOwned}awake(){xo&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new x,this._targetRotation=new V,this.lastWorldPos=new x,this.lastWorldRotation=new V,this.rb=O.getComponentInChildren(this.gameObject,ye),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new rg(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(se.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(zc,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&Tg(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(se.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(zc,this.receivedDataCallback)}tryGetLastState(){const t=this.context.connection.tryGetState(this.guid);t&&this.onReceivedData(t)}onReceivedData(t){var i;if(!this.destroyed&&typeof t.guid=="function"&&t.guid()===this.guid){xo&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,t),this.receivedUpdate=!0,this._receivedFastUpdate=t.fast();const n=t.transform();if(n){as.markDirty(this.gameObject,!0);const o=n.position();o&&(this.interpolatePosition&&((i=this._targetPosition)==null||i.set(o.x(),o.y(),o.z())),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(o.x(),o.y(),o.z()));const r=n.rotation();r&&(this.tempEuler.set(r.x(),r.y(),r.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&Wm(this.gameObject,this.tempEuler))}this._receivedDataBefore=!0}}onEnable(){this.lastWorldPos.copy(this.worldPosition),this.lastWorldRotation.copy(this.worldQuaternion),this._needsUpdate=!0,this._model&&this._model.updateIsOwned()}onDisable(){this._model&&this._model.freeOwnership()}onBeforeRender(){if(!this.activeAndEnabled||!this.context.connection.isConnected)return;if(!this.context.connection.isInRoom||!this._model){xo&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());const t=this.worldPosition,i=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){const r=t.distanceTo(this.lastWorldPos),l=i.angleTo(this.lastWorldRotation),c=this._model.hasOwnership||this.fastMode?1e-4:.001;(r>c||l>c)&&(this._model.hasOwnership?this._needsUpdate=!0:(xo&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastWorldPos),this.worldPosition=this.lastWorldPos,t.copy(this.lastWorldPos),this.worldQuaternion=this.lastWorldRotation,i.copy(this.lastWorldRotation),as.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 l=!1;if(this.interpolatePosition&&this._targetPosition){const c=this.worldPosition;c.lerp(this._targetPosition,r),this.worldPosition=c,l=!0}if(this.interpolateRotation&&this._targetRotation){const c=this.worldQuaternion;c.slerp(this._targetRotation,r),this.worldQuaternion=c,l=!0}l&&as.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastWorldPos.copy(t),this.lastWorldRotation.copy(i),!this._model||!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership)return;this.rb&&this.overridePhysics&&this._wasKinematic!==void 0&&(xo&&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(uf++,o&&Uc>0&&this.context.time.frameCount%Uc!==0)return;xo&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this._needsUpdate=!1;const r=Mw(this.guid,this,!!o);this.context.connection.sendBinary(r)}}}const nM=C("debugshadowcomponents");gv.prototype.interactable={get(){return this.interactive},set(s){this.interactable=s}};const Ki=Symbol("shadowDomOwner");class rs extends A{constructor(){super(...arguments),a(this,"_shadowComponent",null),a(this,"_controlsChildLayout",!0),a(this,"_root"),a(this,"_parentComponent")}isRoot(){var t;return((t=this.Root)==null?void 0:t.gameObject)===this.gameObject}get canvas(){const t=this.Root;return t!=null&&t.isCanvas?t:null}get Canvas(){return this.canvas}markDirty(){si.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(t){this._shadowComponent=t}get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(t){this._controlsChildLayout=t,this.shadowComponent&&(this.shadowComponent.autoLayout=t)}get Root(){return this._root===void 0&&(this._root=O.getComponentInParent(this.gameObject,Nc)),this._root}__internalNewInstanceCreated(t){return super.__internalNewInstanceCreated(t),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0,this}onEnable(){super.onEnable()}addShadowComponent(t,i){var n;if(!t)return;this.removeShadowComponent();const o=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=O.getComponentInParent(o,rs),!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}t.name=this.name+" ("+(this.constructor.name??"UI")+")",t.autoLayout=this._parentComponent.controlsChildLayout,t[Ki]=this,this.setShadowComponentOwner(t);let r=!1;if(((n=this.Root)==null?void 0:n.gameObject)===this.gameObject)this.gameObject.add(t);else{const l=this._parentComponent.shadowComponent;l&&(l?.add(t),r=!0)}this.shadowComponent=t,i&&i.shadowComponent&&this.shadowComponent&&i.shadowComponent.add(this.shadowComponent),xc&&t.add(new xi(.5)),this.onAfterAddedToScene(),r&&pO(),nM&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(t){if(t&&(t[Ki]===void 0||t[Ki]===this)&&(t[Ki]=this,t.children))for(const i of t.children)this.setShadowComponentOwner(i)}traverseOwnedShadowComponents(t,i,n){if(t&&t[Ki]===i){n(t);for(const o of t.children)this.traverseOwnedShadowComponents(o,i,n)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(t){this.shadowComponent&&(this.shadowComponent.interactable=t)}}class Nc extends rs{awake(){super.awake()}}class id{constructor(t,i){a(this,"event"),a(this,"button"),a(this,"buttonName"),a(this,"_used",!1),a(this,"_propagationStopped",!1),a(this,"z__pointer_ctured",!1),a(this,"z__pointer_cture_rleased",!1),a(this,"inputSource"),a(this,"object"),a(this,"point"),a(this,"normal"),a(this,"face"),a(this,"distance"),a(this,"instanceId"),a(this,"intersection"),a(this,"isDown"),a(this,"isUp"),a(this,"isPressed"),a(this,"isClick"),a(this,"isDoubleClick"),a(this,"input"),this.event=i,this.input=t,this.button=i.button}get deviceIndex(){return this.event.deviceIndex}get pointerId(){return this.event.pointerId}get pressure(){return this.event.pressure}get used(){return this._used}use(){this._used||(this._used=!0,this.event.use())}get propagationStopped(){return this._propagationStopped}stopPropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}stopImmediatePropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}setPointerCapture(){this.z__pointer_ctured=!0}releasePointerCapture(){this.z__pointer_cture_rleased=!0}get mode(){return this.event.mode}clone(){const t=new id(this.input,this.event);return Object.assign(t,this),t}Use(){this.use()}StopPropagation(){this.event.stopImmediatePropagation()}}function Su(s,t){return O.foreachComponent(s,i=>{if(!i.enabled)return;const n=i;if(t)switch(t){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 Mn=new Array;class Rn{constructor(t,i,n,o){a(this,"enabled",!0),a(this,"target"),a(this,"methodName"),a(this,"arguments"),this.target=t,this.methodName=i||null,this.arguments=n,o!=null&&(this.enabled=o)}get canClone(){return this.target instanceof Object}invoke(...t){if(this.enabled!==!1){if(typeof this.target=="function")this.arguments?(Mn.length=0,t!==void 0&&t.length>0&&Mn.push(...t),Mn.push(...this.arguments),this.target(...this.arguments),Mn.length=0):this.target(...t);else if(this.methodName!=null){const i=this.target[this.methodName];typeof i=="function"?this.arguments?(Mn.length=0,t!==void 0&&t.length>0&&Mn.push(...t),Mn.push(...this.arguments),i.call(this.target,...Mn),Mn.length=0):i.call(this.target,...t):this.arguments?this.target[this.methodName]=this.arguments[0]||t[0]:this.target[this.methodName]=t[0]}}}}const oM=s=>/^[A-Z]*$/.test(s);class Cu extends Event{constructor(){super(...arguments),a(this,"args")}}class Se{constructor(t){if(a(this,"isEventList",!0),a(this,"target"),a(this,"key"),a(this,"_isInvoking",!1),a(this,"methods",[]),a(this,"_methodsCopy",[]),this.methods=[],Array.isArray(t))for(const i of t)i instanceof Rn?this.methods.push(i):typeof i=="function"&&this.methods.push(new Rn(i));else typeof t=="function"&&this.methods.push(new Rn(t))}__internalOnInstantiate(t){var i;const n=new Array;for(let o=0;o<this.methods.length;o++){const r=this.methods[o];if(!(r.target instanceof Function)){const l=r.target;let c=l?.uuid;if(l&&(c=l.guid),c){const h=t[c];if(h){const d=(i=r.arguments)==null?void 0:i.map(u=>u instanceof Object&&u.uuid?t[u.uuid]:u!=null&&u.isComponent?t[u.guid]:u);n.push(new Rn(h.clone,r.methodName,d,r.enabled))}else F()&&console.warn("Could not find target for event listener")}}}return new Se(n)}setEventTarget(t,i){if(this.key=t,this.target=i,this.key!==void 0){let n="",o=!1;for(const r of this.key)o&&oM(r)&&(n+="-"),o=!0,n+=r.toLowerCase();this.key=n}}get listenerCount(){var t;return((t=this.methods)==null?void 0:t.length)??0}get isInvoking(){return this._isInvoking}static from(...t){return new Se(t)}invoke(...t){var i;if(this._isInvoking)return console.warn("Circular event invocation detected. Please check your event listeners for circular references.",this),!1;if(((i=this.methods)==null?void 0:i.length)<=0)return!1;this._isInvoking=!0;try{this._methodsCopy.length=0,this._methodsCopy.push(...this.methods);for(const n of this._methodsCopy)n.invoke(...t);if(typeof this.target=="object"&&typeof this.key=="string"){const n=this.target.dispatchEvent;if(typeof n=="function"){const o=new Cu(this.key);o.args=t,n.call(this.target,o)}}}finally{this._isInvoking=!1,this._methodsCopy.length=0}return!0}addEventListener(t){return this.methods.push(new Rn(t)),t}removeEventListener(t){if(t)for(let i=this.methods.length-1;i>=0;i--)this.methods[i].target===t&&(this.methods[i].enabled=!1,this.methods.splice(i,1))}removeAllEventListeners(){this.methods.length=0}}class rM extends Qi{constructor(){super([ae,xe],"ColorSerializer")}onDeserialize(t){if(t!=null)return t.a!==void 0?new xe(t.r,t.g,t.b,t.a):t.alpha!==void 0?new xe(t.r,t.g,t.b,t.alpha):new ae(t.r,t.g,t.b)}onSerialize(t){if(t!=null)return t.a!==void 0?{r:t.r,g:t.g,b:t.b,a:t.a}:{r:t.r,g:t.g,b:t.b}}}const aM=new rM;class lM extends Qi{constructor(){super([Bt],"EulerSerializer")}onDeserialize(t,i){if(t!=null){if(t.order)return new Bt(t.x,t.y,t.z,t.order);if(t.x!=null)return new Bt(t.x,t.y,t.z)}}onSerialize(t,i){return{x:t.x,y:t.y,z:t.z,order:t.order}}}const cM=new lM;class hM extends Qi{constructor(){super(I,"ObjectSerializer")}onSerialize(t,i){if(i.objectToNode!==void 0&&t.uuid){const n=i.objectToNode[t.uuid];return vt&&console.log(n,t.name,t.uuid),{node:n}}}onDeserialize(t,i){var n,o,r;if(typeof t=="string"){if(t.endsWith(".glb")||t.endsWith(".gltf")){if(i.serializable instanceof Array&&i.serializable.includes(le))return;F()&&we("Detected wrong usage of @serializable with Object3D or GameObject. Instead you should use AssetReference here! Please see the console for details.");const l=(o=(n=i.target)==null?void 0:n.constructor)==null?void 0:o.name;console.warn(`Wrong usage of @serializable detected in your script "${l}"
915
+ `;var Gk=Object.defineProperty,Xk=Object.getOwnPropertyDescriptor,hf=(s,t,i,n)=>{for(var o=n>1?void 0:n?Xk(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&Gk(t,i,o),o};class Mr extends A{constructor(){super(...arguments),a(this,"constraintActive",!0),a(this,"locked",!1),a(this,"sources",[])}}hf([m()],Mr.prototype,"constraintActive",2),hf([m()],Mr.prototype,"locked",2),hf([m(I)],Mr.prototype,"sources",2);function Cw(s,t){return Sn(s,ge.ContextCreated,t),()=>uo(s,ge.ContextCreated)}function Qk(s,t){return Sn(s,ge.ContextClearing,t),()=>uo(s,ge.ContextClearing)}function Yk(s,t){return Sn(s,ge.ContextDestroying,t),()=>uo(s,ge.ContextDestroying)}function Ow(s,t){return Sn(s,Me.Start,t),()=>uo(s,Me.Start)}function Pw(s,t){return Sn(s,Me.Update,t),()=>uo(s,Me.Update)}function Zk(s,t){return Sn(s,Me.OnBeforeRender,t),()=>uo(s,Me.OnBeforeRender)}function Kk(s,t){return Sn(s,Me.OnAfterRender,t),()=>uo(s,Me.OnAfterRender)}let Rr=class{constructor(){a(this,"bb",null),a(this,"bb_pos",0)}__init(s,t){return this.bb_pos=s,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(s,t,i,n){return s.prep(4,12),s.writeFloat32(n),s.writeFloat32(i),s.writeFloat32(t),s.offset()}};class kw{constructor(){a(this,"bb",null),a(this,"bb_pos",0)}__init(t,i){return this.bb_pos=t,this.bb=i,this}position(t){return(t||new Rr).__init(this.bb_pos,this.bb)}rotation(t){return(t||new Rr).__init(this.bb_pos+12,this.bb)}scale(t){return(t||new Rr).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(t,i,n,o,r,l,c,h,d,u){return t.prep(4,36),t.prep(4,12),t.writeFloat32(u),t.writeFloat32(d),t.writeFloat32(h),t.prep(4,12),t.writeFloat32(c),t.writeFloat32(l),t.writeFloat32(r),t.prep(4,12),t.writeFloat32(o),t.writeFloat32(n),t.writeFloat32(i),t.offset()}}class to{constructor(){a(this,"bb",null),a(this,"bb_pos",0)}__init(t,i){return this.bb_pos=t,this.bb=i,this}static getRootAsSyncedTransformModel(t,i){return(i||new to).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSyncedTransformModel(t,i){return t.setPosition(t.position()+uv),(i||new to).__init(t.readInt32(t.position())+t.position(),t)}guid(t){const i=this.bb.__offset(this.bb_pos,4);return i?this.bb.__string(this.bb_pos+i,t):null}fast(){const t=this.bb.__offset(this.bb_pos,6);return t?!!this.bb.readInt8(this.bb_pos+t):!1}transform(t){const i=this.bb.__offset(this.bb_pos,8);return i?(t||new kw).__init(this.bb_pos+i,this.bb):null}dontSave(){const t=this.bb.__offset(this.bb_pos,10);return t?!!this.bb.readInt8(this.bb_pos+t):!1}static startSyncedTransformModel(t){t.startObject(4)}static addGuid(t,i){t.addFieldOffset(0,i,0)}static addFast(t,i){t.addFieldInt8(1,+i,0)}static addTransform(t,i){t.addFieldStruct(2,i,0)}static addDontSave(t,i){t.addFieldInt8(3,+i,0)}static endSyncedTransformModel(t){return t.endObject()}static finishSyncedTransformModelBuffer(t,i){t.finish(i)}static finishSizePrefixedSyncedTransformModelBuffer(t,i){t.finish(i,void 0,!0)}}var j;(s=>{(t=>{t.MAYBEMODULE=null;const i=[];function n(){return t.MODULE?Promise.resolve(t.MODULE):new Promise(r=>{i.push(r)})}t.ready=n;async function o(){if(t.MODULE)return t.MODULE;const r=await import("./rapier.light.min.js");return t.MODULE=r,t.MAYBEMODULE=r,i.forEach(l=>l(r)),i.length=0,r}t.load=o})(s.RAPIER_PHYSICS||(s.RAPIER_PHYSICS={})),(t=>{t.MAYBEMODULE=null;const i=[];function n(){return t.MODULE?Promise.resolve(t.MODULE):new Promise(r=>{i.push(r)})}t.ready=n;async function o(){if(t.MODULE)return t.MODULE;const r=await import("./postprocessing.light.min.js").then(l=>l.i);return t.MODULE=r,t.MAYBEMODULE=r,i.forEach(l=>l(r)),i.length=0,r}t.load=o})(s.POSTPROCESSING||(s.POSTPROCESSING={})),(t=>{t.MAYBEMODULE=null;const i=[];function n(){return t.MODULE?Promise.resolve(t.MODULE):new Promise(r=>{i.push(r)})}t.ready=n;async function o(){if(t.MODULE)return t.MODULE;const r=await import("./postprocessing.light.min.js").then(l=>l.N);return t.MODULE=r,t.MAYBEMODULE=r,i.forEach(l=>l(r)),i.length=0,r}t.load=o})(s.POSTPROCESSING_AO||(s.POSTPROCESSING_AO={}))})(j||(j={}));var _t=(s=>(s[s.Average=0]="Average",s[s.Multiply=1]="Multiply",s[s.Minimum=2]="Minimum",s[s.Maximum=3]="Maximum",s))(_t||{}),wu=(s=>(s[s.Discrete=0]="Discrete",s[s.Continuous=1]="Continuous",s))(wu||{}),st=(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))(st||{}),Na=(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))(Na||{});const kt=function(s,t){return function(i,n,o){Jk(i,n,o,s,t)}};function Jk(s,t,i,n,o){if(!o&&!n&&!s.onValidate)return;if(i!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",s,t,i),De("Invalid usage of validate decorator. Only fields can be validated. Property: "+t,Oi.Error);return}let r="";if(typeof t=="string"?r=t:r=t.name,s.__internalAwake){const l=Symbol(r),c=s.__internalAwake;s.__internalAwake=function(){var h;if(!this.onValidate){F()&&console.warn('Usage of @validate decorate detected but there is no onValidate method in your class: "'+((h=s.constructor)==null?void 0:h.name)+'"');return}if(this[l]===void 0){this[l]=this[r];const d=this[r];if(d instanceof re||d instanceof x||d instanceof fe||d instanceof V){const u=this[r];md(u,()=>{this.onValidate(r)})}Object.defineProperty(this,r,{set:function(u){var p;if(this[zg]===!0)this[l]=u;else{n?.call(this,u);const g=this[l];this[l]=u,(p=this.onValidate)==null||p.call(this,r,g)}},get:function(){return o?.call(this),this[l]}})}c.call(this)}}}const eM=function(s){return function(t,i,n){let o="";typeof i=="string"?o=i:o=i.name;const r=s.prototype,l=Object.getOwnPropertyDescriptor(r,o);if(!(l!=null&&l.value)){console.warn("Can not apply prefix: type does not have method named",i,s);return}const c=l.value,h=t[o];Object.defineProperty(r,o,{value:function(...d){const u=h?.call(this,...d);if(u instanceof Promise){u.then(p=>{if(p!==!1)return c.call(this,...d)});return}if(u!==!1)return c.call(this,...d)}})}};var tM=Object.defineProperty,iM=Object.getOwnPropertyDescriptor,Ti=(s,t,i,n)=>{for(var o=n>1?void 0:n?iM(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&tM(t,i,o),o};class sM{constructor(t,i){a(this,"positionChanged",!1),a(this,"rotationChanged",!1),a(this,"position"),a(this,"quaternion"),a(this,"_positionKeys",["x","y","z"]),a(this,"_quaternionKeys",["_x","_y","_z","_w"]),a(this,"mute",!1),a(this,"context"),a(this,"obj"),a(this,"_positionWatch"),a(this,"_rotationWatch"),this.context=i,this.obj=t}get isDirty(){return this.positionChanged||this.rotationChanged}reset(t=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,t){if(this.position)for(const i of this._positionKeys)delete this.position[i];if(this.quaternion)for(const i of this._quaternionKeys)delete this.quaternion[i]}}syncValues(){for(const t of this._positionKeys)this.position[t]=this.obj.position[t];for(const t of this._quaternionKeys)this.quaternion[t]=this.obj.quaternion[t]}applyValues(){if(this.positionChanged&&this.position)for(const t of this._positionKeys){const i=this.position[t];i!==void 0&&(this.obj.position[t]=i)}if(this.rotationChanged&&this.quaternion)for(const t of this._quaternionKeys){const i=this.quaternion[t];i!==void 0&&(this.obj.quaternion[t]=i)}}start(t,i){this.reset(),t&&(this._positionWatch||(this._positionWatch=new eo(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((r,l)=>{var c;if((c=this.context.physics.engine)!=null&&c.isUpdating||this.mute)return;const h=this.position[l];Math.abs(h-r)<1e-5||(this.position[l]=r,this.positionChanged=!0)})),i&&(this._rotationWatch||(this._rotationWatch=new eo(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((r,l)=>{var c;if((c=this.context.physics.engine)!=null&&c.isUpdating||this.mute)return;const h=this.quaternion[l];Math.abs(h-r)<1e-5||(this.quaternion[l]=r,this.rotationChanged=!0)}));const n=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),o=new ne;this.obj.matrixWorld.multiplyMatrices=(r,l)=>{var c;return(c=this.context.physics.engine)!=null&&c.isUpdating||this.mute||o.equals(r)||(this.positionChanged=!0,this.rotationChanged=!0,o.copy(r)),n(r,l)}}stop(){var t,i;(t=this._positionWatch)==null||t.revoke(),(i=this._rotationWatch)==null||i.revoke()}}var df;const xu=(df=class extends A{constructor(){super(...arguments),a(this,"autoMass",!0),a(this,"_mass",0),a(this,"useGravity",!0),a(this,"centerOfMass",new x(0,0,0)),a(this,"constraints",st.None),a(this,"isKinematic",!1),a(this,"drag",0),a(this,"angularDrag",1),a(this,"detectCollisions",!0),a(this,"sleepThreshold",.01),a(this,"collisionDetectionMode",wu.Discrete),a(this,"_gravityScale",1),a(this,"dominanceGroup",0),a(this,"_propertiesChanged",!1),a(this,"_currentVelocity",new x),a(this,"_smoothedVelocity",new x),a(this,"_smoothedVelocityGetter",new x),a(this,"_lastPosition",new x),a(this,"_watch")}get isRigidbody(){return!0}set mass(s){s!==this._mass&&(this._mass=s,this._propertiesChanged=!0,this.__didAwake&&(this.autoMass=!1))}get mass(){var s,t;return this.autoMass?((t=(s=this.context.physics.engine)==null?void 0:s.getBody(this))==null?void 0:t.mass())??-1:this._mass}get lockPositionX(){return(this.constraints&st.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&st.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&st.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&st.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&st.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&st.FreezeRotationZ)!==0}set lockPositionX(s){s?this.constraints|=st.FreezePositionX:this.constraints&=~st.FreezePositionX}set lockPositionY(s){s?this.constraints|=st.FreezePositionY:this.constraints&=~st.FreezePositionY}set lockPositionZ(s){s?this.constraints|=st.FreezePositionZ:this.constraints&=~st.FreezePositionZ}set lockRotationX(s){s?this.constraints|=st.FreezeRotationX:this.constraints&=~st.FreezeRotationX}set lockRotationY(s){s?this.constraints|=st.FreezeRotationY:this.constraints&=~st.FreezeRotationY}set lockRotationZ(s){s?this.constraints|=st.FreezeRotationZ:this.constraints&=~st.FreezeRotationZ}set gravityScale(s){this._gravityScale=s}get gravityScale(){return this._gravityScale}awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new sM(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),Me.LateUpdate),F()&&(globalThis.false?j.RAPIER_PHYSICS.ready().then(async()=>{var s;await Kl(3),(s=this.context.physics.engine)!=null&&s.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(){var s,t;(s=this._watch)==null||s.stop(),(t=this.context.physics.engine)==null||t.removeBody(this)}onDestroy(){var s;(s=this.context.physics.engine)==null||s.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){for(var s,t,i,n;;)this._propertiesChanged&&(this._propertiesChanged=!1,(s=this.context.physics.engine)==null||s.updateProperties(this)),(t=this._watch)!=null&&t.isDirty?(this._watch.mute=!0,this._watch.applyValues(),(i=this.context.physics.engine)==null||i.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):(n=this._watch)==null||n.syncValues(),this.captureVelocity(),yield}teleport(s,t=!0){var i;(i=this._watch)==null||i.reset(!0),t?this.gameObject.position.set(s.x,s.y,s.z):this.setWorldPosition(s.x,s.y,s.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(s=!0){var t;(t=this.context.physics.engine)==null||t.resetForces(this,s)}resetTorques(s=!0){var t;(t=this.context.physics.engine)==null||t.resetTorques(this,s)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){var s;(s=this.context.physics.engine)==null||s.wakeup(this)}get isSleeping(){var s;return(s=this.context.physics.engine)==null?void 0:s.isSleeping(this)}updateProperties(){var s;return this._propertiesChanged=!1,(s=this.context.physics.engine)==null?void 0:s.updateProperties(this)}applyForce(s,t,i=!0){var n;this._propertiesChanged&&this.updateProperties(),(n=this.context.physics.engine)==null||n.addForce(this,s,i)}applyImpulse(s,t=!0){var i;this._propertiesChanged&&this.updateProperties(),(i=this.context.physics.engine)==null||i.applyImpulse(this,s,t)}setForce(s,t,i,n=!0){var o,r,l;(o=this.context.physics.engine)==null||o.resetForces(this,n),typeof s=="number"?(t??(t=0),i??(i=0),(r=this.context.physics.engine)==null||r.addForce(this,{x:s,y:t,z:i},n)):(l=this.context.physics.engine)==null||l.addForce(this,s,n)}getVelocity(){var s;const t=(s=this.context.physics.engine)==null?void 0:s.getLinearVelocity(this);return t?(this._currentVelocity.x=t.x,this._currentVelocity.y=t.y,this._currentVelocity.z=t.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(s,t,i,n=!0){var o,r;if(s instanceof x){const l=s;(o=this.context.physics.engine)==null||o.setLinearVelocity(this,l,n);return}t===void 0||i===void 0||(r=this.context.physics.engine)==null||r.setLinearVelocity(this,{x:s,y:t,z:i},n)}getAngularVelocity(){var s;const t=(s=this.context.physics.engine)==null?void 0:s.getAngularVelocity(this);return t?(this._currentVelocity.x=t.x,this._currentVelocity.y=t.y,this._currentVelocity.z=t.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setAngularVelocity(s,t,i,n=!0){var o,r;if(typeof s=="object"){const l=s;(o=this.context.physics.engine)==null||o.setAngularVelocity(this,l,n);return}if(t===void 0||i===void 0||typeof t=="boolean"){console.warn("setAngularVelocity expects either a Vec3 or 3 numbers");return}(r=this.context.physics.engine)==null||r.setAngularVelocity(this,{x:s,y:t,z:i},n)}setTorque(s,t,i){typeof s=="number"?this.setAngularVelocity(s,t,i):this.setAngularVelocity(s)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(s=null){}captureVelocity(){const s=this.gameObject.matrixWorld;xu.tempPosition.setFromMatrixPosition(s);const t=xu.tempPosition.sub(this._lastPosition);this._lastPosition.copy(xu.tempPosition),this._smoothedVelocity.lerp(t,this.context.time.deltaTime/.1)}},a(df,"tempPosition",new x),df);let ye=xu;Ti([kt()],ye.prototype,"autoMass",2),Ti([m()],ye.prototype,"mass",1),Ti([kt(),m()],ye.prototype,"useGravity",2),Ti([m(x)],ye.prototype,"centerOfMass",2),Ti([kt(),m()],ye.prototype,"constraints",2),Ti([kt(),m()],ye.prototype,"isKinematic",2),Ti([kt(),m()],ye.prototype,"drag",2),Ti([kt(),m()],ye.prototype,"angularDrag",2),Ti([kt(),m()],ye.prototype,"detectCollisions",2),Ti([kt(),m()],ye.prototype,"sleepThreshold",2),Ti([kt(),m()],ye.prototype,"collisionDetectionMode",2),Ti([kt()],ye.prototype,"_gravityScale",2),Ti([kt()],ye.prototype,"dominanceGroup",2),new x,new x;const xo=C("debugsync"),zc="STRS";sg(zc,to.getRootAsSyncedTransformModel);const $s=new vm;function Mw(s,t,i=!0){$s.clear();const n=$s.createString(s);to.startSyncedTransformModel($s),to.addGuid($s,n),to.addFast($s,i);const o=t.worldPosition,r=t.worldEuler,l=t.gameObject.scale;to.addTransform($s,kw.createTransform($s,o.x,o.y,o.z,r.x,r.y,r.z,l.x,l.y,l.z));const c=to.endSyncedTransformModel($s);return $s.finish(c,zc),$s.asUint8Array()}let uf=0,Uc=0;Pw(s=>{var t;const i=(t=s.connection.currentServerUrl)!=null&&t.includes("glitch")?10:40;Uc=Math.floor(uf/i),uf=0,xo&&Uc>0&&console.log("Sync Transform Fast Interval",Uc)});class qs extends A{constructor(){super(...arguments),a(this,"overridePhysics",!0),a(this,"interpolatePosition",!0),a(this,"interpolateRotation",!0),a(this,"fastMode",!1),a(this,"syncDestroy",!1),a(this,"_model",null),a(this,"_needsUpdate",!0),a(this,"rb",null),a(this,"_wasKinematic",!1),a(this,"_receivedDataBefore",!1),a(this,"_targetPosition"),a(this,"_targetRotation"),a(this,"_receivedFastUpdate",!1),a(this,"_shouldRequestOwnership",!1),a(this,"joinedRoomCallback",null),a(this,"receivedDataCallback",null),a(this,"tempEuler",new Bt),a(this,"receivedUpdate",!1),a(this,"lastWorldPos"),a(this,"lastWorldRotation")}requestOwnership(){xo&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}hasOwnership(){var t;return((t=this._model)==null?void 0:t.hasOwnership)??void 0}isOwned(){var t;return(t=this._model)==null?void 0:t.isOwned}awake(){xo&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new x,this._targetRotation=new V,this.lastWorldPos=new x,this.lastWorldRotation=new V,this.rb=O.getComponentInChildren(this.gameObject,ye),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new rg(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(se.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(zc,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&Tg(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(se.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(zc,this.receivedDataCallback)}tryGetLastState(){const t=this.context.connection.tryGetState(this.guid);t&&this.onReceivedData(t)}onReceivedData(t){var i;if(!this.destroyed&&typeof t.guid=="function"&&t.guid()===this.guid){xo&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,t),this.receivedUpdate=!0,this._receivedFastUpdate=t.fast();const n=t.transform();if(n){as.markDirty(this.gameObject,!0);const o=n.position();o&&(this.interpolatePosition&&((i=this._targetPosition)==null||i.set(o.x(),o.y(),o.z())),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(o.x(),o.y(),o.z()));const r=n.rotation();r&&(this.tempEuler.set(r.x(),r.y(),r.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&Wm(this.gameObject,this.tempEuler))}this._receivedDataBefore=!0}}onEnable(){this.lastWorldPos.copy(this.worldPosition),this.lastWorldRotation.copy(this.worldQuaternion),this._needsUpdate=!0,this._model&&this._model.updateIsOwned()}onDisable(){this._model&&this._model.freeOwnership()}onBeforeRender(){if(!this.activeAndEnabled||!this.context.connection.isConnected)return;if(!this.context.connection.isInRoom||!this._model){xo&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());const t=this.worldPosition,i=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){const r=t.distanceTo(this.lastWorldPos),l=i.angleTo(this.lastWorldRotation),c=this._model.hasOwnership||this.fastMode?1e-4:.001;(r>c||l>c)&&(this._model.hasOwnership?this._needsUpdate=!0:(xo&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastWorldPos),this.worldPosition=this.lastWorldPos,t.copy(this.lastWorldPos),this.worldQuaternion=this.lastWorldRotation,i.copy(this.lastWorldRotation),as.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 l=!1;if(this.interpolatePosition&&this._targetPosition){const c=this.worldPosition;c.lerp(this._targetPosition,r),this.worldPosition=c,l=!0}if(this.interpolateRotation&&this._targetRotation){const c=this.worldQuaternion;c.slerp(this._targetRotation,r),this.worldQuaternion=c,l=!0}l&&as.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastWorldPos.copy(t),this.lastWorldRotation.copy(i),!this._model||!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership)return;this.rb&&this.overridePhysics&&this._wasKinematic!==void 0&&(xo&&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(uf++,o&&Uc>0&&this.context.time.frameCount%Uc!==0)return;xo&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this._needsUpdate=!1;const r=Mw(this.guid,this,!!o);this.context.connection.sendBinary(r)}}}const nM=C("debugshadowcomponents");gv.prototype.interactable={get(){return this.interactive},set(s){this.interactable=s}};const Ki=Symbol("shadowDomOwner");class rs extends A{constructor(){super(...arguments),a(this,"_shadowComponent",null),a(this,"_controlsChildLayout",!0),a(this,"_root"),a(this,"_parentComponent")}isRoot(){var t;return((t=this.Root)==null?void 0:t.gameObject)===this.gameObject}get canvas(){const t=this.Root;return t!=null&&t.isCanvas?t:null}get Canvas(){return this.canvas}markDirty(){si.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(t){this._shadowComponent=t}get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(t){this._controlsChildLayout=t,this.shadowComponent&&(this.shadowComponent.autoLayout=t)}get Root(){return this._root===void 0&&(this._root=O.getComponentInParent(this.gameObject,Nc)),this._root}__internalNewInstanceCreated(t){return super.__internalNewInstanceCreated(t),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0,this}onEnable(){super.onEnable()}addShadowComponent(t,i){var n;if(!t)return;this.removeShadowComponent();const o=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=O.getComponentInParent(o,rs),!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}t.name=this.name+" ("+(this.constructor.name??"UI")+")",t.autoLayout=this._parentComponent.controlsChildLayout,t[Ki]=this,this.setShadowComponentOwner(t);let r=!1;if(((n=this.Root)==null?void 0:n.gameObject)===this.gameObject)this.gameObject.add(t);else{const l=this._parentComponent.shadowComponent;l&&(l?.add(t),r=!0)}this.shadowComponent=t,i&&i.shadowComponent&&this.shadowComponent&&i.shadowComponent.add(this.shadowComponent),xc&&t.add(new xi(.5)),this.onAfterAddedToScene(),r&&pO(),nM&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(t){if(t&&(t[Ki]===void 0||t[Ki]===this)&&(t[Ki]=this,t.children))for(const i of t.children)this.setShadowComponentOwner(i)}traverseOwnedShadowComponents(t,i,n){if(t&&t[Ki]===i){n(t);for(const o of t.children)this.traverseOwnedShadowComponents(o,i,n)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(t){this.shadowComponent&&(this.shadowComponent.interactable=t)}}class Nc extends rs{awake(){super.awake()}}class id{constructor(t,i){a(this,"event"),a(this,"button"),a(this,"buttonName"),a(this,"_used",!1),a(this,"_propagationStopped",!1),a(this,"z__pointer_ctured",!1),a(this,"z__pointer_cture_rleased",!1),a(this,"inputSource"),a(this,"object"),a(this,"point"),a(this,"normal"),a(this,"face"),a(this,"distance"),a(this,"instanceId"),a(this,"intersection"),a(this,"isDown"),a(this,"isUp"),a(this,"isPressed"),a(this,"isClick"),a(this,"isDoubleClick"),a(this,"input"),this.event=i,this.input=t,this.button=i.button}get deviceIndex(){return this.event.deviceIndex}get pointerId(){return this.event.pointerId}get pressure(){return this.event.pressure}get used(){return this._used}use(){this._used||(this._used=!0,this.event.use())}get propagationStopped(){return this._propagationStopped}stopPropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}stopImmediatePropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}setPointerCapture(){this.z__pointer_ctured=!0}releasePointerCapture(){this.z__pointer_cture_rleased=!0}get mode(){return this.event.mode}clone(){const t=new id(this.input,this.event);return Object.assign(t,this),t}Use(){this.use()}StopPropagation(){this.event.stopImmediatePropagation()}}function Su(s,t){return O.foreachComponent(s,i=>{if(!i.enabled)return;const n=i;if(t)switch(t){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 Mn=new Array;class Rn{constructor(t,i,n,o){a(this,"enabled",!0),a(this,"target"),a(this,"methodName"),a(this,"arguments"),this.target=t,this.methodName=i||null,this.arguments=n,o!=null&&(this.enabled=o)}get canClone(){return this.target instanceof Object}invoke(...t){if(this.enabled!==!1){if(typeof this.target=="function")this.arguments?(Mn.length=0,t!==void 0&&t.length>0&&Mn.push(...t),Mn.push(...this.arguments),this.target(...this.arguments),Mn.length=0):this.target(...t);else if(this.methodName!=null){const i=this.target[this.methodName];typeof i=="function"?this.arguments?(Mn.length=0,t!==void 0&&t.length>0&&Mn.push(...t),Mn.push(...this.arguments),i.call(this.target,...Mn),Mn.length=0):i.call(this.target,...t):this.arguments?this.target[this.methodName]=this.arguments[0]||t[0]:this.target[this.methodName]=t[0]}}}}const oM=s=>/^[A-Z]*$/.test(s);class Cu extends Event{constructor(){super(...arguments),a(this,"args")}}class Se{constructor(t){if(a(this,"isEventList",!0),a(this,"target"),a(this,"key"),a(this,"_isInvoking",!1),a(this,"methods",[]),a(this,"_methodsCopy",[]),this.methods=[],Array.isArray(t))for(const i of t)i instanceof Rn?this.methods.push(i):typeof i=="function"&&this.methods.push(new Rn(i));else typeof t=="function"&&this.methods.push(new Rn(t))}__internalOnInstantiate(t){var i;const n=new Array;for(let o=0;o<this.methods.length;o++){const r=this.methods[o];if(!(r.target instanceof Function)){const l=r.target;let c=l?.uuid;if(l&&(c=l.guid),c){const h=t[c];if(h){const d=(i=r.arguments)==null?void 0:i.map(u=>u instanceof Object&&u.uuid?t[u.uuid]:u!=null&&u.isComponent?t[u.guid]:u);n.push(new Rn(h.clone,r.methodName,d,r.enabled))}else F()&&console.warn("Could not find target for event listener")}}}return new Se(n)}setEventTarget(t,i){if(this.key=t,this.target=i,this.key!==void 0){let n="",o=!1;for(const r of this.key)o&&oM(r)&&(n+="-"),o=!0,n+=r.toLowerCase();this.key=n}}get listenerCount(){var t;return((t=this.methods)==null?void 0:t.length)??0}get isInvoking(){return this._isInvoking}static from(...t){return new Se(t)}invoke(...t){var i;if(this._isInvoking)return console.warn("Circular event invocation detected. Please check your event listeners for circular references.",this),!1;if(((i=this.methods)==null?void 0:i.length)<=0)return!1;this._isInvoking=!0;try{this._methodsCopy.length=0,this._methodsCopy.push(...this.methods);for(const n of this._methodsCopy)n.invoke(...t);if(typeof this.target=="object"&&typeof this.key=="string"){const n=this.target.dispatchEvent;if(typeof n=="function"){const o=new Cu(this.key);o.args=t,n.call(this.target,o)}}}finally{this._isInvoking=!1,this._methodsCopy.length=0}return!0}addEventListener(t){return this.methods.push(new Rn(t)),t}removeEventListener(t){if(t)for(let i=this.methods.length-1;i>=0;i--)this.methods[i].target===t&&(this.methods[i].enabled=!1,this.methods.splice(i,1))}removeAllEventListeners(){this.methods.length=0}}class rM extends Qi{constructor(){super([ae,xe],"ColorSerializer")}onDeserialize(t){if(t!=null)return t.a!==void 0?new xe(t.r,t.g,t.b,t.a):t.alpha!==void 0?new xe(t.r,t.g,t.b,t.alpha):new ae(t.r,t.g,t.b)}onSerialize(t){if(t!=null)return t.a!==void 0?{r:t.r,g:t.g,b:t.b,a:t.a}:{r:t.r,g:t.g,b:t.b}}}const aM=new rM;class lM extends Qi{constructor(){super([Bt],"EulerSerializer")}onDeserialize(t,i){if(t!=null){if(t.order)return new Bt(t.x,t.y,t.z,t.order);if(t.x!=null)return new Bt(t.x,t.y,t.z)}}onSerialize(t,i){return{x:t.x,y:t.y,z:t.z,order:t.order}}}const cM=new lM;class hM extends Qi{constructor(){super(I,"ObjectSerializer")}onSerialize(t,i){if(i.objectToNode!==void 0&&t.uuid){const n=i.objectToNode[t.uuid];return vt&&console.log(n,t.name,t.uuid),{node:n}}}onDeserialize(t,i){var n,o,r;if(typeof t=="string"){if(t.endsWith(".glb")||t.endsWith(".gltf")){if(i.serializable instanceof Array&&i.serializable.includes(le))return;F()&&we("Detected wrong usage of @serializable with Object3D or GameObject. Instead you should use AssetReference here! Please see the console for details.");const l=(o=(n=i.target)==null?void 0:n.constructor)==null?void 0:o.name;console.warn(`Wrong usage of @serializable detected in your script "${l}"
912
916
 
913
917
  It looks like you used @serializable(Object3D) or @serializable(GameObject) for a prefab or scene reference which is exported to a separate glTF file.
914
918
 
@@ -920,7 +924,7 @@ ${i.path}! : AssetReference;
920
924
  Could not find method ${d.method} on object ${p.name}. Please rename ${d.method} to ${f}?
921
925
  `,p[f],`
922
926
  in script: `,p),we("EventList methods must start with lowercase letter, see console for details");return}else console.warn(`EventList method:
923
- Could not find method ${d.method} on object ${p.name}`,p,typeof p[d.method])};if(typeof p[d.method]!="function"){let f=!1,v=p;for(;v;){const b=Object.getOwnPropertyDescriptor(v,d.method);if(b&&(b.writable===!0||b.set)){f=!0;break}v=Object.getPrototypeOf(v)}!f&&(F()||vt)&&y()}}if(p){let y=d.argument;if(y!==void 0?y=u(y):d.arguments!==void 0&&(y=d.arguments.map(u)),!p[d.method])console.warn(`EventList method not found: "${d.method}" on ${p?.name}`);else{y!==void 0&&!Array.isArray(y)&&(y=[y]);const f=new Rn(p,d.method,y,d.enabled);l.push(f)}}else F()&&console.warn("[Debug] EventList: Could not find event listener in scene",d,i.object,t)}const c=new Se(l);vt&&console.log(c);const h=i.target;return h!==void 0&&i.path!==void 0&&c.setEventTarget(i.path,h),c}}}const pM=new uM,Pu=new WeakMap,mM=Le.prototype.clone;Le.prototype.clone=function(){const s=mM.call(this);return Pu.has(s)||Pu.set(s,this),s};class Tw extends Qi{constructor(){super([Ua,vn])}onSerialize(t,i){}onDeserialize(t,i){if(t instanceof Le&&i.type===Ua){let n=t;Pu.has(n)&&(n=Pu.get(n)),n.isRenderTargetTexture=!0,n.flipY=!0,n.offset.y=1,n.repeat.y=-1,n.needsUpdate=!0,n.mipmaps=[],n instanceof jS&&(n.isCompressedTexture=!1,n.format=ad);const o=new Ua(n.image.width,n.image.height,{colorSpace:or});return o.texture=n,o}}}new Tw;class Ew extends Qi{constructor(){super([URL])}onSerialize(t,i){return null}onDeserialize(t,i){if(typeof t=="string"&&t.length>0)return lo(i.gltfId,t)}}new Ew;var gM=Object.defineProperty,fM=Object.getOwnPropertyDescriptor,yM=(s,t,i,n)=>{for(var o=n>1?void 0:n?fM(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&gM(t,i,o),o};class Wa extends A{awake(){si.createIfNoneExists(this.context)}onEnable(){var t;(t=si.get(this.context))==null||t.register(this)}onDisable(){var t;(t=si.get(this.context))==null||t.unregister(this)}}class Ei extends Wa{constructor(){super(...arguments),a(this,"targets",null),a(this,"raycastHits",[]),a(this,"ignoreSkinnedMeshes",!1)}start(){this.targets=[this.gameObject]}performRaycast(t=null){if(!this.targets)return null;t??(t=new Ws),t.targets=this.targets,t.results=this.raycastHits,t.useAcceleratedRaycast=!0;const i=t.testObject;this.ignoreSkinnedMeshes&&(t.testObject=o=>o instanceof fn?"continue in children":i?i(o):!0);const n=this.context.physics.raycast(t);return t.testObject=i,n}}yM([m()],Ei.prototype,"ignoreSkinnedMeshes",2);class ku extends Ei{constructor(){super(),this.ignoreSkinnedMeshes=!0}}const Aw=class extends Wa{performRaycast(s){if(!J.active||!Aw.allow||!(s!=null&&s.ray))return null;const t=s.ray.origin,i=.015;return this.context.physics.sphereOverlap(t,i,!1,!0)}};let Va=Aw;a(Va,"allow",!0);class pf{static getObject(t){const i=t[Ki];return i&&(i.isComponent===!0?t=i.gameObject:t=i),t}static isInteractable(t,i){if(i&&(i.canvasGroup=void 0,i.graphic=void 0),t==null||!t.visible||(t=this.getObject(t),!t.visible))return!1;const n=this.tryFindCanvasGroup(t);if(n?.isCanvasGroup===!0&&(i&&(i.canvasGroup=n),n.blocksRaycasts===!1||n.interactable===!1))return!1;const o=br(t,r=>{if(r.isGraphic===!0)return r},!1);return i&&o?.isGraphic===!0&&(i.graphic=o),!(o?.raycastTarget===!1||o?.layer===2)}static tryFindCanvasGroup(t){if(!t)return null;const i=br(t,n=>{const o=n;if(o.blocksRaycasts!==void 0&&o.interactable!==void 0)return o},!1);return i!==void 0?i:this.tryFindCanvasGroup(t.parent)}}function mf(s){return s[Ki]||(s.parent?mf(s.parent):null)}function vM(s){return s.isUI===!0||typeof s[Ki]=="object"}function Mu(s,t){if(!s)return;const i=s.material;if(i?.isMaterial===!0){const n=s.parent;n&&n.isText,i.side=t.doubleSided??!0?Si:ao,i.shadowSide=t.doubleSided?Si:ao,s.castShadow=t.castShadows?t.castShadows:!1,s.receiveShadow=t.receiveShadows?t.receiveShadows:!1}for(const n of s.children)Mu(n,t)}function Ha(s,t,i){s[t]===void 0&&console.warn("Field",t,"is undefined on",s);const n=Proxy.revocable(s[t],{set(l,c,h,d){const u=l[c],p=Reflect.set(l,c,h,d);return i(h,u),p}}),o=n.revoke,r=s[t];return n.revoke=()=>{s[t]=r,o()},s[t]=n.proxy,n}const Iw=Symbol("Scheduled action");function bM(s,t,i=Me.OnBeforeRender){let n=s[Iw];n||(n=s[Iw]={});const o=t.name;n[i]||(n[i]={});const r=n[i];if(r[o])return;function*l(){t?.call(s),r[o]=null}const c=s.startCoroutine(l(),i);r[o]=c}const So=C("debugeventsystem");var gf=(s=>(s.BeforeHandleInput="BeforeHandleInput",s.AfterHandleInput="AfterHandleInput",s))(gf||{});Cw(s=>{si.createIfNoneExists(s)});class si extends A{constructor(){super(...arguments),a(this,"raycaster",[]),a(this,"pressedByID",new Map),a(this,"hoveredByID",new Map),a(this,"onPointerEvent",t=>{if(t===void 0||t.propagationStopped||t.defaultPrevented||t.used)return;const i=new id(this.context.input,t);this._currentPointerEventName=t.type,i.inputSource=this.context.input,i.isClick=t.isClick,i.isDoubleClick=t.isDoubleClick,i.isDown=t.type==Be.PointerDown,i.isUp=t.type==Be.PointerUp,i.isPressed=this.context.input.getPointerPressed(t.pointerId),So&&(i.isDown?console.log("DOWN",i.pointerId):i.isUp&&console.log("UP",i.pointerId),i.isClick&&console.log("CLICK",i.pointerId));const n=new Ws;t.hasRay?n.ray=t.ray:n.screenPoint=this.context.input.getPointerPositionRC(t.pointerId);const o=this.performRaycast(n);if(o){for(const l of o)l.event=t,t.intersections.push(l);t.origin.onPointerHits&&t.origin.onPointerHits({sender:this,event:t,hits:o})}So&&i.isClick&&De("EventSystem: "+i.pointerId+" - "+this.context.time.frame+" - Up:"+i.isUp+", Down:"+i.isDown);const r={sender:this,args:i,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:r})),this.handleIntersections(o,i),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:r}))}),a(this,"_sortedHits",[]),a(this,"_testObjectsCache",new Map),a(this,"_currentlyActiveRaycaster",null),a(this,"_currentPointerEventName",null),a(this,"shouldRaycastObject",t=>{var i;const n=t&&"getComponent"in t?t.getComponent(Wa):null;if(n&&n!=this._currentlyActiveRaycaster)return!1;let o=null;if(vM(t)&&(o=(i=t[Ki])==null?void 0:i.gameObject),this._testObjectsCache.has(t)||o&&this._testObjectsCache.has(o))return this._testObjectsCache.get(t)===!1?"continue in children":!0;{let r=Su(t,this._currentPointerEventName);if(!r&&o&&(r=Su(o,this._currentPointerEventName)),r){this._testObjectsCache.set(t,!0);for(const l of t.children)this.shouldRaycastObject_AddToYesCache(l);return!0}return this._testObjectsCache.set(t,!1),"continue in children"}}),a(this,"_sortingBuffer",[]),a(this,"_noDepthTestingResults",[]),a(this,"out",{}),a(this,"_capturedPointer",{}),a(this,"pointerEnterSymbol",Symbol("pointerEnter")),a(this,"pointerExitSymbol",Symbol("pointerExit")),a(this,"currentActiveMeshUIComponents",[])}static ensureUpdateMeshUI(t,i,n=!1){Co.update(t,i,n)}static markUIDirty(t){Co.markDirty()}static createIfNoneExists(t){t.scene.getComponent(si)||t.scene.addComponent(si)}static get(t){return this.createIfNoneExists(t),t.scene.getComponent(si)}static get instance(){return this.get(ee.Current)}register(t){var i;t&&this.raycaster&&!this.raycaster.includes(t)&&((i=this.raycaster)==null||i.push(t))}unregister(t){var i,n;const o=(i=this.raycaster)==null?void 0:i.indexOf(t);o!==void 0&&o!==-1&&((n=this.raycaster)==null||n.splice(o,1))}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}awake(){this.gameObject!==this.context.scene&&(this.enabled=!1)}start(){this.context.scene.getComponent(Wa)||this.context.scene.addComponent(Ei)}onEnable(){this.context.input.addEventListener(Be.PointerDown,this.onPointerEvent),this.context.input.addEventListener(Be.PointerUp,this.onPointerEvent),this.context.input.addEventListener(Be.PointerMove,this.onPointerEvent)}onDisable(){this.context.input.removeEventListener(Be.PointerDown,this.onPointerEvent),this.context.input.removeEventListener(Be.PointerUp,this.onPointerEvent),this.context.input.removeEventListener(Be.PointerMove,this.onPointerEvent)}onBeforeRender(){this.resetMeshUIStates()}shouldRaycastObject_AddToYesCache(t){this._testObjectsCache.set(t,!0);for(const i of t.children)this.shouldRaycastObject_AddToYesCache(i)}performRaycast(t){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,t||(t=new Ws),t.testObject=this.shouldRaycastObject;for(const i of this.raycaster){if(!i.activeAndEnabled)continue;this._currentlyActiveRaycaster=i;const n=i.performRaycast(t);this._currentlyActiveRaycaster=null,n&&n.length>0&&this._sortedHits.push(...n)}return this._sortedHits.sort((i,n)=>i.distance-n.distance),this._sortedHits}assignHitInformation(t,i){i?(t.intersection=i,t.point=i.point,t.normal=i.normal,t.face=i.face,t.distance=i.distance,t.instanceId=i.instanceId):(t.intersection=void 0,t.point=void 0,t.normal=void 0,t.face=void 0,t.distance=void 0,t.instanceId=void 0)}handleIntersections(t,i){var n;if(t!=null&&t.length){t=this.sortCandidates(t);for(const r of t){if(i.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(i,r),this.handleEventOnObject(r.object,i))return!0}}this.assignHitInformation(i,t?.[0]),this.invokePointerCapture(i);const o=this.hoveredByID.get(i.pointerId);return o&&this.propagatePointerExit(o.obj,o.data,null),this.hoveredByID.delete(i.pointerId),i.isUp&&((n=this.pressedByID.get(i.pointerId))==null||n.handlers.forEach(r=>this.invokeOnPointerUp(i,r)),this.pressedByID.delete(i.pointerId)),!1}sortCandidates(t){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let i=0;i<t.length;i++){const n=t[i],o=n.object;if(o.material&&o.material.depthTest===!1){this._noDepthTestingResults.push(n);continue}this._sortingBuffer.push(n)}for(const i of this._sortingBuffer)this._noDepthTestingResults.push(i);return this._noDepthTestingResults}handleEventOnObject(t,i){if(!this.testIsVisible(t))return i.isClick&&So&&console.log("not allowed",t),!1;if(i.pointerId===void 0)return So&&console.error("Event without pointer can't be handled",i),!1;i.object=t;const n=t.parent,o=i.isClick??!1;let r=null;if(n&&n.isUI){const d=(i.isPressed||i.isClick)??!1;if(n[Ki]){const u=n[Ki].gameObject;if(u){if(!pf.isInteractable(u,this.out))return!1;r=this.out.canvasGroup??null,this.handleMeshUIIntersection(t,d),t=u}}}o&&So&&console.log(this.context.time.frame,t);const l=this.hoveredByID.get(i.pointerId),c=l?.obj;c!==t&&c&&this.propagatePointerExit(c,l.data,t);const h=this.hoveredByID.get(i.pointerId);if(h?(h.obj=t,h.data=i):this.hoveredByID.set(i.pointerId,{obj:t,data:i}),i.isDown){const d=this.pressedByID.get(i.pointerId);d?(d.obj=t,d.data=i):this.pressedByID.set(i.pointerId,{obj:t,data:i,handlers:new Set})}return(r===null||r.interactable)&&this.handleMainInteraction(t,i,c??null),!0}propagate(t,i){for(;t;)O.foreachComponent(t,n=>{i(n)},!1),t=t.parent}handleMainInteraction(t,i,n){const o=this.pressedByID.get(i.pointerId),r=n!==t;let l=!0;switch(i.event.pointerType){case"mouse":case"touch":const c=this.context.input.getPointerPositionLastFrame(i.pointerId),h=this.context.input.getPointerPosition(i.pointerId);l=c&&!W.approximately(c,h);break}this.propagate(t,c=>{var h;const d=c;d.interactable!==!1&&(!d.activeAndEnabled||!d.enabled||(d.onPointerEnter&&r&&this.handlePointerEnter(d,i),i.isDown&&d.onPointerDown&&(d.onPointerDown(i),o?.handlers.add(d),this.handlePointerCapture(i,d)),d.onPointerMove&&(l&&d.onPointerMove(i),this.handlePointerCapture(i,d)),i.isUp&&(d.onPointerUp&&(this.invokeOnPointerUp(i,d),o?.handlers.delete(d)),d.onPointerExit&&((h=i.event)==null?void 0:h.pointerType)===Pd.Touch&&(this.handlePointerExit(d,i),this.hoveredByID.delete(i.pointerId))),i.isClick&&d.onPointerClick&&d.onPointerClick(i)))}),i.isUp&&(o?.handlers.forEach(c=>{this.invokeOnPointerUp(i,c)}),this.pressedByID.delete(i.pointerId))}propagatePointerExit(t,i,n){this.propagate(t,o=>{if(!o.gameObject||o.destroyed)return;const r=o;if(r.onPointerExit||r.onPointerEnter){if(n&&this.isChild(n,o.gameObject))return;this.handlePointerExit(r,i)}})}invokeOnPointerUp(t,i){var n;(n=i.onPointerUp)==null||n.call(i,t),this.releasePointerCapture(t,i)}handlePointerEnter(t,i){t.onPointerEnter&&this.updatePointerState(t,i.pointerId,this.pointerEnterSymbol,!0)&&t.onPointerEnter(i),this.updatePointerState(t,i.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(t,i){t.onPointerExit&&this.updatePointerState(t,i.pointerId,this.pointerExitSymbol,!0)&&t.onPointerExit(i),this.updatePointerState(t,i.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(t,i,n,o){let r=t[n];if(o)return r&&r.includes(i)?!1:(r=r||[],r.push(i),t[n]=r,!0);{if(!r||!r.includes(i))return!1;const l=r.indexOf(i);return l!==-1&&r.splice(l,1),!0}}handlePointerCapture(t,i){if(t.z__pointer_ctured){t.z__pointer_ctured=!1;const n=t.pointerId;if(i.onPointerMove){const o=this._capturedPointer[n]||[];o.push(i),this._capturedPointer[n]=o}else F()&&!i.z__warned_no_pointermove&&(i.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 t.z__pointer_cture_rleased&&(t.z__pointer_cture_rleased=!1,this.releasePointerCapture(t,i))}releasePointerCapture(t,i){const n=t.pointerId;if(this._capturedPointer[n]){const o=this._capturedPointer[n].indexOf(i);o!==-1&&(this._capturedPointer[n].splice(o,1),So&&console.log("released pointer capture",n,i,this._capturedPointer))}}invokePointerCapture(t){var i;if(t.event.type===Be.PointerMove){const n=t.pointerId,o=this._capturedPointer[n];if(o){So&&console.log("Captured",n,o);for(let r=0;r<o.length;r++){const l=o[r];if(l.destroyed){o.splice(r,1),r--;continue}(i=l.onPointerMove)==null||i.call(l,t)}}}}isChild(t,i){return!t||!i?!1:t===i?!0:t.parent?this.isChild(t.parent,i):!1}handleMeshUiObjectWithoutShadowDom(t,i){return!t||!t.isUI?!0:this.handleMeshUIIntersection(t,i)}handleMeshUIIntersection(t,i){const n=Co.updateState(t,i);return n&&this.currentActiveMeshUIComponents.push(n),n!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&Co.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let t=0;t<this.currentActiveMeshUIComponents.length;t++){const i=this.currentActiveMeshUIComponents[t];Co.resetState(i)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(t){return t?O.isActiveSelf(t)?this.testIsVisible(t.parent):!1:!0}}class Co{static markDirty(){this.needsUpdate=!0}static update(t,i,n=!1){if(n){t.update();return}const o=i.time.frameCount;for(const r of this.lastUpdateFrame)if(r.context===i){if(o===r.frame)return;r.frame=o;let l=this.needsUpdate||o<1;r.nextUpdate<=o&&(l=!0),l&&(So&&console.log("Update threemeshui"),this.needsUpdate=!1,r.nextUpdate=o+60,t.update());return}this.lastUpdateFrame=[{context:i,frame:o,nextUpdate:o+60}],t.update(),this.needsUpdate=!1}static updateState(t,i){let n=null;if(t&&(n=this.findBlockOrTextInParent(t),n&&n!==this.lastSelected)){if(n.interactable===!1)return null;this.needsUpdate=!0}return n}static resetLastSelected(){const t=this.lastSelected;t&&(this.lastSelected=null,this.resetState(t))}static resetState(t){t&&(this.needsUpdate=!0)}static findBlockOrTextInParent(t){return t?t.isBlock||t.isText?t:this.findBlockOrTextInParent(t.parent):null}}a(Co,"lastSelected",null),a(Co,"lastUpdateFrame",[]),a(Co,"needsUpdate",!1);var _M=Object.defineProperty,wM=Object.getOwnPropertyDescriptor,ze=(s,t,i,n)=>{for(var o=n>1?void 0:n?wM(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&_M(t,i,o),o};const $a=C("debugorbit"),ff=C("freecam"),Ru=C("debugcamerafit"),Tu=C("smoothcam"),xM={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let yf;class Wc extends CustomEvent{constructor(t,i){super("target-reached",{detail:{controls:t,type:i}})}}class be extends A{constructor(){super(...arguments),a(this,"autoTarget",!0),a(this,"autoFit",!1),a(this,"enableRotate",!0),a(this,"autoRotate",!1),a(this,"autoRotateSpeed",1),a(this,"minAzimuthAngle",1/0),a(this,"maxAzimuthAngle",1/0),a(this,"minPolarAngle",0),a(this,"maxPolarAngle",Math.PI),a(this,"enableKeys",!1),a(this,"enableDamping",!0),a(this,"dampingFactor",.1),a(this,"enableZoom",!0),a(this,"minZoom",0),a(this,"maxZoom",1/0),a(this,"zoomSpeed",1),a(this,"zoomToCursor",!1),a(this,"enablePan",!0),a(this,"lookAtConstraint",null),a(this,"lookAtConstraint01",1),a(this,"allowInterrupt",!0),a(this,"middleClickToFocus",!0),a(this,"doubleClickToFocus",!0),a(this,"clickBackgroundToFitScene",2),a(this,"debugLog",!1),a(this,"targetLerpDuration",1),a(this,"_controls",null),a(this,"_cameraObject",null),a(this,"_lookTargetLerpActive",!1),a(this,"_lookTargetStartPosition",new x),a(this,"_lookTargetEndPosition",new x),a(this,"_lookTargetLerp01",0),a(this,"_lookTargetLerpDuration",0),a(this,"_cameraLerpActive",!1),a(this,"_cameraStartPosition",new x),a(this,"_cameraEndPosition",new x),a(this,"_cameraLerp01",0),a(this,"_cameraLerpDuration",0),a(this,"_fovLerpActive",!1),a(this,"_fovLerpStartValue",0),a(this,"_fovLerpEndValue",0),a(this,"_fovLerp01",0),a(this,"_fovLerpDuration",0),a(this,"_inputs",0),a(this,"_enableTime",0),a(this,"_startedListeningToKeyEvents",!1),a(this,"_eventSystem"),a(this,"_afterHandleInputFn"),a(this,"_camera",null),a(this,"_syncedTransform"),a(this,"_didSetTarget",0),a(this,"targetElement",null),a(this,"_activePointerEvents"),a(this,"_lastTimeClickOnBackground",-1),a(this,"_clickOnBackgroundCount",0),a(this,"_onPointerDown",t=>{this._activePointerEvents.push(t)}),a(this,"_onPointerDownLate",t=>{t.used&&this._controls&&(this._controls.enabled=!1)}),a(this,"_onPointerUp",t=>{for(let i=this._activePointerEvents.length-1;i>=0;i--){const n=this._activePointerEvents[i];if(n.pointerId===t.pointerId&&n.button===t.button){this._activePointerEvents.splice(i,1);break}}if(this.clickBackgroundToFitScene>0&&t.isClick&&t.button===0){if(t.hasRay||t.intersections.push(...this.context.physics.raycast()),t.intersections.length<=0){const i=this.context.time.time-this._lastTimeClickOnBackground;this._lastTimeClickOnBackground=this.context.time.time,this.clickBackgroundToFitScene<=1||i<this.clickBackgroundToFitScene*.15?(this._clickOnBackgroundCount+=1,this._clickOnBackgroundCount>=this.clickBackgroundToFitScene-1&&this.fitCamera(this.context.scene.children,{immediate:!1})):this._clickOnBackgroundCount=0}$a&&console.log(this.clickBackgroundToFitScene,t.intersections.length,this._clickOnBackgroundCount)}}),a(this,"_onPointerUpLate",t=>{var i,n,o;if(this.doubleClickToFocus&&t.isDoubleClick&&!t.used)this.setTargetFromRaycast();else if(!t.used&&this.autoTarget){const r=new no((i=this._cameraObject)==null?void 0:i.worldPosition,(n=this._cameraObject)==null?void 0:n.worldForward.multiplyScalar(-1)),l=this.context.physics.raycastFromRay(r),c=l.length>0?l[0]:void 0;c&&c.distance>this.minZoom&&c.distance<this.maxZoom&&($a&&q.DrawWireSphere(c.point,.1,16711680,2),(o=this._controls)==null||o.target.copy(l[0].point))}}),a(this,"onControlsChangeStarted",()=>{this._syncedTransform&&this._syncedTransform.requestOwnership()}),a(this,"_shouldDisable",!1),a(this,"__onPreRender",()=>{const t=this.context.pre_render_callbacks.indexOf(this.__onPreRender);t>=0&&this.context.pre_render_callbacks.splice(t,1),this.autoFit&&(this.autoFit=!1,this.fitCamera({centerCamera:"y",immediate:!0,objects:this.scene.children}))}),a(this,"_haveAttachedKeyboardEvents",!1)}get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(t){var i;(i=this.controls)==null||i.addEventListener("start",t)}get targetLerpSpeed(){return 5}set targetLerpSpeed(t){this.targetLerpDuration=1/t}awake(){$a&&console.debug("OrbitControls",this),this._didSetTarget=0,this._startedListeningToKeyEvents=!1}start(){this._eventSystem=si.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(gf.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){var t,i;(t=this._controls)==null||t.dispose(),(i=this._eventSystem)==null||i.removeEventListener(gf.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._enableTime=this.context.time.time;const t=O.getComponent(this.gameObject,Oe);this._camera=t;let i=t?.threeCamera;if(!i&&this.gameObject instanceof _e&&(i=this.gameObject),i&&Lm(i,this,!0),!this._controls&&i instanceof I){this._cameraObject=i;const n=this.targetElement??this.context.renderer.domElement,o=i?.quaternion.clone();this._controls=new ov(i,n),i?.quaternion.copy(o),yf===void 0&&(yf={...this._controls.keys});const r=te(i),l=this.gameObject.worldForward,c=2.5,h=r.clone().sub(l.multiplyScalar(c));this._controls.target.copy(h)}if(this._controls)if(ff&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,X.isMobileDevice()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),!this._startedListeningToKeyEvents&&this.enableKeys)this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(this.context.domElement);else try{this._controls.stopListenToKeyEvents()}catch{}this._syncedTransform=O.getComponent(this.gameObject,qs)??void 0,this.context.pre_render_callbacks.push(this.__onPreRender),this._activePointerEvents=[],this.context.input.addEventListener("pointerdown",this._onPointerDown,{queue:ai.Early}),this.context.input.addEventListener("pointerdown",this._onPointerDownLate,{queue:ai.Late}),this.context.input.addEventListener("pointerup",this._onPointerUp,{queue:ai.Early}),this.context.input.addEventListener("pointerup",this._onPointerUpLate,{queue:ai.Late})}onDisable(){var t;if((t=this._camera)!=null&&t.threeCamera&&Lm(this._camera.threeCamera,this,!1),this._controls){this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted);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)}afterHandleInput(t){t.detail.args.pointerId===0&&(t.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!t.detail.args.isPressed||t.detail.args.isUp)&&(this._shouldDisable=!1))}onBeforeRender(){var t,i,n,o;if(!!this._controls){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)&&(t=this.context.input.getPointerPositionDelta(0))!=null&&t.length()||0>.1)&&(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 r=O.getComponent(this.gameObject,Oe);if(r&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const l=te(r.threeCamera),c=Math.max(.01,l.length()),h=new x(0,0,-c).applyMatrix4(r.threeCamera.matrixWorld);this.setLookTargetPosition(h,!0)}if(!this.setLookTargetFromConstraint()){const l=new Ws;l.screenPoint=new re(0,0),l.lineThreshold=.1;const c=this.context.physics.raycast(l);c.length>0&&this.setLookTargetPosition(c[0].point,!0),Ru&&console.log("OrbitControls hits",...c)}}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 Wc(this,"camera"));else{const r=W.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,r)}if(this._lookTargetLerpActive)if(this._lookTargetLerp01+=this.context.time.deltaTime/this._lookTargetLerpDuration,this._lookTargetLerp01>=1)this._controls.target.copy(this._lookTargetEndPosition),this._lookTargetLerpActive=!1,this.dispatchEvent(new Wc(this,"lookat"));else{const r=W.easeInOutCubic(this._lookTargetLerp01);this._controls.target.lerpVectors(this._lookTargetStartPosition,this._lookTargetEndPosition,r)}if(this._fovLerpActive&&this._cameraObject){const r=this._cameraObject;if(this._fovLerp01+=this.context.time.deltaTime/this._fovLerpDuration,this._fovLerp01>=1)r.fov=this._fovLerpEndValue,this._fovLerpActive=!1;else{const l=W.easeInOutCubic(this._fovLerp01);r.fov=W.lerp(this._fovLerpStartValue,this._fovLerpEndValue,l)}r.updateProjectionMatrix()}}if(this._controls){if(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!this._shouldDisable&&this._camera===this.context.mainCameraComponent&&!this.context.isInXR&&!this._activePointerEvents.some(r=>r.used),this._controls.keys=this.enableKeys?yf:xM,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.enableRotate=this.enableRotate,this._controls.minAzimuthAngle=this.minAzimuthAngle,this._controls.maxAzimuthAngle=this.maxAzimuthAngle,this._controls.minPolarAngle=this.minPolarAngle,this._controls.maxPolarAngle=this.maxPolarAngle,ff||(((n=(i=this._camera)==null?void 0:i.threeCamera)==null?void 0:n.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 Tu=="number"||Tu===!0){this._controls.enableDamping=!0;const r=typeof Tu=="number"?Tu:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,r))}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||(!ff&&(o=this.lookAtConstraint)!=null&&o.locked&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(this.context.time.deltaTime),$a&&q.DrawWireSphere(this._controls.target,.1,65280))}}}setCameraAndLookTarget(t,i=!1){if(!t)return F()&&console.warn("[OrbitControls] setCameraAndLookTarget target is null"),!1;if(!(t instanceof I)&&!(t instanceof Oe))return F()&&console.warn("[OrbitControls] setCameraAndLookTarget target is not an Object3D or Camera"),!1;t instanceof Oe&&(t=t.gameObject);const n=t.worldPosition,o=t.worldForward,r=new no(n,o.multiplyScalar(-1));return $a&&q.DrawRay(r.origin,r.direction,16711680,10),this.setTargetFromRaycast(r,i)||this.setLookTargetPosition(r.at(2,G()),i),this.setCameraTargetPosition(n,i),!0}setCameraTargetPosition(t,i=!1){var n;t&&(t instanceof I&&(t=te(t)),this._cameraEndPosition||(this._cameraEndPosition=new x),this._cameraEndPosition.copy(t),i===!0?(this._cameraLerpActive=!1,this._cameraObject&&this._cameraObject.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy((n=this._cameraObject)==null?void 0:n.position),typeof i=="number"?this._cameraLerpDuration=i:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setFieldOfView(t,i=!1){var n;if(!this._controls||typeof t!="number")return;const o=(n=this._camera)==null?void 0:n.threeCamera;o&&(i===!0?o.fov=t:(this._fovLerpActive=!0,this._fovLerp01=0,this._fovLerpStartValue=o.fov,this._fovLerpEndValue=t,typeof i=="number"?this._fovLerpDuration=i:this._fovLerpDuration=this.targetLerpDuration))}setLookTargetPosition(t=null,i=!1){this._controls&&t&&(t instanceof I&&(t=te(t)),this._lookTargetEndPosition.copy(t),this._didSetTarget++,$a&&(console.warn("OrbitControls: setLookTargetPosition",t,i),q.DrawWireSphere(this._lookTargetEndPosition,.2,16711680,2)),i===!0?this._controls.target.copy(this._lookTargetEndPosition):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof i=="number"?this._lookTargetLerpDuration=i:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(t=0,i=1){var n,o;if(!this._controls||((n=this.lookAtConstraint)==null?void 0:n.enabled)===!1)return!1;const r=(o=this.lookAtConstraint)==null?void 0:o.sources;if(r&&r.length>0){const l=r[t];if(l)return l.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._lookTargetEndPosition,i),!0}return!1}lerpTarget(t,i){return this.lerpLookTarget(t,i)}lerpLookTarget(t,i){this._controls&&(i>=1?this._controls.target.copy(t):this._controls.target.lerp(t,i))}setTargetFromRaycast(t,i=!1){if(!this.controls)return!1;const n=t?this.context.physics.raycastFromRay(t):this.context.physics.raycast();for(const o of n)if(o.distance>0&&O.isActiveInHierarchy(o.object)){const r=mf(o.object);if(r){const l=r.canvas;if(l!=null&&l.screenspace)break}return this.setLookTargetPosition(o.point,i),!0}return!1}fitCamera(t,i){var n,o;if(this.context.isInXR)return;let r;if(Array.isArray(t)?r=t:t&&"type"in t?r=t.children:t&&"objects"in t&&(r=t?.objects,i=t),r&&!Array.isArray(r)&&(r=r.children),(!Array.isArray(r)||r&&r.length<=0)&&(r=this.context.scene.children),!Array.isArray(r)||r.length<=0){console.warn("No objects to fit camera to...");return}const l=this._cameraObject,c=this._controls;if(!l||!c){console.warn("No camera or controls found to fit camera to objects...");return}i||(i={});const{immediate:h=!1,centerCamera:d="y",cameraNearFar:u="auto",fitOffset:p=1.1,fov:g=l?.fov}=i,y=new x,f=new x,v=oi(r,void 0,(o=(n=this._camera)==null?void 0:n.threeCamera)==null?void 0:o.layers),b=v.clone();l.updateMatrixWorld(),l.updateProjectionMatrix(),v.getCenter(f);const w=new x;if(v.getSize(w),v.applyMatrix4(l.matrixWorldInverse),v.getSize(y),v.setFromCenterAndSize(f,y),Number.isNaN(y.x)||Number.isNaN(y.y)||Number.isNaN(y.z)){console.warn("Camera fit size resultet in NaN",l,v,[...r]);return}if(y.length()<=1e-10){Ru&&console.warn("Camera fit size is zero",v,[...r]);return}const _=i.fov||l.fov,S=2*Math.atan(Math.tan(_*Math.PI/360/2)*l.aspect)/Math.PI*360,R=y.y/(2*Math.atan(Math.PI*_/360)),M=y.x/(2*Math.atan(Math.PI*S/360)),T=p*Math.max(R,M)+y.z/2;Ru&&console.log("Fit camera to objects",{fitHeightDistance:R,fitWidthDistance:M,distance:T,verticalFov:_,horizontalFov:S}),this.maxZoom=T*10,this.minZoom=T*.01;const j=.05,L=f.clone();if(L.y-=y.y*j,this.setLookTargetPosition(L,h),this.setFieldOfView(i.fov,h),u==null||u=="auto"){const E=O.findObjectOfType(Hs),z=E?E.radius:0,H=Math.max(w.x,w.y,w.z,z);l.near=T/100,l.far=H+T*10,E&&(this.maxZoom=Math.max(Math.min(this.maxZoom,z*.5),T))}const U=c.getDistance();U<this.minZoom&&(this.minZoom=U*.9),U>this.maxZoom&&(this.maxZoom=U*1.1),l.updateMatrixWorld(),l.updateProjectionMatrix();const B=te(l),Q=f.clone();Q.sub(B),d==="y"&&(Q.y=0),Q.normalize(),Q.multiplyScalar(T),d==="y"&&(Q.y+=-j*4*T);let $=f.clone().sub(Q);if(l.parent&&($=l.parent.worldToLocal($)),this.setCameraTargetPosition($,h),Ru){const E=new Ny(v);this.context.scene.add(E),Vm(E,ic(l)),setTimeout(()=>{this.context.scene.remove(E)},1e4),q.DrawWireBox3(b,65280,10),this._haveAttachedKeyboardEvents||(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",z=>{if(z.code==="KeyF"){let H;this._cameraObject instanceof _e&&(H=Math.random()*Math.random()*170+10),this.fitCamera({objects:r,fitOffset:p,immediate:!1,fov:H})}z.code==="KeyV"&&this._cameraObject instanceof _e&&(this._cameraObject.fov=60)}))}c.update()}}ze([m()],be.prototype,"autoTarget",2),ze([m()],be.prototype,"autoFit",2),ze([m()],be.prototype,"enableRotate",2),ze([m()],be.prototype,"autoRotate",2),ze([m()],be.prototype,"autoRotateSpeed",2),ze([m()],be.prototype,"minAzimuthAngle",2),ze([m()],be.prototype,"maxAzimuthAngle",2),ze([m()],be.prototype,"minPolarAngle",2),ze([m()],be.prototype,"maxPolarAngle",2),ze([m()],be.prototype,"enableKeys",2),ze([m()],be.prototype,"enableDamping",2),ze([m()],be.prototype,"dampingFactor",2),ze([m()],be.prototype,"enableZoom",2),ze([m()],be.prototype,"minZoom",2),ze([m()],be.prototype,"maxZoom",2),ze([m()],be.prototype,"zoomSpeed",2),ze([m()],be.prototype,"enablePan",2),ze([m(Mr)],be.prototype,"lookAtConstraint",2),ze([m()],be.prototype,"lookAtConstraint01",2),ze([m()],be.prototype,"allowInterrupt",2),ze([m()],be.prototype,"middleClickToFocus",2),ze([m()],be.prototype,"doubleClickToFocus",2),ze([m()],be.prototype,"clickBackgroundToFitScene",2),ze([m()],be.prototype,"targetLerpDuration",2);var SM=Object.defineProperty,CM=Object.getOwnPropertyDescriptor,Qt=(s,t,i,n)=>{for(var o=n>1?void 0:n?CM(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&SM(t,i,o),o},Oo=(s=>(s[s.None=0]="None",s[s.Skybox=1]="Skybox",s[s.SolidColor=2]="SolidColor",s[s.Uninitialized=4]="Uninitialized",s))(Oo||{});const Po=C("debugcam"),jw=C("debugscreenpointtoray");var Eu;const Vc=(Eu=class extends A{constructor(){super(...arguments),a(this,"_nearClipPlane",.1),a(this,"_farClipPlane",1e3),a(this,"orthographic",!1),a(this,"orthographicSize",5),a(this,"ARBackgroundAlpha",0),a(this,"_cullingMask",4294967295),a(this,"_backgroundBlurriness"),a(this,"_backgroundIntensity"),a(this,"_backgroundRotation"),a(this,"_environmentIntensity"),a(this,"_targetTexture",null),a(this,"_backgroundColor"),a(this,"_fov"),a(this,"_cam",null),a(this,"_clearFlags",2),a(this,"_skybox"),a(this,"_frustum"),a(this,"_projScreenMatrix",new ne)}get isCamera(){return!0}get aspect(){return this._cam instanceof _e?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(s){this._cam instanceof _e&&this._cam.aspect!==s&&(this._cam.aspect=s,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof _e?this._cam.fov:this._fov}set fieldOfView(s){const t=this.fieldOfView!=s;if(this._fov=s,t&&this._cam&&this._cam instanceof _e){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(s){const t=this._nearClipPlane!=s;this._nearClipPlane=s,this._cam&&(t||this._cam.near!=s)&&(this._cam.near=s,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(s){const t=this._farClipPlane!=s;this._farClipPlane=s,this._cam&&(t||this._cam.far!=s)&&(this._cam.far=s,this._cam.updateProjectionMatrix())}applyClippingPlane(){this._cam&&(this._cam.near=this._nearClipPlane,this._cam.far=this._farClipPlane,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(s){s!==this._clearFlags&&(this._clearFlags=s,this.applyClearFlagsIfIsActiveCamera())}set cullingMask(s){this._cullingMask=s,this._cam&&(this._cam.layers.mask=s)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}set cullingLayer(s){this.cullingMask=(1<<s|0)>>>0}set backgroundBlurriness(s){s!==this._backgroundBlurriness&&(s===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(s,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}set backgroundIntensity(s){s!==this._backgroundIntensity&&(s===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(s,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}set backgroundRotation(s){s!==this._backgroundRotation&&(s===void 0?this._backgroundRotation=void 0:this._backgroundRotation=s,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}set environmentIntensity(s){this._environmentIntensity=s}get environmentIntensity(){return this._environmentIntensity}get backgroundColor(){return this._backgroundColor??null}set backgroundColor(s){if(s){if(this._backgroundColor)this._backgroundColor.copy(s);else{if(!s.clone)return;this._backgroundColor=s.clone()}s.alpha===void 0&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera()}}set targetTexture(s){this._targetTexture=s}get targetTexture(){return this._targetTexture}get cam(){return this.threeCamera}get threeCamera(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(s,t,i){const n=this.threeCamera,o=Vc._origin;o.set(s,t,-1),this.context.input.convertScreenspaceToRaycastSpace(o),jw&&console.log("screenPointToRay",s.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=Vc._direction.set(o.x,o.y,o.z),l=te(n);return r.sub(l),r.normalize(),i?(i.set(l,r),i):new no(l.clone(),r.clone())}getFrustum(){return this._frustum||(this._frustum=new Qy,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new Qy),this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(s,t){return t&&this._projScreenMatrix.multiplyMatrices(this.threeCamera.projectionMatrix,this.threeCamera.matrixWorldInverse),s===this._projScreenMatrix?s:s.copy(this._projScreenMatrix)}awake(){jw&&window.addEventListener("pointerdown",s=>{const t=s.clientX,i=s.clientY;console.log("touch",t.toFixed(2),i.toFixed(2));const n=this.screenPointToRay(t,i),o="#"+Math.floor(Math.random()*16777215).toString(16);q.DrawRay(n.origin,n.direction,o,10)})}onEnable(){Po&&console.log(`Camera enabled: "${this.name}". ClearFlags=${Oo[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),PM(this)),this.applyClearFlagsIfIsActiveCamera({applySkybox:!0})}onDisable(){this.context.removeCamera(this)}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 s=this.context.renderer;if(s){const t=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,s),t?.applyClearFlags()}}}buildCamera(){if(this._cam)return;const s=this.gameObject.isCamera;let t=null;if(s?(t=this.gameObject,t?.layers.enableAll(),t instanceof _e&&(this._fov=t.fov)):t=this.gameObject.children[0],t&&t.isCamera)t instanceof _e&&(this._fov&&(t.fov=this._fov),t.near=this._nearClipPlane,t.far=this._farClipPlane,t.updateProjectionMatrix());else if(!this.orthographic)t=new _e(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 lm(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(s){this.context.mainCameraComponent===this&&this.applyClearFlags(s)}applyClearFlags(s){var t;if(!this._cam){Po&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this._fov,Po){const i=`Camera "${this.name}" clear flags: ${Oo[this._clearFlags]}`;console.debug(i)}switch(this._clearFlags){case 0:return;case 1:if(Vc.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||s?.applySkybox===!0)&&this.applySceneSkybox(),this._backgroundBlurriness!==void 0?this.context.scene.backgroundBlurriness=this._backgroundBlurriness:Po&&console.warn(`Camera "${this.name}" has no background blurriness`),this._backgroundIntensity!==void 0&&(this.context.scene.backgroundIntensity=this._backgroundIntensity),this._backgroundRotation!==void 0?this.context.scene.backgroundRotation=this._backgroundRotation:Po&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor){let i=this._backgroundColor.alpha;Vc.backgroundShouldBeTransparent(this.context)&&(i=this.ARBackgroundAlpha??0),this.context.scene.background=null,(t=this.context.xr)!=null&&t.isVR?this.context.renderer.setClearColor(Vv(this._backgroundColor).convertLinearToSRGB()):this.context.renderer.setClearColor(this._backgroundColor,i)}else Po&&console.warn(`Camera "${this.name}" has no background color`,this);break;case 4:this.context.scene.background=null,this.context.renderer.setClearColor(0,0);break}}applySceneSkybox(){this._skybox||(this._skybox=new OM(this)),this._skybox.apply()}static backgroundShouldBeTransparent(s){var t,i,n,o;const r=(t=s.renderer.xr)==null?void 0:t.getSession();if(!r)return!1;if(typeof r._transparent=="boolean")return r._transparent;const l=r.environmentBlendMode;Po&&De("Environment blend mode: "+l+" on "+navigator.userAgent);let c=l==="additive"||l==="alpha-blend";return s.isInAR&&l==="opaque"&&((i=navigator.userAgent)!=null&&i.includes("OculusBrowser")||(n=navigator.userAgent)!=null&&n.includes("Mozilla")&&(o=navigator.userAgent)!=null&&o.includes("Mobile WebXRViewer/v2"))&&(c=!0),r._transparent=c,c}},a(Eu,"_origin",new x),a(Eu,"_direction",new x),Eu);let Oe=Vc;Qt([m()],Oe.prototype,"aspect",1),Qt([m()],Oe.prototype,"fieldOfView",1),Qt([m()],Oe.prototype,"nearClipPlane",1),Qt([m()],Oe.prototype,"farClipPlane",1),Qt([m()],Oe.prototype,"clearFlags",1),Qt([m()],Oe.prototype,"orthographic",2),Qt([m()],Oe.prototype,"orthographicSize",2),Qt([m()],Oe.prototype,"ARBackgroundAlpha",2),Qt([m()],Oe.prototype,"cullingMask",1),Qt([m()],Oe.prototype,"backgroundBlurriness",1),Qt([m()],Oe.prototype,"backgroundIntensity",1),Qt([m(Bt)],Oe.prototype,"backgroundRotation",1),Qt([m()],Oe.prototype,"environmentIntensity",1),Qt([m(xe)],Oe.prototype,"backgroundColor",1),Qt([m(Ua)],Oe.prototype,"targetTexture",1);class OM{constructor(t){a(this,"_camera"),a(this,"_skybox"),this._camera=t}get context(){var t;return(t=this._camera)==null?void 0:t.context}apply(){this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),this._skybox?this.context.scene.background!==this._skybox&&(Po&&console.log(`Camera "${this._camera.name}" set skybox`,this._camera,this._skybox),this._skybox.mapping=yn,this.context.scene.background=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}`))}}function PM(s){C("freecam")&&s.context.mainCameraComponent===s&&O.getOrAddComponent(s.gameObject,be)}class Tn extends A{constructor(){super(...arguments),a(this,"_listener",null),a(this,"onInteraction",()=>{this.destroyed||this.listener==null||this.addListenerIfItExists()})}get listener(){return this._listener==null&&(this._listener=new LS),this._listener}onEnable(){Pn.registerWaitForInteraction(this.onInteraction),this.addListenerIfItExists()}onDisable(){Pn.unregisterWaitForInteraction(this.onInteraction),this.removeListenerIfItExists()}addListenerIfItExists(){const t=this._listener;if(!t||t!=null&&t.parent)return;const i=this.context.mainCameraComponent||O.getComponentInParent(this.gameObject,Oe);i!=null&&i.threeCamera?i.threeCamera.add(t):this.gameObject.add(t),t.filter?(t.gain.connect(t.filter),t.filter.connect(t.context.destination)):t.gain.connect(t.context.destination)}removeListenerIfItExists(){const t=this._listener;t&&(t.removeFromParent(),t.filter&&t.filter.disconnect(),t.gain&&t.gain.disconnect())}}var kM=Object.defineProperty,MM=Object.getOwnPropertyDescriptor,Os=(s,t,i,n)=>{for(var o=n>1?void 0:n?MM(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&kM(t,i,o),o};const Ut=C("debugaudio"),ko=class extends A{constructor(){super(...arguments),a(this,"clip",""),a(this,"playOnAwake",!1),a(this,"preload",!1),a(this,"playInBackground",!0),a(this,"_spatialBlend",0),a(this,"_minDistance",1),a(this,"_maxDistance",100),a(this,"_volume",1),a(this,"rollOffMode",0),a(this,"_loop",!1),a(this,"sound",null),a(this,"helper",null),a(this,"wasPlaying",!1),a(this,"audioLoader",null),a(this,"shouldPlay",!1),a(this,"_lastClipStartedLoading",null),a(this,"_audioElement",null),a(this,"onVisibilityChanged",()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||X.isMobileDevice())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":Ut&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,ko.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&ko.userInteractionRegistered&&this.wasPlaying&&this.play();break}}),a(this,"onApplicationMuteChanged",()=>{var s,t;this.context.application.muted?(s=this.sound)==null||s.setVolume(0):(t=this.sound)==null||t.setVolume(this.volume)}),a(this,"createAudio",s=>{Ut&&console.log("AudioBuffer finished loading",s);const t=this.Sound;if(!t){Ut&&console.warn("Failed getting sound?",this.name);return}t.isPlaying&&t.stop(),s&&t.setBuffer(s),t.loop=this._loop,this.context.application.muted?t.setVolume(0):t.setVolume(this.volume),t.autoplay=this.shouldPlay&&ko.userInteractionRegistered,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),ko.registerWaitForAllowAudio(this.__onAllowAudioCallback)}),a(this,"__onAllowAudioCallback",()=>{this.shouldPlay&&this.play()}),a(this,"_lastContextTime",0),a(this,"_hasEnded",!0),a(this,"_needUpdateSpatialDistanceSettings",!1)}static get userInteractionRegistered(){return Pn.userInteractionRegistered}static registerWaitForAllowAudio(s){Pn.registerWaitForInteraction(s)}get isPlaying(){var s;return((s=this.sound)==null?void 0:s.isPlaying)??!1}get duration(){var s,t;return(t=(s=this.sound)==null?void 0:s.buffer)==null?void 0:t.duration}get time01(){var s;const t=this.duration;return t&&this.sound?((s=this.sound)==null?void 0:s.context.currentTime)/t:0}set time01(s){const t=this.duration;t&&this.sound&&(this.time=s*t)}get time(){var s,t;return(s=this.sound)!=null&&s.source?((t=this.sound.source)==null?void 0:t.context.currentTime)-this._lastContextTime+this.sound.offset:0}set time(s){if(this.sound){if(s===this.sound.offset)return;const t=this.isPlaying;this.stop(),this.sound.offset=s,t&&this.play()}}get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(s){this._loop=s,this.sound&&this.sound.setLoop(s)}get spatialBlend(){return this._spatialBlend}set spatialBlend(s){s!==this._spatialBlend&&(this._spatialBlend=s,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(s){this._minDistance!==s&&(this._minDistance=s,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(s){this._maxDistance!==s&&(this._maxDistance=s,this._needUpdateSpatialDistanceSettings=!0)}get volume(){return this._volume}set volume(s){this._volume=s,this.sound&&!this.context.application.muted&&(Ut&&console.log(this.name,"audio set volume",s),this.sound.setVolume(s))}set pitch(s){this.sound&&this.sound.setPlaybackRate(s)}get pitch(){return this.sound?this.sound.getPlaybackRate():1}get Sound(){var s;if(!this.sound&&ko.userInteractionRegistered){let t=this.gameObject.getComponent(Tn)??this.context.mainCamera.getComponent(Tn)??kc(Tn,this.context,!1);!t&&this.context.mainCamera&&(t=this.context.mainCamera.addComponent(Tn)),t!=null&&t.listener?(this.sound=new DS(t.listener),(s=this.gameObject)==null||s.add(this.sound)):Ut&&console.warn("No audio listener found in scene - can not play audio")}return this.sound}get ShouldPlay(){return this.shouldPlay}get audioContext(){var s;return(s=this.sound)==null?void 0:s.context}awake(){Ut&&console.log(this),this.audioLoader=new cm,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),ko.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():ko.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(iu.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(iu.MuteChanged,this.onApplicationMuteChanged),this.pause()}applySpatialDistanceSettings(){const s=this.sound;if(!s)return;this._needUpdateSpatialDistanceSettings=!1;const t=W.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(Ut&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+t),s.setRefDistance(t),s.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:s.setDistanceModel("exponential");break;case 1:s.setDistanceModel("linear");break;case 2:console.warn("Custom rolloff for AudioSource is not supported: "+this.name);break}this.spatialBlend>0?Ut&&!this.helper&&(this.helper=new UC(s,s.getRefDistance()),s.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}async onNewClip(s){if(s&&(this.clip=s),typeof s=="string")if(Ut&&console.log(s),s.endsWith(".mp3")||s.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new cm),this.shouldPlay=!0,this._lastClipStartedLoading===s){Ut&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=s,Ut&&console.log("load audio",s);const t=await this.audioLoader.loadAsync(s).catch(console.error);this._lastClipStartedLoading=null,t&&this.createAudio(t)}else console.warn("Unsupported audio clip type",s);else this.shouldPlay=!0,this.createAudio()}play(s=void 0){var t,i,n;!s&&this.clip&&(s=this.clip),s!==void 0&&typeof s!="string"&&!(s instanceof MediaStream)&&(F()&&console.warn("Called play on AudioSource with unknown argument type:",s+`
927
+ Could not find method ${d.method} on object ${p.name}`,p,typeof p[d.method])};if(typeof p[d.method]!="function"){let f=!1,v=p;for(;v;){const b=Object.getOwnPropertyDescriptor(v,d.method);if(b&&(b.writable===!0||b.set)){f=!0;break}v=Object.getPrototypeOf(v)}!f&&(F()||vt)&&y()}}if(p){let y=d.argument;if(y!==void 0?y=u(y):d.arguments!==void 0&&(y=d.arguments.map(u)),!p[d.method])console.warn(`EventList method not found: "${d.method}" on ${p?.name}`);else{y!==void 0&&!Array.isArray(y)&&(y=[y]);const f=new Rn(p,d.method,y,d.enabled);l.push(f)}}else F()&&console.warn("[Debug] EventList: Could not find event listener in scene",d,i.object,t)}const c=new Se(l);vt&&console.log(c);const h=i.target;return h!==void 0&&i.path!==void 0&&c.setEventTarget(i.path,h),c}}}const pM=new uM,Pu=new WeakMap,mM=Le.prototype.clone;Le.prototype.clone=function(){const s=mM.call(this);return Pu.has(s)||Pu.set(s,this),s};class Tw extends Qi{constructor(){super([Ua,vn])}onSerialize(t,i){}onDeserialize(t,i){if(t instanceof Le&&i.type===Ua){let n=t;Pu.has(n)&&(n=Pu.get(n)),n.isRenderTargetTexture=!0,n.flipY=!0,n.offset.y=1,n.repeat.y=-1,n.needsUpdate=!0,n.mipmaps=[],n instanceof jS&&(n.isCompressedTexture=!1,n.format=ad);const o=new Ua(n.image.width,n.image.height,{colorSpace:or});return o.texture=n,o}}}new Tw;class Ew extends Qi{constructor(){super([URL])}onSerialize(t,i){return null}onDeserialize(t,i){if(typeof t=="string"&&t.length>0)return lo(i.gltfId,t)}}new Ew;var gM=Object.defineProperty,fM=Object.getOwnPropertyDescriptor,yM=(s,t,i,n)=>{for(var o=n>1?void 0:n?fM(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&gM(t,i,o),o};class Wa extends A{awake(){si.createIfNoneExists(this.context)}onEnable(){var t;(t=si.get(this.context))==null||t.register(this)}onDisable(){var t;(t=si.get(this.context))==null||t.unregister(this)}}class Ei extends Wa{constructor(){super(...arguments),a(this,"targets",null),a(this,"raycastHits",[]),a(this,"ignoreSkinnedMeshes",!1)}start(){this.targets=[this.gameObject]}performRaycast(t=null){if(!this.targets)return null;t??(t=new Ws),t.targets=this.targets,t.results=this.raycastHits,t.useAcceleratedRaycast=!0;const i=t.testObject;this.ignoreSkinnedMeshes&&(t.testObject=o=>o instanceof fn?"continue in children":i?i(o):!0);const n=this.context.physics.raycast(t);return t.testObject=i,n}}yM([m()],Ei.prototype,"ignoreSkinnedMeshes",2);class ku extends Ei{constructor(){super(),this.ignoreSkinnedMeshes=!0}}const Aw=class extends Wa{performRaycast(s){if(!J.active||!Aw.allow||!(s!=null&&s.ray))return null;const t=s.ray.origin,i=.015;return this.context.physics.sphereOverlap(t,i,!1,!0)}};let Va=Aw;a(Va,"allow",!0);class pf{static getObject(t){const i=t[Ki];return i&&(i.isComponent===!0?t=i.gameObject:t=i),t}static isInteractable(t,i){if(i&&(i.canvasGroup=void 0,i.graphic=void 0),t==null||!t.visible||(t=this.getObject(t),!t.visible))return!1;const n=this.tryFindCanvasGroup(t);if(n?.isCanvasGroup===!0&&(i&&(i.canvasGroup=n),n.blocksRaycasts===!1||n.interactable===!1))return!1;const o=br(t,r=>{if(r.isGraphic===!0)return r},!1);return i&&o?.isGraphic===!0&&(i.graphic=o),!(o?.raycastTarget===!1||o?.layer===2)}static tryFindCanvasGroup(t){if(!t)return null;const i=br(t,n=>{const o=n;if(o.blocksRaycasts!==void 0&&o.interactable!==void 0)return o},!1);return i!==void 0?i:this.tryFindCanvasGroup(t.parent)}}function mf(s){return s[Ki]||(s.parent?mf(s.parent):null)}function vM(s){return s.isUI===!0||typeof s[Ki]=="object"}function Mu(s,t){if(!s)return;const i=s.material;if(i?.isMaterial===!0){const n=s.parent;n&&n.isText,i.side=t.doubleSided??!0?Si:ao,i.shadowSide=t.doubleSided?Si:ao,s.castShadow=t.castShadows?t.castShadows:!1,s.receiveShadow=t.receiveShadows?t.receiveShadows:!1}for(const n of s.children)Mu(n,t)}function Ha(s,t,i){s[t]===void 0&&console.warn("Field",t,"is undefined on",s);const n=Proxy.revocable(s[t],{set(l,c,h,d){const u=l[c],p=Reflect.set(l,c,h,d);return i(h,u),p}}),o=n.revoke,r=s[t];return n.revoke=()=>{s[t]=r,o()},s[t]=n.proxy,n}const Iw=Symbol("Scheduled action");function bM(s,t,i=Me.OnBeforeRender){let n=s[Iw];n||(n=s[Iw]={});const o=t.name;n[i]||(n[i]={});const r=n[i];if(r[o])return;function*l(){t?.call(s),r[o]=null}const c=s.startCoroutine(l(),i);r[o]=c}const So=C("debugeventsystem");var gf=(s=>(s.BeforeHandleInput="BeforeHandleInput",s.AfterHandleInput="AfterHandleInput",s))(gf||{});Cw(s=>{si.createIfNoneExists(s)});class si extends A{constructor(){super(...arguments),a(this,"raycaster",[]),a(this,"pressedByID",new Map),a(this,"hoveredByID",new Map),a(this,"onPointerEvent",t=>{if(t===void 0||t.propagationStopped||t.defaultPrevented||t.used)return;const i=new id(this.context.input,t);this._currentPointerEventName=t.type,i.inputSource=this.context.input,i.isClick=t.isClick,i.isDoubleClick=t.isDoubleClick,i.isDown=t.type==Be.PointerDown,i.isUp=t.type==Be.PointerUp,i.isPressed=this.context.input.getPointerPressed(t.pointerId),So&&(i.isDown?console.log("DOWN",i.pointerId):i.isUp&&console.log("UP",i.pointerId),i.isClick&&console.log("CLICK",i.pointerId));const n=new Ws;t.hasRay?n.ray=t.ray:n.screenPoint=this.context.input.getPointerPositionRC(t.pointerId);const o=this.performRaycast(n);if(o){for(const l of o)l.event=t,t.intersections.push(l);t.origin.onPointerHits&&t.origin.onPointerHits({sender:this,event:t,hits:o})}So&&i.isClick&&De("EventSystem: "+i.pointerId+" - "+this.context.time.frame+" - Up:"+i.isUp+", Down:"+i.isDown);const r={sender:this,args:i,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:r})),this.handleIntersections(o,i),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:r}))}),a(this,"_sortedHits",[]),a(this,"_testObjectsCache",new Map),a(this,"_currentlyActiveRaycaster",null),a(this,"_currentPointerEventName",null),a(this,"shouldRaycastObject",t=>{var i;const n=t&&"getComponent"in t?t.getComponent(Wa):null;if(n&&n!=this._currentlyActiveRaycaster)return!1;let o=null;if(vM(t)&&(o=(i=t[Ki])==null?void 0:i.gameObject),this._testObjectsCache.has(t)||o&&this._testObjectsCache.has(o))return this._testObjectsCache.get(t)===!1?"continue in children":!0;{let r=Su(t,this._currentPointerEventName);if(!r&&o&&(r=Su(o,this._currentPointerEventName)),r){this._testObjectsCache.set(t,!0);for(const l of t.children)this.shouldRaycastObject_AddToYesCache(l);return!0}return this._testObjectsCache.set(t,!1),"continue in children"}}),a(this,"_sortingBuffer",[]),a(this,"_noDepthTestingResults",[]),a(this,"out",{}),a(this,"_capturedPointer",{}),a(this,"pointerEnterSymbol",Symbol("pointerEnter")),a(this,"pointerExitSymbol",Symbol("pointerExit")),a(this,"currentActiveMeshUIComponents",[])}static ensureUpdateMeshUI(t,i,n=!1){Co.update(t,i,n)}static markUIDirty(t){Co.markDirty()}static createIfNoneExists(t){t.scene.getComponent(si)||t.scene.addComponent(si)}static get(t){return this.createIfNoneExists(t),t.scene.getComponent(si)}static get instance(){return this.get(ee.Current)}register(t){var i;t&&this.raycaster&&!this.raycaster.includes(t)&&((i=this.raycaster)==null||i.push(t))}unregister(t){var i,n;const o=(i=this.raycaster)==null?void 0:i.indexOf(t);o!==void 0&&o!==-1&&((n=this.raycaster)==null||n.splice(o,1))}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}awake(){this.gameObject!==this.context.scene&&(this.enabled=!1)}start(){this.context.scene.getComponent(Wa)||this.context.scene.addComponent(Ei)}onEnable(){this.context.input.addEventListener(Be.PointerDown,this.onPointerEvent),this.context.input.addEventListener(Be.PointerUp,this.onPointerEvent),this.context.input.addEventListener(Be.PointerMove,this.onPointerEvent)}onDisable(){this.context.input.removeEventListener(Be.PointerDown,this.onPointerEvent),this.context.input.removeEventListener(Be.PointerUp,this.onPointerEvent),this.context.input.removeEventListener(Be.PointerMove,this.onPointerEvent)}onBeforeRender(){this.resetMeshUIStates()}shouldRaycastObject_AddToYesCache(t){this._testObjectsCache.set(t,!0);for(const i of t.children)this.shouldRaycastObject_AddToYesCache(i)}performRaycast(t){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,t||(t=new Ws),t.testObject=this.shouldRaycastObject;for(const i of this.raycaster){if(!i.activeAndEnabled)continue;this._currentlyActiveRaycaster=i;const n=i.performRaycast(t);this._currentlyActiveRaycaster=null,n&&n.length>0&&this._sortedHits.push(...n)}return this._sortedHits.sort((i,n)=>i.distance-n.distance),this._sortedHits}assignHitInformation(t,i){i?(t.intersection=i,t.point=i.point,t.normal=i.normal,t.face=i.face,t.distance=i.distance,t.instanceId=i.instanceId):(t.intersection=void 0,t.point=void 0,t.normal=void 0,t.face=void 0,t.distance=void 0,t.instanceId=void 0)}handleIntersections(t,i){var n;if(t!=null&&t.length){t=this.sortCandidates(t);for(const r of t){if(i.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(i,r),this.handleEventOnObject(r.object,i))return!0}}this.assignHitInformation(i,t?.[0]),this.invokePointerCapture(i);const o=this.hoveredByID.get(i.pointerId);return o&&this.propagatePointerExit(o.obj,o.data,null),this.hoveredByID.delete(i.pointerId),i.isUp&&((n=this.pressedByID.get(i.pointerId))==null||n.handlers.forEach(r=>this.invokeOnPointerUp(i,r)),this.pressedByID.delete(i.pointerId)),!1}sortCandidates(t){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let i=0;i<t.length;i++){const n=t[i],o=n.object;if(o.material&&o.material.depthTest===!1){this._noDepthTestingResults.push(n);continue}this._sortingBuffer.push(n)}for(const i of this._sortingBuffer)this._noDepthTestingResults.push(i);return this._noDepthTestingResults}handleEventOnObject(t,i){if(!this.testIsVisible(t))return i.isClick&&So&&console.log("not allowed",t),!1;if(i.pointerId===void 0)return So&&console.error("Event without pointer can't be handled",i),!1;i.object=t;const n=t.parent,o=i.isClick??!1;let r=null;if(n&&n.isUI){const d=(i.isPressed||i.isClick)??!1;if(n[Ki]){const u=n[Ki].gameObject;if(u){if(!pf.isInteractable(u,this.out))return!1;r=this.out.canvasGroup??null,this.handleMeshUIIntersection(t,d),t=u}}}o&&So&&console.log(this.context.time.frame,t);const l=this.hoveredByID.get(i.pointerId),c=l?.obj;c!==t&&c&&this.propagatePointerExit(c,l.data,t);const h=this.hoveredByID.get(i.pointerId);if(h?(h.obj=t,h.data=i):this.hoveredByID.set(i.pointerId,{obj:t,data:i}),i.isDown){const d=this.pressedByID.get(i.pointerId);d?(d.obj=t,d.data=i):this.pressedByID.set(i.pointerId,{obj:t,data:i,handlers:new Set})}return(r===null||r.interactable)&&this.handleMainInteraction(t,i,c??null),!0}propagate(t,i){for(;t;)O.foreachComponent(t,n=>{i(n)},!1),t=t.parent}handleMainInteraction(t,i,n){const o=this.pressedByID.get(i.pointerId),r=n!==t;let l=!0;switch(i.event.pointerType){case"mouse":case"touch":const c=this.context.input.getPointerPositionLastFrame(i.pointerId),h=this.context.input.getPointerPosition(i.pointerId);l=c&&!W.approximately(c,h);break}this.propagate(t,c=>{var h;const d=c;d.interactable!==!1&&(!d.activeAndEnabled||!d.enabled||(d.onPointerEnter&&r&&this.handlePointerEnter(d,i),i.isDown&&d.onPointerDown&&(d.onPointerDown(i),o?.handlers.add(d),this.handlePointerCapture(i,d)),d.onPointerMove&&(l&&d.onPointerMove(i),this.handlePointerCapture(i,d)),i.isUp&&(d.onPointerUp&&(this.invokeOnPointerUp(i,d),o?.handlers.delete(d)),d.onPointerExit&&((h=i.event)==null?void 0:h.pointerType)===Pd.Touch&&(this.handlePointerExit(d,i),this.hoveredByID.delete(i.pointerId))),i.isClick&&d.onPointerClick&&d.onPointerClick(i)))}),i.isUp&&(o?.handlers.forEach(c=>{this.invokeOnPointerUp(i,c)}),this.pressedByID.delete(i.pointerId))}propagatePointerExit(t,i,n){this.propagate(t,o=>{if(!o.gameObject||o.destroyed)return;const r=o;if(r.onPointerExit||r.onPointerEnter){if(n&&this.isChild(n,o.gameObject))return;this.handlePointerExit(r,i)}})}invokeOnPointerUp(t,i){var n;(n=i.onPointerUp)==null||n.call(i,t),this.releasePointerCapture(t,i)}handlePointerEnter(t,i){t.onPointerEnter&&this.updatePointerState(t,i.pointerId,this.pointerEnterSymbol,!0)&&t.onPointerEnter(i),this.updatePointerState(t,i.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(t,i){t.onPointerExit&&this.updatePointerState(t,i.pointerId,this.pointerExitSymbol,!0)&&t.onPointerExit(i),this.updatePointerState(t,i.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(t,i,n,o){let r=t[n];if(o)return r&&r.includes(i)?!1:(r=r||[],r.push(i),t[n]=r,!0);{if(!r||!r.includes(i))return!1;const l=r.indexOf(i);return l!==-1&&r.splice(l,1),!0}}handlePointerCapture(t,i){if(t.z__pointer_ctured){t.z__pointer_ctured=!1;const n=t.pointerId;if(i.onPointerMove){const o=this._capturedPointer[n]||[];o.push(i),this._capturedPointer[n]=o}else F()&&!i.z__warned_no_pointermove&&(i.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 t.z__pointer_cture_rleased&&(t.z__pointer_cture_rleased=!1,this.releasePointerCapture(t,i))}releasePointerCapture(t,i){const n=t.pointerId;if(this._capturedPointer[n]){const o=this._capturedPointer[n].indexOf(i);o!==-1&&(this._capturedPointer[n].splice(o,1),So&&console.log("released pointer capture",n,i,this._capturedPointer))}}invokePointerCapture(t){var i;if(t.event.type===Be.PointerMove){const n=t.pointerId,o=this._capturedPointer[n];if(o){So&&console.log("Captured",n,o);for(let r=0;r<o.length;r++){const l=o[r];if(l.destroyed){o.splice(r,1),r--;continue}(i=l.onPointerMove)==null||i.call(l,t)}}}}isChild(t,i){return!t||!i?!1:t===i?!0:t.parent?this.isChild(t.parent,i):!1}handleMeshUiObjectWithoutShadowDom(t,i){return!t||!t.isUI?!0:this.handleMeshUIIntersection(t,i)}handleMeshUIIntersection(t,i){const n=Co.updateState(t,i);return n&&this.currentActiveMeshUIComponents.push(n),n!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&Co.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let t=0;t<this.currentActiveMeshUIComponents.length;t++){const i=this.currentActiveMeshUIComponents[t];Co.resetState(i)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(t){return t?O.isActiveSelf(t)?this.testIsVisible(t.parent):!1:!0}}class Co{static markDirty(){this.needsUpdate=!0}static update(t,i,n=!1){if(n){t.update();return}const o=i.time.frameCount;for(const r of this.lastUpdateFrame)if(r.context===i){if(o===r.frame)return;r.frame=o;let l=this.needsUpdate||o<1;r.nextUpdate<=o&&(l=!0),l&&(So&&console.log("Update threemeshui"),this.needsUpdate=!1,r.nextUpdate=o+60,t.update());return}this.lastUpdateFrame=[{context:i,frame:o,nextUpdate:o+60}],t.update(),this.needsUpdate=!1}static updateState(t,i){let n=null;if(t&&(n=this.findBlockOrTextInParent(t),n&&n!==this.lastSelected)){if(n.interactable===!1)return null;this.needsUpdate=!0}return n}static resetLastSelected(){const t=this.lastSelected;t&&(this.lastSelected=null,this.resetState(t))}static resetState(t){t&&(this.needsUpdate=!0)}static findBlockOrTextInParent(t){return t?t.isBlock||t.isText?t:this.findBlockOrTextInParent(t.parent):null}}a(Co,"lastSelected",null),a(Co,"lastUpdateFrame",[]),a(Co,"needsUpdate",!1);var _M=Object.defineProperty,wM=Object.getOwnPropertyDescriptor,ze=(s,t,i,n)=>{for(var o=n>1?void 0:n?wM(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&_M(t,i,o),o};const $a=C("debugorbit"),ff=C("freecam"),Ru=C("debugcamerafit"),Tu=C("smoothcam"),xM={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let yf;class Wc extends CustomEvent{constructor(t,i){super("target-reached",{detail:{controls:t,type:i}})}}class be extends A{constructor(){super(...arguments),a(this,"autoTarget",!0),a(this,"autoFit",!1),a(this,"enableRotate",!0),a(this,"autoRotate",!1),a(this,"autoRotateSpeed",1),a(this,"minAzimuthAngle",1/0),a(this,"maxAzimuthAngle",1/0),a(this,"minPolarAngle",0),a(this,"maxPolarAngle",Math.PI),a(this,"enableKeys",!1),a(this,"enableDamping",!0),a(this,"dampingFactor",.1),a(this,"enableZoom",!0),a(this,"minZoom",0),a(this,"maxZoom",1/0),a(this,"zoomSpeed",1),a(this,"zoomToCursor",!1),a(this,"enablePan",!0),a(this,"lookAtConstraint",null),a(this,"lookAtConstraint01",1),a(this,"allowInterrupt",!0),a(this,"middleClickToFocus",!0),a(this,"doubleClickToFocus",!0),a(this,"clickBackgroundToFitScene",2),a(this,"debugLog",!1),a(this,"targetLerpDuration",1),a(this,"_controls",null),a(this,"_cameraObject",null),a(this,"_lookTargetLerpActive",!1),a(this,"_lookTargetStartPosition",new x),a(this,"_lookTargetEndPosition",new x),a(this,"_lookTargetLerp01",0),a(this,"_lookTargetLerpDuration",0),a(this,"_cameraLerpActive",!1),a(this,"_cameraStartPosition",new x),a(this,"_cameraEndPosition",new x),a(this,"_cameraLerp01",0),a(this,"_cameraLerpDuration",0),a(this,"_fovLerpActive",!1),a(this,"_fovLerpStartValue",0),a(this,"_fovLerpEndValue",0),a(this,"_fovLerp01",0),a(this,"_fovLerpDuration",0),a(this,"_inputs",0),a(this,"_enableTime",0),a(this,"_startedListeningToKeyEvents",!1),a(this,"_eventSystem"),a(this,"_afterHandleInputFn"),a(this,"_camera",null),a(this,"_syncedTransform"),a(this,"_didSetTarget",0),a(this,"targetElement",null),a(this,"_activePointerEvents"),a(this,"_lastTimeClickOnBackground",-1),a(this,"_clickOnBackgroundCount",0),a(this,"_onPointerDown",t=>{this._activePointerEvents.push(t)}),a(this,"_onPointerDownLate",t=>{t.used&&this._controls&&(this._controls.enabled=!1)}),a(this,"_onPointerUp",t=>{for(let i=this._activePointerEvents.length-1;i>=0;i--){const n=this._activePointerEvents[i];if(n.pointerId===t.pointerId&&n.button===t.button){this._activePointerEvents.splice(i,1);break}}if(this.clickBackgroundToFitScene>0&&t.isClick&&t.button===0){if(t.hasRay||t.intersections.push(...this.context.physics.raycast()),t.intersections.length<=0){const i=this.context.time.time-this._lastTimeClickOnBackground;this._lastTimeClickOnBackground=this.context.time.time,this.clickBackgroundToFitScene<=1||i<this.clickBackgroundToFitScene*.15?(this._clickOnBackgroundCount+=1,this._clickOnBackgroundCount>=this.clickBackgroundToFitScene-1&&this.fitCamera(this.context.scene.children,{immediate:!1})):this._clickOnBackgroundCount=0}$a&&console.log(this.clickBackgroundToFitScene,t.intersections.length,this._clickOnBackgroundCount)}}),a(this,"_onPointerUpLate",t=>{var i,n,o;if(this.doubleClickToFocus&&t.isDoubleClick&&!t.used)this.setTargetFromRaycast();else if(!t.used&&this.autoTarget){const r=new no((i=this._cameraObject)==null?void 0:i.worldPosition,(n=this._cameraObject)==null?void 0:n.worldForward.multiplyScalar(-1)),l=this.context.physics.raycastFromRay(r),c=l.length>0?l[0]:void 0;c&&c.distance>this.minZoom&&c.distance<this.maxZoom&&($a&&q.DrawWireSphere(c.point,.1,16711680,2),(o=this._controls)==null||o.target.copy(l[0].point))}}),a(this,"onControlsChangeStarted",()=>{this._syncedTransform&&this._syncedTransform.requestOwnership()}),a(this,"_shouldDisable",!1),a(this,"__onPreRender",()=>{const t=this.context.pre_render_callbacks.indexOf(this.__onPreRender);t>=0&&this.context.pre_render_callbacks.splice(t,1),this.autoFit&&(this.autoFit=!1,this.fitCamera({centerCamera:"y",immediate:!0,objects:this.scene.children}))}),a(this,"_haveAttachedKeyboardEvents",!1)}get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(t){var i;(i=this.controls)==null||i.addEventListener("start",t)}get targetLerpSpeed(){return 5}set targetLerpSpeed(t){this.targetLerpDuration=1/t}awake(){$a&&console.debug("OrbitControls",this),this._didSetTarget=0,this._startedListeningToKeyEvents=!1}start(){this._eventSystem=si.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(gf.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){var t,i;(t=this._controls)==null||t.dispose(),(i=this._eventSystem)==null||i.removeEventListener(gf.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._enableTime=this.context.time.time;const t=O.getComponent(this.gameObject,Oe);this._camera=t;let i=t?.threeCamera;if(!i&&this.gameObject instanceof _e&&(i=this.gameObject),i&&Lm(i,this,!0),!this._controls&&i instanceof I){this._cameraObject=i;const n=this.targetElement??this.context.renderer.domElement,o=i?.quaternion.clone();this._controls=new ov(i,n),i?.quaternion.copy(o),yf===void 0&&(yf={...this._controls.keys});const r=te(i),l=this.gameObject.worldForward,c=2.5,h=r.clone().sub(l.multiplyScalar(c));this._controls.target.copy(h)}if(this._controls)if(ff&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,X.isMobileDevice()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),!this._startedListeningToKeyEvents&&this.enableKeys)this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(this.context.domElement);else try{this._controls.stopListenToKeyEvents()}catch{}this._syncedTransform=O.getComponent(this.gameObject,qs)??void 0,this.context.pre_render_callbacks.push(this.__onPreRender),this._activePointerEvents=[],this.context.input.addEventListener("pointerdown",this._onPointerDown,{queue:ai.Early}),this.context.input.addEventListener("pointerdown",this._onPointerDownLate,{queue:ai.Late}),this.context.input.addEventListener("pointerup",this._onPointerUp,{queue:ai.Early}),this.context.input.addEventListener("pointerup",this._onPointerUpLate,{queue:ai.Late})}onDisable(){var t;if((t=this._camera)!=null&&t.threeCamera&&Lm(this._camera.threeCamera,this,!1),this._controls){this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted);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)}afterHandleInput(t){t.detail.args.pointerId===0&&(t.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!t.detail.args.isPressed||t.detail.args.isUp)&&(this._shouldDisable=!1))}onBeforeRender(){var t,i,n,o;if(!!this._controls){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)&&(t=this.context.input.getPointerPositionDelta(0))!=null&&t.length()||0>.1)&&(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 r=O.getComponent(this.gameObject,Oe);if(r&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const l=te(r.threeCamera),c=Math.max(.01,l.length()),h=new x(0,0,-c).applyMatrix4(r.threeCamera.matrixWorld);this.setLookTargetPosition(h,!0)}if(!this.setLookTargetFromConstraint()){const l=new Ws;l.screenPoint=new re(0,0),l.lineThreshold=.1;const c=this.context.physics.raycast(l);c.length>0&&this.setLookTargetPosition(c[0].point,!0),Ru&&console.log("OrbitControls hits",...c)}}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 Wc(this,"camera"));else{const r=W.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,r)}if(this._lookTargetLerpActive)if(this._lookTargetLerp01+=this.context.time.deltaTime/this._lookTargetLerpDuration,this._lookTargetLerp01>=1)this._controls.target.copy(this._lookTargetEndPosition),this._lookTargetLerpActive=!1,this.dispatchEvent(new Wc(this,"lookat"));else{const r=W.easeInOutCubic(this._lookTargetLerp01);this._controls.target.lerpVectors(this._lookTargetStartPosition,this._lookTargetEndPosition,r)}if(this._fovLerpActive&&this._cameraObject){const r=this._cameraObject;if(this._fovLerp01+=this.context.time.deltaTime/this._fovLerpDuration,this._fovLerp01>=1)r.fov=this._fovLerpEndValue,this._fovLerpActive=!1;else{const l=W.easeInOutCubic(this._fovLerp01);r.fov=W.lerp(this._fovLerpStartValue,this._fovLerpEndValue,l)}r.updateProjectionMatrix()}}if(this._controls){if(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!this._shouldDisable&&this._camera===this.context.mainCameraComponent&&!this.context.isInXR&&!this._activePointerEvents.some(r=>r.used),this._controls.keys=this.enableKeys?yf:xM,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.enableRotate=this.enableRotate,this._controls.minAzimuthAngle=this.minAzimuthAngle,this._controls.maxAzimuthAngle=this.maxAzimuthAngle,this._controls.minPolarAngle=this.minPolarAngle,this._controls.maxPolarAngle=this.maxPolarAngle,ff||(((n=(i=this._camera)==null?void 0:i.threeCamera)==null?void 0:n.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 Tu=="number"||Tu===!0){this._controls.enableDamping=!0;const r=typeof Tu=="number"?Tu:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,r))}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||(!ff&&(o=this.lookAtConstraint)!=null&&o.locked&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(this.context.time.deltaTime),$a&&q.DrawWireSphere(this._controls.target,.1,65280))}}}setCameraAndLookTarget(t,i=!1){if(!t)return F()&&console.warn("[OrbitControls] setCameraAndLookTarget target is null"),!1;if(!(t instanceof I)&&!(t instanceof Oe))return F()&&console.warn("[OrbitControls] setCameraAndLookTarget target is not an Object3D or Camera"),!1;t instanceof Oe&&(t=t.gameObject);const n=t.worldPosition,o=t.worldForward,r=new no(n,o.multiplyScalar(-1));return $a&&q.DrawRay(r.origin,r.direction,16711680,10),this.setTargetFromRaycast(r,i)||this.setLookTargetPosition(r.at(2,G()),i),this.setCameraTargetPosition(n,i),!0}setCameraTargetPosition(t,i=!1){var n;t&&(t instanceof I&&(t=te(t)),this._cameraEndPosition||(this._cameraEndPosition=new x),this._cameraEndPosition.copy(t),i===!0?(this._cameraLerpActive=!1,this._cameraObject&&this._cameraObject.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy((n=this._cameraObject)==null?void 0:n.position),typeof i=="number"?this._cameraLerpDuration=i:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setFieldOfView(t,i=!1){var n;if(!this._controls||typeof t!="number")return;const o=(n=this._camera)==null?void 0:n.threeCamera;o&&(i===!0?o.fov=t:(this._fovLerpActive=!0,this._fovLerp01=0,this._fovLerpStartValue=o.fov,this._fovLerpEndValue=t,typeof i=="number"?this._fovLerpDuration=i:this._fovLerpDuration=this.targetLerpDuration))}setLookTargetPosition(t=null,i=!1){this._controls&&t&&(t instanceof I&&(t=te(t)),this._lookTargetEndPosition.copy(t),this._didSetTarget++,$a&&(console.warn("OrbitControls: setLookTargetPosition",t,i),q.DrawWireSphere(this._lookTargetEndPosition,.2,16711680,2)),i===!0?this._controls.target.copy(this._lookTargetEndPosition):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof i=="number"?this._lookTargetLerpDuration=i:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(t=0,i=1){var n,o;if(!this._controls||((n=this.lookAtConstraint)==null?void 0:n.enabled)===!1)return!1;const r=(o=this.lookAtConstraint)==null?void 0:o.sources;if(r&&r.length>0){const l=r[t];if(l)return l.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._lookTargetEndPosition,i),!0}return!1}lerpTarget(t,i){return this.lerpLookTarget(t,i)}lerpLookTarget(t,i){this._controls&&(i>=1?this._controls.target.copy(t):this._controls.target.lerp(t,i))}setTargetFromRaycast(t,i=!1){if(!this.controls)return!1;const n=t?this.context.physics.raycastFromRay(t):this.context.physics.raycast();for(const o of n)if(o.distance>0&&O.isActiveInHierarchy(o.object)){const r=mf(o.object);if(r){const l=r.canvas;if(l!=null&&l.screenspace)break}return this.setLookTargetPosition(o.point,i),!0}return!1}fitCamera(t,i){var n,o;if(this.context.isInXR)return;let r;if(Array.isArray(t)?r=t:t&&"type"in t?r=t.children:t&&"objects"in t&&(r=t?.objects,i=t),r&&!Array.isArray(r)&&(r=r.children),(!Array.isArray(r)||r&&r.length<=0)&&(r=this.context.scene.children),!Array.isArray(r)||r.length<=0){console.warn("No objects to fit camera to...");return}const l=this._cameraObject,c=this._controls;if(!l||!c){console.warn("No camera or controls found to fit camera to objects...");return}i||(i={});const{immediate:h=!1,centerCamera:d="y",cameraNearFar:u="auto",fitOffset:p=1.1,fov:g=l?.fov}=i,y=new x,f=new x,v=oi(r,void 0,(o=(n=this._camera)==null?void 0:n.threeCamera)==null?void 0:o.layers),b=v.clone();l.updateMatrixWorld(),l.updateProjectionMatrix(),v.getCenter(f);const w=new x;if(v.getSize(w),v.applyMatrix4(l.matrixWorldInverse),v.getSize(y),v.setFromCenterAndSize(f,y),Number.isNaN(y.x)||Number.isNaN(y.y)||Number.isNaN(y.z)){console.warn("Camera fit size resultet in NaN",l,v,[...r]);return}if(y.length()<=1e-10){Ru&&console.warn("Camera fit size is zero",v,[...r]);return}const _=i.fov||l.fov,S=2*Math.atan(Math.tan(_*Math.PI/360/2)*l.aspect)/Math.PI*360,R=y.y/(2*Math.atan(Math.PI*_/360)),M=y.x/(2*Math.atan(Math.PI*S/360)),T=p*Math.max(R,M)+y.z/2;Ru&&console.log("Fit camera to objects",{fitHeightDistance:R,fitWidthDistance:M,distance:T,verticalFov:_,horizontalFov:S}),this.maxZoom=T*10,this.minZoom=T*.01;const L=.05,D=f.clone();if(D.y-=y.y*L,this.setLookTargetPosition(D,h),this.setFieldOfView(i.fov,h),u==null||u=="auto"){const E=O.findObjectOfType(Hs),z=E?E.radius:0,H=Math.max(w.x,w.y,w.z,z);l.near=T/100,l.far=H+T*10,E&&(this.maxZoom=Math.max(Math.min(this.maxZoom,z*.5),T))}const U=c.getDistance();U<this.minZoom&&(this.minZoom=U*.9),U>this.maxZoom&&(this.maxZoom=U*1.1),l.updateMatrixWorld(),l.updateProjectionMatrix();const B=te(l),Q=f.clone();Q.sub(B),d==="y"&&(Q.y=0),Q.normalize(),Q.multiplyScalar(T),d==="y"&&(Q.y+=-L*4*T);let $=f.clone().sub(Q);if(l.parent&&($=l.parent.worldToLocal($)),this.setCameraTargetPosition($,h),Ru){const E=new Ny(v);this.context.scene.add(E),Vm(E,ic(l)),setTimeout(()=>{this.context.scene.remove(E)},1e4),q.DrawWireBox3(b,65280,10),this._haveAttachedKeyboardEvents||(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",z=>{if(z.code==="KeyF"){let H;this._cameraObject instanceof _e&&(H=Math.random()*Math.random()*170+10),this.fitCamera({objects:r,fitOffset:p,immediate:!1,fov:H})}z.code==="KeyV"&&this._cameraObject instanceof _e&&(this._cameraObject.fov=60)}))}c.update()}}ze([m()],be.prototype,"autoTarget",2),ze([m()],be.prototype,"autoFit",2),ze([m()],be.prototype,"enableRotate",2),ze([m()],be.prototype,"autoRotate",2),ze([m()],be.prototype,"autoRotateSpeed",2),ze([m()],be.prototype,"minAzimuthAngle",2),ze([m()],be.prototype,"maxAzimuthAngle",2),ze([m()],be.prototype,"minPolarAngle",2),ze([m()],be.prototype,"maxPolarAngle",2),ze([m()],be.prototype,"enableKeys",2),ze([m()],be.prototype,"enableDamping",2),ze([m()],be.prototype,"dampingFactor",2),ze([m()],be.prototype,"enableZoom",2),ze([m()],be.prototype,"minZoom",2),ze([m()],be.prototype,"maxZoom",2),ze([m()],be.prototype,"zoomSpeed",2),ze([m()],be.prototype,"enablePan",2),ze([m(Mr)],be.prototype,"lookAtConstraint",2),ze([m()],be.prototype,"lookAtConstraint01",2),ze([m()],be.prototype,"allowInterrupt",2),ze([m()],be.prototype,"middleClickToFocus",2),ze([m()],be.prototype,"doubleClickToFocus",2),ze([m()],be.prototype,"clickBackgroundToFitScene",2),ze([m()],be.prototype,"targetLerpDuration",2);var SM=Object.defineProperty,CM=Object.getOwnPropertyDescriptor,Qt=(s,t,i,n)=>{for(var o=n>1?void 0:n?CM(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&SM(t,i,o),o},Oo=(s=>(s[s.None=0]="None",s[s.Skybox=1]="Skybox",s[s.SolidColor=2]="SolidColor",s[s.Uninitialized=4]="Uninitialized",s))(Oo||{});const Po=C("debugcam"),jw=C("debugscreenpointtoray");var Eu;const Vc=(Eu=class extends A{constructor(){super(...arguments),a(this,"_nearClipPlane",.1),a(this,"_farClipPlane",1e3),a(this,"orthographic",!1),a(this,"orthographicSize",5),a(this,"ARBackgroundAlpha",0),a(this,"_cullingMask",4294967295),a(this,"_backgroundBlurriness"),a(this,"_backgroundIntensity"),a(this,"_backgroundRotation"),a(this,"_environmentIntensity"),a(this,"_targetTexture",null),a(this,"_backgroundColor"),a(this,"_fov"),a(this,"_cam",null),a(this,"_clearFlags",2),a(this,"_skybox"),a(this,"_frustum"),a(this,"_projScreenMatrix",new ne)}get isCamera(){return!0}get aspect(){return this._cam instanceof _e?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(s){this._cam instanceof _e&&this._cam.aspect!==s&&(this._cam.aspect=s,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof _e?this._cam.fov:this._fov}set fieldOfView(s){const t=this.fieldOfView!=s;if(this._fov=s,t&&this._cam&&this._cam instanceof _e){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(s){const t=this._nearClipPlane!=s;this._nearClipPlane=s,this._cam&&(t||this._cam.near!=s)&&(this._cam.near=s,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(s){const t=this._farClipPlane!=s;this._farClipPlane=s,this._cam&&(t||this._cam.far!=s)&&(this._cam.far=s,this._cam.updateProjectionMatrix())}applyClippingPlane(){this._cam&&(this._cam.near=this._nearClipPlane,this._cam.far=this._farClipPlane,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(s){if(typeof s=="string")switch(s){case"skybox":s=1;break;case"solidcolor":s=2;break;default:s=0;break}s!==this._clearFlags&&(this._clearFlags=s,this.applyClearFlagsIfIsActiveCamera())}set cullingMask(s){this._cullingMask=s,this._cam&&(this._cam.layers.mask=s)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}set cullingLayer(s){this.cullingMask=(1<<s|0)>>>0}set backgroundBlurriness(s){s!==this._backgroundBlurriness&&(s===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(s,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}set backgroundIntensity(s){s!==this._backgroundIntensity&&(s===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(s,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}set backgroundRotation(s){s!==this._backgroundRotation&&(s===void 0?this._backgroundRotation=void 0:this._backgroundRotation=s,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}set environmentIntensity(s){this._environmentIntensity=s}get environmentIntensity(){return this._environmentIntensity}get backgroundColor(){return this._backgroundColor??null}set backgroundColor(s){if(s){if(this._backgroundColor)this._backgroundColor.copy(s);else{if(!s.clone)return;this._backgroundColor=s.clone()}s.alpha===void 0&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera()}}set targetTexture(s){this._targetTexture=s}get targetTexture(){return this._targetTexture}get cam(){return this.threeCamera}get threeCamera(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(s,t,i){const n=this.threeCamera,o=Vc._origin;o.set(s,t,-1),this.context.input.convertScreenspaceToRaycastSpace(o),jw&&console.log("screenPointToRay",s.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=Vc._direction.set(o.x,o.y,o.z),l=te(n);return r.sub(l),r.normalize(),i?(i.set(l,r),i):new no(l.clone(),r.clone())}getFrustum(){return this._frustum||(this._frustum=new Qy,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new Qy),this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(s,t){return t&&this._projScreenMatrix.multiplyMatrices(this.threeCamera.projectionMatrix,this.threeCamera.matrixWorldInverse),s===this._projScreenMatrix?s:s.copy(this._projScreenMatrix)}awake(){jw&&window.addEventListener("pointerdown",s=>{const t=s.clientX,i=s.clientY;console.log("touch",t.toFixed(2),i.toFixed(2));const n=this.screenPointToRay(t,i),o="#"+Math.floor(Math.random()*16777215).toString(16);q.DrawRay(n.origin,n.direction,o,10)})}onEnable(){Po&&console.log(`Camera enabled: "${this.name}". ClearFlags=${Oo[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),PM(this)),this.applyClearFlagsIfIsActiveCamera({applySkybox:!0})}onDisable(){this.context.removeCamera(this)}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 s=this.context.renderer;if(s){const t=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,s),t?.applyClearFlags()}}}buildCamera(){if(this._cam)return;const s=this.gameObject.isCamera;let t=null;if(s?(t=this.gameObject,t?.layers.enableAll(),t instanceof _e&&(this._fov=t.fov)):t=this.gameObject.children[0],t&&t.isCamera)t instanceof _e&&(this._fov&&(t.fov=this._fov),t.near=this._nearClipPlane,t.far=this._farClipPlane,t.updateProjectionMatrix());else if(!this.orthographic)t=new _e(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 lm(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(s){this.context.mainCameraComponent===this&&this.applyClearFlags(s)}applyClearFlags(s){var t;if(!this._cam){Po&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this._fov,Po){const i=`Camera "${this.name}" clear flags: ${Oo[this._clearFlags]}`;console.debug(i)}switch(this._clearFlags){case 0:return;case 1:if(Vc.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||s?.applySkybox===!0)&&this.applySceneSkybox(),this._backgroundBlurriness!==void 0?this.context.scene.backgroundBlurriness=this._backgroundBlurriness:Po&&console.warn(`Camera "${this.name}" has no background blurriness`),this._backgroundIntensity!==void 0&&(this.context.scene.backgroundIntensity=this._backgroundIntensity),this._backgroundRotation!==void 0?this.context.scene.backgroundRotation=this._backgroundRotation:Po&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor){let i=this._backgroundColor.alpha;Vc.backgroundShouldBeTransparent(this.context)&&(i=this.ARBackgroundAlpha??0),this.context.scene.background=null,(t=this.context.xr)!=null&&t.isVR?this.context.renderer.setClearColor(Vv(this._backgroundColor).convertLinearToSRGB()):this.context.renderer.setClearColor(this._backgroundColor,i)}else Po&&console.warn(`Camera "${this.name}" has no background color`,this);break;case 4:this.context.scene.background=null,this.context.renderer.setClearColor(0,0);break}}applySceneSkybox(){this._skybox||(this._skybox=new OM(this)),this._skybox.apply()}static backgroundShouldBeTransparent(s){var t,i,n,o;const r=(t=s.renderer.xr)==null?void 0:t.getSession();if(!r)return!1;if(typeof r._transparent=="boolean")return r._transparent;const l=r.environmentBlendMode;Po&&De("Environment blend mode: "+l+" on "+navigator.userAgent);let c=l==="additive"||l==="alpha-blend";return s.isInAR&&l==="opaque"&&((i=navigator.userAgent)!=null&&i.includes("OculusBrowser")||(n=navigator.userAgent)!=null&&n.includes("Mozilla")&&(o=navigator.userAgent)!=null&&o.includes("Mobile WebXRViewer/v2"))&&(c=!0),r._transparent=c,c}},a(Eu,"_origin",new x),a(Eu,"_direction",new x),Eu);let Oe=Vc;Qt([m()],Oe.prototype,"aspect",1),Qt([m()],Oe.prototype,"fieldOfView",1),Qt([m()],Oe.prototype,"nearClipPlane",1),Qt([m()],Oe.prototype,"farClipPlane",1),Qt([m()],Oe.prototype,"clearFlags",1),Qt([m()],Oe.prototype,"orthographic",2),Qt([m()],Oe.prototype,"orthographicSize",2),Qt([m()],Oe.prototype,"ARBackgroundAlpha",2),Qt([m()],Oe.prototype,"cullingMask",1),Qt([m()],Oe.prototype,"backgroundBlurriness",1),Qt([m()],Oe.prototype,"backgroundIntensity",1),Qt([m(Bt)],Oe.prototype,"backgroundRotation",1),Qt([m()],Oe.prototype,"environmentIntensity",1),Qt([m(xe)],Oe.prototype,"backgroundColor",1),Qt([m(Ua)],Oe.prototype,"targetTexture",1);class OM{constructor(t){a(this,"_camera"),a(this,"_skybox"),this._camera=t}get context(){var t;return(t=this._camera)==null?void 0:t.context}apply(){this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),this._skybox?this.context.scene.background!==this._skybox&&(Po&&console.log(`Camera "${this._camera.name}" set skybox`,this._camera,this._skybox),this._skybox.mapping=yn,this.context.scene.background=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}`))}}function PM(s){C("freecam")&&s.context.mainCameraComponent===s&&O.getOrAddComponent(s.gameObject,be)}class Tn extends A{constructor(){super(...arguments),a(this,"_listener",null),a(this,"onInteraction",()=>{this.destroyed||this.listener==null||this.addListenerIfItExists()})}get listener(){return this._listener==null&&(this._listener=new LS),this._listener}onEnable(){Pn.registerWaitForInteraction(this.onInteraction),this.addListenerIfItExists()}onDisable(){Pn.unregisterWaitForInteraction(this.onInteraction),this.removeListenerIfItExists()}addListenerIfItExists(){const t=this._listener;if(!t||t!=null&&t.parent)return;const i=this.context.mainCameraComponent||O.getComponentInParent(this.gameObject,Oe);i!=null&&i.threeCamera?i.threeCamera.add(t):this.gameObject.add(t),t.filter?(t.gain.connect(t.filter),t.filter.connect(t.context.destination)):t.gain.connect(t.context.destination)}removeListenerIfItExists(){const t=this._listener;t&&(t.removeFromParent(),t.filter&&t.filter.disconnect(),t.gain&&t.gain.disconnect())}}var kM=Object.defineProperty,MM=Object.getOwnPropertyDescriptor,Os=(s,t,i,n)=>{for(var o=n>1?void 0:n?MM(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&kM(t,i,o),o};const Ut=C("debugaudio"),ko=class extends A{constructor(){super(...arguments),a(this,"clip",""),a(this,"playOnAwake",!1),a(this,"preload",!1),a(this,"playInBackground",!0),a(this,"_spatialBlend",0),a(this,"_minDistance",1),a(this,"_maxDistance",100),a(this,"_volume",1),a(this,"rollOffMode",0),a(this,"_loop",!1),a(this,"sound",null),a(this,"helper",null),a(this,"wasPlaying",!1),a(this,"audioLoader",null),a(this,"shouldPlay",!1),a(this,"_lastClipStartedLoading",null),a(this,"_audioElement",null),a(this,"onVisibilityChanged",()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||X.isMobileDevice())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":Ut&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,ko.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&ko.userInteractionRegistered&&this.wasPlaying&&this.play();break}}),a(this,"onApplicationMuteChanged",()=>{var s,t;this.context.application.muted?(s=this.sound)==null||s.setVolume(0):(t=this.sound)==null||t.setVolume(this.volume)}),a(this,"createAudio",s=>{Ut&&console.log("AudioBuffer finished loading",s);const t=this.Sound;if(!t){Ut&&console.warn("Failed getting sound?",this.name);return}t.isPlaying&&t.stop(),s&&t.setBuffer(s),t.loop=this._loop,this.context.application.muted?t.setVolume(0):t.setVolume(this.volume),t.autoplay=this.shouldPlay&&ko.userInteractionRegistered,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),ko.registerWaitForAllowAudio(this.__onAllowAudioCallback)}),a(this,"__onAllowAudioCallback",()=>{this.shouldPlay&&this.play()}),a(this,"_lastContextTime",0),a(this,"_hasEnded",!0),a(this,"_needUpdateSpatialDistanceSettings",!1)}static get userInteractionRegistered(){return Pn.userInteractionRegistered}static registerWaitForAllowAudio(s){Pn.registerWaitForInteraction(s)}get isPlaying(){var s;return((s=this.sound)==null?void 0:s.isPlaying)??!1}get duration(){var s,t;return(t=(s=this.sound)==null?void 0:s.buffer)==null?void 0:t.duration}get time01(){var s;const t=this.duration;return t&&this.sound?((s=this.sound)==null?void 0:s.context.currentTime)/t:0}set time01(s){const t=this.duration;t&&this.sound&&(this.time=s*t)}get time(){var s,t;return(s=this.sound)!=null&&s.source?((t=this.sound.source)==null?void 0:t.context.currentTime)-this._lastContextTime+this.sound.offset:0}set time(s){if(this.sound){if(s===this.sound.offset)return;const t=this.isPlaying;this.stop(),this.sound.offset=s,t&&this.play()}}get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(s){this._loop=s,this.sound&&this.sound.setLoop(s)}get spatialBlend(){return this._spatialBlend}set spatialBlend(s){s!==this._spatialBlend&&(this._spatialBlend=s,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(s){this._minDistance!==s&&(this._minDistance=s,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(s){this._maxDistance!==s&&(this._maxDistance=s,this._needUpdateSpatialDistanceSettings=!0)}get volume(){return this._volume}set volume(s){this._volume=s,this.sound&&!this.context.application.muted&&(Ut&&console.log(this.name,"audio set volume",s),this.sound.setVolume(s))}set pitch(s){this.sound&&this.sound.setPlaybackRate(s)}get pitch(){return this.sound?this.sound.getPlaybackRate():1}get Sound(){var s;if(!this.sound&&ko.userInteractionRegistered){let t=this.gameObject.getComponent(Tn)??this.context.mainCamera.getComponent(Tn)??kc(Tn,this.context,!1);!t&&this.context.mainCamera&&(t=this.context.mainCamera.addComponent(Tn)),t!=null&&t.listener?(this.sound=new DS(t.listener),(s=this.gameObject)==null||s.add(this.sound)):Ut&&console.warn("No audio listener found in scene - can not play audio")}return this.sound}get ShouldPlay(){return this.shouldPlay}get audioContext(){var s;return(s=this.sound)==null?void 0:s.context}awake(){Ut&&console.log(this),this.audioLoader=new cm,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),ko.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():ko.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(iu.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(iu.MuteChanged,this.onApplicationMuteChanged),this.pause()}applySpatialDistanceSettings(){const s=this.sound;if(!s)return;this._needUpdateSpatialDistanceSettings=!1;const t=W.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(Ut&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+t),s.setRefDistance(t),s.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:s.setDistanceModel("exponential");break;case 1:s.setDistanceModel("linear");break;case 2:console.warn("Custom rolloff for AudioSource is not supported: "+this.name);break}this.spatialBlend>0?Ut&&!this.helper&&(this.helper=new UC(s,s.getRefDistance()),s.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}async onNewClip(s){if(s&&(this.clip=s),typeof s=="string")if(Ut&&console.log(s),s.endsWith(".mp3")||s.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new cm),this.shouldPlay=!0,this._lastClipStartedLoading===s){Ut&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=s,Ut&&console.log("load audio",s);const t=await this.audioLoader.loadAsync(s).catch(console.error);this._lastClipStartedLoading=null,t&&this.createAudio(t)}else console.warn("Unsupported audio clip type",s);else this.shouldPlay=!0,this.createAudio()}play(s=void 0){var t,i,n;!s&&this.clip&&(s=this.clip),s!==void 0&&typeof s!="string"&&!(s instanceof MediaStream)&&(F()&&console.warn("Called play on AudioSource with unknown argument type:",s+`
924
928
  Using the assigned clip instead:`,this.clip),s=this.clip);let o=!this.sound||s&&s!==this.clip;if(typeof s=="string"&&!this.audioLoader&&(o=!0),(s instanceof MediaStream||typeof s=="string")&&(this.clip=s),o){this.shouldPlay=!0,this.onNewClip(s);return}if(this.shouldPlay=!0,this._hasEnded=!1,Ut&&console.log("play",(t=this.sound)==null?void 0:t.getVolume(),this.sound),this.sound&&!this.sound.isPlaying){const r=this.context.application.muted;r&&this.sound.setVolume(0),(i=this.gameObject)==null||i.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||(n=this.context.domElement.shadowRoot)==null||n.append(this._audioElement),this._audioElement.srcObject=this.clip,this._audioElement.autoplay=!1):(this._audioElement&&this._audioElement.remove(),this.sound.play(r?.1:0))}}pause(){var s,t;Ut&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=(s=this.sound)==null?void 0:s.context.currentTime,this.sound.pause()),(t=this._audioElement)==null||t.remove()}stop(){var s,t;Ut&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=(s=this.sound)==null?void 0:s.context.currentTime,Ut&&console.log(this._lastContextTime),this.sound.stop()),(t=this._audioElement)==null||t.remove()}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,Ut&&console.log("Audio clip ended",this.clip),this.dispatchEvent(new CustomEvent("ended",{detail:this})))}};let Ne=ko;Os([m(URL)],Ne.prototype,"clip",2),Os([m()],Ne.prototype,"playOnAwake",2),Os([m()],Ne.prototype,"preload",2),Os([m()],Ne.prototype,"playInBackground",2),Os([m()],Ne.prototype,"loop",1),Os([m()],Ne.prototype,"spatialBlend",1),Os([m()],Ne.prototype,"minDistance",1),Os([m()],Ne.prototype,"maxDistance",1),Os([m()],Ne.prototype,"volume",1),Os([m()],Ne.prototype,"pitch",1),Os([m()],Ne.prototype,"rollOffMode",2);const RM=C("debugavatar"),Gs=class extends A{constructor(){super(...arguments),a(this,"connectionId"),a(this,"avatar")}static getAvatar(s){return s>=0&&s<Gs.instances.length?Gs.instances[s]:null}static onAvatarMarkerCreated(s){return Gs._onNewAvatarMarkerAdded.push(s),s}static onAvatarMarkerDestroyed(s){return Gs._onAvatarMarkerDestroyed.push(s),s}awake(){Gs.instances.push(this),RM&&console.log(this);for(const s of Gs._onNewAvatarMarkerAdded)s({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){Gs.instances.splice(Gs.instances.indexOf(this),1);for(const s of Gs._onAvatarMarkerDestroyed)s({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}};let Mt=Gs;a(Mt,"instances",[]),a(Mt,"_onNewAvatarMarkerAdded",[]),a(Mt,"_onAvatarMarkerDestroyed",[]);class En{static Add(t,i,n=null){if(i){for(const o of this.Pois)if(o.obj===i)return;this.Pois.push({obj:i,avatar:n}),this.LastChangeTime=t.time.time}}static Remove(t,i){var n;if(i){for(const o of this.Pois)if(o.obj===i){this.Pois.splice(this.Pois.indexOf(o),1),this.LastChangeTime=t?.time.time??((n=ee.Current)==null?void 0:n.time.time);return}}}}a(En,"Pois",[]),a(En,"LastChangeTime",0);class TM{constructor(){a(this,"guid"),a(this,"position",new x)}}class Hc extends A{constructor(){super(...arguments),a(this,"target",null),a(this,"avatar",null),a(this,"_model",null),a(this,"_targetModel",new TM),a(this,"_currentTargetObject",null),a(this,"_lastUpdateTime",0),a(this,"_lookDuration",0),a(this,"_lastPoiChangedTime",0)}set controlledTarget(t){this.target=t;const i=k.get("MoveRandom");if(i&&this.target){const n=O.getComponent(this.target,i);n&&n.destroy()}}awake(){if(this.avatar=O.getComponentInParent(this.gameObject,Mt),this.avatar){const t=O.getComponentInParent(this.gameObject,Mt);this._model=new rg(this.context.connection,this.guid),t!=null&&t.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",t=>{var i;this.target&&t&&t.guid===((i=this.avatar)==null?void 0:i.guid)&&ht(this.target,t.position)})}update(){var t;if((!this.context.connection.isConnected||(t=this._model)!=null&&t.hasOwnership)&&(En.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=En.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){const i=te(this._currentTargetObject);ht(this.target,i),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(i))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;const t=En.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}}}}}var Au=(s=>(s[s.None=0]="None",s[s.DontExport=1]="DontExport",s))(Au||{});function Lw(s){return s&&s.isComponent}const EM=Symbol("object"),vf=new Ci(()=>new x,20);class Dw{constructor(t,i,n,o,r,l){a(this,"_point"),a(this,"_normal"),a(this,"_tangentVelocity"),a(this,"distance"),a(this,"impulse"),a(this,"friction"),this._point=t,this.distance=i,this._normal=n,this.impulse=o,this.friction=r,this._tangentVelocity=l}get point(){return vf.get().set(this._point.x,this._point.y,this._point.z)}get normal(){return vf.get().set(this._normal.x,this._normal.y,this._normal.z)}get tangentVelocity(){return vf.get().set(this._tangentVelocity.x,this._tangentVelocity.y,this._tangentVelocity.z)}}class Bw{constructor(t,i,n){a(this,"contacts"),a(this,"me"),a(this,"_collider"),a(this,"_gameObject"),this.me=t,this._collider=i,this._gameObject=i.gameObject,this.contacts=n}get collider(){return this._collider}get gameObject(){return this._gameObject}get rigidBody(){var t;return(t=this.collider)==null?void 0:t.attachedRigidbody}}class Fw{constructor(t,i){a(this,"object"),a(this,"collider"),this.object=t,this.collider=i}}const nt=C("debugnetworkingstreams");var Xs=(s=>(s.Connected="peer-user-connected",s.StreamReceived="receive-stream",s.StreamEnded="call-ended",s.Disconnected="peer-user-disconnected",s.UserJoined="user-joined",s))(Xs||{});class bf{constructor(t,i){a(this,"type","call-ended"),a(this,"userId"),a(this,"direction"),this.userId=t,this.direction=i}}class zw{constructor(t,i,n){a(this,"type","receive-stream"),a(this,"userId"),a(this,"stream"),a(this,"target"),this.userId=t,this.stream=i,this.target=n}}class AM{constructor(t,i){a(this,"guid"),a(this,"peerId"),a(this,"dontSave",!0),this.guid=t.id,this.peerId=i}}var Uw=(s=>(s.Incoming="incoming",s.Outgoing="outgoing",s))(Uw||{});class IM extends hm{constructor(t,i,n,o=null){super(),a(this,"peerId"),a(this,"userId"),a(this,"direction"),a(this,"call"),a(this,"_stream",null),a(this,"_isDisposed",!1),this.peerId=i.peer,this.userId=t,this.call=i,this.direction=n,this._stream=o,i.on("stream",r=>{if(nt&&console.log("Receive stream",`
925
929
  Audio:`,r.getAudioTracks(),`
926
930
  Video:`,r.getVideoTracks()),this._stream=r,n==="incoming"){const l=new zw(t,r,this);this.dispatchEvent(l)}}),i.on("close",()=>{this.dispatchEvent(new bf(t,n))})}get stream(){return this._stream}close(){this._isDisposed||(this._isDisposed=!0,this.call.close(),Qs(this._stream))}get isOpen(){var t;return((t=this.call.peerConnection)==null?void 0:t.connectionState)==="connected"}get isOpening(){var t;return((t=this.call.peerConnection)==null?void 0:t.connectionState)==="connecting"}get isClosed(){return!this.isOpen||this._isDisposed}}function Nw(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}const $c=class extends hm{constructor(s,t){super(),a(this,"updateCalls",()=>{var i;for(let n=this._incomingCalls.length-1;n>=0;n--){const o=this._incomingCalls[n];o.isClosed&&!o.isOpening&&this._incomingCalls.splice(n,1)}for(let n=this._outgoingCalls.length-1;n>=0;n--){const o=this._outgoingCalls[n];let r=!1;o.isClosed&&!o.isOpening&&((i=o.stream)!=null&&i.active?nt&&console.warn("!!! Stream is still active, don't remove call",o.userId,"Your id: "+this.context.connection.connectionId):(nt&&console.warn("!!! Remove closed call",o.userId),r=!0)),this.context.connection.userIsInRoom(o.userId)===!1&&(nt&&console.warn("!!! User is not in room anymore, remove call",o.userId),r=!0),r&&(o.close(),this._outgoingCalls.splice(n,1))}}),a(this,"id"),a(this,"context"),a(this,"_incomingCalls",[]),a(this,"_outgoingCalls",[]),a(this,"_peer"),a(this,"_enabled",!1),a(this,"_enabledPeer",!1),a(this,"onConnectRoomFn",this.onConnectRoom.bind(this)),a(this,"onPeerConnect",i=>{if(nt&&console.log("PEER opened as",i),i===null){console.error("Peer connection failed",i);return}this.context.connection.send("peer-user-connected",new AM(this,i))}),a(this,"onPeerClose",()=>{nt&&console.log("PEER closed"),this.updateCalls()}),a(this,"onPeerDisconnected",()=>{nt&&console.log("PEER disconnected"),this.updateCalls()}),a(this,"onPeerError",i=>{nt&&console.error("PEER error",i)}),a(this,"onPeerReceivingCall",i=>{i.answer(void 0,{sdpTransform:n=>Nw(n)}),this.registerCall(i,"incoming",null)}),this.context=s,this.id=t,this.setupPeer(),navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia}static getOrCreate(s,t){if($c.instances.has(t))return $c.instances.get(t);const i=new $c(s,t);return $c.instances.set(t,i),i}getMyPeerId(){if(this.context.connection.connectionId)return this.getPeerIdFromUserId(this.context.connection.connectionId)}getPeerIdFromUserId(s){return this.id+"-"+s}getUserIdFromPeerId(s){return s.substring(this.id.length+1)}makeCall(s,t){var i;if(!(t!=null&&t.id)){nt?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 n={metadata:{userId:this.context.connection.connectionId,streamId:t.id},sdpTransform:r=>Nw(r)},o=(i=this._peer)==null?void 0:i.call(s,t,n);if(o){const r=this.registerCall(o,"outgoing",t);return nt&&console.warn(`\u{1F4DE} CALL ${s}`,`
@@ -930,7 +934,7 @@ Incoming:`,this._incomingCalls),r}else nt&&console.error("Failed to make call",s
930
934
  ${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) );")}
931
935
  `)},this.depthMaterial.depthTest=!1,this.depthMaterial.depthWrite=!1,this.horizontalBlurMaterial=new ps(NC),this.horizontalBlurMaterial.depthTest=!1,this.verticalBlurMaterial=new ps(WC),this.verticalBlurMaterial.depthTest=!1,this.shadowGroup.visible=!1,this.autoFit?this.fitShadows():this.applyMinSize()}onDestroy(){var s,t,i,n,o,r,l,c;Yc._instances.get(this.context)===this&&Yc._instances.delete(this.context),(s=this.renderTarget)==null||s.dispose(),(t=this.renderTargetBlur)==null||t.dispose(),(i=this.depthMaterial)==null||i.dispose(),(n=this.horizontalBlurMaterial)==null||n.dispose(),(o=this.verticalBlurMaterial)==null||o.dispose(),(r=this.blurPlane)==null||r.geometry.dispose(),(l=this.plane)==null||l.geometry.dispose(),(c=this.occluderMesh)==null||c.geometry.dispose()}onBeforeRender(s){if(!this.renderTarget||!this.renderTargetBlur||!this.depthMaterial||!this.shadowCamera||!this.blurPlane||!this.shadowGroup||!this.plane||!this.horizontalBlurMaterial||!this.verticalBlurMaterial){Qc&&console.error("ContactShadows: not initialized yet");return}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 Y&&On(this.gameObject,!1);const r=t.background;t.background=null,t.overrideMaterial=this.depthMaterial,this.backfaceShadows?this.depthMaterial.side=Si:this.depthMaterial.side=ao;const l=i.getClearAlpha();i.setClearAlpha(0);const c=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;Xw.length=0,d.transparent=Xw,kf.length=0;for(const g of d.opaque){if(!g.object.visible)continue;const y=g.material;let f=g.material.colorWrite==!1||y.wireframe===!0||Kv(g.object)===!1;!f&&g.material.isLineMaterial&&(f=!0),!f&&g.material.isPointsMaterial&&(f=!0),f&&(kf.push(g.object),g.object["needle:visible"]=g.object.visible,g.object.visible=!1)}i.setRenderTarget(this.renderTarget),i.clear(),i.render(t,this.shadowCamera),d.transparent=u;for(const g of kf)g["needle:visible"]!=null&&(g.visible=g["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(l),t.background=r,i.xr.enabled=c,this.context.scene.matrixWorldAutoUpdate=h}blurShadow(s){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=s*1/this.textureSize*n;const r=this.context.renderer,l=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=s*1/this.textureSize*o,r.setRenderTarget(this.renderTarget),r.render(this.blurPlane,this.shadowCamera),this.blurPlane.visible=!1,r.setRenderTarget(l)}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))}},a(Pf,"_instances",new Map),Pf);let Ps=Yc;Za([m()],Ps.prototype,"autoFit",2),Za([m()],Ps.prototype,"darkness",2),Za([m()],Ps.prototype,"opacity",2),Za([m()],Ps.prototype,"blur",2),Za([m()],Ps.prototype,"occludeBelowGround",2),Za([m()],Ps.prototype,"backfaceShadows",2);const Xw=[],kf=new Array,nR=C("logstats");class Mf extends A{onEnable(){console.log(this),nR&&this.startCoroutine(this.run(),Me.OnAfterRender)}*run(){for(;this.enabled;){const t=this.context.renderer.info;console.log(t.memory,t.render,t.programs),yield}}}class Zc extends A{constructor(){super(...arguments),a(this,"isUsed",!0),a(this,"usedBy",null)}}class Rf extends A{}const Qw=C("debugdeletable"),ju=class extends Ji{onEnable(){ju._instances.push(this)}onDisable(){const s=ju._instances.indexOf(this);s>=0&&ju._instances.splice(s,1)}};let Kc=ju;a(Kc,"_instances",[]);class Tf extends A{update(){for(const t of Kc._instances){const i=this.gameObject;if(t.isInBox(i)===!0){const n=O.getComponentInParent(this.gameObject,Zc);if(n)Qw&&console.warn("DeleteBox: Not deleting object with usage marker",this.guid,n);else{if(Qw)try{if(t.box){const o=t.box,r=Ji.testBox;q.DrawWireBox3(o,16711680,5),q.DrawWireBox3(r,255,5),console.log("DeleteBox: Destroying",this.gameObject,{deleteBoxArea:o,deletedObjectArea:r})}else console.log("DeleteBox: Destroying",this.gameObject)}catch{}wc(this.gameObject,this.context.connection)}}}}}var oR=Object.defineProperty,rR=Object.getOwnPropertyDescriptor,aR=(s,t,i,n)=>{for(var o=n>1?void 0:n?rR(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&oR(t,i,o),o};class Lu extends A{constructor(){super(...arguments),a(this,"visibleOn")}onEnable(){this.apply()}apply(){this.test()||O.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:X.isMobileDevice()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}}aR([m()],Lu.prototype,"visibleOn",2);var lR=Object.defineProperty,cR=Object.getOwnPropertyDescriptor,Ar=(s,t,i,n)=>{for(var o=n>1?void 0:n?cR(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&lR(t,i,o),o};const Ks=C("debugdrag"),Ef=[];var Af=(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))(Af||{}),Jc;const es=(Jc=class extends A{constructor(){super(...arguments),a(this,"dragMode",3),a(this,"snapGridResolution",0),a(this,"keepRotation",!0),a(this,"xrDragMode",1),a(this,"xrKeepRotation",!1),a(this,"xrDistanceDragFactor",1),a(this,"showGizmo",!1),a(this,"_rigidbody",null),a(this,"_targetObject",null),a(this,"_dragHelper",null),a(this,"_draggingRigidbodies",[]),a(this,"_potentialDragStartEvt",null),a(this,"_dragHandlers",new Map),a(this,"_totalMovement",new x),a(this,"_marker",null),a(this,"_isDragging",!1),a(this,"_didDrag",!1)}static get HasAnySelected(){return this._active>0}static get CurrentlySelected(){Ef.length=0;for(const s of this._instances)s._isDragging&&Ef.push(s);return Ef}get draggedObject(){return this._targetObject}setTargetObject(s){var t,i;this._targetObject=s;for(const o of this._dragHandlers.values())o.setTargetObject(s);const n="_rigidbody-was-kinematic";((t=this._rigidbody)==null?void 0:t[n])===!1&&(this._rigidbody.isKinematic=!1,this._rigidbody[n]=void 0),this._rigidbody=null,s&&(this._rigidbody=O.getComponentInChildren(s,ye),((i=this._rigidbody)==null?void 0:i.isKinematic)===!1&&(this._rigidbody.isKinematic=!0,this._rigidbody[n]=!1))}awake(){this._potentialDragStartEvt=null,this._dragHandlers=new Map,this._totalMovement=new x,this._marker=null,this._isDragging=!1,this._didDrag=!1,this._dragHelper=null,this._draggingRigidbodies=[]}start(){this.gameObject.getComponentInParent(Ei)||this.gameObject.addComponent(Ei)}onEnable(){es._instances.push(this)}onDisable(){es._instances=es._instances.filter(s=>s!==this)}allowEdit(s=null){return this.context.connection.allowEditing}onPointerEnter(s){if(!this.allowEdit(this.gameObject)||s.mode!=="screen"||(s.event.mode==="tracked-pointer"||s.event.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)return;const t=O.getComponentInParent(s.object,es);!t||t!==this||(es.lastHovered=s.object,this.context.domElement.style.cursor="pointer")}onPointerMove(s){(this._isDragging||this._potentialDragStartEvt!==null)&&s.use()}onPointerExit(s){this.allowEdit(this.gameObject)&&s.mode==="screen"&&es.lastHovered===s.object&&(this.context.domElement.style.cursor="auto")}onPointerDown(s){if(!(!this.allowEdit(this.gameObject)||s.used||(s.mode==="tracked-pointer"||s.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)&&(es.lastHovered=s.object,s.button===0)){this._dragHandlers.size===0&&(this._didDrag=!1,this._totalMovement.set(0,0,0),this._potentialDragStartEvt=s),this._targetObject||this.setTargetObject(this.gameObject),es._active+=1;const t=new If(this,this._targetObject);if(this._dragHandlers.set(s.event.space,t),t.onDragStart(s),this._dragHandlers.size===2){const i=this._dragHandlers.values(),n=i.next().value,o=i.next().value;if(n instanceof If&&o instanceof If){const r=new hR(this,this._targetObject,n,o);this._dragHandlers.set(this.gameObject,r),r.onDragStart(s)}else console.error("Attempting to construct a MultiTouchDragHandler with invalid DragPointerHandlers. This is likely a bug.",{a:n,b:o})}s.use()}}onPointerUp(s){if(Ks&&q.DrawLabel(s.point??this.gameObject.worldPosition,"POINTERUP:"+s.pointerId+", "+s.button,.03,3),!this.allowEdit(this.gameObject)||s.button!==0)return;this._potentialDragStartEvt=null;const t=this._dragHandlers.get(s.event.space),i=this._dragHandlers.get(this.gameObject);i&&(i.handlerA===t||i.handlerB===t)&&(this._dragHandlers.delete(this.gameObject),i.onDragEnd(s)),t&&(es._active>0&&(es._active-=1),this.setTargetObject(null),t.onDragEnd&&t.onDragEnd(s),this._dragHandlers.delete(s.event.space),this._dragHandlers.size===0&&this.onLastDragEnd(s),s.use())}update(){for(const s of this._dragHandlers.values())s.collectMovementInfo&&s.collectMovementInfo(),s.getTotalMovement&&this._totalMovement.add(s.getTotalMovement());if(this._potentialDragStartEvt){if(!this._didDrag)if(this._totalMovement.length()>3e-4)this._didDrag=!0;else return;const s=this._potentialDragStartEvt;this._potentialDragStartEvt=null,this.onFirstDragStart(s)}for(const s of this._dragHandlers.values())s.onDragUpdate&&s.onDragUpdate(this._dragHandlers.size);this._dragHelper&&this._dragHelper.hasSelected&&this.onAnyDragUpdate()}onFirstDragStart(s){if(!s||!s.object)return;const t=O.getComponentInParent(s.object,es);if(!t||t!==this&&t._isDragging)return;const i=this._targetObject||this.gameObject;if(!i)return;this._isDragging=!0;const n=O.getComponentInChildren(i,qs);Ks&&console.log("DRAG START",n,i),n&&(n.fastMode=!0,n?.requestOwnership()),this._marker=O.addComponent(i,Zc),this._draggingRigidbodies.length=0;const o=O.getComponentsInChildren(i,ye);o&&this._draggingRigidbodies.push(...o)}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 s=this._targetObject||this.gameObject;as.markDirty(s)}onLastDragEnd(s){if(!this||!this._isDragging)return;this._isDragging=!1;for(const i of this._draggingRigidbodies)i.setVelocity(i.smoothedVelocity);if(this._draggingRigidbodies.length=0,this._targetObject=null,s!=null&&s.object){const i=O.getComponentInChildren(s.object,qs);i&&(i.fastMode=!1)}if(this._marker&&this._marker.destroy(),!this._dragHelper)return;const t=this._dragHelper.selected;Ks&&console.log("DRAG END",t,t?.visible),this._dragHelper.setSelected(null,this.context)}},a(Jc,"_active",0),a(Jc,"_instances",[]),a(Jc,"lastHovered"),Jc);let ui=es;Ar([m()],ui.prototype,"dragMode",2),Ar([m()],ui.prototype,"snapGridResolution",2),Ar([m()],ui.prototype,"keepRotation",2),Ar([m()],ui.prototype,"xrDragMode",2),Ar([m()],ui.prototype,"xrKeepRotation",2),Ar([m()],ui.prototype,"xrDistanceDragFactor",2),Ar([m()],ui.prototype,"showGizmo",2);class hR{constructor(t,i,n,o){a(this,"handlerA"),a(this,"handlerB"),a(this,"context"),a(this,"settings"),a(this,"gameObject"),a(this,"_handlerAAttachmentPoint",new x),a(this,"_handlerBAttachmentPoint",new x),a(this,"_followObject"),a(this,"_manipulatorObject"),a(this,"_deviceMode"),a(this,"_followObjectStartWorldQuaternion",new V),a(this,"_manipulatorPosOffset",new x),a(this,"_manipulatorRotOffset",new V),a(this,"_manipulatorScaleOffset",new x),a(this,"_tempVec1",new x),a(this,"_tempVec2",new x),a(this,"_tempVec3",new x),a(this,"tempLookMatrix",new ne),a(this,"_initialScale",new x),a(this,"_initialDistance",0);var r,l;this.context=t.context,this.settings=t,this.gameObject=i,this.handlerA=n,this.handlerB=o,this._followObject=new I,this._manipulatorObject=new I,this.context.scene.add(this._manipulatorObject);const c=(l=(r=J.active)==null?void 0:r.rig)==null?void 0:l.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),c&&(c.worldToLocal(this._tempVec1),c.worldToLocal(this._tempVec2)),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.02?(Ks&&console.log("Finding alternative drag attachment points since initial distance is too low: "+this._initialDistance.toFixed(2)),this.handlerA.followObject.parent.getWorldPosition(this._tempVec1),this.handlerB.followObject.parent.getWorldPosition(this._tempVec2),this._handlerAAttachmentPoint.copy(this._tempVec1),this._handlerBAttachmentPoint.copy(this._tempVec2),this.gameObject.worldToLocal(this._handlerAAttachmentPoint),this.gameObject.worldToLocal(this._handlerBAttachmentPoint),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.001&&(console.warn("Not supported right now \u2013 controller drag points for multitouch are too close!"),this._initialDistance=1)):(this._handlerAAttachmentPoint.copy(this.handlerA.hitPointInLocalSpace),this._handlerBAttachmentPoint.copy(this.handlerB.hitPointInLocalSpace)),this._tempVec3.lerpVectors(this._tempVec1,this._tempVec2,.5),this._initialScale.copy(i.scale),Ks){this._followObject.add(new xi(2)),this._manipulatorObject.add(new xi(5));const h=d=>`${d.x.toFixed(2)}, ${d.y.toFixed(2)}, ${d.z.toFixed(2)}`;q.DrawLine(this._tempVec1,this._tempVec2,65535,0,!1),q.DrawLabel(this._tempVec3,"A:B "+this._initialDistance.toFixed(2)+`
932
936
  `+h(this._tempVec1)+`
933
- `+h(this._tempVec2),.03,5)}}onDragStart(t){this.gameObject.add(this._followObject),this._followObject.matrixAutoUpdate=!1,this._followObject.matrix.identity(),this._deviceMode=t.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(t){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()}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 t=this.context.mainCamera;this.tempLookMatrix.lookAt(this._tempVec3,this._tempVec2,t.worldUp),this._manipulatorObject.quaternion.setFromRotationMatrix(this.tempLookMatrix);const i=this._tempVec1.distanceTo(this._tempVec2);this._manipulatorObject.scale.copy(this._initialScale).multiplyScalar(i/this._initialDistance),this._manipulatorObject.updateMatrix(),this._manipulatorObject.updateMatrixWorld(!0),Ks&&(q.DrawLabel(this._tempVec3.clone().add(new x(0,.2,0)),"A:B "+i.toFixed(2),.03),q.DrawLine(this._tempVec1,this._tempVec2,65280,0,!1))}onDragUpdate(){this.alignManipulator();const t=30,i=1;this._followObject.position.copy(this._manipulatorPosOffset),this._followObject.quaternion.copy(this._manipulatorRotOffset),this._followObject.scale.copy(this._manipulatorScaleOffset);const n=this.gameObject,o=this._followObject;if(!n){console.error("MultiTouchDragHandler has no dragged object. This is likely a bug.");return}o.updateMatrix(),o.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 l=W.clamp01(this.context.time.deltaTime*t*i),c=n.worldPosition;c.lerp(o.worldPosition,l),n.worldPosition=c;const h=n.worldQuaternion;h.slerp(o.worldQuaternion,l),n.worldQuaternion=h;const d=n.worldScale;d.lerp(o.worldScale,l),n.worldScale=d}setTargetObject(t){this.gameObject=t}}class If{constructor(t,i){a(this,"context"),a(this,"gameObject"),a(this,"settings"),a(this,"_lastRig"),a(this,"_followObject"),a(this,"_totalMovement",new x),a(this,"_totalMovementAlongRayDirection",0),a(this,"_grabStartDistance",0),a(this,"_deviceMode"),a(this,"_followObjectStartPosition",new x),a(this,"_followObjectStartQuaternion",new V),a(this,"_followObjectStartWorldQuaternion",new V),a(this,"_lastDragPosRigSpace"),a(this,"_tempVec",new x),a(this,"_tempMat",new ne),a(this,"_hitPointInLocalSpace",new x),a(this,"_hitNormalInLocalSpace",new x),a(this,"_bottomCenter",new x),a(this,"_backCenter",new x),a(this,"_backBottomCenter",new x),a(this,"_bounds",new wi),a(this,"_dragPlane",new nr(new x(0,1,0))),a(this,"_draggedOverObject",null),a(this,"_draggedOverObjectLastSetUp",null),a(this,"_draggedOverObjectLastNormal",new x),a(this,"_draggedOverObjectDuration",0),a(this,"_hasLastSurfaceHitPoint",!1),a(this,"_lastSurfaceHitPoint",new x),this.settings=t,this.context=t.context,this.gameObject=i,this._followObject=new I}getTotalMovement(){return this._totalMovement}get followObject(){return this._followObject}get hitPointInLocalSpace(){return this._hitPointInLocalSpace}setTargetObject(t){this.gameObject=t}recenter(){var t,i;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 n=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),n.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 o=this._hitPointInLocalSpace.clone();this.gameObject.localToWorld(o),this._grabStartDistance=o.distanceTo(n.worldPosition);const r=(i=(t=J.active)==null?void 0:t.rig)==null?void 0:i.gameObject,l=r?.worldScale.x||1;this._grabStartDistance/=l,this._totalMovementAlongRayDirection=0,this._lastDragPosRigSpace=void 0,Ks&&(q.DrawLine(o,n.worldPosition,65280,.5,!1),q.DrawLabel(n.worldPosition.add(new x(0,.1,0)),this._grabStartDistance.toFixed(2),.03,.5))}onDragStart(t){if(!this.gameObject){console.warn("Error: space follow object doesn't have a gameObject");return}if(t.event.space.add(this._followObject),this._lastDragPosRigSpace=void 0,t.point&&t.normal)this._hitPointInLocalSpace.copy(t.point),this.gameObject.worldToLocal(this._hitPointInLocalSpace),this._hitNormalInLocalSpace.copy(t.normal);else if(t){const y=t.event.space,f=y.worldPosition;this.gameObject.worldToLocal(f),this._hitPointInLocalSpace.copy(f);const v=y.worldUp;this._tempMat.copy(this.gameObject.matrixWorld).invert(),v.transformDirection(this._tempMat),this._hitNormalInLocalSpace.copy(v)}this.recenter(),this._totalMovement.set(0,0,0),this._deviceMode=t.mode;const i=this._followObject.parent.worldForward,n=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrDragMode:this.settings.dragMode,o=this._hitPointInLocalSpace.clone();switch(this.gameObject.localToWorld(o),n){case 0:const y=new x(0,1,0);this.gameObject.parent&&y.transformDirection(this.gameObject.parent.matrixWorld.clone().invert()),this._dragPlane.setFromNormalAndCoplanarPoint(y,o);break;case 2:const f=this._hitNormalInLocalSpace.clone();f.transformDirection(this.gameObject.matrixWorld),this._dragPlane.setFromNormalAndCoplanarPoint(f,o);break;case 1:this._dragPlane.setFromNormalAndCoplanarPoint(i,o);break;case 3:this.setPlaneViewAligned(o,!0);break;case 4:this.setPlaneViewAligned(o,!1);break}const r=this.gameObject.parent,l=this.gameObject.position.clone(),c=this.gameObject.quaternion.clone(),h=this.gameObject.scale.clone(),d=this.gameObject.matrixWorld.clone();r&&r.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 u=oi([this.gameObject]);u.expandByPoint(this.gameObject.worldPosition);const p=new x;u.getCenter(p);const g=new x;u.getSize(g),this._bottomCenter.copy(p.clone().add(new x(0,-g.y/2,0))),this._backCenter.copy(p.clone().add(new x(0,0,g.z/2))),this._backBottomCenter.copy(p.clone().add(new x(0,-g.y/2,g.z/2))),this._bounds.copy(u),r&&r.add(this.gameObject),this.gameObject.position.copy(l),this.gameObject.quaternion.copy(c),this.gameObject.scale.copy(h),this.gameObject.matrixWorld.copy(d),this._draggedOverObject=null,this._draggedOverObjectLastSetUp=null,this._draggedOverObjectLastNormal.set(0,1,0),this._draggedOverObjectDuration=0}collectMovementInfo(){var t,i;if(!this._followObject.parent)return;const n=this._followObject.parent;this._followObject.updateMatrix();const o=n.worldPosition,r=(i=(t=J.active)==null?void 0:t.rig)==null?void 0:i.gameObject;r&&r.worldToLocal(o),(this._lastDragPosRigSpace===void 0||r!=this._lastRig)&&(this._lastDragPosRigSpace=o.clone(),this._lastRig=r),this._tempVec.copy(o).sub(this._lastDragPosRigSpace);const l=n.worldForward;if(r&&(this._tempMat.copy(r.matrixWorld).invert(),l.transformDirection(this._tempMat)),this._totalMovementAlongRayDirection+=l.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(o),Ks){let c=o;r&&(c=c.clone(),c.transformDirection(r.matrixWorld)),q.DrawRay(c,l,255)}}onDragUpdate(t){if(t>1)return;const i=this.gameObject;if(!i||!this._followObject){console.warn("Warning: DragPointerHandler doesn't have a dragged object. This is likely a bug.");return}const n=this._followObject.parent;if(!n){console.warn("Warning: DragPointerHandler doesn't have a drag source. This is likely a bug.");return}this._followObject.updateMatrix();const o=n.worldPosition,r=n.worldForward,l=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer",c=l?this.settings.xrKeepRotation:this.settings.keepRotation,h=l?this.settings.xrDragMode:this.settings.dragMode;if(h===5)return;const d=10;c&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);let u=1,p=2;if(l&&this._grabStartDistance>.5){const _=1+this._totalMovementAlongRayDirection*(2*this.settings.xrDistanceDragFactor);u=Math.max(0,_),u=u*u*u}else this._grabStartDistance<=.5&&(p=3);this._followObject.position.copy(this._followObjectStartPosition),c||this._followObject.quaternion.copy(this._followObjectStartQuaternion),this._followObject.position.multiplyScalar(u),this._followObject.updateMatrix();const g=this._hasLastSurfaceHitPoint;this._hasLastSurfaceHitPoint=!1;const y=new no(o,r);if(h==4){const _=this.context.physics.raycastFromRay(y,{testObject:S=>S!==this.followObject&&S!==n&&S!==i});if(_.length>0){const S=_[0];if(this._draggedOverObject===S.object?this._draggedOverObjectDuration+=this.context.time.deltaTime:(this._draggedOverObject=S.object,this._draggedOverObjectDuration=0),S.face){this._hasLastSurfaceHitPoint=!0,this._lastSurfaceHitPoint.copy(S.point);const R=.15,M=this._draggedOverObjectDuration>=R,T=.001,j=this._totalMovement.length()>=T,L=G(S.normal||S.face.normal).applyQuaternion(S.object.worldQuaternion);if((M||j)&&(this._draggedOverObjectLastSetUp!==this._draggedOverObject||this._draggedOverObjectLastNormal.dot(L)<.999999||this.context.time.frame%60===0)){this._draggedOverObjectLastSetUp=this._draggedOverObject,this._draggedOverObjectLastNormal.copy(S.face.normal);const U=G(),B=G();this._bounds.getCenter(U),this._bounds.getSize(B),U.sub(B.multiplyScalar(.5).multiply(L)),this._hitPointInLocalSpace.copy(U),this._hitNormalInLocalSpace.copy(S.face.normal),this._bounds.getCenter(U),this._bounds.getSize(B),U.add(B.multiplyScalar(.5).multiply(S.face.normal));const Q=G(this._hitPointInLocalSpace).add(U);this._followObject.localToWorld(Q);const $=S.point;this._dragPlane.setFromNormalAndCoplanarPoint(L,$)}else if(!(M||j))return}}else g&&this.gameObject&&this.setPlaneViewAligned(this.gameObject.worldPosition,!1)}if(h!==1&&y.intersectPlane(this._dragPlane,this._tempVec)){this._followObject.worldPosition=this._tempVec,this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);const _=G(this._hitPointInLocalSpace);this._followObject.localToWorld(_),Ks&&q.DrawLine(_,this._tempVec,65535,0,!1),this._followObject.worldPosition=this._tempVec.multiplyScalar(2).sub(_),this._followObject.updateMatrix(),this._followObject.updateMatrix()}if(this.settings.snapGridResolution>0){const _=this._followObject.worldPosition,S=this.settings.snapGridResolution;_.x=Math.round(_.x/S)*S,_.y=Math.round(_.y/S)*S,_.z=Math.round(_.z/S)*S,this._followObject.worldPosition=_,this._followObject.updateMatrix()}c&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const f=W.clamp01(this.context.time.deltaTime*d*p),v=W.clamp01(this.context.time.deltaTime*d*.5*p),b=i.worldPosition;b.lerp(this._followObject.worldPosition,f),i.worldPosition=b;const w=i.worldQuaternion;if(w.slerp(this._followObject.worldQuaternion,v),i.worldQuaternion=w,Ks){const _=this._hitPointInLocalSpace.clone();i.localToWorld(_),q.DrawSphere(_,.02,16711680);const S=this._hitNormalInLocalSpace.clone();S.applyQuaternion(w),q.DrawRay(_,S,16711680),q.DrawLabel(b.add(new x(0,.25,0)),`Distance: ${this._totalMovement.length().toFixed(2)}
937
+ `+h(this._tempVec2),.03,5)}}onDragStart(t){this.gameObject.add(this._followObject),this._followObject.matrixAutoUpdate=!1,this._followObject.matrix.identity(),this._deviceMode=t.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(t){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()}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 t=this.context.mainCamera;this.tempLookMatrix.lookAt(this._tempVec3,this._tempVec2,t.worldUp),this._manipulatorObject.quaternion.setFromRotationMatrix(this.tempLookMatrix);const i=this._tempVec1.distanceTo(this._tempVec2);this._manipulatorObject.scale.copy(this._initialScale).multiplyScalar(i/this._initialDistance),this._manipulatorObject.updateMatrix(),this._manipulatorObject.updateMatrixWorld(!0),Ks&&(q.DrawLabel(this._tempVec3.clone().add(new x(0,.2,0)),"A:B "+i.toFixed(2),.03),q.DrawLine(this._tempVec1,this._tempVec2,65280,0,!1))}onDragUpdate(){this.alignManipulator();const t=30,i=1;this._followObject.position.copy(this._manipulatorPosOffset),this._followObject.quaternion.copy(this._manipulatorRotOffset),this._followObject.scale.copy(this._manipulatorScaleOffset);const n=this.gameObject,o=this._followObject;if(!n){console.error("MultiTouchDragHandler has no dragged object. This is likely a bug.");return}o.updateMatrix(),o.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 l=W.clamp01(this.context.time.deltaTime*t*i),c=n.worldPosition;c.lerp(o.worldPosition,l),n.worldPosition=c;const h=n.worldQuaternion;h.slerp(o.worldQuaternion,l),n.worldQuaternion=h;const d=n.worldScale;d.lerp(o.worldScale,l),n.worldScale=d}setTargetObject(t){this.gameObject=t}}class If{constructor(t,i){a(this,"context"),a(this,"gameObject"),a(this,"settings"),a(this,"_lastRig"),a(this,"_followObject"),a(this,"_totalMovement",new x),a(this,"_totalMovementAlongRayDirection",0),a(this,"_grabStartDistance",0),a(this,"_deviceMode"),a(this,"_followObjectStartPosition",new x),a(this,"_followObjectStartQuaternion",new V),a(this,"_followObjectStartWorldQuaternion",new V),a(this,"_lastDragPosRigSpace"),a(this,"_tempVec",new x),a(this,"_tempMat",new ne),a(this,"_hitPointInLocalSpace",new x),a(this,"_hitNormalInLocalSpace",new x),a(this,"_bottomCenter",new x),a(this,"_backCenter",new x),a(this,"_backBottomCenter",new x),a(this,"_bounds",new wi),a(this,"_dragPlane",new nr(new x(0,1,0))),a(this,"_draggedOverObject",null),a(this,"_draggedOverObjectLastSetUp",null),a(this,"_draggedOverObjectLastNormal",new x),a(this,"_draggedOverObjectDuration",0),a(this,"_hasLastSurfaceHitPoint",!1),a(this,"_lastSurfaceHitPoint",new x),this.settings=t,this.context=t.context,this.gameObject=i,this._followObject=new I}getTotalMovement(){return this._totalMovement}get followObject(){return this._followObject}get hitPointInLocalSpace(){return this._hitPointInLocalSpace}setTargetObject(t){this.gameObject=t}recenter(){var t,i;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 n=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),n.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 o=this._hitPointInLocalSpace.clone();this.gameObject.localToWorld(o),this._grabStartDistance=o.distanceTo(n.worldPosition);const r=(i=(t=J.active)==null?void 0:t.rig)==null?void 0:i.gameObject,l=r?.worldScale.x||1;this._grabStartDistance/=l,this._totalMovementAlongRayDirection=0,this._lastDragPosRigSpace=void 0,Ks&&(q.DrawLine(o,n.worldPosition,65280,.5,!1),q.DrawLabel(n.worldPosition.add(new x(0,.1,0)),this._grabStartDistance.toFixed(2),.03,.5))}onDragStart(t){if(!this.gameObject){console.warn("Error: space follow object doesn't have a gameObject");return}if(t.event.space.add(this._followObject),this._lastDragPosRigSpace=void 0,t.point&&t.normal)this._hitPointInLocalSpace.copy(t.point),this.gameObject.worldToLocal(this._hitPointInLocalSpace),this._hitNormalInLocalSpace.copy(t.normal);else if(t){const y=t.event.space,f=y.worldPosition;this.gameObject.worldToLocal(f),this._hitPointInLocalSpace.copy(f);const v=y.worldUp;this._tempMat.copy(this.gameObject.matrixWorld).invert(),v.transformDirection(this._tempMat),this._hitNormalInLocalSpace.copy(v)}this.recenter(),this._totalMovement.set(0,0,0),this._deviceMode=t.mode;const i=this._followObject.parent.worldForward,n=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrDragMode:this.settings.dragMode,o=this._hitPointInLocalSpace.clone();switch(this.gameObject.localToWorld(o),n){case 0:const y=new x(0,1,0);this.gameObject.parent&&y.transformDirection(this.gameObject.parent.matrixWorld.clone().invert()),this._dragPlane.setFromNormalAndCoplanarPoint(y,o);break;case 2:const f=this._hitNormalInLocalSpace.clone();f.transformDirection(this.gameObject.matrixWorld),this._dragPlane.setFromNormalAndCoplanarPoint(f,o);break;case 1:this._dragPlane.setFromNormalAndCoplanarPoint(i,o);break;case 3:this.setPlaneViewAligned(o,!0);break;case 4:this.setPlaneViewAligned(o,!1);break}const r=this.gameObject.parent,l=this.gameObject.position.clone(),c=this.gameObject.quaternion.clone(),h=this.gameObject.scale.clone(),d=this.gameObject.matrixWorld.clone();r&&r.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 u=oi([this.gameObject]);u.expandByPoint(this.gameObject.worldPosition);const p=new x;u.getCenter(p);const g=new x;u.getSize(g),this._bottomCenter.copy(p.clone().add(new x(0,-g.y/2,0))),this._backCenter.copy(p.clone().add(new x(0,0,g.z/2))),this._backBottomCenter.copy(p.clone().add(new x(0,-g.y/2,g.z/2))),this._bounds.copy(u),r&&r.add(this.gameObject),this.gameObject.position.copy(l),this.gameObject.quaternion.copy(c),this.gameObject.scale.copy(h),this.gameObject.matrixWorld.copy(d),this._draggedOverObject=null,this._draggedOverObjectLastSetUp=null,this._draggedOverObjectLastNormal.set(0,1,0),this._draggedOverObjectDuration=0}collectMovementInfo(){var t,i;if(!this._followObject.parent)return;const n=this._followObject.parent;this._followObject.updateMatrix();const o=n.worldPosition,r=(i=(t=J.active)==null?void 0:t.rig)==null?void 0:i.gameObject;r&&r.worldToLocal(o),(this._lastDragPosRigSpace===void 0||r!=this._lastRig)&&(this._lastDragPosRigSpace=o.clone(),this._lastRig=r),this._tempVec.copy(o).sub(this._lastDragPosRigSpace);const l=n.worldForward;if(r&&(this._tempMat.copy(r.matrixWorld).invert(),l.transformDirection(this._tempMat)),this._totalMovementAlongRayDirection+=l.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(o),Ks){let c=o;r&&(c=c.clone(),c.transformDirection(r.matrixWorld)),q.DrawRay(c,l,255)}}onDragUpdate(t){if(t>1)return;const i=this.gameObject;if(!i||!this._followObject){console.warn("Warning: DragPointerHandler doesn't have a dragged object. This is likely a bug.");return}const n=this._followObject.parent;if(!n){console.warn("Warning: DragPointerHandler doesn't have a drag source. This is likely a bug.");return}this._followObject.updateMatrix();const o=n.worldPosition,r=n.worldForward,l=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer",c=l?this.settings.xrKeepRotation:this.settings.keepRotation,h=l?this.settings.xrDragMode:this.settings.dragMode;if(h===5)return;const d=10;c&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);let u=1,p=2;if(l&&this._grabStartDistance>.5){const _=1+this._totalMovementAlongRayDirection*(2*this.settings.xrDistanceDragFactor);u=Math.max(0,_),u=u*u*u}else this._grabStartDistance<=.5&&(p=3);this._followObject.position.copy(this._followObjectStartPosition),c||this._followObject.quaternion.copy(this._followObjectStartQuaternion),this._followObject.position.multiplyScalar(u),this._followObject.updateMatrix();const g=this._hasLastSurfaceHitPoint;this._hasLastSurfaceHitPoint=!1;const y=new no(o,r);if(h==4){const _=this.context.physics.raycastFromRay(y,{testObject:S=>S!==this.followObject&&S!==n&&S!==i});if(_.length>0){const S=_[0];if(this._draggedOverObject===S.object?this._draggedOverObjectDuration+=this.context.time.deltaTime:(this._draggedOverObject=S.object,this._draggedOverObjectDuration=0),S.face){this._hasLastSurfaceHitPoint=!0,this._lastSurfaceHitPoint.copy(S.point);const R=.15,M=this._draggedOverObjectDuration>=R,T=.001,L=this._totalMovement.length()>=T,D=G(S.normal||S.face.normal).applyQuaternion(S.object.worldQuaternion);if((M||L)&&(this._draggedOverObjectLastSetUp!==this._draggedOverObject||this._draggedOverObjectLastNormal.dot(D)<.999999||this.context.time.frame%60===0)){this._draggedOverObjectLastSetUp=this._draggedOverObject,this._draggedOverObjectLastNormal.copy(S.face.normal);const U=G(),B=G();this._bounds.getCenter(U),this._bounds.getSize(B),U.sub(B.multiplyScalar(.5).multiply(D)),this._hitPointInLocalSpace.copy(U),this._hitNormalInLocalSpace.copy(S.face.normal),this._bounds.getCenter(U),this._bounds.getSize(B),U.add(B.multiplyScalar(.5).multiply(S.face.normal));const Q=G(this._hitPointInLocalSpace).add(U);this._followObject.localToWorld(Q);const $=S.point;this._dragPlane.setFromNormalAndCoplanarPoint(D,$)}else if(!(M||L))return}}else g&&this.gameObject&&this.setPlaneViewAligned(this.gameObject.worldPosition,!1)}if(h!==1&&y.intersectPlane(this._dragPlane,this._tempVec)){this._followObject.worldPosition=this._tempVec,this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);const _=G(this._hitPointInLocalSpace);this._followObject.localToWorld(_),Ks&&q.DrawLine(_,this._tempVec,65535,0,!1),this._followObject.worldPosition=this._tempVec.multiplyScalar(2).sub(_),this._followObject.updateMatrix(),this._followObject.updateMatrix()}if(this.settings.snapGridResolution>0){const _=this._followObject.worldPosition,S=this.settings.snapGridResolution;_.x=Math.round(_.x/S)*S,_.y=Math.round(_.y/S)*S,_.z=Math.round(_.z/S)*S,this._followObject.worldPosition=_,this._followObject.updateMatrix()}c&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const f=W.clamp01(this.context.time.deltaTime*d*p),v=W.clamp01(this.context.time.deltaTime*d*.5*p),b=i.worldPosition;b.lerp(this._followObject.worldPosition,f),i.worldPosition=b;const w=i.worldQuaternion;if(w.slerp(this._followObject.worldQuaternion,v),i.worldQuaternion=w,Ks){const _=this._hitPointInLocalSpace.clone();i.localToWorld(_),q.DrawSphere(_,.02,16711680);const S=this._hitNormalInLocalSpace.clone();S.applyQuaternion(w),q.DrawRay(_,S,16711680),q.DrawLabel(b.add(new x(0,.25,0)),`Distance: ${this._totalMovement.length().toFixed(2)}
934
938
 
935
939
  Along Ray: ${this._totalMovementAlongRayDirection.toFixed(2)}
936
940
 
@@ -939,7 +943,7 @@ Incoming:`,this._incomingCalls),r}else nt&&console.error("Failed to make call",s
939
943
  Device: ${this._deviceMode}
940
944
 
941
945
  `,.03);const R=this._bottomCenter.clone(),M=this._backCenter.clone(),T=this._backBottomCenter.clone();i.localToWorld(R),i.localToWorld(M),i.localToWorld(T),q.DrawSphere(R,.01,65280,0,!1),q.DrawSphere(M,.01,255,0,!1),q.DrawSphere(T,.01,16711935,0,!1),q.DrawLine(R,T,65535,0,!1),q.DrawLine(T,M,65535,0,!1)}}onDragEnd(t){console.assert(this._followObject.parent===t.event.space,"Drag end: _followObject is not parented to the space object"),this._followObject.removeFromParent(),this._followObject.destroy(),this._lastDragPosRigSpace=void 0}setPlaneViewAligned(t,i){if(!this._followObject.parent)return!1;const n=this._followObject.parent.worldForward,o=G(0,1,0),r=n,l=o.angleTo(r),c=.5;return i&&(l>Math.PI/2+c||l<Math.PI/2-c)?this._dragPlane.setFromNormalAndCoplanarPoint(o,t):this._dragPlane.setFromNormalAndCoplanarPoint(n,t),!0}}const Yw=class{constructor(s){a(this,"showGizmo",!0),a(this,"useViewAngle",!0),a(this,"_selected",null),a(this,"_context",null),a(this,"_camera"),a(this,"_cameraPlane",new nr),a(this,"_hasGroundPlane",!1),a(this,"_groundPlane",new nr),a(this,"_groundOffset",new x),a(this,"_groundOffsetFactor",0),a(this,"_groundDistance",0),a(this,"_groundPlanePoint",new x),a(this,"_raycaster",new rd),a(this,"_cameraPlaneOffset",new x),a(this,"_intersection",new x),a(this,"_worldPosition",new x),a(this,"_inverseMatrix",new ne),a(this,"_rbs",[]),a(this,"_groundLine"),a(this,"_groundMarker"),a(this,"_groundOffsetVector",new x(0,1,0)),a(this,"_requireUpdateGroundPlane",!0),a(this,"_didDragOnGroundPlaneLastFrame",!1),this._camera=s;const t=new Gl(Yw.geometry),i=t.material;i.color=new ae(.4,.4,.4),t.layers.set(2),t.name="line",t.scale.y=1,this._groundLine=t;const n=new nd(.5,22,22),o=new Re({color:i.color}),r=new Y(n,o);r.visible=!1,r.layers.set(2),this._groundMarker=r}get hasSelected(){return this._selected!==null&&this._selected!==void 0}get selected(){return this._selected}setSelected(s,t){if(this._selected&&t)for(const i of this._rbs)i.wakeUp(),i.setVelocity(0,0,0);if(this._selected&&En.Remove(t,this._selected),this._selected=s,this._context=t,this._rbs.length=0,s?(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}En.Add(t,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this.onUpdateScreenSpacePlane()}}onUpdate(s){this._selected}onUpdateWorldPosition(s,t,i){if(this._selected){if(i){const n=te(this._selected);n.y=s.y,s=n}if(ht(this._selected,s),ht(this._groundLine,s),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=te(this._camera).distanceTo(t)*.01;this._groundMarker.scale.set(n,n,n),ht(this._groundMarker,t)}}}onUpdateScreenSpacePlane(){if(!this._selected||!this._context)return;const s=this._context.input.getPointerPositionRC(0);s&&(this._raycaster.setFromCamera(s,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 s=te(this._selected),t=new no(G(0,.1,0).add(s),G(0,-1,0)),i=new Ws;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 l=G(0,1,0);this._groundPlane.setFromNormalAndCoplanarPoint(l,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(s),this._groundOffset.copy(this._intersection).sub(s)}contains(s,t){if(s===t)return!0;if(s.children){for(const i of s.children)if(this.contains(i,t))return!0}return!1}};let dR=Yw;a(dR,"geometry",new gn().setFromPoints([new x(0,0,0),new x(0,-1,0)]));var Zw=(s=>(s.File_Spawned="file-spawned",s))(Zw||{});class uR{constructor(t,i,n,o,r,l,c,h,d){a(this,"guid"),a(this,"file_name"),a(this,"file_hash"),a(this,"file_size"),a(this,"position"),a(this,"scale"),a(this,"seed"),a(this,"sender"),a(this,"downloadUrl"),a(this,"parentGuid"),a(this,"boundsSize"),this.seed=i,this.guid=n,this.file_name=o,this.file_hash=r,this.file_size=l,this.position=c,this.scale=h,this.sender=t,this.downloadUrl=d}}var To;(s=>{const t=new Map;function i(o){var r;t.has(o.guid)&&n(o.guid);const l=new I;t.set(o.guid,l);const c=new I;c.position.y=-.5,l.add(c);const h=new Y(new ql(1,1,1,1,1,1),new Re({color:14540253,wireframe:!0,transparent:!0,opacity:.3}));h.position.y=.5,c.add(h);const d=new I;c.add(d);const u=new Y(new ql(1,1,1,1,1,1),new Re({color:12307660,transparent:!0,opacity:.4}));u.position.y=.5,d.scale.y=.01,d.add(u);const p=new Y(new Fs(1,1,1,1),new Re({color:34,transparent:!0,opacity:.05,depthTest:!1}));return p.rotateX(-Math.PI/2),p.position.y=.51,u.add(p),o.parent.add(l),l.rotateY(Math.PI/2),o.position&&((r=l.position)==null||r.copy(o.position)),o.size&&(l.worldScale=new x().copy(o.size)),l.position.y=l.scale.y/2,{object:l,onProgress:g=>{d instanceof I&&d.scale.set(1,g,1)}}}s.addPreview=i;function n(o){const r=t.get(o);r&&(t.delete(o),r.removeFromParent())}s.removePreview=n})(To||(To={}));var pR=Object.defineProperty,mR=Object.getOwnPropertyDescriptor,Ka=(s,t,i,n)=>{for(var o=n>1?void 0:n?mR(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&pR(t,i,o),o};const ks=C("debugdroplistener");class gR extends CustomEvent{constructor(t){super("object-added",{detail:t})}}const fR="blob";class Dn extends A{constructor(){super(...arguments),a(this,"useNetworking",!0),a(this,"dropArea"),a(this,"fitIntoVolume",!1),a(this,"fitVolumeSize",new x(1,1,1)),a(this,"placeAtHitPosition",!0),a(this,"onDropped",new Se),a(this,"onNetworkEvent",t=>{var i;if(!this.useNetworking){ks&&console.debug("[DropListener] Ignoring networked event because networking is disabled",t);return}if((i=t.guid)!=null&&i.startsWith(this.guid)){const n=t.url;if(console.debug("[DropListener] Received networked event",t),n)if(Array.isArray(n))for(const o of n)this.addFromUrl(o,{screenposition:new re,point:t.point,size:t.size},!0);else this.addFromUrl(n,{screenposition:new re,point:t.point,size:t.size},!0)}}),a(this,"handlePaste",t=>{this.context.connection.allowEditing===!1||t.defaultPrevented||navigator.clipboard.readText().then(i=>{if(i&&(i.startsWith("http")||i.startsWith("https")||i.startsWith("blob"))){const n={screenposition:new re(this.context.input.mousePosition.x,this.context.input.mousePosition.y)};this.testIfIsInDropArea(n)&&this.addFromUrl(i,n,!1)}}).catch(console.warn)}),a(this,"onDrag",t=>{this.context.connection.allowEditing!==!1&&t.preventDefault()}),a(this,"onDrop",async t=>{if(this.context.connection.allowEditing===!1||(ks&&console.log(t),!(t!=null&&t.dataTransfer))||t["droplistener:handled"])return;t.preventDefault();const i={screenposition:new re(t.offsetX,t.offsetY)};if(this.dropArea&&this.testIfIsInDropArea(i)===!1)return;t["droplistener:handled"]=!0;const n=t.dataTransfer.items;if(!n)return;const o=[];for(const r in n){const l=n[r];if(l.kind==="file"){const c=l.getAsFile();if(!c)continue;o.push(c)}else l.kind==="string"&&l.type=="text/plain"&&l.getAsString(c=>{this.addFromUrl(c,i,!1)})}o.length>0&&await this.addDroppedFiles(o,i)}),a(this,"_abort",null),a(this,"_addedObjects",new Array),a(this,"_addedModels",new Array)}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)}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)}loadFromURL(t,i){this.addFromUrl(t,{screenposition:new re,point:i?.point,size:i?.size},!0)}forgetObjects(){this.removePreviouslyAddedObjects(!1)}async addFromUrl(t,i,n){ks&&console.log("dropped url",t);try{if(t.startsWith("https://github.com/")){const l=t.split("/"),c=l[3],h=l[4],d=l[6],u=l.slice(7).join("/");t=`https://raw.githubusercontent.com/${c}/${h}/${d}/${u}`}else t.startsWith("https://polyhaven.com/a")&&(t=yR(t));if(!t)return null;const o=t.toLowerCase();if(o.endsWith(".hdr")||o.endsWith(".hdri")||o.endsWith(".exr")||o.endsWith(".png")||o.endsWith(".jpg")||o.endsWith(".jpeg"))return null;this.removePreviouslyAddedObjects();const r=await Du.loadFileFromURL(new URL(t),{guid:this.guid,context:this.context,parent:this.gameObject,point:i.point,size:i.size});if(r&&this._addedObjects.length<=0)return i.url=t,this.addObject(r,i,n)}catch{console.warn("String is not a valid URL",t)}return null}async addDroppedFiles(t,i){var n,o;if(ks&&console.log("Add files",t),!!Array.isArray(t)&&t.length){this.deleteDropEvent(),this.removePreviouslyAddedObjects(),Yl(fR,null),(n=this._abort)==null||n.abort("New files dropped"),this._abort=new AbortController;for(const r of t){if(!r)continue;console.debug("Load file "+r.name);const l=await Du.loadFile(r,this.context,{guid:this.guid});if(l){this.dispatchEvent(new CustomEvent("file-dropped",{detail:r})),i.file=r;const c=this.addObject(l,i,!1);c&&this.context.connection.isConnected&&this.useNetworking&&(console.debug("Uploading dropped file to blob storage"),_r.upload(r,{abort:(o=this._abort)==null?void 0:o.signal}).then(h=>{h!=null&&h.download_url&&this._addedObjects.includes(c)&&this.sendDropEvent(h.download_url,c,l.contentMD5)}).catch(console.warn));break}}}}removePreviouslyAddedObjects(t=!0){if(t)for(const i of this._addedObjects)i.parent===this.gameObject&&Ri(i,!0,!0);this._addedObjects.length=0,this._addedModels.length=0}addObject(t,i,n){var o,r;const{model:l,contentMD5:c}=t;if(ks&&console.log(`Dropped ${this.gameObject.name}`,l),!(l!=null&&l.scene))return console.warn("No object specified to add to scene",l),null;this.removePreviouslyAddedObjects();const h=l.scene;this.gameObject.attach(h),h.position.set(0,0,0),h.quaternion.identity(),this._addedObjects.push(h),this._addedModels.push(l);const d=new wi().setFromCenterAndSize(new x(0,this.fitVolumeSize.y*.5,0).add(this.gameObject.worldPosition),this.fitVolumeSize);if(ks&&q.DrawWireBox3(d,255,5),this.fitIntoVolume&&Jv(h,d,{position:!this.placeAtHitPosition}),this.placeAtHitPosition&&i&&i.screenposition){h.visible=!1;const p=this.context.physics.raycast({screenPoint:this.context.input.convertScreenspaceToRaycastSpace(i.screenposition.clone())});if(h.visible=!0,p&&p.length>0)for(const g of p){const y=g.point.clone();ks&&console.log("Place object at hit",g),eb(h,y);break}}Ba.assignAnimationsFromFile(l,{createAnimationComponent:p=>Mi(p,zt)});const u=new gR({sender:this,gltf:l,model:l,object:h,contentMD5:c,dropped:i.file||(i.url?new URL(i.url):void 0)});return this.dispatchEvent(u),(o=this.onDropped)==null||o.invoke(u.detail),!n&&(r=i.url)!=null&&r.startsWith("http")&&this.context.connection.isConnected&&h&&this.sendDropEvent(i.url,h,c),h}async sendDropEvent(t,i,n){if(!this.useNetworking){ks&&console.debug("[DropListener] Ignoring networked event because networking is disabled",t);return}if(this.context.connection.isConnected){console.debug('Sending drop event "'+i.name+'"',t);const o=oi([i]),r={name:i.name,guid:this.guid,url:t,point:i.worldPosition.clone(),size:o.getSize(new x),contentMD5:n};this.context.connection.send("droplistener",r)}}deleteDropEvent(){this.context.connection.sendDeleteRemoteState(this.guid)}testIfIsInDropArea(t){if(this.dropArea){const i=this.context.input.convertScreenspaceToRaycastSpace(t.screenposition.clone());if(!this.context.physics.raycast({targets:[this.dropArea],screenPoint:i,recursive:!0,testObject:n=>!this._addedObjects.includes(n)}).length)return F()&&console.log(`Dropped outside of drop area for DropListener "${this.name}".`),!1}return!0}}Ka([m()],Dn.prototype,"useNetworking",2),Ka([m(I)],Dn.prototype,"dropArea",2),Ka([m()],Dn.prototype,"fitIntoVolume",2),Ka([m(x)],Dn.prototype,"fitVolumeSize",2),Ka([m()],Dn.prototype,"placeAtHitPosition",2),Ka([m(Se)],Dn.prototype,"onDropped",2);function yR(s){if(!s.startsWith("https://polyhaven.com/"))return s;const t="https://dl.polyhaven.org/file/ph-assets/Models/gltf/4k/",i=new URL(s).pathname.split("/").pop(),n=`${t}${i}/${i}_4k.gltf`;return console.log("Resolved polyhaven asset url",s,"\u2192",n),n}var Du;(s=>{async function t(n,o,r){const l=n.name.toLowerCase();return l.endsWith(".gltf")||l.endsWith(".glb")||l.endsWith(".fbx")||l.endsWith(".obj")||l.endsWith(".usdz")||l.endsWith(".vrm")||n.type==="model/gltf+json"||n.type==="model/gltf-binary"?new Promise((c,h)=>{const d=new FileReader;d.readAsArrayBuffer(n),d.onloadend=async u=>{const p=d.result,g=r.guid,y=new Dt(g),f=await gs().parseSync(o,p,n.name,y);if(f){const v=_r.hashMD5(p);c({model:f,contentMD5:v})}}}):(console.warn("Unsupported file type: "+l,n.type),null)}s.loadFile=t;async function i(n,o){return new Promise(async(r,l)=>{const c=new Dt(o.guid),h=n.toString();ks&&q.DrawWireSphere(o.point,.1,16711680,3);const d=To.addPreview({guid:o.guid,parent:o.parent,position:o?.point,size:o?.size}),u=await gs().loadSync(o.context,h,h,c,p=>{d.onProgress(p.loaded/p.total)}).catch(console.warn);if(u){const p=await fetch(h).then(y=>y.arrayBuffer()),g=_r.hashMD5(p);ks?setTimeout(()=>To.removePreview(o.guid),3e3):To.removePreview(o.guid),r({model:u,contentMD5:g})}else ks?setTimeout(()=>To.removePreview(o.guid),3e3):To.removePreview(o.guid),console.warn("Unsupported file type: "+n.toString())})}s.loadFileFromURL=i})(Du||(Du={}));var vR=Object.defineProperty,bR=Object.getOwnPropertyDescriptor,jf=(s,t,i,n)=>{for(var o=n>1?void 0:n?bR(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&vR(t,i,o),o};const Kw=class extends A{constructor(){super(...arguments),a(this,"parent",null),a(this,"object",null),a(this,"limitCount",60),a(this,"_currentCount",0),a(this,"_startPosition",null),a(this,"_startQuaternion",null),a(this,"_forwardPointerEvents",new Map)}start(){var s,t;if(this._currentCount=0,this._startPosition=null,this._startQuaternion=null,this.object||(this.object=this.gameObject),this.object){if(this.object===this.gameObject){const n=new Dt(this.guid);this.object=O.instantiate(this.object,{idProvider:n,keepWorldPosition:!1});const o=O.getComponent(this.object,Kw);o?.destroy();let r=this.object.getComponentInChildren(ui);r||(r=this.object.addComponent(ui,{dragMode:Af.SnapToSurfaces}),r.guid=n.generateUUID());let l=O.getComponent(r.gameObject,qs);l||(l=r.gameObject.addComponent(qs),l.guid=n.generateUUID())}this.object.visible=!1;const i=this.gameObject.getComponent(ui);i&&(i.enabled=!1),this._startPosition=((s=this.object.position)==null?void 0:s.clone())??new x(0,0,0),this._startQuaternion=((t=this.object.quaternion)==null?void 0:t.clone())??new V(0,0,0,1)}this.gameObject.getComponentInParent(Ei)||this.gameObject.addComponent(Ei)}onEnable(){this.startCoroutine(this.cloneLimitIntervalFn())}onPointerEnter(s){s.used||this.object&&this.context.connection.allowEditing&&s.button===0&&this.context.input.setCursor("pointer")}onPointerExit(s){s.used||this.object&&this.context.connection.allowEditing&&s.button===0&&this.context.input.unsetCursor("pointer")}onPointerDown(s){if(s.used||!this.object||!this.context.connection.allowEditing||s.button!==0)return;const t=this.handleDuplication();if(t){const i=O.getComponent(t,ui);i?(i.onPointerDown(s),this._forwardPointerEvents.set(s.event.space,i)):console.warn("Duplicated object does not have DragControls",t)}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(s){if(s.used)return;const t=this._forwardPointerEvents.get(s.event.space);t&&(t.onPointerUp(s),this._forwardPointerEvents.delete(s.event.space))}*cloneLimitIntervalFn(){for(;this.activeAndEnabled&&!this.destroyed;)this._currentCount>0?this._currentCount-=1:this._currentCount<0&&(this._currentCount=0),yield $g(1)}handleDuplication(){var s;if(!this.object||this.limitCount>0&&this._currentCount>=this.limitCount||this.object===this.gameObject)return null;if(O.isDestroyed(this.object))return this.object=null,null;this.object.visible=!0,this._startPosition&&this.object.position.copy(this._startPosition),this._startQuaternion&&this.object.quaternion.copy(this._startQuaternion);const t=new Ds;this.parent||(this.parent=this.gameObject.parent),this.parent&&(t.parent=this.parent.guid??((s=this.parent.userData)==null?void 0:s.guid),t.keepWorldPosition=!0),t.position=this.worldPosition,t.rotation=this.worldQuaternion,t.context=this.context,this._currentCount+=1;const i=O.instantiateSynced(this.object,t);return console.assert(i!==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),i}};let Ja=Kw;jf([m(I)],Ja.prototype,"parent",2),jf([m(I)],Ja.prototype,"object",2),jf([m()],Ja.prototype,"limitCount",2);var Bn=(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[s.Drag=5]="Drag",s[s.Drop=6]="Drop",s[s.Scroll=7]="Scroll",s[s.UpdateSelected=8]="UpdateSelected",s[s.Select=9]="Select",s[s.Deselect=10]="Deselect",s[s.Move=11]="Move",s[s.InitializePotentialDrag=12]="InitializePotentialDrag",s[s.BeginDrag=13]="BeginDrag",s[s.EndDrag=14]="EndDrag",s[s.Submit=15]="Submit",s[s.Cancel=16]="Cancel",s))(Bn||{}),_R=Object.defineProperty,wR=Object.getOwnPropertyDescriptor,Lf=(s,t,i,n)=>{for(var o=n>1?void 0:n?wR(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&_R(t,i,o),o};class Df{constructor(){a(this,"eventID"),a(this,"callback",new Se)}}Lf([m()],Df.prototype,"eventID",2),Lf([m(Se)],Df.prototype,"callback",2);class Bu extends A{constructor(){super(...arguments),a(this,"triggers",[])}invoke(t){var i;if(this.triggers)for(const n of this.triggers)n.eventID===t&&((i=n.callback)==null||i.invoke())}hasTrigger(t){var i;return((i=this.triggers)==null?void 0:i.some(n=>n.eventID===t))??!1}shouldChangeCursor(){return this.hasTrigger(Bn.PointerClick)||this.hasTrigger(Bn.PointerDown)||this.hasTrigger(Bn.PointerUp)}onPointerClick(t){this.invoke(Bn.PointerClick)}onPointerEnter(t){this.shouldChangeCursor()&&this.context.input.setCursor("pointer"),this.invoke(Bn.PointerEnter)}onPointerExit(t){this.shouldChangeCursor()&&this.context.input.unsetCursor("pointer"),this.invoke(Bn.PointerExit)}onPointerDown(t){this.invoke(Bn.PointerDown)}onPointerUp(t){this.invoke(Bn.PointerUp)}}Lf([m(Df)],Bu.prototype,"triggers",2);class Jw{constructor(t){a(this,"writer"),this.writer=t}writeNode(t){}}class xR extends Jw{beforeWriteNode(t,i){q.isGizmo(t)&&(i.keep=!1)}}class ex extends Jw{beforeWriteTexture(t,i){t.isRenderTargetTexture&&(i.newTexture=Gg(new xe(1,1,1,0)))}}function Bf(s){const t=Au.DontExport;return!(s.hideFlags&t)}const Ff=C("debugexr");class SR{constructor(t){a(this,"parser"),this.parser=t,Ff&&console.log(t)}get name(){return"EXT_texture_exr"}loadTexture(t){const i=this.name,n=this.parser,o=n.json.textures[t];if(Ff&&console.log("EXT_texture_exr.loadTexture",t,o),!o.extensions||!o.extensions[i])return null;const r=o.extensions[i],l=new ud(n.options.manager);return Ff&&console.log("EXT_texture_exr.loadTexture",r),n.loadTextureImage(t,r.source,l)}}typeof window<"u"&&window.addEventListener("unhandledrejection",s=>{});const Fn=vt,Fu="$___Export_Components",CR="NEEDLE_components";var tx;class OR{constructor(){a(this,tx)}}tx=dr;class PR{constructor(t,i,n){a(this,"node"),a(this,"nodeIndex"),a(this,"nodeDef"),this.node=t,this.nodeIndex=i,this.nodeDef=n}}class ix{constructor(){a(this,"parser"),a(this,"nodeToObjectMap",{}),a(this,"gltf",null),a(this,"exportContext"),a(this,"objectToNodeMap",{}),a(this,"context"),a(this,"writer")}get name(){return CR}registerExport(t){t.register(i=>{if("serializeUserData"in i){const n=i.serializeUserData.bind(i);this.writer=i,i.serializeUserData=(o,r)=>{try{this.serializeUserData(o,r)&&(i.extensionsUsed[this.name]=!0),n(o,r)}finally{this.afterSerializeUserData(o,r)}}}return this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(t,i){var n;const o=(n=t.userData)==null?void 0:n.components;return!o||o.length<=0?!1:(delete t.userData.components,t[Fu]=o,!0)}afterSerializeUserData(t,i){if(t.type==="Scene"&&Fn&&console.log("DONE",JSON.stringify(i)),t[Fu]===void 0)return;const n=t[Fu];delete t[Fu],n!==null&&(t.userData.components=n)}writeNode(t,i){const n=this.writer.json.nodes.length;Fn&&console.log(t.name,n,t.uuid);const o=new PR(t,n,i);this.exportContext[n]=o,this.objectToNodeMap[t.uuid]=n}afterParse(t){var i;Fn&&console.log("AFTER",t);for(const n in this.exportContext){const o=this.exportContext[n],r=o.node,l=o.nodeDef,c=o.nodeIndex,h=(i=r.userData)==null?void 0:i.components;if(!h||h.length<=0)continue;const d=new OR;l.extensions=l.extensions||{},l.extensions[this.name]=d,this.context.object=r,this.context.nodeId=c,this.context.objectToNode=this.objectToNodeMap;const u=[];for(const p of h){this.context.target=p;const g=gs().writeBuiltinComponentData(p,this.context);g!==null&&u.push(g)}u.length>0&&(d[dr]=u,Fn&&console.log("DID WRITE",r,"nodeIndex",c,u))}}beforeRoot(){return Fn&&console.log("BEGIN LOAD"),this.nodeToObjectMap={},null}async afterRoot(t){this.gltf=t;const i=t.parser,n=i?.extensions;if(!n)return;const o=n[this.name];Fn&&console.log("After root",t,this.parser,n);const r=[];if(o===!0){const l=i.json.nodes;if(l){for(let c=0;c<l.length;c++){const h=await i.getDependency("node",c);this.nodeToObjectMap[c]=h}for(let c=0;c<l.length;c++){const h=l[c],d=c,u=h.extensions;if(!u)continue;const p=u[this.name];if(!p)continue;Fn&&console.log("NODE",h);const g=this.nodeToObjectMap[d];if(!g){console.error("Could not find object for node index: "+d,h,i);continue}$d(g),r.push(this.createComponents(g,p))}}}await Promise.all(r);for(const l of i.associations.keys()){const c=i.associations.get(l);if(c?.materials!=null){const h="/materials/"+c.materials;E2(l,h)}}}async createComponents(t,i){if(!i)return;const n=i[dr];if(n){const o=new Array;Fn&&console.log(t.name,n);for(const r in n){const l=n[r];Fn&&console.log("Serialized data",JSON.parse(JSON.stringify(l))),l&&this.parser&&o.push(jg(this.parser,l).catch(c=>console.error(`Error while resolving references (see console for details)
942
- `,c,t,l))),t.userData=t.userData||{},t.userData[dr]=t.userData[dr]||[],t.userData[dr].push(l)}await Promise.all(o).catch(r=>{console.error("Error while loading components",r)})}}}const sx="NEEDLE_gameobject_data";class kR{constructor(t){a(this,"parser"),this.parser=t}get name(){return sx}afterRoot(t){var i;const n=[];for(let o=0;o<((i=this.parser.json.nodes)==null?void 0:i.length);o++){const r=this.parser.json.nodes[o];if(r&&r.extensions){const l=r.extensions[sx];if(l){const c=this.findAndApplyExtensionData(o,l);n.push(c)}}}return Promise.all(n).then(()=>null)}async findAndApplyExtensionData(t,i){const n=await this.parser.getDependency("node",t);n&&this.applyExtensionData(n,i)}applyExtensionData(t,i){i.layers===void 0&&(i.layers=0),t.userData.layer=i.layers,t.layers.disableAll(),t.layers.set(i.layers),t.userData.tag=i.tag??"none",t.hideFlags=0,t.userData.static=i.static??!1,t.visible=i.activeSelf??!0,t.guid=i.guid}}const nx="NEEDLE_lighting_settings",el=C("debugenvlight");class MR{constructor(t,i,n){a(this,"parser"),a(this,"sourceId"),a(this,"context"),this.parser=t,this.sourceId=i,this.context=n}get name(){return nx}afterRoot(t){const i=this.parser.json.extensions;if(i){const n=i[nx];if(n){el&&console.log('Loaded "'+this.name+'", src: "'+this.sourceId+'"',n);let o;if(t.scene.children.length===1){const r=t.scene.children[0];o=O.addComponent(r,zu,{},{callAwake:!1})}else{const r=new I;r.name="LightSettings "+this.sourceId,t.scene.add(r),o=O.addComponent(r,zu,{},{callAwake:!1})}o.sourceId=this.sourceId,o.ambientIntensity=n.ambientIntensity,o.ambientLight=new ae().fromArray(n.ambientLight),Array.isArray(n.ambientTrilight)&&(o.ambientTrilight=n.ambientTrilight.map(r=>new ae().fromArray(r))),o.ambientMode=n.ambientMode,o.environmentReflectionSource=n.environmentReflectionSource}}return null}}ue.registerCallback(ge.ContextCreated,s=>{const t=s.context,i=O.findObjectOfType(zu,t);i!=null&&i.sourceId&&(i.enabled=!0)});class zu extends A{constructor(){super(...arguments),a(this,"ambientMode",za.Skybox),a(this,"ambientLight"),a(this,"ambientTrilight"),a(this,"ambientIntensity",1),a(this,"environmentReflectionSource",au.Skybox),a(this,"_hasReflection",!1),a(this,"_ambientLightObj"),a(this,"_hemisphereLightObj")}awake(){var t;if(this.sourceId){const n=this.environmentReflectionSource===au.Skybox?fo.Skybox:fo.Reflection,o=this.context.lightmaps.tryGet(this.sourceId,n,0);this._hasReflection=o!=null,o&&this.context.sceneLighting.internalRegisterReflection(this.sourceId,o)}this.enabled=!1,this.context.sceneLighting.internalRegisterSceneLightSettings(this),el&&window.addEventListener("keydown",n=>{if(!this.destroyed)switch(n.key){case"l":this.enabled=!this.enabled;break}});const i=(t=this.gameObject.userData)==null?void 0:t.components;if(i){const n=i.indexOf(this);i.splice(n,1),i.push(this)}}onDestroy(){this.context.sceneLighting.internalUnregisterSceneLightSettings(this)}calculateIntensityFactor(t){const i=Math.max(t.r,t.g,t.b);return 2.2*W.lerp(0,1.33,i)}onEnable(){if(el&&console.warn("\u{1F4A1}\u{1F7E1} >>> Enable lighting",this.sourceId,this.enabled,this),this.ambientMode==za.Flat){if(this.ambientLight&&!this._ambientLightObj){const t=this.calculateIntensityFactor(this.ambientLight);this._ambientLightObj=new US(this.ambientLight,this.ambientIntensity*t),el&&console.log("Created ambient light",this.sourceId,this._ambientLightObj,this.ambientIntensity,t)}this._ambientLightObj&&this.gameObject.add(this._ambientLightObj)}else if(this.ambientMode===za.Trilight){if(this.ambientTrilight){const t=this.ambientTrilight[0],i=this.ambientTrilight[this.ambientTrilight.length-1],n=this.calculateIntensityFactor(i);this._hemisphereLightObj=new NS(i,t,this.ambientIntensity*n),this.gameObject.add(this._hemisphereLightObj),el&&console.log("Created hemisphere ambient light",this.sourceId,this._hemisphereLightObj,this.ambientIntensity,n)}}else this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent();this.sourceId&&this.context.sceneLighting.internalEnableReflection(this.sourceId)}onDisable(){el&&console.warn("\u{1F4A1}\u26AB <<< Disable lighting:",this.sourceId,this),this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent(),this.sourceId&&this.context.sceneLighting.internalDisableReflection(this.sourceId)}}const zf=C("debugstencil");function RR(s,t){return(s&1<<t.layer)!=0}const TR=Symbol("stencils"),tl=class{constructor(s,t){a(this,"parser"),a(this,"source"),this.parser=s,this.source=t}get name(){return"NEEDLE_render_objects"}static applyStencil(s){if(!s)return;const t=s.sourceId;if(zf&&console.log(t,tl.stencils),!t)return;const i=tl.stencils[t];if(i)for(let n=i.length-1;n>=0;n--){const o=i[n];if(RR(o.layer,s)){zf&&console.log(o),setTimeout(()=>{Gt()&&Xd(s.gameObject)&&(we("Stencil not supported on instanced objects"),console.warn("Stencil not supported on instanced objects",s))},500);for(let r=0;r<s.sharedMaterials.length;r++){let l=s.sharedMaterials[r];l&&(l=l.clone(),l[TR]=!0,l.stencilWrite=!0,l.stencilWriteMask=255,l.stencilFuncMask=255,l.stencilRef=o.value,l.stencilFunc=o.compareFunc,l.stencilZPass=o.passOp,l.stencilFail=o.failOp,l.stencilZFail=o.zFailOp,s.sharedMaterials[r]=l)}s.gameObject.renderOrder=o.event*1e3+o.index*50;break}}}afterRoot(s){const t=this.parser.json.extensions;if(t){const i=t[AR];if(i){zf&&console.log(i);const n=i.stencil;if(n&&Array.isArray(n))for(const o of n){const r={...o};r.compareFunc=ER(r.compareFunc),r.passOp=Nf(r.passOp),r.failOp=Nf(r.failOp),r.zFailOp=Nf(r.zFailOp),tl.stencils[this.source]||(tl.stencils[this.source]=[]),tl.stencils[this.source].push(r)}}}return null}};let Uf=tl;a(Uf,"stencils",{});function Nf(s){switch(s){case 0:return QS;case 1:return XS;case 2:return GS;case 3:return qS;case 4:return $S;case 6:return HS;case 7:return VS;case 5:return WS}return 0}function ER(s){switch(s){case 1:return Yy;case 2:return iC;case 3:return tC;case 4:return eC;case 5:return JS;case 6:return KS;case 7:return ZS;case 8:return YS}return Yy}const AR="NEEDLE_render_objects";var ox=(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))(ox||{});const Js=C("debugcustomshader"),il="NEEDLE_techniques_webgl";class IR{constructor(){a(this,"objectToWorldMatrix",new ne),a(this,"worldToObjectMatrix",new ne),a(this,"objectToWorld",new Array),a(this,"worldToObject",new Array)}updateFrom(t){this.objectToWorldMatrix.copy(t.matrixWorld),ru(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(t.matrixWorld).invert(),ru(this.worldToObjectMatrix,this.worldToObject)}}const We=class extends Zy{constructor(s,...t){super(...t),a(this,"identifier"),a(this,"onBeforeRenderSceneCallback",this.onBeforeRenderScene.bind(this)),a(this,"_sphericalHarmonicsName","unity_SpecCube0"),a(this,"_objToWorldName","hlslcc_mtx4x4unity_ObjectToWorld"),a(this,"_worldToObjectName","hlslcc_mtx4x4unity_WorldToObject"),a(this,"_viewProjectionName","hlslcc_mtx4x4unity_MatrixVP"),a(this,"_viewMatrixName","hlslcc_mtx4x4unity_MatrixV"),a(this,"_rendererData",new IR),this.identifier=s,Js&&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)&&ee.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}clone(){const s=super.clone();return rx(s),s}dispose(){super.dispose();const s=ee.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);s>=0&&ee.Current.pre_render_callbacks.splice(s,1)}get depthTextureUniform(){if(this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&ee.Current.setRequireColor(!0),this.depthTextureUniform&&ee.Current.setRequireDepth(!0)}onBeforeRender(s,t,i,n,o,r){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,o)}onUpdateUniforms(s,t){const i=ee.Current;if(s&&(We.viewProjection&&this.uniforms[this._viewProjectionName]&&(We.viewProjection.copy(s.projectionMatrix).multiply(s.matrixWorldInverse),ru(We.viewProjection,We._viewProjectionValues)),We.viewMatrix&&this.uniforms[this._viewMatrixName]&&(We.viewMatrix.copy(s.matrixWorldInverse),ru(We.viewMatrix,We._viewMatrixValues)),this.uniforms[We._worldSpaceCameraPosName]&&We._worldSpaceCameraPos.setFromMatrixPosition(s.matrixWorld)),this.uniforms._TimeParameters&&(this.uniforms._TimeParameters.value=i.sceneLighting.timeVec4),this.uniforms._Time){const l=this.uniforms._Time.value;l.x=i.sceneLighting.timeVec4.x/20,l.y=i.sceneLighting.timeVec4.x,l.z=i.sceneLighting.timeVec4.x*2,l.w=i.sceneLighting.timeVec4.x*3}if(this.uniforms._SinTime){const l=this.uniforms._SinTime.value;l.x=Math.sin(i.sceneLighting.timeVec4.x/8),l.y=Math.sin(i.sceneLighting.timeVec4.x/4),l.z=Math.sin(i.sceneLighting.timeVec4.x/2),l.w=Math.sin(i.sceneLighting.timeVec4.x)}if(this.uniforms._CosTime){const l=this.uniforms._CosTime.value;l.x=Math.cos(i.sceneLighting.timeVec4.x/8),l.y=Math.cos(i.sceneLighting.timeVec4.x/4),l.z=Math.cos(i.sceneLighting.timeVec4.x/2),l.w=Math.cos(i.sceneLighting.timeVec4.x)}if(this.uniforms.unity_DeltaTime){const l=this.uniforms.unity_DeltaTime.value;l.x=i.time.deltaTime,l.y=1/i.time.deltaTime,l.z=i.time.smoothedDeltaTime,l.w=1/i.time.smoothedDeltaTime}const n=i.mainLight;if(n){const l=te(n.gameObject,We._mainLightPosition);this.uniforms._MainLightPosition={value:l.normalize()},We._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:We._mainLightColor};const c=n.intensity;We._lightData.z=c,this.uniforms.unity_LightData={value:We._lightData}}if(s&&(We.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=We._viewProjectionValues),We.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=We._viewMatrixValues),this.uniforms[We._worldSpaceCameraPosName]&&(this.uniforms[We._worldSpaceCameraPosName]={value:We._worldSpaceCameraPos}),i.mainCameraComponent)){if(this.uniforms._ProjectionParams){const l=this.uniforms._ProjectionParams.value;l.x=1,l.y=i.mainCameraComponent.nearClipPlane,l.z=i.mainCameraComponent.farClipPlane,l.w=1/l.z,this.uniforms._ProjectionParams.value=l}if(this.uniforms._ZBufferParams){const l=this.uniforms._ZBufferParams.value,c=i.mainCameraComponent;l.x=1-c.farClipPlane/c.nearClipPlane,l.y=c.farClipPlane/c.nearClipPlane,l.z=l.x/c.farClipPlane,l.w=l.y/c.farClipPlane,this.uniforms._ZBufferParams.value=l}if(this.uniforms._ScreenParams){const l=this.uniforms._ScreenParams.value;l.x=i.domWidth,l.y=i.domHeight,l.z=1+1/l.x,l.w=1+1/l.y,this.uniforms._ScreenParams.value=l}if(this.uniforms._ScaledScreenParams){const l=this.uniforms._ScaledScreenParams.value;l.x=i.domWidth,l.y=i.domHeight,l.z=1+1/l.x,l.w=1+1/l.y,this.uniforms._ScaledScreenParams.value=l}}const o=this.depthTextureUniform;o&&(o.value=i.depthTexture);const r=this.opaqueTextureUniform;if(r&&(r.value=i.opaqueColorTexture),t){const l=this._rendererData;l.updateFrom(t),this.uniforms[this._worldToObjectName].value=l.worldToObject,this.uniforms[this._objToWorldName].value=l.objectToWorld}this.uniformsNeedUpdate=!0}};let Ms=We;a(Ms,"viewProjection",new ne),a(Ms,"_viewProjectionValues",[]),a(Ms,"viewMatrix",new ne),a(Ms,"_viewMatrixValues",[]),a(Ms,"_worldSpaceCameraPosName","_WorldSpaceCameraPos"),a(Ms,"_worldSpaceCameraPos",new x),a(Ms,"_mainLightColor",new fe),a(Ms,"_mainLightPosition",new x),a(Ms,"_lightData",new fe);class jR{constructor(t,i){a(this,"parser"),a(this,"identifier"),this.parser=t,this.identifier=i}get name(){return il}loadMaterial(t){const i=this.parser.json.materials[t];if(!i)return Js&&console.log(t,this.parser.json.materials),null;if(!i.extensions||!i.extensions[il])return Js&&console.log(`Material ${t} does not use NEEDLE_techniques_webgl`),null;Js&&console.log(`Material ${t} uses NEEDLE_techniques_webgl`,i);const n=i.extensions[il].technique;if(n<0)return console.debug(`Material ${t} does not have a valid technique index`),null;const o=this.parser.json.extensions[il];if(!o)return Js?console.error("Missing shader data",this.parser.json.extensions):console.debug("Missing custom shader data in parser.json.extensions"),null;Js&&console.log(o);const r=o.techniques[n];return r?new Promise(async(l,c)=>{var h,d,u;const p=await ak(o,r.program),g=p?.fragmentShader,y=p?.vertexShader;if(!g||!y)return c();Js&&console.log("loadMaterial",i,p);const f={},v=r.uniforms;(y.includes("_Time")||g.includes("_Time"))&&(f._Time={value:new fe(0,0,0,0)}),(y.includes("_SinTime")||g.includes("_SinTime"))&&(f._SinTime={value:new fe(0,0,0,0)}),(y.includes("_CosTime")||g.includes("_CosTime"))&&(f._CosTime={value:new fe(0,0,0,0)}),(y.includes("unity_DeltaTime")||g.includes("unity_DeltaTime"))&&(f.unity_DeltaTime={value:new fe(0,0,0,0)});for(const _ in v){const S=_;switch(S){case"_TimeParameters":const R=new fe;f[S]={value:R};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":f[S]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":f[S]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":f[S]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":f[S]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":f[S]={value:null};break}}let b=!1;if(i.extensions&&i.extensions[il]){const _=i.extensions[il];if(_.technique===n){Js&&console.log(i.name,"Material Properties",_);for(const S in _.values){const R=_.values[S];if(typeof R=="string"){if(R.startsWith("/textures/")){const M=R.substring(10),T=Number.parseInt(M);if(T>=0){const j=await this.parser.getDependency("texture",T);j instanceof Le&&(j.colorSpace=or,j.needsUpdate=!0),f[S]={value:j};continue}}switch(S){case"alphaMode":R==="BLEND"&&(b=!0);continue}}if(Array.isArray(R)&&R.length===4){f[S]={value:new fe(R[0],R[1],R[2],R[3])};continue}f[S]={value:R}}}}const w=new Ms(this.identifier,{name:i.name??"",uniforms:f,vertexShader:y,fragmentShader:g,lights:!1});switch(w.glslVersion=sC,w.vertexShader=w.vertexShader.replace("#version 300 es",""),w.fragmentShader=w.fragmentShader.replace("#version 300 es",""),(h=f._Cull)==null?void 0:h.value){case 0:w.side=Si;break;case 1:w.side=dm;break;case 2:w.side=ao;break;default:w.side=ao;break}switch((d=f._ZTest)==null?void 0:d.value){case 3:w.depthTest=!0,w.depthFunc=hC;break;case 6:w.depthTest=!0,w.depthFunc=cC;break;case 2:w.depthTest=!0,w.depthFunc=lC;break;case 4:w.depthTest=!0,w.depthFunc=aC;break;case 5:w.depthTest=!0,w.depthFunc=rC;break;case 7:w.depthTest=!0,w.depthFunc=oC;break;case 8:w.depthTest=!1,w.depthFunc=nC;break}w.transparent=b,b&&(w.depthWrite=!1),ok(f),w.onUpdateUniforms();for(const _ in v){const S=_,R=v[_].type;if(((u=f[S])==null?void 0:u.value)===void 0)switch(R){case ox.SAMPLER_2D:f[S]={value:sk},console.warn("Missing/unassigned texture, fallback to white: "+S);break;default:S==="unity_OrthoParams"||console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+S,v[_]);break}}Js&&console.log(w.uuid,f),rx(w),l(w)}):null}}function rx(s){if(s.uniforms){Js&&console.log("Uniforms:",s.uniforms);for(const i in s.uniforms)switch(t(i,i),i){case"_Color":t("color",i);break}}function t(i,n){Object.getOwnPropertyDescriptor(s,i)||Object.defineProperty(s,i,{get:()=>s.uniforms[n].value,set:o=>{s.uniforms[n].value=o,s.needsUpdate=!0}})}}const LR=C("debugextensions");let Uu;const DR=import("./three-examples.light.min.js").then(s=>s.r).then(async s=>(Uu=s.GLTFAnimationPointerExtension,Uu)).catch(s=>{console.warn("Failed to import GLTFLoaderAnimationPointer. Please use @needle-tools/three for full KHR_animation support",s)}),Ir=new Array;function BR(s){Ir.includes(s)||Ir.push(s)}function FR(s){const t=Ir.indexOf(s);t>=0&&Ir.splice(t,1)}function Nu(s){const t=new ix;return s.register(i=>(t.parser=i,t)),t}class zR{resolvePath(t){return t.includes("/extensions/builtin_components/")?t.replace("/extensions/builtin_components/","/userData/components/"):t.includes("extensions/builtin_components/")?t.replace("extensions/builtin_components/","/userData/components/"):t}}async function Wu(s,t,i){const n=i.indexOf("?");n>=0&&(i=i.substring(0,n)),s.register(o=>new kR(o)),s.register(o=>new I2(o)),s.register(o=>new J2(o,t.lightmaps,i)),s.register(o=>new MR(o,i,t)),s.register(o=>new jR(o,i)),s.register(o=>new Uf(o,i)),s.register(o=>new it(o,i)),s.register(o=>new SR(o)),Xb()&&s.register(o=>new bg(o)),await DR.catch(o=>{}),s.register(o=>{if(Uu){const r=new Uu(o);return r.setAnimationPointerResolver.bind(r)(new zR),r}else return(LR||F())&&console.error("Missing KHR_animation_pointer extension..."),{name:"KHR_animation_pointer_NOT_AVAILABLE"}});for(const o of Ir)o.onImport&&o.onImport(s,i,t)}function Wf(s,t){for(const i of Ir)i.onExport&&i.onExport(s,t)}function Vf(s,t,i){for(const n of Ir)n.onLoaded&&n.onLoaded(s,t,i)}class ax{constructor(t){this.writer=t,this.name="EXT_mesh_gpu_instancing"}writeNode(t,i){if(t.constructor.name!=="InstancedMesh")return;const n=this.writer,o=n.extensionsUsed,r={};i.extensions=i.extensions||{},i.extensions[this.name]=r;let l=new ne;const c=new Array,h=new Array,d=new Array;for(let y=0;y<t.count;y++){t.getMatrixAt(y,l);let f=new x,v=new V,b=new x;l.decompose(f,v,b),c.push(f.x,f.y,f.z),h.push(v.x,v.y,v.z,v.w),d.push(b.x,b.y,b.z)}const u=new Float32Array(c),p=new Float32Array(h),g=new Float32Array(d);r.attributes={TRANSLATION:n.processAccessor(new ft(u,3)),ROTATION:n.processAccessor(new ft(p,4)),SCALE:n.processAccessor(new ft(g,3))},o[this.name]=!0}}var UR=Object.defineProperty,NR=Object.getOwnPropertyDescriptor,lx=(s,t,i,n)=>{for(var o=n>1?void 0:n?NR(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&UR(t,i,o),o};const Vu=C("debugreflectionprobe"),cx=C("noreflectionprobe"),WR=Symbol("reflectionProbeKey"),VR=Symbol("original material");var Hu;const zn=(Hu=class extends A{constructor(){var s;super(),a(this,"_texture"),a(this,"center"),a(this,"size"),a(this,"_boxHelper"),zn._probes.has(this.context)||zn._probes.set(this.context,[]),(s=zn._probes.get(this.context))==null||s.push(this)}static get(s,t,i,n){if(!s||s.isObject3D!==!0||cx)return null;const o=zn._probes.get(t);if(o){for(const r of o)if(r.__didAwake||r.__internalAwake(),r.enabled&&n&&r.gameObject===n)return r}return Vu&&console.debug("Did not find reflection probe",s.name,i,s),null}set texture(s){if(s&&!(s instanceof Le)){console.error("ReflectionProbe.texture must be a Texture",s);return}this._texture=s,s&&(s.mapping=yn,s.colorSpace=ms,s.needsUpdate=!0)}get texture(){return this._texture}isInBox(s){var t;return(t=this._boxHelper)==null?void 0:t.isInBox(s)}awake(){this._boxHelper=this.gameObject.addComponent(Ji),this._boxHelper.updateBox(!0),Vu&&this._boxHelper.showHelper(5592320,!0),this.texture&&(this.texture.mapping=yn,this.texture.colorSpace=ms,this.texture.needsUpdate=!0)}onDestroy(){const s=zn._probes.get(this.context);if(s){const t=s.indexOf(this);t>=0&&s.splice(t,1)}}onSet(s){var t;if(cx||!this.enabled||((t=s.sharedMaterials)==null?void 0:t.length)<=0||!this.texture)return;let i=zn._rendererMaterialsCache.get(s);i||(i=[],zn._rendererMaterialsCache.set(s,i));for(let n=0;n<s.sharedMaterials.length;n++){const o=s.sharedMaterials[n];if(!o||o.envMap===void 0||o instanceof Re)continue;let r=i[n];const l=o===r?.copy,c=!r||r.material.uuid!==o.uuid||r.copy.version!==o.version;if(!l&&c){if(Vu){let u="";r?r.material!==o?u="reference changed; cached instance?: "+l:r.copy.version!==o.version&&(u="version changed"):u="not cached",console.warn("Cloning material",o.name,o.version,"Reason:",u,`
946
+ `,c,t,l))),t.userData=t.userData||{},t.userData[dr]=t.userData[dr]||[],t.userData[dr].push(l)}await Promise.all(o).catch(r=>{console.error("Error while loading components",r)})}}}const sx="NEEDLE_gameobject_data";class kR{constructor(t){a(this,"parser"),this.parser=t}get name(){return sx}afterRoot(t){var i;const n=[];for(let o=0;o<((i=this.parser.json.nodes)==null?void 0:i.length);o++){const r=this.parser.json.nodes[o];if(r&&r.extensions){const l=r.extensions[sx];if(l){const c=this.findAndApplyExtensionData(o,l);n.push(c)}}}return Promise.all(n).then(()=>null)}async findAndApplyExtensionData(t,i){const n=await this.parser.getDependency("node",t);n&&this.applyExtensionData(n,i)}applyExtensionData(t,i){i.layers===void 0&&(i.layers=0),t.userData.layer=i.layers,t.layers.disableAll(),t.layers.set(i.layers),t.userData.tag=i.tag??"none",t.hideFlags=0,t.userData.static=i.static??!1,t.visible=i.activeSelf??!0,t.guid=i.guid}}const nx="NEEDLE_lighting_settings",el=C("debugenvlight");class MR{constructor(t,i,n){a(this,"parser"),a(this,"sourceId"),a(this,"context"),this.parser=t,this.sourceId=i,this.context=n}get name(){return nx}afterRoot(t){const i=this.parser.json.extensions;if(i){const n=i[nx];if(n){el&&console.log('Loaded "'+this.name+'", src: "'+this.sourceId+'"',n);let o;if(t.scene.children.length===1){const r=t.scene.children[0];o=O.addComponent(r,zu,{},{callAwake:!1})}else{const r=new I;r.name="LightSettings "+this.sourceId,t.scene.add(r),o=O.addComponent(r,zu,{},{callAwake:!1})}o.sourceId=this.sourceId,o.ambientIntensity=n.ambientIntensity,o.ambientLight=new ae().fromArray(n.ambientLight),Array.isArray(n.ambientTrilight)&&(o.ambientTrilight=n.ambientTrilight.map(r=>new ae().fromArray(r))),o.ambientMode=n.ambientMode,o.environmentReflectionSource=n.environmentReflectionSource}}return null}}ue.registerCallback(ge.ContextCreated,s=>{const t=s.context,i=O.findObjectOfType(zu,t);i!=null&&i.sourceId&&(i.enabled=!0)});class zu extends A{constructor(){super(...arguments),a(this,"ambientMode",za.Skybox),a(this,"ambientLight"),a(this,"ambientTrilight"),a(this,"ambientIntensity",1),a(this,"environmentReflectionSource",au.Skybox),a(this,"_hasReflection",!1),a(this,"_ambientLightObj"),a(this,"_hemisphereLightObj")}awake(){var t;if(this.sourceId){const n=this.environmentReflectionSource===au.Skybox?fo.Skybox:fo.Reflection,o=this.context.lightmaps.tryGet(this.sourceId,n,0);this._hasReflection=o!=null,o&&this.context.sceneLighting.internalRegisterReflection(this.sourceId,o)}this.enabled=!1,this.context.sceneLighting.internalRegisterSceneLightSettings(this),el&&window.addEventListener("keydown",n=>{if(!this.destroyed)switch(n.key){case"l":this.enabled=!this.enabled;break}});const i=(t=this.gameObject.userData)==null?void 0:t.components;if(i){const n=i.indexOf(this);i.splice(n,1),i.push(this)}}onDestroy(){this.context.sceneLighting.internalUnregisterSceneLightSettings(this)}calculateIntensityFactor(t){const i=Math.max(t.r,t.g,t.b);return 2.2*W.lerp(0,1.33,i)}onEnable(){if(el&&console.warn("\u{1F4A1}\u{1F7E1} >>> Enable lighting",this.sourceId,this.enabled,this),this.ambientMode==za.Flat){if(this.ambientLight&&!this._ambientLightObj){const t=this.calculateIntensityFactor(this.ambientLight);this._ambientLightObj=new US(this.ambientLight,this.ambientIntensity*t),el&&console.log("Created ambient light",this.sourceId,this._ambientLightObj,this.ambientIntensity,t)}this._ambientLightObj&&this.gameObject.add(this._ambientLightObj)}else if(this.ambientMode===za.Trilight){if(this.ambientTrilight){const t=this.ambientTrilight[0],i=this.ambientTrilight[this.ambientTrilight.length-1],n=this.calculateIntensityFactor(i);this._hemisphereLightObj=new NS(i,t,this.ambientIntensity*n),this.gameObject.add(this._hemisphereLightObj),el&&console.log("Created hemisphere ambient light",this.sourceId,this._hemisphereLightObj,this.ambientIntensity,n)}}else this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent();this.sourceId&&this.context.sceneLighting.internalEnableReflection(this.sourceId)}onDisable(){el&&console.warn("\u{1F4A1}\u26AB <<< Disable lighting:",this.sourceId,this),this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent(),this.sourceId&&this.context.sceneLighting.internalDisableReflection(this.sourceId)}}const zf=C("debugstencil");function RR(s,t){return(s&1<<t.layer)!=0}const TR=Symbol("stencils"),tl=class{constructor(s,t){a(this,"parser"),a(this,"source"),this.parser=s,this.source=t}get name(){return"NEEDLE_render_objects"}static applyStencil(s){if(!s)return;const t=s.sourceId;if(zf&&console.log(t,tl.stencils),!t)return;const i=tl.stencils[t];if(i)for(let n=i.length-1;n>=0;n--){const o=i[n];if(RR(o.layer,s)){zf&&console.log(o),setTimeout(()=>{Gt()&&Xd(s.gameObject)&&(we("Stencil not supported on instanced objects"),console.warn("Stencil not supported on instanced objects",s))},500);for(let r=0;r<s.sharedMaterials.length;r++){let l=s.sharedMaterials[r];l&&(l=l.clone(),l[TR]=!0,l.stencilWrite=!0,l.stencilWriteMask=255,l.stencilFuncMask=255,l.stencilRef=o.value,l.stencilFunc=o.compareFunc,l.stencilZPass=o.passOp,l.stencilFail=o.failOp,l.stencilZFail=o.zFailOp,s.sharedMaterials[r]=l)}s.gameObject.renderOrder=o.event*1e3+o.index*50;break}}}afterRoot(s){const t=this.parser.json.extensions;if(t){const i=t[AR];if(i){zf&&console.log(i);const n=i.stencil;if(n&&Array.isArray(n))for(const o of n){const r={...o};r.compareFunc=ER(r.compareFunc),r.passOp=Nf(r.passOp),r.failOp=Nf(r.failOp),r.zFailOp=Nf(r.zFailOp),tl.stencils[this.source]||(tl.stencils[this.source]=[]),tl.stencils[this.source].push(r)}}}return null}};let Uf=tl;a(Uf,"stencils",{});function Nf(s){switch(s){case 0:return QS;case 1:return XS;case 2:return GS;case 3:return qS;case 4:return $S;case 6:return HS;case 7:return VS;case 5:return WS}return 0}function ER(s){switch(s){case 1:return Yy;case 2:return iC;case 3:return tC;case 4:return eC;case 5:return JS;case 6:return KS;case 7:return ZS;case 8:return YS}return Yy}const AR="NEEDLE_render_objects";var ox=(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))(ox||{});const Js=C("debugcustomshader"),il="NEEDLE_techniques_webgl";class IR{constructor(){a(this,"objectToWorldMatrix",new ne),a(this,"worldToObjectMatrix",new ne),a(this,"objectToWorld",new Array),a(this,"worldToObject",new Array)}updateFrom(t){this.objectToWorldMatrix.copy(t.matrixWorld),ru(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(t.matrixWorld).invert(),ru(this.worldToObjectMatrix,this.worldToObject)}}const We=class extends Zy{constructor(s,...t){super(...t),a(this,"identifier"),a(this,"onBeforeRenderSceneCallback",this.onBeforeRenderScene.bind(this)),a(this,"_sphericalHarmonicsName","unity_SpecCube0"),a(this,"_objToWorldName","hlslcc_mtx4x4unity_ObjectToWorld"),a(this,"_worldToObjectName","hlslcc_mtx4x4unity_WorldToObject"),a(this,"_viewProjectionName","hlslcc_mtx4x4unity_MatrixVP"),a(this,"_viewMatrixName","hlslcc_mtx4x4unity_MatrixV"),a(this,"_rendererData",new IR),this.identifier=s,Js&&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)&&ee.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}clone(){const s=super.clone();return rx(s),s}dispose(){super.dispose();const s=ee.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);s>=0&&ee.Current.pre_render_callbacks.splice(s,1)}get depthTextureUniform(){if(this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&ee.Current.setRequireColor(!0),this.depthTextureUniform&&ee.Current.setRequireDepth(!0)}onBeforeRender(s,t,i,n,o,r){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,o)}onUpdateUniforms(s,t){const i=ee.Current;if(s&&(We.viewProjection&&this.uniforms[this._viewProjectionName]&&(We.viewProjection.copy(s.projectionMatrix).multiply(s.matrixWorldInverse),ru(We.viewProjection,We._viewProjectionValues)),We.viewMatrix&&this.uniforms[this._viewMatrixName]&&(We.viewMatrix.copy(s.matrixWorldInverse),ru(We.viewMatrix,We._viewMatrixValues)),this.uniforms[We._worldSpaceCameraPosName]&&We._worldSpaceCameraPos.setFromMatrixPosition(s.matrixWorld)),this.uniforms._TimeParameters&&(this.uniforms._TimeParameters.value=i.sceneLighting.timeVec4),this.uniforms._Time){const l=this.uniforms._Time.value;l.x=i.sceneLighting.timeVec4.x/20,l.y=i.sceneLighting.timeVec4.x,l.z=i.sceneLighting.timeVec4.x*2,l.w=i.sceneLighting.timeVec4.x*3}if(this.uniforms._SinTime){const l=this.uniforms._SinTime.value;l.x=Math.sin(i.sceneLighting.timeVec4.x/8),l.y=Math.sin(i.sceneLighting.timeVec4.x/4),l.z=Math.sin(i.sceneLighting.timeVec4.x/2),l.w=Math.sin(i.sceneLighting.timeVec4.x)}if(this.uniforms._CosTime){const l=this.uniforms._CosTime.value;l.x=Math.cos(i.sceneLighting.timeVec4.x/8),l.y=Math.cos(i.sceneLighting.timeVec4.x/4),l.z=Math.cos(i.sceneLighting.timeVec4.x/2),l.w=Math.cos(i.sceneLighting.timeVec4.x)}if(this.uniforms.unity_DeltaTime){const l=this.uniforms.unity_DeltaTime.value;l.x=i.time.deltaTime,l.y=1/i.time.deltaTime,l.z=i.time.smoothedDeltaTime,l.w=1/i.time.smoothedDeltaTime}const n=i.mainLight;if(n){const l=te(n.gameObject,We._mainLightPosition);this.uniforms._MainLightPosition={value:l.normalize()},We._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:We._mainLightColor};const c=n.intensity;We._lightData.z=c,this.uniforms.unity_LightData={value:We._lightData}}if(s&&(We.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=We._viewProjectionValues),We.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=We._viewMatrixValues),this.uniforms[We._worldSpaceCameraPosName]&&(this.uniforms[We._worldSpaceCameraPosName]={value:We._worldSpaceCameraPos}),i.mainCameraComponent)){if(this.uniforms._ProjectionParams){const l=this.uniforms._ProjectionParams.value;l.x=1,l.y=i.mainCameraComponent.nearClipPlane,l.z=i.mainCameraComponent.farClipPlane,l.w=1/l.z,this.uniforms._ProjectionParams.value=l}if(this.uniforms._ZBufferParams){const l=this.uniforms._ZBufferParams.value,c=i.mainCameraComponent;l.x=1-c.farClipPlane/c.nearClipPlane,l.y=c.farClipPlane/c.nearClipPlane,l.z=l.x/c.farClipPlane,l.w=l.y/c.farClipPlane,this.uniforms._ZBufferParams.value=l}if(this.uniforms._ScreenParams){const l=this.uniforms._ScreenParams.value;l.x=i.domWidth,l.y=i.domHeight,l.z=1+1/l.x,l.w=1+1/l.y,this.uniforms._ScreenParams.value=l}if(this.uniforms._ScaledScreenParams){const l=this.uniforms._ScaledScreenParams.value;l.x=i.domWidth,l.y=i.domHeight,l.z=1+1/l.x,l.w=1+1/l.y,this.uniforms._ScaledScreenParams.value=l}}const o=this.depthTextureUniform;o&&(o.value=i.depthTexture);const r=this.opaqueTextureUniform;if(r&&(r.value=i.opaqueColorTexture),t){const l=this._rendererData;l.updateFrom(t),this.uniforms[this._worldToObjectName].value=l.worldToObject,this.uniforms[this._objToWorldName].value=l.objectToWorld}this.uniformsNeedUpdate=!0}};let Ms=We;a(Ms,"viewProjection",new ne),a(Ms,"_viewProjectionValues",[]),a(Ms,"viewMatrix",new ne),a(Ms,"_viewMatrixValues",[]),a(Ms,"_worldSpaceCameraPosName","_WorldSpaceCameraPos"),a(Ms,"_worldSpaceCameraPos",new x),a(Ms,"_mainLightColor",new fe),a(Ms,"_mainLightPosition",new x),a(Ms,"_lightData",new fe);class jR{constructor(t,i){a(this,"parser"),a(this,"identifier"),this.parser=t,this.identifier=i}get name(){return il}loadMaterial(t){const i=this.parser.json.materials[t];if(!i)return Js&&console.log(t,this.parser.json.materials),null;if(!i.extensions||!i.extensions[il])return Js&&console.log(`Material ${t} does not use NEEDLE_techniques_webgl`),null;Js&&console.log(`Material ${t} uses NEEDLE_techniques_webgl`,i);const n=i.extensions[il].technique;if(n<0)return console.debug(`Material ${t} does not have a valid technique index`),null;const o=this.parser.json.extensions[il];if(!o)return Js?console.error("Missing shader data",this.parser.json.extensions):console.debug("Missing custom shader data in parser.json.extensions"),null;Js&&console.log(o);const r=o.techniques[n];return r?new Promise(async(l,c)=>{var h,d,u;const p=await ak(o,r.program),g=p?.fragmentShader,y=p?.vertexShader;if(!g||!y)return c();Js&&console.log("loadMaterial",i,p);const f={},v=r.uniforms;(y.includes("_Time")||g.includes("_Time"))&&(f._Time={value:new fe(0,0,0,0)}),(y.includes("_SinTime")||g.includes("_SinTime"))&&(f._SinTime={value:new fe(0,0,0,0)}),(y.includes("_CosTime")||g.includes("_CosTime"))&&(f._CosTime={value:new fe(0,0,0,0)}),(y.includes("unity_DeltaTime")||g.includes("unity_DeltaTime"))&&(f.unity_DeltaTime={value:new fe(0,0,0,0)});for(const _ in v){const S=_;switch(S){case"_TimeParameters":const R=new fe;f[S]={value:R};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":f[S]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":f[S]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":f[S]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":f[S]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":f[S]={value:null};break}}let b=!1;if(i.extensions&&i.extensions[il]){const _=i.extensions[il];if(_.technique===n){Js&&console.log(i.name,"Material Properties",_);for(const S in _.values){const R=_.values[S];if(typeof R=="string"){if(R.startsWith("/textures/")){const M=R.substring(10),T=Number.parseInt(M);if(T>=0){const L=await this.parser.getDependency("texture",T);L instanceof Le&&(L.colorSpace=or,L.needsUpdate=!0),f[S]={value:L};continue}}switch(S){case"alphaMode":R==="BLEND"&&(b=!0);continue}}if(Array.isArray(R)&&R.length===4){f[S]={value:new fe(R[0],R[1],R[2],R[3])};continue}f[S]={value:R}}}}const w=new Ms(this.identifier,{name:i.name??"",uniforms:f,vertexShader:y,fragmentShader:g,lights:!1});switch(w.glslVersion=sC,w.vertexShader=w.vertexShader.replace("#version 300 es",""),w.fragmentShader=w.fragmentShader.replace("#version 300 es",""),(h=f._Cull)==null?void 0:h.value){case 0:w.side=Si;break;case 1:w.side=dm;break;case 2:w.side=ao;break;default:w.side=ao;break}switch((d=f._ZTest)==null?void 0:d.value){case 3:w.depthTest=!0,w.depthFunc=hC;break;case 6:w.depthTest=!0,w.depthFunc=cC;break;case 2:w.depthTest=!0,w.depthFunc=lC;break;case 4:w.depthTest=!0,w.depthFunc=aC;break;case 5:w.depthTest=!0,w.depthFunc=rC;break;case 7:w.depthTest=!0,w.depthFunc=oC;break;case 8:w.depthTest=!1,w.depthFunc=nC;break}w.transparent=b,b&&(w.depthWrite=!1),ok(f),w.onUpdateUniforms();for(const _ in v){const S=_,R=v[_].type;if(((u=f[S])==null?void 0:u.value)===void 0)switch(R){case ox.SAMPLER_2D:f[S]={value:sk},console.warn("Missing/unassigned texture, fallback to white: "+S);break;default:S==="unity_OrthoParams"||console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+S,v[_]);break}}Js&&console.log(w.uuid,f),rx(w),l(w)}):null}}function rx(s){if(s.uniforms){Js&&console.log("Uniforms:",s.uniforms);for(const i in s.uniforms)switch(t(i,i),i){case"_Color":t("color",i);break}}function t(i,n){Object.getOwnPropertyDescriptor(s,i)||Object.defineProperty(s,i,{get:()=>s.uniforms[n].value,set:o=>{s.uniforms[n].value=o,s.needsUpdate=!0}})}}const LR=C("debugextensions");let Uu;const DR=import("./three-examples.light.min.js").then(s=>s.r).then(async s=>(Uu=s.GLTFAnimationPointerExtension,Uu)).catch(s=>{console.warn("Failed to import GLTFLoaderAnimationPointer. Please use @needle-tools/three for full KHR_animation support",s)}),Ir=new Array;function BR(s){Ir.includes(s)||Ir.push(s)}function FR(s){const t=Ir.indexOf(s);t>=0&&Ir.splice(t,1)}function Nu(s){const t=new ix;return s.register(i=>(t.parser=i,t)),t}class zR{resolvePath(t){return t.includes("/extensions/builtin_components/")?t.replace("/extensions/builtin_components/","/userData/components/"):t.includes("extensions/builtin_components/")?t.replace("extensions/builtin_components/","/userData/components/"):t}}async function Wu(s,t,i){const n=i.indexOf("?");n>=0&&(i=i.substring(0,n)),s.register(o=>new kR(o)),s.register(o=>new I2(o)),s.register(o=>new J2(o,t.lightmaps,i)),s.register(o=>new MR(o,i,t)),s.register(o=>new jR(o,i)),s.register(o=>new Uf(o,i)),s.register(o=>new it(o,i)),s.register(o=>new SR(o)),Xb()&&s.register(o=>new bg(o)),await DR.catch(o=>{}),s.register(o=>{if(Uu){const r=new Uu(o);return r.setAnimationPointerResolver.bind(r)(new zR),r}else return(LR||F())&&console.error("Missing KHR_animation_pointer extension..."),{name:"KHR_animation_pointer_NOT_AVAILABLE"}});for(const o of Ir)o.onImport&&o.onImport(s,i,t)}function Wf(s,t){for(const i of Ir)i.onExport&&i.onExport(s,t)}function Vf(s,t,i){for(const n of Ir)n.onLoaded&&n.onLoaded(s,t,i)}class ax{constructor(t){this.writer=t,this.name="EXT_mesh_gpu_instancing"}writeNode(t,i){if(t.constructor.name!=="InstancedMesh")return;const n=this.writer,o=n.extensionsUsed,r={};i.extensions=i.extensions||{},i.extensions[this.name]=r;let l=new ne;const c=new Array,h=new Array,d=new Array;for(let y=0;y<t.count;y++){t.getMatrixAt(y,l);let f=new x,v=new V,b=new x;l.decompose(f,v,b),c.push(f.x,f.y,f.z),h.push(v.x,v.y,v.z,v.w),d.push(b.x,b.y,b.z)}const u=new Float32Array(c),p=new Float32Array(h),g=new Float32Array(d);r.attributes={TRANSLATION:n.processAccessor(new ft(u,3)),ROTATION:n.processAccessor(new ft(p,4)),SCALE:n.processAccessor(new ft(g,3))},o[this.name]=!0}}var UR=Object.defineProperty,NR=Object.getOwnPropertyDescriptor,lx=(s,t,i,n)=>{for(var o=n>1?void 0:n?NR(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&UR(t,i,o),o};const Vu=C("debugreflectionprobe"),cx=C("noreflectionprobe"),WR=Symbol("reflectionProbeKey"),VR=Symbol("original material");var Hu;const zn=(Hu=class extends A{constructor(){var s;super(),a(this,"_texture"),a(this,"center"),a(this,"size"),a(this,"_boxHelper"),zn._probes.has(this.context)||zn._probes.set(this.context,[]),(s=zn._probes.get(this.context))==null||s.push(this)}static get(s,t,i,n){if(!s||s.isObject3D!==!0||cx)return null;const o=zn._probes.get(t);if(o){for(const r of o)if(r.__didAwake||r.__internalAwake(),r.enabled&&n&&r.gameObject===n)return r}return Vu&&console.debug("Did not find reflection probe",s.name,i,s),null}set texture(s){if(s&&!(s instanceof Le)){console.error("ReflectionProbe.texture must be a Texture",s);return}this._texture=s,s&&(s.mapping=yn,s.colorSpace=ms,s.needsUpdate=!0)}get texture(){return this._texture}isInBox(s){var t;return(t=this._boxHelper)==null?void 0:t.isInBox(s)}awake(){this._boxHelper=this.gameObject.addComponent(Ji),this._boxHelper.updateBox(!0),Vu&&this._boxHelper.showHelper(5592320,!0),this.texture&&(this.texture.mapping=yn,this.texture.colorSpace=ms,this.texture.needsUpdate=!0)}onDestroy(){const s=zn._probes.get(this.context);if(s){const t=s.indexOf(this);t>=0&&s.splice(t,1)}}onSet(s){var t;if(cx||!this.enabled||((t=s.sharedMaterials)==null?void 0:t.length)<=0||!this.texture)return;let i=zn._rendererMaterialsCache.get(s);i||(i=[],zn._rendererMaterialsCache.set(s,i));for(let n=0;n<s.sharedMaterials.length;n++){const o=s.sharedMaterials[n];if(!o||o.envMap===void 0||o instanceof Re)continue;let r=i[n];const l=o===r?.copy,c=!r||r.material.uuid!==o.uuid||r.copy.version!==o.version;if(!l&&c){if(Vu){let u="";r?r.material!==o?u="reference changed; cached instance?: "+l:r.copy.version!==o.version&&(u="version changed"):u="not cached",console.warn("Cloning material",o.name,o.version,"Reason:",u,`
943
947
  `,o.uuid,`
944
948
  `,r?.copy.uuid,`
945
949
  `,s.name)}const d=o.clone();d.version=o.version,r?(r.copy=d,r.material=o):(r={material:o,copy:d},i.push(r)),d[WR]=this,d[VR]=o,Vu&&console.log("Set reflection",s.name,s.guid)}r&&r.copy&&(r.copy.onBeforeCompile=o.onBeforeCompile);const h=r?.copy;h.envMap=this.texture,s.sharedMaterials[n]=h}}onUnset(s){const t=zn._rendererMaterialsCache.get(s);if(t)for(let i=0;i<t.length;i++){const n=t[i];s.sharedMaterials[i]=n.material}}},a(Hu,"_probes",new Map),a(Hu,"_rendererMaterialsCache",new Map),Hu);let sl=zn;lx([m(x)],sl.prototype,"center",2),lx([m(x)],sl.prototype,"size",2);const pi=C("debuginstancing"),Hf=class{constructor(){a(this,"objs",[])}setup(s,t,i,n,o,r=0){s.applySettings(t);const l=this.tryCreateOrAddInstance(t,i,o);if(l){n===null&&(n=[]),n.push(l),it.assignTextureLOD(l.renderer.material,0);for(let c=0;c<s.sharedMeshes.length;c++){const h=s.sharedMeshes[c],d=h.geometry;it.assignMeshLOD(h,0).then(u=>{u&&s.activeAndEnabled&&d!=u&&l.setGeometry(u)})}}else if(r<=0&&t.type!=="Mesh"){const c=r+1;for(const h of t.children)n=this.setup(s,h,i,n,o,c)}return r===0&&o.useMatrixWorldAutoUpdate&&n&&n.length>=0&&this.autoUpdateInstanceMatrix(t),n}tryCreateOrAddInstance(s,t,i){if(s.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 pi&&console.error("Something is wrong with instance setup",s,i.rend.enableInstancing,n),null;if(!i.rend.enableInstancing[n])return null}const o=s,r=o.material;for(const d of this.objs)if(!!d.canAdd(o.geometry,r))return d.addInstance(o);let l=Hf.getStartInstanceCount(s);(!l||l<0)&&(l=4);let c=s.name;c!=null&&c.length||(c=Pv());const h=new hx(c,o.geometry,r,l,t);return this.objs.push(h),h.addInstance(o)}return null}autoUpdateInstanceMatrix(s){const t=s.matrixWorld.multiplyMatrices.bind(s.matrixWorld),i=s.matrixWorld.clone(),n=(o,r)=>{const l=t(o,r);return(s[vc]||i.equals(l)===!1)&&(i.copy(l),s[vc]=!0),l};s.matrixWorld.multiplyMatrices=n}};let nl=Hf;a(nl,"instance",new Hf),a(nl,"getStartInstanceCount",s=>4);const $u=class{constructor(s,t){a(this,"object"),a(this,"renderer"),a(this,"__instanceIndex",-1),a(this,"__reservedVertexRange",0),a(this,"__reservedIndexRange",0),a(this,"__geometryIndex",-1),a(this,"meshInformation"),this.__instanceIndex=-1,this.object=s,this.renderer=t,s[e_]=t,this.meshInformation=jr(s.geometry),$u.all.push(this)}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}updateMeshInformation(){const s=jr(this.object.geometry),t=this.meshInformation.vertexCount,i=this.meshInformation.indexCount;return Object.assign(this.meshInformation,s),t!==this.meshInformation.vertexCount||i!==this.meshInformation.indexCount}updateInstanceMatrix(s=!1,t=!0){this.__instanceIndex<0||(t&&this.object.updateWorldMatrix(!0,s),this.renderer.updateInstance(this.object.matrixWorld,this.__instanceIndex))}setMatrix(s){this.__instanceIndex<0||this.renderer.updateInstance(s,this.__instanceIndex)}setGeometry(s){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(s,this.__geometryIndex);function i(n){return t.updateMeshInformation()&&(t.renderer.remove(t,!0),t.renderer.add(t))?!0:((F()||pi)&&console.error(n),!1)}}add(){this.__instanceIndex>=0||(this.renderer.add(this),O.markAsInstancedRendered(this.object,!0))}remove(s){if(!(this.__instanceIndex<0)&&(this.renderer.remove(this,s),O.markAsInstancedRendered(this.object,!1),s)){const t=$u.all.indexOf(this);t>=0&&$u.all.splice(t,1)}}};let qu=$u;a(qu,"all",[]);class hx{constructor(t,i,n,o,r){a(this,"allowResize",!0),a(this,"name",""),a(this,"geometry"),a(this,"material"),a(this,"_context"),a(this,"_batchedMesh"),a(this,"_handles",[]),a(this,"_geometryIds",new Map),a(this,"_maxInstanceCount"),a(this,"_currentInstanceCount",0),a(this,"_currentVertexCount",0),a(this,"_currentIndexCount",0),a(this,"_maxVertexCount"),a(this,"_maxIndexCount"),a(this,"_needUpdateBounds",!1),a(this,"_debugMaterial",null),a(this,"onBeforeRender",()=>{this._batchedMesh.layers.enableAll(),this._needUpdateBounds&&this._batchedMesh[bc]===!0&&(pi==="verbose"&&console.log("Update instancing bounds",this.name,this._batchedMesh.matrixWorldNeedsUpdate),this.updateBounds())}),a(this,"onAfterRender",()=>{this._batchedMesh.layers.disableAll()}),this.name=t,this.geometry=i,this.material=n,this._context=r,this._maxInstanceCount=Math.max(2,o),pi&&(this._debugMaterial=dx());const l=this.tryEstimateVertexCountSize(this._maxInstanceCount,[i],o);this._maxVertexCount=l.vertexCount,this._maxIndexCount=l.indexCount,this._batchedMesh=new Ky(this._maxInstanceCount,this._maxVertexCount,this._maxIndexCount,this._debugMaterial??this.material),this._batchedMesh[bc]=!0,this._batchedMesh.visible=!0,this._context.scene.add(this._batchedMesh),n instanceof Zy&&(n.defines.USE_INSTANCING=!0,n.needsUpdate=!0),r.pre_render_callbacks.push(this.onBeforeRender),r.post_render_callbacks.push(this.onAfterRender),pi&&console.log(`Instanced renderer created with ${this._maxInstanceCount} instances, ${this._maxVertexCount} max vertices and ${this._maxIndexCount} max indices for "${t}"`)}get batchedMesh(){return this._batchedMesh}get visible(){return this._batchedMesh.visible}set visible(t){this._batchedMesh.visible=t}get castShadow(){return this._batchedMesh.castShadow}set castShadow(t){this._batchedMesh.castShadow=t}set receiveShadow(t){this._batchedMesh.receiveShadow=t}get count(){return this._currentInstanceCount}updateBounds(t=!0,i=!0){if(this._needUpdateBounds=!1,t&&this._batchedMesh.computeBoundingBox(),i&&this._batchedMesh.computeBoundingSphere(),pi&&this._batchedMesh.boundingSphere){const n=this._batchedMesh.boundingSphere;q.DrawWireSphere(n.center,n.radius,65280)}}canAdd(t,i){return this._maxVertexCount>1e7||i!==this.material||!this.validateGeometry(t)?!1:!!(!this.mustGrow(t)||this.allowResize)}dispose(){pi&&console.warn("Dispose instanced renderer",this.name),this._context.scene.remove(this._batchedMesh),this._batchedMesh.dispose(),this._batchedMesh=null,this._handles=[]}addInstance(t){const i=new qu(t,this);t.castShadow===!0&&this._batchedMesh.castShadow===!1&&(this._batchedMesh.castShadow=!0),t.receiveShadow===!0&&this._batchedMesh.receiveShadow===!1&&(this._batchedMesh.receiveShadow=!0);try{this.add(i)}catch(n){if(console.error(`Failed adding mesh to instancing (object name: "${t.name}", instances: ${this._currentInstanceCount.toLocaleString()}/${this._maxInstanceCount.toLocaleString()}, vertices: ${this._currentVertexCount.toLocaleString()}/${this._maxVertexCount.toLocaleString()}, indices: ${this._currentIndexCount.toLocaleString()}/${this._maxIndexCount.toLocaleString()})
@@ -1013,7 +1017,7 @@ ${g}
1013
1017
  )
1014
1018
  `}}const ll=`
1015
1019
  `,Zt="</StageRoot/Materials";class _x{constructor(){a(this,"str"),a(this,"indent"),this.str="",this.indent=0}clear(){this.str="",this.indent=0}beginBlock(t=void 0,i="{",n=!0){t!==void 0?(t=this.applyIndent(t),this.str+=t,n?(this.str+=ll,this.str+=this.applyIndent(i)):this.str+=" "+i):this.str+=this.applyIndent(i),this.str+=ll,this.indent+=1}closeBlock(t="}"){this.indent-=1,this.str+=this.applyIndent(t)+ll}beginArray(t){t=this.applyIndent(t+" = ["),this.str+=t,this.str+=ll,this.indent+=1}closeArray(){this.indent-=1,this.str+=this.applyIndent("]")+ll}appendLine(t=""){t=this.applyIndent(t),this.str+=t,this.str+=ll}toString(){return this.str}applyIndent(t){let i="";for(let n=0;n<this.indent;n++)i+=" ";return i+t}}class tT{constructor(t,i,n){a(this,"root"),a(this,"exporter"),a(this,"extensions",[]),a(this,"quickLookCompatible"),a(this,"exportInvisible"),a(this,"materials"),a(this,"textures"),a(this,"files"),a(this,"document"),a(this,"output"),a(this,"animations"),this.root=t,this.exporter=i,this.quickLookCompatible=n.quickLookCompatible,this.exportInvisible=n.exportInvisible,n.extensions&&(this.extensions=n.extensions),this.materials=new Map,this.textures={},this.files={},this.document=new Gf,this.output="",this.animations=[]}}class Xf{constructor(){a(this,"ar",{anchoring:{type:"plane"},planeAnchoring:{alignment:"horizontal"}}),a(this,"quickLookCompatible",!1),a(this,"extensions",[]),a(this,"maxTextureSize",4096),a(this,"exportInvisible",!1)}}let wx=class{constructor(){a(this,"debug"),a(this,"pruneUnusedNodes"),a(this,"sceneAnchoringOptions",new Xf),a(this,"extensions",[]),a(this,"keepObject"),a(this,"beforeWritingDocument"),this.debug=!1,this.pruneUnusedNodes=!0}async parse(s,t=new Xf){var i,n;t=Object.assign(new Xf,t),this.sceneAnchoringOptions=t;const o=new tT(s,this,t);this.extensions=o.extensions;const r=o.files,l="model.usda";r[l]=null;const c=o.materials,h=o.textures;ce.report("export-usdz","Invoking onBeforeBuildDocument"),await Yu(o,"onBeforeBuildDocument"),ce.report("export-usdz","Done onBeforeBuildDocument"),ce.report("export-usdz","Reparent bones to common ancestor");const d=[],u=new Set;s?.traverse(_=>{if(!(!t.exportInvisible&&!_.visible)&&_ instanceof fn){const S=_.skeleton.bones,R=vx(S);if(R){const M={object:_,originalParent:_.parent,newParent:R};d.push(M),u.add(M.object.uuid),M.newParent&&u.add(M.newParent.uuid),M.originalParent&&u.add(M.originalParent.uuid)}}});for(const _ of d){const{object:S,originalParent:R,newParent:M}=_;M.add(S)}ce.report("export-usdz","Traversing hierarchy"),s&&xx(s,o.document,o,this.keepObject),ce.report("export-usdz","Invoking onAfterBuildDocument"),await Yu(o,"onAfterBuildDocument");const p=o.extensions.find(_=>_.extensionName==="Behaviour"),g=p?.getAllTargetUuids()??new Set;if(this.pruneUnusedNodes){const _={allBehaviorTargets:g,debug:!1,boneReparentings:u,quickLookCompatible:o.quickLookCompatible};this.debug&&Sx(o.document,"Hierarchy BEFORE pruning",_),Cx(o.document,_),this.debug&&Sx(o.document,"Hierarchy AFTER pruning")}else this.debug&&console.log("Pruning of empty nodes is disabled. This may result in a larger USDZ file.");ce.report("export-usdz",{message:"Parsing document",autoStep:10}),await iT(o,()=>(ce.report("export-usdz","Building materials"),hT(c,h,t.quickLookCompatible))),ce.report("export-usdz","Invoking onAfterSerialize"),await Yu(o,"onAfterSerialize");for(const _ of d){const{object:S,originalParent:R,newParent:M}=_;R&&R.add(S)}(n=(i=o.exporter)==null?void 0:i.beforeWritingDocument)==null||n.call(i);const y=o.document.buildHeader(o)+`
1016
- `+o.output;this.debug&&console.log(y),r[l]=av(y),o.output="",ce.report("export-usdz",{message:"Exporting textures",autoStep:10}),ce.start("export-usdz-textures",{parentScope:"export-usdz",logTimings:!1});const f=new sr({antialias:!1,alpha:!0,premultipliedAlpha:!1,preserveDrawingBuffer:!0}),v=Object.keys(h).length;ce.report("export-usdz-textures",{totalSteps:v*3,currentStep:0});const b=async _=>{const S=h[_],R=S.texture,M=Lx.includes(R.format);let T={imageData:R.image};ce.report("export-usdz-textures",{message:"read back texture",autoStep:!0});const j=S.scale!==void 0&&S.scale.x!==1&&S.scale.y!==1&&S.scale.z!==1&&S.scale.w!==1;(R.isCompressedTexture||R.isRenderTargetTexture||j)&&(T=await Px(R,t.maxTextureSize,f,S.scale)),ce.report("export-usdz-textures",{message:"convert texture to canvas",autoStep:!0});const L=await nT(T.imageBitmap||T.imageData,t.maxTextureSize).catch(U=>{console.error("Error converting texture to canvas",R,U)});if(L){ce.report("export-usdz-textures",{message:"convert canvas to blob",autoStep:!0});const U=await L.convertToBlob({type:M?"image/png":"image/jpeg",quality:.95});r[`textures/${_}.${M?"png":"jpg"}`]=new Uint8Array(await U.arrayBuffer())}else console.warn("Can`t export texture: ",R)};for(const _ in h)await b(_);f.dispose(),ce.end("export-usdz-textures");let w=0;for(const _ in r){const S=r[_],R=34+_.length;w+=R;const M=w&63;if(M!==4){const T=64-M,j=new Uint8Array(T);r[_]=[S,{extra:{12345:j}}]}w=S.length}return ce.report("export-usdz","zip archive"),VC(r,{level:0})}};function xx(s,t,i,n){var o;if(!i.exportInvisible&&!s.visible)return;let r,l,c;const h={position:s.position,quaternion:s.quaternion,scale:s.scale};if(s.position.x===0&&s.position.y===0&&s.position.z===0&&(h.position=null),s.quaternion.x===0&&s.quaternion.y===0&&s.quaternion.z===0&&s.quaternion.w===1&&(h.quaternion=null),s.scale.x===1&&s.scale.y===1&&s.scale.z===1&&(h.scale=null),(s instanceof Y||s instanceof fn)&&(l=s.geometry,c=s.material),n&&!n(s)&&(l=void 0,c=void 0),(s instanceof Y||s instanceof fn)&&c&&(c instanceof ni||c instanceof Re||c instanceof ke&&c.type==="MeshLineMaterial")){const d=Ju(s),u=s instanceof fn?s:null;r=new Yt(s.uuid,d,h,l,c,void 0,u,s.animations)}else if(s instanceof _e||s instanceof lm){const d=Ju(s);r=new Yt(s.uuid,d,h,void 0,void 0,s)}else{const d=Ju(s);r=new Yt(s.uuid,d,h,void 0,void 0,void 0,void 0,s.animations)}if(r){if(r.displayName=((o=s.userData)==null?void 0:o.name)||s.name,r.visibility=s.visible?void 0:"invisible",t&&t.add(r),t=r,i.extensions)for(const d of i.extensions)d.onExportObject&&d.onExportObject.call(d,s,r,i)}else{const d=Ju(s),u=new Yt(s.uuid,d,{position:s.position,quaternion:s.quaternion,scale:s.scale});t&&t.add(u),t=u}for(const d of s.children)xx(d,t,i,n)}function Sx(s,t,...i){const n={};let o=0;function r(l,c){o++;let h=l.displayName||l.name;h+=" ("+l.uuid+")",(l.geometry||l.material||l.camera||l.skinnedMesh)&&(h+=" ("+(l.geometry?"geo, ":"")+(l.material?"mat, ":"")+(l.camera?"cam, ":"")+(l.skinnedMesh?"skin, ":"")+")"),c[h]={};const d={object:l};l.material&&(d.mat=!0),l.geometry&&(d.geo=!0),l.camera&&(d.cam=!0),l.skinnedMesh&&(d.skin=!0),c[h]._self=d;for(const u of l.children)u&&r(u,c[h])}r(s,n),console.log(t+" ("+o+" nodes)",n,...i)}function Cx(s,t){var i;let n=!0;const o=new Array,r=new Array;if(s.children.length===0)n=!0;else{const u=[...s.children];for(const p of u)if(p){const g=Cx(p,t);t.debug&&(g?o.push(p):r.push(p)),n=n&&g}}const l=t.allBehaviorTargets.has(s.uuid),c=s.geometry||s.material||s.camera&&!t.quickLookCompatible||s.skinnedMesh||!1,h=t.boneReparentings.has(s.uuid),d=n&&!l&&!c&&!h;return d?(t.debug&&console.log("Pruned object:",(s.displayName||s.name)+" ("+s.uuid+")",{isVisible:c,isBehaviorSourceOrTarget:l,allChildsWerePruned:n,isBoneReparenting:h,object:s,prunedChilds:o,keptChilds:r}),(i=s.parent)==null||i.remove(s)):t.debug&&console.log("Kept object:",(s.displayName||s.name)+" ("+s.uuid+")",{isVisible:c,isBehaviorSourceOrTarget:l,allChildsWerePruned:n,isBoneReparenting:h,object:s,prunedChilds:o,keptChilds:r}),d}async function iT(s,t){ce.start("export-usdz-resources","export-usdz");const i=[];for(const h of s.document.children)Ox(h,s,i);const n=i.length;for(let h=0;h<n;h++)ce.report("export-usdz-resources",{totalSteps:n,currentStep:h}),await new Promise((d,u)=>{i[h](),d()});ce.end("export-usdz-resources");const o=new _x,r=s.exporter.sceneAnchoringOptions.ar;o.beginBlock(`def Xform "${s.document.name}"`),o.beginBlock(`def Scope "Scenes" (
1020
+ `+o.output;this.debug&&console.log(y),r[l]=av(y),o.output="",ce.report("export-usdz",{message:"Exporting textures",autoStep:10}),ce.start("export-usdz-textures",{parentScope:"export-usdz",logTimings:!1});const f=new sr({antialias:!1,alpha:!0,premultipliedAlpha:!1,preserveDrawingBuffer:!0}),v=Object.keys(h).length;ce.report("export-usdz-textures",{totalSteps:v*3,currentStep:0});const b=async _=>{const S=h[_],R=S.texture,M=Lx.includes(R.format);let T={imageData:R.image};ce.report("export-usdz-textures",{message:"read back texture",autoStep:!0});const L=S.scale!==void 0&&S.scale.x!==1&&S.scale.y!==1&&S.scale.z!==1&&S.scale.w!==1;(R.isCompressedTexture||R.isRenderTargetTexture||L)&&(T=await Px(R,t.maxTextureSize,f,S.scale)),ce.report("export-usdz-textures",{message:"convert texture to canvas",autoStep:!0});const D=await nT(T.imageBitmap||T.imageData,t.maxTextureSize).catch(U=>{console.error("Error converting texture to canvas",R,U)});if(D){ce.report("export-usdz-textures",{message:"convert canvas to blob",autoStep:!0});const U=await D.convertToBlob({type:M?"image/png":"image/jpeg",quality:.95});r[`textures/${_}.${M?"png":"jpg"}`]=new Uint8Array(await U.arrayBuffer())}else console.warn("Can`t export texture: ",R)};for(const _ in h)await b(_);f.dispose(),ce.end("export-usdz-textures");let w=0;for(const _ in r){const S=r[_],R=34+_.length;w+=R;const M=w&63;if(M!==4){const T=64-M,L=new Uint8Array(T);r[_]=[S,{extra:{12345:L}}]}w=S.length}return ce.report("export-usdz","zip archive"),VC(r,{level:0})}};function xx(s,t,i,n){var o;if(!i.exportInvisible&&!s.visible)return;let r,l,c;const h={position:s.position,quaternion:s.quaternion,scale:s.scale};if(s.position.x===0&&s.position.y===0&&s.position.z===0&&(h.position=null),s.quaternion.x===0&&s.quaternion.y===0&&s.quaternion.z===0&&s.quaternion.w===1&&(h.quaternion=null),s.scale.x===1&&s.scale.y===1&&s.scale.z===1&&(h.scale=null),(s instanceof Y||s instanceof fn)&&(l=s.geometry,c=s.material),n&&!n(s)&&(l=void 0,c=void 0),(s instanceof Y||s instanceof fn)&&c&&(c instanceof ni||c instanceof Re||c instanceof ke&&c.type==="MeshLineMaterial")){const d=Ju(s),u=s instanceof fn?s:null;r=new Yt(s.uuid,d,h,l,c,void 0,u,s.animations)}else if(s instanceof _e||s instanceof lm){const d=Ju(s);r=new Yt(s.uuid,d,h,void 0,void 0,s)}else{const d=Ju(s);r=new Yt(s.uuid,d,h,void 0,void 0,void 0,void 0,s.animations)}if(r){if(r.displayName=((o=s.userData)==null?void 0:o.name)||s.name,r.visibility=s.visible?void 0:"invisible",t&&t.add(r),t=r,i.extensions)for(const d of i.extensions)d.onExportObject&&d.onExportObject.call(d,s,r,i)}else{const d=Ju(s),u=new Yt(s.uuid,d,{position:s.position,quaternion:s.quaternion,scale:s.scale});t&&t.add(u),t=u}for(const d of s.children)xx(d,t,i,n)}function Sx(s,t,...i){const n={};let o=0;function r(l,c){o++;let h=l.displayName||l.name;h+=" ("+l.uuid+")",(l.geometry||l.material||l.camera||l.skinnedMesh)&&(h+=" ("+(l.geometry?"geo, ":"")+(l.material?"mat, ":"")+(l.camera?"cam, ":"")+(l.skinnedMesh?"skin, ":"")+")"),c[h]={};const d={object:l};l.material&&(d.mat=!0),l.geometry&&(d.geo=!0),l.camera&&(d.cam=!0),l.skinnedMesh&&(d.skin=!0),c[h]._self=d;for(const u of l.children)u&&r(u,c[h])}r(s,n),console.log(t+" ("+o+" nodes)",n,...i)}function Cx(s,t){var i;let n=!0;const o=new Array,r=new Array;if(s.children.length===0)n=!0;else{const u=[...s.children];for(const p of u)if(p){const g=Cx(p,t);t.debug&&(g?o.push(p):r.push(p)),n=n&&g}}const l=t.allBehaviorTargets.has(s.uuid),c=s.geometry||s.material||s.camera&&!t.quickLookCompatible||s.skinnedMesh||!1,h=t.boneReparentings.has(s.uuid),d=n&&!l&&!c&&!h;return d?(t.debug&&console.log("Pruned object:",(s.displayName||s.name)+" ("+s.uuid+")",{isVisible:c,isBehaviorSourceOrTarget:l,allChildsWerePruned:n,isBoneReparenting:h,object:s,prunedChilds:o,keptChilds:r}),(i=s.parent)==null||i.remove(s)):t.debug&&console.log("Kept object:",(s.displayName||s.name)+" ("+s.uuid+")",{isVisible:c,isBehaviorSourceOrTarget:l,allChildsWerePruned:n,isBoneReparenting:h,object:s,prunedChilds:o,keptChilds:r}),d}async function iT(s,t){ce.start("export-usdz-resources","export-usdz");const i=[];for(const h of s.document.children)Ox(h,s,i);const n=i.length;for(let h=0;h<n;h++)ce.report("export-usdz-resources",{totalSteps:n,currentStep:h}),await new Promise((d,u)=>{i[h](),d()});ce.end("export-usdz-resources");const o=new _x,r=s.exporter.sceneAnchoringOptions.ar;o.beginBlock(`def Xform "${s.document.name}"`),o.beginBlock(`def Scope "Scenes" (
1017
1021
  kind = "sceneLibrary"
1018
1022
  )`),o.beginBlock('def Xform "Scene"',"(",!1),o.appendLine('apiSchemas = ["Preliminary_AnchoringAPI"]'),o.appendLine("customData = {"),o.appendLine(" bool preliminary_collidesWithEnvironment = 0"),o.appendLine(' string sceneName = "Scene"'),o.appendLine("}"),o.appendLine('sceneName = "Scene"'),o.closeBlock(")"),o.beginBlock(),o.appendLine(`token preliminary:anchoring:type = "${r.anchoring.type}"`),r.anchoring.type==="plane"&&o.appendLine(`token preliminary:planeAnchoring:alignment = "${r.planeAnchoring.alignment}"`),r.anchoring.type==="image"&&o.appendLine(`rel preliminary:imageAnchoring:referenceImage = </${s.document.name}/Scenes/Scene/AnchoringReferenceImage>`),o.appendLine();const l=h=>{if(!h)return 0;let d=1;for(const u of h.children)d+=l(u);return d},c=l(s.document);ce.start("export-usdz-xforms","export-usdz"),ce.report("export-usdz-xforms",{totalSteps:c,currentStep:1});for(const h of s.document.children)Rx(h,o,s);ce.end("export-usdz-xforms"),ce.report("export-usdz","invoke onAfterHierarchy"),Yu(s,"onAfterHierarchy",o),o.closeBlock(),o.closeBlock(),o.appendLine(t()),o.closeBlock(),ce.report("export-usdz","write to string"),s.output+=o.toString()}function Ox(s,t,i){if(!s)return;const n=s.geometry,o=s.material;if(n)if(o&&("isMeshStandardMaterial"in o&&o.isMeshStandardMaterial||"isMeshBasicMaterial"in o&&o.isMeshBasicMaterial||o.type==="MeshLineMaterial")){const r="geometries/"+Yf(n,s.name)+".usda";if(!(r in t.files)){const l=()=>{var c,h;const d=aT(n,(h=(c=s.skinnedMesh)==null?void 0:c.skeleton)==null?void 0:h.bones,t.quickLookCompatible);t.files[r]=rT(d)};i.push(l)}}else console.warn("NeedleUSDZExporter: Unsupported material type (USDZ only supports MeshStandardMaterial)",o?.name);o&&(o.uuid in t.materials||(t.materials[o.uuid]=o));for(const r of s.children)Ox(r,t,i)}async function Yu(s,t,i=null){if(s.extensions){for(const n of s.extensions)if(n&&typeof n[t]=="function"){const o=n[t].call(n,s,i);o instanceof Promise&&await o}}}let Zu=null,Kt=null,Qf,cl,Ku;async function Px(s,t=1/0,i=null,n=void 0){Qf||(Qf=new Fs(2,2,1,1)),cl||(cl=new ps({uniforms:{blitTexture:new io(s),flipY:new io(!1),scale:new io(new fe(1,1,1,1))},vertexShader:`
1019
1023
  varying vec2 vUv;
@@ -1122,7 +1126,7 @@ ${n.join("")}
1122
1126
  uniform token info:id = "${b}"
1123
1127
  token outputs:out
1124
1128
  }
1125
- }`}const c=" ",h=[],d=[],u=new Set;function p(b){var w;return Rs(b.name)+"_"+(((w=b.source)==null?void 0:w.id)??b.id)}function g(b,w,_=void 0,S=void 0){const R=p(b),M=R+(S!==void 0&&S!==1?"_"+S:""),T=i&&S!==void 0&&S!==1,j=T?new fe(1,1,1,S):void 0;S===void 0&&(S=1),T&&(S=1),j&&j.w<=.05&&(j.w=.05),t[M]={texture:b,scale:j};const L=b.channel>0?"st"+b.channel:"st";u.add(b.channel);const U=Lx.includes(b.format),B={1e3:"repeat",1001:"clamp",1002:"mirror"},Q=b.repeat.clone(),$=b.offset.clone(),E=b.rotation,z=Math.sin(E),H=Math.cos(E);$.y=1-$.y-Q.y,i?(Q.x===0&&(Q.x=1e-4),Q.y===0&&(Q.y=1e-4),$.x=$.x/Q.x,$.y=$.y/Q.y,$.x+=z/Q.x,$.y+=H-1):($.x+=z*Q.x,$.y+=(1-H)*Q.y);const ie=Q.x!=1||Q.y!=1||$.x!=0||$.y!=0||E!=0,oe=`${Zt}/${l}/${"uvReader_"+L}.outputs:result>`,de=`${Zt}/${l}/Transform2d_${w}.outputs:result>`,pe=w!=="normal"&&_&&(_.r!==1||_.g!==1||_.b!==1||S!==1)||!1,Xe=w==="normal",Qe=s instanceof ni&&s.normalScale?s.normalScale.x*2:2,hs=Qe.toFixed(je),ds=(-1*(Qe/2)).toFixed(je),Vl=(1-Qe).toFixed(je);return`
1129
+ }`}const c=" ",h=[],d=[],u=new Set;function p(b){var w;return Rs(b.name)+"_"+(((w=b.source)==null?void 0:w.id)??b.id)}function g(b,w,_=void 0,S=void 0){const R=p(b),M=R+(S!==void 0&&S!==1?"_"+S:""),T=i&&S!==void 0&&S!==1,L=T?new fe(1,1,1,S):void 0;S===void 0&&(S=1),T&&(S=1),L&&L.w<=.05&&(L.w=.05),t[M]={texture:b,scale:L};const D=b.channel>0?"st"+b.channel:"st";u.add(b.channel);const U=Lx.includes(b.format),B={1e3:"repeat",1001:"clamp",1002:"mirror"},Q=b.repeat.clone(),$=b.offset.clone(),E=b.rotation,z=Math.sin(E),H=Math.cos(E);$.y=1-$.y-Q.y,i?(Q.x===0&&(Q.x=1e-4),Q.y===0&&(Q.y=1e-4),$.x=$.x/Q.x,$.y=$.y/Q.y,$.x+=z/Q.x,$.y+=H-1):($.x+=z*Q.x,$.y+=(1-H)*Q.y);const ie=Q.x!=1||Q.y!=1||$.x!=0||$.y!=0||E!=0,oe=`${Zt}/${l}/${"uvReader_"+D}.outputs:result>`,de=`${Zt}/${l}/Transform2d_${w}.outputs:result>`,pe=w!=="normal"&&_&&(_.r!==1||_.g!==1||_.b!==1||S!==1)||!1,Xe=w==="normal",Qe=s instanceof ni&&s.normalScale?s.normalScale.x*2:2,hs=Qe.toFixed(je),ds=(-1*(Qe/2)).toFixed(je),Vl=(1-Qe).toFixed(je);return`
1126
1130
  ${ie?`def Shader "Transform2d_${w}" (
1127
1131
  sdrMetadata = {
1128
1132
  string role = "math"
@@ -1196,7 +1200,7 @@ ${d.join(`
1196
1200
  `)}`:""}
1197
1201
  }`}function Ix(s){return`(${s.r}, ${s.g}, ${s.b})`}function jx(s){return`(${s.x}, ${s.y})`}const Lx=[1023,33777,33778,33779,35842,35843,37496,37808,37809,37810,37811,37812,37813,37814,37815,37816,37817,37818,37819,37820,37821,36492];C("debugusdz");const Dx=class{constructor(s,t,i){a(this,"id"),a(this,"trigger"),a(this,"action"),a(this,"exclusive",!1),this.id="Behavior_"+Rs(s)+"_"+Dx.global_id++,this.trigger=t,this.action=i}makeExclusive(s){return this.exclusive=s,this}writeTo(s,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()}};let Nt=Dx;a(Nt,"global_id",0);const dl=new Set;function t0(s,t){var i,n;let o="";if(Array.isArray(s)){dl.clear();let r="[ ";for(let l=0;l<s.length;l++){let c=s[l];if(!c){console.warn("Invalid target object in behavior",s+". Is the object exported?");continue}if(typeof c=="string"){if(dl.has(c))continue;r+=c,dl.add(c)}else if(typeof c=="object"){if(c.isObject3D&&(c=t.findById(c.uuid),!c)){console.warn("Invalid target object in behavior",s+". Is the object exported?");continue}const h=(i=c.getPath)==null?void 0:i.call(c);if(dl.has(h))continue;r+=h,dl.add(h)}l+1<s.length&&(r+=", ")}r+=" ]",o=r,dl.clear()}else if(typeof s=="object"){const r=s;if(r.isObject3D&&(s=t.findById(r.uuid)),!s)throw console.error("Invalid target object in behavior, the target object is likely missing from USDZ export. Is the object exported?",r),new Error(`Invalid target object in behavior, the target object is likely missing from USDZ export. Please report a bug. uuid: ${r.uuid}.`);o=(n=s.getPath)==null?void 0:n.call(s)}return o}const Bx=class{constructor(s,t){a(this,"id"),a(this,"targetId"),a(this,"tokenId"),a(this,"type"),a(this,"distance"),s&&(this.targetId=s),t?this.id=t:this.id="Trigger_"+Bx.global_id++}writeTo(s,t){t.beginBlock(`def Preliminary_Trigger "${this.id}"`),this.targetId&&(typeof this.targetId!="string"&&(this.targetId=t0(this.targetId,s)),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()}};let Lr=Bx;a(Lr,"global_id",0);function Fx(s,t={direct:!0,indirect:!0}){const i=Yt.createEmpty();i.name="InputTarget_"+i.name,i.displayName=void 0,i.type="RealityKitComponent",i.onSerialize=n=>{n.appendLine("bool allowsDirectInput = "+(t.direct?1:0)),n.appendLine("bool allowsIndirectInput = "+(t.indirect?1:0)),n.appendLine('uniform token info:id = "RealityKit.InputTarget"')},s.add(i)}class Rt{static sceneStartTrigger(){if(this.__sceneStartTrigger!==void 0)return this.__sceneStartTrigger;const t=new Lr(void 0,"SceneStart");return t.tokenId="SceneTransition",t.type="enter",this.__sceneStartTrigger=t,t}static tapTrigger(t,i={direct:!0,indirect:!0}){const n=new Lr(t);if(Array.isArray(t)&&t.length>1)for(const o of t)o instanceof Yt&&Fx(o,i);else t instanceof Yt&&Fx(t,i);return n.tokenId="TapGesture",n}static isTapTrigger(t){return t?.tokenId==="TapGesture"}static proximityToCameraTrigger(t,i){const n=new Lr(t);return n.tokenId="ProximityToCamera",n.distance=i,n}}a(Rt,"__sceneStartTrigger");class Eo{constructor(t,i){a(this,"id"),a(this,"actions"),a(this,"loops",0),a(this,"performCount",1),a(this,"type","serial"),a(this,"multiplePerformOperation"),this.id=t,this.actions=i}static getId(){return this.global_id++}addAction(t){return this.actions.push(t),this}makeParallel(){return this.type="parallel",this}makeSequence(){return this.type="serial",this}makeLooping(){return this.loops=1,this.performCount=0,this}makeRepeat(t){return this.performCount=t,this}writeTo(t,i){i.beginBlock(`def Preliminary_Action "${this.id}"`),i.beginArray("rel actions");for(const n of this.actions){if(!n)continue;const o=n===this.actions[this.actions.length-1];i.appendLine("<"+n.id+">"+(o?"":", "))}i.closeArray(),i.appendLine(),i.appendLine('token info:id = "Group"'),i.appendLine(`bool loops = ${this.loops}`),i.appendLine(`int performCount = ${this.loops>0?0:Math.max(0,this.performCount)}`),i.appendLine(`token type = "${this.type}"`),typeof this.multiplePerformOperation=="string"&&i.appendLine(`token multiplePerformOperation = "${this.multiplePerformOperation}"`),i.appendLine();for(const n of this.actions)n&&(n.writeTo(t,i),i.appendLine());i.closeBlock()}}a(Eo,"global_id",0);const i0=class{constructor(s,t){a(this,"id"),a(this,"tokenId"),a(this,"affectedObjects"),a(this,"easeType"),a(this,"motionType"),a(this,"duration"),a(this,"moveDistance"),a(this,"style"),a(this,"type"),a(this,"front"),a(this,"up"),a(this,"start"),a(this,"animationSpeed"),a(this,"reversed"),a(this,"pingPong"),a(this,"xFormTarget"),a(this,"audio"),a(this,"gain"),a(this,"auralMode"),a(this,"multiplePerformOperation"),a(this,"velocity"),a(this,"comment"),a(this,"animationName"),s&&(this.affectedObjects=s),t?this.id=t:this.id="Action",this.id+="_"+i0.global_id++}clone(){const s=new i0,t=s.id;return Object.assign(s,this),s.id=t,s}writeTo(s,t){t.beginBlock(`def Preliminary_Action "${this.id}"`),this.comment&&t.appendLine(`# ${this.comment}`),this.affectedObjects&&(typeof this.affectedObjects!="string"&&(this.affectedObjects=t0(this.affectedObjects,s)),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=t0(this.xFormTarget,s)),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()}};let ts=i0;a(ts,"global_id",0);class cs{constructor(t,i,n){a(this,"x",0),a(this,"y",0),a(this,"z",0),this.x=t,this.y=i,this.z=n}static get up(){return new cs(0,1,0)}static get right(){return new cs(1,0,0)}static get forward(){return new cs(0,0,1)}static get back(){return new cs(0,0,-1)}static get zero(){return new cs(0,0,0)}}class ve{static sequence(...t){return new Eo("Group_"+Eo.getId(),t).makeSequence()}static parallel(...t){return new Eo("Group_"+Eo.getId(),t).makeParallel()}static fadeAction(t,i,n){const o=new ts(t);return o.tokenId="Visibility",o.type=n?"show":"hide",o.duration=i,o.style="basic",o.motionType="none",o.moveDistance=0,o.easeType="none",o}static startAnimationAction(t,i,n=!1,o=!1){const r=new ts(t);r.tokenId="StartAnimation";const l=i.start,c=i.duration,h=i.speed,d=i.clipName;if(r.comment=`Animation: ${d}, start=${l*60}, length=${c*60}, end=${(l+c)*60}`,r.animationName=d,r.start=l,r.duration=c,r.animationSpeed=h,r.reversed=n,r.pingPong=o,r.multiplePerformOperation="allow",n&&(r.start-=c),o){r.pingPong=!1;const u=r.clone();return u.reversed=!n,u.start=r.start,u.reversed&&(u.start-=c),ve.sequence(r,u)}return r}static waitAction(t){const i=new ts;return i.tokenId="Wait",i.duration=t,i.motionType=void 0,i}static lookAtCameraAction(t,i,n,o){const r=new ts(t);return r.tokenId="LookAtCamera",r.duration=i===void 0?9999999999999:i,r.front=n??cs.forward,r.up=o??cs.up,r}static emphasize(t,i,n="bounce",o=1,r="basic"){const l=new ts(t);return l.tokenId="Emphasize",l.duration=i,l.style=r??"basic",l.motionType=n,l.moveDistance=o,l}static transformAction(t,i,n,o,r="inout"){const l=new ts(t);return l.tokenId="Transform",l.duration=n,l.duration=Math.max(1e-6,n),l.type=o,l.easeType=n>0?r:"none",Array.isArray(i)&&console.error("Transform target must not be an array",i),l.xFormTarget=i,l}static playAudioAction(t,i,n="play",o=1,r="spatial"){const l=new ts(t);return l.tokenId="Audio",l.type=n,l.audio=i,l.gain=o,l.auralMode=r,l.multiplePerformOperation="allow",l}static impulseAction(t,i){const n=new ts(t);return n.tokenId="Impulse",n.velocity=i,n}}class uT{constructor(t){a(this,"object"),a(this,"model"),this.object=t}get id(){return this.object.uuid}apply(t){if(!this.model&&(this.model=t.findById(this.object.uuid),!this.model)){console.error("could not find model with id "+this.object.uuid);return}this.onApply(t)}}class s0 extends uT{constructor(t,i,n,o){super(t),a(this,"matrix"),a(this,"material"),a(this,"geometry"),a(this,"_enableAction"),a(this,"_disableAction"),this.matrix=i,this.material=n,this.geometry=o}onApply(t){var i,n;const o=this.model;if(!o)return;(i=o.parent)!=null&&i.isDynamic||Yt.createEmptyParent(o);const r=o.clone();this.matrix&&r.setMatrix(this.matrix),this.material&&(r.material=this.material),this.geometry&&(r.geometry=this.geometry),(n=o.parent)==null||n.add(r)}enable(){return this._enableAction?this._enableAction:(this._enableAction=ve.fadeAction(this.object,0,!0),this._enableAction)}disable(){return this._disableAction?this._disableAction:(this._disableAction=ve.fadeAction(this.object,0,!1),this._disableAction)}}class zx{constructor(t){a(this,"actions"),a(this,"sortedActions"),this.actions=[...t]}organize(){this.sortedActions={};for(const t of this.actions){const i=t.id;this.sortedActions[i]||(this.sortedActions[i]=[]),this.sortedActions[i].push(t)}}getActions(t){return this.sortedActions||this.organize(),this.sortedActions[t.uuid]}}const en=C("debugusdzanimation"),n0=C("debugusdzanimationserialization");class ir{constructor(t,i,n){a(this,"_start"),a(this,"ext"),a(this,"root"),a(this,"_nearestAnimatedRoot"),a(this,"clip"),a(this,"speed"),this.ext=t,this.root=i,this.clip=n,this._nearestAnimatedRoot=this.getNearestAnimatedRoot()}get start(){return this._start===void 0&&(this._start=this.ext.getStartTimeByClip(this.clip)),this._start}get duration(){var t;return((t=this.clip)==null?void 0:t.duration)??Ke.restPoseClipDuration}get nearestAnimatedRoot(){return this._nearestAnimatedRoot}get clipName(){var t;return((t=this.clip)==null?void 0:t.name)??"rest"}static isDescendantOf(t,i){let n=i;if(!n||!t)return!1;for(;n;){if(!n)return!1;if(n===t)return!0;n=n.parent}return!1}getNearestAnimatedRoot(){var t;let i;try{for(const n of((t=this.clip)==null?void 0:t.tracks)??[]){const o=ga.parseTrackName(n.name);let r=ga.findNode(this.root,o.nodeName);if(r)if(!i)i=r;else{if(r===i||ir.isDescendantOf(i,r))continue;if(!ir.isDescendantOf(r,i)){for(;!ir.isDescendantOf(r,i)&&r.parent;)r=r.parent;ir.isDescendantOf(r,i)||console.error("USDZExporter: Animation clip targets multiple roots that are not parent/child. Please report a bug",this.root,this.clip,i,r)}i=r}}}catch(n){console.error("USDZExporter: Exception when trying to find nearest animated root. Please report a bug",n),i=void 0}return i}}const ip=class{constructor(s,t,i){if(a(this,"clip"),a(this,"pos"),a(this,"rot"),a(this,"scale"),a(this,"root"),a(this,"target"),a(this,"duration",0),a(this,"useRootMotion",!1),this.root=s,this.target=t,this.clip=i,i?this.duration=i.duration:this.duration=ip.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=O.getComponent(s,Pt);n&&(this.useRootMotion=n.applyRootMotion)}addTrack(s){var t,i;if(!this.clip){console.error("This is a rest clip but you're trying to add tracks to it \u2013 this is likely a bug");return}s.name.endsWith("position")?this.pos=s:s.name.endsWith("quaternion")?this.rot=s:s.name.endsWith("scale")?this.scale=s:(s.name.endsWith("activeSelf")?console.warn("[USDZ] Animation of enabled/disabled state is not supported for USDZ export and will NOT be exported: "+s.name+" on "+(((t=this.root)==null?void 0:t.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: "+s.name+" on "+(((i=this.root)==null?void 0:i.name)??this.target.name)+". Only .position, .rotation, .scale are supported."),F()&&we("[USDZ] Some animations can't be exported. See console for details."))}getFrames(){var s,t,i,n,o,r;return this.clip?Math.max(((t=(s=this.pos)==null?void 0:s.times)==null?void 0:t.length)??0,((n=(i=this.rot)==null?void 0:i.times)==null?void 0:n.length)??0,((r=(o=this.scale)==null?void 0:o.times)==null?void 0:r.length)??0):2}getDuration(){return this.duration}getSortedTimesArray(s=!0,t=!0,i=!0){var n,o,r;if(!this.clip)return[0,this.duration];const l=(n=this.pos)==null?void 0:n.times,c=(o=this.rot)==null?void 0:o.times,h=(r=this.scale)==null?void 0:r.times,d=[];if(s&&l)for(const u of l)d.push(u);if(t&&c)for(const u of c)d.push(u);if(i&&h)for(const u of h)d.push(u);return d.includes(0)||d.push(0),d.sort((u,p)=>u-p),[...new Set(d)]}*getValues(s,t=!0,i=!0,n=!0){var o,r,l;const c=new x,h=new V,d=new x(1,1,1),u=this.target,p=t?(o=this.pos)==null?void 0:o.createInterpolant():void 0,g=i?(r=this.rot)==null?void 0:r.createInterpolant():void 0,y=n?(l=this.scale)==null?void 0:l.createInterpolant():void 0;p||c.set(u.position.x,u.position.y,u.position.z),g||h.set(u.quaternion.x,u.quaternion.y,u.quaternion.z,u.quaternion.w),y||d.set(u.scale.x,u.scale.y,u.scale.z),p&&p.valueSize!==3&&(p.valueSize=3),g&&g.valueSize!==4&&(g.valueSize=4),y&&y.valueSize!==3&&(y.valueSize=3);const f=0;for(let v=0-f;v<s.length+f;v++){let b=0,w=0;if(v<0?(b=s[0],w=b-ip.animationDurationPadding/2+1/60):v>=s.length?(b=s[s.length-1],w=b+ip.animationDurationPadding/2-1/60):(b=s[v],w=b),p){const _=p.evaluate(b);c.set(_[0],_[1],_[2])}if(g){const _=g.evaluate(b);h.set(_[0],_[1],_[2],_[3])}if(y){const _=y.evaluate(b);d.set(_[0],_[1],_[2])}if(this.useRootMotion&&u===this.root){const _=new ne;_.compose(c,h,d),_.multiply(u.matrix),_.decompose(c,h,d)}yield{time:w,translation:c,rotation:h,scale:d,index:v}}}};let Ke=ip;a(Ke,"frameRate",60),a(Ke,"animationDurationPadding",6/60),a(Ke,"restPoseClipDuration",6/60);class sp{constructor(t){a(this,"dict",new Map),a(this,"rootTargetMap",new Map),a(this,"rootAndClipToRegisteredAnimationMap",new Map),a(this,"rootToRegisteredClip",new Map),a(this,"lastClipEndTime",0),a(this,"clipToStartTime",new Map),a(this,"clipToHoldClip",new Map),a(this,"serializers",[]),a(this,"injectRestPoses",!1),a(this,"injectImplicitBehaviours",!1),this.injectRestPoses=t,this.injectImplicitBehaviours=t}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}getStartTimeCode(){return!this.injectRestPoses||this.rootAndClipToRegisteredAnimationMap.size===0?0:(Ke.restPoseClipDuration+Ke.animationDurationPadding)*60}getEndTimeCode(){let t=0;for(const[i,n]of this.rootAndClipToRegisteredAnimationMap){const o=n.start+n.duration;o>t&&(t=o)}return t*60}getClipCount(t){var i;return((i=this.rootToRegisteredClip.get(t))==null?void 0:i.length)??0??0}getStartTimeByClip(t){return t?this.clipToStartTime.has(t)?this.clipToStartTime.get(t):(console.error("USDZExporter: Missing start time for clip \u2013 please report a bug.",t),0):0}registerAnimation(t,i){var n;if(!t)return null;this.rootTargetMap.has(t)||this.rootTargetMap.set(t,[]);const o=t.uuid+(i?.uuid??"-rest");if(this.rootAndClipToRegisteredAnimationMap.has(o))return this.rootAndClipToRegisteredAnimationMap.get(o);en&&console.log("registerAnimation",t,i);const r=this.injectRestPoses?1:0,l=(((n=this.rootToRegisteredClip.get(t))==null?void 0:n.length)??0)+r,c=this.rootTargetMap.get(t),h=new Set(c);if(i&&i.tracks)for(const u of i.tracks){const p=ga.parseTrackName(u.name),g=ga.findNode(t,p.nodeName);if(!g){console.warn("no object found for track",u.name,"using "+t.name+" instead");continue}this.dict.has(g)||this.dict.set(g,[]);const y=this.dict.get(g);if(!y){console.warn("no transform data found for target ",g,"at slot "+l+", this is likely a bug");continue}h.delete(g),this.injectRestPoses&&!y[0]&&(console.log("Injecting rest pose",g,i,"at slot",l),y[0]=new Ke(null,g,null));let f=y[l];f||(f=new Ke(t,g,i),y[l]=f),f.addTrack(u),c!=null&&c.includes(g)||c==null||c.push(g)}en&&console.log("Unregistered nodes for this clip",h,"clip",i,"at slot",l,"for root",t,"targets",c);for(const u of h){const p=this.dict.get(u);if(!p)continue;if(this.injectRestPoses&&!p[0]){console.warn("Adding rest pose for ",u,i,"at slot",l,"This is likely a bug, should have been added earlier.");const y=new Ke(null,u,null);p[0]=y}let g=p[l];g||(en&&console.log("Adding padding clip for ",u,i,"at slot",l),g=new Ke(t,u,i),p[l]=g)}const d=new ir(this,t,i);if(this.rootAndClipToRegisteredAnimationMap.set(o,d),en&&console.log({root:t,clip:i,info:d}),i){const u=this.rootToRegisteredClip.get(t);if(u?u.push(i):this.rootToRegisteredClip.set(t,[i]),!this.clipToStartTime.get(i)){this.lastClipEndTime==null&&(this.lastClipEndTime=Ke.restPoseClipDuration);let p=this.lastClipEndTime+Ke.animationDurationPadding,g=p+i.duration;const y=Math.round(p*60)/60,f=Math.round(g*60)/60;Math.abs(y-p)<.01&&(p=y),Math.abs(f-g)<.01&&(g=f),p=Math.ceil(p),g=p+i.duration,this.clipToStartTime.set(i,p),this.lastClipEndTime=g}}return d}onAfterHierarchy(t){en&&console.log("Animation clips per animation target node",this.dict)}onAfterBuildDocument(t){var i,n;en&&console.log("Animation data",{dict:this.dict,rootTargetMap:this.rootTargetMap,rootToRegisteredClip:this.rootToRegisteredClip});for(const o of this.rootTargetMap.keys()){const r=this.rootTargetMap.get(o);if(!r)continue;let l;const c=[];for(const h of r){const d=this.dict.get(h);if(!d){console.error("No data found for target on USDZ export \u2013 please report a bug!",h);continue}l===void 0&&(l=d?.length),l!==d?.length&&console.error("Different array lengths for targets \u2013 please report a bug!",d);for(let u=0;u<d.length;u++){let p=d[u];if(!p){const y=u-(this.injectRestPoses?1:0);d[u]=new Ke(null,h,this.rootToRegisteredClip.get(o)[y]),p=d[u]}const g=p.getDuration();if(c[u]===void 0)c[u]=g;else if(c[u]!==g){console.error("Error during UDSZ export: Encountered different animation durations for animated targets. Please report a bug!",{datas:d,target:h}),c[u]=g;continue}}}}for(const o of this.serializers){const r=(i=o.model)==null?void 0:i.parent,l=r?.isDynamic===!0;n0&&console.log(l,(n=o.model)==null?void 0:n.parent),l&&o.registerCallback(r)}}onExportObject(t,i,n){O.foreachComponent(t,r=>{const l=r;typeof l.createAnimation=="function"&&l.createAnimation(this,i,n)},!1);const o=new pT(t,this);this.serializers.push(o),o.registerCallback(i)}}class pT{constructor(t,i){a(this,"model"),a(this,"object"),a(this,"animationData"),a(this,"ext"),a(this,"callback"),this.object=t,this.animationData=i.animationData,this.ext=i}registerCallback(t){this.model&&this.callback&&this.model.removeEventListener("serialize",this.callback),this.callback||(this.callback=this.onSerialize.bind(this)),n0&&console.log("REPARENT",t),this.model=t,this.callback&&this.model.addEventListener("serialize",this.callback)}skinnedMeshExport(t,i,n){var o;const r=this.model,l=this.animationData;if(r&&r.skinnedMesh){let c=function(E){const z=[];for(const[H,ie]of E){let oe=`${H} : [`;const de=[];for(const pe of ie)de.push(`(${he(pe.x)}, ${he(pe.y)}, ${he(pe.z)})`);oe=oe.concat(de.join(", ")),oe=oe.concat("],"),z.push(oe)}return z},h=function(E){const z=[];for(const[H,ie]of E){let oe=`${H} : [`;const de=[];for(const pe of ie)de.push(`(${he(pe.w)}, ${he(pe.x)}, ${he(pe.y)}, ${he(pe.z)})`);oe=oe.concat(de.join(", ")),oe=oe.concat("],"),z.push(oe)}return z},d=function(E){let z,H=!0;const ie=new Map;for(const[de,pe]of E){z===void 0&&(z=pe.length),z!==pe.length&&(H=!1);let Xe=0;for(const Qe of pe)Xe++,Qe||(ie.has(de)||ie.set(de,[]),ie.get(de).push(Xe))}en&&console.log("Bone count: ",E.size,"TransformData entries per bone: ",z,"Undefined bone entries: ",ie),console.assert(H,"All bones should have the same number of TransformData entries",E),console.assert(ie.size===0,"All TransformData entries should be set",ie);const oe=[];for(const[de,pe]of E)for(let Xe=0;Xe<pe.length;Xe++){const Qe=pe[Xe],hs=n.getStartTimeByClip(Qe.clip);oe.length<=Xe&&oe.push({pos:[],rot:[],scale:[],timeOffset:hs});const ds=oe[Xe];ds.pos.push(...Qe.getSortedTimesArray(!0,!1,!1)),ds.rot.push(...Qe.getSortedTimesArray(!1,!0,!1)),ds.scale.push(...Qe.getSortedTimesArray(!1,!1,!0))}for(const de of oe)de.pos.sort((pe,Xe)=>pe-Xe),de.rot.sort((pe,Xe)=>pe-Xe),de.scale.sort((pe,Xe)=>pe-Xe),de.pos=[...new Set(de.pos)],de.rot=[...new Set(de.rot)],de.scale=[...new Set(de.scale)];return oe},u=function(E,z,H){const ie=new Map,oe=new Map,de=new Map,pe=z.length;for(const Xe of H){const Qe=E.get(Xe);let hs;Qe?console.assert(Qe.length===pe,"We should have the same number of TransformData entries for each bone",Qe,z):hs=new Ke(null,Xe,null);for(let ds=0;ds<pe;ds++){const Vl=Qe?Qe[ds]:hs,ua=z[ds];for(const{time:Hl,translation:$l}of Vl.getValues(ua.pos,!0,!1,!1)){const us=(Hl+ua.timeOffset)*60;ie.has(us)||ie.set(us,new Array),ie.get(us).push($l.clone())}for(const{time:Hl,rotation:$l}of Vl.getValues(ua.rot,!1,!0,!1)){const us=(Hl+ua.timeOffset)*60;oe.has(us)||oe.set(us,new Array),oe.get(us).push($l.clone())}for(const{time:Hl,scale:$l}of Vl.getValues(ua.scale,!1,!1,!0)){const us=(Hl+ua.timeOffset)*60;de.has(us)||de.set(us,new Array),de.get(us).push($l.clone())}}}return{position:ie.size==0?void 0:ie,quaternion:oe.size==0?void 0:oe,scale:de.size==0?void 0:de}},p=function(E){const z=[];for(const H of E)z.push(`(${he(H.x)}, ${he(H.y)}, ${he(H.z)})`);return z.join(", ")},g=function(E){const z=[];for(const H of E)z.push(`(${he(H.w)}, ${he(H.x)}, ${he(H.y)}, ${he(H.z)})`);return z.join(", ")},y=function(E){const z=new Map;if(en){const H=new Array;for(const[ie,oe]of l)H.push(ie.uuid+": "+oe.length+" "+oe.map(de=>{var pe;return(pe=de.clip)==null?void 0:pe.uuid.substring(0,6)}).join(" "));console.log(`getPerBoneTransformData
1198
1202
  `+H.join(`
1199
- `))}for(const H of E){const ie=l.get(H);ie&&z.set(H,ie)}return z},f=function(E){const z=y(E),H=d(z);return u(z,H,E)};const v=r.skinnedMesh.skeleton,b=new Array,w=[],_=[];for(const E of v.bones){w.push(E),_.push(E.uuid);const z=v.boneInverses[v.bones.indexOf(E)];b.push({bone:E,inverse:z})}let S=1e4;for(;_.length<v.bones.length&&S-- >0;)for(const E of w){const z=E.children;for(const H of z)if(_.indexOf(H.uuid)===-1&&v.bones.indexOf(H)!==-1){w.push(H),_.push(H.uuid);const ie=v.boneInverses[v.bones.indexOf(H)];b.push({bone:H,inverse:ie})}}S<=0&&console.error("Failed to sort bones in skinned mesh",r.skinnedMesh,v.bones,_);for(const E of bx(v.bones))b.push({bone:E,inverse:E.matrixWorld.clone().invert()});const R=b[0].bone.parent;R||console.error("No bone parent found for skinned mesh during USDZ export",r.skinnedMesh),b.sort((E,z)=>hl(E.bone,R)>hl(z.bone,R)?1:-1);const M=i.quickLookCompatible,T=[],j=[],L=[],U=[];for(const{bone:E}of b){if(M){const z=E.scale;z.x==0&&(z.x=1e-5),z.y==0&&(z.y=1e-5),z.z==0&&(z.z=1e-5),T.push(new ne().compose(E.position,E.quaternion,E.scale))}else T.push(E.matrix.clone());j.push(E.position),L.push(E.quaternion),U.push(E.scale)}const B=b.map(E=>'"'+hl(E.bone,R)+'"').join(", "),Q=b.map(E=>Tx(E.inverse.clone().invert())).join(", ");t.beginBlock('def Skeleton "Rig"'),t.appendLine(`uniform matrix4d[] bindTransforms = [${Q}]`),t.appendLine(`uniform token[] joints = [${B}]`),t.appendLine('uniform token purpose = "guide"'),t.appendLine(`uniform matrix4d[] restTransforms = [${T.map(E=>Tx(E)).join(", ")}]`);const $=f(b.map(E=>E.bone));if(en){let E=1e7,z=0;for(const H of((o=$.position)==null?void 0:o.keys())??[])E=Math.min(E,H),z=Math.max(z,H);console.log("Time samples",E,z,$)}if(t.beginBlock('def SkelAnimation "_anim"'),t.appendLine(`uniform token[] joints = [${B}]`),t.appendLine(`quatf[] rotations = [${g(L)}]`),$&&$.quaternion){t.beginBlock("quatf[] rotations.timeSamples = {","");const E=h($.quaternion);for(const z of E)t.appendLine(z);t.closeBlock()}if(t.appendLine(`half3[] scales = [${p(U)}]`),$&&$.scale){t.beginBlock("half3[] scales.timeSamples = {","");const E=c($.scale);for(const z of E)t.appendLine(z);t.closeBlock()}if(t.appendLine(`float3[] translations = [${p(j)}]`),$&&$.position){t.beginBlock("float3[] translations.timeSamples = {","");const E=c($.position);for(const z of E)t.appendLine(z);t.closeBlock()}t.closeBlock(),t.closeBlock()}}onSerialize(t,i){if(!this.model)return;const n=this.animationData.get(this.object);if(n)for(let u=0;u<n.length;u++)n[u]===void 0&&(n[u]=new Ke(null,this.object,null));const o=this.ext;this.skinnedMeshExport(t,i,o);const r=this.object,l=this.model,c=this.animationData.get(r);if(!c||r.isSkinnedMesh)return;n0&&console.log("SERIALIZE",this.model.name,this.object.type,c);const h=Intl.NumberFormat("en-US",{maximumFractionDigits:3,minimumFractionDigits:0,useGrouping:!1});function d(u,p){var g;if(u.some(y=>y&&{position:y.pos,rotation:y.rot,scale:y.scale}[p])){switch(p){case"position":l.needsTranslate=!0,t.beginBlock("double3 xformOp:translate.timeSamples = {","");break;case"rotation":l.needsOrient=!0,t.beginBlock("quatf xformOp:orient.timeSamples = {","");break;case"scale":l.needsScale=!0,t.beginBlock("double3 xformOp:scale.timeSamples = {","");break}for(let y=0;y<u.length;y++){const f=u[y];if(!f)continue;const v=o.getStartTimeByClip(f.clip),b=f.getSortedTimesArray(p==="position",p==="rotation",p==="scale");if(!b||b.length===0){console.error("got an animated object but no time values?",r,f);continue}const w=!f.clip,_=p==="position"&&(f.pos||w),S=p==="rotation"&&(f.rot||w),R=p==="scale"&&(f.scale||w);if(_||S||R){const M=((g=f.clip)==null?void 0:g.name)??"rest",T=f.getDuration();en&&console.log("Write .timeSamples:",M,v,T,u),t.appendLine("# "+M+": start="+h.format(v*Ke.frameRate)+", length="+h.format(T*Ke.frameRate)+", frames="+f.getFrames())}if(_)for(const{time:M,translation:T}of f.getValues(b,!0,!1,!1)){const j=`${h.format((v+M)*Ke.frameRate)}: (${he(T.x)}, ${he(T.y)}, ${he(T.z)}),`;t.appendLine(j)}if(S)for(const{time:M,rotation:T}of f.getValues(b,!1,!0,!1)){const j=`${h.format((v+M)*Ke.frameRate)}: (${he(T.w)}, ${he(T.x)}, ${he(T.y)}, ${he(T.z)}),`;t.appendLine(j)}if(R)for(const{time:M,scale:T}of f.getValues(b,!1,!1,!0)){const j=`${h.format((v+M)*Ke.frameRate)}: (${he(T.x)}, ${he(T.y)}, ${he(T.z)}),`;t.appendLine(j)}}t.closeBlock()}}d(c,"position"),d(c,"rotation"),d(c,"scale")}}const mT=C("debugusdz");class da{constructor(){a(this,"files",new Array)}static getName(t){var i;const n=t.split(".").pop();let o=(i=t.split(".").slice(0,-1).join(".").split("/").pop())==null?void 0:i.replace(".","_");return o||(o="Audio_"+Math.random().toString(36).substring(2,15)),Rs(o)+"."+n}get extensionName(){return"Audio"}onExportObject(t,i,n){const o=O.getComponents(t,Ne);if(o.length)for(const r of o){if(!r.clip||typeof r.clip!="string"||!r.playOnAwake)continue;const l=r.clip.split("/").pop()||"Audio",c=da.getName(r.clip),h=Rs(c);if(!this.files.some(d=>d.path===r.clip)){this.files.push({path:r.clip,name:c});const d=c.toLowerCase();n.quickLookCompatible&&!d.endsWith(".mp3")&&!d.endsWith(".wav")&&!d.endsWith(".m4a")&&console.error("Audio file "+r.clip+" from "+r.name+" is not an MP3 or WAV file. QuickLook may not support playing it.")}n.quickLookCompatible||i.addEventListener("serialize",(d,u)=>{d.appendLine(),d.beginBlock(`def SpatialAudio "${h}"`,"(",!1),d.appendLine(`displayName = "${l}"`),d.closeBlock(")"),d.beginBlock(),d.appendLine(`uniform asset filePath = @audio/${c}@`),d.appendLine(`uniform token auralMode = "${r.spatialBlend>0?"spatial":"nonSpatial"}"`),d.appendLine(`uniform token playbackMode = "${r.loop?"loopFromStage":"onceFromStart"}"`),d.appendLine(`uniform float gain = ${r.volume}`),d.closeBlock()})}}async onAfterSerialize(t){for(const i of this.files){const n="audio/"+i.name;if(t.files[n]){mT&&console.warn("Audio file with name "+n+" already exists in the context. Skipping.");continue}const o=await(await(await fetch(i.path)).blob()).arrayBuffer(),r=new Uint8Array(o);t.files[n]=r}}}var gT=Object.defineProperty,fT=Object.getOwnPropertyDescriptor,Ve=(s,t,i,n)=>{for(var o=n>1?void 0:n?fT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&gT(t,i,o),o};const Ux=C("debugusdzbehaviours");function nh(s){s&&(s.getComponentInParent(Wa)||(F()&&console.debug('Raycaster on "'+s.name+'" was automatically added, because no raycaster was found in the parent hierarchy.'),s.addComponent(Ei)))}class Dr extends A{constructor(){super(...arguments),a(this,"object"),a(this,"target"),a(this,"duration",1),a(this,"relativeMotion",!1),a(this,"coroutine",null),a(this,"targetPos",new x),a(this,"targetRot",new V),a(this,"targetScale",new x)}start(){nh(this.gameObject)}onPointerClick(t){t.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 t=te(this.object).clone(),i=te(this.target).clone(),n=Ce(this.object).clone(),o=Ce(this.target).clone(),r=Ye(this.object).clone(),l=Ye(this.target).clone(),c=t.distanceTo(i),h=n.angleTo(o),d=r.distanceTo(l);if(c<.01&&h<.01&&d<.01){ht(this.object,i),Hi(this.object,o),wa(this.object,l),this.coroutine=null;return}let u=0,p=0;for(;u<1;)u+=this.context.time.deltaTime/this.duration,u>1&&(u=1),p=u<.5?4*u*u*u:1-Math.pow(-2*u+2,3)/2,this.targetPos.lerpVectors(t,i,p),this.targetRot.slerpQuaternions(n,o,p),this.targetScale.lerpVectors(r,l,p),ht(this.object,this.targetPos),Hi(this.object,this.targetRot),wa(this.object,this.targetScale),yield;this.coroutine=null}*moveRelative(){if(!this.target||!this.object)return;const t=this.object.position.clone(),i=this.object.quaternion.clone(),n=this.object.scale.clone(),o=this.target.position.clone(),r=this.target.quaternion.clone(),l=this.target.scale.clone();o.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(o),this.targetRot.copy(this.object.quaternion).multiply(r),this.targetScale.copy(this.object.scale).multiply(l);let c=0,h=0;for(;c<1;)c+=this.context.time.deltaTime/this.duration,c>1&&(c=1),h=c<.5?4*c*c*c:1-Math.pow(-2*c+2,3)/2,this.object.position.lerpVectors(t,this.targetPos,h),this.object.quaternion.slerpQuaternions(i,this.targetRot,h),this.object.scale.lerpVectors(n,this.targetScale,h),yield;this.coroutine=null}beforeCreateDocument(t){var i;if(this.target&&this.object&&this.gameObject){const n=new Nt("Move to "+((i=this.target)==null?void 0:i.name),Rt.tapTrigger(this.gameObject),ve.transformAction(this.object,this.target,this.duration,this.relativeMotion?"relative":"absolute"));t.addBehavior(n)}}}Ve([m(I)],Dr.prototype,"object",2),Ve([m(I)],Dr.prototype,"target",2),Ve([m()],Dr.prototype,"duration",2),Ve([m()],Dr.prototype,"relativeMotion",2);var ul;const Jt=(ul=class extends A{constructor(){super(...arguments),a(this,"materialToSwitch"),a(this,"variantMaterial"),a(this,"fadeDuration",0),a(this,"_objectsWithThisMaterial",null),a(this,"selfModel"),a(this,"targetModels")}start(){var s;this._objectsWithThisMaterial=this.objectsWithThisMaterial,nh(this.gameObject),F()&&this._objectsWithThisMaterial.length<=0&&console.warn('ChangeMaterialOnClick: No objects found with material "'+((s=this.materialToSwitch)==null?void 0:s.name)+'"')}onPointerEnter(s){this.context.input.setCursor("pointer")}onPointerExit(s){this.context.input.unsetCursor("pointer")}onPointerClick(s){if(s.use(),!!this.variantMaterial)for(let t=0;t<this.objectsWithThisMaterial.length;t++){const i=this.objectsWithThisMaterial[t];i.material=this.variantMaterial}}get objectsWithThisMaterial(){return this._objectsWithThisMaterial!=null?this._objectsWithThisMaterial:(this._objectsWithThisMaterial=[],this.variantMaterial&&this.materialToSwitch&&this.context.scene.traverse(s=>{if(s instanceof Y)if(Array.isArray(s.material)){for(const t of s.material)if(t===this.materialToSwitch){this.objectsWithThisMaterial.push(s);break}}else s.material===this.materialToSwitch?this.objectsWithThisMaterial.push(s):p_(s.material,this.materialToSwitch)&&this.objectsWithThisMaterial.push(s)}),this._objectsWithThisMaterial)}async beforeCreateDocument(s,t){this.targetModels=[],Jt._materialTriggersPerId={},Jt.variantSwitchIndex=0,this.materialToSwitch&&await it.assignTextureLOD(this.materialToSwitch,0),this.variantMaterial&&await it.assignTextureLOD(this.variantMaterial,0)}createBehaviours(s,t,i){this.objectsWithThisMaterial.find(n=>n.uuid===t.uuid)&&this.targetModels.push(t),this.gameObject.uuid===t.uuid&&(this.selfModel=t,this.materialToSwitch&&(Jt._materialTriggersPerId[this.materialToSwitch.uuid]||(Jt._materialTriggersPerId[this.materialToSwitch.uuid]=[]),Jt._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(s,t){if(!this.materialToSwitch)return;const i=Jt._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 l in n)l!==o.selfModel.uuid&&r.push(...n[l]);o.createAndAttachBehaviors(s,n[o.selfModel.uuid],r)}}delete Jt._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(s,t,i){const n=[],o=Math.max(0,this.fadeDuration);n.push(ve.fadeAction([...this.targetModels,...i],o,!1)),n.push(ve.fadeAction(t,o,!0)),s.addBehavior(new Nt("Select_"+this.selfModel.name,Rt.tapTrigger(this.selfModel),ve.parallel(...n))),Jt._parallelStartHiddenActions.push(...t),Jt._startHiddenBehaviour||(Jt._startHiddenBehaviour=new Nt("StartHidden_"+this.selfModel.name,Rt.sceneStartTrigger(),ve.fadeAction(Jt._parallelStartHiddenActions,o,!1)),s.addBehavior(Jt._startHiddenBehaviour))}static getMaterialName(s){return Rs(s.name||"Material")+"_"+s.id}createVariants(){if(!this.variantMaterial)return null;const s=[];for(const t of this.targetModels){const i=t.clone();i.name+="_Variant_"+Jt.variantSwitchIndex+++"_"+Jt.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())&&Yt.createEmptyParent(t),t.parent&&t.parent.add(i),s.push(i)}return s}},a(ul,"_materialTriggersPerId",{}),a(ul,"_startHiddenBehaviour",null),a(ul,"_parallelStartHiddenActions",[]),a(ul,"variantSwitchIndex",0),ul);let pl=Jt;Ve([m(ke)],pl.prototype,"materialToSwitch",2),Ve([m(ke)],pl.prototype,"variantMaterial",2),Ve([m()],pl.prototype,"fadeDuration",2);var ml;const He=(ml=class extends A{constructor(){super(...arguments),a(this,"target"),a(this,"toggleOnClick",!1),a(this,"targetState",!0),a(this,"hideSelf",!0),a(this,"selfModel"),a(this,"selfModelClone"),a(this,"targetModel"),a(this,"toggleModel"),a(this,"stateBeforeCreatingDocument",!1),a(this,"targetStateBeforeCreatingDocument",!1)}start(){nh(this.gameObject)}onPointerClick(s){s.use(),!this.toggleOnClick&&this.hideSelf&&(this.gameObject.visible=!1),this.target&&(this.target.visible=this.toggleOnClick?!this.target.visible:this.targetState)}createBehaviours(s,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t,this.selfModelClone=t.clone())}beforeCreateDocument(){this.target&&(this.gameObject[He.wasVisible]===void 0&&(this.gameObject[He.wasVisible]=this.gameObject.activeSelf),this.target[He.wasVisible]===void 0&&(this.target[He.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[He.wasVisible],this.targetStateBeforeCreatingDocument=this.target[He.wasVisible],this.gameObject.visible=!0,this.target.visible=!0)}afterCreateDocument(s,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())&&Gf.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[He.toggleClone]){const c=this.selfModelClone.clone();c.setMatrix(new ne),c.name+="_toggle"+He.clonedToggleIndex++,i.add(c),this.gameObject[He.toggleClone]=c,console.warn("USDZExport: Toggle "+this.gameObject.name+" doesn't have geometry. It will be deep cloned and nested behaviours will likely not work.")}const l=this.gameObject[He.toggleClone];if(!this.gameObject[He.reverseToggleClone]){const c=this.selfModelClone.clone();c.setMatrix(new ne),c.name+="_toggleReverse"+He.clonedToggleIndex++,i.add(c),this.gameObject[He.reverseToggleClone]=c}this.toggleModel=this.gameObject[He.reverseToggleClone],(!this.toggleModel.geometry||!l.geometry)&&console.error("triggers without childs and without geometry won't work!",this,i.geometry),n=l,i.geometry=null,i.material=null}if(this.toggleModel){if(this.toggleOnClick){const l=[];l.push(ve.fadeAction(n,0,!1)),l.push(ve.fadeAction(this.toggleModel,0,!0)),l.push(ve.fadeAction(this.targetModel,0,o)),s.addBehavior(new Nt("Toggle_"+n.name+"_ToggleTo"+(o?"On":"Off"),Rt.tapTrigger(n),ve.parallel(...l)));const c=[];c.push(ve.fadeAction(this.toggleModel,0,!1)),c.push(ve.fadeAction(n,0,!0)),c.push(ve.fadeAction(this.targetModel,0,!o)),s.addBehavior(new Nt("Toggle_"+n.name+"_ToggleTo"+(o?"Off":"On"),Rt.tapTrigger(this.toggleModel),ve.parallel(...c)))}}else{const l=[];this.hideSelf&&l.push(ve.fadeAction(n,0,!1)),l.push(ve.fadeAction(this.targetModel,0,o)),s.addBehavior(new Nt("Toggle_"+n.name+"_ToggleTo"+(o?"On":"Off"),Rt.tapTrigger(n),l.length>1?ve.parallel(...l):l[0]))}const r=new Array;this.targetStateBeforeCreatingDocument||r.push(this.targetModel),this.stateBeforeCreatingDocument||r.push(i),this.toggleModel&&r.push(this.toggleModel),gl.add(r,s)}}afterSerialize(s,t){this.gameObject[He.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[He.wasVisible],delete this.gameObject[He.wasVisible]),this.target&&this.target[He.wasVisible]!==void 0&&(this.target.visible=this.target[He.wasVisible],delete this.target[He.wasVisible]),delete this.gameObject[He.toggleClone],delete this.gameObject[He.reverseToggleClone]}},a(ml,"clonedToggleIndex",0),a(ml,"wasVisible",Symbol("usdz_SetActiveOnClick_wasVisible")),a(ml,"toggleClone",Symbol("clone for toggling")),a(ml,"reverseToggleClone",Symbol("clone for reverse toggling")),ml);let Br=He;Ve([m(I)],Br.prototype,"target",2),Ve([m()],Br.prototype,"toggleOnClick",2),Ve([m()],Br.prototype,"targetState",2),Ve([m()],Br.prototype,"hideSelf",2);const Ao=class extends A{constructor(){super(...arguments),a(this,"wasVisible",!1)}static add(s,t){const i=Array.isArray(s)?s:[s];for(const n of i)Ao._fadeObjects.includes(n)||(console.log("adding hide on start",n),Ao._fadeObjects.push(n));Ao._fadeBehaviour===void 0&&(Ao._fadeBehaviour=new Nt("HideOnStart",Rt.sceneStartTrigger(),ve.fadeAction(Ao._fadeObjects,0,!1)),t.addBehavior(Ao._fadeBehaviour))}start(){O.setActive(this.gameObject,!1)}createBehaviours(s,t,i){t.uuid===this.gameObject.uuid&&(this.wasVisible||Ao.add(t,s))}beforeCreateDocument(){this.wasVisible=O.isActiveSelf(this.gameObject)}};let gl=Ao;a(gl,"_fadeBehaviour"),a(gl,"_fadeObjects",[]);class fl extends A{constructor(){super(...arguments),a(this,"target"),a(this,"duration",.5),a(this,"motionType","bounce")}beforeCreateDocument(){}createBehaviours(t,i,n){if(this.target&&i.uuid===this.gameObject.uuid){const o=new Nt("emphasize "+this.name,Rt.tapTrigger(this.gameObject),ve.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));t.addBehavior(o)}}afterCreateDocument(t,i){}}Ve([m()],fl.prototype,"target",2),Ve([m()],fl.prototype,"duration",2),Ve([m()],fl.prototype,"motionType",2);class Io extends A{constructor(){super(...arguments),a(this,"target"),a(this,"clip",""),a(this,"toggleOnClick",!1),a(this,"trigger","tap")}start(){nh(this.gameObject)}ensureAudioSource(){if(!this.target){const t=this.gameObject.addComponent(Ne);t&&(this.target=t,t.spatialBlend=1,t.volume=1,t.loop=!1,t.preload=!0)}}onPointerClick(t){var i;t.use(),!(!((i=this.target)!=null&&i.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(t,i,n){if(!(!this.target&&!this.clip)&&i.uuid===this.gameObject.uuid){const o=this.clip?this.clip:this.target?this.target.clip:void 0;if(!o||typeof o!="string")return;const r=this.target?this.target.gameObject:this.gameObject;da.getName(o);const l=this.target?this.target.volume:1,c=this.target&&this.target.spatialBlend==0?"nonSpatial":"spatial";let h=!1;this.gameObject.traverse(g=>{g instanceof Y&&g.visible&&(h=!0)}),h=!0;const d=t.addAudioClip(o);let u=ve.playAudioAction(r,d,"play",l,c);this.target&&this.target.loop&&(u=ve.sequence(u).makeLooping());const p=this.name?"_"+this.name:"";if(h&&this.trigger==="tap"){this.toggleOnClick&&(u.multiplePerformOperation="stop");const g=new Nt("playAudio"+p,Rt.tapTrigger(i),u);t.addBehavior(g)}if(this.target&&this.target.playOnAwake&&this.target.enabled)if(h&&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 g=new Nt("playAudioOnStart"+p,Rt.sceneStartTrigger(),u);t.addBehavior(g)}}}}Ve([m(Ne)],Io.prototype,"target",2),Ve([m(URL)],Io.prototype,"clip",2),Ve([m()],Io.prototype,"toggleOnClick",2);var np;const tn=(np=class extends A{constructor(){super(...arguments),a(this,"animator"),a(this,"stateName"),a(this,"trigger","tap"),a(this,"animation"),a(this,"selfModel"),a(this,"stateAnimationModel"),a(this,"animationSequence",new Array),a(this,"animationLoopAfterSequence",new Array),a(this,"randomOffsetNormalized",0)}get target(){var s,t;return((s=this.animator)==null?void 0:s.gameObject)||((t=this.animation)==null?void 0:t.gameObject)}start(){nh(this.gameObject)}onPointerClick(s){var t;s.use(),this.target&&this.stateName&&((t=this.animator)==null||t.play(this.stateName,0,0,.1))}createBehaviours(s,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t)}afterSerialize(){if(tn.rootsWithExclusivePlayback.size>1){const s='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.';F()&&we(s),console.warn(s,...tn.rootsWithExclusivePlayback)}tn.animationActions=[],tn.rootsWithExclusivePlayback=new Set}afterCreateDocument(s,t){if(this.animationSequence===void 0&&this.animationLoopAfterSequence===void 0||!this.stateAnimationModel||!this.target)return;const i=t.document,n=t.extensions.find(l=>l instanceof sp);if(!n)return;const o=n.getClipCount(this.target)>1;o&&(F()&&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."),tn.rootsWithExclusivePlayback.add(this.target));const r=this.name?this.name:"";i.traverse(l=>{var c,h;if(l.uuid===((c=this.target)==null?void 0:c.uuid)){const d=tn.getActionForSequences(i,l,this.animationSequence,this.animationLoopAfterSequence,this.randomOffsetNormalized),u=new Nt(this.trigger+"_"+r+"_toPlayAnimation_"+this.stateName+"_on_"+((h=this.target)==null?void 0:h.name),this.trigger=="tap"?Rt.tapTrigger(this.selfModel):Rt.sceneStartTrigger(),d);o&&u.makeExclusive(!0),s.addBehavior(u)}})}static getActionForSequences(s,t,i,n,o){const r=(c,h)=>{let d=tn.animationActions.find(u=>u.affectedObjects==c&&u.start==h.start&&u.duration==h.duration&&u.animationSpeed==h.speed);return d||(d=ve.startAnimationAction(c,h),tn.animationActions.push(d)),d},l=ve.sequence();if(i&&i.length>0)for(const c of i)l.addAction(r(t,c));if(n&&n.length>0){const c=l.actions.length==0?l:ve.sequence();for(const h of n)c.addAction(r(t,h));c.makeLooping(),l!==c&&l.addAction(c)}return o&&o>0&&l.actions.unshift(ve.waitAction(o)),l}static getAndRegisterAnimationSequences(s,t,i){var n,o,r,l,c,h,d,u;if(!t)return;const p=t.getComponent(Pt),g=t.getComponent(zt);if(!p&&!g)return;if(p&&!i)throw new Error("PlayAnimationOnClick: No stateName specified for animator "+p.name+" on "+t.name);let y=[],f=[];if(g){const M=s.registerAnimation(t,g.clip);M&&(g.loop?f.push(M):y.push(M));let T=0;if(g.minMaxOffsetNormalized){const j=g.minMaxOffsetNormalized.x,L=g.minMaxOffsetNormalized.y;T=(((n=g.clip)==null?void 0:n.duration)||1)*(j+Math.random()*(L-j))}return{animationSequence:y,animationLoopAfterSequence:f,randomTimeOffset:T}}const v=p?.runtimeAnimatorController;let b=v?.findState(i),w=[],_=[];if(v&&b){const M=new Array;M.push(b);let T=!1;for(;M.length<100;){if(!b||b===null||!b.transitions||b.transitions.length===0){(o=b.motion)!=null&&o.isLooping&&(T=!0);break}const j=b.transitions.find(U=>U.conditions.length===0),L=j?v.getState(j.destinationState,0):null;if(L&&M.includes(L)){b=L,T=!0;break}else if(j){if(b=L,!b)break;M.push(b)}else{T=((r=b.motion)==null?void 0:r.isLooping)??!1;break}}if(T&&b){const j=M.indexOf(b);w=M.slice(0,j),_=M.slice(j),Ux&&console.log("found loop from "+i,"states until loop",w,"states looping",_)}else w=M,_=[],Ux&&console.log("found no loop from "+i,"states",w);if(!_.length){const j=w[w.length-1],L=(l=j.motion)==null?void 0:l.clip;if(L){let U;if(s.holdClipMap.has(L))U=s.holdClipMap.get(L);else{const B=j.name+"_hold";U=L.clone(),U.duration=1,U.name=B;const Q=L.duration;U.tracks=L.tracks.map($=>{const E=$.clone();E.times=new Float32Array([0,Q]);const z=$.values.length,H=$.getValueSize(),ie=$.values.slice(z-H,z);return E.values=new Float32Array(2*H),E.values.set(ie,0),E.values.set(ie,H),E}),U.name=B,s.holdClipMap.set(L,U)}if(U){const B={name:U.name,motion:{clip:U,isLooping:!1,name:U.name},speed:1,transitions:[],behaviours:[],hash:j.hash+1};_.push(B)}}}}if(w.length===1&&(!((c=w[0].motion)!=null&&c.clip)||((d=(h=w[0].motion)==null?void 0:h.clip.tracks)==null?void 0:d.length)===0)){y=new Array;const M=s.registerAnimation(t,null);M&&y.push(M);return}if(w=w.filter(M=>{var T,j,L;return((T=M.motion)==null?void 0:T.clip)&&((L=(j=M.motion)==null?void 0:j.clip.tracks)==null?void 0:L.length)>0}),_=_.filter(M=>{var T,j,L;return((T=M.motion)==null?void 0:T.clip)&&((L=(j=M.motion)==null?void 0:j.clip.tracks)==null?void 0:L.length)>0}),w.length===0&&_.length===0){console.warn("No clips found for state "+i+" on "+p?.name+", can't export animation data");return}const S=(M,T)=>{if(!t)return;const j=s.registerAnimation(t,M.motion.clip??null);j?(j.speed=M.speed,T.push(j)):console.warn("Couldn't register animation for state "+M.name+" on "+p?.name)};if(w.length>0){y=new Array;for(const M of w)S(M,y)}if(_.length>0){f=new Array;for(const M of _)S(M,f)}let R=0;if(p&&v&&p.minMaxOffsetNormalized){const M=p.minMaxOffsetNormalized.x,T=p.minMaxOffsetNormalized.y,j=w.length?w[0]:_.length?_[0]:null;R=(((u=j?.motion.clip)==null?void 0:u.duration)||1)*(M+Math.random()*(T-M))}return{animationSequence:y,animationLoopAfterSequence:f,randomTimeOffset:R}}createAnimation(s,t,i){if(!this.target||!this.animator&&!this.animation)return;const n=tn.getAndRegisterAnimationSequences(s,this.target,this.stateName);n&&(this.animationSequence=n.animationSequence,this.animationLoopAfterSequence=n.animationLoopAfterSequence,this.randomOffsetNormalized=n.randomTimeOffset,this.stateAnimationModel=t)}},a(np,"animationActions",[]),a(np,"rootsWithExclusivePlayback",new Set),np);let Fr=tn;Ve([m(Pt)],Fr.prototype,"animator",2),Ve([m()],Fr.prototype,"stateName",2);class yl extends A{constructor(){super(...arguments),a(this,"target")}getType(){}getDuration(){}}Ve([m(I)],yl.prototype,"target",2);class oh extends A{constructor(){super(...arguments),a(this,"target")}}Ve([m(yl)],oh.prototype,"target",2);class rh extends yl{constructor(){super(...arguments),a(this,"type",1),a(this,"duration",1)}getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}Ve([m()],rh.prototype,"type",2),Ve([m()],rh.prototype,"duration",2);class o0 extends oh{}const Nx=class{constructor(){a(this,"_quicklookButton"),a(this,"_arButton"),a(this,"_vrButton"),a(this,"_sendToQuestButton")}static create(){return new Nx}static getOrCreate(){return this._instance||(this._instance=this.create()),this._instance}get isSecureConnection(){return window.location.protocol==="https:"}get quicklookButton(){return this._quicklookButton}get arButton(){return this._arButton}get vrButton(){return this._vrButton}get sendToQuestButton(){return this._sendToQuestButton}get qrButton(){return kn.getOrCreate().createQRCode()}createQuicklookButton(){if(this._quicklookButton)return this._quicklookButton;const s=document.createElement("button");this._quicklookButton=s,s.dataset.needle="quicklook-button";const t=X.supportsQuickLookAR();s.innerText="View in AR",s.prepend(Ot("view_in_ar"));let i=!1,n=null;return s.addEventListener("click",()=>{n=kc($e),n||(i=!0,n=new $e),i&&(n.objectToExport=ee.Current.scene),n?(s.classList.add("this-mode-is-requested"),n.exportAndOpen().then(()=>{s.classList.remove("this-mode-is-requested")}).catch(o=>{s.classList.remove("this-mode-is-requested"),console.error(o)})):console.warn("No USDZExporter component found in the scene")}),this.hideElementDuringXRSession(s),s}createARButton(s){var t;if(this._arButton)return this._arButton;const i="immersive-ar",n=document.createElement("button");return this._arButton=n,n.classList.add("webxr-button"),n.dataset.needle="webxr-ar-button",n.innerText="Enter AR",n.prepend(Ot("view_in_ar")),n.title="Click to start an AR session",n.addEventListener("click",()=>J.start(i,s)),this.updateSessionSupported(n,i),this.listenToXRSessionState(n,i),this.hideElementDuringXRSession(n),this.isSecureConnection||(n.disabled=!0,n.title="WebXR requires a secure connection (HTTPS)"),X.isMozillaXR()||(t=navigator.xr)==null||t.addEventListener("devicechange",()=>this.updateSessionSupported(n,i)),n}createVRButton(s){var t;if(this._vrButton)return this._vrButton;const i="immersive-vr",n=document.createElement("button");return this._vrButton=n,n.classList.add("webxr-button"),n.dataset.needle="webxr-vr-button",n.innerText="Enter VR",n.prepend(Ot("panorama_photosphere")),n.title="Click to start a VR session",n.addEventListener("click",()=>J.start(i,s)),this.updateSessionSupported(n,i),this.listenToXRSessionState(n,i),this.hideElementDuringXRSession(n),this.isSecureConnection||(n.disabled=!0,n.title="WebXR requires a secure connection (HTTPS)"),X.isMozillaXR()||(t=navigator.xr)==null||t.addEventListener("devicechange",()=>this.updateSessionSupported(n,i)),n}createSendToQuestButton(){var s;if(this._sendToQuestButton)return this._sendToQuestButton;const t="https://oculus.com/open_url/?url=",i=document.createElement("button");return this._sendToQuestButton=i,i.dataset.needle="webxr-sendtoquest-button",i.innerText="Open on Quest",i.prepend(Ot("share_windows")),i.title="Click to send this page to the Oculus Browser on your Quest",i.addEventListener("click",()=>{const n=encodeURIComponent(window.location.href),o=t+n;window.open(o)==null&&De("This page doesn't allow popups. Please paste "+o+" into your browser.")}),this.listenToXRSessionState(i),this.hideElementDuringXRSession(i),X.isMozillaXR()||(s=navigator.xr)==null||s.addEventListener("devicechange",()=>{var n;(n=navigator.xr)!=null&&n.isSessionSupported("immersive-vr")?i.style.display="none":i.style.display=""}),i}createQRCode(){return kn.getOrCreate().createQRCode()}updateSessionSupported(s,t){if(!("xr"in navigator)){s.style.display="none";return}J.isSessionSupported(t).then(i=>{s.style.display=i?"":"none",F()&&!i&&console.log('[WebXR] "'+t+'" is not supported on this device \u2013 make sure your server runs using HTTPS and you have a device connected that supports '+t)})}hideElementDuringXRSession(s){Od(t=>{s["previous-display"]=s.style.display,s.style.display="none"}),Jm(t=>{s["previous-display"]!=null&&(s.style.display=s["previous-display"])})}listenToXRSessionState(s,t){t&&(J.onSessionRequestStart(i=>{i.mode===t?s.classList.add("this-mode-is-requested"):(s["was-disabled"]=s.disabled,s.disabled=!0,s.classList.add("other-mode-is-requested"))}),J.onSessionRequestEnd(i=>{s.classList.remove("this-mode-is-requested"),s.classList.remove("other-mode-is-requested"),s.disabled=s["was-disabled"]}))}};let zr=Nx;a(zr,"_instance");var yT=Object.defineProperty,vT=Object.getOwnPropertyDescriptor,wt=(s,t,i,n)=>{for(var o=n>1?void 0:n?vT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&yT(t,i,o),o};const op=C("debugspriterenderer"),bT=C("wireframe"),r0=class{static getOrCreateGeometry(s){if(s.__cached_geometry)return s.__cached_geometry;if(s.guid&&r0.cache[s.guid])return op&&console.log("Take cached geometry for sprite",s.guid),r0.cache[s.guid];const t=new gn;s.__cached_geometry=t;const i=new Float32Array(s.triangles.length*3),n=new Float32Array(s.triangles.length*2);for(let o=0;o<s.triangles.length;o+=1){const r=s.triangles[o];i[o*3]=-s.vertices[r].x,i[o*3+1]=s.vertices[r].y,i[o*3+2]=0;const l=s.uv[r];n[o*2]=l.x,n[o*2+1]=1-l.y}return t.setAttribute("position",new ft(i,3)),t.setAttribute("uv",new ft(n,2)),s.guid&&(this.cache[s.guid]=t),op&&console.log("Built sprite geometry",s,t),t}};let ah=r0;a(ah,"cache",{});class _T{constructor(){a(this,"x"),a(this,"y")}}function Wx(s){s&&(s.colorSpace!=ms&&(s.colorSpace=ms,s.needsUpdate=!0),s.minFilter==ld&&s.magFilter==ld&&(s.anisotropy=1,s.needsUpdate=!0))}let Nn=class{constructor(s){a(this,"guid"),a(this,"texture"),a(this,"triangles"),a(this,"uv"),a(this,"vertices"),a(this,"__cached_geometry"),a(this,"_mesh"),a(this,"_material"),s&&(this.texture=s,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}])}get mesh(){return this._mesh||(this._mesh=new Y(ah.getOrCreateGeometry(this),this.material)),this._mesh}get material(){return this._material||(this.texture&&Wx(this.texture),this._material=new Re({map:this.texture,color:16777215,side:Si,transparent:!0})),this._material}getGeometry(){return ah.getOrCreateGeometry(this)}};wt([m()],Nn.prototype,"guid",2),wt([m(Le)],Nn.prototype,"texture",2),wt([Pr()],Nn.prototype,"triangles",2),wt([Pr()],Nn.prototype,"uv",2),wt([Pr()],Nn.prototype,"vertices",2);const a0=Symbol("spriteOwner");class vl{constructor(){a(this,"sprites"),this.sprites=[]}}wt([m(Nn)],vl.prototype,"sprites",2);const l0=class{constructor(){a(this,"spriteSheet"),a(this,"index",0)}static create(){const s=new l0;return s.spriteSheet=new vl,s}clone(){const s=new l0;return s.index=this.index,s.spriteSheet=this.spriteSheet,s}set sprite(s){s&&(this.spriteSheet?((this.index===null||this.index===void 0)&&(this.index=0),this.spriteSheet.sprites[this.index]=s):(this.spriteSheet=new vl,this.spriteSheet.sprites=[s],this.index=0))}get sprite(){if(this.spriteSheet)return this.spriteSheet.sprites[this.index]}update(s){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&&(Wx(n),!i.__hasLoadedProgressive)){i.__hasLoadedProgressive=!0;const o=n;it.assignTextureLOD(n,0).then(r=>{r instanceof Le&&(i.texture=r,s?.map===o&&(s.map=r,s.needsUpdate=!0))})}}};let jo=l0;wt([m(vl)],jo.prototype,"spriteSheet",2),wt([m()],jo.prototype,"index",2);class mi extends A{constructor(){super(...arguments),a(this,"drawMode",0),a(this,"size",{x:1,y:1}),a(this,"color"),a(this,"sharedMaterial"),a(this,"transparent",!0),a(this,"cutoutThreshold",0),a(this,"castShadows",!1),a(this,"renderOrder",0),a(this,"toneMapped",!0),a(this,"_spriteSheet"),a(this,"_currentSprite")}set texture(t){var i;if(!this._spriteSheet)return;const n=(i=this._spriteSheet.spriteSheet)==null?void 0:i.sprites[this.spriteIndex];n&&(n.texture=t,this.updateSprite())}addSprite(t,i=!1){var n,o;if(this._spriteSheet||(this._spriteSheet=jo.create()),!this._spriteSheet.spriteSheet)return-1;(n=this._spriteSheet.spriteSheet)==null||n.sprites.push(t);const r=((o=this._spriteSheet.spriteSheet)==null?void 0:o.sprites.length)-1;return i&&(this.spriteIndex=r),r}get sprite(){return this._spriteSheet}set sprite(t){if(t!==this._spriteSheet)if(typeof t=="number"){const i=Math.floor(t);this.spriteIndex=i}else t instanceof Nn?(this._spriteSheet||(this._spriteSheet=jo.create()),this._spriteSheet.sprite!=t&&(this._spriteSheet.sprite=t),this.updateSprite()):t!=this._spriteSheet&&(this._spriteSheet=t,this.updateSprite())}set spriteIndex(t){this._spriteSheet&&(this._spriteSheet.index=t,this.updateSprite())}get spriteIndex(){var t;return((t=this._spriteSheet)==null?void 0:t.index)??0}get spriteFrames(){var t,i;return((i=(t=this._spriteSheet)==null?void 0:t.spriteSheet)==null?void 0:i.sprites.length)??0}awake(){this._currentSprite=void 0,this._spriteSheet?this._spriteSheet=this._spriteSheet.clone():this._spriteSheet=jo.create(),op&&console.log("Awake",this.name,this,this.sprite)}start(){this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(t=!1){var i;if(!this.__didAwake&&!t)return!1;const n=this._spriteSheet;if(!((i=n?.spriteSheet)!=null&&i.sprites))return console.warn("SpriteRenderer has no data or spritesheet assigned..."),!1;const o=n.spriteSheet.sprites[this.spriteIndex];if(!o)return op&&console.warn("Sprite not found",this.spriteIndex,n.spriteSheet.sprites),!1;if(this._currentSprite)this._currentSprite.geometry=ah.getOrCreateGeometry(o),this._currentSprite.material.map=o.texture;else{const r=new Re({color:16777215,side:Si});if(bT&&(r.wireframe=!0),this.color&&(r.color||(r.color=new ae),r.color.copy(this.color),r.opacity=this.color.alpha),r.transparent=!0,r.toneMapped=this.toneMapped,r.depthWrite=!1,o.texture&&!r.wireframe){let l=o.texture;l[a0]!==void 0&&l[a0]!==this&&this.spriteFrames>1&&(l=o.texture=l.clone()),l[a0]=this,r.map=l}this.sharedMaterial=r,this._currentSprite=new Y(ah.getOrCreateGeometry(o),r),this._currentSprite.renderOrder=Math.round(this.renderOrder),it.assignTextureLOD(r,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,n?.update(this.sharedMaterial),!0}}wt([m()],mi.prototype,"drawMode",2),wt([m(_T)],mi.prototype,"size",2),wt([m(xe)],mi.prototype,"color",2),wt([m(ke)],mi.prototype,"sharedMaterial",2),wt([m()],mi.prototype,"transparent",2),wt([m()],mi.prototype,"cutoutThreshold",2),wt([m()],mi.prototype,"castShadows",2),wt([m()],mi.prototype,"renderOrder",2),wt([m()],mi.prototype,"toneMapped",2),wt([m(jo)],mi.prototype,"sprite",1);const Vx=C("debugwebxr"),wT=new ne().makeRotationY(Math.PI),lh=class extends A{constructor(){super(...arguments),a(this,"_arScale",1),a(this,"invertForward",!1),a(this,"customReticle"),a(this,"arTouchTransform",!0),a(this,"autoPlace",!1),a(this,"autoCenter",!1),a(this,"useXRAnchor",!1),a(this,"_isPlacing",!0),a(this,"_startOffset",new ne),a(this,"_createdPlacementObject",null),a(this,"_reparentedComponents",[]),a(this,"_placementScene",new Vi),a(this,"_reticle",[]),a(this,"_hits",[]),a(this,"_placementStartTime",-1),a(this,"_rigPlacementMatrix"),a(this,"_anchor",null),a(this,"userInput"),a(this,"onPlaceScene",s=>{var t;if(this._isPlacing==!1||s!=null&&s.used)return;let i=this._reticle[0];if(!i){console.warn("No reticle to place...");return}if(!i.visible&&!this.autoPlace){console.warn("Reticle is not visible (can not place)");return}if((t=J.active)!=null&&t.isTrackingImages){console.warn("Scene Placement is disabled while images are being tracked");return}let n=this._hits[0];if(s&&s.origin instanceof eg){const o=this._reticle[s.origin.index];o&&(i=o,n=this._hits[s.origin.index])}if(s&&(s.stopImmediatePropagation(),s.stopPropagation(),s.use()),this._isPlacing=!1,this.context.input.removeEventListener("pointerup",this.onPlaceScene),this.onRevertSceneChanges(),i.position.copy(i.lastPos),i.quaternion.copy(i.lastQuat),this.onApplyPose(i),lh._hasPlaced=!0,this.useXRAnchor&&this.onCreateAnchor(J.active,n),this.context.xr)for(const o of this.context.xr.controllers)o.cancelHitTestSource()}),a(this,"upVec",new x(0,1,0)),a(this,"lookPoint",new x),a(this,"worldUpVec",new x(0,1,0))}static onPlaced(s){const t="placed";return this._eventListeners[t]||(this._eventListeners[t]=[]),this._eventListeners[t].push(s),()=>{const i=this._eventListeners[t].indexOf(s);i>=0&&this._eventListeners[t].splice(i,1)}}static get hasPlaced(){return this._hasPlaced}get arScale(){return this._arScale}set arScale(s){this._arScale=Math.max(1e-6,s),this.onSetScale()}onEnable(){var s;(s=this.customReticle)==null||s.preload()}supportsXR(s){return s==="immersive-ar"}onEnterXR(s){Vx&&console.log("ENTER WEBXR: SessionRoot start..."),this._anchor=null,lh._hasPlaced=!1,this.gameObject.updateMatrixWorld(),this._startOffset.copy(this.gameObject.matrixWorld);const t=new I;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=oi(this._placementScene.children),n=i.getCenter(new x),o=i.getSize(new x),r=new ne;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}),O.addComponent(t,this);for(const i of this._reticle)Ri(i);this._reticle.length=0,this._isPlacing=!0,this.context.input.addEventListener("pointerup",this.onPlaceScene,{queue:ai.Early})}onLeaveXR(){this.context.input.removeEventListener("pointerup",this.onPlaceScene,{queue:ai.Early}),this.onRevertSceneChanges(),this._anchor=null,lh._hasPlaced=!1,this._rigPlacementMatrix=void 0}onUpdateXR(s){var t,i,n,o;if(s.xr.isTrackingImages){for(const r of this._reticle)r.visible=!1;return}if(this._isPlacing){const r=(t=s.xr.rig)==null?void 0:t.gameObject;r&&r.parent!==this.context.scene&&this.context.scene.add(r);let l=!1;if(s.xr.isPassThrough&&s.xr.controllers.length>0&&!this.autoPlace)for(const c of s.xr.controllers){const h=c.getHitTest();h&&(l=!0,this.updateReticleAndHits(s.xr,c.index,h,s.xr.rigScale))}if(!l){const c=s.xr.getHitTest();c&&this.updateReticleAndHits(s.xr,0,c,s.xr.rigScale)}}else{if(this._anchor&&s.xr.referenceSpace){const r=s.xr.frame.getPose(this._anchor.anchorSpace,s.xr.referenceSpace);if(r&&this.context.time.frame%20===0){const l=s.xr.convertSpace(r.transform),c=this._reticle[0];c&&(c.position.copy(l.position),c.quaternion.copy(l.quaternion),this.onApplyPose(c))}}if(this.arTouchTransform?(this.userInput||(this.userInput=new rp(this.context)),(i=this.userInput)==null||i.enable()):(n=this.userInput)==null||n.disable(),this.arTouchTransform&&(o=this.userInput)!=null&&o.hasChanged){if(s.xr.rig){const r=s.xr.rig.gameObject;this.userInput.applyMatrixTo(r.matrix,!0),r.matrix.decompose(r.position,r.quaternion,r.scale),this.userInput.factor=r.scale.x}this.userInput.reset()}}}updateReticleAndHits(s,t,i,n){this._hits[t]=i.hit;let o=this._reticle[t];if(!o){if(this.customReticle)if(this.customReticle.asset)o=La(this.customReticle.asset);else{this.customReticle.loadAssetAsync();return}else o=new Y(new uC(.07,.09,32).rotateX(-Math.PI/2),new Re({side:Si,depthTest:!1,depthWrite:!1,transparent:!0,opacity:1,color:15658734})),o.name="AR Placement Reticle";if(Vx){const r=new xi(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(G(0,1,0))>.9){let r=o["autoplace:timer"]||0;r>=1?(o.visible=!1,this.onPlaceScene(null)):(r+=this.context.time.deltaTime,o["autoplace:timer"]=r)}else o["autoplace:timer"]=0}onSetScale(){var s,t,i;if(!lh._hasPlaced)return;const n=(t=(s=J.active)==null?void 0:s.rig)==null?void 0:t.gameObject;if(n){const o=((i=J.active)==null?void 0:i.rigScale)||1,r=1/this._arScale*o,l=new ne().makeScale(r,r,r).invert();n.matrix.premultiply(l),n.matrix.decompose(n.position,n.quaternion,n.scale)}}onRevertSceneChanges(){var s;for(const t of this._reticle)t&&(t.visible=!1,t?.removeFromParent());this._reticle.length=0;for(let t=this._placementScene.children.length-1;t>=0;t--){const i=this._placementScene.children[t];this.context.scene.add(i)}(s=this._createdPlacementObject)==null||s.removeFromParent();for(const t of this._reparentedComponents)O.addComponent(t.originalObject,t.comp)}async onCreateAnchor(s,t){if(t.createAnchor===void 0){console.warn("Hit does not support creating an anchor",t),F()&&we("Hit does not support creating an anchor");return}else{const i=await t.createAnchor(s.viewerPose.transform);s.running&&i&&(this._anchor=i)}}applyViewBasedTransform(s){const t=this.context.mainCamera,i=s,n=t.worldPosition,o=i.worldPosition;this.upVec.set(0,1,0).applyQuaternion(s.quaternion);const r=t.worldPosition;r&&s.position.clone().sub(r).angleTo(this.upVec)<Math.PI/2&&this.upVec.negate();const l=this.upVec.angleTo(this.worldUpVec)*180/Math.PI,c=30;l>c&&l<180-c||l<-c&&l>-180+c?(this.lookPoint.copy(s.position).add(this.upVec),this.lookPoint.y=s.position.y,s.lookAt(this.lookPoint)):(n.y=o.y,s.lookAt(n))}onApplyPose(s){var t,i,n;const o=(i=(t=J.active)==null?void 0:t.rig)==null?void 0:i.gameObject;if(!o){console.warn("No rig object to place");return}const r=o.parent||this.context.scene;this._rigPlacementMatrix?(n=this._rigPlacementMatrix)==null||n.decompose(o.position,o.quaternion,o.scale):this._rigPlacementMatrix=o.matrix.clone(),this.applyViewBasedTransform(s),s.updateMatrix(),this.context.scene.add(s),s.attach(o),s.removeFromParent(),o.scale.set(this.arScale,this.arScale,this.arScale),o.position.multiplyScalar(this.arScale),o.updateMatrix(),this.invertForward&&o.matrix.premultiply(wT),o.matrix.premultiply(this._startOffset),o.matrix.decompose(o.position,o.quaternion,o.scale),r.add(o)}};let sn=lh;a(sn,"_eventListeners",{}),a(sn,"_hasPlaced",!1);const c0=class{constructor(s){a(this,"oneFingerDrag",!0),a(this,"twoFingerRotate",!0),a(this,"twoFingerScale",!0),a(this,"factor",1),a(this,"context"),a(this,"offset"),a(this,"plane"),a(this,"_scale",1),a(this,"_hasChanged",!1),a(this,"_enabled",!1),a(this,"currentlyUsedPointerIds",new Set),a(this,"currentlyUnusedPointerIds",new Set),a(this,"onPointerDownEarly",t=>{this.isActive&&t.stopPropagation()}),a(this,"onPointerDownLate",t=>{t.used?this.currentlyUsedPointerIds.add(t.pointerId):this.currentlyUsedPointerIds.size<=0&&this.currentlyUnusedPointerIds.add(t.pointerId)}),a(this,"onPointerUpEarly",t=>{this.currentlyUsedPointerIds.delete(t.pointerId),this.currentlyUnusedPointerIds.delete(t.pointerId)}),a(this,"prev",new Map),a(this,"_didMultitouch",!1),a(this,"touchStart",t=>{if(!t.defaultPrevented)for(let i=0;i<t.changedTouches.length;i++){const n=t.changedTouches[i],o=X.isAndroidDevice()&&n.clientY<window.innerHeight*.1;this.prev.has(n.identifier)||this.prev.set(n.identifier,{ignore:o,x:0,z:0,screenx:0,screeny:0});const r=this.prev.get(n.identifier);if(r){const l=this.getPositionOnPlane(n.clientX,n.clientY);r.x=l.x,r.z=l.z,r.screenx=n.clientX,r.screeny=n.clientY}}}),a(this,"touchEnd",t=>{t.touches.length<=0&&(this._didMultitouch=!1);for(let i=0;i<t.changedTouches.length;i++){const n=t.changedTouches[i];this.prev.delete(n.identifier)}}),a(this,"touchMove",t=>{if(!t.defaultPrevented&&this.isActive){if(t.touches.length===1){if(this._didMultitouch)return;const i=t.touches[0],n=this.prev.get(i.identifier);if(!n||n.ignore)return;const o=this.getPositionOnPlane(i.clientX,i.clientY),r=o.x-n.x,l=o.z-n.z;if(r===0&&l===0)return;this.oneFingerDrag&&this.addMovement(r,l),n.x=o.x,n.z=o.z,n.screenx=i.clientX,n.screeny=i.clientY;return}else if(t.touches.length===2){this._didMultitouch=!0;const i=t.touches[0],n=t.touches[1],o=this.prev.get(i.identifier),r=this.prev.get(n.identifier);if(!o||!r)return;if(this.twoFingerRotate){const l=Math.atan2(i.clientY-n.clientY,i.clientX-n.clientX),c=Math.atan2(o.screeny-r.screeny,o.screenx-r.screenx),h=l-c;Math.abs(h)>.001&&this.addRotation(h)}if(this.twoFingerScale){const l=i.clientX-n.clientX,c=i.clientY-n.clientY,h=Math.sqrt(l*l+c*c),d=o.screenx-r.screenx,u=o.screeny-r.screeny,p=Math.sqrt(d*d+u*u),g=h-p;Math.abs(g)>2&&this.addScale(g)}o.screenx=i.clientX,o.screeny=i.clientY,r.screenx=n.clientX,r.screeny=n.clientY}}}),a(this,"_raycaster",new rd),a(this,"_intersection",new x),a(this,"_screenPos",new x),a(this,"_tempMatrix",new ne),this.context=s,this.offset=new ne,this.plane=new nr,this.plane.setFromNormalAndCoplanarPoint(c0.up,c0.zero)}get scale(){return this._scale}reset(){this._scale=1,this.offset.identity(),this._hasChanged=!0}get hasChanged(){return this._hasChanged}applyMatrixTo(s,t){this._hasChanged=!1,t?(this.offset.invert(),s.premultiply(this.offset)):s.multiply(this.offset)}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:ai.Early}),this.context.input.addEventListener("pointerdown",this.onPointerDownLate,{queue:ai.Late}),this.context.input.addEventListener("pointerup",this.onPointerUpEarly,{queue:ai.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:ai.Early}),this.context.input.removeEventListener("pointerdown",this.onPointerDownLate,{queue:ai.Late}),this.context.input.removeEventListener("pointerup",this.onPointerUpEarly,{queue:ai.Early}),window.removeEventListener("touchstart",this.touchStart),window.removeEventListener("touchmove",this.touchMove),window.removeEventListener("touchend",this.touchEnd))}getPositionOnPlane(s,t){const i=this.context.mainCamera;return this._screenPos.x=s/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(s,t){s/=this._scale,t/=this._scale,s*=this.factor,t*=this.factor,this.offset.elements[12]+=s,this.offset.elements[14]+=t,(s!==0||t!==0)&&(this._hasChanged=!0)}addScale(s){s/=window.innerWidth,s*=-1,this._scale*=1+s,this._tempMatrix.makeScale(1-s,1-s,1-s),this.offset.premultiply(this._tempMatrix),s!==0&&(this._hasChanged=!0)}addRotation(s){s*=-1,this._tempMatrix.makeRotationY(s),this.offset.premultiply(this._tempMatrix),s!==0&&(this._hasChanged=!0)}};let rp=c0;a(rp,"up",new x(0,1,0)),a(rp,"zero",new x(0,0,0)),a(rp,"one",new x(1,1,1));const Lo=C("debugautosync"),h0=Symbol("syncerId");class xT{constructor(){a(this,"_syncers",{})}getOrCreateSyncer(t){if(!t.guid)return null;if(this._syncers[t.guid])return this._syncers[t.guid];const i=new ST(t);return i[h0]=t.guid,this._syncers[i[h0]]=i,i}removeSyncer(t){delete this._syncers[t[h0]]}}const d0=new xT;class ST{constructor(t){a(this,"comp"),a(this,"hasChanges",!1),a(this,"changedProperties",{}),a(this,"_isReceiving",!1),a(this,"_isInit",!1),a(this,"onHandleSending",()=>{if(!this.hasChanges)return;this.hasChanges=!1;const i=this.comp.context.connection;if(!i||!i.isConnected||!i.isInRoom){for(const n in this.changedProperties)delete this.changedProperties[n];return}for(const n in this.changedProperties){const o=this.changedProperties[n];Lo&&console.log("SEND",this.comp.guid,this.networkingKey),i.send(this.networkingKey,{guid:this.comp.guid,property:n,data:o},_s.Queued),delete this.changedProperties[n]}}),a(this,"onHandleReceiving",i=>{if(Lo&&console.log("SYNCFIELD RECEIVE",this.comp.name,this.comp.guid,i),!!this._isInit&&this.comp&&i.guid===this.comp.guid)try{this._isReceiving=!0,this.comp[i.property]=i.data}catch(n){console.error(n)}finally{this._isReceiving=!1}}),this.comp=t}get networkingKey(){return this.comp.guid}init(t){if(this._isInit)return;this._isInit=!0,this.comp=t,this.comp.context.post_render_callbacks.push(this.onHandleSending),this.comp.context.connection.beginListen(this.networkingKey,this.onHandleReceiving);const i=this.comp.context.connection.tryGetState(this.comp.guid);i&&this.onHandleReceiving(i)}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(t,i){this._isReceiving||(Lo&&console.log("Property changed: "+t,i),this.hasChanges=!0,this.changedProperties[t]=i)}}function CT(s,t){let i=t!==s;return!i&&s&&t&&(Array.isArray(s)&&Array.isArray(t)||typeof s=="object"&&typeof t=="object")&&(i=!0),i}const ch=Symbol("AutoSyncHandler");function OT(s){if(s[ch])return s[ch];const t=d0.getOrCreateSyncer(s);return t?.init(s),s[ch]=t,t}function PT(s){const t=s[ch];t&&(d0.removeSyncer(t),t.destroy(),delete s[ch])}const u0=function(s=null){return function(t,i){var n;let o="";typeof i=="string"?o=i:o=i.name;let r=null,l;typeof s=="string"?l=t[s]:typeof s=="function"&&(l=s),l==null&&(F()||Lo)&&s!=null&&console.warn('syncField: no callback function found for property "'+o+'"','"'+s+'"');const c=t,h=c.__internalAwake;if(typeof h!="function"){(Lo||F())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+((n=t?.constructor)==null?void 0:n.name)+'" is not supported',t);return}Lo&&console.log(o);const d=Symbol(o);c.__internalAwake=function(){if(this[d]!==void 0)return;this[d]=this[o],r=d0.getOrCreateSyncer(this);const p=Object.getOwnPropertyDescriptor(this,o);if(p?.set===void 0){let g=!1;Object.defineProperty(this,o,{set:function(y){var f;const v=this[d];if(this[d]=y,g){(F()||Lo)&&console.warn("Recursive call detected",o);return}g=!0;try{const b=CT(y,v);Lo&&console.log("SyncField assignment",o,"changed?",b,y,l),b&&l?.call(this,y,v)!==!1&&((f=OT(this))==null||f.notifyChanged(o,y))}finally{g=!1}},get:function(){return this[d]},configurable:!0,enumerable:!0})}r?.init(this),h.call(this)};const u=c.__internalDestroy;c.__internalDestroy=function(){PT(this),u.call(this)}}};var kT=Object.defineProperty,MT=Object.getOwnPropertyDescriptor,ap=(s,t,i,n)=>{for(var o=n>1?void 0:n?MT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&kT(t,i,o),o};const ei=C("debugplayersync"),Hx=class extends A{constructor(){super(...arguments),a(this,"autoSync",!0),a(this,"asset"),a(this,"onPlayerSpawned"),a(this,"_localInstance"),a(this,"onJoinedRoom",()=>{ei&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()}),a(this,"destroyInstance",()=>{var s;(s=this._localInstance)==null||s.then(t=>{ei&&console.log("PlayerSync.destroyInstance",t),wc(t,this.context.connection,!0,{saveInRoom:!1})}),this._localInstance=void 0})}static async setupFrom(s,t){const i=le.getOrCreateFromUrl(s);if(!i.asset){const r=await i.loadAssetAsync();r&&O.getOrAddComponent(r,Ii)}const n=new Hx;n._internalInit(t),n.asset=i;const o=new I;return o.guid=s,O.addComponent(o,n),n}awake(){this.watchTabVisible(),this.onPlayerSpawned||(this.onPlayerSpawned=new Se)}onEnable(){this.context.connection.beginListen(se.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(se.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(se.LeftRoom,this.destroyInstance),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(se.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(se.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(se.LeftRoom,this.destroyInstance)}async getInstance(){var s,t,i,n,o,r;if(this._localInstance)return this._localInstance;if(ei&&console.log("PlayerSync.createInstance",(s=this.asset)==null?void 0:s.url),!((t=this.asset)!=null&&t.asset)&&!((i=this.asset)!=null&&i.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=(n=this.asset)==null?void 0:n.instantiateSynced({parent:this.gameObject,deleteOnDisconnect:!0},!0);const l=await this._localInstance;if(l){const c=O.getComponentsInChildren(l,Ii);if(ei&&console.log(`PlayerSync.createInstance: found ${c?.length} PlayerState components. Owner: ${this.context.connection.connectionId}`),c!=null&&c.length){for(const h of c)h.owner=this.context.connection.connectionId;(o=this.onPlayerSpawned)==null||o.invoke(l)}else this._localInstance=void 0,console.error("<strong>Failed finding PlayerState on "+((r=this.asset)==null?void 0:r.url)+"</strong>: please make sure the asset has a PlayerState component!"),O.destroySynced(l)}else this._localInstance=void 0,console.warn("PlayerSync: failed instantiating asset!");return this._localInstance}watchTabVisible(){window.addEventListener("visibilitychange",s=>{if(document.visibilityState==="visible")for(let t=Ii.all.length-1;t>=0;t--){const i=Ii.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}};let bl=Hx;ap([m()],bl.prototype,"autoSync",2),ap([m(le)],bl.prototype,"asset",2),ap([m(Se)],bl.prototype,"onPlayerSpawned",2);var $x=(s=>(s.OwnerChanged="ownerChanged",s))($x||{}),hh;const Tt=(hh=class extends A{constructor(){super(...arguments),a(this,"onOwnerChangeEvent",new Se),a(this,"onFirstOwnerChangeEvent",new Se),a(this,"hasOwner",!1),a(this,"owner"),a(this,"dontDestroy",!1),a(this,"onUserLeftRoom",s=>{if(s.userId===this.owner){ei&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}})}static get all(){return Tt._all}static get local(){return Tt._local}static getFor(s){if(s instanceof I)return O.getComponentInParent(s,Tt);if(s instanceof A)return O.getComponentInParent(s.gameObject,Tt)}static isLocalPlayer(s){const t=Tt.getFor(s);return t?.isLocalPlayer??!1}static addEventListener(s,t){return this._callbacks[s]||(this._callbacks[s]=[]),this._callbacks[s].push(t),t}static removeEventListener(s,t){if(!this._callbacks[s])return;const i=this._callbacks[s].indexOf(t);i>=0&&this._callbacks[s].splice(i,1)}static dispatchEvent(s,t){if(this._callbacks[s])for(const i of this._callbacks[s])i(t)}get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(s,t){var i,n;ei&&console.log(`PlayerSync.onOwnerChange: ${t} \u2192 ${s} (me: ${this.context.connection.connectionId})`);const o=Tt._local.indexOf(this);o>=0&&Tt._local.splice(o,1);const r={playerState:this,oldValue:t,newValue:s};if(this.hasOwner||(this.hasOwner=!0,(i=this.onFirstOwnerChangeEvent)==null||i.invoke(r)),(n=this.onOwnerChangeEvent)==null||n.invoke(r),this.owner===this.context.connection.connectionId){Tt._local.push(this);const c=new CustomEvent("local-owner-changed",{detail:r});this.dispatchEvent(c)}const l=new CustomEvent("owner-changed",{detail:r});this.dispatchEvent(l),Tt.dispatchEvent("ownerChanged",l)}awake(){Tt.all.push(this),ei&&console.log("Registered new PlayerState",this.guid,Tt.all.length-1,Tt.all),this.context.connection.beginListen(se.UserLeftRoom,this.onUserLeftRoom)}async start(){ei&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await fs(300),this.context.connection.userIsInRoom(this.owner)==!1&&(ei&&console.log(`PlayerSync.start \u2192 doDestroy "${this.name}" because user "${this.owner}" is not in room anymore...`,"Currently in room:",...this.context.connection.usersInRoom()),this.doDestroy())):this.owner||(ei&&console.warn("PlayerState.start \u2192 owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?ei&&console.warn("PlayerState.start \u2192 owner is still undefined but dontDestroy is set to true",this.name):(ei&&console.warn(`PlayerState.start \u2192 owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):ei&&console.log("PlayerState.start \u2192 owner is assigned",this.owner)},2e3))}doDestroy(){ei&&console.log("PlayerSync.doDestroy \u2192 syncDestroy",this.name),wc(this.gameObject,this.context.connection,!0,{saveInRoom:!1})}onDestroy(){if(ei&&console.warn("PlayerState.onDestroy",this.owner),this.context.connection.stopListen(se.UserLeftRoom,this.onUserLeftRoom),Tt.all.splice(Tt.all.indexOf(this),1),this.isLocalPlayer){const s=Tt._local.indexOf(this);s>=0&&Tt._local.splice(s,1)}}},a(hh,"_all",[]),a(hh,"_local",[]),a(hh,"_callbacks",{}),hh);let Ii=Tt;ap([u0(Ii.prototype.onOwnerChange)],Ii.prototype,"owner",2);var RT=Object.defineProperty,TT=Object.getOwnPropertyDescriptor,_l=(s,t,i,n)=>{for(var o=n>1?void 0:n?TT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&RT(t,i,o),o};class nn extends A{constructor(){super(...arguments),a(this,"position","bottom"),a(this,"showNeedleLogo",!0),a(this,"showSpatialMenu"),a(this,"createFullscreenButton"),a(this,"createMuteButton"),a(this,"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&&(X.isMobileDevice()||this.context.menu.showQRCodeButton(!0))}}_l([m()],nn.prototype,"position",2),_l([m()],nn.prototype,"showNeedleLogo",2),_l([m()],nn.prototype,"showSpatialMenu",2),_l([m()],nn.prototype,"createFullscreenButton",2),_l([m()],nn.prototype,"createMuteButton",2),_l([m()],nn.prototype,"createQRCodeButton",2);var ET=Object.defineProperty,AT=Object.getOwnPropertyDescriptor,p0=(s,t,i,n)=>{for(var o=n>1?void 0:n?AT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&ET(t,i,o),o};const dh=C("debugwebxr"),qx=new V().setFromAxisAngle(new x(0,1,0),Math.PI);class Do extends A{constructor(){super(...arguments),a(this,"head"),a(this,"leftHand"),a(this,"rightHand"),a(this,"_leftHandMeshes"),a(this,"_rightHandMeshes"),a(this,"_syncTransforms")}async onEnterXR(t){if(!this.activeAndEnabled)return;dh&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const i=Ii.getFor(this);if(i!=null&&i.owner){const n=this.gameObject.addComponent(Mt);n.avatar=this.gameObject,n.connectionId=i.owner}else this.context.connection.isConnected?console.error("No player state found for avatar",this):i&&!this.context.connection.isConnected&&(i.dontDestroy=!0)}onLeaveXR(t){const i=this.gameObject.getComponent(Mt);i&&i.destroy()}onUpdateXR(t){var i,n;if(!this.activeAndEnabled)return;const o=Ii.isLocalPlayer(this);if(!o)return;const r=t.xr;if(r.rig&&r.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),r.rig.gameObject.add(this.gameObject)),this._syncTransforms&&o)for(const u of this._syncTransforms)u.fastMode=!0,u.isOwned()||u.requestOwnership();if(this.head&&this.context.mainCamera){const u=this.head.asset;if(u.position.copy(this.context.mainCamera.position),u.position.x*=-1,u.position.z*=-1,u.quaternion.copy(this.context.mainCamera.quaternion),u.quaternion.x*=-1,this.context.time.frameCount%10===0&&this.head.asset){const p=O.getComponentsInChildren(this.head.asset,Ai);for(const g of p)g.enabled=!1,g.gameObject.visible=!1}}const l=t.xr.leftController,c=(i=this.leftHand)==null?void 0:i.asset;l&&c?(c.position.copy(l.gripPosition),c.quaternion.copy(l.gripQuaternion),c.quaternion.multiply(qx),c.visible=l.isTracking,this.updateHandVisibility(l,c,this._leftHandMeshes)):c&&c.visible&&(c.visible=!1);const h=t.xr.rightController,d=(n=this.rightHand)==null?void 0:n.asset;h&&d?(d.position.copy(h.gripPosition),d.quaternion.copy(h.gripQuaternion),d.quaternion.multiply(qx),d.visible=h.isTracking,this.updateHandVisibility(h,d,this._rightHandMeshes)):d&&d.visible&&(d.visible=!1)}onBeforeRender(){this.context.xr&&this.context.time.frame%10===0&&this.updateRemoteAvatarVisibility()}updateHandVisibility(t,i,n){if(n){const o=t.model&&t.model.visible&&t.model!==i;n.forEach(r=>{On(r,!o)})}}updateRemoteAvatarVisibility(){var t,i,n;if(this.context.connection.isConnected){const o=Ii.getFor(this);if(o&&o.isLocalPlayer==!1){const r=J.getXRSync(this.context);if(r&&r.hasState(o.owner)){this.tryFindAvatarObjectsIfMissing();const l=(t=this.leftHand)==null?void 0:t.asset;l&&(l.visible=r?.isTracking(o.owner,"left")??!1);const c=(i=this.rightHand)==null?void 0:i.asset;c&&(c.visible=r?.isTracking(o.owner,"right")??!1)}if((n=this.head)!=null&&n.asset){const l=O.getComponentsInChildren(this.head.asset,Ai);for(const c of l)c.enabled=!1,c.gameObject.visible=!0}}}}tryFindAvatarObjectsIfMissing(){if(!this.head||!this.leftHand||!this.rightHand){const t={head:this.head,leftHand:this.leftHand,rightHand:this.rightHand};Ub.tryFindAvatarObjects(this.gameObject,this.sourceId||"",t),t.head&&(this.head=t.head),t.leftHand&&(this.leftHand=t.leftHand),t.rightHand&&(this.rightHand=t.rightHand)}}async prepareAvatar(){var t,i;if(this.tryFindAvatarObjectsIfMissing(),this.head)this.head instanceof I&&(this.head=new le("",this.sourceId,this.head));else{const n=new I;n.name="Head";const o=po.createPrimitive(ur.Cube);n.add(o),this.gameObject.add(n),this.head=new le("",this.sourceId,n),dh&&console.log("Create head",n)}if(this.rightHand)this.rightHand instanceof I&&(this.rightHand=new le("",this.sourceId,this.rightHand));else{const n=new I;n.name="Right Hand",this.gameObject.add(n),this.rightHand=new le("",this.sourceId,n),dh&&console.log("Create right hand",n)}if(this.leftHand)this.leftHand instanceof I&&(this.leftHand=new le("",this.sourceId,this.leftHand));else{const n=new I;n.name="Left Hand",this.gameObject.add(n),this.leftHand=new le("",this.sourceId,n),dh&&console.log("Create left hand",n)}await this.loadAvatarObjects(this.head,this.leftHand,this.rightHand),this._leftHandMeshes=[],(t=this.leftHand.asset)==null||t.traverse(n=>{n!=null&&n.isMesh&&this._leftHandMeshes.push(n)}),this._rightHandMeshes=[],(i=this.rightHand.asset)==null||i.traverse(n=>{n!=null&&n.isMesh&&this._rightHandMeshes.push(n)}),Ii.isLocalPlayer(this.gameObject)&&(this._syncTransforms=O.getComponentsInChildren(this.gameObject,qs))}async loadAvatarObjects(t,i,n){const o=t.loadAssetAsync(),r=i.loadAssetAsync(),l=n.loadAssetAsync(),c=new Array;o&&c.push(o),r&&c.push(r),l&&c.push(l);const h=await Mm(c);dh&&console.log("Avatar loaded results:",h)}}p0([m(le)],Do.prototype,"head",2),p0([m(le)],Do.prototype,"leftHand",2),p0([m(le)],Do.prototype,"rightHand",2);var IT=Object.defineProperty,jT=Object.getOwnPropertyDescriptor,lp=(s,t,i,n)=>{for(var o=n>1?void 0:n?jT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&IT(t,i,o),o};const Wn=C("debugwebxr"),Bo=new Array;class on extends A{constructor(){super(...arguments),a(this,"createControllerModel",!0),a(this,"createHandModel",!0),a(this,"customLeftHand"),a(this,"customRightHand"),a(this,"_models",new Array)}supportsXR(t){return t==="immersive-vr"||t==="immersive-ar"}async onXRControllerAdded(t){var i;if(!(t.xr.isVR||t.xr.isPassThrough))return;const{controller:n}=t;if(Wn&&console.warn("Add Controller Model for",n.side,n.index),this.createControllerModel||this.createHandModel){if(n.hand){if(this.createHandModel){const o=await this.loadHandModel(this,n);if(!o||!n.connected||!n.isHand){o!=null&&o.handObject&&ja(o.handObject,!1),(i=o?.handObject)==null||i.destroy();return}this._models.push({controller:n,model:o.handObject,handmesh:o.handmesh}),this._models.sort((r,l)=>r.controller.index-l.controller.index),this.scene.add(o.handObject),n.model=o.handObject}}else if(this.createControllerModel){const o=await n.getModelUrl();if(o){const r=await this.loadModel(n,o);if(!r||!n.connected||n.isHand)return;this._models.push({controller:n,model:r}),this._models.sort((l,c)=>l.controller.index-c.controller.index),this.scene.add(r),r.traverse(l=>{l.layers.set(2),l.matrixAutoUpdate=!1,l.updateMatrix()}),n.model=r}else n.targetRayMode!=="transient-pointer"&&console.warn("XRControllerModel: no model found for "+n.side)}}}onXRControllerRemoved(t){console.debug("XR Controller Removed",t.controller.side,t.controller.index);const i=this._models.findIndex(o=>o.controller===t.controller),n=this._models[i];n&&(this._models.splice(i,1),n.model&&(ja(n.model,!1),n.model.destroy(),n.model=void 0))}onBeforeXR(t,i){this.createHandModel&&(this.customLeftHand||this.customRightHand)&&(i.optionalFeatures=i.optionalFeatures||[],i.optionalFeatures.includes("hand-tracking")||i.optionalFeatures.push("hand-tracking"))}onLeaveXR(t){for(const i of this._models)i&&(i.model&&(ja(i.model,!1),i.model.destroy(),i.model=void 0),i.controller.model===i.model&&(i.controller.model=null));this._models.length=0}onBeforeRender(){if(J.active&&(Wn&&(Bo[0]=Date.now()),this.updateRendering(J.active),Wn)){const t=Date.now()-Bo[0];Bo.push(t),Bo.length>=30&&(Bo[0]=0,Bo.reduce((i,n)=>i+n,0)/Bo.length,Bo.length=0)}}updateRendering(t){var i,n,o,r,l;for(let c=0;c<this._models.length;c++){const h=this._models[c];if(!h)continue;const d=h.controller;if(!d.connected){Wn&&console.warn("XRControllerModel.onUpdateXR: controller is not connected anymore",d.side,d.hand);continue}if(h.model&&!h.handmesh)h.model.matrixAutoUpdate=!1,h.model.matrix.copy(d.gripMatrix),h.model.visible=d.isTracking,(i=t.rig)==null||i.gameObject.add(h.model);else if(d.inputSource.hand&&h.handmesh){const u=t.referenceSpace,p=this.context.renderer.xr.getHand(d.index);if(u&&t.frame.getJointPose){for(const g of d.inputSource.hand.values()){const y=p.joints[g.jointName];if(y){const f=d.getHandJointPose(g);if(f){const v=f.transform.position,b=f.transform.orientation;y.position.copy(v),y.quaternion.copy(b),y.matrixAutoUpdate=!1}y.visible=f!=null}}h.model&&(h.model.visible=d.isTracking,h.model.visible&&h.model.parent!==((n=t.rig)==null?void 0:n.gameObject)&&((o=t.rig)==null||o.gameObject.add(h.model))),(r=h.model)!=null&&r.visible&&((l=h.handmesh)==null||l.updateMesh(),h.model.matrixAutoUpdate=!1,h.model.matrix.identity(),h.model.applyMatrix4(Ca))}}}}async loadModel(t,i){var n;if(!t.connected)return console.warn("XRControllerModel.onXRControllerAdded: controller is not connected anymore",t.side),null;const o=await le.getOrCreate("",i).instantiate();return ja(o),(n=J.active)!=null&&n.isPassThrough&&o.traverseVisible(r=>{this.makeOccluder(r)}),o}async loadHandModel(t,i){const n=this.context,o=n.renderer.xr.getHand(i.index);o||(Wn?q.DrawLabel(i.rayWorldPosition,"No hand found for index "+i.index,.05,5):console.warn("No hand found for index "+i.index));const r=new rr;gu(r,n),await Wu(r,n,this.sourceId??"");const l=Nu(r);let c="";const h=i.side==="left"?this.customLeftHand:this.customRightHand;h?(c=h.url.split(".").slice(0,-1).join("."),r.setPath("")):(c=i.inputSource.handedness==="left"?"left":"right",r.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/"));const d=new I;ja(d);const u=new $C(d,o,r.path,c,r,p=>{var g;const y=l.gltf;((g=y?.scene.children)==null?void 0:g.length)===0&&(y.scene.children[0]=p),gs().createBuiltinComponents(t.context,t.sourceId||c,l.gltf,null,l),p.traverse(f=>{var v;f.layers.set(2),(v=J.active)!=null&&v.isPassThrough&&!h&&this.makeOccluder(f),f instanceof Y&&it.assignMeshLOD(f,0)}),i.connected||(Wn&&q.DrawLabel(i.rayWorldPosition,"Hand is loaded but not connected anymore",.05,5),p.removeFromParent())});if(Wn&&d.add(new xi(.5)),i.inputSource.hand){Wn&&console.log(i.inputSource.hand);for(const p of i.inputSource.hand.values())if(o.joints[p.jointName]===void 0){const g=new oo;g.matrixAutoUpdate=!1,g.visible=!0,o.joints[p.jointName]=g,o.add(g)}}else Wn&&q.DrawLabel(i.rayWorldPosition,"No inputSource.hand found for index "+i.index,.05,5);return{handObject:d,handmesh:u}}makeOccluder(t){if(t instanceof Y){let i=t.material;i instanceof ke&&(i=t.material=i.clone(),i.depthWrite=!0,i.depthTest=!0,i.colorWrite=!1,t.receiveShadow=!1,t.renderOrder=-100)}}}a(on,"factory",new HC),lp([m()],on.prototype,"createControllerModel",2),lp([m()],on.prototype,"createHandModel",2),lp([m(le)],on.prototype,"customLeftHand",2),lp([m(le)],on.prototype,"customRightHand",2);class cp extends A{}var LT=Object.defineProperty,DT=Object.getOwnPropertyDescriptor,Fo=(s,t,i,n)=>{for(var o=n>1?void 0:n?DT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&LT(t,i,o),o};const m0=C("debugwebxr");class ji extends A{constructor(){super(...arguments),a(this,"movementSpeed",1.5),a(this,"rotationStep",30),a(this,"useTeleport",!0),a(this,"usePinchToTeleport",!0),a(this,"useTeleportTarget",!1),a(this,"useTeleportFade",!1),a(this,"showRays",!0),a(this,"showHits",!0),a(this,"isXRMovementHandler",!0),a(this,"xrSessionMode","immersive-vr"),a(this,"_didApplyRotation",!1),a(this,"_didTeleport",!1),a(this,"_teleportBuffer",new Array),a(this,"_plane",null),a(this,"_lines",[]),a(this,"_hitDiscs",[]),a(this,"_hitDistances",[]),a(this,"_lastHitDistances",[]),a(this,"hitPointRaycastFilter",t=>t.type==="SkinnedMesh"?"continue in children":!0)}onUpdateXR(t){const i=t.xr.rig;if(!(i!=null&&i.gameObject)||t.xr.isPassThrough)return;const n=t.xr.leftController,o=t.xr.rightController;n&&this.onHandleMovement(n,i.gameObject),o&&(this.onHandleRotation(o,i.gameObject),this.useTeleport&&this.onHandleTeleport(o,i.gameObject))}onLeaveXR(t){for(const i of this._lines)i.removeFromParent();for(const i of this._hitDiscs)i?.removeFromParent()}onBeforeRender(){var t;(t=this.context.xr)!=null&&t.running&&(this.showRays&&this.renderRays(this.context.xr),this.showHits&&this.renderHits(this.context.xr))}onHandleMovement(t,i){const n=t.getStick("xr-standard-thumbstick");if(n.x!=0||n.y!=0){const o=G(n.x,0,n.y);o.multiplyScalar(this.context.time.deltaTimeUnscaled*this.movementSpeed);const r=Ye(i);o.multiplyScalar(r.x),o.applyQuaternion(t.xr.poseOrientation),o.y=0,o.applyQuaternion(i.worldQuaternion),i.position.add(o),i.updateWorldMatrix(!1,!1);for(const l of i.children)l.updateWorldMatrix(!1,!1)}}onHandleRotation(t,i){if(t._isMxInk)return;const n=t.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=te(this.context.mainCamera).clone();i.rotateY(o*W.toRadians(this.rotationStep));const l=te(this.context.mainCamera).clone().sub(r);l.y=0,i.position.sub(l)}}onHandleTeleport(t,i){var n,o,r,l,c;let h=0;if(t.hand&&this.usePinchToTeleport&&t.isTeleportGesture){const d=t.getPointerId("primary");if(d!=null&&this.context.input.getIsPointerIdInUse(d))return;const u=t.getGesture("pinch");u&&(h=u.value)}else h=(n=t.getStick("xr-standard-thumbstick"))==null?void 0:n.y;if(this._didTeleport)h>=0&&h<.4?this._didTeleport=!1:h<0&&h>-.4&&(this._didTeleport=!1);else if(h>.8){this._didTeleport=!0;const d=this.context.physics.raycastFromRay(t.ray)[0];if(d&&d.object instanceof va){const p=(o=d.normal)==null?void 0:o.dot(G(0,1,0));if(p!==void 0&&p<.4)return}let u=d?.point;if(!u&&!this.useTeleportTarget){this._plane||(this._plane=new nr(new x(0,1,0),0));const p=i.worldPosition;this._plane.setFromNormalAndCoplanarPoint(new x(0,1,0),p);const g=t.ray;u=p.clone(),this._plane.intersectLine(new pC(g.origin,G(g.direction).multiplyScalar(1e4).add(g.origin)),u),u.distanceTo(p)>i.scale.x*10&&(u=null)}if(u){if(this.useTeleportTarget&&!O.getComponentInParent(d.object,cp))return;const p=u.clone();if(m0&&q.DrawSphere(u,.025,16711680,5),(r=this.context.mainCamera)==null?void 0:r.position){const g=(l=this.context.xr)==null?void 0:l.getUserOffsetInRig();g&&(g.y=0,p.sub(g),m0&&q.DrawWireSphere(g.add(p),.025,65280,5))}this._teleportBuffer.push(i.matrix.clone()),this._teleportBuffer.length>10&&this._teleportBuffer.shift(),this.useTeleportFade?(c=t.xr.fadeTransition())==null||c.then(()=>{i.worldPosition=p}):i.worldPosition=p}}else if(h<-.8&&(this._didTeleport=!0,this._teleportBuffer.length>0)){const d=this._teleportBuffer.pop();d&&d.decompose(i.position,i.quaternion,i.scale)}}renderRays(t){var i;for(let n=0;n<this._lines.length;n++){const o=this._lines[n];o&&(o.visible=!1)}for(let n=0;n<t.controllers.length;n++){const o=t.controllers[n];let r=this._lines[n];if(!o.connected||!o.isTracking||!o.ray||o.targetRayMode==="transient-pointer"||!o.hasSelectEvent){r&&(r.visible=!1);continue}r||(r=this.createRayLineObject(),r.scale.z=.5,this._lines[n]=r),o.updateRayWorldPosition(),o.updateRayWorldQuaternion();const l=o.rayWorldPosition,c=o.rayWorldQuaternion;r.position.copy(l),r.quaternion.copy(c);const h=t.rigScale,d=this.usePinchToTeleport&&o.isTeleportGesture,u=this._lastHitDistances[n],p=this._hitDistances[n]!=null,g=u??h;r.scale.set(h,h,g),r.visible=!0,r.layers.disableAll(),r.layers.enable(2);let y=r.material.opacity;d?y=1:this.showHits&&g<t.rigScale*.5?y=0:(i=o.getButton("primary"))!=null&&i.pressed?y=.5:y=p?.2:.1,r.material.opacity=W.lerp(r.material.opacity,y,this.context.time.deltaTimeUnscaled/.1),r.parent!==this.context.scene&&this.context.scene.add(r)}}renderHits(t){var i;for(const n of this._hitDiscs){if(!n)continue;const o=n.controller;if(!o||!o.connected||!o.isTracking){n.visible=!1;continue}}for(let n=0;n<t.controllers.length;n++){const o=t.controllers[n];if(!o.connected||!o.isTracking||!o.ray||!o.hasSelectEvent)continue;let r=this._hitDiscs[n],l=!0;const c=o.getPointerId("primary");c!=null&&this.context.input.getIsPointerIdInUse(c)&&(r&&(r.visible=!1),this._hitDistances[n]=null,this._lastHitDistances[n]=0,l=!1);const h=this.context.time.smoothedFps>=59?1:10;if((this.context.time.frame+o.index)%h!==0&&(l=!1),!l){const p=this._hitDiscs[n];p&&p.visible&&p.hit&&this.updateHitPointerPosition(o,p,p.hit.distance);continue}const d=this.context.physics.raycastFromRay(o.ray,{testObject:this.hitPointRaycastFilter,precise:!1});let u=d.find(p=>this.usePinchToTeleport&&o.isTeleportGesture?!0:this.isObjectWithInteractiveComponent(p.object));if(u||(u=d[0]),r&&(r.controller=o,r.hit=u),this._hitDistances[n]=u?.distance||null,u){this._lastHitDistances[n]=u.distance;const p=t.rigScale??1;m0&&(q.DrawWireSphere(u.point,.025*p,16711680),q.DrawLabel(G(0,.2,0).add(u.point),u.object.name,.02,0)),r||(r=this.createHitPointObject(),this._hitDiscs[n]=r),r.hit=u,r.visible=u.distance>p*.05;let g=.01*(p+u.distance);const y=(i=o.getButton("primary"))==null?void 0:i.pressed;y&&(g*=1.1),r.scale.set(g,g,g),r.layers.set(2);let f=r.material.opacity;if(y?f=1:f=u.distance<.15*p?.2:.6,r.material.opacity=W.lerp(r.material.opacity,f,this.context.time.deltaTimeUnscaled/.1),r.visible){if(u.normal){this.updateHitPointerPosition(o,r,u.distance);const v=u.normal.applyQuaternion(Ce(u.object));r.quaternion.setFromUnitVectors(BT,v)}else this.updateHitPointerPosition(o,r,u.distance);r.parent!==this.context.scene&&this.context.scene.add(r)}}else this._hitDiscs[n]&&(this._hitDiscs[n].visible=!1)}}isObjectWithInteractiveComponent(t,i=0){return Su(t)||t.isUI===!0?!0:t.isScene?!1:t.parent?this.isObjectWithInteractiveComponent(t.parent,i+1):!1}updateHitPointerPosition(t,i,n){const o=G(t.rayWorldPosition);o.add(G(0,0,n-.01).applyQuaternion(t.rayWorldQuaternion)),i.position.lerp(o,this.context.time.deltaTimeUnscaled/.05)}createHitPointObject(){const t=new Y(new nd(.3,6,6),new Re({color:15658734,opacity:.7,transparent:!0,depthTest:!1,depthWrite:!1,side:Si}));return t.layers.disableAll(),t.layers.enable(2),t}createRayLineObject(){const t=new qC;t.layers.disableAll(),t.layers.enable(2);const i=new GC;t.geometry=i;const n=new Float32Array(9);n.set([0,0,.02,0,0,.4,0,0,1]),i.setPositions(n);const o=new Float32Array(9);o.set([1,1,1,.1,.1,.1,0,0,0]),i.setColors(o);const r=new XC({color:16777215,vertexColors:!0,worldUnits:!0,linewidth:.004,transparent:!0,depthWrite:!1,blending:ev,dashed:!1});return t.material=r,t}}Fo([m()],ji.prototype,"movementSpeed",2),Fo([m()],ji.prototype,"rotationStep",2),Fo([m()],ji.prototype,"useTeleport",2),Fo([m()],ji.prototype,"usePinchToTeleport",2),Fo([m()],ji.prototype,"useTeleportTarget",2),Fo([m()],ji.prototype,"useTeleportFade",2),Fo([m()],ji.prototype,"showRays",2),Fo([m()],ji.prototype,"showHits",2);const BT=new x(0,1,0);var FT=Object.defineProperty,zT=Object.getOwnPropertyDescriptor,xt=(s,t,i,n)=>{for(var o=n>1?void 0:n?zT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&FT(t,i,o),o};const uh=C("debugwebxr"),UT=C("debugusdz");var g0;const wl=(g0=class extends A{constructor(){super(...arguments),a(this,"createVRButton",!0),a(this,"createARButton",!0),a(this,"createSendToQuestButton",!0),a(this,"createQRCode",!0),a(this,"useDefaultControls",!0),a(this,"showControllerModels",!0),a(this,"showHandModels",!0),a(this,"usePlacementReticle",!0),a(this,"customARPlacementReticle"),a(this,"usePlacementAdjustment",!0),a(this,"arScale",1),a(this,"useXRAnchor",!1),a(this,"autoPlace",!1),a(this,"autoCenter",!1),a(this,"useQuicklookExport",!1),a(this,"useDepthSensing",!1),a(this,"useSpatialGrab",!0),a(this,"defaultAvatar"),a(this,"_playerSync"),a(this,"_createdComponentsInSession",[]),a(this,"_usdzExporter"),a(this,"_exitXRMenuButton"),a(this,"_previousXRState",0),a(this,"_spatialGrabRaycaster"),a(this,"_activeWebARSessionRoot",null),a(this,"onAvatarSpawned",s=>{uh&&console.log("WebXR.onAvatarSpawned",s),O.getComponentInChildren(s,Do)??(e=O.addComponent(s,Do))}),a(this,"_buttonFactory"),a(this,"_buttons",[])}awake(){J.getXRSync(this.context)}onEnable(){var s,t;window.location.protocol!=="https:"&&we('<a href="https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API" target="_blank">WebXR</a> only works on secure connections (https).'),this.useQuicklookExport&&(O.findObjectOfType($e)||(uh&&console.log("WebXR: Adding USDZExporter"),this._usdzExporter=O.addComponent(this.gameObject,$e),this._usdzExporter.objectToExport=this.context.scene,this._usdzExporter.autoExportAnimations=!0,this._usdzExporter.autoExportAudioSources=!0)),this.handleCreatingHTML(),this.handleOfferSession(),this.defaultAvatar===!0&&(uh&&console.warn("WebXR: No default avatar set, using static default avatar"),this.defaultAvatar=new le("https://cdn.needle.tools/static/avatars/DefaultAvatar.glb")),this.defaultAvatar&&(this._playerSync=this.gameObject.getOrAddComponent(bl),this._playerSync.autoSync=!1),this._playerSync&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,(s=this._playerSync.onPlayerSpawned)==null||s.removeEventListener(this.onAvatarSpawned),(t=this._playerSync.onPlayerSpawned)==null||t.addEventListener(this.onAvatarSpawned))}onDisable(){var s;(s=this._usdzExporter)==null||s.destroy(),this.removeButtons()}async handleOfferSession(){return this.createVRButton&&await J.isVRSupported()&&this.createVRButton?J.offerSession("immersive-vr","default",this.context):this.createARButton&&await J.isARSupported()&&this.createARButton?J.offerSession("immersive-ar","default",this.context):!1}get session(){return J.active??null}get sessionMode(){return J.activeMode??null}get arSessionRoot(){return this._activeWebARSessionRoot}async enterVR(s){return J.start("immersive-vr",s,this.context)}async enterAR(s){return J.start("immersive-ar",s,this.context)}exitXR(){J.stop()}get isActiveWebXR(){return!wl.activeWebXRComponent||wl.activeWebXRComponent===this}onBeforeXR(s,t){var i;if(!this.isActiveWebXR){console.warn(`WebXR: another WebXR component is already active (${(i=wl.activeWebXRComponent)==null?void 0:i.name}). This is ignored: ${this.name}`);return}wl.activeWebXRComponent=this,s=="immersive-ar"&&this.useDepthSensing&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("depth-sensing"))}async onEnterXR(s){if(!this.isActiveWebXR)return;uh&&console.log("WebXR onEnterXR"),this._previousXRState=ci.Global.Mask;const t=s.xr.isVR;if(ci.Global.Set(t?Ys.VR:Ys.AR),s.xr.isAR){let i=O.findObjectOfType(sn);if(!i)if(this.usePlacementReticle){const n=new I;for(const o of this.context.scene.children)n.add(o);this.context.scene.add(n),i=O.addComponent(n,sn),this._createdComponentsInSession.push(i)}else(uh||F())&&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=O.findObjectOfType(Va)??void 0,this._spatialGrabRaycaster||(this._spatialGrabRaycaster=this.gameObject.addComponent(Va))),this.createLocalAvatar(s.xr),s.xr.isScreenBasedAR||(this._exitXRMenuButton=this.context.menu.appendChild({label:"Quit XR",onClick:()=>this.exitXR(),icon:"exit_to_app",priority:2e4}))}onUpdateXR(s){this.isActiveWebXR&&this._spatialGrabRaycaster&&(this._spatialGrabRaycaster.enabled=this.useSpatialGrab)}onLeaveXR(s){var t,i;if((t=this._exitXRMenuButton)==null||t.remove(),!!this.isActiveWebXR){ci.Global.Set(this._previousXRState),(i=this._playerSync)==null||i.destroyInstance();for(const n of this._createdComponentsInSession)n.destroy();this._createdComponentsInSession.length=0,this._activeWebARSessionRoot=null,this.handleOfferSession(),Kl(1).then(()=>wl.activeWebXRComponent=null)}}setDefaultMovementEnabled(s){let t=this.gameObject.getComponent(ji);return!t&&s&&(t=this.gameObject.addComponent(ji),this._createdComponentsInSession.push(t)),t&&(t.enabled=s),t}setDefaultControllerRenderingEnabled(s){let t=this.gameObject.getComponent(on);return!t&&s&&(t=this.gameObject.addComponent(on),this._createdComponentsInSession.push(t),t.createControllerModel=this.showControllerModels,t.createHandModel==this.showHandModels),t&&(t.enabled=s),t}async createLocalAvatar(s){this._playerSync&&s.running&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,await this._playerSync.getInstance())}getButtonsContainer(){return this.getButtonsFactory()}getButtonsFactory(){return this._buttonFactory||(this._buttonFactory=zr.getOrCreate()),this._buttonFactory}handleCreatingHTML(){if(this.createARButton||this.createVRButton||this.useQuicklookExport){if((X.isiOS()&&X.isSafari()||UT)&&this.useQuicklookExport){const s=O.findObjectOfType($e);if(!s||s&&s.allowCreateQuicklookButton){const t=this.getButtonsFactory().createQuicklookButton();this.addButton(t,50)}}if(this.createARButton){const s=this.getButtonsFactory().createARButton();this.addButton(s,50)}if(this.createVRButton){const s=this.getButtonsFactory().createVRButton();this.addButton(s,50)}}if(this.createSendToQuestButton&&!X.isQuest()&&J.isVRSupported().then(s=>{if(!s){const t=this.getButtonsFactory().createSendToQuestButton();this.addButton(t,50)}}),this.createQRCode){const s=kc(nn);if(s&&s.createQRCodeButton===!1)F()&&console.warn("WebXR: QRCode button is disabled in the Needle Menu component");else if(!X.isMobileDevice()){const t=kn.getOrCreate().createQRCode();this.addButton(t,50)}}}addButton(s,t){this._buttons.push(s),s.setAttribute("priority",t.toString()),this.context.menu.appendChild(s)}removeButtons(){for(const s of this._buttons)s.remove();this._buttons.length=0}},a(g0,"activeWebXRComponent",null),g0);let Je=wl;xt([m()],Je.prototype,"createVRButton",2),xt([m()],Je.prototype,"createARButton",2),xt([m()],Je.prototype,"createSendToQuestButton",2),xt([m()],Je.prototype,"createQRCode",2),xt([m()],Je.prototype,"useDefaultControls",2),xt([m()],Je.prototype,"showControllerModels",2),xt([m()],Je.prototype,"showHandModels",2),xt([m()],Je.prototype,"usePlacementReticle",2),xt([m(le)],Je.prototype,"customARPlacementReticle",2),xt([m()],Je.prototype,"usePlacementAdjustment",2),xt([m()],Je.prototype,"arScale",2),xt([m()],Je.prototype,"useXRAnchor",2),xt([m()],Je.prototype,"autoPlace",2),xt([m()],Je.prototype,"autoCenter",2),xt([m()],Je.prototype,"useQuicklookExport",2),xt([m()],Je.prototype,"useDepthSensing",2),xt([m()],Je.prototype,"useSpatialGrab",2),xt([m(le)],Je.prototype,"defaultAvatar",2);const hp=C("debugusdzbehaviours");class f0{constructor(){a(this,"behaviours",[]),a(this,"behaviourComponents",[]),a(this,"behaviourComponentsCopy",[]),a(this,"audioClips",[]),a(this,"audioClipsCopy",[]),a(this,"targetUuids",new Set)}get extensionName(){return"Behaviour"}addBehavior(t){this.behaviours.push(t)}addAudioClip(t){if(!t||typeof t!="string")return"";const i="audio/"+da.getName(t);return this.audioClips.push({clipUrl:t,filesKey:i}),i}getAllTargetUuids(){return this.targetUuids}onBeforeBuildDocument(t){if(!t.root)return Promise.resolve();const i=[];return t.root.traverse(n=>{O.foreachComponent(n,o=>{var r;const l=o;if(typeof l.createBehaviours=="function"||typeof l.beforeCreateDocument=="function"||typeof l.afterCreateDocument=="function"||typeof l.afterSerialize=="function"){this.behaviourComponents.push(l);const c=(r=l.beforeCreateDocument)==null?void 0:r.call(l,this,t);c instanceof Promise&&i.push(c)}},!1)}),hp&&console.log("onBeforeBuildDocument: all components",this.behaviourComponents),Promise.all(i)}onExportObject(t,i,n){var o;for(const r of this.behaviourComponents)(o=r.createBehaviours)==null||o.call(r,this,i,n)}onAfterBuildDocument(t){for(const p of this.behaviourComponents)typeof p.afterCreateDocument=="function"&&p.afterCreateDocument(this,t);this.behaviourComponentsCopy=this.behaviourComponents.slice(),this.behaviourComponents.length=0,this.audioClipsCopy=this.audioClips.slice(),this.audioClips.length=0;const i=new Set,n=new Set,o=new Set,r=new Set,l=hp;let c=`graph LR
1203
+ `))}for(const H of E){const ie=l.get(H);ie&&z.set(H,ie)}return z},f=function(E){const z=y(E),H=d(z);return u(z,H,E)};const v=r.skinnedMesh.skeleton,b=new Array,w=[],_=[];for(const E of v.bones){w.push(E),_.push(E.uuid);const z=v.boneInverses[v.bones.indexOf(E)];b.push({bone:E,inverse:z})}let S=1e4;for(;_.length<v.bones.length&&S-- >0;)for(const E of w){const z=E.children;for(const H of z)if(_.indexOf(H.uuid)===-1&&v.bones.indexOf(H)!==-1){w.push(H),_.push(H.uuid);const ie=v.boneInverses[v.bones.indexOf(H)];b.push({bone:H,inverse:ie})}}S<=0&&console.error("Failed to sort bones in skinned mesh",r.skinnedMesh,v.bones,_);for(const E of bx(v.bones))b.push({bone:E,inverse:E.matrixWorld.clone().invert()});const R=b[0].bone.parent;R||console.error("No bone parent found for skinned mesh during USDZ export",r.skinnedMesh),b.sort((E,z)=>hl(E.bone,R)>hl(z.bone,R)?1:-1);const M=i.quickLookCompatible,T=[],L=[],D=[],U=[];for(const{bone:E}of b){if(M){const z=E.scale;z.x==0&&(z.x=1e-5),z.y==0&&(z.y=1e-5),z.z==0&&(z.z=1e-5),T.push(new ne().compose(E.position,E.quaternion,E.scale))}else T.push(E.matrix.clone());L.push(E.position),D.push(E.quaternion),U.push(E.scale)}const B=b.map(E=>'"'+hl(E.bone,R)+'"').join(", "),Q=b.map(E=>Tx(E.inverse.clone().invert())).join(", ");t.beginBlock('def Skeleton "Rig"'),t.appendLine(`uniform matrix4d[] bindTransforms = [${Q}]`),t.appendLine(`uniform token[] joints = [${B}]`),t.appendLine('uniform token purpose = "guide"'),t.appendLine(`uniform matrix4d[] restTransforms = [${T.map(E=>Tx(E)).join(", ")}]`);const $=f(b.map(E=>E.bone));if(en){let E=1e7,z=0;for(const H of((o=$.position)==null?void 0:o.keys())??[])E=Math.min(E,H),z=Math.max(z,H);console.log("Time samples",E,z,$)}if(t.beginBlock('def SkelAnimation "_anim"'),t.appendLine(`uniform token[] joints = [${B}]`),t.appendLine(`quatf[] rotations = [${g(D)}]`),$&&$.quaternion){t.beginBlock("quatf[] rotations.timeSamples = {","");const E=h($.quaternion);for(const z of E)t.appendLine(z);t.closeBlock()}if(t.appendLine(`half3[] scales = [${p(U)}]`),$&&$.scale){t.beginBlock("half3[] scales.timeSamples = {","");const E=c($.scale);for(const z of E)t.appendLine(z);t.closeBlock()}if(t.appendLine(`float3[] translations = [${p(L)}]`),$&&$.position){t.beginBlock("float3[] translations.timeSamples = {","");const E=c($.position);for(const z of E)t.appendLine(z);t.closeBlock()}t.closeBlock(),t.closeBlock()}}onSerialize(t,i){if(!this.model)return;const n=this.animationData.get(this.object);if(n)for(let u=0;u<n.length;u++)n[u]===void 0&&(n[u]=new Ke(null,this.object,null));const o=this.ext;this.skinnedMeshExport(t,i,o);const r=this.object,l=this.model,c=this.animationData.get(r);if(!c||r.isSkinnedMesh)return;n0&&console.log("SERIALIZE",this.model.name,this.object.type,c);const h=Intl.NumberFormat("en-US",{maximumFractionDigits:3,minimumFractionDigits:0,useGrouping:!1});function d(u,p){var g;if(u.some(y=>y&&{position:y.pos,rotation:y.rot,scale:y.scale}[p])){switch(p){case"position":l.needsTranslate=!0,t.beginBlock("double3 xformOp:translate.timeSamples = {","");break;case"rotation":l.needsOrient=!0,t.beginBlock("quatf xformOp:orient.timeSamples = {","");break;case"scale":l.needsScale=!0,t.beginBlock("double3 xformOp:scale.timeSamples = {","");break}for(let y=0;y<u.length;y++){const f=u[y];if(!f)continue;const v=o.getStartTimeByClip(f.clip),b=f.getSortedTimesArray(p==="position",p==="rotation",p==="scale");if(!b||b.length===0){console.error("got an animated object but no time values?",r,f);continue}const w=!f.clip,_=p==="position"&&(f.pos||w),S=p==="rotation"&&(f.rot||w),R=p==="scale"&&(f.scale||w);if(_||S||R){const M=((g=f.clip)==null?void 0:g.name)??"rest",T=f.getDuration();en&&console.log("Write .timeSamples:",M,v,T,u),t.appendLine("# "+M+": start="+h.format(v*Ke.frameRate)+", length="+h.format(T*Ke.frameRate)+", frames="+f.getFrames())}if(_)for(const{time:M,translation:T}of f.getValues(b,!0,!1,!1)){const L=`${h.format((v+M)*Ke.frameRate)}: (${he(T.x)}, ${he(T.y)}, ${he(T.z)}),`;t.appendLine(L)}if(S)for(const{time:M,rotation:T}of f.getValues(b,!1,!0,!1)){const L=`${h.format((v+M)*Ke.frameRate)}: (${he(T.w)}, ${he(T.x)}, ${he(T.y)}, ${he(T.z)}),`;t.appendLine(L)}if(R)for(const{time:M,scale:T}of f.getValues(b,!1,!1,!0)){const L=`${h.format((v+M)*Ke.frameRate)}: (${he(T.x)}, ${he(T.y)}, ${he(T.z)}),`;t.appendLine(L)}}t.closeBlock()}}d(c,"position"),d(c,"rotation"),d(c,"scale")}}const mT=C("debugusdz");class da{constructor(){a(this,"files",new Array)}static getName(t){var i;const n=t.split(".").pop();let o=(i=t.split(".").slice(0,-1).join(".").split("/").pop())==null?void 0:i.replace(".","_");return o||(o="Audio_"+Math.random().toString(36).substring(2,15)),Rs(o)+"."+n}get extensionName(){return"Audio"}onExportObject(t,i,n){const o=O.getComponents(t,Ne);if(o.length)for(const r of o){if(!r.clip||typeof r.clip!="string"||!r.playOnAwake)continue;const l=r.clip.split("/").pop()||"Audio",c=da.getName(r.clip),h=Rs(c);if(!this.files.some(d=>d.path===r.clip)){this.files.push({path:r.clip,name:c});const d=c.toLowerCase();n.quickLookCompatible&&!d.endsWith(".mp3")&&!d.endsWith(".wav")&&!d.endsWith(".m4a")&&console.error("Audio file "+r.clip+" from "+r.name+" is not an MP3 or WAV file. QuickLook may not support playing it.")}n.quickLookCompatible||i.addEventListener("serialize",(d,u)=>{d.appendLine(),d.beginBlock(`def SpatialAudio "${h}"`,"(",!1),d.appendLine(`displayName = "${l}"`),d.closeBlock(")"),d.beginBlock(),d.appendLine(`uniform asset filePath = @audio/${c}@`),d.appendLine(`uniform token auralMode = "${r.spatialBlend>0?"spatial":"nonSpatial"}"`),d.appendLine(`uniform token playbackMode = "${r.loop?"loopFromStage":"onceFromStart"}"`),d.appendLine(`uniform float gain = ${r.volume}`),d.closeBlock()})}}async onAfterSerialize(t){for(const i of this.files){const n="audio/"+i.name;if(t.files[n]){mT&&console.warn("Audio file with name "+n+" already exists in the context. Skipping.");continue}const o=await(await(await fetch(i.path)).blob()).arrayBuffer(),r=new Uint8Array(o);t.files[n]=r}}}var gT=Object.defineProperty,fT=Object.getOwnPropertyDescriptor,Ve=(s,t,i,n)=>{for(var o=n>1?void 0:n?fT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&gT(t,i,o),o};const Ux=C("debugusdzbehaviours");function nh(s){s&&(s.getComponentInParent(Wa)||(F()&&console.debug('Raycaster on "'+s.name+'" was automatically added, because no raycaster was found in the parent hierarchy.'),s.addComponent(Ei)))}class Dr extends A{constructor(){super(...arguments),a(this,"object"),a(this,"target"),a(this,"duration",1),a(this,"relativeMotion",!1),a(this,"coroutine",null),a(this,"targetPos",new x),a(this,"targetRot",new V),a(this,"targetScale",new x)}start(){nh(this.gameObject)}onPointerClick(t){t.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 t=te(this.object).clone(),i=te(this.target).clone(),n=Ce(this.object).clone(),o=Ce(this.target).clone(),r=Ye(this.object).clone(),l=Ye(this.target).clone(),c=t.distanceTo(i),h=n.angleTo(o),d=r.distanceTo(l);if(c<.01&&h<.01&&d<.01){ht(this.object,i),Hi(this.object,o),wa(this.object,l),this.coroutine=null;return}let u=0,p=0;for(;u<1;)u+=this.context.time.deltaTime/this.duration,u>1&&(u=1),p=u<.5?4*u*u*u:1-Math.pow(-2*u+2,3)/2,this.targetPos.lerpVectors(t,i,p),this.targetRot.slerpQuaternions(n,o,p),this.targetScale.lerpVectors(r,l,p),ht(this.object,this.targetPos),Hi(this.object,this.targetRot),wa(this.object,this.targetScale),yield;this.coroutine=null}*moveRelative(){if(!this.target||!this.object)return;const t=this.object.position.clone(),i=this.object.quaternion.clone(),n=this.object.scale.clone(),o=this.target.position.clone(),r=this.target.quaternion.clone(),l=this.target.scale.clone();o.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(o),this.targetRot.copy(this.object.quaternion).multiply(r),this.targetScale.copy(this.object.scale).multiply(l);let c=0,h=0;for(;c<1;)c+=this.context.time.deltaTime/this.duration,c>1&&(c=1),h=c<.5?4*c*c*c:1-Math.pow(-2*c+2,3)/2,this.object.position.lerpVectors(t,this.targetPos,h),this.object.quaternion.slerpQuaternions(i,this.targetRot,h),this.object.scale.lerpVectors(n,this.targetScale,h),yield;this.coroutine=null}beforeCreateDocument(t){var i;if(this.target&&this.object&&this.gameObject){const n=new Nt("Move to "+((i=this.target)==null?void 0:i.name),Rt.tapTrigger(this.gameObject),ve.transformAction(this.object,this.target,this.duration,this.relativeMotion?"relative":"absolute"));t.addBehavior(n)}}}Ve([m(I)],Dr.prototype,"object",2),Ve([m(I)],Dr.prototype,"target",2),Ve([m()],Dr.prototype,"duration",2),Ve([m()],Dr.prototype,"relativeMotion",2);var ul;const Jt=(ul=class extends A{constructor(){super(...arguments),a(this,"materialToSwitch"),a(this,"variantMaterial"),a(this,"fadeDuration",0),a(this,"_objectsWithThisMaterial",null),a(this,"selfModel"),a(this,"targetModels")}start(){var s;this._objectsWithThisMaterial=this.objectsWithThisMaterial,nh(this.gameObject),F()&&this._objectsWithThisMaterial.length<=0&&console.warn('ChangeMaterialOnClick: No objects found with material "'+((s=this.materialToSwitch)==null?void 0:s.name)+'"')}onPointerEnter(s){this.context.input.setCursor("pointer")}onPointerExit(s){this.context.input.unsetCursor("pointer")}onPointerClick(s){if(s.use(),!!this.variantMaterial)for(let t=0;t<this.objectsWithThisMaterial.length;t++){const i=this.objectsWithThisMaterial[t];i.material=this.variantMaterial}}get objectsWithThisMaterial(){return this._objectsWithThisMaterial!=null?this._objectsWithThisMaterial:(this._objectsWithThisMaterial=[],this.variantMaterial&&this.materialToSwitch&&this.context.scene.traverse(s=>{if(s instanceof Y)if(Array.isArray(s.material)){for(const t of s.material)if(t===this.materialToSwitch){this.objectsWithThisMaterial.push(s);break}}else s.material===this.materialToSwitch?this.objectsWithThisMaterial.push(s):p_(s.material,this.materialToSwitch)&&this.objectsWithThisMaterial.push(s)}),this._objectsWithThisMaterial)}async beforeCreateDocument(s,t){this.targetModels=[],Jt._materialTriggersPerId={},Jt.variantSwitchIndex=0,this.materialToSwitch&&await it.assignTextureLOD(this.materialToSwitch,0),this.variantMaterial&&await it.assignTextureLOD(this.variantMaterial,0)}createBehaviours(s,t,i){this.objectsWithThisMaterial.find(n=>n.uuid===t.uuid)&&this.targetModels.push(t),this.gameObject.uuid===t.uuid&&(this.selfModel=t,this.materialToSwitch&&(Jt._materialTriggersPerId[this.materialToSwitch.uuid]||(Jt._materialTriggersPerId[this.materialToSwitch.uuid]=[]),Jt._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(s,t){if(!this.materialToSwitch)return;const i=Jt._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 l in n)l!==o.selfModel.uuid&&r.push(...n[l]);o.createAndAttachBehaviors(s,n[o.selfModel.uuid],r)}}delete Jt._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(s,t,i){const n=[],o=Math.max(0,this.fadeDuration);n.push(ve.fadeAction([...this.targetModels,...i],o,!1)),n.push(ve.fadeAction(t,o,!0)),s.addBehavior(new Nt("Select_"+this.selfModel.name,Rt.tapTrigger(this.selfModel),ve.parallel(...n))),Jt._parallelStartHiddenActions.push(...t),Jt._startHiddenBehaviour||(Jt._startHiddenBehaviour=new Nt("StartHidden_"+this.selfModel.name,Rt.sceneStartTrigger(),ve.fadeAction(Jt._parallelStartHiddenActions,o,!1)),s.addBehavior(Jt._startHiddenBehaviour))}static getMaterialName(s){return Rs(s.name||"Material")+"_"+s.id}createVariants(){if(!this.variantMaterial)return null;const s=[];for(const t of this.targetModels){const i=t.clone();i.name+="_Variant_"+Jt.variantSwitchIndex+++"_"+Jt.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())&&Yt.createEmptyParent(t),t.parent&&t.parent.add(i),s.push(i)}return s}},a(ul,"_materialTriggersPerId",{}),a(ul,"_startHiddenBehaviour",null),a(ul,"_parallelStartHiddenActions",[]),a(ul,"variantSwitchIndex",0),ul);let pl=Jt;Ve([m(ke)],pl.prototype,"materialToSwitch",2),Ve([m(ke)],pl.prototype,"variantMaterial",2),Ve([m()],pl.prototype,"fadeDuration",2);var ml;const He=(ml=class extends A{constructor(){super(...arguments),a(this,"target"),a(this,"toggleOnClick",!1),a(this,"targetState",!0),a(this,"hideSelf",!0),a(this,"selfModel"),a(this,"selfModelClone"),a(this,"targetModel"),a(this,"toggleModel"),a(this,"stateBeforeCreatingDocument",!1),a(this,"targetStateBeforeCreatingDocument",!1)}start(){nh(this.gameObject)}onPointerClick(s){s.use(),!this.toggleOnClick&&this.hideSelf&&(this.gameObject.visible=!1),this.target&&(this.target.visible=this.toggleOnClick?!this.target.visible:this.targetState)}createBehaviours(s,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t,this.selfModelClone=t.clone())}beforeCreateDocument(){this.target&&(this.gameObject[He.wasVisible]===void 0&&(this.gameObject[He.wasVisible]=this.gameObject.activeSelf),this.target[He.wasVisible]===void 0&&(this.target[He.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[He.wasVisible],this.targetStateBeforeCreatingDocument=this.target[He.wasVisible],this.gameObject.visible=!0,this.target.visible=!0)}afterCreateDocument(s,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())&&Gf.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[He.toggleClone]){const c=this.selfModelClone.clone();c.setMatrix(new ne),c.name+="_toggle"+He.clonedToggleIndex++,i.add(c),this.gameObject[He.toggleClone]=c,console.warn("USDZExport: Toggle "+this.gameObject.name+" doesn't have geometry. It will be deep cloned and nested behaviours will likely not work.")}const l=this.gameObject[He.toggleClone];if(!this.gameObject[He.reverseToggleClone]){const c=this.selfModelClone.clone();c.setMatrix(new ne),c.name+="_toggleReverse"+He.clonedToggleIndex++,i.add(c),this.gameObject[He.reverseToggleClone]=c}this.toggleModel=this.gameObject[He.reverseToggleClone],(!this.toggleModel.geometry||!l.geometry)&&console.error("triggers without childs and without geometry won't work!",this,i.geometry),n=l,i.geometry=null,i.material=null}if(this.toggleModel){if(this.toggleOnClick){const l=[];l.push(ve.fadeAction(n,0,!1)),l.push(ve.fadeAction(this.toggleModel,0,!0)),l.push(ve.fadeAction(this.targetModel,0,o)),s.addBehavior(new Nt("Toggle_"+n.name+"_ToggleTo"+(o?"On":"Off"),Rt.tapTrigger(n),ve.parallel(...l)));const c=[];c.push(ve.fadeAction(this.toggleModel,0,!1)),c.push(ve.fadeAction(n,0,!0)),c.push(ve.fadeAction(this.targetModel,0,!o)),s.addBehavior(new Nt("Toggle_"+n.name+"_ToggleTo"+(o?"Off":"On"),Rt.tapTrigger(this.toggleModel),ve.parallel(...c)))}}else{const l=[];this.hideSelf&&l.push(ve.fadeAction(n,0,!1)),l.push(ve.fadeAction(this.targetModel,0,o)),s.addBehavior(new Nt("Toggle_"+n.name+"_ToggleTo"+(o?"On":"Off"),Rt.tapTrigger(n),l.length>1?ve.parallel(...l):l[0]))}const r=new Array;this.targetStateBeforeCreatingDocument||r.push(this.targetModel),this.stateBeforeCreatingDocument||r.push(i),this.toggleModel&&r.push(this.toggleModel),gl.add(r,s)}}afterSerialize(s,t){this.gameObject[He.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[He.wasVisible],delete this.gameObject[He.wasVisible]),this.target&&this.target[He.wasVisible]!==void 0&&(this.target.visible=this.target[He.wasVisible],delete this.target[He.wasVisible]),delete this.gameObject[He.toggleClone],delete this.gameObject[He.reverseToggleClone]}},a(ml,"clonedToggleIndex",0),a(ml,"wasVisible",Symbol("usdz_SetActiveOnClick_wasVisible")),a(ml,"toggleClone",Symbol("clone for toggling")),a(ml,"reverseToggleClone",Symbol("clone for reverse toggling")),ml);let Br=He;Ve([m(I)],Br.prototype,"target",2),Ve([m()],Br.prototype,"toggleOnClick",2),Ve([m()],Br.prototype,"targetState",2),Ve([m()],Br.prototype,"hideSelf",2);const Ao=class extends A{constructor(){super(...arguments),a(this,"wasVisible",!1)}static add(s,t){const i=Array.isArray(s)?s:[s];for(const n of i)Ao._fadeObjects.includes(n)||(console.log("adding hide on start",n),Ao._fadeObjects.push(n));Ao._fadeBehaviour===void 0&&(Ao._fadeBehaviour=new Nt("HideOnStart",Rt.sceneStartTrigger(),ve.fadeAction(Ao._fadeObjects,0,!1)),t.addBehavior(Ao._fadeBehaviour))}start(){O.setActive(this.gameObject,!1)}createBehaviours(s,t,i){t.uuid===this.gameObject.uuid&&(this.wasVisible||Ao.add(t,s))}beforeCreateDocument(){this.wasVisible=O.isActiveSelf(this.gameObject)}};let gl=Ao;a(gl,"_fadeBehaviour"),a(gl,"_fadeObjects",[]);class fl extends A{constructor(){super(...arguments),a(this,"target"),a(this,"duration",.5),a(this,"motionType","bounce")}beforeCreateDocument(){}createBehaviours(t,i,n){if(this.target&&i.uuid===this.gameObject.uuid){const o=new Nt("emphasize "+this.name,Rt.tapTrigger(this.gameObject),ve.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));t.addBehavior(o)}}afterCreateDocument(t,i){}}Ve([m()],fl.prototype,"target",2),Ve([m()],fl.prototype,"duration",2),Ve([m()],fl.prototype,"motionType",2);class Io extends A{constructor(){super(...arguments),a(this,"target"),a(this,"clip",""),a(this,"toggleOnClick",!1),a(this,"trigger","tap")}start(){nh(this.gameObject)}ensureAudioSource(){if(!this.target){const t=this.gameObject.addComponent(Ne);t&&(this.target=t,t.spatialBlend=1,t.volume=1,t.loop=!1,t.preload=!0)}}onPointerClick(t){var i;t.use(),!(!((i=this.target)!=null&&i.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(t,i,n){if(!(!this.target&&!this.clip)&&i.uuid===this.gameObject.uuid){const o=this.clip?this.clip:this.target?this.target.clip:void 0;if(!o||typeof o!="string")return;const r=this.target?this.target.gameObject:this.gameObject;da.getName(o);const l=this.target?this.target.volume:1,c=this.target&&this.target.spatialBlend==0?"nonSpatial":"spatial";let h=!1;this.gameObject.traverse(g=>{g instanceof Y&&g.visible&&(h=!0)}),h=!0;const d=t.addAudioClip(o);let u=ve.playAudioAction(r,d,"play",l,c);this.target&&this.target.loop&&(u=ve.sequence(u).makeLooping());const p=this.name?"_"+this.name:"";if(h&&this.trigger==="tap"){this.toggleOnClick&&(u.multiplePerformOperation="stop");const g=new Nt("playAudio"+p,Rt.tapTrigger(i),u);t.addBehavior(g)}if(this.target&&this.target.playOnAwake&&this.target.enabled)if(h&&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 g=new Nt("playAudioOnStart"+p,Rt.sceneStartTrigger(),u);t.addBehavior(g)}}}}Ve([m(Ne)],Io.prototype,"target",2),Ve([m(URL)],Io.prototype,"clip",2),Ve([m()],Io.prototype,"toggleOnClick",2);var np;const tn=(np=class extends A{constructor(){super(...arguments),a(this,"animator"),a(this,"stateName"),a(this,"trigger","tap"),a(this,"animation"),a(this,"selfModel"),a(this,"stateAnimationModel"),a(this,"animationSequence",new Array),a(this,"animationLoopAfterSequence",new Array),a(this,"randomOffsetNormalized",0)}get target(){var s,t;return((s=this.animator)==null?void 0:s.gameObject)||((t=this.animation)==null?void 0:t.gameObject)}start(){nh(this.gameObject)}onPointerClick(s){var t;s.use(),this.target&&this.stateName&&((t=this.animator)==null||t.play(this.stateName,0,0,.1))}createBehaviours(s,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t)}afterSerialize(){if(tn.rootsWithExclusivePlayback.size>1){const s='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.';F()&&we(s),console.warn(s,...tn.rootsWithExclusivePlayback)}tn.animationActions=[],tn.rootsWithExclusivePlayback=new Set}afterCreateDocument(s,t){if(this.animationSequence===void 0&&this.animationLoopAfterSequence===void 0||!this.stateAnimationModel||!this.target)return;const i=t.document,n=t.extensions.find(l=>l instanceof sp);if(!n)return;const o=n.getClipCount(this.target)>1;o&&(F()&&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."),tn.rootsWithExclusivePlayback.add(this.target));const r=this.name?this.name:"";i.traverse(l=>{var c,h;if(l.uuid===((c=this.target)==null?void 0:c.uuid)){const d=tn.getActionForSequences(i,l,this.animationSequence,this.animationLoopAfterSequence,this.randomOffsetNormalized),u=new Nt(this.trigger+"_"+r+"_toPlayAnimation_"+this.stateName+"_on_"+((h=this.target)==null?void 0:h.name),this.trigger=="tap"?Rt.tapTrigger(this.selfModel):Rt.sceneStartTrigger(),d);o&&u.makeExclusive(!0),s.addBehavior(u)}})}static getActionForSequences(s,t,i,n,o){const r=(c,h)=>{let d=tn.animationActions.find(u=>u.affectedObjects==c&&u.start==h.start&&u.duration==h.duration&&u.animationSpeed==h.speed);return d||(d=ve.startAnimationAction(c,h),tn.animationActions.push(d)),d},l=ve.sequence();if(i&&i.length>0)for(const c of i)l.addAction(r(t,c));if(n&&n.length>0){const c=l.actions.length==0?l:ve.sequence();for(const h of n)c.addAction(r(t,h));c.makeLooping(),l!==c&&l.addAction(c)}return o&&o>0&&l.actions.unshift(ve.waitAction(o)),l}static getAndRegisterAnimationSequences(s,t,i){var n,o,r,l,c,h,d,u;if(!t)return;const p=t.getComponent(Pt),g=t.getComponent(zt);if(!p&&!g)return;if(p&&!i)throw new Error("PlayAnimationOnClick: No stateName specified for animator "+p.name+" on "+t.name);let y=[],f=[];if(g){const M=s.registerAnimation(t,g.clip);M&&(g.loop?f.push(M):y.push(M));let T=0;if(g.minMaxOffsetNormalized){const L=g.minMaxOffsetNormalized.x,D=g.minMaxOffsetNormalized.y;T=(((n=g.clip)==null?void 0:n.duration)||1)*(L+Math.random()*(D-L))}return{animationSequence:y,animationLoopAfterSequence:f,randomTimeOffset:T}}const v=p?.runtimeAnimatorController;let b=v?.findState(i),w=[],_=[];if(v&&b){const M=new Array;M.push(b);let T=!1;for(;M.length<100;){if(!b||b===null||!b.transitions||b.transitions.length===0){(o=b.motion)!=null&&o.isLooping&&(T=!0);break}const L=b.transitions.find(U=>U.conditions.length===0),D=L?v.getState(L.destinationState,0):null;if(D&&M.includes(D)){b=D,T=!0;break}else if(L){if(b=D,!b)break;M.push(b)}else{T=((r=b.motion)==null?void 0:r.isLooping)??!1;break}}if(T&&b){const L=M.indexOf(b);w=M.slice(0,L),_=M.slice(L),Ux&&console.log("found loop from "+i,"states until loop",w,"states looping",_)}else w=M,_=[],Ux&&console.log("found no loop from "+i,"states",w);if(!_.length){const L=w[w.length-1],D=(l=L.motion)==null?void 0:l.clip;if(D){let U;if(s.holdClipMap.has(D))U=s.holdClipMap.get(D);else{const B=L.name+"_hold";U=D.clone(),U.duration=1,U.name=B;const Q=D.duration;U.tracks=D.tracks.map($=>{const E=$.clone();E.times=new Float32Array([0,Q]);const z=$.values.length,H=$.getValueSize(),ie=$.values.slice(z-H,z);return E.values=new Float32Array(2*H),E.values.set(ie,0),E.values.set(ie,H),E}),U.name=B,s.holdClipMap.set(D,U)}if(U){const B={name:U.name,motion:{clip:U,isLooping:!1,name:U.name},speed:1,transitions:[],behaviours:[],hash:L.hash+1};_.push(B)}}}}if(w.length===1&&(!((c=w[0].motion)!=null&&c.clip)||((d=(h=w[0].motion)==null?void 0:h.clip.tracks)==null?void 0:d.length)===0)){y=new Array;const M=s.registerAnimation(t,null);M&&y.push(M);return}if(w=w.filter(M=>{var T,L,D;return((T=M.motion)==null?void 0:T.clip)&&((D=(L=M.motion)==null?void 0:L.clip.tracks)==null?void 0:D.length)>0}),_=_.filter(M=>{var T,L,D;return((T=M.motion)==null?void 0:T.clip)&&((D=(L=M.motion)==null?void 0:L.clip.tracks)==null?void 0:D.length)>0}),w.length===0&&_.length===0){console.warn("No clips found for state "+i+" on "+p?.name+", can't export animation data");return}const S=(M,T)=>{if(!t)return;const L=s.registerAnimation(t,M.motion.clip??null);L?(L.speed=M.speed,T.push(L)):console.warn("Couldn't register animation for state "+M.name+" on "+p?.name)};if(w.length>0){y=new Array;for(const M of w)S(M,y)}if(_.length>0){f=new Array;for(const M of _)S(M,f)}let R=0;if(p&&v&&p.minMaxOffsetNormalized){const M=p.minMaxOffsetNormalized.x,T=p.minMaxOffsetNormalized.y,L=w.length?w[0]:_.length?_[0]:null;R=(((u=L?.motion.clip)==null?void 0:u.duration)||1)*(M+Math.random()*(T-M))}return{animationSequence:y,animationLoopAfterSequence:f,randomTimeOffset:R}}createAnimation(s,t,i){if(!this.target||!this.animator&&!this.animation)return;const n=tn.getAndRegisterAnimationSequences(s,this.target,this.stateName);n&&(this.animationSequence=n.animationSequence,this.animationLoopAfterSequence=n.animationLoopAfterSequence,this.randomOffsetNormalized=n.randomTimeOffset,this.stateAnimationModel=t)}},a(np,"animationActions",[]),a(np,"rootsWithExclusivePlayback",new Set),np);let Fr=tn;Ve([m(Pt)],Fr.prototype,"animator",2),Ve([m()],Fr.prototype,"stateName",2);class yl extends A{constructor(){super(...arguments),a(this,"target")}getType(){}getDuration(){}}Ve([m(I)],yl.prototype,"target",2);class oh extends A{constructor(){super(...arguments),a(this,"target")}}Ve([m(yl)],oh.prototype,"target",2);class rh extends yl{constructor(){super(...arguments),a(this,"type",1),a(this,"duration",1)}getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}Ve([m()],rh.prototype,"type",2),Ve([m()],rh.prototype,"duration",2);class o0 extends oh{}const Nx=class{constructor(){a(this,"_quicklookButton"),a(this,"_arButton"),a(this,"_vrButton"),a(this,"_sendToQuestButton")}static create(){return new Nx}static getOrCreate(){return this._instance||(this._instance=this.create()),this._instance}get isSecureConnection(){return window.location.protocol==="https:"}get quicklookButton(){return this._quicklookButton}get arButton(){return this._arButton}get vrButton(){return this._vrButton}get sendToQuestButton(){return this._sendToQuestButton}get qrButton(){return kn.getOrCreate().createQRCode()}createQuicklookButton(){if(this._quicklookButton)return this._quicklookButton;const s=document.createElement("button");this._quicklookButton=s,s.dataset.needle="quicklook-button";const t=X.supportsQuickLookAR();s.innerText="View in AR",s.prepend(Ot("view_in_ar"));let i=!1,n=null;return s.addEventListener("click",()=>{n=kc($e),n||(i=!0,n=new $e),i&&(n.objectToExport=ee.Current.scene),n?(s.classList.add("this-mode-is-requested"),n.exportAndOpen().then(()=>{s.classList.remove("this-mode-is-requested")}).catch(o=>{s.classList.remove("this-mode-is-requested"),console.error(o)})):console.warn("No USDZExporter component found in the scene")}),this.hideElementDuringXRSession(s),s}createARButton(s){var t;if(this._arButton)return this._arButton;const i="immersive-ar",n=document.createElement("button");return this._arButton=n,n.classList.add("webxr-button"),n.dataset.needle="webxr-ar-button",n.innerText="Enter AR",n.prepend(Ot("view_in_ar")),n.title="Click to start an AR session",n.addEventListener("click",()=>J.start(i,s)),this.updateSessionSupported(n,i),this.listenToXRSessionState(n,i),this.hideElementDuringXRSession(n),this.isSecureConnection||(n.disabled=!0,n.title="WebXR requires a secure connection (HTTPS)"),X.isMozillaXR()||(t=navigator.xr)==null||t.addEventListener("devicechange",()=>this.updateSessionSupported(n,i)),n}createVRButton(s){var t;if(this._vrButton)return this._vrButton;const i="immersive-vr",n=document.createElement("button");return this._vrButton=n,n.classList.add("webxr-button"),n.dataset.needle="webxr-vr-button",n.innerText="Enter VR",n.prepend(Ot("panorama_photosphere")),n.title="Click to start a VR session",n.addEventListener("click",()=>J.start(i,s)),this.updateSessionSupported(n,i),this.listenToXRSessionState(n,i),this.hideElementDuringXRSession(n),this.isSecureConnection||(n.disabled=!0,n.title="WebXR requires a secure connection (HTTPS)"),X.isMozillaXR()||(t=navigator.xr)==null||t.addEventListener("devicechange",()=>this.updateSessionSupported(n,i)),n}createSendToQuestButton(){var s;if(this._sendToQuestButton)return this._sendToQuestButton;const t="https://oculus.com/open_url/?url=",i=document.createElement("button");return this._sendToQuestButton=i,i.dataset.needle="webxr-sendtoquest-button",i.innerText="Open on Quest",i.prepend(Ot("share_windows")),i.title="Click to send this page to the Oculus Browser on your Quest",i.addEventListener("click",()=>{const n=encodeURIComponent(window.location.href),o=t+n;window.open(o)==null&&De("This page doesn't allow popups. Please paste "+o+" into your browser.")}),this.listenToXRSessionState(i),this.hideElementDuringXRSession(i),X.isMozillaXR()||(s=navigator.xr)==null||s.addEventListener("devicechange",()=>{var n;(n=navigator.xr)!=null&&n.isSessionSupported("immersive-vr")?i.style.display="none":i.style.display=""}),i}createQRCode(){return kn.getOrCreate().createQRCode()}updateSessionSupported(s,t){if(!("xr"in navigator)){s.style.display="none";return}J.isSessionSupported(t).then(i=>{s.style.display=i?"":"none",F()&&!i&&console.log('[WebXR] "'+t+'" is not supported on this device \u2013 make sure your server runs using HTTPS and you have a device connected that supports '+t)})}hideElementDuringXRSession(s){Od(t=>{s["previous-display"]=s.style.display,s.style.display="none"}),Jm(t=>{s["previous-display"]!=null&&(s.style.display=s["previous-display"])})}listenToXRSessionState(s,t){t&&(J.onSessionRequestStart(i=>{i.mode===t?s.classList.add("this-mode-is-requested"):(s["was-disabled"]=s.disabled,s.disabled=!0,s.classList.add("other-mode-is-requested"))}),J.onSessionRequestEnd(i=>{s.classList.remove("this-mode-is-requested"),s.classList.remove("other-mode-is-requested"),s.disabled=s["was-disabled"]}))}};let zr=Nx;a(zr,"_instance");var yT=Object.defineProperty,vT=Object.getOwnPropertyDescriptor,wt=(s,t,i,n)=>{for(var o=n>1?void 0:n?vT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&yT(t,i,o),o};const op=C("debugspriterenderer"),bT=C("wireframe"),r0=class{static getOrCreateGeometry(s){if(s.__cached_geometry)return s.__cached_geometry;if(s.guid&&r0.cache[s.guid])return op&&console.log("Take cached geometry for sprite",s.guid),r0.cache[s.guid];const t=new gn;s.__cached_geometry=t;const i=new Float32Array(s.triangles.length*3),n=new Float32Array(s.triangles.length*2);for(let o=0;o<s.triangles.length;o+=1){const r=s.triangles[o];i[o*3]=-s.vertices[r].x,i[o*3+1]=s.vertices[r].y,i[o*3+2]=0;const l=s.uv[r];n[o*2]=l.x,n[o*2+1]=1-l.y}return t.setAttribute("position",new ft(i,3)),t.setAttribute("uv",new ft(n,2)),s.guid&&(this.cache[s.guid]=t),op&&console.log("Built sprite geometry",s,t),t}};let ah=r0;a(ah,"cache",{});class _T{constructor(){a(this,"x"),a(this,"y")}}function Wx(s){s&&(s.colorSpace!=ms&&(s.colorSpace=ms,s.needsUpdate=!0),s.minFilter==ld&&s.magFilter==ld&&(s.anisotropy=1,s.needsUpdate=!0))}let Nn=class{constructor(s){a(this,"guid"),a(this,"texture"),a(this,"triangles"),a(this,"uv"),a(this,"vertices"),a(this,"__cached_geometry"),a(this,"_mesh"),a(this,"_material"),s&&(this.texture=s,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}])}get mesh(){return this._mesh||(this._mesh=new Y(ah.getOrCreateGeometry(this),this.material)),this._mesh}get material(){return this._material||(this.texture&&Wx(this.texture),this._material=new Re({map:this.texture,color:16777215,side:Si,transparent:!0})),this._material}getGeometry(){return ah.getOrCreateGeometry(this)}};wt([m()],Nn.prototype,"guid",2),wt([m(Le)],Nn.prototype,"texture",2),wt([Pr()],Nn.prototype,"triangles",2),wt([Pr()],Nn.prototype,"uv",2),wt([Pr()],Nn.prototype,"vertices",2);const a0=Symbol("spriteOwner");class vl{constructor(){a(this,"sprites"),this.sprites=[]}}wt([m(Nn)],vl.prototype,"sprites",2);const l0=class{constructor(){a(this,"spriteSheet"),a(this,"index",0)}static create(){const s=new l0;return s.spriteSheet=new vl,s}clone(){const s=new l0;return s.index=this.index,s.spriteSheet=this.spriteSheet,s}set sprite(s){s&&(this.spriteSheet?((this.index===null||this.index===void 0)&&(this.index=0),this.spriteSheet.sprites[this.index]=s):(this.spriteSheet=new vl,this.spriteSheet.sprites=[s],this.index=0))}get sprite(){if(this.spriteSheet)return this.spriteSheet.sprites[this.index]}update(s){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&&(Wx(n),!i.__hasLoadedProgressive)){i.__hasLoadedProgressive=!0;const o=n;it.assignTextureLOD(n,0).then(r=>{r instanceof Le&&(i.texture=r,s?.map===o&&(s.map=r,s.needsUpdate=!0))})}}};let jo=l0;wt([m(vl)],jo.prototype,"spriteSheet",2),wt([m()],jo.prototype,"index",2);class mi extends A{constructor(){super(...arguments),a(this,"drawMode",0),a(this,"size",{x:1,y:1}),a(this,"color"),a(this,"sharedMaterial"),a(this,"transparent",!0),a(this,"cutoutThreshold",0),a(this,"castShadows",!1),a(this,"renderOrder",0),a(this,"toneMapped",!0),a(this,"_spriteSheet"),a(this,"_currentSprite")}set texture(t){var i;if(!this._spriteSheet)return;const n=(i=this._spriteSheet.spriteSheet)==null?void 0:i.sprites[this.spriteIndex];n&&(n.texture=t,this.updateSprite())}addSprite(t,i=!1){var n,o;if(this._spriteSheet||(this._spriteSheet=jo.create()),!this._spriteSheet.spriteSheet)return-1;(n=this._spriteSheet.spriteSheet)==null||n.sprites.push(t);const r=((o=this._spriteSheet.spriteSheet)==null?void 0:o.sprites.length)-1;return i&&(this.spriteIndex=r),r}get sprite(){return this._spriteSheet}set sprite(t){if(t!==this._spriteSheet)if(typeof t=="number"){const i=Math.floor(t);this.spriteIndex=i}else t instanceof Nn?(this._spriteSheet||(this._spriteSheet=jo.create()),this._spriteSheet.sprite!=t&&(this._spriteSheet.sprite=t),this.updateSprite()):t!=this._spriteSheet&&(this._spriteSheet=t,this.updateSprite())}set spriteIndex(t){this._spriteSheet&&(this._spriteSheet.index=t,this.updateSprite())}get spriteIndex(){var t;return((t=this._spriteSheet)==null?void 0:t.index)??0}get spriteFrames(){var t,i;return((i=(t=this._spriteSheet)==null?void 0:t.spriteSheet)==null?void 0:i.sprites.length)??0}awake(){this._currentSprite=void 0,this._spriteSheet?this._spriteSheet=this._spriteSheet.clone():this._spriteSheet=jo.create(),op&&console.log("Awake",this.name,this,this.sprite)}start(){this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(t=!1){var i;if(!this.__didAwake&&!t)return!1;const n=this._spriteSheet;if(!((i=n?.spriteSheet)!=null&&i.sprites))return console.warn("SpriteRenderer has no data or spritesheet assigned..."),!1;const o=n.spriteSheet.sprites[this.spriteIndex];if(!o)return op&&console.warn("Sprite not found",this.spriteIndex,n.spriteSheet.sprites),!1;if(this._currentSprite)this._currentSprite.geometry=ah.getOrCreateGeometry(o),this._currentSprite.material.map=o.texture;else{const r=new Re({color:16777215,side:Si});if(bT&&(r.wireframe=!0),this.color&&(r.color||(r.color=new ae),r.color.copy(this.color),r.opacity=this.color.alpha),r.transparent=!0,r.toneMapped=this.toneMapped,r.depthWrite=!1,o.texture&&!r.wireframe){let l=o.texture;l[a0]!==void 0&&l[a0]!==this&&this.spriteFrames>1&&(l=o.texture=l.clone()),l[a0]=this,r.map=l}this.sharedMaterial=r,this._currentSprite=new Y(ah.getOrCreateGeometry(o),r),this._currentSprite.renderOrder=Math.round(this.renderOrder),it.assignTextureLOD(r,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,n?.update(this.sharedMaterial),!0}}wt([m()],mi.prototype,"drawMode",2),wt([m(_T)],mi.prototype,"size",2),wt([m(xe)],mi.prototype,"color",2),wt([m(ke)],mi.prototype,"sharedMaterial",2),wt([m()],mi.prototype,"transparent",2),wt([m()],mi.prototype,"cutoutThreshold",2),wt([m()],mi.prototype,"castShadows",2),wt([m()],mi.prototype,"renderOrder",2),wt([m()],mi.prototype,"toneMapped",2),wt([m(jo)],mi.prototype,"sprite",1);const Vx=C("debugwebxr"),wT=new ne().makeRotationY(Math.PI),lh=class extends A{constructor(){super(...arguments),a(this,"_arScale",1),a(this,"invertForward",!1),a(this,"customReticle"),a(this,"arTouchTransform",!0),a(this,"autoPlace",!1),a(this,"autoCenter",!1),a(this,"useXRAnchor",!1),a(this,"_isPlacing",!0),a(this,"_startOffset",new ne),a(this,"_createdPlacementObject",null),a(this,"_reparentedComponents",[]),a(this,"_placementScene",new Vi),a(this,"_reticle",[]),a(this,"_hits",[]),a(this,"_placementStartTime",-1),a(this,"_rigPlacementMatrix"),a(this,"_anchor",null),a(this,"userInput"),a(this,"onPlaceScene",s=>{var t;if(this._isPlacing==!1||s!=null&&s.used)return;let i=this._reticle[0];if(!i){console.warn("No reticle to place...");return}if(!i.visible&&!this.autoPlace){console.warn("Reticle is not visible (can not place)");return}if((t=J.active)!=null&&t.isTrackingImages){console.warn("Scene Placement is disabled while images are being tracked");return}let n=this._hits[0];if(s&&s.origin instanceof eg){const o=this._reticle[s.origin.index];o&&(i=o,n=this._hits[s.origin.index])}if(s&&(s.stopImmediatePropagation(),s.stopPropagation(),s.use()),this._isPlacing=!1,this.context.input.removeEventListener("pointerup",this.onPlaceScene),this.onRevertSceneChanges(),i.position.copy(i.lastPos),i.quaternion.copy(i.lastQuat),this.onApplyPose(i),lh._hasPlaced=!0,this.useXRAnchor&&this.onCreateAnchor(J.active,n),this.context.xr)for(const o of this.context.xr.controllers)o.cancelHitTestSource()}),a(this,"upVec",new x(0,1,0)),a(this,"lookPoint",new x),a(this,"worldUpVec",new x(0,1,0))}static onPlaced(s){const t="placed";return this._eventListeners[t]||(this._eventListeners[t]=[]),this._eventListeners[t].push(s),()=>{const i=this._eventListeners[t].indexOf(s);i>=0&&this._eventListeners[t].splice(i,1)}}static get hasPlaced(){return this._hasPlaced}get arScale(){return this._arScale}set arScale(s){this._arScale=Math.max(1e-6,s),this.onSetScale()}onEnable(){var s;(s=this.customReticle)==null||s.preload()}supportsXR(s){return s==="immersive-ar"}onEnterXR(s){Vx&&console.log("ENTER WEBXR: SessionRoot start..."),this._anchor=null,lh._hasPlaced=!1,this.gameObject.updateMatrixWorld(),this._startOffset.copy(this.gameObject.matrixWorld);const t=new I;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=oi(this._placementScene.children),n=i.getCenter(new x),o=i.getSize(new x),r=new ne;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}),O.addComponent(t,this);for(const i of this._reticle)Ri(i);this._reticle.length=0,this._isPlacing=!0,this.context.input.addEventListener("pointerup",this.onPlaceScene,{queue:ai.Early})}onLeaveXR(){this.context.input.removeEventListener("pointerup",this.onPlaceScene,{queue:ai.Early}),this.onRevertSceneChanges(),this._anchor=null,lh._hasPlaced=!1,this._rigPlacementMatrix=void 0}onUpdateXR(s){var t,i,n,o;if(s.xr.isTrackingImages){for(const r of this._reticle)r.visible=!1;return}if(this._isPlacing){const r=(t=s.xr.rig)==null?void 0:t.gameObject;r&&r.parent!==this.context.scene&&this.context.scene.add(r);let l=!1;if(s.xr.isPassThrough&&s.xr.controllers.length>0&&!this.autoPlace)for(const c of s.xr.controllers){const h=c.getHitTest();h&&(l=!0,this.updateReticleAndHits(s.xr,c.index,h,s.xr.rigScale))}if(!l){const c=s.xr.getHitTest();c&&this.updateReticleAndHits(s.xr,0,c,s.xr.rigScale)}}else{if(this._anchor&&s.xr.referenceSpace){const r=s.xr.frame.getPose(this._anchor.anchorSpace,s.xr.referenceSpace);if(r&&this.context.time.frame%20===0){const l=s.xr.convertSpace(r.transform),c=this._reticle[0];c&&(c.position.copy(l.position),c.quaternion.copy(l.quaternion),this.onApplyPose(c))}}if(this.arTouchTransform?(this.userInput||(this.userInput=new rp(this.context)),(i=this.userInput)==null||i.enable()):(n=this.userInput)==null||n.disable(),this.arTouchTransform&&(o=this.userInput)!=null&&o.hasChanged){if(s.xr.rig){const r=s.xr.rig.gameObject;this.userInput.applyMatrixTo(r.matrix,!0),r.matrix.decompose(r.position,r.quaternion,r.scale),this.userInput.factor=r.scale.x}this.userInput.reset()}}}updateReticleAndHits(s,t,i,n){this._hits[t]=i.hit;let o=this._reticle[t];if(!o){if(this.customReticle)if(this.customReticle.asset)o=La(this.customReticle.asset);else{this.customReticle.loadAssetAsync();return}else o=new Y(new uC(.07,.09,32).rotateX(-Math.PI/2),new Re({side:Si,depthTest:!1,depthWrite:!1,transparent:!0,opacity:1,color:15658734})),o.name="AR Placement Reticle";if(Vx){const r=new xi(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(G(0,1,0))>.9){let r=o["autoplace:timer"]||0;r>=1?(o.visible=!1,this.onPlaceScene(null)):(r+=this.context.time.deltaTime,o["autoplace:timer"]=r)}else o["autoplace:timer"]=0}onSetScale(){var s,t,i;if(!lh._hasPlaced)return;const n=(t=(s=J.active)==null?void 0:s.rig)==null?void 0:t.gameObject;if(n){const o=((i=J.active)==null?void 0:i.rigScale)||1,r=1/this._arScale*o,l=new ne().makeScale(r,r,r).invert();n.matrix.premultiply(l),n.matrix.decompose(n.position,n.quaternion,n.scale)}}onRevertSceneChanges(){var s;for(const t of this._reticle)t&&(t.visible=!1,t?.removeFromParent());this._reticle.length=0;for(let t=this._placementScene.children.length-1;t>=0;t--){const i=this._placementScene.children[t];this.context.scene.add(i)}(s=this._createdPlacementObject)==null||s.removeFromParent();for(const t of this._reparentedComponents)O.addComponent(t.originalObject,t.comp)}async onCreateAnchor(s,t){if(t.createAnchor===void 0){console.warn("Hit does not support creating an anchor",t),F()&&we("Hit does not support creating an anchor");return}else{const i=await t.createAnchor(s.viewerPose.transform);s.running&&i&&(this._anchor=i)}}applyViewBasedTransform(s){const t=this.context.mainCamera,i=s,n=t.worldPosition,o=i.worldPosition;this.upVec.set(0,1,0).applyQuaternion(s.quaternion);const r=t.worldPosition;r&&s.position.clone().sub(r).angleTo(this.upVec)<Math.PI/2&&this.upVec.negate();const l=this.upVec.angleTo(this.worldUpVec)*180/Math.PI,c=30;l>c&&l<180-c||l<-c&&l>-180+c?(this.lookPoint.copy(s.position).add(this.upVec),this.lookPoint.y=s.position.y,s.lookAt(this.lookPoint)):(n.y=o.y,s.lookAt(n))}onApplyPose(s){var t,i,n;const o=(i=(t=J.active)==null?void 0:t.rig)==null?void 0:i.gameObject;if(!o){console.warn("No rig object to place");return}const r=o.parent||this.context.scene;this._rigPlacementMatrix?(n=this._rigPlacementMatrix)==null||n.decompose(o.position,o.quaternion,o.scale):this._rigPlacementMatrix=o.matrix.clone(),this.applyViewBasedTransform(s),s.updateMatrix(),this.context.scene.add(s),s.attach(o),s.removeFromParent(),o.scale.set(this.arScale,this.arScale,this.arScale),o.position.multiplyScalar(this.arScale),o.updateMatrix(),this.invertForward&&o.matrix.premultiply(wT),o.matrix.premultiply(this._startOffset),o.matrix.decompose(o.position,o.quaternion,o.scale),r.add(o)}};let sn=lh;a(sn,"_eventListeners",{}),a(sn,"_hasPlaced",!1);const c0=class{constructor(s){a(this,"oneFingerDrag",!0),a(this,"twoFingerRotate",!0),a(this,"twoFingerScale",!0),a(this,"factor",1),a(this,"context"),a(this,"offset"),a(this,"plane"),a(this,"_scale",1),a(this,"_hasChanged",!1),a(this,"_enabled",!1),a(this,"currentlyUsedPointerIds",new Set),a(this,"currentlyUnusedPointerIds",new Set),a(this,"onPointerDownEarly",t=>{this.isActive&&t.stopPropagation()}),a(this,"onPointerDownLate",t=>{t.used?this.currentlyUsedPointerIds.add(t.pointerId):this.currentlyUsedPointerIds.size<=0&&this.currentlyUnusedPointerIds.add(t.pointerId)}),a(this,"onPointerUpEarly",t=>{this.currentlyUsedPointerIds.delete(t.pointerId),this.currentlyUnusedPointerIds.delete(t.pointerId)}),a(this,"prev",new Map),a(this,"_didMultitouch",!1),a(this,"touchStart",t=>{if(!t.defaultPrevented)for(let i=0;i<t.changedTouches.length;i++){const n=t.changedTouches[i],o=X.isAndroidDevice()&&n.clientY<window.innerHeight*.1;this.prev.has(n.identifier)||this.prev.set(n.identifier,{ignore:o,x:0,z:0,screenx:0,screeny:0});const r=this.prev.get(n.identifier);if(r){const l=this.getPositionOnPlane(n.clientX,n.clientY);r.x=l.x,r.z=l.z,r.screenx=n.clientX,r.screeny=n.clientY}}}),a(this,"touchEnd",t=>{t.touches.length<=0&&(this._didMultitouch=!1);for(let i=0;i<t.changedTouches.length;i++){const n=t.changedTouches[i];this.prev.delete(n.identifier)}}),a(this,"touchMove",t=>{if(!t.defaultPrevented&&this.isActive){if(t.touches.length===1){if(this._didMultitouch)return;const i=t.touches[0],n=this.prev.get(i.identifier);if(!n||n.ignore)return;const o=this.getPositionOnPlane(i.clientX,i.clientY),r=o.x-n.x,l=o.z-n.z;if(r===0&&l===0)return;this.oneFingerDrag&&this.addMovement(r,l),n.x=o.x,n.z=o.z,n.screenx=i.clientX,n.screeny=i.clientY;return}else if(t.touches.length===2){this._didMultitouch=!0;const i=t.touches[0],n=t.touches[1],o=this.prev.get(i.identifier),r=this.prev.get(n.identifier);if(!o||!r)return;if(this.twoFingerRotate){const l=Math.atan2(i.clientY-n.clientY,i.clientX-n.clientX),c=Math.atan2(o.screeny-r.screeny,o.screenx-r.screenx),h=l-c;Math.abs(h)>.001&&this.addRotation(h)}if(this.twoFingerScale){const l=i.clientX-n.clientX,c=i.clientY-n.clientY,h=Math.sqrt(l*l+c*c),d=o.screenx-r.screenx,u=o.screeny-r.screeny,p=Math.sqrt(d*d+u*u),g=h-p;Math.abs(g)>2&&this.addScale(g)}o.screenx=i.clientX,o.screeny=i.clientY,r.screenx=n.clientX,r.screeny=n.clientY}}}),a(this,"_raycaster",new rd),a(this,"_intersection",new x),a(this,"_screenPos",new x),a(this,"_tempMatrix",new ne),this.context=s,this.offset=new ne,this.plane=new nr,this.plane.setFromNormalAndCoplanarPoint(c0.up,c0.zero)}get scale(){return this._scale}reset(){this._scale=1,this.offset.identity(),this._hasChanged=!0}get hasChanged(){return this._hasChanged}applyMatrixTo(s,t){this._hasChanged=!1,t?(this.offset.invert(),s.premultiply(this.offset)):s.multiply(this.offset)}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:ai.Early}),this.context.input.addEventListener("pointerdown",this.onPointerDownLate,{queue:ai.Late}),this.context.input.addEventListener("pointerup",this.onPointerUpEarly,{queue:ai.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:ai.Early}),this.context.input.removeEventListener("pointerdown",this.onPointerDownLate,{queue:ai.Late}),this.context.input.removeEventListener("pointerup",this.onPointerUpEarly,{queue:ai.Early}),window.removeEventListener("touchstart",this.touchStart),window.removeEventListener("touchmove",this.touchMove),window.removeEventListener("touchend",this.touchEnd))}getPositionOnPlane(s,t){const i=this.context.mainCamera;return this._screenPos.x=s/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(s,t){s/=this._scale,t/=this._scale,s*=this.factor,t*=this.factor,this.offset.elements[12]+=s,this.offset.elements[14]+=t,(s!==0||t!==0)&&(this._hasChanged=!0)}addScale(s){s/=window.innerWidth,s*=-1,this._scale*=1+s,this._tempMatrix.makeScale(1-s,1-s,1-s),this.offset.premultiply(this._tempMatrix),s!==0&&(this._hasChanged=!0)}addRotation(s){s*=-1,this._tempMatrix.makeRotationY(s),this.offset.premultiply(this._tempMatrix),s!==0&&(this._hasChanged=!0)}};let rp=c0;a(rp,"up",new x(0,1,0)),a(rp,"zero",new x(0,0,0)),a(rp,"one",new x(1,1,1));const Lo=C("debugautosync"),h0=Symbol("syncerId");class xT{constructor(){a(this,"_syncers",{})}getOrCreateSyncer(t){if(!t.guid)return null;if(this._syncers[t.guid])return this._syncers[t.guid];const i=new ST(t);return i[h0]=t.guid,this._syncers[i[h0]]=i,i}removeSyncer(t){delete this._syncers[t[h0]]}}const d0=new xT;class ST{constructor(t){a(this,"comp"),a(this,"hasChanges",!1),a(this,"changedProperties",{}),a(this,"_isReceiving",!1),a(this,"_isInit",!1),a(this,"onHandleSending",()=>{if(!this.hasChanges)return;this.hasChanges=!1;const i=this.comp.context.connection;if(!i||!i.isConnected||!i.isInRoom){for(const n in this.changedProperties)delete this.changedProperties[n];return}for(const n in this.changedProperties){const o=this.changedProperties[n];Lo&&console.log("SEND",this.comp.guid,this.networkingKey),i.send(this.networkingKey,{guid:this.comp.guid,property:n,data:o},_s.Queued),delete this.changedProperties[n]}}),a(this,"onHandleReceiving",i=>{if(Lo&&console.log("SYNCFIELD RECEIVE",this.comp.name,this.comp.guid,i),!!this._isInit&&this.comp&&i.guid===this.comp.guid)try{this._isReceiving=!0,this.comp[i.property]=i.data}catch(n){console.error(n)}finally{this._isReceiving=!1}}),this.comp=t}get networkingKey(){return this.comp.guid}init(t){if(this._isInit)return;this._isInit=!0,this.comp=t,this.comp.context.post_render_callbacks.push(this.onHandleSending),this.comp.context.connection.beginListen(this.networkingKey,this.onHandleReceiving);const i=this.comp.context.connection.tryGetState(this.comp.guid);i&&this.onHandleReceiving(i)}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(t,i){this._isReceiving||(Lo&&console.log("Property changed: "+t,i),this.hasChanges=!0,this.changedProperties[t]=i)}}function CT(s,t){let i=t!==s;return!i&&s&&t&&(Array.isArray(s)&&Array.isArray(t)||typeof s=="object"&&typeof t=="object")&&(i=!0),i}const ch=Symbol("AutoSyncHandler");function OT(s){if(s[ch])return s[ch];const t=d0.getOrCreateSyncer(s);return t?.init(s),s[ch]=t,t}function PT(s){const t=s[ch];t&&(d0.removeSyncer(t),t.destroy(),delete s[ch])}const u0=function(s=null){return function(t,i){var n;let o="";typeof i=="string"?o=i:o=i.name;let r=null,l;typeof s=="string"?l=t[s]:typeof s=="function"&&(l=s),l==null&&(F()||Lo)&&s!=null&&console.warn('syncField: no callback function found for property "'+o+'"','"'+s+'"');const c=t,h=c.__internalAwake;if(typeof h!="function"){(Lo||F())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+((n=t?.constructor)==null?void 0:n.name)+'" is not supported',t);return}Lo&&console.log(o);const d=Symbol(o);c.__internalAwake=function(){if(this[d]!==void 0)return;this[d]=this[o],r=d0.getOrCreateSyncer(this);const p=Object.getOwnPropertyDescriptor(this,o);if(p?.set===void 0){let g=!1;Object.defineProperty(this,o,{set:function(y){var f;const v=this[d];if(this[d]=y,g){(F()||Lo)&&console.warn("Recursive call detected",o);return}g=!0;try{const b=CT(y,v);Lo&&console.log("SyncField assignment",o,"changed?",b,y,l),b&&l?.call(this,y,v)!==!1&&((f=OT(this))==null||f.notifyChanged(o,y))}finally{g=!1}},get:function(){return this[d]},configurable:!0,enumerable:!0})}r?.init(this),h.call(this)};const u=c.__internalDestroy;c.__internalDestroy=function(){PT(this),u.call(this)}}};var kT=Object.defineProperty,MT=Object.getOwnPropertyDescriptor,ap=(s,t,i,n)=>{for(var o=n>1?void 0:n?MT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&kT(t,i,o),o};const ei=C("debugplayersync"),Hx=class extends A{constructor(){super(...arguments),a(this,"autoSync",!0),a(this,"asset"),a(this,"onPlayerSpawned"),a(this,"_localInstance"),a(this,"onJoinedRoom",()=>{ei&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()}),a(this,"destroyInstance",()=>{var s;(s=this._localInstance)==null||s.then(t=>{ei&&console.log("PlayerSync.destroyInstance",t),wc(t,this.context.connection,!0,{saveInRoom:!1})}),this._localInstance=void 0})}static async setupFrom(s,t){const i=le.getOrCreateFromUrl(s);if(!i.asset){const r=await i.loadAssetAsync();r&&O.getOrAddComponent(r,Ii)}const n=new Hx;n._internalInit(t),n.asset=i;const o=new I;return o.guid=s,O.addComponent(o,n),n}awake(){this.watchTabVisible(),this.onPlayerSpawned||(this.onPlayerSpawned=new Se)}onEnable(){this.context.connection.beginListen(se.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(se.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(se.LeftRoom,this.destroyInstance),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(se.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(se.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(se.LeftRoom,this.destroyInstance)}async getInstance(){var s,t,i,n,o,r;if(this._localInstance)return this._localInstance;if(ei&&console.log("PlayerSync.createInstance",(s=this.asset)==null?void 0:s.url),!((t=this.asset)!=null&&t.asset)&&!((i=this.asset)!=null&&i.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=(n=this.asset)==null?void 0:n.instantiateSynced({parent:this.gameObject,deleteOnDisconnect:!0},!0);const l=await this._localInstance;if(l){const c=O.getComponentsInChildren(l,Ii);if(ei&&console.log(`PlayerSync.createInstance: found ${c?.length} PlayerState components. Owner: ${this.context.connection.connectionId}`),c!=null&&c.length){for(const h of c)h.owner=this.context.connection.connectionId;(o=this.onPlayerSpawned)==null||o.invoke(l)}else this._localInstance=void 0,console.error("<strong>Failed finding PlayerState on "+((r=this.asset)==null?void 0:r.url)+"</strong>: please make sure the asset has a PlayerState component!"),O.destroySynced(l)}else this._localInstance=void 0,console.warn("PlayerSync: failed instantiating asset!");return this._localInstance}watchTabVisible(){window.addEventListener("visibilitychange",s=>{if(document.visibilityState==="visible")for(let t=Ii.all.length-1;t>=0;t--){const i=Ii.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}};let bl=Hx;ap([m()],bl.prototype,"autoSync",2),ap([m(le)],bl.prototype,"asset",2),ap([m(Se)],bl.prototype,"onPlayerSpawned",2);var $x=(s=>(s.OwnerChanged="ownerChanged",s))($x||{}),hh;const Tt=(hh=class extends A{constructor(){super(...arguments),a(this,"onOwnerChangeEvent",new Se),a(this,"onFirstOwnerChangeEvent",new Se),a(this,"hasOwner",!1),a(this,"owner"),a(this,"dontDestroy",!1),a(this,"onUserLeftRoom",s=>{if(s.userId===this.owner){ei&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}})}static get all(){return Tt._all}static get local(){return Tt._local}static getFor(s){if(s instanceof I)return O.getComponentInParent(s,Tt);if(s instanceof A)return O.getComponentInParent(s.gameObject,Tt)}static isLocalPlayer(s){const t=Tt.getFor(s);return t?.isLocalPlayer??!1}static addEventListener(s,t){return this._callbacks[s]||(this._callbacks[s]=[]),this._callbacks[s].push(t),t}static removeEventListener(s,t){if(!this._callbacks[s])return;const i=this._callbacks[s].indexOf(t);i>=0&&this._callbacks[s].splice(i,1)}static dispatchEvent(s,t){if(this._callbacks[s])for(const i of this._callbacks[s])i(t)}get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(s,t){var i,n;ei&&console.log(`PlayerSync.onOwnerChange: ${t} \u2192 ${s} (me: ${this.context.connection.connectionId})`);const o=Tt._local.indexOf(this);o>=0&&Tt._local.splice(o,1);const r={playerState:this,oldValue:t,newValue:s};if(this.hasOwner||(this.hasOwner=!0,(i=this.onFirstOwnerChangeEvent)==null||i.invoke(r)),(n=this.onOwnerChangeEvent)==null||n.invoke(r),this.owner===this.context.connection.connectionId){Tt._local.push(this);const c=new CustomEvent("local-owner-changed",{detail:r});this.dispatchEvent(c)}const l=new CustomEvent("owner-changed",{detail:r});this.dispatchEvent(l),Tt.dispatchEvent("ownerChanged",l)}awake(){Tt.all.push(this),ei&&console.log("Registered new PlayerState",this.guid,Tt.all.length-1,Tt.all),this.context.connection.beginListen(se.UserLeftRoom,this.onUserLeftRoom)}async start(){ei&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await fs(300),this.context.connection.userIsInRoom(this.owner)==!1&&(ei&&console.log(`PlayerSync.start \u2192 doDestroy "${this.name}" because user "${this.owner}" is not in room anymore...`,"Currently in room:",...this.context.connection.usersInRoom()),this.doDestroy())):this.owner||(ei&&console.warn("PlayerState.start \u2192 owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?ei&&console.warn("PlayerState.start \u2192 owner is still undefined but dontDestroy is set to true",this.name):(ei&&console.warn(`PlayerState.start \u2192 owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):ei&&console.log("PlayerState.start \u2192 owner is assigned",this.owner)},2e3))}doDestroy(){ei&&console.log("PlayerSync.doDestroy \u2192 syncDestroy",this.name),wc(this.gameObject,this.context.connection,!0,{saveInRoom:!1})}onDestroy(){if(ei&&console.warn("PlayerState.onDestroy",this.owner),this.context.connection.stopListen(se.UserLeftRoom,this.onUserLeftRoom),Tt.all.splice(Tt.all.indexOf(this),1),this.isLocalPlayer){const s=Tt._local.indexOf(this);s>=0&&Tt._local.splice(s,1)}}},a(hh,"_all",[]),a(hh,"_local",[]),a(hh,"_callbacks",{}),hh);let Ii=Tt;ap([u0(Ii.prototype.onOwnerChange)],Ii.prototype,"owner",2);var RT=Object.defineProperty,TT=Object.getOwnPropertyDescriptor,_l=(s,t,i,n)=>{for(var o=n>1?void 0:n?TT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&RT(t,i,o),o};class nn extends A{constructor(){super(...arguments),a(this,"position","bottom"),a(this,"showNeedleLogo",!0),a(this,"showSpatialMenu"),a(this,"createFullscreenButton"),a(this,"createMuteButton"),a(this,"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&&(X.isMobileDevice()||this.context.menu.showQRCodeButton(!0))}}_l([m()],nn.prototype,"position",2),_l([m()],nn.prototype,"showNeedleLogo",2),_l([m()],nn.prototype,"showSpatialMenu",2),_l([m()],nn.prototype,"createFullscreenButton",2),_l([m()],nn.prototype,"createMuteButton",2),_l([m()],nn.prototype,"createQRCodeButton",2);var ET=Object.defineProperty,AT=Object.getOwnPropertyDescriptor,p0=(s,t,i,n)=>{for(var o=n>1?void 0:n?AT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&ET(t,i,o),o};const dh=C("debugwebxr"),qx=new V().setFromAxisAngle(new x(0,1,0),Math.PI);class Do extends A{constructor(){super(...arguments),a(this,"head"),a(this,"leftHand"),a(this,"rightHand"),a(this,"_leftHandMeshes"),a(this,"_rightHandMeshes"),a(this,"_syncTransforms")}async onEnterXR(t){if(!this.activeAndEnabled)return;dh&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const i=Ii.getFor(this);if(i!=null&&i.owner){const n=this.gameObject.addComponent(Mt);n.avatar=this.gameObject,n.connectionId=i.owner}else this.context.connection.isConnected?console.error("No player state found for avatar",this):i&&!this.context.connection.isConnected&&(i.dontDestroy=!0)}onLeaveXR(t){const i=this.gameObject.getComponent(Mt);i&&i.destroy()}onUpdateXR(t){var i,n;if(!this.activeAndEnabled)return;const o=Ii.isLocalPlayer(this);if(!o)return;const r=t.xr;if(r.rig&&r.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),r.rig.gameObject.add(this.gameObject)),this._syncTransforms&&o)for(const u of this._syncTransforms)u.fastMode=!0,u.isOwned()||u.requestOwnership();if(this.head&&this.context.mainCamera){const u=this.head.asset;if(u.position.copy(this.context.mainCamera.position),u.position.x*=-1,u.position.z*=-1,u.quaternion.copy(this.context.mainCamera.quaternion),u.quaternion.x*=-1,this.context.time.frameCount%10===0&&this.head.asset){const p=O.getComponentsInChildren(this.head.asset,Ai);for(const g of p)g.enabled=!1,g.gameObject.visible=!1}}const l=t.xr.leftController,c=(i=this.leftHand)==null?void 0:i.asset;l&&c?(c.position.copy(l.gripPosition),c.quaternion.copy(l.gripQuaternion),c.quaternion.multiply(qx),c.visible=l.isTracking,this.updateHandVisibility(l,c,this._leftHandMeshes)):c&&c.visible&&(c.visible=!1);const h=t.xr.rightController,d=(n=this.rightHand)==null?void 0:n.asset;h&&d?(d.position.copy(h.gripPosition),d.quaternion.copy(h.gripQuaternion),d.quaternion.multiply(qx),d.visible=h.isTracking,this.updateHandVisibility(h,d,this._rightHandMeshes)):d&&d.visible&&(d.visible=!1)}onBeforeRender(){this.context.xr&&this.context.time.frame%10===0&&this.updateRemoteAvatarVisibility()}updateHandVisibility(t,i,n){if(n){const o=t.model&&t.model.visible&&t.model!==i;n.forEach(r=>{On(r,!o)})}}updateRemoteAvatarVisibility(){var t,i,n;if(this.context.connection.isConnected){const o=Ii.getFor(this);if(o&&o.isLocalPlayer==!1){const r=J.getXRSync(this.context);if(r&&r.hasState(o.owner)){this.tryFindAvatarObjectsIfMissing();const l=(t=this.leftHand)==null?void 0:t.asset;l&&(l.visible=r?.isTracking(o.owner,"left")??!1);const c=(i=this.rightHand)==null?void 0:i.asset;c&&(c.visible=r?.isTracking(o.owner,"right")??!1)}if((n=this.head)!=null&&n.asset){const l=O.getComponentsInChildren(this.head.asset,Ai);for(const c of l)c.enabled=!1,c.gameObject.visible=!0}}}}tryFindAvatarObjectsIfMissing(){if(!this.head||!this.leftHand||!this.rightHand){const t={head:this.head,leftHand:this.leftHand,rightHand:this.rightHand};Ub.tryFindAvatarObjects(this.gameObject,this.sourceId||"",t),t.head&&(this.head=t.head),t.leftHand&&(this.leftHand=t.leftHand),t.rightHand&&(this.rightHand=t.rightHand)}}async prepareAvatar(){var t,i;if(this.tryFindAvatarObjectsIfMissing(),this.head)this.head instanceof I&&(this.head=new le("",this.sourceId,this.head));else{const n=new I;n.name="Head";const o=po.createPrimitive(ur.Cube);n.add(o),this.gameObject.add(n),this.head=new le("",this.sourceId,n),dh&&console.log("Create head",n)}if(this.rightHand)this.rightHand instanceof I&&(this.rightHand=new le("",this.sourceId,this.rightHand));else{const n=new I;n.name="Right Hand",this.gameObject.add(n),this.rightHand=new le("",this.sourceId,n),dh&&console.log("Create right hand",n)}if(this.leftHand)this.leftHand instanceof I&&(this.leftHand=new le("",this.sourceId,this.leftHand));else{const n=new I;n.name="Left Hand",this.gameObject.add(n),this.leftHand=new le("",this.sourceId,n),dh&&console.log("Create left hand",n)}await this.loadAvatarObjects(this.head,this.leftHand,this.rightHand),this._leftHandMeshes=[],(t=this.leftHand.asset)==null||t.traverse(n=>{n!=null&&n.isMesh&&this._leftHandMeshes.push(n)}),this._rightHandMeshes=[],(i=this.rightHand.asset)==null||i.traverse(n=>{n!=null&&n.isMesh&&this._rightHandMeshes.push(n)}),Ii.isLocalPlayer(this.gameObject)&&(this._syncTransforms=O.getComponentsInChildren(this.gameObject,qs))}async loadAvatarObjects(t,i,n){const o=t.loadAssetAsync(),r=i.loadAssetAsync(),l=n.loadAssetAsync(),c=new Array;o&&c.push(o),r&&c.push(r),l&&c.push(l);const h=await Mm(c);dh&&console.log("Avatar loaded results:",h)}}p0([m(le)],Do.prototype,"head",2),p0([m(le)],Do.prototype,"leftHand",2),p0([m(le)],Do.prototype,"rightHand",2);var IT=Object.defineProperty,jT=Object.getOwnPropertyDescriptor,lp=(s,t,i,n)=>{for(var o=n>1?void 0:n?jT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&IT(t,i,o),o};const Wn=C("debugwebxr"),Bo=new Array;class on extends A{constructor(){super(...arguments),a(this,"createControllerModel",!0),a(this,"createHandModel",!0),a(this,"customLeftHand"),a(this,"customRightHand"),a(this,"_models",new Array)}supportsXR(t){return t==="immersive-vr"||t==="immersive-ar"}async onXRControllerAdded(t){var i;if(!(t.xr.isVR||t.xr.isPassThrough))return;const{controller:n}=t;if(Wn&&console.warn("Add Controller Model for",n.side,n.index),this.createControllerModel||this.createHandModel){if(n.hand){if(this.createHandModel){const o=await this.loadHandModel(this,n);if(!o||!n.connected||!n.isHand){o!=null&&o.handObject&&ja(o.handObject,!1),(i=o?.handObject)==null||i.destroy();return}this._models.push({controller:n,model:o.handObject,handmesh:o.handmesh}),this._models.sort((r,l)=>r.controller.index-l.controller.index),this.scene.add(o.handObject),n.model=o.handObject}}else if(this.createControllerModel){const o=await n.getModelUrl();if(o){const r=await this.loadModel(n,o);if(!r||!n.connected||n.isHand)return;this._models.push({controller:n,model:r}),this._models.sort((l,c)=>l.controller.index-c.controller.index),this.scene.add(r),r.traverse(l=>{l.layers.set(2),l.matrixAutoUpdate=!1,l.updateMatrix()}),n.model=r}else n.targetRayMode!=="transient-pointer"&&console.warn("XRControllerModel: no model found for "+n.side)}}}onXRControllerRemoved(t){console.debug("XR Controller Removed",t.controller.side,t.controller.index);const i=this._models.findIndex(o=>o.controller===t.controller),n=this._models[i];n&&(this._models.splice(i,1),n.model&&(ja(n.model,!1),n.model.destroy(),n.model=void 0))}onBeforeXR(t,i){this.createHandModel&&(this.customLeftHand||this.customRightHand)&&(i.optionalFeatures=i.optionalFeatures||[],i.optionalFeatures.includes("hand-tracking")||i.optionalFeatures.push("hand-tracking"))}onLeaveXR(t){for(const i of this._models)i&&(i.model&&(ja(i.model,!1),i.model.destroy(),i.model=void 0),i.controller.model===i.model&&(i.controller.model=null));this._models.length=0}onBeforeRender(){if(J.active&&(Wn&&(Bo[0]=Date.now()),this.updateRendering(J.active),Wn)){const t=Date.now()-Bo[0];Bo.push(t),Bo.length>=30&&(Bo[0]=0,Bo.reduce((i,n)=>i+n,0)/Bo.length,Bo.length=0)}}updateRendering(t){var i,n,o,r,l;for(let c=0;c<this._models.length;c++){const h=this._models[c];if(!h)continue;const d=h.controller;if(!d.connected){Wn&&console.warn("XRControllerModel.onUpdateXR: controller is not connected anymore",d.side,d.hand);continue}if(h.model&&!h.handmesh)h.model.matrixAutoUpdate=!1,h.model.matrix.copy(d.gripMatrix),h.model.visible=d.isTracking,(i=t.rig)==null||i.gameObject.add(h.model);else if(d.inputSource.hand&&h.handmesh){const u=t.referenceSpace,p=this.context.renderer.xr.getHand(d.index);if(u&&t.frame.getJointPose){for(const g of d.inputSource.hand.values()){const y=p.joints[g.jointName];if(y){const f=d.getHandJointPose(g);if(f){const v=f.transform.position,b=f.transform.orientation;y.position.copy(v),y.quaternion.copy(b),y.matrixAutoUpdate=!1}y.visible=f!=null}}h.model&&(h.model.visible=d.isTracking,h.model.visible&&h.model.parent!==((n=t.rig)==null?void 0:n.gameObject)&&((o=t.rig)==null||o.gameObject.add(h.model))),(r=h.model)!=null&&r.visible&&((l=h.handmesh)==null||l.updateMesh(),h.model.matrixAutoUpdate=!1,h.model.matrix.identity(),h.model.applyMatrix4(Ca))}}}}async loadModel(t,i){var n;if(!t.connected)return console.warn("XRControllerModel.onXRControllerAdded: controller is not connected anymore",t.side),null;const o=await le.getOrCreate("",i).instantiate();return ja(o),(n=J.active)!=null&&n.isPassThrough&&o.traverseVisible(r=>{this.makeOccluder(r)}),o}async loadHandModel(t,i){const n=this.context,o=n.renderer.xr.getHand(i.index);o||(Wn?q.DrawLabel(i.rayWorldPosition,"No hand found for index "+i.index,.05,5):console.warn("No hand found for index "+i.index));const r=new rr;gu(r,n),await Wu(r,n,this.sourceId??"");const l=Nu(r);let c="";const h=i.side==="left"?this.customLeftHand:this.customRightHand;h?(c=h.url.split(".").slice(0,-1).join("."),r.setPath("")):(c=i.inputSource.handedness==="left"?"left":"right",r.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/"));const d=new I;ja(d);const u=new $C(d,o,r.path,c,r,p=>{var g;const y=l.gltf;((g=y?.scene.children)==null?void 0:g.length)===0&&(y.scene.children[0]=p),gs().createBuiltinComponents(t.context,t.sourceId||c,l.gltf,null,l),p.traverse(f=>{var v;f.layers.set(2),(v=J.active)!=null&&v.isPassThrough&&!h&&this.makeOccluder(f),f instanceof Y&&it.assignMeshLOD(f,0)}),i.connected||(Wn&&q.DrawLabel(i.rayWorldPosition,"Hand is loaded but not connected anymore",.05,5),p.removeFromParent())});if(Wn&&d.add(new xi(.5)),i.inputSource.hand){Wn&&console.log(i.inputSource.hand);for(const p of i.inputSource.hand.values())if(o.joints[p.jointName]===void 0){const g=new oo;g.matrixAutoUpdate=!1,g.visible=!0,o.joints[p.jointName]=g,o.add(g)}}else Wn&&q.DrawLabel(i.rayWorldPosition,"No inputSource.hand found for index "+i.index,.05,5);return{handObject:d,handmesh:u}}makeOccluder(t){if(t instanceof Y){let i=t.material;i instanceof ke&&(i=t.material=i.clone(),i.depthWrite=!0,i.depthTest=!0,i.colorWrite=!1,t.receiveShadow=!1,t.renderOrder=-100)}}}a(on,"factory",new HC),lp([m()],on.prototype,"createControllerModel",2),lp([m()],on.prototype,"createHandModel",2),lp([m(le)],on.prototype,"customLeftHand",2),lp([m(le)],on.prototype,"customRightHand",2);class cp extends A{}var LT=Object.defineProperty,DT=Object.getOwnPropertyDescriptor,Fo=(s,t,i,n)=>{for(var o=n>1?void 0:n?DT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&LT(t,i,o),o};const m0=C("debugwebxr");class ji extends A{constructor(){super(...arguments),a(this,"movementSpeed",1.5),a(this,"rotationStep",30),a(this,"useTeleport",!0),a(this,"usePinchToTeleport",!0),a(this,"useTeleportTarget",!1),a(this,"useTeleportFade",!1),a(this,"showRays",!0),a(this,"showHits",!0),a(this,"isXRMovementHandler",!0),a(this,"xrSessionMode","immersive-vr"),a(this,"_didApplyRotation",!1),a(this,"_didTeleport",!1),a(this,"_teleportBuffer",new Array),a(this,"_plane",null),a(this,"_lines",[]),a(this,"_hitDiscs",[]),a(this,"_hitDistances",[]),a(this,"_lastHitDistances",[]),a(this,"hitPointRaycastFilter",t=>t.type==="SkinnedMesh"?"continue in children":!0)}onUpdateXR(t){const i=t.xr.rig;if(!(i!=null&&i.gameObject)||t.xr.isPassThrough)return;const n=t.xr.leftController,o=t.xr.rightController;n&&this.onHandleMovement(n,i.gameObject),o&&(this.onHandleRotation(o,i.gameObject),this.useTeleport&&this.onHandleTeleport(o,i.gameObject))}onLeaveXR(t){for(const i of this._lines)i.removeFromParent();for(const i of this._hitDiscs)i?.removeFromParent()}onBeforeRender(){var t;(t=this.context.xr)!=null&&t.running&&(this.showRays&&this.renderRays(this.context.xr),this.showHits&&this.renderHits(this.context.xr))}onHandleMovement(t,i){const n=t.getStick("xr-standard-thumbstick");if(n.x!=0||n.y!=0){const o=G(n.x,0,n.y);o.multiplyScalar(this.context.time.deltaTimeUnscaled*this.movementSpeed);const r=Ye(i);o.multiplyScalar(r.x),o.applyQuaternion(t.xr.poseOrientation),o.y=0,o.applyQuaternion(i.worldQuaternion),i.position.add(o),i.updateWorldMatrix(!1,!1);for(const l of i.children)l.updateWorldMatrix(!1,!1)}}onHandleRotation(t,i){if(t._isMxInk)return;const n=t.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=te(this.context.mainCamera).clone();i.rotateY(o*W.toRadians(this.rotationStep));const l=te(this.context.mainCamera).clone().sub(r);l.y=0,i.position.sub(l)}}onHandleTeleport(t,i){var n,o,r,l,c;let h=0;if(t.hand&&this.usePinchToTeleport&&t.isTeleportGesture){const d=t.getPointerId("primary");if(d!=null&&this.context.input.getIsPointerIdInUse(d))return;const u=t.getGesture("pinch");u&&(h=u.value)}else h=(n=t.getStick("xr-standard-thumbstick"))==null?void 0:n.y;if(this._didTeleport)h>=0&&h<.4?this._didTeleport=!1:h<0&&h>-.4&&(this._didTeleport=!1);else if(h>.8){this._didTeleport=!0;const d=this.context.physics.raycastFromRay(t.ray)[0];if(d&&d.object instanceof va){const p=(o=d.normal)==null?void 0:o.dot(G(0,1,0));if(p!==void 0&&p<.4)return}let u=d?.point;if(!u&&!this.useTeleportTarget){this._plane||(this._plane=new nr(new x(0,1,0),0));const p=i.worldPosition;this._plane.setFromNormalAndCoplanarPoint(new x(0,1,0),p);const g=t.ray;u=p.clone(),this._plane.intersectLine(new pC(g.origin,G(g.direction).multiplyScalar(1e4).add(g.origin)),u),u.distanceTo(p)>i.scale.x*10&&(u=null)}if(u){if(this.useTeleportTarget&&!O.getComponentInParent(d.object,cp))return;const p=u.clone();if(m0&&q.DrawSphere(u,.025,16711680,5),(r=this.context.mainCamera)==null?void 0:r.position){const g=(l=this.context.xr)==null?void 0:l.getUserOffsetInRig();g&&(g.y=0,p.sub(g),m0&&q.DrawWireSphere(g.add(p),.025,65280,5))}this._teleportBuffer.push(i.matrix.clone()),this._teleportBuffer.length>10&&this._teleportBuffer.shift(),this.useTeleportFade?(c=t.xr.fadeTransition())==null||c.then(()=>{i.worldPosition=p}):i.worldPosition=p}}else if(h<-.8&&(this._didTeleport=!0,this._teleportBuffer.length>0)){const d=this._teleportBuffer.pop();d&&d.decompose(i.position,i.quaternion,i.scale)}}renderRays(t){var i;for(let n=0;n<this._lines.length;n++){const o=this._lines[n];o&&(o.visible=!1)}for(let n=0;n<t.controllers.length;n++){const o=t.controllers[n];let r=this._lines[n];if(!o.connected||!o.isTracking||!o.ray||o.targetRayMode==="transient-pointer"||!o.hasSelectEvent){r&&(r.visible=!1);continue}r||(r=this.createRayLineObject(),r.scale.z=.5,this._lines[n]=r),o.updateRayWorldPosition(),o.updateRayWorldQuaternion();const l=o.rayWorldPosition,c=o.rayWorldQuaternion;r.position.copy(l),r.quaternion.copy(c);const h=t.rigScale,d=this.usePinchToTeleport&&o.isTeleportGesture,u=this._lastHitDistances[n],p=this._hitDistances[n]!=null,g=u??h;r.scale.set(h,h,g),r.visible=!0,r.layers.disableAll(),r.layers.enable(2);let y=r.material.opacity;d?y=1:this.showHits&&g<t.rigScale*.5?y=0:(i=o.getButton("primary"))!=null&&i.pressed?y=.5:y=p?.2:.1,r.material.opacity=W.lerp(r.material.opacity,y,this.context.time.deltaTimeUnscaled/.1),r.parent!==this.context.scene&&this.context.scene.add(r)}}renderHits(t){var i;for(const n of this._hitDiscs){if(!n)continue;const o=n.controller;if(!o||!o.connected||!o.isTracking){n.visible=!1;continue}}for(let n=0;n<t.controllers.length;n++){const o=t.controllers[n];if(!o.connected||!o.isTracking||!o.ray||!o.hasSelectEvent)continue;let r=this._hitDiscs[n],l=!0;const c=o.getPointerId("primary");c!=null&&this.context.input.getIsPointerIdInUse(c)&&(r&&(r.visible=!1),this._hitDistances[n]=null,this._lastHitDistances[n]=0,l=!1);const h=this.context.time.smoothedFps>=59?1:10;if((this.context.time.frame+o.index)%h!==0&&(l=!1),!l){const p=this._hitDiscs[n];p&&p.visible&&p.hit&&this.updateHitPointerPosition(o,p,p.hit.distance);continue}const d=this.context.physics.raycastFromRay(o.ray,{testObject:this.hitPointRaycastFilter,precise:!1});let u=d.find(p=>this.usePinchToTeleport&&o.isTeleportGesture?!0:this.isObjectWithInteractiveComponent(p.object));if(u||(u=d[0]),r&&(r.controller=o,r.hit=u),this._hitDistances[n]=u?.distance||null,u){this._lastHitDistances[n]=u.distance;const p=t.rigScale??1;m0&&(q.DrawWireSphere(u.point,.025*p,16711680),q.DrawLabel(G(0,.2,0).add(u.point),u.object.name,.02,0)),r||(r=this.createHitPointObject(),this._hitDiscs[n]=r),r.hit=u,r.visible=u.distance>p*.05;let g=.01*(p+u.distance);const y=(i=o.getButton("primary"))==null?void 0:i.pressed;y&&(g*=1.1),r.scale.set(g,g,g),r.layers.set(2);let f=r.material.opacity;if(y?f=1:f=u.distance<.15*p?.2:.6,r.material.opacity=W.lerp(r.material.opacity,f,this.context.time.deltaTimeUnscaled/.1),r.visible){if(u.normal){this.updateHitPointerPosition(o,r,u.distance);const v=u.normal.applyQuaternion(Ce(u.object));r.quaternion.setFromUnitVectors(BT,v)}else this.updateHitPointerPosition(o,r,u.distance);r.parent!==this.context.scene&&this.context.scene.add(r)}}else this._hitDiscs[n]&&(this._hitDiscs[n].visible=!1)}}isObjectWithInteractiveComponent(t,i=0){return Su(t)||t.isUI===!0?!0:t.isScene?!1:t.parent?this.isObjectWithInteractiveComponent(t.parent,i+1):!1}updateHitPointerPosition(t,i,n){const o=G(t.rayWorldPosition);o.add(G(0,0,n-.01).applyQuaternion(t.rayWorldQuaternion)),i.position.lerp(o,this.context.time.deltaTimeUnscaled/.05)}createHitPointObject(){const t=new Y(new nd(.3,6,6),new Re({color:15658734,opacity:.7,transparent:!0,depthTest:!1,depthWrite:!1,side:Si}));return t.layers.disableAll(),t.layers.enable(2),t}createRayLineObject(){const t=new qC;t.layers.disableAll(),t.layers.enable(2);const i=new GC;t.geometry=i;const n=new Float32Array(9);n.set([0,0,.02,0,0,.4,0,0,1]),i.setPositions(n);const o=new Float32Array(9);o.set([1,1,1,.1,.1,.1,0,0,0]),i.setColors(o);const r=new XC({color:16777215,vertexColors:!0,worldUnits:!0,linewidth:.004,transparent:!0,depthWrite:!1,blending:ev,dashed:!1});return t.material=r,t}}Fo([m()],ji.prototype,"movementSpeed",2),Fo([m()],ji.prototype,"rotationStep",2),Fo([m()],ji.prototype,"useTeleport",2),Fo([m()],ji.prototype,"usePinchToTeleport",2),Fo([m()],ji.prototype,"useTeleportTarget",2),Fo([m()],ji.prototype,"useTeleportFade",2),Fo([m()],ji.prototype,"showRays",2),Fo([m()],ji.prototype,"showHits",2);const BT=new x(0,1,0);var FT=Object.defineProperty,zT=Object.getOwnPropertyDescriptor,xt=(s,t,i,n)=>{for(var o=n>1?void 0:n?zT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&FT(t,i,o),o};const uh=C("debugwebxr"),UT=C("debugusdz");var g0;const wl=(g0=class extends A{constructor(){super(...arguments),a(this,"createVRButton",!0),a(this,"createARButton",!0),a(this,"createSendToQuestButton",!0),a(this,"createQRCode",!0),a(this,"useDefaultControls",!0),a(this,"showControllerModels",!0),a(this,"showHandModels",!0),a(this,"usePlacementReticle",!0),a(this,"customARPlacementReticle"),a(this,"usePlacementAdjustment",!0),a(this,"arScale",1),a(this,"useXRAnchor",!1),a(this,"autoPlace",!1),a(this,"autoCenter",!1),a(this,"useQuicklookExport",!1),a(this,"useDepthSensing",!1),a(this,"useSpatialGrab",!0),a(this,"defaultAvatar"),a(this,"_playerSync"),a(this,"_createdComponentsInSession",[]),a(this,"_usdzExporter"),a(this,"_exitXRMenuButton"),a(this,"_previousXRState",0),a(this,"_spatialGrabRaycaster"),a(this,"_activeWebARSessionRoot",null),a(this,"onAvatarSpawned",s=>{uh&&console.log("WebXR.onAvatarSpawned",s),O.getComponentInChildren(s,Do)??(e=O.addComponent(s,Do))}),a(this,"_buttonFactory"),a(this,"_buttons",[])}awake(){J.getXRSync(this.context)}onEnable(){var s,t;window.location.protocol!=="https:"&&we('<a href="https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API" target="_blank">WebXR</a> only works on secure connections (https).'),this.useQuicklookExport&&(O.findObjectOfType($e)||(uh&&console.log("WebXR: Adding USDZExporter"),this._usdzExporter=O.addComponent(this.gameObject,$e),this._usdzExporter.objectToExport=this.context.scene,this._usdzExporter.autoExportAnimations=!0,this._usdzExporter.autoExportAudioSources=!0)),this.handleCreatingHTML(),this.handleOfferSession(),this.defaultAvatar===!0&&(uh&&console.warn("WebXR: No default avatar set, using static default avatar"),this.defaultAvatar=new le("https://cdn.needle.tools/static/avatars/DefaultAvatar.glb")),this.defaultAvatar&&(this._playerSync=this.gameObject.getOrAddComponent(bl),this._playerSync.autoSync=!1),this._playerSync&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,(s=this._playerSync.onPlayerSpawned)==null||s.removeEventListener(this.onAvatarSpawned),(t=this._playerSync.onPlayerSpawned)==null||t.addEventListener(this.onAvatarSpawned))}onDisable(){var s;(s=this._usdzExporter)==null||s.destroy(),this.removeButtons()}async handleOfferSession(){return this.createVRButton&&await J.isVRSupported()&&this.createVRButton?J.offerSession("immersive-vr","default",this.context):this.createARButton&&await J.isARSupported()&&this.createARButton?J.offerSession("immersive-ar","default",this.context):!1}get session(){return J.active??null}get sessionMode(){return J.activeMode??null}get arSessionRoot(){return this._activeWebARSessionRoot}async enterVR(s){return J.start("immersive-vr",s,this.context)}async enterAR(s){return J.start("immersive-ar",s,this.context)}exitXR(){J.stop()}get isActiveWebXR(){return!wl.activeWebXRComponent||wl.activeWebXRComponent===this}onBeforeXR(s,t){var i;if(!this.isActiveWebXR){console.warn(`WebXR: another WebXR component is already active (${(i=wl.activeWebXRComponent)==null?void 0:i.name}). This is ignored: ${this.name}`);return}wl.activeWebXRComponent=this,s=="immersive-ar"&&this.useDepthSensing&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("depth-sensing"))}async onEnterXR(s){if(!this.isActiveWebXR)return;uh&&console.log("WebXR onEnterXR"),this._previousXRState=ci.Global.Mask;const t=s.xr.isVR;if(ci.Global.Set(t?Ys.VR:Ys.AR),s.xr.isAR){let i=O.findObjectOfType(sn);if(!i)if(this.usePlacementReticle){const n=new I;for(const o of this.context.scene.children)n.add(o);this.context.scene.add(n),i=O.addComponent(n,sn),this._createdComponentsInSession.push(i)}else(uh||F())&&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=O.findObjectOfType(Va)??void 0,this._spatialGrabRaycaster||(this._spatialGrabRaycaster=this.gameObject.addComponent(Va))),this.createLocalAvatar(s.xr),s.xr.isScreenBasedAR||(this._exitXRMenuButton=this.context.menu.appendChild({label:"Quit XR",onClick:()=>this.exitXR(),icon:"exit_to_app",priority:2e4}))}onUpdateXR(s){this.isActiveWebXR&&this._spatialGrabRaycaster&&(this._spatialGrabRaycaster.enabled=this.useSpatialGrab)}onLeaveXR(s){var t,i;if((t=this._exitXRMenuButton)==null||t.remove(),!!this.isActiveWebXR){ci.Global.Set(this._previousXRState),(i=this._playerSync)==null||i.destroyInstance();for(const n of this._createdComponentsInSession)n.destroy();this._createdComponentsInSession.length=0,this._activeWebARSessionRoot=null,this.handleOfferSession(),Kl(1).then(()=>wl.activeWebXRComponent=null)}}setDefaultMovementEnabled(s){let t=this.gameObject.getComponent(ji);return!t&&s&&(t=this.gameObject.addComponent(ji),this._createdComponentsInSession.push(t)),t&&(t.enabled=s),t}setDefaultControllerRenderingEnabled(s){let t=this.gameObject.getComponent(on);return!t&&s&&(t=this.gameObject.addComponent(on),this._createdComponentsInSession.push(t),t.createControllerModel=this.showControllerModels,t.createHandModel==this.showHandModels),t&&(t.enabled=s),t}async createLocalAvatar(s){this._playerSync&&s.running&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,await this._playerSync.getInstance())}getButtonsContainer(){return this.getButtonsFactory()}getButtonsFactory(){return this._buttonFactory||(this._buttonFactory=zr.getOrCreate()),this._buttonFactory}handleCreatingHTML(){if(this.createARButton||this.createVRButton||this.useQuicklookExport){if((X.isiOS()&&X.isSafari()||UT)&&this.useQuicklookExport){const s=O.findObjectOfType($e);if(!s||s&&s.allowCreateQuicklookButton){const t=this.getButtonsFactory().createQuicklookButton();this.addButton(t,50)}}if(this.createARButton){const s=this.getButtonsFactory().createARButton();this.addButton(s,50)}if(this.createVRButton){const s=this.getButtonsFactory().createVRButton();this.addButton(s,50)}}if(this.createSendToQuestButton&&!X.isQuest()&&J.isVRSupported().then(s=>{if(!s){const t=this.getButtonsFactory().createSendToQuestButton();this.addButton(t,50)}}),this.createQRCode){const s=kc(nn);if(s&&s.createQRCodeButton===!1)F()&&console.warn("WebXR: QRCode button is disabled in the Needle Menu component");else if(!X.isMobileDevice()){const t=kn.getOrCreate().createQRCode();this.addButton(t,50)}}}addButton(s,t){this._buttons.push(s),s.setAttribute("priority",t.toString()),this.context.menu.appendChild(s)}removeButtons(){for(const s of this._buttons)s.remove();this._buttons.length=0}},a(g0,"activeWebXRComponent",null),g0);let Je=wl;xt([m()],Je.prototype,"createVRButton",2),xt([m()],Je.prototype,"createARButton",2),xt([m()],Je.prototype,"createSendToQuestButton",2),xt([m()],Je.prototype,"createQRCode",2),xt([m()],Je.prototype,"useDefaultControls",2),xt([m()],Je.prototype,"showControllerModels",2),xt([m()],Je.prototype,"showHandModels",2),xt([m()],Je.prototype,"usePlacementReticle",2),xt([m(le)],Je.prototype,"customARPlacementReticle",2),xt([m()],Je.prototype,"usePlacementAdjustment",2),xt([m()],Je.prototype,"arScale",2),xt([m()],Je.prototype,"useXRAnchor",2),xt([m()],Je.prototype,"autoPlace",2),xt([m()],Je.prototype,"autoCenter",2),xt([m()],Je.prototype,"useQuicklookExport",2),xt([m()],Je.prototype,"useDepthSensing",2),xt([m()],Je.prototype,"useSpatialGrab",2),xt([m(le)],Je.prototype,"defaultAvatar",2);const hp=C("debugusdzbehaviours");class f0{constructor(){a(this,"behaviours",[]),a(this,"behaviourComponents",[]),a(this,"behaviourComponentsCopy",[]),a(this,"audioClips",[]),a(this,"audioClipsCopy",[]),a(this,"targetUuids",new Set)}get extensionName(){return"Behaviour"}addBehavior(t){this.behaviours.push(t)}addAudioClip(t){if(!t||typeof t!="string")return"";const i="audio/"+da.getName(t);return this.audioClips.push({clipUrl:t,filesKey:i}),i}getAllTargetUuids(){return this.targetUuids}onBeforeBuildDocument(t){if(!t.root)return Promise.resolve();const i=[];return t.root.traverse(n=>{O.foreachComponent(n,o=>{var r;const l=o;if(typeof l.createBehaviours=="function"||typeof l.beforeCreateDocument=="function"||typeof l.afterCreateDocument=="function"||typeof l.afterSerialize=="function"){this.behaviourComponents.push(l);const c=(r=l.beforeCreateDocument)==null?void 0:r.call(l,this,t);c instanceof Promise&&i.push(c)}},!1)}),hp&&console.log("onBeforeBuildDocument: all components",this.behaviourComponents),Promise.all(i)}onExportObject(t,i,n){var o;for(const r of this.behaviourComponents)(o=r.createBehaviours)==null||o.call(r,this,i,n)}onAfterBuildDocument(t){for(const p of this.behaviourComponents)typeof p.afterCreateDocument=="function"&&p.afterCreateDocument(this,t);this.behaviourComponentsCopy=this.behaviourComponents.slice(),this.behaviourComponents.length=0,this.audioClipsCopy=this.audioClips.slice(),this.audioClips.length=0;const i=new Set,n=new Set,o=new Set,r=new Set,l=hp;let c=`graph LR
1200
1204
  `,h="";function d(p){if(p instanceof Eo){l&&(c+=`subgraph Group_${p.id}
1201
1205
  `);for(const g of p.actions)l&&(c+=`${p.id}[${p.id}] -- ${p.type},loops:${p.loops} --> ${g.id}[${g.id}]
1202
1206
  `),d(g);l&&(c+=`end
@@ -1218,7 +1222,7 @@ dateFormat X
1218
1222
  axisFormat %s
1219
1223
  `;const g=Array.from(r),y=new Set;for(const w of g)if(w.affectedObjects&&typeof w.affectedObjects!="string"){if(Array.isArray(w.affectedObjects))for(const _ of w.affectedObjects)y.add(_);else y.add(w.affectedObjects);l&&(p+=`section ${w.animationName} (${w.id})
1220
1224
  `,p+=`${w.id} : ${w.start}, ${w.duration}s
1221
- `)}l&&r.size&&console.log(p);const f=new Set;for(const w of y){w.getPath||console.error("USDZExporter: Animation target object has no getPath method. This is likely a bug",w);let _=w.getPath();_.startsWith("<")&&(_=_.substring(1)),_.endsWith(">")&&(_=_.substring(0,_.length-1)),f.add({path:_,obj:w})}const v=Array.from(f).sort((w,_)=>w.path.length-_.path.length),b=new Array;for(let w=0;w<v.length;w++)for(let _=w+1;_<v.length;_++)if(v[_].path.startsWith(v[w].path)){const S=v[_],R=v[w];b.push({child:S.obj.displayName+" ("+S.path+")",parent:R.obj.displayName+" ("+R.path+")"})}b.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:b,playAnimationActions:r})}for(const p of new Set([...i,...n]))if(Array.isArray(p))for(const g of p)o.add(g.uuid);else o.add(p.uuid);hp&&console.log("All Behavior trigger sources and action targets",i,n,o),this.targetUuids=new Set(o)}onAfterHierarchy(t,i){var n;if((n=this.behaviours)!=null&&n.length){i.beginBlock('def Scope "Behaviors"');for(const o of this.behaviours)o.writeTo(this,t.document,i);i.closeBlock()}}async onAfterSerialize(t){hp&&console.log("onAfterSerialize behaviours",this.behaviourComponentsCopy);for(const i of this.behaviourComponentsCopy)typeof i.afterSerialize=="function"&&(i.afterSerialize.constructor.name==="AsyncFunction"?await i.afterSerialize(this,t):i.afterSerialize(this,t));for(const{clipUrl:i,filesKey:n}of this.audioClipsCopy){if(t.files[n])return;const o=await(await(await fetch(i)).blob()).arrayBuffer(),r=new Uint8Array(o);t.files[n]=r}this.behaviourComponentsCopy.length=0,this.audioClipsCopy.length=0}}class y0{get extensionName(){return"Physics"}onExportObject(t,i,n){const o=O.getComponents(t,ye).filter(h=>h.enabled),r=O.getComponents(t,di).filter(h=>h.enabled&&!h.isTrigger);let l=o.length>0?o[0]:null;const c=r.length>0?r[0]:null;c&&!l&&(l=new ye,l.isKinematic=!0),l&&i.addEventListener("serialize",(h,d)=>{var u,p,g;if(l){if(h.appendLine(),h.beginBlock('def RealityKitComponent "RigidBody"',"{",!0),l.useGravity||h.appendLine("bool gravityEnabled = 0"),h.appendLine('uniform token info:id = "RealityKit.RigidBody"'),l.isKinematic&&h.appendLine('token motionType = "Kinematic"'),h.beginBlock('def RealityKitStruct "massFrame"',"{",!0),h.appendLine(`float m_mass = ${l.mass}`),h.beginBlock('def RealityKitStruct "m_pose"',"{",!0),h.appendLine(`float3 position = (${l.centerOfMass.x}, ${l.centerOfMass.y}, ${l.centerOfMass.z})`),h.closeBlock("}"),h.closeBlock("}"),r.length>0){const y=r[0];h.beginBlock('def RealityKitStruct "material"',"{",!0);const f=y.sharedMaterial;f&&f.dynamicFriction!==void 0&&h.appendLine(`double dynamicFriction = ${(u=y.sharedMaterial)==null?void 0:u.dynamicFriction}`),f&&f.bounciness!==void 0&&h.appendLine(`double restitution = ${(p=y.sharedMaterial)==null?void 0:p.bounciness}`),f&&f.staticFriction!==void 0&&h.appendLine(`double staticFriction = ${(g=y.sharedMaterial)==null?void 0:g.staticFriction}`),h.closeBlock("}")}h.closeBlock("}")}}),c&&(i.addEventListener("serialize",(h,d)=>{var u;h.beginBlock('def RealityKitComponent "Collider"',"{",!0),h.appendLine("uint group = 1"),h.appendLine('uniform token info:id = "RealityKit.Collider"'),h.appendLine("uint mask = 4294967295");const p=c.isTrigger?"Trigger":"Default";if(h.appendLine(`token type = "${p}"`),h.beginBlock('def RealityKitStruct "Shape"',"{",!0),c instanceof Qa){const g=c;h.appendLine('token shapeType = "Sphere"'),h.appendLine(`float radius = ${g.radius}`)}else if(c instanceof Ya){const g=c;h.appendLine('token shapeType = "Box"'),h.appendLine(`float3 extent = (${g.size.x}, ${g.size.y}, ${g.size.z})`)}else if(c instanceof In){const g=c;h.appendLine('token shapeType = "Capsule"'),h.appendLine(`float radius = ${g.radius}`),h.appendLine(`float height = ${g.height}`)}else if(c instanceof Ro&&(u=c.sharedMesh)!=null&&u.geometry){const g=c.sharedMesh.geometry;g.boundingBox||g.computeBoundingBox();const y=c.sharedMesh.geometry.boundingBox;y&&(h.appendLine('token shapeType = "Box"'),h.appendLine(`float3 extent = (${y.max.x-y.min.x}, ${y.max.y-y.min.y}, ${y.max.z-y.min.z})`),console.log("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. MeshCollider will be exported as Box",c))}else console.warn("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. Ignoring collider:",c);h.beginBlock('def RealityKitStruct "pose"',"{",!0),h.closeBlock("}"),h.closeBlock("}"),h.closeBlock("}")}),r.length>1&&console.log("WARNING: Multiple colliders detected. visionOS / iOS can only support objects with a single collider, only exporting the first collider: ",c))}}var NT=Object.defineProperty,WT=Object.getOwnPropertyDescriptor,ph=(s,t,i,n)=>{for(var o=n>1?void 0:n?WT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&NT(t,i,o),o};const v0=C("debugui"),b0=C("debuguilayout");class Gx{constructor(){a(this,"width"),a(this,"height")}}class Xx{constructor(){a(this,"x"),a(this,"y"),a(this,"width"),a(this,"height")}}const Ts=new x,mh=new ne,dp=new V,Qx=class extends rs{constructor(){super(...arguments),a(this,"_anchoredPosition"),a(this,"sizeDelta",new re(100,100)),a(this,"pivot",new re(.5,.5)),a(this,"anchorMin",new re(0,0)),a(this,"anchorMax",new re(1,1)),a(this,"minWidth"),a(this,"minHeight"),a(this,"lastMatrix"),a(this,"rectBlock"),a(this,"_transformNeedsUpdate",!1),a(this,"_initialPosition"),a(this,"_parentRectTransform"),a(this,"_lastUpdateFrame",-1),a(this,"_lastAnchoring"),a(this,"_createdBlocks",[]),a(this,"_createdTextBlocks",[])}get parent(){return this._parentRectTransform}get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new re),this._anchoredPosition}set anchoredPosition(s){this._anchoredPosition=s}get width(){let s=this.sizeDelta.x;if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const t=this._parentRectTransform.width,i=this.anchorMax.x-this.anchorMin.x;s=t*i,s+=this.sizeDelta.x}return this.minWidth!==void 0&&s<this.minWidth?this.minWidth:s}get height(){let s=this.sizeDelta.y;if(this.anchorMin.y!==this.anchorMax.y&&this._parentRectTransform){const t=this._parentRectTransform.height,i=this.anchorMax.y-this.anchorMin.y;s=t*i,s+=this.sizeDelta.y}return this.minHeight!==void 0&&s<this.minHeight?this.minHeight:s}awake(){super.awake(),this._anchoredPosition||(this._anchoredPosition=new re),this.lastMatrix=new ne,this.rectBlock=new I,this.rectBlock.name=this.name,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,Ha(this,"_anchoredPosition",()=>{this.markDirty()}),Ha(this,"sizeDelta",()=>{this.markDirty()}),Ha(this,"pivot",()=>{this.markDirty()}),Ha(this,"anchorMin",()=>{this.markDirty()}),Ha(this,"anchorMax",()=>{this.markDirty()})}onEnable(){var s;super.onEnable(),this.rectBlock||(this.rectBlock=new I),this.lastMatrix||(this.lastMatrix=new ne),this._lastAnchoring||(this._lastAnchoring=new re),this._initialPosition||(this._initialPosition=new x),this._anchoredPosition||(this._anchoredPosition=new re),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,(s=this.canvas)==null||s.registerTransform(this)}onDisable(){var s;super.onDisable(),this.removeShadowComponent(),(s=this.canvas)==null||s.unregisterTransform(this)}onParentRectTransformChanged(s){this._transformNeedsUpdate||this.onApplyTransform(b0?`${s.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(b0&&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(s){var t;if(this.context.time.frameCount===this._lastUpdateFrame)return;this._lastUpdateFrame=this.context.time.frameCount;const i=this.shadowComponent;if(!i)return;this.gameObject.parent?this._parentRectTransform=O.getComponentInParent(this.gameObject.parent,Qx):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,b0&&console.warn("RectTransform \u2192 ApplyTransform",this.name+" because "+s),this.isRoot()?this.Root.screenspace||(i.rotation.y=Math.PI):(i.matrix.identity(),i.matrixAutoUpdate=!1,Ts.set(0,0,0),this.applyPivot(Ts),i.matrix.setPosition(Ts.x,Ts.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(dp.copy(this.gameObject.quaternion),dp.x*=-1,dp.z*=-1,mh.makeRotationFromQuaternion(dp),i.matrix.premultiply(mh)),Ts.set(0,0,0),this.applyAnchoring(Ts),(t=this.canvas)!=null&&t.screenspace?Ts.z+=.1:Ts.z+=.01,mh.identity(),mh.setPosition(Ts.x,Ts.y,Ts.z),i.matrix.premultiply(mh),i.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const n=!0;for(const o of Zd(this.gameObject,rs,n,1)){if(o===this||!o.activeAndEnabled)continue;const r=o;r.onParentRectTransformChanged&&r.onParentRectTransformChanged(this)}}applyAnchoring(s){this._lastAnchoring||(this._lastAnchoring=new re);const t=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=t.x,this.gameObject.position.y+=t.y,this._lastAnchoring.copy(this._anchoredPosition),s.x+=this._initialPosition.x-this.gameObject.position.x,s.y+=this._initialPosition.y-this.gameObject.position.y,s.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,s.y+=n;let r=0;const l=1-this.anchorMax.x-this.anchorMin.x;r-=i.width*.5*l,s.x+=r}}applyPivot(s){if(this.pivot&&!this.isRoot()){const t=this.pivot.x-.5;s.x-=t*this.sizeDelta.x*this.gameObject.scale.x;const i=this.pivot.y-.5;s.y-=i*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){const s={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:0,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(s),s}ensureValidSize(s,t=1e-4){return s.width<=0&&(s.width=t),s.height<=0&&(s.height=1e-4),s}createNewBlock(s){s={...this.getBasicOptions(),...s},v0&&console.log(this.name,s);const t=new gv(s);return this._createdBlocks.push(t),t}createNewText(s){v0&&console.log(s),s={...this.getBasicOptions(),...s},v0&&console.log(this.name,s);const t=new mv(s);return this._createdTextBlocks.push(t),t}};let Wt=Qx;ph([m(re)],Wt.prototype,"anchoredPosition",1),ph([m(re)],Wt.prototype,"sizeDelta",2),ph([m(re)],Wt.prototype,"pivot",2),ph([m(re)],Wt.prototype,"anchorMin",2),ph([m(re)],Wt.prototype,"anchorMax",2);var VT=Object.defineProperty,HT=Object.getOwnPropertyDescriptor,Yx=(s,t,i,n)=>{for(var o=n>1?void 0:n?HT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&VT(t,i,o),o};class xl extends A{constructor(){super(...arguments),a(this,"effectColor"),a(this,"effectDistance")}}Yx([m(xe)],xl.prototype,"effectColor",2),Yx([m(re)],xl.prototype,"effectDistance",2);var $T=Object.defineProperty,qT=Object.getOwnPropertyDescriptor,Zx=(s,t,i,n)=>{for(var o=n>1?void 0:n?qT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&$T(t,i,o),o};const up={backgroundColor:new ae(1,1,1),backgroundOpacity:1,borderColor:new ae(1,1,1),borderOpacity:1};var _0;const gh=(_0=class extends rs{constructor(){super(...arguments),a(this,"_alphaFactor",1),a(this,"sRGBColor",new ae(1,0,1)),a(this,"raycastTarget",!0),a(this,"uiObject",null),a(this,"_color",null),a(this,"_rect",null),a(this,"_stateManager",null),a(this,"_currentlyCreatingPanel",!1)}get isGraphic(){return!0}get color(){return this._color||(this._color=new xe(1,1,1,1)),this._color}set color(s){(!this._color||this._color.r!==s.r||this._color.g!==s.g||this._color.b!==s.b||this._color.alpha!==s.alpha)&&(this._color||(this._color=new xe(1,1,1,1)),this._color.copy(s),this.onColorChanged())}setAlphaFactor(s){this._alphaFactor=s,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}onColorChanged(){this.uiObject&&(this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),up.backgroundColor=this.sRGBColor,up.backgroundOpacity=this._color.alpha*this._alphaFactor,this.applyEffects(up,this._alphaFactor),this.uiObject.set(up),this.markDirty())}get m_Color(){return this._color}get rectTransform(){if(this._rect||(this._rect=O.getComponent(this.gameObject,Wt)),!this._rect)throw new Error("Not Supported: Make sure to add a RectTransform component before adding a UI Graphic component.");return this._rect}onParentRectTransformChanged(){var s;(s=this.uiObject)==null||s.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(s){return super.__internalNewInstanceCreated(s),this._rect=null,this.uiObject=null,this._color&&(this._color=this._color.clone()),this}setState(s){this.makePanel(),this.uiObject&&(this.uiObject.setState(s),this==null||this.markDirty())}setupState(s){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new mO(this.uiObject)),this.uiObject.setupState(s.state,s.attributes))}setOptions(s){this.makePanel(),this.uiObject&&this.uiObject.set(s)}awake(){super.awake(),this.makePanel(),Ha(this,"_color",()=>bM(this,this.onColorChanged))}onEnable(){var s;super.onEnable(),this.uiObject&&((s=this.rectTransform.shadowComponent)==null||s.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;const s=.015,t={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:s};this.onBeforeCreate(t),this.applyEffects(t),this.onCreate(t),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated(),this.onColorChanged()}onBeforeCreate(s){}onCreate(s){this.uiObject=this.rectTransform.createNewBlock(s),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(s,t=1){var i;const n=(i=this.gameObject)==null?void 0:i.getComponent(xl);n&&(n.effectDistance&&(s.borderWidth=Math.max(Math.abs(n.effectDistance.x),Math.abs(n.effectDistance.y))),n.effectColor&&(s.borderColor=n.effectColor,s.borderOpacity=n.effectColor.alpha*t))}async setTexture(s){if(this.setOptions({backgroundOpacity:0}),s){if(gh.textureCache.has(s))s=gh.textureCache.get(s);else if(!s.isRenderTargetTexture){const t=s.clone();t.colorSpace=or,gh.textureCache.set(s,t),s=t}this.setOptions({backgroundImage:s,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}),it.assignTextureLOD(s,0).then(t=>{t instanceof Le&&(s&&gh.textureCache.set(s,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)}},a(_0,"textureCache",new Map),_0);let Ur=gh;Zx([m(xe)],Ur.prototype,"color",1),Zx([m()],Ur.prototype,"raycastTarget",2);class fh extends Ur{constructor(){super(...arguments),a(this,"_flippedObject",!1)}onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var GT=Object.defineProperty,XT=Object.getOwnPropertyDescriptor,Vn=(s,t,i,n)=>{for(var o=n>1?void 0:n?XT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&GT(t,i,o),o};const Nr=C("debugtext");var pt=(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))(pt||{}),Kx=(s=>(s[s.Normal=0]="Normal",s[s.Bold=1]="Bold",s[s.Italic=2]="Italic",s[s.BoldAndItalic=3]="BoldAndItalic",s))(Kx||{});class Vt extends Ur{constructor(){super(...arguments),a(this,"alignment",0),a(this,"verticalOverflow",0),a(this,"horizontalOverflow",0),a(this,"lineSpacing",1),a(this,"supportRichText",!1),a(this,"font"),a(this,"fontStyle",0),a(this,"sRGBTextColor",new ae(1,0,1)),a(this,"_text",""),a(this,"_fontSize",12),a(this,"_textMeshUi",null),a(this,"_didHandleTextRenderOnTop",!1)}setAlphaFactor(t){var i;super.setAlphaFactor(t),(i=this.uiObject)==null||i.set({fontOpacity:this.color.alpha*this.alphaFactor}),this.markDirty()}get text(){return this._text}set text(t){t!==this._text&&(this._text=t,this.feedText(this.text,this.supportRichText),this.markDirty())}set_text(t){this.text=t}get fontSize(){return this._fontSize}set fontSize(t){var i;this._fontSize=t,(i=this.uiObject)==null||i.set({fontSize:t})}onColorChanged(){var t;this.sRGBTextColor.copy(this.color),this.sRGBTextColor.convertLinearToSRGB(),(t=this.uiObject)==null||t.set({color:this.sRGBTextColor,fontOpacity:this.color.alpha})}onParentRectTransformChanged(){super.onParentRectTransformChanged(),this.uiObject&&this.updateOverflow()}onBeforeCanvasRender(t){this.updateOverflow()}updateOverflow(){var t;const i=(t=this.uiObject)==null?void 0:t._overflow;i&&(i._needsUpdate=!0)}onCreate(t){Nr&&console.log(this),this.horizontalOverflow==1&&(t.whiteSpace="pre"),this.verticalOverflow==0&&(this.context.renderer.localClippingEnabled=!0,t.overflow="hidden"),this.horizontalOverflow==1&&this.verticalOverflow==0,t.lineHeight=this.lineSpacing,delete t.backgroundOpacity,delete t.backgroundColor,Nr&&(t.backgroundColor=16750848,t.backgroundOpacity=.5);const i=this.rectTransform;t={...t,...this.getTextOpts()},this.getAlignment(t),Nr&&(t.backgroundColor=Math.random()*16777215,t.backgroundOpacity=.1),this.uiObject=i.createNewText(t),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}getTextOpts(){const t=this.fontSize,i={color:this.color,fontOpacity:this.color.alpha,fontSize:t,fontKerning:"normal"};return this.setFont(i,this.fontStyle),i}onEnable(){var t;super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&this.uiObject.addAfterUpdate(()=>{this.setShadowComponentOwner(this.uiObject),this.markDirty()}),setTimeout(()=>this.markDirty(),10),(t=this.canvas)==null||t.registerEventReceiver(this)}onDisable(){var t;super.onDisable(),(t=this.canvas)==null||t.unregisterEventReceiver(this)}getAlignment(t){switch(t.flexDirection="column",this.alignment){case 0:case 3:case 6:t.textAlign="left";break;case 1:case 4:case 7:t.textAlign="center";break;case 2:case 5:case 8:t.textAlign="right";break}switch(this.alignment){default:case 0:case 1:case 2:t.alignItems="start";break;case 3:case 4:case 5:t.alignItems="center";break;case 6:case 7:case 8:t.alignItems="end";break}return t}feedText(t,i){var n,o,r;if(Nr&&console.log("feedText",this.uiObject,t,i),!!this.uiObject)if(this._textMeshUi||(this._textMeshUi=[]),this.uiObject.children.length=0,!i||t.length===0)this.uiObject.textContent=t;else{let l=this.getNextTag(t);if(l){if(l.startIndex>0){for(let d=this.uiObject.children.length-1;d>=0;d--){const u=this.uiObject.children[d];u.isUI&&(this.uiObject.remove(u),u.clear())}const h=new _m({textContent:t.substring(0,l.startIndex),color:"inherit"});this.uiObject.add(h)}}else{this.uiObject.textContent="",this.setOptions({textContent:t});return}const c=[];for(;l;){const h=this.getNextTag(t,l.endIndex),d={fontFamily:(n=this.uiObject)==null?void 0:n.get("fontFamily"),color:"inherit",textContent:""};if(h){d.textContent=this.getText(t,l,h),this.handleTag(l,d,c);const u=new _m(d);(o=this.uiObject)==null||o.add(u)}else{d.textContent=t.substring(l.endIndex),this.handleTag(l,d,c);const u=new _m(d);(r=this.uiObject)==null||r.add(u)}l=h}}}handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const t=[],i=this.canvas,n={renderOnTop:i.renderOnTop,depthWrite:i.depthWrite,doubleSided:i.doubleSided};for(;;){let o=!1;if(this._textMeshUi)for(let r=0;r<this._textMeshUi.length;r++){if(t[r]===!0)continue;o=!0;const l=this._textMeshUi[r];l.textContent&&(Mu(l,n),t[r]=!0)}if(!o)break;yield}}handleTag(t,i,n){if(!t.isEndTag){if(t.type.includes("color")){const o=new w0(t,{color:i.color});if(n.push(o),t.type.length>6){const r=parseInt("0x"+t.type.substring(7));i.color=r}else i.color=new ae(1,1,1)}else if(t.type=="b"){this.setFont(i,1);const o=new w0(t,{fontWeight:700});n.push(o)}else if(t.type=="i"){this.setFont(i,2);const o=new w0(t,{fontStyle:"italic"});n.push(o)}}}getText(t,i,n){return t.substring(i.endIndex,n.startIndex)}getNextTag(t,i=0){const n=t.indexOf("<",i),o=t.indexOf(">",n);if(n>=0&&o>=0){const r=t.substring(n+1,o);return{type:r,startIndex:n,endIndex:o+1,isEndTag:r.startsWith("/")}}return null}setFont(t,i){if(!this.font)return;const n=this.font,o=this.getFamilyNameWithCorrectSuffix(n,i);Nr&&console.log("Selected font family:"+o);let r=fv.getFontFamily(o);switch(r||(r=fv.addFontFamily(o)),t.fontFamily=r,i){default:case 0:t.fontWeight=400,t.fontStyle="normal";break;case 1:t.fontWeight=700,t.fontStyle="normal";break;case 2:t.fontWeight=400,t.fontStyle="italic";break;case 3:t.fontStyle="italic",t.fontWeight=400}let l=r.getVariant(t.fontWeight,t.fontStyle);if(!l){let c=o;c!=null&&c.endsWith("-msdf.json")||(c+="-msdf.json");let h=o;h!=null&&h.endsWith(".png")||(h+=".png"),l=r.addVariant(t.fontWeight,t.fontStyle,c,h),l?.addEventListener("ready",()=>{this.markDirty()})}}getFamilyNameWithCorrectSuffix(t,i){var n;const o=t.lastIndexOf("-");if(o<0)return t;const r=(n=t.substring(o+1))==null?void 0:n.toLowerCase();if(QT.includes(r))return Nr&&console.warn("Unsupported font style: "+r),t;const l=t.lastIndexOf("/");let c=t;l>=0&&(c=c.substring(l+1));const h=c[0]===c[0].toUpperCase(),d=t.substring(0,o);switch(Nr&&console.log("Select font: ",t,Kx[i],c,h,d),i){case 0:return h?d+"-Regular":d+"-regular";case 1:return h?d+"-Bold":d+"-bold";case 2:return h?d+"-Italic":d+"-italic";case 3:return h?d+"-BoldItalic":d+"-bolditalic";default:return t}}}Vn([m()],Vt.prototype,"alignment",2),Vn([m()],Vt.prototype,"verticalOverflow",2),Vn([m()],Vt.prototype,"horizontalOverflow",2),Vn([m()],Vt.prototype,"lineSpacing",2),Vn([m()],Vt.prototype,"supportRichText",2),Vn([m(URL)],Vt.prototype,"font",2),Vn([m()],Vt.prototype,"fontStyle",2),Vn([m()],Vt.prototype,"text",1),Vn([m()],Vt.prototype,"fontSize",1);class w0{constructor(t,i){a(this,"tag"),a(this,"previousValues"),this.tag=t,this.previousValues=i}}const QT=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class Wr{constructor(t){a(this,"id"),a(this,"content",""),a(this,"font",[]),a(this,"pointSize",144),a(this,"width"),a(this,"height"),a(this,"depth"),a(this,"wrapMode"),a(this,"horizontalAlignment"),a(this,"verticalAlignment"),a(this,"material"),this.id=t}static getId(){return this.global_id++}setDepth(t){return this.depth=t,this}setPointSize(t){return this.pointSize=t,this}setHorizontalAlignment(t){return this.horizontalAlignment=t,this}setVerticalAlignment(t){return this.verticalAlignment=t,this}writeTo(t,i){var n;i.beginBlock(`def Preliminary_Text "${this.id}"`,"(",!1),i.appendLine('prepend apiSchemas = ["MaterialBindingAPI"]'),i.closeBlock(")"),i.beginBlock(),this.content&&i.appendLine(`string content = "${this.content}"`),(!this.font||this.font.length<=0)&&(this.font||(this.font=[]),(n=this.font)==null||n.push("sans-serif"));const o=this.font.map(r=>`"${r}"`).join(", ");i.appendLine(`string[] font = [ ${o} ]`),i.appendLine(`double pointSize = ${this.pointSize}`),typeof this.width=="number"&&i.appendLine(`double width = ${this.width}`),typeof this.height=="number"&&i.appendLine(`double height = ${this.height}`),typeof this.depth=="number"&&i.appendLine(`double depth = ${this.depth}`),this.wrapMode&&i.appendLine(`token wrapMode = "${this.wrapMode}"`),this.horizontalAlignment&&i.appendLine(`token horizontalAlignment = "${this.horizontalAlignment}"`),this.verticalAlignment&&i.appendLine(`token verticalAlignment = "${this.verticalAlignment}"`),this.material!==void 0&&i.appendLine(`rel material:binding = </StageRoot/Materials/${Zf(this.material)}>`),i.closeBlock()}}a(Wr,"global_id",0);class x0{static singleLine(t,i,n){const o=new Wr("text_"+Wr.getId());return o.content=t,i&&(o.pointSize=i),n&&(o.depth=n),o}static multiLine(t,i,n,o,r,l){const c=new Wr("text_"+Wr.getId());return c.content=t,c.width=i,c.height=n,c.horizontalAlignment=o,c.verticalAlignment=r,l!==void 0&&(c.wrapMode=l),c}}const YT=new ne().makeRotationY(Math.PI),ZT=new ne().makeScale(-1,1,-1);class pp{get extensionName(){return"text"}exportText(t,i,n){const o=O.getComponent(t,Vt);if(!o)return;const r=O.getComponent(t,Wt);let l=100,c=100;r&&(l=r.width,c=r.height);const h=YT.clone();r&&h.premultiply(ZT),i.setMatrix(h);const d=o.color.clone();i.material=new ni({color:d,emissive:d}),i.addEventListener("serialize",(u,p)=>{let g=o.text;g=g.replace(/\r/g,""),g=g.replace(/\n/g,"\\n");const y=x0.multiLine(g,l,c,"center","bottom","flowing");this.setTextAlignment(y,o.alignment),this.setOverflow(y,o),i.material&&(y.material=i.material),y.pointSize=this.convertToTextSize(o.fontSize),y.depth=.001,y.writeTo(void 0,u)})}convertToTextSize(t){return 1/.0502*144*t}setOverflow(t,i){i.horizontalOverflow?t.wrapMode="singleLine":t.wrapMode="flowing"}setTextAlignment(t,i){switch(i){case pt.LowerLeft:case pt.MiddleLeft:case pt.UpperLeft:t.horizontalAlignment="left";break;case pt.LowerCenter:case pt.MiddleCenter:case pt.UpperCenter:t.horizontalAlignment="center";break;case pt.LowerRight:case pt.MiddleRight:case pt.UpperRight:t.horizontalAlignment="right";break}switch(i){case pt.LowerLeft:case pt.LowerCenter:case pt.LowerRight:t.verticalAlignment="bottom";break;case pt.MiddleLeft:case pt.MiddleCenter:case pt.MiddleRight:t.verticalAlignment="middle";break;case pt.UpperLeft:case pt.UpperCenter:case pt.UpperRight:t.verticalAlignment="top";break}}}var KT=Object.defineProperty,JT=Object.getOwnPropertyDescriptor,at=(s,t,i,n)=>{for(var o=n>1?void 0:n?JT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&KT(t,i,o),o};const Jx=C("debuguilayout");class Vr{constructor(){a(this,"left",0),a(this,"right",0),a(this,"top",0),a(this,"bottom",0)}get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}at([m()],Vr.prototype,"left",2),at([m()],Vr.prototype,"right",2),at([m()],Vr.prototype,"top",2),at([m()],Vr.prototype,"bottom",2);class Li extends A{constructor(){super(...arguments),a(this,"_rectTransform",null),a(this,"_needsUpdate",!1),a(this,"childAlignment",0),a(this,"reverseArrangement",!1),a(this,"spacing",0),a(this,"padding"),a(this,"minWidth",0),a(this,"minHeight",0),a(this,"flexibleHeight",0),a(this,"flexibleWidth",0),a(this,"preferredHeight",0),a(this,"preferredWidth",0)}get rectTransform(){return this._rectTransform}onParentRectTransformChanged(t){this._needsUpdate=!0}get isDirty(){return this._needsUpdate}get isLayoutGroup(){return!0}updateLayout(){this._rectTransform&&(Jx&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}start(){this._needsUpdate=!0}onEnable(){Jx&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(Wt);const t=this.gameObject.getComponentInParent(Et);t&&t.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const t=this.gameObject.getComponentInParent(Et);t&&t.unregisterLayoutGroup(this)}set m_Spacing(t){t!==this.spacing&&(this._needsUpdate=!0,this.spacing=t)}get m_Spacing(){return this.spacing}}at([m()],Li.prototype,"childAlignment",2),at([m()],Li.prototype,"reverseArrangement",2),at([m()],Li.prototype,"spacing",2),at([m(Vr)],Li.prototype,"padding",2),at([m()],Li.prototype,"minWidth",2),at([m()],Li.prototype,"minHeight",2),at([m()],Li.prototype,"flexibleHeight",2),at([m()],Li.prototype,"flexibleWidth",2),at([m()],Li.prototype,"preferredHeight",2),at([m()],Li.prototype,"preferredWidth",2);class zo extends Li{constructor(){super(...arguments),a(this,"childControlHeight",!0),a(this,"childControlWidth",!0),a(this,"childForceExpandHeight",!1),a(this,"childForceExpandWidth",!1),a(this,"childScaleHeight",!1),a(this,"childScaleWidth",!1)}onCalculateLayout(t){var i;const n=this.primaryAxis,o=t.width;let r=o;const l=t.height;let c=l;r-=this.padding.horizontal,c-=this.padding.vertical,n==="x"?this.padding.horizontal:this.padding.vertical;const h=n==="x",d=h?"y":"x",u=h?this.childControlWidth:this.childControlHeight,p=h?this.childControlHeight:this.childControlWidth,g=h?this.childForceExpandWidth:this.childForceExpandHeight,y=h?this.childForceExpandHeight:this.childForceExpandWidth,f=h?c:r,v=h?o:l,b=.5*(h?this.childAlignment%3:Math.floor(this.childAlignment/3));let w=0;h?w+=this.padding.left:w+=this.padding.top;let _=0,S=0;for(let L=0;L<this.gameObject.children.length;L++){const U=this.gameObject.children[L],B=O.getComponent(U,Wt);B!=null&&B.activeAndEnabled&&(S+=1,h?_+=B.width:_+=B.height)}let R=0;const M=this.spacing*(S-1);if(g||u){let L=0;h?L=r-=M:L=c-=M,S>0&&(R=L/S)}let T=0;T+=this.padding.left,T-=this.padding.right,b!==0&&(w=v-_,w*=b,w-=M*b,h?(w-=this.padding.right*b,w+=this.padding.left*(1-b),w<this.padding.left&&(w=this.padding.left)):(w-=this.padding.bottom*b,w+=this.padding.top*(1-b),w<this.padding.top&&(w=this.padding.top)));let j=1;for(let L=0;L<this.gameObject.children.length;L++){const U=this.gameObject.children[L],B=O.getComponent(U,Wt);if(B!=null&&B.activeAndEnabled){(i=B.pivot)==null||i.set(.5,.5),B.anchorMin.set(0,1),B.anchorMax.set(0,1);const Q=o*.5+T*.5;B.anchoredPosition.x!==Q&&(B.anchoredPosition.x=Q);const $=l*-.5;B.anchoredPosition.y!==$&&(B.anchoredPosition.y=$),y&&p&&B.sizeDelta[d]!==f&&(B.sizeDelta[d]=f),g&&u&&B.sizeDelta[n]!==R&&(B.sizeDelta[n]=R);const E=h?B.width:B.height,z=E*.5;if(w+=z,g){const ie=R*j-R*.5;ie>w&&(w=ie-R*.5+E+this.padding.left,w-=z)}let H=w;n==="y"&&(H=-H),B.anchoredPosition[n]!==H&&(B.anchoredPosition[n]=H),w+=z,w+=this.spacing,j+=1}}}}at([m()],zo.prototype,"childControlHeight",2),at([m()],zo.prototype,"childControlWidth",2),at([m()],zo.prototype,"childForceExpandHeight",2),at([m()],zo.prototype,"childForceExpandWidth",2),at([m()],zo.prototype,"childScaleHeight",2),at([m()],zo.prototype,"childScaleWidth",2);class S0 extends zo{get primaryAxis(){return"y"}}class C0 extends zo{get primaryAxis(){return"x"}}class O0 extends Li{onCalculateLayout(){}}var eE=Object.defineProperty,tE=Object.getOwnPropertyDescriptor,rn=(s,t,i,n)=>{for(var o=n>1?void 0:n?tE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&eE(t,i,o),o},e1=(s=>(s[s.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",s[s.ScreenSpaceCamera=1]="ScreenSpaceCamera",s[s.WorldSpace=2]="WorldSpace",s[s.Undefined=-1]="Undefined",s))(e1||{});const P0=C("debuguilayout"),t1=class extends Nc{constructor(){super(...arguments),a(this,"_renderOnTop"),a(this,"_depthWrite",!1),a(this,"_doubleSided",!0),a(this,"_castShadows",!1),a(this,"_receiveShadows",!1),a(this,"_renderMode",-1),a(this,"_rootCanvas"),a(this,"_scaleFactor",1),a(this,"worldCamera"),a(this,"planeDistance",-1),a(this,"_boundRenderSettingsChanged",this.onRenderSettingsChanged.bind(this)),a(this,"previousParent",null),a(this,"_lastMatrixWorld",null),a(this,"_rectTransforms",[]),a(this,"_layoutGroups",new Map),a(this,"_receivers",[]),a(this,"onBeforeRenderRoutine",()=>{var s,t,i,n;if(this.previousParent=this.gameObject.parent,((s=this.context.xr)!=null&&s.isVR||(t=this.context.xr)!=null&&t.isPassThrough)&&this.screenspace){this.gameObject.visible=!1,this.gameObject.removeFromParent();return}this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),(i=this.shadowComponent)==null||i.updateMatrixWorld(!0),(n=this.shadowComponent)==null||n.updateWorldMatrix(!0,!0),this.invokeBeforeRenderEvents(),si.ensureUpdateMeshUI(yv,this.context))}),a(this,"onAfterRenderRoutine",()=>{var s,t,i,n,o;if(((s=this.context.xr)!=null&&s.isVR||(t=this.context.xr)!=null&&t.isPassThrough)&&this.screenspace){(i=this.previousParent)==null||i.add(this.gameObject);return}if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){if(this.screenspace){const c=this.context.mainCamera;c?.add(this.gameObject)}else this.previousParent.add(this.gameObject);const r=this.context.renderer.autoClear,l=this.context.renderer.autoClearColor;this.context.renderer.autoClear=!1,this.context.renderer.autoClearColor=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),(n=this.shadowComponent)==null||n.updateMatrixWorld(!0),this.invokeBeforeRenderEvents(),si.ensureUpdateMeshUI(yv,this.context,!0),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=r,this.context.renderer.autoClearColor=l,this.previousParent.add(this.gameObject)}(o=this._lastMatrixWorld)==null||o.copy(this.gameObject.matrixWorld)}),a(this,"_updateRenderSettingsRoutine"),a(this,"_activeRenderMode",-1),a(this,"_lastWidth",-1),a(this,"_lastHeight",-1)}get isCanvas(){return!0}get screenspace(){return this.renderMode!==2}set renderOnTop(s){s!==this._renderOnTop&&(this._renderOnTop=s,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop!==void 0?this._renderOnTop:!!(this.screenspace&&this._renderMode===0)}set depthWrite(s){this._depthWrite!==s&&(this._depthWrite=s,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}set doubleSided(s){this._doubleSided!==s&&(this._doubleSided=s,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}set castShadows(s){this._castShadows!==s&&(this._castShadows=s,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}set receiveShadows(s){this._receiveShadows!==s&&(this._receiveShadows=s,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}get renderMode(){return this._renderMode}set renderMode(s){this._renderMode!==s&&(this._renderMode=s,this.onRenderSettingsChanged())}set rootCanvas(s){this._rootCanvas instanceof t1||(this._rootCanvas=s)}get rootCanvas(){return this._rootCanvas}get scaleFactor(){return this._scaleFactor}set scaleFactor(s){this._scaleFactor=s}awake(){var s;this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,P0&&console.log("Canvas.Awake()",((s=this.previousParent)==null?void 0:s.name)+"/"+this.gameObject.name),super.awake()}start(){this.applyRenderSettings()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new ne,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 s=this.context.pre_render_callbacks.indexOf(this.onBeforeRenderRoutine);s!==-1&&this.context.pre_render_callbacks.splice(s,1);const t=this.context.post_render_callbacks.indexOf(this.onAfterRenderRoutine);t!==-1&&this.context.post_render_callbacks.splice(t,1)}registerTransform(s){this._rectTransforms.push(s)}unregisterTransform(s){const t=this._rectTransforms.indexOf(s);t!==-1&&this._rectTransforms.splice(t,1)}registerLayoutGroup(s){const t=s.gameObject;this._layoutGroups.set(t,s)}unregisterLayoutGroup(s){const t=s.gameObject;this._layoutGroups.delete(t)}registerEventReceiver(s){this._receivers.push(s)}unregisterEventReceiver(s){const t=this._receivers.indexOf(s);t!==-1&&this._receivers.splice(t,1)}async onEnterXR(s){this.screenspace?(s.xr.isVR||s.xr.isPassThrough)&&(this.gameObject.visible=!1):(this.gameObject.visible=!1,await Kl(1).then(()=>{this.gameObject.visible=!0}))}onLeaveXR(s){this.screenspace&&(s.xr.isVR||s.xr.isPassThrough)&&(this.gameObject.visible=!0)}invokeBeforeRenderEvents(){var s;for(const t of this._receivers)(s=t.onBeforeCanvasRender)==null||s.call(t,this)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new ne);const s=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);P0&&s&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);const t=!1;for(const i of this._rectTransforms){s&&i.markDirty();let n=this._layoutGroups.get(i.gameObject);i.isDirty&&!n&&(n=i.gameObject.getComponentInParent(Li)),(i.isDirty||n!=null&&n.isDirty)&&(P0&&!t&&console.log("CANVAS UPDATE ### "+i.name+" ##################################### "+this.context.time.frame),n?.updateLayout(),i.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),Me.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),Mu(this.shadowComponent,this);for(const s of O.getComponentsInChildren(this.gameObject,rs))Mu(s.shadowComponent,this)}}onUpdateRenderMode(s=!1){if(!s&&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=W.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(Wt);let r=!1;o.sizeDelta.x!==this.context.domWidth&&(r=!0),o.sizeDelta.y!==this.context.domHeight&&(r=!0);const l=t.fieldOfView*Math.PI/180,c=2*Math.tan(l/2)*Math.abs(n);this.gameObject.scale.x=c/this.context.domHeight,this.gameObject.scale.y=c/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}}};let Et=t1;rn([m()],Et.prototype,"renderOnTop",1),rn([m()],Et.prototype,"depthWrite",1),rn([m()],Et.prototype,"doubleSided",1),rn([m()],Et.prototype,"castShadows",1),rn([m()],Et.prototype,"receiveShadows",1),rn([m()],Et.prototype,"renderMode",1),rn([m(Et)],Et.prototype,"rootCanvas",1),rn([m()],Et.prototype,"scaleFactor",1),rn([m(Oe)],Et.prototype,"worldCamera",2),rn([m()],Et.prototype,"planeDistance",2);var iE=Object.defineProperty,sE=Object.getOwnPropertyDescriptor,k0=(s,t,i,n)=>{for(var o=n>1?void 0:n?sE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&iE(t,i,o),o};class Uo extends A{constructor(){super(...arguments),a(this,"_alpha",1),a(this,"interactable",!0),a(this,"blocksRaycasts",!0),a(this,"_isDirty",!1),a(this,"_buffer",[])}get alpha(){return this._alpha}set alpha(t){t!==this._alpha&&(this._alpha=t,this.markDirty())}get isCanvasGroup(){return!0}markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),Me.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}applyChangesNow(){this._buffer.length=0;for(const t of O.getComponentsInChildren(this.gameObject,rs,this._buffer)){const i=t;i.setAlphaFactor&&i.setAlphaFactor(this._alpha)}}}k0([m()],Uo.prototype,"alpha",1),k0([m()],Uo.prototype,"interactable",2),k0([m()],Uo.prototype,"blocksRaycasts",2);class M0{get extensionName(){return"tmui"}onExportObject(t,i,n){const o=O.getComponent(t,Et);if(o&&o.enabled&&o.renderMode===e1.WorldSpace){const r=new pp,l=O.getComponent(t,Wt),c=O.getComponent(t,Uo),h=new Array;if(l){if(!O.isActiveSelf(t)){const p=O.isActiveSelf(t);O.setActive(t,!0),l.onEnable(),l.updateTransform(),h.push(()=>{l.onDisable(),O.setActive(t,p)})}t.traverse(p=>{if(!O.isActiveInHierarchy(p)){const g=O.isActiveSelf(p);O.setActive(p,!0);const y=O.getComponent(p,rs);y&&(y.onEnable(),h.push(()=>{y.onDisable()}));const f=O.getComponent(p,Wt);f&&(f.onEnable(),f.updateTransform(),f.onApplyTransform(),h.push(()=>{f.onDisable()}));const v=O.getComponent(p,Vt);v&&(v.onEnable(),h.push(()=>{v.onDisable()})),h.push(()=>{O.setActive(p,g)})}}),l.width,l.height;const d=Yt.createEmpty(),u=l.shadowComponent;if(i.add(d),u){const p=u.matrix;d.setMatrix(p);const g=new Map,y=new Map;g.set(u,d),y.set(u,c?c.alpha:1),u.traverse(f=>{if(f===u)return;const v=Yt.createEmpty();v.setMatrix(f.matrix);const b=f.parent,w=!!b&&typeof b.textContent=="string"&&b.textContent.length>0;let _=y.get(b)||1;const S=O.getComponent(f,Uo);if(S&&(_*=S.alpha),f instanceof Y&&w){const M=f[Ki];M?r.exportText(M.gameObject,v,n):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",f)}if(f instanceof Y&&!w){const M=f.geometry.clone();M.scale(1,1,-1),this.flipWindingOrder(M),v.geometry=M;const T=new ae,j=f.material.opacity;T.copy(f.material.color),v.material=new Re({color:T,opacity:j*_,map:f.material.map,transparent:!0})}g.set(f,v),y.set(f,_);const R=g.get(b);if(!R){console.error("Error when exporting UI: shadow component parent not found!",f,f.parent);return}R.add(v)})}}for(const d of h)d()}}flipWindingOrder(t){const i=t.index.array;for(let n=0,o=i.length/3;n<o;n++){const r=i[n*3];i[n*3]=i[n*3+2],i[n*3+2]=r}t.index.needsUpdate=!0}}const yh=C("debugusdz");function nE(s,t){var i;const n=[],o=O.getComponentsInChildren(s,Pt),r=O.getComponentsInChildren(s,zt),l=new Array,c=new Array;if(t.injectImplicitBehaviours)for(const h of o){if(!h||!h.runtimeAnimatorController||!h.enabled)continue;const d=h.runtimeAnimatorController.activeState;if(!d||!d.motion||!d.motion.clip||((i=d.motion.clip.tracks)==null?void 0:i.length)<1||l.includes(h))continue;const u=new Fr;u.animator=h,u.stateName=d.name,u.trigger="start",u.name="PlayAnimationOnClick_implicitAtStart_"+u.stateName;const p=new I;O.addComponent(p,u),c.push(p),l.push(h),s.add(p)}else for(const h of o){if(!h||!h.runtimeAnimatorController||!h.enabled)continue;yh&&console.log(h);const d=[];for(const u of h.runtimeAnimatorController.enumerateActions()){yh&&console.log(u);const p=u.getClip();d.includes(p)||d.push(p)}n.push({root:h.gameObject,clips:d})}if(t.injectImplicitBehaviours)for(const h of r){if(!h||!h.clip||!h.enabled||!h.playAutomatically||l.includes(h))continue;const d=new Fr;d.animation=h,d.stateName=h.clip.name,d.trigger="start",d.name="PlayAnimationOnClick_implicitAtStart_"+d.stateName;const u=new I;O.addComponent(u,d),c.push(u),l.push(h),s.add(u)}else for(const h of r){yh&&console.log(h);const d=[];for(const u of h.animations)d.includes(u)||d.push(u);n.push({root:h.gameObject,clips:d})}yh&&n?.length>0&&console.log("USDZ Animation Clips without behaviours",n);for(const h of n)for(const d of h.clips)t.registerAnimation(h.root,d);return c}function oE(s,t){const i=O.getComponentsInChildren(s,Ne),n=O.getComponentsInChildren(s,Io),o=new Array,r=new Array;yh&&console.log({audioSources:i,playAudioOnClicks:n});for(const l of n){if(!l.target)continue;const c=i.indexOf(l.target);c>-1&&i.splice(c,1)}for(const l of i){if(!l||!l.clip||l.volume<=0||o.includes(l))continue;const c=new Io;c.target=l,c.name="PlayAudioOnClick_implicitAtStart_",c.trigger="start";const h=new I;O.addComponent(h,c),console.log("implicit PlayAudioOnStart",h,c),r.push(h),o.push(l),s.add(h)}return r}function rE(s){return new Nt("DisableAtStart",Rt.sceneStartTrigger(),ve.fadeAction(s,0,!1))}function i1(s,t){const i=s.domElement.shadowRoot.querySelector("link[rel='ar']");if(i)return i;const n=document.createElement("div");n.classList.add("menu"),n.classList.add("quicklook-menu"),n.style.display="none",n.style.visibility="hidden";const o=document.createElement("button");o.id="open-in-ar",t?(o.innerText="View in AR",o.title="View this scene in AR. The scene will be exported to USDZ and opened with Apple's QuickLook."):(o.innerText="View in AR",o.title="Download this scene for AR. Open the downloaded USDZ file to view it in AR using Apple's QuickLook."),n.appendChild(o);const r=document.createElement("a");r.id="needle-usdz-link",r.style.display="none",r.rel="ar",r.href="",r.target="_blank",n.appendChild(r);const l=document.createElement("img");return l.id="button",r.appendChild(l),s.domElement.shadowRoot.appendChild(n),r}var aE=Object.defineProperty,lE=Object.getOwnPropertyDescriptor,At=(s,t,i,n)=>{for(var o=n>1?void 0:n?lE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&aE(t,i,o),o};const Di=C("debugusdz"),cE=C("debugusdzpruning");class Hr{constructor(){a(this,"callToAction"),a(this,"checkoutTitle"),a(this,"checkoutSubtitle"),a(this,"callToActionURL")}}At([m()],Hr.prototype,"callToAction",2),At([m()],Hr.prototype,"checkoutTitle",2),At([m()],Hr.prototype,"checkoutSubtitle",2),At([m()],Hr.prototype,"callToActionURL",2);var mp;const R0=(mp=class extends A{constructor(){super(...arguments),a(this,"objectToExport"),a(this,"autoExportAnimations",!0),a(this,"autoExportAudioSources",!0),a(this,"exportFileName"),a(this,"customUsdzFile"),a(this,"customBranding"),a(this,"anchoringType","plane"),a(this,"maxTextureSize",2048),a(this,"planeAnchoringAlignment","horizontal"),a(this,"interactive",!0),a(this,"physics",!0),a(this,"allowCreateQuicklookButton",!0),a(this,"quickLookCompatible",!0),a(this,"extensions",[]),a(this,"link"),a(this,"button"),a(this,"onClickedOpenInARElement",s=>{s.preventDefault(),this.exportAndOpen()}),a(this,"_currentExportTasks",new Map),a(this,"_previousTimeScale",1),a(this,"lastCallback"),a(this,"_rootSessionRootWasAppliedTo",null),a(this,"_rootPositionBeforeExport",new x),a(this,"_rootRotationBeforeExport",new V),a(this,"_rootScaleBeforeExport",new x)}start(){var s,t,i;Di&&(console.log("USDZExporter",this),console.log("Debug USDZ Mode. Press 'T' to export"),window.addEventListener("keydown",n=>{switch(n.key){case"t":this.exportAndOpen();break}})),this.objectToExport||(this.objectToExport=this.gameObject),!((t=(s=this.objectToExport)==null?void 0:s.children)!=null&&t.length)&&!((i=this.objectToExport)!=null&&i.isMesh)&&(this.objectToExport=this.context.scene)}onEnable(){var s;const t=X.supportsQuickLookAR(),i=X.isiOS()||X.isiPad();!this.button&&(Di||t||i)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=i1(this.context,t),this.link.addEventListener("message",this.lastCallback)),Di&&De("USDZ Exporter enabled: "+this.name),(s=document.getElementById("open-in-ar"))==null||s.addEventListener("click",this.onClickedOpenInARElement),mc.registerExporter(this)}onDisable(){var s,t,i;(s=this.button)==null||s.remove(),(t=this.link)==null||t.removeEventListener("message",this.lastCallback),Di&&De("USDZ Exporter disabled: "+this.name),(i=document.getElementById("open-in-ar"))==null||i.removeEventListener("click",this.onClickedOpenInARElement),mc.unregisterExporter(this)}async exportAsync(){return this.exportAndOpen()}async exportAndOpen(){var s;let t=this.exportFileName??((s=this.objectToExport)==null?void 0:s.name)??this.name;if(t+="-"+fx(),vo()||(t!==""&&(t+="-"),t+="MadeWithNeedle"),this.link||(this.link=i1(this.context,X.supportsQuickLookAR())),this.customUsdzFile)return Di&&console.log("Exporting custom usdz",this.customUsdzFile),this.openInQuickLook(this.customUsdzFile,t),null;if(!this.objectToExport)return console.warn("No object to export",this),null;const i=await this.export(this.objectToExport);return i?(Di&&console.log("USDZ generation done. Downloading as "+t),this.openInQuickLook(i,t),i):(console.error("USDZ generation failed. Please report a bug",this),null)}async export(s){if(!s)return console.warn("No object to export"),null;const t=this._currentExportTasks.get(s);if(t)return t;const i=this.internalExport(s);return i instanceof Promise?(this._currentExportTasks.set(s,i),i.then(n=>(this._currentExportTasks.delete(s),n)).catch(n=>(this._currentExportTasks.delete(s),console.error("Error during USDZ export \u2013 please report a bug!",n),null))):i}async internalExport(s){ce.start("export-usdz",{onProgress:S=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:S}}))}}),ce.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),ce.report("export-usdz",{message:"Load progressive textures",autoStep:5}),ce.start("export-usdz-textures","export-usdz");const t=O.getComponentsInChildren(s,mi);for(const S of t)S&&S.enabled&&S.updateSprite(!0);const i=O.getComponentsInChildren(s,Ze),n=new Array;let o=0;for(const S of i){for(const R of S.sharedMeshes)if(R){const M=it.assignMeshLOD(R,0);M instanceof Promise&&n.push(new Promise((T,j)=>{M.then(()=>{o++,ce.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:o,totalSteps:n.length}),T()}).catch(L=>j(L))}))}for(const R of S.sharedMaterials)if(R){const M=it.assignTextureLOD(R,0);M instanceof Promise&&n.push(new Promise((T,j)=>{M.then(()=>{o++,ce.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:o,totalSteps:n.length}),T()}).catch(L=>j(L))}))}}Di&&De("Progressive Loading: "+n.length),await Promise.all(n),Di&&De("Progressive Loading: done"),ce.end("export-usdz-textures");const r=ci.Global.Mask;ci.Global.Set(Ys.AR);const l=new wx,c=new sp(this.quickLookCompatible);let h;const d=[];this.interactive&&(d.push(new f0),d.push(new da),globalThis.false&&O.getComponentsInChildren(s,ye).length>0&&(this.physics?(h=new y0,d.push(h)):F()&&console.warn("USDZExporter: Physics export is disabled, but there are active Rigidbody components in the scene. They will not be exported.")),d.push(new pp),d.push(new M0));const u=[c,...d,...this.extensions],p={self:this,exporter:l,extensions:u,object:s};ce.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,ce.report("export-usdz","auto export animations and audio sources");const g=new Array;this.autoExportAnimations&&g.push(...nE(s,c)),u.find(S=>S.extensionName==="Audio")&&this.autoExportAudioSources&&g.push(...oE(s)),l.debug=Di,l.pruneUnusedNodes=!cE;const y=nl.instance.objs.map(S=>S.batchedMesh);l.keepObject=S=>{let R=!0;const M=O.getComponent(S,Ze);return M&&!M.enabled&&(R=!1),R&&y.includes(S)&&(R=!1),R&&O.getComponentInParent(S,Ps)&&(R=!1),R&&O.getComponentInParent(S,Hs)&&(R=!1),Di&&!R&&console.log("USDZExporter: Discarding object",S),R},l.beforeWritingDocument=()=>{if(F()&&c&&h){const S=c.animatedRoots;for(const R of S){const M=O.getComponentsInChildren(R,ye).filter(j=>j.enabled),T=O.getComponents(R,di).filter(j=>j.enabled&&!j.isTrigger);(M.length>0||T.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.",R)}}};const f=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(S=>{S.visible||f.push(S)});const v=u.find(S=>S.extensionName==="Behaviour");this.interactive&&v&&f.length>0&&v.addBehavior(rE(f));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"),ce.report("export-usdz","Invoking exporter.parse");const w=await l.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:u,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:b}),_=new Blob([w],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,ce.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:p}));for(const S of g)O.destroy(S);return ci.Global.Set(r),ce.end("export-usdz"),_}openInQuickLook(s,t){const i=s instanceof Blob?URL.createObjectURL(s):s,n=this.buildQuicklookOverlay();Di&&console.log("QuickLook Overlay",n);const o=n.callToAction?encodeURIComponent(n.callToAction):"",r=n.checkoutTitle?encodeURIComponent(n.checkoutTitle):"",l=n.checkoutSubtitle?encodeURIComponent(n.checkoutSubtitle):"";this.link.href=i+`#callToAction=${o}&checkoutTitle=${r}&checkoutSubtitle=${l}&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(s,t){R0.save(s,t)}static save(s,t){const i=document.createElement("a");i.style.display="none",document.body.appendChild(i),typeof s=="string"?i.href=s:i.href=URL.createObjectURL(s),i.download=t,i.click(),i.remove()}quicklookCallback(s){if(s?.data=="_apple_ar_quicklook_button_tapped"){Di&&we("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");Di&&De("Quicklook url: "+n),n&&(vo()?globalThis.open(n,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",n))}}}}buildQuicklookOverlay(){var s,t,i,n,o,r;const l={};return this.customBranding&&Object.assign(l,this.customBranding),vo()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),l.callToAction="Close",l.checkoutTitle="\u{1F335} Made with Needle",l.checkoutSubtitle="_"),(((s=l.callToAction)==null?void 0:s.length)||((t=l.checkoutTitle)==null?void 0:t.length)||((i=l.checkoutSubtitle)==null?void 0:i.length))&&((n=l.callToAction)!=null&&n.length||(l.callToAction="\0"),(o=l.checkoutTitle)!=null&&o.length||(l.checkoutTitle="\0"),(r=l.checkoutSubtitle)!=null&&r.length||(l.checkoutSubtitle="\0")),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:l})),l}getARScaleAndTarget(){if(!this.objectToExport)return{scale:1,_invertForward:!1,target:this.gameObject,sessionRoot:null};const s=O.findObjectOfType(Je);let t=O.getComponentInParent(this.objectToExport,sn);t||(t=O.getComponentInChildren(this.objectToExport,sn));let i=1,n=!1;const o=this.objectToExport;return s?i=s.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:s,_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(s),t&&i.quaternion.multiply(R0.invertForwardQuaternion),i.updateMatrix(),i.updateMatrixWorld(!0),n&&o&&i.matrix.premultiply(o)}revertWebARSessionRoot(){if(!this.objectToExport||!this._rootSessionRootWasAppliedTo)return;const s=this._rootSessionRootWasAppliedTo;s.position.copy(this._rootPositionBeforeExport),s.quaternion.copy(this._rootRotationBeforeExport),s.scale.copy(this._rootScaleBeforeExport),s.updateMatrix(),s.updateMatrixWorld(!0),this._rootSessionRootWasAppliedTo=null}createQuicklookButton(){const s=zr.getOrCreate().createQuicklookButton();return s.parentNode||this.context.menu.appendChild(s),s}},a(mp,"invertForwardMatrix",new ne().makeRotationY(Math.PI)),a(mp,"invertForwardQuaternion",new V().setFromEuler(new Bt(0,Math.PI,0))),mp);let $e=R0;At([m(I)],$e.prototype,"objectToExport",2),At([m()],$e.prototype,"autoExportAnimations",2),At([m()],$e.prototype,"autoExportAudioSources",2),At([m()],$e.prototype,"exportFileName",2),At([m(URL)],$e.prototype,"customUsdzFile",2),At([m(Hr)],$e.prototype,"customBranding",2),At([m()],$e.prototype,"anchoringType",2),At([m()],$e.prototype,"maxTextureSize",2),At([m()],$e.prototype,"planeAnchoringAlignment",2),At([m()],$e.prototype,"interactive",2),At([m()],$e.prototype,"physics",2),At([m()],$e.prototype,"allowCreateQuicklookButton",2),At([m()],$e.prototype,"quickLookCompatible",2);var hE=Object.defineProperty,dE=Object.getOwnPropertyDescriptor,T0=(s,t,i,n)=>{for(var o=n>1?void 0:n?dE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&hE(t,i,o),o};class Sl extends A{constructor(){super(...arguments),a(this,"_fog")}get fog(){return this._fog||(this._fog=new Vy(0,0,50)),this._fog}get mode(){return 1}set near(t){this.fog.near=t}get near(){return this.fog.near}set far(t){this.fog.far=t}get far(){return this.fog.far}set color(t){this.fog.color.copy(t)}get color(){return this.fog.color}onEnable(){this.scene.fog=this.fog}onDisable(){this.scene.fog===this._fog&&(this.scene.fog=null)}}T0([m()],Sl.prototype,"near",1),T0([m()],Sl.prototype,"far",1),T0([m(ae)],Sl.prototype,"color",1);var uE=Object.defineProperty,pE=Object.getOwnPropertyDescriptor,E0=(s,t,i,n)=>{for(var o=n>1?void 0:n?pE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&uE(t,i,o),o};class $r extends A{constructor(){super(...arguments),a(this,"objectBounds",!1),a(this,"color"),a(this,"isGizmo",!0),a(this,"_gizmoObject",null),a(this,"_boxHelper",null)}onEnable(){this.isGizmo&&!xc||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new mC(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=gg(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),Me.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(var t;this._boxHelper;)(t=this._boxHelper)==null||t.update(),yield}}E0([m()],$r.prototype,"objectBounds",2),E0([m(ae)],$r.prototype,"color",2),E0([m()],$r.prototype,"isGizmo",2);var mE=Object.defineProperty,gE=Object.getOwnPropertyDescriptor,A0=(s,t,i,n)=>{for(var o=n>1?void 0:n?gE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&mE(t,i,o),o};class Cl extends A{constructor(){super(...arguments),a(this,"isGizmo",!1),a(this,"color0"),a(this,"color1"),a(this,"gridHelper"),a(this,"size"),a(this,"divisions"),a(this,"offset")}onEnable(){if(this.isGizmo&&!xc)return;const t=this.size,i=this.divisions;this.gridHelper||(this.gridHelper=new sm(t,i,this.color0??new ae(.4,.4,.4),this.color1??new ae(.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)}}A0([m()],Cl.prototype,"isGizmo",2),A0([m(ae)],Cl.prototype,"color0",2),A0([m(ae)],Cl.prototype,"color1",2);var fE=Object.defineProperty,yE=Object.getOwnPropertyDescriptor,I0=(s,t,i,n)=>{for(var o=n>1?void 0:n?yE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&fE(t,i,o),o};class j0 extends A{constructor(){super(...arguments),a(this,"connectedBody"),a(this,"_rigidBody",null)}get rigidBody(){return this._rigidBody}onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(ye)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.activeAndEnabled&&this.createJoint(this.rigidBody,this.connectedBody)}}I0([m(ye)],j0.prototype,"connectedBody",2);class L0 extends j0{createJoint(t,i){var n;(n=this.context.physics.engine)==null||n.addFixedJoint(t,i)}}class vh extends j0{constructor(){super(...arguments),a(this,"anchor"),a(this,"axis")}createJoint(t,i){var n;this.axis&&this.anchor&&((n=this.context.physics.engine)==null||n.addHingeJoint(t,i,this.anchor,this.axis))}}I0([m(x)],vh.prototype,"anchor",2),I0([m(x)],vh.prototype,"axis",2);var vE=Object.defineProperty,bE=Object.getOwnPropertyDescriptor,an=(s,t,i,n)=>{for(var o=n>1?void 0:n?bE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&vE(t,i,o),o};function D0(s){return s*Math.PI/180}const s1=300,No=C("debuglights");class gi extends A{constructor(){super(...arguments),a(this,"type",0),a(this,"range",1),a(this,"spotAngle",1),a(this,"innerSpotAngle",1),a(this,"_color",new ae(16777215)),a(this,"_shadowNearPlane",.1),a(this,"_shadowBias",0),a(this,"_shadowNormalBias",0),a(this,"_overrideShadowBiasSettings",!1),a(this,"_shadows",1),a(this,"lightmapBakeType",4),a(this,"_intensity",-1),a(this,"_shadowDistance"),a(this,"shadowWidth"),a(this,"shadowHeight"),a(this,"_shadowResolution"),a(this,"light"),a(this,"_webXRStartedListener"),a(this,"_webXREndedListener"),a(this,"_webARRoot")}set color(t){this._color=t,this.light!==void 0&&(this.light.color=t)}get color(){return this.light?this.light.color:this._color}set shadowNearPlane(t){var i,n;if(t!==this._shadowNearPlane&&(this._shadowNearPlane=t,((n=(i=this.light)==null?void 0:i.shadow)==null?void 0:n.camera)!==void 0)){const o=this.light.shadow.camera;o.near=t}}get shadowNearPlane(){return this._shadowNearPlane}set shadowBias(t){var i,n;t!==this._shadowBias&&(this._shadowBias=t,((n=(i=this.light)==null?void 0:i.shadow)==null?void 0:n.bias)!==void 0&&(this.light.shadow.bias=t,this.light.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}set shadowNormalBias(t){var i,n;t!==this._shadowNormalBias&&(this._shadowNormalBias=t,((n=(i=this.light)==null?void 0:i.shadow)==null?void 0:n.normalBias)!==void 0&&(this.light.shadow.normalBias=t,this.light.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}set shadows(t){this._shadows=t,this.light&&(this.light.castShadow=t!==0,this.updateShadowSoftHard())}get shadows(){return this._shadows}set intensity(t){var i;if(this._intensity=t,this.light){let n=1;if(this.context.isInXR&&this._webARRoot){const o=(i=this._webARRoot)==null?void 0:i.arScale;typeof o=="number"&&o>0&&(n/=o)}this.light.intensity=t*n}No&&console.log("Set light intensity to "+this._intensity,t,this)}get intensity(){return this._intensity}get shadowDistance(){const t=this.light;return t!=null&&t.shadow?t.shadow.camera.far:-1}set shadowDistance(t){this._shadowDistance=t;const i=this.light;if(i!=null&&i.shadow){const n=i.shadow.camera;n.far=t,n.updateProjectionMatrix()}}get shadowResolution(){const t=this.light;return t!=null&&t.shadow?t.shadow.mapSize.x:-1}set shadowResolution(t){if(t===this._shadowResolution)return;this._shadowResolution=t;const i=this.light;i!=null&&i.shadow&&(i.shadow.mapSize.set(t,t),i.shadow.needsUpdate=!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}getWorldPosition(t){return this.light?this.type===1?this.light.getWorldPosition(t).multiplyScalar(1):this.light.getWorldPosition(t):t}awake(){this.color=new ae(this.color??16777215),No&&console.log(this.name,this)}onEnable(){No&&console.log("ENABLE LIGHT",this.name),this.createLight(),!this.isBaked&&(this.light&&(this.light.visible=!0,this.light.intensity=this._intensity,No&&console.log("Set light intensity to "+this.light.intensity,this.name),this.selfIsLight||this.light.parent!==this.gameObject&&this.gameObject.add(this.light)),this.type===1&&this.startCoroutine(this.updateMainLightRoutine(),Me.LateUpdate))}onDisable(){No&&console.log("DISABLE LIGHT",this.name),this.light&&(this.selfIsLight?this.light.intensity=0:this.light.visible=!1)}onEnterXR(t){this._webARRoot=O.getComponentInParent(this.gameObject,sn)??void 0}onLeaveXR(t){}createLight(){const t=this.selfIsLight;if(t&&!this.light)switch(this.light=this.gameObject,this.light.name=this.name,this._intensity=this.light.intensity,this.type){case 1:this.setDirectionalLight(this.light);break}else if(!this.light)switch(this.type){case 1:const i=new nm(this.color,this.intensity*Math.PI);if(i.position.set(0,0,-s1*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(i.target),lr(i.target,0,0,0),this.light=i,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),No){const l=new fC(this.light,.2,this.color);this.context.scene.add(l)}break;case 0:const n=new gC(this.color,this.intensity*Math.PI,this.range,D0(this.spotAngle/2),1-D0(this.innerSpotAngle/2)/D0(this.spotAngle/2),2);n.position.set(0,0,0),n.rotation.set(0,0,0),this.light=n;const o=n.target;n.add(o),o.position.set(0,0,this.range),o.rotation.set(0,0,0);break;case 2:const r=new Hy(this.color,this.intensity*Math.PI,this.range);this.light=r;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),No&&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 i=this.light.shadow.camera;if(i.near=this.shadowNearPlane,this._shadowDistance!==void 0&&typeof this._shadowDistance=="number"?i.far=this._shadowDistance:i.far=s1*Math.abs(this.gameObject.scale.z),this.gameObject.scale.set(1,1,1),this.shadowWidth!==void 0)i.left=-this.shadowWidth/2,i.right=this.shadowWidth/2;else{const n=this.gameObject.scale.x;i.left*=n,i.right*=n}if(this.shadowHeight!==void 0)i.top=this.shadowHeight/2,i.bottom=-this.shadowHeight/2;else{const n=this.gameObject.scale.y;i.top*=n,i.bottom*=n}this.light.shadow.needsUpdate=!0,No&&this.context.scene.add(new yC(i))}this.isBaked?this.light.removeFromParent():t||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}}updateShadowSoftHard(){this.light&&this.light.shadow&&(this.shadows===2||(this.light.shadow.radius=1,this.light.shadow.blurSamples=1))}setDirectionalLight(t){t.add(t.target),t.target.position.set(0,0,-1)}}a(gi,"allowChangingRendererShadowMapType",!0),an([m()],gi.prototype,"type",2),an([m(ae)],gi.prototype,"color",1),an([m()],gi.prototype,"shadowNearPlane",1),an([m()],gi.prototype,"shadowBias",1),an([m()],gi.prototype,"shadowNormalBias",1),an([m()],gi.prototype,"shadows",1),an([m()],gi.prototype,"lightmapBakeType",2),an([m()],gi.prototype,"intensity",1),an([m()],gi.prototype,"shadowDistance",1),an([m()],gi.prototype,"shadowResolution",1),new x(0,0,0);var _E=Object.defineProperty,wE=Object.getOwnPropertyDescriptor,bh=(s,t,i,n)=>{for(var o=n>1?void 0:n?wE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&_E(t,i,o),o};const B0=C("debuglods"),xE=C("nolods");class Ol{constructor(){a(this,"screenRelativeTransitionHeight"),a(this,"distance"),a(this,"renderers")}}bh([m()],Ol.prototype,"screenRelativeTransitionHeight",2),bh([m()],Ol.prototype,"distance",2),bh([m(Ze)],Ol.prototype,"renderers",2);class SE{constructor(t){a(this,"model"),this.model=t}get renderers(){return this.model.renderers}}class _h extends A{constructor(){super(...arguments),a(this,"fadeMode",0),a(this,"localReferencePoint"),a(this,"lodCount",0),a(this,"size",0),a(this,"animateCrossFading",!1),a(this,"lodModels"),a(this,"_lods",[]),a(this,"_settings",[]),a(this,"_lodsHandler"),a(this,"_distanceFactor",1)}start(){if(B0&&console.log("LODGROUP",this.name,this.lodModels,this),!xE&&!this._lodsHandler&&this.gameObject&&this.lodModels&&Array.isArray(this.lodModels)){const t=[];for(const n of this.lodModels){const o=new SE(n);this._lods.push(o);for(const r of o.renderers)t.includes(r)||t.push(r)}this._lodsHandler=new Array;for(let n=0;n<t.length;n++){const o=new vC;this._lodsHandler.push(o),this.gameObject.add(o)}const i=new I;i.name="Cull "+this.name;for(let n=0;n<t.length;n++){const o=t[n],r=this._lodsHandler[n],l=o.gameObject;B0&&console.log(n,l.name);for(const c of this._lods){const h=c.model.distance;let d=null;if(c.renderers.includes(o)?d=l:d=i,d.type==="Group"){console.warn(`LODGroup ${this.name}: Group or MultiMaterial object's are not supported as LOD object: ${d.name}`);continue}B0&&console.log("LEVEL",d.name,h),r.autoUpdate=!1,this.onAddLodLevel(r,d,c.model.distance)}}}}onAfterRender(){if(!this.gameObject||!this._lodsHandler)return;const t=this.context.mainCamera;if(t)for(const i of this._lodsHandler){i.update(t);const n=i.getCurrentLevel(),o=i.levels[n];i.layers.mask=o.object.layers.mask}}onAddLodLevel(t,i,n){if(i===this.gameObject){console.warn("LODGroup component must be on parent object and not mesh directly at the moment",i.name,i);return}t.addLevel(i,n*this._distanceFactor,.01);const o={lod:t,levelIndex:t.levels.length-1,distance:n};this._settings.push(o)}distanceFactor(t){if(t!==this._distanceFactor){this._distanceFactor=t;for(const i of this._settings){const n=i.lod.levels[i.levelIndex];n.distance=i.distance*t}}}}bh([m(x)],_h.prototype,"localReferencePoint",2),bh([m(Ol)],_h.prototype,"lodModels",2);var CE=Object.defineProperty,OE=Object.getOwnPropertyDescriptor,PE=(s,t,i,n)=>{for(var o=n>1?void 0:n?OE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&CE(t,i,o),o};const gp=C("debugnestedgltf");class fp extends A{constructor(){super(...arguments),a(this,"filePath"),a(this,"loadAssetInParent",!0),a(this,"_isLoadingOrDoneLoading",!1)}listenToProgress(t){var i;(i=this.filePath)==null||i.beginListenDownload(t)}preload(){var t;(t=this.filePath)==null||t.preload()}async start(){var t,i,n,o,r;if(this._isLoadingOrDoneLoading)return;gp&&console.log(this,this.guid);const l=this.gameObject.parent;if(l){this._isLoadingOrDoneLoading=!0;const c=new Ds;c.idProvider=new Dt(this.hash(this.guid)),c.parent=this.loadAssetInParent!==!1?l:this.gameObject,this.gameObject.updateMatrix();const h=this.gameObject.matrix;gp&&console.log("Load nested:",((t=this.filePath)==null?void 0:t.url)??this.filePath,this.gameObject.position);const d=await((n=(i=this.filePath)==null?void 0:i.instantiate)==null?void 0:n.call(this.filePath,c));gp&&console.log("Nested loaded:",((o=this.filePath)==null?void 0:o.url)??this.filePath,d),d&&this.loadAssetInParent!==!1&&(d.matrixAutoUpdate=!1,d.matrix.identity(),d.applyMatrix4(h),d.matrixAutoUpdate=!0,d.layers.disableAll(),d.layers.set(this.layer),this.dispatchEvent(new CustomEvent("loaded",{detail:{instance:d,assetReference:this.filePath}}))),gp&&console.log("Nested loading done:",((r=this.filePath)==null?void 0:r.url)??this.filePath,d)}}onDestroy(){var t;(t=this.filePath)==null||t.unload()}hash(t){let i=0;for(let n=0;n<t.length;n++)i=t.charCodeAt(n)+((i<<5)-i);return i}}PE([m(le)],fp.prototype,"filePath",2);var kE=Object.defineProperty,ME=Object.getOwnPropertyDescriptor,F0=(s,t,i,n)=>{for(var o=n>1?void 0:n?ME(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&kE(t,i,o),o};const RE=C("debugnet"),z0=class extends A{constructor(){super(...arguments),a(this,"url",null),a(this,"urlParameterName",null),a(this,"localhost",null)}awake(){RE&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let s=this.url?z0.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const i=C(this.urlParameterName);i&&typeof i=="string"&&(s=i)}if(!s)return null;const t=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(s);return t!=null&&t.groups?t?.groups.socket_prefix?s:"wss://"+t?.groups.url:null}static GetUrl(s,t){let i=s;const n=z0.IsLocalNetwork()&&t;if(n&&(i=t),s!=null&&s.startsWith("/")){const o=n?i:window.location.origin;o!=null&&o.endsWith("/")&&s.startsWith("/")&&(s=s.substring(1)),i=o+s}return i}static IsLocalNetwork(s=window.location.hostname){return Gt(s)}};let Pl=z0;F0([m()],Pl.prototype,"url",2),F0([m()],Pl.prototype,"urlParameterName",2),F0([m()],Pl.prototype,"localhost",2);var TE=Object.defineProperty,EE=Object.getOwnPropertyDescriptor,yp=(s,t,i,n)=>{for(var o=n>1?void 0:n?EE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&TE(t,i,o),o};class qr extends A{constructor(){super(...arguments),a(this,"referenceSpace"),a(this,"from"),a(this,"affectPosition",!1),a(this,"affectRotation",!1),a(this,"alignLookDirection",!1),a(this,"levelLookDirection",!1),a(this,"levelPosition",!1),a(this,"positionOffset",new x(0,0,0)),a(this,"rotationOffset",new x(0,0,0)),a(this,"offset",new x(0,0,0))}update(){if(!this.from)return;var t=te(this.from),i=Ce(this.from);this.offset.copy(this.positionOffset);const n=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(n),t.add(this.offset),this.levelPosition&&this.referenceSpace){const c=new nr(this.gameObject.up,0),h=te(this.referenceSpace);c.setFromNormalAndCoplanarPoint(this.gameObject.up,h);const d=new x(0,0,0);c.projectPoint(t,d),t.copy(d)}this.affectPosition&&ht(this.gameObject,t);const o=new Bt(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),r=new V().setFromEuler(o);this.affectRotation&&Hi(this.gameObject,i.multiply(r));const l=new x;this.from.getWorldDirection(l).multiplyScalar(50),this.levelLookDirection&&(l.y=0),this.alignLookDirection&&this.gameObject.lookAt(l)}}yp([m(O)],qr.prototype,"referenceSpace",2),yp([m(O)],qr.prototype,"from",2),yp([m(x)],qr.prototype,"positionOffset",2),yp([m(x)],qr.prototype,"rotationOffset",2);var AE=Object.defineProperty,IE=Object.getOwnPropertyDescriptor,Wo=(s,t,i,n)=>{for(var o=n>1?void 0:n?IE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&AE(t,i,o),o};class fi{constructor(t=0,i=0){a(this,"time",0),a(this,"value",0),a(this,"inTangent",1/0),a(this,"inWeight"),a(this,"outTangent",1/0),a(this,"outWeight"),a(this,"weightedMode"),this.time=t,this.value=i}}Wo([m()],fi.prototype,"time",2),Wo([m()],fi.prototype,"value",2),Wo([m()],fi.prototype,"inTangent",2),Wo([m()],fi.prototype,"inWeight",2),Wo([m()],fi.prototype,"outTangent",2),Wo([m()],fi.prototype,"outWeight",2),Wo([m()],fi.prototype,"weightedMode",2);const wh=class{constructor(){a(this,"keys",[])}static linearFromTo(s,t,i){const n=new wh,o=new fi;o.time=0,o.value=s;const r=new fi;return r.time=i,r.value=t,n.keys.push(o,r),n}static constant(s){const t=new wh,i=new fi;return i.time=0,i.value=s,t.keys.push(i),t}clone(){var s;const t=new wh;return t.keys=((s=this.keys)==null?void 0:s.map(i=>{const n=new fi;return n.time=i.time,n.value=i.value,n.inTangent=i.inTangent,n.inWeight=i.inWeight,n.outTangent=i.outTangent,n.outWeight=i.outWeight,n.weightedMode=i.weightedMode,n}))||[],t}get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(s){if(!this.keys||this.keys.length==0)return 0;if(this.keys.length===1)return this.keys[0].value;if(this.keys[0].time>=s)return this.keys[0].value;for(let t=0;t<this.keys.length;t++){const i=this.keys[t];if(i.time<=s)if(t+1<this.keys.length){const n=this.keys[t+1];if(n.time<s)continue;return!isFinite(i.outTangent)||!isFinite(n.inTangent)?i.value:wh.interpolateValue(s,i,n)}else return i.value}return this.keys[this.keys.length-1].value}static interpolateValue(s,t,i){const n=t.time,o=t.value,r=t.outTangent,l=i.time,c=i.value,h=i.inTangent,d=l-n,u=d*d,p=u*d,g=((r+h)*d-2*(c-o))/p,y=(3*(c-o)-(h+2*r)*d)/u,f=r,v=o,b=s-n,w=b*b,_=w*b;return g*_+y*w+f*b+v}};let kl=wh;Wo([m(fi)],kl.prototype,"keys",2);var jE=Object.defineProperty,LE=Object.getOwnPropertyDescriptor,P=(s,t,i,n)=>{for(var o=n>1?void 0:n?LE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&jE(t,i,o),o};const vp=C("debugparticles");var Hn=(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))(Hn||{});class Gr{constructor(){a(this,"alphaKeys",[]),a(this,"colorKeys",[])}get duration(){return 1}evaluate(t,i){let n,o=0,r=null,l=0;for(let c=0;c<this.alphaKeys.length;c++){const h=this.alphaKeys[c];(h.time<t||!n)&&(n=h,o=c)}for(let c=0;c<this.colorKeys.length;c++){const h=this.colorKeys[c];(h.time<t||!r)&&(r=h,l=c)}if(r)if(l+1<this.colorKeys.length){const c=this.colorKeys[l+1],h=W.remap(t,r.time,c.time,0,1);i.r=W.lerp(r.color.r,c.color.r,h),i.g=W.lerp(r.color.g,c.color.g,h),i.b=W.lerp(r.color.b,c.color.b,h)}else i.r=r.color.r,i.g=r.color.g,i.b=r.color.b;if(n)if(o+1<this.alphaKeys.length){const c=this.alphaKeys[o+1],h=W.remap(t,n.time,c.time,0,1);i.alpha=W.lerp(n.alpha,c.alpha,h)}else i.alpha=n.alpha;return i}}P([m()],Gr.prototype,"alphaKeys",2),P([m()],Gr.prototype,"colorKeys",2);var xh=(s=>(s[s.Local=0]="Local",s[s.World=1]="World",s[s.Custom=2]="Custom",s))(xh||{}),bp=(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))(bp||{});const Sh=class{constructor(){a(this,"mode","Constant"),a(this,"constant"),a(this,"constantMin"),a(this,"constantMax"),a(this,"curve"),a(this,"curveMin"),a(this,"curveMax"),a(this,"curveMultiplier")}static constant(s){const t=new Sh;return t.setConstant(s),t}static betweenTwoConstants(s,t){const i=new Sh;return i.setMinMaxConstant(s,t),i}static curve(s,t=1){const i=new Sh;return i.setCurve(s,t),i}setConstant(s){this.mode=0,this.constant=s}setMinMaxConstant(s,t){this.mode=3,this.constantMin=s,this.constantMax=t}setCurve(s,t=1){this.mode=1,this.curve=s,this.curveMultiplier=t}clone(){var s,t,i;const n=new Sh;return n.mode=this.mode,n.constant=this.constant,n.constantMin=this.constantMin,n.constantMax=this.constantMax,n.curve=(s=this.curve)==null?void 0:s.clone(),n.curveMin=(t=this.curveMin)==null?void 0:t.clone(),n.curveMax=(i=this.curveMax)==null?void 0:i.clone(),n.curveMultiplier=this.curveMultiplier,n}evaluate(s,t){const i=t===void 0?Math.random():t;switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return s=W.clamp01(s),this.curve.evaluate(s)*this.curveMultiplier;case 2:case"TwoCurves":const n=s*this.curveMin.duration,o=s*this.curveMax.duration;return W.lerp(this.curveMin.evaluate(n),this.curveMax.evaluate(o),i%1)*this.curveMultiplier;case 3:case"TwoConstants":return W.lerp(this.constantMin,this.constantMax,i%1);default:this.curveMax.evaluate(s)*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(s){if(!s)return 0;let t=Number.MIN_VALUE;for(let i=0;i<s.keys.length;i++){const n=s.keys[i];n.value>t&&(t=n.value)}return t}};let Z=Sh;P([m()],Z.prototype,"mode",2),P([m()],Z.prototype,"constant",2),P([m()],Z.prototype,"constantMin",2),P([m()],Z.prototype,"constantMax",2),P([m(kl)],Z.prototype,"curve",2),P([m(kl)],Z.prototype,"curveMin",2),P([m(kl)],Z.prototype,"curveMax",2),P([m()],Z.prototype,"curveMultiplier",2);var _p;const It=(_p=class{constructor(){a(this,"mode",0),a(this,"color"),a(this,"colorMin"),a(this,"colorMax"),a(this,"gradient"),a(this,"gradientMin"),a(this,"gradientMax")}static constant(s){const t=new It;return t.constant(s),t}static betweenTwoColors(s,t){const i=new It;return i.betweenTwoColors(s,t),i}constant(s){return this.mode=0,this.color=s,this}betweenTwoColors(s,t){return this.mode=2,this.colorMin=s,this.colorMax=t,this}evaluate(s,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(s,It._temp),It._temp;case 2:case"TwoColors":return It._temp.lerpColors(this.colorMin,this.colorMax,i);case 3:case"TwoGradients":return this.gradientMin.evaluate(s,It._temp),this.gradientMax.evaluate(s,It._temp2),It._temp.lerp(It._temp2,i);case 4:case"RandomColor":const n=Math.random();return this.gradientMin.evaluate(s,It._temp),this.gradientMax.evaluate(s,It._temp2),It._temp.lerp(It._temp2,n)}return It._temp.set(16777215),It._temp.alpha=1,It._temp}},a(_p,"_temp",new xe(0,0,0,1)),a(_p,"_temp2",new xe(0,0,0,1)),_p);let yi=It;P([m()],yi.prototype,"mode",2),P([m(xe)],yi.prototype,"color",2),P([m(xe)],yi.prototype,"colorMin",2),P([m(xe)],yi.prototype,"colorMax",2),P([m(Gr)],yi.prototype,"gradient",2),P([m(Gr)],yi.prototype,"gradientMin",2),P([m(Gr)],yi.prototype,"gradientMax",2);var U0=(s=>(s[s.Hierarchy=0]="Hierarchy",s[s.Local=1]="Local",s[s.Shape=2]="Shape",s))(U0||{});class Ht{constructor(){a(this,"cullingMode"),a(this,"duration"),a(this,"emitterVelocityMode"),a(this,"flipRotation"),a(this,"gravityModifier"),a(this,"gravityModifierMultiplier"),a(this,"loop"),a(this,"maxParticles"),a(this,"playOnAwake"),a(this,"prewarm"),a(this,"ringBufferLoopRange"),a(this,"ringBufferMode"),a(this,"scalingMode"),a(this,"simulationSpace"),a(this,"simulationSpeed"),a(this,"startColor"),a(this,"startDelay"),a(this,"startDelayMultiplier"),a(this,"startLifetime"),a(this,"startLifetimeMultiplier"),a(this,"startRotation"),a(this,"startRotationMultiplier"),a(this,"startRotation3D"),a(this,"startRotationX"),a(this,"startRotationXMultiplier"),a(this,"startRotationY"),a(this,"startRotationYMultiplier"),a(this,"startRotationZ"),a(this,"startRotationZMultiplier"),a(this,"startSize"),a(this,"startSize3D"),a(this,"startSizeMultiplier"),a(this,"startSizeX"),a(this,"startSizeXMultiplier"),a(this,"startSizeY"),a(this,"startSizeYMultiplier"),a(this,"startSizeZ"),a(this,"startSizeZMultiplier"),a(this,"startSpeed"),a(this,"startSpeedMultiplier"),a(this,"stopAction"),a(this,"useUnscaledTime")}}P([m(Z)],Ht.prototype,"gravityModifier",2),P([m(yi)],Ht.prototype,"startColor",2),P([m(Z)],Ht.prototype,"startDelay",2),P([m(Z)],Ht.prototype,"startLifetime",2),P([m(Z)],Ht.prototype,"startRotation",2),P([m(Z)],Ht.prototype,"startRotationX",2),P([m(Z)],Ht.prototype,"startRotationY",2),P([m(Z)],Ht.prototype,"startRotationZ",2),P([m(Z)],Ht.prototype,"startSize",2),P([m(Z)],Ht.prototype,"startSizeX",2),P([m(Z)],Ht.prototype,"startSizeY",2),P([m(Z)],Ht.prototype,"startSizeZ",2),P([m(Z)],Ht.prototype,"startSpeed",2);class wp{constructor(){a(this,"cycleCount"),a(this,"maxCount"),a(this,"minCount"),a(this,"probability"),a(this,"repeatInterval"),a(this,"time"),a(this,"count"),a(this,"_performed",0)}reset(){this._performed=0}run(t){if(t<=this.time)return 0;let i=0;if(this.cycleCount===0||this._performed<this.cycleCount){const n=this.time+this.repeatInterval*this._performed;if(t>=n&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:i=this.count.constant;break;case 3:i=W.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:i=this.count.curve.evaluate(Math.random());break;case 2:const o=Math.random();i=W.lerp(this.count.curveMin.evaluate(o),this.count.curveMax.evaluate(o),Math.random());break}}return i}}class $n{constructor(){a(this,"enabled"),a(this,"bursts"),a(this,"rateOverTime"),a(this,"rateOverTimeMultiplier"),a(this,"rateOverDistance"),a(this,"rateOverDistanceMultiplier"),a(this,"system")}get burstCount(){var t;return((t=this.bursts)==null?void 0:t.length)??0}reset(){var t;(t=this.bursts)==null||t.forEach(i=>i.reset())}getBurst(){let t=0;if(this.burstCount>0)for(let i=0;i<this.burstCount;i++){const n=this.bursts[i];this.system.main.loop&&n.time>=this.system.time&&n.reset(),t+=Math.round(n.run(this.system.time))}return t}}P([m()],$n.prototype,"enabled",2),P([m()],$n.prototype,"bursts",2),P([m(Z)],$n.prototype,"rateOverTime",2),P([m()],$n.prototype,"rateOverTimeMultiplier",2),P([m(Z)],$n.prototype,"rateOverDistance",2),P([m()],$n.prototype,"rateOverDistanceMultiplier",2);class xp{constructor(){a(this,"enabled"),a(this,"color")}}P([m(yi)],xp.prototype,"color",2);class Xr{constructor(){a(this,"enabled"),a(this,"separateAxes"),a(this,"size"),a(this,"sizeMultiplier"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier"),a(this,"_time",0),a(this,"_temp",new x)}evaluate(t,i,n){if(i||(i=this._temp),!this.enabled)return i.x=i.y=i.z=1,i;if(this.separateAxes)i.x=this.x.evaluate(t,n)*this.xMultiplier,i.y=this.y.evaluate(t,n)*this.yMultiplier,i.z=this.z.evaluate(t,n)*this.zMultiplier;else{const o=this.size.evaluate(t,n)*this.sizeMultiplier;i.x=o}return i}}P([m(Z)],Xr.prototype,"size",2),P([m(Z)],Xr.prototype,"x",2),P([m(Z)],Xr.prototype,"y",2),P([m(Z)],Xr.prototype,"z",2);var Sp;const Ch=(Sp=class{constructor(){a(this,"shapeType",5),a(this,"enabled",!0),a(this,"alignToDirection",!1),a(this,"angle",0),a(this,"arc",360),a(this,"arcSpread"),a(this,"arcSpeedMultiplier"),a(this,"arcMode"),a(this,"boxThickness"),a(this,"position"),a(this,"rotation"),a(this,"_rotation",new Bt),a(this,"scale"),a(this,"radius"),a(this,"radiusThickness"),a(this,"sphericalDirectionAmount"),a(this,"randomDirectionAmount"),a(this,"randomPositionAmount"),a(this,"meshShapeType"),a(this,"meshRenderer"),a(this,"_meshObj"),a(this,"_meshGeometry"),a(this,"system"),a(this,"_space"),a(this,"_worldSpaceMatrix",new ne),a(this,"_worldSpaceMatrixInverse",new ne),a(this,"_vector",new x(0,0,0)),a(this,"_temp",new x(0,0,0)),a(this,"_triangle",new bC),a(this,"_dir",new x),a(this,"_loopTime",0),a(this,"_loopDirection",1),vp&&console.log(this)}get type(){return bp[this.shapeType]}initialize(s){this.onInitialize(s),s.position.x=this._vector.x,s.position.y=this._vector.y,s.position.z=this._vector.z}toJSON(){return this}clone(){return new Ch}setMesh(s){this.meshRenderer=s,s?(this._meshObj=s.sharedMeshes[Math.floor(Math.random()*s.sharedMeshes.length)],this._meshGeometry=this._meshObj.geometry):(this._meshObj=void 0,this._meshGeometry=void 0)}update(s,t){}onUpdate(s,t,i,n){this.system=s,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(s){const t=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return t&&(this._rotation.x=W.toRadians(this.rotation.x),this._rotation.y=W.toRadians(this.rotation.y),this._rotation.z=W.toRadians(this.rotation.z),this._rotation.order="ZYX",s.applyEuler(this._rotation)),t}onInitialize(s){this._vector.set(0,0,0),s.mesh=void 0,s.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:vp&&q.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=s.mesh=this._meshObj,l=s.mesh_geometry=this._meshGeometry;if(r&&l)switch(this.meshShapeType){case 0:{const c=l.getAttribute("position"),h=Math.floor(Math.random()*c.count);this._vector.fromBufferAttribute(c,h),this._vector.applyMatrix4(r.matrixWorld),s.mesh_normal=h}break;case 1:break;case 2:{const c=l.index;if(c){let h=Math.random(),d=Math.random();h+d>1&&(h=1-h,d=1-d);const u=Math.floor(Math.random()*(c.count/3));let p=u*3,g=u*3+1,y=u*3+2;p=c.getX(p),g=c.getX(g),y=c.getX(y);const f=l.getAttribute("position");this._triangle.a.fromBufferAttribute(f,p),this._triangle.b.fromBufferAttribute(f,g),this._triangle.c.fromBufferAttribute(f,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),s.mesh_normal=u}}break}break;default:this._vector.set(0,0,0),F()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",bp[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)),vp&&q.DrawSphere(this._vector,.03,16711680,.5,!0)}getDirection(s,t){var i;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 n=t.x,o=t.y,r=t.z;this._dir.set(n,o,r),(i=this.system)!=null&&i.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;case 13:const l=s.mesh,c=s.mesh_geometry;if(l&&c)switch(this.meshShapeType){case 0:{const h=c.getAttribute("normal"),d=s.mesh_normal;this._dir.fromBufferAttribute(h,d)}break;case 1:break;case 2:{const h=c.index;if(h){const d=s.mesh_normal,u=h.getX(d*3),p=h.getX(d*3+1),g=h.getX(d*3+2),y=c.getAttribute("position"),f=G(),v=G(),b=G();f.fromBufferAttribute(y,u),v.fromBufferAttribute(y,p),b.fromBufferAttribute(y,g),f.sub(v),b.sub(v),f.cross(b),this._dir.copy(f).multiplyScalar(-1);const w=Ce(l);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),vp&&(q.DrawSphere(t,.01,8925952,.5,!0),q.DrawDirection(t,this._dir,8925952,.5,!0)),this._dir}randomizePosition(s,t){if(t<=0)return;const i=Ch._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,s.add(i)}randomizeDirection(s,t){if(t===0)return;const i=Ch._randomQuat,n=Ch._tempVec;n.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),i.setFromAxisAngle(n,t*Math.random()*Math.PI),s.applyQuaternion(i)}spherizeDirection(s,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),l=Math.cos(n),c=new x(o,r,l);s.lerp(c,t)}randomSpherePoint(s,t,i,n,o){const r=Math.random(),l=Math.random(),c=2*Math.PI*r*(n/360),h=Math.acos(2*l-1),d=W.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,u=s.x+this.scale.x*(-d*Math.sin(h)*Math.cos(c)),p=s.y+this.scale.y*(d*Math.sin(h)*Math.sin(c)),g=s.z+this.scale.z*(d*Math.cos(h));o.x=u,o.y=p,o.z=g}randomCirclePoint(s,t,i,n,o){const r=Math.random(),l=2*Math.PI*r*(n/360),c=W.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,h=s.x+this.scale.x*c*Math.cos(l),d=s.y+this.scale.y*c*Math.sin(l),u=s.z;o.x=h,o.y=d,o.z=u}randomConePoint(s,t,i,n,o,r,l){let c=0,h=0;switch(r){case 0:c=Math.random(),h=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:c=.5,h=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let d=2*Math.PI*c*(o/360);switch(r){case 2:case 1:d+=Math.PI+.5,d+=this._loopTime*Math.PI*2,d%=W.toRadians(o);break}const u=Math.acos(2*h-1),p=W.lerp(1,1-Math.pow(1-Math.random(),Math.PI),n)*i,g=s.x+-p*Math.sin(u)*Math.cos(d),y=s.y+p*Math.sin(u)*Math.sin(d),f=s.z;l.x=g*this.scale.x,l.y=y*this.scale.y,l.z=f*this.scale.z}},a(Sp,"_randomQuat",new V),a(Sp,"_tempVec",new x),Sp);let et=Ch;P([m()],et.prototype,"shapeType",2),P([m()],et.prototype,"enabled",2),P([m()],et.prototype,"alignToDirection",2),P([m()],et.prototype,"angle",2),P([m()],et.prototype,"arc",2),P([m()],et.prototype,"arcSpread",2),P([m()],et.prototype,"arcSpeedMultiplier",2),P([m()],et.prototype,"arcMode",2),P([m(x)],et.prototype,"boxThickness",2),P([m(x)],et.prototype,"position",2),P([m(x)],et.prototype,"rotation",2),P([m(x)],et.prototype,"scale",2),P([m()],et.prototype,"radius",2),P([m()],et.prototype,"radiusThickness",2),P([m()],et.prototype,"sphericalDirectionAmount",2),P([m()],et.prototype,"randomDirectionAmount",2),P([m()],et.prototype,"randomPositionAmount",2),P([m()],et.prototype,"meshShapeType",2),P([m(th)],et.prototype,"meshRenderer",2);class Pe{constructor(){a(this,"damping"),a(this,"enabled"),a(this,"frequency"),a(this,"octaveCount"),a(this,"octaveMultiplier"),a(this,"octaveScale"),a(this,"positionAmount"),a(this,"quality"),a(this,"remap"),a(this,"remapEnabled"),a(this,"remapMultiplier"),a(this,"remapX"),a(this,"remapXMultiplier"),a(this,"remapY"),a(this,"remapYMultiplier"),a(this,"remapZ"),a(this,"remapZMultiplier"),a(this,"scrollSpeedMultiplier"),a(this,"separateAxes"),a(this,"strengthMultiplier"),a(this,"strengthX"),a(this,"strengthXMultiplier"),a(this,"strengthY"),a(this,"strengthYMultiplier"),a(this,"strengthZ"),a(this,"strengthZMultiplier"),a(this,"_noise"),a(this,"_time",0),a(this,"_temp",new x)}update(t){this._time+=t.time.deltaTime*this.scrollSpeedMultiplier}apply(t,i,n,o,r,l){if(!this.enabled)return;this._noise||(this._noise=nO(()=>0));const c=this._temp.set(i.x,i.y,i.z).multiplyScalar(this.frequency),h=this._noise(c.x,c.y,c.z,this._time),d=this._noise(c.x,c.y,c.z,this._time+1e3*this.frequency),u=this._noise(c.x,c.y,c.z,this._time+2e3*this.frequency);this._temp.set(h,d,u).normalize();const p=r/l;let g=this.positionAmount.evaluate(p);this.separateAxes?(this._temp.x*=g*this.strengthXMultiplier,this._temp.y*=g*this.strengthYMultiplier,this._temp.z*=g*this.strengthZMultiplier):(this.strengthX&&(g*=this.strengthX.evaluate(p)*1.5),this._temp.multiplyScalar(g)),n.x+=this._temp.x,n.y+=this._temp.y,n.z+=this._temp.z}}P([m()],Pe.prototype,"damping",2),P([m()],Pe.prototype,"enabled",2),P([m()],Pe.prototype,"frequency",2),P([m()],Pe.prototype,"octaveCount",2),P([m()],Pe.prototype,"octaveMultiplier",2),P([m()],Pe.prototype,"octaveScale",2),P([m(Z)],Pe.prototype,"positionAmount",2),P([m()],Pe.prototype,"quality",2),P([m(Z)],Pe.prototype,"remap",2),P([m()],Pe.prototype,"remapEnabled",2),P([m()],Pe.prototype,"remapMultiplier",2),P([m(Z)],Pe.prototype,"remapX",2),P([m()],Pe.prototype,"remapXMultiplier",2),P([m(Z)],Pe.prototype,"remapY",2),P([m()],Pe.prototype,"remapYMultiplier",2),P([m(Z)],Pe.prototype,"remapZ",2),P([m()],Pe.prototype,"remapZMultiplier",2),P([m()],Pe.prototype,"scrollSpeedMultiplier",2),P([m()],Pe.prototype,"separateAxes",2),P([m()],Pe.prototype,"strengthMultiplier",2),P([m(Z)],Pe.prototype,"strengthX",2),P([m()],Pe.prototype,"strengthXMultiplier",2),P([m(Z)],Pe.prototype,"strengthY",2),P([m()],Pe.prototype,"strengthYMultiplier",2),P([m(Z)],Pe.prototype,"strengthZ",2),P([m()],Pe.prototype,"strengthZMultiplier",2);class qe{constructor(){a(this,"enabled"),a(this,"attachRibbonToTransform",!1),a(this,"colorOverLifetime"),a(this,"colorOverTrail"),a(this,"dieWithParticles",!0),a(this,"inheritParticleColor",!0),a(this,"lifetime"),a(this,"lifetimeMultiplier"),a(this,"minVertexDistance",.2),a(this,"mode",0),a(this,"ratio",1),a(this,"ribbonCount",1),a(this,"shadowBias",0),a(this,"sizeAffectsLifetime",!1),a(this,"sizeAffectsWidth",!1),a(this,"splitSubEmitterRibbons",!1),a(this,"textureMode",0),a(this,"widthOverTrail"),a(this,"widthOverTrailMultiplier"),a(this,"worldSpace",!1)}getWidth(t,i,n,o){const r=this.widthOverTrail.evaluate(n,o);return t*=r,t}getColor(t,i,n){const o=this.colorOverTrail.evaluate(n),r=this.colorOverLifetime.evaluate(i);t.x*=o.r*r.r,t.y*=o.g*r.g,t.z*=o.b*r.b,"alpha"in o&&"alpha"in r&&(t.w*=o.alpha*r.alpha)}}P([m()],qe.prototype,"enabled",2),P([m()],qe.prototype,"attachRibbonToTransform",2),P([m(yi)],qe.prototype,"colorOverLifetime",2),P([m(yi)],qe.prototype,"colorOverTrail",2),P([m()],qe.prototype,"dieWithParticles",2),P([m()],qe.prototype,"inheritParticleColor",2),P([m(Z)],qe.prototype,"lifetime",2),P([m()],qe.prototype,"lifetimeMultiplier",2),P([m()],qe.prototype,"minVertexDistance",2),P([m()],qe.prototype,"mode",2),P([m()],qe.prototype,"ratio",2),P([m()],qe.prototype,"ribbonCount",2),P([m()],qe.prototype,"shadowBias",2),P([m()],qe.prototype,"sizeAffectsLifetime",2),P([m()],qe.prototype,"sizeAffectsWidth",2),P([m()],qe.prototype,"splitSubEmitterRibbons",2),P([m()],qe.prototype,"textureMode",2),P([m(Z)],qe.prototype,"widthOverTrail",2),P([m()],qe.prototype,"widthOverTrailMultiplier",2),P([m()],qe.prototype,"worldSpace",2);class tt{constructor(){a(this,"enabled"),a(this,"space",0),a(this,"orbitalX"),a(this,"orbitalY"),a(this,"orbitalZ"),a(this,"orbitalXMultiplier"),a(this,"orbitalYMultiplier"),a(this,"orbitalZMultiplier"),a(this,"orbitalOffsetX"),a(this,"orbitalOffsetY"),a(this,"orbitalOffsetZ"),a(this,"speedModifier"),a(this,"speedModifierMultiplier"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier"),a(this,"_system"),a(this,"_temp",new x),a(this,"_temp2",new x),a(this,"_temp3",new x),a(this,"_hasOrbital",!1),a(this,"_index",0),a(this,"_orbitalMatrix",new ne)}update(t){this._system=t}init(t){this._index==0&&(t.debug=!0),this._index+=1,t.orbitx=this.orbitalX.evaluate(Math.random()),t.orbity=this.orbitalY.evaluate(Math.random()),t.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=t.orbitx!=0||t.orbity!=0||t.orbitz!=0}apply(t,i,n,o,r,l,c){var h;if(!this.enabled)return;const d=l/c,u=this.speedModifier.evaluate(d)*this.speedModifierMultiplier,p=this.x.evaluate(d),g=this.y.evaluate(d),y=this.z.evaluate(d);if(this._temp.set(-p,g,y),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&((h=this._system)==null?void 0:h.worldPos)){const f=this._temp2.set(n.x,n.y,n.z),v=this.orbitalXMultiplier,b=this.orbitalYMultiplier,w=this.orbitalZMultiplier,_=u*Math.PI*2*10,S=Math.cos(_*v),R=Math.sin(_*v),M=Math.cos(_*b),T=Math.sin(_*b),j=Math.cos(_*w),L=Math.sin(_*w),U=f.x*(M*j)+f.y*(M*L)+f.z*-T,B=f.x*(R*T*j-S*L)+f.y*(R*T*L+S*j)+f.z*(R*M),Q=f.x*(S*T*j+R*L)+f.y*(S*T*L-R*j)+f.z*(S*M),$=this._temp3.set(f.x-U,f.y-B,f.z-Q);$.normalize(),$.multiplyScalar(.2/r*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),o.x+=$.x,o.y+=$.y,o.z+=$.z}o.x+=this._temp.x,o.y+=this._temp.y,o.z+=this._temp.z,o.x*=u,o.y*=u,o.z*=u}}P([m()],tt.prototype,"enabled",2),P([m()],tt.prototype,"space",2),P([m(Z)],tt.prototype,"orbitalX",2),P([m(Z)],tt.prototype,"orbitalY",2),P([m(Z)],tt.prototype,"orbitalZ",2),P([m()],tt.prototype,"orbitalXMultiplier",2),P([m()],tt.prototype,"orbitalYMultiplier",2),P([m()],tt.prototype,"orbitalZMultiplier",2),P([m()],tt.prototype,"orbitalOffsetX",2),P([m()],tt.prototype,"orbitalOffsetY",2),P([m()],tt.prototype,"orbitalOffsetZ",2),P([m(Z)],tt.prototype,"speedModifier",2),P([m()],tt.prototype,"speedModifierMultiplier",2),P([m(Z)],tt.prototype,"x",2),P([m()],tt.prototype,"xMultiplier",2),P([m(Z)],tt.prototype,"y",2),P([m()],tt.prototype,"yMultiplier",2),P([m(Z)],tt.prototype,"z",2),P([m()],tt.prototype,"zMultiplier",2);class $t{constructor(){a(this,"animation"),a(this,"enabled"),a(this,"cycleCount"),a(this,"frameOverTime"),a(this,"frameOverTimeMultiplier"),a(this,"numTilesX"),a(this,"numTilesY"),a(this,"startFrame"),a(this,"startFrameMultiplier"),a(this,"rowMode"),a(this,"rowIndex"),a(this,"spriteCount"),a(this,"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(t){if(!this.sampleOnceAtStart())return this.getIndex(t)}getIndex(t){const i=this.numTilesX*this.numTilesY;t=t*this.cycleCount;let n=this.frameOverTime.evaluate(t%1);return n*=this.frameOverTimeMultiplier,n*=i,n=n%i,n=Math.floor(n),n}}P([m()],$t.prototype,"animation",2),P([m()],$t.prototype,"enabled",2),P([m()],$t.prototype,"cycleCount",2),P([m(Z)],$t.prototype,"frameOverTime",2),P([m()],$t.prototype,"frameOverTimeMultiplier",2),P([m()],$t.prototype,"numTilesX",2),P([m()],$t.prototype,"numTilesY",2),P([m(Z)],$t.prototype,"startFrame",2),P([m()],$t.prototype,"startFrameMultiplier",2),P([m()],$t.prototype,"rowMode",2),P([m()],$t.prototype,"rowIndex",2),P([m()],$t.prototype,"spriteCount",2),P([m()],$t.prototype,"timeMode",2);class Es{constructor(){a(this,"enabled"),a(this,"separateAxes"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier")}evaluate(t,i){return this.enabled?this.separateAxes?0:this.z.evaluate(t,i)*-1:0}}P([m()],Es.prototype,"enabled",2),P([m()],Es.prototype,"separateAxes",2),P([m(Z)],Es.prototype,"x",2),P([m()],Es.prototype,"xMultiplier",2),P([m(Z)],Es.prototype,"y",2),P([m()],Es.prototype,"yMultiplier",2),P([m(Z)],Es.prototype,"z",2),P([m()],Es.prototype,"zMultiplier",2);class is{constructor(){a(this,"enabled"),a(this,"range"),a(this,"separateAxes"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier")}evaluate(t,i){if(!this.enabled)return 0;if(!this.separateAxes){const n=W.lerp(this.range.x,this.range.y,i);return this.z.evaluate(n)*-1}return 0}}P([m()],is.prototype,"enabled",2),P([m()],is.prototype,"range",2),P([m()],is.prototype,"separateAxes",2),P([m(Z)],is.prototype,"x",2),P([m()],is.prototype,"xMultiplier",2),P([m(Z)],is.prototype,"y",2),P([m()],is.prototype,"yMultiplier",2),P([m(Z)],is.prototype,"z",2),P([m()],is.prototype,"zMultiplier",2);class mt{constructor(){a(this,"enabled"),a(this,"dampen"),a(this,"drag"),a(this,"dragMultiplier"),a(this,"limit"),a(this,"limitMultiplier"),a(this,"separateAxes"),a(this,"limitX"),a(this,"limitXMultiplier"),a(this,"limitY"),a(this,"limitYMultiplier"),a(this,"limitZ"),a(this,"limitZMultiplier"),a(this,"multiplyDragByParticleSize",!1),a(this,"multiplyDragByParticleVelocity",!1),a(this,"space"),a(this,"_temp",new x),a(this,"_temp2",new x)}apply(t,i,n,o,r,l,c){if(this.enabled){const h=this.limit.evaluate(r)*this.limitMultiplier;if(i.length()>h){this._temp.copy(i).normalize().multiplyScalar(h);const d=this.dampen*.5;i.x=W.lerp(i.x,this._temp.x,d),i.y=W.lerp(i.y,this._temp.y,d),i.z=W.lerp(i.z,this._temp.z,d),n.x=W.lerp(n.x,this._temp.x,d),n.y=W.lerp(n.y,this._temp.y,d),n.z=W.lerp(n.z,this._temp.z,d)}}}}P([m()],mt.prototype,"enabled",2),P([m()],mt.prototype,"dampen",2),P([m(Z)],mt.prototype,"drag",2),P([m()],mt.prototype,"dragMultiplier",2),P([m(Z)],mt.prototype,"limit",2),P([m()],mt.prototype,"limitMultiplier",2),P([m()],mt.prototype,"separateAxes",2),P([m(Z)],mt.prototype,"limitX",2),P([m()],mt.prototype,"limitXMultiplier",2),P([m(Z)],mt.prototype,"limitY",2),P([m()],mt.prototype,"limitYMultiplier",2),P([m(Z)],mt.prototype,"limitZ",2),P([m()],mt.prototype,"limitZMultiplier",2),P([m()],mt.prototype,"multiplyDragByParticleSize",2),P([m()],mt.prototype,"multiplyDragByParticleVelocity",2),P([m()],mt.prototype,"space",2);const n1=class{constructor(){a(this,"enabled"),a(this,"curve"),a(this,"curveMultiplier"),a(this,"mode"),a(this,"system"),a(this,"_temp",new x),a(this,"_firstUpdate",!0),a(this,"_frames",0)}clone(){var s;const t=new n1;return t.enabled=this.enabled,t.curve=(s=this.curve)==null?void 0:s.clone(),t.curveMultiplier=this.curveMultiplier,t.mode=this.mode,t}get _lastWorldPosition(){return this.system._iv_lastWorldPosition||(this.system._iv_lastWorldPosition=new x),this.system._iv_lastWorldPosition}get _velocity(){return this.system._iv_velocity||(this.system._iv_velocity=new x),this.system._iv_velocity}awake(s){this.system=s,this.reset()}reset(){this._firstUpdate=!0}update(s){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(s){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),s.x+=this._temp.x,s.y+=this._temp.y,s.z+=this._temp.z}}applyCurrent(s,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),s.x+=this._temp.x,s.y+=this._temp.y,s.z+=this._temp.z}}};let Qr=n1;P([m()],Qr.prototype,"enabled",2),P([m(Z)],Qr.prototype,"curve",2),P([m()],Qr.prototype,"curveMultiplier",2),P([m()],Qr.prototype,"mode",2);class vi{constructor(){a(this,"enabled"),a(this,"range"),a(this,"separateAxes"),a(this,"size"),a(this,"sizeMultiplier"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier")}evaluate(t,i,n,o){const r=t.length(),l=W.remap(r,this.range.x,this.range.y,0,1),c=this.size.evaluate(l,n);return o.x*=c,o.y*=c,o.z*=c,o}}P([m()],vi.prototype,"enabled",2),P([m(re)],vi.prototype,"range",2),P([m()],vi.prototype,"separateAxes",2),P([m(Z)],vi.prototype,"size",2),P([m()],vi.prototype,"sizeMultiplier",2),P([m(Z)],vi.prototype,"x",2),P([m()],vi.prototype,"xMultiplier",2),P([m(Z)],vi.prototype,"y",2),P([m()],vi.prototype,"yMultiplier",2),P([m(Z)],vi.prototype,"z",2),P([m()],vi.prototype,"zMultiplier",2);class Ml{constructor(){a(this,"enabled"),a(this,"range"),a(this,"color")}evaluate(t,i,n){const o=t.length(),r=W.remap(o,this.range.x,this.range.y,0,1),l=this.color.evaluate(r,i);n.x*=l.r,n.y*=l.g,n.z*=l.b,"alpha"in l&&(n.w*=l.alpha)}}P([m()],Ml.prototype,"enabled",2),P([m(re)],Ml.prototype,"range",2),P([m(yi)],Ml.prototype,"color",2),new x(1,1,1),new x(0,0,1);class N0{constructor(t,i,n,o){a(this,"type","NeedleParticleSubEmitter"),a(this,"emitterType"),a(this,"emitterProbability"),a(this,"q_",new V),a(this,"v_",new x),a(this,"v2_",new x),a(this,"_emitterMatrix",new bm),a(this,"_circularBuffer"),this.system=t,this.particleSystem=i,this.subSystem=n,this.subParticleSystem=o,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const r=1e3;this._circularBuffer=new Ci(()=>new bm,r)}clone(){throw new Error("Method not implemented.")}initialize(t){t.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===W0.Birth&&this.run(t)}update(t,i){this.run(t)}frameUpdate(t){}toJSON(){}reset(){}run(t){if(this.subSystem.currentParticles>=this.subSystem.main.maxParticles||!this.subParticleSystem||!t.emissionState||this.emitterProbability&&Math.random()>this.emitterProbability)return;const i=this.system.deltaTime;if(this.emitterType===W0.Death){let o=t.life;if(t[Rl]!==void 0&&(o=t[Rl]),!(t.age+i*1.2>=o))return;const r=this.subSystem.main.maxParticles-this.subSystem.currentParticles;t.emissionState.waitEmiting=r}const n=new bm;n.set(1,0,0,t.position.x,0,1,0,t.position.y,0,0,1,t.position.z,0,0,0,1),this.particleSystem.worldSpace||n.multiplyMatrices(this._emitterMatrix,n),this.subParticleSystem.emit(i,t.emissionState,n)}}var DE=Object.defineProperty,BE=Object.getOwnPropertyDescriptor,Ge=(s,t,i,n)=>{for(var o=n>1?void 0:n?BE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&DE(t,i,o),o};const Vo=C("debugparticles"),FE=C("noprogressive"),zE=C("debugprogressive");var W0=(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))(W0||{});class ss extends A{constructor(){super(...arguments),a(this,"renderMode"),a(this,"particleMaterial"),a(this,"trailMaterial"),a(this,"particleMesh"),a(this,"maxParticleSize"),a(this,"minParticleSize"),a(this,"velocityScale"),a(this,"cameraVelocityScale"),a(this,"lengthScale")}start(){if(this.maxParticleSize!==.5&&this.minParticleSize!==0&&F()){const t=`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(t)}}get transparent(){var t;return((t=this.particleMaterial)==null?void 0:t.transparent)??!1}getMaterial(t=!1){let i=t===!0&&this.trailMaterial?this.trailMaterial:this.particleMaterial;if(i){if(i.type==="MeshStandardMaterial"){Vo&&console.debug("ParticleSystemRenderer.getMaterial: MeshStandardMaterial detected, converting to MeshBasicMaterial. See https://github.com/Alchemist0823/three.quarks/issues/101"),"map"in i&&i.map&&(i.map.colorSpace=or,i.map.premultiplyAlpha=!1);const n=new Re;n.copy(i),t?this.trailMaterial=n:this.particleMaterial=n}i.map&&(i.map.colorSpace=or,i.map.premultiplyAlpha=!1),t&&i.side===ao&&(i=i.clone(),i.side=dm,t?this.trailMaterial=i:this.particleMaterial=i)}return i&&!FE&&i._didRequestTextureLOD===void 0&&(i._didRequestTextureLOD=0,zE&&console.log("Load material LOD",i.name),it.assignTextureLOD(i,0)),i}getMesh(t){let i=null;if(!i&&(this.particleMesh instanceof Y&&(i=this.particleMesh.geometry),i===null)){i=new Fs(1,1);const n=i.attributes.uv;for(let o=0;o<n.count;o++)n.setX(o,1-n.getX(o))}return new Y(i,this.getMaterial())}}Ge([m()],ss.prototype,"renderMode",2),Ge([m(ke)],ss.prototype,"particleMaterial",2),Ge([m(ke)],ss.prototype,"trailMaterial",2),Ge([m()],ss.prototype,"maxParticleSize",2),Ge([m()],ss.prototype,"minParticleSize",2),Ge([m()],ss.prototype,"velocityScale",2),Ge([m()],ss.prototype,"cameraVelocityScale",2),Ge([m()],ss.prototype,"lengthScale",2);class Cp{constructor(t,i=1){a(this,"_curve"),a(this,"_factor"),a(this,"type","function"),this._curve=t,this._factor=i}startGen(t){}genValue(t,i){return this._curve.evaluate(i,Math.random())*this._factor}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}}class V0{constructor(t){a(this,"type","value"),a(this,"system"),this.system=t}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}startGen(t){}}class UE extends V0{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class NE extends V0{constructor(){super(...arguments),a(this,"_lastPosition",new x),a(this,"_lastDistance",0)}update(){const t=te(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(t),this._lastPosition.copy(t)}genValue(){if(!this.system.isPlaying||!this.system.emission.enabled||this.system.currentParticles>=this.system.maxParticles)return 0;let t=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){const o=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let r=this._lastDistance/this.system.deltaTime*o;Number.isFinite(r)||(r=0),t+=r}const i=this.system.emission.getBurst();i>0&&(t+=i/this.system.deltaTime);const n=this.system.maxParticles-this.system.currentParticles;return W.clamp(t,0,n/this.system.deltaTime)}}class WE extends V0{genValue(){return this.system.isPlaying,0}}class Ho{constructor(t){a(this,"system"),a(this,"type"),this.type=Object.getPrototypeOf(this).constructor.name||"ParticleSystemBaseBehaviour",t&&(this.system=t)}get context(){return this.system.context}initialize(t){}update(t,i){}frameUpdate(t){}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}reset(){}}class VE extends Ho{constructor(){super(...arguments),a(this,"type","NeedleTextureSheet")}update(t,i){const n=this.system.textureSheetAnimation;if(n.enabled){const o=t.age/t.life,r=n.evaluate(o);r!==void 0&&(t.uvTile=r)}}}const o1=Symbol("particleRotation");class HE extends Ho{constructor(){super(...arguments),a(this,"type","NeedleRotation")}initialize(t){t[o1]=Math.random()}update(t,i){if(t.rotation===void 0)return;const n=t.age/t.life;if(typeof t.rotation=="number"&&(this.system.rotationOverLifetime.enabled?t.rotation+=this.system.rotationOverLifetime.evaluate(n,t[o1])*i:this.system.renderer.renderMode===Hn.Billboard&&(t.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const o=t.velocity.length();t.rotation+=this.system.rotationBySpeed.evaluate(n,o)*i}}}const r1=Symbol("sizeLerpFactor"),$E=new x;class qE extends Ho{constructor(){super(...arguments),a(this,"type","NeedleSize"),a(this,"_minSize",0),a(this,"_maxSize",1)}initialize(t){t[r1]=Math.random(),this._minSize=this.system.renderer.minParticleSize,this._maxSize=this.system.renderer.maxParticleSize}update(t,i){const n=t.age/t.life;let o=1;this.system.sizeOverLifetime.enabled&&(o*=this.system.sizeOverLifetime.evaluate(n,void 0,t[r1]).x);let r=1;this.system.renderer.renderMode!==Hn.Mesh&&(r=this.system.worldScale.x/this.system.cameraScale);const l=G(t.startSize).multiplyScalar(o*r);if(t.size.set(l.x,l.y,l.z),this.system.localspace){const c=d1(this.system,$E);t.size.x*=c.x,t.size.y*=c.y,t.size.z*=c.z}}}const Rl=Symbol("particleLife"),H0=Symbol("trailLifetime"),a1=Symbol("trailStartLength"),$0=Symbol("trailWidthRandom");class GE extends Ho{constructor(){super(...arguments),a(this,"type","NeedleTrail")}initialize(t){t instanceof pv&&(t[Rl]=t.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(t[H0]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),t.life+=t[H0]),t[a1]=t.length,t[$0]=Math.random())}update(t){var i;if((i=this.system.trails)!=null&&i.enabled&&t instanceof pv){const n=t,o=t.age/t[Rl],r=t.previous.values(),l=t.previous.length;for(let c=0;c<l;c++){const h=r.next().value,d=1-c/(l-1),u=t.size;if(u.x<=0&&!this.system.trails.sizeAffectsWidth){const p=20*this.system.trails.widthOverTrail.evaluate(.5,n[$0]);u.x=p,u.y=p,u.z=p}h.size=this.system.trails.getWidth(u.x,o,d,n[$0]),h.color.copy(t.color),this.system.trails.getColor(h.color,o,d)}if(t.age>t[Rl]){t.velocity.set(0,0,0);const c=(t.age-t[Rl])/t[H0];n.length=W.lerp(t[a1],0,c)}}}}const Op=Symbol("startVelocity"),l1=Symbol("gravityModifier"),q0=Symbol("gravitySpeed"),Pp=Symbol("velocity lerp factor"),G0=new x;class XE extends Ho{constructor(){super(...arguments),a(this,"type","NeedleVelocity"),a(this,"_gravityDirection",new x)}initialize(t){var i,n;const o=this.system.main.simulationSpeed;t.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random());const r=this.system.shape.getDirection(t,t.position);t.velocity.x=r.x*t.startSpeed,t.velocity.y=r.y*t.startSpeed,t.velocity.z=r.z*t.startSpeed,(i=this.system.inheritVelocity)!=null&&i.enabled&&this.system.inheritVelocity.applyInitial(t.velocity),t[Op]?t[Op].copy(t.velocity):t[Op]=t.velocity.clone();const l=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());t[l1]=l*o,t[q0]=l*o*.5,t[Pp]=Math.random(),(n=this.system.velocityOverLifetime)==null||n.init(t),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===xh.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(t,i){var n;const o=t[Op],r=t[l1];if(r!==0){const g=r*t[q0];G0.copy(this._gravityDirection).multiplyScalar(g),t[q0]+=i*.05,o.add(G0)}t.velocity.copy(o);const l=t.age/t.life;(n=this.system.inheritVelocity)!=null&&n.enabled&&this.system.inheritVelocity.applyCurrent(t.velocity,l,t[Pp]);const c=this.system.noise;c.enabled&&c.apply(0,t.position,t.velocity,i,t.age,t.life);const h=this.system.sizeBySpeed;h!=null&&h.enabled&&(t.size=h.evaluate(t.velocity,l,t[Pp],t.size));const d=this.system.colorBySpeed;d!=null&&d.enabled&&d.evaluate(t.velocity,t[Pp],t.color);const u=this.system.velocityOverLifetime;u.enabled&&u.apply(t,0,t.position,t.velocity,i,t.age,t.life);const p=this.system.limitVelocityOverLifetime;if(p.enabled&&p.apply(t.position,o,t.velocity,t.size,l,i,1),this.system.worldspace){const g=this.system.worldScale;t.velocity.x*=g.x,t.velocity.y*=g.y,t.velocity.z*=g.z}}}const c1=Symbol("colorLerpFactor"),h1=new xe(1,1,1,1),Yr=new xe(1,1,1,1);class QE extends Ho{constructor(){super(...arguments),a(this,"type","NeedleColor")}initialize(t){}_init(t){const i=this.system.renderer.particleMaterial;Yr.copy(this.system.main.startColor.evaluate(Math.random())),i!=null&&i.color&&(h1.copy(i.color),Yr.multiply(h1)),Yr.convertLinearToSRGB(),t.startColor.set(Yr.r,Yr.g,Yr.b,Yr.alpha),t.color.copy(t.startColor),t[c1]=Math.random()}update(t,i){if(t.age===0&&this._init(t),this.system.colorOverLifetime.enabled){const n=t.age/t.life,o=this.system.colorOverLifetime.color.evaluate(n,t[c1]);t.color.set(o.r,o.g,o.b,"alpha"in o?o.alpha:1).multiply(t.startColor)}else t.color.copy(t.startColor)}}class YE{constructor(t){a(this,"system"),a(this,"emission"),a(this,"autoDestroy"),a(this,"startLength"),a(this,"emissionBursts"),a(this,"onlyUsedByOther"),a(this,"behaviors",[]),a(this,"rendererEmitterSettings",{startLength:new cO(220),followLocalOrigin:!1}),a(this,"flatWhiteTexture"),a(this,"clonedTexture",{original:void 0,clone:void 0}),this.system=t,this.emission=new NE(this.system)}get anim(){return this.system.textureSheetAnimation}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()}get looping(){return this.system.main.loop}get duration(){return this.system.duration}get shape(){return this.system.shape}get startLife(){return new Cp(this.system.main.startLifetime)}get startSpeed(){return new Cp(this.system.main.startSpeed)}get startRotation(){return new Cp(this.system.main.startRotation)}get startSize(){return new Cp(this.system.main.startSize)}get startColor(){return new aO(new lO(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new WE(this.system)}get instancingGeometry(){return this.system.renderer.getMesh(this.system.renderer.renderMode).geometry}get renderMode(){if(this.system.trails.enabled===!0)return bn.Trail;switch(this.system.renderer.renderMode){case Hn.Billboard:return bn.BillBoard;case Hn.Stretch:return bn.StretchedBillBoard;case Hn.HorizontalBillboard:return bn.HorizontalBillBoard;case Hn.VerticalBillboard:return bn.VerticalBillBoard;case Hn.Mesh:return bn.Mesh}return bn.BillBoard}get speedFactor(){var t;let i=this.system.main.simulationSpeed;return((t=this.system.renderer)==null?void 0:t.renderMode)===Hn.Stretch&&(i*=this.system.renderer.velocityScale??1),i}get texture(){const t=this.material;if(t&&t.map){const i=t.map;if(this.clonedTexture.original!==i||!this.clonedTexture.clone){const n=i.clone();n.premultiplyAlpha=!1,n.colorSpace=or,this.clonedTexture.original=i,this.clonedTexture.clone=n}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=Gg(new xe(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new UE(this.system)}get uTileCount(){var t;return this.anim.enabled?(t=this.anim)==null?void 0:t.numTilesX:void 0}get vTileCount(){var t;return this.anim.enabled?(t=this.anim)==null?void 0:t.numTilesY:void 0}get renderOrder(){return 1}get blending(){var t;return((t=this.system.renderer.particleMaterial)==null?void 0:t.blending)??_C}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===xh.World}}class ZE{constructor(){a(this,"burstParticleIndex",0),a(this,"burstParticleCount",0),a(this,"isBursting",!1),a(this,"travelDistance",0),a(this,"previousWorldPos"),a(this,"burstIndex",0),a(this,"burstWaveIndex",0),a(this,"time",0),a(this,"waitEmiting",0)}}const kp=class extends A{constructor(){super(...arguments),a(this,"_state"),a(this,"colorOverLifetime"),a(this,"main"),a(this,"emission"),a(this,"sizeOverLifetime"),a(this,"shape"),a(this,"noise"),a(this,"trails"),a(this,"velocityOverLifetime"),a(this,"limitVelocityOverLifetime"),a(this,"inheritVelocity"),a(this,"colorBySpeed"),a(this,"textureSheetAnimation"),a(this,"rotationOverLifetime"),a(this,"rotationBySpeed"),a(this,"sizeBySpeed"),a(this,"_cameraScale",1),a(this,"__worldQuaternion",new V),a(this,"_worldQuaternionInverted",new V),a(this,"_worldScale",new x),a(this,"_worldPositionFrame",-1),a(this,"_worldPos",new x),a(this,"_renderer"),a(this,"_batchSystem"),a(this,"_particleSystem"),a(this,"_interface"),a(this,"_container"),a(this,"_time",0),a(this,"_isPlaying",!0),a(this,"_isUsedAsSubsystem",!1),a(this,"_didPreWarm",!1),a(this,"_bursts"),a(this,"_subEmitterSystems"),a(this,"_lastBatchesCount",-1)}play(s=!1){var t;s&&O.foreachComponent(this.gameObject,i=>{i instanceof kp&&i!==this&&i.play(!1)},!0),this._isPlaying=!0,this._particleSystem&&(this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1),(t=this.emission)==null||t.reset()}pause(s=!0){s&&O.foreachComponent(this.gameObject,t=>{t instanceof kp&&t!==this&&t.pause(!1)},!0),this._isPlaying=!1}stop(s=!0,t=!1){s&&O.foreachComponent(this.gameObject,i=>{i instanceof kp&&i!==this&&i.stop(!1,t)},!0),this._isPlaying=!1,this._time=0,t&&this.reset()}reset(){var s;this._time=0,this._particleSystem&&(this._particleSystem.particleNum=0,this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1,(s=this.emission)==null||s.reset())}emit(s){if(this._particleSystem){this.onUpdate(),s=Math.min(s,this.maxParticles-this.currentParticles),this._state||(this._state=new ZE),this._state.waitEmiting=s,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(s){this.main.playOnAwake=s}get renderer(){return this._renderer}get isPlaying(){return this._isPlaying}get currentParticles(){var s;return((s=this._particleSystem)==null?void 0:s.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}get container(){return this._container}get worldspace(){return this.main.simulationSpace===xh.World}get localspace(){return this.main.simulationSpace===xh.Local}get worldQuaternion(){return this.__worldQuaternion}get worldQuaternionInverted(){return this._worldQuaternionInverted}get worldScale(){return this._worldScale}get worldPos(){return this._worldPositionFrame!==this.context.time.frame&&(this._worldPositionFrame=this.context.time.frame,te(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}addBehaviour(s){return this._particleSystem?(s instanceof Ho&&(s.system=this),Vo&&console.debug("Add custom ParticleSystem Behaviour",s),this._particleSystem.addBehavior(s),!0):!1}removeBehaviour(s){if(!this._particleSystem)return!1;const t=this._particleSystem.behaviors,i=t.indexOf(s);return i!==-1&&((F()||Vo)&&console.debug("Remove custom ParticleSystem Behaviour",i,s),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}set bursts(s){for(let t=0;t<s.length;t++){const i=s[t];if(!(i instanceof wp)){const n=new wp;Ea(n,i),s[t]=n}}this._bursts=s}set subEmitterSystems(s){for(let t=0;t<s.length;t++){const i=s[t];if(!(i instanceof Mp)){const n=new Mp;Ea(n,i),s[t]=n}}Vo&&s.length>0&&console.log("SubEmitters: ",s,this),this._subEmitterSystems=s}onAfterDeserialize(s){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(ss),!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 I,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new oO,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new YE(this),this._particleSystem=new rO(this._interface),this._particleSystem.addBehavior(new qE(this)),this._particleSystem.addBehavior(new QE(this)),this._particleSystem.addBehavior(new VE(this)),this._particleSystem.addBehavior(new HE(this)),this._particleSystem.addBehavior(new XE(this)),this._particleSystem.addBehavior(new GE(this)),this._batchSystem.addSystem(this._particleSystem);const s=this._particleSystem.emitter;this.context.scene.add(s),this.inheritVelocity.system&&this.inheritVelocity.system!==this&&(this.inheritVelocity=this.inheritVelocity.clone()),this.inheritVelocity.awake(this),Vo&&(console.log(this),this.gameObject.add(new xi(1)))}start(){this.addSubParticleSystems(),this.updateLayers(),this.renderer.particleMesh instanceof Y&&this._interface.renderMode==bn.Mesh&&it.assignMeshLOD(this.renderer.particleMesh,0).then(s=>{s&&this.particleSystem&&this._interface.renderMode==bn.Mesh&&(this.particleSystem.instancingGeometry=s)})}onDestroy(){var s,t,i,n;(s=this._container)==null||s.removeFromParent(),(t=this._batchSystem)==null||t.removeFromParent(),(i=this._particleSystem)==null||i.emitter.removeFromParent(),(n=this._particleSystem)==null||n.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(){var s;this.main&&(this._didPreWarm===!1&&((s=this.main)==null?void 0:s.prewarm)===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){var s;if(!((s=this.emission)!=null&&s.enabled)||this.emission.rateOverTime.getMax()<=0)return;const t=1/60,i=this.main.duration,n=this.main.startLifetime.getMax(),o=1e3,r=Math.min(Math.max(i,n)/Math.max(.01,this.main.simulationSpeed),o),l=Math.ceil(r/t),c=Date.now();Vo&&console.log(`Particles ${this.name} - Prewarm for ${l} frames (${r} sec). Duration: ${i}, Lifetime: ${n}`);for(let h=0;h<l&&!(this.currentParticles>=this.maxParticles);h++){const d=Date.now()-c;if(d>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${d}`);break}this.onUpdate(),this.onSimulate(t)}}onSimulate(s){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(s)}this._time+=s,this._time>this.duration&&(this._time=0)}updateLayers(){if(this._batchSystem)for(let s=0;s<this._batchSystem.batches.length;s++){const t=this._batchSystem.batches[s];t.layers.disableAll();const i=this.layer;t.layers.mask=1<<i}}onUpdate(){var s,t;if(this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const i=this.context.mainCamera;if(i){const r=Ye(i);this._cameraScale=r.x}const n=!this.worldspace,o=this.gameObject;if(Ce(o,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),Ye(this.gameObject,this._worldScale),n&&this._container&&(s=this.gameObject)!=null&&s.parent){const r=d1(this,G0);this._container.matrix.makeScale(r.x,r.y,r.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),(t=this.inheritVelocity)==null||t.update(this.context),this.velocityOverLifetime.update(this)}addSubParticleSystems(){var s;if(this._subEmitterSystems&&this._particleSystem)for(const t of this._subEmitterSystems){t.particleSystem&&(t.particleSystem.__internalAwake?t.particleSystem.__internalAwake():F()&&console.warn("SubParticleSystem serialization issue(?)",t.particleSystem,t));const i=(s=t.particleSystem)==null?void 0:s._particleSystem;if(i){t.particleSystem._isUsedAsSubsystem=!0;const n=new N0(this,this._particleSystem,t.particleSystem,i);n.emitterType=t.type,n.emitterProbability=t.emitProbability,this._particleSystem.addBehavior(n)}else Vo&&console.warn("Could not add SubParticleSystem",t,this)}}};let lt=kp;Ge([m(xp)],lt.prototype,"colorOverLifetime",2),Ge([m(Ht)],lt.prototype,"main",2),Ge([m($n)],lt.prototype,"emission",2),Ge([m(Xr)],lt.prototype,"sizeOverLifetime",2),Ge([m(et)],lt.prototype,"shape",2),Ge([m(Pe)],lt.prototype,"noise",2),Ge([m(qe)],lt.prototype,"trails",2),Ge([m(tt)],lt.prototype,"velocityOverLifetime",2),Ge([m(mt)],lt.prototype,"limitVelocityOverLifetime",2),Ge([m(Qr)],lt.prototype,"inheritVelocity",2),Ge([m(Ml)],lt.prototype,"colorBySpeed",2),Ge([m($t)],lt.prototype,"textureSheetAnimation",2),Ge([m(Es)],lt.prototype,"rotationOverLifetime",2),Ge([m(is)],lt.prototype,"rotationBySpeed",2),Ge([m(vi)],lt.prototype,"sizeBySpeed",2);class Mp{constructor(){a(this,"particleSystem"),a(this,"emitProbability",1),a(this,"properties"),a(this,"type")}_deserialize(t,i){const n=this.particleSystem;if(n instanceof lt)return;let o="";n&&typeof n.guid=="string"&&(o=n.guid,this.particleSystem=O.findByGuid(o,i)),Vo&&!(this.particleSystem instanceof lt)&&console.warn("Could not find particle system for sub emitter",o,i,this)}}function d1(s,t){if(t.set(1,1,1),s.gameObject.parent&&s.localspace)switch(s.main.scalingMode){case U0.Local:t=Ye(s.gameObject.parent,t),t.x=1/t.x,t.y=1/t.y,t.z=1/t.z;break;default:if(!s.unsupported_scaling_mode){s.unsupported_scaling_mode=!0;const i="ParticleSystem scale mode "+U0[s.main.scalingMode]+" is not supported";F()&&we(i),console.warn(i,s.name,s)}t=Ye(s.gameObject,t);break}return t}class Wl extends A{constructor(){super(...arguments),a(this,"_didAssignPlayerColor",!1),a(this,"tryAssignColor",()=>{const t=O.getComponentInParent(this.gameObject,Ii);if(t&&t.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(t.owner),!0;const i=O.getComponentInParent(this.gameObject,Mt);return i!=null&&i.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(i.connectionId),!0):!1})}onEnable(){this.context.connection.beginListen(se.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(se.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield $g(.2),!this.tryAssignColor()););}assignUserColor(t){const i=Wl.hashCode(t),n=Wl.colorFromHashCode(i);if(this.gameObject.type==="Mesh"){const o=this.gameObject;this.assignColor(n,t,o)}else if(this.gameObject.children)for(const o of this.gameObject.children){const r=o;r.material&&r.material.color&&this.assignColor(n,t,r)}}assignColor(t,i,n){let o=n.material;o&&(o._playerMaterial!==i&&(o=o.clone(),o._playerMaterial=i,n.material=o),o.color=t)}static hashCode(t){var i=0,n,o;if(t.length===0)return i;for(n=0;n<t.length;n++)o=t.charCodeAt(n),i=(i<<5)-i+o,i|=0;return i}static colorFromHashCode(t){const i=(t&16711680)>>16,n=(t&65280)>>8,o=t&255;return new ae(i/255,n/255,o/255)}}const KE=C("debugpost");let X0=null;function JE(s){X0=s}function u1(s){let t=s.gameObject;for(;t;){for(const i of Zd(t))if(i.isPostProcessingManager===!0)return i;t=t.parent}return null}function eA(s){let t=u1(s);if(!t)if(X0){KE&&console.warn("Adding postprocessing manager to the scene.");const i=s.scene;t=Mi(i,X0)}else F()&&console.warn("No post processing manager found");return t}var tA=Object.defineProperty,iA=Object.getOwnPropertyDescriptor,p1=(s,t,i,n)=>{for(var o=n>1?void 0:n?iA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&tA(t,i,o),o};const sA=C("debugpost");class N{constructor(t){a(this,"isVolumeParameter",!0),a(this,"_isInitialized",!1),a(this,"_active",!0),a(this,"_value"),a(this,"_valueRaw"),a(this,"_defaultValue"),a(this,"valueProcessor"),a(this,"onValueChanged"),t!==void 0&&this.initialize(t)}get isInitialized(){return this._isInitialized}initialize(t){t!==void 0&&(this._value=t,this._defaultValue=t,this._valueRaw=t,this._isInitialized=!0)}get overrideState(){return this._active}set overrideState(t){if(this._active===t)return;this._active=t;const i=t?this._valueRaw:this._defaultValue;this.processValue(i,!0)}get value(){return this._valueRaw}set value(t){this.isInitialized||this.initialize(t),this.processValue(t,!1)}set defaultValue(t){this._defaultValue=t}__init(){this.processValue(this._valueRaw,!0)}processValue(t,i){if(t==null||!i&&this.testIfValueChanged(t)===!1)return;const n=this._value;sA&&typeof n=="number"&&typeof t=="number"&&(n?.toFixed(4),t?.toFixed(4)),!this._active&&this._defaultValue!==void 0?(this._value=this._defaultValue,t=this._defaultValue,this._valueRaw=t):(this._valueRaw=t,this._active&&this.valueProcessor&&(t=this.valueProcessor(t)),this._value=t),this.onValueChanged&&this.onValueChanged(t,n,this)}testIfValueChanged(t){return this._valueRaw!==t}}p1([m()],N.prototype,"overrideState",1),p1([m()],N.prototype,"value",1);class nA extends Qi{constructor(){super([N])}onSerialize(t,i){}onDeserialize(t,i){const n=i.target,o=i.path;let r;if(n&&o&&(r=n[o]),(typeof r!="object"||typeof r=="object"&&r.isVolumeParameter!==!0)&&(r=new N),typeof t=="object"&&"value"in t){const l=t.value;r.initialize(l),r.overrideState=t.overrideState}else r.value=t;return r}}new nA;var oA=Object.defineProperty,rA=Object.getOwnPropertyDescriptor,aA=(s,t,i,n)=>{for(var o=n>1?void 0:n?rA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&oA(t,i,o),o};const Q0=C("debugpost");class ct extends A{constructor(t=void 0){if(super(),a(this,"active",!0),a(this,"_manager",null),a(this,"_result"),a(this,"_postprocessingContext",null),t)for(const i of Object.keys(t)){const n=t[i],o=this[i];o instanceof N?o.initialize(n):o!==void 0&&(this[i]=n)}}get isPostProcessingEffect(){return!0}onEnable(){super.onEnable(),Q0&&console.warn("onEnable effect",this,this.__internalDidAwakeAndStart),this.__internalDidAwakeAndStart&&(this.active=!0),this.onEffectEnabled()}onDisable(){var t;super.onDisable(),Q0&&console.warn("onDisable effect",this),(t=this._manager)==null||t.removeEffect(this),this.active=!1}onEffectEnabled(t){var i;t&&t.isPostProcessingManager===!0?this._manager=t:this._manager||(this._manager=eA(this)),(i=this._manager)==null||i.addEffect(this)}init(){}get postprocessingContext(){return this._postprocessingContext}apply(t){var i;return this._postprocessingContext=t,this._result||(this.initParameters(),this._result=(i=this.onCreateEffect)==null?void 0:i.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){Q0&&console.warn("DISPOSE",this),this._result&&(Array.isArray(this._result)?this._result.forEach(t=>t.dispose()):this._result.dispose()),this._result=void 0}initParameters(){const t=Object.keys(this);for(const i of t){const n=this[i];n instanceof N&&n.__init()}}onEditorModification(t){const i=t.propertyName;if(this[i]instanceof N){const n=t.value;return this[i].value=n,!0}}}aA([m()],ct.prototype,"active",2);var lA=Object.defineProperty,cA=Object.getOwnPropertyDescriptor,hA=(s,t,i,n)=>{for(var o=n>1?void 0:n?cA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&lA(t,i,o),o};const dA=C("debugpost"),Y0={};function ns(s,t){Y0[s]=t}function uA(s){return s.__type in Y0?Y0[s.__type]:(dA&&s.__type&&console.warn("Unknown postprocessing type",s.__type,s),ct)}class Rp{constructor(){a(this,"components",[])}__init(t){var i;(i=this.components)==null||i.forEach(n=>{n.gameObject===void 0&&t.gameObject.addComponent(n),n.init()})}addEffect(t){this.components.push(t)}removeEffect(t){const i=this.components.indexOf(t);i>=0&&this.components.splice(i,1)}}hA([Pr([s=>uA(s),ct])],Rp.prototype,"components",2);var pA=Object.defineProperty,mA=Object.getOwnPropertyDescriptor,gA=(s,t,i,n)=>{for(var o=n>1?void 0:n?mA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&pA(t,i,o),o};class Oh extends ct{constructor(){super(...arguments),a(this,"preset",new N(2))}get typeName(){return"Antialiasing"}onCreateEffect(){const t=new D.POSTPROCESSING.MODULE.SMAAEffect({preset:D.POSTPROCESSING.MODULE.SMAAPreset.HIGH,edgeDetectionMode:D.POSTPROCESSING.MODULE.EdgeDetectionMode.DEPTH});return this.preset.onValueChanged=i=>{t.applyPreset(i)},t}}gA([m(N)],Oh.prototype,"preset",2),ns("Antialiasing",Oh);var fA=Object.defineProperty,yA=Object.getOwnPropertyDescriptor,Z0=(s,t,i,n)=>{for(var o=n>1?void 0:n?yA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&fA(t,i,o),o},K0;const m1=(K0=class extends ct{constructor(){super(...arguments),a(this,"threshold",new N(.9)),a(this,"intensity",new N(1)),a(this,"scatter",new N(.3)),a(this,"selectiveBloom")}get typeName(){return"Bloom"}init(){this.threshold.valueProcessor=s=>s,this.intensity.valueProcessor=s=>s,this.scatter.valueProcessor=s=>s}onCreateEffect(){let s;if(this.selectiveBloom==null&&(this.selectiveBloom=m1.useSelectiveBloom),this.selectiveBloom){const t=s=new D.POSTPROCESSING.MODULE.SelectiveBloomEffect(this.context.scene,this.context.mainCamera,{blendFunction:D.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});t.inverted=!0}else s=new D.POSTPROCESSING.MODULE.BloomEffect({blendFunction:D.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=>{s.intensity=t},this.threshold.onValueChanged=t=>{s.luminanceMaterial.threshold=Math.pow(t,2.2)},this.scatter.onValueChanged=t=>{s.luminancePass.enabled=!0,s.luminanceMaterial.smoothing=t,s.mipmapBlurPass&&(s.mipmapBlurPass.radius=mn.lerp(.1,.9,t))},s}},a(K0,"useSelectiveBloom",!1),K0);let Zr=m1;Z0([m(N)],Zr.prototype,"threshold",2),Z0([m(N)],Zr.prototype,"intensity",2),Z0([m(N)],Zr.prototype,"scatter",2),ns("Bloom",Zr);var vA=Object.defineProperty,bA=Object.getOwnPropertyDescriptor,_A=(s,t,i,n)=>{for(var o=n>1?void 0:n?bA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&vA(t,i,o),o};class Ph extends ct{constructor(){super(...arguments),a(this,"intensity",new N(0))}get typeName(){return"ChromaticAberration"}onCreateEffect(){const t=new D.POSTPROCESSING.MODULE.ChromaticAberrationEffect;return t.offset=new re(0,0),t.radialModulation=!0,t.modulationOffset=.15,this.intensity.valueProcessor=i=>i*.02,this.intensity.onValueChanged=i=>{t.offset.x=-i,t.offset.y=i},t}}_A([m(N)],Ph.prototype,"intensity",2),ns("ChromaticAberration",Ph);var wA=Object.defineProperty,xA=Object.getOwnPropertyDescriptor,g1=(s,t,i,n)=>{for(var o=n>1?void 0:n?xA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&wA(t,i,o),o};const f1=C("debugpost");var Tp=(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))(Tp||{});function J0(s){switch(s){case 0:return hd;case 1:return mm;case 2:return pm;case 3:return cd;case 4:return Xl;default:return Xl}}function SA(s){switch(s){case hd:return 0;case pm:return 2;case cd:return 3;case Xl:return 1;case mm:return 1;default:return 0}}function y1(s){switch(s){case hd:return D.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR;case pm:return D.POSTPROCESSING.MODULE.ToneMappingMode.ACES_FILMIC;case cd:return D.POSTPROCESSING.MODULE.ToneMappingMode.AGX;case Xl:return D.POSTPROCESSING.MODULE.ToneMappingMode.NEUTRAL;case mm:return D.POSTPROCESSING.MODULE.ToneMappingMode.REINHARD;default:return D.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR}}const v1=class extends ct{constructor(){super(...arguments),a(this,"mode",new N(void 0)),a(this,"exposure",new N(1))}get typeName(){return"ToneMapping"}setMode(s){const t=Tp[s];return t===void 0?(console.error("Invalid ToneMapping mode",s),this):(this.mode.value=t,this)}get isToneMapping(){return!0}onEffectEnabled(){const s=u1(this);s&&super.onEffectEnabled(s)}onCreateEffect(){if(this.postprocessingContext)for(const i of this.postprocessingContext.components){if(i===this)break;if(i!=this&&i instanceof v1){console.warn("Multiple tonemapping effects found in the same postprocessing stack: Please check your scene setup.",{activeEffect:i,ignoredEffect:this});return}}if(this.mode.isInitialized==!1){const i=SA(this.context.renderer.toneMapping);this.mode.initialize(i)}const s=J0(this.mode.value),t=new D.POSTPROCESSING.MODULE.ToneMappingEffect({mode:y1(s)});return this.mode.onValueChanged=i=>{const n=J0(i);t.mode=y1(n),f1&&console.log("ToneMapping mode changed to",Tp[i],n,t.mode)},f1&&console.log("Use ToneMapping",Tp[this.mode.value],s,t.mode,"renderer.tonemapping: "+this.context.renderer.toneMapping),this.exposure.onValueChanged=i=>{this.context.renderer.toneMappingExposure=i},t}onBeforeRender(){this.mode.overrideState&&(this.context.renderer.toneMapping=J0(this.mode.value)),this.exposure.overrideState&&(this.context.renderer.toneMappingExposure=this.exposure.value)}};let $o=v1;g1([m(N)],$o.prototype,"mode",2),g1([m(N)],$o.prototype,"exposure",2),ns("Tonemapping",$o);var CA=Object.defineProperty,OA=Object.getOwnPropertyDescriptor,Ep=(s,t,i,n)=>{for(var o=n>1?void 0:n?OA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&CA(t,i,o),o};class qo extends ct{constructor(){super(...arguments),a(this,"postExposure",new N(0)),a(this,"contrast",new N(0)),a(this,"hueShift",new N(0)),a(this,"saturation",new N(0))}get typeName(){return"ColorAdjustments"}init(){this.postExposure.valueProcessor=t=>(t=Math.pow(2,t),t),this.contrast.valueProcessor=t=>{let i=1;return t>0?i=200:t<0&&(i=100),t/i},this.contrast.defaultValue=0,this.hueShift.valueProcessor=t=>Math.PI*t/180,this.hueShift.defaultValue=0,this.saturation.valueProcessor=t=>t<0?t/100:t/(100*Math.PI),this.saturation.defaultValue=0}onCreateEffect(){var t,i;const n=[];this.context.renderer.toneMapping!==fa&&this.postExposure.overrideState&&(this.context.renderer.toneMapping=fa);let o=(t=this.postprocessingContext)==null?void 0:t.components.find(c=>c instanceof $o);o||(o=new $o,(i=this.postprocessingContext)==null||i.components.push(o)),this.postExposure.onValueChanged=c=>{this.postExposure.overrideState&&(o.exposure.value=c)};const r=new D.POSTPROCESSING.MODULE.BrightnessContrastEffect;this.contrast.onValueChanged=c=>r.contrast=c;const l=new D.POSTPROCESSING.MODULE.HueSaturationEffect;return n.push(r),n.push(l),this.hueShift.onValueChanged=c=>l.hue=c,this.saturation.onValueChanged=c=>l.saturation=c,n}}Ep([m(N)],qo.prototype,"postExposure",2),Ep([m(N)],qo.prototype,"contrast",2),Ep([m(N)],qo.prototype,"hueShift",2),Ep([m(N)],qo.prototype,"saturation",2),ns("ColorAdjustments",qo);var PA=Object.defineProperty,kA=Object.getOwnPropertyDescriptor,Kr=(s,t,i,n)=>{for(var o=n>1?void 0:n?kA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&PA(t,i,o),o};const MA=C("debugpost");class As extends ct{constructor(){super(...arguments),a(this,"mode"),a(this,"focusDistance",new N(1)),a(this,"focalLength",new N(.2)),a(this,"aperture",new N(20)),a(this,"gaussianMaxRadius",new N),a(this,"resolutionScale",new N(1*1/window.devicePixelRatio)),a(this,"bokehScale",new N)}get typeName(){return"DepthOfField"}init(){this.focalLength.valueProcessor=i=>{const n=i/300,o=2;return W.lerp(o,.01,n)};const t=20;this.aperture.valueProcessor=i=>{const n=1-i/32;return W.lerp(1,t,n)}}onCreateEffect(){if(this.mode===0){MA&&console.warn("DepthOfField: Mode is set to Off");return}const t=new D.POSTPROCESSING.MODULE.DepthOfFieldEffect(this.context.mainCamera,{worldFocusRange:.2,focalLength:1,bokehScale:20,resolutionScale:this.resolutionScale.value});return this.focusDistance.onValueChanged=i=>{t.cocMaterial.worldFocusDistance=i},this.focalLength.onValueChanged=i=>t.cocMaterial.worldFocusRange=i,this.aperture.onValueChanged=i=>t.bokehScale=i,this.resolutionScale&&(this.resolutionScale.onValueChanged=i=>t.resolution.scale=i),[t]}unapply(){}}Kr([m()],As.prototype,"mode",2),Kr([m(N)],As.prototype,"focusDistance",2),Kr([m(N)],As.prototype,"focalLength",2),Kr([m(N)],As.prototype,"aperture",2),Kr([m(N)],As.prototype,"gaussianMaxRadius",2),Kr([m(N)],As.prototype,"resolutionScale",2),Kr([m(N)],As.prototype,"bokehScale",2),ns("DepthOfField",As);class kh extends ct{constructor(t){super(),a(this,"effect"),this.effect=t}get typeName(){return this.effect.constructor.name}onCreateEffect(){return this.effect}}var RA=Object.defineProperty,TA=Object.getOwnPropertyDescriptor,EA=(s,t,i,n)=>{for(var o=n>1?void 0:n?TA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&RA(t,i,o),o};class Mh extends ct{constructor(){super(...arguments),a(this,"granularity",new N(10))}get typeName(){return"PixelationEffect"}onCreateEffect(){const t=new D.POSTPROCESSING.MODULE.PixelationEffect;return this.granularity.onValueChanged=i=>{t.granularity=i},t}}EA([m(N)],Mh.prototype,"granularity",2),ns("PixelationEffect",Mh);var AA=Object.defineProperty,IA=Object.getOwnPropertyDescriptor,Rh=(s,t,i,n)=>{for(var o=n>1?void 0:n?IA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&AA(t,i,o),o};class qn extends ct{constructor(){super(...arguments),a(this,"intensity",new N(2)),a(this,"falloff",new N(1)),a(this,"samples",new N(9)),a(this,"color",new N(new ae(0,0,0))),a(this,"luminanceInfluence",new N(.7)),a(this,"_ssao")}get typeName(){return"ScreenSpaceAmbientOcclusion"}onBeforeRender(){if(this._ssao&&this.context.mainCamera instanceof _e){const t=this.context.mainCamera.far-this.context.mainCamera.near;this._ssao.ssaoMaterial.worldDistanceFalloff=t*.01,this._ssao.ssaoMaterial.worldDistanceThreshold=this.context.mainCamera.far}}onCreateEffect(){const t=this.context.mainCamera,i=new D.POSTPROCESSING.MODULE.NormalPass(this.context.scene,t),n=new D.POSTPROCESSING.MODULE.DepthDownsamplingPass({normalBuffer:i.texture,resolutionScale:.5}),o=this._ssao=new D.POSTPROCESSING.MODULE.SSAOEffect(t,i.texture,{normalDepthBuffer:n.texture,worldDistanceThreshold:1,worldDistanceFalloff:1,worldProximityThreshold:.1,worldProximityFalloff:2,intensity:1,blendFunction:D.POSTPROCESSING.MODULE.BlendFunction.MULTIPLY,luminanceInfluence:.5});this.intensity.onValueChanged=l=>{o.intensity=l},this.falloff.onValueChanged=l=>{o.ssaoMaterial.radius=l*.1},this.samples.onValueChanged=l=>{o.ssaoMaterial.samples=l},this.color.onValueChanged=l=>{o.color||(o.color=new ae),o.color.copy(l)},this.luminanceInfluence.onValueChanged=l=>{o.luminanceInfluence=l};const r=new Array;return r.push(i),r.push(n),r.push(o),r}}Rh([m(N)],qn.prototype,"intensity",2),Rh([m(N)],qn.prototype,"falloff",2),Rh([m(N)],qn.prototype,"samples",2),Rh([m(N)],qn.prototype,"color",2),Rh([m(N)],qn.prototype,"luminanceInfluence",2),ns("ScreenSpaceAmbientOcclusion",qn);var jA=Object.defineProperty,LA=Object.getOwnPropertyDescriptor,Jr=(s,t,i,n)=>{for(var o=n>1?void 0:n?LA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&jA(t,i,o),o};const DA=C("debugN8AO");var ey=(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))(ey||{});class Is extends ct{constructor(){super(...arguments),a(this,"gammaCorrection",!0),a(this,"aoRadius",new N(1)),a(this,"falloff",new N(1)),a(this,"intensity",new N(1)),a(this,"color",new N(new ae(0,0,0))),a(this,"screenspaceRadius",!1),a(this,"quality",2),a(this,"_ssao")}get typeName(){return"ScreenSpaceAmbientOcclusionN8"}get pass(){return this._ssao}onValidate(){this._ssao&&(this._ssao.setQualityMode(ey[this.quality]),this._ssao.configuration.gammaCorrection=this.gammaCorrection,this._ssao.configuration.screenSpaceRadius=this.screenspaceRadius)}onCreateEffect(){const t=this.context.mainCamera,i=this.context.domWidth,n=this.context.domHeight,o=this._ssao=new D.POSTPROCESSING_AO.MODULE.N8AOPostPass(this.context.scene,t,i,n),r=ey[this.quality];o.setQualityMode(r),o.configuration.transparencyAware=!1;const l=new vn(i,n);return o.configuration.beautyRenderTarget=l,o.configuration.autoRenderBeauty=!1,o.configuration.gammaCorrection=this.gammaCorrection,o.configuration.screenSpaceRadius=this.screenspaceRadius,DA&&(o.enableDebugMode(),console.log(o),setInterval(()=>{console.log("SSAO",o.lastTime)},1e3),setInterval(()=>{console.log("SSAO",o.enabled,{ssao:o,autoRenderBeauty:o.configuration.autoRenderBeauty})},4e3)),this.intensity.onValueChanged=c=>{o.configuration.intensity=c},this.falloff.onValueChanged=c=>{o.configuration.distanceFalloff=c},this.aoRadius.onValueChanged=c=>{o.configuration.aoRadius=c},this.color.onValueChanged=c=>{o.color||(o.color=new ae),o.configuration.color.copy(c)},o}}Jr([kt(),m()],Is.prototype,"gammaCorrection",2),Jr([m(N)],Is.prototype,"aoRadius",2),Jr([m(N)],Is.prototype,"falloff",2),Jr([m(N)],Is.prototype,"intensity",2),Jr([m(N)],Is.prototype,"color",2),Jr([kt(),m()],Is.prototype,"screenspaceRadius",2),Jr([kt(),m()],Is.prototype,"quality",2),ns("ScreenSpaceAmbientOcclusionN8",Is);var BA=Object.defineProperty,FA=Object.getOwnPropertyDescriptor,b1=(s,t,i,n)=>{for(var o=n>1?void 0:n?FA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&BA(t,i,o),o};class Th extends ct{constructor(){super(...arguments),a(this,"_effect"),a(this,"_amount",1),a(this,"_radius",1)}get typeName(){return"Sharpening"}onCreateEffect(){return this._effect??(this._effect=new(zA())),this.effect}get effect(){return this._effect}set amount(t){this._amount=t,this._effect&&(this._effect.uniforms.get("amount").value=t)}get amount(){return this._effect?this._effect.uniforms.get("amount").value:this._amount}set radius(t){this._radius=t,this._effect&&(this._effect.uniforms.get("radius").value=t)}get radius(){return this._effect?this._effect.uniforms.get("radius").value:this._radius}}b1([m()],Th.prototype,"amount",1),b1([m()],Th.prototype,"radius",1);function zA(){const s=`
1225
+ `)}l&&r.size&&console.log(p);const f=new Set;for(const w of y){w.getPath||console.error("USDZExporter: Animation target object has no getPath method. This is likely a bug",w);let _=w.getPath();_.startsWith("<")&&(_=_.substring(1)),_.endsWith(">")&&(_=_.substring(0,_.length-1)),f.add({path:_,obj:w})}const v=Array.from(f).sort((w,_)=>w.path.length-_.path.length),b=new Array;for(let w=0;w<v.length;w++)for(let _=w+1;_<v.length;_++)if(v[_].path.startsWith(v[w].path)){const S=v[_],R=v[w];b.push({child:S.obj.displayName+" ("+S.path+")",parent:R.obj.displayName+" ("+R.path+")"})}b.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:b,playAnimationActions:r})}for(const p of new Set([...i,...n]))if(Array.isArray(p))for(const g of p)o.add(g.uuid);else o.add(p.uuid);hp&&console.log("All Behavior trigger sources and action targets",i,n,o),this.targetUuids=new Set(o)}onAfterHierarchy(t,i){var n;if((n=this.behaviours)!=null&&n.length){i.beginBlock('def Scope "Behaviors"');for(const o of this.behaviours)o.writeTo(this,t.document,i);i.closeBlock()}}async onAfterSerialize(t){hp&&console.log("onAfterSerialize behaviours",this.behaviourComponentsCopy);for(const i of this.behaviourComponentsCopy)typeof i.afterSerialize=="function"&&(i.afterSerialize.constructor.name==="AsyncFunction"?await i.afterSerialize(this,t):i.afterSerialize(this,t));for(const{clipUrl:i,filesKey:n}of this.audioClipsCopy){if(t.files[n])return;const o=await(await(await fetch(i)).blob()).arrayBuffer(),r=new Uint8Array(o);t.files[n]=r}this.behaviourComponentsCopy.length=0,this.audioClipsCopy.length=0}}class y0{get extensionName(){return"Physics"}onExportObject(t,i,n){const o=O.getComponents(t,ye).filter(h=>h.enabled),r=O.getComponents(t,di).filter(h=>h.enabled&&!h.isTrigger);let l=o.length>0?o[0]:null;const c=r.length>0?r[0]:null;c&&!l&&(l=new ye,l.isKinematic=!0),l&&i.addEventListener("serialize",(h,d)=>{var u,p,g;if(l){if(h.appendLine(),h.beginBlock('def RealityKitComponent "RigidBody"',"{",!0),l.useGravity||h.appendLine("bool gravityEnabled = 0"),h.appendLine('uniform token info:id = "RealityKit.RigidBody"'),l.isKinematic&&h.appendLine('token motionType = "Kinematic"'),h.beginBlock('def RealityKitStruct "massFrame"',"{",!0),h.appendLine(`float m_mass = ${l.mass}`),h.beginBlock('def RealityKitStruct "m_pose"',"{",!0),h.appendLine(`float3 position = (${l.centerOfMass.x}, ${l.centerOfMass.y}, ${l.centerOfMass.z})`),h.closeBlock("}"),h.closeBlock("}"),r.length>0){const y=r[0];h.beginBlock('def RealityKitStruct "material"',"{",!0);const f=y.sharedMaterial;f&&f.dynamicFriction!==void 0&&h.appendLine(`double dynamicFriction = ${(u=y.sharedMaterial)==null?void 0:u.dynamicFriction}`),f&&f.bounciness!==void 0&&h.appendLine(`double restitution = ${(p=y.sharedMaterial)==null?void 0:p.bounciness}`),f&&f.staticFriction!==void 0&&h.appendLine(`double staticFriction = ${(g=y.sharedMaterial)==null?void 0:g.staticFriction}`),h.closeBlock("}")}h.closeBlock("}")}}),c&&(i.addEventListener("serialize",(h,d)=>{var u;h.beginBlock('def RealityKitComponent "Collider"',"{",!0),h.appendLine("uint group = 1"),h.appendLine('uniform token info:id = "RealityKit.Collider"'),h.appendLine("uint mask = 4294967295");const p=c.isTrigger?"Trigger":"Default";if(h.appendLine(`token type = "${p}"`),h.beginBlock('def RealityKitStruct "Shape"',"{",!0),c instanceof Qa){const g=c;h.appendLine('token shapeType = "Sphere"'),h.appendLine(`float radius = ${g.radius}`)}else if(c instanceof Ya){const g=c;h.appendLine('token shapeType = "Box"'),h.appendLine(`float3 extent = (${g.size.x}, ${g.size.y}, ${g.size.z})`)}else if(c instanceof In){const g=c;h.appendLine('token shapeType = "Capsule"'),h.appendLine(`float radius = ${g.radius}`),h.appendLine(`float height = ${g.height}`)}else if(c instanceof Ro&&(u=c.sharedMesh)!=null&&u.geometry){const g=c.sharedMesh.geometry;g.boundingBox||g.computeBoundingBox();const y=c.sharedMesh.geometry.boundingBox;y&&(h.appendLine('token shapeType = "Box"'),h.appendLine(`float3 extent = (${y.max.x-y.min.x}, ${y.max.y-y.min.y}, ${y.max.z-y.min.z})`),console.log("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. MeshCollider will be exported as Box",c))}else console.warn("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. Ignoring collider:",c);h.beginBlock('def RealityKitStruct "pose"',"{",!0),h.closeBlock("}"),h.closeBlock("}"),h.closeBlock("}")}),r.length>1&&console.log("WARNING: Multiple colliders detected. visionOS / iOS can only support objects with a single collider, only exporting the first collider: ",c))}}var NT=Object.defineProperty,WT=Object.getOwnPropertyDescriptor,ph=(s,t,i,n)=>{for(var o=n>1?void 0:n?WT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&NT(t,i,o),o};const v0=C("debugui"),b0=C("debuguilayout");class Gx{constructor(){a(this,"width"),a(this,"height")}}class Xx{constructor(){a(this,"x"),a(this,"y"),a(this,"width"),a(this,"height")}}const Ts=new x,mh=new ne,dp=new V,Qx=class extends rs{constructor(){super(...arguments),a(this,"_anchoredPosition"),a(this,"sizeDelta",new re(100,100)),a(this,"pivot",new re(.5,.5)),a(this,"anchorMin",new re(0,0)),a(this,"anchorMax",new re(1,1)),a(this,"minWidth"),a(this,"minHeight"),a(this,"lastMatrix"),a(this,"rectBlock"),a(this,"_transformNeedsUpdate",!1),a(this,"_initialPosition"),a(this,"_parentRectTransform"),a(this,"_lastUpdateFrame",-1),a(this,"_lastAnchoring"),a(this,"_createdBlocks",[]),a(this,"_createdTextBlocks",[])}get parent(){return this._parentRectTransform}get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new re),this._anchoredPosition}set anchoredPosition(s){this._anchoredPosition=s}get width(){let s=this.sizeDelta.x;if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const t=this._parentRectTransform.width,i=this.anchorMax.x-this.anchorMin.x;s=t*i,s+=this.sizeDelta.x}return this.minWidth!==void 0&&s<this.minWidth?this.minWidth:s}get height(){let s=this.sizeDelta.y;if(this.anchorMin.y!==this.anchorMax.y&&this._parentRectTransform){const t=this._parentRectTransform.height,i=this.anchorMax.y-this.anchorMin.y;s=t*i,s+=this.sizeDelta.y}return this.minHeight!==void 0&&s<this.minHeight?this.minHeight:s}awake(){super.awake(),this._anchoredPosition||(this._anchoredPosition=new re),this.lastMatrix=new ne,this.rectBlock=new I,this.rectBlock.name=this.name,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,Ha(this,"_anchoredPosition",()=>{this.markDirty()}),Ha(this,"sizeDelta",()=>{this.markDirty()}),Ha(this,"pivot",()=>{this.markDirty()}),Ha(this,"anchorMin",()=>{this.markDirty()}),Ha(this,"anchorMax",()=>{this.markDirty()})}onEnable(){var s;super.onEnable(),this.rectBlock||(this.rectBlock=new I),this.lastMatrix||(this.lastMatrix=new ne),this._lastAnchoring||(this._lastAnchoring=new re),this._initialPosition||(this._initialPosition=new x),this._anchoredPosition||(this._anchoredPosition=new re),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,(s=this.canvas)==null||s.registerTransform(this)}onDisable(){var s;super.onDisable(),this.removeShadowComponent(),(s=this.canvas)==null||s.unregisterTransform(this)}onParentRectTransformChanged(s){this._transformNeedsUpdate||this.onApplyTransform(b0?`${s.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(b0&&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(s){var t;if(this.context.time.frameCount===this._lastUpdateFrame)return;this._lastUpdateFrame=this.context.time.frameCount;const i=this.shadowComponent;if(!i)return;this.gameObject.parent?this._parentRectTransform=O.getComponentInParent(this.gameObject.parent,Qx):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,b0&&console.warn("RectTransform \u2192 ApplyTransform",this.name+" because "+s),this.isRoot()?this.Root.screenspace||(i.rotation.y=Math.PI):(i.matrix.identity(),i.matrixAutoUpdate=!1,Ts.set(0,0,0),this.applyPivot(Ts),i.matrix.setPosition(Ts.x,Ts.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(dp.copy(this.gameObject.quaternion),dp.x*=-1,dp.z*=-1,mh.makeRotationFromQuaternion(dp),i.matrix.premultiply(mh)),Ts.set(0,0,0),this.applyAnchoring(Ts),(t=this.canvas)!=null&&t.screenspace?Ts.z+=.1:Ts.z+=.01,mh.identity(),mh.setPosition(Ts.x,Ts.y,Ts.z),i.matrix.premultiply(mh),i.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const n=!0;for(const o of Zd(this.gameObject,rs,n,1)){if(o===this||!o.activeAndEnabled)continue;const r=o;r.onParentRectTransformChanged&&r.onParentRectTransformChanged(this)}}applyAnchoring(s){this._lastAnchoring||(this._lastAnchoring=new re);const t=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=t.x,this.gameObject.position.y+=t.y,this._lastAnchoring.copy(this._anchoredPosition),s.x+=this._initialPosition.x-this.gameObject.position.x,s.y+=this._initialPosition.y-this.gameObject.position.y,s.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,s.y+=n;let r=0;const l=1-this.anchorMax.x-this.anchorMin.x;r-=i.width*.5*l,s.x+=r}}applyPivot(s){if(this.pivot&&!this.isRoot()){const t=this.pivot.x-.5;s.x-=t*this.sizeDelta.x*this.gameObject.scale.x;const i=this.pivot.y-.5;s.y-=i*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){const s={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:0,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(s),s}ensureValidSize(s,t=1e-4){return s.width<=0&&(s.width=t),s.height<=0&&(s.height=1e-4),s}createNewBlock(s){s={...this.getBasicOptions(),...s},v0&&console.log(this.name,s);const t=new gv(s);return this._createdBlocks.push(t),t}createNewText(s){v0&&console.log(s),s={...this.getBasicOptions(),...s},v0&&console.log(this.name,s);const t=new mv(s);return this._createdTextBlocks.push(t),t}};let Wt=Qx;ph([m(re)],Wt.prototype,"anchoredPosition",1),ph([m(re)],Wt.prototype,"sizeDelta",2),ph([m(re)],Wt.prototype,"pivot",2),ph([m(re)],Wt.prototype,"anchorMin",2),ph([m(re)],Wt.prototype,"anchorMax",2);var VT=Object.defineProperty,HT=Object.getOwnPropertyDescriptor,Yx=(s,t,i,n)=>{for(var o=n>1?void 0:n?HT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&VT(t,i,o),o};class xl extends A{constructor(){super(...arguments),a(this,"effectColor"),a(this,"effectDistance")}}Yx([m(xe)],xl.prototype,"effectColor",2),Yx([m(re)],xl.prototype,"effectDistance",2);var $T=Object.defineProperty,qT=Object.getOwnPropertyDescriptor,Zx=(s,t,i,n)=>{for(var o=n>1?void 0:n?qT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&$T(t,i,o),o};const up={backgroundColor:new ae(1,1,1),backgroundOpacity:1,borderColor:new ae(1,1,1),borderOpacity:1};var _0;const gh=(_0=class extends rs{constructor(){super(...arguments),a(this,"_alphaFactor",1),a(this,"sRGBColor",new ae(1,0,1)),a(this,"raycastTarget",!0),a(this,"uiObject",null),a(this,"_color",null),a(this,"_rect",null),a(this,"_stateManager",null),a(this,"_currentlyCreatingPanel",!1)}get isGraphic(){return!0}get color(){return this._color||(this._color=new xe(1,1,1,1)),this._color}set color(s){(!this._color||this._color.r!==s.r||this._color.g!==s.g||this._color.b!==s.b||this._color.alpha!==s.alpha)&&(this._color||(this._color=new xe(1,1,1,1)),this._color.copy(s),this.onColorChanged())}setAlphaFactor(s){this._alphaFactor=s,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}onColorChanged(){this.uiObject&&(this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),up.backgroundColor=this.sRGBColor,up.backgroundOpacity=this._color.alpha*this._alphaFactor,this.applyEffects(up,this._alphaFactor),this.uiObject.set(up),this.markDirty())}get m_Color(){return this._color}get rectTransform(){if(this._rect||(this._rect=O.getComponent(this.gameObject,Wt)),!this._rect)throw new Error("Not Supported: Make sure to add a RectTransform component before adding a UI Graphic component.");return this._rect}onParentRectTransformChanged(){var s;(s=this.uiObject)==null||s.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(s){return super.__internalNewInstanceCreated(s),this._rect=null,this.uiObject=null,this._color&&(this._color=this._color.clone()),this}setState(s){this.makePanel(),this.uiObject&&(this.uiObject.setState(s),this==null||this.markDirty())}setupState(s){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new mO(this.uiObject)),this.uiObject.setupState(s.state,s.attributes))}setOptions(s){this.makePanel(),this.uiObject&&this.uiObject.set(s)}awake(){super.awake(),this.makePanel(),Ha(this,"_color",()=>bM(this,this.onColorChanged))}onEnable(){var s;super.onEnable(),this.uiObject&&((s=this.rectTransform.shadowComponent)==null||s.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;const s=.015,t={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:s};this.onBeforeCreate(t),this.applyEffects(t),this.onCreate(t),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated(),this.onColorChanged()}onBeforeCreate(s){}onCreate(s){this.uiObject=this.rectTransform.createNewBlock(s),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(s,t=1){var i;const n=(i=this.gameObject)==null?void 0:i.getComponent(xl);n&&(n.effectDistance&&(s.borderWidth=Math.max(Math.abs(n.effectDistance.x),Math.abs(n.effectDistance.y))),n.effectColor&&(s.borderColor=n.effectColor,s.borderOpacity=n.effectColor.alpha*t))}async setTexture(s){if(this.setOptions({backgroundOpacity:0}),s){if(gh.textureCache.has(s))s=gh.textureCache.get(s);else if(!s.isRenderTargetTexture){const t=s.clone();t.colorSpace=or,gh.textureCache.set(s,t),s=t}this.setOptions({backgroundImage:s,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}),it.assignTextureLOD(s,0).then(t=>{t instanceof Le&&(s&&gh.textureCache.set(s,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)}},a(_0,"textureCache",new Map),_0);let Ur=gh;Zx([m(xe)],Ur.prototype,"color",1),Zx([m()],Ur.prototype,"raycastTarget",2);class fh extends Ur{constructor(){super(...arguments),a(this,"_flippedObject",!1)}onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var GT=Object.defineProperty,XT=Object.getOwnPropertyDescriptor,Vn=(s,t,i,n)=>{for(var o=n>1?void 0:n?XT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&GT(t,i,o),o};const Nr=C("debugtext");var pt=(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))(pt||{}),Kx=(s=>(s[s.Normal=0]="Normal",s[s.Bold=1]="Bold",s[s.Italic=2]="Italic",s[s.BoldAndItalic=3]="BoldAndItalic",s))(Kx||{});class Vt extends Ur{constructor(){super(...arguments),a(this,"alignment",0),a(this,"verticalOverflow",0),a(this,"horizontalOverflow",0),a(this,"lineSpacing",1),a(this,"supportRichText",!1),a(this,"font"),a(this,"fontStyle",0),a(this,"sRGBTextColor",new ae(1,0,1)),a(this,"_text",""),a(this,"_fontSize",12),a(this,"_textMeshUi",null),a(this,"_didHandleTextRenderOnTop",!1)}setAlphaFactor(t){var i;super.setAlphaFactor(t),(i=this.uiObject)==null||i.set({fontOpacity:this.color.alpha*this.alphaFactor}),this.markDirty()}get text(){return this._text}set text(t){t!==this._text&&(this._text=t,this.feedText(this.text,this.supportRichText),this.markDirty())}set_text(t){this.text=t}get fontSize(){return this._fontSize}set fontSize(t){var i;this._fontSize=t,(i=this.uiObject)==null||i.set({fontSize:t})}onColorChanged(){var t;this.sRGBTextColor.copy(this.color),this.sRGBTextColor.convertLinearToSRGB(),(t=this.uiObject)==null||t.set({color:this.sRGBTextColor,fontOpacity:this.color.alpha})}onParentRectTransformChanged(){super.onParentRectTransformChanged(),this.uiObject&&this.updateOverflow()}onBeforeCanvasRender(t){this.updateOverflow()}updateOverflow(){var t;const i=(t=this.uiObject)==null?void 0:t._overflow;i&&(i._needsUpdate=!0)}onCreate(t){Nr&&console.log(this),this.horizontalOverflow==1&&(t.whiteSpace="pre"),this.verticalOverflow==0&&(this.context.renderer.localClippingEnabled=!0,t.overflow="hidden"),this.horizontalOverflow==1&&this.verticalOverflow==0,t.lineHeight=this.lineSpacing,delete t.backgroundOpacity,delete t.backgroundColor,Nr&&(t.backgroundColor=16750848,t.backgroundOpacity=.5);const i=this.rectTransform;t={...t,...this.getTextOpts()},this.getAlignment(t),Nr&&(t.backgroundColor=Math.random()*16777215,t.backgroundOpacity=.1),this.uiObject=i.createNewText(t),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}getTextOpts(){const t=this.fontSize,i={color:this.color,fontOpacity:this.color.alpha,fontSize:t,fontKerning:"normal"};return this.setFont(i,this.fontStyle),i}onEnable(){var t;super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&this.uiObject.addAfterUpdate(()=>{this.setShadowComponentOwner(this.uiObject),this.markDirty()}),setTimeout(()=>this.markDirty(),10),(t=this.canvas)==null||t.registerEventReceiver(this)}onDisable(){var t;super.onDisable(),(t=this.canvas)==null||t.unregisterEventReceiver(this)}getAlignment(t){switch(t.flexDirection="column",this.alignment){case 0:case 3:case 6:t.textAlign="left";break;case 1:case 4:case 7:t.textAlign="center";break;case 2:case 5:case 8:t.textAlign="right";break}switch(this.alignment){default:case 0:case 1:case 2:t.alignItems="start";break;case 3:case 4:case 5:t.alignItems="center";break;case 6:case 7:case 8:t.alignItems="end";break}return t}feedText(t,i){var n,o,r;if(Nr&&console.log("feedText",this.uiObject,t,i),!!this.uiObject)if(this._textMeshUi||(this._textMeshUi=[]),this.uiObject.children.length=0,!i||t.length===0)this.uiObject.textContent=t;else{let l=this.getNextTag(t);if(l){if(l.startIndex>0){for(let d=this.uiObject.children.length-1;d>=0;d--){const u=this.uiObject.children[d];u.isUI&&(this.uiObject.remove(u),u.clear())}const h=new _m({textContent:t.substring(0,l.startIndex),color:"inherit"});this.uiObject.add(h)}}else{this.uiObject.textContent="",this.setOptions({textContent:t});return}const c=[];for(;l;){const h=this.getNextTag(t,l.endIndex),d={fontFamily:(n=this.uiObject)==null?void 0:n.get("fontFamily"),color:"inherit",textContent:""};if(h){d.textContent=this.getText(t,l,h),this.handleTag(l,d,c);const u=new _m(d);(o=this.uiObject)==null||o.add(u)}else{d.textContent=t.substring(l.endIndex),this.handleTag(l,d,c);const u=new _m(d);(r=this.uiObject)==null||r.add(u)}l=h}}}handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const t=[],i=this.canvas,n={renderOnTop:i.renderOnTop,depthWrite:i.depthWrite,doubleSided:i.doubleSided};for(;;){let o=!1;if(this._textMeshUi)for(let r=0;r<this._textMeshUi.length;r++){if(t[r]===!0)continue;o=!0;const l=this._textMeshUi[r];l.textContent&&(Mu(l,n),t[r]=!0)}if(!o)break;yield}}handleTag(t,i,n){if(!t.isEndTag){if(t.type.includes("color")){const o=new w0(t,{color:i.color});if(n.push(o),t.type.length>6){const r=parseInt("0x"+t.type.substring(7));i.color=r}else i.color=new ae(1,1,1)}else if(t.type=="b"){this.setFont(i,1);const o=new w0(t,{fontWeight:700});n.push(o)}else if(t.type=="i"){this.setFont(i,2);const o=new w0(t,{fontStyle:"italic"});n.push(o)}}}getText(t,i,n){return t.substring(i.endIndex,n.startIndex)}getNextTag(t,i=0){const n=t.indexOf("<",i),o=t.indexOf(">",n);if(n>=0&&o>=0){const r=t.substring(n+1,o);return{type:r,startIndex:n,endIndex:o+1,isEndTag:r.startsWith("/")}}return null}setFont(t,i){if(!this.font)return;const n=this.font,o=this.getFamilyNameWithCorrectSuffix(n,i);Nr&&console.log("Selected font family:"+o);let r=fv.getFontFamily(o);switch(r||(r=fv.addFontFamily(o)),t.fontFamily=r,i){default:case 0:t.fontWeight=400,t.fontStyle="normal";break;case 1:t.fontWeight=700,t.fontStyle="normal";break;case 2:t.fontWeight=400,t.fontStyle="italic";break;case 3:t.fontStyle="italic",t.fontWeight=400}let l=r.getVariant(t.fontWeight,t.fontStyle);if(!l){let c=o;c!=null&&c.endsWith("-msdf.json")||(c+="-msdf.json");let h=o;h!=null&&h.endsWith(".png")||(h+=".png"),l=r.addVariant(t.fontWeight,t.fontStyle,c,h),l?.addEventListener("ready",()=>{this.markDirty()})}}getFamilyNameWithCorrectSuffix(t,i){var n;const o=t.lastIndexOf("-");if(o<0)return t;const r=(n=t.substring(o+1))==null?void 0:n.toLowerCase();if(QT.includes(r))return Nr&&console.warn("Unsupported font style: "+r),t;const l=t.lastIndexOf("/");let c=t;l>=0&&(c=c.substring(l+1));const h=c[0]===c[0].toUpperCase(),d=t.substring(0,o);switch(Nr&&console.log("Select font: ",t,Kx[i],c,h,d),i){case 0:return h?d+"-Regular":d+"-regular";case 1:return h?d+"-Bold":d+"-bold";case 2:return h?d+"-Italic":d+"-italic";case 3:return h?d+"-BoldItalic":d+"-bolditalic";default:return t}}}Vn([m()],Vt.prototype,"alignment",2),Vn([m()],Vt.prototype,"verticalOverflow",2),Vn([m()],Vt.prototype,"horizontalOverflow",2),Vn([m()],Vt.prototype,"lineSpacing",2),Vn([m()],Vt.prototype,"supportRichText",2),Vn([m(URL)],Vt.prototype,"font",2),Vn([m()],Vt.prototype,"fontStyle",2),Vn([m()],Vt.prototype,"text",1),Vn([m()],Vt.prototype,"fontSize",1);class w0{constructor(t,i){a(this,"tag"),a(this,"previousValues"),this.tag=t,this.previousValues=i}}const QT=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class Wr{constructor(t){a(this,"id"),a(this,"content",""),a(this,"font",[]),a(this,"pointSize",144),a(this,"width"),a(this,"height"),a(this,"depth"),a(this,"wrapMode"),a(this,"horizontalAlignment"),a(this,"verticalAlignment"),a(this,"material"),this.id=t}static getId(){return this.global_id++}setDepth(t){return this.depth=t,this}setPointSize(t){return this.pointSize=t,this}setHorizontalAlignment(t){return this.horizontalAlignment=t,this}setVerticalAlignment(t){return this.verticalAlignment=t,this}writeTo(t,i){var n;i.beginBlock(`def Preliminary_Text "${this.id}"`,"(",!1),i.appendLine('prepend apiSchemas = ["MaterialBindingAPI"]'),i.closeBlock(")"),i.beginBlock(),this.content&&i.appendLine(`string content = "${this.content}"`),(!this.font||this.font.length<=0)&&(this.font||(this.font=[]),(n=this.font)==null||n.push("sans-serif"));const o=this.font.map(r=>`"${r}"`).join(", ");i.appendLine(`string[] font = [ ${o} ]`),i.appendLine(`double pointSize = ${this.pointSize}`),typeof this.width=="number"&&i.appendLine(`double width = ${this.width}`),typeof this.height=="number"&&i.appendLine(`double height = ${this.height}`),typeof this.depth=="number"&&i.appendLine(`double depth = ${this.depth}`),this.wrapMode&&i.appendLine(`token wrapMode = "${this.wrapMode}"`),this.horizontalAlignment&&i.appendLine(`token horizontalAlignment = "${this.horizontalAlignment}"`),this.verticalAlignment&&i.appendLine(`token verticalAlignment = "${this.verticalAlignment}"`),this.material!==void 0&&i.appendLine(`rel material:binding = </StageRoot/Materials/${Zf(this.material)}>`),i.closeBlock()}}a(Wr,"global_id",0);class x0{static singleLine(t,i,n){const o=new Wr("text_"+Wr.getId());return o.content=t,i&&(o.pointSize=i),n&&(o.depth=n),o}static multiLine(t,i,n,o,r,l){const c=new Wr("text_"+Wr.getId());return c.content=t,c.width=i,c.height=n,c.horizontalAlignment=o,c.verticalAlignment=r,l!==void 0&&(c.wrapMode=l),c}}const YT=new ne().makeRotationY(Math.PI),ZT=new ne().makeScale(-1,1,-1);class pp{get extensionName(){return"text"}exportText(t,i,n){const o=O.getComponent(t,Vt);if(!o)return;const r=O.getComponent(t,Wt);let l=100,c=100;r&&(l=r.width,c=r.height);const h=YT.clone();r&&h.premultiply(ZT),i.setMatrix(h);const d=o.color.clone();i.material=new ni({color:d,emissive:d}),i.addEventListener("serialize",(u,p)=>{let g=o.text;g=g.replace(/\r/g,""),g=g.replace(/\n/g,"\\n");const y=x0.multiLine(g,l,c,"center","bottom","flowing");this.setTextAlignment(y,o.alignment),this.setOverflow(y,o),i.material&&(y.material=i.material),y.pointSize=this.convertToTextSize(o.fontSize),y.depth=.001,y.writeTo(void 0,u)})}convertToTextSize(t){return 1/.0502*144*t}setOverflow(t,i){i.horizontalOverflow?t.wrapMode="singleLine":t.wrapMode="flowing"}setTextAlignment(t,i){switch(i){case pt.LowerLeft:case pt.MiddleLeft:case pt.UpperLeft:t.horizontalAlignment="left";break;case pt.LowerCenter:case pt.MiddleCenter:case pt.UpperCenter:t.horizontalAlignment="center";break;case pt.LowerRight:case pt.MiddleRight:case pt.UpperRight:t.horizontalAlignment="right";break}switch(i){case pt.LowerLeft:case pt.LowerCenter:case pt.LowerRight:t.verticalAlignment="bottom";break;case pt.MiddleLeft:case pt.MiddleCenter:case pt.MiddleRight:t.verticalAlignment="middle";break;case pt.UpperLeft:case pt.UpperCenter:case pt.UpperRight:t.verticalAlignment="top";break}}}var KT=Object.defineProperty,JT=Object.getOwnPropertyDescriptor,at=(s,t,i,n)=>{for(var o=n>1?void 0:n?JT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&KT(t,i,o),o};const Jx=C("debuguilayout");class Vr{constructor(){a(this,"left",0),a(this,"right",0),a(this,"top",0),a(this,"bottom",0)}get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}at([m()],Vr.prototype,"left",2),at([m()],Vr.prototype,"right",2),at([m()],Vr.prototype,"top",2),at([m()],Vr.prototype,"bottom",2);class Li extends A{constructor(){super(...arguments),a(this,"_rectTransform",null),a(this,"_needsUpdate",!1),a(this,"childAlignment",0),a(this,"reverseArrangement",!1),a(this,"spacing",0),a(this,"padding"),a(this,"minWidth",0),a(this,"minHeight",0),a(this,"flexibleHeight",0),a(this,"flexibleWidth",0),a(this,"preferredHeight",0),a(this,"preferredWidth",0)}get rectTransform(){return this._rectTransform}onParentRectTransformChanged(t){this._needsUpdate=!0}get isDirty(){return this._needsUpdate}get isLayoutGroup(){return!0}updateLayout(){this._rectTransform&&(Jx&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}start(){this._needsUpdate=!0}onEnable(){Jx&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(Wt);const t=this.gameObject.getComponentInParent(Et);t&&t.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const t=this.gameObject.getComponentInParent(Et);t&&t.unregisterLayoutGroup(this)}set m_Spacing(t){t!==this.spacing&&(this._needsUpdate=!0,this.spacing=t)}get m_Spacing(){return this.spacing}}at([m()],Li.prototype,"childAlignment",2),at([m()],Li.prototype,"reverseArrangement",2),at([m()],Li.prototype,"spacing",2),at([m(Vr)],Li.prototype,"padding",2),at([m()],Li.prototype,"minWidth",2),at([m()],Li.prototype,"minHeight",2),at([m()],Li.prototype,"flexibleHeight",2),at([m()],Li.prototype,"flexibleWidth",2),at([m()],Li.prototype,"preferredHeight",2),at([m()],Li.prototype,"preferredWidth",2);class zo extends Li{constructor(){super(...arguments),a(this,"childControlHeight",!0),a(this,"childControlWidth",!0),a(this,"childForceExpandHeight",!1),a(this,"childForceExpandWidth",!1),a(this,"childScaleHeight",!1),a(this,"childScaleWidth",!1)}onCalculateLayout(t){var i;const n=this.primaryAxis,o=t.width;let r=o;const l=t.height;let c=l;r-=this.padding.horizontal,c-=this.padding.vertical,n==="x"?this.padding.horizontal:this.padding.vertical;const h=n==="x",d=h?"y":"x",u=h?this.childControlWidth:this.childControlHeight,p=h?this.childControlHeight:this.childControlWidth,g=h?this.childForceExpandWidth:this.childForceExpandHeight,y=h?this.childForceExpandHeight:this.childForceExpandWidth,f=h?c:r,v=h?o:l,b=.5*(h?this.childAlignment%3:Math.floor(this.childAlignment/3));let w=0;h?w+=this.padding.left:w+=this.padding.top;let _=0,S=0;for(let D=0;D<this.gameObject.children.length;D++){const U=this.gameObject.children[D],B=O.getComponent(U,Wt);B!=null&&B.activeAndEnabled&&(S+=1,h?_+=B.width:_+=B.height)}let R=0;const M=this.spacing*(S-1);if(g||u){let D=0;h?D=r-=M:D=c-=M,S>0&&(R=D/S)}let T=0;T+=this.padding.left,T-=this.padding.right,b!==0&&(w=v-_,w*=b,w-=M*b,h?(w-=this.padding.right*b,w+=this.padding.left*(1-b),w<this.padding.left&&(w=this.padding.left)):(w-=this.padding.bottom*b,w+=this.padding.top*(1-b),w<this.padding.top&&(w=this.padding.top)));let L=1;for(let D=0;D<this.gameObject.children.length;D++){const U=this.gameObject.children[D],B=O.getComponent(U,Wt);if(B!=null&&B.activeAndEnabled){(i=B.pivot)==null||i.set(.5,.5),B.anchorMin.set(0,1),B.anchorMax.set(0,1);const Q=o*.5+T*.5;B.anchoredPosition.x!==Q&&(B.anchoredPosition.x=Q);const $=l*-.5;B.anchoredPosition.y!==$&&(B.anchoredPosition.y=$),y&&p&&B.sizeDelta[d]!==f&&(B.sizeDelta[d]=f),g&&u&&B.sizeDelta[n]!==R&&(B.sizeDelta[n]=R);const E=h?B.width:B.height,z=E*.5;if(w+=z,g){const ie=R*L-R*.5;ie>w&&(w=ie-R*.5+E+this.padding.left,w-=z)}let H=w;n==="y"&&(H=-H),B.anchoredPosition[n]!==H&&(B.anchoredPosition[n]=H),w+=z,w+=this.spacing,L+=1}}}}at([m()],zo.prototype,"childControlHeight",2),at([m()],zo.prototype,"childControlWidth",2),at([m()],zo.prototype,"childForceExpandHeight",2),at([m()],zo.prototype,"childForceExpandWidth",2),at([m()],zo.prototype,"childScaleHeight",2),at([m()],zo.prototype,"childScaleWidth",2);class S0 extends zo{get primaryAxis(){return"y"}}class C0 extends zo{get primaryAxis(){return"x"}}class O0 extends Li{onCalculateLayout(){}}var eE=Object.defineProperty,tE=Object.getOwnPropertyDescriptor,rn=(s,t,i,n)=>{for(var o=n>1?void 0:n?tE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&eE(t,i,o),o},e1=(s=>(s[s.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",s[s.ScreenSpaceCamera=1]="ScreenSpaceCamera",s[s.WorldSpace=2]="WorldSpace",s[s.Undefined=-1]="Undefined",s))(e1||{});const P0=C("debuguilayout"),t1=class extends Nc{constructor(){super(...arguments),a(this,"_renderOnTop"),a(this,"_depthWrite",!1),a(this,"_doubleSided",!0),a(this,"_castShadows",!1),a(this,"_receiveShadows",!1),a(this,"_renderMode",-1),a(this,"_rootCanvas"),a(this,"_scaleFactor",1),a(this,"worldCamera"),a(this,"planeDistance",-1),a(this,"_boundRenderSettingsChanged",this.onRenderSettingsChanged.bind(this)),a(this,"previousParent",null),a(this,"_lastMatrixWorld",null),a(this,"_rectTransforms",[]),a(this,"_layoutGroups",new Map),a(this,"_receivers",[]),a(this,"onBeforeRenderRoutine",()=>{var s,t,i,n;if(this.previousParent=this.gameObject.parent,((s=this.context.xr)!=null&&s.isVR||(t=this.context.xr)!=null&&t.isPassThrough)&&this.screenspace){this.gameObject.visible=!1,this.gameObject.removeFromParent();return}this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),(i=this.shadowComponent)==null||i.updateMatrixWorld(!0),(n=this.shadowComponent)==null||n.updateWorldMatrix(!0,!0),this.invokeBeforeRenderEvents(),si.ensureUpdateMeshUI(yv,this.context))}),a(this,"onAfterRenderRoutine",()=>{var s,t,i,n,o;if(((s=this.context.xr)!=null&&s.isVR||(t=this.context.xr)!=null&&t.isPassThrough)&&this.screenspace){(i=this.previousParent)==null||i.add(this.gameObject);return}if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){if(this.screenspace){const c=this.context.mainCamera;c?.add(this.gameObject)}else this.previousParent.add(this.gameObject);const r=this.context.renderer.autoClear,l=this.context.renderer.autoClearColor;this.context.renderer.autoClear=!1,this.context.renderer.autoClearColor=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),(n=this.shadowComponent)==null||n.updateMatrixWorld(!0),this.invokeBeforeRenderEvents(),si.ensureUpdateMeshUI(yv,this.context,!0),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=r,this.context.renderer.autoClearColor=l,this.previousParent.add(this.gameObject)}(o=this._lastMatrixWorld)==null||o.copy(this.gameObject.matrixWorld)}),a(this,"_updateRenderSettingsRoutine"),a(this,"_activeRenderMode",-1),a(this,"_lastWidth",-1),a(this,"_lastHeight",-1)}get isCanvas(){return!0}get screenspace(){return this.renderMode!==2}set renderOnTop(s){s!==this._renderOnTop&&(this._renderOnTop=s,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop!==void 0?this._renderOnTop:!!(this.screenspace&&this._renderMode===0)}set depthWrite(s){this._depthWrite!==s&&(this._depthWrite=s,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}set doubleSided(s){this._doubleSided!==s&&(this._doubleSided=s,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}set castShadows(s){this._castShadows!==s&&(this._castShadows=s,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}set receiveShadows(s){this._receiveShadows!==s&&(this._receiveShadows=s,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}get renderMode(){return this._renderMode}set renderMode(s){this._renderMode!==s&&(this._renderMode=s,this.onRenderSettingsChanged())}set rootCanvas(s){this._rootCanvas instanceof t1||(this._rootCanvas=s)}get rootCanvas(){return this._rootCanvas}get scaleFactor(){return this._scaleFactor}set scaleFactor(s){this._scaleFactor=s}awake(){var s;this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,P0&&console.log("Canvas.Awake()",((s=this.previousParent)==null?void 0:s.name)+"/"+this.gameObject.name),super.awake()}start(){this.applyRenderSettings()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new ne,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 s=this.context.pre_render_callbacks.indexOf(this.onBeforeRenderRoutine);s!==-1&&this.context.pre_render_callbacks.splice(s,1);const t=this.context.post_render_callbacks.indexOf(this.onAfterRenderRoutine);t!==-1&&this.context.post_render_callbacks.splice(t,1)}registerTransform(s){this._rectTransforms.push(s)}unregisterTransform(s){const t=this._rectTransforms.indexOf(s);t!==-1&&this._rectTransforms.splice(t,1)}registerLayoutGroup(s){const t=s.gameObject;this._layoutGroups.set(t,s)}unregisterLayoutGroup(s){const t=s.gameObject;this._layoutGroups.delete(t)}registerEventReceiver(s){this._receivers.push(s)}unregisterEventReceiver(s){const t=this._receivers.indexOf(s);t!==-1&&this._receivers.splice(t,1)}async onEnterXR(s){this.screenspace?(s.xr.isVR||s.xr.isPassThrough)&&(this.gameObject.visible=!1):(this.gameObject.visible=!1,await Kl(1).then(()=>{this.gameObject.visible=!0}))}onLeaveXR(s){this.screenspace&&(s.xr.isVR||s.xr.isPassThrough)&&(this.gameObject.visible=!0)}invokeBeforeRenderEvents(){var s;for(const t of this._receivers)(s=t.onBeforeCanvasRender)==null||s.call(t,this)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new ne);const s=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);P0&&s&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);const t=!1;for(const i of this._rectTransforms){s&&i.markDirty();let n=this._layoutGroups.get(i.gameObject);i.isDirty&&!n&&(n=i.gameObject.getComponentInParent(Li)),(i.isDirty||n!=null&&n.isDirty)&&(P0&&!t&&console.log("CANVAS UPDATE ### "+i.name+" ##################################### "+this.context.time.frame),n?.updateLayout(),i.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),Me.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),Mu(this.shadowComponent,this);for(const s of O.getComponentsInChildren(this.gameObject,rs))Mu(s.shadowComponent,this)}}onUpdateRenderMode(s=!1){if(!s&&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=W.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(Wt);let r=!1;o.sizeDelta.x!==this.context.domWidth&&(r=!0),o.sizeDelta.y!==this.context.domHeight&&(r=!0);const l=t.fieldOfView*Math.PI/180,c=2*Math.tan(l/2)*Math.abs(n);this.gameObject.scale.x=c/this.context.domHeight,this.gameObject.scale.y=c/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}}};let Et=t1;rn([m()],Et.prototype,"renderOnTop",1),rn([m()],Et.prototype,"depthWrite",1),rn([m()],Et.prototype,"doubleSided",1),rn([m()],Et.prototype,"castShadows",1),rn([m()],Et.prototype,"receiveShadows",1),rn([m()],Et.prototype,"renderMode",1),rn([m(Et)],Et.prototype,"rootCanvas",1),rn([m()],Et.prototype,"scaleFactor",1),rn([m(Oe)],Et.prototype,"worldCamera",2),rn([m()],Et.prototype,"planeDistance",2);var iE=Object.defineProperty,sE=Object.getOwnPropertyDescriptor,k0=(s,t,i,n)=>{for(var o=n>1?void 0:n?sE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&iE(t,i,o),o};class Uo extends A{constructor(){super(...arguments),a(this,"_alpha",1),a(this,"interactable",!0),a(this,"blocksRaycasts",!0),a(this,"_isDirty",!1),a(this,"_buffer",[])}get alpha(){return this._alpha}set alpha(t){t!==this._alpha&&(this._alpha=t,this.markDirty())}get isCanvasGroup(){return!0}markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),Me.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}applyChangesNow(){this._buffer.length=0;for(const t of O.getComponentsInChildren(this.gameObject,rs,this._buffer)){const i=t;i.setAlphaFactor&&i.setAlphaFactor(this._alpha)}}}k0([m()],Uo.prototype,"alpha",1),k0([m()],Uo.prototype,"interactable",2),k0([m()],Uo.prototype,"blocksRaycasts",2);class M0{get extensionName(){return"tmui"}onExportObject(t,i,n){const o=O.getComponent(t,Et);if(o&&o.enabled&&o.renderMode===e1.WorldSpace){const r=new pp,l=O.getComponent(t,Wt),c=O.getComponent(t,Uo),h=new Array;if(l){if(!O.isActiveSelf(t)){const p=O.isActiveSelf(t);O.setActive(t,!0),l.onEnable(),l.updateTransform(),h.push(()=>{l.onDisable(),O.setActive(t,p)})}t.traverse(p=>{if(!O.isActiveInHierarchy(p)){const g=O.isActiveSelf(p);O.setActive(p,!0);const y=O.getComponent(p,rs);y&&(y.onEnable(),h.push(()=>{y.onDisable()}));const f=O.getComponent(p,Wt);f&&(f.onEnable(),f.updateTransform(),f.onApplyTransform(),h.push(()=>{f.onDisable()}));const v=O.getComponent(p,Vt);v&&(v.onEnable(),h.push(()=>{v.onDisable()})),h.push(()=>{O.setActive(p,g)})}}),l.width,l.height;const d=Yt.createEmpty(),u=l.shadowComponent;if(i.add(d),u){const p=u.matrix;d.setMatrix(p);const g=new Map,y=new Map;g.set(u,d),y.set(u,c?c.alpha:1),u.traverse(f=>{if(f===u)return;const v=Yt.createEmpty();v.setMatrix(f.matrix);const b=f.parent,w=!!b&&typeof b.textContent=="string"&&b.textContent.length>0;let _=y.get(b)||1;const S=O.getComponent(f,Uo);if(S&&(_*=S.alpha),f instanceof Y&&w){const M=f[Ki];M?r.exportText(M.gameObject,v,n):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",f)}if(f instanceof Y&&!w){const M=f.geometry.clone();M.scale(1,1,-1),this.flipWindingOrder(M),v.geometry=M;const T=new ae,L=f.material.opacity;T.copy(f.material.color),v.material=new Re({color:T,opacity:L*_,map:f.material.map,transparent:!0})}g.set(f,v),y.set(f,_);const R=g.get(b);if(!R){console.error("Error when exporting UI: shadow component parent not found!",f,f.parent);return}R.add(v)})}}for(const d of h)d()}}flipWindingOrder(t){const i=t.index.array;for(let n=0,o=i.length/3;n<o;n++){const r=i[n*3];i[n*3]=i[n*3+2],i[n*3+2]=r}t.index.needsUpdate=!0}}const yh=C("debugusdz");function nE(s,t){var i;const n=[],o=O.getComponentsInChildren(s,Pt),r=O.getComponentsInChildren(s,zt),l=new Array,c=new Array;if(t.injectImplicitBehaviours)for(const h of o){if(!h||!h.runtimeAnimatorController||!h.enabled)continue;const d=h.runtimeAnimatorController.activeState;if(!d||!d.motion||!d.motion.clip||((i=d.motion.clip.tracks)==null?void 0:i.length)<1||l.includes(h))continue;const u=new Fr;u.animator=h,u.stateName=d.name,u.trigger="start",u.name="PlayAnimationOnClick_implicitAtStart_"+u.stateName;const p=new I;O.addComponent(p,u),c.push(p),l.push(h),s.add(p)}else for(const h of o){if(!h||!h.runtimeAnimatorController||!h.enabled)continue;yh&&console.log(h);const d=[];for(const u of h.runtimeAnimatorController.enumerateActions()){yh&&console.log(u);const p=u.getClip();d.includes(p)||d.push(p)}n.push({root:h.gameObject,clips:d})}if(t.injectImplicitBehaviours)for(const h of r){if(!h||!h.clip||!h.enabled||!h.playAutomatically||l.includes(h))continue;const d=new Fr;d.animation=h,d.stateName=h.clip.name,d.trigger="start",d.name="PlayAnimationOnClick_implicitAtStart_"+d.stateName;const u=new I;O.addComponent(u,d),c.push(u),l.push(h),s.add(u)}else for(const h of r){yh&&console.log(h);const d=[];for(const u of h.animations)d.includes(u)||d.push(u);n.push({root:h.gameObject,clips:d})}yh&&n?.length>0&&console.log("USDZ Animation Clips without behaviours",n);for(const h of n)for(const d of h.clips)t.registerAnimation(h.root,d);return c}function oE(s,t){const i=O.getComponentsInChildren(s,Ne),n=O.getComponentsInChildren(s,Io),o=new Array,r=new Array;yh&&console.log({audioSources:i,playAudioOnClicks:n});for(const l of n){if(!l.target)continue;const c=i.indexOf(l.target);c>-1&&i.splice(c,1)}for(const l of i){if(!l||!l.clip||l.volume<=0||o.includes(l))continue;const c=new Io;c.target=l,c.name="PlayAudioOnClick_implicitAtStart_",c.trigger="start";const h=new I;O.addComponent(h,c),console.log("implicit PlayAudioOnStart",h,c),r.push(h),o.push(l),s.add(h)}return r}function rE(s){return new Nt("DisableAtStart",Rt.sceneStartTrigger(),ve.fadeAction(s,0,!1))}function i1(s,t){const i=s.domElement.shadowRoot.querySelector("link[rel='ar']");if(i)return i;const n=document.createElement("div");n.classList.add("menu"),n.classList.add("quicklook-menu"),n.style.display="none",n.style.visibility="hidden";const o=document.createElement("button");o.id="open-in-ar",t?(o.innerText="View in AR",o.title="View this scene in AR. The scene will be exported to USDZ and opened with Apple's QuickLook."):(o.innerText="View in AR",o.title="Download this scene for AR. Open the downloaded USDZ file to view it in AR using Apple's QuickLook."),n.appendChild(o);const r=document.createElement("a");r.id="needle-usdz-link",r.style.display="none",r.rel="ar",r.href="",r.target="_blank",n.appendChild(r);const l=document.createElement("img");return l.id="button",r.appendChild(l),s.domElement.shadowRoot.appendChild(n),r}var aE=Object.defineProperty,lE=Object.getOwnPropertyDescriptor,At=(s,t,i,n)=>{for(var o=n>1?void 0:n?lE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&aE(t,i,o),o};const Di=C("debugusdz"),cE=C("debugusdzpruning");class Hr{constructor(){a(this,"callToAction"),a(this,"checkoutTitle"),a(this,"checkoutSubtitle"),a(this,"callToActionURL")}}At([m()],Hr.prototype,"callToAction",2),At([m()],Hr.prototype,"checkoutTitle",2),At([m()],Hr.prototype,"checkoutSubtitle",2),At([m()],Hr.prototype,"callToActionURL",2);var mp;const R0=(mp=class extends A{constructor(){super(...arguments),a(this,"objectToExport"),a(this,"autoExportAnimations",!0),a(this,"autoExportAudioSources",!0),a(this,"exportFileName"),a(this,"customUsdzFile"),a(this,"customBranding"),a(this,"anchoringType","plane"),a(this,"maxTextureSize",2048),a(this,"planeAnchoringAlignment","horizontal"),a(this,"interactive",!0),a(this,"physics",!0),a(this,"allowCreateQuicklookButton",!0),a(this,"quickLookCompatible",!0),a(this,"extensions",[]),a(this,"link"),a(this,"button"),a(this,"onClickedOpenInARElement",s=>{s.preventDefault(),this.exportAndOpen()}),a(this,"_currentExportTasks",new Map),a(this,"_previousTimeScale",1),a(this,"lastCallback"),a(this,"_rootSessionRootWasAppliedTo",null),a(this,"_rootPositionBeforeExport",new x),a(this,"_rootRotationBeforeExport",new V),a(this,"_rootScaleBeforeExport",new x)}start(){var s,t,i;Di&&(console.log("USDZExporter",this),console.log("Debug USDZ Mode. Press 'T' to export"),window.addEventListener("keydown",n=>{switch(n.key){case"t":this.exportAndOpen();break}})),this.objectToExport||(this.objectToExport=this.gameObject),!((t=(s=this.objectToExport)==null?void 0:s.children)!=null&&t.length)&&!((i=this.objectToExport)!=null&&i.isMesh)&&(this.objectToExport=this.context.scene)}onEnable(){var s;const t=X.supportsQuickLookAR(),i=X.isiOS()||X.isiPad();!this.button&&(Di||t||i)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=i1(this.context,t),this.link.addEventListener("message",this.lastCallback)),Di&&De("USDZ Exporter enabled: "+this.name),(s=document.getElementById("open-in-ar"))==null||s.addEventListener("click",this.onClickedOpenInARElement),mc.registerExporter(this)}onDisable(){var s,t,i;(s=this.button)==null||s.remove(),(t=this.link)==null||t.removeEventListener("message",this.lastCallback),Di&&De("USDZ Exporter disabled: "+this.name),(i=document.getElementById("open-in-ar"))==null||i.removeEventListener("click",this.onClickedOpenInARElement),mc.unregisterExporter(this)}async exportAsync(){return this.exportAndOpen()}async exportAndOpen(){var s;let t=this.exportFileName??((s=this.objectToExport)==null?void 0:s.name)??this.name;if(t+="-"+fx(),vo()||(t!==""&&(t+="-"),t+="MadeWithNeedle"),this.link||(this.link=i1(this.context,X.supportsQuickLookAR())),this.customUsdzFile)return Di&&console.log("Exporting custom usdz",this.customUsdzFile),this.openInQuickLook(this.customUsdzFile,t),null;if(!this.objectToExport)return console.warn("No object to export",this),null;const i=await this.export(this.objectToExport);return i?(Di&&console.log("USDZ generation done. Downloading as "+t),this.openInQuickLook(i,t),i):(console.error("USDZ generation failed. Please report a bug",this),null)}async export(s){if(!s)return console.warn("No object to export"),null;const t=this._currentExportTasks.get(s);if(t)return t;const i=this.internalExport(s);return i instanceof Promise?(this._currentExportTasks.set(s,i),i.then(n=>(this._currentExportTasks.delete(s),n)).catch(n=>(this._currentExportTasks.delete(s),console.error("Error during USDZ export \u2013 please report a bug!",n),null))):i}async internalExport(s){ce.start("export-usdz",{onProgress:S=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:S}}))}}),ce.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),ce.report("export-usdz",{message:"Load progressive textures",autoStep:5}),ce.start("export-usdz-textures","export-usdz");const t=O.getComponentsInChildren(s,mi);for(const S of t)S&&S.enabled&&S.updateSprite(!0);const i=O.getComponentsInChildren(s,Ze),n=new Array;let o=0;for(const S of i){for(const R of S.sharedMeshes)if(R){const M=it.assignMeshLOD(R,0);M instanceof Promise&&n.push(new Promise((T,L)=>{M.then(()=>{o++,ce.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:o,totalSteps:n.length}),T()}).catch(D=>L(D))}))}for(const R of S.sharedMaterials)if(R){const M=it.assignTextureLOD(R,0);M instanceof Promise&&n.push(new Promise((T,L)=>{M.then(()=>{o++,ce.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:o,totalSteps:n.length}),T()}).catch(D=>L(D))}))}}Di&&De("Progressive Loading: "+n.length),await Promise.all(n),Di&&De("Progressive Loading: done"),ce.end("export-usdz-textures");const r=ci.Global.Mask;ci.Global.Set(Ys.AR);const l=new wx,c=new sp(this.quickLookCompatible);let h;const d=[];this.interactive&&(d.push(new f0),d.push(new da),globalThis.false&&O.getComponentsInChildren(s,ye).length>0&&(this.physics?(h=new y0,d.push(h)):F()&&console.warn("USDZExporter: Physics export is disabled, but there are active Rigidbody components in the scene. They will not be exported.")),d.push(new pp),d.push(new M0));const u=[c,...d,...this.extensions],p={self:this,exporter:l,extensions:u,object:s};ce.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,ce.report("export-usdz","auto export animations and audio sources");const g=new Array;this.autoExportAnimations&&g.push(...nE(s,c)),u.find(S=>S.extensionName==="Audio")&&this.autoExportAudioSources&&g.push(...oE(s)),l.debug=Di,l.pruneUnusedNodes=!cE;const y=nl.instance.objs.map(S=>S.batchedMesh);l.keepObject=S=>{let R=!0;const M=O.getComponent(S,Ze);return M&&!M.enabled&&(R=!1),R&&y.includes(S)&&(R=!1),R&&O.getComponentInParent(S,Ps)&&(R=!1),R&&O.getComponentInParent(S,Hs)&&(R=!1),Di&&!R&&console.log("USDZExporter: Discarding object",S),R},l.beforeWritingDocument=()=>{if(F()&&c&&h){const S=c.animatedRoots;for(const R of S){const M=O.getComponentsInChildren(R,ye).filter(L=>L.enabled),T=O.getComponents(R,di).filter(L=>L.enabled&&!L.isTrigger);(M.length>0||T.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.",R)}}};const f=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(S=>{S.visible||f.push(S)});const v=u.find(S=>S.extensionName==="Behaviour");this.interactive&&v&&f.length>0&&v.addBehavior(rE(f));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"),ce.report("export-usdz","Invoking exporter.parse");const w=await l.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:u,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:b}),_=new Blob([w],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,ce.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:p}));for(const S of g)O.destroy(S);return ci.Global.Set(r),ce.end("export-usdz"),_}openInQuickLook(s,t){const i=s instanceof Blob?URL.createObjectURL(s):s,n=this.buildQuicklookOverlay();Di&&console.log("QuickLook Overlay",n);const o=n.callToAction?encodeURIComponent(n.callToAction):"",r=n.checkoutTitle?encodeURIComponent(n.checkoutTitle):"",l=n.checkoutSubtitle?encodeURIComponent(n.checkoutSubtitle):"";this.link.href=i+`#callToAction=${o}&checkoutTitle=${r}&checkoutSubtitle=${l}&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(s,t){R0.save(s,t)}static save(s,t){const i=document.createElement("a");i.style.display="none",document.body.appendChild(i),typeof s=="string"?i.href=s:i.href=URL.createObjectURL(s),i.download=t,i.click(),i.remove()}quicklookCallback(s){if(s?.data=="_apple_ar_quicklook_button_tapped"){Di&&we("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");Di&&De("Quicklook url: "+n),n&&(vo()?globalThis.open(n,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",n))}}}}buildQuicklookOverlay(){var s,t,i,n,o,r;const l={};return this.customBranding&&Object.assign(l,this.customBranding),vo()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),l.callToAction="Close",l.checkoutTitle="\u{1F335} Made with Needle",l.checkoutSubtitle="_"),(((s=l.callToAction)==null?void 0:s.length)||((t=l.checkoutTitle)==null?void 0:t.length)||((i=l.checkoutSubtitle)==null?void 0:i.length))&&((n=l.callToAction)!=null&&n.length||(l.callToAction="\0"),(o=l.checkoutTitle)!=null&&o.length||(l.checkoutTitle="\0"),(r=l.checkoutSubtitle)!=null&&r.length||(l.checkoutSubtitle="\0")),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:l})),l}getARScaleAndTarget(){if(!this.objectToExport)return{scale:1,_invertForward:!1,target:this.gameObject,sessionRoot:null};const s=O.findObjectOfType(Je);let t=O.getComponentInParent(this.objectToExport,sn);t||(t=O.getComponentInChildren(this.objectToExport,sn));let i=1,n=!1;const o=this.objectToExport;return s?i=s.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:s,_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(s),t&&i.quaternion.multiply(R0.invertForwardQuaternion),i.updateMatrix(),i.updateMatrixWorld(!0),n&&o&&i.matrix.premultiply(o)}revertWebARSessionRoot(){if(!this.objectToExport||!this._rootSessionRootWasAppliedTo)return;const s=this._rootSessionRootWasAppliedTo;s.position.copy(this._rootPositionBeforeExport),s.quaternion.copy(this._rootRotationBeforeExport),s.scale.copy(this._rootScaleBeforeExport),s.updateMatrix(),s.updateMatrixWorld(!0),this._rootSessionRootWasAppliedTo=null}createQuicklookButton(){const s=zr.getOrCreate().createQuicklookButton();return s.parentNode||this.context.menu.appendChild(s),s}},a(mp,"invertForwardMatrix",new ne().makeRotationY(Math.PI)),a(mp,"invertForwardQuaternion",new V().setFromEuler(new Bt(0,Math.PI,0))),mp);let $e=R0;At([m(I)],$e.prototype,"objectToExport",2),At([m()],$e.prototype,"autoExportAnimations",2),At([m()],$e.prototype,"autoExportAudioSources",2),At([m()],$e.prototype,"exportFileName",2),At([m(URL)],$e.prototype,"customUsdzFile",2),At([m(Hr)],$e.prototype,"customBranding",2),At([m()],$e.prototype,"anchoringType",2),At([m()],$e.prototype,"maxTextureSize",2),At([m()],$e.prototype,"planeAnchoringAlignment",2),At([m()],$e.prototype,"interactive",2),At([m()],$e.prototype,"physics",2),At([m()],$e.prototype,"allowCreateQuicklookButton",2),At([m()],$e.prototype,"quickLookCompatible",2);var hE=Object.defineProperty,dE=Object.getOwnPropertyDescriptor,T0=(s,t,i,n)=>{for(var o=n>1?void 0:n?dE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&hE(t,i,o),o};class Sl extends A{constructor(){super(...arguments),a(this,"_fog")}get fog(){return this._fog||(this._fog=new Vy(0,0,50)),this._fog}get mode(){return 1}set near(t){this.fog.near=t}get near(){return this.fog.near}set far(t){this.fog.far=t}get far(){return this.fog.far}set color(t){this.fog.color.copy(t)}get color(){return this.fog.color}onEnable(){this.scene.fog=this.fog}onDisable(){this.scene.fog===this._fog&&(this.scene.fog=null)}}T0([m()],Sl.prototype,"near",1),T0([m()],Sl.prototype,"far",1),T0([m(ae)],Sl.prototype,"color",1);var uE=Object.defineProperty,pE=Object.getOwnPropertyDescriptor,E0=(s,t,i,n)=>{for(var o=n>1?void 0:n?pE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&uE(t,i,o),o};class $r extends A{constructor(){super(...arguments),a(this,"objectBounds",!1),a(this,"color"),a(this,"isGizmo",!0),a(this,"_gizmoObject",null),a(this,"_boxHelper",null)}onEnable(){this.isGizmo&&!xc||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new mC(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=gg(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),Me.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(var t;this._boxHelper;)(t=this._boxHelper)==null||t.update(),yield}}E0([m()],$r.prototype,"objectBounds",2),E0([m(ae)],$r.prototype,"color",2),E0([m()],$r.prototype,"isGizmo",2);var mE=Object.defineProperty,gE=Object.getOwnPropertyDescriptor,A0=(s,t,i,n)=>{for(var o=n>1?void 0:n?gE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&mE(t,i,o),o};class Cl extends A{constructor(){super(...arguments),a(this,"isGizmo",!1),a(this,"color0"),a(this,"color1"),a(this,"gridHelper"),a(this,"size"),a(this,"divisions"),a(this,"offset")}onEnable(){if(this.isGizmo&&!xc)return;const t=this.size,i=this.divisions;this.gridHelper||(this.gridHelper=new sm(t,i,this.color0??new ae(.4,.4,.4),this.color1??new ae(.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)}}A0([m()],Cl.prototype,"isGizmo",2),A0([m(ae)],Cl.prototype,"color0",2),A0([m(ae)],Cl.prototype,"color1",2);var fE=Object.defineProperty,yE=Object.getOwnPropertyDescriptor,I0=(s,t,i,n)=>{for(var o=n>1?void 0:n?yE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&fE(t,i,o),o};class j0 extends A{constructor(){super(...arguments),a(this,"connectedBody"),a(this,"_rigidBody",null)}get rigidBody(){return this._rigidBody}onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(ye)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.activeAndEnabled&&this.createJoint(this.rigidBody,this.connectedBody)}}I0([m(ye)],j0.prototype,"connectedBody",2);class L0 extends j0{createJoint(t,i){var n;(n=this.context.physics.engine)==null||n.addFixedJoint(t,i)}}class vh extends j0{constructor(){super(...arguments),a(this,"anchor"),a(this,"axis")}createJoint(t,i){var n;this.axis&&this.anchor&&((n=this.context.physics.engine)==null||n.addHingeJoint(t,i,this.anchor,this.axis))}}I0([m(x)],vh.prototype,"anchor",2),I0([m(x)],vh.prototype,"axis",2);var vE=Object.defineProperty,bE=Object.getOwnPropertyDescriptor,an=(s,t,i,n)=>{for(var o=n>1?void 0:n?bE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&vE(t,i,o),o};function D0(s){return s*Math.PI/180}const s1=300,No=C("debuglights");class gi extends A{constructor(){super(...arguments),a(this,"type",0),a(this,"range",1),a(this,"spotAngle",1),a(this,"innerSpotAngle",1),a(this,"_color",new ae(16777215)),a(this,"_shadowNearPlane",.1),a(this,"_shadowBias",0),a(this,"_shadowNormalBias",0),a(this,"_overrideShadowBiasSettings",!1),a(this,"_shadows",1),a(this,"lightmapBakeType",4),a(this,"_intensity",-1),a(this,"_shadowDistance"),a(this,"shadowWidth"),a(this,"shadowHeight"),a(this,"_shadowResolution"),a(this,"light"),a(this,"_webXRStartedListener"),a(this,"_webXREndedListener"),a(this,"_webARRoot")}set color(t){this._color=t,this.light!==void 0&&(this.light.color=t)}get color(){return this.light?this.light.color:this._color}set shadowNearPlane(t){var i,n;if(t!==this._shadowNearPlane&&(this._shadowNearPlane=t,((n=(i=this.light)==null?void 0:i.shadow)==null?void 0:n.camera)!==void 0)){const o=this.light.shadow.camera;o.near=t}}get shadowNearPlane(){return this._shadowNearPlane}set shadowBias(t){var i,n;t!==this._shadowBias&&(this._shadowBias=t,((n=(i=this.light)==null?void 0:i.shadow)==null?void 0:n.bias)!==void 0&&(this.light.shadow.bias=t,this.light.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}set shadowNormalBias(t){var i,n;t!==this._shadowNormalBias&&(this._shadowNormalBias=t,((n=(i=this.light)==null?void 0:i.shadow)==null?void 0:n.normalBias)!==void 0&&(this.light.shadow.normalBias=t,this.light.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}set shadows(t){this._shadows=t,this.light&&(this.light.castShadow=t!==0,this.updateShadowSoftHard())}get shadows(){return this._shadows}set intensity(t){var i;if(this._intensity=t,this.light){let n=1;if(this.context.isInXR&&this._webARRoot){const o=(i=this._webARRoot)==null?void 0:i.arScale;typeof o=="number"&&o>0&&(n/=o)}this.light.intensity=t*n}No&&console.log("Set light intensity to "+this._intensity,t,this)}get intensity(){return this._intensity}get shadowDistance(){const t=this.light;return t!=null&&t.shadow?t.shadow.camera.far:-1}set shadowDistance(t){this._shadowDistance=t;const i=this.light;if(i!=null&&i.shadow){const n=i.shadow.camera;n.far=t,n.updateProjectionMatrix()}}get shadowResolution(){const t=this.light;return t!=null&&t.shadow?t.shadow.mapSize.x:-1}set shadowResolution(t){if(t===this._shadowResolution)return;this._shadowResolution=t;const i=this.light;i!=null&&i.shadow&&(i.shadow.mapSize.set(t,t),i.shadow.needsUpdate=!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}getWorldPosition(t){return this.light?this.type===1?this.light.getWorldPosition(t).multiplyScalar(1):this.light.getWorldPosition(t):t}awake(){this.color=new ae(this.color??16777215),No&&console.log(this.name,this)}onEnable(){No&&console.log("ENABLE LIGHT",this.name),this.createLight(),!this.isBaked&&(this.light&&(this.light.visible=!0,this.light.intensity=this._intensity,No&&console.log("Set light intensity to "+this.light.intensity,this.name),this.selfIsLight||this.light.parent!==this.gameObject&&this.gameObject.add(this.light)),this.type===1&&this.startCoroutine(this.updateMainLightRoutine(),Me.LateUpdate))}onDisable(){No&&console.log("DISABLE LIGHT",this.name),this.light&&(this.selfIsLight?this.light.intensity=0:this.light.visible=!1)}onEnterXR(t){this._webARRoot=O.getComponentInParent(this.gameObject,sn)??void 0}onLeaveXR(t){}createLight(){const t=this.selfIsLight;if(t&&!this.light)switch(this.light=this.gameObject,this.light.name=this.name,this._intensity=this.light.intensity,this.type){case 1:this.setDirectionalLight(this.light);break}else if(!this.light)switch(this.type){case 1:const i=new nm(this.color,this.intensity*Math.PI);if(i.position.set(0,0,-s1*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(i.target),lr(i.target,0,0,0),this.light=i,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),No){const l=new fC(this.light,.2,this.color);this.context.scene.add(l)}break;case 0:const n=new gC(this.color,this.intensity*Math.PI,this.range,D0(this.spotAngle/2),1-D0(this.innerSpotAngle/2)/D0(this.spotAngle/2),2);n.position.set(0,0,0),n.rotation.set(0,0,0),this.light=n;const o=n.target;n.add(o),o.position.set(0,0,this.range),o.rotation.set(0,0,0);break;case 2:const r=new Hy(this.color,this.intensity*Math.PI,this.range);this.light=r;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),No&&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 i=this.light.shadow.camera;if(i.near=this.shadowNearPlane,this._shadowDistance!==void 0&&typeof this._shadowDistance=="number"?i.far=this._shadowDistance:i.far=s1*Math.abs(this.gameObject.scale.z),this.gameObject.scale.set(1,1,1),this.shadowWidth!==void 0)i.left=-this.shadowWidth/2,i.right=this.shadowWidth/2;else{const n=this.gameObject.scale.x;i.left*=n,i.right*=n}if(this.shadowHeight!==void 0)i.top=this.shadowHeight/2,i.bottom=-this.shadowHeight/2;else{const n=this.gameObject.scale.y;i.top*=n,i.bottom*=n}this.light.shadow.needsUpdate=!0,No&&this.context.scene.add(new yC(i))}this.isBaked?this.light.removeFromParent():t||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}}updateShadowSoftHard(){this.light&&this.light.shadow&&(this.shadows===2||(this.light.shadow.radius=1,this.light.shadow.blurSamples=1))}setDirectionalLight(t){t.add(t.target),t.target.position.set(0,0,-1)}}a(gi,"allowChangingRendererShadowMapType",!0),an([m()],gi.prototype,"type",2),an([m(ae)],gi.prototype,"color",1),an([m()],gi.prototype,"shadowNearPlane",1),an([m()],gi.prototype,"shadowBias",1),an([m()],gi.prototype,"shadowNormalBias",1),an([m()],gi.prototype,"shadows",1),an([m()],gi.prototype,"lightmapBakeType",2),an([m()],gi.prototype,"intensity",1),an([m()],gi.prototype,"shadowDistance",1),an([m()],gi.prototype,"shadowResolution",1),new x(0,0,0);var _E=Object.defineProperty,wE=Object.getOwnPropertyDescriptor,bh=(s,t,i,n)=>{for(var o=n>1?void 0:n?wE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&_E(t,i,o),o};const B0=C("debuglods"),xE=C("nolods");class Ol{constructor(){a(this,"screenRelativeTransitionHeight"),a(this,"distance"),a(this,"renderers")}}bh([m()],Ol.prototype,"screenRelativeTransitionHeight",2),bh([m()],Ol.prototype,"distance",2),bh([m(Ze)],Ol.prototype,"renderers",2);class SE{constructor(t){a(this,"model"),this.model=t}get renderers(){return this.model.renderers}}class _h extends A{constructor(){super(...arguments),a(this,"fadeMode",0),a(this,"localReferencePoint"),a(this,"lodCount",0),a(this,"size",0),a(this,"animateCrossFading",!1),a(this,"lodModels"),a(this,"_lods",[]),a(this,"_settings",[]),a(this,"_lodsHandler"),a(this,"_distanceFactor",1)}start(){if(B0&&console.log("LODGROUP",this.name,this.lodModels,this),!xE&&!this._lodsHandler&&this.gameObject&&this.lodModels&&Array.isArray(this.lodModels)){const t=[];for(const n of this.lodModels){const o=new SE(n);this._lods.push(o);for(const r of o.renderers)t.includes(r)||t.push(r)}this._lodsHandler=new Array;for(let n=0;n<t.length;n++){const o=new vC;this._lodsHandler.push(o),this.gameObject.add(o)}const i=new I;i.name="Cull "+this.name;for(let n=0;n<t.length;n++){const o=t[n],r=this._lodsHandler[n],l=o.gameObject;B0&&console.log(n,l.name);for(const c of this._lods){const h=c.model.distance;let d=null;if(c.renderers.includes(o)?d=l:d=i,d.type==="Group"){console.warn(`LODGroup ${this.name}: Group or MultiMaterial object's are not supported as LOD object: ${d.name}`);continue}B0&&console.log("LEVEL",d.name,h),r.autoUpdate=!1,this.onAddLodLevel(r,d,c.model.distance)}}}}onAfterRender(){if(!this.gameObject||!this._lodsHandler)return;const t=this.context.mainCamera;if(t)for(const i of this._lodsHandler){i.update(t);const n=i.getCurrentLevel(),o=i.levels[n];i.layers.mask=o.object.layers.mask}}onAddLodLevel(t,i,n){if(i===this.gameObject){console.warn("LODGroup component must be on parent object and not mesh directly at the moment",i.name,i);return}t.addLevel(i,n*this._distanceFactor,.01);const o={lod:t,levelIndex:t.levels.length-1,distance:n};this._settings.push(o)}distanceFactor(t){if(t!==this._distanceFactor){this._distanceFactor=t;for(const i of this._settings){const n=i.lod.levels[i.levelIndex];n.distance=i.distance*t}}}}bh([m(x)],_h.prototype,"localReferencePoint",2),bh([m(Ol)],_h.prototype,"lodModels",2);var CE=Object.defineProperty,OE=Object.getOwnPropertyDescriptor,PE=(s,t,i,n)=>{for(var o=n>1?void 0:n?OE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&CE(t,i,o),o};const gp=C("debugnestedgltf");class fp extends A{constructor(){super(...arguments),a(this,"filePath"),a(this,"loadAssetInParent",!0),a(this,"_isLoadingOrDoneLoading",!1)}listenToProgress(t){var i;(i=this.filePath)==null||i.beginListenDownload(t)}preload(){var t;(t=this.filePath)==null||t.preload()}async start(){var t,i,n,o,r;if(this._isLoadingOrDoneLoading)return;gp&&console.log(this,this.guid);const l=this.gameObject.parent;if(l){this._isLoadingOrDoneLoading=!0;const c=new Ds;c.idProvider=new Dt(this.hash(this.guid)),c.parent=this.loadAssetInParent!==!1?l:this.gameObject,this.gameObject.updateMatrix();const h=this.gameObject.matrix;gp&&console.log("Load nested:",((t=this.filePath)==null?void 0:t.url)??this.filePath,this.gameObject.position);const d=await((n=(i=this.filePath)==null?void 0:i.instantiate)==null?void 0:n.call(this.filePath,c));gp&&console.log("Nested loaded:",((o=this.filePath)==null?void 0:o.url)??this.filePath,d),d&&this.loadAssetInParent!==!1&&(d.matrixAutoUpdate=!1,d.matrix.identity(),d.applyMatrix4(h),d.matrixAutoUpdate=!0,d.layers.disableAll(),d.layers.set(this.layer),this.dispatchEvent(new CustomEvent("loaded",{detail:{instance:d,assetReference:this.filePath}}))),gp&&console.log("Nested loading done:",((r=this.filePath)==null?void 0:r.url)??this.filePath,d)}}onDestroy(){var t;(t=this.filePath)==null||t.unload()}hash(t){let i=0;for(let n=0;n<t.length;n++)i=t.charCodeAt(n)+((i<<5)-i);return i}}PE([m(le)],fp.prototype,"filePath",2);var kE=Object.defineProperty,ME=Object.getOwnPropertyDescriptor,F0=(s,t,i,n)=>{for(var o=n>1?void 0:n?ME(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&kE(t,i,o),o};const RE=C("debugnet"),z0=class extends A{constructor(){super(...arguments),a(this,"url",null),a(this,"urlParameterName",null),a(this,"localhost",null)}awake(){RE&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let s=this.url?z0.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const i=C(this.urlParameterName);i&&typeof i=="string"&&(s=i)}if(!s)return null;const t=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(s);return t!=null&&t.groups?t?.groups.socket_prefix?s:"wss://"+t?.groups.url:null}static GetUrl(s,t){let i=s;const n=z0.IsLocalNetwork()&&t;if(n&&(i=t),s!=null&&s.startsWith("/")){const o=n?i:window.location.origin;o!=null&&o.endsWith("/")&&s.startsWith("/")&&(s=s.substring(1)),i=o+s}return i}static IsLocalNetwork(s=window.location.hostname){return Gt(s)}};let Pl=z0;F0([m()],Pl.prototype,"url",2),F0([m()],Pl.prototype,"urlParameterName",2),F0([m()],Pl.prototype,"localhost",2);var TE=Object.defineProperty,EE=Object.getOwnPropertyDescriptor,yp=(s,t,i,n)=>{for(var o=n>1?void 0:n?EE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&TE(t,i,o),o};class qr extends A{constructor(){super(...arguments),a(this,"referenceSpace"),a(this,"from"),a(this,"affectPosition",!1),a(this,"affectRotation",!1),a(this,"alignLookDirection",!1),a(this,"levelLookDirection",!1),a(this,"levelPosition",!1),a(this,"positionOffset",new x(0,0,0)),a(this,"rotationOffset",new x(0,0,0)),a(this,"offset",new x(0,0,0))}update(){if(!this.from)return;var t=te(this.from),i=Ce(this.from);this.offset.copy(this.positionOffset);const n=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(n),t.add(this.offset),this.levelPosition&&this.referenceSpace){const c=new nr(this.gameObject.up,0),h=te(this.referenceSpace);c.setFromNormalAndCoplanarPoint(this.gameObject.up,h);const d=new x(0,0,0);c.projectPoint(t,d),t.copy(d)}this.affectPosition&&ht(this.gameObject,t);const o=new Bt(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),r=new V().setFromEuler(o);this.affectRotation&&Hi(this.gameObject,i.multiply(r));const l=new x;this.from.getWorldDirection(l).multiplyScalar(50),this.levelLookDirection&&(l.y=0),this.alignLookDirection&&this.gameObject.lookAt(l)}}yp([m(O)],qr.prototype,"referenceSpace",2),yp([m(O)],qr.prototype,"from",2),yp([m(x)],qr.prototype,"positionOffset",2),yp([m(x)],qr.prototype,"rotationOffset",2);var AE=Object.defineProperty,IE=Object.getOwnPropertyDescriptor,Wo=(s,t,i,n)=>{for(var o=n>1?void 0:n?IE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&AE(t,i,o),o};class fi{constructor(t=0,i=0){a(this,"time",0),a(this,"value",0),a(this,"inTangent",1/0),a(this,"inWeight"),a(this,"outTangent",1/0),a(this,"outWeight"),a(this,"weightedMode"),this.time=t,this.value=i}}Wo([m()],fi.prototype,"time",2),Wo([m()],fi.prototype,"value",2),Wo([m()],fi.prototype,"inTangent",2),Wo([m()],fi.prototype,"inWeight",2),Wo([m()],fi.prototype,"outTangent",2),Wo([m()],fi.prototype,"outWeight",2),Wo([m()],fi.prototype,"weightedMode",2);const wh=class{constructor(){a(this,"keys",[])}static linearFromTo(s,t,i){const n=new wh,o=new fi;o.time=0,o.value=s;const r=new fi;return r.time=i,r.value=t,n.keys.push(o,r),n}static constant(s){const t=new wh,i=new fi;return i.time=0,i.value=s,t.keys.push(i),t}clone(){var s;const t=new wh;return t.keys=((s=this.keys)==null?void 0:s.map(i=>{const n=new fi;return n.time=i.time,n.value=i.value,n.inTangent=i.inTangent,n.inWeight=i.inWeight,n.outTangent=i.outTangent,n.outWeight=i.outWeight,n.weightedMode=i.weightedMode,n}))||[],t}get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(s){if(!this.keys||this.keys.length==0)return 0;if(this.keys.length===1)return this.keys[0].value;if(this.keys[0].time>=s)return this.keys[0].value;for(let t=0;t<this.keys.length;t++){const i=this.keys[t];if(i.time<=s)if(t+1<this.keys.length){const n=this.keys[t+1];if(n.time<s)continue;return!isFinite(i.outTangent)||!isFinite(n.inTangent)?i.value:wh.interpolateValue(s,i,n)}else return i.value}return this.keys[this.keys.length-1].value}static interpolateValue(s,t,i){const n=t.time,o=t.value,r=t.outTangent,l=i.time,c=i.value,h=i.inTangent,d=l-n,u=d*d,p=u*d,g=((r+h)*d-2*(c-o))/p,y=(3*(c-o)-(h+2*r)*d)/u,f=r,v=o,b=s-n,w=b*b,_=w*b;return g*_+y*w+f*b+v}};let kl=wh;Wo([m(fi)],kl.prototype,"keys",2);var jE=Object.defineProperty,LE=Object.getOwnPropertyDescriptor,P=(s,t,i,n)=>{for(var o=n>1?void 0:n?LE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&jE(t,i,o),o};const vp=C("debugparticles");var Hn=(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))(Hn||{});class Gr{constructor(){a(this,"alphaKeys",[]),a(this,"colorKeys",[])}get duration(){return 1}evaluate(t,i){let n,o=0,r=null,l=0;for(let c=0;c<this.alphaKeys.length;c++){const h=this.alphaKeys[c];(h.time<t||!n)&&(n=h,o=c)}for(let c=0;c<this.colorKeys.length;c++){const h=this.colorKeys[c];(h.time<t||!r)&&(r=h,l=c)}if(r)if(l+1<this.colorKeys.length){const c=this.colorKeys[l+1],h=W.remap(t,r.time,c.time,0,1);i.r=W.lerp(r.color.r,c.color.r,h),i.g=W.lerp(r.color.g,c.color.g,h),i.b=W.lerp(r.color.b,c.color.b,h)}else i.r=r.color.r,i.g=r.color.g,i.b=r.color.b;if(n)if(o+1<this.alphaKeys.length){const c=this.alphaKeys[o+1],h=W.remap(t,n.time,c.time,0,1);i.alpha=W.lerp(n.alpha,c.alpha,h)}else i.alpha=n.alpha;return i}}P([m()],Gr.prototype,"alphaKeys",2),P([m()],Gr.prototype,"colorKeys",2);var xh=(s=>(s[s.Local=0]="Local",s[s.World=1]="World",s[s.Custom=2]="Custom",s))(xh||{}),bp=(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))(bp||{});const Sh=class{constructor(){a(this,"mode","Constant"),a(this,"constant"),a(this,"constantMin"),a(this,"constantMax"),a(this,"curve"),a(this,"curveMin"),a(this,"curveMax"),a(this,"curveMultiplier")}static constant(s){const t=new Sh;return t.setConstant(s),t}static betweenTwoConstants(s,t){const i=new Sh;return i.setMinMaxConstant(s,t),i}static curve(s,t=1){const i=new Sh;return i.setCurve(s,t),i}setConstant(s){this.mode=0,this.constant=s}setMinMaxConstant(s,t){this.mode=3,this.constantMin=s,this.constantMax=t}setCurve(s,t=1){this.mode=1,this.curve=s,this.curveMultiplier=t}clone(){var s,t,i;const n=new Sh;return n.mode=this.mode,n.constant=this.constant,n.constantMin=this.constantMin,n.constantMax=this.constantMax,n.curve=(s=this.curve)==null?void 0:s.clone(),n.curveMin=(t=this.curveMin)==null?void 0:t.clone(),n.curveMax=(i=this.curveMax)==null?void 0:i.clone(),n.curveMultiplier=this.curveMultiplier,n}evaluate(s,t){const i=t===void 0?Math.random():t;switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return s=W.clamp01(s),this.curve.evaluate(s)*this.curveMultiplier;case 2:case"TwoCurves":const n=s*this.curveMin.duration,o=s*this.curveMax.duration;return W.lerp(this.curveMin.evaluate(n),this.curveMax.evaluate(o),i%1)*this.curveMultiplier;case 3:case"TwoConstants":return W.lerp(this.constantMin,this.constantMax,i%1);default:this.curveMax.evaluate(s)*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(s){if(!s)return 0;let t=Number.MIN_VALUE;for(let i=0;i<s.keys.length;i++){const n=s.keys[i];n.value>t&&(t=n.value)}return t}};let Z=Sh;P([m()],Z.prototype,"mode",2),P([m()],Z.prototype,"constant",2),P([m()],Z.prototype,"constantMin",2),P([m()],Z.prototype,"constantMax",2),P([m(kl)],Z.prototype,"curve",2),P([m(kl)],Z.prototype,"curveMin",2),P([m(kl)],Z.prototype,"curveMax",2),P([m()],Z.prototype,"curveMultiplier",2);var _p;const It=(_p=class{constructor(){a(this,"mode",0),a(this,"color"),a(this,"colorMin"),a(this,"colorMax"),a(this,"gradient"),a(this,"gradientMin"),a(this,"gradientMax")}static constant(s){const t=new It;return t.constant(s),t}static betweenTwoColors(s,t){const i=new It;return i.betweenTwoColors(s,t),i}constant(s){return this.mode=0,this.color=s,this}betweenTwoColors(s,t){return this.mode=2,this.colorMin=s,this.colorMax=t,this}evaluate(s,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(s,It._temp),It._temp;case 2:case"TwoColors":return It._temp.lerpColors(this.colorMin,this.colorMax,i);case 3:case"TwoGradients":return this.gradientMin.evaluate(s,It._temp),this.gradientMax.evaluate(s,It._temp2),It._temp.lerp(It._temp2,i);case 4:case"RandomColor":const n=Math.random();return this.gradientMin.evaluate(s,It._temp),this.gradientMax.evaluate(s,It._temp2),It._temp.lerp(It._temp2,n)}return It._temp.set(16777215),It._temp.alpha=1,It._temp}},a(_p,"_temp",new xe(0,0,0,1)),a(_p,"_temp2",new xe(0,0,0,1)),_p);let yi=It;P([m()],yi.prototype,"mode",2),P([m(xe)],yi.prototype,"color",2),P([m(xe)],yi.prototype,"colorMin",2),P([m(xe)],yi.prototype,"colorMax",2),P([m(Gr)],yi.prototype,"gradient",2),P([m(Gr)],yi.prototype,"gradientMin",2),P([m(Gr)],yi.prototype,"gradientMax",2);var U0=(s=>(s[s.Hierarchy=0]="Hierarchy",s[s.Local=1]="Local",s[s.Shape=2]="Shape",s))(U0||{});class Ht{constructor(){a(this,"cullingMode"),a(this,"duration"),a(this,"emitterVelocityMode"),a(this,"flipRotation"),a(this,"gravityModifier"),a(this,"gravityModifierMultiplier"),a(this,"loop"),a(this,"maxParticles"),a(this,"playOnAwake"),a(this,"prewarm"),a(this,"ringBufferLoopRange"),a(this,"ringBufferMode"),a(this,"scalingMode"),a(this,"simulationSpace"),a(this,"simulationSpeed"),a(this,"startColor"),a(this,"startDelay"),a(this,"startDelayMultiplier"),a(this,"startLifetime"),a(this,"startLifetimeMultiplier"),a(this,"startRotation"),a(this,"startRotationMultiplier"),a(this,"startRotation3D"),a(this,"startRotationX"),a(this,"startRotationXMultiplier"),a(this,"startRotationY"),a(this,"startRotationYMultiplier"),a(this,"startRotationZ"),a(this,"startRotationZMultiplier"),a(this,"startSize"),a(this,"startSize3D"),a(this,"startSizeMultiplier"),a(this,"startSizeX"),a(this,"startSizeXMultiplier"),a(this,"startSizeY"),a(this,"startSizeYMultiplier"),a(this,"startSizeZ"),a(this,"startSizeZMultiplier"),a(this,"startSpeed"),a(this,"startSpeedMultiplier"),a(this,"stopAction"),a(this,"useUnscaledTime")}}P([m(Z)],Ht.prototype,"gravityModifier",2),P([m(yi)],Ht.prototype,"startColor",2),P([m(Z)],Ht.prototype,"startDelay",2),P([m(Z)],Ht.prototype,"startLifetime",2),P([m(Z)],Ht.prototype,"startRotation",2),P([m(Z)],Ht.prototype,"startRotationX",2),P([m(Z)],Ht.prototype,"startRotationY",2),P([m(Z)],Ht.prototype,"startRotationZ",2),P([m(Z)],Ht.prototype,"startSize",2),P([m(Z)],Ht.prototype,"startSizeX",2),P([m(Z)],Ht.prototype,"startSizeY",2),P([m(Z)],Ht.prototype,"startSizeZ",2),P([m(Z)],Ht.prototype,"startSpeed",2);class wp{constructor(){a(this,"cycleCount"),a(this,"maxCount"),a(this,"minCount"),a(this,"probability"),a(this,"repeatInterval"),a(this,"time"),a(this,"count"),a(this,"_performed",0)}reset(){this._performed=0}run(t){if(t<=this.time)return 0;let i=0;if(this.cycleCount===0||this._performed<this.cycleCount){const n=this.time+this.repeatInterval*this._performed;if(t>=n&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:i=this.count.constant;break;case 3:i=W.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:i=this.count.curve.evaluate(Math.random());break;case 2:const o=Math.random();i=W.lerp(this.count.curveMin.evaluate(o),this.count.curveMax.evaluate(o),Math.random());break}}return i}}class $n{constructor(){a(this,"enabled"),a(this,"bursts"),a(this,"rateOverTime"),a(this,"rateOverTimeMultiplier"),a(this,"rateOverDistance"),a(this,"rateOverDistanceMultiplier"),a(this,"system")}get burstCount(){var t;return((t=this.bursts)==null?void 0:t.length)??0}reset(){var t;(t=this.bursts)==null||t.forEach(i=>i.reset())}getBurst(){let t=0;if(this.burstCount>0)for(let i=0;i<this.burstCount;i++){const n=this.bursts[i];this.system.main.loop&&n.time>=this.system.time&&n.reset(),t+=Math.round(n.run(this.system.time))}return t}}P([m()],$n.prototype,"enabled",2),P([m()],$n.prototype,"bursts",2),P([m(Z)],$n.prototype,"rateOverTime",2),P([m()],$n.prototype,"rateOverTimeMultiplier",2),P([m(Z)],$n.prototype,"rateOverDistance",2),P([m()],$n.prototype,"rateOverDistanceMultiplier",2);class xp{constructor(){a(this,"enabled"),a(this,"color")}}P([m(yi)],xp.prototype,"color",2);class Xr{constructor(){a(this,"enabled"),a(this,"separateAxes"),a(this,"size"),a(this,"sizeMultiplier"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier"),a(this,"_time",0),a(this,"_temp",new x)}evaluate(t,i,n){if(i||(i=this._temp),!this.enabled)return i.x=i.y=i.z=1,i;if(this.separateAxes)i.x=this.x.evaluate(t,n)*this.xMultiplier,i.y=this.y.evaluate(t,n)*this.yMultiplier,i.z=this.z.evaluate(t,n)*this.zMultiplier;else{const o=this.size.evaluate(t,n)*this.sizeMultiplier;i.x=o}return i}}P([m(Z)],Xr.prototype,"size",2),P([m(Z)],Xr.prototype,"x",2),P([m(Z)],Xr.prototype,"y",2),P([m(Z)],Xr.prototype,"z",2);var Sp;const Ch=(Sp=class{constructor(){a(this,"shapeType",5),a(this,"enabled",!0),a(this,"alignToDirection",!1),a(this,"angle",0),a(this,"arc",360),a(this,"arcSpread"),a(this,"arcSpeedMultiplier"),a(this,"arcMode"),a(this,"boxThickness"),a(this,"position"),a(this,"rotation"),a(this,"_rotation",new Bt),a(this,"scale"),a(this,"radius"),a(this,"radiusThickness"),a(this,"sphericalDirectionAmount"),a(this,"randomDirectionAmount"),a(this,"randomPositionAmount"),a(this,"meshShapeType"),a(this,"meshRenderer"),a(this,"_meshObj"),a(this,"_meshGeometry"),a(this,"system"),a(this,"_space"),a(this,"_worldSpaceMatrix",new ne),a(this,"_worldSpaceMatrixInverse",new ne),a(this,"_vector",new x(0,0,0)),a(this,"_temp",new x(0,0,0)),a(this,"_triangle",new bC),a(this,"_dir",new x),a(this,"_loopTime",0),a(this,"_loopDirection",1),vp&&console.log(this)}get type(){return bp[this.shapeType]}initialize(s){this.onInitialize(s),s.position.x=this._vector.x,s.position.y=this._vector.y,s.position.z=this._vector.z}toJSON(){return this}clone(){return new Ch}setMesh(s){this.meshRenderer=s,s?(this._meshObj=s.sharedMeshes[Math.floor(Math.random()*s.sharedMeshes.length)],this._meshGeometry=this._meshObj.geometry):(this._meshObj=void 0,this._meshGeometry=void 0)}update(s,t){}onUpdate(s,t,i,n){this.system=s,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(s){const t=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return t&&(this._rotation.x=W.toRadians(this.rotation.x),this._rotation.y=W.toRadians(this.rotation.y),this._rotation.z=W.toRadians(this.rotation.z),this._rotation.order="ZYX",s.applyEuler(this._rotation)),t}onInitialize(s){this._vector.set(0,0,0),s.mesh=void 0,s.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:vp&&q.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=s.mesh=this._meshObj,l=s.mesh_geometry=this._meshGeometry;if(r&&l)switch(this.meshShapeType){case 0:{const c=l.getAttribute("position"),h=Math.floor(Math.random()*c.count);this._vector.fromBufferAttribute(c,h),this._vector.applyMatrix4(r.matrixWorld),s.mesh_normal=h}break;case 1:break;case 2:{const c=l.index;if(c){let h=Math.random(),d=Math.random();h+d>1&&(h=1-h,d=1-d);const u=Math.floor(Math.random()*(c.count/3));let p=u*3,g=u*3+1,y=u*3+2;p=c.getX(p),g=c.getX(g),y=c.getX(y);const f=l.getAttribute("position");this._triangle.a.fromBufferAttribute(f,p),this._triangle.b.fromBufferAttribute(f,g),this._triangle.c.fromBufferAttribute(f,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),s.mesh_normal=u}}break}break;default:this._vector.set(0,0,0),F()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",bp[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)),vp&&q.DrawSphere(this._vector,.03,16711680,.5,!0)}getDirection(s,t){var i;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 n=t.x,o=t.y,r=t.z;this._dir.set(n,o,r),(i=this.system)!=null&&i.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;case 13:const l=s.mesh,c=s.mesh_geometry;if(l&&c)switch(this.meshShapeType){case 0:{const h=c.getAttribute("normal"),d=s.mesh_normal;this._dir.fromBufferAttribute(h,d)}break;case 1:break;case 2:{const h=c.index;if(h){const d=s.mesh_normal,u=h.getX(d*3),p=h.getX(d*3+1),g=h.getX(d*3+2),y=c.getAttribute("position"),f=G(),v=G(),b=G();f.fromBufferAttribute(y,u),v.fromBufferAttribute(y,p),b.fromBufferAttribute(y,g),f.sub(v),b.sub(v),f.cross(b),this._dir.copy(f).multiplyScalar(-1);const w=Ce(l);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),vp&&(q.DrawSphere(t,.01,8925952,.5,!0),q.DrawDirection(t,this._dir,8925952,.5,!0)),this._dir}randomizePosition(s,t){if(t<=0)return;const i=Ch._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,s.add(i)}randomizeDirection(s,t){if(t===0)return;const i=Ch._randomQuat,n=Ch._tempVec;n.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),i.setFromAxisAngle(n,t*Math.random()*Math.PI),s.applyQuaternion(i)}spherizeDirection(s,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),l=Math.cos(n),c=new x(o,r,l);s.lerp(c,t)}randomSpherePoint(s,t,i,n,o){const r=Math.random(),l=Math.random(),c=2*Math.PI*r*(n/360),h=Math.acos(2*l-1),d=W.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,u=s.x+this.scale.x*(-d*Math.sin(h)*Math.cos(c)),p=s.y+this.scale.y*(d*Math.sin(h)*Math.sin(c)),g=s.z+this.scale.z*(d*Math.cos(h));o.x=u,o.y=p,o.z=g}randomCirclePoint(s,t,i,n,o){const r=Math.random(),l=2*Math.PI*r*(n/360),c=W.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,h=s.x+this.scale.x*c*Math.cos(l),d=s.y+this.scale.y*c*Math.sin(l),u=s.z;o.x=h,o.y=d,o.z=u}randomConePoint(s,t,i,n,o,r,l){let c=0,h=0;switch(r){case 0:c=Math.random(),h=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:c=.5,h=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let d=2*Math.PI*c*(o/360);switch(r){case 2:case 1:d+=Math.PI+.5,d+=this._loopTime*Math.PI*2,d%=W.toRadians(o);break}const u=Math.acos(2*h-1),p=W.lerp(1,1-Math.pow(1-Math.random(),Math.PI),n)*i,g=s.x+-p*Math.sin(u)*Math.cos(d),y=s.y+p*Math.sin(u)*Math.sin(d),f=s.z;l.x=g*this.scale.x,l.y=y*this.scale.y,l.z=f*this.scale.z}},a(Sp,"_randomQuat",new V),a(Sp,"_tempVec",new x),Sp);let et=Ch;P([m()],et.prototype,"shapeType",2),P([m()],et.prototype,"enabled",2),P([m()],et.prototype,"alignToDirection",2),P([m()],et.prototype,"angle",2),P([m()],et.prototype,"arc",2),P([m()],et.prototype,"arcSpread",2),P([m()],et.prototype,"arcSpeedMultiplier",2),P([m()],et.prototype,"arcMode",2),P([m(x)],et.prototype,"boxThickness",2),P([m(x)],et.prototype,"position",2),P([m(x)],et.prototype,"rotation",2),P([m(x)],et.prototype,"scale",2),P([m()],et.prototype,"radius",2),P([m()],et.prototype,"radiusThickness",2),P([m()],et.prototype,"sphericalDirectionAmount",2),P([m()],et.prototype,"randomDirectionAmount",2),P([m()],et.prototype,"randomPositionAmount",2),P([m()],et.prototype,"meshShapeType",2),P([m(th)],et.prototype,"meshRenderer",2);class Pe{constructor(){a(this,"damping"),a(this,"enabled"),a(this,"frequency"),a(this,"octaveCount"),a(this,"octaveMultiplier"),a(this,"octaveScale"),a(this,"positionAmount"),a(this,"quality"),a(this,"remap"),a(this,"remapEnabled"),a(this,"remapMultiplier"),a(this,"remapX"),a(this,"remapXMultiplier"),a(this,"remapY"),a(this,"remapYMultiplier"),a(this,"remapZ"),a(this,"remapZMultiplier"),a(this,"scrollSpeedMultiplier"),a(this,"separateAxes"),a(this,"strengthMultiplier"),a(this,"strengthX"),a(this,"strengthXMultiplier"),a(this,"strengthY"),a(this,"strengthYMultiplier"),a(this,"strengthZ"),a(this,"strengthZMultiplier"),a(this,"_noise"),a(this,"_time",0),a(this,"_temp",new x)}update(t){this._time+=t.time.deltaTime*this.scrollSpeedMultiplier}apply(t,i,n,o,r,l){if(!this.enabled)return;this._noise||(this._noise=nO(()=>0));const c=this._temp.set(i.x,i.y,i.z).multiplyScalar(this.frequency),h=this._noise(c.x,c.y,c.z,this._time),d=this._noise(c.x,c.y,c.z,this._time+1e3*this.frequency),u=this._noise(c.x,c.y,c.z,this._time+2e3*this.frequency);this._temp.set(h,d,u).normalize();const p=r/l;let g=this.positionAmount.evaluate(p);this.separateAxes?(this._temp.x*=g*this.strengthXMultiplier,this._temp.y*=g*this.strengthYMultiplier,this._temp.z*=g*this.strengthZMultiplier):(this.strengthX&&(g*=this.strengthX.evaluate(p)*1.5),this._temp.multiplyScalar(g)),n.x+=this._temp.x,n.y+=this._temp.y,n.z+=this._temp.z}}P([m()],Pe.prototype,"damping",2),P([m()],Pe.prototype,"enabled",2),P([m()],Pe.prototype,"frequency",2),P([m()],Pe.prototype,"octaveCount",2),P([m()],Pe.prototype,"octaveMultiplier",2),P([m()],Pe.prototype,"octaveScale",2),P([m(Z)],Pe.prototype,"positionAmount",2),P([m()],Pe.prototype,"quality",2),P([m(Z)],Pe.prototype,"remap",2),P([m()],Pe.prototype,"remapEnabled",2),P([m()],Pe.prototype,"remapMultiplier",2),P([m(Z)],Pe.prototype,"remapX",2),P([m()],Pe.prototype,"remapXMultiplier",2),P([m(Z)],Pe.prototype,"remapY",2),P([m()],Pe.prototype,"remapYMultiplier",2),P([m(Z)],Pe.prototype,"remapZ",2),P([m()],Pe.prototype,"remapZMultiplier",2),P([m()],Pe.prototype,"scrollSpeedMultiplier",2),P([m()],Pe.prototype,"separateAxes",2),P([m()],Pe.prototype,"strengthMultiplier",2),P([m(Z)],Pe.prototype,"strengthX",2),P([m()],Pe.prototype,"strengthXMultiplier",2),P([m(Z)],Pe.prototype,"strengthY",2),P([m()],Pe.prototype,"strengthYMultiplier",2),P([m(Z)],Pe.prototype,"strengthZ",2),P([m()],Pe.prototype,"strengthZMultiplier",2);class qe{constructor(){a(this,"enabled"),a(this,"attachRibbonToTransform",!1),a(this,"colorOverLifetime"),a(this,"colorOverTrail"),a(this,"dieWithParticles",!0),a(this,"inheritParticleColor",!0),a(this,"lifetime"),a(this,"lifetimeMultiplier"),a(this,"minVertexDistance",.2),a(this,"mode",0),a(this,"ratio",1),a(this,"ribbonCount",1),a(this,"shadowBias",0),a(this,"sizeAffectsLifetime",!1),a(this,"sizeAffectsWidth",!1),a(this,"splitSubEmitterRibbons",!1),a(this,"textureMode",0),a(this,"widthOverTrail"),a(this,"widthOverTrailMultiplier"),a(this,"worldSpace",!1)}getWidth(t,i,n,o){const r=this.widthOverTrail.evaluate(n,o);return t*=r,t}getColor(t,i,n){const o=this.colorOverTrail.evaluate(n),r=this.colorOverLifetime.evaluate(i);t.x*=o.r*r.r,t.y*=o.g*r.g,t.z*=o.b*r.b,"alpha"in o&&"alpha"in r&&(t.w*=o.alpha*r.alpha)}}P([m()],qe.prototype,"enabled",2),P([m()],qe.prototype,"attachRibbonToTransform",2),P([m(yi)],qe.prototype,"colorOverLifetime",2),P([m(yi)],qe.prototype,"colorOverTrail",2),P([m()],qe.prototype,"dieWithParticles",2),P([m()],qe.prototype,"inheritParticleColor",2),P([m(Z)],qe.prototype,"lifetime",2),P([m()],qe.prototype,"lifetimeMultiplier",2),P([m()],qe.prototype,"minVertexDistance",2),P([m()],qe.prototype,"mode",2),P([m()],qe.prototype,"ratio",2),P([m()],qe.prototype,"ribbonCount",2),P([m()],qe.prototype,"shadowBias",2),P([m()],qe.prototype,"sizeAffectsLifetime",2),P([m()],qe.prototype,"sizeAffectsWidth",2),P([m()],qe.prototype,"splitSubEmitterRibbons",2),P([m()],qe.prototype,"textureMode",2),P([m(Z)],qe.prototype,"widthOverTrail",2),P([m()],qe.prototype,"widthOverTrailMultiplier",2),P([m()],qe.prototype,"worldSpace",2);class tt{constructor(){a(this,"enabled"),a(this,"space",0),a(this,"orbitalX"),a(this,"orbitalY"),a(this,"orbitalZ"),a(this,"orbitalXMultiplier"),a(this,"orbitalYMultiplier"),a(this,"orbitalZMultiplier"),a(this,"orbitalOffsetX"),a(this,"orbitalOffsetY"),a(this,"orbitalOffsetZ"),a(this,"speedModifier"),a(this,"speedModifierMultiplier"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier"),a(this,"_system"),a(this,"_temp",new x),a(this,"_temp2",new x),a(this,"_temp3",new x),a(this,"_hasOrbital",!1),a(this,"_index",0),a(this,"_orbitalMatrix",new ne)}update(t){this._system=t}init(t){this._index==0&&(t.debug=!0),this._index+=1,t.orbitx=this.orbitalX.evaluate(Math.random()),t.orbity=this.orbitalY.evaluate(Math.random()),t.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=t.orbitx!=0||t.orbity!=0||t.orbitz!=0}apply(t,i,n,o,r,l,c){var h;if(!this.enabled)return;const d=l/c,u=this.speedModifier.evaluate(d)*this.speedModifierMultiplier,p=this.x.evaluate(d),g=this.y.evaluate(d),y=this.z.evaluate(d);if(this._temp.set(-p,g,y),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&((h=this._system)==null?void 0:h.worldPos)){const f=this._temp2.set(n.x,n.y,n.z),v=this.orbitalXMultiplier,b=this.orbitalYMultiplier,w=this.orbitalZMultiplier,_=u*Math.PI*2*10,S=Math.cos(_*v),R=Math.sin(_*v),M=Math.cos(_*b),T=Math.sin(_*b),L=Math.cos(_*w),D=Math.sin(_*w),U=f.x*(M*L)+f.y*(M*D)+f.z*-T,B=f.x*(R*T*L-S*D)+f.y*(R*T*D+S*L)+f.z*(R*M),Q=f.x*(S*T*L+R*D)+f.y*(S*T*D-R*L)+f.z*(S*M),$=this._temp3.set(f.x-U,f.y-B,f.z-Q);$.normalize(),$.multiplyScalar(.2/r*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),o.x+=$.x,o.y+=$.y,o.z+=$.z}o.x+=this._temp.x,o.y+=this._temp.y,o.z+=this._temp.z,o.x*=u,o.y*=u,o.z*=u}}P([m()],tt.prototype,"enabled",2),P([m()],tt.prototype,"space",2),P([m(Z)],tt.prototype,"orbitalX",2),P([m(Z)],tt.prototype,"orbitalY",2),P([m(Z)],tt.prototype,"orbitalZ",2),P([m()],tt.prototype,"orbitalXMultiplier",2),P([m()],tt.prototype,"orbitalYMultiplier",2),P([m()],tt.prototype,"orbitalZMultiplier",2),P([m()],tt.prototype,"orbitalOffsetX",2),P([m()],tt.prototype,"orbitalOffsetY",2),P([m()],tt.prototype,"orbitalOffsetZ",2),P([m(Z)],tt.prototype,"speedModifier",2),P([m()],tt.prototype,"speedModifierMultiplier",2),P([m(Z)],tt.prototype,"x",2),P([m()],tt.prototype,"xMultiplier",2),P([m(Z)],tt.prototype,"y",2),P([m()],tt.prototype,"yMultiplier",2),P([m(Z)],tt.prototype,"z",2),P([m()],tt.prototype,"zMultiplier",2);class $t{constructor(){a(this,"animation"),a(this,"enabled"),a(this,"cycleCount"),a(this,"frameOverTime"),a(this,"frameOverTimeMultiplier"),a(this,"numTilesX"),a(this,"numTilesY"),a(this,"startFrame"),a(this,"startFrameMultiplier"),a(this,"rowMode"),a(this,"rowIndex"),a(this,"spriteCount"),a(this,"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(t){if(!this.sampleOnceAtStart())return this.getIndex(t)}getIndex(t){const i=this.numTilesX*this.numTilesY;t=t*this.cycleCount;let n=this.frameOverTime.evaluate(t%1);return n*=this.frameOverTimeMultiplier,n*=i,n=n%i,n=Math.floor(n),n}}P([m()],$t.prototype,"animation",2),P([m()],$t.prototype,"enabled",2),P([m()],$t.prototype,"cycleCount",2),P([m(Z)],$t.prototype,"frameOverTime",2),P([m()],$t.prototype,"frameOverTimeMultiplier",2),P([m()],$t.prototype,"numTilesX",2),P([m()],$t.prototype,"numTilesY",2),P([m(Z)],$t.prototype,"startFrame",2),P([m()],$t.prototype,"startFrameMultiplier",2),P([m()],$t.prototype,"rowMode",2),P([m()],$t.prototype,"rowIndex",2),P([m()],$t.prototype,"spriteCount",2),P([m()],$t.prototype,"timeMode",2);class Es{constructor(){a(this,"enabled"),a(this,"separateAxes"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier")}evaluate(t,i){return this.enabled?this.separateAxes?0:this.z.evaluate(t,i)*-1:0}}P([m()],Es.prototype,"enabled",2),P([m()],Es.prototype,"separateAxes",2),P([m(Z)],Es.prototype,"x",2),P([m()],Es.prototype,"xMultiplier",2),P([m(Z)],Es.prototype,"y",2),P([m()],Es.prototype,"yMultiplier",2),P([m(Z)],Es.prototype,"z",2),P([m()],Es.prototype,"zMultiplier",2);class is{constructor(){a(this,"enabled"),a(this,"range"),a(this,"separateAxes"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier")}evaluate(t,i){if(!this.enabled)return 0;if(!this.separateAxes){const n=W.lerp(this.range.x,this.range.y,i);return this.z.evaluate(n)*-1}return 0}}P([m()],is.prototype,"enabled",2),P([m()],is.prototype,"range",2),P([m()],is.prototype,"separateAxes",2),P([m(Z)],is.prototype,"x",2),P([m()],is.prototype,"xMultiplier",2),P([m(Z)],is.prototype,"y",2),P([m()],is.prototype,"yMultiplier",2),P([m(Z)],is.prototype,"z",2),P([m()],is.prototype,"zMultiplier",2);class mt{constructor(){a(this,"enabled"),a(this,"dampen"),a(this,"drag"),a(this,"dragMultiplier"),a(this,"limit"),a(this,"limitMultiplier"),a(this,"separateAxes"),a(this,"limitX"),a(this,"limitXMultiplier"),a(this,"limitY"),a(this,"limitYMultiplier"),a(this,"limitZ"),a(this,"limitZMultiplier"),a(this,"multiplyDragByParticleSize",!1),a(this,"multiplyDragByParticleVelocity",!1),a(this,"space"),a(this,"_temp",new x),a(this,"_temp2",new x)}apply(t,i,n,o,r,l,c){if(this.enabled){const h=this.limit.evaluate(r)*this.limitMultiplier;if(i.length()>h){this._temp.copy(i).normalize().multiplyScalar(h);const d=this.dampen*.5;i.x=W.lerp(i.x,this._temp.x,d),i.y=W.lerp(i.y,this._temp.y,d),i.z=W.lerp(i.z,this._temp.z,d),n.x=W.lerp(n.x,this._temp.x,d),n.y=W.lerp(n.y,this._temp.y,d),n.z=W.lerp(n.z,this._temp.z,d)}}}}P([m()],mt.prototype,"enabled",2),P([m()],mt.prototype,"dampen",2),P([m(Z)],mt.prototype,"drag",2),P([m()],mt.prototype,"dragMultiplier",2),P([m(Z)],mt.prototype,"limit",2),P([m()],mt.prototype,"limitMultiplier",2),P([m()],mt.prototype,"separateAxes",2),P([m(Z)],mt.prototype,"limitX",2),P([m()],mt.prototype,"limitXMultiplier",2),P([m(Z)],mt.prototype,"limitY",2),P([m()],mt.prototype,"limitYMultiplier",2),P([m(Z)],mt.prototype,"limitZ",2),P([m()],mt.prototype,"limitZMultiplier",2),P([m()],mt.prototype,"multiplyDragByParticleSize",2),P([m()],mt.prototype,"multiplyDragByParticleVelocity",2),P([m()],mt.prototype,"space",2);const n1=class{constructor(){a(this,"enabled"),a(this,"curve"),a(this,"curveMultiplier"),a(this,"mode"),a(this,"system"),a(this,"_temp",new x),a(this,"_firstUpdate",!0),a(this,"_frames",0)}clone(){var s;const t=new n1;return t.enabled=this.enabled,t.curve=(s=this.curve)==null?void 0:s.clone(),t.curveMultiplier=this.curveMultiplier,t.mode=this.mode,t}get _lastWorldPosition(){return this.system._iv_lastWorldPosition||(this.system._iv_lastWorldPosition=new x),this.system._iv_lastWorldPosition}get _velocity(){return this.system._iv_velocity||(this.system._iv_velocity=new x),this.system._iv_velocity}awake(s){this.system=s,this.reset()}reset(){this._firstUpdate=!0}update(s){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(s){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),s.x+=this._temp.x,s.y+=this._temp.y,s.z+=this._temp.z}}applyCurrent(s,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),s.x+=this._temp.x,s.y+=this._temp.y,s.z+=this._temp.z}}};let Qr=n1;P([m()],Qr.prototype,"enabled",2),P([m(Z)],Qr.prototype,"curve",2),P([m()],Qr.prototype,"curveMultiplier",2),P([m()],Qr.prototype,"mode",2);class vi{constructor(){a(this,"enabled"),a(this,"range"),a(this,"separateAxes"),a(this,"size"),a(this,"sizeMultiplier"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier")}evaluate(t,i,n,o){const r=t.length(),l=W.remap(r,this.range.x,this.range.y,0,1),c=this.size.evaluate(l,n);return o.x*=c,o.y*=c,o.z*=c,o}}P([m()],vi.prototype,"enabled",2),P([m(re)],vi.prototype,"range",2),P([m()],vi.prototype,"separateAxes",2),P([m(Z)],vi.prototype,"size",2),P([m()],vi.prototype,"sizeMultiplier",2),P([m(Z)],vi.prototype,"x",2),P([m()],vi.prototype,"xMultiplier",2),P([m(Z)],vi.prototype,"y",2),P([m()],vi.prototype,"yMultiplier",2),P([m(Z)],vi.prototype,"z",2),P([m()],vi.prototype,"zMultiplier",2);class Ml{constructor(){a(this,"enabled"),a(this,"range"),a(this,"color")}evaluate(t,i,n){const o=t.length(),r=W.remap(o,this.range.x,this.range.y,0,1),l=this.color.evaluate(r,i);n.x*=l.r,n.y*=l.g,n.z*=l.b,"alpha"in l&&(n.w*=l.alpha)}}P([m()],Ml.prototype,"enabled",2),P([m(re)],Ml.prototype,"range",2),P([m(yi)],Ml.prototype,"color",2),new x(1,1,1),new x(0,0,1);class N0{constructor(t,i,n,o){a(this,"type","NeedleParticleSubEmitter"),a(this,"emitterType"),a(this,"emitterProbability"),a(this,"q_",new V),a(this,"v_",new x),a(this,"v2_",new x),a(this,"_emitterMatrix",new bm),a(this,"_circularBuffer"),this.system=t,this.particleSystem=i,this.subSystem=n,this.subParticleSystem=o,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const r=1e3;this._circularBuffer=new Ci(()=>new bm,r)}clone(){throw new Error("Method not implemented.")}initialize(t){t.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===W0.Birth&&this.run(t)}update(t,i){this.run(t)}frameUpdate(t){}toJSON(){}reset(){}run(t){if(this.subSystem.currentParticles>=this.subSystem.main.maxParticles||!this.subParticleSystem||!t.emissionState||this.emitterProbability&&Math.random()>this.emitterProbability)return;const i=this.system.deltaTime;if(this.emitterType===W0.Death){let o=t.life;if(t[Rl]!==void 0&&(o=t[Rl]),!(t.age+i*1.2>=o))return;const r=this.subSystem.main.maxParticles-this.subSystem.currentParticles;t.emissionState.waitEmiting=r}const n=new bm;n.set(1,0,0,t.position.x,0,1,0,t.position.y,0,0,1,t.position.z,0,0,0,1),this.particleSystem.worldSpace||n.multiplyMatrices(this._emitterMatrix,n),this.subParticleSystem.emit(i,t.emissionState,n)}}var DE=Object.defineProperty,BE=Object.getOwnPropertyDescriptor,Ge=(s,t,i,n)=>{for(var o=n>1?void 0:n?BE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&DE(t,i,o),o};const Vo=C("debugparticles"),FE=C("noprogressive"),zE=C("debugprogressive");var W0=(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))(W0||{});class ss extends A{constructor(){super(...arguments),a(this,"renderMode"),a(this,"particleMaterial"),a(this,"trailMaterial"),a(this,"particleMesh"),a(this,"maxParticleSize"),a(this,"minParticleSize"),a(this,"velocityScale"),a(this,"cameraVelocityScale"),a(this,"lengthScale")}start(){if(this.maxParticleSize!==.5&&this.minParticleSize!==0&&F()){const t=`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(t)}}get transparent(){var t;return((t=this.particleMaterial)==null?void 0:t.transparent)??!1}getMaterial(t=!1){let i=t===!0&&this.trailMaterial?this.trailMaterial:this.particleMaterial;if(i){if(i.type==="MeshStandardMaterial"){Vo&&console.debug("ParticleSystemRenderer.getMaterial: MeshStandardMaterial detected, converting to MeshBasicMaterial. See https://github.com/Alchemist0823/three.quarks/issues/101"),"map"in i&&i.map&&(i.map.colorSpace=or,i.map.premultiplyAlpha=!1);const n=new Re;n.copy(i),t?this.trailMaterial=n:this.particleMaterial=n}i.map&&(i.map.colorSpace=or,i.map.premultiplyAlpha=!1),t&&i.side===ao&&(i=i.clone(),i.side=dm,t?this.trailMaterial=i:this.particleMaterial=i)}return i&&!FE&&i._didRequestTextureLOD===void 0&&(i._didRequestTextureLOD=0,zE&&console.log("Load material LOD",i.name),it.assignTextureLOD(i,0)),i}getMesh(t){let i=null;if(!i&&(this.particleMesh instanceof Y&&(i=this.particleMesh.geometry),i===null)){i=new Fs(1,1);const n=i.attributes.uv;for(let o=0;o<n.count;o++)n.setX(o,1-n.getX(o))}return new Y(i,this.getMaterial())}}Ge([m()],ss.prototype,"renderMode",2),Ge([m(ke)],ss.prototype,"particleMaterial",2),Ge([m(ke)],ss.prototype,"trailMaterial",2),Ge([m()],ss.prototype,"maxParticleSize",2),Ge([m()],ss.prototype,"minParticleSize",2),Ge([m()],ss.prototype,"velocityScale",2),Ge([m()],ss.prototype,"cameraVelocityScale",2),Ge([m()],ss.prototype,"lengthScale",2);class Cp{constructor(t,i=1){a(this,"_curve"),a(this,"_factor"),a(this,"type","function"),this._curve=t,this._factor=i}startGen(t){}genValue(t,i){return this._curve.evaluate(i,Math.random())*this._factor}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}}class V0{constructor(t){a(this,"type","value"),a(this,"system"),this.system=t}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}startGen(t){}}class UE extends V0{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class NE extends V0{constructor(){super(...arguments),a(this,"_lastPosition",new x),a(this,"_lastDistance",0)}update(){const t=te(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(t),this._lastPosition.copy(t)}genValue(){if(!this.system.isPlaying||!this.system.emission.enabled||this.system.currentParticles>=this.system.maxParticles)return 0;let t=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){const o=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let r=this._lastDistance/this.system.deltaTime*o;Number.isFinite(r)||(r=0),t+=r}const i=this.system.emission.getBurst();i>0&&(t+=i/this.system.deltaTime);const n=this.system.maxParticles-this.system.currentParticles;return W.clamp(t,0,n/this.system.deltaTime)}}class WE extends V0{genValue(){return this.system.isPlaying,0}}class Ho{constructor(t){a(this,"system"),a(this,"type"),this.type=Object.getPrototypeOf(this).constructor.name||"ParticleSystemBaseBehaviour",t&&(this.system=t)}get context(){return this.system.context}initialize(t){}update(t,i){}frameUpdate(t){}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}reset(){}}class VE extends Ho{constructor(){super(...arguments),a(this,"type","NeedleTextureSheet")}update(t,i){const n=this.system.textureSheetAnimation;if(n.enabled){const o=t.age/t.life,r=n.evaluate(o);r!==void 0&&(t.uvTile=r)}}}const o1=Symbol("particleRotation");class HE extends Ho{constructor(){super(...arguments),a(this,"type","NeedleRotation")}initialize(t){t[o1]=Math.random()}update(t,i){if(t.rotation===void 0)return;const n=t.age/t.life;if(typeof t.rotation=="number"&&(this.system.rotationOverLifetime.enabled?t.rotation+=this.system.rotationOverLifetime.evaluate(n,t[o1])*i:this.system.renderer.renderMode===Hn.Billboard&&(t.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const o=t.velocity.length();t.rotation+=this.system.rotationBySpeed.evaluate(n,o)*i}}}const r1=Symbol("sizeLerpFactor"),$E=new x;class qE extends Ho{constructor(){super(...arguments),a(this,"type","NeedleSize"),a(this,"_minSize",0),a(this,"_maxSize",1)}initialize(t){t[r1]=Math.random(),this._minSize=this.system.renderer.minParticleSize,this._maxSize=this.system.renderer.maxParticleSize}update(t,i){const n=t.age/t.life;let o=1;this.system.sizeOverLifetime.enabled&&(o*=this.system.sizeOverLifetime.evaluate(n,void 0,t[r1]).x);let r=1;this.system.renderer.renderMode!==Hn.Mesh&&(r=this.system.worldScale.x/this.system.cameraScale);const l=G(t.startSize).multiplyScalar(o*r);if(t.size.set(l.x,l.y,l.z),this.system.localspace){const c=d1(this.system,$E);t.size.x*=c.x,t.size.y*=c.y,t.size.z*=c.z}}}const Rl=Symbol("particleLife"),H0=Symbol("trailLifetime"),a1=Symbol("trailStartLength"),$0=Symbol("trailWidthRandom");class GE extends Ho{constructor(){super(...arguments),a(this,"type","NeedleTrail")}initialize(t){t instanceof pv&&(t[Rl]=t.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(t[H0]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),t.life+=t[H0]),t[a1]=t.length,t[$0]=Math.random())}update(t){var i;if((i=this.system.trails)!=null&&i.enabled&&t instanceof pv){const n=t,o=t.age/t[Rl],r=t.previous.values(),l=t.previous.length;for(let c=0;c<l;c++){const h=r.next().value,d=1-c/(l-1),u=t.size;if(u.x<=0&&!this.system.trails.sizeAffectsWidth){const p=20*this.system.trails.widthOverTrail.evaluate(.5,n[$0]);u.x=p,u.y=p,u.z=p}h.size=this.system.trails.getWidth(u.x,o,d,n[$0]),h.color.copy(t.color),this.system.trails.getColor(h.color,o,d)}if(t.age>t[Rl]){t.velocity.set(0,0,0);const c=(t.age-t[Rl])/t[H0];n.length=W.lerp(t[a1],0,c)}}}}const Op=Symbol("startVelocity"),l1=Symbol("gravityModifier"),q0=Symbol("gravitySpeed"),Pp=Symbol("velocity lerp factor"),G0=new x;class XE extends Ho{constructor(){super(...arguments),a(this,"type","NeedleVelocity"),a(this,"_gravityDirection",new x)}initialize(t){var i,n;const o=this.system.main.simulationSpeed;t.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random());const r=this.system.shape.getDirection(t,t.position);t.velocity.x=r.x*t.startSpeed,t.velocity.y=r.y*t.startSpeed,t.velocity.z=r.z*t.startSpeed,(i=this.system.inheritVelocity)!=null&&i.enabled&&this.system.inheritVelocity.applyInitial(t.velocity),t[Op]?t[Op].copy(t.velocity):t[Op]=t.velocity.clone();const l=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());t[l1]=l*o,t[q0]=l*o*.5,t[Pp]=Math.random(),(n=this.system.velocityOverLifetime)==null||n.init(t),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===xh.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(t,i){var n;const o=t[Op],r=t[l1];if(r!==0){const g=r*t[q0];G0.copy(this._gravityDirection).multiplyScalar(g),t[q0]+=i*.05,o.add(G0)}t.velocity.copy(o);const l=t.age/t.life;(n=this.system.inheritVelocity)!=null&&n.enabled&&this.system.inheritVelocity.applyCurrent(t.velocity,l,t[Pp]);const c=this.system.noise;c.enabled&&c.apply(0,t.position,t.velocity,i,t.age,t.life);const h=this.system.sizeBySpeed;h!=null&&h.enabled&&(t.size=h.evaluate(t.velocity,l,t[Pp],t.size));const d=this.system.colorBySpeed;d!=null&&d.enabled&&d.evaluate(t.velocity,t[Pp],t.color);const u=this.system.velocityOverLifetime;u.enabled&&u.apply(t,0,t.position,t.velocity,i,t.age,t.life);const p=this.system.limitVelocityOverLifetime;if(p.enabled&&p.apply(t.position,o,t.velocity,t.size,l,i,1),this.system.worldspace){const g=this.system.worldScale;t.velocity.x*=g.x,t.velocity.y*=g.y,t.velocity.z*=g.z}}}const c1=Symbol("colorLerpFactor"),h1=new xe(1,1,1,1),Yr=new xe(1,1,1,1);class QE extends Ho{constructor(){super(...arguments),a(this,"type","NeedleColor")}initialize(t){}_init(t){const i=this.system.renderer.particleMaterial;Yr.copy(this.system.main.startColor.evaluate(Math.random())),i!=null&&i.color&&(h1.copy(i.color),Yr.multiply(h1)),Yr.convertLinearToSRGB(),t.startColor.set(Yr.r,Yr.g,Yr.b,Yr.alpha),t.color.copy(t.startColor),t[c1]=Math.random()}update(t,i){if(t.age===0&&this._init(t),this.system.colorOverLifetime.enabled){const n=t.age/t.life,o=this.system.colorOverLifetime.color.evaluate(n,t[c1]);t.color.set(o.r,o.g,o.b,"alpha"in o?o.alpha:1).multiply(t.startColor)}else t.color.copy(t.startColor)}}class YE{constructor(t){a(this,"system"),a(this,"emission"),a(this,"autoDestroy"),a(this,"startLength"),a(this,"emissionBursts"),a(this,"onlyUsedByOther"),a(this,"behaviors",[]),a(this,"rendererEmitterSettings",{startLength:new cO(220),followLocalOrigin:!1}),a(this,"flatWhiteTexture"),a(this,"clonedTexture",{original:void 0,clone:void 0}),this.system=t,this.emission=new NE(this.system)}get anim(){return this.system.textureSheetAnimation}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()}get looping(){return this.system.main.loop}get duration(){return this.system.duration}get shape(){return this.system.shape}get startLife(){return new Cp(this.system.main.startLifetime)}get startSpeed(){return new Cp(this.system.main.startSpeed)}get startRotation(){return new Cp(this.system.main.startRotation)}get startSize(){return new Cp(this.system.main.startSize)}get startColor(){return new aO(new lO(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new WE(this.system)}get instancingGeometry(){return this.system.renderer.getMesh(this.system.renderer.renderMode).geometry}get renderMode(){if(this.system.trails.enabled===!0)return bn.Trail;switch(this.system.renderer.renderMode){case Hn.Billboard:return bn.BillBoard;case Hn.Stretch:return bn.StretchedBillBoard;case Hn.HorizontalBillboard:return bn.HorizontalBillBoard;case Hn.VerticalBillboard:return bn.VerticalBillBoard;case Hn.Mesh:return bn.Mesh}return bn.BillBoard}get speedFactor(){var t;let i=this.system.main.simulationSpeed;return((t=this.system.renderer)==null?void 0:t.renderMode)===Hn.Stretch&&(i*=this.system.renderer.velocityScale??1),i}get texture(){const t=this.material;if(t&&t.map){const i=t.map;if(this.clonedTexture.original!==i||!this.clonedTexture.clone){const n=i.clone();n.premultiplyAlpha=!1,n.colorSpace=or,this.clonedTexture.original=i,this.clonedTexture.clone=n}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=Gg(new xe(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new UE(this.system)}get uTileCount(){var t;return this.anim.enabled?(t=this.anim)==null?void 0:t.numTilesX:void 0}get vTileCount(){var t;return this.anim.enabled?(t=this.anim)==null?void 0:t.numTilesY:void 0}get renderOrder(){return 1}get blending(){var t;return((t=this.system.renderer.particleMaterial)==null?void 0:t.blending)??_C}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===xh.World}}class ZE{constructor(){a(this,"burstParticleIndex",0),a(this,"burstParticleCount",0),a(this,"isBursting",!1),a(this,"travelDistance",0),a(this,"previousWorldPos"),a(this,"burstIndex",0),a(this,"burstWaveIndex",0),a(this,"time",0),a(this,"waitEmiting",0)}}const kp=class extends A{constructor(){super(...arguments),a(this,"_state"),a(this,"colorOverLifetime"),a(this,"main"),a(this,"emission"),a(this,"sizeOverLifetime"),a(this,"shape"),a(this,"noise"),a(this,"trails"),a(this,"velocityOverLifetime"),a(this,"limitVelocityOverLifetime"),a(this,"inheritVelocity"),a(this,"colorBySpeed"),a(this,"textureSheetAnimation"),a(this,"rotationOverLifetime"),a(this,"rotationBySpeed"),a(this,"sizeBySpeed"),a(this,"_cameraScale",1),a(this,"__worldQuaternion",new V),a(this,"_worldQuaternionInverted",new V),a(this,"_worldScale",new x),a(this,"_worldPositionFrame",-1),a(this,"_worldPos",new x),a(this,"_renderer"),a(this,"_batchSystem"),a(this,"_particleSystem"),a(this,"_interface"),a(this,"_container"),a(this,"_time",0),a(this,"_isPlaying",!0),a(this,"_isUsedAsSubsystem",!1),a(this,"_didPreWarm",!1),a(this,"_bursts"),a(this,"_subEmitterSystems"),a(this,"_lastBatchesCount",-1)}play(s=!1){var t;s&&O.foreachComponent(this.gameObject,i=>{i instanceof kp&&i!==this&&i.play(!1)},!0),this._isPlaying=!0,this._particleSystem&&(this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1),(t=this.emission)==null||t.reset()}pause(s=!0){s&&O.foreachComponent(this.gameObject,t=>{t instanceof kp&&t!==this&&t.pause(!1)},!0),this._isPlaying=!1}stop(s=!0,t=!1){s&&O.foreachComponent(this.gameObject,i=>{i instanceof kp&&i!==this&&i.stop(!1,t)},!0),this._isPlaying=!1,this._time=0,t&&this.reset()}reset(){var s;this._time=0,this._particleSystem&&(this._particleSystem.particleNum=0,this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1,(s=this.emission)==null||s.reset())}emit(s){if(this._particleSystem){this.onUpdate(),s=Math.min(s,this.maxParticles-this.currentParticles),this._state||(this._state=new ZE),this._state.waitEmiting=s,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(s){this.main.playOnAwake=s}get renderer(){return this._renderer}get isPlaying(){return this._isPlaying}get currentParticles(){var s;return((s=this._particleSystem)==null?void 0:s.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}get container(){return this._container}get worldspace(){return this.main.simulationSpace===xh.World}get localspace(){return this.main.simulationSpace===xh.Local}get worldQuaternion(){return this.__worldQuaternion}get worldQuaternionInverted(){return this._worldQuaternionInverted}get worldScale(){return this._worldScale}get worldPos(){return this._worldPositionFrame!==this.context.time.frame&&(this._worldPositionFrame=this.context.time.frame,te(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}addBehaviour(s){return this._particleSystem?(s instanceof Ho&&(s.system=this),Vo&&console.debug("Add custom ParticleSystem Behaviour",s),this._particleSystem.addBehavior(s),!0):!1}removeBehaviour(s){if(!this._particleSystem)return!1;const t=this._particleSystem.behaviors,i=t.indexOf(s);return i!==-1&&((F()||Vo)&&console.debug("Remove custom ParticleSystem Behaviour",i,s),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}set bursts(s){for(let t=0;t<s.length;t++){const i=s[t];if(!(i instanceof wp)){const n=new wp;Ea(n,i),s[t]=n}}this._bursts=s}set subEmitterSystems(s){for(let t=0;t<s.length;t++){const i=s[t];if(!(i instanceof Mp)){const n=new Mp;Ea(n,i),s[t]=n}}Vo&&s.length>0&&console.log("SubEmitters: ",s,this),this._subEmitterSystems=s}onAfterDeserialize(s){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(ss),!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 I,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new oO,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new YE(this),this._particleSystem=new rO(this._interface),this._particleSystem.addBehavior(new qE(this)),this._particleSystem.addBehavior(new QE(this)),this._particleSystem.addBehavior(new VE(this)),this._particleSystem.addBehavior(new HE(this)),this._particleSystem.addBehavior(new XE(this)),this._particleSystem.addBehavior(new GE(this)),this._batchSystem.addSystem(this._particleSystem);const s=this._particleSystem.emitter;this.context.scene.add(s),this.inheritVelocity.system&&this.inheritVelocity.system!==this&&(this.inheritVelocity=this.inheritVelocity.clone()),this.inheritVelocity.awake(this),Vo&&(console.log(this),this.gameObject.add(new xi(1)))}start(){this.addSubParticleSystems(),this.updateLayers(),this.renderer.particleMesh instanceof Y&&this._interface.renderMode==bn.Mesh&&it.assignMeshLOD(this.renderer.particleMesh,0).then(s=>{s&&this.particleSystem&&this._interface.renderMode==bn.Mesh&&(this.particleSystem.instancingGeometry=s)})}onDestroy(){var s,t,i,n;(s=this._container)==null||s.removeFromParent(),(t=this._batchSystem)==null||t.removeFromParent(),(i=this._particleSystem)==null||i.emitter.removeFromParent(),(n=this._particleSystem)==null||n.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(){var s;this.main&&(this._didPreWarm===!1&&((s=this.main)==null?void 0:s.prewarm)===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){var s;if(!((s=this.emission)!=null&&s.enabled)||this.emission.rateOverTime.getMax()<=0)return;const t=1/60,i=this.main.duration,n=this.main.startLifetime.getMax(),o=1e3,r=Math.min(Math.max(i,n)/Math.max(.01,this.main.simulationSpeed),o),l=Math.ceil(r/t),c=Date.now();Vo&&console.log(`Particles ${this.name} - Prewarm for ${l} frames (${r} sec). Duration: ${i}, Lifetime: ${n}`);for(let h=0;h<l&&!(this.currentParticles>=this.maxParticles);h++){const d=Date.now()-c;if(d>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${d}`);break}this.onUpdate(),this.onSimulate(t)}}onSimulate(s){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(s)}this._time+=s,this._time>this.duration&&(this._time=0)}updateLayers(){if(this._batchSystem)for(let s=0;s<this._batchSystem.batches.length;s++){const t=this._batchSystem.batches[s];t.layers.disableAll();const i=this.layer;t.layers.mask=1<<i}}onUpdate(){var s,t;if(this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const i=this.context.mainCamera;if(i){const r=Ye(i);this._cameraScale=r.x}const n=!this.worldspace,o=this.gameObject;if(Ce(o,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),Ye(this.gameObject,this._worldScale),n&&this._container&&(s=this.gameObject)!=null&&s.parent){const r=d1(this,G0);this._container.matrix.makeScale(r.x,r.y,r.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),(t=this.inheritVelocity)==null||t.update(this.context),this.velocityOverLifetime.update(this)}addSubParticleSystems(){var s;if(this._subEmitterSystems&&this._particleSystem)for(const t of this._subEmitterSystems){t.particleSystem&&(t.particleSystem.__internalAwake?t.particleSystem.__internalAwake():F()&&console.warn("SubParticleSystem serialization issue(?)",t.particleSystem,t));const i=(s=t.particleSystem)==null?void 0:s._particleSystem;if(i){t.particleSystem._isUsedAsSubsystem=!0;const n=new N0(this,this._particleSystem,t.particleSystem,i);n.emitterType=t.type,n.emitterProbability=t.emitProbability,this._particleSystem.addBehavior(n)}else Vo&&console.warn("Could not add SubParticleSystem",t,this)}}};let lt=kp;Ge([m(xp)],lt.prototype,"colorOverLifetime",2),Ge([m(Ht)],lt.prototype,"main",2),Ge([m($n)],lt.prototype,"emission",2),Ge([m(Xr)],lt.prototype,"sizeOverLifetime",2),Ge([m(et)],lt.prototype,"shape",2),Ge([m(Pe)],lt.prototype,"noise",2),Ge([m(qe)],lt.prototype,"trails",2),Ge([m(tt)],lt.prototype,"velocityOverLifetime",2),Ge([m(mt)],lt.prototype,"limitVelocityOverLifetime",2),Ge([m(Qr)],lt.prototype,"inheritVelocity",2),Ge([m(Ml)],lt.prototype,"colorBySpeed",2),Ge([m($t)],lt.prototype,"textureSheetAnimation",2),Ge([m(Es)],lt.prototype,"rotationOverLifetime",2),Ge([m(is)],lt.prototype,"rotationBySpeed",2),Ge([m(vi)],lt.prototype,"sizeBySpeed",2);class Mp{constructor(){a(this,"particleSystem"),a(this,"emitProbability",1),a(this,"properties"),a(this,"type")}_deserialize(t,i){const n=this.particleSystem;if(n instanceof lt)return;let o="";n&&typeof n.guid=="string"&&(o=n.guid,this.particleSystem=O.findByGuid(o,i)),Vo&&!(this.particleSystem instanceof lt)&&console.warn("Could not find particle system for sub emitter",o,i,this)}}function d1(s,t){if(t.set(1,1,1),s.gameObject.parent&&s.localspace)switch(s.main.scalingMode){case U0.Local:t=Ye(s.gameObject.parent,t),t.x=1/t.x,t.y=1/t.y,t.z=1/t.z;break;default:if(!s.unsupported_scaling_mode){s.unsupported_scaling_mode=!0;const i="ParticleSystem scale mode "+U0[s.main.scalingMode]+" is not supported";F()&&we(i),console.warn(i,s.name,s)}t=Ye(s.gameObject,t);break}return t}class Wl extends A{constructor(){super(...arguments),a(this,"_didAssignPlayerColor",!1),a(this,"tryAssignColor",()=>{const t=O.getComponentInParent(this.gameObject,Ii);if(t&&t.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(t.owner),!0;const i=O.getComponentInParent(this.gameObject,Mt);return i!=null&&i.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(i.connectionId),!0):!1})}onEnable(){this.context.connection.beginListen(se.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(se.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield $g(.2),!this.tryAssignColor()););}assignUserColor(t){const i=Wl.hashCode(t),n=Wl.colorFromHashCode(i);if(this.gameObject.type==="Mesh"){const o=this.gameObject;this.assignColor(n,t,o)}else if(this.gameObject.children)for(const o of this.gameObject.children){const r=o;r.material&&r.material.color&&this.assignColor(n,t,r)}}assignColor(t,i,n){let o=n.material;o&&(o._playerMaterial!==i&&(o=o.clone(),o._playerMaterial=i,n.material=o),o.color=t)}static hashCode(t){var i=0,n,o;if(t.length===0)return i;for(n=0;n<t.length;n++)o=t.charCodeAt(n),i=(i<<5)-i+o,i|=0;return i}static colorFromHashCode(t){const i=(t&16711680)>>16,n=(t&65280)>>8,o=t&255;return new ae(i/255,n/255,o/255)}}const KE=C("debugpost");let X0=null;function JE(s){X0=s}function u1(s){let t=s.gameObject;for(;t;){for(const i of Zd(t))if(i.isPostProcessingManager===!0)return i;t=t.parent}return null}function eA(s){let t=u1(s);if(!t)if(X0){KE&&console.warn("Adding postprocessing manager to the scene.");const i=s.scene;t=Mi(i,X0)}else F()&&console.warn("No post processing manager found");return t}var tA=Object.defineProperty,iA=Object.getOwnPropertyDescriptor,p1=(s,t,i,n)=>{for(var o=n>1?void 0:n?iA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&tA(t,i,o),o};const sA=C("debugpost");class N{constructor(t){a(this,"isVolumeParameter",!0),a(this,"_isInitialized",!1),a(this,"_active",!0),a(this,"_value"),a(this,"_valueRaw"),a(this,"_defaultValue"),a(this,"valueProcessor"),a(this,"onValueChanged"),t!==void 0&&this.initialize(t)}get isInitialized(){return this._isInitialized}initialize(t){t!==void 0&&(this._value=t,this._defaultValue=t,this._valueRaw=t,this._isInitialized=!0)}get overrideState(){return this._active}set overrideState(t){if(this._active===t)return;this._active=t;const i=t?this._valueRaw:this._defaultValue;this.processValue(i,!0)}get value(){return this._valueRaw}set value(t){this.isInitialized||this.initialize(t),this.processValue(t,!1)}set defaultValue(t){this._defaultValue=t}__init(){this.processValue(this._valueRaw,!0)}processValue(t,i){if(t==null||!i&&this.testIfValueChanged(t)===!1)return;const n=this._value;sA&&typeof n=="number"&&typeof t=="number"&&(n?.toFixed(4),t?.toFixed(4)),!this._active&&this._defaultValue!==void 0?(this._value=this._defaultValue,t=this._defaultValue,this._valueRaw=t):(this._valueRaw=t,this._active&&this.valueProcessor&&(t=this.valueProcessor(t)),this._value=t),this.onValueChanged&&this.onValueChanged(t,n,this)}testIfValueChanged(t){return this._valueRaw!==t}}p1([m()],N.prototype,"overrideState",1),p1([m()],N.prototype,"value",1);class nA extends Qi{constructor(){super([N])}onSerialize(t,i){}onDeserialize(t,i){const n=i.target,o=i.path;let r;if(n&&o&&(r=n[o]),(typeof r!="object"||typeof r=="object"&&r.isVolumeParameter!==!0)&&(r=new N),typeof t=="object"&&"value"in t){const l=t.value;r.initialize(l),r.overrideState=t.overrideState}else r.value=t;return r}}new nA;var oA=Object.defineProperty,rA=Object.getOwnPropertyDescriptor,aA=(s,t,i,n)=>{for(var o=n>1?void 0:n?rA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&oA(t,i,o),o};const Q0=C("debugpost");class ct extends A{constructor(t=void 0){if(super(),a(this,"active",!0),a(this,"_manager",null),a(this,"_result"),a(this,"_postprocessingContext",null),t)for(const i of Object.keys(t)){const n=t[i],o=this[i];o instanceof N?o.initialize(n):o!==void 0&&(this[i]=n)}}get isPostProcessingEffect(){return!0}onEnable(){super.onEnable(),Q0&&console.warn("onEnable effect",this,this.__internalDidAwakeAndStart),this.__internalDidAwakeAndStart&&(this.active=!0),this.onEffectEnabled()}onDisable(){var t;super.onDisable(),Q0&&console.warn("onDisable effect",this),(t=this._manager)==null||t.removeEffect(this),this.active=!1}onEffectEnabled(t){var i;t&&t.isPostProcessingManager===!0?this._manager=t:this._manager||(this._manager=eA(this)),(i=this._manager)==null||i.addEffect(this)}init(){}get postprocessingContext(){return this._postprocessingContext}apply(t){var i;return this._postprocessingContext=t,this._result||(this.initParameters(),this._result=(i=this.onCreateEffect)==null?void 0:i.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){Q0&&console.warn("DISPOSE",this),this._result&&(Array.isArray(this._result)?this._result.forEach(t=>t.dispose()):this._result.dispose()),this._result=void 0}initParameters(){const t=Object.keys(this);for(const i of t){const n=this[i];n instanceof N&&n.__init()}}onEditorModification(t){const i=t.propertyName;if(this[i]instanceof N){const n=t.value;return this[i].value=n,!0}}}aA([m()],ct.prototype,"active",2);var lA=Object.defineProperty,cA=Object.getOwnPropertyDescriptor,hA=(s,t,i,n)=>{for(var o=n>1?void 0:n?cA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&lA(t,i,o),o};const dA=C("debugpost"),Y0={};function ns(s,t){Y0[s]=t}function uA(s){return s.__type in Y0?Y0[s.__type]:(dA&&s.__type&&console.warn("Unknown postprocessing type",s.__type,s),ct)}class Rp{constructor(){a(this,"components",[])}__init(t){var i;(i=this.components)==null||i.forEach(n=>{n.gameObject===void 0&&t.gameObject.addComponent(n),n.init()})}addEffect(t){this.components.push(t)}removeEffect(t){const i=this.components.indexOf(t);i>=0&&this.components.splice(i,1)}}hA([Pr([s=>uA(s),ct])],Rp.prototype,"components",2);var pA=Object.defineProperty,mA=Object.getOwnPropertyDescriptor,gA=(s,t,i,n)=>{for(var o=n>1?void 0:n?mA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&pA(t,i,o),o};class Oh extends ct{constructor(){super(...arguments),a(this,"preset",new N(2))}get typeName(){return"Antialiasing"}onCreateEffect(){const t=new j.POSTPROCESSING.MODULE.SMAAEffect({preset:j.POSTPROCESSING.MODULE.SMAAPreset.HIGH,edgeDetectionMode:j.POSTPROCESSING.MODULE.EdgeDetectionMode.DEPTH});return this.preset.onValueChanged=i=>{t.applyPreset(i)},t}}gA([m(N)],Oh.prototype,"preset",2),ns("Antialiasing",Oh);var fA=Object.defineProperty,yA=Object.getOwnPropertyDescriptor,Z0=(s,t,i,n)=>{for(var o=n>1?void 0:n?yA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&fA(t,i,o),o},K0;const m1=(K0=class extends ct{constructor(){super(...arguments),a(this,"threshold",new N(.9)),a(this,"intensity",new N(1)),a(this,"scatter",new N(.3)),a(this,"selectiveBloom")}get typeName(){return"Bloom"}init(){this.threshold.valueProcessor=s=>s,this.intensity.valueProcessor=s=>s,this.scatter.valueProcessor=s=>s}onCreateEffect(){let s;if(this.selectiveBloom==null&&(this.selectiveBloom=m1.useSelectiveBloom),this.selectiveBloom){const t=s=new j.POSTPROCESSING.MODULE.SelectiveBloomEffect(this.context.scene,this.context.mainCamera,{blendFunction:j.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});t.inverted=!0}else s=new j.POSTPROCESSING.MODULE.BloomEffect({blendFunction:j.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=>{s.intensity=t},this.threshold.onValueChanged=t=>{s.luminanceMaterial.threshold=Math.pow(t,2.2)},this.scatter.onValueChanged=t=>{s.luminancePass.enabled=!0,s.luminanceMaterial.smoothing=t,s.mipmapBlurPass&&(s.mipmapBlurPass.radius=mn.lerp(.1,.9,t))},s}},a(K0,"useSelectiveBloom",!1),K0);let Zr=m1;Z0([m(N)],Zr.prototype,"threshold",2),Z0([m(N)],Zr.prototype,"intensity",2),Z0([m(N)],Zr.prototype,"scatter",2),ns("Bloom",Zr);var vA=Object.defineProperty,bA=Object.getOwnPropertyDescriptor,_A=(s,t,i,n)=>{for(var o=n>1?void 0:n?bA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&vA(t,i,o),o};class Ph extends ct{constructor(){super(...arguments),a(this,"intensity",new N(0))}get typeName(){return"ChromaticAberration"}onCreateEffect(){const t=new j.POSTPROCESSING.MODULE.ChromaticAberrationEffect;return t.offset=new re(0,0),t.radialModulation=!0,t.modulationOffset=.15,this.intensity.valueProcessor=i=>i*.02,this.intensity.onValueChanged=i=>{t.offset.x=-i,t.offset.y=i},t}}_A([m(N)],Ph.prototype,"intensity",2),ns("ChromaticAberration",Ph);var wA=Object.defineProperty,xA=Object.getOwnPropertyDescriptor,g1=(s,t,i,n)=>{for(var o=n>1?void 0:n?xA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&wA(t,i,o),o};const f1=C("debugpost");var Tp=(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))(Tp||{});function J0(s){switch(s){case 0:return hd;case 1:return mm;case 2:return pm;case 3:return cd;case 4:return Xl;default:return Xl}}function SA(s){switch(s){case hd:return 0;case pm:return 2;case cd:return 3;case Xl:return 1;case mm:return 1;default:return 0}}function y1(s){switch(s){case hd:return j.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR;case pm:return j.POSTPROCESSING.MODULE.ToneMappingMode.ACES_FILMIC;case cd:return j.POSTPROCESSING.MODULE.ToneMappingMode.AGX;case Xl:return j.POSTPROCESSING.MODULE.ToneMappingMode.NEUTRAL;case mm:return j.POSTPROCESSING.MODULE.ToneMappingMode.REINHARD;default:return j.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR}}const v1=class extends ct{constructor(){super(...arguments),a(this,"mode",new N(void 0)),a(this,"exposure",new N(1))}get typeName(){return"ToneMapping"}setMode(s){const t=Tp[s];return t===void 0?(console.error("Invalid ToneMapping mode",s),this):(this.mode.value=t,this)}get isToneMapping(){return!0}onEffectEnabled(){const s=u1(this);s&&super.onEffectEnabled(s)}onCreateEffect(){if(this.postprocessingContext)for(const i of this.postprocessingContext.components){if(i===this)break;if(i!=this&&i instanceof v1){console.warn("Multiple tonemapping effects found in the same postprocessing stack: Please check your scene setup.",{activeEffect:i,ignoredEffect:this});return}}if(this.mode.isInitialized==!1){const i=SA(this.context.renderer.toneMapping);this.mode.initialize(i)}const s=J0(this.mode.value),t=new j.POSTPROCESSING.MODULE.ToneMappingEffect({mode:y1(s)});return this.mode.onValueChanged=i=>{const n=J0(i);t.mode=y1(n),f1&&console.log("ToneMapping mode changed to",Tp[i],n,t.mode)},f1&&console.log("Use ToneMapping",Tp[this.mode.value],s,t.mode,"renderer.tonemapping: "+this.context.renderer.toneMapping),this.exposure.onValueChanged=i=>{this.context.renderer.toneMappingExposure=i},t}onBeforeRender(){this.mode.overrideState&&(this.context.renderer.toneMapping=J0(this.mode.value)),this.exposure.overrideState&&this.exposure.value!==void 0&&(this.context.renderer.toneMappingExposure=this.exposure.value)}};let $o=v1;g1([m(N)],$o.prototype,"mode",2),g1([m(N)],$o.prototype,"exposure",2),ns("Tonemapping",$o);var CA=Object.defineProperty,OA=Object.getOwnPropertyDescriptor,Ep=(s,t,i,n)=>{for(var o=n>1?void 0:n?OA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&CA(t,i,o),o};class qo extends ct{constructor(){super(...arguments),a(this,"postExposure",new N(0)),a(this,"contrast",new N(0)),a(this,"hueShift",new N(0)),a(this,"saturation",new N(0))}get typeName(){return"ColorAdjustments"}init(){this.postExposure.valueProcessor=t=>(t=Math.pow(2,t),t),this.contrast.valueProcessor=t=>{let i=1;return t>0?i=200:t<0&&(i=100),t/i},this.contrast.defaultValue=0,this.hueShift.valueProcessor=t=>Math.PI*t/180,this.hueShift.defaultValue=0,this.saturation.valueProcessor=t=>t<0?t/100:t/(100*Math.PI),this.saturation.defaultValue=0}onCreateEffect(){var t,i;const n=[];this.context.renderer.toneMapping!==fa&&this.postExposure.overrideState&&(this.context.renderer.toneMapping=fa);let o=(t=this.postprocessingContext)==null?void 0:t.components.find(c=>c instanceof $o);o||(o=new $o,(i=this.postprocessingContext)==null||i.components.push(o)),this.postExposure.onValueChanged=c=>{this.postExposure.overrideState&&(o.exposure.value=c)};const r=new j.POSTPROCESSING.MODULE.BrightnessContrastEffect;this.contrast.onValueChanged=c=>r.contrast=c;const l=new j.POSTPROCESSING.MODULE.HueSaturationEffect;return n.push(r),n.push(l),this.hueShift.onValueChanged=c=>l.hue=c,this.saturation.onValueChanged=c=>l.saturation=c,n}}Ep([m(N)],qo.prototype,"postExposure",2),Ep([m(N)],qo.prototype,"contrast",2),Ep([m(N)],qo.prototype,"hueShift",2),Ep([m(N)],qo.prototype,"saturation",2),ns("ColorAdjustments",qo);var PA=Object.defineProperty,kA=Object.getOwnPropertyDescriptor,Kr=(s,t,i,n)=>{for(var o=n>1?void 0:n?kA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&PA(t,i,o),o};const MA=C("debugpost");class As extends ct{constructor(){super(...arguments),a(this,"mode"),a(this,"focusDistance",new N(1)),a(this,"focalLength",new N(.2)),a(this,"aperture",new N(20)),a(this,"gaussianMaxRadius",new N),a(this,"resolutionScale",new N(1*1/window.devicePixelRatio)),a(this,"bokehScale",new N)}get typeName(){return"DepthOfField"}init(){this.focalLength.valueProcessor=i=>{const n=i/300,o=2;return W.lerp(o,.01,n)};const t=20;this.aperture.valueProcessor=i=>{const n=1-i/32;return W.lerp(1,t,n)}}onCreateEffect(){if(this.mode===0){MA&&console.warn("DepthOfField: Mode is set to Off");return}const t=new j.POSTPROCESSING.MODULE.DepthOfFieldEffect(this.context.mainCamera,{worldFocusRange:.2,focalLength:1,bokehScale:20,resolutionScale:this.resolutionScale.value});return this.focusDistance.onValueChanged=i=>{t.cocMaterial.worldFocusDistance=i},this.focalLength.onValueChanged=i=>t.cocMaterial.worldFocusRange=i,this.aperture.onValueChanged=i=>t.bokehScale=i,this.resolutionScale&&(this.resolutionScale.onValueChanged=i=>t.resolution.scale=i),[t]}unapply(){}}Kr([m()],As.prototype,"mode",2),Kr([m(N)],As.prototype,"focusDistance",2),Kr([m(N)],As.prototype,"focalLength",2),Kr([m(N)],As.prototype,"aperture",2),Kr([m(N)],As.prototype,"gaussianMaxRadius",2),Kr([m(N)],As.prototype,"resolutionScale",2),Kr([m(N)],As.prototype,"bokehScale",2),ns("DepthOfField",As);class kh extends ct{constructor(t){super(),a(this,"effect"),this.effect=t}get typeName(){return this.effect.constructor.name}onCreateEffect(){return this.effect}}var RA=Object.defineProperty,TA=Object.getOwnPropertyDescriptor,EA=(s,t,i,n)=>{for(var o=n>1?void 0:n?TA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&RA(t,i,o),o};class Mh extends ct{constructor(){super(...arguments),a(this,"granularity",new N(10))}get typeName(){return"PixelationEffect"}onCreateEffect(){const t=new j.POSTPROCESSING.MODULE.PixelationEffect;return this.granularity.onValueChanged=i=>{t.granularity=i},t}}EA([m(N)],Mh.prototype,"granularity",2),ns("PixelationEffect",Mh);var AA=Object.defineProperty,IA=Object.getOwnPropertyDescriptor,Rh=(s,t,i,n)=>{for(var o=n>1?void 0:n?IA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&AA(t,i,o),o};class qn extends ct{constructor(){super(...arguments),a(this,"intensity",new N(2)),a(this,"falloff",new N(1)),a(this,"samples",new N(9)),a(this,"color",new N(new ae(0,0,0))),a(this,"luminanceInfluence",new N(.7)),a(this,"_ssao")}get typeName(){return"ScreenSpaceAmbientOcclusion"}onBeforeRender(){if(this._ssao&&this.context.mainCamera instanceof _e){const t=this.context.mainCamera.far-this.context.mainCamera.near;this._ssao.ssaoMaterial.worldDistanceFalloff=t*.01,this._ssao.ssaoMaterial.worldDistanceThreshold=this.context.mainCamera.far}}onCreateEffect(){const t=this.context.mainCamera,i=new j.POSTPROCESSING.MODULE.NormalPass(this.context.scene,t),n=new j.POSTPROCESSING.MODULE.DepthDownsamplingPass({normalBuffer:i.texture,resolutionScale:.5}),o=this._ssao=new j.POSTPROCESSING.MODULE.SSAOEffect(t,i.texture,{normalDepthBuffer:n.texture,worldDistanceThreshold:1,worldDistanceFalloff:1,worldProximityThreshold:.1,worldProximityFalloff:2,intensity:1,blendFunction:j.POSTPROCESSING.MODULE.BlendFunction.MULTIPLY,luminanceInfluence:.5});this.intensity.onValueChanged=l=>{o.intensity=l},this.falloff.onValueChanged=l=>{o.ssaoMaterial.radius=l*.1},this.samples.onValueChanged=l=>{o.ssaoMaterial.samples=l},this.color.onValueChanged=l=>{o.color||(o.color=new ae),o.color.copy(l)},this.luminanceInfluence.onValueChanged=l=>{o.luminanceInfluence=l};const r=new Array;return r.push(i),r.push(n),r.push(o),r}}Rh([m(N)],qn.prototype,"intensity",2),Rh([m(N)],qn.prototype,"falloff",2),Rh([m(N)],qn.prototype,"samples",2),Rh([m(N)],qn.prototype,"color",2),Rh([m(N)],qn.prototype,"luminanceInfluence",2),ns("ScreenSpaceAmbientOcclusion",qn);var jA=Object.defineProperty,LA=Object.getOwnPropertyDescriptor,Jr=(s,t,i,n)=>{for(var o=n>1?void 0:n?LA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&jA(t,i,o),o};const DA=C("debugN8AO");var ey=(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))(ey||{});class Is extends ct{constructor(){super(...arguments),a(this,"gammaCorrection",!0),a(this,"aoRadius",new N(1)),a(this,"falloff",new N(1)),a(this,"intensity",new N(1)),a(this,"color",new N(new ae(0,0,0))),a(this,"screenspaceRadius",!1),a(this,"quality",2),a(this,"_ssao")}get typeName(){return"ScreenSpaceAmbientOcclusionN8"}get pass(){return this._ssao}onValidate(){this._ssao&&(this._ssao.setQualityMode(ey[this.quality]),this._ssao.configuration.gammaCorrection=this.gammaCorrection,this._ssao.configuration.screenSpaceRadius=this.screenspaceRadius)}onCreateEffect(){const t=this.context.mainCamera,i=this.context.domWidth,n=this.context.domHeight,o=this._ssao=new j.POSTPROCESSING_AO.MODULE.N8AOPostPass(this.context.scene,t,i,n),r=ey[this.quality];o.setQualityMode(r),o.configuration.transparencyAware=!1;const l=new vn(i,n);return o.configuration.beautyRenderTarget=l,o.configuration.autoRenderBeauty=!1,o.configuration.gammaCorrection=this.gammaCorrection,o.configuration.screenSpaceRadius=this.screenspaceRadius,DA&&(o.enableDebugMode(),console.log(o),setInterval(()=>{console.log("SSAO",o.lastTime)},1e3),setInterval(()=>{console.log("SSAO",o.enabled,{ssao:o,autoRenderBeauty:o.configuration.autoRenderBeauty})},4e3)),this.intensity.onValueChanged=c=>{o.configuration.intensity=c},this.falloff.onValueChanged=c=>{o.configuration.distanceFalloff=c},this.aoRadius.onValueChanged=c=>{o.configuration.aoRadius=c},this.color.onValueChanged=c=>{o.color||(o.color=new ae),o.configuration.color.copy(c)},o}}Jr([kt(),m()],Is.prototype,"gammaCorrection",2),Jr([m(N)],Is.prototype,"aoRadius",2),Jr([m(N)],Is.prototype,"falloff",2),Jr([m(N)],Is.prototype,"intensity",2),Jr([m(N)],Is.prototype,"color",2),Jr([kt(),m()],Is.prototype,"screenspaceRadius",2),Jr([kt(),m()],Is.prototype,"quality",2),ns("ScreenSpaceAmbientOcclusionN8",Is);var BA=Object.defineProperty,FA=Object.getOwnPropertyDescriptor,b1=(s,t,i,n)=>{for(var o=n>1?void 0:n?FA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&BA(t,i,o),o};class Th extends ct{constructor(){super(...arguments),a(this,"_effect"),a(this,"_amount",1),a(this,"_radius",1)}get typeName(){return"Sharpening"}onCreateEffect(){return this._effect??(this._effect=new(zA())),this.effect}get effect(){return this._effect}set amount(t){this._amount=t,this._effect&&(this._effect.uniforms.get("amount").value=t)}get amount(){return this._effect?this._effect.uniforms.get("amount").value:this._amount}set radius(t){this._radius=t,this._effect&&(this._effect.uniforms.get("radius").value=t)}get radius(){return this._effect?this._effect.uniforms.get("radius").value:this._radius}}b1([m()],Th.prototype,"amount",1),b1([m()],Th.prototype,"radius",1);function zA(){const s=`
1222
1226
  void mainSupport() {
1223
1227
  vUv = uv;
1224
1228
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
@@ -1262,7 +1266,7 @@ axisFormat %s
1262
1266
  outputColor = sharp;
1263
1267
  }
1264
1268
 
1265
- `;class i extends D.POSTPROCESSING.MODULE.Effect{constructor(){super("Sharpening",t,{vertexShader:s,blendFunction:D.POSTPROCESSING.MODULE.BlendFunction.NORMAL,uniforms:new Map([["amount",new io(1)],["radius",new io(1)]])})}}return i}var UA=Object.defineProperty,NA=Object.getOwnPropertyDescriptor,Tl=(s,t,i,n)=>{for(var o=n>1?void 0:n?NA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&UA(t,i,o),o};class ln extends ct{constructor(){super(...arguments),a(this,"offset",new N(0)),a(this,"rotation",new N(0)),a(this,"focusArea",new N(.4)),a(this,"feather",new N(.3)),a(this,"kernelSize",new N(2)),a(this,"resolutionScale",new N(1/window.devicePixelRatio))}get typeName(){return"TiltShiftEffect"}init(){this.offset.defaultValue=0,this.rotation.defaultValue=0,this.focusArea.defaultValue=.4,this.feather.defaultValue=.3,this.kernelSize.defaultValue=D.POSTPROCESSING.MODULE.KernelSize.MEDIUM,this.resolutionScale.defaultValue=1/window.devicePixelRatio}onCreateEffect(){const t=new D.POSTPROCESSING.MODULE.TiltShiftEffect({kernelSize:D.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=i=>t.offset=i,this.rotation.onValueChanged=i=>t.rotation=i,this.focusArea.onValueChanged=i=>t.focusArea=i,this.feather.onValueChanged=i=>t.feather=i,this.kernelSize.onValueChanged=i=>t.blurPass.kernelSize=i,this.resolutionScale.onValueChanged=i=>t.resolution.scale=i/window.devicePixelRatio,t}}Tl([m(N)],ln.prototype,"offset",2),Tl([m(N)],ln.prototype,"rotation",2),Tl([m(N)],ln.prototype,"focusArea",2),Tl([m(N)],ln.prototype,"feather",2),Tl([m(N)],ln.prototype,"kernelSize",2),Tl([m(N)],ln.prototype,"resolutionScale",2),ns("TiltShiftEffect",ln);var WA=Object.defineProperty,VA=Object.getOwnPropertyDescriptor,ty=(s,t,i,n)=>{for(var o=n>1?void 0:n?VA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&WA(t,i,o),o};class ea extends ct{constructor(){super(...arguments),a(this,"color",new N({r:0,g:0,b:0,a:1})),a(this,"intensity",new N(0)),a(this,"center",new N({x:.5,y:.5}))}get typeName(){return"Vignette"}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 t=new D.POSTPROCESSING.MODULE.VignetteEffect;return this.intensity.onValueChanged=i=>{t.offset=i,this.updateDarkness(t)},this.color.onValueChanged=i=>{this.updateDarkness(t)},t}updateDarkness(t){const i=this.intensity.value;t.darkness=i}}ty([m(N)],ea.prototype,"color",2),ty([m(N)],ea.prototype,"intensity",2),ty([m(N)],ea.prototype,"center",2),ns("Vignette",ea),globalThis.false=globalThis.false!==void 0?globalThis.false:!0;const Gn=C("debugpost"),iy=Symbol("needle:postprocessing-handler"),sy=Symbol("needle:previous-autoclear-state");class ny{constructor(t){a(this,"_composer",null),a(this,"_lastVolumeComponents"),a(this,"_effects",[]),a(this,"_isActive",!1),a(this,"context"),this.context=t}get isActive(){return this._isActive}get composer(){return this._composer}apply(t){return"env"in import.meta&&{}.VITE_NEEDLE_USE_POSTPROCESSING==="false"?(Gn?console.warn("Postprocessing is disabled via vite env setting"):console.debug("Postprocessing is disabled via vite env setting"),Promise.resolve()):(Gn?console.warn("Postprocessing is disabled via global vite define setting"):console.debug("Postprocessing is disabled via vite define"),Promise.resolve())}unapply(){var t;if(Gn&&console.log("Unapplying postprocessing effects"),this._isActive=!1,this._lastVolumeComponents){for(const n of this._lastVolumeComponents)n.unapply();this._lastVolumeComponents.length=0}const i=this.context;i[iy]===this&&delete i[iy],i.composer===this._composer&&((t=i.composer)==null||t.dispose(),i.composer=null),typeof i.renderer[sy]=="boolean"&&(i.renderer.autoClear=i.renderer[sy])}dispose(){this.unapply();for(const t of this._effects)t.dispose();this._effects.length=0,this._composer=null}async onApply(t,i){if(!i)return;await Promise.all([D.POSTPROCESSING.load(),D.POSTPROCESSING_AO.load()]),t[iy]=this,Gn&&console.log("Apply Postprocessing Effects",i),this._lastVolumeComponents=[...i],this._effects.length=0;const n={handler:this,components:this._lastVolumeComponents};for(let o=0;o<this._lastVolumeComponents.length;o++){const r=this._lastVolumeComponents[o];if(r.context=t,r.apply){if(r.active){if(!t.mainCameraComponent){console.error("No camera in scene found or available yet - can not create postprocessing effects");return}const l=r.apply(n);if(!l)continue;Array.isArray(l)?this._effects.push(...l):this._effects.push(l)}}else r.active&&we("Volume component is not a VolumeComponent: "+r.__type)}if(this.context.renderer.toneMapping!=fa&&!this._effects.find(o=>o instanceof D.POSTPROCESSING.MODULE.ToneMappingEffect)){const o=new D.POSTPROCESSING.MODULE.ToneMappingEffect;this._effects.push(o)}this.applyEffects(t)}applyEffects(t){const i=this._effects;if(i.length<=0)return;const n=t.mainCameraComponent,o=t.renderer,r=t.scene,l=n.threeCamera;o[sy]=o.autoClear,this._composer||(this._composer=new D.POSTPROCESSING.MODULE.EffectComposer(o,{frameBufferType:wC,stencilBuffer:!0})),t.composer&&t.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."),t.composer=this._composer;const c=t.composer;c.setMainCamera(l),c.setRenderer(o),c.setMainScene(r);for(const d of c.passes)d.dispose();c.removeAllPasses();const h=new D.POSTPROCESSING.MODULE.RenderPass(r,l);h.name="Render To Screen",h.mainScene=r,c.addPass(h);try{this.orderEffects();const d=[];for(const u of i)u instanceof D.POSTPROCESSING.MODULE.Effect?d.push(u):(u instanceof D.POSTPROCESSING.MODULE.Pass,c.addPass(u));if(d.length>0){const u=new D.POSTPROCESSING.MODULE.EffectPass(l,...d);u.name=d.map(p=>p.name).join(" "),u.mainScene=r,u.enabled=!0,c.addPass(u)}}catch(d){console.error("Error while applying postprocessing effects",d),c.removeAllPasses()}Gn&&console.log("[PostProcessing] Passes \u2192",c.passes)}orderEffects(){var t;Gn&&console.log("Before ordering effects",[...this._effects]),Ap??(Ap=[D.POSTPROCESSING.MODULE.NormalPass,D.POSTPROCESSING.MODULE.DepthDownsamplingPass,D.POSTPROCESSING.MODULE.SMAAEffect,D.POSTPROCESSING.MODULE.SSAOEffect,D.POSTPROCESSING_AO.MODULE.N8AOPostPass,D.POSTPROCESSING.MODULE.TiltShiftEffect,D.POSTPROCESSING.MODULE.DepthOfFieldEffect,D.POSTPROCESSING.MODULE.ChromaticAberrationEffect,D.POSTPROCESSING.MODULE.BloomEffect,D.POSTPROCESSING.MODULE.SelectiveBloomEffect,D.POSTPROCESSING.MODULE.VignetteEffect,D.POSTPROCESSING.MODULE.PixelationEffect,D.POSTPROCESSING.MODULE.ToneMappingEffect,D.POSTPROCESSING.MODULE.HueSaturationEffect,D.POSTPROCESSING.MODULE.BrightnessContrastEffect]);const i=this._effects;i.sort((n,o)=>{const r=Ap.findIndex(c=>n.constructor.name.endsWith(c.name)),l=Ap.findIndex(c=>o.constructor.name.endsWith(c.name));return r<0?(Gn&&console.warn("Unknown effect found: ",n.constructor.name),-1):l<0?(Gn&&console.warn("Unknown effect found: ",o.constructor.name),1):r<0?1:l<0?-1:r-l}),Gn&&console.log("After ordering effects",[...this._effects]);for(let n=0;n<i.length;n++){const o=i[n];if(((t=o?.configuration)==null?void 0:t.gammaCorrection)!==void 0){const r=n===i.length-1;o.configuration.gammaCorrection=r}}}}let Ap=null;var HA=Object.defineProperty,$A=Object.getOwnPropertyDescriptor,_1=(s,t,i,n)=>{for(var o=n>1?void 0:n?$A(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&HA(t,i,o),o};const El=C("debugpost");class Al extends A{constructor(){super(...arguments),a(this,"sharedProfile"),a(this,"multisampling","auto"),a(this,"_postprocessing"),a(this,"_activeEffects",[]),a(this,"_effects",[]),a(this,"_componentEnabledTime",-1),a(this,"_multisampleAutoChangeTime",0),a(this,"_multisampleAutoDecreaseTime",0),a(this,"_lastApplyTime"),a(this,"_rapidApplyCount",0),a(this,"_isDirty",!1),a(this,"_modificationQueue"),a(this,"_recreateId",-1)}get isPostProcessingManager(){return!0}get effects(){return this._activeEffects}addEffect(t){let i=t;return i instanceof ct||(i=new kh(i)),i.gameObject===void 0&&this.gameObject.addComponent(i),this._effects.includes(i)||(this._effects.push(i),this._isDirty=!0),t}removeEffect(t){var i,n,o,r;let l=-1;if(t instanceof ct?l=this._effects.indexOf(t):l=this._effects.findIndex(c=>c instanceof kh&&c.effect===t),l!==-1)return this._effects.splice(l,1),this._isDirty=!0,t;if(t instanceof ct){const c=(n=(i=this.sharedProfile)==null?void 0:i.components)==null?void 0:n.indexOf(t);c!==void 0&&c!==-1&&(this._isDirty=!0,(r=(o=this.sharedProfile)==null?void 0:o.components)==null||r.splice(c,1))}return t}markDirty(){this._isDirty=!0}awake(){var t;El&&(console.log("PostprocessingManager Awake",this),console.log("Press P to toggle post processing"),window.addEventListener("keydown",i=>{i.key==="p"&&(this.enabled=!this.enabled,De("Toggle PostProcessing "+this.name+": Enabled="+this.enabled),this.markDirty())})),(t=this.sharedProfile)==null||t.__init(this)}onEnable(){this._componentEnabledTime=this.context.time.realtimeSinceStartup,this._isDirty=!0}onDisable(){var t;(t=this._postprocessing)==null||t.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)){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);const t=this.context.composer;if(this.multisampling==="auto"){const i=this.context.time.realtimeSinceStartup-this._multisampleAutoChangeTime;if(this.context.time.realtimeSinceStartup-this._componentEnabledTime>2&&i>.5){const n=t.multisampling;t.multisampling>0&&this.context.time.smoothedFps<=50?(this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup,this._multisampleAutoDecreaseTime=this.context.time.realtimeSinceStartup,t.multisampling*=.5,t.multisampling=Math.floor(t.multisampling),El&&console.debug(`[PostProcessing] Reduced multisampling from ${n} to ${t.multisampling}`)):i>1&&this.context.time.smoothedFps>=59&&t.multisampling<this.context.renderer.capabilities.maxSamples&&this.context.time.realtimeSinceStartup-this._multisampleAutoDecreaseTime>10&&(this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup,t.multisampling=t.multisampling<=0?1:t.multisampling*2,t.multisampling=Math.floor(t.multisampling),El&&console.debug(`[PostProcessing] Increased multisampling from ${n} to ${t.multisampling}`))}}else t.multisampling=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples));if(this.context.mainCamera){const i=this.context.composer.passes;for(const n of i)if(n.mainCamera&&n.mainCamera!==this.context.mainCamera){this.context.composer.setMainCamera(this.context.mainCamera);break}}}}onDestroy(){var t;(t=this._postprocessing)==null||t.dispose()}apply(){var t,i;if(El&&console.log(`Apply PostProcessing "${this.name}"`),F()&&(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.unapply(),this._activeEffects.length=0,(t=this.sharedProfile)!=null&&t.components){const n=this.sharedProfile.components;for(const o of n)o.active&&o.enabled&&!this._activeEffects.includes(o)&&this._activeEffects.push(o)}for(const n of this._effects)n.active&&n.enabled&&!this._activeEffects.includes(n)&&this._activeEffects.push(n);this._activeEffects.length>0&&(this._postprocessing||(this._postprocessing=new ny(this.context)),(i=this._postprocessing.apply(this._activeEffects))==null||i.then(()=>{var n;if(!this.activeAndEnabled)return;this._applyPostQueue();const o=(n=this._postprocessing)==null?void 0:n.composer;o?(this.multisampling==="auto"?o.multisampling=X.isMobileDevice()?2:4:o.multisampling=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples)),El&&console.debug(`[PostProcessing] Set multisampling to ${o.multisampling} (Is Mobile: ${X.isMobileDevice()})`)):El&&console.warn("[PostProcessing] No composer found")}))}unapply(){var t;(t=this._postprocessing)==null||t.unapply()}_applyPostQueue(){if(this._modificationQueue){for(const t of this._modificationQueue.values())this.onEditorModification(t);this._modificationQueue.clear()}}onEditorModification(t){var i,n;if(t.propertyName.startsWith("postprocessing.")){if(!this._postprocessing)return this._modificationQueue||(this._modificationQueue=new Map),this._modificationQueue.set(t.propertyName,t),!0;if(!((i=this._activeEffects)!=null&&i.length))return;const o=t.propertyName.split(".");if(o.length===3||o.length===4){const r=o[1],l=o[2];for(const c of this._activeEffects)if(((n=c.typeName)==null?void 0:n.toLowerCase())===r.toLowerCase()){if(l==="active"){c.active=t.value,this.scheduleRecreate();return}if(!Ip.has(r)){const h=new Array;Ip.set(r,h);const d=Object.keys(c);for(const u of d)c[u]instanceof N&&h.push(u)}if(Ip.has(r)){const h=l.toLowerCase(),d=Ip.get(r);for(const u of d)if(u.toLowerCase()===h){const p=c[u];p instanceof N&&(o.length===4&&o[3]==="active"?(p.overrideState=t.value,this.scheduleRecreate()):p&&p.value!==void 0&&(p.value=t.value));return}}console.warn("Unknown modification",l);return}}return!0}return!1}scheduleRecreate(){const t=++this._recreateId;setTimeout(()=>{t===this._recreateId&&(this.onDisable(),this.onEnable())},200)}}_1([Pr(Rp)],Al.prototype,"sharedProfile",2),_1([Pr()],Al.prototype,"multisampling",2);const Ip=new Map;JE(Al);async function oy(s){const{NeedleEngineHTMLElement:t}=await Promise.resolve().then(()=>Ij);t.observedAttributes.includes(s)||t.observedAttributes.push(s)}var qA=Object.defineProperty,GA=Object.getOwnPropertyDescriptor,St=(s,t,i,n)=>{for(var o=n>1?void 0:n?GA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&qA(t,i,o),o};const ti=C("debugsceneswitcher"),XA=C("sceneswitcher:clearscene"),jp="scene";oy(jp);const Go=Promise.resolve(!1);class ot extends A{constructor(){super(...arguments),a(this,"autoLoadFirstScene",!0),a(this,"scenes",[]),a(this,"loadingScene"),a(this,"queryParameterName","scene"),a(this,"useSceneName",!0),a(this,"clamp",!0),a(this,"useHistory",!0),a(this,"useKeyboard",!0),a(this,"useSwipe",!0),a(this,"useSceneLighting",!0),a(this,"useSceneBackground",!0),a(this,"preloadNext",1),a(this,"preloadPrevious",1),a(this,"preloadConcurrent",2),a(this,"createMenuButtons",!1),a(this,"sceneLoadingStart",new Se),a(this,"sceneLoadingProgress",new Se),a(this,"sceneLoaded",new Se),a(this,"_currentIndex",-1),a(this,"_currentScene"),a(this,"_engineElementOverserver"),a(this,"_preloadScheduler"),a(this,"_menuButtons"),a(this,"onPopState",async t=>{if(!this.useHistory)return;const i=this.useHistory;try{this.useHistory=!1;let n=!1;if(this.queryParameterName&&(n=await this.tryLoadFromQueryParam()),!n){const o=t?.state;if(o&&o.startsWith(this.guid)){const r=o.substr(this.guid.length+2);ti&&console.log("PopState",r),await this.trySelectSceneFromValue(r)}}}finally{this.useHistory=i}}),a(this,"normalizedSwipeThresholdX",.1),a(this,"_didSwipe",!1),a(this,"onInputPointerMove",t=>{if(this.useSwipe&&!this._didSwipe&&t.button===0&&t.pointerType==="touch"&&this.context.input.getPointerPressedCount()===1){const i=this.context.input.getPointerPositionDelta(t.button);if(i){const n=i.x/this.context.domWidth;n>=this.normalizedSwipeThresholdX?(this._didSwipe=!0,this.selectPrev()):n<=-this.normalizedSwipeThresholdX&&(this._didSwipe=!0,this.selectNext())}}}),a(this,"onInputPointerUp",t=>{t.button===0&&(this._didSwipe=!1)}),a(this,"onInputKeyDown",t=>{if(!this.useKeyboard||!this.scenes)return;const i=t.key.toLowerCase();if(!i)return;const n=parseInt(i)-1;if(n>=0){this.trySelectSceneFromValue(n);return}switch(i){case"arrowright":case"d":this.selectNext();break;case"arrowleft":case"a":this.selectPrev();break}}),a(this,"__lastSwitchScene"),a(this,"__lastSwitchScenePromise"),a(this,"_currentlyLoadingScene"),a(this,"_lastLoadingScene"),a(this,"_loadingScenePromise"),a(this,"_isCurrentlyLoading",!1),a(this,"_currentLoadingProgress")}get currentIndex(){return this._currentIndex}get currentLoadingProgress(){return this._currentLoadingProgress}get currentlyLoadingScene(){return this._currentlyLoadingScene}get currentlyLoadedScene(){return this._currentScene}awake(){this.scenes===void 0&&(this.scenes=[]);for(const t of this.scenes)t&&!t.hasUrl&&t.asset instanceof I&&t.asset.removeFromParent();ti&&console.log("SceneSwitcher",this)}async onEnable(){if(globalThis.addEventListener("popstate",this.onPopState),this.context.input.addEventListener(Be.KeyDown,this.onInputKeyDown),this.context.input.addEventListener(Be.PointerMove,this.onInputPointerMove),this.context.input.addEventListener(Be.PointerUp,this.onInputPointerUp),this._engineElementOverserver||(this._engineElementOverserver=new MutationObserver(t=>{for(const i of t)if(i.type==="attributes"&&i.attributeName===jp){const n=this.context.domElement.getAttribute(jp);n!==null&&this.trySelectSceneFromValue(n)}})),this._engineElementOverserver.observe(this.context.domElement,{attributes:!0}),this._preloadScheduler||(this._preloadScheduler=new QA(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 t=this.context.domElement.getAttribute(jp);try{(t===null||!await this.trySelectSceneFromValue(t))&&this._currentIndex===-1&&this.select(0)}finally{}}this.createMenuButtons&&(this._menuButtons??(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(){var t;if(globalThis.removeEventListener("popstate",this.onPopState),this.context.input.removeEventListener(Be.KeyDown,this.onInputKeyDown),this.context.input.removeEventListener(Be.PointerMove,this.onInputPointerMove),this.context.input.removeEventListener(Be.PointerUp,this.onInputPointerUp),(t=this._preloadScheduler)==null||t.stop(),this._menuButtons){for(const i of this._menuButtons)i.remove();this._menuButtons=void 0}}addScene(t){if(typeof t=="string"){let i=this.context.addressables.findAssetReference(t);return i||(i=new le(t),this.context.addressables.registerAssetReference(i)),this.scenes.push(i),i}return this.scenes.push(t),t}selectNext(){return this.select(this._currentIndex+1)}selectPrev(){return this.select(this._currentIndex-1)}select(t){var i,n,o;if(ti&&console.log("select",t),typeof t=="object"&&console.warn('Switching to "'+t+'" might not work. Please either use an index or a AssetReference (not a scene reference)'),typeof t=="string"){const l=(i=this.scenes)==null?void 0:i.find(c=>c.url===t);if(!l){const c=le.getOrCreate(this.sourceId??"",t,this.context);return this.switchScene(c)}if(l)t=(n=this.scenes)==null?void 0:n.indexOf(l);else return Go}if(!((o=this.scenes)!=null&&o.length))return Go;if(t<0){if(this.clamp)return Go;t=this.scenes.length-1}else if(t>=this.scenes.length){if(this.clamp)return Go;t=0}const r=this.scenes[t];return this.switchScene(r)}unload(){return this.__lastSwitchScene=void 0,this.__lastSwitchScenePromise=void 0,this.__unloadCurrentScene()}async reload(){if(this.__lastSwitchScene){const t=this.__lastSwitchScene;return this.__lastSwitchScene=void 0,this.switchScene(t)}return!1}async switchScene(t){if(!(t instanceof le)){const i=typeof t;return i==="string"?this.select(t):i==="number"?this.select(t):(console.warn("SceneSwitcher: Can't switch to scene",t,"of type",i),!1)}return t.url===this.sourceId?(console.warn("SceneSwitcher: can't load own scene - prevent recursive loading",this.sourceId),!1):this.__lastSwitchScene===t&&this.__lastSwitchScenePromise?this.__lastSwitchScenePromise:(this.__lastSwitchScene=t,this.__lastSwitchScenePromise=this.__internalSwitchScene(t),await this.__lastSwitchScenePromise)}async __unloadCurrentScene(){const t=this._currentScene;if(this._currentScene=void 0,t){ti&&console.log("UNLOAD",t.url,"HasURL?: "+t.hasUrl);const i=this.tryGetSceneEventListener(t.asset);if(i!=null&&i.sceneClosing){const n=i.sceneClosing();n instanceof Promise&&await n}t.hasUrl?t.unload():t.asset instanceof I&&t.asset.removeFromParent()}}async __internalSwitchScene(t){var i,n,o,r,l;await this.__unloadCurrentScene();const c=this._currentIndex=((i=this.scenes)==null?void 0:i.indexOf(t))??-1;try{this._currentlyLoadingScene=t,this._currentLoadingProgress=new ProgressEvent("progress",{loaded:0,total:1});const h=new CustomEvent("loadscene-start",{detail:{scene:t,switcher:this,index:c}});this.dispatchEvent(h),(n=this.sceneLoadingStart)==null||n.invoke(h.detail),await this.onStartLoading(),await t.loadAssetAsync((u,p)=>{var g;this._currentLoadingProgress=p,this.dispatchEvent(p),(g=this.sceneLoadingProgress)==null||g.invoke(p)}).catch(console.error),await this.onEndLoading();const d=new CustomEvent("loadscene-finished",{detail:{scene:t,switcher:this,index:c}});if(this.dispatchEvent(d),this._currentLoadingProgress=void 0,this._currentlyLoadingScene=void 0,d.defaultPrevented)return ti&&console.warn("Adding loaded scene prevented:",t,d),!1;if(!t.asset)return ti&&console.warn("Failed loading scene:",t),!1;if(this._currentIndex===c){if(ti&&console.log("ADD",t.url),this._currentScene=t,XA){const g=((o=this.context.mainCameraComponent)==null?void 0:o.gameObject)||this.context.mainCamera;g?.removeFromParent();const y=this.gameObject.removeFromParent();Ri(this.context.scene,!0,!0),this.context.scene=new Vi,this.context.scene.add(y),g&&this.context.scene.add(g)}if(O.add(t.asset,this.gameObject),this.useSceneLighting&&this.context.sceneLighting.enable(t),this.useSceneBackground){const g=this.context.lightmaps.tryGetSkybox(t.url);g?(g.mapping=yn,this.context.scene.background=g):ti&&console.warn("SceneSwitcher: Can't find skybox for scene "+t.url)}if(this.useHistory&&c>=0){let g=c.toString();if(this.useSceneName&&(g=w1(t.url)),(r=this.queryParameterName)!=null&&r.length)Yl(this.queryParameterName,g,this.useHistory);else{const y=history.state,f=this.guid+"::"+c;y!==f&&history.pushState(f,"unused",location.href)}}const u=this.tryGetSceneEventListener(t.asset);if(u!=null&&u.sceneOpened){const g=u.sceneOpened(this);g instanceof Promise&&await g}const p=new CustomEvent("scene-opened",{detail:{scene:t,switcher:this,index:c}});return this.dispatchEvent(p),(l=this.sceneLoaded)==null||l.invoke(this),!0}}catch(h){console.error(h)}return!1}preload(t){if(t>=0&&t<this.scenes.length){const i=this.scenes[t];if(i instanceof le)return i.preload()}return Go}tryLoadFromQueryParam(){var t;if(!((t=this.queryParameterName)!=null&&t.length))return Go;const i=C(this.queryParameterName);return typeof i=="boolean"?Go:this.trySelectSceneFromValue(i)}trySelectSceneFromValue(t){if(typeof t=="string"){const i=parseInt(t);if(i>=0&&i<this.scenes.length)return this.select(i);{const n=t.toLowerCase();for(let o=0;o<this.scenes.length;o++){const r=this.scenes[o];if(r&&w1(r.url).toLowerCase().includes(n))return this.select(o)}}}else if(typeof t=="number"&&t>=0&&t<this.scenes.length)return this.select(t);return Gt()&&console.warn('Can not find scene: "'+t+'"',this),Go}async onStartLoading(){var t,i;if(this._isCurrentlyLoading=!0,this.loadingScene&&(this._lastLoadingScene!==this.loadingScene&&(this._loadingScenePromise=void 0),this._lastLoadingScene=this.loadingScene,this._loadingScenePromise||(this._loadingScenePromise=(t=this.loadingScene)==null?void 0:t.loadAssetAsync().then(n=>n!=null)),await this._loadingScenePromise,this._isCurrentlyLoading&&(i=this.loadingScene)!=null&&i.asset)){ti&&console.log("Add loading scene",this.loadingScene.url,this.loadingScene.asset);const n=this.loadingScene.asset;O.add(n,this.gameObject);const o=this.tryGetSceneEventListener(n);if(o!=null&&o.sceneOpened){const r=o.sceneOpened(this);r instanceof Promise&&await r}}if(this._isCurrentlyLoading){const n=this.tryGetSceneEventListener(this.gameObject);if(n&&n.sceneOpened){const o=n.sceneOpened(this);o instanceof Promise&&await o}}}async onEndLoading(){var t;if(this._isCurrentlyLoading=!1,(t=this.loadingScene)!=null&&t.asset){ti&&console.log("Remove loading scene",this.loadingScene.url);const i=this.loadingScene.asset,n=this.tryGetSceneEventListener(i);if(typeof n?.sceneClosing=="function"){const o=n.sceneClosing();o instanceof Promise&&await o}O.remove(i)}if(!this._isCurrentlyLoading){const i=this.tryGetSceneEventListener(this.gameObject);if(i&&i.sceneClosing){const n=i.sceneClosing();n instanceof Promise&&await n}}}tryGetSceneEventListener(t,i=0){if(!t)return null;const n=O.foreachComponent(t,o=>{const r=o;if(r.sceneClosing||r.sceneOpened)return r});if(i===0&&!n&&t.children.length)for(const o of t.children){const r=this.tryGetSceneEventListener(o,i+1);if(r)return r}return n||null}}St([m()],ot.prototype,"autoLoadFirstScene",2),St([m(le)],ot.prototype,"scenes",2),St([m(le)],ot.prototype,"loadingScene",2),St([m()],ot.prototype,"queryParameterName",2),St([m()],ot.prototype,"useSceneName",2),St([m()],ot.prototype,"clamp",2),St([m()],ot.prototype,"useHistory",2),St([m()],ot.prototype,"useKeyboard",2),St([m()],ot.prototype,"useSwipe",2),St([m()],ot.prototype,"useSceneLighting",2),St([m()],ot.prototype,"useSceneBackground",2),St([m()],ot.prototype,"preloadNext",2),St([m()],ot.prototype,"preloadPrevious",2),St([m()],ot.prototype,"preloadConcurrent",2),St([m()],ot.prototype,"createMenuButtons",2),St([m(Se)],ot.prototype,"sceneLoadingStart",2),St([m(Se)],ot.prototype,"sceneLoadingProgress",2),St([m(Se)],ot.prototype,"sceneLoaded",2);function w1(s){const t=s.split("/").pop(),i=t?.split(".").shift();return i!=null&&i.length?i:s}class QA{constructor(t,i=1,n=1,o=2){a(this,"maxLoadAhead"),a(this,"maxLoadBehind"),a(this,"maxConcurrent"),a(this,"_isRunning",!1),a(this,"_switcher"),a(this,"_loadTasks",[]),a(this,"_maxConcurrentLoads",1),this._switcher=t,this.maxLoadAhead=i,this.maxLoadBehind=n,this.maxConcurrent=o}begin(t){if(this._isRunning)return;ti&&console.log("Preload begin",{delay:t}),this._isRunning=!0;let i=-10,n,o;const r=this._switcher.scenes,l=Date.now()+t,c=setInterval(()=>{if(this.allLoaded()&&(ti&&console.log("All scenes (pre-)loaded"),this.stop()),!this._isRunning){clearInterval(c);return}if(Date.now()<l||this.canLoadNewScene()===!1)return;(i===-10||i!==this._switcher.currentIndex)&&(i=this._switcher.currentIndex,o=0,n=0);const h=o%2===0;h&&(n+=1),o+=1;const d=h?this.maxLoadAhead:this.maxLoadBehind;if(n>d)return;const u=h?i+n:i-n;if(!(u<0)&&!(u<0||u>=r.length)&&!this._loadTasks.some(p=>p.index===u)){const p=r[u];ti&&console.log("Preload scene",{roomIndex:u,searchForward:h,lastRoom:i,currentIndex:this._switcher.currentIndex,tasks:this._loadTasks.length},p?.url),new YA(u,p,this._loadTasks)}},200)}stop(){this._isRunning=!1}canLoadNewScene(){return this._loadTasks.length<this._maxConcurrentLoads}allLoaded(){if(this._switcher.scenes){for(const t of this._switcher.scenes)if(t?.isLoaded()===!1)return!1}return!0}}class YA{constructor(t,i,n){a(this,"index"),a(this,"asset"),a(this,"tasks"),this.index=t,this.asset=i,this.tasks=n,n.push(this),this.awaitLoading()}async awaitLoading(){this.asset&&!this.asset.isLoaded()&&(ti&&console.log("Preload start: "+this.asset.url,this.index),await this.asset.preload(),ti&&console.log("Preload finished: "+this.asset.url,this.index));const t=this.tasks.indexOf(this);t>=0&&this.tasks.splice(t,1)}}function ZA(){return new Promise((s,t)=>{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 KA(s){await ZA(),s()}var JA=Object.defineProperty,eI=Object.getOwnPropertyDescriptor,Bi=(s,t,i,n)=>{for(var o=n>1?void 0:n?eI(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&JA(t,i,o),o};const Ct=C("debugvideo");var x1=(s=>(s[s.None=0]="None",s[s.AdjustHeight=1]="AdjustHeight",s[s.AdjustWidth=2]="AdjustWidth",s))(x1||{}),S1=(s=>(s[s.VideoClip=0]="VideoClip",s[s.Url=1]="Url",s))(S1||{}),C1=(s=>(s[s.CameraFarPlane=0]="CameraFarPlane",s[s.CameraNearPlane=1]="CameraNearPlane",s[s.RenderTexture=2]="RenderTexture",s[s.MaterialOverride=3]="MaterialOverride",s))(C1||{});class gt extends A{constructor(){super(),a(this,"playOnAwake",!0),a(this,"aspectMode",0),a(this,"clip",null),a(this,"source",1),a(this,"_url",null),a(this,"renderMode"),a(this,"targetMaterialProperty"),a(this,"targetMaterialRenderer"),a(this,"targetTexture"),a(this,"time",0),a(this,"_playbackSpeed",1),a(this,"_isLooping",!1),a(this,"_muted",!1),a(this,"_audioOutputMode",2),a(this,"playInBackground",!0),a(this,"_crossOrigin","anonymous"),a(this,"_videoElement",null),a(this,"_videoTexture",null),a(this,"_videoMaterial",null),a(this,"_isPlaying",!1),a(this,"wasPlaying",!1),a(this,"visibilityChanged",t=>{switch(document.visibilityState){case"hidden":this.playInBackground||(this.wasPlaying=this._isPlaying,this.pause());break;case"visible":this.wasPlaying&&!this._isPlaying&&this.play();break}}),a(this,"_receivedInput",!1),a(this,"_overlay",null),a(this,"_targetObjects"),a(this,"_updateAspectRoutineId",-1),a(this,"_hls"),a(this,"onHlsAvailable",()=>{var t;Ct&&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),(t=this._videoElement)==null||t.play(),Ct&&console.log("HLS: loaded",this.clip))}),KA(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[],C("videoscreenspace")&&window.addEventListener("keydown",t=>{t.key==="f"&&(this.screenspace=!this.screenspace)})}get url(){return this._url}set url(t){const i=this._url!==t;this.__didAwake?i&&this.setClipURL(t??""):this._url=t}get playbackSpeed(){var t;return((t=this._videoElement)==null?void 0:t.playbackRate)??this._playbackSpeed}set playbackSpeed(t){this._playbackSpeed=t,this._videoElement&&(this._videoElement.playbackRate=t)}get isLooping(){var t;return((t=this._videoElement)==null?void 0:t.loop)??this._isLooping}set isLooping(t){this._isLooping=t,this._videoElement&&(this._videoElement.loop=t)}get currentTime(){var t;return((t=this._videoElement)==null?void 0:t.currentTime)??this.time}set currentTime(t){this._videoElement?this._videoElement.currentTime=t:this.time=t}get isPlaying(){const t=this._videoElement;return!!(t&&(t.currentTime>0&&!t.paused&&!t.ended&&t.readyState>t.HAVE_CURRENT_DATA||t.srcObject&&t.srcObject.active))}get crossOrigin(){var t;return((t=this._videoElement)==null?void 0:t.crossOrigin)??this._crossOrigin}set crossOrigin(t){this._crossOrigin=t,this._videoElement&&(t!==null?this._videoElement.setAttribute("crossorigin",t):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(){var t;return((t=this._videoElement)==null?void 0:t.muted)??this._muted}set muted(t){this._muted=t,this._videoElement&&(this._videoElement.muted=t)}get currentVideo(){return this.clip}set audioOutputMode(t){t!==this._audioOutputMode&&(t===1&&F()&&console.warn("VideoAudioOutputMode.AudioSource is not yet implemented"),this._audioOutputMode=t,this.updateVideoElementSettings())}get audioOutputMode(){return this._audioOutputMode}preloadVideo(){Ct&&console.log("Video Preload: "+this.name,this.clip),this.create(!1)}preload(){this.preloadVideo()}setVideo(t){this.clip=t,this.source=0,this._videoElement?(this._videoElement.srcObject=t,this._isPlaying&&this.play(),this.updateAspect()):this.create(this.playOnAwake)}setClipURL(t){this._url!==t&&(this._url=t,this.source=1,Ct&&console.log("set url",t),this._videoElement?t.endsWith(".m3u8")||t.includes(".m3u")?this.ensureM3UCanBePlayed():(this._videoElement.src=t,this._isPlaying&&(this.stop(),this.play())):this.create(this.playOnAwake))}onEnable(){var t,i;Ct&&console.log("VideoPlayer.onEnable",S1[this.source],this.clip,this.url,this),window.addEventListener("visibilitychange",this.visibilityChanged),this.playOnAwake===!0?this.create(!0):this.preloadVideo(),this.screenspace?(t=this._overlay)==null||t.start():(i=this._overlay)==null||i.stop()}onDisable(){var t;window.removeEventListener("visibilitychange",this.visibilityChanged),(t=this._overlay)==null||t.stop(),this.pause()}onDestroy(){var t;this._videoElement&&((t=this.videoElement)==null||t.remove(),this._videoElement=null),this._videoTexture&&(this._videoTexture.dispose(),this._videoTexture=null)}play(){var t,i;if(this._videoElement||this.create(!1),!this._videoElement){Ct&&console.warn("Can not play: no video element found",this);return}if(!(this._isPlaying&&!((t=this._videoElement)!=null&&t.ended)&&!((i=this._videoElement)!=null&&i.paused))){if(this._isPlaying=!0,this._receivedInput||(this._videoElement.muted=!0),this.handleBeginPlaying(!1),this.shouldUseM3U){this.ensureM3UCanBePlayed();return}Ct&&console.log("Video Play()",this.clip,this._videoElement,this.time),this._videoElement.currentTime=this.time,this._videoElement.play().catch(n=>{var o;console.log(n),Ct&&console.error("Error playing video",n,"CODE="+n.code,(o=this.videoElement)==null?void 0:o.src,this),setTimeout(()=>{this._isPlaying&&!this.destroyed&&this.activeAndEnabled&&this.play()},1e3)}),Ct&&console.log("play",this._videoElement,this.time)}}stop(){this._isPlaying=!1,this.time=0,this._videoElement&&(this._videoElement.currentTime=0,this._videoElement.pause(),Ct&&console.log("STOP",this))}pause(){var t,i;this.time=((t=this._videoElement)==null?void 0:t.currentTime)??0,this._isPlaying=!1,(i=this._videoElement)==null||i.pause(),Ct&&console.log("PAUSE",this,this.currentTime)}create(t){let i;switch(this.source){case 0:i=this.clip;break;case 1:i=this.url,!(i!=null&&i.length)&&typeof this.clip=="string"&&(i=this.clip);break}return i?(this._videoElement||(Ct&&console.warn("Create VideoElement",this),this._videoElement=this.createVideoElement(),this.context.domElement.shadowRoot.prepend(this._videoElement),this.updateVideoElementStyles()),typeof i=="string"?(Ct&&console.log("Set Video src",i),this._videoElement.src=i):(Ct&&console.log("Set Video srcObject",i),this._videoElement.srcObject=i),this._videoTexture||(this._videoTexture=new xC(this._videoElement)),this._videoTexture.flipY=!1,this._videoTexture.colorSpace=ms,t&&this.handleBeginPlaying(t),Ct&&console.log("Video: handle playing done...",i,t),!0):(Ct&&console.warn("No video source set",this),!1)}updateAspect(){this.aspectMode!==0&&this.startCoroutine(this.updateAspectImpl())}get screenspace(){var t;return((t=this._overlay)==null?void 0:t.enabled)??!1}set screenspace(t){var i;if(t){if(!this._videoTexture)return;this._overlay||(this._overlay=new tI(this.context)),this._overlay.add(this._videoTexture)}else(i=this._overlay)==null||i.remove(this._videoTexture);this._overlay&&(this._overlay.enabled=t)}createVideoElement(){const t=document.createElement("video");return this._crossOrigin&&t.setAttribute("crossorigin",this._crossOrigin),Ct&&console.log("created video element",t),t}handleBeginPlaying(t){var i,n;if(!this.activeAndEnabled||!this._videoElement)return;this._targetObjects.length=0;let o=this.gameObject;switch(this.renderMode){case 3:o=(i=this.targetMaterialRenderer)==null?void 0:i.gameObject,o||(o=(n=O.getComponent(this.gameObject,Ze))==null?void 0:n.gameObject);break;case 2:console.error("VideoPlayer renderTexture not implemented yet. Please use material override instead");return}if(!o){console.error("Missing target for video material renderer",this.name,C1[this.renderMode],this);return}const r=o.material;if(r){this._targetObjects.push(o),r!==this._videoMaterial&&(this._videoMaterial=r.clone(),o.material=this._videoMaterial);const l="map",c=this._videoMaterial;if(!this.targetMaterialProperty)c[l]=this._videoTexture;else switch(this.targetMaterialProperty){default:c[l]=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(),t&&(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 t=!this._receivedInput||this.audioOutputMode===0;!t&&this._muted&&(t=!0),this._videoElement.muted=t,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())}*updateAspectImpl(){const t=++this._updateAspectRoutineId,i=void 0,n=this.clip;for(;t===this._updateAspectRoutineId&&this.aspectMode!==0&&this.clip&&n===this.clip&&this._isPlaying;){if(!n||typeof n=="string")return;let o;for(const r of n.getVideoTracks()){const l=r.getSettings();if(l&&l.width&&l.height){o=l.width/l.height;break}else o=this.context.renderer.domElement.clientWidth/this.context.renderer.domElement.clientHeight}if(o===void 0){for(let r=0;r<10;r++)yield;if(!this.isPlaying)break;continue}if(i===o){yield;continue}for(const r of this._targetObjects){let l=1;if(r.parent){const c=Ye(r.parent);l=c.x/c.y}switch(this.aspectMode){case 1:r.scale.y=1/o*r.scale.x*l;break;case 2:r.scale.x=o*r.scale.y*l;break}}for(let r=0;r<3;r++)yield}}get shouldUseM3U(){return this.url!=null&&(this.url.endsWith(".m3u8")||this.url.endsWith(".m3u"))&&this.source===1}ensureM3UCanBePlayed(){if(!this.shouldUseM3U)return;let t=document.head.querySelector("script[data-hls_library]");t?globalThis.Hls?this.onHlsAvailable():t.addEventListener("load",this.onHlsAvailable):(Ct&&console.log("HLS: load script"),t=document.createElement("script"),t.dataset.hls_library="hls.js",t.src="https://cdn.jsdelivr.net/npm/hls.js@1",t.addEventListener("load",this.onHlsAvailable),document.head.append(t))}}Bi([m()],gt.prototype,"playOnAwake",2),Bi([m()],gt.prototype,"aspectMode",2),Bi([m(URL)],gt.prototype,"clip",2),Bi([m()],gt.prototype,"source",2),Bi([m(URL)],gt.prototype,"url",1),Bi([m()],gt.prototype,"renderMode",2),Bi([m()],gt.prototype,"targetMaterialProperty",2),Bi([m(Ze)],gt.prototype,"targetMaterialRenderer",2),Bi([m(Le)],gt.prototype,"targetTexture",2),Bi([m()],gt.prototype,"time",2),Bi([m()],gt.prototype,"playbackSpeed",1),Bi([m()],gt.prototype,"isLooping",1),Bi([m()],gt.prototype,"audioOutputMode",1);class tI{constructor(t){a(this,"context"),a(this,"_videos",[]),a(this,"_screenspaceModeQuad"),a(this,"_isInScreenspaceMode",!1),a(this,"_input"),this.context=t,this._input=new iI(this)}get enabled(){return this._isInScreenspaceMode}set enabled(t){t?this.start():this.stop()}add(t){this._videos.indexOf(t)===-1&&this._videos.push(t)}remove(t){if(!t)return;const i=this._videos.indexOf(t);i>=0&&this._videos.splice(i,1)}start(){var t;if(this._isInScreenspaceMode||this._videos.length<0)return;const i=this._videos[this._videos.length-1];if(!i)return;if(this._isInScreenspaceMode=!0,!this._screenspaceModeQuad){if(this._screenspaceModeQuad=po.createPrimitive(ur.Quad,{material:new sI(i)}),!this._screenspaceModeQuad)return;this._screenspaceModeQuad.geometry.scale(2,2,2)}const n=this._screenspaceModeQuad;this.context.scene.add(n),this.updateScreenspaceMaterialUniforms();const o=n.material;o?.reset(),(t=this._input)==null||t.enable(o)}stop(){var t;this._isInScreenspaceMode=!1,this._screenspaceModeQuad&&((t=this._input)==null||t.disable(),this._screenspaceModeQuad.removeFromParent())}updateScreenspaceMaterialUniforms(){var t;const i=(t=this._screenspaceModeQuad)==null?void 0:t.material;i&&(i.screenAspect=this.context.domElement.clientWidth/this.context.domElement.clientHeight)}}class iI{constructor(t){a(this,"_onResizeScreenFn"),a(this,"_onKeyUpFn"),a(this,"_onMouseWheelFn"),a(this,"context"),a(this,"overlay"),a(this,"_material"),a(this,"_isPinching",!1),a(this,"_lastPinch",0),this.overlay=t,this.context=t.context}enable(t){this._material=t,window.addEventListener("resize",this._onResizeScreenFn=()=>{this.overlay.updateScreenspaceMaterialUniforms()}),window.addEventListener("keyup",this._onKeyUpFn=o=>{o.key==="Escape"&&this.overlay.stop()}),window.addEventListener("wheel",this._onMouseWheelFn=o=>{this.overlay.enabled&&(t.zoom+=o.deltaY*5e-4,o.preventDefault())},{passive:!1});const i=new re;window.addEventListener("mousemove",o=>{if(this.overlay.enabled&&this.context.input.getPointerPressed(0)){const r=new re(o.movementX,o.movementY);r.x/=this.context.domElement.clientWidth,r.y/=this.context.domElement.clientHeight,i.set(r.x,r.y),i.multiplyScalar(t.zoom/-this.context.time.deltaTime*.01),t.offset=t.offset.add(i)}}),window.addEventListener("pointermove",o=>{this.overlay.enabled&&this.context.input.getPointerPressed(0)&&this.context.input.getTouchesPressedCount()===1&&(i.set(o.movementX,o.movementY),i.multiplyScalar(t.zoom*-this.context.time.deltaTime*.05),t.offset=t.offset.add(i))});let n=0;window.addEventListener("touchstart",o=>{if(o.touches.length<2){this.context.time.time-n<.3&&this.overlay.stop(),n=this.context.time.time;return}this._isPinching=!0,this._lastPinch=0}),window.addEventListener("touchmove",o=>{if(!this._isPinching||!this._material)return;const r=o.touches[0],l=o.touches[1],c=r.clientX-l.clientX,h=r.clientY-l.clientY,d=Math.sqrt(c*c+h*h);if(this._lastPinch!==0){const u=d-this._lastPinch;this._material.zoom-=u*.004}this._lastPinch=d}),window.addEventListener("touchend",()=>{this._isPinching=!1})}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 sI extends ps{constructor(t){super(),a(this,"_offset",new re),this.uniforms={map:{value:t},screenAspect:{value:1},offsetScale:{value:new fe(0,0,1,1)}},this.vertexShader=`
1269
+ `;class i extends j.POSTPROCESSING.MODULE.Effect{constructor(){super("Sharpening",t,{vertexShader:s,blendFunction:j.POSTPROCESSING.MODULE.BlendFunction.NORMAL,uniforms:new Map([["amount",new io(1)],["radius",new io(1)]])})}}return i}var UA=Object.defineProperty,NA=Object.getOwnPropertyDescriptor,Tl=(s,t,i,n)=>{for(var o=n>1?void 0:n?NA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&UA(t,i,o),o};class ln extends ct{constructor(){super(...arguments),a(this,"offset",new N(0)),a(this,"rotation",new N(0)),a(this,"focusArea",new N(.4)),a(this,"feather",new N(.3)),a(this,"kernelSize",new N(2)),a(this,"resolutionScale",new N(1/window.devicePixelRatio))}get typeName(){return"TiltShiftEffect"}init(){this.offset.defaultValue=0,this.rotation.defaultValue=0,this.focusArea.defaultValue=.4,this.feather.defaultValue=.3,this.kernelSize.defaultValue=j.POSTPROCESSING.MODULE.KernelSize.MEDIUM,this.resolutionScale.defaultValue=1/window.devicePixelRatio}onCreateEffect(){const t=new j.POSTPROCESSING.MODULE.TiltShiftEffect({kernelSize:j.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=i=>t.offset=i,this.rotation.onValueChanged=i=>t.rotation=i,this.focusArea.onValueChanged=i=>t.focusArea=i,this.feather.onValueChanged=i=>t.feather=i,this.kernelSize.onValueChanged=i=>t.blurPass.kernelSize=i,this.resolutionScale.onValueChanged=i=>t.resolution.scale=i/window.devicePixelRatio,t}}Tl([m(N)],ln.prototype,"offset",2),Tl([m(N)],ln.prototype,"rotation",2),Tl([m(N)],ln.prototype,"focusArea",2),Tl([m(N)],ln.prototype,"feather",2),Tl([m(N)],ln.prototype,"kernelSize",2),Tl([m(N)],ln.prototype,"resolutionScale",2),ns("TiltShiftEffect",ln);var WA=Object.defineProperty,VA=Object.getOwnPropertyDescriptor,ty=(s,t,i,n)=>{for(var o=n>1?void 0:n?VA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&WA(t,i,o),o};class ea extends ct{constructor(){super(...arguments),a(this,"color",new N({r:0,g:0,b:0,a:1})),a(this,"intensity",new N(0)),a(this,"center",new N({x:.5,y:.5}))}get typeName(){return"Vignette"}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 t=new j.POSTPROCESSING.MODULE.VignetteEffect;return this.intensity.onValueChanged=i=>{t.offset=i,this.updateDarkness(t)},this.color.onValueChanged=i=>{this.updateDarkness(t)},t}updateDarkness(t){const i=this.intensity.value;t.darkness=i}}ty([m(N)],ea.prototype,"color",2),ty([m(N)],ea.prototype,"intensity",2),ty([m(N)],ea.prototype,"center",2),ns("Vignette",ea),globalThis.false=globalThis.false!==void 0?globalThis.false:!0;const Gn=C("debugpost"),HA=C("debugpostpasses"),iy=Symbol("needle:postprocessing-handler"),sy=Symbol("needle:previous-autoclear-state");class ny{constructor(t){a(this,"_composer",null),a(this,"_lastVolumeComponents"),a(this,"_effects",[]),a(this,"_isActive",!1),a(this,"context"),a(this,"_menuEntry",null),a(this,"_passIndices",null),this.context=t}get isActive(){return this._isActive}get composer(){return this._composer}apply(t){return"env"in import.meta&&{}.VITE_NEEDLE_USE_POSTPROCESSING==="false"?(Gn?console.warn("Postprocessing is disabled via vite env setting"):console.debug("Postprocessing is disabled via vite env setting"),Promise.resolve()):(Gn?console.warn("Postprocessing is disabled via global vite define setting"):console.debug("Postprocessing is disabled via vite define"),Promise.resolve())}unapply(){var t;if(Gn&&console.log("Unapplying postprocessing effects"),this._isActive=!1,this._lastVolumeComponents){for(const n of this._lastVolumeComponents)n.unapply();this._lastVolumeComponents.length=0}const i=this.context;i[iy]===this&&delete i[iy],i.composer===this._composer&&((t=i.composer)==null||t.dispose(),i.composer=null),typeof i.renderer[sy]=="boolean"&&(i.renderer.autoClear=i.renderer[sy])}dispose(){this.unapply();for(const t of this._effects)t.dispose();this._effects.length=0,this._composer=null}async onApply(t,i){if(!i)return;await Promise.all([j.POSTPROCESSING.load(),j.POSTPROCESSING_AO.load()]),t[iy]=this,Gn&&console.log("Apply Postprocessing Effects",i),this._lastVolumeComponents=[...i],this._effects.length=0;const n={handler:this,components:this._lastVolumeComponents};for(let o=0;o<this._lastVolumeComponents.length;o++){const r=this._lastVolumeComponents[o];if(r.context=t,r.apply){if(r.active){if(!t.mainCameraComponent){console.error("No camera in scene found or available yet - can not create postprocessing effects");return}const l=r.apply(n);if(!l)continue;Array.isArray(l)?this._effects.push(...l):this._effects.push(l)}}else r.active&&we("Volume component is not a VolumeComponent: "+r.__type)}if(this.context.renderer.toneMapping!=fa&&!this._effects.find(o=>o instanceof j.POSTPROCESSING.MODULE.ToneMappingEffect)){const o=new j.POSTPROCESSING.MODULE.ToneMappingEffect;this._effects.push(o)}this.applyEffects(t)}applyEffects(t){const i=this._effects;if(i.length<=0)return;const n=t.mainCameraComponent,o=t.renderer,r=t.scene,l=n.threeCamera;o[sy]=o.autoClear,this._composer||(this._composer=new j.POSTPROCESSING.MODULE.EffectComposer(o,{frameBufferType:wC,stencilBuffer:!0})),t.composer&&t.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."),t.composer=this._composer;const c=t.composer;c.setMainCamera(l),c.setRenderer(o),c.setMainScene(r);for(const d of c.passes)d.dispose();c.removeAllPasses();const h=new j.POSTPROCESSING.MODULE.RenderPass(r,l);if(h.name="Render To Screen",h.mainScene=r,c.addPass(h),HA){this.orderEffects();for(const d of i)if(d instanceof j.POSTPROCESSING.MODULE.Effect){const u=new j.POSTPROCESSING.MODULE.EffectPass(l,d);u.name=d.name,c.addPass(u)}else d instanceof j.POSTPROCESSING.MODULE.Pass,c.addPass(d)}else try{this.orderEffects();const d=[];for(const u of i)u instanceof j.POSTPROCESSING.MODULE.Effect?d.push(u):(u instanceof j.POSTPROCESSING.MODULE.Pass,c.addPass(u));if(d.length>0){const u=new j.POSTPROCESSING.MODULE.EffectPass(l,...d);u.name=d.map(p=>p.name).join(" "),u.mainScene=r,u.enabled=!0,c.addPass(u)}}catch(d){console.error("Error while applying postprocessing effects",d),c.removeAllPasses()}if(Gn){console.log("[PostProcessing] Passes \u2192",c.passes);const d=new j.POSTPROCESSING.MODULE.DepthEffect({blendFunction:j.POSTPROCESSING.MODULE.BlendFunction.NORMAL,inverted:!0});d.name="Depth Effect";const u=new j.POSTPROCESSING.MODULE.EffectPass(l,d);if(u.name="Depth Effect Pass",u.enabled=!1,c.passes.push(u),this._passIndices!==null){const g=[c.passes[0]];this._passIndices.length>0&&this._passIndices[0]!==0&&g.push(...this._passIndices.map(y=>c.passes[y]).filter(y=>y)),g.length>0&&console.log("[PostProcessing] Passes (selected) \u2192",g),c.passes.length=0;for(const y of g)y.enabled=!0,c.addPass(y)}const p=this.context.menu;if(p&&this._passIndices===null){this._menuEntry&&this._menuEntry.remove();const g=document.createElement("select");g.multiple=!0;const y=document.createElement("option");y.innerText="Final Output",y.value="-1",g.appendChild(y);for(const f of c.passes){const v=document.createElement("option");v.innerText=f.name,v.value=`${c.passes.indexOf(f)}`,v.title=f.name,g.appendChild(v)}p.appendChild(g),this._menuEntry=g,g.addEventListener("change",()=>{const f=Array.from(g.selectedOptions).map(v=>parseInt(v.value));f.length===1&&f[0]===-1?this._passIndices=null:this._passIndices=f,this.applyEffects(t)})}}}orderEffects(){var t;Gn&&console.log("Before ordering effects",[...this._effects]),Ap??(Ap=[j.POSTPROCESSING.MODULE.NormalPass,j.POSTPROCESSING.MODULE.DepthDownsamplingPass,j.POSTPROCESSING.MODULE.SMAAEffect,j.POSTPROCESSING.MODULE.SSAOEffect,j.POSTPROCESSING_AO.MODULE.N8AOPostPass,j.POSTPROCESSING.MODULE.TiltShiftEffect,j.POSTPROCESSING.MODULE.DepthOfFieldEffect,j.POSTPROCESSING.MODULE.ChromaticAberrationEffect,j.POSTPROCESSING.MODULE.BloomEffect,j.POSTPROCESSING.MODULE.SelectiveBloomEffect,j.POSTPROCESSING.MODULE.VignetteEffect,j.POSTPROCESSING.MODULE.PixelationEffect,j.POSTPROCESSING.MODULE.ToneMappingEffect,j.POSTPROCESSING.MODULE.HueSaturationEffect,j.POSTPROCESSING.MODULE.BrightnessContrastEffect]);const i=this._effects;i.sort((n,o)=>{const r=Ap.findIndex(c=>n.constructor.name.endsWith(c.name)),l=Ap.findIndex(c=>o.constructor.name.endsWith(c.name));return r<0?(Gn&&console.warn("Unknown effect found: ",n.constructor.name),-1):l<0?(Gn&&console.warn("Unknown effect found: ",o.constructor.name),1):r<0?1:l<0?-1:r-l}),Gn&&console.log("After ordering effects",[...this._effects]);for(let n=0;n<i.length;n++){const o=i[n];if(((t=o?.configuration)==null?void 0:t.gammaCorrection)!==void 0){const r=n===i.length-1;o.configuration.gammaCorrection=r}}}}let Ap=null;var $A=Object.defineProperty,qA=Object.getOwnPropertyDescriptor,_1=(s,t,i,n)=>{for(var o=n>1?void 0:n?qA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&$A(t,i,o),o};const El=C("debugpost");class Al extends A{constructor(){super(...arguments),a(this,"sharedProfile"),a(this,"multisampling","auto"),a(this,"_postprocessing"),a(this,"_activeEffects",[]),a(this,"_effects",[]),a(this,"_componentEnabledTime",-1),a(this,"_multisampleAutoChangeTime",0),a(this,"_multisampleAutoDecreaseTime",0),a(this,"_lastApplyTime"),a(this,"_rapidApplyCount",0),a(this,"_isDirty",!1),a(this,"_modificationQueue"),a(this,"_recreateId",-1)}get isPostProcessingManager(){return!0}get effects(){return this._activeEffects}addEffect(t){let i=t;return i instanceof ct||(i=new kh(i)),i.gameObject===void 0&&this.gameObject.addComponent(i),this._effects.includes(i)||(this._effects.push(i),this._isDirty=!0),t}removeEffect(t){var i,n,o,r;let l=-1;if(t instanceof ct?l=this._effects.indexOf(t):l=this._effects.findIndex(c=>c instanceof kh&&c.effect===t),l!==-1)return this._effects.splice(l,1),this._isDirty=!0,t;if(t instanceof ct){const c=(n=(i=this.sharedProfile)==null?void 0:i.components)==null?void 0:n.indexOf(t);c!==void 0&&c!==-1&&(this._isDirty=!0,(r=(o=this.sharedProfile)==null?void 0:o.components)==null||r.splice(c,1))}return t}markDirty(){this._isDirty=!0}awake(){var t;El&&(console.log("PostprocessingManager Awake",this),console.log("Press P to toggle post processing"),window.addEventListener("keydown",i=>{i.key==="p"&&(this.enabled=!this.enabled,De("Toggle PostProcessing "+this.name+": Enabled="+this.enabled),this.markDirty())})),(t=this.sharedProfile)==null||t.__init(this)}onEnable(){this._componentEnabledTime=this.context.time.realtimeSinceStartup,this._isDirty=!0}onDisable(){var t;(t=this._postprocessing)==null||t.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)){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);const t=this.context.composer;if(this.multisampling==="auto"){const i=this.context.time.realtimeSinceStartup-this._multisampleAutoChangeTime;if(this.context.time.realtimeSinceStartup-this._componentEnabledTime>2&&i>.5){const n=t.multisampling;t.multisampling>0&&this.context.time.smoothedFps<=50?(this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup,this._multisampleAutoDecreaseTime=this.context.time.realtimeSinceStartup,t.multisampling*=.5,t.multisampling=Math.floor(t.multisampling),El&&console.debug(`[PostProcessing] Reduced multisampling from ${n} to ${t.multisampling}`)):i>1&&this.context.time.smoothedFps>=59&&t.multisampling<this.context.renderer.capabilities.maxSamples&&this.context.time.realtimeSinceStartup-this._multisampleAutoDecreaseTime>10&&(this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup,t.multisampling=t.multisampling<=0?1:t.multisampling*2,t.multisampling=Math.floor(t.multisampling),El&&console.debug(`[PostProcessing] Increased multisampling from ${n} to ${t.multisampling}`))}}else t.multisampling=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples));if(this.context.mainCamera){const i=this.context.composer.passes;for(const n of i)if(n.mainCamera&&n.mainCamera!==this.context.mainCamera){this.context.composer.setMainCamera(this.context.mainCamera);break}}}}onDestroy(){var t;(t=this._postprocessing)==null||t.dispose()}apply(){var t,i;if(El&&console.log(`Apply PostProcessing "${this.name}"`),F()&&(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.unapply(),this._activeEffects.length=0,(t=this.sharedProfile)!=null&&t.components){const n=this.sharedProfile.components;for(const o of n)o.active&&o.enabled&&!this._activeEffects.includes(o)&&this._activeEffects.push(o)}for(const n of this._effects)n.active&&n.enabled&&!this._activeEffects.includes(n)&&this._activeEffects.push(n);this._activeEffects.length>0&&(this._postprocessing||(this._postprocessing=new ny(this.context)),(i=this._postprocessing.apply(this._activeEffects))==null||i.then(()=>{var n;if(!this.activeAndEnabled)return;this._applyPostQueue();const o=(n=this._postprocessing)==null?void 0:n.composer;o?(this.multisampling==="auto"?o.multisampling=X.isMobileDevice()?2:4:o.multisampling=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples)),El&&console.debug(`[PostProcessing] Set multisampling to ${o.multisampling} (Is Mobile: ${X.isMobileDevice()})`)):El&&console.warn("[PostProcessing] No composer found")}))}unapply(){var t;(t=this._postprocessing)==null||t.unapply()}_applyPostQueue(){if(this._modificationQueue){for(const t of this._modificationQueue.values())this.onEditorModification(t);this._modificationQueue.clear()}}onEditorModification(t){var i,n;if(t.propertyName.startsWith("postprocessing.")){if(!this._postprocessing)return this._modificationQueue||(this._modificationQueue=new Map),this._modificationQueue.set(t.propertyName,t),!0;if(!((i=this._activeEffects)!=null&&i.length))return;const o=t.propertyName.split(".");if(o.length===3||o.length===4){const r=o[1],l=o[2];for(const c of this._activeEffects)if(((n=c.typeName)==null?void 0:n.toLowerCase())===r.toLowerCase()){if(l==="active"){c.active=t.value,this.scheduleRecreate();return}if(!Ip.has(r)){const h=new Array;Ip.set(r,h);const d=Object.keys(c);for(const u of d)c[u]instanceof N&&h.push(u)}if(Ip.has(r)){const h=l.toLowerCase(),d=Ip.get(r);for(const u of d)if(u.toLowerCase()===h){const p=c[u];p instanceof N&&(o.length===4&&o[3]==="active"?(p.overrideState=t.value,this.scheduleRecreate()):p&&p.value!==void 0&&(p.value=t.value));return}}console.warn("Unknown modification",l);return}}return!0}return!1}scheduleRecreate(){const t=++this._recreateId;setTimeout(()=>{t===this._recreateId&&(this.onDisable(),this.onEnable())},200)}}_1([Pr(Rp)],Al.prototype,"sharedProfile",2),_1([Pr()],Al.prototype,"multisampling",2);const Ip=new Map;JE(Al);async function oy(s){const{NeedleEngineHTMLElement:t}=await Promise.resolve().then(()=>jj);t.observedAttributes.includes(s)||t.observedAttributes.push(s)}var GA=Object.defineProperty,XA=Object.getOwnPropertyDescriptor,St=(s,t,i,n)=>{for(var o=n>1?void 0:n?XA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&GA(t,i,o),o};const ti=C("debugsceneswitcher"),QA=C("sceneswitcher:clearscene"),jp="scene";oy(jp);const Go=Promise.resolve(!1);class ot extends A{constructor(){super(...arguments),a(this,"autoLoadFirstScene",!0),a(this,"scenes",[]),a(this,"loadingScene"),a(this,"queryParameterName","scene"),a(this,"useSceneName",!0),a(this,"clamp",!0),a(this,"useHistory",!0),a(this,"useKeyboard",!0),a(this,"useSwipe",!0),a(this,"useSceneLighting",!0),a(this,"useSceneBackground",!0),a(this,"preloadNext",1),a(this,"preloadPrevious",1),a(this,"preloadConcurrent",2),a(this,"createMenuButtons",!1),a(this,"sceneLoadingStart",new Se),a(this,"sceneLoadingProgress",new Se),a(this,"sceneLoaded",new Se),a(this,"_currentIndex",-1),a(this,"_currentScene"),a(this,"_engineElementOverserver"),a(this,"_preloadScheduler"),a(this,"_menuButtons"),a(this,"onPopState",async t=>{if(!this.useHistory)return;const i=this.useHistory;try{this.useHistory=!1;let n=!1;if(this.queryParameterName&&(n=await this.tryLoadFromQueryParam()),!n){const o=t?.state;if(o&&o.startsWith(this.guid)){const r=o.substr(this.guid.length+2);ti&&console.log("PopState",r),await this.trySelectSceneFromValue(r)}}}finally{this.useHistory=i}}),a(this,"normalizedSwipeThresholdX",.1),a(this,"_didSwipe",!1),a(this,"onInputPointerMove",t=>{if(this.useSwipe&&!this._didSwipe&&t.button===0&&t.pointerType==="touch"&&this.context.input.getPointerPressedCount()===1){const i=this.context.input.getPointerPositionDelta(t.button);if(i){const n=i.x/this.context.domWidth;n>=this.normalizedSwipeThresholdX?(this._didSwipe=!0,this.selectPrev()):n<=-this.normalizedSwipeThresholdX&&(this._didSwipe=!0,this.selectNext())}}}),a(this,"onInputPointerUp",t=>{t.button===0&&(this._didSwipe=!1)}),a(this,"onInputKeyDown",t=>{if(!this.useKeyboard||!this.scenes)return;const i=t.key.toLowerCase();if(!i)return;const n=parseInt(i)-1;if(n>=0){this.trySelectSceneFromValue(n);return}switch(i){case"arrowright":case"d":this.selectNext();break;case"arrowleft":case"a":this.selectPrev();break}}),a(this,"__lastSwitchScene"),a(this,"__lastSwitchScenePromise"),a(this,"_currentlyLoadingScene"),a(this,"_lastLoadingScene"),a(this,"_loadingScenePromise"),a(this,"_isCurrentlyLoading",!1),a(this,"_currentLoadingProgress")}get currentIndex(){return this._currentIndex}get currentLoadingProgress(){return this._currentLoadingProgress}get currentlyLoadingScene(){return this._currentlyLoadingScene}get currentlyLoadedScene(){return this._currentScene}awake(){this.scenes===void 0&&(this.scenes=[]);for(const t of this.scenes)t&&!t.hasUrl&&t.asset instanceof I&&t.asset.removeFromParent();ti&&console.log("SceneSwitcher",this)}async onEnable(){if(globalThis.addEventListener("popstate",this.onPopState),this.context.input.addEventListener(Be.KeyDown,this.onInputKeyDown),this.context.input.addEventListener(Be.PointerMove,this.onInputPointerMove),this.context.input.addEventListener(Be.PointerUp,this.onInputPointerUp),this._engineElementOverserver||(this._engineElementOverserver=new MutationObserver(t=>{for(const i of t)if(i.type==="attributes"&&i.attributeName===jp){const n=this.context.domElement.getAttribute(jp);n!==null&&this.trySelectSceneFromValue(n)}})),this._engineElementOverserver.observe(this.context.domElement,{attributes:!0}),this._preloadScheduler||(this._preloadScheduler=new YA(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 t=this.context.domElement.getAttribute(jp);try{(t===null||!await this.trySelectSceneFromValue(t))&&this._currentIndex===-1&&this.select(0)}finally{}}this.createMenuButtons&&(this._menuButtons??(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(){var t;if(globalThis.removeEventListener("popstate",this.onPopState),this.context.input.removeEventListener(Be.KeyDown,this.onInputKeyDown),this.context.input.removeEventListener(Be.PointerMove,this.onInputPointerMove),this.context.input.removeEventListener(Be.PointerUp,this.onInputPointerUp),(t=this._preloadScheduler)==null||t.stop(),this._menuButtons){for(const i of this._menuButtons)i.remove();this._menuButtons=void 0}}addScene(t){if(typeof t=="string"){let i=this.context.addressables.findAssetReference(t);return i||(i=new le(t),this.context.addressables.registerAssetReference(i)),this.scenes.push(i),i}return this.scenes.push(t),t}selectNext(){return this.select(this._currentIndex+1)}selectPrev(){return this.select(this._currentIndex-1)}select(t){var i,n,o;if(ti&&console.log("select",t),typeof t=="object"&&console.warn('Switching to "'+t+'" might not work. Please either use an index or a AssetReference (not a scene reference)'),typeof t=="string"){const l=(i=this.scenes)==null?void 0:i.find(c=>c.url===t);if(!l){const c=le.getOrCreate(this.sourceId??"",t,this.context);return this.switchScene(c)}if(l)t=(n=this.scenes)==null?void 0:n.indexOf(l);else return Go}if(!((o=this.scenes)!=null&&o.length))return Go;if(t<0){if(this.clamp)return Go;t=this.scenes.length-1}else if(t>=this.scenes.length){if(this.clamp)return Go;t=0}const r=this.scenes[t];return this.switchScene(r)}unload(){return this.__lastSwitchScene=void 0,this.__lastSwitchScenePromise=void 0,this.__unloadCurrentScene()}async reload(){if(this.__lastSwitchScene){const t=this.__lastSwitchScene;return this.__lastSwitchScene=void 0,this.switchScene(t)}return!1}async switchScene(t){if(!(t instanceof le)){const i=typeof t;return i==="string"?this.select(t):i==="number"?this.select(t):(console.warn("SceneSwitcher: Can't switch to scene",t,"of type",i),!1)}return t.url===this.sourceId?(console.warn("SceneSwitcher: can't load own scene - prevent recursive loading",this.sourceId),!1):this.__lastSwitchScene===t&&this.__lastSwitchScenePromise?this.__lastSwitchScenePromise:(this.__lastSwitchScene=t,this.__lastSwitchScenePromise=this.__internalSwitchScene(t),await this.__lastSwitchScenePromise)}async __unloadCurrentScene(){const t=this._currentScene;if(this._currentScene=void 0,t){ti&&console.log("UNLOAD",t.url,"HasURL?: "+t.hasUrl);const i=this.tryGetSceneEventListener(t.asset);if(i!=null&&i.sceneClosing){const n=i.sceneClosing();n instanceof Promise&&await n}t.hasUrl?t.unload():t.asset instanceof I&&t.asset.removeFromParent()}}async __internalSwitchScene(t){var i,n,o,r,l;await this.__unloadCurrentScene();const c=this._currentIndex=((i=this.scenes)==null?void 0:i.indexOf(t))??-1;try{this._currentlyLoadingScene=t,this._currentLoadingProgress=new ProgressEvent("progress",{loaded:0,total:1});const h=new CustomEvent("loadscene-start",{detail:{scene:t,switcher:this,index:c}});this.dispatchEvent(h),(n=this.sceneLoadingStart)==null||n.invoke(h.detail),await this.onStartLoading(),await t.loadAssetAsync((u,p)=>{var g;this._currentLoadingProgress=p,this.dispatchEvent(p),(g=this.sceneLoadingProgress)==null||g.invoke(p)}).catch(console.error),await this.onEndLoading();const d=new CustomEvent("loadscene-finished",{detail:{scene:t,switcher:this,index:c}});if(this.dispatchEvent(d),this._currentLoadingProgress=void 0,this._currentlyLoadingScene=void 0,d.defaultPrevented)return ti&&console.warn("Adding loaded scene prevented:",t,d),!1;if(!t.asset)return ti&&console.warn("Failed loading scene:",t),!1;if(this._currentIndex===c){if(ti&&console.log("ADD",t.url),this._currentScene=t,QA){const g=((o=this.context.mainCameraComponent)==null?void 0:o.gameObject)||this.context.mainCamera;g?.removeFromParent();const y=this.gameObject.removeFromParent();Ri(this.context.scene,!0,!0),this.context.scene=new Vi,this.context.scene.add(y),g&&this.context.scene.add(g)}if(O.add(t.asset,this.gameObject),this.useSceneLighting&&this.context.sceneLighting.enable(t),this.useSceneBackground){const g=this.context.lightmaps.tryGetSkybox(t.url);g?(g.mapping=yn,this.context.scene.background=g):ti&&console.warn("SceneSwitcher: Can't find skybox for scene "+t.url)}if(this.useHistory&&c>=0){let g=c.toString();if(this.useSceneName&&(g=w1(t.url)),(r=this.queryParameterName)!=null&&r.length)Yl(this.queryParameterName,g,this.useHistory);else{const y=history.state,f=this.guid+"::"+c;y!==f&&history.pushState(f,"unused",location.href)}}const u=this.tryGetSceneEventListener(t.asset);if(u!=null&&u.sceneOpened){const g=u.sceneOpened(this);g instanceof Promise&&await g}const p=new CustomEvent("scene-opened",{detail:{scene:t,switcher:this,index:c}});return this.dispatchEvent(p),(l=this.sceneLoaded)==null||l.invoke(this),!0}}catch(h){console.error(h)}return!1}preload(t){if(t>=0&&t<this.scenes.length){const i=this.scenes[t];if(i instanceof le)return i.preload()}return Go}tryLoadFromQueryParam(){var t;if(!((t=this.queryParameterName)!=null&&t.length))return Go;const i=C(this.queryParameterName);return typeof i=="boolean"?Go:this.trySelectSceneFromValue(i)}trySelectSceneFromValue(t){if(typeof t=="string"){const i=parseInt(t);if(i>=0&&i<this.scenes.length)return this.select(i);{const n=t.toLowerCase();for(let o=0;o<this.scenes.length;o++){const r=this.scenes[o];if(r&&w1(r.url).toLowerCase().includes(n))return this.select(o)}}}else if(typeof t=="number"&&t>=0&&t<this.scenes.length)return this.select(t);return Gt()&&console.warn('Can not find scene: "'+t+'"',this),Go}async onStartLoading(){var t,i;if(this._isCurrentlyLoading=!0,this.loadingScene&&(this._lastLoadingScene!==this.loadingScene&&(this._loadingScenePromise=void 0),this._lastLoadingScene=this.loadingScene,this._loadingScenePromise||(this._loadingScenePromise=(t=this.loadingScene)==null?void 0:t.loadAssetAsync().then(n=>n!=null)),await this._loadingScenePromise,this._isCurrentlyLoading&&(i=this.loadingScene)!=null&&i.asset)){ti&&console.log("Add loading scene",this.loadingScene.url,this.loadingScene.asset);const n=this.loadingScene.asset;O.add(n,this.gameObject);const o=this.tryGetSceneEventListener(n);if(o!=null&&o.sceneOpened){const r=o.sceneOpened(this);r instanceof Promise&&await r}}if(this._isCurrentlyLoading){const n=this.tryGetSceneEventListener(this.gameObject);if(n&&n.sceneOpened){const o=n.sceneOpened(this);o instanceof Promise&&await o}}}async onEndLoading(){var t;if(this._isCurrentlyLoading=!1,(t=this.loadingScene)!=null&&t.asset){ti&&console.log("Remove loading scene",this.loadingScene.url);const i=this.loadingScene.asset,n=this.tryGetSceneEventListener(i);if(typeof n?.sceneClosing=="function"){const o=n.sceneClosing();o instanceof Promise&&await o}O.remove(i)}if(!this._isCurrentlyLoading){const i=this.tryGetSceneEventListener(this.gameObject);if(i&&i.sceneClosing){const n=i.sceneClosing();n instanceof Promise&&await n}}}tryGetSceneEventListener(t,i=0){if(!t)return null;const n=O.foreachComponent(t,o=>{const r=o;if(r.sceneClosing||r.sceneOpened)return r});if(i===0&&!n&&t.children.length)for(const o of t.children){const r=this.tryGetSceneEventListener(o,i+1);if(r)return r}return n||null}}St([m()],ot.prototype,"autoLoadFirstScene",2),St([m(le)],ot.prototype,"scenes",2),St([m(le)],ot.prototype,"loadingScene",2),St([m()],ot.prototype,"queryParameterName",2),St([m()],ot.prototype,"useSceneName",2),St([m()],ot.prototype,"clamp",2),St([m()],ot.prototype,"useHistory",2),St([m()],ot.prototype,"useKeyboard",2),St([m()],ot.prototype,"useSwipe",2),St([m()],ot.prototype,"useSceneLighting",2),St([m()],ot.prototype,"useSceneBackground",2),St([m()],ot.prototype,"preloadNext",2),St([m()],ot.prototype,"preloadPrevious",2),St([m()],ot.prototype,"preloadConcurrent",2),St([m()],ot.prototype,"createMenuButtons",2),St([m(Se)],ot.prototype,"sceneLoadingStart",2),St([m(Se)],ot.prototype,"sceneLoadingProgress",2),St([m(Se)],ot.prototype,"sceneLoaded",2);function w1(s){const t=s.split("/").pop(),i=t?.split(".").shift();return i!=null&&i.length?i:s}class YA{constructor(t,i=1,n=1,o=2){a(this,"maxLoadAhead"),a(this,"maxLoadBehind"),a(this,"maxConcurrent"),a(this,"_isRunning",!1),a(this,"_switcher"),a(this,"_loadTasks",[]),a(this,"_maxConcurrentLoads",1),this._switcher=t,this.maxLoadAhead=i,this.maxLoadBehind=n,this.maxConcurrent=o}begin(t){if(this._isRunning)return;ti&&console.log("Preload begin",{delay:t}),this._isRunning=!0;let i=-10,n,o;const r=this._switcher.scenes,l=Date.now()+t,c=setInterval(()=>{if(this.allLoaded()&&(ti&&console.log("All scenes (pre-)loaded"),this.stop()),!this._isRunning){clearInterval(c);return}if(Date.now()<l||this.canLoadNewScene()===!1)return;(i===-10||i!==this._switcher.currentIndex)&&(i=this._switcher.currentIndex,o=0,n=0);const h=o%2===0;h&&(n+=1),o+=1;const d=h?this.maxLoadAhead:this.maxLoadBehind;if(n>d)return;const u=h?i+n:i-n;if(!(u<0)&&!(u<0||u>=r.length)&&!this._loadTasks.some(p=>p.index===u)){const p=r[u];ti&&console.log("Preload scene",{roomIndex:u,searchForward:h,lastRoom:i,currentIndex:this._switcher.currentIndex,tasks:this._loadTasks.length},p?.url),new ZA(u,p,this._loadTasks)}},200)}stop(){this._isRunning=!1}canLoadNewScene(){return this._loadTasks.length<this._maxConcurrentLoads}allLoaded(){if(this._switcher.scenes){for(const t of this._switcher.scenes)if(t?.isLoaded()===!1)return!1}return!0}}class ZA{constructor(t,i,n){a(this,"index"),a(this,"asset"),a(this,"tasks"),this.index=t,this.asset=i,this.tasks=n,n.push(this),this.awaitLoading()}async awaitLoading(){this.asset&&!this.asset.isLoaded()&&(ti&&console.log("Preload start: "+this.asset.url,this.index),await this.asset.preload(),ti&&console.log("Preload finished: "+this.asset.url,this.index));const t=this.tasks.indexOf(this);t>=0&&this.tasks.splice(t,1)}}function KA(){return new Promise((s,t)=>{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 JA(s){await KA(),s()}var eI=Object.defineProperty,tI=Object.getOwnPropertyDescriptor,Bi=(s,t,i,n)=>{for(var o=n>1?void 0:n?tI(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&eI(t,i,o),o};const Ct=C("debugvideo");var x1=(s=>(s[s.None=0]="None",s[s.AdjustHeight=1]="AdjustHeight",s[s.AdjustWidth=2]="AdjustWidth",s))(x1||{}),S1=(s=>(s[s.VideoClip=0]="VideoClip",s[s.Url=1]="Url",s))(S1||{}),C1=(s=>(s[s.CameraFarPlane=0]="CameraFarPlane",s[s.CameraNearPlane=1]="CameraNearPlane",s[s.RenderTexture=2]="RenderTexture",s[s.MaterialOverride=3]="MaterialOverride",s))(C1||{});class gt extends A{constructor(){super(),a(this,"playOnAwake",!0),a(this,"aspectMode",0),a(this,"clip",null),a(this,"source",1),a(this,"_url",null),a(this,"renderMode"),a(this,"targetMaterialProperty"),a(this,"targetMaterialRenderer"),a(this,"targetTexture"),a(this,"time",0),a(this,"_playbackSpeed",1),a(this,"_isLooping",!1),a(this,"_muted",!1),a(this,"_audioOutputMode",2),a(this,"playInBackground",!0),a(this,"_crossOrigin","anonymous"),a(this,"_videoElement",null),a(this,"_videoTexture",null),a(this,"_videoMaterial",null),a(this,"_isPlaying",!1),a(this,"wasPlaying",!1),a(this,"visibilityChanged",t=>{switch(document.visibilityState){case"hidden":this.playInBackground||(this.wasPlaying=this._isPlaying,this.pause());break;case"visible":this.wasPlaying&&!this._isPlaying&&this.play();break}}),a(this,"_receivedInput",!1),a(this,"_overlay",null),a(this,"_targetObjects"),a(this,"_updateAspectRoutineId",-1),a(this,"_hls"),a(this,"onHlsAvailable",()=>{var t;Ct&&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),(t=this._videoElement)==null||t.play(),Ct&&console.log("HLS: loaded",this.clip))}),JA(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[],C("videoscreenspace")&&window.addEventListener("keydown",t=>{t.key==="f"&&(this.screenspace=!this.screenspace)})}get url(){return this._url}set url(t){const i=this._url!==t;this.__didAwake?i&&this.setClipURL(t??""):this._url=t}get playbackSpeed(){var t;return((t=this._videoElement)==null?void 0:t.playbackRate)??this._playbackSpeed}set playbackSpeed(t){this._playbackSpeed=t,this._videoElement&&(this._videoElement.playbackRate=t)}get isLooping(){var t;return((t=this._videoElement)==null?void 0:t.loop)??this._isLooping}set isLooping(t){this._isLooping=t,this._videoElement&&(this._videoElement.loop=t)}get currentTime(){var t;return((t=this._videoElement)==null?void 0:t.currentTime)??this.time}set currentTime(t){this._videoElement?this._videoElement.currentTime=t:this.time=t}get isPlaying(){const t=this._videoElement;return!!(t&&(t.currentTime>0&&!t.paused&&!t.ended&&t.readyState>t.HAVE_CURRENT_DATA||t.srcObject&&t.srcObject.active))}get crossOrigin(){var t;return((t=this._videoElement)==null?void 0:t.crossOrigin)??this._crossOrigin}set crossOrigin(t){this._crossOrigin=t,this._videoElement&&(t!==null?this._videoElement.setAttribute("crossorigin",t):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(){var t;return((t=this._videoElement)==null?void 0:t.muted)??this._muted}set muted(t){this._muted=t,this._videoElement&&(this._videoElement.muted=t)}get currentVideo(){return this.clip}set audioOutputMode(t){t!==this._audioOutputMode&&(t===1&&F()&&console.warn("VideoAudioOutputMode.AudioSource is not yet implemented"),this._audioOutputMode=t,this.updateVideoElementSettings())}get audioOutputMode(){return this._audioOutputMode}preloadVideo(){Ct&&console.log("Video Preload: "+this.name,this.clip),this.create(!1)}preload(){this.preloadVideo()}setVideo(t){this.clip=t,this.source=0,this._videoElement?(this._videoElement.srcObject=t,this._isPlaying&&this.play(),this.updateAspect()):this.create(this.playOnAwake)}setClipURL(t){this._url!==t&&(this._url=t,this.source=1,Ct&&console.log("set url",t),this._videoElement?t.endsWith(".m3u8")||t.includes(".m3u")?this.ensureM3UCanBePlayed():(this._videoElement.src=t,this._isPlaying&&(this.stop(),this.play())):this.create(this.playOnAwake))}onEnable(){var t,i;Ct&&console.log("VideoPlayer.onEnable",S1[this.source],this.clip,this.url,this),window.addEventListener("visibilitychange",this.visibilityChanged),this.playOnAwake===!0?this.create(!0):this.preloadVideo(),this.screenspace?(t=this._overlay)==null||t.start():(i=this._overlay)==null||i.stop()}onDisable(){var t;window.removeEventListener("visibilitychange",this.visibilityChanged),(t=this._overlay)==null||t.stop(),this.pause()}onDestroy(){var t;this._videoElement&&((t=this.videoElement)==null||t.remove(),this._videoElement=null),this._videoTexture&&(this._videoTexture.dispose(),this._videoTexture=null)}play(){var t,i;if(this._videoElement||this.create(!1),!this._videoElement){Ct&&console.warn("Can not play: no video element found",this);return}if(!(this._isPlaying&&!((t=this._videoElement)!=null&&t.ended)&&!((i=this._videoElement)!=null&&i.paused))){if(this._isPlaying=!0,this._receivedInput||(this._videoElement.muted=!0),this.handleBeginPlaying(!1),this.shouldUseM3U){this.ensureM3UCanBePlayed();return}Ct&&console.log("Video Play()",this.clip,this._videoElement,this.time),this._videoElement.currentTime=this.time,this._videoElement.play().catch(n=>{var o;console.log(n),Ct&&console.error("Error playing video",n,"CODE="+n.code,(o=this.videoElement)==null?void 0:o.src,this),setTimeout(()=>{this._isPlaying&&!this.destroyed&&this.activeAndEnabled&&this.play()},1e3)}),Ct&&console.log("play",this._videoElement,this.time)}}stop(){this._isPlaying=!1,this.time=0,this._videoElement&&(this._videoElement.currentTime=0,this._videoElement.pause(),Ct&&console.log("STOP",this))}pause(){var t,i;this.time=((t=this._videoElement)==null?void 0:t.currentTime)??0,this._isPlaying=!1,(i=this._videoElement)==null||i.pause(),Ct&&console.log("PAUSE",this,this.currentTime)}create(t){let i;switch(this.source){case 0:i=this.clip;break;case 1:i=this.url,!(i!=null&&i.length)&&typeof this.clip=="string"&&(i=this.clip);break}return i?(this._videoElement||(Ct&&console.warn("Create VideoElement",this),this._videoElement=this.createVideoElement(),this.context.domElement.shadowRoot.prepend(this._videoElement),this.updateVideoElementStyles()),typeof i=="string"?(Ct&&console.log("Set Video src",i),this._videoElement.src=i):(Ct&&console.log("Set Video srcObject",i),this._videoElement.srcObject=i),this._videoTexture||(this._videoTexture=new xC(this._videoElement)),this._videoTexture.flipY=!1,this._videoTexture.colorSpace=ms,t&&this.handleBeginPlaying(t),Ct&&console.log("Video: handle playing done...",i,t),!0):(Ct&&console.warn("No video source set",this),!1)}updateAspect(){this.aspectMode!==0&&this.startCoroutine(this.updateAspectImpl())}get screenspace(){var t;return((t=this._overlay)==null?void 0:t.enabled)??!1}set screenspace(t){var i;if(t){if(!this._videoTexture)return;this._overlay||(this._overlay=new iI(this.context)),this._overlay.add(this._videoTexture)}else(i=this._overlay)==null||i.remove(this._videoTexture);this._overlay&&(this._overlay.enabled=t)}createVideoElement(){const t=document.createElement("video");return this._crossOrigin&&t.setAttribute("crossorigin",this._crossOrigin),Ct&&console.log("created video element",t),t}handleBeginPlaying(t){var i,n;if(!this.activeAndEnabled||!this._videoElement)return;this._targetObjects.length=0;let o=this.gameObject;switch(this.renderMode){case 3:o=(i=this.targetMaterialRenderer)==null?void 0:i.gameObject,o||(o=(n=O.getComponent(this.gameObject,Ze))==null?void 0:n.gameObject);break;case 2:console.error("VideoPlayer renderTexture not implemented yet. Please use material override instead");return}if(!o){console.error("Missing target for video material renderer",this.name,C1[this.renderMode],this);return}const r=o.material;if(r){this._targetObjects.push(o),r!==this._videoMaterial&&(this._videoMaterial=r.clone(),o.material=this._videoMaterial);const l="map",c=this._videoMaterial;if(!this.targetMaterialProperty)c[l]=this._videoTexture;else switch(this.targetMaterialProperty){default:c[l]=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(),t&&(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 t=!this._receivedInput||this.audioOutputMode===0;!t&&this._muted&&(t=!0),this._videoElement.muted=t,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())}*updateAspectImpl(){const t=++this._updateAspectRoutineId,i=void 0,n=this.clip;for(;t===this._updateAspectRoutineId&&this.aspectMode!==0&&this.clip&&n===this.clip&&this._isPlaying;){if(!n||typeof n=="string")return;let o;for(const r of n.getVideoTracks()){const l=r.getSettings();if(l&&l.width&&l.height){o=l.width/l.height;break}else o=this.context.renderer.domElement.clientWidth/this.context.renderer.domElement.clientHeight}if(o===void 0){for(let r=0;r<10;r++)yield;if(!this.isPlaying)break;continue}if(i===o){yield;continue}for(const r of this._targetObjects){let l=1;if(r.parent){const c=Ye(r.parent);l=c.x/c.y}switch(this.aspectMode){case 1:r.scale.y=1/o*r.scale.x*l;break;case 2:r.scale.x=o*r.scale.y*l;break}}for(let r=0;r<3;r++)yield}}get shouldUseM3U(){return this.url!=null&&(this.url.endsWith(".m3u8")||this.url.endsWith(".m3u"))&&this.source===1}ensureM3UCanBePlayed(){if(!this.shouldUseM3U)return;let t=document.head.querySelector("script[data-hls_library]");t?globalThis.Hls?this.onHlsAvailable():t.addEventListener("load",this.onHlsAvailable):(Ct&&console.log("HLS: load script"),t=document.createElement("script"),t.dataset.hls_library="hls.js",t.src="https://cdn.jsdelivr.net/npm/hls.js@1",t.addEventListener("load",this.onHlsAvailable),document.head.append(t))}}Bi([m()],gt.prototype,"playOnAwake",2),Bi([m()],gt.prototype,"aspectMode",2),Bi([m(URL)],gt.prototype,"clip",2),Bi([m()],gt.prototype,"source",2),Bi([m(URL)],gt.prototype,"url",1),Bi([m()],gt.prototype,"renderMode",2),Bi([m()],gt.prototype,"targetMaterialProperty",2),Bi([m(Ze)],gt.prototype,"targetMaterialRenderer",2),Bi([m(Le)],gt.prototype,"targetTexture",2),Bi([m()],gt.prototype,"time",2),Bi([m()],gt.prototype,"playbackSpeed",1),Bi([m()],gt.prototype,"isLooping",1),Bi([m()],gt.prototype,"audioOutputMode",1);class iI{constructor(t){a(this,"context"),a(this,"_videos",[]),a(this,"_screenspaceModeQuad"),a(this,"_isInScreenspaceMode",!1),a(this,"_input"),this.context=t,this._input=new sI(this)}get enabled(){return this._isInScreenspaceMode}set enabled(t){t?this.start():this.stop()}add(t){this._videos.indexOf(t)===-1&&this._videos.push(t)}remove(t){if(!t)return;const i=this._videos.indexOf(t);i>=0&&this._videos.splice(i,1)}start(){var t;if(this._isInScreenspaceMode||this._videos.length<0)return;const i=this._videos[this._videos.length-1];if(!i)return;if(this._isInScreenspaceMode=!0,!this._screenspaceModeQuad){if(this._screenspaceModeQuad=po.createPrimitive(ur.Quad,{material:new nI(i)}),!this._screenspaceModeQuad)return;this._screenspaceModeQuad.geometry.scale(2,2,2)}const n=this._screenspaceModeQuad;this.context.scene.add(n),this.updateScreenspaceMaterialUniforms();const o=n.material;o?.reset(),(t=this._input)==null||t.enable(o)}stop(){var t;this._isInScreenspaceMode=!1,this._screenspaceModeQuad&&((t=this._input)==null||t.disable(),this._screenspaceModeQuad.removeFromParent())}updateScreenspaceMaterialUniforms(){var t;const i=(t=this._screenspaceModeQuad)==null?void 0:t.material;i&&(i.screenAspect=this.context.domElement.clientWidth/this.context.domElement.clientHeight)}}class sI{constructor(t){a(this,"_onResizeScreenFn"),a(this,"_onKeyUpFn"),a(this,"_onMouseWheelFn"),a(this,"context"),a(this,"overlay"),a(this,"_material"),a(this,"_isPinching",!1),a(this,"_lastPinch",0),this.overlay=t,this.context=t.context}enable(t){this._material=t,window.addEventListener("resize",this._onResizeScreenFn=()=>{this.overlay.updateScreenspaceMaterialUniforms()}),window.addEventListener("keyup",this._onKeyUpFn=o=>{o.key==="Escape"&&this.overlay.stop()}),window.addEventListener("wheel",this._onMouseWheelFn=o=>{this.overlay.enabled&&(t.zoom+=o.deltaY*5e-4,o.preventDefault())},{passive:!1});const i=new re;window.addEventListener("mousemove",o=>{if(this.overlay.enabled&&this.context.input.getPointerPressed(0)){const r=new re(o.movementX,o.movementY);r.x/=this.context.domElement.clientWidth,r.y/=this.context.domElement.clientHeight,i.set(r.x,r.y),i.multiplyScalar(t.zoom/-this.context.time.deltaTime*.01),t.offset=t.offset.add(i)}}),window.addEventListener("pointermove",o=>{this.overlay.enabled&&this.context.input.getPointerPressed(0)&&this.context.input.getTouchesPressedCount()===1&&(i.set(o.movementX,o.movementY),i.multiplyScalar(t.zoom*-this.context.time.deltaTime*.05),t.offset=t.offset.add(i))});let n=0;window.addEventListener("touchstart",o=>{if(o.touches.length<2){this.context.time.time-n<.3&&this.overlay.stop(),n=this.context.time.time;return}this._isPinching=!0,this._lastPinch=0}),window.addEventListener("touchmove",o=>{if(!this._isPinching||!this._material)return;const r=o.touches[0],l=o.touches[1],c=r.clientX-l.clientX,h=r.clientY-l.clientY,d=Math.sqrt(c*c+h*h);if(this._lastPinch!==0){const u=d-this._lastPinch;this._material.zoom-=u*.004}this._lastPinch=d}),window.addEventListener("touchend",()=>{this._isPinching=!1})}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 nI extends ps{constructor(t){super(),a(this,"_offset",new re),this.uniforms={map:{value:t},screenAspect:{value:1},offsetScale:{value:new fe(0,0,1,1)}},this.vertexShader=`
1266
1270
  uniform sampler2D map;
1267
1271
  uniform float screenAspect;
1268
1272
  uniform vec4 offsetScale;
@@ -1315,8 +1319,8 @@ axisFormat %s
1315
1319
  gl_FragColor = texcolor;
1316
1320
  }
1317
1321
  }
1318
- `}set screenAspect(t){this.uniforms.screenAspect.value=t,this.needsUpdate=!0}set offset(t){const i=this.uniforms.offsetScale.value;i.x=t.x,i.y=t.y,this.uniforms.offsetScale.value=i,this.needsUpdate=!0}get offset(){const t=this.uniforms.offsetScale.value;return this._offset.set(t.x,t.y),this._offset}set zoom(t){const i=this.uniforms.offsetScale.value;t<.001&&(t=.001),i.z=t,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}}var nI=Object.defineProperty,oI=Object.getOwnPropertyDescriptor,Eh=(s,t,i,n)=>{for(var o=n>1?void 0:n?oI(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&nI(t,i,o),o};const jt=C("debugscreensharing");var O1=(s=>(s[s.Screen=0]="Screen",s[s.Camera=1]="Camera",s[s.Canvas=2]="Canvas",s[s.Microphone=3]="Microphone",s))(O1||{});class Xo extends A{constructor(){super(...arguments),a(this,"allowStartOnClick",!0),a(this,"autoConnect",!1),a(this,"_videoPlayer"),a(this,"_audioSource"),a(this,"device","Screen"),a(this,"deviceName"),a(this,"deviceFilter"),a(this,"_net"),a(this,"_requestOpen",!1),a(this,"_currentStream",null),a(this,"_currentMode",0),a(this,"onJoinedRoom",async()=>{await fs(1e3),this.autoConnect&&!this.isSending&&!this.isReceiving&&this.context.connection.isInRoom&&this.share()}),a(this,"_activeShareRequest",null),a(this,"onReceiveStream",t=>{var i;((i=t.stream)==null?void 0:i.active)===!0&&this.setStream(t.stream,2)}),a(this,"onCallEnded",t=>{jt&&console.log("CALL ENDED",this.isReceiving,this==null?void 0:this.screenspace),this.isReceiving&&(this.screenspace=!1)})}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(t){var i;if(this.context.connection.allowEditing!=!1&&this.allowStartOnClick&&!(t&&t.pointerId!==0)){if(this.isReceiving&&(i=this.videoPlayer)!=null&&i.isPlaying){this.videoPlayer&&(this.videoPlayer.screenspace=!this.videoPlayer.screenspace);return}if(this.isSending){this.close();return}this.share()}}set videoPlayer(t){this._videoPlayer&&(this.isSending||this.isReceiving)&&this._videoPlayer.stop(),this._videoPlayer=t,this._videoPlayer&&this._currentStream&&(this.isSending||this.isReceiving)&&this._videoPlayer.setVideo(this._currentStream)}get videoPlayer(){return this._videoPlayer}get screenspace(){var t;return((t=this.videoPlayer)==null?void 0:t.screenspace)??!1}set screenspace(t){this.videoPlayer&&(this.videoPlayer.screenspace=t)}get currentScream(){return this._currentStream}get currentMode(){return this._currentMode}get isSending(){var t;return((t=this._currentStream)==null?void 0:t.active)&&this._currentMode===1}get isReceiving(){if(this._currentMode===2){if(!this._currentStream||this._currentStream.active===!1)return!1;const t=this._currentStream.getTracks();for(const i of t)if(i.readyState==="live")return!0}return!1}get requiresVideoPlayer(){return this.device!=="Microphone"}awake(){typeof this.device=="number"&&(this.device=O1[this.device]),jt&&console.log("Screensharing",this.name,this),Ne.registerWaitForAllowAudio(()=>{this._videoPlayer&&this._currentStream&&this._currentMode===2&&(this._videoPlayer.playInBackground=!0,this._videoPlayer.setVideo(this._currentStream))}),this._net=new sd(this)}onEnable(){var t,i,n;(t=this._net)==null||t.enable(),(i=this._net)==null||i.addEventListener(Xs.StreamReceived,this.onReceiveStream),(n=this._net)==null||n.addEventListener(Xs.StreamEnded,this.onCallEnded),this.context.connection.beginListen(se.JoinedRoom,this.onJoinedRoom),this.autoConnect&&fs(1e3).then(()=>(this.enabled&&this.autoConnect&&!this.isReceiving&&!this.isSending&&this.context.connection.isInRoom&&this.share(),0))}onDisable(){var t,i,n;(t=this._net)==null||t.removeEventListener(Xs.StreamReceived,this.onReceiveStream),(i=this._net)==null||i.removeEventListener(Xs.StreamEnded,this.onCallEnded),this.context.connection.stopListen(se.JoinedRoom,this.onJoinedRoom),(n=this._net)==null||n.disable(),this.close()}_ensureVideoPlayer(){const t=new gt;t.aspectMode=x1.AdjustWidth,O.addComponent(this.gameObject,t),this._videoPlayer=t}async share(t){return this._activeShareRequest?this._activeShareRequest:(this._activeShareRequest=this.internalShare(t),this._activeShareRequest.then(()=>this._activeShareRequest=null))}async internalShare(t){if(this.context.connection.isInRoom===!1){console.warn("Can not start screensharing: requires network connection"),F()&&we("Can not start screensharing: requires network connection. Add a SyncedRoom component or join a room first.");return}if(t!=null&&t.device&&(this.device=t.device),!this.videoPlayer&&this.requiresVideoPlayer&&(this._videoPlayer||(this._videoPlayer=O.getComponent(this.gameObject,gt)??void 0),this.videoPlayer||this._ensureVideoPlayer(),!this.videoPlayer)){console.warn("Can not share video without a videoPlayer assigned");return}this._requestOpen=!0;try{const i=t?.constraints??{echoCancellation:!0,autoGainControl:!1},n={video:i,audio:i},o=n.video;switch(o!==void 0&&typeof o!="boolean"&&(o.width||(o.width={max:1920}),o.height||(o.height={max:1920}),o.aspectRatio||(o.aspectRatio={ideal:1.7777777778}),o.frameRate||(o.frameRate={ideal:24}),o.facingMode||(o.facingMode={ideal:"user"})),this.device){case"Camera":this.tryShareUserCamera(n,t);break;case"Screen":{if(!navigator.mediaDevices.getDisplayMedia){console.error("No getDisplayMedia support");return}const c=await navigator.mediaDevices.getDisplayMedia(n);this._requestOpen?this.setStream(c,1):Qs(c)}break;case"Canvas":const r=0,l=this.context.renderer.domElement.captureStream(r);this.setStream(l,1);break;case"Microphone":{if(!navigator.mediaDevices.getUserMedia){console.error("No getDisplayMedia support");return}n.video=!1;const c=await navigator.mediaDevices.getUserMedia(n);this._requestOpen?this.setStream(c,1):Qs(c)}break;default:console.error("Can not start screen sharing: Unknown device type",this.device)}}catch(i){if(i.name==="NotAllowedError"){console.log("Selection cancelled"),this._requestOpen=!1;return}console.error("Error opening video",i)}}close(){var t;this._requestOpen=!1,this._currentStream&&(jt&&console.warn("Close current stream / disposing resources, stream was active?",this._currentStream.active),(t=this._net)==null||t.stopSendingStream(this._currentStream),Qs(this._currentStream),this._currentMode=0,this._currentStream=null)}setStream(t,i){var n,o,r;if(t===this._currentStream||(this.close(),!t))return;this._currentStream=t,this._requestOpen=!0,this._currentMode=i;const l=this.device!=="Microphone",c=i===1;l?(this._videoPlayer||this._ensureVideoPlayer(),this._videoPlayer?this._videoPlayer.setVideo(t):console.error("No video player assigned for video stream")):(this._audioSource||(this._audioSource=new Ne,this._audioSource.spatialBlend=0,this._audioSource.volume=1,this.gameObject.addComponent(this._audioSource)),c||(jt&&console.log("PLAY",t.getAudioTracks()),this._audioSource.volume=1,(n=this._audioSource)==null||n.play(t))),c&&((o=this._net)==null||o.startSendingStream(t)),c&&(this._videoPlayer&&(this._videoPlayer.muted=!0),(r=this._audioSource)==null||r.stop());for(const h of t.getTracks())h.addEventListener("ended",()=>{jt&&console.log("Track ended",h),this.close()}),jt&&h.kind==="video"&&console.log(c?"Video \u2192":"Video \u2190",h.getSettings())}async tryShareUserCamera(t,i){const n=(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="videoinput");jt&&console.log(`Request camera. These are your kind:videoinput devices:
1319
- `,n);let o=!1;for(const r of n)try{if(!this._requestOpen){jt&&console.log("Camera selection cancelled");break}if(r.kind!=="videoinput"){jt&&console.log("Skipping non-video device",r);continue}const l=r.deviceId;if(i?.deviceId!=null||i?.deviceFilter!=null){if(i?.deviceId!==void 0&&l!==i.deviceId){jt&&console.log("Skipping device due to options.deviceId: "+r.label+"; "+r.deviceId);continue}if(i!=null&&i.deviceFilter&&i.deviceFilter(r)===!1){jt&&console.log("Skipping device due to options.deviceFilter: "+r.label+"; "+r.deviceId);continue}}else if(this.deviceFilter)if(this.deviceFilter(r)===!1){jt&&console.log("Skipping device due to ScreenShare.deviceFilter: "+r.label+"; "+r.deviceId);continue}else jt&&console.log("Selected device by filter",r);else if(this.deviceName){const h=r.label.toLowerCase(),d=this.deviceName.toLowerCase(),u=h.includes(d),p=r.deviceId===this.deviceName;if(!u&&!p){jt&&console.log("Skipping device due to ScreenShare.deviceName: "+r.label+"; "+r.deviceId);continue}else jt&&console.log("Selected device by name",r)}t.video!==!1&&((typeof t.video>"u"||typeof t.video=="boolean")&&(t.video={}),t.video.deviceId=l),o=!0;const c=await navigator.mediaDevices.getUserMedia(t).catch(h=>(console.error("Failed to get user media",h),null));if(c===null)continue;this._requestOpen?(this.setStream(c,1),jt&&console.log("Selected camera",r)):(Qs(c),jt&&console.log("Camera selection cancelled"));break}catch(l){if(l.message==="Failed to allocate videosource"||l.message==="Could not start video source"){we("Failed to start video: Try another camera (Code "+l.code+")"),console.warn(l);continue}else console.error("Failed to get user media",l.message,l.code,l)}!o&&F()&&(we("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",n,this.deviceName,"Using deviceFilter? "+this.deviceFilter!=null,"Using options? "+i!=null,"Using deviceName? "+this.deviceName!=null,"Using options.deviceId? "+i?.deviceId!=null,"Using options.deviceFilter? "+i?.deviceFilter!=null))}}Eh([m()],Xo.prototype,"allowStartOnClick",2),Eh([m()],Xo.prototype,"autoConnect",2),Eh([m(gt)],Xo.prototype,"videoPlayer",1),Eh([m()],Xo.prototype,"device",2),Eh([m()],Xo.prototype,"deviceName",2);var rI=Object.defineProperty,aI=Object.getOwnPropertyDescriptor,P1=(s,t,i,n)=>{for(var o=n>1?void 0:n?aI(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&rI(t,i,o),o};class Ah extends A{constructor(){super(...arguments),a(this,"mode",0),a(this,"shadowColor",new xe(0,0,0,1)),a(this,"targetMesh")}start(){if(this.gameObject instanceof Y)this.gameObject instanceof Y&&this.gameObject.material&&(this.gameObject.material=this.gameObject.material.clone(),this.targetMesh=this.gameObject,this.targetMesh.receiveShadow=!0);else{const t=po.createPrimitive(ur.Quad,{name:"ShadowCatcher",material:new ni({color:10066329,roughness:1,metalness:0,transparent:!0})});t.receiveShadow=!0,t.geometry.rotateX(-Math.PI/2),this.gameObject.add(t),this.targetMesh=t}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 t=this.targetMesh.material;t.blending=ev,this.applyMaterialOptions(t),t.onBeforeCompile=i=>{i.fragmentShader=i.fragmentShader.replace("vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;",`vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
1322
+ `}set screenAspect(t){this.uniforms.screenAspect.value=t,this.needsUpdate=!0}set offset(t){const i=this.uniforms.offsetScale.value;i.x=t.x,i.y=t.y,this.uniforms.offsetScale.value=i,this.needsUpdate=!0}get offset(){const t=this.uniforms.offsetScale.value;return this._offset.set(t.x,t.y),this._offset}set zoom(t){const i=this.uniforms.offsetScale.value;t<.001&&(t=.001),i.z=t,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}}var oI=Object.defineProperty,rI=Object.getOwnPropertyDescriptor,Eh=(s,t,i,n)=>{for(var o=n>1?void 0:n?rI(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&oI(t,i,o),o};const jt=C("debugscreensharing");var O1=(s=>(s[s.Screen=0]="Screen",s[s.Camera=1]="Camera",s[s.Canvas=2]="Canvas",s[s.Microphone=3]="Microphone",s))(O1||{});class Xo extends A{constructor(){super(...arguments),a(this,"allowStartOnClick",!0),a(this,"autoConnect",!1),a(this,"_videoPlayer"),a(this,"_audioSource"),a(this,"device","Screen"),a(this,"deviceName"),a(this,"deviceFilter"),a(this,"_net"),a(this,"_requestOpen",!1),a(this,"_currentStream",null),a(this,"_currentMode",0),a(this,"onJoinedRoom",async()=>{await fs(1e3),this.autoConnect&&!this.isSending&&!this.isReceiving&&this.context.connection.isInRoom&&this.share()}),a(this,"_activeShareRequest",null),a(this,"onReceiveStream",t=>{var i;((i=t.stream)==null?void 0:i.active)===!0&&this.setStream(t.stream,2)}),a(this,"onCallEnded",t=>{jt&&console.log("CALL ENDED",this.isReceiving,this==null?void 0:this.screenspace),this.isReceiving&&(this.screenspace=!1)})}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(t){var i;if(this.context.connection.allowEditing!=!1&&this.allowStartOnClick&&!(t&&t.pointerId!==0)){if(this.isReceiving&&(i=this.videoPlayer)!=null&&i.isPlaying){this.videoPlayer&&(this.videoPlayer.screenspace=!this.videoPlayer.screenspace);return}if(this.isSending){this.close();return}this.share()}}set videoPlayer(t){this._videoPlayer&&(this.isSending||this.isReceiving)&&this._videoPlayer.stop(),this._videoPlayer=t,this._videoPlayer&&this._currentStream&&(this.isSending||this.isReceiving)&&this._videoPlayer.setVideo(this._currentStream)}get videoPlayer(){return this._videoPlayer}get screenspace(){var t;return((t=this.videoPlayer)==null?void 0:t.screenspace)??!1}set screenspace(t){this.videoPlayer&&(this.videoPlayer.screenspace=t)}get currentScream(){return this._currentStream}get currentMode(){return this._currentMode}get isSending(){var t;return((t=this._currentStream)==null?void 0:t.active)&&this._currentMode===1}get isReceiving(){if(this._currentMode===2){if(!this._currentStream||this._currentStream.active===!1)return!1;const t=this._currentStream.getTracks();for(const i of t)if(i.readyState==="live")return!0}return!1}get requiresVideoPlayer(){return this.device!=="Microphone"}awake(){typeof this.device=="number"&&(this.device=O1[this.device]),jt&&console.log("Screensharing",this.name,this),Ne.registerWaitForAllowAudio(()=>{this._videoPlayer&&this._currentStream&&this._currentMode===2&&(this._videoPlayer.playInBackground=!0,this._videoPlayer.setVideo(this._currentStream))}),this._net=new sd(this)}onEnable(){var t,i,n;(t=this._net)==null||t.enable(),(i=this._net)==null||i.addEventListener(Xs.StreamReceived,this.onReceiveStream),(n=this._net)==null||n.addEventListener(Xs.StreamEnded,this.onCallEnded),this.context.connection.beginListen(se.JoinedRoom,this.onJoinedRoom),this.autoConnect&&fs(1e3).then(()=>(this.enabled&&this.autoConnect&&!this.isReceiving&&!this.isSending&&this.context.connection.isInRoom&&this.share(),0))}onDisable(){var t,i,n;(t=this._net)==null||t.removeEventListener(Xs.StreamReceived,this.onReceiveStream),(i=this._net)==null||i.removeEventListener(Xs.StreamEnded,this.onCallEnded),this.context.connection.stopListen(se.JoinedRoom,this.onJoinedRoom),(n=this._net)==null||n.disable(),this.close()}_ensureVideoPlayer(){const t=new gt;t.aspectMode=x1.AdjustWidth,O.addComponent(this.gameObject,t),this._videoPlayer=t}async share(t){return this._activeShareRequest?this._activeShareRequest:(this._activeShareRequest=this.internalShare(t),this._activeShareRequest.then(()=>this._activeShareRequest=null))}async internalShare(t){if(this.context.connection.isInRoom===!1){console.warn("Can not start screensharing: requires network connection"),F()&&we("Can not start screensharing: requires network connection. Add a SyncedRoom component or join a room first.");return}if(t!=null&&t.device&&(this.device=t.device),!this.videoPlayer&&this.requiresVideoPlayer&&(this._videoPlayer||(this._videoPlayer=O.getComponent(this.gameObject,gt)??void 0),this.videoPlayer||this._ensureVideoPlayer(),!this.videoPlayer)){console.warn("Can not share video without a videoPlayer assigned");return}this._requestOpen=!0;try{const i=t?.constraints??{echoCancellation:!0,autoGainControl:!1},n={video:i,audio:i},o=n.video;switch(o!==void 0&&typeof o!="boolean"&&(o.width||(o.width={max:1920}),o.height||(o.height={max:1920}),o.aspectRatio||(o.aspectRatio={ideal:1.7777777778}),o.frameRate||(o.frameRate={ideal:24}),o.facingMode||(o.facingMode={ideal:"user"})),this.device){case"Camera":this.tryShareUserCamera(n,t);break;case"Screen":{if(!navigator.mediaDevices.getDisplayMedia){console.error("No getDisplayMedia support");return}const c=await navigator.mediaDevices.getDisplayMedia(n);this._requestOpen?this.setStream(c,1):Qs(c)}break;case"Canvas":const r=0,l=this.context.renderer.domElement.captureStream(r);this.setStream(l,1);break;case"Microphone":{if(!navigator.mediaDevices.getUserMedia){console.error("No getDisplayMedia support");return}n.video=!1;const c=await navigator.mediaDevices.getUserMedia(n);this._requestOpen?this.setStream(c,1):Qs(c)}break;default:console.error("Can not start screen sharing: Unknown device type",this.device)}}catch(i){if(i.name==="NotAllowedError"){console.log("Selection cancelled"),this._requestOpen=!1;return}console.error("Error opening video",i)}}close(){var t;this._requestOpen=!1,this._currentStream&&(jt&&console.warn("Close current stream / disposing resources, stream was active?",this._currentStream.active),(t=this._net)==null||t.stopSendingStream(this._currentStream),Qs(this._currentStream),this._currentMode=0,this._currentStream=null)}setStream(t,i){var n,o,r;if(t===this._currentStream||(this.close(),!t))return;this._currentStream=t,this._requestOpen=!0,this._currentMode=i;const l=this.device!=="Microphone",c=i===1;l?(this._videoPlayer||this._ensureVideoPlayer(),this._videoPlayer?this._videoPlayer.setVideo(t):console.error("No video player assigned for video stream")):(this._audioSource||(this._audioSource=new Ne,this._audioSource.spatialBlend=0,this._audioSource.volume=1,this.gameObject.addComponent(this._audioSource)),c||(jt&&console.log("PLAY",t.getAudioTracks()),this._audioSource.volume=1,(n=this._audioSource)==null||n.play(t))),c&&((o=this._net)==null||o.startSendingStream(t)),c&&(this._videoPlayer&&(this._videoPlayer.muted=!0),(r=this._audioSource)==null||r.stop());for(const h of t.getTracks())h.addEventListener("ended",()=>{jt&&console.log("Track ended",h),this.close()}),jt&&h.kind==="video"&&console.log(c?"Video \u2192":"Video \u2190",h.getSettings())}async tryShareUserCamera(t,i){const n=(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="videoinput");jt&&console.log(`Request camera. These are your kind:videoinput devices:
1323
+ `,n);let o=!1;for(const r of n)try{if(!this._requestOpen){jt&&console.log("Camera selection cancelled");break}if(r.kind!=="videoinput"){jt&&console.log("Skipping non-video device",r);continue}const l=r.deviceId;if(i?.deviceId!=null||i?.deviceFilter!=null){if(i?.deviceId!==void 0&&l!==i.deviceId){jt&&console.log("Skipping device due to options.deviceId: "+r.label+"; "+r.deviceId);continue}if(i!=null&&i.deviceFilter&&i.deviceFilter(r)===!1){jt&&console.log("Skipping device due to options.deviceFilter: "+r.label+"; "+r.deviceId);continue}}else if(this.deviceFilter)if(this.deviceFilter(r)===!1){jt&&console.log("Skipping device due to ScreenShare.deviceFilter: "+r.label+"; "+r.deviceId);continue}else jt&&console.log("Selected device by filter",r);else if(this.deviceName){const h=r.label.toLowerCase(),d=this.deviceName.toLowerCase(),u=h.includes(d),p=r.deviceId===this.deviceName;if(!u&&!p){jt&&console.log("Skipping device due to ScreenShare.deviceName: "+r.label+"; "+r.deviceId);continue}else jt&&console.log("Selected device by name",r)}t.video!==!1&&((typeof t.video>"u"||typeof t.video=="boolean")&&(t.video={}),t.video.deviceId=l),o=!0;const c=await navigator.mediaDevices.getUserMedia(t).catch(h=>(console.error("Failed to get user media",h),null));if(c===null)continue;this._requestOpen?(this.setStream(c,1),jt&&console.log("Selected camera",r)):(Qs(c),jt&&console.log("Camera selection cancelled"));break}catch(l){if(l.message==="Failed to allocate videosource"||l.message==="Could not start video source"){we("Failed to start video: Try another camera (Code "+l.code+")"),console.warn(l);continue}else console.error("Failed to get user media",l.message,l.code,l)}!o&&F()&&(we("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",n,this.deviceName,"Using deviceFilter? "+this.deviceFilter!=null,"Using options? "+i!=null,"Using deviceName? "+this.deviceName!=null,"Using options.deviceId? "+i?.deviceId!=null,"Using options.deviceFilter? "+i?.deviceFilter!=null))}}Eh([m()],Xo.prototype,"allowStartOnClick",2),Eh([m()],Xo.prototype,"autoConnect",2),Eh([m(gt)],Xo.prototype,"videoPlayer",1),Eh([m()],Xo.prototype,"device",2),Eh([m()],Xo.prototype,"deviceName",2);var aI=Object.defineProperty,lI=Object.getOwnPropertyDescriptor,P1=(s,t,i,n)=>{for(var o=n>1?void 0:n?lI(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&aI(t,i,o),o};class Ah extends A{constructor(){super(...arguments),a(this,"mode",0),a(this,"shadowColor",new xe(0,0,0,1)),a(this,"targetMesh")}start(){if(this.gameObject instanceof Y)this.gameObject instanceof Y&&this.gameObject.material&&(this.gameObject.material=this.gameObject.material.clone(),this.targetMesh=this.gameObject,this.targetMesh.receiveShadow=!0);else{const t=po.createPrimitive(ur.Quad,{name:"ShadowCatcher",material:new ni({color:10066329,roughness:1,metalness:0,transparent:!0})});t.receiveShadow=!0,t.geometry.rotateX(-Math.PI/2),this.gameObject.add(t),this.targetMesh=t}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 t=this.targetMesh.material;t.blending=ev,this.applyMaterialOptions(t),t.onBeforeCompile=i=>{i.fragmentShader=i.fragmentShader.replace("vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;",`vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
1320
1324
  // diffuse-only lighting with overdrive to somewhat compensate
1321
1325
  // for the loss of indirect lighting and to make it more visible.
1322
1326
  vec3 direct = (reflectedLight.directDiffuse + reflectedLight.directSpecular) * 6.6;
@@ -1326,19 +1330,19 @@ axisFormat %s
1326
1330
  // be blended onto the scene.
1327
1331
  gl_FragColor = vec4(direct, max);
1328
1332
  return;
1329
- `)},t.userData.isLightBlendMaterial=!0}applyShadowMaterial(){if(this.targetMesh)if(this.targetMesh.material.type!=="ShadowMaterial"){const t=new Uy;t.color=this.shadowColor,t.opacity=this.shadowColor.alpha,this.applyMaterialOptions(t),this.targetMesh.material=t,t.userData.isShadowCatcherMaterial=!0}else{const t=this.targetMesh.material;t.color=this.shadowColor,t.opacity=this.shadowColor.alpha,this.applyMaterialOptions(t),t.userData.isShadowCatcherMaterial=!0}}applyOccluderMaterial(){if(this.targetMesh){let t=this.targetMesh.material;if(!t){const i=new Re;this.targetMesh.material=i,t=i}t.depthWrite=!0,t.stencilWrite=!0,t.colorWrite=!1,this.gameObject.renderOrder=-100}}applyMaterialOptions(t){t&&(t.depthWrite=!1,t.stencilWrite=!1)}}P1([m()],Ah.prototype,"mode",2),P1([m(xe)],Ah.prototype,"shadowColor",2);var lI=Object.defineProperty,cI=Object.getOwnPropertyDescriptor,Ih=(s,t,i,n)=>{for(var o=n>1?void 0:n?cI(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&lI(t,i,o),o};const os=C("debugskybox");oy("skybox-image"),oy("environment-image");function k1(s,t,i,n,o){const r=new cn;r.allowDrop=!1,r.allowNetworking=!1,r.background=i,r.environment=n,O.addComponent(s.scene,r);const l=c=>{typeof c=="string"&&(os&&console.log(o,"CHANGED TO",c),r.setSkybox(c))};return Rv(s.domElement,o,l),r.addEventListener("destroy",()=>{os&&console.log("Destroyed attribute remote skybox",o),Tv(s.domElement,o,l)}),r.setSkybox(t)}const Lp=new Array;ue.registerCallback(ge.ContextCreationStart,s=>{var t;const i=s.context,n=i.domElement.getAttribute("skybox-image")||i.domElement.getAttribute("background-image"),o=i.domElement.getAttribute("environment-image");if(n){os&&console.log("Creating remote skybox to load "+n),((t=i.mainCameraComponent)==null?void 0:t.clearFlags)!==Oo.Skybox&&console.warn('"skybox-image"/"background-image" attribute has no effect: camera clearflags are not set to "Skybox"');const r=k1(i,n,!0,!1,"skybox-image");Lp.push(r)}if(o){os&&console.log("Creating remote environment to load "+o);const r=k1(i,o,!1,!0,"environment-image");Lp.push(r)}}),ue.registerCallback(ge.ContextCreationStart,()=>Promise.all(Lp).finally(()=>{Lp.length=0}));function M1(){return globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES||(globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES=new Array),globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES}function R1(s){const t=M1().find(i=>i.src===s);return t?(os&&console.log("Skybox: Found previously loaded texture for "+s),t.texture):null}async function hI(s){const t=await s;_g(t,!0),Ee(t)}function dI(s,t){const i=M1();for(;i.length>5;){const n=i.shift();n&&hI(n.texture)}t.then(n=>_g(n,!1)),i.push({src:s,texture:t})}class cn extends A{constructor(){super(...arguments),a(this,"url"),a(this,"allowDrop",!0),a(this,"background",!0),a(this,"environment",!0),a(this,"allowNetworking",!0),a(this,"_loader"),a(this,"_prevUrl"),a(this,"_prevLoadedEnvironment"),a(this,"_prevEnvironment",null),a(this,"_prevBackground",null),a(this,"validTextureTypes",[".ktx2",".hdr",".exr",".jpg",".jpeg",".png"]),a(this,"onDragOverEvent",t=>{if(this.allowDrop&&t.dataTransfer)for(const i of t.dataTransfer.types)(i==="text/uri-list"||i==="Files")&&t.preventDefault()}),a(this,"onDrop",t=>{var i,n,o,r;if(this.allowDrop&&t.dataTransfer){for(const l of t.dataTransfer.types)if(os&&console.log(l),l==="text/uri-list"){const c=t.dataTransfer.getData(l);os&&console.log(l,c);let h=(n=(i=new RegExp(/polyhaven.com\/asset_img\/.+?\/(?<name>.+)\.png/).exec(c))==null?void 0:i.groups)==null?void 0:n.name;if(h||(h=(r=(o=new RegExp(/polyhaven\.com\/a\/(?<name>.+)/).exec(c))==null?void 0:o.groups)==null?void 0:r.name),os&&console.log(h),h){const d="https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/"+h+"_1k.exr";console.log(`[Remote Skybox] Setting skybox from url: ${d}`),t.preventDefault(),this.setSkybox(d);break}else if(this.isValidTextureType(c)){console.log("[Remote Skybox] Setting skybox from url: "+c),t.preventDefault(),this.setSkybox(c);break}else{console.warn(`[RemoteSkybox] Unknown url ${c}. 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 d=new CustomEvent("dropped-unknown-url",{detail:{sender:this,event:t,url:c,apply:u=>{t.preventDefault(),this.setSkybox(u)}}});this.dispatchEvent(d)}}else if(l=="Files"){const c=t.dataTransfer.files.item(0);if(os&&console.log(l,c),!c)continue;if(!this.isValidTextureType(c.name)){console.warn(`[RemoteSkybox]: File "${c.name}" is not supported. Supported files are ${this.validTextureTypes.join(", ")}`);return}if(R1(c.name)===null){const h=new Blob([c]),d=URL.createObjectURL(h);t.preventDefault(),this.setSkybox(d,c.name)}else t.preventDefault(),this.setSkybox(c.name);break}}})}onEnable(){this.setSkybox(this.url),this.registerDropEvents()}onDisable(){var t;this.context.scene.environment===this._prevLoadedEnvironment&&(this.context.scene.environment=this._prevEnvironment,Oe.backgroundShouldBeTransparent(this.context)||(this.context.scene.background=this._prevBackground),this._prevLoadedEnvironment=void 0),this.unregisterDropEvents(),(t=this.context.mainCameraComponent)==null||t.applyClearFlags()}urlChangedSyncField(){this.allowNetworking&&this.url&&this.isRemoteTexture(this.url)&&this.setSkybox(this.url)}async setSkybox(t,i){var n;if(!this.activeAndEnabled||(t=uI(t,this.environment,this.background),!t))return!1;if(i??(i=t),this.isValidTextureType(i)||console.warn("Potentially invalid skybox url",i,"on",this.name),os&&console.log("Set remote skybox url: "+t),this._prevUrl===t&&this._prevLoadedEnvironment)return this.applySkybox(),!0;(n=this._prevLoadedEnvironment)==null||n.dispose(),this._prevLoadedEnvironment=void 0,this._prevUrl=t;const o=await this.loadTexture(t,i);if(!o||!this.enabled)return!1;this.url=t;const r=t.lastIndexOf("/");return o.name=t.substring(r>=0?r+1:0),this._loader instanceof ma&&(o.colorSpace=ms),this._prevLoadedEnvironment=o,this.applySkybox(),!0}async loadTexture(t,i){var n,o,r,l,c;if(!t)return Promise.resolve(null);i??(i=t);const h=R1(i);if(h){const y=await h;if(((o=(n=y.source)==null?void 0:n.data)==null?void 0:o.length)>0||(c=(l=(r=y.source)==null?void 0:r.data)==null?void 0:l.data)!=null&&c.length)return y}const d=i.endsWith(".exr"),u=i.endsWith(".hdr"),p=i.endsWith(".ktx2");if(d)this._loader instanceof ud||(this._loader=new ud);else if(u)this._loader instanceof fm||(this._loader=new fm);else if(p){if(!(this._loader instanceof QC)){const{ktx2Loader:y}=gm(this.context.renderer);this._loader=y}}else this._loader instanceof ma||(this._loader=new ma);os&&console.log("Loading skybox: "+t);const g=this._loader.loadAsync(t);return dI(i,g),await g}applySkybox(){var t;const i=this._prevLoadedEnvironment;i&&(i instanceof SC||i instanceof CC||(i.mapping=OC,i.needsUpdate=!0),this.context.scene.background!==i&&(this._prevBackground=this.context.scene.background),this.context.scene.environment!==i&&(this._prevEnvironment=this.context.scene.environment),os&&console.log("Set remote skybox",this.url,!Oe.backgroundShouldBeTransparent(this.context)),this.environment&&(this.context.scene.environment=i),this.background&&!Oe.backgroundShouldBeTransparent(this.context)&&(this.context.scene.background=i),((t=this.context.mainCameraComponent)==null?void 0:t.backgroundBlurriness)!==void 0&&(this.context.scene.backgroundBlurriness=this.context.mainCameraComponent.backgroundBlurriness))}isRemoteTexture(t){return t.startsWith("http://")||t.startsWith("https://")}isValidTextureType(t){for(const i of this.validTextureTypes)if(t.endsWith(i))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)}}Ih([u0(cn.prototype.urlChangedSyncField),m(URL)],cn.prototype,"url",2),Ih([m()],cn.prototype,"allowDrop",2),Ih([m()],cn.prototype,"background",2),Ih([m()],cn.prototype,"environment",2),Ih([m()],cn.prototype,"allowNetworking",2);function uI(s,t,i){const n=t&&!i;switch(s?.toLowerCase()){case"studio":return n?"https://cdn.needle.tools/static/skybox/modelviewer-Neutral-small.hdr":"https://cdn.needle.tools/static/skybox/modelviewer-Neutral.hdr";case"blurred-skybox":return n?"https://cdn.needle.tools/static/skybox/blurred-skybox-small.exr":"https://cdn.needle.tools/static/skybox/blurred-skybox.exr";case"quicklook-ar":return n?"https://cdn.needle.tools/static/skybox/QuickLook-ARMode-small.exr":"https://cdn.needle.tools/static/skybox/QuickLook-ARMode.exr";case"quicklook":return n?"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode-small.exr":"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode.exr"}return s===void 0?null:s}var pI=Object.defineProperty,mI=Object.getOwnPropertyDescriptor,Dp=(s,t,i,n)=>{for(var o=n>1?void 0:n?mI(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&pI(t,i,o),o},ry;const T1=(ry=class extends A{constructor(){super(...arguments),a(this,"target",null),a(this,"followFactor",.1),a(this,"rotateFactor",.1),a(this,"positionAxes",Na.All),a(this,"flipForward",!1),a(this,"_firstUpdate",!0)}onBeforeRender(){this.updateNow(!1)}updateNow(s){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){const t=te(this.target),i=this._firstUpdate||s?1:W.clamp01(this.context.time.deltaTime*this.followFactor),n=this.worldPosition;this.positionAxes&Na.X&&(n.x=W.lerp(n.x,t.x,i)),this.positionAxes&Na.Y&&(n.y=W.lerp(n.y,t.y,i)),this.positionAxes&Na.Z&&(n.z=W.lerp(n.z,t.z,i)),this.worldPosition=n}if(this.rotateFactor>0){const t=Ce(this.target);this.flipForward&&t.premultiply(T1._invertForward);const i=this._firstUpdate||s?1:W.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(t,i)}this._firstUpdate=!1}}},a(ry,"_invertForward",new V().setFromAxisAngle(new x(0,1,0),Math.PI)),ry);let Qo=T1;Dp([m(I)],Qo.prototype,"target",2),Dp([m()],Qo.prototype,"followFactor",2),Dp([m()],Qo.prototype,"rotateFactor",2),Dp([m()],Qo.prototype,"positionAxes",2);var gI=Object.defineProperty,fI=Object.getOwnPropertyDescriptor,jh=(s,t,i,n)=>{for(var o=n>1?void 0:n?fI(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&gI(t,i,o),o};const Lh=C("debugspatialtrigger"),E1=new so,A1=new so;function yI(s,t){return E1.mask=s,A1.mask=t,E1.test(A1)}class hn extends A{constructor(){super(...arguments),a(this,"triggerMask",0),a(this,"onEnter"),a(this,"onStay"),a(this,"onExit"),a(this,"currentIntersected",[]),a(this,"lastIntersected",[])}start(){Lh&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(const t of Dh.triggers)yI(t.triggerMask,this.triggerMask)&&t.test(this.gameObject)&&this.currentIntersected.push(t);for(let t=this.lastIntersected.length-1;t>=0;t--){const i=this.lastIntersected[t];this.currentIntersected.indexOf(i)<0&&(this.onExitTrigger(i),this.lastIntersected.splice(t,1))}for(const t of this.currentIntersected)this.lastIntersected.indexOf(t)<0&&this.onEnterTrigger(t),this.onStayTrigger(t);this.lastIntersected.length=0,this.lastIntersected.push(...this.currentIntersected)}onEnterTrigger(t){var i;Lh&&console.log("ENTER TRIGGER",this.name,t.name,this,t),t.raiseOnEnterEvent(this),(i=this.onEnter)==null||i.invoke()}onExitTrigger(t){var i;Lh&&console.log("EXIT TRIGGER",this.name,t.name),t.raiseOnExitEvent(this),(i=this.onExit)==null||i.invoke()}onStayTrigger(t){var i;t.raiseOnStayEvent(this),(i=this.onStay)==null||i.invoke()}}jh([m()],hn.prototype,"triggerMask",2),jh([m(Se)],hn.prototype,"onEnter",2),jh([m(Se)],hn.prototype,"onStay",2),jh([m(Se)],hn.prototype,"onExit",2);var ay;const Bp=(ay=class extends A{constructor(){super(...arguments),a(this,"triggerMask"),a(this,"boxHelper")}start(){Lh&&console.log(this.name,this.triggerMask,this)}onEnable(){var s;Bp.triggers.push(this),this.boxHelper||(this.boxHelper=O.addComponent(this.gameObject,Ji),(s=this.boxHelper)==null||s.showHelper(null,Lh))}onDisable(){Bp.triggers.splice(Bp.triggers.indexOf(this),1)}test(s){return this.boxHelper?this.boxHelper.isInBox(s)??!1:!1}raiseOnEnterEvent(s){O.foreachComponent(this.gameObject,t=>{t!==s&&t instanceof hn&&t.onEnterTrigger(this)},!1)}raiseOnStayEvent(s){O.foreachComponent(this.gameObject,t=>{t!==s&&t instanceof hn&&t.onStayTrigger(this)},!1)}raiseOnExitEvent(s){O.foreachComponent(this.gameObject,t=>{t!==s&&t instanceof hn&&t.onExitTrigger(this)},!1)}},a(ay,"triggers",[]),ay);let Dh=Bp;jh([m()],Dh.prototype,"triggerMask",2);var vI=Object.defineProperty,bI=Object.getOwnPropertyDescriptor,_I=(s,t,i,n)=>{for(var o=n>1?void 0:n?bI(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&vI(t,i,o),o};const Fi=C("debugspectator");class Fp extends A{constructor(){super(...arguments),a(this,"cam",null),a(this,"useKeys",!0),a(this,"_mode",0),a(this,"orbit",null),a(this,"_handler"),a(this,"eventSub_WebXRRequestStartEvent",null),a(this,"eventSub_WebXRStartEvent",null),a(this,"eventSub_WebXREndEvent",null),a(this,"_debug"),a(this,"_networking")}get mode(){return this._mode}set mode(t){this._mode=t}get isSpectating(){var t;return((t=this._handler)==null?void 0:t.currentTarget)!==void 0}isSpectatingUser(t){var i;return((i=this.target)==null?void 0:i.userId)===t}isFollowedBy(t){var i;return(i=this.followers)==null?void 0:i.includes(t)}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(t){var i;if(this._handler){const n=(i=this._handler.currentTarget)==null?void 0:i.userId,o=this.context.players.getPlayerView(this.localId);t===void 0||this.context.isInXR===!1&&o?.currentObject===t.currentObject?this._handler.currentTarget!==void 0&&(this._handler.disable(),O.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(t,n)):this._handler.currentTarget!==t&&(this._handler.set(t),O.setActive(this.gameObject,!0),this.orbit&&(this.orbit.enabled=!1),this._networking.onSpectatedObjectChanged(t,n))}}get target(){var t;return(t=this._handler)==null?void 0:t.currentTarget}requestAllFollowMe(){this._networking.onRequestFollowMe()}get isSpectatingSelf(){var t,i;return this.isSpectating&&((t=this.target)==null?void 0:t.currentObject)===((i=this.context.players.getPlayerView(this.localId))==null?void 0:i.currentObject)}awake(){if(this._debug=new SI(this.context,this),this._networking=new PI(this.context,this),this._networking.awake(),O.setActive(this.gameObject,!1),this.cam=O.getComponent(this.gameObject,Oe),!this.cam){console.warn("SpectatorCamera: Spectator camera needs camera component on the same object.",this);return}!this._handler&&this.cam&&(this._handler=new wI(this.context,this.cam,this)),this.orbit=O.getComponent(this.context.mainCamera,be)}onDestroy(){var t,i;this.stopSpectating(),(t=this._handler)==null||t.destroy(),(i=this._networking)==null||i.destroy()}isSupportedPlatform(){const t=window.navigator.userAgent,i=/Windows|MacOS/.test(t),n=/Windows NT/.test(t)&&/Edg/.test(t)&&!/Win64/.test(t);return i&&!n}onBeforeXR(t){this.isSupportedPlatform()&&O.setActive(this.gameObject,!0)}onEnterXR(t){this.isSupportedPlatform()&&(Fi&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onLeaveXR(t){var i,n;this.context.removeCamera(this.cam),O.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),(i=this._handler)==null||i.set(void 0),(n=this._handler)==null||n.disable(),this.isSpectatingSelf&&this.stopSpectating()}followSelf(){this.target=this.context.players.getPlayerView(this.context.connection.connectionId),this.target||(this.context.players.setPlayerView(this.localId,this.context.mainCamera,yo.Headset),this.target=this.context.players.getPlayerView(this.localId)),Fi&&console.log("Follow self",this.target)}onAfterRender(){var t,i,n;if(!this.cam)return;const o=this.context.renderer,r=o.xr.enabled;if(!o.xr.isPresenting&&!((t=this._handler)!=null&&t.currentTarget))return;(i=this._handler)==null||i.update(this._mode);const l=o.getRenderTarget();let c=null;const h=o.state;if(!l){if(!o.state.bindFramebuffer||!h.bindXRFramebuffer)return;c=o._framebuffer,h.bindXRFramebuffer(null)}this.setAvatarFlagsBeforeRender();const d=this.context.mainCameraComponent;if(d){const g=d.backgroundColor;g&&o.setClearColor(g,g.alpha),this.cam.backgroundColor=g,this.cam.clearFlags=d.clearFlags,this.cam.nearClipPlane=d.nearClipPlane,this.cam.farClipPlane=d.farClipPlane}else o.setClearColor(new ae(1,1,1));o.setRenderTarget(null),o.xr.enabled=!1;const u=(n=this.cam)==null?void 0:n.threeCamera;this.context.updateAspect(u);const p=o.xr.isPresenting;o.xr.isPresenting=!1,o.setSize(this.context.domWidth,this.context.domHeight),o.render(this.context.scene,u),o.xr.isPresenting=p,o.xr.enabled=r,l?o.setRenderTarget(l):h.bindXRFramebuffer&&h.bindXRFramebuffer(c),this.resetAvatarFlags()}setAvatarFlagsBeforeRender(){const t=this._mode===0;for(const i of Mt.instances)if(i.avatar&&"isLocalAvatar"in i.avatar&&"flags"in i.avatar){let n=Ys.All;this.isSpectatingSelf&&(n=t&&i.avatar.isLocalAvatar?Ys.FirstPerson:Ys.ThirdPerson);const o=i.avatar.flags;if(!o)continue;for(const r of o)r.UpdateVisible(n)}}resetAvatarFlags(){var t;for(const i of Mt.instances)if(i.avatar&&"flags"in i.avatar){const n=i.avatar.flags;if(!n)continue;for(const o of n)"isLocalAvatar"in i.avatar&&(t=i.avatar)!=null&&t.isLocalAvatar?o.UpdateVisible(Ys.FirstPerson):o.UpdateVisible(Ys.ThirdPerson)}}}_I([m()],Fp.prototype,"useKeys",2);class wI{constructor(t,i,n){a(this,"context"),a(this,"cam"),a(this,"spectator"),a(this,"follow"),a(this,"target"),a(this,"view"),a(this,"currentObject"),this.context=t,this.cam=i,this.spectator=n}get currentTarget(){return this.view}set(t){const i=t?.currentObject;if(!i){this.spectator.stopSpectating();return}i!==this.currentObject&&(this.currentObject=i,this.view=t,this.follow||(this.follow=O.addComponent(this.cam.gameObject,Qo)),this.target||(this.target=new I),i.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,Fi&&console.log("FOLLOW",i),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){Fi&&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(){var t;(t=this.target)==null||t.removeFromParent(),this.follow&&O.destroy(this.follow)}update(t){var i,n,o,r,l,c;if(((i=this.currentTarget)==null?void 0:i.isConnected)===!1||((n=this.currentTarget)==null?void 0:n.removed)===!0){Fi&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&((o=this.currentTarget)==null?void 0:o.currentObject)!==this.currentObject&&(Fi&&console.log("Target changed",this.currentObject,"to",this.currentTarget.currentObject),this.set(this.currentTarget));const h=this.context.mainCamera;if(h){const u=this.cam.threeCamera;(u.near!==h.near||u.far!==h.far)&&(u.near=h.near,u.far=h.far,u.updateProjectionMatrix())}const d=(r=this.follow)==null?void 0:r.target;if(!(!d||!this.follow)){switch(t){case 0:((l=this.view)==null?void 0:l.viewDevice)!==yo.Browser?(this.follow.followFactor=5,this.follow.rotateFactor=5):(this.follow.followFactor=50,this.follow.rotateFactor=50),d.position.set(0,0,0);break;case 1:this.follow.followFactor=3,this.follow.rotateFactor=2,d.position.set(0,.5,1.5);break}this.follow.flipForward=!1,((c=this.view)==null?void 0:c.viewDevice)!==yo.Browser?d.quaternion.copy(xI):d.quaternion.identity()}}}const xI=new V().setFromAxisAngle(new x(0,1,0),Math.PI);class SI{constructor(t,i){a(this,"context"),a(this,"spectator"),this.context=t,this.spectator=i,console.log("[Spectator Camera] Click other avatars or cameras to follow them. Press ESC to exit spectator mode."),this.context.domElement.addEventListener("keydown",o=>{!this.spectator.useKeys||o.key==="Escape"&&this.spectator.stopSpectating()});let n=0;this.context.input.addEventListener(Be.PointerDown,o=>{n=this.context.time.time}),this.context.input.addEventListener(Be.PointerUp,o=>{const r=this.context.time.time-n;r>1?this.spectator.stopSpectating():this.context.input.getPointerClicked(0)&&r<.3&&this.trySelectObject()})}trySelectObject(){const t=new Ws;t.setMask(16777215);const i=this.context.physics.raycast(t);if(Fi&&console.log(...i),i!=null&&i.length)for(const n of i){if(n.distance<.2)continue;const o=n.object,r=O.getComponentInParent(o,Mt),l=r?.connectionId;if(l){const c=this.context.players.getPlayerView(l);this.spectator.target=c,Fi&&console.log("spectate",l,r);break}}}}class CI{constructor(t,i,n){a(this,"guid"),a(this,"dontSave",!0),a(this,"targetUserId"),a(this,"stoppedFollowing"),this.guid=t,this.targetUserId=i,this.stoppedFollowing=n}}class OI{constructor(t,i){a(this,"guid"),a(this,"userId"),this.guid=t.guid,this.userId=i}}class PI{constructor(t,i){a(this,"followers",[]),a(this,"context"),a(this,"spectator"),a(this,"_followerEventMethod"),a(this,"_requestFollowMethod"),a(this,"_joinedRoomMethod"),a(this,"_lastRequestFollowUser"),a(this,"_enforceFollowInterval"),this.context=t,this.spectator=i,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(se.JoinedRoom,this._joinedRoomMethod),this.context.domElement.addEventListener("keydown",t=>{this.spectator.useKeys&&(t.key==="f"?this.onRequestFollowMe():t.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(se.JoinedRoom,this._joinedRoomMethod)}onSpectatedObjectChanged(t,i){if(Fi&&console.log(this.context.connection.connectionId,"onSpectatedObjectChanged",t,i),this.context.connection.connectionId){const n=t?.userId===void 0,o=n?i:t?.userId,r=new CI(this.context.connection.connectionId,o,n);this.context.connection.send("spectator-follower-changed",r)}}onRequestFollowMe(t=!1){if(Fi&&console.log("Request follow",this.context.connection.connectionId),this.context.connection.connectionId){this.spectator.stopSpectating();const i=t?void 0:this.context.connection.connectionId,n=new OI(this.spectator,i);this.context.connection.send("spectator-request-follow",n)}}onUserJoinedRoom(){C("followme")&&this.onRequestFollowMe()}onFollowerEvent(t){const i=t.targetUserId,n=t.guid;if(Fi&&console.log(t),i===this.context.connection.connectionId)if(t.stoppedFollowing){const o=this.followers.indexOf(n);o!==-1&&(this.followers.splice(o,1),this.removeDisconnectedFollowers(),console.log(n,"unfollows you",this.followers.length))}else this.followers.includes(n)||(this.followers.push(n),this.removeDisconnectedFollowers(),console.log(n,"follows you",this.followers.length))}removeDisconnectedFollowers(){for(let t=this.followers.length-1;t>=0;t--){const i=this.followers[t];this.context.connection.userIsInRoom(i)===!1&&this.followers.splice(t,1)}}onRequestFollowEvent(t){if(this._lastRequestFollowUser=t,t.userId===this.context.connection.connectionId)this.spectator.stopSpectating();else if(t.userId===void 0)this.spectator.stopSpectating();else{const i=this.context.players.getPlayerView(t.userId);if(i)this.spectator.target=i;else return Fi&&console.warn("Could not find view",t.userId),this.enforceFollow(),!1}return!0}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):(Fi&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}}class pn{constructor(){a(this,"bb",null),a(this,"bb_pos",0)}__init(t,i){return this.bb_pos=t,this.bb=i,this}static getRootAsSyncedCameraModel(t,i){return(i||new pn).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSyncedCameraModel(t,i){return t.setPosition(t.position()+uv),(i||new pn).__init(t.readInt32(t.position())+t.position(),t)}userId(t){const i=this.bb.__offset(this.bb_pos,4);return i?this.bb.__string(this.bb_pos+i,t):null}guid(t){const i=this.bb.__offset(this.bb_pos,6);return i?this.bb.__string(this.bb_pos+i,t):null}dontSave(){const t=this.bb.__offset(this.bb_pos,8);return t?!!this.bb.readInt8(this.bb_pos+t):!1}pos(t){const i=this.bb.__offset(this.bb_pos,10);return i?(t||new Rr).__init(this.bb_pos+i,this.bb):null}rot(t){const i=this.bb.__offset(this.bb_pos,12);return i?(t||new Rr).__init(this.bb_pos+i,this.bb):null}static startSyncedCameraModel(t){t.startObject(5)}static addUserId(t,i){t.addFieldOffset(0,i,0)}static addGuid(t,i){t.addFieldOffset(1,i,0)}static addDontSave(t,i){t.addFieldInt8(2,+i,0)}static addPos(t,i){t.addFieldStruct(3,i,0)}static addRot(t,i){t.addFieldStruct(4,i,0)}static endSyncedCameraModel(t){return t.endObject()}static finishSyncedCameraModelBuffer(t,i){t.finish(i)}static finishSizePrefixedSyncedCameraModelBuffer(t,i){t.finish(i,void 0,!0)}}var kI=Object.defineProperty,MI=Object.getOwnPropertyDescriptor,RI=(s,t,i,n)=>{for(var o=n>1?void 0:n?MI(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&kI(t,i,o),o};const zp="SCAM";sg(zp,pn.getRootAsSyncedCameraModel);const zi=new vm;class TI{constructor(t,i){a(this,"userId"),a(this,"guid"),this.guid=i,this.userId=t}send(t,i){if(t){zi.clear();const n=zi.createString(this.guid),o=zi.createString(this.userId);pn.startSyncedCameraModel(zi),pn.addGuid(zi,n),pn.addUserId(zi,o);const r=te(t),l=ic(t);pn.addPos(zi,Rr.createVec3(zi,r.x,r.y,r.z)),pn.addRot(zi,Rr.createVec3(zi,l.x,l.y,l.z));const c=pn.endSyncedCameraModel(zi);zi.finish(c,zp),i.sendBinary(zi.asUint8Array())}}}var ly;const cy=(ly=class extends A{constructor(){super(...arguments),a(this,"cameraPrefab",null),a(this,"_lastWorldPosition"),a(this,"_lastWorldQuaternion"),a(this,"_model",null),a(this,"_needsUpdate",!0),a(this,"_lastUpdateTime",0),a(this,"remoteCams",{}),a(this,"userToCamMap",{}),a(this,"_camTimeoutInSeconds",10),a(this,"_receiveCallback",null)}getCameraObject(s){const t=this.userToCamMap[s];return t?this.remoteCams[t].obj: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(zp,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(zp,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){F()&&console.log("Remote cam timeout",n),o!=null&&o.obj&&O.destroy(o.obj),delete this.remoteCams[n],o&&delete this.userToCamMap[o.userId],cy.instances.push(o),this.context.players.removePlayerView(o.userId,yo.Browser);continue}}if(this.context.isInXR)return;const s=this.context.mainCamera;if(s===null){this.enabled=!1;return}if(!this.context.connection.isConnected||this.context.connection.connectionId===null)return;this._model===null&&(this._model=new TI(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));const t=te(s),i=Ce(s);(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(s,this.context.connection),this.context.isInXR||this.context.players.setPlayerView(this.context.connection.connectionId,s,yo.Browser))}onReceivedRemoteCameraInfoBin(s){const t=s.guid();if(!t)return;const i=s.userId();if(!i||!this.context.connection.userIsInRoom(i)||!this.cameraPrefab)return;let n=this.remoteCams[t];if(!n)if("isObject3D"in this.cameraPrefab){const c=new Ds;c.context=this.context;const h=O.instantiate(this.cameraPrefab,c);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,cy.instances.push(n);const d=O.getOrAddComponent(h,Mt);d.connectionId=i,d.avatar=h}else return;const o=n.obj;this.context.players.setPlayerView(i,o,yo.Browser),n.lastUpdate=this.context.time.realtimeSinceStartup,as.markDirty(o);const r=s.pos();r&&lr(o,r.x(),r.y(),r.z());const l=s.rot();l&&sc(o,l.x(),l.y(),l.z())}},a(ly,"instances",[]),ly);let Up=cy;RI([m([I,le])],Up.prototype,"cameraPrefab",2);var EI=Object.defineProperty,AI=Object.getOwnPropertyDescriptor,Yo=(s,t,i,n)=>{for(var o=n>1?void 0:n?AI(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&EI(t,i,o),o};const hy="view",dy=C("debugsyncedroom");class js extends A{constructor(){super(...arguments),a(this,"roomName",""),a(this,"urlParameterName","room"),a(this,"joinRandomRoom"),a(this,"requireRoomParameter",!1),a(this,"autoRejoin",!0),a(this,"createJoinButton",!0),a(this,"createViewOnlyButton",!1),a(this,"_lastJoinedRoom"),a(this,"_roomPrefix",""),a(this,"_lastPingTime",0),a(this,"_lastRoomTime",-1),a(this,"_userWantsToBeInARoom",!1),a(this,"_roomButton"),a(this,"_roomButtonIconJoin"),a(this,"_roomButtonIconLeave"),a(this,"updateRoomButtonState",()=>{var t,i;this._roomButton&&(this.context.connection.isInRoom?(this._roomButton.title="Leave the networked room",this._roomButton.textContent="Leave Room",(t=this._roomButtonIconJoin)==null||t.remove(),this._roomButton.prepend(this._roomButtonIconLeave)):(this._roomButton.title="Create or join a networked room",this._roomButton.textContent="Join Room",(i=this._roomButtonIconLeave)==null||i.remove(),this._roomButton.prepend(this._roomButtonIconJoin)))}),a(this,"_viewOnlyButton"),a(this,"onCreateViewOnlyButton",()=>{if(!this._viewOnlyButton){const t=document.createElement("button");this._viewOnlyButton=t,t.classList.add("view-only-button"),t.setAttribute("priority","90"),t.onclick=()=>{var i;const n=this.getViewOnlyUrl();n!=null&&n.length?navigator.canShare({url:n})?(i=navigator.share({url:n}))==null||i.catch(o=>{console.warn(o)}):(navigator.clipboard.writeText(n),De("View only URL copied to clipboard")):we("Could not create view only URL")},t.title="Copy the view only URL: A page accessed by the view only URL can not be modified by visiting users.",t.textContent="Share View URL",t.prepend(Ot("visibility"))}this.context.menu.appendChild(this._viewOnlyButton)})}get currentRoomName(){return C(hy)||C(this.urlParameterName)}set roomPrefix(t){this._roomPrefix=t}get roomPrefix(){return this._roomPrefix}awake(){var t;this.joinRandomRoom===void 0&&((t=this.roomName)==null?void 0:t.length)<=0&&(this.joinRandomRoom=!0),dy&&console.log(`SyncedRoom roomName:${this.roomName}, urlParamName:${this.urlParameterName}, joinRandomRoom:${this.joinRandomRoom}`)}onEnable(){const t=C(hy);if(t&&typeof t=="string"&&t.length>0){console.log("Join as viewer"),this.context.connection.joinRoom(t,!0);return}if(this.tryJoinRoom(),this.createJoinButton){const i=this.createRoomButton();this.context.menu.appendChild(i)}this.createViewOnlyButton&&this.onEnableViewOnlyButton()}onDisable(){var t;(t=this._roomButton)==null||t.remove(),this.onDisableViewOnlyButton(),this.roomName&&this.roomName.length>0&&this.context.connection.leaveRoom(this.roomName)}onDestroy(){this.destroyRoomButton()}tryJoinRandomRoom(){this.setRandomRoomUrlParameter(),this.tryJoinRoom()}tryJoinRoom(t=0){var i;t===void 0&&(t=0);let n=!1;if(((i=this.urlParameterName)==null?void 0:i.length)>0){const o=C(this.urlParameterName);if(o&&(typeof o=="string"||typeof o=="number")){n=!0;const r=kv(o.toString());this.roomName=r}else if(this.joinRandomRoom&&(console.log("No room name found in url, generating random one"),this.setRandomRoomUrlParameter(),t<1))return this.tryJoinRoom(t+1)}else this.joinRandomRoom&&(this.roomName===null||this.roomName===void 0||this.roomName.length<=0)&&(this.roomName=this.generateRoomName());return this.requireRoomParameter&&!n?((dy||F())&&console.warn('[SyncedRoom] Missing required room parameter "'+this.urlParameterName+`" in url - will not connect.
1333
+ `)},t.userData.isLightBlendMaterial=!0}applyShadowMaterial(){if(this.targetMesh)if(this.targetMesh.material.type!=="ShadowMaterial"){const t=new Uy;t.color=this.shadowColor,t.opacity=this.shadowColor.alpha,this.applyMaterialOptions(t),this.targetMesh.material=t,t.userData.isShadowCatcherMaterial=!0}else{const t=this.targetMesh.material;t.color=this.shadowColor,t.opacity=this.shadowColor.alpha,this.applyMaterialOptions(t),t.userData.isShadowCatcherMaterial=!0}}applyOccluderMaterial(){if(this.targetMesh){let t=this.targetMesh.material;if(!t){const i=new Re;this.targetMesh.material=i,t=i}t.depthWrite=!0,t.stencilWrite=!0,t.colorWrite=!1,this.gameObject.renderOrder=-100}}applyMaterialOptions(t){t&&(t.depthWrite=!1,t.stencilWrite=!1)}}P1([m()],Ah.prototype,"mode",2),P1([m(xe)],Ah.prototype,"shadowColor",2);var cI=Object.defineProperty,hI=Object.getOwnPropertyDescriptor,Ih=(s,t,i,n)=>{for(var o=n>1?void 0:n?hI(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&cI(t,i,o),o};const os=C("debugskybox");oy("skybox-image"),oy("environment-image");function k1(s,t,i,n,o){const r=new cn;r.allowDrop=!1,r.allowNetworking=!1,r.background=i,r.environment=n,O.addComponent(s.scene,r);const l=c=>{typeof c=="string"&&(os&&console.log(o,"CHANGED TO",c),r.setSkybox(c))};return Rv(s.domElement,o,l),r.addEventListener("destroy",()=>{os&&console.log("Destroyed attribute remote skybox",o),Tv(s.domElement,o,l)}),r.setSkybox(t)}const Lp=new Array;ue.registerCallback(ge.ContextCreationStart,s=>{var t;const i=s.context,n=i.domElement.getAttribute("skybox-image")||i.domElement.getAttribute("background-image"),o=i.domElement.getAttribute("environment-image");if(n){os&&console.log("Creating remote skybox to load "+n),((t=i.mainCameraComponent)==null?void 0:t.clearFlags)!==Oo.Skybox&&console.warn('"skybox-image"/"background-image" attribute has no effect: camera clearflags are not set to "Skybox"');const r=k1(i,n,!0,!1,"skybox-image");Lp.push(r)}if(o){os&&console.log("Creating remote environment to load "+o);const r=k1(i,o,!1,!0,"environment-image");Lp.push(r)}}),ue.registerCallback(ge.ContextCreationStart,()=>Promise.all(Lp).finally(()=>{Lp.length=0}));function M1(){return globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES||(globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES=new Array),globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES}function R1(s){const t=M1().find(i=>i.src===s);return t?(os&&console.log("Skybox: Found previously loaded texture for "+s),t.texture):null}async function dI(s){const t=await s;_g(t,!0),Ee(t)}function uI(s,t){const i=M1();for(;i.length>5;){const n=i.shift();n&&dI(n.texture)}t.then(n=>_g(n,!1)),i.push({src:s,texture:t})}class cn extends A{constructor(){super(...arguments),a(this,"url"),a(this,"allowDrop",!0),a(this,"background",!0),a(this,"environment",!0),a(this,"allowNetworking",!0),a(this,"_loader"),a(this,"_prevUrl"),a(this,"_prevLoadedEnvironment"),a(this,"_prevEnvironment",null),a(this,"_prevBackground",null),a(this,"validTextureTypes",[".ktx2",".hdr",".exr",".jpg",".jpeg",".png"]),a(this,"onDragOverEvent",t=>{if(this.allowDrop&&t.dataTransfer)for(const i of t.dataTransfer.types)(i==="text/uri-list"||i==="Files")&&t.preventDefault()}),a(this,"onDrop",t=>{var i,n,o,r;if(this.allowDrop&&t.dataTransfer){for(const l of t.dataTransfer.types)if(os&&console.log(l),l==="text/uri-list"){const c=t.dataTransfer.getData(l);os&&console.log(l,c);let h=(n=(i=new RegExp(/polyhaven.com\/asset_img\/.+?\/(?<name>.+)\.png/).exec(c))==null?void 0:i.groups)==null?void 0:n.name;if(h||(h=(r=(o=new RegExp(/polyhaven\.com\/a\/(?<name>.+)/).exec(c))==null?void 0:o.groups)==null?void 0:r.name),os&&console.log(h),h){const d="https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/"+h+"_1k.exr";console.log(`[Remote Skybox] Setting skybox from url: ${d}`),t.preventDefault(),this.setSkybox(d);break}else if(this.isValidTextureType(c)){console.log("[Remote Skybox] Setting skybox from url: "+c),t.preventDefault(),this.setSkybox(c);break}else{console.warn(`[RemoteSkybox] Unknown url ${c}. 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 d=new CustomEvent("dropped-unknown-url",{detail:{sender:this,event:t,url:c,apply:u=>{t.preventDefault(),this.setSkybox(u)}}});this.dispatchEvent(d)}}else if(l=="Files"){const c=t.dataTransfer.files.item(0);if(os&&console.log(l,c),!c)continue;if(!this.isValidTextureType(c.name)){console.warn(`[RemoteSkybox]: File "${c.name}" is not supported. Supported files are ${this.validTextureTypes.join(", ")}`);return}if(R1(c.name)===null){const h=new Blob([c]),d=URL.createObjectURL(h);t.preventDefault(),this.setSkybox(d,c.name)}else t.preventDefault(),this.setSkybox(c.name);break}}})}onEnable(){this.setSkybox(this.url),this.registerDropEvents()}onDisable(){var t;this.context.scene.environment===this._prevLoadedEnvironment&&(this.context.scene.environment=this._prevEnvironment,Oe.backgroundShouldBeTransparent(this.context)||(this.context.scene.background=this._prevBackground),this._prevLoadedEnvironment=void 0),this.unregisterDropEvents(),(t=this.context.mainCameraComponent)==null||t.applyClearFlags()}urlChangedSyncField(){this.allowNetworking&&this.url&&this.isRemoteTexture(this.url)&&this.setSkybox(this.url)}async setSkybox(t,i){var n;if(!this.activeAndEnabled||(t=pI(t,this.environment,this.background),!t))return!1;if(i??(i=t),this.isValidTextureType(i)||console.warn("Potentially invalid skybox url",i,"on",this.name),os&&console.log("Set remote skybox url: "+t),this._prevUrl===t&&this._prevLoadedEnvironment)return this.applySkybox(),!0;(n=this._prevLoadedEnvironment)==null||n.dispose(),this._prevLoadedEnvironment=void 0,this._prevUrl=t;const o=await this.loadTexture(t,i);if(!o||!this.enabled)return!1;this.url=t;const r=t.lastIndexOf("/");return o.name=t.substring(r>=0?r+1:0),this._loader instanceof ma&&(o.colorSpace=ms),this._prevLoadedEnvironment=o,this.applySkybox(),!0}async loadTexture(t,i){var n,o,r,l,c;if(!t)return Promise.resolve(null);i??(i=t);const h=R1(i);if(h){const y=await h;if(((o=(n=y.source)==null?void 0:n.data)==null?void 0:o.length)>0||(c=(l=(r=y.source)==null?void 0:r.data)==null?void 0:l.data)!=null&&c.length)return y}const d=i.endsWith(".exr"),u=i.endsWith(".hdr"),p=i.endsWith(".ktx2");if(d)this._loader instanceof ud||(this._loader=new ud);else if(u)this._loader instanceof fm||(this._loader=new fm);else if(p){if(!(this._loader instanceof QC)){const{ktx2Loader:y}=gm(this.context.renderer);this._loader=y}}else this._loader instanceof ma||(this._loader=new ma);os&&console.log("Loading skybox: "+t);const g=this._loader.loadAsync(t);return uI(i,g),await g}applySkybox(){var t;const i=this._prevLoadedEnvironment;i&&(i instanceof SC||i instanceof CC||(i.mapping=OC,i.needsUpdate=!0),this.context.scene.background!==i&&(this._prevBackground=this.context.scene.background),this.context.scene.environment!==i&&(this._prevEnvironment=this.context.scene.environment),os&&console.log("Set remote skybox",this.url,!Oe.backgroundShouldBeTransparent(this.context)),this.environment&&(this.context.scene.environment=i),this.background&&!Oe.backgroundShouldBeTransparent(this.context)&&(this.context.scene.background=i),((t=this.context.mainCameraComponent)==null?void 0:t.backgroundBlurriness)!==void 0&&(this.context.scene.backgroundBlurriness=this.context.mainCameraComponent.backgroundBlurriness))}isRemoteTexture(t){return t.startsWith("http://")||t.startsWith("https://")}isValidTextureType(t){for(const i of this.validTextureTypes)if(t.endsWith(i))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)}}Ih([u0(cn.prototype.urlChangedSyncField),m(URL)],cn.prototype,"url",2),Ih([m()],cn.prototype,"allowDrop",2),Ih([m()],cn.prototype,"background",2),Ih([m()],cn.prototype,"environment",2),Ih([m()],cn.prototype,"allowNetworking",2);function pI(s,t,i){const n=t&&!i;switch(s?.toLowerCase()){case"studio":return n?"https://cdn.needle.tools/static/skybox/modelviewer-Neutral-small.hdr":"https://cdn.needle.tools/static/skybox/modelviewer-Neutral.hdr";case"blurred-skybox":return n?"https://cdn.needle.tools/static/skybox/blurred-skybox-small.exr":"https://cdn.needle.tools/static/skybox/blurred-skybox.exr";case"quicklook-ar":return n?"https://cdn.needle.tools/static/skybox/QuickLook-ARMode-small.exr":"https://cdn.needle.tools/static/skybox/QuickLook-ARMode.exr";case"quicklook":return n?"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode-small.exr":"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode.exr"}return s===void 0?null:s}var mI=Object.defineProperty,gI=Object.getOwnPropertyDescriptor,Dp=(s,t,i,n)=>{for(var o=n>1?void 0:n?gI(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&mI(t,i,o),o},ry;const T1=(ry=class extends A{constructor(){super(...arguments),a(this,"target",null),a(this,"followFactor",.1),a(this,"rotateFactor",.1),a(this,"positionAxes",Na.All),a(this,"flipForward",!1),a(this,"_firstUpdate",!0)}onBeforeRender(){this.updateNow(!1)}updateNow(s){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){const t=te(this.target),i=this._firstUpdate||s?1:W.clamp01(this.context.time.deltaTime*this.followFactor),n=this.worldPosition;this.positionAxes&Na.X&&(n.x=W.lerp(n.x,t.x,i)),this.positionAxes&Na.Y&&(n.y=W.lerp(n.y,t.y,i)),this.positionAxes&Na.Z&&(n.z=W.lerp(n.z,t.z,i)),this.worldPosition=n}if(this.rotateFactor>0){const t=Ce(this.target);this.flipForward&&t.premultiply(T1._invertForward);const i=this._firstUpdate||s?1:W.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(t,i)}this._firstUpdate=!1}}},a(ry,"_invertForward",new V().setFromAxisAngle(new x(0,1,0),Math.PI)),ry);let Qo=T1;Dp([m(I)],Qo.prototype,"target",2),Dp([m()],Qo.prototype,"followFactor",2),Dp([m()],Qo.prototype,"rotateFactor",2),Dp([m()],Qo.prototype,"positionAxes",2);var fI=Object.defineProperty,yI=Object.getOwnPropertyDescriptor,jh=(s,t,i,n)=>{for(var o=n>1?void 0:n?yI(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&fI(t,i,o),o};const Lh=C("debugspatialtrigger"),E1=new so,A1=new so;function vI(s,t){return E1.mask=s,A1.mask=t,E1.test(A1)}class hn extends A{constructor(){super(...arguments),a(this,"triggerMask",0),a(this,"onEnter"),a(this,"onStay"),a(this,"onExit"),a(this,"currentIntersected",[]),a(this,"lastIntersected",[])}start(){Lh&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(const t of Dh.triggers)vI(t.triggerMask,this.triggerMask)&&t.test(this.gameObject)&&this.currentIntersected.push(t);for(let t=this.lastIntersected.length-1;t>=0;t--){const i=this.lastIntersected[t];this.currentIntersected.indexOf(i)<0&&(this.onExitTrigger(i),this.lastIntersected.splice(t,1))}for(const t of this.currentIntersected)this.lastIntersected.indexOf(t)<0&&this.onEnterTrigger(t),this.onStayTrigger(t);this.lastIntersected.length=0,this.lastIntersected.push(...this.currentIntersected)}onEnterTrigger(t){var i;Lh&&console.log("ENTER TRIGGER",this.name,t.name,this,t),t.raiseOnEnterEvent(this),(i=this.onEnter)==null||i.invoke()}onExitTrigger(t){var i;Lh&&console.log("EXIT TRIGGER",this.name,t.name),t.raiseOnExitEvent(this),(i=this.onExit)==null||i.invoke()}onStayTrigger(t){var i;t.raiseOnStayEvent(this),(i=this.onStay)==null||i.invoke()}}jh([m()],hn.prototype,"triggerMask",2),jh([m(Se)],hn.prototype,"onEnter",2),jh([m(Se)],hn.prototype,"onStay",2),jh([m(Se)],hn.prototype,"onExit",2);var ay;const Bp=(ay=class extends A{constructor(){super(...arguments),a(this,"triggerMask"),a(this,"boxHelper")}start(){Lh&&console.log(this.name,this.triggerMask,this)}onEnable(){var s;Bp.triggers.push(this),this.boxHelper||(this.boxHelper=O.addComponent(this.gameObject,Ji),(s=this.boxHelper)==null||s.showHelper(null,Lh))}onDisable(){Bp.triggers.splice(Bp.triggers.indexOf(this),1)}test(s){return this.boxHelper?this.boxHelper.isInBox(s)??!1:!1}raiseOnEnterEvent(s){O.foreachComponent(this.gameObject,t=>{t!==s&&t instanceof hn&&t.onEnterTrigger(this)},!1)}raiseOnStayEvent(s){O.foreachComponent(this.gameObject,t=>{t!==s&&t instanceof hn&&t.onStayTrigger(this)},!1)}raiseOnExitEvent(s){O.foreachComponent(this.gameObject,t=>{t!==s&&t instanceof hn&&t.onExitTrigger(this)},!1)}},a(ay,"triggers",[]),ay);let Dh=Bp;jh([m()],Dh.prototype,"triggerMask",2);var bI=Object.defineProperty,_I=Object.getOwnPropertyDescriptor,wI=(s,t,i,n)=>{for(var o=n>1?void 0:n?_I(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&bI(t,i,o),o};const Fi=C("debugspectator");class Fp extends A{constructor(){super(...arguments),a(this,"cam",null),a(this,"useKeys",!0),a(this,"_mode",0),a(this,"orbit",null),a(this,"_handler"),a(this,"eventSub_WebXRRequestStartEvent",null),a(this,"eventSub_WebXRStartEvent",null),a(this,"eventSub_WebXREndEvent",null),a(this,"_debug"),a(this,"_networking")}get mode(){return this._mode}set mode(t){this._mode=t}get isSpectating(){var t;return((t=this._handler)==null?void 0:t.currentTarget)!==void 0}isSpectatingUser(t){var i;return((i=this.target)==null?void 0:i.userId)===t}isFollowedBy(t){var i;return(i=this.followers)==null?void 0:i.includes(t)}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(t){var i;if(this._handler){const n=(i=this._handler.currentTarget)==null?void 0:i.userId,o=this.context.players.getPlayerView(this.localId);t===void 0||this.context.isInXR===!1&&o?.currentObject===t.currentObject?this._handler.currentTarget!==void 0&&(this._handler.disable(),O.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(t,n)):this._handler.currentTarget!==t&&(this._handler.set(t),O.setActive(this.gameObject,!0),this.orbit&&(this.orbit.enabled=!1),this._networking.onSpectatedObjectChanged(t,n))}}get target(){var t;return(t=this._handler)==null?void 0:t.currentTarget}requestAllFollowMe(){this._networking.onRequestFollowMe()}get isSpectatingSelf(){var t,i;return this.isSpectating&&((t=this.target)==null?void 0:t.currentObject)===((i=this.context.players.getPlayerView(this.localId))==null?void 0:i.currentObject)}awake(){if(this._debug=new CI(this.context,this),this._networking=new kI(this.context,this),this._networking.awake(),O.setActive(this.gameObject,!1),this.cam=O.getComponent(this.gameObject,Oe),!this.cam){console.warn("SpectatorCamera: Spectator camera needs camera component on the same object.",this);return}!this._handler&&this.cam&&(this._handler=new xI(this.context,this.cam,this)),this.orbit=O.getComponent(this.context.mainCamera,be)}onDestroy(){var t,i;this.stopSpectating(),(t=this._handler)==null||t.destroy(),(i=this._networking)==null||i.destroy()}isSupportedPlatform(){const t=window.navigator.userAgent,i=/Windows|MacOS/.test(t),n=/Windows NT/.test(t)&&/Edg/.test(t)&&!/Win64/.test(t);return i&&!n}onBeforeXR(t){this.isSupportedPlatform()&&O.setActive(this.gameObject,!0)}onEnterXR(t){this.isSupportedPlatform()&&(Fi&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onLeaveXR(t){var i,n;this.context.removeCamera(this.cam),O.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),(i=this._handler)==null||i.set(void 0),(n=this._handler)==null||n.disable(),this.isSpectatingSelf&&this.stopSpectating()}followSelf(){this.target=this.context.players.getPlayerView(this.context.connection.connectionId),this.target||(this.context.players.setPlayerView(this.localId,this.context.mainCamera,yo.Headset),this.target=this.context.players.getPlayerView(this.localId)),Fi&&console.log("Follow self",this.target)}onAfterRender(){var t,i,n;if(!this.cam)return;const o=this.context.renderer,r=o.xr.enabled;if(!o.xr.isPresenting&&!((t=this._handler)!=null&&t.currentTarget))return;(i=this._handler)==null||i.update(this._mode);const l=o.getRenderTarget();let c=null;const h=o.state;if(!l){if(!o.state.bindFramebuffer||!h.bindXRFramebuffer)return;c=o._framebuffer,h.bindXRFramebuffer(null)}this.setAvatarFlagsBeforeRender();const d=this.context.mainCameraComponent;if(d){const g=d.backgroundColor;g&&o.setClearColor(g,g.alpha),this.cam.backgroundColor=g,this.cam.clearFlags=d.clearFlags,this.cam.nearClipPlane=d.nearClipPlane,this.cam.farClipPlane=d.farClipPlane}else o.setClearColor(new ae(1,1,1));o.setRenderTarget(null),o.xr.enabled=!1;const u=(n=this.cam)==null?void 0:n.threeCamera;this.context.updateAspect(u);const p=o.xr.isPresenting;o.xr.isPresenting=!1,o.setSize(this.context.domWidth,this.context.domHeight),o.render(this.context.scene,u),o.xr.isPresenting=p,o.xr.enabled=r,l?o.setRenderTarget(l):h.bindXRFramebuffer&&h.bindXRFramebuffer(c),this.resetAvatarFlags()}setAvatarFlagsBeforeRender(){const t=this._mode===0;for(const i of Mt.instances)if(i.avatar&&"isLocalAvatar"in i.avatar&&"flags"in i.avatar){let n=Ys.All;this.isSpectatingSelf&&(n=t&&i.avatar.isLocalAvatar?Ys.FirstPerson:Ys.ThirdPerson);const o=i.avatar.flags;if(!o)continue;for(const r of o)r.UpdateVisible(n)}}resetAvatarFlags(){var t;for(const i of Mt.instances)if(i.avatar&&"flags"in i.avatar){const n=i.avatar.flags;if(!n)continue;for(const o of n)"isLocalAvatar"in i.avatar&&(t=i.avatar)!=null&&t.isLocalAvatar?o.UpdateVisible(Ys.FirstPerson):o.UpdateVisible(Ys.ThirdPerson)}}}wI([m()],Fp.prototype,"useKeys",2);class xI{constructor(t,i,n){a(this,"context"),a(this,"cam"),a(this,"spectator"),a(this,"follow"),a(this,"target"),a(this,"view"),a(this,"currentObject"),this.context=t,this.cam=i,this.spectator=n}get currentTarget(){return this.view}set(t){const i=t?.currentObject;if(!i){this.spectator.stopSpectating();return}i!==this.currentObject&&(this.currentObject=i,this.view=t,this.follow||(this.follow=O.addComponent(this.cam.gameObject,Qo)),this.target||(this.target=new I),i.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,Fi&&console.log("FOLLOW",i),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){Fi&&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(){var t;(t=this.target)==null||t.removeFromParent(),this.follow&&O.destroy(this.follow)}update(t){var i,n,o,r,l,c;if(((i=this.currentTarget)==null?void 0:i.isConnected)===!1||((n=this.currentTarget)==null?void 0:n.removed)===!0){Fi&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&((o=this.currentTarget)==null?void 0:o.currentObject)!==this.currentObject&&(Fi&&console.log("Target changed",this.currentObject,"to",this.currentTarget.currentObject),this.set(this.currentTarget));const h=this.context.mainCamera;if(h){const u=this.cam.threeCamera;(u.near!==h.near||u.far!==h.far)&&(u.near=h.near,u.far=h.far,u.updateProjectionMatrix())}const d=(r=this.follow)==null?void 0:r.target;if(!(!d||!this.follow)){switch(t){case 0:((l=this.view)==null?void 0:l.viewDevice)!==yo.Browser?(this.follow.followFactor=5,this.follow.rotateFactor=5):(this.follow.followFactor=50,this.follow.rotateFactor=50),d.position.set(0,0,0);break;case 1:this.follow.followFactor=3,this.follow.rotateFactor=2,d.position.set(0,.5,1.5);break}this.follow.flipForward=!1,((c=this.view)==null?void 0:c.viewDevice)!==yo.Browser?d.quaternion.copy(SI):d.quaternion.identity()}}}const SI=new V().setFromAxisAngle(new x(0,1,0),Math.PI);class CI{constructor(t,i){a(this,"context"),a(this,"spectator"),this.context=t,this.spectator=i,console.log("[Spectator Camera] Click other avatars or cameras to follow them. Press ESC to exit spectator mode."),this.context.domElement.addEventListener("keydown",o=>{!this.spectator.useKeys||o.key==="Escape"&&this.spectator.stopSpectating()});let n=0;this.context.input.addEventListener(Be.PointerDown,o=>{n=this.context.time.time}),this.context.input.addEventListener(Be.PointerUp,o=>{const r=this.context.time.time-n;r>1?this.spectator.stopSpectating():this.context.input.getPointerClicked(0)&&r<.3&&this.trySelectObject()})}trySelectObject(){const t=new Ws;t.setMask(16777215);const i=this.context.physics.raycast(t);if(Fi&&console.log(...i),i!=null&&i.length)for(const n of i){if(n.distance<.2)continue;const o=n.object,r=O.getComponentInParent(o,Mt),l=r?.connectionId;if(l){const c=this.context.players.getPlayerView(l);this.spectator.target=c,Fi&&console.log("spectate",l,r);break}}}}class OI{constructor(t,i,n){a(this,"guid"),a(this,"dontSave",!0),a(this,"targetUserId"),a(this,"stoppedFollowing"),this.guid=t,this.targetUserId=i,this.stoppedFollowing=n}}class PI{constructor(t,i){a(this,"guid"),a(this,"userId"),this.guid=t.guid,this.userId=i}}class kI{constructor(t,i){a(this,"followers",[]),a(this,"context"),a(this,"spectator"),a(this,"_followerEventMethod"),a(this,"_requestFollowMethod"),a(this,"_joinedRoomMethod"),a(this,"_lastRequestFollowUser"),a(this,"_enforceFollowInterval"),this.context=t,this.spectator=i,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(se.JoinedRoom,this._joinedRoomMethod),this.context.domElement.addEventListener("keydown",t=>{this.spectator.useKeys&&(t.key==="f"?this.onRequestFollowMe():t.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(se.JoinedRoom,this._joinedRoomMethod)}onSpectatedObjectChanged(t,i){if(Fi&&console.log(this.context.connection.connectionId,"onSpectatedObjectChanged",t,i),this.context.connection.connectionId){const n=t?.userId===void 0,o=n?i:t?.userId,r=new OI(this.context.connection.connectionId,o,n);this.context.connection.send("spectator-follower-changed",r)}}onRequestFollowMe(t=!1){if(Fi&&console.log("Request follow",this.context.connection.connectionId),this.context.connection.connectionId){this.spectator.stopSpectating();const i=t?void 0:this.context.connection.connectionId,n=new PI(this.spectator,i);this.context.connection.send("spectator-request-follow",n)}}onUserJoinedRoom(){C("followme")&&this.onRequestFollowMe()}onFollowerEvent(t){const i=t.targetUserId,n=t.guid;if(Fi&&console.log(t),i===this.context.connection.connectionId)if(t.stoppedFollowing){const o=this.followers.indexOf(n);o!==-1&&(this.followers.splice(o,1),this.removeDisconnectedFollowers(),console.log(n,"unfollows you",this.followers.length))}else this.followers.includes(n)||(this.followers.push(n),this.removeDisconnectedFollowers(),console.log(n,"follows you",this.followers.length))}removeDisconnectedFollowers(){for(let t=this.followers.length-1;t>=0;t--){const i=this.followers[t];this.context.connection.userIsInRoom(i)===!1&&this.followers.splice(t,1)}}onRequestFollowEvent(t){if(this._lastRequestFollowUser=t,t.userId===this.context.connection.connectionId)this.spectator.stopSpectating();else if(t.userId===void 0)this.spectator.stopSpectating();else{const i=this.context.players.getPlayerView(t.userId);if(i)this.spectator.target=i;else return Fi&&console.warn("Could not find view",t.userId),this.enforceFollow(),!1}return!0}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):(Fi&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}}class pn{constructor(){a(this,"bb",null),a(this,"bb_pos",0)}__init(t,i){return this.bb_pos=t,this.bb=i,this}static getRootAsSyncedCameraModel(t,i){return(i||new pn).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSyncedCameraModel(t,i){return t.setPosition(t.position()+uv),(i||new pn).__init(t.readInt32(t.position())+t.position(),t)}userId(t){const i=this.bb.__offset(this.bb_pos,4);return i?this.bb.__string(this.bb_pos+i,t):null}guid(t){const i=this.bb.__offset(this.bb_pos,6);return i?this.bb.__string(this.bb_pos+i,t):null}dontSave(){const t=this.bb.__offset(this.bb_pos,8);return t?!!this.bb.readInt8(this.bb_pos+t):!1}pos(t){const i=this.bb.__offset(this.bb_pos,10);return i?(t||new Rr).__init(this.bb_pos+i,this.bb):null}rot(t){const i=this.bb.__offset(this.bb_pos,12);return i?(t||new Rr).__init(this.bb_pos+i,this.bb):null}static startSyncedCameraModel(t){t.startObject(5)}static addUserId(t,i){t.addFieldOffset(0,i,0)}static addGuid(t,i){t.addFieldOffset(1,i,0)}static addDontSave(t,i){t.addFieldInt8(2,+i,0)}static addPos(t,i){t.addFieldStruct(3,i,0)}static addRot(t,i){t.addFieldStruct(4,i,0)}static endSyncedCameraModel(t){return t.endObject()}static finishSyncedCameraModelBuffer(t,i){t.finish(i)}static finishSizePrefixedSyncedCameraModelBuffer(t,i){t.finish(i,void 0,!0)}}var MI=Object.defineProperty,RI=Object.getOwnPropertyDescriptor,TI=(s,t,i,n)=>{for(var o=n>1?void 0:n?RI(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&MI(t,i,o),o};const zp="SCAM";sg(zp,pn.getRootAsSyncedCameraModel);const zi=new vm;class EI{constructor(t,i){a(this,"userId"),a(this,"guid"),this.guid=i,this.userId=t}send(t,i){if(t){zi.clear();const n=zi.createString(this.guid),o=zi.createString(this.userId);pn.startSyncedCameraModel(zi),pn.addGuid(zi,n),pn.addUserId(zi,o);const r=te(t),l=ic(t);pn.addPos(zi,Rr.createVec3(zi,r.x,r.y,r.z)),pn.addRot(zi,Rr.createVec3(zi,l.x,l.y,l.z));const c=pn.endSyncedCameraModel(zi);zi.finish(c,zp),i.sendBinary(zi.asUint8Array())}}}var ly;const cy=(ly=class extends A{constructor(){super(...arguments),a(this,"cameraPrefab",null),a(this,"_lastWorldPosition"),a(this,"_lastWorldQuaternion"),a(this,"_model",null),a(this,"_needsUpdate",!0),a(this,"_lastUpdateTime",0),a(this,"remoteCams",{}),a(this,"userToCamMap",{}),a(this,"_camTimeoutInSeconds",10),a(this,"_receiveCallback",null)}getCameraObject(s){const t=this.userToCamMap[s];return t?this.remoteCams[t].obj: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(zp,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(zp,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){F()&&console.log("Remote cam timeout",n),o!=null&&o.obj&&O.destroy(o.obj),delete this.remoteCams[n],o&&delete this.userToCamMap[o.userId],cy.instances.push(o),this.context.players.removePlayerView(o.userId,yo.Browser);continue}}if(this.context.isInXR)return;const s=this.context.mainCamera;if(s===null){this.enabled=!1;return}if(!this.context.connection.isConnected||this.context.connection.connectionId===null)return;this._model===null&&(this._model=new EI(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));const t=te(s),i=Ce(s);(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(s,this.context.connection),this.context.isInXR||this.context.players.setPlayerView(this.context.connection.connectionId,s,yo.Browser))}onReceivedRemoteCameraInfoBin(s){const t=s.guid();if(!t)return;const i=s.userId();if(!i||!this.context.connection.userIsInRoom(i)||!this.cameraPrefab)return;let n=this.remoteCams[t];if(!n)if("isObject3D"in this.cameraPrefab){const c=new Ds;c.context=this.context;const h=O.instantiate(this.cameraPrefab,c);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,cy.instances.push(n);const d=O.getOrAddComponent(h,Mt);d.connectionId=i,d.avatar=h}else return;const o=n.obj;this.context.players.setPlayerView(i,o,yo.Browser),n.lastUpdate=this.context.time.realtimeSinceStartup,as.markDirty(o);const r=s.pos();r&&lr(o,r.x(),r.y(),r.z());const l=s.rot();l&&sc(o,l.x(),l.y(),l.z())}},a(ly,"instances",[]),ly);let Up=cy;TI([m([I,le])],Up.prototype,"cameraPrefab",2);var AI=Object.defineProperty,II=Object.getOwnPropertyDescriptor,Yo=(s,t,i,n)=>{for(var o=n>1?void 0:n?II(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&AI(t,i,o),o};const hy="view",dy=C("debugsyncedroom");class js extends A{constructor(){super(...arguments),a(this,"roomName",""),a(this,"urlParameterName","room"),a(this,"joinRandomRoom"),a(this,"requireRoomParameter",!1),a(this,"autoRejoin",!0),a(this,"createJoinButton",!0),a(this,"createViewOnlyButton",!1),a(this,"_lastJoinedRoom"),a(this,"_roomPrefix",""),a(this,"_lastPingTime",0),a(this,"_lastRoomTime",-1),a(this,"_userWantsToBeInARoom",!1),a(this,"_roomButton"),a(this,"_roomButtonIconJoin"),a(this,"_roomButtonIconLeave"),a(this,"updateRoomButtonState",()=>{var t,i;this._roomButton&&(this.context.connection.isInRoom?(this._roomButton.title="Leave the networked room",this._roomButton.textContent="Leave Room",(t=this._roomButtonIconJoin)==null||t.remove(),this._roomButton.prepend(this._roomButtonIconLeave)):(this._roomButton.title="Create or join a networked room",this._roomButton.textContent="Join Room",(i=this._roomButtonIconLeave)==null||i.remove(),this._roomButton.prepend(this._roomButtonIconJoin)))}),a(this,"_viewOnlyButton"),a(this,"onCreateViewOnlyButton",()=>{if(!this._viewOnlyButton){const t=document.createElement("button");this._viewOnlyButton=t,t.classList.add("view-only-button"),t.setAttribute("priority","90"),t.onclick=()=>{var i;const n=this.getViewOnlyUrl();n!=null&&n.length?navigator.canShare({url:n})?(i=navigator.share({url:n}))==null||i.catch(o=>{console.warn(o)}):(navigator.clipboard.writeText(n),De("View only URL copied to clipboard")):we("Could not create view only URL")},t.title="Copy the view only URL: A page accessed by the view only URL can not be modified by visiting users.",t.textContent="Share View URL",t.prepend(Ot("visibility"))}this.context.menu.appendChild(this._viewOnlyButton)})}get currentRoomName(){return C(hy)||C(this.urlParameterName)}set roomPrefix(t){this._roomPrefix=t}get roomPrefix(){return this._roomPrefix}awake(){var t;this.joinRandomRoom===void 0&&((t=this.roomName)==null?void 0:t.length)<=0&&(this.joinRandomRoom=!0),dy&&console.log(`SyncedRoom roomName:${this.roomName}, urlParamName:${this.urlParameterName}, joinRandomRoom:${this.joinRandomRoom}`)}onEnable(){const t=C(hy);if(t&&typeof t=="string"&&t.length>0){console.log("Join as viewer"),this.context.connection.joinRoom(t,!0);return}if(this.tryJoinRoom(),this.createJoinButton){const i=this.createRoomButton();this.context.menu.appendChild(i)}this.createViewOnlyButton&&this.onEnableViewOnlyButton()}onDisable(){var t;(t=this._roomButton)==null||t.remove(),this.onDisableViewOnlyButton(),this.roomName&&this.roomName.length>0&&this.context.connection.leaveRoom(this.roomName)}onDestroy(){this.destroyRoomButton()}tryJoinRandomRoom(){this.setRandomRoomUrlParameter(),this.tryJoinRoom()}tryJoinRoom(t=0){var i;t===void 0&&(t=0);let n=!1;if(((i=this.urlParameterName)==null?void 0:i.length)>0){const o=C(this.urlParameterName);if(o&&(typeof o=="string"||typeof o=="number")){n=!0;const r=kv(o.toString());this.roomName=r}else if(this.joinRandomRoom&&(console.log("No room name found in url, generating random one"),this.setRandomRoomUrlParameter(),t<1))return this.tryJoinRoom(t+1)}else this.joinRandomRoom&&(this.roomName===null||this.roomName===void 0||this.roomName.length<=0)&&(this.roomName=this.generateRoomName());return this.requireRoomParameter&&!n?((dy||F())&&console.warn('[SyncedRoom] Missing required room parameter "'+this.urlParameterName+`" in url - will not connect.
1330
1334
  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.
1331
1335
  Please choose one of the following options to fix this:
1332
1336
  A) Set a room name in the SyncedRoom component
1333
1337
  B) Set a room name in the URL parameter "?`+this.urlParameterName+`=my_room"
1334
- C) Set "joinRandomRoom" to true`),!1):(dy&&console.log("Join "+this.roomName),this._userWantsToBeInARoom=!0,this.context.connection.joinRoom(this.roomName),!0))}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()):F()&&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 t=window.location.search,i=new URLSearchParams(t);return i.has(this.urlParameterName)&&i.delete(this.urlParameterName),i.set(hy,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+i.toString()}return null}setRandomRoomUrlParameter(){const t=Ql(),i=this.generateRoomName();C(this.urlParameterName)?t.set(this.urlParameterName,i):t.append(this.urlParameterName,i),Om(i,t)}generateRoomName(){let t="";for(let i=0;i<6;i++)t+=Math.floor(Math.random()*10).toFixed(0);return t}createRoomButton(){if(this._roomButton)return this._roomButton;const t=document.createElement("button");return this._roomButton=t,t.classList.add("create-room-button"),t.setAttribute("priority","90"),t.onclick=()=>{if(this.context.connection.isInRoom)this.urlParameterName&&Yl(this.urlParameterName,null),this.context.connection.leaveRoom(),this._userWantsToBeInARoom=!1;else{if(this.urlParameterName){const i=C(this.urlParameterName);(!i||i===!0)&&(this._lastJoinedRoom?Yl(this.urlParameterName,this._lastJoinedRoom):this.setRandomRoomUrlParameter())}this.tryJoinRoom()}},this._roomButtonIconJoin=Ot("group"),this._roomButtonIconLeave=Ot("group_off"),this.updateRoomButtonState(),this.context.connection.beginListen(se.JoinedRoom,this.updateRoomButtonState),this.context.connection.beginListen(se.LeftRoom,this.updateRoomButtonState),t}destroyRoomButton(){this.context.connection.stopListen(se.JoinedRoom,this.updateRoomButtonState),this.context.connection.stopListen(se.LeftRoom,this.updateRoomButtonState)}onEnableViewOnlyButton(){this.context.connection.isConnected?this.onCreateViewOnlyButton():(this.context.connection.stopListen(se.JoinedRoom,this.onCreateViewOnlyButton),this.context.connection.beginListen(se.JoinedRoom,this.onCreateViewOnlyButton))}onDisableViewOnlyButton(){var t;this.context.connection.stopListen(se.JoinedRoom,this.onCreateViewOnlyButton),(t=this._viewOnlyButton)==null||t.remove()}}Yo([m()],js.prototype,"roomName",2),Yo([m()],js.prototype,"urlParameterName",2),Yo([m()],js.prototype,"joinRandomRoom",2),Yo([m()],js.prototype,"requireRoomParameter",2),Yo([m()],js.prototype,"autoRejoin",2),Yo([m()],js.prototype,"createJoinButton",2),Yo([m()],js.prototype,"createViewOnlyButton",2),Yo([m()],js.prototype,"roomPrefix",1);function II(){const s=C("testwindowcount")||0;s&&s>0&&jI(s)}function jI(s){if(C("testwindow"))return null;const t=new URL(window.location.href);Cm(t.searchParams,DM,1),Cm(t.searchParams,"testwindow",1);const i=t.toString(),n=[];window.onbeforeunload=()=>{for(const h of n)h.close()};const o=.05,r=128;let l=0,c=0;for(let h=0;h<s;h++){l*r+r*.01>=window.innerWidth&&(c+=1,l=0);const d=l*(r*(1+o))+window.screenLeft,u=c*(r*(1+o))+window.screenTop+90+60*c;l+=1;const p=window.open(i,"test window "+h,`popup=yes width=${r} height=${r} top=${u} left=${d}`);if(!p){console.warn("Failed to open window");continue}n.push(p),p.onload=()=>{p.onbeforeunload=()=>{for(let g=0;g<n.length;g++){const y=n[g];y!==p&&y.close()}n.length=0}}}return n}class uy extends A{awake(){II()}}class py extends A{constructor(){super(...arguments),a(this,"transformsPerFrame",10),a(this,"interval",0),a(this,"useFlatbuffers",!0),a(this,"builder",null),a(this,"models",null)}awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinary(zc,t=>{});else{this.models=[];for(let t=0;t<this.transformsPerFrame;t++)this.models.push(new I1(this.context.connection.connectionId+"_simulatedTransform_"+t,this))}}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 vm(1024));const t=this.builder;for(let i=0;i<this.transformsPerFrame;i++){t.clear();const n=Mw(this.context.connection.connectionId,this);this.context.connection.sendBinary(n)}}else if(this.models)for(let t=0;t<this.models.length;t++){const i=this.models[t];i.dontSave=!0,i.update(this,null),this.context.connection.send("TestSimulateUserData-"+t,i)}}}}class I1{constructor(t,i){a(this,"guid"),a(this,"fast",!1),a(this,"position"),a(this,"rotation"),a(this,"velocity"),a(this,"dontSave"),this.guid=t,this.position={x:0,y:0,z:0},this.rotation={x:0,y:0,z:0,w:0},this.update(i,null)}isValid(){return this.fast!==void 0||this.position!==void 0||this.rotation!==void 0||this.velocity!==void 0}update(t,i){const n=t.worldPosition;this.position.x=n.x,this.position.y=n.y,this.position.z=n.z;const o=t.worldQuaternion;if(this.rotation.x=o.x,this.rotation.y=o.y,this.rotation.z=o.z,this.rotation.w=o.w,this.fast=!1,i){const r=i.getVelocity();this.velocity===void 0&&(this.velocity={x:0,y:0,z:0}),this.velocity.x=r.x,this.velocity.y=r.y,this.velocity.z=r.z}}}a(I1,"temp",new x);var LI=Object.defineProperty,DI=Object.getOwnPropertyDescriptor,Np=(s,t,i,n)=>{for(var o=n>1?void 0:n?DI(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&LI(t,i,o),o};const BI=C("debugsignals");class Wp{constructor(){a(this,"guid")}}Np([m()],Wp.prototype,"guid",2);class Bh{constructor(){a(this,"signal"),a(this,"reaction")}}Np([m(Wp)],Bh.prototype,"signal",2),Np([m(Se)],Bh.prototype,"reaction",2);var my;const Xn=(my=class extends A{constructor(){super(...arguments),a(this,"events")}static invoke(s){if(Xn.receivers[s]){const t=Xn.receivers[s];if(!t)return;for(const i of t)i.invoke(s)}}awake(){BI&&console.log("SignalReceiver awake",this)}onEnable(){if(this.events)for(const s of this.events)Xn.receivers[s.signal.guid]||(Xn.receivers[s.signal.guid]=[]),Xn.receivers[s.signal.guid].push(this)}onDisable(){if(this.events){for(const s of this.events)if(Xn.receivers[s.signal.guid]){const t=Xn.receivers[s.signal.guid].indexOf(this);t>=0&&Xn.receivers[s.signal.guid].splice(t,1)}}}invoke(s){if(!this.events||!Array.isArray(this.events))return;const t=typeof s=="object"?s.guid:s;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)}}},a(my,"receivers",{}),my);let Il=Xn;Np([m(Bh)],Il.prototype,"events",2);var Ui=(s=>(s.Activation="ActivationTrack",s.Animation="AnimationTrack",s.Audio="AudioTrack",s.Control="ControlTrack",s.Marker="MarkerTrack",s.Signal="SignalTrack",s))(Ui||{}),dn=(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))(dn||{}),gy=(s=>(s.Signal="SignalEmitter",s))(gy||{});const un=C("debugtimeline");class Fh{constructor(){a(this,"director"),a(this,"track")}get muted(){return this.track.muted}set muted(t){var i;t!==this.track.muted&&(this.track.muted=t,(i=this.onMuteChanged)==null||i.call(this))}*forEachClip(t=!1){var i;if((i=this.track)!=null&&i.clips)if(t)for(let n=this.track.clips.length-1;n>=0;n--)yield this.track.clips[n];else for(const n of this.track.clips)yield n}getClipTime(t,i){return i.clipIn+(t-i.start)*i.timeScale}getClipTimeNormalized(t,i){return(t-i.start)/i.duration}evaluateWeight(t,i,n,o=!0){if(i<0||i>=n.length)return 0;const r=n[i];if(o||t>=r.start&&t<=r.end){let l=1;const c=!1;if(r.easeInDuration>0){const h=Math.min((t-r.start)/r.easeInDuration,1);l*=h}if(r.easeOutDuration>0&&!c){const h=Math.min((r.end-t)/r.easeOutDuration,1);l*=h}return l}return 0}}class FI{constructor(t){a(this,"clip"),a(this,"rootPositionOffset"),a(this,"rootQuaternionOffset"),a(this,"rootStartPosition"),a(this,"rootEndPosition"),a(this,"rootStartQuaternion"),a(this,"rootEndQuaternion");const i=t.getClip();this.clip=i;const n=t.getRoot(),o=n.name+".position",r=n.name+".quaternion";un&&console.log(i.name,i.tracks,o);for(const l of i.tracks)if(!(l.times.length<=0)){if(l.name.endsWith(o))this.rootStartPosition=new x().fromArray(l.values,0),this.rootEndPosition=new x().fromArray(l.values,l.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),un&&console.log(this.rootPositionOffset);else if(l.name.endsWith(r)&&(this.rootStartQuaternion=new V().fromArray(l.values,0),this.rootEndQuaternion=new V().fromArray(l.values,l.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),un)){const c=new Bt().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",c)}}}get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}}class Vp extends Fh{constructor(){super(...arguments),a(this,"models",[]),a(this,"trackOffset"),a(this,"target"),a(this,"mixer"),a(this,"clips",[]),a(this,"actions",[]),a(this,"weight",1),a(this,"_actionOffsets",[]),a(this,"_didBind",!1),a(this,"_animator",null),a(this,"_useclipOffsets",!0),a(this,"_totalOffsetPosition",new x),a(this,"_totalOffsetRotation",new V),a(this,"_totalOffsetPosition2",new x),a(this,"_totalOffsetRotation2",new V),a(this,"_summedPos",new x),a(this,"_tempPos",new x),a(this,"_summedRot",new V),a(this,"_tempRot",new V),a(this,"_clipRotQuat",new V)}onDisable(){var t;(t=this.mixer)==null||t.stopAllAction()}onDestroy(){this.director.context.animations.unregisterAnimationMixer(this.mixer)}onStateChanged(){this._animator&&_w(this._animator.gameObject,this,this.director.isPlaying)}createHooks(t,i){var n,o;if(((n=i.tracks)==null?void 0:n.length)<=0){console.warn("No tracks in AnimationClip",i);return}const r=i.tracks[0].name.split("."),l=r[r.length-2],c=l+".position",h=l+".quaternion";let d=!1,u=!1;for(const p of i.tracks)p.name.endsWith(c)?(d=!0,this.createPositionInterpolant(i,t,p)):p.name.endsWith(h)&&(u=!0,this.createRotationInterpolant(i,t,p));if(!d||!u){const p=(o=this.mixer)==null?void 0:o.getRoot(),g=i.tracks[0],y=g.name.lastIndexOf("."),f=g.name.substring(0,y),v=f.substring(f.lastIndexOf(".")+1),b=p.getObjectByName(v);if(b)if(d){if(!u){const w=i.tracks[0].name.substring(0,y)+".quaternion";un&&console.warn("Create quaternion track",v,b);const _=b.quaternion,S=new kC(w,[0,i.duration],[_.x,_.y,_.z,_.w,_.x,_.y,_.z,_.w]);i.tracks.push(S),this.createRotationInterpolant(i,t,S)}}else{const w=f+".position";un&&console.warn("Create position track",v,b);const _=b.position,S=new PC(w,[0,i.duration],[_.x,_.y,_.z,_.x,_.y,_.z]);i.tracks.push(S),this.createPositionInterpolant(i,t,S)}}}bind(){if(!this._didBind){this._didBind=!0,un&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(const t of this.actions){const i=new FI(t);this._actionOffsets.push(i)}this.target&&(this._animator=O.getComponent(this.target,Pt)??null,this._animator&&_w(this._animator.gameObject,this,!0));for(const t of this.models){const i=t.asset,n=i.position,o=i.rotation;n&&n.x!==void 0&&(n.isVector3||(i.position=new x(n.x,n.y,n.z)),o.isQuaternion||(i.rotation=new V(o.x,o.y,o.z,o.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){const t=this.trackOffset.position;t&&(t.isVector3||(this.trackOffset.position=new x(t.x,t.y,t.z)));const i=this.trackOffset.rotation;i&&(i.isQuaternion||(this.trackOffset.rotation=new V(i.x,i.y,i.z,i.w)))}}evaluate(t){var i,n,o,r,l,c,h;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 d=0,u=0,p=!1,g=!1,y=0;for(let f=0;f<this.clips.length;f++){const v=this.models[f],b=this.actions[f],w=v.asset;b.weight=0;const _=t>=v.start&&t<=v.end,S=v.preExtrapolationMode,R=v.postExtrapolationMode,M=f<this.clips.length-1?this.models[f+1]:null;let T=_,j=!1;if(!T&&!p&&v.end<t&&R!==dn.None?(!M||M.start>t)&&(T=!0,p=!0):f==0&&!T&&!g&&v.start>t&&S!==dn.None&&(!M||M.start<t)&&(T=!0,j=!0,g=!0),T){let L=this.weight;L*=this.evaluateWeight(t,f,this.models,T),L*=this.director.weight;let U=_;if(j)switch(S){case dn.Hold:break;case dn.Loop:t+=v.start,U=!0;break;default:t+=v.start,U=!0;break}let B=this.getClipTime(t,v),Q=0;const $=w.duration;if(j&&S===dn.Hold&&(B=0),U){if(w.loop)for(Q+=Math.floor(B/($+1e-6));B>$;)B-=$}else if(!_&&p)switch(R){case dn.Hold:B=this.getClipTime(v.end,v);break;case dn.Loop:B%=$;break;case dn.PingPong:const z=Math.floor(B/$)%2!==0;B%=$,z&&(B=$-B);break}v.reversed===!0?b.time=b.getClip().duration-B:b.time=B,b.timeScale=0;const E=Math.max(0,L);if(b.weight=E,y+=E,b.clampWhenFinished=!1,b.isRunning()||b.play(),this._useclipOffsets){const z=d==0?this._totalOffsetPosition:this._totalOffsetPosition2,H=d==0?this._totalOffsetRotation:this._totalOffsetRotation2;d<1&&(u=1-L),d+=1;const ie=this._summedPos.set(0,0,0),oe=this._tempPos.set(0,0,0),de=this._summedRot.identity(),pe=this._tempRot.identity(),Xe=w.rotation;Xe&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp(Xe,L));const Qe=this._actionOffsets[f];if(Qe.hasOffsets)for(let hs=0;hs<Q;hs++)Qe.rootPositionOffset?oe.copy(Qe.rootPositionOffset):oe.set(0,0,0),oe.applyQuaternion(de),this._clipRotQuat&&oe.applyQuaternion(this._clipRotQuat),Qe.rootQuaternionOffset&&(pe.copy(Qe.rootQuaternionOffset),de.multiply(pe)),ie.add(oe);this._clipRotQuat&&H.multiply(this._clipRotQuat),H.multiply(de),w.position&&ie.add(w.position),z.add(ie)}}}if(this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,u),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,u)),this.__mixerError===void 0&&(un||F())&&(n=(i=this._animator)==null?void 0:i.runtimeAnimatorController)!=null&&n.mixer&&this.mixer!==((r=(o=this._animator)==null?void 0:o.runtimeAnimatorController)==null?void 0:r.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)),(l=this._animator)!=null&&l.runtimeAnimatorController){const f=Math.max(0,1-y);(h=(c=this._animator)==null?void 0:c.runtimeAnimatorController)==null||h.update(f)}else this.mixer.update(t)}createRotationInterpolant(t,i,n){var o;const r=n.createInterpolant.bind(n),l=new V;this.ensureTrackOffsets();const c=(o=this.trackOffset)==null?void 0:o.rotation;n.createInterpolant=()=>{const h=r(),d=h.evaluate.bind(h);return h.evaluate=u=>{var p;const g=d(u);if(l.set(g[0],g[1],g[2],g[3]),l.premultiply(this._totalOffsetRotation),c&&l.premultiply(c),this.director.animationCallbackReceivers)for(const y of this.director.animationCallbackReceivers)(p=y?.onTimelineRotation)==null||p.call(y,this.director,this.target,u,l);return g[0]=l.x,g[1]=l.y,g[2]=l.z,g[3]=l.w,g},h}}createPositionInterpolant(t,i,n){var o,r;const l=n.createInterpolant.bind(n),c=new x;this.ensureTrackOffsets();const h=(o=this.trackOffset)==null?void 0:o.rotation,d=(r=this.trackOffset)==null?void 0:r.position;let u;n.createInterpolant=()=>{const p=l(),g=p.evaluate.bind(p);return p.evaluate=y=>{var f,v,b;const w=g(y);if(c.set(w[0],w[1],w[2]),i.removeStartOffset&&(u===void 0?(u=null,u=(v=(f=this._actionOffsets.find(_=>_.clip===t))==null?void 0:f.rootStartPosition)==null?void 0:v.clone()):u!=null&&u.isVector3&&c.sub(u)),c.applyQuaternion(this._totalOffsetRotation),c.add(this._totalOffsetPosition),h&&c.applyQuaternion(h),d&&(c.x-=d.x,c.y+=d.y,c.z+=d.z),this.director.animationCallbackReceivers)for(const _ of this.director.animationCallbackReceivers)(b=_?.onTimelinePosition)==null||b.call(_,this.director,this.target,y,c);return w[0]=c.x,w[1]=c.y,w[2]=c.z,w},p}}}const zI=C("mutetimeline"),zh=class extends Fh{constructor(){super(...arguments),a(this,"models",[]),a(this,"listener"),a(this,"audio",[]),a(this,"audioContextTimeOffset",[]),a(this,"lastTime",0),a(this,"audioSource"),a(this,"_audioLoader",null),a(this,"_playableDirectorResumed",!1)}getAudioFilePath(s){const t=this.director.sourceId;return lo(t,s)}onAllowAudioChanged(s){for(let t=0;t<this.models.length;t++){const i=this.models[t];this.audio[t].setVolume(s?i.asset.volume:0)}}addModel(s){const t=new MC(this.listener);this.audio.push(t);const i=s;i._didTriggerPlay=!1,this.models.push(i)}onDisable(){for(const s of this.audio)s.isPlaying&&s.stop();for(const s of this.models)s._didTriggerPlay=!1}onDestroy(){for(const s of this.audio)s.source&&s?.disconnect();this.audio.length=0}onMuteChanged(){if(this.muted)for(let s=0;s<this.audio.length;s++){const t=this.audio[s];t!=null&&t.isPlaying&&t.stop()}}stop(){for(let s=0;s<this.audio.length;s++){const t=this.audio[s];t!=null&&t.isPlaying&&t.stop()}for(const s of this.models)s._didTriggerPlay=!1}onPauseChanged(){for(let s=0;s<this.audio.length;s++){const t=this.audio[s];t!=null&&t.isPlaying&&t.stop()}this._playableDirectorResumed=this.director.isPlaying}evaluate(s){if(zI||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],l=this.audio[o],c=r.asset;if((!l||!l.buffer)&&this.isInTimeRange(r,s-1,s+1)&&this.handleAudioLoading(r,l),Ne.userInteractionRegistered!==!1&&!(l===null||!l.buffer))if(l.playbackRate=this.director.context.time.timeScale*this.director.speed,l.loop=c.loop,s>=r.start&&s<=r.end&&s<this.director.duration){if(!l.isPlaying||!this.director.isPlaying)(i||!r._didTriggerPlay&&this.lastTime<s)&&(r.duration*r.timeScale>.3?l.offset=r.clipIn+(s-r.start)*r.timeScale:l.offset=0,un&&console.log("Timeline Audio ("+this.track.name+") play with offset "+l.offset+" - "+r.asset.clip),l.play(n),r._didTriggerPlay=!0);else{const d=r.clipIn+(s-r.start)*r.timeScale,u=l.context.currentTime-l._startedAt+l.offset;Math.abs(d-u)>.3&&(l.offset=d,l.stop(),l.play(n))}let h=c.volume;if(this.track.volume!==void 0&&(h*=this.track.volume),t&&(h=0),r.easeInDuration>0){const d=Math.min((s-r.start)/r.easeInDuration,1);h*=d}if(r.easeOutDuration>0){const d=Math.min((r.end-s)/r.easeOutDuration,1);h*=d}l.setVolume(h*this.director.weight)}else r._didTriggerPlay=!1,this.director.isPlaying&&l.isPlaying&&l.stop()}this.lastTime=s}loadAudio(s,t=0,i=0){let n=null;const o=s-i,r=s+t;for(const l of this.models)if(this.isInTimeRange(l,o,r)){const c=this.audio[this.models.indexOf(l)],h=this.handleAudioLoading(l,c);h!==null&&(n===null&&(n=[]),n.push(h))}return n!==null?Promise.all(n):null}isInTimeRange(s,t,i){return t<=s.start&&i>=s.end||t>=s.start&&t<=s.end||i>=s.start&&i<=s.end}static dispose(){zh._audioBuffers.clear()}handleAudioLoading(s,t){this._audioLoader||(this._audioLoader=new cm);const i=this.getAudioFilePath(s.asset.clip);if(zh._audioBuffers.get(i)){const o=zh._audioBuffers.get(i);return o.then(r=>{r&&t.setBuffer(r)}),o}un&&console.warn("LOAD audio track",i,this.director.sourceId);const n=new Promise((o,r)=>{this._audioLoader.load(i,l=>{t.setBuffer(l),o(l)},void 0,l=>{console.error("Error loading audio",l),o(null)})});return zh._audioBuffers.set(i,n),n}};let Uh=zh;a(Uh,"_audioBuffers",new Map);class Nh extends Fh{constructor(){super(...arguments),a(this,"models",[]),a(this,"didTrigger",[]),a(this,"receivers",[])}evaluate(t){var i;if(this.track.muted)return;const n=this.director.context.time.deltaTime*1.5;for(let o=0;o<this.models.length;o++){const r=this.models[o],l=this.didTrigger[o],c=r.time-t;let h=!1;if(r.retroActive)h=c<=1e-6;else{const d=Math.abs(c);(d===0||d>=1e-5&&d<n)&&(h=!0)}if(h){if(!l)if(un&&console.log("Trigger signal",t,r.time,r),this.didTrigger[o]=!0,((i=this.receivers)==null?void 0:i.length)<=0)Il.invoke(r.asset);else for(const d of this.receivers)d&&d.invoke(r.asset)}else r.emitOnce||(this.didTrigger[o]=!1)}}}class Hp extends Fh{constructor(){super(...arguments),a(this,"models",[]),a(this,"timelines",[]),a(this,"_previousActiveModel",null)}resolveSourceObjects(t){for(let i=this.models.length-1;i>=0;i--){const n=this.models[i].asset;if(!n.sourceObject||typeof n.sourceObject!="object"){console.log("no source object, removing model",i,n),this.models.splice(i,1);continue}else{const o=O.getComponent(n.sourceObject,Zo);this.timelines.push(o),o&&n.updateDirector&&(o.playOnAwake=!1)}}}evaluate(t){var i;this._previousActiveModel=null;for(let n=0;n<this.models.length;n++){const o=this.models[n],r=o.asset;if(t>=o.start&&t<=o.end){this._previousActiveModel=o;const l=this.getClipTime(t,o);if(r.controlActivation){const c=r.sourceObject;c.visible=!0}if(r.updateDirector){const c=this.timelines[n];c&&(c.isPlaying&&c.pause(),c.time=l,c.evaluate())}}else{const l=(i=this._previousActiveModel)==null?void 0:i.asset;if(r.controlActivation){const c=r.sourceObject;l?.sourceObject!==c&&(c.visible=!1)}}}}}var UI=Object.defineProperty,NI=Object.getOwnPropertyDescriptor,j1=(s,t,i,n)=>{for(var o=n>1?void 0:n?NI(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&UI(t,i,o),o};const Qn=C("debugtimeline");var fy;const yy=(fy=class extends A{constructor(){super(...arguments),a(this,"playableAsset"),a(this,"playOnAwake"),a(this,"extrapolationMode",1),a(this,"waitForAudio",!0),a(this,"_visibilityChangeEvt"),a(this,"_clonedPlayableAsset",!1),a(this,"_speed",1),a(this,"_guidsMap"),a(this,"_isPlaying",!1),a(this,"_internalUpdateRoutine"),a(this,"_isPaused",!1),a(this,"_isStopping",!1),a(this,"_time",0),a(this,"_duration",0),a(this,"_weight",1),a(this,"_animationTracks",[]),a(this,"_audioTracks",[]),a(this,"_signalTracks",[]),a(this,"_controlTracks",[]),a(this,"_customTracks",[]),a(this,"_allTracks",[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks]),a(this,"animationCallbackReceivers",[])}static registerCreateTrack(s,t){this.createTrackFunctions[s]=t}get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(s){typeof s=="number"&&!Number.isNaN(s)?this._time=s:(Qn||Gt())&&console.error("INVALID TIMELINE.TIME VALUE",s,this.name)}get duration(){return this._duration}set duration(s){this._duration=s}get weight(){return this._weight}set weight(s){this._weight=s}get speed(){return this._speed}set speed(s){this._speed=s}awake(){var s,t,i,n,o;Qn&&console.log(this,(s=this.playableAsset)==null?void 0:s.tracks),this.rebuildGraph(),!this.isValid()&&(Qn||F())&&(Qn?console.warn("PlayableDirector is not valid","Asset?",this.playableAsset,"Tracks:",(t=this.playableAsset)==null?void 0:t.tracks,"IsArray?",Array.isArray((i=this.playableAsset)==null?void 0:i.tracks),this):(o=(n=this.playableAsset)==null?void 0:n.tracks)!=null&&o.length?console.warn("PlayableDirector is not valid"):console.warn("PlayableDirector has no tracks"))}onEnable(){var s,t,i;for(const n of this._audioTracks)(s=n.onEnable)==null||s.call(n);for(const n of this._customTracks)(t=n.onEnable)==null||t.call(n);for(const n of this._animationTracks)(i=n.onEnable)==null||i.call(n);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(){var s,t,i;this.stop();for(const n of this._audioTracks)(s=n.onDisable)==null||s.call(n);for(const n of this._customTracks)(t=n.onDisable)==null||t.call(n);for(const n of this._animationTracks)(i=n.onDisable)==null||i.call(n);this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){var s;for(const t of this._allTracks)for(const i of t)(s=i.onDestroy)==null||s.call(i)}rebuildGraph(){this.isValid()&&(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}async play(){if(!this.isValid())return;const s=this._isPaused==!0;if(this._isPaused=!1,!this._isPlaying){if(this._isPlaying=!0,s&&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&&!Ne.userInteractionRegistered&&this.waitForAudio;)await fs(200)}this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate(),Me.LateUpdate)}}pause(){this.isValid()&&(this._isPlaying=!1,!this._isPaused&&(this._isPaused=!0,this.internalEvaluate(),this.invokePauseChangedMethodsOnTracks(),this.invokeStateChangedMethodsOnTracks()))}stop(){this._isStopping=!0;for(const i of this._audioTracks)i.stop();const s=this._isPaused==!0,t=this._isPlaying;this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.internalEvaluate(),s&&this.invokePauseChangedMethodsOnTracks()),this._isPlaying=!1,this._isPaused=!1,s&&!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 s of this._allTracks)for(const t of s)yield t}get animationTracks(){return this._animationTracks}get audioTracks(){return this._audioTracks}resolveGuids(s){this._guidsMap=s}invokePauseChangedMethodsOnTracks(){var s;for(const t of this.forEachTrack())(s=t.onPauseChanged)==null||s.call(t)}invokeStateChangedMethodsOnTracks(){var s;for(const t of this.forEachTrack())(s=t.onStateChanged)==null||s.call(t,this._isPlaying)}*internalUpdate(){for(;this._isPlaying&&this.activeAndEnabled;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime*this.speed,this.internalEvaluate()),yield}internalEvaluate(s=!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 Ui.Activation:if(!s&&!this._isPlaying)continue;for(let o=0;o<n.outputs.length;o++){const r=n.outputs[o];if(typeof r=="object"){let l=!1;if(n.clips)for(const h of n.clips)h.start<=i&&i<=h.end&&(l=!0);const c=r;c.visible!==void 0&&c.visible!==l&&(c.visible=l,Qn&&console.warn(this.name,"set ActivationTrack-"+o,c.name,l,i))}}break}if(!this._isStopping)for(const n of this._animationTracks)n.evaluate(i);for(const n of this._audioTracks)n.evaluate(i);for(const n of this._signalTracks)n.evaluate(i);for(const n of this._controlTracks)n.evaluate(i);for(const n of this._customTracks)n.evaluate(i)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=Zl(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;const s=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=O.findByGuid(n,s);o===null||typeof o!="object"?(t.outputs.splice(i,1),console.warn("Failed to resolve binding",n,t.name,t.type)):(Qn&&console.log("Resolved binding",n,"to",o),t.outputs[i]=o)}else if(n===null){if(t.outputs.splice(i,1),yy.createTrackFunctions[t.type])continue;t.type!==Ui.Audio&&t.type!==Ui.Control&&t.type!==Ui.Marker&&t.type!==Ui.Signal&&console.warn("Missing binding",n,t.name,t.type,this.name,this.playableAsset.name)}}if(t.type===Ui.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=O.findByGuid(o,s);r===null||typeof r!="object"?console.warn("Failed to resolve sourceObject binding",o,t.name,n):(Qn&&console.log("Resolved binding",o,"to",r),n.asset.sourceObject=r)}}}}findRoot(s){return s.parent?this.findRoot(s.parent):s}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const s of this.playableAsset.tracks)if(s.muted!==!0){if(s.clips)for(const t of s.clips)t.end>this._duration&&(this._duration=t.end);if(s.markers)for(const t of s.markers)t.time>this._duration&&(this._duration=t.time+.001)}}}setupAndCreateTrackHandlers(){var s,t,i;if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let n=O.findObjectOfType(Tn,this.context);for(const o of this.playableAsset.tracks){const r=o.type,l=yy.createTrackFunctions[r];if(l!=null){const c=l(this,o);if(typeof c.evaluate=="function"){c.director=this,c.track=o,this._customTracks.push(c);continue}}if(o.type===Ui.Animation){if(!o.clips||o.clips.length<=0){Qn&&console.warn("Animation track has no clips",o);continue}for(let c=o.outputs.length-1;c>=0;c--){let h=o.outputs[c];if(h instanceof I){const u=O.getOrAddComponent(h,Pt);u&&(h=u)}const d=(s=h?.gameObject)==null?void 0:s.animations;if(d){const u=new Vp;u.trackOffset=o.trackOffset,u.director=this,u.track=o;for(let p=0;p<o.clips.length;p++){const g=o.clips[p],y=g.asset;if(!y){console.error(`Timeline ${this.name}: clip #${p} on track "${o.name}" has no animation data`);continue}const f=y.clip;let v=f;if((typeof v=="string"||typeof v=="number")&&(v=d.find(w=>w.name===f)),Qn&&console.log(y,f,"\u2192",v),!v){console.warn("Could not find animationClip for model",g,o.name,this.name,(t=this.playableAsset)==null?void 0:t.name,d,h);continue}h instanceof Pt&&h.runtimeAnimatorController&&(h.__internalDidAwakeAndStart||h.initializeRuntimeAnimatorController(),h.runtimeAnimatorController.mixer||h.runtimeAnimatorController.bind(h),u.mixer=h.runtimeAnimatorController.mixer),u.mixer||(u.mixer=new am(h.gameObject),this.context.animations.registerAnimationMixer(u.mixer)),u.clips.push(v),u.mixer.uncacheAction(v),u.createHooks(g.asset,v);const b=u.mixer.clipAction(v);u.actions.push(b),u.models.push(g)}this._animationTracks.push(u)}}}else if(o.type===Ui.Audio){if(!o.clips||o.clips.length<=0)continue;const c=new Uh;c.director=this,c.track=o,c.audioSource=o.outputs.find(h=>h instanceof Ne),this._audioTracks.push(c),n||(n=(i=this.context.mainCameraComponent)==null?void 0:i.gameObject.addComponent(Tn)),c.listener=n.listener;for(let h=0;h<o.clips.length;h++){const d=o.clips[h];c.addModel(d)}}else if(o.type===Ui.Marker){const c=new Nh;if(c.director=this,c.track=o,o.markers)for(const h of o.markers)switch(h.type){case gy.Signal:c.models.push(h),c.didTrigger.push(!1);break}if(c!==null&&c.models.length>0){const h=O.getComponent(this.gameObject,Il);h&&(c.receivers.push(h),this._signalTracks.push(c))}}else if(o.type===Ui.Signal){const c=new Nh;if(c.director=this,c.track=o,o.markers)for(const h of o.markers)c.models.push(h),c.didTrigger.push(!1);for(const h of o.outputs)c.receivers.push(h);this._signalTracks.push(c)}else if(o.type===Ui.Control){const c=new Hp;if(c.director=this,c.track=o,o.clips)for(const h of o.clips)c.models.push(h);c.resolveSourceObjects(this.context),this._controlTracks.push(c)}}}setAudioTracksAllowPlaying(s){for(const t of this._audioTracks)t.onAllowAudioChanged(s)}registerAnimationCallback(s){this.animationCallbackReceivers.push(s)}unregisterAnimationCallback(s){const t=this.animationCallbackReceivers.indexOf(s);t!==-1&&this.animationCallbackReceivers.splice(t,1)}},a(fy,"createTrackFunctions",{}),fy);let Zo=yy;j1([m()],Zo.prototype,"playOnAwake",2),j1([m()],Zo.prototype,"extrapolationMode",2);var WI=Object.defineProperty,VI=Object.getOwnPropertyDescriptor,$p=(s,t,i,n)=>{for(var o=n>1?void 0:n?VI(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&WI(t,i,o),o};class ta extends A{constructor(){super(...arguments),a(this,"isGizmo",!1),a(this,"translationSnap",1),a(this,"rotationSnapAngle",15),a(this,"scaleSnap",.25),a(this,"_control"),a(this,"orbit"),a(this,"onControlChangedEvent",t=>{const i=this.orbit;if(i&&(i.enabled=!t.value),t.value){const n=O.getComponentInParent(this.gameObject,qs);n&&n.requestOwnership()}}),a(this,"windowKeyDownListener",t=>{if(this.enabled&&this._control)switch(t.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}}),a(this,"windowKeyUpListener",t=>{if(this.enabled)switch(t.keyCode){case 16:this.disableSnapping();break}})}get control(){return this._control}onEnable(){var t;if(!(this.isGizmo&&!xc)&&this.context.mainCamera&&(this._control||(this._control=new YC(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(i=>{const n=i;if(n.layers.set(2),n){const o=n.material;o&&(o.opacity=.3)}}),this.orbit=O.getComponentInParent(this.context.mainCamera,be)??void 0),this._control)){const i=this._control.getHelper();this.context.scene.add(i),this._control.attach(this.gameObject),(t=this._control)==null||t.addEventListener("dragging-changed",this.onControlChangedEvent),window.addEventListener("keydown",this.windowKeyDownListener),window.addEventListener("keyup",this.windowKeyUpListener)}}onDisable(){var t,i,n;(i=(t=this._control)==null?void 0:t.getHelper())==null||i.removeFromParent(),(n=this._control)==null||n.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(mn.degToRad(this.rotationSnapAngle)),this._control.setScaleSnap(this.scaleSnap))}disableSnapping(){this._control&&(this._control.setTranslationSnap(null),this._control.setRotationSnap(null),this._control.setScaleSnap(null))}}$p([m()],ta.prototype,"isGizmo",2),$p([m()],ta.prototype,"translationSnap",2),$p([m()],ta.prototype,"rotationSnapAngle",2),$p([m()],ta.prototype,"scaleSnap",2);var HI=Object.defineProperty,$I=Object.getOwnPropertyDescriptor,qp=(s,t,i,n)=>{for(var o=n>1?void 0:n?$I(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&HI(t,i,o),o};class vy{constructor(){a(this,"texture",null),a(this,"rect")}}qp([m(Le)],vy.prototype,"texture",2);let jl=class extends fh{constructor(){super(...arguments),a(this,"_sprite"),a(this,"pixelsPerUnitMultiplier",1)}set image(s){this.sprite||(this.sprite=new vy),this.sprite.texture=s,this.onAfterCreated()}get image(){return this.sprite?this.sprite.texture:null}get sprite(){return this._sprite}set sprite(s){this._sprite!==s&&(this._sprite=s,this.onAfterCreated())}isBuiltinSprite(){var s,t,i,n,o,r,l;const c=this.sprite;switch((s=c?.texture)==null?void 0:s.name){case"InputFieldBackground":case"UISprite":case"Background":case"Knob":return!0}return!((i=(t=c?.texture)==null?void 0:t.name)!=null&&i.length)&&((o=(n=c?.texture)==null?void 0:n.image)==null?void 0:o.width)===32&&((l=(r=c?.texture)==null?void 0:r.image)==null?void 0:l.height)===32}onBeforeCreate(s){var t,i;super.onBeforeCreate(s),this.isBuiltinSprite()&&(s.borderRadius=5/this.pixelsPerUnitMultiplier,((i=(t=this.sprite)==null?void 0:t.texture)==null?void 0:i.name)==="Knob"&&(s.borderRadius=999))}onAfterCreated(){var s;this.__didAwake&&(super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture((s=this.sprite)==null?void 0:s.texture))}};qp([m(vy)],jl.prototype,"sprite",1),qp([m()],jl.prototype,"pixelsPerUnitMultiplier",2);class Gp extends fh{constructor(){super(...arguments),a(this,"_mainTexture")}get mainTexture(){return this._mainTexture}set mainTexture(t){this._mainTexture!==t&&(this._mainTexture=t,this.onAfterCreated())}onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),this.setTexture(this.mainTexture))}}qp([m(Le)],Gp.prototype,"mainTexture",1);var qI=Object.defineProperty,GI=Object.getOwnPropertyDescriptor,Ni=(s,t,i,n)=>{for(var o=n>1?void 0:n?GI(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&qI(t,i,o),o};const ia=C("debugbutton");class Ko{constructor(){a(this,"colorMultiplier"),a(this,"disabledColor"),a(this,"fadeDuration"),a(this,"highlightedColor"),a(this,"normalColor"),a(this,"pressedColor"),a(this,"selectedColor")}}Ni([m()],Ko.prototype,"colorMultiplier",2),Ni([m(xe)],Ko.prototype,"disabledColor",2),Ni([m()],Ko.prototype,"fadeDuration",2),Ni([m(xe)],Ko.prototype,"highlightedColor",2),Ni([m(xe)],Ko.prototype,"normalColor",2),Ni([m(xe)],Ko.prototype,"pressedColor",2),Ni([m(xe)],Ko.prototype,"selectedColor",2);class XI{constructor(){a(this,"disabledTrigger"),a(this,"highlightedTrigger"),a(this,"normalTrigger"),a(this,"pressedTrigger"),a(this,"selectedTrigger")}}class Yn extends A{constructor(){super(...arguments),a(this,"onClick",new Se),a(this,"_isHovered",0),a(this,"colors"),a(this,"transition"),a(this,"animationTriggers"),a(this,"animator"),a(this,"_interactable",!0),a(this,"_requestedAnimatorTrigger"),a(this,"_isInit",!1),a(this,"_image")}click(){var t;(t=this.onClick)==null||t.invoke()}onPointerEnter(t){var i,n;const o=t.event.pointerType==="mouse"&&t.button===0;o&&(this._isHovered+=1),ia&&console.warn("Button Enter",o,this._isHovered,(i=this.animationTriggers)==null?void 0:i.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.highlightedTrigger):this.transition===1&&this.colors&&((n=this._image)==null||n.setState("hovered")),o&&this.context.input.setCursor("pointer"))}onPointerExit(){var t,i;this._isHovered-=1,this._isHovered<0&&(this._isHovered=0),ia&&console.log("Button Exit",this._isHovered,(t=this.animationTriggers)==null?void 0:t.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&&((i=this._image)==null||i.setState("normal")),this.context.input.unsetCursor("pointer")))}onPointerDown(t){var i,n;ia&&console.log("Button Down",(i=this.animationTriggers)==null?void 0:i.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&((n=this._image)==null||n.setState("pressed")))}onPointerUp(t){var i,n;ia&&console.warn("Button Up",(i=this.animationTriggers)==null?void 0:i.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&&((n=this._image)==null||n.setState(this._isHovered?"hovered":"normal")))}onPointerClick(t){if(this.interactable&&!(t.button!==0&&t.event.pointerType===Pd.Mouse)&&(ia&&(console.warn("Button Click",this.onClick),De("CLICKED button "+this.name+" at "+this.context.time.frameCount)),this.onClick&&this.onClick.listenerCount>0&&(this.onClick.invoke(),t.use(),ia))){const i=this.gameObject.worldPosition;i.add(this.gameObject.worldUp.multiplyScalar(1+Math.random()*.5)),q.DrawLabel(i,"CLICK:"+Date.now(),.1,1+Math.random()*.5)}}set interactable(t){this._interactable=t,this._image&&(this._image.setInteractable(t),t?this._image.setState("normal"):this._image.setState("disabled"))}get interactable(){return this._interactable}set_interactable(t){this.interactable=t}awake(){super.awake(),ia&&console.log(this),this._isInit=!1,this.init()}start(){var t;(t=this._image)==null||t.setInteractable(this.interactable),this.gameObject.getComponentInParent(Wa)||this.gameObject.addComponent(ku)}onEnable(){super.onEnable()}onDestroy(){this._isHovered&&this.context.input.unsetCursor("pointer")}*setAnimatorTriggerAtEndOfFrame(t){var i;this._requestedAnimatorTrigger=t,yield,yield,this._requestedAnimatorTrigger==t&&((i=this.animator)==null||i.setTrigger(t))}init(){this._isInit||(this._isInit=!0,this._image=O.getComponent(this.gameObject,jl),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(t){var i,n,o,r,l;t.setInteractable(this.interactable);const c=this.getFinalColor(t.color,(i=this.colors)==null?void 0:i.normalColor),h={state:"normal",attributes:{backgroundColor:c,backgroundOpacity:c.alpha}};t.setupState(h);const d=this.getFinalColor(t.color,(n=this.colors)==null?void 0:n.highlightedColor),u={state:"hovered",attributes:{backgroundColor:d,backgroundOpacity:d.alpha}};t.setupState(u);const p=this.getFinalColor(t.color,(o=this.colors)==null?void 0:o.pressedColor),g={state:"pressed",attributes:{backgroundColor:p,backgroundOpacity:p.alpha}};t.setupState(g);const y=this.getFinalColor(t.color,(r=this.colors)==null?void 0:r.selectedColor),f={state:"selected",attributes:{backgroundColor:y,backgroundOpacity:y.alpha}};t.setupState(f);const v=this.getFinalColor(t.color,(l=this.colors)==null?void 0:l.disabledColor),b={state:"disabled",attributes:{backgroundColor:v,backgroundOpacity:v.alpha}};t.setupState(b)}getFinalColor(t,i){return i?t.clone().multiply(i).convertLinearToSRGB():t.clone().convertLinearToSRGB()}}Ni([m(Se)],Yn.prototype,"onClick",2),Ni([m(Ko)],Yn.prototype,"colors",2),Ni([m()],Yn.prototype,"transition",2),Ni([m(XI)],Yn.prototype,"animationTriggers",2),Ni([m(Pt)],Yn.prototype,"animator",2),Ni([m()],Yn.prototype,"interactable",1);var QI=Object.defineProperty,YI=Object.getOwnPropertyDescriptor,Xp=(s,t,i,n)=>{for(var o=n>1?void 0:n?YI(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&QI(t,i,o),o};const Jo=C("debuginputfield");var Ll;const K=(Ll=class extends A{constructor(){super(...arguments),a(this,"textComponent"),a(this,"placeholder"),a(this,"onValueChanged"),a(this,"onEndEdit"),a(this,"inputEventFn"),a(this,"_iosEventFn")}get text(){var s;return((s=this.textComponent)==null?void 0:s.text)??""}set text(s){this.textComponent&&(this.textComponent.text=s,this.placeholder&&(s.length>0?this.placeholder.gameObject.visible=!1:this.placeholder.gameObject.visible=!0))}get isFocused(){return K.active===this}start(){Jo&&console.log(this.name,this)}onEnable(){var s;K.htmlField||(K.htmlField=document.createElement("input"),K.htmlField.style.width="0px",K.htmlField.style.height="0px",K.htmlField.style.padding="0px",K.htmlField.style.border="none",K.htmlField.style.overflow="hidden",K.htmlField.style.caretColor="transparent",K.htmlField.style.outline="none",K.htmlField.classList.add("ar"),K.htmlField.onfocus=()=>K.htmlFieldFocused=!0,K.htmlField.onblur=()=>K.htmlFieldFocused=!1,document.body.append(K.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),K.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&(s=this.textComponent)!=null&&s.text.length&&O.setActive(this.placeholder.gameObject,!1),X.isiOS()&&(this._iosEventFn=this.processInputOniOS.bind(this),window.addEventListener("click",this._iosEventFn))}onDisable(){var s;(s=K.htmlField)==null||s.removeEventListener("keyup",this.inputEventFn),this.onDeselected(),this._iosEventFn&&window.removeEventListener("click",this._iosEventFn)}clear(){K.active===this&&K.htmlField?(K.htmlField.value="",this.setTextFromInputField()):(this.textComponent&&(this.textComponent.text=""),this.placeholder&&O.setActive(this.placeholder.gameObject,!0))}select(){this.onSelected()}deselect(){this.onDeselected()}onPointerEnter(s){s.event.pointerType==="mouse"&&s.button===0&&this.context.input.setCursor("text")}onPointerExit(s){this.context.input.unsetCursor("text")}onPointerClick(s){Jo&&console.log("CLICK",s,K.active),K.activeTime=this.context.time.time,K.active!==this&&this.startCoroutine(this.activeLoop(),Me.LateUpdate),this.selectInputField()}*activeLoop(){for(this.onSelected();K.active===this&&!(this.context.input.getPointerClicked(0)&&this.context.time.time-K.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){var s,t,i,n;if(K.active!==this&&(Jo&&console.log("Select",this.name,this,K.htmlField,this.context.isInXR,this.context.arOverlayElement,(s=this.textComponent)==null?void 0:s.text,(t=K.htmlField)==null?void 0:t.value),(i=K.active)==null||i.onDeselected(),K.active=this,this.placeholder&&O.setActive(this.placeholder.gameObject,!1),K.htmlField)){if(K.htmlField.value=((n=this.textComponent)==null?void 0:n.text)||"",Jo&&console.log("set input field value",K.htmlField.value),this.context.isInXR){const o=this.context.arOverlayElement;o&&o.append(K.htmlField)}this.selectInputField()}}onDeselected(){var s;K.active===this&&(K.active=null,Jo&&console.log("Deselect",this.name,this),K.htmlField&&(K.htmlField.blur(),document.body.append(K.htmlField)),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&O.setActive(this.placeholder.gameObject,!0),K.htmlField&&((s=this.onEndEdit)==null||s.invoke(K.htmlField.value)))}update(){var s;K.active===this&&((s=this.textComponent)==null||s.markDirty())}onInput(s){var t,i;if(K.active===this){if(Jo&&console.log(s.code,s,(t=K.htmlField)==null?void 0:t.value,(i=this.textComponent)==null?void 0:i.text),s.code==="Escape"||s.code==="Enter"){this.onDeselected();return}K.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&O.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){var s;if(this.textComponent&&K.htmlField){const t=this.textComponent.text,i=K.htmlField.value,n=this.textComponent.text!==K.htmlField.value;this.textComponent.text=K.htmlField.value,n&&(Jo&&console.log("[InputField] value changed:",i,t),(s=this.onValueChanged)==null||s.invoke(i,t))}}selectInputField(){K.htmlField&&(Jo&&console.log("Focus Inputfield",K.htmlFieldFocused),K.htmlField.setSelectionRange(K.htmlField.value.length,K.htmlField.value.length),X.isiOS()?K.htmlField.focus({preventScroll:!0}):setTimeout(()=>{var s;return(s=K.htmlField)==null?void 0:s.focus()},1))}processInputOniOS(){const s=this.context.physics.raycast();if(!s.length)return;const t=s[0].object,i=mf(t);(i?.gameObject===this.gameObject||i?.gameObject.parent===this.gameObject)&&this.selectInputField()}},a(Ll,"active",null),a(Ll,"activeTime",-1),a(Ll,"htmlField",null),a(Ll,"htmlFieldFocused",!1),Ll);let sa=K;Xp([m(Vt)],sa.prototype,"textComponent",2),Xp([m(Vt)],sa.prototype,"placeholder",2),Xp([m(Se)],sa.prototype,"onValueChanged",2),Xp([m(Se)],sa.prototype,"onEndEdit",2);var ZI=Object.defineProperty,KI=Object.getOwnPropertyDescriptor,L1=(s,t,i,n)=>{for(var o=n>1?void 0:n?KI(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&ZI(t,i,o),o};class Wh extends A{constructor(){super(...arguments),a(this,"id",null),a(this,"keepAspect",!1),a(this,"_object",null)}onEnable(){if(this._object){this.gameObject.add(this._object);return}if(!this.id||!this.context.mainCamera)return;const t=document.getElementById(this.id);if(!t){console.warn('Could not find element with id "'+this.id+'"');return}t.style.display="block",t.style.visibility="hidden";const i=new ZC;i.listenToPointerEvents(this.context.renderer,this.context.mainCamera),this.gameObject.add(i);const n=new KC(t);i.add(n),n.visible=!1;const o=n.material;o.transparent=!0,setTimeout(()=>{n.visible=!0;const r=ic(this.gameObject).clone();sc(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();const l=new wi;l.setFromObject(i),this.setWorldRotation(r.x,r.y,r.z);const c=l.max.x-l.min.x,h=l.max.y-l.min.y;if(this.keepAspect){const u=c/h;c>h?n.scale.set(1/c,1/h/u,1):n.scale.set(1/c*u,1/h,1)}else n.scale.set(1/c,1/h,1);const d=this.gameObject.scale;n.scale.multiply(d)},1)}onDisable(){var t;(t=this._object)==null||t.removeFromParent()}}L1([m()],Wh.prototype,"id",2),L1([m()],Wh.prototype,"keepAspect",2);var JI=Object.defineProperty,ej=Object.getOwnPropertyDescriptor,Qp=(s,t,i,n)=>{for(var o=n>1?void 0:n?ej(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&JI(t,i,o),o},by;const D1=(by=class extends A{constructor(){super(...arguments),a(this,"target"),a(this,"invertForward",!1),a(this,"keepUpDirection",!0),a(this,"copyTargetRotation",!1)}onBeforeRender(){let s=this.target;if(s||(s=this.context.mainCamera),!s)return;let t=this.copyTargetRotation;(this.context.isInVR||this.context.isInPassThrough)&&(t=!1),tc(this.gameObject,s,this.keepUpDirection,t),this.invertForward&&this.gameObject.quaternion.multiply(D1.flipYQuat)}createBehaviours(s,t,i){if(t.uuid===this.gameObject.uuid){let n=t;if(this.keepUpDirection){const r=Yt.createEmptyParent(t);n=r;const l=this.invertForward?-1:1;r.setMatrix(r.getMatrix().multiply(new ne().makeRotationZ(Math.PI/2*l))),t.setMatrix(t.getMatrix().multiply(new ne().makeRotationZ(-Math.PI/2*l)))}const o=new Nt("lookat "+this.name,Rt.sceneStartTrigger(),ve.lookAtCameraAction(n,void 0,this.invertForward?cs.back:cs.forward,this.keepUpDirection?cs.up:cs.zero));s.addBehavior(o)}}},a(by,"flipYQuat",new V().setFromAxisAngle(new x(0,1,0),Math.PI)),by);let na=D1;Qp([m(I)],na.prototype,"target",2),Qp([m()],na.prototype,"invertForward",2),Qp([m()],na.prototype,"keepUpDirection",2),Qp([m()],na.prototype,"copyTargetRotation",2);var tj=Object.defineProperty,ij=Object.getOwnPropertyDescriptor,_y=(s,t,i,n)=>{for(var o=n>1?void 0:n?ij(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&tj(t,i,o),o};class Dl extends A{constructor(){super(...arguments),a(this,"url"),a(this,"mode",0),a(this,"clickable",!0)}async open(){if(!this.url){console.warn("OpenURL: URL is not set, can't open.",this);return}this._validateUrl();let t=this.url;switch(!t.startsWith("mailto:")&&t.includes("@")&&(t="mailto:"+t),F()&&De("Open URL: "+t),this.mode){case 0:X.isSafari(),globalThis.open(t,"_blank");break;case 1:X.isSafari()&&X.isiOS()?globalThis.open(t,"_top"):globalThis.open(t,"_self");break;case 2:X.isSafari()?globalThis.open(t,"_top"):globalThis.open(t,"_new");break}}start(){this.gameObject.getComponentInParent(Ei)||this.gameObject.addComponent(Ei)}onPointerEnter(t){!t.used&&this.clickable&&this.context.input.setCursor("pointer")}onPointerExit(){this.clickable&&this.context.input.unsetCursor("pointer")}onPointerClick(t){var i;this.clickable&&!t.used&&(i=this.url)!=null&&i.length&&this.open()}_validateUrl(){this.url&&this.url.startsWith("www.")&&(F()&&console.warn("URL is not valid, adding https:// to the start of the URL",this.url),this.url="https://"+this.url)}}_y([m()],Dl.prototype,"url",2),_y([m()],Dl.prototype,"mode",2),_y([m()],Dl.prototype,"clickable",2);var sj=Object.defineProperty,nj=Object.getOwnPropertyDescriptor,Bl=(s,t,i,n)=>{for(var o=n>1?void 0:n?nj(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&sj(t,i,o),o};class Zn extends A{constructor(){super(...arguments),a(this,"side","none"),a(this,"controller",!0),a(this,"hands",!1),a(this,"controlVisibility",!0),a(this,"useGripSpace",!1),a(this,"resetTransformAfterXRSession",!0),a(this,"_startPosition",new x),a(this,"_startRotation",new V),a(this,"_startScale",new x)}get activeAndEnabled(){return!0}onEnterXR(t){this._startPosition.copy(this.gameObject.position),this._startRotation.copy(this.gameObject.quaternion),this._startScale.copy(this.gameObject.scale)}onUpdateXR(t){if(!this.enabled)return;const i=t.xr.getController(this.side);if(i){if(i.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||i.targetRayMode==="transient-pointer"?(this.gameObject.worldPosition=i.gripWorldPosition,this.gameObject.worldQuaternion=i.gripWorldQuaternion,this.gameObject.worldScale=G(i.xr.rigScale,i.xr.rigScale,i.xr.rigScale).multiply(this._startScale)):(this.gameObject.worldPosition=i.rayWorldPosition,this.gameObject.worldQuaternion=i.rayWorldQuaternion,this.gameObject.worldScale=G(i.xr.rigScale,i.xr.rigScale,i.xr.rigScale).multiply(this._startScale))}}onLeaveXR(t){this.resetTransformAfterXRSession&&(this.gameObject.position.copy(this._startPosition),this.gameObject.quaternion.copy(this._startRotation),this.gameObject.scale.copy(this._startScale))}}Bl([m()],Zn.prototype,"side",2),Bl([m()],Zn.prototype,"controller",2),Bl([m()],Zn.prototype,"hands",2),Bl([m()],Zn.prototype,"controlVisibility",2),Bl([m()],Zn.prototype,"useGripSpace",2),Bl([m()],Zn.prototype,"resetTransformAfterXRSession",2);function B1(s,t){const i=s.xr.getFrame();if(!i)return console.warn("No XRFrame available"),!1;const n=i.session.enabledFeatures;if(n&&!n.some(r=>r==="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.
1338
+ C) Set "joinRandomRoom" to true`),!1):(dy&&console.log("Join "+this.roomName),this._userWantsToBeInARoom=!0,this.context.connection.joinRoom(this.roomName),!0))}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()):F()&&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 t=window.location.search,i=new URLSearchParams(t);return i.has(this.urlParameterName)&&i.delete(this.urlParameterName),i.set(hy,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+i.toString()}return null}setRandomRoomUrlParameter(){const t=Ql(),i=this.generateRoomName();C(this.urlParameterName)?t.set(this.urlParameterName,i):t.append(this.urlParameterName,i),Om(i,t)}generateRoomName(){let t="";for(let i=0;i<6;i++)t+=Math.floor(Math.random()*10).toFixed(0);return t}createRoomButton(){if(this._roomButton)return this._roomButton;const t=document.createElement("button");return this._roomButton=t,t.classList.add("create-room-button"),t.setAttribute("priority","90"),t.onclick=()=>{if(this.context.connection.isInRoom)this.urlParameterName&&Yl(this.urlParameterName,null),this.context.connection.leaveRoom(),this._userWantsToBeInARoom=!1;else{if(this.urlParameterName){const i=C(this.urlParameterName);(!i||i===!0)&&(this._lastJoinedRoom?Yl(this.urlParameterName,this._lastJoinedRoom):this.setRandomRoomUrlParameter())}this.tryJoinRoom()}},this._roomButtonIconJoin=Ot("group"),this._roomButtonIconLeave=Ot("group_off"),this.updateRoomButtonState(),this.context.connection.beginListen(se.JoinedRoom,this.updateRoomButtonState),this.context.connection.beginListen(se.LeftRoom,this.updateRoomButtonState),t}destroyRoomButton(){this.context.connection.stopListen(se.JoinedRoom,this.updateRoomButtonState),this.context.connection.stopListen(se.LeftRoom,this.updateRoomButtonState)}onEnableViewOnlyButton(){this.context.connection.isConnected?this.onCreateViewOnlyButton():(this.context.connection.stopListen(se.JoinedRoom,this.onCreateViewOnlyButton),this.context.connection.beginListen(se.JoinedRoom,this.onCreateViewOnlyButton))}onDisableViewOnlyButton(){var t;this.context.connection.stopListen(se.JoinedRoom,this.onCreateViewOnlyButton),(t=this._viewOnlyButton)==null||t.remove()}}Yo([m()],js.prototype,"roomName",2),Yo([m()],js.prototype,"urlParameterName",2),Yo([m()],js.prototype,"joinRandomRoom",2),Yo([m()],js.prototype,"requireRoomParameter",2),Yo([m()],js.prototype,"autoRejoin",2),Yo([m()],js.prototype,"createJoinButton",2),Yo([m()],js.prototype,"createViewOnlyButton",2),Yo([m()],js.prototype,"roomPrefix",1);function jI(){const s=C("testwindowcount")||0;s&&s>0&&LI(s)}function LI(s){if(C("testwindow"))return null;const t=new URL(window.location.href);Cm(t.searchParams,DM,1),Cm(t.searchParams,"testwindow",1);const i=t.toString(),n=[];window.onbeforeunload=()=>{for(const h of n)h.close()};const o=.05,r=128;let l=0,c=0;for(let h=0;h<s;h++){l*r+r*.01>=window.innerWidth&&(c+=1,l=0);const d=l*(r*(1+o))+window.screenLeft,u=c*(r*(1+o))+window.screenTop+90+60*c;l+=1;const p=window.open(i,"test window "+h,`popup=yes width=${r} height=${r} top=${u} left=${d}`);if(!p){console.warn("Failed to open window");continue}n.push(p),p.onload=()=>{p.onbeforeunload=()=>{for(let g=0;g<n.length;g++){const y=n[g];y!==p&&y.close()}n.length=0}}}return n}class uy extends A{awake(){jI()}}class py extends A{constructor(){super(...arguments),a(this,"transformsPerFrame",10),a(this,"interval",0),a(this,"useFlatbuffers",!0),a(this,"builder",null),a(this,"models",null)}awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinary(zc,t=>{});else{this.models=[];for(let t=0;t<this.transformsPerFrame;t++)this.models.push(new I1(this.context.connection.connectionId+"_simulatedTransform_"+t,this))}}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 vm(1024));const t=this.builder;for(let i=0;i<this.transformsPerFrame;i++){t.clear();const n=Mw(this.context.connection.connectionId,this);this.context.connection.sendBinary(n)}}else if(this.models)for(let t=0;t<this.models.length;t++){const i=this.models[t];i.dontSave=!0,i.update(this,null),this.context.connection.send("TestSimulateUserData-"+t,i)}}}}class I1{constructor(t,i){a(this,"guid"),a(this,"fast",!1),a(this,"position"),a(this,"rotation"),a(this,"velocity"),a(this,"dontSave"),this.guid=t,this.position={x:0,y:0,z:0},this.rotation={x:0,y:0,z:0,w:0},this.update(i,null)}isValid(){return this.fast!==void 0||this.position!==void 0||this.rotation!==void 0||this.velocity!==void 0}update(t,i){const n=t.worldPosition;this.position.x=n.x,this.position.y=n.y,this.position.z=n.z;const o=t.worldQuaternion;if(this.rotation.x=o.x,this.rotation.y=o.y,this.rotation.z=o.z,this.rotation.w=o.w,this.fast=!1,i){const r=i.getVelocity();this.velocity===void 0&&(this.velocity={x:0,y:0,z:0}),this.velocity.x=r.x,this.velocity.y=r.y,this.velocity.z=r.z}}}a(I1,"temp",new x);var DI=Object.defineProperty,BI=Object.getOwnPropertyDescriptor,Np=(s,t,i,n)=>{for(var o=n>1?void 0:n?BI(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&DI(t,i,o),o};const FI=C("debugsignals");class Wp{constructor(){a(this,"guid")}}Np([m()],Wp.prototype,"guid",2);class Bh{constructor(){a(this,"signal"),a(this,"reaction")}}Np([m(Wp)],Bh.prototype,"signal",2),Np([m(Se)],Bh.prototype,"reaction",2);var my;const Xn=(my=class extends A{constructor(){super(...arguments),a(this,"events")}static invoke(s){if(Xn.receivers[s]){const t=Xn.receivers[s];if(!t)return;for(const i of t)i.invoke(s)}}awake(){FI&&console.log("SignalReceiver awake",this)}onEnable(){if(this.events)for(const s of this.events)Xn.receivers[s.signal.guid]||(Xn.receivers[s.signal.guid]=[]),Xn.receivers[s.signal.guid].push(this)}onDisable(){if(this.events){for(const s of this.events)if(Xn.receivers[s.signal.guid]){const t=Xn.receivers[s.signal.guid].indexOf(this);t>=0&&Xn.receivers[s.signal.guid].splice(t,1)}}}invoke(s){if(!this.events||!Array.isArray(this.events))return;const t=typeof s=="object"?s.guid:s;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)}}},a(my,"receivers",{}),my);let Il=Xn;Np([m(Bh)],Il.prototype,"events",2);var Ui=(s=>(s.Activation="ActivationTrack",s.Animation="AnimationTrack",s.Audio="AudioTrack",s.Control="ControlTrack",s.Marker="MarkerTrack",s.Signal="SignalTrack",s))(Ui||{}),dn=(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))(dn||{}),gy=(s=>(s.Signal="SignalEmitter",s))(gy||{});const un=C("debugtimeline");class Fh{constructor(){a(this,"director"),a(this,"track")}get muted(){return this.track.muted}set muted(t){var i;t!==this.track.muted&&(this.track.muted=t,(i=this.onMuteChanged)==null||i.call(this))}*forEachClip(t=!1){var i;if((i=this.track)!=null&&i.clips)if(t)for(let n=this.track.clips.length-1;n>=0;n--)yield this.track.clips[n];else for(const n of this.track.clips)yield n}getClipTime(t,i){return i.clipIn+(t-i.start)*i.timeScale}getClipTimeNormalized(t,i){return(t-i.start)/i.duration}evaluateWeight(t,i,n,o=!0){if(i<0||i>=n.length)return 0;const r=n[i];if(o||t>=r.start&&t<=r.end){let l=1;const c=!1;if(r.easeInDuration>0){const h=Math.min((t-r.start)/r.easeInDuration,1);l*=h}if(r.easeOutDuration>0&&!c){const h=Math.min((r.end-t)/r.easeOutDuration,1);l*=h}return l}return 0}}class zI{constructor(t){a(this,"clip"),a(this,"rootPositionOffset"),a(this,"rootQuaternionOffset"),a(this,"rootStartPosition"),a(this,"rootEndPosition"),a(this,"rootStartQuaternion"),a(this,"rootEndQuaternion");const i=t.getClip();this.clip=i;const n=t.getRoot(),o=n.name+".position",r=n.name+".quaternion";un&&console.log(i.name,i.tracks,o);for(const l of i.tracks)if(!(l.times.length<=0)){if(l.name.endsWith(o))this.rootStartPosition=new x().fromArray(l.values,0),this.rootEndPosition=new x().fromArray(l.values,l.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),un&&console.log(this.rootPositionOffset);else if(l.name.endsWith(r)&&(this.rootStartQuaternion=new V().fromArray(l.values,0),this.rootEndQuaternion=new V().fromArray(l.values,l.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),un)){const c=new Bt().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",c)}}}get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}}class Vp extends Fh{constructor(){super(...arguments),a(this,"models",[]),a(this,"trackOffset"),a(this,"target"),a(this,"mixer"),a(this,"clips",[]),a(this,"actions",[]),a(this,"weight",1),a(this,"_actionOffsets",[]),a(this,"_didBind",!1),a(this,"_animator",null),a(this,"_useclipOffsets",!0),a(this,"_totalOffsetPosition",new x),a(this,"_totalOffsetRotation",new V),a(this,"_totalOffsetPosition2",new x),a(this,"_totalOffsetRotation2",new V),a(this,"_summedPos",new x),a(this,"_tempPos",new x),a(this,"_summedRot",new V),a(this,"_tempRot",new V),a(this,"_clipRotQuat",new V)}onDisable(){var t;(t=this.mixer)==null||t.stopAllAction()}onDestroy(){this.director.context.animations.unregisterAnimationMixer(this.mixer)}onStateChanged(){this._animator&&_w(this._animator.gameObject,this,this.director.isPlaying)}createHooks(t,i){var n,o;if(((n=i.tracks)==null?void 0:n.length)<=0){console.warn("No tracks in AnimationClip",i);return}const r=i.tracks[0].name.split("."),l=r[r.length-2],c=l+".position",h=l+".quaternion";let d=!1,u=!1;for(const p of i.tracks)p.name.endsWith(c)?(d=!0,this.createPositionInterpolant(i,t,p)):p.name.endsWith(h)&&(u=!0,this.createRotationInterpolant(i,t,p));if(!d||!u){const p=(o=this.mixer)==null?void 0:o.getRoot(),g=i.tracks[0],y=g.name.lastIndexOf("."),f=g.name.substring(0,y),v=f.substring(f.lastIndexOf(".")+1),b=p.getObjectByName(v);if(b)if(d){if(!u){const w=i.tracks[0].name.substring(0,y)+".quaternion";un&&console.warn("Create quaternion track",v,b);const _=b.quaternion,S=new kC(w,[0,i.duration],[_.x,_.y,_.z,_.w,_.x,_.y,_.z,_.w]);i.tracks.push(S),this.createRotationInterpolant(i,t,S)}}else{const w=f+".position";un&&console.warn("Create position track",v,b);const _=b.position,S=new PC(w,[0,i.duration],[_.x,_.y,_.z,_.x,_.y,_.z]);i.tracks.push(S),this.createPositionInterpolant(i,t,S)}}}bind(){if(!this._didBind){this._didBind=!0,un&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(const t of this.actions){const i=new zI(t);this._actionOffsets.push(i)}this.target&&(this._animator=O.getComponent(this.target,Pt)??null,this._animator&&_w(this._animator.gameObject,this,!0));for(const t of this.models){const i=t.asset,n=i.position,o=i.rotation;n&&n.x!==void 0&&(n.isVector3||(i.position=new x(n.x,n.y,n.z)),o.isQuaternion||(i.rotation=new V(o.x,o.y,o.z,o.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){const t=this.trackOffset.position;t&&(t.isVector3||(this.trackOffset.position=new x(t.x,t.y,t.z)));const i=this.trackOffset.rotation;i&&(i.isQuaternion||(this.trackOffset.rotation=new V(i.x,i.y,i.z,i.w)))}}evaluate(t){var i,n,o,r,l,c,h;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 d=0,u=0,p=!1,g=!1,y=0;for(let f=0;f<this.clips.length;f++){const v=this.models[f],b=this.actions[f],w=v.asset;b.weight=0;const _=t>=v.start&&t<=v.end,S=v.preExtrapolationMode,R=v.postExtrapolationMode,M=f<this.clips.length-1?this.models[f+1]:null;let T=_,L=!1;if(!T&&!p&&v.end<t&&R!==dn.None?(!M||M.start>t)&&(T=!0,p=!0):f==0&&!T&&!g&&v.start>t&&S!==dn.None&&(!M||M.start<t)&&(T=!0,L=!0,g=!0),T){let D=this.weight;D*=this.evaluateWeight(t,f,this.models,T),D*=this.director.weight;let U=_;if(L)switch(S){case dn.Hold:break;case dn.Loop:t+=v.start,U=!0;break;default:t+=v.start,U=!0;break}let B=this.getClipTime(t,v),Q=0;const $=w.duration;if(L&&S===dn.Hold&&(B=0),U){if(w.loop)for(Q+=Math.floor(B/($+1e-6));B>$;)B-=$}else if(!_&&p)switch(R){case dn.Hold:B=this.getClipTime(v.end,v);break;case dn.Loop:B%=$;break;case dn.PingPong:const z=Math.floor(B/$)%2!==0;B%=$,z&&(B=$-B);break}v.reversed===!0?b.time=b.getClip().duration-B:b.time=B,b.timeScale=0;const E=Math.max(0,D);if(b.weight=E,y+=E,b.clampWhenFinished=!1,b.isRunning()||b.play(),this._useclipOffsets){const z=d==0?this._totalOffsetPosition:this._totalOffsetPosition2,H=d==0?this._totalOffsetRotation:this._totalOffsetRotation2;d<1&&(u=1-D),d+=1;const ie=this._summedPos.set(0,0,0),oe=this._tempPos.set(0,0,0),de=this._summedRot.identity(),pe=this._tempRot.identity(),Xe=w.rotation;Xe&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp(Xe,D));const Qe=this._actionOffsets[f];if(Qe.hasOffsets)for(let hs=0;hs<Q;hs++)Qe.rootPositionOffset?oe.copy(Qe.rootPositionOffset):oe.set(0,0,0),oe.applyQuaternion(de),this._clipRotQuat&&oe.applyQuaternion(this._clipRotQuat),Qe.rootQuaternionOffset&&(pe.copy(Qe.rootQuaternionOffset),de.multiply(pe)),ie.add(oe);this._clipRotQuat&&H.multiply(this._clipRotQuat),H.multiply(de),w.position&&ie.add(w.position),z.add(ie)}}}if(this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,u),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,u)),this.__mixerError===void 0&&(un||F())&&(n=(i=this._animator)==null?void 0:i.runtimeAnimatorController)!=null&&n.mixer&&this.mixer!==((r=(o=this._animator)==null?void 0:o.runtimeAnimatorController)==null?void 0:r.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)),(l=this._animator)!=null&&l.runtimeAnimatorController){const f=Math.max(0,1-y);(h=(c=this._animator)==null?void 0:c.runtimeAnimatorController)==null||h.update(f)}else this.mixer.update(t)}createRotationInterpolant(t,i,n){var o;const r=n.createInterpolant.bind(n),l=new V;this.ensureTrackOffsets();const c=(o=this.trackOffset)==null?void 0:o.rotation;n.createInterpolant=()=>{const h=r(),d=h.evaluate.bind(h);return h.evaluate=u=>{var p;const g=d(u);if(l.set(g[0],g[1],g[2],g[3]),l.premultiply(this._totalOffsetRotation),c&&l.premultiply(c),this.director.animationCallbackReceivers)for(const y of this.director.animationCallbackReceivers)(p=y?.onTimelineRotation)==null||p.call(y,this.director,this.target,u,l);return g[0]=l.x,g[1]=l.y,g[2]=l.z,g[3]=l.w,g},h}}createPositionInterpolant(t,i,n){var o,r;const l=n.createInterpolant.bind(n),c=new x;this.ensureTrackOffsets();const h=(o=this.trackOffset)==null?void 0:o.rotation,d=(r=this.trackOffset)==null?void 0:r.position;let u;n.createInterpolant=()=>{const p=l(),g=p.evaluate.bind(p);return p.evaluate=y=>{var f,v,b;const w=g(y);if(c.set(w[0],w[1],w[2]),i.removeStartOffset&&(u===void 0?(u=null,u=(v=(f=this._actionOffsets.find(_=>_.clip===t))==null?void 0:f.rootStartPosition)==null?void 0:v.clone()):u!=null&&u.isVector3&&c.sub(u)),c.applyQuaternion(this._totalOffsetRotation),c.add(this._totalOffsetPosition),h&&c.applyQuaternion(h),d&&(c.x-=d.x,c.y+=d.y,c.z+=d.z),this.director.animationCallbackReceivers)for(const _ of this.director.animationCallbackReceivers)(b=_?.onTimelinePosition)==null||b.call(_,this.director,this.target,y,c);return w[0]=c.x,w[1]=c.y,w[2]=c.z,w},p}}}const UI=C("mutetimeline"),zh=class extends Fh{constructor(){super(...arguments),a(this,"models",[]),a(this,"listener"),a(this,"audio",[]),a(this,"audioContextTimeOffset",[]),a(this,"lastTime",0),a(this,"audioSource"),a(this,"_audioLoader",null),a(this,"_playableDirectorResumed",!1)}getAudioFilePath(s){const t=this.director.sourceId;return lo(t,s)}onAllowAudioChanged(s){for(let t=0;t<this.models.length;t++){const i=this.models[t];this.audio[t].setVolume(s?i.asset.volume:0)}}addModel(s){const t=new MC(this.listener);this.audio.push(t);const i=s;i._didTriggerPlay=!1,this.models.push(i)}onDisable(){for(const s of this.audio)s.isPlaying&&s.stop();for(const s of this.models)s._didTriggerPlay=!1}onDestroy(){for(const s of this.audio)s.source&&s?.disconnect();this.audio.length=0}onMuteChanged(){if(this.muted)for(let s=0;s<this.audio.length;s++){const t=this.audio[s];t!=null&&t.isPlaying&&t.stop()}}stop(){for(let s=0;s<this.audio.length;s++){const t=this.audio[s];t!=null&&t.isPlaying&&t.stop()}for(const s of this.models)s._didTriggerPlay=!1}onPauseChanged(){for(let s=0;s<this.audio.length;s++){const t=this.audio[s];t!=null&&t.isPlaying&&t.stop()}this._playableDirectorResumed=this.director.isPlaying}evaluate(s){if(UI||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],l=this.audio[o],c=r.asset;if((!l||!l.buffer)&&this.isInTimeRange(r,s-1,s+1)&&this.handleAudioLoading(r,l),Ne.userInteractionRegistered!==!1&&!(l===null||!l.buffer))if(l.playbackRate=this.director.context.time.timeScale*this.director.speed,l.loop=c.loop,s>=r.start&&s<=r.end&&s<this.director.duration){if(!l.isPlaying||!this.director.isPlaying)(i||!r._didTriggerPlay&&this.lastTime<s)&&(r.duration*r.timeScale>.3?l.offset=r.clipIn+(s-r.start)*r.timeScale:l.offset=0,un&&console.log("Timeline Audio ("+this.track.name+") play with offset "+l.offset+" - "+r.asset.clip),l.play(n),r._didTriggerPlay=!0);else{const d=r.clipIn+(s-r.start)*r.timeScale,u=l.context.currentTime-l._startedAt+l.offset;Math.abs(d-u)>.3&&(l.offset=d,l.stop(),l.play(n))}let h=c.volume;if(this.track.volume!==void 0&&(h*=this.track.volume),t&&(h=0),r.easeInDuration>0){const d=Math.min((s-r.start)/r.easeInDuration,1);h*=d}if(r.easeOutDuration>0){const d=Math.min((r.end-s)/r.easeOutDuration,1);h*=d}l.setVolume(h*this.director.weight)}else r._didTriggerPlay=!1,this.director.isPlaying&&l.isPlaying&&l.stop()}this.lastTime=s}loadAudio(s,t=0,i=0){let n=null;const o=s-i,r=s+t;for(const l of this.models)if(this.isInTimeRange(l,o,r)){const c=this.audio[this.models.indexOf(l)],h=this.handleAudioLoading(l,c);h!==null&&(n===null&&(n=[]),n.push(h))}return n!==null?Promise.all(n):null}isInTimeRange(s,t,i){return t<=s.start&&i>=s.end||t>=s.start&&t<=s.end||i>=s.start&&i<=s.end}static dispose(){zh._audioBuffers.clear()}handleAudioLoading(s,t){this._audioLoader||(this._audioLoader=new cm);const i=this.getAudioFilePath(s.asset.clip);if(zh._audioBuffers.get(i)){const o=zh._audioBuffers.get(i);return o.then(r=>{r&&t.setBuffer(r)}),o}un&&console.warn("LOAD audio track",i,this.director.sourceId);const n=new Promise((o,r)=>{this._audioLoader.load(i,l=>{t.setBuffer(l),o(l)},void 0,l=>{console.error("Error loading audio",l),o(null)})});return zh._audioBuffers.set(i,n),n}};let Uh=zh;a(Uh,"_audioBuffers",new Map);class Nh extends Fh{constructor(){super(...arguments),a(this,"models",[]),a(this,"didTrigger",[]),a(this,"receivers",[])}evaluate(t){var i;if(this.track.muted)return;const n=this.director.context.time.deltaTime*1.5;for(let o=0;o<this.models.length;o++){const r=this.models[o],l=this.didTrigger[o],c=r.time-t;let h=!1;if(r.retroActive)h=c<=1e-6;else{const d=Math.abs(c);(d===0||d>=1e-5&&d<n)&&(h=!0)}if(h){if(!l)if(un&&console.log("Trigger signal",t,r.time,r),this.didTrigger[o]=!0,((i=this.receivers)==null?void 0:i.length)<=0)Il.invoke(r.asset);else for(const d of this.receivers)d&&d.invoke(r.asset)}else r.emitOnce||(this.didTrigger[o]=!1)}}}class Hp extends Fh{constructor(){super(...arguments),a(this,"models",[]),a(this,"timelines",[]),a(this,"_previousActiveModel",null)}resolveSourceObjects(t){for(let i=this.models.length-1;i>=0;i--){const n=this.models[i].asset;if(!n.sourceObject||typeof n.sourceObject!="object"){console.log("no source object, removing model",i,n),this.models.splice(i,1);continue}else{const o=O.getComponent(n.sourceObject,Zo);this.timelines.push(o),o&&n.updateDirector&&(o.playOnAwake=!1)}}}evaluate(t){var i;this._previousActiveModel=null;for(let n=0;n<this.models.length;n++){const o=this.models[n],r=o.asset;if(t>=o.start&&t<=o.end){this._previousActiveModel=o;const l=this.getClipTime(t,o);if(r.controlActivation){const c=r.sourceObject;c.visible=!0}if(r.updateDirector){const c=this.timelines[n];c&&(c.isPlaying&&c.pause(),c.time=l,c.evaluate())}}else{const l=(i=this._previousActiveModel)==null?void 0:i.asset;if(r.controlActivation){const c=r.sourceObject;l?.sourceObject!==c&&(c.visible=!1)}}}}}var NI=Object.defineProperty,WI=Object.getOwnPropertyDescriptor,j1=(s,t,i,n)=>{for(var o=n>1?void 0:n?WI(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&NI(t,i,o),o};const Qn=C("debugtimeline");var fy;const yy=(fy=class extends A{constructor(){super(...arguments),a(this,"playableAsset"),a(this,"playOnAwake"),a(this,"extrapolationMode",1),a(this,"waitForAudio",!0),a(this,"_visibilityChangeEvt"),a(this,"_clonedPlayableAsset",!1),a(this,"_speed",1),a(this,"_guidsMap"),a(this,"_isPlaying",!1),a(this,"_internalUpdateRoutine"),a(this,"_isPaused",!1),a(this,"_isStopping",!1),a(this,"_time",0),a(this,"_duration",0),a(this,"_weight",1),a(this,"_animationTracks",[]),a(this,"_audioTracks",[]),a(this,"_signalTracks",[]),a(this,"_controlTracks",[]),a(this,"_customTracks",[]),a(this,"_allTracks",[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks]),a(this,"animationCallbackReceivers",[])}static registerCreateTrack(s,t){this.createTrackFunctions[s]=t}get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(s){typeof s=="number"&&!Number.isNaN(s)?this._time=s:(Qn||Gt())&&console.error("INVALID TIMELINE.TIME VALUE",s,this.name)}get duration(){return this._duration}set duration(s){this._duration=s}get weight(){return this._weight}set weight(s){this._weight=s}get speed(){return this._speed}set speed(s){this._speed=s}awake(){var s,t,i,n,o;Qn&&console.log(this,(s=this.playableAsset)==null?void 0:s.tracks),this.rebuildGraph(),!this.isValid()&&(Qn||F())&&(Qn?console.warn("PlayableDirector is not valid","Asset?",this.playableAsset,"Tracks:",(t=this.playableAsset)==null?void 0:t.tracks,"IsArray?",Array.isArray((i=this.playableAsset)==null?void 0:i.tracks),this):(o=(n=this.playableAsset)==null?void 0:n.tracks)!=null&&o.length?console.warn("PlayableDirector is not valid"):console.warn("PlayableDirector has no tracks"))}onEnable(){var s,t,i;for(const n of this._audioTracks)(s=n.onEnable)==null||s.call(n);for(const n of this._customTracks)(t=n.onEnable)==null||t.call(n);for(const n of this._animationTracks)(i=n.onEnable)==null||i.call(n);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(){var s,t,i;this.stop();for(const n of this._audioTracks)(s=n.onDisable)==null||s.call(n);for(const n of this._customTracks)(t=n.onDisable)==null||t.call(n);for(const n of this._animationTracks)(i=n.onDisable)==null||i.call(n);this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){var s;for(const t of this._allTracks)for(const i of t)(s=i.onDestroy)==null||s.call(i)}rebuildGraph(){this.isValid()&&(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}async play(){if(!this.isValid())return;const s=this._isPaused==!0;if(this._isPaused=!1,!this._isPlaying){if(this._isPlaying=!0,s&&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&&!Ne.userInteractionRegistered&&this.waitForAudio;)await fs(200)}this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate(),Me.LateUpdate)}}pause(){this.isValid()&&(this._isPlaying=!1,!this._isPaused&&(this._isPaused=!0,this.internalEvaluate(),this.invokePauseChangedMethodsOnTracks(),this.invokeStateChangedMethodsOnTracks()))}stop(){this._isStopping=!0;for(const i of this._audioTracks)i.stop();const s=this._isPaused==!0,t=this._isPlaying;this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.internalEvaluate(),s&&this.invokePauseChangedMethodsOnTracks()),this._isPlaying=!1,this._isPaused=!1,s&&!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 s of this._allTracks)for(const t of s)yield t}get animationTracks(){return this._animationTracks}get audioTracks(){return this._audioTracks}resolveGuids(s){this._guidsMap=s}invokePauseChangedMethodsOnTracks(){var s;for(const t of this.forEachTrack())(s=t.onPauseChanged)==null||s.call(t)}invokeStateChangedMethodsOnTracks(){var s;for(const t of this.forEachTrack())(s=t.onStateChanged)==null||s.call(t,this._isPlaying)}*internalUpdate(){for(;this._isPlaying&&this.activeAndEnabled;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime*this.speed,this.internalEvaluate()),yield}internalEvaluate(s=!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 Ui.Activation:if(!s&&!this._isPlaying)continue;for(let o=0;o<n.outputs.length;o++){const r=n.outputs[o];if(typeof r=="object"){let l=!1;if(n.clips)for(const h of n.clips)h.start<=i&&i<=h.end&&(l=!0);const c=r;c.visible!==void 0&&c.visible!==l&&(c.visible=l,Qn&&console.warn(this.name,"set ActivationTrack-"+o,c.name,l,i))}}break}if(!this._isStopping)for(const n of this._animationTracks)n.evaluate(i);for(const n of this._audioTracks)n.evaluate(i);for(const n of this._signalTracks)n.evaluate(i);for(const n of this._controlTracks)n.evaluate(i);for(const n of this._customTracks)n.evaluate(i)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=Zl(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;const s=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=O.findByGuid(n,s);o===null||typeof o!="object"?(t.outputs.splice(i,1),console.warn("Failed to resolve binding",n,t.name,t.type)):(Qn&&console.log("Resolved binding",n,"to",o),t.outputs[i]=o)}else if(n===null){if(t.outputs.splice(i,1),yy.createTrackFunctions[t.type])continue;t.type!==Ui.Audio&&t.type!==Ui.Control&&t.type!==Ui.Marker&&t.type!==Ui.Signal&&console.warn("Missing binding",n,t.name,t.type,this.name,this.playableAsset.name)}}if(t.type===Ui.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=O.findByGuid(o,s);r===null||typeof r!="object"?console.warn("Failed to resolve sourceObject binding",o,t.name,n):(Qn&&console.log("Resolved binding",o,"to",r),n.asset.sourceObject=r)}}}}findRoot(s){return s.parent?this.findRoot(s.parent):s}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const s of this.playableAsset.tracks)if(s.muted!==!0){if(s.clips)for(const t of s.clips)t.end>this._duration&&(this._duration=t.end);if(s.markers)for(const t of s.markers)t.time>this._duration&&(this._duration=t.time+.001)}}}setupAndCreateTrackHandlers(){var s,t,i;if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let n=O.findObjectOfType(Tn,this.context);for(const o of this.playableAsset.tracks){const r=o.type,l=yy.createTrackFunctions[r];if(l!=null){const c=l(this,o);if(typeof c.evaluate=="function"){c.director=this,c.track=o,this._customTracks.push(c);continue}}if(o.type===Ui.Animation){if(!o.clips||o.clips.length<=0){Qn&&console.warn("Animation track has no clips",o);continue}for(let c=o.outputs.length-1;c>=0;c--){let h=o.outputs[c];if(h instanceof I){const u=O.getOrAddComponent(h,Pt);u&&(h=u)}const d=(s=h?.gameObject)==null?void 0:s.animations;if(d){const u=new Vp;u.trackOffset=o.trackOffset,u.director=this,u.track=o;for(let p=0;p<o.clips.length;p++){const g=o.clips[p],y=g.asset;if(!y){console.error(`Timeline ${this.name}: clip #${p} on track "${o.name}" has no animation data`);continue}const f=y.clip;let v=f;if((typeof v=="string"||typeof v=="number")&&(v=d.find(w=>w.name===f)),Qn&&console.log(y,f,"\u2192",v),!v){console.warn("Could not find animationClip for model",g,o.name,this.name,(t=this.playableAsset)==null?void 0:t.name,d,h);continue}h instanceof Pt&&h.runtimeAnimatorController&&(h.__internalDidAwakeAndStart||h.initializeRuntimeAnimatorController(),h.runtimeAnimatorController.mixer||h.runtimeAnimatorController.bind(h),u.mixer=h.runtimeAnimatorController.mixer),u.mixer||(u.mixer=new am(h.gameObject),this.context.animations.registerAnimationMixer(u.mixer)),u.clips.push(v),u.mixer.uncacheAction(v),u.createHooks(g.asset,v);const b=u.mixer.clipAction(v);u.actions.push(b),u.models.push(g)}this._animationTracks.push(u)}}}else if(o.type===Ui.Audio){if(!o.clips||o.clips.length<=0)continue;const c=new Uh;c.director=this,c.track=o,c.audioSource=o.outputs.find(h=>h instanceof Ne),this._audioTracks.push(c),n||(n=(i=this.context.mainCameraComponent)==null?void 0:i.gameObject.addComponent(Tn)),c.listener=n.listener;for(let h=0;h<o.clips.length;h++){const d=o.clips[h];c.addModel(d)}}else if(o.type===Ui.Marker){const c=new Nh;if(c.director=this,c.track=o,o.markers)for(const h of o.markers)switch(h.type){case gy.Signal:c.models.push(h),c.didTrigger.push(!1);break}if(c!==null&&c.models.length>0){const h=O.getComponent(this.gameObject,Il);h&&(c.receivers.push(h),this._signalTracks.push(c))}}else if(o.type===Ui.Signal){const c=new Nh;if(c.director=this,c.track=o,o.markers)for(const h of o.markers)c.models.push(h),c.didTrigger.push(!1);for(const h of o.outputs)c.receivers.push(h);this._signalTracks.push(c)}else if(o.type===Ui.Control){const c=new Hp;if(c.director=this,c.track=o,o.clips)for(const h of o.clips)c.models.push(h);c.resolveSourceObjects(this.context),this._controlTracks.push(c)}}}setAudioTracksAllowPlaying(s){for(const t of this._audioTracks)t.onAllowAudioChanged(s)}registerAnimationCallback(s){this.animationCallbackReceivers.push(s)}unregisterAnimationCallback(s){const t=this.animationCallbackReceivers.indexOf(s);t!==-1&&this.animationCallbackReceivers.splice(t,1)}},a(fy,"createTrackFunctions",{}),fy);let Zo=yy;j1([m()],Zo.prototype,"playOnAwake",2),j1([m()],Zo.prototype,"extrapolationMode",2);var VI=Object.defineProperty,HI=Object.getOwnPropertyDescriptor,$p=(s,t,i,n)=>{for(var o=n>1?void 0:n?HI(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&VI(t,i,o),o};class ta extends A{constructor(){super(...arguments),a(this,"isGizmo",!1),a(this,"translationSnap",1),a(this,"rotationSnapAngle",15),a(this,"scaleSnap",.25),a(this,"_control"),a(this,"orbit"),a(this,"onControlChangedEvent",t=>{const i=this.orbit;if(i&&(i.enabled=!t.value),t.value){const n=O.getComponentInParent(this.gameObject,qs);n&&n.requestOwnership()}}),a(this,"windowKeyDownListener",t=>{if(this.enabled&&this._control)switch(t.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}}),a(this,"windowKeyUpListener",t=>{if(this.enabled)switch(t.keyCode){case 16:this.disableSnapping();break}})}get control(){return this._control}onEnable(){var t;if(!(this.isGizmo&&!xc)&&this.context.mainCamera&&(this._control||(this._control=new YC(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(i=>{const n=i;if(n.layers.set(2),n){const o=n.material;o&&(o.opacity=.3)}}),this.orbit=O.getComponentInParent(this.context.mainCamera,be)??void 0),this._control)){const i=this._control.getHelper();this.context.scene.add(i),this._control.attach(this.gameObject),(t=this._control)==null||t.addEventListener("dragging-changed",this.onControlChangedEvent),window.addEventListener("keydown",this.windowKeyDownListener),window.addEventListener("keyup",this.windowKeyUpListener)}}onDisable(){var t,i,n;(i=(t=this._control)==null?void 0:t.getHelper())==null||i.removeFromParent(),(n=this._control)==null||n.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(mn.degToRad(this.rotationSnapAngle)),this._control.setScaleSnap(this.scaleSnap))}disableSnapping(){this._control&&(this._control.setTranslationSnap(null),this._control.setRotationSnap(null),this._control.setScaleSnap(null))}}$p([m()],ta.prototype,"isGizmo",2),$p([m()],ta.prototype,"translationSnap",2),$p([m()],ta.prototype,"rotationSnapAngle",2),$p([m()],ta.prototype,"scaleSnap",2);var $I=Object.defineProperty,qI=Object.getOwnPropertyDescriptor,qp=(s,t,i,n)=>{for(var o=n>1?void 0:n?qI(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&$I(t,i,o),o};class vy{constructor(){a(this,"texture",null),a(this,"rect")}}qp([m(Le)],vy.prototype,"texture",2);let jl=class extends fh{constructor(){super(...arguments),a(this,"_sprite"),a(this,"pixelsPerUnitMultiplier",1)}set image(s){this.sprite||(this.sprite=new vy),this.sprite.texture=s,this.onAfterCreated()}get image(){return this.sprite?this.sprite.texture:null}get sprite(){return this._sprite}set sprite(s){this._sprite!==s&&(this._sprite=s,this.onAfterCreated())}isBuiltinSprite(){var s,t,i,n,o,r,l;const c=this.sprite;switch((s=c?.texture)==null?void 0:s.name){case"InputFieldBackground":case"UISprite":case"Background":case"Knob":return!0}return!((i=(t=c?.texture)==null?void 0:t.name)!=null&&i.length)&&((o=(n=c?.texture)==null?void 0:n.image)==null?void 0:o.width)===32&&((l=(r=c?.texture)==null?void 0:r.image)==null?void 0:l.height)===32}onBeforeCreate(s){var t,i;super.onBeforeCreate(s),this.isBuiltinSprite()&&(s.borderRadius=5/this.pixelsPerUnitMultiplier,((i=(t=this.sprite)==null?void 0:t.texture)==null?void 0:i.name)==="Knob"&&(s.borderRadius=999))}onAfterCreated(){var s;this.__didAwake&&(super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture((s=this.sprite)==null?void 0:s.texture))}};qp([m(vy)],jl.prototype,"sprite",1),qp([m()],jl.prototype,"pixelsPerUnitMultiplier",2);class Gp extends fh{constructor(){super(...arguments),a(this,"_mainTexture")}get mainTexture(){return this._mainTexture}set mainTexture(t){this._mainTexture!==t&&(this._mainTexture=t,this.onAfterCreated())}onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),this.setTexture(this.mainTexture))}}qp([m(Le)],Gp.prototype,"mainTexture",1);var GI=Object.defineProperty,XI=Object.getOwnPropertyDescriptor,Ni=(s,t,i,n)=>{for(var o=n>1?void 0:n?XI(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&GI(t,i,o),o};const ia=C("debugbutton");class Ko{constructor(){a(this,"colorMultiplier"),a(this,"disabledColor"),a(this,"fadeDuration"),a(this,"highlightedColor"),a(this,"normalColor"),a(this,"pressedColor"),a(this,"selectedColor")}}Ni([m()],Ko.prototype,"colorMultiplier",2),Ni([m(xe)],Ko.prototype,"disabledColor",2),Ni([m()],Ko.prototype,"fadeDuration",2),Ni([m(xe)],Ko.prototype,"highlightedColor",2),Ni([m(xe)],Ko.prototype,"normalColor",2),Ni([m(xe)],Ko.prototype,"pressedColor",2),Ni([m(xe)],Ko.prototype,"selectedColor",2);class QI{constructor(){a(this,"disabledTrigger"),a(this,"highlightedTrigger"),a(this,"normalTrigger"),a(this,"pressedTrigger"),a(this,"selectedTrigger")}}class Yn extends A{constructor(){super(...arguments),a(this,"onClick",new Se),a(this,"_isHovered",0),a(this,"colors"),a(this,"transition"),a(this,"animationTriggers"),a(this,"animator"),a(this,"_interactable",!0),a(this,"_requestedAnimatorTrigger"),a(this,"_isInit",!1),a(this,"_image")}click(){var t;(t=this.onClick)==null||t.invoke()}onPointerEnter(t){var i,n;const o=t.event.pointerType==="mouse"&&t.button===0;o&&(this._isHovered+=1),ia&&console.warn("Button Enter",o,this._isHovered,(i=this.animationTriggers)==null?void 0:i.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.highlightedTrigger):this.transition===1&&this.colors&&((n=this._image)==null||n.setState("hovered")),o&&this.context.input.setCursor("pointer"))}onPointerExit(){var t,i;this._isHovered-=1,this._isHovered<0&&(this._isHovered=0),ia&&console.log("Button Exit",this._isHovered,(t=this.animationTriggers)==null?void 0:t.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&&((i=this._image)==null||i.setState("normal")),this.context.input.unsetCursor("pointer")))}onPointerDown(t){var i,n;ia&&console.log("Button Down",(i=this.animationTriggers)==null?void 0:i.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&((n=this._image)==null||n.setState("pressed")))}onPointerUp(t){var i,n;ia&&console.warn("Button Up",(i=this.animationTriggers)==null?void 0:i.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&&((n=this._image)==null||n.setState(this._isHovered?"hovered":"normal")))}onPointerClick(t){if(this.interactable&&!(t.button!==0&&t.event.pointerType===Pd.Mouse)&&(ia&&(console.warn("Button Click",this.onClick),De("CLICKED button "+this.name+" at "+this.context.time.frameCount)),this.onClick&&this.onClick.listenerCount>0&&(this.onClick.invoke(),t.use(),ia))){const i=this.gameObject.worldPosition;i.add(this.gameObject.worldUp.multiplyScalar(1+Math.random()*.5)),q.DrawLabel(i,"CLICK:"+Date.now(),.1,1+Math.random()*.5)}}set interactable(t){this._interactable=t,this._image&&(this._image.setInteractable(t),t?this._image.setState("normal"):this._image.setState("disabled"))}get interactable(){return this._interactable}set_interactable(t){this.interactable=t}awake(){super.awake(),ia&&console.log(this),this._isInit=!1,this.init()}start(){var t;(t=this._image)==null||t.setInteractable(this.interactable),this.gameObject.getComponentInParent(Wa)||this.gameObject.addComponent(ku)}onEnable(){super.onEnable()}onDestroy(){this._isHovered&&this.context.input.unsetCursor("pointer")}*setAnimatorTriggerAtEndOfFrame(t){var i;this._requestedAnimatorTrigger=t,yield,yield,this._requestedAnimatorTrigger==t&&((i=this.animator)==null||i.setTrigger(t))}init(){this._isInit||(this._isInit=!0,this._image=O.getComponent(this.gameObject,jl),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(t){var i,n,o,r,l;t.setInteractable(this.interactable);const c=this.getFinalColor(t.color,(i=this.colors)==null?void 0:i.normalColor),h={state:"normal",attributes:{backgroundColor:c,backgroundOpacity:c.alpha}};t.setupState(h);const d=this.getFinalColor(t.color,(n=this.colors)==null?void 0:n.highlightedColor),u={state:"hovered",attributes:{backgroundColor:d,backgroundOpacity:d.alpha}};t.setupState(u);const p=this.getFinalColor(t.color,(o=this.colors)==null?void 0:o.pressedColor),g={state:"pressed",attributes:{backgroundColor:p,backgroundOpacity:p.alpha}};t.setupState(g);const y=this.getFinalColor(t.color,(r=this.colors)==null?void 0:r.selectedColor),f={state:"selected",attributes:{backgroundColor:y,backgroundOpacity:y.alpha}};t.setupState(f);const v=this.getFinalColor(t.color,(l=this.colors)==null?void 0:l.disabledColor),b={state:"disabled",attributes:{backgroundColor:v,backgroundOpacity:v.alpha}};t.setupState(b)}getFinalColor(t,i){return i?t.clone().multiply(i).convertLinearToSRGB():t.clone().convertLinearToSRGB()}}Ni([m(Se)],Yn.prototype,"onClick",2),Ni([m(Ko)],Yn.prototype,"colors",2),Ni([m()],Yn.prototype,"transition",2),Ni([m(QI)],Yn.prototype,"animationTriggers",2),Ni([m(Pt)],Yn.prototype,"animator",2),Ni([m()],Yn.prototype,"interactable",1);var YI=Object.defineProperty,ZI=Object.getOwnPropertyDescriptor,Xp=(s,t,i,n)=>{for(var o=n>1?void 0:n?ZI(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&YI(t,i,o),o};const Jo=C("debuginputfield");var Ll;const K=(Ll=class extends A{constructor(){super(...arguments),a(this,"textComponent"),a(this,"placeholder"),a(this,"onValueChanged"),a(this,"onEndEdit"),a(this,"inputEventFn"),a(this,"_iosEventFn")}get text(){var s;return((s=this.textComponent)==null?void 0:s.text)??""}set text(s){this.textComponent&&(this.textComponent.text=s,this.placeholder&&(s.length>0?this.placeholder.gameObject.visible=!1:this.placeholder.gameObject.visible=!0))}get isFocused(){return K.active===this}start(){Jo&&console.log(this.name,this)}onEnable(){var s;K.htmlField||(K.htmlField=document.createElement("input"),K.htmlField.style.width="0px",K.htmlField.style.height="0px",K.htmlField.style.padding="0px",K.htmlField.style.border="none",K.htmlField.style.overflow="hidden",K.htmlField.style.caretColor="transparent",K.htmlField.style.outline="none",K.htmlField.classList.add("ar"),K.htmlField.onfocus=()=>K.htmlFieldFocused=!0,K.htmlField.onblur=()=>K.htmlFieldFocused=!1,document.body.append(K.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),K.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&(s=this.textComponent)!=null&&s.text.length&&O.setActive(this.placeholder.gameObject,!1),X.isiOS()&&(this._iosEventFn=this.processInputOniOS.bind(this),window.addEventListener("click",this._iosEventFn))}onDisable(){var s;(s=K.htmlField)==null||s.removeEventListener("keyup",this.inputEventFn),this.onDeselected(),this._iosEventFn&&window.removeEventListener("click",this._iosEventFn)}clear(){K.active===this&&K.htmlField?(K.htmlField.value="",this.setTextFromInputField()):(this.textComponent&&(this.textComponent.text=""),this.placeholder&&O.setActive(this.placeholder.gameObject,!0))}select(){this.onSelected()}deselect(){this.onDeselected()}onPointerEnter(s){s.event.pointerType==="mouse"&&s.button===0&&this.context.input.setCursor("text")}onPointerExit(s){this.context.input.unsetCursor("text")}onPointerClick(s){Jo&&console.log("CLICK",s,K.active),K.activeTime=this.context.time.time,K.active!==this&&this.startCoroutine(this.activeLoop(),Me.LateUpdate),this.selectInputField()}*activeLoop(){for(this.onSelected();K.active===this&&!(this.context.input.getPointerClicked(0)&&this.context.time.time-K.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){var s,t,i,n;if(K.active!==this&&(Jo&&console.log("Select",this.name,this,K.htmlField,this.context.isInXR,this.context.arOverlayElement,(s=this.textComponent)==null?void 0:s.text,(t=K.htmlField)==null?void 0:t.value),(i=K.active)==null||i.onDeselected(),K.active=this,this.placeholder&&O.setActive(this.placeholder.gameObject,!1),K.htmlField)){if(K.htmlField.value=((n=this.textComponent)==null?void 0:n.text)||"",Jo&&console.log("set input field value",K.htmlField.value),this.context.isInXR){const o=this.context.arOverlayElement;o&&o.append(K.htmlField)}this.selectInputField()}}onDeselected(){var s;K.active===this&&(K.active=null,Jo&&console.log("Deselect",this.name,this),K.htmlField&&(K.htmlField.blur(),document.body.append(K.htmlField)),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&O.setActive(this.placeholder.gameObject,!0),K.htmlField&&((s=this.onEndEdit)==null||s.invoke(K.htmlField.value)))}update(){var s;K.active===this&&((s=this.textComponent)==null||s.markDirty())}onInput(s){var t,i;if(K.active===this){if(Jo&&console.log(s.code,s,(t=K.htmlField)==null?void 0:t.value,(i=this.textComponent)==null?void 0:i.text),s.code==="Escape"||s.code==="Enter"){this.onDeselected();return}K.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&O.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){var s;if(this.textComponent&&K.htmlField){const t=this.textComponent.text,i=K.htmlField.value,n=this.textComponent.text!==K.htmlField.value;this.textComponent.text=K.htmlField.value,n&&(Jo&&console.log("[InputField] value changed:",i,t),(s=this.onValueChanged)==null||s.invoke(i,t))}}selectInputField(){K.htmlField&&(Jo&&console.log("Focus Inputfield",K.htmlFieldFocused),K.htmlField.setSelectionRange(K.htmlField.value.length,K.htmlField.value.length),X.isiOS()?K.htmlField.focus({preventScroll:!0}):setTimeout(()=>{var s;return(s=K.htmlField)==null?void 0:s.focus()},1))}processInputOniOS(){const s=this.context.physics.raycast();if(!s.length)return;const t=s[0].object,i=mf(t);(i?.gameObject===this.gameObject||i?.gameObject.parent===this.gameObject)&&this.selectInputField()}},a(Ll,"active",null),a(Ll,"activeTime",-1),a(Ll,"htmlField",null),a(Ll,"htmlFieldFocused",!1),Ll);let sa=K;Xp([m(Vt)],sa.prototype,"textComponent",2),Xp([m(Vt)],sa.prototype,"placeholder",2),Xp([m(Se)],sa.prototype,"onValueChanged",2),Xp([m(Se)],sa.prototype,"onEndEdit",2);var KI=Object.defineProperty,JI=Object.getOwnPropertyDescriptor,L1=(s,t,i,n)=>{for(var o=n>1?void 0:n?JI(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&KI(t,i,o),o};class Wh extends A{constructor(){super(...arguments),a(this,"id",null),a(this,"keepAspect",!1),a(this,"_object",null)}onEnable(){if(this._object){this.gameObject.add(this._object);return}if(!this.id||!this.context.mainCamera)return;const t=document.getElementById(this.id);if(!t){console.warn('Could not find element with id "'+this.id+'"');return}t.style.display="block",t.style.visibility="hidden";const i=new ZC;i.listenToPointerEvents(this.context.renderer,this.context.mainCamera),this.gameObject.add(i);const n=new KC(t);i.add(n),n.visible=!1;const o=n.material;o.transparent=!0,setTimeout(()=>{n.visible=!0;const r=ic(this.gameObject).clone();sc(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();const l=new wi;l.setFromObject(i),this.setWorldRotation(r.x,r.y,r.z);const c=l.max.x-l.min.x,h=l.max.y-l.min.y;if(this.keepAspect){const u=c/h;c>h?n.scale.set(1/c,1/h/u,1):n.scale.set(1/c*u,1/h,1)}else n.scale.set(1/c,1/h,1);const d=this.gameObject.scale;n.scale.multiply(d)},1)}onDisable(){var t;(t=this._object)==null||t.removeFromParent()}}L1([m()],Wh.prototype,"id",2),L1([m()],Wh.prototype,"keepAspect",2);var ej=Object.defineProperty,tj=Object.getOwnPropertyDescriptor,Qp=(s,t,i,n)=>{for(var o=n>1?void 0:n?tj(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&ej(t,i,o),o},by;const D1=(by=class extends A{constructor(){super(...arguments),a(this,"target"),a(this,"invertForward",!1),a(this,"keepUpDirection",!0),a(this,"copyTargetRotation",!1)}onBeforeRender(){let s=this.target;if(s||(s=this.context.mainCamera),!s)return;let t=this.copyTargetRotation;(this.context.isInVR||this.context.isInPassThrough)&&(t=!1),tc(this.gameObject,s,this.keepUpDirection,t),this.invertForward&&this.gameObject.quaternion.multiply(D1.flipYQuat)}createBehaviours(s,t,i){if(t.uuid===this.gameObject.uuid){let n=t;if(this.keepUpDirection){const r=Yt.createEmptyParent(t);n=r;const l=this.invertForward?-1:1;r.setMatrix(r.getMatrix().multiply(new ne().makeRotationZ(Math.PI/2*l))),t.setMatrix(t.getMatrix().multiply(new ne().makeRotationZ(-Math.PI/2*l)))}const o=new Nt("lookat "+this.name,Rt.sceneStartTrigger(),ve.lookAtCameraAction(n,void 0,this.invertForward?cs.back:cs.forward,this.keepUpDirection?cs.up:cs.zero));s.addBehavior(o)}}},a(by,"flipYQuat",new V().setFromAxisAngle(new x(0,1,0),Math.PI)),by);let na=D1;Qp([m(I)],na.prototype,"target",2),Qp([m()],na.prototype,"invertForward",2),Qp([m()],na.prototype,"keepUpDirection",2),Qp([m()],na.prototype,"copyTargetRotation",2);var ij=Object.defineProperty,sj=Object.getOwnPropertyDescriptor,_y=(s,t,i,n)=>{for(var o=n>1?void 0:n?sj(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&ij(t,i,o),o};class Dl extends A{constructor(){super(...arguments),a(this,"url"),a(this,"mode",0),a(this,"clickable",!0)}async open(){if(!this.url){console.warn("OpenURL: URL is not set, can't open.",this);return}this._validateUrl();let t=this.url;switch(!t.startsWith("mailto:")&&t.includes("@")&&(t="mailto:"+t),F()&&De("Open URL: "+t),this.mode){case 0:X.isSafari(),globalThis.open(t,"_blank");break;case 1:X.isSafari()&&X.isiOS()?globalThis.open(t,"_top"):globalThis.open(t,"_self");break;case 2:X.isSafari()?globalThis.open(t,"_top"):globalThis.open(t,"_new");break}}start(){this.gameObject.getComponentInParent(Ei)||this.gameObject.addComponent(Ei)}onPointerEnter(t){!t.used&&this.clickable&&this.context.input.setCursor("pointer")}onPointerExit(){this.clickable&&this.context.input.unsetCursor("pointer")}onPointerClick(t){var i;this.clickable&&!t.used&&(i=this.url)!=null&&i.length&&this.open()}_validateUrl(){this.url&&this.url.startsWith("www.")&&(F()&&console.warn("URL is not valid, adding https:// to the start of the URL",this.url),this.url="https://"+this.url)}}_y([m()],Dl.prototype,"url",2),_y([m()],Dl.prototype,"mode",2),_y([m()],Dl.prototype,"clickable",2);var nj=Object.defineProperty,oj=Object.getOwnPropertyDescriptor,Bl=(s,t,i,n)=>{for(var o=n>1?void 0:n?oj(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&nj(t,i,o),o};class Zn extends A{constructor(){super(...arguments),a(this,"side","none"),a(this,"controller",!0),a(this,"hands",!1),a(this,"controlVisibility",!0),a(this,"useGripSpace",!1),a(this,"resetTransformAfterXRSession",!0),a(this,"_startPosition",new x),a(this,"_startRotation",new V),a(this,"_startScale",new x)}get activeAndEnabled(){return!0}onEnterXR(t){this._startPosition.copy(this.gameObject.position),this._startRotation.copy(this.gameObject.quaternion),this._startScale.copy(this.gameObject.scale)}onUpdateXR(t){if(!this.enabled)return;const i=t.xr.getController(this.side);if(i){if(i.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||i.targetRayMode==="transient-pointer"?(this.gameObject.worldPosition=i.gripWorldPosition,this.gameObject.worldQuaternion=i.gripWorldQuaternion,this.gameObject.worldScale=G(i.xr.rigScale,i.xr.rigScale,i.xr.rigScale).multiply(this._startScale)):(this.gameObject.worldPosition=i.rayWorldPosition,this.gameObject.worldQuaternion=i.rayWorldQuaternion,this.gameObject.worldScale=G(i.xr.rigScale,i.xr.rigScale,i.xr.rigScale).multiply(this._startScale))}}onLeaveXR(t){this.resetTransformAfterXRSession&&(this.gameObject.position.copy(this._startPosition),this.gameObject.quaternion.copy(this._startRotation),this.gameObject.scale.copy(this._startScale))}}Bl([m()],Zn.prototype,"side",2),Bl([m()],Zn.prototype,"controller",2),Bl([m()],Zn.prototype,"hands",2),Bl([m()],Zn.prototype,"controlVisibility",2),Bl([m()],Zn.prototype,"useGripSpace",2),Bl([m()],Zn.prototype,"resetTransformAfterXRSession",2);function B1(s,t){const i=s.xr.getFrame();if(!i)return console.warn("No XRFrame available"),!1;const n=i.session.enabledFeatures;if(n&&!n.some(r=>r==="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.
1335
1339
 
1336
1340
  Example to request camera-access in global scope:
1337
1341
  NeedleXRSession.onSessionRequestStart(evt => {
1338
1342
  evt.init.optionalFeatures = evt.init.optionalFeatures || [];
1339
1343
  evt.init.optionalFeatures.push('camera-access');
1340
1344
  });
1341
- `),F()&&rc("No camera feed available - please request the 'camera-access' feature before starting WebXR or add the ARCameraBackground component to your scene"),!1;const o=i.getViewerPose(s.xr.getReferenceSpace());if(o)for(const r of o.views)if("camera"in r&&r.camera){let l=s.xr.getBinding();if(l||(l=new XRWebGLBinding(i.session,s.getContext())),l){let c=null;if("getCameraImage"in l){oj(s,t);const h=s.properties.get(t);if(h)return c=l.getCameraImage(r.camera),h.__webglTexture=c,!0;console.warn("No texture properties found for target texture")}}else console.error(r.camera,s.xr)}else console.error("NO CAMERA IN VIEW");else console.error(s.xr.getReferenceSpace(),i);return!1}const F1=new WeakMap;function oj(s,t){const i=F1.get(t)||new WeakSet;if(i.has(s))return;i.add(s),F1.set(t,i),console.debug("Initialize texture for camera feed");const n=new Re,o=new Fs,r=new Vi;r.add(new Y(o,n));const l=new _e;n.map=t,s.render(r,l)}function rj(s,t,i,n="image/webp",o){return wy({context:s,width:t,height:i,mimeType:n,camera:o})}function wy(s){var t,i;s||(s={});const{transparent:n=!1}=s;let{mimeType:o,context:r,width:l,height:c,camera:h}=s;if(!r&&(r=ue.Current,!r))return console.error("Can not save screenshot: No needle-engine context found or provided."),null;if(!h&&(h=r.mainCamera,!h))return console.error("No camera found"),null;const d=r.renderer,u=d.xr.enabled;if(u&&r.currentFrameEvent!=Me.EarlyUpdate)return console.warn("Screenshot: defer to access XR frame"),new Promise(j=>{Sn(L=>{const U=wy(s);j(U)},Me.EarlyUpdate,{once:!0})});const p=d.domElement,g=p.width,y=p.height;l||(l=g),c||(c=y);const f=l,v=c,b=window.devicePixelRatio||1;l/=b,c/=b,d.xr.isPresenting&&d.xr.getFrame();const w=d.xr.enabled;d.xr.enabled=!1,d.xr.isPresenting=!1,p.style.width=`${l}px`,p.style.height=`${c}px`;const _=d.getRenderTarget(),S=d.getClearColor(new ae),R=d.getClearAlpha(),M=r.scene.background,T="aspect"in h?h.aspect:null;try{const j=s.render_events!==!1,L=new Array;j&&(Aa(r.scene,Ze,L),L.forEach(E=>{var z;if(E?.onBeforeRender(),E.isInstancingActive&&E.instances)for(let H=0;H<((z=E.instances)==null?void 0:z.length);H++){const ie=E.instances[H];On(ie.object,!0)}})),n&&(r.scene.background=null,d.setClearColor(0,0)),s.background&&(r.scene.background=null,d.setClearColor(s.background),s.background instanceof xe&&d.setClearAlpha(s.background.a)),n&&d.setClearAlpha(0),d.setSize(l,c,!1),"cam"in h&&(h=h.threeCamera),h instanceof _e&&(h.aspect=l/c,h.updateProjectionMatrix());const U="type"in s&&s.type==="texture";let B=null;U&&(B=new vn(l,c,{wrapS:tv,wrapT:tv,format:1023}),d.setRenderTarget(B));let Q=p;if(u?(B&&console.error('Taking XR screenshots with { type: "texture" } is currently not supported.'),Q=Hh.compositeWithCameraImage({width:f,height:v,scene:r.scene,camera:h,renderer:d})):r.renderNow(h||null),h instanceof _e&&T!=null&&(h.aspect=T,h.updateProjectionMatrix()),j&&L.forEach(E=>E.onAfterRender()),!o&&"download_filename"in s&&s.download_filename)switch((t=s.download_filename.split(".").pop())==null?void 0:t.toLowerCase()){case"png":o="image/png";break;case"jpg":case"jpeg":o="image/jpeg";break;case"webp":o="image/webp";break}if(n&&s.trim===!0){const E=aj(Q);E&&(Q=E)}if("type"in s){if(s.type==="texture")return B?(s.target&&(s.target.image=B?.texture.image,s.target.needsUpdate=!0),B.texture.offset.set(0,-1),B.texture.needsUpdate=!0,B.texture):(console.error("No target texture found"),null);if(s.type==="blob")return new Promise((E,z)=>{Q.toBlob(H=>{E(H)},o)});if(s.type==="share")return new Promise((E,z)=>{Q.toBlob(H=>{if(H&&"share"in navigator){let ie="file_type"in s&&s.file_type||o;o||(ie="image/png");const oe=ie?.split("/")[1]||"png",de=new File([H],"filename"in s?s.filename||`screenshot.${oe}`:`screenshot.${oe}`,{type:ie});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:[de]}).catch(pe=>{console.warn("User cancelled share",pe.message)}).finally(()=>{E({blob:H,shared:!0})})}return{blob:H,shared:!1}},o)})}const $=Q.toDataURL(o);if("download_filename"in s&&s.download_filename){let E=s.download_filename;if(X.isMobileDevice()&&typeof window<"u"){const z=E+"_screenshots",H=E.split("."),ie=(i=H.pop())==null?void 0:i.toLowerCase();let oe=0;localStorage.getItem(z)&&(oe=parseInt(sessionStorage.getItem(z)||"0")),oe>0&&(E=`${H.join()}-${oe}.${ie}`),oe+=1,sessionStorage.setItem(z,oe.toString())}z1($,E)}return $}finally{d.setRenderTarget(_),r.scene.background=M,d.setSize(g,y,!1),d.setClearColor(S,R),T!=null&&h instanceof _e&&(h.aspect=T,h.updateProjectionMatrix()),d.xr.enabled=w,d.xr.isPresenting=u,u||r.updateSize(!0)}return null}function aj(s){if(!("document"in globalThis))return null;const t=document.createElement("canvas");t.width=s.width,t.height=s.height;const i=t.getContext("2d");if(!i)return null;i.drawImage(s,0,0);const n=t.width,o=t.height,r=i.getImageData(0,0,n,o).data;let l=o,c=n,h=0,d=0;for(let f=0;f<o;f++)for(let v=0;v<n;v++){const b=(f*n+v)*4;r[b+3]!==0&&(v<c&&(c=v),v>d&&(d=v),f<l&&(l=f),f>h&&(h=f))}const u=d-c+1,p=h-l+1,g=document.createElement("canvas"),y=g.getContext("2d");return y?(g.width=u,g.height=p,y.drawImage(t,c,l,u,p,0,0,u,p),g):null}let Vh=null;function z1(s,t){if(s){if(!s.startsWith("data:image")){console.error("Can not save image: Data url is not an image",s);return}Vh||(Vh=document.createElement("a")),Vh.href=s,Vh.download=t,Vh.click()}}var Hh;(s=>{let t=null,i=null,n=null,o=null,r=null;function l(d){const{renderer:u,width:p,height:g}=d,y=u.xr.enabled,f=u.getRenderTarget(),v=u.autoClear,b=p,w=g,_=p/g;(!n||n.width!==b||n.height!==w)&&(n??(n=new vn(b,w,{colorSpace:ms})),n.width=b,n.height=w,n.samples=4,n.texture.repeat.y=-1,n.texture.offset.y=1),(!r||r.width!==b||r.height!==w)&&(r=document.createElement("canvas"),r.width=b,r.height=w,r.style.position="fixed",r.style.top="0px",r.style.right="0px",r.style.width="300px",r.style.height=`${300/_}px`,r.style.zIndex="1000",r.style.pointerEvents="none",r.style.opacity="1.0",r.style.willChange="contents"),t||(t=h({defines:{DECODE_VIDEO_TEXTURE:!0}})),i||(i=h()),o||(o=new Le),u.xr.updateCamera(d.camera),u.xr.enabled=!1,u.autoClear=!1,u.clear(),u.setSize(b,w),u.setRenderTarget(n),B1(d.renderer,o)||console.error("Could not update texture from XR frame");const S=O.findObjectOfType($h);return S?S.setTexture(o):(t.setTexture(o),u.render(t,d.camera)),u.clearDepth(),u.setSize(b,w),u.render(d.scene,d.camera),u.setRenderTarget(null),i.setTexture(n.texture),u.render(i,d.camera),r.getContext("2d",{alpha:!1}).drawImage(u.domElement,0,0,r.width,r.height),u.setRenderTarget(f),u.xr.enabled=y,u.autoClear=v,r}s.compositeWithCameraImage=l;const c=`
1345
+ `),F()&&rc("No camera feed available - please request the 'camera-access' feature before starting WebXR or add the ARCameraBackground component to your scene"),!1;const o=i.getViewerPose(s.xr.getReferenceSpace());if(o)for(const r of o.views)if("camera"in r&&r.camera){let l=s.xr.getBinding();if(l||(l=new XRWebGLBinding(i.session,s.getContext())),l){let c=null;if("getCameraImage"in l){rj(s,t);const h=s.properties.get(t);if(h)return c=l.getCameraImage(r.camera),h.__webglTexture=c,!0;console.warn("No texture properties found for target texture")}}else console.error(r.camera,s.xr)}else console.error("NO CAMERA IN VIEW");else console.error(s.xr.getReferenceSpace(),i);return!1}const F1=new WeakMap;function rj(s,t){const i=F1.get(t)||new WeakSet;if(i.has(s))return;i.add(s),F1.set(t,i),console.debug("Initialize texture for camera feed");const n=new Re,o=new Fs,r=new Vi;r.add(new Y(o,n));const l=new _e;n.map=t,s.render(r,l)}function aj(s,t,i,n="image/webp",o){return wy({context:s,width:t,height:i,mimeType:n,camera:o})}function wy(s){var t,i;s||(s={});const{transparent:n=!1}=s;let{mimeType:o,context:r,width:l,height:c,camera:h}=s;if(!r&&(r=ue.Current,!r))return console.error("Can not save screenshot: No needle-engine context found or provided."),null;if(!h&&(h=r.mainCamera,!h))return console.error("No camera found"),null;const d=r.renderer,u=d.xr.enabled;if(u&&r.currentFrameEvent!=Me.EarlyUpdate)return console.warn("Screenshot: defer to access XR frame"),new Promise(L=>{Sn(D=>{const U=wy(s);L(U)},Me.EarlyUpdate,{once:!0})});const p=d.domElement,g=p.width,y=p.height;l||(l=g),c||(c=y);const f=l,v=c,b=window.devicePixelRatio||1;l/=b,c/=b,d.xr.isPresenting&&d.xr.getFrame();const w=d.xr.enabled;d.xr.enabled=!1,d.xr.isPresenting=!1,p.style.width=`${l}px`,p.style.height=`${c}px`;const _=d.getRenderTarget(),S=d.getClearColor(new ae),R=d.getClearAlpha(),M=r.scene.background,T="aspect"in h?h.aspect:null;try{const L=s.render_events!==!1,D=new Array;L&&(Aa(r.scene,Ze,D),D.forEach(E=>{var z;if(E?.onBeforeRender(),E.isInstancingActive&&E.instances)for(let H=0;H<((z=E.instances)==null?void 0:z.length);H++){const ie=E.instances[H];On(ie.object,!0)}})),n&&(r.scene.background=null,d.setClearColor(0,0)),s.background&&(r.scene.background=null,d.setClearColor(s.background),s.background instanceof xe&&d.setClearAlpha(s.background.a)),n&&d.setClearAlpha(0),d.setSize(l,c,!1),"cam"in h&&(h=h.threeCamera),h instanceof _e&&(h.aspect=l/c,h.updateProjectionMatrix());const U="type"in s&&s.type==="texture";let B=null;U&&(B=new vn(l,c,{wrapS:tv,wrapT:tv,format:1023}),d.setRenderTarget(B));let Q=p;if(u?(B&&console.error('Taking XR screenshots with { type: "texture" } is currently not supported.'),Q=Hh.compositeWithCameraImage({width:f,height:v,scene:r.scene,camera:h,renderer:d})):r.renderNow(h||null),h instanceof _e&&T!=null&&(h.aspect=T,h.updateProjectionMatrix()),L&&D.forEach(E=>E.onAfterRender()),!o&&"download_filename"in s&&s.download_filename)switch((t=s.download_filename.split(".").pop())==null?void 0:t.toLowerCase()){case"png":o="image/png";break;case"jpg":case"jpeg":o="image/jpeg";break;case"webp":o="image/webp";break}if(n&&s.trim===!0){const E=lj(Q);E&&(Q=E)}if("type"in s){if(s.type==="texture")return B?(s.target&&(s.target.image=B?.texture.image,s.target.needsUpdate=!0),B.texture.offset.set(0,-1),B.texture.needsUpdate=!0,B.texture):(console.error("No target texture found"),null);if(s.type==="blob")return new Promise((E,z)=>{Q.toBlob(H=>{E(H)},o)});if(s.type==="share")return new Promise((E,z)=>{Q.toBlob(H=>{if(H&&"share"in navigator){let ie="file_type"in s&&s.file_type||o;o||(ie="image/png");const oe=ie?.split("/")[1]||"png",de=new File([H],"filename"in s?s.filename||`screenshot.${oe}`:`screenshot.${oe}`,{type:ie});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:[de]}).catch(pe=>{console.warn("User cancelled share",pe.message)}).finally(()=>{E({blob:H,shared:!0})})}return{blob:H,shared:!1}},o)})}const $=Q.toDataURL(o);if("download_filename"in s&&s.download_filename){let E=s.download_filename;if(X.isMobileDevice()&&typeof window<"u"){const z=E+"_screenshots",H=E.split("."),ie=(i=H.pop())==null?void 0:i.toLowerCase();let oe=0;localStorage.getItem(z)&&(oe=parseInt(sessionStorage.getItem(z)||"0")),oe>0&&(E=`${H.join()}-${oe}.${ie}`),oe+=1,sessionStorage.setItem(z,oe.toString())}z1($,E)}return $}finally{d.setRenderTarget(_),r.scene.background=M,d.setSize(g,y,!1),d.setClearColor(S,R),T!=null&&h instanceof _e&&(h.aspect=T,h.updateProjectionMatrix()),d.xr.enabled=w,d.xr.isPresenting=u,u||r.updateSize(!0)}return null}function lj(s){if(!("document"in globalThis))return null;const t=document.createElement("canvas");t.width=s.width,t.height=s.height;const i=t.getContext("2d");if(!i)return null;i.drawImage(s,0,0);const n=t.width,o=t.height,r=i.getImageData(0,0,n,o).data;let l=o,c=n,h=0,d=0;for(let f=0;f<o;f++)for(let v=0;v<n;v++){const b=(f*n+v)*4;r[b+3]!==0&&(v<c&&(c=v),v>d&&(d=v),f<l&&(l=f),f>h&&(h=f))}const u=d-c+1,p=h-l+1,g=document.createElement("canvas"),y=g.getContext("2d");return y?(g.width=u,g.height=p,y.drawImage(t,c,l,u,p,0,0,u,p),g):null}let Vh=null;function z1(s,t){if(s){if(!s.startsWith("data:image")){console.error("Can not save image: Data url is not an image",s);return}Vh||(Vh=document.createElement("a")),Vh.href=s,Vh.download=t,Vh.click()}}var Hh;(s=>{let t=null,i=null,n=null,o=null,r=null;function l(d){const{renderer:u,width:p,height:g}=d,y=u.xr.enabled,f=u.getRenderTarget(),v=u.autoClear,b=p,w=g,_=p/g;(!n||n.width!==b||n.height!==w)&&(n??(n=new vn(b,w,{colorSpace:ms})),n.width=b,n.height=w,n.samples=4,n.texture.repeat.y=-1,n.texture.offset.y=1),(!r||r.width!==b||r.height!==w)&&(r=document.createElement("canvas"),r.width=b,r.height=w,r.style.position="fixed",r.style.top="0px",r.style.right="0px",r.style.width="300px",r.style.height=`${300/_}px`,r.style.zIndex="1000",r.style.pointerEvents="none",r.style.opacity="1.0",r.style.willChange="contents"),t||(t=h({defines:{DECODE_VIDEO_TEXTURE:!0}})),i||(i=h()),o||(o=new Le),u.xr.updateCamera(d.camera),u.xr.enabled=!1,u.autoClear=!1,u.clear(),u.setSize(b,w),u.setRenderTarget(n),B1(d.renderer,o)||console.error("Could not update texture from XR frame");const S=O.findObjectOfType($h);return S?S.setTexture(o):(t.setTexture(o),u.render(t,d.camera)),u.clearDepth(),u.setSize(b,w),u.render(d.scene,d.camera),u.setRenderTarget(null),i.setTexture(n.texture),u.render(i,d.camera),r.getContext("2d",{alpha:!1}).drawImage(u.domElement,0,0,r.width,r.height),u.setRenderTarget(f),u.xr.enabled=y,u.autoClear=v,r}s.compositeWithCameraImage=l;const c=`
1342
1346
  uniform sampler2D t2D;
1343
1347
  varying vec2 vUv;
1344
1348
 
@@ -1357,7 +1361,7 @@ void main() {
1357
1361
  #include <tonemapping_fragment>
1358
1362
  #include <colorspace_fragment>
1359
1363
  }
1360
- `;function h(d){const u=d?.material||new ps({name:"BackgroundMaterial",uniforms:iv.clone(dd.background.uniforms),vertexShader:dd.background.vertexShader,fragmentShader:c,defines:d?.defines,side:ao,depthTest:!1,depthWrite:!1,fog:!1});Object.defineProperty(u,"map",{get:function(){return this.threeTexture}});const p=new Y(new Fs(2,2),u);return vd(p,!1),p.geometry.deleteAttribute("normal"),p.renderOrder=-1e6,p.setTexture=function(g){u.uniforms.t2D.value=g},p}s.makeFullscreenPlane=h})(Hh||(Hh={}));var lj=Object.defineProperty,cj=Object.getOwnPropertyDescriptor,hj=(s,t,i,n)=>{for(var o=n>1?void 0:n?cj(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&lj(t,i,o),o};const U1=C("debugarcamera");class $h extends A{constructor(){super(...arguments),a(this,"backgroundTint",new xe(1,1,1,1)),a(this,"backgroundPlane"),a(this,"threeTexture"),a(this,"forceTextureInitialization",function(){const t=new Re,i=new Fs,n=new Vi;n.add(new Y(i,t));const o=new _e;return function(r,l){t.map=l,r.render(n,o),U1&&console.warn("Force texture initialization")}}()),a(this,"preRender",()=>{if(!(!this||!this.gameObject)&&this.context.renderer.xr.getFrame()){if(!this.threeTexture&&this.context.renderer&&(this.threeTexture=new Le,this.forceTextureInitialization(this.context.renderer,this.threeTexture)),this.backgroundPlane===void 0){const t=this.backgroundTint;this.backgroundPlane=Hh.makeFullscreenPlane({material:new ps({name:"BackgroundMaterial",uniforms:{...iv.clone(dd.background.uniforms),tint:{value:new fe(t.r,t.g,t.b,t.a)}},vertexShader:dd.background.vertexShader,fragmentShader:dj,side:Si,depthTest:!1,depthWrite:!1,fog:!1})})}this.backgroundPlane.parent!==this.scene&&this.scene.add(this.backgroundPlane),this.backgroundPlane.material instanceof ps&&this.backgroundPlane.material.uniforms.tint.value.set(this.backgroundTint.r,this.backgroundTint.g,this.backgroundTint.b,this.backgroundTint.a),this.updateFromFrame()}})}onBeforeXR(t,i){t==="immersive-ar"&&(i.optionalFeatures=i.optionalFeatures||[],i.optionalFeatures.push("camera-access"),U1&&console.warn("Requesting camera-access"))}onEnterXR(t){t.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(t){this.backgroundPlane&&this.backgroundPlane.removeFromParent();const i=this.context.pre_render_callbacks.indexOf(this.preRender);i>=0&&this.context.pre_render_callbacks.splice(i,1)}get background(){return this.backgroundPlane}onBeforeRender(t){this.updateFromFrame()}updateFromFrame(){var t;this.threeTexture&&((t=this.context.xr)==null?void 0:t.mode)==="immersive-ar"&&(B1(this.context.renderer,this.threeTexture),this.setTexture(this.threeTexture))}setTexture(t){this.backgroundPlane&&(this.threeTexture=t,this.backgroundPlane.setTexture(this.threeTexture),this.backgroundPlane.visible=!0)}}hj([m(xe)],$h.prototype,"backgroundTint",2);const dj=`
1364
+ `;function h(d){const u=d?.material||new ps({name:"BackgroundMaterial",uniforms:iv.clone(dd.background.uniforms),vertexShader:dd.background.vertexShader,fragmentShader:c,defines:d?.defines,side:ao,depthTest:!1,depthWrite:!1,fog:!1});Object.defineProperty(u,"map",{get:function(){return this.threeTexture}});const p=new Y(new Fs(2,2),u);return vd(p,!1),p.geometry.deleteAttribute("normal"),p.renderOrder=-1e6,p.setTexture=function(g){u.uniforms.t2D.value=g},p}s.makeFullscreenPlane=h})(Hh||(Hh={}));var cj=Object.defineProperty,hj=Object.getOwnPropertyDescriptor,dj=(s,t,i,n)=>{for(var o=n>1?void 0:n?hj(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&cj(t,i,o),o};const U1=C("debugarcamera");class $h extends A{constructor(){super(...arguments),a(this,"backgroundTint",new xe(1,1,1,1)),a(this,"backgroundPlane"),a(this,"threeTexture"),a(this,"forceTextureInitialization",function(){const t=new Re,i=new Fs,n=new Vi;n.add(new Y(i,t));const o=new _e;return function(r,l){t.map=l,r.render(n,o),U1&&console.warn("Force texture initialization")}}()),a(this,"preRender",()=>{if(!(!this||!this.gameObject)&&this.context.renderer.xr.getFrame()){if(!this.threeTexture&&this.context.renderer&&(this.threeTexture=new Le,this.forceTextureInitialization(this.context.renderer,this.threeTexture)),this.backgroundPlane===void 0){const t=this.backgroundTint;this.backgroundPlane=Hh.makeFullscreenPlane({material:new ps({name:"BackgroundMaterial",uniforms:{...iv.clone(dd.background.uniforms),tint:{value:new fe(t.r,t.g,t.b,t.a)}},vertexShader:dd.background.vertexShader,fragmentShader:uj,side:Si,depthTest:!1,depthWrite:!1,fog:!1})})}this.backgroundPlane.parent!==this.scene&&this.scene.add(this.backgroundPlane),this.backgroundPlane.material instanceof ps&&this.backgroundPlane.material.uniforms.tint.value.set(this.backgroundTint.r,this.backgroundTint.g,this.backgroundTint.b,this.backgroundTint.a),this.updateFromFrame()}})}onBeforeXR(t,i){t==="immersive-ar"&&(i.optionalFeatures=i.optionalFeatures||[],i.optionalFeatures.push("camera-access"),U1&&console.warn("Requesting camera-access"))}onEnterXR(t){t.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(t){this.backgroundPlane&&this.backgroundPlane.removeFromParent();const i=this.context.pre_render_callbacks.indexOf(this.preRender);i>=0&&this.context.pre_render_callbacks.splice(i,1)}get background(){return this.backgroundPlane}onBeforeRender(t){this.updateFromFrame()}updateFromFrame(){var t;this.threeTexture&&((t=this.context.xr)==null?void 0:t.mode)==="immersive-ar"&&(B1(this.context.renderer,this.threeTexture),this.setTexture(this.threeTexture))}setTexture(t){this.backgroundPlane&&(this.threeTexture=t,this.backgroundPlane.setTexture(this.threeTexture),this.backgroundPlane.visible=!0)}}dj([m(xe)],$h.prototype,"backgroundTint",2);const uj=`
1361
1365
  uniform sampler2D t2D;
1362
1366
  uniform vec4 tint;
1363
1367
 
@@ -1376,18 +1380,18 @@ void main() {
1376
1380
  #include <tonemapping_fragment>
1377
1381
  #include <colorspace_fragment>
1378
1382
  }
1379
- `;var uj=Object.defineProperty,pj=Object.getOwnPropertyDescriptor,er=(s,t,i,n)=>{for(var o=n>1?void 0:n?pj(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&uj(t,i,o),o};const N1=C("debugimagetracking"),xy=class{constructor(s,t,i,n,o,r){a(this,"measuredSize"),a(this,"state"),a(this,"_position"),a(this,"_rotation"),a(this,"_trackingComponent"),a(this,"_trackedImage"),a(this,"_bitmap"),a(this,"_pose"),this._trackingComponent=s,this._trackedImage=t,this._bitmap=i,this.measuredSize=n,this.state=o,this._pose=r}get url(){return this._trackedImage.image??""}get widthInMeters(){return this._trackedImage.widthInMeters??void 0}get bitmap(){return this._bitmap}get model(){return this._trackedImage}getPosition(s){return this.ensureTransformData(),s.copy(this._position),s}getQuaternion(s){return this.ensureTransformData(),s.copy(this._rotation),s}applyToObject(s,t=void 0){this.ensureTransformData();const i=s.position.distanceToSquared(this._position)/.05+s.quaternion.angleTo(this._rotation)/.05;t&&(t*=Math.max(1,i)),t===void 0||t>=1?(s.position.copy(this._position),s.quaternion.copy(this._rotation)):(t=Math.max(0,Math.min(1,t)),s.position.lerp(this._position,t),s.quaternion.slerp(this._rotation,t))}ensureTransformData(){if(!this._position){this._position=xy._positionBuffer.get(),this._rotation=xy._rotationBuffer.get();const s=this._pose.transform,t=J.active.convertSpace(s);this._position.copy(t?.position),this._rotation.copy(t?.quaternion)}}};let qh=xy;a(qh,"_positionBuffer",new Ci(()=>new x,20)),a(qh,"_rotationBuffer",new Ci(()=>new V,20));class Kn{constructor(){a(this,"image"),a(this,"widthInMeters",.25),a(this,"object"),a(this,"createObjectInstance",!1),a(this,"imageDoesNotMove",!1),a(this,"hideWhenTrackingIsLost",!0)}}er([m(URL)],Kn.prototype,"image",2),er([m()],Kn.prototype,"widthInMeters",2),er([m(le)],Kn.prototype,"object",2),er([m()],Kn.prototype,"createObjectInstance",2),er([m()],Kn.prototype,"imageDoesNotMove",2),er([m()],Kn.prototype,"hideWhenTrackingIsLost",2);class mj{constructor(t,i,n){a(this,"filename"),a(this,"widthInMeters"),a(this,"imageData"),this.filename=t,this.imageData=i,this.widthInMeters=n}get extensionName(){return"image-tracking"}onAfterHierarchy(t,i){const n=X.getiOSVersion(),o=(n?parseInt(n.split(".")[0]):18)>=18?1:100;i.beginBlock('def Preliminary_ReferenceImage "AnchoringReferenceImage"'),i.appendLine("uniform asset image = @image_tracking/"+this.filename+"@"),i.appendLine("uniform double physicalWidth = "+(this.widthInMeters*o).toFixed(8)),i.closeBlock()}onBeforeBuildDocument(t){const i=O.findObjectOfType(oa);!i||!i.trackedImages||i.trackedImages.length>1&&(F()&&we("USDZ: Only one tracked image is supported."),console.warn("USDZ: Only one tracked image is supported."))}onAfterSerialize(t){t.files["image_tracking/"+this.filename]=this.imageData}onExportObject(t,i,n){var o;const r=O.findObjectOfType(oa);if(!(!r||!r.trackedImages)){for(const l of r.trackedImages)if(((o=l.object)==null?void 0:o.asset)===t){const c=O.findObjectOfType($e);if(!c)continue;const{scale:h,target:d}=c.getARScaleAndTarget();let u=t;const p=new ne;if(t!==d)for(;u.parent&&u.parent!==d;)u=u.parent,p.premultiply(u.matrix);const g=p.clone().invert();i.setMatrix(g.scale(new x(h,h,h)));break}}}}var Sy;const Gh=(Sy=class extends A{constructor(){super(...arguments),a(this,"trackedImages"),a(this,"smooth",!0),a(this,"trackedImageIndexMap",new Map),a(this,"_supported",!0),a(this,"imageToObjectMap",new Map),a(this,"currentImages",[]),a(this,"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.`),a(this,"onImageTrackingUpdate",s=>{const t=J.active;if(t)for(const i of s){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(l=>{if(n.createObjectInstance&&l&&(l=O.instantiate(l)),l){r.object=l;for(const c of l.getComponentsInChildren(Ze))c.setInstancingEnabled(!1);t.rig?(t.rig.gameObject.add(l),i.applyToObject(l),l.activeSelf||O.setActive(l,!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||O.setActive(r.object,!0))}}})}get supported(){return this._supported}awake(){if(N1&&console.log(this),!!this.trackedImages){for(const s of this.trackedImages)if(s.image&&!Gh._imageElements.has(s.image)){const t=s.image;Gh._imageElements.set(t,null);const i=document.createElement("img");i.src=t,i.addEventListener("load",async()=>{const n=await createImageBitmap(i);Gh._imageElements.set(t,n);const o=await kx(n);if(o){const r=await(await o.convertToBlob({type:"image/png"})).arrayBuffer(),l=O.findObjectOfType($e);l&&this.trackedImages&&(l.extensions.push(new mj("marker.png",new Uint8Array(r),this.trackedImages[0].widthInMeters)),l.anchoringType="image")}})}}}onBeforeXR(s,t){var i;if(this.trackedImages){t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.includes("image-tracking")||t.optionalFeatures.push("image-tracking"),t.trackedImages=[];for(const n of this.trackedImages)if((i=n.image)!=null&&i.length&&n.widthInMeters>0){const o=Gh._imageElements.get(n.image);o&&(this.trackedImageIndexMap.set(t.trackedImages.length,n),t.trackedImages.push({image:o,widthInMeters:n.widthInMeters}))}}}onEnterXR(s){var t;if(this.trackedImages){for(const i of this.trackedImages)if((t=i.object)!=null&&t.asset){const n=i.object.asset;n.userData||(n.userData={});const o={visible:n.visible,parent:n.parent,matrix:n.matrix.clone()};n.userData["image-tracking"]=o}}for(const i of this.imageToObjectMap.values())i.frames=0}onLeaveXR(s){var t,i;if(!this.supported&&X.isAndroidDevice()&&we(this.webXRIncubationsWarning),this.trackedImages){for(const n of this.trackedImages)if((t=n.object)!=null&&t.asset){const o=n.object.asset;if(o.userData){const r=o.userData["image-tracking"];r&&(o.visible=r.visible,(i=r.parent)==null||i.add(o),o.matrix.copy(r.matrix),o.matrix.decompose(o.position,o.quaternion,o.scale)),delete o.userData["image-tracking"]}}}}onUpdateXR(s){var t;this.currentImages.length=0;const i=s.xr.frame;if(!i)return;if("getImageTrackingResults"in i){if(((t=s.xr.session.enabledFeatures)==null?void 0:t.includes("image-tracking"))===!1)return;if(i.session&&typeof i.getImageTrackingResults=="function"){const o=i.getImageTrackingResults();if(o.length>0){const r=this.context.renderer.xr.getReferenceSpace();if(r){for(const l of o){const c=l.trackingState,h=l.index,d=this.trackedImageIndexMap.get(h);if(d){const u=i.getPose(l.imageSpace,r),p=new qh(this,d,l.image,l.measuredSize,c,u);this.currentImages.push(p)}else N1&&console.warn("No tracked image for index",h)}if(this.currentImages.length>0)try{this.dispatchEvent(new CustomEvent("image-tracking",{detail:this.currentImages})),this.onImageTrackingUpdate(this.currentImages)}catch(l){console.error(l)}}}}}else{this.didPrintWarning||(this.didPrintWarning=!0,console.log(this.webXRIncubationsWarning)),this._supported=!1,we(this.webXRIncubationsWarning);return}const n=1e3;for(const[o,r]of this.imageToObjectMap){if(!r.object||!o||o.hideWhenTrackingIsLost===!1)continue;let l=!1;for(const c of this.currentImages)if(c.model===o){const h=Date.now()-r.lastTrackingTime;if(o.imageDoesNotMove||c.state==="tracked"||h<=n){l=!0;break}}l||O.setActive(r.object,!1)}}},a(Sy,"_imageElements",new Map),Sy);let oa=Gh;er([m(Kn)],oa.prototype,"trackedImages",2),er([m()],oa.prototype,"smooth",2);var gj=Object.defineProperty,fj=Object.getOwnPropertyDescriptor,Fl=(s,t,i,n)=>{for(var o=n>1?void 0:n?fj(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&gj(t,i,o),o};const ra=C("debugplanetracking");class Jn extends A{constructor(){super(...arguments),a(this,"dataTemplate"),a(this,"occluder",!0),a(this,"initiateRoomCaptureIfNoData",!0),a(this,"usePlaneData",!0),a(this,"useMeshData",!0),a(this,"runInVR",!0),a(this,"bounds",new wi),a(this,"center",new x),a(this,"labelOffset",new x),a(this,"_dataId",1),a(this,"_allPlanes",new Map),a(this,"_allMeshes",new Map),a(this,"firstTimeNoPlanesDetected",-100),a(this,"makeOccluder",(t,i,n=!1)=>{if(i){if(i instanceof Array){for(const o of i)this.makeOccluder(t,o,n);return}!n&&!i.name.toLowerCase().includes("occlu")||(i.colorWrite=!1,i.depthTest=!0,i.depthWrite=!0,i.transparent=!1,i.polygonOffset=!0,i.polygonOffsetFactor=1,i.polygonOffsetUnits=.1,t.renderOrder=-1e3)}}),a(this,"_flipForwardMatrix",new ne().makeRotationY(Math.PI)),a(this,"_verticesCache",new Map)}get trackedPlanes(){return this._allPlanes.values()}get trackedMeshes(){return this._allMeshes.values()}onBeforeXR(t,i){t==="immersive-vr"&&!this.runInVR||(i.optionalFeatures=i.optionalFeatures||[],this.usePlaneData&&!i.optionalFeatures.includes("plane-detection")&&i.optionalFeatures.push("plane-detection"),this.useMeshData&&!i.optionalFeatures.includes("mesh-detection")&&i.optionalFeatures.push("mesh-detection"))}onEnterXR(t){for(const i of this._allPlanes.keys())this.removeData(i,this._allPlanes);for(const i of this._allMeshes.keys())this.removeData(i,this._allMeshes)}onLeaveXR(t){for(const i of this._allPlanes.keys())this.removeData(i,this._allPlanes);for(const i of this._allMeshes.keys())this.removeData(i,this._allMeshes)}onUpdateXR(t){if(!this.runInVR&&t.xr.isVR)return;const i=t.xr.rig;if(!i){console.warn("No XR rig found, cannot parent tracked planes to it");return}const n=t.xr.frame;if(!this.context.renderer.xr.getReferenceSpace())return;const o=n.detectedPlanes,r=n.detectedMeshes,l=o!==void 0&&o.size>0,c=r!==void 0&&r.size>0;if(this.initiateRoomCaptureIfNoData&&(!l&&!c&&this.firstTimeNoPlanesDetected<-10&&(this.firstTimeNoPlanesDetected=Date.now()),(l||c)&&(this.firstTimeNoPlanesDetected=-1),this.firstTimeNoPlanesDetected>0&&Date.now()-this.firstTimeNoPlanesDetected>2500&&"initiateRoomCapture"in n.session&&(n.session.initiateRoomCapture(),this.firstTimeNoPlanesDetected=-1)),o!==void 0&&this.processFrameData(t.xr,i.gameObject,n,o,this._allPlanes),r!==void 0&&this.processFrameData(t.xr,i.gameObject,n,r,this._allMeshes),ra){const h=this.context.mainCameraComponent.gameObject.worldPosition;for(const d of this._allPlanes.values())!d.mesh||!d.mesh.visible||(this.bounds.makeEmpty(),d.mesh.traverse(u=>{u instanceof Y&&this.bounds.expandByObject(u)}),this.bounds.getCenter(this.center),this.labelOffset.copy(h).sub(this.center).normalize().multiplyScalar(.1),q.DrawLabel(this.center.add(this.labelOffset),(d.xrData.semanticLabel||"plane").toUpperCase()+`
1380
- `+d.xrData.lastChangedTime.toFixed(2),.02))}}removeData(t,i){const n=i.get(t);if(!n)return;i.delete(t),ra&&console.log("Plane no longer tracked, id="+n.id),n.mesh&&(n.mesh.removeFromParent(),n.mesh.traverse(r=>{const l=r.userData.normalsHelper;l?(l.dispose(),l.removeFromParent()):ra&&console.warn("No normals helper found for mesh",n.mesh)}),Ri(n.mesh,!0,!0));const o=new CustomEvent("plane-tracking",{detail:{type:"plane-removed",context:n}});this.dispatchEvent(o)}processFrameData(t,i,n,o,r){const l=this.context.renderer.xr.getReferenceSpace();if(l){for(const c of r.keys())o.has(c)||this.removeData(c,r);for(const c of o){const h="planeSpace"in c?c.planeSpace:"meshSpace"in c?c.meshSpace:void 0;if(!h)continue;const d=n.getPose(h,l);let u;if(r.has(c)){const p=r.get(c);if(u=p.mesh,p.timestamp<c.lastChangedTime){if(p.timestamp=c.lastChangedTime,p.mesh){const y=this.createGeometry(c);if(p.mesh instanceof Y)p.mesh.geometry.dispose(),p.mesh.geometry=y,this.makeOccluder(p.mesh,p.mesh.material);else if(p.mesh instanceof oo)for(const f of p.mesh.children)f instanceof Y&&(f.geometry.dispose(),f.geometry=y,this.makeOccluder(f,f.material));if(p.collider){const f=p.mesh;p.collider.sharedMesh=f,p.collider.convex=this.checkIfContextShouldBeConvex(f,p.xrData),p.collider.onDisable(),p.collider.onEnable()}ra&&(console.log("Plane updated, id="+p.id,p),p.mesh.traverse(f=>{if(!(f instanceof Y))return;const v=f.userData.normalsHelper;v&&v.update()}))}const g=new CustomEvent("plane-tracking",{detail:{type:"plane-updated",context:p}});this.dispatchEvent(g)}}else{if(!this.dataTemplate){const p=new Y;ra?p.material=new RC:this.occluder?(p.material=new Re,this.makeOccluder(p,p.material,!0)):p.material=new Re({wireframe:!0,opacity:.5,transparent:!0,color:3355443}),this.dataTemplate=new le("","",p)}if(!this.dataTemplate.asset)this.dataTemplate.loadAssetAsync();else{const p=O.instantiate(this.dataTemplate.asset);if(p.name="xr-tracked-plane",u=p,Hm(p,!1),p instanceof Y)Ee(p.geometry),p.geometry=this.createGeometry(c),this.makeOccluder(p,p.material,this.occluder&&!this.dataTemplate);else if(p instanceof oo)for(const f of p.children)f instanceof Y&&(Ee(f.geometry),f.geometry=this.createGeometry(c),this.makeOccluder(f,f.material,this.occluder&&!this.dataTemplate));const g=p.getComponent(Ro);if(g){const f=p;g.sharedMesh=f,g.convex=this.checkIfContextShouldBeConvex(f,c),g.onDisable(),g.onEnable()}p.matrixAutoUpdate=!1,p.matrixWorldNeedsUpdate=!0,i.add(p);const y={id:this._dataId++,xrData:c,timestamp:c.lastChangedTime,mesh:p,collider:g};r.set(c,y),ra&&console.log("New plane detected, id="+y.id,y,{hasCollider:!!g,isGroup:p instanceof oo});try{const f=new CustomEvent("plane-tracking",{detail:{type:"plane-added",context:y}});this.dispatchEvent(f)}catch(f){console.error(f)}}}u&&(d?(u.visible=!0,u.matrix.fromArray(d.transform.matrix),u.matrix.premultiply(this._flipForwardMatrix)):u.visible=!1,ra&&u.traverse(p=>{if(p instanceof Y)if(p.userData.normalsHelper)p.userData.normalsHelper.update();else{const g=new JC(p,.05,255);g.layers.disableAll(),g.layers.set(2),this.context.scene.add(g),p.userData.normalsHelper=g}}))}}}checkIfContextShouldBeConvex(t,i){if(!t)return!0;if(t){const n=new wi;n.expandByObject(t);const o=new x;n.getSize(o);let r=!0;return o.x>2&&o.y>2&&o.z>1.5&&(r=!1),r&&"semanticLabel"in i&&i.semanticLabel==="wall"&&(r=!0),r}return!0}createGeometry(t){return"polygon"in t?this.createPlaneGeometry(t.polygon):"vertices"in t&&"indices"in t?this.createMeshGeometry(t.vertices,t.indices):new gn}createMeshGeometry(t,i){const n=t.toString()+"_"+i.toString();if(this._verticesCache.has(n))return this._verticesCache.get(n);const o=new gn;o.setIndex(new ft(i,1)),o.setAttribute("position",new ft(t,3));const r=Array();for(let l=0;l<t.length;l+=3)r.push(t[l],t[l+2]);return o.setAttribute("uv",new ft(t,3)),o.computeVertexNormals(),this._verticesCache.set(n,o),o}createPlaneGeometry(t){const i=new gn,n=[],o=[];t.forEach(g=>{n.push(g.x,g.y,g.z),o.push(g.x,g.z)});const r=new x(n[0],n[1],n[2]),l=new x(n[3],n[4],n[5]),c=new x(n[6],n[7],n[8]),h=new x,d=new x;h.subVectors(l,r),d.subVectors(c,r),h.cross(d),h.normalize();const u=[];for(let g=0;g<n.length/3;g++)u.push(h.x,h.y,h.z);const p=[];for(let g=2;g<t.length;++g)p.push(0,g-1,g);return i.setAttribute("position",new ft(new Float32Array(n),3)),i.setAttribute("uv",new ft(new Float32Array(o),2)),i.setAttribute("normal",new ft(new Float32Array(u),3)),i.setIndex(p),i.computeBoundingBox(),i.computeBoundingSphere(),i}}Fl([m(le)],Jn.prototype,"dataTemplate",2),Fl([m()],Jn.prototype,"occluder",2),Fl([m()],Jn.prototype,"initiateRoomCaptureIfNoData",2),Fl([m()],Jn.prototype,"usePlaneData",2),Fl([m()],Jn.prototype,"useMeshData",2),Fl([m()],Jn.prototype,"runInVR",2);var yj=Object.defineProperty,vj=Object.getOwnPropertyDescriptor,bj=(s,t,i,n)=>{for(var o=n>1?void 0:n?vj(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&yj(t,i,o),o};const W1=C("debugwebxr");class Yp extends A{constructor(){super(...arguments),a(this,"priority",0),a(this,"_startScale")}get isActive(){return this.activeAndEnabled&&this.gameObject.visible}setAsActiveXRRig(){var t;(t=J.active)==null||t.setRigActive(this)}setPriority(t){this.priority=t}awake(){if(W1){const t=new I;t.position.y+=.5,this.gameObject.add(t);const i=t.addNewComponent($r);i&&(i.isGizmo=!1);const n=new xi(.5);this.gameObject.add(n)}}isXRRig(){return!0}supportsXR(t){return!0}onEnterXR(t){this._startScale=this.gameObject.scale.clone(),t.xr.addRig(this),W1&&console.log("WebXR: add Rig",this.name,this.priority)}onLeaveXR(t){t.xr.removeRig(this),this._startScale&&this.gameObject&&this.gameObject.scale.copy(this._startScale)}}bj([m()],Yp.prototype,"priority",2);class _j extends A{constructor(){super(...arguments),a(this,"toggleKey","KeyP")}update(){this.context.input.isKeyDown(this.toggleKey)&&this.context.domElement.classList.toggle("presentation-mode")}}k.add("AlignmentConstraint",Lc),k.add("Animation",zt),k.add("Animator",Pt),k.add("AudioListener",Tn),k.add("AudioSource",Ne),k.add("Avatar_Brain_LookAt",Hc),k.add("Avatar_MouthShapes",Gc),k.add("Avatar_MustacheShake",wf),k.add("AvatarBlink_Simple",Tr),k.add("AvatarEyeLook_Rotation",Ga),k.add("AxesHelper",Xa),k.add("BasicIKConstraint",Of),k.add("BoxHelperComponent",Ji),k.add("Camera",Oe),k.add("CharacterController",Er),k.add("CharacterControllerInput",Ln),k.add("Collider",di),k.add("SphereCollider",Qa),k.add("BoxCollider",Ya),k.add("MeshCollider",Ro),k.add("CapsuleCollider",In),k.add("ContactShadows",Ps),k.add("LogStats",Mf),k.add("DeleteBox",Kc),k.add("Deletable",Tf),k.add("DeviceFlag",Lu),k.add("DragControls",ui),k.add("DropListener",Dn),k.add("Duplicatable",Ja),k.add("EventListEvent",Cu),k.add("EventTrigger",Bu),k.add("GltfExportBox",qf),k.add("GltfExport",ih),k.add("VariantAction",s0),k.add("ChangeTransformOnClick",Dr),k.add("ChangeMaterialOnClick",pl),k.add("SetActiveOnClick",Br),k.add("HideOnStart",gl),k.add("EmphasizeOnClick",fl),k.add("PlayAudioOnClick",Io),k.add("PlayAnimationOnClick",Fr),k.add("PreliminaryAction",yl),k.add("PreliminaryTrigger",oh),k.add("VisibilityAction",rh),k.add("TapGestureTrigger",o0),k.add("USDZExporter",$e),k.add("Fog",Sl),k.add("BoxGizmo",$r),k.add("GridHelper",Cl),k.add("GroundProjectedEnv",Hs),k.add("UsageMarker",Zc),k.add("Interactable",Rf),k.add("FixedJoint",L0),k.add("HingeJoint",vh),k.add("Light",gi),k.add("LODGroup",_h),k.add("LookAtConstraint",Mr),k.add("NeedleMenu",nn),k.add("NestedGltf",fp),k.add("Networking",Pl),k.add("OffsetConstraint",qr),k.add("CameraTargetReachedEvent",Wc),k.add("OrbitControls",be),k.add("ParticleSystemRenderer",ss),k.add("ParticleSystem",lt),k.add("PlayerColor",Wl),k.add("Antialiasing",Oh),k.add("BloomEffect",Zr),k.add("ChromaticAberration",Ph),k.add("ColorAdjustments",qo),k.add("DepthOfField",As),k.add("EffectWrapper",kh),k.add("PixelationEffect",Mh),k.add("ScreenSpaceAmbientOcclusion",qn),k.add("ScreenSpaceAmbientOcclusionN8",Is),k.add("SharpeningEffect",Th),k.add("TiltShiftEffect",ln),k.add("ToneMappingEffect",$o),k.add("Vignette",ea),k.add("Volume",Al),k.add("ReflectionProbe",sl),k.add("Renderer",Ze),k.add("MeshRenderer",th),k.add("SkinnedMeshRenderer",$f),k.add("Rigidbody",ye),k.add("SceneSwitcher",ot),k.add("ScreenCapture",Xo),k.add("ShadowCatcher",Ah),k.add("RemoteSkybox",cn),k.add("SmoothFollow",Qo),k.add("SpatialTriggerReceiver",hn),k.add("SpatialTrigger",Dh),k.add("SpectatorCamera",Fp),k.add("SpriteRenderer",mi),k.add("SyncedCamera",Up),k.add("SyncedRoom",js),k.add("SyncedTransform",qs),k.add("TestRunner",uy),k.add("TestSimulateUserData",py),k.add("PlayableDirector",Zo),k.add("SignalReceiver",Il),k.add("AnimationTrackHandler",Vp),k.add("AudioTrackHandler",Uh),k.add("SignalTrackHandler",Nh),k.add("ControlTrackHandler",Hp),k.add("TransformGizmo",ta),k.add("BaseUIComponent",rs),k.add("UIRootComponent",Nc),k.add("Button",Yn),k.add("Canvas",Et),k.add("CanvasGroup",Uo),k.add("EventSystem",si),k.add("Graphic",Ur),k.add("MaskableGraphic",fh),k.add("Image",jl),k.add("RawImage",Gp),k.add("InputField",sa),k.add("VerticalLayoutGroup",S0),k.add("HorizontalLayoutGroup",C0),k.add("GridLayoutGroup",O0),k.add("Outline",xl),k.add("ObjectRaycaster",Ei),k.add("GraphicRaycaster",ku),k.add("SpatialGrabRaycaster",Va),k.add("RectTransform",Wt),k.add("SpatialHtml",Wh),k.add("Text",Vt),k.add("LookAt",na),k.add("OpenURL",Dl),k.add("VideoPlayer",gt),k.add("Voip",Mo),k.add("Avatar",Do),k.add("XRControllerFollow",Zn),k.add("XRControllerModel",on),k.add("XRControllerMovement",ji),k.add("TeleportTarget",cp),k.add("WebARCameraBackground",$h),k.add("WebARSessionRoot",sn),k.add("WebXR",Je),k.add("AvatarMarker",Mt),k.add("WebXRImageTracking",oa),k.add("WebXRPlaneTracking",Jn),k.add("XRRig",Yp),k.add("XRFlag",Ai),k.add("PlayerSync",bl),k.add("PlayerState",Ii),k.add("PresentationMode",_j);const Xh=vt,wj=C("debugtypestore");wj&&console.log(k);function xj(s,t){const i=y_(s,t);return i!==void 0?i:null}const Sj=new L2,Cy=Symbol("deserialize-queue");async function Cj(s,t,i,n=null,o){if(!i){console.debug("Can not create component instances: gltf is null");return}let r=n;typeof r=="number"&&(r=new Dt(n));const l=t.indexOf("?");t=l===-1?t:t.substring(0,l);const c=new Bg(i.scene);c.gltfId=t,c.context=s,c.gltf=i,c.nodeToObject=o?.nodeToObjectMap,c.implementationInformation=Sj;let h=s[Cy];if(h||(h=s[Cy]=[]),i.scenes)for(const d of i.scenes)await ky(c,d,h);if(i.children)for(const d of i.children)await ky(c,d,h);s.new_scripts_pre_setup_callbacks.push(()=>{const d=s[Cy];if(d){for(const u of d)Oj(u,c);d.length=0}if(r){const u={},p=[];Py(i,r,u,p);for(const g of i.scenes)Py(g,r,u,p);for(const g of p)g.resolveGuids(u)}})}const Oy=Symbol("original-component-name"),zl=new Map;function Py(s,t,i,n){if(t===null||!s)return;const o=s.guid,r=s.guid;r!=null&&r.length&&(zl.has(r)||(Xh&&console.log('Creating InstanceIdProvider with key "'+r+'" for object '+s.name),zl.set(r,new Dt(r))));const l=r&&zl.get(r)||t;if(s.guid=l.generateUUID(),o&&o!=="invalid"&&(i[o]=s.guid),s&&s.userData&&s.userData.components)for(const c of s.userData.components){if(c===null)continue;const h=c.guid;h?zl.has(h)||(Xh&&console.log('Creating InstanceIdProvider with key "'+h+'" for component '+c[Oy]),zl.set(h,new Dt(h))):Xh&&console.warn("Can not create IdProvider: component "+c[Oy]+" has no guid",c.guid);const d=zl.get(h)||t,u=c.guid;c.guid=d.generateUUID(),u&&u!=="invalid"&&(i[u]=c.guid),c.resolveGuids&&n.push(c)}if(s.children)for(const c of s.children)Py(c,t,i,n)}const Qh=[];async function ky(s,t,i,n){var o,r,l,c,h;if(!t)return;const d=t.userData;if(d){const u=d.builtin_components;if(u&&u.length>0)for(const p of u)try{if(p===null)continue;const g=k.get(p.name);if(g!=null){const y=new g;y.sourceId=s.gltfId,Ea(y,p,s.implementationInformation),y.context=s.context,"guid"in p&&(y[hc]=p.guid),y[Oy]=p.name,fr(t,y,!1),i.push({instance:y,compData:p,obj:t}),y.isCamera&&s.context&&s.context.mainCamera===null&&y.tag==="MainCamera"&&s.context.setCurrentCamera(y),((l=(r=(o=s.context)==null?void 0:o.physics)==null?void 0:r.engine)==null?void 0:l.isInitialized)===!1&&(y.isCollider||y.isRigidbody)&&((h=(c=s.context)==null?void 0:c.physics.engine)==null||h.initialize())}else Xh&&console.debug("unknown component: "+p.name),Qh.includes(p.name)||Qh.push(p.name)}catch(g){console.error(p.name+" - "+g.message,g)}if(Qh.length>0){const p=Qh.join(", ");console.warn("unknown components: "+p),Qh.length=0,Gt()&&De(`<strong>Unknown components in scene</strong>:
1383
+ `;var pj=Object.defineProperty,mj=Object.getOwnPropertyDescriptor,er=(s,t,i,n)=>{for(var o=n>1?void 0:n?mj(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&pj(t,i,o),o};const N1=C("debugimagetracking"),xy=class{constructor(s,t,i,n,o,r){a(this,"measuredSize"),a(this,"state"),a(this,"_position"),a(this,"_rotation"),a(this,"_trackingComponent"),a(this,"_trackedImage"),a(this,"_bitmap"),a(this,"_pose"),this._trackingComponent=s,this._trackedImage=t,this._bitmap=i,this.measuredSize=n,this.state=o,this._pose=r}get url(){return this._trackedImage.image??""}get widthInMeters(){return this._trackedImage.widthInMeters??void 0}get bitmap(){return this._bitmap}get model(){return this._trackedImage}getPosition(s){return this.ensureTransformData(),s.copy(this._position),s}getQuaternion(s){return this.ensureTransformData(),s.copy(this._rotation),s}applyToObject(s,t=void 0){this.ensureTransformData();const i=s.position.distanceToSquared(this._position)/.05+s.quaternion.angleTo(this._rotation)/.05;t&&(t*=Math.max(1,i)),t===void 0||t>=1?(s.position.copy(this._position),s.quaternion.copy(this._rotation)):(t=Math.max(0,Math.min(1,t)),s.position.lerp(this._position,t),s.quaternion.slerp(this._rotation,t))}ensureTransformData(){if(!this._position){this._position=xy._positionBuffer.get(),this._rotation=xy._rotationBuffer.get();const s=this._pose.transform,t=J.active.convertSpace(s);this._position.copy(t?.position),this._rotation.copy(t?.quaternion)}}};let qh=xy;a(qh,"_positionBuffer",new Ci(()=>new x,20)),a(qh,"_rotationBuffer",new Ci(()=>new V,20));class Kn{constructor(){a(this,"image"),a(this,"widthInMeters",.25),a(this,"object"),a(this,"createObjectInstance",!1),a(this,"imageDoesNotMove",!1),a(this,"hideWhenTrackingIsLost",!0)}}er([m(URL)],Kn.prototype,"image",2),er([m()],Kn.prototype,"widthInMeters",2),er([m(le)],Kn.prototype,"object",2),er([m()],Kn.prototype,"createObjectInstance",2),er([m()],Kn.prototype,"imageDoesNotMove",2),er([m()],Kn.prototype,"hideWhenTrackingIsLost",2);class gj{constructor(t,i,n){a(this,"filename"),a(this,"widthInMeters"),a(this,"imageData"),this.filename=t,this.imageData=i,this.widthInMeters=n}get extensionName(){return"image-tracking"}onAfterHierarchy(t,i){const n=X.getiOSVersion(),o=(n?parseInt(n.split(".")[0]):18)>=18?1:100;i.beginBlock('def Preliminary_ReferenceImage "AnchoringReferenceImage"'),i.appendLine("uniform asset image = @image_tracking/"+this.filename+"@"),i.appendLine("uniform double physicalWidth = "+(this.widthInMeters*o).toFixed(8)),i.closeBlock()}onBeforeBuildDocument(t){const i=O.findObjectOfType(oa);!i||!i.trackedImages||i.trackedImages.length>1&&(F()&&we("USDZ: Only one tracked image is supported."),console.warn("USDZ: Only one tracked image is supported."))}onAfterSerialize(t){t.files["image_tracking/"+this.filename]=this.imageData}onExportObject(t,i,n){var o;const r=O.findObjectOfType(oa);if(!(!r||!r.trackedImages)){for(const l of r.trackedImages)if(((o=l.object)==null?void 0:o.asset)===t){const c=O.findObjectOfType($e);if(!c)continue;const{scale:h,target:d}=c.getARScaleAndTarget();let u=t;const p=new ne;if(t!==d)for(;u.parent&&u.parent!==d;)u=u.parent,p.premultiply(u.matrix);const g=p.clone().invert();i.setMatrix(g.scale(new x(h,h,h)));break}}}}var Sy;const Gh=(Sy=class extends A{constructor(){super(...arguments),a(this,"trackedImages"),a(this,"smooth",!0),a(this,"trackedImageIndexMap",new Map),a(this,"_supported",!0),a(this,"imageToObjectMap",new Map),a(this,"currentImages",[]),a(this,"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.`),a(this,"onImageTrackingUpdate",s=>{const t=J.active;if(t)for(const i of s){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(l=>{if(n.createObjectInstance&&l&&(l=O.instantiate(l)),l){r.object=l;for(const c of l.getComponentsInChildren(Ze))c.setInstancingEnabled(!1);t.rig?(t.rig.gameObject.add(l),i.applyToObject(l),l.activeSelf||O.setActive(l,!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||O.setActive(r.object,!0))}}})}get supported(){return this._supported}awake(){if(N1&&console.log(this),!!this.trackedImages){for(const s of this.trackedImages)if(s.image&&!Gh._imageElements.has(s.image)){const t=s.image;Gh._imageElements.set(t,null);const i=document.createElement("img");i.src=t,i.addEventListener("load",async()=>{const n=await createImageBitmap(i);Gh._imageElements.set(t,n);const o=await kx(n);if(o){const r=await(await o.convertToBlob({type:"image/png"})).arrayBuffer(),l=O.findObjectOfType($e);l&&this.trackedImages&&(l.extensions.push(new gj("marker.png",new Uint8Array(r),this.trackedImages[0].widthInMeters)),l.anchoringType="image")}})}}}onBeforeXR(s,t){var i;if(this.trackedImages){t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.includes("image-tracking")||t.optionalFeatures.push("image-tracking"),t.trackedImages=[];for(const n of this.trackedImages)if((i=n.image)!=null&&i.length&&n.widthInMeters>0){const o=Gh._imageElements.get(n.image);o&&(this.trackedImageIndexMap.set(t.trackedImages.length,n),t.trackedImages.push({image:o,widthInMeters:n.widthInMeters}))}}}onEnterXR(s){var t;if(this.trackedImages){for(const i of this.trackedImages)if((t=i.object)!=null&&t.asset){const n=i.object.asset;n.userData||(n.userData={});const o={visible:n.visible,parent:n.parent,matrix:n.matrix.clone()};n.userData["image-tracking"]=o}}for(const i of this.imageToObjectMap.values())i.frames=0}onLeaveXR(s){var t,i;if(!this.supported&&X.isAndroidDevice()&&we(this.webXRIncubationsWarning),this.trackedImages){for(const n of this.trackedImages)if((t=n.object)!=null&&t.asset){const o=n.object.asset;if(o.userData){const r=o.userData["image-tracking"];r&&(o.visible=r.visible,(i=r.parent)==null||i.add(o),o.matrix.copy(r.matrix),o.matrix.decompose(o.position,o.quaternion,o.scale)),delete o.userData["image-tracking"]}}}}onUpdateXR(s){var t;this.currentImages.length=0;const i=s.xr.frame;if(!i)return;if("getImageTrackingResults"in i){if(((t=s.xr.session.enabledFeatures)==null?void 0:t.includes("image-tracking"))===!1)return;if(i.session&&typeof i.getImageTrackingResults=="function"){const o=i.getImageTrackingResults();if(o.length>0){const r=this.context.renderer.xr.getReferenceSpace();if(r){for(const l of o){const c=l.trackingState,h=l.index,d=this.trackedImageIndexMap.get(h);if(d){const u=i.getPose(l.imageSpace,r),p=new qh(this,d,l.image,l.measuredSize,c,u);this.currentImages.push(p)}else N1&&console.warn("No tracked image for index",h)}if(this.currentImages.length>0)try{this.dispatchEvent(new CustomEvent("image-tracking",{detail:this.currentImages})),this.onImageTrackingUpdate(this.currentImages)}catch(l){console.error(l)}}}}}else{this.didPrintWarning||(this.didPrintWarning=!0,console.log(this.webXRIncubationsWarning)),this._supported=!1,we(this.webXRIncubationsWarning);return}const n=1e3;for(const[o,r]of this.imageToObjectMap){if(!r.object||!o||o.hideWhenTrackingIsLost===!1)continue;let l=!1;for(const c of this.currentImages)if(c.model===o){const h=Date.now()-r.lastTrackingTime;if(o.imageDoesNotMove||c.state==="tracked"||h<=n){l=!0;break}}l||O.setActive(r.object,!1)}}},a(Sy,"_imageElements",new Map),Sy);let oa=Gh;er([m(Kn)],oa.prototype,"trackedImages",2),er([m()],oa.prototype,"smooth",2);var fj=Object.defineProperty,yj=Object.getOwnPropertyDescriptor,Fl=(s,t,i,n)=>{for(var o=n>1?void 0:n?yj(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&fj(t,i,o),o};const ra=C("debugplanetracking");class Jn extends A{constructor(){super(...arguments),a(this,"dataTemplate"),a(this,"occluder",!0),a(this,"initiateRoomCaptureIfNoData",!0),a(this,"usePlaneData",!0),a(this,"useMeshData",!0),a(this,"runInVR",!0),a(this,"bounds",new wi),a(this,"center",new x),a(this,"labelOffset",new x),a(this,"_dataId",1),a(this,"_allPlanes",new Map),a(this,"_allMeshes",new Map),a(this,"firstTimeNoPlanesDetected",-100),a(this,"makeOccluder",(t,i,n=!1)=>{if(i){if(i instanceof Array){for(const o of i)this.makeOccluder(t,o,n);return}!n&&!i.name.toLowerCase().includes("occlu")||(i.colorWrite=!1,i.depthTest=!0,i.depthWrite=!0,i.transparent=!1,i.polygonOffset=!0,i.polygonOffsetFactor=1,i.polygonOffsetUnits=.1,t.renderOrder=-1e3)}}),a(this,"_flipForwardMatrix",new ne().makeRotationY(Math.PI)),a(this,"_verticesCache",new Map)}get trackedPlanes(){return this._allPlanes.values()}get trackedMeshes(){return this._allMeshes.values()}onBeforeXR(t,i){t==="immersive-vr"&&!this.runInVR||(i.optionalFeatures=i.optionalFeatures||[],this.usePlaneData&&!i.optionalFeatures.includes("plane-detection")&&i.optionalFeatures.push("plane-detection"),this.useMeshData&&!i.optionalFeatures.includes("mesh-detection")&&i.optionalFeatures.push("mesh-detection"))}onEnterXR(t){for(const i of this._allPlanes.keys())this.removeData(i,this._allPlanes);for(const i of this._allMeshes.keys())this.removeData(i,this._allMeshes)}onLeaveXR(t){for(const i of this._allPlanes.keys())this.removeData(i,this._allPlanes);for(const i of this._allMeshes.keys())this.removeData(i,this._allMeshes)}onUpdateXR(t){if(!this.runInVR&&t.xr.isVR)return;const i=t.xr.rig;if(!i){console.warn("No XR rig found, cannot parent tracked planes to it");return}const n=t.xr.frame;if(!this.context.renderer.xr.getReferenceSpace())return;const o=n.detectedPlanes,r=n.detectedMeshes,l=o!==void 0&&o.size>0,c=r!==void 0&&r.size>0;if(this.initiateRoomCaptureIfNoData&&(!l&&!c&&this.firstTimeNoPlanesDetected<-10&&(this.firstTimeNoPlanesDetected=Date.now()),(l||c)&&(this.firstTimeNoPlanesDetected=-1),this.firstTimeNoPlanesDetected>0&&Date.now()-this.firstTimeNoPlanesDetected>2500&&"initiateRoomCapture"in n.session&&(n.session.initiateRoomCapture(),this.firstTimeNoPlanesDetected=-1)),o!==void 0&&this.processFrameData(t.xr,i.gameObject,n,o,this._allPlanes),r!==void 0&&this.processFrameData(t.xr,i.gameObject,n,r,this._allMeshes),ra){const h=this.context.mainCameraComponent.gameObject.worldPosition;for(const d of this._allPlanes.values())!d.mesh||!d.mesh.visible||(this.bounds.makeEmpty(),d.mesh.traverse(u=>{u instanceof Y&&this.bounds.expandByObject(u)}),this.bounds.getCenter(this.center),this.labelOffset.copy(h).sub(this.center).normalize().multiplyScalar(.1),q.DrawLabel(this.center.add(this.labelOffset),(d.xrData.semanticLabel||"plane").toUpperCase()+`
1384
+ `+d.xrData.lastChangedTime.toFixed(2),.02))}}removeData(t,i){const n=i.get(t);if(!n)return;i.delete(t),ra&&console.log("Plane no longer tracked, id="+n.id),n.mesh&&(n.mesh.removeFromParent(),n.mesh.traverse(r=>{const l=r.userData.normalsHelper;l?(l.dispose(),l.removeFromParent()):ra&&console.warn("No normals helper found for mesh",n.mesh)}),Ri(n.mesh,!0,!0));const o=new CustomEvent("plane-tracking",{detail:{type:"plane-removed",context:n}});this.dispatchEvent(o)}processFrameData(t,i,n,o,r){const l=this.context.renderer.xr.getReferenceSpace();if(l){for(const c of r.keys())o.has(c)||this.removeData(c,r);for(const c of o){const h="planeSpace"in c?c.planeSpace:"meshSpace"in c?c.meshSpace:void 0;if(!h)continue;const d=n.getPose(h,l);let u;if(r.has(c)){const p=r.get(c);if(u=p.mesh,p.timestamp<c.lastChangedTime){if(p.timestamp=c.lastChangedTime,p.mesh){const y=this.createGeometry(c);if(p.mesh instanceof Y)p.mesh.geometry.dispose(),p.mesh.geometry=y,this.makeOccluder(p.mesh,p.mesh.material);else if(p.mesh instanceof oo)for(const f of p.mesh.children)f instanceof Y&&(f.geometry.dispose(),f.geometry=y,this.makeOccluder(f,f.material));if(p.collider){const f=p.mesh;p.collider.sharedMesh=f,p.collider.convex=this.checkIfContextShouldBeConvex(f,p.xrData),p.collider.onDisable(),p.collider.onEnable()}ra&&(console.log("Plane updated, id="+p.id,p),p.mesh.traverse(f=>{if(!(f instanceof Y))return;const v=f.userData.normalsHelper;v&&v.update()}))}const g=new CustomEvent("plane-tracking",{detail:{type:"plane-updated",context:p}});this.dispatchEvent(g)}}else{if(!this.dataTemplate){const p=new Y;ra?p.material=new RC:this.occluder?(p.material=new Re,this.makeOccluder(p,p.material,!0)):p.material=new Re({wireframe:!0,opacity:.5,transparent:!0,color:3355443}),this.dataTemplate=new le("","",p)}if(!this.dataTemplate.asset)this.dataTemplate.loadAssetAsync();else{const p=O.instantiate(this.dataTemplate.asset);if(p.name="xr-tracked-plane",u=p,Hm(p,!1),p instanceof Y)Ee(p.geometry),p.geometry=this.createGeometry(c),this.makeOccluder(p,p.material,this.occluder&&!this.dataTemplate);else if(p instanceof oo)for(const f of p.children)f instanceof Y&&(Ee(f.geometry),f.geometry=this.createGeometry(c),this.makeOccluder(f,f.material,this.occluder&&!this.dataTemplate));const g=p.getComponent(Ro);if(g){const f=p;g.sharedMesh=f,g.convex=this.checkIfContextShouldBeConvex(f,c),g.onDisable(),g.onEnable()}p.matrixAutoUpdate=!1,p.matrixWorldNeedsUpdate=!0,i.add(p);const y={id:this._dataId++,xrData:c,timestamp:c.lastChangedTime,mesh:p,collider:g};r.set(c,y),ra&&console.log("New plane detected, id="+y.id,y,{hasCollider:!!g,isGroup:p instanceof oo});try{const f=new CustomEvent("plane-tracking",{detail:{type:"plane-added",context:y}});this.dispatchEvent(f)}catch(f){console.error(f)}}}u&&(d?(u.visible=!0,u.matrix.fromArray(d.transform.matrix),u.matrix.premultiply(this._flipForwardMatrix)):u.visible=!1,ra&&u.traverse(p=>{if(p instanceof Y)if(p.userData.normalsHelper)p.userData.normalsHelper.update();else{const g=new JC(p,.05,255);g.layers.disableAll(),g.layers.set(2),this.context.scene.add(g),p.userData.normalsHelper=g}}))}}}checkIfContextShouldBeConvex(t,i){if(!t)return!0;if(t){const n=new wi;n.expandByObject(t);const o=new x;n.getSize(o);let r=!0;return o.x>2&&o.y>2&&o.z>1.5&&(r=!1),r&&"semanticLabel"in i&&i.semanticLabel==="wall"&&(r=!0),r}return!0}createGeometry(t){return"polygon"in t?this.createPlaneGeometry(t.polygon):"vertices"in t&&"indices"in t?this.createMeshGeometry(t.vertices,t.indices):new gn}createMeshGeometry(t,i){const n=t.toString()+"_"+i.toString();if(this._verticesCache.has(n))return this._verticesCache.get(n);const o=new gn;o.setIndex(new ft(i,1)),o.setAttribute("position",new ft(t,3));const r=Array();for(let l=0;l<t.length;l+=3)r.push(t[l],t[l+2]);return o.setAttribute("uv",new ft(t,3)),o.computeVertexNormals(),this._verticesCache.set(n,o),o}createPlaneGeometry(t){const i=new gn,n=[],o=[];t.forEach(g=>{n.push(g.x,g.y,g.z),o.push(g.x,g.z)});const r=new x(n[0],n[1],n[2]),l=new x(n[3],n[4],n[5]),c=new x(n[6],n[7],n[8]),h=new x,d=new x;h.subVectors(l,r),d.subVectors(c,r),h.cross(d),h.normalize();const u=[];for(let g=0;g<n.length/3;g++)u.push(h.x,h.y,h.z);const p=[];for(let g=2;g<t.length;++g)p.push(0,g-1,g);return i.setAttribute("position",new ft(new Float32Array(n),3)),i.setAttribute("uv",new ft(new Float32Array(o),2)),i.setAttribute("normal",new ft(new Float32Array(u),3)),i.setIndex(p),i.computeBoundingBox(),i.computeBoundingSphere(),i}}Fl([m(le)],Jn.prototype,"dataTemplate",2),Fl([m()],Jn.prototype,"occluder",2),Fl([m()],Jn.prototype,"initiateRoomCaptureIfNoData",2),Fl([m()],Jn.prototype,"usePlaneData",2),Fl([m()],Jn.prototype,"useMeshData",2),Fl([m()],Jn.prototype,"runInVR",2);var vj=Object.defineProperty,bj=Object.getOwnPropertyDescriptor,_j=(s,t,i,n)=>{for(var o=n>1?void 0:n?bj(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&vj(t,i,o),o};const W1=C("debugwebxr");class Yp extends A{constructor(){super(...arguments),a(this,"priority",0),a(this,"_startScale")}get isActive(){return this.activeAndEnabled&&this.gameObject.visible}setAsActiveXRRig(){var t;(t=J.active)==null||t.setRigActive(this)}setPriority(t){this.priority=t}awake(){if(W1){const t=new I;t.position.y+=.5,this.gameObject.add(t);const i=t.addNewComponent($r);i&&(i.isGizmo=!1);const n=new xi(.5);this.gameObject.add(n)}}isXRRig(){return!0}supportsXR(t){return!0}onEnterXR(t){this._startScale=this.gameObject.scale.clone(),t.xr.addRig(this),W1&&console.log("WebXR: add Rig",this.name,this.priority)}onLeaveXR(t){t.xr.removeRig(this),this._startScale&&this.gameObject&&this.gameObject.scale.copy(this._startScale)}}_j([m()],Yp.prototype,"priority",2);class wj extends A{constructor(){super(...arguments),a(this,"toggleKey","KeyP")}update(){this.context.input.isKeyDown(this.toggleKey)&&this.context.domElement.classList.toggle("presentation-mode")}}k.add("AlignmentConstraint",Lc),k.add("Animation",zt),k.add("Animator",Pt),k.add("AudioListener",Tn),k.add("AudioSource",Ne),k.add("Avatar_Brain_LookAt",Hc),k.add("Avatar_MouthShapes",Gc),k.add("Avatar_MustacheShake",wf),k.add("AvatarBlink_Simple",Tr),k.add("AvatarEyeLook_Rotation",Ga),k.add("AxesHelper",Xa),k.add("BasicIKConstraint",Of),k.add("BoxHelperComponent",Ji),k.add("Camera",Oe),k.add("CharacterController",Er),k.add("CharacterControllerInput",Ln),k.add("Collider",di),k.add("SphereCollider",Qa),k.add("BoxCollider",Ya),k.add("MeshCollider",Ro),k.add("CapsuleCollider",In),k.add("ContactShadows",Ps),k.add("LogStats",Mf),k.add("DeleteBox",Kc),k.add("Deletable",Tf),k.add("DeviceFlag",Lu),k.add("DragControls",ui),k.add("DropListener",Dn),k.add("Duplicatable",Ja),k.add("EventListEvent",Cu),k.add("EventTrigger",Bu),k.add("GltfExportBox",qf),k.add("GltfExport",ih),k.add("VariantAction",s0),k.add("ChangeTransformOnClick",Dr),k.add("ChangeMaterialOnClick",pl),k.add("SetActiveOnClick",Br),k.add("HideOnStart",gl),k.add("EmphasizeOnClick",fl),k.add("PlayAudioOnClick",Io),k.add("PlayAnimationOnClick",Fr),k.add("PreliminaryAction",yl),k.add("PreliminaryTrigger",oh),k.add("VisibilityAction",rh),k.add("TapGestureTrigger",o0),k.add("USDZExporter",$e),k.add("Fog",Sl),k.add("BoxGizmo",$r),k.add("GridHelper",Cl),k.add("GroundProjectedEnv",Hs),k.add("UsageMarker",Zc),k.add("Interactable",Rf),k.add("FixedJoint",L0),k.add("HingeJoint",vh),k.add("Light",gi),k.add("LODGroup",_h),k.add("LookAtConstraint",Mr),k.add("NeedleMenu",nn),k.add("NestedGltf",fp),k.add("Networking",Pl),k.add("OffsetConstraint",qr),k.add("CameraTargetReachedEvent",Wc),k.add("OrbitControls",be),k.add("ParticleSystemRenderer",ss),k.add("ParticleSystem",lt),k.add("PlayerColor",Wl),k.add("Antialiasing",Oh),k.add("BloomEffect",Zr),k.add("ChromaticAberration",Ph),k.add("ColorAdjustments",qo),k.add("DepthOfField",As),k.add("EffectWrapper",kh),k.add("PixelationEffect",Mh),k.add("ScreenSpaceAmbientOcclusion",qn),k.add("ScreenSpaceAmbientOcclusionN8",Is),k.add("SharpeningEffect",Th),k.add("TiltShiftEffect",ln),k.add("ToneMappingEffect",$o),k.add("Vignette",ea),k.add("Volume",Al),k.add("ReflectionProbe",sl),k.add("Renderer",Ze),k.add("MeshRenderer",th),k.add("SkinnedMeshRenderer",$f),k.add("Rigidbody",ye),k.add("SceneSwitcher",ot),k.add("ScreenCapture",Xo),k.add("ShadowCatcher",Ah),k.add("RemoteSkybox",cn),k.add("SmoothFollow",Qo),k.add("SpatialTriggerReceiver",hn),k.add("SpatialTrigger",Dh),k.add("SpectatorCamera",Fp),k.add("SpriteRenderer",mi),k.add("SyncedCamera",Up),k.add("SyncedRoom",js),k.add("SyncedTransform",qs),k.add("TestRunner",uy),k.add("TestSimulateUserData",py),k.add("PlayableDirector",Zo),k.add("SignalReceiver",Il),k.add("AnimationTrackHandler",Vp),k.add("AudioTrackHandler",Uh),k.add("SignalTrackHandler",Nh),k.add("ControlTrackHandler",Hp),k.add("TransformGizmo",ta),k.add("BaseUIComponent",rs),k.add("UIRootComponent",Nc),k.add("Button",Yn),k.add("Canvas",Et),k.add("CanvasGroup",Uo),k.add("EventSystem",si),k.add("Graphic",Ur),k.add("MaskableGraphic",fh),k.add("Image",jl),k.add("RawImage",Gp),k.add("InputField",sa),k.add("VerticalLayoutGroup",S0),k.add("HorizontalLayoutGroup",C0),k.add("GridLayoutGroup",O0),k.add("Outline",xl),k.add("ObjectRaycaster",Ei),k.add("GraphicRaycaster",ku),k.add("SpatialGrabRaycaster",Va),k.add("RectTransform",Wt),k.add("SpatialHtml",Wh),k.add("Text",Vt),k.add("LookAt",na),k.add("OpenURL",Dl),k.add("VideoPlayer",gt),k.add("Voip",Mo),k.add("Avatar",Do),k.add("XRControllerFollow",Zn),k.add("XRControllerModel",on),k.add("XRControllerMovement",ji),k.add("TeleportTarget",cp),k.add("WebARCameraBackground",$h),k.add("WebARSessionRoot",sn),k.add("WebXR",Je),k.add("AvatarMarker",Mt),k.add("WebXRImageTracking",oa),k.add("WebXRPlaneTracking",Jn),k.add("XRRig",Yp),k.add("XRFlag",Ai),k.add("PlayerSync",bl),k.add("PlayerState",Ii),k.add("PresentationMode",wj);const Xh=vt,xj=C("debugtypestore");xj&&console.log(k);function Sj(s,t){const i=y_(s,t);return i!==void 0?i:null}const Cj=new L2,Cy=Symbol("deserialize-queue");async function Oj(s,t,i,n=null,o){if(!i){console.debug("Can not create component instances: gltf is null");return}let r=n;typeof r=="number"&&(r=new Dt(n));const l=t.indexOf("?");t=l===-1?t:t.substring(0,l);const c=new Bg(i.scene);c.gltfId=t,c.context=s,c.gltf=i,c.nodeToObject=o?.nodeToObjectMap,c.implementationInformation=Cj;let h=s[Cy];if(h||(h=s[Cy]=[]),i.scenes)for(const d of i.scenes)await ky(c,d,h);if(i.children)for(const d of i.children)await ky(c,d,h);s.new_scripts_pre_setup_callbacks.push(()=>{const d=s[Cy];if(d){for(const u of d)Pj(u,c);d.length=0}if(r){const u={},p=[];Py(i,r,u,p);for(const g of i.scenes)Py(g,r,u,p);for(const g of p)g.resolveGuids(u)}})}const Oy=Symbol("original-component-name"),zl=new Map;function Py(s,t,i,n){if(t===null||!s)return;const o=s.guid,r=s.guid;r!=null&&r.length&&(zl.has(r)||(Xh&&console.log('Creating InstanceIdProvider with key "'+r+'" for object '+s.name),zl.set(r,new Dt(r))));const l=r&&zl.get(r)||t;if(s.guid=l.generateUUID(),o&&o!=="invalid"&&(i[o]=s.guid),s&&s.userData&&s.userData.components)for(const c of s.userData.components){if(c===null)continue;const h=c.guid;h?zl.has(h)||(Xh&&console.log('Creating InstanceIdProvider with key "'+h+'" for component '+c[Oy]),zl.set(h,new Dt(h))):Xh&&console.warn("Can not create IdProvider: component "+c[Oy]+" has no guid",c.guid);const d=zl.get(h)||t,u=c.guid;c.guid=d.generateUUID(),u&&u!=="invalid"&&(i[u]=c.guid),c.resolveGuids&&n.push(c)}if(s.children)for(const c of s.children)Py(c,t,i,n)}const Qh=[];async function ky(s,t,i,n){var o,r,l,c,h;if(!t)return;const d=t.userData;if(d){const u=d.builtin_components;if(u&&u.length>0)for(const p of u)try{if(p===null)continue;const g=k.get(p.name);if(g!=null){const y=new g;y.sourceId=s.gltfId,Ea(y,p,s.implementationInformation),y.context=s.context,"guid"in p&&(y[hc]=p.guid),y[Oy]=p.name,fr(t,y,!1),i.push({instance:y,compData:p,obj:t}),y.isCamera&&s.context&&s.context.mainCamera===null&&y.tag==="MainCamera"&&s.context.setCurrentCamera(y),((l=(r=(o=s.context)==null?void 0:o.physics)==null?void 0:r.engine)==null?void 0:l.isInitialized)===!1&&(y.isCollider||y.isRigidbody)&&((h=(c=s.context)==null?void 0:c.physics.engine)==null||h.initialize())}else Xh&&console.debug("unknown component: "+p.name),Qh.includes(p.name)||Qh.push(p.name)}catch(g){console.error(p.name+" - "+g.message,g)}if(Qh.length>0){const p=Qh.join(", ");console.warn("unknown components: "+p),Qh.length=0,Gt()&&De(`<strong>Unknown components in scene</strong>:
1381
1385
 
1382
1386
  ${p}
1383
1387
 
1384
1388
  This could mean you forgot to add a npmdef to your ExportInfo
1385
- <a href="https://engine.needle.tools/docs/project_structure.html#creating-and-installing-a-npmdef" target="_blank">documentation</a>`,Oi.Warn)}}if(t.children)for(const u of t.children)await ky(s,u,i)}function Oj(s,t){const{instance:i,compData:n,obj:o}=s;t.object=o,t.target=i,Vd(i,n,t),Xh&&console.debug("add "+n.name,n,i)}const Zp=C("debugfileformat");async function V1(s,t=!0){var i;if(t){const r=s,l=new URL(r,globalThis.location.origin);let c=null;const h=l.searchParams.get("filetype");switch(h&&(c=h.toUpperCase()),c!=null&&c.length||(c=(i=l.pathname.split(".").pop())==null?void 0:i.toUpperCase()),Zp&&console.debug("Use file extension to determine type: "+c),c){case"GLTF":return"gltf";case"VRM":return"vrm";case"GLB":return"glb";case"FBX":return"fbx";case"USD":return"usd";case"USDA":return"usda";case"USDZ":return"usdz";case"OBJ":return"obj"}}const n=new URL(s);n.searchParams.append("range","true");const o=await fetch(n,{method:"GET",headers:{range:"bytes=0-32"}}).catch(r=>null);if(o!=null&&o.ok){const r=await o.arrayBuffer(),l=H1(r,o);return Zp&&console.log("Determined file type from header: "+l),l}return"unknown"}function H1(s,t){if(s.byteLength<4)return"unknown";const i=new Uint8Array(s);if(Zp&&console.warn(`Trying to determine file type from binary data
1389
+ <a href="https://engine.needle.tools/docs/project_structure.html#creating-and-installing-a-npmdef" target="_blank">documentation</a>`,Oi.Warn)}}if(t.children)for(const u of t.children)await ky(s,u,i)}function Pj(s,t){const{instance:i,compData:n,obj:o}=s;t.object=o,t.target=i,Vd(i,n,t),Xh&&console.debug("add "+n.name,n,i)}const Zp=C("debugfileformat");async function V1(s,t=!0){var i;if(t){const r=s,l=new URL(r,globalThis.location.origin);let c=null;const h=l.searchParams.get("filetype");switch(h&&(c=h.toUpperCase()),c!=null&&c.length||(c=(i=l.pathname.split(".").pop())==null?void 0:i.toUpperCase()),Zp&&console.debug("Use file extension to determine type: "+c),c){case"GLTF":return"gltf";case"VRM":return"vrm";case"GLB":return"glb";case"FBX":return"fbx";case"USD":return"usd";case"USDA":return"usda";case"USDZ":return"usdz";case"OBJ":return"obj"}}const n=new URL(s);n.searchParams.append("range","true");const o=await fetch(n,{method:"GET",headers:{range:"bytes=0-32"}}).catch(r=>null);if(o!=null&&o.ok){const r=await o.arrayBuffer(),l=H1(r,o);return Zp&&console.log("Determined file type from header: "+l),l}return"unknown"}function H1(s,t){if(s.byteLength<4)return"unknown";const i=new Uint8Array(s);if(Zp&&console.warn(`Trying to determine file type from binary data
1386
1390
  `,'"'+new TextDecoder().decode(s)+`"
1387
- `,i),i[0]==103&&i[1]==108&&i[2]==84&&i[3]==70)return console.debug("GLTF detected"),"glb";if(i[0]==80&&i[1]==75&&i[2]==3&&i[3]==4)return console.debug("USDZ detected"),"usdz";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 console.debug("Binary USD detected"),"usd";if(i[0]==35&&i[1]==117&&i[2]==115&&i[3]==100&&i[4]==97)return console.debug("ASCII USD detected"),"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 console.debug("Binary FBX detected"),"fbx";if(i[0]==59&&i[1]==32&&i[2]==70&&i[3]==66&&i[4]==88&&i[5]==32)return console.debug("ASCII FBX detected"),"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||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 console.debug("OBJ detected"),"obj";if(t.headers.has("content-type")){const n=t.headers.get("content-type");switch(console.debug("Content-Type: "+n),n){case"model/gltf+json":return"gltf";case"model/gltf-binary":return"glb";case"model/vrm":return"vrm";case"model/vnd.usdz+zip":return"usdz";case"model/vnd.usd+zip":return"usd";case"model/vnd.usda+zip":return"usda";case"model/fbx":case"model/vnd.autodesk.fbx":return"fbx";case"model/obj":return"obj"}}if(i[0]==118&&i[1]==32||i[0]==102&&i[1]==32)return 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 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 console.debug("OBJ detected (mtllib)"),"obj";if(F()||Zp){const n=new TextDecoder().decode(s.slice(0,16));console.debug('Could not determine file type from binary data: "'+n+'..."',i)}else console.debug("Could not determine file type from binary data",i);return"unknown"}class My{createBuiltinComponents(t,i,n,o,r){return Cj(t,i,n,o,r)}writeBuiltinComponentData(t,i){return xj(t,i)}parseSync(t,i,n,o){return Q1(t,i,n,o)}loadSync(t,i,n,o,r){return Y1(t,i,n,o,r)}}wm(My);const $1=C("printGltf")||C("printgltf"),q1=C("downloadgltf"),Pj=C("debugfileformat");var G1=(s=>(s[s.BeforeLoad=0]="BeforeLoad",s[s.AfterLoaded=1]="AfterLoaded",s[s.FinishedSetup=10]="FinishedSetup",s))(G1||{});class aa{constructor(t,i,n,o){a(this,"context"),a(this,"loader"),a(this,"path"),a(this,"gltf"),this.context=t,this.path=i,this.loader=n,this.gltf=o}}const tr={};function kj(s,t){tr[s]=tr[s]||[],tr[s].push(t)}function Mj(s,t){if(tr[s]){const i=tr[s].indexOf(t);i>=0&&tr[s].splice(i,1)}}function Ul(s,t){if(tr[s])for(const i of tr[s])i(t)}async function X1(s,t,i,n,o){$1&&console.warn("glTF",t,i),t.includes("?")&&(t=t.split("?")[0]),await gs().createBuiltinComponents(s,t,i,n,o)}async function Ry(s,t){const i=await V1(s)||"unknown";switch(Pj&&console.debug("Determined file type: "+i+" for url",s),i){case"unknown":{console.warn("Unknown file type. Assuming glTF:",s);const n=new rr;return await Wu(n,t,s),n}case"fbx":return new lv;case"obj":return new ym;case"usd":case"usda":case"usdz":return console.warn(i.toUpperCase()+" files are not supported."),null;default:console.warn("Unknown file type:",i);case"gltf":case"glb":case"vrm":{const n=new rr;return await Wu(n,t,s),n}}}async function Q1(s,t,i,n){typeof i!="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",i,typeof i),i=""),$1&&console.log("Parse glTF",i);const o=await Ry(i,s);if(!o)return;if(o instanceof ym){typeof t!="string"&&(t=new TextDecoder().decode(t));const l=o.parse(t);return{animations:l.animations,scene:l,scenes:[l]}}if(!(o instanceof rr)){const l=o.parse(t,i);return J1(o,l),{animations:l.animations,scene:l,scenes:[l]}}const r=Nu(o);return new Promise((l,c)=>{try{let h=i.split("?")[0].trimEnd();{const u=h.split("/");u.length>0&&u[u.length-1]!==""&&u.pop(),h=u.join("/"),h.endsWith("/")||(h+="/")}o.resourcePath=h,gu(o,s),Ul(0,new aa(s,i,o));const d=s.mainCamera;o.parse(t,"",async u=>{Vf(i,u,s),Ul(1,new aa(s,i,o,u)),await X1(s,i,u,n,r),await Z1(u.scene,s,d),Ul(10,new aa(s,i,o,u)),l(u),q1&&K1(t)},u=>{console.error('Loading asset at "'+i+`" failed
1388
- `,u),l(void 0)})}catch(h){console.error(h),c(h)}})}async function Y1(s,t,i,n,o){Rj(t);const r=await Ry(t,s);if(!r)return;if(!(r instanceof rr)){const c=await r.loadAsync(t,o);return J1(r,c),{animations:c.animations,scene:c,scenes:[c]}}const l=Nu(r);return new Promise((c,h)=>{try{gu(r,s),Ul(0,new aa(s,t,r));const d=s.mainCamera;r.load(t,async u=>{Vf(t,u,s),Ul(1,new aa(s,t,r,u)),await X1(s,i,u,n,l),await Z1(u.scene,s,d),Ul(10,new aa(s,t,r,u)),c(u),q1&&K1(t)},u=>{o?.call(r,u)},u=>{console.error('Loading asset at "'+t+`" failed
1389
- `,u),c(void 0)})}catch(d){console.error(d),h(d)}})}async function Z1(s,t,i){i||(i=t.mainCamera);try{i?await t.renderer.compileAsync(s,i,t.scene).catch(n=>{console.warn(n.message)}):_2(s,t)}catch(n){console.warn(n?.message||n)}}function Rj(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.
1390
- 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>`;De(t),console.warn(t)}}function K1(s){if(typeof s=="string"){const t=document.createElement("a");t.href=s,t.download=s.split("/").pop(),t.click()}else{const t=new Blob([s],{type:"application/octet-stream"}),i=window.URL.createObjectURL(t),n=document.createElement("a");n.href=i,n.download="download.glb",n.click()}}function J1(s,t){if(t!=null&&t.isObject3D){const i=t;(s instanceof lv||s instanceof ym)&&i.traverse(n=>{const o=n;o!=null&&o.isMesh&&$m(o,o.material)})}}wm(My);const Ue=C("debugwebcomponent"),eS="needle-engine",tS="vr",iS="desktop",Tj=[uw,tS,iS],Yh="ar-session-active",Zh="desktop-session-active",Ej=["public-key","version","hash","src","camera-controls","loadstart","progress","loadfinished","dracoDecoderPath","dracoDecoderType","ktx2DecoderPath","tone-mapping","tone-mapping-exposure","background-blurriness","background-color"];class Ty extends HTMLElement{constructor(){super(),a(this,"_context"),a(this,"_overlay_ar"),a(this,"_loadingProgress01",0),a(this,"_loadingView"),a(this,"_previousSrc",null),a(this,"_didFullyLoad",!1),a(this,"_loadId",0),a(this,"_abortController",null),a(this,"_lastSourceFiles",null),a(this,"_createContextPromise",null),a(this,"onXRSessionStarted",()=>{var i;const n=this.context.xrSessionMode;n==="immersive-ar"?this.onEnterAR(this.context.xrSession):n==="immersive-vr"&&this.onEnterVR(this.context.xrSession),(i=this.context.xrSession)==null||i.addEventListener("end",()=>{this.dispatchEvent(new CustomEvent("xr-session-ended",{detail:{session:this.context.xrSession,context:this._context,sessionMode:n}})),n==="immersive-ar"?this.onExitAR(this.context.xrSession):n==="immersive-vr"&&this.onExitVR(this.context.xrSession)})}),a(this,"onReady",()=>{var i;return(i=this._loadingView)==null?void 0:i.onLoadingFinished()}),a(this,"onError",()=>{var i;return(i=this._loadingView)==null?void 0:i.setMessage("Loading failed!")}),a(this,"_previouslyRegisteredMap",new Map),this._overlay_ar=new Rk,this.addEventListener("ready",this.onReady),iw(),this.attachShadow({mode:"open"});const t=document.createElement("template");t.innerHTML=`<style>
1391
+ `,i),i[0]==103&&i[1]==108&&i[2]==84&&i[3]==70)return console.debug("GLTF detected"),"glb";if(i[0]==80&&i[1]==75&&i[2]==3&&i[3]==4)return console.debug("USDZ detected"),"usdz";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 console.debug("Binary USD detected"),"usd";if(i[0]==35&&i[1]==117&&i[2]==115&&i[3]==100&&i[4]==97)return console.debug("ASCII USD detected"),"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 console.debug("Binary FBX detected"),"fbx";if(i[0]==59&&i[1]==32&&i[2]==70&&i[3]==66&&i[4]==88&&i[5]==32)return console.debug("ASCII FBX detected"),"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||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 console.debug("OBJ detected"),"obj";if(t.headers.has("content-type")){const n=t.headers.get("content-type");switch(console.debug("Content-Type: "+n),n){case"model/gltf+json":return"gltf";case"model/gltf-binary":return"glb";case"model/vrm":return"vrm";case"model/vnd.usdz+zip":return"usdz";case"model/vnd.usd+zip":return"usd";case"model/vnd.usda+zip":return"usda";case"model/fbx":case"model/vnd.autodesk.fbx":return"fbx";case"model/obj":return"obj"}}if(i[0]==118&&i[1]==32||i[0]==102&&i[1]==32)return 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 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 console.debug("OBJ detected (mtllib)"),"obj";if(F()||Zp){const n=new TextDecoder().decode(s.slice(0,16));console.debug('Could not determine file type from binary data: "'+n+'..."',i)}else console.debug("Could not determine file type from binary data",i);return"unknown"}class My{createBuiltinComponents(t,i,n,o,r){return Oj(t,i,n,o,r)}writeBuiltinComponentData(t,i){return Sj(t,i)}parseSync(t,i,n,o){return Q1(t,i,n,o)}loadSync(t,i,n,o,r){return Y1(t,i,n,o,r)}}wm(My);const $1=C("printGltf")||C("printgltf"),q1=C("downloadgltf"),kj=C("debugfileformat");var G1=(s=>(s[s.BeforeLoad=0]="BeforeLoad",s[s.AfterLoaded=1]="AfterLoaded",s[s.FinishedSetup=10]="FinishedSetup",s))(G1||{});class aa{constructor(t,i,n,o){a(this,"context"),a(this,"loader"),a(this,"path"),a(this,"gltf"),this.context=t,this.path=i,this.loader=n,this.gltf=o}}const tr={};function Mj(s,t){tr[s]=tr[s]||[],tr[s].push(t)}function Rj(s,t){if(tr[s]){const i=tr[s].indexOf(t);i>=0&&tr[s].splice(i,1)}}function Ul(s,t){if(tr[s])for(const i of tr[s])i(t)}async function X1(s,t,i,n,o){$1&&console.warn("glTF",t,i),t.includes("?")&&(t=t.split("?")[0]),await gs().createBuiltinComponents(s,t,i,n,o)}async function Ry(s,t){const i=await V1(s)||"unknown";switch(kj&&console.debug("Determined file type: "+i+" for url",s),i){case"unknown":{console.warn("Unknown file type. Assuming glTF:",s);const n=new rr;return await Wu(n,t,s),n}case"fbx":return new lv;case"obj":return new ym;case"usd":case"usda":case"usdz":return console.warn(i.toUpperCase()+" files are not supported."),null;default:console.warn("Unknown file type:",i);case"gltf":case"glb":case"vrm":{const n=new rr;return await Wu(n,t,s),n}}}async function Q1(s,t,i,n){typeof i!="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",i,typeof i),i=""),$1&&console.log("Parse glTF",i);const o=await Ry(i,s);if(!o)return;if(o instanceof ym){typeof t!="string"&&(t=new TextDecoder().decode(t));const l=o.parse(t);return{animations:l.animations,scene:l,scenes:[l]}}if(!(o instanceof rr)){const l=o.parse(t,i);return J1(o,l),{animations:l.animations,scene:l,scenes:[l]}}const r=Nu(o);return new Promise((l,c)=>{try{let h=i.split("?")[0].trimEnd();{const u=h.split("/");u.length>0&&u[u.length-1]!==""&&u.pop(),h=u.join("/"),h.endsWith("/")||(h+="/")}o.resourcePath=h,gu(o,s),Ul(0,new aa(s,i,o));const d=s.mainCamera;o.parse(t,"",async u=>{Vf(i,u,s),Ul(1,new aa(s,i,o,u)),await X1(s,i,u,n,r),await Z1(u.scene,s,d),Ul(10,new aa(s,i,o,u)),l(u),q1&&K1(t)},u=>{console.error('Loading asset at "'+i+`" failed
1392
+ `,u),l(void 0)})}catch(h){console.error(h),c(h)}})}async function Y1(s,t,i,n,o){Tj(t);const r=await Ry(t,s);if(!r)return;if(!(r instanceof rr)){const c=await r.loadAsync(t,o);return J1(r,c),{animations:c.animations,scene:c,scenes:[c]}}const l=Nu(r);return new Promise((c,h)=>{try{gu(r,s),Ul(0,new aa(s,t,r));const d=s.mainCamera;r.load(t,async u=>{Vf(t,u,s),Ul(1,new aa(s,t,r,u)),await X1(s,i,u,n,l),await Z1(u.scene,s,d),Ul(10,new aa(s,t,r,u)),c(u),q1&&K1(t)},u=>{o?.call(r,u)},u=>{console.error('Loading asset at "'+t+`" failed
1393
+ `,u),c(void 0)})}catch(d){console.error(d),h(d)}})}async function Z1(s,t,i){i||(i=t.mainCamera);try{i?await t.renderer.compileAsync(s,i,t.scene).catch(n=>{console.warn(n.message)}):_2(s,t)}catch(n){console.warn(n?.message||n)}}function Tj(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.
1394
+ 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>`;De(t),console.warn(t)}}function K1(s){if(typeof s=="string"){const t=document.createElement("a");t.href=s,t.download=s.split("/").pop(),t.click()}else{const t=new Blob([s],{type:"application/octet-stream"}),i=window.URL.createObjectURL(t),n=document.createElement("a");n.href=i,n.download="download.glb",n.click()}}function J1(s,t){if(t!=null&&t.isObject3D){const i=t;(s instanceof lv||s instanceof ym)&&i.traverse(n=>{const o=n;o!=null&&o.isMesh&&$m(o,o.material)})}}wm(My);const Ue=C("debugwebcomponent"),eS="needle-engine",tS="vr",iS="desktop",Ej=[uw,tS,iS],Yh="ar-session-active",Zh="desktop-session-active",Aj=["public-key","version","hash","src","camera-controls","loadstart","progress","loadfinished","dracoDecoderPath","dracoDecoderType","ktx2DecoderPath","tone-mapping","tone-mapping-exposure","background-blurriness","background-color"];class Ty extends HTMLElement{constructor(){super(),a(this,"_context"),a(this,"_overlay_ar"),a(this,"_loadingProgress01",0),a(this,"_loadingView"),a(this,"_previousSrc",null),a(this,"_didFullyLoad",!1),a(this,"_loadId",0),a(this,"_abortController",null),a(this,"_lastSourceFiles",null),a(this,"_createContextPromise",null),a(this,"onXRSessionStarted",()=>{var i;const n=this.context.xrSessionMode;n==="immersive-ar"?this.onEnterAR(this.context.xrSession):n==="immersive-vr"&&this.onEnterVR(this.context.xrSession),(i=this.context.xrSession)==null||i.addEventListener("end",()=>{this.dispatchEvent(new CustomEvent("xr-session-ended",{detail:{session:this.context.xrSession,context:this._context,sessionMode:n}})),n==="immersive-ar"?this.onExitAR(this.context.xrSession):n==="immersive-vr"&&this.onExitVR(this.context.xrSession)})}),a(this,"onReady",()=>{var i;return(i=this._loadingView)==null?void 0:i.onLoadingFinished()}),a(this,"onError",()=>{var i;return(i=this._loadingView)==null?void 0:i.setMessage("Loading failed!")}),a(this,"_previouslyRegisteredMap",new Map),this._overlay_ar=new Rk,this.addEventListener("ready",this.onReady),iw(),this.attachShadow({mode:"open"});const t=document.createElement("template");t.innerHTML=`<style>
1391
1395
  @import url('https://fonts.googleapis.com/css2?family=Roboto+Flex:opsz,wght@8..144,100..1000&display=swap');
1392
1396
 
1393
1397
  :host {
@@ -1461,14 +1465,14 @@ Please refer to the documentation on <a href="https://fwd.needle.tools/needle-en
1461
1465
  <div class="content">
1462
1466
  <slot class="overlay-content"></slot>
1463
1467
  </div>
1464
- `,this.shadowRoot&&this.shadowRoot.appendChild(t.content.cloneNode(!0)),this._context=new ee({domElement:this}),this.addEventListener("error",this.onError)}static get observedAttributes(){return Ej}get loadingProgress01(){return this._loadingProgress01}get loadingFinished(){return this.loadingProgress01>.999}get cameraControls(){const t=this.getAttribute("camera-controls");return t==null?null:!(t===null||t==="False"||t==="false"||t==="0"||t==="none")}getContext(){return new Promise((t,i)=>{if(this._context&&this.loadingFinished)t(this._context);else{const n=()=>{this.removeEventListener("loadfinished",n),this._context&&this.loadingFinished&&t(this._context)};this.addEventListener("loadfinished",n)}})}get context(){return this._context}async connectedCallback(){if(Ue&&console.log("<needle-engine> connected"),this.setPublicKey(),this.setVersion(),this.addEventListener("xr-session-started",this.onXRSessionStarted),this.onSetupDesktop(),!this.getAttribute("src")){const i=globalThis["needle:codegen_files"];Ue&&console.log('src is null, trying to load from globalThis["needle:codegen_files"]',i),i&&(Ue&&console.log('globalThis["needle:codegen_files"]',i),this.setAttribute("src",i))}Ue&&console.log("src",this.getAttribute("src"));const t=this._loadId;setTimeout(()=>{this.isConnected!==!1&&t===this._loadId&&this.onLoad()},1)}disconnectedCallback(){var t;this.removeEventListener("xr-session-started",this.onXRSessionStarted),this._didFullyLoad=!1;const i=this.getAttribute("keep-alive"),n=i==null||i?.length>0&&i!=="true"&&i!=="1";Ue&&console.warn('<needle-engine> disconnected, keep-alive: "'+i+'"',typeof i,"Dispose=",n),n?(Ue&&console.warn("<needle-engine> dispose"),(t=this._context)==null||t.dispose(),this._context=null,this._lastSourceFiles=null,this._loadId+=1):Ue&&console.warn("<needle-engine> is not disposed because keep-alive is set")}attributeChangedCallback(t,i,n){switch(Ue&&console.log("attributeChangedCallback",t,i,n),t){case"src":Ue&&console.warn(`<needle-engine src>
1468
+ `,this.shadowRoot&&this.shadowRoot.appendChild(t.content.cloneNode(!0)),this._context=new ee({domElement:this}),this.addEventListener("error",this.onError)}static get observedAttributes(){return Aj}get loadingProgress01(){return this._loadingProgress01}get loadingFinished(){return this.loadingProgress01>.999}get cameraControls(){const t=this.getAttribute("camera-controls");return t==null?null:!(t===null||t==="False"||t==="false"||t==="0"||t==="none")}getContext(){return new Promise((t,i)=>{if(this._context&&this.loadingFinished)t(this._context);else{const n=()=>{this.removeEventListener("loadfinished",n),this._context&&this.loadingFinished&&t(this._context)};this.addEventListener("loadfinished",n)}})}get context(){return this._context}async connectedCallback(){if(Ue&&console.log("<needle-engine> connected"),this.setPublicKey(),this.setVersion(),this.addEventListener("xr-session-started",this.onXRSessionStarted),this.onSetupDesktop(),!this.getAttribute("src")){const i=globalThis["needle:codegen_files"];Ue&&console.log('src is null, trying to load from globalThis["needle:codegen_files"]',i),i&&(Ue&&console.log('globalThis["needle:codegen_files"]',i),this.setAttribute("src",i))}Ue&&console.log("src",this.getAttribute("src"));const t=this._loadId;setTimeout(()=>{this.isConnected!==!1&&t===this._loadId&&this.onLoad()},1)}disconnectedCallback(){var t;this.removeEventListener("xr-session-started",this.onXRSessionStarted),this._didFullyLoad=!1;const i=this.getAttribute("keep-alive"),n=i==null||i?.length>0&&i!=="true"&&i!=="1";Ue&&console.warn('<needle-engine> disconnected, keep-alive: "'+i+'"',typeof i,"Dispose=",n),n?(Ue&&console.warn("<needle-engine> dispose"),(t=this._context)==null||t.dispose(),this._context=null,this._lastSourceFiles=null,this._loadId+=1):Ue&&console.warn("<needle-engine> is not disposed because keep-alive is set")}attributeChangedCallback(t,i,n){switch(Ue&&console.log("attributeChangedCallback",t,i,n),t){case"src":Ue&&console.warn(`<needle-engine src>
1465
1469
  changed from "`,i,'" to "',n,'"'),this.onLoad();break;case"hash":this._context&&(this._context.hash=n);break;case"loadstart":case"progress":case"loadfinished":typeof n=="string"&&n.length>0&&(Ue&&console.log(t+" attribute changed",n),this.registerEventFromAttribute(t,n));break;case"dracoDecoderPath":Ue&&console.log("dracoDecoderPath",n),mw(n);break;case"dracoDecoderType":n==="wasm"||n==="js"?(Ue&&console.log("dracoDecoderType",n),gw(n)):console.error("Invalid dracoDecoderType",n,"expected js or wasm");break;case"ktx2DecoderPath":Ue&&console.log("ktx2DecoderPath",n),fw(n);break;case"tone-mapping":{this.applyAttributes();break}case"tone-mapping-exposure":{this.applyAttributes();break}case"background-blurriness":{const o=parseFloat(n);o!=null&&this._context&&(this._context.scene.backgroundBlurriness=o);break}case"background-color":{this.applyAttributes();break}case"public-key":{n!=cc&&this.setPublicKey();break}case"version":{n!=bs&&this.setVersion();break}}}async onLoad(){var t,i;if(!this.isConnected)return;if(this._context||(Ue&&console.warn("Create new context"),this._context=new ee({domElement:this})),!this._context){console.error("Needle Engine: Context not initialized");return}const n=this.getSourceFiles();if(!this.checkIfSourceHasChanged(n,this._lastSourceFiles))return;this._abortController&&(Ue&&console.warn("Abort previous loading process"),this._abortController.abort(),this._abortController=null),this._lastSourceFiles=n;const o=++this._loadId;if((n==null||n.length<=0)&&(Ue&&console.warn("Clear scene",n),this._context.clear(),o!==this._loadId))return;const r=this.getAttribute("alias");this.classList.add("loading");const l=Cs();this.ensureLoadStartIsRegistered();let c=this.dispatchEvent(new CustomEvent("loadstart",{detail:{context:this._context,alias:r},cancelable:!0}));if(l){const b=this.getAttribute("hide-loading-overlay");b!=null&&b!=="0"&&(c=!1)}c===!1&&!l&&(F()||(c=!0),console.warn("Needle Engine: You need a commercial license to override the default loading view. Visit https://needle.tools/pricing"),F()&&we('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&&c&&(this._loadingView=new af(this)),c&&(this._didFullyLoad!==!0?(t=this._loadingView)==null||t.onLoadingBegin("begin load"):setTimeout(()=>{this._loadingView&&this._loadingProgress01<.3&&this._loadId===o&&this._loadingView.onLoadingBegin("begin load")},300)),Ue&&console.warn(`--------------
1466
1470
  Needle Engine: Begin loading `+o+`
1467
- `,n),this.onBeforeBeginLoading();const h=[],d={context:this._context,name:"",progress:{},index:0,count:n.length,totalProgress01:this._loadingProgress01},u=new CustomEvent("progress",{detail:d}),p=new Array,g=new AbortController;this._abortController=g;const y={files:n,abortSignal:g.signal,onLoadingProgress:b=>{var w;if(Ue&&console.debug("Loading progress: ",b),g.signal.aborted)return;const _=b.index;!p[_]&&b.name&&(p[_]=Aj(b.name)),b.name=p[_],c&&((w=this._loadingView)==null||w.onLoadingUpdate(b)),d.name=b.name,d.progress=b.progress,this._loadingProgress01=of(b),d.totalProgress01=this._loadingProgress01,this.dispatchEvent(u)},onLoadingFinished:(b,w,_)=>{Ue&&console.debug(`Finished loading "${w}" (aborted? ${g.signal.aborted})`),!g.signal.aborted&&_&&h.push({src:w,file:_})}},f=this.getAttribute("hash");f!=null&&(this._context.hash=f),this._context.alias=r,this._createContextPromise=this._context.create(y);const v=await this._createContextPromise;if(this.applyAttributes(),Ue&&console.warn(`--------------
1471
+ `,n),this.onBeforeBeginLoading();const h=[],d={context:this._context,name:"",progress:{},index:0,count:n.length,totalProgress01:this._loadingProgress01},u=new CustomEvent("progress",{detail:d}),p=new Array,g=new AbortController;this._abortController=g;const y={files:n,abortSignal:g.signal,onLoadingProgress:b=>{var w;if(Ue&&console.debug("Loading progress: ",b),g.signal.aborted)return;const _=b.index;!p[_]&&b.name&&(p[_]=Ij(b.name)),b.name=p[_],c&&((w=this._loadingView)==null||w.onLoadingUpdate(b)),d.name=b.name,d.progress=b.progress,this._loadingProgress01=of(b),d.totalProgress01=this._loadingProgress01,this.dispatchEvent(u)},onLoadingFinished:(b,w,_)=>{Ue&&console.debug(`Finished loading "${w}" (aborted? ${g.signal.aborted})`),!g.signal.aborted&&_&&h.push({src:w,file:_})}},f=this.getAttribute("hash");f!=null&&(this._context.hash=f),this._context.alias=r,this._createContextPromise=this._context.create(y);const v=await this._createContextPromise;if(this.applyAttributes(),Ue&&console.warn(`--------------
1468
1472
  Needle Engine: finished loading `+o+`
1469
1473
  `,n,`Aborted? ${g.signal.aborted}`),g.signal.aborted){console.log("Loading finished but aborted...");return}if(this._loadId!==o){console.log("Load id changed during loading process");return}this._loadingProgress01=1,c&&v&&((i=this._loadingView)==null||i.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:r,loadedFiles:h}}))}applyAttributes(){if(this._context.renderer){const n=this.getAttribute("tonemapping")||this.getAttribute("tone-mapping");switch(n?.toLowerCase()){case"none":this._context.renderer.toneMapping=fa;break;case"linear":this._context.renderer.toneMapping=hd;break;case"neutral":this._context.renderer.toneMapping=Xl;break;case"agx":this._context.renderer.toneMapping=cd;break;default:n!=null&&console.warn("Invalid tone-mapping attribute: "+n)}const o=this.getAttribute("tone-mapping-exposure");if(o!=null){const r=parseFloat(o);isNaN(r)||(this._context.renderer.toneMappingExposure=r)}}const t=this.getAttribute("background-blurriness");if(t!=null){const n=parseFloat(t);n!==void 0&&this._context&&(this._context.scene.backgroundBlurriness=n)}const i=this.getAttribute("background-color");if(this._context&&typeof i=="string"&&i.length>0){const n=this._context.scene.background;n instanceof ae?n.set(i):this._context.scene.background=new ae(i)}}internalSetLoadingMessage(t){var i;(i=this._loadingView)==null||i.setMessage(t)}getSourceFiles(){const t=this.getAttribute("src");if(!t)return[];let i;Array.isArray(t)?i=t:t.startsWith("[")&&t.endsWith("]")?i=JSON.parse(t):t.includes(",")?i=t.split(","):i=[t];for(let n=i.length-1;n>=0;n--){const o=i[n];(o==="null"||o==="undefined"||o?.length<=0)&&i.splice(n,1)}return i}checkIfSourceHasChanged(t,i){if(t?.length!==i?.length||t==null&&i!==null||t!==null&&i==null)return!0;if(t!==null&&i!==null){for(let n=0;n<t?.length;n++)if(t[n]!==i[n])return!0}return!1}ensureLoadStartIsRegistered(){const t=this.getAttribute("loadstart");t&&this.registerEventFromAttribute("loadstart",t)}registerEventFromAttribute(t,i){const n=this._previouslyRegisteredMap.get(t);if(n&&(this._previouslyRegisteredMap.delete(t),this.removeEventListener(t,n)),typeof i=="string"&&i.length>0)try{const o=(0,eval)(i);typeof o=="function"&&(this._previouslyRegisteredMap.set(t,o),this.addEventListener(t,r=>o?.call(globalThis,this._context,r)))}catch(o){console.error("Error registering event "+t+'="'+i+`" failed with the following error:
1470
- `,o)}}setPublicKey(){cc.length>0&&this.setAttribute("public-key",cc)}setVersion(){bs.length>0&&this.setAttribute("version",bs)}getAROverlayContainer(){return this._overlay_ar.createOverlayContainer(this)}getVROverlayContainer(){for(let t=0;t<this.children.length;t++){const i=this.children[t];if(i.classList.contains("vr"))return i}return null}onEnterAR(t){var i;this.onSetupAR();const n=this.getAROverlayContainer();this._overlay_ar.onBegin(this._context,n,t),this.dispatchEvent(new CustomEvent("enter-ar",{detail:{session:t,context:this._context,htmlContainer:(i=this._overlay_ar)==null?void 0:i.ARContainer}}))}onExitAR(t){var i;this._overlay_ar.onEnd(this._context),this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-ar",{detail:{session:t,context:this._context,htmlContainer:(i=this._overlay_ar)==null?void 0:i.ARContainer}}))}onEnterVR(t){this.onSetupVR(),this.dispatchEvent(new CustomEvent("enter-vr",{detail:{session:t,context:this._context}}))}onExitVR(t){this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-vr",{detail:{session:t,context:this._context}}))}onSetupAR(){this.classList.add(Yh),this.classList.remove(Zh);const t=this.getAROverlayContainer();Ue&&console.warn("onSetupAR:",t),t&&(t.classList.add(Yh),t.classList.remove(Zh)),this.foreachHtmlElement(i=>this.setupElementsForMode(i,uw))}onSetupVR(){this.classList.remove(Yh),this.classList.remove(Zh),this.foreachHtmlElement(t=>this.setupElementsForMode(t,tS))}onSetupDesktop(){this.classList.remove(Yh),this.classList.add(Zh);const t=this.getAROverlayContainer();t&&(t.classList.remove(Yh),t.classList.add(Zh)),this.foreachHtmlElement(i=>this.setupElementsForMode(i,iS))}setupElementsForMode(t,i,n=null){var o,r;if(!(t===((r=(o=this._context)==null?void 0:o.renderer)==null?void 0:r.domElement)||t.id==="VRButton"||t.id==="ARButton"))if(t.classList.contains(i))t.style.visibility="visible",t.style.display==="none"&&(t.style.display="block");else for(const l of Tj)t.classList.contains(l)&&(t.style.visibility="hidden",t.style.display="none")}foreachHtmlElement(t){for(let i=0;i<this.children.length;i++){const n=this.children[i];n.style&&t(n)}}onBeforeBeginLoading(){const t=this.getAttribute("dracoDecoderPath");t&&(Ue&&console.log("using custom draco decoder path",t),mw(t));const i=this.getAttribute("dracoDecoderType");i&&(Ue&&console.log("using custom draco decoder type",i),gw(i));const n=this.getAttribute("ktx2DecoderPath");n&&(Ue&&console.log("using custom ktx2 decoder path",n),fw(n))}}typeof window<"u"&&!window.customElements.get(eS)&&window.customElements.define(eS,Ty);function Aj(s){if(s.startsWith("blob:"))return"blob";const t=s.split("/");let i=t[t.length-1];const n=i.indexOf("?");n>0&&(i=i.substring(0,n));const o=i.indexOf("=");o>0&&(i=i.substring(o));const r=i.split(".").pop(),l=r?["glb","gltf","usdz","usd","fbx","obj","mtl"].indexOf(r.toLowerCase()):-1;if(r&&l>=0&&(i=i.substring(0,i.length-r.length-1)),i=decodeURIComponent(i),i.length>3){let c="",h=!1;const d=["(",")","[","]","{","}",":",";",",",".","!","?"];for(let u=0;u<i.length;u++){let p=i[u];(p==="_"||p==="-")&&(p=" "),!(p===" "&&c.length<=0||d.includes(p)||(c.length===0&&(p=p.toUpperCase()),h&&p===" "))&&(h&&(p=p.toUpperCase()),h=!1,c+=p,p===" "&&(h=!0))}return F()&&i!==c&&console.debug('Generated display name: "'+i+'" \u2192 "'+c+'"'),c.trim()}return F()&&console.debug("Loading: use default name",i),i}const Ij=Object.freeze(Object.defineProperty({__proto__:null,NeedleEngineHTMLElement:Ty},Symbol.toStringTag,{value:"Module"}));function jj(){Pn.registerWaitForInteraction(()=>{const s=TC.getContext();s.addEventListener("statechange",()=>{setTimeout(()=>{const t=s.state;(t==="suspended"||t==="interrupted")&&s.resume().then(()=>{console.log("AudioContext resumed successfully")}).catch(i=>{console.log("Failed to resume AudioContext: "+i)})},500)})})}setTimeout(jj,1e3);const Kp=C("debughotreload");let Kh=!1;const Jh=new Map;function Lj(){return Kh}function Dj(s){var t;if(Kh)return;const i=s.constructor.name;Jh.has(i)?(t=Jh.get(i))==null||t.push(s):Jh.set(i,[s])}function Bj(s){if(Kh)return;const t=s.constructor.name,i=Jh.get(t);if(!i)return;const n=i.indexOf(s);n!==-1&&i.splice(n,1)}let sS=!1;function Fj(){if(Kp||sS)return;sS=!0;const s=console.error;console.error=(...t)=>{if(t.length){const i=t[0];if(typeof i=="string"&&i.includes("[hmr] Failed to reload ")){console.log("[Needle Engine] Hot reloading failed"),window.location.reload();return}}s.apply(console,t)}}function zj(s){Kp&&console.log("[HMR] Apply changes",s,Object.keys(s)),Fj();for(const t of Object.keys(s))try{Kh=!0;const i=k.get(t);if(!i){Kp&&console.log("[HMR] Type not found: "+t);continue}const n=s[t],o=Jh.get(n.name);let r="[Needle Engine] Updating type: "+t;const l=o?.length??-1;l>0?r+=" x"+l:r+=" - no instances",console.log(r);const c=Object.getOwnPropertyNames(i.prototype),h=Object.getOwnPropertyDescriptors(n.prototype);for(const d in h)h[d].writable&&(i.prototype[d]=s[t].prototype[d]);for(const d of c)h[d]||delete i.prototype[d];if(o){const d=new n,u=Object.getOwnPropertyDescriptors(d);for(const p of o){const g=p,y=g.isComponent===!0,f=y?g.activeAndEnabled:!0,v=y?g.context:void 0;try{if(y&&v&&Cn(g,v),y&&f&&(g.enabled=!1),p.onBeforeHotReloadFields&&p.onBeforeHotReloadFields()===!1)continue;for(const b in u)if(u[b].writable){if(p[b]===void 0)p[b]=d[b];else if(typeof p[b]=="function"&&!p[b].prototype){const w=p[b],_=w.name,S="bound ";if(_===S)continue;const R=w.name.substring(S.length),M=n.prototype[R];M&&(p[b]=M.bind(p))}}p.onAfterHotReloadFields&&p.onAfterHotReloadFields()}finally{y&&v&&Cg(g,v),y&&f&&(g.enabled=!0)}}}}catch(i){if(Kp)console.error(i);else return!1}finally{Kh=!1,zs(Oi.Log,"Script changes applied (HMR)")}return!0}const Lt=C("debugphysics"),Ey=C("debugcolliderplacement"),Ay=C("debugcollisions"),Uj=C("showcolliders"),Iy=C("debugraycasts"),bi=Symbol("needle component"),ii=Symbol("physics body"),nS=Symbol("rigidbody");globalThis.false=globalThis.false!==void 0?globalThis.false:!0,Lt&&console.log("Use Rapier",!1,globalThis.false);const Jp=class{constructor(s){a(this,"debugRenderColliders",!1),a(this,"debugRenderRaycasts",!1),a(this,"context"),a(this,"_initializePromise"),a(this,"_isInitialized",!1),a(this,"rapierRay"),a(this,"raycastVectorsBuffer",new Ci(()=>new x,10)),a(this,"rapierSphere",null),a(this,"rapierColliderArray",[]),a(this,"rapierIdentityRotation",{x:0,y:0,z:0,w:1}),a(this,"rapierForwardVector",{x:0,y:0,z:1}),a(this,"enabled",!1),a(this,"_tempPosition",new x),a(this,"_tempQuaternion",new V),a(this,"_tempScale",new x),a(this,"_tempMatrix",new ne),a(this,"_isUpdatingPhysicsWorld",!1),a(this,"_world"),a(this,"_hasCreatedWorld",!1),a(this,"eventQueue"),a(this,"collisionHandler"),a(this,"objects",[]),a(this,"bodies",[]),a(this,"_meshCache",new Map),a(this,"_gravity",{x:0,y:-9.81,z:0}),a(this,"lines"),a(this,"_tempCenterPos",new x),a(this,"_tempCenterVec",new x),a(this,"_tempCenterQuaternion",new V),this.context=s}removeBody(s){var t,i,n;if(!s)return;this.validate();const o=s[ii];if(s[ii]=null,o&&this.world){const r=this.objects.findIndex(l=>l===s);if(r>=0){const l=this.bodies[r];if(this.bodies.splice(r,1),this.objects.splice(r,1),l instanceof D.RAPIER_PHYSICS.MODULE.Collider){const c=l;(t=this.world)==null||t.removeCollider(c,!0);const h=c.parent();h&&h.numColliders()<=0&&(h[bi]||(i=this.world)==null||i.removeRigidBody(h))}else l instanceof D.RAPIER_PHYSICS.MODULE.RigidBody&&(l.numColliders()<=0?(n=this.world)==null||n.removeRigidBody(l):F()&&(l.did_log_removing||setTimeout(()=>{l.numColliders()>0&&(l.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(s,t,i){if(this.validate(),!!this.enabled&&!(s.destroyed||!s.gameObject)&&!(!t&&!i))if(s.isCollider===!0)console.warn("TODO: implement updating collider position");else{const n=s,o=n[ii];o&&this.syncPhysicsBody(n.gameObject,o,t,i)}}updateProperties(s){if(this.validate(),s.isCollider){const t=s,i=t[ii];i&&(this.internalUpdateColliderProperties(t,i),t.sharedMaterial&&this.updatePhysicsMaterial(t))}else{const t=s,i=this.internal_getRigidbody(t);i&&this.internalUpdateRigidbodyProperties(t,i)}}addForce(s,t,i){this.validate();const n=this.internal_getRigidbody(s);n?n.addForce(t,i):console.warn("Rigidbody doesn't exist: can not apply force (does your object with the Rigidbody have a collider?)")}addImpulse(s,t,i){this.validate();const n=this.internal_getRigidbody(s);n?n.applyImpulse(t,i):console.warn("Rigidbody doesn't exist: can not apply impulse (does your object with the Rigidbody have a collider?)")}getLinearVelocity(s){this.validate();const t=this.internal_getRigidbody(s);return t?t.linvel():null}getAngularVelocity(s){this.validate();const t=this.internal_getRigidbody(s);return t?t.angvel():null}resetForces(s,t){this.validate();const i=this.internal_getRigidbody(s);i?.resetForces(t)}resetTorques(s,t){this.validate();const i=this.internal_getRigidbody(s);i?.resetTorques(t)}applyImpulse(s,t,i){this.validate();const n=this.internal_getRigidbody(s);n?n.applyImpulse(t,i):console.warn("Rigidbody doesn't exist: can not apply impulse (does your object with the Rigidbody have a collider?)")}wakeup(s){this.validate();const t=this.internal_getRigidbody(s);t?t.wakeUp():console.warn("Rigidbody doesn't exist: can not wake up (does your object with the Rigidbody have a collider?)")}isSleeping(s){this.validate();const t=this.internal_getRigidbody(s);return t?.isSleeping()}setAngularVelocity(s,t,i){this.validate();const n=this.internal_getRigidbody(s);n?n.setAngvel(t,i):console.warn("Rigidbody doesn't exist: can not set angular velocity (does your object with the Rigidbody have a collider?)")}setLinearVelocity(s,t,i){this.validate();const n=this.internal_getRigidbody(s);n?n.setLinvel(t,i):console.warn("Rigidbody doesn't exist: can not set linear velocity (does your object with the Rigidbody have a collider?)")}get isInitialized(){return this._isInitialized}async initialize(){return this._initializePromise||(this._initializePromise=this.internalInitialization()),this._initializePromise}async internalInitialization(){return C("__nophysics")?(console.warn("Physics are disabled"),!1):(Lt&&console.log("Initialize rapier physics engine"),"env"in import.meta&&{}.VITE_NEEDLE_USE_RAPIER==="false"&&Lt&&console.log("Rapier disabled"),!1)}validate(){this._isInitialized||Lt&&(this._lastWarnTime=this._lastWarnTime??0,Date.now()-this._lastWarnTime>1e3&&(this._lastWarnTime=Date.now(),console.warn("Physics engine is not initialized")))}raycast(s,t,i){var n;if(!this._isInitialized)return console.log("Physics engine is not initialized"),null;let o=i?.maxDistance,r=i?.solid;o===void 0&&(o=1/0),r===void 0&&(r=!0);const l=this.getPhysicsRay(this.rapierRay,s,t);if(!l)return null;(this.debugRenderRaycasts||Iy)&&q.DrawRay(l.origin,l.dir,255,1);const c=(n=this.world)==null?void 0:n.castRay(l,o,r,i?.queryFilterFlags,i?.filterGroups,void 0,void 0,h=>{const d=h[bi];return i!=null&&i.filterPredicate?i.filterPredicate(d):i?.useIgnoreRaycastLayer!==!1?!(d!=null&&d.gameObject.layers.isEnabled(2)):!0});if(c){const h=l.pointAt(c.timeOfImpact),d=this.raycastVectorsBuffer.get();return d.set(h.x,h.y,h.z),{point:d,collider:c.collider[bi]}}return null}raycastAndGetNormal(s,t,i){var n;if(!this._isInitialized)return null;let o=i?.maxDistance,r=i?.solid;o===void 0&&(o=1/0),r===void 0&&(r=!0);const l=this.getPhysicsRay(this.rapierRay,s,t);if(!l)return null;(this.debugRenderRaycasts||Iy)&&q.DrawRay(l.origin,l.dir,255,1);const c=(n=this.world)==null?void 0:n.castRayAndGetNormal(l,o,r,i?.queryFilterFlags,i?.filterGroups,void 0,void 0,h=>{const d=h[bi];return i!=null&&i.filterPredicate?i.filterPredicate(d):i?.useIgnoreRaycastLayer!==!1?!(d!=null&&d.gameObject.layers.isEnabled(2)):!0});if(c){const h=l.pointAt(c.timeOfImpact),d=c.normal,u=this.raycastVectorsBuffer.get(),p=this.raycastVectorsBuffer.get();return u.set(h.x,h.y,h.z),p.set(d.x,d.y,d.z),{point:u,normal:p,collider:c.collider[bi]}}return null}getPhysicsRay(s,t,i){var n,o,r;const l=(n=this.context)==null?void 0:n.mainCamera;if(t===void 0){const d=(o=this.context)==null?void 0:o.input.getPointerPosition(0);if(d)t=d;else return null}if(t.z===void 0){if(!l)return console.error("Can not perform raycast from 2d point - no main camera found"),null;const d=this.raycastVectorsBuffer.get();d.x=t.x,d.y=t.y,d.z=0,(d.x>1||d.y>1||d.y<-1||d.x<-1)&&(Lt&&console.warn("Converting screenspace to raycast space",d),(r=this.context)==null||r.input.convertScreenspaceToRaycastSpace(d)),d.unproject(l),t=d}const c=t;s.origin.x=c.x,s.origin.y=c.y,s.origin.z=c.z;const h=this.raycastVectorsBuffer.get();if(i)h.set(i.x,i.y,i.z);else{if(!l)return console.error("Can not perform raycast - no camera found"),null;h.set(s.origin.x,s.origin.y,s.origin.z);const d=te(l);h.sub(d)}return h.normalize(),s.dir.x=h.x,s.dir.y=h.y,s.dir.z=h.z,s}sphereOverlap(s,t){return this.rapierColliderArray.length=0,this._isInitialized?this.world?(this.rapierSphere??(this.rapierSphere=new D.RAPIER_PHYSICS.MODULE.Ball(t)),this.rapierSphere.radius=t,(this.debugRenderRaycasts||Iy)&&q.DrawWireSphere(s,t,3359999,1),this.world.intersectionsWithShape(s,this.rapierIdentityRotation,this.rapierSphere,i=>{const n=i[bi],o=new Fw(n.gameObject,n);return this.rapierColliderArray.push(o),!0},void 0,void 0,void 0,void 0,i=>i.isSensor()?!1:i[bi].gameObject.layers.isEnabled(2)==!1),this.rapierColliderArray):this.rapierColliderArray:this.rapierColliderArray}get world(){return this._world}get isUpdating(){return this._isUpdatingPhysicsWorld}get gravity(){var s;return((s=this.world)==null?void 0:s.gravity)??this._gravity}set gravity(s){this.world?this.world.gravity=s:this._gravity=s}clearCaches(){var s,t,i,n;this._meshCache.clear(),(s=this.eventQueue)!=null&&s.raw&&((t=this.eventQueue)==null||t.free()),(i=this.world)!=null&&i.bodies&&((n=this.world)==null||n.free())}async addBoxCollider(s,t){if(this._isInitialized||await this.initialize(),!s.activeAndEnabled)return;if(!this.enabled){Lt&&console.warn("Physics are disabled");return}const i=s.gameObject,n=Ye(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)),n.x==0&&(n.x=1e-7),n.y==0&&(n.y=1e-7),n.z==0&&(n.z=1e-7);const o=D.RAPIER_PHYSICS.MODULE.ColliderDesc.cuboid(n.x,n.y,n.z);this.createCollider(s,o)}async addSphereCollider(s){if(this._isInitialized||await this.initialize(),!s.activeAndEnabled)return;if(!this.enabled){Lt&&console.warn("Physics are disabled");return}const t=D.RAPIER_PHYSICS.MODULE.ColliderDesc.ball(.5);this.createCollider(s,t),this.updateProperties(s)}async addCapsuleCollider(s,t,i){if(this._isInitialized||await this.initialize(),!s.activeAndEnabled)return;if(!this.enabled){Lt&&console.warn("Physics are disabled");return}const n=s.gameObject,o=Ye(n,this._tempPosition);o.x=Math.abs(o.x),o.y=Math.abs(o.y);const r=i*o.x;t=Math.max(t,r*2);const l=W.clamp(t*.5*o.y-i*o.x,0,Number.MAX_SAFE_INTEGER),c=D.RAPIER_PHYSICS.MODULE.ColliderDesc.capsule(l,r);this.createCollider(s,c)}async addMeshCollider(s,t,i,n){var o,r,l;let c=t.geometry;if(!c){Lt&&console.warn("Missing mesh geometry",t.name);return}(r=(o=c.index)==null?void 0:o.array)!=null&&r.length||(console.warn(`Your MeshCollider is missing vertices or indices in the assined mesh "${t.name}". Consider providing an indexed geometry.`),c=eO(c));let h=null;const d=c.getAttribute("position");if(d instanceof Gy){const y=d.count;h=new Float32Array(y*3);for(let f=0;f<y;f++){const v=d.getX(f),b=d.getY(f),w=d.getZ(f);h[f*3]=v,h[f*3+1]=b,h[f*3+2]=w}}else h=d.array;if(await this.initialize(),!this.enabled){Lt&&console.warn("Physics are disabled");return}if(!s.activeAndEnabled)return;const u=(l=c.index)==null?void 0:l.array,p=s.gameObject.worldScale.clone();if(n&&p.multiply(n),Math.abs(p.x-1)>1e-4||Math.abs(p.y-1)>1e-4||Math.abs(p.z-1)>1e-4){const y=`${c.uuid}_${p.x}_${p.y}_${p.z}_${i}`;if(this._meshCache.has(y))Lt&&console.warn("Use cached mesh collider"),h=this._meshCache.get(y);else{(Lt||F())&&console.debug(`[Performance] Your MeshCollider "${s.name}" is scaled: consider applying the scale to the collider mesh instead (${p.x}, ${p.y}, ${p.z})`);const f=new Float32Array(h.length);for(let v=0;v<h.length;v+=3)f[v]=h[v]*p.x,f[v+1]=h[v+1]*p.y,f[v+2]=h[v+2]*p.z;h=f,this._meshCache.set(y,f)}}const g=i?D.RAPIER_PHYSICS.MODULE.ColliderDesc.convexHull(h):D.RAPIER_PHYSICS.MODULE.ColliderDesc.trimesh(h,u);g&&this.createCollider(s,g)}updatePhysicsMaterial(s){if(!s)return;const t=s.sharedMaterial,i=s[ii];if(i&&t){if(t.bounciness!==void 0&&i.setRestitution(t.bounciness),t.bounceCombine!==void 0)switch(t.bounceCombine){case _t.Average:i.setRestitutionCombineRule(D.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case _t.Maximum:i.setRestitutionCombineRule(D.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case _t.Minimum:i.setRestitutionCombineRule(D.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case _t.Multiply:i.setRestitutionCombineRule(D.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(t.dynamicFriction!==void 0&&i.setFriction(t.dynamicFriction),t.frictionCombine!==void 0)switch(t.frictionCombine){case _t.Average:i.setFrictionCombineRule(D.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case _t.Maximum:i.setFrictionCombineRule(D.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case _t.Minimum:i.setFrictionCombineRule(D.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case _t.Multiply:i.setFrictionCombineRule(D.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}}}getBody(s){return s?s[ii]:null}getComponent(s){return s?s[bi]:null}createCollider(s,t){var i;if(!this.world)throw new Error("Physics world not initialized");const n=this._tempMatrix;let o;s.attachedRigidbody?o=this.getRigidbody(s,this._tempMatrix):(Lt&&console.log("Create collider without rigidbody",s.name),n.makeRotationFromQuaternion(Ce(s.gameObject)),n.setPosition(te(s.gameObject))),n.decompose(this._tempPosition,this._tempQuaternion,this._tempScale),this.tryApplyCenter(s,this._tempPosition),t.setTranslation(this._tempPosition.x,this._tempPosition.y,this._tempPosition.z),t.setRotation(this._tempQuaternion),t.setSensor(s.isTrigger);const r=s.sharedMaterial;if(r){if(r.bounciness!==void 0&&t.setRestitution(r.bounciness),r.bounceCombine!==void 0)switch(r.bounceCombine){case _t.Average:t.setRestitutionCombineRule(D.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case _t.Maximum:t.setRestitutionCombineRule(D.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case _t.Minimum:t.setRestitutionCombineRule(D.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case _t.Multiply:t.setRestitutionCombineRule(D.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(r.dynamicFriction!==void 0&&t.setFriction(r.dynamicFriction),r.frictionCombine!==void 0)switch(r.frictionCombine){case _t.Average:t.setFrictionCombineRule(D.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case _t.Maximum:t.setFrictionCombineRule(D.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case _t.Minimum:t.setFrictionCombineRule(D.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case _t.Multiply:t.setFrictionCombineRule(D.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}}((i=s.attachedRigidbody)==null?void 0:i.autoMass)===!1&&(t.setDensity(1e-6),t.setMass(1e-6));try{const l=this.world.createCollider(t,o);return l[bi]=s,s[ii]=l,l.setActiveEvents(D.RAPIER_PHYSICS.MODULE.ActiveEvents.COLLISION_EVENTS),l.setActiveCollisionTypes(D.RAPIER_PHYSICS.MODULE.ActiveCollisionTypes.ALL),this.objects.push(s),this.bodies.push(l),this.updateColliderCollisionGroups(s),l}catch(l){return console.error('Error creating collider "'+s.name+`"
1471
- Error:`,l),null}}updateColliderCollisionGroups(s){const t=s[ii],i=s.membership;let n=0;if(i==null)n=65535;else for(let l=0;l<i.length;l++){const c=i[l];c>31?console.error(`Rapier only supports 32 layers, layer ${c} is not supported`):n|=1<<Math.floor(c)}const o=s.filter;let r=0;if(o==null)r=65535;else for(let l=0;l<o.length;l++){const c=o[l];c>31?console.error(`Rapier only supports 32 layers, layer ${c} is not supported`):r|=1<<Math.floor(c)}t.setCollisionGroups(n<<16|r)}getRigidbody(s,t){if(!this.world)throw new Error("Physics world not initialized");let i=null;if(s.attachedRigidbody){const n=s.attachedRigidbody;if(i=n[ii],!i){const o=n.isKinematic&&!Ey;Lt&&console.log("Create rigidbody",o);const r=o?D.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased():D.RAPIER_PHYSICS.MODULE.RigidBodyDesc.dynamic(),l=te(s.attachedRigidbody.gameObject);r.setTranslation(l.x,l.y,l.z),r.setRotation(Ce(s.attachedRigidbody.gameObject)),r.centerOfMass=new D.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[bi]=n,n[ii]=i,this.internalUpdateRigidbodyProperties(n,i),this.getRigidbodyRelativeMatrix(s.gameObject,n.gameObject,t),s[nS]=i}else{const n=D.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased(),o=te(s.gameObject);n.setTranslation(o.x,o.y,o.z),n.setRotation(Ce(s.gameObject)),i=this.world.createRigidBody(n),t.identity(),i[bi]=null}return i}internal_getRigidbody(s){return s.isCollider===!0?s[nS]:s[ii]}internalUpdateColliderProperties(s,t){const i=t.shape;let n=!1;switch(i.type){case D.RAPIER_PHYSICS.MODULE.ShapeType.Ball:{const p=i,g=s,y=s.gameObject,f=Ye(y,this._tempPosition),v=Math.abs(g.radius*f.x);n=p.radius!==v,p.radius=v,n&&t.setShape(p);break}case D.RAPIER_PHYSICS.MODULE.ShapeType.Cuboid:const o=i,r=s,l=s.gameObject,c=Ye(l,this._tempPosition),h=r.size.x*.5*c.x,d=r.size.y*.5*c.y,u=r.size.z*.5*c.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=s.attachedRigidbody;if(o!=null&&o.autoMass){const r=this.getBody(o);r?.recomputeMassPropertiesFromColliders()}}this.updateColliderCollisionGroups(s),s.isTrigger!==t.isSensor()&&t.setSensor(s.isTrigger)}internalUpdateRigidbodyProperties(s,t){if(t.enableCcd(s.collisionDetectionMode!==wu.Discrete),t.setLinearDamping(s.drag),t.setAngularDamping(s.angularDrag),t.setGravityScale(s.useGravity?s.gravityScale:0,!0),s.dominanceGroup<=127&&s.dominanceGroup>=-127?t.setDominanceGroup(Math.floor(s.dominanceGroup)):t.setDominanceGroup(0),s.autoMass){t.setAdditionalMass(0,!1);for(let i=0;i<t.numColliders();i++)t.collider(i).setDensity(1);t.recomputeMassPropertiesFromColliders()}else{t.setAdditionalMass(s.mass,!1);for(let i=0;i<t.numColliders();i++)t.collider(i).setDensity(1e-7);t.recomputeMassPropertiesFromColliders()}t.setEnabledRotations(!s.lockRotationX,!s.lockRotationY,!s.lockRotationZ,!1),t.setEnabledTranslations(!s.lockPositionX,!s.lockPositionY,!s.lockPositionZ,!1),s.isKinematic?t.setBodyType(D.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased,!1):t.setBodyType(D.RAPIER_PHYSICS.MODULE.RigidBodyType.Dynamic,!1)}step(s){if(this.world&&this.enabled){if(this._isUpdatingPhysicsWorld=!0,this.eventQueue||(this.eventQueue=new D.RAPIER_PHYSICS.MODULE.EventQueue(!1)),s===void 0||s<=0){this._isUpdatingPhysicsWorld=!1;return}else s!==void 0&&(this.world.timestep=W.lerp(this.world.timestep,s,.8));try{this.world.step(this.eventQueue)}catch(t){console.warn("Error running physics step",t)}this._isUpdatingPhysicsWorld=!1}}postStep(){this.world&&this.enabled&&(this._isUpdatingPhysicsWorld=!0,this.syncObjects(),this._isUpdatingPhysicsWorld=!1,this.eventQueue&&!this.collisionHandler&&(this.collisionHandler=new Nj(this.world,this.eventQueue)),this.collisionHandler&&(this.collisionHandler.handleCollisionEvents(),this.collisionHandler.update()),this.updateDebugRendering(this.world))}updateDebugRendering(s){var t,i,n,o;if(Lt||Ey||Uj||this.debugRenderColliders===!0){if(!this.lines){const l=new qy({color:7855479,fog:!1}),c=new gn;this.lines=new $y(c,l),this.lines.layers.disableAll(),this.lines.layers.enable(2)}this.lines.parent!==((t=this.context)==null?void 0:t.scene)&&((i=this.context)==null||i.scene.add(this.lines));const r=s.debugRender();this.lines.geometry.setAttribute("position",new ft(r.vertices,3)),this.lines.geometry.setAttribute("color",new ft(r.colors,4)),(this.context.time.frame%30===0||((n=this.lines.geometry.boundingSphere)==null?void 0:n.radius)===0)&&this.lines.geometry.computeBoundingSphere()}else this.lines&&((o=this.context)==null||o.scene.remove(this.lines))}syncObjects(){if(!Ey)for(let s=0;s<this.bodies.length;s++){const t=this.objects[s],i=this.bodies[s],n=t;if(n?.isCollider===!0&&!n.attachedRigidbody){const c=i.parent();c?this.syncPhysicsBody(t.gameObject,c,!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&&F()&&(console.warn("Collider has NaN values",n.name,n.gameObject,i),n.__COLLIDER_NAN=!0);continue}const l=t.center;if(l&&l.isVector3){this._tempQuaternion.set(r.x,r.y,r.z,r.w);const c=this._tempPosition.copy(l).applyQuaternion(this._tempQuaternion),h=Ye(t.gameObject);c.multiply(h),o.x-=c.x,o.y-=c.y,o.z-=c.z}lr(t.gameObject,o.x,o.y,o.z),Um(t.gameObject,r.x,r.y,r.z,r.w)}}syncPhysicsBody(s,t,i,n){if(t instanceof D.RAPIER_PHYSICS.MODULE.RigidBody){const o=te(s,this._tempPosition),r=Ce(s,this._tempQuaternion);switch(t.bodyType()){case D.RAPIER_PHYSICS.MODULE.RigidBodyType.Fixed:case D.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased:case D.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 D.RAPIER_PHYSICS.MODULE.Collider){s.matrixWorldNeedsUpdate&&s.updateWorldMatrix(!0,!1),s.matrixWorld.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const o=this._tempPosition,r=this._tempQuaternion,l=t[bi];if(this.tryApplyCenter(l,o),i){const c=t.translation();(c.x!==o.x||c.y!==o.y||c.z!==o.z)&&t.setTranslation(o)}if(n){const c=t.rotation();(c.x!==r.x||c.y!==r.y||c.z!==r.z||c.w!==r.w)&&t.setRotation(r)}}}tryApplyCenter(s,t){const i=s.center;i&&s.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,Ye(s.gameObject,this._tempCenterVec),this._tempCenterPos.multiply(this._tempCenterVec),s.attachedRigidbody?this._tempCenterPos.applyQuaternion(s.gameObject.quaternion):(Ce(s.gameObject,this._tempCenterQuaternion),this._tempCenterPos.applyQuaternion(this._tempCenterQuaternion)),t.x+=this._tempCenterPos.x,t.y+=this._tempCenterPos.y,t.z+=this._tempCenterPos.z)}getRigidbodyRelativeMatrix(s,t,i,n){if(n===void 0&&(n=Jp._matricesBuffer,n.length=0),s===t){const o=Ye(s,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(s.matrix),s.parent&&this.getRigidbodyRelativeMatrix(s.parent,t,i,n),i}addFixedJoint(s,t){if(!this.world){console.error("Physics world not initialized");return}const i=s[ii],n=t[ii];this.calculateJointRelativeMatrices(s.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const o=D.RAPIER_PHYSICS.MODULE.JointData.fixed(Jp.centerConnectionPos,Jp.centerConnectionRot,this._tempPosition,this._tempQuaternion),r=this.world.createImpulseJoint(o,i,n,!0);Lt&&console.log("ADD FIXED JOINT",r)}addHingeJoint(s,t,i,n){if(!this.world){console.error("Physics world not initialized");return}const o=s[ii],r=t[ii];this.calculateJointRelativeMatrices(s.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const l=D.RAPIER_PHYSICS.MODULE.JointData.revolute(i,this._tempPosition,n),c=this.world.createImpulseJoint(l,o,r,!0);Lt&&console.log("ADD HINGE JOINT",c)}calculateJointRelativeMatrices(s,t,i){s.updateWorldMatrix(!0,!1),t.updateWorldMatrix(!0,!1);const n=s.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()}};let ed=Jp;a(ed,"_didLoadPhysicsEngine",!1),a(ed,"_matricesBuffer",[]),a(ed,"centerConnectionPos",{x:0,y:0,z:0}),a(ed,"centerConnectionRot",{x:0,y:0,z:0,w:1});class Nj{constructor(t,i){a(this,"world"),a(this,"eventQueue"),a(this,"activeCollisions",[]),a(this,"activeCollisionsStay",[]),a(this,"activeTriggers",[]),this.world=t,this.eventQueue=i}handleCollisionEvents(){this.eventQueue&&this.world&&this.eventQueue.drainCollisionEvents((t,i,n)=>{const o=this.world.getCollider(t),r=this.world.getCollider(i);if(!o||!r)return;const l=o[bi],c=r[bi];Ay&&console.log("EVT",l.name,c.name,n,o,r),l&&c&&(n?(this.onCollisionStarted(l,o,c,r),this.onCollisionStarted(c,r,l,o)):(this.onCollisionEnded(l,c),this.onCollisionEnded(c,l)))})}update(){this.onHandleCollisionStay()}onCollisionStarted(t,i,n,o){let r=null;if(t.isTrigger||n.isTrigger)br(t.gameObject,l=>{l.onTriggerEnter&&!l.destroyed&&l.onTriggerEnter(n),this.activeTriggers.push({collider:t,component:l,otherCollider:n})});else{const l=t.gameObject;this.world.contactPair(i,o,(c,h)=>{br(l,d=>{var u;if(d.destroyed)return;const p=d.onCollisionEnter||d.onCollisionStay||d.onCollisionExit;if(p||Ay){if(!r){const g=[],y=c.normal();n instanceof Ro&&n.convex&&(y.x=-y.x,y.y=-y.y,y.z=-y.z);for(let f=0;f<c.numSolverContacts();f++){const v=c.solverContactPoint(f),b=c.contactImpulse(f);if(v){const w=c.contactDist(f),_=c.solverContactFriction(f),S=c.solverContactTangentVelocity(f),R=new Dw(v,w,y,b,_,S);g.push(R),Ay&&q.DrawDirection(v,y,16711680,3,!0)}}r=new Bw(l,n,g)}if(p){const g={collider:t,component:d,collision:r};this.activeCollisions.push(g),d.onCollisionStay&&this.activeCollisionsStay.push(g),(u=d.onCollisionEnter)==null||u.call(d,r)}}})})}}onHandleCollisionStay(){for(const t of this.activeCollisionsStay){const i=t.component;if(!i.destroyed&&i.activeAndEnabled&&i.onCollisionStay){if(t.collision.collider.destroyed)continue;const n=t.collision;i.onCollisionStay(n)}}for(const t of this.activeTriggers){const i=t.component;if(!i.destroyed&&i.activeAndEnabled&&i.onTriggerStay){const n=t.otherCollider;if(n.destroyed)continue;i.onTriggerStay(n)}}}onCollisionEnded(t,i){if(!(t.destroyed||i.destroyed)){for(let n=0;n<this.activeCollisions.length;n++){const o=this.activeCollisions[n],r=o.collider;if(r.destroyed||o.collision.collider.destroyed){this.activeCollisions.splice(n,1),n--;continue}if(r===t&&o.collision.collider===i){const l=o.component;if(this.activeCollisions.splice(n,1),n--,l.activeAndEnabled&&l.onCollisionExit){const c=o.collision;l.onCollisionExit(c)}}}for(let n=0;n<this.activeCollisionsStay.length;n++){const o=this.activeCollisionsStay[n],r=o.collider;if(r.destroyed||o.collision.collider.destroyed){this.activeCollisionsStay.splice(n,1),n--;continue}if(r===t&&o.collision.collider===i){const l=o.component;if(this.activeCollisionsStay.splice(n,1),n--,l.activeAndEnabled&&l.onCollisionExit){const c=o.collision;l.onCollisionExit(c)}}}for(let n=0;n<this.activeTriggers.length;n++){const o=this.activeTriggers[n],r=o.collider;if(r.destroyed||o.otherCollider.destroyed){this.activeTriggers.splice(n,1),n--;continue}if(r===t&&o.otherCollider===i){const l=o.component;if(this.activeTriggers.splice(n,1),n--,l.activeAndEnabled&&l.onTriggerExit){const c=o.otherCollider;l.onTriggerExit(c)}}}}}}class Wj{static async createComparisonScene(t){const{files:i}=t,n=await Promise.all(i.map(f=>new le(f).loadAssetAsync())),o=new Vi;let r=0;for(const f of n)if(f instanceof I){f.position.y=r,o.add(f);const v=oi([f]);r+=v.getSize(new x).y,r+=.1}const l=new _e(20);o.add(l);const c=t.environment||"https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/studio_small_09_1k.exr";if(c){let f=null;if(c.endsWith(".hdr")){const v=(await import("./three-examples.light.min.js").then(b=>b.q)).RGBELoader;f=new v}else if(c.endsWith(".exr")){const v=(await import("./three-examples.light.min.js").then(b=>b.p)).EXRLoader;f=new v}if(f){const v=await f.loadAsync(c).catch(b=>(console.error(b),null));v&&(v.mapping=yn,v.needsUpdate=!0,o.background=v,o.environment=v,o.backgroundBlurriness=.75)}else console.warn("Unsupported environment map format",c)}const h=oi(o.children),d=h.getCenter(new x),u=h.getSize(new x),p=Math.max(u.x,u.y,u.z)/(2*Math.tan(Math.PI*l.fov/360));l.position.set(d.x,d.y,p),l.lookAt(d);const g=new ov(l,t.domElement||document.body);g.target=d,g.update();const y=(t.domElement||document.body).getBoundingClientRect();return l.aspect=y.width/y.height,l.updateProjectionMatrix(),{scene:o,camera:l}}}let jy=0;function oS(s){s?jy++:jy--}function Vj(){return jy>0}const Hj={binary:!0,animations:!0};async function $j(s){if(!s.context)throw new Error("No context provided to exportAsGLTF");s.scene||(s.scene=s.context.scene);const t={...Hj,...s},{context:i}=t,n=new rv;n.register(c=>new ax(c)),n.register(c=>new xR(c)),n.register(c=>new ex(c)),Wf(n,t.context);const o={binary:t.binary,animations:Gj(i,t.scene,[])},r=new qj;console.debug("Exporting GLTF",o),r.onBeforeExport(t),oS(!0);const l=await n.parseAsync(t.scene,o).catch(c=>(console.error(c),null));if(oS(!1),r.onAfterExport(t),!l)throw new Error("Failed to export GLTF");if(t.downloadAs!=null){let c=null;if(l instanceof ArrayBuffer?c=new Blob([l],{type:"application/octet-stream"}):console.error("Can not download GLTF as a blob",l),c){const h=URL.createObjectURL(c),d=document.createElement("a");d.href=h;let u=t.downloadAs;!u.endsWith(".glb")&&!u.endsWith(".gltf")&&(u+=t.binary?".glb":".gltf"),d.download=u,d.click()}}return l}const rS=Symbol("needle:weight");class qj{constructor(){a(this,"_undo",[])}onBeforeExport(t){t.context.animations.mixers.forEach(i=>{const n=Ba.tryGetActionsFromMixer(i);if(n)for(let o=0;o<n.length;o++){const r=n[o];r[rS]=r.weight,r.weight=0,this._undo.push(()=>{r.weight=r[rS]})}i.update(0)}),t.context.scene.traverse(i=>{if(!Bf(i)){const n=i.parent;n&&(i.removeFromParent(),this._undo.push(()=>n.add(i)))}})}onAfterExport(t){this._undo.forEach(i=>i()),this._undo.length=0}}function Gj(s,t,i){s.animations.mixers.forEach(o=>{const r=Ba.tryGetActionsFromMixer(o);if(r)for(let l=0;l<r.length;l++){const c=r[l].getClip();i.push(c)}}),Array.isArray(t)||(t=[t]);for(const o of t)Ba.tryGetAnimationClipsFromObjectHierarchy(o,i);const n=new Set(i);return Array.from(n)}const aS="needle-button",Ly=F();var la,ca,ha,_i,Ls,Nl,Dy,lS,By,cS,em;class Fy extends HTMLElement{constructor(){super(),Wi(this,Dy),Wi(this,By),Wi(this,la,void 0),Wi(this,ca,void 0),Wi(this,ha,void 0),Wi(this,_i,void 0),Wi(this,Ls,void 0),Wi(this,Nl,void 0),Wi(this,em,t=>{Ly&&console.log("Needle Button clicked"),!t.defaultPrevented&&me(this,_i)&&me(this,_i).click()}),this.removeEventListener("click",me(this,em)),this.addEventListener("click",me(this,em))}attributeChangedCallback(t,i,n){pa(this,Dy,lS).call(this)}}la=new WeakMap,ca=new WeakMap,ha=new WeakMap,_i=new WeakMap,Ls=new WeakMap,Nl=new WeakMap,Dy=new WeakSet,lS=function(){var s,t;if((s=me(this,_i))==null||s.remove(),this.getAttribute("ar")!=null)me(this,Ls)??Bs(this,Ls,new zr),Bs(this,_i,me(this,Ls).createARButton());else if(this.getAttribute("vr")!=null)me(this,Ls)??Bs(this,Ls,new zr),Bs(this,_i,me(this,Ls).createVRButton());else if(this.getAttribute("quicklook")!=null)me(this,Ls)??Bs(this,Ls,new zr),Bs(this,_i,me(this,Ls).createQuicklookButton());else{Ly?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.");return}me(this,la)??Bs(this,la,this.attachShadow({mode:"open"})),me(this,ca)??Bs(this,ca,document.createElement("slot")),me(this,ha)??Bs(this,ha,document.createElement("style")),me(this,ha).innerHTML=`
1474
+ `,o)}}setPublicKey(){cc.length>0&&this.setAttribute("public-key",cc)}setVersion(){bs.length>0&&this.setAttribute("version",bs)}getAROverlayContainer(){return this._overlay_ar.createOverlayContainer(this)}getVROverlayContainer(){for(let t=0;t<this.children.length;t++){const i=this.children[t];if(i.classList.contains("vr"))return i}return null}onEnterAR(t){var i;this.onSetupAR();const n=this.getAROverlayContainer();this._overlay_ar.onBegin(this._context,n,t),this.dispatchEvent(new CustomEvent("enter-ar",{detail:{session:t,context:this._context,htmlContainer:(i=this._overlay_ar)==null?void 0:i.ARContainer}}))}onExitAR(t){var i;this._overlay_ar.onEnd(this._context),this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-ar",{detail:{session:t,context:this._context,htmlContainer:(i=this._overlay_ar)==null?void 0:i.ARContainer}}))}onEnterVR(t){this.onSetupVR(),this.dispatchEvent(new CustomEvent("enter-vr",{detail:{session:t,context:this._context}}))}onExitVR(t){this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-vr",{detail:{session:t,context:this._context}}))}onSetupAR(){this.classList.add(Yh),this.classList.remove(Zh);const t=this.getAROverlayContainer();Ue&&console.warn("onSetupAR:",t),t&&(t.classList.add(Yh),t.classList.remove(Zh)),this.foreachHtmlElement(i=>this.setupElementsForMode(i,uw))}onSetupVR(){this.classList.remove(Yh),this.classList.remove(Zh),this.foreachHtmlElement(t=>this.setupElementsForMode(t,tS))}onSetupDesktop(){this.classList.remove(Yh),this.classList.add(Zh);const t=this.getAROverlayContainer();t&&(t.classList.remove(Yh),t.classList.add(Zh)),this.foreachHtmlElement(i=>this.setupElementsForMode(i,iS))}setupElementsForMode(t,i,n=null){var o,r;if(!(t===((r=(o=this._context)==null?void 0:o.renderer)==null?void 0:r.domElement)||t.id==="VRButton"||t.id==="ARButton"))if(t.classList.contains(i))t.style.visibility="visible",t.style.display==="none"&&(t.style.display="block");else for(const l of Ej)t.classList.contains(l)&&(t.style.visibility="hidden",t.style.display="none")}foreachHtmlElement(t){for(let i=0;i<this.children.length;i++){const n=this.children[i];n.style&&t(n)}}onBeforeBeginLoading(){const t=this.getAttribute("dracoDecoderPath");t&&(Ue&&console.log("using custom draco decoder path",t),mw(t));const i=this.getAttribute("dracoDecoderType");i&&(Ue&&console.log("using custom draco decoder type",i),gw(i));const n=this.getAttribute("ktx2DecoderPath");n&&(Ue&&console.log("using custom ktx2 decoder path",n),fw(n))}}typeof window<"u"&&!window.customElements.get(eS)&&window.customElements.define(eS,Ty);function Ij(s){if(s.startsWith("blob:"))return"blob";const t=s.split("/");let i=t[t.length-1];const n=i.indexOf("?");n>0&&(i=i.substring(0,n));const o=i.indexOf("=");o>0&&(i=i.substring(o));const r=i.split(".").pop(),l=r?["glb","gltf","usdz","usd","fbx","obj","mtl"].indexOf(r.toLowerCase()):-1;if(r&&l>=0&&(i=i.substring(0,i.length-r.length-1)),i=decodeURIComponent(i),i.length>3){let c="",h=!1;const d=["(",")","[","]","{","}",":",";",",",".","!","?"];for(let u=0;u<i.length;u++){let p=i[u];(p==="_"||p==="-")&&(p=" "),!(p===" "&&c.length<=0||d.includes(p)||(c.length===0&&(p=p.toUpperCase()),h&&p===" "))&&(h&&(p=p.toUpperCase()),h=!1,c+=p,p===" "&&(h=!0))}return F()&&i!==c&&console.debug('Generated display name: "'+i+'" \u2192 "'+c+'"'),c.trim()}return F()&&console.debug("Loading: use default name",i),i}const jj=Object.freeze(Object.defineProperty({__proto__:null,NeedleEngineHTMLElement:Ty},Symbol.toStringTag,{value:"Module"}));function Lj(){Pn.registerWaitForInteraction(()=>{const s=TC.getContext();s.addEventListener("statechange",()=>{setTimeout(()=>{const t=s.state;(t==="suspended"||t==="interrupted")&&s.resume().then(()=>{console.log("AudioContext resumed successfully")}).catch(i=>{console.log("Failed to resume AudioContext: "+i)})},500)})})}setTimeout(Lj,1e3);const Kp=C("debughotreload");let Kh=!1;const Jh=new Map;function Dj(){return Kh}function Bj(s){var t;if(Kh)return;const i=s.constructor.name;Jh.has(i)?(t=Jh.get(i))==null||t.push(s):Jh.set(i,[s])}function Fj(s){if(Kh)return;const t=s.constructor.name,i=Jh.get(t);if(!i)return;const n=i.indexOf(s);n!==-1&&i.splice(n,1)}let sS=!1;function zj(){if(Kp||sS)return;sS=!0;const s=console.error;console.error=(...t)=>{if(t.length){const i=t[0];if(typeof i=="string"&&i.includes("[hmr] Failed to reload ")){console.log("[Needle Engine] Hot reloading failed"),window.location.reload();return}}s.apply(console,t)}}function Uj(s){Kp&&console.log("[HMR] Apply changes",s,Object.keys(s)),zj();for(const t of Object.keys(s))try{Kh=!0;const i=k.get(t);if(!i){Kp&&console.log("[HMR] Type not found: "+t);continue}const n=s[t],o=Jh.get(n.name);let r="[Needle Engine] Updating type: "+t;const l=o?.length??-1;l>0?r+=" x"+l:r+=" - no instances",console.log(r);const c=Object.getOwnPropertyNames(i.prototype),h=Object.getOwnPropertyDescriptors(n.prototype);for(const d in h)h[d].writable&&(i.prototype[d]=s[t].prototype[d]);for(const d of c)h[d]||delete i.prototype[d];if(o){const d=new n,u=Object.getOwnPropertyDescriptors(d);for(const p of o){const g=p,y=g.isComponent===!0,f=y?g.activeAndEnabled:!0,v=y?g.context:void 0;try{if(y&&v&&Cn(g,v),y&&f&&(g.enabled=!1),p.onBeforeHotReloadFields&&p.onBeforeHotReloadFields()===!1)continue;for(const b in u)if(u[b].writable){if(p[b]===void 0)p[b]=d[b];else if(typeof p[b]=="function"&&!p[b].prototype){const w=p[b],_=w.name,S="bound ";if(_===S)continue;const R=w.name.substring(S.length),M=n.prototype[R];M&&(p[b]=M.bind(p))}}p.onAfterHotReloadFields&&p.onAfterHotReloadFields()}finally{y&&v&&Cg(g,v),y&&f&&(g.enabled=!0)}}}}catch(i){if(Kp)console.error(i);else return!1}finally{Kh=!1,zs(Oi.Log,"Script changes applied (HMR)")}return!0}const Lt=C("debugphysics"),Ey=C("debugcolliderplacement"),Ay=C("debugcollisions"),Nj=C("showcolliders"),Iy=C("debugraycasts"),bi=Symbol("needle component"),ii=Symbol("physics body"),nS=Symbol("rigidbody");globalThis.false=globalThis.false!==void 0?globalThis.false:!0,Lt&&console.log("Use Rapier",!1,globalThis.false);const Jp=class{constructor(s){a(this,"debugRenderColliders",!1),a(this,"debugRenderRaycasts",!1),a(this,"context"),a(this,"_initializePromise"),a(this,"_isInitialized",!1),a(this,"rapierRay"),a(this,"raycastVectorsBuffer",new Ci(()=>new x,10)),a(this,"rapierSphere",null),a(this,"rapierColliderArray",[]),a(this,"rapierIdentityRotation",{x:0,y:0,z:0,w:1}),a(this,"rapierForwardVector",{x:0,y:0,z:1}),a(this,"enabled",!1),a(this,"_tempPosition",new x),a(this,"_tempQuaternion",new V),a(this,"_tempScale",new x),a(this,"_tempMatrix",new ne),a(this,"_isUpdatingPhysicsWorld",!1),a(this,"_world"),a(this,"_hasCreatedWorld",!1),a(this,"eventQueue"),a(this,"collisionHandler"),a(this,"objects",[]),a(this,"bodies",[]),a(this,"_meshCache",new Map),a(this,"_gravity",{x:0,y:-9.81,z:0}),a(this,"lines"),a(this,"_tempCenterPos",new x),a(this,"_tempCenterVec",new x),a(this,"_tempCenterQuaternion",new V),this.context=s}removeBody(s){var t,i,n;if(!s)return;this.validate();const o=s[ii];if(s[ii]=null,o&&this.world){const r=this.objects.findIndex(l=>l===s);if(r>=0){const l=this.bodies[r];if(this.bodies.splice(r,1),this.objects.splice(r,1),l instanceof j.RAPIER_PHYSICS.MODULE.Collider){const c=l;(t=this.world)==null||t.removeCollider(c,!0);const h=c.parent();h&&h.numColliders()<=0&&(h[bi]||(i=this.world)==null||i.removeRigidBody(h))}else l instanceof j.RAPIER_PHYSICS.MODULE.RigidBody&&(l.numColliders()<=0?(n=this.world)==null||n.removeRigidBody(l):F()&&(l.did_log_removing||setTimeout(()=>{l.numColliders()>0&&(l.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(s,t,i){if(this.validate(),!!this.enabled&&!(s.destroyed||!s.gameObject)&&!(!t&&!i))if(s.isCollider===!0)console.warn("TODO: implement updating collider position");else{const n=s,o=n[ii];o&&this.syncPhysicsBody(n.gameObject,o,t,i)}}updateProperties(s){if(this.validate(),s.isCollider){const t=s,i=t[ii];i&&(this.internalUpdateColliderProperties(t,i),t.sharedMaterial&&this.updatePhysicsMaterial(t))}else{const t=s,i=this.internal_getRigidbody(t);i&&this.internalUpdateRigidbodyProperties(t,i)}}addForce(s,t,i){this.validate();const n=this.internal_getRigidbody(s);n?n.addForce(t,i):console.warn("Rigidbody doesn't exist: can not apply force (does your object with the Rigidbody have a collider?)")}addImpulse(s,t,i){this.validate();const n=this.internal_getRigidbody(s);n?n.applyImpulse(t,i):console.warn("Rigidbody doesn't exist: can not apply impulse (does your object with the Rigidbody have a collider?)")}getLinearVelocity(s){this.validate();const t=this.internal_getRigidbody(s);return t?t.linvel():null}getAngularVelocity(s){this.validate();const t=this.internal_getRigidbody(s);return t?t.angvel():null}resetForces(s,t){this.validate();const i=this.internal_getRigidbody(s);i?.resetForces(t)}resetTorques(s,t){this.validate();const i=this.internal_getRigidbody(s);i?.resetTorques(t)}applyImpulse(s,t,i){this.validate();const n=this.internal_getRigidbody(s);n?n.applyImpulse(t,i):console.warn("Rigidbody doesn't exist: can not apply impulse (does your object with the Rigidbody have a collider?)")}wakeup(s){this.validate();const t=this.internal_getRigidbody(s);t?t.wakeUp():console.warn("Rigidbody doesn't exist: can not wake up (does your object with the Rigidbody have a collider?)")}isSleeping(s){this.validate();const t=this.internal_getRigidbody(s);return t?.isSleeping()}setAngularVelocity(s,t,i){this.validate();const n=this.internal_getRigidbody(s);n?n.setAngvel(t,i):console.warn("Rigidbody doesn't exist: can not set angular velocity (does your object with the Rigidbody have a collider?)")}setLinearVelocity(s,t,i){this.validate();const n=this.internal_getRigidbody(s);n?n.setLinvel(t,i):console.warn("Rigidbody doesn't exist: can not set linear velocity (does your object with the Rigidbody have a collider?)")}get isInitialized(){return this._isInitialized}async initialize(){return this._initializePromise||(this._initializePromise=this.internalInitialization()),this._initializePromise}async internalInitialization(){return C("__nophysics")?(console.warn("Physics are disabled"),!1):(Lt&&console.log("Initialize rapier physics engine"),"env"in import.meta&&{}.VITE_NEEDLE_USE_RAPIER==="false"&&Lt&&console.log("Rapier disabled"),!1)}validate(){this._isInitialized||Lt&&(this._lastWarnTime=this._lastWarnTime??0,Date.now()-this._lastWarnTime>1e3&&(this._lastWarnTime=Date.now(),console.warn("Physics engine is not initialized")))}raycast(s,t,i){var n;if(!this._isInitialized)return console.log("Physics engine is not initialized"),null;let o=i?.maxDistance,r=i?.solid;o===void 0&&(o=1/0),r===void 0&&(r=!0);const l=this.getPhysicsRay(this.rapierRay,s,t);if(!l)return null;(this.debugRenderRaycasts||Iy)&&q.DrawRay(l.origin,l.dir,255,1);const c=(n=this.world)==null?void 0:n.castRay(l,o,r,i?.queryFilterFlags,i?.filterGroups,void 0,void 0,h=>{const d=h[bi];return i!=null&&i.filterPredicate?i.filterPredicate(d):i?.useIgnoreRaycastLayer!==!1?!(d!=null&&d.gameObject.layers.isEnabled(2)):!0});if(c){const h=l.pointAt(c.timeOfImpact),d=this.raycastVectorsBuffer.get();return d.set(h.x,h.y,h.z),{point:d,collider:c.collider[bi]}}return null}raycastAndGetNormal(s,t,i){var n;if(!this._isInitialized)return null;let o=i?.maxDistance,r=i?.solid;o===void 0&&(o=1/0),r===void 0&&(r=!0);const l=this.getPhysicsRay(this.rapierRay,s,t);if(!l)return null;(this.debugRenderRaycasts||Iy)&&q.DrawRay(l.origin,l.dir,255,1);const c=(n=this.world)==null?void 0:n.castRayAndGetNormal(l,o,r,i?.queryFilterFlags,i?.filterGroups,void 0,void 0,h=>{const d=h[bi];return i!=null&&i.filterPredicate?i.filterPredicate(d):i?.useIgnoreRaycastLayer!==!1?!(d!=null&&d.gameObject.layers.isEnabled(2)):!0});if(c){const h=l.pointAt(c.timeOfImpact),d=c.normal,u=this.raycastVectorsBuffer.get(),p=this.raycastVectorsBuffer.get();return u.set(h.x,h.y,h.z),p.set(d.x,d.y,d.z),{point:u,normal:p,collider:c.collider[bi]}}return null}getPhysicsRay(s,t,i){var n,o,r;const l=(n=this.context)==null?void 0:n.mainCamera;if(t===void 0){const d=(o=this.context)==null?void 0:o.input.getPointerPosition(0);if(d)t=d;else return null}if(t.z===void 0){if(!l)return console.error("Can not perform raycast from 2d point - no main camera found"),null;const d=this.raycastVectorsBuffer.get();d.x=t.x,d.y=t.y,d.z=0,(d.x>1||d.y>1||d.y<-1||d.x<-1)&&(Lt&&console.warn("Converting screenspace to raycast space",d),(r=this.context)==null||r.input.convertScreenspaceToRaycastSpace(d)),d.unproject(l),t=d}const c=t;s.origin.x=c.x,s.origin.y=c.y,s.origin.z=c.z;const h=this.raycastVectorsBuffer.get();if(i)h.set(i.x,i.y,i.z);else{if(!l)return console.error("Can not perform raycast - no camera found"),null;h.set(s.origin.x,s.origin.y,s.origin.z);const d=te(l);h.sub(d)}return h.normalize(),s.dir.x=h.x,s.dir.y=h.y,s.dir.z=h.z,s}sphereOverlap(s,t){return this.rapierColliderArray.length=0,this._isInitialized?this.world?(this.rapierSphere??(this.rapierSphere=new j.RAPIER_PHYSICS.MODULE.Ball(t)),this.rapierSphere.radius=t,(this.debugRenderRaycasts||Iy)&&q.DrawWireSphere(s,t,3359999,1),this.world.intersectionsWithShape(s,this.rapierIdentityRotation,this.rapierSphere,i=>{const n=i[bi],o=new Fw(n.gameObject,n);return this.rapierColliderArray.push(o),!0},void 0,void 0,void 0,void 0,i=>i.isSensor()?!1:i[bi].gameObject.layers.isEnabled(2)==!1),this.rapierColliderArray):this.rapierColliderArray:this.rapierColliderArray}get world(){return this._world}get isUpdating(){return this._isUpdatingPhysicsWorld}get gravity(){var s;return((s=this.world)==null?void 0:s.gravity)??this._gravity}set gravity(s){this.world?this.world.gravity=s:this._gravity=s}clearCaches(){var s,t,i,n;this._meshCache.clear(),(s=this.eventQueue)!=null&&s.raw&&((t=this.eventQueue)==null||t.free()),(i=this.world)!=null&&i.bodies&&((n=this.world)==null||n.free())}async addBoxCollider(s,t){if(this._isInitialized||await this.initialize(),!s.activeAndEnabled)return;if(!this.enabled){Lt&&console.warn("Physics are disabled");return}const i=s.gameObject,n=Ye(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)),n.x==0&&(n.x=1e-7),n.y==0&&(n.y=1e-7),n.z==0&&(n.z=1e-7);const o=j.RAPIER_PHYSICS.MODULE.ColliderDesc.cuboid(n.x,n.y,n.z);this.createCollider(s,o)}async addSphereCollider(s){if(this._isInitialized||await this.initialize(),!s.activeAndEnabled)return;if(!this.enabled){Lt&&console.warn("Physics are disabled");return}const t=j.RAPIER_PHYSICS.MODULE.ColliderDesc.ball(.5);this.createCollider(s,t),this.updateProperties(s)}async addCapsuleCollider(s,t,i){if(this._isInitialized||await this.initialize(),!s.activeAndEnabled)return;if(!this.enabled){Lt&&console.warn("Physics are disabled");return}const n=s.gameObject,o=Ye(n,this._tempPosition);o.x=Math.abs(o.x),o.y=Math.abs(o.y);const r=i*o.x;t=Math.max(t,r*2);const l=W.clamp(t*.5*o.y-i*o.x,0,Number.MAX_SAFE_INTEGER),c=j.RAPIER_PHYSICS.MODULE.ColliderDesc.capsule(l,r);this.createCollider(s,c)}async addMeshCollider(s,t,i,n){var o,r,l;let c=t.geometry;if(!c){Lt&&console.warn("Missing mesh geometry",t.name);return}(r=(o=c.index)==null?void 0:o.array)!=null&&r.length||(console.warn(`Your MeshCollider is missing vertices or indices in the assined mesh "${t.name}". Consider providing an indexed geometry.`),c=eO(c));let h=null;const d=c.getAttribute("position");if(d instanceof Gy){const y=d.count;h=new Float32Array(y*3);for(let f=0;f<y;f++){const v=d.getX(f),b=d.getY(f),w=d.getZ(f);h[f*3]=v,h[f*3+1]=b,h[f*3+2]=w}}else h=d.array;if(await this.initialize(),!this.enabled){Lt&&console.warn("Physics are disabled");return}if(!s.activeAndEnabled)return;const u=(l=c.index)==null?void 0:l.array,p=s.gameObject.worldScale.clone();if(n&&p.multiply(n),Math.abs(p.x-1)>1e-4||Math.abs(p.y-1)>1e-4||Math.abs(p.z-1)>1e-4){const y=`${c.uuid}_${p.x}_${p.y}_${p.z}_${i}`;if(this._meshCache.has(y))Lt&&console.warn("Use cached mesh collider"),h=this._meshCache.get(y);else{(Lt||F())&&console.debug(`[Performance] Your MeshCollider "${s.name}" is scaled: consider applying the scale to the collider mesh instead (${p.x}, ${p.y}, ${p.z})`);const f=new Float32Array(h.length);for(let v=0;v<h.length;v+=3)f[v]=h[v]*p.x,f[v+1]=h[v+1]*p.y,f[v+2]=h[v+2]*p.z;h=f,this._meshCache.set(y,f)}}const g=i?j.RAPIER_PHYSICS.MODULE.ColliderDesc.convexHull(h):j.RAPIER_PHYSICS.MODULE.ColliderDesc.trimesh(h,u);g&&this.createCollider(s,g)}updatePhysicsMaterial(s){if(!s)return;const t=s.sharedMaterial,i=s[ii];if(i&&t){if(t.bounciness!==void 0&&i.setRestitution(t.bounciness),t.bounceCombine!==void 0)switch(t.bounceCombine){case _t.Average:i.setRestitutionCombineRule(j.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case _t.Maximum:i.setRestitutionCombineRule(j.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case _t.Minimum:i.setRestitutionCombineRule(j.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case _t.Multiply:i.setRestitutionCombineRule(j.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(t.dynamicFriction!==void 0&&i.setFriction(t.dynamicFriction),t.frictionCombine!==void 0)switch(t.frictionCombine){case _t.Average:i.setFrictionCombineRule(j.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case _t.Maximum:i.setFrictionCombineRule(j.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case _t.Minimum:i.setFrictionCombineRule(j.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case _t.Multiply:i.setFrictionCombineRule(j.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}}}getBody(s){return s?s[ii]:null}getComponent(s){return s?s[bi]:null}createCollider(s,t){var i;if(!this.world)throw new Error("Physics world not initialized");const n=this._tempMatrix;let o;s.attachedRigidbody?o=this.getRigidbody(s,this._tempMatrix):(Lt&&console.log("Create collider without rigidbody",s.name),n.makeRotationFromQuaternion(Ce(s.gameObject)),n.setPosition(te(s.gameObject))),n.decompose(this._tempPosition,this._tempQuaternion,this._tempScale),this.tryApplyCenter(s,this._tempPosition),t.setTranslation(this._tempPosition.x,this._tempPosition.y,this._tempPosition.z),t.setRotation(this._tempQuaternion),t.setSensor(s.isTrigger);const r=s.sharedMaterial;if(r){if(r.bounciness!==void 0&&t.setRestitution(r.bounciness),r.bounceCombine!==void 0)switch(r.bounceCombine){case _t.Average:t.setRestitutionCombineRule(j.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case _t.Maximum:t.setRestitutionCombineRule(j.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case _t.Minimum:t.setRestitutionCombineRule(j.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case _t.Multiply:t.setRestitutionCombineRule(j.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(r.dynamicFriction!==void 0&&t.setFriction(r.dynamicFriction),r.frictionCombine!==void 0)switch(r.frictionCombine){case _t.Average:t.setFrictionCombineRule(j.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case _t.Maximum:t.setFrictionCombineRule(j.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case _t.Minimum:t.setFrictionCombineRule(j.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case _t.Multiply:t.setFrictionCombineRule(j.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}}((i=s.attachedRigidbody)==null?void 0:i.autoMass)===!1&&(t.setDensity(1e-6),t.setMass(1e-6));try{const l=this.world.createCollider(t,o);return l[bi]=s,s[ii]=l,l.setActiveEvents(j.RAPIER_PHYSICS.MODULE.ActiveEvents.COLLISION_EVENTS),l.setActiveCollisionTypes(j.RAPIER_PHYSICS.MODULE.ActiveCollisionTypes.ALL),this.objects.push(s),this.bodies.push(l),this.updateColliderCollisionGroups(s),l}catch(l){return console.error('Error creating collider "'+s.name+`"
1475
+ Error:`,l),null}}updateColliderCollisionGroups(s){const t=s[ii],i=s.membership;let n=0;if(i==null)n=65535;else for(let l=0;l<i.length;l++){const c=i[l];c>31?console.error(`Rapier only supports 32 layers, layer ${c} is not supported`):n|=1<<Math.floor(c)}const o=s.filter;let r=0;if(o==null)r=65535;else for(let l=0;l<o.length;l++){const c=o[l];c>31?console.error(`Rapier only supports 32 layers, layer ${c} is not supported`):r|=1<<Math.floor(c)}t.setCollisionGroups(n<<16|r)}getRigidbody(s,t){if(!this.world)throw new Error("Physics world not initialized");let i=null;if(s.attachedRigidbody){const n=s.attachedRigidbody;if(i=n[ii],!i){const o=n.isKinematic&&!Ey;Lt&&console.log("Create rigidbody",o);const r=o?j.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased():j.RAPIER_PHYSICS.MODULE.RigidBodyDesc.dynamic(),l=te(s.attachedRigidbody.gameObject);r.setTranslation(l.x,l.y,l.z),r.setRotation(Ce(s.attachedRigidbody.gameObject)),r.centerOfMass=new j.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[bi]=n,n[ii]=i,this.internalUpdateRigidbodyProperties(n,i),this.getRigidbodyRelativeMatrix(s.gameObject,n.gameObject,t),s[nS]=i}else{const n=j.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased(),o=te(s.gameObject);n.setTranslation(o.x,o.y,o.z),n.setRotation(Ce(s.gameObject)),i=this.world.createRigidBody(n),t.identity(),i[bi]=null}return i}internal_getRigidbody(s){return s.isCollider===!0?s[nS]:s[ii]}internalUpdateColliderProperties(s,t){const i=t.shape;let n=!1;switch(i.type){case j.RAPIER_PHYSICS.MODULE.ShapeType.Ball:{const p=i,g=s,y=s.gameObject,f=Ye(y,this._tempPosition),v=Math.abs(g.radius*f.x);n=p.radius!==v,p.radius=v,n&&t.setShape(p);break}case j.RAPIER_PHYSICS.MODULE.ShapeType.Cuboid:const o=i,r=s,l=s.gameObject,c=Ye(l,this._tempPosition),h=r.size.x*.5*c.x,d=r.size.y*.5*c.y,u=r.size.z*.5*c.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=s.attachedRigidbody;if(o!=null&&o.autoMass){const r=this.getBody(o);r?.recomputeMassPropertiesFromColliders()}}this.updateColliderCollisionGroups(s),s.isTrigger!==t.isSensor()&&t.setSensor(s.isTrigger)}internalUpdateRigidbodyProperties(s,t){if(t.enableCcd(s.collisionDetectionMode!==wu.Discrete),t.setLinearDamping(s.drag),t.setAngularDamping(s.angularDrag),t.setGravityScale(s.useGravity?s.gravityScale:0,!0),s.dominanceGroup<=127&&s.dominanceGroup>=-127?t.setDominanceGroup(Math.floor(s.dominanceGroup)):t.setDominanceGroup(0),s.autoMass){t.setAdditionalMass(0,!1);for(let i=0;i<t.numColliders();i++)t.collider(i).setDensity(1);t.recomputeMassPropertiesFromColliders()}else{t.setAdditionalMass(s.mass,!1);for(let i=0;i<t.numColliders();i++)t.collider(i).setDensity(1e-7);t.recomputeMassPropertiesFromColliders()}t.setEnabledRotations(!s.lockRotationX,!s.lockRotationY,!s.lockRotationZ,!1),t.setEnabledTranslations(!s.lockPositionX,!s.lockPositionY,!s.lockPositionZ,!1),s.isKinematic?t.setBodyType(j.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased,!1):t.setBodyType(j.RAPIER_PHYSICS.MODULE.RigidBodyType.Dynamic,!1)}step(s){if(this.world&&this.enabled){if(this._isUpdatingPhysicsWorld=!0,this.eventQueue||(this.eventQueue=new j.RAPIER_PHYSICS.MODULE.EventQueue(!1)),s===void 0||s<=0){this._isUpdatingPhysicsWorld=!1;return}else s!==void 0&&(this.world.timestep=W.lerp(this.world.timestep,s,.8));try{this.world.step(this.eventQueue)}catch(t){console.warn("Error running physics step",t)}this._isUpdatingPhysicsWorld=!1}}postStep(){this.world&&this.enabled&&(this._isUpdatingPhysicsWorld=!0,this.syncObjects(),this._isUpdatingPhysicsWorld=!1,this.eventQueue&&!this.collisionHandler&&(this.collisionHandler=new Wj(this.world,this.eventQueue)),this.collisionHandler&&(this.collisionHandler.handleCollisionEvents(),this.collisionHandler.update()),this.updateDebugRendering(this.world))}updateDebugRendering(s){var t,i,n,o;if(Lt||Ey||Nj||this.debugRenderColliders===!0){if(!this.lines){const l=new qy({color:7855479,fog:!1}),c=new gn;this.lines=new $y(c,l),this.lines.layers.disableAll(),this.lines.layers.enable(2)}this.lines.parent!==((t=this.context)==null?void 0:t.scene)&&((i=this.context)==null||i.scene.add(this.lines));const r=s.debugRender();this.lines.geometry.setAttribute("position",new ft(r.vertices,3)),this.lines.geometry.setAttribute("color",new ft(r.colors,4)),(this.context.time.frame%30===0||((n=this.lines.geometry.boundingSphere)==null?void 0:n.radius)===0)&&this.lines.geometry.computeBoundingSphere()}else this.lines&&((o=this.context)==null||o.scene.remove(this.lines))}syncObjects(){if(!Ey)for(let s=0;s<this.bodies.length;s++){const t=this.objects[s],i=this.bodies[s],n=t;if(n?.isCollider===!0&&!n.attachedRigidbody){const c=i.parent();c?this.syncPhysicsBody(t.gameObject,c,!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&&F()&&(console.warn("Collider has NaN values",n.name,n.gameObject,i),n.__COLLIDER_NAN=!0);continue}const l=t.center;if(l&&l.isVector3){this._tempQuaternion.set(r.x,r.y,r.z,r.w);const c=this._tempPosition.copy(l).applyQuaternion(this._tempQuaternion),h=Ye(t.gameObject);c.multiply(h),o.x-=c.x,o.y-=c.y,o.z-=c.z}lr(t.gameObject,o.x,o.y,o.z),Um(t.gameObject,r.x,r.y,r.z,r.w)}}syncPhysicsBody(s,t,i,n){if(t instanceof j.RAPIER_PHYSICS.MODULE.RigidBody){const o=te(s,this._tempPosition),r=Ce(s,this._tempQuaternion);switch(t.bodyType()){case j.RAPIER_PHYSICS.MODULE.RigidBodyType.Fixed:case j.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased:case j.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 j.RAPIER_PHYSICS.MODULE.Collider){s.matrixWorldNeedsUpdate&&s.updateWorldMatrix(!0,!1),s.matrixWorld.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const o=this._tempPosition,r=this._tempQuaternion,l=t[bi];if(this.tryApplyCenter(l,o),i){const c=t.translation();(c.x!==o.x||c.y!==o.y||c.z!==o.z)&&t.setTranslation(o)}if(n){const c=t.rotation();(c.x!==r.x||c.y!==r.y||c.z!==r.z||c.w!==r.w)&&t.setRotation(r)}}}tryApplyCenter(s,t){const i=s.center;i&&s.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,Ye(s.gameObject,this._tempCenterVec),this._tempCenterPos.multiply(this._tempCenterVec),s.attachedRigidbody?this._tempCenterPos.applyQuaternion(s.gameObject.quaternion):(Ce(s.gameObject,this._tempCenterQuaternion),this._tempCenterPos.applyQuaternion(this._tempCenterQuaternion)),t.x+=this._tempCenterPos.x,t.y+=this._tempCenterPos.y,t.z+=this._tempCenterPos.z)}getRigidbodyRelativeMatrix(s,t,i,n){if(n===void 0&&(n=Jp._matricesBuffer,n.length=0),s===t){const o=Ye(s,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(s.matrix),s.parent&&this.getRigidbodyRelativeMatrix(s.parent,t,i,n),i}addFixedJoint(s,t){if(!this.world){console.error("Physics world not initialized");return}const i=s[ii],n=t[ii];this.calculateJointRelativeMatrices(s.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const o=j.RAPIER_PHYSICS.MODULE.JointData.fixed(Jp.centerConnectionPos,Jp.centerConnectionRot,this._tempPosition,this._tempQuaternion),r=this.world.createImpulseJoint(o,i,n,!0);Lt&&console.log("ADD FIXED JOINT",r)}addHingeJoint(s,t,i,n){if(!this.world){console.error("Physics world not initialized");return}const o=s[ii],r=t[ii];this.calculateJointRelativeMatrices(s.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const l=j.RAPIER_PHYSICS.MODULE.JointData.revolute(i,this._tempPosition,n),c=this.world.createImpulseJoint(l,o,r,!0);Lt&&console.log("ADD HINGE JOINT",c)}calculateJointRelativeMatrices(s,t,i){s.updateWorldMatrix(!0,!1),t.updateWorldMatrix(!0,!1);const n=s.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()}};let ed=Jp;a(ed,"_didLoadPhysicsEngine",!1),a(ed,"_matricesBuffer",[]),a(ed,"centerConnectionPos",{x:0,y:0,z:0}),a(ed,"centerConnectionRot",{x:0,y:0,z:0,w:1});class Wj{constructor(t,i){a(this,"world"),a(this,"eventQueue"),a(this,"activeCollisions",[]),a(this,"activeCollisionsStay",[]),a(this,"activeTriggers",[]),this.world=t,this.eventQueue=i}handleCollisionEvents(){this.eventQueue&&this.world&&this.eventQueue.drainCollisionEvents((t,i,n)=>{const o=this.world.getCollider(t),r=this.world.getCollider(i);if(!o||!r)return;const l=o[bi],c=r[bi];Ay&&console.log("EVT",l.name,c.name,n,o,r),l&&c&&(n?(this.onCollisionStarted(l,o,c,r),this.onCollisionStarted(c,r,l,o)):(this.onCollisionEnded(l,c),this.onCollisionEnded(c,l)))})}update(){this.onHandleCollisionStay()}onCollisionStarted(t,i,n,o){let r=null;if(t.isTrigger||n.isTrigger)br(t.gameObject,l=>{l.onTriggerEnter&&!l.destroyed&&l.onTriggerEnter(n),this.activeTriggers.push({collider:t,component:l,otherCollider:n})});else{const l=t.gameObject;this.world.contactPair(i,o,(c,h)=>{br(l,d=>{var u;if(d.destroyed)return;const p=d.onCollisionEnter||d.onCollisionStay||d.onCollisionExit;if(p||Ay){if(!r){const g=[],y=c.normal();n instanceof Ro&&n.convex&&(y.x=-y.x,y.y=-y.y,y.z=-y.z);for(let f=0;f<c.numSolverContacts();f++){const v=c.solverContactPoint(f),b=c.contactImpulse(f);if(v){const w=c.contactDist(f),_=c.solverContactFriction(f),S=c.solverContactTangentVelocity(f),R=new Dw(v,w,y,b,_,S);g.push(R),Ay&&q.DrawDirection(v,y,16711680,3,!0)}}r=new Bw(l,n,g)}if(p){const g={collider:t,component:d,collision:r};this.activeCollisions.push(g),d.onCollisionStay&&this.activeCollisionsStay.push(g),(u=d.onCollisionEnter)==null||u.call(d,r)}}})})}}onHandleCollisionStay(){for(const t of this.activeCollisionsStay){const i=t.component;if(!i.destroyed&&i.activeAndEnabled&&i.onCollisionStay){if(t.collision.collider.destroyed)continue;const n=t.collision;i.onCollisionStay(n)}}for(const t of this.activeTriggers){const i=t.component;if(!i.destroyed&&i.activeAndEnabled&&i.onTriggerStay){const n=t.otherCollider;if(n.destroyed)continue;i.onTriggerStay(n)}}}onCollisionEnded(t,i){if(!(t.destroyed||i.destroyed)){for(let n=0;n<this.activeCollisions.length;n++){const o=this.activeCollisions[n],r=o.collider;if(r.destroyed||o.collision.collider.destroyed){this.activeCollisions.splice(n,1),n--;continue}if(r===t&&o.collision.collider===i){const l=o.component;if(this.activeCollisions.splice(n,1),n--,l.activeAndEnabled&&l.onCollisionExit){const c=o.collision;l.onCollisionExit(c)}}}for(let n=0;n<this.activeCollisionsStay.length;n++){const o=this.activeCollisionsStay[n],r=o.collider;if(r.destroyed||o.collision.collider.destroyed){this.activeCollisionsStay.splice(n,1),n--;continue}if(r===t&&o.collision.collider===i){const l=o.component;if(this.activeCollisionsStay.splice(n,1),n--,l.activeAndEnabled&&l.onCollisionExit){const c=o.collision;l.onCollisionExit(c)}}}for(let n=0;n<this.activeTriggers.length;n++){const o=this.activeTriggers[n],r=o.collider;if(r.destroyed||o.otherCollider.destroyed){this.activeTriggers.splice(n,1),n--;continue}if(r===t&&o.otherCollider===i){const l=o.component;if(this.activeTriggers.splice(n,1),n--,l.activeAndEnabled&&l.onTriggerExit){const c=o.otherCollider;l.onTriggerExit(c)}}}}}}class Vj{static async createComparisonScene(t){const{files:i}=t,n=await Promise.all(i.map(f=>new le(f).loadAssetAsync())),o=new Vi;let r=0;for(const f of n)if(f instanceof I){f.position.y=r,o.add(f);const v=oi([f]);r+=v.getSize(new x).y,r+=.1}const l=new _e(20);o.add(l);const c=t.environment||"https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/studio_small_09_1k.exr";if(c){let f=null;if(c.endsWith(".hdr")){const v=(await import("./three-examples.light.min.js").then(b=>b.q)).RGBELoader;f=new v}else if(c.endsWith(".exr")){const v=(await import("./three-examples.light.min.js").then(b=>b.p)).EXRLoader;f=new v}if(f){const v=await f.loadAsync(c).catch(b=>(console.error(b),null));v&&(v.mapping=yn,v.needsUpdate=!0,o.background=v,o.environment=v,o.backgroundBlurriness=.75)}else console.warn("Unsupported environment map format",c)}const h=oi(o.children),d=h.getCenter(new x),u=h.getSize(new x),p=Math.max(u.x,u.y,u.z)/(2*Math.tan(Math.PI*l.fov/360));l.position.set(d.x,d.y,p),l.lookAt(d);const g=new ov(l,t.domElement||document.body);g.target=d,g.update();const y=(t.domElement||document.body).getBoundingClientRect();return l.aspect=y.width/y.height,l.updateProjectionMatrix(),{scene:o,camera:l}}}let jy=0;function oS(s){s?jy++:jy--}function Hj(){return jy>0}const $j={binary:!0,animations:!0};async function qj(s){if(!s.context)throw new Error("No context provided to exportAsGLTF");s.scene||(s.scene=s.context.scene);const t={...$j,...s},{context:i}=t,n=new rv;n.register(c=>new ax(c)),n.register(c=>new xR(c)),n.register(c=>new ex(c)),Wf(n,t.context);const o={binary:t.binary,animations:Xj(i,t.scene,[])},r=new Gj;console.debug("Exporting GLTF",o),r.onBeforeExport(t),oS(!0);const l=await n.parseAsync(t.scene,o).catch(c=>(console.error(c),null));if(oS(!1),r.onAfterExport(t),!l)throw new Error("Failed to export GLTF");if(t.downloadAs!=null){let c=null;if(l instanceof ArrayBuffer?c=new Blob([l],{type:"application/octet-stream"}):console.error("Can not download GLTF as a blob",l),c){const h=URL.createObjectURL(c),d=document.createElement("a");d.href=h;let u=t.downloadAs;!u.endsWith(".glb")&&!u.endsWith(".gltf")&&(u+=t.binary?".glb":".gltf"),d.download=u,d.click()}}return l}const rS=Symbol("needle:weight");class Gj{constructor(){a(this,"_undo",[])}onBeforeExport(t){t.context.animations.mixers.forEach(i=>{const n=Ba.tryGetActionsFromMixer(i);if(n)for(let o=0;o<n.length;o++){const r=n[o];r[rS]=r.weight,r.weight=0,this._undo.push(()=>{r.weight=r[rS]})}i.update(0)}),t.context.scene.traverse(i=>{if(!Bf(i)){const n=i.parent;n&&(i.removeFromParent(),this._undo.push(()=>n.add(i)))}})}onAfterExport(t){this._undo.forEach(i=>i()),this._undo.length=0}}function Xj(s,t,i){s.animations.mixers.forEach(o=>{const r=Ba.tryGetActionsFromMixer(o);if(r)for(let l=0;l<r.length;l++){const c=r[l].getClip();i.push(c)}}),Array.isArray(t)||(t=[t]);for(const o of t)Ba.tryGetAnimationClipsFromObjectHierarchy(o,i);const n=new Set(i);return Array.from(n)}const aS="needle-button",Ly=F();var la,ca,ha,_i,Ls,Nl,Dy,lS,By,cS,em;class Fy extends HTMLElement{constructor(){super(),Wi(this,Dy),Wi(this,By),Wi(this,la,void 0),Wi(this,ca,void 0),Wi(this,ha,void 0),Wi(this,_i,void 0),Wi(this,Ls,void 0),Wi(this,Nl,void 0),Wi(this,em,t=>{Ly&&console.log("Needle Button clicked"),!t.defaultPrevented&&me(this,_i)&&me(this,_i).click()}),this.removeEventListener("click",me(this,em)),this.addEventListener("click",me(this,em))}attributeChangedCallback(t,i,n){pa(this,Dy,lS).call(this)}}la=new WeakMap,ca=new WeakMap,ha=new WeakMap,_i=new WeakMap,Ls=new WeakMap,Nl=new WeakMap,Dy=new WeakSet,lS=function(){var s,t;if((s=me(this,_i))==null||s.remove(),this.getAttribute("ar")!=null)me(this,Ls)??Bs(this,Ls,new zr),Bs(this,_i,me(this,Ls).createARButton());else if(this.getAttribute("vr")!=null)me(this,Ls)??Bs(this,Ls,new zr),Bs(this,_i,me(this,Ls).createVRButton());else if(this.getAttribute("quicklook")!=null)me(this,Ls)??Bs(this,Ls,new zr),Bs(this,_i,me(this,Ls).createQuicklookButton());else{Ly?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.");return}me(this,la)??Bs(this,la,this.attachShadow({mode:"open"})),me(this,ca)??Bs(this,ca,document.createElement("slot")),me(this,ha)??Bs(this,ha,document.createElement("style")),me(this,ha).innerHTML=`
1472
1476
  button {
1473
1477
  all: initial;
1474
1478
  cursor: inherit;
@@ -1502,4 +1506,4 @@ Error:`,l),null}}updateColliderCollisionGroups(s){const t=s[ii],i=s.membership;l
1502
1506
  justify-content: center;
1503
1507
  gap: .5rem;
1504
1508
  }
1505
- `),me(this,ca).innerHTML=me(this,_i).innerHTML,me(this,ca).style.cssText="display: flex; align-items: center; justify-content: center;",me(this,_i).innerHTML=me(this,ca).outerHTML,me(this,la).innerHTML=me(this,_i).outerHTML,me(this,la).prepend(me(this,ha)),cu(Kg,{element:me(this,la)}),(t=me(this,Nl))==null||t.disconnect(),me(this,Nl)??Bs(this,Nl,new MutationObserver(()=>pa(this,By,cS).call(this))),me(this,Nl).observe(me(this,_i),{attributes:!0}),Ly&&console.log("Needle Button updated")},By=new WeakSet,cS=function(){me(this,_i)&&(me(this,_i).style.display==="none"?this.style.display="none":this.style.display==="none"&&(this.style.display=""))},em=new WeakMap,a(Fy,"observedAttributes",["ar","vr","quicklook"]),typeof window<"u"&&!window.customElements.get(aS)&&window.customElements.define(aS,Fy);const td=C("debugavatar");class zy{constructor(t,i,n,o){a(this,"root"),a(this,"head"),a(this,"leftHand"),a(this,"rigthHand");var r;this.root=t,this.head=i,this.leftHand=n,this.rigthHand=o,(r=this.root)==null||r.traverse(l=>l.layers.set(2))}get isValid(){return this.head!==null&&this.head!==void 0}}class hS{constructor(){a(this,"avatarRegistryUrl",null)}async getOrCreateNewAvatarInstance(t,i){if(!i)return console.error("Can not create avatar: failed to provide id or root object"),null;let n=null;if(typeof i=="string"){if(n=await this.loadAvatar(t,i),!n){const r=new Ds;n=O.instantiate(ba(i,t.scene),r)}}else n=i;if(!n)return null;const o=this.findAvatar(n);return o.isValid?(td&&console.log("[Custom Avatar] valid config",i,td?o:""),o):(console.warn("[Custom Avatar] config isn't valid",i,td?o:""),null)}async loadAvatar(t,i){if(console.assert(i!=null&&typeof i=="string","Avatar id must not be null"),i.length<=0||!i)return null;if(td&&console.log("[Custom Avatar] "+i+", loading..."),i.endsWith(".glb")||(i+=".glb"),this.avatarRegistryUrl===null){const o=await fetch("./"+i);let r=null;if(o.ok){const c=await o.blob();c&&(r=await c.arrayBuffer())}if(!r)return null;const l=await gs().parseSync(t,r,null,0);return l?.scene??null}const n=new rr;return gu(n,t),new Promise((o,r)=>{const l=this.avatarRegistryUrl+"/"+i;n.load(l,async c=>{await gs().createBuiltinComponents(t,l,c,null,void 0),o(c.scene)},c=>{td&&console.log("[Custom Avatar] "+c.loaded/c.total*100+"% loaded of "+c.total/1024+"kB")},c=>{console.error("[Custom Avatar] Error when loading: "+c),o(null)})})}cacheModel(t,i){}findAvatar(t){const i=t;let n=i;n.children.length==1&&(n=t.children[0]);let o=this.findAvatarPart(n,["head"]);const r=this.findAvatarPart(n,["left","hand"]),l=this.findAvatarPart(n,["right","hand"]);if(!o){o=i;const c=new x;new wi().setFromObject(o).getSize(c);const h=Math.max(c.x,c.y,c.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+h+" meters! Should be < 0.3m"),h>.3&&o.scale.multiplyScalar(1/h*.3)}return new zy(i,o,r,l)}findAvatarPart(t,i){const n=t.name.toLowerCase();let o=!0;for(const r of i){if(!o)break;n.indexOf(r)===-1&&(o=!1)}if(o)return t;if(t.children)for(const r of t.children){const l=this.findAvatarPart(r,i);if(l)return l}return null}handleCustomAvatarErrors(t){if(!t.ok)throw Error(t.statusText);return t}}class dS{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(t){}}class uS{}const Xj=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:ve,ActionCollection:zx,ActionModel:ts,AlignmentConstraint:Lc,Animation:zt,AnimationCurve:kl,AnimationExtension:sp,AnimationTrackHandler:Vp,Animator:Pt,AnimatorController:ls,Antialiasing:Oh,AudioExtension:da,AudioListener:Tn,AudioSource:Ne,AudioTrackHandler:Uh,Avatar:Do,AvatarBlink_Simple:Tr,AvatarEyeLook_Rotation:Ga,AvatarLoader:hS,AvatarMarker:Mt,AvatarModel:zy,Avatar_Brain_LookAt:Hc,Avatar_MouthShapes:Gc,Avatar_MustacheShake:wf,Avatar_POI:En,AxesHelper:Xa,BaseUIComponent:rs,BasicIKConstraint:Of,BehaviorExtension:f0,BehaviorModel:Nt,BloomEffect:Zr,BoxCollider:Ya,BoxGizmo:$r,BoxHelperComponent:Ji,Button:Yn,CallInfo:Rn,Camera:Oe,CameraTargetReachedEvent:Wc,Canvas:Et,CanvasGroup:Uo,CapsuleCollider:In,ChangeMaterialOnClick:pl,ChangeTransformOnClick:Dr,CharacterController:Er,CharacterControllerInput:Ln,ChromaticAberration:Ph,Collider:di,ColorAdjustments:qo,ColorBySpeedModule:Ml,ColorOverLifetimeModule:xp,ContactShadows:Ps,ControlTrackHandler:Hp,CustomBranding:Hr,Deletable:Tf,DeleteBox:Kc,DepthOfField:As,DeviceFlag:Lu,DocumentExtension:dS,DragControls:ui,DropListener:Dn,Duplicatable:Ja,EffectWrapper:kh,EmissionModule:$n,EmphasizeOnClick:fl,EventList:Se,EventListEvent:Cu,EventSystem:si,EventTrigger:Bu,FieldWithDefault:mx,FixedJoint:L0,Fog:Sl,GltfExport:ih,GltfExportBox:qf,Gradient:Gr,Graphic:Ur,GraphicRaycaster:ku,GridHelper:Cl,GridLayoutGroup:O0,GroundProjectedEnv:Hs,GroupActionModel:Eo,HideOnStart:gl,HingeJoint:vh,HorizontalLayoutGroup:C0,Image:jl,InheritVelocityModule:Qr,InputField:sa,InstanceHandle:qu,InstancingHandler:nl,Interactable:Rf,Keyframe:fi,LODGroup:_h,LODModel:Ol,Light:gi,LimitVelocityOverLifetimeModule:mt,LogStats:Mf,LookAt:na,LookAtConstraint:Mr,MainModule:Ht,MaskableGraphic:fh,MeshCollider:Ro,MeshRenderer:th,MinMaxCurve:Z,MinMaxGradient:yi,NeedleMenu:nn,NestedGltf:fp,Networking:Pl,NoiseModule:Pe,ObjectRaycaster:Ei,OffsetConstraint:qr,OpenURL:Dl,OrbitControls:be,Outline:xl,Padding:Vr,ParticleBurst:wp,ParticleSubEmitter:N0,ParticleSystem:lt,ParticleSystemRenderer:ss,PhysicsExtension:y0,PixelationEffect:Mh,PlayAnimationOnClick:Fr,PlayAudioOnClick:Io,PlayableDirector:Zo,PlayerColor:Wl,PointerEventData:id,PostProcessingHandler:ny,PreliminaryAction:yl,PreliminaryTrigger:oh,RawImage:Gp,Rect:Xx,RectTransform:Wt,ReflectionProbe:sl,RegisteredAnimationInfo:ir,RemoteSkybox:cn,Renderer:Ze,RendererLightmap:Gu,Rigidbody:ye,RotationBySpeedModule:is,RotationOverLifetimeModule:Es,SceneSwitcher:ot,ScreenCapture:Xo,ScreenSpaceAmbientOcclusion:qn,ScreenSpaceAmbientOcclusionN8:Is,SetActiveOnClick:Br,ShadowCatcher:Ah,ShapeModule:et,SharpeningEffect:Th,SignalAsset:Wp,SignalReceiver:Il,SignalReceiverEvent:Bh,SignalTrackHandler:Nh,Size:Gx,SizeBySpeedModule:vi,SizeOverLifetimeModule:Xr,SkinnedMeshRenderer:$f,SmoothFollow:Qo,SpatialGrabRaycaster:Va,SpatialHtml:Wh,SpatialTrigger:Dh,SpatialTriggerReceiver:hn,SpectatorCamera:Fp,SphereCollider:Qa,Sprite:Nn,SpriteData:jo,SpriteRenderer:mi,SpriteSheet:vl,SubEmitterSystem:Mp,SyncedCamera:Up,SyncedRoom:js,SyncedTransform:qs,TapGestureTrigger:o0,TeleportTarget:cp,TestRunner:uy,TestSimulateUserData:py,Text:Vt,TextBuilder:x0,TextExtension:pp,TextureSheetAnimationModule:$t,TiltShiftEffect:ln,ToneMappingEffect:$o,TrailModule:qe,TransformData:Ke,TransformGizmo:ta,TriggerBuilder:Rt,TriggerModel:Lr,UIRaycastUtils:pf,UIRootComponent:Nc,USDZExporter:$e,USDZText:Wr,USDZUIExtension:M0,UsageMarker:Zc,VariantAction:s0,VelocityOverLifetimeModule:tt,VerticalLayoutGroup:S0,VideoPlayer:gt,Vignette:ea,VisibilityAction:rh,Voip:Mo,Volume:Al,VolumeParameter:N,VolumeProfile:Rp,WebARCameraBackground:$h,WebARSessionRoot:sn,WebXR:Je,WebXRImageTracking:oa,WebXRImageTrackingModel:Kn,WebXRPlaneTracking:Jn,WebXRTrackedImage:qh,XRControllerFollow:Zn,XRControllerModel:on,XRControllerMovement:ji,XRFlag:Ai,XRRig:Yp,XRState:ci,__Ignore:uS},Symbol.toStringTag,{value:"Module"})),tm=C("debugmissingcamera");ue.registerCallback(ge.MissingCamera,s=>{var t,i,n;tm&&console.warn("Creating missing camera");const o=s.context.scene,r=new _e;r.name="Default Fallback Camera",o.add(r);const l=new Oe;l.sourceId=((i=(t=s.files)==null?void 0:t[0])==null?void 0:i.src)??"unknown",(n=s.context.domElement.getAttribute("skybox-image"))!=null&&n.length||0>0||s.context.lightmaps.tryGetSkybox(l.sourceId)?l.clearFlags=Oo.Skybox:l.clearFlags=Oo.SolidColor,l.backgroundColor=new xe(.5,.5,.5,1),l.fieldOfView=35,s.context.domElement.getAttribute("transparent")!=null&&(l.clearFlags=Oo.Uninitialized),l.backgroundBlurriness=.2;const c=fr(r,l,!0);r.position.x=0,r.position.y=1,r.position.z=2;const h=s.context.domElement;return h?.cameraControls!=!1&&pS(s.context,c),c}),ue.registerCallback(ge.ContextCreated,s=>{if(!s.context.mainCamera){tm&&console.log("Will not auto-fit because a default camera exists");return}const t=s.context.domElement;if(t?.cameraControls==!0){const i=Uv(s.context.mainCamera);if(i?.isCameraController==!0){tm&&console.log("Will not auto-fit because a camera controller exists");return}pS(s.context)}});function pS(s,t){t=t??s.mainCameraComponent;const i=t?.gameObject;if(tm&&console.log("Creating default camera controls",t?.name),i){const n=Sc(i,be);n.sourceId=t?.sourceId??"unknown";const o=s.domElement.getAttribute("auto-rotate");if(n.autoRotate=o!=null&&o!="0"&&o?.toLowerCase()!="false",n.autoRotateSpeed=.5,n.autoFit=!0,n.autoRotate&&o){const r=parseFloat(o);isNaN(r)||(n.autoRotateSpeed=r)}}else console.warn("Missing camera object, can not add orbit controls")}ue.registerCallback(ge.ContextCreated,s=>{const t=s.context.domElement.getAttribute("autoplay");if(t!==void 0&&(t===""||t==="true"||t==="1")&&s.files)for(const i of s.files)O.foreachComponent(i.file.scene,n=>{if(n.enabled!==!1){if(n instanceof zt&&n.playAutomatically||n instanceof Pt||n instanceof Zo&&n.playOnAwake===!0)return!0;if(n instanceof zt)return n.playAutomatically=!0,!0;if(n instanceof Zo)return n.playOnAwake=!0,!0}},!0)!==!0&&Ba.assignAnimationsFromFile(i.file,{createAnimationComponent:(n,o)=>Mi(n,zt)})});class Qj extends hO{constructor(){super(new dO),this.name="GenerateMeshBVHWorker"}runTask(t,i,n={}){return new Promise((o,r)=>{if(i.getAttribute("position").isInterleavedBufferAttribute||i.index&&i.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");t.onerror=d=>{r(new Error(`GenerateMeshBVHWorker: ${d.message}`))},t.onmessage=d=>{const{data:u}=d;if(u.error)r(new Error(u.error)),t.onmessage=null;else if(u.serialized){const{serialized:p,position:g}=u,y=uO.deserialize(p,i,{setIndex:!1}),f=Object.assign({setBoundingBox:!0},n);if(i.attributes.position.array=g,p.index)if(i.index)i.index.array=p.index;else{const v=new ft(p.index,1,!1);i.setIndex(v)}f.setBoundingBox&&(i.boundingBox=y.getBoundingBox(new wi)),n.onProgress&&n.onProgress(u.progress),o(y),t.onmessage=null}else n.onProgress&&n.onProgress(u.progress)};const l=i.index?i.index.array:null,c=i.attributes.position.array,h=[c];l&&h.push(l),t.postMessage({index:l,position:c,options:{...n,onProgress:null,includedProgressCallback:!!n.onProgress,groups:[...i.groups]}},h.map(d=>d.buffer).filter(d=>typeof SharedArrayBuffer>"u"||!(d instanceof SharedArrayBuffer)))})}}const Yj=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:Qj},Symbol.toStringTag,{value:"Module"}));export{_g as $,Ba as A,we as B,ee as C,rc as D,F as E,gP as F,O as G,hr as H,as as I,Qm as J,nb as K,Oi as L,D as M,J as N,F_ as O,le as P,Jd as Q,z_ as R,tu as S,k as T,U_ as U,bs as V,iu as W,Pn as X,qb as Y,d2 as Z,Xb as _,Pw as a,dc as a$,u2 as a0,Ee as a1,Zb as a2,wg as a3,m2 as a4,Ug as a5,Sc as a6,fr as a7,Mi as a8,k_ as a9,Ty as aA,kk as aB,of as aC,af as aD,Ds as aE,Ia as aF,Mc as aG,E_ as aH,A_ as aI,Xd as aJ,Ng as aK,vr as aL,j_ as aM,ja as aN,Ri as aO,br as aP,Zd as aQ,La as aR,gs as aS,wm as aT,Lj as aU,Dj as aV,Bj as aW,zj as aX,Pd as aY,Be as aZ,wn as a_,yr as aa,Cc as ab,Oc as ac,Aa as ad,Pc as ae,Hd as af,kc as ag,T_ as ah,yc as ai,xd as aj,Ym as ak,cc as al,_n as am,dr as an,hc as ao,vk as ap,bk as aq,Me as ar,pu as as,ge as at,ue as au,$g as av,K2 as aw,W_ as ax,ur as ay,po as az,Zk as b,My as b$,FP as b0,ai as b1,gb as b2,W as b3,fd as b4,jm as b5,li as b6,uc as b7,Mb as b8,se as b9,bf as bA,zw as bB,Uw as bC,qc as bD,sd as bE,Qs as bF,_s as bG,Gt as bH,_v as bI,Sd as bJ,jP as bK,Cd as bL,Ws as bM,yg as bN,Ed as bO,_t as bP,wu as bQ,st as bR,Na as bS,ed as bT,yo as bU,$_ as bV,q_ as bW,za as bX,au as bY,Q_ as bZ,Y_ as b_,QP as ba,YP as bb,ZP as bc,Rb as bd,rg as be,Tb as bf,_r as bg,Zw as bh,uR as bi,To as bj,Dt as bk,o_ as bl,wc as bm,Tg as bn,r_ as bo,S2 as bp,a_ as bq,Eg as br,l_ as bs,c_ as bt,d_ as bu,$P as bv,qP as bw,Cb as bx,Pb as by,Xs as bz,Kk as c,gO as c$,G1 as c0,aa as c1,kj as c2,Mj as c3,Ry as c4,Q1 as c5,Vd as c6,Bg as c7,y_ as c8,m as c9,Nm as cA,Wm as cB,ic as cC,Vm as cD,sc as cE,_d as cF,aP as cG,Yv as cH,$i as cI,Zv as cJ,lP as cK,Hm as cL,Kv as cM,oi as cN,Jv as cO,eb as cP,$m as cQ,K_ as cR,fx as cS,ce as cT,Au as cU,Lw as cV,EM as cW,Dw as cX,Bw as cY,Fw as cZ,xv as c_,Pr as ca,aM as cb,cM as cc,Rw as cd,Ou as ce,pM as cf,Tw as cg,Ew as ch,Wj as ci,Ua as cj,YO as ck,ZO as cl,tc as cm,G as cn,Vv as co,ys as cp,te as cq,ht as cr,lr as cs,Ce as ct,Hi as cu,Um as cv,Ye as cw,wa as cx,nP as cy,Gv as cz,Cw as d,ww as d$,fO as d0,Ci as d1,Ql as d2,C as d3,yO as d4,Yl as d5,Cm as d6,Sv as d7,Om as d8,vO as d9,jO as dA,LO as dB,DO as dC,Rv as dD,Tv as dE,km as dF,Mm as dG,Ev as dH,V1 as dI,H1 as dJ,rj as dK,wy as dL,z1 as dM,Hh as dN,Vj as dO,$j as dP,p_ as dQ,zu as dR,Ms as dS,BR as dT,FR as dU,Nu as dV,Wu as dW,Wf as dX,Vf as dY,Fk as dZ,Dc as d_,bO as da,Pv as db,kv as dc,ba as dd,Zl as de,fs as df,Kl as dg,Mv as dh,_O as di,lo as dj,eo as dk,md as dl,Pm as dm,X as dn,xO as dp,SO as dq,CO as dr,OO as ds,PO as dt,kO as du,MO as dv,RO as dw,TO as dx,EO as dy,AO as dz,Yk as e,Bu as e$,_o as e0,cf as e1,S_ as e2,C_ as e3,$d as e4,xe as e5,kn as e6,Fy as e7,zr as e8,Ot as e9,wf as eA,Tr as eB,Ga as eC,zy as eD,hS as eE,Xa as eF,Of as eG,Ji as eH,Oe as eI,Er as eJ,Ln as eK,di as eL,Qa as eM,Ya as eN,Ro as eO,In as eP,Ps as eQ,Mf as eR,Kc as eS,Tf as eT,Lu as eU,ui as eV,Dn as eW,Ja as eX,Rn as eY,Cu as eZ,Se as e_,tw as ea,Yg as eb,Od as ec,DP as ed,Jm as ee,BP as ef,pb as eg,mb as eh,eg as ei,Eb as ej,Ub as ek,A as el,Oo as em,Af as en,uS as eo,Lc as ep,zt as eq,fi as er,kl as es,Pt as et,ls as eu,Tn as ev,Ne as ew,En as ex,Hc as ey,Gc as ez,Qk as f,et as f$,qf as f0,ih as f1,ir as f2,Ke as f3,sp as f4,s0 as f5,zx as f6,da as f7,f0 as f8,Dr as f9,Cl as fA,Hs as fB,Zc as fC,Rf as fD,L0 as fE,vh as fF,gi as fG,Ol as fH,_h as fI,Mr as fJ,nn as fK,fp as fL,Pl as fM,qr as fN,Wc as fO,be as fP,ss as fQ,lt as fR,Mp as fS,Gr as fT,Z as fU,yi as fV,Ht as fW,wp as fX,$n as fY,xp as fZ,Xr as f_,pl as fa,Br as fb,gl as fc,fl as fd,Io as fe,Fr as ff,yl as fg,oh as fh,rh as fi,o0 as fj,Nt as fk,Lr as fl,Rt as fm,Eo as fn,ts as fo,ve as fp,y0 as fq,dS as fr,Wr as fs,x0 as ft,pp as fu,M0 as fv,Hr as fw,$e as fx,Sl as fy,$r as fz,Ek as g,ta as g$,Pe as g0,qe as g1,tt as g2,$t as g3,Es as g4,is as g5,mt as g6,Qr as g7,vi as g8,Ml as g9,Gu as gA,ye as gB,ot as gC,Xo as gD,Ah as gE,cn as gF,Qo as gG,hn as gH,Dh as gI,Fp as gJ,Nn as gK,vl as gL,jo as gM,mi as gN,Up as gO,js as gP,qs as gQ,uy as gR,py as gS,Zo as gT,Wp as gU,Bh as gV,Il as gW,Vp as gX,Uh as gY,Nh as gZ,Hp as g_,N0 as ga,Wl as gb,Oh as gc,Zr as gd,Ph as ge,qo as gf,As as gg,kh as gh,Mh as gi,qn as gj,Is as gk,Th as gl,ln as gm,$o as gn,ea as go,ny as gp,Al as gq,N as gr,Rp as gs,sl as gt,mx as gu,Ze as gv,th as gw,$f as gx,nl as gy,qu as gz,Xj as h,bl as h$,rs as h0,Nc as h1,Yn as h2,Et as h3,Uo as h4,si as h5,Ur as h6,fh as h7,jl as h8,Gp as h9,sn as hA,Je as hB,Mt as hC,qh as hD,Kn as hE,oa as hF,Jn as hG,Yp as hH,ci as hI,Ai as hJ,Px as hK,kx as hL,Rs as hM,wx as hN,Gf as hO,Yt as hP,_x as hQ,ct as hR,ns as hS,Ui as hT,dn as hU,gy as hV,Fh as hW,Su as hX,Ys as hY,Ho as hZ,bp as h_,sa as ha,Vr as hb,S0 as hc,C0 as hd,O0 as he,xl as hf,id as hg,Ei as hh,ku as hi,Va as hj,pf as hk,Gx as hl,Xx as hm,Wt as hn,Wh as ho,Vt as hp,na as hq,Dl as hr,gt as hs,Mo as ht,Do as hu,Zn as hv,on as hw,ji as hx,cp as hy,$h as hz,Uv as i,$x as i0,Ii as i1,ig as i2,sg as i3,xb as i4,Sb as i5,Lm as j,q as k,Y1 as l,Cs as m,tf as n,Ow as o,vo as p,u0 as q,M2 as r,vd as s,eM as t,Nv as u,kt as v,HO as w,Lv as x,UO as y,De as z};
1509
+ `),me(this,ca).innerHTML=me(this,_i).innerHTML,me(this,ca).style.cssText="display: flex; align-items: center; justify-content: center;",me(this,_i).innerHTML=me(this,ca).outerHTML,me(this,la).innerHTML=me(this,_i).outerHTML,me(this,la).prepend(me(this,ha)),cu(Kg,{element:me(this,la)}),(t=me(this,Nl))==null||t.disconnect(),me(this,Nl)??Bs(this,Nl,new MutationObserver(()=>pa(this,By,cS).call(this))),me(this,Nl).observe(me(this,_i),{attributes:!0}),Ly&&console.log("Needle Button updated")},By=new WeakSet,cS=function(){me(this,_i)&&(me(this,_i).style.display==="none"?this.style.display="none":this.style.display==="none"&&(this.style.display=""))},em=new WeakMap,a(Fy,"observedAttributes",["ar","vr","quicklook"]),typeof window<"u"&&!window.customElements.get(aS)&&window.customElements.define(aS,Fy);const td=C("debugavatar");class zy{constructor(t,i,n,o){a(this,"root"),a(this,"head"),a(this,"leftHand"),a(this,"rigthHand");var r;this.root=t,this.head=i,this.leftHand=n,this.rigthHand=o,(r=this.root)==null||r.traverse(l=>l.layers.set(2))}get isValid(){return this.head!==null&&this.head!==void 0}}class hS{constructor(){a(this,"avatarRegistryUrl",null)}async getOrCreateNewAvatarInstance(t,i){if(!i)return console.error("Can not create avatar: failed to provide id or root object"),null;let n=null;if(typeof i=="string"){if(n=await this.loadAvatar(t,i),!n){const r=new Ds;n=O.instantiate(ba(i,t.scene),r)}}else n=i;if(!n)return null;const o=this.findAvatar(n);return o.isValid?(td&&console.log("[Custom Avatar] valid config",i,td?o:""),o):(console.warn("[Custom Avatar] config isn't valid",i,td?o:""),null)}async loadAvatar(t,i){if(console.assert(i!=null&&typeof i=="string","Avatar id must not be null"),i.length<=0||!i)return null;if(td&&console.log("[Custom Avatar] "+i+", loading..."),i.endsWith(".glb")||(i+=".glb"),this.avatarRegistryUrl===null){const o=await fetch("./"+i);let r=null;if(o.ok){const c=await o.blob();c&&(r=await c.arrayBuffer())}if(!r)return null;const l=await gs().parseSync(t,r,null,0);return l?.scene??null}const n=new rr;return gu(n,t),new Promise((o,r)=>{const l=this.avatarRegistryUrl+"/"+i;n.load(l,async c=>{await gs().createBuiltinComponents(t,l,c,null,void 0),o(c.scene)},c=>{td&&console.log("[Custom Avatar] "+c.loaded/c.total*100+"% loaded of "+c.total/1024+"kB")},c=>{console.error("[Custom Avatar] Error when loading: "+c),o(null)})})}cacheModel(t,i){}findAvatar(t){const i=t;let n=i;n.children.length==1&&(n=t.children[0]);let o=this.findAvatarPart(n,["head"]);const r=this.findAvatarPart(n,["left","hand"]),l=this.findAvatarPart(n,["right","hand"]);if(!o){o=i;const c=new x;new wi().setFromObject(o).getSize(c);const h=Math.max(c.x,c.y,c.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+h+" meters! Should be < 0.3m"),h>.3&&o.scale.multiplyScalar(1/h*.3)}return new zy(i,o,r,l)}findAvatarPart(t,i){const n=t.name.toLowerCase();let o=!0;for(const r of i){if(!o)break;n.indexOf(r)===-1&&(o=!1)}if(o)return t;if(t.children)for(const r of t.children){const l=this.findAvatarPart(r,i);if(l)return l}return null}handleCustomAvatarErrors(t){if(!t.ok)throw Error(t.statusText);return t}}class dS{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(t){}}class uS{}const Qj=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:ve,ActionCollection:zx,ActionModel:ts,AlignmentConstraint:Lc,Animation:zt,AnimationCurve:kl,AnimationExtension:sp,AnimationTrackHandler:Vp,Animator:Pt,AnimatorController:ls,Antialiasing:Oh,AudioExtension:da,AudioListener:Tn,AudioSource:Ne,AudioTrackHandler:Uh,Avatar:Do,AvatarBlink_Simple:Tr,AvatarEyeLook_Rotation:Ga,AvatarLoader:hS,AvatarMarker:Mt,AvatarModel:zy,Avatar_Brain_LookAt:Hc,Avatar_MouthShapes:Gc,Avatar_MustacheShake:wf,Avatar_POI:En,AxesHelper:Xa,BaseUIComponent:rs,BasicIKConstraint:Of,BehaviorExtension:f0,BehaviorModel:Nt,BloomEffect:Zr,BoxCollider:Ya,BoxGizmo:$r,BoxHelperComponent:Ji,Button:Yn,CallInfo:Rn,Camera:Oe,CameraTargetReachedEvent:Wc,Canvas:Et,CanvasGroup:Uo,CapsuleCollider:In,ChangeMaterialOnClick:pl,ChangeTransformOnClick:Dr,CharacterController:Er,CharacterControllerInput:Ln,ChromaticAberration:Ph,Collider:di,ColorAdjustments:qo,ColorBySpeedModule:Ml,ColorOverLifetimeModule:xp,ContactShadows:Ps,ControlTrackHandler:Hp,CustomBranding:Hr,Deletable:Tf,DeleteBox:Kc,DepthOfField:As,DeviceFlag:Lu,DocumentExtension:dS,DragControls:ui,DropListener:Dn,Duplicatable:Ja,EffectWrapper:kh,EmissionModule:$n,EmphasizeOnClick:fl,EventList:Se,EventListEvent:Cu,EventSystem:si,EventTrigger:Bu,FieldWithDefault:mx,FixedJoint:L0,Fog:Sl,GltfExport:ih,GltfExportBox:qf,Gradient:Gr,Graphic:Ur,GraphicRaycaster:ku,GridHelper:Cl,GridLayoutGroup:O0,GroundProjectedEnv:Hs,GroupActionModel:Eo,HideOnStart:gl,HingeJoint:vh,HorizontalLayoutGroup:C0,Image:jl,InheritVelocityModule:Qr,InputField:sa,InstanceHandle:qu,InstancingHandler:nl,Interactable:Rf,Keyframe:fi,LODGroup:_h,LODModel:Ol,Light:gi,LimitVelocityOverLifetimeModule:mt,LogStats:Mf,LookAt:na,LookAtConstraint:Mr,MainModule:Ht,MaskableGraphic:fh,MeshCollider:Ro,MeshRenderer:th,MinMaxCurve:Z,MinMaxGradient:yi,NeedleMenu:nn,NestedGltf:fp,Networking:Pl,NoiseModule:Pe,ObjectRaycaster:Ei,OffsetConstraint:qr,OpenURL:Dl,OrbitControls:be,Outline:xl,Padding:Vr,ParticleBurst:wp,ParticleSubEmitter:N0,ParticleSystem:lt,ParticleSystemRenderer:ss,PhysicsExtension:y0,PixelationEffect:Mh,PlayAnimationOnClick:Fr,PlayAudioOnClick:Io,PlayableDirector:Zo,PlayerColor:Wl,PointerEventData:id,PostProcessingHandler:ny,PreliminaryAction:yl,PreliminaryTrigger:oh,RawImage:Gp,Rect:Xx,RectTransform:Wt,ReflectionProbe:sl,RegisteredAnimationInfo:ir,RemoteSkybox:cn,Renderer:Ze,RendererLightmap:Gu,Rigidbody:ye,RotationBySpeedModule:is,RotationOverLifetimeModule:Es,SceneSwitcher:ot,ScreenCapture:Xo,ScreenSpaceAmbientOcclusion:qn,ScreenSpaceAmbientOcclusionN8:Is,SetActiveOnClick:Br,ShadowCatcher:Ah,ShapeModule:et,SharpeningEffect:Th,SignalAsset:Wp,SignalReceiver:Il,SignalReceiverEvent:Bh,SignalTrackHandler:Nh,Size:Gx,SizeBySpeedModule:vi,SizeOverLifetimeModule:Xr,SkinnedMeshRenderer:$f,SmoothFollow:Qo,SpatialGrabRaycaster:Va,SpatialHtml:Wh,SpatialTrigger:Dh,SpatialTriggerReceiver:hn,SpectatorCamera:Fp,SphereCollider:Qa,Sprite:Nn,SpriteData:jo,SpriteRenderer:mi,SpriteSheet:vl,SubEmitterSystem:Mp,SyncedCamera:Up,SyncedRoom:js,SyncedTransform:qs,TapGestureTrigger:o0,TeleportTarget:cp,TestRunner:uy,TestSimulateUserData:py,Text:Vt,TextBuilder:x0,TextExtension:pp,TextureSheetAnimationModule:$t,TiltShiftEffect:ln,ToneMappingEffect:$o,TrailModule:qe,TransformData:Ke,TransformGizmo:ta,TriggerBuilder:Rt,TriggerModel:Lr,UIRaycastUtils:pf,UIRootComponent:Nc,USDZExporter:$e,USDZText:Wr,USDZUIExtension:M0,UsageMarker:Zc,VariantAction:s0,VelocityOverLifetimeModule:tt,VerticalLayoutGroup:S0,VideoPlayer:gt,Vignette:ea,VisibilityAction:rh,Voip:Mo,Volume:Al,VolumeParameter:N,VolumeProfile:Rp,WebARCameraBackground:$h,WebARSessionRoot:sn,WebXR:Je,WebXRImageTracking:oa,WebXRImageTrackingModel:Kn,WebXRPlaneTracking:Jn,WebXRTrackedImage:qh,XRControllerFollow:Zn,XRControllerModel:on,XRControllerMovement:ji,XRFlag:Ai,XRRig:Yp,XRState:ci,__Ignore:uS},Symbol.toStringTag,{value:"Module"})),tm=C("debugmissingcamera");ue.registerCallback(ge.MissingCamera,s=>{var t,i,n,o;tm&&console.warn("Creating missing camera");const r=s.context.scene,l=new _e;l.name="Default Fallback Camera",r.add(l);const c=new Oe;c.sourceId=((i=(t=s.files)==null?void 0:t[0])==null?void 0:i.src)??"unknown",(n=s.context.domElement.getAttribute("skybox-image"))!=null&&n.length||(o=s.context.domElement.getAttribute("background-image"))!=null&&o.length||s.context.lightmaps.tryGetSkybox(c.sourceId)?c.clearFlags=Oo.Skybox:c.clearFlags=Oo.SolidColor,c.backgroundColor=new xe(.5,.5,.5,1),c.fieldOfView=35,s.context.domElement.getAttribute("transparent")!=null&&(c.clearFlags=Oo.Uninitialized),c.backgroundBlurriness=.2;const h=fr(l,c,!0);l.position.x=0,l.position.y=1,l.position.z=2;const d=s.context.domElement;return d?.cameraControls!=!1&&pS(s.context,h),h}),ue.registerCallback(ge.ContextCreated,s=>{if(!s.context.mainCamera){tm&&console.log("Will not auto-fit because a default camera exists");return}const t=s.context.domElement;if(t?.cameraControls==!0){const i=Uv(s.context.mainCamera);if(i?.isCameraController==!0){tm&&console.log("Will not auto-fit because a camera controller exists");return}pS(s.context)}});function pS(s,t){t=t??s.mainCameraComponent;const i=t?.gameObject;if(tm&&console.log("Creating default camera controls",t?.name),i){const n=Sc(i,be);n.sourceId=t?.sourceId??"unknown";const o=s.domElement.getAttribute("auto-rotate");if(n.autoRotate=o!=null&&o!="0"&&o?.toLowerCase()!="false",n.autoRotateSpeed=.5,n.autoFit=!0,n.autoRotate&&o){const r=parseFloat(o);isNaN(r)||(n.autoRotateSpeed=r)}}else console.warn("Missing camera object, can not add orbit controls")}ue.registerCallback(ge.ContextCreated,s=>{const t=s.context.domElement.getAttribute("autoplay");if(t!==void 0&&(t===""||t==="true"||t==="1")&&s.files)for(const i of s.files)O.foreachComponent(i.file.scene,n=>{if(n.enabled!==!1){if(n instanceof zt&&n.playAutomatically||n instanceof Pt||n instanceof Zo&&n.playOnAwake===!0)return!0;if(n instanceof zt)return n.playAutomatically=!0,!0;if(n instanceof Zo)return n.playOnAwake=!0,!0}},!0)!==!0&&Ba.assignAnimationsFromFile(i.file,{createAnimationComponent:(n,o)=>Mi(n,zt)})});class Yj extends hO{constructor(){super(new dO),this.name="GenerateMeshBVHWorker"}runTask(t,i,n={}){return new Promise((o,r)=>{if(i.getAttribute("position").isInterleavedBufferAttribute||i.index&&i.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");t.onerror=d=>{r(new Error(`GenerateMeshBVHWorker: ${d.message}`))},t.onmessage=d=>{const{data:u}=d;if(u.error)r(new Error(u.error)),t.onmessage=null;else if(u.serialized){const{serialized:p,position:g}=u,y=uO.deserialize(p,i,{setIndex:!1}),f=Object.assign({setBoundingBox:!0},n);if(i.attributes.position.array=g,p.index)if(i.index)i.index.array=p.index;else{const v=new ft(p.index,1,!1);i.setIndex(v)}f.setBoundingBox&&(i.boundingBox=y.getBoundingBox(new wi)),n.onProgress&&n.onProgress(u.progress),o(y),t.onmessage=null}else n.onProgress&&n.onProgress(u.progress)};const l=i.index?i.index.array:null,c=i.attributes.position.array,h=[c];l&&h.push(l),t.postMessage({index:l,position:c,options:{...n,onProgress:null,includedProgressCallback:!!n.onProgress,groups:[...i.groups]}},h.map(d=>d.buffer).filter(d=>typeof SharedArrayBuffer>"u"||!(d instanceof SharedArrayBuffer)))})}}const Zj=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:Yj},Symbol.toStringTag,{value:"Module"}));export{_g as $,Ba as A,we as B,ee as C,rc as D,F as E,gP as F,O as G,hr as H,as as I,Qm as J,nb as K,Oi as L,j as M,J as N,F_ as O,le as P,Jd as Q,z_ as R,tu as S,k as T,U_ as U,bs as V,iu as W,Pn as X,qb as Y,d2 as Z,Xb as _,Pw as a,dc as a$,u2 as a0,Ee as a1,Zb as a2,wg as a3,m2 as a4,Ug as a5,Sc as a6,fr as a7,Mi as a8,k_ as a9,Ty as aA,kk as aB,of as aC,af as aD,Ds as aE,Ia as aF,Mc as aG,E_ as aH,A_ as aI,Xd as aJ,Ng as aK,vr as aL,j_ as aM,ja as aN,Ri as aO,br as aP,Zd as aQ,La as aR,gs as aS,wm as aT,Dj as aU,Bj as aV,Fj as aW,Uj as aX,Pd as aY,Be as aZ,wn as a_,yr as aa,Cc as ab,Oc as ac,Aa as ad,Pc as ae,Hd as af,kc as ag,T_ as ah,yc as ai,xd as aj,Ym as ak,cc as al,_n as am,dr as an,hc as ao,vk as ap,bk as aq,Me as ar,pu as as,ge as at,ue as au,$g as av,K2 as aw,W_ as ax,ur as ay,po as az,Zk as b,My as b$,FP as b0,ai as b1,gb as b2,W as b3,fd as b4,jm as b5,li as b6,uc as b7,Mb as b8,se as b9,bf as bA,zw as bB,Uw as bC,qc as bD,sd as bE,Qs as bF,_s as bG,Gt as bH,_v as bI,Sd as bJ,jP as bK,Cd as bL,Ws as bM,yg as bN,Ed as bO,_t as bP,wu as bQ,st as bR,Na as bS,ed as bT,yo as bU,$_ as bV,q_ as bW,za as bX,au as bY,Q_ as bZ,Y_ as b_,QP as ba,YP as bb,ZP as bc,Rb as bd,rg as be,Tb as bf,_r as bg,Zw as bh,uR as bi,To as bj,Dt as bk,o_ as bl,wc as bm,Tg as bn,r_ as bo,S2 as bp,a_ as bq,Eg as br,l_ as bs,c_ as bt,d_ as bu,$P as bv,qP as bw,Cb as bx,Pb as by,Xs as bz,Kk as c,gO as c$,G1 as c0,aa as c1,Mj as c2,Rj as c3,Ry as c4,Q1 as c5,Vd as c6,Bg as c7,y_ as c8,m as c9,Nm as cA,Wm as cB,ic as cC,Vm as cD,sc as cE,_d as cF,aP as cG,Yv as cH,$i as cI,Zv as cJ,lP as cK,Hm as cL,Kv as cM,oi as cN,Jv as cO,eb as cP,$m as cQ,K_ as cR,fx as cS,ce as cT,Au as cU,Lw as cV,EM as cW,Dw as cX,Bw as cY,Fw as cZ,xv as c_,Pr as ca,aM as cb,cM as cc,Rw as cd,Ou as ce,pM as cf,Tw as cg,Ew as ch,Vj as ci,Ua as cj,YO as ck,ZO as cl,tc as cm,G as cn,Vv as co,ys as cp,te as cq,ht as cr,lr as cs,Ce as ct,Hi as cu,Um as cv,Ye as cw,wa as cx,nP as cy,Gv as cz,Cw as d,ww as d$,fO as d0,Ci as d1,Ql as d2,C as d3,yO as d4,Yl as d5,Cm as d6,Sv as d7,Om as d8,vO as d9,jO as dA,LO as dB,DO as dC,Rv as dD,Tv as dE,km as dF,Mm as dG,Ev as dH,V1 as dI,H1 as dJ,aj as dK,wy as dL,z1 as dM,Hh as dN,Hj as dO,qj as dP,p_ as dQ,zu as dR,Ms as dS,BR as dT,FR as dU,Nu as dV,Wu as dW,Wf as dX,Vf as dY,Fk as dZ,Dc as d_,bO as da,Pv as db,kv as dc,ba as dd,Zl as de,fs as df,Kl as dg,Mv as dh,_O as di,lo as dj,eo as dk,md as dl,Pm as dm,X as dn,xO as dp,SO as dq,CO as dr,OO as ds,PO as dt,kO as du,MO as dv,RO as dw,TO as dx,EO as dy,AO as dz,Yk as e,Bu as e$,_o as e0,cf as e1,S_ as e2,C_ as e3,$d as e4,xe as e5,kn as e6,Fy as e7,zr as e8,Ot as e9,wf as eA,Tr as eB,Ga as eC,zy as eD,hS as eE,Xa as eF,Of as eG,Ji as eH,Oe as eI,Er as eJ,Ln as eK,di as eL,Qa as eM,Ya as eN,Ro as eO,In as eP,Ps as eQ,Mf as eR,Kc as eS,Tf as eT,Lu as eU,ui as eV,Dn as eW,Ja as eX,Rn as eY,Cu as eZ,Se as e_,tw as ea,Yg as eb,Od as ec,DP as ed,Jm as ee,BP as ef,pb as eg,mb as eh,eg as ei,Eb as ej,Ub as ek,A as el,Oo as em,Af as en,uS as eo,Lc as ep,zt as eq,fi as er,kl as es,Pt as et,ls as eu,Tn as ev,Ne as ew,En as ex,Hc as ey,Gc as ez,Qk as f,et as f$,qf as f0,ih as f1,ir as f2,Ke as f3,sp as f4,s0 as f5,zx as f6,da as f7,f0 as f8,Dr as f9,Cl as fA,Hs as fB,Zc as fC,Rf as fD,L0 as fE,vh as fF,gi as fG,Ol as fH,_h as fI,Mr as fJ,nn as fK,fp as fL,Pl as fM,qr as fN,Wc as fO,be as fP,ss as fQ,lt as fR,Mp as fS,Gr as fT,Z as fU,yi as fV,Ht as fW,wp as fX,$n as fY,xp as fZ,Xr as f_,pl as fa,Br as fb,gl as fc,fl as fd,Io as fe,Fr as ff,yl as fg,oh as fh,rh as fi,o0 as fj,Nt as fk,Lr as fl,Rt as fm,Eo as fn,ts as fo,ve as fp,y0 as fq,dS as fr,Wr as fs,x0 as ft,pp as fu,M0 as fv,Hr as fw,$e as fx,Sl as fy,$r as fz,Ek as g,ta as g$,Pe as g0,qe as g1,tt as g2,$t as g3,Es as g4,is as g5,mt as g6,Qr as g7,vi as g8,Ml as g9,Gu as gA,ye as gB,ot as gC,Xo as gD,Ah as gE,cn as gF,Qo as gG,hn as gH,Dh as gI,Fp as gJ,Nn as gK,vl as gL,jo as gM,mi as gN,Up as gO,js as gP,qs as gQ,uy as gR,py as gS,Zo as gT,Wp as gU,Bh as gV,Il as gW,Vp as gX,Uh as gY,Nh as gZ,Hp as g_,N0 as ga,Wl as gb,Oh as gc,Zr as gd,Ph as ge,qo as gf,As as gg,kh as gh,Mh as gi,qn as gj,Is as gk,Th as gl,ln as gm,$o as gn,ea as go,ny as gp,Al as gq,N as gr,Rp as gs,sl as gt,mx as gu,Ze as gv,th as gw,$f as gx,nl as gy,qu as gz,Qj as h,bl as h$,rs as h0,Nc as h1,Yn as h2,Et as h3,Uo as h4,si as h5,Ur as h6,fh as h7,jl as h8,Gp as h9,sn as hA,Je as hB,Mt as hC,qh as hD,Kn as hE,oa as hF,Jn as hG,Yp as hH,ci as hI,Ai as hJ,Px as hK,kx as hL,Rs as hM,wx as hN,Gf as hO,Yt as hP,_x as hQ,ct as hR,ns as hS,Ui as hT,dn as hU,gy as hV,Fh as hW,Su as hX,Ys as hY,Ho as hZ,bp as h_,sa as ha,Vr as hb,S0 as hc,C0 as hd,O0 as he,xl as hf,id as hg,Ei as hh,ku as hi,Va as hj,pf as hk,Gx as hl,Xx as hm,Wt as hn,Wh as ho,Vt as hp,na as hq,Dl as hr,gt as hs,Mo as ht,Do as hu,Zn as hv,on as hw,ji as hx,cp as hy,$h as hz,Uv as i,$x as i0,Ii as i1,ig as i2,sg as i3,xb as i4,Sb as i5,Lm as j,q as k,Y1 as l,Cs as m,tf as n,Ow as o,vo as p,u0 as q,M2 as r,vd as s,eM as t,Nv as u,kt as v,HO as w,Lv as x,UO as y,De as z};