@needle-tools/engine 3.32.18-alpha โ†’ 3.32.19-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.
@@ -3944,7 +3944,7 @@ Open this page console: `+e.toString())}const n=Ec()||Gx()&&Mt();if(n&&(D6(),ZU(
3944
3944
  }
3945
3945
  }
3946
3946
  `,ro==null||ro.prepend(t),n===!0&&lI()<=0&&z6(),console.log("๐ŸŒต Debug console has loaded")}},e.src="https://unpkg.com/vconsole@latest/dist/vconsole.min.js",document.body.appendChild(e)}function j6(){const n=document.querySelector("#__vconsole .vc-switch");return n||null}function W6(){const n=document.querySelector("#__vconsole");return n||null}const q6=se("nodevlogs");function xn(n,e=Jo.Log){Al(e,n)}function pn(n){xn(n,Jo.Warn)}function eN(n){xn(n,Jo.Error)}let B1;function Mt(){return q6?!1:B1!==void 0?B1:Er()}function X6(n){B1=n}const _u=new Qp,tr=new w,Zl=new w,$i=new Ee,ND={X:new w(1,0,0),Y:new w(0,1,0),Z:new w(0,0,1)},eC={type:"change"},zD={type:"mouseDown"},GD={type:"mouseUp",mode:null},HD={type:"objectChange"};class Y6 extends ge{constructor(e,t){super(),t===void 0&&(console.warn('THREE.TransformControls: The second parameter "domElement" is now mandatory.'),t=document),this.isTransformControls=!0,this.visible=!1,this.domElement=t,this.domElement.style.touchAction="none";const i=new uI;this._gizmo=i,this.add(i);const s=new tq;this._plane=s,this.add(s);const r=this;function o(A,_){let b=_;Object.defineProperty(r,A,{get:function(){return b!==void 0?b:_},set:function(C){b!==C&&(b=C,s[A]=C,i[A]=C,r.dispatchEvent({type:A+"-changed",value:C}),r.dispatchEvent(eC))}}),r[A]=_,s[A]=_,i[A]=_}o("camera",e),o("object",void 0),o("enabled",!0),o("axis",null),o("mode","translate"),o("translationSnap",null),o("rotationSnap",null),o("scaleSnap",null),o("space","world"),o("size",1),o("dragging",!1),o("showX",!0),o("showY",!0),o("showZ",!0);const a=new w,c=new w,l=new Ee,h=new Ee,d=new w,f=new Ee,p=new w,m=new w,g=new w,y=0,v=new w;o("worldPosition",a),o("worldPositionStart",c),o("worldQuaternion",l),o("worldQuaternionStart",h),o("cameraPosition",d),o("cameraQuaternion",f),o("pointStart",p),o("pointEnd",m),o("rotationAxis",g),o("rotationAngle",y),o("eye",v),this._offset=new w,this._startNorm=new w,this._endNorm=new w,this._cameraScale=new w,this._parentPosition=new w,this._parentQuaternion=new Ee,this._parentQuaternionInv=new Ee,this._parentScale=new w,this._worldScaleStart=new w,this._worldQuaternionInv=new Ee,this._worldScale=new w,this._positionStart=new w,this._quaternionStart=new Ee,this._scaleStart=new w,this._getPointer=J6.bind(this),this._onPointerDown=Z6.bind(this),this._onPointerHover=K6.bind(this),this._onPointerMove=$6.bind(this),this._onPointerUp=eq.bind(this),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointermove",this._onPointerHover),this.domElement.addEventListener("pointerup",this._onPointerUp)}updateMatrixWorld(){this.object!==void 0&&(this.object.updateMatrixWorld(),this.object.parent===null?console.error("TransformControls: The attached 3D object must be a part of the scene graph."):this.object.parent.matrixWorld.decompose(this._parentPosition,this._parentQuaternion,this._parentScale),this.object.matrixWorld.decompose(this.worldPosition,this.worldQuaternion,this._worldScale),this._parentQuaternionInv.copy(this._parentQuaternion).invert(),this._worldQuaternionInv.copy(this.worldQuaternion).invert()),this.camera.updateMatrixWorld(),this.camera.matrixWorld.decompose(this.cameraPosition,this.cameraQuaternion,this._cameraScale),this.camera.isOrthographicCamera?this.camera.getWorldDirection(this.eye).negate():this.eye.copy(this.cameraPosition).sub(this.worldPosition).normalize(),super.updateMatrixWorld(this)}pointerHover(e){if(this.object===void 0||this.dragging===!0)return;_u.setFromCamera(e,this.camera);const t=tC(this._gizmo.picker[this.mode],_u);t?this.axis=t.object.name:this.axis=null}pointerDown(e){if(!(this.object===void 0||this.dragging===!0||e.button!==0)&&this.axis!==null){_u.setFromCamera(e,this.camera);const t=tC(this._plane,_u,!0);t&&(this.object.updateMatrixWorld(),this.object.parent.updateMatrixWorld(),this._positionStart.copy(this.object.position),this._quaternionStart.copy(this.object.quaternion),this._scaleStart.copy(this.object.scale),this.object.matrixWorld.decompose(this.worldPositionStart,this.worldQuaternionStart,this._worldScaleStart),this.pointStart.copy(t.point).sub(this.worldPositionStart)),this.dragging=!0,zD.mode=this.mode,this.dispatchEvent(zD)}}pointerMove(e){const t=this.axis,i=this.mode,s=this.object;let r=this.space;if(i==="scale"?r="local":(t==="E"||t==="XYZE"||t==="XYZ")&&(r="world"),s===void 0||t===null||this.dragging===!1||e.button!==-1)return;_u.setFromCamera(e,this.camera);const o=tC(this._plane,_u,!0);if(o){if(this.pointEnd.copy(o.point).sub(this.worldPositionStart),i==="translate")this._offset.copy(this.pointEnd).sub(this.pointStart),r==="local"&&t!=="XYZ"&&this._offset.applyQuaternion(this._worldQuaternionInv),t.indexOf("X")===-1&&(this._offset.x=0),t.indexOf("Y")===-1&&(this._offset.y=0),t.indexOf("Z")===-1&&(this._offset.z=0),r==="local"&&t!=="XYZ"?this._offset.applyQuaternion(this._quaternionStart).divide(this._parentScale):this._offset.applyQuaternion(this._parentQuaternionInv).divide(this._parentScale),s.position.copy(this._offset).add(this._positionStart),this.translationSnap&&(r==="local"&&(s.position.applyQuaternion($i.copy(this._quaternionStart).invert()),t.search("X")!==-1&&(s.position.x=Math.round(s.position.x/this.translationSnap)*this.translationSnap),t.search("Y")!==-1&&(s.position.y=Math.round(s.position.y/this.translationSnap)*this.translationSnap),t.search("Z")!==-1&&(s.position.z=Math.round(s.position.z/this.translationSnap)*this.translationSnap),s.position.applyQuaternion(this._quaternionStart)),r==="world"&&(s.parent&&s.position.add(tr.setFromMatrixPosition(s.parent.matrixWorld)),t.search("X")!==-1&&(s.position.x=Math.round(s.position.x/this.translationSnap)*this.translationSnap),t.search("Y")!==-1&&(s.position.y=Math.round(s.position.y/this.translationSnap)*this.translationSnap),t.search("Z")!==-1&&(s.position.z=Math.round(s.position.z/this.translationSnap)*this.translationSnap),s.parent&&s.position.sub(tr.setFromMatrixPosition(s.parent.matrixWorld))));else if(i==="scale"){if(t.search("XYZ")!==-1){let a=this.pointEnd.length()/this.pointStart.length();this.pointEnd.dot(this.pointStart)<0&&(a*=-1),Zl.set(a,a,a)}else tr.copy(this.pointStart),Zl.copy(this.pointEnd),tr.applyQuaternion(this._worldQuaternionInv),Zl.applyQuaternion(this._worldQuaternionInv),Zl.divide(tr),t.search("X")===-1&&(Zl.x=1),t.search("Y")===-1&&(Zl.y=1),t.search("Z")===-1&&(Zl.z=1);s.scale.copy(this._scaleStart).multiply(Zl),this.scaleSnap&&(t.search("X")!==-1&&(s.scale.x=Math.round(s.scale.x/this.scaleSnap)*this.scaleSnap||this.scaleSnap),t.search("Y")!==-1&&(s.scale.y=Math.round(s.scale.y/this.scaleSnap)*this.scaleSnap||this.scaleSnap),t.search("Z")!==-1&&(s.scale.z=Math.round(s.scale.z/this.scaleSnap)*this.scaleSnap||this.scaleSnap))}else if(i==="rotate"){this._offset.copy(this.pointEnd).sub(this.pointStart);const a=20/this.worldPosition.distanceTo(tr.setFromMatrixPosition(this.camera.matrixWorld));let c=!1;t==="XYZE"?(this.rotationAxis.copy(this._offset).cross(this.eye).normalize(),this.rotationAngle=this._offset.dot(tr.copy(this.rotationAxis).cross(this.eye))*a):(t==="X"||t==="Y"||t==="Z")&&(this.rotationAxis.copy(ND[t]),tr.copy(ND[t]),r==="local"&&tr.applyQuaternion(this.worldQuaternion),tr.cross(this.eye),tr.length()===0?c=!0:this.rotationAngle=this._offset.dot(tr.normalize())*a),(t==="E"||c)&&(this.rotationAxis.copy(this.eye),this.rotationAngle=this.pointEnd.angleTo(this.pointStart),this._startNorm.copy(this.pointStart).normalize(),this._endNorm.copy(this.pointEnd).normalize(),this.rotationAngle*=this._endNorm.cross(this._startNorm).dot(this.eye)<0?1:-1),this.rotationSnap&&(this.rotationAngle=Math.round(this.rotationAngle/this.rotationSnap)*this.rotationSnap),r==="local"&&t!=="E"&&t!=="XYZE"?(s.quaternion.copy(this._quaternionStart),s.quaternion.multiply($i.setFromAxisAngle(this.rotationAxis,this.rotationAngle)).normalize()):(this.rotationAxis.applyQuaternion(this._parentQuaternionInv),s.quaternion.copy($i.setFromAxisAngle(this.rotationAxis,this.rotationAngle)),s.quaternion.multiply(this._quaternionStart).normalize())}this.dispatchEvent(eC),this.dispatchEvent(HD)}}pointerUp(e){e.button===0&&(this.dragging&&this.axis!==null&&(GD.mode=this.mode,this.dispatchEvent(GD)),this.dragging=!1,this.axis=null)}dispose(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerHover),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.traverse(function(e){e.geometry&&e.geometry.dispose(),e.material&&e.material.dispose()})}attach(e){return this.object=e,this.visible=!0,this}detach(){return this.object=void 0,this.visible=!1,this.axis=null,this}reset(){this.enabled&&this.dragging&&(this.object.position.copy(this._positionStart),this.object.quaternion.copy(this._quaternionStart),this.object.scale.copy(this._scaleStart),this.dispatchEvent(eC),this.dispatchEvent(HD),this.pointStart.copy(this.pointEnd))}getRaycaster(){return _u}getMode(){return this.mode}setMode(e){this.mode=e}setTranslationSnap(e){this.translationSnap=e}setRotationSnap(e){this.rotationSnap=e}setScaleSnap(e){this.scaleSnap=e}setSize(e){this.size=e}setSpace(e){this.space=e}}function J6(n){if(this.domElement.ownerDocument.pointerLockElement)return{x:0,y:0,button:n.button};{const e=this.domElement.getBoundingClientRect();return{x:(n.clientX-e.left)/e.width*2-1,y:-(n.clientY-e.top)/e.height*2+1,button:n.button}}}function K6(n){if(this.enabled)switch(n.pointerType){case"mouse":case"pen":this.pointerHover(this._getPointer(n));break}}function Z6(n){this.enabled&&(document.pointerLockElement||this.domElement.setPointerCapture(n.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.pointerHover(this._getPointer(n)),this.pointerDown(this._getPointer(n)))}function $6(n){this.enabled&&this.pointerMove(this._getPointer(n))}function eq(n){this.enabled&&(this.domElement.releasePointerCapture(n.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.pointerUp(this._getPointer(n)))}function tC(n,e,t){const i=e.intersectObject(n,!0);for(let s=0;s<i.length;s++)if(i[s].object.visible||t)return i[s];return!1}const A0=new ks,Ui=new w(0,1,0),VD=new w(0,0,0),QD=new Se,y0=new Ee,y_=new Ee,Ha=new w,jD=new Se,pg=new w(1,0,0),Lu=new w(0,1,0),mg=new w(0,0,1),_0=new w,Um=new w,Nm=new w;class uI extends ge{constructor(){super(),this.isTransformControlsGizmo=!0,this.type="TransformControlsGizmo";const e=new ci({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),t=new kn({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),i=e.clone();i.opacity=.15;const s=t.clone();s.opacity=.5;const r=e.clone();r.color.setHex(16711680);const o=e.clone();o.color.setHex(65280);const a=e.clone();a.color.setHex(255);const c=e.clone();c.color.setHex(16711680),c.opacity=.5;const l=e.clone();l.color.setHex(65280),l.opacity=.5;const h=e.clone();h.color.setHex(255),h.opacity=.5;const d=e.clone();d.opacity=.25;const f=e.clone();f.color.setHex(16776960),f.opacity=.25,e.clone().color.setHex(16776960);const m=e.clone();m.color.setHex(7895160);const g=new Rn(0,.04,.1,12);g.translate(0,.05,0);const y=new Vi(.08,.08,.08);y.translate(0,.04,0);const v=new _t;v.setAttribute("position",new ut([0,0,0,1,0,0],3));const A=new Rn(.0075,.0075,.5,3);A.translate(0,.25,0);function _(H,O){const U=new rl(H,.0075,3,64,O*Math.PI*2);return U.rotateY(Math.PI/2),U.rotateX(Math.PI/2),U}function b(){const H=new _t;return H.setAttribute("position",new ut([0,0,0,1,1,1],3)),H}const C={X:[[new me(g,r),[.5,0,0],[0,0,-Math.PI/2]],[new me(g,r),[-.5,0,0],[0,0,Math.PI/2]],[new me(A,r),[0,0,0],[0,0,-Math.PI/2]]],Y:[[new me(g,o),[0,.5,0]],[new me(g,o),[0,-.5,0],[Math.PI,0,0]],[new me(A,o)]],Z:[[new me(g,a),[0,0,.5],[Math.PI/2,0,0]],[new me(g,a),[0,0,-.5],[-Math.PI/2,0,0]],[new me(A,a),null,[Math.PI/2,0,0]]],XYZ:[[new me(new ul(.1,0),d.clone()),[0,0,0]]],XY:[[new me(new Vi(.15,.15,.01),h.clone()),[.15,.15,0]]],YZ:[[new me(new Vi(.15,.15,.01),c.clone()),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new me(new Vi(.15,.15,.01),l.clone()),[.15,0,.15],[-Math.PI/2,0,0]]]},E={X:[[new me(new Rn(.2,0,.6,4),i),[.3,0,0],[0,0,-Math.PI/2]],[new me(new Rn(.2,0,.6,4),i),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new me(new Rn(.2,0,.6,4),i),[0,.3,0]],[new me(new Rn(.2,0,.6,4),i),[0,-.3,0],[0,0,Math.PI]]],Z:[[new me(new Rn(.2,0,.6,4),i),[0,0,.3],[Math.PI/2,0,0]],[new me(new Rn(.2,0,.6,4),i),[0,0,-.3],[-Math.PI/2,0,0]]],XYZ:[[new me(new ul(.2,0),i)]],XY:[[new me(new Vi(.2,.2,.01),i),[.15,.15,0]]],YZ:[[new me(new Vi(.2,.2,.01),i),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new me(new Vi(.2,.2,.01),i),[.15,0,.15],[-Math.PI/2,0,0]]]},T={START:[[new me(new ul(.01,2),s),null,null,null,"helper"]],END:[[new me(new ul(.01,2),s),null,null,null,"helper"]],DELTA:[[new Bn(b(),s),null,null,null,"helper"]],X:[[new Bn(v,s.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new Bn(v,s.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new Bn(v,s.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},I={XYZE:[[new me(_(.5,1),m),null,[0,Math.PI/2,0]]],X:[[new me(_(.5,.5),r)]],Y:[[new me(_(.5,.5),o),null,[0,0,-Math.PI/2]]],Z:[[new me(_(.5,.5),a),null,[0,Math.PI/2,0]]],E:[[new me(_(.75,1),f),null,[0,Math.PI/2,0]]]},S={AXIS:[[new Bn(v,s.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]]},M={XYZE:[[new me(new Da(.25,10,8),i)]],X:[[new me(new rl(.5,.1,4,24),i),[0,0,0],[0,-Math.PI/2,-Math.PI/2]]],Y:[[new me(new rl(.5,.1,4,24),i),[0,0,0],[Math.PI/2,0,0]]],Z:[[new me(new rl(.5,.1,4,24),i),[0,0,0],[0,0,-Math.PI/2]]],E:[[new me(new rl(.75,.1,2,24),i)]]},D={X:[[new me(y,r),[.5,0,0],[0,0,-Math.PI/2]],[new me(A,r),[0,0,0],[0,0,-Math.PI/2]],[new me(y,r),[-.5,0,0],[0,0,Math.PI/2]]],Y:[[new me(y,o),[0,.5,0]],[new me(A,o)],[new me(y,o),[0,-.5,0],[0,0,Math.PI]]],Z:[[new me(y,a),[0,0,.5],[Math.PI/2,0,0]],[new me(A,a),[0,0,0],[Math.PI/2,0,0]],[new me(y,a),[0,0,-.5],[-Math.PI/2,0,0]]],XY:[[new me(new Vi(.15,.15,.01),h),[.15,.15,0]]],YZ:[[new me(new Vi(.15,.15,.01),c),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new me(new Vi(.15,.15,.01),l),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new me(new Vi(.1,.1,.1),d.clone())]]},G={X:[[new me(new Rn(.2,0,.6,4),i),[.3,0,0],[0,0,-Math.PI/2]],[new me(new Rn(.2,0,.6,4),i),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new me(new Rn(.2,0,.6,4),i),[0,.3,0]],[new me(new Rn(.2,0,.6,4),i),[0,-.3,0],[0,0,Math.PI]]],Z:[[new me(new Rn(.2,0,.6,4),i),[0,0,.3],[Math.PI/2,0,0]],[new me(new Rn(.2,0,.6,4),i),[0,0,-.3],[-Math.PI/2,0,0]]],XY:[[new me(new Vi(.2,.2,.01),i),[.15,.15,0]]],YZ:[[new me(new Vi(.2,.2,.01),i),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new me(new Vi(.2,.2,.01),i),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new me(new Vi(.2,.2,.2),i),[0,0,0]]]},Q={X:[[new Bn(v,s.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new Bn(v,s.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new Bn(v,s.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]};function L(H){const O=new ge;for(const U in H)for(let V=H[U].length;V--;){const J=H[U][V][0].clone(),K=H[U][V][1],oe=H[U][V][2],fe=H[U][V][3],be=H[U][V][4];J.name=U,J.tag=be,K&&J.position.set(K[0],K[1],K[2]),oe&&J.rotation.set(oe[0],oe[1],oe[2]),fe&&J.scale.set(fe[0],fe[1],fe[2]),J.updateMatrix();const ke=J.geometry.clone();ke.applyMatrix4(J.matrix),J.geometry=ke,J.renderOrder=1/0,J.position.set(0,0,0),J.rotation.set(0,0,0),J.scale.set(1,1,1),O.add(J)}return O}this.gizmo={},this.picker={},this.helper={},this.add(this.gizmo.translate=L(C)),this.add(this.gizmo.rotate=L(I)),this.add(this.gizmo.scale=L(D)),this.add(this.picker.translate=L(E)),this.add(this.picker.rotate=L(M)),this.add(this.picker.scale=L(G)),this.add(this.helper.translate=L(T)),this.add(this.helper.rotate=L(S)),this.add(this.helper.scale=L(Q)),this.picker.translate.visible=!1,this.picker.rotate.visible=!1,this.picker.scale.visible=!1}updateMatrixWorld(e){const i=(this.mode==="scale"?"local":this.space)==="local"?this.worldQuaternion:y_;this.gizmo.translate.visible=this.mode==="translate",this.gizmo.rotate.visible=this.mode==="rotate",this.gizmo.scale.visible=this.mode==="scale",this.helper.translate.visible=this.mode==="translate",this.helper.rotate.visible=this.mode==="rotate",this.helper.scale.visible=this.mode==="scale";let s=[];s=s.concat(this.picker[this.mode].children),s=s.concat(this.gizmo[this.mode].children),s=s.concat(this.helper[this.mode].children);for(let r=0;r<s.length;r++){const o=s[r];o.visible=!0,o.rotation.set(0,0,0),o.position.copy(this.worldPosition);let a;if(this.camera.isOrthographicCamera?a=(this.camera.top-this.camera.bottom)/this.camera.zoom:a=this.worldPosition.distanceTo(this.cameraPosition)*Math.min(1.9*Math.tan(Math.PI*this.camera.fov/360)/this.camera.zoom,7),o.scale.set(1,1,1).multiplyScalar(a*this.size/4),o.tag==="helper"){o.visible=!1,o.name==="AXIS"?(o.visible=!!this.axis,this.axis==="X"&&($i.setFromEuler(A0.set(0,0,0)),o.quaternion.copy(i).multiply($i),Math.abs(Ui.copy(pg).applyQuaternion(i).dot(this.eye))>.9&&(o.visible=!1)),this.axis==="Y"&&($i.setFromEuler(A0.set(0,0,Math.PI/2)),o.quaternion.copy(i).multiply($i),Math.abs(Ui.copy(Lu).applyQuaternion(i).dot(this.eye))>.9&&(o.visible=!1)),this.axis==="Z"&&($i.setFromEuler(A0.set(0,Math.PI/2,0)),o.quaternion.copy(i).multiply($i),Math.abs(Ui.copy(mg).applyQuaternion(i).dot(this.eye))>.9&&(o.visible=!1)),this.axis==="XYZE"&&($i.setFromEuler(A0.set(0,Math.PI/2,0)),Ui.copy(this.rotationAxis),o.quaternion.setFromRotationMatrix(QD.lookAt(VD,Ui,Lu)),o.quaternion.multiply($i),o.visible=this.dragging),this.axis==="E"&&(o.visible=!1)):o.name==="START"?(o.position.copy(this.worldPositionStart),o.visible=this.dragging):o.name==="END"?(o.position.copy(this.worldPosition),o.visible=this.dragging):o.name==="DELTA"?(o.position.copy(this.worldPositionStart),o.quaternion.copy(this.worldQuaternionStart),tr.set(1e-10,1e-10,1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1),tr.applyQuaternion(this.worldQuaternionStart.clone().invert()),o.scale.copy(tr),o.visible=this.dragging):(o.quaternion.copy(i),this.dragging?o.position.copy(this.worldPositionStart):o.position.copy(this.worldPosition),this.axis&&(o.visible=this.axis.search(o.name)!==-1));continue}o.quaternion.copy(i),this.mode==="translate"||this.mode==="scale"?(o.name==="X"&&Math.abs(Ui.copy(pg).applyQuaternion(i).dot(this.eye))>.99&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="Y"&&Math.abs(Ui.copy(Lu).applyQuaternion(i).dot(this.eye))>.99&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="Z"&&Math.abs(Ui.copy(mg).applyQuaternion(i).dot(this.eye))>.99&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="XY"&&Math.abs(Ui.copy(mg).applyQuaternion(i).dot(this.eye))<.2&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="YZ"&&Math.abs(Ui.copy(pg).applyQuaternion(i).dot(this.eye))<.2&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="XZ"&&Math.abs(Ui.copy(Lu).applyQuaternion(i).dot(this.eye))<.2&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1)):this.mode==="rotate"&&(y0.copy(i),Ui.copy(this.eye).applyQuaternion($i.copy(i).invert()),o.name.search("E")!==-1&&o.quaternion.setFromRotationMatrix(QD.lookAt(this.eye,VD,Lu)),o.name==="X"&&($i.setFromAxisAngle(pg,Math.atan2(-Ui.y,Ui.z)),$i.multiplyQuaternions(y0,$i),o.quaternion.copy($i)),o.name==="Y"&&($i.setFromAxisAngle(Lu,Math.atan2(Ui.x,Ui.z)),$i.multiplyQuaternions(y0,$i),o.quaternion.copy($i)),o.name==="Z"&&($i.setFromAxisAngle(mg,Math.atan2(Ui.y,Ui.x)),$i.multiplyQuaternions(y0,$i),o.quaternion.copy($i))),o.visible=o.visible&&(o.name.indexOf("X")===-1||this.showX),o.visible=o.visible&&(o.name.indexOf("Y")===-1||this.showY),o.visible=o.visible&&(o.name.indexOf("Z")===-1||this.showZ),o.visible=o.visible&&(o.name.indexOf("E")===-1||this.showX&&this.showY&&this.showZ),o.material._color=o.material._color||o.material.color.clone(),o.material._opacity=o.material._opacity||o.material.opacity,o.material.color.copy(o.material._color),o.material.opacity=o.material._opacity,this.enabled&&this.axis&&(o.name===this.axis||this.axis.split("").some(function(c){return o.name===c}))&&(o.material.color.setHex(16776960),o.material.opacity=1)}super.updateMatrixWorld(e)}}class tq extends me{constructor(){super(new rs(1e5,1e5,2,2),new ci({visible:!1,wireframe:!0,side:_i,transparent:!0,opacity:.1,toneMapped:!1})),this.isTransformControlsPlane=!0,this.type="TransformControlsPlane"}updateMatrixWorld(e){let t=this.space;switch(this.position.copy(this.worldPosition),this.mode==="scale"&&(t="local"),_0.copy(pg).applyQuaternion(t==="local"?this.worldQuaternion:y_),Um.copy(Lu).applyQuaternion(t==="local"?this.worldQuaternion:y_),Nm.copy(mg).applyQuaternion(t==="local"?this.worldQuaternion:y_),Ui.copy(Um),this.mode){case"translate":case"scale":switch(this.axis){case"X":Ui.copy(this.eye).cross(_0),Ha.copy(_0).cross(Ui);break;case"Y":Ui.copy(this.eye).cross(Um),Ha.copy(Um).cross(Ui);break;case"Z":Ui.copy(this.eye).cross(Nm),Ha.copy(Nm).cross(Ui);break;case"XY":Ha.copy(Nm);break;case"YZ":Ha.copy(_0);break;case"XZ":Ui.copy(Nm),Ha.copy(Um);break;case"XYZ":case"E":Ha.set(0,0,0);break}break;case"rotate":default:Ha.set(0,0,0)}Ha.length()===0?this.quaternion.copy(this.cameraQuaternion):(jD.lookAt(tr.set(0,0,0),Ha,Ui),this.quaternion.setFromRotationMatrix(jD)),super.updateMatrixWorld(e)}}const iq=se("debugpatch");function Hx(n,e,t,i){const s=iq===e;if(!t&&!i)return;const r=e+"___needle";sq(n,e,t,i);const o=Object.getOwnPropertyDescriptor(n,e),a=n[e];s&&console.log("Patch",n.constructor.name,e,o,a),o?(s&&console.log("Apply patch with existing descriptor",n.constructor.name,e,o),typeof o.value=="function"&&(n[e]=qD(o.value,n,e))):(s&&console.log("Create patch with new property",n.constructor.name,e,o),Object.defineProperty(n,e,{set:function(c){if(typeof c=="function")this[r]=qD(c,n,e);else{const l=this[r];tN(n,e,this,l,c),this[r]=c,iN(n,e,this,l,c)}},get:function(){const c=this[r];return typeof c=="function"&&c[r]?c[r]:c}}))}function nq(n,e,t){const i=dI(n,e);if(i)for(let s=i.length-1;s>=0;s--){const r=i[s];r.prefix===t&&(r.prefix=null),r.postfix===t&&(r.postfix=null),!r.prefix&&!r.postfix&&i.splice(s,1)}}const WD=Symbol("Needle:Patches:WrappedFunction");function qD(n,e,t){if(n[WD])return n;const i=function(...s){tN(e,t,this,...s);const r=n.apply(this,s);return iN(e,t,this,r,...s),r};return i[WD]=!0,i}const __="Needle:Patches";function D1(){return globalThis[__]||(globalThis[__]=new WeakMap),globalThis[__]}function dI(n,e){const t=D1().get(n);return t?t.get(e):null}function sq(n,e,t,i){let s=D1().get(n);s||(s=new Map,D1().set(n,s));let r=s.get(e);r||(r=[],s.set(e,r)),r.push({prefix:t,postfix:i})}function tN(n,e,t,...i){var r;if(!t)return;const s=dI(n,e);if(s)for(const o of s)(r=o.prefix)==null||r.call(t,...i)}function iN(n,e,t,i,...s){var o;if(!t)return;const r=dI(n,e);if(r)for(const a of r)(o=a.postfix)==null||o.call(t,i,...s)}const XD=Symbol("gltf-loader-internal-usage-tracker"),rq=se("debugusers"),tv=class{constructor(e){u(this,"parser");u(this,"_getDependency");u(this,"_loadingId");u(this,"_loadedObjects",new Set);this.parser=e,this._getDependency=this.parser.getDependency,this._loadingId=Date.now().toString()}get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(e){return tv._loadingProcesses>0}beforeRoot(){tv._loadingProcesses++;const e=this,t=this._getDependency;return this.parser.getDependency=function(i,s){const r=t.call(this,i,s);return r.then(o=>(o&&(e._loadedObjects.add(o),o[XD]=e._loadingId),o)),r},null}afterRoot(e){tv._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[XD],t instanceof ge&&(t.parent||t instanceof me&&(rq&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null));return null}};let kg=tv;u(kg,"_loadingProcesses",0);class nN{constructor(){window.addEventListener("unhandledrejection",e=>{var i;if(e.defaultPrevented)return;const t=(i=e==null?void 0:e.reason)==null?void 0:i.path;if(t){const s=t[0];s&&s.tagName==="IMG"&&(console.warn(`Could not load image:
3947
- `+s.src),e.preventDefault())}})}}const Vx=se("trackresources");function sN(){return Vx==="dispose"}let Ed=!0;Vx===0&&(Ed=!1);function oq(n){Ed=n}function rN(){return Ed}const oN=Symbol("disposable");function fI(n,e){n&&(n[oN]=e,sd&&console.warn("Set disposable",e,n))}const aN=Symbol("disposed");function aq(n){return n[aN]===!0}function Gi(n){var e;if(n){if(n[oN]===!1){sd&&console.warn("Object is marked as not disposable",n);return}if(n[aN]=!0,n instanceof rr)Gi(n.environment),Gi(n.background),Gi(n.customDepthMaterial),Gi(n.customDistanceMaterial);else if(n instanceof Ea)Gi(n.geometry),Gi(n.material),Gi(n.skeleton),Gi(n.bindMatrix),Gi(n.bindMatrixInverse),Gi(n.customDepthMaterial),Gi(n.customDistanceMaterial),n.geometry=null,n.material=null;else if(n instanceof me)Gi(n.geometry),Gi(n.material),Gi(n.customDepthMaterial),Gi(n.customDistanceMaterial),n.geometry=null,n.material=null;else if(n instanceof _t){xf(n);for(const t of Object.keys(n.attributes)){const i=n.attributes[t];Gi(i)}}else if(n instanceof tt||n instanceof wr)sd&&console.warn("BufferAttribute dispose not supported",n.count);else if(n instanceof Array)for(const t of n)t instanceof Gt&&Gi(t);else if(n instanceof Gt){xf(n);for(const i of Object.keys(n)){const s=n[i];s instanceof Ht&&(Gi(s),n[i]=null)}const t=n.uniforms;if(t)for(const i of Object.keys(t)){const s=t[i];s instanceof Ht?(Gi(s),t[i]=null):s instanceof we&&(Gi(s.value),s.value=null)}}else n instanceof Ht?(xf(n),xf(n.source),((e=n.source)==null?void 0:e.data)instanceof ImageBitmap&&xf(n.source.data)):n instanceof Hp?(xf(n.boneTexture),n.boneTexture=null):n instanceof cA||!(n instanceof ge)&&sd&&console.warn("Unknown object type",n)}}function xf(n){n&&((sd||sN()||Vx)&&console.warn("๐Ÿงจ FREE",n),n instanceof ImageBitmap?n.close():n instanceof hl?n.data=null:n.dispose())}function cN(n){(n instanceof me||n instanceof Ea)&&(n.material=null,n.geometry=null)}const cq=new Set;function pI(n,e,t=null,i){if(i||(i=cq,i.clear()),!n)return i;const s=n[wv];if(s)for(const r of s)i.has(r)||(t==null?void 0:t.call(null,r))!==!1&&(i.add(r),e&&pI(r,!0,t,i));return i}function lq(n){return n[gg]}const sd=se("debugresourceusers")||se("debugmemory"),wv=Symbol("needle-resource-users"),gg=Symbol("needle-resource-users-count");function ur(n,e){Hx(n,e,function(t,i){Ed&&(mb(wv,this,t,!1),mb(wv,this,i,!0))})}Ed&&(ur(me.prototype,"material"),ur(me.prototype,"geometry"),ur(Gt.prototype,"map"),ur(Gt.prototype,"bumpMap"),ur(Gt.prototype,"alphaMap"),ur(Gt.prototype,"normalMap"),ur(Gt.prototype,"displacementMap"),ur(Gt.prototype,"roughnessMap"),ur(Gt.prototype,"metalnessMap"),ur(Gt.prototype,"emissiveMap"),ur(Gt.prototype,"specularMap"),ur(Gt.prototype,"envMap"),ur(Gt.prototype,"lightMap"),ur(Gt.prototype,"aoMap"),ur(Gt.prototype,"gradientMap"));function hq(n){if(Ed===!1)return;const e=n[wv];if(e)for(const t of e)mb(wv,t,n,!1)}Ed&&Hx(Gt.prototype,"dispose",function(){hq(this)});let O1=0;function mb(n,e,t,i){if(O1>0)return;if(Array.isArray(t)){for(const r of t)mb(n,e,r,i);return}if(!t)return;let s=t[n];if(s||(s=new Set),i){if(e&&!s.has(e)){s.add(e);let r=t[gg]||0;r+=1,t[gg]=r,sd&&console.warn(`๐ŸŸข Added user of "${t.type}"`,e,t,r,"users:",s)}}else if(e&&s.has(e)){s.delete(e);let r=t[gg]||0;r>0&&(r-=1,t[gg]=r),sd&&console.warn(`๐Ÿ”ด Removed user of "${t.type}"`,e,t,r,"users:",s),r<=0&&(kg.isLoading(t)||(Vx&&console.warn(`๐Ÿ”ด Removed all user of "${t.type}"`,t),sN()&&Gi(t)))}t[n]=s}try{Hx(Bl.prototype,"render",function(){O1++},function(){O1--})}catch(n){console.warn("Could not wrap WebGLRenderer.render",n)}var pA=(n=>(n.Added="component-added",n.Removing="removing-component",n))(pA||{});const YD=se("debugcomponentevents");class mA{static addComponentLifecylceEventListener(e,t){this.eventListeners.has(e)&&this.eventListeners.set(e,[]);let i=this.eventListeners.get(e);i||(i=[]),i.push(t),this.eventListeners.set(e,i),YD&&console.log("Added event listener for "+e,this.eventListeners)}static removeComponentLifecylceEventListener(e,t){const i=this.eventListeners.get(e);if(!i)return;const s=i.indexOf(t);s<0||i.splice(s,1)}static dispatchComponentLifecycleEvent(e,t){const i=this.eventListeners.get(e);if(YD&&console.log("Dispatching event "+e,i),!!i)for(const s of i)s(t)}}u(mA,"eventListeners",new Map);const lN=se("debugdefines");Wp('if(!globalThis[""3.32.18-alpha""]) globalThis[""3.32.18-alpha""] = "0.0.0";');Wp('if(!globalThis[""undefined""]) globalThis[""undefined""] = "unknown";');Wp('if(!globalThis[""Fri Feb 09 2024 20:32:00 GMT+0800 (Pacific Standard Time)""]) globalThis[""Fri Feb 09 2024 20:32:00 GMT+0800 (Pacific Standard Time)""] = "unknown";');Wp('globalThis["__NEEDLE_ENGINE_VERSION__"] = "3.32.18-alpha";');Wp('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');Wp('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Fri Feb 09 2024 20:32:00 GMT+0800 (Pacific Standard Time)";');const fc="3.32.18-alpha",Qx="undefined",uq="Fri Feb 09 2024 20:32:00 GMT+0800 (Pacific Standard Time)";lN&&console.log(`Engine version: ${fc} (generator: ${Qx})
3947
+ `+s.src),e.preventDefault())}})}}const Vx=se("trackresources");function sN(){return Vx==="dispose"}let Ed=!0;Vx===0&&(Ed=!1);function oq(n){Ed=n}function rN(){return Ed}const oN=Symbol("disposable");function fI(n,e){n&&(n[oN]=e,sd&&console.warn("Set disposable",e,n))}const aN=Symbol("disposed");function aq(n){return n[aN]===!0}function Gi(n){var e;if(n){if(n[oN]===!1){sd&&console.warn("Object is marked as not disposable",n);return}if(n[aN]=!0,n instanceof rr)Gi(n.environment),Gi(n.background),Gi(n.customDepthMaterial),Gi(n.customDistanceMaterial);else if(n instanceof Ea)Gi(n.geometry),Gi(n.material),Gi(n.skeleton),Gi(n.bindMatrix),Gi(n.bindMatrixInverse),Gi(n.customDepthMaterial),Gi(n.customDistanceMaterial),n.geometry=null,n.material=null;else if(n instanceof me)Gi(n.geometry),Gi(n.material),Gi(n.customDepthMaterial),Gi(n.customDistanceMaterial),n.geometry=null,n.material=null;else if(n instanceof _t){xf(n);for(const t of Object.keys(n.attributes)){const i=n.attributes[t];Gi(i)}}else if(n instanceof tt||n instanceof wr)sd&&console.warn("BufferAttribute dispose not supported",n.count);else if(n instanceof Array)for(const t of n)t instanceof Gt&&Gi(t);else if(n instanceof Gt){xf(n);for(const i of Object.keys(n)){const s=n[i];s instanceof Ht&&(Gi(s),n[i]=null)}const t=n.uniforms;if(t)for(const i of Object.keys(t)){const s=t[i];s instanceof Ht?(Gi(s),t[i]=null):s instanceof we&&(Gi(s.value),s.value=null)}}else n instanceof Ht?(xf(n),xf(n.source),((e=n.source)==null?void 0:e.data)instanceof ImageBitmap&&xf(n.source.data)):n instanceof Hp?(xf(n.boneTexture),n.boneTexture=null):n instanceof cA||!(n instanceof ge)&&sd&&console.warn("Unknown object type",n)}}function xf(n){n&&((sd||sN()||Vx)&&console.warn("๐Ÿงจ FREE",n),n instanceof ImageBitmap?n.close():n instanceof hl?n.data=null:n.dispose())}function cN(n){(n instanceof me||n instanceof Ea)&&(n.material=null,n.geometry=null)}const cq=new Set;function pI(n,e,t=null,i){if(i||(i=cq,i.clear()),!n)return i;const s=n[wv];if(s)for(const r of s)i.has(r)||(t==null?void 0:t.call(null,r))!==!1&&(i.add(r),e&&pI(r,!0,t,i));return i}function lq(n){return n[gg]}const sd=se("debugresourceusers")||se("debugmemory"),wv=Symbol("needle-resource-users"),gg=Symbol("needle-resource-users-count");function ur(n,e){Hx(n,e,function(t,i){Ed&&(mb(wv,this,t,!1),mb(wv,this,i,!0))})}Ed&&(ur(me.prototype,"material"),ur(me.prototype,"geometry"),ur(Gt.prototype,"map"),ur(Gt.prototype,"bumpMap"),ur(Gt.prototype,"alphaMap"),ur(Gt.prototype,"normalMap"),ur(Gt.prototype,"displacementMap"),ur(Gt.prototype,"roughnessMap"),ur(Gt.prototype,"metalnessMap"),ur(Gt.prototype,"emissiveMap"),ur(Gt.prototype,"specularMap"),ur(Gt.prototype,"envMap"),ur(Gt.prototype,"lightMap"),ur(Gt.prototype,"aoMap"),ur(Gt.prototype,"gradientMap"));function hq(n){if(Ed===!1)return;const e=n[wv];if(e)for(const t of e)mb(wv,t,n,!1)}Ed&&Hx(Gt.prototype,"dispose",function(){hq(this)});let O1=0;function mb(n,e,t,i){if(O1>0)return;if(Array.isArray(t)){for(const r of t)mb(n,e,r,i);return}if(!t)return;let s=t[n];if(s||(s=new Set),i){if(e&&!s.has(e)){s.add(e);let r=t[gg]||0;r+=1,t[gg]=r,sd&&console.warn(`๐ŸŸข Added user of "${t.type}"`,e,t,r,"users:",s)}}else if(e&&s.has(e)){s.delete(e);let r=t[gg]||0;r>0&&(r-=1,t[gg]=r),sd&&console.warn(`๐Ÿ”ด Removed user of "${t.type}"`,e,t,r,"users:",s),r<=0&&(kg.isLoading(t)||(Vx&&console.warn(`๐Ÿ”ด Removed all user of "${t.type}"`,t),sN()&&Gi(t)))}t[n]=s}try{Hx(Bl.prototype,"render",function(){O1++},function(){O1--})}catch(n){console.warn("Could not wrap WebGLRenderer.render",n)}var pA=(n=>(n.Added="component-added",n.Removing="removing-component",n))(pA||{});const YD=se("debugcomponentevents");class mA{static addComponentLifecylceEventListener(e,t){this.eventListeners.has(e)&&this.eventListeners.set(e,[]);let i=this.eventListeners.get(e);i||(i=[]),i.push(t),this.eventListeners.set(e,i),YD&&console.log("Added event listener for "+e,this.eventListeners)}static removeComponentLifecylceEventListener(e,t){const i=this.eventListeners.get(e);if(!i)return;const s=i.indexOf(t);s<0||i.splice(s,1)}static dispatchComponentLifecycleEvent(e,t){const i=this.eventListeners.get(e);if(YD&&console.log("Dispatching event "+e,i),!!i)for(const s of i)s(t)}}u(mA,"eventListeners",new Map);const lN=se("debugdefines");Wp('if(!globalThis[""3.32.19-alpha""]) globalThis[""3.32.19-alpha""] = "0.0.0";');Wp('if(!globalThis[""undefined""]) globalThis[""undefined""] = "unknown";');Wp('if(!globalThis[""Fri Feb 09 2024 21:56:39 GMT+0800 (Pacific Standard Time)""]) globalThis[""Fri Feb 09 2024 21:56:39 GMT+0800 (Pacific Standard Time)""] = "unknown";');Wp('globalThis["__NEEDLE_ENGINE_VERSION__"] = "3.32.19-alpha";');Wp('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');Wp('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Fri Feb 09 2024 21:56:39 GMT+0800 (Pacific Standard Time)";');const fc="3.32.19-alpha",Qx="undefined",uq="Fri Feb 09 2024 21:56:39 GMT+0800 (Pacific Standard Time)";lN&&console.log(`Engine version: ${fc} (generator: ${Qx})
3948
3948
  Project built at ${uq}`);const _l="needle_isActiveInHierarchy",Nu="builtin_components",Lg="needle_editor_guid";function Wp(n){try{(0,eval)(n)}catch(e){lN&&console.error(e)}}const Sv=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),hN=Symbol("isUsingInstancing"),uN=Symbol("instancingRenderer"),k1=Symbol("instancingAutoUpdateBounds");class Ma{static isUsingInstancing(e){return e[hN]===!0}static getRenderer(e){return e[uN]||null}setAutoUpdateBounds(e,t){const i=Ma.getRenderer(e);i&&(i[k1]=t)}static markDirty(e,t=!0){if(e&&(this.isUsingInstancing(e)&&(e[Sv]=!0,e.matrixWorldNeedsUpdate=!0),t))for(const i of e.children)Ma.markDirty(i,!0)}}function rd(n,e){try{e?n(e):n()}catch(t){return console.error(t),!1}return!0}const L1=se("debugnewscripts"),dq=se("debughierarchy"),Ki=[];function fq(){return Ki.length>0}function gb(n){if(!(n.new_scripts.length<=0)){if(L1&&console.log("Register new components",n.new_scripts.length,[...n.new_scripts],n.alias?"element: "+n.alias:n.hash,n),n.new_scripts_pre_setup_callbacks.length>0){for(const e of n.new_scripts_pre_setup_callbacks)e&&e();n.new_scripts_pre_setup_callbacks.length=0}Ki.length=0,n.new_scripts.length>0&&Ki.push(...n.new_scripts),n.new_scripts.length=0;for(let e=0;e<Ki.length;e++)try{const t=Ki[e];if(t.isComponent!==!0){(Mt()||L1)&&console.error(`Registered script is not a Needle Engine component.
3949
3949
  The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
3950
3950
  `,t),Ki.splice(e,1),e--;continue}if(t.destroyed)continue;if(!t.gameObject){console.error("MISSING GAMEOBJECT - will ignore",t),Ki.splice(e,1),e--;continue}t.context=n,Fg(t.gameObject),mI(t,n)}catch(t){console.error(t),ol(Ki[e],n),Ki.splice(e,1),e--}for(let e=0;e<Ki.length;e++)try{const t=Ki[e];if(t.destroyed){ol(Ki[e],n),Ki.splice(e,1),e--;continue}if(t.registering)try{t.registering()}catch(i){console.error(i)}t.__internalAwake!==void 0&&(t.gameObject||console.error("MISSING GAMEOBJECT",t,t.gameObject),Fg(t.gameObject),t.activeAndEnabled&&rd(t.__internalAwake.bind(t)))}catch(t){console.error(t),ol(Ki[e],n),Ki.splice(e,1),e--}for(let e=0;e<Ki.length;e++)try{const t=Ki[e];if(t.destroyed||t.enabled===!1||(Fg(t.gameObject),t.activeAndEnabled===!1))continue;t.__internalEnable!==void 0&&(t.enabled=!0,rd(t.__internalEnable.bind(t)))}catch(t){console.error(t),ol(Ki[e],n),Ki.splice(e,1),e--}for(let e=0;e<Ki.length;e++)try{const t=Ki[e];if(t.destroyed||!t.gameObject)continue;n.new_script_start.push(t)}catch(t){console.error(t),ol(Ki[e],n),Ki.splice(e,1),e--}Ki.length=0;for(const e of n.new_scripts_post_setup_callbacks)e&&e();n.new_scripts_post_setup_callbacks.length=0}}function pq(n){n&&(n.__internalDisable(!0),ol(n,n.context))}function dN(n,e){for(let t=0;t<n.new_script_start.length;t++)try{const i=n.new_script_start[t];if(e!==void 0&&i.gameObject!==e||i.destroyed||i.activeAndEnabled===!1)continue;rd(i.__internalAwake.bind(i)),i.enabled&&(rd(i.__internalEnable.bind(i)),rd(i.__internalStart.bind(i)),n.new_script_start.splice(t,1),t--)}catch(i){console.error(i),ol(n.new_script_start[t],n),n.new_script_start.splice(t,1),t--}}function mI(n,e){e.scripts.indexOf(n)===-1&&(e.scripts.push(n),n.earlyUpdate&&e.scripts_earlyUpdate.push(n),n.update&&e.scripts_update.push(n),n.lateUpdate&&e.scripts_lateUpdate.push(n),n.onBeforeRender&&e.scripts_onBeforeRender.push(n),n.onAfterRender&&e.scripts_onAfterRender.push(n),n.onPausedChanged&&e.scripts_pausedChanged.push(n),iC(n,null)&&e.new_scripts_xr.push(n),iC(n,"immersive-vr")&&e.scripts_immersive_vr.push(n),iC(n,"immersive-ar")&&e.scripts_immersive_ar.push(n))}function ol(n,e){Po(n,e.new_scripts),Po(n,e.new_script_start),Po(n,e.scripts),Po(n,e.scripts_earlyUpdate),Po(n,e.scripts_update),Po(n,e.scripts_lateUpdate),Po(n,e.scripts_onBeforeRender),Po(n,e.scripts_onAfterRender),Po(n,e.scripts_pausedChanged),Po(n,e.new_scripts_xr),Po(n,e.scripts_immersive_vr),Po(n,e.scripts_immersive_ar),e.stopAllCoroutinesFrom(n)}function Po(n,e){const t=e.indexOf(n);t>=0&&e.splice(t,1)}function iC(n,e){var t;if(n){const i=n;if(i.onBeforeXR||i.onEnterXR||i.onUpdateXR||i.onLeaveXR||i.onXRControllerAdded||i.onXRControllerRemoved)return!(e!=null&&((t=i.supportsXR)==null?void 0:t.call(i,e))===!1)}return!1}function b_(n){if(n||(n=Bi.Current.scene),!n){console.trace("Invalid call - no current context.");return}const e=$p(n);fN(n,e,!0)||(L1||Mt()?console.error(`Error updating hierarchy
@@ -4988,10 +4988,12 @@ Pinch: ${(s=this.getGesture("pinch"))==null?void 0:s.value.toFixed(3)}`),i+=`
4988
4988
  `+i.uuid,.01,5,0,new Ti(1,1,1,.1))}this.emitPointerEvent(f,0,"pinch",!1,null,p)}}}}}onUpdateMove(){var i,s;let e=!1;if(this._lastPointerMovePosition.distanceTo(this.gripWorldPosition)>.02&&(e=!0),e||this._lastPointerMoveQuaternion.angleTo(this.gripWorldQuaternion)>.02&&(e=!0),e){this._didMoveLastFrame=!0,this._lastPointerMovePosition.copy(this.gripWorldPosition),this._lastPointerMoveQuaternion.copy(this.gripWorldQuaternion),sh&&It.DrawLabel(this.rayWorldPosition.add(this.object.worldForward.multiplyScalar(.1)),"move",.01);let r=this.xr.context.input.getFirstPressedButtonForPointer(this.index);r===void 0&&(r=0);const o=(s=(i=this.gamepad)==null?void 0:i.buttons[r])==null?void 0:s.value;this.emitPointerEvent("pointermove",r,"none",!1,null,o)}else this._didMoveLastFrame=!1}emitPointerEvent(e,t,i,s,r=null,o){if(!this.emitEvents){sh&&e!==tn.PointerMove&&console.warn("Pointer events are disabled for this controller",this.index,e,t);return}if(this.xr.mode==="immersive-vr"||this.xr.isPassThrough){this.pointerInit.origin=this,this.pointerInit.pointerId=this.index*10+t,this.pointerInit.pointerType=this.hand?"hand":"controller",this.pointerInit.button=t,this.pointerInit.buttonName=i,this.pointerInit.isPrimary=s,this.pointerInit.mode=this.inputSource.targetRayMode,this.pointerInit.ray=this.ray,this.pointerInit.device=this.object,this.pointerInit.pressure=o;const a=Ot.Current;Ot.Current=this.xr.context,sh&&e!=="pointermove"&&console.warn("Pointer event",e,t,i,{...this.pointerInit}),this.xr.context.input.createInputEvent(new $c(e,r,this.pointerInit)),Ot.Current=a}}}class hk{constructor(){u(this,"isDown",!1);u(this,"isUp",!1);u(this,"pressed",!1);u(this,"value",0)}}class uk{constructor(){u(this,"touched",!1);u(this,"pressed",!1);u(this,"value",0);u(this,"isDown",!1);u(this,"isUp",!1)}}const Vg=se("debugwebxr");class CC{constructor(e,t){u(this,"controllerStates",[]);u(this,"userId");u(this,"context");u(this,"userStateEvtName");u(this,"onReceivedControllerState",e=>{Vg&&console.log(`XRSync: Received change for ${this.userId}: ${e.type} ${e.handedness}; tracked=${e.isTracking}`);let t=!1;for(let i=0;i<this.controllerStates.length;i++)if(this.controllerStates[i].index===e.index){this.controllerStates[i]=e,t=!0;break}t||this.controllerStates.push(e)});this.userId=e,this.context=t,this.userStateEvtName="xr-sync-user-state-"+e,this.context.connection.beginListen(this.userStateEvtName,this.onReceivedControllerState)}dispose(){this.context.connection.stopListen(this.userStateEvtName,this.onReceivedControllerState)}update(e){if(this.context.connection.isConnected!=!1){for(let t=this.controllerStates.length-1;t>=0;t--){const i=this.controllerStates[t];let s=!1;for(let r=0;r<e.controllers.length;r++)e.controllers[r].index===i.index&&(s=!0);s||(Vg&&console.log(`XRSync: ${i.type} ${i.handedness} removed`,i.index),this.controllerStates.splice(t,1),this.sendControllerRemoved(i))}for(const t of e.controllers)this.updateControllerStates(t)}}onExitXR(e){for(const t of this.controllerStates)this.sendControllerRemoved(t);this.controllerStates.length=0}sendControllerRemoved(e){e.isTracking=!1,e.guid="",this.context.connection.send(this.userStateEvtName,e),this.context.connection.sendDeleteRemoteState(e.guid)}updateControllerStates(e){const t=this.controllerStates.find(i=>i.index===e.index);if(t){let i=!1;i||(i=t.isTracking!=e.isTracking),i&&(t.isTracking=e.isTracking,this.context.connection.send(this.userStateEvtName,t))}else{const i={guid:this.userId+"-"+e.index,isTracking:e.isTracking,handedness:e.side,index:e.index,type:e.hand?"hand":"controller"};this.controllerStates.push(i),this.context.connection.send(this.userStateEvtName,i),Vg&&console.log(`XRSync: ${i.type} ${i.handedness} added`,i.index)}}}class _G{constructor(e){u(this,"context");u(this,"onJoinedRoom",()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(Vg&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new CC(this.context.connection.connectionId,this.context)));for(const e of this.context.connection.usersInRoom())this._states.has(e)||this._states.set(e,new CC(e,this.context))}});u(this,"onLeftRoom",()=>{if(this.context.connection.connectionId&&!this._states.has(this.context.connection.connectionId)){const e=this._states.get(this.context.connection.connectionId);e==null||e.dispose(),this._states.delete(this.context.connection.connectionId)}});u(this,"onOtherUserJoinedRoom",e=>{const t=e.userId;this._states.has(t)||(Vg&&console.log("XRSync: Remote user joined room",t),this._states.set(t,new CC(t,this.context)))});u(this,"onOtherUserLeftRoom",e=>{const t=e.userId;if(!this._states.has(t)){const i=this._states.get(t);i==null||i.dispose(),this._states.delete(t)}});u(this,"_states",new Map);this.context=e,this.context.connection.beginListen(mi.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(mi.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(mi.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(mi.UserLeftRoom,this.onOtherUserLeftRoom)}hasState(e){return e?this._states.has(e):!1}isTracking(e,t){if(!e)return;const i=this._states.get(e);if(!i)return;const s=i.controllerStates.find(r=>r.handedness===t);return(s==null?void 0:s.isTracking)||!1}getDeviceType(e,t){if(!e)return;const i=this._states.get(e);if(!i)return;const s=i.controllerStates.find(r=>r.handedness===t);return(s==null?void 0:s.type)||"unknown"}destroy(){this.context.connection.stopListen(mi.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(mi.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(mi.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(mi.UserLeftRoom,this.onOtherUserLeftRoom)}onUpdate(e){if(this.context.connection.isConnected&&this.context.connection.connectionId){const t=this._states.get(this.context.connection.connectionId);t==null||t.update(e)}}onExitXR(e){if(this.context.connection.isConnected&&this.context.connection.connectionId){const t=this._states.get(this.context.connection.connectionId);t==null||t.onExitXR(e)}}}class dk{constructor(){u(this,"_fadeToColorQuad");u(this,"_fadeToColorMaterial");u(this,"_requestedFadeValue",0);u(this,"_transitionPromise",null);u(this,"_transitionResolve",null);this._fadeToColorMaterial=new ci({color:0,transparent:!0,depthTest:!1,fog:!1,side:_i}),this._fadeToColorQuad=new me(new rs(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(e,t){const i=this._fadeToColorQuad,s=this._fadeToColorMaterial;i.parent!==e&&s.opacity>0?e.add(i):s.opacity===0&&i.removeFromParent(),i.layers.set(2),i.material=this._fadeToColorMaterial,i.position.z=-1,i.renderOrder=1/0;const r=this._requestedFadeValue;s.opacity=rt.lerp(s.opacity,r,t/.03),Math.abs(s.opacity-r)<=.01&&this._transitionResolve&&(this._transitionResolve(),this._transitionResolve=null,this._transitionPromise=null,this._requestedFadeValue=0)}remove(){this._fadeToColorQuad.removeFromParent()}fadeTransition(){if(this._transitionPromise)return this._transitionPromise;this._requestedFadeValue=1;const e=new Promise(t=>{this._transitionResolve=t});return this._transitionPromise=e,e}}var _d=(n=>(n[n.Quad=0]="Quad",n[n.Cube=1]="Cube",n[n.Sphere=2]="Sphere",n))(_d||{});class Dp{static createPrimitive(e,t){let i;switch(e){case 0:const r=new rs(1,1,1,1),o=(t==null?void 0:t.material)??new qr({color:16777215});i=new me(r,o);break;case 1:const a=new Vi(1,1,1),c=(t==null?void 0:t.material)??new qr({color:16777215});i=new me(a,c);break;case 2:const l=new Da(.5,16,16),h=(t==null?void 0:t.material)??new qr({color:16777215});i=new me(l,h);break}return t!=null&&t.name&&(i.name=t.name),t!=null&&t.position&&i.position.set(t.position.x,t.position.y,t.position.z),t!=null&&t.rotation&&i.rotation.set(t.rotation.x,t.rotation.y,t.rotation.z),t!=null&&t.scale&&i.scale.set(t.scale.x,t.scale.y,t.scale.z),i}}const WP=class{constructor(e,t,i){u(this,"_session");u(this,"_mode");u(this,"_init");u(this,"_renderer");u(this,"_camera");u(this,"_scene");u(this,"onEnd",()=>{var e;(e=this._session)==null||e.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()});u(this,"_lastTime",0);u(this,"onFrame",(e,t)=>{const i=e-this._lastTime;this.update(e,i),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera)});u(this,"_spheres",[]);this._mode=e,this._init=t,this._session=i,this._session.addEventListener("end",this.onEnd),this._renderer=new Bl({alpha:!0}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(i),this._renderer.xr.enabled=!0,this._camera=new Jt,this._scene=new rr,this._scene.add(this._camera),this.setupScene()}static get active(){return this._active}static async start(e,t){if(this._active)return console.error("Cannot start a new XR session while one is already active"),null;if(this._requestInFlight)return console.error("Cannot start a new XR session while a request is already in flight"),null;if("xr"in navigator&&navigator.xr){if(!t)return console.error("XRSessionInit must be provided"),null;this._requestInFlight=!0;const i=await navigator.xr.requestSession(e,t);return i.addEventListener("end",()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new WP(e,t,i),this._active):(i.end(),null)}return null}static async handoff(){return this._active?this._active.handoff():null}static async stop(){this._requestInFlight=!1,this._active&&(await this._active.end(),await Yo(100)),this._active=null}end(){return this._session?this._session.end():Promise.resolve()}async handoff(){if(!this._session)throw new Error("Cannot handoff a session that has already ended");const e={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,e}async onBeforeHandoff(){const e=Dp.createPrimitive(_d.Cube);e.position.z=-3,e.position.y=.5,this._scene.add(e),await Yo(4e3),this._scene.clear(),await Yo(100)}setupScene(){this._scene.background=new ye(0),this._scene.add(new Nx(5,10,1118481,2236962));const e=new Ep(16777215,1);e.position.set(2,2,2),e.castShadow=!1,this._scene.add(e);const t=new Ep(16777215,1);t.position.set(-2,-2,-2),t.castShadow=!1,this._scene.add(t);const i=50;for(let s=0;s<100;s++){const r=Dp.createPrimitive(_d.Sphere,{material:new qr({color:2236962,metalness:1,roughness:.8})});r.position.x=rt.random(-i,i),r.position.y=rt.random(3,40),r.position.z=rt.random(-i,i),r.scale.multiplyScalar(2),this._spheres.push(r),this._scene.add(r)}}update(e,t){const i=e*4e-4;for(let s=0;s<this._spheres.length;s++){const r=this._spheres[s];r.position.y+=Math.sin(i+s*.5)*.002}}};let Ku=WP;u(Ku,"_active",null),u(Ku,"_requestInFlight",!1);const Zs=se("debugwebxr"),Uee=se("stats");function Nee(n){let e=null;const t=n;return t.getAROverlayContainer?e=t.getAROverlayContainer():e=n,e}zee();function zee(){var n;if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent)){console.warn("WebXRViewer does not support addEventListener");return}(n=navigator.xr)==null||n.addEventListener("sessiongranted",()=>{console.log("Received Session Granted...");const e=sessionStorage.getItem("needle_xr_session_mode"),t=sessionStorage.getItem("needle_xr_session_init");if(e&&t){console.log("Session Granted: Restore last session");const i=JSON.parse(t);yt.start(e,i).catch(s=>console.warn(s))}else yt.start("immersive-vr").catch(i=>console.warn("Session Granted failed:",i))})}}function Gee(n,e){sessionStorage.setItem("needle_xr_session_mode",n),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(e))}function Hee(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}xv()&&Mt()&&window.addEventListener("keydown",n=>{n.key==="x"&&yt.active&&yt.stop()});if(se("simulatewebxrloading")){Bi.registerCallback(Kn.ContextCreationStart,async e=>{await Yo(3e3),setTimeout(async()=>{const t=await Ku.handoff();t?yt.setSession(t.mode,t.session,t.init,Ot.Current):yt.start("immersive-vr")},6e3)});let n=!1;window.addEventListener("click",()=>{n||(n=!0,Ku.start("immersive-vr",yt.getDefaultSessionInit("immersive-vr")))})}const gh=class{constructor(e,t,i,s){u(this,"context");u(this,"session");u(this,"mode");u(this,"controllers",[]);u(this,"_rigScale",1);u(this,"_lastRigScaleUpdate",-1);u(this,"_rigs",[]);u(this,"_viewerHitTestSource",null);u(this,"_defaultRig");u(this,"_xr_scripts");u(this,"_xr_update_scripts",[]);u(this,"_inactive_scripts",[]);u(this,"_controllerAdded");u(this,"_controllerRemoved");u(this,"_originalCameraWorldPosition");u(this,"_originalCameraWorldRotation");u(this,"_originalCameraWorldScale");u(this,"_originalCameraParent");u(this,"_mainCamera",null);u(this,"onRendererSessionSet",()=>{this.running&&(this.context.renderer.xr.enabled=!0,this.context.renderer.xr.updateCamera(this.context.mainCamera))});u(this,"onInputSourceAdded",e=>{if(e.targetRayMode==="screen")return;let t=0;for(let s=0;s<this.session.inputSources.length;s++)if(this.session.inputSources[s]===e){t=s;break}if(this.controllers.find(s=>s.inputSource===e))return;const i=new xR(this,e,t);this.controllers.push(i),this.controllers.sort((s,r)=>s.index-r.index),this._newControllers.push(i),this.invokeControllerEvent(i,this._controllerAdded,"added")});u(this,"_ended",!1);u(this,"_newControllers",[]);u(this,"onEnd",e=>{var s,r,o,a;if(this._ended)return;this._ended=!0,Zs&&console.log("XR Session ended"),Hee(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,KY(this.onBefore,Vn.LateUpdate);const t=this.context.pre_render_callbacks.indexOf(this.onBeforeRender);t>=0&&this.context.pre_render_callbacks.splice(t,1);const i=this.context.post_render_callbacks.indexOf(this.onAfterRender);i>=0&&this.context.post_render_callbacks.splice(i,1),this.context.xr=null,this.context.renderer.xr.enabled=!1,(s=this.context.mainCameraComponent)==null||s.applyClearFlags();for(const c of gh._xrEndListeners)c({xr:this});for(let c=0;c<this.controllers.length;c++)this.disconnectInputSource(this.controllers[c].inputSource);for(const c of this._xr_scripts)(r=c==null?void 0:c.onLeaveXR)==null||r.call(c,{xr:this});(o=this.sync)==null||o.onExitXR(this),this.context.mainCamera&&((a=this._originalCameraParent)==null||a.add(this.context.mainCamera),this._originalCameraWorldPosition&&sr(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&ea(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&kv(this.context.mainCamera,this._originalCameraWorldScale)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent()});u(this,"_didStart",!1);u(this,"onBefore",e=>{var s,r,o,a,c,l,h,d;const t=e.xrFrame;if(!t)return;this.context.xr=this,this.context.mainCameraComponent&&this.context.mainCameraComponent!==this._mainCamera&&(this._mainCamera=this.context.mainCameraComponent),((s=this.rig)==null?void 0:s.isActive)==!1&&(Zs&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig&&((r=this._mainCamera)!=null&&r.gameObject)&&((a=(o=this._mainCamera)==null?void 0:o.gameObject)==null?void 0:a.parent)!==this.rig.gameObject&&this.rig.gameObject.add((c=this._mainCamera)==null?void 0:c.gameObject),this.internalUpdateState(),this.applyCustomForward();const i={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const f=[...this.context.new_scripts_xr];for(let p=0;p<f.length;p++){const m=this.context.new_scripts_xr[p];if(!m||m.destroyed||((l=m.supportsXR)==null?void 0:l.call(m,this.mode))==!1){this.context.new_scripts_xr.splice(p,1);continue}if(!m.activeAndEnabled){this.context.new_scripts_xr.splice(p,1),this.markInactive(m);continue}if(this.addScript(m)){this.invokeCallback_EnterXR(m);for(const g of this.controllers)this.invokeCallback_ControllerAdded(m,g)}}}}else{this._didStart=!0;for(const p of gh._xrStartListeners)p(i);const f=[...this._xr_scripts];Zs&&console.log("NeedleXRSession start, handle scripts:",f);for(const p of f){if(p.destroyed){this._script_to_remove.push(p);continue}if(!p.activeAndEnabled){this.markInactive(p);continue}this.invokeCallback_EnterXR(p);for(const m of this.controllers)this.invokeCallback_ControllerAdded(p,m)}}this.syncCameraCullingMask();for(const f of this.controllers)f.onUpdate(t);for(const f of this._newControllers)for(const p of this._xr_scripts){if(p.destroyed){this._script_to_remove.push(p);continue}p.onXRControllerAdded&&p.onXRControllerAdded({xr:this,controller:f,change:"added"})}this._newControllers.length=0;for(const f of this._xr_update_scripts){if(f.destroyed===!0){this._script_to_remove.push(f);continue}if(f.activeAndEnabled===!1){this.markInactive(f);continue}f.onUpdateXR&&f.onUpdateXR(i)}if(this.handleInactiveScripts(),this._script_to_remove.length>0){const f=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const p of f)!p.destroyed&&this.running&&((h=p.onLeaveXR)==null||h.call(p,i)),this.removeScript(p)}(d=this.sync)==null||d.onUpdate(this),this.onRenderDebug()});u(this,"onBeforeRender",()=>{this.context.mainCamera&&this.updateFade(this.context.mainCamera)});u(this,"onAfterRender",()=>{if(this.onUpdateFade_PostRender(),xv()){const e=this.context.renderer;if(e.xr.isPresenting&&this.context.mainCamera){const t=e.xr.enabled,i=e.getRenderTarget();e.xr.enabled=!1,e.setRenderTarget(null),e.render(this.context.scene,this.context.mainCamera),e.xr.enabled=t,e.setRenderTarget(i)}}});u(this,"_script_to_remove",[]);u(this,"_camera");u(this,"_cameraRenderParent",new ge().rotateY(Math.PI));u(this,"_previousCameraParent");u(this,"_customforward",!0);u(this,"originalCameraNearPlane");u(this,"_viewerPose");u(this,"_transformOrientation",new Ee);u(this,"_transformPosition",new w);u(this,"_transition");var r,o,a;Gee(e,s.init),this.session=t,this.mode=e,this.context=i,this.context.xr=this,this.context.renderer.xr.setSession(this.session).then(this.onRendererSessionSet),this._xr_scripts=[...s.scripts],this._xr_update_scripts=this._xr_scripts.filter(c=>typeof c.onUpdateXR=="function"),this._controllerAdded=s.controller_added,this._controllerRemoved=s.controller_removed,vA(this.onBefore,Vn.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),((r=s.init.optionalFeatures)!=null&&r.includes("hit-test")||(o=s.init.requiredFeatures)!=null&&o.includes("hit-test"))&&t.requestReferenceSpace("viewer").then(c=>{var l,h;return(h=(l=t.requestHitTestSource)==null?void 0:l.call(t,{space:c}))==null?void 0:h.then(d=>this._viewerHitTestSource=d)}).catch(c=>console.warn(c)),this.context.mainCamera&&(this._originalCameraWorldPosition=Dt(this.context.mainCamera,new w),this._originalCameraWorldRotation=Di(this.context.mainCamera,new Ee),this._originalCameraWorldScale=hn(this.context.mainCamera,new w),this._originalCameraParent=this.context.mainCamera.parent),(a=this.context.mainCameraComponent)==null||a.applyClearFlags(),this._defaultRig=new kee,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(const c of this.session.inputSources)this.onInputSourceAdded(c);this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",c=>{for(const l of c.removed)this.disconnectInputSource(l);for(const l of c.added)this.onInputSourceAdded(l)})}static getXRSync(e){return this._sync||(this._sync=new _G(e)),this._sync}static get currentSessionRequest(){return this._currentSessionRequestMode}static get active(){return this._activeSession}static get activeMode(){var e;return((e=this._activeSession)==null?void 0:e.mode)??null}static get xrSystem(){return"xr"in navigator?navigator.xr:void 0}static isXRSupported(){return Promise.all([this.isVRSupported(),this.isARSupported()]).then(e=>e.some(t=>t)).catch(()=>!1)}static isVRSupported(){var e;return((e=this.xrSystem)==null?void 0:e.isSessionSupported("immersive-vr").catch(t=>(Zs&&console.error(t),!1)))??Promise.resolve(!1)}static isARSupported(){var e;return((e=this.xrSystem)==null?void 0:e.isSessionSupported("immersive-ar").catch(t=>(Zs&&console.error(t),!1)))??Promise.resolve(!1)}static onSessionRequestStart(e){this._sessionRequestStartListeners.push(e)}static offSessionRequestStart(e){const t=this._sessionRequestStartListeners.indexOf(e);t>=0&&this._sessionRequestStartListeners.splice(t,1)}static onSessionRequestEnd(e){this._sessionRequestEndListeners.push(e)}static offSessionRequestEnd(e){const t=this._sessionRequestEndListeners.indexOf(e);t>=0&&this._sessionRequestEndListeners.splice(t,1)}static onXRSessionStart(e){this._xrStartListeners.push(e)}static offXRSessionStart(e){const t=this._xrStartListeners.indexOf(e);t>=0&&this._xrStartListeners.splice(t,1)}static onXRSessionEnd(e){this._xrEndListeners.push(e)}static offXRSessionEnd(e){const t=this._xrEndListeners.indexOf(e);t>=0&&this._xrEndListeners.splice(t,1)}static onControllerAdded(e){this._controllerAddedListeners.push(e)}static offControllerAdded(e){const t=this._controllerAddedListeners.indexOf(e);t>=0&&this._controllerAddedListeners.splice(t,1)}static onControllerRemoved(e){this._controllerRemovedListeners.push(e)}static offControllerRemoved(e){const t=this._controllerRemovedListeners.indexOf(e);t>=0&&this._controllerRemovedListeners.splice(t,1)}static offerSession(e,t,i){return"xr"in navigator&&navigator.xr&&"offerSession"in navigator.xr?(typeof navigator.xr.offerSession=="function"&&(console.log("WebXR offerSession is available - requesting mode: "+e),t=="default"&&(t=this.getDefaultSessionInit(e)),navigator.xr.offerSession(e,{...t}).then(s=>gh.setSession(e,s,t,i)).catch(s=>{console.log("XRSession offer rejected (perhaps because another call to offerSession was made or a call to requestSession was made)")})),!0):!1}static getDefaultSessionInit(e){switch(e){case"immersive-ar":return{optionalFeatures:["anchors","local-floor","hand-tracking","layers","dom-overlay","hit-test"]};case"immersive-vr":return{optionalFeatures:["local-floor","bounded-floor","hand-tracking","high-fixed-foveation-level","layers"]};default:return console.warn("No default session init for mode",e),{}}}static async start(e,t,i){var o,a,c,l;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(Zs||Mt())&&pn("A XRSession is already being requested"),this._currentSessionRequest.then(()=>this._activeSession);if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;if(i||(i=Ot.Current),i||(i=Bi.All[0]),!i)throw new Error("No Needle Engine Context found");switch(t||(t={}),e){case"immersive-ar":{if(await((o=this.xrSystem)==null?void 0:o.isSessionSupported("immersive-ar"))!==!0)return console.error(e+" is not supported by this browser."),null;const d=this.getDefaultSessionInit(e),f=Nee(i.domElement);f&&!Gx()&&(d.domOverlay={root:f},d.optionalFeatures.push("dom-overlay")),t={...d,...t}}break;case"immersive-vr":{if(await((a=this.xrSystem)==null?void 0:a.isSessionSupported("immersive-vr"))!==!0)return console.error(e+" is not supported by this browser."),null;t={...this.getDefaultSessionInit(e),...t}}break;default:console.warn("No default session init for mode",e);break}await Ku.stop();const s=e=="immersive-ar"?i.scripts_immersive_ar:i.scripts_immersive_vr;Zs?console.log(`%cRequesting ${e} session`,"font-weight:bold;",t,s):console.log(`%cRequesting ${e} session`,"font-weight:bold;");for(const h of s)h.onBeforeXR&&h.onBeforeXR(e,t);for(const h of this._sessionRequestStartListeners)h({mode:e,init:t});Zs&&xn("Requesting "+e+" session ("+Date.now()+")"),this._currentSessionRequest=(c=navigator.xr)==null?void 0:c.requestSession(e,t),this._currentSessionRequestMode=e;const r=await((l=this._currentSessionRequest)==null?void 0:l.catch(h=>{console.error(h,"Code: "+h.code),h.code===9&&pn("Make sure your device has the required permissions (e.g. camera access)"),console.log("If the specified XR configuration is not supported (e.g. entering AR doesnt work) - make sure you access the website on a secure connection (HTTPS) and your device has the required permissions (e.g. camera access)"),location.protocol==="http:"&&pn("XR requires a secure connection (HTTPS)")}));this._currentSessionRequest=void 0,this._currentSessionRequestMode=null;for(const h of this._sessionRequestEndListeners)h({mode:e,init:t,newSession:r||null});return r?this.setSession(e,r,t,i):(console.warn("XR Session request was rejected"),null)}static setSession(e,t,i,s){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const r=e=="immersive-ar"?s.scripts_immersive_ar:s.scripts_immersive_vr;return this._activeSession=new gh(e,t,s,{scripts:r,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:i}),t.addEventListener("end",this.onEnd),Zs?console.log(`%cStarted ${e} session`,"font-weight:bold;",r):console.log(`%cStarted ${e} session`,"font-weight:bold;"),this._activeSession}static stop(){var e;(e=this._activeSession)==null||e.end()}get sync(){return gh._sync}get running(){return!this._ended&&this.session!=null}get interactionMode(){return this.session.interactionMode}get visibilityState(){return this.session.visibilityState}get environmentBlendMode(){return this.session.environmentBlendMode}get frame(){return this.context.xrFrame}get leftController(){return this.controllers.find(e=>e.isLeft)}get rightController(){return this.controllers.find(e=>e.isRight)}getController(e){return this.controllers.find(t=>t.side===e)||null}get isPassThrough(){return!!(this.environmentBlendMode!=="opaque"&&this.interactionMode==="world-space"||this.mode==="immersive-ar"&&this.environmentBlendMode!=="opaque"&&this.controllers.some(e=>e.inputSource.targetRayMode==="tracked-pointer")||Mt()&&xv()&&this.mode==="immersive-ar")}get isAR(){return this.mode==="immersive-ar"}get isVR(){return this.mode==="immersive-vr"}get posePosition(){return this._transformPosition}get poseOrientation(){return this._transformOrientation}get referenceSpace(){return this.context.renderer.xr.getReferenceSpace()}get viewerPose(){return this._viewerPose}get isTrackingImages(){if(this.frame&&"getImageTrackingResults"in this.frame&&typeof this.frame.getImageTrackingResults=="function")try{const e=this.frame.getImageTrackingResults();for(const t of e)if(t.trackingState==="tracked")return!0}catch{return!1}return!1}get rig(){const e=this._rigs[0]??null;return e!=null&&e.gameObject&&bd(e.gameObject)||(e==null?void 0:e.isActive)===!1?(this.updateActiveXRRig(),this._rigs[0]??null):e}get rigScale(){return this._rigs[0]?(this._lastRigScaleUpdate!==this.context.time.frame&&(this._lastRigScaleUpdate=this.context.time.frame,this._rigScale=this._rigs[0].gameObject.worldScale.x),this._rigScale):1}addRig(e){this._rigs.indexOf(e)>=0||(e.priority===void 0&&(e.priority=0),this._rigs.push(e),this.updateActiveXRRig())}removeRig(e){const t=this._rigs.indexOf(e);t!==-1&&(this._rigs.splice(t,1),this.updateActiveXRRig())}setRigActive(e){const t=this._rigs.indexOf(e);this._rigs.splice(t,1),this._rigs.unshift(e),this.updateActiveXRRig()}updateActiveXRRig(){const e=this._rigs[0]??null;this._defaultRig.gameObject.parent!==this.context.scene&&this.context.scene.add(this._defaultRig.gameObject),this._defaultRig.gameObject.visible=!0,this._rigs.includes(this._defaultRig)||this._rigs.push(this._defaultRig);let t=this._rigs[0];t&&t.priority===void 0&&(t.priority=0);for(let i=1;i<this._rigs.length;i++){const s=this._rigs[i];if(s.isActive){if(bd(s.gameObject)){this._rigs.splice(i,1),i--;continue}(!t||t.isActive===!1||s.priority!==void 0&&s.priority>t.priority)&&(t=s)}}if(e!==t){const i=this._rigs.indexOf(t);i>=0&&this._rigs.splice(i,1),this._rigs.unshift(t)}Zs&&(e===t?console.log("Updated Active XR Rig:",t,"prev:",e):console.log("Updated Active XRRig:",t," (the same as before)"))}getHitTest(e){if(e)return this.getControllerHitTest(e);if(!this._viewerHitTestSource)return null;const t=this._viewerHitTestSource,i=this.frame.getHitTestResults(t);if(i.length>0){const s=i[0];return this.convertHitTestResult(s)}return null}getControllerHitTest(e){const t=e.hitTestSource;if(!t)return null;const i=this.frame.getHitTestResultsForTransientInput(t);for(const s of i)if(s.inputSource===e.inputSource)for(const r of s.results)return this.convertHitTestResult(r);return null}convertHitTestResult(e){const t=this.context.renderer.xr.getReferenceSpace(),i=t&&e.getPose(t);if(i){const s=Gn(i.transform.position),r=Ju(i.transform.orientation),o=this.context.mainCamera;if((o==null?void 0:o.parent)!==this._cameraRenderParent&&s.applyMatrix4(Ob),o!=null&&o.parent){s.applyMatrix4(o.parent.matrixWorld),r.multiply(_a);const a=Di(o.parent);a.premultiply(_a),r.premultiply(a)}return{hit:e,position:s,quaternion:r}}return null}convertSpace(e){const t=Gn(e.position);t.applyMatrix4(Ob);const i=Ju(e.orientation);return i.premultiply(_a),{position:t,quaternion:i}}end(){this._ended||this.session.end().catch(e=>console.warn(e))}disconnectInputSource(e){for(let t=this.controllers.length-1;t>=0;t--){const i=this.controllers[t];if(i.inputSource===e){this.controllers.splice(t,1),this.invokeControllerEvent(i,this._controllerRemoved,"removed");const s={xr:this,controller:i,change:"removed"};for(const r of this._xr_scripts)r.onXRControllerRemoved&&r.onXRControllerRemoved(s);i.onDisconnected()}}}onRenderDebug(){if(Zs)for(const e of this.controllers)e.onRenderDebug();if((Zs||Uee)&&this.rig){const e=this.rig.gameObject.worldPosition,t=this.rig.gameObject.worldForward;e.add(t.multiplyScalar(1.5));const i=this.rig.gameObject.worldUp;e.add(i.multiplyScalar(2.5));let s="";if(s+=this.context.time.smoothedFps.toFixed(1),Zs)for(const r of this.controllers)s+=`
4989
4989
  ${r.hand?"hand":"ctrl"} ${r.inputSource.handedness}[${r.index}] con:${r.connected} tr:${r.isTracking}`;It.DrawLabel(e,s)}}addScript(e){return this._xr_scripts.includes(e)?!1:(Zs&&console.log("Register new XRScript",e),this._xr_scripts.push(e),typeof e.onUpdateXR=="function"&&this._xr_update_scripts.push(e),!0)}markInactive(e){if(!(this._inactive_scripts.indexOf(e)>=0)){this.removeScript(e,!1),this._inactive_scripts.push(e);for(const t of this.controllers)this.invokeCallback_ControllerRemoved(e,t);this.invokeCallback_LeaveXR(e)}}handleInactiveScripts(){if(this._inactive_scripts.length>0)for(let e=this._inactive_scripts.length-1;e>=0;e--){const t=this._inactive_scripts[e];if(t.activeAndEnabled){this._inactive_scripts.splice(e,1),this.addScript(t),this.invokeCallback_EnterXR(t);for(const i of this.controllers)this.invokeCallback_ControllerAdded(t,i)}}}removeScript(e,t=!0){Zs&&console.log("Remove XRScript",e);const i=this._xr_scripts.indexOf(e);i>=0&&this._xr_scripts.splice(i,1);const s=this._xr_update_scripts.indexOf(e);if(s>=0&&this._xr_update_scripts.splice(s,1),t){const r=this._inactive_scripts.indexOf(e);r>=0&&this._inactive_scripts.splice(r,1)}}invokeCallback_EnterXR(e){e.onEnterXR&&e.onEnterXR({xr:this})}invokeCallback_ControllerAdded(e,t){e.onXRControllerAdded&&e.onXRControllerAdded({xr:this,controller:t,change:"added"})}invokeCallback_ControllerRemoved(e,t){e.onXRControllerRemoved&&e.onXRControllerRemoved({xr:this,controller:t,change:"removed"})}invokeCallback_LeaveXR(e){e.onLeaveXR&&!e.destroyed&&e.onLeaveXR({xr:this})}syncCameraCullingMask(){var i;const e=this.context.xrCamera,t=(i=this.context.mainCameraComponent)==null?void 0:i.cullingMask;if(e&&t!==void 0){for(const s of e.cameras)s.layers.mask=t;e.layers.mask=t}else if(e){for(const s of e.cameras)s.layers.enableAll();e.layers.enableAll()}}invokeControllerEvent(e,t,i){for(let s=t.length-1;s>=0;s--){const r=t[s];if(r)try{r({xr:this,controller:e,change:i})}catch(o){console.error(o)}}}applyCustomForward(){var e;if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,(e=this._previousCameraParent)==null||e.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);let t=.02;if(this.rig){const i=hn(this.rig.gameObject);t*=i.x}this._camera instanceof Jt&&this._camera.near>t&&(this.originalCameraNearPlane=this._camera.near,this._camera.near=t)}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof Jt&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane)}internalUpdateState(){const e=this.context.renderer.xr.getReferenceSpace();if(!e){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(e),this._viewerPose){const t=this._viewerPose.transform;this._transformPosition.set(t.position.x,t.position.y,t.position.z),this._transformOrientation.set(t.orientation.x,t.orientation.y,t.orientation.z,t.orientation.w)}}get transition(){return this._transition||(this._transition=new dk),this._transition}fadeTransition(){return this._transition||(this._transition=new dk),this._transition.fadeTransition()}updateFade(e){this._transition&&e instanceof Jt&&this._transition.update(e,this.context.time.deltaTime)}onUpdateFade_PostRender(){var e;(e=this._transition)==null||e.remove()}};let yt=gh;u(yt,"_sync",null),u(yt,"_currentSessionRequestMode",null),u(yt,"_currentSessionRequest"),u(yt,"_activeSession"),u(yt,"_sessionRequestStartListeners",[]),u(yt,"_sessionRequestEndListeners",[]),u(yt,"_xrStartListeners",[]),u(yt,"_xrEndListeners",[]),u(yt,"_controllerAddedListeners",[]),u(yt,"_controllerRemovedListeners",[]),u(yt,"onEnd",()=>{Zs&&console.log("XR Session ended"),gh._activeSession=null});const EC=se("debugwebxr");class bG{static tryFindAvatarObjects(e,t,i){if(i.head&&i.leftHand&&i.rightHand)return;const s=e.name.toLocaleLowerCase();!i.head&&s.includes("head")&&(EC&&console.log("FOUND AVATAR HEAD",e.name),i.head=new ii("",t,e)),s.includes("hand")&&(!i.leftHand&&s.includes("left")&&(EC&&console.log("FOUND AVATAR LEFT HAND",e.name),i.leftHand=new ii("",t,e)),!i.rightHand&&s.includes("right")&&(EC&&console.log("FOUND AVATAR RIGHT HAND",e.name),i.rightHand=new ii("",t,e)));for(let r=0;r<e.children.length;r++){if(i.head&&i.leftHand&&i.rightHand)return;const o=e.children[r];this.tryFindAvatarObjects(o,t,i)}}}const dr=new w,fk=new w,pk=new Ee,Vee=se("debuggizmos"),Vc=8947848,va=class{static isGizmo(e){return e[pM]!==void 0}static DrawLabel(e,t,i=.05,s=0,r,o,a){var h;if(!va.enabled)return null;r||(r=Vc);const c=((h=yt.active)==null?void 0:h.rigScale)??1,l=zn.getTextLabel(s,t,i*c,r,o);return a instanceof ge&&a.add(l),l.position.x=e.x,l.position.y=e.y,l.position.z=e.z,l}static DrawRay(e,t,i=Vc,s=0,r=!0){if(!va.enabled)return;const o=zn.getLine(s),a=o.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),dr.set(t.x,t.y,t.z).multiplyScalar(999999999),a.setXYZ(1,e.x+dr.x,e.y+dr.y,e.z+dr.z),a.needsUpdate=!0,o.material.color.set(i),o.material.depthTest=r,o.material.depthWrite=!1}static DrawDirection(e,t,i=Vc,s=0,r=!0,o=1){if(!va.enabled)return;const a=zn.getLine(s),c=a.geometry.getAttribute("position");c.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(dr.set(0,0,-o),pk.set(t.x,t.y,t.z,t.w),dr.applyQuaternion(pk)):(dr.set(t.x,t.y,t.z),dr.multiplyScalar(o)),c.setXYZ(1,e.x+dr.x,e.y+dr.y,e.z+dr.z),c.needsUpdate=!0,a.material.color.set(i),a.material.depthTest=r,a.material.depthWrite=!1}static DrawLine(e,t,i=Vc,s=0,r=!0){if(!va.enabled)return;const o=zn.getLine(s),a=o.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),a.setXYZ(1,t.x,t.y,t.z),a.needsUpdate=!0,o.material.color.set(i),o.material.depthTest=r,o.material.depthWrite=!1}static DrawWireSphere(e,t,i=Vc,s=0,r=!0){if(!va.enabled)return;const o=zn.getSphere(t,s,!0);yd(o,e.x,e.y,e.z),o.material.color.set(i),o.material.depthTest=r,o.material.depthWrite=!1}static DrawSphere(e,t,i=Vc,s=0,r=!0){if(!va.enabled)return;const o=zn.getSphere(t,s,!1);yd(o,e.x,e.y,e.z),o.material.color.set(i),o.material.depthTest=r,o.material.depthWrite=!1}static DrawWireBox(e,t,i=Vc,s=0,r=!0){if(!va.enabled)return;const o=zn.getBox(s);o.position.set(e.x,e.y,e.z),o.scale.set(t.x,t.y,t.z),o.material.color.set(i),o.material.depthTest=r,o.material.wireframe=!0,o.material.depthWrite=!1}static DrawWireBox3(e,t=Vc,i=0,s=!0){if(!va.enabled)return;const r=zn.getBox(i);r.position.copy(e.getCenter(dr)),r.scale.copy(e.getSize(dr)),r.material.color.set(t),r.material.depthTest=s,r.material.wireframe=!0,r.material.depthWrite=!1}static DrawArrow(e,t,i=Vc,s=0,r=!0,o=!1){if(!va.enabled)return;const a=zn.getArrowHead(s);a.position.set(t.x,t.y,t.z),a.quaternion.setFromUnitVectors(this._up.set(0,1,0),dr.set(t.x,t.y,t.z).sub(fk.set(e.x,e.y,e.z)).normalize());const l=dr.set(t.x,t.y,t.z).sub(fk.set(e.x,e.y,e.z)).length()*.1;a.scale.set(l,l,l),a.material.color.set(i),a.material.depthTest=r,a.material.wireframe=o,this.DrawLine(e,t,i,s,r)}};let It=va;u(It,"enabled",!0),u(It,"_up",new w(0,1,0));const Qee=new Vi(1,1,1);function wR(n=null){const e=new ye(n??14540253),t=new jT(Qee);return new xo(t,new kn({color:e}))}const pM=Symbol("GizmoCache");class zn{static ensureFont(){let e=Ff.FontLibrary.getFontFamily(this.familyName);if(!e){e=Ff.FontLibrary.addFontFamily(this.familyName);const t=e.addVariant("normal","normal","./include/needle/arial-msdf.json","./include/needle/arial.png");t==null||t.addEventListener("ready",()=>{Ff.update()})}}static getTextLabel(e,t,i,s,r){this.ensureFont();let o=this.textLabelCache.pop(),a=1;r&&typeof r=="string"&&(r==null?void 0:r.length)>=8&&r.startsWith("#")?(a=parseInt(r.substring(7),16)/255,r=r.substring(0,7),Vee&&console.log(r,a)):typeof r=="object"&&r.a!==void 0&&(a=r.a);const c={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:i,color:s,lineHeight:1,backgroundColor:r??void 0,backgroundOpacity:a,textContent:t,borderRadius:.5*i,padding:.8*i,whiteSpace:"pre"};if(o)o.set(c);else{o=new pR(c);const l=this,h=o;h.setText=function(d){this.set({textContent:d}),l.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(Ot.Current,o,e,this.textLabelCache),o}static getBox(e){let t=this.boxesCache.pop();if(!t){const i=new Vi(1,1,1);t=new me(i)}return this.registerTimedObject(Ot.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new Bn;let i=t.geometry.getAttribute("position");i||(i=new tt(new Float32Array(2*3),3),t.geometry.setAttribute("position",i))}return t.frustumCulled=!1,this.registerTimedObject(Ot.Current,t,e,this.linesCache),t}static getSphere(e,t,i){let s=this.spheresCache.pop();return s||(s=new me(new Da(1,8,8))),s.scale.set(e,e,e),s.material.wireframe=i,this.registerTimedObject(Ot.Current,s,t,this.spheresCache),s}static getArrowHead(e){let t=this.arrowHeadsCache.pop();return t||(t=new me(new Rn(0,.5,1,8))),this.registerTimedObject(Ot.Current,t,e,this.arrowHeadsCache),t}static registerTimedObject(e,t,i,s){const r=this.contextBeforeRenderCallbacks.get(e),o=this.contextPostRenderCallbacks.get(e);if(r){if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==r){const a=e.pre_render_callbacks.indexOf(r);a>=0&&e.pre_render_callbacks.splice(a,1),e.pre_render_callbacks.push(r)}}else{const a=()=>{this.onBeforeRender(e,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(e,a),e.pre_render_callbacks.push(a)}if(o){if(e.post_render_callbacks[e.post_render_callbacks.length-1]!==o){const a=e.post_render_callbacks.indexOf(o);a>=0&&e.post_render_callbacks.splice(a,1),e.post_render_callbacks.push(o)}}else{const a=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,a),e.post_render_callbacks.push(a)}t.traverse(a=>{a.layers.disableAll(),a.layers.enable(2)}),t.renderOrder=999999,t[pM]=s,this.timedObjectsBuffer.push(t),this.timesBuffer.push(Ot.Current.time.realtimeSinceStartup+i),e.scene.add(t)}static onBeforeRender(e,t){this.tmuiNeedsUpdate&&Ff.update();for(let i=0;i<t.length;i++){const s=t[i];if(e.mainCamera&&s instanceof Ff.MeshUIBaseElement){if(bd(s))continue;const r=e.isInVR,o=!1,a=!r;mR(s,e.mainCamera,o,a)}}}static onPostRender(e,t,i){const s=e.time.realtimeSinceStartup;for(let r=t.length-1;r>=0;r--){const o=t[r];s>i[r]&&(t.splice(r,1),i.splice(r,1),o.removeFromParent(),bd(o)!=!0&&o[pM].push(o))}}}u(zn,"familyName","needle-gizmos"),u(zn,"linesCache",[]),u(zn,"spheresCache",[]),u(zn,"boxesCache",[]),u(zn,"arrowHeadsCache",[]),u(zn,"textLabelCache",[]),u(zn,"timedObjectsBuffer",new Array),u(zn,"timesBuffer",new Array),u(zn,"contextPostRenderCallbacks",new Map),u(zn,"contextBeforeRenderCallbacks",new Map),u(zn,"tmuiNeedsUpdate",!1);const jee=se("debugphysics"),mk=new Cr;class ta{constructor(){u(this,"ray");u(this,"cam");u(this,"screenPoint");u(this,"raycaster");u(this,"results");u(this,"targets");u(this,"recursive",!0);u(this,"minDistance");u(this,"maxDistance");u(this,"lineThreshold");u(this,"layerMask");u(this,"ignore");u(this,"testObject")}screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new ie),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setLayer(e){mk.set(e),this.layerMask=mk}setMask(e){this.layerMask||(this.layerMask=new Cr);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}u(ta,"AllLayers",4294967295);class xG{constructor(e,t,i){u(this,"distance");u(this,"point");u(this,"object");this.object=e,this.distance=t,this.point=i}}class wG{constructor(e){u(this,"context");u(this,"engine");u(this,"raycaster",new Qp);u(this,"defaultRaycastOptions",new ta);u(this,"targetBuffer",new Array(1));u(this,"defaultThresholds",{Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}});u(this,"sphereResults",new Array);u(this,"sphereMask",new Cr);u(this,"tempBoundingBox",new Oi);this.context=e}raycastPhysicsFast(e,t=void 0,i=1/0,s=!0){var r;return((r=this.context.physics.engine)==null?void 0:r.raycast(e,t,i,s))??null}raycastPhysicsFastAndGetNormal(e,t=void 0,i=1/0,s=!0){var r;return((r=this.context.physics.engine)==null?void 0:r.raycastAndGetNormal(e,t,i,s))??null}sphereOverlapPhysics(e,t){var i;return((i=this.context.physics.engine)==null?void 0:i.sphereOverlap(e,t))??null}sphereOverlap(e,t,i=!0){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const s=new On(e,t),r=this.sphereMask;r.enableAll(),r.disable(2);for(const o of this.context.scene.children)this.onSphereOverlap(o,s,r,this.sphereResults,i);return this.sphereResults.sort((o,a)=>o.distance-a.distance)}onSphereOverlap(e,t,i,s,r){if(e.type==="Mesh"&&e.layers.test(i)&&!It.isGizmo(e)){const o=e,a=o.geometry;if(a&&(a.boundingBox||a.computeBoundingBox(),a.boundingBox)){o.matrixWorldNeedsUpdate&&o.updateMatrixWorld();const c=this.tempBoundingBox.copy(a.boundingBox).applyMatrix4(o.matrixWorld);if(t.intersectsBox(c)){const l=Dt(e),h=l.distanceTo(t.center),d=new xG(e,h,l);if(s.push(d),!r)return}}}if(e.children)for(const o of e.children){const a=s.length;if(this.onSphereOverlap(o,t,i,s,r),a!=s.length&&!r)return}}raycastFromRay(e,t=null){const i=t??this.defaultRaycastOptions;i.ray=e;const s=this.raycast(i);return i===this.defaultRaycastOptions&&(i.ray=void 0),s}raycast(e=null){e||(e=this.defaultRaycastOptions);const t=e.screenPoint??this.context.input.mousePositionRC,i=e.raycaster??this.raycaster;if(i.near=e.minDistance??0,i.far=e.maxDistance??1/0,i.params=this.defaultThresholds,e.lineThreshold===void 0&&(e.lineThreshold=-1),i.params.Line={threshold:e.lineThreshold},e.ray)i.ray.copy(e.ray);else{const a=e.cam??this.context.mainCamera;if(!a)return jee&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];i.setFromCamera(t,a)}let s=e.targets;s||(s=this.targetBuffer,s.length=1,s[0]=this.context.scene);let r=e.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),r||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),r=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof Cr?i.layers.mask=e.layerMask.mask:i.layers.mask=e.layerMask:(i.layers.enableAll(),i.layers.disable(2)),r.length=0,this.intersect(this.raycaster,s,r,e),r.sort((a,c)=>a.distance-c.distance);const o=e.ignore;return o!==void 0&&o.length>0&&(r=r.filter(a=>!o.includes(a.object))),r}intersect(e,t,i,s){var r;for(const o of t){if(o.visible===!1||It.isGizmo(o)||s.lineThreshold!==void 0&&s.lineThreshold<0&&o instanceof Bn)continue;const a=(r=s.testObject)==null?void 0:r.call(s,o);if(a===!1)continue;a!=="continue in children"&&e.intersectObject(o,!1,i),s.recursive!==!1&&this.intersect(e,o.children,i,s)}return i}}const Wee=se("debugplayerview");var Th=(n=>(n.Browser="browser",n.Headset="headset",n.Handheld="handheld",n))(Th||{});class SG{constructor(e,t){u(this,"userId");u(this,"context");u(this,"viewDevice","browser");u(this,"removed",!1);u(this,"_object");this.userId=e,this.context=t}get currentObject(){return this._object}set currentObject(e){this._object=e}get isConnected(){return this.context.connection.userIsInRoom(this.userId)}}class CG{constructor(e){u(this,"context");u(this,"playerViews",new Map);this.context=e}setPlayerView(e,t,i){let s=this.playerViews.get(e);s||(s=new SG(e,this.context),this.playerViews.set(e,s)),s.viewDevice=i,s.currentObject=t,s.removed=!1}getPlayerView(e){if(!e)return;if(!this.context.connection.userIsInRoom(e)){this.playerViews.delete(e);return}return this.playerViews.get(e)}removePlayerView(e,t){const i=this.playerViews.get(e);(i==null?void 0:i.viewDevice)===t&&(Wee&&console.log("REMOVE",e),i.removed=!0,this.playerViews.delete(e))}}new ts;const MA=new Uint8Array(4);MA[0]=255;MA[1]=255;MA[2]=255;MA[3]=255;const qee=new po(MA,1,1,Ci);function EG(n,e=1){const t="alpha"in n,i=e*e,s=new Uint8Array(4*i),r=Math.floor(n.r*255),o=Math.floor(n.g*255),a=Math.floor(n.b*255);for(let l=0;l<i;l++){const h=l*4;s[h+0]=r,s[h+1]=o,s[h+2]=a,t?s[h+3]=Math.floor(n.alpha*255):s[h+3]=255}const c=new po(s,e,e);return c.needsUpdate=!0,c}function Xee(n,e,t,i=1,s=3){const o=i*s,a=[n,e,t],c=a.length,l=new Uint8Array(4*c*o),h=new ye;for(let f=0;f<s;f++){const p=Math.floor(f/s*c),m=rt.clamp(p+1,0,c-1),g=a[p],y=a[m],v=f/s*c%1;h.lerpColors(g,y,v);const A=Math.floor(h.r*255),_=Math.floor(h.g*255),b=Math.floor(h.b*255);for(let C=0;C<i;C++){const E=(f*i+C)*4;l[E+0]=A,l[E+1]=_,l[E+2]=b,l[E+3]=255}}const d=new po(l,i,s);return d.needsUpdate=!0,d}function kb(n,e){const t=n.elements;e||(e=[]),e.length=0;for(let i=0;i<16;i+=4){const s=t[i],r=t[i+1],o=t[i+2],a=t[i+3],c=new st(s,r,o,a);e.push(c)}return e}const MC=[],gk=[];function Yee(n,e){if(MC.length===0)for(let t=0;t<27;t++)MC.push(0);e||(e=MC);for(let t=0;t<27;t++)gk[t]=e[t];e=gk,n.unity_SHAr={value:new st(e[9],e[3],e[6],e[0])},n.unity_SHBr={value:new st(e[12],e[15],e[18],e[21])},n.unity_SHAg={value:new st(e[10],e[4],e[7],e[1])},n.unity_SHBg={value:new st(e[13],e[16],e[19],e[22])},n.unity_SHAb={value:new st(e[11],e[5],e[8],e[2])},n.unity_SHBb={value:new st(e[14],e[17],e[20],e[23])},n.unity_SHC={value:new st(e[24],e[25],e[26],1)}}class Jee{constructor(e,t,i){u(this,"vertexShader");u(this,"fragmentShader");u(this,"technique");this.vertexShader=e,this.fragmentShader=t,this.technique=i}}async function Kee(n,e){if(!n)return console.error("Can not find technique: no shader data"),null;const t=n.programs[e],i=t.vertexShader,s=t.fragmentShader;if(i!==void 0&&s!==void 0){const r=n.shaders[i],o=n.shaders[s];if(r.uri&&o.uri||r.code&&o.code){if(!r.code&&r.uri&&await vk(r),!o.code&&o.uri&&await vk(o),!r.code||!o.code)return null;const a=n.techniques[e];return new Jee(r.code,o.code,a)}}return console.error("Shader technique not found",e),null}async function vk(n){const e=n.uri;if(e)if(e.endsWith(".glsl")){const i=await new ts().loadAsync(e);n.code=i.toString()}else n.code=Zee(n.uri)}function Zee(n){return decodeURIComponent(Array.prototype.map.call(atob(n),function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}const Va=se("debugenvlight");var dp=(n=>(n[n.Skybox=0]="Skybox",n[n.Trilight=1]="Trilight",n[n.Flat=3]="Flat",n[n.Custom=4]="Custom",n))(dp||{}),Lb=(n=>(n[n.Skybox=0]="Skybox",n[n.Custom=1]="Custom",n))(Lb||{});class MG{constructor(e){u(this,"context");u(this,"_currentLightSettingsId");u(this,"_sceneLightSettings");u(this,"_timevec4",new st);u(this,"__currentReflectionId",null);u(this,"_lighting",{});this.context=e,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}preUpdate(){const e=this.context.time;this._timevec4.x=e.time,this._timevec4.y=Math.sin(e.time),this._timevec4.z=Math.cos(e.time),this._timevec4.w=e.deltaTime}get timeVec4(){return this._timevec4}get environmentIntensity(){if(!this._sceneLightSettings||!this._currentLightSettingsId)return 1;const e=this._sceneLightSettings.get(this._currentLightSettingsId);return e?e.ambientIntensity:1}get sceneLightSettings(){var e;return(e=this._sceneLightSettings)==null?void 0:e.values()}enable(e){var i;e instanceof ii&&(e=e.uri);const t=(i=this._sceneLightSettings)==null?void 0:i.get(e);return t?(Va&&console.log("Enable scene light settings",e,t),e!==this._currentLightSettingsId&&this._currentLightSettingsId&&this.disable(this._currentLightSettingsId),this._currentLightSettingsId=e,t.enabled=!0,!0):!1}disable(e){var i;if(e instanceof ii&&(e=e.uri),e==null)return!1;const t=(i=this._sceneLightSettings)==null?void 0:i.get(e);return t?(Va&&console.log("Disable scene light settings",e,t),t.enabled=!1,!0):!1}disableCurrent(){if(this._currentLightSettingsId){const e=this._currentLightSettingsId;return this.disable(this._currentLightSettingsId),e}return null}internalRegisterSceneLightSettings(e){const t=e.sourceId;if(!t){console.error("Missing source id for scene light settings, can not register:",e);return}Va&&console.log("Register "+(e==null?void 0:e.sourceId)+" lighting",e),this._sceneLightSettings||(this._sceneLightSettings=new Map),this._sceneLightSettings.set(t,e)}internalUnregisterSceneLightSettings(e){const t=e.sourceId;if(!t){console.error("Missing source id for scene light settings, can not unregister:",e);return}Va&&console.log("Unregister "+(e==null?void 0:e.sourceId)+" lighting",e),this._sceneLightSettings&&this._sceneLightSettings.delete(t)}internalRegisterReflection(e,t){Va&&console.log("Register reflection",e,t);const i=new TG(this.context,t,1);this._lighting[e]=i}internalGetReflection(e){return this._lighting[e]}internalEnableReflection(e){var i;this.__currentReflectionId=e;const t=(i=this._sceneLightSettings)==null?void 0:i.get(e);switch(Va&&console.log("Enable reflection",e,t?dp[t.ambientMode]:"Unknown ambient mode"),t==null?void 0:t.ambientMode){case 0:case 4:const s=this.internalGetReflection(e);if(s&&s.Source){Va&&console.log("Setting environment reflection",s);const r=this.context.scene,o=s.Source;o.colorSpace=Wt,o.mapping=Xo,r.environment=o;return}else Va&&console.warn("Could not find reflection for source",e);break}if((t==null?void 0:t.environmentReflectionSource)===1)switch(t==null?void 0:t.ambientMode){case 1:if(t.ambientTrilight){const s=t.ambientTrilight,r=Xee(s[0],s[1],s[2],64,64);r.colorSpace=Wt,r.mapping=Xo,this.context.scene.environment=r}else console.error("Missing ambient trilight",t.sourceId);return;case 3:if(t.ambientLight){const s=EG(t.ambientLight,64);s.colorSpace=Wt,s.mapping=Xo,this.context.scene.environment=s}else console.error("Missing ambientlight",t.sourceId);return;default:return}}internalDisableReflection(e){if(e&&e!==this.__currentReflectionId){Va&&console.log("Not disabling reflection for",e,"because it is not the current light settings id",this.__currentReflectionId);return}Va&&console.log("Disable reflection",e);const t=this.context.scene;t.environment=null}}class TG{constructor(e,t,i=1){u(this,"_context");u(this,"_source");u(this,"_sphericalHarmonics",null);u(this,"_sphericalHarmonicsArray");u(this,"_ambientScale",1);u(this,"_lightProbe");this._context=e,this._source=t,this._ambientScale=i,t.mapping=Xo,t.colorSpace=Wt}get Source(){return this._source}get Array(){return this._sphericalHarmonicsArray}}const Ak=se("timescale");let mM=1;typeof Ak=="number"&&(mM=Ak);class IG{constructor(){u(this,"deltaTime",0);u(this,"time",0);u(this,"timeScale",1);u(this,"frame",0);u(this,"clock",new eI);u(this,"_smoothedFps",0);u(this,"_smoothedDeltaTime",0);u(this,"_fpsSamples",[]);u(this,"_fpsSampleIndex",0);typeof mM=="number"&&(this.timeScale=mM)}get realtimeSinceStartup(){return this.clock.elapsedTime}get frameCount(){return this.frame}get smoothedFps(){return this._smoothedFps}get smoothedDeltaTime(){return 1/this._smoothedFps}update(){this.deltaTime=this.clock.getDelta(),this.deltaTime=Math.min(.1,this.deltaTime),this.deltaTime*=this.timeScale,this.deltaTime<=0&&(this.deltaTime=1e-12),this.frame+=1,this.time+=this.deltaTime,this._fpsSamples.length<60?this._fpsSamples.push(this.deltaTime):this._fpsSamples[this._fpsSampleIndex++%60]=this.deltaTime;let e=0;for(let t=0;t<this._fpsSamples.length;t++)e+=this._fpsSamples[t];this._smoothedDeltaTime=e/this._fpsSamples.length,this._smoothedFps=1/this._smoothedDeltaTime}}const Ur=se("debugcontext"),$ee=se("stats"),ete=se("debugactive"),tte=se("debugframerate"),ite=se("debugcoroutine"),nte={};class ste{constructor(){u(this,"name");u(this,"alias");u(this,"hash");u(this,"runInBackground");u(this,"domElement");u(this,"renderer");u(this,"camera");u(this,"scene")}}var Vn=(n=>(n[n.Start=-1]="Start",n[n.EarlyUpdate=0]="EarlyUpdate",n[n.Update=1]="Update",n[n.LateUpdate=2]="LateUpdate",n[n.OnBeforeRender=3]="OnBeforeRender",n[n.OnAfterRender=4]="OnAfterRender",n[n.PrePhysicsStep=9]="PrePhysicsStep",n[n.PostPhysicsStep=10]="PostPhysicsStep",n[n.Undefined=-1]="Undefined",n))(Vn||{});function ow(n,e){if(!n)return;if(!n.isComponent){(Mt()||Ur)&&console.error(`Registered script is not a Needle Engine component.
4990
4990
  The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
4991
- `,n);return}const t=(e==null?void 0:e.new_scripts)??Ot.Current.new_scripts;t.includes(n)||t.push(n)}const Wi=class{constructor(e){u(this,"name");u(this,"alias");u(this,"isManagedExternally",!1);u(this,"isPaused",!1);u(this,"runInBackground",!1);u(this,"targetFrameRate");u(this,"physicsSteps",1);u(this,"hash");u(this,"domElement");u(this,"_resolutionScaleFactor",1);u(this,"_boundingClientRectFrame",-1);u(this,"_boundingClientRect",null);u(this,"_domX");u(this,"_domY");u(this,"xr",null);u(this,"_xrFrame",null);u(this,"_currentFrameEvent",-1);u(this,"scene");u(this,"renderer");u(this,"composer",null);u(this,"scripts",[]);u(this,"scripts_pausedChanged",[]);u(this,"scripts_earlyUpdate",[]);u(this,"scripts_update",[]);u(this,"scripts_lateUpdate",[]);u(this,"scripts_onBeforeRender",[]);u(this,"scripts_onAfterRender",[]);u(this,"scripts_WithCorroutines",[]);u(this,"scripts_immersive_vr",[]);u(this,"scripts_immersive_ar",[]);u(this,"coroutines",{});u(this,"post_setup_callbacks",[]);u(this,"pre_update_callbacks",[]);u(this,"pre_render_callbacks",[]);u(this,"post_render_callbacks",[]);u(this,"pre_update_oneshot_callbacks",[]);u(this,"new_scripts",[]);u(this,"new_script_start",[]);u(this,"new_scripts_pre_setup_callbacks",[]);u(this,"new_scripts_post_setup_callbacks",[]);u(this,"new_scripts_xr",[]);u(this,"mainCameraComponent");u(this,"_camera",null);u(this,"application");u(this,"time");u(this,"input");u(this,"physics");u(this,"connection");u(this,"assets");u(this,"mainLight",null);u(this,"sceneLighting");u(this,"addressables");u(this,"lightmaps");u(this,"players");u(this,"_sizeChanged",!1);u(this,"_isCreated",!1);u(this,"_isCreating",!1);u(this,"_isVisible",!1);u(this,"_stats",$ee?new CY:null);u(this,"_intersectionObserver",null);u(this,"_disposeCallbacks",[]);u(this,"_originalCreationArgs");u(this,"onUnhandledRejection",e=>{this.domElement.dispatchEvent(new CustomEvent("error",{detail:e.reason}))});u(this,"_cameraStack",[]);u(this,"_onBeforeRenderListeners",new Map);u(this,"_onAfterRenderListeners",new Map);u(this,"_requireDepthTexture",!1);u(this,"_requireColorTexture",!1);u(this,"_renderTarget");u(this,"_isRendering",!1);u(this,"_createId",0);u(this,"_renderlooperrors",0);u(this,"_lastTimestamp",0);u(this,"_accumulatedTime",0);u(this,"_dispatchReadyAfterFrame",!1);u(this,"_wasPaused",!1);this.name=(e==null?void 0:e.name)||"",this.alias=e==null?void 0:e.alias,this.domElement=(e==null?void 0:e.domElement)||document.body,this.hash=e==null?void 0:e.hash,e!=null&&e.renderer&&(this.renderer=e.renderer,this.isManagedExternally=!0),(e==null?void 0:e.runInBackground)!==void 0&&(this.runInBackground=e.runInBackground),e!=null&&e.scene?this.scene=e.scene:this.scene=new rr,e!=null&&e.camera&&(this._camera=e.camera),this.application=new VN(this),this.time=new IG,this.input=new WN(this),this.physics=new wG(this),this.connection=new X3(this),this.assets=new nN,this.sceneLighting=new MG(this),this.addressables=new GN(this),this.lightmaps=new v7(this),this.players=new CG(this);const t=()=>this._sizeChanged=!0;window.addEventListener("resize",t),this._disposeCallbacks.push(()=>window.removeEventListener("resize",t));const i=new ResizeObserver(s=>this._sizeChanged=!0);i.observe(this.domElement),this._disposeCallbacks.push(()=>i.disconnect()),this._intersectionObserver=new IntersectionObserver(s=>{this._isVisible=s[0].isIntersecting}),this._disposeCallbacks.push(()=>{var s;return(s=this._intersectionObserver)==null?void 0:s.disconnect()}),Bi.register(this)}static get DefaultTargetFrameRate(){return Wi._defaultTargetFramerate.value}static set DefaultTargetFrameRate(e){Wi._defaultTargetFramerate.value=e}static get DefaultWebGLRendererParameters(){return Wi._defaultWebglRendererParameters}get version(){return fc}static get Current(){return Bi.Current}static set Current(e){Bi.Current=e}appendHTMLElement(e){return this.domElement.shadowRoot?this.domElement.shadowRoot.appendChild(e):this.domElement.appendChild(e)}get resolutionScaleFactor(){return this._resolutionScaleFactor}set resolutionScaleFactor(e){if(e!==this._resolutionScaleFactor&&typeof e=="number"){if(e<=0){console.error("Invalid resolution scale factor",e);return}this._resolutionScaleFactor=e,this.updateSize()}}calculateBoundingClientRect(){if(this.isInAR){this._domX=0,this._domY=0;return}this._boundingClientRectFrame!==this.time.frame&&(this._boundingClientRectFrame=this.time.frame,this._boundingClientRect=this.domElement.getBoundingClientRect(),this._domX=this._boundingClientRect.x,this._domY=this._boundingClientRect.y)}get domWidth(){return this.isInAR?window.innerWidth:this.domElement.clientWidth}get domHeight(){return this.isInAR?window.innerHeight:this.domElement.clientHeight}get domX(){return this.calculateBoundingClientRect(),this._domX}get domY(){return this.calculateBoundingClientRect(),this._domY}get isInXR(){var e,t;return((t=(e=this.renderer)==null?void 0:e.xr)==null?void 0:t.isPresenting)||!1}get xrSessionMode(){var e;return(e=this.xr)==null?void 0:e.mode}get isInVR(){return this.xrSessionMode==="immersive-vr"}get isInAR(){return this.xrSessionMode==="immersive-ar"}get isInPassThrough(){return this.xr?this.xr.isPassThrough:!1}get xrSession(){var e,t;return(t=(e=this.renderer)==null?void 0:e.xr)==null?void 0:t.getSession()}get xrFrame(){return this._xrFrame}get xrCamera(){var e,t;return(t=(e=this.renderer)==null?void 0:e.xr)==null?void 0:t.getCamera()}get arOverlayElement(){const e=this.domElement;return typeof e.getAROverlayContainer=="function"?e.getAROverlayContainer():this.domElement}get currentFrameEvent(){return this._currentFrameEvent}get mainCamera(){if(this._camera)return this._camera;if(this.mainCameraComponent){const e=this.mainCameraComponent;return e.cam||e.buildCamera(),e.cam}return null}set mainCamera(e){this._camera=e}get rendererData(){return this.sceneLighting}get isCreated(){return this._isCreated}createNewRenderer(){var t,i,s;(t=this.renderer)==null||t.dispose();const e={...Wi.DefaultWebGLRendererParameters};if(!e.canvas){const r=(s=(i=this.domElement)==null?void 0:i.shadowRoot)==null?void 0:s.querySelector("canvas");r&&(e.canvas=r,Ur&&console.log("Using canvas from shadow root",r))}Ur&&console.log("Using Renderer Parameters:",e,this.domElement),this.renderer=new Bl(e),this.renderer.debug.checkShaderErrors=Mt()||se("checkshadererrors")===!0,this.renderer.toneMappingExposure=1,this.renderer.toneMapping=Wr,this.renderer.setClearColor(new ye("lightgrey"),0),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=hT,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputColorSpace=Wt,this.renderer.useLegacyLights=!1,this.input.bindEvents()}internalOnUpdateVisible(){var e,t;(e=this._intersectionObserver)==null||e.disconnect(),(t=this._intersectionObserver)==null||t.observe(this.domElement)}requestSizeUpdate(){this._sizeChanged=!0}updateSize(e=!1){var t,i,s;if(e||!this.isManagedExternally&&((t=this.renderer.xr)==null?void 0:t.isPresenting)===!1){this._sizeChanged=!1;const r=this.resolutionScaleFactor,o=this.domWidth*r,a=this.domHeight*r,c=this.mainCamera;this.updateAspect(c),this.renderer.setSize(o,a,!0),this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%",this.composer&&((i=this.composer.setSize)==null||i.call(this.composer,o,a),"setPixelRatio"in this.composer&&typeof this.composer.setPixelRatio=="function"&&((s=this.composer.setPixelRatio)==null||s.call(this.composer,window.devicePixelRatio)))}}updateAspect(e,t,i){if(!e)return;t===void 0&&(t=this.domWidth),i===void 0&&(i=this.domHeight);const s=e.aspect;e.aspect=t/i,s!==e.aspect&&e.updateProjectionMatrix()}recreate(){this.clear(),this.create(this._originalCreationArgs)}async onCreate(e){return this.create(e)}async create(e){try{this._isCreating=!0,e!==this._originalCreationArgs&&(this._originalCreationArgs=dA(e)),window.addEventListener("unhandledrejection",this.onUnhandledRejection);const t=await this.internalOnCreate(e);return this._isCreated=!0,t}finally{window.removeEventListener("unhandledrejection",this.onUnhandledRejection),this._isCreating=!1}}clear(){var e,t,i,s;Bi.dispatchCallback(Kn.ContextClearing,this),Ra(this.scene,!0,!0),this.scene=new rr,(e=this.addressables)==null||e.dispose(),(t=this.lightmaps)==null||t.clear(),(s=(i=this.physics)==null?void 0:i.engine)==null||s.clearCaches(),this.isManagedExternally||this.renderer&&(this.renderer.renderLists.dispose(),this.renderer.state.reset(),this.renderer.resetState()),Bi.dispatchCallback(Kn.ContextCleared,this)}dispose(){this.internalOnDestroy()}onDestroy(){this.internalOnDestroy()}internalOnDestroy(){var e,t;this.clear(),(e=this.renderer)==null||e.setAnimationLoop(null),this.renderer&&(this.renderer.setClearAlpha(0),this.renderer.clear(),this.isManagedExternally||(Ur&&console.log("Disposing renderer"),this.renderer.dispose())),this.scene=null,this.renderer=null,this.input.dispose();for(const i of this._disposeCallbacks)try{i()}catch(s){console.error("Error in on dispose callback:",s,i)}(t=this.domElement)!=null&&t.parentElement&&this.domElement.parentElement.removeChild(this.domElement),this._isCreated=!1,Bi.dispatchCallback(Kn.ContextDestroyed,this),Bi.unregister(this),Wi.Current===this&&(Wi.Current=null)}registerCoroutineUpdate(e,t,i){return typeof(t==null?void 0:t.next)!="function"?(console.error("Registered invalid coroutine function from "+e.name+`
4991
+ `,n);return}const t=(e==null?void 0:e.new_scripts)??Ot.Current.new_scripts;t.includes(n)||t.push(n)}const Wi=class{constructor(e){u(this,"name");u(this,"alias");u(this,"isManagedExternally",!1);u(this,"isPaused",!1);u(this,"runInBackground",!1);u(this,"targetFrameRate");u(this,"physicsSteps",1);u(this,"hash");u(this,"domElement");u(this,"_resolutionScaleFactor",1);u(this,"_boundingClientRectFrame",-1);u(this,"_boundingClientRect",null);u(this,"_domX");u(this,"_domY");u(this,"xr",null);u(this,"_xrFrame",null);u(this,"_currentFrameEvent",-1);u(this,"scene");u(this,"renderer");u(this,"composer",null);u(this,"scripts",[]);u(this,"scripts_pausedChanged",[]);u(this,"scripts_earlyUpdate",[]);u(this,"scripts_update",[]);u(this,"scripts_lateUpdate",[]);u(this,"scripts_onBeforeRender",[]);u(this,"scripts_onAfterRender",[]);u(this,"scripts_WithCorroutines",[]);u(this,"scripts_immersive_vr",[]);u(this,"scripts_immersive_ar",[]);u(this,"coroutines",{});u(this,"post_setup_callbacks",[]);u(this,"pre_update_callbacks",[]);u(this,"pre_render_callbacks",[]);u(this,"post_render_callbacks",[]);u(this,"pre_update_oneshot_callbacks",[]);u(this,"new_scripts",[]);u(this,"new_script_start",[]);u(this,"new_scripts_pre_setup_callbacks",[]);u(this,"new_scripts_post_setup_callbacks",[]);u(this,"new_scripts_xr",[]);u(this,"mainCameraComponent");u(this,"_camera",null);u(this,"application");u(this,"time");u(this,"input");u(this,"physics");u(this,"connection");u(this,"assets");u(this,"mainLight",null);u(this,"sceneLighting");u(this,"addressables");u(this,"lightmaps");u(this,"players");u(this,"_sizeChanged",!1);u(this,"_isCreated",!1);u(this,"_isCreating",!1);u(this,"_isVisible",!1);u(this,"_stats",$ee?new CY:null);u(this,"_intersectionObserver",null);u(this,"_disposeCallbacks",[]);u(this,"_originalCreationArgs");u(this,"onUnhandledRejection",e=>{this.domElement.dispatchEvent(new CustomEvent("error",{detail:e.reason}))});u(this,"_cameraStack",[]);u(this,"_onBeforeRenderListeners",new Map);u(this,"_onAfterRenderListeners",new Map);u(this,"_requireDepthTexture",!1);u(this,"_requireColorTexture",!1);u(this,"_renderTarget");u(this,"_isRendering",!1);u(this,"_createId",0);u(this,"_renderlooperrors",0);u(this,"_lastTimestamp",0);u(this,"_accumulatedTime",0);u(this,"_dispatchReadyAfterFrame",!1);u(this,"_wasPaused",!1);this.name=(e==null?void 0:e.name)||"",this.alias=e==null?void 0:e.alias,this.domElement=(e==null?void 0:e.domElement)||document.body,this.hash=e==null?void 0:e.hash,e!=null&&e.renderer&&(this.renderer=e.renderer,this.isManagedExternally=!0),(e==null?void 0:e.runInBackground)!==void 0&&(this.runInBackground=e.runInBackground),e!=null&&e.scene?this.scene=e.scene:this.scene=new rr,e!=null&&e.camera&&(this._camera=e.camera),this.application=new VN(this),this.time=new IG,this.input=new WN(this),this.physics=new wG(this),this.connection=new X3(this),this.assets=new nN,this.sceneLighting=new MG(this),this.addressables=new GN(this),this.lightmaps=new v7(this),this.players=new CG(this);const t=()=>this._sizeChanged=!0;window.addEventListener("resize",t),this._disposeCallbacks.push(()=>window.removeEventListener("resize",t));const i=new ResizeObserver(s=>this._sizeChanged=!0);i.observe(this.domElement),this._disposeCallbacks.push(()=>i.disconnect()),this._intersectionObserver=new IntersectionObserver(s=>{this._isVisible=s[0].isIntersecting}),this._disposeCallbacks.push(()=>{var s;return(s=this._intersectionObserver)==null?void 0:s.disconnect()}),Bi.register(this)}static get DefaultTargetFrameRate(){return Wi._defaultTargetFramerate.value}static set DefaultTargetFrameRate(e){Wi._defaultTargetFramerate.value=e}static get DefaultWebGLRendererParameters(){return Wi._defaultWebglRendererParameters}get version(){return fc}static get Current(){return Bi.Current}static set Current(e){Bi.Current=e}appendHTMLElement(e){return this.domElement.shadowRoot?this.domElement.shadowRoot.appendChild(e):this.domElement.appendChild(e)}get resolutionScaleFactor(){return this._resolutionScaleFactor}set resolutionScaleFactor(e){if(e!==this._resolutionScaleFactor&&typeof e=="number"){if(e<=0){console.error("Invalid resolution scale factor",e);return}this._resolutionScaleFactor=e,this.updateSize()}}calculateBoundingClientRect(){if(this.isInAR){this._domX=0,this._domY=0;return}this._boundingClientRectFrame!==this.time.frame&&(this._boundingClientRectFrame=this.time.frame,this._boundingClientRect=this.domElement.getBoundingClientRect(),this._domX=this._boundingClientRect.x,this._domY=this._boundingClientRect.y)}get domWidth(){return this.isInAR?window.innerWidth:this.domElement.clientWidth}get domHeight(){return this.isInAR?window.innerHeight:this.domElement.clientHeight}get domX(){return this.calculateBoundingClientRect(),this._domX}get domY(){return this.calculateBoundingClientRect(),this._domY}get isInXR(){var e,t;return((t=(e=this.renderer)==null?void 0:e.xr)==null?void 0:t.isPresenting)||!1}get xrSessionMode(){var e;return(e=this.xr)==null?void 0:e.mode}get isInVR(){return this.xrSessionMode==="immersive-vr"}get isInAR(){return this.xrSessionMode==="immersive-ar"}get isInPassThrough(){return this.xr?this.xr.isPassThrough:!1}get xrSession(){var e,t;return(t=(e=this.renderer)==null?void 0:e.xr)==null?void 0:t.getSession()}get xrFrame(){return this._xrFrame}get xrCamera(){var e,t;return(t=(e=this.renderer)==null?void 0:e.xr)==null?void 0:t.getCamera()}get arOverlayElement(){const e=this.domElement;return typeof e.getAROverlayContainer=="function"?e.getAROverlayContainer():this.domElement}get currentFrameEvent(){return this._currentFrameEvent}get mainCamera(){if(this._camera)return this._camera;if(this.mainCameraComponent){const e=this.mainCameraComponent;return e.cam||e.buildCamera(),e.cam}return null}set mainCamera(e){this._camera=e}get rendererData(){return this.sceneLighting}get isCreated(){return this._isCreated}createNewRenderer(e){var t,i,s;if((t=this.renderer)==null||t.dispose(),e={...Wi.DefaultWebGLRendererParameters,...e},!e.canvas){const r=(s=(i=this.domElement)==null?void 0:i.shadowRoot)==null?void 0:s.querySelector("canvas");r&&(e.canvas=r,Ur&&console.log("Using canvas from shadow root",r))}Ur&&console.log("Using Renderer Parameters:",e,this.domElement),this.renderer=new Bl(e),this.renderer.debug.checkShaderErrors=Mt()||se("checkshadererrors")===!0,this.renderer.toneMappingExposure=1,this.renderer.toneMapping=Wr,this.renderer.setClearColor(new ye("lightgrey"),0),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=hT,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputColorSpace=Wt,this.renderer.useLegacyLights=!1,this.input.bindEvents()}internalOnUpdateVisible(){var e,t;(e=this._intersectionObserver)==null||e.disconnect(),(t=this._intersectionObserver)==null||t.observe(this.domElement)}requestSizeUpdate(){this._sizeChanged=!0}updateSize(e=!1){var t,i,s;if(e||!this.isManagedExternally&&((t=this.renderer.xr)==null?void 0:t.isPresenting)===!1){this._sizeChanged=!1;const r=this.resolutionScaleFactor,o=this.domWidth*r,a=this.domHeight*r,c=this.mainCamera;this.updateAspect(c),this.renderer.setSize(o,a,!0),this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%",this.composer&&((i=this.composer.setSize)==null||i.call(this.composer,o,a),"setPixelRatio"in this.composer&&typeof this.composer.setPixelRatio=="function"&&((s=this.composer.setPixelRatio)==null||s.call(this.composer,window.devicePixelRatio)))}}updateAspect(e,t,i){if(!e)return;t===void 0&&(t=this.domWidth),i===void 0&&(i=this.domHeight);const s=e.aspect;e.aspect=t/i,s!==e.aspect&&e.updateProjectionMatrix()}recreate(){this.clear(),this.create(this._originalCreationArgs)}async onCreate(e){return this.create(e)}async create(e){try{this._isCreating=!0,e!==this._originalCreationArgs&&(this._originalCreationArgs=dA(e)),window.addEventListener("unhandledrejection",this.onUnhandledRejection);const t=await this.internalOnCreate(e);return this._isCreated=!0,t}finally{window.removeEventListener("unhandledrejection",this.onUnhandledRejection),this._isCreating=!1}}clear(){var e,t,i,s;Bi.dispatchCallback(Kn.ContextClearing,this),Ra(this.scene,!0,!0),this.scene=new rr,(e=this.addressables)==null||e.dispose(),(t=this.lightmaps)==null||t.clear(),(s=(i=this.physics)==null?void 0:i.engine)==null||s.clearCaches(),this.isManagedExternally||this.renderer&&(this.renderer.renderLists.dispose(),this.renderer.state.reset(),this.renderer.resetState()),Bi.dispatchCallback(Kn.ContextCleared,this)}dispose(){this.internalOnDestroy()}onDestroy(){this.internalOnDestroy()}internalOnDestroy(){var e,t;this.clear(),(e=this.renderer)==null||e.setAnimationLoop(null),this.renderer&&(this.renderer.setClearAlpha(0),this.renderer.clear(),this.isManagedExternally||(Ur&&console.log("Disposing renderer"),this.renderer.dispose())),this.scene=null,this.renderer=null,this.input.dispose();for(const i of this._disposeCallbacks)try{i()}catch(s){console.error("Error in on dispose callback:",s,i)}(t=this.domElement)!=null&&t.parentElement&&this.domElement.parentElement.removeChild(this.domElement),this._isCreated=!1,Bi.dispatchCallback(Kn.ContextDestroyed,this),Bi.unregister(this),Wi.Current===this&&(Wi.Current=null)}registerCoroutineUpdate(e,t,i){return typeof(t==null?void 0:t.next)!="function"?(console.error("Registered invalid coroutine function from "+e.name+`
4992
4992
  Coroutine functions must be generators: "*myCoroutine() {...}"
4993
4993
  Start a coroutine from a component by calling "this.startCoroutine(myCoroutine())"`),t):(this.coroutines[i]||(this.coroutines[i]=[]),this.coroutines[i].push({comp:e,main:t}),t)}unregisterCoroutineUpdate(e,t){if(!this.coroutines[t])return;const i=this.coroutines[t].findIndex(s=>s.main===e);i>=0&&this.coroutines[t].splice(i,1)}stopAllCoroutinesFrom(e){for(const t in this.coroutines){const i=this.coroutines[t];for(let s=i.length-1;s>=0;s--)i[s].comp===e&&i.splice(s,1)}}setCurrentCamera(e){var s;if(!e)return;if(e.cam||e.buildCamera(),!e.cam){console.warn("Camera component is missing camera",e);return}const t=this._cameraStack.indexOf(e);t>=0&&this._cameraStack.splice(t,1),this._cameraStack.push(e),this.mainCameraComponent=e;const i=e.cam;i.isPerspectiveCamera&&this.updateAspect(i),(s=this.mainCameraComponent)==null||s.applyClearFlagsIfIsActiveCamera()}removeCamera(e){if(!e)return;const t=this._cameraStack.indexOf(e);if(t>=0&&this._cameraStack.splice(t,1),this.mainCameraComponent===e&&(this.mainCameraComponent=void 0,this._cameraStack.length>0)){const i=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(i)}}addBeforeRenderListener(e,t){this._onBeforeRenderListeners.has(e.uuid)||(this._onBeforeRenderListeners.set(e.uuid,[]),e.onBeforeRender=this._createRenderCallbackWrapper(e,this._onBeforeRenderListeners)),this._onBeforeRenderListeners.get(e.uuid).push(t)}removeBeforeRenderListener(e,t){if(this._onBeforeRenderListeners.has(e.uuid)){const i=this._onBeforeRenderListeners.get(e.uuid),s=i.indexOf(t);s>=0&&i.splice(s,1)}}addAfterRenderListener(e,t){var i;this._onAfterRenderListeners.has(e.uuid)||(this._onAfterRenderListeners.set(e.uuid,[]),e.onAfterRender=this._createRenderCallbackWrapper(e,this._onAfterRenderListeners)),(i=this._onAfterRenderListeners.get(e.uuid))==null||i.push(t)}removeAfterRenderListener(e,t){if(this._onAfterRenderListeners.has(e.uuid)){const i=this._onAfterRenderListeners.get(e.uuid),s=i.indexOf(t);s>=0&&i.splice(s,1)}}_createRenderCallbackWrapper(e,t){return(i,s,r,o,a,c)=>{const l=t.get(e.uuid);if(l)for(let h=0;h<l.length;h++){const d=l[h];d(i,s,r,o,a,c)}}}get isRendering(){return this._isRendering}setRequireDepth(e){this._requireDepthTexture=e}setRequireColor(e){this._requireColorTexture=e}get depthTexture(){var e;return((e=this._renderTarget)==null?void 0:e.depthTexture)||null}get opaqueColorTexture(){var e;return((e=this._renderTarget)==null?void 0:e.texture)||null}get isVisibleToUser(){if(this.isInXR)return!0;if(!this._isVisible)return!1;const e=getComputedStyle(this.domElement);return e.visibility!=="hidden"&&e.display!=="none"&&e.opacity!=="0"}async internalOnCreate(e){var o,a,c,l,h;const t=++this._createId;Ur&&console.log("Creating context",this.name,e),this.clear(),this.isManagedExternally===!1&&(this.createNewRenderer(),(o=this.renderer)==null||o.setAnimationLoop(null)),await Yo(1),Wi.Current=this,await Bi.dispatchCallback(Kn.ContextCreationStart,this);let i=!0,s;try{Wi.Current=this,e?s=await this.internalLoadInitialContent(t,e):s=[]}catch(d){console.error(d),i=!1}if(!i||t!==this._createId)return!1;if(this.internalOnUpdateVisible(),!this.renderer)return Ur&&console.warn("Context has no renderer (perhaps it was disconnected?",this.domElement.isConnected),!1;!this.isManagedExternally&&!this.domElement.shadowRoot&&this.domElement.prepend(this.renderer.domElement),Wi.Current=this,Wi.Current=this;for(let d=0;d<this.new_scripts.length;d++){const f=this.new_scripts[d];if(f.gameObject!==void 0&&f.gameObject!==null){f.gameObject.userData===void 0&&(f.gameObject.userData={}),f.gameObject.userData.components===void 0&&(f.gameObject.userData.components=[]);const p=f.gameObject.userData.components;p.includes(f)||p.push(f)}}if(this.post_setup_callbacks)for(let d=0;d<this.post_setup_callbacks.length;d++)Wi.Current=this,await this.post_setup_callbacks[d](this);if(!this.mainCamera){Wi.Current=this;let d=null;xd(this.scene,f=>{const p=f;if(p!=null&&p.isCamera){if(Fg(p.gameObject),!p.activeAndEnabled)return;if(p.tag==="MainCamera")return d=p,!0;d=p}}),d?this.setCurrentCamera(d):!Bi.dispatchCallback(Kn.MissingCamera,this,{files:s})&&!this.mainCamera&&!this.isManagedExternally&&console.warn("Missing camera in main scene",this)}if(this.input.bindEvents(),Wi.Current=this,gb(this),this.physics.engine&&((a=this.physics.engine)==null||a.step(0),(c=this.physics.engine)==null||c.postStep()),!this.isManagedExternally&&this.composer&&this.mainCamera){const d=new qx(this.scene,this.mainCamera);this.renderer.setSize(this.domWidth,this.domHeight),this.composer.addPass(d),this.composer.setSize(this.domWidth,this.domHeight)}this._sizeChanged=!0,this._stats&&(this._stats.showPanel(0),(l=this.domElement.shadowRoot)==null||l.appendChild(this._stats.dom)),Ur&&Db(this.scene,!0),this.targetFrameRate===void 0?(Ur&&console.warn("No target framerate set, using default",Wi.DefaultTargetFrameRate),this.targetFrameRate=Wi._defaultTargetFramerate):Ur&&console.log("Target framerate set to",this.targetFrameRate),this._dispatchReadyAfterFrame=!0;const r=Bi.dispatchCallback(Kn.ContextCreated,this,{files:s});return r&&("internalSetLoadingMessage"in this.domElement&&typeof this.domElement.internalSetLoadingMessage=="function"&&((h=this.domElement)==null||h.internalSetLoadingMessage("finish loading")),await r),bu(this,Kn.ContextCreated),Ur&&console.log("Context Created...",this.renderer,this.renderer.domElement),this._isCreating=!1,this.isManagedExternally||this.restartRenderLoop(),r}async internalLoadInitialContent(e,t){var c,l;const i=new Array;if(t.files.length===0)return i;const s=[...t.files],r={name:"",progress:null,index:0,count:s.length},o=Ia(),a=0;for(let h=0;h<s.length;h++){if(e!==this._createId){Ur&&console.log("Aborting loading because create id changed",e,this._createId);break}const d=s[h];if(!d.includes(".glb")&&!d.includes(".gltf")){const p=`Needle Engine: found suspicious src "${d}"`;console.warn(p),Er()&&pn(p)}(c=t==null?void 0:t.onLoadingStart)==null||c.call(this,h,d),Ur&&console.log("Context Load "+d);const f=await o.loadSync(this,d,d,a,p=>{var m;r.name=d,r.progress=p,r.index=h,r.count=s.length,(m=t.onLoadingProgress)==null||m.call(this,r)});(l=t==null?void 0:t.onLoadingFinished)==null||l.call(this,h,d,f??null),f?i.push({src:d,file:f}):console.warn("Could not load file: "+d)}if(e!==this._createId){for(const h of i)if(h&&h.file)for(const d of h.file.scenes)Ra(d,!0,!0)}else for(const h of i)h&&h.file&&this.scene.add(h.file.scene);return i}restartRenderLoop(){return this.renderer?this._isCreating?(console.warn("Can not start render loop while creating context"),!1):(this.renderer.setAnimationLoop((e,t)=>{this.isManagedExternally||this.update(e,t)}),!0):(console.error("Can not start render loop without renderer"),!1)}update(e,t){if(t===void 0&&(t=null),Mt()||Ur||fq())try{this.internalStep(e,t),this._renderlooperrors=0}catch(i){this._renderlooperrors+=1,(Mt()||Ur)&&(i instanceof Error||i instanceof TypeError)&&xn("Caught unhandled exception during render-loop - see console for details.",Jo.Error),console.error("Frame #"+this.time.frame+`
4994
- `,i),this._renderlooperrors>=3&&(console.warn("Stopping render loop due to error"),this.renderer.setAnimationLoop(null)),this.domElement.dispatchEvent(new CustomEvent("error",{detail:i}))}else this.internalStep(e,t)}updatePhysics(e){this.internalUpdatePhysics(e)}internalStep(e,t){this.internalOnBeforeRender(e,t)!==!1&&(this.internalOnRender(),this.internalOnAfterRender())}internalOnBeforeRender(e,t){var s;const i=t!==null&&this._xrFrame===null;if(this._xrFrame=t,i&&this.domElement.dispatchEvent(new CustomEvent("xr-session-started",{detail:{context:this,session:this.xrSession,frame:t}})),this._currentFrameEvent=-1,this.isManagedExternally===!1&&this.isInXR===!1&&this.targetFrameRate!==void 0){this._lastTimestamp===0&&(this._lastTimestamp=e),this._accumulatedTime+=(e-this._lastTimestamp)/1e3,this._lastTimestamp=e;let r=this.targetFrameRate;if(typeof r=="object"&&(r=r.value),this._accumulatedTime<1/(r+1))return!1;this._accumulatedTime=0}if((s=this._stats)==null||s.begin(),Wi.Current=this,this.onHandlePaused())return!1;for(Wi.Current=this,this.time.update(),tte&&console.log("FPS",this.time.smoothedFps.toFixed(0)),gb(this),b_(this.scene),dN(this),bu(this,-1);this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);const r=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(r)}if(this.pre_update_oneshot_callbacks){for(const r in this.pre_update_oneshot_callbacks)this.pre_update_oneshot_callbacks[r]();this.pre_update_oneshot_callbacks.length=0}if(this.pre_update_callbacks)for(const r in this.pre_update_callbacks)this.pre_update_callbacks[r]();this._currentFrameEvent=0;for(let r=0;r<this.scripts_earlyUpdate.length;r++){const o=this.scripts_earlyUpdate[r];o.activeAndEnabled&&o.earlyUpdate!==void 0&&(Wi.Current=this,o.earlyUpdate())}if(this.executeCoroutines(0),bu(this,0),this.onHandlePaused())return!1;this._currentFrameEvent=1;for(let r=0;r<this.scripts_update.length;r++){const o=this.scripts_update[r];o.activeAndEnabled&&o.update!==void 0&&(Wi.Current=this,o.update())}if(this.executeCoroutines(1),bu(this,1),this.onHandlePaused())return!1;this._currentFrameEvent=2;for(let r=0;r<this.scripts_lateUpdate.length;r++){const o=this.scripts_lateUpdate[r];o.activeAndEnabled&&o.lateUpdate!==void 0&&(Wi.Current=this,o.lateUpdate())}if(this.executeCoroutines(2),bu(this,2),this.onHandlePaused()||(this.physicsSteps===void 0&&(this.physicsSteps=1),this.physics.engine&&this.physicsSteps>0&&this.internalUpdatePhysics(this.physicsSteps),this.onHandlePaused()))return!1;if(this.isVisibleToUser||this.runInBackground){this._currentFrameEvent=3;for(let r=0;r<this.scripts_onBeforeRender.length;r++){const o=this.scripts_onBeforeRender[r];o.activeAndEnabled&&o.onBeforeRender!==void 0&&(Wi.Current=this,o.onBeforeRender(t))}if(this.executeCoroutines(3),bu(this,3),this._sizeChanged&&this.updateSize(),this.pre_render_callbacks)for(const r in this.pre_render_callbacks)this.pre_render_callbacks[r](t)}return!0}internalUpdatePhysics(e){if(!this.physics.engine)return!1;const t=e,i=this.time.deltaTime/t;for(let s=0;s<t;s++)this._currentFrameEvent=9,this.executeCoroutines(9),this.physics.engine.step(i),this._currentFrameEvent=10,this.executeCoroutines(10);return this.physics.engine.postStep(),!0}internalOnRender(){this.isManagedExternally||(gq(this),this._currentFrameEvent=-1,this.renderNow(),this._currentFrameEvent=4)}internalOnAfterRender(){if(this.isVisibleToUser||this.runInBackground){for(let e=0;e<this.scripts_onAfterRender.length;e++){const t=this.scripts_onAfterRender[e];t.activeAndEnabled&&t.onAfterRender!==void 0&&(Wi.Current=this,t.onAfterRender())}if(this.executeCoroutines(4),bu(this,4),this.post_render_callbacks)for(const e in this.post_render_callbacks)this.post_render_callbacks[e]()}this._currentFrameEvent=-1,this.connection.sendBufferedMessagesNow(),this._stats&&(this._stats.end(),this.time.frameCount%150===0&&console.log({...this.renderer.info.memory},{...this.renderer.info.render})),this._dispatchReadyAfterFrame&&(this._dispatchReadyAfterFrame=!1,this.domElement.dispatchEvent(new CustomEvent("ready")),Bi.dispatchCallback(Kn.ContextFirstFrameRendered,this))}renderNow(e){return!e&&(e=this.mainCamera,!e)?!1:(this._isRendering=!0,this.renderRequiredTextures(),this.composer&&!this.isInXR?this.composer.render(this.time.deltaTime):e&&this.renderer.render(this.scene,e),this._isRendering=!1,!0)}onHandlePaused(){const e=this.evaluatePaused();if(this._wasPaused!==e){ete&&console.log("Paused?",e,"context:"+this.alias);for(let t=0;t<this.scripts_pausedChanged.length;t++){const i=this.scripts_pausedChanged[t];i.activeAndEnabled&&i.onPausedChanged!==void 0&&(Wi.Current=this,i.onPausedChanged(e,this._wasPaused))}}return this._wasPaused=e,e}evaluatePaused(){return this.isInXR?!1:this.isPaused?!0:this.runInBackground?!1:!this.isVisibleToUser}renderRequiredTextures(){if(!this.mainCamera||!this._requireDepthTexture&&!this._requireColorTexture)return;if(!this._renderTarget){if(this._renderTarget=new ti(this.domWidth,this.domHeight),this._requireDepthTexture){const i=new zp(this.domWidth,this.domHeight);this._renderTarget.depthTexture=i}this._requireColorTexture&&(this._renderTarget.texture=new Ht,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=jt,this._renderTarget.texture.magFilter=jt,this._renderTarget.texture.format=Ci)}const e=this._renderTarget;e.texture&&(e.texture.colorSpace=this.renderer.outputColorSpace);const t=this.renderer.getRenderTarget();this.renderer.setRenderTarget(e),this.renderer.render(this.scene,this.mainCamera),this.renderer.setRenderTarget(t)}executeCoroutines(e){var i;if(this.coroutines[e]){const s=this.coroutines[e];for(let r=0;r<s.length;r++)try{const o=s[r];if(!o.comp||o.comp.destroyed||!o.main||o.comp.enabled===!1){ite&&console.log("Removing coroutine",o.comp,o.comp.enabled),s.splice(r,1),--r;continue}const c=o.chained;if(c&&c.length>0){const f=c[c.length-1].next();if(f.done&&c.pop(),t(f)&&(o.chained||(o.chained=[]),o.chained.push(f.value)),!f.done)continue}const l=o.main.next();if(l.done===!0){s.splice(r,1),--r;continue}const h=l.value;if(t(h)){if(h.next().done)continue;o.chained||(o.chained=[]),o.chained.push(h)}else if(h instanceof Promise){const d=h;o.chained||(o.chained=[]);const f=jN(d);(i=o.chained)==null||i.push(f);continue}}catch(o){console.error(o)}}function t(s){return!!(s&&s.next&&s.return)}}};let Ot=Wi;u(Ot,"_defaultTargetFramerate",{value:60}),u(Ot,"_defaultWebglRendererParameters",{antialias:!0,alpha:!1});Bi.registerCallback(Kn.ContextCreated,n=>{const e=n.context;kG(e),DG(e)});const Fb=se("debugcomponents"),yk="eff8ba80-635d-11ec-90d6-0242ac120003";class ms{constructor(e){u(this,"_originalSeed");u(this,"_seed");typeof e=="string"&&(e=ms.hash(e)),this._originalSeed=e,this._seed=e}get seed(){return this._seed}set seed(e){this._seed=e}reset(){this._seed=this._originalSeed}generateUUID(e){if(typeof e=="string")return ZD(e,yk);const t=this._seed;return this._seed-=1,ZD(t.toString(),yk)}initialize(e){typeof e=="string"?this._seed=ms.hash(e):this._seed=e}static createFromString(e){return new ms(this.hash(e))}static hash(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);return t}}var RG=(n=>(n.NewInstanceCreated="new-instance-created",n.InstanceDestroyed="instance-destroyed",n))(RG||{});class PG{constructor(e){u(this,"guid");this.guid=e}}function aw(n,e,t=!0){if(!n)return;const i=n;if(Ra(n,t),!e){console.warn("Can not send destroy: No networking connection provided",n.guid);return}if(!e.isConnected){console.warn("Can not send destroy: not connected",n.guid);return}let s=n.guid;if(!s&&i.uuid&&(s=i.uuid),!s){console.warn("Can not send destroy: failed to find guid",n);return}const r=new PG(s);e.send("instance-destroyed",r,ba.Queued)}function BG(n,e){const t=new PG(n);e.send("instance-destroyed",t,ba.Queued)}function DG(n){n.connection.beginListen("instance-destroyed",e=>{Fb&&console.log("[Remote] Destroyed",n.scene,e);const t=TA(e.guid,n.scene);t&&Ra(t)})}class rte{constructor(e,t,i){u(this,"filename");u(this,"hash");u(this,"size");this.filename=e,this.hash=t,this.size=i}}class OG{constructor(e,t){u(this,"guid");u(this,"originalGuid");u(this,"seed");u(this,"visible");u(this,"hostData");u(this,"dontSave");u(this,"parent");u(this,"position");u(this,"rotation");u(this,"scale");u(this,"preventCreation");this.originalGuid=e,this.guid=t}}function SR(n,e,t,i){var c;const s=n;if(!s.guid)return console.warn("Can not instantiate: No guid",s),null;if(e.context||(e.context=Ot.Current),!e.context)return console.error("Missing network instantiate options / reference to network connection in sync instantiate"),null;const r=e?{...e}:null,{instance:o,seed:a}=ote(s,e);if(o){const l=o;if(l.guid){Fb&&console.log("[Local] new instance","gameobject:",o==null?void 0:o.guid);const h=new OG(s.guid,l.guid);h.seed=a,r&&(r.position&&(h.position={x:r.position.x,y:r.position.y,z:r.position.z}),r.rotation&&(h.rotation={x:r.rotation.x,y:r.rotation.y,z:r.rotation.z,w:r.rotation.w}),r.scale&&(h.scale={x:r.scale.x,y:r.scale.y,z:r.scale.z})),h.position||(h.position={x:l.position.x,y:l.position.y,z:l.position.z}),h.rotation||(h.rotation={x:l.quaternion.x,y:l.quaternion.y,z:l.quaternion.z,w:l.quaternion.w}),h.scale||(h.scale={x:l.scale.x,y:l.scale.y,z:l.scale.z}),h.visible=s.visible,r!=null&&r.parent&&(typeof r.parent=="string"?h.parent=r.parent:h.parent=r.parent.guid),h.hostData=t,i===!1&&(h.dontSave=!0),(c=e==null?void 0:e.context)==null||c.connection.send("new-instance-created",h)}else console.warn("Missing guid, can not send new instance event",l)}return o}function cw(){return Math.random()*9999999}function kG(n){n.connection.beginListen("new-instance-created",async e=>{const t=await ate(e.originalGuid,n.scene);if(e.preventCreation===!0)return;if(!t){console.warn("could not find object that was instantiated: "+e.guid);return}const i=new Fa;e.position&&(i.position=new w(e.position.x,e.position.y,e.position.z)),e.rotation&&(i.rotation=new Ee(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w)),e.scale&&(i.scale=new w(e.scale.x,e.scale.y,e.scale.z)),i.parent=e.parent,e.seed&&(i.idProvider=new ms(e.seed)),i.visible=e.visible,i.context=n,Fb&&n.alias&&console.log("[Remote] instantiate in: "+n.alias);const s=em(t,i);s&&(e.parent==="scene"&&n.scene.add(s),Fb&&console.log("[Remote] new instance","gameobject:",s==null?void 0:s.guid,t))})}function ote(n,e){const t=cw(),i=e??new Fa;i.idProvider=new ms(t);const s=em(n,i);return{seed:t,instance:s}}const LG={};function FG(n,e){LG[n]=e}async function ate(n,e){const t=LG[n];if(t!=null){const i=await t(n);if(i)return i}return UG(n,e)}function UG(n,e){if(e===null||!n)return null;if(e.guid===n)return e;if(e.children)for(const t of e.children){const i=UG(n,t);if(i)return i}return null}const P_=se("debuggetcomponent"),B_=se("debuginstantiate");var NG=(n=>(n[n.None=0]="None",n[n.HideInHierarchy=1]="HideInHierarchy",n[n.HideInInspector=2]="HideInInspector",n[n.DontSaveInEditor=4]="DontSaveInEditor",n[n.NotEditable=8]="NotEditable",n[n.DontSaveInBuild=16]="DontSaveInBuild",n[n.DontUnloadUnusedAsset=32]="DontUnloadUnusedAsset",n[n.DontSave=52]="DontSave",n[n.HideAndDontSave=61]="HideAndDontSave",n))(NG||{});class Fa{constructor(){u(this,"idProvider");u(this,"parent");u(this,"keepWorldPosition");u(this,"position");u(this,"rotation");u(this,"scale");u(this,"visible");u(this,"context")}clone(){var t,i,s;const e=new Fa;return e.idProvider=this.idProvider,e.parent=this.parent,e.keepWorldPosition=this.keepWorldPosition,e.position=(t=this.position)==null?void 0:t.clone(),e.rotation=(i=this.rotation)==null?void 0:i.clone(),e.scale=(s=this.scale)==null?void 0:s.clone(),e}cloneAssign(e){var t,i,s;this.idProvider=e.idProvider,this.parent=e.parent,this.keepWorldPosition=e.keepWorldPosition,this.position=(t=e.position)==null?void 0:t.clone(),this.rotation=(i=e.rotation)==null?void 0:i.clone(),this.scale=(s=e.scale)==null?void 0:s.clone()}}function $p(n){return n.visible}function Qg(n,e){return typeof e=="number"&&(e=e>.5),n.visible=e,n.visible}function zG(n){return n[_l]||lw(n)}function GG(n,e){n[hN]=e}function lw(n){return Ma.isUsingInstancing(n)}function TA(n,e){return Mp(n,e,!0,!0)}const HG=Symbol("isDestroyed");function bd(n){return n[HG]}function VG(n,e){n[HG]=e}const gM=Symbol("isDontDestroy");function vM(n,e=!0){n[gM]=e}const D_=[],O_=[];function Ra(n,e=!0,t=!1){D_.length=0,O_.length=0,AM(n,e,t,!0);for(const i of D_)i.gameObject=null,i.context=null;for(const i of O_)VG(i,!0),t&&Gi(i),cN(i);O_.length=0,D_.length=0}function AM(n,e=!0,t=!1,i=!0){if(n==null)return;const s=n;if(s.isComponent){if(s[gM])return;D_.push(s);const a=s.gameObject;s.__internalDisable(),s.__internalDestroy(),s.gameObject=a;return}if(n[gM])return;const r=n;P_&&console.log(r),O_.push(r);const o=r.userData.components;if(o){let a=o.length;for(let c=0;c<o.length;c++){const l=o[c];AM(l,e,t,!1),o.length<a&&(a=o.length,c--)}}if(e&&r.children)for(const a of r.children)AM(a,e,t,!1);i&&r.removeFromParent()}function xd(n,e,t=!0){return QG(n,e,t)}function*CR(n,e,t=!1,i=999,s=0){if(n!=null&&n.userData.components&&!(s>i)){for(const r of n.userData.components)e&&(r==null?void 0:r.isComponent)===!0&&r instanceof e?yield r:yield r;if(t===!0)for(const r of n.children)yield*CR(r,e,!0,i,s+1)}}function QG(n,e,t,i=0){var s;if(n){if(n.isObject3D,i>1e3){console.warn("Failed to iterate components: too many levels");return}if((s=n.userData)!=null&&s.components)for(let r=0;r<n.userData.components.length;r++){const o=n.userData.components[r];if((o==null?void 0:o.isComponent)===!0){const a=e(o);if(a!==void 0)return a}}if(t&&n.children){const r=i+1;for(let o=0;o<n.children.length;o++){const a=n.children[o];if(!a)continue;const c=QG(a,e,t,r);if(c!==void 0)return c}}}}function em(n,e=null){let t=null;e!==null&&(e.x!==void 0?(t=new Fa,t.position=e):t=e);let i=Ot.Current;t!=null&&t.context&&(i=t.context),P_&&i.alias&&console.log("context",i.alias),t&&!t.idProvider&&(t.idProvider=new ms(Date.now()));const s=[],r={},o={},a=jG(i,n,t,s,r,o);a&&(lte(r),cte(o,r)),P_&&(Db(n,!0),Db(a,!0));const c={};for(const l in s){const h=s[l],d=h.guid;t&&t.idProvider&&(h.guid=t.idProvider.generateUUID(),c[d]=h.guid,P_&&console.log(h.name,h.guid)),ow(h,i),h.__internalNewInstanceCreated&&h.__internalNewInstanceCreated()}for(const l in s){const h=s[l];h.resolveGuids&&h.resolveGuids(c),h.enabled!==!1&&(h.enabled=!0)}return gb(i),a}function jG(n,e,t,i,s,r){var h;if(!e)return null;const o=e.userData;e.userData={};const a=e.children;e.children=[];const c=e.clone(!1);if(hw(c),e.userData=o,e.children=a,s[e.uuid]={original:e,clone:c},B_&&console.log("ADD",e,c),e.type==="SkinnedMesh"&&(r[e.uuid]={original:e,clone:c}),(t==null?void 0:t.visible)!==void 0&&(c.visible=t.visible),t!=null&&t.idProvider){c.uuid=t.idProvider.generateUUID();const d=c;d&&(d.guid=c.uuid)}e.animations&&e.animations.length>0&&(c.animations=[...e.animations]);const l=e.parent;if(l&&l.add(c),t!=null&&t.position?sr(c,t.position):c.position.copy(e.position),t!=null&&t.rotation?ea(c,t.rotation):c.quaternion.copy(e.quaternion),t!=null&&t.scale?c.scale.copy(t.scale):c.scale.copy(e.scale),t!=null&&t.parent&&t.parent!=="scene"){let d=null;if(typeof t.parent=="string"?d=Mp(t.parent,n.scene,!0):d=t.parent,d){const f=t.keepWorldPosition===!0?d.attach:d.add;f?f.call(d,c):console.error("Invalid parent object",d,"received when instantiating:",e)}else console.warn("could not find parent:",t.parent)}for(const[d,f]of Object.entries(e.userData))d!=="components"&&(c.userData[d]=f);if((h=e.userData)!=null&&h.components){const d=e.userData.components,f=[];c.userData.components=f;for(let p=0;p<d.length;p++){const m=d[p],g=new m.constructor;Tp(g,m),m[Lg]!==void 0&&(g[Lg]=m[Lg]),f.push(g),g.gameObject=c,i.push(g),mA.dispatchComponentLifecycleEvent(pA.Added,g)}}t&&(t.position=void 0,t.rotation=void 0,t.scale=void 0,t.parent=void 0);for(const d in e.children){const f=e.children[d],p=jG(n,f,t,i,s,r);p&&c.add(p)}return c}function cte(n,e){for(const t in n){const i=n[t],s=i.original,r=s.skeleton,o=i.clone;if(!r){console.warn("Skinned mesh has no skeleton?",i);continue}const a=r.bones,c=o.skeleton.clone();o.skeleton=c,o.bindMatrix.clone().copy(s.bindMatrix),o.bindMatrixInverse.copy(s.bindMatrixInverse);const l=[];c.bones=l;for(let h=0;h<a.length;h++){const d=a[h],p=e[d.uuid].clone;l.push(p)}}for(const t in n){const i=n[t].clone;i.skeleton.update(),i.bind(i.skeleton,i.bindMatrix),i.updateMatrixWorld(!0)}}function lte(n){var e;for(const t in n){const s=n[t].clone;if((e=s.userData)!=null&&e.components)for(let r=0;r<s.userData.components.length;r++){const o=s.userData.components[r],a=Object.entries(o);for(const[c,l]of a)if(Array.isArray(l)){const h=[];o[c]=h;for(let d=0;d<l.length;d++){const f=l[d];if(typeof f!="object"){h.push(f);continue}const p=_k(o,c,f,n);p!==void 0?h.push(p):h.push(f)}}else if(typeof l=="object"){const h=_k(o,c,l,n);h!==void 0&&(o[c]=h)}}}}function _k(n,e,t,i){var s,r;if(t!=null)if(t.isComponent===!0){const o=t.gameObject;if(o){const a=o.uuid,c=(s=i[a])==null?void 0:s.clone;if(!c){B_&&console.log("reference did not change",e,n,t);return}const l=o.userData.components.indexOf(t);if(l>=0)return B_&&console.log(e,a),c.userData.components[l];console.warn("could not find component",e,t)}}else if(t.isObject3D===!0){if(e==="gameObject")return;const o=t;if(o){const a=o.uuid,c=(r=i[a])==null?void 0:r.clone;if(c)return B_&&console.log(e,"old",t,"new",c),c}}else{if(t.isVector4||t.isVector3||t.isVector2||t.isQuaternion||t.isEuler)return t.clone();if(t.isColor===!0)return t.clone();if(t.isEventList===!0)return new t.constructor}}const WG=new Map;function hte(n,e){if(!n)return;if(!e){console.warn("No prototype found",n,n.prototype,n.constructor);return}const t=WG.get(e);t&&t.apply(n)}function ute(n){const e=dte(n.prototype);WG.set(n,e)}function dte(n){return new fte(n)}class fte{constructor(e){u(this,"$symbol");u(this,"extensions");u(this,"descriptors");this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(e),this.descriptors=new Array;for(let t=0;t<this.extensions.length;t++){const i=this.extensions[t],s=Object.getOwnPropertyDescriptor(e,i);s&&this.descriptors.push(s)}}apply(e){if(!e[this.$symbol]){e[this.$symbol]=!0;for(let t=0;t<this.extensions.length;t++){const i=this.extensions[t],s=this.descriptors[t];s&&Object.defineProperty(e,i,s)}}}}function hw(n){n&&n.isObject3D===!0&&hte(n,ge)}ge.prototype.SetActive=function(n){this.visible=n};ge.prototype.setActive=function(n){this.visible=n};ge.prototype.destroy=function(){Ra(this)};ge.prototype.addComponent=function(n){return MR(this,n)};ge.prototype.addNewComponent=function(n){return Xh(this,new n)};ge.prototype.removeComponent=function(n){return ER(this,n)};ge.prototype.getOrAddComponent=function(n){return uw(this,n)};ge.prototype.getComponent=function(n){return tm(this,n)};ge.prototype.getComponents=function(n,e){return IA(this,n,e)};ge.prototype.getComponentInChildren=function(n){return RA(this,n)};ge.prototype.getComponentsInChildren=function(n,e){return PA(this,n,e)};ge.prototype.getComponentInParent=function(n){return Lv(this,n)};ge.prototype.getComponentsInParent=function(n,e){return dw(this,n,e)};Object.getOwnPropertyDescriptor(ge.prototype,"activeSelf")||Object.defineProperty(ge.prototype,"activeSelf",{get:function(){return $p(this)},set:function(n){Qg(this,n)}});Object.getOwnPropertyDescriptor(ge.prototype,"transform")||Object.defineProperty(ge.prototype,"transform",{get:function(){return this}});Object.getOwnPropertyDescriptor(ge.prototype,"worldPosition")||Object.defineProperty(ge.prototype,"worldPosition",{get:function(){return this instanceof uI?Dt(this.object):Dt(this)},set:function(n){sr(this,n)}});Object.getOwnPropertyDescriptor(ge.prototype,"worldQuaternion")||Object.defineProperty(ge.prototype,"worldQuaternion",{get:function(){return this instanceof uI?Di(this.object):Di(this)},set:function(n){ea(this,n)}});Object.getOwnPropertyDescriptor(ge.prototype,"worldRotation")||Object.defineProperty(ge.prototype,"worldRotation",{get:function(){return CA(this)},set:function(n){bR(this,n)}});Object.getOwnPropertyDescriptor(ge.prototype,"worldScale")||Object.defineProperty(ge.prototype,"worldScale",{get:function(){return hn(this)},set:function(n){kv(this,n)}});Object.getOwnPropertyDescriptor(ge.prototype,"worldForward")||Object.defineProperty(ge.prototype,"worldForward",{get:function(){return Gn().set(0,0,1).applyQuaternion(Di(this))}});Object.getOwnPropertyDescriptor(ge.prototype,"worldRight")||Object.defineProperty(ge.prototype,"worldRight",{get:function(){return Gn().set(1,0,0).applyQuaternion(Di(this))}});Object.getOwnPropertyDescriptor(ge.prototype,"worldUp")||Object.defineProperty(ge.prototype,"worldUp",{get:function(){return Gn().set(0,1,0).applyQuaternion(Di(this))}});ute(ge);const TC=se("debuggetcomponent");function pte(n){return n==null||n.isObject3D?n:n.object&&n.object.isObject3D?n.object:n}function ER(n,e){if(!n||!n.userData.components)return;const t=n.userData.components.indexOf(e);t<0||(mA.dispatchComponentLifecycleEvent(pA.Removing,e),e.gameObject=null,n.userData.components.splice(t,1))}function uw(n,e){const t=tm(n,e);if(t)return t;const i=new e;return Xh(n,i)}const qG=new ms("addComponentIdProvider");function Xh(n,e,t=!0){n.userData||(n.userData={}),n.userData.components||(n.userData.components=[]),n.userData.components.push(e),e.gameObject=n,(e.guid===void 0||e.guid==="invalid")&&(e.guid=qG.generateUUID()),hw(n),ow(e);try{t&&e.__internalAwake&&(Fg(n),e.activeAndEnabled&&e.__internalAwake()),mA.dispatchComponentLifecycleEvent(pA.Added,e)}catch(i){console.error(i)}return e}function MR(n,e){if(typeof e=="function")return Xh(n,new e);if(e.destroyed)return console.warn("Can not move/add a destroyed component",e),e;if(e.gameObject===n)return e;if(e.gameObject&&e.gameObject.userData.components){const t=e.gameObject.userData.components.indexOf(e);e.gameObject.userData.components.splice(t,1)}if(!n.userData.components)n.userData.components=[];else if(n.userData.components.includes(e))return e;return n.userData.components.push(e),e.gameObject=n,(e.guid===void 0||e.guid==="invalid")&&(e.guid=qG.generateUUID()),ow(e),e}function XG(n){if(n.gameObject&&n.gameObject.userData.components){const e=n.gameObject.userData.components.indexOf(n);n.gameObject.userData.components.splice(e,1)}n.__internalDisable&&n.__internalDisable(),ol(n,n.context??Ot.Current),n.destroy(),n.gameObject=null}let bk=!1;function YG(n,e,t){var i;if(n==null)return null;if(!n.isObject3D)return console.error("Object is not object3D"),null;if(!((i=n==null?void 0:n.userData)!=null&&i.components)||(typeof e=="string"&&(bk||(bk=!0,console.warn(`Accessing components by name is not supported.
4994
+ `,i),this._renderlooperrors>=3&&(console.warn("Stopping render loop due to error"),this.renderer.setAnimationLoop(null)),this.domElement.dispatchEvent(new CustomEvent("error",{detail:i}))}else this.internalStep(e,t)}updatePhysics(e){this.internalUpdatePhysics(e)}internalStep(e,t){this.internalOnBeforeRender(e,t)!==!1&&(this.internalOnRender(),this.internalOnAfterRender())}internalOnBeforeRender(e,t){var s;const i=t!==null&&this._xrFrame===null;if(this._xrFrame=t,i&&this.domElement.dispatchEvent(new CustomEvent("xr-session-started",{detail:{context:this,session:this.xrSession,frame:t}})),this._currentFrameEvent=-1,this.isManagedExternally===!1&&this.isInXR===!1&&this.targetFrameRate!==void 0){this._lastTimestamp===0&&(this._lastTimestamp=e),this._accumulatedTime+=(e-this._lastTimestamp)/1e3,this._lastTimestamp=e;let r=this.targetFrameRate;if(typeof r=="object"&&(r=r.value),this._accumulatedTime<1/(r+1))return!1;this._accumulatedTime=0}if((s=this._stats)==null||s.begin(),Wi.Current=this,this.onHandlePaused())return!1;for(Wi.Current=this,this.time.update(),tte&&console.log("FPS",this.time.smoothedFps.toFixed(0)),gb(this),b_(this.scene),dN(this),bu(this,-1);this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);const r=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(r)}if(this.pre_update_oneshot_callbacks){for(const r in this.pre_update_oneshot_callbacks)this.pre_update_oneshot_callbacks[r]();this.pre_update_oneshot_callbacks.length=0}if(this.pre_update_callbacks)for(const r in this.pre_update_callbacks)this.pre_update_callbacks[r]();this._currentFrameEvent=0;for(let r=0;r<this.scripts_earlyUpdate.length;r++){const o=this.scripts_earlyUpdate[r];o.activeAndEnabled&&o.earlyUpdate!==void 0&&(Wi.Current=this,o.earlyUpdate())}if(this.executeCoroutines(0),bu(this,0),this.onHandlePaused())return!1;this._currentFrameEvent=1;for(let r=0;r<this.scripts_update.length;r++){const o=this.scripts_update[r];o.activeAndEnabled&&o.update!==void 0&&(Wi.Current=this,o.update())}if(this.executeCoroutines(1),bu(this,1),this.onHandlePaused())return!1;this._currentFrameEvent=2;for(let r=0;r<this.scripts_lateUpdate.length;r++){const o=this.scripts_lateUpdate[r];o.activeAndEnabled&&o.lateUpdate!==void 0&&(Wi.Current=this,o.lateUpdate())}if(this.executeCoroutines(2),bu(this,2),this.onHandlePaused()||(this.physicsSteps===void 0&&(this.physicsSteps=1),this.physics.engine&&this.physicsSteps>0&&this.internalUpdatePhysics(this.physicsSteps),this.onHandlePaused()))return!1;if(this.isVisibleToUser||this.runInBackground){this._currentFrameEvent=3;for(let r=0;r<this.scripts_onBeforeRender.length;r++){const o=this.scripts_onBeforeRender[r];o.activeAndEnabled&&o.onBeforeRender!==void 0&&(Wi.Current=this,o.onBeforeRender(t))}if(this.executeCoroutines(3),bu(this,3),this._sizeChanged&&this.updateSize(),this.pre_render_callbacks)for(const r in this.pre_render_callbacks)this.pre_render_callbacks[r](t)}return!0}internalUpdatePhysics(e){if(!this.physics.engine)return!1;const t=e,i=this.time.deltaTime/t;for(let s=0;s<t;s++)this._currentFrameEvent=9,this.executeCoroutines(9),this.physics.engine.step(i),this._currentFrameEvent=10,this.executeCoroutines(10);return this.physics.engine.postStep(),!0}internalOnRender(){this.isManagedExternally||(gq(this),this._currentFrameEvent=-1,this.renderNow(),this._currentFrameEvent=4)}internalOnAfterRender(){if(this.isVisibleToUser||this.runInBackground){for(let e=0;e<this.scripts_onAfterRender.length;e++){const t=this.scripts_onAfterRender[e];t.activeAndEnabled&&t.onAfterRender!==void 0&&(Wi.Current=this,t.onAfterRender())}if(this.executeCoroutines(4),bu(this,4),this.post_render_callbacks)for(const e in this.post_render_callbacks)this.post_render_callbacks[e]()}this._currentFrameEvent=-1,this.connection.sendBufferedMessagesNow(),this._stats&&(this._stats.end(),this.time.frameCount%150===0&&console.log(this.renderer.info.render.calls+" DrawCalls",`
4995
+ Render:`,{...this.renderer.info.render},`
4996
+ Memory:`,{...this.renderer.info.memory})),this._dispatchReadyAfterFrame&&(this._dispatchReadyAfterFrame=!1,this.domElement.dispatchEvent(new CustomEvent("ready")),Bi.dispatchCallback(Kn.ContextFirstFrameRendered,this))}renderNow(e){return!e&&(e=this.mainCamera,!e)?!1:(this._isRendering=!0,this.renderRequiredTextures(),this.composer&&!this.isInXR?this.composer.render(this.time.deltaTime):e&&this.renderer.render(this.scene,e),this._isRendering=!1,!0)}onHandlePaused(){const e=this.evaluatePaused();if(this._wasPaused!==e){ete&&console.log("Paused?",e,"context:"+this.alias);for(let t=0;t<this.scripts_pausedChanged.length;t++){const i=this.scripts_pausedChanged[t];i.activeAndEnabled&&i.onPausedChanged!==void 0&&(Wi.Current=this,i.onPausedChanged(e,this._wasPaused))}}return this._wasPaused=e,e}evaluatePaused(){return this.isInXR?!1:this.isPaused?!0:this.runInBackground?!1:!this.isVisibleToUser}renderRequiredTextures(){if(!this.mainCamera||!this._requireDepthTexture&&!this._requireColorTexture)return;if(!this._renderTarget){if(this._renderTarget=new ti(this.domWidth,this.domHeight),this._requireDepthTexture){const i=new zp(this.domWidth,this.domHeight);this._renderTarget.depthTexture=i}this._requireColorTexture&&(this._renderTarget.texture=new Ht,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=jt,this._renderTarget.texture.magFilter=jt,this._renderTarget.texture.format=Ci)}const e=this._renderTarget;e.texture&&(e.texture.colorSpace=this.renderer.outputColorSpace);const t=this.renderer.getRenderTarget();this.renderer.setRenderTarget(e),this.renderer.render(this.scene,this.mainCamera),this.renderer.setRenderTarget(t)}executeCoroutines(e){var i;if(this.coroutines[e]){const s=this.coroutines[e];for(let r=0;r<s.length;r++)try{const o=s[r];if(!o.comp||o.comp.destroyed||!o.main||o.comp.enabled===!1){ite&&console.log("Removing coroutine",o.comp,o.comp.enabled),s.splice(r,1),--r;continue}const c=o.chained;if(c&&c.length>0){const f=c[c.length-1].next();if(f.done&&c.pop(),t(f)&&(o.chained||(o.chained=[]),o.chained.push(f.value)),!f.done)continue}const l=o.main.next();if(l.done===!0){s.splice(r,1),--r;continue}const h=l.value;if(t(h)){if(h.next().done)continue;o.chained||(o.chained=[]),o.chained.push(h)}else if(h instanceof Promise){const d=h;o.chained||(o.chained=[]);const f=jN(d);(i=o.chained)==null||i.push(f);continue}}catch(o){console.error(o)}}function t(s){return!!(s&&s.next&&s.return)}}};let Ot=Wi;u(Ot,"_defaultTargetFramerate",{value:60}),u(Ot,"_defaultWebglRendererParameters",{antialias:!0,alpha:!1});Bi.registerCallback(Kn.ContextCreated,n=>{const e=n.context;kG(e),DG(e)});const Fb=se("debugcomponents"),yk="eff8ba80-635d-11ec-90d6-0242ac120003";class ms{constructor(e){u(this,"_originalSeed");u(this,"_seed");typeof e=="string"&&(e=ms.hash(e)),this._originalSeed=e,this._seed=e}get seed(){return this._seed}set seed(e){this._seed=e}reset(){this._seed=this._originalSeed}generateUUID(e){if(typeof e=="string")return ZD(e,yk);const t=this._seed;return this._seed-=1,ZD(t.toString(),yk)}initialize(e){typeof e=="string"?this._seed=ms.hash(e):this._seed=e}static createFromString(e){return new ms(this.hash(e))}static hash(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);return t}}var RG=(n=>(n.NewInstanceCreated="new-instance-created",n.InstanceDestroyed="instance-destroyed",n))(RG||{});class PG{constructor(e){u(this,"guid");this.guid=e}}function aw(n,e,t=!0){if(!n)return;const i=n;if(Ra(n,t),!e){console.warn("Can not send destroy: No networking connection provided",n.guid);return}if(!e.isConnected){console.warn("Can not send destroy: not connected",n.guid);return}let s=n.guid;if(!s&&i.uuid&&(s=i.uuid),!s){console.warn("Can not send destroy: failed to find guid",n);return}const r=new PG(s);e.send("instance-destroyed",r,ba.Queued)}function BG(n,e){const t=new PG(n);e.send("instance-destroyed",t,ba.Queued)}function DG(n){n.connection.beginListen("instance-destroyed",e=>{Fb&&console.log("[Remote] Destroyed",n.scene,e);const t=TA(e.guid,n.scene);t&&Ra(t)})}class rte{constructor(e,t,i){u(this,"filename");u(this,"hash");u(this,"size");this.filename=e,this.hash=t,this.size=i}}class OG{constructor(e,t){u(this,"guid");u(this,"originalGuid");u(this,"seed");u(this,"visible");u(this,"hostData");u(this,"dontSave");u(this,"parent");u(this,"position");u(this,"rotation");u(this,"scale");u(this,"preventCreation");this.originalGuid=e,this.guid=t}}function SR(n,e,t,i){var c;const s=n;if(!s.guid)return console.warn("Can not instantiate: No guid",s),null;if(e.context||(e.context=Ot.Current),!e.context)return console.error("Missing network instantiate options / reference to network connection in sync instantiate"),null;const r=e?{...e}:null,{instance:o,seed:a}=ote(s,e);if(o){const l=o;if(l.guid){Fb&&console.log("[Local] new instance","gameobject:",o==null?void 0:o.guid);const h=new OG(s.guid,l.guid);h.seed=a,r&&(r.position&&(h.position={x:r.position.x,y:r.position.y,z:r.position.z}),r.rotation&&(h.rotation={x:r.rotation.x,y:r.rotation.y,z:r.rotation.z,w:r.rotation.w}),r.scale&&(h.scale={x:r.scale.x,y:r.scale.y,z:r.scale.z})),h.position||(h.position={x:l.position.x,y:l.position.y,z:l.position.z}),h.rotation||(h.rotation={x:l.quaternion.x,y:l.quaternion.y,z:l.quaternion.z,w:l.quaternion.w}),h.scale||(h.scale={x:l.scale.x,y:l.scale.y,z:l.scale.z}),h.visible=s.visible,r!=null&&r.parent&&(typeof r.parent=="string"?h.parent=r.parent:h.parent=r.parent.guid),h.hostData=t,i===!1&&(h.dontSave=!0),(c=e==null?void 0:e.context)==null||c.connection.send("new-instance-created",h)}else console.warn("Missing guid, can not send new instance event",l)}return o}function cw(){return Math.random()*9999999}function kG(n){n.connection.beginListen("new-instance-created",async e=>{const t=await ate(e.originalGuid,n.scene);if(e.preventCreation===!0)return;if(!t){console.warn("could not find object that was instantiated: "+e.guid);return}const i=new Fa;e.position&&(i.position=new w(e.position.x,e.position.y,e.position.z)),e.rotation&&(i.rotation=new Ee(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w)),e.scale&&(i.scale=new w(e.scale.x,e.scale.y,e.scale.z)),i.parent=e.parent,e.seed&&(i.idProvider=new ms(e.seed)),i.visible=e.visible,i.context=n,Fb&&n.alias&&console.log("[Remote] instantiate in: "+n.alias);const s=em(t,i);s&&(e.parent==="scene"&&n.scene.add(s),Fb&&console.log("[Remote] new instance","gameobject:",s==null?void 0:s.guid,t))})}function ote(n,e){const t=cw(),i=e??new Fa;i.idProvider=new ms(t);const s=em(n,i);return{seed:t,instance:s}}const LG={};function FG(n,e){LG[n]=e}async function ate(n,e){const t=LG[n];if(t!=null){const i=await t(n);if(i)return i}return UG(n,e)}function UG(n,e){if(e===null||!n)return null;if(e.guid===n)return e;if(e.children)for(const t of e.children){const i=UG(n,t);if(i)return i}return null}const P_=se("debuggetcomponent"),B_=se("debuginstantiate");var NG=(n=>(n[n.None=0]="None",n[n.HideInHierarchy=1]="HideInHierarchy",n[n.HideInInspector=2]="HideInInspector",n[n.DontSaveInEditor=4]="DontSaveInEditor",n[n.NotEditable=8]="NotEditable",n[n.DontSaveInBuild=16]="DontSaveInBuild",n[n.DontUnloadUnusedAsset=32]="DontUnloadUnusedAsset",n[n.DontSave=52]="DontSave",n[n.HideAndDontSave=61]="HideAndDontSave",n))(NG||{});class Fa{constructor(){u(this,"idProvider");u(this,"parent");u(this,"keepWorldPosition");u(this,"position");u(this,"rotation");u(this,"scale");u(this,"visible");u(this,"context")}clone(){var t,i,s;const e=new Fa;return e.idProvider=this.idProvider,e.parent=this.parent,e.keepWorldPosition=this.keepWorldPosition,e.position=(t=this.position)==null?void 0:t.clone(),e.rotation=(i=this.rotation)==null?void 0:i.clone(),e.scale=(s=this.scale)==null?void 0:s.clone(),e}cloneAssign(e){var t,i,s;this.idProvider=e.idProvider,this.parent=e.parent,this.keepWorldPosition=e.keepWorldPosition,this.position=(t=e.position)==null?void 0:t.clone(),this.rotation=(i=e.rotation)==null?void 0:i.clone(),this.scale=(s=e.scale)==null?void 0:s.clone()}}function $p(n){return n.visible}function Qg(n,e){return typeof e=="number"&&(e=e>.5),n.visible=e,n.visible}function zG(n){return n[_l]||lw(n)}function GG(n,e){n[hN]=e}function lw(n){return Ma.isUsingInstancing(n)}function TA(n,e){return Mp(n,e,!0,!0)}const HG=Symbol("isDestroyed");function bd(n){return n[HG]}function VG(n,e){n[HG]=e}const gM=Symbol("isDontDestroy");function vM(n,e=!0){n[gM]=e}const D_=[],O_=[];function Ra(n,e=!0,t=!1){D_.length=0,O_.length=0,AM(n,e,t,!0);for(const i of D_)i.gameObject=null,i.context=null;for(const i of O_)VG(i,!0),t&&Gi(i),cN(i);O_.length=0,D_.length=0}function AM(n,e=!0,t=!1,i=!0){if(n==null)return;const s=n;if(s.isComponent){if(s[gM])return;D_.push(s);const a=s.gameObject;s.__internalDisable(),s.__internalDestroy(),s.gameObject=a;return}if(n[gM])return;const r=n;P_&&console.log(r),O_.push(r);const o=r.userData.components;if(o){let a=o.length;for(let c=0;c<o.length;c++){const l=o[c];AM(l,e,t,!1),o.length<a&&(a=o.length,c--)}}if(e&&r.children)for(const a of r.children)AM(a,e,t,!1);i&&r.removeFromParent()}function xd(n,e,t=!0){return QG(n,e,t)}function*CR(n,e,t=!1,i=999,s=0){if(n!=null&&n.userData.components&&!(s>i)){for(const r of n.userData.components)e&&(r==null?void 0:r.isComponent)===!0&&r instanceof e?yield r:yield r;if(t===!0)for(const r of n.children)yield*CR(r,e,!0,i,s+1)}}function QG(n,e,t,i=0){var s;if(n){if(n.isObject3D,i>1e3){console.warn("Failed to iterate components: too many levels");return}if((s=n.userData)!=null&&s.components)for(let r=0;r<n.userData.components.length;r++){const o=n.userData.components[r];if((o==null?void 0:o.isComponent)===!0){const a=e(o);if(a!==void 0)return a}}if(t&&n.children){const r=i+1;for(let o=0;o<n.children.length;o++){const a=n.children[o];if(!a)continue;const c=QG(a,e,t,r);if(c!==void 0)return c}}}}function em(n,e=null){let t=null;e!==null&&(e.x!==void 0?(t=new Fa,t.position=e):t=e);let i=Ot.Current;t!=null&&t.context&&(i=t.context),P_&&i.alias&&console.log("context",i.alias),t&&!t.idProvider&&(t.idProvider=new ms(Date.now()));const s=[],r={},o={},a=jG(i,n,t,s,r,o);a&&(lte(r),cte(o,r)),P_&&(Db(n,!0),Db(a,!0));const c={};for(const l in s){const h=s[l],d=h.guid;t&&t.idProvider&&(h.guid=t.idProvider.generateUUID(),c[d]=h.guid,P_&&console.log(h.name,h.guid)),ow(h,i),h.__internalNewInstanceCreated&&h.__internalNewInstanceCreated()}for(const l in s){const h=s[l];h.resolveGuids&&h.resolveGuids(c),h.enabled!==!1&&(h.enabled=!0)}return gb(i),a}function jG(n,e,t,i,s,r){var h;if(!e)return null;const o=e.userData;e.userData={};const a=e.children;e.children=[];const c=e.clone(!1);if(hw(c),e.userData=o,e.children=a,s[e.uuid]={original:e,clone:c},B_&&console.log("ADD",e,c),e.type==="SkinnedMesh"&&(r[e.uuid]={original:e,clone:c}),(t==null?void 0:t.visible)!==void 0&&(c.visible=t.visible),t!=null&&t.idProvider){c.uuid=t.idProvider.generateUUID();const d=c;d&&(d.guid=c.uuid)}e.animations&&e.animations.length>0&&(c.animations=[...e.animations]);const l=e.parent;if(l&&l.add(c),t!=null&&t.position?sr(c,t.position):c.position.copy(e.position),t!=null&&t.rotation?ea(c,t.rotation):c.quaternion.copy(e.quaternion),t!=null&&t.scale?c.scale.copy(t.scale):c.scale.copy(e.scale),t!=null&&t.parent&&t.parent!=="scene"){let d=null;if(typeof t.parent=="string"?d=Mp(t.parent,n.scene,!0):d=t.parent,d){const f=t.keepWorldPosition===!0?d.attach:d.add;f?f.call(d,c):console.error("Invalid parent object",d,"received when instantiating:",e)}else console.warn("could not find parent:",t.parent)}for(const[d,f]of Object.entries(e.userData))d!=="components"&&(c.userData[d]=f);if((h=e.userData)!=null&&h.components){const d=e.userData.components,f=[];c.userData.components=f;for(let p=0;p<d.length;p++){const m=d[p],g=new m.constructor;Tp(g,m),m[Lg]!==void 0&&(g[Lg]=m[Lg]),f.push(g),g.gameObject=c,i.push(g),mA.dispatchComponentLifecycleEvent(pA.Added,g)}}t&&(t.position=void 0,t.rotation=void 0,t.scale=void 0,t.parent=void 0);for(const d in e.children){const f=e.children[d],p=jG(n,f,t,i,s,r);p&&c.add(p)}return c}function cte(n,e){for(const t in n){const i=n[t],s=i.original,r=s.skeleton,o=i.clone;if(!r){console.warn("Skinned mesh has no skeleton?",i);continue}const a=r.bones,c=o.skeleton.clone();o.skeleton=c,o.bindMatrix.clone().copy(s.bindMatrix),o.bindMatrixInverse.copy(s.bindMatrixInverse);const l=[];c.bones=l;for(let h=0;h<a.length;h++){const d=a[h],p=e[d.uuid].clone;l.push(p)}}for(const t in n){const i=n[t].clone;i.skeleton.update(),i.bind(i.skeleton,i.bindMatrix),i.updateMatrixWorld(!0)}}function lte(n){var e;for(const t in n){const s=n[t].clone;if((e=s.userData)!=null&&e.components)for(let r=0;r<s.userData.components.length;r++){const o=s.userData.components[r],a=Object.entries(o);for(const[c,l]of a)if(Array.isArray(l)){const h=[];o[c]=h;for(let d=0;d<l.length;d++){const f=l[d];if(typeof f!="object"){h.push(f);continue}const p=_k(o,c,f,n);p!==void 0?h.push(p):h.push(f)}}else if(typeof l=="object"){const h=_k(o,c,l,n);h!==void 0&&(o[c]=h)}}}}function _k(n,e,t,i){var s,r;if(t!=null)if(t.isComponent===!0){const o=t.gameObject;if(o){const a=o.uuid,c=(s=i[a])==null?void 0:s.clone;if(!c){B_&&console.log("reference did not change",e,n,t);return}const l=o.userData.components.indexOf(t);if(l>=0)return B_&&console.log(e,a),c.userData.components[l];console.warn("could not find component",e,t)}}else if(t.isObject3D===!0){if(e==="gameObject")return;const o=t;if(o){const a=o.uuid,c=(r=i[a])==null?void 0:r.clone;if(c)return B_&&console.log(e,"old",t,"new",c),c}}else{if(t.isVector4||t.isVector3||t.isVector2||t.isQuaternion||t.isEuler)return t.clone();if(t.isColor===!0)return t.clone();if(t.isEventList===!0)return new t.constructor}}const WG=new Map;function hte(n,e){if(!n)return;if(!e){console.warn("No prototype found",n,n.prototype,n.constructor);return}const t=WG.get(e);t&&t.apply(n)}function ute(n){const e=dte(n.prototype);WG.set(n,e)}function dte(n){return new fte(n)}class fte{constructor(e){u(this,"$symbol");u(this,"extensions");u(this,"descriptors");this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(e),this.descriptors=new Array;for(let t=0;t<this.extensions.length;t++){const i=this.extensions[t],s=Object.getOwnPropertyDescriptor(e,i);s&&this.descriptors.push(s)}}apply(e){if(!e[this.$symbol]){e[this.$symbol]=!0;for(let t=0;t<this.extensions.length;t++){const i=this.extensions[t],s=this.descriptors[t];s&&Object.defineProperty(e,i,s)}}}}function hw(n){n&&n.isObject3D===!0&&hte(n,ge)}ge.prototype.SetActive=function(n){this.visible=n};ge.prototype.setActive=function(n){this.visible=n};ge.prototype.destroy=function(){Ra(this)};ge.prototype.addComponent=function(n){return MR(this,n)};ge.prototype.addNewComponent=function(n){return Xh(this,new n)};ge.prototype.removeComponent=function(n){return ER(this,n)};ge.prototype.getOrAddComponent=function(n){return uw(this,n)};ge.prototype.getComponent=function(n){return tm(this,n)};ge.prototype.getComponents=function(n,e){return IA(this,n,e)};ge.prototype.getComponentInChildren=function(n){return RA(this,n)};ge.prototype.getComponentsInChildren=function(n,e){return PA(this,n,e)};ge.prototype.getComponentInParent=function(n){return Lv(this,n)};ge.prototype.getComponentsInParent=function(n,e){return dw(this,n,e)};Object.getOwnPropertyDescriptor(ge.prototype,"activeSelf")||Object.defineProperty(ge.prototype,"activeSelf",{get:function(){return $p(this)},set:function(n){Qg(this,n)}});Object.getOwnPropertyDescriptor(ge.prototype,"transform")||Object.defineProperty(ge.prototype,"transform",{get:function(){return this}});Object.getOwnPropertyDescriptor(ge.prototype,"worldPosition")||Object.defineProperty(ge.prototype,"worldPosition",{get:function(){return this instanceof uI?Dt(this.object):Dt(this)},set:function(n){sr(this,n)}});Object.getOwnPropertyDescriptor(ge.prototype,"worldQuaternion")||Object.defineProperty(ge.prototype,"worldQuaternion",{get:function(){return this instanceof uI?Di(this.object):Di(this)},set:function(n){ea(this,n)}});Object.getOwnPropertyDescriptor(ge.prototype,"worldRotation")||Object.defineProperty(ge.prototype,"worldRotation",{get:function(){return CA(this)},set:function(n){bR(this,n)}});Object.getOwnPropertyDescriptor(ge.prototype,"worldScale")||Object.defineProperty(ge.prototype,"worldScale",{get:function(){return hn(this)},set:function(n){kv(this,n)}});Object.getOwnPropertyDescriptor(ge.prototype,"worldForward")||Object.defineProperty(ge.prototype,"worldForward",{get:function(){return Gn().set(0,0,1).applyQuaternion(Di(this))}});Object.getOwnPropertyDescriptor(ge.prototype,"worldRight")||Object.defineProperty(ge.prototype,"worldRight",{get:function(){return Gn().set(1,0,0).applyQuaternion(Di(this))}});Object.getOwnPropertyDescriptor(ge.prototype,"worldUp")||Object.defineProperty(ge.prototype,"worldUp",{get:function(){return Gn().set(0,1,0).applyQuaternion(Di(this))}});ute(ge);const TC=se("debuggetcomponent");function pte(n){return n==null||n.isObject3D?n:n.object&&n.object.isObject3D?n.object:n}function ER(n,e){if(!n||!n.userData.components)return;const t=n.userData.components.indexOf(e);t<0||(mA.dispatchComponentLifecycleEvent(pA.Removing,e),e.gameObject=null,n.userData.components.splice(t,1))}function uw(n,e){const t=tm(n,e);if(t)return t;const i=new e;return Xh(n,i)}const qG=new ms("addComponentIdProvider");function Xh(n,e,t=!0){n.userData||(n.userData={}),n.userData.components||(n.userData.components=[]),n.userData.components.push(e),e.gameObject=n,(e.guid===void 0||e.guid==="invalid")&&(e.guid=qG.generateUUID()),hw(n),ow(e);try{t&&e.__internalAwake&&(Fg(n),e.activeAndEnabled&&e.__internalAwake()),mA.dispatchComponentLifecycleEvent(pA.Added,e)}catch(i){console.error(i)}return e}function MR(n,e){if(typeof e=="function")return Xh(n,new e);if(e.destroyed)return console.warn("Can not move/add a destroyed component",e),e;if(e.gameObject===n)return e;if(e.gameObject&&e.gameObject.userData.components){const t=e.gameObject.userData.components.indexOf(e);e.gameObject.userData.components.splice(t,1)}if(!n.userData.components)n.userData.components=[];else if(n.userData.components.includes(e))return e;return n.userData.components.push(e),e.gameObject=n,(e.guid===void 0||e.guid==="invalid")&&(e.guid=qG.generateUUID()),ow(e),e}function XG(n){if(n.gameObject&&n.gameObject.userData.components){const e=n.gameObject.userData.components.indexOf(n);n.gameObject.userData.components.splice(e,1)}n.__internalDisable&&n.__internalDisable(),ol(n,n.context??Ot.Current),n.destroy(),n.gameObject=null}let bk=!1;function YG(n,e,t){var i;if(n==null)return null;if(!n.isObject3D)return console.error("Object is not object3D"),null;if(!((i=n==null?void 0:n.userData)!=null&&i.components)||(typeof e=="string"&&(bk||(bk=!0,console.warn(`Accessing components by name is not supported.
4995
4997
  Please use the component type instead. This may keep working in local development but it will fail when bundling your application.
4996
4998
 
4997
4999
  You can import other modules your main module to get access to types
@@ -5405,9 +5407,9 @@ ${r.join(`
5405
5407
 
5406
5408
  }
5407
5409
  `}function Jk(n){return`(${n.r}, ${n.g}, ${n.b})`}function Kk(n){return`(${n.x}, ${n.y})`}const RH=[1023,33777,33778,33779,35842,35843,37496,37808,37809,37810,37811,37812,37813,37814,37815,37816,37817,37818,37819,37820,37821,36492];se("debugusdz");const XP=class{constructor(e,t,i){u(this,"id");u(this,"trigger");u(this,"action");u(this,"exclusive",!1);this.id="Behavior_"+pw(e)+"_"+XP.global_id++,this.trigger=t,this.action=i}makeExclusive(e){return this.exclusive=e,this}writeTo(e,t,i){if(!this.trigger||!this.action)return;i.beginBlock(`def Preliminary_Behavior "${this.id}"`),i.appendLine(`rel actions = <${this.action.id}>`),i.appendLine(`uniform bool exclusive = ${this.exclusive}`);let s="";if(Array.isArray(this.trigger)){s="[";for(let r=0;r<this.trigger.length;r++){const o=this.trigger[r];s+="<"+o.id+">",r+1<this.trigger.length&&(s+=", ")}s+="]"}else s=`<${this.trigger.id}>`;if(i.appendLine(`rel triggers = ${s} `),i.appendLine(),Array.isArray(this.trigger))for(const r of this.trigger)r.writeTo(t,i),i.appendLine();else this.trigger.writeTo(t,i);i.appendLine(),this.action.writeTo(t,i),i.closeBlock()}};let $n=XP;u($n,"global_id",0);function MM(n,e){var i,s;let t="";if(Array.isArray(n)){let r="[ ";for(let o=0;o<n.length;o++){let a=n[o];if(typeof a=="string")r+=a;else if(typeof a=="object"){a.isObject3D&&(a=e.findById(a.uuid));const c=(i=a.getPath)==null?void 0:i.call(a);r+=c}o+1<n.length&&(r+=", ")}r+=" ]",t=r}else typeof n=="object"&&(n.isObject3D&&(n=e.findById(n.uuid)),t=(s=n.getPath)==null?void 0:s.call(n));return t}const YP=class{constructor(e,t){u(this,"id");u(this,"targetId");u(this,"tokenId");u(this,"type");u(this,"distance");e&&(this.targetId=e),t?this.id=t:this.id="Trigger_"+YP.global_id++}writeTo(e,t){t.beginBlock(`def Preliminary_Trigger "${this.id}"`),this.targetId&&(typeof this.targetId!="string"&&(this.targetId=MM(this.targetId,e)),t.appendLine("rel affectedObjects = "+this.targetId)),this.tokenId&&t.appendLine(`token info:id = "${this.tokenId}"`),this.type&&t.appendLine(`token type = "${this.type}"`),typeof this.distance=="number"&&t.appendLine(`double distance = ${this.distance}`),t.closeBlock()}};let wl=YP;u(wl,"global_id",0);class Os{static sceneStartTrigger(){const e=new wl;return e.targetId=void 0,e.tokenId="SceneTransition",e.type="enter",e}static tapTrigger(e){const t=new wl(e);return t.tokenId="TapGesture",t}static isTapTrigger(e){return(e==null?void 0:e.tokenId)==="TapGesture"}static proximityToCameraTrigger(e,t){const i=new wl(e);return i.tokenId="ProximityToCamera",i.distance=t,i}}class wh{constructor(e,t){u(this,"id");u(this,"actions");u(this,"loops",0);u(this,"performCount",1);u(this,"type","serial");this.id=e,this.actions=t}static getId(){return this.global_id++}addAction(e){return this.actions.push(e),this}makeParallel(){return this.type="parallel",this}makeSequence(){return this.type="serial",this}makeLooping(){return this.loops=1,this}makeRepeat(e){return this.performCount=e,this}writeTo(e,t){t.beginBlock(`def Preliminary_Action "${this.id}"`),t.beginArray("rel actions");for(const i of this.actions){if(!i)continue;const s=i===this.actions[this.actions.length-1];t.appendLine("<"+i.id+">"+(s?"":", "))}t.closeArray(),t.appendLine(),t.appendLine('token info:id = "Group"'),t.appendLine(`bool loops = ${this.loops} `),t.appendLine(`int performCount = ${this.performCount} `),t.appendLine(`token type = "${this.type}"`),t.appendLine();for(const i of this.actions)i&&(i.writeTo(e,t),t.appendLine());t.closeBlock()}}u(wh,"global_id",0);var OR=(n=>(n[n.pop=0]="pop",n[n.blink=1]="blink",n[n.bounce=2]="bounce",n[n.flip=3]="flip",n[n.float=4]="float",n[n.jiggle=5]="jiggle",n[n.pulse=6]="pulse",n[n.spin=7]="spin",n))(OR||{}),TM=(n=>(n.Relative="relative",n.Absolute="absolute",n))(TM||{}),PH=(n=>(n.Allow="allow",n.Ignore="ignore",n.Stop="stop",n))(PH||{});const $b=class{constructor(e,t){u(this,"id");u(this,"tokenId");u(this,"affectedObjects");u(this,"easeType");u(this,"motionType");u(this,"duration");u(this,"moveDistance");u(this,"style");u(this,"type");u(this,"front");u(this,"up");u(this,"start");u(this,"animationSpeed");u(this,"reversed");u(this,"pingPong");u(this,"xFormTarget");u(this,"audio");u(this,"gain");u(this,"auralMode");u(this,"multiplePerformOperation");e&&(this.affectedObjects=e),t?this.id=t:this.id="Action",this.id+="_"+$b.global_id++}clone(){const e=new $b,t=e.id;return Object.assign(e,this),e.id=t,e}writeTo(e,t){t.beginBlock(`def Preliminary_Action "${this.id}"`),this.affectedObjects&&(typeof this.affectedObjects!="string"&&(this.affectedObjects=MM(this.affectedObjects,e)),t.appendLine("rel affectedObjects = "+this.affectedObjects)),typeof this.duration=="number"&&t.appendLine(`double duration = ${this.duration} `),this.easeType&&t.appendLine(`token easeType = "${this.easeType}"`),this.tokenId&&t.appendLine(`token info:id = "${this.tokenId}"`),this.motionType&&t.appendLine(`token motionType = "${this.motionType}"`),typeof this.moveDistance=="number"&&t.appendLine(`double moveDistance = ${this.moveDistance} `),this.style&&t.appendLine(`token style = "${this.style}"`),this.type&&t.appendLine(`token type = "${this.type}"`),this.front&&t.appendLine(`vector3d front = (${this.front.x}, ${this.front.y}, ${this.front.z})`),this.up&&t.appendLine(`vector3d upVector = (${this.up.x}, ${this.up.y}, ${this.up.z})`),typeof this.start=="number"&&t.appendLine(`double start = ${this.start} `),typeof this.animationSpeed=="number"&&t.appendLine(`double animationSpeed = ${this.animationSpeed} `),typeof this.reversed=="boolean"&&t.appendLine(`bool reversed = ${this.reversed}`),typeof this.pingPong=="boolean"&&t.appendLine(`bool reverses = ${this.pingPong}`),this.xFormTarget&&(typeof this.xFormTarget!="string"&&(this.xFormTarget=MM(this.xFormTarget,e)),t.appendLine(`rel xformTarget = ${this.xFormTarget}`)),typeof this.audio=="string"&&t.appendLine(`asset audio = @${this.audio}@`),typeof this.gain=="number"&&t.appendLine(`double gain = ${this.gain}`),typeof this.auralMode=="string"&&t.appendLine(`token auralMode = "${this.auralMode}"`),typeof this.multiplePerformOperation=="string"&&t.appendLine(`token multiplePerformOperation = "${this.multiplePerformOperation}"`),t.closeBlock()}};let co=$b;u(co,"global_id",0);let Zf=class Nf{constructor(e,t,i){u(this,"x",0);u(this,"y",0);u(this,"z",0);this.x=e,this.y=t,this.z=i}static get up(){return new Nf(0,1,0)}static get right(){return new Nf(1,0,0)}static get forward(){return new Nf(0,0,1)}static get back(){return new Nf(0,0,-1)}static get zero(){return new Nf(0,0,0)}};var IM=(n=>(n.Play="play",n.Pause="pause",n.Stop="stop",n))(IM||{}),RM=(n=>(n.Spatial="spatial",n.NonSpatial="nonSpatial",n.Ambient="ambient",n))(RM||{});class di{static sequence(...e){return new wh("group_"+wh.getId(),e).makeSequence()}static parallel(...e){return new wh("group_"+wh.getId(),e).makeParallel()}static fadeAction(e,t,i){const s=new co(e);return s.tokenId="Visibility",s.type=i?"show":"hide",s.duration=t,s.style="basic",s.motionType="none",s.moveDistance=0,s.easeType="none",s}static startAnimationAction(e,t,i=0,s=1,r=!1,o=!1){const a=new co(e);if(a.tokenId="StartAnimation",a.start=t,a.duration=i,a.animationSpeed=s,a.reversed=r,a.pingPong=o,a.multiplePerformOperation="allow",r&&(a.start-=i),o){a.pingPong=!1;const c=a.clone();return c.reversed=!r,c.start=a.start,c.reversed&&(c.start-=i),di.sequence(a,c)}return a}static waitAction(e){const t=new co;return t.tokenId="Wait",t.duration=e,t}static lookAtCameraAction(e,t=9999999999999,i,s){const r=new co(e);return r.tokenId="LookAtCamera",r.duration=t,r.front=i??Zf.forward,r.up=s??Zf.up,r}static emphasize(e,t,i=2,s=1,r="basic"){const o=new co(e);return o.tokenId="Emphasize",o.duration=t,o.style=r??"basic",o.motionType=OR[i],o.moveDistance=s,o}static transformAction(e,t,i,s,r="inout"){const o=new co(e);return o.tokenId="Transform",o.duration=i,o.type=s,o.easeType=r,Array.isArray(t)&&console.error("Transform target must not be an array",t),o.xFormTarget=t,o}static playAudioAction(e,t,i="play",s=1,r="spatial"){const o=new co(e);return o.tokenId="Audio",o.type=i,o.audio=t,o.gain=s,o.auralMode=r,o.multiplePerformOperation="allow",o}}class hne{constructor(e){u(this,"object");u(this,"model");this.object=e}get id(){return this.object.uuid}apply(e){if(!this.model&&(this.model=e.findById(this.object.uuid),!this.model)){console.error("could not find model with id "+this.object.uuid);return}this.onApply(e)}}class kR extends hne{constructor(t,i,s,r){super(t);u(this,"matrix");u(this,"material");u(this,"geometry");u(this,"_enableAction");u(this,"_disableAction");this.matrix=i,this.material=s,this.geometry=r}onApply(t){var r,o;const i=this.model;if(!i)return;(r=i.parent)!=null&&r.isDynamic||Qr.createEmptyParent(i);const s=i.clone();this.matrix&&(s.matrix=this.matrix),this.material&&(s.material=this.material),this.geometry&&(s.geometry=this.geometry),(o=i.parent)==null||o.add(s)}enable(){return this._enableAction?this._enableAction:(this._enableAction=di.fadeAction(this.object,0,!0),this._enableAction)}disable(){return this._disableAction?this._disableAction:(this._disableAction=di.fadeAction(this.object,0,!1),this._disableAction)}}class LR{constructor(e){u(this,"actions");u(this,"sortedActions");this.actions=[...e]}organize(){this.sortedActions={};for(const e of this.actions){const t=e.id;this.sortedActions[t]||(this.sortedActions[t]=[]),this.sortedActions[t].push(e)}}getActions(e){return this.sortedActions||this.organize(),this.sortedActions[e.uuid]}}var une=Object.defineProperty,dne=Object.getOwnPropertyDescriptor,BH=(n,e,t,i)=>{for(var s=i>1?void 0:i?dne(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&une(e,t,s),s};class OA extends Ie{constructor(){super(...arguments);u(this,"from");u(this,"to");u(this,"width",0);u(this,"centered",!0);u(this,"_centerPos")}awake(){this._centerPos=new w}update(){if(!this.from||!this.to)return;const t=Dt(this.from).clone(),i=Dt(this.to).clone(),s=t.distanceTo(i);this._centerPos.copy(t),this._centerPos.add(i),this._centerPos.multiplyScalar(.5),sr(this.gameObject,this.centered?this._centerPos:t),this.gameObject.lookAt(Dt(this.to).clone()),this.gameObject.scale.set(this.width,this.width,s)}}BH([x(le)],OA.prototype,"from",2);BH([x(le)],OA.prototype,"to",2);var fne=Object.defineProperty,pne=Object.getOwnPropertyDescriptor,kA=(n,e,t,i)=>{for(var s=i>1?void 0:i?pne(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&fne(e,t,s),s};const Cf=se("debuganimation");class Ao extends Ie{constructor(){super(...arguments);u(this,"playAutomatically",!0);u(this,"randomStartTime",!0);u(this,"minMaxSpeed");u(this,"minMaxOffsetNormalized");u(this,"loop",!0);u(this,"clampWhenFinished",!1);u(this,"_tempAnimationClipBeforeGameObjectExisted",null);u(this,"_tempAnimationsArray");u(this,"mixer");u(this,"_actions",[]);u(this,"_currentActions",[]);u(this,"_handles",[]);u(this,"_didInit",!1)}get clip(){var t;return(t=this.animations)!=null&&t.length?this.animations[0]:null}set clip(t){if(!this.__didAwake){Cf&&console.warn("Assign clip during serialization",t),this._tempAnimationClipBeforeGameObjectExisted=t;return}t&&(this.gameObject.animations||(this.gameObject.animations=[]),!this.animations.includes(t)&&(this.animations.length>0?this.animations.splice(0,0,t):this.animations.push(t)))}set clips(t){this.animations=t}set animations(t){t==null||!Array.isArray(t)||(this.gameObject?this.gameObject.animations=t:this._tempAnimationsArray=t)}get animations(){return this.gameObject.animations||this._tempAnimationsArray||[]}get currentAction(){return this._currentActions[0]}get currentActions(){return this._currentActions}get actions(){return this._actions}set actions(t){this._actions=t}awake(){Cf&&console.log("Animation Awake",this.name,this),this._tempAnimationsArray&&(this.animations=this._tempAnimationsArray,this._tempAnimationsArray=void 0),this._tempAnimationClipBeforeGameObjectExisted&&(this.clip=this._tempAnimationClipBeforeGameObjectExisted,this._tempAnimationClipBeforeGameObjectExisted=null),this.playAutomatically&&this.init()}onEnable(){var t;if(this.playAutomatically&&((t=this.animations)==null?void 0:t.length)>0&&this.currentActions.length<=0){const i=Math.floor(Math.random()*this.actions.length);this.play(i)}}start(){this.randomStartTime&&this.currentAction&&(this.currentAction.time=Math.random()*this.currentAction.getClip().duration)}update(){this.mixer&&this.mixer.update(this.context.time.deltaTime)}getAction(t){var i;return(i=this.actions)==null?void 0:i.find(s=>s.getClip().name===t)}get isPlaying(){for(let t=0;t<this.actions.length;t++)if(this.actions[t].isRunning())return!0;return!1}play(t=0,i){if(Cf&&console.log("PLAY",t),this.init(),!this.mixer){Cf&&console.warn("Missing mixer",this);return}t===void 0&&(t=0);let s=t;if(typeof t=="number"){if(t>=this.animations.length){Cf&&console.log("No animation at index",t);return}s=this.animations[t]}else typeof t=="string"&&(s=this.animations.find(o=>o.name===t));if(!s){console.error("Could not find clip",t);return}i||(i={}),i.minMaxOffsetNormalized||(i.minMaxOffsetNormalized=this.minMaxOffsetNormalized),i.minMaxSpeed||(i.minMaxSpeed=this.minMaxSpeed),i.loop===void 0&&(i.loop=this.loop),i.clampWhenFinished===void 0&&(i.clampWhenFinished=this.clampWhenFinished);for(const o of this.actions)if(o.getClip()===s)return this.internalOnPlay(o,i);if(!(s instanceof Xr)){console.warn("Clip is no AnimationClip",s,"on object: "+this.name);return}const r=this.mixer.clipAction(s);return this.actions.push(r),this.internalOnPlay(r,i)}internalOnPlay(t,i){var s=this.currentAction;if(s===t&&s.isRunning()&&s.time<s.getClip().duration){const c=this.tryFindHandle(t);if(c)return c.getPromise()}const r=(i==null?void 0:i.exclusive)??!0;i!=null&&i.fadeDuration?(r&&(s==null||s.fadeOut(i.fadeDuration)),t.fadeIn(i.fadeDuration)):r&&(s==null||s.stop()),t.reset(),t.enabled=!0,t.time=0,t.timeScale=1;const o=t.getClip();i!=null&&i.minMaxOffsetNormalized&&(t.time=rt.lerp(i.minMaxOffsetNormalized.x,i.minMaxOffsetNormalized.y,Math.random())*o.duration),i!=null&&i.minMaxSpeed&&(t.timeScale=rt.lerp(i.minMaxSpeed.x,i.minMaxSpeed.y,Math.random())),i!=null&&i.clampWhenFinished&&(t.clampWhenFinished=!0),(i==null?void 0:i.startTime)!==void 0&&(t.time=i.startTime),(i==null?void 0:i.loop)!==void 0?t.loop=i.loop?bT:lv:t.loop=lv,t.play(),Cf&&console.log("PLAY",t.getClip().name,t);const a=new mne(t,this.mixer,i,c=>{this._handles.splice(this._handles.indexOf(a),1)});return this._handles.push(a),a.getPromise()}tryFindHandle(t){for(const i of this._handles)if(i.action===t)return i}init(){this._didInit||(this._didInit=!0,this.gameObject&&(this.actions=[],this.mixer=new Ux(this.gameObject)))}}kA([x()],Ao.prototype,"playAutomatically",2);kA([x()],Ao.prototype,"randomStartTime",2);kA([x()],Ao.prototype,"loop",2);kA([x()],Ao.prototype,"clampWhenFinished",2);kA([x(Xr)],Ao.prototype,"clips",1);class mne{constructor(e,t,i,s){u(this,"mixer");u(this,"action");u(this,"promise",null);u(this,"resolve",null);u(this,"reject",null);u(this,"_options");u(this,"_resolveCallback",null);u(this,"_rejectCallback",null);u(this,"_loopCallback");u(this,"_finishedCallback");u(this,"_resolvedOrRejectedCallback");this.action=e,this.mixer=t,this._resolvedOrRejectedCallback=s,this._options=i}getPromise(){return this.promise?this.promise:(this.promise=new Promise((e,t)=>{this._resolveCallback=e,this._rejectCallback=t,this.resolve=this.onResolve.bind(this),this.reject=this.onReject.bind(this)}),this._loopCallback=this.onLoop.bind(this),this._finishedCallback=this.onFinished.bind(this),this.mixer.addEventListener("loop",this._loopCallback),this.mixer.addEventListener("finished",this._finishedCallback),this.promise)}_update(){this._options&&this._options.endTime!==void 0&&this.action.time>this._options.endTime&&(this._options.loop===!0?this.action.time=this._options.startTime??0:(this.action.time=this._options.endTime,this.action.timeScale=0,this.onResolve()))}onResolve(){var e,t;this.dispose(),(e=this._resolvedOrRejectedCallback)==null||e.call(this,this),(t=this._resolveCallback)==null||t.call(this,this.action)}onReject(e){var t,i;this.dispose(),(t=this._resolvedOrRejectedCallback)==null||t.call(this,this),(i=this._rejectCallback)==null||i.call(this,e)}onLoop(e){}onFinished(e){e.action===this.action&&this.onResolve()}dispose(){this._loopCallback&&this.mixer.removeEventListener("loop",this._loopCallback),this._finishedCallback&&this.mixer.removeEventListener("finished",this._finishedCallback),this._loopCallback=void 0,this._finishedCallback=void 0}}var gne=Object.defineProperty,vne=Object.getOwnPropertyDescriptor,Yh=(n,e,t,i)=>{for(var s=i>1?void 0:i?vne(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&gne(e,t,s),s};class Ll{constructor(){u(this,"time");u(this,"value");u(this,"inTangent");u(this,"inWeight");u(this,"outTangent");u(this,"outWeight");u(this,"weightedMode")}}Yh([x()],Ll.prototype,"time",2);Yh([x()],Ll.prototype,"value",2);Yh([x()],Ll.prototype,"inTangent",2);Yh([x()],Ll.prototype,"inWeight",2);Yh([x()],Ll.prototype,"outTangent",2);Yh([x()],Ll.prototype,"outWeight",2);Yh([x()],Ll.prototype,"weightedMode",2);const PM=class{constructor(){u(this,"keys")}clone(){var e;const n=new PM;return n.keys=((e=this.keys)==null?void 0:e.map(t=>{const i=new Ll;return i.time=t.time,i.value=t.value,i.inTangent=t.inTangent,i.inWeight=t.inWeight,i.outTangent=t.outTangent,i.outWeight=t.outWeight,i.weightedMode=t.weightedMode,i}))||[],n}get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(n){if(!this.keys||this.keys.length==0)return 0;if(this.keys[0].time>=n)return this.keys[0].value;for(let e=0;e<this.keys.length;e++){const t=this.keys[e];if(t.time<=n)if(e+1<this.keys.length){const s=this.keys[e+1];if(s.time<n)continue;return!isFinite(t.outTangent)||!isFinite(s.inTangent)?t.value:PM.interpolateValue(n,t,s)}else return t.value}return this.keys[this.keys.length-1].value}static interpolateValue(n,e,t){const i=e.time,s=e.value,r=e.outTangent,o=t.time,a=t.value,c=t.inTangent,l=o-i,h=l*l,d=h*l,f=((r+c)*l-2*(a-s))/d,p=(3*(a-s)-(c+2*r)*l)/h,m=r,g=s,y=n-i,v=y*y,A=v*y;return f*A+p*v+m*y+g}};let Td=PM;Yh([x(Ll)],Td.prototype,"keys",2);class Ane extends Bn{constructor(e,t=1,i=16,s=2){const r=new _t,o=i+s*2,a=new Float32Array((o*3+3)*3);r.setAttribute("position",new tt(a,3));const c=new kn({color:65280}),l=new kn({color:16776960});super(r,[l,c]),this.audio=e,this.range=t,this.divisionsInnerAngle=i,this.divisionsOuterAngle=s,this.type="PositionalAudioHelper",this.update()}update(){const e=this.audio,t=this.range,i=this.divisionsInnerAngle,s=this.divisionsOuterAngle,r=es.degToRad(e.panner.coneInnerAngle),o=es.degToRad(e.panner.coneOuterAngle),a=r/2,c=o/2;let l=0,h=0,d,f;const p=this.geometry,m=p.attributes.position;p.clearGroups();function g(y,v,A,_){const b=(v-y)/A;for(m.setXYZ(l,0,0,0),h++,d=y;d<v;d+=b)f=l+h,m.setXYZ(f,Math.sin(d)*t,0,Math.cos(d)*t),m.setXYZ(f+1,Math.sin(Math.min(d+b,v))*t,0,Math.cos(Math.min(d+b,v))*t),m.setXYZ(f+2,0,0,0),h+=3;p.addGroup(l,h,_),l+=h,h=0}g(-c,-a,s,0),g(-a,a,i,1),g(a,c,s,0),m.needsUpdate=!0,r===o&&(this.material[0].visible=!1)}dispose(){this.geometry.dispose(),this.material[0].dispose(),this.material[1].dispose()}}var yne=Object.defineProperty,_ne=Object.getOwnPropertyDescriptor,Ic=(n,e,t,i)=>{for(var s=i>1?void 0:i?_ne(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&yne(e,t,s),s};const $s=se("debugaudio");let Ub=!1;const Nb=[];function mw(){if(Ub)return;Mt()&&console.log("User interaction registered: audio can now be played"),Ub=!0;const n=[...Nb];Nb.length=0,n.forEach(e=>e())}document.addEventListener("pointerdown",mw);document.addEventListener("click",mw);document.addEventListener("dragstart",mw);document.addEventListener("touchstart",mw);const lh=class extends Ie{constructor(){super(...arguments);u(this,"clip","");u(this,"playOnAwake",!1);u(this,"preload",!1);u(this,"_spatialBlend",0);u(this,"_minDistance",1);u(this,"_maxDistance",100);u(this,"_volume",1);u(this,"rollOffMode",0);u(this,"playInBackground",!0);u(this,"_loop",!1);u(this,"sound",null);u(this,"helper",null);u(this,"wasPlaying",!1);u(this,"audioLoader",null);u(this,"shouldPlay",!1);u(this,"_lastClipStartedLoading",null);u(this,"_audioElement",null);u(this,"onVisibilityChanged",()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||Ec())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":$s&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,lh.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&lh.userInteractionRegistered&&this.wasPlaying&&this.play();break}});u(this,"onApplicationMuteChanged",()=>{var e,t;this.context.application.muted?(e=this.sound)==null||e.setVolume(0):(t=this.sound)==null||t.setVolume(this.volume)});u(this,"createAudio",e=>{$s&&console.log("AudioBuffer finished loading",e);const t=this.Sound;if(!t){$s&&console.warn("Failed getting sound?",this.name);return}t.isPlaying&&t.stop(),e&&t.setBuffer(e),t.loop=this._loop,this.context.application.muted?t.setVolume(0):t.setVolume(this.volume),t.autoplay=this.shouldPlay&&lh.userInteractionRegistered,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),lh.registerWaitForAllowAudio(this.__onAllowAudioCallback)});u(this,"__onAllowAudioCallback",()=>{this.shouldPlay&&this.play()});u(this,"_lastContextTime",0);u(this,"_hasEnded",!0);u(this,"_needUpdateSpatialDistanceSettings",!1)}static get userInteractionRegistered(){return Ub}static registerWaitForAllowAudio(e){if(e!==null){if(Ub){e();return}Nb.indexOf(e)===-1&&Nb.push(e)}}get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(e){this._loop=e,this.sound&&this.sound.setLoop(e)}get spatialBlend(){return this._spatialBlend}set spatialBlend(e){e!==this._spatialBlend&&(this._spatialBlend=e,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(e){this._minDistance!==e&&(this._minDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(e){this._maxDistance!==e&&(this._maxDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&!this.context.application.muted&&($s&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}get Sound(){var e;if(!this.sound&&lh.userInteractionRegistered){let t=le.getComponent(this.context.mainCamera,Ph)??le.findObjectOfType(Ph,this.context);!t&&this.context.mainCamera&&(t=le.addNewComponent(this.context.mainCamera,Ph)),t!=null&&t.listener?(this.sound=new IU(t.listener),(e=this.gameObject)==null||e.add(this.sound)):$s&&console.warn("No audio listener found in scene - can not play audio")}return this.sound}get ShouldPlay(){return this.shouldPlay}get audioContext(){var e;return(e=this.sound)==null?void 0:e.context}awake(){$s&&console.log(this),this.audioLoader=new db,this.playOnAwake&&(this.shouldPlay=!0),this.preload&&typeof this.clip=="string"&&this.audioLoader.load(this.clip,this.createAudio,()=>{},console.error)}onEnable(){this.sound&&this.gameObject.add(this.sound),lh.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():lh.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(_b.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(_b.MuteChanged,this.onApplicationMuteChanged),this.pause()}applySpatialDistanceSettings(){const e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;const t=rt.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch($s&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+t),e.setRefDistance(t),e.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:e.setDistanceModel("exponential");break;case 1:e.setDistanceModel("linear");break}this.spatialBlend>0?$s&&!this.helper&&(this.helper=new Ane(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}async onNewClip(e){if(e&&(this.clip=e),typeof e=="string")if($s&&console.log(e),e.endsWith(".mp3")||e.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new db),this.shouldPlay=!0,this._lastClipStartedLoading===e){$s&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=e,$s&&console.log("load audio",e);const t=await this.audioLoader.loadAsync(e).catch(console.error);this._lastClipStartedLoading=null,t&&this.createAudio(t)}else console.warn("Unsupported audio clip type",e);else this.shouldPlay=!0,this.createAudio()}play(e=void 0){var i,s,r;!e&&this.clip&&(e=this.clip),e!==void 0&&typeof e!="string"&&!(e instanceof MediaStream)&&(Mt()&&console.warn("Called play on AudioSource with unknown argument type:",e+`
5408
- Using the assigned clip instead:`,this.clip),e=this.clip);let t=!this.sound||e&&e!==this.clip;if(typeof e=="string"&&!this.audioLoader&&(t=!0),(e instanceof MediaStream||typeof e=="string")&&(this.clip=e),t){this.shouldPlay=!0,this.onNewClip(e);return}if(this.shouldPlay=!0,this._hasEnded=!1,$s&&console.log("play",(i=this.sound)==null?void 0:i.getVolume(),this.sound),this.sound&&!this.sound.isPlaying){const o=this.context.application.muted;o&&this.sound.setVolume(0),(s=this.gameObject)==null||s.add(this.sound),this.clip instanceof MediaStream?(this.sound.setMediaStreamSource(this.clip),this._audioElement||(this._audioElement=document.createElement("audio"),this._audioElement.style.display="none"),this._audioElement.parentNode||(r=this.context.domElement.shadowRoot)==null||r.append(this._audioElement),this._audioElement.srcObject=this.clip,this._audioElement.autoplay=!1):(this._audioElement&&this._audioElement.remove(),this.sound.play(o?.1:0))}}pause(){var e,t;$s&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=(e=this.sound)==null?void 0:e.context.currentTime,this.sound.pause()),(t=this._audioElement)==null||t.remove()}stop(){var e,t;$s&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=(e=this.sound)==null?void 0:e.context.currentTime,$s&&console.log(this._lastContextTime),this.sound.stop()),(t=this._audioElement)==null||t.remove()}get isPlaying(){var e;return((e=this.sound)==null?void 0:e.isPlaying)??!1}set isPlaying(e){}get time(){var e,t;return(e=this.sound)!=null&&e.source?((t=this.sound.source)==null?void 0:t.context.currentTime)-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;const t=this.isPlaying;this.stop(),this.sound.offset=e,t&&this.play()}}update(){this.helper&&(this.isPlaying&&this.helper.update(),this.helper.visible=this.isPlaying),this._needUpdateSpatialDistanceSettings&&this.applySpatialDistanceSettings(),this.sound&&!this.sound.isPlaying&&this.shouldPlay&&!this._hasEnded&&(this._hasEnded=!0,$s&&console.log("Audio clip ended",this.clip),this.dispatchEvent(new CustomEvent("ended",{detail:this})))}};let Cn=lh;Ic([x(URL)],Cn.prototype,"clip",2);Ic([x()],Cn.prototype,"playOnAwake",2);Ic([x()],Cn.prototype,"preload",2);Ic([x()],Cn.prototype,"loop",1);Ic([x()],Cn.prototype,"spatialBlend",1);Ic([x()],Cn.prototype,"minDistance",1);Ic([x()],Cn.prototype,"maxDistance",1);Ic([x()],Cn.prototype,"volume",1);Ic([x()],Cn.prototype,"rollOffMode",2);Ic([x()],Cn.prototype,"playInBackground",2);const Zk={type:"change"},JC={type:"start"},$k={type:"end"},L0=new bo,e2=new yr,bne=Math.cos(70*es.DEG2RAD);let xne=class extends ys{constructor(e,t){super(),this.object=e,this.domElement=t,this.domElement.style.touchAction="none",this.enabled=!0,this.target=new w,this.cursor=new w,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:Du.ROTATE,MIDDLE:Du.DOLLY,RIGHT:Du.PAN},this.touches={ONE:Ou.ROTATE,TWO:Ou.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this.getPolarAngle=function(){return a.phi},this.getAzimuthalAngle=function(){return a.theta},this.getDistance=function(){return this.object.position.distanceTo(this.target)},this.listenToKeyEvents=function(j){j.addEventListener("keydown",bt),this._domElementKeyEvents=j},this.stopListenToKeyEvents=function(){this._domElementKeyEvents.removeEventListener("keydown",bt),this._domElementKeyEvents=null},this.saveState=function(){i.target0.copy(i.target),i.position0.copy(i.object.position),i.zoom0=i.object.zoom},this.reset=function(){i.target.copy(i.target0),i.object.position.copy(i.position0),i.object.zoom=i.zoom0,i.object.updateProjectionMatrix(),i.dispatchEvent(Zk),i.update(),r=s.NONE},this.update=function(){const j=new w,ze=new Ee().setFromUnitVectors(e.up,new w(0,1,0)),ne=ze.clone().invert(),q=new w,je=new Ee,Ke=new w,ct=2*Math.PI;return function(Pi=null){const bi=i.object.getWorldPosition(e.position);j.copy(bi).sub(i.target),j.applyQuaternion(ze),a.setFromVector3(j),i.autoRotate&&r===s.NONE&&Q(D(Pi)),i.enableDamping?(a.theta+=c.theta*i.dampingFactor,a.phi+=c.phi*i.dampingFactor):(a.theta+=c.theta,a.phi+=c.phi);let gi=i.minAzimuthAngle,Ni=i.maxAzimuthAngle;isFinite(gi)&&isFinite(Ni)&&(gi<-Math.PI?gi+=ct:gi>Math.PI&&(gi-=ct),Ni<-Math.PI?Ni+=ct:Ni>Math.PI&&(Ni-=ct),gi<=Ni?a.theta=Math.max(gi,Math.min(Ni,a.theta)):a.theta=a.theta>(gi+Ni)/2?Math.max(gi,a.theta):Math.min(Ni,a.theta)),a.phi=Math.max(i.minPolarAngle,Math.min(i.maxPolarAngle,a.phi)),a.makeSafe(),i.enableDamping===!0?i.target.addScaledVector(d,i.dampingFactor):i.target.add(d),i.target.sub(i.cursor),i.target.clampLength(i.minTargetRadius,i.maxTargetRadius),i.target.add(i.cursor),i.zoomToCursor&&T||i.object.isOrthographicCamera?a.radius=oe(a.radius):(i.enableDamping?h=es.lerp(h,l,i.dampingFactor):h=l,a.radius=oe(a.radius*h)),j.setFromSpherical(a),j.applyQuaternion(ne),bi.copy(i.target).add(j),i.object.parent?i.object.parent.worldToLocal(bi):i.object.position.copy(bi),i.object.lookAt(i.target),i.enableDamping===!0?(c.theta*=1-i.dampingFactor,c.phi*=1-i.dampingFactor,d.multiplyScalar(1-i.dampingFactor)):(c.set(0,0,0),d.set(0,0,0));let pi=!1;if(i.zoomToCursor&&T){let En=null;if(i.object.isPerspectiveCamera){const an=j.length();En=oe(an*l);const Io=an-En;i.object.position.addScaledVector(C,Io),i.object.updateMatrixWorld()}else if(i.object.isOrthographicCamera){const an=new w(E.x,E.y,0);an.unproject(i.object),i.object.zoom=Math.max(i.minZoom,Math.min(i.maxZoom,i.object.zoom/l)),i.object.updateProjectionMatrix(),pi=!0;const Io=new w(E.x,E.y,0);Io.unproject(i.object),i.object.position.sub(Io).add(an),i.object.updateMatrixWorld(),En=j.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),i.zoomToCursor=!1;En!==null&&(this.screenSpacePanning?i.target.set(0,0,-1).transformDirection(i.object.matrix).multiplyScalar(En).add(i.object.position):(L0.origin.copy(i.object.position),L0.direction.set(0,0,-1).transformDirection(i.object.matrix),Math.abs(i.object.up.dot(L0.direction))<bne?e.lookAt(i.target):(e2.setFromNormalAndCoplanarPoint(i.object.up,i.target),L0.intersectPlane(e2,i.target))))}else i.object.isOrthographicCamera&&(pi=l!==1,pi&&(i.object.zoom=Math.max(i.minZoom,Math.min(i.maxZoom,i.object.zoom/l)),i.object.updateProjectionMatrix()));return l=1,T=!1,pi||q.distanceToSquared(i.object.position)>o||8*(1-je.dot(i.object.quaternion))>o||Ke.distanceToSquared(i.target)>0?(i.dispatchEvent(Zk),q.copy(i.object.position),je.copy(i.object.quaternion),Ke.copy(i.target),!0):!1}}(),this.dispose=function(){i.domElement.removeEventListener("contextmenu",pt),i.domElement.removeEventListener("pointerdown",B),i.domElement.removeEventListener("pointercancel",Ce),i.domElement.removeEventListener("wheel",nt),i.domElement.removeEventListener("pointermove",ce),i.domElement.removeEventListener("pointerup",Ce),i._domElementKeyEvents!==null&&(i._domElementKeyEvents.removeEventListener("keydown",bt),i._domElementKeyEvents=null)};const i=this,s={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6};let r=s.NONE;const o=1e-6,a=new w1,c=new w1;let l=1,h=1;const d=new w,f=new ie,p=new ie,m=new ie,g=new ie,y=new ie,v=new ie,A=new ie,_=new ie,b=new ie,C=new w,E=new ie;let T=!1;const I=[],S={};let M=!1;function D(j){return j!==null?2*Math.PI/60*i.autoRotateSpeed*j:2*Math.PI/60/60*i.autoRotateSpeed}function G(j){const ze=Math.abs(j*.01);return Math.pow(.95,i.zoomSpeed*ze)}function Q(j){c.theta-=j}function L(j){c.phi-=j}const H=function(){const j=new w;return function(ne,q){j.setFromMatrixColumn(q,0),j.multiplyScalar(-ne),d.add(j)}}(),O=function(){const j=new w;return function(ne,q){i.screenSpacePanning===!0?j.setFromMatrixColumn(q,1):(j.setFromMatrixColumn(q,0),j.crossVectors(i.object.up,j)),j.multiplyScalar(ne),d.add(j)}}(),U=function(){const j=new w,ze=new w;return function(q,je){const Ke=i.domElement;if(i.object.isPerspectiveCamera){i.object.getWorldPosition(ze),j.copy(ze).sub(i.target);let ct=j.length();ct*=Math.tan(i.object.fov/2*Math.PI/180),H(2*q*ct/Ke.clientHeight,i.object.matrixWorld),O(2*je*ct/Ke.clientHeight,i.object.matrixWorld)}else i.object.isOrthographicCamera?(H(q*(i.object.right-i.object.left)/i.object.zoom/Ke.clientWidth,i.object.matrixWorld),O(je*(i.object.top-i.object.bottom)/i.object.zoom/Ke.clientHeight,i.object.matrixWorld)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),i.enablePan=!1)}}();function V(j){i.object.isPerspectiveCamera||i.object.isOrthographicCamera?l/=j:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),i.enableZoom=!1)}function J(j){i.object.isPerspectiveCamera||i.object.isOrthographicCamera?l*=j:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),i.enableZoom=!1)}function K(j,ze){if(!i.zoomToCursor)return;T=!0;const ne=i.domElement.getBoundingClientRect(),q=j-ne.left,je=ze-ne.top,Ke=ne.width,ct=ne.height;E.x=q/Ke*2-1,E.y=-(je/ct)*2+1,C.set(E.x,E.y,1).unproject(i.object).sub(i.object.position).normalize()}function oe(j){return Math.max(i.minDistance,Math.min(i.maxDistance,j))}function fe(j){f.set(j.clientX,j.clientY)}function be(j){K(j.clientX,j.clientX),A.set(j.clientX,j.clientY)}function ke(j){g.set(j.clientX,j.clientY)}function Ye(j){p.set(j.clientX,j.clientY),m.subVectors(p,f).multiplyScalar(i.rotateSpeed);const ze=i.domElement;Q(2*Math.PI*m.x/ze.clientHeight),L(2*Math.PI*m.y/ze.clientHeight),f.copy(p),i.update()}function ae(j){_.set(j.clientX,j.clientY),b.subVectors(_,A),b.y>0?V(G(b.y)):b.y<0&&J(G(b.y)),A.copy(_),i.update()}function Ae(j){y.set(j.clientX,j.clientY),v.subVectors(y,g).multiplyScalar(i.panSpeed),U(v.x,v.y),g.copy(y),i.update()}function Ne(j){K(j.clientX,j.clientY),j.deltaY<0?J(G(j.deltaY)):j.deltaY>0&&V(G(j.deltaY)),i.update()}function Ve(j){let ze=!1;switch(j.code){case i.keys.UP:j.ctrlKey||j.metaKey||j.shiftKey?L(2*Math.PI*i.rotateSpeed/i.domElement.clientHeight):U(0,i.keyPanSpeed),ze=!0;break;case i.keys.BOTTOM:j.ctrlKey||j.metaKey||j.shiftKey?L(-2*Math.PI*i.rotateSpeed/i.domElement.clientHeight):U(0,-i.keyPanSpeed),ze=!0;break;case i.keys.LEFT:j.ctrlKey||j.metaKey||j.shiftKey?Q(2*Math.PI*i.rotateSpeed/i.domElement.clientHeight):U(i.keyPanSpeed,0),ze=!0;break;case i.keys.RIGHT:j.ctrlKey||j.metaKey||j.shiftKey?Q(-2*Math.PI*i.rotateSpeed/i.domElement.clientHeight):U(-i.keyPanSpeed,0),ze=!0;break}ze&&(j.preventDefault(),i.update())}function Je(j){if(I.length===1)f.set(j.pageX,j.pageY);else{const ze=vt(j),ne=.5*(j.pageX+ze.x),q=.5*(j.pageY+ze.y);f.set(ne,q)}}function He(j){if(I.length===1)g.set(j.pageX,j.pageY);else{const ze=vt(j),ne=.5*(j.pageX+ze.x),q=.5*(j.pageY+ze.y);g.set(ne,q)}}function Be(j){const ze=vt(j),ne=j.pageX-ze.x,q=j.pageY-ze.y,je=Math.sqrt(ne*ne+q*q);A.set(0,je)}function X(j){i.enableZoom&&Be(j),i.enablePan&&He(j)}function ve(j){i.enableZoom&&Be(j),i.enableRotate&&Je(j)}function Le(j){if(I.length==1)p.set(j.pageX,j.pageY);else{const ne=vt(j),q=.5*(j.pageX+ne.x),je=.5*(j.pageY+ne.y);p.set(q,je)}m.subVectors(p,f).multiplyScalar(i.rotateSpeed);const ze=i.domElement;Q(2*Math.PI*m.x/ze.clientHeight),L(2*Math.PI*m.y/ze.clientHeight),f.copy(p)}function _e(j){if(I.length===1)y.set(j.pageX,j.pageY);else{const ze=vt(j),ne=.5*(j.pageX+ze.x),q=.5*(j.pageY+ze.y);y.set(ne,q)}v.subVectors(y,g).multiplyScalar(i.panSpeed),U(v.x,v.y),g.copy(y)}function qe(j){const ze=vt(j),ne=j.pageX-ze.x,q=j.pageY-ze.y,je=Math.sqrt(ne*ne+q*q);_.set(0,je),b.set(0,Math.pow(_.y/A.y,i.zoomSpeed)),V(b.y),A.copy(_);const Ke=(j.pageX+ze.x)*.5,ct=(j.pageY+ze.y)*.5;K(Ke,ct)}function lt(j){i.enableZoom&&qe(j),i.enablePan&&_e(j)}function F(j){i.enableZoom&&qe(j),i.enableRotate&&Le(j)}function B(j){i.enabled!==!1&&(I.length===0&&(i.domElement.addEventListener("pointermove",ce),i.domElement.addEventListener("pointerup",Ce)),mt(j),j.pointerType==="touch"?Me(j):xe(j))}function ce(j){i.enabled!==!1&&(j.pointerType==="touch"?Ft(j):Re(j))}function Ce(j){switch(et(j),I.length){case 0:i.domElement.removeEventListener("pointermove",ce),i.domElement.removeEventListener("pointerup",Ce),i.dispatchEvent($k),r=s.NONE;break;case 1:const ze=I[0],ne=S[ze];Me({pointerId:ze,pageX:ne.x,pageY:ne.y});break}}function xe(j){let ze;switch(j.button){case 0:ze=i.mouseButtons.LEFT;break;case 1:ze=i.mouseButtons.MIDDLE;break;case 2:ze=i.mouseButtons.RIGHT;break;default:ze=-1}switch(ze){case Du.DOLLY:if(i.enableZoom===!1)return;be(j),r=s.DOLLY;break;case Du.ROTATE:if(j.ctrlKey||j.metaKey||j.shiftKey){if(i.enablePan===!1)return;ke(j),r=s.PAN}else{if(i.enableRotate===!1)return;fe(j),r=s.ROTATE}break;case Du.PAN:if(j.ctrlKey||j.metaKey||j.shiftKey){if(i.enableRotate===!1)return;fe(j),r=s.ROTATE}else{if(i.enablePan===!1)return;ke(j),r=s.PAN}break;default:r=s.NONE}r!==s.NONE&&i.dispatchEvent(JC)}function Re(j){switch(r){case s.ROTATE:if(i.enableRotate===!1)return;Ye(j);break;case s.DOLLY:if(i.enableZoom===!1)return;ae(j);break;case s.PAN:if(i.enablePan===!1)return;Ae(j);break}}function nt(j){i.enabled===!1||i.enableZoom===!1||r!==s.NONE||(j.preventDefault(),i.dispatchEvent(JC),Ne(Ue(j)),i.dispatchEvent($k))}function Ue(j){const ze=j.deltaMode,ne={clientX:j.clientX,clientY:j.clientY,deltaY:j.deltaY};switch(ze){case 1:ne.deltaY*=16;break;case 2:ne.deltaY*=100;break}return j.ctrlKey&&!M&&(ne.deltaY*=10),ne}function $e(j){j.key==="Control"&&(M=!0,i.domElement.getRootNode().addEventListener("keyup",at,{passive:!0,capture:!0}))}function at(j){j.key==="Control"&&(M=!1,i.domElement.getRootNode().removeEventListener("keyup",at,{passive:!0,capture:!0}))}function bt(j){i.enabled===!1||i.enablePan===!1||Ve(j)}function Me(j){switch(Qe(j),I.length){case 1:switch(i.touches.ONE){case Ou.ROTATE:if(i.enableRotate===!1)return;Je(j),r=s.TOUCH_ROTATE;break;case Ou.PAN:if(i.enablePan===!1)return;He(j),r=s.TOUCH_PAN;break;default:r=s.NONE}break;case 2:switch(i.touches.TWO){case Ou.DOLLY_PAN:if(i.enableZoom===!1&&i.enablePan===!1)return;X(j),r=s.TOUCH_DOLLY_PAN;break;case Ou.DOLLY_ROTATE:if(i.enableZoom===!1&&i.enableRotate===!1)return;ve(j),r=s.TOUCH_DOLLY_ROTATE;break;default:r=s.NONE}break;default:r=s.NONE}r!==s.NONE&&i.dispatchEvent(JC)}function Ft(j){switch(Qe(j),r){case s.TOUCH_ROTATE:if(i.enableRotate===!1)return;Le(j),i.update();break;case s.TOUCH_PAN:if(i.enablePan===!1)return;_e(j),i.update();break;case s.TOUCH_DOLLY_PAN:if(i.enableZoom===!1&&i.enablePan===!1)return;lt(j),i.update();break;case s.TOUCH_DOLLY_ROTATE:if(i.enableZoom===!1&&i.enableRotate===!1)return;F(j),i.update();break;default:r=s.NONE}}function pt(j){i.enabled!==!1&&j.preventDefault()}function mt(j){I.push(j.pointerId)}function et(j){delete S[j.pointerId];for(let ze=0;ze<I.length;ze++)if(I[ze]==j.pointerId){I.splice(ze,1);return}}function Qe(j){let ze=S[j.pointerId];ze===void 0&&(ze=new ie,S[j.pointerId]=ze),ze.set(j.pageX,j.pageY)}function vt(j){const ze=j.pointerId===I[0]?I[1]:I[0];return S[ze]}i.domElement.addEventListener("contextmenu",pt),i.domElement.addEventListener("pointerdown",B),i.domElement.addEventListener("pointercancel",Ce),i.domElement.addEventListener("wheel",nt,{passive:!1}),i.domElement.getRootNode().addEventListener("keydown",$e,{passive:!0,capture:!0}),this.update()}};class DH extends me{constructor(e,t,i,s=128){if(t<=0||i<=0||s<=0)throw new Error("GroundedSkybox height, radius, and resolution must be positive.");const r=new Da(i,2*s,s);r.scale(1,1,-1);const o=r.getAttribute("position"),a=new w;for(let c=0;c<o.count;++c)if(a.fromBufferAttribute(o,c),a.y<0){const l=-t*3/2,h=a.y<l?-t/a.y:1-a.y*a.y/(3*l*l);a.multiplyScalar(h),a.toArray(o.array,3*c)}o.needsUpdate=!0,super(r,new ci({map:e,depthWrite:!1}))}}const G_=Symbol("cameraController");function wne(n){return n[G_]}function t2(n,e,t){t?n[G_]=e:n[G_]===e&&(n[G_]=null)}const i2=Symbol("camera autofit");function Sne(n){return n[i2]===void 0?!0:n[i2]!==!1}var Cne=Object.defineProperty,Ene=Object.getOwnPropertyDescriptor,Mne=(n,e,t,i)=>{for(var s=i>1?void 0:i?Ene(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Cne(e,t,s),s};class LA extends Ie{constructor(){super(...arguments);u(this,"constraintActive",!0);u(this,"locked",!1);u(this,"sources",[])}}Mne([x(ge)],LA.prototype,"sources",2);function Tne(n){vA(n,Kn.ContextCreated)}function Ine(n){vA(n,Vn.Start)}function OH(n){vA(n,Vn.Update)}function Rne(n){vA(n,Vn.OnBeforeRender)}class ld{constructor(){u(this,"bb",null);u(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}static sizeOf(){return 12}static createVec3(e,t,i,s){return e.prep(4,12),e.writeFloat32(s),e.writeFloat32(i),e.writeFloat32(t),e.offset()}}class kH{constructor(){u(this,"bb",null);u(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new ld).__init(this.bb_pos,this.bb)}rotation(e){return(e||new ld).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new ld).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,i,s,r,o,a,c,l,h){return e.prep(4,36),e.prep(4,12),e.writeFloat32(h),e.writeFloat32(l),e.writeFloat32(c),e.prep(4,12),e.writeFloat32(a),e.writeFloat32(o),e.writeFloat32(r),e.prep(4,12),e.writeFloat32(s),e.writeFloat32(i),e.writeFloat32(t),e.offset()}}class cl{constructor(){u(this,"bb",null);u(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedTransformModel(e,t){return(t||new cl).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+TI),(t||new cl).__init(e.readInt32(e.position())+e.position(),e)}guid(e){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}fast(){const e=this.bb.__offset(this.bb_pos,6);return e?!!this.bb.readInt8(this.bb_pos+e):!1}transform(e){const t=this.bb.__offset(this.bb_pos,8);return t?(e||new kH).__init(this.bb_pos+t,this.bb):null}dontSave(){const e=this.bb.__offset(this.bb_pos,10);return e?!!this.bb.readInt8(this.bb_pos+e):!1}static startSyncedTransformModel(e){e.startObject(4)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addFast(e,t){e.addFieldInt8(1,+t,0)}static addTransform(e,t){e.addFieldStruct(2,t,0)}static addDontSave(e,t){e.addFieldInt8(3,+t,0)}static endSyncedTransformModel(e){return e.endObject()}static finishSyncedTransformModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedTransformModelBuffer(e,t){e.finish(t,void 0,!0)}}var ls=(n=>(n[n.Average=0]="Average",n[n.Multiply=1]="Multiply",n[n.Minimum=2]="Minimum",n[n.Maximum=3]="Maximum",n))(ls||{}),gw=(n=>(n[n.Discrete=0]="Discrete",n[n.Continuous=1]="Continuous",n))(gw||{}),In=(n=>(n[n.None=0]="None",n[n.FreezePositionX=2]="FreezePositionX",n[n.FreezePositionY=4]="FreezePositionY",n[n.FreezePositionZ=8]="FreezePositionZ",n[n.FreezePosition=14]="FreezePosition",n[n.FreezeRotationX=16]="FreezeRotationX",n[n.FreezeRotationY=32]="FreezeRotationY",n[n.FreezeRotationZ=64]="FreezeRotationZ",n[n.FreezeRotation=112]="FreezeRotation",n[n.FreezeAll=126]="FreezeAll",n))(In||{}),$f=(n=>(n[n.None=0]="None",n[n.X=2]="X",n[n.Y=4]="Y",n[n.Z=8]="Z",n[n.All=-1]="All",n))($f||{});const Vs=function(n,e){return function(t,i,s){Pne(t,i,s,n,e)}};function Pne(n,e,t,i,s){if(!s&&!i&&!n.onValidate)return;if(t!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",n,e,t),xn("Invalid usage of validate decorator. Only fields can be validated. Property: "+e,Jo.Error);return}let r="";if(typeof e=="string"?r=e:r=e.name,n.__internalAwake){const o=Symbol(r),a=n.__internalAwake;n.__internalAwake=function(){var c;if(!this.onValidate){Mt()&&console.warn('Usage of @validate decorate detected but there is no onValidate method in your class: "'+((c=n.constructor)==null?void 0:c.name)+'"');return}if(this[o]===void 0){this[o]=this[r];const l=this[r];if(l instanceof ie||l instanceof w||l instanceof st||l instanceof Ee){const h=this[r];zx(h,()=>{this.onValidate(r)})}Object.defineProperty(this,r,{set:function(h){var d;if(this[H1]===!0)this[o]=h;else{i==null||i.call(this,h);const f=this[o];this[o]=h,(d=this.onValidate)==null||d.call(this,r,f)}},get:function(){return s==null||s.call(this),this[o]}})}a.call(this)}}}const Bne=function(n){return function(e,t,i){let s="";typeof t=="string"?s=t:s=t.name;const r=n.prototype,o=Object.getOwnPropertyDescriptor(r,s);if(!(o!=null&&o.value)){console.warn("Can not apply prefix: type does not have method named",t,n);return}const a=o.value,c=e[s];Object.defineProperty(r,s,{value:function(...l){const h=c==null?void 0:c.call(this,...l);if(h instanceof Promise){h.then(d=>{if(d!==!1)return a.call(this,...l)});return}if(h!==!1)return a.call(this,...l)}})}};var Dne=Object.defineProperty,One=Object.getOwnPropertyDescriptor,ra=(n,e,t,i)=>{for(var s=i>1?void 0:i?One(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Dne(e,t,s),s};class kne{constructor(e,t){u(this,"positionChanged",!1);u(this,"rotationChanged",!1);u(this,"position");u(this,"quaternion");u(this,"_positionKeys",["x","y","z"]);u(this,"_quaternionKeys",["_x","_y","_z","_w"]);u(this,"mute",!1);u(this,"context");u(this,"obj");u(this,"_positionWatch");u(this,"_rotationWatch");this.context=t,this.obj=e}get isDirty(){return this.positionChanged||this.rotationChanged}reset(e=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,e){if(this.position)for(const t of this._positionKeys)delete this.position[t];if(this.quaternion)for(const t of this._quaternionKeys)delete this.quaternion[t]}}syncValues(){for(const e of this._positionKeys)this.position[e]=this.obj.position[e];for(const e of this._quaternionKeys)this.quaternion[e]=this.obj.quaternion[e]}applyValues(){if(this.positionChanged&&this.position)for(const e of this._positionKeys){const t=this.position[e];t!==void 0&&(this.obj.position[e]=t)}if(this.rotationChanged&&this.quaternion)for(const e of this._quaternionKeys){const t=this.quaternion[e];t!==void 0&&(this.obj.quaternion[e]=t)}}start(e,t){this.reset(),e&&(this._positionWatch||(this._positionWatch=new vl(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((r,o)=>{var c;if((c=this.context.physics.engine)!=null&&c.isUpdating||this.mute)return;const a=this.position[o];Math.abs(a-r)<1e-5||(this.position[o]=r,this.positionChanged=!0)})),t&&(this._rotationWatch||(this._rotationWatch=new vl(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((r,o)=>{var c;if((c=this.context.physics.engine)!=null&&c.isUpdating||this.mute)return;const a=this.quaternion[o];Math.abs(a-r)<1e-5||(this.quaternion[o]=r,this.rotationChanged=!0)}));const i=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),s=new Se;this.obj.matrixWorld.multiplyMatrices=(r,o)=>{var a;return(a=this.context.physics.engine)!=null&&a.isUpdating||this.mute||s.equals(r)||(this.positionChanged=!0,this.rotationChanged=!0,s.copy(r)),i(r,o)}}stop(){var e,t;(e=this._positionWatch)==null||e.revoke(),(t=this._rotationWatch)==null||t.revoke()}}var OE;const BM=(OE=class extends Ie{constructor(){super(...arguments);u(this,"autoMass",!0);u(this,"_mass",0);u(this,"useGravity",!0);u(this,"constraints",In.None);u(this,"isKinematic",!1);u(this,"drag",0);u(this,"angularDrag",1);u(this,"detectCollisions",!0);u(this,"sleepThreshold",.01);u(this,"collisionDetectionMode",gw.Discrete);u(this,"_gravityScale",1);u(this,"dominanceGroup",0);u(this,"_propertiesChanged",!1);u(this,"_currentVelocity",new w);u(this,"_smoothedVelocity",new w);u(this,"_smoothedVelocityGetter",new w);u(this,"_lastPosition",new w);u(this,"_watch")}set mass(e){e!==this._mass&&(this._mass=e,this._propertiesChanged=!0,this.__didAwake&&(this.autoMass=!1))}get mass(){var e,t;return this.autoMass?((t=(e=this.context.physics.engine)==null?void 0:e.getBody(this))==null?void 0:t.mass())??-1:this._mass}get lockPositionX(){return(this.constraints&In.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&In.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&In.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&In.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&In.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&In.FreezeRotationZ)!==0}set lockPositionX(e){e?this.constraints|=In.FreezePositionX:this.constraints&=~In.FreezePositionX}set lockPositionY(e){e?this.constraints|=In.FreezePositionY:this.constraints&=~In.FreezePositionY}set lockPositionZ(e){e?this.constraints|=In.FreezePositionZ:this.constraints&=~In.FreezePositionZ}set lockRotationX(e){e?this.constraints|=In.FreezeRotationX:this.constraints&=~In.FreezeRotationX}set lockRotationY(e){e?this.constraints|=In.FreezeRotationY:this.constraints&=~In.FreezeRotationY}set lockRotationZ(e){e?this.constraints|=In.FreezeRotationZ:this.constraints&=~In.FreezeRotationZ}set gravityScale(e){this._gravityScale=e}get gravityScale(){return this._gravityScale}awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new kne(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),Vn.LateUpdate)}onDisable(){var e,t;(e=this._watch)==null||e.stop(),(t=this.context.physics.engine)==null||t.removeBody(this)}onDestroy(){var e;(e=this.context.physics.engine)==null||e.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){var e,t,i,s;for(;;)this._propertiesChanged&&(this._propertiesChanged=!1,(e=this.context.physics.engine)==null||e.updateProperties(this)),(t=this._watch)!=null&&t.isDirty?(this._watch.mute=!0,this._watch.applyValues(),(i=this.context.physics.engine)==null||i.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):(s=this._watch)==null||s.syncValues(),this.captureVelocity(),yield}teleport(e,t=!0){var i;(i=this._watch)==null||i.reset(!0),t?this.gameObject.position.set(e.x,e.y,e.z):this.setWorldPosition(e.x,e.y,e.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(e=!0){var t;(t=this.context.physics.engine)==null||t.resetForces(this,e)}resetTorques(e=!0){var t;(t=this.context.physics.engine)==null||t.resetTorques(this,e)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){var e;(e=this.context.physics.engine)==null||e.wakeup(this)}get isSleeping(){var e;return(e=this.context.physics.engine)==null?void 0:e.isSleeping(this)}updateProperties(){var e;return this._propertiesChanged=!1,(e=this.context.physics.engine)==null?void 0:e.updateProperties(this)}applyForce(e,t,i=!0){var s;this._propertiesChanged&&this.updateProperties(),(s=this.context.physics.engine)==null||s.addForce(this,e,i)}applyImpulse(e,t=!0){var i;this._propertiesChanged&&this.updateProperties(),(i=this.context.physics.engine)==null||i.applyImpulse(this,e,t)}setForce(e,t,i,s=!0){var r,o,a;(r=this.context.physics.engine)==null||r.resetForces(this,s),typeof e=="number"?(t??(t=0),i??(i=0),(o=this.context.physics.engine)==null||o.addForce(this,{x:e,y:t,z:i},s)):(a=this.context.physics.engine)==null||a.addForce(this,e,s)}getVelocity(){var t;const e=(t=this.context.physics.engine)==null?void 0:t.getLinearVelocity(this);return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(e,t,i,s=!0){var r,o;if(e instanceof w){const a=e;(r=this.context.physics.engine)==null||r.setLinearVelocity(this,a,s);return}t===void 0||i===void 0||(o=this.context.physics.engine)==null||o.setLinearVelocity(this,{x:e,y:t,z:i},s)}getAngularVelocity(){var t;const e=(t=this.context.physics.engine)==null?void 0:t.getAngularVelocity(this);return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setAngularVelocity(e,t,i,s=!0){var r,o;if(e instanceof w){const a=e;(r=this.context.physics.engine)==null||r.setAngularVelocity(this,a,s);return}t===void 0||i===void 0||(o=this.context.physics.engine)==null||o.setAngularVelocity(this,{x:e,y:t,z:i},s)}setTorque(e,t,i){this.setAngularVelocity(e,t,i)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(e=null){}captureVelocity(){const e=Dt(this.gameObject);BM.tempPosition.copy(e);const t=e.sub(this._lastPosition);this._lastPosition.copy(BM.tempPosition),this._smoothedVelocity.lerp(t,this.context.time.deltaTime/.1)}},u(OE,"tempPosition",new w),OE);let Xi=BM;ra([Vs()],Xi.prototype,"autoMass",2);ra([x()],Xi.prototype,"mass",1);ra([Vs(),x()],Xi.prototype,"useGravity",2);ra([Vs(),x()],Xi.prototype,"constraints",2);ra([Vs(),x()],Xi.prototype,"isKinematic",2);ra([Vs(),x()],Xi.prototype,"drag",2);ra([Vs(),x()],Xi.prototype,"angularDrag",2);ra([Vs(),x()],Xi.prototype,"detectCollisions",2);ra([Vs(),x()],Xi.prototype,"sleepThreshold",2);ra([Vs(),x()],Xi.prototype,"collisionDetectionMode",2);ra([Vs()],Xi.prototype,"_gravityScale",2);ra([Vs()],Xi.prototype,"dominanceGroup",2);const Xc=se("debugsync"),Uv="STRS";RI(Uv,cl.getRootAsSyncedTransformModel);const Qa=new AA;function LH(n,e,t=!0){Qa.clear();const i=Qa.createString(n);cl.startSyncedTransformModel(Qa),cl.addGuid(Qa,i),cl.addFast(Qa,t);const s=e.worldPosition,r=e.worldEuler,o=e.gameObject.scale;cl.addTransform(Qa,kH.createTransform(Qa,s.x,s.y,s.z,r.x,r.y,r.z,o.x,o.y,o.z));const a=cl.endSyncedTransformModel(Qa);return Qa.finish(a,Uv),Qa.asUint8Array()}let DM=0,qg=0;OH(n=>{var i;const t=((i=n.connection.currentServerUrl)==null?void 0:i.includes("glitch"))?10:40;qg=Math.floor(DM/t),DM=0,Xc&&qg>0&&console.log("Sync Transform Fast Interval",qg)});class Nh extends Ie{constructor(){super(...arguments);u(this,"overridePhysics",!0);u(this,"interpolatePosition",!0);u(this,"interpolateRotation",!0);u(this,"fastMode",!1);u(this,"syncDestroy",!1);u(this,"_model",null);u(this,"_needsUpdate",!0);u(this,"rb",null);u(this,"_wasKinematic",!1);u(this,"_receivedDataBefore",!1);u(this,"_targetPosition");u(this,"_targetRotation");u(this,"_receivedFastUpdate",!1);u(this,"_shouldRequestOwnership",!1);u(this,"joinedRoomCallback",null);u(this,"receivedDataCallback",null);u(this,"tempEuler",new ks);u(this,"receivedUpdate",!1);u(this,"lastWorldPos");u(this,"lastWorldRotation")}requestOwnership(){Xc&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}hasOwnership(){var t;return((t=this._model)==null?void 0:t.hasOwnership)??void 0}isOwned(){var t;return(t=this._model)==null?void 0:t.isOwned}awake(){Xc&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new w,this._targetRotation=new Ee,this.lastWorldPos=new w,this.lastWorldRotation=new Ee,this.rb=le.getComponentInChildren(this.gameObject,Xi),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new LI(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(mi.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(Uv,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&BG(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(mi.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(Uv,this.receivedDataCallback)}tryGetLastState(){const t=this.context.connection.tryGetState(this.guid);t&&this.onReceivedData(t)}onReceivedData(t){var i;if(!this.destroyed&&typeof t.guid=="function"&&t.guid()===this.guid){Xc&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,t),this.receivedUpdate=!0,this._receivedFastUpdate=t.fast();const s=t.transform();if(s){Ma.markDirty(this.gameObject,!0);const r=s.position();r&&(this.interpolatePosition&&((i=this._targetPosition)==null||i.set(r.x(),r.y(),r.z())),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(r.x(),r.y(),r.z()));const o=s.rotation();o&&(this.tempEuler.set(o.x(),o.y(),o.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&_R(this.gameObject,this.tempEuler))}this._receivedDataBefore=!0}}onEnable(){this.lastWorldPos.copy(this.worldPosition),this.lastWorldRotation.copy(this.worldQuaternion),this._needsUpdate=!0,this._model&&this._model.updateIsOwned()}onDisable(){this._model&&this._model.freeOwnership()}onBeforeRender(){if(!this.activeAndEnabled||!this.context.connection.isConnected)return;if(!this.context.connection.isInRoom||!this._model){Xc&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());const t=this.worldPosition,i=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){const o=t.distanceTo(this.lastWorldPos),a=i.angleTo(this.lastWorldRotation),c=this._model.hasOwnership||this.fastMode?1e-4:.001;(o>c||a>c)&&(this._model.hasOwnership?this._needsUpdate=!0:(Xc&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastWorldPos),this.worldPosition=this.lastWorldPos,t.copy(this.lastWorldPos),this.worldQuaternion=this.lastWorldRotation,i.copy(this.lastWorldRotation),Ma.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const a=this._receivedFastUpdate||this.fastMode?.5:.3;let c=!1;if(this.interpolatePosition&&this._targetPosition){const l=this.worldPosition;l.lerp(this._targetPosition,a),this.worldPosition=l,c=!0}if(this.interpolateRotation&&this._targetRotation){const l=this.worldQuaternion;l.slerp(this._targetRotation,a),this.worldQuaternion=l,c=!0}c&&Ma.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastWorldPos.copy(t),this.lastWorldRotation.copy(i),!this._model)return;if(!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership){this.rb&&(this.rb.isKinematic=this._model.isOwned??!1,this.rb.setVelocity(0,0,0));return}this.rb&&(this._wasKinematic!==void 0&&(Xc&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic),this.gameObject.position.distanceTo(new w(0,0,0))>1e3&&(Xc&&console.log("RESET",this.name),this.gameObject.position.set(0,1,0),this.rb.setVelocity(0,0,0)));const s=10,r=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%s===0||r)){if(DM++,r&&qg>0&&this.context.time.frameCount%qg!==0)return;Xc&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this.overridePhysics&&this.rb,this._needsUpdate=!1;const o=LH(this.guid,this,!!r);this.context.connection.sendBinary(o)}}}const Lne=se("debugshadowcomponents");fR.prototype.interactable={get(){return this.interactive},set(n){this.interactable=n}};const jo=Symbol("shadowDomOwner");class Pa extends Ie{constructor(){super(...arguments);u(this,"_shadowComponent",null);u(this,"_controlsChildLayout",!0);u(this,"_root");u(this,"_parentComponent")}isRoot(){var t;return((t=this.Root)==null?void 0:t.gameObject)===this.gameObject}get canvas(){const t=this.Root;return t!=null&&t.isCanvas?t:null}get Canvas(){return this.canvas}markDirty(){jr.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(t){this._shadowComponent=t}get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(t){this._controlsChildLayout=t,this.shadowComponent&&(this.shadowComponent.autoLayout=t)}get Root(){return this._root===void 0&&(this._root=le.getComponentInParent(this.gameObject,FA)),this._root}__internalNewInstanceCreated(){super.__internalNewInstanceCreated(),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0}onEnable(){super.onEnable()}addShadowComponent(t,i){var o;this.removeShadowComponent();const s=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=le.getComponentInParent(s,Pa),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}t.name=this.name+" ("+(this.constructor.name??"UI")+")",t.autoLayout=this._parentComponent.controlsChildLayout,t[jo]=this,this.setShadowComponentOwner(t);let r=!1;if(((o=this.Root)==null?void 0:o.gameObject)===this.gameObject)this.gameObject.add(t);else{const a=this._parentComponent.shadowComponent;a&&(a==null||a.add(t),r=!0)}this.shadowComponent=t,i&&i.shadowComponent&&this.shadowComponent&&i.shadowComponent.add(this.shadowComponent),gA&&t.add(new Zo(.5)),this.onAfterAddedToScene(),r&&gG(),Lne&&console.log(this.shadowComponent)}setShadowComponentOwner(t){if(t&&(t[jo]===void 0||t[jo]===this)&&(t[jo]=this,t.children))for(const i of t.children)this.setShadowComponentOwner(i)}traverseOwnedShadowComponents(t,i,s){if(t&&t[jo]===i){s(t);for(const r of t.children)this.traverseOwnedShadowComponents(r,i,s)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(t){this.shadowComponent&&(this.shadowComponent.interactable=t)}}class FA extends Pa{awake(){super.awake()}}class rm{constructor(e,t){u(this,"event");u(this,"button");u(this,"buttonName");u(this,"_used",!1);u(this,"_propagationStopped",!1);u(this,"z__pointer_ctured",!1);u(this,"z__pointer_cture_rleased",!1);u(this,"inputSource");u(this,"object");u(this,"point");u(this,"normal");u(this,"face");u(this,"distance");u(this,"instanceId");u(this,"isDown");u(this,"isUp");u(this,"isPressed");u(this,"isClick");u(this,"isDoubleClick");u(this,"input");this.event=t,this.input=e,this.button=t.button}get deviceIndex(){return this.event.deviceIndex}get pointerId(){return this.event.pointerId}get pressure(){return this.event.pressure}get used(){return this._used}use(){this._used||(this._used=!0,this.pointerId!==void 0&&this.input.setPointerUsed(this.pointerId))}get propagationStopped(){return this._propagationStopped}stopPropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}stopImmediatePropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}setPointerCapture(){this.z__pointer_ctured=!0}releasePointerCapture(){this.z__pointer_cture_rleased=!0}get mode(){return this.event.mode}clone(){const e=new rm(this.input,this.event);return Object.assign(e,this),e}Use(){this.use()}StopPropagation(){this.event.stopImmediatePropagation()}}function OM(n,e){return le.foreachComponent(n,i=>{if(!i.enabled)return;const s=i;if(e)switch(e){case"pointerdown":if(s.onPointerDown)return!0;break;case"pointerup":if(s.onPointerUp||s.onPointerClick)return!0;break;case"pointermove":if(s.onPointerEnter||s.onPointerExit||s.onPointerMove)return!0;break}else if(s.onPointerDown||s.onPointerUp||s.onPointerEnter||s.onPointerExit||s.onPointerClick)return!0},!1)===!0}var Fne=Object.defineProperty,Une=Object.getOwnPropertyDescriptor,Nne=(n,e,t,i)=>{for(var s=i>1?void 0:i?Une(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Fne(e,t,s),s};class UA extends Ie{awake(){jr.createIfNoneExists(this.context)}onEnable(){var e;(e=jr.get(this.context))==null||e.register(this)}onDisable(){var e;(e=jr.get(this.context))==null||e.unregister(this)}}class yo extends UA{constructor(){super(...arguments);u(this,"targets",null);u(this,"raycastHits",[]);u(this,"ignoreSkinnedMeshes",!1)}start(){this.targets=[this.gameObject]}performRaycast(t=null){if(!this.targets)return null;t??(t=new ta),t.targets=this.targets,t.results=this.raycastHits;const i=t.testObject;this.ignoreSkinnedMeshes&&(t.testObject=r=>r instanceof Ea?"continue in children":i?i(r):!0);const s=this.context.physics.raycast(t);return t.testObject=i,s}}Nne([x()],yo.prototype,"ignoreSkinnedMeshes",2);class vw extends yo{constructor(){super(),this.ignoreSkinnedMeshes=!0}}class Nv extends UA{performRaycast(e){if(!yt.active||!(e!=null&&e.ray))return null;const t=e.ray.origin,i=.01;return this.context.physics.sphereOverlap(t,i)}}class Aw{static getObject(e){const t=e[jo];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(t&&(t.canvasGroup=void 0,t.graphic=void 0),e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;const i=this.tryFindCanvasGroup(e);if((i==null?void 0:i.isCanvasGroup)===!0&&(t&&(t.canvasGroup=i),i.blocksRaycasts===!1||i.interactable===!1))return!1;const s=xd(e,r=>{if(r.isGraphic===!0)return r},!1);return t&&(s==null?void 0:s.isGraphic)===!0&&(t.graphic=s),!((s==null?void 0:s.raycastTarget)===!1||(s==null?void 0:s.layer)===2)}static tryFindCanvasGroup(e){if(!e)return null;const t=xd(e,i=>{const s=i;if(s.blocksRaycasts!==void 0&&s.interactable!==void 0)return s},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}}function FR(n){const e=n[jo];return e||(n.parent?FR(n.parent):null)}function zne(n){return n.isUI===!0||typeof n[jo]=="object"}function zb(n,e){if(!n)return;const t=n.material;if((t==null?void 0:t.isMaterial)===!0){const i=n.parent;i&&i.isText,t.side=e.doubleSided??!0?_i:Ls,t.shadowSide=e.doubleSided?_i:Ls,n.castShadow=e.castShadows?e.castShadows:!1,n.receiveShadow=e.receiveShadows?e.receiveShadows:!1}for(const i of n.children)zb(i,e)}function zf(n,e,t){n[e]===void 0&&console.warn("Field",e,"is undefined on",n);const i=Proxy.revocable(n[e],{set(o,a,c,l){const h=o[a],d=Reflect.set(o,a,c,l);return t(c,h),d}}),s=i.revoke,r=n[e];return i.revoke=()=>{n[e]=r,s()},n[e]=i.proxy,i}const n2=Symbol("Scheduled action");function Gne(n,e,t=Vn.OnBeforeRender){let i=n[n2];i||(i=n[n2]={});const s=e.name;i[t]||(i[t]={});const r=i[t];if(r[s])return;function*a(){e==null||e.call(n),r[s]=null}const c=n.startCoroutine(a(),t);r[s]=c}const Yc=se("debugeventsystem");var kM=(n=>(n.BeforeHandleInput="BeforeHandleInput",n.AfterHandleInput="AfterHandleInput",n))(kM||{});const ec=class extends Ie{constructor(){super();u(this,"raycaster",[]);u(this,"_handleInputFn");u(this,"pressedByID",new Map);u(this,"hoveredByID",new Map);u(this,"_sortedHits",[]);u(this,"_testObjectsCache",new Map);u(this,"_currentlyActiveRaycaster",null);u(this,"_currentPointerEventName",null);u(this,"shouldRaycastObject",t=>{var r;let i=null;if(zne(t)&&(i=(r=t[jo])==null?void 0:r.gameObject),this._testObjectsCache.has(t)||i&&this._testObjectsCache.has(i))return this._testObjectsCache.get(t)===!1?"continue in children":!0;{let o=OM(t,this._currentPointerEventName);if(!o&&i&&(o=OM(i,this._currentPointerEventName)),o){this._testObjectsCache.set(t,!0);for(const a of t.children)this.shouldRaycastObject_AddToYesCache(a);return!0}return this._testObjectsCache.set(t,!1),"continue in children"}});u(this,"_sortingBuffer",[]);u(this,"_noDepthTestingResults",[]);u(this,"out",{});u(this,"_capturedPointer",{});u(this,"pointerEnterSymbol",Symbol("pointerEnter"));u(this,"pointerExitSymbol",Symbol("pointerExit"));u(this,"currentActiveMeshUIComponents",[]);ec.systems.push(this)}static createIfNoneExists(t){this.didSearchEventSystem||(this.didSearchEventSystem=!0,ec.systems.length<=0&&ec.systems.push(...le.findObjectsOfType(ec,t)));for(const s of ec.systems)if(s.context===t)return;const i=new ge;le.addNewComponent(i,ec),t.scene.add(i)}static get systems(){const t=Ot.Current;return this._eventSystemMap.has(t)||this._eventSystemMap.set(t,[]),this._eventSystemMap.get(t)}static get(t){const i=this._eventSystemMap.get(t);return i&&i.length>0?i[0]:null}static get instance(){return this.systems[0]}static ensureUpdateMeshUI(t,i,s=!1){yh.update(t,i,s)}static markUIDirty(t){yh.markDirty()}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}onDestroy(){ec.systems.splice(ec.systems.indexOf(this),1)}start(){if(this.raycaster.length<=0&&!le.findObjectOfType(UA,this.context)){const i=le.addNewComponent(this.context.scene,yo);this.raycaster.push(i),(Mt()||Yc)&&console.warn("Added an ObjectRaycaster to the scene because no raycaster was found.")}}register(t){var i;t&&this.raycaster&&!this.raycaster.includes(t)&&((i=this.raycaster)==null||i.push(t))}unregister(t){var s,r;const i=(s=this.raycaster)==null?void 0:s.indexOf(t);i!==void 0&&i!==-1&&((r=this.raycaster)==null||r.splice(i,1))}onEnable(){this._handleInputFn??(this._handleInputFn=this.onPointerEvent.bind(this)),this.context.input.addEventListener(tn.PointerDown,this._handleInputFn),this.context.input.addEventListener(tn.PointerUp,this._handleInputFn),this.context.input.addEventListener(tn.PointerMove,this._handleInputFn)}onDisable(){this.context.input.removeEventListener(tn.PointerDown,this._handleInputFn),this.context.input.removeEventListener(tn.PointerUp,this._handleInputFn),this.context.input.removeEventListener(tn.PointerMove,this._handleInputFn)}onBeforeRender(){this.resetMeshUIStates()}onPointerEvent(t){if(t===void 0||t.propagationStopped)return;const i=new rm(this.context.input,t);this._currentPointerEventName=t.type,i.inputSource=this.context.input,i.isClick=t.isClick,i.isDoubleClick=t.isDoubleClick,i.isDown=t.type==tn.PointerDown,i.isUp=t.type==tn.PointerUp,i.isPressed=this.context.input.getPointerPressed(t.pointerId),Yc&&(i.isDown?console.log("DOWN",i.pointerId):i.isUp&&console.log("UP",i.pointerId),i.isClick&&console.log("CLICK",i.pointerId));const s=new ta;t.ray?s.ray=t.ray:s.screenPoint=this.context.input.getPointerPositionRC(t.pointerId);const r=this.performRaycast(s);Yc&&i.isClick&&xn("EventSystem: "+i.pointerId+" - "+this.context.time.frame+" - Up:"+i.isUp+", Down:"+i.isDown);const o={sender:this,args:i,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:o})),this.handleIntersections(r,i),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:o}))}shouldRaycastObject_AddToYesCache(t){this._testObjectsCache.set(t,!0);for(const i of t.children)this.shouldRaycastObject_AddToYesCache(i)}performRaycast(t){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,t||(t=new ta),t.testObject=this.shouldRaycastObject;for(const i of this.raycaster){if(!i.activeAndEnabled)continue;this._currentlyActiveRaycaster=i;const s=i.performRaycast(t);this._currentlyActiveRaycaster=null,s&&s.length>0&&this._sortedHits.push(...s)}return this._sortedHits.sort((i,s)=>i.distance-s.distance),this._sortedHits}assignHitInformation(t,i){i?(t.point=i.point,t.normal=i.normal,t.face=i.face,t.distance=i.distance,t.instanceId=i.instanceId):(t.point=void 0,t.normal=void 0,t.face=void 0,t.distance=void 0,t.instanceId=void 0)}handleIntersections(t,i){var r;if(t!=null&&t.length){t=this.sortCandidates(t);for(const o of t){if(i.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(i,o),this.handleEventOnObject(o.object,i))return!0}}this.assignHitInformation(i,t==null?void 0:t[0]),this.invokePointerCapture(i);const s=this.hoveredByID.get(i.pointerId);return s&&this.propagatePointerExit(s.obj,s.data,null),this.hoveredByID.delete(i.pointerId),i.isUp&&((r=this.pressedByID.get(i.pointerId))==null||r.handlers.forEach(o=>this.invokeOnPointerUp(i,o)),this.pressedByID.delete(i.pointerId)),!1}sortCandidates(t){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let i=0;i<t.length;i++){const s=t[i],r=s.object;if(r.material&&r.material.depthTest===!1){this._noDepthTestingResults.push(s);continue}this._sortingBuffer.push(s)}for(const i of this._sortingBuffer)this._noDepthTestingResults.push(i);return this._noDepthTestingResults}handleEventOnObject(t,i){if(!this.testIsVisible(t))return i.isClick&&Yc&&console.log("not allowed",t),!1;if(i.pointerId===void 0)return Yc&&console.error("Event without pointer can't be handled",i),!1;i.object=t;const s=t.parent;let r=!1;const o=i.isClick??!1;let a=null;if(s&&s.isUI){const f=(i.isPressed||i.isClick)??!1;if(s[jo]){const p=s[jo].gameObject;if(p){if(!Aw.isInteractable(p,this.out))return!1;a=this.out.canvasGroup??null,this.handleMeshUIIntersection(t,f),t=p,r=!0}}if(!r&&this.handleMeshUiObjectWithoutShadowDom(s,f))return!0}o&&Yc&&console.log(this.context.time.frame,t);const c=this.hoveredByID.get(i.pointerId),l=c==null?void 0:c.obj;l!==t&&l&&this.propagatePointerExit(l,c.data,t);const d=this.hoveredByID.get(i.pointerId);if(d?(d.obj=t,d.data=i):this.hoveredByID.set(i.pointerId,{obj:t,data:i}),i.isDown){const f=this.pressedByID.get(i.pointerId);f?(f.obj=t,f.data=i):this.pressedByID.set(i.pointerId,{obj:t,data:i,handlers:new Set})}return(a===null||a.interactable)&&this.handleMainInteraction(t,i,l??null),!0}propagate(t,i){for(;t;)le.foreachComponent(t,s=>{i(s)},!1),t=t.parent}handleMainInteraction(t,i,s){const r=this.pressedByID.get(i.pointerId),o=s!==t;let a=!0;switch(i.event.pointerType){case"mouse":case"touch":const c=this.context.input.getPointerPositionLastFrame(i.pointerId),l=this.context.input.getPointerPosition(i.pointerId);a=c&&!rt.approximately(c,l);break}this.propagate(t,c=>{const l=c;l.interactable!==!1&&(!l.activeAndEnabled||!l.enabled||(l.onPointerEnter&&o&&this.handlePointerEnter(l,i),i.isDown&&l.onPointerDown&&(l.onPointerDown(i),r==null||r.handlers.add(l),this.handlePointerCapture(i,l)),l.onPointerMove&&(a&&l.onPointerMove(i),this.handlePointerCapture(i,l)),i.isUp&&l.onPointerUp&&(this.invokeOnPointerUp(i,l),r==null||r.handlers.delete(l)),i.isClick&&l.onPointerClick&&l.onPointerClick(i)))}),i.isUp&&(r==null||r.handlers.forEach(c=>{this.invokeOnPointerUp(i,c)}),this.pressedByID.delete(i.pointerId))}propagatePointerExit(t,i,s){this.propagate(t,r=>{if(!r.gameObject||r.destroyed)return;const o=r;if(o.onPointerExit){if(s&&this.isChild(s,r.gameObject))return;this.handlePointerExit(o,i)}})}invokeOnPointerUp(t,i){var s;(s=i.onPointerUp)==null||s.call(i,t),this.releasePointerCapture(t,i)}handlePointerEnter(t,i){t.onPointerEnter&&this.updatePointerState(t,i.pointerId,this.pointerEnterSymbol,!0)&&t.onPointerEnter(i),this.updatePointerState(t,i.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(t,i){t.onPointerExit&&this.updatePointerState(t,i.pointerId,this.pointerExitSymbol,!0)&&t.onPointerExit(i),this.updatePointerState(t,i.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(t,i,s,r){let o=t[s];if(r)return o&&o.includes(i)?!1:(o=o||[],o.push(i),t[s]=o,!0);{if(!o||!o.includes(i))return!1;const a=o.indexOf(i);return a!==-1&&o.splice(a,1),!0}}handlePointerCapture(t,i){if(t.z__pointer_ctured){t.z__pointer_ctured=!1;const s=t.pointerId;if(i.onPointerMove){const r=this._capturedPointer[s]||[];r.push(i),this._capturedPointer[s]=r}else Mt()&&!i.z__warned_no_pointermove&&(i.z__warned_no_pointermove=!0,console.warn("PointerCapture was requested but the component doesn't implement onPointerMove. It will not receive any pointer events"))}else t.z__pointer_cture_rleased&&(t.z__pointer_cture_rleased=!1,this.releasePointerCapture(t,i))}releasePointerCapture(t,i){const s=t.pointerId;if(this._capturedPointer[s]){const r=this._capturedPointer[s].indexOf(i);r!==-1&&(this._capturedPointer[s].splice(r,1),Yc&&console.log("released pointer capture",s,i,this._capturedPointer))}}invokePointerCapture(t){var i;if(t.event.type===tn.PointerMove){const s=t.pointerId,r=this._capturedPointer[s];if(r){Yc&&console.log("Captured",s,r);for(let o=0;o<r.length;o++){const a=r[o];if(a.destroyed){r.splice(o,1),o--;continue}(i=a.onPointerMove)==null||i.call(a,t)}}}}isChild(t,i){return!t||!i?!1:t===i?!0:t.parent?this.isChild(t.parent,i):!1}handleMeshUiObjectWithoutShadowDom(t,i){return!t||!t.isUI?!0:this.handleMeshUIIntersection(t,i)}handleMeshUIIntersection(t,i){const s=yh.updateState(t,i);return s&&this.currentActiveMeshUIComponents.push(s),s!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&yh.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let t=0;t<this.currentActiveMeshUIComponents.length;t++){const i=this.currentActiveMeshUIComponents[t];yh.resetState(i)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(t){return t?le.isActiveSelf(t)?this.testIsVisible(t.parent):!1:!0}};let jr=ec;u(jr,"_eventSystemMap",new Map),u(jr,"didSearchEventSystem",!1);class yh{static markDirty(){this.needsUpdate=!0}static update(e,t,i=!1){if(i){e.update();return}const s=t.time.frameCount;for(const r of this.lastUpdateFrame)if(r.context===t){if(s===r.frame)return;r.frame=s;let o=this.needsUpdate||s<1;r.nextUpdate===t.time.frameCount&&(o=!0),o&&(Yc&&console.log("Update threemeshui"),this.needsUpdate=!1,e.update());return}this.lastUpdateFrame=[{context:t,frame:s,nextUpdate:s}],e.update()}static updateState(e,t){let i=null;if(e&&(i=this.findBlockInParent(e),i&&i!==this.lastSelected)){if(i.interactable===!1)return null;this.needsUpdate=!0}return i}static resetLastSelected(){const e=this.lastSelected;e&&(this.lastSelected=null,this.resetState(e))}static resetState(e){e&&(this.needsUpdate=!0)}static findBlockInParent(e){return e?e.isBlock?e:this.findBlockInParent(e.parent):null}}u(yh,"lastSelected",null),u(yh,"lastUpdateFrame",[]),u(yh,"needsUpdate",!1);var Hne=Object.defineProperty,Vne=Object.getOwnPropertyDescriptor,Qs=(n,e,t,i)=>{for(var s=i>1?void 0:i?Vne(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Hne(e,t,s),s};const Qne=se("debugorbit"),F0=se("freecam"),Zm=se("debugcamerafit"),U0=se("smoothcam"),jne={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let KC;class zv extends CustomEvent{constructor(e,t){super("target-reached",{detail:{controls:e,type:t}})}}class Ji extends Ie{constructor(){super(...arguments);u(this,"autoFit",!1);u(this,"enableRotate",!0);u(this,"autoRotate",!1);u(this,"autoRotateSpeed",1);u(this,"enableKeys",!0);u(this,"enableDamping",!0);u(this,"dampingFactor",.1);u(this,"enableZoom",!0);u(this,"minZoom",0);u(this,"maxZoom",1/0);u(this,"enablePan",!0);u(this,"lookAtConstraint",null);u(this,"lookAtConstraint01",1);u(this,"allowInterrupt",!0);u(this,"middleClickToFocus",!0);u(this,"doubleClickToFocus",!0);u(this,"useSlerp",!0);u(this,"debugLog",!1);u(this,"targetLerpDuration",1);u(this,"autoTarget",!0);u(this,"_controls",null);u(this,"_cameraObject",null);u(this,"_lookTargetLerpActive",!1);u(this,"_lookTargetStartPosition",new w);u(this,"_lookTargetEndPosition",new w);u(this,"_lookTargetLerp01",0);u(this,"_lookTargetLerpDuration",0);u(this,"_cameraLerpActive",!1);u(this,"_cameraStartPosition",new w);u(this,"_cameraEndPosition",new w);u(this,"_cameraLerp01",0);u(this,"_cameraLerpDuration",0);u(this,"_inputs",0);u(this,"_enableTime",0);u(this,"_startedListeningToKeyEvents",!1);u(this,"_eventSystem");u(this,"_afterHandleInputFn");u(this,"_camera",null);u(this,"_syncedTransform");u(this,"_didStart",!1);u(this,"targetElement",null);u(this,"onControlsChangeStarted",()=>{this._syncedTransform&&this._syncedTransform.requestOwnership()});u(this,"_shouldDisable",!1);u(this,"_haveAttachedKeyboardEvents",!1)}get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(t){var i;(i=this.controls)==null||i.addEventListener("start",t)}get targetLerpSpeed(){return 5}set targetLerpSpeed(t){this.targetLerpDuration=1/t}awake(){this._didStart=!1,this._startedListeningToKeyEvents=!1}start(){if(this._didStart=!0,this.autoTarget&&this._controls){const t=le.getComponent(this.gameObject,Yi);if(t&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const s=Dt(t.cam).length(),r=new w(0,0,-s).applyMatrix4(t.cam.matrixWorld);this.setLookTargetPosition(r,!0)}if(this.autoTarget&&!this.setLookTargetFromConstraint()){const i=new ta;i.screenPoint=new ie(0,0),i.lineThreshold=.1;const s=this.context.physics.raycast(i);s.length>0&&this.setLookTargetPosition(s[0].point,!0),Zm&&console.log("OrbitControls hits",...s)}this.autoFit&&this.fitCamera()}this._eventSystem=jr.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(kM.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){var t,i;(t=this._controls)==null||t.dispose(),(i=this._eventSystem)==null||i.removeEventListener(kM.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._enableTime=this.context.time.time;const t=le.getComponent(this.gameObject,Yi);this._camera=t;const i=t==null?void 0:t.cam;if(i&&t2(i,this,!0),!this._controls){if(!i){console.warn("OrbitControls: Requires a Camera component on the same object as this component.");return}i&&(this._cameraObject=i);const s=this.targetElement??this.context.renderer.domElement,r=i==null?void 0:i.quaternion.clone();this._controls=new xne(i,s),i==null||i.quaternion.copy(r),KC===void 0&&(KC={...this._controls.keys})}this._controls&&(F0&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,Ec()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),(i==null?void 0:i.type)==="PerspectiveCamera"?F0||(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):F0||(this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom),this._startedListeningToKeyEvents||(this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(window.document.body))),this._syncedTransform=le.getComponent(this.gameObject,Nh)??void 0}onDisable(){var t;(t=this._camera)!=null&&t.cam&&t2(this._camera.cam,this,!1),this._controls&&(this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted))}afterHandleInput(t){t.detail.args.pointerId===0&&(t.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!t.detail.args.isPressed||t.detail.args.isUp)&&(this._shouldDisable=!1))}onBeforeRender(){var i,s;if(!this._controls||this._cameraObject!==this.context.mainCamera)return;(this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2)||this.context.input.mouseWheelChanged||this.context.input.getPointerPressed(0)&&((i=this.context.input.getPointerPositionDelta(0))!=null&&i.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 t=this.middleClickToFocus&&this.context.input.getPointerClicked(1);if(t||(t=this.doubleClickToFocus&&this.context.input.getPointerDoubleClicked(0)&&this.context.time.time-this._enableTime>.3),t&&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 zv(this,"camera"));else{const r=rt.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,r)}if(this._lookTargetLerpActive)if(this._lookTargetLerp01+=this.context.time.deltaTime/this._lookTargetLerpDuration,this._lookTargetLerp01>=1)this._controls.target.copy(this._lookTargetEndPosition),this._lookTargetLerpActive=!1,this.dispatchEvent(new zv(this,"lookat"));else{const r=rt.easeInOutCubic(this._lookTargetLerp01);this._controls.target.lerpVectors(this._lookTargetStartPosition,this._lookTargetEndPosition,r)}}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?KC:jne,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,typeof U0=="number"||U0===!0){this._controls.enableDamping=!0;const r=typeof U0=="number"?U0:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,r))}this.allowInterrupt||(this._lookTargetLerpActive&&(this._controls.enablePan=!1),this._cameraLerpActive&&(this._controls.enableRotate=!1,this._controls.autoRotate=!1),(this._lookTargetLerpActive||this._cameraLerpActive)&&(this._controls.enableZoom=!1)),this.context.isInXR||(!F0&&((s=this.lookAtConstraint)!=null&&s.locked)&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(),Qne&&It.DrawWireSphere(this._controls.target,.1,65280))}}setCameraAndLookTarget(t){if(!t||!(t instanceof ge))return;const i=Dt(t),s=AR(t);this.setTargetFromRaycast(new bo(i,s)),this.setCameraTargetPosition(i)}setCameraTargetPosition(t,i=!1){var s,r;t&&(t instanceof ge&&(t=Dt(t)),this._cameraEndPosition||(this._cameraEndPosition=new w),this._cameraEndPosition.copy(t),i===!0?(this._cameraLerpActive=!1,(s=this.controllerObject)==null||s.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy((r=this._cameraObject)==null?void 0:r.position),typeof i=="number"?this._cameraLerpDuration=i:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setLookTargetPosition(t=null,i=!1){this._controls&&t&&(t instanceof ge&&(t=Dt(t)),this._lookTargetEndPosition.copy(t),i===!0?this._controls.target.copy(this._lookTargetEndPosition):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof i=="number"?this._lookTargetLerpDuration=i:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(t=0,i=1){var r;if(!this._controls)return!1;const s=(r=this.lookAtConstraint)==null?void 0:r.sources;if(s&&s.length>0){const o=s[t];if(o)return o.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._lookTargetEndPosition,i),!0}return!1}lerpTarget(t,i){return this.lerpLookTarget(t,i)}lerpLookTarget(t,i){this._controls&&(i>=1?this._controls.target.copy(t):this._controls.target.lerp(t,i))}setTargetFromRaycast(t){var s,r;if(!this.controls)return;const i=t?this.context.physics.raycastFromRay(t):this.context.physics.raycast();for(const o of i)if(o.distance>0&&le.isActiveInHierarchy(o.object)){const a=FR(o.object);if(a){const c=a.canvas;if(c!=null&&c.screenspace)break}if(this.setLookTargetPosition(o.point),this.context.mainCamera){const l=Dt(this.context.mainCamera).clone().sub(this.controls.target).add(this._lookTargetEndPosition);(r=(s=this._cameraObject)==null?void 0:s.parent)==null||r.worldToLocal(l),this.setCameraTargetPosition(l)}break}}fitCamera(t,i=1.1,s=!0){const r=this._cameraObject,o=this._controls;if(t!=null&&t.length||(t=this.context.scene.children),t.length<=0||!r||!o)return;const a=new w,c=new w,l=new Oi;l.makeEmpty();const h=[];function d(_){let b=!0;if(_.visible&&Sne(_)!==!1&&!(_.type==="TransformControlsGizmo"||_.type==="TransformControlsPlane")&&(_ instanceof S1&&(b=!1),_ instanceof Nx&&(b=!1),_ instanceof DH&&(b=!1),_.material instanceof Rx&&(b=!1),_ instanceof me||(b=!1),_!==r&&_.isUI!==!0)){if(b){Zm&&console.log(_.name,_.type,_);const C=_.children;_.children=h;const E=_.position,T=_.scale;if(Number.isNaN(E.x)||Number.isNaN(E.y)||Number.isNaN(E.z)){console.warn(`Object "${_.name}" has NaN values in position or scale.... will ignore it`,E,T);return}l.expandByObject(_,!0),_.children=C}for(const C of _.children)d(C)}}for(const _ of t)_.updateMatrixWorld(),d(_);if(r.updateMatrixWorld(),r.updateProjectionMatrix(),l.getCenter(c),l.applyMatrix4(r.matrixWorldInverse),l.getSize(a),l.setFromCenterAndSize(c,a),Number.isNaN(a.x)||Number.isNaN(a.y)||Number.isNaN(a.z)){console.warn("Camera fit size resultet in NaN",r,l,[...t]);return}if(a.length()<=1e-10){Zm&&console.warn("Camera fit size is zero",l,[...t]);return}const f=r.fov,p=2*Math.atan(Math.tan(f*Math.PI/360/2)*r.aspect)/Math.PI*360,m=a.y/(2*Math.atan(Math.PI*f/360)),g=a.x/(2*Math.atan(Math.PI*p/360)),y=i*Math.max(m,g)+a.z/2;Zm&&console.log("Fit camera to objects",m,g,"distance",y);const v=Dt(r),A=o.target.clone().sub(v).normalize().multiplyScalar(y);if(o.maxDistance=y*10,o.minDistance=y*.01,this.setLookTargetPosition(c,s),this.autoTarget=!1,r.near=y/1e3,r.far=y*100,r.updateMatrixWorld(),r.updateProjectionMatrix(),r.parent){const _=r.parent.worldToLocal(o.target.clone().sub(A));this.setCameraTargetPosition(_,s)}else console.error(`Can not fit camera ${r.name} because it has no parent`);if(Zm){const _=new S1(l);this.context.scene.add(_),bR(_,CA(r)),this._haveAttachedKeyboardEvents||(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",b=>{b.code==="KeyF"&&this.fitCamera(t)}))}o.update()}}Qs([x()],Ji.prototype,"autoFit",2);Qs([x()],Ji.prototype,"enableRotate",2);Qs([x()],Ji.prototype,"autoRotate",2);Qs([x()],Ji.prototype,"autoRotateSpeed",2);Qs([x()],Ji.prototype,"enableKeys",2);Qs([x()],Ji.prototype,"enableDamping",2);Qs([x()],Ji.prototype,"dampingFactor",2);Qs([x()],Ji.prototype,"enableZoom",2);Qs([x()],Ji.prototype,"minZoom",2);Qs([x()],Ji.prototype,"maxZoom",2);Qs([x()],Ji.prototype,"enablePan",2);Qs([x(LA)],Ji.prototype,"lookAtConstraint",2);Qs([x()],Ji.prototype,"lookAtConstraint01",2);Qs([x()],Ji.prototype,"allowInterrupt",2);Qs([x()],Ji.prototype,"middleClickToFocus",2);Qs([x()],Ji.prototype,"doubleClickToFocus",2);Qs([x()],Ji.prototype,"targetLerpDuration",2);var Wne=Object.defineProperty,qne=Object.getOwnPropertyDescriptor,wo=(n,e,t,i)=>{for(var s=i>1?void 0:i?qne(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Wne(e,t,s),s},wd=(n=>(n[n.Skybox=1]="Skybox",n[n.SolidColor=2]="SolidColor",n[n.Uninitialized=4]="Uninitialized",n))(wd||{});const Gu=se("debugcam"),s2=se("debugscreenpointtoray");var l_;const Sg=(l_=class extends Ie{constructor(){super(...arguments);u(this,"_nearClipPlane",.1);u(this,"_farClipPlane",1e3);u(this,"orthographic",!1);u(this,"orthographicSize",5);u(this,"ARBackgroundAlpha",0);u(this,"_cullingMask",4294967295);u(this,"_backgroundBlurriness");u(this,"_backgroundIntensity");u(this,"_environmentIntensity");u(this,"_targetTexture",null);u(this,"_backgroundColor");u(this,"_fov");u(this,"_cam",null);u(this,"_clearFlags",2);u(this,"_skybox")}get isCamera(){return!0}get aspect(){return this._cam instanceof Jt?this._cam.aspect:this.context.domWidth/this.context.domHeight}get fieldOfView(){return this._cam instanceof Jt?this._cam.fov:this._fov}set fieldOfView(e){const t=this.fieldOfView!=e;if(this._fov=e,t&&this._cam&&this._cam instanceof Jt){if(this._fov===void 0){console.warn("Can not set undefined fov on PerspectiveCamera");return}this._cam.fov=this._fov,this._cam.updateProjectionMatrix()}}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(e){const t=this._nearClipPlane!=e;this._nearClipPlane=e,this._cam&&t&&(this._cam.near=e,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(e){const t=this._farClipPlane!=e;this._farClipPlane=e,this._cam&&t&&(this._cam.far=e,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(e){e!==this._clearFlags&&(this._clearFlags=e,this.applyClearFlagsIfIsActiveCamera())}set cullingMask(e){this._cullingMask=e,this._cam&&(this._cam.layers.mask=e)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}set cullingLayer(e){this.cullingMask=(1<<e|0)>>>0}set backgroundBlurriness(e){e!==this._backgroundBlurriness&&(e===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(e,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}set backgroundIntensity(e){e!==this._backgroundIntensity&&(e===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(e,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}set environmentIntensity(e){this._environmentIntensity=e}get environmentIntensity(){return this._environmentIntensity}get backgroundColor(){return this._backgroundColor??null}set backgroundColor(e){if(e){if(this._backgroundColor)this._backgroundColor.copy(e);else{if(!e.clone)return;this._backgroundColor=e.clone()}e.alpha===void 0&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera()}}set targetTexture(e){this._targetTexture=e}get targetTexture(){return this._targetTexture}get cam(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(e,t,i){const s=this.cam,r=Sg._origin;r.set(e,t,-1),this.context.input.convertScreenspaceToRaycastSpace(r),s2&&console.log("screenPointToRay",e.toFixed(2),t.toFixed(2),"now:",r.x.toFixed(2),r.y.toFixed(2),"isInXR:"+this.context.isInXR),r.z=-1,r.unproject(s);const o=Sg._direction.set(r.x,r.y,r.z),a=Dt(s);return o.sub(a),o.normalize(),i?(i.set(a,o),i):new bo(a.clone(),o.clone())}awake(){s2&&window.addEventListener("pointerdown",e=>{const t=e.clientX,i=e.clientY;console.log("touch",t.toFixed(2),i.toFixed(2));const s=this.screenPointToRay(t,i),r="#"+Math.floor(Math.random()*16777215).toString(16);It.DrawRay(s.origin,s.direction,r,10)})}onEnable(){Gu&&console.log(`Camera enabled: "${this.name}". ClearFlags=${wd[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),Yne(this)),this.applyClearFlagsIfIsActiveCamera()}onDisable(){this.context.removeCamera(this)}onBeforeRender(){if(this._cam&&(this._clearFlags===2&&this.applyClearFlagsIfIsActiveCamera(),this._targetTexture)){this.context.isManagedExternally&&(this._warnedAboutExternalRenderer||(this._warnedAboutExternalRenderer=!0,console.warn("Rendering with external renderer is not supported yet. This may not work or throw errors. Please remove the the target texture from your camera: "+this.name,this.targetTexture))),this.context.composer;const e=this.context.renderer;if(e){const t=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,e),t==null||t.applyClearFlags()}}}buildCamera(){if(this._cam)return;const e=this.gameObject.isCamera;let t=null;if(e?(t=this.gameObject,t==null||t.layers.enableAll(),t instanceof Jt&&(this._fov=t.fov)):t=this.gameObject.children[0],t&&t.isCamera)t instanceof Jt&&(this._fov&&(t.fov=this._fov),t.near=this._nearClipPlane,t.far=this._farClipPlane,t.updateProjectionMatrix());else if(!this.orthographic)t=new Jt(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(t.fov=this.fieldOfView),this.gameObject.add(t);else{const i=this.orthographicSize*100;t=new Pl(window.innerWidth/-i,window.innerWidth/i,window.innerHeight/i,window.innerHeight/-i,this._nearClipPlane,this._farClipPlane),this.gameObject.add(t)}this._cam=t,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(){this.context.mainCameraComponent===this&&this.applyClearFlags()}applyClearFlags(){if(!this._cam){Gu&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this._fov,Gu){const e=`Camera "${this.name}" clear flags: ${wd[this._clearFlags]}`;console.log(e)}switch(this._clearFlags){case 1:if(Sg.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),this._backgroundIntensity!==void 0&&(this.context.scene.backgroundIntensity=this._backgroundIntensity);break;case 2:if(this._backgroundColor){let e=this._backgroundColor.alpha;Sg.backgroundShouldBeTransparent(this.context)&&(e=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.renderer.setClearColor(this._backgroundColor,e)}else Gu&&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 Xne(this)),this._skybox.enable()}static backgroundShouldBeTransparent(e){var r,o,a,c;const t=(r=e.renderer.xr)==null?void 0:r.getSession();if(!t)return!1;if(typeof t._transparent=="boolean")return t._transparent;const i=t.environmentBlendMode;Gu&&xn("Environment blend mode: "+i+" on "+navigator.userAgent);let s=i==="additive"||i==="alpha-blend";return e.isInAR&&i==="opaque"&&((o=navigator.userAgent)!=null&&o.includes("OculusBrowser")||(a=navigator.userAgent)!=null&&a.includes("Mozilla")&&((c=navigator.userAgent)!=null&&c.includes("Mobile WebXRViewer/v2")))&&(s=!0),t._transparent=s,s}},u(l_,"_origin",new w),u(l_,"_direction",new w),l_);let Yi=Sg;wo([x()],Yi.prototype,"fieldOfView",1);wo([x()],Yi.prototype,"nearClipPlane",1);wo([x()],Yi.prototype,"farClipPlane",1);wo([x()],Yi.prototype,"clearFlags",1);wo([x()],Yi.prototype,"orthographic",2);wo([x()],Yi.prototype,"orthographicSize",2);wo([x()],Yi.prototype,"ARBackgroundAlpha",2);wo([x()],Yi.prototype,"cullingMask",1);wo([x()],Yi.prototype,"backgroundBlurriness",1);wo([x()],Yi.prototype,"backgroundIntensity",1);wo([x()],Yi.prototype,"environmentIntensity",1);wo([x(Ti)],Yi.prototype,"backgroundColor",1);wo([x(Rh)],Yi.prototype,"targetTexture",1);class Xne{constructor(e){u(this,"_camera");u(this,"_skybox");this._camera=e}get context(){var e;return(e=this._camera)==null?void 0:e.context}enable(){this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),this._skybox?this.context.scene.background!==this._skybox&&(Gu&&console.log(`Camera "${this._camera.name}" set skybox`,this._camera,this._skybox),this._skybox.colorSpace=Wt,this._skybox.mapping=Xo,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)),(Gu||Mt())&&pn(`Camera "${this._camera.name}" has no skybox texture`))}}function Yne(n){se("freecam")&&n.context.mainCameraComponent===n&&le.getOrAddComponent(n.gameObject,Ji)}class Ph extends Ie{constructor(){super(...arguments);u(this,"_listener",null)}get listener(){return this._listener==null&&(this._listener=new TU),this._listener}awake(){Cn.registerWaitForAllowAudio(()=>{if(this.destroyed)return;const t=this.listener;if(t==null||t.parent)return;const i=this.context.mainCameraComponent||le.getComponentInParent(this.gameObject,Yi);i!=null&&i.cam?i.cam.add(t):this.gameObject.add(t)})}}var Jne=Object.defineProperty,Kne=Object.getOwnPropertyDescriptor,yw=(n,e,t,i)=>{for(var s=i>1?void 0:i?Kne(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Jne(e,t,s),s};const Zne=se("debugsignals");class NA{constructor(){u(this,"guid")}}yw([x()],NA.prototype,"guid",2);class om{constructor(){u(this,"signal");u(this,"reaction")}}yw([x(NA)],om.prototype,"signal",2);yw([x(gs)],om.prototype,"reaction",2);var kE;const Jc=(kE=class extends Ie{constructor(){super(...arguments);u(this,"events")}static invoke(e){if(Jc.receivers[e]){const t=Jc.receivers[e];if(!t)return;for(const i of t)i.invoke(e)}}awake(){Zne&&console.log("SignalReceiver awake",this)}onEnable(){if(this.events)for(const e of this.events)Jc.receivers[e.signal.guid]||(Jc.receivers[e.signal.guid]=[]),Jc.receivers[e.signal.guid].push(this)}onDisable(){if(this.events){for(const e of this.events)if(Jc.receivers[e.signal.guid]){const t=Jc.receivers[e.signal.guid].indexOf(this);t>=0&&Jc.receivers[e.signal.guid].splice(t,1)}}}invoke(e){if(!this.events||!Array.isArray(this.events))return;const t=typeof e=="object"?e.guid:e;for(const i of this.events)if(i.signal.guid===t)try{if(i.reaction){if(!i.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",i,this);continue}}else{console.warn("Missing reaction for signal",i,this);continue}i.reaction.invoke()}catch(s){console.error(s)}}},u(kE,"receivers",{}),kE);let am=Jc;yw([x(om)],am.prototype,"events",2);var io=(n=>(n.Activation="ActivationTrack",n.Animation="AnimationTrack",n.Audio="AudioTrack",n.Control="ControlTrack",n.Marker="MarkerTrack",n.Signal="SignalTrack",n))(io||{}),Za=(n=>(n[n.None=0]="None",n[n.Hold=1]="Hold",n[n.Loop=2]="Loop",n[n.PingPong=3]="PingPong",n[n.Continue=4]="Continue",n))(Za||{}),UR=(n=>(n.Signal="SignalEmitter",n))(UR||{});const pc=se("debugtimeline");class zA{constructor(){u(this,"director");u(this,"track")}get muted(){return this.track.muted}set muted(e){var t;e!==this.track.muted&&(this.track.muted=e,(t=this.onMuteChanged)==null||t.call(this))}*forEachClip(e=!1){var t;if((t=this.track)!=null&&t.clips)if(e)for(let i=this.track.clips.length-1;i>=0;i--)yield this.track.clips[i];else for(const i of this.track.clips)yield i}getClipTime(e,t){return t.clipIn+(e-t.start)*t.timeScale}getClipTimeNormalized(e,t){return(e-t.start)/t.duration}evaluateWeight(e,t,i,s=!0){if(t<0||t>=i.length)return 0;const r=i[t];if(s||e>=r.start&&e<=r.end){let o=1;const a=!1;if(r.easeInDuration>0){const c=Math.min((e-r.start)/r.easeInDuration,1);o*=c}if(r.easeOutDuration>0&&!a){const c=Math.min((r.end-e)/r.easeOutDuration,1);o*=c}return o}return 0}}class $ne{constructor(e){u(this,"clip");u(this,"rootPositionOffset");u(this,"rootQuaternionOffset");u(this,"rootStartPosition");u(this,"rootEndPosition");u(this,"rootStartQuaternion");u(this,"rootEndQuaternion");const t=e.getClip();this.clip=t;const i=e.getRoot(),s=i.name+".position",r=i.name+".quaternion";pc&&console.log(t.name,t.tracks,s);for(const o of t.tracks)if(!(o.times.length<=0)){if(o.name.endsWith(s))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),pc&&console.log(this.rootPositionOffset);else if(o.name.endsWith(r)&&(this.rootStartQuaternion=new Ee().fromArray(o.values,0),this.rootEndQuaternion=new Ee().fromArray(o.values,o.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),pc)){const a=new ks().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",a)}}}get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}}class _w extends zA{constructor(){super(...arguments);u(this,"models",[]);u(this,"trackOffset");u(this,"target");u(this,"mixer");u(this,"clips",[]);u(this,"actions",[]);u(this,"_actionOffsets",[]);u(this,"_didBind",!1);u(this,"_animator",null);u(this,"_useclipOffsets",!0);u(this,"_totalOffsetPosition",new w);u(this,"_totalOffsetRotation",new Ee);u(this,"_totalOffsetPosition2",new w);u(this,"_totalOffsetRotation2",new Ee);u(this,"_summedPos",new w);u(this,"_tempPos",new w);u(this,"_summedRot",new Ee);u(this,"_tempRot",new Ee);u(this,"_clipRotQuat",new Ee)}onStateChanged(){this._animator&&r2(this._animator.gameObject,this,this.director.isPlaying)}createHooks(t,i){var h,d;if(((h=i.tracks)==null?void 0:h.length)<=0){console.warn("No tracks in AnimationClip",i);return}const s=i.tracks[0].name.split("."),r=s[s.length-2],o=r+".position",a=r+".quaternion";let c=!1,l=!1;for(const f of i.tracks)f.name.endsWith(o)?(c=!0,this.createPositionInterpolant(i,t,f)):f.name.endsWith(a)&&(l=!0,this.createRotationInterpolant(i,t,f));if(!c||!l){const f=(d=this.mixer)==null?void 0:d.getRoot(),p=i.tracks[0],m=p.name.lastIndexOf("."),g=p.name.substring(0,m),y=g.substring(g.lastIndexOf(".")+1),v=f.getObjectByName(y);if(v)if(c){if(!l){const A=i.tracks[0].name.substring(0,m)+".quaternion";pc&&console.warn("Create quaternion track",y,v);const _=v.quaternion,b=new Sc(A,[0,i.duration],[_.x,_.y,_.z,_.w,_.x,_.y,_.z,_.w]);i.tracks.push(b),this.createRotationInterpolant(i,t,b)}}else{const A=g+".position";pc&&console.warn("Create position track",y,v);const _=v.position,b=new El(A,[0,i.duration],[_.x,_.y,_.z,_.x,_.y,_.z]);i.tracks.push(b),this.createPositionInterpolant(i,t,b)}}}bind(){if(!this._didBind){this._didBind=!0,pc&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(const t of this.actions){const i=new $ne(t);this._actionOffsets.push(i)}this.target&&(this._animator=le.getComponent(this.target,Us)??null,this._animator&&r2(this._animator.gameObject,this,!0));for(const t of this.models){const i=t.asset,s=i.position,r=i.rotation;s&&s.x!==void 0&&(s.isVector3||(i.position=new w(s.x,s.y,s.z)),r.isQuaternion||(i.rotation=new Ee(r.x,r.y,r.z,r.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){const t=this.trackOffset.position;t&&(t.isVector3||(this.trackOffset.position=new w(t.x,t.y,t.z)));const i=this.trackOffset.rotation;i&&(i.isQuaternion||(this.trackOffset.rotation=new Ee(i.x,i.y,i.z,i.w)))}}evaluate(t){var c,l,h,d,f,p,m;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 i=0,s=0,r=!1,o=!1,a=0;for(let g=0;g<this.clips.length;g++){const y=this.models[g],v=this.actions[g],A=y.asset;v.weight=0;const _=t>=y.start&&t<=y.end,b=y.preExtrapolationMode,C=y.postExtrapolationMode,E=g<this.clips.length-1?this.models[g+1]:null;let T=_,I=!1;if(!T&&!r&&y.end<t&&C!==Za.None?(!E||E.start>t)&&(T=!0,r=!0):g==0&&!T&&!o&&y.start>t&&b!==Za.None&&(!E||E.start<t)&&(T=!0,I=!0,o=!0),T){let S=1;S*=this.evaluateWeight(t,g,this.models,T),S*=this.director.weight;let M=_;if(I)switch(b){case Za.Hold:break;case Za.Loop:t+=y.start,M=!0;break;default:t+=y.start,M=!0;break}let D=this.getClipTime(t,y),G=0;const Q=A.duration;if(I&&b===Za.Hold&&(D=0),M){if(A.loop)for(G+=Math.floor(D/(Q+1e-6));D>Q;)D-=Q}else if(!_&&r)switch(C){case Za.Hold:D=this.getClipTime(y.end,y);break;case Za.Loop:D%=Q;break;case Za.PingPong:const O=Math.floor(D/Q)%2!==0;D%=Q,O&&(D=Q-D);break}y.reversed===!0?v.time=v.getClip().duration-D:v.time=D,v.timeScale=0;const L=Math.max(0,S);if(v.weight=L,a+=L,v.clampWhenFinished=!1,v.isRunning()||v.play(),this._useclipOffsets){const H=i==0?this._totalOffsetPosition:this._totalOffsetPosition2,O=i==0?this._totalOffsetRotation:this._totalOffsetRotation2;i<1&&(s=1-S),i+=1;const U=this._summedPos.set(0,0,0),V=this._tempPos.set(0,0,0),J=this._summedRot.identity(),K=this._tempRot.identity(),oe=A.rotation;oe&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp(oe,S));const fe=this._actionOffsets[g];if(fe.hasOffsets)for(let be=0;be<G;be++)fe.rootPositionOffset?V.copy(fe.rootPositionOffset):V.set(0,0,0),V.applyQuaternion(J),this._clipRotQuat&&V.applyQuaternion(this._clipRotQuat),fe.rootQuaternionOffset&&(K.copy(fe.rootQuaternionOffset),J.multiply(K)),U.add(V);this._clipRotQuat&&O.multiply(this._clipRotQuat),O.multiply(J),A.position&&U.add(A.position),H.add(U)}}}if(this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,s),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,s)),this.__mixerError===void 0&&(pc||Mt())&&((l=(c=this._animator)==null?void 0:c.runtimeAnimatorController)!=null&&l.mixer)&&this.mixer!==((d=(h=this._animator)==null?void 0:h.runtimeAnimatorController)==null?void 0:d.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)),(f=this._animator)!=null&&f.runtimeAnimatorController){const g=Math.max(0,1-a);(m=(p=this._animator)==null?void 0:p.runtimeAnimatorController)==null||m.update(g)}else this.mixer.update(t)}createRotationInterpolant(t,i,s){var c;const r=s.createInterpolant.bind(s),o=new Ee;this.ensureTrackOffsets();const a=(c=this.trackOffset)==null?void 0:c.rotation;s.createInterpolant=()=>{const l=r(),h=l.evaluate.bind(l);return l.evaluate=d=>{var p;const f=h(d);if(o.set(f[0],f[1],f[2],f[3]),o.premultiply(this._totalOffsetRotation),a&&o.premultiply(a),this.director.animationCallbackReceivers)for(const m of this.director.animationCallbackReceivers)(p=m==null?void 0:m.onTimelineRotation)==null||p.call(m,this.director,this.target,d,o);return f[0]=o.x,f[1]=o.y,f[2]=o.z,f[3]=o.w,f},l}}createPositionInterpolant(t,i,s){var h,d;const r=s.createInterpolant.bind(s),o=new w;this.ensureTrackOffsets();const a=(h=this.trackOffset)==null?void 0:h.rotation,c=(d=this.trackOffset)==null?void 0:d.position;let l;s.createInterpolant=()=>{const f=r(),p=f.evaluate.bind(f);return f.evaluate=m=>{var y,v,A;const g=p(m);if(o.set(g[0],g[1],g[2]),i.removeStartOffset&&(l===void 0?(l=null,l=(v=(y=this._actionOffsets.find(_=>_.clip===t))==null?void 0:y.rootStartPosition)==null?void 0:v.clone()):l!=null&&l.isVector3&&o.sub(l)),o.applyQuaternion(this._totalOffsetRotation),o.add(this._totalOffsetPosition),a&&o.applyQuaternion(a),c&&(o.x-=c.x,o.y+=c.y,o.z+=c.z),this.director.animationCallbackReceivers)for(const _ of this.director.animationCallbackReceivers)(A=_==null?void 0:_.onTimelinePosition)==null||A.call(_,this.director,this.target,m,o);return g[0]=o.x,g[1]=o.y,g[2]=o.z,g},f}}}const ese=se("mutetimeline"),op=class extends zA{constructor(){super(...arguments);u(this,"models",[]);u(this,"listener");u(this,"audio",[]);u(this,"audioContextTimeOffset",[]);u(this,"lastTime",0);u(this,"audioSource");u(this,"_audioLoader",null);u(this,"_playableDirectorResumed",!1)}getAudioFilePath(t){const i=this.director.sourceId;return Wh(i,t)}onAllowAudioChanged(t){for(let i=0;i<this.models.length;i++){const s=this.models[i];this.audio[i].setVolume(t?s.asset.volume:0)}}addModel(t){const i=new tI(this.listener);this.audio.push(i);const s=t;s._didTriggerPlay=!1,this.models.push(s)}onDisable(){for(const t of this.audio)t.isPlaying&&t.stop();for(const t of this.models)t._didTriggerPlay=!1}onDestroy(){for(const t of this.audio)t.source&&(t==null||t.disconnect());this.audio.length=0}onMuteChanged(){if(this.muted)for(let t=0;t<this.audio.length;t++){const i=this.audio[t];i!=null&&i.isPlaying&&i.stop()}}stop(){for(let t=0;t<this.audio.length;t++){const i=this.audio[t];i!=null&&i.isPlaying&&i.stop()}for(const t of this.models)t._didTriggerPlay=!1}onPauseChanged(){for(let t=0;t<this.audio.length;t++){const i=this.audio[t];i!=null&&i.isPlaying&&i.stop()}this._playableDirectorResumed=this.director.isPlaying}evaluate(t){if(ese||this.track.muted||this.director.speed<0)return;const i=this.director.context.application.muted,s=this._playableDirectorResumed;this._playableDirectorResumed=!1;const r=i?.1:0;for(let o=0;o<this.models.length;o++){const a=this.models[o],c=this.audio[o],l=a.asset;if((!c||!c.buffer)&&this.isInTimeRange(a,t-1,t+1)&&this.handleAudioLoading(a,c),Cn.userInteractionRegistered!==!1&&!(c===null||!c.buffer))if(c.playbackRate=this.director.context.time.timeScale*this.director.speed,c.loop=l.loop,t>=a.start&&t<=a.end&&t<this.director.duration){if(!c.isPlaying||!this.director.isPlaying)(s||!a._didTriggerPlay&&this.lastTime<t)&&(a.duration*a.timeScale>.3?c.offset=a.clipIn+(t-a.start)*a.timeScale:c.offset=0,pc&&console.log("Timeline Audio ("+this.track.name+") play with offset "+c.offset+" - "+a.asset.clip),c.play(r),a._didTriggerPlay=!0);else{const d=a.clipIn+(t-a.start)*a.timeScale,f=c.context.currentTime-c._startedAt+c.offset;Math.abs(d-f)>.3&&(c.offset=d,c.stop(),c.play(r))}let h=l.volume;if(this.track.volume!==void 0&&(h*=this.track.volume),i&&(h=0),a.easeInDuration>0){const d=Math.min((t-a.start)/a.easeInDuration,1);h*=d}if(a.easeOutDuration>0){const d=Math.min((a.end-t)/a.easeOutDuration,1);h*=d}c.setVolume(h*this.director.weight)}else a._didTriggerPlay=!1,this.director.isPlaying&&c.isPlaying&&c.stop()}this.lastTime=t}loadAudio(t,i=0,s=0){let r=null;const o=t-s,a=t+i;for(const c of this.models)if(this.isInTimeRange(c,o,a)){const l=this.audio[this.models.indexOf(c)],h=this.handleAudioLoading(c,l);h!==null&&(r===null&&(r=[]),r.push(h))}return r!==null?Promise.all(r):null}isInTimeRange(t,i,s){return i<=t.start&&s>=t.end||i>=t.start&&i<=t.end||s>=t.start&&s<=t.end}static dispose(){op._audioBuffers.clear()}handleAudioLoading(t,i){this._audioLoader||(this._audioLoader=new db);const s=this.getAudioFilePath(t.asset.clip);if(op._audioBuffers.get(s)){const o=op._audioBuffers.get(s);return o.then(a=>{a&&i.setBuffer(a)}),o}pc&&console.warn("LOAD audio track",s,this.director.sourceId);const r=new Promise((o,a)=>{this._audioLoader.load(s,c=>{i.setBuffer(c),o(c)},void 0,c=>{console.error("Error loading audio",c),o(null)})});return op._audioBuffers.set(s,r),r}};let hd=op;u(hd,"_audioBuffers",new Map);class Gv extends zA{constructor(){super(...arguments);u(this,"models",[]);u(this,"didTrigger",[]);u(this,"receivers",[])}evaluate(t){var s;if(this.track.muted)return;const i=this.director.context.time.deltaTime*1.5;for(let r=0;r<this.models.length;r++){const o=this.models[r],a=this.didTrigger[r],c=o.time-t;let l=!1;if(o.retroActive)l=c<=1e-6;else{const h=Math.abs(c);(h===0||h>=1e-5&&h<i)&&(l=!0)}if(l){if(!a)if(pc&&console.log("Trigger signal",t,o.time,o),this.didTrigger[r]=!0,((s=this.receivers)==null?void 0:s.length)<=0)am.invoke(o.asset);else for(const h of this.receivers)h&&h.invoke(o.asset)}else o.emitOnce||(this.didTrigger[r]=!1)}}}class bw extends zA{constructor(){super(...arguments);u(this,"models",[]);u(this,"timelines",[]);u(this,"_previousActiveModel",null)}resolveSourceObjects(t){for(let i=this.models.length-1;i>=0;i--){const r=this.models[i].asset;if(!r.sourceObject||typeof r.sourceObject!="object"){console.log("no source object, removing model",i,r),this.models.splice(i,1);continue}else{const o=le.getComponent(r.sourceObject,Sl);this.timelines.push(o),o&&r.updateDirector&&(o.playOnAwake=!1)}}}evaluate(t){var i;this._previousActiveModel=null;for(let s=0;s<this.models.length;s++){const r=this.models[s],o=r.asset;if(t>=r.start&&t<=r.end){this._previousActiveModel=r;const a=this.getClipTime(t,r);if(o.controlActivation){const c=o.sourceObject;c.visible=!0}if(o.updateDirector){const c=this.timelines[s];c&&(c.isPlaying&&c.pause(),c.time=a,c.evaluate())}}else{const a=(i=this._previousActiveModel)==null?void 0:i.asset;if(o.controlActivation){const c=o.sourceObject;(a==null?void 0:a.sourceObject)!==c&&(c.visible=!1)}}}}}const Ef=se("debugtimeline"),ex=class extends Ie{constructor(){super(...arguments);u(this,"playableAsset");u(this,"playOnAwake");u(this,"extrapolationMode",1);u(this,"waitForAudio",!0);u(this,"_visibilityChangeEvt");u(this,"_clonedPlayableAsset",!1);u(this,"_speed",1);u(this,"_guidsMap");u(this,"_isPlaying",!1);u(this,"_internalUpdateRoutine");u(this,"_isPaused",!1);u(this,"_isStopping",!1);u(this,"_time",0);u(this,"_duration",0);u(this,"_weight",1);u(this,"_animationTracks",[]);u(this,"_audioTracks",[]);u(this,"_signalTracks",[]);u(this,"_controlTracks",[]);u(this,"_customTracks",[]);u(this,"_allTracks",[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks]);u(this,"animationCallbackReceivers",[])}static registerCreateTrack(t,i){this.createTrackFunctions[t]=i}get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(t){typeof t=="number"&&!Number.isNaN(t)?this._time=t:(Ef||Er())&&console.error("INVALID TIMELINE.TIME VALUE",t,this.name)}get duration(){return this._duration}set duration(t){this._duration=t}get weight(){return this._weight}set weight(t){this._weight=t}get speed(){return this._speed}set speed(t){this._speed=t}awake(){var t,i,s;Ef&&console.log(this,(t=this.playableAsset)==null?void 0:t.tracks),this.rebuildGraph(),this.isValid()||console.warn("PlayableDirector is not valid",this.playableAsset,(i=this.playableAsset)==null?void 0:i.tracks,Array.isArray((s=this.playableAsset)==null?void 0:s.tracks),this)}onEnable(){var t,i,s;for(const r of this._audioTracks)(t=r.onEnable)==null||t.call(r);for(const r of this._customTracks)(i=r.onEnable)==null||i.call(r);for(const r of this._animationTracks)(s=r.onEnable)==null||s.call(r);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 t,i,s;this.stop();for(const r of this._audioTracks)(t=r.onDisable)==null||t.call(r);for(const r of this._customTracks)(i=r.onDisable)==null||i.call(r);for(const r of this._animationTracks)(s=r.onDisable)==null||s.call(r);this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){var t;for(const i of this._allTracks)for(const s of i)(t=s.onDestroy)==null||t.call(s)}rebuildGraph(){this.isValid()&&(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}async play(){if(!this.isValid())return;const t=this._isPaused==!0;if(this._isPaused=!1,!this._isPlaying){if(this._isPlaying=!0,t&&this.invokePauseChangedMethodsOnTracks(),this.waitForAudio){const i=[];for(const s of this._audioTracks){const r=s.loadAudio(this._time,1,0);r&&i.push(r)}if(i.length>0&&(await Promise.all(i),!this._isPlaying))return;for(;this._audioTracks.length>0&&this._isPlaying&&!Cn.userInteractionRegistered&&this.waitForAudio;)await Yo(200)}this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate(),Vn.LateUpdate)}}pause(){this.isValid()&&(this._isPlaying=!1,!this._isPaused&&(this._isPaused=!0,this.internalEvaluate(),this.invokePauseChangedMethodsOnTracks(),this.invokeStateChangedMethodsOnTracks()))}stop(){this._isStopping=!0;for(const s of this._audioTracks)s.stop();const t=this._isPaused==!0,i=this._isPlaying;this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.internalEvaluate(),t&&this.invokePauseChangedMethodsOnTracks()),this._isPlaying=!1,this._isPaused=!1,t&&!i&&this.invokePauseChangedMethodsOnTracks(),i&&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 t of this._allTracks)for(const i of t)yield i}get audioTracks(){return this._audioTracks}resolveGuids(t){this._guidsMap=t}invokePauseChangedMethodsOnTracks(){var t;for(const i of this.forEachTrack())(t=i.onPauseChanged)==null||t.call(i)}invokeStateChangedMethodsOnTracks(){var t;for(const i of this.forEachTrack())(t=i.onStateChanged)==null||t.call(i,this._isPlaying)}*internalUpdate(){for(;this._isPlaying&&this.activeAndEnabled;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime*this.speed,this.internalEvaluate()),yield}internalEvaluate(t=!1){if(!this.isValid())return;let i=this._time;switch(this.extrapolationMode){case 0:this._speed>0?i=Math.min(i,this._duration):this._speed<0&&(i=Math.max(i,0)),this._time=i;break;case 1:i%=this._duration,this._time=i;break;case 2:if(i>this._duration){this.stop();return}break}const s=this._time;for(const r of this.playableAsset.tracks)if(!r.muted)switch(r.type){case io.Activation:if(!t&&!this._isPlaying)continue;for(let o=0;o<r.outputs.length;o++){const a=r.outputs[o];if(typeof a=="object"){let c=!1;if(r.clips)for(const h of r.clips)h.start<=s&&s<=h.end&&(c=!0);const l=a;l.visible!==void 0&&l.visible!==c&&(l.visible=c,Ef&&console.warn(this.name,"set ActivationTrack-"+o,l.name,c,s))}}break}if(!this._isStopping)for(const r of this._animationTracks)r.evaluate(s);for(const r of this._audioTracks)r.evaluate(s);for(const r of this._signalTracks)r.evaluate(s);for(const r of this._controlTracks)r.evaluate(s);for(const r of this._customTracks)r.evaluate(s)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=dA(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;const t=this.findRoot(this.gameObject);for(const i of this.playableAsset.tracks){for(let s=i.outputs.length-1;s>=0;s--){let r=i.outputs[s];if(typeof r=="string"){this._guidsMap&&this._guidsMap[r]&&(r=this._guidsMap[r]);const o=le.findByGuid(r,t);o===null||typeof o!="object"?(i.outputs.splice(s,1),console.warn("Failed to resolve binding",r,i.name,i.type)):(Ef&&console.log("Resolved binding",r,"to",o),i.outputs[s]=o)}else if(r===null){if(i.outputs.splice(s,1),ex.createTrackFunctions[i.type])continue;i.type!==io.Audio&&i.type!==io.Control&&i.type!==io.Marker&&i.type!==io.Signal&&console.warn("Missing binding",r,i.name,i.type,this.name,this.playableAsset.name)}}if(i.type===io.Control&&i.clips)for(let s=0;s<i.clips.length;s++){const r=i.clips[s];let o=r.asset.sourceObject;if(typeof o=="string"){this._guidsMap&&this._guidsMap[o]&&(o=this._guidsMap[o]);const a=le.findByGuid(o,t);a===null||typeof a!="object"?console.warn("Failed to resolve sourceObject binding",o,i.name,r):(Ef&&console.log("Resolved binding",o,"to",a),r.asset.sourceObject=a)}}}}findRoot(t){return t.parent?this.findRoot(t.parent):t}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const t of this.playableAsset.tracks)if(t.muted!==!0){if(t.clips)for(const i of t.clips)i.end>this._duration&&(this._duration=i.end);if(t.markers)for(const i of t.markers)i.time>this._duration&&(this._duration=i.time+.001)}}}setupAndCreateTrackHandlers(){var i,s,r;if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let t=le.findObjectOfType(Ph,this.context);for(const o of this.playableAsset.tracks){const a=o.type,c=ex.createTrackFunctions[a];if(c!=null){const l=c(this,o);if(typeof l.evaluate=="function"){l.director=this,l.track=o,this._customTracks.push(l);continue}}if(o.type===io.Animation){if(!o.clips||o.clips.length<=0){Ef&&console.warn("Animation track has no clips",o);continue}for(let l=o.outputs.length-1;l>=0;l--){let h=o.outputs[l];if(h instanceof ge){const f=le.getOrAddComponent(h,Us);f&&(h=f)}const d=(i=h==null?void 0:h.gameObject)==null?void 0:i.animations;if(d){const f=new _w;f.trackOffset=o.trackOffset,f.director=this,f.track=o;for(let p=0;p<o.clips.length;p++){const m=o.clips[p],g=m.asset;if(!g){console.error(`Timeline ${this.name}: clip #${p} on track "${o.name}" has no animation data`);continue}const y=g.clip;let v=y;if((typeof v=="string"||typeof v=="number")&&(v=d.find(_=>_.name===y)),!v){console.warn("Could not find animationClip for model",m,o.name,this.name,(s=this.playableAsset)==null?void 0:s.name);continue}h instanceof Us&&h.runtimeAnimatorController&&(h.__internalDidAwakeAndStart||h.initializeRuntimeAnimatorController(),h.runtimeAnimatorController.mixer||h.runtimeAnimatorController.bind(h),f.mixer=h.runtimeAnimatorController.mixer),f.mixer||(f.mixer=new Ux(h.gameObject)),f.clips.push(v),f.mixer.uncacheAction(v),f.createHooks(m.asset,v);const A=f.mixer.clipAction(v);f.actions.push(A),f.models.push(m)}this._animationTracks.push(f)}}}else if(o.type===io.Audio){if(!o.clips||o.clips.length<=0)continue;const l=new hd;l.director=this,l.track=o,l.audioSource=o.outputs.find(h=>h instanceof Cn),this._audioTracks.push(l),t||(t=(r=this.context.mainCameraComponent)==null?void 0:r.gameObject.addNewComponent(Ph)),l.listener=t.listener;for(let h=0;h<o.clips.length;h++){const d=o.clips[h];l.addModel(d)}}else if(o.type===io.Marker){const l=new Gv;if(l.director=this,l.track=o,o.markers)for(const h of o.markers)switch(h.type){case UR.Signal:l.models.push(h),l.didTrigger.push(!1);break}if(l!==null&&l.models.length>0){const h=le.getComponent(this.gameObject,am);h&&(l.receivers.push(h),this._signalTracks.push(l))}}else if(o.type===io.Signal){const l=new Gv;if(l.director=this,l.track=o,o.markers)for(const h of o.markers)l.models.push(h),l.didTrigger.push(!1);for(const h of o.outputs)l.receivers.push(h);this._signalTracks.push(l)}else if(o.type===io.Control){const l=new bw;if(l.director=this,l.track=o,o.clips)for(const h of o.clips)l.models.push(h);l.resolveSourceObjects(this.context),this._controlTracks.push(l)}}}setAudioTracksAllowPlaying(t){for(const i of this._audioTracks)i.onAllowAudioChanged(t)}registerAnimationCallback(t){this.animationCallbackReceivers.push(t)}unregisterAnimationCallback(t){const i=this.animationCallbackReceivers.indexOf(t);i!==-1&&this.animationCallbackReceivers.splice(i,1)}};let Sl=ex;u(Sl,"createTrackFunctions",{});const H_=Symbol("objectIsAnimatedData");function r2(n,e,t){if(!n)return;if(n[H_]===void 0){if(!t)return;n[H_]=new Set}const i=n[H_];t?i.add(e):i.has(e)&&i.delete(e)}function tse(n){if(!n)return!1;const e=n[H_];return e!==void 0&&e.size>0}Bi.registerCallback(Kn.ContextCreated,n=>{const e=n.context.domElement.getAttribute("autoplay");if(e!==void 0&&(e===""||e==="true")&&n.files)for(const t of n.files)le.foreachComponent(t.file.scene,s=>{if(s.enabled!==!1){if(s instanceof Ao&&s.playAutomatically||s instanceof Us||s instanceof Sl&&s.playOnAwake===!0)return!0;if(s instanceof Ao)return s.playAutomatically=!0,!0;if(s instanceof Sl)return s.playOnAwake=!0,!0}},!0)!==!0&&ise(t.file)});function ise(n){if(!n||!n.animations)return;for(let t=0;t<n.animations.length;t++){const i=n.animations[t];if(!(!i.tracks||i.tracks.length<=0))for(const s in i.tracks){const r=i.tracks[s],o=r.__objectName??r.name.substring(0,r.name.indexOf("."));let a=n.scene.getObjectByName(o);if(!a&&(a=n.scene.getObjectByProperty("uuid",o),!a))continue;let c=e(a);c||(c=Xh(n.scene,new Ao));const l=c.animations=c.animations||[];i.name_animator=c.name,l.indexOf(i)<0&&l.push(i)}}function e(t){var s;if(!t)return;const i=(s=t.userData)==null?void 0:s.components;if(i&&i.length>0)for(let r=0;r<i.length;r++){const o=i[r];if(o instanceof Us||o instanceof Ao)return t}return e(t.parent)}}class nse{constructor(){u(this,"_context")}get context(){return this._context??Ot.Current}get isStateMachineBehaviour(){return!0}}class V_{constructor(e,t,i,s){u(this,"_name");u(this,"_nameHash");u(this,"_normalizedTime");u(this,"_length");u(this,"_speed");this._name=e.name,this._nameHash=e.hash,this._normalizedTime=t,this._length=i,this._speed=s}get name(){return this._name}get nameHash(){return this._nameHash}get normalizedTime(){return this._normalizedTime}get length(){return this._length}get speed(){return this._speed}}function FH(n,e){return{name:"",isLooping:!1,guid:(e==null?void 0:e.generateUUID())??es.generateUUID(),index:-1,clip:new Xr(n,1,[])}}var ph=(n=>(n[n.If=1]="If",n[n.IfNot=2]="IfNot",n[n.Greater=3]="Greater",n[n.Less=4]="Less",n[n.Equals=6]="Equals",n[n.NotEqual=7]="NotEqual",n))(ph||{}),NR=(n=>(n[n.Float=1]="Float",n[n.Int=3]="Int",n[n.Bool=4]="Bool",n[n.Trigger=9]="Trigger",n))(NR||{});const pr=se("debuganimatorcontroller"),N0=se("debugrootmotion");class go{constructor(e){u(this,"normalizedStartOffset",0);u(this,"_speed",1);u(this,"animator");u(this,"model");u(this,"_mixer");u(this,"_activeState");u(this,"_activeStates",[]);u(this,"rootMotionHandler");this.model=e,pr&&console.log(this)}static createFromClips(e,t={looping:!1,autoTransition:!0,transitionDuration:0}){const i=[];for(let o=0;o<e.length;o++){const a=e[o],c=[];if(t.autoTransition!==!1){const h=t.transitionDuration??0,d=h/a.duration;let f=o;(t.autoTransition===void 0||t.autoTransition===!0)&&(f=(o+1)%e.length),c.push({exitTime:1-d,offset:0,duration:h,hasExitTime:!0,destinationState:f,conditions:[]})}const l={name:a.name,hash:o,motion:{name:a.name,clip:a,isLooping:(t==null?void 0:t.looping)??!1},transitions:c,behaviours:[]};i.push(l)}const s={name:"AnimatorController",guid:new ms(Date.now()).generateUUID(),parameters:[],layers:[{name:"Base Layer",stateMachine:{defaultState:0,states:i}}]};return new go(s)}play(e,t=-1,i=Number.NEGATIVE_INFINITY,s=0){if(t<0)t=0;else if(t>=this.model.layers.length){console.warn("invalid layer");return}const o=this.model.layers[t].stateMachine;for(const a of o.states)if(a.name===e||a.hash===e){pr&&console.log("transition to ",a),this.transitionTo(a,s,i);return}console.warn("Could not find "+e+" to play")}reset(){this.setStartTransition()}setBool(e,t){var s,r;const i=typeof e=="string"?"name":"hash";return(r=(s=this.model)==null?void 0:s.parameters)==null?void 0:r.filter(o=>o[i]===e).forEach(o=>o.value=t)}getBool(e){var i,s,r;const t=typeof e=="string"?"name":"hash";return((r=(s=(i=this.model)==null?void 0:i.parameters)==null?void 0:s.find(o=>o[t]===e))==null?void 0:r.value)??!1}setFloat(e,t){var r,o;const i=typeof e=="string"?"name":"hash",s=(o=(r=this.model)==null?void 0:r.parameters)==null?void 0:o.filter(a=>a[i]===e);return s.forEach(a=>a.value=t),(s==null?void 0:s.length)>0}getFloat(e){var i,s,r;const t=typeof e=="string"?"name":"hash";return((r=(s=(i=this.model)==null?void 0:i.parameters)==null?void 0:s.find(o=>o[t]===e))==null?void 0:r.value)??0}setInteger(e,t){var s,r;const i=typeof e=="string"?"name":"hash";return(r=(s=this.model)==null?void 0:s.parameters)==null?void 0:r.filter(o=>o[i]===e).forEach(o=>o.value=t)}getInteger(e){var i,s,r;const t=typeof e=="string"?"name":"hash";return((r=(s=(i=this.model)==null?void 0:i.parameters)==null?void 0:s.find(o=>o[t]===e))==null?void 0:r.value)??0}setTrigger(e){var i,s;pr&&console.log("SET TRIGGER",e);const t=typeof e=="string"?"name":"hash";return(s=(i=this.model)==null?void 0:i.parameters)==null?void 0:s.filter(r=>r[t]===e).forEach(r=>r.value=!0)}resetTrigger(e){var i,s;const t=typeof e=="string"?"name":"hash";return(s=(i=this.model)==null?void 0:i.parameters)==null?void 0:s.filter(r=>r[t]===e).forEach(r=>r.value=!1)}getTrigger(e){var i,s,r;const t=typeof e=="string"?"name":"hash";return((r=(s=(i=this.model)==null?void 0:i.parameters)==null?void 0:s.find(o=>o[t]===e))==null?void 0:r.value)??!1}isInTransition(){return this._activeStates.length>1}setSpeed(e){this._speed=e}FindState(e){return this.findState(e)}findState(e){if(!e)return null;if(Array.isArray(this.model.layers)){for(const t of this.model.layers)for(const i of t.stateMachine.states)if(i.name===e||i.hash==e)return i}return null}get context(){var e;return(e=this.animator)==null?void 0:e.context}get mixer(){return this._mixer}bind(e){e?this.animator!==e&&(this.animator=e,this._mixer=new Ux(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;pr&&console.warn("AnimatorController clone()",this.model);const e=dA(this.model,(i,s,r)=>r==null?!0:!(r.type==="Object3D"||r.isObject3D===!0||vG(r)||r.tracks!==void 0||r instanceof go));return console.assert(e!==this.model),new go(e)}update(e){var i,s;if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates(e);const t=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&((i=this.rootMotionHandler)==null||i.onBeforeUpdate(e)),this._mixer.update(t),this.animator.applyRootMotion&&((s=this.rootMotionHandler)==null||s.onAfterUpdate(e))}get activeState(){return this._activeState}updateActiveStates(e){for(let t=0;t<this._activeStates.length;t++){const i=this._activeStates[t],s=i.motion;if(!s.action)this._activeStates.splice(t,1),t--;else{const r=s.action;r.weight=e,r.getEffectiveWeight()<=0&&!r.isRunning()&&(pr&&console.debug("REMOVE",i.name,r.getEffectiveWeight(),r.isRunning(),r.isScheduled()),this._activeStates.splice(t,1),t--)}}}setStartTransition(){for(const e of this.model.layers){const t=e.stateMachine;t.defaultState===void 0&&(pr&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",e),t.defaultState=0);const i=t.states[t.defaultState];this.transitionTo(i,0,this.normalizedStartOffset)}}evaluateTransitions(){var r;let e=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;e=!0}const t=this._activeState,i=t.motion.action;for(const o of t.transitions){if(!o.hasExitTime&&o.conditions.length<=0)continue;let a=!0;for(const c of o.conditions)if(!this.evaluateCondition(c)){a=!1;break}if(a)if(i){const c=t.motion.clip.duration,l=c<=0?1:Math.abs(i.time/c);let h=!1;if(o.hasExitTime?i.timeScale>0?h=l>=o.exitTime:i.timeScale<0&&(h=1-l>=o.exitTime):h=!0,h){for(const d of o.conditions){const f=this.model.parameters.find(p=>p.name===d.parameter);(f==null?void 0:f.type)===NR.Trigger&&f.value&&(f.value=!1)}i.clampWhenFinished=!0,pr&&console.log("transition to "+o.destinationState,o,l,o.exitTime,o.hasExitTime),this.transitionTo(o.destinationState,o.duration,o.offset);return}}else{this.transitionTo(o.destinationState,o.duration,o.offset);return}}if(i){let o=t.speed??1;t.speedParameter&&(o*=this.getFloat(t.speedParameter)),o!==void 0&&(i.timeScale=o*this._speed)}let s=!1;if(t.motion.isLooping&&i&&(i.time>=i.getClip().duration?(s=!0,i.reset(),i.time=0,i.play()):i.time<=0&&i.timeScale<0&&(s=!0,i.reset(),i.time=i.getClip().duration,i.play())),!s&&t&&!e&&i&&this.animator&&t.behaviours){const o=i==null?void 0:i.getClip().duration,a=i.time/o,c=new V_(this._activeState,a,o,this._speed);for(const l of t.behaviours)l.instance&&((r=l.instance.onStateUpdate)==null||r.call(l.instance,this.animator,c,0))}}getState(e,t){return typeof e=="number"&&(e==-1&&(e=this.model.layers[t].stateMachine.defaultState,e===void 0&&(pr&&console.warn("AnimatorController default state is undefined: ",this.model,"Layer: "+t),e=0)),e=this.model.layers[t].stateMachine.states[e]),e}transitionTo(e,t,i){var l,h,d,f,p,m,g,y;if(!this.animator)return;const s=0;if(e=this.getState(e,s),!(e!=null&&e.motion)||!e.motion.clip||!(e.motion.clip instanceof Xr))return;const r=this._activeState===e;if(r){const v=e.motion;if(!v.action_loopback&&v.clip){const A=this.rootMotionHandler?this.animator.gameObject.matrix.clone():null;this._mixer.uncacheAction(v.clip,this.animator.gameObject),A&&A.decompose(this.animator.gameObject.position,this.animator.gameObject.quaternion,this.animator.gameObject.scale),v.action_loopback=this.createAction(v.clip)}}if((l=this._activeState)!=null&&l.behaviours&&this._activeState.motion.action){const v=(h=this._activeState)==null?void 0:h.motion.clip.duration,A=this._activeState.motion.action.time/v,_=new V_(this._activeState,A,v,this._speed);for(const b of this._activeState.behaviours)(f=(d=b.instance)==null?void 0:d.onStateExit)==null||f.call(b.instance,this.animator,_,s)}const o=(p=this._activeState)==null?void 0:p.motion.action;o&&o.fadeOut(t),r&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=o);const a=this._activeState;this._activeState=e;const c=(m=e.motion)==null?void 0:m.action;if(c){if(i=Math.max(0,Math.min(1,i)),e.cycleOffsetParameter){let A=this.getFloat(e.cycleOffsetParameter);typeof A=="number"?(A<0&&(A+=1),i+=A,i%=1):pr&&console.warn("AnimatorController cycle offset parameter is not a number",e.cycleOffsetParameter)}else typeof e.cycleOffset=="number"&&(i+=e.cycleOffset,i%=1);c.isRunning()&&c.stop(),c.reset(),c.enabled=!0;const v=e.motion.clip.duration;if(c.time=r?0:i*v,c.timeScale<0&&(c.time=v-c.time),c.clampWhenFinished=!0,c.setLoop(lv,0),t>0?c.fadeIn(t):c.weight=1,c.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(c),this._activeStates.includes(e)||this._activeStates.push(e),this._activeState.behaviours){const A=new V_(e,i,v,this._speed);for(const _ of this._activeState.behaviours)(y=(g=_.instance)==null?void 0:g.onStateEnter)==null||y.call(_.instance,this.animator,A,s)}}else pr&&(e.__warned_no_motion||(e.__warned_no_motion=!0,console.warn("No action",e.motion,this)));pr&&console.log("TRANSITION FROM "+(a==null?void 0:a.name)+" TO "+e.name,t,o,c,c==null?void 0:c.getEffectiveTimeScale(),c==null?void 0:c.getEffectiveWeight(),c==null?void 0:c.isRunning(),c==null?void 0:c.isScheduled(),c==null?void 0:c.paused)}createAction(e){var i,s;if(this._mixer.existingAction(e)&&this._mixer.uncacheAction(e,(i=this.animator)==null?void 0:i.gameObject),(s=this.animator)!=null&&s.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new sse(this));const r=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,r,e)}else return this._mixer.clipAction(e)}evaluateCondition(e){const t=this.model.parameters.find(i=>i.name===e.parameter);if(!t)return!1;switch(e.mode){case ph.If:return t.value===!0;case ph.IfNot:return t.value===!1;case ph.Greater:return t.value>e.threshold;case ph.Less:return t.value<e.threshold;case ph.Equals:return t.value===e.threshold;case ph.NotEqual:return t.value!==e.threshold}return!1}createActions(e){var t,i,s,r;pr&&console.log("AnimatorController createActions",this.model);for(const o of this.model.layers){const a=o.stateMachine;for(let c=0;c<a.states.length;c++){const l=a.states[c];l.transitions||(l.transitions=[]);for(const h of l.transitions)h.conditions||(h.conditions=[]);if(l.motion||(l.motion=FH(l.name)),this.animator&&l.motion.clips){const h=(t=l.motion.clips)==null?void 0:t.find(d=>{var f,p;return d.node.name===((p=(f=this.animator)==null?void 0:f.gameObject)==null?void 0:p.name)});h?l.motion.clip=h.clip:(pr||Mt())&&console.warn('Could not find clip for animator "'+((s=(i=this.animator)==null?void 0:i.gameObject)==null?void 0:s.name)+'"',l.motion.clips.map(d=>d.node.name))}if(!l.motion.clip){const h=new Xr(void 0,void 0,[]);l.motion.clip=h}if((r=l.motion)!=null&&r.clip){const h=l.motion.clip;if(h instanceof Xr){const d=this.createAction(h);l.motion.action=d}else(pr||Mt())&&console.warn("No valid animationclip assigned",l)}if(l.behaviours&&Array.isArray(l.behaviours))for(const h of l.behaviours){if(!(h!=null&&h.typeName))continue;const d=$.get(h.typeName),f=new d;f.isStateMachineBehaviour&&(f._context=this.context??void 0,Tp(f,h.properties),h.instance=f),pr&&console.log("Created animator controller behaviour",l.name,h.typeName,h.properties,f)}}}}*enumerateActions(){if(this.model.layers)for(const e of this.model.layers){const t=e.stateMachine;for(let i=0;i<t.states.length;i++){const s=t.states[i];s!=null&&s.motion&&(s.motion.action&&(yield s.motion.action),s.motion.action_loopback&&(yield s.motion.action_loopback))}}}}class o2{constructor(e,t){u(this,"track");u(this,"createdInterpolant");u(this,"originalEvaluate");u(this,"customEvaluate");this.track=e;const i=e,s=i.createInterpolant.bind(e);i.createInterpolant=()=>(i.createInterpolant=s,this.createdInterpolant=s(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=r=>{if(!this.originalEvaluate)return;const o=this.originalEvaluate(r);return t(r,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 Jn=class{constructor(e,t,i,s,r){u(this,"_action");u(this,"root");u(this,"clip");u(this,"positionWrapper",null);u(this,"rotationWrapper",null);u(this,"context");u(this,"positionChange",new w);u(this,"rotationChange",new Ee);u(this,"_prevTime",0);if(this.context=e,this.root=t,this.clip=i,Jn.firstKeyframeRotation[this.cacheId]||(Jn.firstKeyframeRotation[this.cacheId]=new Ee),r){const o=r.values;Jn.firstKeyframeRotation[this.cacheId].set(o[0],o[1],o[2],o[3])}Jn.spaceRotation[this.cacheId]||(Jn.spaceRotation[this.cacheId]=new Ee),Jn.effectiveSpaceRotation[this.cacheId]||(Jn.effectiveSpaceRotation[this.cacheId]=new Ee),Jn.clipOffsetRotation[this.cacheId]=new Ee,r&&Jn.clipOffsetRotation[this.cacheId].set(r.values[0],r.values[1],r.values[2],r.values[3]).invert(),this.handlePosition(i,s),this.handleRotation(i,r)}set action(e){this._action=e}get action(){return this._action}get cacheId(){return this.root.uuid}onStart(e){if(e.getClip()!==this.clip)return;Jn.lastObjRotation[this.cacheId]||(Jn.lastObjRotation[this.cacheId]=this.root.quaternion.clone());const t=Jn.lastObjRotation[this.cacheId];if(Jn.spaceRotation[this.cacheId].copy(t),N0){const i=new ks().setFromQuaternion(t);console.log("START",this.clip.name,rt.toDegrees(i.y),this.root.position.z)}}getClipRotationOffset(){return Jn.clipOffsetRotation[this.cacheId]}handlePosition(e,t){if(t){const i=this.root;N0&&i.add(new Zo),Jn.lastObjPosition[this.cacheId]||(Jn.lastObjPosition[this.cacheId]=this.root.position.clone());const s=new w,r=new w;this.positionWrapper=new o2(t,(o,a)=>{const c=this.action.getEffectiveWeight();return N0&&i.position.length()>8&&i.position.set(0,i.position.y,0),o>this._prevTime&&(s.set(a[0],a[1],a[2]),s.sub(r),s.multiplyScalar(c),s.applyQuaternion(this.getClipRotationOffset()),s.applyQuaternion(i.quaternion),this.positionChange.copy(s)),r.fromArray(a),this._prevTime=o,a[0]=0,a[1]=0,a[2]=0,a})}}handleRotation(e,t){if(t){if(N0){const o=t.values,a=new ks().setFromQuaternion(new Ee(o[0],o[1],o[2],o[3]));console.log(e.name,t.name,"FIRST ROTATION IN TRACK",rt.toDegrees(a.y));const c=t.values.length-4,l=new Ee().set(o[c],o[c+1],o[c+2],o[c+3]),h=new ks().setFromQuaternion(l);console.log(e.name,t.name,"LAST ROTATION IN TRACK",rt.toDegrees(h.y))}let i=0;const s=new Ee,r=new Ee;this.rotationWrapper=new o2(t,(o,a)=>(o>i&&(r.set(a[0],a[1],a[2],a[3]),s.invert(),r.multiply(s),this.rotationChange.copy(r)),s.fromArray(a),i=o,a[0]=0,a[1]=0,a[2]=0,a[3]=1,a))}}onBeforeUpdate(e){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(e){return!this.action||(e*=this.action.getEffectiveWeight(),e<=0)?!1:(this.positionChange.multiplyScalar(e),this.rotationChange.slerp(Jn.identityQuaternion,1-e),!0)}};let Ya=Jn;u(Ya,"lastObjPosition",{}),u(Ya,"lastObjRotation",{}),u(Ya,"firstKeyframeRotation",{}),u(Ya,"spaceRotation",{}),u(Ya,"effectiveSpaceRotation",{}),u(Ya,"clipOffsetRotation",{}),u(Ya,"identityQuaternion",new Ee);class sse{constructor(e){u(this,"controller");u(this,"handler",[]);u(this,"root");u(this,"basePosition",new w);u(this,"baseQuaternion",new Ee);u(this,"baseRotation",new ks);u(this,"summedPosition",new w);u(this,"summedRotation",new Ee);this.controller=e}createClip(e,t,i){this.root=t,t&&"name"in t&&t.name;const s=this.findRootTrack(i,".position"),r=this.findRootTrack(i,".quaternion"),o=new Ya(this.controller.context,t,i,s,r);this.handler.push(o);const a=e.clipAction(i);return o.action=a,a}onStart(e){for(const t of this.handler)t.onStart(e)}onBeforeUpdate(e){this.basePosition.copy(this.root.position),this.baseQuaternion.copy(this.root.quaternion);for(const t of this.handler)t.onBeforeUpdate(e)}onAfterUpdate(e){if(!(e<=0)){this.root.position.copy(this.basePosition),this.root.quaternion.copy(this.baseQuaternion),this.summedPosition.set(0,0,0),this.summedRotation.set(0,0,0,1);for(const t of this.handler)t.onAfterUpdate(e)&&(this.summedPosition.add(t.positionChange),this.summedRotation.multiply(t.rotationChange));this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation)}}findRootTrack(e,t){const i=e.tracks;if(!i)return null;for(const s of i)if(s.name.endsWith(t))return s;return null}}class rse extends Dl{onSerialize(e,t){}onDeserialize(e,t){if(t.type===go&&(e==null?void 0:e.__type)==="AnimatorController")return new go(e)}}new rse(go);var ose=Object.defineProperty,ase=Object.getOwnPropertyDescriptor,xw=(n,e,t,i)=>{for(var s=i>1?void 0:i?ase(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&ose(e,t,s),s};const Oo=se("debuganimator");class Us extends Ie{constructor(){super(...arguments);u(this,"applyRootMotion",!1);u(this,"hasRootMotion",!1);u(this,"keepAnimatorControllerStateOnDisable",!1);u(this,"_parametersAreDirty",!1);u(this,"_isDirty",!1);u(this,"speed",1);u(this,"normalizedStartOffset",0);u(this,"_animatorController",null);u(this,"_initializeWithRuntimeAnimatorController")}set runtimeAnimatorController(t){var i;this._animatorController&&this._animatorController.model===t||(t?t instanceof go?(t.animator&&t.animator!==this&&(console.warn("AnimatorController can not be bound to multiple animators",(i=t.model)==null?void 0:i.name),t.model||console.error("AnimatorController has no model"),t=new go(t.model)),this._animatorController=t,this._animatorController.bind(this)):(Oo&&console.log("Assign animator controller",t,this),this._animatorController=new go(t),this.__didAwake&&this._animatorController.bind(this)):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}get parametersAreDirty(){return this._parametersAreDirty}get isDirty(){return this._isDirty}Play(t,i=-1,s=Number.NEGATIVE_INFINITY,r=0){this.play(t,i,s,r)}play(t,i=-1,s=Number.NEGATIVE_INFINITY,r=0){var o;(o=this.runtimeAnimatorController)==null||o.play(t,i,s,r),this._isDirty=!0}Reset(){this.reset()}reset(){var t;(t=this._animatorController)==null||t.reset(),this._isDirty=!0}SetBool(t,i){this.setBool(t,i)}setBool(t,i){var s,r;Oo&&console.log("setBool",t,i),((s=this.runtimeAnimatorController)==null?void 0:s.getBool(t))!==i&&(this._parametersAreDirty=!0),(r=this.runtimeAnimatorController)==null||r.setBool(t,i)}GetBool(t){return this.getBool(t)}getBool(t){var s;const i=((s=this.runtimeAnimatorController)==null?void 0:s.getBool(t))??!1;return Oo&&console.log("getBool",t,i),i}toggleBool(t){this.setBool(t,!this.getBool(t))}SetFloat(t,i){this.setFloat(t,i)}setFloat(t,i){var s,r;((s=this.runtimeAnimatorController)==null?void 0:s.getFloat(t))!==i&&(this._parametersAreDirty=!0),Oo&&console.log("setFloat",t,i),(r=this.runtimeAnimatorController)==null||r.setFloat(t,i)}GetFloat(t){return this.getFloat(t)}getFloat(t){var s;const i=((s=this.runtimeAnimatorController)==null?void 0:s.getFloat(t))??-1;return Oo&&console.log("getFloat",t,i),i}SetInteger(t,i){this.setInteger(t,i)}setInteger(t,i){var s,r;((s=this.runtimeAnimatorController)==null?void 0:s.getInteger(t))!==i&&(this._parametersAreDirty=!0),Oo&&console.log("setInteger",t,i),(r=this.runtimeAnimatorController)==null||r.setInteger(t,i)}GetInteger(t){return this.getInteger(t)}getInteger(t){var s;const i=((s=this.runtimeAnimatorController)==null?void 0:s.getInteger(t))??-1;return Oo&&console.log("getInteger",t,i),i}SetTrigger(t){this.setTrigger(t)}setTrigger(t){var i;this._parametersAreDirty=!0,Oo&&console.log("setTrigger",t),(i=this.runtimeAnimatorController)==null||i.setTrigger(t)}ResetTrigger(t){this.resetTrigger(t)}resetTrigger(t){var i;this._parametersAreDirty=!0,Oo&&console.log("resetTrigger",t),(i=this.runtimeAnimatorController)==null||i.resetTrigger(t)}GetTrigger(t){this.getTrigger(t)}getTrigger(t){var s;const i=(s=this.runtimeAnimatorController)==null?void 0:s.getTrigger(t);return Oo&&console.log("getTrigger",t,i),i}IsInTransition(){return this.isInTransition()}isInTransition(){var t;return((t=this.runtimeAnimatorController)==null?void 0:t.isInTransition())??!1}SetSpeed(t){return this.setSpeed(t)}setSpeed(t){var i;t!==this.speed&&(Oo&&console.log("setSpeed",t),this.speed=t,(i=this._animatorController)==null||i.setSpeed(t))}set minMaxSpeed(t){this.speed=rt.lerp(t.x,t.y,Math.random())}set minMaxOffsetNormalized(t){this.normalizedStartOffset=rt.lerp(t.x,t.y,Math.random()),this.runtimeAnimatorController&&(this.runtimeAnimatorController.normalizedStartOffset=this.normalizedStartOffset)}awake(){Oo&&console.log("ANIMATOR",this.name,this),this.gameObject&&this.initializeRuntimeAnimatorController()}initializeRuntimeAnimatorController(t=!1){const i=t||this.runtimeAnimatorController!==this._initializeWithRuntimeAnimatorController;if(this.runtimeAnimatorController&&i){const s=this.runtimeAnimatorController.clone();this._initializeWithRuntimeAnimatorController=s,s?(console.assert(this.runtimeAnimatorController!==s),this.runtimeAnimatorController=s,console.assert(this.runtimeAnimatorController===s),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 t;this.keepAnimatorControllerStateOnDisable||(t=this._animatorController)==null||t.reset()}onBeforeRender(){this._isDirty=!1,this._parametersAreDirty=!1,!tse(this.gameObject)&&this._animatorController&&this._animatorController.update(1)}}xw([x()],Us.prototype,"applyRootMotion",2);xw([x()],Us.prototype,"hasRootMotion",2);xw([x()],Us.prototype,"keepAnimatorControllerStateOnDisable",2);xw([x()],Us.prototype,"runtimeAnimatorController",1);const vp=se("debugusdzanimation"),LM=se("debugusdzanimationserialization");class ww{constructor(e,t,i){u(this,"_start");u(this,"ext");u(this,"root");u(this,"clip");this.ext=e,this.root=t,this.clip=i}get start(){return this._start===void 0&&(this._start=this.ext.getStartTime01(this.root,this.clip)),this._start}get duration(){return this.clip.duration}}class Wo{constructor(e,t,i){u(this,"clip");u(this,"pos");u(this,"rot");u(this,"scale");u(this,"root");u(this,"target");u(this,"duration",0);u(this,"useRootMotion",!1);this.root=e,this.target=t,this.clip=i,i?this.duration=i.duration:this.duration=1/this.frameRate;const s=le.getComponent(e,Us);s&&(this.useRootMotion=s.applyRootMotion)}get frameRate(){return 60}addTrack(e){if(!this.clip){console.error("This is a rest clip but you're trying to add tracks to it โ€“ this is likely a bug");return}e.name.endsWith("position")&&(this.pos=e),e.name.endsWith("quaternion")&&(this.rot=e),e.name.endsWith("scale")&&(this.scale=e)}getFrames(){var e,t,i,s,r,o;return this.clip?Math.max(((t=(e=this.pos)==null?void 0:e.times)==null?void 0:t.length)??0,((s=(i=this.rot)==null?void 0:i.times)==null?void 0:s.length)??0,((o=(r=this.scale)==null?void 0:r.times)==null?void 0:o.length)??0):2}getDuration(){return this.duration}getSortedTimesArray(e=!0,t=!0,i=!0){var c,l,h;if(!this.clip)return[0,this.duration];const s=(c=this.pos)==null?void 0:c.times,r=(l=this.rot)==null?void 0:l.times,o=(h=this.scale)==null?void 0:h.times,a=[];if(e&&s)for(const d of s)a.push(d);if(t&&r)for(const d of r)a.push(d);if(i&&o)for(const d of o)a.push(d);return a.includes(0)||a.push(0),a.sort((d,f)=>d-f),[...new Set(a)]}*getValues(e,t=!0,i=!0,s=!0){var f,p,m;const r=new w,o=new Ee,a=new w(1,1,1),c=this.target,l=t?(f=this.pos)==null?void 0:f.createInterpolant():void 0,h=i?(p=this.rot)==null?void 0:p.createInterpolant():void 0,d=s?(m=this.scale)==null?void 0:m.createInterpolant():void 0;l||r.set(c.position.x,c.position.y,c.position.z),h||o.set(c.quaternion.x,c.quaternion.y,c.quaternion.z,c.quaternion.w),d||a.set(c.scale.x,c.scale.y,c.scale.z);for(let g=0;g<e.length;g++){const y=e[g];if(l){const v=l.evaluate(y);r.set(v[0],v[1],v[2])}if(h){const v=h.evaluate(y);o.set(v[0],v[1],v[2],v[3])}if(d){const v=d.evaluate(y);a.set(v[0],v[1],v[2])}if(this.useRootMotion&&c===this.root){const v=new Se;v.compose(r,o,a),v.multiply(c.matrix),v.decompose(r,o,a)}yield{time:y,translation:r,rotation:o,scale:a,index:g}}}}u(Wo,"animationDurationPadding",1);class GA{constructor(e){u(this,"dict",new Map);u(this,"rootTargetMap",new Map);u(this,"rootAndClipToRegisteredAnimationMap",new Map);u(this,"rootToRegisteredClipCount",new Map);u(this,"serializers",[]);u(this,"injectRestPoses",!1);u(this,"injectImplicitBehaviours",!1);this.injectRestPoses=e,this.injectImplicitBehaviours=e}get extensionName(){return"animation"}getClipCount(e){let t=this.rootToRegisteredClipCount.get(e);return this.injectRestPoses&&(t=t?t-1:0),t??0}getStartTime01(e,t){const i=this.rootTargetMap.get(e);if(!i)return 0;const s=this.dict.get(i[0]);if(!s)return console.error("Trying to get start time for root that has no animation data",e,t,...this.dict),0;let r=0;for(let o=0;o<s.length&&s[o].clip!==t;o++)r+=s[o].getDuration()+Wo.animationDurationPadding;return r}registerAnimation(e,t){if(!t||!e)return null;this.rootTargetMap.has(e)||this.rootTargetMap.set(e,[]);const i=e.uuid+t.uuid;if(this.rootAndClipToRegisteredAnimationMap.has(i))return this.rootAndClipToRegisteredAnimationMap.get(i);vp&&console.log("registerAnimation",e,t);const s=this.injectRestPoses?1:0,r=this.rootToRegisteredClipCount.get(e)??s,o=this.rootTargetMap.get(e),a=new Set(o);if(t.tracks)for(const l of t.tracks){const h=Yt.parseTrackName(l.name),d=Yt.findNode(e,h.nodeName);if(!d){console.warn("no object found for track",l.name,"using "+e.name+" instead");continue}this.dict.has(d)||this.dict.set(d,[]);const f=this.dict.get(d);if(!f)continue;if(a.delete(d),this.injectRestPoses&&!f[0]){const m=new Wo(null,d,void 0);f[0]=m}let p=f[r];p||(p=new Wo(e,d,t),f[r]=p),p.addTrack(l),o!=null&&o.includes(d)||o==null||o.push(d)}for(const l of a){const h=this.dict.get(l);if(!h)continue;if(this.injectRestPoses&&!h[0]){const f=new Wo(null,l,void 0);h[0]=f}let d=h[r];d||(vp&&console.log("Adding padding clip for ",l,t),d=new Wo(e,l,t),h[r]=d)}const c=new ww(this,e,t);return this.rootAndClipToRegisteredAnimationMap.set(i,c),this.rootToRegisteredClipCount.set(e,r+1),c}onAfterHierarchy(e){vp&&console.log("Animation clips per animation target node",this.dict)}onAfterBuildDocument(e){var t,i;for(const s of this.serializers){const r=(t=s.model)==null?void 0:t.parent,o=(r==null?void 0:r.isDynamic)===!0;LM&&console.log(o,(i=s.model)==null?void 0:i.parent),o&&s.registerCallback(r)}}onExportObject(e,t,i){le.foreachComponent(e,r=>{const o=r;typeof o.createAnimation=="function"&&o.createAnimation(this,t,i)},!1);const s=new cse(e,this.dict);this.serializers.push(s),s.registerCallback(t)}}class cse{constructor(e,t){u(this,"object");u(this,"dict");u(this,"model");u(this,"callback");this.object=e,this.dict=t}registerCallback(e){this.model&&this.callback&&this.model.removeEventListener("serialize",this.callback),this.callback||(this.callback=this.onSerialize.bind(this)),LM&&console.log("REPARENT",e),this.model=e,this.model.addEventListener("serialize",this.callback)}skinnedMeshExport(e,t){const i=this.model,s=this.dict;if(i&&i.skinnedMesh){let r=function(T){const I=[];for(const[S,M]of T){let D=`${S} : [`;const G=[];for(const Q of M)G.push(`(${hs(Q.x)}, ${hs(Q.y)}, ${hs(Q.z)})`);D=D.concat(G.join(", ")),D=D.concat("],"),I.push(D)}return I},o=function(T){const I=[];for(const[S,M]of T){let D=`${S} : [`;const G=[];for(const Q of M)G.push(`(${hs(Q.w)}, ${hs(Q.x)}, ${hs(Q.y)}, ${hs(Q.z)})`);D=D.concat(G.join(", ")),D=D.concat("],"),I.push(D)}return I},a=function(T){let I=!0,S;for(const[D,G]of T)if(S===void 0&&(S=G.length),S!==G.length){I=!1;break}vp&&console.log("Bone count: ",T.size,"TransformData entries per bone: ",S),console.assert(I,"All bones should have the same number of TransformData entries",T);const M=[];for(const[D,G]of T){const Q=new Array;let L=0;for(let H=0;H<G.length;H++)Q.push(L),L+=G[H].getDuration()+Wo.animationDurationPadding;for(let H=0;H<G.length;H++){const O=G[H],U=Q[H];M.length<=H&&M.push({pos:[],rot:[],scale:[],timeOffset:U});const V=M[H];V.pos.push(...O.getSortedTimesArray(!0,!1,!1)),V.rot.push(...O.getSortedTimesArray(!1,!0,!1)),V.scale.push(...O.getSortedTimesArray(!1,!1,!0))}}for(const D of M)D.pos.sort((G,Q)=>G-Q),D.rot.sort((G,Q)=>G-Q),D.scale.sort((G,Q)=>G-Q),D.pos=[...new Set(D.pos)],D.rot=[...new Set(D.rot)],D.scale=[...new Set(D.scale)];return M},c=function(T,I,S){const M=new Map,D=new Map,G=new Map,Q=I.length;for(const L of S){const H=T.get(L);let O;H?console.assert(H.length===Q,"We should have the same number of TransformData entries for each bone",H,I):O=new Wo(null,L,void 0);for(let U=0;U<Q;U++){const V=H?H[U]:O,J=I[U];for(const{time:K,translation:oe}of V.getValues(J.pos,!0,!1,!1)){const be=(K+J.timeOffset)*60;M.has(be)||M.set(be,new Array),M.get(be).push(oe.clone())}for(const{time:K,rotation:oe}of V.getValues(J.rot,!1,!0,!1)){const be=(K+J.timeOffset)*60;D.has(be)||D.set(be,new Array),D.get(be).push(oe.clone())}for(const{time:K,scale:oe}of V.getValues(J.scale,!1,!1,!0)){const be=(K+J.timeOffset)*60;G.has(be)||G.set(be,new Array),G.get(be).push(oe.clone())}}}return{position:M.size==0?void 0:M,quaternion:D.size==0?void 0:D,scale:G.size==0?void 0:G}},l=function(T){const I=[];for(const S of T)I.push(`(${hs(S.x)}, ${hs(S.y)}, ${hs(S.z)})`);return I.join(", ")},h=function(T){const I=[];for(const S of T)I.push(`(${hs(S.w)}, ${hs(S.x)}, ${hs(S.y)}, ${hs(S.z)})`);return I.join(", ")},d=function(T){const I=new Map;if(vp){const S=new Array;for(const[M,D]of s)S.push(M.uuid+": "+D.length+" "+D.map(G=>{var Q;return(Q=G.clip)==null?void 0:Q.uuid.substring(0,6)}).join(" "));console.log(`getPerBoneTransformData
5410
+ Using the assigned clip instead:`,this.clip),e=this.clip);let t=!this.sound||e&&e!==this.clip;if(typeof e=="string"&&!this.audioLoader&&(t=!0),(e instanceof MediaStream||typeof e=="string")&&(this.clip=e),t){this.shouldPlay=!0,this.onNewClip(e);return}if(this.shouldPlay=!0,this._hasEnded=!1,$s&&console.log("play",(i=this.sound)==null?void 0:i.getVolume(),this.sound),this.sound&&!this.sound.isPlaying){const o=this.context.application.muted;o&&this.sound.setVolume(0),(s=this.gameObject)==null||s.add(this.sound),this.clip instanceof MediaStream?(this.sound.setMediaStreamSource(this.clip),this._audioElement||(this._audioElement=document.createElement("audio"),this._audioElement.style.display="none"),this._audioElement.parentNode||(r=this.context.domElement.shadowRoot)==null||r.append(this._audioElement),this._audioElement.srcObject=this.clip,this._audioElement.autoplay=!1):(this._audioElement&&this._audioElement.remove(),this.sound.play(o?.1:0))}}pause(){var e,t;$s&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=(e=this.sound)==null?void 0:e.context.currentTime,this.sound.pause()),(t=this._audioElement)==null||t.remove()}stop(){var e,t;$s&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=(e=this.sound)==null?void 0:e.context.currentTime,$s&&console.log(this._lastContextTime),this.sound.stop()),(t=this._audioElement)==null||t.remove()}get isPlaying(){var e;return((e=this.sound)==null?void 0:e.isPlaying)??!1}set isPlaying(e){}get time(){var e,t;return(e=this.sound)!=null&&e.source?((t=this.sound.source)==null?void 0:t.context.currentTime)-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;const t=this.isPlaying;this.stop(),this.sound.offset=e,t&&this.play()}}update(){this.helper&&(this.isPlaying&&this.helper.update(),this.helper.visible=this.isPlaying),this._needUpdateSpatialDistanceSettings&&this.applySpatialDistanceSettings(),this.sound&&!this.sound.isPlaying&&this.shouldPlay&&!this._hasEnded&&(this._hasEnded=!0,$s&&console.log("Audio clip ended",this.clip),this.dispatchEvent(new CustomEvent("ended",{detail:this})))}};let Cn=lh;Ic([x(URL)],Cn.prototype,"clip",2);Ic([x()],Cn.prototype,"playOnAwake",2);Ic([x()],Cn.prototype,"preload",2);Ic([x()],Cn.prototype,"loop",1);Ic([x()],Cn.prototype,"spatialBlend",1);Ic([x()],Cn.prototype,"minDistance",1);Ic([x()],Cn.prototype,"maxDistance",1);Ic([x()],Cn.prototype,"volume",1);Ic([x()],Cn.prototype,"rollOffMode",2);Ic([x()],Cn.prototype,"playInBackground",2);const Zk={type:"change"},JC={type:"start"},$k={type:"end"},L0=new bo,e2=new yr,bne=Math.cos(70*es.DEG2RAD);let xne=class extends ys{constructor(e,t){super(),this.object=e,this.domElement=t,this.domElement.style.touchAction="none",this.enabled=!0,this.target=new w,this.cursor=new w,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:Du.ROTATE,MIDDLE:Du.DOLLY,RIGHT:Du.PAN},this.touches={ONE:Ou.ROTATE,TWO:Ou.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this.getPolarAngle=function(){return a.phi},this.getAzimuthalAngle=function(){return a.theta},this.getDistance=function(){return this.object.position.distanceTo(this.target)},this.listenToKeyEvents=function(j){j.addEventListener("keydown",bt),this._domElementKeyEvents=j},this.stopListenToKeyEvents=function(){this._domElementKeyEvents.removeEventListener("keydown",bt),this._domElementKeyEvents=null},this.saveState=function(){i.target0.copy(i.target),i.position0.copy(i.object.position),i.zoom0=i.object.zoom},this.reset=function(){i.target.copy(i.target0),i.object.position.copy(i.position0),i.object.zoom=i.zoom0,i.object.updateProjectionMatrix(),i.dispatchEvent(Zk),i.update(),r=s.NONE},this.update=function(){const j=new w,ze=new Ee().setFromUnitVectors(e.up,new w(0,1,0)),ne=ze.clone().invert(),q=new w,je=new Ee,Ke=new w,ct=2*Math.PI;return function(Pi=null){const bi=i.object.getWorldPosition(e.position);j.copy(bi).sub(i.target),j.applyQuaternion(ze),a.setFromVector3(j),i.autoRotate&&r===s.NONE&&Q(D(Pi)),i.enableDamping?(a.theta+=c.theta*i.dampingFactor,a.phi+=c.phi*i.dampingFactor):(a.theta+=c.theta,a.phi+=c.phi);let gi=i.minAzimuthAngle,Ni=i.maxAzimuthAngle;isFinite(gi)&&isFinite(Ni)&&(gi<-Math.PI?gi+=ct:gi>Math.PI&&(gi-=ct),Ni<-Math.PI?Ni+=ct:Ni>Math.PI&&(Ni-=ct),gi<=Ni?a.theta=Math.max(gi,Math.min(Ni,a.theta)):a.theta=a.theta>(gi+Ni)/2?Math.max(gi,a.theta):Math.min(Ni,a.theta)),a.phi=Math.max(i.minPolarAngle,Math.min(i.maxPolarAngle,a.phi)),a.makeSafe(),i.enableDamping===!0?i.target.addScaledVector(d,i.dampingFactor):i.target.add(d),i.target.sub(i.cursor),i.target.clampLength(i.minTargetRadius,i.maxTargetRadius),i.target.add(i.cursor),i.zoomToCursor&&T||i.object.isOrthographicCamera?a.radius=oe(a.radius):(i.enableDamping?h=es.lerp(h,l,i.dampingFactor):h=l,a.radius=oe(a.radius*h)),j.setFromSpherical(a),j.applyQuaternion(ne),bi.copy(i.target).add(j),i.object.parent?i.object.parent.worldToLocal(bi):i.object.position.copy(bi),i.object.lookAt(i.target),i.enableDamping===!0?(c.theta*=1-i.dampingFactor,c.phi*=1-i.dampingFactor,d.multiplyScalar(1-i.dampingFactor)):(c.set(0,0,0),d.set(0,0,0));let pi=!1;if(i.zoomToCursor&&T){let En=null;if(i.object.isPerspectiveCamera){const an=j.length();En=oe(an*l);const Io=an-En;i.object.position.addScaledVector(C,Io),i.object.updateMatrixWorld()}else if(i.object.isOrthographicCamera){const an=new w(E.x,E.y,0);an.unproject(i.object),i.object.zoom=Math.max(i.minZoom,Math.min(i.maxZoom,i.object.zoom/l)),i.object.updateProjectionMatrix(),pi=!0;const Io=new w(E.x,E.y,0);Io.unproject(i.object),i.object.position.sub(Io).add(an),i.object.updateMatrixWorld(),En=j.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),i.zoomToCursor=!1;En!==null&&(this.screenSpacePanning?i.target.set(0,0,-1).transformDirection(i.object.matrix).multiplyScalar(En).add(i.object.position):(L0.origin.copy(i.object.position),L0.direction.set(0,0,-1).transformDirection(i.object.matrix),Math.abs(i.object.up.dot(L0.direction))<bne?e.lookAt(i.target):(e2.setFromNormalAndCoplanarPoint(i.object.up,i.target),L0.intersectPlane(e2,i.target))))}else i.object.isOrthographicCamera&&(pi=l!==1,pi&&(i.object.zoom=Math.max(i.minZoom,Math.min(i.maxZoom,i.object.zoom/l)),i.object.updateProjectionMatrix()));return l=1,T=!1,pi||q.distanceToSquared(i.object.position)>o||8*(1-je.dot(i.object.quaternion))>o||Ke.distanceToSquared(i.target)>0?(i.dispatchEvent(Zk),q.copy(i.object.position),je.copy(i.object.quaternion),Ke.copy(i.target),!0):!1}}(),this.dispose=function(){i.domElement.removeEventListener("contextmenu",pt),i.domElement.removeEventListener("pointerdown",B),i.domElement.removeEventListener("pointercancel",Ce),i.domElement.removeEventListener("wheel",nt),i.domElement.removeEventListener("pointermove",ce),window.removeEventListener("pointerup",Ce),i._domElementKeyEvents!==null&&(i._domElementKeyEvents.removeEventListener("keydown",bt),i._domElementKeyEvents=null)};const i=this,s={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6};let r=s.NONE;const o=1e-6,a=new w1,c=new w1;let l=1,h=1;const d=new w,f=new ie,p=new ie,m=new ie,g=new ie,y=new ie,v=new ie,A=new ie,_=new ie,b=new ie,C=new w,E=new ie;let T=!1;const I=[],S={};let M=!1;function D(j){return j!==null?2*Math.PI/60*i.autoRotateSpeed*j:2*Math.PI/60/60*i.autoRotateSpeed}function G(j){const ze=Math.abs(j*.01);return Math.pow(.95,i.zoomSpeed*ze)}function Q(j){c.theta-=j}function L(j){c.phi-=j}const H=function(){const j=new w;return function(ne,q){j.setFromMatrixColumn(q,0),j.multiplyScalar(-ne),d.add(j)}}(),O=function(){const j=new w;return function(ne,q){i.screenSpacePanning===!0?j.setFromMatrixColumn(q,1):(j.setFromMatrixColumn(q,0),j.crossVectors(i.object.up,j)),j.multiplyScalar(ne),d.add(j)}}(),U=function(){const j=new w,ze=new w;return function(q,je){const Ke=i.domElement;if(i.object.isPerspectiveCamera){i.object.getWorldPosition(ze),j.copy(ze).sub(i.target);let ct=j.length();ct*=Math.tan(i.object.fov/2*Math.PI/180),H(2*q*ct/Ke.clientHeight,i.object.matrixWorld),O(2*je*ct/Ke.clientHeight,i.object.matrixWorld)}else i.object.isOrthographicCamera?(H(q*(i.object.right-i.object.left)/i.object.zoom/Ke.clientWidth,i.object.matrixWorld),O(je*(i.object.top-i.object.bottom)/i.object.zoom/Ke.clientHeight,i.object.matrixWorld)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),i.enablePan=!1)}}();function V(j){i.object.isPerspectiveCamera||i.object.isOrthographicCamera?l/=j:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),i.enableZoom=!1)}function J(j){i.object.isPerspectiveCamera||i.object.isOrthographicCamera?l*=j:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),i.enableZoom=!1)}function K(j,ze){if(!i.zoomToCursor)return;T=!0;const ne=i.domElement.getBoundingClientRect(),q=j-ne.left,je=ze-ne.top,Ke=ne.width,ct=ne.height;E.x=q/Ke*2-1,E.y=-(je/ct)*2+1,C.set(E.x,E.y,1).unproject(i.object).sub(i.object.position).normalize()}function oe(j){return Math.max(i.minDistance,Math.min(i.maxDistance,j))}function fe(j){f.set(j.clientX,j.clientY)}function be(j){K(j.clientX,j.clientX),A.set(j.clientX,j.clientY)}function ke(j){g.set(j.clientX,j.clientY)}function Ye(j){p.set(j.clientX,j.clientY),m.subVectors(p,f).multiplyScalar(i.rotateSpeed);const ze=i.domElement;Q(2*Math.PI*m.x/ze.clientHeight),L(2*Math.PI*m.y/ze.clientHeight),f.copy(p),i.update()}function ae(j){_.set(j.clientX,j.clientY),b.subVectors(_,A),b.y>0?V(G(b.y)):b.y<0&&J(G(b.y)),A.copy(_),i.update()}function Ae(j){y.set(j.clientX,j.clientY),v.subVectors(y,g).multiplyScalar(i.panSpeed),U(v.x,v.y),g.copy(y),i.update()}function Ne(j){K(j.clientX,j.clientY),j.deltaY<0?J(G(j.deltaY)):j.deltaY>0&&V(G(j.deltaY)),i.update()}function Ve(j){let ze=!1;switch(j.code){case i.keys.UP:j.ctrlKey||j.metaKey||j.shiftKey?L(2*Math.PI*i.rotateSpeed/i.domElement.clientHeight):U(0,i.keyPanSpeed),ze=!0;break;case i.keys.BOTTOM:j.ctrlKey||j.metaKey||j.shiftKey?L(-2*Math.PI*i.rotateSpeed/i.domElement.clientHeight):U(0,-i.keyPanSpeed),ze=!0;break;case i.keys.LEFT:j.ctrlKey||j.metaKey||j.shiftKey?Q(2*Math.PI*i.rotateSpeed/i.domElement.clientHeight):U(i.keyPanSpeed,0),ze=!0;break;case i.keys.RIGHT:j.ctrlKey||j.metaKey||j.shiftKey?Q(-2*Math.PI*i.rotateSpeed/i.domElement.clientHeight):U(-i.keyPanSpeed,0),ze=!0;break}ze&&(j.preventDefault(),i.update())}function Je(j){if(I.length===1)f.set(j.pageX,j.pageY);else{const ze=vt(j),ne=.5*(j.pageX+ze.x),q=.5*(j.pageY+ze.y);f.set(ne,q)}}function He(j){if(I.length===1)g.set(j.pageX,j.pageY);else{const ze=vt(j),ne=.5*(j.pageX+ze.x),q=.5*(j.pageY+ze.y);g.set(ne,q)}}function Be(j){const ze=vt(j),ne=j.pageX-ze.x,q=j.pageY-ze.y,je=Math.sqrt(ne*ne+q*q);A.set(0,je)}function X(j){i.enableZoom&&Be(j),i.enablePan&&He(j)}function ve(j){i.enableZoom&&Be(j),i.enableRotate&&Je(j)}function Le(j){if(I.length==1)p.set(j.pageX,j.pageY);else{const ne=vt(j),q=.5*(j.pageX+ne.x),je=.5*(j.pageY+ne.y);p.set(q,je)}m.subVectors(p,f).multiplyScalar(i.rotateSpeed);const ze=i.domElement;Q(2*Math.PI*m.x/ze.clientHeight),L(2*Math.PI*m.y/ze.clientHeight),f.copy(p)}function _e(j){if(I.length===1)y.set(j.pageX,j.pageY);else{const ze=vt(j),ne=.5*(j.pageX+ze.x),q=.5*(j.pageY+ze.y);y.set(ne,q)}v.subVectors(y,g).multiplyScalar(i.panSpeed),U(v.x,v.y),g.copy(y)}function qe(j){const ze=vt(j),ne=j.pageX-ze.x,q=j.pageY-ze.y,je=Math.sqrt(ne*ne+q*q);_.set(0,je),b.set(0,Math.pow(_.y/A.y,i.zoomSpeed)),V(b.y),A.copy(_);const Ke=(j.pageX+ze.x)*.5,ct=(j.pageY+ze.y)*.5;K(Ke,ct)}function lt(j){i.enableZoom&&qe(j),i.enablePan&&_e(j)}function F(j){i.enableZoom&&qe(j),i.enableRotate&&Le(j)}function B(j){i.enabled!==!1&&(I.length===0&&(i.domElement.addEventListener("pointermove",ce),window.addEventListener("pointerup",Ce)),mt(j),j.pointerType==="touch"?Me(j):xe(j))}function ce(j){i.enabled!==!1&&(j.pointerType==="touch"?Ft(j):Re(j))}function Ce(j){switch(et(j),I.length){case 0:i.domElement.removeEventListener("pointermove",ce),i.domElement.removeEventListener("pointerup",Ce),i.dispatchEvent($k),r=s.NONE;break;case 1:const ze=I[0],ne=S[ze];Me({pointerId:ze,pageX:ne.x,pageY:ne.y});break}}function xe(j){let ze;switch(j.button){case 0:ze=i.mouseButtons.LEFT;break;case 1:ze=i.mouseButtons.MIDDLE;break;case 2:ze=i.mouseButtons.RIGHT;break;default:ze=-1}switch(ze){case Du.DOLLY:if(i.enableZoom===!1)return;be(j),r=s.DOLLY;break;case Du.ROTATE:if(j.ctrlKey||j.metaKey||j.shiftKey){if(i.enablePan===!1)return;ke(j),r=s.PAN}else{if(i.enableRotate===!1)return;fe(j),r=s.ROTATE}break;case Du.PAN:if(j.ctrlKey||j.metaKey||j.shiftKey){if(i.enableRotate===!1)return;fe(j),r=s.ROTATE}else{if(i.enablePan===!1)return;ke(j),r=s.PAN}break;default:r=s.NONE}r!==s.NONE&&i.dispatchEvent(JC)}function Re(j){switch(r){case s.ROTATE:if(i.enableRotate===!1)return;Ye(j);break;case s.DOLLY:if(i.enableZoom===!1)return;ae(j);break;case s.PAN:if(i.enablePan===!1)return;Ae(j);break}}function nt(j){i.enabled===!1||i.enableZoom===!1||r!==s.NONE||(j.preventDefault(),i.dispatchEvent(JC),Ne(Ue(j)),i.dispatchEvent($k))}function Ue(j){const ze=j.deltaMode,ne={clientX:j.clientX,clientY:j.clientY,deltaY:j.deltaY};switch(ze){case 1:ne.deltaY*=16;break;case 2:ne.deltaY*=100;break}return j.ctrlKey&&!M&&(ne.deltaY*=10),ne}function $e(j){j.key==="Control"&&(M=!0,i.domElement.getRootNode().addEventListener("keyup",at,{passive:!0,capture:!0}))}function at(j){j.key==="Control"&&(M=!1,i.domElement.getRootNode().removeEventListener("keyup",at,{passive:!0,capture:!0}))}function bt(j){i.enabled===!1||i.enablePan===!1||Ve(j)}function Me(j){switch(Qe(j),I.length){case 1:switch(i.touches.ONE){case Ou.ROTATE:if(i.enableRotate===!1)return;Je(j),r=s.TOUCH_ROTATE;break;case Ou.PAN:if(i.enablePan===!1)return;He(j),r=s.TOUCH_PAN;break;default:r=s.NONE}break;case 2:switch(i.touches.TWO){case Ou.DOLLY_PAN:if(i.enableZoom===!1&&i.enablePan===!1)return;X(j),r=s.TOUCH_DOLLY_PAN;break;case Ou.DOLLY_ROTATE:if(i.enableZoom===!1&&i.enableRotate===!1)return;ve(j),r=s.TOUCH_DOLLY_ROTATE;break;default:r=s.NONE}break;default:r=s.NONE}r!==s.NONE&&i.dispatchEvent(JC)}function Ft(j){switch(Qe(j),r){case s.TOUCH_ROTATE:if(i.enableRotate===!1)return;Le(j),i.update();break;case s.TOUCH_PAN:if(i.enablePan===!1)return;_e(j),i.update();break;case s.TOUCH_DOLLY_PAN:if(i.enableZoom===!1&&i.enablePan===!1)return;lt(j),i.update();break;case s.TOUCH_DOLLY_ROTATE:if(i.enableZoom===!1&&i.enableRotate===!1)return;F(j),i.update();break;default:r=s.NONE}}function pt(j){i.enabled!==!1&&j.preventDefault()}function mt(j){I.push(j.pointerId)}function et(j){delete S[j.pointerId];for(let ze=0;ze<I.length;ze++)if(I[ze]==j.pointerId){I.splice(ze,1);return}}function Qe(j){let ze=S[j.pointerId];ze===void 0&&(ze=new ie,S[j.pointerId]=ze),ze.set(j.pageX,j.pageY)}function vt(j){const ze=j.pointerId===I[0]?I[1]:I[0];return S[ze]}i.domElement.addEventListener("contextmenu",pt),i.domElement.addEventListener("pointerdown",B),i.domElement.addEventListener("pointercancel",Ce),i.domElement.addEventListener("wheel",nt,{passive:!1}),i.domElement.getRootNode().addEventListener("keydown",$e,{passive:!0,capture:!0}),this.update()}};class DH extends me{constructor(e,t,i,s=128){if(t<=0||i<=0||s<=0)throw new Error("GroundedSkybox height, radius, and resolution must be positive.");const r=new Da(i,2*s,s);r.scale(1,1,-1);const o=r.getAttribute("position"),a=new w;for(let c=0;c<o.count;++c)if(a.fromBufferAttribute(o,c),a.y<0){const l=-t*3/2,h=a.y<l?-t/a.y:1-a.y*a.y/(3*l*l);a.multiplyScalar(h),a.toArray(o.array,3*c)}o.needsUpdate=!0,super(r,new ci({map:e,depthWrite:!1}))}}const G_=Symbol("cameraController");function wne(n){return n[G_]}function t2(n,e,t){t?n[G_]=e:n[G_]===e&&(n[G_]=null)}const i2=Symbol("camera autofit");function Sne(n){return n[i2]===void 0?!0:n[i2]!==!1}var Cne=Object.defineProperty,Ene=Object.getOwnPropertyDescriptor,Mne=(n,e,t,i)=>{for(var s=i>1?void 0:i?Ene(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Cne(e,t,s),s};class LA extends Ie{constructor(){super(...arguments);u(this,"constraintActive",!0);u(this,"locked",!1);u(this,"sources",[])}}Mne([x(ge)],LA.prototype,"sources",2);function Tne(n){vA(n,Kn.ContextCreated)}function Ine(n){vA(n,Vn.Start)}function OH(n){vA(n,Vn.Update)}function Rne(n){vA(n,Vn.OnBeforeRender)}class ld{constructor(){u(this,"bb",null);u(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}static sizeOf(){return 12}static createVec3(e,t,i,s){return e.prep(4,12),e.writeFloat32(s),e.writeFloat32(i),e.writeFloat32(t),e.offset()}}class kH{constructor(){u(this,"bb",null);u(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new ld).__init(this.bb_pos,this.bb)}rotation(e){return(e||new ld).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new ld).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,i,s,r,o,a,c,l,h){return e.prep(4,36),e.prep(4,12),e.writeFloat32(h),e.writeFloat32(l),e.writeFloat32(c),e.prep(4,12),e.writeFloat32(a),e.writeFloat32(o),e.writeFloat32(r),e.prep(4,12),e.writeFloat32(s),e.writeFloat32(i),e.writeFloat32(t),e.offset()}}class cl{constructor(){u(this,"bb",null);u(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedTransformModel(e,t){return(t||new cl).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+TI),(t||new cl).__init(e.readInt32(e.position())+e.position(),e)}guid(e){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}fast(){const e=this.bb.__offset(this.bb_pos,6);return e?!!this.bb.readInt8(this.bb_pos+e):!1}transform(e){const t=this.bb.__offset(this.bb_pos,8);return t?(e||new kH).__init(this.bb_pos+t,this.bb):null}dontSave(){const e=this.bb.__offset(this.bb_pos,10);return e?!!this.bb.readInt8(this.bb_pos+e):!1}static startSyncedTransformModel(e){e.startObject(4)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addFast(e,t){e.addFieldInt8(1,+t,0)}static addTransform(e,t){e.addFieldStruct(2,t,0)}static addDontSave(e,t){e.addFieldInt8(3,+t,0)}static endSyncedTransformModel(e){return e.endObject()}static finishSyncedTransformModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedTransformModelBuffer(e,t){e.finish(t,void 0,!0)}}var ls=(n=>(n[n.Average=0]="Average",n[n.Multiply=1]="Multiply",n[n.Minimum=2]="Minimum",n[n.Maximum=3]="Maximum",n))(ls||{}),gw=(n=>(n[n.Discrete=0]="Discrete",n[n.Continuous=1]="Continuous",n))(gw||{}),In=(n=>(n[n.None=0]="None",n[n.FreezePositionX=2]="FreezePositionX",n[n.FreezePositionY=4]="FreezePositionY",n[n.FreezePositionZ=8]="FreezePositionZ",n[n.FreezePosition=14]="FreezePosition",n[n.FreezeRotationX=16]="FreezeRotationX",n[n.FreezeRotationY=32]="FreezeRotationY",n[n.FreezeRotationZ=64]="FreezeRotationZ",n[n.FreezeRotation=112]="FreezeRotation",n[n.FreezeAll=126]="FreezeAll",n))(In||{}),$f=(n=>(n[n.None=0]="None",n[n.X=2]="X",n[n.Y=4]="Y",n[n.Z=8]="Z",n[n.All=-1]="All",n))($f||{});const Vs=function(n,e){return function(t,i,s){Pne(t,i,s,n,e)}};function Pne(n,e,t,i,s){if(!s&&!i&&!n.onValidate)return;if(t!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",n,e,t),xn("Invalid usage of validate decorator. Only fields can be validated. Property: "+e,Jo.Error);return}let r="";if(typeof e=="string"?r=e:r=e.name,n.__internalAwake){const o=Symbol(r),a=n.__internalAwake;n.__internalAwake=function(){var c;if(!this.onValidate){Mt()&&console.warn('Usage of @validate decorate detected but there is no onValidate method in your class: "'+((c=n.constructor)==null?void 0:c.name)+'"');return}if(this[o]===void 0){this[o]=this[r];const l=this[r];if(l instanceof ie||l instanceof w||l instanceof st||l instanceof Ee){const h=this[r];zx(h,()=>{this.onValidate(r)})}Object.defineProperty(this,r,{set:function(h){var d;if(this[H1]===!0)this[o]=h;else{i==null||i.call(this,h);const f=this[o];this[o]=h,(d=this.onValidate)==null||d.call(this,r,f)}},get:function(){return s==null||s.call(this),this[o]}})}a.call(this)}}}const Bne=function(n){return function(e,t,i){let s="";typeof t=="string"?s=t:s=t.name;const r=n.prototype,o=Object.getOwnPropertyDescriptor(r,s);if(!(o!=null&&o.value)){console.warn("Can not apply prefix: type does not have method named",t,n);return}const a=o.value,c=e[s];Object.defineProperty(r,s,{value:function(...l){const h=c==null?void 0:c.call(this,...l);if(h instanceof Promise){h.then(d=>{if(d!==!1)return a.call(this,...l)});return}if(h!==!1)return a.call(this,...l)}})}};var Dne=Object.defineProperty,One=Object.getOwnPropertyDescriptor,ra=(n,e,t,i)=>{for(var s=i>1?void 0:i?One(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Dne(e,t,s),s};class kne{constructor(e,t){u(this,"positionChanged",!1);u(this,"rotationChanged",!1);u(this,"position");u(this,"quaternion");u(this,"_positionKeys",["x","y","z"]);u(this,"_quaternionKeys",["_x","_y","_z","_w"]);u(this,"mute",!1);u(this,"context");u(this,"obj");u(this,"_positionWatch");u(this,"_rotationWatch");this.context=t,this.obj=e}get isDirty(){return this.positionChanged||this.rotationChanged}reset(e=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,e){if(this.position)for(const t of this._positionKeys)delete this.position[t];if(this.quaternion)for(const t of this._quaternionKeys)delete this.quaternion[t]}}syncValues(){for(const e of this._positionKeys)this.position[e]=this.obj.position[e];for(const e of this._quaternionKeys)this.quaternion[e]=this.obj.quaternion[e]}applyValues(){if(this.positionChanged&&this.position)for(const e of this._positionKeys){const t=this.position[e];t!==void 0&&(this.obj.position[e]=t)}if(this.rotationChanged&&this.quaternion)for(const e of this._quaternionKeys){const t=this.quaternion[e];t!==void 0&&(this.obj.quaternion[e]=t)}}start(e,t){this.reset(),e&&(this._positionWatch||(this._positionWatch=new vl(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((r,o)=>{var c;if((c=this.context.physics.engine)!=null&&c.isUpdating||this.mute)return;const a=this.position[o];Math.abs(a-r)<1e-5||(this.position[o]=r,this.positionChanged=!0)})),t&&(this._rotationWatch||(this._rotationWatch=new vl(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((r,o)=>{var c;if((c=this.context.physics.engine)!=null&&c.isUpdating||this.mute)return;const a=this.quaternion[o];Math.abs(a-r)<1e-5||(this.quaternion[o]=r,this.rotationChanged=!0)}));const i=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),s=new Se;this.obj.matrixWorld.multiplyMatrices=(r,o)=>{var a;return(a=this.context.physics.engine)!=null&&a.isUpdating||this.mute||s.equals(r)||(this.positionChanged=!0,this.rotationChanged=!0,s.copy(r)),i(r,o)}}stop(){var e,t;(e=this._positionWatch)==null||e.revoke(),(t=this._rotationWatch)==null||t.revoke()}}var OE;const BM=(OE=class extends Ie{constructor(){super(...arguments);u(this,"autoMass",!0);u(this,"_mass",0);u(this,"useGravity",!0);u(this,"constraints",In.None);u(this,"isKinematic",!1);u(this,"drag",0);u(this,"angularDrag",1);u(this,"detectCollisions",!0);u(this,"sleepThreshold",.01);u(this,"collisionDetectionMode",gw.Discrete);u(this,"_gravityScale",1);u(this,"dominanceGroup",0);u(this,"_propertiesChanged",!1);u(this,"_currentVelocity",new w);u(this,"_smoothedVelocity",new w);u(this,"_smoothedVelocityGetter",new w);u(this,"_lastPosition",new w);u(this,"_watch")}set mass(e){e!==this._mass&&(this._mass=e,this._propertiesChanged=!0,this.__didAwake&&(this.autoMass=!1))}get mass(){var e,t;return this.autoMass?((t=(e=this.context.physics.engine)==null?void 0:e.getBody(this))==null?void 0:t.mass())??-1:this._mass}get lockPositionX(){return(this.constraints&In.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&In.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&In.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&In.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&In.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&In.FreezeRotationZ)!==0}set lockPositionX(e){e?this.constraints|=In.FreezePositionX:this.constraints&=~In.FreezePositionX}set lockPositionY(e){e?this.constraints|=In.FreezePositionY:this.constraints&=~In.FreezePositionY}set lockPositionZ(e){e?this.constraints|=In.FreezePositionZ:this.constraints&=~In.FreezePositionZ}set lockRotationX(e){e?this.constraints|=In.FreezeRotationX:this.constraints&=~In.FreezeRotationX}set lockRotationY(e){e?this.constraints|=In.FreezeRotationY:this.constraints&=~In.FreezeRotationY}set lockRotationZ(e){e?this.constraints|=In.FreezeRotationZ:this.constraints&=~In.FreezeRotationZ}set gravityScale(e){this._gravityScale=e}get gravityScale(){return this._gravityScale}awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new kne(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),Vn.LateUpdate)}onDisable(){var e,t;(e=this._watch)==null||e.stop(),(t=this.context.physics.engine)==null||t.removeBody(this)}onDestroy(){var e;(e=this.context.physics.engine)==null||e.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){var e,t,i,s;for(;;)this._propertiesChanged&&(this._propertiesChanged=!1,(e=this.context.physics.engine)==null||e.updateProperties(this)),(t=this._watch)!=null&&t.isDirty?(this._watch.mute=!0,this._watch.applyValues(),(i=this.context.physics.engine)==null||i.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):(s=this._watch)==null||s.syncValues(),this.captureVelocity(),yield}teleport(e,t=!0){var i;(i=this._watch)==null||i.reset(!0),t?this.gameObject.position.set(e.x,e.y,e.z):this.setWorldPosition(e.x,e.y,e.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(e=!0){var t;(t=this.context.physics.engine)==null||t.resetForces(this,e)}resetTorques(e=!0){var t;(t=this.context.physics.engine)==null||t.resetTorques(this,e)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){var e;(e=this.context.physics.engine)==null||e.wakeup(this)}get isSleeping(){var e;return(e=this.context.physics.engine)==null?void 0:e.isSleeping(this)}updateProperties(){var e;return this._propertiesChanged=!1,(e=this.context.physics.engine)==null?void 0:e.updateProperties(this)}applyForce(e,t,i=!0){var s;this._propertiesChanged&&this.updateProperties(),(s=this.context.physics.engine)==null||s.addForce(this,e,i)}applyImpulse(e,t=!0){var i;this._propertiesChanged&&this.updateProperties(),(i=this.context.physics.engine)==null||i.applyImpulse(this,e,t)}setForce(e,t,i,s=!0){var r,o,a;(r=this.context.physics.engine)==null||r.resetForces(this,s),typeof e=="number"?(t??(t=0),i??(i=0),(o=this.context.physics.engine)==null||o.addForce(this,{x:e,y:t,z:i},s)):(a=this.context.physics.engine)==null||a.addForce(this,e,s)}getVelocity(){var t;const e=(t=this.context.physics.engine)==null?void 0:t.getLinearVelocity(this);return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(e,t,i,s=!0){var r,o;if(e instanceof w){const a=e;(r=this.context.physics.engine)==null||r.setLinearVelocity(this,a,s);return}t===void 0||i===void 0||(o=this.context.physics.engine)==null||o.setLinearVelocity(this,{x:e,y:t,z:i},s)}getAngularVelocity(){var t;const e=(t=this.context.physics.engine)==null?void 0:t.getAngularVelocity(this);return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setAngularVelocity(e,t,i,s=!0){var r,o;if(e instanceof w){const a=e;(r=this.context.physics.engine)==null||r.setAngularVelocity(this,a,s);return}t===void 0||i===void 0||(o=this.context.physics.engine)==null||o.setAngularVelocity(this,{x:e,y:t,z:i},s)}setTorque(e,t,i){this.setAngularVelocity(e,t,i)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(e=null){}captureVelocity(){const e=Dt(this.gameObject);BM.tempPosition.copy(e);const t=e.sub(this._lastPosition);this._lastPosition.copy(BM.tempPosition),this._smoothedVelocity.lerp(t,this.context.time.deltaTime/.1)}},u(OE,"tempPosition",new w),OE);let Xi=BM;ra([Vs()],Xi.prototype,"autoMass",2);ra([x()],Xi.prototype,"mass",1);ra([Vs(),x()],Xi.prototype,"useGravity",2);ra([Vs(),x()],Xi.prototype,"constraints",2);ra([Vs(),x()],Xi.prototype,"isKinematic",2);ra([Vs(),x()],Xi.prototype,"drag",2);ra([Vs(),x()],Xi.prototype,"angularDrag",2);ra([Vs(),x()],Xi.prototype,"detectCollisions",2);ra([Vs(),x()],Xi.prototype,"sleepThreshold",2);ra([Vs(),x()],Xi.prototype,"collisionDetectionMode",2);ra([Vs()],Xi.prototype,"_gravityScale",2);ra([Vs()],Xi.prototype,"dominanceGroup",2);const Xc=se("debugsync"),Uv="STRS";RI(Uv,cl.getRootAsSyncedTransformModel);const Qa=new AA;function LH(n,e,t=!0){Qa.clear();const i=Qa.createString(n);cl.startSyncedTransformModel(Qa),cl.addGuid(Qa,i),cl.addFast(Qa,t);const s=e.worldPosition,r=e.worldEuler,o=e.gameObject.scale;cl.addTransform(Qa,kH.createTransform(Qa,s.x,s.y,s.z,r.x,r.y,r.z,o.x,o.y,o.z));const a=cl.endSyncedTransformModel(Qa);return Qa.finish(a,Uv),Qa.asUint8Array()}let DM=0,qg=0;OH(n=>{var i;const t=((i=n.connection.currentServerUrl)==null?void 0:i.includes("glitch"))?10:40;qg=Math.floor(DM/t),DM=0,Xc&&qg>0&&console.log("Sync Transform Fast Interval",qg)});class Nh extends Ie{constructor(){super(...arguments);u(this,"overridePhysics",!0);u(this,"interpolatePosition",!0);u(this,"interpolateRotation",!0);u(this,"fastMode",!1);u(this,"syncDestroy",!1);u(this,"_model",null);u(this,"_needsUpdate",!0);u(this,"rb",null);u(this,"_wasKinematic",!1);u(this,"_receivedDataBefore",!1);u(this,"_targetPosition");u(this,"_targetRotation");u(this,"_receivedFastUpdate",!1);u(this,"_shouldRequestOwnership",!1);u(this,"joinedRoomCallback",null);u(this,"receivedDataCallback",null);u(this,"tempEuler",new ks);u(this,"receivedUpdate",!1);u(this,"lastWorldPos");u(this,"lastWorldRotation")}requestOwnership(){Xc&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}hasOwnership(){var t;return((t=this._model)==null?void 0:t.hasOwnership)??void 0}isOwned(){var t;return(t=this._model)==null?void 0:t.isOwned}awake(){Xc&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new w,this._targetRotation=new Ee,this.lastWorldPos=new w,this.lastWorldRotation=new Ee,this.rb=le.getComponentInChildren(this.gameObject,Xi),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new LI(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(mi.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(Uv,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&BG(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(mi.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(Uv,this.receivedDataCallback)}tryGetLastState(){const t=this.context.connection.tryGetState(this.guid);t&&this.onReceivedData(t)}onReceivedData(t){var i;if(!this.destroyed&&typeof t.guid=="function"&&t.guid()===this.guid){Xc&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,t),this.receivedUpdate=!0,this._receivedFastUpdate=t.fast();const s=t.transform();if(s){Ma.markDirty(this.gameObject,!0);const r=s.position();r&&(this.interpolatePosition&&((i=this._targetPosition)==null||i.set(r.x(),r.y(),r.z())),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(r.x(),r.y(),r.z()));const o=s.rotation();o&&(this.tempEuler.set(o.x(),o.y(),o.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&_R(this.gameObject,this.tempEuler))}this._receivedDataBefore=!0}}onEnable(){this.lastWorldPos.copy(this.worldPosition),this.lastWorldRotation.copy(this.worldQuaternion),this._needsUpdate=!0,this._model&&this._model.updateIsOwned()}onDisable(){this._model&&this._model.freeOwnership()}onBeforeRender(){if(!this.activeAndEnabled||!this.context.connection.isConnected)return;if(!this.context.connection.isInRoom||!this._model){Xc&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());const t=this.worldPosition,i=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){const o=t.distanceTo(this.lastWorldPos),a=i.angleTo(this.lastWorldRotation),c=this._model.hasOwnership||this.fastMode?1e-4:.001;(o>c||a>c)&&(this._model.hasOwnership?this._needsUpdate=!0:(Xc&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastWorldPos),this.worldPosition=this.lastWorldPos,t.copy(this.lastWorldPos),this.worldQuaternion=this.lastWorldRotation,i.copy(this.lastWorldRotation),Ma.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const a=this._receivedFastUpdate||this.fastMode?.5:.3;let c=!1;if(this.interpolatePosition&&this._targetPosition){const l=this.worldPosition;l.lerp(this._targetPosition,a),this.worldPosition=l,c=!0}if(this.interpolateRotation&&this._targetRotation){const l=this.worldQuaternion;l.slerp(this._targetRotation,a),this.worldQuaternion=l,c=!0}c&&Ma.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastWorldPos.copy(t),this.lastWorldRotation.copy(i),!this._model)return;if(!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership){this.rb&&(this.rb.isKinematic=this._model.isOwned??!1,this.rb.setVelocity(0,0,0));return}this.rb&&(this._wasKinematic!==void 0&&(Xc&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic),this.gameObject.position.distanceTo(new w(0,0,0))>1e3&&(Xc&&console.log("RESET",this.name),this.gameObject.position.set(0,1,0),this.rb.setVelocity(0,0,0)));const s=10,r=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%s===0||r)){if(DM++,r&&qg>0&&this.context.time.frameCount%qg!==0)return;Xc&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this.overridePhysics&&this.rb,this._needsUpdate=!1;const o=LH(this.guid,this,!!r);this.context.connection.sendBinary(o)}}}const Lne=se("debugshadowcomponents");fR.prototype.interactable={get(){return this.interactive},set(n){this.interactable=n}};const jo=Symbol("shadowDomOwner");class Pa extends Ie{constructor(){super(...arguments);u(this,"_shadowComponent",null);u(this,"_controlsChildLayout",!0);u(this,"_root");u(this,"_parentComponent")}isRoot(){var t;return((t=this.Root)==null?void 0:t.gameObject)===this.gameObject}get canvas(){const t=this.Root;return t!=null&&t.isCanvas?t:null}get Canvas(){return this.canvas}markDirty(){jr.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(t){this._shadowComponent=t}get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(t){this._controlsChildLayout=t,this.shadowComponent&&(this.shadowComponent.autoLayout=t)}get Root(){return this._root===void 0&&(this._root=le.getComponentInParent(this.gameObject,FA)),this._root}__internalNewInstanceCreated(){super.__internalNewInstanceCreated(),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0}onEnable(){super.onEnable()}addShadowComponent(t,i){var o;this.removeShadowComponent();const s=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=le.getComponentInParent(s,Pa),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}t.name=this.name+" ("+(this.constructor.name??"UI")+")",t.autoLayout=this._parentComponent.controlsChildLayout,t[jo]=this,this.setShadowComponentOwner(t);let r=!1;if(((o=this.Root)==null?void 0:o.gameObject)===this.gameObject)this.gameObject.add(t);else{const a=this._parentComponent.shadowComponent;a&&(a==null||a.add(t),r=!0)}this.shadowComponent=t,i&&i.shadowComponent&&this.shadowComponent&&i.shadowComponent.add(this.shadowComponent),gA&&t.add(new Zo(.5)),this.onAfterAddedToScene(),r&&gG(),Lne&&console.log(this.shadowComponent)}setShadowComponentOwner(t){if(t&&(t[jo]===void 0||t[jo]===this)&&(t[jo]=this,t.children))for(const i of t.children)this.setShadowComponentOwner(i)}traverseOwnedShadowComponents(t,i,s){if(t&&t[jo]===i){s(t);for(const r of t.children)this.traverseOwnedShadowComponents(r,i,s)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(t){this.shadowComponent&&(this.shadowComponent.interactable=t)}}class FA extends Pa{awake(){super.awake()}}class rm{constructor(e,t){u(this,"event");u(this,"button");u(this,"buttonName");u(this,"_used",!1);u(this,"_propagationStopped",!1);u(this,"z__pointer_ctured",!1);u(this,"z__pointer_cture_rleased",!1);u(this,"inputSource");u(this,"object");u(this,"point");u(this,"normal");u(this,"face");u(this,"distance");u(this,"instanceId");u(this,"isDown");u(this,"isUp");u(this,"isPressed");u(this,"isClick");u(this,"isDoubleClick");u(this,"input");this.event=t,this.input=e,this.button=t.button}get deviceIndex(){return this.event.deviceIndex}get pointerId(){return this.event.pointerId}get pressure(){return this.event.pressure}get used(){return this._used}use(){this._used||(this._used=!0,this.pointerId!==void 0&&this.input.setPointerUsed(this.pointerId))}get propagationStopped(){return this._propagationStopped}stopPropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}stopImmediatePropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}setPointerCapture(){this.z__pointer_ctured=!0}releasePointerCapture(){this.z__pointer_cture_rleased=!0}get mode(){return this.event.mode}clone(){const e=new rm(this.input,this.event);return Object.assign(e,this),e}Use(){this.use()}StopPropagation(){this.event.stopImmediatePropagation()}}function OM(n,e){return le.foreachComponent(n,i=>{if(!i.enabled)return;const s=i;if(e)switch(e){case"pointerdown":if(s.onPointerDown)return!0;break;case"pointerup":if(s.onPointerUp||s.onPointerClick)return!0;break;case"pointermove":if(s.onPointerEnter||s.onPointerExit||s.onPointerMove)return!0;break}else if(s.onPointerDown||s.onPointerUp||s.onPointerEnter||s.onPointerExit||s.onPointerClick)return!0},!1)===!0}var Fne=Object.defineProperty,Une=Object.getOwnPropertyDescriptor,Nne=(n,e,t,i)=>{for(var s=i>1?void 0:i?Une(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Fne(e,t,s),s};class UA extends Ie{awake(){jr.createIfNoneExists(this.context)}onEnable(){var e;(e=jr.get(this.context))==null||e.register(this)}onDisable(){var e;(e=jr.get(this.context))==null||e.unregister(this)}}class yo extends UA{constructor(){super(...arguments);u(this,"targets",null);u(this,"raycastHits",[]);u(this,"ignoreSkinnedMeshes",!1)}start(){this.targets=[this.gameObject]}performRaycast(t=null){if(!this.targets)return null;t??(t=new ta),t.targets=this.targets,t.results=this.raycastHits;const i=t.testObject;this.ignoreSkinnedMeshes&&(t.testObject=r=>r instanceof Ea?"continue in children":i?i(r):!0);const s=this.context.physics.raycast(t);return t.testObject=i,s}}Nne([x()],yo.prototype,"ignoreSkinnedMeshes",2);class vw extends yo{constructor(){super(),this.ignoreSkinnedMeshes=!0}}class Nv extends UA{performRaycast(e){if(!yt.active||!(e!=null&&e.ray))return null;const t=e.ray.origin,i=.01;return this.context.physics.sphereOverlap(t,i)}}class Aw{static getObject(e){const t=e[jo];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(t&&(t.canvasGroup=void 0,t.graphic=void 0),e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;const i=this.tryFindCanvasGroup(e);if((i==null?void 0:i.isCanvasGroup)===!0&&(t&&(t.canvasGroup=i),i.blocksRaycasts===!1||i.interactable===!1))return!1;const s=xd(e,r=>{if(r.isGraphic===!0)return r},!1);return t&&(s==null?void 0:s.isGraphic)===!0&&(t.graphic=s),!((s==null?void 0:s.raycastTarget)===!1||(s==null?void 0:s.layer)===2)}static tryFindCanvasGroup(e){if(!e)return null;const t=xd(e,i=>{const s=i;if(s.blocksRaycasts!==void 0&&s.interactable!==void 0)return s},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}}function FR(n){const e=n[jo];return e||(n.parent?FR(n.parent):null)}function zne(n){return n.isUI===!0||typeof n[jo]=="object"}function zb(n,e){if(!n)return;const t=n.material;if((t==null?void 0:t.isMaterial)===!0){const i=n.parent;i&&i.isText,t.side=e.doubleSided??!0?_i:Ls,t.shadowSide=e.doubleSided?_i:Ls,n.castShadow=e.castShadows?e.castShadows:!1,n.receiveShadow=e.receiveShadows?e.receiveShadows:!1}for(const i of n.children)zb(i,e)}function zf(n,e,t){n[e]===void 0&&console.warn("Field",e,"is undefined on",n);const i=Proxy.revocable(n[e],{set(o,a,c,l){const h=o[a],d=Reflect.set(o,a,c,l);return t(c,h),d}}),s=i.revoke,r=n[e];return i.revoke=()=>{n[e]=r,s()},n[e]=i.proxy,i}const n2=Symbol("Scheduled action");function Gne(n,e,t=Vn.OnBeforeRender){let i=n[n2];i||(i=n[n2]={});const s=e.name;i[t]||(i[t]={});const r=i[t];if(r[s])return;function*a(){e==null||e.call(n),r[s]=null}const c=n.startCoroutine(a(),t);r[s]=c}const Yc=se("debugeventsystem");var kM=(n=>(n.BeforeHandleInput="BeforeHandleInput",n.AfterHandleInput="AfterHandleInput",n))(kM||{});const ec=class extends Ie{constructor(){super();u(this,"raycaster",[]);u(this,"_handleInputFn");u(this,"pressedByID",new Map);u(this,"hoveredByID",new Map);u(this,"_sortedHits",[]);u(this,"_testObjectsCache",new Map);u(this,"_currentlyActiveRaycaster",null);u(this,"_currentPointerEventName",null);u(this,"shouldRaycastObject",t=>{var r;let i=null;if(zne(t)&&(i=(r=t[jo])==null?void 0:r.gameObject),this._testObjectsCache.has(t)||i&&this._testObjectsCache.has(i))return this._testObjectsCache.get(t)===!1?"continue in children":!0;{let o=OM(t,this._currentPointerEventName);if(!o&&i&&(o=OM(i,this._currentPointerEventName)),o){this._testObjectsCache.set(t,!0);for(const a of t.children)this.shouldRaycastObject_AddToYesCache(a);return!0}return this._testObjectsCache.set(t,!1),"continue in children"}});u(this,"_sortingBuffer",[]);u(this,"_noDepthTestingResults",[]);u(this,"out",{});u(this,"_capturedPointer",{});u(this,"pointerEnterSymbol",Symbol("pointerEnter"));u(this,"pointerExitSymbol",Symbol("pointerExit"));u(this,"currentActiveMeshUIComponents",[]);ec.systems.push(this)}static createIfNoneExists(t){this.didSearchEventSystem||(this.didSearchEventSystem=!0,ec.systems.length<=0&&ec.systems.push(...le.findObjectsOfType(ec,t)));for(const s of ec.systems)if(s.context===t)return;const i=new ge;le.addNewComponent(i,ec),t.scene.add(i)}static get systems(){const t=Ot.Current;return this._eventSystemMap.has(t)||this._eventSystemMap.set(t,[]),this._eventSystemMap.get(t)}static get(t){const i=this._eventSystemMap.get(t);return i&&i.length>0?i[0]:null}static get instance(){return this.systems[0]}static ensureUpdateMeshUI(t,i,s=!1){yh.update(t,i,s)}static markUIDirty(t){yh.markDirty()}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}onDestroy(){ec.systems.splice(ec.systems.indexOf(this),1)}start(){if(this.raycaster.length<=0&&!le.findObjectOfType(UA,this.context)){const i=le.addNewComponent(this.context.scene,yo);this.raycaster.push(i),(Mt()||Yc)&&console.warn("Added an ObjectRaycaster to the scene because no raycaster was found.")}}register(t){var i;t&&this.raycaster&&!this.raycaster.includes(t)&&((i=this.raycaster)==null||i.push(t))}unregister(t){var s,r;const i=(s=this.raycaster)==null?void 0:s.indexOf(t);i!==void 0&&i!==-1&&((r=this.raycaster)==null||r.splice(i,1))}onEnable(){this._handleInputFn??(this._handleInputFn=this.onPointerEvent.bind(this)),this.context.input.addEventListener(tn.PointerDown,this._handleInputFn),this.context.input.addEventListener(tn.PointerUp,this._handleInputFn),this.context.input.addEventListener(tn.PointerMove,this._handleInputFn)}onDisable(){this.context.input.removeEventListener(tn.PointerDown,this._handleInputFn),this.context.input.removeEventListener(tn.PointerUp,this._handleInputFn),this.context.input.removeEventListener(tn.PointerMove,this._handleInputFn)}onBeforeRender(){this.resetMeshUIStates()}onPointerEvent(t){if(t===void 0||t.propagationStopped)return;const i=new rm(this.context.input,t);this._currentPointerEventName=t.type,i.inputSource=this.context.input,i.isClick=t.isClick,i.isDoubleClick=t.isDoubleClick,i.isDown=t.type==tn.PointerDown,i.isUp=t.type==tn.PointerUp,i.isPressed=this.context.input.getPointerPressed(t.pointerId),Yc&&(i.isDown?console.log("DOWN",i.pointerId):i.isUp&&console.log("UP",i.pointerId),i.isClick&&console.log("CLICK",i.pointerId));const s=new ta;t.ray?s.ray=t.ray:s.screenPoint=this.context.input.getPointerPositionRC(t.pointerId);const r=this.performRaycast(s);Yc&&i.isClick&&xn("EventSystem: "+i.pointerId+" - "+this.context.time.frame+" - Up:"+i.isUp+", Down:"+i.isDown);const o={sender:this,args:i,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:o})),this.handleIntersections(r,i),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:o}))}shouldRaycastObject_AddToYesCache(t){this._testObjectsCache.set(t,!0);for(const i of t.children)this.shouldRaycastObject_AddToYesCache(i)}performRaycast(t){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,t||(t=new ta),t.testObject=this.shouldRaycastObject;for(const i of this.raycaster){if(!i.activeAndEnabled)continue;this._currentlyActiveRaycaster=i;const s=i.performRaycast(t);this._currentlyActiveRaycaster=null,s&&s.length>0&&this._sortedHits.push(...s)}return this._sortedHits.sort((i,s)=>i.distance-s.distance),this._sortedHits}assignHitInformation(t,i){i?(t.point=i.point,t.normal=i.normal,t.face=i.face,t.distance=i.distance,t.instanceId=i.instanceId):(t.point=void 0,t.normal=void 0,t.face=void 0,t.distance=void 0,t.instanceId=void 0)}handleIntersections(t,i){var r;if(t!=null&&t.length){t=this.sortCandidates(t);for(const o of t){if(i.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(i,o),this.handleEventOnObject(o.object,i))return!0}}this.assignHitInformation(i,t==null?void 0:t[0]),this.invokePointerCapture(i);const s=this.hoveredByID.get(i.pointerId);return s&&this.propagatePointerExit(s.obj,s.data,null),this.hoveredByID.delete(i.pointerId),i.isUp&&((r=this.pressedByID.get(i.pointerId))==null||r.handlers.forEach(o=>this.invokeOnPointerUp(i,o)),this.pressedByID.delete(i.pointerId)),!1}sortCandidates(t){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let i=0;i<t.length;i++){const s=t[i],r=s.object;if(r.material&&r.material.depthTest===!1){this._noDepthTestingResults.push(s);continue}this._sortingBuffer.push(s)}for(const i of this._sortingBuffer)this._noDepthTestingResults.push(i);return this._noDepthTestingResults}handleEventOnObject(t,i){if(!this.testIsVisible(t))return i.isClick&&Yc&&console.log("not allowed",t),!1;if(i.pointerId===void 0)return Yc&&console.error("Event without pointer can't be handled",i),!1;i.object=t;const s=t.parent;let r=!1;const o=i.isClick??!1;let a=null;if(s&&s.isUI){const f=(i.isPressed||i.isClick)??!1;if(s[jo]){const p=s[jo].gameObject;if(p){if(!Aw.isInteractable(p,this.out))return!1;a=this.out.canvasGroup??null,this.handleMeshUIIntersection(t,f),t=p,r=!0}}if(!r&&this.handleMeshUiObjectWithoutShadowDom(s,f))return!0}o&&Yc&&console.log(this.context.time.frame,t);const c=this.hoveredByID.get(i.pointerId),l=c==null?void 0:c.obj;l!==t&&l&&this.propagatePointerExit(l,c.data,t);const d=this.hoveredByID.get(i.pointerId);if(d?(d.obj=t,d.data=i):this.hoveredByID.set(i.pointerId,{obj:t,data:i}),i.isDown){const f=this.pressedByID.get(i.pointerId);f?(f.obj=t,f.data=i):this.pressedByID.set(i.pointerId,{obj:t,data:i,handlers:new Set})}return(a===null||a.interactable)&&this.handleMainInteraction(t,i,l??null),!0}propagate(t,i){for(;t;)le.foreachComponent(t,s=>{i(s)},!1),t=t.parent}handleMainInteraction(t,i,s){const r=this.pressedByID.get(i.pointerId),o=s!==t;let a=!0;switch(i.event.pointerType){case"mouse":case"touch":const c=this.context.input.getPointerPositionLastFrame(i.pointerId),l=this.context.input.getPointerPosition(i.pointerId);a=c&&!rt.approximately(c,l);break}this.propagate(t,c=>{const l=c;l.interactable!==!1&&(!l.activeAndEnabled||!l.enabled||(l.onPointerEnter&&o&&this.handlePointerEnter(l,i),i.isDown&&l.onPointerDown&&(l.onPointerDown(i),r==null||r.handlers.add(l),this.handlePointerCapture(i,l)),l.onPointerMove&&(a&&l.onPointerMove(i),this.handlePointerCapture(i,l)),i.isUp&&l.onPointerUp&&(this.invokeOnPointerUp(i,l),r==null||r.handlers.delete(l)),i.isClick&&l.onPointerClick&&l.onPointerClick(i)))}),i.isUp&&(r==null||r.handlers.forEach(c=>{this.invokeOnPointerUp(i,c)}),this.pressedByID.delete(i.pointerId))}propagatePointerExit(t,i,s){this.propagate(t,r=>{if(!r.gameObject||r.destroyed)return;const o=r;if(o.onPointerExit){if(s&&this.isChild(s,r.gameObject))return;this.handlePointerExit(o,i)}})}invokeOnPointerUp(t,i){var s;(s=i.onPointerUp)==null||s.call(i,t),this.releasePointerCapture(t,i)}handlePointerEnter(t,i){t.onPointerEnter&&this.updatePointerState(t,i.pointerId,this.pointerEnterSymbol,!0)&&t.onPointerEnter(i),this.updatePointerState(t,i.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(t,i){t.onPointerExit&&this.updatePointerState(t,i.pointerId,this.pointerExitSymbol,!0)&&t.onPointerExit(i),this.updatePointerState(t,i.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(t,i,s,r){let o=t[s];if(r)return o&&o.includes(i)?!1:(o=o||[],o.push(i),t[s]=o,!0);{if(!o||!o.includes(i))return!1;const a=o.indexOf(i);return a!==-1&&o.splice(a,1),!0}}handlePointerCapture(t,i){if(t.z__pointer_ctured){t.z__pointer_ctured=!1;const s=t.pointerId;if(i.onPointerMove){const r=this._capturedPointer[s]||[];r.push(i),this._capturedPointer[s]=r}else Mt()&&!i.z__warned_no_pointermove&&(i.z__warned_no_pointermove=!0,console.warn("PointerCapture was requested but the component doesn't implement onPointerMove. It will not receive any pointer events"))}else t.z__pointer_cture_rleased&&(t.z__pointer_cture_rleased=!1,this.releasePointerCapture(t,i))}releasePointerCapture(t,i){const s=t.pointerId;if(this._capturedPointer[s]){const r=this._capturedPointer[s].indexOf(i);r!==-1&&(this._capturedPointer[s].splice(r,1),Yc&&console.log("released pointer capture",s,i,this._capturedPointer))}}invokePointerCapture(t){var i;if(t.event.type===tn.PointerMove){const s=t.pointerId,r=this._capturedPointer[s];if(r){Yc&&console.log("Captured",s,r);for(let o=0;o<r.length;o++){const a=r[o];if(a.destroyed){r.splice(o,1),o--;continue}(i=a.onPointerMove)==null||i.call(a,t)}}}}isChild(t,i){return!t||!i?!1:t===i?!0:t.parent?this.isChild(t.parent,i):!1}handleMeshUiObjectWithoutShadowDom(t,i){return!t||!t.isUI?!0:this.handleMeshUIIntersection(t,i)}handleMeshUIIntersection(t,i){const s=yh.updateState(t,i);return s&&this.currentActiveMeshUIComponents.push(s),s!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&yh.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let t=0;t<this.currentActiveMeshUIComponents.length;t++){const i=this.currentActiveMeshUIComponents[t];yh.resetState(i)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(t){return t?le.isActiveSelf(t)?this.testIsVisible(t.parent):!1:!0}};let jr=ec;u(jr,"_eventSystemMap",new Map),u(jr,"didSearchEventSystem",!1);class yh{static markDirty(){this.needsUpdate=!0}static update(e,t,i=!1){if(i){e.update();return}const s=t.time.frameCount;for(const r of this.lastUpdateFrame)if(r.context===t){if(s===r.frame)return;r.frame=s;let o=this.needsUpdate||s<1;r.nextUpdate===t.time.frameCount&&(o=!0),o&&(Yc&&console.log("Update threemeshui"),this.needsUpdate=!1,e.update());return}this.lastUpdateFrame=[{context:t,frame:s,nextUpdate:s}],e.update()}static updateState(e,t){let i=null;if(e&&(i=this.findBlockInParent(e),i&&i!==this.lastSelected)){if(i.interactable===!1)return null;this.needsUpdate=!0}return i}static resetLastSelected(){const e=this.lastSelected;e&&(this.lastSelected=null,this.resetState(e))}static resetState(e){e&&(this.needsUpdate=!0)}static findBlockInParent(e){return e?e.isBlock?e:this.findBlockInParent(e.parent):null}}u(yh,"lastSelected",null),u(yh,"lastUpdateFrame",[]),u(yh,"needsUpdate",!1);var Hne=Object.defineProperty,Vne=Object.getOwnPropertyDescriptor,Qs=(n,e,t,i)=>{for(var s=i>1?void 0:i?Vne(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Hne(e,t,s),s};const Qne=se("debugorbit"),F0=se("freecam"),Zm=se("debugcamerafit"),U0=se("smoothcam"),jne={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let KC;class zv extends CustomEvent{constructor(e,t){super("target-reached",{detail:{controls:e,type:t}})}}class Ji extends Ie{constructor(){super(...arguments);u(this,"autoFit",!1);u(this,"enableRotate",!0);u(this,"autoRotate",!1);u(this,"autoRotateSpeed",1);u(this,"enableKeys",!0);u(this,"enableDamping",!0);u(this,"dampingFactor",.1);u(this,"enableZoom",!0);u(this,"minZoom",0);u(this,"maxZoom",1/0);u(this,"enablePan",!0);u(this,"lookAtConstraint",null);u(this,"lookAtConstraint01",1);u(this,"allowInterrupt",!0);u(this,"middleClickToFocus",!0);u(this,"doubleClickToFocus",!0);u(this,"useSlerp",!0);u(this,"debugLog",!1);u(this,"targetLerpDuration",1);u(this,"autoTarget",!0);u(this,"_controls",null);u(this,"_cameraObject",null);u(this,"_lookTargetLerpActive",!1);u(this,"_lookTargetStartPosition",new w);u(this,"_lookTargetEndPosition",new w);u(this,"_lookTargetLerp01",0);u(this,"_lookTargetLerpDuration",0);u(this,"_cameraLerpActive",!1);u(this,"_cameraStartPosition",new w);u(this,"_cameraEndPosition",new w);u(this,"_cameraLerp01",0);u(this,"_cameraLerpDuration",0);u(this,"_inputs",0);u(this,"_enableTime",0);u(this,"_startedListeningToKeyEvents",!1);u(this,"_eventSystem");u(this,"_afterHandleInputFn");u(this,"_camera",null);u(this,"_syncedTransform");u(this,"_didStart",!1);u(this,"targetElement",null);u(this,"onControlsChangeStarted",()=>{this._syncedTransform&&this._syncedTransform.requestOwnership()});u(this,"_shouldDisable",!1);u(this,"_haveAttachedKeyboardEvents",!1)}get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(t){var i;(i=this.controls)==null||i.addEventListener("start",t)}get targetLerpSpeed(){return 5}set targetLerpSpeed(t){this.targetLerpDuration=1/t}awake(){this._didStart=!1,this._startedListeningToKeyEvents=!1}start(){if(this._didStart=!0,this.autoTarget&&this._controls){const t=le.getComponent(this.gameObject,Yi);if(t&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const s=Dt(t.cam).length(),r=new w(0,0,-s).applyMatrix4(t.cam.matrixWorld);this.setLookTargetPosition(r,!0)}if(this.autoTarget&&!this.setLookTargetFromConstraint()){const i=new ta;i.screenPoint=new ie(0,0),i.lineThreshold=.1;const s=this.context.physics.raycast(i);s.length>0&&this.setLookTargetPosition(s[0].point,!0),Zm&&console.log("OrbitControls hits",...s)}this.autoFit&&this.fitCamera()}this._eventSystem=jr.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(kM.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){var t,i;(t=this._controls)==null||t.dispose(),(i=this._eventSystem)==null||i.removeEventListener(kM.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._enableTime=this.context.time.time;const t=le.getComponent(this.gameObject,Yi);this._camera=t;const i=t==null?void 0:t.cam;if(i&&t2(i,this,!0),!this._controls){if(!i){console.warn("OrbitControls: Requires a Camera component on the same object as this component.");return}i&&(this._cameraObject=i);const s=this.targetElement??this.context.renderer.domElement,r=i==null?void 0:i.quaternion.clone();this._controls=new xne(i,s),i==null||i.quaternion.copy(r),KC===void 0&&(KC={...this._controls.keys})}this._controls&&(F0&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,Ec()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),(i==null?void 0:i.type)==="PerspectiveCamera"?F0||(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):F0||(this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom),this._startedListeningToKeyEvents||(this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(window.document.body))),this._syncedTransform=le.getComponent(this.gameObject,Nh)??void 0}onDisable(){var t;(t=this._camera)!=null&&t.cam&&t2(this._camera.cam,this,!1),this._controls&&(this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted))}afterHandleInput(t){t.detail.args.pointerId===0&&(t.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!t.detail.args.isPressed||t.detail.args.isUp)&&(this._shouldDisable=!1))}onBeforeRender(){var i,s;if(!this._controls||this._cameraObject!==this.context.mainCamera)return;(this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2)||this.context.input.mouseWheelChanged||this.context.input.getPointerPressed(0)&&((i=this.context.input.getPointerPositionDelta(0))!=null&&i.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 t=this.middleClickToFocus&&this.context.input.getPointerClicked(1);if(t||(t=this.doubleClickToFocus&&this.context.input.getPointerDoubleClicked(0)&&this.context.time.time-this._enableTime>.3),t&&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 zv(this,"camera"));else{const r=rt.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,r)}if(this._lookTargetLerpActive)if(this._lookTargetLerp01+=this.context.time.deltaTime/this._lookTargetLerpDuration,this._lookTargetLerp01>=1)this._controls.target.copy(this._lookTargetEndPosition),this._lookTargetLerpActive=!1,this.dispatchEvent(new zv(this,"lookat"));else{const r=rt.easeInOutCubic(this._lookTargetLerp01);this._controls.target.lerpVectors(this._lookTargetStartPosition,this._lookTargetEndPosition,r)}}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?KC:jne,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,typeof U0=="number"||U0===!0){this._controls.enableDamping=!0;const r=typeof U0=="number"?U0:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,r))}this.allowInterrupt||(this._lookTargetLerpActive&&(this._controls.enablePan=!1),this._cameraLerpActive&&(this._controls.enableRotate=!1,this._controls.autoRotate=!1),(this._lookTargetLerpActive||this._cameraLerpActive)&&(this._controls.enableZoom=!1)),this.context.isInXR||(!F0&&((s=this.lookAtConstraint)!=null&&s.locked)&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(),Qne&&It.DrawWireSphere(this._controls.target,.1,65280))}}setCameraAndLookTarget(t){if(!t||!(t instanceof ge))return;const i=Dt(t),s=AR(t);this.setTargetFromRaycast(new bo(i,s)),this.setCameraTargetPosition(i)}setCameraTargetPosition(t,i=!1){var s,r;t&&(t instanceof ge&&(t=Dt(t)),this._cameraEndPosition||(this._cameraEndPosition=new w),this._cameraEndPosition.copy(t),i===!0?(this._cameraLerpActive=!1,(s=this.controllerObject)==null||s.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy((r=this._cameraObject)==null?void 0:r.position),typeof i=="number"?this._cameraLerpDuration=i:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setLookTargetPosition(t=null,i=!1){this._controls&&t&&(t instanceof ge&&(t=Dt(t)),this._lookTargetEndPosition.copy(t),i===!0?this._controls.target.copy(this._lookTargetEndPosition):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof i=="number"?this._lookTargetLerpDuration=i:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(t=0,i=1){var r;if(!this._controls)return!1;const s=(r=this.lookAtConstraint)==null?void 0:r.sources;if(s&&s.length>0){const o=s[t];if(o)return o.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._lookTargetEndPosition,i),!0}return!1}lerpTarget(t,i){return this.lerpLookTarget(t,i)}lerpLookTarget(t,i){this._controls&&(i>=1?this._controls.target.copy(t):this._controls.target.lerp(t,i))}setTargetFromRaycast(t){var s,r;if(!this.controls)return;const i=t?this.context.physics.raycastFromRay(t):this.context.physics.raycast();for(const o of i)if(o.distance>0&&le.isActiveInHierarchy(o.object)){const a=FR(o.object);if(a){const c=a.canvas;if(c!=null&&c.screenspace)break}if(this.setLookTargetPosition(o.point),this.context.mainCamera){const l=Dt(this.context.mainCamera).clone().sub(this.controls.target).add(this._lookTargetEndPosition);(r=(s=this._cameraObject)==null?void 0:s.parent)==null||r.worldToLocal(l),this.setCameraTargetPosition(l)}break}}fitCamera(t,i=1.1,s=!0){const r=this._cameraObject,o=this._controls;if(t!=null&&t.length||(t=this.context.scene.children),t.length<=0||!r||!o)return;const a=new w,c=new w,l=new Oi;l.makeEmpty();const h=[];function d(_){let b=!0;if(_.visible&&Sne(_)!==!1&&!(_.type==="TransformControlsGizmo"||_.type==="TransformControlsPlane")&&(_ instanceof S1&&(b=!1),_ instanceof Nx&&(b=!1),_ instanceof DH&&(b=!1),_.material instanceof Rx&&(b=!1),_ instanceof me||(b=!1),_!==r&&_.isUI!==!0)){if(b){Zm&&console.log(_.name,_.type,_);const C=_.children;_.children=h;const E=_.position,T=_.scale;if(Number.isNaN(E.x)||Number.isNaN(E.y)||Number.isNaN(E.z)){console.warn(`Object "${_.name}" has NaN values in position or scale.... will ignore it`,E,T);return}l.expandByObject(_,!0),_.children=C}for(const C of _.children)d(C)}}for(const _ of t)_.updateMatrixWorld(),d(_);if(r.updateMatrixWorld(),r.updateProjectionMatrix(),l.getCenter(c),l.applyMatrix4(r.matrixWorldInverse),l.getSize(a),l.setFromCenterAndSize(c,a),Number.isNaN(a.x)||Number.isNaN(a.y)||Number.isNaN(a.z)){console.warn("Camera fit size resultet in NaN",r,l,[...t]);return}if(a.length()<=1e-10){Zm&&console.warn("Camera fit size is zero",l,[...t]);return}const f=r.fov,p=2*Math.atan(Math.tan(f*Math.PI/360/2)*r.aspect)/Math.PI*360,m=a.y/(2*Math.atan(Math.PI*f/360)),g=a.x/(2*Math.atan(Math.PI*p/360)),y=i*Math.max(m,g)+a.z/2;Zm&&console.log("Fit camera to objects",m,g,"distance",y);const v=Dt(r),A=o.target.clone().sub(v).normalize().multiplyScalar(y);if(o.maxDistance=y*10,o.minDistance=y*.01,this.setLookTargetPosition(c,s),this.autoTarget=!1,r.near=y/1e3,r.far=y*100,r.updateMatrixWorld(),r.updateProjectionMatrix(),r.parent){const _=r.parent.worldToLocal(o.target.clone().sub(A));this.setCameraTargetPosition(_,s)}else console.error(`Can not fit camera ${r.name} because it has no parent`);if(Zm){const _=new S1(l);this.context.scene.add(_),bR(_,CA(r)),this._haveAttachedKeyboardEvents||(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",b=>{b.code==="KeyF"&&this.fitCamera(t)}))}o.update()}}Qs([x()],Ji.prototype,"autoFit",2);Qs([x()],Ji.prototype,"enableRotate",2);Qs([x()],Ji.prototype,"autoRotate",2);Qs([x()],Ji.prototype,"autoRotateSpeed",2);Qs([x()],Ji.prototype,"enableKeys",2);Qs([x()],Ji.prototype,"enableDamping",2);Qs([x()],Ji.prototype,"dampingFactor",2);Qs([x()],Ji.prototype,"enableZoom",2);Qs([x()],Ji.prototype,"minZoom",2);Qs([x()],Ji.prototype,"maxZoom",2);Qs([x()],Ji.prototype,"enablePan",2);Qs([x(LA)],Ji.prototype,"lookAtConstraint",2);Qs([x()],Ji.prototype,"lookAtConstraint01",2);Qs([x()],Ji.prototype,"allowInterrupt",2);Qs([x()],Ji.prototype,"middleClickToFocus",2);Qs([x()],Ji.prototype,"doubleClickToFocus",2);Qs([x()],Ji.prototype,"targetLerpDuration",2);var Wne=Object.defineProperty,qne=Object.getOwnPropertyDescriptor,wo=(n,e,t,i)=>{for(var s=i>1?void 0:i?qne(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Wne(e,t,s),s},wd=(n=>(n[n.Skybox=1]="Skybox",n[n.SolidColor=2]="SolidColor",n[n.Uninitialized=4]="Uninitialized",n))(wd||{});const Gu=se("debugcam"),s2=se("debugscreenpointtoray");var l_;const Sg=(l_=class extends Ie{constructor(){super(...arguments);u(this,"_nearClipPlane",.1);u(this,"_farClipPlane",1e3);u(this,"orthographic",!1);u(this,"orthographicSize",5);u(this,"ARBackgroundAlpha",0);u(this,"_cullingMask",4294967295);u(this,"_backgroundBlurriness");u(this,"_backgroundIntensity");u(this,"_environmentIntensity");u(this,"_targetTexture",null);u(this,"_backgroundColor");u(this,"_fov");u(this,"_cam",null);u(this,"_clearFlags",2);u(this,"_skybox")}get isCamera(){return!0}get aspect(){return this._cam instanceof Jt?this._cam.aspect:this.context.domWidth/this.context.domHeight}get fieldOfView(){return this._cam instanceof Jt?this._cam.fov:this._fov}set fieldOfView(e){const t=this.fieldOfView!=e;if(this._fov=e,t&&this._cam&&this._cam instanceof Jt){if(this._fov===void 0){console.warn("Can not set undefined fov on PerspectiveCamera");return}this._cam.fov=this._fov,this._cam.updateProjectionMatrix()}}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(e){const t=this._nearClipPlane!=e;this._nearClipPlane=e,this._cam&&t&&(this._cam.near=e,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(e){const t=this._farClipPlane!=e;this._farClipPlane=e,this._cam&&t&&(this._cam.far=e,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(e){e!==this._clearFlags&&(this._clearFlags=e,this.applyClearFlagsIfIsActiveCamera())}set cullingMask(e){this._cullingMask=e,this._cam&&(this._cam.layers.mask=e)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}set cullingLayer(e){this.cullingMask=(1<<e|0)>>>0}set backgroundBlurriness(e){e!==this._backgroundBlurriness&&(e===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(e,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}set backgroundIntensity(e){e!==this._backgroundIntensity&&(e===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(e,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}set environmentIntensity(e){this._environmentIntensity=e}get environmentIntensity(){return this._environmentIntensity}get backgroundColor(){return this._backgroundColor??null}set backgroundColor(e){if(e){if(this._backgroundColor)this._backgroundColor.copy(e);else{if(!e.clone)return;this._backgroundColor=e.clone()}e.alpha===void 0&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera()}}set targetTexture(e){this._targetTexture=e}get targetTexture(){return this._targetTexture}get cam(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(e,t,i){const s=this.cam,r=Sg._origin;r.set(e,t,-1),this.context.input.convertScreenspaceToRaycastSpace(r),s2&&console.log("screenPointToRay",e.toFixed(2),t.toFixed(2),"now:",r.x.toFixed(2),r.y.toFixed(2),"isInXR:"+this.context.isInXR),r.z=-1,r.unproject(s);const o=Sg._direction.set(r.x,r.y,r.z),a=Dt(s);return o.sub(a),o.normalize(),i?(i.set(a,o),i):new bo(a.clone(),o.clone())}awake(){s2&&window.addEventListener("pointerdown",e=>{const t=e.clientX,i=e.clientY;console.log("touch",t.toFixed(2),i.toFixed(2));const s=this.screenPointToRay(t,i),r="#"+Math.floor(Math.random()*16777215).toString(16);It.DrawRay(s.origin,s.direction,r,10)})}onEnable(){Gu&&console.log(`Camera enabled: "${this.name}". ClearFlags=${wd[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),Yne(this)),this.applyClearFlagsIfIsActiveCamera()}onDisable(){this.context.removeCamera(this)}onBeforeRender(){if(this._cam&&(this._clearFlags===2&&this.applyClearFlagsIfIsActiveCamera(),this._targetTexture)){this.context.isManagedExternally&&(this._warnedAboutExternalRenderer||(this._warnedAboutExternalRenderer=!0,console.warn("Rendering with external renderer is not supported yet. This may not work or throw errors. Please remove the the target texture from your camera: "+this.name,this.targetTexture))),this.context.composer;const e=this.context.renderer;if(e){const t=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,e),t==null||t.applyClearFlags()}}}buildCamera(){if(this._cam)return;const e=this.gameObject.isCamera;let t=null;if(e?(t=this.gameObject,t==null||t.layers.enableAll(),t instanceof Jt&&(this._fov=t.fov)):t=this.gameObject.children[0],t&&t.isCamera)t instanceof Jt&&(this._fov&&(t.fov=this._fov),t.near=this._nearClipPlane,t.far=this._farClipPlane,t.updateProjectionMatrix());else if(!this.orthographic)t=new Jt(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(t.fov=this.fieldOfView),this.gameObject.add(t);else{const i=this.orthographicSize*100;t=new Pl(window.innerWidth/-i,window.innerWidth/i,window.innerHeight/i,window.innerHeight/-i,this._nearClipPlane,this._farClipPlane),this.gameObject.add(t)}this._cam=t,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(){this.context.mainCameraComponent===this&&this.applyClearFlags()}applyClearFlags(){if(!this._cam){Gu&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this._fov,Gu){const e=`Camera "${this.name}" clear flags: ${wd[this._clearFlags]}`;console.log(e)}switch(this._clearFlags){case 1:if(Sg.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),this._backgroundIntensity!==void 0&&(this.context.scene.backgroundIntensity=this._backgroundIntensity);break;case 2:if(this._backgroundColor){let e=this._backgroundColor.alpha;Sg.backgroundShouldBeTransparent(this.context)&&(e=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.renderer.setClearColor(this._backgroundColor,e)}else Gu&&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 Xne(this)),this._skybox.enable()}static backgroundShouldBeTransparent(e){var r,o,a,c;const t=(r=e.renderer.xr)==null?void 0:r.getSession();if(!t)return!1;if(typeof t._transparent=="boolean")return t._transparent;const i=t.environmentBlendMode;Gu&&xn("Environment blend mode: "+i+" on "+navigator.userAgent);let s=i==="additive"||i==="alpha-blend";return e.isInAR&&i==="opaque"&&((o=navigator.userAgent)!=null&&o.includes("OculusBrowser")||(a=navigator.userAgent)!=null&&a.includes("Mozilla")&&((c=navigator.userAgent)!=null&&c.includes("Mobile WebXRViewer/v2")))&&(s=!0),t._transparent=s,s}},u(l_,"_origin",new w),u(l_,"_direction",new w),l_);let Yi=Sg;wo([x()],Yi.prototype,"fieldOfView",1);wo([x()],Yi.prototype,"nearClipPlane",1);wo([x()],Yi.prototype,"farClipPlane",1);wo([x()],Yi.prototype,"clearFlags",1);wo([x()],Yi.prototype,"orthographic",2);wo([x()],Yi.prototype,"orthographicSize",2);wo([x()],Yi.prototype,"ARBackgroundAlpha",2);wo([x()],Yi.prototype,"cullingMask",1);wo([x()],Yi.prototype,"backgroundBlurriness",1);wo([x()],Yi.prototype,"backgroundIntensity",1);wo([x()],Yi.prototype,"environmentIntensity",1);wo([x(Ti)],Yi.prototype,"backgroundColor",1);wo([x(Rh)],Yi.prototype,"targetTexture",1);class Xne{constructor(e){u(this,"_camera");u(this,"_skybox");this._camera=e}get context(){var e;return(e=this._camera)==null?void 0:e.context}enable(){this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),this._skybox?this.context.scene.background!==this._skybox&&(Gu&&console.log(`Camera "${this._camera.name}" set skybox`,this._camera,this._skybox),this._skybox.colorSpace=Wt,this._skybox.mapping=Xo,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)),(Gu||Mt())&&pn(`Camera "${this._camera.name}" has no skybox texture`))}}function Yne(n){se("freecam")&&n.context.mainCameraComponent===n&&le.getOrAddComponent(n.gameObject,Ji)}class Ph extends Ie{constructor(){super(...arguments);u(this,"_listener",null)}get listener(){return this._listener==null&&(this._listener=new TU),this._listener}awake(){Cn.registerWaitForAllowAudio(()=>{if(this.destroyed)return;const t=this.listener;if(t==null||t.parent)return;const i=this.context.mainCameraComponent||le.getComponentInParent(this.gameObject,Yi);i!=null&&i.cam?i.cam.add(t):this.gameObject.add(t)})}}var Jne=Object.defineProperty,Kne=Object.getOwnPropertyDescriptor,yw=(n,e,t,i)=>{for(var s=i>1?void 0:i?Kne(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Jne(e,t,s),s};const Zne=se("debugsignals");class NA{constructor(){u(this,"guid")}}yw([x()],NA.prototype,"guid",2);class om{constructor(){u(this,"signal");u(this,"reaction")}}yw([x(NA)],om.prototype,"signal",2);yw([x(gs)],om.prototype,"reaction",2);var kE;const Jc=(kE=class extends Ie{constructor(){super(...arguments);u(this,"events")}static invoke(e){if(Jc.receivers[e]){const t=Jc.receivers[e];if(!t)return;for(const i of t)i.invoke(e)}}awake(){Zne&&console.log("SignalReceiver awake",this)}onEnable(){if(this.events)for(const e of this.events)Jc.receivers[e.signal.guid]||(Jc.receivers[e.signal.guid]=[]),Jc.receivers[e.signal.guid].push(this)}onDisable(){if(this.events){for(const e of this.events)if(Jc.receivers[e.signal.guid]){const t=Jc.receivers[e.signal.guid].indexOf(this);t>=0&&Jc.receivers[e.signal.guid].splice(t,1)}}}invoke(e){if(!this.events||!Array.isArray(this.events))return;const t=typeof e=="object"?e.guid:e;for(const i of this.events)if(i.signal.guid===t)try{if(i.reaction){if(!i.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",i,this);continue}}else{console.warn("Missing reaction for signal",i,this);continue}i.reaction.invoke()}catch(s){console.error(s)}}},u(kE,"receivers",{}),kE);let am=Jc;yw([x(om)],am.prototype,"events",2);var io=(n=>(n.Activation="ActivationTrack",n.Animation="AnimationTrack",n.Audio="AudioTrack",n.Control="ControlTrack",n.Marker="MarkerTrack",n.Signal="SignalTrack",n))(io||{}),Za=(n=>(n[n.None=0]="None",n[n.Hold=1]="Hold",n[n.Loop=2]="Loop",n[n.PingPong=3]="PingPong",n[n.Continue=4]="Continue",n))(Za||{}),UR=(n=>(n.Signal="SignalEmitter",n))(UR||{});const pc=se("debugtimeline");class zA{constructor(){u(this,"director");u(this,"track")}get muted(){return this.track.muted}set muted(e){var t;e!==this.track.muted&&(this.track.muted=e,(t=this.onMuteChanged)==null||t.call(this))}*forEachClip(e=!1){var t;if((t=this.track)!=null&&t.clips)if(e)for(let i=this.track.clips.length-1;i>=0;i--)yield this.track.clips[i];else for(const i of this.track.clips)yield i}getClipTime(e,t){return t.clipIn+(e-t.start)*t.timeScale}getClipTimeNormalized(e,t){return(e-t.start)/t.duration}evaluateWeight(e,t,i,s=!0){if(t<0||t>=i.length)return 0;const r=i[t];if(s||e>=r.start&&e<=r.end){let o=1;const a=!1;if(r.easeInDuration>0){const c=Math.min((e-r.start)/r.easeInDuration,1);o*=c}if(r.easeOutDuration>0&&!a){const c=Math.min((r.end-e)/r.easeOutDuration,1);o*=c}return o}return 0}}class $ne{constructor(e){u(this,"clip");u(this,"rootPositionOffset");u(this,"rootQuaternionOffset");u(this,"rootStartPosition");u(this,"rootEndPosition");u(this,"rootStartQuaternion");u(this,"rootEndQuaternion");const t=e.getClip();this.clip=t;const i=e.getRoot(),s=i.name+".position",r=i.name+".quaternion";pc&&console.log(t.name,t.tracks,s);for(const o of t.tracks)if(!(o.times.length<=0)){if(o.name.endsWith(s))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),pc&&console.log(this.rootPositionOffset);else if(o.name.endsWith(r)&&(this.rootStartQuaternion=new Ee().fromArray(o.values,0),this.rootEndQuaternion=new Ee().fromArray(o.values,o.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),pc)){const a=new ks().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",a)}}}get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}}class _w extends zA{constructor(){super(...arguments);u(this,"models",[]);u(this,"trackOffset");u(this,"target");u(this,"mixer");u(this,"clips",[]);u(this,"actions",[]);u(this,"_actionOffsets",[]);u(this,"_didBind",!1);u(this,"_animator",null);u(this,"_useclipOffsets",!0);u(this,"_totalOffsetPosition",new w);u(this,"_totalOffsetRotation",new Ee);u(this,"_totalOffsetPosition2",new w);u(this,"_totalOffsetRotation2",new Ee);u(this,"_summedPos",new w);u(this,"_tempPos",new w);u(this,"_summedRot",new Ee);u(this,"_tempRot",new Ee);u(this,"_clipRotQuat",new Ee)}onStateChanged(){this._animator&&r2(this._animator.gameObject,this,this.director.isPlaying)}createHooks(t,i){var h,d;if(((h=i.tracks)==null?void 0:h.length)<=0){console.warn("No tracks in AnimationClip",i);return}const s=i.tracks[0].name.split("."),r=s[s.length-2],o=r+".position",a=r+".quaternion";let c=!1,l=!1;for(const f of i.tracks)f.name.endsWith(o)?(c=!0,this.createPositionInterpolant(i,t,f)):f.name.endsWith(a)&&(l=!0,this.createRotationInterpolant(i,t,f));if(!c||!l){const f=(d=this.mixer)==null?void 0:d.getRoot(),p=i.tracks[0],m=p.name.lastIndexOf("."),g=p.name.substring(0,m),y=g.substring(g.lastIndexOf(".")+1),v=f.getObjectByName(y);if(v)if(c){if(!l){const A=i.tracks[0].name.substring(0,m)+".quaternion";pc&&console.warn("Create quaternion track",y,v);const _=v.quaternion,b=new Sc(A,[0,i.duration],[_.x,_.y,_.z,_.w,_.x,_.y,_.z,_.w]);i.tracks.push(b),this.createRotationInterpolant(i,t,b)}}else{const A=g+".position";pc&&console.warn("Create position track",y,v);const _=v.position,b=new El(A,[0,i.duration],[_.x,_.y,_.z,_.x,_.y,_.z]);i.tracks.push(b),this.createPositionInterpolant(i,t,b)}}}bind(){if(!this._didBind){this._didBind=!0,pc&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(const t of this.actions){const i=new $ne(t);this._actionOffsets.push(i)}this.target&&(this._animator=le.getComponent(this.target,Us)??null,this._animator&&r2(this._animator.gameObject,this,!0));for(const t of this.models){const i=t.asset,s=i.position,r=i.rotation;s&&s.x!==void 0&&(s.isVector3||(i.position=new w(s.x,s.y,s.z)),r.isQuaternion||(i.rotation=new Ee(r.x,r.y,r.z,r.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){const t=this.trackOffset.position;t&&(t.isVector3||(this.trackOffset.position=new w(t.x,t.y,t.z)));const i=this.trackOffset.rotation;i&&(i.isQuaternion||(this.trackOffset.rotation=new Ee(i.x,i.y,i.z,i.w)))}}evaluate(t){var c,l,h,d,f,p,m;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 i=0,s=0,r=!1,o=!1,a=0;for(let g=0;g<this.clips.length;g++){const y=this.models[g],v=this.actions[g],A=y.asset;v.weight=0;const _=t>=y.start&&t<=y.end,b=y.preExtrapolationMode,C=y.postExtrapolationMode,E=g<this.clips.length-1?this.models[g+1]:null;let T=_,I=!1;if(!T&&!r&&y.end<t&&C!==Za.None?(!E||E.start>t)&&(T=!0,r=!0):g==0&&!T&&!o&&y.start>t&&b!==Za.None&&(!E||E.start<t)&&(T=!0,I=!0,o=!0),T){let S=1;S*=this.evaluateWeight(t,g,this.models,T),S*=this.director.weight;let M=_;if(I)switch(b){case Za.Hold:break;case Za.Loop:t+=y.start,M=!0;break;default:t+=y.start,M=!0;break}let D=this.getClipTime(t,y),G=0;const Q=A.duration;if(I&&b===Za.Hold&&(D=0),M){if(A.loop)for(G+=Math.floor(D/(Q+1e-6));D>Q;)D-=Q}else if(!_&&r)switch(C){case Za.Hold:D=this.getClipTime(y.end,y);break;case Za.Loop:D%=Q;break;case Za.PingPong:const O=Math.floor(D/Q)%2!==0;D%=Q,O&&(D=Q-D);break}y.reversed===!0?v.time=v.getClip().duration-D:v.time=D,v.timeScale=0;const L=Math.max(0,S);if(v.weight=L,a+=L,v.clampWhenFinished=!1,v.isRunning()||v.play(),this._useclipOffsets){const H=i==0?this._totalOffsetPosition:this._totalOffsetPosition2,O=i==0?this._totalOffsetRotation:this._totalOffsetRotation2;i<1&&(s=1-S),i+=1;const U=this._summedPos.set(0,0,0),V=this._tempPos.set(0,0,0),J=this._summedRot.identity(),K=this._tempRot.identity(),oe=A.rotation;oe&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp(oe,S));const fe=this._actionOffsets[g];if(fe.hasOffsets)for(let be=0;be<G;be++)fe.rootPositionOffset?V.copy(fe.rootPositionOffset):V.set(0,0,0),V.applyQuaternion(J),this._clipRotQuat&&V.applyQuaternion(this._clipRotQuat),fe.rootQuaternionOffset&&(K.copy(fe.rootQuaternionOffset),J.multiply(K)),U.add(V);this._clipRotQuat&&O.multiply(this._clipRotQuat),O.multiply(J),A.position&&U.add(A.position),H.add(U)}}}if(this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,s),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,s)),this.__mixerError===void 0&&(pc||Mt())&&((l=(c=this._animator)==null?void 0:c.runtimeAnimatorController)!=null&&l.mixer)&&this.mixer!==((d=(h=this._animator)==null?void 0:h.runtimeAnimatorController)==null?void 0:d.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)),(f=this._animator)!=null&&f.runtimeAnimatorController){const g=Math.max(0,1-a);(m=(p=this._animator)==null?void 0:p.runtimeAnimatorController)==null||m.update(g)}else this.mixer.update(t)}createRotationInterpolant(t,i,s){var c;const r=s.createInterpolant.bind(s),o=new Ee;this.ensureTrackOffsets();const a=(c=this.trackOffset)==null?void 0:c.rotation;s.createInterpolant=()=>{const l=r(),h=l.evaluate.bind(l);return l.evaluate=d=>{var p;const f=h(d);if(o.set(f[0],f[1],f[2],f[3]),o.premultiply(this._totalOffsetRotation),a&&o.premultiply(a),this.director.animationCallbackReceivers)for(const m of this.director.animationCallbackReceivers)(p=m==null?void 0:m.onTimelineRotation)==null||p.call(m,this.director,this.target,d,o);return f[0]=o.x,f[1]=o.y,f[2]=o.z,f[3]=o.w,f},l}}createPositionInterpolant(t,i,s){var h,d;const r=s.createInterpolant.bind(s),o=new w;this.ensureTrackOffsets();const a=(h=this.trackOffset)==null?void 0:h.rotation,c=(d=this.trackOffset)==null?void 0:d.position;let l;s.createInterpolant=()=>{const f=r(),p=f.evaluate.bind(f);return f.evaluate=m=>{var y,v,A;const g=p(m);if(o.set(g[0],g[1],g[2]),i.removeStartOffset&&(l===void 0?(l=null,l=(v=(y=this._actionOffsets.find(_=>_.clip===t))==null?void 0:y.rootStartPosition)==null?void 0:v.clone()):l!=null&&l.isVector3&&o.sub(l)),o.applyQuaternion(this._totalOffsetRotation),o.add(this._totalOffsetPosition),a&&o.applyQuaternion(a),c&&(o.x-=c.x,o.y+=c.y,o.z+=c.z),this.director.animationCallbackReceivers)for(const _ of this.director.animationCallbackReceivers)(A=_==null?void 0:_.onTimelinePosition)==null||A.call(_,this.director,this.target,m,o);return g[0]=o.x,g[1]=o.y,g[2]=o.z,g},f}}}const ese=se("mutetimeline"),op=class extends zA{constructor(){super(...arguments);u(this,"models",[]);u(this,"listener");u(this,"audio",[]);u(this,"audioContextTimeOffset",[]);u(this,"lastTime",0);u(this,"audioSource");u(this,"_audioLoader",null);u(this,"_playableDirectorResumed",!1)}getAudioFilePath(t){const i=this.director.sourceId;return Wh(i,t)}onAllowAudioChanged(t){for(let i=0;i<this.models.length;i++){const s=this.models[i];this.audio[i].setVolume(t?s.asset.volume:0)}}addModel(t){const i=new tI(this.listener);this.audio.push(i);const s=t;s._didTriggerPlay=!1,this.models.push(s)}onDisable(){for(const t of this.audio)t.isPlaying&&t.stop();for(const t of this.models)t._didTriggerPlay=!1}onDestroy(){for(const t of this.audio)t.source&&(t==null||t.disconnect());this.audio.length=0}onMuteChanged(){if(this.muted)for(let t=0;t<this.audio.length;t++){const i=this.audio[t];i!=null&&i.isPlaying&&i.stop()}}stop(){for(let t=0;t<this.audio.length;t++){const i=this.audio[t];i!=null&&i.isPlaying&&i.stop()}for(const t of this.models)t._didTriggerPlay=!1}onPauseChanged(){for(let t=0;t<this.audio.length;t++){const i=this.audio[t];i!=null&&i.isPlaying&&i.stop()}this._playableDirectorResumed=this.director.isPlaying}evaluate(t){if(ese||this.track.muted||this.director.speed<0)return;const i=this.director.context.application.muted,s=this._playableDirectorResumed;this._playableDirectorResumed=!1;const r=i?.1:0;for(let o=0;o<this.models.length;o++){const a=this.models[o],c=this.audio[o],l=a.asset;if((!c||!c.buffer)&&this.isInTimeRange(a,t-1,t+1)&&this.handleAudioLoading(a,c),Cn.userInteractionRegistered!==!1&&!(c===null||!c.buffer))if(c.playbackRate=this.director.context.time.timeScale*this.director.speed,c.loop=l.loop,t>=a.start&&t<=a.end&&t<this.director.duration){if(!c.isPlaying||!this.director.isPlaying)(s||!a._didTriggerPlay&&this.lastTime<t)&&(a.duration*a.timeScale>.3?c.offset=a.clipIn+(t-a.start)*a.timeScale:c.offset=0,pc&&console.log("Timeline Audio ("+this.track.name+") play with offset "+c.offset+" - "+a.asset.clip),c.play(r),a._didTriggerPlay=!0);else{const d=a.clipIn+(t-a.start)*a.timeScale,f=c.context.currentTime-c._startedAt+c.offset;Math.abs(d-f)>.3&&(c.offset=d,c.stop(),c.play(r))}let h=l.volume;if(this.track.volume!==void 0&&(h*=this.track.volume),i&&(h=0),a.easeInDuration>0){const d=Math.min((t-a.start)/a.easeInDuration,1);h*=d}if(a.easeOutDuration>0){const d=Math.min((a.end-t)/a.easeOutDuration,1);h*=d}c.setVolume(h*this.director.weight)}else a._didTriggerPlay=!1,this.director.isPlaying&&c.isPlaying&&c.stop()}this.lastTime=t}loadAudio(t,i=0,s=0){let r=null;const o=t-s,a=t+i;for(const c of this.models)if(this.isInTimeRange(c,o,a)){const l=this.audio[this.models.indexOf(c)],h=this.handleAudioLoading(c,l);h!==null&&(r===null&&(r=[]),r.push(h))}return r!==null?Promise.all(r):null}isInTimeRange(t,i,s){return i<=t.start&&s>=t.end||i>=t.start&&i<=t.end||s>=t.start&&s<=t.end}static dispose(){op._audioBuffers.clear()}handleAudioLoading(t,i){this._audioLoader||(this._audioLoader=new db);const s=this.getAudioFilePath(t.asset.clip);if(op._audioBuffers.get(s)){const o=op._audioBuffers.get(s);return o.then(a=>{a&&i.setBuffer(a)}),o}pc&&console.warn("LOAD audio track",s,this.director.sourceId);const r=new Promise((o,a)=>{this._audioLoader.load(s,c=>{i.setBuffer(c),o(c)},void 0,c=>{console.error("Error loading audio",c),o(null)})});return op._audioBuffers.set(s,r),r}};let hd=op;u(hd,"_audioBuffers",new Map);class Gv extends zA{constructor(){super(...arguments);u(this,"models",[]);u(this,"didTrigger",[]);u(this,"receivers",[])}evaluate(t){var s;if(this.track.muted)return;const i=this.director.context.time.deltaTime*1.5;for(let r=0;r<this.models.length;r++){const o=this.models[r],a=this.didTrigger[r],c=o.time-t;let l=!1;if(o.retroActive)l=c<=1e-6;else{const h=Math.abs(c);(h===0||h>=1e-5&&h<i)&&(l=!0)}if(l){if(!a)if(pc&&console.log("Trigger signal",t,o.time,o),this.didTrigger[r]=!0,((s=this.receivers)==null?void 0:s.length)<=0)am.invoke(o.asset);else for(const h of this.receivers)h&&h.invoke(o.asset)}else o.emitOnce||(this.didTrigger[r]=!1)}}}class bw extends zA{constructor(){super(...arguments);u(this,"models",[]);u(this,"timelines",[]);u(this,"_previousActiveModel",null)}resolveSourceObjects(t){for(let i=this.models.length-1;i>=0;i--){const r=this.models[i].asset;if(!r.sourceObject||typeof r.sourceObject!="object"){console.log("no source object, removing model",i,r),this.models.splice(i,1);continue}else{const o=le.getComponent(r.sourceObject,Sl);this.timelines.push(o),o&&r.updateDirector&&(o.playOnAwake=!1)}}}evaluate(t){var i;this._previousActiveModel=null;for(let s=0;s<this.models.length;s++){const r=this.models[s],o=r.asset;if(t>=r.start&&t<=r.end){this._previousActiveModel=r;const a=this.getClipTime(t,r);if(o.controlActivation){const c=o.sourceObject;c.visible=!0}if(o.updateDirector){const c=this.timelines[s];c&&(c.isPlaying&&c.pause(),c.time=a,c.evaluate())}}else{const a=(i=this._previousActiveModel)==null?void 0:i.asset;if(o.controlActivation){const c=o.sourceObject;(a==null?void 0:a.sourceObject)!==c&&(c.visible=!1)}}}}}const Ef=se("debugtimeline"),ex=class extends Ie{constructor(){super(...arguments);u(this,"playableAsset");u(this,"playOnAwake");u(this,"extrapolationMode",1);u(this,"waitForAudio",!0);u(this,"_visibilityChangeEvt");u(this,"_clonedPlayableAsset",!1);u(this,"_speed",1);u(this,"_guidsMap");u(this,"_isPlaying",!1);u(this,"_internalUpdateRoutine");u(this,"_isPaused",!1);u(this,"_isStopping",!1);u(this,"_time",0);u(this,"_duration",0);u(this,"_weight",1);u(this,"_animationTracks",[]);u(this,"_audioTracks",[]);u(this,"_signalTracks",[]);u(this,"_controlTracks",[]);u(this,"_customTracks",[]);u(this,"_allTracks",[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks]);u(this,"animationCallbackReceivers",[])}static registerCreateTrack(t,i){this.createTrackFunctions[t]=i}get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(t){typeof t=="number"&&!Number.isNaN(t)?this._time=t:(Ef||Er())&&console.error("INVALID TIMELINE.TIME VALUE",t,this.name)}get duration(){return this._duration}set duration(t){this._duration=t}get weight(){return this._weight}set weight(t){this._weight=t}get speed(){return this._speed}set speed(t){this._speed=t}awake(){var t,i,s;Ef&&console.log(this,(t=this.playableAsset)==null?void 0:t.tracks),this.rebuildGraph(),this.isValid()||console.warn("PlayableDirector is not valid",this.playableAsset,(i=this.playableAsset)==null?void 0:i.tracks,Array.isArray((s=this.playableAsset)==null?void 0:s.tracks),this)}onEnable(){var t,i,s;for(const r of this._audioTracks)(t=r.onEnable)==null||t.call(r);for(const r of this._customTracks)(i=r.onEnable)==null||i.call(r);for(const r of this._animationTracks)(s=r.onEnable)==null||s.call(r);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 t,i,s;this.stop();for(const r of this._audioTracks)(t=r.onDisable)==null||t.call(r);for(const r of this._customTracks)(i=r.onDisable)==null||i.call(r);for(const r of this._animationTracks)(s=r.onDisable)==null||s.call(r);this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){var t;for(const i of this._allTracks)for(const s of i)(t=s.onDestroy)==null||t.call(s)}rebuildGraph(){this.isValid()&&(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}async play(){if(!this.isValid())return;const t=this._isPaused==!0;if(this._isPaused=!1,!this._isPlaying){if(this._isPlaying=!0,t&&this.invokePauseChangedMethodsOnTracks(),this.waitForAudio){const i=[];for(const s of this._audioTracks){const r=s.loadAudio(this._time,1,0);r&&i.push(r)}if(i.length>0&&(await Promise.all(i),!this._isPlaying))return;for(;this._audioTracks.length>0&&this._isPlaying&&!Cn.userInteractionRegistered&&this.waitForAudio;)await Yo(200)}this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate(),Vn.LateUpdate)}}pause(){this.isValid()&&(this._isPlaying=!1,!this._isPaused&&(this._isPaused=!0,this.internalEvaluate(),this.invokePauseChangedMethodsOnTracks(),this.invokeStateChangedMethodsOnTracks()))}stop(){this._isStopping=!0;for(const s of this._audioTracks)s.stop();const t=this._isPaused==!0,i=this._isPlaying;this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.internalEvaluate(),t&&this.invokePauseChangedMethodsOnTracks()),this._isPlaying=!1,this._isPaused=!1,t&&!i&&this.invokePauseChangedMethodsOnTracks(),i&&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 t of this._allTracks)for(const i of t)yield i}get audioTracks(){return this._audioTracks}resolveGuids(t){this._guidsMap=t}invokePauseChangedMethodsOnTracks(){var t;for(const i of this.forEachTrack())(t=i.onPauseChanged)==null||t.call(i)}invokeStateChangedMethodsOnTracks(){var t;for(const i of this.forEachTrack())(t=i.onStateChanged)==null||t.call(i,this._isPlaying)}*internalUpdate(){for(;this._isPlaying&&this.activeAndEnabled;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime*this.speed,this.internalEvaluate()),yield}internalEvaluate(t=!1){if(!this.isValid())return;let i=this._time;switch(this.extrapolationMode){case 0:this._speed>0?i=Math.min(i,this._duration):this._speed<0&&(i=Math.max(i,0)),this._time=i;break;case 1:i%=this._duration,this._time=i;break;case 2:if(i>this._duration){this.stop();return}break}const s=this._time;for(const r of this.playableAsset.tracks)if(!r.muted)switch(r.type){case io.Activation:if(!t&&!this._isPlaying)continue;for(let o=0;o<r.outputs.length;o++){const a=r.outputs[o];if(typeof a=="object"){let c=!1;if(r.clips)for(const h of r.clips)h.start<=s&&s<=h.end&&(c=!0);const l=a;l.visible!==void 0&&l.visible!==c&&(l.visible=c,Ef&&console.warn(this.name,"set ActivationTrack-"+o,l.name,c,s))}}break}if(!this._isStopping)for(const r of this._animationTracks)r.evaluate(s);for(const r of this._audioTracks)r.evaluate(s);for(const r of this._signalTracks)r.evaluate(s);for(const r of this._controlTracks)r.evaluate(s);for(const r of this._customTracks)r.evaluate(s)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=dA(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;const t=this.findRoot(this.gameObject);for(const i of this.playableAsset.tracks){for(let s=i.outputs.length-1;s>=0;s--){let r=i.outputs[s];if(typeof r=="string"){this._guidsMap&&this._guidsMap[r]&&(r=this._guidsMap[r]);const o=le.findByGuid(r,t);o===null||typeof o!="object"?(i.outputs.splice(s,1),console.warn("Failed to resolve binding",r,i.name,i.type)):(Ef&&console.log("Resolved binding",r,"to",o),i.outputs[s]=o)}else if(r===null){if(i.outputs.splice(s,1),ex.createTrackFunctions[i.type])continue;i.type!==io.Audio&&i.type!==io.Control&&i.type!==io.Marker&&i.type!==io.Signal&&console.warn("Missing binding",r,i.name,i.type,this.name,this.playableAsset.name)}}if(i.type===io.Control&&i.clips)for(let s=0;s<i.clips.length;s++){const r=i.clips[s];let o=r.asset.sourceObject;if(typeof o=="string"){this._guidsMap&&this._guidsMap[o]&&(o=this._guidsMap[o]);const a=le.findByGuid(o,t);a===null||typeof a!="object"?console.warn("Failed to resolve sourceObject binding",o,i.name,r):(Ef&&console.log("Resolved binding",o,"to",a),r.asset.sourceObject=a)}}}}findRoot(t){return t.parent?this.findRoot(t.parent):t}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const t of this.playableAsset.tracks)if(t.muted!==!0){if(t.clips)for(const i of t.clips)i.end>this._duration&&(this._duration=i.end);if(t.markers)for(const i of t.markers)i.time>this._duration&&(this._duration=i.time+.001)}}}setupAndCreateTrackHandlers(){var i,s,r;if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let t=le.findObjectOfType(Ph,this.context);for(const o of this.playableAsset.tracks){const a=o.type,c=ex.createTrackFunctions[a];if(c!=null){const l=c(this,o);if(typeof l.evaluate=="function"){l.director=this,l.track=o,this._customTracks.push(l);continue}}if(o.type===io.Animation){if(!o.clips||o.clips.length<=0){Ef&&console.warn("Animation track has no clips",o);continue}for(let l=o.outputs.length-1;l>=0;l--){let h=o.outputs[l];if(h instanceof ge){const f=le.getOrAddComponent(h,Us);f&&(h=f)}const d=(i=h==null?void 0:h.gameObject)==null?void 0:i.animations;if(d){const f=new _w;f.trackOffset=o.trackOffset,f.director=this,f.track=o;for(let p=0;p<o.clips.length;p++){const m=o.clips[p],g=m.asset;if(!g){console.error(`Timeline ${this.name}: clip #${p} on track "${o.name}" has no animation data`);continue}const y=g.clip;let v=y;if((typeof v=="string"||typeof v=="number")&&(v=d.find(_=>_.name===y)),!v){console.warn("Could not find animationClip for model",m,o.name,this.name,(s=this.playableAsset)==null?void 0:s.name);continue}h instanceof Us&&h.runtimeAnimatorController&&(h.__internalDidAwakeAndStart||h.initializeRuntimeAnimatorController(),h.runtimeAnimatorController.mixer||h.runtimeAnimatorController.bind(h),f.mixer=h.runtimeAnimatorController.mixer),f.mixer||(f.mixer=new Ux(h.gameObject)),f.clips.push(v),f.mixer.uncacheAction(v),f.createHooks(m.asset,v);const A=f.mixer.clipAction(v);f.actions.push(A),f.models.push(m)}this._animationTracks.push(f)}}}else if(o.type===io.Audio){if(!o.clips||o.clips.length<=0)continue;const l=new hd;l.director=this,l.track=o,l.audioSource=o.outputs.find(h=>h instanceof Cn),this._audioTracks.push(l),t||(t=(r=this.context.mainCameraComponent)==null?void 0:r.gameObject.addNewComponent(Ph)),l.listener=t.listener;for(let h=0;h<o.clips.length;h++){const d=o.clips[h];l.addModel(d)}}else if(o.type===io.Marker){const l=new Gv;if(l.director=this,l.track=o,o.markers)for(const h of o.markers)switch(h.type){case UR.Signal:l.models.push(h),l.didTrigger.push(!1);break}if(l!==null&&l.models.length>0){const h=le.getComponent(this.gameObject,am);h&&(l.receivers.push(h),this._signalTracks.push(l))}}else if(o.type===io.Signal){const l=new Gv;if(l.director=this,l.track=o,o.markers)for(const h of o.markers)l.models.push(h),l.didTrigger.push(!1);for(const h of o.outputs)l.receivers.push(h);this._signalTracks.push(l)}else if(o.type===io.Control){const l=new bw;if(l.director=this,l.track=o,o.clips)for(const h of o.clips)l.models.push(h);l.resolveSourceObjects(this.context),this._controlTracks.push(l)}}}setAudioTracksAllowPlaying(t){for(const i of this._audioTracks)i.onAllowAudioChanged(t)}registerAnimationCallback(t){this.animationCallbackReceivers.push(t)}unregisterAnimationCallback(t){const i=this.animationCallbackReceivers.indexOf(t);i!==-1&&this.animationCallbackReceivers.splice(i,1)}};let Sl=ex;u(Sl,"createTrackFunctions",{});const H_=Symbol("objectIsAnimatedData");function r2(n,e,t){if(!n)return;if(n[H_]===void 0){if(!t)return;n[H_]=new Set}const i=n[H_];t?i.add(e):i.has(e)&&i.delete(e)}function tse(n){if(!n)return!1;const e=n[H_];return e!==void 0&&e.size>0}Bi.registerCallback(Kn.ContextCreated,n=>{const e=n.context.domElement.getAttribute("autoplay");if(e!==void 0&&(e===""||e==="true")&&n.files)for(const t of n.files)le.foreachComponent(t.file.scene,s=>{if(s.enabled!==!1){if(s instanceof Ao&&s.playAutomatically||s instanceof Us||s instanceof Sl&&s.playOnAwake===!0)return!0;if(s instanceof Ao)return s.playAutomatically=!0,!0;if(s instanceof Sl)return s.playOnAwake=!0,!0}},!0)!==!0&&ise(t.file)});function ise(n){if(!n||!n.animations)return;for(let t=0;t<n.animations.length;t++){const i=n.animations[t];if(!(!i.tracks||i.tracks.length<=0))for(const s in i.tracks){const r=i.tracks[s],o=r.__objectName??r.name.substring(0,r.name.indexOf("."));let a=n.scene.getObjectByName(o);if(!a&&(a=n.scene.getObjectByProperty("uuid",o),!a))continue;let c=e(a);c||(c=Xh(n.scene,new Ao));const l=c.animations=c.animations||[];i.name_animator=c.name,l.indexOf(i)<0&&l.push(i)}}function e(t){var s;if(!t)return;const i=(s=t.userData)==null?void 0:s.components;if(i&&i.length>0)for(let r=0;r<i.length;r++){const o=i[r];if(o instanceof Us||o instanceof Ao)return t}return e(t.parent)}}class nse{constructor(){u(this,"_context")}get context(){return this._context??Ot.Current}get isStateMachineBehaviour(){return!0}}class V_{constructor(e,t,i,s){u(this,"_name");u(this,"_nameHash");u(this,"_normalizedTime");u(this,"_length");u(this,"_speed");this._name=e.name,this._nameHash=e.hash,this._normalizedTime=t,this._length=i,this._speed=s}get name(){return this._name}get nameHash(){return this._nameHash}get normalizedTime(){return this._normalizedTime}get length(){return this._length}get speed(){return this._speed}}function FH(n,e){return{name:"",isLooping:!1,guid:(e==null?void 0:e.generateUUID())??es.generateUUID(),index:-1,clip:new Xr(n,1,[])}}var ph=(n=>(n[n.If=1]="If",n[n.IfNot=2]="IfNot",n[n.Greater=3]="Greater",n[n.Less=4]="Less",n[n.Equals=6]="Equals",n[n.NotEqual=7]="NotEqual",n))(ph||{}),NR=(n=>(n[n.Float=1]="Float",n[n.Int=3]="Int",n[n.Bool=4]="Bool",n[n.Trigger=9]="Trigger",n))(NR||{});const pr=se("debuganimatorcontroller"),N0=se("debugrootmotion");class go{constructor(e){u(this,"normalizedStartOffset",0);u(this,"_speed",1);u(this,"animator");u(this,"model");u(this,"_mixer");u(this,"_activeState");u(this,"_activeStates",[]);u(this,"rootMotionHandler");this.model=e,pr&&console.log(this)}static createFromClips(e,t={looping:!1,autoTransition:!0,transitionDuration:0}){const i=[];for(let o=0;o<e.length;o++){const a=e[o],c=[];if(t.autoTransition!==!1){const h=t.transitionDuration??0,d=h/a.duration;let f=o;(t.autoTransition===void 0||t.autoTransition===!0)&&(f=(o+1)%e.length),c.push({exitTime:1-d,offset:0,duration:h,hasExitTime:!0,destinationState:f,conditions:[]})}const l={name:a.name,hash:o,motion:{name:a.name,clip:a,isLooping:(t==null?void 0:t.looping)??!1},transitions:c,behaviours:[]};i.push(l)}const s={name:"AnimatorController",guid:new ms(Date.now()).generateUUID(),parameters:[],layers:[{name:"Base Layer",stateMachine:{defaultState:0,states:i}}]};return new go(s)}play(e,t=-1,i=Number.NEGATIVE_INFINITY,s=0){if(t<0)t=0;else if(t>=this.model.layers.length){console.warn("invalid layer");return}const o=this.model.layers[t].stateMachine;for(const a of o.states)if(a.name===e||a.hash===e){pr&&console.log("transition to ",a),this.transitionTo(a,s,i);return}console.warn("Could not find "+e+" to play")}reset(){this.setStartTransition()}setBool(e,t){var s,r;const i=typeof e=="string"?"name":"hash";return(r=(s=this.model)==null?void 0:s.parameters)==null?void 0:r.filter(o=>o[i]===e).forEach(o=>o.value=t)}getBool(e){var i,s,r;const t=typeof e=="string"?"name":"hash";return((r=(s=(i=this.model)==null?void 0:i.parameters)==null?void 0:s.find(o=>o[t]===e))==null?void 0:r.value)??!1}setFloat(e,t){var r,o;const i=typeof e=="string"?"name":"hash",s=(o=(r=this.model)==null?void 0:r.parameters)==null?void 0:o.filter(a=>a[i]===e);return s.forEach(a=>a.value=t),(s==null?void 0:s.length)>0}getFloat(e){var i,s,r;const t=typeof e=="string"?"name":"hash";return((r=(s=(i=this.model)==null?void 0:i.parameters)==null?void 0:s.find(o=>o[t]===e))==null?void 0:r.value)??0}setInteger(e,t){var s,r;const i=typeof e=="string"?"name":"hash";return(r=(s=this.model)==null?void 0:s.parameters)==null?void 0:r.filter(o=>o[i]===e).forEach(o=>o.value=t)}getInteger(e){var i,s,r;const t=typeof e=="string"?"name":"hash";return((r=(s=(i=this.model)==null?void 0:i.parameters)==null?void 0:s.find(o=>o[t]===e))==null?void 0:r.value)??0}setTrigger(e){var i,s;pr&&console.log("SET TRIGGER",e);const t=typeof e=="string"?"name":"hash";return(s=(i=this.model)==null?void 0:i.parameters)==null?void 0:s.filter(r=>r[t]===e).forEach(r=>r.value=!0)}resetTrigger(e){var i,s;const t=typeof e=="string"?"name":"hash";return(s=(i=this.model)==null?void 0:i.parameters)==null?void 0:s.filter(r=>r[t]===e).forEach(r=>r.value=!1)}getTrigger(e){var i,s,r;const t=typeof e=="string"?"name":"hash";return((r=(s=(i=this.model)==null?void 0:i.parameters)==null?void 0:s.find(o=>o[t]===e))==null?void 0:r.value)??!1}isInTransition(){return this._activeStates.length>1}setSpeed(e){this._speed=e}FindState(e){return this.findState(e)}findState(e){if(!e)return null;if(Array.isArray(this.model.layers)){for(const t of this.model.layers)for(const i of t.stateMachine.states)if(i.name===e||i.hash==e)return i}return null}get context(){var e;return(e=this.animator)==null?void 0:e.context}get mixer(){return this._mixer}bind(e){e?this.animator!==e&&(this.animator=e,this._mixer=new Ux(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;pr&&console.warn("AnimatorController clone()",this.model);const e=dA(this.model,(i,s,r)=>r==null?!0:!(r.type==="Object3D"||r.isObject3D===!0||vG(r)||r.tracks!==void 0||r instanceof go));return console.assert(e!==this.model),new go(e)}update(e){var i,s;if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates(e);const t=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&((i=this.rootMotionHandler)==null||i.onBeforeUpdate(e)),this._mixer.update(t),this.animator.applyRootMotion&&((s=this.rootMotionHandler)==null||s.onAfterUpdate(e))}get activeState(){return this._activeState}updateActiveStates(e){for(let t=0;t<this._activeStates.length;t++){const i=this._activeStates[t],s=i.motion;if(!s.action)this._activeStates.splice(t,1),t--;else{const r=s.action;r.weight=e,r.getEffectiveWeight()<=0&&!r.isRunning()&&(pr&&console.debug("REMOVE",i.name,r.getEffectiveWeight(),r.isRunning(),r.isScheduled()),this._activeStates.splice(t,1),t--)}}}setStartTransition(){for(const e of this.model.layers){const t=e.stateMachine;t.defaultState===void 0&&(pr&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",e),t.defaultState=0);const i=t.states[t.defaultState];this.transitionTo(i,0,this.normalizedStartOffset)}}evaluateTransitions(){var r;let e=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;e=!0}const t=this._activeState,i=t.motion.action;for(const o of t.transitions){if(!o.hasExitTime&&o.conditions.length<=0)continue;let a=!0;for(const c of o.conditions)if(!this.evaluateCondition(c)){a=!1;break}if(a)if(i){const c=t.motion.clip.duration,l=c<=0?1:Math.abs(i.time/c);let h=!1;if(o.hasExitTime?i.timeScale>0?h=l>=o.exitTime:i.timeScale<0&&(h=1-l>=o.exitTime):h=!0,h){for(const d of o.conditions){const f=this.model.parameters.find(p=>p.name===d.parameter);(f==null?void 0:f.type)===NR.Trigger&&f.value&&(f.value=!1)}i.clampWhenFinished=!0,pr&&console.log("transition to "+o.destinationState,o,l,o.exitTime,o.hasExitTime),this.transitionTo(o.destinationState,o.duration,o.offset);return}}else{this.transitionTo(o.destinationState,o.duration,o.offset);return}}if(i){let o=t.speed??1;t.speedParameter&&(o*=this.getFloat(t.speedParameter)),o!==void 0&&(i.timeScale=o*this._speed)}let s=!1;if(t.motion.isLooping&&i&&(i.time>=i.getClip().duration?(s=!0,i.reset(),i.time=0,i.play()):i.time<=0&&i.timeScale<0&&(s=!0,i.reset(),i.time=i.getClip().duration,i.play())),!s&&t&&!e&&i&&this.animator&&t.behaviours){const o=i==null?void 0:i.getClip().duration,a=i.time/o,c=new V_(this._activeState,a,o,this._speed);for(const l of t.behaviours)l.instance&&((r=l.instance.onStateUpdate)==null||r.call(l.instance,this.animator,c,0))}}getState(e,t){return typeof e=="number"&&(e==-1&&(e=this.model.layers[t].stateMachine.defaultState,e===void 0&&(pr&&console.warn("AnimatorController default state is undefined: ",this.model,"Layer: "+t),e=0)),e=this.model.layers[t].stateMachine.states[e]),e}transitionTo(e,t,i){var l,h,d,f,p,m,g,y;if(!this.animator)return;const s=0;if(e=this.getState(e,s),!(e!=null&&e.motion)||!e.motion.clip||!(e.motion.clip instanceof Xr))return;const r=this._activeState===e;if(r){const v=e.motion;if(!v.action_loopback&&v.clip){const A=this.rootMotionHandler?this.animator.gameObject.matrix.clone():null;this._mixer.uncacheAction(v.clip,this.animator.gameObject),A&&A.decompose(this.animator.gameObject.position,this.animator.gameObject.quaternion,this.animator.gameObject.scale),v.action_loopback=this.createAction(v.clip)}}if((l=this._activeState)!=null&&l.behaviours&&this._activeState.motion.action){const v=(h=this._activeState)==null?void 0:h.motion.clip.duration,A=this._activeState.motion.action.time/v,_=new V_(this._activeState,A,v,this._speed);for(const b of this._activeState.behaviours)(f=(d=b.instance)==null?void 0:d.onStateExit)==null||f.call(b.instance,this.animator,_,s)}const o=(p=this._activeState)==null?void 0:p.motion.action;o&&o.fadeOut(t),r&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=o);const a=this._activeState;this._activeState=e;const c=(m=e.motion)==null?void 0:m.action;if(c){if(i=Math.max(0,Math.min(1,i)),e.cycleOffsetParameter){let A=this.getFloat(e.cycleOffsetParameter);typeof A=="number"?(A<0&&(A+=1),i+=A,i%=1):pr&&console.warn("AnimatorController cycle offset parameter is not a number",e.cycleOffsetParameter)}else typeof e.cycleOffset=="number"&&(i+=e.cycleOffset,i%=1);c.isRunning()&&c.stop(),c.reset(),c.enabled=!0;const v=e.motion.clip.duration;if(c.time=r?0:i*v,c.timeScale<0&&(c.time=v-c.time),c.clampWhenFinished=!0,c.setLoop(lv,0),t>0?c.fadeIn(t):c.weight=1,c.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(c),this._activeStates.includes(e)||this._activeStates.push(e),this._activeState.behaviours){const A=new V_(e,i,v,this._speed);for(const _ of this._activeState.behaviours)(y=(g=_.instance)==null?void 0:g.onStateEnter)==null||y.call(_.instance,this.animator,A,s)}}else pr&&(e.__warned_no_motion||(e.__warned_no_motion=!0,console.warn("No action",e.motion,this)));pr&&console.log("TRANSITION FROM "+(a==null?void 0:a.name)+" TO "+e.name,t,o,c,c==null?void 0:c.getEffectiveTimeScale(),c==null?void 0:c.getEffectiveWeight(),c==null?void 0:c.isRunning(),c==null?void 0:c.isScheduled(),c==null?void 0:c.paused)}createAction(e){var i,s;if(this._mixer.existingAction(e)&&this._mixer.uncacheAction(e,(i=this.animator)==null?void 0:i.gameObject),(s=this.animator)!=null&&s.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new sse(this));const r=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,r,e)}else return this._mixer.clipAction(e)}evaluateCondition(e){const t=this.model.parameters.find(i=>i.name===e.parameter);if(!t)return!1;switch(e.mode){case ph.If:return t.value===!0;case ph.IfNot:return t.value===!1;case ph.Greater:return t.value>e.threshold;case ph.Less:return t.value<e.threshold;case ph.Equals:return t.value===e.threshold;case ph.NotEqual:return t.value!==e.threshold}return!1}createActions(e){var t,i,s,r;pr&&console.log("AnimatorController createActions",this.model);for(const o of this.model.layers){const a=o.stateMachine;for(let c=0;c<a.states.length;c++){const l=a.states[c];l.transitions||(l.transitions=[]);for(const h of l.transitions)h.conditions||(h.conditions=[]);if(l.motion||(l.motion=FH(l.name)),this.animator&&l.motion.clips){const h=(t=l.motion.clips)==null?void 0:t.find(d=>{var f,p;return d.node.name===((p=(f=this.animator)==null?void 0:f.gameObject)==null?void 0:p.name)});h?l.motion.clip=h.clip:(pr||Mt())&&console.warn('Could not find clip for animator "'+((s=(i=this.animator)==null?void 0:i.gameObject)==null?void 0:s.name)+'"',l.motion.clips.map(d=>d.node.name))}if(!l.motion.clip){const h=new Xr(void 0,void 0,[]);l.motion.clip=h}if((r=l.motion)!=null&&r.clip){const h=l.motion.clip;if(h instanceof Xr){const d=this.createAction(h);l.motion.action=d}else(pr||Mt())&&console.warn("No valid animationclip assigned",l)}if(l.behaviours&&Array.isArray(l.behaviours))for(const h of l.behaviours){if(!(h!=null&&h.typeName))continue;const d=$.get(h.typeName),f=new d;f.isStateMachineBehaviour&&(f._context=this.context??void 0,Tp(f,h.properties),h.instance=f),pr&&console.log("Created animator controller behaviour",l.name,h.typeName,h.properties,f)}}}}*enumerateActions(){if(this.model.layers)for(const e of this.model.layers){const t=e.stateMachine;for(let i=0;i<t.states.length;i++){const s=t.states[i];s!=null&&s.motion&&(s.motion.action&&(yield s.motion.action),s.motion.action_loopback&&(yield s.motion.action_loopback))}}}}class o2{constructor(e,t){u(this,"track");u(this,"createdInterpolant");u(this,"originalEvaluate");u(this,"customEvaluate");this.track=e;const i=e,s=i.createInterpolant.bind(e);i.createInterpolant=()=>(i.createInterpolant=s,this.createdInterpolant=s(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=r=>{if(!this.originalEvaluate)return;const o=this.originalEvaluate(r);return t(r,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 Jn=class{constructor(e,t,i,s,r){u(this,"_action");u(this,"root");u(this,"clip");u(this,"positionWrapper",null);u(this,"rotationWrapper",null);u(this,"context");u(this,"positionChange",new w);u(this,"rotationChange",new Ee);u(this,"_prevTime",0);if(this.context=e,this.root=t,this.clip=i,Jn.firstKeyframeRotation[this.cacheId]||(Jn.firstKeyframeRotation[this.cacheId]=new Ee),r){const o=r.values;Jn.firstKeyframeRotation[this.cacheId].set(o[0],o[1],o[2],o[3])}Jn.spaceRotation[this.cacheId]||(Jn.spaceRotation[this.cacheId]=new Ee),Jn.effectiveSpaceRotation[this.cacheId]||(Jn.effectiveSpaceRotation[this.cacheId]=new Ee),Jn.clipOffsetRotation[this.cacheId]=new Ee,r&&Jn.clipOffsetRotation[this.cacheId].set(r.values[0],r.values[1],r.values[2],r.values[3]).invert(),this.handlePosition(i,s),this.handleRotation(i,r)}set action(e){this._action=e}get action(){return this._action}get cacheId(){return this.root.uuid}onStart(e){if(e.getClip()!==this.clip)return;Jn.lastObjRotation[this.cacheId]||(Jn.lastObjRotation[this.cacheId]=this.root.quaternion.clone());const t=Jn.lastObjRotation[this.cacheId];if(Jn.spaceRotation[this.cacheId].copy(t),N0){const i=new ks().setFromQuaternion(t);console.log("START",this.clip.name,rt.toDegrees(i.y),this.root.position.z)}}getClipRotationOffset(){return Jn.clipOffsetRotation[this.cacheId]}handlePosition(e,t){if(t){const i=this.root;N0&&i.add(new Zo),Jn.lastObjPosition[this.cacheId]||(Jn.lastObjPosition[this.cacheId]=this.root.position.clone());const s=new w,r=new w;this.positionWrapper=new o2(t,(o,a)=>{const c=this.action.getEffectiveWeight();return N0&&i.position.length()>8&&i.position.set(0,i.position.y,0),o>this._prevTime&&(s.set(a[0],a[1],a[2]),s.sub(r),s.multiplyScalar(c),s.applyQuaternion(this.getClipRotationOffset()),s.applyQuaternion(i.quaternion),this.positionChange.copy(s)),r.fromArray(a),this._prevTime=o,a[0]=0,a[1]=0,a[2]=0,a})}}handleRotation(e,t){if(t){if(N0){const o=t.values,a=new ks().setFromQuaternion(new Ee(o[0],o[1],o[2],o[3]));console.log(e.name,t.name,"FIRST ROTATION IN TRACK",rt.toDegrees(a.y));const c=t.values.length-4,l=new Ee().set(o[c],o[c+1],o[c+2],o[c+3]),h=new ks().setFromQuaternion(l);console.log(e.name,t.name,"LAST ROTATION IN TRACK",rt.toDegrees(h.y))}let i=0;const s=new Ee,r=new Ee;this.rotationWrapper=new o2(t,(o,a)=>(o>i&&(r.set(a[0],a[1],a[2],a[3]),s.invert(),r.multiply(s),this.rotationChange.copy(r)),s.fromArray(a),i=o,a[0]=0,a[1]=0,a[2]=0,a[3]=1,a))}}onBeforeUpdate(e){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(e){return!this.action||(e*=this.action.getEffectiveWeight(),e<=0)?!1:(this.positionChange.multiplyScalar(e),this.rotationChange.slerp(Jn.identityQuaternion,1-e),!0)}};let Ya=Jn;u(Ya,"lastObjPosition",{}),u(Ya,"lastObjRotation",{}),u(Ya,"firstKeyframeRotation",{}),u(Ya,"spaceRotation",{}),u(Ya,"effectiveSpaceRotation",{}),u(Ya,"clipOffsetRotation",{}),u(Ya,"identityQuaternion",new Ee);class sse{constructor(e){u(this,"controller");u(this,"handler",[]);u(this,"root");u(this,"basePosition",new w);u(this,"baseQuaternion",new Ee);u(this,"baseRotation",new ks);u(this,"summedPosition",new w);u(this,"summedRotation",new Ee);this.controller=e}createClip(e,t,i){this.root=t,t&&"name"in t&&t.name;const s=this.findRootTrack(i,".position"),r=this.findRootTrack(i,".quaternion"),o=new Ya(this.controller.context,t,i,s,r);this.handler.push(o);const a=e.clipAction(i);return o.action=a,a}onStart(e){for(const t of this.handler)t.onStart(e)}onBeforeUpdate(e){this.basePosition.copy(this.root.position),this.baseQuaternion.copy(this.root.quaternion);for(const t of this.handler)t.onBeforeUpdate(e)}onAfterUpdate(e){if(!(e<=0)){this.root.position.copy(this.basePosition),this.root.quaternion.copy(this.baseQuaternion),this.summedPosition.set(0,0,0),this.summedRotation.set(0,0,0,1);for(const t of this.handler)t.onAfterUpdate(e)&&(this.summedPosition.add(t.positionChange),this.summedRotation.multiply(t.rotationChange));this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation)}}findRootTrack(e,t){const i=e.tracks;if(!i)return null;for(const s of i)if(s.name.endsWith(t))return s;return null}}class rse extends Dl{onSerialize(e,t){}onDeserialize(e,t){if(t.type===go&&(e==null?void 0:e.__type)==="AnimatorController")return new go(e)}}new rse(go);var ose=Object.defineProperty,ase=Object.getOwnPropertyDescriptor,xw=(n,e,t,i)=>{for(var s=i>1?void 0:i?ase(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&ose(e,t,s),s};const Oo=se("debuganimator");class Us extends Ie{constructor(){super(...arguments);u(this,"applyRootMotion",!1);u(this,"hasRootMotion",!1);u(this,"keepAnimatorControllerStateOnDisable",!1);u(this,"_parametersAreDirty",!1);u(this,"_isDirty",!1);u(this,"speed",1);u(this,"normalizedStartOffset",0);u(this,"_animatorController",null);u(this,"_initializeWithRuntimeAnimatorController")}set runtimeAnimatorController(t){var i;this._animatorController&&this._animatorController.model===t||(t?t instanceof go?(t.animator&&t.animator!==this&&(console.warn("AnimatorController can not be bound to multiple animators",(i=t.model)==null?void 0:i.name),t.model||console.error("AnimatorController has no model"),t=new go(t.model)),this._animatorController=t,this._animatorController.bind(this)):(Oo&&console.log("Assign animator controller",t,this),this._animatorController=new go(t),this.__didAwake&&this._animatorController.bind(this)):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}get parametersAreDirty(){return this._parametersAreDirty}get isDirty(){return this._isDirty}Play(t,i=-1,s=Number.NEGATIVE_INFINITY,r=0){this.play(t,i,s,r)}play(t,i=-1,s=Number.NEGATIVE_INFINITY,r=0){var o;(o=this.runtimeAnimatorController)==null||o.play(t,i,s,r),this._isDirty=!0}Reset(){this.reset()}reset(){var t;(t=this._animatorController)==null||t.reset(),this._isDirty=!0}SetBool(t,i){this.setBool(t,i)}setBool(t,i){var s,r;Oo&&console.log("setBool",t,i),((s=this.runtimeAnimatorController)==null?void 0:s.getBool(t))!==i&&(this._parametersAreDirty=!0),(r=this.runtimeAnimatorController)==null||r.setBool(t,i)}GetBool(t){return this.getBool(t)}getBool(t){var s;const i=((s=this.runtimeAnimatorController)==null?void 0:s.getBool(t))??!1;return Oo&&console.log("getBool",t,i),i}toggleBool(t){this.setBool(t,!this.getBool(t))}SetFloat(t,i){this.setFloat(t,i)}setFloat(t,i){var s,r;((s=this.runtimeAnimatorController)==null?void 0:s.getFloat(t))!==i&&(this._parametersAreDirty=!0),Oo&&console.log("setFloat",t,i),(r=this.runtimeAnimatorController)==null||r.setFloat(t,i)}GetFloat(t){return this.getFloat(t)}getFloat(t){var s;const i=((s=this.runtimeAnimatorController)==null?void 0:s.getFloat(t))??-1;return Oo&&console.log("getFloat",t,i),i}SetInteger(t,i){this.setInteger(t,i)}setInteger(t,i){var s,r;((s=this.runtimeAnimatorController)==null?void 0:s.getInteger(t))!==i&&(this._parametersAreDirty=!0),Oo&&console.log("setInteger",t,i),(r=this.runtimeAnimatorController)==null||r.setInteger(t,i)}GetInteger(t){return this.getInteger(t)}getInteger(t){var s;const i=((s=this.runtimeAnimatorController)==null?void 0:s.getInteger(t))??-1;return Oo&&console.log("getInteger",t,i),i}SetTrigger(t){this.setTrigger(t)}setTrigger(t){var i;this._parametersAreDirty=!0,Oo&&console.log("setTrigger",t),(i=this.runtimeAnimatorController)==null||i.setTrigger(t)}ResetTrigger(t){this.resetTrigger(t)}resetTrigger(t){var i;this._parametersAreDirty=!0,Oo&&console.log("resetTrigger",t),(i=this.runtimeAnimatorController)==null||i.resetTrigger(t)}GetTrigger(t){this.getTrigger(t)}getTrigger(t){var s;const i=(s=this.runtimeAnimatorController)==null?void 0:s.getTrigger(t);return Oo&&console.log("getTrigger",t,i),i}IsInTransition(){return this.isInTransition()}isInTransition(){var t;return((t=this.runtimeAnimatorController)==null?void 0:t.isInTransition())??!1}SetSpeed(t){return this.setSpeed(t)}setSpeed(t){var i;t!==this.speed&&(Oo&&console.log("setSpeed",t),this.speed=t,(i=this._animatorController)==null||i.setSpeed(t))}set minMaxSpeed(t){this.speed=rt.lerp(t.x,t.y,Math.random())}set minMaxOffsetNormalized(t){this.normalizedStartOffset=rt.lerp(t.x,t.y,Math.random()),this.runtimeAnimatorController&&(this.runtimeAnimatorController.normalizedStartOffset=this.normalizedStartOffset)}awake(){Oo&&console.log("ANIMATOR",this.name,this),this.gameObject&&this.initializeRuntimeAnimatorController()}initializeRuntimeAnimatorController(t=!1){const i=t||this.runtimeAnimatorController!==this._initializeWithRuntimeAnimatorController;if(this.runtimeAnimatorController&&i){const s=this.runtimeAnimatorController.clone();this._initializeWithRuntimeAnimatorController=s,s?(console.assert(this.runtimeAnimatorController!==s),this.runtimeAnimatorController=s,console.assert(this.runtimeAnimatorController===s),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 t;this.keepAnimatorControllerStateOnDisable||(t=this._animatorController)==null||t.reset()}onBeforeRender(){this._isDirty=!1,this._parametersAreDirty=!1,!tse(this.gameObject)&&this._animatorController&&this._animatorController.update(1)}}xw([x()],Us.prototype,"applyRootMotion",2);xw([x()],Us.prototype,"hasRootMotion",2);xw([x()],Us.prototype,"keepAnimatorControllerStateOnDisable",2);xw([x()],Us.prototype,"runtimeAnimatorController",1);const vp=se("debugusdzanimation"),LM=se("debugusdzanimationserialization");class ww{constructor(e,t,i){u(this,"_start");u(this,"ext");u(this,"root");u(this,"clip");this.ext=e,this.root=t,this.clip=i}get start(){return this._start===void 0&&(this._start=this.ext.getStartTime01(this.root,this.clip)),this._start}get duration(){return this.clip.duration}}class Wo{constructor(e,t,i){u(this,"clip");u(this,"pos");u(this,"rot");u(this,"scale");u(this,"root");u(this,"target");u(this,"duration",0);u(this,"useRootMotion",!1);this.root=e,this.target=t,this.clip=i,i?this.duration=i.duration:this.duration=1/this.frameRate;const s=le.getComponent(e,Us);s&&(this.useRootMotion=s.applyRootMotion)}get frameRate(){return 60}addTrack(e){if(!this.clip){console.error("This is a rest clip but you're trying to add tracks to it โ€“ this is likely a bug");return}e.name.endsWith("position")&&(this.pos=e),e.name.endsWith("quaternion")&&(this.rot=e),e.name.endsWith("scale")&&(this.scale=e)}getFrames(){var e,t,i,s,r,o;return this.clip?Math.max(((t=(e=this.pos)==null?void 0:e.times)==null?void 0:t.length)??0,((s=(i=this.rot)==null?void 0:i.times)==null?void 0:s.length)??0,((o=(r=this.scale)==null?void 0:r.times)==null?void 0:o.length)??0):2}getDuration(){return this.duration}getSortedTimesArray(e=!0,t=!0,i=!0){var c,l,h;if(!this.clip)return[0,this.duration];const s=(c=this.pos)==null?void 0:c.times,r=(l=this.rot)==null?void 0:l.times,o=(h=this.scale)==null?void 0:h.times,a=[];if(e&&s)for(const d of s)a.push(d);if(t&&r)for(const d of r)a.push(d);if(i&&o)for(const d of o)a.push(d);return a.includes(0)||a.push(0),a.sort((d,f)=>d-f),[...new Set(a)]}*getValues(e,t=!0,i=!0,s=!0){var f,p,m;const r=new w,o=new Ee,a=new w(1,1,1),c=this.target,l=t?(f=this.pos)==null?void 0:f.createInterpolant():void 0,h=i?(p=this.rot)==null?void 0:p.createInterpolant():void 0,d=s?(m=this.scale)==null?void 0:m.createInterpolant():void 0;l||r.set(c.position.x,c.position.y,c.position.z),h||o.set(c.quaternion.x,c.quaternion.y,c.quaternion.z,c.quaternion.w),d||a.set(c.scale.x,c.scale.y,c.scale.z);for(let g=0;g<e.length;g++){const y=e[g];if(l){const v=l.evaluate(y);r.set(v[0],v[1],v[2])}if(h){const v=h.evaluate(y);o.set(v[0],v[1],v[2],v[3])}if(d){const v=d.evaluate(y);a.set(v[0],v[1],v[2])}if(this.useRootMotion&&c===this.root){const v=new Se;v.compose(r,o,a),v.multiply(c.matrix),v.decompose(r,o,a)}yield{time:y,translation:r,rotation:o,scale:a,index:g}}}}u(Wo,"animationDurationPadding",1);class GA{constructor(e){u(this,"dict",new Map);u(this,"rootTargetMap",new Map);u(this,"rootAndClipToRegisteredAnimationMap",new Map);u(this,"rootToRegisteredClipCount",new Map);u(this,"serializers",[]);u(this,"injectRestPoses",!1);u(this,"injectImplicitBehaviours",!1);this.injectRestPoses=e,this.injectImplicitBehaviours=e}get extensionName(){return"animation"}getClipCount(e){let t=this.rootToRegisteredClipCount.get(e);return this.injectRestPoses&&(t=t?t-1:0),t??0}getStartTime01(e,t){const i=this.rootTargetMap.get(e);if(!i)return 0;const s=this.dict.get(i[0]);if(!s)return console.error("Trying to get start time for root that has no animation data",e,t,...this.dict),0;let r=0;for(let o=0;o<s.length&&s[o].clip!==t;o++)r+=s[o].getDuration()+Wo.animationDurationPadding;return r}registerAnimation(e,t){if(!t||!e)return null;this.rootTargetMap.has(e)||this.rootTargetMap.set(e,[]);const i=e.uuid+t.uuid;if(this.rootAndClipToRegisteredAnimationMap.has(i))return this.rootAndClipToRegisteredAnimationMap.get(i);vp&&console.log("registerAnimation",e,t);const s=this.injectRestPoses?1:0,r=this.rootToRegisteredClipCount.get(e)??s,o=this.rootTargetMap.get(e),a=new Set(o);if(t.tracks)for(const l of t.tracks){const h=Yt.parseTrackName(l.name),d=Yt.findNode(e,h.nodeName);if(!d){console.warn("no object found for track",l.name,"using "+e.name+" instead");continue}this.dict.has(d)||this.dict.set(d,[]);const f=this.dict.get(d);if(!f)continue;if(a.delete(d),this.injectRestPoses&&!f[0]){const m=new Wo(null,d,void 0);f[0]=m}let p=f[r];p||(p=new Wo(e,d,t),f[r]=p),p.addTrack(l),o!=null&&o.includes(d)||o==null||o.push(d)}for(const l of a){const h=this.dict.get(l);if(!h)continue;if(this.injectRestPoses&&!h[0]){const f=new Wo(null,l,void 0);h[0]=f}let d=h[r];d||(vp&&console.log("Adding padding clip for ",l,t),d=new Wo(e,l,t),h[r]=d)}const c=new ww(this,e,t);return this.rootAndClipToRegisteredAnimationMap.set(i,c),this.rootToRegisteredClipCount.set(e,r+1),c}onAfterHierarchy(e){vp&&console.log("Animation clips per animation target node",this.dict)}onAfterBuildDocument(e){var t,i;for(const s of this.serializers){const r=(t=s.model)==null?void 0:t.parent,o=(r==null?void 0:r.isDynamic)===!0;LM&&console.log(o,(i=s.model)==null?void 0:i.parent),o&&s.registerCallback(r)}}onExportObject(e,t,i){le.foreachComponent(e,r=>{const o=r;typeof o.createAnimation=="function"&&o.createAnimation(this,t,i)},!1);const s=new cse(e,this.dict);this.serializers.push(s),s.registerCallback(t)}}class cse{constructor(e,t){u(this,"object");u(this,"dict");u(this,"model");u(this,"callback");this.object=e,this.dict=t}registerCallback(e){this.model&&this.callback&&this.model.removeEventListener("serialize",this.callback),this.callback||(this.callback=this.onSerialize.bind(this)),LM&&console.log("REPARENT",e),this.model=e,this.model.addEventListener("serialize",this.callback)}skinnedMeshExport(e,t){const i=this.model,s=this.dict;if(i&&i.skinnedMesh){let r=function(T){const I=[];for(const[S,M]of T){let D=`${S} : [`;const G=[];for(const Q of M)G.push(`(${hs(Q.x)}, ${hs(Q.y)}, ${hs(Q.z)})`);D=D.concat(G.join(", ")),D=D.concat("],"),I.push(D)}return I},o=function(T){const I=[];for(const[S,M]of T){let D=`${S} : [`;const G=[];for(const Q of M)G.push(`(${hs(Q.w)}, ${hs(Q.x)}, ${hs(Q.y)}, ${hs(Q.z)})`);D=D.concat(G.join(", ")),D=D.concat("],"),I.push(D)}return I},a=function(T){let I=!0,S;for(const[D,G]of T)if(S===void 0&&(S=G.length),S!==G.length){I=!1;break}vp&&console.log("Bone count: ",T.size,"TransformData entries per bone: ",S),console.assert(I,"All bones should have the same number of TransformData entries",T);const M=[];for(const[D,G]of T){const Q=new Array;let L=0;for(let H=0;H<G.length;H++)Q.push(L),L+=G[H].getDuration()+Wo.animationDurationPadding;for(let H=0;H<G.length;H++){const O=G[H],U=Q[H];M.length<=H&&M.push({pos:[],rot:[],scale:[],timeOffset:U});const V=M[H];V.pos.push(...O.getSortedTimesArray(!0,!1,!1)),V.rot.push(...O.getSortedTimesArray(!1,!0,!1)),V.scale.push(...O.getSortedTimesArray(!1,!1,!0))}}for(const D of M)D.pos.sort((G,Q)=>G-Q),D.rot.sort((G,Q)=>G-Q),D.scale.sort((G,Q)=>G-Q),D.pos=[...new Set(D.pos)],D.rot=[...new Set(D.rot)],D.scale=[...new Set(D.scale)];return M},c=function(T,I,S){const M=new Map,D=new Map,G=new Map,Q=I.length;for(const L of S){const H=T.get(L);let O;H?console.assert(H.length===Q,"We should have the same number of TransformData entries for each bone",H,I):O=new Wo(null,L,void 0);for(let U=0;U<Q;U++){const V=H?H[U]:O,J=I[U];for(const{time:K,translation:oe}of V.getValues(J.pos,!0,!1,!1)){const be=(K+J.timeOffset)*60;M.has(be)||M.set(be,new Array),M.get(be).push(oe.clone())}for(const{time:K,rotation:oe}of V.getValues(J.rot,!1,!0,!1)){const be=(K+J.timeOffset)*60;D.has(be)||D.set(be,new Array),D.get(be).push(oe.clone())}for(const{time:K,scale:oe}of V.getValues(J.scale,!1,!1,!0)){const be=(K+J.timeOffset)*60;G.has(be)||G.set(be,new Array),G.get(be).push(oe.clone())}}}return{position:M.size==0?void 0:M,quaternion:D.size==0?void 0:D,scale:G.size==0?void 0:G}},l=function(T){const I=[];for(const S of T)I.push(`(${hs(S.x)}, ${hs(S.y)}, ${hs(S.z)})`);return I.join(", ")},h=function(T){const I=[];for(const S of T)I.push(`(${hs(S.w)}, ${hs(S.x)}, ${hs(S.y)}, ${hs(S.z)})`);return I.join(", ")},d=function(T){const I=new Map;if(vp){const S=new Array;for(const[M,D]of s)S.push(M.uuid+": "+D.length+" "+D.map(G=>{var Q;return(Q=G.clip)==null?void 0:Q.uuid.substring(0,6)}).join(" "));console.log(`getPerBoneTransformData
5409
5411
  `+S.join(`
5410
- `))}for(const S of T){const M=s.get(S);M&&I.set(S,M)}return I},f=function(T){const I=d(T),S=a(I);return c(I,S,T)};const p=i.skinnedMesh.skeleton,m=new Array;for(const T in p.bones){const I=p.bones[T],S=p.boneInverses[T];m.push({bone:I,inverse:S})}for(const T of CH(p.bones))m.push({bone:T,inverse:T.matrixWorld.clone().invert()});const g=m[0].bone.parent;g||console.error("No bone parent found for skinned mesh during USDZ export",i.skinnedMesh),m.sort((T,I)=>gp(T.bone,g)>gp(I.bone,g)?1:-1);const y=[],v=[],A=[],_=[];for(const{bone:T}of m)y.push(T.matrix.clone()),v.push(T.position),A.push(T.quaternion),_.push(T.scale);const b=m.map(T=>'"'+gp(T.bone,g)+'"').join(", "),C=m.map(T=>Kf(T.inverse.clone().invert())).join(", ");e.beginBlock('def Skeleton "Rig"'),e.appendLine(`uniform matrix4d[] bindTransforms = [${C}]`),e.appendLine(`uniform token[] joints = [${b}]`),e.appendLine('uniform token purpose = "guide"'),e.appendLine(`uniform matrix4d[] restTransforms = [${y.map(T=>Kf(T)).join(", ")}]`),e.appendLine(`matrix4d xformOp:transform = ${Kf(new Se)}`),e.appendLine('uniform token[] xformOpOrder = ["xformOp:transform"]');const E=f(m.map(T=>T.bone));if(e.beginBlock('def SkelAnimation "_anim"'),e.appendLine(`uniform token[] joints = [${b}]`),e.appendLine(`quatf[] rotations = [${h(A)}]`),E&&E.quaternion){e.beginBlock("quatf[] rotations.timeSamples = {","");const T=o(E.quaternion);for(const I of T)e.appendLine(I);e.closeBlock()}if(e.appendLine(`half3[] scales = [${l(_)}]`),E&&E.scale){e.beginBlock("half3[] scales.timeSamples = {","");const T=r(E.scale);for(const I of T)e.appendLine(I);e.closeBlock()}if(e.appendLine(`float3[] translations = [${l(v)}]`),E&&E.position){e.beginBlock("float3[] translations.timeSamples = {","");const T=r(E.position);for(const I of T)e.appendLine(I);e.closeBlock()}e.closeBlock(),e.closeBlock()}}onSerialize(e,t){var c;if(!this.model)return;this.skinnedMeshExport(e,t);const i=this.object,s=this.dict.get(i);if(!s||i.isSkinnedMesh)return;LM&&console.log("SERIALIZE",this.model.name,this.object.type,s);const r=new Se;e.appendLine("matrix4d xformOp:transform.timeSamples = {"),e.indent++;const o=new Array;let a=0;for(let l=0;l<s.length;l++)o.push(a),a+=s[l].getDuration()+Wo.animationDurationPadding;for(let l=0;l<s.length;l++){const h=s[l];if(!h)continue;const d=o[l];{const f=h.getSortedTimesArray();if(!f||f.length===0){console.error("got an animated object but no time values?",i,h);continue}if(vp){const p=((c=h.clip)==null?void 0:c.name)??"rest",m=h.getDuration();console.log("Write .timeSamples:",p,d,m,s),e.appendLine("# "+p+": start="+(d*h.frameRate).toFixed(3)+", length="+(m*h.frameRate).toFixed(3)+", frames="+h.getFrames())}for(const{time:p,translation:m,rotation:g,scale:y}of h.getValues(f)){r.compose(m,g,y);const v=`${(d+p)*h.frameRate}: ${Kf(r)},`;e.appendLine(v)}}}e.indent--,e.appendLine("}")}}var lse=Object.defineProperty,hse=Object.getOwnPropertyDescriptor,UH=(n,e,t,i)=>{for(var s=i>1?void 0:i?hse(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&lse(e,t,s),s};const a2=se("debugpost");class kt{constructor(e){u(this,"_active",!0);u(this,"_value");u(this,"_valueRaw");u(this,"_defaultValue");u(this,"valueProcessor");u(this,"onValueChanged");this._value=e,this._defaultValue=e,this._valueRaw=e}get overrideState(){return this._active}set overrideState(e){if(this._active===e)return;this._active=e;const t=e?this._valueRaw:this._defaultValue;this.processValue(t,!0)}get value(){return this._valueRaw}set value(e){this.processValue(e,!1)}set defaultValue(e){this._defaultValue=e}__init(){this.processValue(this._valueRaw,!0)}processValue(e,t){if(e==null||!t&&this.testIfValueChanged(e)===!1)return;const i=this._value;a2&&console.log("VolumeParameter: value changed from",i,"to",e),!this._active&&this._defaultValue!==void 0?(this._value=this._defaultValue,e=this._defaultValue,this._valueRaw=e):(this._valueRaw=e,this._active&&this.valueProcessor&&(e=this.valueProcessor(e)),this._value=e),this.onValueChanged?this.onValueChanged(e,i,this):a2&&console.log("VolumeParameter: onValueChanged not set")}testIfValueChanged(e){return this._valueRaw!==e}}UH([x()],kt.prototype,"overrideState",1);UH([x()],kt.prototype,"value",1);var use=Object.defineProperty,dse=Object.getOwnPropertyDescriptor,fse=(n,e,t,i)=>{for(var s=i>1?void 0:i?dse(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&use(e,t,s),s};const pse=se("debugpost");class cr extends Ie{constructor(t=void 0){super();u(this,"active",!0);u(this,"_result");u(this,"_didCreateVolumeParameters",!1);if(t){this.ensureVolumeParameters();for(const i of Object.keys(t)){const s=t[i],r=this[i];r instanceof kt&&(r.value=s)}}}onEnable(){this.__internalDidAwakeAndStart&&(this.active=!0)}onDisable(){this.active=!1}init(){}apply(){var t;return this.ensureVolumeParameters(),this._result||(this._result=(t=this.onCreateEffect)==null?void 0:t.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){pse&&console.warn("DISPOSE",this),this._result&&(Array.isArray(this._result)?this._result.forEach(t=>t.dispose()):this._result.dispose()),this._result=void 0}initParameters(){const t=Object.keys(this);for(const i of t){const s=this[i];s instanceof kt&&s.__init()}}onAfterDeserialize(t,i){if(typeof t=="object"){const s=this.$serializedTypes;if(s){for(const r of Object.keys(s))if(s[r]===kt){const a=t[r];if(a!==void 0){const c=this[r];c.value=a}}}}}onEditorModification(t){const i=t.propertyName;if(this[i]instanceof kt){const s=t.value;return this[i].value=s,!0}}ensureVolumeParameters(){if(this._didCreateVolumeParameters)return;this._didCreateVolumeParameters=!0;const t=this.$serializedTypes;if(t)for(const i of Object.keys(t))t[i]===kt&&(this[i]||(this[i]=new kt))}}fse([x()],cr.prototype,"active",2);var mse=Object.defineProperty,gse=Object.getOwnPropertyDescriptor,vse=(n,e,t,i)=>{for(var s=i>1?void 0:i?gse(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&mse(e,t,s),s};const Ase=se("debugpost"),FM={};function oa(n,e){FM[n]=e}function yse(n){return n.__type in FM?FM[n.__type]:(Ase&&n.__type&&console.warn("Unknown postprocessing type",n.__type,n),cr)}class HA{constructor(){u(this,"components",[])}init(){var e;(e=this.components)==null||e.forEach(t=>t.init())}}vse([nm([n=>yse(n),cr])],HA.prototype,"components",2);var _se=Object.defineProperty,bse=Object.getOwnPropertyDescriptor,xse=(n,e,t,i)=>{for(var s=i>1?void 0:i?bse(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&_se(e,t,s),s};class VA extends cr{constructor(){super(...arguments);u(this,"preset")}get typeName(){return"Antialiasing"}onCreateEffect(){const t=new yY({preset:Lf.HIGH,edgeDetectionMode:gI.DEPTH});return this.preset.onValueChanged=i=>{t.applyPreset(i)},t}}xse([x(kt)],VA.prototype,"preset",2);oa("Antialiasing",VA);class Sw{constructor(){u(this,"files",[])}get extensionName(){return"Audio"}onExportObject(e,t,i){const s=le.getComponents(e,Cn);if(s.length)for(const r of s){if(!r.clip||typeof r.clip!="string"||!r.playOnAwake)continue;const o=r.clip.split("/").pop();this.files.includes(r.clip)||this.files.push(r.clip),t.addEventListener("serialize",(a,c)=>{a.appendLine(),a.beginBlock(`def SpatialAudio "${t.name}"`),a.appendLine(`uniform asset filePath = @audio/${o}@`),a.appendLine(`uniform token auralMode = "${r.spatialBlend>0?"spatial":"nonSpatial"}"`),a.appendLine(`uniform token playbackMode = "${r.loop?"loopFromStage":"onceFromStart"}"`),a.appendLine(`uniform float gain = ${r.volume}`),a.closeBlock()})}}async onAfterSerialize(e){for(const t of this.files){const i=t.split("/").pop(),o=await(await(await fetch(t)).blob()).arrayBuffer(),a=new Uint8Array(o);e.files["audio/"+i]=a}}}const Zu=se("debugautosync"),ZC=Symbol("syncerId");class wse{constructor(){u(this,"_syncers",{})}getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];const t=new Sse(e);return t[ZC]=e.guid,this._syncers[t[ZC]]=t,t}removeSyncer(e){delete this._syncers[e[ZC]]}}const zR=new wse;class Sse{constructor(e){u(this,"comp");u(this,"hasChanges",!1);u(this,"changedProperties",{});u(this,"data",{});u(this,"_boundEvent");u(this,"_handleReceivingMethod");u(this,"_isReceiving",!1);u(this,"_isInit",!1);this.comp=e}get networkingKey(){return this.comp.guid}init(e){if(this._isInit)return;this._isInit=!0,this.comp=e,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 t=this.comp.context.connection.tryGetState(this.comp.guid);t&&this.onHandleReceiving(t)}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(e,t){this._isReceiving||(Zu&&console.log("Property changed: "+e,t),this.hasChanges=!0,this.changedProperties[e]=t)}onHandleSending(){if(!this.hasChanges)return;this.hasChanges=!1;const e=this.comp.context.connection;if(!e||!e.isConnected){for(const t in this.changedProperties)delete this.changedProperties[t];return}for(const t in this.data)delete this.data[t];this.data.guid=this.comp.guid;for(const t in this.changedProperties){const i=this.changedProperties[t];delete this.changedProperties[t],this.data[t]=i}e.send(this.networkingKey,this.data)}onHandleReceiving(e){if(Zu&&console.log("RECEIVE",this.comp.name,this.comp.guid,e),!this._isInit||!this.comp)return;const t=e.guid;if(!(t&&t!==this.comp.guid)){Zu&&console.log("RECEIVED",this.comp.name,this.comp.guid,e);try{this._isReceiving=!0;for(const i in e){if(i==="guid")continue;const s=e[i];this.comp[i]=s,Zu&&console.log("SET",i,s)}}catch(i){console.error(i)}finally{this._isReceiving=!1}}}}function Cse(n,e){let t=e!==n;return!t&&n&&e&&(Array.isArray(n)&&Array.isArray(e)||typeof n=="object"&&typeof e=="object")&&(t=!0),t}const Xg=Symbol("AutoSyncHandler");function Ese(n){if(n[Xg])return n[Xg];const e=zR.getOrCreateSyncer(n);return e==null||e.init(n),n[Xg]=e,e}function Mse(n){const e=n[Xg];e&&(zR.removeSyncer(e),e.destroy(),delete n[Xg])}const GR=function(n){return function(e,t){var h;let i="";typeof t=="string"?i=t:i=t.name;let s=null,r;typeof n=="string"?r=e[n]:typeof n=="function"&&(r=n);const o=e,a=o.__internalAwake;if(typeof a!="function"){(Zu||Mt())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+((h=e==null?void 0:e.constructor)==null?void 0:h.name)+'" is not supported',e);return}Zu&&console.log(i);const c=Symbol(i);o.__internalAwake=function(){if(this[c]!==void 0)return;this[c]=this[i],s=zR.getOrCreateSyncer(this);const d=Object.getOwnPropertyDescriptor(this,i);if((d==null?void 0:d.set)===void 0){let f=!1;Object.defineProperty(this,i,{set:function(p){var g;const m=this[c];if(this[c]=p,f){Mt()&&console.warn("Recursive call detected",i);return}f=!0;try{const y=Cse(p,m);Zu&&console.log("SyncField assignment",i,"changed?",y,p),y&&(r==null?void 0:r.call(this,p,m))!==!1&&((g=Ese(this))==null||g.notifyChanged(i,p))}finally{f=!1}},get:function(){return this[c]},configurable:!0,enumerable:!0})}s==null||s.init(this),a.call(this)};const l=o.__internalDestroy;o.__internalDestroy=function(){Mse(this),l.call(this)}}};var Tse=Object.defineProperty,Ise=Object.getOwnPropertyDescriptor,Cw=(n,e,t,i)=>{for(var s=i>1?void 0:i?Ise(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Tse(e,t,s),s};const zo=se("debugplayersync");class cm extends Ie{constructor(){super(...arguments);u(this,"autoSync",!0);u(this,"asset");u(this,"onPlayerSpawned");u(this,"_localInstance");u(this,"onJoinedRoom",()=>{zo&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()})}awake(){this.watchTabVisible(),this.onPlayerSpawned||(this.onPlayerSpawned=new gs)}onEnable(){this.context.connection.beginListen(mi.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(mi.JoinedRoom,this.onJoinedRoom),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(mi.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(mi.JoinedRoom,this.onJoinedRoom)}async getInstance(){var i,s,r,o,a,c;if(this._localInstance)return this._localInstance;if(zo&&console.log("PlayerSync.createInstance",(i=this.asset)==null?void 0:i.uri),!((s=this.asset)!=null&&s.asset)&&!((r=this.asset)!=null&&r.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 t=await this._localInstance;if(t){const l=le.getComponent(t,qo);l?(l.owner=this.context.connection.connectionId,(a=this.onPlayerSpawned)==null||a.invoke(t)):(this._localInstance=void 0,console.error("<strong>Failed finding PlayerState on "+((c=this.asset)==null?void 0:c.uri)+"</strong>: please make sure the asset has a PlayerState component!"),le.destroySynced(t))}else this._localInstance=void 0,console.warn("PlayerSync: failed instantiating asset!");return this._localInstance}destroyInstance(){var t;(t=this._localInstance)==null||t.then(i=>(zo&&console.log("PlayerSync.destroyInstance",i),le.destroySynced(i))),this._localInstance=void 0}watchTabVisible(){window.addEventListener("visibilitychange",t=>{if(document.visibilityState==="visible")for(let i=qo.all.length-1;i>=0;i--){const s=qo.all[i];(!s.owner||!this.context.connection.userIsInRoom(s.owner))&&s.doDestroy()}})}}Cw([x()],cm.prototype,"autoSync",2);Cw([x(ii)],cm.prototype,"asset",2);Cw([x(gs)],cm.prototype,"onPlayerSpawned",2);var NH=(n=>(n.OwnerChanged="ownerChanged",n))(NH||{}),hg;const Ms=(hg=class extends Ie{constructor(){super(...arguments);u(this,"onOwnerChangeEvent",new gs);u(this,"onFirstOwnerChangeEvent",new gs);u(this,"hasOwner",!1);u(this,"owner");u(this,"dontDestroy",!1);u(this,"onUserLeftRoom",e=>{if(e.userId===this.owner){zo&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}})}static get all(){return Ms._all}static get local(){return Ms._local}static getFor(e){if(e instanceof ge)return le.getComponentInParent(e,Ms);if(e instanceof Ie)return le.getComponentInParent(e.gameObject,Ms)}static isLocalPlayer(e){const t=Ms.getFor(e);return(t==null?void 0:t.isLocalPlayer)??!1}static addEventListener(e,t){return this._callbacks[e]||(this._callbacks[e]=[]),this._callbacks[e].push(t),t}static removeEventListener(e,t){if(!this._callbacks[e])return;const i=this._callbacks[e].indexOf(t);i>=0&&this._callbacks[e].splice(i,1)}static dispatchEvent(e,t){if(this._callbacks[e])for(const i of this._callbacks[e])i(t)}get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(e,t){var o,a;zo&&console.log("PlayerSync.onOwnerChange",this,"newOwner",e,"oldOwner",t);const i=Ms._local.indexOf(this);i>=0&&Ms._local.splice(i,1);const s={playerState:this,oldValue:t,newValue:e};if(this.hasOwner||(this.hasOwner=!0,(o=this.onFirstOwnerChangeEvent)==null||o.invoke(s)),(a=this.onOwnerChangeEvent)==null||a.invoke(s),this.owner===this.context.connection.connectionId){Ms._local.push(this);const c=new CustomEvent("local-owner-changed",{detail:s});this.dispatchEvent(c)}const r=new CustomEvent("owner-changed",{detail:s});this.dispatchEvent(r),Ms.dispatchEvent("ownerChanged",r)}awake(){Ms.all.push(this),zo&&console.log("Registered new PlayerState",this.guid,Ms.all.length-1,Ms.all),this.context.connection.beginListen(mi.UserLeftRoom,this.onUserLeftRoom)}async start(){zo&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await Yo(300),this.context.connection.userIsInRoom(this.owner)==!1&&(zo&&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||(zo&&console.warn("PlayerState.start โ†’ owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?zo&&console.warn("PlayerState.start โ†’ owner is still undefined but dontDestroy is set to true",this.name):(zo&&console.warn(`PlayerState.start โ†’ owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):console.log("PlayerState.start โ†’ owner is assigned",this.owner)},2e3))}doDestroy(){zo&&console.log("PlayerSync.doDestroy โ†’ syncDestroy",this.name),aw(this.gameObject,this.context.connection)}onDestroy(){if(this.context.connection.stopListen(mi.UserLeftRoom,this.onUserLeftRoom),Ms.all.splice(Ms.all.indexOf(this),1),this.isLocalPlayer){const e=Ms._local.indexOf(this);e>=0&&Ms._local.splice(e,1)}}},u(hg,"_all",[]),u(hg,"_local",[]),u(hg,"_callbacks",{}),hg);let qo=Ms;Cw([GR(qo.prototype.onOwnerChange)],qo.prototype,"owner",2);const Rse=se("debugavatar"),Aa=class extends Ie{constructor(){super(...arguments);u(this,"connectionId");u(this,"avatar")}static getAvatar(t){return t>=0&&t<Aa.instances.length?Aa.instances[t]:null}static onAvatarMarkerCreated(t){return Aa._onNewAvatarMarkerAdded.push(t),t}static onAvatarMarkerDestroyed(t){return Aa._onAvatarMarkerDestroyed.push(t),t}awake(){Aa.instances.push(this),Rse&&console.log(this);for(const t of Aa._onNewAvatarMarkerAdded)t({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){Aa.instances.splice(Aa.instances.indexOf(this),1);for(const t of Aa._onAvatarMarkerDestroyed)t({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}};let Zn=Aa;u(Zn,"instances",[]),u(Zn,"_onNewAvatarMarkerAdded",[]),u(Zn,"_onAvatarMarkerDestroyed",[]);var Pse=Object.defineProperty,Bse=Object.getOwnPropertyDescriptor,Dse=(n,e,t,i)=>{for(var s=i>1?void 0:i?Bse(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Pse(e,t,s),s};const Gf=se("debugxrflags"),zH=se("disablexrflags");zH&&console.warn("XRFlags are disabled");var rc=(n=>(n[n.Never=0]="Never",n[n.Browser=1]="Browser",n[n.AR=2]="AR",n[n.VR=4]="VR",n[n.FirstPerson=8]="FirstPerson",n[n.ThirdPerson=16]="ThirdPerson",n[n.All=4294967295]="All",n))(rc||{});const JP=class{constructor(){u(this,"Mask",17)}Has(e){return(this.Mask&e)!==0}Set(e){Gf&&console.warn("Set XR flag state to",e),this.Mask=e,lo.Apply()}Enable(e){this.Mask|=e,lo.Apply()}Disable(e){this.Mask&=~e,lo.Apply()}Toggle(e){this.Mask^=e,lo.Apply()}EnableAll(){this.Mask=-1,lo.Apply()}DisableAll(){this.Mask=0,lo.Apply()}};let Bs=JP;u(Bs,"Global",new JP);var ug;const Kc=(ug=class extends Ie{constructor(){super(...arguments);u(this,"visibleIn")}static Apply(){for(const e of this.registry)e.UpdateVisible(Bs.Global)}awake(){Kc.registry.push(this)}onEnable(){Kc.firstApply?this.UpdateVisible(Bs.Global):(Kc.firstApply=!0,Kc.Apply())}onDestroy(){const e=Kc.registry.indexOf(this);e>=0&&Kc.registry.splice(e,1)}get isOn(){return this.gameObject.visible}UpdateVisible(e=null){if(zH)return;let t;const i=e;if(i&&typeof i=="number"&&(console.assert(typeof i=="number","XRFlag.UpdateVisible: state must be a number",i),Gf&&console.log(i),Kc.buffer.Mask=i,e=Kc.buffer),e instanceof Bs?(Gf&&console.warn(this.name,"use passed in mask",e.Mask,this.visibleIn),t=e.Has(this.visibleIn)):(Gf&&console.log(this.name,"use global mask"),Bs.Global.Has(this.visibleIn)),t!==void 0)if(t)Gf&&console.log(this.name,"is visible",this.gameObject.uuid),le.setActive(this.gameObject,!0);else{if(Gf&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},u(ug,"registry",[]),u(ug,"firstApply"),u(ug,"buffer",new Bs),ug);let lo=Kc;Dse([x()],lo.prototype,"visibleIn",2);var Ose=Object.defineProperty,kse=Object.getOwnPropertyDescriptor,HR=(n,e,t,i)=>{for(var s=i>1?void 0:i?kse(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Ose(e,t,s),s};const $m=se("debugwebxr"),c2=new Ee().setFromAxisAngle(new w(0,1,0),Math.PI);class Id extends Ie{constructor(){super(...arguments);u(this,"head");u(this,"leftHand");u(this,"rightHand");u(this,"_syncTransforms")}async onEnterXR(t){if(!this.activeAndEnabled)return;$m&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const i=qo.getFor(this);if(i!=null&&i.owner){const s=this.gameObject.addNewComponent(Zn);s.avatar=this.gameObject,s.connectionId=i.owner}else this.context.connection.isConnected?console.error("No player state found for avatar",this):i&&!this.context.connection.isConnected&&(i.dontDestroy=!0)}onLeaveXR(t){const i=this.gameObject.getComponent(Zn);i&&i.destroy()}onUpdateXR(t){var c,l;if(!this.activeAndEnabled)return;const i=qo.isLocalPlayer(this);if(!i)return;const s=t.xr;if(s.rig&&s.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),s.rig.gameObject.add(this.gameObject)),this._syncTransforms&&i)for(const h of this._syncTransforms)h.fastMode=!0,h.isOwned()||h.requestOwnership();if(this.head&&this.context.mainCamera){const h=this.head.asset;if(h.position.copy(this.context.mainCamera.position),h.quaternion.copy(this.context.mainCamera.quaternion),h.quaternion.x*=-1,this.context.time.frameCount%10===0){const d=le.getComponentsInChildren(this.head.asset,lo);for(const f of d)f.enabled=!1,f.gameObject.visible=!1}}const r=t.xr.leftController,o=(c=this.leftHand)==null?void 0:c.asset;r&&o&&(o.position.copy(r.gripPosition),o.quaternion.copy(r.gripQuaternion),o.quaternion.multiply(c2),o.visible=r.isTracking);const a=t.xr.rightController;if(a&&((l=this.rightHand)!=null&&l.asset)){const h=this.rightHand.asset;h.position.copy(a.gripPosition),h.quaternion.copy(a.gripQuaternion),h.quaternion.multiply(c2),h.visible=a.isTracking}}onBeforeRender(){this.context.time.frame%10===0&&this.updateRemoteAvatarVisibility()}updateRemoteAvatarVisibility(){var t,i,s;if(this.context.connection.isConnected){const r=qo.getFor(this);if(r&&r.isLocalPlayer==!1){const o=yt.getXRSync(this.context);if(o&&o.hasState(r.owner)){this.tryFindAvatarObjectsIfMissing();const a=(t=this.leftHand)==null?void 0:t.asset;a&&(a.visible=(o==null?void 0:o.isTracking(r.owner,"left"))??!1);const c=(i=this.rightHand)==null?void 0:i.asset;c&&(c.visible=(o==null?void 0:o.isTracking(r.owner,"right"))??!1)}if((s=this.head)!=null&&s.asset){const a=le.getComponentsInChildren(this.head.asset,lo);for(const c of a)c.enabled=!1,c.gameObject.visible=!0}}}}tryFindAvatarObjectsIfMissing(){if(!this.head||!this.leftHand||!this.rightHand){const t={head:this.head,leftHand:this.leftHand,rightHand:this.rightHand};bG.tryFindAvatarObjects(this.gameObject,this.sourceId||"",t),t.head&&(this.head=t.head),t.leftHand&&(this.leftHand=t.leftHand),t.rightHand&&(this.rightHand=t.rightHand)}}async prepareAvatar(){if(this.tryFindAvatarObjectsIfMissing(),this.head)this.head instanceof ge&&(this.head=new ii("",this.sourceId,this.head));else{const t=new ge;t.name="Head";const i=Dp.createPrimitive(_d.Cube);t.add(i),this.gameObject.add(t),this.head=new ii("",this.sourceId,t),$m&&console.log("Create head",t)}if(this.rightHand)this.rightHand instanceof ge&&(this.rightHand=new ii("",this.sourceId,this.rightHand));else{const t=new ge;t.name="Right Hand",this.gameObject.add(t),this.rightHand=new ii("",this.sourceId,t),$m&&console.log("Create right hand",t)}if(this.leftHand)this.leftHand instanceof ge&&(this.leftHand=new ii("",this.sourceId,this.leftHand));else{const t=new ge;t.name="Left Hand",this.gameObject.add(t),this.leftHand=new ii("",this.sourceId,t),$m&&console.log("Create left hand",t)}await this.loadAvatarObjects(this.head,this.leftHand,this.rightHand),qo.isLocalPlayer(this.gameObject)&&(this._syncTransforms=le.getComponentsInChildren(this.gameObject,Nh))}async loadAvatarObjects(t,i,s){const r=t.loadAssetAsync(),o=i.loadAssetAsync(),a=s.loadAssetAsync(),c=new Array;r&&c.push(r),o&&c.push(o),a&&c.push(a);const l=await fA(c);$m&&console.log("Avatar loaded results:",l)}}HR([x(ii)],Id.prototype,"head",2);HR([x(ii)],Id.prototype,"leftHand",2);HR([x(ii)],Id.prototype,"rightHand",2);class bc{static Add(e,t,i=null){if(t){for(const s of this.Pois)if(s.obj===t)return;this.Pois.push({obj:t,avatar:i}),this.LastChangeTime=e.time.time}}static Remove(e,t){var i;if(t){for(const s of this.Pois)if(s.obj===t){this.Pois.splice(this.Pois.indexOf(s),1),this.LastChangeTime=(e==null?void 0:e.time.time)??((i=Ot.Current)==null?void 0:i.time.time);return}}}}u(bc,"Pois",[]),u(bc,"LastChangeTime",0);class Lse{constructor(){u(this,"guid");u(this,"position",new w)}}class Hv extends Ie{constructor(){super(...arguments);u(this,"target",null);u(this,"avatar",null);u(this,"_model",null);u(this,"_targetModel",new Lse);u(this,"_currentTargetObject",null);u(this,"_lastUpdateTime",0);u(this,"_lookDuration",0);u(this,"_lastPoiChangedTime",0)}set controlledTarget(t){this.target=t;const i=$.get("MoveRandom");if(i&&this.target){const s=le.getComponent(this.target,i);s&&s.destroy()}}awake(){if(this.avatar=le.getComponentInParent(this.gameObject,Zn),this.avatar){const t=le.getComponentInParent(this.gameObject,Zn);this._model=new LI(this.context.connection,this.guid),t!=null&&t.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",t=>{var i;this.target&&t&&t.guid===((i=this.avatar)==null?void 0:i.guid)&&sr(this.target,t.position)})}update(){var i;if((!this.context.connection.isConnected||(i=this._model)!=null&&i.hasOwnership)&&(bc.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=bc.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){const s=Dt(this._currentTargetObject);sr(this.target,s),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(s))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;const i=bc.Pois;if(i.length>0){const s=i[Math.floor(Math.random()*i.length)];if(s&&s.obj){if(s.avatar&&s.avatar===this.avatar)return;this._currentTargetObject=s.obj}}}}}const ep=se("debugnetworkingstreams");var mc=(n=>(n.Connected="peer-user-connected",n.StreamReceived="receive-stream",n.StreamEnded="call-ended",n.Disconnected="peer-user-disconnected",n.UserJoined="user-joined",n))(mc||{});class GH{constructor(e,t){u(this,"type","call-ended");u(this,"userId");u(this,"direction");this.userId=e,this.direction=t}}class HH{constructor(e,t){u(this,"type","receive-stream");u(this,"stream");u(this,"target");this.stream=e,this.target=t}}class Fse{constructor(e,t){u(this,"guid");u(this,"peerId");u(this,"dontSave",!0);this.guid=e.id,this.peerId=t}}var VH=(n=>(n.Incoming="incoming",n.Outgoing="outgoing",n))(VH||{});class Use extends ys{constructor(t,i,s){super();u(this,"userId");u(this,"direction");u(this,"call");u(this,"_stream",null);u(this,"_isDisposed",!1);this.userId=t,this.call=i,this.direction=s,this._stream=null,i.on("stream",r=>{if(ep&&console.log("Receive video",r.getAudioTracks(),r.getVideoTracks()),this._stream=r,s==="incoming"){const o=new HH(r,this);this.dispatchEvent(o)}}),i.on("close",()=>{this.dispatchEvent(new GH(t,s))})}get stream(){return this._stream}close(){this._isDisposed||(this._isDisposed=!0,this.call.close(),pl(this._stream))}get isOpen(){var t;return((t=this.call.peerConnection)==null?void 0:t.connectionState)==="connected"}get isOpening(){var t;return((t=this.call.peerConnection)==null?void 0:t.connectionState)==="connecting"}get isClosed(){return!this.isOpen}}const ap=class extends ys{constructor(t,i){super();u(this,"id");u(this,"context");u(this,"_peer");u(this,"_incomingCalls",[]);u(this,"_outgoingCalls",[]);u(this,"_enabled",!1);u(this,"_enabledPeer",!1);u(this,"onConnectRoomFn",this.onConnectRoom.bind(this));u(this,"onPeerConnectFn",this.onPeerConnect.bind(this));u(this,"onPeerReceiveCallFn",this.onPeerReceivingCall.bind(this));this.context=t,this.id=i,this.setupPeer(),navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia}static getOrCreate(t,i){if(ap.instances.has(i))return ap.instances.get(i);const s=new ap(t,i);return ap.instances.set(i,s),s}getMyPeerId(){if(this.context.connection.connectionId)return this.getPeerIdFromUserId(this.context.connection.connectionId)}getPeerIdFromUserId(t){return this.id+"-"+t}getUserIdFromPeerId(t){return t.substring(this.id.length+1)}makeCall(t,i){var o;const s={metadata:{userId:this.context.connection.connectionId}},r=(o=this._peer)==null?void 0:o.call(t,i,s);if(r)return this.registerCall(r,"outgoing")}get peer(){return this._peer}enable(){this._enabled||(this._enabled=!0,this.context.connection.beginListen(mi.JoinedRoom,this.onConnectRoomFn),this.subscribePeerEvents())}disable(){this._enabled&&(this._enabled=!1,this.context.connection.stopListen(mi.JoinedRoom,this.onConnectRoomFn),this.unsubscribePeerEvents())}onConnectRoom(){this.setupPeer()}setupPeer(){if(this.context.connection.connectionId&&!this._enabledPeer){if(this._enabledPeer=!0,!this._peer){const t=this.getMyPeerId();t?this._peer=Q3(t):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(t){ep&&console.log("Peer connected as",t),this.context.connection.send("peer-user-connected",new Fse(this,t))}onPeerReceivingCall(t){t.answer(),this.registerCall(t,"incoming")}registerCall(t,i){const s=t.metadata;(!s||!s.userId)&&console.error("Missing call metadata",t);const r=s.userId;i==="incoming"&&ep?console.log("Receive call from",t.metadata):ep&&console.log("Make call to",t.metadata);const o=i==="incoming"?this._incomingCalls:this._outgoingCalls,a=new Use(r,t,i);return o.push(a),t.on("error",c=>{console.error("Call error",c)}),t.on("close",()=>{ep&&console.log("Call ended",t.metadata),t.close();const c=o.indexOf(a);c!==-1&&o.splice(c,1)}),a.addEventListener("call-ended",c=>{this.dispatchEvent(c)}),i==="incoming"&&(a.addEventListener("receive-stream",c=>{this.dispatchEvent(c)}),t.on("stream",()=>{let c=0;const l=setInterval(()=>{const h=c===0;!a.isOpen&&h&&(c+=1,clearInterval(l),a.close())},2e3)})),a}};let Ap=ap;u(Ap,"instances",new Map);class QA extends ys{constructor(t,i){super();u(this,"context");u(this,"peer");u(this,"_sendingStreams",new Map);u(this,"debug",!1);u(this,"onJoinedRoom",t=>{this.debug&&console.log(`${t.userId} joined room and I'm currently sending ${this._sendingStreams.size} streams`),this._sendingStreams.size>0&&this.updateSendingCalls()});u(this,"onReceiveStream",t=>{this.debug&&console.log("RECEIVE STREAM",t),this.dispatchEvent({type:"receive-stream",target:this,stream:t.stream,userId:t.userId})});u(this,"onCallEnded",t=>{this.dispatchEvent(t)});u(this,"onUserConnected",t=>{if(this.peer.id===t.guid){this.debug&&console.log("USER CONNECTED",t.guid,t);const i=this._sendingStreams.keys().next().value;this.peer.makeCall(t.peerId,i)}});u(this,"onUserLeft",t=>{this.stopCallsToUsersThatAreNotInTheRoomAnymore()});this.context=t,this.peer=i,ep&&(this.debug=!0)}static create(t){const i=Ap.getOrCreate(t.context,t.context.connection.connectionId);return new QA(t.context,i)}startSendingStream(t){this._sendingStreams.has(t)?console.warn("Received start sending stream with stream that is already being sent"):(this._sendingStreams.set(t,[]),this.updateSendingCalls())}stopSendingStream(t){if(t){const i=this._sendingStreams.get(t);if(i){this.debug&&console.log("Closing calls",i);for(const s of i)s.close()}this._sendingStreams.delete(t),i&&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(mi.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(mi.UserJoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(mi.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(mi.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(mi.UserJoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(mi.UserLeftRoom,this.onUserLeft)}updateSendingCalls(){var s;let t=!1;const i=this.context.connection.connectionId;for(const r of this._sendingStreams.keys()){const o=this._sendingStreams.get(r)||[];for(const a of this.context.connection.usersInRoom()){if(a===i)continue;const c=o.find(l=>l.userId===a);if(!c||((s=c.stream)==null?void 0:s.active)===!1){this.debug&&console.log("Starting call to",a,i);const l=this.peer.makeCall(this.peer.getPeerIdFromUserId(a),r);l&&(t=!0,o.push(l))}}this._sendingStreams.set(r,o)}this.stopCallsToUsersThatAreNotInTheRoomAnymore(),t&&this.debug&&console.log("Currently sending",this._sendingStreams)}stopCallsToUsersThatAreNotInTheRoomAnymore(){for(const t of this._sendingStreams.keys()){const i=this._sendingStreams.get(t);if(i)for(let s=i.length-1;s>=0;s--){const r=i[s];this.context.connection.userIsInRoom(r.userId)||(r.close(),i.splice(s,1))}}}}function pl(n){if(n&&n instanceof MediaStream)for(const e of n.getTracks())e.stop()}var Nse=Object.defineProperty,zse=Object.getOwnPropertyDescriptor,QH=(n,e,t,i)=>{for(var s=i>1?void 0:i?zse(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Nse(e,t,s),s};const Gse="noVoip",Hse=se("debugvoip");class Rd extends Ie{constructor(){super(...arguments);u(this,"autoConnect",!1);u(this,"runInBackground",!0);u(this,"debug",!1);u(this,"_net");u(this,"_outputStream",null);u(this,"onJoinedRoom",async()=>{await Yo(300),this.autoConnect&&!this.isSending&&this.connect()});u(this,"_incomingStreams",new Map);u(this,"onReceiveStream",t=>{const i=t.target.userId,s=t.stream,r=this._incomingStreams.get(i);if(r)r.srcObject=s,r.setAttribute("autoplay","true");else{const o=new Audio;this._incomingStreams.set(i,o),o.setAttribute("autoplay","true"),o.srcObject=s}});u(this,"onStreamEnded",t=>{const i=this._incomingStreams.get(t.userId);pl(i==null?void 0:i.srcObject),this._incomingStreams.delete(t.userId)});u(this,"onEnabledChanged",()=>{for(const t of this._incomingStreams){const i=t[1];i.muted=!this.enabled}});u(this,"onVisibilityChanged",()=>{if(this.runInBackground)return;const i=!(document.visibilityState==="visible");this.setMuted(i);for(const s of this._incomingStreams){const r=s[1];r.muted=i}})}awake(){Hse&&(this.debug=!0),this.debug&&window.addEventListener("keydown",async t=>{t.key==="v"&&(console.log("MUTE?",!this.isMuted),this.setMuted(!this.isMuted))})}onEnable(){this._net||(this._net=QA.create(this)),this._net.addEventListener(mc.StreamReceived,this.onReceiveStream),this._net.addEventListener(mc.StreamEnded,this.onStreamEnded),this._net.enable(),this.autoConnect&&(this.context.connection.isConnected?this.connect():this.context.connection.beginListen(mi.JoinedRoom,this.onJoinedRoom)),this.onEnabledChanged(),window.addEventListener("visibilitychange",this.onVisibilityChanged)}onDisable(){var t;this._net.stopSendingStream(this._outputStream),this._net.removeEventListener(mc.StreamReceived,this.onReceiveStream),this._net.removeEventListener(mc.StreamEnded,this.onStreamEnded),(t=this._net)==null||t.disable(),this.context.connection.stopListen(mi.JoinedRoom,this.onJoinedRoom),this.onEnabledChanged(),window.removeEventListener("visibilitychange",this.onVisibilityChanged)}get isSending(){return this._outputStream!=null&&this._outputStream.active}async connect(t){if(this.context.connection.isConnected){if(!await M1())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),pl(this._outputStream),this._outputStream=await this.getAudioStream(t),this._outputStream?(this._net.startSendingStream(this._outputStream),!0):(await M1()?console.error("VOIP: Could not get audio stream - please make sure to connect an audio device and grant microphone permissions"):eN("Microphone permissions not granted: Please grant microphone permissions to use voice chat"),!1)}disconnect(){this._net.stopSendingStream(this._outputStream),pl(this._outputStream),this._outputStream=null}setMuted(t){var s;const i=(s=this._outputStream)==null?void 0:s.getAudioTracks();if(i)for(const r of i)r.enabled=!t}get isMuted(){var i;if(this._outputStream===null)return!1;const t=(i=this._outputStream)==null?void 0:i.getAudioTracks();if(t){for(const s of t)if(!s.enabled)return!0}return!1}getFrequency(t){return this.unsupported_getfrequency||(this.unsupported_getfrequency=!0,Mt()&&pn("VOIP: getFrequency is currently not supported"),console.warn("VOIP: getFrequency is currently not supported")),null}async getAudioStream(t){return navigator.mediaDevices.getUserMedia?await navigator.mediaDevices.getUserMedia({audio:t??!0,video:!1}).catch(s=>(console.warn("VOIP failed getting audio stream",s),null)):(console.error("No getDisplayMedia support"),null)}}QH([x()],Rd.prototype,"autoConnect",2);QH([x()],Rd.prototype,"runInBackground",2);var Vse=Object.defineProperty,Qse=Object.getOwnPropertyDescriptor,jH=(n,e,t,i)=>{for(var s=i>1?void 0:i?Qse(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Vse(e,t,s),s};const jse=se("debugmouth");class jA extends Ie{constructor(){super(...arguments);u(this,"idle",[]);u(this,"talking",[]);u(this,"marker",null);u(this,"voip",null);u(this,"lastMouthChangeTime",0);u(this,"mouthChangeLength",0)}awake(){setTimeout(()=>{this.voip=le.findObjectOfType(Rd,this.context),this.marker||(this.marker=le.getComponentInParent(this.gameObject,Zn))},3e3)}update(){var s;if(!this.voip||this.context.time.frameCount%10!==0)return;let t=((s=this.marker)==null?void 0:s.connectionId)??null;if(!t){jse&&(t=null);return}const i=this.voip.getFrequency(t)??0;this.updateLips(i)}updateLips(t){if(this.context.time.time-this.lastMouthChangeTime>this.mouthChangeLength){if(this.mouthChangeLength=.05+Math.random()*.1,this.talking&&this.talking.length>0&&t>30){this.lastMouthChangeTime=this.context.time.time;const i=Math.floor(Math.random()*this.talking.length);this.setMouthShapeActive(this.talking,i)}else if(this.idle.length>0&&this.context.time.time-this.lastMouthChangeTime>.5){this.lastMouthChangeTime=this.context.time.time;const i=Math.floor(Math.random()*this.idle.length);this.setMouthShapeActive(this.idle,i)}}}setMouthShapeActive(t,i){if(t){t!=this.idle?this.idle.map(s=>s.visible=!1):this.talking.map(s=>s.visible=!1);for(let s=0;s<t.length;s++){const r=t[s];r&&(r.visible=s===i)}}}}jH([x(ge)],jA.prototype,"idle",2);jH([x(ge)],jA.prototype,"talking",2);class VR extends Ie{constructor(){super(...arguments);u(this,"voip",null);u(this,"marker",null);u(this,"_startPosition",null)}awake(){this.voip=le.findObjectOfType(Rd,this.context),this.marker=le.getComponentInParent(this.gameObject,Zn)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!==0)return;const t=this.marker.connectionId,i=this.voip.getFrequency(t);if(i==null)return;this._startPosition||(this._startPosition=this.gameObject.position.clone());const s=i/100;this.gameObject.position.y=this._startPosition.y+s*.07}}var Wse=Object.defineProperty,qse=Object.getOwnPropertyDescriptor,Ew=(n,e,t,i)=>{for(var s=i>1?void 0:i?qse(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Wse(e,t,s),s};class Pd extends Ie{constructor(){super(...arguments);u(this,"eyes",[]);u(this,"lastBlinkTime",0);u(this,"blinkLength",0);u(this,"eyesOpen",!0);u(this,"state",null)}awake(){this.state=le.getComponentInParent(this.gameObject,lo)}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 i of this.eyes)i&&(i.visible=this.eyesOpen)}}}Ew([x(ge)],Pd.prototype,"eyes",2);Ew([x()],Pd.prototype,"lastBlinkTime",2);Ew([x()],Pd.prototype,"blinkLength",2);Ew([x()],Pd.prototype,"eyesOpen",2);var Xse=Object.defineProperty,Yse=Object.getOwnPropertyDescriptor,QR=(n,e,t,i)=>{for(var s=i>1?void 0:i?Yse(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Xse(e,t,s),s},LE;const WH=(LE=class extends Ie{constructor(){super(...arguments);u(this,"head",null);u(this,"eyes",null);u(this,"target",null);u(this,"brain",null);u(this,"vec",new w);u(this,"currentTargetPoint",new w)}awake(){this.brain||(this.brain=le.getComponentInParent(this.gameObject,Hv)),this.brain||(console.log("No look at brain found, adding it now"),this.brain=le.addNewComponent(this.gameObject,Hv)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}update(){const e=this.target;if(e&&this.head){const t=this.eyes;if(t){const i=Dt(e);this.currentTargetPoint.lerp(i,this.context.time.deltaTime/.1);const s=Dt(this.head),r=this.vec.copy(this.currentTargetPoint).sub(s).normalize();if(r.length()<.1)return;const o=WH.forward;if(o.set(0,0,1),o.applyQuaternion(Di(this.head)),o.dot(r)>.45)for(let c=0;c<t.length;c++)t[c].lookAt(this.currentTargetPoint)}}}},u(LE,"forward",new w(0,0,1)),LE);let lm=WH;QR([x(ge)],lm.prototype,"head",2);QR([x(ge)],lm.prototype,"eyes",2);QR([x(ge)],lm.prototype,"target",2);const eg=se("debugavatar");class Mw{constructor(e,t,i,s){u(this,"root");u(this,"head");u(this,"leftHand");u(this,"rigthHand");var r;this.root=e,this.head=t,this.leftHand=i,this.rigthHand=s,(r=this.root)==null||r.traverse(o=>o.layers.set(2))}get isValid(){return this.head!==null&&this.head!==void 0}}class jR{constructor(){u(this,"avatarRegistryUrl",null)}async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let i=null;if(typeof t=="string"){if(i=await this.loadAvatar(e,t),!i){const r=new Fa;i=le.instantiate(Mp(t,e.scene),r)}}else i=t;if(!i)return null;const s=this.findAvatar(i);return s.isValid?(eg&&console.log("[Custom Avatar] valid config",t,eg?s:""),s):(console.warn("[Custom Avatar] config isn't valid",t,eg?s:""),null)}async loadAvatar(e,t){if(console.assert(t!=null&&typeof t=="string","Avatar id must not be null"),t.length<=0||!t)return null;if(eg&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const s=await fetch("./"+t);let r=null;if(s.ok){const a=await s.blob();a&&(r=await a.arrayBuffer())}if(!r&&(r=await wI(t,t,0,"no url here go away",!0),!r))return null;const o=await Ia().parseSync(e,r,null,0);return(o==null?void 0:o.scene)??null}const i=new im;return BA(i,e),new Promise((s,r)=>{const o=this.avatarRegistryUrl+"/"+t;i.load(o,async a=>{await Ia().createBuiltinComponents(e,o,a,null,void 0),s(a.scene)},a=>{eg&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),s(null)})})}cacheModel(e,t){}findAvatar(e){const t=e;let i=t;i.children.length==1&&(i=e.children[0]);let s=this.findAvatarPart(i,["head"]);const r=this.findAvatarPart(i,["left","hand"]),o=this.findAvatarPart(i,["right","hand"]);if(!s){s=t;const c=new w;new Oi().setFromObject(s).getSize(c);const l=Math.max(c.x,c.y,c.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+l+" meters! Should be < 0.3m"),l>.3&&s.scale.multiplyScalar(1/l*.3)}return new Mw(t,s,r,o)}findAvatarPart(e,t){const i=e.name.toLowerCase();let s=!0;for(const r of t){if(!s)break;i.indexOf(r)===-1&&(s=!1)}if(s)return e;if(e.children)for(const r of e.children){const o=this.findAvatarPart(r,t);if(o)return o}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}var Jse=Object.defineProperty,Kse=Object.getOwnPropertyDescriptor,WR=(n,e,t,i)=>{for(var s=i>1?void 0:i?Kse(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Jse(e,t,s),s};class hm extends Ie{constructor(){super(...arguments);u(this,"length",1);u(this,"depthTest",!0);u(this,"isGizmo",!0);u(this,"_axes",null)}onEnable(){if(this.isGizmo&&!gA)return;this._axes||(this._axes=new Zo(this.length)),this._axes.layers.disableAll(),this._axes.layers.set(this.layer),this.gameObject.add(this._axes);const t=this._axes.material;t&&t.depthTest!==void 0&&(t.depthTest=this.depthTest)}onDisable(){this._axes&&this.gameObject.remove(this._axes)}}WR([x()],hm.prototype,"length",2);WR([x()],hm.prototype,"depthTest",2);WR([x()],hm.prototype,"isGizmo",2);class qR extends Ie{constructor(){super(...arguments);u(this,"from");u(this,"to");u(this,"hint");u(this,"desiredDistance",1)}onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;const t=Dt(this.to).clone(),i=Dt(this.from).clone(),s=t.distanceTo(i),r=t.clone();r.sub(i);const o=i.clone();o.add(t),o.multiplyScalar(.5);const a=Dt(this.hint).clone();a.sub(o);const c=new w;c.crossVectors(a,r),c.crossVectors(r,c),c.normalize();const l=s*.5,h=Math.max(this.desiredDistance,l),d=Math.sqrt(h*h-l*l),f=c.clone();f.multiplyScalar(d),f.add(o),sr(this.gameObject,f);const p=o.clone();p.sub(c),this.gameObject.lookAt(p)}}const Zse=se("debugusdz");class Tw{constructor(){u(this,"behaviours",[]);u(this,"behaviourComponents",[]);u(this,"behaviourComponentsCopy",[])}get extensionName(){return"Behaviour"}addBehavior(e){this.behaviours.push(e)}onBeforeBuildDocument(e){const t=[];return e.root.traverse(i=>{le.foreachComponent(i,s=>{var o;const r=s;if(typeof r.createBehaviours=="function"||typeof r.beforeCreateDocument=="function"||typeof r.afterCreateDocument=="function"||typeof r.afterSerialize=="function"){this.behaviourComponents.push(r);const a=(o=r.beforeCreateDocument)==null?void 0:o.call(r,this,e);a instanceof Promise&&t.push(a)}},!1)}),Promise.all(t)}onExportObject(e,t,i){var s;for(const r of this.behaviourComponents)(s=r.createBehaviours)==null||s.call(r,this,t,i)}onAfterBuildDocument(e){for(const t of this.behaviourComponents)typeof t.afterCreateDocument=="function"&&t.afterCreateDocument(this,e);this.behaviourComponentsCopy=this.behaviourComponents.slice(),this.behaviourComponents.length=0}onAfterHierarchy(e,t){var i;if((i=this.behaviours)!=null&&i.length){t.beginBlock('def Scope "Behaviors"');for(const s of this.behaviours)s.writeTo(this,e.document,t);t.closeBlock()}}async onAfterSerialize(e){Zse&&console.log("onAfterSerialize behaviours",this.behaviourComponentsCopy);for(const t of this.behaviourComponentsCopy)typeof t.afterSerialize=="function"&&(t.afterSerialize.constructor.name==="AsyncFunction"?await t.afterSerialize(this,e):t.afterSerialize(this,e));this.behaviours.length=0}}var $se=Object.defineProperty,ere=Object.getOwnPropertyDescriptor,XR=(n,e,t,i)=>{for(var s=i>1?void 0:i?ere(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&$se(e,t,s),s};class Bd extends cr{constructor(){super(...arguments);u(this,"threshold");u(this,"intensity");u(this,"scatter");u(this,"selectiveBloom",!0)}get typeName(){return"Bloom"}init(){this.threshold.defaultValue=1,this.intensity.defaultValue=0,this.scatter.defaultValue=.2,this.selectiveBloom?(this.threshold.valueProcessor=t=>t,this.intensity.valueProcessor=t=>t,this.scatter.valueProcessor=t=>1*Math.PI*(1-t)):(this.threshold.valueProcessor=t=>t,this.intensity.valueProcessor=t=>t,this.scatter.valueProcessor=t=>100*(1-t))}onCreateEffect(){let t;if(this.selectiveBloom){const i=t=new RN(this.context.scene,this.context.mainCamera,{blendFunction:qt.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,intensity:this.intensity.value});i.inverted=!0}else t=new _I;return this.intensity.onValueChanged=i=>{t.intensity=i},this.threshold.onValueChanged=i=>{t.luminanceMaterial.threshold=i},this.scatter.onValueChanged=i=>{t.luminancePass.enabled=!0,t.luminanceMaterial.smoothing=i},t}}XR([x(kt)],Bd.prototype,"threshold",2);XR([x(kt)],Bd.prototype,"intensity",2);XR([x(kt)],Bd.prototype,"scatter",2);oa("Bloom",Bd);var tre=Object.defineProperty,ire=Object.getOwnPropertyDescriptor,Yr=(n,e,t,i)=>{for(var s=i>1?void 0:i?ire(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&tre(e,t,s),s};class aa extends Ie{constructor(){super(...arguments);u(this,"attachedRigidbody",null);u(this,"isTrigger",!1);u(this,"sharedMaterial");u(this,"membership",[0]);u(this,"filter");u(this,"updateProperties",()=>{var t;(t=this.context.physics.engine)==null||t.updateProperties(this)})}get isCollider(){return!0}awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Xi))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Xi))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Xi))}onDisable(){var t;(t=this.context.physics.engine)==null||t.removeBody(this)}get body(){var t;return(t=this.context.physics.engine)==null?void 0:t.getBody(this)}updatePhysicsMaterial(){var t;(t=this.context.physics.engine)==null||t.updatePhysicsMaterial(this)}}Yr([x(Xi)],aa.prototype,"attachedRigidbody",2);Yr([x()],aa.prototype,"isTrigger",2);Yr([x()],aa.prototype,"sharedMaterial",2);Yr([x()],aa.prototype,"membership",2);Yr([x()],aa.prototype,"filter",2);class WA extends aa{constructor(){super(...arguments);u(this,"radius",.5);u(this,"center",new w(0,0,0))}onEnable(){var t;super.onEnable(),(t=this.context.physics.engine)==null||t.addSphereCollider(this),zx(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),cI(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}}Yr([Vs(),x()],WA.prototype,"radius",2);Yr([x(w)],WA.prototype,"center",2);class qA extends aa{constructor(){super(...arguments);u(this,"size",new w(1,1,1));u(this,"center",new w(0,0,0))}onEnable(){var t;super.onEnable(),(t=this.context.physics.engine)==null||t.addBoxCollider(this,this.size),zx(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),cI(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}}Yr([Vs(),x(w)],qA.prototype,"size",2);Yr([x(w)],qA.prototype,"center",2);class um extends aa{constructor(){super(...arguments);u(this,"sharedMesh");u(this,"convex",!1)}onEnable(){var t,i,s,r,o;if(super.onEnable(),(t=this.sharedMesh)!=null&&t.isMesh||this.gameObject instanceof me&&(this.sharedMesh=this.gameObject),(i=this.sharedMesh)!=null&&i.isMesh)(s=this.context.physics.engine)==null||s.addMeshCollider(this,this.sharedMesh,this.convex,hn(this.gameObject));else{const a=this.sharedMesh;if(a!=null&&a.isGroup){console.warn(`MeshCollider mesh is a group "${((r=this.sharedMesh)==null?void 0:r.name)||this.gameObject.name}", adding all children as colliders. This is currently not fully supported (colliders can not be removed from world again)`,this);for(const c in a.children){const l=a.children[c];l.isMesh&&((o=this.context.physics.engine)==null||o.addMeshCollider(this,l,this.convex,hn(this.gameObject)))}}}}}Yr([x()],um.prototype,"sharedMesh",2);Yr([x()],um.prototype,"convex",2);class zh extends aa{constructor(){super(...arguments);u(this,"center",new w(0,0,0));u(this,"radius",.5);u(this,"height",2)}onEnable(){var t;super.onEnable(),(t=this.context.physics.engine)==null||t.addCapsuleCollider(this,this.height,this.radius)}}Yr([x(w)],zh.prototype,"center",2);Yr([x()],zh.prototype,"radius",2);Yr([x()],zh.prototype,"height",2);var nre=Object.defineProperty,sre=Object.getOwnPropertyDescriptor,YR=(n,e,t,i)=>{for(var s=i>1?void 0:i?sre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&nre(e,t,s),s};class Dd extends Ie{constructor(){super(...arguments);u(this,"objectBounds",!1);u(this,"color");u(this,"isGizmo",!0);u(this,"_gizmoObject",null);u(this,"_boxHelper",null)}onEnable(){this.isGizmo&&!gA||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new rI(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=wR(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),Vn.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){var t;for(;this._boxHelper;)(t=this._boxHelper)==null||t.update(),yield}}YR([x()],Dd.prototype,"objectBounds",2);YR([x(ye)],Dd.prototype,"color",2);YR([x()],Dd.prototype,"isGizmo",2);class rre extends mG{constructor(e,t={}){super(e),e._simpleState__activeStates=[],e._simpleState__normalStyles={},e._simpleState__states=t,e._simpleState__statesProperties={};for(const i in t)for(const s in t[i])e._simpleState__statesProperties[s]||(e._simpleState__statesProperties[s]=[]),e._simpleState__statesProperties[s].push(i);for(const i of e._components)e._simpleState__statesProperties[i.id]&&(e._simpleState__normalStyles[i.id]=i.inline?i.inline:i._value);e.__overridedSet=e.set,e.set=this.storeSet.bind(e),e.renderStates=this.renderStates.bind(e),e.setupState=this.setupState.bind(e),e.setState=this.setState.bind(e),e.activatePseudoState=this.activatePseudoState.bind(e),e.deactivatePseudoState=this.deactivatePseudoState.bind(e),e.togglePseudoState=this.togglePseudoState.bind(e)}act(){}attach(){}detach(){}setupState(e,t){this._simpleState__states[e]=t;const i=[];for(const s in t)this._simpleState__statesProperties[s]||(this._simpleState__statesProperties[s]=[],i.push(s)),this._simpleState__statesProperties[s].push(e);for(const s of this._components)i.indexOf(s.id)>-1&&(this._simpleState__normalStyles[s.id]=s.inline?s.inline:s._value)}renderStates(){let e={...this._simpleState__normalStyles};for(const t in this._simpleState__states)this._simpleState__activeStates.indexOf(t)>-1&&(e={...e,...this._simpleState__states[t]});this.set(e,!1)}storeSet(e,t=!0){if(t)for(const i in e)this._simpleState__statesProperties[i]&&(this._simpleState__normalStyles[i]=e[i]);this.__overridedSet(e)}activatePseudoState(e){this._simpleState__activeStates.indexOf(e)===-1&&(this._simpleState__activeStates.push(e),this.renderStates())}deactivatePseudoState(e){const t=this._simpleState__activeStates.indexOf(e);t>-1&&(this._simpleState__activeStates.splice(t,1),this.renderStates())}togglePseudoState(e){const t=this._simpleState__activeStates.indexOf(e);t>-1?this._simpleState__activeStates.splice(t,1):this._simpleState__activeStates.push(e),this.renderStates()}setState(e){Array.isArray(e)?this._simpleState__activeStates=e:this._simpleState__activeStates=[e],this.renderStates()}}var ore=Object.defineProperty,are=Object.getOwnPropertyDescriptor,qH=(n,e,t,i)=>{for(var s=i>1?void 0:i?are(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&ore(e,t,s),s};class dm extends Ie{constructor(){super(...arguments);u(this,"effectColor");u(this,"effectDistance")}}qH([x(Ti)],dm.prototype,"effectColor",2);qH([x(ie)],dm.prototype,"effectDistance",2);var cre=Object.defineProperty,lre=Object.getOwnPropertyDescriptor,XA=(n,e,t,i)=>{for(var s=i>1?void 0:i?lre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&cre(e,t,s),s};const $C=se("debugui"),eE=se("debuguilayout");class JR{constructor(){u(this,"width");u(this,"height")}}class KR{constructor(){u(this,"x");u(this,"y");u(this,"width");u(this,"height")}}const pa=new w,tg=new Se,z0=new Ee,XH=class extends Pa{constructor(){super(...arguments);u(this,"_anchoredPosition");u(this,"sizeDelta",new ie(100,100));u(this,"pivot",new ie(.5,.5));u(this,"anchorMin",new ie(0,0));u(this,"anchorMax",new ie(1,1));u(this,"minWidth");u(this,"minHeight");u(this,"lastMatrix");u(this,"rectBlock");u(this,"_transformNeedsUpdate",!1);u(this,"_initialPosition");u(this,"_parentRectTransform");u(this,"_lastUpdateFrame",-1);u(this,"_lastAnchoring");u(this,"_createdBlocks",[]);u(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 ie),this._anchoredPosition}set anchoredPosition(e){this._anchoredPosition=e}get width(){let e=this.sizeDelta.x;if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const t=this._parentRectTransform.width,i=this.anchorMax.x-this.anchorMin.x;e=t*i,e+=this.sizeDelta.x}return this.minWidth!==void 0&&e<this.minWidth?this.minWidth:e}get height(){let e=this.sizeDelta.y;if(this.anchorMin.y!==this.anchorMax.y&&this._parentRectTransform){const t=this._parentRectTransform.height,i=this.anchorMax.y-this.anchorMin.y;e=t*i,e+=this.sizeDelta.y}return this.minHeight!==void 0&&e<this.minHeight?this.minHeight:e}awake(){super.awake(),this._anchoredPosition||(this._anchoredPosition=new ie),this.lastMatrix=new Se,this.rectBlock=new ge,this.rectBlock.name=this.name,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,zf(this,"_anchoredPosition",()=>{this.markDirty()}),zf(this,"sizeDelta",()=>{this.markDirty()}),zf(this,"pivot",()=>{this.markDirty()}),zf(this,"anchorMin",()=>{this.markDirty()}),zf(this,"anchorMax",()=>{this.markDirty()})}onEnable(){var e;super.onEnable(),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,(e=this.Canvas)==null||e.registerTransform(this)}onDisable(){var e;super.onDisable(),this.removeShadowComponent(),(e=this.Canvas)==null||e.unregisterTransform(this)}onParentRectTransformChanged(e){this._transformNeedsUpdate||this.onApplyTransform(eE?`${e.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(eE&&console.warn("RectTransform markDirty()",this.name),this._transformNeedsUpdate=!0,this._lastUpdateFrame=-1)}updateTransform(){(this._transformNeedsUpdate||!this.lastMatrix.equals(this.gameObject.matrix))&&this.canUpdate()&&this.onApplyTransform(this._transformNeedsUpdate?"Marked dirty":"Matrix changed")}canUpdate(){return this._transformNeedsUpdate&&this.activeAndEnabled&&this._lastUpdateFrame!==this.context.time.frame}onApplyTransform(e){var s;if(this.context.time.frameCount===this._lastUpdateFrame)return;this._lastUpdateFrame=this.context.time.frameCount;const t=this.shadowComponent;if(!t)return;this.gameObject.parent?this._parentRectTransform=le.getComponentInParent(this.gameObject.parent,XH):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,eE&&console.warn("RectTransform โ†’ ApplyTransform",this.name+" because "+e),this.isRoot()?this.Root.screenspace||(t.rotation.y=Math.PI):(t.matrix.identity(),t.matrixAutoUpdate=!1,pa.set(0,0,0),this.applyPivot(pa),t.matrix.setPosition(pa.x,pa.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(z0.copy(this.gameObject.quaternion),z0.x*=-1,z0.z*=-1,tg.makeRotationFromQuaternion(z0),t.matrix.premultiply(tg)),pa.set(0,0,0),this.applyAnchoring(pa),(s=this.Canvas)!=null&&s.screenspace?pa.z+=.1:pa.z+=.01,tg.identity(),tg.setPosition(pa.x,pa.y,pa.z),t.matrix.premultiply(tg),t.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const i=!0;for(const r of CR(this.gameObject,Pa,i,1)){if(r===this||!r.activeAndEnabled)continue;const o=r;o.onParentRectTransformChanged&&o.onParentRectTransformChanged(this)}}applyAnchoring(e){this._lastAnchoring||(this._lastAnchoring=new ie);const t=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=t.x,this.gameObject.position.y+=t.y,this._lastAnchoring.copy(this._anchoredPosition),e.x+=this._initialPosition.x-this.gameObject.position.x,e.y+=this._initialPosition.y-this.gameObject.position.y,e.z+=this._initialPosition.z-this.gameObject.position.z;const i=this._parentRectTransform;if(i){let s=0;const r=1-this.anchorMax.y-this.anchorMin.y;s-=i.height*.5*r,e.y+=s;let o=0;const a=1-this.anchorMax.x-this.anchorMin.x;o-=i.width*.5*a,e.x+=o}}applyPivot(e){if(this.pivot&&!this.isRoot()){const t=this.pivot.x-.5;e.x-=t*this.sizeDelta.x*this.gameObject.scale.x;const i=this.pivot.y-.5;e.y-=i*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){const e={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:0,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(e),e}ensureValidSize(e,t=1e-4){return e.width<=0&&(e.width=t),e.height<=0&&(e.height=1e-4),e}createNewBlock(e){e={...this.getBasicOptions(),...e},$C&&console.log(this.name,e);const t=new fR(e);return this._createdBlocks.push(t),t}createNewText(e){$C&&console.log(e),e={...this.getBasicOptions(),...e},$C&&console.log(this.name,e);const t=new pR(e);return this._createdTextBlocks.push(t),t}};let Tr=XH;XA([x(ie)],Tr.prototype,"anchoredPosition",1);XA([x(ie)],Tr.prototype,"sizeDelta",2);XA([x(ie)],Tr.prototype,"pivot",2);XA([x(ie)],Tr.prototype,"anchorMin",2);XA([x(ie)],Tr.prototype,"anchorMax",2);var hre=Object.defineProperty,ure=Object.getOwnPropertyDescriptor,YH=(n,e,t,i)=>{for(var s=i>1?void 0:i?ure(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&hre(e,t,s),s};const G0={backgroundColor:new ye(1,1,1),backgroundOpacity:1,borderColor:new ye(1,1,1),borderOpacity:1};var FE;const Q_=(FE=class extends Pa{constructor(){super(...arguments);u(this,"_alphaFactor",1);u(this,"sRGBColor",new ye(1,0,1));u(this,"raycastTarget",!0);u(this,"uiObject",null);u(this,"_color",null);u(this,"_rect",null);u(this,"_stateManager",null);u(this,"_currentlyCreatingPanel",!1)}get isGraphic(){return!0}get color(){return this._color||(this._color=new Ti(1,1,1,1)),this._color}set color(e){(!this._color||this._color.r!==e.r||this._color.g!==e.g||this._color.b!==e.b||this._color.alpha!==e.alpha)&&(this._color||(this._color=new Ti(1,1,1,1)),this._color.copy(e),this.onColorChanged())}setAlphaFactor(e){this._alphaFactor=e,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}onColorChanged(){this.uiObject&&(this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),G0.backgroundColor=this.sRGBColor,G0.backgroundOpacity=this._color.alpha*this._alphaFactor,this.applyEffects(G0,this._alphaFactor),this.uiObject.set(G0),this.markDirty())}get m_Color(){return this._color}get rectTransform(){if(this._rect||(this._rect=le.getComponent(this.gameObject,Tr)),!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 e;(e=this.uiObject)==null||e.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(){super.__internalNewInstanceCreated(),this._rect=null,this.uiObject=null,this._color&&(this._color=this._color.clone())}setState(e){this.makePanel(),this.uiObject&&(this.uiObject.setState(e),this==null||this.markDirty())}setupState(e){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new rre(this.uiObject)),this.uiObject.setupState(e.state,e.attributes))}setOptions(e){this.makePanel(),this.uiObject&&this.uiObject.set(e)}awake(){super.awake(),this.makePanel(),zf(this,"_color",()=>Gne(this,this.onColorChanged))}onEnable(){var e;super.onEnable(),this.uiObject&&((e=this.rectTransform.shadowComponent)==null||e.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 e=.015,t={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:e};this.onBeforeCreate(t),this.applyEffects(t),this.onCreate(t),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated(),this.onColorChanged()}onBeforeCreate(e){}onCreate(e){this.uiObject=this.rectTransform.createNewBlock(e),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(e,t=1){var s;const i=(s=this.gameObject)==null?void 0:s.getComponent(dm);i&&(i.effectDistance&&(e.borderWidth=Math.max(Math.abs(i.effectDistance.x),Math.abs(i.effectDistance.y))),i.effectColor&&(e.borderColor=i.effectColor,e.borderOpacity=i.effectColor.alpha*t))}async setTexture(e){if(this.setOptions({backgroundOpacity:0}),e){if(Q_.textureCache.has(e))e=Q_.textureCache.get(e);else if(!e.isRenderTargetTexture){const t=e.clone();t.colorSpace=ki,Q_.textureCache.set(e,t),e=t}this.setOptions({backgroundImage:e,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"})}else this.setOptions({backgroundImage:null,borderRadius:0,backgroundOpacity:this.color.alpha});this.markDirty()}onAfterAddedToScene(){super.onAfterAddedToScene(),this.shadowComponent&&(this.shadowComponent.offset=this.shadowComponent.position.z)}},u(FE,"textureCache",new Map),FE);let Od=Q_;YH([x(Ti)],Od.prototype,"color",1);YH([x()],Od.prototype,"raycastTarget",2);class YA extends Od{constructor(){super(...arguments);u(this,"_flippedObject",!1)}onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var dre=Object.defineProperty,fre=Object.getOwnPropertyDescriptor,Iw=(n,e,t,i)=>{for(var s=i>1?void 0:i?fre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&dre(e,t,s),s};let ZR=class{constructor(){u(this,"texture",null);u(this,"rect")}};Iw([x(Ht)],ZR.prototype,"texture",2);let fm=class extends YA{constructor(){super(...arguments);u(this,"_sprite");u(this,"pixelsPerUnitMultiplier",1)}set image(t){this.sprite||(this.sprite=new ZR),this.sprite.texture=t,this.onAfterCreated()}get image(){return this.sprite?this.sprite.texture:null}get sprite(){return this._sprite}set sprite(t){this._sprite!==t&&(this._sprite=t,this.onAfterCreated())}isBuiltinSprite(){var t,i,s,r,o,a,c,l,h,d,f;switch((i=(t=this.sprite)==null?void 0:t.texture)==null?void 0:i.name){case"InputFieldBackground":case"UISprite":case"Background":case"Knob":return!0}return!((o=(r=(s=this.sprite)==null?void 0:s.texture)==null?void 0:r.name)!=null&&o.length)&&((l=(c=(a=this.sprite)==null?void 0:a.texture)==null?void 0:c.image)==null?void 0:l.width)===32&&((f=(d=(h=this.sprite)==null?void 0:h.texture)==null?void 0:d.image)==null?void 0:f.height)===32}onBeforeCreate(t){var i,s;super.onBeforeCreate(t),this.isBuiltinSprite()&&(t.borderRadius=5/this.pixelsPerUnitMultiplier,((s=(i=this.sprite)==null?void 0:i.texture)==null?void 0:s.name)==="Knob"&&(t.borderRadius=999))}onAfterCreated(){var t;this.__didAwake&&(super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture((t=this.sprite)==null?void 0:t.texture))}};Iw([x(ZR)],fm.prototype,"sprite",1);Iw([x()],fm.prototype,"pixelsPerUnitMultiplier",2);class Rw extends YA{constructor(){super(...arguments);u(this,"_mainTexture")}get mainTexture(){return this._mainTexture}set mainTexture(t){this._mainTexture!==t&&(this._mainTexture=t,this.onAfterCreated())}onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),this.setTexture(this.mainTexture))}}Iw([x(Ht)],Rw.prototype,"mainTexture",1);var pre=Object.defineProperty,mre=Object.getOwnPropertyDescriptor,So=(n,e,t,i)=>{for(var s=i>1?void 0:i?mre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&pre(e,t,s),s};const Cu=se("debugbutton");class kd{constructor(){u(this,"colorMultiplier");u(this,"disabledColor");u(this,"fadeDuration");u(this,"highlightedColor");u(this,"normalColor");u(this,"pressedColor");u(this,"selectedColor")}}So([x()],kd.prototype,"colorMultiplier",2);So([x(Ti)],kd.prototype,"disabledColor",2);So([x()],kd.prototype,"fadeDuration",2);So([x(Ti)],kd.prototype,"highlightedColor",2);So([x(Ti)],kd.prototype,"normalColor",2);So([x(Ti)],kd.prototype,"pressedColor",2);So([x(Ti)],kd.prototype,"selectedColor",2);class Fl extends Ie{constructor(){super(...arguments);u(this,"onClick");u(this,"_isHovered",0);u(this,"colors");u(this,"transition");u(this,"animationTriggers");u(this,"animator");u(this,"_interactable",!0);u(this,"_requestedAnimatorTrigger");u(this,"_isInit",!1);u(this,"_image")}onPointerEnter(t){var i,s;this._isHovered+=1,Cu&&console.warn("Button Enter",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&&((s=this._image)==null||s.setState("hovered")),this.context.input.setCursorPointer())}onPointerExit(){var t,i;this._isHovered-=1,Cu&&console.log("Button Exit",this._isHovered,(t=this.animationTriggers)==null?void 0:t.highlightedTrigger,this.animator),this.interactable&&(this._isHovered>0||(this._isHovered=0,this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&((i=this._image)==null||i.setState("normal")),this.context.input.setCursorNormal()))}onPointerDown(t){var i,s;Cu&&console.log("Button Down",(i=this.animationTriggers)==null?void 0:i.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&((s=this._image)==null||s.setState("pressed")))}onPointerUp(t){var i,s;Cu&&console.warn("Button Up",(i=this.animationTriggers)==null?void 0:i.highlightedTrigger,this.animator,this._isHovered),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this._isHovered?this.animationTriggers.highlightedTrigger:this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&((s=this._image)==null||s.setState(this._isHovered?"hovered":"normal")))}onPointerClick(t){if(this.interactable&&!(t.button!==0&&t.event.pointerType===SI.Mouse)&&(Cu&&(console.warn("Button Click",this.onClick),xn("CLICKED button "+this.name+" at "+this.context.time.frameCount)),this.onClick&&this.onClick.listenerCount>0&&(this.onClick.invoke(),t.use(),Cu))){const i=this.gameObject.worldPosition;i.add(this.gameObject.worldUp.multiplyScalar(1+Math.random()*.5)),It.DrawLabel(i,"CLICK:"+Date.now(),.1,1+Math.random()*.5)}}set interactable(t){this._interactable=t,this._image&&(this._image.setInteractable(t),t?this._image.setState("normal"):this._image.setState("disabled"))}get interactable(){return this._interactable}set_interactable(t){this.interactable=t}awake(){super.awake(),Cu&&console.log(this),this._isInit=!1,this.init()}start(){var t;(t=this._image)==null||t.setInteractable(this.interactable),this.gameObject.getComponentInParent(UA)||this.gameObject.addComponent(vw)}onEnable(){super.onEnable()}onDestroy(){this._isHovered&&this.context.input.setCursorNormal()}*setAnimatorTriggerAtEndOfFrame(t){var i;this._requestedAnimatorTrigger=t,yield,yield,this._requestedAnimatorTrigger==t&&((i=this.animator)==null||i.SetTrigger(t))}init(){this._isInit||(this._isInit=!0,this._image=le.getComponent(this.gameObject,fm),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(t){var p,m,g,y,v;t.setInteractable(this.interactable);const i=this.getFinalColor(t.color,(p=this.colors)==null?void 0:p.normalColor),s={state:"normal",attributes:{backgroundColor:i,backgroundOpacity:i.alpha}};t.setupState(s);const r=this.getFinalColor(t.color,(m=this.colors)==null?void 0:m.highlightedColor),o={state:"hovered",attributes:{backgroundColor:r,backgroundOpacity:r.alpha}};t.setupState(o);const a=this.getFinalColor(t.color,(g=this.colors)==null?void 0:g.pressedColor),c={state:"pressed",attributes:{backgroundColor:a,backgroundOpacity:a.alpha}};t.setupState(c);const l=this.getFinalColor(t.color,(y=this.colors)==null?void 0:y.selectedColor),h={state:"selected",attributes:{backgroundColor:l,backgroundOpacity:l.alpha}};t.setupState(h);const d=this.getFinalColor(t.color,(v=this.colors)==null?void 0:v.disabledColor),f={state:"disabled",attributes:{backgroundColor:d,backgroundOpacity:d.alpha}};t.setupState(f)}getFinalColor(t,i){return i?t.clone().multiply(i).convertLinearToSRGB():t.clone().convertLinearToSRGB()}}So([x(gs)],Fl.prototype,"onClick",2);So([x()],Fl.prototype,"colors",2);So([x()],Fl.prototype,"transition",2);So([x()],Fl.prototype,"animationTriggers",2);So([x(Us)],Fl.prototype,"animator",2);So([x()],Fl.prototype,"interactable",1);var gre=Object.defineProperty,vre=Object.getOwnPropertyDescriptor,Wn=(n,e,t,i)=>{for(var s=i>1?void 0:i?vre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&gre(e,t,s),s};const l2=se("debuguilayout");class Jh{constructor(){u(this,"left",0);u(this,"right",0);u(this,"top",0);u(this,"bottom",0)}get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}Wn([x()],Jh.prototype,"left",2);Wn([x()],Jh.prototype,"right",2);Wn([x()],Jh.prototype,"top",2);Wn([x()],Jh.prototype,"bottom",2);class Co extends Ie{constructor(){super(...arguments);u(this,"_rectTransform",null);u(this,"_needsUpdate",!1);u(this,"childAlignment",0);u(this,"reverseArrangement",!1);u(this,"spacing",0);u(this,"padding");u(this,"minWidth",0);u(this,"minHeight",0);u(this,"flexibleHeight",0);u(this,"flexibleWidth",0);u(this,"preferredHeight",0);u(this,"preferredWidth",0)}get rectTransform(){return this._rectTransform}onParentRectTransformChanged(t){this._needsUpdate=!0}get isDirty(){return this._needsUpdate}get isLayoutGroup(){return!0}updateLayout(){this._rectTransform&&(l2&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}start(){this._needsUpdate=!0}onEnable(){l2&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(Tr);const t=this.gameObject.getComponentInParent(Ns);t&&t.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const t=this.gameObject.getComponentInParent(Ns);t&&t.unregisterLayoutGroup(this)}set m_Spacing(t){t!==this.spacing&&(this._needsUpdate=!0,this.spacing=t)}get m_Spacing(){return this.spacing}}Wn([x()],Co.prototype,"childAlignment",2);Wn([x()],Co.prototype,"reverseArrangement",2);Wn([x()],Co.prototype,"spacing",2);Wn([x(Jh)],Co.prototype,"padding",2);Wn([x()],Co.prototype,"minWidth",2);Wn([x()],Co.prototype,"minHeight",2);Wn([x()],Co.prototype,"flexibleHeight",2);Wn([x()],Co.prototype,"flexibleWidth",2);Wn([x()],Co.prototype,"preferredHeight",2);Wn([x()],Co.prototype,"preferredWidth",2);class Kh extends Co{constructor(){super(...arguments);u(this,"childControlHeight",!0);u(this,"childControlWidth",!0);u(this,"childForceExpandHeight",!1);u(this,"childForceExpandWidth",!1);u(this,"childScaleHeight",!1);u(this,"childScaleWidth",!1)}onCalculateLayout(t){var I;const i=this.primaryAxis,s=t.width;let r=s;const o=t.height;let a=o;r-=this.padding.horizontal,a-=this.padding.vertical,i==="x"?this.padding.horizontal:this.padding.vertical;const c=i==="x",l=c?"y":"x",h=c?this.childControlWidth:this.childControlHeight,d=c?this.childControlHeight:this.childControlWidth,f=c?this.childForceExpandWidth:this.childForceExpandHeight,p=c?this.childForceExpandHeight:this.childForceExpandWidth,m=c?a:r,g=c?s:o,y=.5*(c?this.childAlignment%3:Math.floor(this.childAlignment/3));let v=0;c?v+=this.padding.left:v+=this.padding.top;let A=0,_=0;for(let S=0;S<this.gameObject.children.length;S++){const M=this.gameObject.children[S],D=le.getComponent(M,Tr);D!=null&&D.activeAndEnabled&&(_+=1,c?A+=D.width:A+=D.height)}let b=0;const C=this.spacing*(_-1);if(f||h){let S=0;c?S=r-=C:S=a-=C,_>0&&(b=S/_)}let E=0;E+=this.padding.left,E-=this.padding.right,y!==0&&(v=g-A,v*=y,v-=C*y,c?(v-=this.padding.right*y,v+=this.padding.left*(1-y),v<this.padding.left&&(v=this.padding.left)):(v-=this.padding.bottom*y,v+=this.padding.top*(1-y),v<this.padding.top&&(v=this.padding.top)));let T=1;for(let S=0;S<this.gameObject.children.length;S++){const M=this.gameObject.children[S],D=le.getComponent(M,Tr);if(D!=null&&D.activeAndEnabled){(I=D.pivot)==null||I.set(.5,.5),D.anchorMin.set(0,1),D.anchorMax.set(0,1);const G=s*.5+E*.5;D.anchoredPosition.x!==G&&(D.anchoredPosition.x=G);const Q=o*-.5;D.anchoredPosition.y!==Q&&(D.anchoredPosition.y=Q),p&&d&&D.sizeDelta[l]!==m&&(D.sizeDelta[l]=m),f&&h&&D.sizeDelta[i]!==b&&(D.sizeDelta[i]=b);const L=c?D.width:D.height,H=L*.5;if(v+=H,f){const U=b*T-b*.5;U>v&&(v=U-b*.5+L+this.padding.left,v-=H)}let O=v;i==="y"&&(O=-O),D.anchoredPosition[i]!==O&&(D.anchoredPosition[i]=O),v+=H,v+=this.spacing,T+=1}}}}Wn([x()],Kh.prototype,"childControlHeight",2);Wn([x()],Kh.prototype,"childControlWidth",2);Wn([x()],Kh.prototype,"childForceExpandHeight",2);Wn([x()],Kh.prototype,"childForceExpandWidth",2);Wn([x()],Kh.prototype,"childScaleHeight",2);Wn([x()],Kh.prototype,"childScaleWidth",2);class $R extends Kh{get primaryAxis(){return"y"}}class eP extends Kh{get primaryAxis(){return"x"}}class tP extends Co{onCalculateLayout(){}}var Are=Object.defineProperty,yre=Object.getOwnPropertyDescriptor,Rc=(n,e,t,i)=>{for(var s=i>1?void 0:i?yre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Are(e,t,s),s},JH=(n=>(n[n.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",n[n.ScreenSpaceCamera=1]="ScreenSpaceCamera",n[n.WorldSpace=2]="WorldSpace",n[n.Undefined=-1]="Undefined",n))(JH||{});const tE=se("debuguilayout"),KH=class extends FA{constructor(){super(...arguments);u(this,"_renderOnTop");u(this,"_depthWrite",!1);u(this,"_doubleSided",!0);u(this,"_castShadows",!1);u(this,"_receiveShadows",!1);u(this,"_renderMode",-1);u(this,"_rootCanvas");u(this,"_scaleFactor",1);u(this,"worldCamera");u(this,"planeDistance",-1);u(this,"_boundRenderSettingsChanged",this.onRenderSettingsChanged.bind(this));u(this,"previousParent",null);u(this,"_lastMatrixWorld",null);u(this,"_rectTransforms",[]);u(this,"_layoutGroups",new Map);u(this,"_receivers",[]);u(this,"onBeforeRenderRoutine",()=>{var e,t,i,s;if(this.previousParent=this.gameObject.parent,((e=this.context.xr)!=null&&e.isVR||(t=this.context.xr)!=null&&t.isPassThrough)&&this.screenspace){this.gameObject.visible=!1,this.gameObject.removeFromParent();return}this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),(i=this.shadowComponent)==null||i.updateMatrixWorld(!0),(s=this.shadowComponent)==null||s.updateWorldMatrix(!0,!0),this.invokeBeforeRenderEvents(),jr.ensureUpdateMeshUI(nk,this.context))});u(this,"onAfterRenderRoutine",()=>{var e,t,i,s,r;if(((e=this.context.xr)!=null&&e.isVR||(t=this.context.xr)!=null&&t.isPassThrough)&&this.screenspace){(i=this.previousParent)==null||i.add(this.gameObject);return}if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){if(this.screenspace){const c=this.context.mainCamera;c==null||c.add(this.gameObject)}else this.previousParent.add(this.gameObject);const o=this.context.renderer.autoClear,a=this.context.renderer.autoClearColor;this.context.renderer.autoClear=!1,this.context.renderer.autoClearColor=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),(s=this.shadowComponent)==null||s.updateMatrixWorld(!0),this.invokeBeforeRenderEvents(),jr.ensureUpdateMeshUI(nk,this.context,!0),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=o,this.context.renderer.autoClearColor=a,this.previousParent.add(this.gameObject)}(r=this._lastMatrixWorld)==null||r.copy(this.gameObject.matrixWorld)});u(this,"_updateRenderSettingsRoutine");u(this,"_activeRenderMode",-1);u(this,"_lastWidth",-1);u(this,"_lastHeight",-1)}get isCanvas(){return!0}get screenspace(){return this.renderMode!==2}set renderOnTop(e){e!==this._renderOnTop&&(this._renderOnTop=e,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop!==void 0?this._renderOnTop:!!(this.screenspace&&this._renderMode===0)}set depthWrite(e){this._depthWrite!==e&&(this._depthWrite=e,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}set doubleSided(e){this._doubleSided!==e&&(this._doubleSided=e,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}set castShadows(e){this._castShadows!==e&&(this._castShadows=e,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}set receiveShadows(e){this._receiveShadows!==e&&(this._receiveShadows=e,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}get renderMode(){return this._renderMode}set renderMode(e){this._renderMode!==e&&(this._renderMode=e,this.onRenderSettingsChanged())}set rootCanvas(e){this._rootCanvas instanceof KH||(this._rootCanvas=e)}get rootCanvas(){return this._rootCanvas}get scaleFactor(){return this._scaleFactor}set scaleFactor(e){this._scaleFactor=e}awake(){var e;this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,tE&&console.log("Canvas.Awake()",((e=this.previousParent)==null?void 0:e.name)+"/"+this.gameObject.name),super.awake()}start(){this.onUpdateRenderMode()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new Se,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 e=this.context.pre_render_callbacks.indexOf(this.onBeforeRenderRoutine);e!==-1&&this.context.pre_render_callbacks.splice(e,1);const t=this.context.post_render_callbacks.indexOf(this.onAfterRenderRoutine);t!==-1&&this.context.post_render_callbacks.splice(t,1)}registerTransform(e){this._rectTransforms.push(e)}unregisterTransform(e){const t=this._rectTransforms.indexOf(e);t!==-1&&this._rectTransforms.splice(t,1)}registerLayoutGroup(e){const t=e.gameObject;this._layoutGroups.set(t,e)}unregisterLayoutGroup(e){const t=e.gameObject;this._layoutGroups.delete(t)}registerEventReceiver(e){this._receivers.push(e)}unregisterEventReceiver(e){const t=this._receivers.indexOf(e);t!==-1&&this._receivers.splice(t,1)}async onEnterXR(e){this.screenspace?(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!1):(this.gameObject.visible=!1,await HU(1).then(()=>{this.gameObject.visible=!0}))}onLeaveXR(e){this.screenspace&&(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!0)}invokeBeforeRenderEvents(){var e;for(const t of this._receivers)(e=t.onBeforeCanvasRender)==null||e.call(t,this)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new Se);const e=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);tE&&e&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);const t=!1;for(const i of this._rectTransforms){e&&i.markDirty();let s=this._layoutGroups.get(i.gameObject);i.isDirty&&!s&&(s=i.gameObject.getComponentInParent(Co)),(i.isDirty||s!=null&&s.isDirty)&&(tE&&!t&&console.log("CANVAS UPDATE ### "+i.name+" ##################################### "+this.context.time.frame),s==null||s.updateLayout(),i.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),Vn.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),zb(this.shadowComponent,this);for(const e of le.getComponentsInChildren(this.gameObject,Pa))zb(e.shadowComponent,this)}}onUpdateRenderMode(e=!1){if(!e&&this._renderMode===this._activeRenderMode&&this._lastWidth===this.context.domWidth&&this._lastHeight===this.context.domHeight)return;this._activeRenderMode=this._renderMode;let t=this.context.mainCameraComponent,i=10;switch(t&&t.nearClipPlane>0&&t.farClipPlane>0&&(i=rt.lerp(t.nearClipPlane,t.farClipPlane,.01)),this._renderMode===1&&(this.worldCamera&&(t=this.worldCamera),this.planeDistance>0&&(i=this.planeDistance)),this._renderMode){case 0:case 1:if(this._lastWidth=this.context.domWidth,this._lastHeight=this.context.domHeight,!t)return;const s=i+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-s,this.gameObject.quaternion.identity();const r=this.gameObject.getComponent(Tr);let o=!1;r.sizeDelta.x!==this.context.domWidth&&(o=!0),r.sizeDelta.y!==this.context.domHeight&&(o=!0);const a=t.fieldOfView*Math.PI/180,c=2*Math.tan(a/2)*Math.abs(s);this.gameObject.scale.x=c/this.context.domHeight,this.gameObject.scale.y=c/this.context.domHeight,this.gameObject.scale.z=.01,o&&(r.sizeDelta.x=this.context.domWidth,r.sizeDelta.y=this.context.domHeight,r==null||r.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};let Ns=KH;Rc([x()],Ns.prototype,"renderOnTop",1);Rc([x()],Ns.prototype,"depthWrite",1);Rc([x()],Ns.prototype,"doubleSided",1);Rc([x()],Ns.prototype,"castShadows",1);Rc([x()],Ns.prototype,"receiveShadows",1);Rc([x()],Ns.prototype,"renderMode",1);Rc([x(Ns)],Ns.prototype,"rootCanvas",1);Rc([x()],Ns.prototype,"scaleFactor",1);Rc([x(Yi)],Ns.prototype,"worldCamera",2);Rc([x()],Ns.prototype,"planeDistance",2);var _re=Object.defineProperty,bre=Object.getOwnPropertyDescriptor,iP=(n,e,t,i)=>{for(var s=i>1?void 0:i?bre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&_re(e,t,s),s};class Gh extends Ie{constructor(){super(...arguments);u(this,"_alpha",1);u(this,"interactable",!0);u(this,"blocksRaycasts",!0);u(this,"_isDirty",!1);u(this,"_buffer",[])}get alpha(){return this._alpha}set alpha(t){t!==this._alpha&&(this._alpha=t,this.markDirty())}get isCanvasGroup(){return!0}markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),Vn.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}applyChangesNow(){for(const t of le.getComponentsInChildren(this.gameObject,Pa,this._buffer)){const i=t;i.setAlphaFactor&&i.setAlphaFactor(this._alpha)}}}iP([x()],Gh.prototype,"alpha",1);iP([x()],Gh.prototype,"interactable",2);iP([x()],Gh.prototype,"blocksRaycasts",2);var xre=Object.defineProperty,wre=Object.getOwnPropertyDescriptor,mn=(n,e,t,i)=>{for(var s=i>1?void 0:i?wre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&xre(e,t,s),s};function JA(n){n&&(n.getComponentInParent(UA)||(Mt()&&console.warn("Create Raycaster on "+n.name+" because no raycaster was found in the hierarchy"),n.addNewComponent(yo)))}class Ld extends Ie{constructor(){super(...arguments);u(this,"object");u(this,"target");u(this,"duration",1);u(this,"relativeMotion",!1);u(this,"coroutine",null);u(this,"targetPos",new w);u(this,"targetRot",new Ee);u(this,"targetScale",new w)}start(){JA(this.gameObject)}onPointerClick(t){t.use(),this.coroutine&&this.stopCoroutine(this.coroutine),this.relativeMotion?this.coroutine=this.startCoroutine(this.moveRelative()):this.coroutine=this.startCoroutine(this.moveToTarget())}*moveToTarget(){if(!this.target||!this.object)return;const t=Dt(this.object).clone(),i=Dt(this.target).clone(),s=Di(this.object).clone(),r=Di(this.target).clone(),o=hn(this.object).clone(),a=hn(this.target).clone(),c=t.distanceTo(i),l=s.angleTo(r),h=o.distanceTo(a);if(c<.01&&l<.01&&h<.01){sr(this.object,i),ea(this.object,r),kv(this.object,a),this.coroutine=null;return}let d=0,f=0;for(;d<1;)d+=this.context.time.deltaTime/this.duration,d>1&&(d=1),f=d<.5?4*d*d*d:1-Math.pow(-2*d+2,3)/2,this.targetPos.lerpVectors(t,i,f),this.targetRot.slerpQuaternions(s,r,f),this.targetScale.lerpVectors(o,a,f),sr(this.object,this.targetPos),ea(this.object,this.targetRot),kv(this.object,this.targetScale),yield;this.coroutine=null}*moveRelative(){if(!this.target||!this.object)return;const t=this.object.position.clone(),i=this.object.quaternion.clone(),s=this.object.scale.clone(),r=this.target.position.clone(),o=this.target.quaternion.clone(),a=this.target.scale.clone();r.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(r),this.targetRot.copy(this.object.quaternion).multiply(o),this.targetScale.copy(this.object.scale).multiply(a);let c=0,l=0;for(;c<1;)c+=this.context.time.deltaTime/this.duration,c>1&&(c=1),l=c<.5?4*c*c*c:1-Math.pow(-2*c+2,3)/2,this.object.position.lerpVectors(t,this.targetPos,l),this.object.quaternion.slerpQuaternions(i,this.targetRot,l),this.object.scale.lerpVectors(s,this.targetScale,l),yield;this.coroutine=null}beforeCreateDocument(t){var i;if(this.target&&this.object&&this.gameObject){const s=new $n("Move to "+((i=this.target)==null?void 0:i.name),Os.tapTrigger(this.gameObject),di.transformAction(this.object,this.target,this.duration,this.relativeMotion?TM.Relative:TM.Absolute));t.addBehavior(s)}}}mn([x(ge)],Ld.prototype,"object",2);mn([x(ge)],Ld.prototype,"target",2);mn([x()],Ld.prototype,"duration",2);mn([x()],Ld.prototype,"relativeMotion",2);var h_;const Zc=(h_=class extends Ie{constructor(){super(...arguments);u(this,"materialToSwitch");u(this,"variantMaterial");u(this,"fadeDuration",0);u(this,"_objectsWithThisMaterial",[]);u(this,"selfModel");u(this,"targetModels")}awake(){if(this.variantMaterial&&this.materialToSwitch){const e=le.findObjectsOfType(Sn);for(const t of e)for(let i=0;i<t.sharedMaterials.length;i++){const s=t.sharedMaterials[i];if(s===this.materialToSwitch){if(t.gameObject instanceof me)this._objectsWithThisMaterial.push(t.gameObject);else if(t.gameObject instanceof xr)for(const r of t.gameObject.children)r instanceof me&&r.material===s&&this._objectsWithThisMaterial.push(r);break}}}}start(){JA(this.gameObject)}onPointerClick(e){if(e.use(),!!this.variantMaterial)for(let t=0;t<this._objectsWithThisMaterial.length;t++){const i=this._objectsWithThisMaterial[t];i.material=this.variantMaterial}}async beforeCreateDocument(e,t){this.targetModels=[],Zc._materialTriggersPerId={},Zc.variantSwitchIndex=0,this.materialToSwitch&&await ao.assignTextureLOD(this.context,this.sourceId,this.materialToSwitch,0),this.variantMaterial&&await ao.assignTextureLOD(this.context,this.sourceId,this.variantMaterial,0)}createBehaviours(e,t,i){this._objectsWithThisMaterial.find(r=>r.uuid===t.uuid)&&this.targetModels.push(t),this.gameObject.uuid===t.uuid&&(this.selfModel=t,this.materialToSwitch&&(Zc._materialTriggersPerId[this.materialToSwitch.uuid]||(Zc._materialTriggersPerId[this.materialToSwitch.uuid]=[]),Zc._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(e,t){if(!this.materialToSwitch)return;const i=Zc._materialTriggersPerId[this.materialToSwitch.uuid];if(i){const s={};for(const r of i){const o=r.createVariants();o&&o.length>0&&(s[r.selfModel.uuid]=o)}for(const r of i){const o=[];for(const a in s)a!==r.selfModel.uuid&&o.push(...s[a]);r.createAndAttachBehaviors(e,s[r.selfModel.uuid],o)}}delete Zc._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(e,t,i){const s=[],r=[],o=Math.max(0,this.fadeDuration);r.push(di.fadeAction([...this.targetModels,...i],o,!1)),s.push(di.fadeAction(t,o,!1)),r.push(di.fadeAction(t,o,!0)),e.addBehavior(new $n("Select_"+this.selfModel.name,Os.tapTrigger(this.selfModel),di.parallel(...r))),e.addBehavior(new $n("StartHidden_"+this.selfModel.name,Os.sceneStartTrigger(),di.parallel(...s)))}createVariants(){if(!this.variantMaterial)return null;const e=[];for(const t of this.targetModels){const i=t.clone();i.name+=" variant_"+this.variantMaterial.name+"_"+Zc.variantSwitchIndex++,i.name=i.name.replace(/\s/g,"_"),i.material=this.variantMaterial,i.geometry=t.geometry,i.matrix=t.matrix,(!t.parent||!t.parent.isEmpty())&&Qr.createEmptyParent(t),t.parent&&t.parent.add(i),e.push(i)}return e}},u(h_,"_materialTriggersPerId",{}),u(h_,"variantSwitchIndex",0),h_);let pm=Zc;mn([x(Gt)],pm.prototype,"materialToSwitch",2);mn([x(Gt)],pm.prototype,"variantMaterial",2);mn([x()],pm.prototype,"fadeDuration",2);var Of;const cn=(Of=class extends Ie{constructor(){super(...arguments);u(this,"target");u(this,"toggleOnClick",!1);u(this,"targetState",!0);u(this,"hideSelf",!0);u(this,"selfModel");u(this,"selfModelClone");u(this,"targetModel");u(this,"toggleModel");u(this,"stateBeforeCreatingDocument",!1);u(this,"targetStateBeforeCreatingDocument",!1)}start(){JA(this.gameObject)}onPointerClick(e){e.use(),!this.toggleOnClick&&this.hideSelf&&(this.gameObject.visible=!1),this.target&&(this.target.visible=this.toggleOnClick?!this.target.visible:this.targetState)}createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t,this.selfModelClone=t.clone())}beforeCreateDocument(){this.target&&(this.gameObject[cn.wasVisible]===void 0&&(this.gameObject[cn.wasVisible]=this.gameObject.activeSelf),this.target[cn.wasVisible]===void 0&&(this.target[cn.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[cn.wasVisible],this.targetStateBeforeCreatingDocument=this.target[cn.wasVisible],this.gameObject.visible=!0,this.target.visible=!0)}afterCreateDocument(e,t){if(!this.target)return;this.targetModel=t.document.findById(this.target.uuid);const i=this.selfModel;if(this.selfModel&&this.targetModel){let s=this.selfModel,r=this.targetState;if(this.toggleOnClick)if(r=!this.targetStateBeforeCreatingDocument,!this.selfModelClone.geometry)(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&EH.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[cn.toggleClone]){const c=this.selfModelClone.clone();c.matrix.identity(),c.name+="_toggle"+cn.clonedToggleIndex++,i.add(c),this.gameObject[cn.toggleClone]=c,console.warn("USDZExport: Toggle "+this.gameObject.name+" doesn't have geometry. It will be deep cloned and nested behaviours will likely not work.")}const a=this.gameObject[cn.toggleClone];if(!this.gameObject[cn.reverseToggleClone]){const c=this.selfModelClone.clone();c.matrix.identity(),c.name+="_toggleReverse"+cn.clonedToggleIndex++,i.add(c),this.gameObject[cn.reverseToggleClone]=c}this.toggleModel=this.gameObject[cn.reverseToggleClone],(!this.toggleModel.geometry||!a.geometry)&&console.error("triggers without childs and without geometry won't work!",this,i.geometry),s=a,i.geometry=null,i.material=null}if(this.toggleModel){if(this.toggleOnClick){const a=[];a.push(di.fadeAction(s,0,!1)),a.push(di.fadeAction(this.toggleModel,0,!0)),a.push(di.fadeAction(this.targetModel,0,r)),e.addBehavior(new $n("Toggle_"+s.name+"_toggleTo"+(r?"On":"Off"),Os.tapTrigger(s),di.parallel(...a)));const c=[];c.push(di.fadeAction(this.toggleModel,0,!1)),c.push(di.fadeAction(s,0,!0)),c.push(di.fadeAction(this.targetModel,0,!r)),e.addBehavior(new $n("Toggle_"+s.name+"_toggleTo"+(r?"Off":"On"),Os.tapTrigger(this.toggleModel),di.parallel(...c)))}}else{const a=[];this.hideSelf&&a.push(di.fadeAction(s,0,!1)),a.push(di.fadeAction(this.targetModel,0,r)),e.addBehavior(new $n("Toggle_"+s.name+"_toggleTo"+(r?"On":"Off"),Os.tapTrigger(s),di.parallel(...a)))}const o=new Array;this.targetStateBeforeCreatingDocument||o.push(this.targetModel),this.stateBeforeCreatingDocument||o.push(i),this.toggleModel&&o.push(this.toggleModel),e.addBehavior(new $n("HideOnStart_"+this.gameObject.name,Os.sceneStartTrigger(),di.fadeAction(o,0,!1)))}}afterSerialize(e,t){this.gameObject[cn.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[cn.wasVisible],delete this.gameObject[cn.wasVisible]),this.target&&this.target[cn.wasVisible]!==void 0&&(this.target.visible=this.target[cn.wasVisible],delete this.target[cn.wasVisible]),delete this.gameObject[cn.toggleClone],delete this.gameObject[cn.reverseToggleClone]}},u(Of,"clonedToggleIndex",0),u(Of,"wasVisible",Symbol("usdz_SetActiveOnClick_wasVisible")),u(Of,"toggleClone",Symbol("clone for toggling")),u(Of,"reverseToggleClone",Symbol("clone for reverse toggling")),Of);let Fd=cn;mn([x(ge)],Fd.prototype,"target",2);mn([x()],Fd.prototype,"toggleOnClick",2);mn([x()],Fd.prototype,"targetState",2);mn([x()],Fd.prototype,"hideSelf",2);class nP extends Ie{start(){this.gameObject.visible=!1}createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&e.addBehavior(new $n("HideOnStart_"+this.gameObject.name,Os.sceneStartTrigger(),di.fadeAction(t,0,!1)))}beforeCreateDocument(){this.gameObject.visible=!0}afterCreateDocument(){this.gameObject.visible=!1}}class mm extends Ie{constructor(){super(...arguments);u(this,"target");u(this,"duration",.5);u(this,"motionType",OR.bounce)}beforeCreateDocument(){}createBehaviours(t,i,s){if(this.target&&i.uuid===this.gameObject.uuid){const r=new $n("emphasize "+this.name,Os.tapTrigger(this.gameObject),di.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));t.addBehavior(r)}}afterCreateDocument(t,i){}}mn([x()],mm.prototype,"target",2);mn([x()],mm.prototype,"duration",2);mn([x()],mm.prototype,"motionType",2);class gm extends Ie{constructor(){super(...arguments);u(this,"target");u(this,"clip","");u(this,"toggleOnClick",!1)}start(){JA(this.gameObject)}ensureAudioSource(){if(!this.target){const t=this.gameObject.addNewComponent(Cn);t&&(this.target=t,t.spatialBlend=1,t.volume=1,t.loop=!1)}}onPointerClick(t){var i;t.use(),!(!((i=this.target)!=null&&i.clip)&&!this.clip)&&(this.ensureAudioSource(),this.target&&(this.target.isPlaying&&this.toggleOnClick?this.target.stop():(!this.toggleOnClick&&this.target.isPlaying&&this.target.stop(),this.clip?this.target.play(this.clip):this.target.play())))}createBehaviours(t,i,s){if(!(!this.target&&!this.clip)&&i.uuid===this.gameObject.uuid){const r=this.clip?this.clip:this.target?this.target.clip:void 0;if(!r||typeof r!="string")return;const o=this.target?this.target.gameObject:this.gameObject,a=r.split("/").pop(),c=this.target?this.target.volume:1,l=this.target&&this.target.spatialBlend==0?RM.NonSpatial:RM.Spatial;{let h=di.playAudioAction(o,"audio/"+a,IM.Play,c,l);this.toggleOnClick&&(h.multiplePerformOperation=PH.Stop),this.target&&this.target.loop&&(h=di.sequence(h).makeLooping());const d=new $n("playAudio "+this.name,Os.tapTrigger(this.gameObject),h);t.addBehavior(d)}if(this.target&&this.target.playOnAwake&&this.target.enabled){let h=di.playAudioAction(o,"audio/"+a,IM.Play,c,l);this.target.loop&&(h=di.sequence(h).makeLooping());const d=new $n("playAudioOnStart "+this.name,Os.sceneStartTrigger(),h);t.addBehavior(d)}}}async afterSerialize(t,i){if(!this.target&&!this.clip)return;const s=this.clip?this.clip:this.target?this.target.clip:void 0;if(!s||typeof s!="string")return;const r=s.split("/").pop(),c=await(await(await fetch(s)).blob()).arrayBuffer(),l=new Uint8Array(c);i.files["audio/"+r]=l}}mn([x(Cn)],gm.prototype,"target",2);mn([x(URL)],gm.prototype,"clip",2);mn([x()],gm.prototype,"toggleOnClick",2);var u_;const hh=(u_=class extends Ie{constructor(){super(...arguments);u(this,"animator");u(this,"stateName");u(this,"trigger","tap");u(this,"selfModel");u(this,"stateAnimationModel");u(this,"animationSequence",new Array);u(this,"animationLoopAfterSequence",new Array)}get target(){var e;return(e=this.animator)==null?void 0:e.gameObject}start(){JA(this.gameObject)}onPointerClick(e){var t;e.use(),this.target&&this.stateName&&((t=this.animator)==null||t.play(this.stateName,0,0,.1))}createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t)}afterSerialize(){if(hh.rootsWithExclusivePlayback.size>1){const e='Multiple root objects targeted by more than one animation. To work around QuickLook bug FB13410767, animations will be set as "exclusive" and activating them will stop other animations being marked as exclusive.';Mt()&&pn(e),console.warn(e,...hh.rootsWithExclusivePlayback)}hh.animationActions=[],hh.rootsWithExclusivePlayback=new Set}afterCreateDocument(e,t){if(!this.animationSequence||!this.stateAnimationModel||!this.target)return;const i=t.document,s=t.extensions.find(a=>a instanceof GA);if(!s)return;const r=s.getClipCount(this.target)>1;r&&(Mt()&&console.warn("Setting exclusive playback for "+this.target.name+"@"+this.stateName+" because it has "+s.getClipCount(this.target)+" animations. This works around QuickLook bug FB13410767."),hh.rootsWithExclusivePlayback.add(this.target));const o=(a,c)=>{let l=hh.animationActions.find(h=>h.affectedObjects==a&&h.start==c.start&&h.duration==c.duration);return l||(l=di.startAnimationAction(a,c.start,c.duration),hh.animationActions.push(l)),l};i.traverse(a=>{var c,l;if(a.uuid===((c=this.target)==null?void 0:c.uuid)){const h=di.sequence();if(this.animationSequence!==void 0)for(const f of this.animationSequence)h.addAction(o(a,f));if(this.animationLoopAfterSequence!==void 0){const f=h.actions.length==0?h:di.sequence();for(const p of this.animationLoopAfterSequence)f.addAction(o(a,p));f.makeLooping(),h!==f&&h.addAction(f)}const d=new $n("tap "+this.name+" for "+this.stateName+" on "+((l=this.target)==null?void 0:l.name),this.trigger=="tap"?Os.tapTrigger(this.selfModel):Os.sceneStartTrigger(),h);r&&d.makeExclusive(!0),e.addBehavior(d)}})}createAnimation(e,t,i){var c,l,h,d;if(!this.target||!this.animator)return;const s=(c=this.animator)==null?void 0:c.runtimeAnimatorController;let r=s==null?void 0:s.findState(this.stateName),o=[],a=[];if(s&&r){const f=new Array;f.push(r);let p=!1;for(;f.length<100;){if(!r||r===null||!r.transitions||r.transitions.length===0){(l=r.motion)!=null&&l.isLooping&&(p=!0);break}const m=r.transitions.find(y=>y.conditions.length===0),g=m?s.getState(m.destinationState,0):null;if(g&&f.includes(g)){r=g,p=!0;break}else if(m){if(r=g,!r)break;f.push(r)}else{p=((h=r.motion)==null?void 0:h.isLooping)??!1;break}}if(p&&r){const m=f.indexOf(r);o=f.slice(0,m),a=f.slice(m),console.log("found loop from "+this.stateName,"states until loop",o,"states looping",a)}else o=f,a=[],console.log("found no loop from "+this.stateName,"states",o)}if(o=o.filter(f=>{var p,m,g;return((p=f.motion)==null?void 0:p.clip)&&((g=(m=f.motion)==null?void 0:m.clip.tracks)==null?void 0:g.length)>0}),a=a.filter(f=>{var p,m,g;return((p=f.motion)==null?void 0:p.clip)&&((g=(m=f.motion)==null?void 0:m.clip.tracks)==null?void 0:g.length)>0}),o.length===0&&a.length===0){console.warn("No clips found for state "+this.stateName+" on "+((d=this.animator)==null?void 0:d.name)+", can't export animation data");return}if(this.stateAnimationModel=t,o.length>0){this.animationSequence=new Array;for(const f of o)this.animationSequence.push(e.registerAnimation(this.target,f.motion.clip))}if(a.length>0){this.animationLoopAfterSequence=new Array;for(const f of a)this.animationLoopAfterSequence.push(e.registerAnimation(this.target,f.motion.clip))}}},u(u_,"animationActions",[]),u(u_,"rootsWithExclusivePlayback",new Set),u_);let vm=hh;mn([x(Us)],vm.prototype,"animator",2);mn([x()],vm.prototype,"stateName",2);class Am extends Ie{constructor(){super(...arguments);u(this,"target")}getType(){}getDuration(){}}mn([x(ge)],Am.prototype,"target",2);class KA extends Ie{constructor(){super(...arguments);u(this,"target")}}mn([x(Am)],KA.prototype,"target",2);class ZA extends Am{constructor(){super(...arguments);u(this,"type",1);u(this,"duration",1)}getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}mn([x()],ZA.prototype,"type",2);mn([x()],ZA.prototype,"duration",2);class sP extends KA{}var Sre=Object.defineProperty,Cre=Object.getOwnPropertyDescriptor,Ul=(n,e,t,i)=>{for(var s=i>1?void 0:i?Cre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Sre(e,t,s),s};const h2=se("debugcharactercontroller");class Ud extends Ie{constructor(){super(...arguments);u(this,"center",new w(0,0,0));u(this,"radius",.5);u(this,"height",2);u(this,"_rigidbody",null);u(this,"_activeGroundCollisions");u(this,"_contactVelocity",new w)}get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(Xi),this._rigidbody||(this._rigidbody=this.gameObject.addNewComponent(Xi)),this.rigidbody)}awake(){this._activeGroundCollisions=new Set}onEnable(){const t=this.rigidbody;let i=this.gameObject.getComponent(zh);i||(i=this.gameObject.addNewComponent(zh)),i.center.copy(this.center),i.radius=this.radius,i.height=this.height;const s=new w(0,0,1),r=new w(1,0,0),o=new w(0,1,0),a=this.gameObject.getWorldDirection(new w);a.y=0;const c=r.dot(a)<0?-1:1,l=s.angleTo(a)*c;this.gameObject.setRotationFromAxisAngle(o,l),t.lockRotationX=!0,t.lockRotationY=!0,t.lockRotationZ=!0}move(t){this.gameObject.position.add(t)}onCollisionEnter(t){(t.contacts.length==0||t.contacts.some(i=>i.normal.y>.2))&&(this._activeGroundCollisions.add(t),h2&&console.log(`Collision(${this._activeGroundCollisions.size}): ${t.contacts.map(i=>i.normal.y.toFixed(2)).join(", ")} - ${this.isGrounded}`))}onCollisionExit(t){this._activeGroundCollisions.delete(t),h2&&console.log(`Collision(${this._activeGroundCollisions.size}) - ${this.isGrounded}`)}get isGrounded(){return this._activeGroundCollisions.size>0}get contactVelocity(){var t;this._contactVelocity.set(0,0,0);for(const i of this._activeGroundCollisions){const s=(t=this.context.physics.engine)==null?void 0:t.getLinearVelocity(i.collider);s&&(this._contactVelocity.x+=s.x,this._contactVelocity.y+=s.y,this._contactVelocity.z+=s.z)}return this._contactVelocity}}Ul([x(w)],Ud.prototype,"center",2);Ul([x()],Ud.prototype,"radius",2);Ul([x()],Ud.prototype,"height",2);class Nl extends Ie{constructor(){super(...arguments);u(this,"controller");u(this,"movementSpeed",2);u(this,"rotationSpeed",2);u(this,"jumpForce",1);u(this,"doubleJumpForce",2);u(this,"animator");u(this,"lookForward",!0);u(this,"lookInput",new ie(0,0));u(this,"moveInput",new ie(0,0));u(this,"jumpInput",!1);u(this,"_currentSpeed",new w(0,0,0));u(this,"_currentAngularSpeed",new w(0,0,0));u(this,"_temp",new w(0,0,0));u(this,"_jumpCount",0);u(this,"_currentRotation");u(this,"_raycastOptions",new ta)}awake(){this._currentRotation=new Ee}update(){const t=this.context.input;t.isKeyPressed("KeyW")?this.moveInput.y+=1:t.isKeyPressed("KeyS")&&(this.moveInput.y-=1),t.isKeyPressed("KeyD")?this.lookInput.x+=1:t.isKeyPressed("KeyA")&&(this.lookInput.x-=1),this.jumpInput||(this.jumpInput=t.isKeyDown("Space"))}move(t){this.moveInput.add(t)}look(t){this.lookInput.add(t)}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(t,i,s){var r,o,a,c,l,h,d,f,p,m,g;if((r=this.controller)!=null&&r.isGrounded&&(this._jumpCount=0,this.doubleJumpForce>0&&((o=this.animator)==null||o.setBool("doubleJump",!1))),this._currentSpeed.z+=t.y*this.movementSpeed*this.context.time.deltaTime,(a=this.animator)==null||a.setBool("running",t.length()>.01),(l=this.animator)==null||l.setBool("jumping",((c=this.controller)==null?void 0:c.isGrounded)===!0&&s),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+=rt.toRadians(-i.x*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){const y=this.context.mainCameraComponent.forward;y.y=0,y.normalize(),this._currentRotation.setFromUnitVectors(new w(0,0,1),y),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&&s&&this.jumpForce>0){let y=(h=this.controller)==null?void 0:h.isGrounded;if(this.doubleJumpForce>0&&!((d=this.controller)!=null&&d.isGrounded)&&this._jumpCount===1&&(y=!0,(f=this.animator)==null||f.setBool("doubleJump",!0)),y){this._jumpCount+=1;const v=this.controller.rigidbody,A=this._jumpCount===2?this.doubleJumpForce:this.jumpForce;v.applyImpulse(new w(0,1,0).multiplyScalar(A))}}if(this.controller){const y=(p=this.controller)==null?void 0:p.rigidbody.getVelocity().y;if(y<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new bo),this._raycastOptions.ray.origin.copy(Dt(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);const v=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);const A=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(v),(A.length&&A[0].distance>2||y<-10)&&((m=this.animator)==null||m.setBool("falling",!0))}else(g=this.animator)==null||g.setBool("falling",!1)}}}Ul([x(Ud)],Nl.prototype,"controller",2);Ul([x()],Nl.prototype,"movementSpeed",2);Ul([x()],Nl.prototype,"rotationSpeed",2);Ul([x()],Nl.prototype,"jumpForce",2);Ul([x()],Nl.prototype,"doubleJumpForce",2);Ul([x(Us)],Nl.prototype,"animator",2);var Ere=Object.defineProperty,Mre=Object.getOwnPropertyDescriptor,Tre=(n,e,t,i)=>{for(var s=i>1?void 0:i?Mre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Ere(e,t,s),s};class $A extends cr{constructor(){super(...arguments);u(this,"intensity")}get typeName(){return"ChromaticAberration"}init(){this.intensity.defaultValue=0}onCreateEffect(){const t=new EN;return t.offset=new ie(0,0),t.radialModulation=!0,t.modulationOffset=.15,this.intensity.valueProcessor=i=>i*.02,this.intensity.onValueChanged=i=>{t.offset.x=-i,t.offset.y=i},t}}Tre([x(kt)],$A.prototype,"intensity",2);oa("ChromaticAberration",$A);var Ire=Object.defineProperty,Rre=Object.getOwnPropertyDescriptor,Pw=(n,e,t,i)=>{for(var s=i>1?void 0:i?Rre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Ire(e,t,s),s};class Zh extends cr{constructor(){super(...arguments);u(this,"postExposure");u(this,"contrast");u(this,"hueShift");u(this,"saturation")}get typeName(){return"ColorAdjustments"}init(){this.postExposure.valueProcessor=t=>(t=Math.pow(2,t),t),this.postExposure.defaultValue=0,this.contrast.valueProcessor=t=>{let i=1;return t>0?i=200:t<0&&(i=100),t/i},this.contrast.defaultValue=0,this.hueShift.valueProcessor=t=>Math.PI*t/180,this.hueShift.defaultValue=0,this.saturation.valueProcessor=t=>t<0?t/100:t/(100*Math.PI),this.saturation.defaultValue=0}unapply(){this.context.renderer.toneMappingExposure=1}onCreateEffect(){this.context.renderer.toneMapping===Wr&&this.postExposure.overrideState&&(this.context.renderer.toneMapping=av);const t=new CN;this.postExposure.onValueChanged=s=>{this.context.renderer.toneMapping===Wr&&(this.context.renderer.toneMapping=av),this.postExposure.overrideState&&(this.context.renderer.toneMappingExposure=s)},this.contrast.onValueChanged=s=>{t.contrast=s};const i=new TN;return this.hueShift.onValueChanged=s=>i.hue=s,this.saturation.onValueChanged=s=>i.saturation=s,[i,t]}}Pw([x(kt)],Zh.prototype,"postExposure",2);Pw([x(kt)],Zh.prototype,"contrast",2);Pw([x(kt)],Zh.prototype,"hueShift",2);Pw([x(kt)],Zh.prototype,"saturation",2);oa("ColorAdjustments",Zh);const Pre=(Math.sqrt(5)-1)/4,xs=(5-Math.sqrt(5))/20,H0=n=>Math.floor(n)|0,V0=new Float64Array([0,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,1,0,1,1,1,0,1,-1,1,0,-1,1,1,0,-1,-1,-1,0,1,1,-1,0,1,-1,-1,0,-1,1,-1,0,-1,-1,1,1,0,1,1,1,0,-1,1,-1,0,1,1,-1,0,-1,-1,1,0,1,-1,1,0,-1,-1,-1,0,1,-1,-1,0,-1,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,0]);function Bre(n=Math.random){const e=Dre(n),t=new Float64Array(e).map(o=>V0[o%32*4]),i=new Float64Array(e).map(o=>V0[o%32*4+1]),s=new Float64Array(e).map(o=>V0[o%32*4+2]),r=new Float64Array(e).map(o=>V0[o%32*4+3]);return function(a,c,l,h){let d,f,p,m,g;const y=(a+c+l+h)*Pre,v=H0(a+y),A=H0(c+y),_=H0(l+y),b=H0(h+y),C=(v+A+_+b)*xs,E=v-C,T=A-C,I=_-C,S=b-C,M=a-E,D=c-T,G=l-I,Q=h-S;let L=0,H=0,O=0,U=0;M>D?L++:H++,M>G?L++:O++,M>Q?L++:U++,D>G?H++:O++,D>Q?H++:U++,G>Q?O++:U++;const V=L>=3?1:0,J=H>=3?1:0,K=O>=3?1:0,oe=U>=3?1:0,fe=L>=2?1:0,be=H>=2?1:0,ke=O>=2?1:0,Ye=U>=2?1:0,ae=L>=1?1:0,Ae=H>=1?1:0,Ne=O>=1?1:0,Ve=U>=1?1:0,Je=M-V+xs,He=D-J+xs,Be=G-K+xs,X=Q-oe+xs,ve=M-fe+2*xs,Le=D-be+2*xs,_e=G-ke+2*xs,qe=Q-Ye+2*xs,lt=M-ae+3*xs,F=D-Ae+3*xs,B=G-Ne+3*xs,ce=Q-Ve+3*xs,Ce=M-1+4*xs,xe=D-1+4*xs,Re=G-1+4*xs,nt=Q-1+4*xs,Ue=v&255,$e=A&255,at=_&255,bt=b&255;let Me=.6-M*M-D*D-G*G-Q*Q;if(Me<0)d=0;else{const Qe=Ue+e[$e+e[at+e[bt]]];Me*=Me,d=Me*Me*(t[Qe]*M+i[Qe]*D+s[Qe]*G+r[Qe]*Q)}let Ft=.6-Je*Je-He*He-Be*Be-X*X;if(Ft<0)f=0;else{const Qe=Ue+V+e[$e+J+e[at+K+e[bt+oe]]];Ft*=Ft,f=Ft*Ft*(t[Qe]*Je+i[Qe]*He+s[Qe]*Be+r[Qe]*X)}let pt=.6-ve*ve-Le*Le-_e*_e-qe*qe;if(pt<0)p=0;else{const Qe=Ue+fe+e[$e+be+e[at+ke+e[bt+Ye]]];pt*=pt,p=pt*pt*(t[Qe]*ve+i[Qe]*Le+s[Qe]*_e+r[Qe]*qe)}let mt=.6-lt*lt-F*F-B*B-ce*ce;if(mt<0)m=0;else{const Qe=Ue+ae+e[$e+Ae+e[at+Ne+e[bt+Ve]]];mt*=mt,m=mt*mt*(t[Qe]*lt+i[Qe]*F+s[Qe]*B+r[Qe]*ce)}let et=.6-Ce*Ce-xe*xe-Re*Re-nt*nt;if(et<0)g=0;else{const Qe=Ue+1+e[$e+1+e[at+1+e[bt+1]]];et*=et,g=et*et*(t[Qe]*Ce+i[Qe]*xe+s[Qe]*Re+r[Qe]*nt)}return 27*(d+f+p+m+g)}}function Dre(n){const t=new Uint8Array(512);for(let i=0;i<512/2;i++)t[i]=i;for(let i=0;i<512/2-1;i++){const s=i+~~(n()*(256-i)),r=t[i];t[i]=t[s],t[s]=r}for(let i=256;i<512;i++)t[i]=t[i-256];return t}var Ore=Object.defineProperty,kre=Object.getOwnPropertyDescriptor,re=(n,e,t,i)=>{for(var s=i>1?void 0:i?kre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Ore(e,t,s),s};const Q0=se("debugparticles");var il=(n=>(n[n.Billboard=0]="Billboard",n[n.Stretch=1]="Stretch",n[n.HorizontalBillboard=2]="HorizontalBillboard",n[n.VerticalBillboard=3]="VerticalBillboard",n[n.Mesh=4]="Mesh",n))(il||{});let $h=class{constructor(){u(this,"alphaKeys");u(this,"colorKeys")}get duration(){return 1}evaluate(e,t){let i,s=0,r=null,o=0;for(let a=0;a<this.alphaKeys.length;a++){const c=this.alphaKeys[a];(c.time<e||!i)&&(i=c,s=a)}for(let a=0;a<this.colorKeys.length;a++){const c=this.colorKeys[a];(c.time<e||!r)&&(r=c,o=a)}if(r)if(o+1<this.colorKeys.length){const c=this.colorKeys[o+1],l=rt.remap(e,r.time,c.time,0,1);t.r=rt.lerp(r.color.r,c.color.r,l),t.g=rt.lerp(r.color.g,c.color.g,l),t.b=rt.lerp(r.color.b,c.color.b,l)}else t.r=r.color.r,t.g=r.color.g,t.b=r.color.b;if(i)if(s+1<this.alphaKeys.length){const c=this.alphaKeys[s+1],l=rt.remap(e,i.time,c.time,0,1);t.alpha=rt.lerp(i.alpha,c.alpha,l)}else t.alpha=i.alpha;return t}};re([x()],$h.prototype,"alphaKeys",2);re([x()],$h.prototype,"colorKeys",2);var Vv=(n=>(n[n.Local=0]="Local",n[n.World=1]="World",n[n.Custom=2]="Custom",n))(Vv||{}),Gb=(n=>(n[n.Sphere=0]="Sphere",n[n.SphereShell=1]="SphereShell",n[n.Hemisphere=2]="Hemisphere",n[n.HemisphereShell=3]="HemisphereShell",n[n.Cone=4]="Cone",n[n.Box=5]="Box",n[n.Mesh=6]="Mesh",n[n.ConeShell=7]="ConeShell",n[n.ConeVolume=8]="ConeVolume",n[n.ConeVolumeShell=9]="ConeVolumeShell",n[n.Circle=10]="Circle",n[n.CircleEdge=11]="CircleEdge",n[n.SingleSidedEdge=12]="SingleSidedEdge",n[n.MeshRenderer=13]="MeshRenderer",n[n.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",n[n.BoxShell=15]="BoxShell",n[n.BoxEdge=16]="BoxEdge",n[n.Donut=17]="Donut",n[n.Rectangle=18]="Rectangle",n[n.Sprite=19]="Sprite",n[n.SpriteRenderer=20]="SpriteRenderer",n))(Gb||{});const ZH=class{constructor(){u(this,"mode");u(this,"constant");u(this,"constantMin");u(this,"constantMax");u(this,"curve");u(this,"curveMin");u(this,"curveMax");u(this,"curveMultiplier")}clone(){var e,t,i;const n=new ZH;return n.mode=this.mode,n.constant=this.constant,n.constantMin=this.constantMin,n.constantMax=this.constantMax,n.curve=(e=this.curve)==null?void 0:e.clone(),n.curveMin=(t=this.curveMin)==null?void 0:t.clone(),n.curveMax=(i=this.curveMax)==null?void 0:i.clone(),n.curveMultiplier=this.curveMultiplier,n}evaluate(n,e){const t=e===void 0?Math.random():e;switch(this.mode){case 0:return this.constant;case 1:return n=rt.clamp01(n),this.curve.evaluate(n)*this.curveMultiplier;case 2:const i=n*this.curveMin.duration,s=n*this.curveMax.duration;return rt.lerp(this.curveMin.evaluate(i),this.curveMax.evaluate(s),t%1)*this.curveMultiplier;case 3:return rt.lerp(this.constantMin,this.constantMax,t%1);default:this.curveMax.evaluate(n)*this.curveMultiplier;break}return 0}getMax(){switch(this.mode){case 0:return this.constant;case 1:return this.getMaxFromCurve(this.curve)*this.curveMultiplier;case 2:return Math.max(this.getMaxFromCurve(this.curveMin),this.getMaxFromCurve(this.curveMax))*this.curveMultiplier;case 3:return Math.max(this.constantMin,this.constantMax);default:return 0}}getMaxFromCurve(n){if(!n)return 0;let e=Number.MIN_VALUE;for(let t=0;t<n.keys.length;t++){const i=n.keys[t];i.value>e&&(e=i.value)}return e}};let ft=ZH;re([x()],ft.prototype,"mode",2);re([x()],ft.prototype,"constant",2);re([x()],ft.prototype,"constantMin",2);re([x()],ft.prototype,"constantMax",2);re([x(Td)],ft.prototype,"curve",2);re([x(Td)],ft.prototype,"curveMin",2);re([x(Td)],ft.prototype,"curveMax",2);re([x()],ft.prototype,"curveMultiplier",2);var d_;const ga=(d_=class{constructor(){u(this,"mode");u(this,"color");u(this,"colorMin");u(this,"colorMax");u(this,"gradient");u(this,"gradientMin");u(this,"gradientMax")}evaluate(n,e){const t=e===void 0?Math.random():e;switch(this.mode){case 0:return this.color;case 1:return this.gradient.evaluate(n,ga._temp),ga._temp;case 2:return ga._temp.lerpColors(this.colorMin,this.colorMax,t);case 3:return this.gradientMin.evaluate(n,ga._temp),this.gradientMax.evaluate(n,ga._temp2),ga._temp.lerp(ga._temp2,t)}return ga._temp.set(16711935),ga._temp.alpha=1,ga._temp}},u(d_,"_temp",new Ti(0,0,0,1)),u(d_,"_temp2",new Ti(0,0,0,1)),d_);let Jr=ga;re([x(Ti)],Jr.prototype,"color",2);re([x(Ti)],Jr.prototype,"colorMin",2);re([x(Ti)],Jr.prototype,"colorMax",2);re([x($h)],Jr.prototype,"gradient",2);re([x($h)],Jr.prototype,"gradientMin",2);re([x($h)],Jr.prototype,"gradientMax",2);var UM=(n=>(n[n.Hierarchy=0]="Hierarchy",n[n.Local=1]="Local",n[n.Shape=2]="Shape",n))(UM||{});class js{constructor(){u(this,"cullingMode");u(this,"duration");u(this,"emitterVelocityMode");u(this,"flipRotation");u(this,"gravityModifier");u(this,"gravityModifierMultiplier");u(this,"loop");u(this,"maxParticles");u(this,"playOnAwake");u(this,"prewarm");u(this,"ringBufferLoopRange");u(this,"ringBufferMode");u(this,"scalingMode");u(this,"simulationSpace");u(this,"simulationSpeed");u(this,"startColor");u(this,"startDelay");u(this,"startDelayMultiplier");u(this,"startLifetime");u(this,"startLifetimeMultiplier");u(this,"startRotation");u(this,"startRotationMultiplier");u(this,"startRotation3D");u(this,"startRotationX");u(this,"startRotationXMultiplier");u(this,"startRotationY");u(this,"startRotationYMultiplier");u(this,"startRotationZ");u(this,"startRotationZMultiplier");u(this,"startSize");u(this,"startSize3D");u(this,"startSizeMultiplier");u(this,"startSizeX");u(this,"startSizeXMultiplier");u(this,"startSizeY");u(this,"startSizeYMultiplier");u(this,"startSizeZ");u(this,"startSizeZMultiplier");u(this,"startSpeed");u(this,"startSpeedMultiplier");u(this,"stopAction");u(this,"useUnscaledTime")}}re([x(ft)],js.prototype,"gravityModifier",2);re([x(Jr)],js.prototype,"startColor",2);re([x(ft)],js.prototype,"startDelay",2);re([x(ft)],js.prototype,"startLifetime",2);re([x(ft)],js.prototype,"startRotation",2);re([x(ft)],js.prototype,"startRotationX",2);re([x(ft)],js.prototype,"startRotationY",2);re([x(ft)],js.prototype,"startRotationZ",2);re([x(ft)],js.prototype,"startSize",2);re([x(ft)],js.prototype,"startSizeX",2);re([x(ft)],js.prototype,"startSizeY",2);re([x(ft)],js.prototype,"startSizeZ",2);re([x(ft)],js.prototype,"startSpeed",2);class Qv{constructor(){u(this,"cycleCount");u(this,"maxCount");u(this,"minCount");u(this,"probability");u(this,"repeatInterval");u(this,"time");u(this,"count");u(this,"_performed",0)}reset(){this._performed=0}run(e){if(e<=this.time)return 0;let t=0;if(this.cycleCount===0||this._performed<this.cycleCount){const i=this.time+this.repeatInterval*this._performed;if(e>=i&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:t=this.count.constant;break;case 3:t=rt.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:t=this.count.curve.evaluate(Math.random());break;case 2:const s=Math.random();t=rt.lerp(this.count.curveMin.evaluate(s),this.count.curveMax.evaluate(s),Math.random());break}}return t}}class Pc{constructor(){u(this,"enabled");u(this,"bursts");u(this,"rateOverTime");u(this,"rateOverTimeMultiplier");u(this,"rateOverDistance");u(this,"rateOverDistanceMultiplier");u(this,"system")}get burstCount(){var e;return((e=this.bursts)==null?void 0:e.length)??0}reset(){var e;(e=this.bursts)==null||e.forEach(t=>t.reset())}getBurst(){let e=0;if(this.burstCount>0)for(let t=0;t<this.burstCount;t++){const i=this.bursts[t];this.system.main.loop&&i.time>=this.system.time&&i.reset(),e+=Math.round(i.run(this.system.time))}return e}}re([x()],Pc.prototype,"enabled",2);re([x()],Pc.prototype,"bursts",2);re([x(ft)],Pc.prototype,"rateOverTime",2);re([x()],Pc.prototype,"rateOverTimeMultiplier",2);re([x(ft)],Pc.prototype,"rateOverDistance",2);re([x()],Pc.prototype,"rateOverDistanceMultiplier",2);class ey{constructor(){u(this,"enabled");u(this,"color")}}re([x(Jr)],ey.prototype,"color",2);class eu{constructor(){u(this,"enabled");u(this,"separateAxes");u(this,"size");u(this,"sizeMultiplier");u(this,"x");u(this,"xMultiplier");u(this,"y");u(this,"yMultiplier");u(this,"z");u(this,"zMultiplier");u(this,"_time",0);u(this,"_temp",new w)}evaluate(e,t,i){if(t||(t=this._temp),!this.enabled)return t.x=t.y=t.z=1,t;if(this.separateAxes)t.x=this.x.evaluate(e,i)*this.xMultiplier,t.y=this.y.evaluate(e,i)*this.yMultiplier,t.z=this.z.evaluate(e,i)*this.zMultiplier;else{const s=this.size.evaluate(e,i)*this.sizeMultiplier;t.x=s}return t}}re([x(ft)],eu.prototype,"size",2);re([x(ft)],eu.prototype,"x",2);re([x(ft)],eu.prototype,"y",2);re([x(ft)],eu.prototype,"z",2);var f_;const Cg=(f_=class{constructor(){u(this,"shapeType",5);u(this,"enabled",!0);u(this,"alignToDirection",!1);u(this,"angle",0);u(this,"arc",360);u(this,"arcSpread");u(this,"arcSpeedMultiplier");u(this,"arcMode");u(this,"boxThickness");u(this,"position");u(this,"rotation");u(this,"_rotation",new ks);u(this,"scale");u(this,"radius");u(this,"radiusThickness");u(this,"sphericalDirectionAmount");u(this,"randomDirectionAmount");u(this,"randomPositionAmount");u(this,"meshShapeType");u(this,"meshRenderer");u(this,"_meshObj");u(this,"_meshGeometry");u(this,"system");u(this,"_space");u(this,"_worldSpaceMatrix",new Se);u(this,"_worldSpaceMatrixInverse",new Se);u(this,"_vector",new w(0,0,0));u(this,"_temp",new w(0,0,0));u(this,"_triangle",new br);u(this,"_dir",new w);u(this,"_loopTime",0);u(this,"_loopDirection",1);Q0&&console.log(this)}get type(){return Gb[this.shapeType]}initialize(n){this.onInitialize(n),n.position.copy(this._vector)}toJSON(){return this}clone(){return new Cg}setMesh(n){this.meshRenderer=n,n?(this._meshObj=n.sharedMeshes[Math.floor(Math.random()*n.sharedMeshes.length)],this._meshGeometry=this._meshObj.geometry):(this._meshObj=void 0,this._meshGeometry=void 0)}update(n,e,t,i){this.system=n,this._space=t,t===1&&(this._worldSpaceMatrix.copy(i.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}applyRotation(n){const e=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return e&&(this._rotation.x=rt.toRadians(this.rotation.x),this._rotation.y=rt.toRadians(this.rotation.y),this._rotation.z=rt.toRadians(this.rotation.z),this._rotation.order="ZYX",n.applyEuler(this._rotation)),e}onInitialize(n){this._vector.set(0,0,0),n.mesh=void 0,n.mesh_geometry=void 0;const e=this._temp.copy(this.position),t=this._space===1;t&&e.applyQuaternion(this.system.worldQuaternion);let i=this.radius;if(t&&(i*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:Q0&&It.DrawWireBox(this.position,this.scale,14540253,1),this._vector.x=Math.random()*this.scale.x-this.scale.x/2,this._vector.y=Math.random()*this.scale.y-this.scale.y/2,this._vector.z=Math.random()*this.scale.z-this.scale.z/2,this._vector.add(e);break;case 4:this.randomConePoint(this.position,this.angle,i,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,i,this.radiusThickness,this.arc,this._vector);break;case 10:this.randomCirclePoint(this.position,i,this.radiusThickness,this.arc,this._vector);break;case 13:const s=this.meshRenderer;(s==null?void 0:s.destroyed)==!1&&this.setMesh(s);const r=n.mesh=this._meshObj,o=n.mesh_geometry=this._meshGeometry;if(r&&o)switch(this.meshShapeType){case 0:{const a=o.getAttribute("position"),c=Math.floor(Math.random()*a.count);this._vector.fromBufferAttribute(a,c),this._vector.applyMatrix4(r.matrixWorld),n.mesh_normal=c}break;case 1:break;case 2:{const a=o.index;if(a){let c=Math.random(),l=Math.random();c+l>1&&(c=1-c,l=1-l);const h=Math.floor(Math.random()*(a.count/3));let d=h*3,f=h*3+1,p=h*3+2;d=a.getX(d),f=a.getX(f),p=a.getX(p);const m=o.getAttribute("position");this._triangle.a.fromBufferAttribute(m,d),this._triangle.b.fromBufferAttribute(m,f),this._triangle.c.fromBufferAttribute(m,p),this._vector.set(0,0,0).addScaledVector(this._triangle.a,c).addScaledVector(this._triangle.b,l).addScaledVector(this._triangle.c,1-(c+l)),this._vector.applyMatrix4(r.matrixWorld),n.mesh_normal=h}}break}break;default:this._vector.set(0,0,0),Mt()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",Gb[this.shapeType]),globalThis.__particlesystem_shapetype_unsupported=!0);break}this.randomizePosition(this._vector,this.randomPositionAmount)}this.applyRotation(this._vector),t&&(this._vector.applyQuaternion(this.system.worldQuaternion),this._vector.add(this.system.worldPos)),Q0&&It.DrawSphere(this._vector,.03,16711680,.5,!0)}getDirection(n,e){var t;if(!this.enabled)return this._dir.set(0,0,1),this._dir;switch(this.shapeType){case 5:this._dir.set(0,0,1);break;case 4:this._dir.set(0,0,1);break;case 10:case 0:const i=e.x,s=e.y,r=e.z;this._dir.set(i,s,r),(t=this.system)!=null&&t.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;case 13:const o=n.mesh,a=n.mesh_geometry;if(o&&a)switch(this.meshShapeType){case 0:{const c=a.getAttribute("normal"),l=n.mesh_normal;this._dir.fromBufferAttribute(c,l)}break;case 1:break;case 2:{const c=a.index;if(c){const l=n.mesh_normal,h=c.getX(l*3),d=c.getX(l*3+1),f=c.getX(l*3+2),p=a.getAttribute("position"),m=Gn(),g=Gn(),y=Gn();m.fromBufferAttribute(p,h),g.fromBufferAttribute(p,d),y.fromBufferAttribute(p,f),m.sub(g),y.sub(g),m.cross(y),this._dir.copy(m).multiplyScalar(-1);const v=Di(o);this._dir.applyQuaternion(v)}}break}break;default:this._dir.set(0,0,1);break}return this._space===1&&this._dir.applyQuaternion(this.system.worldQuaternion),this.applyRotation(this._dir),this._dir.normalize(),this.spherizeDirection(this._dir,this.sphericalDirectionAmount),this.randomizeDirection(this._dir,this.randomDirectionAmount),Q0&&(It.DrawSphere(e,.01,8925952,.5,!0),It.DrawDirection(e,this._dir,8925952,.5,!0)),this._dir}randomizePosition(n,e){if(e<=0)return;const t=Cg._tempVec;t.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),t.x*=e*this.scale.x,t.y*=e*this.scale.y,t.z*=e*this.scale.z,n.add(t)}randomizeDirection(n,e){if(e===0)return;const t=Cg._randomQuat,i=Cg._tempVec;i.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),t.setFromAxisAngle(i,e*Math.random()*Math.PI),n.applyQuaternion(t)}spherizeDirection(n,e){if(e===0)return;const t=Math.random()*Math.PI*2,i=Math.acos(1-Math.random()*2),s=Math.sin(i)*Math.cos(t),r=Math.sin(i)*Math.sin(t),o=Math.cos(i),a=new w(s,r,o);n.lerp(a,e)}randomSpherePoint(n,e,t,i,s){const r=Math.random(),o=Math.random(),a=2*Math.PI*r*(i/360),c=Math.acos(2*o-1),l=rt.lerp(1,1-Math.pow(1-Math.random(),Math.PI),t)*e,h=n.x+this.scale.x*(-l*Math.sin(c)*Math.cos(a)),d=n.y+this.scale.y*(l*Math.sin(c)*Math.sin(a)),f=n.z+this.scale.z*(l*Math.cos(c));s.x=h,s.y=d,s.z=f}randomCirclePoint(n,e,t,i,s){const r=Math.random(),o=2*Math.PI*r*(i/360),a=rt.lerp(1,1-Math.pow(1-Math.random(),Math.PI),t)*e,c=n.x+this.scale.x*a*Math.cos(o),l=n.y+this.scale.y*a*Math.sin(o),h=n.z;s.x=c,s.y=l,s.z=h}randomConePoint(n,e,t,i,s,r,o){let a=0,c=0;switch(r){case 0:a=Math.random(),c=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:a=.5,c=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let l=2*Math.PI*a*(s/360);switch(r){case 2:case 1:l+=Math.PI+.5,l+=this._loopTime*Math.PI*2,l%=rt.toRadians(s);break}const h=Math.acos(2*c-1),d=rt.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,f=n.x+-d*Math.sin(h)*Math.cos(l),p=n.y+d*Math.sin(h)*Math.sin(l),m=n.z;o.x=f*this.scale.x,o.y=p*this.scale.y,o.z=m*this.scale.z}},u(f_,"_randomQuat",new Ee),u(f_,"_tempVec",new w),f_);let gn=Cg;re([x()],gn.prototype,"shapeType",2);re([x()],gn.prototype,"enabled",2);re([x()],gn.prototype,"alignToDirection",2);re([x()],gn.prototype,"angle",2);re([x()],gn.prototype,"arc",2);re([x()],gn.prototype,"arcSpread",2);re([x()],gn.prototype,"arcSpeedMultiplier",2);re([x()],gn.prototype,"arcMode",2);re([x(w)],gn.prototype,"boxThickness",2);re([x(w)],gn.prototype,"position",2);re([x(w)],gn.prototype,"rotation",2);re([x(w)],gn.prototype,"scale",2);re([x()],gn.prototype,"radius",2);re([x()],gn.prototype,"radiusThickness",2);re([x()],gn.prototype,"sphericalDirectionAmount",2);re([x()],gn.prototype,"randomDirectionAmount",2);re([x()],gn.prototype,"randomPositionAmount",2);re([x()],gn.prototype,"meshShapeType",2);re([x(DA)],gn.prototype,"meshRenderer",2);class Ri{constructor(){u(this,"damping");u(this,"enabled");u(this,"frequency");u(this,"octaveCount");u(this,"octaveMultiplier");u(this,"octaveScale");u(this,"positionAmount");u(this,"quality");u(this,"remap");u(this,"remapEnabled");u(this,"remapMultiplier");u(this,"remapX");u(this,"remapXMultiplier");u(this,"remapY");u(this,"remapYMultiplier");u(this,"remapZ");u(this,"remapZMultiplier");u(this,"scrollSpeedMultiplier");u(this,"separateAxes");u(this,"strengthMultiplier");u(this,"strengthX");u(this,"strengthXMultiplier");u(this,"strengthY");u(this,"strengthYMultiplier");u(this,"strengthZ");u(this,"strengthZMultiplier");u(this,"_noise");u(this,"_time",0);u(this,"_temp",new w)}update(e){this._time+=e.time.deltaTime*this.scrollSpeedMultiplier}apply(e,t,i,s,r,o){if(!this.enabled)return;this._noise||(this._noise=Bre(()=>0));const a=this._temp.set(t.x,t.y,t.z).multiplyScalar(this.frequency),c=this._noise(a.x,a.y,a.z,this._time),l=this._noise(a.x,a.y,a.z,this._time+1e3*this.frequency),h=this._noise(a.x,a.y,a.z,this._time+2e3*this.frequency);this._temp.set(c,l,h).normalize();const d=r/o;let f=this.positionAmount.evaluate(d);this.separateAxes?(this._temp.x*=f*this.strengthXMultiplier,this._temp.y*=f*this.strengthYMultiplier,this._temp.z*=f*this.strengthZMultiplier):(this.strengthX&&(f*=this.strengthX.evaluate(d)*1.5),this._temp.multiplyScalar(f)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z}}re([x()],Ri.prototype,"damping",2);re([x()],Ri.prototype,"enabled",2);re([x()],Ri.prototype,"frequency",2);re([x()],Ri.prototype,"octaveCount",2);re([x()],Ri.prototype,"octaveMultiplier",2);re([x()],Ri.prototype,"octaveScale",2);re([x(ft)],Ri.prototype,"positionAmount",2);re([x()],Ri.prototype,"quality",2);re([x(ft)],Ri.prototype,"remap",2);re([x()],Ri.prototype,"remapEnabled",2);re([x()],Ri.prototype,"remapMultiplier",2);re([x(ft)],Ri.prototype,"remapX",2);re([x()],Ri.prototype,"remapXMultiplier",2);re([x(ft)],Ri.prototype,"remapY",2);re([x()],Ri.prototype,"remapYMultiplier",2);re([x(ft)],Ri.prototype,"remapZ",2);re([x()],Ri.prototype,"remapZMultiplier",2);re([x()],Ri.prototype,"scrollSpeedMultiplier",2);re([x()],Ri.prototype,"separateAxes",2);re([x()],Ri.prototype,"strengthMultiplier",2);re([x(ft)],Ri.prototype,"strengthX",2);re([x()],Ri.prototype,"strengthXMultiplier",2);re([x(ft)],Ri.prototype,"strengthY",2);re([x()],Ri.prototype,"strengthYMultiplier",2);re([x(ft)],Ri.prototype,"strengthZ",2);re([x()],Ri.prototype,"strengthZMultiplier",2);class on{constructor(){u(this,"enabled");u(this,"attachRibbonToTransform",!1);u(this,"colorOverLifetime");u(this,"colorOverTrail");u(this,"dieWithParticles",!0);u(this,"inheritParticleColor",!0);u(this,"lifetime");u(this,"lifetimeMultiplier");u(this,"minVertexDistance",.2);u(this,"mode",0);u(this,"ratio",1);u(this,"ribbonCount",1);u(this,"shadowBias",0);u(this,"sizeAffectsLifetime",!1);u(this,"sizeAffectsWidth",!1);u(this,"splitSubEmitterRibbons",!1);u(this,"textureMode",0);u(this,"widthOverTrail");u(this,"widthOverTrailMultiplier");u(this,"worldSpace",!1)}getWidth(e,t,i,s){const r=this.widthOverTrail.evaluate(i,s);return e*=r,e}getColor(e,t,i){const s=this.colorOverTrail.evaluate(i),r=this.colorOverLifetime.evaluate(t);e.x*=s.r*r.r,e.y*=s.g*r.g,e.z*=s.b*r.b,e.w*=s.alpha*r.alpha}}re([x()],on.prototype,"enabled",2);re([x()],on.prototype,"attachRibbonToTransform",2);re([x(Jr)],on.prototype,"colorOverLifetime",2);re([x(Jr)],on.prototype,"colorOverTrail",2);re([x()],on.prototype,"dieWithParticles",2);re([x()],on.prototype,"inheritParticleColor",2);re([x(ft)],on.prototype,"lifetime",2);re([x()],on.prototype,"lifetimeMultiplier",2);re([x()],on.prototype,"minVertexDistance",2);re([x()],on.prototype,"mode",2);re([x()],on.prototype,"ratio",2);re([x()],on.prototype,"ribbonCount",2);re([x()],on.prototype,"shadowBias",2);re([x()],on.prototype,"sizeAffectsLifetime",2);re([x()],on.prototype,"sizeAffectsWidth",2);re([x()],on.prototype,"splitSubEmitterRibbons",2);re([x()],on.prototype,"textureMode",2);re([x(ft)],on.prototype,"widthOverTrail",2);re([x()],on.prototype,"widthOverTrailMultiplier",2);re([x()],on.prototype,"worldSpace",2);class vn{constructor(){u(this,"enabled");u(this,"space",0);u(this,"orbitalX");u(this,"orbitalY");u(this,"orbitalZ");u(this,"orbitalXMultiplier");u(this,"orbitalYMultiplier");u(this,"orbitalZMultiplier");u(this,"orbitalOffsetX");u(this,"orbitalOffsetY");u(this,"orbitalOffsetZ");u(this,"speedModifier");u(this,"speedModifierMultiplier");u(this,"x");u(this,"xMultiplier");u(this,"y");u(this,"yMultiplier");u(this,"z");u(this,"zMultiplier");u(this,"_system");u(this,"_temp",new w);u(this,"_temp2",new w);u(this,"_temp3",new w);u(this,"_hasOrbital",!1);u(this,"_index",0);u(this,"_orbitalMatrix",new Se)}update(e){this._system=e}init(e){this._index==0&&(e.debug=!0),this._index+=1,e.orbitx=this.orbitalX.evaluate(Math.random()),e.orbity=this.orbitalY.evaluate(Math.random()),e.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=e.orbitx!=0||e.orbity!=0||e.orbitz!=0}apply(e,t,i,s,r,o,a){var p;if(!this.enabled)return;const c=o/a,l=this.speedModifier.evaluate(c)*this.speedModifierMultiplier,h=this.x.evaluate(c),d=this.y.evaluate(c),f=this.z.evaluate(c);if(this._temp.set(-h,d,f),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&((p=this._system)==null?void 0:p.worldPos)){const g=this._temp2.set(i.x,i.y,i.z),y=this.orbitalXMultiplier,v=this.orbitalYMultiplier,A=this.orbitalZMultiplier,_=l*Math.PI*2*10,b=Math.cos(_*y),C=Math.sin(_*y),E=Math.cos(_*v),T=Math.sin(_*v),I=Math.cos(_*A),S=Math.sin(_*A),M=g.x*(E*I)+g.y*(E*S)+g.z*-T,D=g.x*(C*T*I-b*S)+g.y*(C*T*S+b*I)+g.z*(C*E),G=g.x*(b*T*I+C*S)+g.y*(b*T*S-C*I)+g.z*(b*E),Q=this._temp3.set(g.x-M,g.y-D,g.z-G);Q.normalize(),Q.multiplyScalar(.2/r*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),s.x+=Q.x,s.y+=Q.y,s.z+=Q.z}s.x+=this._temp.x,s.y+=this._temp.y,s.z+=this._temp.z,s.x*=l,s.y*=l,s.z*=l}}re([x()],vn.prototype,"enabled",2);re([x()],vn.prototype,"space",2);re([x(ft)],vn.prototype,"orbitalX",2);re([x(ft)],vn.prototype,"orbitalY",2);re([x(ft)],vn.prototype,"orbitalZ",2);re([x()],vn.prototype,"orbitalXMultiplier",2);re([x()],vn.prototype,"orbitalYMultiplier",2);re([x()],vn.prototype,"orbitalZMultiplier",2);re([x()],vn.prototype,"orbitalOffsetX",2);re([x()],vn.prototype,"orbitalOffsetY",2);re([x()],vn.prototype,"orbitalOffsetZ",2);re([x(ft)],vn.prototype,"speedModifier",2);re([x()],vn.prototype,"speedModifierMultiplier",2);re([x(ft)],vn.prototype,"x",2);re([x()],vn.prototype,"xMultiplier",2);re([x(ft)],vn.prototype,"y",2);re([x()],vn.prototype,"yMultiplier",2);re([x(ft)],vn.prototype,"z",2);re([x()],vn.prototype,"zMultiplier",2);class Ws{constructor(){u(this,"animation");u(this,"enabled");u(this,"cycleCount");u(this,"frameOverTime");u(this,"frameOverTimeMultiplier");u(this,"numTilesX");u(this,"numTilesY");u(this,"startFrame");u(this,"startFrameMultiplier");u(this,"rowMode");u(this,"rowIndex");u(this,"spriteCount");u(this,"timeMode")}sampleOnceAtStart(){if(this.timeMode===0)switch(this.frameOverTime.mode){case 0:case 3:case 2:case 1:return!0}return!1}getStartIndex(){return this.sampleOnceAtStart()?Math.random()*(this.numTilesX*this.numTilesY):0}evaluate(e){if(!this.sampleOnceAtStart())return this.getIndex(e)}getIndex(e){const t=this.numTilesX*this.numTilesY;e=e*this.cycleCount;let i=this.frameOverTime.evaluate(e%1);return i*=this.frameOverTimeMultiplier,i*=t,i=i%t,i=Math.floor(i),i}}re([x()],Ws.prototype,"animation",2);re([x()],Ws.prototype,"enabled",2);re([x()],Ws.prototype,"cycleCount",2);re([x(ft)],Ws.prototype,"frameOverTime",2);re([x()],Ws.prototype,"frameOverTimeMultiplier",2);re([x()],Ws.prototype,"numTilesX",2);re([x()],Ws.prototype,"numTilesY",2);re([x(ft)],Ws.prototype,"startFrame",2);re([x()],Ws.prototype,"startFrameMultiplier",2);re([x()],Ws.prototype,"rowMode",2);re([x()],Ws.prototype,"rowIndex",2);re([x()],Ws.prototype,"spriteCount",2);re([x()],Ws.prototype,"timeMode",2);class ca{constructor(){u(this,"enabled");u(this,"separateAxes");u(this,"x");u(this,"xMultiplier");u(this,"y");u(this,"yMultiplier");u(this,"z");u(this,"zMultiplier")}evaluate(e,t){return this.enabled?this.separateAxes?0:this.z.evaluate(e,t)*-1:0}}re([x()],ca.prototype,"enabled",2);re([x()],ca.prototype,"separateAxes",2);re([x(ft)],ca.prototype,"x",2);re([x()],ca.prototype,"xMultiplier",2);re([x(ft)],ca.prototype,"y",2);re([x()],ca.prototype,"yMultiplier",2);re([x(ft)],ca.prototype,"z",2);re([x()],ca.prototype,"zMultiplier",2);class Eo{constructor(){u(this,"enabled");u(this,"range");u(this,"separateAxes");u(this,"x");u(this,"xMultiplier");u(this,"y");u(this,"yMultiplier");u(this,"z");u(this,"zMultiplier")}evaluate(e,t){if(!this.enabled)return 0;if(!this.separateAxes){const i=rt.lerp(this.range.x,this.range.y,t);return this.z.evaluate(i)*-1}return 0}}re([x()],Eo.prototype,"enabled",2);re([x()],Eo.prototype,"range",2);re([x()],Eo.prototype,"separateAxes",2);re([x(ft)],Eo.prototype,"x",2);re([x()],Eo.prototype,"xMultiplier",2);re([x(ft)],Eo.prototype,"y",2);re([x()],Eo.prototype,"yMultiplier",2);re([x(ft)],Eo.prototype,"z",2);re([x()],Eo.prototype,"zMultiplier",2);class qn{constructor(){u(this,"enabled");u(this,"dampen");u(this,"drag");u(this,"dragMultiplier");u(this,"limit");u(this,"limitMultiplier");u(this,"separateAxes");u(this,"limitX");u(this,"limitXMultiplier");u(this,"limitY");u(this,"limitYMultiplier");u(this,"limitZ");u(this,"limitZMultiplier");u(this,"multiplyDragByParticleSize",!1);u(this,"multiplyDragByParticleVelocity",!1);u(this,"space");u(this,"_temp",new w);u(this,"_temp2",new w)}apply(e,t,i,s,r,o,a){if(this.enabled){const c=this.limit.evaluate(r)*this.limitMultiplier;if(t.length()>c){this._temp.copy(t).normalize().multiplyScalar(c);const h=this.dampen*.5;t.x=rt.lerp(t.x,this._temp.x,h),t.y=rt.lerp(t.y,this._temp.y,h),t.z=rt.lerp(t.z,this._temp.z,h),i.x=rt.lerp(i.x,this._temp.x,h),i.y=rt.lerp(i.y,this._temp.y,h),i.z=rt.lerp(i.z,this._temp.z,h)}}}}re([x()],qn.prototype,"enabled",2);re([x()],qn.prototype,"dampen",2);re([x(ft)],qn.prototype,"drag",2);re([x()],qn.prototype,"dragMultiplier",2);re([x(ft)],qn.prototype,"limit",2);re([x()],qn.prototype,"limitMultiplier",2);re([x()],qn.prototype,"separateAxes",2);re([x(ft)],qn.prototype,"limitX",2);re([x()],qn.prototype,"limitXMultiplier",2);re([x(ft)],qn.prototype,"limitY",2);re([x()],qn.prototype,"limitYMultiplier",2);re([x(ft)],qn.prototype,"limitZ",2);re([x()],qn.prototype,"limitZMultiplier",2);re([x()],qn.prototype,"multiplyDragByParticleSize",2);re([x()],qn.prototype,"multiplyDragByParticleVelocity",2);re([x()],qn.prototype,"space",2);const $H=class{constructor(){u(this,"enabled");u(this,"curve");u(this,"curveMultiplier");u(this,"mode");u(this,"system");u(this,"_temp",new w);u(this,"_firstUpdate",!0);u(this,"_frames",0)}clone(){var e;const n=new $H;return n.enabled=this.enabled,n.curve=(e=this.curve)==null?void 0:e.clone(),n.curveMultiplier=this.curveMultiplier,n.mode=this.mode,n}get _lastWorldPosition(){return this.system._iv_lastWorldPosition||(this.system._iv_lastWorldPosition=new w),this.system._iv_lastWorldPosition}get _velocity(){return this.system._iv_velocity||(this.system._iv_velocity=new w),this.system._iv_velocity}awake(n){this.system=n,this.reset()}reset(){this._firstUpdate=!0}update(n){this.enabled&&this.system.worldspace!==!1&&(this._firstUpdate?(this._firstUpdate=!1,this._velocity.set(0,0,0),this._lastWorldPosition.copy(this.system.worldPos)):this._lastWorldPosition&&(this._velocity.copy(this.system.worldPos).sub(this._lastWorldPosition).multiplyScalar(1/this.system.deltaTime),this._lastWorldPosition.copy(this.system.worldPos)))}applyInitial(n){if(this.enabled&&this.system.worldspace!==!1&&this.mode===0){const e=this.curve.evaluate(Math.random(),Math.random());this._temp.copy(this._velocity).multiplyScalar(e),n.add(this._temp)}}applyCurrent(n,e,t){if(this.enabled&&this.system&&this.system.worldspace!==!1&&this.mode===1){const i=this.curve.evaluate(e,t);this._temp.copy(this._velocity).multiplyScalar(i),n.add(this._temp)}}};let tu=$H;re([x()],tu.prototype,"enabled",2);re([x(ft)],tu.prototype,"curve",2);re([x()],tu.prototype,"curveMultiplier",2);re([x()],tu.prototype,"mode",2);class Rr{constructor(){u(this,"enabled");u(this,"range");u(this,"separateAxes");u(this,"size");u(this,"sizeMultiplier");u(this,"x");u(this,"xMultiplier");u(this,"y");u(this,"yMultiplier");u(this,"z");u(this,"zMultiplier")}evaluate(e,t,i,s){const r=e.length(),o=rt.remap(r,this.range.x,this.range.y,0,1),a=this.size.evaluate(o,i);return s*a}}re([x()],Rr.prototype,"enabled",2);re([x(ie)],Rr.prototype,"range",2);re([x()],Rr.prototype,"separateAxes",2);re([x(ft)],Rr.prototype,"size",2);re([x()],Rr.prototype,"sizeMultiplier",2);re([x(ft)],Rr.prototype,"x",2);re([x()],Rr.prototype,"xMultiplier",2);re([x(ft)],Rr.prototype,"y",2);re([x()],Rr.prototype,"yMultiplier",2);re([x(ft)],Rr.prototype,"z",2);re([x()],Rr.prototype,"zMultiplier",2);class Nd{constructor(){u(this,"enabled");u(this,"range");u(this,"color")}evaluate(e,t,i){const s=e.length(),r=rt.remap(s,this.range.x,this.range.y,0,1),o=this.color.evaluate(r,t);i.x*=o.r,i.y*=o.g,i.z*=o.b,i.w*=o.alpha}}re([x()],Nd.prototype,"enabled",2);re([x(ie)],Nd.prototype,"range",2);re([x(Jr)],Nd.prototype,"color",2);const Lre={name:"HorizontalBlurShader",uniforms:{tDiffuse:{value:null},h:{value:1/512}},vertexShader:`
5412
+ `))}for(const S of T){const M=s.get(S);M&&I.set(S,M)}return I},f=function(T){const I=d(T),S=a(I);return c(I,S,T)};const p=i.skinnedMesh.skeleton,m=new Array;for(const T in p.bones){const I=p.bones[T],S=p.boneInverses[T];m.push({bone:I,inverse:S})}for(const T of CH(p.bones))m.push({bone:T,inverse:T.matrixWorld.clone().invert()});const g=m[0].bone.parent;g||console.error("No bone parent found for skinned mesh during USDZ export",i.skinnedMesh),m.sort((T,I)=>gp(T.bone,g)>gp(I.bone,g)?1:-1);const y=[],v=[],A=[],_=[];for(const{bone:T}of m)y.push(T.matrix.clone()),v.push(T.position),A.push(T.quaternion),_.push(T.scale);const b=m.map(T=>'"'+gp(T.bone,g)+'"').join(", "),C=m.map(T=>Kf(T.inverse.clone().invert())).join(", ");e.beginBlock('def Skeleton "Rig"'),e.appendLine(`uniform matrix4d[] bindTransforms = [${C}]`),e.appendLine(`uniform token[] joints = [${b}]`),e.appendLine('uniform token purpose = "guide"'),e.appendLine(`uniform matrix4d[] restTransforms = [${y.map(T=>Kf(T)).join(", ")}]`),e.appendLine(`matrix4d xformOp:transform = ${Kf(new Se)}`),e.appendLine('uniform token[] xformOpOrder = ["xformOp:transform"]');const E=f(m.map(T=>T.bone));if(e.beginBlock('def SkelAnimation "_anim"'),e.appendLine(`uniform token[] joints = [${b}]`),e.appendLine(`quatf[] rotations = [${h(A)}]`),E&&E.quaternion){e.beginBlock("quatf[] rotations.timeSamples = {","");const T=o(E.quaternion);for(const I of T)e.appendLine(I);e.closeBlock()}if(e.appendLine(`half3[] scales = [${l(_)}]`),E&&E.scale){e.beginBlock("half3[] scales.timeSamples = {","");const T=r(E.scale);for(const I of T)e.appendLine(I);e.closeBlock()}if(e.appendLine(`float3[] translations = [${l(v)}]`),E&&E.position){e.beginBlock("float3[] translations.timeSamples = {","");const T=r(E.position);for(const I of T)e.appendLine(I);e.closeBlock()}e.closeBlock(),e.closeBlock()}}onSerialize(e,t){var c;if(!this.model)return;this.skinnedMeshExport(e,t);const i=this.object,s=this.dict.get(i);if(!s||i.isSkinnedMesh)return;LM&&console.log("SERIALIZE",this.model.name,this.object.type,s);const r=new Se;e.appendLine("matrix4d xformOp:transform.timeSamples = {"),e.indent++;const o=new Array;let a=0;for(let l=0;l<s.length;l++)o.push(a),a+=s[l].getDuration()+Wo.animationDurationPadding;for(let l=0;l<s.length;l++){const h=s[l];if(!h)continue;const d=o[l];{const f=h.getSortedTimesArray();if(!f||f.length===0){console.error("got an animated object but no time values?",i,h);continue}if(vp){const p=((c=h.clip)==null?void 0:c.name)??"rest",m=h.getDuration();console.log("Write .timeSamples:",p,d,m,s),e.appendLine("# "+p+": start="+(d*h.frameRate).toFixed(3)+", length="+(m*h.frameRate).toFixed(3)+", frames="+h.getFrames())}for(const{time:p,translation:m,rotation:g,scale:y}of h.getValues(f)){r.compose(m,g,y);const v=`${(d+p)*h.frameRate}: ${Kf(r)},`;e.appendLine(v)}}}e.indent--,e.appendLine("}")}}var lse=Object.defineProperty,hse=Object.getOwnPropertyDescriptor,UH=(n,e,t,i)=>{for(var s=i>1?void 0:i?hse(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&lse(e,t,s),s};const a2=se("debugpost");class kt{constructor(e){u(this,"_active",!0);u(this,"_value");u(this,"_valueRaw");u(this,"_defaultValue");u(this,"valueProcessor");u(this,"onValueChanged");this._value=e,this._defaultValue=e,this._valueRaw=e}get overrideState(){return this._active}set overrideState(e){if(this._active===e)return;this._active=e;const t=e?this._valueRaw:this._defaultValue;this.processValue(t,!0)}get value(){return this._valueRaw}set value(e){this.processValue(e,!1)}set defaultValue(e){this._defaultValue=e}__init(){this.processValue(this._valueRaw,!0)}processValue(e,t){if(e==null||!t&&this.testIfValueChanged(e)===!1)return;const i=this._value;a2&&console.log("VolumeParameter: value changed from",i,"to",e),!this._active&&this._defaultValue!==void 0?(this._value=this._defaultValue,e=this._defaultValue,this._valueRaw=e):(this._valueRaw=e,this._active&&this.valueProcessor&&(e=this.valueProcessor(e)),this._value=e),this.onValueChanged?this.onValueChanged(e,i,this):a2&&console.log("VolumeParameter: onValueChanged not set")}testIfValueChanged(e){return this._valueRaw!==e}}UH([x()],kt.prototype,"overrideState",1);UH([x()],kt.prototype,"value",1);var use=Object.defineProperty,dse=Object.getOwnPropertyDescriptor,fse=(n,e,t,i)=>{for(var s=i>1?void 0:i?dse(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&use(e,t,s),s};const pse=se("debugpost");class cr extends Ie{constructor(t=void 0){super();u(this,"active",!0);u(this,"_result");u(this,"_didCreateVolumeParameters",!1);if(t){this.ensureVolumeParameters();for(const i of Object.keys(t)){const s=t[i],r=this[i];r instanceof kt&&(r.value=s)}}}onEnable(){this.__internalDidAwakeAndStart&&(this.active=!0)}onDisable(){this.active=!1}init(){}apply(){var t;return this.ensureVolumeParameters(),this._result||(this._result=(t=this.onCreateEffect)==null?void 0:t.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){pse&&console.warn("DISPOSE",this),this._result&&(Array.isArray(this._result)?this._result.forEach(t=>t.dispose()):this._result.dispose()),this._result=void 0}initParameters(){const t=Object.keys(this);for(const i of t){const s=this[i];s instanceof kt&&s.__init()}}onAfterDeserialize(t,i){if(typeof t=="object"){const s=this.$serializedTypes;if(s){for(const r of Object.keys(s))if(s[r]===kt){const a=t[r];if(a!==void 0){const c=this[r];c.value=a}}}}}onEditorModification(t){const i=t.propertyName;if(this[i]instanceof kt){const s=t.value;return this[i].value=s,!0}}ensureVolumeParameters(){if(this._didCreateVolumeParameters)return;this._didCreateVolumeParameters=!0;const t=this.$serializedTypes;if(t)for(const i of Object.keys(t))t[i]===kt&&(this[i]||(this[i]=new kt))}}fse([x()],cr.prototype,"active",2);var mse=Object.defineProperty,gse=Object.getOwnPropertyDescriptor,vse=(n,e,t,i)=>{for(var s=i>1?void 0:i?gse(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&mse(e,t,s),s};const Ase=se("debugpost"),FM={};function oa(n,e){FM[n]=e}function yse(n){return n.__type in FM?FM[n.__type]:(Ase&&n.__type&&console.warn("Unknown postprocessing type",n.__type,n),cr)}class HA{constructor(){u(this,"components",[])}init(){var e;(e=this.components)==null||e.forEach(t=>t.init())}}vse([nm([n=>yse(n),cr])],HA.prototype,"components",2);var _se=Object.defineProperty,bse=Object.getOwnPropertyDescriptor,xse=(n,e,t,i)=>{for(var s=i>1?void 0:i?bse(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&_se(e,t,s),s};class VA extends cr{constructor(){super(...arguments);u(this,"preset")}get typeName(){return"Antialiasing"}onCreateEffect(){const t=new yY({preset:Lf.HIGH,edgeDetectionMode:gI.DEPTH});return this.preset.onValueChanged=i=>{t.applyPreset(i)},t}}xse([x(kt)],VA.prototype,"preset",2);oa("Antialiasing",VA);class Sw{constructor(){u(this,"files",[])}get extensionName(){return"Audio"}onExportObject(e,t,i){const s=le.getComponents(e,Cn);if(s.length)for(const r of s){if(!r.clip||typeof r.clip!="string"||!r.playOnAwake)continue;const o=r.clip.split("/").pop();this.files.includes(r.clip)||this.files.push(r.clip),t.addEventListener("serialize",(a,c)=>{a.appendLine(),a.beginBlock(`def SpatialAudio "${t.name}"`),a.appendLine(`uniform asset filePath = @audio/${o}@`),a.appendLine(`uniform token auralMode = "${r.spatialBlend>0?"spatial":"nonSpatial"}"`),a.appendLine(`uniform token playbackMode = "${r.loop?"loopFromStage":"onceFromStart"}"`),a.appendLine(`uniform float gain = ${r.volume}`),a.closeBlock()})}}async onAfterSerialize(e){for(const t of this.files){const i=t.split("/").pop(),o=await(await(await fetch(t)).blob()).arrayBuffer(),a=new Uint8Array(o);e.files["audio/"+i]=a}}}const Zu=se("debugautosync"),ZC=Symbol("syncerId");class wse{constructor(){u(this,"_syncers",{})}getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];const t=new Sse(e);return t[ZC]=e.guid,this._syncers[t[ZC]]=t,t}removeSyncer(e){delete this._syncers[e[ZC]]}}const zR=new wse;class Sse{constructor(e){u(this,"comp");u(this,"hasChanges",!1);u(this,"changedProperties",{});u(this,"data",{});u(this,"_boundEvent");u(this,"_handleReceivingMethod");u(this,"_isReceiving",!1);u(this,"_isInit",!1);this.comp=e}get networkingKey(){return this.comp.guid}init(e){if(this._isInit)return;this._isInit=!0,this.comp=e,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 t=this.comp.context.connection.tryGetState(this.comp.guid);t&&this.onHandleReceiving(t)}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(e,t){this._isReceiving||(Zu&&console.log("Property changed: "+e,t),this.hasChanges=!0,this.changedProperties[e]=t)}onHandleSending(){if(!this.hasChanges)return;this.hasChanges=!1;const e=this.comp.context.connection;if(!e||!e.isConnected){for(const t in this.changedProperties)delete this.changedProperties[t];return}for(const t in this.data)delete this.data[t];this.data.guid=this.comp.guid;for(const t in this.changedProperties){const i=this.changedProperties[t];delete this.changedProperties[t],this.data[t]=i}e.send(this.networkingKey,this.data)}onHandleReceiving(e){if(Zu&&console.log("RECEIVE",this.comp.name,this.comp.guid,e),!this._isInit||!this.comp)return;const t=e.guid;if(!(t&&t!==this.comp.guid)){Zu&&console.log("RECEIVED",this.comp.name,this.comp.guid,e);try{this._isReceiving=!0;for(const i in e){if(i==="guid")continue;const s=e[i];this.comp[i]=s,Zu&&console.log("SET",i,s)}}catch(i){console.error(i)}finally{this._isReceiving=!1}}}}function Cse(n,e){let t=e!==n;return!t&&n&&e&&(Array.isArray(n)&&Array.isArray(e)||typeof n=="object"&&typeof e=="object")&&(t=!0),t}const Xg=Symbol("AutoSyncHandler");function Ese(n){if(n[Xg])return n[Xg];const e=zR.getOrCreateSyncer(n);return e==null||e.init(n),n[Xg]=e,e}function Mse(n){const e=n[Xg];e&&(zR.removeSyncer(e),e.destroy(),delete n[Xg])}const GR=function(n){return function(e,t){var h;let i="";typeof t=="string"?i=t:i=t.name;let s=null,r;typeof n=="string"?r=e[n]:typeof n=="function"&&(r=n);const o=e,a=o.__internalAwake;if(typeof a!="function"){(Zu||Mt())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+((h=e==null?void 0:e.constructor)==null?void 0:h.name)+'" is not supported',e);return}Zu&&console.log(i);const c=Symbol(i);o.__internalAwake=function(){if(this[c]!==void 0)return;this[c]=this[i],s=zR.getOrCreateSyncer(this);const d=Object.getOwnPropertyDescriptor(this,i);if((d==null?void 0:d.set)===void 0){let f=!1;Object.defineProperty(this,i,{set:function(p){var g;const m=this[c];if(this[c]=p,f){Mt()&&console.warn("Recursive call detected",i);return}f=!0;try{const y=Cse(p,m);Zu&&console.log("SyncField assignment",i,"changed?",y,p),y&&(r==null?void 0:r.call(this,p,m))!==!1&&((g=Ese(this))==null||g.notifyChanged(i,p))}finally{f=!1}},get:function(){return this[c]},configurable:!0,enumerable:!0})}s==null||s.init(this),a.call(this)};const l=o.__internalDestroy;o.__internalDestroy=function(){Mse(this),l.call(this)}}};var Tse=Object.defineProperty,Ise=Object.getOwnPropertyDescriptor,Cw=(n,e,t,i)=>{for(var s=i>1?void 0:i?Ise(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Tse(e,t,s),s};const zo=se("debugplayersync");class cm extends Ie{constructor(){super(...arguments);u(this,"autoSync",!0);u(this,"asset");u(this,"onPlayerSpawned");u(this,"_localInstance");u(this,"onJoinedRoom",()=>{zo&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()})}awake(){this.watchTabVisible(),this.onPlayerSpawned||(this.onPlayerSpawned=new gs)}onEnable(){this.context.connection.beginListen(mi.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(mi.JoinedRoom,this.onJoinedRoom),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(mi.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(mi.JoinedRoom,this.onJoinedRoom)}async getInstance(){var i,s,r,o,a,c;if(this._localInstance)return this._localInstance;if(zo&&console.log("PlayerSync.createInstance",(i=this.asset)==null?void 0:i.uri),!((s=this.asset)!=null&&s.asset)&&!((r=this.asset)!=null&&r.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 t=await this._localInstance;if(t){const l=le.getComponent(t,qo);l?(l.owner=this.context.connection.connectionId,(a=this.onPlayerSpawned)==null||a.invoke(t)):(this._localInstance=void 0,console.error("<strong>Failed finding PlayerState on "+((c=this.asset)==null?void 0:c.uri)+"</strong>: please make sure the asset has a PlayerState component!"),le.destroySynced(t))}else this._localInstance=void 0,console.warn("PlayerSync: failed instantiating asset!");return this._localInstance}destroyInstance(){var t;(t=this._localInstance)==null||t.then(i=>(zo&&console.log("PlayerSync.destroyInstance",i),le.destroySynced(i))),this._localInstance=void 0}watchTabVisible(){window.addEventListener("visibilitychange",t=>{if(document.visibilityState==="visible")for(let i=qo.all.length-1;i>=0;i--){const s=qo.all[i];(!s.owner||!this.context.connection.userIsInRoom(s.owner))&&s.doDestroy()}})}}Cw([x()],cm.prototype,"autoSync",2);Cw([x(ii)],cm.prototype,"asset",2);Cw([x(gs)],cm.prototype,"onPlayerSpawned",2);var NH=(n=>(n.OwnerChanged="ownerChanged",n))(NH||{}),hg;const Ms=(hg=class extends Ie{constructor(){super(...arguments);u(this,"onOwnerChangeEvent",new gs);u(this,"onFirstOwnerChangeEvent",new gs);u(this,"hasOwner",!1);u(this,"owner");u(this,"dontDestroy",!1);u(this,"onUserLeftRoom",e=>{if(e.userId===this.owner){zo&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}})}static get all(){return Ms._all}static get local(){return Ms._local}static getFor(e){if(e instanceof ge)return le.getComponentInParent(e,Ms);if(e instanceof Ie)return le.getComponentInParent(e.gameObject,Ms)}static isLocalPlayer(e){const t=Ms.getFor(e);return(t==null?void 0:t.isLocalPlayer)??!1}static addEventListener(e,t){return this._callbacks[e]||(this._callbacks[e]=[]),this._callbacks[e].push(t),t}static removeEventListener(e,t){if(!this._callbacks[e])return;const i=this._callbacks[e].indexOf(t);i>=0&&this._callbacks[e].splice(i,1)}static dispatchEvent(e,t){if(this._callbacks[e])for(const i of this._callbacks[e])i(t)}get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(e,t){var o,a;zo&&console.log("PlayerSync.onOwnerChange",this,"newOwner",e,"oldOwner",t);const i=Ms._local.indexOf(this);i>=0&&Ms._local.splice(i,1);const s={playerState:this,oldValue:t,newValue:e};if(this.hasOwner||(this.hasOwner=!0,(o=this.onFirstOwnerChangeEvent)==null||o.invoke(s)),(a=this.onOwnerChangeEvent)==null||a.invoke(s),this.owner===this.context.connection.connectionId){Ms._local.push(this);const c=new CustomEvent("local-owner-changed",{detail:s});this.dispatchEvent(c)}const r=new CustomEvent("owner-changed",{detail:s});this.dispatchEvent(r),Ms.dispatchEvent("ownerChanged",r)}awake(){Ms.all.push(this),zo&&console.log("Registered new PlayerState",this.guid,Ms.all.length-1,Ms.all),this.context.connection.beginListen(mi.UserLeftRoom,this.onUserLeftRoom)}async start(){zo&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await Yo(300),this.context.connection.userIsInRoom(this.owner)==!1&&(zo&&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||(zo&&console.warn("PlayerState.start โ†’ owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?zo&&console.warn("PlayerState.start โ†’ owner is still undefined but dontDestroy is set to true",this.name):(zo&&console.warn(`PlayerState.start โ†’ owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):console.log("PlayerState.start โ†’ owner is assigned",this.owner)},2e3))}doDestroy(){zo&&console.log("PlayerSync.doDestroy โ†’ syncDestroy",this.name),aw(this.gameObject,this.context.connection)}onDestroy(){if(this.context.connection.stopListen(mi.UserLeftRoom,this.onUserLeftRoom),Ms.all.splice(Ms.all.indexOf(this),1),this.isLocalPlayer){const e=Ms._local.indexOf(this);e>=0&&Ms._local.splice(e,1)}}},u(hg,"_all",[]),u(hg,"_local",[]),u(hg,"_callbacks",{}),hg);let qo=Ms;Cw([GR(qo.prototype.onOwnerChange)],qo.prototype,"owner",2);const Rse=se("debugavatar"),Aa=class extends Ie{constructor(){super(...arguments);u(this,"connectionId");u(this,"avatar")}static getAvatar(t){return t>=0&&t<Aa.instances.length?Aa.instances[t]:null}static onAvatarMarkerCreated(t){return Aa._onNewAvatarMarkerAdded.push(t),t}static onAvatarMarkerDestroyed(t){return Aa._onAvatarMarkerDestroyed.push(t),t}awake(){Aa.instances.push(this),Rse&&console.log(this);for(const t of Aa._onNewAvatarMarkerAdded)t({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){Aa.instances.splice(Aa.instances.indexOf(this),1);for(const t of Aa._onAvatarMarkerDestroyed)t({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}};let Zn=Aa;u(Zn,"instances",[]),u(Zn,"_onNewAvatarMarkerAdded",[]),u(Zn,"_onAvatarMarkerDestroyed",[]);var Pse=Object.defineProperty,Bse=Object.getOwnPropertyDescriptor,Dse=(n,e,t,i)=>{for(var s=i>1?void 0:i?Bse(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Pse(e,t,s),s};const Gf=se("debugxrflags"),zH=se("disablexrflags");zH&&console.warn("XRFlags are disabled");var rc=(n=>(n[n.Never=0]="Never",n[n.Browser=1]="Browser",n[n.AR=2]="AR",n[n.VR=4]="VR",n[n.FirstPerson=8]="FirstPerson",n[n.ThirdPerson=16]="ThirdPerson",n[n.All=4294967295]="All",n))(rc||{});const JP=class{constructor(){u(this,"Mask",17)}Has(e){return(this.Mask&e)!==0}Set(e){Gf&&console.warn("Set XR flag state to",e),this.Mask=e,lo.Apply()}Enable(e){this.Mask|=e,lo.Apply()}Disable(e){this.Mask&=~e,lo.Apply()}Toggle(e){this.Mask^=e,lo.Apply()}EnableAll(){this.Mask=-1,lo.Apply()}DisableAll(){this.Mask=0,lo.Apply()}};let Bs=JP;u(Bs,"Global",new JP);var ug;const Kc=(ug=class extends Ie{constructor(){super(...arguments);u(this,"visibleIn")}static Apply(){for(const e of this.registry)e.UpdateVisible(Bs.Global)}awake(){Kc.registry.push(this)}onEnable(){Kc.firstApply?this.UpdateVisible(Bs.Global):(Kc.firstApply=!0,Kc.Apply())}onDestroy(){const e=Kc.registry.indexOf(this);e>=0&&Kc.registry.splice(e,1)}get isOn(){return this.gameObject.visible}UpdateVisible(e=null){if(zH)return;let t;const i=e;if(i&&typeof i=="number"&&(console.assert(typeof i=="number","XRFlag.UpdateVisible: state must be a number",i),Gf&&console.log(i),Kc.buffer.Mask=i,e=Kc.buffer),e instanceof Bs?(Gf&&console.warn(this.name,"use passed in mask",e.Mask,this.visibleIn),t=e.Has(this.visibleIn)):(Gf&&console.log(this.name,"use global mask"),Bs.Global.Has(this.visibleIn)),t!==void 0)if(t)Gf&&console.log(this.name,"is visible",this.gameObject.uuid),le.setActive(this.gameObject,!0);else{if(Gf&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},u(ug,"registry",[]),u(ug,"firstApply"),u(ug,"buffer",new Bs),ug);let lo=Kc;Dse([x()],lo.prototype,"visibleIn",2);var Ose=Object.defineProperty,kse=Object.getOwnPropertyDescriptor,HR=(n,e,t,i)=>{for(var s=i>1?void 0:i?kse(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Ose(e,t,s),s};const $m=se("debugwebxr"),c2=new Ee().setFromAxisAngle(new w(0,1,0),Math.PI);class Id extends Ie{constructor(){super(...arguments);u(this,"head");u(this,"leftHand");u(this,"rightHand");u(this,"_syncTransforms")}async onEnterXR(t){if(!this.activeAndEnabled)return;$m&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const i=qo.getFor(this);if(i!=null&&i.owner){const s=this.gameObject.addNewComponent(Zn);s.avatar=this.gameObject,s.connectionId=i.owner}else this.context.connection.isConnected?console.error("No player state found for avatar",this):i&&!this.context.connection.isConnected&&(i.dontDestroy=!0)}onLeaveXR(t){const i=this.gameObject.getComponent(Zn);i&&i.destroy()}onUpdateXR(t){var c,l;if(!this.activeAndEnabled)return;const i=qo.isLocalPlayer(this);if(!i)return;const s=t.xr;if(s.rig&&s.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),s.rig.gameObject.add(this.gameObject)),this._syncTransforms&&i)for(const h of this._syncTransforms)h.fastMode=!0,h.isOwned()||h.requestOwnership();if(this.head&&this.context.mainCamera){const h=this.head.asset;if(h.position.copy(this.context.mainCamera.position),h.quaternion.copy(this.context.mainCamera.quaternion),h.quaternion.x*=-1,this.context.time.frameCount%10===0){const d=le.getComponentsInChildren(this.head.asset,lo);for(const f of d)f.enabled=!1,f.gameObject.visible=!1}}const r=t.xr.leftController,o=(c=this.leftHand)==null?void 0:c.asset;r&&o&&(o.position.copy(r.gripPosition),o.quaternion.copy(r.gripQuaternion),o.quaternion.multiply(c2),o.visible=r.isTracking);const a=t.xr.rightController;if(a&&((l=this.rightHand)!=null&&l.asset)){const h=this.rightHand.asset;h.position.copy(a.gripPosition),h.quaternion.copy(a.gripQuaternion),h.quaternion.multiply(c2),h.visible=a.isTracking}}onBeforeRender(){this.context.time.frame%10===0&&this.updateRemoteAvatarVisibility()}updateRemoteAvatarVisibility(){var t,i,s;if(this.context.connection.isConnected){const r=qo.getFor(this);if(r&&r.isLocalPlayer==!1){const o=yt.getXRSync(this.context);if(o&&o.hasState(r.owner)){this.tryFindAvatarObjectsIfMissing();const a=(t=this.leftHand)==null?void 0:t.asset;a&&(a.visible=(o==null?void 0:o.isTracking(r.owner,"left"))??!1);const c=(i=this.rightHand)==null?void 0:i.asset;c&&(c.visible=(o==null?void 0:o.isTracking(r.owner,"right"))??!1)}if((s=this.head)!=null&&s.asset){const a=le.getComponentsInChildren(this.head.asset,lo);for(const c of a)c.enabled=!1,c.gameObject.visible=!0}}}}tryFindAvatarObjectsIfMissing(){if(!this.head||!this.leftHand||!this.rightHand){const t={head:this.head,leftHand:this.leftHand,rightHand:this.rightHand};bG.tryFindAvatarObjects(this.gameObject,this.sourceId||"",t),t.head&&(this.head=t.head),t.leftHand&&(this.leftHand=t.leftHand),t.rightHand&&(this.rightHand=t.rightHand)}}async prepareAvatar(){if(this.tryFindAvatarObjectsIfMissing(),this.head)this.head instanceof ge&&(this.head=new ii("",this.sourceId,this.head));else{const t=new ge;t.name="Head";const i=Dp.createPrimitive(_d.Cube);t.add(i),this.gameObject.add(t),this.head=new ii("",this.sourceId,t),$m&&console.log("Create head",t)}if(this.rightHand)this.rightHand instanceof ge&&(this.rightHand=new ii("",this.sourceId,this.rightHand));else{const t=new ge;t.name="Right Hand",this.gameObject.add(t),this.rightHand=new ii("",this.sourceId,t),$m&&console.log("Create right hand",t)}if(this.leftHand)this.leftHand instanceof ge&&(this.leftHand=new ii("",this.sourceId,this.leftHand));else{const t=new ge;t.name="Left Hand",this.gameObject.add(t),this.leftHand=new ii("",this.sourceId,t),$m&&console.log("Create left hand",t)}await this.loadAvatarObjects(this.head,this.leftHand,this.rightHand),qo.isLocalPlayer(this.gameObject)&&(this._syncTransforms=le.getComponentsInChildren(this.gameObject,Nh))}async loadAvatarObjects(t,i,s){const r=t.loadAssetAsync(),o=i.loadAssetAsync(),a=s.loadAssetAsync(),c=new Array;r&&c.push(r),o&&c.push(o),a&&c.push(a);const l=await fA(c);$m&&console.log("Avatar loaded results:",l)}}HR([x(ii)],Id.prototype,"head",2);HR([x(ii)],Id.prototype,"leftHand",2);HR([x(ii)],Id.prototype,"rightHand",2);class bc{static Add(e,t,i=null){if(t){for(const s of this.Pois)if(s.obj===t)return;this.Pois.push({obj:t,avatar:i}),this.LastChangeTime=e.time.time}}static Remove(e,t){var i;if(t){for(const s of this.Pois)if(s.obj===t){this.Pois.splice(this.Pois.indexOf(s),1),this.LastChangeTime=(e==null?void 0:e.time.time)??((i=Ot.Current)==null?void 0:i.time.time);return}}}}u(bc,"Pois",[]),u(bc,"LastChangeTime",0);class Lse{constructor(){u(this,"guid");u(this,"position",new w)}}class Hv extends Ie{constructor(){super(...arguments);u(this,"target",null);u(this,"avatar",null);u(this,"_model",null);u(this,"_targetModel",new Lse);u(this,"_currentTargetObject",null);u(this,"_lastUpdateTime",0);u(this,"_lookDuration",0);u(this,"_lastPoiChangedTime",0)}set controlledTarget(t){this.target=t;const i=$.get("MoveRandom");if(i&&this.target){const s=le.getComponent(this.target,i);s&&s.destroy()}}awake(){if(this.avatar=le.getComponentInParent(this.gameObject,Zn),this.avatar){const t=le.getComponentInParent(this.gameObject,Zn);this._model=new LI(this.context.connection,this.guid),t!=null&&t.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",t=>{var i;this.target&&t&&t.guid===((i=this.avatar)==null?void 0:i.guid)&&sr(this.target,t.position)})}update(){var i;if((!this.context.connection.isConnected||(i=this._model)!=null&&i.hasOwnership)&&(bc.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=bc.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){const s=Dt(this._currentTargetObject);sr(this.target,s),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(s))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;const i=bc.Pois;if(i.length>0){const s=i[Math.floor(Math.random()*i.length)];if(s&&s.obj){if(s.avatar&&s.avatar===this.avatar)return;this._currentTargetObject=s.obj}}}}}const ep=se("debugnetworkingstreams");var mc=(n=>(n.Connected="peer-user-connected",n.StreamReceived="receive-stream",n.StreamEnded="call-ended",n.Disconnected="peer-user-disconnected",n.UserJoined="user-joined",n))(mc||{});class GH{constructor(e,t){u(this,"type","call-ended");u(this,"userId");u(this,"direction");this.userId=e,this.direction=t}}class HH{constructor(e,t){u(this,"type","receive-stream");u(this,"stream");u(this,"target");this.stream=e,this.target=t}}class Fse{constructor(e,t){u(this,"guid");u(this,"peerId");u(this,"dontSave",!0);this.guid=e.id,this.peerId=t}}var VH=(n=>(n.Incoming="incoming",n.Outgoing="outgoing",n))(VH||{});class Use extends ys{constructor(t,i,s){super();u(this,"userId");u(this,"direction");u(this,"call");u(this,"_stream",null);u(this,"_isDisposed",!1);this.userId=t,this.call=i,this.direction=s,this._stream=null,i.on("stream",r=>{if(ep&&console.log("Receive video",r.getAudioTracks(),r.getVideoTracks()),this._stream=r,s==="incoming"){const o=new HH(r,this);this.dispatchEvent(o)}}),i.on("close",()=>{this.dispatchEvent(new GH(t,s))})}get stream(){return this._stream}close(){this._isDisposed||(this._isDisposed=!0,this.call.close(),pl(this._stream))}get isOpen(){var t;return((t=this.call.peerConnection)==null?void 0:t.connectionState)==="connected"}get isOpening(){var t;return((t=this.call.peerConnection)==null?void 0:t.connectionState)==="connecting"}get isClosed(){return!this.isOpen}}const ap=class extends ys{constructor(t,i){super();u(this,"id");u(this,"context");u(this,"_peer");u(this,"_incomingCalls",[]);u(this,"_outgoingCalls",[]);u(this,"_enabled",!1);u(this,"_enabledPeer",!1);u(this,"onConnectRoomFn",this.onConnectRoom.bind(this));u(this,"onPeerConnectFn",this.onPeerConnect.bind(this));u(this,"onPeerReceiveCallFn",this.onPeerReceivingCall.bind(this));this.context=t,this.id=i,this.setupPeer(),navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia}static getOrCreate(t,i){if(ap.instances.has(i))return ap.instances.get(i);const s=new ap(t,i);return ap.instances.set(i,s),s}getMyPeerId(){if(this.context.connection.connectionId)return this.getPeerIdFromUserId(this.context.connection.connectionId)}getPeerIdFromUserId(t){return this.id+"-"+t}getUserIdFromPeerId(t){return t.substring(this.id.length+1)}makeCall(t,i){var o;const s={metadata:{userId:this.context.connection.connectionId}},r=(o=this._peer)==null?void 0:o.call(t,i,s);if(r)return this.registerCall(r,"outgoing")}get peer(){return this._peer}enable(){this._enabled||(this._enabled=!0,this.context.connection.beginListen(mi.JoinedRoom,this.onConnectRoomFn),this.subscribePeerEvents())}disable(){this._enabled&&(this._enabled=!1,this.context.connection.stopListen(mi.JoinedRoom,this.onConnectRoomFn),this.unsubscribePeerEvents())}onConnectRoom(){this.setupPeer()}setupPeer(){if(this.context.connection.connectionId&&!this._enabledPeer){if(this._enabledPeer=!0,!this._peer){const t=this.getMyPeerId();t?this._peer=Q3(t):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(t){ep&&console.log("Peer connected as",t),this.context.connection.send("peer-user-connected",new Fse(this,t))}onPeerReceivingCall(t){t.answer(),this.registerCall(t,"incoming")}registerCall(t,i){const s=t.metadata;(!s||!s.userId)&&console.error("Missing call metadata",t);const r=s.userId;i==="incoming"&&ep?console.log("Receive call from",t.metadata):ep&&console.log("Make call to",t.metadata);const o=i==="incoming"?this._incomingCalls:this._outgoingCalls,a=new Use(r,t,i);return o.push(a),t.on("error",c=>{console.error("Call error",c)}),t.on("close",()=>{ep&&console.log("Call ended",t.metadata),t.close();const c=o.indexOf(a);c!==-1&&o.splice(c,1)}),a.addEventListener("call-ended",c=>{this.dispatchEvent(c)}),i==="incoming"&&(a.addEventListener("receive-stream",c=>{this.dispatchEvent(c)}),t.on("stream",()=>{let c=0;const l=setInterval(()=>{const h=c===0;!a.isOpen&&h&&(c+=1,clearInterval(l),a.close())},2e3)})),a}};let Ap=ap;u(Ap,"instances",new Map);class QA extends ys{constructor(t,i){super();u(this,"context");u(this,"peer");u(this,"_sendingStreams",new Map);u(this,"debug",!1);u(this,"onJoinedRoom",t=>{this.debug&&console.log(`${t.userId} joined room and I'm currently sending ${this._sendingStreams.size} streams`),this._sendingStreams.size>0&&this.updateSendingCalls()});u(this,"onReceiveStream",t=>{this.debug&&console.log("RECEIVE STREAM",t),this.dispatchEvent({type:"receive-stream",target:this,stream:t.stream,userId:t.userId})});u(this,"onCallEnded",t=>{this.dispatchEvent(t)});u(this,"onUserConnected",t=>{if(this.peer.id===t.guid){this.debug&&console.log("USER CONNECTED",t.guid,t);const i=this._sendingStreams.keys().next().value;this.peer.makeCall(t.peerId,i)}});u(this,"onUserLeft",t=>{this.stopCallsToUsersThatAreNotInTheRoomAnymore()});this.context=t,this.peer=i,ep&&(this.debug=!0)}static create(t){const i=Ap.getOrCreate(t.context,t.context.connection.connectionId);return new QA(t.context,i)}startSendingStream(t){this._sendingStreams.has(t)?console.warn("Received start sending stream with stream that is already being sent"):(this._sendingStreams.set(t,[]),this.updateSendingCalls())}stopSendingStream(t){if(t){const i=this._sendingStreams.get(t);if(i){this.debug&&console.log("Closing calls",i);for(const s of i)s.close()}this._sendingStreams.delete(t),i&&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(mi.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(mi.UserJoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(mi.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(mi.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(mi.UserJoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(mi.UserLeftRoom,this.onUserLeft)}updateSendingCalls(){var s;let t=!1;const i=this.context.connection.connectionId;for(const r of this._sendingStreams.keys()){const o=this._sendingStreams.get(r)||[];for(const a of this.context.connection.usersInRoom()){if(a===i)continue;const c=o.find(l=>l.userId===a);if(!c||((s=c.stream)==null?void 0:s.active)===!1){this.debug&&console.log("Starting call to",a,i);const l=this.peer.makeCall(this.peer.getPeerIdFromUserId(a),r);l&&(t=!0,o.push(l))}}this._sendingStreams.set(r,o)}this.stopCallsToUsersThatAreNotInTheRoomAnymore(),t&&this.debug&&console.log("Currently sending",this._sendingStreams)}stopCallsToUsersThatAreNotInTheRoomAnymore(){for(const t of this._sendingStreams.keys()){const i=this._sendingStreams.get(t);if(i)for(let s=i.length-1;s>=0;s--){const r=i[s];this.context.connection.userIsInRoom(r.userId)||(r.close(),i.splice(s,1))}}}}function pl(n){if(n&&n instanceof MediaStream)for(const e of n.getTracks())e.stop()}var Nse=Object.defineProperty,zse=Object.getOwnPropertyDescriptor,QH=(n,e,t,i)=>{for(var s=i>1?void 0:i?zse(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Nse(e,t,s),s};const Gse="noVoip",Hse=se("debugvoip");class Rd extends Ie{constructor(){super(...arguments);u(this,"autoConnect",!1);u(this,"runInBackground",!0);u(this,"debug",!1);u(this,"_net");u(this,"_outputStream",null);u(this,"onJoinedRoom",async()=>{await Yo(300),this.autoConnect&&!this.isSending&&this.connect()});u(this,"_incomingStreams",new Map);u(this,"onReceiveStream",t=>{const i=t.target.userId,s=t.stream,r=this._incomingStreams.get(i);if(r)r.srcObject=s,r.setAttribute("autoplay","true");else{const o=new Audio;this._incomingStreams.set(i,o),o.setAttribute("autoplay","true"),o.srcObject=s}});u(this,"onStreamEnded",t=>{const i=this._incomingStreams.get(t.userId);pl(i==null?void 0:i.srcObject),this._incomingStreams.delete(t.userId)});u(this,"onEnabledChanged",()=>{for(const t of this._incomingStreams){const i=t[1];i.muted=!this.enabled}});u(this,"onVisibilityChanged",()=>{if(this.runInBackground)return;const i=!(document.visibilityState==="visible");this.setMuted(i);for(const s of this._incomingStreams){const r=s[1];r.muted=i}})}awake(){Hse&&(this.debug=!0),this.debug&&window.addEventListener("keydown",async t=>{t.key==="v"&&(console.log("MUTE?",!this.isMuted),this.setMuted(!this.isMuted))})}onEnable(){this._net||(this._net=QA.create(this)),this._net.addEventListener(mc.StreamReceived,this.onReceiveStream),this._net.addEventListener(mc.StreamEnded,this.onStreamEnded),this._net.enable(),this.autoConnect&&(this.context.connection.isConnected?this.connect():this.context.connection.beginListen(mi.JoinedRoom,this.onJoinedRoom)),this.onEnabledChanged(),window.addEventListener("visibilitychange",this.onVisibilityChanged)}onDisable(){var t;this._net.stopSendingStream(this._outputStream),this._net.removeEventListener(mc.StreamReceived,this.onReceiveStream),this._net.removeEventListener(mc.StreamEnded,this.onStreamEnded),(t=this._net)==null||t.disable(),this.context.connection.stopListen(mi.JoinedRoom,this.onJoinedRoom),this.onEnabledChanged(),window.removeEventListener("visibilitychange",this.onVisibilityChanged)}get isSending(){return this._outputStream!=null&&this._outputStream.active}async connect(t){if(this.context.connection.isConnected){if(!await M1())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),pl(this._outputStream),this._outputStream=await this.getAudioStream(t),this._outputStream?(this._net.startSendingStream(this._outputStream),!0):(await M1()?console.error("VOIP: Could not get audio stream - please make sure to connect an audio device and grant microphone permissions"):eN("Microphone permissions not granted: Please grant microphone permissions to use voice chat"),!1)}disconnect(){this._net.stopSendingStream(this._outputStream),pl(this._outputStream),this._outputStream=null}setMuted(t){var s;const i=(s=this._outputStream)==null?void 0:s.getAudioTracks();if(i)for(const r of i)r.enabled=!t}get isMuted(){var i;if(this._outputStream===null)return!1;const t=(i=this._outputStream)==null?void 0:i.getAudioTracks();if(t){for(const s of t)if(!s.enabled)return!0}return!1}getFrequency(t){return this.unsupported_getfrequency||(this.unsupported_getfrequency=!0,Mt()&&pn("VOIP: getFrequency is currently not supported"),console.warn("VOIP: getFrequency is currently not supported")),null}async getAudioStream(t){return navigator.mediaDevices.getUserMedia?await navigator.mediaDevices.getUserMedia({audio:t??!0,video:!1}).catch(s=>(console.warn("VOIP failed getting audio stream",s),null)):(console.error("No getDisplayMedia support"),null)}}QH([x()],Rd.prototype,"autoConnect",2);QH([x()],Rd.prototype,"runInBackground",2);var Vse=Object.defineProperty,Qse=Object.getOwnPropertyDescriptor,jH=(n,e,t,i)=>{for(var s=i>1?void 0:i?Qse(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Vse(e,t,s),s};const jse=se("debugmouth");class jA extends Ie{constructor(){super(...arguments);u(this,"idle",[]);u(this,"talking",[]);u(this,"marker",null);u(this,"voip",null);u(this,"lastMouthChangeTime",0);u(this,"mouthChangeLength",0)}awake(){setTimeout(()=>{this.voip=le.findObjectOfType(Rd,this.context),this.marker||(this.marker=le.getComponentInParent(this.gameObject,Zn))},3e3)}update(){var s;if(!this.voip||this.context.time.frameCount%10!==0)return;let t=((s=this.marker)==null?void 0:s.connectionId)??null;if(!t){jse&&(t=null);return}const i=this.voip.getFrequency(t)??0;this.updateLips(i)}updateLips(t){if(this.context.time.time-this.lastMouthChangeTime>this.mouthChangeLength){if(this.mouthChangeLength=.05+Math.random()*.1,this.talking&&this.talking.length>0&&t>30){this.lastMouthChangeTime=this.context.time.time;const i=Math.floor(Math.random()*this.talking.length);this.setMouthShapeActive(this.talking,i)}else if(this.idle.length>0&&this.context.time.time-this.lastMouthChangeTime>.5){this.lastMouthChangeTime=this.context.time.time;const i=Math.floor(Math.random()*this.idle.length);this.setMouthShapeActive(this.idle,i)}}}setMouthShapeActive(t,i){if(t){t!=this.idle?this.idle.map(s=>s.visible=!1):this.talking.map(s=>s.visible=!1);for(let s=0;s<t.length;s++){const r=t[s];r&&(r.visible=s===i)}}}}jH([x(ge)],jA.prototype,"idle",2);jH([x(ge)],jA.prototype,"talking",2);class VR extends Ie{constructor(){super(...arguments);u(this,"voip",null);u(this,"marker",null);u(this,"_startPosition",null)}awake(){this.voip=le.findObjectOfType(Rd,this.context),this.marker=le.getComponentInParent(this.gameObject,Zn)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!==0)return;const t=this.marker.connectionId,i=this.voip.getFrequency(t);if(i==null)return;this._startPosition||(this._startPosition=this.gameObject.position.clone());const s=i/100;this.gameObject.position.y=this._startPosition.y+s*.07}}var Wse=Object.defineProperty,qse=Object.getOwnPropertyDescriptor,Ew=(n,e,t,i)=>{for(var s=i>1?void 0:i?qse(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Wse(e,t,s),s};class Pd extends Ie{constructor(){super(...arguments);u(this,"eyes",[]);u(this,"lastBlinkTime",0);u(this,"blinkLength",0);u(this,"eyesOpen",!0);u(this,"state",null)}awake(){this.state=le.getComponentInParent(this.gameObject,lo)}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 i of this.eyes)i&&(i.visible=this.eyesOpen)}}}Ew([x(ge)],Pd.prototype,"eyes",2);Ew([x()],Pd.prototype,"lastBlinkTime",2);Ew([x()],Pd.prototype,"blinkLength",2);Ew([x()],Pd.prototype,"eyesOpen",2);var Xse=Object.defineProperty,Yse=Object.getOwnPropertyDescriptor,QR=(n,e,t,i)=>{for(var s=i>1?void 0:i?Yse(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Xse(e,t,s),s},LE;const WH=(LE=class extends Ie{constructor(){super(...arguments);u(this,"head",null);u(this,"eyes",null);u(this,"target",null);u(this,"brain",null);u(this,"vec",new w);u(this,"currentTargetPoint",new w)}awake(){this.brain||(this.brain=le.getComponentInParent(this.gameObject,Hv)),this.brain||(console.log("No look at brain found, adding it now"),this.brain=le.addNewComponent(this.gameObject,Hv)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}update(){const e=this.target;if(e&&this.head){const t=this.eyes;if(t){const i=Dt(e);this.currentTargetPoint.lerp(i,this.context.time.deltaTime/.1);const s=Dt(this.head),r=this.vec.copy(this.currentTargetPoint).sub(s).normalize();if(r.length()<.1)return;const o=WH.forward;if(o.set(0,0,1),o.applyQuaternion(Di(this.head)),o.dot(r)>.45)for(let c=0;c<t.length;c++)t[c].lookAt(this.currentTargetPoint)}}}},u(LE,"forward",new w(0,0,1)),LE);let lm=WH;QR([x(ge)],lm.prototype,"head",2);QR([x(ge)],lm.prototype,"eyes",2);QR([x(ge)],lm.prototype,"target",2);const eg=se("debugavatar");class Mw{constructor(e,t,i,s){u(this,"root");u(this,"head");u(this,"leftHand");u(this,"rigthHand");var r;this.root=e,this.head=t,this.leftHand=i,this.rigthHand=s,(r=this.root)==null||r.traverse(o=>o.layers.set(2))}get isValid(){return this.head!==null&&this.head!==void 0}}class jR{constructor(){u(this,"avatarRegistryUrl",null)}async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let i=null;if(typeof t=="string"){if(i=await this.loadAvatar(e,t),!i){const r=new Fa;i=le.instantiate(Mp(t,e.scene),r)}}else i=t;if(!i)return null;const s=this.findAvatar(i);return s.isValid?(eg&&console.log("[Custom Avatar] valid config",t,eg?s:""),s):(console.warn("[Custom Avatar] config isn't valid",t,eg?s:""),null)}async loadAvatar(e,t){if(console.assert(t!=null&&typeof t=="string","Avatar id must not be null"),t.length<=0||!t)return null;if(eg&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const s=await fetch("./"+t);let r=null;if(s.ok){const a=await s.blob();a&&(r=await a.arrayBuffer())}if(!r&&(r=await wI(t,t,0,"no url here go away",!0),!r))return null;const o=await Ia().parseSync(e,r,null,0);return(o==null?void 0:o.scene)??null}const i=new im;return BA(i,e),new Promise((s,r)=>{const o=this.avatarRegistryUrl+"/"+t;i.load(o,async a=>{await Ia().createBuiltinComponents(e,o,a,null,void 0),s(a.scene)},a=>{eg&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),s(null)})})}cacheModel(e,t){}findAvatar(e){const t=e;let i=t;i.children.length==1&&(i=e.children[0]);let s=this.findAvatarPart(i,["head"]);const r=this.findAvatarPart(i,["left","hand"]),o=this.findAvatarPart(i,["right","hand"]);if(!s){s=t;const c=new w;new Oi().setFromObject(s).getSize(c);const l=Math.max(c.x,c.y,c.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+l+" meters! Should be < 0.3m"),l>.3&&s.scale.multiplyScalar(1/l*.3)}return new Mw(t,s,r,o)}findAvatarPart(e,t){const i=e.name.toLowerCase();let s=!0;for(const r of t){if(!s)break;i.indexOf(r)===-1&&(s=!1)}if(s)return e;if(e.children)for(const r of e.children){const o=this.findAvatarPart(r,t);if(o)return o}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}var Jse=Object.defineProperty,Kse=Object.getOwnPropertyDescriptor,WR=(n,e,t,i)=>{for(var s=i>1?void 0:i?Kse(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Jse(e,t,s),s};class hm extends Ie{constructor(){super(...arguments);u(this,"length",1);u(this,"depthTest",!0);u(this,"isGizmo",!0);u(this,"_axes",null)}onEnable(){if(this.isGizmo&&!gA)return;this._axes||(this._axes=new Zo(this.length)),this._axes.layers.disableAll(),this._axes.layers.set(this.layer),this.gameObject.add(this._axes);const t=this._axes.material;t&&t.depthTest!==void 0&&(t.depthTest=this.depthTest)}onDisable(){this._axes&&this.gameObject.remove(this._axes)}}WR([x()],hm.prototype,"length",2);WR([x()],hm.prototype,"depthTest",2);WR([x()],hm.prototype,"isGizmo",2);class qR extends Ie{constructor(){super(...arguments);u(this,"from");u(this,"to");u(this,"hint");u(this,"desiredDistance",1)}onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;const t=Dt(this.to).clone(),i=Dt(this.from).clone(),s=t.distanceTo(i),r=t.clone();r.sub(i);const o=i.clone();o.add(t),o.multiplyScalar(.5);const a=Dt(this.hint).clone();a.sub(o);const c=new w;c.crossVectors(a,r),c.crossVectors(r,c),c.normalize();const l=s*.5,h=Math.max(this.desiredDistance,l),d=Math.sqrt(h*h-l*l),f=c.clone();f.multiplyScalar(d),f.add(o),sr(this.gameObject,f);const p=o.clone();p.sub(c),this.gameObject.lookAt(p)}}const Zse=se("debugusdz");class Tw{constructor(){u(this,"behaviours",[]);u(this,"behaviourComponents",[]);u(this,"behaviourComponentsCopy",[])}get extensionName(){return"Behaviour"}addBehavior(e){this.behaviours.push(e)}onBeforeBuildDocument(e){const t=[];return e.root.traverse(i=>{le.foreachComponent(i,s=>{var o;const r=s;if(typeof r.createBehaviours=="function"||typeof r.beforeCreateDocument=="function"||typeof r.afterCreateDocument=="function"||typeof r.afterSerialize=="function"){this.behaviourComponents.push(r);const a=(o=r.beforeCreateDocument)==null?void 0:o.call(r,this,e);a instanceof Promise&&t.push(a)}},!1)}),Promise.all(t)}onExportObject(e,t,i){var s;for(const r of this.behaviourComponents)(s=r.createBehaviours)==null||s.call(r,this,t,i)}onAfterBuildDocument(e){for(const t of this.behaviourComponents)typeof t.afterCreateDocument=="function"&&t.afterCreateDocument(this,e);this.behaviourComponentsCopy=this.behaviourComponents.slice(),this.behaviourComponents.length=0}onAfterHierarchy(e,t){var i;if((i=this.behaviours)!=null&&i.length){t.beginBlock('def Scope "Behaviors"');for(const s of this.behaviours)s.writeTo(this,e.document,t);t.closeBlock()}}async onAfterSerialize(e){Zse&&console.log("onAfterSerialize behaviours",this.behaviourComponentsCopy);for(const t of this.behaviourComponentsCopy)typeof t.afterSerialize=="function"&&(t.afterSerialize.constructor.name==="AsyncFunction"?await t.afterSerialize(this,e):t.afterSerialize(this,e));this.behaviours.length=0}}var $se=Object.defineProperty,ere=Object.getOwnPropertyDescriptor,XR=(n,e,t,i)=>{for(var s=i>1?void 0:i?ere(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&$se(e,t,s),s};class Bd extends cr{constructor(){super(...arguments);u(this,"threshold");u(this,"intensity");u(this,"scatter");u(this,"selectiveBloom",!0)}get typeName(){return"Bloom"}init(){this.threshold.defaultValue=1,this.intensity.defaultValue=0,this.scatter.defaultValue=.2,this.selectiveBloom?(this.threshold.valueProcessor=t=>t,this.intensity.valueProcessor=t=>t,this.scatter.valueProcessor=t=>1*Math.PI*(1-t)):(this.threshold.valueProcessor=t=>t,this.intensity.valueProcessor=t=>t,this.scatter.valueProcessor=t=>100*(1-t))}onCreateEffect(){let t;if(this.selectiveBloom){const i=t=new RN(this.context.scene,this.context.mainCamera,{blendFunction:qt.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,intensity:this.intensity.value});i.inverted=!0}else t=new _I;return this.intensity.onValueChanged=i=>{t.intensity=i},this.threshold.onValueChanged=i=>{t.luminanceMaterial.threshold=i},this.scatter.onValueChanged=i=>{t.luminancePass.enabled=!0,t.luminanceMaterial.smoothing=i},t}}XR([x(kt)],Bd.prototype,"threshold",2);XR([x(kt)],Bd.prototype,"intensity",2);XR([x(kt)],Bd.prototype,"scatter",2);oa("Bloom",Bd);var tre=Object.defineProperty,ire=Object.getOwnPropertyDescriptor,Yr=(n,e,t,i)=>{for(var s=i>1?void 0:i?ire(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&tre(e,t,s),s};class aa extends Ie{constructor(){super(...arguments);u(this,"attachedRigidbody",null);u(this,"isTrigger",!1);u(this,"sharedMaterial");u(this,"membership",[0]);u(this,"filter");u(this,"updateProperties",()=>{var t;(t=this.context.physics.engine)==null||t.updateProperties(this)})}get isCollider(){return!0}awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Xi))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Xi))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Xi))}onDisable(){var t;(t=this.context.physics.engine)==null||t.removeBody(this)}get body(){var t;return(t=this.context.physics.engine)==null?void 0:t.getBody(this)}updatePhysicsMaterial(){var t;(t=this.context.physics.engine)==null||t.updatePhysicsMaterial(this)}}Yr([x(Xi)],aa.prototype,"attachedRigidbody",2);Yr([x()],aa.prototype,"isTrigger",2);Yr([x()],aa.prototype,"sharedMaterial",2);Yr([x()],aa.prototype,"membership",2);Yr([x()],aa.prototype,"filter",2);class WA extends aa{constructor(){super(...arguments);u(this,"radius",.5);u(this,"center",new w(0,0,0))}onEnable(){var t;super.onEnable(),(t=this.context.physics.engine)==null||t.addSphereCollider(this),zx(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),cI(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}}Yr([Vs(),x()],WA.prototype,"radius",2);Yr([x(w)],WA.prototype,"center",2);class qA extends aa{constructor(){super(...arguments);u(this,"size",new w(1,1,1));u(this,"center",new w(0,0,0))}onEnable(){var t;super.onEnable(),(t=this.context.physics.engine)==null||t.addBoxCollider(this,this.size),zx(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),cI(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}}Yr([Vs(),x(w)],qA.prototype,"size",2);Yr([x(w)],qA.prototype,"center",2);class um extends aa{constructor(){super(...arguments);u(this,"sharedMesh");u(this,"convex",!1)}onEnable(){var t,i,s,r,o;if(super.onEnable(),(t=this.sharedMesh)!=null&&t.isMesh||this.gameObject instanceof me&&(this.sharedMesh=this.gameObject),(i=this.sharedMesh)!=null&&i.isMesh)(s=this.context.physics.engine)==null||s.addMeshCollider(this,this.sharedMesh,this.convex,hn(this.gameObject));else{const a=this.sharedMesh;if(a!=null&&a.isGroup){console.warn(`MeshCollider mesh is a group "${((r=this.sharedMesh)==null?void 0:r.name)||this.gameObject.name}", adding all children as colliders. This is currently not fully supported (colliders can not be removed from world again)`,this);for(const c in a.children){const l=a.children[c];l.isMesh&&((o=this.context.physics.engine)==null||o.addMeshCollider(this,l,this.convex,hn(this.gameObject)))}}}}}Yr([x()],um.prototype,"sharedMesh",2);Yr([x()],um.prototype,"convex",2);class zh extends aa{constructor(){super(...arguments);u(this,"center",new w(0,0,0));u(this,"radius",.5);u(this,"height",2)}onEnable(){var t;super.onEnable(),(t=this.context.physics.engine)==null||t.addCapsuleCollider(this,this.height,this.radius)}}Yr([x(w)],zh.prototype,"center",2);Yr([x()],zh.prototype,"radius",2);Yr([x()],zh.prototype,"height",2);var nre=Object.defineProperty,sre=Object.getOwnPropertyDescriptor,YR=(n,e,t,i)=>{for(var s=i>1?void 0:i?sre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&nre(e,t,s),s};class Dd extends Ie{constructor(){super(...arguments);u(this,"objectBounds",!1);u(this,"color");u(this,"isGizmo",!0);u(this,"_gizmoObject",null);u(this,"_boxHelper",null)}onEnable(){this.isGizmo&&!gA||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new rI(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=wR(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),Vn.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){var t;for(;this._boxHelper;)(t=this._boxHelper)==null||t.update(),yield}}YR([x()],Dd.prototype,"objectBounds",2);YR([x(ye)],Dd.prototype,"color",2);YR([x()],Dd.prototype,"isGizmo",2);class rre extends mG{constructor(e,t={}){super(e),e._simpleState__activeStates=[],e._simpleState__normalStyles={},e._simpleState__states=t,e._simpleState__statesProperties={};for(const i in t)for(const s in t[i])e._simpleState__statesProperties[s]||(e._simpleState__statesProperties[s]=[]),e._simpleState__statesProperties[s].push(i);for(const i of e._components)e._simpleState__statesProperties[i.id]&&(e._simpleState__normalStyles[i.id]=i.inline?i.inline:i._value);e.__overridedSet=e.set,e.set=this.storeSet.bind(e),e.renderStates=this.renderStates.bind(e),e.setupState=this.setupState.bind(e),e.setState=this.setState.bind(e),e.activatePseudoState=this.activatePseudoState.bind(e),e.deactivatePseudoState=this.deactivatePseudoState.bind(e),e.togglePseudoState=this.togglePseudoState.bind(e)}act(){}attach(){}detach(){}setupState(e,t){this._simpleState__states[e]=t;const i=[];for(const s in t)this._simpleState__statesProperties[s]||(this._simpleState__statesProperties[s]=[],i.push(s)),this._simpleState__statesProperties[s].push(e);for(const s of this._components)i.indexOf(s.id)>-1&&(this._simpleState__normalStyles[s.id]=s.inline?s.inline:s._value)}renderStates(){let e={...this._simpleState__normalStyles};for(const t in this._simpleState__states)this._simpleState__activeStates.indexOf(t)>-1&&(e={...e,...this._simpleState__states[t]});this.set(e,!1)}storeSet(e,t=!0){if(t)for(const i in e)this._simpleState__statesProperties[i]&&(this._simpleState__normalStyles[i]=e[i]);this.__overridedSet(e)}activatePseudoState(e){this._simpleState__activeStates.indexOf(e)===-1&&(this._simpleState__activeStates.push(e),this.renderStates())}deactivatePseudoState(e){const t=this._simpleState__activeStates.indexOf(e);t>-1&&(this._simpleState__activeStates.splice(t,1),this.renderStates())}togglePseudoState(e){const t=this._simpleState__activeStates.indexOf(e);t>-1?this._simpleState__activeStates.splice(t,1):this._simpleState__activeStates.push(e),this.renderStates()}setState(e){Array.isArray(e)?this._simpleState__activeStates=e:this._simpleState__activeStates=[e],this.renderStates()}}var ore=Object.defineProperty,are=Object.getOwnPropertyDescriptor,qH=(n,e,t,i)=>{for(var s=i>1?void 0:i?are(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&ore(e,t,s),s};class dm extends Ie{constructor(){super(...arguments);u(this,"effectColor");u(this,"effectDistance")}}qH([x(Ti)],dm.prototype,"effectColor",2);qH([x(ie)],dm.prototype,"effectDistance",2);var cre=Object.defineProperty,lre=Object.getOwnPropertyDescriptor,XA=(n,e,t,i)=>{for(var s=i>1?void 0:i?lre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&cre(e,t,s),s};const $C=se("debugui"),eE=se("debuguilayout");class JR{constructor(){u(this,"width");u(this,"height")}}class KR{constructor(){u(this,"x");u(this,"y");u(this,"width");u(this,"height")}}const pa=new w,tg=new Se,z0=new Ee,XH=class extends Pa{constructor(){super(...arguments);u(this,"_anchoredPosition");u(this,"sizeDelta",new ie(100,100));u(this,"pivot",new ie(.5,.5));u(this,"anchorMin",new ie(0,0));u(this,"anchorMax",new ie(1,1));u(this,"minWidth");u(this,"minHeight");u(this,"lastMatrix");u(this,"rectBlock");u(this,"_transformNeedsUpdate",!1);u(this,"_initialPosition");u(this,"_parentRectTransform");u(this,"_lastUpdateFrame",-1);u(this,"_lastAnchoring");u(this,"_createdBlocks",[]);u(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 ie),this._anchoredPosition}set anchoredPosition(e){this._anchoredPosition=e}get width(){let e=this.sizeDelta.x;if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const t=this._parentRectTransform.width,i=this.anchorMax.x-this.anchorMin.x;e=t*i,e+=this.sizeDelta.x}return this.minWidth!==void 0&&e<this.minWidth?this.minWidth:e}get height(){let e=this.sizeDelta.y;if(this.anchorMin.y!==this.anchorMax.y&&this._parentRectTransform){const t=this._parentRectTransform.height,i=this.anchorMax.y-this.anchorMin.y;e=t*i,e+=this.sizeDelta.y}return this.minHeight!==void 0&&e<this.minHeight?this.minHeight:e}awake(){super.awake(),this._anchoredPosition||(this._anchoredPosition=new ie),this.lastMatrix=new Se,this.rectBlock=new ge,this.rectBlock.name=this.name,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,zf(this,"_anchoredPosition",()=>{this.markDirty()}),zf(this,"sizeDelta",()=>{this.markDirty()}),zf(this,"pivot",()=>{this.markDirty()}),zf(this,"anchorMin",()=>{this.markDirty()}),zf(this,"anchorMax",()=>{this.markDirty()})}onEnable(){var e;super.onEnable(),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,(e=this.Canvas)==null||e.registerTransform(this)}onDisable(){var e;super.onDisable(),this.removeShadowComponent(),(e=this.Canvas)==null||e.unregisterTransform(this)}onParentRectTransformChanged(e){this._transformNeedsUpdate||this.onApplyTransform(eE?`${e.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(eE&&console.warn("RectTransform markDirty()",this.name),this._transformNeedsUpdate=!0,this._lastUpdateFrame=-1)}updateTransform(){(this._transformNeedsUpdate||!this.lastMatrix.equals(this.gameObject.matrix))&&this.canUpdate()&&this.onApplyTransform(this._transformNeedsUpdate?"Marked dirty":"Matrix changed")}canUpdate(){return this._transformNeedsUpdate&&this.activeAndEnabled&&this._lastUpdateFrame!==this.context.time.frame}onApplyTransform(e){var s;if(this.context.time.frameCount===this._lastUpdateFrame)return;this._lastUpdateFrame=this.context.time.frameCount;const t=this.shadowComponent;if(!t)return;this.gameObject.parent?this._parentRectTransform=le.getComponentInParent(this.gameObject.parent,XH):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,eE&&console.warn("RectTransform โ†’ ApplyTransform",this.name+" because "+e),this.isRoot()?this.Root.screenspace||(t.rotation.y=Math.PI):(t.matrix.identity(),t.matrixAutoUpdate=!1,pa.set(0,0,0),this.applyPivot(pa),t.matrix.setPosition(pa.x,pa.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(z0.copy(this.gameObject.quaternion),z0.x*=-1,z0.z*=-1,tg.makeRotationFromQuaternion(z0),t.matrix.premultiply(tg)),pa.set(0,0,0),this.applyAnchoring(pa),(s=this.Canvas)!=null&&s.screenspace?pa.z+=.1:pa.z+=.01,tg.identity(),tg.setPosition(pa.x,pa.y,pa.z),t.matrix.premultiply(tg),t.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const i=!0;for(const r of CR(this.gameObject,Pa,i,1)){if(r===this||!r.activeAndEnabled)continue;const o=r;o.onParentRectTransformChanged&&o.onParentRectTransformChanged(this)}}applyAnchoring(e){this._lastAnchoring||(this._lastAnchoring=new ie);const t=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=t.x,this.gameObject.position.y+=t.y,this._lastAnchoring.copy(this._anchoredPosition),e.x+=this._initialPosition.x-this.gameObject.position.x,e.y+=this._initialPosition.y-this.gameObject.position.y,e.z+=this._initialPosition.z-this.gameObject.position.z;const i=this._parentRectTransform;if(i){let s=0;const r=1-this.anchorMax.y-this.anchorMin.y;s-=i.height*.5*r,e.y+=s;let o=0;const a=1-this.anchorMax.x-this.anchorMin.x;o-=i.width*.5*a,e.x+=o}}applyPivot(e){if(this.pivot&&!this.isRoot()){const t=this.pivot.x-.5;e.x-=t*this.sizeDelta.x*this.gameObject.scale.x;const i=this.pivot.y-.5;e.y-=i*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){const e={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:0,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(e),e}ensureValidSize(e,t=1e-4){return e.width<=0&&(e.width=t),e.height<=0&&(e.height=1e-4),e}createNewBlock(e){e={...this.getBasicOptions(),...e},$C&&console.log(this.name,e);const t=new fR(e);return this._createdBlocks.push(t),t}createNewText(e){$C&&console.log(e),e={...this.getBasicOptions(),...e},$C&&console.log(this.name,e);const t=new pR(e);return this._createdTextBlocks.push(t),t}};let Tr=XH;XA([x(ie)],Tr.prototype,"anchoredPosition",1);XA([x(ie)],Tr.prototype,"sizeDelta",2);XA([x(ie)],Tr.prototype,"pivot",2);XA([x(ie)],Tr.prototype,"anchorMin",2);XA([x(ie)],Tr.prototype,"anchorMax",2);var hre=Object.defineProperty,ure=Object.getOwnPropertyDescriptor,YH=(n,e,t,i)=>{for(var s=i>1?void 0:i?ure(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&hre(e,t,s),s};const G0={backgroundColor:new ye(1,1,1),backgroundOpacity:1,borderColor:new ye(1,1,1),borderOpacity:1};var FE;const Q_=(FE=class extends Pa{constructor(){super(...arguments);u(this,"_alphaFactor",1);u(this,"sRGBColor",new ye(1,0,1));u(this,"raycastTarget",!0);u(this,"uiObject",null);u(this,"_color",null);u(this,"_rect",null);u(this,"_stateManager",null);u(this,"_currentlyCreatingPanel",!1)}get isGraphic(){return!0}get color(){return this._color||(this._color=new Ti(1,1,1,1)),this._color}set color(e){(!this._color||this._color.r!==e.r||this._color.g!==e.g||this._color.b!==e.b||this._color.alpha!==e.alpha)&&(this._color||(this._color=new Ti(1,1,1,1)),this._color.copy(e),this.onColorChanged())}setAlphaFactor(e){this._alphaFactor=e,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}onColorChanged(){this.uiObject&&(this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),G0.backgroundColor=this.sRGBColor,G0.backgroundOpacity=this._color.alpha*this._alphaFactor,this.applyEffects(G0,this._alphaFactor),this.uiObject.set(G0),this.markDirty())}get m_Color(){return this._color}get rectTransform(){if(this._rect||(this._rect=le.getComponent(this.gameObject,Tr)),!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 e;(e=this.uiObject)==null||e.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(){super.__internalNewInstanceCreated(),this._rect=null,this.uiObject=null,this._color&&(this._color=this._color.clone())}setState(e){this.makePanel(),this.uiObject&&(this.uiObject.setState(e),this==null||this.markDirty())}setupState(e){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new rre(this.uiObject)),this.uiObject.setupState(e.state,e.attributes))}setOptions(e){this.makePanel(),this.uiObject&&this.uiObject.set(e)}awake(){super.awake(),this.makePanel(),zf(this,"_color",()=>Gne(this,this.onColorChanged))}onEnable(){var e;super.onEnable(),this.uiObject&&((e=this.rectTransform.shadowComponent)==null||e.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 e=.015,t={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:e};this.onBeforeCreate(t),this.applyEffects(t),this.onCreate(t),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated(),this.onColorChanged()}onBeforeCreate(e){}onCreate(e){this.uiObject=this.rectTransform.createNewBlock(e),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(e,t=1){var s;const i=(s=this.gameObject)==null?void 0:s.getComponent(dm);i&&(i.effectDistance&&(e.borderWidth=Math.max(Math.abs(i.effectDistance.x),Math.abs(i.effectDistance.y))),i.effectColor&&(e.borderColor=i.effectColor,e.borderOpacity=i.effectColor.alpha*t))}async setTexture(e){if(this.setOptions({backgroundOpacity:0}),e){if(Q_.textureCache.has(e))e=Q_.textureCache.get(e);else if(!e.isRenderTargetTexture){const t=e.clone();t.colorSpace=ki,Q_.textureCache.set(e,t),e=t}this.setOptions({backgroundImage:e,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"})}else this.setOptions({backgroundImage:null,borderRadius:0,backgroundOpacity:this.color.alpha});this.markDirty()}onAfterAddedToScene(){super.onAfterAddedToScene(),this.shadowComponent&&(this.shadowComponent.offset=this.shadowComponent.position.z)}},u(FE,"textureCache",new Map),FE);let Od=Q_;YH([x(Ti)],Od.prototype,"color",1);YH([x()],Od.prototype,"raycastTarget",2);class YA extends Od{constructor(){super(...arguments);u(this,"_flippedObject",!1)}onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var dre=Object.defineProperty,fre=Object.getOwnPropertyDescriptor,Iw=(n,e,t,i)=>{for(var s=i>1?void 0:i?fre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&dre(e,t,s),s};let ZR=class{constructor(){u(this,"texture",null);u(this,"rect")}};Iw([x(Ht)],ZR.prototype,"texture",2);let fm=class extends YA{constructor(){super(...arguments);u(this,"_sprite");u(this,"pixelsPerUnitMultiplier",1)}set image(t){this.sprite||(this.sprite=new ZR),this.sprite.texture=t,this.onAfterCreated()}get image(){return this.sprite?this.sprite.texture:null}get sprite(){return this._sprite}set sprite(t){this._sprite!==t&&(this._sprite=t,this.onAfterCreated())}isBuiltinSprite(){var t,i,s,r,o,a,c,l,h,d,f;switch((i=(t=this.sprite)==null?void 0:t.texture)==null?void 0:i.name){case"InputFieldBackground":case"UISprite":case"Background":case"Knob":return!0}return!((o=(r=(s=this.sprite)==null?void 0:s.texture)==null?void 0:r.name)!=null&&o.length)&&((l=(c=(a=this.sprite)==null?void 0:a.texture)==null?void 0:c.image)==null?void 0:l.width)===32&&((f=(d=(h=this.sprite)==null?void 0:h.texture)==null?void 0:d.image)==null?void 0:f.height)===32}onBeforeCreate(t){var i,s;super.onBeforeCreate(t),this.isBuiltinSprite()&&(t.borderRadius=5/this.pixelsPerUnitMultiplier,((s=(i=this.sprite)==null?void 0:i.texture)==null?void 0:s.name)==="Knob"&&(t.borderRadius=999))}onAfterCreated(){var t;this.__didAwake&&(super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture((t=this.sprite)==null?void 0:t.texture))}};Iw([x(ZR)],fm.prototype,"sprite",1);Iw([x()],fm.prototype,"pixelsPerUnitMultiplier",2);class Rw extends YA{constructor(){super(...arguments);u(this,"_mainTexture")}get mainTexture(){return this._mainTexture}set mainTexture(t){this._mainTexture!==t&&(this._mainTexture=t,this.onAfterCreated())}onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),this.setTexture(this.mainTexture))}}Iw([x(Ht)],Rw.prototype,"mainTexture",1);var pre=Object.defineProperty,mre=Object.getOwnPropertyDescriptor,So=(n,e,t,i)=>{for(var s=i>1?void 0:i?mre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&pre(e,t,s),s};const Cu=se("debugbutton");class kd{constructor(){u(this,"colorMultiplier");u(this,"disabledColor");u(this,"fadeDuration");u(this,"highlightedColor");u(this,"normalColor");u(this,"pressedColor");u(this,"selectedColor")}}So([x()],kd.prototype,"colorMultiplier",2);So([x(Ti)],kd.prototype,"disabledColor",2);So([x()],kd.prototype,"fadeDuration",2);So([x(Ti)],kd.prototype,"highlightedColor",2);So([x(Ti)],kd.prototype,"normalColor",2);So([x(Ti)],kd.prototype,"pressedColor",2);So([x(Ti)],kd.prototype,"selectedColor",2);class Fl extends Ie{constructor(){super(...arguments);u(this,"onClick");u(this,"_isHovered",0);u(this,"colors");u(this,"transition");u(this,"animationTriggers");u(this,"animator");u(this,"_interactable",!0);u(this,"_requestedAnimatorTrigger");u(this,"_isInit",!1);u(this,"_image")}onPointerEnter(t){var i,s;this._isHovered+=1,Cu&&console.warn("Button Enter",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&&((s=this._image)==null||s.setState("hovered")),this.context.input.setCursorPointer())}onPointerExit(){var t,i;this._isHovered-=1,Cu&&console.log("Button Exit",this._isHovered,(t=this.animationTriggers)==null?void 0:t.highlightedTrigger,this.animator),this.interactable&&(this._isHovered>0||(this._isHovered=0,this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&((i=this._image)==null||i.setState("normal")),this.context.input.setCursorNormal()))}onPointerDown(t){var i,s;Cu&&console.log("Button Down",(i=this.animationTriggers)==null?void 0:i.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&((s=this._image)==null||s.setState("pressed")))}onPointerUp(t){var i,s;Cu&&console.warn("Button Up",(i=this.animationTriggers)==null?void 0:i.highlightedTrigger,this.animator,this._isHovered),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this._isHovered?this.animationTriggers.highlightedTrigger:this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&((s=this._image)==null||s.setState(this._isHovered?"hovered":"normal")))}onPointerClick(t){if(this.interactable&&!(t.button!==0&&t.event.pointerType===SI.Mouse)&&(Cu&&(console.warn("Button Click",this.onClick),xn("CLICKED button "+this.name+" at "+this.context.time.frameCount)),this.onClick&&this.onClick.listenerCount>0&&(this.onClick.invoke(),t.use(),Cu))){const i=this.gameObject.worldPosition;i.add(this.gameObject.worldUp.multiplyScalar(1+Math.random()*.5)),It.DrawLabel(i,"CLICK:"+Date.now(),.1,1+Math.random()*.5)}}set interactable(t){this._interactable=t,this._image&&(this._image.setInteractable(t),t?this._image.setState("normal"):this._image.setState("disabled"))}get interactable(){return this._interactable}set_interactable(t){this.interactable=t}awake(){super.awake(),Cu&&console.log(this),this._isInit=!1,this.init()}start(){var t;(t=this._image)==null||t.setInteractable(this.interactable),this.gameObject.getComponentInParent(UA)||this.gameObject.addComponent(vw)}onEnable(){super.onEnable()}onDestroy(){this._isHovered&&this.context.input.setCursorNormal()}*setAnimatorTriggerAtEndOfFrame(t){var i;this._requestedAnimatorTrigger=t,yield,yield,this._requestedAnimatorTrigger==t&&((i=this.animator)==null||i.SetTrigger(t))}init(){this._isInit||(this._isInit=!0,this._image=le.getComponent(this.gameObject,fm),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(t){var p,m,g,y,v;t.setInteractable(this.interactable);const i=this.getFinalColor(t.color,(p=this.colors)==null?void 0:p.normalColor),s={state:"normal",attributes:{backgroundColor:i,backgroundOpacity:i.alpha}};t.setupState(s);const r=this.getFinalColor(t.color,(m=this.colors)==null?void 0:m.highlightedColor),o={state:"hovered",attributes:{backgroundColor:r,backgroundOpacity:r.alpha}};t.setupState(o);const a=this.getFinalColor(t.color,(g=this.colors)==null?void 0:g.pressedColor),c={state:"pressed",attributes:{backgroundColor:a,backgroundOpacity:a.alpha}};t.setupState(c);const l=this.getFinalColor(t.color,(y=this.colors)==null?void 0:y.selectedColor),h={state:"selected",attributes:{backgroundColor:l,backgroundOpacity:l.alpha}};t.setupState(h);const d=this.getFinalColor(t.color,(v=this.colors)==null?void 0:v.disabledColor),f={state:"disabled",attributes:{backgroundColor:d,backgroundOpacity:d.alpha}};t.setupState(f)}getFinalColor(t,i){return i?t.clone().multiply(i).convertLinearToSRGB():t.clone().convertLinearToSRGB()}}So([x(gs)],Fl.prototype,"onClick",2);So([x()],Fl.prototype,"colors",2);So([x()],Fl.prototype,"transition",2);So([x()],Fl.prototype,"animationTriggers",2);So([x(Us)],Fl.prototype,"animator",2);So([x()],Fl.prototype,"interactable",1);var gre=Object.defineProperty,vre=Object.getOwnPropertyDescriptor,Wn=(n,e,t,i)=>{for(var s=i>1?void 0:i?vre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&gre(e,t,s),s};const l2=se("debuguilayout");class Jh{constructor(){u(this,"left",0);u(this,"right",0);u(this,"top",0);u(this,"bottom",0)}get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}Wn([x()],Jh.prototype,"left",2);Wn([x()],Jh.prototype,"right",2);Wn([x()],Jh.prototype,"top",2);Wn([x()],Jh.prototype,"bottom",2);class Co extends Ie{constructor(){super(...arguments);u(this,"_rectTransform",null);u(this,"_needsUpdate",!1);u(this,"childAlignment",0);u(this,"reverseArrangement",!1);u(this,"spacing",0);u(this,"padding");u(this,"minWidth",0);u(this,"minHeight",0);u(this,"flexibleHeight",0);u(this,"flexibleWidth",0);u(this,"preferredHeight",0);u(this,"preferredWidth",0)}get rectTransform(){return this._rectTransform}onParentRectTransformChanged(t){this._needsUpdate=!0}get isDirty(){return this._needsUpdate}get isLayoutGroup(){return!0}updateLayout(){this._rectTransform&&(l2&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}start(){this._needsUpdate=!0}onEnable(){l2&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(Tr);const t=this.gameObject.getComponentInParent(Ns);t&&t.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const t=this.gameObject.getComponentInParent(Ns);t&&t.unregisterLayoutGroup(this)}set m_Spacing(t){t!==this.spacing&&(this._needsUpdate=!0,this.spacing=t)}get m_Spacing(){return this.spacing}}Wn([x()],Co.prototype,"childAlignment",2);Wn([x()],Co.prototype,"reverseArrangement",2);Wn([x()],Co.prototype,"spacing",2);Wn([x(Jh)],Co.prototype,"padding",2);Wn([x()],Co.prototype,"minWidth",2);Wn([x()],Co.prototype,"minHeight",2);Wn([x()],Co.prototype,"flexibleHeight",2);Wn([x()],Co.prototype,"flexibleWidth",2);Wn([x()],Co.prototype,"preferredHeight",2);Wn([x()],Co.prototype,"preferredWidth",2);class Kh extends Co{constructor(){super(...arguments);u(this,"childControlHeight",!0);u(this,"childControlWidth",!0);u(this,"childForceExpandHeight",!1);u(this,"childForceExpandWidth",!1);u(this,"childScaleHeight",!1);u(this,"childScaleWidth",!1)}onCalculateLayout(t){var I;const i=this.primaryAxis,s=t.width;let r=s;const o=t.height;let a=o;r-=this.padding.horizontal,a-=this.padding.vertical,i==="x"?this.padding.horizontal:this.padding.vertical;const c=i==="x",l=c?"y":"x",h=c?this.childControlWidth:this.childControlHeight,d=c?this.childControlHeight:this.childControlWidth,f=c?this.childForceExpandWidth:this.childForceExpandHeight,p=c?this.childForceExpandHeight:this.childForceExpandWidth,m=c?a:r,g=c?s:o,y=.5*(c?this.childAlignment%3:Math.floor(this.childAlignment/3));let v=0;c?v+=this.padding.left:v+=this.padding.top;let A=0,_=0;for(let S=0;S<this.gameObject.children.length;S++){const M=this.gameObject.children[S],D=le.getComponent(M,Tr);D!=null&&D.activeAndEnabled&&(_+=1,c?A+=D.width:A+=D.height)}let b=0;const C=this.spacing*(_-1);if(f||h){let S=0;c?S=r-=C:S=a-=C,_>0&&(b=S/_)}let E=0;E+=this.padding.left,E-=this.padding.right,y!==0&&(v=g-A,v*=y,v-=C*y,c?(v-=this.padding.right*y,v+=this.padding.left*(1-y),v<this.padding.left&&(v=this.padding.left)):(v-=this.padding.bottom*y,v+=this.padding.top*(1-y),v<this.padding.top&&(v=this.padding.top)));let T=1;for(let S=0;S<this.gameObject.children.length;S++){const M=this.gameObject.children[S],D=le.getComponent(M,Tr);if(D!=null&&D.activeAndEnabled){(I=D.pivot)==null||I.set(.5,.5),D.anchorMin.set(0,1),D.anchorMax.set(0,1);const G=s*.5+E*.5;D.anchoredPosition.x!==G&&(D.anchoredPosition.x=G);const Q=o*-.5;D.anchoredPosition.y!==Q&&(D.anchoredPosition.y=Q),p&&d&&D.sizeDelta[l]!==m&&(D.sizeDelta[l]=m),f&&h&&D.sizeDelta[i]!==b&&(D.sizeDelta[i]=b);const L=c?D.width:D.height,H=L*.5;if(v+=H,f){const U=b*T-b*.5;U>v&&(v=U-b*.5+L+this.padding.left,v-=H)}let O=v;i==="y"&&(O=-O),D.anchoredPosition[i]!==O&&(D.anchoredPosition[i]=O),v+=H,v+=this.spacing,T+=1}}}}Wn([x()],Kh.prototype,"childControlHeight",2);Wn([x()],Kh.prototype,"childControlWidth",2);Wn([x()],Kh.prototype,"childForceExpandHeight",2);Wn([x()],Kh.prototype,"childForceExpandWidth",2);Wn([x()],Kh.prototype,"childScaleHeight",2);Wn([x()],Kh.prototype,"childScaleWidth",2);class $R extends Kh{get primaryAxis(){return"y"}}class eP extends Kh{get primaryAxis(){return"x"}}class tP extends Co{onCalculateLayout(){}}var Are=Object.defineProperty,yre=Object.getOwnPropertyDescriptor,Rc=(n,e,t,i)=>{for(var s=i>1?void 0:i?yre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Are(e,t,s),s},JH=(n=>(n[n.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",n[n.ScreenSpaceCamera=1]="ScreenSpaceCamera",n[n.WorldSpace=2]="WorldSpace",n[n.Undefined=-1]="Undefined",n))(JH||{});const tE=se("debuguilayout"),KH=class extends FA{constructor(){super(...arguments);u(this,"_renderOnTop");u(this,"_depthWrite",!1);u(this,"_doubleSided",!0);u(this,"_castShadows",!1);u(this,"_receiveShadows",!1);u(this,"_renderMode",-1);u(this,"_rootCanvas");u(this,"_scaleFactor",1);u(this,"worldCamera");u(this,"planeDistance",-1);u(this,"_boundRenderSettingsChanged",this.onRenderSettingsChanged.bind(this));u(this,"previousParent",null);u(this,"_lastMatrixWorld",null);u(this,"_rectTransforms",[]);u(this,"_layoutGroups",new Map);u(this,"_receivers",[]);u(this,"onBeforeRenderRoutine",()=>{var e,t,i,s;if(this.previousParent=this.gameObject.parent,((e=this.context.xr)!=null&&e.isVR||(t=this.context.xr)!=null&&t.isPassThrough)&&this.screenspace){this.gameObject.visible=!1,this.gameObject.removeFromParent();return}this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),(i=this.shadowComponent)==null||i.updateMatrixWorld(!0),(s=this.shadowComponent)==null||s.updateWorldMatrix(!0,!0),this.invokeBeforeRenderEvents(),jr.ensureUpdateMeshUI(nk,this.context))});u(this,"onAfterRenderRoutine",()=>{var e,t,i,s,r;if(((e=this.context.xr)!=null&&e.isVR||(t=this.context.xr)!=null&&t.isPassThrough)&&this.screenspace){(i=this.previousParent)==null||i.add(this.gameObject);return}if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){if(this.screenspace){const c=this.context.mainCamera;c==null||c.add(this.gameObject)}else this.previousParent.add(this.gameObject);const o=this.context.renderer.autoClear,a=this.context.renderer.autoClearColor;this.context.renderer.autoClear=!1,this.context.renderer.autoClearColor=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),(s=this.shadowComponent)==null||s.updateMatrixWorld(!0),this.invokeBeforeRenderEvents(),jr.ensureUpdateMeshUI(nk,this.context,!0),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=o,this.context.renderer.autoClearColor=a,this.previousParent.add(this.gameObject)}(r=this._lastMatrixWorld)==null||r.copy(this.gameObject.matrixWorld)});u(this,"_updateRenderSettingsRoutine");u(this,"_activeRenderMode",-1);u(this,"_lastWidth",-1);u(this,"_lastHeight",-1)}get isCanvas(){return!0}get screenspace(){return this.renderMode!==2}set renderOnTop(e){e!==this._renderOnTop&&(this._renderOnTop=e,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop!==void 0?this._renderOnTop:!!(this.screenspace&&this._renderMode===0)}set depthWrite(e){this._depthWrite!==e&&(this._depthWrite=e,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}set doubleSided(e){this._doubleSided!==e&&(this._doubleSided=e,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}set castShadows(e){this._castShadows!==e&&(this._castShadows=e,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}set receiveShadows(e){this._receiveShadows!==e&&(this._receiveShadows=e,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}get renderMode(){return this._renderMode}set renderMode(e){this._renderMode!==e&&(this._renderMode=e,this.onRenderSettingsChanged())}set rootCanvas(e){this._rootCanvas instanceof KH||(this._rootCanvas=e)}get rootCanvas(){return this._rootCanvas}get scaleFactor(){return this._scaleFactor}set scaleFactor(e){this._scaleFactor=e}awake(){var e;this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,tE&&console.log("Canvas.Awake()",((e=this.previousParent)==null?void 0:e.name)+"/"+this.gameObject.name),super.awake()}start(){this.onUpdateRenderMode()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new Se,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 e=this.context.pre_render_callbacks.indexOf(this.onBeforeRenderRoutine);e!==-1&&this.context.pre_render_callbacks.splice(e,1);const t=this.context.post_render_callbacks.indexOf(this.onAfterRenderRoutine);t!==-1&&this.context.post_render_callbacks.splice(t,1)}registerTransform(e){this._rectTransforms.push(e)}unregisterTransform(e){const t=this._rectTransforms.indexOf(e);t!==-1&&this._rectTransforms.splice(t,1)}registerLayoutGroup(e){const t=e.gameObject;this._layoutGroups.set(t,e)}unregisterLayoutGroup(e){const t=e.gameObject;this._layoutGroups.delete(t)}registerEventReceiver(e){this._receivers.push(e)}unregisterEventReceiver(e){const t=this._receivers.indexOf(e);t!==-1&&this._receivers.splice(t,1)}async onEnterXR(e){this.screenspace?(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!1):(this.gameObject.visible=!1,await HU(1).then(()=>{this.gameObject.visible=!0}))}onLeaveXR(e){this.screenspace&&(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!0)}invokeBeforeRenderEvents(){var e;for(const t of this._receivers)(e=t.onBeforeCanvasRender)==null||e.call(t,this)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new Se);const e=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);tE&&e&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);const t=!1;for(const i of this._rectTransforms){e&&i.markDirty();let s=this._layoutGroups.get(i.gameObject);i.isDirty&&!s&&(s=i.gameObject.getComponentInParent(Co)),(i.isDirty||s!=null&&s.isDirty)&&(tE&&!t&&console.log("CANVAS UPDATE ### "+i.name+" ##################################### "+this.context.time.frame),s==null||s.updateLayout(),i.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),Vn.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),zb(this.shadowComponent,this);for(const e of le.getComponentsInChildren(this.gameObject,Pa))zb(e.shadowComponent,this)}}onUpdateRenderMode(e=!1){if(!e&&this._renderMode===this._activeRenderMode&&this._lastWidth===this.context.domWidth&&this._lastHeight===this.context.domHeight)return;this._activeRenderMode=this._renderMode;let t=this.context.mainCameraComponent,i=10;switch(t&&t.nearClipPlane>0&&t.farClipPlane>0&&(i=rt.lerp(t.nearClipPlane,t.farClipPlane,.01)),this._renderMode===1&&(this.worldCamera&&(t=this.worldCamera),this.planeDistance>0&&(i=this.planeDistance)),this._renderMode){case 0:case 1:if(this._lastWidth=this.context.domWidth,this._lastHeight=this.context.domHeight,!t)return;const s=i+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-s,this.gameObject.quaternion.identity();const r=this.gameObject.getComponent(Tr);let o=!1;r.sizeDelta.x!==this.context.domWidth&&(o=!0),r.sizeDelta.y!==this.context.domHeight&&(o=!0);const a=t.fieldOfView*Math.PI/180,c=2*Math.tan(a/2)*Math.abs(s);this.gameObject.scale.x=c/this.context.domHeight,this.gameObject.scale.y=c/this.context.domHeight,this.gameObject.scale.z=.01,o&&(r.sizeDelta.x=this.context.domWidth,r.sizeDelta.y=this.context.domHeight,r==null||r.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};let Ns=KH;Rc([x()],Ns.prototype,"renderOnTop",1);Rc([x()],Ns.prototype,"depthWrite",1);Rc([x()],Ns.prototype,"doubleSided",1);Rc([x()],Ns.prototype,"castShadows",1);Rc([x()],Ns.prototype,"receiveShadows",1);Rc([x()],Ns.prototype,"renderMode",1);Rc([x(Ns)],Ns.prototype,"rootCanvas",1);Rc([x()],Ns.prototype,"scaleFactor",1);Rc([x(Yi)],Ns.prototype,"worldCamera",2);Rc([x()],Ns.prototype,"planeDistance",2);var _re=Object.defineProperty,bre=Object.getOwnPropertyDescriptor,iP=(n,e,t,i)=>{for(var s=i>1?void 0:i?bre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&_re(e,t,s),s};class Gh extends Ie{constructor(){super(...arguments);u(this,"_alpha",1);u(this,"interactable",!0);u(this,"blocksRaycasts",!0);u(this,"_isDirty",!1);u(this,"_buffer",[])}get alpha(){return this._alpha}set alpha(t){t!==this._alpha&&(this._alpha=t,this.markDirty())}get isCanvasGroup(){return!0}markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),Vn.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}applyChangesNow(){this._buffer.length=0;for(const t of le.getComponentsInChildren(this.gameObject,Pa,this._buffer)){const i=t;i.setAlphaFactor&&i.setAlphaFactor(this._alpha)}}}iP([x()],Gh.prototype,"alpha",1);iP([x()],Gh.prototype,"interactable",2);iP([x()],Gh.prototype,"blocksRaycasts",2);var xre=Object.defineProperty,wre=Object.getOwnPropertyDescriptor,mn=(n,e,t,i)=>{for(var s=i>1?void 0:i?wre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&xre(e,t,s),s};function JA(n){n&&(n.getComponentInParent(UA)||(Mt()&&console.warn("Create Raycaster on "+n.name+" because no raycaster was found in the hierarchy"),n.addNewComponent(yo)))}class Ld extends Ie{constructor(){super(...arguments);u(this,"object");u(this,"target");u(this,"duration",1);u(this,"relativeMotion",!1);u(this,"coroutine",null);u(this,"targetPos",new w);u(this,"targetRot",new Ee);u(this,"targetScale",new w)}start(){JA(this.gameObject)}onPointerClick(t){t.use(),this.coroutine&&this.stopCoroutine(this.coroutine),this.relativeMotion?this.coroutine=this.startCoroutine(this.moveRelative()):this.coroutine=this.startCoroutine(this.moveToTarget())}*moveToTarget(){if(!this.target||!this.object)return;const t=Dt(this.object).clone(),i=Dt(this.target).clone(),s=Di(this.object).clone(),r=Di(this.target).clone(),o=hn(this.object).clone(),a=hn(this.target).clone(),c=t.distanceTo(i),l=s.angleTo(r),h=o.distanceTo(a);if(c<.01&&l<.01&&h<.01){sr(this.object,i),ea(this.object,r),kv(this.object,a),this.coroutine=null;return}let d=0,f=0;for(;d<1;)d+=this.context.time.deltaTime/this.duration,d>1&&(d=1),f=d<.5?4*d*d*d:1-Math.pow(-2*d+2,3)/2,this.targetPos.lerpVectors(t,i,f),this.targetRot.slerpQuaternions(s,r,f),this.targetScale.lerpVectors(o,a,f),sr(this.object,this.targetPos),ea(this.object,this.targetRot),kv(this.object,this.targetScale),yield;this.coroutine=null}*moveRelative(){if(!this.target||!this.object)return;const t=this.object.position.clone(),i=this.object.quaternion.clone(),s=this.object.scale.clone(),r=this.target.position.clone(),o=this.target.quaternion.clone(),a=this.target.scale.clone();r.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(r),this.targetRot.copy(this.object.quaternion).multiply(o),this.targetScale.copy(this.object.scale).multiply(a);let c=0,l=0;for(;c<1;)c+=this.context.time.deltaTime/this.duration,c>1&&(c=1),l=c<.5?4*c*c*c:1-Math.pow(-2*c+2,3)/2,this.object.position.lerpVectors(t,this.targetPos,l),this.object.quaternion.slerpQuaternions(i,this.targetRot,l),this.object.scale.lerpVectors(s,this.targetScale,l),yield;this.coroutine=null}beforeCreateDocument(t){var i;if(this.target&&this.object&&this.gameObject){const s=new $n("Move to "+((i=this.target)==null?void 0:i.name),Os.tapTrigger(this.gameObject),di.transformAction(this.object,this.target,this.duration,this.relativeMotion?TM.Relative:TM.Absolute));t.addBehavior(s)}}}mn([x(ge)],Ld.prototype,"object",2);mn([x(ge)],Ld.prototype,"target",2);mn([x()],Ld.prototype,"duration",2);mn([x()],Ld.prototype,"relativeMotion",2);var h_;const Zc=(h_=class extends Ie{constructor(){super(...arguments);u(this,"materialToSwitch");u(this,"variantMaterial");u(this,"fadeDuration",0);u(this,"_objectsWithThisMaterial",[]);u(this,"selfModel");u(this,"targetModels")}awake(){if(this.variantMaterial&&this.materialToSwitch){const e=le.findObjectsOfType(Sn);for(const t of e)for(let i=0;i<t.sharedMaterials.length;i++){const s=t.sharedMaterials[i];if(s===this.materialToSwitch){if(t.gameObject instanceof me)this._objectsWithThisMaterial.push(t.gameObject);else if(t.gameObject instanceof xr)for(const r of t.gameObject.children)r instanceof me&&r.material===s&&this._objectsWithThisMaterial.push(r);break}}}}start(){JA(this.gameObject)}onPointerClick(e){if(e.use(),!!this.variantMaterial)for(let t=0;t<this._objectsWithThisMaterial.length;t++){const i=this._objectsWithThisMaterial[t];i.material=this.variantMaterial}}async beforeCreateDocument(e,t){this.targetModels=[],Zc._materialTriggersPerId={},Zc.variantSwitchIndex=0,this.materialToSwitch&&await ao.assignTextureLOD(this.context,this.sourceId,this.materialToSwitch,0),this.variantMaterial&&await ao.assignTextureLOD(this.context,this.sourceId,this.variantMaterial,0)}createBehaviours(e,t,i){this._objectsWithThisMaterial.find(r=>r.uuid===t.uuid)&&this.targetModels.push(t),this.gameObject.uuid===t.uuid&&(this.selfModel=t,this.materialToSwitch&&(Zc._materialTriggersPerId[this.materialToSwitch.uuid]||(Zc._materialTriggersPerId[this.materialToSwitch.uuid]=[]),Zc._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(e,t){if(!this.materialToSwitch)return;const i=Zc._materialTriggersPerId[this.materialToSwitch.uuid];if(i){const s={};for(const r of i){const o=r.createVariants();o&&o.length>0&&(s[r.selfModel.uuid]=o)}for(const r of i){const o=[];for(const a in s)a!==r.selfModel.uuid&&o.push(...s[a]);r.createAndAttachBehaviors(e,s[r.selfModel.uuid],o)}}delete Zc._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(e,t,i){const s=[],r=[],o=Math.max(0,this.fadeDuration);r.push(di.fadeAction([...this.targetModels,...i],o,!1)),s.push(di.fadeAction(t,o,!1)),r.push(di.fadeAction(t,o,!0)),e.addBehavior(new $n("Select_"+this.selfModel.name,Os.tapTrigger(this.selfModel),di.parallel(...r))),e.addBehavior(new $n("StartHidden_"+this.selfModel.name,Os.sceneStartTrigger(),di.parallel(...s)))}createVariants(){if(!this.variantMaterial)return null;const e=[];for(const t of this.targetModels){const i=t.clone();i.name+=" variant_"+this.variantMaterial.name+"_"+Zc.variantSwitchIndex++,i.name=i.name.replace(/\s/g,"_"),i.material=this.variantMaterial,i.geometry=t.geometry,i.matrix=t.matrix,(!t.parent||!t.parent.isEmpty())&&Qr.createEmptyParent(t),t.parent&&t.parent.add(i),e.push(i)}return e}},u(h_,"_materialTriggersPerId",{}),u(h_,"variantSwitchIndex",0),h_);let pm=Zc;mn([x(Gt)],pm.prototype,"materialToSwitch",2);mn([x(Gt)],pm.prototype,"variantMaterial",2);mn([x()],pm.prototype,"fadeDuration",2);var Of;const cn=(Of=class extends Ie{constructor(){super(...arguments);u(this,"target");u(this,"toggleOnClick",!1);u(this,"targetState",!0);u(this,"hideSelf",!0);u(this,"selfModel");u(this,"selfModelClone");u(this,"targetModel");u(this,"toggleModel");u(this,"stateBeforeCreatingDocument",!1);u(this,"targetStateBeforeCreatingDocument",!1)}start(){JA(this.gameObject)}onPointerClick(e){e.use(),!this.toggleOnClick&&this.hideSelf&&(this.gameObject.visible=!1),this.target&&(this.target.visible=this.toggleOnClick?!this.target.visible:this.targetState)}createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t,this.selfModelClone=t.clone())}beforeCreateDocument(){this.target&&(this.gameObject[cn.wasVisible]===void 0&&(this.gameObject[cn.wasVisible]=this.gameObject.activeSelf),this.target[cn.wasVisible]===void 0&&(this.target[cn.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[cn.wasVisible],this.targetStateBeforeCreatingDocument=this.target[cn.wasVisible],this.gameObject.visible=!0,this.target.visible=!0)}afterCreateDocument(e,t){if(!this.target)return;this.targetModel=t.document.findById(this.target.uuid);const i=this.selfModel;if(this.selfModel&&this.targetModel){let s=this.selfModel,r=this.targetState;if(this.toggleOnClick)if(r=!this.targetStateBeforeCreatingDocument,!this.selfModelClone.geometry)(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&EH.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[cn.toggleClone]){const c=this.selfModelClone.clone();c.matrix.identity(),c.name+="_toggle"+cn.clonedToggleIndex++,i.add(c),this.gameObject[cn.toggleClone]=c,console.warn("USDZExport: Toggle "+this.gameObject.name+" doesn't have geometry. It will be deep cloned and nested behaviours will likely not work.")}const a=this.gameObject[cn.toggleClone];if(!this.gameObject[cn.reverseToggleClone]){const c=this.selfModelClone.clone();c.matrix.identity(),c.name+="_toggleReverse"+cn.clonedToggleIndex++,i.add(c),this.gameObject[cn.reverseToggleClone]=c}this.toggleModel=this.gameObject[cn.reverseToggleClone],(!this.toggleModel.geometry||!a.geometry)&&console.error("triggers without childs and without geometry won't work!",this,i.geometry),s=a,i.geometry=null,i.material=null}if(this.toggleModel){if(this.toggleOnClick){const a=[];a.push(di.fadeAction(s,0,!1)),a.push(di.fadeAction(this.toggleModel,0,!0)),a.push(di.fadeAction(this.targetModel,0,r)),e.addBehavior(new $n("Toggle_"+s.name+"_toggleTo"+(r?"On":"Off"),Os.tapTrigger(s),di.parallel(...a)));const c=[];c.push(di.fadeAction(this.toggleModel,0,!1)),c.push(di.fadeAction(s,0,!0)),c.push(di.fadeAction(this.targetModel,0,!r)),e.addBehavior(new $n("Toggle_"+s.name+"_toggleTo"+(r?"Off":"On"),Os.tapTrigger(this.toggleModel),di.parallel(...c)))}}else{const a=[];this.hideSelf&&a.push(di.fadeAction(s,0,!1)),a.push(di.fadeAction(this.targetModel,0,r)),e.addBehavior(new $n("Toggle_"+s.name+"_toggleTo"+(r?"On":"Off"),Os.tapTrigger(s),di.parallel(...a)))}const o=new Array;this.targetStateBeforeCreatingDocument||o.push(this.targetModel),this.stateBeforeCreatingDocument||o.push(i),this.toggleModel&&o.push(this.toggleModel),e.addBehavior(new $n("HideOnStart_"+this.gameObject.name,Os.sceneStartTrigger(),di.fadeAction(o,0,!1)))}}afterSerialize(e,t){this.gameObject[cn.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[cn.wasVisible],delete this.gameObject[cn.wasVisible]),this.target&&this.target[cn.wasVisible]!==void 0&&(this.target.visible=this.target[cn.wasVisible],delete this.target[cn.wasVisible]),delete this.gameObject[cn.toggleClone],delete this.gameObject[cn.reverseToggleClone]}},u(Of,"clonedToggleIndex",0),u(Of,"wasVisible",Symbol("usdz_SetActiveOnClick_wasVisible")),u(Of,"toggleClone",Symbol("clone for toggling")),u(Of,"reverseToggleClone",Symbol("clone for reverse toggling")),Of);let Fd=cn;mn([x(ge)],Fd.prototype,"target",2);mn([x()],Fd.prototype,"toggleOnClick",2);mn([x()],Fd.prototype,"targetState",2);mn([x()],Fd.prototype,"hideSelf",2);class nP extends Ie{start(){this.gameObject.visible=!1}createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&e.addBehavior(new $n("HideOnStart_"+this.gameObject.name,Os.sceneStartTrigger(),di.fadeAction(t,0,!1)))}beforeCreateDocument(){this.gameObject.visible=!0}afterCreateDocument(){this.gameObject.visible=!1}}class mm extends Ie{constructor(){super(...arguments);u(this,"target");u(this,"duration",.5);u(this,"motionType",OR.bounce)}beforeCreateDocument(){}createBehaviours(t,i,s){if(this.target&&i.uuid===this.gameObject.uuid){const r=new $n("emphasize "+this.name,Os.tapTrigger(this.gameObject),di.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));t.addBehavior(r)}}afterCreateDocument(t,i){}}mn([x()],mm.prototype,"target",2);mn([x()],mm.prototype,"duration",2);mn([x()],mm.prototype,"motionType",2);class gm extends Ie{constructor(){super(...arguments);u(this,"target");u(this,"clip","");u(this,"toggleOnClick",!1)}start(){JA(this.gameObject)}ensureAudioSource(){if(!this.target){const t=this.gameObject.addNewComponent(Cn);t&&(this.target=t,t.spatialBlend=1,t.volume=1,t.loop=!1)}}onPointerClick(t){var i;t.use(),!(!((i=this.target)!=null&&i.clip)&&!this.clip)&&(this.ensureAudioSource(),this.target&&(this.target.isPlaying&&this.toggleOnClick?this.target.stop():(!this.toggleOnClick&&this.target.isPlaying&&this.target.stop(),this.clip?this.target.play(this.clip):this.target.play())))}createBehaviours(t,i,s){if(!(!this.target&&!this.clip)&&i.uuid===this.gameObject.uuid){const r=this.clip?this.clip:this.target?this.target.clip:void 0;if(!r||typeof r!="string")return;const o=this.target?this.target.gameObject:this.gameObject,a=r.split("/").pop(),c=this.target?this.target.volume:1,l=this.target&&this.target.spatialBlend==0?RM.NonSpatial:RM.Spatial;{let h=di.playAudioAction(o,"audio/"+a,IM.Play,c,l);this.toggleOnClick&&(h.multiplePerformOperation=PH.Stop),this.target&&this.target.loop&&(h=di.sequence(h).makeLooping());const d=new $n("playAudio "+this.name,Os.tapTrigger(this.gameObject),h);t.addBehavior(d)}if(this.target&&this.target.playOnAwake&&this.target.enabled){let h=di.playAudioAction(o,"audio/"+a,IM.Play,c,l);this.target.loop&&(h=di.sequence(h).makeLooping());const d=new $n("playAudioOnStart "+this.name,Os.sceneStartTrigger(),h);t.addBehavior(d)}}}async afterSerialize(t,i){if(!this.target&&!this.clip)return;const s=this.clip?this.clip:this.target?this.target.clip:void 0;if(!s||typeof s!="string")return;const r=s.split("/").pop(),c=await(await(await fetch(s)).blob()).arrayBuffer(),l=new Uint8Array(c);i.files["audio/"+r]=l}}mn([x(Cn)],gm.prototype,"target",2);mn([x(URL)],gm.prototype,"clip",2);mn([x()],gm.prototype,"toggleOnClick",2);var u_;const hh=(u_=class extends Ie{constructor(){super(...arguments);u(this,"animator");u(this,"stateName");u(this,"trigger","tap");u(this,"selfModel");u(this,"stateAnimationModel");u(this,"animationSequence",new Array);u(this,"animationLoopAfterSequence",new Array)}get target(){var e;return(e=this.animator)==null?void 0:e.gameObject}start(){JA(this.gameObject)}onPointerClick(e){var t;e.use(),this.target&&this.stateName&&((t=this.animator)==null||t.play(this.stateName,0,0,.1))}createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t)}afterSerialize(){if(hh.rootsWithExclusivePlayback.size>1){const e='Multiple root objects targeted by more than one animation. To work around QuickLook bug FB13410767, animations will be set as "exclusive" and activating them will stop other animations being marked as exclusive.';Mt()&&pn(e),console.warn(e,...hh.rootsWithExclusivePlayback)}hh.animationActions=[],hh.rootsWithExclusivePlayback=new Set}afterCreateDocument(e,t){if(!this.animationSequence||!this.stateAnimationModel||!this.target)return;const i=t.document,s=t.extensions.find(a=>a instanceof GA);if(!s)return;const r=s.getClipCount(this.target)>1;r&&(Mt()&&console.warn("Setting exclusive playback for "+this.target.name+"@"+this.stateName+" because it has "+s.getClipCount(this.target)+" animations. This works around QuickLook bug FB13410767."),hh.rootsWithExclusivePlayback.add(this.target));const o=(a,c)=>{let l=hh.animationActions.find(h=>h.affectedObjects==a&&h.start==c.start&&h.duration==c.duration);return l||(l=di.startAnimationAction(a,c.start,c.duration),hh.animationActions.push(l)),l};i.traverse(a=>{var c,l;if(a.uuid===((c=this.target)==null?void 0:c.uuid)){const h=di.sequence();if(this.animationSequence!==void 0)for(const f of this.animationSequence)h.addAction(o(a,f));if(this.animationLoopAfterSequence!==void 0){const f=h.actions.length==0?h:di.sequence();for(const p of this.animationLoopAfterSequence)f.addAction(o(a,p));f.makeLooping(),h!==f&&h.addAction(f)}const d=new $n("tap "+this.name+" for "+this.stateName+" on "+((l=this.target)==null?void 0:l.name),this.trigger=="tap"?Os.tapTrigger(this.selfModel):Os.sceneStartTrigger(),h);r&&d.makeExclusive(!0),e.addBehavior(d)}})}createAnimation(e,t,i){var c,l,h,d;if(!this.target||!this.animator)return;const s=(c=this.animator)==null?void 0:c.runtimeAnimatorController;let r=s==null?void 0:s.findState(this.stateName),o=[],a=[];if(s&&r){const f=new Array;f.push(r);let p=!1;for(;f.length<100;){if(!r||r===null||!r.transitions||r.transitions.length===0){(l=r.motion)!=null&&l.isLooping&&(p=!0);break}const m=r.transitions.find(y=>y.conditions.length===0),g=m?s.getState(m.destinationState,0):null;if(g&&f.includes(g)){r=g,p=!0;break}else if(m){if(r=g,!r)break;f.push(r)}else{p=((h=r.motion)==null?void 0:h.isLooping)??!1;break}}if(p&&r){const m=f.indexOf(r);o=f.slice(0,m),a=f.slice(m),console.log("found loop from "+this.stateName,"states until loop",o,"states looping",a)}else o=f,a=[],console.log("found no loop from "+this.stateName,"states",o)}if(o=o.filter(f=>{var p,m,g;return((p=f.motion)==null?void 0:p.clip)&&((g=(m=f.motion)==null?void 0:m.clip.tracks)==null?void 0:g.length)>0}),a=a.filter(f=>{var p,m,g;return((p=f.motion)==null?void 0:p.clip)&&((g=(m=f.motion)==null?void 0:m.clip.tracks)==null?void 0:g.length)>0}),o.length===0&&a.length===0){console.warn("No clips found for state "+this.stateName+" on "+((d=this.animator)==null?void 0:d.name)+", can't export animation data");return}if(this.stateAnimationModel=t,o.length>0){this.animationSequence=new Array;for(const f of o)this.animationSequence.push(e.registerAnimation(this.target,f.motion.clip))}if(a.length>0){this.animationLoopAfterSequence=new Array;for(const f of a)this.animationLoopAfterSequence.push(e.registerAnimation(this.target,f.motion.clip))}}},u(u_,"animationActions",[]),u(u_,"rootsWithExclusivePlayback",new Set),u_);let vm=hh;mn([x(Us)],vm.prototype,"animator",2);mn([x()],vm.prototype,"stateName",2);class Am extends Ie{constructor(){super(...arguments);u(this,"target")}getType(){}getDuration(){}}mn([x(ge)],Am.prototype,"target",2);class KA extends Ie{constructor(){super(...arguments);u(this,"target")}}mn([x(Am)],KA.prototype,"target",2);class ZA extends Am{constructor(){super(...arguments);u(this,"type",1);u(this,"duration",1)}getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}mn([x()],ZA.prototype,"type",2);mn([x()],ZA.prototype,"duration",2);class sP extends KA{}var Sre=Object.defineProperty,Cre=Object.getOwnPropertyDescriptor,Ul=(n,e,t,i)=>{for(var s=i>1?void 0:i?Cre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Sre(e,t,s),s};const h2=se("debugcharactercontroller");class Ud extends Ie{constructor(){super(...arguments);u(this,"center",new w(0,0,0));u(this,"radius",.5);u(this,"height",2);u(this,"_rigidbody",null);u(this,"_activeGroundCollisions");u(this,"_contactVelocity",new w)}get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(Xi),this._rigidbody||(this._rigidbody=this.gameObject.addNewComponent(Xi)),this.rigidbody)}awake(){this._activeGroundCollisions=new Set}onEnable(){const t=this.rigidbody;let i=this.gameObject.getComponent(zh);i||(i=this.gameObject.addNewComponent(zh)),i.center.copy(this.center),i.radius=this.radius,i.height=this.height;const s=new w(0,0,1),r=new w(1,0,0),o=new w(0,1,0),a=this.gameObject.getWorldDirection(new w);a.y=0;const c=r.dot(a)<0?-1:1,l=s.angleTo(a)*c;this.gameObject.setRotationFromAxisAngle(o,l),t.lockRotationX=!0,t.lockRotationY=!0,t.lockRotationZ=!0}move(t){this.gameObject.position.add(t)}onCollisionEnter(t){(t.contacts.length==0||t.contacts.some(i=>i.normal.y>.2))&&(this._activeGroundCollisions.add(t),h2&&console.log(`Collision(${this._activeGroundCollisions.size}): ${t.contacts.map(i=>i.normal.y.toFixed(2)).join(", ")} - ${this.isGrounded}`))}onCollisionExit(t){this._activeGroundCollisions.delete(t),h2&&console.log(`Collision(${this._activeGroundCollisions.size}) - ${this.isGrounded}`)}get isGrounded(){return this._activeGroundCollisions.size>0}get contactVelocity(){var t;this._contactVelocity.set(0,0,0);for(const i of this._activeGroundCollisions){const s=(t=this.context.physics.engine)==null?void 0:t.getLinearVelocity(i.collider);s&&(this._contactVelocity.x+=s.x,this._contactVelocity.y+=s.y,this._contactVelocity.z+=s.z)}return this._contactVelocity}}Ul([x(w)],Ud.prototype,"center",2);Ul([x()],Ud.prototype,"radius",2);Ul([x()],Ud.prototype,"height",2);class Nl extends Ie{constructor(){super(...arguments);u(this,"controller");u(this,"movementSpeed",2);u(this,"rotationSpeed",2);u(this,"jumpForce",1);u(this,"doubleJumpForce",2);u(this,"animator");u(this,"lookForward",!0);u(this,"lookInput",new ie(0,0));u(this,"moveInput",new ie(0,0));u(this,"jumpInput",!1);u(this,"_currentSpeed",new w(0,0,0));u(this,"_currentAngularSpeed",new w(0,0,0));u(this,"_temp",new w(0,0,0));u(this,"_jumpCount",0);u(this,"_currentRotation");u(this,"_raycastOptions",new ta)}awake(){this._currentRotation=new Ee}update(){const t=this.context.input;t.isKeyPressed("KeyW")?this.moveInput.y+=1:t.isKeyPressed("KeyS")&&(this.moveInput.y-=1),t.isKeyPressed("KeyD")?this.lookInput.x+=1:t.isKeyPressed("KeyA")&&(this.lookInput.x-=1),this.jumpInput||(this.jumpInput=t.isKeyDown("Space"))}move(t){this.moveInput.add(t)}look(t){this.lookInput.add(t)}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(t,i,s){var r,o,a,c,l,h,d,f,p,m,g;if((r=this.controller)!=null&&r.isGrounded&&(this._jumpCount=0,this.doubleJumpForce>0&&((o=this.animator)==null||o.setBool("doubleJump",!1))),this._currentSpeed.z+=t.y*this.movementSpeed*this.context.time.deltaTime,(a=this.animator)==null||a.setBool("running",t.length()>.01),(l=this.animator)==null||l.setBool("jumping",((c=this.controller)==null?void 0:c.isGrounded)===!0&&s),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+=rt.toRadians(-i.x*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){const y=this.context.mainCameraComponent.forward;y.y=0,y.normalize(),this._currentRotation.setFromUnitVectors(new w(0,0,1),y),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&&s&&this.jumpForce>0){let y=(h=this.controller)==null?void 0:h.isGrounded;if(this.doubleJumpForce>0&&!((d=this.controller)!=null&&d.isGrounded)&&this._jumpCount===1&&(y=!0,(f=this.animator)==null||f.setBool("doubleJump",!0)),y){this._jumpCount+=1;const v=this.controller.rigidbody,A=this._jumpCount===2?this.doubleJumpForce:this.jumpForce;v.applyImpulse(new w(0,1,0).multiplyScalar(A))}}if(this.controller){const y=(p=this.controller)==null?void 0:p.rigidbody.getVelocity().y;if(y<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new bo),this._raycastOptions.ray.origin.copy(Dt(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);const v=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);const A=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(v),(A.length&&A[0].distance>2||y<-10)&&((m=this.animator)==null||m.setBool("falling",!0))}else(g=this.animator)==null||g.setBool("falling",!1)}}}Ul([x(Ud)],Nl.prototype,"controller",2);Ul([x()],Nl.prototype,"movementSpeed",2);Ul([x()],Nl.prototype,"rotationSpeed",2);Ul([x()],Nl.prototype,"jumpForce",2);Ul([x()],Nl.prototype,"doubleJumpForce",2);Ul([x(Us)],Nl.prototype,"animator",2);var Ere=Object.defineProperty,Mre=Object.getOwnPropertyDescriptor,Tre=(n,e,t,i)=>{for(var s=i>1?void 0:i?Mre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Ere(e,t,s),s};class $A extends cr{constructor(){super(...arguments);u(this,"intensity")}get typeName(){return"ChromaticAberration"}init(){this.intensity.defaultValue=0}onCreateEffect(){const t=new EN;return t.offset=new ie(0,0),t.radialModulation=!0,t.modulationOffset=.15,this.intensity.valueProcessor=i=>i*.02,this.intensity.onValueChanged=i=>{t.offset.x=-i,t.offset.y=i},t}}Tre([x(kt)],$A.prototype,"intensity",2);oa("ChromaticAberration",$A);var Ire=Object.defineProperty,Rre=Object.getOwnPropertyDescriptor,Pw=(n,e,t,i)=>{for(var s=i>1?void 0:i?Rre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Ire(e,t,s),s};class Zh extends cr{constructor(){super(...arguments);u(this,"postExposure");u(this,"contrast");u(this,"hueShift");u(this,"saturation")}get typeName(){return"ColorAdjustments"}init(){this.postExposure.valueProcessor=t=>(t=Math.pow(2,t),t),this.postExposure.defaultValue=0,this.contrast.valueProcessor=t=>{let i=1;return t>0?i=200:t<0&&(i=100),t/i},this.contrast.defaultValue=0,this.hueShift.valueProcessor=t=>Math.PI*t/180,this.hueShift.defaultValue=0,this.saturation.valueProcessor=t=>t<0?t/100:t/(100*Math.PI),this.saturation.defaultValue=0}unapply(){this.context.renderer.toneMappingExposure=1}onCreateEffect(){this.context.renderer.toneMapping===Wr&&this.postExposure.overrideState&&(this.context.renderer.toneMapping=av);const t=new CN;this.postExposure.onValueChanged=s=>{this.context.renderer.toneMapping===Wr&&(this.context.renderer.toneMapping=av),this.postExposure.overrideState&&(this.context.renderer.toneMappingExposure=s)},this.contrast.onValueChanged=s=>{t.contrast=s};const i=new TN;return this.hueShift.onValueChanged=s=>i.hue=s,this.saturation.onValueChanged=s=>i.saturation=s,[i,t]}}Pw([x(kt)],Zh.prototype,"postExposure",2);Pw([x(kt)],Zh.prototype,"contrast",2);Pw([x(kt)],Zh.prototype,"hueShift",2);Pw([x(kt)],Zh.prototype,"saturation",2);oa("ColorAdjustments",Zh);const Pre=(Math.sqrt(5)-1)/4,xs=(5-Math.sqrt(5))/20,H0=n=>Math.floor(n)|0,V0=new Float64Array([0,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,1,0,1,1,1,0,1,-1,1,0,-1,1,1,0,-1,-1,-1,0,1,1,-1,0,1,-1,-1,0,-1,1,-1,0,-1,-1,1,1,0,1,1,1,0,-1,1,-1,0,1,1,-1,0,-1,-1,1,0,1,-1,1,0,-1,-1,-1,0,1,-1,-1,0,-1,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,0]);function Bre(n=Math.random){const e=Dre(n),t=new Float64Array(e).map(o=>V0[o%32*4]),i=new Float64Array(e).map(o=>V0[o%32*4+1]),s=new Float64Array(e).map(o=>V0[o%32*4+2]),r=new Float64Array(e).map(o=>V0[o%32*4+3]);return function(a,c,l,h){let d,f,p,m,g;const y=(a+c+l+h)*Pre,v=H0(a+y),A=H0(c+y),_=H0(l+y),b=H0(h+y),C=(v+A+_+b)*xs,E=v-C,T=A-C,I=_-C,S=b-C,M=a-E,D=c-T,G=l-I,Q=h-S;let L=0,H=0,O=0,U=0;M>D?L++:H++,M>G?L++:O++,M>Q?L++:U++,D>G?H++:O++,D>Q?H++:U++,G>Q?O++:U++;const V=L>=3?1:0,J=H>=3?1:0,K=O>=3?1:0,oe=U>=3?1:0,fe=L>=2?1:0,be=H>=2?1:0,ke=O>=2?1:0,Ye=U>=2?1:0,ae=L>=1?1:0,Ae=H>=1?1:0,Ne=O>=1?1:0,Ve=U>=1?1:0,Je=M-V+xs,He=D-J+xs,Be=G-K+xs,X=Q-oe+xs,ve=M-fe+2*xs,Le=D-be+2*xs,_e=G-ke+2*xs,qe=Q-Ye+2*xs,lt=M-ae+3*xs,F=D-Ae+3*xs,B=G-Ne+3*xs,ce=Q-Ve+3*xs,Ce=M-1+4*xs,xe=D-1+4*xs,Re=G-1+4*xs,nt=Q-1+4*xs,Ue=v&255,$e=A&255,at=_&255,bt=b&255;let Me=.6-M*M-D*D-G*G-Q*Q;if(Me<0)d=0;else{const Qe=Ue+e[$e+e[at+e[bt]]];Me*=Me,d=Me*Me*(t[Qe]*M+i[Qe]*D+s[Qe]*G+r[Qe]*Q)}let Ft=.6-Je*Je-He*He-Be*Be-X*X;if(Ft<0)f=0;else{const Qe=Ue+V+e[$e+J+e[at+K+e[bt+oe]]];Ft*=Ft,f=Ft*Ft*(t[Qe]*Je+i[Qe]*He+s[Qe]*Be+r[Qe]*X)}let pt=.6-ve*ve-Le*Le-_e*_e-qe*qe;if(pt<0)p=0;else{const Qe=Ue+fe+e[$e+be+e[at+ke+e[bt+Ye]]];pt*=pt,p=pt*pt*(t[Qe]*ve+i[Qe]*Le+s[Qe]*_e+r[Qe]*qe)}let mt=.6-lt*lt-F*F-B*B-ce*ce;if(mt<0)m=0;else{const Qe=Ue+ae+e[$e+Ae+e[at+Ne+e[bt+Ve]]];mt*=mt,m=mt*mt*(t[Qe]*lt+i[Qe]*F+s[Qe]*B+r[Qe]*ce)}let et=.6-Ce*Ce-xe*xe-Re*Re-nt*nt;if(et<0)g=0;else{const Qe=Ue+1+e[$e+1+e[at+1+e[bt+1]]];et*=et,g=et*et*(t[Qe]*Ce+i[Qe]*xe+s[Qe]*Re+r[Qe]*nt)}return 27*(d+f+p+m+g)}}function Dre(n){const t=new Uint8Array(512);for(let i=0;i<512/2;i++)t[i]=i;for(let i=0;i<512/2-1;i++){const s=i+~~(n()*(256-i)),r=t[i];t[i]=t[s],t[s]=r}for(let i=256;i<512;i++)t[i]=t[i-256];return t}var Ore=Object.defineProperty,kre=Object.getOwnPropertyDescriptor,re=(n,e,t,i)=>{for(var s=i>1?void 0:i?kre(e,t):e,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=(i?o(e,t,s):o(s))||s);return i&&s&&Ore(e,t,s),s};const Q0=se("debugparticles");var il=(n=>(n[n.Billboard=0]="Billboard",n[n.Stretch=1]="Stretch",n[n.HorizontalBillboard=2]="HorizontalBillboard",n[n.VerticalBillboard=3]="VerticalBillboard",n[n.Mesh=4]="Mesh",n))(il||{});let $h=class{constructor(){u(this,"alphaKeys");u(this,"colorKeys")}get duration(){return 1}evaluate(e,t){let i,s=0,r=null,o=0;for(let a=0;a<this.alphaKeys.length;a++){const c=this.alphaKeys[a];(c.time<e||!i)&&(i=c,s=a)}for(let a=0;a<this.colorKeys.length;a++){const c=this.colorKeys[a];(c.time<e||!r)&&(r=c,o=a)}if(r)if(o+1<this.colorKeys.length){const c=this.colorKeys[o+1],l=rt.remap(e,r.time,c.time,0,1);t.r=rt.lerp(r.color.r,c.color.r,l),t.g=rt.lerp(r.color.g,c.color.g,l),t.b=rt.lerp(r.color.b,c.color.b,l)}else t.r=r.color.r,t.g=r.color.g,t.b=r.color.b;if(i)if(s+1<this.alphaKeys.length){const c=this.alphaKeys[s+1],l=rt.remap(e,i.time,c.time,0,1);t.alpha=rt.lerp(i.alpha,c.alpha,l)}else t.alpha=i.alpha;return t}};re([x()],$h.prototype,"alphaKeys",2);re([x()],$h.prototype,"colorKeys",2);var Vv=(n=>(n[n.Local=0]="Local",n[n.World=1]="World",n[n.Custom=2]="Custom",n))(Vv||{}),Gb=(n=>(n[n.Sphere=0]="Sphere",n[n.SphereShell=1]="SphereShell",n[n.Hemisphere=2]="Hemisphere",n[n.HemisphereShell=3]="HemisphereShell",n[n.Cone=4]="Cone",n[n.Box=5]="Box",n[n.Mesh=6]="Mesh",n[n.ConeShell=7]="ConeShell",n[n.ConeVolume=8]="ConeVolume",n[n.ConeVolumeShell=9]="ConeVolumeShell",n[n.Circle=10]="Circle",n[n.CircleEdge=11]="CircleEdge",n[n.SingleSidedEdge=12]="SingleSidedEdge",n[n.MeshRenderer=13]="MeshRenderer",n[n.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",n[n.BoxShell=15]="BoxShell",n[n.BoxEdge=16]="BoxEdge",n[n.Donut=17]="Donut",n[n.Rectangle=18]="Rectangle",n[n.Sprite=19]="Sprite",n[n.SpriteRenderer=20]="SpriteRenderer",n))(Gb||{});const ZH=class{constructor(){u(this,"mode");u(this,"constant");u(this,"constantMin");u(this,"constantMax");u(this,"curve");u(this,"curveMin");u(this,"curveMax");u(this,"curveMultiplier")}clone(){var e,t,i;const n=new ZH;return n.mode=this.mode,n.constant=this.constant,n.constantMin=this.constantMin,n.constantMax=this.constantMax,n.curve=(e=this.curve)==null?void 0:e.clone(),n.curveMin=(t=this.curveMin)==null?void 0:t.clone(),n.curveMax=(i=this.curveMax)==null?void 0:i.clone(),n.curveMultiplier=this.curveMultiplier,n}evaluate(n,e){const t=e===void 0?Math.random():e;switch(this.mode){case 0:return this.constant;case 1:return n=rt.clamp01(n),this.curve.evaluate(n)*this.curveMultiplier;case 2:const i=n*this.curveMin.duration,s=n*this.curveMax.duration;return rt.lerp(this.curveMin.evaluate(i),this.curveMax.evaluate(s),t%1)*this.curveMultiplier;case 3:return rt.lerp(this.constantMin,this.constantMax,t%1);default:this.curveMax.evaluate(n)*this.curveMultiplier;break}return 0}getMax(){switch(this.mode){case 0:return this.constant;case 1:return this.getMaxFromCurve(this.curve)*this.curveMultiplier;case 2:return Math.max(this.getMaxFromCurve(this.curveMin),this.getMaxFromCurve(this.curveMax))*this.curveMultiplier;case 3:return Math.max(this.constantMin,this.constantMax);default:return 0}}getMaxFromCurve(n){if(!n)return 0;let e=Number.MIN_VALUE;for(let t=0;t<n.keys.length;t++){const i=n.keys[t];i.value>e&&(e=i.value)}return e}};let ft=ZH;re([x()],ft.prototype,"mode",2);re([x()],ft.prototype,"constant",2);re([x()],ft.prototype,"constantMin",2);re([x()],ft.prototype,"constantMax",2);re([x(Td)],ft.prototype,"curve",2);re([x(Td)],ft.prototype,"curveMin",2);re([x(Td)],ft.prototype,"curveMax",2);re([x()],ft.prototype,"curveMultiplier",2);var d_;const ga=(d_=class{constructor(){u(this,"mode");u(this,"color");u(this,"colorMin");u(this,"colorMax");u(this,"gradient");u(this,"gradientMin");u(this,"gradientMax")}evaluate(n,e){const t=e===void 0?Math.random():e;switch(this.mode){case 0:return this.color;case 1:return this.gradient.evaluate(n,ga._temp),ga._temp;case 2:return ga._temp.lerpColors(this.colorMin,this.colorMax,t);case 3:return this.gradientMin.evaluate(n,ga._temp),this.gradientMax.evaluate(n,ga._temp2),ga._temp.lerp(ga._temp2,t)}return ga._temp.set(16711935),ga._temp.alpha=1,ga._temp}},u(d_,"_temp",new Ti(0,0,0,1)),u(d_,"_temp2",new Ti(0,0,0,1)),d_);let Jr=ga;re([x(Ti)],Jr.prototype,"color",2);re([x(Ti)],Jr.prototype,"colorMin",2);re([x(Ti)],Jr.prototype,"colorMax",2);re([x($h)],Jr.prototype,"gradient",2);re([x($h)],Jr.prototype,"gradientMin",2);re([x($h)],Jr.prototype,"gradientMax",2);var UM=(n=>(n[n.Hierarchy=0]="Hierarchy",n[n.Local=1]="Local",n[n.Shape=2]="Shape",n))(UM||{});class js{constructor(){u(this,"cullingMode");u(this,"duration");u(this,"emitterVelocityMode");u(this,"flipRotation");u(this,"gravityModifier");u(this,"gravityModifierMultiplier");u(this,"loop");u(this,"maxParticles");u(this,"playOnAwake");u(this,"prewarm");u(this,"ringBufferLoopRange");u(this,"ringBufferMode");u(this,"scalingMode");u(this,"simulationSpace");u(this,"simulationSpeed");u(this,"startColor");u(this,"startDelay");u(this,"startDelayMultiplier");u(this,"startLifetime");u(this,"startLifetimeMultiplier");u(this,"startRotation");u(this,"startRotationMultiplier");u(this,"startRotation3D");u(this,"startRotationX");u(this,"startRotationXMultiplier");u(this,"startRotationY");u(this,"startRotationYMultiplier");u(this,"startRotationZ");u(this,"startRotationZMultiplier");u(this,"startSize");u(this,"startSize3D");u(this,"startSizeMultiplier");u(this,"startSizeX");u(this,"startSizeXMultiplier");u(this,"startSizeY");u(this,"startSizeYMultiplier");u(this,"startSizeZ");u(this,"startSizeZMultiplier");u(this,"startSpeed");u(this,"startSpeedMultiplier");u(this,"stopAction");u(this,"useUnscaledTime")}}re([x(ft)],js.prototype,"gravityModifier",2);re([x(Jr)],js.prototype,"startColor",2);re([x(ft)],js.prototype,"startDelay",2);re([x(ft)],js.prototype,"startLifetime",2);re([x(ft)],js.prototype,"startRotation",2);re([x(ft)],js.prototype,"startRotationX",2);re([x(ft)],js.prototype,"startRotationY",2);re([x(ft)],js.prototype,"startRotationZ",2);re([x(ft)],js.prototype,"startSize",2);re([x(ft)],js.prototype,"startSizeX",2);re([x(ft)],js.prototype,"startSizeY",2);re([x(ft)],js.prototype,"startSizeZ",2);re([x(ft)],js.prototype,"startSpeed",2);class Qv{constructor(){u(this,"cycleCount");u(this,"maxCount");u(this,"minCount");u(this,"probability");u(this,"repeatInterval");u(this,"time");u(this,"count");u(this,"_performed",0)}reset(){this._performed=0}run(e){if(e<=this.time)return 0;let t=0;if(this.cycleCount===0||this._performed<this.cycleCount){const i=this.time+this.repeatInterval*this._performed;if(e>=i&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:t=this.count.constant;break;case 3:t=rt.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:t=this.count.curve.evaluate(Math.random());break;case 2:const s=Math.random();t=rt.lerp(this.count.curveMin.evaluate(s),this.count.curveMax.evaluate(s),Math.random());break}}return t}}class Pc{constructor(){u(this,"enabled");u(this,"bursts");u(this,"rateOverTime");u(this,"rateOverTimeMultiplier");u(this,"rateOverDistance");u(this,"rateOverDistanceMultiplier");u(this,"system")}get burstCount(){var e;return((e=this.bursts)==null?void 0:e.length)??0}reset(){var e;(e=this.bursts)==null||e.forEach(t=>t.reset())}getBurst(){let e=0;if(this.burstCount>0)for(let t=0;t<this.burstCount;t++){const i=this.bursts[t];this.system.main.loop&&i.time>=this.system.time&&i.reset(),e+=Math.round(i.run(this.system.time))}return e}}re([x()],Pc.prototype,"enabled",2);re([x()],Pc.prototype,"bursts",2);re([x(ft)],Pc.prototype,"rateOverTime",2);re([x()],Pc.prototype,"rateOverTimeMultiplier",2);re([x(ft)],Pc.prototype,"rateOverDistance",2);re([x()],Pc.prototype,"rateOverDistanceMultiplier",2);class ey{constructor(){u(this,"enabled");u(this,"color")}}re([x(Jr)],ey.prototype,"color",2);class eu{constructor(){u(this,"enabled");u(this,"separateAxes");u(this,"size");u(this,"sizeMultiplier");u(this,"x");u(this,"xMultiplier");u(this,"y");u(this,"yMultiplier");u(this,"z");u(this,"zMultiplier");u(this,"_time",0);u(this,"_temp",new w)}evaluate(e,t,i){if(t||(t=this._temp),!this.enabled)return t.x=t.y=t.z=1,t;if(this.separateAxes)t.x=this.x.evaluate(e,i)*this.xMultiplier,t.y=this.y.evaluate(e,i)*this.yMultiplier,t.z=this.z.evaluate(e,i)*this.zMultiplier;else{const s=this.size.evaluate(e,i)*this.sizeMultiplier;t.x=s}return t}}re([x(ft)],eu.prototype,"size",2);re([x(ft)],eu.prototype,"x",2);re([x(ft)],eu.prototype,"y",2);re([x(ft)],eu.prototype,"z",2);var f_;const Cg=(f_=class{constructor(){u(this,"shapeType",5);u(this,"enabled",!0);u(this,"alignToDirection",!1);u(this,"angle",0);u(this,"arc",360);u(this,"arcSpread");u(this,"arcSpeedMultiplier");u(this,"arcMode");u(this,"boxThickness");u(this,"position");u(this,"rotation");u(this,"_rotation",new ks);u(this,"scale");u(this,"radius");u(this,"radiusThickness");u(this,"sphericalDirectionAmount");u(this,"randomDirectionAmount");u(this,"randomPositionAmount");u(this,"meshShapeType");u(this,"meshRenderer");u(this,"_meshObj");u(this,"_meshGeometry");u(this,"system");u(this,"_space");u(this,"_worldSpaceMatrix",new Se);u(this,"_worldSpaceMatrixInverse",new Se);u(this,"_vector",new w(0,0,0));u(this,"_temp",new w(0,0,0));u(this,"_triangle",new br);u(this,"_dir",new w);u(this,"_loopTime",0);u(this,"_loopDirection",1);Q0&&console.log(this)}get type(){return Gb[this.shapeType]}initialize(n){this.onInitialize(n),n.position.copy(this._vector)}toJSON(){return this}clone(){return new Cg}setMesh(n){this.meshRenderer=n,n?(this._meshObj=n.sharedMeshes[Math.floor(Math.random()*n.sharedMeshes.length)],this._meshGeometry=this._meshObj.geometry):(this._meshObj=void 0,this._meshGeometry=void 0)}update(n,e,t,i){this.system=n,this._space=t,t===1&&(this._worldSpaceMatrix.copy(i.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}applyRotation(n){const e=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return e&&(this._rotation.x=rt.toRadians(this.rotation.x),this._rotation.y=rt.toRadians(this.rotation.y),this._rotation.z=rt.toRadians(this.rotation.z),this._rotation.order="ZYX",n.applyEuler(this._rotation)),e}onInitialize(n){this._vector.set(0,0,0),n.mesh=void 0,n.mesh_geometry=void 0;const e=this._temp.copy(this.position),t=this._space===1;t&&e.applyQuaternion(this.system.worldQuaternion);let i=this.radius;if(t&&(i*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:Q0&&It.DrawWireBox(this.position,this.scale,14540253,1),this._vector.x=Math.random()*this.scale.x-this.scale.x/2,this._vector.y=Math.random()*this.scale.y-this.scale.y/2,this._vector.z=Math.random()*this.scale.z-this.scale.z/2,this._vector.add(e);break;case 4:this.randomConePoint(this.position,this.angle,i,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,i,this.radiusThickness,this.arc,this._vector);break;case 10:this.randomCirclePoint(this.position,i,this.radiusThickness,this.arc,this._vector);break;case 13:const s=this.meshRenderer;(s==null?void 0:s.destroyed)==!1&&this.setMesh(s);const r=n.mesh=this._meshObj,o=n.mesh_geometry=this._meshGeometry;if(r&&o)switch(this.meshShapeType){case 0:{const a=o.getAttribute("position"),c=Math.floor(Math.random()*a.count);this._vector.fromBufferAttribute(a,c),this._vector.applyMatrix4(r.matrixWorld),n.mesh_normal=c}break;case 1:break;case 2:{const a=o.index;if(a){let c=Math.random(),l=Math.random();c+l>1&&(c=1-c,l=1-l);const h=Math.floor(Math.random()*(a.count/3));let d=h*3,f=h*3+1,p=h*3+2;d=a.getX(d),f=a.getX(f),p=a.getX(p);const m=o.getAttribute("position");this._triangle.a.fromBufferAttribute(m,d),this._triangle.b.fromBufferAttribute(m,f),this._triangle.c.fromBufferAttribute(m,p),this._vector.set(0,0,0).addScaledVector(this._triangle.a,c).addScaledVector(this._triangle.b,l).addScaledVector(this._triangle.c,1-(c+l)),this._vector.applyMatrix4(r.matrixWorld),n.mesh_normal=h}}break}break;default:this._vector.set(0,0,0),Mt()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",Gb[this.shapeType]),globalThis.__particlesystem_shapetype_unsupported=!0);break}this.randomizePosition(this._vector,this.randomPositionAmount)}this.applyRotation(this._vector),t&&(this._vector.applyQuaternion(this.system.worldQuaternion),this._vector.add(this.system.worldPos)),Q0&&It.DrawSphere(this._vector,.03,16711680,.5,!0)}getDirection(n,e){var t;if(!this.enabled)return this._dir.set(0,0,1),this._dir;switch(this.shapeType){case 5:this._dir.set(0,0,1);break;case 4:this._dir.set(0,0,1);break;case 10:case 0:const i=e.x,s=e.y,r=e.z;this._dir.set(i,s,r),(t=this.system)!=null&&t.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;case 13:const o=n.mesh,a=n.mesh_geometry;if(o&&a)switch(this.meshShapeType){case 0:{const c=a.getAttribute("normal"),l=n.mesh_normal;this._dir.fromBufferAttribute(c,l)}break;case 1:break;case 2:{const c=a.index;if(c){const l=n.mesh_normal,h=c.getX(l*3),d=c.getX(l*3+1),f=c.getX(l*3+2),p=a.getAttribute("position"),m=Gn(),g=Gn(),y=Gn();m.fromBufferAttribute(p,h),g.fromBufferAttribute(p,d),y.fromBufferAttribute(p,f),m.sub(g),y.sub(g),m.cross(y),this._dir.copy(m).multiplyScalar(-1);const v=Di(o);this._dir.applyQuaternion(v)}}break}break;default:this._dir.set(0,0,1);break}return this._space===1&&this._dir.applyQuaternion(this.system.worldQuaternion),this.applyRotation(this._dir),this._dir.normalize(),this.spherizeDirection(this._dir,this.sphericalDirectionAmount),this.randomizeDirection(this._dir,this.randomDirectionAmount),Q0&&(It.DrawSphere(e,.01,8925952,.5,!0),It.DrawDirection(e,this._dir,8925952,.5,!0)),this._dir}randomizePosition(n,e){if(e<=0)return;const t=Cg._tempVec;t.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),t.x*=e*this.scale.x,t.y*=e*this.scale.y,t.z*=e*this.scale.z,n.add(t)}randomizeDirection(n,e){if(e===0)return;const t=Cg._randomQuat,i=Cg._tempVec;i.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),t.setFromAxisAngle(i,e*Math.random()*Math.PI),n.applyQuaternion(t)}spherizeDirection(n,e){if(e===0)return;const t=Math.random()*Math.PI*2,i=Math.acos(1-Math.random()*2),s=Math.sin(i)*Math.cos(t),r=Math.sin(i)*Math.sin(t),o=Math.cos(i),a=new w(s,r,o);n.lerp(a,e)}randomSpherePoint(n,e,t,i,s){const r=Math.random(),o=Math.random(),a=2*Math.PI*r*(i/360),c=Math.acos(2*o-1),l=rt.lerp(1,1-Math.pow(1-Math.random(),Math.PI),t)*e,h=n.x+this.scale.x*(-l*Math.sin(c)*Math.cos(a)),d=n.y+this.scale.y*(l*Math.sin(c)*Math.sin(a)),f=n.z+this.scale.z*(l*Math.cos(c));s.x=h,s.y=d,s.z=f}randomCirclePoint(n,e,t,i,s){const r=Math.random(),o=2*Math.PI*r*(i/360),a=rt.lerp(1,1-Math.pow(1-Math.random(),Math.PI),t)*e,c=n.x+this.scale.x*a*Math.cos(o),l=n.y+this.scale.y*a*Math.sin(o),h=n.z;s.x=c,s.y=l,s.z=h}randomConePoint(n,e,t,i,s,r,o){let a=0,c=0;switch(r){case 0:a=Math.random(),c=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:a=.5,c=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let l=2*Math.PI*a*(s/360);switch(r){case 2:case 1:l+=Math.PI+.5,l+=this._loopTime*Math.PI*2,l%=rt.toRadians(s);break}const h=Math.acos(2*c-1),d=rt.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,f=n.x+-d*Math.sin(h)*Math.cos(l),p=n.y+d*Math.sin(h)*Math.sin(l),m=n.z;o.x=f*this.scale.x,o.y=p*this.scale.y,o.z=m*this.scale.z}},u(f_,"_randomQuat",new Ee),u(f_,"_tempVec",new w),f_);let gn=Cg;re([x()],gn.prototype,"shapeType",2);re([x()],gn.prototype,"enabled",2);re([x()],gn.prototype,"alignToDirection",2);re([x()],gn.prototype,"angle",2);re([x()],gn.prototype,"arc",2);re([x()],gn.prototype,"arcSpread",2);re([x()],gn.prototype,"arcSpeedMultiplier",2);re([x()],gn.prototype,"arcMode",2);re([x(w)],gn.prototype,"boxThickness",2);re([x(w)],gn.prototype,"position",2);re([x(w)],gn.prototype,"rotation",2);re([x(w)],gn.prototype,"scale",2);re([x()],gn.prototype,"radius",2);re([x()],gn.prototype,"radiusThickness",2);re([x()],gn.prototype,"sphericalDirectionAmount",2);re([x()],gn.prototype,"randomDirectionAmount",2);re([x()],gn.prototype,"randomPositionAmount",2);re([x()],gn.prototype,"meshShapeType",2);re([x(DA)],gn.prototype,"meshRenderer",2);class Ri{constructor(){u(this,"damping");u(this,"enabled");u(this,"frequency");u(this,"octaveCount");u(this,"octaveMultiplier");u(this,"octaveScale");u(this,"positionAmount");u(this,"quality");u(this,"remap");u(this,"remapEnabled");u(this,"remapMultiplier");u(this,"remapX");u(this,"remapXMultiplier");u(this,"remapY");u(this,"remapYMultiplier");u(this,"remapZ");u(this,"remapZMultiplier");u(this,"scrollSpeedMultiplier");u(this,"separateAxes");u(this,"strengthMultiplier");u(this,"strengthX");u(this,"strengthXMultiplier");u(this,"strengthY");u(this,"strengthYMultiplier");u(this,"strengthZ");u(this,"strengthZMultiplier");u(this,"_noise");u(this,"_time",0);u(this,"_temp",new w)}update(e){this._time+=e.time.deltaTime*this.scrollSpeedMultiplier}apply(e,t,i,s,r,o){if(!this.enabled)return;this._noise||(this._noise=Bre(()=>0));const a=this._temp.set(t.x,t.y,t.z).multiplyScalar(this.frequency),c=this._noise(a.x,a.y,a.z,this._time),l=this._noise(a.x,a.y,a.z,this._time+1e3*this.frequency),h=this._noise(a.x,a.y,a.z,this._time+2e3*this.frequency);this._temp.set(c,l,h).normalize();const d=r/o;let f=this.positionAmount.evaluate(d);this.separateAxes?(this._temp.x*=f*this.strengthXMultiplier,this._temp.y*=f*this.strengthYMultiplier,this._temp.z*=f*this.strengthZMultiplier):(this.strengthX&&(f*=this.strengthX.evaluate(d)*1.5),this._temp.multiplyScalar(f)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z}}re([x()],Ri.prototype,"damping",2);re([x()],Ri.prototype,"enabled",2);re([x()],Ri.prototype,"frequency",2);re([x()],Ri.prototype,"octaveCount",2);re([x()],Ri.prototype,"octaveMultiplier",2);re([x()],Ri.prototype,"octaveScale",2);re([x(ft)],Ri.prototype,"positionAmount",2);re([x()],Ri.prototype,"quality",2);re([x(ft)],Ri.prototype,"remap",2);re([x()],Ri.prototype,"remapEnabled",2);re([x()],Ri.prototype,"remapMultiplier",2);re([x(ft)],Ri.prototype,"remapX",2);re([x()],Ri.prototype,"remapXMultiplier",2);re([x(ft)],Ri.prototype,"remapY",2);re([x()],Ri.prototype,"remapYMultiplier",2);re([x(ft)],Ri.prototype,"remapZ",2);re([x()],Ri.prototype,"remapZMultiplier",2);re([x()],Ri.prototype,"scrollSpeedMultiplier",2);re([x()],Ri.prototype,"separateAxes",2);re([x()],Ri.prototype,"strengthMultiplier",2);re([x(ft)],Ri.prototype,"strengthX",2);re([x()],Ri.prototype,"strengthXMultiplier",2);re([x(ft)],Ri.prototype,"strengthY",2);re([x()],Ri.prototype,"strengthYMultiplier",2);re([x(ft)],Ri.prototype,"strengthZ",2);re([x()],Ri.prototype,"strengthZMultiplier",2);class on{constructor(){u(this,"enabled");u(this,"attachRibbonToTransform",!1);u(this,"colorOverLifetime");u(this,"colorOverTrail");u(this,"dieWithParticles",!0);u(this,"inheritParticleColor",!0);u(this,"lifetime");u(this,"lifetimeMultiplier");u(this,"minVertexDistance",.2);u(this,"mode",0);u(this,"ratio",1);u(this,"ribbonCount",1);u(this,"shadowBias",0);u(this,"sizeAffectsLifetime",!1);u(this,"sizeAffectsWidth",!1);u(this,"splitSubEmitterRibbons",!1);u(this,"textureMode",0);u(this,"widthOverTrail");u(this,"widthOverTrailMultiplier");u(this,"worldSpace",!1)}getWidth(e,t,i,s){const r=this.widthOverTrail.evaluate(i,s);return e*=r,e}getColor(e,t,i){const s=this.colorOverTrail.evaluate(i),r=this.colorOverLifetime.evaluate(t);e.x*=s.r*r.r,e.y*=s.g*r.g,e.z*=s.b*r.b,e.w*=s.alpha*r.alpha}}re([x()],on.prototype,"enabled",2);re([x()],on.prototype,"attachRibbonToTransform",2);re([x(Jr)],on.prototype,"colorOverLifetime",2);re([x(Jr)],on.prototype,"colorOverTrail",2);re([x()],on.prototype,"dieWithParticles",2);re([x()],on.prototype,"inheritParticleColor",2);re([x(ft)],on.prototype,"lifetime",2);re([x()],on.prototype,"lifetimeMultiplier",2);re([x()],on.prototype,"minVertexDistance",2);re([x()],on.prototype,"mode",2);re([x()],on.prototype,"ratio",2);re([x()],on.prototype,"ribbonCount",2);re([x()],on.prototype,"shadowBias",2);re([x()],on.prototype,"sizeAffectsLifetime",2);re([x()],on.prototype,"sizeAffectsWidth",2);re([x()],on.prototype,"splitSubEmitterRibbons",2);re([x()],on.prototype,"textureMode",2);re([x(ft)],on.prototype,"widthOverTrail",2);re([x()],on.prototype,"widthOverTrailMultiplier",2);re([x()],on.prototype,"worldSpace",2);class vn{constructor(){u(this,"enabled");u(this,"space",0);u(this,"orbitalX");u(this,"orbitalY");u(this,"orbitalZ");u(this,"orbitalXMultiplier");u(this,"orbitalYMultiplier");u(this,"orbitalZMultiplier");u(this,"orbitalOffsetX");u(this,"orbitalOffsetY");u(this,"orbitalOffsetZ");u(this,"speedModifier");u(this,"speedModifierMultiplier");u(this,"x");u(this,"xMultiplier");u(this,"y");u(this,"yMultiplier");u(this,"z");u(this,"zMultiplier");u(this,"_system");u(this,"_temp",new w);u(this,"_temp2",new w);u(this,"_temp3",new w);u(this,"_hasOrbital",!1);u(this,"_index",0);u(this,"_orbitalMatrix",new Se)}update(e){this._system=e}init(e){this._index==0&&(e.debug=!0),this._index+=1,e.orbitx=this.orbitalX.evaluate(Math.random()),e.orbity=this.orbitalY.evaluate(Math.random()),e.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=e.orbitx!=0||e.orbity!=0||e.orbitz!=0}apply(e,t,i,s,r,o,a){var p;if(!this.enabled)return;const c=o/a,l=this.speedModifier.evaluate(c)*this.speedModifierMultiplier,h=this.x.evaluate(c),d=this.y.evaluate(c),f=this.z.evaluate(c);if(this._temp.set(-h,d,f),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&((p=this._system)==null?void 0:p.worldPos)){const g=this._temp2.set(i.x,i.y,i.z),y=this.orbitalXMultiplier,v=this.orbitalYMultiplier,A=this.orbitalZMultiplier,_=l*Math.PI*2*10,b=Math.cos(_*y),C=Math.sin(_*y),E=Math.cos(_*v),T=Math.sin(_*v),I=Math.cos(_*A),S=Math.sin(_*A),M=g.x*(E*I)+g.y*(E*S)+g.z*-T,D=g.x*(C*T*I-b*S)+g.y*(C*T*S+b*I)+g.z*(C*E),G=g.x*(b*T*I+C*S)+g.y*(b*T*S-C*I)+g.z*(b*E),Q=this._temp3.set(g.x-M,g.y-D,g.z-G);Q.normalize(),Q.multiplyScalar(.2/r*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),s.x+=Q.x,s.y+=Q.y,s.z+=Q.z}s.x+=this._temp.x,s.y+=this._temp.y,s.z+=this._temp.z,s.x*=l,s.y*=l,s.z*=l}}re([x()],vn.prototype,"enabled",2);re([x()],vn.prototype,"space",2);re([x(ft)],vn.prototype,"orbitalX",2);re([x(ft)],vn.prototype,"orbitalY",2);re([x(ft)],vn.prototype,"orbitalZ",2);re([x()],vn.prototype,"orbitalXMultiplier",2);re([x()],vn.prototype,"orbitalYMultiplier",2);re([x()],vn.prototype,"orbitalZMultiplier",2);re([x()],vn.prototype,"orbitalOffsetX",2);re([x()],vn.prototype,"orbitalOffsetY",2);re([x()],vn.prototype,"orbitalOffsetZ",2);re([x(ft)],vn.prototype,"speedModifier",2);re([x()],vn.prototype,"speedModifierMultiplier",2);re([x(ft)],vn.prototype,"x",2);re([x()],vn.prototype,"xMultiplier",2);re([x(ft)],vn.prototype,"y",2);re([x()],vn.prototype,"yMultiplier",2);re([x(ft)],vn.prototype,"z",2);re([x()],vn.prototype,"zMultiplier",2);class Ws{constructor(){u(this,"animation");u(this,"enabled");u(this,"cycleCount");u(this,"frameOverTime");u(this,"frameOverTimeMultiplier");u(this,"numTilesX");u(this,"numTilesY");u(this,"startFrame");u(this,"startFrameMultiplier");u(this,"rowMode");u(this,"rowIndex");u(this,"spriteCount");u(this,"timeMode")}sampleOnceAtStart(){if(this.timeMode===0)switch(this.frameOverTime.mode){case 0:case 3:case 2:case 1:return!0}return!1}getStartIndex(){return this.sampleOnceAtStart()?Math.random()*(this.numTilesX*this.numTilesY):0}evaluate(e){if(!this.sampleOnceAtStart())return this.getIndex(e)}getIndex(e){const t=this.numTilesX*this.numTilesY;e=e*this.cycleCount;let i=this.frameOverTime.evaluate(e%1);return i*=this.frameOverTimeMultiplier,i*=t,i=i%t,i=Math.floor(i),i}}re([x()],Ws.prototype,"animation",2);re([x()],Ws.prototype,"enabled",2);re([x()],Ws.prototype,"cycleCount",2);re([x(ft)],Ws.prototype,"frameOverTime",2);re([x()],Ws.prototype,"frameOverTimeMultiplier",2);re([x()],Ws.prototype,"numTilesX",2);re([x()],Ws.prototype,"numTilesY",2);re([x(ft)],Ws.prototype,"startFrame",2);re([x()],Ws.prototype,"startFrameMultiplier",2);re([x()],Ws.prototype,"rowMode",2);re([x()],Ws.prototype,"rowIndex",2);re([x()],Ws.prototype,"spriteCount",2);re([x()],Ws.prototype,"timeMode",2);class ca{constructor(){u(this,"enabled");u(this,"separateAxes");u(this,"x");u(this,"xMultiplier");u(this,"y");u(this,"yMultiplier");u(this,"z");u(this,"zMultiplier")}evaluate(e,t){return this.enabled?this.separateAxes?0:this.z.evaluate(e,t)*-1:0}}re([x()],ca.prototype,"enabled",2);re([x()],ca.prototype,"separateAxes",2);re([x(ft)],ca.prototype,"x",2);re([x()],ca.prototype,"xMultiplier",2);re([x(ft)],ca.prototype,"y",2);re([x()],ca.prototype,"yMultiplier",2);re([x(ft)],ca.prototype,"z",2);re([x()],ca.prototype,"zMultiplier",2);class Eo{constructor(){u(this,"enabled");u(this,"range");u(this,"separateAxes");u(this,"x");u(this,"xMultiplier");u(this,"y");u(this,"yMultiplier");u(this,"z");u(this,"zMultiplier")}evaluate(e,t){if(!this.enabled)return 0;if(!this.separateAxes){const i=rt.lerp(this.range.x,this.range.y,t);return this.z.evaluate(i)*-1}return 0}}re([x()],Eo.prototype,"enabled",2);re([x()],Eo.prototype,"range",2);re([x()],Eo.prototype,"separateAxes",2);re([x(ft)],Eo.prototype,"x",2);re([x()],Eo.prototype,"xMultiplier",2);re([x(ft)],Eo.prototype,"y",2);re([x()],Eo.prototype,"yMultiplier",2);re([x(ft)],Eo.prototype,"z",2);re([x()],Eo.prototype,"zMultiplier",2);class qn{constructor(){u(this,"enabled");u(this,"dampen");u(this,"drag");u(this,"dragMultiplier");u(this,"limit");u(this,"limitMultiplier");u(this,"separateAxes");u(this,"limitX");u(this,"limitXMultiplier");u(this,"limitY");u(this,"limitYMultiplier");u(this,"limitZ");u(this,"limitZMultiplier");u(this,"multiplyDragByParticleSize",!1);u(this,"multiplyDragByParticleVelocity",!1);u(this,"space");u(this,"_temp",new w);u(this,"_temp2",new w)}apply(e,t,i,s,r,o,a){if(this.enabled){const c=this.limit.evaluate(r)*this.limitMultiplier;if(t.length()>c){this._temp.copy(t).normalize().multiplyScalar(c);const h=this.dampen*.5;t.x=rt.lerp(t.x,this._temp.x,h),t.y=rt.lerp(t.y,this._temp.y,h),t.z=rt.lerp(t.z,this._temp.z,h),i.x=rt.lerp(i.x,this._temp.x,h),i.y=rt.lerp(i.y,this._temp.y,h),i.z=rt.lerp(i.z,this._temp.z,h)}}}}re([x()],qn.prototype,"enabled",2);re([x()],qn.prototype,"dampen",2);re([x(ft)],qn.prototype,"drag",2);re([x()],qn.prototype,"dragMultiplier",2);re([x(ft)],qn.prototype,"limit",2);re([x()],qn.prototype,"limitMultiplier",2);re([x()],qn.prototype,"separateAxes",2);re([x(ft)],qn.prototype,"limitX",2);re([x()],qn.prototype,"limitXMultiplier",2);re([x(ft)],qn.prototype,"limitY",2);re([x()],qn.prototype,"limitYMultiplier",2);re([x(ft)],qn.prototype,"limitZ",2);re([x()],qn.prototype,"limitZMultiplier",2);re([x()],qn.prototype,"multiplyDragByParticleSize",2);re([x()],qn.prototype,"multiplyDragByParticleVelocity",2);re([x()],qn.prototype,"space",2);const $H=class{constructor(){u(this,"enabled");u(this,"curve");u(this,"curveMultiplier");u(this,"mode");u(this,"system");u(this,"_temp",new w);u(this,"_firstUpdate",!0);u(this,"_frames",0)}clone(){var e;const n=new $H;return n.enabled=this.enabled,n.curve=(e=this.curve)==null?void 0:e.clone(),n.curveMultiplier=this.curveMultiplier,n.mode=this.mode,n}get _lastWorldPosition(){return this.system._iv_lastWorldPosition||(this.system._iv_lastWorldPosition=new w),this.system._iv_lastWorldPosition}get _velocity(){return this.system._iv_velocity||(this.system._iv_velocity=new w),this.system._iv_velocity}awake(n){this.system=n,this.reset()}reset(){this._firstUpdate=!0}update(n){this.enabled&&this.system.worldspace!==!1&&(this._firstUpdate?(this._firstUpdate=!1,this._velocity.set(0,0,0),this._lastWorldPosition.copy(this.system.worldPos)):this._lastWorldPosition&&(this._velocity.copy(this.system.worldPos).sub(this._lastWorldPosition).multiplyScalar(1/this.system.deltaTime),this._lastWorldPosition.copy(this.system.worldPos)))}applyInitial(n){if(this.enabled&&this.system.worldspace!==!1&&this.mode===0){const e=this.curve.evaluate(Math.random(),Math.random());this._temp.copy(this._velocity).multiplyScalar(e),n.add(this._temp)}}applyCurrent(n,e,t){if(this.enabled&&this.system&&this.system.worldspace!==!1&&this.mode===1){const i=this.curve.evaluate(e,t);this._temp.copy(this._velocity).multiplyScalar(i),n.add(this._temp)}}};let tu=$H;re([x()],tu.prototype,"enabled",2);re([x(ft)],tu.prototype,"curve",2);re([x()],tu.prototype,"curveMultiplier",2);re([x()],tu.prototype,"mode",2);class Rr{constructor(){u(this,"enabled");u(this,"range");u(this,"separateAxes");u(this,"size");u(this,"sizeMultiplier");u(this,"x");u(this,"xMultiplier");u(this,"y");u(this,"yMultiplier");u(this,"z");u(this,"zMultiplier")}evaluate(e,t,i,s){const r=e.length(),o=rt.remap(r,this.range.x,this.range.y,0,1),a=this.size.evaluate(o,i);return s*a}}re([x()],Rr.prototype,"enabled",2);re([x(ie)],Rr.prototype,"range",2);re([x()],Rr.prototype,"separateAxes",2);re([x(ft)],Rr.prototype,"size",2);re([x()],Rr.prototype,"sizeMultiplier",2);re([x(ft)],Rr.prototype,"x",2);re([x()],Rr.prototype,"xMultiplier",2);re([x(ft)],Rr.prototype,"y",2);re([x()],Rr.prototype,"yMultiplier",2);re([x(ft)],Rr.prototype,"z",2);re([x()],Rr.prototype,"zMultiplier",2);class Nd{constructor(){u(this,"enabled");u(this,"range");u(this,"color")}evaluate(e,t,i){const s=e.length(),r=rt.remap(s,this.range.x,this.range.y,0,1),o=this.color.evaluate(r,t);i.x*=o.r,i.y*=o.g,i.z*=o.b,i.w*=o.alpha}}re([x()],Nd.prototype,"enabled",2);re([x(ie)],Nd.prototype,"range",2);re([x(Jr)],Nd.prototype,"color",2);const Lre={name:"HorizontalBlurShader",uniforms:{tDiffuse:{value:null},h:{value:1/512}},vertexShader:`
5411
5413
 
5412
5414
  varying vec2 vUv;
5413
5415