@needle-tools/engine 3.37.5-alpha → 3.37.6-alpha

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.
@@ -4340,7 +4340,7 @@ void main() {
4340
4340
  }`),r(Rs,"blipMaterial"),r(Rs,"mesh");function fH(g){return Rs.copyTexture(g)}function Z9(g,A=!1){return Rs.textureToCanvas(g,A)}function j9(g){return typeof HTMLImageElement<"u"&&g instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&g instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&g instanceof OffscreenCanvas||typeof ImageBitmap<"u"&&g instanceof ImageBitmap}let hf=!1;H5((...g)=>{var A;he()&&((A=st.Current)!=null&&A.isInXR)&&(Ic(!0),DH("error",...g))});function Ic(g){if(g){if(hf)return;hf=!0,z9()}else{if(!hf)return;hf=!1,X9()}}const Uh={log:void 0,warn:void 0,error:void 0};class V9{constructor(){r(this,"familyName","needle-xr");r(this,"root",null);r(this,"context",null);r(this,"defaultFontSize",.06);r(this,"targetObject",new uA);r(this,"userForwardViewPoint",new w);r(this,"oneEuroFilter",new OR(90,.8));r(this,"_lastElementRemoveTime",0);r(this,"onBeforeRender",()=>{var e,t;const A=(e=this.context)==null?void 0:e.mainCamera;if(this.context&&A instanceof He){const i=this.getRoot();Number.isNaN(i.position.x)&&i.position.set(0,0,0),Number.isNaN(i.quaternion.x)&&i.quaternion.set(0,0,0,1),this.context.scene.add(this.targetObject);const I=((t=this.context.xr)==null?void 0:t.rigScale)??1,o=3.5*I,s=A.worldForward;s.y=0,s.normalize().multiplyScalar(o),this.userForwardViewPoint.copy(A.worldPosition).sub(s),this.targetObject.position.distanceTo(this.userForwardViewPoint)>2*I&&(this.targetObject.position.copy(this.userForwardViewPoint),Qu(this.targetObject,A,!0,!0),this.targetObject.rotateY(Math.PI)),this.oneEuroFilter.filter(this.targetObject.position,i.position,this.context.time.time);const C=this.context.time.deltaTime;if(i.quaternion.slerp(this.targetObject.quaternion,C*5),i.scale.setScalar(I),this.targetObject.removeFromParent(),this.context.scene.add(i),this.context.time.time-this._lastElementRemoveTime>.1){this._lastElementRemoveTime=this.context.time.time;const a=Date.now();for(let B=0;B<this._activeTexts.length;B++){const Q=this._activeTexts[B];if(Q instanceof _t.Text&&a-Q._activatedTime>2e4){Q.removeFromParent(),this._textBuffer.push(Q),this._activeTexts.splice(B,1);break}}}}});r(this,"textOptions",{fontSize:this.defaultFontSize,fontFamily:this.familyName,padding:.03,margin:.005,color:0,backgroundColor:16777215,backgroundOpacity:.4,borderRadius:.03,offset:.025});r(this,"_textBuffer",[]);r(this,"_activeTexts",[]);this.ensureFont()}onEnable(){this.context=st.Current||st.All[0],this.context.pre_render_callbacks.push(this.onBeforeRender)}onDisable(){var A,e,t;(e=this.context)==null||e.pre_render_callbacks.splice((A=this.context)==null?void 0:A.pre_render_callbacks.indexOf(this.onBeforeRender),1),(t=this.root)==null||t.removeFromParent()}addLog(A,e){const t=this.getRoot(),i=this.getText();let I=16777215,o=0;switch(A){case"log":I=16777215,o=0;break;case"warn":I=16772761,o=4465152;break;case"error":I=16755370,o=7798784;break}e.length>1e3&&(e=e.substring(0,1e3)+"...");const s=new Date().toISOString().split("T")[1].split(".")[0];i.textContent="["+s+"] "+e,i.visible=!0,i._activatedTime=Date.now(),t.add(i),this._activeTexts.push(i),this.context&&this.context.scene.add(t),i.set({backgroundColor:I,color:o}),_t.update()}ensureFont(){let A=_t.FontLibrary.getFontFamily(this.familyName);if(!A){A=_t.FontLibrary.addFontFamily(this.familyName);const e=A.addVariant("normal","normal","./include/needle/arial-msdf.json","./include/needle/arial.png");e==null||e.addEventListener("ready",()=>{_t.update()})}}getText(){const A=this.getRoot();if(this._textBuffer.length>0){const t=this._textBuffer.pop();return t.visible=!0,setTimeout(()=>this.disableDepthTestRecursive(t),100),t}if(A.children.length>20&&this._activeTexts.length>0)return this._activeTexts.shift();const e=new _t.Text(this.textOptions);return setTimeout(()=>this.disableDepthTestRecursive(e),500),setTimeout(()=>this.disableDepthTestRecursive(e),1500),e}disableDepthTestRecursive(A,e=0){for(let i=0;i<A.children.length;i++){const I=A.children[i];I instanceof uA&&this.disableDepthTestRecursive(I,e+1)}A.renderOrder=10*e,A.layers.set(2);const t=A.material;t&&(t.depthWrite=!1,t.depthTest=!1,t.transparent=!0),e===0&&_t.update()}getRoot(){if(this.root)return this.root;const A=this.defaultFontSize,e={boxSizing:"border-box",fontFamily:this.familyName,width:"2.6",fontSize:A,color:0,lineHeight:1,backgroundColor:16777215,backgroundOpacity:0,whiteSpace:"pre-wrap",flexDirection:"column-reverse"};return this.root=new _t.Block(e),this.root}}let UI=null;function z9(){UI||(UI=new V9),UI.onEnable();for(const g in Uh){Uh[g]=console[g];let A=!1;console[g]=function(){var e;if((e=Uh[g])==null||e.apply(console,arguments),!A)try{A=!0,DH(g,...arguments)}finally{A=!1}}}}function X9(){UI==null||UI.onDisable();for(const g in Uh)console[g]=Uh[g]}const wl=new Map;function DH(g,...A){try{switch(wl.clear(),g){case"log":UI==null||UI.addLog("log",e());break;case"warn":UI==null||UI.addLog("warn",e());break;case"error":UI==null||UI.addLog("error",e());break}}catch(I){console.error("Error in spatial console",I)}finally{wl.clear()}function e(){let I="";for(let o=0;o<A.length;o++){const s=A[o];I+=t(s),o<A.length-1&&(I+=", ")}return I}function t(I,o=0){if(typeof I=="string")return'"'+I+'"';if(typeof I=="number"){if(I%1!==0){const n=I.toFixed(5),C=n.indexOf(".");let a=n.length-1;for(;a>C&&n[a]==="0";)a--;return n.substring(0,a+1)}return I.toString()}else if(Array.isArray(I)){let s="[";for(let n=0;n<I.length;n++){const C=I[n];s+=t(C,o+1),n<I.length-1&&(s+=", ")}return s+="]",s}else{if(I===null)return"null";if(I===void 0)return"undefined";if(typeof I=="function")return I.name+"()"}if(I instanceof iA)return`(${t(I.x)}, ${t(I.y)})`;if(I instanceof w)return`(${t(I.x)}, ${t(I.y)}, ${t(I.z)})`;if(I instanceof Ae)return`(${t(I.x)}, ${t(I.y)}, ${t(I.z)}, ${t(I.w)})`;if(I instanceof MA)return`(${t(I.x)}, ${t(I.y)}, ${t(I.z)}, ${t(I.w)})`;if(I instanceof be||I instanceof fe)return I.name;if(I instanceof Le)return`[${I.elements.join(", ")}]`;if(I instanceof GA)return`[${I.elements.join(", ")}]`;if(I instanceof QI)return I.mask.toString();if(typeof I=="object"){if(wl.has(I))return"*";let s=`{
4341
4341
  `;s+=i(o);const n=Object.keys(I);let C="";for(let a=0;a<n.length;a++){const B=n[a],Q=I[B];if(wl.has(Q)){C+="";continue}wl.set(Q,!0),C+=B+":"+t(Q,o+1),a<n.length-1&&(C+=", "),C.length>=60&&(C+=`
4342
4342
  `,C+=i(o),s+=C,C="")}return s+=C,s+=`
4343
- }`,s}return I}function i(I){let o="";for(let s=0;s<I;s++)o+=" ";return o}}const $9=IA("nodevlogs");function Ci(g,A=So.Log){Dn(A,g)}function fi(g){Ci(g,So.Warn)}function XR(g){Ci(g,So.Error)}let $k;function he(){return $9?!1:$k!==void 0?$k:No()}function A6(g){$k=g}const wH=IA("debugdefines");kc('if(!globalThis[""3.37.5-alpha""]) globalThis[""3.37.5-alpha""] = "0.0.0";');kc('if(!globalThis[""undefined""]) globalThis[""undefined""] = "unknown";');kc('if(!globalThis[""Tue Apr 23 2024 09:16:03 GMT+0200 (Central European Summer Time)""]) globalThis[""Tue Apr 23 2024 09:16:03 GMT+0200 (Central European Summer Time)""] = "unknown";');kc('globalThis["__NEEDLE_ENGINE_VERSION__"] = "3.37.5-alpha";');kc('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');kc('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Tue Apr 23 2024 09:16:03 GMT+0200 (Central European Summer Time)";');const yn="3.37.5-alpha",Xy="undefined",$R="Tue Apr 23 2024 09:16:03 GMT+0200 (Central European Summer Time)";wH&&console.log(`Engine version: ${yn} (generator: ${Xy})
4343
+ }`,s}return I}function i(I){let o="";for(let s=0;s<I;s++)o+=" ";return o}}const $9=IA("nodevlogs");function Ci(g,A=So.Log){Dn(A,g)}function fi(g){Ci(g,So.Warn)}function XR(g){Ci(g,So.Error)}let $k;function he(){return $9?!1:$k!==void 0?$k:No()}function A6(g){$k=g}const wH=IA("debugdefines");kc('if(!globalThis[""3.37.6-alpha""]) globalThis[""3.37.6-alpha""] = "0.0.0";');kc('if(!globalThis[""undefined""]) globalThis[""undefined""] = "unknown";');kc('if(!globalThis[""Wed Apr 24 2024 17:26:38 GMT+0200 (Central European Summer Time)""]) globalThis[""Wed Apr 24 2024 17:26:38 GMT+0200 (Central European Summer Time)""] = "unknown";');kc('globalThis["__NEEDLE_ENGINE_VERSION__"] = "3.37.6-alpha";');kc('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');kc('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Wed Apr 24 2024 17:26:38 GMT+0200 (Central European Summer Time)";');const yn="3.37.6-alpha",Xy="undefined",$R="Wed Apr 24 2024 17:26:38 GMT+0200 (Central European Summer Time)";wH&&console.log(`Engine version: ${yn} (generator: ${Xy})
4344
4344
  Project built at ${$R}`);const RC="needle_isActiveInHierarchy",iB="builtin_components",Rh="needle_editor_guid";function kc(g){try{(0,eval)(g)}catch(A){wH&&console.error(A)}}const e6='<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>',t6=btoa(e6),i6="data:image/svg+xml;base64,"+t6,g6=i6,I6=`<?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(I6);const o6='<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>',s6=btoa(o6),n6="data:image/svg+xml;charset=utf-8;base64,"+s6,C6=n6,ts=IA("debuglicense");let fB="basic";ts&&console.log("License Type: "+fB);function Hs(){switch(fB){case"pro":case"enterprise":return!0}return!1}function AN(){switch(fB){case"indie":return!0}return!1}function oc(){return Hs()||AN()}const yH=[];function a6(g){if(Hs()||AN())return g(!0);yH.push(g)}function r6(g){for(const A of yH)try{A(g)}catch{}}st.registerCallback(di.ContextRegistered,g=>{E6(g.context),l6(),Q6(g.context)});let Wa,AM=!1,Ah="";async function B6(){if(Wa)return Wa;if(fB==="basic")try{const g="https://engine.needle.tools/licensing/check?location="+encodeURIComponent(window.location.href)+"&version="+yn+"&generator="+encodeURIComponent(Xy),A=await fetch(g,{method:"GET"}).catch(e=>{ts&&console.error("License check failed",e)});(A==null?void 0:A.status)===200?(AM=!1,ts&&console.log("License check succeeded"),fB="pro",r6(!0)):(A==null?void 0:A.status)===403?(AM=!0,Ah=await A.text()):ts&&console.log("License check failed with status "+(A==null?void 0:A.status))}catch(g){ts&&console.error("License check failed",g)}else ts&&console.log('Runtime license check is skipped because license is already applied as "'+fB+'"')}Wa=B6();async function Q6(g){function A(){const i=document.createElement("div");i.className="needle-forbidden",i.style.cssText=`
4345
4345
  position: fixed;
4346
4346
  top: 0;
@@ -5506,8 +5506,8 @@ Could not find method ${a.method} on object ${Q.name}. Please rename ${a.method}
5506
5506
  Could not find method ${a.method} on object ${Q.name}`,Q,typeof Q[a.method])};if(typeof Q[a.method]!="function"){let u=!1,f=Q;for(;f;){const k=Object.getOwnPropertyDescriptor(f,a.method);if(k&&(k.writable===!0||k.set)){u=!0;break}f=Object.getPrototypeOf(f)}!u&&(he()||Og)&&h()}}let c=a.argument;c!==void 0?c=B(c):a.arguments!==void 0&&(c=a.arguments.map(B));const d=E?this.createEventMethod(Q,a.method,c):void 0,l=new rc(d,a.enabled);if(l.method||(l[CgA]=(o=e.object)==null?void 0:o.name),!Q||!l.method){const h=e.object?"Current object: "+e.object.name+", "+e.object.guid:null;Q?console.warn('EventList method not found: "'+a.method+'" on',Q):console.warn("EventList is missing target - will be ignored",a.target,h,A)}else s.push(l)}const n=new rg(s);Og&&console.log(n);const C=e.target;return C!==void 0&&e.path!==void 0&&n.setEventTarget(e.path,C),n}}createEventMethod(A,e,t){return(...i)=>{const I=A[e];typeof I=="function"?t!==void 0?Array.isArray(t)?I==null||I.call(A,...t):I==null||I.call(A,t):I==null||I.call(A,...i):A[e]=t}}}const rgA=new agA;class xO extends qn{constructor(){super([za,Xe])}onSerialize(A,e){}onDeserialize(A,e){if(A instanceof fe&&e.type===za){const t=A,i=new za(t.image.width,t.image.height,{colorSpace:yt});return i.texture=t,t.isRenderTargetTexture=!0,t.flipY=!0,t.offset.y=1,t.repeat.y=-1,t.needsUpdate=!0,t.mipmaps=[],t instanceof kn&&(t.isCompressedTexture=!1,t.format=RGBAFormat),i}}}new xO;class LO extends qn{constructor(){super([URL])}onSerialize(A,e){return null}onDeserialize(A,e){if(typeof A=="string"&&A.length>0)return PC(e.gltfId,A)}}new LO;var BgA=Object.defineProperty,QgA=Object.getOwnPropertyDescriptor,EgA=(g,A,e,t)=>{for(var i=t>1?void 0:t?QgA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&BgA(A,e,i),i};class Ru extends RA{awake(){Ao.createIfNoneExists(this.context)}onEnable(){var A;(A=Ao.get(this.context))==null||A.register(this)}onDisable(){var A;(A=Ao.get(this.context))==null||A.unregister(this)}}class Ko extends Ru{constructor(){super(...arguments);r(this,"targets",null);r(this,"raycastHits",[]);r(this,"ignoreSkinnedMeshes",!1)}start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??(e=new Bs),e.targets=this.targets,e.results=this.raycastHits;const t=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=I=>I instanceof Mo?"continue in children":t?t(I):!0);const i=this.context.physics.raycast(e);return e.testObject=t,i}}EgA([D()],Ko.prototype,"ignoreSkinnedMeshes",2);class uS extends Ko{constructor(){super(),this.ignoreSkinnedMeshes=!0}}class Nd extends Ru{performRaycast(A){if(!Se.active||!(A!=null&&A.ray))return null;const e=A.ray.origin,t=.01;return this.context.physics.sphereOverlap(e,t)}}class pS{static getObject(A){const e=A[is];return e&&(e.isComponent===!0?A=e.gameObject:A=e),A}static isInteractable(A,e){if(e&&(e.canvasGroup=void 0,e.graphic=void 0),A==null||!A.visible||(A=this.getObject(A),!A.visible))return!1;const t=this.tryFindCanvasGroup(A);if((t==null?void 0:t.isCanvasGroup)===!0&&(e&&(e.canvasGroup=t),t.blocksRaycasts===!1||t.interactable===!1))return!1;const i=HB(A,I=>{if(I.isGraphic===!0)return I},!1);return e&&(i==null?void 0:i.isGraphic)===!0&&(e.graphic=i),!((i==null?void 0:i.raycastTarget)===!1||(i==null?void 0:i.layer)===2)}static tryFindCanvasGroup(A){if(!A)return null;const e=HB(A,t=>{const i=t;if(i.blocksRaycasts!==void 0&&i.interactable!==void 0)return i},!1);return e!==void 0?e:this.tryFindCanvasGroup(A.parent)}}function xN(g){const A=g[is];return A||(g.parent?xN(g.parent):null)}function cgA(g){return g.isUI===!0||typeof g[is]=="object"}function bw(g,A){if(!g)return;const e=g.material;if((e==null?void 0:e.isMaterial)===!0){const t=g.parent;t&&t.isText,e.side=A.doubleSided??!0?ht:Pg,e.shadowSide=A.doubleSided?ht:Pg,g.castShadow=A.castShadows?A.castShadows:!1,g.receiveShadow=A.receiveShadows?A.receiveShadows:!1}for(const t of g.children)bw(t,A)}function EE(g,A,e){g[A]===void 0&&console.warn("Field",A,"is undefined on",g);const t=Proxy.revocable(g[A],{set(o,s,n,C){const a=o[s],B=Reflect.set(o,s,n,C);return e(n,a),B}}),i=t.revoke,I=g[A];return t.revoke=()=>{g[A]=I,i()},g[A]=t.proxy,t}const bq=Symbol("Scheduled action");function lgA(g,A,e=Ai.OnBeforeRender){let t=g[bq];t||(t=g[bq]={});const i=A.name;t[e]||(t[e]={});const I=t[e];if(I[i])return;function*s(){A==null||A.call(g),I[i]=null}const n=g.startCoroutine(s(),e);I[i]=n}const oC=IA("debugeventsystem");var ZM=(g=>(g.BeforeHandleInput="BeforeHandleInput",g.AfterHandleInput="AfterHandleInput",g))(ZM||{});const Bn=class extends RA{constructor(){super();r(this,"raycaster",[]);r(this,"_handleInputFn");r(this,"pressedByID",new Map);r(this,"hoveredByID",new Map);r(this,"_sortedHits",[]);r(this,"_testObjectsCache",new Map);r(this,"_currentlyActiveRaycaster",null);r(this,"_currentPointerEventName",null);r(this,"shouldRaycastObject",e=>{var I;let t=null;if(cgA(e)&&(t=(I=e[is])==null?void 0:I.gameObject),this._testObjectsCache.has(e)||t&&this._testObjectsCache.has(t))return this._testObjectsCache.get(e)===!1?"continue in children":!0;{let o=WM(e,this._currentPointerEventName);if(!o&&t&&(o=WM(t,this._currentPointerEventName)),o){this._testObjectsCache.set(e,!0);for(const s of e.children)this.shouldRaycastObject_AddToYesCache(s);return!0}return this._testObjectsCache.set(e,!1),"continue in children"}});r(this,"_sortingBuffer",[]);r(this,"_noDepthTestingResults",[]);r(this,"out",{});r(this,"_capturedPointer",{});r(this,"pointerEnterSymbol",Symbol("pointerEnter"));r(this,"pointerExitSymbol",Symbol("pointerExit"));r(this,"currentActiveMeshUIComponents",[]);Bn.systems.push(this)}static createIfNoneExists(e){this.didSearchEventSystem||(this.didSearchEventSystem=!0,Bn.systems.length<=0&&Bn.systems.push(...aA.findObjectsOfType(Bn,e)));for(const i of Bn.systems)if(i.context===e)return;const t=new uA;aA.addNewComponent(t,Bn),e.scene.add(t)}static get systems(){const e=ve.Current;return this._eventSystemMap.has(e)||this._eventSystemMap.set(e,[]),this._eventSystemMap.get(e)}static get(e){const t=this._eventSystemMap.get(e);return t&&t.length>0?t[0]:null}static get instance(){return this.systems[0]}static ensureUpdateMeshUI(e,t,i=!1){ba.update(e,t,i)}static markUIDirty(e){ba.markDirty()}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}onDestroy(){Bn.systems.splice(Bn.systems.indexOf(this),1)}start(){if(this.raycaster.length<=0&&!aA.findObjectOfType(Ru,this.context)){const t=aA.addNewComponent(this.context.scene,Ko);this.raycaster.push(t),(he()||oC)&&console.warn("Added an ObjectRaycaster to the scene because no raycaster was found.")}}register(e){var t;e&&this.raycaster&&!this.raycaster.includes(e)&&((t=this.raycaster)==null||t.push(e))}unregister(e){var i,I;const t=(i=this.raycaster)==null?void 0:i.indexOf(e);t!==void 0&&t!==-1&&((I=this.raycaster)==null||I.splice(t,1))}onEnable(){this._handleInputFn??(this._handleInputFn=this.onPointerEvent.bind(this)),this.context.input.addEventListener(ni.PointerDown,this._handleInputFn),this.context.input.addEventListener(ni.PointerUp,this._handleInputFn),this.context.input.addEventListener(ni.PointerMove,this._handleInputFn)}onDisable(){this.context.input.removeEventListener(ni.PointerDown,this._handleInputFn),this.context.input.removeEventListener(ni.PointerUp,this._handleInputFn),this.context.input.removeEventListener(ni.PointerMove,this._handleInputFn)}onBeforeRender(){this.resetMeshUIStates()}onPointerEvent(e){if(e===void 0||e.propagationStopped)return;const t=new vc(this.context.input,e);this._currentPointerEventName=e.type,t.inputSource=this.context.input,t.isClick=e.isClick,t.isDoubleClick=e.isDoubleClick,t.isDown=e.type==ni.PointerDown,t.isUp=e.type==ni.PointerUp,t.isPressed=this.context.input.getPointerPressed(e.pointerId),oC&&(t.isDown?console.log("DOWN",t.pointerId):t.isUp&&console.log("UP",t.pointerId),t.isClick&&console.log("CLICK",t.pointerId));const i=new Bs;e.hasRay?i.ray=e.ray:i.screenPoint=this.context.input.getPointerPositionRC(e.pointerId);const I=this.performRaycast(i);if(I)for(const s of I)s.event=e,e.intersections.push(s);oC&&t.isClick&&Ci("EventSystem: "+t.pointerId+" - "+this.context.time.frame+" - Up:"+t.isUp+", Down:"+t.isDown);const o={sender:this,args:t,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:o})),this.handleIntersections(I,t),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:o}))}shouldRaycastObject_AddToYesCache(e){this._testObjectsCache.set(e,!0);for(const t of e.children)this.shouldRaycastObject_AddToYesCache(t)}performRaycast(e){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,e||(e=new Bs),e.testObject=this.shouldRaycastObject;for(const t of this.raycaster){if(!t.activeAndEnabled)continue;this._currentlyActiveRaycaster=t;const i=t.performRaycast(e);this._currentlyActiveRaycaster=null,i&&i.length>0&&this._sortedHits.push(...i)}return this._sortedHits.sort((t,i)=>t.distance-i.distance),this._sortedHits}assignHitInformation(e,t){t?(e.intersection=t,e.point=t.point,e.normal=t.normal,e.face=t.face,e.distance=t.distance,e.instanceId=t.instanceId):(e.intersection=void 0,e.point=void 0,e.normal=void 0,e.face=void 0,e.distance=void 0,e.instanceId=void 0)}handleIntersections(e,t){var I;if(e!=null&&e.length){e=this.sortCandidates(e);for(const o of e){if(t.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(t,o),this.handleEventOnObject(o.object,t))return!0}}this.assignHitInformation(t,e==null?void 0:e[0]),this.invokePointerCapture(t);const i=this.hoveredByID.get(t.pointerId);return i&&this.propagatePointerExit(i.obj,i.data,null),this.hoveredByID.delete(t.pointerId),t.isUp&&((I=this.pressedByID.get(t.pointerId))==null||I.handlers.forEach(o=>this.invokeOnPointerUp(t,o)),this.pressedByID.delete(t.pointerId)),!1}sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){const i=e[t],I=i.object;if(I.material&&I.material.depthTest===!1){this._noDepthTestingResults.push(i);continue}this._sortingBuffer.push(i)}for(const t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}handleEventOnObject(e,t){if(!this.testIsVisible(e))return t.isClick&&oC&&console.log("not allowed",e),!1;if(t.pointerId===void 0)return oC&&console.error("Event without pointer can't be handled",t),!1;t.object=e;const i=e.parent,I=t.isClick??!1;let o=null;if(i&&i.isUI){const B=(t.isPressed||t.isClick)??!1;if(i[is]){const Q=i[is].gameObject;if(Q){if(!pS.isInteractable(Q,this.out))return!1;o=this.out.canvasGroup??null,this.handleMeshUIIntersection(e,B),e=Q}}}I&&oC&&console.log(this.context.time.frame,e);const s=this.hoveredByID.get(t.pointerId),n=s==null?void 0:s.obj;n!==e&&n&&this.propagatePointerExit(n,s.data,e);const a=this.hoveredByID.get(t.pointerId);if(a?(a.obj=e,a.data=t):this.hoveredByID.set(t.pointerId,{obj:e,data:t}),t.isDown){const B=this.pressedByID.get(t.pointerId);B?(B.obj=e,B.data=t):this.pressedByID.set(t.pointerId,{obj:e,data:t,handlers:new Set})}return(o===null||o.interactable)&&this.handleMainInteraction(e,t,n??null),!0}propagate(e,t){for(;e;)aA.foreachComponent(e,i=>{t(i)},!1),e=e.parent}handleMainInteraction(e,t,i){const I=this.pressedByID.get(t.pointerId),o=i!==e;let s=!0;switch(t.event.pointerType){case"mouse":case"touch":const n=this.context.input.getPointerPositionLastFrame(t.pointerId),C=this.context.input.getPointerPosition(t.pointerId);s=n&&!te.approximately(n,C);break}this.propagate(e,n=>{var a;const C=n;C.interactable!==!1&&(!C.activeAndEnabled||!C.enabled||(C.onPointerEnter&&o&&this.handlePointerEnter(C,t),t.isDown&&C.onPointerDown&&(C.onPointerDown(t),I==null||I.handlers.add(C),this.handlePointerCapture(t,C)),C.onPointerMove&&(s&&C.onPointerMove(t),this.handlePointerCapture(t,C)),t.isUp&&(C.onPointerUp&&(this.invokeOnPointerUp(t,C),I==null||I.handlers.delete(C)),C.onPointerExit&&((a=t.event)==null?void 0:a.pointerType)===nS.Touch&&(this.handlePointerExit(C,t),this.hoveredByID.delete(t.pointerId))),t.isClick&&C.onPointerClick&&C.onPointerClick(t)))}),t.isUp&&(I==null||I.handlers.forEach(n=>{this.invokeOnPointerUp(t,n)}),this.pressedByID.delete(t.pointerId))}propagatePointerExit(e,t,i){this.propagate(e,I=>{if(!I.gameObject||I.destroyed)return;const o=I;if(o.onPointerExit){if(i&&this.isChild(i,I.gameObject))return;this.handlePointerExit(o,t)}})}invokeOnPointerUp(e,t){var i;(i=t.onPointerUp)==null||i.call(t,e),this.releasePointerCapture(e,t)}handlePointerEnter(e,t){e.onPointerEnter&&this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!0)&&e.onPointerEnter(t),this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(e,t){e.onPointerExit&&this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!0)&&e.onPointerExit(t),this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(e,t,i,I){let o=e[i];if(I)return o&&o.includes(t)?!1:(o=o||[],o.push(t),e[i]=o,!0);{if(!o||!o.includes(t))return!1;const s=o.indexOf(t);return s!==-1&&o.splice(s,1),!0}}handlePointerCapture(e,t){if(e.z__pointer_ctured){e.z__pointer_ctured=!1;const i=e.pointerId;if(t.onPointerMove){const I=this._capturedPointer[i]||[];I.push(t),this._capturedPointer[i]=I}else he()&&!t.z__warned_no_pointermove&&(t.z__warned_no_pointermove=!0,console.warn("PointerCapture was requested but the component doesn't implement onPointerMove. It will not receive any pointer events"))}else e.z__pointer_cture_rleased&&(e.z__pointer_cture_rleased=!1,this.releasePointerCapture(e,t))}releasePointerCapture(e,t){const i=e.pointerId;if(this._capturedPointer[i]){const I=this._capturedPointer[i].indexOf(t);I!==-1&&(this._capturedPointer[i].splice(I,1),oC&&console.log("released pointer capture",i,t,this._capturedPointer))}}invokePointerCapture(e){var t;if(e.event.type===ni.PointerMove){const i=e.pointerId,I=this._capturedPointer[i];if(I){oC&&console.log("Captured",i,I);for(let o=0;o<I.length;o++){const s=I[o];if(s.destroyed){I.splice(o,1),o--;continue}(t=s.onPointerMove)==null||t.call(s,e)}}}}isChild(e,t){return!e||!t?!1:e===t?!0:e.parent?this.isChild(e.parent,t):!1}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}handleMeshUIIntersection(e,t){const i=ba.updateState(e,t);return i&&this.currentActiveMeshUIComponents.push(i),i!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&ba.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){const t=this.currentActiveMeshUIComponents[e];ba.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?aA.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}};let Ao=Bn;r(Ao,"_eventSystemMap",new Map),r(Ao,"didSearchEventSystem",!1);class ba{static markDirty(){this.needsUpdate=!0}static update(A,e,t=!1){if(t){A.update();return}const i=e.time.frameCount;for(const I of this.lastUpdateFrame)if(I.context===e){if(i===I.frame)return;I.frame=i;let o=this.needsUpdate||i<1;I.nextUpdate===e.time.frameCount&&(o=!0),o&&(oC&&console.log("Update threemeshui"),this.needsUpdate=!1,A.update());return}this.lastUpdateFrame=[{context:e,frame:i,nextUpdate:i}],A.update()}static updateState(A,e){let t=null;if(A&&(t=this.findBlockInParent(A),t&&t!==this.lastSelected)){if(t.interactable===!1)return null;this.needsUpdate=!0}return t}static resetLastSelected(){const A=this.lastSelected;A&&(this.lastSelected=null,this.resetState(A))}static resetState(A){A&&(this.needsUpdate=!0)}static findBlockInParent(A){return A?A.isBlock?A:this.findBlockInParent(A.parent):null}}r(ba,"lastSelected",null),r(ba,"lastUpdateFrame",[]),r(ba,"needsUpdate",!1);var hgA=Object.defineProperty,dgA=Object.getOwnPropertyDescriptor,bi=(g,A,e,t)=>{for(var i=t>1?void 0:t?dgA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&hgA(A,e,i),i};const ugA=IA("debugorbit"),Kf=IA("freecam"),vl=IA("debugcamerafit"),Jf=IA("smoothcam"),pgA={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let aG;class Fd extends CustomEvent{constructor(A,e){super("target-reached",{detail:{controls:A,type:e}})}}class Rt extends RA{constructor(){super(...arguments);r(this,"autoTarget",!0);r(this,"autoFit",!1);r(this,"enableRotate",!0);r(this,"autoRotate",!1);r(this,"autoRotateSpeed",1);r(this,"minAzimuthAngle",1/0);r(this,"maxAzimuthAngle",1/0);r(this,"minPolarAngle",0);r(this,"maxPolarAngle",Math.PI);r(this,"enableKeys",!0);r(this,"enableDamping",!0);r(this,"dampingFactor",.1);r(this,"enableZoom",!0);r(this,"minZoom",0);r(this,"maxZoom",1/0);r(this,"enablePan",!0);r(this,"lookAtConstraint",null);r(this,"lookAtConstraint01",1);r(this,"allowInterrupt",!0);r(this,"middleClickToFocus",!0);r(this,"doubleClickToFocus",!0);r(this,"useSlerp",!0);r(this,"debugLog",!1);r(this,"targetLerpDuration",1);r(this,"_controls",null);r(this,"_cameraObject",null);r(this,"_lookTargetLerpActive",!1);r(this,"_lookTargetStartPosition",new w);r(this,"_lookTargetEndPosition",new w);r(this,"_lookTargetLerp01",0);r(this,"_lookTargetLerpDuration",0);r(this,"_cameraLerpActive",!1);r(this,"_cameraStartPosition",new w);r(this,"_cameraEndPosition",new w);r(this,"_cameraLerp01",0);r(this,"_cameraLerpDuration",0);r(this,"_inputs",0);r(this,"_enableTime",0);r(this,"_startedListeningToKeyEvents",!1);r(this,"_eventSystem");r(this,"_afterHandleInputFn");r(this,"_camera",null);r(this,"_syncedTransform");r(this,"_didStart",!1);r(this,"_didSetTarget",!1);r(this,"targetElement",null);r(this,"onControlsChangeStarted",()=>{this._syncedTransform&&this._syncedTransform.requestOwnership()});r(this,"_shouldDisable",!1);r(this,"_haveAttachedKeyboardEvents",!1)}get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){var t;(t=this.controls)==null||t.addEventListener("start",e)}get targetLerpSpeed(){return 5}set targetLerpSpeed(e){this.targetLerpDuration=1/e}awake(){this._didStart=!1,this._didSetTarget=!1,this._startedListeningToKeyEvents=!1}start(){this._didStart=!0,this._eventSystem=Ao.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(ZM.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){var e,t;(e=this._controls)==null||e.dispose(),(t=this._eventSystem)==null||t.removeEventListener(ZM.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._enableTime=this.context.time.time;const e=aA.getComponent(this.gameObject,Wt);this._camera=e;let t=e==null?void 0:e.cam;if(!t&&this.gameObject instanceof He&&(t=this.gameObject),t&&HM(t,this,!0),!this._controls&&t instanceof He){this._cameraObject=t;const i=this.targetElement??this.context.renderer.domElement,I=t==null?void 0:t.quaternion.clone();this._controls=new OiA(t,i),t==null||t.quaternion.copy(I),aG===void 0&&(aG={...this._controls.keys})}this._controls&&(Kf&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,vo()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),(t==null?void 0:t.type)==="PerspectiveCamera"?Kf||(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):Kf||(this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom),this._startedListeningToKeyEvents||(this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(window.document.body))),this._syncedTransform=aA.getComponent(this.gameObject,sr)??void 0}onDisable(){var e;(e=this._camera)!=null&&e.cam&&HM(this._camera.cam,this,!1),this._controls&&(this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted))}afterHandleInput(e){e.detail.args.pointerId===0&&(e.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!e.detail.args.isPressed||e.detail.args.isUp)&&(this._shouldDisable=!1))}onBeforeRender(){var t,i;if(!this._controls)return;if(this._cameraObject!==this.context.mainCamera){this._controls.enabled=!1;return}this._controls.enabled=!0,this.__handleSetTargetWhenBecomingActiveTheFirstTime(),(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;let e=this.middleClickToFocus&&this.context.input.getPointerClicked(1);if(e||(e=this.doubleClickToFocus&&this.context.input.getPointerDoubleClicked(0)&&this.context.time.time-this._enableTime>.3),e&&this.setTargetFromRaycast(),this._lookTargetLerpActive||this._cameraLerpActive){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 Fd(this,"camera"));else{const I=te.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,I)}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 Fd(this,"lookat"));else{const I=te.easeInOutCubic(this._lookTargetLerp01);this._controls.target.lerpVectors(this._lookTargetStartPosition,this._lookTargetEndPosition,I)}}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._controls.keys=this.enableKeys?aG:pgA,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,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,typeof Jf=="number"||Jf===!0){this._controls.enableDamping=!0;const I=typeof Jf=="number"?Jf:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,I))}this.allowInterrupt||(this._lookTargetLerpActive&&(this._controls.enablePan=!1),this._cameraLerpActive&&(this._controls.enableRotate=!1,this._controls.autoRotate=!1),(this._lookTargetLerpActive||this._cameraLerpActive)&&(this._controls.enableZoom=!1)),this.context.isInXR||(!Kf&&((i=this.lookAtConstraint)!=null&&i.locked)&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(),ugA&&De.DrawWireSphere(this._controls.target,.1,65280))}}__handleSetTargetWhenBecomingActiveTheFirstTime(){if(!this._didSetTarget&&(this._didSetTarget=!0,this.autoTarget)){const e=aA.getComponent(this.gameObject,Wt);if(e&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const i=_e(e.cam).length(),I=new w(0,0,-i).applyMatrix4(e.cam.matrixWorld);this.setLookTargetPosition(I,!0)}if(!this.autoFit&&!this.setLookTargetFromConstraint()){const t=new Bs;t.screenPoint=new iA(0,0),t.lineThreshold=.1;const i=this.context.physics.raycast(t);i.length>0&&this.setLookTargetPosition(i[0].point,!0),vl&&console.log("OrbitControls hits",...i)}this.autoFit&&this.fitCamera()}}setCameraAndLookTarget(e){if(!e||!(e instanceof uA))return;const t=_e(e),i=ZR(e);this.setTargetFromRaycast(new io(t,i)),this.setCameraTargetPosition(t)}setCameraTargetPosition(e,t=!1){var i,I;e&&(e instanceof uA&&(e=_e(e)),this._cameraEndPosition||(this._cameraEndPosition=new w),this._cameraEndPosition.copy(e),t===!0?(this._cameraLerpActive=!1,(i=this.controllerObject)==null||i.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy((I=this._cameraObject)==null?void 0:I.position),typeof t=="number"?this._cameraLerpDuration=t:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setLookTargetPosition(e=null,t=!1){this._controls&&e&&(e instanceof uA&&(e=_e(e)),this._lookTargetEndPosition.copy(e),t===!0?this._controls.target.copy(this._lookTargetEndPosition):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof t=="number"?this._lookTargetLerpDuration=t:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(e=0,t=1){var I;if(!this._controls)return!1;const i=(I=this.lookAtConstraint)==null?void 0:I.sources;if(i&&i.length>0){const o=i[e];if(o)return o.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._lookTargetEndPosition,t),!0}return!1}lerpTarget(e,t){return this.lerpLookTarget(e,t)}lerpLookTarget(e,t){this._controls&&(t>=1?this._controls.target.copy(e):this._controls.target.lerp(e,t))}setTargetFromRaycast(e){if(!this.controls)return;const t=e?this.context.physics.raycastFromRay(e):this.context.physics.raycast();for(const i of t)if(i.distance>0&&aA.isActiveInHierarchy(i.object)){const I=xN(i.object);if(I){const o=I.canvas;if(o!=null&&o.screenspace)break}this.setLookTargetPosition(i.point);break}}fitCamera(e,t=void 0,i=!0){if(this.context.isInXR)return;t==null&&(t=1.1);const I=this._cameraObject,o=this._controls;if(e!=null&&e.length||(e=this.context.scene.children),e.length<=0){console.warn("No objects to fit camera to...");return}if(!I||!o){console.warn("No camera or controls found to fit camera to objects...");return}const s=new w,n=new w,C=new wt;C.makeEmpty();const a=[];function B(G){let M=!0;if(G.visible&&FO(G)!==!1&&!(G.type==="TransformControlsGizmo"||G.type==="TransformControlsPlane")&&(G instanceof Tk&&(M=!1),G instanceof Oy&&(M=!1),G instanceof RO&&(M=!1),G.material instanceof by&&(M=!1),G instanceof lA||(M=!1),G!==I&&G.isUI!==!0)){if(M){vl&&console.log(G.name,G.type,G);const m=G.children;G.children=a;const N=G.position,y=G.scale;if(Number.isNaN(N.x)||Number.isNaN(N.y)||Number.isNaN(N.z)){console.warn(`Object "${G.name}" has NaN values in position or scale.... will ignore it`,N,y);return}C.expandByObject(G,!0),G.children=m}for(const m of G.children)B(m)}}let Q=!1;for(const G of e)G&&(Q=!0,G.updateMatrixWorld(),B(G));if(!Q){console.warn("No objects to fit camera to...");return}if(I.updateMatrixWorld(),I.updateProjectionMatrix(),C.getCenter(n),C.applyMatrix4(I.matrixWorldInverse),C.getSize(s),C.setFromCenterAndSize(n,s),Number.isNaN(s.x)||Number.isNaN(s.y)||Number.isNaN(s.z)){console.warn("Camera fit size resultet in NaN",I,C,[...e]);return}if(s.length()<=1e-10){vl&&console.warn("Camera fit size is zero",C,[...e]);return}const E=I.fov,c=2*Math.atan(Math.tan(E*Math.PI/360/2)*I.aspect)/Math.PI*360,d=s.y/(2*Math.atan(Math.PI*E/360)),l=s.x/(2*Math.atan(Math.PI*c/360)),h=t*Math.max(d,l)+s.z/2;vl&&console.log("Fit camera to objects",d,l,"distance",h),o.maxDistance=h*10,o.minDistance=h*.01;const p=.05,u=n.clone();u.y-=s.y*p,this.setLookTargetPosition(u,i),this.autoTarget=!1,I.near=h/1e3,I.far=h*100,I.updateMatrixWorld(),I.updateProjectionMatrix();const f=_e(I),k=n.clone();if(k.sub(f),k.y=0,k.normalize(),k.multiplyScalar(h),k.y+=-p*4*s.y,I.parent){const G=I.parent.worldToLocal(n.clone().sub(k));this.setCameraTargetPosition(G,i)}else console.error(`Can not fit camera ${I.name} because it has no parent`);if(vl){const G=new Tk(C);this.context.scene.add(G),zR(G,Eu(I)),setTimeout(()=>{this.context.scene.remove(G)},1e4),this._haveAttachedKeyboardEvents||(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",M=>{M.code==="KeyF"&&this.fitCamera(e,t,i)}))}o.update()}}bi([D()],Rt.prototype,"autoTarget",2);bi([D()],Rt.prototype,"autoFit",2);bi([D()],Rt.prototype,"enableRotate",2);bi([D()],Rt.prototype,"autoRotate",2);bi([D()],Rt.prototype,"autoRotateSpeed",2);bi([D()],Rt.prototype,"minAzimuthAngle",2);bi([D()],Rt.prototype,"maxAzimuthAngle",2);bi([D()],Rt.prototype,"minPolarAngle",2);bi([D()],Rt.prototype,"maxPolarAngle",2);bi([D()],Rt.prototype,"enableKeys",2);bi([D()],Rt.prototype,"enableDamping",2);bi([D()],Rt.prototype,"dampingFactor",2);bi([D()],Rt.prototype,"enableZoom",2);bi([D()],Rt.prototype,"minZoom",2);bi([D()],Rt.prototype,"maxZoom",2);bi([D()],Rt.prototype,"enablePan",2);bi([D(IQ)],Rt.prototype,"lookAtConstraint",2);bi([D()],Rt.prototype,"lookAtConstraint01",2);bi([D()],Rt.prototype,"allowInterrupt",2);bi([D()],Rt.prototype,"middleClickToFocus",2);bi([D()],Rt.prototype,"doubleClickToFocus",2);bi([D()],Rt.prototype,"targetLerpDuration",2);var fgA=Object.defineProperty,DgA=Object.getOwnPropertyDescriptor,go=(g,A,e,t)=>{for(var i=t>1?void 0:t?DgA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&fgA(A,e,i),i},YB=(g=>(g[g.Skybox=1]="Skybox",g[g.SolidColor=2]="SolidColor",g[g.Uninitialized=4]="Uninitialized",g))(YB||{});const QC=IA("debugcam"),vq=IA("debugscreenpointtoray");var oD;const rh=(oD=class extends RA{constructor(){super(...arguments);r(this,"_nearClipPlane",.1);r(this,"_farClipPlane",1e3);r(this,"orthographic",!1);r(this,"orthographicSize",5);r(this,"ARBackgroundAlpha",0);r(this,"_cullingMask",4294967295);r(this,"_backgroundBlurriness",0);r(this,"_backgroundIntensity",1);r(this,"_environmentIntensity");r(this,"_targetTexture",null);r(this,"_backgroundColor");r(this,"_fov");r(this,"_cam",null);r(this,"_clearFlags",2);r(this,"_skybox");r(this,"_frustum");r(this,"_projScreenMatrix",new GA)}get isCamera(){return!0}get aspect(){return this._cam instanceof He?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(A){this._cam instanceof He&&this._cam.aspect!==A&&(this._cam.aspect=A,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof He?this._cam.fov:this._fov}set fieldOfView(A){const e=this.fieldOfView!=A;if(this._fov=A,e&&this._cam&&this._cam instanceof He){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(A){const e=this._nearClipPlane!=A;this._nearClipPlane=A,this._cam&&e&&(this._cam.near=A,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(A){const e=this._farClipPlane!=A;this._farClipPlane=A,this._cam&&e&&(this._cam.far=A,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(A){A!==this._clearFlags&&(this._clearFlags=A,this.applyClearFlagsIfIsActiveCamera())}set cullingMask(A){this._cullingMask=A,this._cam&&(this._cam.layers.mask=A)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}set cullingLayer(A){this.cullingMask=(1<<A|0)>>>0}set backgroundBlurriness(A){A!==this._backgroundBlurriness&&(A===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(A,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}set backgroundIntensity(A){A!==this._backgroundIntensity&&(A===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(A,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}set environmentIntensity(A){this._environmentIntensity=A}get environmentIntensity(){return this._environmentIntensity}get backgroundColor(){return this._backgroundColor??null}set backgroundColor(A){if(A){if(this._backgroundColor)this._backgroundColor.copy(A);else{if(!A.clone)return;this._backgroundColor=A.clone()}A.alpha===void 0&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera()}}set targetTexture(A){this._targetTexture=A}get targetTexture(){return this._targetTexture}get cam(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(A,e,t){const i=this.cam,I=rh._origin;I.set(A,e,-1),this.context.input.convertScreenspaceToRaycastSpace(I),vq&&console.log("screenPointToRay",A.toFixed(2),e.toFixed(2),"now:",I.x.toFixed(2),I.y.toFixed(2),"isInXR:"+this.context.isInXR),I.z=-1,I.unproject(i);const o=rh._direction.set(I.x,I.y,I.z),s=_e(i);return o.sub(s),o.normalize(),t?(t.set(s,o),t):new io(s.clone(),o.clone())}getFrustum(){return this._frustum||(this._frustum=new JB,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new JB),this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(A,e){return e&&this._projScreenMatrix.multiplyMatrices(this.cam.projectionMatrix,this.cam.matrixWorldInverse),A===this._projScreenMatrix?A:A.copy(this._projScreenMatrix)}awake(){vq&&window.addEventListener("pointerdown",A=>{const e=A.clientX,t=A.clientY;console.log("touch",e.toFixed(2),t.toFixed(2));const i=this.screenPointToRay(e,t),I="#"+Math.floor(Math.random()*16777215).toString(16);De.DrawRay(i.origin,i.direction,I,10)})}onEnable(){QC&&console.log(`Camera enabled: "${this.name}". ClearFlags=${YB[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),ygA(this)),this.applyClearFlagsIfIsActiveCamera()}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 A=this.context.renderer;if(A){const e=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,A),e==null||e.applyClearFlags()}}}buildCamera(){if(this._cam)return;const A=this.gameObject.isCamera;let e=null;if(A?(e=this.gameObject,e==null||e.layers.enableAll(),e instanceof He&&(this._fov=e.fov)):e=this.gameObject.children[0],e&&e.isCamera)e instanceof He&&(this._fov&&(e.fov=this._fov),e.near=this._nearClipPlane,e.far=this._farClipPlane,e.updateProjectionMatrix());else if(!this.orthographic)e=new He(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(e.fov=this.fieldOfView),this.gameObject.add(e);else{const t=this.orthographicSize*100;e=new YC(window.innerWidth/-t,window.innerWidth/t,window.innerHeight/t,window.innerHeight/-t,this._nearClipPlane,this._farClipPlane),this.gameObject.add(e)}this._cam=e,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(){this.context.mainCameraComponent===this&&this.applyClearFlags()}applyClearFlags(){if(!this._cam){QC&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this._fov,QC){const A=`Camera "${this.name}" clear flags: ${YB[this._clearFlags]}`;console.debug(A)}switch(this._clearFlags){case 1:if(rh.backgroundShouldBeTransparent(this.context)&&(!this.ARBackgroundAlpha||this.ARBackgroundAlpha<.001)){this.context.scene.background=null,this.context.renderer.setClearColor(0,0);return}this.enableSkybox(),this._backgroundBlurriness!==void 0?this.context.scene.backgroundBlurriness=this._backgroundBlurriness:QC&&console.warn(`Camera "${this.name}" has no background blurriness`),this._backgroundIntensity!==void 0?this.context.scene.backgroundIntensity=this._backgroundIntensity:QC&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor){let A=this._backgroundColor.alpha;rh.backgroundShouldBeTransparent(this.context)&&(A=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.renderer.setClearColor(this._backgroundColor,A)}else QC&&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}}enableSkybox(){this._skybox||(this._skybox=new wgA(this)),this._skybox.enable()}static backgroundShouldBeTransparent(A){var I,o,s,n;const e=(I=A.renderer.xr)==null?void 0:I.getSession();if(!e)return!1;if(typeof e._transparent=="boolean")return e._transparent;const t=e.environmentBlendMode;QC&&Ci("Environment blend mode: "+t+" on "+navigator.userAgent);let i=t==="additive"||t==="alpha-blend";return A.isInAR&&t==="opaque"&&((o=navigator.userAgent)!=null&&o.includes("OculusBrowser")||(s=navigator.userAgent)!=null&&s.includes("Mozilla")&&((n=navigator.userAgent)!=null&&n.includes("Mobile WebXRViewer/v2")))&&(i=!0),e._transparent=i,i}},r(oD,"_origin",new w),r(oD,"_direction",new w),oD);let Wt=rh;go([D()],Wt.prototype,"aspect",1);go([D()],Wt.prototype,"fieldOfView",1);go([D()],Wt.prototype,"nearClipPlane",1);go([D()],Wt.prototype,"farClipPlane",1);go([D()],Wt.prototype,"clearFlags",1);go([D()],Wt.prototype,"orthographic",2);go([D()],Wt.prototype,"orthographicSize",2);go([D()],Wt.prototype,"ARBackgroundAlpha",2);go([D()],Wt.prototype,"cullingMask",1);go([D()],Wt.prototype,"backgroundBlurriness",1);go([D()],Wt.prototype,"backgroundIntensity",1);go([D()],Wt.prototype,"environmentIntensity",1);go([D(Mt)],Wt.prototype,"backgroundColor",1);go([D(za)],Wt.prototype,"targetTexture",1);class wgA{constructor(A){r(this,"_camera");r(this,"_skybox");this._camera=A}get context(){var A;return(A=this._camera)==null?void 0:A.context}enable(){this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),this._skybox?this.context.scene.background!==this._skybox&&(QC&&console.log(`Camera "${this._camera.name}" set skybox`,this._camera,this._skybox),this._skybox.mapping=os,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}" failed to load/find skybox texture`,this._camera.sourceId,this.context.lightmaps,"Current background: ",this.context.scene.background)),(QC||he())&&fi(`Camera "${this._camera.name}" has no skybox texture`))}}function ygA(g){IA("freecam")&&g.context.mainCameraComponent===g&&aA.getOrAddComponent(g.gameObject,Rt)}class Xa extends RA{constructor(){super(...arguments);r(this,"_listener",null)}get listener(){return this._listener==null&&(this._listener=new sT),this._listener}awake(){Di.registerWaitForAllowAudio(()=>{if(this.destroyed)return;const e=this.listener;if(e==null||e.parent)return;const t=this.context.mainCameraComponent||aA.getComponentInParent(this.gameObject,Wt);t!=null&&t.cam?t.cam.add(e):this.gameObject.add(e)})}}var SgA=Object.defineProperty,mgA=Object.getOwnPropertyDescriptor,fS=(g,A,e,t)=>{for(var i=t>1?void 0:t?mgA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&SgA(A,e,i),i};const GgA=IA("debugsignals");class Nu{constructor(){r(this,"guid")}}fS([D()],Nu.prototype,"guid",2);class qc{constructor(){r(this,"signal");r(this,"reaction")}}fS([D(Nu)],qc.prototype,"signal",2);fS([D(rg)],qc.prototype,"reaction",2);var VG;const sC=(VG=class extends RA{constructor(){super(...arguments);r(this,"events")}static invoke(A){if(sC.receivers[A]){const e=sC.receivers[A];if(!e)return;for(const t of e)t.invoke(A)}}awake(){GgA&&console.log("SignalReceiver awake",this)}onEnable(){if(this.events)for(const A of this.events)sC.receivers[A.signal.guid]||(sC.receivers[A.signal.guid]=[]),sC.receivers[A.signal.guid].push(this)}onDisable(){if(this.events){for(const A of this.events)if(sC.receivers[A.signal.guid]){const e=sC.receivers[A.signal.guid].indexOf(this);e>=0&&sC.receivers[A.signal.guid].splice(e,1)}}}invoke(A){if(!this.events||!Array.isArray(this.events))return;const e=typeof A=="object"?A.guid:A;for(const t of this.events)if(t.signal.guid===e)try{if(t.reaction){if(!t.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",t,this);continue}}else{console.warn("Missing reaction for signal",t,this);continue}t.reaction.invoke()}catch(i){console.error(i)}}},r(VG,"receivers",{}),VG);let xc=sC;fS([D(qc)],xc.prototype,"events",2);var Eo=(g=>(g.Activation="ActivationTrack",g.Animation="AnimationTrack",g.Audio="AudioTrack",g.Control="ControlTrack",g.Marker="MarkerTrack",g.Signal="SignalTrack",g))(Eo||{}),rn=(g=>(g[g.None=0]="None",g[g.Hold=1]="Hold",g[g.Loop=2]="Loop",g[g.PingPong=3]="PingPong",g[g.Continue=4]="Continue",g))(rn||{}),LN=(g=>(g.Signal="SignalEmitter",g))(LN||{});const Sn=IA("debugtimeline");class Fu{constructor(){r(this,"director");r(this,"track")}get muted(){return this.track.muted}set muted(A){var e;A!==this.track.muted&&(this.track.muted=A,(e=this.onMuteChanged)==null||e.call(this))}*forEachClip(A=!1){var e;if((e=this.track)!=null&&e.clips)if(A)for(let t=this.track.clips.length-1;t>=0;t--)yield this.track.clips[t];else for(const t of this.track.clips)yield t}getClipTime(A,e){return e.clipIn+(A-e.start)*e.timeScale}getClipTimeNormalized(A,e){return(A-e.start)/e.duration}evaluateWeight(A,e,t,i=!0){if(e<0||e>=t.length)return 0;const I=t[e];if(i||A>=I.start&&A<=I.end){let o=1;const s=!1;if(I.easeInDuration>0){const n=Math.min((A-I.start)/I.easeInDuration,1);o*=n}if(I.easeOutDuration>0&&!s){const n=Math.min((I.end-A)/I.easeOutDuration,1);o*=n}return o}return 0}}class kgA{constructor(A){r(this,"clip");r(this,"rootPositionOffset");r(this,"rootQuaternionOffset");r(this,"rootStartPosition");r(this,"rootEndPosition");r(this,"rootStartQuaternion");r(this,"rootEndQuaternion");const e=A.getClip();this.clip=e;const t=A.getRoot(),i=t.name+".position",I=t.name+".quaternion";Sn&&console.log(e.name,e.tracks,i);for(const o of e.tracks)if(!(o.times.length<=0)){if(o.name.endsWith(i))this.rootStartPosition=new w().fromArray(o.values,0),this.rootEndPosition=new w().fromArray(o.values,o.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),Sn&&console.log(this.rootPositionOffset);else if(o.name.endsWith(I)&&(this.rootStartQuaternion=new MA().fromArray(o.values,0),this.rootEndQuaternion=new MA().fromArray(o.values,o.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),Sn)){const s=new $t().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",s)}}}get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}}class DS extends Fu{constructor(){super(...arguments);r(this,"models",[]);r(this,"trackOffset");r(this,"target");r(this,"mixer");r(this,"clips",[]);r(this,"actions",[]);r(this,"_actionOffsets",[]);r(this,"_didBind",!1);r(this,"_animator",null);r(this,"_useclipOffsets",!0);r(this,"_totalOffsetPosition",new w);r(this,"_totalOffsetRotation",new MA);r(this,"_totalOffsetPosition2",new w);r(this,"_totalOffsetRotation2",new MA);r(this,"_summedPos",new w);r(this,"_tempPos",new w);r(this,"_summedRot",new MA);r(this,"_tempRot",new MA);r(this,"_clipRotQuat",new MA)}onStateChanged(){this._animator&&qq(this._animator.gameObject,this,this.director.isPlaying)}createHooks(e,t){var a,B;if(((a=t.tracks)==null?void 0:a.length)<=0){console.warn("No tracks in AnimationClip",t);return}const i=t.tracks[0].name.split("."),I=i[i.length-2],o=I+".position",s=I+".quaternion";let n=!1,C=!1;for(const Q of t.tracks)Q.name.endsWith(o)?(n=!0,this.createPositionInterpolant(t,e,Q)):Q.name.endsWith(s)&&(C=!0,this.createRotationInterpolant(t,e,Q));if(!n||!C){const Q=(B=this.mixer)==null?void 0:B.getRoot(),E=t.tracks[0],c=E.name.lastIndexOf("."),d=E.name.substring(0,c),l=d.substring(d.lastIndexOf(".")+1),h=Q.getObjectByName(l);if(h)if(n){if(!C){const p=t.tracks[0].name.substring(0,c)+".quaternion";Sn&&console.warn("Create quaternion track",l,h);const u=h.quaternion,f=new Jn(p,[0,t.duration],[u.x,u.y,u.z,u.w,u.x,u.y,u.z,u.w]);t.tracks.push(f),this.createRotationInterpolant(t,e,f)}}else{const p=d+".position";Sn&&console.warn("Create position track",l,h);const u=h.position,f=new bC(p,[0,t.duration],[u.x,u.y,u.z,u.x,u.y,u.z]);t.tracks.push(f),this.createPositionInterpolant(t,e,f)}}}bind(){if(!this._didBind){this._didBind=!0,Sn&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(const e of this.actions){const t=new kgA(e);this._actionOffsets.push(t)}this.target&&(this._animator=aA.getComponent(this.target,Zg)??null,this._animator&&qq(this._animator.gameObject,this,!0));for(const e of this.models){const t=e.asset,i=t.position,I=t.rotation;i&&i.x!==void 0&&(i.isVector3||(t.position=new w(i.x,i.y,i.z)),I.isQuaternion||(t.rotation=new MA(I.x,I.y,I.z,I.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){const e=this.trackOffset.position;e&&(e.isVector3||(this.trackOffset.position=new w(e.x,e.y,e.z)));const t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new MA(t.x,t.y,t.z,t.w)))}}evaluate(e){var n,C,a,B,Q,E,c;if(this.track.muted||!this.mixer)return;this.bind(),this._totalOffsetPosition.set(0,0,0),this._totalOffsetRotation.set(0,0,0,1),this._totalOffsetPosition2.set(0,0,0),this._totalOffsetRotation2.set(0,0,0,1);let t=0,i=0,I=!1,o=!1,s=0;for(let d=0;d<this.clips.length;d++){const l=this.models[d],h=this.actions[d],p=l.asset;h.weight=0;const u=e>=l.start&&e<=l.end,f=l.preExtrapolationMode,k=l.postExtrapolationMode,G=d<this.clips.length-1?this.models[d+1]:null;let M=u,m=!1;if(!M&&!I&&l.end<e&&k!==rn.None?(!G||G.start>e)&&(M=!0,I=!0):d==0&&!M&&!o&&l.start>e&&f!==rn.None&&(!G||G.start<e)&&(M=!0,m=!0,o=!0),M){let N=1;N*=this.evaluateWeight(e,d,this.models,M),N*=this.director.weight;let y=u;if(m)switch(f){case rn.Hold:break;case rn.Loop:e+=l.start,y=!0;break;default:e+=l.start,y=!0;break}let U=this.getClipTime(e,l),H=0;const x=p.duration;if(m&&f===rn.Hold&&(U=0),y){if(p.loop)for(H+=Math.floor(U/(x+1e-6));U>x;)U-=x}else if(!u&&I)switch(k){case rn.Hold:U=this.getClipTime(l.end,l);break;case rn.Loop:U%=x;break;case rn.PingPong:const b=Math.floor(U/x)%2!==0;U%=x,b&&(U=x-U);break}l.reversed===!0?h.time=h.getClip().duration-U:h.time=U,h.timeScale=0;const K=Math.max(0,N);if(h.weight=K,s+=K,h.clampWhenFinished=!1,h.isRunning()||h.play(),this._useclipOffsets){const O=t==0?this._totalOffsetPosition:this._totalOffsetPosition2,b=t==0?this._totalOffsetRotation:this._totalOffsetRotation2;t<1&&(i=1-N),t+=1;const v=this._summedPos.set(0,0,0),T=this._tempPos.set(0,0,0),V=this._summedRot.identity(),X=this._tempRot.identity(),CA=p.rotation;CA&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp(CA,N));const QA=this._actionOffsets[d];if(QA.hasOffsets)for(let FA=0;FA<H;FA++)QA.rootPositionOffset?T.copy(QA.rootPositionOffset):T.set(0,0,0),T.applyQuaternion(V),this._clipRotQuat&&T.applyQuaternion(this._clipRotQuat),QA.rootQuaternionOffset&&(X.copy(QA.rootQuaternionOffset),V.multiply(X)),v.add(T);this._clipRotQuat&&b.multiply(this._clipRotQuat),b.multiply(V),p.position&&v.add(p.position),O.add(v)}}}if(this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,i),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,i)),this.__mixerError===void 0&&(Sn||he())&&((C=(n=this._animator)==null?void 0:n.runtimeAnimatorController)!=null&&C.mixer)&&this.mixer!==((B=(a=this._animator)==null?void 0:a.runtimeAnimatorController)==null?void 0:B.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)),(Q=this._animator)!=null&&Q.runtimeAnimatorController){const d=Math.max(0,1-s);(c=(E=this._animator)==null?void 0:E.runtimeAnimatorController)==null||c.update(d)}else this.mixer.update(e)}createRotationInterpolant(e,t,i){var n;const I=i.createInterpolant.bind(i),o=new MA;this.ensureTrackOffsets();const s=(n=this.trackOffset)==null?void 0:n.rotation;i.createInterpolant=()=>{const C=I(),a=C.evaluate.bind(C);return C.evaluate=B=>{var E;const Q=a(B);if(o.set(Q[0],Q[1],Q[2],Q[3]),o.premultiply(this._totalOffsetRotation),s&&o.premultiply(s),this.director.animationCallbackReceivers)for(const c of this.director.animationCallbackReceivers)(E=c==null?void 0:c.onTimelineRotation)==null||E.call(c,this.director,this.target,B,o);return Q[0]=o.x,Q[1]=o.y,Q[2]=o.z,Q[3]=o.w,Q},C}}createPositionInterpolant(e,t,i){var a,B;const I=i.createInterpolant.bind(i),o=new w;this.ensureTrackOffsets();const s=(a=this.trackOffset)==null?void 0:a.rotation,n=(B=this.trackOffset)==null?void 0:B.position;let C;i.createInterpolant=()=>{const Q=I(),E=Q.evaluate.bind(Q);return Q.evaluate=c=>{var l,h,p;const d=E(c);if(o.set(d[0],d[1],d[2]),t.removeStartOffset&&(C===void 0?(C=null,C=(h=(l=this._actionOffsets.find(u=>u.clip===e))==null?void 0:l.rootStartPosition)==null?void 0:h.clone()):C!=null&&C.isVector3&&o.sub(C)),o.applyQuaternion(this._totalOffsetRotation),o.add(this._totalOffsetPosition),s&&o.applyQuaternion(s),n&&(o.x-=n.x,o.y+=n.y,o.z+=n.z),this.director.animationCallbackReceivers)for(const u of this.director.animationCallbackReceivers)(p=u==null?void 0:u.onTimelinePosition)==null||p.call(u,this.director,this.target,c,o);return d[0]=o.x,d[1]=o.y,d[2]=o.z,d},Q}}}const MgA=IA("mutetimeline"),JE=class extends Fu{constructor(){super(...arguments);r(this,"models",[]);r(this,"listener");r(this,"audio",[]);r(this,"audioContextTimeOffset",[]);r(this,"lastTime",0);r(this,"audioSource");r(this,"_audioLoader",null);r(this,"_playableDirectorResumed",!1)}getAudioFilePath(e){const t=this.director.sourceId;return PC(t,e)}onAllowAudioChanged(e){for(let t=0;t<this.models.length;t++){const i=this.models[t];this.audio[t].setVolume(e?i.asset.volume:0)}}addModel(e){const t=new aR(this.listener);this.audio.push(t);const i=e;i._didTriggerPlay=!1,this.models.push(i)}onDisable(){for(const e of this.audio)e.isPlaying&&e.stop();for(const e of this.models)e._didTriggerPlay=!1}onDestroy(){for(const e of this.audio)e.source&&(e==null||e.disconnect());this.audio.length=0}onMuteChanged(){if(this.muted)for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t!=null&&t.isPlaying&&t.stop()}}stop(){for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t!=null&&t.isPlaying&&t.stop()}for(const e of this.models)e._didTriggerPlay=!1}onPauseChanged(){for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t!=null&&t.isPlaying&&t.stop()}this._playableDirectorResumed=this.director.isPlaying}evaluate(e){if(MgA||this.track.muted||this.director.speed<0)return;const t=this.director.context.application.muted,i=this._playableDirectorResumed;this._playableDirectorResumed=!1;const I=t?.1:0;for(let o=0;o<this.models.length;o++){const s=this.models[o],n=this.audio[o],C=s.asset;if((!n||!n.buffer)&&this.isInTimeRange(s,e-1,e+1)&&this.handleAudioLoading(s,n),Di.userInteractionRegistered!==!1&&!(n===null||!n.buffer))if(n.playbackRate=this.director.context.time.timeScale*this.director.speed,n.loop=C.loop,e>=s.start&&e<=s.end&&e<this.director.duration){if(!n.isPlaying||!this.director.isPlaying)(i||!s._didTriggerPlay&&this.lastTime<e)&&(s.duration*s.timeScale>.3?n.offset=s.clipIn+(e-s.start)*s.timeScale:n.offset=0,Sn&&console.log("Timeline Audio ("+this.track.name+") play with offset "+n.offset+" - "+s.asset.clip),n.play(I),s._didTriggerPlay=!0);else{const B=s.clipIn+(e-s.start)*s.timeScale,Q=n.context.currentTime-n._startedAt+n.offset;Math.abs(B-Q)>.3&&(n.offset=B,n.stop(),n.play(I))}let a=C.volume;if(this.track.volume!==void 0&&(a*=this.track.volume),t&&(a=0),s.easeInDuration>0){const B=Math.min((e-s.start)/s.easeInDuration,1);a*=B}if(s.easeOutDuration>0){const B=Math.min((s.end-e)/s.easeOutDuration,1);a*=B}n.setVolume(a*this.director.weight)}else s._didTriggerPlay=!1,this.director.isPlaying&&n.isPlaying&&n.stop()}this.lastTime=e}loadAudio(e,t=0,i=0){let I=null;const o=e-i,s=e+t;for(const n of this.models)if(this.isInTimeRange(n,o,s)){const C=this.audio[this.models.indexOf(n)],a=this.handleAudioLoading(n,C);a!==null&&(I===null&&(I=[]),I.push(a))}return I!==null?Promise.all(I):null}isInTimeRange(e,t,i){return t<=e.start&&i>=e.end||t>=e.start&&t<=e.end||i>=e.start&&i<=e.end}static dispose(){JE._audioBuffers.clear()}handleAudioLoading(e,t){this._audioLoader||(this._audioLoader=new nw);const i=this.getAudioFilePath(e.asset.clip);if(JE._audioBuffers.get(i)){const o=JE._audioBuffers.get(i);return o.then(s=>{s&&t.setBuffer(s)}),o}Sn&&console.warn("LOAD audio track",i,this.director.sourceId);const I=new Promise((o,s)=>{this._audioLoader.load(i,n=>{t.setBuffer(n),o(n)},void 0,n=>{console.error("Error loading audio",n),o(null)})});return JE._audioBuffers.set(i,I),I}};let mB=JE;r(mB,"_audioBuffers",new Map);class Kd extends Fu{constructor(){super(...arguments);r(this,"models",[]);r(this,"didTrigger",[]);r(this,"receivers",[])}evaluate(e){var i;if(this.track.muted)return;const t=this.director.context.time.deltaTime*1.5;for(let I=0;I<this.models.length;I++){const o=this.models[I],s=this.didTrigger[I],n=o.time-e;let C=!1;if(o.retroActive)C=n<=1e-6;else{const a=Math.abs(n);(a===0||a>=1e-5&&a<t)&&(C=!0)}if(C){if(!s)if(Sn&&console.log("Trigger signal",e,o.time,o),this.didTrigger[I]=!0,((i=this.receivers)==null?void 0:i.length)<=0)xc.invoke(o.asset);else for(const a of this.receivers)a&&a.invoke(o.asset)}else o.emitOnce||(this.didTrigger[I]=!1)}}}class wS extends Fu{constructor(){super(...arguments);r(this,"models",[]);r(this,"timelines",[]);r(this,"_previousActiveModel",null)}resolveSourceObjects(e){for(let t=this.models.length-1;t>=0;t--){const I=this.models[t].asset;if(!I.sourceObject||typeof I.sourceObject!="object"){console.log("no source object, removing model",t,I),this.models.splice(t,1);continue}else{const o=aA.getComponent(I.sourceObject,KC);this.timelines.push(o),o&&I.updateDirector&&(o.playOnAwake=!1)}}}evaluate(e){var t;this._previousActiveModel=null;for(let i=0;i<this.models.length;i++){const I=this.models[i],o=I.asset;if(e>=I.start&&e<=I.end){this._previousActiveModel=I;const s=this.getClipTime(e,I);if(o.controlActivation){const n=o.sourceObject;n.visible=!0}if(o.updateDirector){const n=this.timelines[i];n&&(n.isPlaying&&n.pause(),n.time=s,n.evaluate())}}else{const s=(t=this._previousActiveModel)==null?void 0:t.asset;if(o.controlActivation){const n=o.sourceObject;(s==null?void 0:s.sourceObject)!==n&&(n.visible=!1)}}}}}const iE=IA("debugtimeline"),iy=class extends RA{constructor(){super(...arguments);r(this,"playableAsset");r(this,"playOnAwake");r(this,"extrapolationMode",1);r(this,"waitForAudio",!0);r(this,"_visibilityChangeEvt");r(this,"_clonedPlayableAsset",!1);r(this,"_speed",1);r(this,"_guidsMap");r(this,"_isPlaying",!1);r(this,"_internalUpdateRoutine");r(this,"_isPaused",!1);r(this,"_isStopping",!1);r(this,"_time",0);r(this,"_duration",0);r(this,"_weight",1);r(this,"_animationTracks",[]);r(this,"_audioTracks",[]);r(this,"_signalTracks",[]);r(this,"_controlTracks",[]);r(this,"_customTracks",[]);r(this,"_allTracks",[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks]);r(this,"animationCallbackReceivers",[])}static registerCreateTrack(e,t){this.createTrackFunctions[e]=t}get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(e){typeof e=="number"&&!Number.isNaN(e)?this._time=e:(iE||No())&&console.error("INVALID TIMELINE.TIME VALUE",e,this.name)}get duration(){return this._duration}set duration(e){this._duration=e}get weight(){return this._weight}set weight(e){this._weight=e}get speed(){return this._speed}set speed(e){this._speed=e}awake(){var e,t,i;iE&&console.log(this,(e=this.playableAsset)==null?void 0:e.tracks),this.rebuildGraph(),this.isValid()||console.warn("PlayableDirector is not valid",this.playableAsset,(t=this.playableAsset)==null?void 0:t.tracks,Array.isArray((i=this.playableAsset)==null?void 0:i.tracks),this)}onEnable(){var e,t,i;for(const I of this._audioTracks)(e=I.onEnable)==null||e.call(I);for(const I of this._customTracks)(t=I.onEnable)==null||t.call(I);for(const I of this._animationTracks)(i=I.onEnable)==null||i.call(I);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 e,t,i;this.stop();for(const I of this._audioTracks)(e=I.onDisable)==null||e.call(I);for(const I of this._customTracks)(t=I.onDisable)==null||t.call(I);for(const I of this._animationTracks)(i=I.onDisable)==null||i.call(I);this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){var e;for(const t of this._allTracks)for(const i of t)(e=i.onDestroy)==null||e.call(i)}rebuildGraph(){this.isValid()&&(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}async play(){if(!this.isValid())return;const e=this._isPaused==!0;if(this._isPaused=!1,!this._isPlaying){if(this._isPlaying=!0,e&&this.invokePauseChangedMethodsOnTracks(),this.waitForAudio){const t=[];for(const i of this._audioTracks){const I=i.loadAudio(this._time,1,0);I&&t.push(I)}if(t.length>0&&(await Promise.all(t),!this._isPlaying))return;for(;this._audioTracks.length>0&&this._isPlaying&&!Di.userInteractionRegistered&&this.waitForAudio;)await Os(200)}this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate(),Ai.LateUpdate)}}pause(){this.isValid()&&(this._isPlaying=!1,!this._isPaused&&(this._isPaused=!0,this.internalEvaluate(),this.invokePauseChangedMethodsOnTracks(),this.invokeStateChangedMethodsOnTracks()))}stop(){this._isStopping=!0;for(const i of this._audioTracks)i.stop();const e=this._isPaused==!0,t=this._isPlaying;this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.internalEvaluate(),e&&this.invokePauseChangedMethodsOnTracks()),this._isPlaying=!1,this._isPaused=!1,e&&!t&&this.invokePauseChangedMethodsOnTracks(),t&&this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine&&this.stopCoroutine(this._internalUpdateRoutine),this._internalUpdateRoutine=null,this._isStopping=!1}evaluate(){this.internalEvaluate(!0)}isValid(){return this.playableAsset&&this.playableAsset.tracks&&Array.isArray(this.playableAsset.tracks)}*forEachTrack(){for(const e of this._allTracks)for(const t of e)yield t}get audioTracks(){return this._audioTracks}resolveGuids(e){this._guidsMap=e}invokePauseChangedMethodsOnTracks(){var e;for(const t of this.forEachTrack())(e=t.onPauseChanged)==null||e.call(t)}invokeStateChangedMethodsOnTracks(){var e;for(const t of this.forEachTrack())(e=t.onStateChanged)==null||e.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(e=!1){if(!this.isValid())return;let t=this._time;switch(this.extrapolationMode){case 0:this._speed>0?t=Math.min(t,this._duration):this._speed<0&&(t=Math.max(t,0)),this._time=t;break;case 1:t%=this._duration,this._time=t;break;case 2:if(t>this._duration){this.stop();return}break}const i=this._time;for(const I of this.playableAsset.tracks)if(!I.muted)switch(I.type){case Eo.Activation:if(!e&&!this._isPlaying)continue;for(let o=0;o<I.outputs.length;o++){const s=I.outputs[o];if(typeof s=="object"){let n=!1;if(I.clips)for(const a of I.clips)a.start<=i&&i<=a.end&&(n=!0);const C=s;C.visible!==void 0&&C.visible!==n&&(C.visible=n,iE&&console.warn(this.name,"set ActivationTrack-"+o,C.name,n,i))}}break}if(!this._isStopping)for(const I of this._animationTracks)I.evaluate(i);for(const I of this._audioTracks)I.evaluate(i);for(const I of this._signalTracks)I.evaluate(i);for(const I of this._controlTracks)I.evaluate(i);for(const I of this._customTracks)I.evaluate(i)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=Cu(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;const e=this.findRoot(this.gameObject);for(const t of this.playableAsset.tracks){for(let i=t.outputs.length-1;i>=0;i--){let I=t.outputs[i];if(typeof I=="string"){this._guidsMap&&this._guidsMap[I]&&(I=this._guidsMap[I]);const o=aA.findByGuid(I,e);o===null||typeof o!="object"?(t.outputs.splice(i,1),console.warn("Failed to resolve binding",I,t.name,t.type)):(iE&&console.log("Resolved binding",I,"to",o),t.outputs[i]=o)}else if(I===null){if(t.outputs.splice(i,1),iy.createTrackFunctions[t.type])continue;t.type!==Eo.Audio&&t.type!==Eo.Control&&t.type!==Eo.Marker&&t.type!==Eo.Signal&&console.warn("Missing binding",I,t.name,t.type,this.name,this.playableAsset.name)}}if(t.type===Eo.Control&&t.clips)for(let i=0;i<t.clips.length;i++){const I=t.clips[i];let o=I.asset.sourceObject;if(typeof o=="string"){this._guidsMap&&this._guidsMap[o]&&(o=this._guidsMap[o]);const s=aA.findByGuid(o,e);s===null||typeof s!="object"?console.warn("Failed to resolve sourceObject binding",o,t.name,I):(iE&&console.log("Resolved binding",o,"to",s),I.asset.sourceObject=s)}}}}findRoot(e){return e.parent?this.findRoot(e.parent):e}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const e of this.playableAsset.tracks)if(e.muted!==!0){if(e.clips)for(const t of e.clips)t.end>this._duration&&(this._duration=t.end);if(e.markers)for(const t of e.markers)t.time>this._duration&&(this._duration=t.time+.001)}}}setupAndCreateTrackHandlers(){var t,i,I;if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let e=aA.findObjectOfType(Xa,this.context);for(const o of this.playableAsset.tracks){const s=o.type,n=iy.createTrackFunctions[s];if(n!=null){const C=n(this,o);if(typeof C.evaluate=="function"){C.director=this,C.track=o,this._customTracks.push(C);continue}}if(o.type===Eo.Animation){if(!o.clips||o.clips.length<=0){iE&&console.warn("Animation track has no clips",o);continue}for(let C=o.outputs.length-1;C>=0;C--){let a=o.outputs[C];if(a instanceof uA){const Q=aA.getOrAddComponent(a,Zg);Q&&(a=Q)}const B=(t=a==null?void 0:a.gameObject)==null?void 0:t.animations;if(B){const Q=new DS;Q.trackOffset=o.trackOffset,Q.director=this,Q.track=o;for(let E=0;E<o.clips.length;E++){const c=o.clips[E],d=c.asset;if(!d){console.error(`Timeline ${this.name}: clip #${E} on track "${o.name}" has no animation data`);continue}const l=d.clip;let h=l;if((typeof h=="string"||typeof h=="number")&&(h=B.find(u=>u.name===l)),!h){console.warn("Could not find animationClip for model",c,o.name,this.name,(i=this.playableAsset)==null?void 0:i.name);continue}a instanceof Zg&&a.runtimeAnimatorController&&(a.__internalDidAwakeAndStart||a.initializeRuntimeAnimatorController(),a.runtimeAnimatorController.mixer||a.runtimeAnimatorController.bind(a),Q.mixer=a.runtimeAnimatorController.mixer),Q.mixer||(Q.mixer=new Yy(a.gameObject)),Q.clips.push(h),Q.mixer.uncacheAction(h),Q.createHooks(c.asset,h);const p=Q.mixer.clipAction(h);Q.actions.push(p),Q.models.push(c)}this._animationTracks.push(Q)}}}else if(o.type===Eo.Audio){if(!o.clips||o.clips.length<=0)continue;const C=new mB;C.director=this,C.track=o,C.audioSource=o.outputs.find(a=>a instanceof Di),this._audioTracks.push(C),e||(e=(I=this.context.mainCameraComponent)==null?void 0:I.gameObject.addNewComponent(Xa)),C.listener=e.listener;for(let a=0;a<o.clips.length;a++){const B=o.clips[a];C.addModel(B)}}else if(o.type===Eo.Marker){const C=new Kd;if(C.director=this,C.track=o,o.markers)for(const a of o.markers)switch(a.type){case LN.Signal:C.models.push(a),C.didTrigger.push(!1);break}if(C!==null&&C.models.length>0){const a=aA.getComponent(this.gameObject,xc);a&&(C.receivers.push(a),this._signalTracks.push(C))}}else if(o.type===Eo.Signal){const C=new Kd;if(C.director=this,C.track=o,o.markers)for(const a of o.markers)C.models.push(a),C.didTrigger.push(!1);for(const a of o.outputs)C.receivers.push(a);this._signalTracks.push(C)}else if(o.type===Eo.Control){const C=new wS;if(C.director=this,C.track=o,o.clips)for(const a of o.clips)C.models.push(a);C.resolveSourceObjects(this.context),this._controlTracks.push(C)}}}setAudioTracksAllowPlaying(e){for(const t of this._audioTracks)t.onAllowAudioChanged(e)}registerAnimationCallback(e){this.animationCallbackReceivers.push(e)}unregisterAnimationCallback(e){const t=this.animationCallbackReceivers.indexOf(e);t!==-1&&this.animationCallbackReceivers.splice(t,1)}};let KC=iy;r(KC,"createTrackFunctions",{});const qD=Symbol("objectIsAnimatedData");function qq(g,A,e){if(!g)return;if(g[qD]===void 0){if(!e)return;g[qD]=new Set}const t=g[qD];e?t.add(A):t.has(A)&&t.delete(A)}function UgA(g){if(!g)return!1;const A=g[qD];return A!==void 0&&A.size>0}st.registerCallback(di.ContextCreated,g=>{const A=g.context.domElement.getAttribute("autoplay");if(A!==void 0&&(A===""||A==="true")&&g.files)for(const e of g.files)aA.foreachComponent(e.file.scene,i=>{if(i.enabled!==!1){if(i instanceof TI&&i.playAutomatically||i instanceof Zg||i instanceof KC&&i.playOnAwake===!0)return!0;if(i instanceof TI)return i.playAutomatically=!0,!0;if(i instanceof KC)return i.playOnAwake=!0,!0}},!0)!==!0&&RgA(e.file)});function RgA(g){if(!g||!g.animations)return;for(let e=0;e<g.animations.length;e++){const t=g.animations[e];if(!(!t.tracks||t.tracks.length<=0))for(const i in t.tracks){const I=t.tracks[i],o=I.__objectName??I.name.substring(0,I.name.indexOf("."));let s=g.scene.getObjectByName(o);if(!s&&(s=g.scene.getObjectByProperty("uuid",o),!s))continue;let n=A(s);n||(n=Va(g.scene,new TI));const C=n.animations=n.animations||[];t.name_animator=n.name,C.indexOf(t)<0&&C.push(t)}}function A(e){var i;if(!e)return;const t=(i=e.userData)==null?void 0:i.components;if(t&&t.length>0)for(let I=0;I<t.length;I++){const o=t[I];if(o instanceof Zg||o instanceof TI)return e}return A(e.parent)}}class NgA{constructor(){r(this,"_context")}get context(){return this._context??ve.Current}get isStateMachineBehaviour(){return!0}}class Bh{constructor(A,e,t,i){r(this,"name");r(this,"nameHash");r(this,"normalizedTime");r(this,"length");r(this,"speed");r(this,"action");this.name=A.name,this.nameHash=A.hash,this.normalizedTime=e,this.length=t,this.speed=i,this.action=A.motion.action||null}}function _O(g,A){return{name:"",isLooping:!1,guid:(A==null?void 0:A.generateUUID())??Cg.generateUUID(),index:-1,clip:new LI(g,1,[])}}var Ra=(g=>(g[g.If=1]="If",g[g.IfNot=2]="IfNot",g[g.Greater=3]="Greater",g[g.Less=4]="Less",g[g.Equals=6]="Equals",g[g.NotEqual=7]="NotEqual",g))(Ra||{}),_N=(g=>(g[g.Float=1]="Float",g[g.Int=3]="Int",g[g.Bool=4]="Bool",g[g.Trigger=9]="Trigger",g))(_N||{});const mI=IA("debuganimatorcontroller"),bf=IA("debugrootmotion");class Ro{constructor(A){r(this,"_speed",1);r(this,"normalizedStartOffset",0);r(this,"animator");r(this,"model");r(this,"_mixer");r(this,"_activeState");r(this,"_activeStates",[]);r(this,"rootMotionHandler");this.model=A,mI&&console.log(this)}static createFromClips(A,e={looping:!1,autoTransition:!0,transitionDuration:0}){const t=[];for(let o=0;o<A.length;o++){const s=A[o],n=[];if(e.autoTransition!==!1){const a=e.transitionDuration??0,B=a/s.duration;let Q=o;(e.autoTransition===void 0||e.autoTransition===!0)&&(Q=(o+1)%A.length),n.push({exitTime:1-B,offset:0,duration:a,hasExitTime:!0,destinationState:Q,conditions:[]})}const C={name:s.name,hash:o,motion:{name:s.name,clip:s,isLooping:(e==null?void 0:e.looping)??!1},transitions:n,behaviours:[]};t.push(C)}const i={name:"AnimatorController",guid:new Gg(Date.now()).generateUUID(),parameters:[],layers:[{name:"Base Layer",stateMachine:{defaultState:0,states:t}}]};return new Ro(i)}play(A,e=-1,t=Number.NEGATIVE_INFINITY,i=0){if(e<0)e=0;else if(e>=this.model.layers.length){console.warn("invalid layer");return}const o=this.model.layers[e].stateMachine;for(const s of o.states)if(s.name===A||s.hash===A){mI&&console.log("transition to ",s),this.transitionTo(s,i,t);return}console.warn("Could not find "+A+" to play")}reset(){this.setStartTransition()}setBool(A,e){var i,I;const t=typeof A=="string"?"name":"hash";return(I=(i=this.model)==null?void 0:i.parameters)==null?void 0:I.filter(o=>o[t]===A).forEach(o=>o.value=e)}getBool(A){var t,i,I;const e=typeof A=="string"?"name":"hash";return((I=(i=(t=this.model)==null?void 0:t.parameters)==null?void 0:i.find(o=>o[e]===A))==null?void 0:I.value)??!1}setFloat(A,e){var I,o;const t=typeof A=="string"?"name":"hash",i=(o=(I=this.model)==null?void 0:I.parameters)==null?void 0:o.filter(s=>s[t]===A);return i.forEach(s=>s.value=e),(i==null?void 0:i.length)>0}getFloat(A){var t,i,I;const e=typeof A=="string"?"name":"hash";return((I=(i=(t=this.model)==null?void 0:t.parameters)==null?void 0:i.find(o=>o[e]===A))==null?void 0:I.value)??0}setInteger(A,e){var i,I;const t=typeof A=="string"?"name":"hash";return(I=(i=this.model)==null?void 0:i.parameters)==null?void 0:I.filter(o=>o[t]===A).forEach(o=>o.value=e)}getInteger(A){var t,i,I;const e=typeof A=="string"?"name":"hash";return((I=(i=(t=this.model)==null?void 0:t.parameters)==null?void 0:i.find(o=>o[e]===A))==null?void 0:I.value)??0}setTrigger(A){var t,i;mI&&console.log("SET TRIGGER",A);const e=typeof A=="string"?"name":"hash";return(i=(t=this.model)==null?void 0:t.parameters)==null?void 0:i.filter(I=>I[e]===A).forEach(I=>I.value=!0)}resetTrigger(A){var t,i;const e=typeof A=="string"?"name":"hash";return(i=(t=this.model)==null?void 0:t.parameters)==null?void 0:i.filter(I=>I[e]===A).forEach(I=>I.value=!1)}getTrigger(A){var t,i,I;const e=typeof A=="string"?"name":"hash";return((I=(i=(t=this.model)==null?void 0:t.parameters)==null?void 0:i.find(o=>o[e]===A))==null?void 0:I.value)??!1}isInTransition(){return this._activeStates.length>1}setSpeed(A){this._speed=A}FindState(A){return this.findState(A)}findState(A){if(!A)return null;if(Array.isArray(this.model.layers)){for(const e of this.model.layers)for(const t of e.stateMachine.states)if(t.name===A||t.hash==A)return t}return null}getCurrentStateInfo(){if(!this._activeState)return null;const A=this._activeState.motion.action;if(!A)return null;const e=this._activeState.motion.clip.duration,t=e<=0?0:Math.abs(A.time/e);return new Bh(this._activeState,t,e,this._speed)}get currentAction(){if(!this._activeState)return null;const A=this._activeState.motion.action;return A||null}get context(){var A;return(A=this.animator)==null?void 0:A.context}get mixer(){return this._mixer}bind(A){A?this.animator!==A&&(this.animator=A,this._mixer=new Yy(this.animator.gameObject),this.createActions(this.animator)):console.error("AnimatorController.bind: animator is null")}clone(){if(typeof this.model=="string")return console.warn("AnimatorController has not been resolved, can not create model from string",this.model),null;mI&&console.warn("AnimatorController clone()",this.model);const A=Cu(this.model,(t,i,I)=>I==null?!0:!(I.type==="Object3D"||I.isObject3D===!0||pH(I)||I.tracks!==void 0||I instanceof Ro));return console.assert(A!==this.model),new Ro(A)}update(A){var t,i;if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates(A);const e=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&((t=this.rootMotionHandler)==null||t.onBeforeUpdate(A)),this._mixer.update(e),this.animator.applyRootMotion&&((i=this.rootMotionHandler)==null||i.onAfterUpdate(A))}get activeState(){return this._activeState}updateActiveStates(A){for(let e=0;e<this._activeStates.length;e++){const t=this._activeStates[e],i=t.motion;if(!i.action)this._activeStates.splice(e,1),e--;else{const I=i.action;I.weight=A,I.getEffectiveWeight()<=0&&!I.isRunning()&&(mI&&console.debug("REMOVE",t.name,I.getEffectiveWeight(),I.isRunning(),I.isScheduled()),this._activeStates.splice(e,1),e--)}}}setStartTransition(){for(const A of this.model.layers){const e=A.stateMachine;e.defaultState===void 0&&(mI&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",A),e.defaultState=0);const t=e.states[e.defaultState];this.transitionTo(t,0,this.normalizedStartOffset)}}evaluateTransitions(){var I;let A=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;A=!0}const e=this._activeState,t=e.motion.action;for(const o of e.transitions){if(!o.hasExitTime&&o.conditions.length<=0)continue;let s=!0;for(const n of o.conditions)if(!this.evaluateCondition(n)){s=!1;break}if(s)if(t){const n=e.motion.clip.duration,C=n<=0?1:Math.abs(t.time/n);let a=!1;if(o.hasExitTime?t.timeScale>0?a=C>=o.exitTime:t.timeScale<0&&(a=1-C>=o.exitTime):a=!0,a){for(const B of o.conditions){const Q=this.model.parameters.find(E=>E.name===B.parameter);(Q==null?void 0:Q.type)===_N.Trigger&&Q.value&&(Q.value=!1)}t.clampWhenFinished=!0,mI&&console.log("transition to "+o.destinationState,o,C,o.exitTime,o.hasExitTime),this.transitionTo(o.destinationState,o.duration,o.offset);return}}else{this.transitionTo(o.destinationState,o.duration,o.offset);return}}if(t){let o=e.speed??1;e.speedParameter&&(o*=this.getFloat(e.speedParameter)),o!==void 0&&(t.timeScale=o*this._speed)}let i=!1;if(e.motion.isLooping&&t&&(t.time>=t.getClip().duration?(i=!0,t.reset(),t.time=0,t.play()):t.time<=0&&t.timeScale<0&&(i=!0,t.reset(),t.time=t.getClip().duration,t.play())),!i&&e&&!A&&t&&this.animator&&e.behaviours){const o=t==null?void 0:t.getClip().duration,s=t.time/o,n=new Bh(this._activeState,s,o,this._speed);for(const C of e.behaviours)C.instance&&((I=C.instance.onStateUpdate)==null||I.call(C.instance,this.animator,n,0))}}getState(A,e){return typeof A=="number"&&(A==-1&&(A=this.model.layers[e].stateMachine.defaultState,A===void 0&&(mI&&console.warn("AnimatorController default state is undefined: ",this.model,"Layer: "+e),A=0)),A=this.model.layers[e].stateMachine.states[A]),A}transitionTo(A,e,t){var C,a,B,Q,E,c,d,l;if(!this.animator)return;const i=0;if(A=this.getState(A,i),!(A!=null&&A.motion)||!A.motion.clip||!(A.motion.clip instanceof LI))return;const I=this._activeState===A;if(I){const h=A.motion;if(!h.action_loopback&&h.clip){const p=this.rootMotionHandler?this.animator.gameObject.matrix.clone():null;this._mixer.uncacheAction(h.clip,this.animator.gameObject),p&&p.decompose(this.animator.gameObject.position,this.animator.gameObject.quaternion,this.animator.gameObject.scale),h.action_loopback=this.createAction(h.clip)}}if((C=this._activeState)!=null&&C.behaviours&&this._activeState.motion.action){const h=(a=this._activeState)==null?void 0:a.motion.clip.duration,p=this._activeState.motion.action.time/h,u=new Bh(this._activeState,p,h,this._speed);for(const f of this._activeState.behaviours)(Q=(B=f.instance)==null?void 0:B.onStateExit)==null||Q.call(f.instance,this.animator,u,i)}const o=(E=this._activeState)==null?void 0:E.motion.action;o&&o.fadeOut(e),I&&(A.motion.action=A.motion.action_loopback,A.motion.action_loopback=o);const s=this._activeState;this._activeState=A;const n=(c=A.motion)==null?void 0:c.action;if(n){if(t=Math.max(0,Math.min(1,t)),A.cycleOffsetParameter){let p=this.getFloat(A.cycleOffsetParameter);typeof p=="number"?(p<0&&(p+=1),t+=p,t%=1):mI&&console.warn("AnimatorController cycle offset parameter is not a number",A.cycleOffsetParameter)}else typeof A.cycleOffset=="number"&&(t+=A.cycleOffset,t%=1);n.isRunning()&&n.stop(),n.reset(),n.enabled=!0;const h=A.motion.clip.duration;if(n.time=I?0:t*h,n.timeScale<0&&(n.time=h-n.time),n.clampWhenFinished=!0,n.setLoop(gd,0),e>0?n.fadeIn(e):n.weight=1,n.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(n),this._activeStates.includes(A)||this._activeStates.push(A),this._activeState.behaviours){const p=new Bh(A,t,h,this._speed);for(const u of this._activeState.behaviours)(l=(d=u.instance)==null?void 0:d.onStateEnter)==null||l.call(u.instance,this.animator,p,i)}}else mI&&(A.__warned_no_motion||(A.__warned_no_motion=!0,console.warn("No action",A.motion,this)));mI&&console.log("TRANSITION FROM "+(s==null?void 0:s.name)+" TO "+A.name,e,o,n,n==null?void 0:n.getEffectiveTimeScale(),n==null?void 0:n.getEffectiveWeight(),n==null?void 0:n.isRunning(),n==null?void 0:n.isScheduled(),n==null?void 0:n.paused)}createAction(A){var t,i;if(this._mixer.existingAction(A)&&this._mixer.uncacheAction(A,(t=this.animator)==null?void 0:t.gameObject),(i=this.animator)!=null&&i.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new FgA(this));const I=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,I,A)}else return this._mixer.clipAction(A)}evaluateCondition(A){const e=this.model.parameters.find(t=>t.name===A.parameter);if(!e)return!1;switch(A.mode){case Ra.If:return e.value===!0;case Ra.IfNot:return e.value===!1;case Ra.Greater:return e.value>A.threshold;case Ra.Less:return e.value<A.threshold;case Ra.Equals:return e.value===A.threshold;case Ra.NotEqual:return e.value!==A.threshold}return!1}createActions(A){var e,t,i,I;mI&&console.log("AnimatorController createActions",this.model);for(const o of this.model.layers){const s=o.stateMachine;for(let n=0;n<s.states.length;n++){const C=s.states[n];C.transitions||(C.transitions=[]);for(const a of C.transitions)a.conditions||(a.conditions=[]);if(C.motion||(C.motion=_O(C.name)),this.animator&&C.motion.clips){const a=(e=C.motion.clips)==null?void 0:e.find(B=>{var Q,E;return B.node.name===((E=(Q=this.animator)==null?void 0:Q.gameObject)==null?void 0:E.name)});a?C.motion.clip=a.clip:(mI||he())&&console.warn('Could not find clip for animator "'+((i=(t=this.animator)==null?void 0:t.gameObject)==null?void 0:i.name)+'"',C.motion.clips.map(B=>B.node.name))}if(!C.motion.clip){const a=new LI(void 0,void 0,[]);C.motion.clip=a}if((I=C.motion)!=null&&I.clip){const a=C.motion.clip;if(a instanceof LI){const B=this.createAction(a);C.motion.action=B}else(mI||he())&&console.warn("No valid animationclip assigned",C)}if(C.behaviours&&Array.isArray(C.behaviours))for(const a of C.behaviours){if(!(a!=null&&a.typeName))continue;const B=z.get(a.typeName),Q=new B;Q.isStateMachineBehaviour&&(Q._context=this.context??void 0,nc(Q,a.properties),a.instance=Q),mI&&console.log("Created animator controller behaviour",C.name,a.typeName,a.properties,Q)}}}}*enumerateActions(){if(this.model.layers)for(const A of this.model.layers){const e=A.stateMachine;for(let t=0;t<e.states.length;t++){const i=e.states[t];i!=null&&i.motion&&(i.motion.action&&(yield i.motion.action),i.motion.action_loopback&&(yield i.motion.action_loopback))}}}}class xq{constructor(A,e){r(this,"track");r(this,"createdInterpolant");r(this,"originalEvaluate");r(this,"customEvaluate");this.track=A;const t=A,i=t.createInterpolant.bind(A);t.createInterpolant=()=>(t.createInterpolant=i,this.createdInterpolant=i(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=I=>{if(!this.originalEvaluate)return;const o=this.originalEvaluate(I);return e(I,o)},this.createdInterpolant.evaluate=this.customEvaluate,this.createdInterpolant)}dispose(){this.createdInterpolant&&this.originalEvaluate&&(this.createdInterpolant.evaluate=this.originalEvaluate),this.track=void 0,this.createdInterpolant=null,this.originalEvaluate=void 0,this.customEvaluate=void 0}}const Ig=class{constructor(A,e,t,i,I){r(this,"_action");r(this,"root");r(this,"clip");r(this,"positionWrapper",null);r(this,"rotationWrapper",null);r(this,"context");r(this,"positionChange",new w);r(this,"rotationChange",new MA);r(this,"_prevTime",0);if(this.context=A,this.root=e,this.clip=t,Ig.firstKeyframeRotation[this.cacheId]||(Ig.firstKeyframeRotation[this.cacheId]=new MA),I){const o=I.values;Ig.firstKeyframeRotation[this.cacheId].set(o[0],o[1],o[2],o[3])}Ig.spaceRotation[this.cacheId]||(Ig.spaceRotation[this.cacheId]=new MA),Ig.effectiveSpaceRotation[this.cacheId]||(Ig.effectiveSpaceRotation[this.cacheId]=new MA),Ig.clipOffsetRotation[this.cacheId]=new MA,I&&Ig.clipOffsetRotation[this.cacheId].set(I.values[0],I.values[1],I.values[2],I.values[3]).invert(),this.handlePosition(t,i),this.handleRotation(t,I)}set action(A){this._action=A}get action(){return this._action}get cacheId(){return this.root.uuid}onStart(A){if(A.getClip()!==this.clip)return;Ig.lastObjRotation[this.cacheId]||(Ig.lastObjRotation[this.cacheId]=this.root.quaternion.clone());const e=Ig.lastObjRotation[this.cacheId];if(Ig.spaceRotation[this.cacheId].copy(e),bf){const t=new $t().setFromQuaternion(e);console.log("START",this.clip.name,te.toDegrees(t.y),this.root.position.z)}}getClipRotationOffset(){return Ig.clipOffsetRotation[this.cacheId]}handlePosition(A,e){if(e){const t=this.root;bf&&t.add(new Cs),Ig.lastObjPosition[this.cacheId]||(Ig.lastObjPosition[this.cacheId]=this.root.position.clone());const i=new w,I=new w;this.positionWrapper=new xq(e,(o,s)=>{const n=this.action.getEffectiveWeight();return bf&&t.position.length()>8&&t.position.set(0,t.position.y,0),o>this._prevTime&&(i.set(s[0],s[1],s[2]),i.sub(I),i.multiplyScalar(n),i.applyQuaternion(this.getClipRotationOffset()),i.applyQuaternion(t.quaternion),this.positionChange.copy(i)),I.fromArray(s),this._prevTime=o,s[0]=0,s[1]=0,s[2]=0,s})}}handleRotation(A,e){if(e){if(bf){const o=e.values,s=new $t().setFromQuaternion(new MA(o[0],o[1],o[2],o[3]));console.log(A.name,e.name,"FIRST ROTATION IN TRACK",te.toDegrees(s.y));const n=e.values.length-4,C=new MA().set(o[n],o[n+1],o[n+2],o[n+3]),a=new $t().setFromQuaternion(C);console.log(A.name,e.name,"LAST ROTATION IN TRACK",te.toDegrees(a.y))}let t=0;const i=new MA,I=new MA;this.rotationWrapper=new xq(e,(o,s)=>(o>t&&(I.set(s[0],s[1],s[2],s[3]),i.invert(),I.multiply(i),this.rotationChange.copy(I)),i.fromArray(s),t=o,s[0]=0,s[1]=0,s[2]=0,s[3]=1,s))}}onBeforeUpdate(A){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(A){return!this.action||(A*=this.action.getEffectiveWeight(),A<=0)?!1:(this.positionChange.multiplyScalar(A),this.rotationChange.slerp(Ig.identityQuaternion,1-A),!0)}};let nn=Ig;r(nn,"lastObjPosition",{}),r(nn,"lastObjRotation",{}),r(nn,"firstKeyframeRotation",{}),r(nn,"spaceRotation",{}),r(nn,"effectiveSpaceRotation",{}),r(nn,"clipOffsetRotation",{}),r(nn,"identityQuaternion",new MA);class FgA{constructor(A){r(this,"controller");r(this,"handler",[]);r(this,"root");r(this,"basePosition",new w);r(this,"baseQuaternion",new MA);r(this,"baseRotation",new $t);r(this,"summedPosition",new w);r(this,"summedRotation",new MA);this.controller=A}createClip(A,e,t){this.root=e,e&&"name"in e&&e.name;const i=this.findRootTrack(t,".position"),I=this.findRootTrack(t,".quaternion"),o=new nn(this.controller.context,e,t,i,I);this.handler.push(o);const s=A.clipAction(t);return o.action=s,s}onStart(A){for(const e of this.handler)e.onStart(A)}onBeforeUpdate(A){this.basePosition.copy(this.root.position),this.baseQuaternion.copy(this.root.quaternion);for(const e of this.handler)e.onBeforeUpdate(A)}onAfterUpdate(A){if(!(A<=0)){this.root.position.copy(this.basePosition),this.root.quaternion.copy(this.baseQuaternion),this.summedPosition.set(0,0,0),this.summedRotation.set(0,0,0,1);for(const e of this.handler)e.onAfterUpdate(A)&&(this.summedPosition.add(e.positionChange),this.summedRotation.multiply(e.rotationChange));this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation)}}findRootTrack(A,e){const t=A.tracks;if(!t)return null;for(const i of t)if(i.name.endsWith(e))return i;return null}}class KgA extends qn{onSerialize(A,e){}onDeserialize(A,e){if(e.type===Ro&&(A==null?void 0:A.__type)==="AnimatorController")return new Ro(A)}}new KgA(Ro);var JgA=Object.defineProperty,bgA=Object.getOwnPropertyDescriptor,yS=(g,A,e,t)=>{for(var i=t>1?void 0:t?bgA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&JgA(A,e,i),i};const Wo=IA("debuganimator");class Zg extends RA{constructor(){super(...arguments);r(this,"applyRootMotion",!1);r(this,"hasRootMotion",!1);r(this,"keepAnimatorControllerStateOnDisable",!1);r(this,"_parametersAreDirty",!1);r(this,"_isDirty",!1);r(this,"_speed",1);r(this,"_normalizedStartOffset",0);r(this,"_animatorController",null);r(this,"_initializeWithRuntimeAnimatorController")}set runtimeAnimatorController(e){var t;this._animatorController&&this._animatorController.model===e||(e?e instanceof Ro?(e.animator&&e.animator!==this&&(console.warn("AnimatorController can not be bound to multiple animators",(t=e.model)==null?void 0:t.name),e.model||console.error("AnimatorController has no model"),e=new Ro(e.model)),this._animatorController=e,this._animatorController.bind(this)):(Wo&&console.log("Assign animator controller",e,this),this._animatorController=new Ro(e),this.__didAwake&&this._animatorController.bind(this)):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}getCurrentStateInfo(){var e;return(e=this.runtimeAnimatorController)==null?void 0:e.getCurrentStateInfo()}get currentAction(){var e;return((e=this.runtimeAnimatorController)==null?void 0:e.currentAction)||null}get parametersAreDirty(){return this._parametersAreDirty}get isDirty(){return this._isDirty}Play(e,t=-1,i=Number.NEGATIVE_INFINITY,I=0){this.play(e,t,i,I)}play(e,t=-1,i=Number.NEGATIVE_INFINITY,I=0){var o;(o=this.runtimeAnimatorController)==null||o.play(e,t,i,I),this._isDirty=!0}Reset(){this.reset()}reset(){var e;(e=this._animatorController)==null||e.reset(),this._isDirty=!0}SetBool(e,t){this.setBool(e,t)}setBool(e,t){var i,I;Wo&&console.log("setBool",e,t),((i=this.runtimeAnimatorController)==null?void 0:i.getBool(e))!==t&&(this._parametersAreDirty=!0),(I=this.runtimeAnimatorController)==null||I.setBool(e,t)}GetBool(e){return this.getBool(e)}getBool(e){var i;const t=((i=this.runtimeAnimatorController)==null?void 0:i.getBool(e))??!1;return Wo&&console.log("getBool",e,t),t}toggleBool(e){this.setBool(e,!this.getBool(e))}SetFloat(e,t){this.setFloat(e,t)}setFloat(e,t){var i,I;((i=this.runtimeAnimatorController)==null?void 0:i.getFloat(e))!==t&&(this._parametersAreDirty=!0),Wo&&console.log("setFloat",e,t),(I=this.runtimeAnimatorController)==null||I.setFloat(e,t)}GetFloat(e){return this.getFloat(e)}getFloat(e){var i;const t=((i=this.runtimeAnimatorController)==null?void 0:i.getFloat(e))??-1;return Wo&&console.log("getFloat",e,t),t}SetInteger(e,t){this.setInteger(e,t)}setInteger(e,t){var i,I;((i=this.runtimeAnimatorController)==null?void 0:i.getInteger(e))!==t&&(this._parametersAreDirty=!0),Wo&&console.log("setInteger",e,t),(I=this.runtimeAnimatorController)==null||I.setInteger(e,t)}GetInteger(e){return this.getInteger(e)}getInteger(e){var i;const t=((i=this.runtimeAnimatorController)==null?void 0:i.getInteger(e))??-1;return Wo&&console.log("getInteger",e,t),t}SetTrigger(e){this.setTrigger(e)}setTrigger(e){var t;this._parametersAreDirty=!0,Wo&&console.log("setTrigger",e),(t=this.runtimeAnimatorController)==null||t.setTrigger(e)}ResetTrigger(e){this.resetTrigger(e)}resetTrigger(e){var t;this._parametersAreDirty=!0,Wo&&console.log("resetTrigger",e),(t=this.runtimeAnimatorController)==null||t.resetTrigger(e)}GetTrigger(e){this.getTrigger(e)}getTrigger(e){var i;const t=(i=this.runtimeAnimatorController)==null?void 0:i.getTrigger(e);return Wo&&console.log("getTrigger",e,t),t}IsInTransition(){return this.isInTransition()}isInTransition(){var e;return((e=this.runtimeAnimatorController)==null?void 0:e.isInTransition())??!1}SetSpeed(e){return this.setSpeed(e)}setSpeed(e){var t;e!==this._speed&&(Wo&&console.log("setSpeed",e),this._speed=e,((t=this._animatorController)==null?void 0:t.animator)==this&&this._animatorController.setSpeed(e))}set minMaxSpeed(e){var t;this._speed=te.lerp(e.x,e.y,Math.random()),((t=this._animatorController)==null?void 0:t.animator)==this&&this._animatorController.setSpeed(this._speed)}set minMaxOffsetNormalized(e){var t;this._normalizedStartOffset=te.lerp(e.x,e.y,Math.random()),((t=this.runtimeAnimatorController)==null?void 0:t.animator)==this&&(this.runtimeAnimatorController.normalizedStartOffset=this._normalizedStartOffset)}awake(){Wo&&console.log("ANIMATOR",this.name,this),this.gameObject&&this.initializeRuntimeAnimatorController()}initializeRuntimeAnimatorController(e=!1){const t=e||this.runtimeAnimatorController!==this._initializeWithRuntimeAnimatorController;if(this.runtimeAnimatorController&&t){const i=this.runtimeAnimatorController.clone();this._initializeWithRuntimeAnimatorController=i,i?(console.assert(this.runtimeAnimatorController!==i),this.runtimeAnimatorController=i,console.assert(this.runtimeAnimatorController===i),this.runtimeAnimatorController.bind(this),this.runtimeAnimatorController.setSpeed(this._speed),this.runtimeAnimatorController.normalizedStartOffset=this._normalizedStartOffset):console.warn("Could not clone animator controller",this.runtimeAnimatorController)}}onDisable(){var e;this.keepAnimatorControllerStateOnDisable||(e=this._animatorController)==null||e.reset()}onBeforeRender(){this._isDirty=!1,this._parametersAreDirty=!1,!UgA(this.gameObject)&&this._animatorController&&this._animatorController.update(1)}}yS([D()],Zg.prototype,"applyRootMotion",2);yS([D()],Zg.prototype,"hasRootMotion",2);yS([D()],Zg.prototype,"keepAnimatorControllerStateOnDisable",2);yS([D()],Zg.prototype,"runtimeAnimatorController",1);const EB=IA("debugusdzanimation"),jM=IA("debugusdzanimationserialization");class SS{constructor(A,e,t){r(this,"_start");r(this,"ext");r(this,"root");r(this,"clip");this.ext=A,this.root=e,this.clip=t}get start(){return this._start===void 0&&(this._start=this.ext.getStartTime01(this.root,this.clip)),this._start}get duration(){return this.clip.duration}}const JK=class{constructor(A,e,t){r(this,"clip");r(this,"pos");r(this,"rot");r(this,"scale");r(this,"root");r(this,"target");r(this,"duration",0);r(this,"useRootMotion",!1);this.root=A,this.target=e,this.clip=t,t?this.duration=t.duration:this.duration=JK.restPoseClipDuration;const i=aA.getComponent(A,Zg);i&&(this.useRootMotion=i.applyRootMotion)}get frameRate(){return 60}addTrack(A){if(!this.clip){console.error("This is a rest clip but you're trying to add tracks to it – this is likely a bug");return}A.name.endsWith("position")&&(this.pos=A),A.name.endsWith("quaternion")&&(this.rot=A),A.name.endsWith("scale")&&(this.scale=A)}getFrames(){var A,e,t,i,I,o;return this.clip?Math.max(((e=(A=this.pos)==null?void 0:A.times)==null?void 0:e.length)??0,((i=(t=this.rot)==null?void 0:t.times)==null?void 0:i.length)??0,((o=(I=this.scale)==null?void 0:I.times)==null?void 0:o.length)??0):2}getDuration(){return this.duration}getSortedTimesArray(A=!0,e=!0,t=!0){var n,C,a;if(!this.clip)return[0,this.duration];const i=(n=this.pos)==null?void 0:n.times,I=(C=this.rot)==null?void 0:C.times,o=(a=this.scale)==null?void 0:a.times,s=[];if(A&&i)for(const B of i)s.push(B);if(e&&I)for(const B of I)s.push(B);if(t&&o)for(const B of o)s.push(B);return s.includes(0)||s.push(0),s.sort((B,Q)=>B-Q),[...new Set(s)]}*getValues(A,e=!0,t=!0,i=!0){var Q,E,c;const I=new w,o=new MA,s=new w(1,1,1),n=this.target,C=e?(Q=this.pos)==null?void 0:Q.createInterpolant():void 0,a=t?(E=this.rot)==null?void 0:E.createInterpolant():void 0,B=i?(c=this.scale)==null?void 0:c.createInterpolant():void 0;C||I.set(n.position.x,n.position.y,n.position.z),a||o.set(n.quaternion.x,n.quaternion.y,n.quaternion.z,n.quaternion.w),B||s.set(n.scale.x,n.scale.y,n.scale.z);for(let d=0;d<A.length;d++){const l=A[d];if(C){const h=C.evaluate(l);I.set(h[0],h[1],h[2])}if(a){const h=a.evaluate(l);o.set(h[0],h[1],h[2],h[3])}if(B){const h=B.evaluate(l);s.set(h[0],h[1],h[2])}if(this.useRootMotion&&n===this.root){const h=new GA;h.compose(I,o,s),h.multiply(n.matrix),h.decompose(I,o,s)}yield{time:l,translation:I,rotation:o,scale:s,index:d}}}};let Sg=JK;r(Sg,"animationDurationPadding",1/60),r(Sg,"restPoseClipDuration",1/60);class Ku{constructor(A){r(this,"dict",new Map);r(this,"rootTargetMap",new Map);r(this,"rootAndClipToRegisteredAnimationMap",new Map);r(this,"rootToRegisteredClipCount",new Map);r(this,"serializers",[]);r(this,"injectRestPoses",!1);r(this,"injectImplicitBehaviours",!1);this.injectRestPoses=A,this.injectImplicitBehaviours=A}get extensionName(){return"animation"}getStartTimeCode(){return!this.injectRestPoses||this.rootAndClipToRegisteredAnimationMap.size===0?0:(Sg.restPoseClipDuration+Sg.animationDurationPadding)*60}getEndTimeCode(){let A=0;for(const[e,t]of this.rootAndClipToRegisteredAnimationMap){const i=t.start+t.duration;i>A&&(A=i)}return A*60}getClipCount(A){let e=this.rootToRegisteredClipCount.get(A);return this.injectRestPoses&&(e=e?e-1:0),e??0}getStartTime01(A,e){const t=this.rootTargetMap.get(A);if(!t)return 0;const i=this.dict.get(t[0]);if(!i)return console.error("Trying to get start time for root that has no animation data",A,e,...this.dict),0;let I=0;for(let o=0;o<i.length&&i[o].clip!==e;o++)I+=i[o].getDuration()+Sg.animationDurationPadding;return I}registerAnimation(A,e){if(!e||!A)return null;this.rootTargetMap.has(A)||this.rootTargetMap.set(A,[]);const t=A.uuid+e.uuid;if(this.rootAndClipToRegisteredAnimationMap.has(t))return this.rootAndClipToRegisteredAnimationMap.get(t);EB&&console.log("registerAnimation",A,e);const i=this.injectRestPoses?1:0,I=this.rootToRegisteredClipCount.get(A)??i,o=this.rootTargetMap.get(A),s=new Set(o);if(e.tracks)for(const C of e.tracks){const a=Ve.parseTrackName(C.name),B=Ve.findNode(A,a.nodeName);if(!B){console.warn("no object found for track",C.name,"using "+A.name+" instead");continue}this.dict.has(B)||this.dict.set(B,[]);const Q=this.dict.get(B);if(!Q){console.warn("no transform data found for target ",B,"at slot "+I+", this is likely a bug");continue}if(s.delete(B),this.injectRestPoses&&!Q[0]){const c=new Sg(null,B,void 0);Q[0]=c}let E=Q[I];E||(E=new Sg(A,B,e),Q[I]=E),E.addTrack(C),o!=null&&o.includes(B)||o==null||o.push(B)}for(const C of s){const a=this.dict.get(C);if(!a)continue;if(this.injectRestPoses&&!a[0]){const Q=new Sg(null,C,void 0);a[0]=Q}let B=a[I];B||(EB&&console.log("Adding padding clip for ",C,e,"at slot",I),B=new Sg(A,C,e),a[I]=B)}const n=new SS(this,A,e);return this.rootAndClipToRegisteredAnimationMap.set(t,n),this.rootToRegisteredClipCount.set(A,I+1),n}onAfterHierarchy(A){EB&&console.log("Animation clips per animation target node",this.dict)}onAfterBuildDocument(A){var e,t;for(const i of this.serializers){const I=(e=i.model)==null?void 0:e.parent,o=(I==null?void 0:I.isDynamic)===!0;jM&&console.log(o,(t=i.model)==null?void 0:t.parent),o&&i.registerCallback(I)}}onExportObject(A,e,t){aA.foreachComponent(A,I=>{const o=I;typeof o.createAnimation=="function"&&o.createAnimation(this,e,t)},!1);const i=new vgA(A,this.dict);this.serializers.push(i),i.registerCallback(e)}}class vgA{constructor(A,e){r(this,"object");r(this,"dict");r(this,"model");r(this,"callback");this.object=A,this.dict=e}registerCallback(A){this.model&&this.callback&&this.model.removeEventListener("serialize",this.callback),this.callback||(this.callback=this.onSerialize.bind(this)),jM&&console.log("REPARENT",A),this.model=A,this.model.addEventListener("serialize",this.callback)}skinnedMeshExport(A,e){var I;const t=this.model,i=this.dict;if(t&&t.skinnedMesh){let o=function(m){const N=[];for(const[y,U]of m){let H=`${y} : [`;const x=[];for(const K of U)x.push(`(${fg(K.x)}, ${fg(K.y)}, ${fg(K.z)})`);H=H.concat(x.join(", ")),H=H.concat("],"),N.push(H)}return N},s=function(m){const N=[];for(const[y,U]of m){let H=`${y} : [`;const x=[];for(const K of U)x.push(`(${fg(K.w)}, ${fg(K.x)}, ${fg(K.y)}, ${fg(K.z)})`);H=H.concat(x.join(", ")),H=H.concat("],"),N.push(H)}return N},n=function(m){let N,y=!0;const U=new Map;for(const[x,K]of m){N===void 0&&(N=K.length),N!==K.length&&(y=!1);let O=0;for(const b of K)O++,b||(U.has(x)||U.set(x,[]),U.get(x).push(O))}EB&&console.log("Bone count: ",m.size,"TransformData entries per bone: ",N,"Undefined bone entries: ",U),console.assert(y,"All bones should have the same number of TransformData entries",m),console.assert(U.size===0,"All TransformData entries should be set",U);const H=[];for(const[x,K]of m){const O=new Array;let b=0;for(let v=0;v<K.length;v++)O.push(b),b+=K[v].getDuration()+Sg.animationDurationPadding;for(let v=0;v<K.length;v++){const T=K[v],V=O[v];H.length<=v&&H.push({pos:[],rot:[],scale:[],timeOffset:V});const X=H[v];X.pos.push(...T.getSortedTimesArray(!0,!1,!1)),X.rot.push(...T.getSortedTimesArray(!1,!0,!1)),X.scale.push(...T.getSortedTimesArray(!1,!1,!0))}}for(const x of H)x.pos.sort((K,O)=>K-O),x.rot.sort((K,O)=>K-O),x.scale.sort((K,O)=>K-O),x.pos=[...new Set(x.pos)],x.rot=[...new Set(x.rot)],x.scale=[...new Set(x.scale)];return H},C=function(m,N,y){const U=new Map,H=new Map,x=new Map,K=N.length;for(const O of y){const b=m.get(O);let v;b?console.assert(b.length===K,"We should have the same number of TransformData entries for each bone",b,N):v=new Sg(null,O,void 0);for(let T=0;T<K;T++){const V=b?b[T]:v,X=N[T];for(const{time:CA,translation:QA}of V.getValues(X.pos,!0,!1,!1)){const gA=(CA+X.timeOffset)*60;U.has(gA)||U.set(gA,new Array),U.get(gA).push(QA.clone())}for(const{time:CA,rotation:QA}of V.getValues(X.rot,!1,!0,!1)){const gA=(CA+X.timeOffset)*60;H.has(gA)||H.set(gA,new Array),H.get(gA).push(QA.clone())}for(const{time:CA,scale:QA}of V.getValues(X.scale,!1,!1,!0)){const gA=(CA+X.timeOffset)*60;x.has(gA)||x.set(gA,new Array),x.get(gA).push(QA.clone())}}}return{position:U.size==0?void 0:U,quaternion:H.size==0?void 0:H,scale:x.size==0?void 0:x}},a=function(m){const N=[];for(const y of m)N.push(`(${fg(y.x)}, ${fg(y.y)}, ${fg(y.z)})`);return N.join(", ")},B=function(m){const N=[];for(const y of m)N.push(`(${fg(y.w)}, ${fg(y.x)}, ${fg(y.y)}, ${fg(y.z)})`);return N.join(", ")},Q=function(m){const N=new Map;if(EB){const y=new Array;for(const[U,H]of i)y.push(U.uuid+": "+H.length+" "+H.map(x=>{var K;return(K=x.clip)==null?void 0:K.uuid.substring(0,6)}).join(" "));console.log(`getPerBoneTransformData
5507
5507
  `+y.join(`
5508
5508
  `))}for(const y of m){const U=i.get(y);U&&N.set(y,U)}return N},E=function(m){const N=Q(m),y=n(N);return C(N,y,m)};const c=t.skinnedMesh.skeleton,d=new Array;for(const m in c.bones){const N=c.bones[m],y=c.boneInverses[m];d.push({bone:N,inverse:y})}for(const m of zH(c.bones))d.push({bone:m,inverse:m.matrixWorld.clone().invert()});const l=d[0].bone.parent;l||console.error("No bone parent found for skinned mesh during USDZ export",t.skinnedMesh),d.sort((m,N)=>_E(m.bone,l)>_E(N.bone,l)?1:-1);const h=[],p=[],u=[],f=[];for(const{bone:m}of d)h.push(m.matrix.clone()),p.push(m.position),u.push(m.quaternion),f.push(m.scale);const k=d.map(m=>'"'+_E(m.bone,l)+'"').join(", "),G=d.map(m=>GE(m.inverse.clone().invert())).join(", ");A.beginBlock('def Skeleton "Rig"'),A.appendLine(`uniform matrix4d[] bindTransforms = [${G}]`),A.appendLine(`uniform token[] joints = [${k}]`),A.appendLine('uniform token purpose = "guide"'),A.appendLine(`uniform matrix4d[] restTransforms = [${h.map(m=>GE(m)).join(", ")}]`),A.appendLine(`matrix4d xformOp:transform = ${GE(new GA)}`),A.appendLine('uniform token[] xformOpOrder = ["xformOp:transform"]');const M=E(d.map(m=>m.bone));if(EB){let m=1e7,N=0;for(const y of((I=M.position)==null?void 0:I.keys())??[])m=Math.min(m,y),N=Math.max(N,y);console.log("Time samples",m,N,M)}if(A.beginBlock('def SkelAnimation "_anim"'),A.appendLine(`uniform token[] joints = [${k}]`),A.appendLine(`quatf[] rotations = [${B(u)}]`),M&&M.quaternion){A.beginBlock("quatf[] rotations.timeSamples = {","");const m=s(M.quaternion);for(const N of m)A.appendLine(N);A.closeBlock()}if(A.appendLine(`half3[] scales = [${a(f)}]`),M&&M.scale){A.beginBlock("half3[] scales.timeSamples = {","");const m=o(M.scale);for(const N of m)A.appendLine(N);A.closeBlock()}if(A.appendLine(`float3[] translations = [${a(p)}]`),M&&M.position){A.beginBlock("float3[] translations.timeSamples = {","");const m=o(M.position);for(const N of m)A.appendLine(N);A.closeBlock()}A.closeBlock(),A.closeBlock()}}onSerialize(A,e){var C;if(!this.model)return;const t=this.dict.get(this.object);if(t)for(let a=0;a<t.length;a++)t[a]===void 0&&(t[a]=new Sg(null,this.object,void 0));this.skinnedMeshExport(A,e);const i=this.object,I=this.dict.get(i);if(!I||i.isSkinnedMesh)return;jM&&console.log("SERIALIZE",this.model.name,this.object.type,I);const o=new GA;A.appendLine("matrix4d xformOp:transform.timeSamples = {"),A.indent++;const s=new Array;let n=0;for(let a=0;a<I.length;a++){if(s.push(n),I[a]===void 0){console.error("Got an undefined transform data, this is likely a bug.",i,I);continue}n+=I[a].getDuration()+Sg.animationDurationPadding}for(let a=0;a<I.length;a++){const B=I[a];if(!B)continue;const Q=s[a];{const E=B.getSortedTimesArray();if(!E||E.length===0){console.error("got an animated object but no time values?",i,B);continue}if(EB){const c=((C=B.clip)==null?void 0:C.name)??"rest",d=B.getDuration();console.log("Write .timeSamples:",c,Q,d,I),A.appendLine("# "+c+": start="+(Q*B.frameRate).toFixed(3)+", length="+(d*B.frameRate).toFixed(3)+", frames="+B.getFrames())}for(const{time:c,translation:d,rotation:l,scale:h}of B.getValues(E)){o.compose(d,l,h);const p=`${(Q+c)*B.frameRate}: ${GE(o)},`;A.appendLine(p)}}}A.indent--,A.appendLine("}")}}var qgA=Object.defineProperty,xgA=Object.getOwnPropertyDescriptor,TO=(g,A,e,t)=>{for(var i=t>1?void 0:t?xgA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&qgA(A,e,i),i};const Lq=IA("debugpost");class qe{constructor(A){r(this,"_active",!0);r(this,"_value");r(this,"_valueRaw");r(this,"_defaultValue");r(this,"valueProcessor");r(this,"onValueChanged");this._value=A,this._defaultValue=A,this._valueRaw=A}get overrideState(){return this._active}set overrideState(A){if(this._active===A)return;this._active=A;const e=A?this._valueRaw:this._defaultValue;this.processValue(e,!0)}get value(){return this._valueRaw}set value(A){this.processValue(A,!1)}set defaultValue(A){this._defaultValue=A}__init(){this.processValue(this._valueRaw,!0)}processValue(A,e){if(A==null||!e&&this.testIfValueChanged(A)===!1)return;const t=this._value;if(Lq){let i=!0;if(typeof t=="number"&&typeof A=="number"){const I=t==null?void 0:t.toFixed(4),o=A==null?void 0:A.toFixed(4);I!=o?i=!0:i=!1}i&&console.log("VolumeParameter: value changed from",t,"to",A)}!this._active&&this._defaultValue!==void 0?(this._value=this._defaultValue,A=this._defaultValue,this._valueRaw=A):(this._valueRaw=A,this._active&&this.valueProcessor&&(A=this.valueProcessor(A)),this._value=A),this.onValueChanged?this.onValueChanged(A,t,this):Lq&&console.log("VolumeParameter: onValueChanged not set")}testIfValueChanged(A){return this._valueRaw!==A}}TO([D()],qe.prototype,"overrideState",1);TO([D()],qe.prototype,"value",1);var LgA=Object.defineProperty,_gA=Object.getOwnPropertyDescriptor,TgA=(g,A,e,t)=>{for(var i=t>1?void 0:t?_gA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&LgA(A,e,i),i};const HgA=IA("debugpost");class hI extends RA{constructor(e=void 0){super();r(this,"active",!0);r(this,"_result");r(this,"_didCreateVolumeParameters",!1);if(e){this.ensureVolumeParameters();for(const t of Object.keys(e)){const i=e[t],I=this[t];I instanceof qe&&(I.value=i)}}}onEnable(){this.__internalDidAwakeAndStart&&(this.active=!0)}onDisable(){this.active=!1}init(){}apply(){var e;return this.ensureVolumeParameters(),this._result||(this._result=(e=this.onCreateEffect)==null?void 0:e.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){HgA&&console.warn("DISPOSE",this),this._result&&(Array.isArray(this._result)?this._result.forEach(e=>e.dispose()):this._result.dispose()),this._result=void 0}initParameters(){const e=Object.keys(this);for(const t of e){const i=this[t];i instanceof qe&&i.__init()}}onAfterDeserialize(e,t){if(typeof e=="object"){const i=this.$serializedTypes;if(i){for(const I of Object.keys(i))if(i[I]===qe){const s=e[I];if(s!==void 0){const n=this[I];n.value=s}}}}}onEditorModification(e){const t=e.propertyName;if(this[t]instanceof qe){const i=e.value;return this[t].value=i,!0}}ensureVolumeParameters(){if(this._didCreateVolumeParameters)return;this._didCreateVolumeParameters=!0;const e=this.$serializedTypes;if(e)for(const t of Object.keys(e))e[t]===qe&&(this[t]||(this[t]=new qe))}}TgA([D()],hI.prototype,"active",2);var YgA=Object.defineProperty,OgA=Object.getOwnPropertyDescriptor,PgA=(g,A,e,t)=>{for(var i=t>1?void 0:t?OgA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&YgA(A,e,i),i};const WgA=IA("debugpost"),VM={};function ds(g,A){VM[g]=A}function ZgA(g){return g.__type in VM?VM[g.__type]:(WgA&&g.__type&&console.warn("Unknown postprocessing type",g.__type,g),hI)}class Ju{constructor(){r(this,"components",[])}init(){var A;(A=this.components)==null||A.forEach(e=>e.init())}}PgA([Uc([g=>ZgA(g),hI])],Ju.prototype,"components",2);var jgA=Object.defineProperty,VgA=Object.getOwnPropertyDescriptor,zgA=(g,A,e,t)=>{for(var i=t>1?void 0:t?VgA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&jgA(A,e,i),i};class bu extends hI{constructor(){super(...arguments);r(this,"preset")}get typeName(){return"Antialiasing"}onCreateEffect(){const e=new RY({preset:QE.HIGH,edgeDetectionMode:QN.DEPTH});return this.preset.onValueChanged=t=>{e.applyPreset(t)},e}}zgA([D(qe)],bu.prototype,"preset",2);ds("Antialiasing",bu);const XgA=IA("debugusdz");class nr{constructor(){r(this,"files",new Array)}static getName(A){var I;const e=A.split(".").pop();let i=(I=A.split(".").slice(0,-1).join(".").split("/").pop())==null?void 0:I.replace(".","_");return i||(i="Audio_"+Math.random().toString(36).substring(2,15)),vC(i)+"."+e}get extensionName(){return"Audio"}onExportObject(A,e,t){const i=aA.getComponents(A,Di);if(i.length)for(const I of i){if(!I.clip||typeof I.clip!="string"||!I.playOnAwake)continue;const o=I.clip.split("/").pop()||"Audio",s=nr.getName(I.clip),n=vC(s);this.files.some(C=>C.path===I.clip)||this.files.push({path:I.clip,name:s}),t.quickLookCompatible||e.addEventListener("serialize",(C,a)=>{C.appendLine(),C.beginBlock(`def SpatialAudio "${n}"`,"(",!1),C.appendLine(`displayName = "${o}"`),C.closeBlock(")"),C.beginBlock(),C.appendLine(`uniform asset filePath = @audio/${s}@`),C.appendLine(`uniform token auralMode = "${I.spatialBlend>0?"spatial":"nonSpatial"}"`),C.appendLine(`uniform token playbackMode = "${I.loop?"loopFromStage":"onceFromStart"}"`),C.appendLine(`uniform float gain = ${I.volume}`),C.closeBlock()})}}async onAfterSerialize(A){for(const e of this.files){const t="audio/"+e.name;if(A.files[t]){XgA&&console.warn("Audio file with name "+t+" already exists in the context. Skipping.");continue}const o=await(await(await fetch(e.path)).blob()).arrayBuffer(),s=new Uint8Array(o);A.files[t]=s}}}const cB=IA("debugautosync"),rG=Symbol("syncerId");class $gA{constructor(){r(this,"_syncers",{})}getOrCreateSyncer(A){if(!A.guid)return null;if(this._syncers[A.guid])return this._syncers[A.guid];const e=new AIA(A);return e[rG]=A.guid,this._syncers[e[rG]]=e,e}removeSyncer(A){delete this._syncers[A[rG]]}}const TN=new $gA;class AIA{constructor(A){r(this,"comp");r(this,"hasChanges",!1);r(this,"changedProperties",{});r(this,"data",{});r(this,"_boundEvent");r(this,"_handleReceivingMethod");r(this,"_isReceiving",!1);r(this,"_isInit",!1);this.comp=A}get networkingKey(){return this.comp.guid}init(A){if(this._isInit)return;this._isInit=!0,this.comp=A,this._boundEvent=this.onHandleSending.bind(this),this.comp.context.post_render_callbacks.push(this._boundEvent),this._handleReceivingMethod=this.onHandleReceiving.bind(this),this.comp.context.connection.beginListen(this.networkingKey,this._handleReceivingMethod);const e=this.comp.context.connection.tryGetState(this.comp.guid);e&&this.onHandleReceiving(e)}destroy(){this._isInit&&(this._boundEvent&&this.comp.context.post_render_callbacks.splice(this.comp.context.post_render_callbacks.indexOf(this._boundEvent),1),this._handleReceivingMethod&&this.comp.context.connection.stopListen(this.networkingKey,this._handleReceivingMethod),this.comp=null,this._isInit=!1)}notifyChanged(A,e){this._isReceiving||(cB&&console.log("Property changed: "+A,e),this.hasChanges=!0,this.changedProperties[A]=e)}onHandleSending(){if(!this.hasChanges)return;this.hasChanges=!1;const A=this.comp.context.connection;if(!A||!A.isConnected){for(const e in this.changedProperties)delete this.changedProperties[e];return}for(const e in this.data)delete this.data[e];this.data.guid=this.comp.guid;for(const e in this.changedProperties){const t=this.changedProperties[e];delete this.changedProperties[e],this.data[e]=t}A.send(this.networkingKey,this.data)}onHandleReceiving(A){if(cB&&console.log("RECEIVE",this.comp.name,this.comp.guid,A),!this._isInit||!this.comp)return;const e=A.guid;if(!(e&&e!==this.comp.guid)){cB&&console.log("RECEIVED",this.comp.name,this.comp.guid,A);try{this._isReceiving=!0;for(const t in A){if(t==="guid")continue;const i=A[t];this.comp[t]=i,cB&&console.log("SET",t,i)}}catch(t){console.error(t)}finally{this._isReceiving=!1}}}}function eIA(g,A){let e=A!==g;return!e&&g&&A&&(Array.isArray(g)&&Array.isArray(A)||typeof g=="object"&&typeof A=="object")&&(e=!0),e}const Yh=Symbol("AutoSyncHandler");function tIA(g){if(g[Yh])return g[Yh];const A=TN.getOrCreateSyncer(g);return A==null||A.init(g),g[Yh]=A,A}function iIA(g){const A=g[Yh];A&&(TN.removeSyncer(A),A.destroy(),delete g[Yh])}const HN=function(g){return function(A,e){var a;let t="";typeof e=="string"?t=e:t=e.name;let i=null,I;typeof g=="string"?I=A[g]:typeof g=="function"&&(I=g);const o=A,s=o.__internalAwake;if(typeof s!="function"){(cB||he())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+((a=A==null?void 0:A.constructor)==null?void 0:a.name)+'" is not supported',A);return}cB&&console.log(t);const n=Symbol(t);o.__internalAwake=function(){if(this[n]!==void 0)return;this[n]=this[t],i=TN.getOrCreateSyncer(this);const B=Object.getOwnPropertyDescriptor(this,t);if((B==null?void 0:B.set)===void 0){let Q=!1;Object.defineProperty(this,t,{set:function(E){var d;const c=this[n];if(this[n]=E,Q){he()&&console.warn("Recursive call detected",t);return}Q=!0;try{const l=eIA(E,c);cB&&console.log("SyncField assignment",t,"changed?",l,E),l&&(I==null?void 0:I.call(this,E,c))!==!1&&((d=tIA(this))==null||d.notifyChanged(t,E))}finally{Q=!1}},get:function(){return this[n]},configurable:!0,enumerable:!0})}i==null||i.init(this),s.call(this)};const C=o.__internalDestroy;o.__internalDestroy=function(){iIA(this),C.call(this)}}};var gIA=Object.defineProperty,IIA=Object.getOwnPropertyDescriptor,mS=(g,A,e,t)=>{for(var i=t>1?void 0:t?IIA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&gIA(A,e,i),i};const ho=IA("debugplayersync");class Lc extends RA{constructor(){super(...arguments);r(this,"autoSync",!0);r(this,"asset");r(this,"onPlayerSpawned");r(this,"_localInstance");r(this,"onJoinedRoom",()=>{ho&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()})}awake(){this.watchTabVisible(),this.onPlayerSpawned||(this.onPlayerSpawned=new rg)}onEnable(){this.context.connection.beginListen(It.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(It.JoinedRoom,this.onJoinedRoom),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(It.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(It.JoinedRoom,this.onJoinedRoom)}async getInstance(){var t,i,I,o,s,n;if(this._localInstance)return this._localInstance;if(ho&&console.log("PlayerSync.createInstance",(t=this.asset)==null?void 0:t.uri),!((i=this.asset)!=null&&i.asset)&&!((I=this.asset)!=null&&I.uri))return console.error('PlayerSync: can not create an instance because "asset" is not set!'),null;this._localInstance=(o=this.asset)==null?void 0:o.instantiateSynced({parent:this.gameObject},!0);const e=await this._localInstance;if(e){const C=aA.getComponent(e,Is);C?(C.owner=this.context.connection.connectionId,(s=this.onPlayerSpawned)==null||s.invoke(e)):(this._localInstance=void 0,console.error("<strong>Failed finding PlayerState on "+((n=this.asset)==null?void 0:n.uri)+"</strong>: please make sure the asset has a PlayerState component!"),aA.destroySynced(e))}else this._localInstance=void 0,console.warn("PlayerSync: failed instantiating asset!");return this._localInstance}destroyInstance(){var e;(e=this._localInstance)==null||e.then(t=>(ho&&console.log("PlayerSync.destroyInstance",t),aA.destroySynced(t))),this._localInstance=void 0}watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=Is.all.length-1;t>=0;t--){const i=Is.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}}mS([D()],Lc.prototype,"autoSync",2);mS([D(tt)],Lc.prototype,"asset",2);mS([D(rg)],Lc.prototype,"onPlayerSpawned",2);var HO=(g=>(g.OwnerChanged="ownerChanged",g))(HO||{}),jl;const vg=(jl=class extends RA{constructor(){super(...arguments);r(this,"onOwnerChangeEvent",new rg);r(this,"onFirstOwnerChangeEvent",new rg);r(this,"hasOwner",!1);r(this,"owner");r(this,"dontDestroy",!1);r(this,"onUserLeftRoom",A=>{if(A.userId===this.owner){ho&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}})}static get all(){return vg._all}static get local(){return vg._local}static getFor(A){if(A instanceof uA)return aA.getComponentInParent(A,vg);if(A instanceof RA)return aA.getComponentInParent(A.gameObject,vg)}static isLocalPlayer(A){const e=vg.getFor(A);return(e==null?void 0:e.isLocalPlayer)??!1}static addEventListener(A,e){return this._callbacks[A]||(this._callbacks[A]=[]),this._callbacks[A].push(e),e}static removeEventListener(A,e){if(!this._callbacks[A])return;const t=this._callbacks[A].indexOf(e);t>=0&&this._callbacks[A].splice(t,1)}static dispatchEvent(A,e){if(this._callbacks[A])for(const t of this._callbacks[A])t(e)}get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(A,e){var o,s;ho&&console.log("PlayerSync.onOwnerChange",this,"newOwner",A,"oldOwner",e);const t=vg._local.indexOf(this);t>=0&&vg._local.splice(t,1);const i={playerState:this,oldValue:e,newValue:A};if(this.hasOwner||(this.hasOwner=!0,(o=this.onFirstOwnerChangeEvent)==null||o.invoke(i)),(s=this.onOwnerChangeEvent)==null||s.invoke(i),this.owner===this.context.connection.connectionId){vg._local.push(this);const n=new CustomEvent("local-owner-changed",{detail:i});this.dispatchEvent(n)}const I=new CustomEvent("owner-changed",{detail:i});this.dispatchEvent(I),vg.dispatchEvent("ownerChanged",I)}awake(){vg.all.push(this),ho&&console.log("Registered new PlayerState",this.guid,vg.all.length-1,vg.all),this.context.connection.beginListen(It.UserLeftRoom,this.onUserLeftRoom)}async start(){ho&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await Os(300),this.context.connection.userIsInRoom(this.owner)==!1&&(ho&&console.log(`PlayerSync.start → doDestroy "${this.name}" because user "${this.owner}" is not in room anymore...`,"Currently in room:",...this.context.connection.usersInRoom()),this.doDestroy())):this.owner||(ho&&console.warn("PlayerState.start → owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?ho&&console.warn("PlayerState.start → owner is still undefined but dontDestroy is set to true",this.name):(ho&&console.warn(`PlayerState.start → owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):ho&&console.log("PlayerState.start → owner is assigned",this.owner)},2e3))}doDestroy(){ho&&console.log("PlayerSync.doDestroy → syncDestroy",this.name),BS(this.gameObject,this.context.connection)}onDestroy(){if(this.context.connection.stopListen(It.UserLeftRoom,this.onUserLeftRoom),vg.all.splice(vg.all.indexOf(this),1),this.isLocalPlayer){const A=vg._local.indexOf(this);A>=0&&vg._local.splice(A,1)}}},r(jl,"_all",[]),r(jl,"_local",[]),r(jl,"_callbacks",{}),jl);let Is=vg;mS([HN(Is.prototype.onOwnerChange)],Is.prototype,"owner",2);const oIA=IA("debugavatar"),Us=class extends RA{constructor(){super(...arguments);r(this,"connectionId");r(this,"avatar")}static getAvatar(e){return e>=0&&e<Us.instances.length?Us.instances[e]:null}static onAvatarMarkerCreated(e){return Us._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return Us._onAvatarMarkerDestroyed.push(e),e}awake(){Us.instances.push(this),oIA&&console.log(this);for(const e of Us._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){Us.instances.splice(Us.instances.indexOf(this),1);for(const e of Us._onAvatarMarkerDestroyed)e({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}};let sg=Us;r(sg,"instances",[]),r(sg,"_onNewAvatarMarkerAdded",[]),r(sg,"_onAvatarMarkerDestroyed",[]);var sIA=Object.defineProperty,nIA=Object.getOwnPropertyDescriptor,CIA=(g,A,e,t)=>{for(var i=t>1?void 0:t?nIA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&sIA(A,e,i),i};const cE=IA("debugxrflags"),YO=IA("disablexrflags");YO&&console.warn("XRFlags are disabled");var dn=(g=>(g[g.Never=0]="Never",g[g.Browser=1]="Browser",g[g.AR=2]="AR",g[g.VR=4]="VR",g[g.FirstPerson=8]="FirstPerson",g[g.ThirdPerson=16]="ThirdPerson",g[g.All=4294967295]="All",g))(dn||{});const bK=class{constructor(){r(this,"Mask",17)}Has(A){return(this.Mask&A)!==0}Set(A){cE&&console.warn("Set XR flag state to",A),this.Mask=A,Do.Apply()}Enable(A){this.Mask|=A,Do.Apply()}Disable(A){this.Mask&=~A,Do.Apply()}Toggle(A){this.Mask^=A,Do.Apply()}EnableAll(){this.Mask=-1,Do.Apply()}DisableAll(){this.Mask=0,Do.Apply()}};let Hg=bK;r(Hg,"Global",new bK);var Vl;const nC=(Vl=class extends RA{constructor(){super(...arguments);r(this,"visibleIn")}static Apply(){for(const A of this.registry)A.UpdateVisible(Hg.Global)}awake(){nC.registry.push(this)}onEnable(){nC.firstApply?this.UpdateVisible(Hg.Global):(nC.firstApply=!0,nC.Apply())}onDestroy(){const A=nC.registry.indexOf(this);A>=0&&nC.registry.splice(A,1)}get isOn(){return this.gameObject.visible}UpdateVisible(A=null){if(YO)return;let e;const t=A;if(t&&typeof t=="number"&&(console.assert(typeof t=="number","XRFlag.UpdateVisible: state must be a number",t),cE&&console.log(t),nC.buffer.Mask=t,A=nC.buffer),A instanceof Hg?(cE&&console.warn(this.name,"use passed in mask",A.Mask,this.visibleIn),e=A.Has(this.visibleIn)):(cE&&console.log(this.name,"use global mask"),Hg.Global.Has(this.visibleIn)),e!==void 0)if(e)cE&&console.log(this.name,"is visible",this.gameObject.uuid),aA.setActive(this.gameObject,!0);else{if(cE&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},r(Vl,"registry",[]),r(Vl,"firstApply"),r(Vl,"buffer",new Hg),Vl);let Do=nC;CIA([D()],Do.prototype,"visibleIn",2);var aIA=Object.defineProperty,rIA=Object.getOwnPropertyDescriptor,YN=(g,A,e,t)=>{for(var i=t>1?void 0:t?rIA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&aIA(A,e,i),i};const ql=IA("debugwebxr"),_q=new MA().setFromAxisAngle(new w(0,1,0),Math.PI);class oQ extends RA{constructor(){super(...arguments);r(this,"head");r(this,"leftHand");r(this,"rightHand");r(this,"_syncTransforms")}async onEnterXR(e){if(!this.activeAndEnabled)return;ql&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const t=Is.getFor(this);if(t!=null&&t.owner){const i=this.gameObject.addNewComponent(sg);i.avatar=this.gameObject,i.connectionId=t.owner}else this.context.connection.isConnected?console.error("No player state found for avatar",this):t&&!this.context.connection.isConnected&&(t.dontDestroy=!0)}onLeaveXR(e){const t=this.gameObject.getComponent(sg);t&&t.destroy()}onUpdateXR(e){var n,C;if(!this.activeAndEnabled)return;const t=Is.isLocalPlayer(this);if(!t)return;const i=e.xr;if(i.rig&&i.rig.gameObject!==this.gameObject.parent&&(this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),this.gameObject.scale.set(1,1,1),i.rig.gameObject.add(this.gameObject)),this._syncTransforms&&t)for(const a of this._syncTransforms)a.fastMode=!0,a.isOwned()||a.requestOwnership();if(this.head&&this.context.mainCamera){const a=this.head.asset;if(a.position.copy(this.context.mainCamera.position),a.quaternion.copy(this.context.mainCamera.quaternion),a.quaternion.x*=-1,this.context.time.frameCount%10===0){const B=aA.getComponentsInChildren(this.head.asset,Do);for(const Q of B)Q.enabled=!1,Q.gameObject.visible=!1}}const I=e.xr.leftController,o=(n=this.leftHand)==null?void 0:n.asset;I&&o&&(o.position.copy(I.gripPosition),o.quaternion.copy(I.gripQuaternion),o.quaternion.multiply(_q),o.visible=I.isTracking);const s=e.xr.rightController;if(s&&((C=this.rightHand)!=null&&C.asset)){const a=this.rightHand.asset;a.position.copy(s.gripPosition),a.quaternion.copy(s.gripQuaternion),a.quaternion.multiply(_q),a.visible=s.isTracking}}onBeforeRender(){this.context.time.frame%10===0&&this.updateRemoteAvatarVisibility()}updateRemoteAvatarVisibility(){var e,t,i;if(this.context.connection.isConnected){const I=Is.getFor(this);if(I&&I.isLocalPlayer==!1){const o=Se.getXRSync(this.context);if(o&&o.hasState(I.owner)){this.tryFindAvatarObjectsIfMissing();const s=(e=this.leftHand)==null?void 0:e.asset;s&&(s.visible=(o==null?void 0:o.isTracking(I.owner,"left"))??!1);const n=(t=this.rightHand)==null?void 0:t.asset;n&&(n.visible=(o==null?void 0:o.isTracking(I.owner,"right"))??!1)}if((i=this.head)!=null&&i.asset){const s=aA.getComponentsInChildren(this.head.asset,Do);for(const n of s)n.enabled=!1,n.gameObject.visible=!0}}}}tryFindAvatarObjectsIfMissing(){if(!this.head||!this.leftHand||!this.rightHand){const e={head:this.head,leftHand:this.leftHand,rightHand:this.rightHand};W2.tryFindAvatarObjects(this.gameObject,this.sourceId||"",e),e.head&&(this.head=e.head),e.leftHand&&(this.leftHand=e.leftHand),e.rightHand&&(this.rightHand=e.rightHand)}}async prepareAvatar(){if(this.tryFindAvatarObjectsIfMissing(),this.head)this.head instanceof uA&&(this.head=new tt("",this.sourceId,this.head));else{const e=new uA;e.name="Head";const t=Du.createPrimitive(_B.Cube);e.add(t),this.gameObject.add(e),this.head=new tt("",this.sourceId,e),ql&&console.log("Create head",e)}if(this.rightHand)this.rightHand instanceof uA&&(this.rightHand=new tt("",this.sourceId,this.rightHand));else{const e=new uA;e.name="Right Hand",this.gameObject.add(e),this.rightHand=new tt("",this.sourceId,e),ql&&console.log("Create right hand",e)}if(this.leftHand)this.leftHand instanceof uA&&(this.leftHand=new tt("",this.sourceId,this.leftHand));else{const e=new uA;e.name="Left Hand",this.gameObject.add(e),this.leftHand=new tt("",this.sourceId,e),ql&&console.log("Create left hand",e)}await this.loadAvatarObjects(this.head,this.leftHand,this.rightHand),Is.isLocalPlayer(this.gameObject)&&(this._syncTransforms=aA.getComponentsInChildren(this.gameObject,sr))}async loadAvatarObjects(e,t,i){const I=e.loadAssetAsync(),o=t.loadAssetAsync(),s=i.loadAssetAsync(),n=new Array;I&&n.push(I),o&&n.push(o),s&&n.push(s);const C=await au(n);ql&&console.log("Avatar loaded results:",C)}}YN([D(tt)],oQ.prototype,"head",2);YN([D(tt)],oQ.prototype,"leftHand",2);YN([D(tt)],oQ.prototype,"rightHand",2);class Nn{static Add(A,e,t=null){if(e){for(const i of this.Pois)if(i.obj===e)return;this.Pois.push({obj:e,avatar:t}),this.LastChangeTime=A.time.time}}static Remove(A,e){var t;if(e){for(const i of this.Pois)if(i.obj===e){this.Pois.splice(this.Pois.indexOf(i),1),this.LastChangeTime=(A==null?void 0:A.time.time)??((t=ve.Current)==null?void 0:t.time.time);return}}}}r(Nn,"Pois",[]),r(Nn,"LastChangeTime",0);class BIA{constructor(){r(this,"guid");r(this,"position",new w)}}class Jd extends RA{constructor(){super(...arguments);r(this,"target",null);r(this,"avatar",null);r(this,"_model",null);r(this,"_targetModel",new BIA);r(this,"_currentTargetObject",null);r(this,"_lastUpdateTime",0);r(this,"_lookDuration",0);r(this,"_lastPoiChangedTime",0)}set controlledTarget(e){this.target=e;const t=z.get("MoveRandom");if(t&&this.target){const i=aA.getComponent(this.target,t);i&&i.destroy()}}awake(){if(this.avatar=aA.getComponentInParent(this.gameObject,sg),this.avatar){const e=aA.getComponentInParent(this.gameObject,sg);this._model=new FN(this.context.connection,this.guid),e!=null&&e.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",e=>{var t;this.target&&e&&e.guid===((t=this.avatar)==null?void 0:t.guid)&&EI(this.target,e.position)})}update(){var t;if((!this.context.connection.isConnected||(t=this._model)!=null&&t.hasOwnership)&&(Nn.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=Nn.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){const i=_e(this._currentTargetObject);EI(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=Nn.Pois;if(t.length>0){const i=t[Math.floor(Math.random()*t.length)];if(i&&i.obj){if(i.avatar&&i.avatar===this.avatar)return;this._currentTargetObject=i.obj}}}}}const NE=IA("debugnetworkingstreams");var mn=(g=>(g.Connected="peer-user-connected",g.StreamReceived="receive-stream",g.StreamEnded="call-ended",g.Disconnected="peer-user-disconnected",g.UserJoined="user-joined",g))(mn||{});class OO{constructor(A,e){r(this,"type","call-ended");r(this,"userId");r(this,"direction");this.userId=A,this.direction=e}}class PO{constructor(A,e){r(this,"type","receive-stream");r(this,"stream");r(this,"target");this.stream=A,this.target=e}}class QIA{constructor(A,e){r(this,"guid");r(this,"peerId");r(this,"dontSave",!0);this.guid=A.id,this.peerId=e}}var WO=(g=>(g.Incoming="incoming",g.Outgoing="outgoing",g))(WO||{});class EIA extends kg{constructor(e,t,i){super();r(this,"userId");r(this,"direction");r(this,"call");r(this,"_stream",null);r(this,"_isDisposed",!1);this.userId=e,this.call=t,this.direction=i,this._stream=null,t.on("stream",I=>{if(NE&&console.log("Receive video",I.getAudioTracks(),I.getVideoTracks()),this._stream=I,i==="incoming"){const o=new PO(I,this);this.dispatchEvent(o)}}),t.on("close",()=>{this.dispatchEvent(new OO(e,i))})}get stream(){return this._stream}close(){this._isDisposed||(this._isDisposed=!0,this.call.close(),kC(this._stream))}get isOpen(){var e;return((e=this.call.peerConnection)==null?void 0:e.connectionState)==="connected"}get isOpening(){var e;return((e=this.call.peerConnection)==null?void 0:e.connectionState)==="connecting"}get isClosed(){return!this.isOpen}}const bE=class extends kg{constructor(e,t){super();r(this,"id");r(this,"context");r(this,"_peer");r(this,"_incomingCalls",[]);r(this,"_outgoingCalls",[]);r(this,"_enabled",!1);r(this,"_enabledPeer",!1);r(this,"onConnectRoomFn",this.onConnectRoom.bind(this));r(this,"onPeerConnectFn",this.onPeerConnect.bind(this));r(this,"onPeerReceiveCallFn",this.onPeerReceivingCall.bind(this));this.context=e,this.id=t,this.setupPeer(),navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia}static getOrCreate(e,t){if(bE.instances.has(t))return bE.instances.get(t);const i=new bE(e,t);return bE.instances.set(t,i),i}getMyPeerId(){if(this.context.connection.connectionId)return this.getPeerIdFromUserId(this.context.connection.connectionId)}getPeerIdFromUserId(e){return this.id+"-"+e}getUserIdFromPeerId(e){return e.substring(this.id.length+1)}makeCall(e,t){var o;const i={metadata:{userId:this.context.connection.connectionId}},I=(o=this._peer)==null?void 0:o.call(e,t,i);if(I)return this.registerCall(I,"outgoing")}get peer(){return this._peer}enable(){this._enabled||(this._enabled=!0,this.context.connection.beginListen(It.JoinedRoom,this.onConnectRoomFn),this.subscribePeerEvents())}disable(){this._enabled&&(this._enabled=!1,this.context.connection.stopListen(It.JoinedRoom,this.onConnectRoomFn),this.unsubscribePeerEvents())}onConnectRoom(){this.setupPeer()}setupPeer(){if(this.context.connection.connectionId&&!this._enabledPeer){if(this._enabledPeer=!0,!this._peer){const e=this.getMyPeerId();e?this._peer=L2(e):console.error("Failed to setup peerjs because we dont have a connection id",this.context.connection.connectionId)}this._enabled&&this.subscribePeerEvents()}}subscribePeerEvents(){this._peer&&(this._peer.on("open",this.onPeerConnectFn),this._peer.on("call",this.onPeerReceiveCallFn))}unsubscribePeerEvents(){this._peer&&(this._peer.off("open",this.onPeerConnectFn),this._peer.off("call",this.onPeerReceiveCallFn))}onPeerConnect(e){NE&&console.log("Peer connected as",e),this.context.connection.send("peer-user-connected",new QIA(this,e))}onPeerReceivingCall(e){e.answer(),this.registerCall(e,"incoming")}registerCall(e,t){const i=e.metadata;(!i||!i.userId)&&console.error("Missing call metadata",e);const I=i.userId;t==="incoming"&&NE?console.log("Receive call from",e.metadata):NE&&console.log("Make call to",e.metadata);const o=t==="incoming"?this._incomingCalls:this._outgoingCalls,s=new EIA(I,e,t);return o.push(s),e.on("error",n=>{console.error("Call error",n)}),e.on("close",()=>{NE&&console.log("Call ended",e.metadata),e.close();const n=o.indexOf(s);n!==-1&&o.splice(n,1)}),s.addEventListener("call-ended",n=>{this.dispatchEvent(n)}),t==="incoming"&&(s.addEventListener("receive-stream",n=>{this.dispatchEvent(n)}),e.on("stream",()=>{let n=0;const C=setInterval(()=>{const a=n===0;!s.isOpen&&a&&(n+=1,clearInterval(C),s.close())},2e3)})),s}};let OE=bE;r(OE,"instances",new Map);class vu extends kg{constructor(e,t){super();r(this,"context");r(this,"peer");r(this,"_sendingStreams",new Map);r(this,"debug",!1);r(this,"onJoinedRoom",e=>{this.debug&&console.log(`${e.userId} joined room and I'm currently sending ${this._sendingStreams.size} streams`),this._sendingStreams.size>0&&this.updateSendingCalls()});r(this,"onReceiveStream",e=>{this.debug&&console.log("RECEIVE STREAM",e),this.dispatchEvent({type:"receive-stream",target:this,stream:e.stream,userId:e.userId})});r(this,"onCallEnded",e=>{this.dispatchEvent(e)});r(this,"onUserConnected",e=>{if(this.peer.id===e.guid){this.debug&&console.log("USER CONNECTED",e.guid,e);const t=this._sendingStreams.keys().next().value;this.peer.makeCall(e.peerId,t)}});r(this,"onUserLeft",e=>{this.stopCallsToUsersThatAreNotInTheRoomAnymore()});this.context=e,this.peer=t,NE&&(this.debug=!0)}static create(e){const t=OE.getOrCreate(e.context,e.context.connection.connectionId);return new vu(e.context,t)}startSendingStream(e){this._sendingStreams.has(e)?console.warn("Received start sending stream with stream that is already being sent"):(this._sendingStreams.set(e,[]),this.updateSendingCalls())}stopSendingStream(e){if(e){const t=this._sendingStreams.get(e);if(t){this.debug&&console.log("Closing calls",t);for(const i of t)i.close()}this._sendingStreams.delete(e),t&&this.debug&&console.log("Currently sending",this._sendingStreams)}}enable(){this.peer.enable(),this.peer.addEventListener("receive-stream",this.onReceiveStream),this.peer.addEventListener("call-ended",this.onCallEnded),this.context.connection.beginListen("peer-user-connected",this.onUserConnected),this.context.connection.beginListen(It.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(It.UserJoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(It.UserLeftRoom,this.onUserLeft)}disable(){this.peer.disable(),this.peer.removeEventListener("receive-stream",this.onReceiveStream),this.peer.removeEventListener("call-ended",this.onCallEnded),this.context.connection.stopListen("peer-user-connected",this.onUserConnected),this.context.connection.stopListen(It.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(It.UserJoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(It.UserLeftRoom,this.onUserLeft)}updateSendingCalls(){var i;let e=!1;const t=this.context.connection.connectionId;for(const I of this._sendingStreams.keys()){const o=this._sendingStreams.get(I)||[];for(const s of this.context.connection.usersInRoom()){if(s===t)continue;const n=o.find(C=>C.userId===s);if(!n||((i=n.stream)==null?void 0:i.active)===!1){this.debug&&console.log("Starting call to",s,t);const C=this.peer.makeCall(this.peer.getPeerIdFromUserId(s),I);C&&(e=!0,o.push(C))}}this._sendingStreams.set(I,o)}this.stopCallsToUsersThatAreNotInTheRoomAnymore(),e&&this.debug&&console.log("Currently sending",this._sendingStreams)}stopCallsToUsersThatAreNotInTheRoomAnymore(){for(const e of this._sendingStreams.keys()){const t=this._sendingStreams.get(e);if(t)for(let i=t.length-1;i>=0;i--){const I=t[i];this.context.connection.userIsInRoom(I.userId)||(I.close(),t.splice(i,1))}}}}function kC(g){if(g&&g instanceof MediaStream)for(const A of g.getTracks())A.stop()}var cIA=Object.defineProperty,lIA=Object.getOwnPropertyDescriptor,ZO=(g,A,e,t)=>{for(var i=t>1?void 0:t?lIA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&cIA(A,e,i),i};const hIA="noVoip",dIA=IA("debugvoip");class sQ extends RA{constructor(){super(...arguments);r(this,"autoConnect",!1);r(this,"runInBackground",!0);r(this,"debug",!1);r(this,"_net");r(this,"_outputStream",null);r(this,"onJoinedRoom",async()=>{await Os(300),this.autoConnect&&!this.isSending&&this.connect()});r(this,"_incomingStreams",new Map);r(this,"onReceiveStream",e=>{const t=e.target.userId,i=e.stream,I=this._incomingStreams.get(t);if(I)I.srcObject=i,I.setAttribute("autoplay","true");else{const o=new Audio;this._incomingStreams.set(t,o),o.setAttribute("autoplay","true"),o.srcObject=i}});r(this,"onStreamEnded",e=>{const t=this._incomingStreams.get(e.userId);kC(t==null?void 0:t.srcObject),this._incomingStreams.delete(e.userId)});r(this,"onEnabledChanged",()=>{for(const e of this._incomingStreams){const t=e[1];t.muted=!this.enabled}});r(this,"onVisibilityChanged",()=>{if(this.runInBackground)return;const t=!(document.visibilityState==="visible");this.setMuted(t);for(const i of this._incomingStreams){const I=i[1];I.muted=t}})}awake(){dIA&&(this.debug=!0),this.debug&&window.addEventListener("keydown",async e=>{e.key==="v"&&(console.log("MUTE?",!this.isMuted),this.setMuted(!this.isMuted))})}onEnable(){this._net||(this._net=vu.create(this)),this._net.addEventListener(mn.StreamReceived,this.onReceiveStream),this._net.addEventListener(mn.StreamEnded,this.onStreamEnded),this._net.enable(),this.autoConnect&&(this.context.connection.isConnected?this.connect():this.context.connection.beginListen(It.JoinedRoom,this.onJoinedRoom)),this.onEnabledChanged(),window.addEventListener("visibilitychange",this.onVisibilityChanged)}onDisable(){var e;this._net.stopSendingStream(this._outputStream),this._net.removeEventListener(mn.StreamReceived,this.onReceiveStream),this._net.removeEventListener(mn.StreamEnded,this.onStreamEnded),(e=this._net)==null||e.disable(),this.context.connection.stopListen(It.JoinedRoom,this.onJoinedRoom),this.onEnabledChanged(),window.removeEventListener("visibilitychange",this.onVisibilityChanged)}get isSending(){return this._outputStream!=null&&this._outputStream.active}async connect(e){if(this.context.connection.isConnected){if(!await Ok())return console.error("Cannot connect to voice chat - microphone permissions not granted"),!1}else return console.error("Cannot connect to voice chat - not connected to server"),!1;return this._net.stopSendingStream(this._outputStream),kC(this._outputStream),this._outputStream=await this.getAudioStream(e),this._outputStream?(this._net.startSendingStream(this._outputStream),!0):(await Ok()?console.error("VOIP: Could not get audio stream - please make sure to connect an audio device and grant microphone permissions"):XR("Microphone permissions not granted: Please grant microphone permissions to use voice chat"),!1)}disconnect(){this._net.stopSendingStream(this._outputStream),kC(this._outputStream),this._outputStream=null}setMuted(e){var i;const t=(i=this._outputStream)==null?void 0:i.getAudioTracks();if(t)for(const I of t)I.enabled=!e}get isMuted(){var t;if(this._outputStream===null)return!1;const e=(t=this._outputStream)==null?void 0:t.getAudioTracks();if(e){for(const i of e)if(!i.enabled)return!0}return!1}getFrequency(e){return this.unsupported_getfrequency||(this.unsupported_getfrequency=!0,he()&&fi("VOIP: getFrequency is currently not supported"),console.warn("VOIP: getFrequency is currently not supported")),null}async getAudioStream(e){return navigator.mediaDevices.getUserMedia?await navigator.mediaDevices.getUserMedia({audio:e??!0,video:!1}).catch(i=>(console.warn("VOIP failed getting audio stream",i),null)):(console.error("No getDisplayMedia support"),null)}}ZO([D()],sQ.prototype,"autoConnect",2);ZO([D()],sQ.prototype,"runInBackground",2);var uIA=Object.defineProperty,pIA=Object.getOwnPropertyDescriptor,jO=(g,A,e,t)=>{for(var i=t>1?void 0:t?pIA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&uIA(A,e,i),i};const fIA=IA("debugmouth");class qu extends RA{constructor(){super(...arguments);r(this,"idle",[]);r(this,"talking",[]);r(this,"marker",null);r(this,"voip",null);r(this,"lastMouthChangeTime",0);r(this,"mouthChangeLength",0)}awake(){setTimeout(()=>{this.voip=aA.findObjectOfType(sQ,this.context),this.marker||(this.marker=aA.getComponentInParent(this.gameObject,sg))},3e3)}update(){var i;if(!this.voip||this.context.time.frameCount%10!==0)return;let e=((i=this.marker)==null?void 0:i.connectionId)??null;if(!e){fIA&&(e=null);return}const t=this.voip.getFrequency(e)??0;this.updateLips(t)}updateLips(e){if(this.context.time.time-this.lastMouthChangeTime>this.mouthChangeLength){if(this.mouthChangeLength=.05+Math.random()*.1,this.talking&&this.talking.length>0&&e>30){this.lastMouthChangeTime=this.context.time.time;const t=Math.floor(Math.random()*this.talking.length);this.setMouthShapeActive(this.talking,t)}else if(this.idle.length>0&&this.context.time.time-this.lastMouthChangeTime>.5){this.lastMouthChangeTime=this.context.time.time;const t=Math.floor(Math.random()*this.idle.length);this.setMouthShapeActive(this.idle,t)}}}setMouthShapeActive(e,t){if(e){e!=this.idle?this.idle.map(i=>i.visible=!1):this.talking.map(i=>i.visible=!1);for(let i=0;i<e.length;i++){const I=e[i];I&&(I.visible=i===t)}}}}jO([D(uA)],qu.prototype,"idle",2);jO([D(uA)],qu.prototype,"talking",2);class ON extends RA{constructor(){super(...arguments);r(this,"voip",null);r(this,"marker",null);r(this,"_startPosition",null)}awake(){this.voip=aA.findObjectOfType(sQ,this.context),this.marker=aA.getComponentInParent(this.gameObject,sg)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!==0)return;const e=this.marker.connectionId,t=this.voip.getFrequency(e);if(t==null)return;this._startPosition||(this._startPosition=this.gameObject.position.clone());const i=t/100;this.gameObject.position.y=this._startPosition.y+i*.07}}var DIA=Object.defineProperty,wIA=Object.getOwnPropertyDescriptor,GS=(g,A,e,t)=>{for(var i=t>1?void 0:t?wIA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&DIA(A,e,i),i};class nQ extends RA{constructor(){super(...arguments);r(this,"eyes",[]);r(this,"lastBlinkTime",0);r(this,"blinkLength",0);r(this,"eyesOpen",!0);r(this,"state",null)}awake(){this.state=aA.getComponentInParent(this.gameObject,Do)}update(){if(!this.gameObject||!this.gameObject.visible||!this.eyes||!Array.isArray(this.eyes)||this.eyes.length===0)return;if(this.context.time.time-this.lastBlinkTime>this.blinkLength){if(this.lastBlinkTime=this.context.time.time,this.state&&!this.state.isOn||!this.activeAndEnabled)return;if(this.eyesOpen=!this.eyesOpen,this.blinkLength=Math.random(),this.eyesOpen?(this.blinkLength*=3,this.blinkLength+=.5,Math.random()<.1&&(this.blinkLength=.1+Math.random()*.2)):(this.blinkLength*=Math.random()*.2,this.blinkLength+=.1),Math.random()<.1&&(this.blinkLength*=3),this.blinkLength=Math.max(.2,this.blinkLength),this.blinkLength=Math.min(3,this.blinkLength),this.eyes)for(const t of this.eyes)t&&(t.visible=this.eyesOpen)}}}GS([D(uA)],nQ.prototype,"eyes",2);GS([D()],nQ.prototype,"lastBlinkTime",2);GS([D()],nQ.prototype,"blinkLength",2);GS([D()],nQ.prototype,"eyesOpen",2);var yIA=Object.defineProperty,SIA=Object.getOwnPropertyDescriptor,PN=(g,A,e,t)=>{for(var i=t>1?void 0:t?SIA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&yIA(A,e,i),i},zG;const VO=(zG=class extends RA{constructor(){super(...arguments);r(this,"head",null);r(this,"eyes",null);r(this,"target",null);r(this,"brain",null);r(this,"vec",new w);r(this,"currentTargetPoint",new w)}awake(){this.brain||(this.brain=aA.getComponentInParent(this.gameObject,Jd)),this.brain||(console.log("No look at brain found, adding it now"),this.brain=aA.addNewComponent(this.gameObject,Jd)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}update(){const A=this.target;if(A&&this.head){const e=this.eyes;if(e){const t=_e(A);this.currentTargetPoint.lerp(t,this.context.time.deltaTime/.1);const i=_e(this.head),I=this.vec.copy(this.currentTargetPoint).sub(i).normalize();if(I.length()<.1)return;const o=VO.forward;if(o.set(0,0,1),o.applyQuaternion(Jt(this.head)),o.dot(I)>.45)for(let n=0;n<e.length;n++)e[n].lookAt(this.currentTargetPoint)}}}},r(zG,"forward",new w(0,0,1)),zG);let _c=VO;PN([D(uA)],_c.prototype,"head",2);PN([D(uA)],_c.prototype,"eyes",2);PN([D(uA)],_c.prototype,"target",2);const xl=IA("debugavatar");class kS{constructor(A,e,t,i){r(this,"root");r(this,"head");r(this,"leftHand");r(this,"rigthHand");var I;this.root=A,this.head=e,this.leftHand=t,this.rigthHand=i,(I=this.root)==null||I.traverse(o=>o.layers.set(2))}get isValid(){return this.head!==null&&this.head!==void 0}}class WN{constructor(){r(this,"avatarRegistryUrl",null)}async getOrCreateNewAvatarInstance(A,e){if(!e)return console.error("Can not create avatar: failed to provide id or root object"),null;let t=null;if(typeof e=="string"){if(t=await this.loadAvatar(A,e),!t){const I=new zs;t=aA.instantiate(tc(e,A.scene),I)}}else t=e;if(!t)return null;const i=this.findAvatar(t);return i.isValid?(xl&&console.log("[Custom Avatar] valid config",e,xl?i:""),i):(console.warn("[Custom Avatar] config isn't valid",e,xl?i:""),null)}async loadAvatar(A,e){if(console.assert(e!=null&&typeof e=="string","Avatar id must not be null"),e.length<=0||!e)return null;if(xl&&console.log("[Custom Avatar] "+e+", loading..."),e.endsWith(".glb")||(e+=".glb"),this.avatarRegistryUrl===null){const i=await fetch("./"+e);let I=null;if(i.ok){const s=await i.blob();s&&(I=await s.arrayBuffer())}if(!I&&(I=await fN(e,e,0,"no url here go away",!0),!I))return null;const o=await Ys().parseSync(A,I,null,0);return(o==null?void 0:o.scene)??null}const t=new Mc;return lu(t,A),new Promise((i,I)=>{const o=this.avatarRegistryUrl+"/"+e;t.load(o,async s=>{await Ys().createBuiltinComponents(A,o,s,null,void 0),i(s.scene)},s=>{xl&&console.log("[Custom Avatar] "+s.loaded/s.total*100+"% loaded of "+s.total/1024+"kB")},s=>{console.error("[Custom Avatar] Error when loading: "+s),i(null)})})}cacheModel(A,e){}findAvatar(A){const e=A;let t=e;t.children.length==1&&(t=A.children[0]);let i=this.findAvatarPart(t,["head"]);const I=this.findAvatarPart(t,["left","hand"]),o=this.findAvatarPart(t,["right","hand"]);if(!i){i=e;const n=new w;new wt().setFromObject(i).getSize(n);const C=Math.max(n.x,n.y,n.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+C+" meters! Should be < 0.3m"),C>.3&&i.scale.multiplyScalar(1/C*.3)}return new kS(e,i,I,o)}findAvatarPart(A,e){const t=A.name.toLowerCase();let i=!0;for(const I of e){if(!i)break;t.indexOf(I)===-1&&(i=!1)}if(i)return A;if(A.children)for(const I of A.children){const o=this.findAvatarPart(I,e);if(o)return o}return null}handleCustomAvatarErrors(A){if(!A.ok)throw Error(A.statusText);return A}}var mIA=Object.defineProperty,GIA=Object.getOwnPropertyDescriptor,ZN=(g,A,e,t)=>{for(var i=t>1?void 0:t?GIA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&mIA(A,e,i),i};class Tc extends RA{constructor(){super(...arguments);r(this,"length",1);r(this,"depthTest",!0);r(this,"isGizmo",!0);r(this,"_axes",null)}onEnable(){if(this.isGizmo&&!uu)return;this._axes||(this._axes=new Cs(this.length)),this._axes.layers.disableAll(),this._axes.layers.set(this.layer),this.gameObject.add(this._axes);const e=this._axes.material;e&&e.depthTest!==void 0&&(e.depthTest=this.depthTest)}onDisable(){this._axes&&this.gameObject.remove(this._axes)}}ZN([D()],Tc.prototype,"length",2);ZN([D()],Tc.prototype,"depthTest",2);ZN([D()],Tc.prototype,"isGizmo",2);class jN extends RA{constructor(){super(...arguments);r(this,"from");r(this,"to");r(this,"hint");r(this,"desiredDistance",1)}onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;const e=_e(this.to).clone(),t=_e(this.from).clone(),i=e.distanceTo(t),I=e.clone();I.sub(t);const o=t.clone();o.add(e),o.multiplyScalar(.5);const s=_e(this.hint).clone();s.sub(o);const n=new w;n.crossVectors(s,I),n.crossVectors(I,n),n.normalize();const C=i*.5,a=Math.max(this.desiredDistance,C),B=Math.sqrt(a*a-C*C),Q=n.clone();Q.multiplyScalar(B),Q.add(o),EI(this.gameObject,Q);const E=o.clone();E.sub(n),this.gameObject.lookAt(E)}}const kIA=IA("debugusdzbehaviours");class MS{constructor(){r(this,"behaviours",[]);r(this,"behaviourComponents",[]);r(this,"behaviourComponentsCopy",[])}get extensionName(){return"Behaviour"}addBehavior(A){this.behaviours.push(A)}onBeforeBuildDocument(A){const e=[];return A.root.traverse(t=>{aA.foreachComponent(t,i=>{var o;const I=i;if(typeof I.createBehaviours=="function"||typeof I.beforeCreateDocument=="function"||typeof I.afterCreateDocument=="function"||typeof I.afterSerialize=="function"){this.behaviourComponents.push(I);const s=(o=I.beforeCreateDocument)==null?void 0:o.call(I,this,A);s instanceof Promise&&e.push(s)}},!1)}),Promise.all(e)}onExportObject(A,e,t){var i;for(const I of this.behaviourComponents)(i=I.createBehaviours)==null||i.call(I,this,e,t)}onAfterBuildDocument(A){for(const e of this.behaviourComponents)typeof e.afterCreateDocument=="function"&&e.afterCreateDocument(this,A);this.behaviourComponentsCopy=this.behaviourComponents.slice(),this.behaviourComponents.length=0}onAfterHierarchy(A,e){var t;if((t=this.behaviours)!=null&&t.length){e.beginBlock('def Scope "Behaviors"');for(const i of this.behaviours)i.writeTo(this,A.document,e);e.closeBlock()}}async onAfterSerialize(A){kIA&&console.log("onAfterSerialize behaviours",this.behaviourComponentsCopy);for(const e of this.behaviourComponentsCopy)typeof e.afterSerialize=="function"&&(e.afterSerialize.constructor.name==="AsyncFunction"?await e.afterSerialize(this,A):e.afterSerialize(this,A));this.behaviours.length=0}}var MIA=Object.defineProperty,UIA=Object.getOwnPropertyDescriptor,VN=(g,A,e,t)=>{for(var i=t>1?void 0:t?UIA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&MIA(A,e,i),i},XG;const zO=(XG=class extends hI{constructor(){super(...arguments);r(this,"threshold");r(this,"intensity");r(this,"scatter");r(this,"selectiveBloom")}get typeName(){return"Bloom"}init(){this.threshold.defaultValue=1,this.intensity.defaultValue=0,this.scatter.defaultValue=.2,this.selectiveBloom?(this.threshold.valueProcessor=A=>A,this.intensity.valueProcessor=A=>A,this.scatter.valueProcessor=A=>1*Math.PI*(1-A)):(this.threshold.valueProcessor=A=>A,this.intensity.valueProcessor=A=>A,this.scatter.valueProcessor=A=>100*(1-A))}onCreateEffect(){let A;if(this.selectiveBloom==null&&(this.selectiveBloom=zO.useSelectiveBloom),this.selectiveBloom){const e=A=new UY(this.context.scene,this.context.mainCamera,{blendFunction:We.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,intensity:this.intensity.value});e.inverted=!0}else A=new hN({blendFunction:We.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,intensity:this.intensity.value});return this.intensity.onValueChanged=e=>{A.intensity=e},this.threshold.onValueChanged=e=>{A.luminanceMaterial.threshold=e},this.scatter.onValueChanged=e=>{A.luminancePass.enabled=!0,A.luminanceMaterial.smoothing=e},A}},r(XG,"useSelectiveBloom",!1),XG);let CQ=zO;VN([D(qe)],CQ.prototype,"threshold",2);VN([D(qe)],CQ.prototype,"intensity",2);VN([D(qe)],CQ.prototype,"scatter",2);ds("Bloom",CQ);const lE="NEEDLE_progressive",nI=IA("debugprogressive"),BG=Symbol("needle-progressive-texture"),PE=new Map;if(nI){let g=function(){A+=1,Ci(`Toggle LOD level: ${A}<br/>Registered objects: ${PE.size}`),console.log("Toggle LOD level",A,PE);const t=st.Current;PE.forEach((i,I)=>{for(const o of i.keys){const s=I[o];if(s instanceof ue){const n=Kt.getMeshLODInformation(s),C=n?Math.min(A,n.lods.length):0;I["DEBUG:LOD"]=C,Kt.assignMeshLOD(t,i.sourceId,I,C),n&&(e=Math.max(e,n.lods.length-1))}else if(I instanceof be){Kt.assignTextureLOD(t,i.sourceId,I,A);break}}}),A>=e&&(A=-1)},A=-1,e=2;window.addEventListener("keyup",t=>{t.key==="p"&&g()}),st.registerCallback(di.ContextCreated,t=>{const i=document.createElement("button");i.innerText="Toggle Progressive",i.onclick=g,t.context.menu.appendChild(i)})}function Tq(g,A,e){var i;if(!nI)return;PE.has(g)||PE.set(g,{keys:[],sourceId:e});const t=PE.get(g);((i=t==null?void 0:t.keys)==null?void 0:i.includes(A))==!1&&t.keys.push(A)}const VI=class{constructor(A,e,t){r(this,"parser");r(this,"sourceId");r(this,"context");this.parser=A,this.sourceId=e,this.context=t}get name(){return lE}static getMeshLODInformation(A){const e=this.getAssignedLODInformation(A);return e!=null&&e.key?this.lodInfos.get(e.key):null}static hasLODLevelAvailable(A,e){var I;if(A instanceof be){for(const o of Object.keys(A)){const s=A[o];if(s instanceof fe&&this.hasLODLevelAvailable(s,e))return!0}return!1}else if(A instanceof bI){for(const o of A.children)if(o instanceof lA&&this.hasLODLevelAvailable(o,e))return!0}let t,i;if(A instanceof lA?t=A.geometry:A instanceof fe&&(t=A),t&&(I=t==null?void 0:t.userData)!=null&&I.LODS){const o=t.userData.LODS;if(i=this.lodInfos.get(o.key),e===void 0)return i!=null;if(i)return Array.isArray(i.lods)?e<i.lods.length:e===0}return!1}static assignMeshLOD(A,e,t,i){if(!t)return Promise.resolve(null);if(t instanceof lA){const I=t.geometry,o=this.getAssignedLODInformation(I);if(!o)return Promise.resolve(null);Md(t)||RD(t,t.geometry);const s=this.onProgressiveLoadStart(A,e,t,null);return t["LOD:requested level"]=i,VI.getOrLoadLOD(A,e,I,i).then(n=>{if(t["LOD:requested level"]===i){if(delete t["LOD:requested level"],Array.isArray(n)){const C=o.index||0;n=n[C]}n&&I!=n&&(nI=="verbose"&&console.log("Progressive Mesh "+t.name+" loaded",I,"→",n,`
5509
- `,t),n instanceof ue&&(t.geometry=n,nI&&Tq(t,"geometry",e)))}return this.onProgressiveLoadEnd(s),n}).catch(n=>(this.onProgressiveLoadEnd(s),console.error("Error loading mesh LOD",t,n),null))}else nI&&console.error("Invalid call to assignMeshLOD: Request mesh LOD but the object is not a mesh",t);return Promise.resolve(null)}static assignTextureLOD(A,e,t,i=0){if(!t)return Promise.resolve(null);if(t instanceof be){const I=t,o=[],s=new Array;if(I instanceof ou)for(const n of Object.keys(I.uniforms)){const C=I.uniforms[n].value;if(C instanceof fe){const a=this.assignTextureLODForSlot(A,e,C,i,I,n);o.push(a),s.push(n)}}else for(const n of Object.keys(I)){const C=I[n];if(C instanceof fe){const a=this.assignTextureLODForSlot(A,e,C,i,I,n);o.push(a),s.push(n)}}return au(o).then(n=>{const C=new Array;for(let a=0;a<n.results.length;a++){const B=n.results[a],Q=s[a];B instanceof fe?C.push({material:I,slot:Q,texture:B,level:i}):C.push({material:I,slot:Q,texture:null,level:i})}return C})}if(t instanceof fe){const I=t;return this.assignTextureLODForSlot(A,e,I,i,null,null)}return Promise.resolve(null)}static assignTextureLODForSlot(A,e,t,i,I,o){if((t==null?void 0:t.isTexture)!==!0)return Promise.resolve(null);const s=this.onProgressiveLoadStart(A,e,I,o);return VI.getOrLoadLOD(A,e,t,i).then(n=>Array.isArray(n)?null:(n==null?void 0:n.isTexture)===!0?(n!=t&&(I&&o&&(I[o]=n),nI&&o&&I&&Tq(I,o,e)),this.onProgressiveLoadEnd(s),n):(nI=="verbose"&&console.warn("No LOD found for",t,i),this.onProgressiveLoadEnd(s),null)).catch(n=>(this.onProgressiveLoadEnd(s),console.error("Error loading LOD",t,n),null))}afterRoot(A){var t,i;nI&&console.log("AFTER",this.sourceId,A),(t=this.parser.json.textures)==null||t.forEach((I,o)=>{if(I!=null&&I.extensions){const s=I==null?void 0:I.extensions[lE];if(s){for(const n of this.parser.associations.keys())if(n instanceof fe&&this.parser.associations.get(n).textures===o){const a=n;nI&&console.log("> Progressive: register texture",o,a.name,a.uuid,a,s),a.source&&(a.source[BG]=s);const B=a.uuid;VI.assignLODInformation(a,B,0,0,void 0),VI.lodInfos.set(B,s),VI.lowresCache.set(B,a)}}}});const e=(I,o,s,n,C)=>{const a=o.geometry;a["needle:raycast-mesh"]=!0,a&&!Md(o)&&(nI&&console.log("Set raycast mesh",o.name,o.uuid,a),RD(o,a),iS(a,!0).forEach(B=>{B instanceof lA&&RD(B,a)})),a.userData||(a.userData={}),VI.assignLODInformation(a,I,s,n,C.density),VI.lodInfos.set(I,C)};return(i=this.parser.json.meshes)==null||i.forEach((I,o)=>{if(I!=null&&I.extensions){const s=I==null?void 0:I.extensions[lE];if(s&&s.lods){for(const n of this.parser.associations.keys())if(n instanceof lA){const C=this.parser.associations.get(n);if(C.meshes===o){const a=n;nI&&console.log("> Progressive: register mesh",o,a.name,s,a.uuid,a);const B=a.uuid,Q=s.lods.length;if(a instanceof lA){e(B,a,Q,C.primitives,s);let E=VI.lowresCache.get(B);E?E.push(a.geometry):E=[a.geometry],VI.lowresCache.set(B,E)}}}}}}),null}static async getOrLoadLOD(A,e,t,i){var C,a,B;const I=nI=="verbose",o=t.userData.LODS;if(!o)return null;const s=o==null?void 0:o.key;let n;if(t instanceof fe&&t.source&&t.source[BG]&&(n=t.source[BG]),n||(n=VI.lodInfos.get(s)),n){if(i>0){let c=!1;const d=Array.isArray(n.lods);if(d&&i>=n.lods.length?c=!0:d||(c=!0),c)return this.lowresCache.get(s)}const Q=Array.isArray(n.lods)?n.lods[i].path:n.lods;if(!Q)return nI&&!n["missing:uri"]&&(n["missing:uri"]=!0,console.warn("Missing uri for progressive asset for LOD "+i,n)),null;const E=PC(e,Q);if(E.endsWith(".glb")||E.endsWith(".gltf")){if(!n.guid)return console.warn("missing pointer for glb/gltf texture",n),null;const c=E+"_"+n.guid,d=this.previouslyLoaded.get(c);if(d!==void 0){I&&console.log(`LOD ${i} was already loading/loaded: ${c}`);let u=await d.catch(k=>(console.error(`Error loading LOD ${i} from ${E}
5510
- `,k),null)),f=!1;if(u==null||(u instanceof fe&&t instanceof fe?(C=u.image)!=null&&C.data||(a=u.source)!=null&&a.data?u=this.copySettings(t,u):(f=!0,this.previouslyLoaded.delete(c)):u instanceof ue&&t instanceof ue&&((B=u.attributes.position)!=null&&B.array||(f=!0,this.previouslyLoaded.delete(c)))),!f)return u}const l=n,h=new Promise(async(u,f)=>{const k=new Mc;lu(k,A),nI&&(await Os(Math.random()*1e3),I&&console.warn("Start loading (delayed) "+E,l.guid));const G=await k.loadAsync(E).catch(N=>(console.error(`Error loading LOD ${i} from ${E}
5509
+ `,t),n instanceof ue&&(t.geometry=n,nI&&Tq(t,"geometry",e)))}return this.onProgressiveLoadEnd(s),n}).catch(n=>(this.onProgressiveLoadEnd(s),console.error("Error loading mesh LOD",t,n),null))}else nI&&console.error("Invalid call to assignMeshLOD: Request mesh LOD but the object is not a mesh",t);return Promise.resolve(null)}static assignTextureLOD(A,e,t,i=0){if(!t)return Promise.resolve(null);if(t instanceof be){const I=t,o=[],s=new Array;if(I instanceof ou)for(const n of Object.keys(I.uniforms)){const C=I.uniforms[n].value;if(C instanceof fe){const a=this.assignTextureLODForSlot(A,e,C,i,I,n);o.push(a),s.push(n)}}else for(const n of Object.keys(I)){const C=I[n];if(C instanceof fe){const a=this.assignTextureLODForSlot(A,e,C,i,I,n);o.push(a),s.push(n)}}return au(o).then(n=>{const C=new Array;for(let a=0;a<n.results.length;a++){const B=n.results[a],Q=s[a];B instanceof fe?C.push({material:I,slot:Q,texture:B,level:i}):C.push({material:I,slot:Q,texture:null,level:i})}return C})}if(t instanceof fe){const I=t;return this.assignTextureLODForSlot(A,e,I,i,null,null)}return Promise.resolve(null)}static assignTextureLODForSlot(A,e,t,i,I,o){if((t==null?void 0:t.isTexture)!==!0)return Promise.resolve(null);const s=this.onProgressiveLoadStart(A,e,I,o);return VI.getOrLoadLOD(A,e,t,i).then(n=>Array.isArray(n)?null:(n==null?void 0:n.isTexture)===!0?(n!=t&&(I&&o&&(I[o]=n),nI&&o&&I&&Tq(I,o,e)),this.onProgressiveLoadEnd(s),n):(nI=="verbose"&&console.warn("No LOD found for",t,i),this.onProgressiveLoadEnd(s),null)).catch(n=>(this.onProgressiveLoadEnd(s),console.error("Error loading LOD",t,n),null))}afterRoot(A){var t,i;nI&&console.log("AFTER",this.sourceId,A),(t=this.parser.json.textures)==null||t.forEach((I,o)=>{if(I!=null&&I.extensions){const s=I==null?void 0:I.extensions[lE];if(s){for(const n of this.parser.associations.keys())if(n instanceof fe&&this.parser.associations.get(n).textures===o){const a=n;nI&&console.log("> Progressive: register texture",o,a.name,a.uuid,a,s),a.source&&(a.source[BG]=s);const B=a.uuid;VI.assignLODInformation(a,B,0,0,void 0),VI.lodInfos.set(B,s),VI.lowresCache.set(B,a)}}}});const e=(I,o,s,n,C)=>{const a=o.geometry;a["needle:raycast-mesh"]=!0,a&&!Md(o)&&(nI&&console.log("Set raycast mesh",o.name,o.uuid,a),RD(o,a),iS(a,!0).forEach(B=>{B instanceof lA&&RD(B,a)})),a.userData||(a.userData={}),VI.assignLODInformation(a,I,s,n,C.density),VI.lodInfos.set(I,C)};return(i=this.parser.json.meshes)==null||i.forEach((I,o)=>{if(I!=null&&I.extensions){const s=I==null?void 0:I.extensions[lE];if(s&&s.lods){for(const n of this.parser.associations.keys())if(n instanceof lA){const C=this.parser.associations.get(n);if(C.meshes===o){const a=n;nI&&console.log("> Progressive: register mesh",o,a.name,s,a.uuid,a);const B=a.uuid,Q=s.lods.length;if(a instanceof lA){e(B,a,Q,C.primitives,s);let E=VI.lowresCache.get(B);E?E.push(a.geometry):E=[a.geometry],VI.lowresCache.set(B,E)}}}}}}),null}static async getOrLoadLOD(A,e,t,i){var C,a,B;const I=nI=="verbose",o=t.userData.LODS;if(!o)return null;const s=o==null?void 0:o.key;let n;if(t instanceof fe&&t.source&&t.source[BG]&&(n=t.source[BG]),n||(n=VI.lodInfos.get(s)),n){if(i>0){let c=!1;const d=Array.isArray(n.lods);if(d&&i>=n.lods.length?c=!0:d||(c=!0),c)return this.lowresCache.get(s)}const Q=Array.isArray(n.lods)?n.lods[i].path:n.lods;if(!Q)return nI&&!n["missing:uri"]&&(n["missing:uri"]=!0,console.warn("Missing uri for progressive asset for LOD "+i,n)),null;let E=PC(e,Q);if(E.endsWith(".glb")||E.endsWith(".gltf")){if(!n.guid)return console.warn("missing pointer for glb/gltf texture",n),null;const c=E+"_"+n.guid,d=this.previouslyLoaded.get(c);if(d!==void 0){I&&console.log(`LOD ${i} was already loading/loaded: ${c}`);let u=await d.catch(k=>(console.error(`Error loading LOD ${i} from ${E}
5510
+ `,k),null)),f=!1;if(u==null||(u instanceof fe&&t instanceof fe?(C=u.image)!=null&&C.data||(a=u.source)!=null&&a.data?u=this.copySettings(t,u):(f=!0,this.previouslyLoaded.delete(c)):u instanceof ue&&t instanceof ue&&((B=u.attributes.position)!=null&&B.array||(f=!0,this.previouslyLoaded.delete(c)))),!f)return u}const l=n,h=new Promise(async(u,f)=>{const k=new Mc;if(lu(k,A),n&&Array.isArray(n.lods)){const N=n.lods[i];N.hash&&(E+="?v="+N.hash)}nI&&(await Os(Math.random()*1e3),I&&console.warn("Start loading (delayed) "+E,l.guid));const G=await k.loadAsync(E).catch(N=>(console.error(`Error loading LOD ${i} from ${E}
5511
5511
  `,N),null));if(!G)return null;const M=G.parser;I&&console.log("Loading finished "+E,l.guid);let m=0;if(G.parser.json.textures){let N=!1;for(const y of G.parser.json.textures){if(y!=null&&y.extensions){const U=y==null?void 0:y.extensions[lE];if(U!=null&&U.guid&&U.guid===l.guid){N=!0;break}}m++}if(N){let y=await M.getDependency("texture",m);return I&&console.log('change "'+t.name+'" → "'+y.name+'"',E,m,y,c),t instanceof fe&&(y=this.copySettings(t,y)),y&&(y.guid=l.guid),u(y)}}if(m=0,G.parser.json.meshes){let N=!1;for(const y of G.parser.json.meshes){if(y!=null&&y.extensions){const U=y==null?void 0:y.extensions[lE];if(U!=null&&U.guid&&U.guid===l.guid){N=!0;break}}m++}if(N){const y=await M.getDependency("mesh",m),U=l;if(I&&console.log(`Loaded Mesh "${y.name}"`,E,m,y,c),y instanceof lA){const H=y.geometry;return VI.assignLODInformation(H,s,i,void 0,U.density),u(H)}else{const H=new Array;for(let x=0;x<y.children.length;x++){const K=y.children[x];if(K instanceof lA){const O=K.geometry;VI.assignLODInformation(O,s,i,x,U.density),H.push(O)}}return u(H)}}}return u(null)});return this.previouslyLoaded.set(c,h),await h}else if(t instanceof fe){I&&console.log("Load texture from uri: "+E);const d=await new Un().loadAsync(E);return d?(d.guid=n.guid,d.flipY=!1,d.needsUpdate=!0,d.colorSpace=t.colorSpace,I&&console.log(n,d)):nI&&console.warn("failed loading",E),d}}else nI&&console.warn(`Can not load LOD ${i}: no LOD info found for "${s}" ${t.name}`,t.type);return null}static assignLODInformation(A,e,t,i,I){if(!A)return;A.userData||(A.userData={});const o=new RIA(e,t,i,I);A.userData.LODS=o,A.userData.LOD=t}static getAssignedLODInformation(A){var e;return((e=A==null?void 0:A.userData)==null?void 0:e.LODS)||null}static copySettings(A,e){const t=this._copiedTextures.get(A);return t||(e=e.clone(),this._copiedTextures.set(A,e),e.offset=A.offset,e.repeat=A.repeat,e.colorSpace=A.colorSpace,e)}static beginListenStart(A,e){this._progressiveEventListeners.has(A)||this._progressiveEventListeners.set(A,new Hq),this._progressiveEventListeners.get(A).start.push(e)}static stopListenStart(A,e){if(!this._progressiveEventListeners.has(A))return;const t=this._progressiveEventListeners.get(A).start,i=t.indexOf(e);i>=0&&t.splice(i,1)}static beginListenEnd(A,e){this._progressiveEventListeners.has(A)||this._progressiveEventListeners.set(A,new Hq),this._progressiveEventListeners.get(A).end.push(e)}static stopListenEnd(A,e){if(!this._progressiveEventListeners.has(A))return;const t=this._progressiveEventListeners.get(A).end,i=t.indexOf(e);i>=0&&t.splice(i,1)}static onProgressiveLoadStart(A,e,t,i){this._currentProgressiveLoadingInfo.has(A)||this._currentProgressiveLoadingInfo.set(A,[]);const I=new XO(A,e,t,i),o=this._currentProgressiveLoadingInfo.get(A),s=this._progressiveEventListeners.get(A);return s&&s.onStart(I),o.push(I),I}static onProgressiveLoadEnd(A){if(!A)return;const e=A.context;if(!this._currentProgressiveLoadingInfo.has(e))return;const t=this._currentProgressiveLoadingInfo.get(e),i=t.indexOf(A);if(i<0)return;t.splice(i,1);const I=this._progressiveEventListeners.get(e);I&&I.onEnd(A)}};let Kt=VI;r(Kt,"lodInfos",new Map),r(Kt,"previouslyLoaded",new Map),r(Kt,"lowresCache",new Map),r(Kt,"_copiedTextures",new Map),r(Kt,"_progressiveEventListeners",new Map),r(Kt,"_currentProgressiveLoadingInfo",new Map);class RIA{constructor(A,e,t,i){r(this,"key");r(this,"level");r(this,"index");r(this,"density");this.key=A,this.level=e,t!=null&&(this.index=t),i!=null&&(this.density=i)}}class XO{constructor(A,e,t,i){r(this,"context");r(this,"source");r(this,"material");r(this,"slot");r(this,"mesh");this.context=A,this.source=e,t instanceof lA?this.mesh=t:this.material=t,this.slot=i}}class Hq{constructor(){r(this,"start",[]);r(this,"end",[])}onStart(A){for(const e of this.start)e(A)}onEnd(A){for(const e of this.end)e(A)}}var NIA=Object.defineProperty,FIA=Object.getOwnPropertyDescriptor,Io=(g,A,e,t)=>{for(var i=t>1?void 0:t?FIA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&NIA(A,e,i),i};class xo extends RA{constructor(){super(...arguments);r(this,"attachedRigidbody",null);r(this,"isTrigger",!1);r(this,"sharedMaterial");r(this,"membership",[0]);r(this,"filter");r(this,"updateProperties",()=>{var e;(e=this.context.physics.engine)==null||e.updateProperties(this)})}get isCollider(){return!0}awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(vt))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(vt))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(vt))}onDisable(){var e;(e=this.context.physics.engine)==null||e.removeBody(this)}get body(){var e;return(e=this.context.physics.engine)==null?void 0:e.getBody(this)}updatePhysicsMaterial(){var e;(e=this.context.physics.engine)==null||e.updatePhysicsMaterial(this)}}Io([D(vt)],xo.prototype,"attachedRigidbody",2);Io([D()],xo.prototype,"isTrigger",2);Io([D()],xo.prototype,"sharedMaterial",2);Io([D()],xo.prototype,"membership",2);Io([D()],xo.prototype,"filter",2);class Hc extends xo{constructor(){super(...arguments);r(this,"radius",.5);r(this,"center",new w(0,0,0))}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addSphereCollider(this),Py(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),dR(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}}Io([AI(),D()],Hc.prototype,"radius",2);Io([D(w)],Hc.prototype,"center",2);class Yc extends xo{constructor(){super(...arguments);r(this,"size",new w(1,1,1));r(this,"center",new w(0,0,0))}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addBoxCollider(this,this.size),Py(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),dR(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}}Io([AI(),D(w)],Yc.prototype,"size",2);Io([D(w)],Yc.prototype,"center",2);class aQ extends xo{constructor(){super(...arguments);r(this,"sharedMesh");r(this,"convex",!1)}onEnable(){var t,i,I;if(super.onEnable(),!this.context.physics.engine)return;(t=this.sharedMesh)!=null&&t.isMesh||this.gameObject instanceof lA&&(this.sharedMesh=this.gameObject);const e=0;if((i=this.sharedMesh)!=null&&i.isMesh)this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex,Vt(this.gameObject)),Kt.assignMeshLOD(this.context,this.sourceId,this.sharedMesh,e).then(o=>{o&&this.activeAndEnabled&&this.context.physics.engine&&this.sharedMesh&&(this.context.physics.engine.removeBody(this),this.sharedMesh.geometry=o,this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex,Vt(this.gameObject)))});else{const o=this.sharedMesh;if(o!=null&&o.isGroup){console.warn(`MeshCollider mesh is a group "${((I=this.sharedMesh)==null?void 0:I.name)||this.gameObject.name}", adding all children as colliders. This is currently not fully supported (colliders can not be removed from world again)`,this);const s=new Array;for(const n in o.children){const C=o.children[n];C.isMesh&&(this.context.physics.engine.addMeshCollider(this,C,this.convex,Vt(this.gameObject)),s.push(Kt.assignMeshLOD(this.context,this.sourceId,C,e)))}Promise.all(s).then(n=>{var a,B;if(n.some(Q=>Q)==!1)return;(a=this.context.physics.engine)==null||a.removeBody(this);const C=new lA;for(const Q of n)Q&&this.activeAndEnabled&&(C.geometry=Q,(B=this.context.physics.engine)==null||B.addMeshCollider(this,C,this.convex,Vt(this.gameObject)))})}}}}Io([D(lA)],aQ.prototype,"sharedMesh",2);Io([D()],aQ.prototype,"convex",2);class xC extends xo{constructor(){super(...arguments);r(this,"center",new w(0,0,0));r(this,"radius",.5);r(this,"height",2)}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addCapsuleCollider(this,this.height,this.radius)}}Io([D(w)],xC.prototype,"center",2);Io([D()],xC.prototype,"radius",2);Io([D()],xC.prototype,"height",2);var KIA=Object.defineProperty,JIA=Object.getOwnPropertyDescriptor,zN=(g,A,e,t)=>{for(var i=t>1?void 0:t?JIA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&KIA(A,e,i),i};class rQ extends RA{constructor(){super(...arguments);r(this,"objectBounds",!1);r(this,"color");r(this,"isGizmo",!0);r(this,"_gizmoObject",null);r(this,"_boxHelper",null)}onEnable(){this.isGizmo&&!uu||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new ER(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=wN(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),Ai.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){var e;for(;this._boxHelper;)(e=this._boxHelper)==null||e.update(),yield}}zN([D()],rQ.prototype,"objectBounds",2);zN([D(mA)],rQ.prototype,"color",2);zN([D()],rQ.prototype,"isGizmo",2);const bIA=IA("gizmos"),vIA=IA("debugboxhelper"),Vo=class extends RA{constructor(){super(...arguments);r(this,"box",null);r(this,"_lastMatrixUpdateFrame",-1);r(this,"_helper",null);r(this,"_color",null)}isInBox(e,t){var I;if(!e)return;if(this.box||(this.box=new wt),e.type==="Mesh")Vo.testBox.setFromObject(e);else if(e.type==="Group"){if(Vo.testBox.makeEmpty(),e.children.length>0)for(let o=0;o<e.children.length;o++)e.children[o].type==="Mesh"&&Vo.testBox.expandByObject(e)}else{const o=_e(e,Vo._position),s=Vt(e,Vo._size);t!==void 0&&s.multiplyScalar(t),Vo.testBox.setFromCenterAndSize(o,s)}this.updateBox();const i=(I=this.box)==null?void 0:I.intersectsBox(Vo.testBox);return i&&vIA&&De.DrawWireBox3(Vo.testBox,16711680,5),i}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){if(this.box||(this.box=new wt),e||this.context.time.frameCount!=this._lastMatrixUpdateFrame){const t=this._lastMatrixUpdateFrame<0;this._lastMatrixUpdateFrame=this.context.time.frameCount;const i=t,I=_e(this.gameObject,Vo._position,i),o=Vt(this.gameObject,Vo._size);this.box.setFromCenterAndSize(I,o)}return this.box}awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,t=!1){var i;if(!(!bIA&&!t)){if(this._helper){e&&((i=this._color)==null||i.set(e)),this.gameObject.add(this._helper);return}this._helper=wN(e),this.gameObject.add(this._helper)}}};let gs=Vo;r(gs,"testBox",new wt),r(gs,"_position",new w),r(gs,"_size",new w(.01,.01,.01));class qIA extends dH{constructor(A,e={}){super(A),A._simpleState__activeStates=[],A._simpleState__normalStyles={},A._simpleState__states=e,A._simpleState__statesProperties={};for(const t in e)for(const i in e[t])A._simpleState__statesProperties[i]||(A._simpleState__statesProperties[i]=[]),A._simpleState__statesProperties[i].push(t);for(const t of A._components)A._simpleState__statesProperties[t.id]&&(A._simpleState__normalStyles[t.id]=t.inline?t.inline:t._value);A.__overridedSet=A.set,A.set=this.storeSet.bind(A),A.renderStates=this.renderStates.bind(A),A.setupState=this.setupState.bind(A),A.setState=this.setState.bind(A),A.activatePseudoState=this.activatePseudoState.bind(A),A.deactivatePseudoState=this.deactivatePseudoState.bind(A),A.togglePseudoState=this.togglePseudoState.bind(A)}act(){}attach(){}detach(){}setupState(A,e){this._simpleState__states[A]=e;const t=[];for(const i in e)this._simpleState__statesProperties[i]||(this._simpleState__statesProperties[i]=[],t.push(i)),this._simpleState__statesProperties[i].push(A);for(const i of this._components)t.indexOf(i.id)>-1&&(this._simpleState__normalStyles[i.id]=i.inline?i.inline:i._value)}renderStates(){let A={...this._simpleState__normalStyles};for(const e in this._simpleState__states)this._simpleState__activeStates.indexOf(e)>-1&&(A={...A,...this._simpleState__states[e]});this.set(A,!1)}storeSet(A,e=!0){if(e)for(const t in A)this._simpleState__statesProperties[t]&&(this._simpleState__normalStyles[t]=A[t]);this.__overridedSet(A)}activatePseudoState(A){this._simpleState__activeStates.indexOf(A)===-1&&(this._simpleState__activeStates.push(A),this.renderStates())}deactivatePseudoState(A){const e=this._simpleState__activeStates.indexOf(A);e>-1&&(this._simpleState__activeStates.splice(e,1),this.renderStates())}togglePseudoState(A){const e=this._simpleState__activeStates.indexOf(A);e>-1?this._simpleState__activeStates.splice(e,1):this._simpleState__activeStates.push(A),this.renderStates()}setState(A){Array.isArray(A)?this._simpleState__activeStates=A:this._simpleState__activeStates=[A],this.renderStates()}}var xIA=Object.defineProperty,LIA=Object.getOwnPropertyDescriptor,$O=(g,A,e,t)=>{for(var i=t>1?void 0:t?LIA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&xIA(A,e,i),i};class Oc extends RA{constructor(){super(...arguments);r(this,"effectColor");r(this,"effectDistance")}}$O([D(Mt)],Oc.prototype,"effectColor",2);$O([D(iA)],Oc.prototype,"effectDistance",2);var _IA=Object.defineProperty,TIA=Object.getOwnPropertyDescriptor,xu=(g,A,e,t)=>{for(var i=t>1?void 0:t?TIA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&_IA(A,e,i),i};const QG=IA("debugui"),EG=IA("debuguilayout");class XN{constructor(){r(this,"width");r(this,"height")}}class $N{constructor(){r(this,"x");r(this,"y");r(this,"width");r(this,"height")}}const ms=new w,Ll=new GA,vf=new MA,AP=class extends Ws{constructor(){super(...arguments);r(this,"_anchoredPosition");r(this,"sizeDelta",new iA(100,100));r(this,"pivot",new iA(.5,.5));r(this,"anchorMin",new iA(0,0));r(this,"anchorMax",new iA(1,1));r(this,"minWidth");r(this,"minHeight");r(this,"lastMatrix");r(this,"rectBlock");r(this,"_transformNeedsUpdate",!1);r(this,"_initialPosition");r(this,"_parentRectTransform");r(this,"_lastUpdateFrame",-1);r(this,"_lastAnchoring");r(this,"_createdBlocks",[]);r(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 iA),this._anchoredPosition}set anchoredPosition(A){this._anchoredPosition=A}get width(){let A=this.sizeDelta.x;if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const e=this._parentRectTransform.width,t=this.anchorMax.x-this.anchorMin.x;A=e*t,A+=this.sizeDelta.x}return this.minWidth!==void 0&&A<this.minWidth?this.minWidth:A}get height(){let A=this.sizeDelta.y;if(this.anchorMin.y!==this.anchorMax.y&&this._parentRectTransform){const e=this._parentRectTransform.height,t=this.anchorMax.y-this.anchorMin.y;A=e*t,A+=this.sizeDelta.y}return this.minHeight!==void 0&&A<this.minHeight?this.minHeight:A}awake(){super.awake(),this._anchoredPosition||(this._anchoredPosition=new iA),this.lastMatrix=new GA,this.rectBlock=new uA,this.rectBlock.name=this.name,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,EE(this,"_anchoredPosition",()=>{this.markDirty()}),EE(this,"sizeDelta",()=>{this.markDirty()}),EE(this,"pivot",()=>{this.markDirty()}),EE(this,"anchorMin",()=>{this.markDirty()}),EE(this,"anchorMax",()=>{this.markDirty()})}onEnable(){var A;super.onEnable(),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,(A=this.Canvas)==null||A.registerTransform(this)}onDisable(){var A;super.onDisable(),this.removeShadowComponent(),(A=this.Canvas)==null||A.unregisterTransform(this)}onParentRectTransformChanged(A){this._transformNeedsUpdate||this.onApplyTransform(EG?`${A.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(EG&&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(A){var i;if(this.context.time.frameCount===this._lastUpdateFrame)return;this._lastUpdateFrame=this.context.time.frameCount;const e=this.shadowComponent;if(!e)return;this.gameObject.parent?this._parentRectTransform=aA.getComponentInParent(this.gameObject.parent,AP):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,EG&&console.warn("RectTransform → ApplyTransform",this.name+" because "+A),this.isRoot()?this.Root.screenspace||(e.rotation.y=Math.PI):(e.matrix.identity(),e.matrixAutoUpdate=!1,ms.set(0,0,0),this.applyPivot(ms),e.matrix.setPosition(ms.x,ms.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(vf.copy(this.gameObject.quaternion),vf.x*=-1,vf.z*=-1,Ll.makeRotationFromQuaternion(vf),e.matrix.premultiply(Ll)),ms.set(0,0,0),this.applyAnchoring(ms),(i=this.Canvas)!=null&&i.screenspace?ms.z+=.1:ms.z+=.01,Ll.identity(),Ll.setPosition(ms.x,ms.y,ms.z),e.matrix.premultiply(Ll),e.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const t=!0;for(const I of bN(this.gameObject,Ws,t,1)){if(I===this||!I.activeAndEnabled)continue;const o=I;o.onParentRectTransformChanged&&o.onParentRectTransformChanged(this)}}applyAnchoring(A){this._lastAnchoring||(this._lastAnchoring=new iA);const e=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=e.x,this.gameObject.position.y+=e.y,this._lastAnchoring.copy(this._anchoredPosition),A.x+=this._initialPosition.x-this.gameObject.position.x,A.y+=this._initialPosition.y-this.gameObject.position.y,A.z+=this._initialPosition.z-this.gameObject.position.z;const t=this._parentRectTransform;if(t){let i=0;const I=1-this.anchorMax.y-this.anchorMin.y;i-=t.height*.5*I,A.y+=i;let o=0;const s=1-this.anchorMax.x-this.anchorMin.x;o-=t.width*.5*s,A.x+=o}}applyPivot(A){if(this.pivot&&!this.isRoot()){const e=this.pivot.x-.5;A.x-=e*this.sizeDelta.x*this.gameObject.scale.x;const t=this.pivot.y-.5;A.y-=t*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){const A={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:0,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(A),A}ensureValidSize(A,e=1e-4){return A.width<=0&&(A.width=e),A.height<=0&&(A.height=1e-4),A}createNewBlock(A){A={...this.getBasicOptions(),...A},QG&&console.log(this.name,A);const e=new HR(A);return this._createdBlocks.push(e),e}createNewText(A){QG&&console.log(A),A={...this.getBasicOptions(),...A},QG&&console.log(this.name,A);const e=new YR(A);return this._createdTextBlocks.push(e),e}};let HI=AP;xu([D(iA)],HI.prototype,"anchoredPosition",1);xu([D(iA)],HI.prototype,"sizeDelta",2);xu([D(iA)],HI.prototype,"pivot",2);xu([D(iA)],HI.prototype,"anchorMin",2);xu([D(iA)],HI.prototype,"anchorMax",2);var HIA=Object.defineProperty,YIA=Object.getOwnPropertyDescriptor,eP=(g,A,e,t)=>{for(var i=t>1?void 0:t?YIA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&HIA(A,e,i),i};const qf={backgroundColor:new mA(1,1,1),backgroundOpacity:1,borderColor:new mA(1,1,1),borderOpacity:1};var $G;const xD=($G=class extends Ws{constructor(){super(...arguments);r(this,"_alphaFactor",1);r(this,"sRGBColor",new mA(1,0,1));r(this,"raycastTarget",!0);r(this,"uiObject",null);r(this,"_color",null);r(this,"_rect",null);r(this,"_stateManager",null);r(this,"_currentlyCreatingPanel",!1)}get isGraphic(){return!0}get color(){return this._color||(this._color=new Mt(1,1,1,1)),this._color}set color(A){(!this._color||this._color.r!==A.r||this._color.g!==A.g||this._color.b!==A.b||this._color.alpha!==A.alpha)&&(this._color||(this._color=new Mt(1,1,1,1)),this._color.copy(A),this.onColorChanged())}setAlphaFactor(A){this._alphaFactor=A,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}onColorChanged(){this.uiObject&&(this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),qf.backgroundColor=this.sRGBColor,qf.backgroundOpacity=this._color.alpha*this._alphaFactor,this.applyEffects(qf,this._alphaFactor),this.uiObject.set(qf),this.markDirty())}get m_Color(){return this._color}get rectTransform(){if(this._rect||(this._rect=aA.getComponent(this.gameObject,HI)),!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 A;(A=this.uiObject)==null||A.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(A){return super.__internalNewInstanceCreated(A),this._rect=null,this.uiObject=null,this._color&&(this._color=this._color.clone()),this}setState(A){this.makePanel(),this.uiObject&&(this.uiObject.setState(A),this==null||this.markDirty())}setupState(A){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new qIA(this.uiObject)),this.uiObject.setupState(A.state,A.attributes))}setOptions(A){this.makePanel(),this.uiObject&&this.uiObject.set(A)}awake(){super.awake(),this.makePanel(),EE(this,"_color",()=>lgA(this,this.onColorChanged))}onEnable(){var A;super.onEnable(),this.uiObject&&((A=this.rectTransform.shadowComponent)==null||A.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 A=.015,e={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:A};this.onBeforeCreate(e),this.applyEffects(e),this.onCreate(e),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated(),this.onColorChanged()}onBeforeCreate(A){}onCreate(A){this.uiObject=this.rectTransform.createNewBlock(A),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(A,e=1){var i;const t=(i=this.gameObject)==null?void 0:i.getComponent(Oc);t&&(t.effectDistance&&(A.borderWidth=Math.max(Math.abs(t.effectDistance.x),Math.abs(t.effectDistance.y))),t.effectColor&&(A.borderColor=t.effectColor,A.borderOpacity=t.effectColor.alpha*e))}async setTexture(A){if(this.setOptions({backgroundOpacity:0}),A){if(xD.textureCache.has(A))A=xD.textureCache.get(A);else if(!A.isRenderTargetTexture){const e=A.clone();e.colorSpace=yt,xD.textureCache.set(A,e),A=e}this.setOptions({backgroundImage:A,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}),Kt.assignTextureLOD(this.context,this.sourceId,A,0).then(e=>{e instanceof fe&&this.setOptions({backgroundImage:e})})}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)}},r($G,"textureCache",new Map),$G);let BQ=xD;eP([D(Mt)],BQ.prototype,"color",1);eP([D()],BQ.prototype,"raycastTarget",2);class Lu extends BQ{constructor(){super(...arguments);r(this,"_flippedObject",!1)}onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var OIA=Object.defineProperty,PIA=Object.getOwnPropertyDescriptor,US=(g,A,e,t)=>{for(var i=t>1?void 0:t?PIA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&OIA(A,e,i),i};let AF=class{constructor(){r(this,"texture",null);r(this,"rect")}};US([D(fe)],AF.prototype,"texture",2);let Pc=class extends Lu{constructor(){super(...arguments);r(this,"_sprite");r(this,"pixelsPerUnitMultiplier",1)}set image(e){this.sprite||(this.sprite=new AF),this.sprite.texture=e,this.onAfterCreated()}get image(){return this.sprite?this.sprite.texture:null}get sprite(){return this._sprite}set sprite(e){this._sprite!==e&&(this._sprite=e,this.onAfterCreated())}isBuiltinSprite(){var t,i,I,o,s,n,C;const e=this.sprite;switch((t=e==null?void 0:e.texture)==null?void 0:t.name){case"InputFieldBackground":case"UISprite":case"Background":case"Knob":return!0}return!((I=(i=e==null?void 0:e.texture)==null?void 0:i.name)!=null&&I.length)&&((s=(o=e==null?void 0:e.texture)==null?void 0:o.image)==null?void 0:s.width)===32&&((C=(n=e==null?void 0:e.texture)==null?void 0:n.image)==null?void 0:C.height)===32}onBeforeCreate(e){var t,i;super.onBeforeCreate(e),this.isBuiltinSprite()&&(e.borderRadius=5/this.pixelsPerUnitMultiplier,((i=(t=this.sprite)==null?void 0:t.texture)==null?void 0:i.name)==="Knob"&&(e.borderRadius=999))}onAfterCreated(){var e;this.__didAwake&&(super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture((e=this.sprite)==null?void 0:e.texture))}};US([D(AF)],Pc.prototype,"sprite",1);US([D()],Pc.prototype,"pixelsPerUnitMultiplier",2);class RS extends Lu{constructor(){super(...arguments);r(this,"_mainTexture")}get mainTexture(){return this._mainTexture}set mainTexture(e){this._mainTexture!==e&&(this._mainTexture=e,this.onAfterCreated())}onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),this.setTexture(this.mainTexture))}}US([D(fe)],RS.prototype,"mainTexture",1);var WIA=Object.defineProperty,ZIA=Object.getOwnPropertyDescriptor,Lo=(g,A,e,t)=>{for(var i=t>1?void 0:t?ZIA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&WIA(A,e,i),i};const Yr=IA("debugbutton");class lr{constructor(){r(this,"colorMultiplier");r(this,"disabledColor");r(this,"fadeDuration");r(this,"highlightedColor");r(this,"normalColor");r(this,"pressedColor");r(this,"selectedColor")}}Lo([D()],lr.prototype,"colorMultiplier",2);Lo([D(Mt)],lr.prototype,"disabledColor",2);Lo([D()],lr.prototype,"fadeDuration",2);Lo([D(Mt)],lr.prototype,"highlightedColor",2);Lo([D(Mt)],lr.prototype,"normalColor",2);Lo([D(Mt)],lr.prototype,"pressedColor",2);Lo([D(Mt)],lr.prototype,"selectedColor",2);class jIA{constructor(){r(this,"disabledTrigger");r(this,"highlightedTrigger");r(this,"normalTrigger");r(this,"pressedTrigger");r(this,"selectedTrigger")}}class WC extends RA{constructor(){super(...arguments);r(this,"onClick");r(this,"_isHovered",0);r(this,"colors");r(this,"transition");r(this,"animationTriggers");r(this,"animator");r(this,"_interactable",!0);r(this,"_requestedAnimatorTrigger");r(this,"_isInit",!1);r(this,"_image")}onPointerEnter(e){var i,I;const t=e.event.pointerType==="mouse"&&e.button===0;t&&(this._isHovered+=1),Yr&&console.warn("Button Enter",t,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&&((I=this._image)==null||I.setState("hovered")),t&&this.context.input.setCursorPointer())}onPointerExit(){var e,t;this._isHovered-=1,this._isHovered<0&&(this._isHovered=0),Yr&&console.log("Button Exit",this._isHovered,(e=this.animationTriggers)==null?void 0:e.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&&((t=this._image)==null||t.setState("normal")),this.context.input.setCursorNormal()))}onPointerDown(e){var t,i;Yr&&console.log("Button Down",(t=this.animationTriggers)==null?void 0:t.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&((i=this._image)==null||i.setState("pressed")))}onPointerUp(e){var t,i;Yr&&console.warn("Button Up",(t=this.animationTriggers)==null?void 0:t.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&&((i=this._image)==null||i.setState(this._isHovered?"hovered":"normal")))}onPointerClick(e){if(this.interactable&&!(e.button!==0&&e.event.pointerType===nS.Mouse)&&(Yr&&(console.warn("Button Click",this.onClick),Ci("CLICKED button "+this.name+" at "+this.context.time.frameCount)),this.onClick&&this.onClick.listenerCount>0&&(this.onClick.invoke(),e.use(),Yr))){const t=this.gameObject.worldPosition;t.add(this.gameObject.worldUp.multiplyScalar(1+Math.random()*.5)),De.DrawLabel(t,"CLICK:"+Date.now(),.1,1+Math.random()*.5)}}set interactable(e){this._interactable=e,this._image&&(this._image.setInteractable(e),e?this._image.setState("normal"):this._image.setState("disabled"))}get interactable(){return this._interactable}set_interactable(e){this.interactable=e}awake(){super.awake(),Yr&&console.log(this),this._isInit=!1,this.init()}start(){var e;(e=this._image)==null||e.setInteractable(this.interactable),this.gameObject.getComponentInParent(Ru)||this.gameObject.addComponent(uS)}onEnable(){super.onEnable()}onDestroy(){this._isHovered&&this.context.input.setCursorNormal()}*setAnimatorTriggerAtEndOfFrame(e){var t;this._requestedAnimatorTrigger=e,yield,yield,this._requestedAnimatorTrigger==e&&((t=this.animator)==null||t.SetTrigger(e))}init(){this._isInit||(this._isInit=!0,this._image=aA.getComponent(this.gameObject,Pc),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){var E,c,d,l,h;e.setInteractable(this.interactable);const t=this.getFinalColor(e.color,(E=this.colors)==null?void 0:E.normalColor),i={state:"normal",attributes:{backgroundColor:t,backgroundOpacity:t.alpha}};e.setupState(i);const I=this.getFinalColor(e.color,(c=this.colors)==null?void 0:c.highlightedColor),o={state:"hovered",attributes:{backgroundColor:I,backgroundOpacity:I.alpha}};e.setupState(o);const s=this.getFinalColor(e.color,(d=this.colors)==null?void 0:d.pressedColor),n={state:"pressed",attributes:{backgroundColor:s,backgroundOpacity:s.alpha}};e.setupState(n);const C=this.getFinalColor(e.color,(l=this.colors)==null?void 0:l.selectedColor),a={state:"selected",attributes:{backgroundColor:C,backgroundOpacity:C.alpha}};e.setupState(a);const B=this.getFinalColor(e.color,(h=this.colors)==null?void 0:h.disabledColor),Q={state:"disabled",attributes:{backgroundColor:B,backgroundOpacity:B.alpha}};e.setupState(Q)}getFinalColor(e,t){return t?e.clone().multiply(t).convertLinearToSRGB():e.clone().convertLinearToSRGB()}}Lo([D(rg)],WC.prototype,"onClick",2);Lo([D(lr)],WC.prototype,"colors",2);Lo([D()],WC.prototype,"transition",2);Lo([D(jIA)],WC.prototype,"animationTriggers",2);Lo([D(Zg)],WC.prototype,"animator",2);Lo([D()],WC.prototype,"interactable",1);var VIA=Object.defineProperty,zIA=Object.getOwnPropertyDescriptor,Ag=(g,A,e,t)=>{for(var i=t>1?void 0:t?zIA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&VIA(A,e,i),i};const Yq=IA("debuguilayout");class hr{constructor(){r(this,"left",0);r(this,"right",0);r(this,"top",0);r(this,"bottom",0)}get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}Ag([D()],hr.prototype,"left",2);Ag([D()],hr.prototype,"right",2);Ag([D()],hr.prototype,"top",2);Ag([D()],hr.prototype,"bottom",2);class _o extends RA{constructor(){super(...arguments);r(this,"_rectTransform",null);r(this,"_needsUpdate",!1);r(this,"childAlignment",0);r(this,"reverseArrangement",!1);r(this,"spacing",0);r(this,"padding");r(this,"minWidth",0);r(this,"minHeight",0);r(this,"flexibleHeight",0);r(this,"flexibleWidth",0);r(this,"preferredHeight",0);r(this,"preferredWidth",0)}get rectTransform(){return this._rectTransform}onParentRectTransformChanged(e){this._needsUpdate=!0}get isDirty(){return this._needsUpdate}get isLayoutGroup(){return!0}updateLayout(){this._rectTransform&&(Yq&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}start(){this._needsUpdate=!0}onEnable(){Yq&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(HI);const e=this.gameObject.getComponentInParent(jg);e&&e.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const e=this.gameObject.getComponentInParent(jg);e&&e.unregisterLayoutGroup(this)}set m_Spacing(e){e!==this.spacing&&(this._needsUpdate=!0,this.spacing=e)}get m_Spacing(){return this.spacing}}Ag([D()],_o.prototype,"childAlignment",2);Ag([D()],_o.prototype,"reverseArrangement",2);Ag([D()],_o.prototype,"spacing",2);Ag([D(hr)],_o.prototype,"padding",2);Ag([D()],_o.prototype,"minWidth",2);Ag([D()],_o.prototype,"minHeight",2);Ag([D()],_o.prototype,"flexibleHeight",2);Ag([D()],_o.prototype,"flexibleWidth",2);Ag([D()],_o.prototype,"preferredHeight",2);Ag([D()],_o.prototype,"preferredWidth",2);class dr extends _o{constructor(){super(...arguments);r(this,"childControlHeight",!0);r(this,"childControlWidth",!0);r(this,"childForceExpandHeight",!1);r(this,"childForceExpandWidth",!1);r(this,"childScaleHeight",!1);r(this,"childScaleWidth",!1)}onCalculateLayout(e){var m;const t=this.primaryAxis,i=e.width;let I=i;const o=e.height;let s=o;I-=this.padding.horizontal,s-=this.padding.vertical,t==="x"?this.padding.horizontal:this.padding.vertical;const n=t==="x",C=n?"y":"x",a=n?this.childControlWidth:this.childControlHeight,B=n?this.childControlHeight:this.childControlWidth,Q=n?this.childForceExpandWidth:this.childForceExpandHeight,E=n?this.childForceExpandHeight:this.childForceExpandWidth,c=n?s:I,d=n?i:o,l=.5*(n?this.childAlignment%3:Math.floor(this.childAlignment/3));let h=0;n?h+=this.padding.left:h+=this.padding.top;let p=0,u=0;for(let N=0;N<this.gameObject.children.length;N++){const y=this.gameObject.children[N],U=aA.getComponent(y,HI);U!=null&&U.activeAndEnabled&&(u+=1,n?p+=U.width:p+=U.height)}let f=0;const k=this.spacing*(u-1);if(Q||a){let N=0;n?N=I-=k:N=s-=k,u>0&&(f=N/u)}let G=0;G+=this.padding.left,G-=this.padding.right,l!==0&&(h=d-p,h*=l,h-=k*l,n?(h-=this.padding.right*l,h+=this.padding.left*(1-l),h<this.padding.left&&(h=this.padding.left)):(h-=this.padding.bottom*l,h+=this.padding.top*(1-l),h<this.padding.top&&(h=this.padding.top)));let M=1;for(let N=0;N<this.gameObject.children.length;N++){const y=this.gameObject.children[N],U=aA.getComponent(y,HI);if(U!=null&&U.activeAndEnabled){(m=U.pivot)==null||m.set(.5,.5),U.anchorMin.set(0,1),U.anchorMax.set(0,1);const H=i*.5+G*.5;U.anchoredPosition.x!==H&&(U.anchoredPosition.x=H);const x=o*-.5;U.anchoredPosition.y!==x&&(U.anchoredPosition.y=x),E&&B&&U.sizeDelta[C]!==c&&(U.sizeDelta[C]=c),Q&&a&&U.sizeDelta[t]!==f&&(U.sizeDelta[t]=f);const K=n?U.width:U.height,O=K*.5;if(h+=O,Q){const v=f*M-f*.5;v>h&&(h=v-f*.5+K+this.padding.left,h-=O)}let b=h;t==="y"&&(b=-b),U.anchoredPosition[t]!==b&&(U.anchoredPosition[t]=b),h+=O,h+=this.spacing,M+=1}}}}Ag([D()],dr.prototype,"childControlHeight",2);Ag([D()],dr.prototype,"childControlWidth",2);Ag([D()],dr.prototype,"childForceExpandHeight",2);Ag([D()],dr.prototype,"childForceExpandWidth",2);Ag([D()],dr.prototype,"childScaleHeight",2);Ag([D()],dr.prototype,"childScaleWidth",2);class eF extends dr{get primaryAxis(){return"y"}}class tF extends dr{get primaryAxis(){return"x"}}class iF extends _o{onCalculateLayout(){}}var XIA=Object.defineProperty,$IA=Object.getOwnPropertyDescriptor,_n=(g,A,e,t)=>{for(var i=t>1?void 0:t?$IA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&XIA(A,e,i),i},tP=(g=>(g[g.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",g[g.ScreenSpaceCamera=1]="ScreenSpaceCamera",g[g.WorldSpace=2]="WorldSpace",g[g.Undefined=-1]="Undefined",g))(tP||{});const cG=IA("debuguilayout"),iP=class extends Uu{constructor(){super(...arguments);r(this,"_renderOnTop");r(this,"_depthWrite",!1);r(this,"_doubleSided",!0);r(this,"_castShadows",!1);r(this,"_receiveShadows",!1);r(this,"_renderMode",-1);r(this,"_rootCanvas");r(this,"_scaleFactor",1);r(this,"worldCamera");r(this,"planeDistance",-1);r(this,"_boundRenderSettingsChanged",this.onRenderSettingsChanged.bind(this));r(this,"previousParent",null);r(this,"_lastMatrixWorld",null);r(this,"_rectTransforms",[]);r(this,"_layoutGroups",new Map);r(this,"_receivers",[]);r(this,"onBeforeRenderRoutine",()=>{var A,e,t,i;if(this.previousParent=this.gameObject.parent,((A=this.context.xr)!=null&&A.isVR||(e=this.context.xr)!=null&&e.isPassThrough)&&this.screenspace){this.gameObject.visible=!1,this.gameObject.removeFromParent();return}this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),(t=this.shadowComponent)==null||t.updateMatrixWorld(!0),(i=this.shadowComponent)==null||i.updateWorldMatrix(!0,!0),this.invokeBeforeRenderEvents(),Ao.ensureUpdateMeshUI(Jb,this.context))});r(this,"onAfterRenderRoutine",()=>{var A,e,t,i,I;if(((A=this.context.xr)!=null&&A.isVR||(e=this.context.xr)!=null&&e.isPassThrough)&&this.screenspace){(t=this.previousParent)==null||t.add(this.gameObject);return}if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){if(this.screenspace){const n=this.context.mainCamera;n==null||n.add(this.gameObject)}else this.previousParent.add(this.gameObject);const o=this.context.renderer.autoClear,s=this.context.renderer.autoClearColor;this.context.renderer.autoClear=!1,this.context.renderer.autoClearColor=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),(i=this.shadowComponent)==null||i.updateMatrixWorld(!0),this.invokeBeforeRenderEvents(),Ao.ensureUpdateMeshUI(Jb,this.context,!0),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=o,this.context.renderer.autoClearColor=s,this.previousParent.add(this.gameObject)}(I=this._lastMatrixWorld)==null||I.copy(this.gameObject.matrixWorld)});r(this,"_updateRenderSettingsRoutine");r(this,"_activeRenderMode",-1);r(this,"_lastWidth",-1);r(this,"_lastHeight",-1)}get isCanvas(){return!0}get screenspace(){return this.renderMode!==2}set renderOnTop(A){A!==this._renderOnTop&&(this._renderOnTop=A,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop!==void 0?this._renderOnTop:!!(this.screenspace&&this._renderMode===0)}set depthWrite(A){this._depthWrite!==A&&(this._depthWrite=A,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}set doubleSided(A){this._doubleSided!==A&&(this._doubleSided=A,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}set castShadows(A){this._castShadows!==A&&(this._castShadows=A,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}set receiveShadows(A){this._receiveShadows!==A&&(this._receiveShadows=A,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}get renderMode(){return this._renderMode}set renderMode(A){this._renderMode!==A&&(this._renderMode=A,this.onRenderSettingsChanged())}set rootCanvas(A){this._rootCanvas instanceof iP||(this._rootCanvas=A)}get rootCanvas(){return this._rootCanvas}get scaleFactor(){return this._scaleFactor}set scaleFactor(A){this._scaleFactor=A}awake(){var A;this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,cG&&console.log("Canvas.Awake()",((A=this.previousParent)==null?void 0:A.name)+"/"+this.gameObject.name),super.awake()}start(){this.onUpdateRenderMode()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new GA,this.onUpdateRenderMode(),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 A=this.context.pre_render_callbacks.indexOf(this.onBeforeRenderRoutine);A!==-1&&this.context.pre_render_callbacks.splice(A,1);const e=this.context.post_render_callbacks.indexOf(this.onAfterRenderRoutine);e!==-1&&this.context.post_render_callbacks.splice(e,1)}registerTransform(A){this._rectTransforms.push(A)}unregisterTransform(A){const e=this._rectTransforms.indexOf(A);e!==-1&&this._rectTransforms.splice(e,1)}registerLayoutGroup(A){const e=A.gameObject;this._layoutGroups.set(e,A)}unregisterLayoutGroup(A){const e=A.gameObject;this._layoutGroups.delete(e)}registerEventReceiver(A){this._receivers.push(A)}unregisterEventReceiver(A){const e=this._receivers.indexOf(A);e!==-1&&this._receivers.splice(e,1)}async onEnterXR(A){this.screenspace?(A.xr.isVR||A.xr.isPassThrough)&&(this.gameObject.visible=!1):(this.gameObject.visible=!1,await dT(1).then(()=>{this.gameObject.visible=!0}))}onLeaveXR(A){this.screenspace&&(A.xr.isVR||A.xr.isPassThrough)&&(this.gameObject.visible=!0)}invokeBeforeRenderEvents(){var A;for(const e of this._receivers)(A=e.onBeforeCanvasRender)==null||A.call(e,this)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new GA);const A=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);cG&&A&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);const e=!1;for(const t of this._rectTransforms){A&&t.markDirty();let i=this._layoutGroups.get(t.gameObject);t.isDirty&&!i&&(i=t.gameObject.getComponentInParent(_o)),(t.isDirty||i!=null&&i.isDirty)&&(cG&&!e&&console.log("CANVAS UPDATE ### "+t.name+" ##################################### "+this.context.time.frame),i==null||i.updateLayout(),t.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),Ai.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),bw(this.shadowComponent,this);for(const A of aA.getComponentsInChildren(this.gameObject,Ws))bw(A.shadowComponent,this)}}onUpdateRenderMode(A=!1){if(!A&&this._renderMode===this._activeRenderMode&&this._lastWidth===this.context.domWidth&&this._lastHeight===this.context.domHeight)return;this._activeRenderMode=this._renderMode;let e=this.context.mainCameraComponent,t=10;switch(e&&e.nearClipPlane>0&&e.farClipPlane>0&&(t=te.lerp(e.nearClipPlane,e.farClipPlane,.01)),this._renderMode===1&&(this.worldCamera&&(e=this.worldCamera),this.planeDistance>0&&(t=this.planeDistance)),this._renderMode){case 0:case 1:if(this._lastWidth=this.context.domWidth,this._lastHeight=this.context.domHeight,!e)return;const i=t+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-i,this.gameObject.quaternion.identity();const I=this.gameObject.getComponent(HI);let o=!1;I.sizeDelta.x!==this.context.domWidth&&(o=!0),I.sizeDelta.y!==this.context.domHeight&&(o=!0);const s=e.fieldOfView*Math.PI/180,n=2*Math.tan(s/2)*Math.abs(i);this.gameObject.scale.x=n/this.context.domHeight,this.gameObject.scale.y=n/this.context.domHeight,this.gameObject.scale.z=.01,o&&(I.sizeDelta.x=this.context.domWidth,I.sizeDelta.y=this.context.domHeight,I==null||I.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};let jg=iP;_n([D()],jg.prototype,"renderOnTop",1);_n([D()],jg.prototype,"depthWrite",1);_n([D()],jg.prototype,"doubleSided",1);_n([D()],jg.prototype,"castShadows",1);_n([D()],jg.prototype,"receiveShadows",1);_n([D()],jg.prototype,"renderMode",1);_n([D(jg)],jg.prototype,"rootCanvas",1);_n([D()],jg.prototype,"scaleFactor",1);_n([D(Wt)],jg.prototype,"worldCamera",2);_n([D()],jg.prototype,"planeDistance",2);var AoA=Object.defineProperty,eoA=Object.getOwnPropertyDescriptor,gF=(g,A,e,t)=>{for(var i=t>1?void 0:t?eoA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&AoA(A,e,i),i};class Cr extends RA{constructor(){super(...arguments);r(this,"_alpha",1);r(this,"interactable",!0);r(this,"blocksRaycasts",!0);r(this,"_isDirty",!1);r(this,"_buffer",[])}get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}get isCanvasGroup(){return!0}markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),Ai.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}applyChangesNow(){this._buffer.length=0;for(const e of aA.getComponentsInChildren(this.gameObject,Ws,this._buffer)){const t=e;t.setAlphaFactor&&t.setAlphaFactor(this._alpha)}}}gF([D()],Cr.prototype,"alpha",1);gF([D()],Cr.prototype,"interactable",2);gF([D()],Cr.prototype,"blocksRaycasts",2);var toA=Object.defineProperty,ioA=Object.getOwnPropertyDescriptor,yi=(g,A,e,t)=>{for(var i=t>1?void 0:t?ioA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&toA(A,e,i),i};const Oq=IA("debugusdzbehaviours");function _u(g){g&&(g.getComponentInParent(Ru)||(he()&&console.warn("Create Raycaster on "+g.name+" because no raycaster was found in the hierarchy"),g.addNewComponent(Ko)))}class QQ extends RA{constructor(){super(...arguments);r(this,"object");r(this,"target");r(this,"duration",1);r(this,"relativeMotion",!1);r(this,"coroutine",null);r(this,"targetPos",new w);r(this,"targetRot",new MA);r(this,"targetScale",new w)}start(){_u(this.gameObject)}onPointerClick(e){e.use(),this.coroutine&&this.stopCoroutine(this.coroutine),this.relativeMotion?this.coroutine=this.startCoroutine(this.moveRelative()):this.coroutine=this.startCoroutine(this.moveToTarget())}*moveToTarget(){if(!this.target||!this.object)return;const e=_e(this.object).clone(),t=_e(this.target).clone(),i=Jt(this.object).clone(),I=Jt(this.target).clone(),o=Vt(this.object).clone(),s=Vt(this.target).clone(),n=e.distanceTo(t),C=i.angleTo(I),a=o.distanceTo(s);if(n<.01&&C<.01&&a<.01){EI(this.object,t),rs(this.object,I),wd(this.object,s),this.coroutine=null;return}let B=0,Q=0;for(;B<1;)B+=this.context.time.deltaTime/this.duration,B>1&&(B=1),Q=B<.5?4*B*B*B:1-Math.pow(-2*B+2,3)/2,this.targetPos.lerpVectors(e,t,Q),this.targetRot.slerpQuaternions(i,I,Q),this.targetScale.lerpVectors(o,s,Q),EI(this.object,this.targetPos),rs(this.object,this.targetRot),wd(this.object,this.targetScale),yield;this.coroutine=null}*moveRelative(){if(!this.target||!this.object)return;const e=this.object.position.clone(),t=this.object.quaternion.clone(),i=this.object.scale.clone(),I=this.target.position.clone(),o=this.target.quaternion.clone(),s=this.target.scale.clone();I.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(I),this.targetRot.copy(this.object.quaternion).multiply(o),this.targetScale.copy(this.object.scale).multiply(s);let n=0,C=0;for(;n<1;)n+=this.context.time.deltaTime/this.duration,n>1&&(n=1),C=n<.5?4*n*n*n:1-Math.pow(-2*n+2,3)/2,this.object.position.lerpVectors(e,this.targetPos,C),this.object.quaternion.slerpQuaternions(t,this.targetRot,C),this.object.scale.lerpVectors(i,this.targetScale,C),yield;this.coroutine=null}beforeCreateDocument(e){var t;if(this.target&&this.object&&this.gameObject){const i=new ng("Move to "+((t=this.target)==null?void 0:t.name),Yg.tapTrigger(this.gameObject),Bt.transformAction(this.object,this.target,this.duration,this.relativeMotion?"relative":"absolute"));e.addBehavior(i)}}}yi([D(uA)],QQ.prototype,"object",2);yi([D(uA)],QQ.prototype,"target",2);yi([D()],QQ.prototype,"duration",2);yi([D()],QQ.prototype,"relativeMotion",2);var sD;const CC=(sD=class extends RA{constructor(){super(...arguments);r(this,"materialToSwitch");r(this,"variantMaterial");r(this,"fadeDuration",0);r(this,"_objectsWithThisMaterial",null);r(this,"selfModel");r(this,"targetModels")}start(){this._objectsWithThisMaterial=this.objectsWithThisMaterial,_u(this.gameObject)}onPointerClick(A){if(A.use(),!!this.variantMaterial)for(let e=0;e<this.objectsWithThisMaterial.length;e++){const t=this.objectsWithThisMaterial[e];t.material=this.variantMaterial}}get objectsWithThisMaterial(){return this._objectsWithThisMaterial!=null?this._objectsWithThisMaterial:(this._objectsWithThisMaterial=[],this.variantMaterial&&this.materialToSwitch&&this.context.scene.traverse(A=>{if(A instanceof lA)if(Array.isArray(A.material)){for(const e of A.material)if(e===this.materialToSwitch){this.objectsWithThisMaterial.push(A);break}}else A.material===this.materialToSwitch&&this.objectsWithThisMaterial.push(A)}),this._objectsWithThisMaterial)}async beforeCreateDocument(A,e){this.targetModels=[],CC._materialTriggersPerId={},CC.variantSwitchIndex=0,this.materialToSwitch&&await Kt.assignTextureLOD(this.context,this.sourceId,this.materialToSwitch,0),this.variantMaterial&&await Kt.assignTextureLOD(this.context,this.sourceId,this.variantMaterial,0)}createBehaviours(A,e,t){this.objectsWithThisMaterial.find(I=>I.uuid===e.uuid)&&this.targetModels.push(e),this.gameObject.uuid===e.uuid&&(this.selfModel=e,this.materialToSwitch&&(CC._materialTriggersPerId[this.materialToSwitch.uuid]||(CC._materialTriggersPerId[this.materialToSwitch.uuid]=[]),CC._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(A,e){if(!this.materialToSwitch)return;const t=CC._materialTriggersPerId[this.materialToSwitch.uuid];if(t){const i={};for(const I of t){const o=I.createVariants();o&&o.length>0&&(i[I.selfModel.uuid]=o)}for(const I of t){const o=[];for(const s in i)s!==I.selfModel.uuid&&o.push(...i[s]);I.createAndAttachBehaviors(A,i[I.selfModel.uuid],o)}}delete CC._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(A,e,t){const i=[],I=[],o=Math.max(0,this.fadeDuration);I.push(Bt.fadeAction([...this.targetModels,...t],o,!1)),i.push(Bt.fadeAction(e,o,!1)),I.push(Bt.fadeAction(e,o,!0)),A.addBehavior(new ng("Select_"+this.selfModel.name,Yg.tapTrigger(this.selfModel),Bt.parallel(...I))),A.addBehavior(new ng("StartHidden_"+this.selfModel.name,Yg.sceneStartTrigger(),Bt.parallel(...i)))}createVariants(){if(!this.variantMaterial)return null;const A=[];for(const e of this.targetModels){const t=e.clone();t.name+=" variant_"+this.variantMaterial.name+"_"+CC.variantSwitchIndex++,t.name=t.name.replace(/\s/g,"_"),t.material=this.variantMaterial,t.geometry=e.geometry,t.matrix=e.matrix,(!e.parent||!e.parent.isEmpty())&&$I.createEmptyParent(e),e.parent&&e.parent.add(t),A.push(t)}return A}},r(sD,"_materialTriggersPerId",{}),r(sD,"variantSwitchIndex",0),sD);let Wc=CC;yi([D(be)],Wc.prototype,"materialToSwitch",2);yi([D(be)],Wc.prototype,"variantMaterial",2);yi([D()],Wc.prototype,"fadeDuration",2);var aE;const ci=(aE=class extends RA{constructor(){super(...arguments);r(this,"target");r(this,"toggleOnClick",!1);r(this,"targetState",!0);r(this,"hideSelf",!0);r(this,"selfModel");r(this,"selfModelClone");r(this,"targetModel");r(this,"toggleModel");r(this,"stateBeforeCreatingDocument",!1);r(this,"targetStateBeforeCreatingDocument",!1)}start(){_u(this.gameObject)}onPointerClick(A){A.use(),!this.toggleOnClick&&this.hideSelf&&(this.gameObject.visible=!1),this.target&&(this.target.visible=this.toggleOnClick?!this.target.visible:this.targetState)}createBehaviours(A,e,t){e.uuid===this.gameObject.uuid&&(this.selfModel=e,this.selfModelClone=e.clone())}beforeCreateDocument(){this.target&&(this.gameObject[ci.wasVisible]===void 0&&(this.gameObject[ci.wasVisible]=this.gameObject.activeSelf),this.target[ci.wasVisible]===void 0&&(this.target[ci.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[ci.wasVisible],this.targetStateBeforeCreatingDocument=this.target[ci.wasVisible],this.gameObject.visible=!0,this.target.visible=!0)}afterCreateDocument(A,e){if(!this.target)return;this.targetModel=e.document.findById(this.target.uuid);const t=this.selfModel;if(this.selfModel&&this.targetModel){let i=this.selfModel,I=this.targetState;if(this.toggleOnClick)if(I=!this.targetStateBeforeCreatingDocument,!this.selfModelClone.geometry)(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&XH.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[ci.toggleClone]){const n=this.selfModelClone.clone();n.matrix.identity(),n.name+="_toggle"+ci.clonedToggleIndex++,t.add(n),this.gameObject[ci.toggleClone]=n,console.warn("USDZExport: Toggle "+this.gameObject.name+" doesn't have geometry. It will be deep cloned and nested behaviours will likely not work.")}const s=this.gameObject[ci.toggleClone];if(!this.gameObject[ci.reverseToggleClone]){const n=this.selfModelClone.clone();n.matrix.identity(),n.name+="_toggleReverse"+ci.clonedToggleIndex++,t.add(n),this.gameObject[ci.reverseToggleClone]=n}this.toggleModel=this.gameObject[ci.reverseToggleClone],(!this.toggleModel.geometry||!s.geometry)&&console.error("triggers without childs and without geometry won't work!",this,t.geometry),i=s,t.geometry=null,t.material=null}if(this.toggleModel){if(this.toggleOnClick){const s=[];s.push(Bt.fadeAction(i,0,!1)),s.push(Bt.fadeAction(this.toggleModel,0,!0)),s.push(Bt.fadeAction(this.targetModel,0,I)),A.addBehavior(new ng("Toggle_"+i.name+"_toggleTo"+(I?"On":"Off"),Yg.tapTrigger(i),Bt.parallel(...s)));const n=[];n.push(Bt.fadeAction(this.toggleModel,0,!1)),n.push(Bt.fadeAction(i,0,!0)),n.push(Bt.fadeAction(this.targetModel,0,!I)),A.addBehavior(new ng("Toggle_"+i.name+"_toggleTo"+(I?"Off":"On"),Yg.tapTrigger(this.toggleModel),Bt.parallel(...n)))}}else{const s=[];this.hideSelf&&s.push(Bt.fadeAction(i,0,!1)),s.push(Bt.fadeAction(this.targetModel,0,I)),A.addBehavior(new ng("Toggle_"+i.name+"_toggleTo"+(I?"On":"Off"),Yg.tapTrigger(i),Bt.parallel(...s)))}const o=new Array;this.targetStateBeforeCreatingDocument||o.push(this.targetModel),this.stateBeforeCreatingDocument||o.push(t),this.toggleModel&&o.push(this.toggleModel),A.addBehavior(new ng("HideOnStart_"+this.gameObject.name,Yg.sceneStartTrigger(),Bt.fadeAction(o,0,!1)))}}afterSerialize(A,e){this.gameObject[ci.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[ci.wasVisible],delete this.gameObject[ci.wasVisible]),this.target&&this.target[ci.wasVisible]!==void 0&&(this.target.visible=this.target[ci.wasVisible],delete this.target[ci.wasVisible]),delete this.gameObject[ci.toggleClone],delete this.gameObject[ci.reverseToggleClone]}},r(aE,"clonedToggleIndex",0),r(aE,"wasVisible",Symbol("usdz_SetActiveOnClick_wasVisible")),r(aE,"toggleClone",Symbol("clone for toggling")),r(aE,"reverseToggleClone",Symbol("clone for reverse toggling")),aE);let EQ=ci;yi([D(uA)],EQ.prototype,"target",2);yi([D()],EQ.prototype,"toggleOnClick",2);yi([D()],EQ.prototype,"targetState",2);yi([D()],EQ.prototype,"hideSelf",2);class IF extends RA{start(){this.gameObject.visible=!1}createBehaviours(A,e,t){e.uuid===this.gameObject.uuid&&A.addBehavior(new ng("HideOnStart_"+this.gameObject.name,Yg.sceneStartTrigger(),Bt.fadeAction(e,0,!1)))}beforeCreateDocument(){this.gameObject.visible=!0}afterCreateDocument(){this.gameObject.visible=!1}}class Zc extends RA{constructor(){super(...arguments);r(this,"target");r(this,"duration",.5);r(this,"motionType","bounce")}beforeCreateDocument(){}createBehaviours(e,t,i){if(this.target&&t.uuid===this.gameObject.uuid){const I=new ng("emphasize "+this.name,Yg.tapTrigger(this.gameObject),Bt.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));e.addBehavior(I)}}afterCreateDocument(e,t){}}yi([D()],Zc.prototype,"target",2);yi([D()],Zc.prototype,"duration",2);yi([D()],Zc.prototype,"motionType",2);class ar extends RA{constructor(){super(...arguments);r(this,"target");r(this,"clip","");r(this,"toggleOnClick",!1)}start(){_u(this.gameObject)}ensureAudioSource(){if(!this.target){const e=this.gameObject.addNewComponent(Di);e&&(this.target=e,e.spatialBlend=1,e.volume=1,e.loop=!1)}}onPointerClick(e){var t;e.use(),!(!((t=this.target)!=null&&t.clip)&&!this.clip)&&(this.ensureAudioSource(),this.target&&(this.target.isPlaying&&this.toggleOnClick?this.target.stop():(!this.toggleOnClick&&this.target.isPlaying&&this.target.stop(),this.clip?this.target.play(this.clip):this.target.play())))}createBehaviours(e,t,i){if(!(!this.target&&!this.clip)&&t.uuid===this.gameObject.uuid){const I=this.clip?this.clip:this.target?this.target.clip:void 0;if(!I||typeof I!="string")return;const o=this.target?this.target.gameObject:this.gameObject,s=nr.getName(I),n=this.target?this.target.volume:1,C=this.target&&this.target.spatialBlend==0?"nonSpatial":"spatial";let a=!1;if(this.gameObject.traverse(B=>{B instanceof lA&&B.visible&&(a=!0)}),a=!0,a){let B=Bt.playAudioAction(o,"audio/"+s,"play",n,C);this.toggleOnClick&&(B.multiplePerformOperation="stop"),this.target&&this.target.loop&&(B=Bt.sequence(B).makeLooping());const Q=new ng("playAudio "+this.name,Yg.tapTrigger(this.gameObject),B);e.addBehavior(Q)}if(this.target&&this.target.playOnAwake&&this.target.enabled){let B=Bt.playAudioAction(o,"audio/"+s,"play",n,C);this.target.loop&&(B=Bt.sequence(B).makeLooping());const Q=new ng("playAudioOnStart"+(this.name?"_"+this.name:""),Yg.sceneStartTrigger(),B);e.addBehavior(Q)}}}async afterSerialize(e,t){if(!this.target&&!this.clip)return;const i=this.clip?this.clip:this.target?this.target.clip:void 0;if(!i||typeof i!="string")return;const o="audio/"+nr.getName(i);if(t.files[o])return;const C=await(await(await fetch(i)).blob()).arrayBuffer(),a=new Uint8Array(C);t.files[o]=a}}yi([D(Di)],ar.prototype,"target",2);yi([D(URL)],ar.prototype,"clip",2);yi([D()],ar.prototype,"toggleOnClick",2);var nD;const Ga=(nD=class extends RA{constructor(){super(...arguments);r(this,"animator");r(this,"stateName");r(this,"trigger","tap");r(this,"animation");r(this,"selfModel");r(this,"stateAnimationModel");r(this,"animationSequence",new Array);r(this,"animationLoopAfterSequence",new Array)}get target(){var A,e;return((A=this.animator)==null?void 0:A.gameObject)||((e=this.animation)==null?void 0:e.gameObject)}start(){_u(this.gameObject)}onPointerClick(A){var e;A.use(),this.target&&this.stateName&&((e=this.animator)==null||e.play(this.stateName,0,0,.1))}createBehaviours(A,e,t){e.uuid===this.gameObject.uuid&&(this.selfModel=e)}afterSerialize(){if(Ga.rootsWithExclusivePlayback.size>1){const A='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.';he()&&fi(A),console.warn(A,...Ga.rootsWithExclusivePlayback)}Ga.animationActions=[],Ga.rootsWithExclusivePlayback=new Set}afterCreateDocument(A,e){if(this.animationSequence===void 0&&this.animationLoopAfterSequence===void 0||!this.stateAnimationModel||!this.target)return;const t=e.document,i=e.extensions.find(s=>s instanceof Ku);if(!i)return;const I=i.getClipCount(this.target)>1;I&&(he()&&console.warn("Setting exclusive playback for "+this.target.name+"@"+this.stateName+" because it has "+i.getClipCount(this.target)+" animations. This works around QuickLook bug FB13410767."),Ga.rootsWithExclusivePlayback.add(this.target));const o=(s,n)=>{let C=Ga.animationActions.find(a=>a.affectedObjects==s&&a.start==n.start&&a.duration==n.duration);return C||(C=Bt.startAnimationAction(s,n.start,n.duration),Ga.animationActions.push(C)),C};t.traverse(s=>{var n,C;if(s.uuid===((n=this.target)==null?void 0:n.uuid)){const a=Bt.sequence();if(this.animationSequence!==void 0)for(const Q of this.animationSequence)a.addAction(o(s,Q));if(this.animationLoopAfterSequence!==void 0){const Q=a.actions.length==0?a:Bt.sequence();for(const E of this.animationLoopAfterSequence)Q.addAction(o(s,E));Q.makeLooping(),a!==Q&&a.addAction(Q)}const B=new ng("tap "+this.name+" for "+this.stateName+" on "+((C=this.target)==null?void 0:C.name),this.trigger=="tap"?Yg.tapTrigger(this.selfModel):Yg.sceneStartTrigger(),a);I&&B.makeExclusive(!0),A.addBehavior(B)}})}createAnimation(A,e,t){var C,a,B,Q;if(!this.target||!this.animator&&!this.animation)return;if(this.stateAnimationModel=e,this.animation&&this.animation.clip){this.animationSequence=new Array,this.animationLoopAfterSequence=new Array;const E=A.registerAnimation(this.target,this.animation.clip);E&&this.animationLoopAfterSequence.push(E);return}const i=(C=this.animator)==null?void 0:C.runtimeAnimatorController;let I=i==null?void 0:i.findState(this.stateName),o=[],s=[];if(i&&I){const E=new Array;E.push(I);let c=!1;for(;E.length<100;){if(!I||I===null||!I.transitions||I.transitions.length===0){(a=I.motion)!=null&&a.isLooping&&(c=!0);break}const d=I.transitions.find(h=>h.conditions.length===0),l=d?i.getState(d.destinationState,0):null;if(l&&E.includes(l)){I=l,c=!0;break}else if(d){if(I=l,!I)break;E.push(I)}else{c=((B=I.motion)==null?void 0:B.isLooping)??!1;break}}if(c&&I){const d=E.indexOf(I);o=E.slice(0,d),s=E.slice(d),Oq&&console.log("found loop from "+this.stateName,"states until loop",o,"states looping",s)}else o=E,s=[],Oq&&console.log("found no loop from "+this.stateName,"states",o)}if(o=o.filter(E=>{var c,d,l;return((c=E.motion)==null?void 0:c.clip)&&((l=(d=E.motion)==null?void 0:d.clip.tracks)==null?void 0:l.length)>0}),s=s.filter(E=>{var c,d,l;return((c=E.motion)==null?void 0:c.clip)&&((l=(d=E.motion)==null?void 0:d.clip.tracks)==null?void 0:l.length)>0}),o.length===0&&s.length===0){console.warn("No clips found for state "+this.stateName+" on "+((Q=this.animator)==null?void 0:Q.name)+", can't export animation data");return}const n=(E,c)=>{var l,h,p;if(!this.target)return;if(!((l=E.motion)!=null&&l.clip)){console.warn("No clip found for state "+E.name+" on "+((h=this.animator)==null?void 0:h.name)+", can't export animation data");return}const d=A.registerAnimation(this.target,E.motion.clip);d?c.push(d):console.warn("Couldn't register animation for state "+E.name+" on "+((p=this.animator)==null?void 0:p.name))};if(o.length>0){this.animationSequence=new Array;for(const E of o)n(E,this.animationSequence)}if(s.length>0){this.animationLoopAfterSequence=new Array;for(const E of s)n(E,this.animationLoopAfterSequence)}}},r(nD,"animationActions",[]),r(nD,"rootsWithExclusivePlayback",new Set),nD);let OB=Ga;yi([D(Zg)],OB.prototype,"animator",2);yi([D()],OB.prototype,"stateName",2);class jc extends RA{constructor(){super(...arguments);r(this,"target")}getType(){}getDuration(){}}yi([D(uA)],jc.prototype,"target",2);class Tu extends RA{constructor(){super(...arguments);r(this,"target")}}yi([D(jc)],Tu.prototype,"target",2);class Hu extends jc{constructor(){super(...arguments);r(this,"type",1);r(this,"duration",1)}getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}yi([D()],Hu.prototype,"type",2);yi([D()],Hu.prototype,"duration",2);class oF extends Tu{}var goA=Object.defineProperty,IoA=Object.getOwnPropertyDescriptor,ZC=(g,A,e,t)=>{for(var i=t>1?void 0:t?IoA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&goA(A,e,i),i};const Pq=IA("debugcharactercontroller");class cQ extends RA{constructor(){super(...arguments);r(this,"center",new w(0,0,0));r(this,"radius",.5);r(this,"height",2);r(this,"_rigidbody",null);r(this,"_activeGroundCollisions");r(this,"_contactVelocity",new w)}get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(vt),this._rigidbody||(this._rigidbody=this.gameObject.addNewComponent(vt)),this.rigidbody)}awake(){this._activeGroundCollisions=new Set}onEnable(){const e=this.rigidbody;let t=this.gameObject.getComponent(xC);t||(t=this.gameObject.addNewComponent(xC)),t.center.copy(this.center),t.radius=this.radius,t.height=this.height;const i=new w(0,0,1),I=new w(1,0,0),o=new w(0,1,0),s=this.gameObject.getWorldDirection(new w);s.y=0;const n=I.dot(s)<0?-1:1,C=i.angleTo(s)*n;this.gameObject.setRotationFromAxisAngle(o,C),e.lockRotationX=!0,e.lockRotationY=!0,e.lockRotationZ=!0}move(e){this.gameObject.position.add(e)}onCollisionEnter(e){(e.contacts.length==0||e.contacts.some(t=>t.normal.y>.2))&&(this._activeGroundCollisions.add(e),Pq&&console.log(`Collision(${this._activeGroundCollisions.size}): ${e.contacts.map(t=>t.normal.y.toFixed(2)).join(", ")} - ${this.isGrounded}`))}onCollisionExit(e){this._activeGroundCollisions.delete(e),Pq&&console.log(`Collision(${this._activeGroundCollisions.size}) - ${this.isGrounded}`)}get isGrounded(){return this._activeGroundCollisions.size>0}get contactVelocity(){var e;this._contactVelocity.set(0,0,0);for(const t of this._activeGroundCollisions){const i=(e=this.context.physics.engine)==null?void 0:e.getLinearVelocity(t.collider);i&&(this._contactVelocity.x+=i.x,this._contactVelocity.y+=i.y,this._contactVelocity.z+=i.z)}return this._contactVelocity}}ZC([D(w)],cQ.prototype,"center",2);ZC([D()],cQ.prototype,"radius",2);ZC([D()],cQ.prototype,"height",2);class jC extends RA{constructor(){super(...arguments);r(this,"controller");r(this,"movementSpeed",2);r(this,"rotationSpeed",2);r(this,"jumpForce",1);r(this,"doubleJumpForce",2);r(this,"animator");r(this,"lookForward",!0);r(this,"lookInput",new iA(0,0));r(this,"moveInput",new iA(0,0));r(this,"jumpInput",!1);r(this,"_currentSpeed",new w(0,0,0));r(this,"_currentAngularSpeed",new w(0,0,0));r(this,"_temp",new w(0,0,0));r(this,"_jumpCount",0);r(this,"_currentRotation");r(this,"_raycastOptions",new Bs)}awake(){this._currentRotation=new MA}update(){const e=this.context.input;e.isKeyPressed("KeyW")?this.moveInput.y+=1:e.isKeyPressed("KeyS")&&(this.moveInput.y-=1),e.isKeyPressed("KeyD")?this.lookInput.x+=1:e.isKeyPressed("KeyA")&&(this.lookInput.x-=1),this.jumpInput||(this.jumpInput=e.isKeyDown("Space"))}move(e){this.moveInput.add(e)}look(e){this.lookInput.add(e)}jump(){this.jumpInput=!0}onBeforeRender(){this.handleInput(this.moveInput,this.lookInput,this.jumpInput),this.lookInput.set(0,0),this.moveInput.set(0,0),this.jumpInput=!1}handleInput(e,t,i){var I,o,s,n,C,a,B,Q,E,c,d;if((I=this.controller)!=null&&I.isGrounded&&(this._jumpCount=0,this.doubleJumpForce>0&&((o=this.animator)==null||o.setBool("doubleJump",!1))),this._currentSpeed.z+=e.y*this.movementSpeed*this.context.time.deltaTime,(s=this.animator)==null||s.setBool("running",e.length()>.01),(C=this.animator)==null||C.setBool("jumping",((n=this.controller)==null?void 0:n.isGrounded)===!0&&i),this._temp.copy(this._currentSpeed),this._temp.applyQuaternion(this.gameObject.quaternion),this.controller?this.controller.move(this._temp):this.gameObject.position.add(this._temp),this._currentAngularSpeed.y+=te.toRadians(-t.x*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){const l=this.context.mainCameraComponent.forward;l.y=0,l.normalize(),this._currentRotation.setFromUnitVectors(new w(0,0,1),l),this.gameObject.quaternion.slerp(this._currentRotation,this.context.time.deltaTime*10)}if(this.gameObject.rotateY(this._currentAngularSpeed.y),this._currentSpeed.multiplyScalar(1-this.context.time.deltaTime*10),this._currentAngularSpeed.y*=1-this.context.time.deltaTime*10,this.controller&&i&&this.jumpForce>0){let l=(a=this.controller)==null?void 0:a.isGrounded;if(this.doubleJumpForce>0&&!((B=this.controller)!=null&&B.isGrounded)&&this._jumpCount===1&&(l=!0,(Q=this.animator)==null||Q.setBool("doubleJump",!0)),l){this._jumpCount+=1;const h=this.controller.rigidbody,p=this._jumpCount===2?this.doubleJumpForce:this.jumpForce;h.applyImpulse(new w(0,1,0).multiplyScalar(p))}}if(this.controller){const l=(E=this.controller)==null?void 0:E.rigidbody.getVelocity().y;if(l<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new io),this._raycastOptions.ray.origin.copy(_e(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);const h=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);const p=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(h),(p.length&&p[0].distance>2||l<-10)&&((c=this.animator)==null||c.setBool("falling",!0))}else(d=this.animator)==null||d.setBool("falling",!1)}}}ZC([D(cQ)],jC.prototype,"controller",2);ZC([D()],jC.prototype,"movementSpeed",2);ZC([D()],jC.prototype,"rotationSpeed",2);ZC([D()],jC.prototype,"jumpForce",2);ZC([D()],jC.prototype,"doubleJumpForce",2);ZC([D(Zg)],jC.prototype,"animator",2);var ooA=Object.defineProperty,soA=Object.getOwnPropertyDescriptor,noA=(g,A,e,t)=>{for(var i=t>1?void 0:t?soA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&ooA(A,e,i),i};class Yu extends hI{constructor(){super(...arguments);r(this,"intensity")}get typeName(){return"ChromaticAberration"}init(){this.intensity.defaultValue=0}onCreateEffect(){const e=new mY;return e.offset=new iA(0,0),e.radialModulation=!0,e.modulationOffset=.15,this.intensity.valueProcessor=t=>t*.02,this.intensity.onValueChanged=t=>{e.offset.x=-t,e.offset.y=t},e}}noA([D(qe)],Yu.prototype,"intensity",2);ds("ChromaticAberration",Yu);const Ou=new ue;Ou.setAttribute("position",new ie(new Float32Array([-1,-1,3,-1,-1,3]),2));Ou.setAttribute("uv",new ie(new Float32Array([0,0,2,0,0,2]),2));Ou.boundingSphere=new Ji;Ou.computeBoundingSphere=function(){};const CoA=new YC;class Or{constructor(A){this._mesh=new lA(Ou,A),this._mesh.frustumCulled=!1}render(A){A.render(this._mesh,CoA)}get material(){return this._mesh.material}set material(A){this._mesh.material=A}dispose(){this._mesh.material.dispose(),this._mesh.geometry.dispose()}}const aoA={uniforms:{sceneDiffuse:{value:null},sceneDepth:{value:null},sceneNormal:{value:null},projMat:{value:new GA},viewMat:{value:new GA},projViewMat:{value:new GA},projectionMatrixInv:{value:new GA},viewMatrixInv:{value:new GA},cameraPos:{value:new w},resolution:{value:new iA},time:{value:0},samples:{value:[]},bluenoise:{value:null},distanceFalloff:{value:1},radius:{value:5},near:{value:.1},far:{value:1e3},logDepth:{value:!1},ortho:{value:!1},screenSpaceRadius:{value:!1},frame:{value:0}},depthWrite:!1,depthTest:!1,vertexShader:`
5512
5512
  varying vec2 vUv;
5513
5513
  void main() {
@@ -6951,7 +6951,7 @@ void main() {
6951
6951
  vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
6952
6952
 
6953
6953
  #include <fog_vertex>
6954
- }`);new w(0,0,1);var SCA=function(g){el(e,g);var A=tl(e);function e(t){var i;return Ge(this,e),i=A.call(this,t),tA(ot(i),"positionBuffer",void 0),tA(ot(i),"previousBuffer",void 0),tA(ot(i),"nextBuffer",void 0),tA(ot(i),"uvBuffer",void 0),tA(ot(i),"sideBuffer",void 0),tA(ot(i),"widthBuffer",void 0),tA(ot(i),"colorBuffer",void 0),tA(ot(i),"indexBuffer",void 0),tA(ot(i),"vector_",new w),tA(ot(i),"vector2_",new w),tA(ot(i),"vector3_",new w),tA(ot(i),"quaternion_",new MA),i.maxParticles=1e4,i.setupBuffers(),i.rebuildMaterial(),i}return ke(e,[{key:"setupBuffers",value:function(){this.geometry&&this.geometry.dispose(),this.geometry=new ue,this.indexBuffer=new ie(new Uint32Array(this.maxParticles*6),1),this.indexBuffer.setUsage(rI),this.geometry.setIndex(this.indexBuffer),this.positionBuffer=new ie(new Float32Array(this.maxParticles*6),3),this.positionBuffer.setUsage(rI),this.geometry.setAttribute("position",this.positionBuffer),this.previousBuffer=new ie(new Float32Array(this.maxParticles*6),3),this.previousBuffer.setUsage(rI),this.geometry.setAttribute("previous",this.previousBuffer),this.nextBuffer=new ie(new Float32Array(this.maxParticles*6),3),this.nextBuffer.setUsage(rI),this.geometry.setAttribute("next",this.nextBuffer),this.widthBuffer=new ie(new Float32Array(this.maxParticles*2),1),this.widthBuffer.setUsage(rI),this.geometry.setAttribute("width",this.widthBuffer),this.sideBuffer=new ie(new Float32Array(this.maxParticles*2),1),this.sideBuffer.setUsage(rI),this.geometry.setAttribute("side",this.sideBuffer),this.uvBuffer=new ie(new Float32Array(this.maxParticles*4),2),this.uvBuffer.setUsage(rI),this.geometry.setAttribute("uv",this.uvBuffer),this.colorBuffer=new ie(new Float32Array(this.maxParticles*8),4),this.colorBuffer.setUsage(rI),this.geometry.setAttribute("color",this.colorBuffer)}},{key:"expandBuffers",value:function(i){for(;i>=this.maxParticles;)this.maxParticles*=2;this.setupBuffers()}},{key:"rebuildMaterial",value:function(){this.layers.mask=this.settings.layers.mask;var i={lineWidth:{value:1},map:{value:null},useMap:{value:0},alphaMap:{value:null},useAlphaMap:{value:0},resolution:{value:new iA(1,1)},sizeAttenuation:{value:1},visibility:{value:1},alphaTest:{value:0},repeat:{value:new iA(1,1)}},I={};if(I.USE_UV="",I.USE_COLOR_ALPHA="",this.settings.material.map&&(I.USE_MAP="",I.MAP_UV=nU(this.settings.material.map.channel),i.map=new yA(this.settings.material.map),i.mapTransform=new yA(new Le().copy(this.settings.material.map.matrix))),this.settings.renderMode===ne.Trail)this.material=new Ke({uniforms:i,defines:I,vertexShader:yCA,fragmentShader:wCA,transparent:this.settings.material.transparent,depthWrite:!this.settings.material.transparent,side:this.settings.material.side,blending:this.settings.material.blending||NB});else throw new Error("render mode unavailable")}},{key:"update",value:function(){var i=this,I=0,o=0,s=0;this.systems.forEach(function(n){for(var C=0;C<n.particleNum;C++)s+=n.particles[C].previous.length*2}),s>this.maxParticles&&this.expandBuffers(s),this.systems.forEach(function(n){var C=i.quaternion_,a=i.vector2_,B=i.vector3_;n.emitter.matrixWorld.decompose(a,C,B);for(var Q=n.particles,E=n.particleNum,c=i.settings.uTileCount,d=i.settings.vTileCount,l=1/c,h=1/d,p=0;p<E;p++){var u=Q[p],f=u.uvTile%d,k=Math.floor(u.uvTile/d),G=u.previous.values(),M=G.next(),m=M.value,N=m;M.done||(M=G.next());var y=void 0;M.value!==void 0?y=M.value:y=N;for(var U=0;U<u.previous.length;U++,I+=2){if(i.positionBuffer.setXYZ(I,N.position.x,N.position.y,N.position.z),i.positionBuffer.setXYZ(I+1,N.position.x,N.position.y,N.position.z),n.worldSpace?(i.positionBuffer.setXYZ(I,N.position.x,N.position.y,N.position.z),i.positionBuffer.setXYZ(I+1,N.position.x,N.position.y,N.position.z)):(u.parentMatrix?i.vector_.copy(N.position).applyMatrix4(u.parentMatrix):i.vector_.copy(N.position).applyMatrix4(n.emitter.matrixWorld),i.positionBuffer.setXYZ(I,i.vector_.x,i.vector_.y,i.vector_.z),i.positionBuffer.setXYZ(I+1,i.vector_.x,i.vector_.y,i.vector_.z)),n.worldSpace?(i.previousBuffer.setXYZ(I,m.position.x,m.position.y,m.position.z),i.previousBuffer.setXYZ(I+1,m.position.x,m.position.y,m.position.z)):(u.parentMatrix?i.vector_.copy(m.position).applyMatrix4(u.parentMatrix):i.vector_.copy(m.position).applyMatrix4(n.emitter.matrixWorld),i.previousBuffer.setXYZ(I,i.vector_.x,i.vector_.y,i.vector_.z),i.previousBuffer.setXYZ(I+1,i.vector_.x,i.vector_.y,i.vector_.z)),n.worldSpace?(i.nextBuffer.setXYZ(I,y.position.x,y.position.y,y.position.z),i.nextBuffer.setXYZ(I+1,y.position.x,y.position.y,y.position.z)):(u.parentMatrix?i.vector_.copy(y.position).applyMatrix4(u.parentMatrix):i.vector_.copy(y.position).applyMatrix4(n.emitter.matrixWorld),i.nextBuffer.setXYZ(I,i.vector_.x,i.vector_.y,i.vector_.z),i.nextBuffer.setXYZ(I+1,i.vector_.x,i.vector_.y,i.vector_.z)),i.sideBuffer.setX(I,-1),i.sideBuffer.setX(I+1,1),n.worldSpace)i.widthBuffer.setX(I,N.size),i.widthBuffer.setX(I+1,N.size);else if(u.parentMatrix)i.widthBuffer.setX(I,N.size),i.widthBuffer.setX(I+1,N.size);else{var H=(Math.abs(B.x)+Math.abs(B.y)+Math.abs(B.z))/3;i.widthBuffer.setX(I,N.size*H),i.widthBuffer.setX(I+1,N.size*H)}i.uvBuffer.setXY(I,(U/u.previous.length+f)*l,(d-k-1)*h),i.uvBuffer.setXY(I+1,(U/u.previous.length+f)*l,(d-k)*h),i.colorBuffer.setXYZW(I,N.color.x,N.color.y,N.color.z,N.color.w),i.colorBuffer.setXYZW(I+1,N.color.x,N.color.y,N.color.z,N.color.w),U+1<u.previous.length&&(i.indexBuffer.setX(o*3,I),i.indexBuffer.setX(o*3+1,I+1),i.indexBuffer.setX(o*3+2,I+2),o++,i.indexBuffer.setX(o*3,I+2),i.indexBuffer.setX(o*3+1,I+1),i.indexBuffer.setX(o*3+2,I+3),o++),m=N,N=y,M.done||(M=G.next(),M.value!==void 0&&(y=M.value))}}}),this.positionBuffer.updateRange.count=I*3,this.positionBuffer.needsUpdate=!0,this.previousBuffer.updateRange.count=I*3,this.previousBuffer.needsUpdate=!0,this.nextBuffer.updateRange.count=I*3,this.nextBuffer.needsUpdate=!0,this.sideBuffer.updateRange.count=I,this.sideBuffer.needsUpdate=!0,this.widthBuffer.updateRange.count=I,this.widthBuffer.needsUpdate=!0,this.uvBuffer.updateRange.count=I*2,this.uvBuffer.needsUpdate=!0,this.colorBuffer.updateRange.count=I*4,this.colorBuffer.needsUpdate=!0,this.indexBuffer.updateRange.count=o*3,this.indexBuffer.needsUpdate=!0,this.geometry.setDrawRange(0,o*3)}},{key:"dispose",value:function(){this.geometry.dispose()}}]),e}(RP),mCA=function(g){el(e,g);var A=tl(e);function e(){var t;return Ge(this,e),t=A.call(this),tA(ot(t),"batches",[]),tA(ot(t),"systemToBatchIndex",new Map),tA(ot(t),"type","BatchedRenderer"),t}return ke(e,[{key:"addSystem",value:function(i){i._renderer=this;for(var I=i.getRendererSettings(),o=0;o<this.batches.length;o++)if(e.equals(this.batches[o].settings,I)){this.batches[o].addSystem(i),this.systemToBatchIndex.set(i,o);return}var s;switch(I.renderMode){case ne.Trail:s=new SCA(I);break;case ne.Mesh:case ne.BillBoard:case ne.VerticalBillBoard:case ne.HorizontalBillBoard:case ne.StretchedBillBoard:s=new DCA(I);break}s.addSystem(i),this.batches.push(s),this.systemToBatchIndex.set(i,this.batches.length-1),this.add(s)}},{key:"deleteSystem",value:function(i){var I=this.systemToBatchIndex.get(i);I!=null&&(this.batches[I].removeSystem(i),this.systemToBatchIndex.delete(i))}},{key:"updateSystem",value:function(i){this.deleteSystem(i),this.addSystem(i)}},{key:"update",value:function(i){this.systemToBatchIndex.forEach(function(o,s){s.update(i)});for(var I=0;I<this.batches.length;I++)this.batches[I].update()}}],[{key:"equals",value:function(i,I){return i.material.side===I.material.side&&i.material.blending===I.material.blending&&i.material.transparent===I.material.transparent&&i.material.type===I.material.type&&i.material.alphaTest===I.material.alphaTest&&i.material.map===I.material.map&&i.renderMode===I.renderMode&&i.uTileCount===I.uTileCount&&i.vTileCount===I.vTileCount&&i.instancingGeometry===I.instancingGeometry&&i.renderOrder===I.renderOrder&&i.layers.mask===I.layers.mask}}]),e}(uA),GCA=mCA,_x=function(){function g(){var A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:new w;Ge(this,g),tA(this,"locations",[]),this.scaleX=A,this.scaleY=e,this.position=t}return ke(g,[{key:"transform",value:function(e,t){e.x=this.locations[t%this.locations.length].x*this.scaleX+this.position.x,e.y=this.locations[t%this.locations.length].y*this.scaleY+this.position.y,e.z=this.position.z}},{key:"clone",value:function(){var e=new g(this.scaleX,this.scaleY,this.position.clone());return e.locations=this.locations.map(function(t){return t.clone()}),e}},{key:"toJSON",value:function(){return{scaleX:this.scaleX,scaleY:this.scaleY,position:this.position,locations:this.locations.map(function(e){return{x:e.x,y:e.y}})}}},{key:"fromImage",value:function(e,t){var i=document.createElement("canvas");i.width=e.width,i.height=e.height;var I=i.getContext("2d");if(I){I.drawImage(e,0,0);var o=I.getImageData(0,0,i.width,i.height,{colorSpace:"srgb"});i.remove(),this.locations.length=0;for(var s=0;s<o.height;s++)for(var n=0;n<o.width;n++)o.data[(s*o.width+n)*4+3]>t&&this.locations.push(new iA(n,o.height-s))}}}],[{key:"fromJSON",value:function(e){var t=new g(e.scaleX,e.scaleY,new w(e.position[0],e.position[1],e.position[2]));return t.locations=e.locations.map(function(i){return new iA(i.x,i.y)}),t}}]),g}();function kCA(g){switch(g.type){case"TextureSequencer":return _x.fromJSON(g);default:return new _x}}var MCA=function(){function g(A){Ge(this,g),tA(this,"type","ApplySequences"),tA(this,"sequencers",[]),tA(this,"time",0),tA(this,"index",0),tA(this,"pCount",0),tA(this,"delay",void 0),tA(this,"tempV",new w),this.delay=A}return ke(g,[{key:"initialize",value:function(e){e.id=this.pCount,e.dst=new w,e.begin=new w,e.inMotion=!1,this.pCount++}},{key:"reset",value:function(){this.time=0,this.index=0,this.pCount=0}},{key:"update",value:function(e,t){var i=this.sequencers[this.index],I=e.id*this.delay;this.time>=i[0].a+I&&this.time<=i[0].b+I?(e.inMotion||(e.inMotion=!0,e.begin.copy(e.position),i[1].transform(e.dst,e.id)),e.position.lerpVectors(e.begin,e.dst,g.BEZIER.genValue((this.time-i[0].a-I)/(i[0].b-i[0].a)))):this.time>i[0].b+I&&(e.inMotion=!1)}},{key:"frameUpdate",value:function(e){for(;this.index+1<this.sequencers.length&&this.time>=this.sequencers[this.index+1][0].a;)this.index++;this.time+=e}},{key:"appendSequencer",value:function(e,t){this.sequencers.push([e,t])}},{key:"toJSON",value:function(){return{type:this.type,delay:this.delay,sequencers:this.sequencers.map(function(e){var t=WE(e,2),i=t[0],I=t[1];return{range:i.toJSON(),sequencer:I.toJSON()}})}}},{key:"clone",value:function(){var e=new g(this.delay);return e.sequencers=this.sequencers.map(function(t){return[t[0].clone(),t[1].clone()]}),e}}],[{key:"fromJSON",value:function(e){var t=new g(e.delay);return e.sequencers.forEach(function(i){t.sequencers.push([Pt(i.range),kCA(i.sequencer)])}),t}}]),g}();tA(MCA,"BEZIER",new gU(0,0,1,1));var cA=function(g){return g[g.Number=0]="Number",g[g.Vec2=1]="Vec2",g[g.Vec3=2]="Vec3",g[g.Vec4=3]="Vec4",g[g.Boolean=4]="Boolean",g[g.AnyType=5]="AnyType",g}({}),Tx=ke(function g(A,e,t,i){Ge(this,g),tA(this,"input",void 0),tA(this,"inputIndex",void 0),tA(this,"output",void 0),tA(this,"outputIndex",void 0),this.input=A,this.inputIndex=e,this.input.outputs[e].push(this),this.output=t,this.outputIndex=i,this.output.inputs[i]=this}),UCA=function(){function g(){Ge(this,g),tA(this,"visited",new Set),tA(this,"graph_",void 0),tA(this,"context_",void 0),g.Instance=this}return ke(g,[{key:"traverse",value:function(e){if(this.context_===void 0)throw new Error("context is undefined");if(this.graph_===void 0)throw new Error("graph is undefined");this.visited.add(e.id);for(var t=[],i=0;i<e.inputs.length;i++)if(e.inputs[i]instanceof Tx){var I=e.inputs[i].input;this.visited.has(I.id)||this.traverse(I),t.push(I.outputValues[e.inputs[i].inputIndex])}else t.push(e.inputs[i].getValue(this.context_));e.func(this.context_,t,e.outputValues),this.graph_.nodesInOrder.push(e)}},{key:"executeCompiledGraph",value:function(){if(this.context_===void 0)throw new Error("context is undefined");if(this.graph_===void 0)throw new Error("graph is undefined");for(var e=this.graph_.nodesInOrder,t=0;t<e.length;t++){for(var i=[],I=e[t],o=0;o<I.inputs.length;o++)if(I.inputs[o]instanceof Tx)i.push(I.inputs[o].input.outputValues[I.inputs[o].inputIndex]);else if(I.inputs[o]!==void 0)i.push(I.inputs[o].getValue(this.context_));else throw new Error("miss input for node ".concat(I.id));I.func(this.context_,i,I.outputValues)}}},{key:"run",value:function(e,t){if(this.graph_=e,this.context_=t,e.compiled)this.executeCompiledGraph();else{e.nodesInOrder.length=0,this.visited.clear();for(var i=0;i<e.outputNodes.length;i++){var I=e.outputNodes[i];this.traverse(I)}e.compiled=!0}}}]),g}();tA(UCA,"Instance",void 0);var Qt=function(){function g(A){Ge(this,g),tA(this,"name",void 0),tA(this,"nodeTypeSignatures",[]),this.name=A}return ke(g,[{key:"addSignature",value:function(e,t,i){this.nodeTypeSignatures.push({inputTypes:e,outputTypes:t,func:i})}}]),g}(),WS=new Qt("add");WS.addSignature([cA.Number,cA.Number],[cA.Number],function(g,A,e,t){t[0]=e[0]+e[1]});WS.addSignature([cA.Vec2,cA.Vec2],[cA.Vec2],function(g,A,e,t){t[0].addVectors(e[0],e[1])});WS.addSignature([cA.Vec3,cA.Vec3],[cA.Vec3],function(g,A,e,t){t[0].addVectors(e[0],e[1])});WS.addSignature([cA.Vec4,cA.Vec4],[cA.Vec4],function(g,A,e,t){t[0].addVectors(e[0],e[1])});var ZS=new Qt("sub");ZS.addSignature([cA.Number,cA.Number],[cA.Number],function(g,A,e,t){t[0]=e[0]-e[1]});ZS.addSignature([cA.Vec2,cA.Vec2],[cA.Vec2],function(g,A,e,t){t[0].subVectors(e[0],e[1])});ZS.addSignature([cA.Vec3,cA.Vec3],[cA.Vec3],function(g,A,e,t){t[0].subVectors(e[0],e[1])});ZS.addSignature([cA.Vec4,cA.Vec4],[cA.Vec4],function(g,A,e,t){t[0].subVectors(e[0],e[1])});var jS=new Qt("mul");jS.addSignature([cA.Number,cA.Number],[cA.Number],function(g,A,e,t){t[0]=e[0]*e[1]});jS.addSignature([cA.Vec2,cA.Number],[cA.Vec2],function(g,A,e,t){t[0].copy(e[0]).multiplyScalar(e[1])});jS.addSignature([cA.Vec3,cA.Number],[cA.Vec3],function(g,A,e,t){t[0].copy(e[0]).multiplyScalar(e[1])});jS.addSignature([cA.Vec4,cA.Number],[cA.Vec4],function(g,A,e,t){t[0].copy(e[0]).multiplyScalar(e[1])});var VS=new Qt("div");VS.addSignature([cA.Number,cA.Number],[cA.Number],function(g,A,e,t){t[0]=e[0]/e[1]});VS.addSignature([cA.Vec2,cA.Number],[cA.Vec2],function(g,A,e,t){t[0].copy(e[0]).divideScalar(e[1])});VS.addSignature([cA.Vec3,cA.Number],[cA.Vec3],function(g,A,e,t){t[0].copy(e[0]).divideScalar(e[1])});VS.addSignature([cA.Vec4,cA.Number],[cA.Vec4],function(g,A,e,t){t[0].copy(e[0]).divideScalar(e[1])});var RCA=new Qt("sin");RCA.addSignature([cA.Number],[cA.Number],function(g,A,e,t){t[0]=Math.sin(e[0])});var NCA=new Qt("cos");NCA.addSignature([cA.Number],[cA.Number],function(g,A,e,t){t[0]=Math.cos(e[0])});var FCA=new Qt("tan");FCA.addSignature([cA.Number],[cA.Number],function(g,A,e,t){t[0]=Math.tan(e[0])});var KCA=new Qt("abs");KCA.addSignature([cA.Number],[cA.Number],function(g,A,e,t){t[0]=Math.abs(e[0])});var JCA=new Qt("min");JCA.addSignature([cA.Number,cA.Number],[cA.Number],function(g,A,e,t){t[0]=Math.min(e[0],e[1])});var bCA=new Qt("max");bCA.addSignature([cA.Number,cA.Number],[cA.Number],function(g,A,e,t){t[0]=Math.max(e[0],e[1])});var MF=new Qt("dot");MF.addSignature([cA.Vec2,cA.Vec2],[cA.Number],function(g,A,e,t){t[0]=e[0].dot(e[1])});MF.addSignature([cA.Vec3,cA.Vec3],[cA.Number],function(g,A,e,t){t[0]=e[0].dot(e[1])});MF.addSignature([cA.Vec4,cA.Vec4],[cA.Number],function(g,A,e,t){t[0]=e[0].dot(e[1])});var vCA=new Qt("cross");vCA.addSignature([cA.Vec3,cA.Vec3],[cA.Vec3],function(g,A,e,t){t[0].crossVectors(e[0],e[1])});var UF=new Qt("length");UF.addSignature([cA.Vec2],[cA.Number],function(g,A,e,t){t[0]=e[0].length()});UF.addSignature([cA.Vec3],[cA.Number],function(g,A,e,t){t[0]=e[0].length()});UF.addSignature([cA.Vec4],[cA.Number],function(g,A,e,t){t[0]=e[0].length()});var RF=new Qt("lengthSq");RF.addSignature([cA.Vec2],[cA.Number],function(g,A,e,t){t[0]=e[0].lengthSq()});RF.addSignature([cA.Vec3],[cA.Number],function(g,A,e,t){t[0]=e[0].lengthSq()});RF.addSignature([cA.Vec4],[cA.Number],function(g,A,e,t){t[0]=e[0].lengthSq()});var NF=new Qt("normalize");NF.addSignature([cA.Vec2],[cA.Vec2],function(g,A,e,t){t[0].copy(e[0]).normalize()});NF.addSignature([cA.Vec3],[cA.Vec3],function(g,A,e,t){t[0].copy(e[0]).normalize()});NF.addSignature([cA.Vec4],[cA.Vec4],function(g,A,e,t){t[0].copy(e[0]).normalize()});var NP=new Qt("distance");NP.addSignature([cA.Vec2,cA.Vec2],[cA.Number],function(g,A,e,t){t[0]=e[0].distanceTo(e[1])});NP.addSignature([cA.Vec3,cA.Vec3],[cA.Number],function(g,A,e,t){t[0]=e[0].distanceTo(e[1])});var qCA=new Qt("and");qCA.addSignature([cA.Boolean,cA.Boolean],[cA.Boolean],function(g,A,e,t){t[0]=e[0]&&e[1]});var xCA=new Qt("or");xCA.addSignature([cA.Boolean,cA.Boolean],[cA.Boolean],function(g,A,e,t){t[0]=e[0]||e[1]});var LCA=new Qt("not");LCA.addSignature([cA.Boolean],[cA.Boolean],function(g,A,e,t){t[0]=!e[0]});var zS=new Qt("equal");zS.addSignature([cA.Number,cA.Number],[cA.Boolean],function(g,A,e,t){t[0]=e[0]===e[1]});zS.addSignature([cA.Vec2,cA.Vec2],[cA.Boolean],function(g,A,e,t){t[0]=e[0].equals(e[1])});zS.addSignature([cA.Vec3,cA.Vec3],[cA.Boolean],function(g,A,e,t){t[0]=e[0].equals(e[1])});zS.addSignature([cA.Vec4,cA.Vec4],[cA.Boolean],function(g,A,e,t){t[0]=e[0].equals(e[1])});var _CA=new Qt("lessThan");_CA.addSignature([cA.Number,cA.Number],[cA.Boolean],function(g,A,e,t){t[0]=e[0]<e[1]});var TCA=new Qt("greaterThan");TCA.addSignature([cA.Number,cA.Number],[cA.Boolean],function(g,A,e,t){t[0]=e[0]>e[1]});var HCA=new Qt("lessThanOrEqual");HCA.addSignature([cA.Number,cA.Number],[cA.Boolean],function(g,A,e,t){t[0]=e[0]<=e[1]});var YCA=new Qt("greaterThanOrEqual");YCA.addSignature([cA.Number,cA.Number],[cA.Boolean],function(g,A,e,t){t[0]=e[0]>=e[1]});var OCA=new Qt("if");OCA.addSignature([cA.Boolean,cA.AnyType,cA.AnyType],[cA.AnyType],function(g,A,e,t){t[0]=e[0]?e[1]:e[2]});var PCA=new Qt("number");PCA.addSignature([],[cA.Number],function(g,A,e,t){t[0]=A.value});var WCA=new Qt("vec2");WCA.addSignature([],[cA.Vec2],function(g,A,e,t){t[0]=A.value});var ZCA=new Qt("vec3");ZCA.addSignature([],[cA.Vec3],function(g,A,e,t){t[0]=A.value});var jCA=new Qt("vec4");jCA.addSignature([],[cA.Vec4],function(g,A,e,t){t[0]=A.value});var VCA=new Qt("bool");VCA.addSignature([],[cA.Boolean],function(g,A,e,t){t[0]=A.value});var zCA=new Qt("particlePosition");zCA.addSignature([],[cA.Vec3],function(g,A,e,t){t[0]=g.particle[A.property]});var XCA=new Qt("particleVelocity");XCA.addSignature([],[cA.Vec3],function(g,A,e,t){t[0]=g.particle[A.property]});var $CA=new Qt("particleRotation");$CA.addSignature([],[cA.Number],function(g,A,e,t){t[0]=g.particle[A.property]});var AaA=new Qt("particleAge");AaA.addSignature([],[cA.Number],function(g,A,e,t){t[0]=g.particle[A.property]});var Ip=new Qt("output");Ip.addSignature([cA.Number],[cA.Number],function(g,A,e,t){t[0]=e[0]});Ip.addSignature([cA.Vec2],[cA.Vec2],function(g,A,e,t){t[0]=e[0]});Ip.addSignature([cA.Vec3],[cA.Vec3],function(g,A,e,t){t[0]=e[0]});Ip.addSignature([cA.Vec4],[cA.Vec4],function(g,A,e,t){t[0]=e[0]});Ip.addSignature([cA.Boolean],[cA.Boolean],function(g,A,e,t){t[0]=e[0]});console.log("%c Particle system powered by three.quarks. https://quarks.art/","font-size: 16px; font-weight: bold;");var eaA=Object.defineProperty,taA=Object.getOwnPropertyDescriptor,Gi=(g,A,e,t)=>{for(var i=t>1?void 0:t?taA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&eaA(A,e,i),i};const hh=IA("debugparticles"),iaA=IA("noprogressive"),gaA=IA("debugprogressive");var CU=(g=>(g[g.Birth=0]="Birth",g[g.Collision=1]="Collision",g[g.Death=2]="Death",g[g.Trigger=3]="Trigger",g[g.Manual=4]="Manual",g))(CU||{});class ps extends RA{constructor(){super(...arguments);r(this,"renderMode");r(this,"particleMaterial");r(this,"trailMaterial");r(this,"particleMesh");r(this,"maxParticleSize");r(this,"minParticleSize");r(this,"velocityScale");r(this,"cameraVelocityScale");r(this,"lengthScale")}start(){if(this.maxParticleSize!==.5&&this.minParticleSize!==0&&he()){const e=`ParticleSystem "${this.name}" has non-default min/max particle size. This may not render correctly. Please set min size to 0 and the max size to 0.5 and use the "StartSize" setting instead`;console.warn(e)}}get transparent(){var t;return((t=this.particleMaterial)==null?void 0:t.transparent)??!1}getMaterial(e=!1){let t=e===!0&&this.trailMaterial?this.trailMaterial:this.particleMaterial;return t&&e&&t.side===Pg&&(t=t.clone(),t.side=Ki,e?this.trailMaterial=t:this.particleMaterial=t),t&&!iaA&&t._didRequestTextureLOD===void 0&&(t._didRequestTextureLOD=0,gaA&&console.log("Load material LOD",t.name),Kt.assignTextureLOD(this.context,this.sourceId,t)),t}getMesh(e){let t=null;if(!t&&(this.particleMesh instanceof lA&&(t=this.particleMesh.geometry),t===null)){t=new Xi(1,1);const I=t.attributes.uv;for(let o=0;o<I.count;o++)I.setX(o,1-I.getX(o))}return new lA(t,this.getMaterial())}}Gi([D()],ps.prototype,"renderMode",2);Gi([D(be)],ps.prototype,"particleMaterial",2);Gi([D(be)],ps.prototype,"trailMaterial",2);Gi([D()],ps.prototype,"maxParticleSize",2);Gi([D()],ps.prototype,"minParticleSize",2);Gi([D()],ps.prototype,"velocityScale",2);Gi([D()],ps.prototype,"cameraVelocityScale",2);Gi([D()],ps.prototype,"lengthScale",2);class zf{constructor(A,e=1){r(this,"_curve");r(this,"_factor");r(this,"type","function");this._curve=A,this._factor=e}genValue(A){return this._curve.evaluate(A,Math.random())*this._factor}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}}class FF{constructor(A){r(this,"type","value");r(this,"system");this.system=A}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}}class IaA extends FF{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class oaA extends FF{constructor(){super(...arguments);r(this,"_lastPosition",new w);r(this,"_lastDistance",0)}update(){const e=_e(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(e),this._lastPosition.copy(e)}genValue(){if(!this.system.isPlaying||!this.system.emission.enabled||this.system.currentParticles>=this.system.maxParticles)return 0;let e=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){const I=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let s=this._lastDistance/this.system.deltaTime*I;Number.isFinite(s)||(s=0),e+=s}const t=this.system.emission.getBurst();t>0&&(e+=t/this.system.deltaTime);const i=this.system.maxParticles-this.system.currentParticles;return te.clamp(e,0,i/this.system.deltaTime)}}class saA extends FF{genValue(){return this.system.isPlaying,0}}class Sr{constructor(A){r(this,"system");r(this,"type");this.type=Object.getPrototypeOf(this).constructor.name||"ParticleSystemBaseBehaviour",A&&(this.system=A)}get context(){return this.system.context}initialize(A){}update(A,e){}frameUpdate(A){}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}reset(){}}class naA extends Sr{constructor(){super(...arguments);r(this,"type","NeedleTextureSheet")}update(e,t){const i=this.system.textureSheetAnimation;if(i.enabled){const I=e.age/e.life,o=i.evaluate(I);o!==void 0&&(e.uvTile=o)}}}const Hx=Symbol("particleRotation");class CaA extends Sr{constructor(){super(...arguments);r(this,"type","NeedleRotation")}initialize(e){e[Hx]=Math.random()}update(e,t){if(e.rotation===void 0)return;const i=e.age/e.life;if(typeof e.rotation=="number"&&(this.system.rotationOverLifetime.enabled?e.rotation+=this.system.rotationOverLifetime.evaluate(i,e[Hx])*t:this.system.renderer.renderMode===cC.Billboard&&(e.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const I=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(i,I)*t}}}const Yx=Symbol("sizeLerpFactor"),aaA=new w;class raA extends Sr{constructor(){super(...arguments);r(this,"type","NeedleSize");r(this,"_minSize",0);r(this,"_maxSize",1)}initialize(e){e[Yx]=Math.random(),this._minSize=this.system.renderer.minParticleSize,this._maxSize=this.system.renderer.maxParticleSize}update(e,t){const i=e.age/e.life;let I=1;this.system.sizeOverLifetime.enabled&&(I*=this.system.sizeOverLifetime.evaluate(i,void 0,e[Yx]).x);let o=1;if(this.system.renderer.renderMode!==cC.Mesh&&(o=this.system.worldScale.x/this.system.cameraScale),e.size=e.startSize*I*o,this.system.localspace){const s=FP(this.system,aaA);e.size*=s.x}}}const FE=Symbol("particleLife"),KG=Symbol("trailLifetime"),Ox=Symbol("trailStartLength"),JG=Symbol("trailWidthRandom");class BaA extends Sr{constructor(){super(...arguments);r(this,"type","NeedleTrail")}initialize(e){e instanceof Ld&&(e[FE]=e.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(e[KG]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),e.life+=e[KG]),e[Ox]=e.length,e[JG]=Math.random())}update(e){var t;if((t=this.system.trails)!=null&&t.enabled&&e instanceof Ld){const i=e,I=e.age/e[FE],o=e.previous.values(),s=e.previous.length;for(let n=0;n<s;n++){const a=o.next().value,B=1-n/(s-1);let Q=e.size;Q<=0&&!this.system.trails.sizeAffectsWidth&&(Q=20*this.system.trails.widthOverTrail.evaluate(.5,i[JG])),a.size=this.system.trails.getWidth(Q,I,B,i[JG]),a.color.copy(e.color),this.system.trails.getColor(a.color,I,B)}if(e.age>e[FE]){e.velocity.set(0,0,0);const n=(e.age-e[FE])/e[KG];i.length=te.lerp(e[Ox],0,n)}}}}const Xf=Symbol("startVelocity"),Px=Symbol("gravityModifier"),bG=Symbol("gravitySpeed"),$f=Symbol("velocity lerp factor"),aU=new w;class QaA extends Sr{constructor(){super(...arguments);r(this,"type","NeedleVelocity");r(this,"_gravityDirection",new w)}initialize(e){var I,o;const t=this.system.main.simulationSpeed;e.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random()),e.velocity.copy(this.system.shape.getDirection(e,e.position)).multiplyScalar(e.startSpeed),(I=this.system.inheritVelocity)!=null&&I.enabled&&this.system.inheritVelocity.applyInitial(e.velocity),e[Xf]?e[Xf].copy(e.velocity):e[Xf]=e.velocity.clone();const i=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());e[Px]=i*t,e[bG]=i*t*.5,e[$f]=Math.random(),(o=this.system.velocityOverLifetime)==null||o.init(e),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===vd.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(e,t){var Q;const i=e[Xf],I=e[Px];if(I!==0){const E=I*e[bG];aU.copy(this._gravityDirection).multiplyScalar(E),e[bG]+=t*.05,i.add(aU)}e.velocity.copy(i);const o=e.age/e.life;(Q=this.system.inheritVelocity)!=null&&Q.enabled&&this.system.inheritVelocity.applyCurrent(e.velocity,o,e[$f]);const s=this.system.noise;s.enabled&&s.apply(0,e.position,e.velocity,t,e.age,e.life);const n=this.system.sizeBySpeed;n!=null&&n.enabled&&(e.size=n.evaluate(e.velocity,o,e[$f],e.size));const C=this.system.colorBySpeed;C!=null&&C.enabled&&C.evaluate(e.velocity,e[$f],e.color);const a=this.system.velocityOverLifetime;a.enabled&&a.apply(e,0,e.position,e.velocity,t,e.age,e.life);const B=this.system.limitVelocityOverLifetime;B.enabled&&B.apply(e.position,i,e.velocity,e.size,o,t,1),this.system.worldspace&&e.velocity.multiply(this.system.worldScale)}}const Wx=Symbol("colorLerpFactor"),Zx=new Mt(1,1,1,1),Zr=new Mt(1,1,1,1);class EaA extends Sr{constructor(){super(...arguments);r(this,"type","NeedleColor")}initialize(e){}_init(e){const t=this.system.renderer.particleMaterial;Zr.copy(this.system.main.startColor.evaluate(Math.random())),t!=null&&t.color&&(Zx.copy(t.color),Zr.multiply(Zx)),Zr.convertLinearToSRGB(),e.startColor.set(Zr.r,Zr.g,Zr.b,Zr.alpha),e.color.copy(e.startColor),e[Wx]=Math.random()}update(e,t){if(e.age===0&&this._init(e),this.system.colorOverLifetime.enabled){const i=e.age/e.life,I=this.system.colorOverLifetime.color.evaluate(i,e[Wx]);e.color.set(I.r,I.g,I.b,I.alpha).multiply(e.startColor)}else e.color.copy(e.startColor)}}class caA{constructor(A){r(this,"system");r(this,"emission");r(this,"autoDestroy");r(this,"startLength");r(this,"emissionBursts");r(this,"onlyUsedByOther");r(this,"behaviors",[]);r(this,"rendererEmitterSettings",{startLength:new aI(220),followLocalOrigin:!1});r(this,"flatWhiteTexture");r(this,"clonedTexture",{original:void 0,clone:void 0});this.system=A,this.emission=new oaA(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 zf(this.system.main.startLifetime)}get startSpeed(){return new zf(this.system.main.startSpeed)}get startRotation(){return new zf(this.system.main.startRotation)}get startSize(){return new zf(this.system.main.startSize)}get startColor(){return new _w(new Ae(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new saA(this.system)}get instancingGeometry(){return this.system.renderer.getMesh(this.system.renderer.renderMode).geometry}get renderMode(){if(this.system.trails.enabled===!0)return ne.Trail;switch(this.system.renderer.renderMode){case cC.Billboard:return ne.BillBoard;case cC.Stretch:return ne.StretchedBillBoard;case cC.HorizontalBillboard:return ne.HorizontalBillBoard;case cC.VerticalBillboard:return ne.VerticalBillBoard;case cC.Mesh:return ne.Mesh}return ne.BillBoard}get speedFactor(){var e;let A=this.system.main.simulationSpeed;return((e=this.system.renderer)==null?void 0:e.renderMode)===cC.Stretch&&(A*=this.system.renderer.velocityScale??1),A}get texture(){const A=this.material;if(A&&A.map){const e=A.map;if(this.clonedTexture.original!==e||!this.clonedTexture.clone){const t=e.clone();t.premultiplyAlpha=!1,t.colorSpace=yt,this.clonedTexture.original=e,this.clonedTexture.clone=t}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=AO(new Mt(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new IaA(this.system)}get uTileCount(){var A;return this.anim.enabled?(A=this.anim)==null?void 0:A.numTilesX:void 0}get vTileCount(){var A;return this.anim.enabled?(A=this.anim)==null?void 0:A.numTilesY:void 0}get renderOrder(){return 1}get blending(){var A;return((A=this.system.renderer.particleMaterial)==null?void 0:A.blending)??Ya}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===vd.World}}class laA{constructor(){r(this,"burstIndex",0);r(this,"burstWaveIndex",0);r(this,"time",0);r(this,"waitEmiting",0)}}const _D=class extends RA{constructor(){super(...arguments);r(this,"_state");r(this,"colorOverLifetime");r(this,"main");r(this,"emission");r(this,"sizeOverLifetime");r(this,"shape");r(this,"noise");r(this,"trails");r(this,"velocityOverLifetime");r(this,"limitVelocityOverLifetime");r(this,"inheritVelocity");r(this,"colorBySpeed");r(this,"textureSheetAnimation");r(this,"rotationOverLifetime");r(this,"rotationBySpeed");r(this,"sizeBySpeed");r(this,"_cameraScale",1);r(this,"__worldQuaternion",new MA);r(this,"_worldQuaternionInverted",new MA);r(this,"_worldScale",new w);r(this,"_worldPositionFrame",-1);r(this,"_worldPos",new w);r(this,"_renderer");r(this,"_batchSystem");r(this,"_particleSystem");r(this,"_interface");r(this,"_container");r(this,"_time",0);r(this,"_isPlaying",!0);r(this,"_isUsedAsSubsystem",!1);r(this,"_didPreWarm",!1);r(this,"_bursts");r(this,"_subEmitterSystems");r(this,"_lastBatchesCount",-1);r(this,"lastMaterialVersion",-1)}play(A=!1){var e;A&&aA.foreachComponent(this.gameObject,t=>{t instanceof _D&&t!==this&&t.play(!1)},!0),this._isPlaying=!0,this._particleSystem&&(this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1),(e=this.emission)==null||e.reset()}pause(A=!0){A&&aA.foreachComponent(this.gameObject,e=>{e instanceof _D&&e!==this&&e.pause(!1)},!0),this._isPlaying=!1}stop(A=!0,e=!1){A&&aA.foreachComponent(this.gameObject,t=>{t instanceof _D&&t!==this&&t.stop(!1,e)},!0),this._isPlaying=!1,this._time=0,e&&this.reset()}reset(){var A;this._time=0,this._particleSystem&&(this._particleSystem.particleNum=0,this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1,(A=this.emission)==null||A.reset())}emit(A){if(this._particleSystem){this.onUpdate(),A=Math.min(A,this.maxParticles-this.currentParticles),this._state||(this._state=new laA),this._state.waitEmiting=A,this._state.time=0;const e=this._particleSystem.emitEnded;this._particleSystem.emitEnded=!1,this._particleSystem.emit(this.deltaTime,this._state,this._particleSystem.emitter.matrixWorld),this._particleSystem.emitEnded=e}}get playOnAwake(){return this.main.playOnAwake}set playOnAwake(A){this.main.playOnAwake=A}get renderer(){return this._renderer}get isPlaying(){return this._isPlaying}get currentParticles(){var A;return((A=this._particleSystem)==null?void 0:A.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===vd.World}get localspace(){return this.main.simulationSpace===vd.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,_e(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}addBehaviour(A){return this._particleSystem?(A instanceof Sr&&(A.system=this),he()&&console.log("add behaviour",A),this._particleSystem.addBehavior(A),!0):!1}removeBehaviour(A){if(!this._particleSystem)return!1;const e=this._particleSystem.behaviors,t=e.indexOf(A);return t!==-1&&e.splice(t,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(A){for(let e=0;e<A.length;e++){const t=A[e];if(!(t instanceof qd)){const i=new qd;nc(i,t),A[e]=i}}this._bursts=A}set subEmitterSystems(A){for(let e=0;e<A.length;e++){const t=A[e];if(!(t instanceof Hd)){const i=new Hd;nc(i,t),A[e]=i}}hh&&A.length>0&&console.log("SubEmitters: ",A,this),this._subEmitterSystems=A}onAfterDeserialize(A){if(this._subEmitterSystems&&Array.isArray(this._subEmitterSystems))for(const e of this._subEmitterSystems)e._deserialize(this.context,this.gameObject)}awake(){if(this._worldPositionFrame=-1,this._renderer=this.gameObject.getComponent(ps),!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 uA,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new GCA,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new caA(this),this._particleSystem=new lCA(this._interface),this._particleSystem.addBehavior(new raA(this)),this._particleSystem.addBehavior(new EaA(this)),this._particleSystem.addBehavior(new naA(this)),this._particleSystem.addBehavior(new CaA(this)),this._particleSystem.addBehavior(new QaA(this)),this._particleSystem.addBehavior(new BaA(this)),this._batchSystem.addSystem(this._particleSystem);const A=this._particleSystem.emitter;this.context.scene.add(A),this.inheritVelocity.system&&this.inheritVelocity.system!==this&&(this.inheritVelocity=this.inheritVelocity.clone()),this.inheritVelocity.awake(this),hh&&(console.log(this),this.gameObject.add(new Cs(1)))}start(){this.addSubParticleSystems(),this.updateLayers()}onDestroy(){var A,e,t,i;(A=this._container)==null||A.removeFromParent(),(e=this._batchSystem)==null||e.removeFromParent(),(t=this._particleSystem)==null||t.emitter.removeFromParent(),(i=this._particleSystem)==null||i.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 A;this.main&&(this._didPreWarm===!1&&((A=this.main)==null?void 0:A.prewarm)===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){var C;if(!((C=this.emission)!=null&&C.enabled)||this.emission.rateOverTime.getMax()<=0)return;const e=1/60,t=this.main.duration,i=this.main.startLifetime.getMax(),I=1e3,o=Math.min(Math.max(t,i)/Math.max(.01,this.main.simulationSpeed),I),s=Math.ceil(o/e),n=Date.now();hh&&console.log(`Particles ${this.name} - Prewarm for ${s} frames (${o} sec). Duration: ${t}, Lifetime: ${i}`);for(let a=0;a<s&&!(this.currentParticles>=this.maxParticles);a++){const B=Date.now()-n;if(B>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${B}`);break}this.onUpdate(),this.onSimulate(e)}}onSimulate(A){if(this._batchSystem){let e=this.context.time.frameCount%60===0;this._lastBatchesCount!==this._batchSystem.batches.length&&(this._lastBatchesCount=this._batchSystem.batches.length,e=!0),e&&this.updateLayers(),this._batchSystem.update(A)}this._time+=A,this._time>this.duration&&(this._time=0)}updateLayers(){if(this._batchSystem)for(let A=0;A<this._batchSystem.batches.length;A++){const e=this._batchSystem.batches[A];e.layers.disableAll();const t=this.layer;e.layers.mask=1<<t}}onUpdate(){var I,o;const A=this.renderer.getMaterial(this.trails.enabled);if(A&&A.version!=this.lastMaterialVersion&&this._particleSystem&&(this.lastMaterialVersion=A.version,this._particleSystem.texture=this._interface.texture),this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const e=this.context.mainCamera;if(e){const s=Vt(e);this._cameraScale=s.x}const t=!this.worldspace,i=this.gameObject;if(Jt(i,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),Vt(this.gameObject,this._worldScale),t&&this._container&&((I=this.gameObject)!=null&&I.parent)){const s=FP(this,aU);this._container.matrix.makeScale(s.x,s.y,s.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.update(this,this.context,this.main.simulationSpace,this.gameObject),this.noise.update(this.context),(o=this.inheritVelocity)==null||o.update(this.context),this.velocityOverLifetime.update(this)}addSubParticleSystems(){var A;if(this._subEmitterSystems&&this._particleSystem)for(const e of this._subEmitterSystems){e.particleSystem&&(e.particleSystem.__internalAwake?e.particleSystem.__internalAwake():he()&&console.warn("SubParticleSystem serialization issue(?)",e.particleSystem,e));const t=(A=e.particleSystem)==null?void 0:A._particleSystem;if(t){e.particleSystem._isUsedAsSubsystem=!0;const i=new XS(this,this._particleSystem,e.particleSystem,t);i.emitterType=e.type,i.emitterProbability=e.emitProbability,this._particleSystem.addBehavior(i)}else hh&&console.warn("Could not add SubParticleSystem",e,this)}}};let zi=_D;Gi([D(Zu)],zi.prototype,"colorOverLifetime",2);Gi([D(eI)],zi.prototype,"main",2);Gi([D(Tn)],zi.prototype,"emission",2);Gi([D(fr)],zi.prototype,"sizeOverLifetime",2);Gi([D(Si)],zi.prototype,"shape",2);Gi([D(Nt)],zi.prototype,"noise",2);Gi([D(Bi)],zi.prototype,"trails",2);Gi([D(mi)],zi.prototype,"velocityOverLifetime",2);Gi([D(eg)],zi.prototype,"limitVelocityOverLifetime",2);Gi([D(Dr)],zi.prototype,"inheritVelocity",2);Gi([D(lQ)],zi.prototype,"colorBySpeed",2);Gi([D(tI)],zi.prototype,"textureSheetAnimation",2);Gi([D(us)],zi.prototype,"rotationOverLifetime",2);Gi([D(To)],zi.prototype,"rotationBySpeed",2);Gi([D(YI)],zi.prototype,"sizeBySpeed",2);class Hd{constructor(){r(this,"particleSystem");r(this,"emitProbability",1);r(this,"properties");r(this,"type")}_deserialize(A,e){const t=this.particleSystem;if(t instanceof zi)return;let i="";t&&typeof t.guid=="string"&&(i=t.guid,this.particleSystem=aA.findByGuid(i,e)),hh&&!(this.particleSystem instanceof zi)&&console.warn("Could not find particle system for sub emitter",i,e,this)}}function FP(g,A){if(A.set(1,1,1),g.gameObject.parent&&g.localspace)switch(g.main.scalingMode){case XM.Local:A=Vt(g.gameObject.parent,A),A.x=1/A.x,A.y=1/A.y,A.z=1/A.z;break;default:if(!g.unsupported_scaling_mode){g.unsupported_scaling_mode=!0;const e="ParticleSystem scale mode "+XM[g.main.scalingMode]+" is not supported";he()&&fi(e),console.warn(e,g.name,g)}A=Vt(g.gameObject,A);break}return A}new w(1,1,1);new w(0,0,1);class XS{constructor(A,e,t,i){r(this,"type","NeedleParticleSubEmitter");r(this,"emitterType");r(this,"emitterProbability");r(this,"q_",new MA);r(this,"v_",new w);r(this,"v2_",new w);r(this,"_emitterMatrix",new GA);r(this,"_circularBuffer");this.system=A,this.particleSystem=e,this.subSystem=t,this.subParticleSystem=i,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const I=1e3;this._circularBuffer=new as(()=>new GA,I)}clone(){throw new Error("Method not implemented.")}initialize(A){A.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===CU.Birth&&this.run(A)}update(A,e){this.run(A)}frameUpdate(A){}toJSON(){}reset(){}run(A){if(this.subSystem.currentParticles>=this.subSystem.main.maxParticles||!this.subParticleSystem||!A.emissionState||this.emitterProbability&&Math.random()>this.emitterProbability)return;const e=this.system.deltaTime;if(this.emitterType===CU.Death){let i=A.life;if(A[FE]!==void 0&&(i=A[FE]),!(A.age+e*1.2>=i))return;const o=this.subSystem.main.maxParticles-this.subSystem.currentParticles;A.emissionState.waitEmiting=o}const t=new GA;t.set(1,0,0,A.position.x,0,1,0,A.position.y,0,0,1,A.position.z,0,0,0,1),this.particleSystem.worldSpace||t.multiplyMatrices(this._emitterMatrix,t),this.subParticleSystem.emit(e,A.emissionState,t)}}var haA=Object.defineProperty,daA=Object.getOwnPropertyDescriptor,uaA=(g,A,e,t)=>{for(var i=t>1?void 0:t?daA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&haA(A,e,i),i};class op extends hI{constructor(){super(...arguments);r(this,"granularity")}get typeName(){return"PixelationEffect"}onCreateEffect(){const e=new MY;return this.granularity.onValueChanged=t=>{e.granularity=t},e}}uaA([D(qe)],op.prototype,"granularity",2);ds("PixelationEffect",op);class Qc extends RA{constructor(){super(...arguments);r(this,"_didAssignPlayerColor",!1);r(this,"tryAssignColor",()=>{const e=aA.getComponentInParent(this.gameObject,Is);if(e&&e.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(e.owner),!0;const t=aA.getComponentInParent(this.gameObject,sg);return t!=null&&t.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(t.connectionId),!0):!1})}onEnable(){this.context.connection.beginListen(It.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(It.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield Z2(.2),!this.tryAssignColor()););}assignUserColor(e){const t=Qc.hashCode(e),i=Qc.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){const I=this.gameObject;this.assignColor(i,e,I)}else if(this.gameObject.children)for(const I of this.gameObject.children){const o=I;o.material&&o.material.color&&this.assignColor(i,e,o)}}assignColor(e,t,i){let I=i.material;I&&(I._playerMaterial!==t&&(I=I.clone(),I._playerMaterial=t,i.material=I),I.color=e)}static hashCode(e){var t=0,i,I;if(e.length===0)return t;for(i=0;i<e.length;i++)I=e.charCodeAt(i),t=(t<<5)-t+I,t|=0;return t}static colorFromHashCode(e){const t=(e&16711680)>>16,i=(e&65280)>>8,I=e&255;return new mA(t/255,i/255,I/255)}}async function KF(g){const{NeedleEngineHTMLElement:A}=await Promise.resolve().then(()=>RBA);A.observedAttributes.includes(g)||A.observedAttributes.push(g)}var paA=Object.defineProperty,faA=Object.getOwnPropertyDescriptor,sp=(g,A,e,t)=>{for(var i=t>1?void 0:t?faA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&paA(A,e,i),i};const es=IA("debugskybox");KF("skybox-image");KF("environment-image");function jx(g,A,e,t,i){const I=new bn;I.allowDrop=!1,I.allowNetworking=!1,I.background=e,I.environment=t,aA.addComponent(g.scene,I);const o=s=>{typeof s=="string"&&(es&&console.log(i,"CHANGED TO",s),I.setSkybox(s))};return fT(g.domElement,i,o),I.addEventListener("destroy",()=>{es&&console.log("Destroyed attribute remote skybox",i),DT(g.domElement,i,o)}),I.setSkybox(A)}st.addContextCreatedCallback(g=>{var I;const A=g.context,e=A.domElement.getAttribute("skybox-image"),t=A.domElement.getAttribute("environment-image"),i=new Array;if(e){es&&console.log("Creating remote skybox to load "+e),((I=A.mainCameraComponent)==null?void 0:I.clearFlags)!==YB.Skybox&&console.warn('"skybox-image" attribute has no effect: camera clearflags are not set to "Skybox"');const o=jx(A,e,!0,!1,"skybox-image");i.push(o)}if(t){es&&console.log("Creating remote environment to load "+t);const o=jx(A,t,!1,!0,"environment-image");i.push(o)}return i.length>0?au(i):Promise.resolve()});function KP(){return globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES||(globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES=new Array),globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES}function Vx(g){const e=KP().find(t=>t.src===g);return e?(es&&console.log("Skybox: Found previously loaded texture for "+g),e.texture):null}async function DaA(g){const A=await g;rN(A,!0),Tt(A)}function waA(g,A){const e=KP();for(;e.length>5;){const t=e.shift();t&&DaA(t.texture)}A.then(t=>rN(t,!1)),e.push({src:g,texture:A})}class bn extends RA{constructor(){super(...arguments);r(this,"url");r(this,"allowDrop",!0);r(this,"background",!0);r(this,"environment",!0);r(this,"allowNetworking",!0);r(this,"_loader");r(this,"_prevUrl");r(this,"_prevLoadedEnvironment");r(this,"_prevEnvironment",null);r(this,"_prevBackground",null);r(this,"validTextureTypes",[".hdr",".exr",".jpg",".jpeg",".png"]);r(this,"onDragOverEvent",e=>{if(this.allowDrop&&e.dataTransfer)for(const t of e.dataTransfer.types)(t==="text/uri-list"||t==="Files")&&e.preventDefault()});r(this,"onDrop",e=>{var t,i,I,o;if(this.allowDrop&&e.dataTransfer){for(const s of e.dataTransfer.types)if(es&&console.log(s),s==="text/uri-list"){const n=e.dataTransfer.getData(s);es&&console.log(s,n);let C=(i=(t=new RegExp(/polyhaven.com\/asset_img\/.+?\/(?<name>.+)\.png/).exec(n))==null?void 0:t.groups)==null?void 0:i.name;if(C||(C=(o=(I=new RegExp(/polyhaven\.com\/a\/(?<name>.+)/).exec(n))==null?void 0:I.groups)==null?void 0:o.name),es&&console.log(C),C){const a="https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/"+C+"_1k.exr";console.log(`[Remote Skybox] Setting skybox from url: ${a}`),e.preventDefault(),this.setSkybox(a);break}else if(this.isValidTextureType(n)){console.log("[Remote Skybox] Setting skybox from url: "+n),e.preventDefault(),this.setSkybox(n);break}else{console.warn(`[RemoteSkybox] Unknown url ${n}. 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 a=new CustomEvent("dropped-unknown-url",{detail:{sender:this,event:e,url:n,apply:B=>{e.preventDefault(),this.setSkybox(B)}}});this.dispatchEvent(a)}}else if(s=="Files"){const n=e.dataTransfer.files.item(0);if(es&&console.log(s,n),!n)continue;if(!this.isValidTextureType(n.name)){console.warn(`[RemoteSkybox]: File "${n.name}" is not supported. Supported files are ${this.validTextureTypes.join(", ")}`);return}if(Vx(n.name)===null){const C=new Blob([n]),a=URL.createObjectURL(C);e.preventDefault(),this.setSkybox(a,n.name)}else e.preventDefault(),this.setSkybox(n.name);break}}})}onEnable(){this.setSkybox(this.url),this.registerDropEvents()}onDisable(){var e;this.context.scene.environment===this._prevLoadedEnvironment&&(this.context.scene.environment=this._prevEnvironment,Wt.backgroundShouldBeTransparent(this.context)||(this.context.scene.background=this._prevBackground),this._prevLoadedEnvironment=void 0),this.unregisterDropEvents(),(e=this.context.mainCameraComponent)==null||e.applyClearFlags()}urlChangedSyncField(){this.allowNetworking&&this.url&&this.isRemoteTexture(this.url)&&this.setSkybox(this.url)}async setSkybox(e,t){var o;if(!this.activeAndEnabled||!e)return!1;if(t??(t=e),this.isValidTextureType(t)||console.warn("Potentially invalid skybox url",t,"on",this.name),es&&console.log("Remote skybox url?: "+e),this._prevUrl===e&&this._prevLoadedEnvironment)return this.applySkybox(),!0;(o=this._prevLoadedEnvironment)==null||o.dispose(),this._prevLoadedEnvironment=void 0,this._prevUrl=e;const i=await this.loadTexture(e,t);if(!i||!this.enabled)return!1;this.url=e;const I=e.lastIndexOf("/");return i.name=e.substring(I>=0?I+1:0),this._loader instanceof Un&&(i.colorSpace=de),this._prevLoadedEnvironment=i,this.applySkybox(),!0}async loadTexture(e,t){var C,a,B,Q,E;if(!e)return Promise.resolve(null);t??(t=e);const i=Vx(t);if(i){const c=await i;if(((a=(C=c.source)==null?void 0:C.data)==null?void 0:a.length)>0||(E=(Q=(B=c.source)==null?void 0:B.data)==null?void 0:Q.data)!=null&&E.length)return c}const I=t.endsWith(".exr"),o=t.endsWith(".hdr");I?this._loader instanceof Uw||(this._loader=new Uw):o?this._loader instanceof JM||(this._loader=new JM):this._loader instanceof Un||(this._loader=new Un),es&&console.log("Loading skybox: "+e);const s=this._loader.loadAsync(e);return waA(t,s),await s}applySkybox(){var t;const e=this._prevLoadedEnvironment;e&&(e.mapping=zE,e.needsUpdate=!0,this.context.scene.background!==e&&(this._prevBackground=this.context.scene.background),this.context.scene.environment!==e&&(this._prevEnvironment=this.context.scene.environment),es&&console.log("Set remote skybox",this.url),this.environment&&(this.context.scene.environment=e),this.background&&!Wt.backgroundShouldBeTransparent(this.context)&&(this.context.scene.background=e),((t=this.context.mainCameraComponent)==null?void 0:t.backgroundBlurriness)!==void 0&&(this.context.scene.backgroundBlurriness=this.context.mainCameraComponent.backgroundBlurriness))}isRemoteTexture(e){return e.startsWith("http://")||e.startsWith("https://")}isValidTextureType(e){for(const t of this.validTextureTypes)if(e.endsWith(t))return!0;return!1}registerDropEvents(){this.unregisterDropEvents(),this.context.domElement.addEventListener("dragover",this.onDragOverEvent),this.context.domElement.addEventListener("drop",this.onDrop)}unregisterDropEvents(){this.context.domElement.removeEventListener("dragover",this.onDragOverEvent),this.context.domElement.removeEventListener("drop",this.onDrop)}}sp([HN(bn.prototype.urlChangedSyncField),D(URL)],bn.prototype,"url",2);sp([D()],bn.prototype,"allowDrop",2);sp([D()],bn.prototype,"background",2);sp([D()],bn.prototype,"environment",2);sp([D()],bn.prototype,"allowNetworking",2);var yaA=Object.defineProperty,SaA=Object.getOwnPropertyDescriptor,Ho=(g,A,e,t)=>{for(var i=t>1?void 0:t?SaA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&yaA(A,e,i),i};const po=IA("debugsceneswitcher"),TD="scene";KF(TD);const wa=Promise.resolve(!1);class uI extends RA{constructor(){super(...arguments);r(this,"autoLoadFirstScene",!0);r(this,"scenes");r(this,"loadingScene");r(this,"queryParameterName","scene");r(this,"useSceneName",!0);r(this,"clamp",!0);r(this,"useHistory",!0);r(this,"useKeyboard",!0);r(this,"useSwipe",!0);r(this,"useSceneLighting",!0);r(this,"preloadNext",1);r(this,"preloadPrevious",1);r(this,"preloadConcurrent",2);r(this,"_currentIndex",-1);r(this,"_currentScene");r(this,"_engineElementOverserver");r(this,"_preloadScheduler");r(this,"onPopState",async e=>{if(!this.useHistory)return;const t=this.useHistory;try{this.useHistory=!1;let i=!1;if(this.queryParameterName&&(i=await this.tryLoadFromQueryParam()),!i){const I=e==null?void 0:e.state;if(I&&I.startsWith(this.guid)){const o=I.substr(this.guid.length+2);po&&console.log("PopState",o),await this.trySelectSceneFromValue(o)}}}finally{this.useHistory=t}});r(this,"normalizedSwipeThresholdX",.1);r(this,"_didSwipe",!1);r(this,"onInputPointerMove",e=>{if(this.useSwipe&&!this._didSwipe&&e.button===0&&e.pointerType==="touch"&&this.context.input.getPointerPressedCount()===1){const t=this.context.input.getPointerPositionDelta(e.button);if(t){const i=t.x/this.context.domWidth;i>=this.normalizedSwipeThresholdX?(this._didSwipe=!0,this.selectPrev()):i<=-this.normalizedSwipeThresholdX&&(this._didSwipe=!0,this.selectNext())}}});r(this,"onInputPointerUp",e=>{e.button===0&&(this._didSwipe=!1)});r(this,"onInputKeyDown",e=>{if(!this.useKeyboard||!this.scenes)return;const t=e.key.toLowerCase();if(!t)return;const i=parseInt(t)-1;if(i>=0){this.trySelectSceneFromValue(i);return}switch(t){case"arrowright":case"d":this.selectNext();break;case"arrowleft":case"a":this.selectPrev();break}});r(this,"__lastSwitchScene");r(this,"__lastSwitchScenePromise");r(this,"_currentlyLoadingScene");r(this,"_lastLoadingScene");r(this,"_loadingScenePromise");r(this,"_isCurrentlyLoading",!1);r(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=[]),po&&console.log("SceneSwitcher",this)}async onEnable(){if(globalThis.addEventListener("popstate",this.onPopState),this.context.input.addEventListener(ni.KeyDown,this.onInputKeyDown),this.context.input.addEventListener(ni.PointerMove,this.onInputPointerMove),this.context.input.addEventListener(ni.PointerUp,this.onInputPointerUp),this._engineElementOverserver||(this._engineElementOverserver=new MutationObserver(e=>{for(const t of e)if(t.type==="attributes"&&t.attributeName===TD){const i=this.context.domElement.getAttribute(TD);i!==null&&this.trySelectSceneFromValue(i)}})),this._engineElementOverserver.observe(this.context.domElement,{attributes:!0}),this._preloadScheduler||(this._preloadScheduler=new maA(this)),this._preloadScheduler.maxLoadAhead=this.preloadNext,this._preloadScheduler.maxLoadBehind=this.preloadPrevious,this._preloadScheduler.maxConcurrent=this.preloadConcurrent,this._preloadScheduler.begin(),this.autoLoadFirstScene&&this._currentIndex===-1&&!await this.tryLoadFromQueryParam()){const e=this.context.domElement.getAttribute(TD);try{(e===null||!await this.trySelectSceneFromValue(e))&&this._currentIndex===-1&&this.select(0)}finally{}}}onDisable(){var e;globalThis.removeEventListener("popstate",this.onPopState),this.context.input.removeEventListener(ni.KeyDown,this.onInputKeyDown),this.context.input.removeEventListener(ni.PointerMove,this.onInputPointerMove),this.context.input.removeEventListener(ni.PointerUp,this.onInputPointerUp),(e=this._preloadScheduler)==null||e.stop()}addScene(e){if(typeof e=="string"){let t=this.context.addressables.findAssetReference(e);return t||(t=new tt(e),this.context.addressables.registerAssetReference(t)),this.scenes.push(t),t}return this.scenes.push(e),e}selectNext(){return this.select(this._currentIndex+1)}selectPrev(){return this.select(this._currentIndex-1)}select(e){var i,I,o;if(po&&console.log("select",e),typeof e=="object"&&console.warn('Switching to "'+e+'" might not work. Please either use an index or a AssetReference (not a scene reference)'),typeof e=="string"){const s=(i=this.scenes)==null?void 0:i.find(n=>n.uri===e);if(!s){const n=tt.getOrCreate(this.sourceId??"",e,this.context);return this.switchScene(n)}if(s)e=(I=this.scenes)==null?void 0:I.indexOf(s);else return wa}if(!((o=this.scenes)!=null&&o.length))return wa;if(e<0){if(this.clamp)return wa;e=this.scenes.length-1}else if(e>=this.scenes.length){if(this.clamp)return wa;e=0}const t=this.scenes[e];return this.switchScene(t)}async switchScene(e){if(!(e instanceof tt)){const i=typeof e;return i==="string"?this.select(e):i==="number"?this.select(e):(console.warn("SceneSwitcher: Can't switch to scene",e,"of type",i),!1)}return e.uri===this.sourceId?(console.warn("SceneSwitcher: can't load own scene - prevent recursive loading",this.sourceId),!1):this.__lastSwitchScene===e&&this.__lastSwitchScenePromise?this.__lastSwitchScenePromise:(this.__lastSwitchScene=e,this.__lastSwitchScenePromise=this.__internalSwitchScene(e),await this.__lastSwitchScenePromise)}async __internalSwitchScene(e){var i,I;if(this._currentScene){po&&console.log("UNLOAD",e.uri);const o=this.tryGetSceneEventListener(this._currentScene.asset);if(o!=null&&o.sceneClosing){const s=o.sceneClosing();s instanceof Promise&&await s}this._currentScene.unload()}this._currentScene=void 0;const t=this._currentIndex=((i=this.scenes)==null?void 0:i.indexOf(e))??-1;try{this._currentlyLoadingScene=e,this._currentLoadingProgress=new ProgressEvent("progress",{loaded:0,total:1});const o=new CustomEvent("loadscene-start",{detail:{scene:e,switcher:this,index:t}});this.dispatchEvent(o),await this.onStartLoading(),await e.loadAssetAsync((n,C)=>{this._currentLoadingProgress=C,this.dispatchEvent(C)}).catch(console.error),await this.onEndLoading();const s=new CustomEvent("loadscene-finished",{detail:{scene:e,switcher:this,index:t}});if(this.dispatchEvent(s),this._currentLoadingProgress=void 0,this._currentlyLoadingScene=void 0,s.defaultPrevented)return po&&console.warn("Adding loaded scene prevented:",e,s),!1;if(!e.asset)return po&&console.warn("Failed loading scene:",e),!1;if(this._currentIndex===t){if(po&&console.log("ADD",e.uri),this._currentScene=e,aA.add(e.asset,this.gameObject),this.useSceneLighting&&this.context.sceneLighting.enable(e),this.useHistory&&t>=0){let a=t.toString();if(this.useSceneName&&(a=zx(e.uri)),(I=this.queryParameterName)!=null&&I.length)aw(this.queryParameterName,a,this.useHistory);else{const B=history.state,Q=this.guid+"::"+t;B!==Q&&history.pushState(Q,"unused",location.href)}}const n=this.tryGetSceneEventListener(e.asset);if(n!=null&&n.sceneOpened){const a=n.sceneOpened(this);a instanceof Promise&&await a}const C=new CustomEvent("scene-opened",{detail:{scene:e,switcher:this,index:t}});return this.dispatchEvent(C),!0}}catch(o){console.error(o)}return!1}preload(e){if(e>=0&&e<this.scenes.length){const t=this.scenes[e];if(t instanceof tt)return t.preload()}return wa}tryLoadFromQueryParam(){var t;if(!((t=this.queryParameterName)!=null&&t.length))return wa;const e=IA(this.queryParameterName);return typeof e=="boolean"?wa:this.trySelectSceneFromValue(e)}trySelectSceneFromValue(e){if(typeof e=="string"){const t=parseInt(e);if(t>=0&&t<this.scenes.length)return this.select(t);{const i=e.toLowerCase();for(let I=0;I<this.scenes.length;I++){const o=this.scenes[I];if(o&&zx(o.uri).toLowerCase().includes(i))return this.select(I)}}}else if(typeof e=="number"&&e>=0&&e<this.scenes.length)return this.select(e);return No()&&console.warn('Can not find scene: "'+e+'"',this),wa}async onStartLoading(){var e,t;if(this._isCurrentlyLoading=!0,this.loadingScene&&(this._lastLoadingScene!==this.loadingScene&&(this._loadingScenePromise=void 0),this._lastLoadingScene=this.loadingScene,this._loadingScenePromise||(this._loadingScenePromise=(e=this.loadingScene)==null?void 0:e.loadAssetAsync()),await this._loadingScenePromise,this._isCurrentlyLoading&&((t=this.loadingScene)!=null&&t.asset))){po&&console.log("Add loading scene",this.loadingScene.uri,this.loadingScene.asset);const i=this.loadingScene.asset;aA.add(i,this.gameObject);const I=this.tryGetSceneEventListener(i);if(I!=null&&I.sceneOpened){const o=I.sceneOpened(this);o instanceof Promise&&await o}}if(this._isCurrentlyLoading){const i=this.tryGetSceneEventListener(this.gameObject);if(i&&i.sceneOpened){const I=i.sceneOpened(this);I instanceof Promise&&await I}}}async onEndLoading(){var e;if(this._isCurrentlyLoading=!1,(e=this.loadingScene)!=null&&e.asset){po&&console.log("Remove loading scene",this.loadingScene.uri);const t=this.loadingScene.asset,i=this.tryGetSceneEventListener(t);if(typeof(i==null?void 0:i.sceneClosing)=="function"){const I=i.sceneClosing();I instanceof Promise&&await I}aA.remove(t)}if(!this._isCurrentlyLoading){const t=this.tryGetSceneEventListener(this.gameObject);if(t&&t.sceneClosing){const i=t.sceneClosing();i instanceof Promise&&await i}}}tryGetSceneEventListener(e,t=0){const i=aA.foreachComponent(e,I=>I.sceneClosing?I:void 0);if(t===0&&!i&&e.children.length)for(const I of e.children){const o=this.tryGetSceneEventListener(I,t+1);if(o)return o}return i||null}}Ho([D()],uI.prototype,"autoLoadFirstScene",2);Ho([D(tt)],uI.prototype,"scenes",2);Ho([D(tt)],uI.prototype,"loadingScene",2);Ho([D()],uI.prototype,"queryParameterName",2);Ho([D()],uI.prototype,"useSceneName",2);Ho([D()],uI.prototype,"clamp",2);Ho([D()],uI.prototype,"useHistory",2);Ho([D()],uI.prototype,"useKeyboard",2);Ho([D()],uI.prototype,"useSwipe",2);Ho([D()],uI.prototype,"useSceneLighting",2);Ho([D()],uI.prototype,"preloadNext",2);Ho([D()],uI.prototype,"preloadPrevious",2);Ho([D()],uI.prototype,"preloadConcurrent",2);function zx(g){const A=g.split("/").pop(),e=A==null?void 0:A.split(".").shift();return e!=null&&e.length?e:g}class maA{constructor(A,e=1,t=1,i=2){r(this,"maxLoadAhead");r(this,"maxLoadBehind");r(this,"maxConcurrent");r(this,"_isRunning",!1);r(this,"_switcher");r(this,"_loadTasks",[]);r(this,"_maxConcurrentLoads",1);this._switcher=A,this.maxLoadAhead=e,this.maxLoadBehind=t,this.maxConcurrent=i}begin(){if(this._isRunning)return;po&&console.log("Preload begin"),this._isRunning=!0;let A=-1,e,t;const i=this._switcher.scenes,I=setInterval(()=>{if(this.allLoaded()&&(po&&console.log("All scenes loaded"),this.stop()),!this._isRunning){clearInterval(I);return}if(this.canLoadNewScene()===!1)return;A!==this._switcher.currentIndex&&(A=this._switcher.currentIndex,t=0,e=0);const o=t%2===0;o&&(e+=1),t+=1;const s=o?this.maxLoadAhead:this.maxLoadBehind;if(e>s)return;const n=o?A+e:A-e;if(n<0||n<0||n>=i.length)return;const C=i[n];new GaA(n,C,this._loadTasks)},200)}stop(){this._isRunning=!1}canLoadNewScene(){return this._loadTasks.length<this._maxConcurrentLoads}allLoaded(){if(this._switcher.scenes){for(const A of this._switcher.scenes)if((A==null?void 0:A.isLoaded())===!1)return!1}return!0}}class GaA{constructor(A,e,t){r(this,"index");r(this,"asset");r(this,"tasks");this.index=A,this.asset=e,this.tasks=t,t.push(this),this.awaitLoading()}async awaitLoading(){this.asset&&!this.asset.isLoaded()&&(po&&console.log("Preload start: "+this.asset.uri,this.index),await this.asset.preload(),po&&console.log("Preload finished: "+this.asset.uri,this.index));const A=this.tasks.indexOf(this);A>=0&&this.tasks.splice(A,1)}}function kaA(){return new Promise((g,A)=>{const t=()=>{t!=null&&(document.removeEventListener("pointerdown",t),document.removeEventListener("click",t),document.removeEventListener("dragstart",t),document.removeEventListener("touchstart",t),g())};document.addEventListener("pointerdown",t),document.addEventListener("click",t),document.addEventListener("dragstart",t),document.addEventListener("touchstart",t)})}async function MaA(g){await kaA(),g()}var UaA=Object.defineProperty,RaA=Object.getOwnPropertyDescriptor,Yo=(g,A,e,t)=>{for(var i=t>1?void 0:t?RaA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&UaA(A,e,i),i};const ug=IA("debugvideo");var JP=(g=>(g[g.None=0]="None",g[g.AdjustHeight=1]="AdjustHeight",g[g.AdjustWidth=2]="AdjustWidth",g))(JP||{}),bP=(g=>(g[g.VideoClip=0]="VideoClip",g[g.Url=1]="Url",g))(bP||{}),vP=(g=>(g[g.CameraFarPlane=0]="CameraFarPlane",g[g.CameraNearPlane=1]="CameraNearPlane",g[g.RenderTexture=2]="RenderTexture",g[g.MaterialOverride=3]="MaterialOverride",g))(vP||{});class cg extends RA{constructor(){super();r(this,"playOnAwake",!0);r(this,"aspectMode",0);r(this,"clip",null);r(this,"source",1);r(this,"url",null);r(this,"renderMode");r(this,"targetMaterialProperty");r(this,"targetMaterialRenderer");r(this,"targetTexture");r(this,"time",0);r(this,"_playbackSpeed",1);r(this,"_isLooping",!1);r(this,"_muted",!1);r(this,"_audioOutputMode",2);r(this,"playInBackground",!0);r(this,"_crossOrigin","anonymous");r(this,"_videoElement",null);r(this,"_videoTexture",null);r(this,"_videoMaterial",null);r(this,"_isPlaying",!1);r(this,"wasPlaying",!1);r(this,"visibilityChanged",e=>{switch(document.visibilityState){case"hidden":this.playInBackground||(this.wasPlaying=this._isPlaying,this.pause());break;case"visible":this.wasPlaying&&!this._isPlaying&&this.play();break}});r(this,"_receivedInput",!1);r(this,"_overlay",null);r(this,"_targetObjects");r(this,"_updateAspectRoutineId",-1);r(this,"_hls");r(this,"onHlsAvailable",()=>{var e;ug&&console.log("HLS: available",this.clip),!(!this.shouldUseM3U8||!this.url)&&(this._hls||(this._hls=new Hls),this.videoElement.autoplay=!0,this._hls.loadSource(this.url),this._hls.attachMedia(this.videoElement),(e=this._videoElement)==null||e.play(),ug&&console.log("HLS: loaded",this.clip))});MaA(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[],IA("videoscreenspace")&&window.addEventListener("keydown",e=>{e.key==="f"&&(this.screenspace=!this.screenspace)})}get playbackSpeed(){var e;return((e=this._videoElement)==null?void 0:e.playbackRate)??this._playbackSpeed}set playbackSpeed(e){this._playbackSpeed=e,this._videoElement&&(this._videoElement.playbackRate=e)}get isLooping(){var e;return((e=this._videoElement)==null?void 0:e.loop)??this._isLooping}set isLooping(e){this._isLooping=e,this._videoElement&&(this._videoElement.loop=e)}get currentTime(){var e;return((e=this._videoElement)==null?void 0:e.currentTime)??this.time}set currentTime(e){this._videoElement?this._videoElement.currentTime=e:this.time=e}get isPlaying(){const e=this._videoElement;if(e){if(e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>e.HAVE_CURRENT_DATA)return!0;if(e.srcObject&&e.srcObject.active)return!0}return!1}get crossOrigin(){var e;return((e=this._videoElement)==null?void 0:e.crossOrigin)??this._crossOrigin}set crossOrigin(e){this._crossOrigin=e,this._videoElement&&(e!==null?this._videoElement.setAttribute("crossorigin",e):this._videoElement.removeAttribute("crossorigin"))}get videoMaterial(){return!this._videoMaterial&&!this.create(!1)?null:this._videoMaterial}get videoTexture(){return!this._videoTexture&&!this.create(!1)?null:this._videoTexture}get videoElement(){return!this._videoElement&&!this.create(!1)?null:this._videoElement}get muted(){var e;return((e=this._videoElement)==null?void 0:e.muted)??this._muted}set muted(e){this._muted=e,this._videoElement&&(this._videoElement.muted=e)}get currentVideo(){return this.clip}set audioOutputMode(e){e!==this._audioOutputMode&&(e===1&&he()&&console.warn("VideoAudioOutputMode.AudioSource is not yet implemented"),this._audioOutputMode=e,this.updateVideoElementSettings())}get audioOutputMode(){return this._audioOutputMode}preloadVideo(){ug&&console.log("Video Preload: "+this.name,this.clip),this.create(!1)}preload(){this.preloadVideo()}setVideo(e){this.clip=e,this.source=0,this._videoElement?(this._videoElement.srcObject=e,this._isPlaying&&this.play(),this.updateAspect()):this.create(this.playOnAwake)}setClipURL(e){this.url!==e&&(this.url=e,this.source=1,ug&&console.log("set url",e),this._videoElement?e.endsWith(".m3u8")?this.ensureM3U8CanBePlayed():(this._videoElement.src=e,this._isPlaying&&(this.stop(),this.play())):this.create(this.playOnAwake))}onEnable(){var e,t;ug&&console.log("VideoPlayer.onEnable",bP[this.source],this.clip,this.url,this),window.addEventListener("visibilitychange",this.visibilityChanged),this.playOnAwake===!0?this.create(!0):this.preloadVideo(),this.screenspace?(e=this._overlay)==null||e.start():(t=this._overlay)==null||t.stop()}onDisable(){var e;window.removeEventListener("visibilitychange",this.visibilityChanged),(e=this._overlay)==null||e.stop(),this.pause()}onDestroy(){var e;this._videoElement&&((e=this.videoElement)==null||e.remove(),this._videoElement=null),this._videoTexture&&(this._videoTexture.dispose(),this._videoTexture=null)}play(){var e,t;if(this._videoElement||this.create(!1),!this._videoElement){ug&&console.warn("Can not play: no video element found",this);return}if(!(this._isPlaying&&!((e=this._videoElement)!=null&&e.ended)&&!((t=this._videoElement)!=null&&t.paused))){if(this._isPlaying=!0,this._receivedInput||(this._videoElement.muted=!0),this.handleBeginPlaying(!1),this.shouldUseM3U8){this.ensureM3U8CanBePlayed();return}ug&&console.log("Video Play()",this.clip,this._videoElement,this.time),this._videoElement.currentTime=this.time,this._videoElement.play().catch(i=>{var I;console.log(i),ug&&console.error("Error playing video",i,"CODE="+i.code,(I=this.videoElement)==null?void 0:I.src,this),setTimeout(()=>{this._isPlaying&&!this.destroyed&&this.activeAndEnabled&&this.play()},1e3)}),ug&&console.log("play",this._videoElement,this.time)}}stop(){this._isPlaying=!1,this.time=0,this._videoElement&&(this._videoElement.currentTime=0,this._videoElement.pause(),ug&&console.log("STOP",this))}pause(){var e,t;this.time=((e=this._videoElement)==null?void 0:e.currentTime)??0,this._isPlaying=!1,(t=this._videoElement)==null||t.pause(),ug&&console.log("PAUSE",this,this.currentTime)}create(e){let t;switch(this.source){case 0:t=this.clip;break;case 1:t=this.url,!(t!=null&&t.length)&&typeof this.clip=="string"&&(t=this.clip);break}return t?(this._videoElement||(ug&&console.warn("Create VideoElement",this),this._videoElement=this.createVideoElement(),this.context.domElement.shadowRoot.prepend(this._videoElement),this.updateVideoElementStyles()),typeof t=="string"?(ug&&console.log("Set Video src",t),this._videoElement.src=t):(ug&&console.log("Set Video srcObject",t),this._videoElement.srcObject=t),this._videoTexture||(this._videoTexture=new K_(this._videoElement)),this._videoTexture.flipY=!1,this._videoTexture.colorSpace=de,e&&this.handleBeginPlaying(e),ug&&console.log("Video: handle playing done...",t,e),!0):(ug&&console.warn("No video source set",this),!1)}updateAspect(){this.aspectMode!==0&&this.startCoroutine(this.updateAspectImpl())}get screenspace(){var e;return((e=this._overlay)==null?void 0:e.enabled)??!1}set screenspace(e){var t;if(e){if(!this._videoTexture)return;this._overlay||(this._overlay=new NaA(this.context)),this._overlay.add(this._videoTexture)}else(t=this._overlay)==null||t.remove(this._videoTexture);this._overlay&&(this._overlay.enabled=e)}createVideoElement(){const e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),ug&&console.log("created video element",e),e}handleBeginPlaying(e){var I,o;if(!this.activeAndEnabled||!this._videoElement)return;this._targetObjects.length=0;let t=this.gameObject;switch(this.renderMode){case 3:t=(I=this.targetMaterialRenderer)==null?void 0:I.gameObject,t||(t=(o=aA.getComponent(this.gameObject,Oi))==null?void 0:o.gameObject);break;case 2:console.error("VideoPlayer renderTexture not implemented yet. Please use material override instead");return}if(!t){console.error("Missing target for video material renderer",this.name,vP[this.renderMode],this);return}const i=t.material;if(i){this._targetObjects.push(t),i!==this._videoMaterial&&(this._videoMaterial=i.clone(),t.material=this._videoMaterial);const s="map",n=this._videoMaterial;if(!this.targetMaterialProperty)n[s]=this._videoTexture;else switch(this.targetMaterialProperty){default:n[s]=this._videoTexture;break}}else{console.warn("Can not play video, no material found, this might be a multimaterial case which is not supported yet");return}this.updateVideoElementSettings(),this.updateVideoElementStyles(),e&&(this.shouldUseM3U8&&this.ensureM3U8CanBePlayed(),this.play())}updateVideoElementSettings(){if(!this._videoElement)return;this._videoElement.loop=this._isLooping,this._videoElement.currentTime=this.currentTime,this._videoElement.playbackRate=this._playbackSpeed,this._videoElement.playsInline=!0;let e=!this._receivedInput||this.audioOutputMode===0;!e&&this._muted&&(e=!0),this._videoElement.muted=e,this.playOnAwake&&(this._videoElement.autoplay=!0)}updateVideoElementStyles(){this._videoElement&&(this._videoElement.style.userSelect="none",this._videoElement.style.visibility="hidden",this._videoElement.style.display="none",this.updateAspect())}*updateAspectImpl(){const e=++this._updateAspectRoutineId,t=void 0,i=this.clip;for(;e===this._updateAspectRoutineId&&this.aspectMode!==0&&this.clip&&i===this.clip&&this._isPlaying;){if(!i||typeof i=="string")return;let I;for(const o of i.getVideoTracks()){const s=o.getSettings();if(s&&s.width&&s.height){I=s.width/s.height;break}else I=this.context.renderer.domElement.clientWidth/this.context.renderer.domElement.clientHeight}if(I===void 0){for(let o=0;o<10;o++)yield;if(!this.isPlaying)break;continue}if(t===I){yield;continue}for(const o of this._targetObjects){let s=1;if(o.parent){const n=Vt(o.parent);s=n.x/n.y}switch(this.aspectMode){case 1:o.scale.y=1/I*o.scale.x*s;break;case 2:o.scale.x=I*o.scale.y*s;break}}for(let o=0;o<3;o++)yield}}get shouldUseM3U8(){return this.url!=null&&this.url.endsWith(".m3u8")&&this.source===1}ensureM3U8CanBePlayed(){if(!this.shouldUseM3U8)return;let e=document.head.querySelector("script[data-hls_library]");e?globalThis.Hls?this.onHlsAvailable():e.addEventListener("load",this.onHlsAvailable):(ug&&console.log("HLS: load script"),e=document.createElement("script"),e.dataset.hls_library="hls.js",e.src="https://cdn.jsdelivr.net/npm/hls.js@1",e.addEventListener("load",this.onHlsAvailable),document.head.append(e))}}Yo([D()],cg.prototype,"playOnAwake",2);Yo([D()],cg.prototype,"aspectMode",2);Yo([D(URL)],cg.prototype,"clip",2);Yo([D()],cg.prototype,"source",2);Yo([D(URL)],cg.prototype,"url",2);Yo([D()],cg.prototype,"renderMode",2);Yo([D()],cg.prototype,"targetMaterialProperty",2);Yo([D(Oi)],cg.prototype,"targetMaterialRenderer",2);Yo([D(fe)],cg.prototype,"targetTexture",2);Yo([D()],cg.prototype,"time",2);Yo([D()],cg.prototype,"playbackSpeed",1);Yo([D()],cg.prototype,"isLooping",1);Yo([D()],cg.prototype,"audioOutputMode",1);class NaA{constructor(A){r(this,"context");r(this,"_videos",[]);r(this,"_screenspaceModeQuad");r(this,"_isInScreenspaceMode",!1);r(this,"_input");this.context=A,this._input=new FaA(this)}get enabled(){return this._isInScreenspaceMode}set enabled(A){A?this.start():this.stop()}add(A){this._videos.indexOf(A)===-1&&this._videos.push(A)}remove(A){if(!A)return;const e=this._videos.indexOf(A);e>=0&&this._videos.splice(e,1)}start(){var i;if(this._isInScreenspaceMode||this._videos.length<0)return;const A=this._videos[this._videos.length-1];if(!A)return;if(this._isInScreenspaceMode=!0,!this._screenspaceModeQuad){if(this._screenspaceModeQuad=Du.createPrimitive(_B.Quad,{material:new KaA(A)}),!this._screenspaceModeQuad)return;this._screenspaceModeQuad.geometry.scale(2,2,2)}const e=this._screenspaceModeQuad;this.context.scene.add(e),this.updateScreenspaceMaterialUniforms();const t=e.material;t==null||t.reset(),(i=this._input)==null||i.enable(t)}stop(){var A;this._isInScreenspaceMode=!1,this._screenspaceModeQuad&&((A=this._input)==null||A.disable(),this._screenspaceModeQuad.removeFromParent())}updateScreenspaceMaterialUniforms(){var e;const A=(e=this._screenspaceModeQuad)==null?void 0:e.material;A&&(A.screenAspect=this.context.domElement.clientWidth/this.context.domElement.clientHeight)}}class FaA{constructor(A){r(this,"_onResizeScreenFn");r(this,"_onKeyUpFn");r(this,"_onMouseWheelFn");r(this,"context");r(this,"overlay");r(this,"_material");r(this,"_isPinching",!1);r(this,"_lastPinch",0);this.overlay=A,this.context=A.context}enable(A){this._material=A,window.addEventListener("resize",this._onResizeScreenFn=()=>{this.overlay.updateScreenspaceMaterialUniforms()}),window.addEventListener("keyup",this._onKeyUpFn=i=>{i.key==="Escape"&&this.overlay.stop()}),window.addEventListener("wheel",this._onMouseWheelFn=i=>{this.overlay.enabled&&(A.zoom+=i.deltaY*5e-4,i.preventDefault())},{passive:!1});const e=new iA;window.addEventListener("mousemove",i=>{if(this.overlay.enabled&&this.context.input.getPointerPressed(0)){const I=new iA(i.movementX,i.movementY);I.x/=this.context.domElement.clientWidth,I.y/=this.context.domElement.clientHeight,e.set(I.x,I.y),e.multiplyScalar(A.zoom/-this.context.time.deltaTime*.01),A.offset=A.offset.add(e)}}),window.addEventListener("pointermove",i=>{this.overlay.enabled&&this.context.input.getPointerPressed(0)&&this.context.input.getTouchesPressedCount()===1&&(e.set(i.movementX,i.movementY),e.multiplyScalar(A.zoom*-this.context.time.deltaTime*.05),A.offset=A.offset.add(e))});let t=0;window.addEventListener("touchstart",i=>{if(i.touches.length<2){this.context.time.time-t<.3&&this.overlay.stop(),t=this.context.time.time;return}this._isPinching=!0,this._lastPinch=0}),window.addEventListener("touchmove",i=>{if(!this._isPinching||!this._material)return;const I=i.touches[0],o=i.touches[1],s=I.clientX-o.clientX,n=I.clientY-o.clientY,C=Math.sqrt(s*s+n*n);if(this._lastPinch!==0){const a=C-this._lastPinch;this._material.zoom-=a*.004}this._lastPinch=C}),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 KaA extends Ke{constructor(e){super();r(this,"_offset",new iA);this.uniforms={map:{value:e},screenAspect:{value:1},offsetScale:{value:new Ae(0,0,1,1)}},this.vertexShader=`
6954
+ }`);new w(0,0,1);var SCA=function(g){el(e,g);var A=tl(e);function e(t){var i;return Ge(this,e),i=A.call(this,t),tA(ot(i),"positionBuffer",void 0),tA(ot(i),"previousBuffer",void 0),tA(ot(i),"nextBuffer",void 0),tA(ot(i),"uvBuffer",void 0),tA(ot(i),"sideBuffer",void 0),tA(ot(i),"widthBuffer",void 0),tA(ot(i),"colorBuffer",void 0),tA(ot(i),"indexBuffer",void 0),tA(ot(i),"vector_",new w),tA(ot(i),"vector2_",new w),tA(ot(i),"vector3_",new w),tA(ot(i),"quaternion_",new MA),i.maxParticles=1e4,i.setupBuffers(),i.rebuildMaterial(),i}return ke(e,[{key:"setupBuffers",value:function(){this.geometry&&this.geometry.dispose(),this.geometry=new ue,this.indexBuffer=new ie(new Uint32Array(this.maxParticles*6),1),this.indexBuffer.setUsage(rI),this.geometry.setIndex(this.indexBuffer),this.positionBuffer=new ie(new Float32Array(this.maxParticles*6),3),this.positionBuffer.setUsage(rI),this.geometry.setAttribute("position",this.positionBuffer),this.previousBuffer=new ie(new Float32Array(this.maxParticles*6),3),this.previousBuffer.setUsage(rI),this.geometry.setAttribute("previous",this.previousBuffer),this.nextBuffer=new ie(new Float32Array(this.maxParticles*6),3),this.nextBuffer.setUsage(rI),this.geometry.setAttribute("next",this.nextBuffer),this.widthBuffer=new ie(new Float32Array(this.maxParticles*2),1),this.widthBuffer.setUsage(rI),this.geometry.setAttribute("width",this.widthBuffer),this.sideBuffer=new ie(new Float32Array(this.maxParticles*2),1),this.sideBuffer.setUsage(rI),this.geometry.setAttribute("side",this.sideBuffer),this.uvBuffer=new ie(new Float32Array(this.maxParticles*4),2),this.uvBuffer.setUsage(rI),this.geometry.setAttribute("uv",this.uvBuffer),this.colorBuffer=new ie(new Float32Array(this.maxParticles*8),4),this.colorBuffer.setUsage(rI),this.geometry.setAttribute("color",this.colorBuffer)}},{key:"expandBuffers",value:function(i){for(;i>=this.maxParticles;)this.maxParticles*=2;this.setupBuffers()}},{key:"rebuildMaterial",value:function(){this.layers.mask=this.settings.layers.mask;var i={lineWidth:{value:1},map:{value:null},useMap:{value:0},alphaMap:{value:null},useAlphaMap:{value:0},resolution:{value:new iA(1,1)},sizeAttenuation:{value:1},visibility:{value:1},alphaTest:{value:0},repeat:{value:new iA(1,1)}},I={};if(I.USE_UV="",I.USE_COLOR_ALPHA="",this.settings.material.map&&(I.USE_MAP="",I.MAP_UV=nU(this.settings.material.map.channel),i.map=new yA(this.settings.material.map),i.mapTransform=new yA(new Le().copy(this.settings.material.map.matrix))),this.settings.renderMode===ne.Trail)this.material=new Ke({uniforms:i,defines:I,vertexShader:yCA,fragmentShader:wCA,transparent:this.settings.material.transparent,depthWrite:!this.settings.material.transparent,side:this.settings.material.side,blending:this.settings.material.blending||NB});else throw new Error("render mode unavailable")}},{key:"update",value:function(){var i=this,I=0,o=0,s=0;this.systems.forEach(function(n){for(var C=0;C<n.particleNum;C++)s+=n.particles[C].previous.length*2}),s>this.maxParticles&&this.expandBuffers(s),this.systems.forEach(function(n){var C=i.quaternion_,a=i.vector2_,B=i.vector3_;n.emitter.matrixWorld.decompose(a,C,B);for(var Q=n.particles,E=n.particleNum,c=i.settings.uTileCount,d=i.settings.vTileCount,l=1/c,h=1/d,p=0;p<E;p++){var u=Q[p],f=u.uvTile%d,k=Math.floor(u.uvTile/d),G=u.previous.values(),M=G.next(),m=M.value,N=m;M.done||(M=G.next());var y=void 0;M.value!==void 0?y=M.value:y=N;for(var U=0;U<u.previous.length;U++,I+=2){if(i.positionBuffer.setXYZ(I,N.position.x,N.position.y,N.position.z),i.positionBuffer.setXYZ(I+1,N.position.x,N.position.y,N.position.z),n.worldSpace?(i.positionBuffer.setXYZ(I,N.position.x,N.position.y,N.position.z),i.positionBuffer.setXYZ(I+1,N.position.x,N.position.y,N.position.z)):(u.parentMatrix?i.vector_.copy(N.position).applyMatrix4(u.parentMatrix):i.vector_.copy(N.position).applyMatrix4(n.emitter.matrixWorld),i.positionBuffer.setXYZ(I,i.vector_.x,i.vector_.y,i.vector_.z),i.positionBuffer.setXYZ(I+1,i.vector_.x,i.vector_.y,i.vector_.z)),n.worldSpace?(i.previousBuffer.setXYZ(I,m.position.x,m.position.y,m.position.z),i.previousBuffer.setXYZ(I+1,m.position.x,m.position.y,m.position.z)):(u.parentMatrix?i.vector_.copy(m.position).applyMatrix4(u.parentMatrix):i.vector_.copy(m.position).applyMatrix4(n.emitter.matrixWorld),i.previousBuffer.setXYZ(I,i.vector_.x,i.vector_.y,i.vector_.z),i.previousBuffer.setXYZ(I+1,i.vector_.x,i.vector_.y,i.vector_.z)),n.worldSpace?(i.nextBuffer.setXYZ(I,y.position.x,y.position.y,y.position.z),i.nextBuffer.setXYZ(I+1,y.position.x,y.position.y,y.position.z)):(u.parentMatrix?i.vector_.copy(y.position).applyMatrix4(u.parentMatrix):i.vector_.copy(y.position).applyMatrix4(n.emitter.matrixWorld),i.nextBuffer.setXYZ(I,i.vector_.x,i.vector_.y,i.vector_.z),i.nextBuffer.setXYZ(I+1,i.vector_.x,i.vector_.y,i.vector_.z)),i.sideBuffer.setX(I,-1),i.sideBuffer.setX(I+1,1),n.worldSpace)i.widthBuffer.setX(I,N.size),i.widthBuffer.setX(I+1,N.size);else if(u.parentMatrix)i.widthBuffer.setX(I,N.size),i.widthBuffer.setX(I+1,N.size);else{var H=(Math.abs(B.x)+Math.abs(B.y)+Math.abs(B.z))/3;i.widthBuffer.setX(I,N.size*H),i.widthBuffer.setX(I+1,N.size*H)}i.uvBuffer.setXY(I,(U/u.previous.length+f)*l,(d-k-1)*h),i.uvBuffer.setXY(I+1,(U/u.previous.length+f)*l,(d-k)*h),i.colorBuffer.setXYZW(I,N.color.x,N.color.y,N.color.z,N.color.w),i.colorBuffer.setXYZW(I+1,N.color.x,N.color.y,N.color.z,N.color.w),U+1<u.previous.length&&(i.indexBuffer.setX(o*3,I),i.indexBuffer.setX(o*3+1,I+1),i.indexBuffer.setX(o*3+2,I+2),o++,i.indexBuffer.setX(o*3,I+2),i.indexBuffer.setX(o*3+1,I+1),i.indexBuffer.setX(o*3+2,I+3),o++),m=N,N=y,M.done||(M=G.next(),M.value!==void 0&&(y=M.value))}}}),this.positionBuffer.updateRange.count=I*3,this.positionBuffer.needsUpdate=!0,this.previousBuffer.updateRange.count=I*3,this.previousBuffer.needsUpdate=!0,this.nextBuffer.updateRange.count=I*3,this.nextBuffer.needsUpdate=!0,this.sideBuffer.updateRange.count=I,this.sideBuffer.needsUpdate=!0,this.widthBuffer.updateRange.count=I,this.widthBuffer.needsUpdate=!0,this.uvBuffer.updateRange.count=I*2,this.uvBuffer.needsUpdate=!0,this.colorBuffer.updateRange.count=I*4,this.colorBuffer.needsUpdate=!0,this.indexBuffer.updateRange.count=o*3,this.indexBuffer.needsUpdate=!0,this.geometry.setDrawRange(0,o*3)}},{key:"dispose",value:function(){this.geometry.dispose()}}]),e}(RP),mCA=function(g){el(e,g);var A=tl(e);function e(){var t;return Ge(this,e),t=A.call(this),tA(ot(t),"batches",[]),tA(ot(t),"systemToBatchIndex",new Map),tA(ot(t),"type","BatchedRenderer"),t}return ke(e,[{key:"addSystem",value:function(i){i._renderer=this;for(var I=i.getRendererSettings(),o=0;o<this.batches.length;o++)if(e.equals(this.batches[o].settings,I)){this.batches[o].addSystem(i),this.systemToBatchIndex.set(i,o);return}var s;switch(I.renderMode){case ne.Trail:s=new SCA(I);break;case ne.Mesh:case ne.BillBoard:case ne.VerticalBillBoard:case ne.HorizontalBillBoard:case ne.StretchedBillBoard:s=new DCA(I);break}s.addSystem(i),this.batches.push(s),this.systemToBatchIndex.set(i,this.batches.length-1),this.add(s)}},{key:"deleteSystem",value:function(i){var I=this.systemToBatchIndex.get(i);I!=null&&(this.batches[I].removeSystem(i),this.systemToBatchIndex.delete(i))}},{key:"updateSystem",value:function(i){this.deleteSystem(i),this.addSystem(i)}},{key:"update",value:function(i){this.systemToBatchIndex.forEach(function(o,s){s.update(i)});for(var I=0;I<this.batches.length;I++)this.batches[I].update()}}],[{key:"equals",value:function(i,I){return i.material.side===I.material.side&&i.material.blending===I.material.blending&&i.material.transparent===I.material.transparent&&i.material.type===I.material.type&&i.material.alphaTest===I.material.alphaTest&&i.material.map===I.material.map&&i.renderMode===I.renderMode&&i.uTileCount===I.uTileCount&&i.vTileCount===I.vTileCount&&i.instancingGeometry===I.instancingGeometry&&i.renderOrder===I.renderOrder&&i.layers.mask===I.layers.mask}}]),e}(uA),GCA=mCA,_x=function(){function g(){var A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:new w;Ge(this,g),tA(this,"locations",[]),this.scaleX=A,this.scaleY=e,this.position=t}return ke(g,[{key:"transform",value:function(e,t){e.x=this.locations[t%this.locations.length].x*this.scaleX+this.position.x,e.y=this.locations[t%this.locations.length].y*this.scaleY+this.position.y,e.z=this.position.z}},{key:"clone",value:function(){var e=new g(this.scaleX,this.scaleY,this.position.clone());return e.locations=this.locations.map(function(t){return t.clone()}),e}},{key:"toJSON",value:function(){return{scaleX:this.scaleX,scaleY:this.scaleY,position:this.position,locations:this.locations.map(function(e){return{x:e.x,y:e.y}})}}},{key:"fromImage",value:function(e,t){var i=document.createElement("canvas");i.width=e.width,i.height=e.height;var I=i.getContext("2d");if(I){I.drawImage(e,0,0);var o=I.getImageData(0,0,i.width,i.height,{colorSpace:"srgb"});i.remove(),this.locations.length=0;for(var s=0;s<o.height;s++)for(var n=0;n<o.width;n++)o.data[(s*o.width+n)*4+3]>t&&this.locations.push(new iA(n,o.height-s))}}}],[{key:"fromJSON",value:function(e){var t=new g(e.scaleX,e.scaleY,new w(e.position[0],e.position[1],e.position[2]));return t.locations=e.locations.map(function(i){return new iA(i.x,i.y)}),t}}]),g}();function kCA(g){switch(g.type){case"TextureSequencer":return _x.fromJSON(g);default:return new _x}}var MCA=function(){function g(A){Ge(this,g),tA(this,"type","ApplySequences"),tA(this,"sequencers",[]),tA(this,"time",0),tA(this,"index",0),tA(this,"pCount",0),tA(this,"delay",void 0),tA(this,"tempV",new w),this.delay=A}return ke(g,[{key:"initialize",value:function(e){e.id=this.pCount,e.dst=new w,e.begin=new w,e.inMotion=!1,this.pCount++}},{key:"reset",value:function(){this.time=0,this.index=0,this.pCount=0}},{key:"update",value:function(e,t){var i=this.sequencers[this.index],I=e.id*this.delay;this.time>=i[0].a+I&&this.time<=i[0].b+I?(e.inMotion||(e.inMotion=!0,e.begin.copy(e.position),i[1].transform(e.dst,e.id)),e.position.lerpVectors(e.begin,e.dst,g.BEZIER.genValue((this.time-i[0].a-I)/(i[0].b-i[0].a)))):this.time>i[0].b+I&&(e.inMotion=!1)}},{key:"frameUpdate",value:function(e){for(;this.index+1<this.sequencers.length&&this.time>=this.sequencers[this.index+1][0].a;)this.index++;this.time+=e}},{key:"appendSequencer",value:function(e,t){this.sequencers.push([e,t])}},{key:"toJSON",value:function(){return{type:this.type,delay:this.delay,sequencers:this.sequencers.map(function(e){var t=WE(e,2),i=t[0],I=t[1];return{range:i.toJSON(),sequencer:I.toJSON()}})}}},{key:"clone",value:function(){var e=new g(this.delay);return e.sequencers=this.sequencers.map(function(t){return[t[0].clone(),t[1].clone()]}),e}}],[{key:"fromJSON",value:function(e){var t=new g(e.delay);return e.sequencers.forEach(function(i){t.sequencers.push([Pt(i.range),kCA(i.sequencer)])}),t}}]),g}();tA(MCA,"BEZIER",new gU(0,0,1,1));var cA=function(g){return g[g.Number=0]="Number",g[g.Vec2=1]="Vec2",g[g.Vec3=2]="Vec3",g[g.Vec4=3]="Vec4",g[g.Boolean=4]="Boolean",g[g.AnyType=5]="AnyType",g}({}),Tx=ke(function g(A,e,t,i){Ge(this,g),tA(this,"input",void 0),tA(this,"inputIndex",void 0),tA(this,"output",void 0),tA(this,"outputIndex",void 0),this.input=A,this.inputIndex=e,this.input.outputs[e].push(this),this.output=t,this.outputIndex=i,this.output.inputs[i]=this}),UCA=function(){function g(){Ge(this,g),tA(this,"visited",new Set),tA(this,"graph_",void 0),tA(this,"context_",void 0),g.Instance=this}return ke(g,[{key:"traverse",value:function(e){if(this.context_===void 0)throw new Error("context is undefined");if(this.graph_===void 0)throw new Error("graph is undefined");this.visited.add(e.id);for(var t=[],i=0;i<e.inputs.length;i++)if(e.inputs[i]instanceof Tx){var I=e.inputs[i].input;this.visited.has(I.id)||this.traverse(I),t.push(I.outputValues[e.inputs[i].inputIndex])}else t.push(e.inputs[i].getValue(this.context_));e.func(this.context_,t,e.outputValues),this.graph_.nodesInOrder.push(e)}},{key:"executeCompiledGraph",value:function(){if(this.context_===void 0)throw new Error("context is undefined");if(this.graph_===void 0)throw new Error("graph is undefined");for(var e=this.graph_.nodesInOrder,t=0;t<e.length;t++){for(var i=[],I=e[t],o=0;o<I.inputs.length;o++)if(I.inputs[o]instanceof Tx)i.push(I.inputs[o].input.outputValues[I.inputs[o].inputIndex]);else if(I.inputs[o]!==void 0)i.push(I.inputs[o].getValue(this.context_));else throw new Error("miss input for node ".concat(I.id));I.func(this.context_,i,I.outputValues)}}},{key:"run",value:function(e,t){if(this.graph_=e,this.context_=t,e.compiled)this.executeCompiledGraph();else{e.nodesInOrder.length=0,this.visited.clear();for(var i=0;i<e.outputNodes.length;i++){var I=e.outputNodes[i];this.traverse(I)}e.compiled=!0}}}]),g}();tA(UCA,"Instance",void 0);var Qt=function(){function g(A){Ge(this,g),tA(this,"name",void 0),tA(this,"nodeTypeSignatures",[]),this.name=A}return ke(g,[{key:"addSignature",value:function(e,t,i){this.nodeTypeSignatures.push({inputTypes:e,outputTypes:t,func:i})}}]),g}(),WS=new Qt("add");WS.addSignature([cA.Number,cA.Number],[cA.Number],function(g,A,e,t){t[0]=e[0]+e[1]});WS.addSignature([cA.Vec2,cA.Vec2],[cA.Vec2],function(g,A,e,t){t[0].addVectors(e[0],e[1])});WS.addSignature([cA.Vec3,cA.Vec3],[cA.Vec3],function(g,A,e,t){t[0].addVectors(e[0],e[1])});WS.addSignature([cA.Vec4,cA.Vec4],[cA.Vec4],function(g,A,e,t){t[0].addVectors(e[0],e[1])});var ZS=new Qt("sub");ZS.addSignature([cA.Number,cA.Number],[cA.Number],function(g,A,e,t){t[0]=e[0]-e[1]});ZS.addSignature([cA.Vec2,cA.Vec2],[cA.Vec2],function(g,A,e,t){t[0].subVectors(e[0],e[1])});ZS.addSignature([cA.Vec3,cA.Vec3],[cA.Vec3],function(g,A,e,t){t[0].subVectors(e[0],e[1])});ZS.addSignature([cA.Vec4,cA.Vec4],[cA.Vec4],function(g,A,e,t){t[0].subVectors(e[0],e[1])});var jS=new Qt("mul");jS.addSignature([cA.Number,cA.Number],[cA.Number],function(g,A,e,t){t[0]=e[0]*e[1]});jS.addSignature([cA.Vec2,cA.Number],[cA.Vec2],function(g,A,e,t){t[0].copy(e[0]).multiplyScalar(e[1])});jS.addSignature([cA.Vec3,cA.Number],[cA.Vec3],function(g,A,e,t){t[0].copy(e[0]).multiplyScalar(e[1])});jS.addSignature([cA.Vec4,cA.Number],[cA.Vec4],function(g,A,e,t){t[0].copy(e[0]).multiplyScalar(e[1])});var VS=new Qt("div");VS.addSignature([cA.Number,cA.Number],[cA.Number],function(g,A,e,t){t[0]=e[0]/e[1]});VS.addSignature([cA.Vec2,cA.Number],[cA.Vec2],function(g,A,e,t){t[0].copy(e[0]).divideScalar(e[1])});VS.addSignature([cA.Vec3,cA.Number],[cA.Vec3],function(g,A,e,t){t[0].copy(e[0]).divideScalar(e[1])});VS.addSignature([cA.Vec4,cA.Number],[cA.Vec4],function(g,A,e,t){t[0].copy(e[0]).divideScalar(e[1])});var RCA=new Qt("sin");RCA.addSignature([cA.Number],[cA.Number],function(g,A,e,t){t[0]=Math.sin(e[0])});var NCA=new Qt("cos");NCA.addSignature([cA.Number],[cA.Number],function(g,A,e,t){t[0]=Math.cos(e[0])});var FCA=new Qt("tan");FCA.addSignature([cA.Number],[cA.Number],function(g,A,e,t){t[0]=Math.tan(e[0])});var KCA=new Qt("abs");KCA.addSignature([cA.Number],[cA.Number],function(g,A,e,t){t[0]=Math.abs(e[0])});var JCA=new Qt("min");JCA.addSignature([cA.Number,cA.Number],[cA.Number],function(g,A,e,t){t[0]=Math.min(e[0],e[1])});var bCA=new Qt("max");bCA.addSignature([cA.Number,cA.Number],[cA.Number],function(g,A,e,t){t[0]=Math.max(e[0],e[1])});var MF=new Qt("dot");MF.addSignature([cA.Vec2,cA.Vec2],[cA.Number],function(g,A,e,t){t[0]=e[0].dot(e[1])});MF.addSignature([cA.Vec3,cA.Vec3],[cA.Number],function(g,A,e,t){t[0]=e[0].dot(e[1])});MF.addSignature([cA.Vec4,cA.Vec4],[cA.Number],function(g,A,e,t){t[0]=e[0].dot(e[1])});var vCA=new Qt("cross");vCA.addSignature([cA.Vec3,cA.Vec3],[cA.Vec3],function(g,A,e,t){t[0].crossVectors(e[0],e[1])});var UF=new Qt("length");UF.addSignature([cA.Vec2],[cA.Number],function(g,A,e,t){t[0]=e[0].length()});UF.addSignature([cA.Vec3],[cA.Number],function(g,A,e,t){t[0]=e[0].length()});UF.addSignature([cA.Vec4],[cA.Number],function(g,A,e,t){t[0]=e[0].length()});var RF=new Qt("lengthSq");RF.addSignature([cA.Vec2],[cA.Number],function(g,A,e,t){t[0]=e[0].lengthSq()});RF.addSignature([cA.Vec3],[cA.Number],function(g,A,e,t){t[0]=e[0].lengthSq()});RF.addSignature([cA.Vec4],[cA.Number],function(g,A,e,t){t[0]=e[0].lengthSq()});var NF=new Qt("normalize");NF.addSignature([cA.Vec2],[cA.Vec2],function(g,A,e,t){t[0].copy(e[0]).normalize()});NF.addSignature([cA.Vec3],[cA.Vec3],function(g,A,e,t){t[0].copy(e[0]).normalize()});NF.addSignature([cA.Vec4],[cA.Vec4],function(g,A,e,t){t[0].copy(e[0]).normalize()});var NP=new Qt("distance");NP.addSignature([cA.Vec2,cA.Vec2],[cA.Number],function(g,A,e,t){t[0]=e[0].distanceTo(e[1])});NP.addSignature([cA.Vec3,cA.Vec3],[cA.Number],function(g,A,e,t){t[0]=e[0].distanceTo(e[1])});var qCA=new Qt("and");qCA.addSignature([cA.Boolean,cA.Boolean],[cA.Boolean],function(g,A,e,t){t[0]=e[0]&&e[1]});var xCA=new Qt("or");xCA.addSignature([cA.Boolean,cA.Boolean],[cA.Boolean],function(g,A,e,t){t[0]=e[0]||e[1]});var LCA=new Qt("not");LCA.addSignature([cA.Boolean],[cA.Boolean],function(g,A,e,t){t[0]=!e[0]});var zS=new Qt("equal");zS.addSignature([cA.Number,cA.Number],[cA.Boolean],function(g,A,e,t){t[0]=e[0]===e[1]});zS.addSignature([cA.Vec2,cA.Vec2],[cA.Boolean],function(g,A,e,t){t[0]=e[0].equals(e[1])});zS.addSignature([cA.Vec3,cA.Vec3],[cA.Boolean],function(g,A,e,t){t[0]=e[0].equals(e[1])});zS.addSignature([cA.Vec4,cA.Vec4],[cA.Boolean],function(g,A,e,t){t[0]=e[0].equals(e[1])});var _CA=new Qt("lessThan");_CA.addSignature([cA.Number,cA.Number],[cA.Boolean],function(g,A,e,t){t[0]=e[0]<e[1]});var TCA=new Qt("greaterThan");TCA.addSignature([cA.Number,cA.Number],[cA.Boolean],function(g,A,e,t){t[0]=e[0]>e[1]});var HCA=new Qt("lessThanOrEqual");HCA.addSignature([cA.Number,cA.Number],[cA.Boolean],function(g,A,e,t){t[0]=e[0]<=e[1]});var YCA=new Qt("greaterThanOrEqual");YCA.addSignature([cA.Number,cA.Number],[cA.Boolean],function(g,A,e,t){t[0]=e[0]>=e[1]});var OCA=new Qt("if");OCA.addSignature([cA.Boolean,cA.AnyType,cA.AnyType],[cA.AnyType],function(g,A,e,t){t[0]=e[0]?e[1]:e[2]});var PCA=new Qt("number");PCA.addSignature([],[cA.Number],function(g,A,e,t){t[0]=A.value});var WCA=new Qt("vec2");WCA.addSignature([],[cA.Vec2],function(g,A,e,t){t[0]=A.value});var ZCA=new Qt("vec3");ZCA.addSignature([],[cA.Vec3],function(g,A,e,t){t[0]=A.value});var jCA=new Qt("vec4");jCA.addSignature([],[cA.Vec4],function(g,A,e,t){t[0]=A.value});var VCA=new Qt("bool");VCA.addSignature([],[cA.Boolean],function(g,A,e,t){t[0]=A.value});var zCA=new Qt("particlePosition");zCA.addSignature([],[cA.Vec3],function(g,A,e,t){t[0]=g.particle[A.property]});var XCA=new Qt("particleVelocity");XCA.addSignature([],[cA.Vec3],function(g,A,e,t){t[0]=g.particle[A.property]});var $CA=new Qt("particleRotation");$CA.addSignature([],[cA.Number],function(g,A,e,t){t[0]=g.particle[A.property]});var AaA=new Qt("particleAge");AaA.addSignature([],[cA.Number],function(g,A,e,t){t[0]=g.particle[A.property]});var Ip=new Qt("output");Ip.addSignature([cA.Number],[cA.Number],function(g,A,e,t){t[0]=e[0]});Ip.addSignature([cA.Vec2],[cA.Vec2],function(g,A,e,t){t[0]=e[0]});Ip.addSignature([cA.Vec3],[cA.Vec3],function(g,A,e,t){t[0]=e[0]});Ip.addSignature([cA.Vec4],[cA.Vec4],function(g,A,e,t){t[0]=e[0]});Ip.addSignature([cA.Boolean],[cA.Boolean],function(g,A,e,t){t[0]=e[0]});console.log("%c Particle system powered by three.quarks. https://quarks.art/","font-size: 16px; font-weight: bold;");var eaA=Object.defineProperty,taA=Object.getOwnPropertyDescriptor,Gi=(g,A,e,t)=>{for(var i=t>1?void 0:t?taA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&eaA(A,e,i),i};const hh=IA("debugparticles"),iaA=IA("noprogressive"),gaA=IA("debugprogressive");var CU=(g=>(g[g.Birth=0]="Birth",g[g.Collision=1]="Collision",g[g.Death=2]="Death",g[g.Trigger=3]="Trigger",g[g.Manual=4]="Manual",g))(CU||{});class ps extends RA{constructor(){super(...arguments);r(this,"renderMode");r(this,"particleMaterial");r(this,"trailMaterial");r(this,"particleMesh");r(this,"maxParticleSize");r(this,"minParticleSize");r(this,"velocityScale");r(this,"cameraVelocityScale");r(this,"lengthScale")}start(){if(this.maxParticleSize!==.5&&this.minParticleSize!==0&&he()){const e=`ParticleSystem "${this.name}" has non-default min/max particle size. This may not render correctly. Please set min size to 0 and the max size to 0.5 and use the "StartSize" setting instead`;console.warn(e)}}get transparent(){var t;return((t=this.particleMaterial)==null?void 0:t.transparent)??!1}getMaterial(e=!1){let t=e===!0&&this.trailMaterial?this.trailMaterial:this.particleMaterial;return t&&e&&t.side===Pg&&(t=t.clone(),t.side=Ki,e?this.trailMaterial=t:this.particleMaterial=t),t&&!iaA&&t._didRequestTextureLOD===void 0&&(t._didRequestTextureLOD=0,gaA&&console.log("Load material LOD",t.name),Kt.assignTextureLOD(this.context,this.sourceId,t)),t}getMesh(e){let t=null;if(!t&&(this.particleMesh instanceof lA&&(t=this.particleMesh.geometry),t===null)){t=new Xi(1,1);const I=t.attributes.uv;for(let o=0;o<I.count;o++)I.setX(o,1-I.getX(o))}return new lA(t,this.getMaterial())}}Gi([D()],ps.prototype,"renderMode",2);Gi([D(be)],ps.prototype,"particleMaterial",2);Gi([D(be)],ps.prototype,"trailMaterial",2);Gi([D()],ps.prototype,"maxParticleSize",2);Gi([D()],ps.prototype,"minParticleSize",2);Gi([D()],ps.prototype,"velocityScale",2);Gi([D()],ps.prototype,"cameraVelocityScale",2);Gi([D()],ps.prototype,"lengthScale",2);class zf{constructor(A,e=1){r(this,"_curve");r(this,"_factor");r(this,"type","function");this._curve=A,this._factor=e}genValue(A){return this._curve.evaluate(A,Math.random())*this._factor}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}}class FF{constructor(A){r(this,"type","value");r(this,"system");this.system=A}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}}class IaA extends FF{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class oaA extends FF{constructor(){super(...arguments);r(this,"_lastPosition",new w);r(this,"_lastDistance",0)}update(){const e=_e(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(e),this._lastPosition.copy(e)}genValue(){if(!this.system.isPlaying||!this.system.emission.enabled||this.system.currentParticles>=this.system.maxParticles)return 0;let e=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){const I=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let s=this._lastDistance/this.system.deltaTime*I;Number.isFinite(s)||(s=0),e+=s}const t=this.system.emission.getBurst();t>0&&(e+=t/this.system.deltaTime);const i=this.system.maxParticles-this.system.currentParticles;return te.clamp(e,0,i/this.system.deltaTime)}}class saA extends FF{genValue(){return this.system.isPlaying,0}}class Sr{constructor(A){r(this,"system");r(this,"type");this.type=Object.getPrototypeOf(this).constructor.name||"ParticleSystemBaseBehaviour",A&&(this.system=A)}get context(){return this.system.context}initialize(A){}update(A,e){}frameUpdate(A){}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}reset(){}}class naA extends Sr{constructor(){super(...arguments);r(this,"type","NeedleTextureSheet")}update(e,t){const i=this.system.textureSheetAnimation;if(i.enabled){const I=e.age/e.life,o=i.evaluate(I);o!==void 0&&(e.uvTile=o)}}}const Hx=Symbol("particleRotation");class CaA extends Sr{constructor(){super(...arguments);r(this,"type","NeedleRotation")}initialize(e){e[Hx]=Math.random()}update(e,t){if(e.rotation===void 0)return;const i=e.age/e.life;if(typeof e.rotation=="number"&&(this.system.rotationOverLifetime.enabled?e.rotation+=this.system.rotationOverLifetime.evaluate(i,e[Hx])*t:this.system.renderer.renderMode===cC.Billboard&&(e.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const I=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(i,I)*t}}}const Yx=Symbol("sizeLerpFactor"),aaA=new w;class raA extends Sr{constructor(){super(...arguments);r(this,"type","NeedleSize");r(this,"_minSize",0);r(this,"_maxSize",1)}initialize(e){e[Yx]=Math.random(),this._minSize=this.system.renderer.minParticleSize,this._maxSize=this.system.renderer.maxParticleSize}update(e,t){const i=e.age/e.life;let I=1;this.system.sizeOverLifetime.enabled&&(I*=this.system.sizeOverLifetime.evaluate(i,void 0,e[Yx]).x);let o=1;if(this.system.renderer.renderMode!==cC.Mesh&&(o=this.system.worldScale.x/this.system.cameraScale),e.size=e.startSize*I*o,this.system.localspace){const s=FP(this.system,aaA);e.size*=s.x}}}const FE=Symbol("particleLife"),KG=Symbol("trailLifetime"),Ox=Symbol("trailStartLength"),JG=Symbol("trailWidthRandom");class BaA extends Sr{constructor(){super(...arguments);r(this,"type","NeedleTrail")}initialize(e){e instanceof Ld&&(e[FE]=e.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(e[KG]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),e.life+=e[KG]),e[Ox]=e.length,e[JG]=Math.random())}update(e){var t;if((t=this.system.trails)!=null&&t.enabled&&e instanceof Ld){const i=e,I=e.age/e[FE],o=e.previous.values(),s=e.previous.length;for(let n=0;n<s;n++){const a=o.next().value,B=1-n/(s-1);let Q=e.size;Q<=0&&!this.system.trails.sizeAffectsWidth&&(Q=20*this.system.trails.widthOverTrail.evaluate(.5,i[JG])),a.size=this.system.trails.getWidth(Q,I,B,i[JG]),a.color.copy(e.color),this.system.trails.getColor(a.color,I,B)}if(e.age>e[FE]){e.velocity.set(0,0,0);const n=(e.age-e[FE])/e[KG];i.length=te.lerp(e[Ox],0,n)}}}}const Xf=Symbol("startVelocity"),Px=Symbol("gravityModifier"),bG=Symbol("gravitySpeed"),$f=Symbol("velocity lerp factor"),aU=new w;class QaA extends Sr{constructor(){super(...arguments);r(this,"type","NeedleVelocity");r(this,"_gravityDirection",new w)}initialize(e){var I,o;const t=this.system.main.simulationSpeed;e.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random()),e.velocity.copy(this.system.shape.getDirection(e,e.position)).multiplyScalar(e.startSpeed),(I=this.system.inheritVelocity)!=null&&I.enabled&&this.system.inheritVelocity.applyInitial(e.velocity),e[Xf]?e[Xf].copy(e.velocity):e[Xf]=e.velocity.clone();const i=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());e[Px]=i*t,e[bG]=i*t*.5,e[$f]=Math.random(),(o=this.system.velocityOverLifetime)==null||o.init(e),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===vd.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(e,t){var Q;const i=e[Xf],I=e[Px];if(I!==0){const E=I*e[bG];aU.copy(this._gravityDirection).multiplyScalar(E),e[bG]+=t*.05,i.add(aU)}e.velocity.copy(i);const o=e.age/e.life;(Q=this.system.inheritVelocity)!=null&&Q.enabled&&this.system.inheritVelocity.applyCurrent(e.velocity,o,e[$f]);const s=this.system.noise;s.enabled&&s.apply(0,e.position,e.velocity,t,e.age,e.life);const n=this.system.sizeBySpeed;n!=null&&n.enabled&&(e.size=n.evaluate(e.velocity,o,e[$f],e.size));const C=this.system.colorBySpeed;C!=null&&C.enabled&&C.evaluate(e.velocity,e[$f],e.color);const a=this.system.velocityOverLifetime;a.enabled&&a.apply(e,0,e.position,e.velocity,t,e.age,e.life);const B=this.system.limitVelocityOverLifetime;B.enabled&&B.apply(e.position,i,e.velocity,e.size,o,t,1),this.system.worldspace&&e.velocity.multiply(this.system.worldScale)}}const Wx=Symbol("colorLerpFactor"),Zx=new Mt(1,1,1,1),Zr=new Mt(1,1,1,1);class EaA extends Sr{constructor(){super(...arguments);r(this,"type","NeedleColor")}initialize(e){}_init(e){const t=this.system.renderer.particleMaterial;Zr.copy(this.system.main.startColor.evaluate(Math.random())),t!=null&&t.color&&(Zx.copy(t.color),Zr.multiply(Zx)),Zr.convertLinearToSRGB(),e.startColor.set(Zr.r,Zr.g,Zr.b,Zr.alpha),e.color.copy(e.startColor),e[Wx]=Math.random()}update(e,t){if(e.age===0&&this._init(e),this.system.colorOverLifetime.enabled){const i=e.age/e.life,I=this.system.colorOverLifetime.color.evaluate(i,e[Wx]);e.color.set(I.r,I.g,I.b,I.alpha).multiply(e.startColor)}else e.color.copy(e.startColor)}}class caA{constructor(A){r(this,"system");r(this,"emission");r(this,"autoDestroy");r(this,"startLength");r(this,"emissionBursts");r(this,"onlyUsedByOther");r(this,"behaviors",[]);r(this,"rendererEmitterSettings",{startLength:new aI(220),followLocalOrigin:!1});r(this,"flatWhiteTexture");r(this,"clonedTexture",{original:void 0,clone:void 0});this.system=A,this.emission=new oaA(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 zf(this.system.main.startLifetime)}get startSpeed(){return new zf(this.system.main.startSpeed)}get startRotation(){return new zf(this.system.main.startRotation)}get startSize(){return new zf(this.system.main.startSize)}get startColor(){return new _w(new Ae(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new saA(this.system)}get instancingGeometry(){return this.system.renderer.getMesh(this.system.renderer.renderMode).geometry}get renderMode(){if(this.system.trails.enabled===!0)return ne.Trail;switch(this.system.renderer.renderMode){case cC.Billboard:return ne.BillBoard;case cC.Stretch:return ne.StretchedBillBoard;case cC.HorizontalBillboard:return ne.HorizontalBillBoard;case cC.VerticalBillboard:return ne.VerticalBillBoard;case cC.Mesh:return ne.Mesh}return ne.BillBoard}get speedFactor(){var e;let A=this.system.main.simulationSpeed;return((e=this.system.renderer)==null?void 0:e.renderMode)===cC.Stretch&&(A*=this.system.renderer.velocityScale??1),A}get texture(){const A=this.material;if(A&&A.map){const e=A.map;if(this.clonedTexture.original!==e||!this.clonedTexture.clone){const t=e.clone();t.premultiplyAlpha=!1,t.colorSpace=yt,this.clonedTexture.original=e,this.clonedTexture.clone=t}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=AO(new Mt(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new IaA(this.system)}get uTileCount(){var A;return this.anim.enabled?(A=this.anim)==null?void 0:A.numTilesX:void 0}get vTileCount(){var A;return this.anim.enabled?(A=this.anim)==null?void 0:A.numTilesY:void 0}get renderOrder(){return 1}get blending(){var A;return((A=this.system.renderer.particleMaterial)==null?void 0:A.blending)??Ya}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===vd.World}}class laA{constructor(){r(this,"burstIndex",0);r(this,"burstWaveIndex",0);r(this,"time",0);r(this,"waitEmiting",0)}}const _D=class extends RA{constructor(){super(...arguments);r(this,"_state");r(this,"colorOverLifetime");r(this,"main");r(this,"emission");r(this,"sizeOverLifetime");r(this,"shape");r(this,"noise");r(this,"trails");r(this,"velocityOverLifetime");r(this,"limitVelocityOverLifetime");r(this,"inheritVelocity");r(this,"colorBySpeed");r(this,"textureSheetAnimation");r(this,"rotationOverLifetime");r(this,"rotationBySpeed");r(this,"sizeBySpeed");r(this,"_cameraScale",1);r(this,"__worldQuaternion",new MA);r(this,"_worldQuaternionInverted",new MA);r(this,"_worldScale",new w);r(this,"_worldPositionFrame",-1);r(this,"_worldPos",new w);r(this,"_renderer");r(this,"_batchSystem");r(this,"_particleSystem");r(this,"_interface");r(this,"_container");r(this,"_time",0);r(this,"_isPlaying",!0);r(this,"_isUsedAsSubsystem",!1);r(this,"_didPreWarm",!1);r(this,"_bursts");r(this,"_subEmitterSystems");r(this,"_lastBatchesCount",-1);r(this,"lastMaterialVersion",-1)}play(A=!1){var e;A&&aA.foreachComponent(this.gameObject,t=>{t instanceof _D&&t!==this&&t.play(!1)},!0),this._isPlaying=!0,this._particleSystem&&(this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1),(e=this.emission)==null||e.reset()}pause(A=!0){A&&aA.foreachComponent(this.gameObject,e=>{e instanceof _D&&e!==this&&e.pause(!1)},!0),this._isPlaying=!1}stop(A=!0,e=!1){A&&aA.foreachComponent(this.gameObject,t=>{t instanceof _D&&t!==this&&t.stop(!1,e)},!0),this._isPlaying=!1,this._time=0,e&&this.reset()}reset(){var A;this._time=0,this._particleSystem&&(this._particleSystem.particleNum=0,this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1,(A=this.emission)==null||A.reset())}emit(A){if(this._particleSystem){this.onUpdate(),A=Math.min(A,this.maxParticles-this.currentParticles),this._state||(this._state=new laA),this._state.waitEmiting=A,this._state.time=0;const e=this._particleSystem.emitEnded;this._particleSystem.emitEnded=!1,this._particleSystem.emit(this.deltaTime,this._state,this._particleSystem.emitter.matrixWorld),this._particleSystem.emitEnded=e}}get playOnAwake(){return this.main.playOnAwake}set playOnAwake(A){this.main.playOnAwake=A}get renderer(){return this._renderer}get isPlaying(){return this._isPlaying}get currentParticles(){var A;return((A=this._particleSystem)==null?void 0:A.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===vd.World}get localspace(){return this.main.simulationSpace===vd.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,_e(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}addBehaviour(A){return this._particleSystem?(A instanceof Sr&&(A.system=this),he()&&console.log("add behaviour",A),this._particleSystem.addBehavior(A),!0):!1}removeBehaviour(A){if(!this._particleSystem)return!1;const e=this._particleSystem.behaviors,t=e.indexOf(A);return t!==-1&&e.splice(t,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(A){for(let e=0;e<A.length;e++){const t=A[e];if(!(t instanceof qd)){const i=new qd;nc(i,t),A[e]=i}}this._bursts=A}set subEmitterSystems(A){for(let e=0;e<A.length;e++){const t=A[e];if(!(t instanceof Hd)){const i=new Hd;nc(i,t),A[e]=i}}hh&&A.length>0&&console.log("SubEmitters: ",A,this),this._subEmitterSystems=A}onAfterDeserialize(A){if(this._subEmitterSystems&&Array.isArray(this._subEmitterSystems))for(const e of this._subEmitterSystems)e._deserialize(this.context,this.gameObject)}awake(){if(this._worldPositionFrame=-1,this._renderer=this.gameObject.getComponent(ps),!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 uA,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new GCA,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new caA(this),this._particleSystem=new lCA(this._interface),this._particleSystem.addBehavior(new raA(this)),this._particleSystem.addBehavior(new EaA(this)),this._particleSystem.addBehavior(new naA(this)),this._particleSystem.addBehavior(new CaA(this)),this._particleSystem.addBehavior(new QaA(this)),this._particleSystem.addBehavior(new BaA(this)),this._batchSystem.addSystem(this._particleSystem);const A=this._particleSystem.emitter;this.context.scene.add(A),this.inheritVelocity.system&&this.inheritVelocity.system!==this&&(this.inheritVelocity=this.inheritVelocity.clone()),this.inheritVelocity.awake(this),hh&&(console.log(this),this.gameObject.add(new Cs(1)))}start(){this.addSubParticleSystems(),this.updateLayers()}onDestroy(){var A,e,t,i;(A=this._container)==null||A.removeFromParent(),(e=this._batchSystem)==null||e.removeFromParent(),(t=this._particleSystem)==null||t.emitter.removeFromParent(),(i=this._particleSystem)==null||i.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 A;this.main&&(this._didPreWarm===!1&&((A=this.main)==null?void 0:A.prewarm)===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){var C;if(!((C=this.emission)!=null&&C.enabled)||this.emission.rateOverTime.getMax()<=0)return;const e=1/60,t=this.main.duration,i=this.main.startLifetime.getMax(),I=1e3,o=Math.min(Math.max(t,i)/Math.max(.01,this.main.simulationSpeed),I),s=Math.ceil(o/e),n=Date.now();hh&&console.log(`Particles ${this.name} - Prewarm for ${s} frames (${o} sec). Duration: ${t}, Lifetime: ${i}`);for(let a=0;a<s&&!(this.currentParticles>=this.maxParticles);a++){const B=Date.now()-n;if(B>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${B}`);break}this.onUpdate(),this.onSimulate(e)}}onSimulate(A){if(this._batchSystem){let e=this.context.time.frameCount%60===0;this._lastBatchesCount!==this._batchSystem.batches.length&&(this._lastBatchesCount=this._batchSystem.batches.length,e=!0),e&&this.updateLayers(),this._batchSystem.update(A)}this._time+=A,this._time>this.duration&&(this._time=0)}updateLayers(){if(this._batchSystem)for(let A=0;A<this._batchSystem.batches.length;A++){const e=this._batchSystem.batches[A];e.layers.disableAll();const t=this.layer;e.layers.mask=1<<t}}onUpdate(){var I,o;const A=this.renderer.getMaterial(this.trails.enabled);if(A&&A.version!=this.lastMaterialVersion&&this._particleSystem&&(this.lastMaterialVersion=A.version,this._particleSystem.texture=this._interface.texture),this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const e=this.context.mainCamera;if(e){const s=Vt(e);this._cameraScale=s.x}const t=!this.worldspace,i=this.gameObject;if(Jt(i,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),Vt(this.gameObject,this._worldScale),t&&this._container&&((I=this.gameObject)!=null&&I.parent)){const s=FP(this,aU);this._container.matrix.makeScale(s.x,s.y,s.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.update(this,this.context,this.main.simulationSpace,this.gameObject),this.noise.update(this.context),(o=this.inheritVelocity)==null||o.update(this.context),this.velocityOverLifetime.update(this)}addSubParticleSystems(){var A;if(this._subEmitterSystems&&this._particleSystem)for(const e of this._subEmitterSystems){e.particleSystem&&(e.particleSystem.__internalAwake?e.particleSystem.__internalAwake():he()&&console.warn("SubParticleSystem serialization issue(?)",e.particleSystem,e));const t=(A=e.particleSystem)==null?void 0:A._particleSystem;if(t){e.particleSystem._isUsedAsSubsystem=!0;const i=new XS(this,this._particleSystem,e.particleSystem,t);i.emitterType=e.type,i.emitterProbability=e.emitProbability,this._particleSystem.addBehavior(i)}else hh&&console.warn("Could not add SubParticleSystem",e,this)}}};let zi=_D;Gi([D(Zu)],zi.prototype,"colorOverLifetime",2);Gi([D(eI)],zi.prototype,"main",2);Gi([D(Tn)],zi.prototype,"emission",2);Gi([D(fr)],zi.prototype,"sizeOverLifetime",2);Gi([D(Si)],zi.prototype,"shape",2);Gi([D(Nt)],zi.prototype,"noise",2);Gi([D(Bi)],zi.prototype,"trails",2);Gi([D(mi)],zi.prototype,"velocityOverLifetime",2);Gi([D(eg)],zi.prototype,"limitVelocityOverLifetime",2);Gi([D(Dr)],zi.prototype,"inheritVelocity",2);Gi([D(lQ)],zi.prototype,"colorBySpeed",2);Gi([D(tI)],zi.prototype,"textureSheetAnimation",2);Gi([D(us)],zi.prototype,"rotationOverLifetime",2);Gi([D(To)],zi.prototype,"rotationBySpeed",2);Gi([D(YI)],zi.prototype,"sizeBySpeed",2);class Hd{constructor(){r(this,"particleSystem");r(this,"emitProbability",1);r(this,"properties");r(this,"type")}_deserialize(A,e){const t=this.particleSystem;if(t instanceof zi)return;let i="";t&&typeof t.guid=="string"&&(i=t.guid,this.particleSystem=aA.findByGuid(i,e)),hh&&!(this.particleSystem instanceof zi)&&console.warn("Could not find particle system for sub emitter",i,e,this)}}function FP(g,A){if(A.set(1,1,1),g.gameObject.parent&&g.localspace)switch(g.main.scalingMode){case XM.Local:A=Vt(g.gameObject.parent,A),A.x=1/A.x,A.y=1/A.y,A.z=1/A.z;break;default:if(!g.unsupported_scaling_mode){g.unsupported_scaling_mode=!0;const e="ParticleSystem scale mode "+XM[g.main.scalingMode]+" is not supported";he()&&fi(e),console.warn(e,g.name,g)}A=Vt(g.gameObject,A);break}return A}new w(1,1,1);new w(0,0,1);class XS{constructor(A,e,t,i){r(this,"type","NeedleParticleSubEmitter");r(this,"emitterType");r(this,"emitterProbability");r(this,"q_",new MA);r(this,"v_",new w);r(this,"v2_",new w);r(this,"_emitterMatrix",new GA);r(this,"_circularBuffer");this.system=A,this.particleSystem=e,this.subSystem=t,this.subParticleSystem=i,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const I=1e3;this._circularBuffer=new as(()=>new GA,I)}clone(){throw new Error("Method not implemented.")}initialize(A){A.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===CU.Birth&&this.run(A)}update(A,e){this.run(A)}frameUpdate(A){}toJSON(){}reset(){}run(A){if(this.subSystem.currentParticles>=this.subSystem.main.maxParticles||!this.subParticleSystem||!A.emissionState||this.emitterProbability&&Math.random()>this.emitterProbability)return;const e=this.system.deltaTime;if(this.emitterType===CU.Death){let i=A.life;if(A[FE]!==void 0&&(i=A[FE]),!(A.age+e*1.2>=i))return;const o=this.subSystem.main.maxParticles-this.subSystem.currentParticles;A.emissionState.waitEmiting=o}const t=new GA;t.set(1,0,0,A.position.x,0,1,0,A.position.y,0,0,1,A.position.z,0,0,0,1),this.particleSystem.worldSpace||t.multiplyMatrices(this._emitterMatrix,t),this.subParticleSystem.emit(e,A.emissionState,t)}}var haA=Object.defineProperty,daA=Object.getOwnPropertyDescriptor,uaA=(g,A,e,t)=>{for(var i=t>1?void 0:t?daA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&haA(A,e,i),i};class op extends hI{constructor(){super(...arguments);r(this,"granularity")}get typeName(){return"PixelationEffect"}onCreateEffect(){const e=new MY;return this.granularity.onValueChanged=t=>{e.granularity=t},e}}uaA([D(qe)],op.prototype,"granularity",2);ds("PixelationEffect",op);class Qc extends RA{constructor(){super(...arguments);r(this,"_didAssignPlayerColor",!1);r(this,"tryAssignColor",()=>{const e=aA.getComponentInParent(this.gameObject,Is);if(e&&e.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(e.owner),!0;const t=aA.getComponentInParent(this.gameObject,sg);return t!=null&&t.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(t.connectionId),!0):!1})}onEnable(){this.context.connection.beginListen(It.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(It.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield Z2(.2),!this.tryAssignColor()););}assignUserColor(e){const t=Qc.hashCode(e),i=Qc.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){const I=this.gameObject;this.assignColor(i,e,I)}else if(this.gameObject.children)for(const I of this.gameObject.children){const o=I;o.material&&o.material.color&&this.assignColor(i,e,o)}}assignColor(e,t,i){let I=i.material;I&&(I._playerMaterial!==t&&(I=I.clone(),I._playerMaterial=t,i.material=I),I.color=e)}static hashCode(e){var t=0,i,I;if(e.length===0)return t;for(i=0;i<e.length;i++)I=e.charCodeAt(i),t=(t<<5)-t+I,t|=0;return t}static colorFromHashCode(e){const t=(e&16711680)>>16,i=(e&65280)>>8,I=e&255;return new mA(t/255,i/255,I/255)}}async function KF(g){const{NeedleEngineHTMLElement:A}=await Promise.resolve().then(()=>RBA);A.observedAttributes.includes(g)||A.observedAttributes.push(g)}var paA=Object.defineProperty,faA=Object.getOwnPropertyDescriptor,sp=(g,A,e,t)=>{for(var i=t>1?void 0:t?faA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&paA(A,e,i),i};const es=IA("debugskybox");KF("skybox-image");KF("environment-image");function jx(g,A,e,t,i){const I=new bn;I.allowDrop=!1,I.allowNetworking=!1,I.background=e,I.environment=t,aA.addComponent(g.scene,I);const o=s=>{typeof s=="string"&&(es&&console.log(i,"CHANGED TO",s),I.setSkybox(s))};return fT(g.domElement,i,o),I.addEventListener("destroy",()=>{es&&console.log("Destroyed attribute remote skybox",i),DT(g.domElement,i,o)}),I.setSkybox(A)}st.addContextCreatedCallback(g=>{var I;const A=g.context,e=A.domElement.getAttribute("skybox-image"),t=A.domElement.getAttribute("environment-image"),i=new Array;if(e){es&&console.log("Creating remote skybox to load "+e),((I=A.mainCameraComponent)==null?void 0:I.clearFlags)!==YB.Skybox&&console.warn('"skybox-image" attribute has no effect: camera clearflags are not set to "Skybox"');const o=jx(A,e,!0,!1,"skybox-image");i.push(o)}if(t){es&&console.log("Creating remote environment to load "+t);const o=jx(A,t,!1,!0,"environment-image");i.push(o)}return i.length>0?au(i):Promise.resolve()});function KP(){return globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES||(globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES=new Array),globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES}function Vx(g){const e=KP().find(t=>t.src===g);return e?(es&&console.log("Skybox: Found previously loaded texture for "+g),e.texture):null}async function DaA(g){const A=await g;rN(A,!0),Tt(A)}function waA(g,A){const e=KP();for(;e.length>5;){const t=e.shift();t&&DaA(t.texture)}A.then(t=>rN(t,!1)),e.push({src:g,texture:A})}class bn extends RA{constructor(){super(...arguments);r(this,"url");r(this,"allowDrop",!0);r(this,"background",!0);r(this,"environment",!0);r(this,"allowNetworking",!0);r(this,"_loader");r(this,"_prevUrl");r(this,"_prevLoadedEnvironment");r(this,"_prevEnvironment",null);r(this,"_prevBackground",null);r(this,"validTextureTypes",[".hdr",".exr",".jpg",".jpeg",".png"]);r(this,"onDragOverEvent",e=>{if(this.allowDrop&&e.dataTransfer)for(const t of e.dataTransfer.types)(t==="text/uri-list"||t==="Files")&&e.preventDefault()});r(this,"onDrop",e=>{var t,i,I,o;if(this.allowDrop&&e.dataTransfer){for(const s of e.dataTransfer.types)if(es&&console.log(s),s==="text/uri-list"){const n=e.dataTransfer.getData(s);es&&console.log(s,n);let C=(i=(t=new RegExp(/polyhaven.com\/asset_img\/.+?\/(?<name>.+)\.png/).exec(n))==null?void 0:t.groups)==null?void 0:i.name;if(C||(C=(o=(I=new RegExp(/polyhaven\.com\/a\/(?<name>.+)/).exec(n))==null?void 0:I.groups)==null?void 0:o.name),es&&console.log(C),C){const a="https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/"+C+"_1k.exr";console.log(`[Remote Skybox] Setting skybox from url: ${a}`),e.preventDefault(),this.setSkybox(a);break}else if(this.isValidTextureType(n)){console.log("[Remote Skybox] Setting skybox from url: "+n),e.preventDefault(),this.setSkybox(n);break}else{console.warn(`[RemoteSkybox] Unknown url ${n}. 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 a=new CustomEvent("dropped-unknown-url",{detail:{sender:this,event:e,url:n,apply:B=>{e.preventDefault(),this.setSkybox(B)}}});this.dispatchEvent(a)}}else if(s=="Files"){const n=e.dataTransfer.files.item(0);if(es&&console.log(s,n),!n)continue;if(!this.isValidTextureType(n.name)){console.warn(`[RemoteSkybox]: File "${n.name}" is not supported. Supported files are ${this.validTextureTypes.join(", ")}`);return}if(Vx(n.name)===null){const C=new Blob([n]),a=URL.createObjectURL(C);e.preventDefault(),this.setSkybox(a,n.name)}else e.preventDefault(),this.setSkybox(n.name);break}}})}onEnable(){this.setSkybox(this.url),this.registerDropEvents()}onDisable(){var e;this.context.scene.environment===this._prevLoadedEnvironment&&(this.context.scene.environment=this._prevEnvironment,Wt.backgroundShouldBeTransparent(this.context)||(this.context.scene.background=this._prevBackground),this._prevLoadedEnvironment=void 0),this.unregisterDropEvents(),(e=this.context.mainCameraComponent)==null||e.applyClearFlags()}urlChangedSyncField(){this.allowNetworking&&this.url&&this.isRemoteTexture(this.url)&&this.setSkybox(this.url)}async setSkybox(e,t){var o;if(!this.activeAndEnabled||!e)return!1;if(t??(t=e),this.isValidTextureType(t)||console.warn("Potentially invalid skybox url",t,"on",this.name),es&&console.log("Remote skybox url?: "+e),this._prevUrl===e&&this._prevLoadedEnvironment)return this.applySkybox(),!0;(o=this._prevLoadedEnvironment)==null||o.dispose(),this._prevLoadedEnvironment=void 0,this._prevUrl=e;const i=await this.loadTexture(e,t);if(!i||!this.enabled)return!1;this.url=e;const I=e.lastIndexOf("/");return i.name=e.substring(I>=0?I+1:0),this._loader instanceof Un&&(i.colorSpace=de),this._prevLoadedEnvironment=i,this.applySkybox(),!0}async loadTexture(e,t){var C,a,B,Q,E;if(!e)return Promise.resolve(null);t??(t=e);const i=Vx(t);if(i){const c=await i;if(((a=(C=c.source)==null?void 0:C.data)==null?void 0:a.length)>0||(E=(Q=(B=c.source)==null?void 0:B.data)==null?void 0:Q.data)!=null&&E.length)return c}const I=t.endsWith(".exr"),o=t.endsWith(".hdr");I?this._loader instanceof Uw||(this._loader=new Uw):o?this._loader instanceof JM||(this._loader=new JM):this._loader instanceof Un||(this._loader=new Un),es&&console.log("Loading skybox: "+e);const s=this._loader.loadAsync(e);return waA(t,s),await s}applySkybox(){var t;const e=this._prevLoadedEnvironment;e&&(e.mapping=zE,e.needsUpdate=!0,this.context.scene.background!==e&&(this._prevBackground=this.context.scene.background),this.context.scene.environment!==e&&(this._prevEnvironment=this.context.scene.environment),es&&console.log("Set remote skybox",this.url),this.environment&&(this.context.scene.environment=e),this.background&&!Wt.backgroundShouldBeTransparent(this.context)&&(this.context.scene.background=e),((t=this.context.mainCameraComponent)==null?void 0:t.backgroundBlurriness)!==void 0&&(this.context.scene.backgroundBlurriness=this.context.mainCameraComponent.backgroundBlurriness))}isRemoteTexture(e){return e.startsWith("http://")||e.startsWith("https://")}isValidTextureType(e){for(const t of this.validTextureTypes)if(e.endsWith(t))return!0;return!1}registerDropEvents(){this.unregisterDropEvents(),this.context.domElement.addEventListener("dragover",this.onDragOverEvent),this.context.domElement.addEventListener("drop",this.onDrop)}unregisterDropEvents(){this.context.domElement.removeEventListener("dragover",this.onDragOverEvent),this.context.domElement.removeEventListener("drop",this.onDrop)}}sp([HN(bn.prototype.urlChangedSyncField),D(URL)],bn.prototype,"url",2);sp([D()],bn.prototype,"allowDrop",2);sp([D()],bn.prototype,"background",2);sp([D()],bn.prototype,"environment",2);sp([D()],bn.prototype,"allowNetworking",2);var yaA=Object.defineProperty,SaA=Object.getOwnPropertyDescriptor,Ho=(g,A,e,t)=>{for(var i=t>1?void 0:t?SaA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&yaA(A,e,i),i};const po=IA("debugsceneswitcher"),TD="scene";KF(TD);const wa=Promise.resolve(!1);class uI extends RA{constructor(){super(...arguments);r(this,"autoLoadFirstScene",!0);r(this,"scenes");r(this,"loadingScene");r(this,"queryParameterName","scene");r(this,"useSceneName",!0);r(this,"clamp",!0);r(this,"useHistory",!0);r(this,"useKeyboard",!0);r(this,"useSwipe",!0);r(this,"useSceneLighting",!0);r(this,"preloadNext",1);r(this,"preloadPrevious",1);r(this,"preloadConcurrent",2);r(this,"_currentIndex",-1);r(this,"_currentScene");r(this,"_engineElementOverserver");r(this,"_preloadScheduler");r(this,"onPopState",async e=>{if(!this.useHistory)return;const t=this.useHistory;try{this.useHistory=!1;let i=!1;if(this.queryParameterName&&(i=await this.tryLoadFromQueryParam()),!i){const I=e==null?void 0:e.state;if(I&&I.startsWith(this.guid)){const o=I.substr(this.guid.length+2);po&&console.log("PopState",o),await this.trySelectSceneFromValue(o)}}}finally{this.useHistory=t}});r(this,"normalizedSwipeThresholdX",.1);r(this,"_didSwipe",!1);r(this,"onInputPointerMove",e=>{if(this.useSwipe&&!this._didSwipe&&e.button===0&&e.pointerType==="touch"&&this.context.input.getPointerPressedCount()===1){const t=this.context.input.getPointerPositionDelta(e.button);if(t){const i=t.x/this.context.domWidth;i>=this.normalizedSwipeThresholdX?(this._didSwipe=!0,this.selectPrev()):i<=-this.normalizedSwipeThresholdX&&(this._didSwipe=!0,this.selectNext())}}});r(this,"onInputPointerUp",e=>{e.button===0&&(this._didSwipe=!1)});r(this,"onInputKeyDown",e=>{if(!this.useKeyboard||!this.scenes)return;const t=e.key.toLowerCase();if(!t)return;const i=parseInt(t)-1;if(i>=0){this.trySelectSceneFromValue(i);return}switch(t){case"arrowright":case"d":this.selectNext();break;case"arrowleft":case"a":this.selectPrev();break}});r(this,"__lastSwitchScene");r(this,"__lastSwitchScenePromise");r(this,"_currentlyLoadingScene");r(this,"_lastLoadingScene");r(this,"_loadingScenePromise");r(this,"_isCurrentlyLoading",!1);r(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=[]),po&&console.log("SceneSwitcher",this)}async onEnable(){if(globalThis.addEventListener("popstate",this.onPopState),this.context.input.addEventListener(ni.KeyDown,this.onInputKeyDown),this.context.input.addEventListener(ni.PointerMove,this.onInputPointerMove),this.context.input.addEventListener(ni.PointerUp,this.onInputPointerUp),this._engineElementOverserver||(this._engineElementOverserver=new MutationObserver(e=>{for(const t of e)if(t.type==="attributes"&&t.attributeName===TD){const i=this.context.domElement.getAttribute(TD);i!==null&&this.trySelectSceneFromValue(i)}})),this._engineElementOverserver.observe(this.context.domElement,{attributes:!0}),this._preloadScheduler||(this._preloadScheduler=new maA(this)),this._preloadScheduler.maxLoadAhead=this.preloadNext,this._preloadScheduler.maxLoadBehind=this.preloadPrevious,this._preloadScheduler.maxConcurrent=this.preloadConcurrent,this._preloadScheduler.begin(),this.autoLoadFirstScene&&this._currentIndex===-1&&!await this.tryLoadFromQueryParam()){const e=this.context.domElement.getAttribute(TD);try{(e===null||!await this.trySelectSceneFromValue(e))&&this._currentIndex===-1&&this.select(0)}finally{}}}onDisable(){var e;globalThis.removeEventListener("popstate",this.onPopState),this.context.input.removeEventListener(ni.KeyDown,this.onInputKeyDown),this.context.input.removeEventListener(ni.PointerMove,this.onInputPointerMove),this.context.input.removeEventListener(ni.PointerUp,this.onInputPointerUp),(e=this._preloadScheduler)==null||e.stop()}addScene(e){if(typeof e=="string"){let t=this.context.addressables.findAssetReference(e);return t||(t=new tt(e),this.context.addressables.registerAssetReference(t)),this.scenes.push(t),t}return this.scenes.push(e),e}selectNext(){return this.select(this._currentIndex+1)}selectPrev(){return this.select(this._currentIndex-1)}select(e){var i,I,o;if(po&&console.log("select",e),typeof e=="object"&&console.warn('Switching to "'+e+'" might not work. Please either use an index or a AssetReference (not a scene reference)'),typeof e=="string"){const s=(i=this.scenes)==null?void 0:i.find(n=>n.uri===e);if(!s){const n=tt.getOrCreate(this.sourceId??"",e,this.context);return this.switchScene(n)}if(s)e=(I=this.scenes)==null?void 0:I.indexOf(s);else return wa}if(!((o=this.scenes)!=null&&o.length))return wa;if(e<0){if(this.clamp)return wa;e=this.scenes.length-1}else if(e>=this.scenes.length){if(this.clamp)return wa;e=0}const t=this.scenes[e];return this.switchScene(t)}async switchScene(e){if(!(e instanceof tt)){const i=typeof e;return i==="string"?this.select(e):i==="number"?this.select(e):(console.warn("SceneSwitcher: Can't switch to scene",e,"of type",i),!1)}return e.uri===this.sourceId?(console.warn("SceneSwitcher: can't load own scene - prevent recursive loading",this.sourceId),!1):this.__lastSwitchScene===e&&this.__lastSwitchScenePromise?this.__lastSwitchScenePromise:(this.__lastSwitchScene=e,this.__lastSwitchScenePromise=this.__internalSwitchScene(e),await this.__lastSwitchScenePromise)}async __internalSwitchScene(e){var i,I;if(this._currentScene){po&&console.log("UNLOAD",e.uri);const o=this.tryGetSceneEventListener(this._currentScene.asset);if(o!=null&&o.sceneClosing){const s=o.sceneClosing();s instanceof Promise&&await s}this._currentScene.unload()}this._currentScene=void 0;const t=this._currentIndex=((i=this.scenes)==null?void 0:i.indexOf(e))??-1;try{this._currentlyLoadingScene=e,this._currentLoadingProgress=new ProgressEvent("progress",{loaded:0,total:1});const o=new CustomEvent("loadscene-start",{detail:{scene:e,switcher:this,index:t}});this.dispatchEvent(o),await this.onStartLoading(),await e.loadAssetAsync((n,C)=>{this._currentLoadingProgress=C,this.dispatchEvent(C)}).catch(console.error),await this.onEndLoading();const s=new CustomEvent("loadscene-finished",{detail:{scene:e,switcher:this,index:t}});if(this.dispatchEvent(s),this._currentLoadingProgress=void 0,this._currentlyLoadingScene=void 0,s.defaultPrevented)return po&&console.warn("Adding loaded scene prevented:",e,s),!1;if(!e.asset)return po&&console.warn("Failed loading scene:",e),!1;if(this._currentIndex===t){if(po&&console.log("ADD",e.uri),this._currentScene=e,aA.add(e.asset,this.gameObject),this.useSceneLighting&&this.context.sceneLighting.enable(e),this.useHistory&&t>=0){let a=t.toString();if(this.useSceneName&&(a=zx(e.uri)),(I=this.queryParameterName)!=null&&I.length)aw(this.queryParameterName,a,this.useHistory);else{const B=history.state,Q=this.guid+"::"+t;B!==Q&&history.pushState(Q,"unused",location.href)}}const n=this.tryGetSceneEventListener(e.asset);if(n!=null&&n.sceneOpened){const a=n.sceneOpened(this);a instanceof Promise&&await a}const C=new CustomEvent("scene-opened",{detail:{scene:e,switcher:this,index:t}});return this.dispatchEvent(C),!0}}catch(o){console.error(o)}return!1}preload(e){if(e>=0&&e<this.scenes.length){const t=this.scenes[e];if(t instanceof tt)return t.preload()}return wa}tryLoadFromQueryParam(){var t;if(!((t=this.queryParameterName)!=null&&t.length))return wa;const e=IA(this.queryParameterName);return typeof e=="boolean"?wa:this.trySelectSceneFromValue(e)}trySelectSceneFromValue(e){if(typeof e=="string"){const t=parseInt(e);if(t>=0&&t<this.scenes.length)return this.select(t);{const i=e.toLowerCase();for(let I=0;I<this.scenes.length;I++){const o=this.scenes[I];if(o&&zx(o.uri).toLowerCase().includes(i))return this.select(I)}}}else if(typeof e=="number"&&e>=0&&e<this.scenes.length)return this.select(e);return No()&&console.warn('Can not find scene: "'+e+'"',this),wa}async onStartLoading(){var e,t;if(this._isCurrentlyLoading=!0,this.loadingScene&&(this._lastLoadingScene!==this.loadingScene&&(this._loadingScenePromise=void 0),this._lastLoadingScene=this.loadingScene,this._loadingScenePromise||(this._loadingScenePromise=(e=this.loadingScene)==null?void 0:e.loadAssetAsync()),await this._loadingScenePromise,this._isCurrentlyLoading&&((t=this.loadingScene)!=null&&t.asset))){po&&console.log("Add loading scene",this.loadingScene.uri,this.loadingScene.asset);const i=this.loadingScene.asset;aA.add(i,this.gameObject);const I=this.tryGetSceneEventListener(i);if(I!=null&&I.sceneOpened){const o=I.sceneOpened(this);o instanceof Promise&&await o}}if(this._isCurrentlyLoading){const i=this.tryGetSceneEventListener(this.gameObject);if(i&&i.sceneOpened){const I=i.sceneOpened(this);I instanceof Promise&&await I}}}async onEndLoading(){var e;if(this._isCurrentlyLoading=!1,(e=this.loadingScene)!=null&&e.asset){po&&console.log("Remove loading scene",this.loadingScene.uri);const t=this.loadingScene.asset,i=this.tryGetSceneEventListener(t);if(typeof(i==null?void 0:i.sceneClosing)=="function"){const I=i.sceneClosing();I instanceof Promise&&await I}aA.remove(t)}if(!this._isCurrentlyLoading){const t=this.tryGetSceneEventListener(this.gameObject);if(t&&t.sceneClosing){const i=t.sceneClosing();i instanceof Promise&&await i}}}tryGetSceneEventListener(e,t=0){const i=aA.foreachComponent(e,I=>I.sceneClosing?I:void 0);if(t===0&&!i&&e.children.length)for(const I of e.children){const o=this.tryGetSceneEventListener(I,t+1);if(o)return o}return i||null}}Ho([D()],uI.prototype,"autoLoadFirstScene",2);Ho([D(tt)],uI.prototype,"scenes",2);Ho([D(tt)],uI.prototype,"loadingScene",2);Ho([D()],uI.prototype,"queryParameterName",2);Ho([D()],uI.prototype,"useSceneName",2);Ho([D()],uI.prototype,"clamp",2);Ho([D()],uI.prototype,"useHistory",2);Ho([D()],uI.prototype,"useKeyboard",2);Ho([D()],uI.prototype,"useSwipe",2);Ho([D()],uI.prototype,"useSceneLighting",2);Ho([D()],uI.prototype,"preloadNext",2);Ho([D()],uI.prototype,"preloadPrevious",2);Ho([D()],uI.prototype,"preloadConcurrent",2);function zx(g){const A=g.split("/").pop(),e=A==null?void 0:A.split(".").shift();return e!=null&&e.length?e:g}class maA{constructor(A,e=1,t=1,i=2){r(this,"maxLoadAhead");r(this,"maxLoadBehind");r(this,"maxConcurrent");r(this,"_isRunning",!1);r(this,"_switcher");r(this,"_loadTasks",[]);r(this,"_maxConcurrentLoads",1);this._switcher=A,this.maxLoadAhead=e,this.maxLoadBehind=t,this.maxConcurrent=i}begin(){if(this._isRunning)return;po&&console.log("Preload begin"),this._isRunning=!0;let A=-1,e,t;const i=this._switcher.scenes,I=setInterval(()=>{if(this.allLoaded()&&(po&&console.log("All scenes loaded"),this.stop()),!this._isRunning){clearInterval(I);return}if(this.canLoadNewScene()===!1)return;A!==this._switcher.currentIndex&&(A=this._switcher.currentIndex,t=0,e=0);const o=t%2===0;o&&(e+=1),t+=1;const s=o?this.maxLoadAhead:this.maxLoadBehind;if(e>s)return;const n=o?A+e:A-e;if(n<0||n<0||n>=i.length)return;const C=i[n];new GaA(n,C,this._loadTasks)},200)}stop(){this._isRunning=!1}canLoadNewScene(){return this._loadTasks.length<this._maxConcurrentLoads}allLoaded(){if(this._switcher.scenes){for(const A of this._switcher.scenes)if((A==null?void 0:A.isLoaded())===!1)return!1}return!0}}class GaA{constructor(A,e,t){r(this,"index");r(this,"asset");r(this,"tasks");this.index=A,this.asset=e,this.tasks=t,t.push(this),this.awaitLoading()}async awaitLoading(){this.asset&&!this.asset.isLoaded()&&(po&&console.log("Preload start: "+this.asset.uri,this.index),await this.asset.preload(),po&&console.log("Preload finished: "+this.asset.uri,this.index));const A=this.tasks.indexOf(this);A>=0&&this.tasks.splice(A,1)}}function kaA(){return new Promise((g,A)=>{const t=()=>{t!=null&&(document.removeEventListener("pointerdown",t),document.removeEventListener("click",t),document.removeEventListener("dragstart",t),document.removeEventListener("touchstart",t),g())};document.addEventListener("pointerdown",t),document.addEventListener("click",t),document.addEventListener("dragstart",t),document.addEventListener("touchstart",t)})}async function MaA(g){await kaA(),g()}var UaA=Object.defineProperty,RaA=Object.getOwnPropertyDescriptor,Yo=(g,A,e,t)=>{for(var i=t>1?void 0:t?RaA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&UaA(A,e,i),i};const ug=IA("debugvideo");var JP=(g=>(g[g.None=0]="None",g[g.AdjustHeight=1]="AdjustHeight",g[g.AdjustWidth=2]="AdjustWidth",g))(JP||{}),bP=(g=>(g[g.VideoClip=0]="VideoClip",g[g.Url=1]="Url",g))(bP||{}),vP=(g=>(g[g.CameraFarPlane=0]="CameraFarPlane",g[g.CameraNearPlane=1]="CameraNearPlane",g[g.RenderTexture=2]="RenderTexture",g[g.MaterialOverride=3]="MaterialOverride",g))(vP||{});class cg extends RA{constructor(){super();r(this,"playOnAwake",!0);r(this,"aspectMode",0);r(this,"clip",null);r(this,"source",1);r(this,"_url",null);r(this,"renderMode");r(this,"targetMaterialProperty");r(this,"targetMaterialRenderer");r(this,"targetTexture");r(this,"time",0);r(this,"_playbackSpeed",1);r(this,"_isLooping",!1);r(this,"_muted",!1);r(this,"_audioOutputMode",2);r(this,"playInBackground",!0);r(this,"_crossOrigin","anonymous");r(this,"_videoElement",null);r(this,"_videoTexture",null);r(this,"_videoMaterial",null);r(this,"_isPlaying",!1);r(this,"wasPlaying",!1);r(this,"visibilityChanged",e=>{switch(document.visibilityState){case"hidden":this.playInBackground||(this.wasPlaying=this._isPlaying,this.pause());break;case"visible":this.wasPlaying&&!this._isPlaying&&this.play();break}});r(this,"_receivedInput",!1);r(this,"_overlay",null);r(this,"_targetObjects");r(this,"_updateAspectRoutineId",-1);r(this,"_hls");r(this,"onHlsAvailable",()=>{var e;ug&&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),(e=this._videoElement)==null||e.play(),ug&&console.log("HLS: loaded",this.clip))});MaA(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[],IA("videoscreenspace")&&window.addEventListener("keydown",e=>{e.key==="f"&&(this.screenspace=!this.screenspace)})}get url(){return this._url}set url(e){const i=this._url!==e;this.__didAwake?i&&this.setClipURL(e??""):this._url=e}get playbackSpeed(){var e;return((e=this._videoElement)==null?void 0:e.playbackRate)??this._playbackSpeed}set playbackSpeed(e){this._playbackSpeed=e,this._videoElement&&(this._videoElement.playbackRate=e)}get isLooping(){var e;return((e=this._videoElement)==null?void 0:e.loop)??this._isLooping}set isLooping(e){this._isLooping=e,this._videoElement&&(this._videoElement.loop=e)}get currentTime(){var e;return((e=this._videoElement)==null?void 0:e.currentTime)??this.time}set currentTime(e){this._videoElement?this._videoElement.currentTime=e:this.time=e}get isPlaying(){const e=this._videoElement;if(e){if(e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>e.HAVE_CURRENT_DATA)return!0;if(e.srcObject&&e.srcObject.active)return!0}return!1}get crossOrigin(){var e;return((e=this._videoElement)==null?void 0:e.crossOrigin)??this._crossOrigin}set crossOrigin(e){this._crossOrigin=e,this._videoElement&&(e!==null?this._videoElement.setAttribute("crossorigin",e):this._videoElement.removeAttribute("crossorigin"))}get videoMaterial(){return!this._videoMaterial&&!this.create(!1)?null:this._videoMaterial}get videoTexture(){return!this._videoTexture&&!this.create(!1)?null:this._videoTexture}get videoElement(){return!this._videoElement&&!this.create(!1)?null:this._videoElement}get muted(){var e;return((e=this._videoElement)==null?void 0:e.muted)??this._muted}set muted(e){this._muted=e,this._videoElement&&(this._videoElement.muted=e)}get currentVideo(){return this.clip}set audioOutputMode(e){e!==this._audioOutputMode&&(e===1&&he()&&console.warn("VideoAudioOutputMode.AudioSource is not yet implemented"),this._audioOutputMode=e,this.updateVideoElementSettings())}get audioOutputMode(){return this._audioOutputMode}preloadVideo(){ug&&console.log("Video Preload: "+this.name,this.clip),this.create(!1)}preload(){this.preloadVideo()}setVideo(e){this.clip=e,this.source=0,this._videoElement?(this._videoElement.srcObject=e,this._isPlaying&&this.play(),this.updateAspect()):this.create(this.playOnAwake)}setClipURL(e){this._url!==e&&(this._url=e,this.source=1,ug&&console.log("set url",e),this._videoElement?e.endsWith(".m3u8")||e.includes(".m3u")?this.ensureM3UCanBePlayed():(this._videoElement.src=e,this._isPlaying&&(this.stop(),this.play())):this.create(this.playOnAwake))}onEnable(){var e,t;ug&&console.log("VideoPlayer.onEnable",bP[this.source],this.clip,this.url,this),window.addEventListener("visibilitychange",this.visibilityChanged),this.playOnAwake===!0?this.create(!0):this.preloadVideo(),this.screenspace?(e=this._overlay)==null||e.start():(t=this._overlay)==null||t.stop()}onDisable(){var e;window.removeEventListener("visibilitychange",this.visibilityChanged),(e=this._overlay)==null||e.stop(),this.pause()}onDestroy(){var e;this._videoElement&&((e=this.videoElement)==null||e.remove(),this._videoElement=null),this._videoTexture&&(this._videoTexture.dispose(),this._videoTexture=null)}play(){var e,t;if(this._videoElement||this.create(!1),!this._videoElement){ug&&console.warn("Can not play: no video element found",this);return}if(!(this._isPlaying&&!((e=this._videoElement)!=null&&e.ended)&&!((t=this._videoElement)!=null&&t.paused))){if(this._isPlaying=!0,this._receivedInput||(this._videoElement.muted=!0),this.handleBeginPlaying(!1),this.shouldUseM3U){this.ensureM3UCanBePlayed();return}ug&&console.log("Video Play()",this.clip,this._videoElement,this.time),this._videoElement.currentTime=this.time,this._videoElement.play().catch(i=>{var I;console.log(i),ug&&console.error("Error playing video",i,"CODE="+i.code,(I=this.videoElement)==null?void 0:I.src,this),setTimeout(()=>{this._isPlaying&&!this.destroyed&&this.activeAndEnabled&&this.play()},1e3)}),ug&&console.log("play",this._videoElement,this.time)}}stop(){this._isPlaying=!1,this.time=0,this._videoElement&&(this._videoElement.currentTime=0,this._videoElement.pause(),ug&&console.log("STOP",this))}pause(){var e,t;this.time=((e=this._videoElement)==null?void 0:e.currentTime)??0,this._isPlaying=!1,(t=this._videoElement)==null||t.pause(),ug&&console.log("PAUSE",this,this.currentTime)}create(e){let t;switch(this.source){case 0:t=this.clip;break;case 1:t=this.url,!(t!=null&&t.length)&&typeof this.clip=="string"&&(t=this.clip);break}return t?(this._videoElement||(ug&&console.warn("Create VideoElement",this),this._videoElement=this.createVideoElement(),this.context.domElement.shadowRoot.prepend(this._videoElement),this.updateVideoElementStyles()),typeof t=="string"?(ug&&console.log("Set Video src",t),this._videoElement.src=t):(ug&&console.log("Set Video srcObject",t),this._videoElement.srcObject=t),this._videoTexture||(this._videoTexture=new K_(this._videoElement)),this._videoTexture.flipY=!1,this._videoTexture.colorSpace=de,e&&this.handleBeginPlaying(e),ug&&console.log("Video: handle playing done...",t,e),!0):(ug&&console.warn("No video source set",this),!1)}updateAspect(){this.aspectMode!==0&&this.startCoroutine(this.updateAspectImpl())}get screenspace(){var e;return((e=this._overlay)==null?void 0:e.enabled)??!1}set screenspace(e){var t;if(e){if(!this._videoTexture)return;this._overlay||(this._overlay=new NaA(this.context)),this._overlay.add(this._videoTexture)}else(t=this._overlay)==null||t.remove(this._videoTexture);this._overlay&&(this._overlay.enabled=e)}createVideoElement(){const e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),ug&&console.log("created video element",e),e}handleBeginPlaying(e){var I,o;if(!this.activeAndEnabled||!this._videoElement)return;this._targetObjects.length=0;let t=this.gameObject;switch(this.renderMode){case 3:t=(I=this.targetMaterialRenderer)==null?void 0:I.gameObject,t||(t=(o=aA.getComponent(this.gameObject,Oi))==null?void 0:o.gameObject);break;case 2:console.error("VideoPlayer renderTexture not implemented yet. Please use material override instead");return}if(!t){console.error("Missing target for video material renderer",this.name,vP[this.renderMode],this);return}const i=t.material;if(i){this._targetObjects.push(t),i!==this._videoMaterial&&(this._videoMaterial=i.clone(),t.material=this._videoMaterial);const s="map",n=this._videoMaterial;if(!this.targetMaterialProperty)n[s]=this._videoTexture;else switch(this.targetMaterialProperty){default:n[s]=this._videoTexture;break}}else{console.warn("Can not play video, no material found, this might be a multimaterial case which is not supported yet");return}this.updateVideoElementSettings(),this.updateVideoElementStyles(),e&&(this.shouldUseM3U&&this.ensureM3UCanBePlayed(),this.play())}updateVideoElementSettings(){if(!this._videoElement)return;this._videoElement.loop=this._isLooping,this._videoElement.currentTime=this.currentTime,this._videoElement.playbackRate=this._playbackSpeed,this._videoElement.playsInline=!0;let e=!this._receivedInput||this.audioOutputMode===0;!e&&this._muted&&(e=!0),this._videoElement.muted=e,this.playOnAwake&&(this._videoElement.autoplay=!0)}updateVideoElementStyles(){this._videoElement&&(this._videoElement.style.userSelect="none",this._videoElement.style.visibility="hidden",this._videoElement.style.display="none",this.updateAspect())}*updateAspectImpl(){const e=++this._updateAspectRoutineId,t=void 0,i=this.clip;for(;e===this._updateAspectRoutineId&&this.aspectMode!==0&&this.clip&&i===this.clip&&this._isPlaying;){if(!i||typeof i=="string")return;let I;for(const o of i.getVideoTracks()){const s=o.getSettings();if(s&&s.width&&s.height){I=s.width/s.height;break}else I=this.context.renderer.domElement.clientWidth/this.context.renderer.domElement.clientHeight}if(I===void 0){for(let o=0;o<10;o++)yield;if(!this.isPlaying)break;continue}if(t===I){yield;continue}for(const o of this._targetObjects){let s=1;if(o.parent){const n=Vt(o.parent);s=n.x/n.y}switch(this.aspectMode){case 1:o.scale.y=1/I*o.scale.x*s;break;case 2:o.scale.x=I*o.scale.y*s;break}}for(let o=0;o<3;o++)yield}}get shouldUseM3U(){return this.url!=null&&(this.url.endsWith(".m3u8")||this.url.endsWith(".m3u"))&&this.source===1}ensureM3UCanBePlayed(){if(!this.shouldUseM3U)return;let e=document.head.querySelector("script[data-hls_library]");e?globalThis.Hls?this.onHlsAvailable():e.addEventListener("load",this.onHlsAvailable):(ug&&console.log("HLS: load script"),e=document.createElement("script"),e.dataset.hls_library="hls.js",e.src="https://cdn.jsdelivr.net/npm/hls.js@1",e.addEventListener("load",this.onHlsAvailable),document.head.append(e))}}Yo([D()],cg.prototype,"playOnAwake",2);Yo([D()],cg.prototype,"aspectMode",2);Yo([D(URL)],cg.prototype,"clip",2);Yo([D()],cg.prototype,"source",2);Yo([D(URL)],cg.prototype,"url",1);Yo([D()],cg.prototype,"renderMode",2);Yo([D()],cg.prototype,"targetMaterialProperty",2);Yo([D(Oi)],cg.prototype,"targetMaterialRenderer",2);Yo([D(fe)],cg.prototype,"targetTexture",2);Yo([D()],cg.prototype,"time",2);Yo([D()],cg.prototype,"playbackSpeed",1);Yo([D()],cg.prototype,"isLooping",1);Yo([D()],cg.prototype,"audioOutputMode",1);class NaA{constructor(A){r(this,"context");r(this,"_videos",[]);r(this,"_screenspaceModeQuad");r(this,"_isInScreenspaceMode",!1);r(this,"_input");this.context=A,this._input=new FaA(this)}get enabled(){return this._isInScreenspaceMode}set enabled(A){A?this.start():this.stop()}add(A){this._videos.indexOf(A)===-1&&this._videos.push(A)}remove(A){if(!A)return;const e=this._videos.indexOf(A);e>=0&&this._videos.splice(e,1)}start(){var i;if(this._isInScreenspaceMode||this._videos.length<0)return;const A=this._videos[this._videos.length-1];if(!A)return;if(this._isInScreenspaceMode=!0,!this._screenspaceModeQuad){if(this._screenspaceModeQuad=Du.createPrimitive(_B.Quad,{material:new KaA(A)}),!this._screenspaceModeQuad)return;this._screenspaceModeQuad.geometry.scale(2,2,2)}const e=this._screenspaceModeQuad;this.context.scene.add(e),this.updateScreenspaceMaterialUniforms();const t=e.material;t==null||t.reset(),(i=this._input)==null||i.enable(t)}stop(){var A;this._isInScreenspaceMode=!1,this._screenspaceModeQuad&&((A=this._input)==null||A.disable(),this._screenspaceModeQuad.removeFromParent())}updateScreenspaceMaterialUniforms(){var e;const A=(e=this._screenspaceModeQuad)==null?void 0:e.material;A&&(A.screenAspect=this.context.domElement.clientWidth/this.context.domElement.clientHeight)}}class FaA{constructor(A){r(this,"_onResizeScreenFn");r(this,"_onKeyUpFn");r(this,"_onMouseWheelFn");r(this,"context");r(this,"overlay");r(this,"_material");r(this,"_isPinching",!1);r(this,"_lastPinch",0);this.overlay=A,this.context=A.context}enable(A){this._material=A,window.addEventListener("resize",this._onResizeScreenFn=()=>{this.overlay.updateScreenspaceMaterialUniforms()}),window.addEventListener("keyup",this._onKeyUpFn=i=>{i.key==="Escape"&&this.overlay.stop()}),window.addEventListener("wheel",this._onMouseWheelFn=i=>{this.overlay.enabled&&(A.zoom+=i.deltaY*5e-4,i.preventDefault())},{passive:!1});const e=new iA;window.addEventListener("mousemove",i=>{if(this.overlay.enabled&&this.context.input.getPointerPressed(0)){const I=new iA(i.movementX,i.movementY);I.x/=this.context.domElement.clientWidth,I.y/=this.context.domElement.clientHeight,e.set(I.x,I.y),e.multiplyScalar(A.zoom/-this.context.time.deltaTime*.01),A.offset=A.offset.add(e)}}),window.addEventListener("pointermove",i=>{this.overlay.enabled&&this.context.input.getPointerPressed(0)&&this.context.input.getTouchesPressedCount()===1&&(e.set(i.movementX,i.movementY),e.multiplyScalar(A.zoom*-this.context.time.deltaTime*.05),A.offset=A.offset.add(e))});let t=0;window.addEventListener("touchstart",i=>{if(i.touches.length<2){this.context.time.time-t<.3&&this.overlay.stop(),t=this.context.time.time;return}this._isPinching=!0,this._lastPinch=0}),window.addEventListener("touchmove",i=>{if(!this._isPinching||!this._material)return;const I=i.touches[0],o=i.touches[1],s=I.clientX-o.clientX,n=I.clientY-o.clientY,C=Math.sqrt(s*s+n*n);if(this._lastPinch!==0){const a=C-this._lastPinch;this._material.zoom-=a*.004}this._lastPinch=C}),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 KaA extends Ke{constructor(e){super();r(this,"_offset",new iA);this.uniforms={map:{value:e},screenAspect:{value:1},offsetScale:{value:new Ae(0,0,1,1)}},this.vertexShader=`
6955
6955
  uniform sampler2D map;
6956
6956
  uniform float screenAspect;
6957
6957
  uniform vec4 offsetScale;
@@ -7015,7 +7015,7 @@ void main() {
7015
7015
  // be blended onto the scene.
7016
7016
  gl_FragColor = vec4(direct, max);
7017
7017
  return;
7018
- `)}}applyShadowMaterial(){if(this.targetMesh)if(this.targetMesh.material.type!=="ShadowMaterial"){const e=new by;e.color=this.shadowColor,e.opacity=this.shadowColor.alpha,this.applyMaterialOptions(e),this.targetMesh.material=e}else{const e=this.targetMesh.material;e.color=this.shadowColor,e.opacity=this.shadowColor.alpha,this.applyMaterialOptions(e)}}applyOccluderMaterial(){if(this.targetMesh){let e=this.targetMesh.material;if(!e){const t=new rt;this.targetMesh.material=t,e=t}e.depthWrite=!0,e.stencilWrite=!0,e.colorWrite=!1,this.gameObject.renderOrder=-100}}applyMaterialOptions(e){e&&(e.depthWrite=!1,e.stencilWrite=!1)}}qP([D()],Cp.prototype,"mode",2);qP([D(Mt)],Cp.prototype,"shadowColor",2);var HaA=Object.defineProperty,YaA=Object.getOwnPropertyDescriptor,A0=(g,A,e,t)=>{for(var i=t>1?void 0:t?YaA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&HaA(A,e,i),i},ik;const xP=(ik=class extends RA{constructor(){super(...arguments);r(this,"target",null);r(this,"followFactor",.1);r(this,"rotateFactor",.1);r(this,"positionAxes",RE.All);r(this,"flipForward",!1);r(this,"_firstUpdate",!0)}onBeforeRender(){this.updateNow(!1)}updateNow(A){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){const e=_e(this.target),t=this._firstUpdate||A?1:te.clamp01(this.context.time.deltaTime*this.followFactor),i=this.worldPosition;this.positionAxes&RE.X&&(i.x=te.lerp(i.x,e.x,t)),this.positionAxes&RE.Y&&(i.y=te.lerp(i.y,e.y,t)),this.positionAxes&RE.Z&&(i.z=te.lerp(i.z,e.z,t)),this.worldPosition=i}if(this.rotateFactor>0){const e=Jt(this.target);this.flipForward&&e.premultiply(xP._invertForward);const t=this._firstUpdate||A?1:te.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(e,t)}this._firstUpdate=!1}}},r(ik,"_invertForward",new MA().setFromAxisAngle(new w(0,1,0),Math.PI)),ik);let mr=xP;A0([D(uA)],mr.prototype,"target",2);A0([D()],mr.prototype,"followFactor",2);A0([D()],mr.prototype,"rotateFactor",2);A0([D()],mr.prototype,"positionAxes",2);class OaA extends lA{constructor(A){const e=new PaA(A),t=new Xi(e.image.width*.001,e.image.height*.001),i=new rt({map:e,toneMapped:!1,transparent:!0});super(t,i);function I(o){i.map.dispatchDOMEvent(o)}this.addEventListener("mousedown",I),this.addEventListener("mousemove",I),this.addEventListener("mouseup",I),this.addEventListener("click",I),this.dispose=function(){t.dispose(),i.dispose(),i.map.dispose(),BU.delete(A),this.removeEventListener("mousedown",I),this.removeEventListener("mousemove",I),this.removeEventListener("mouseup",I),this.removeEventListener("click",I)}}}class PaA extends ZU{constructor(A){super(Xx(A)),this.dom=A,this.anisotropy=16,this.colorSpace=de,this.minFilter=Ue,this.magFilter=Ue;const e=new MutationObserver(()=>{this.scheduleUpdate||(this.scheduleUpdate=setTimeout(()=>this.update(),16))}),t={attributes:!0,childList:!0,subtree:!0,characterData:!0};e.observe(A,t),this.observer=e}dispatchDOMEvent(A){A.data&&WaA(this.dom,A.type,A.data.x,A.data.y)}update(){this.image=Xx(this.dom),this.needsUpdate=!0,this.scheduleUpdate=null}dispose(){this.observer&&this.observer.disconnect(),this.scheduleUpdate=clearTimeout(this.scheduleUpdate),super.dispose()}}const BU=new WeakMap;function Xx(g){const A=document.createRange(),e=new mA;function t(Q){const E=[];let c=!1;function d(){if(c&&(c=!1,Q.restore()),E.length===0)return;let l=-1/0,h=-1/0,p=1/0,u=1/0;for(let f=0;f<E.length;f++){const k=E[f];l=Math.max(l,k.x),h=Math.max(h,k.y),p=Math.min(p,k.x+k.width),u=Math.min(u,k.y+k.height)}Q.save(),Q.beginPath(),Q.rect(l,h,p-l,u-h),Q.clip(),c=!0}return{add:function(l){E.push(l),d()},remove:function(){E.pop(),d()}}}function i(Q,E,c,d){d!==""&&(Q.textTransform==="uppercase"&&(d=d.toUpperCase()),a.font=Q.fontWeight+" "+Q.fontSize+" "+Q.fontFamily,a.textBaseline="top",a.fillStyle=Q.color,a.fillText(d,E,c+parseFloat(Q.fontSize)*.1))}function I(Q,E,c,d,l){c<2*l&&(l=c/2),d<2*l&&(l=d/2),a.beginPath(),a.moveTo(Q+l,E),a.arcTo(Q+c,E,Q+c,E+d,l),a.arcTo(Q+c,E+d,Q,E+d,l),a.arcTo(Q,E+d,Q,E,l),a.arcTo(Q,E,Q+c,E,l),a.closePath()}function o(Q,E,c,d,l,h){const p=Q[E+"Width"],u=Q[E+"Style"],f=Q[E+"Color"];p!=="0px"&&u!=="none"&&f!=="transparent"&&f!=="rgba(0, 0, 0, 0)"&&(a.strokeStyle=f,a.lineWidth=parseFloat(p),a.beginPath(),a.moveTo(c,d),a.lineTo(c+l,d+h),a.stroke())}function s(Q,E){let c=0,d=0,l=0,h=0;if(Q.nodeType===Node.TEXT_NODE){A.selectNode(Q);const u=A.getBoundingClientRect();c=u.left-n.left-.5,d=u.top-n.top-.5,l=u.width,h=u.height,i(E,c,d,Q.nodeValue.trim())}else{if(Q.nodeType===Node.COMMENT_NODE)return;if(Q instanceof HTMLCanvasElement){if(Q.style.display==="none")return;const u=Q.getBoundingClientRect();c=u.left-n.left-.5,d=u.top-n.top-.5,a.save();const f=window.devicePixelRatio;a.scale(1/f,1/f),a.drawImage(Q,c,d),a.restore()}else if(Q instanceof HTMLImageElement){if(Q.style.display==="none")return;const u=Q.getBoundingClientRect();c=u.left-n.left-.5,d=u.top-n.top-.5,l=u.width,h=u.height,a.drawImage(Q,c,d,l,h)}else{if(Q.style.display==="none")return;const u=Q.getBoundingClientRect();c=u.left-n.left-.5,d=u.top-n.top-.5,l=u.width,h=u.height,E=window.getComputedStyle(Q),I(c,d,l,h,parseFloat(E.borderRadius));const f=E.backgroundColor;f!=="transparent"&&f!=="rgba(0, 0, 0, 0)"&&(a.fillStyle=f,a.fill());const k=["borderTop","borderLeft","borderBottom","borderRight"];let G=!0,M=null;for(const m of k){if(M!==null&&(G=E[m+"Width"]===E[M+"Width"]&&E[m+"Color"]===E[M+"Color"]&&E[m+"Style"]===E[M+"Style"]),G===!1)break;M=m}if(G===!0){const m=parseFloat(E.borderTopWidth);E.borderTopWidth!=="0px"&&E.borderTopStyle!=="none"&&E.borderTopColor!=="transparent"&&E.borderTopColor!=="rgba(0, 0, 0, 0)"&&(a.strokeStyle=E.borderTopColor,a.lineWidth=m,a.stroke())}else o(E,"borderTop",c,d,l,0),o(E,"borderLeft",c,d,0,h),o(E,"borderBottom",c,d+h,l,0),o(E,"borderRight",c+l,d,0,h);if(Q instanceof HTMLInputElement){let m=E.accentColor;(m===void 0||m==="auto")&&(m=E.color),e.set(m);const y=Math.sqrt(.299*e.r**2+.587*e.g**2+.114*e.b**2)<.5?"white":"#111111";if(Q.type==="radio"&&(I(c,d,l,h,h),a.fillStyle="white",a.strokeStyle=m,a.lineWidth=1,a.fill(),a.stroke(),Q.checked&&(I(c+2,d+2,l-4,h-4,h),a.fillStyle=m,a.strokeStyle=y,a.lineWidth=2,a.fill(),a.stroke())),Q.type==="checkbox"&&(I(c,d,l,h,2),a.fillStyle=Q.checked?m:"white",a.strokeStyle=Q.checked?y:m,a.lineWidth=1,a.stroke(),a.fill(),Q.checked)){const U=a.textAlign;a.textAlign="center";const H={color:y,fontFamily:E.fontFamily,fontSize:h+"px",fontWeight:"bold"};i(H,c+l/2,d,"✔"),a.textAlign=U}if(Q.type==="range"){const[U,H,x]=["min","max","value"].map(O=>parseFloat(Q[O])),K=(x-U)/(H-U)*(l-h);I(c,d+h/4,l,h/2,h/4),a.fillStyle=y,a.strokeStyle=m,a.lineWidth=1,a.fill(),a.stroke(),I(c,d+h/4,K+h/2,h/2,h/4),a.fillStyle=m,a.fill(),I(c+K,d,h,h,h/2),a.fillStyle=m,a.fill()}(Q.type==="color"||Q.type==="text"||Q.type==="number")&&(B.add({x:c,y:d,width:l,height:h}),i(E,c+parseInt(E.paddingLeft),d+parseInt(E.paddingTop),Q.value),B.remove())}}}const p=E.overflow==="auto"||E.overflow==="hidden";p&&B.add({x:c,y:d,width:l,height:h});for(let u=0;u<Q.childNodes.length;u++)s(Q.childNodes[u],E);p&&B.remove()}const n=g.getBoundingClientRect();let C=BU.get(g);C===void 0&&(C=document.createElement("canvas"),C.width=n.width,C.height=n.height,BU.set(g,C));const a=C.getContext("2d"),B=new t(a);return a.clearRect(0,0,C.width,C.height),s(g),C}function WaA(g,A,e,t){const i={clientX:e*g.offsetWidth+g.offsetLeft,clientY:t*g.offsetHeight+g.offsetTop,view:g.ownerDocument.defaultView};window.dispatchEvent(new MouseEvent(A,i));const I=g.getBoundingClientRect();e=e*I.width+I.left,t=t*I.height+I.top;function o(s){if(s.nodeType!==Node.TEXT_NODE&&s.nodeType!==Node.COMMENT_NODE){const n=s.getBoundingClientRect();if(e>n.left&&e<n.right&&t>n.top&&t<n.bottom&&(s.dispatchEvent(new MouseEvent(A,i)),s instanceof HTMLInputElement&&s.type==="range"&&(A==="mousedown"||A==="click"))){const[C,a]=["min","max"].map(c=>parseFloat(s[c])),B=n.width,E=(e-n.x)/B;s.value=C+(a-C)*E,s.dispatchEvent(new InputEvent("input",{bubbles:!0}))}for(let C=0;C<s.childNodes.length;C++)o(s.childNodes[C])}}o(g)}const HD=new iA,sE={type:"",data:HD},$x=new XB;class ZaA extends bI{listenToPointerEvents(A,e){const t=this,i=new XB,I=A.domElement;function o(s){s.stopPropagation();const n=A.domElement.getBoundingClientRect();HD.x=(s.clientX-n.left)/n.width*2-1,HD.y=-(s.clientY-n.top)/n.height*2+1,i.setFromCamera(HD,e);const C=i.intersectObjects(t.children,!1);if(C.length>0){const a=C[0],B=a.object,Q=a.uv;sE.type=s.type,sE.data.set(Q.x,1-Q.y),B.dispatchEvent(sE)}}I.addEventListener("pointerdown",o),I.addEventListener("pointerup",o),I.addEventListener("pointermove",o),I.addEventListener("mousedown",o),I.addEventListener("mouseup",o),I.addEventListener("mousemove",o),I.addEventListener("click",o)}listenToXRControllerEvents(A){const e=this,t={move:"mousemove",select:"click",selectstart:"mousedown",selectend:"mouseup"};function i(I){const o=I.target;$x.setFromXRController(o);const s=$x.intersectObjects(e.children,!1);if(s.length>0){const n=s[0],C=n.object,a=n.uv;sE.type=t[I.type],sE.data.set(a.x,1-a.y),C.dispatchEvent(sE)}}A.addEventListener("move",i),A.addEventListener("select",i),A.addEventListener("selectstart",i),A.addEventListener("selectend",i)}}var jaA=Object.defineProperty,VaA=Object.getOwnPropertyDescriptor,LP=(g,A,e,t)=>{for(var i=t>1?void 0:t?VaA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&jaA(A,e,i),i};class ap extends RA{constructor(){super(...arguments);r(this,"id",null);r(this,"keepAspect",!1);r(this,"_object",null)}onEnable(){if(this._object){this.gameObject.add(this._object);return}if(!this.id||!this.context.mainCamera)return;const e=document.getElementById(this.id);if(!e){console.warn('Could not find element with id "'+this.id+'"');return}e.style.display="block",e.style.visibility="hidden";const t=new ZaA;t.listenToPointerEvents(this.context.renderer,this.context.mainCamera),this.gameObject.add(t);const i=new OaA(e);t.add(i),i.visible=!1;const I=i.material;I.transparent=!0,setTimeout(()=>{i.visible=!0;const o=Eu(this.gameObject).clone();cu(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();const s=new wt;s.setFromObject(t),this.setWorldRotation(o.x,o.y,o.z);const n=s.max.x-s.min.x,C=s.max.y-s.min.y;if(this.keepAspect){const B=n/C;n>C?i.scale.set(1/n,1/C/B,1):i.scale.set(1/n*B,1/C,1)}else i.scale.set(1/n,1/C,1);const a=this.gameObject.scale;i.scale.multiply(a)},1)}onDisable(){var e;(e=this._object)==null||e.removeFromParent()}}LP([D()],ap.prototype,"id",2);LP([D()],ap.prototype,"keepAspect",2);var zaA=Object.defineProperty,XaA=Object.getOwnPropertyDescriptor,rp=(g,A,e,t)=>{for(var i=t>1?void 0:t?XaA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&zaA(A,e,i),i};const Ph=IA("debugspatialtrigger"),AL=new QI,eL=new QI;function $aA(g,A){return AL.mask=g,eL.mask=A,AL.test(eL)}class Fn extends RA{constructor(){super(...arguments);r(this,"triggerMask",0);r(this,"onEnter");r(this,"onStay");r(this,"onExit");r(this,"currentIntersected",[]);r(this,"lastIntersected",[])}start(){Ph&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(const e of Bp.triggers)$aA(e.triggerMask,this.triggerMask)&&e.test(this.gameObject)&&this.currentIntersected.push(e);for(let e=this.lastIntersected.length-1;e>=0;e--){const t=this.lastIntersected[e];this.currentIntersected.indexOf(t)<0&&(this.onExitTrigger(t),this.lastIntersected.splice(e,1))}for(const e of this.currentIntersected)this.lastIntersected.indexOf(e)<0&&this.onEnterTrigger(e),this.onStayTrigger(e);this.lastIntersected.length=0,this.lastIntersected.push(...this.currentIntersected)}onEnterTrigger(e){var t;Ph&&console.log("ENTER TRIGGER",this.name,e.name,this,e),e.raiseOnEnterEvent(this),(t=this.onEnter)==null||t.invoke(this,e)}onExitTrigger(e){var t;Ph&&console.log("EXIT TRIGGER",this.name,e.name,this,e),e.raiseOnExitEvent(this),(t=this.onExit)==null||t.invoke(this,e)}onStayTrigger(e){var t;e.raiseOnStayEvent(this),(t=this.onStay)==null||t.invoke(this,e)}}rp([D()],Fn.prototype,"triggerMask",2);rp([D(rg)],Fn.prototype,"onEnter",2);rp([D(rg)],Fn.prototype,"onStay",2);rp([D(rg)],Fn.prototype,"onExit",2);var gk;const YD=(gk=class extends RA{constructor(){super(...arguments);r(this,"triggerMask");r(this,"boxHelper")}start(){Ph&&console.log(this.name,this.triggerMask,this)}onEnable(){var A;YD.triggers.push(this),this.boxHelper||(this.boxHelper=aA.addNewComponent(this.gameObject,gs),(A=this.boxHelper)==null||A.showHelper(null,Ph))}onDisable(){YD.triggers.splice(YD.triggers.indexOf(this),1)}test(A){return this.boxHelper?this.boxHelper.isInBox(A)??!1:!1}raiseOnEnterEvent(A){aA.foreachComponent(this.gameObject,e=>{e!==A&&e instanceof Fn&&e.onEnterTrigger(this)},!1)}raiseOnStayEvent(A){aA.foreachComponent(this.gameObject,e=>{e!==A&&e instanceof Fn&&e.onStayTrigger(this)},!1)}raiseOnExitEvent(A){aA.foreachComponent(this.gameObject,e=>{e!==A&&e instanceof Fn&&e.onExitTrigger(this)},!1)}},r(gk,"triggers",[]),gk);let Bp=YD;rp([D()],Bp.prototype,"triggerMask",2);var ArA=Object.defineProperty,erA=Object.getOwnPropertyDescriptor,trA=(g,A,e,t)=>{for(var i=t>1?void 0:t?erA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&ArA(A,e,i),i};const yo=IA("debugspectator");class e0 extends RA{constructor(){super(...arguments);r(this,"cam",null);r(this,"useKeys",!0);r(this,"_mode",0);r(this,"orbit",null);r(this,"_handler");r(this,"eventSub_WebXRRequestStartEvent",null);r(this,"eventSub_WebXRStartEvent",null);r(this,"eventSub_WebXREndEvent",null);r(this,"_debug");r(this,"_networking")}get mode(){return this._mode}set mode(e){this._mode=e}get isSpectating(){var e;return((e=this._handler)==null?void 0:e.currentTarget)!==void 0}isSpectatingUser(e){var t;return((t=this.target)==null?void 0:t.userId)===e}isFollowedBy(e){var t;return(t=this.followers)==null?void 0:t.includes(e)}get followers(){return this._networking.followers}stopSpectating(){if(this.context.isInXR){this.followSelf();return}this.target=void 0}get localId(){return this.context.connection.connectionId??"local"}set target(e){var t;if(this._handler){const i=(t=this._handler.currentTarget)==null?void 0:t.userId,I=this.context.players.getPlayerView(this.localId);e===void 0||this.context.isInXR===!1&&(I==null?void 0:I.currentObject)===e.currentObject?this._handler.currentTarget!==void 0&&(this._handler.disable(),aA.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(e,i)):this._handler.currentTarget!==e&&(this._handler.set(e),aA.setActive(this.gameObject,!0),this.orbit&&(this.orbit.enabled=!1),this._networking.onSpectatedObjectChanged(e,i))}}get target(){var e;return(e=this._handler)==null?void 0:e.currentTarget}requestAllFollowMe(){this._networking.onRequestFollowMe()}get isSpectatingSelf(){var e,t;return this.isSpectating&&((e=this.target)==null?void 0:e.currentObject)===((t=this.context.players.getPlayerView(this.localId))==null?void 0:t.currentObject)}awake(){if(this._debug=new IrA(this.context,this),this._networking=new nrA(this.context,this),this._networking.awake(),aA.setActive(this.gameObject,!1),this.cam=aA.getComponent(this.gameObject,Wt),!this.cam){console.warn("SpectatorCamera: Spectator camera needs camera component on the same object.",this);return}!this._handler&&this.cam&&(this._handler=new irA(this.context,this.cam,this)),this.orbit=aA.getComponent(this.context.mainCamera,Rt)}onDestroy(){var e,t;this.stopSpectating(),(e=this._handler)==null||e.destroy(),(t=this._networking)==null||t.destroy()}isSupportedPlatform(){const e=window.navigator.userAgent,t=/Windows|MacOS/.test(e),i=/Windows NT/.test(e)&&/Edg/.test(e)&&!/Win64/.test(e);return t&&!i}onBeforeXR(e){this.isSupportedPlatform()&&aA.setActive(this.gameObject,!0)}onEnterXR(e){this.isSupportedPlatform()&&(yo&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onLeaveXR(e){var t,i;this.context.removeCamera(this.cam),aA.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),(t=this._handler)==null||t.set(void 0),(i=this._handler)==null||i.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,ja.Headset),this.target=this.context.players.getPlayerView(this.localId)),yo&&console.log("Follow self",this.target)}onAfterRender(){var a,B,Q;if(!this.cam)return;const e=this.context.renderer,t=e.xr.enabled;if(!e.xr.isPresenting&&!((a=this._handler)!=null&&a.currentTarget))return;(B=this._handler)==null||B.update(this._mode);const i=e.getRenderTarget();let I=null;const o=e.state;if(!i){if(!e.state.bindFramebuffer||!o.bindXRFramebuffer)return;I=e._framebuffer,o.bindXRFramebuffer(null)}this.setAvatarFlagsBeforeRender();const s=this.context.mainCameraComponent;if(s){const E=s.backgroundColor;E&&e.setClearColor(E,E.alpha),this.cam.backgroundColor=E,this.cam.clearFlags=s.clearFlags,this.cam.nearClipPlane=s.nearClipPlane,this.cam.farClipPlane=s.farClipPlane}else e.setClearColor(new mA(1,1,1));e.setRenderTarget(null),e.xr.enabled=!1;const n=(Q=this.cam)==null?void 0:Q.cam;this.context.updateAspect(n);const C=e.xr.isPresenting;e.xr.isPresenting=!1,e.setSize(this.context.domWidth,this.context.domHeight),e.render(this.context.scene,n),e.xr.isPresenting=C,e.xr.enabled=t,i?e.setRenderTarget(i):o.bindXRFramebuffer&&o.bindXRFramebuffer(I),this.resetAvatarFlags()}setAvatarFlagsBeforeRender(){const e=this._mode===0;for(const t of sg.instances)if(t.avatar&&"isLocalAvatar"in t.avatar&&"flags"in t.avatar){let i=dn.All;this.isSpectatingSelf&&(i=e&&t.avatar.isLocalAvatar?dn.FirstPerson:dn.ThirdPerson);const I=t.avatar.flags;if(!I)continue;for(const o of I)o.UpdateVisible(i)}}resetAvatarFlags(){var e;for(const t of sg.instances)if(t.avatar&&"flags"in t.avatar){const i=t.avatar.flags;if(!i)continue;for(const I of i)"isLocalAvatar"in t.avatar&&((e=t.avatar)!=null&&e.isLocalAvatar)?I.UpdateVisible(dn.FirstPerson):I.UpdateVisible(dn.ThirdPerson)}}}trA([D()],e0.prototype,"useKeys",2);class irA{constructor(A,e,t){r(this,"context");r(this,"cam");r(this,"spectator");r(this,"follow");r(this,"target");r(this,"view");r(this,"currentObject");this.context=A,this.cam=e,this.spectator=t}get currentTarget(){return this.view}set(A){const e=A==null?void 0:A.currentObject;if(!e){this.spectator.stopSpectating();return}e!==this.currentObject&&(this.currentObject=e,this.view=A,this.follow||(this.follow=aA.addNewComponent(this.cam.gameObject,mr)),this.target||(this.target=new uA),e.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,yo&&console.log("FOLLOW",e),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){yo&&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 A;(A=this.target)==null||A.removeFromParent(),this.follow&&aA.destroy(this.follow)}update(A){var i,I,o,s,n,C;if(((i=this.currentTarget)==null?void 0:i.isConnected)===!1||((I=this.currentTarget)==null?void 0:I.removed)===!0){yo&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&((o=this.currentTarget)==null?void 0:o.currentObject)!==this.currentObject&&(yo&&console.log("Target changed",this.currentObject,"to",this.currentTarget.currentObject),this.set(this.currentTarget));const e=this.context.mainCamera;e&&(this.cam.cam.near!==e.near||this.cam.cam.far!==e.far)&&(this.cam.cam.near=e.near,this.cam.cam.far=e.far,this.cam.cam.updateProjectionMatrix());const t=(s=this.follow)==null?void 0:s.target;if(!(!t||!this.follow)){switch(A){case 0:((n=this.view)==null?void 0:n.viewDevice)!==ja.Browser?(this.follow.followFactor=5,this.follow.rotateFactor=5):(this.follow.followFactor=50,this.follow.rotateFactor=50),t.position.set(0,0,0);break;case 1:this.follow.followFactor=3,this.follow.rotateFactor=2,t.position.set(0,.5,1.5);break}this.follow.flipForward=!1,((C=this.view)==null?void 0:C.viewDevice)!==ja.Browser?t.quaternion.copy(grA):t.quaternion.identity()}}}const grA=new MA().setFromAxisAngle(new w(0,1,0),Math.PI);class IrA{constructor(A,e){r(this,"context");r(this,"spectator");this.context=A,this.spectator=e,console.log("Click other avatars or cameras to follow them. Press ESC to exit spectator mode."),this.context.domElement.addEventListener("keydown",i=>{if(!this.spectator.useKeys)return;i.key==="Escape"&&this.spectator.stopSpectating()});let t=0;this.context.input.addEventListener(ni.PointerDown,i=>{t=this.context.time.time}),this.context.input.addEventListener(ni.PointerUp,i=>{const I=this.context.time.time-t;I>1?this.spectator.stopSpectating():this.context.input.getPointerClicked(0)&&I<.3&&this.trySelectObject()})}trySelectObject(){const A=new Bs;A.setMask(16777215);const e=this.context.physics.raycast(A);if(yo&&console.log(...e),e!=null&&e.length)for(const t of e){if(t.distance<.2)continue;const i=t.object,I=aA.getComponentInParent(i,sg),o=I==null?void 0:I.connectionId;if(o){const s=this.context.players.getPlayerView(o);this.spectator.target=s,yo&&console.log("spectate",o,I);break}}}}class orA{constructor(A,e,t){r(this,"guid");r(this,"dontSave",!0);r(this,"targetUserId");r(this,"stoppedFollowing");this.guid=A,this.targetUserId=e,this.stoppedFollowing=t}}class srA{constructor(A,e){r(this,"guid");r(this,"userId");this.guid=A.guid,this.userId=e}}class nrA{constructor(A,e){r(this,"followers",[]);r(this,"context");r(this,"spectator");r(this,"_followerEventMethod");r(this,"_requestFollowMethod");r(this,"_joinedRoomMethod");r(this,"_lastRequestFollowUser");r(this,"_enforceFollowInterval");this.context=A,this.spectator=e,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(It.JoinedRoom,this._joinedRoomMethod),this.context.domElement.addEventListener("keydown",A=>{this.spectator.useKeys&&(A.key==="f"?this.onRequestFollowMe():A.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(It.JoinedRoom,this._joinedRoomMethod)}onSpectatedObjectChanged(A,e){if(yo&&console.log(this.context.connection.connectionId,"onSpectatedObjectChanged",A,e),this.context.connection.connectionId){const t=(A==null?void 0:A.userId)===void 0,i=t?e:A==null?void 0:A.userId,I=new orA(this.context.connection.connectionId,i,t);this.context.connection.send("spectator-follower-changed",I)}}onRequestFollowMe(A=!1){if(yo&&console.log("Request follow",this.context.connection.connectionId),this.context.connection.connectionId){this.spectator.stopSpectating();const e=A?void 0:this.context.connection.connectionId,t=new srA(this.spectator,e);this.context.connection.send("spectator-request-follow",t)}}onUserJoinedRoom(){IA("followme")&&this.onRequestFollowMe()}onFollowerEvent(A){const e=A.targetUserId,t=A.guid;if(yo&&console.log(A),e===this.context.connection.connectionId)if(A.stoppedFollowing){const i=this.followers.indexOf(t);i!==-1&&(this.followers.splice(i,1),this.removeDisconnectedFollowers(),console.log(t,"unfollows you",this.followers.length))}else this.followers.includes(t)||(this.followers.push(t),this.removeDisconnectedFollowers(),console.log(t,"follows you",this.followers.length))}removeDisconnectedFollowers(){for(let A=this.followers.length-1;A>=0;A--){const e=this.followers[A];this.context.connection.userIsInRoom(e)===!1&&this.followers.splice(A,1)}}onRequestFollowEvent(A){if(this._lastRequestFollowUser=A,A.userId===this.context.connection.connectionId)this.spectator.stopSpectating();else if(A.userId===void 0)this.spectator.stopSpectating();else{const e=this.context.players.getPlayerView(A.userId);if(e)this.spectator.target=e;else return yo&&console.warn("Could not find view",A.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):(yo&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}}var CrA=Object.defineProperty,arA=Object.getOwnPropertyDescriptor,PI=(g,A,e,t)=>{for(var i=t>1?void 0:t?arA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&CrA(A,e,i),i};const Tw=IA("debugspriterenderer"),rrA=IA("wireframe"),Iy=class{static getOrCreateGeometry(A){if(A.__cached_geometry)return A.__cached_geometry;if(A.guid&&Iy.cache[A.guid])return Tw&&console.log("Take cached geometry for sprite",A.guid),Iy.cache[A.guid];const e=new ue;A.__cached_geometry=e;const t=new Float32Array(A.triangles.length*3),i=new Float32Array(A.triangles.length*2);for(let I=0;I<A.triangles.length;I+=1){const o=A.triangles[I];t[I*3]=-A.vertices[o].x,t[I*3+1]=A.vertices[o].y,t[I*3+2]=0;const s=A.uv[o];i[I*2]=s.x,i[I*2+1]=1-s.y}return e.setAttribute("position",new ie(t,3)),e.setAttribute("uv",new ie(i,2)),A.guid&&(this.cache[A.guid]=e),Tw&&console.log("Built sprite geometry",A,e),e}};let MB=Iy;r(MB,"cache",{});class Aa{constructor(){r(this,"guid");r(this,"texture");r(this,"triangles");r(this,"uv");r(this,"vertices");r(this,"__cached_geometry");r(this,"_mesh");r(this,"_material")}get mesh(){return this._mesh||(this._mesh=new lA(MB.getOrCreateGeometry(this),this.material)),this._mesh}get material(){return this._material||(this.texture&&(this.texture.colorSpace=de,this.texture.minFilter==Te&&this.texture.magFilter==Te&&(this.texture.anisotropy=1),this.texture.needsUpdate=!0),this._material=new rt({map:this.texture,color:16777215,side:ht,transparent:!0})),this._material}getGeometry(){return MB.getOrCreateGeometry(this)}}PI([D()],Aa.prototype,"guid",2);PI([D(fe)],Aa.prototype,"texture",2);PI([Uc()],Aa.prototype,"triangles",2);PI([Uc()],Aa.prototype,"uv",2);PI([Uc()],Aa.prototype,"vertices",2);const vG=Symbol("spriteOwner");class Qp{constructor(){r(this,"sprites")}}PI([D(Aa)],Qp.prototype,"sprites",2);class il{constructor(){r(this,"spriteSheet");r(this,"index",0)}update(A,e,t){if(!this.spriteSheet)return;const i=this.index;if(i<0||i>=this.spriteSheet.sprites.length)return;const I=this.spriteSheet.sprites[i],o=I==null?void 0:I.texture;if(o&&(o.colorSpace=de,o.minFilter==Te&&o.magFilter==Te&&(o.anisotropy=1),o.needsUpdate=!0,!I.__hasLoadedProgressive)){I.__hasLoadedProgressive=!0;const s=o;Kt.assignTextureLOD(A,e,o,0).then(n=>{n instanceof fe&&(I.texture=n,(t==null?void 0:t.map)===s&&(t.map=n,t.needsUpdate=!0))})}}}PI([D(Qp)],il.prototype,"spriteSheet",2);PI([D()],il.prototype,"index",2);class Yn extends RA{constructor(){super(...arguments);r(this,"drawMode",0);r(this,"size",{x:1,y:1});r(this,"color");r(this,"sharedMaterial");r(this,"transparent",!0);r(this,"cutoutThreshold",0);r(this,"castShadows",!1);r(this,"_spriteSheet");r(this,"_currentSprite")}get sprite(){return this._spriteSheet}set sprite(e){if(e!==this._spriteSheet)if(typeof e=="number"){const t=Math.floor(e);this.spriteIndex=t;return}else this._spriteSheet=e,this.updateSprite()}set spriteIndex(e){this._spriteSheet&&(this._spriteSheet.index=e,this.updateSprite())}get spriteIndex(){var e;return((e=this._spriteSheet)==null?void 0:e.index)??0}get spriteFrames(){var e,t;return((t=(e=this._spriteSheet)==null?void 0:e.spriteSheet)==null?void 0:t.sprites.length)??0}awake(){this._currentSprite=void 0,Tw&&console.log("Awake",this.name,this,this.sprite)}start(){this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(){var t,i,I;if(!this.__didAwake||!((i=(t=this.sprite)==null?void 0:t.spriteSheet)!=null&&i.sprites))return;const e=this.sprite.spriteSheet.sprites[this.spriteIndex];if(!e){Tw&&console.warn("Sprite not found",this.spriteIndex,this.sprite.spriteSheet.sprites);return}if(this._currentSprite)this._currentSprite.geometry=MB.getOrCreateGeometry(e),this._currentSprite.material.map=e.texture;else{const o=new rt({color:16777215,side:ht});if(!o)return;if(rrA&&(o.wireframe=!0),this.color&&(o.color||(o.color=new mA),o.color.copy(this.color),o.opacity=this.color.alpha),o.transparent=!0,e.texture&&!o.wireframe){let s=e.texture;s[vG]!==void 0&&s[vG]!==this&&this.spriteFrames>1&&(s=e.texture=s.clone()),s[vG]=this,o.map=s}this.sharedMaterial=o,this._currentSprite=new lA(MB.getOrCreateGeometry(e),o),Kt.assignTextureLOD(this.context,this.sourceId,o,0)}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,(I=this._spriteSheet)==null||I.update(this.context,this.sourceId,this.sharedMaterial)}}PI([D()],Yn.prototype,"drawMode",2);PI([D(Mt)],Yn.prototype,"color",2);PI([D(be)],Yn.prototype,"sharedMaterial",2);PI([D()],Yn.prototype,"transparent",2);PI([D()],Yn.prototype,"cutoutThreshold",2);PI([D()],Yn.prototype,"castShadows",2);PI([D(il)],Yn.prototype,"sprite",1);class cn{constructor(){r(this,"bb",null);r(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}static getRootAsSyncedCameraModel(A,e){return(e||new cn).__init(A.readInt32(A.position())+A.position(),A)}static getSizePrefixedRootAsSyncedCameraModel(A,e){return A.setPosition(A.position()+SN),(e||new cn).__init(A.readInt32(A.position())+A.position(),A)}userId(A){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,A):null}guid(A){const e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,A):null}dontSave(){const A=this.bb.__offset(this.bb_pos,8);return A?!!this.bb.readInt8(this.bb_pos+A):!1}pos(A){const e=this.bb.__offset(this.bb_pos,10);return e?(A||new SB).__init(this.bb_pos+e,this.bb):null}rot(A){const e=this.bb.__offset(this.bb_pos,12);return e?(A||new SB).__init(this.bb_pos+e,this.bb):null}static startSyncedCameraModel(A){A.startObject(5)}static addUserId(A,e){A.addFieldOffset(0,e,0)}static addGuid(A,e){A.addFieldOffset(1,e,0)}static addDontSave(A,e){A.addFieldInt8(2,+e,0)}static addPos(A,e){A.addFieldStruct(3,e,0)}static addRot(A,e){A.addFieldStruct(4,e,0)}static endSyncedCameraModel(A){return A.endObject()}static finishSyncedCameraModelBuffer(A,e){A.finish(e)}static finishSizePrefixedSyncedCameraModelBuffer(A,e){A.finish(e,void 0,!0)}}var BrA=Object.defineProperty,QrA=Object.getOwnPropertyDescriptor,ErA=(g,A,e,t)=>{for(var i=t>1?void 0:t?QrA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&BrA(A,e,i),i};const Hw="SCAM";GN(Hw,cn.getRootAsSyncedCameraModel);const Qo=new pu;class crA{constructor(A,e){r(this,"userId");r(this,"guid");this.guid=e,this.userId=A}send(A,e){if(A){Qo.clear();const t=Qo.createString(this.guid),i=Qo.createString(this.userId);cn.startSyncedCameraModel(Qo),cn.addGuid(Qo,t),cn.addUserId(Qo,i);const I=_e(A),o=Eu(A);cn.addPos(Qo,SB.createVec3(Qo,I.x,I.y,I.z)),cn.addRot(Qo,SB.createVec3(Qo,o.x,o.y,o.z));const s=cn.endSyncedCameraModel(Qo);Qo.finish(s,Hw),e.sendBinary(Qo.asUint8Array())}}}var Ik;const QU=(Ik=class extends RA{constructor(){super(...arguments);r(this,"cameraPrefab",null);r(this,"_lastWorldPosition");r(this,"_lastWorldQuaternion");r(this,"_model",null);r(this,"_needsUpdate",!0);r(this,"_lastUpdateTime",0);r(this,"remoteCams",{});r(this,"userToCamMap",{});r(this,"_camTimeoutInSeconds",10);r(this,"_receiveCallback",null)}getCameraObject(A){const e=this.userToCamMap[A];return e?this.remoteCams[e].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(Hw,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(Hw,this._receiveCallback)}update(){for(const i in this.remoteCams){const I=this.remoteCams[i],o=this.context.time.realtimeSinceStartup-I.lastUpdate;if(!I||o>this._camTimeoutInSeconds){he()&&console.log("Remote cam timeout",i),I!=null&&I.obj&&aA.destroy(I.obj),delete this.remoteCams[i],I&&delete this.userToCamMap[I.userId],QU.instances.push(I),this.context.players.removePlayerView(I.userId,ja.Browser);continue}}if(this.context.isInXR)return;const A=this.context.mainCamera;if(A===null){this.enabled=!1;return}if(!this.context.connection.isConnected||this.context.connection.connectionId===null)return;this._model===null&&(this._model=new crA(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));const e=_e(A),t=Jt(A);(e.distanceTo(this._lastWorldPosition)>.001||t.angleTo(this._lastWorldQuaternion)>.01)&&(this._needsUpdate=!0),this._lastWorldPosition.copy(e),this._lastWorldQuaternion.copy(t),!((!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(A,this.context.connection),this.context.isInXR||this.context.players.setPlayerView(this.context.connection.connectionId,A,ja.Browser))}onReceivedRemoteCameraInfoBin(A){const e=A.guid();if(!e)return;const t=A.userId();if(!t||!this.context.connection.userIsInRoom(t)||!this.cameraPrefab)return;let i=this.remoteCams[e];if(!i)if("isObject3D"in this.cameraPrefab){const n=new zs;n.context=this.context;const C=aA.instantiate(this.cameraPrefab,n);i=this.remoteCams[e]={obj:C,lastUpdate:this.context.time.realtimeSinceStartup,userId:t},i.obj.visible=!0,this.gameObject.add(C),this.userToCamMap[t]=e,QU.instances.push(i);const a=aA.getOrAddComponent(C,sg);a.connectionId=t,a.avatar=C}else return;const I=i.obj;this.context.players.setPlayerView(t,I,ja.Browser),i.lastUpdate=this.context.time.realtimeSinceStartup,ss.markDirty(I);const o=A.pos();o&&LB(I,o.x(),o.y(),o.z());const s=A.rot();s&&cu(I,s.x(),s.y(),s.z())}},r(Ik,"instances",[]),Ik);let t0=QU;ErA([D([uA,tt])],t0.prototype,"cameraPrefab",2);var lrA=Object.defineProperty,hrA=Object.getOwnPropertyDescriptor,gl=(g,A,e,t)=>{for(var i=t>1?void 0:t?hrA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&lrA(A,e,i),i};const qG="view",xG=IA("debugsyncedroom");class ea extends RA{constructor(){super(...arguments);r(this,"roomName");r(this,"urlParameterName","room");r(this,"joinRandomRoom",!0);r(this,"requireRoomParameter",!1);r(this,"autoRejoin",!0);r(this,"createJoinButton",!0);r(this,"_roomPrefix");r(this,"_lastJoinedRoom","");r(this,"_lastPingTime",0);r(this,"_lastRoomTime",-1);r(this,"_userWantsToBeInARoom",!1);r(this,"_roomButton");r(this,"_roomButtonIconJoin");r(this,"_roomButtonIconLeave");r(this,"updateRoomButtonState",()=>{var e,t;this._roomButton&&(this.context.connection.isInRoom?(this._roomButton.title="Leave the networked room",this._roomButton.textContent="Leave Room",(e=this._roomButtonIconJoin)==null||e.remove(),this._roomButton.prepend(this._roomButtonIconLeave)):(this._roomButton.title="Create or join a networked room",this._roomButton.textContent="Join Room",(t=this._roomButtonIconLeave)==null||t.remove(),this._roomButton.prepend(this._roomButtonIconJoin)))})}get roomPrefix(){return this._roomPrefix}get RoomPrefix(){return this._roomPrefix}awake(){xG&&console.log("Room",this.roomName,this.urlParameterName,this.joinRandomRoom,this.requireRoomParameter,this.autoRejoin),this._roomPrefix===void 0&&(this._roomPrefix=this.roomName,this.roomName="")}onEnable(){const e=IA(qG);if(e&&typeof e=="string"&&e.length>0){console.log("Join as viewer"),this.context.connection.joinRoom(e,!0);return}if((this.joinRandomRoom||IA(this.urlParameterName))&&this.tryJoinRoom(),this.createJoinButton){const t=this.createRoomButton();this.context.menu.appendChild(t)}}onDisable(){var e;(e=this._roomButton)==null||e.remove(),this.roomName&&this.roomName.length>0&&this.context.connection.leaveRoom(this.roomName)}onDestroy(){this.destroyRoomButton()}tryJoinRandomRoom(){this.setRandomRoomUrlParameter(),this.tryJoinRoom()}tryJoinRoom(e=0){e===void 0&&(e=0);let t=!1;if(this.urlParameterName){const i=IA(this.urlParameterName);if(i&&typeof i=="string"||i==="number"){t=!0;const I=hT(i);this.roomName=I}else if(this.joinRandomRoom&&(console.log("No room name found in url, generating random one"),this.setRandomRoomUrlParameter(),e<1))return this.tryJoinRoom(e+1)}else this.joinRandomRoom&&(this.roomName===null||this.roomName===void 0||this.roomName.length<=0)&&(console.log("generate room name"),this.roomName=this.generateRoomName());return this.requireRoomParameter&&!t?(xG&&console.log('No required room parameter "'+this.urlParameterName+'" in url - will not connect to networking backend.'),!1):(this.context.connection.isConnected||this.context.connection.connect(),xG&&console.log("Join "+this.roomName),this._lastJoinedRoom=this.roomName,this._roomPrefix&&(this.roomName=this._roomPrefix+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()):he()&&console.warn("You are not connected to a room anymore (possibly because the tab was inactive for too long and the server kicked you?)"))}get currentRoomName(){const e=IA(qG);return e||IA(this.urlParameterName)}setRandomRoomUrlParameter(){const e=nu(),t=this.generateRoomName();IA(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),lR(t,e)}generateRoomName(){return hR()+"_"+Math.floor(te.random(100,999))}getViewOnlyUrl(){if(this.context.connection.isConnected&&this.context.connection.currentRoomViewId){const e=window.location.search,t=new URLSearchParams(e);return t.has(this.urlParameterName)&&t.delete(this.urlParameterName),t.set(qG,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}createRoomButton(){if(this._roomButton)return this._roomButton;const e=document.createElement("button");return this._roomButton=e,e.classList.add("create-room-button"),e.setAttribute("priority","90"),e.onclick=()=>{this.context.connection.isInRoom?(this.urlParameterName&&aw(this.urlParameterName,null),this.context.connection.leaveRoom(),this._userWantsToBeInARoom=!1):(this.urlParameterName&&(IA(this.urlParameterName)||(this._lastJoinedRoom?aw(this.urlParameterName,this._lastJoinedRoom):this.setRandomRoomUrlParameter())),this.tryJoinRoom())},this._roomButtonIconJoin=wo("group"),this._roomButtonIconLeave=wo("group_off"),this.updateRoomButtonState(),this.context.connection.beginListen(It.JoinedRoom,this.updateRoomButtonState),this.context.connection.beginListen(It.LeftRoom,this.updateRoomButtonState),e}destroyRoomButton(){this.context.connection.stopListen(It.JoinedRoom,this.updateRoomButtonState),this.context.connection.stopListen(It.LeftRoom,this.updateRoomButtonState)}}gl([D()],ea.prototype,"roomName",2);gl([D()],ea.prototype,"urlParameterName",2);gl([D()],ea.prototype,"joinRandomRoom",2);gl([D()],ea.prototype,"requireRoomParameter",2);gl([D()],ea.prototype,"autoRejoin",2);gl([D()],ea.prototype,"createJoinButton",2);class i0 extends RA{}function drA(){const g=IA("testwindowcount")||0;g&&g>0&&urA(g)}function urA(g){if(IA("testwindow"))return null;const A=new URL(window.location.href);Yk(A.searchParams,hIA,1),Yk(A.searchParams,"testwindow",1);const e=A.toString(),t=[];window.onbeforeunload=()=>{for(const n of t)n.close()};const i=.05,I=128;let o=0,s=0;for(let n=0;n<g;n++){o*I+I*.01>=window.innerWidth&&(s+=1,o=0);const C=o*(I*(1+i))+window.screenLeft,a=s*(I*(1+i))+window.screenTop+90+60*s;o+=1;const B=window.open(e,"test window "+n,`popup=yes width=${I} height=${I} top=${a} left=${C}`);if(!B){console.warn("Failed to open window");continue}t.push(B),B.onload=()=>{B.onbeforeunload=()=>{for(let Q=0;Q<t.length;Q++){const E=t[Q];E!==B&&E.close()}t.length=0}}}return t}class JF extends RA{awake(){drA()}}class bF extends RA{constructor(){super(...arguments);r(this,"transformsPerFrame",10);r(this,"interval",0);r(this,"useFlatbuffers",!0);r(this,"builder",null);r(this,"models",null)}awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinary(Rd,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new _P(this.context.connection.connectionId+"_simulatedTransform_"+e,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 pu(1024));const e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();const i=vO(this.context.connection.connectionId,this);this.context.connection.sendBinary(i)}}else if(this.models)for(let e=0;e<this.models.length;e++){const t=this.models[e];t.dontSave=!0,t.update(this,null),this.context.connection.send("TestSimulateUserData-"+e,t)}}}}class _P{constructor(A,e){r(this,"guid");r(this,"fast",!1);r(this,"position");r(this,"rotation");r(this,"velocity");r(this,"dontSave");this.guid=A,this.position={x:0,y:0,z:0},this.rotation={x:0,y:0,z:0,w:0},this.update(e,null)}isValid(){return this.fast!==void 0||this.position!==void 0||this.rotation!==void 0||this.velocity!==void 0}update(A,e){const t=A.worldPosition;this.position.x=t.x,this.position.y=t.y,this.position.z=t.z;const i=A.worldQuaternion;if(this.rotation.x=i.x,this.rotation.y=i.y,this.rotation.z=i.z,this.rotation.w=i.w,this.fast=!1,e){const I=e.getVelocity();this.velocity===void 0&&(this.velocity={x:0,y:0,z:0}),this.velocity.x=I.x,this.velocity.y=I.y,this.velocity.z=I.z}}}r(_P,"temp",new w);var prA=Object.defineProperty,frA=Object.getOwnPropertyDescriptor,Il=(g,A,e,t)=>{for(var i=t>1?void 0:t?frA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&prA(A,e,i),i};class On extends hI{constructor(){super(...arguments);r(this,"offset");r(this,"rotation");r(this,"focusArea");r(this,"feather");r(this,"kernelSize");r(this,"resolutionScale")}get typeName(){return"TiltShiftEffect"}init(){this.offset.defaultValue=0,this.rotation.defaultValue=0,this.focusArea.defaultValue=.4,this.feather.defaultValue=.3,this.kernelSize.defaultValue=qC.MEDIUM,this.resolutionScale.defaultValue=1/window.devicePixelRatio}onCreateEffect(){console.log(this);const e=new DeA({kernelSize:qC.VERY_LARGE});return this.offset.onValueChanged=t=>e.offset=t,this.rotation.onValueChanged=t=>e.rotation=t,this.focusArea.onValueChanged=t=>e.focusArea=t,this.feather.onValueChanged=t=>e.feather=t,this.kernelSize.onValueChanged=t=>e.blurPass.kernelSize=t,this.resolutionScale.onValueChanged=t=>e.resolution.scale=t/window.devicePixelRatio,e}}Il([D(qe)],On.prototype,"offset",2);Il([D(qe)],On.prototype,"rotation",2);Il([D(qe)],On.prototype,"focusArea",2);Il([D(qe)],On.prototype,"feather",2);Il([D(qe)],On.prototype,"kernelSize",2);Il([D(qe)],On.prototype,"resolutionScale",2);ds("TiltShiftEffect",On);var DrA=Object.defineProperty,wrA=Object.getOwnPropertyDescriptor,yrA=(g,A,e,t)=>{for(var i=t>1?void 0:t?wrA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&DrA(A,e,i),i};class Ep extends hI{constructor(){super(...arguments);r(this,"mode")}get typeName(){return"ToneMapping"}get isToneMapping(){return!0}init(){this.mode||(this.mode=new qe(eo)),this.mode.defaultValue=eo}apply(){this.mode||this.init(),this.mode.onValueChanged=this._apply.bind(this),this._apply(this.mode.value)}_apply(e){this.context.renderer.toneMapping=this.getThreeToneMapping(e)}getThreeToneMapping(e){switch(e){case 0:return VE;case 1:return ay;case 2:return Cy;default:return VE}}}yrA([D(qe)],Ep.prototype,"mode",2);ds("Tonemapping",Ep);var SrA=Object.defineProperty,mrA=Object.getOwnPropertyDescriptor,g0=(g,A,e,t)=>{for(var i=t>1?void 0:t?mrA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&SrA(A,e,i),i};class kQ extends RA{constructor(){super(...arguments);r(this,"isGizmo",!1);r(this,"translationSnap",1);r(this,"rotationSnapAngle",15);r(this,"scaleSnap",.25);r(this,"control");r(this,"orbit");r(this,"onControlChangedEvent",e=>{const t=this.orbit;if(t&&(t.enabled=!e.value),e.value){const i=aA.getComponentInParent(this.gameObject,sr);i&&i.requestOwnership()}});r(this,"windowKeyDownListener",e=>{if(this.enabled&&this.control)switch(e.keyCode){case 81:this.control.setSpace(this.control.space==="local"?"world":"local");break;case 16:this.enableSnapping();break;case 87:this.control.setMode("translate");break;case 69:this.control.setMode("rotate");break;case 82:this.control.setMode("scale");break;case 187:case 107:this.control.setSize(this.control.size+.1);break;case 189:case 109:this.control.setSize(Math.max(this.control.size-.1,.1));break;case 88:this.control.showX=!this.control.showX;break;case 89:this.control.showY=!this.control.showY;break;case 90:this.control.showZ=!this.control.showZ;break;case 32:this.control.enabled=!this.control.enabled;break}});r(this,"windowKeyUpListener",e=>{if(this.enabled)switch(e.keyCode){case 16:this.disableSnapping();break}})}onEnable(){var e;this.isGizmo&&!uu||this.context.mainCamera&&(this.control||(this.control=new V7(this.context.mainCamera,this.context.renderer.domElement),this.control.visible=!0,this.control.enabled=!0,this.control.getRaycaster().layers.set(2),this.control.size=1,this.control.traverse(t=>{const i=t;if(i.layers.set(2),i){const I=i.material;I&&(I.opacity=.3)}}),this.orbit=aA.getComponentInParent(this.context.mainCamera,Rt)??void 0),this.control&&(this.context.scene.add(this.control),this.control.attach(this.gameObject),(e=this.control)==null||e.addEventListener("dragging-changed",this.onControlChangedEvent),window.addEventListener("keydown",this.windowKeyDownListener),window.addEventListener("keyup",this.windowKeyUpListener)))}onDisable(){var e,t;(e=this.control)==null||e.removeFromParent(),(t=this.control)==null||t.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(Cg.degToRad(this.rotationSnapAngle)),this.control.setScaleSnap(this.scaleSnap))}disableSnapping(){this.control&&(this.control.setTranslationSnap(null),this.control.setRotationSnap(null),this.control.setScaleSnap(null))}}g0([D()],kQ.prototype,"isGizmo",2);g0([D()],kQ.prototype,"translationSnap",2);g0([D()],kQ.prototype,"rotationSnapAngle",2);g0([D()],kQ.prototype,"scaleSnap",2);var GrA=Object.defineProperty,krA=Object.getOwnPropertyDescriptor,vF=(g,A,e,t)=>{for(var i=t>1?void 0:t?krA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&GrA(A,e,i),i};class MQ extends hI{constructor(){super(...arguments);r(this,"color");r(this,"intensity");r(this,"center")}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 e=new KY;return this.intensity.onValueChanged=t=>{e.offset=t,this.updateDarkness(e)},this.color.onValueChanged=t=>{this.updateDarkness(e)},e}updateDarkness(e){const t=this.intensity.value;e.darkness=t}}vF([D(qe)],MQ.prototype,"color",2);vF([D(qe)],MQ.prototype,"intensity",2);vF([D(qe)],MQ.prototype,"center",2);ds("Vignette",MQ);var MrA=Object.defineProperty,UrA=Object.getOwnPropertyDescriptor,RrA=(g,A,e,t)=>{for(var i=t>1?void 0:t?UrA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&MrA(A,e,i),i};const OD=IA("debugarcamera");class I0 extends RA{constructor(){super(...arguments);r(this,"backgroundTint",new Mt(1,1,1,1));r(this,"backgroundPlane");r(this,"threeTexture");r(this,"forceTextureInitialization",function(){const e=new rt,t=new Xi,i=new cI;i.add(new lA(t,e));const I=new He;return function(s,n){e.map=n,s.render(i,I),OD&&console.warn("Force texture initialization")}}());r(this,"preRender",()=>{if(!this||!this.gameObject)return;const t=this.context.renderer.xr.getFrame();t&&(!this.threeTexture&&this.context.renderer&&(this.threeTexture=new fe,this.forceTextureInitialization(this.context.renderer,this.threeTexture)),this.backgroundPlane===void 0&&(this.backgroundPlane=FrA(this.backgroundTint)),this.backgroundPlane.parent!==this.scene&&this.scene.add(this.backgroundPlane),this.updateFromFrame(t))})}onBeforeXR(e,t){t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("camera-access"),OD&&console.warn("Requesting camera-access")}onEnterXR(e){this.backgroundPlane&&(this.context.scene.add(this.backgroundPlane),this.backgroundPlane.visible=!1),this.backgroundPlane&&this.context.scene.add(this.backgroundPlane),this.context.pre_render_callbacks.push(this.preRender)}onLeaveXR(e){this.backgroundPlane&&this.backgroundPlane.removeFromParent();const t=this.context.pre_render_callbacks.indexOf(this.preRender);t>=0&&this.context.pre_render_callbacks.splice(t,1)}get background(){return this.backgroundPlane}onBeforeRender(e){this.updateFromFrame(e)}updateFromFrame(e){if(!e)return;const t=e.getViewerPose(this.context.renderer.xr.getReferenceSpace());if(t){for(const i of t.views)if("camera"in i&&i.camera){let o=this.context.renderer.xr.getBinding();if(o||(o=new XRWebGLBinding(e.session,this.context.renderer.getContext())),o){let s=null;if("getCameraImage"in o){s=o.getCameraImage(i.camera);const n=this.context.renderer.properties.get(this.threeTexture);n.__webglTexture=s,this.backgroundPlane?(this.backgroundPlane.setTexture(this.threeTexture),this.backgroundPlane.visible=!0):OD&&console.warn("No background plane to set texture on")}}}}}}RrA([D(Mt)],I0.prototype,"backgroundTint",2);const NrA=`
7018
+ `)}}applyShadowMaterial(){if(this.targetMesh)if(this.targetMesh.material.type!=="ShadowMaterial"){const e=new by;e.color=this.shadowColor,e.opacity=this.shadowColor.alpha,this.applyMaterialOptions(e),this.targetMesh.material=e}else{const e=this.targetMesh.material;e.color=this.shadowColor,e.opacity=this.shadowColor.alpha,this.applyMaterialOptions(e)}}applyOccluderMaterial(){if(this.targetMesh){let e=this.targetMesh.material;if(!e){const t=new rt;this.targetMesh.material=t,e=t}e.depthWrite=!0,e.stencilWrite=!0,e.colorWrite=!1,this.gameObject.renderOrder=-100}}applyMaterialOptions(e){e&&(e.depthWrite=!1,e.stencilWrite=!1)}}qP([D()],Cp.prototype,"mode",2);qP([D(Mt)],Cp.prototype,"shadowColor",2);var HaA=Object.defineProperty,YaA=Object.getOwnPropertyDescriptor,A0=(g,A,e,t)=>{for(var i=t>1?void 0:t?YaA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&HaA(A,e,i),i},ik;const xP=(ik=class extends RA{constructor(){super(...arguments);r(this,"target",null);r(this,"followFactor",.1);r(this,"rotateFactor",.1);r(this,"positionAxes",RE.All);r(this,"flipForward",!1);r(this,"_firstUpdate",!0)}onBeforeRender(){this.updateNow(!1)}updateNow(A){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){const e=_e(this.target),t=this._firstUpdate||A?1:te.clamp01(this.context.time.deltaTime*this.followFactor),i=this.worldPosition;this.positionAxes&RE.X&&(i.x=te.lerp(i.x,e.x,t)),this.positionAxes&RE.Y&&(i.y=te.lerp(i.y,e.y,t)),this.positionAxes&RE.Z&&(i.z=te.lerp(i.z,e.z,t)),this.worldPosition=i}if(this.rotateFactor>0){const e=Jt(this.target);this.flipForward&&e.premultiply(xP._invertForward);const t=this._firstUpdate||A?1:te.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(e,t)}this._firstUpdate=!1}}},r(ik,"_invertForward",new MA().setFromAxisAngle(new w(0,1,0),Math.PI)),ik);let mr=xP;A0([D(uA)],mr.prototype,"target",2);A0([D()],mr.prototype,"followFactor",2);A0([D()],mr.prototype,"rotateFactor",2);A0([D()],mr.prototype,"positionAxes",2);class OaA extends lA{constructor(A){const e=new PaA(A),t=new Xi(e.image.width*.001,e.image.height*.001),i=new rt({map:e,toneMapped:!1,transparent:!0});super(t,i);function I(o){i.map.dispatchDOMEvent(o)}this.addEventListener("mousedown",I),this.addEventListener("mousemove",I),this.addEventListener("mouseup",I),this.addEventListener("click",I),this.dispose=function(){t.dispose(),i.dispose(),i.map.dispose(),BU.delete(A),this.removeEventListener("mousedown",I),this.removeEventListener("mousemove",I),this.removeEventListener("mouseup",I),this.removeEventListener("click",I)}}}class PaA extends ZU{constructor(A){super(Xx(A)),this.dom=A,this.anisotropy=16,this.colorSpace=de,this.minFilter=Ue,this.magFilter=Ue;const e=new MutationObserver(()=>{this.scheduleUpdate||(this.scheduleUpdate=setTimeout(()=>this.update(),16))}),t={attributes:!0,childList:!0,subtree:!0,characterData:!0};e.observe(A,t),this.observer=e}dispatchDOMEvent(A){A.data&&WaA(this.dom,A.type,A.data.x,A.data.y)}update(){this.image=Xx(this.dom),this.needsUpdate=!0,this.scheduleUpdate=null}dispose(){this.observer&&this.observer.disconnect(),this.scheduleUpdate=clearTimeout(this.scheduleUpdate),super.dispose()}}const BU=new WeakMap;function Xx(g){const A=document.createRange(),e=new mA;function t(Q){const E=[];let c=!1;function d(){if(c&&(c=!1,Q.restore()),E.length===0)return;let l=-1/0,h=-1/0,p=1/0,u=1/0;for(let f=0;f<E.length;f++){const k=E[f];l=Math.max(l,k.x),h=Math.max(h,k.y),p=Math.min(p,k.x+k.width),u=Math.min(u,k.y+k.height)}Q.save(),Q.beginPath(),Q.rect(l,h,p-l,u-h),Q.clip(),c=!0}return{add:function(l){E.push(l),d()},remove:function(){E.pop(),d()}}}function i(Q,E,c,d){d!==""&&(Q.textTransform==="uppercase"&&(d=d.toUpperCase()),a.font=Q.fontWeight+" "+Q.fontSize+" "+Q.fontFamily,a.textBaseline="top",a.fillStyle=Q.color,a.fillText(d,E,c+parseFloat(Q.fontSize)*.1))}function I(Q,E,c,d,l){c<2*l&&(l=c/2),d<2*l&&(l=d/2),a.beginPath(),a.moveTo(Q+l,E),a.arcTo(Q+c,E,Q+c,E+d,l),a.arcTo(Q+c,E+d,Q,E+d,l),a.arcTo(Q,E+d,Q,E,l),a.arcTo(Q,E,Q+c,E,l),a.closePath()}function o(Q,E,c,d,l,h){const p=Q[E+"Width"],u=Q[E+"Style"],f=Q[E+"Color"];p!=="0px"&&u!=="none"&&f!=="transparent"&&f!=="rgba(0, 0, 0, 0)"&&(a.strokeStyle=f,a.lineWidth=parseFloat(p),a.beginPath(),a.moveTo(c,d),a.lineTo(c+l,d+h),a.stroke())}function s(Q,E){let c=0,d=0,l=0,h=0;if(Q.nodeType===Node.TEXT_NODE){A.selectNode(Q);const u=A.getBoundingClientRect();c=u.left-n.left-.5,d=u.top-n.top-.5,l=u.width,h=u.height,i(E,c,d,Q.nodeValue.trim())}else{if(Q.nodeType===Node.COMMENT_NODE)return;if(Q instanceof HTMLCanvasElement){if(Q.style.display==="none")return;const u=Q.getBoundingClientRect();c=u.left-n.left-.5,d=u.top-n.top-.5,a.save();const f=window.devicePixelRatio;a.scale(1/f,1/f),a.drawImage(Q,c,d),a.restore()}else if(Q instanceof HTMLImageElement){if(Q.style.display==="none")return;const u=Q.getBoundingClientRect();c=u.left-n.left-.5,d=u.top-n.top-.5,l=u.width,h=u.height,a.drawImage(Q,c,d,l,h)}else{if(Q.style.display==="none")return;const u=Q.getBoundingClientRect();c=u.left-n.left-.5,d=u.top-n.top-.5,l=u.width,h=u.height,E=window.getComputedStyle(Q),I(c,d,l,h,parseFloat(E.borderRadius));const f=E.backgroundColor;f!=="transparent"&&f!=="rgba(0, 0, 0, 0)"&&(a.fillStyle=f,a.fill());const k=["borderTop","borderLeft","borderBottom","borderRight"];let G=!0,M=null;for(const m of k){if(M!==null&&(G=E[m+"Width"]===E[M+"Width"]&&E[m+"Color"]===E[M+"Color"]&&E[m+"Style"]===E[M+"Style"]),G===!1)break;M=m}if(G===!0){const m=parseFloat(E.borderTopWidth);E.borderTopWidth!=="0px"&&E.borderTopStyle!=="none"&&E.borderTopColor!=="transparent"&&E.borderTopColor!=="rgba(0, 0, 0, 0)"&&(a.strokeStyle=E.borderTopColor,a.lineWidth=m,a.stroke())}else o(E,"borderTop",c,d,l,0),o(E,"borderLeft",c,d,0,h),o(E,"borderBottom",c,d+h,l,0),o(E,"borderRight",c+l,d,0,h);if(Q instanceof HTMLInputElement){let m=E.accentColor;(m===void 0||m==="auto")&&(m=E.color),e.set(m);const y=Math.sqrt(.299*e.r**2+.587*e.g**2+.114*e.b**2)<.5?"white":"#111111";if(Q.type==="radio"&&(I(c,d,l,h,h),a.fillStyle="white",a.strokeStyle=m,a.lineWidth=1,a.fill(),a.stroke(),Q.checked&&(I(c+2,d+2,l-4,h-4,h),a.fillStyle=m,a.strokeStyle=y,a.lineWidth=2,a.fill(),a.stroke())),Q.type==="checkbox"&&(I(c,d,l,h,2),a.fillStyle=Q.checked?m:"white",a.strokeStyle=Q.checked?y:m,a.lineWidth=1,a.stroke(),a.fill(),Q.checked)){const U=a.textAlign;a.textAlign="center";const H={color:y,fontFamily:E.fontFamily,fontSize:h+"px",fontWeight:"bold"};i(H,c+l/2,d,"✔"),a.textAlign=U}if(Q.type==="range"){const[U,H,x]=["min","max","value"].map(O=>parseFloat(Q[O])),K=(x-U)/(H-U)*(l-h);I(c,d+h/4,l,h/2,h/4),a.fillStyle=y,a.strokeStyle=m,a.lineWidth=1,a.fill(),a.stroke(),I(c,d+h/4,K+h/2,h/2,h/4),a.fillStyle=m,a.fill(),I(c+K,d,h,h,h/2),a.fillStyle=m,a.fill()}(Q.type==="color"||Q.type==="text"||Q.type==="number")&&(B.add({x:c,y:d,width:l,height:h}),i(E,c+parseInt(E.paddingLeft),d+parseInt(E.paddingTop),Q.value),B.remove())}}}const p=E.overflow==="auto"||E.overflow==="hidden";p&&B.add({x:c,y:d,width:l,height:h});for(let u=0;u<Q.childNodes.length;u++)s(Q.childNodes[u],E);p&&B.remove()}const n=g.getBoundingClientRect();let C=BU.get(g);C===void 0&&(C=document.createElement("canvas"),C.width=n.width,C.height=n.height,BU.set(g,C));const a=C.getContext("2d"),B=new t(a);return a.clearRect(0,0,C.width,C.height),s(g),C}function WaA(g,A,e,t){const i={clientX:e*g.offsetWidth+g.offsetLeft,clientY:t*g.offsetHeight+g.offsetTop,view:g.ownerDocument.defaultView};window.dispatchEvent(new MouseEvent(A,i));const I=g.getBoundingClientRect();e=e*I.width+I.left,t=t*I.height+I.top;function o(s){if(s.nodeType!==Node.TEXT_NODE&&s.nodeType!==Node.COMMENT_NODE){const n=s.getBoundingClientRect();if(e>n.left&&e<n.right&&t>n.top&&t<n.bottom&&(s.dispatchEvent(new MouseEvent(A,i)),s instanceof HTMLInputElement&&s.type==="range"&&(A==="mousedown"||A==="click"))){const[C,a]=["min","max"].map(c=>parseFloat(s[c])),B=n.width,E=(e-n.x)/B;s.value=C+(a-C)*E,s.dispatchEvent(new InputEvent("input",{bubbles:!0}))}for(let C=0;C<s.childNodes.length;C++)o(s.childNodes[C])}}o(g)}const HD=new iA,sE={type:"",data:HD},$x=new XB;class ZaA extends bI{listenToPointerEvents(A,e){const t=this,i=new XB,I=A.domElement;function o(s){s.stopPropagation();const n=A.domElement.getBoundingClientRect();HD.x=(s.clientX-n.left)/n.width*2-1,HD.y=-(s.clientY-n.top)/n.height*2+1,i.setFromCamera(HD,e);const C=i.intersectObjects(t.children,!1);if(C.length>0){const a=C[0],B=a.object,Q=a.uv;sE.type=s.type,sE.data.set(Q.x,1-Q.y),B.dispatchEvent(sE)}}I.addEventListener("pointerdown",o),I.addEventListener("pointerup",o),I.addEventListener("pointermove",o),I.addEventListener("mousedown",o),I.addEventListener("mouseup",o),I.addEventListener("mousemove",o),I.addEventListener("click",o)}listenToXRControllerEvents(A){const e=this,t={move:"mousemove",select:"click",selectstart:"mousedown",selectend:"mouseup"};function i(I){const o=I.target;$x.setFromXRController(o);const s=$x.intersectObjects(e.children,!1);if(s.length>0){const n=s[0],C=n.object,a=n.uv;sE.type=t[I.type],sE.data.set(a.x,1-a.y),C.dispatchEvent(sE)}}A.addEventListener("move",i),A.addEventListener("select",i),A.addEventListener("selectstart",i),A.addEventListener("selectend",i)}}var jaA=Object.defineProperty,VaA=Object.getOwnPropertyDescriptor,LP=(g,A,e,t)=>{for(var i=t>1?void 0:t?VaA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&jaA(A,e,i),i};class ap extends RA{constructor(){super(...arguments);r(this,"id",null);r(this,"keepAspect",!1);r(this,"_object",null)}onEnable(){if(this._object){this.gameObject.add(this._object);return}if(!this.id||!this.context.mainCamera)return;const e=document.getElementById(this.id);if(!e){console.warn('Could not find element with id "'+this.id+'"');return}e.style.display="block",e.style.visibility="hidden";const t=new ZaA;t.listenToPointerEvents(this.context.renderer,this.context.mainCamera),this.gameObject.add(t);const i=new OaA(e);t.add(i),i.visible=!1;const I=i.material;I.transparent=!0,setTimeout(()=>{i.visible=!0;const o=Eu(this.gameObject).clone();cu(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();const s=new wt;s.setFromObject(t),this.setWorldRotation(o.x,o.y,o.z);const n=s.max.x-s.min.x,C=s.max.y-s.min.y;if(this.keepAspect){const B=n/C;n>C?i.scale.set(1/n,1/C/B,1):i.scale.set(1/n*B,1/C,1)}else i.scale.set(1/n,1/C,1);const a=this.gameObject.scale;i.scale.multiply(a)},1)}onDisable(){var e;(e=this._object)==null||e.removeFromParent()}}LP([D()],ap.prototype,"id",2);LP([D()],ap.prototype,"keepAspect",2);var zaA=Object.defineProperty,XaA=Object.getOwnPropertyDescriptor,rp=(g,A,e,t)=>{for(var i=t>1?void 0:t?XaA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&zaA(A,e,i),i};const Ph=IA("debugspatialtrigger"),AL=new QI,eL=new QI;function $aA(g,A){return AL.mask=g,eL.mask=A,AL.test(eL)}class Fn extends RA{constructor(){super(...arguments);r(this,"triggerMask",0);r(this,"onEnter");r(this,"onStay");r(this,"onExit");r(this,"currentIntersected",[]);r(this,"lastIntersected",[])}start(){Ph&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(const e of Bp.triggers)$aA(e.triggerMask,this.triggerMask)&&e.test(this.gameObject)&&this.currentIntersected.push(e);for(let e=this.lastIntersected.length-1;e>=0;e--){const t=this.lastIntersected[e];this.currentIntersected.indexOf(t)<0&&(this.onExitTrigger(t),this.lastIntersected.splice(e,1))}for(const e of this.currentIntersected)this.lastIntersected.indexOf(e)<0&&this.onEnterTrigger(e),this.onStayTrigger(e);this.lastIntersected.length=0,this.lastIntersected.push(...this.currentIntersected)}onEnterTrigger(e){var t;Ph&&console.log("ENTER TRIGGER",this.name,e.name,this,e),e.raiseOnEnterEvent(this),(t=this.onEnter)==null||t.invoke(this,e)}onExitTrigger(e){var t;Ph&&console.log("EXIT TRIGGER",this.name,e.name,this,e),e.raiseOnExitEvent(this),(t=this.onExit)==null||t.invoke(this,e)}onStayTrigger(e){var t;e.raiseOnStayEvent(this),(t=this.onStay)==null||t.invoke(this,e)}}rp([D()],Fn.prototype,"triggerMask",2);rp([D(rg)],Fn.prototype,"onEnter",2);rp([D(rg)],Fn.prototype,"onStay",2);rp([D(rg)],Fn.prototype,"onExit",2);var gk;const YD=(gk=class extends RA{constructor(){super(...arguments);r(this,"triggerMask");r(this,"boxHelper")}start(){Ph&&console.log(this.name,this.triggerMask,this)}onEnable(){var A;YD.triggers.push(this),this.boxHelper||(this.boxHelper=aA.addNewComponent(this.gameObject,gs),(A=this.boxHelper)==null||A.showHelper(null,Ph))}onDisable(){YD.triggers.splice(YD.triggers.indexOf(this),1)}test(A){return this.boxHelper?this.boxHelper.isInBox(A)??!1:!1}raiseOnEnterEvent(A){aA.foreachComponent(this.gameObject,e=>{e!==A&&e instanceof Fn&&e.onEnterTrigger(this)},!1)}raiseOnStayEvent(A){aA.foreachComponent(this.gameObject,e=>{e!==A&&e instanceof Fn&&e.onStayTrigger(this)},!1)}raiseOnExitEvent(A){aA.foreachComponent(this.gameObject,e=>{e!==A&&e instanceof Fn&&e.onExitTrigger(this)},!1)}},r(gk,"triggers",[]),gk);let Bp=YD;rp([D()],Bp.prototype,"triggerMask",2);var ArA=Object.defineProperty,erA=Object.getOwnPropertyDescriptor,trA=(g,A,e,t)=>{for(var i=t>1?void 0:t?erA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&ArA(A,e,i),i};const yo=IA("debugspectator");class e0 extends RA{constructor(){super(...arguments);r(this,"cam",null);r(this,"useKeys",!0);r(this,"_mode",0);r(this,"orbit",null);r(this,"_handler");r(this,"eventSub_WebXRRequestStartEvent",null);r(this,"eventSub_WebXRStartEvent",null);r(this,"eventSub_WebXREndEvent",null);r(this,"_debug");r(this,"_networking")}get mode(){return this._mode}set mode(e){this._mode=e}get isSpectating(){var e;return((e=this._handler)==null?void 0:e.currentTarget)!==void 0}isSpectatingUser(e){var t;return((t=this.target)==null?void 0:t.userId)===e}isFollowedBy(e){var t;return(t=this.followers)==null?void 0:t.includes(e)}get followers(){return this._networking.followers}stopSpectating(){if(this.context.isInXR){this.followSelf();return}this.target=void 0}get localId(){return this.context.connection.connectionId??"local"}set target(e){var t;if(this._handler){const i=(t=this._handler.currentTarget)==null?void 0:t.userId,I=this.context.players.getPlayerView(this.localId);e===void 0||this.context.isInXR===!1&&(I==null?void 0:I.currentObject)===e.currentObject?this._handler.currentTarget!==void 0&&(this._handler.disable(),aA.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(e,i)):this._handler.currentTarget!==e&&(this._handler.set(e),aA.setActive(this.gameObject,!0),this.orbit&&(this.orbit.enabled=!1),this._networking.onSpectatedObjectChanged(e,i))}}get target(){var e;return(e=this._handler)==null?void 0:e.currentTarget}requestAllFollowMe(){this._networking.onRequestFollowMe()}get isSpectatingSelf(){var e,t;return this.isSpectating&&((e=this.target)==null?void 0:e.currentObject)===((t=this.context.players.getPlayerView(this.localId))==null?void 0:t.currentObject)}awake(){if(this._debug=new IrA(this.context,this),this._networking=new nrA(this.context,this),this._networking.awake(),aA.setActive(this.gameObject,!1),this.cam=aA.getComponent(this.gameObject,Wt),!this.cam){console.warn("SpectatorCamera: Spectator camera needs camera component on the same object.",this);return}!this._handler&&this.cam&&(this._handler=new irA(this.context,this.cam,this)),this.orbit=aA.getComponent(this.context.mainCamera,Rt)}onDestroy(){var e,t;this.stopSpectating(),(e=this._handler)==null||e.destroy(),(t=this._networking)==null||t.destroy()}isSupportedPlatform(){const e=window.navigator.userAgent,t=/Windows|MacOS/.test(e),i=/Windows NT/.test(e)&&/Edg/.test(e)&&!/Win64/.test(e);return t&&!i}onBeforeXR(e){this.isSupportedPlatform()&&aA.setActive(this.gameObject,!0)}onEnterXR(e){this.isSupportedPlatform()&&(yo&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onLeaveXR(e){var t,i;this.context.removeCamera(this.cam),aA.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),(t=this._handler)==null||t.set(void 0),(i=this._handler)==null||i.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,ja.Headset),this.target=this.context.players.getPlayerView(this.localId)),yo&&console.log("Follow self",this.target)}onAfterRender(){var a,B,Q;if(!this.cam)return;const e=this.context.renderer,t=e.xr.enabled;if(!e.xr.isPresenting&&!((a=this._handler)!=null&&a.currentTarget))return;(B=this._handler)==null||B.update(this._mode);const i=e.getRenderTarget();let I=null;const o=e.state;if(!i){if(!e.state.bindFramebuffer||!o.bindXRFramebuffer)return;I=e._framebuffer,o.bindXRFramebuffer(null)}this.setAvatarFlagsBeforeRender();const s=this.context.mainCameraComponent;if(s){const E=s.backgroundColor;E&&e.setClearColor(E,E.alpha),this.cam.backgroundColor=E,this.cam.clearFlags=s.clearFlags,this.cam.nearClipPlane=s.nearClipPlane,this.cam.farClipPlane=s.farClipPlane}else e.setClearColor(new mA(1,1,1));e.setRenderTarget(null),e.xr.enabled=!1;const n=(Q=this.cam)==null?void 0:Q.cam;this.context.updateAspect(n);const C=e.xr.isPresenting;e.xr.isPresenting=!1,e.setSize(this.context.domWidth,this.context.domHeight),e.render(this.context.scene,n),e.xr.isPresenting=C,e.xr.enabled=t,i?e.setRenderTarget(i):o.bindXRFramebuffer&&o.bindXRFramebuffer(I),this.resetAvatarFlags()}setAvatarFlagsBeforeRender(){const e=this._mode===0;for(const t of sg.instances)if(t.avatar&&"isLocalAvatar"in t.avatar&&"flags"in t.avatar){let i=dn.All;this.isSpectatingSelf&&(i=e&&t.avatar.isLocalAvatar?dn.FirstPerson:dn.ThirdPerson);const I=t.avatar.flags;if(!I)continue;for(const o of I)o.UpdateVisible(i)}}resetAvatarFlags(){var e;for(const t of sg.instances)if(t.avatar&&"flags"in t.avatar){const i=t.avatar.flags;if(!i)continue;for(const I of i)"isLocalAvatar"in t.avatar&&((e=t.avatar)!=null&&e.isLocalAvatar)?I.UpdateVisible(dn.FirstPerson):I.UpdateVisible(dn.ThirdPerson)}}}trA([D()],e0.prototype,"useKeys",2);class irA{constructor(A,e,t){r(this,"context");r(this,"cam");r(this,"spectator");r(this,"follow");r(this,"target");r(this,"view");r(this,"currentObject");this.context=A,this.cam=e,this.spectator=t}get currentTarget(){return this.view}set(A){const e=A==null?void 0:A.currentObject;if(!e){this.spectator.stopSpectating();return}e!==this.currentObject&&(this.currentObject=e,this.view=A,this.follow||(this.follow=aA.addNewComponent(this.cam.gameObject,mr)),this.target||(this.target=new uA),e.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,yo&&console.log("FOLLOW",e),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){yo&&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 A;(A=this.target)==null||A.removeFromParent(),this.follow&&aA.destroy(this.follow)}update(A){var i,I,o,s,n,C;if(((i=this.currentTarget)==null?void 0:i.isConnected)===!1||((I=this.currentTarget)==null?void 0:I.removed)===!0){yo&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&((o=this.currentTarget)==null?void 0:o.currentObject)!==this.currentObject&&(yo&&console.log("Target changed",this.currentObject,"to",this.currentTarget.currentObject),this.set(this.currentTarget));const e=this.context.mainCamera;e&&(this.cam.cam.near!==e.near||this.cam.cam.far!==e.far)&&(this.cam.cam.near=e.near,this.cam.cam.far=e.far,this.cam.cam.updateProjectionMatrix());const t=(s=this.follow)==null?void 0:s.target;if(!(!t||!this.follow)){switch(A){case 0:((n=this.view)==null?void 0:n.viewDevice)!==ja.Browser?(this.follow.followFactor=5,this.follow.rotateFactor=5):(this.follow.followFactor=50,this.follow.rotateFactor=50),t.position.set(0,0,0);break;case 1:this.follow.followFactor=3,this.follow.rotateFactor=2,t.position.set(0,.5,1.5);break}this.follow.flipForward=!1,((C=this.view)==null?void 0:C.viewDevice)!==ja.Browser?t.quaternion.copy(grA):t.quaternion.identity()}}}const grA=new MA().setFromAxisAngle(new w(0,1,0),Math.PI);class IrA{constructor(A,e){r(this,"context");r(this,"spectator");this.context=A,this.spectator=e,console.log("Click other avatars or cameras to follow them. Press ESC to exit spectator mode."),this.context.domElement.addEventListener("keydown",i=>{if(!this.spectator.useKeys)return;i.key==="Escape"&&this.spectator.stopSpectating()});let t=0;this.context.input.addEventListener(ni.PointerDown,i=>{t=this.context.time.time}),this.context.input.addEventListener(ni.PointerUp,i=>{const I=this.context.time.time-t;I>1?this.spectator.stopSpectating():this.context.input.getPointerClicked(0)&&I<.3&&this.trySelectObject()})}trySelectObject(){const A=new Bs;A.setMask(16777215);const e=this.context.physics.raycast(A);if(yo&&console.log(...e),e!=null&&e.length)for(const t of e){if(t.distance<.2)continue;const i=t.object,I=aA.getComponentInParent(i,sg),o=I==null?void 0:I.connectionId;if(o){const s=this.context.players.getPlayerView(o);this.spectator.target=s,yo&&console.log("spectate",o,I);break}}}}class orA{constructor(A,e,t){r(this,"guid");r(this,"dontSave",!0);r(this,"targetUserId");r(this,"stoppedFollowing");this.guid=A,this.targetUserId=e,this.stoppedFollowing=t}}class srA{constructor(A,e){r(this,"guid");r(this,"userId");this.guid=A.guid,this.userId=e}}class nrA{constructor(A,e){r(this,"followers",[]);r(this,"context");r(this,"spectator");r(this,"_followerEventMethod");r(this,"_requestFollowMethod");r(this,"_joinedRoomMethod");r(this,"_lastRequestFollowUser");r(this,"_enforceFollowInterval");this.context=A,this.spectator=e,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(It.JoinedRoom,this._joinedRoomMethod),this.context.domElement.addEventListener("keydown",A=>{this.spectator.useKeys&&(A.key==="f"?this.onRequestFollowMe():A.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(It.JoinedRoom,this._joinedRoomMethod)}onSpectatedObjectChanged(A,e){if(yo&&console.log(this.context.connection.connectionId,"onSpectatedObjectChanged",A,e),this.context.connection.connectionId){const t=(A==null?void 0:A.userId)===void 0,i=t?e:A==null?void 0:A.userId,I=new orA(this.context.connection.connectionId,i,t);this.context.connection.send("spectator-follower-changed",I)}}onRequestFollowMe(A=!1){if(yo&&console.log("Request follow",this.context.connection.connectionId),this.context.connection.connectionId){this.spectator.stopSpectating();const e=A?void 0:this.context.connection.connectionId,t=new srA(this.spectator,e);this.context.connection.send("spectator-request-follow",t)}}onUserJoinedRoom(){IA("followme")&&this.onRequestFollowMe()}onFollowerEvent(A){const e=A.targetUserId,t=A.guid;if(yo&&console.log(A),e===this.context.connection.connectionId)if(A.stoppedFollowing){const i=this.followers.indexOf(t);i!==-1&&(this.followers.splice(i,1),this.removeDisconnectedFollowers(),console.log(t,"unfollows you",this.followers.length))}else this.followers.includes(t)||(this.followers.push(t),this.removeDisconnectedFollowers(),console.log(t,"follows you",this.followers.length))}removeDisconnectedFollowers(){for(let A=this.followers.length-1;A>=0;A--){const e=this.followers[A];this.context.connection.userIsInRoom(e)===!1&&this.followers.splice(A,1)}}onRequestFollowEvent(A){if(this._lastRequestFollowUser=A,A.userId===this.context.connection.connectionId)this.spectator.stopSpectating();else if(A.userId===void 0)this.spectator.stopSpectating();else{const e=this.context.players.getPlayerView(A.userId);if(e)this.spectator.target=e;else return yo&&console.warn("Could not find view",A.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):(yo&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}}var CrA=Object.defineProperty,arA=Object.getOwnPropertyDescriptor,PI=(g,A,e,t)=>{for(var i=t>1?void 0:t?arA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&CrA(A,e,i),i};const Tw=IA("debugspriterenderer"),rrA=IA("wireframe"),Iy=class{static getOrCreateGeometry(A){if(A.__cached_geometry)return A.__cached_geometry;if(A.guid&&Iy.cache[A.guid])return Tw&&console.log("Take cached geometry for sprite",A.guid),Iy.cache[A.guid];const e=new ue;A.__cached_geometry=e;const t=new Float32Array(A.triangles.length*3),i=new Float32Array(A.triangles.length*2);for(let I=0;I<A.triangles.length;I+=1){const o=A.triangles[I];t[I*3]=-A.vertices[o].x,t[I*3+1]=A.vertices[o].y,t[I*3+2]=0;const s=A.uv[o];i[I*2]=s.x,i[I*2+1]=1-s.y}return e.setAttribute("position",new ie(t,3)),e.setAttribute("uv",new ie(i,2)),A.guid&&(this.cache[A.guid]=e),Tw&&console.log("Built sprite geometry",A,e),e}};let MB=Iy;r(MB,"cache",{});class Aa{constructor(){r(this,"guid");r(this,"texture");r(this,"triangles");r(this,"uv");r(this,"vertices");r(this,"__cached_geometry");r(this,"_mesh");r(this,"_material")}get mesh(){return this._mesh||(this._mesh=new lA(MB.getOrCreateGeometry(this),this.material)),this._mesh}get material(){return this._material||(this.texture&&(this.texture.colorSpace=de,this.texture.minFilter==Te&&this.texture.magFilter==Te&&(this.texture.anisotropy=1),this.texture.needsUpdate=!0),this._material=new rt({map:this.texture,color:16777215,side:ht,transparent:!0})),this._material}getGeometry(){return MB.getOrCreateGeometry(this)}}PI([D()],Aa.prototype,"guid",2);PI([D(fe)],Aa.prototype,"texture",2);PI([Uc()],Aa.prototype,"triangles",2);PI([Uc()],Aa.prototype,"uv",2);PI([Uc()],Aa.prototype,"vertices",2);const vG=Symbol("spriteOwner");class Qp{constructor(){r(this,"sprites")}}PI([D(Aa)],Qp.prototype,"sprites",2);class il{constructor(){r(this,"spriteSheet");r(this,"index",0)}update(A,e,t){if(!this.spriteSheet)return;const i=this.index;if(i<0||i>=this.spriteSheet.sprites.length)return;const I=this.spriteSheet.sprites[i],o=I==null?void 0:I.texture;if(o&&(o.colorSpace=de,o.minFilter==Te&&o.magFilter==Te&&(o.anisotropy=1),o.needsUpdate=!0,!I.__hasLoadedProgressive)){I.__hasLoadedProgressive=!0;const s=o;Kt.assignTextureLOD(A,e,o,0).then(n=>{n instanceof fe&&(I.texture=n,(t==null?void 0:t.map)===s&&(t.map=n,t.needsUpdate=!0))})}}}PI([D(Qp)],il.prototype,"spriteSheet",2);PI([D()],il.prototype,"index",2);class Yn extends RA{constructor(){super(...arguments);r(this,"drawMode",0);r(this,"size",{x:1,y:1});r(this,"color");r(this,"sharedMaterial");r(this,"transparent",!0);r(this,"cutoutThreshold",0);r(this,"castShadows",!1);r(this,"_spriteSheet");r(this,"_currentSprite")}get sprite(){return this._spriteSheet}set sprite(e){if(e!==this._spriteSheet)if(typeof e=="number"){const t=Math.floor(e);this.spriteIndex=t;return}else this._spriteSheet=e,this.updateSprite()}set spriteIndex(e){this._spriteSheet&&(this._spriteSheet.index=e,this.updateSprite())}get spriteIndex(){var e;return((e=this._spriteSheet)==null?void 0:e.index)??0}get spriteFrames(){var e,t;return((t=(e=this._spriteSheet)==null?void 0:e.spriteSheet)==null?void 0:t.sprites.length)??0}awake(){this._currentSprite=void 0,Tw&&console.log("Awake",this.name,this,this.sprite)}start(){this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(){var t,i,I;if(!this.__didAwake||!((i=(t=this.sprite)==null?void 0:t.spriteSheet)!=null&&i.sprites))return;const e=this.sprite.spriteSheet.sprites[this.spriteIndex];if(!e){Tw&&console.warn("Sprite not found",this.spriteIndex,this.sprite.spriteSheet.sprites);return}if(this._currentSprite)this._currentSprite.geometry=MB.getOrCreateGeometry(e),this._currentSprite.material.map=e.texture;else{const o=new rt({color:16777215,side:ht});if(!o)return;if(rrA&&(o.wireframe=!0),this.color&&(o.color||(o.color=new mA),o.color.copy(this.color),o.opacity=this.color.alpha),o.transparent=!0,e.texture&&!o.wireframe){let s=e.texture;s[vG]!==void 0&&s[vG]!==this&&this.spriteFrames>1&&(s=e.texture=s.clone()),s[vG]=this,o.map=s}this.sharedMaterial=o,this._currentSprite=new lA(MB.getOrCreateGeometry(e),o),Kt.assignTextureLOD(this.context,this.sourceId,o,0)}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,(I=this._spriteSheet)==null||I.update(this.context,this.sourceId,this.sharedMaterial)}}PI([D()],Yn.prototype,"drawMode",2);PI([D(Mt)],Yn.prototype,"color",2);PI([D(be)],Yn.prototype,"sharedMaterial",2);PI([D()],Yn.prototype,"transparent",2);PI([D()],Yn.prototype,"cutoutThreshold",2);PI([D()],Yn.prototype,"castShadows",2);PI([D(il)],Yn.prototype,"sprite",1);class cn{constructor(){r(this,"bb",null);r(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}static getRootAsSyncedCameraModel(A,e){return(e||new cn).__init(A.readInt32(A.position())+A.position(),A)}static getSizePrefixedRootAsSyncedCameraModel(A,e){return A.setPosition(A.position()+SN),(e||new cn).__init(A.readInt32(A.position())+A.position(),A)}userId(A){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,A):null}guid(A){const e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,A):null}dontSave(){const A=this.bb.__offset(this.bb_pos,8);return A?!!this.bb.readInt8(this.bb_pos+A):!1}pos(A){const e=this.bb.__offset(this.bb_pos,10);return e?(A||new SB).__init(this.bb_pos+e,this.bb):null}rot(A){const e=this.bb.__offset(this.bb_pos,12);return e?(A||new SB).__init(this.bb_pos+e,this.bb):null}static startSyncedCameraModel(A){A.startObject(5)}static addUserId(A,e){A.addFieldOffset(0,e,0)}static addGuid(A,e){A.addFieldOffset(1,e,0)}static addDontSave(A,e){A.addFieldInt8(2,+e,0)}static addPos(A,e){A.addFieldStruct(3,e,0)}static addRot(A,e){A.addFieldStruct(4,e,0)}static endSyncedCameraModel(A){return A.endObject()}static finishSyncedCameraModelBuffer(A,e){A.finish(e)}static finishSizePrefixedSyncedCameraModelBuffer(A,e){A.finish(e,void 0,!0)}}var BrA=Object.defineProperty,QrA=Object.getOwnPropertyDescriptor,ErA=(g,A,e,t)=>{for(var i=t>1?void 0:t?QrA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&BrA(A,e,i),i};const Hw="SCAM";GN(Hw,cn.getRootAsSyncedCameraModel);const Qo=new pu;class crA{constructor(A,e){r(this,"userId");r(this,"guid");this.guid=e,this.userId=A}send(A,e){if(A){Qo.clear();const t=Qo.createString(this.guid),i=Qo.createString(this.userId);cn.startSyncedCameraModel(Qo),cn.addGuid(Qo,t),cn.addUserId(Qo,i);const I=_e(A),o=Eu(A);cn.addPos(Qo,SB.createVec3(Qo,I.x,I.y,I.z)),cn.addRot(Qo,SB.createVec3(Qo,o.x,o.y,o.z));const s=cn.endSyncedCameraModel(Qo);Qo.finish(s,Hw),e.sendBinary(Qo.asUint8Array())}}}var Ik;const QU=(Ik=class extends RA{constructor(){super(...arguments);r(this,"cameraPrefab",null);r(this,"_lastWorldPosition");r(this,"_lastWorldQuaternion");r(this,"_model",null);r(this,"_needsUpdate",!0);r(this,"_lastUpdateTime",0);r(this,"remoteCams",{});r(this,"userToCamMap",{});r(this,"_camTimeoutInSeconds",10);r(this,"_receiveCallback",null)}getCameraObject(A){const e=this.userToCamMap[A];return e?this.remoteCams[e].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(Hw,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(Hw,this._receiveCallback)}update(){for(const i in this.remoteCams){const I=this.remoteCams[i],o=this.context.time.realtimeSinceStartup-I.lastUpdate;if(!I||o>this._camTimeoutInSeconds){he()&&console.log("Remote cam timeout",i),I!=null&&I.obj&&aA.destroy(I.obj),delete this.remoteCams[i],I&&delete this.userToCamMap[I.userId],QU.instances.push(I),this.context.players.removePlayerView(I.userId,ja.Browser);continue}}if(this.context.isInXR)return;const A=this.context.mainCamera;if(A===null){this.enabled=!1;return}if(!this.context.connection.isConnected||this.context.connection.connectionId===null)return;this._model===null&&(this._model=new crA(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));const e=_e(A),t=Jt(A);(e.distanceTo(this._lastWorldPosition)>.001||t.angleTo(this._lastWorldQuaternion)>.01)&&(this._needsUpdate=!0),this._lastWorldPosition.copy(e),this._lastWorldQuaternion.copy(t),!((!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(A,this.context.connection),this.context.isInXR||this.context.players.setPlayerView(this.context.connection.connectionId,A,ja.Browser))}onReceivedRemoteCameraInfoBin(A){const e=A.guid();if(!e)return;const t=A.userId();if(!t||!this.context.connection.userIsInRoom(t)||!this.cameraPrefab)return;let i=this.remoteCams[e];if(!i)if("isObject3D"in this.cameraPrefab){const n=new zs;n.context=this.context;const C=aA.instantiate(this.cameraPrefab,n);i=this.remoteCams[e]={obj:C,lastUpdate:this.context.time.realtimeSinceStartup,userId:t},i.obj.visible=!0,this.gameObject.add(C),this.userToCamMap[t]=e,QU.instances.push(i);const a=aA.getOrAddComponent(C,sg);a.connectionId=t,a.avatar=C}else return;const I=i.obj;this.context.players.setPlayerView(t,I,ja.Browser),i.lastUpdate=this.context.time.realtimeSinceStartup,ss.markDirty(I);const o=A.pos();o&&LB(I,o.x(),o.y(),o.z());const s=A.rot();s&&cu(I,s.x(),s.y(),s.z())}},r(Ik,"instances",[]),Ik);let t0=QU;ErA([D([uA,tt])],t0.prototype,"cameraPrefab",2);var lrA=Object.defineProperty,hrA=Object.getOwnPropertyDescriptor,gl=(g,A,e,t)=>{for(var i=t>1?void 0:t?hrA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&lrA(A,e,i),i};const qG="view",xG=IA("debugsyncedroom");class ea extends RA{constructor(){super(...arguments);r(this,"roomName");r(this,"urlParameterName","room");r(this,"joinRandomRoom",!0);r(this,"requireRoomParameter",!1);r(this,"autoRejoin",!0);r(this,"createJoinButton",!0);r(this,"_roomPrefix");r(this,"_lastJoinedRoom","");r(this,"_lastPingTime",0);r(this,"_lastRoomTime",-1);r(this,"_userWantsToBeInARoom",!1);r(this,"_roomButton");r(this,"_roomButtonIconJoin");r(this,"_roomButtonIconLeave");r(this,"updateRoomButtonState",()=>{var e,t;this._roomButton&&(this.context.connection.isInRoom?(this._roomButton.title="Leave the networked room",this._roomButton.textContent="Leave Room",(e=this._roomButtonIconJoin)==null||e.remove(),this._roomButton.prepend(this._roomButtonIconLeave)):(this._roomButton.title="Create or join a networked room",this._roomButton.textContent="Join Room",(t=this._roomButtonIconLeave)==null||t.remove(),this._roomButton.prepend(this._roomButtonIconJoin)))})}get roomPrefix(){return this._roomPrefix}get RoomPrefix(){return this._roomPrefix}awake(){xG&&console.log("Room",this.roomName,this.urlParameterName,this.joinRandomRoom,this.requireRoomParameter,this.autoRejoin),this._roomPrefix===void 0&&(this._roomPrefix=this.roomName,this.roomName="")}onEnable(){const e=IA(qG);if(e&&typeof e=="string"&&e.length>0){console.log("Join as viewer"),this.context.connection.joinRoom(e,!0);return}if((this.joinRandomRoom||IA(this.urlParameterName))&&this.tryJoinRoom(),this.createJoinButton){const t=this.createRoomButton();this.context.menu.appendChild(t)}}onDisable(){var e;(e=this._roomButton)==null||e.remove(),this.roomName&&this.roomName.length>0&&this.context.connection.leaveRoom(this.roomName)}onDestroy(){this.destroyRoomButton()}tryJoinRandomRoom(){this.setRandomRoomUrlParameter(),this.tryJoinRoom()}tryJoinRoom(e=0){e===void 0&&(e=0);let t=!1;if(this.urlParameterName){const i=IA(this.urlParameterName);if(i&&typeof i=="string"||i==="number"){t=!0;const I=hT(i);this.roomName=I}else if(this.joinRandomRoom&&(console.log("No room name found in url, generating random one"),this.setRandomRoomUrlParameter(),e<1))return this.tryJoinRoom(e+1)}else this.joinRandomRoom&&(this.roomName===null||this.roomName===void 0||this.roomName.length<=0)&&(console.log("generate room name"),this.roomName=this.generateRoomName());return this.requireRoomParameter&&!t?(xG&&console.log('No required room parameter "'+this.urlParameterName+'" in url - will not connect to networking backend.'),!1):(this.context.connection.isConnected||this.context.connection.connect(),xG&&console.log("Join "+this.roomName),this._lastJoinedRoom=this.roomName,this._roomPrefix&&(this.roomName=this._roomPrefix+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()):he()&&console.warn("You are not connected to a room anymore (possibly because the tab was inactive for too long and the server kicked you?)"))}get currentRoomName(){const e=IA(qG);return e||IA(this.urlParameterName)}setRandomRoomUrlParameter(){const e=nu(),t=this.generateRoomName();IA(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),lR(t,e)}generateRoomName(){return hR()+"_"+Math.floor(te.random(100,999))}getViewOnlyUrl(){if(this.context.connection.isConnected&&this.context.connection.currentRoomViewId){const e=window.location.search,t=new URLSearchParams(e);return t.has(this.urlParameterName)&&t.delete(this.urlParameterName),t.set(qG,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}createRoomButton(){if(this._roomButton)return this._roomButton;const e=document.createElement("button");return this._roomButton=e,e.classList.add("create-room-button"),e.setAttribute("priority","90"),e.onclick=()=>{this.context.connection.isInRoom?(this.urlParameterName&&aw(this.urlParameterName,null),this.context.connection.leaveRoom(),this._userWantsToBeInARoom=!1):(this.urlParameterName&&(IA(this.urlParameterName)||(this._lastJoinedRoom?aw(this.urlParameterName,this._lastJoinedRoom):this.setRandomRoomUrlParameter())),this.tryJoinRoom())},this._roomButtonIconJoin=wo("group"),this._roomButtonIconLeave=wo("group_off"),this.updateRoomButtonState(),this.context.connection.beginListen(It.JoinedRoom,this.updateRoomButtonState),this.context.connection.beginListen(It.LeftRoom,this.updateRoomButtonState),e}destroyRoomButton(){this.context.connection.stopListen(It.JoinedRoom,this.updateRoomButtonState),this.context.connection.stopListen(It.LeftRoom,this.updateRoomButtonState)}}gl([D()],ea.prototype,"roomName",2);gl([D()],ea.prototype,"urlParameterName",2);gl([D()],ea.prototype,"joinRandomRoom",2);gl([D()],ea.prototype,"requireRoomParameter",2);gl([D()],ea.prototype,"autoRejoin",2);gl([D()],ea.prototype,"createJoinButton",2);class i0 extends RA{}function drA(){const g=IA("testwindowcount")||0;g&&g>0&&urA(g)}function urA(g){if(IA("testwindow"))return null;const A=new URL(window.location.href);Yk(A.searchParams,hIA,1),Yk(A.searchParams,"testwindow",1);const e=A.toString(),t=[];window.onbeforeunload=()=>{for(const n of t)n.close()};const i=.05,I=128;let o=0,s=0;for(let n=0;n<g;n++){o*I+I*.01>=window.innerWidth&&(s+=1,o=0);const C=o*(I*(1+i))+window.screenLeft,a=s*(I*(1+i))+window.screenTop+90+60*s;o+=1;const B=window.open(e,"test window "+n,`popup=yes width=${I} height=${I} top=${a} left=${C}`);if(!B){console.warn("Failed to open window");continue}t.push(B),B.onload=()=>{B.onbeforeunload=()=>{for(let Q=0;Q<t.length;Q++){const E=t[Q];E!==B&&E.close()}t.length=0}}}return t}class JF extends RA{awake(){drA()}}class bF extends RA{constructor(){super(...arguments);r(this,"transformsPerFrame",10);r(this,"interval",0);r(this,"useFlatbuffers",!0);r(this,"builder",null);r(this,"models",null)}awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinary(Rd,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new _P(this.context.connection.connectionId+"_simulatedTransform_"+e,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 pu(1024));const e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();const i=vO(this.context.connection.connectionId,this);this.context.connection.sendBinary(i)}}else if(this.models)for(let e=0;e<this.models.length;e++){const t=this.models[e];t.dontSave=!0,t.update(this,null),this.context.connection.send("TestSimulateUserData-"+e,t)}}}}class _P{constructor(A,e){r(this,"guid");r(this,"fast",!1);r(this,"position");r(this,"rotation");r(this,"velocity");r(this,"dontSave");this.guid=A,this.position={x:0,y:0,z:0},this.rotation={x:0,y:0,z:0,w:0},this.update(e,null)}isValid(){return this.fast!==void 0||this.position!==void 0||this.rotation!==void 0||this.velocity!==void 0}update(A,e){const t=A.worldPosition;this.position.x=t.x,this.position.y=t.y,this.position.z=t.z;const i=A.worldQuaternion;if(this.rotation.x=i.x,this.rotation.y=i.y,this.rotation.z=i.z,this.rotation.w=i.w,this.fast=!1,e){const I=e.getVelocity();this.velocity===void 0&&(this.velocity={x:0,y:0,z:0}),this.velocity.x=I.x,this.velocity.y=I.y,this.velocity.z=I.z}}}r(_P,"temp",new w);var prA=Object.defineProperty,frA=Object.getOwnPropertyDescriptor,Il=(g,A,e,t)=>{for(var i=t>1?void 0:t?frA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&prA(A,e,i),i};class On extends hI{constructor(){super(...arguments);r(this,"offset");r(this,"rotation");r(this,"focusArea");r(this,"feather");r(this,"kernelSize");r(this,"resolutionScale")}get typeName(){return"TiltShiftEffect"}init(){this.offset.defaultValue=0,this.rotation.defaultValue=0,this.focusArea.defaultValue=.4,this.feather.defaultValue=.3,this.kernelSize.defaultValue=qC.MEDIUM,this.resolutionScale.defaultValue=1/window.devicePixelRatio}onCreateEffect(){console.log(this);const e=new DeA({kernelSize:qC.VERY_LARGE});return this.offset.onValueChanged=t=>e.offset=t,this.rotation.onValueChanged=t=>e.rotation=t,this.focusArea.onValueChanged=t=>e.focusArea=t,this.feather.onValueChanged=t=>e.feather=t,this.kernelSize.onValueChanged=t=>e.blurPass.kernelSize=t,this.resolutionScale.onValueChanged=t=>e.resolution.scale=t/window.devicePixelRatio,e}}Il([D(qe)],On.prototype,"offset",2);Il([D(qe)],On.prototype,"rotation",2);Il([D(qe)],On.prototype,"focusArea",2);Il([D(qe)],On.prototype,"feather",2);Il([D(qe)],On.prototype,"kernelSize",2);Il([D(qe)],On.prototype,"resolutionScale",2);ds("TiltShiftEffect",On);var DrA=Object.defineProperty,wrA=Object.getOwnPropertyDescriptor,yrA=(g,A,e,t)=>{for(var i=t>1?void 0:t?wrA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&DrA(A,e,i),i};class Ep extends hI{constructor(){super(...arguments);r(this,"mode")}get typeName(){return"ToneMapping"}get isToneMapping(){return!0}init(){this.mode||(this.mode=new qe(eo)),this.mode.defaultValue=eo}apply(){this.mode||this.init(),this.mode.onValueChanged=this._apply.bind(this),this._apply(this.mode.value)}_apply(e){this.context.renderer.toneMapping=this.getThreeToneMapping(e)}getThreeToneMapping(e){switch(e){case 0:return VE;case 1:return ay;case 2:return Cy;default:return VE}}}yrA([D(qe)],Ep.prototype,"mode",2);ds("Tonemapping",Ep);var SrA=Object.defineProperty,mrA=Object.getOwnPropertyDescriptor,g0=(g,A,e,t)=>{for(var i=t>1?void 0:t?mrA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&SrA(A,e,i),i};class kQ extends RA{constructor(){super(...arguments);r(this,"isGizmo",!1);r(this,"translationSnap",1);r(this,"rotationSnapAngle",15);r(this,"scaleSnap",.25);r(this,"control");r(this,"orbit");r(this,"onControlChangedEvent",e=>{const t=this.orbit;if(t&&(t.enabled=!e.value),e.value){const i=aA.getComponentInParent(this.gameObject,sr);i&&i.requestOwnership()}});r(this,"windowKeyDownListener",e=>{if(this.enabled&&this.control)switch(e.keyCode){case 81:this.control.setSpace(this.control.space==="local"?"world":"local");break;case 16:this.enableSnapping();break;case 87:this.control.setMode("translate");break;case 69:this.control.setMode("rotate");break;case 82:this.control.setMode("scale");break;case 187:case 107:this.control.setSize(this.control.size+.1);break;case 189:case 109:this.control.setSize(Math.max(this.control.size-.1,.1));break;case 88:this.control.showX=!this.control.showX;break;case 89:this.control.showY=!this.control.showY;break;case 90:this.control.showZ=!this.control.showZ;break;case 32:this.control.enabled=!this.control.enabled;break}});r(this,"windowKeyUpListener",e=>{if(this.enabled)switch(e.keyCode){case 16:this.disableSnapping();break}})}onEnable(){var e;this.isGizmo&&!uu||this.context.mainCamera&&(this.control||(this.control=new V7(this.context.mainCamera,this.context.renderer.domElement),this.control.visible=!0,this.control.enabled=!0,this.control.getRaycaster().layers.set(2),this.control.size=1,this.control.traverse(t=>{const i=t;if(i.layers.set(2),i){const I=i.material;I&&(I.opacity=.3)}}),this.orbit=aA.getComponentInParent(this.context.mainCamera,Rt)??void 0),this.control&&(this.context.scene.add(this.control),this.control.attach(this.gameObject),(e=this.control)==null||e.addEventListener("dragging-changed",this.onControlChangedEvent),window.addEventListener("keydown",this.windowKeyDownListener),window.addEventListener("keyup",this.windowKeyUpListener)))}onDisable(){var e,t;(e=this.control)==null||e.removeFromParent(),(t=this.control)==null||t.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(Cg.degToRad(this.rotationSnapAngle)),this.control.setScaleSnap(this.scaleSnap))}disableSnapping(){this.control&&(this.control.setTranslationSnap(null),this.control.setRotationSnap(null),this.control.setScaleSnap(null))}}g0([D()],kQ.prototype,"isGizmo",2);g0([D()],kQ.prototype,"translationSnap",2);g0([D()],kQ.prototype,"rotationSnapAngle",2);g0([D()],kQ.prototype,"scaleSnap",2);var GrA=Object.defineProperty,krA=Object.getOwnPropertyDescriptor,vF=(g,A,e,t)=>{for(var i=t>1?void 0:t?krA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&GrA(A,e,i),i};class MQ extends hI{constructor(){super(...arguments);r(this,"color");r(this,"intensity");r(this,"center")}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 e=new KY;return this.intensity.onValueChanged=t=>{e.offset=t,this.updateDarkness(e)},this.color.onValueChanged=t=>{this.updateDarkness(e)},e}updateDarkness(e){const t=this.intensity.value;e.darkness=t}}vF([D(qe)],MQ.prototype,"color",2);vF([D(qe)],MQ.prototype,"intensity",2);vF([D(qe)],MQ.prototype,"center",2);ds("Vignette",MQ);var MrA=Object.defineProperty,UrA=Object.getOwnPropertyDescriptor,RrA=(g,A,e,t)=>{for(var i=t>1?void 0:t?UrA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&MrA(A,e,i),i};const OD=IA("debugarcamera");class I0 extends RA{constructor(){super(...arguments);r(this,"backgroundTint",new Mt(1,1,1,1));r(this,"backgroundPlane");r(this,"threeTexture");r(this,"forceTextureInitialization",function(){const e=new rt,t=new Xi,i=new cI;i.add(new lA(t,e));const I=new He;return function(s,n){e.map=n,s.render(i,I),OD&&console.warn("Force texture initialization")}}());r(this,"preRender",()=>{if(!this||!this.gameObject)return;const t=this.context.renderer.xr.getFrame();t&&(!this.threeTexture&&this.context.renderer&&(this.threeTexture=new fe,this.forceTextureInitialization(this.context.renderer,this.threeTexture)),this.backgroundPlane===void 0&&(this.backgroundPlane=FrA(this.backgroundTint)),this.backgroundPlane.parent!==this.scene&&this.scene.add(this.backgroundPlane),this.updateFromFrame(t))})}onBeforeXR(e,t){t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("camera-access"),OD&&console.warn("Requesting camera-access")}onEnterXR(e){this.backgroundPlane&&(this.context.scene.add(this.backgroundPlane),this.backgroundPlane.visible=!1),this.backgroundPlane&&this.context.scene.add(this.backgroundPlane),this.context.pre_render_callbacks.push(this.preRender)}onLeaveXR(e){this.backgroundPlane&&this.backgroundPlane.removeFromParent();const t=this.context.pre_render_callbacks.indexOf(this.preRender);t>=0&&this.context.pre_render_callbacks.splice(t,1)}get background(){return this.backgroundPlane}onBeforeRender(e){this.updateFromFrame(e)}updateFromFrame(e){if(!e)return;const t=e.session.enabledFeatures;if(t&&!t.some(I=>I==="camera-access")){this.background&&(this.background.visible=!1);return}const i=e.getViewerPose(this.context.renderer.xr.getReferenceSpace());if(i){for(const I of i.views)if("camera"in I&&I.camera){let s=this.context.renderer.xr.getBinding();if(s||(s=new XRWebGLBinding(e.session,this.context.renderer.getContext())),s){let n=null;if("getCameraImage"in s){n=s.getCameraImage(I.camera);const C=this.context.renderer.properties.get(this.threeTexture);C.__webglTexture=n,this.backgroundPlane?(this.backgroundPlane.setTexture(this.threeTexture),this.backgroundPlane.visible=!0):OD&&console.warn("No background plane to set texture on")}}}}}}RrA([D(Mt)],I0.prototype,"backgroundTint",2);const NrA=`
7019
7019
  uniform sampler2D t2D;
7020
7020
 
7021
7021
  varying vec2 vUv;