@needle-tools/engine 3.35.1-beta โ†’ 3.35.1-beta.1

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.
@@ -4341,7 +4341,7 @@ void main() {
4341
4341
  `;s+=i(o);const n=Object.keys(I);let C="";for(let a=0;a<n.length;a++){const B=n[a],Q=I[B];if(el.has(Q)){C+="";continue}el.set(Q,!0),C+=B+":"+t(Q,o+1),a<n.length-1&&(C+=", "),C.length>=60&&(C+=`
4342
4342
  `,C+=i(o),s+=C,C="")}return s+=C,s+=`
4343
4343
  }`,s}return I}function i(I){let o="";for(let s=0;s<I;s++)o+=" ";return o}}const R9=IA("nodevlogs");function Gi(g,A=ho.Log){an(A,g)}function Ii(g){Gi(g,ho.Warn)}function I2(g){Gi(g,ho.Error)}let _G;function pe(){return R9?!1:_G!==void 0?_G:ZI()}function U9(g){_G=g}const Kr=new LB,gI=new y,Ia=new y,ti=new kA,fq={X:new y(1,0,0),Y:new y(0,1,0),Z:new y(0,0,1)},hm={type:"change"},Dq={type:"mouseDown"},yq={type:"mouseUp",mode:null},wq={type:"objectChange"};class N9 extends pA{constructor(A,e){super(),e===void 0&&(console.warn('THREE.TransformControls: The second parameter "domElement" is now mandatory.'),e=document),this.isTransformControls=!0,this.visible=!1,this.domElement=e,this.domElement.style.touchAction="none";const t=new LU;this._gizmo=t,this.add(t);const i=new v9;this._plane=i,this.add(i);const I=this;function o(p,u){let f=u;Object.defineProperty(I,p,{get:function(){return f!==void 0?f:u},set:function(m){f!==m&&(f=m,i[p]=m,t[p]=m,I.dispatchEvent({type:p+"-changed",value:m}),I.dispatchEvent(hm))}}),I[p]=u,i[p]=u,t[p]=u}o("camera",A),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 s=new y,n=new y,C=new kA,a=new kA,B=new y,Q=new kA,E=new y,c=new y,d=new y,h=0,l=new y;o("worldPosition",s),o("worldPositionStart",n),o("worldQuaternion",C),o("worldQuaternionStart",a),o("cameraPosition",B),o("cameraQuaternion",Q),o("pointStart",E),o("pointEnd",c),o("rotationAxis",d),o("rotationAngle",h),o("eye",l),this._offset=new y,this._startNorm=new y,this._endNorm=new y,this._cameraScale=new y,this._parentPosition=new y,this._parentQuaternion=new kA,this._parentQuaternionInv=new kA,this._parentScale=new y,this._worldScaleStart=new y,this._worldQuaternionInv=new kA,this._worldScale=new y,this._positionStart=new y,this._quaternionStart=new kA,this._scaleStart=new y,this._getPointer=F9.bind(this),this._onPointerDown=J9.bind(this),this._onPointerHover=K9.bind(this),this._onPointerMove=q9.bind(this),this._onPointerUp=b9.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(A){if(this.object===void 0||this.dragging===!0)return;A!==null&&Kr.setFromCamera(A,this.camera);const e=dm(this._gizmo.picker[this.mode],Kr);e?this.axis=e.object.name:this.axis=null}pointerDown(A){if(!(this.object===void 0||this.dragging===!0||A!=null&&A.button!==0)&&this.axis!==null){A!==null&&Kr.setFromCamera(A,this.camera);const e=dm(this._plane,Kr,!0);e&&(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(e.point).sub(this.worldPositionStart)),this.dragging=!0,Dq.mode=this.mode,this.dispatchEvent(Dq)}}pointerMove(A){const e=this.axis,t=this.mode,i=this.object;let I=this.space;if(t==="scale"?I="local":(e==="E"||e==="XYZE"||e==="XYZ")&&(I="world"),i===void 0||e===null||this.dragging===!1||A!==null&&A.button!==-1)return;A!==null&&Kr.setFromCamera(A,this.camera);const o=dm(this._plane,Kr,!0);if(o){if(this.pointEnd.copy(o.point).sub(this.worldPositionStart),t==="translate")this._offset.copy(this.pointEnd).sub(this.pointStart),I==="local"&&e!=="XYZ"&&this._offset.applyQuaternion(this._worldQuaternionInv),e.indexOf("X")===-1&&(this._offset.x=0),e.indexOf("Y")===-1&&(this._offset.y=0),e.indexOf("Z")===-1&&(this._offset.z=0),I==="local"&&e!=="XYZ"?this._offset.applyQuaternion(this._quaternionStart).divide(this._parentScale):this._offset.applyQuaternion(this._parentQuaternionInv).divide(this._parentScale),i.position.copy(this._offset).add(this._positionStart),this.translationSnap&&(I==="local"&&(i.position.applyQuaternion(ti.copy(this._quaternionStart).invert()),e.search("X")!==-1&&(i.position.x=Math.round(i.position.x/this.translationSnap)*this.translationSnap),e.search("Y")!==-1&&(i.position.y=Math.round(i.position.y/this.translationSnap)*this.translationSnap),e.search("Z")!==-1&&(i.position.z=Math.round(i.position.z/this.translationSnap)*this.translationSnap),i.position.applyQuaternion(this._quaternionStart)),I==="world"&&(i.parent&&i.position.add(gI.setFromMatrixPosition(i.parent.matrixWorld)),e.search("X")!==-1&&(i.position.x=Math.round(i.position.x/this.translationSnap)*this.translationSnap),e.search("Y")!==-1&&(i.position.y=Math.round(i.position.y/this.translationSnap)*this.translationSnap),e.search("Z")!==-1&&(i.position.z=Math.round(i.position.z/this.translationSnap)*this.translationSnap),i.parent&&i.position.sub(gI.setFromMatrixPosition(i.parent.matrixWorld))));else if(t==="scale"){if(e.search("XYZ")!==-1){let s=this.pointEnd.length()/this.pointStart.length();this.pointEnd.dot(this.pointStart)<0&&(s*=-1),Ia.set(s,s,s)}else gI.copy(this.pointStart),Ia.copy(this.pointEnd),gI.applyQuaternion(this._worldQuaternionInv),Ia.applyQuaternion(this._worldQuaternionInv),Ia.divide(gI),e.search("X")===-1&&(Ia.x=1),e.search("Y")===-1&&(Ia.y=1),e.search("Z")===-1&&(Ia.z=1);i.scale.copy(this._scaleStart).multiply(Ia),this.scaleSnap&&(e.search("X")!==-1&&(i.scale.x=Math.round(i.scale.x/this.scaleSnap)*this.scaleSnap||this.scaleSnap),e.search("Y")!==-1&&(i.scale.y=Math.round(i.scale.y/this.scaleSnap)*this.scaleSnap||this.scaleSnap),e.search("Z")!==-1&&(i.scale.z=Math.round(i.scale.z/this.scaleSnap)*this.scaleSnap||this.scaleSnap))}else if(t==="rotate"){this._offset.copy(this.pointEnd).sub(this.pointStart);const s=20/this.worldPosition.distanceTo(gI.setFromMatrixPosition(this.camera.matrixWorld));let n=!1;e==="XYZE"?(this.rotationAxis.copy(this._offset).cross(this.eye).normalize(),this.rotationAngle=this._offset.dot(gI.copy(this.rotationAxis).cross(this.eye))*s):(e==="X"||e==="Y"||e==="Z")&&(this.rotationAxis.copy(fq[e]),gI.copy(fq[e]),I==="local"&&gI.applyQuaternion(this.worldQuaternion),gI.cross(this.eye),gI.length()===0?n=!0:this.rotationAngle=this._offset.dot(gI.normalize())*s),(e==="E"||n)&&(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),I==="local"&&e!=="E"&&e!=="XYZE"?(i.quaternion.copy(this._quaternionStart),i.quaternion.multiply(ti.setFromAxisAngle(this.rotationAxis,this.rotationAngle)).normalize()):(this.rotationAxis.applyQuaternion(this._parentQuaternionInv),i.quaternion.copy(ti.setFromAxisAngle(this.rotationAxis,this.rotationAngle)),i.quaternion.multiply(this._quaternionStart).normalize())}this.dispatchEvent(hm),this.dispatchEvent(wq)}}pointerUp(A){A!==null&&A.button!==0||(this.dragging&&this.axis!==null&&(yq.mode=this.mode,this.dispatchEvent(yq)),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(A){A.geometry&&A.geometry.dispose(),A.material&&A.material.dispose()})}attach(A){return this.object=A,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(hm),this.dispatchEvent(wq),this.pointStart.copy(this.pointEnd))}getRaycaster(){return Kr}getMode(){return this.mode}setMode(A){this.mode=A}setTranslationSnap(A){this.translationSnap=A}setRotationSnap(A){this.rotationSnap=A}setScaleSnap(A){this.scaleSnap=A}setSize(A){this.size=A}setSpace(A){this.space=A}}function F9(g){if(this.domElement.ownerDocument.pointerLockElement)return{x:0,y:0,button:g.button};{const A=this.domElement.getBoundingClientRect();return{x:(g.clientX-A.left)/A.width*2-1,y:-(g.clientY-A.top)/A.height*2+1,button:g.button}}}function K9(g){if(this.enabled)switch(g.pointerType){case"mouse":case"pen":this.pointerHover(this._getPointer(g));break}}function J9(g){this.enabled&&(document.pointerLockElement||this.domElement.setPointerCapture(g.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.pointerHover(this._getPointer(g)),this.pointerDown(this._getPointer(g)))}function q9(g){this.enabled&&this.pointerMove(this._getPointer(g))}function b9(g){this.enabled&&(this.domElement.releasePointerCapture(g.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.pointerUp(this._getPointer(g)))}function dm(g,A,e){const t=A.intersectObject(g,!0);for(let i=0;i<t.length;i++)if(t[i].object.visible||e)return t[i];return!1}const zp=new jt,bt=new y(0,1,0),Sq=new y(0,0,0),mq=new MA,Vp=new kA,Xf=new kA,Ts=new y,Mq=new MA,Nl=new y(1,0,0),Vr=new y(0,1,0),Fl=new y(0,0,1),Zp=new y,tl=new y,il=new y;class LU extends pA{constructor(){super(),this.isTransformControlsGizmo=!0,this.type="TransformControlsGizmo";const A=new at({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),e=new Yi({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),t=A.clone();t.opacity=.15;const i=e.clone();i.opacity=.5;const I=A.clone();I.color.setHex(16711680);const o=A.clone();o.color.setHex(65280);const s=A.clone();s.color.setHex(255);const n=A.clone();n.color.setHex(16711680),n.opacity=.5;const C=A.clone();C.color.setHex(65280),C.opacity=.5;const a=A.clone();a.color.setHex(255),a.opacity=.5;const B=A.clone();B.opacity=.25;const Q=A.clone();Q.color.setHex(16776960),Q.opacity=.25,A.clone().color.setHex(16776960);const c=A.clone();c.color.setHex(7895160);const d=new Ki(0,.04,.1,12);d.translate(0,.05,0);const h=new Tt(.08,.08,.08);h.translate(0,.04,0);const l=new we;l.setAttribute("position",new Qe([0,0,0,1,0,0],3));const p=new Ki(.0075,.0075,.5,3);p.translate(0,.25,0);function u(O,q){const b=new aC(O,.0075,3,64,q*Math.PI*2);return b.rotateY(Math.PI/2),b.rotateX(Math.PI/2),b}function f(){const O=new we;return O.setAttribute("position",new Qe([0,0,0,1,1,1],3)),O}const m={X:[[new dA(d,I),[.5,0,0],[0,0,-Math.PI/2]],[new dA(d,I),[-.5,0,0],[0,0,Math.PI/2]],[new dA(p,I),[0,0,0],[0,0,-Math.PI/2]]],Y:[[new dA(d,o),[0,.5,0]],[new dA(d,o),[0,-.5,0],[Math.PI,0,0]],[new dA(p,o)]],Z:[[new dA(d,s),[0,0,.5],[Math.PI/2,0,0]],[new dA(d,s),[0,0,-.5],[-Math.PI/2,0,0]],[new dA(p,s),null,[Math.PI/2,0,0]]],XYZ:[[new dA(new hC(.1,0),B.clone()),[0,0,0]]],XY:[[new dA(new Tt(.15,.15,.01),a.clone()),[.15,.15,0]]],YZ:[[new dA(new Tt(.15,.15,.01),n.clone()),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new dA(new Tt(.15,.15,.01),C.clone()),[.15,0,.15],[-Math.PI/2,0,0]]]},M={X:[[new dA(new Ki(.2,0,.6,4),t),[.3,0,0],[0,0,-Math.PI/2]],[new dA(new Ki(.2,0,.6,4),t),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new dA(new Ki(.2,0,.6,4),t),[0,.3,0]],[new dA(new Ki(.2,0,.6,4),t),[0,-.3,0],[0,0,Math.PI]]],Z:[[new dA(new Ki(.2,0,.6,4),t),[0,0,.3],[Math.PI/2,0,0]],[new dA(new Ki(.2,0,.6,4),t),[0,0,-.3],[-Math.PI/2,0,0]]],XYZ:[[new dA(new hC(.2,0),t)]],XY:[[new dA(new Tt(.2,.2,.01),t),[.15,.15,0]]],YZ:[[new dA(new Tt(.2,.2,.01),t),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new dA(new Tt(.2,.2,.01),t),[.15,0,.15],[-Math.PI/2,0,0]]]},k={START:[[new dA(new hC(.01,2),i),null,null,null,"helper"]],END:[[new dA(new hC(.01,2),i),null,null,null,"helper"]],DELTA:[[new bi(f(),i),null,null,null,"helper"]],X:[[new bi(l,i.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new bi(l,i.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new bi(l,i.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},S={XYZE:[[new dA(u(.5,1),c),null,[0,Math.PI/2,0]]],X:[[new dA(u(.5,.5),I)]],Y:[[new dA(u(.5,.5),o),null,[0,0,-Math.PI/2]]],Z:[[new dA(u(.5,.5),s),null,[0,Math.PI/2,0]]],E:[[new dA(u(.75,1),Q),null,[0,Math.PI/2,0]]]},F={AXIS:[[new bi(l,i.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]]},w={XYZE:[[new dA(new qs(.25,10,8),t)]],X:[[new dA(new aC(.5,.1,4,24),t),[0,0,0],[0,-Math.PI/2,-Math.PI/2]]],Y:[[new dA(new aC(.5,.1,4,24),t),[0,0,0],[Math.PI/2,0,0]]],Z:[[new dA(new aC(.5,.1,4,24),t),[0,0,0],[0,0,-Math.PI/2]]],E:[[new dA(new aC(.75,.1,2,24),t)]]},R={X:[[new dA(h,I),[.5,0,0],[0,0,-Math.PI/2]],[new dA(p,I),[0,0,0],[0,0,-Math.PI/2]],[new dA(h,I),[-.5,0,0],[0,0,Math.PI/2]]],Y:[[new dA(h,o),[0,.5,0]],[new dA(p,o)],[new dA(h,o),[0,-.5,0],[0,0,Math.PI]]],Z:[[new dA(h,s),[0,0,.5],[Math.PI/2,0,0]],[new dA(p,s),[0,0,0],[Math.PI/2,0,0]],[new dA(h,s),[0,0,-.5],[-Math.PI/2,0,0]]],XY:[[new dA(new Tt(.15,.15,.01),a),[.15,.15,0]]],YZ:[[new dA(new Tt(.15,.15,.01),n),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new dA(new Tt(.15,.15,.01),C),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new dA(new Tt(.1,.1,.1),B.clone())]]},H={X:[[new dA(new Ki(.2,0,.6,4),t),[.3,0,0],[0,0,-Math.PI/2]],[new dA(new Ki(.2,0,.6,4),t),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new dA(new Ki(.2,0,.6,4),t),[0,.3,0]],[new dA(new Ki(.2,0,.6,4),t),[0,-.3,0],[0,0,Math.PI]]],Z:[[new dA(new Ki(.2,0,.6,4),t),[0,0,.3],[Math.PI/2,0,0]],[new dA(new Ki(.2,0,.6,4),t),[0,0,-.3],[-Math.PI/2,0,0]]],XY:[[new dA(new Tt(.2,.2,.01),t),[.15,.15,0]]],YZ:[[new dA(new Tt(.2,.2,.01),t),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new dA(new Tt(.2,.2,.01),t),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new dA(new Tt(.2,.2,.2),t),[0,0,0]]]},Y={X:[[new bi(l,i.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new bi(l,i.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new bi(l,i.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]};function J(O){const q=new pA;for(const b in O)for(let T=O[b].length;T--;){const V=O[b][T][0].clone(),AA=O[b][T][1],sA=O[b][T][2],QA=O[b][T][3],FA=O[b][T][4];V.name=b,V.tag=FA,AA&&V.position.set(AA[0],AA[1],AA[2]),sA&&V.rotation.set(sA[0],sA[1],sA[2]),QA&&V.scale.set(QA[0],QA[1],QA[2]),V.updateMatrix();const iA=V.geometry.clone();iA.applyMatrix4(V.matrix),V.geometry=iA,V.renderOrder=1/0,V.position.set(0,0,0),V.rotation.set(0,0,0),V.scale.set(1,1,1),q.add(V)}return q}this.gizmo={},this.picker={},this.helper={},this.add(this.gizmo.translate=J(m)),this.add(this.gizmo.rotate=J(S)),this.add(this.gizmo.scale=J(R)),this.add(this.picker.translate=J(M)),this.add(this.picker.rotate=J(w)),this.add(this.picker.scale=J(H)),this.add(this.helper.translate=J(k)),this.add(this.helper.rotate=J(F)),this.add(this.helper.scale=J(Y)),this.picker.translate.visible=!1,this.picker.rotate.visible=!1,this.picker.scale.visible=!1}updateMatrixWorld(A){const t=(this.mode==="scale"?"local":this.space)==="local"?this.worldQuaternion:Xf;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 i=[];i=i.concat(this.picker[this.mode].children),i=i.concat(this.gizmo[this.mode].children),i=i.concat(this.helper[this.mode].children);for(let I=0;I<i.length;I++){const o=i[I];o.visible=!0,o.rotation.set(0,0,0),o.position.copy(this.worldPosition);let s;if(this.camera.isOrthographicCamera?s=(this.camera.top-this.camera.bottom)/this.camera.zoom:s=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(s*this.size/4),o.tag==="helper"){o.visible=!1,o.name==="AXIS"?(o.visible=!!this.axis,this.axis==="X"&&(ti.setFromEuler(zp.set(0,0,0)),o.quaternion.copy(t).multiply(ti),Math.abs(bt.copy(Nl).applyQuaternion(t).dot(this.eye))>.9&&(o.visible=!1)),this.axis==="Y"&&(ti.setFromEuler(zp.set(0,0,Math.PI/2)),o.quaternion.copy(t).multiply(ti),Math.abs(bt.copy(Vr).applyQuaternion(t).dot(this.eye))>.9&&(o.visible=!1)),this.axis==="Z"&&(ti.setFromEuler(zp.set(0,Math.PI/2,0)),o.quaternion.copy(t).multiply(ti),Math.abs(bt.copy(Fl).applyQuaternion(t).dot(this.eye))>.9&&(o.visible=!1)),this.axis==="XYZE"&&(ti.setFromEuler(zp.set(0,Math.PI/2,0)),bt.copy(this.rotationAxis),o.quaternion.setFromRotationMatrix(mq.lookAt(Sq,bt,Vr)),o.quaternion.multiply(ti),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),gI.set(1e-10,1e-10,1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1),gI.applyQuaternion(this.worldQuaternionStart.clone().invert()),o.scale.copy(gI),o.visible=this.dragging):(o.quaternion.copy(t),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(t),this.mode==="translate"||this.mode==="scale"?(o.name==="X"&&Math.abs(bt.copy(Nl).applyQuaternion(t).dot(this.eye))>.99&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="Y"&&Math.abs(bt.copy(Vr).applyQuaternion(t).dot(this.eye))>.99&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="Z"&&Math.abs(bt.copy(Fl).applyQuaternion(t).dot(this.eye))>.99&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="XY"&&Math.abs(bt.copy(Fl).applyQuaternion(t).dot(this.eye))<.2&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="YZ"&&Math.abs(bt.copy(Nl).applyQuaternion(t).dot(this.eye))<.2&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="XZ"&&Math.abs(bt.copy(Vr).applyQuaternion(t).dot(this.eye))<.2&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1)):this.mode==="rotate"&&(Vp.copy(t),bt.copy(this.eye).applyQuaternion(ti.copy(t).invert()),o.name.search("E")!==-1&&o.quaternion.setFromRotationMatrix(mq.lookAt(this.eye,Sq,Vr)),o.name==="X"&&(ti.setFromAxisAngle(Nl,Math.atan2(-bt.y,bt.z)),ti.multiplyQuaternions(Vp,ti),o.quaternion.copy(ti)),o.name==="Y"&&(ti.setFromAxisAngle(Vr,Math.atan2(bt.x,bt.z)),ti.multiplyQuaternions(Vp,ti),o.quaternion.copy(ti)),o.name==="Z"&&(ti.setFromAxisAngle(Fl,Math.atan2(bt.y,bt.x)),ti.multiplyQuaternions(Vp,ti),o.quaternion.copy(ti))),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(n){return o.name===n}))&&(o.material.color.setHex(16776960),o.material.opacity=1)}super.updateMatrixWorld(A)}}class v9 extends dA{constructor(){super(new Zi(1e5,1e5,2,2),new at({visible:!1,wireframe:!0,side:ut,transparent:!0,opacity:.1,toneMapped:!1})),this.isTransformControlsPlane=!0,this.type="TransformControlsPlane"}updateMatrixWorld(A){let e=this.space;switch(this.position.copy(this.worldPosition),this.mode==="scale"&&(e="local"),Zp.copy(Nl).applyQuaternion(e==="local"?this.worldQuaternion:Xf),tl.copy(Vr).applyQuaternion(e==="local"?this.worldQuaternion:Xf),il.copy(Fl).applyQuaternion(e==="local"?this.worldQuaternion:Xf),bt.copy(tl),this.mode){case"translate":case"scale":switch(this.axis){case"X":bt.copy(this.eye).cross(Zp),Ts.copy(Zp).cross(bt);break;case"Y":bt.copy(this.eye).cross(tl),Ts.copy(tl).cross(bt);break;case"Z":bt.copy(this.eye).cross(il),Ts.copy(il).cross(bt);break;case"XY":Ts.copy(il);break;case"YZ":Ts.copy(Zp);break;case"XZ":bt.copy(il),Ts.copy(tl);break;case"XYZ":case"E":Ts.set(0,0,0);break}break;case"rotate":default:Ts.set(0,0,0)}Ts.length()===0?this.quaternion.copy(this.cameraQuaternion):(Mq.lookAt(gI.set(0,0,0),Ts,bt),this.quaternion.setFromRotationMatrix(Mq)),super.updateMatrixWorld(A)}}const L9=IA("debugpatch");function Tw(g,A,e,t){const i=L9===A;if(!e&&!t)return;const I=A+"___needle";Y9(g,A,e,t);const o=Object.getOwnPropertyDescriptor(g,A),s=g[A];i&&console.log("Patch",g.constructor.name,A,o,s),o?(i&&console.log("Apply patch with existing descriptor",g.constructor.name,A,o),typeof o.value=="function"&&(g[A]=kq(o.value,g,A))):(i&&console.log("Create patch with new property",g.constructor.name,A,o),Object.defineProperty(g,A,{set:function(n){if(typeof n=="function")this[I]=kq(n,g,A);else{const C=this[I];o2(g,A,this,C,n),this[I]=n,s2(g,A,this,C,n)}},get:function(){const n=this[I];return typeof n=="function"&&n[I]?n[I]:n}}))}function x9(g,A,e){const t=xU(g,A);if(t)for(let i=t.length-1;i>=0;i--){const I=t[i];I.prefix===e&&(I.prefix=null),I.postfix===e&&(I.postfix=null),!I.prefix&&!I.postfix&&t.splice(i,1)}}const Gq=Symbol("Needle:Patches:WrappedFunction");function kq(g,A,e){if(g[Gq])return g;const t=function(...i){o2(A,e,this,...i);const I=g.apply(this,i);return s2(A,e,this,I,...i),I};return t[Gq]=!0,t}const $f="Needle:Patches";function HG(){return globalThis[$f]||(globalThis[$f]=new WeakMap),globalThis[$f]}function xU(g,A){const e=HG().get(g);return e?e.get(A):null}function Y9(g,A,e,t){let i=HG().get(g);i||(i=new Map,HG().set(g,i));let I=i.get(A);I||(I=[],i.set(A,I)),I.push({prefix:e,postfix:t})}function o2(g,A,e,...t){var I;if(!e)return;const i=xU(g,A);if(i)for(const o of i)(I=o.prefix)==null||I.call(e,...t)}function s2(g,A,e,t,...i){var o;if(!e)return;const I=xU(g,A);if(I)for(const s of I)(o=s.postfix)==null||o.call(e,t,...i)}const Rq=Symbol("gltf-loader-internal-usage-tracker"),T9=IA("debugusers"),Dh=class{constructor(A){r(this,"parser");r(this,"_getDependency");r(this,"_loadingId");r(this,"_loadedObjects",new Set);this.parser=A,this._getDependency=this.parser.getDependency,this._loadingId=Date.now().toString()}get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(A){return Dh._loadingProcesses>0}beforeRoot(){Dh._loadingProcesses++;const A=this,e=this._getDependency;return this.parser.getDependency=function(t,i){const I=e.call(this,t,i);return I.then(o=>(o&&(A._loadedObjects.add(o),o[Rq]=A._loadingId),o)),I},null}afterRoot(A){Dh._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const e of this._loadedObjects)delete e[Rq],e instanceof pA&&(e.parent||e instanceof dA&&(T9&&console.warn("> GLTF LOADER: Mesh not used in scene!",e),e.material=null,e.geometry=null));return null}};let ih=Dh;r(ih,"_loadingProcesses",0);class n2{constructor(){window.addEventListener("unhandledrejection",A=>{var t;if(A.defaultPrevented)return;const e=(t=A==null?void 0:A.reason)==null?void 0:t.path;if(e){const i=e[0];i&&i.tagName==="IMG"&&(console.warn(`Could not load image:
4344
- `+i.src),A.preventDefault())}})}}const _w=IA("trackresources");function C2(){return _w==="dispose"}let YB=!0;_w===0&&(YB=!1);function _9(g){YB=g}function a2(){return YB}const r2=Symbol("disposable");function YU(g,A){g&&(g[r2]=A,cB&&console.warn("Set disposable",A,g))}const B2=Symbol("disposed");function H9(g){return g[B2]===!0}function Lt(g){var A;if(g){if(g[r2]===!1){cB&&console.warn("Object is marked as not disposable",g);return}if(g[B2]=!0,g instanceof rI)Lt(g.environment),Lt(g.background),Lt(g.customDepthMaterial),Lt(g.customDistanceMaterial);else if(g instanceof Gs)Lt(g.geometry),Lt(g.material),Lt(g.skeleton),Lt(g.bindMatrix),Lt(g.bindMatrixInverse),Lt(g.customDepthMaterial),Lt(g.customDistanceMaterial),g.geometry=null,g.material=null;else if(g instanceof dA)Lt(g.geometry),Lt(g.material),Lt(g.customDepthMaterial),Lt(g.customDistanceMaterial),g.geometry=null,g.material=null;else if(g instanceof we){bQ(g);for(const e of Object.keys(g.attributes)){const t=g.attributes[e];Lt(t)}}else if(g instanceof ge||g instanceof NI)cB&&console.warn("BufferAttribute dispose not supported",g.count);else if(g instanceof Array)for(const e of g)e instanceof Ye&&Lt(e);else if(g instanceof Ye){bQ(g);for(const t of Object.keys(g)){const i=g[t];i instanceof Je&&(Lt(i),g[t]=null)}const e=g.uniforms;if(e)for(const t of Object.keys(e)){const i=e[t];i instanceof Je?(Lt(i),e[t]=null):i instanceof wA&&(Lt(i.value),i.value=null)}}else g instanceof Je?(bQ(g),bQ(g.source),((A=g.source)==null?void 0:A.data)instanceof ImageBitmap&&bQ(g.source.data)):g instanceof Ic?(bQ(g.boneTexture),g.boneTexture=null):g instanceof Fd||!(g instanceof pA)&&cB&&console.warn("Unknown object type",g)}}function bQ(g){g&&((cB||C2()||_w)&&console.warn("๐Ÿงจ FREE",g),g instanceof ImageBitmap?g.close():g instanceof lC?g.data=null:g.dispose())}function Q2(g){(g instanceof dA||g instanceof Gs)&&(g.material=null,g.geometry=null)}const O9=new Set;function TU(g,A,e=null,t){if(t||(t=O9,t.clear()),!g)return t;const i=g[Vh];if(i)for(const I of i)t.has(I)||(e==null?void 0:e.call(null,I))!==!1&&(t.add(I),A&&TU(I,!0,e,t));return t}function P9(g){return g[Kl]}const cB=IA("debugresourceusers")||IA("debugmemory"),Vh=Symbol("needle-resource-users"),Kl=Symbol("needle-resource-users-count");function dI(g,A){Tw(g,A,function(e,t){YB&&(ey(Vh,this,e,!1),ey(Vh,this,t,!0))})}YB&&(dI(dA.prototype,"material"),dI(dA.prototype,"geometry"),dI(Ye.prototype,"map"),dI(Ye.prototype,"bumpMap"),dI(Ye.prototype,"alphaMap"),dI(Ye.prototype,"normalMap"),dI(Ye.prototype,"displacementMap"),dI(Ye.prototype,"roughnessMap"),dI(Ye.prototype,"metalnessMap"),dI(Ye.prototype,"emissiveMap"),dI(Ye.prototype,"specularMap"),dI(Ye.prototype,"envMap"),dI(Ye.prototype,"lightMap"),dI(Ye.prototype,"aoMap"),dI(Ye.prototype,"gradientMap"));function W9(g){if(YB===!1)return;const A=g[Vh];if(A)for(const e of A)ey(Vh,e,g,!1)}YB&&Tw(Ye.prototype,"dispose",function(){W9(this)});let OG=0;function ey(g,A,e,t){if(OG>0)return;if(Array.isArray(e)){for(const I of e)ey(g,A,I,t);return}if(!e)return;let i=e[g];if(i||(i=new Set),t){if(A&&!i.has(A)){i.add(A);let I=e[Kl]||0;I+=1,e[Kl]=I,cB&&console.warn(`๐ŸŸข Added user of "${e.type}"`,A,e,I,"users:",i)}}else if(A&&i.has(A)){i.delete(A);let I=e[Kl]||0;I>0&&(I-=1,e[Kl]=I),cB&&console.warn(`๐Ÿ”ด Removed user of "${e.type}"`,A,e,I,"users:",i),I<=0&&(ih.isLoading(e)||(_w&&console.warn(`๐Ÿ”ด Removed all user of "${e.type}"`,e),C2()&&Lt(e)))}e[g]=i}try{Tw(qC.prototype,"render",function(){OG++},function(){OG--})}catch(g){console.warn("Could not wrap WebGLRenderer.render",g)}var Od=(g=>(g.Added="component-added",g.Removing="removing-component",g))(Od||{});const Uq=IA("debugcomponentevents");class Pd{static addComponentLifecylceEventListener(A,e){this.eventListeners.has(A)&&this.eventListeners.set(A,[]);let t=this.eventListeners.get(A);t||(t=[]),t.push(e),this.eventListeners.set(A,t),Uq&&console.log("Added event listener for "+A,this.eventListeners)}static removeComponentLifecylceEventListener(A,e){const t=this.eventListeners.get(A);if(!t)return;const i=t.indexOf(e);i<0||t.splice(i,1)}static dispatchComponentLifecycleEvent(A,e){const t=this.eventListeners.get(A);if(Uq&&console.log("Dispatching event "+A,t),!!t)for(const i of t)i(e)}}r(Pd,"eventListeners",new Map);const E2=IA("debugdefines");nc('if(!globalThis[""3.35.1-beta""]) globalThis[""3.35.1-beta""] = "0.0.0";');nc('if(!globalThis[""undefined""]) globalThis[""undefined""] = "unknown";');nc('if(!globalThis[""Fri Mar 29 2024 11:35:51 GMT+0100 (GMT+01:00)""]) globalThis[""Fri Mar 29 2024 11:35:51 GMT+0100 (GMT+01:00)""] = "unknown";');nc('globalThis["__NEEDLE_ENGINE_VERSION__"] = "3.35.1-beta";');nc('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');nc('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Fri Mar 29 2024 11:35:51 GMT+0100 (GMT+01:00)";');const Bn="3.35.1-beta",Hw="undefined",_U="Fri Mar 29 2024 11:35:51 GMT+0100 (GMT+01:00)";E2&&console.log(`Engine version: ${Bn} (generator: ${Hw})
4344
+ `+i.src),A.preventDefault())}})}}const _w=IA("trackresources");function C2(){return _w==="dispose"}let YB=!0;_w===0&&(YB=!1);function _9(g){YB=g}function a2(){return YB}const r2=Symbol("disposable");function YU(g,A){g&&(g[r2]=A,cB&&console.warn("Set disposable",A,g))}const B2=Symbol("disposed");function H9(g){return g[B2]===!0}function Lt(g){var A;if(g){if(g[r2]===!1){cB&&console.warn("Object is marked as not disposable",g);return}if(g[B2]=!0,g instanceof rI)Lt(g.environment),Lt(g.background),Lt(g.customDepthMaterial),Lt(g.customDistanceMaterial);else if(g instanceof Gs)Lt(g.geometry),Lt(g.material),Lt(g.skeleton),Lt(g.bindMatrix),Lt(g.bindMatrixInverse),Lt(g.customDepthMaterial),Lt(g.customDistanceMaterial),g.geometry=null,g.material=null;else if(g instanceof dA)Lt(g.geometry),Lt(g.material),Lt(g.customDepthMaterial),Lt(g.customDistanceMaterial),g.geometry=null,g.material=null;else if(g instanceof we){bQ(g);for(const e of Object.keys(g.attributes)){const t=g.attributes[e];Lt(t)}}else if(g instanceof ge||g instanceof NI)cB&&console.warn("BufferAttribute dispose not supported",g.count);else if(g instanceof Array)for(const e of g)e instanceof Ye&&Lt(e);else if(g instanceof Ye){bQ(g);for(const t of Object.keys(g)){const i=g[t];i instanceof Je&&(Lt(i),g[t]=null)}const e=g.uniforms;if(e)for(const t of Object.keys(e)){const i=e[t];i instanceof Je?(Lt(i),e[t]=null):i instanceof wA&&(Lt(i.value),i.value=null)}}else g instanceof Je?(bQ(g),bQ(g.source),((A=g.source)==null?void 0:A.data)instanceof ImageBitmap&&bQ(g.source.data)):g instanceof Ic?(bQ(g.boneTexture),g.boneTexture=null):g instanceof Fd||!(g instanceof pA)&&cB&&console.warn("Unknown object type",g)}}function bQ(g){g&&((cB||C2()||_w)&&console.warn("๐Ÿงจ FREE",g),g instanceof ImageBitmap?g.close():g instanceof lC?g.data=null:g.dispose())}function Q2(g){(g instanceof dA||g instanceof Gs)&&(g.material=null,g.geometry=null)}const O9=new Set;function TU(g,A,e=null,t){if(t||(t=O9,t.clear()),!g)return t;const i=g[Vh];if(i)for(const I of i)t.has(I)||(e==null?void 0:e.call(null,I))!==!1&&(t.add(I),A&&TU(I,!0,e,t));return t}function P9(g){return g[Kl]}const cB=IA("debugresourceusers")||IA("debugmemory"),Vh=Symbol("needle-resource-users"),Kl=Symbol("needle-resource-users-count");function dI(g,A){Tw(g,A,function(e,t){YB&&(ey(Vh,this,e,!1),ey(Vh,this,t,!0))})}YB&&(dI(dA.prototype,"material"),dI(dA.prototype,"geometry"),dI(Ye.prototype,"map"),dI(Ye.prototype,"bumpMap"),dI(Ye.prototype,"alphaMap"),dI(Ye.prototype,"normalMap"),dI(Ye.prototype,"displacementMap"),dI(Ye.prototype,"roughnessMap"),dI(Ye.prototype,"metalnessMap"),dI(Ye.prototype,"emissiveMap"),dI(Ye.prototype,"specularMap"),dI(Ye.prototype,"envMap"),dI(Ye.prototype,"lightMap"),dI(Ye.prototype,"aoMap"),dI(Ye.prototype,"gradientMap"));function W9(g){if(YB===!1)return;const A=g[Vh];if(A)for(const e of A)ey(Vh,e,g,!1)}YB&&Tw(Ye.prototype,"dispose",function(){W9(this)});let OG=0;function ey(g,A,e,t){if(OG>0)return;if(Array.isArray(e)){for(const I of e)ey(g,A,I,t);return}if(!e)return;let i=e[g];if(i||(i=new Set),t){if(A&&!i.has(A)){i.add(A);let I=e[Kl]||0;I+=1,e[Kl]=I,cB&&console.warn(`๐ŸŸข Added user of "${e.type}"`,A,e,I,"users:",i)}}else if(A&&i.has(A)){i.delete(A);let I=e[Kl]||0;I>0&&(I-=1,e[Kl]=I),cB&&console.warn(`๐Ÿ”ด Removed user of "${e.type}"`,A,e,I,"users:",i),I<=0&&(ih.isLoading(e)||(_w&&console.warn(`๐Ÿ”ด Removed all user of "${e.type}"`,e),C2()&&Lt(e)))}e[g]=i}try{Tw(qC.prototype,"render",function(){OG++},function(){OG--})}catch(g){console.warn("Could not wrap WebGLRenderer.render",g)}var Od=(g=>(g.Added="component-added",g.Removing="removing-component",g))(Od||{});const Uq=IA("debugcomponentevents");class Pd{static addComponentLifecylceEventListener(A,e){this.eventListeners.has(A)&&this.eventListeners.set(A,[]);let t=this.eventListeners.get(A);t||(t=[]),t.push(e),this.eventListeners.set(A,t),Uq&&console.log("Added event listener for "+A,this.eventListeners)}static removeComponentLifecylceEventListener(A,e){const t=this.eventListeners.get(A);if(!t)return;const i=t.indexOf(e);i<0||t.splice(i,1)}static dispatchComponentLifecycleEvent(A,e){const t=this.eventListeners.get(A);if(Uq&&console.log("Dispatching event "+A,t),!!t)for(const i of t)i(e)}}r(Pd,"eventListeners",new Map);const E2=IA("debugdefines");nc('if(!globalThis[""3.35.1-beta.1""]) globalThis[""3.35.1-beta.1""] = "0.0.0";');nc('if(!globalThis[""undefined""]) globalThis[""undefined""] = "unknown";');nc('if(!globalThis[""Fri Mar 29 2024 16:20:59 GMT+0100 (GMT+01:00)""]) globalThis[""Fri Mar 29 2024 16:20:59 GMT+0100 (GMT+01:00)""] = "unknown";');nc('globalThis["__NEEDLE_ENGINE_VERSION__"] = "3.35.1-beta.1";');nc('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');nc('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Fri Mar 29 2024 16:20:59 GMT+0100 (GMT+01:00)";');const Bn="3.35.1-beta.1",Hw="undefined",_U="Fri Mar 29 2024 16:20:59 GMT+0100 (GMT+01:00)";E2&&console.log(`Engine version: ${Bn} (generator: ${Hw})
4345
4345
  Project built at ${_U}`);const yC="needle_isActiveInHierarchy",Xr="builtin_components",gh="needle_editor_guid";function nc(g){try{(0,eval)(g)}catch(A){E2&&console.error(A)}}const Zh=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),c2=Symbol("isUsingInstancing"),l2=Symbol("instancingRenderer"),PG=Symbol("instancingAutoUpdateBounds");class Rs{static isUsingInstancing(A){return A[c2]===!0}static getRenderer(A){return A[l2]||null}setAutoUpdateBounds(A,e){const t=Rs.getRenderer(A);t&&(t[PG]=e)}static markDirty(A,e=!0){if(A&&(this.isUsingInstancing(A)&&(A[Zh]=!0,A.matrixWorldNeedsUpdate=!0),e))for(const t of A.children)Rs.markDirty(t,!0)}}function lB(g,A){try{A?g(A):g()}catch(e){return console.error(e),!1}return!0}const WG=IA("debugnewscripts"),j9=IA("debughierarchy"),Ai=[];function z9(){return Ai.length>0}function ty(g){if(!(g.new_scripts.length<=0)){if(WG&&console.log("Register new components",g.new_scripts.length,[...g.new_scripts],g.alias?"element: "+g.alias:g.hash,g),g.new_scripts_pre_setup_callbacks.length>0){for(const A of g.new_scripts_pre_setup_callbacks)A&&A();g.new_scripts_pre_setup_callbacks.length=0}Ai.length=0,g.new_scripts.length>0&&Ai.push(...g.new_scripts),g.new_scripts.length=0;for(let A=0;A<Ai.length;A++)try{const e=Ai[A];if(e.isComponent!==!0){(pe()||WG)&&console.error(`Registered script is not a Needle Engine component.
4346
4346
  The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
4347
4347
  `,e),Ai.splice(A,1),A--;continue}if(e.destroyed)continue;if(!e.gameObject){console.error("MISSING GAMEOBJECT - will ignore",e),Ai.splice(A,1),A--;continue}e.context=g,Ih(e.gameObject),HU(e,g)}catch(e){console.error(e),rC(Ai[A],g),Ai.splice(A,1),A--}for(let A=0;A<Ai.length;A++)try{const e=Ai[A];if(e.destroyed){rC(Ai[A],g),Ai.splice(A,1),A--;continue}if(e.registering)try{e.registering()}catch(t){console.error(t)}e.__internalAwake!==void 0&&(e.gameObject||console.error("MISSING GAMEOBJECT",e,e.gameObject),Ih(e.gameObject),e.activeAndEnabled&&lB(e.__internalAwake.bind(e)))}catch(e){console.error(e),rC(Ai[A],g),Ai.splice(A,1),A--}for(let A=0;A<Ai.length;A++)try{const e=Ai[A];if(e.destroyed||e.enabled===!1||(Ih(e.gameObject),e.activeAndEnabled===!1))continue;e.__internalEnable!==void 0&&(e.enabled=!0,lB(e.__internalEnable.bind(e)))}catch(e){console.error(e),rC(Ai[A],g),Ai.splice(A,1),A--}for(let A=0;A<Ai.length;A++)try{const e=Ai[A];if(e.destroyed||!e.gameObject)continue;g.new_script_start.push(e)}catch(e){console.error(e),rC(Ai[A],g),Ai.splice(A,1),A--}Ai.length=0;for(const A of g.new_scripts_post_setup_callbacks)A&&A();g.new_scripts_post_setup_callbacks.length=0}}function V9(g){g&&(g.__internalDisable(!0),rC(g,g.context))}function h2(g,A){for(let e=0;e<g.new_script_start.length;e++)try{const t=g.new_script_start[e];if(A!==void 0&&t.gameObject!==A||t.destroyed||t.activeAndEnabled===!1)continue;lB(t.__internalAwake.bind(t)),t.enabled&&(lB(t.__internalEnable.bind(t)),lB(t.__internalStart.bind(t)),g.new_script_start.splice(e,1),e--)}catch(t){console.error(t),rC(g.new_script_start[e],g),g.new_script_start.splice(e,1),e--}}function HU(g,A){A.scripts.indexOf(g)===-1&&(A.scripts.push(g),g.earlyUpdate&&A.scripts_earlyUpdate.push(g),g.update&&A.scripts_update.push(g),g.lateUpdate&&A.scripts_lateUpdate.push(g),g.onBeforeRender&&A.scripts_onBeforeRender.push(g),g.onAfterRender&&A.scripts_onAfterRender.push(g),g.onPausedChanged&&A.scripts_pausedChanged.push(g),um(g,null)&&A.new_scripts_xr.push(g),um(g,"immersive-vr")&&A.scripts_immersive_vr.push(g),um(g,"immersive-ar")&&A.scripts_immersive_ar.push(g))}function rC(g,A){qo(g,A.new_scripts),qo(g,A.new_script_start),qo(g,A.scripts),qo(g,A.scripts_earlyUpdate),qo(g,A.scripts_update),qo(g,A.scripts_lateUpdate),qo(g,A.scripts_onBeforeRender),qo(g,A.scripts_onAfterRender),qo(g,A.scripts_pausedChanged),qo(g,A.new_scripts_xr),qo(g,A.scripts_immersive_vr),qo(g,A.scripts_immersive_ar),A.stopAllCoroutinesFrom(g)}function qo(g,A){const e=A.indexOf(g);e>=0&&A.splice(e,1)}function um(g,A){var e;if(g){const t=g;if(t.onBeforeXR||t.onEnterXR||t.onUpdateXR||t.onLeaveXR||t.onXRControllerAdded||t.onXRControllerRemoved)return!(A!=null&&((e=t.supportsXR)==null?void 0:e.call(t,A))===!1)}return!1}function AD(g){if(g||(g=Bt.Current.scene),!g){console.trace("Invalid call - no current context.");return}const A=rc(g);d2(g,A,!0)||(WG||pe()?console.error(`Error updating hierarchy
@@ -5475,7 +5475,7 @@ ${e.path}! : AssetReference;
5475
5475
  Could not find method ${a.method} on object ${Q.name}. Please rename ${a.method} to ${u}?
5476
5476
  `,Q[u],`
5477
5477
  in script: `,Q),Ii("EventList methods must start with lowercase letter, see console for details");return}else console.warn(`EventList method:
5478
- Could not find method ${a.method} on object ${Q.name}`,Q,typeof Q[a.method])};if(typeof Q[a.method]!="function"){let u=!1,f=Q;for(;f;){const m=Object.getOwnPropertyDescriptor(f,a.method);if(m&&(m.writable===!0||m.set)){u=!0;break}f=Object.getPrototypeOf(f)}!u&&(pe()||xg)&&l()}}let c=a.argument;c!==void 0?c=B(c):a.arguments!==void 0&&(c=a.arguments.map(B));const d=E?this.createEventMethod(Q,a.method,c):void 0,h=new OE(d,a.enabled);if(h.method||(h[OiA]=(o=e.object)==null?void 0:o.name),!Q||!h.method){const l=e.object?"Current object: "+e.object.name+", "+e.object.guid:null;Q?console.warn('EventList method not found: "'+a.method+'" on',Q):console.warn("EventList is missing target - will be ignored",a.target,l,A)}else s.push(h)}const n=new wg(s);xg&&console.log(n);const C=e.target;return C!==void 0&&e.path!==void 0&&n.setEventTarget(e.path,C),n}}createEventMethod(A,e,t){return(...i)=>{const I=A[e];typeof I=="function"?t!==void 0?Array.isArray(t)?I==null||I.call(A,...t):I==null||I.call(A,t):I==null||I.call(A,...i):A[e]=t}}}const WiA=new PiA;class hO extends Rn{constructor(){super([Ta,Ze])}onSerialize(A,e){}onDeserialize(A,e){if(A instanceof Je&&e.type===Ta){const t=A,i=new Ta(t.image.width,t.image.height,{colorSpace:yt});return i.texture=t,t.isRenderTargetTexture=!0,t.flipY=!0,t.offset.y=1,t.repeat.y=-1,t.needsUpdate=!0,t.mipmaps=[],t instanceof ln&&(t.isCompressedTexture=!1,t.format=RGBAFormat),i}}}new hO;class dO extends Rn{constructor(){super([URL])}onSerialize(A,e){return null}onDeserialize(A,e){if(typeof A=="string"&&A.length>0)return bC(e.gltfId,A)}}new dO;var jiA=Object.defineProperty,ziA=Object.getOwnPropertyDescriptor,ViA=(g,A,e,t)=>{for(var i=t>1?void 0:t?ziA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&jiA(A,e,i),i};class su extends UA{awake(){jI.createIfNoneExists(this.context)}onEnable(){var A;(A=jI.get(this.context))==null||A.register(this)}onDisable(){var A;(A=jI.get(this.context))==null||A.unregister(this)}}class mo extends su{constructor(){super(...arguments);r(this,"targets",null);r(this,"raycastHits",[]);r(this,"ignoreSkinnedMeshes",!1)}start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??(e=new ts),e.targets=this.targets,e.results=this.raycastHits;const t=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=I=>I instanceof Gs?"continue in children":t?t(I):!0);const i=this.context.physics.raycast(e);return e.testObject=t,i}}ViA([D()],mo.prototype,"ignoreSkinnedMeshes",2);class nS extends mo{constructor(){super(),this.ignoreSkinnedMeshes=!0}}class gd extends su{performRaycast(A){if(!he.active||!(A!=null&&A.ray))return null;const e=A.ray.origin,t=.01;return this.context.physics.sphereOverlap(e,t)}}class CS{static getObject(A){const e=A[Wo];return e&&(e.isComponent===!0?A=e.gameObject:A=e),A}static isInteractable(A,e){if(e&&(e.canvasGroup=void 0,e.graphic=void 0),A==null||!A.visible||(A=this.getObject(A),!A.visible))return!1;const t=this.tryFindCanvasGroup(A);if((t==null?void 0:t.isCanvasGroup)===!0&&(e&&(e.canvasGroup=t),t.blocksRaycasts===!1||t.interactable===!1))return!1;const i=FB(A,I=>{if(I.isGraphic===!0)return I},!1);return e&&(i==null?void 0:i.isGraphic)===!0&&(e.graphic=i),!((i==null?void 0:i.raycastTarget)===!1||(i==null?void 0:i.layer)===2)}static tryFindCanvasGroup(A){if(!A)return null;const e=FB(A,t=>{const i=t;if(i.blocksRaycasts!==void 0&&i.interactable!==void 0)return i},!1);return e!==void 0?e:this.tryFindCanvasGroup(A.parent)}}function SN(g){const A=g[Wo];return A||(g.parent?SN(g.parent):null)}function ZiA(g){return g.isUI===!0||typeof g[Wo]=="object"}function py(g,A){if(!g)return;const e=g.material;if((e==null?void 0:e.isMaterial)===!0){const t=g.parent;t&&t.isText,e.side=A.doubleSided??!0?ut:Tg,e.shadowSide=A.doubleSided?ut:Tg,g.castShadow=A.castShadows?A.castShadows:!1,g.receiveShadow=A.receiveShadows?A.receiveShadows:!1}for(const t of g.children)py(t,A)}function XQ(g,A,e){g[A]===void 0&&console.warn("Field",A,"is undefined on",g);const t=Proxy.revocable(g[A],{set(o,s,n,C){const a=o[s],B=Reflect.set(o,s,n,C);return e(n,a),B}}),i=t.revoke,I=g[A];return t.revoke=()=>{g[A]=I,i()},g[A]=t.proxy,t}const pv=Symbol("Scheduled action");function XiA(g,A,e=zi.OnBeforeRender){let t=g[pv];t||(t=g[pv]={});const i=A.name;t[e]||(t[e]={});const I=t[e];if(I[i])return;function*s(){A==null||A.call(g),I[i]=null}const n=g.startCoroutine(s(),e);I[i]=n}const Xn=IA("debugeventsystem");var vk=(g=>(g.BeforeHandleInput="BeforeHandleInput",g.AfterHandleInput="AfterHandleInput",g))(vk||{});const Xs=class extends UA{constructor(){super();r(this,"raycaster",[]);r(this,"_handleInputFn");r(this,"pressedByID",new Map);r(this,"hoveredByID",new Map);r(this,"_sortedHits",[]);r(this,"_testObjectsCache",new Map);r(this,"_currentlyActiveRaycaster",null);r(this,"_currentPointerEventName",null);r(this,"shouldRaycastObject",e=>{var I;let t=null;if(ZiA(e)&&(t=(I=e[Wo])==null?void 0:I.gameObject),this._testObjectsCache.has(e)||t&&this._testObjectsCache.has(t))return this._testObjectsCache.get(e)===!1?"continue in children":!0;{let o=bk(e,this._currentPointerEventName);if(!o&&t&&(o=bk(t,this._currentPointerEventName)),o){this._testObjectsCache.set(e,!0);for(const s of e.children)this.shouldRaycastObject_AddToYesCache(s);return!0}return this._testObjectsCache.set(e,!1),"continue in children"}});r(this,"_sortingBuffer",[]);r(this,"_noDepthTestingResults",[]);r(this,"out",{});r(this,"_capturedPointer",{});r(this,"pointerEnterSymbol",Symbol("pointerEnter"));r(this,"pointerExitSymbol",Symbol("pointerExit"));r(this,"currentActiveMeshUIComponents",[]);Xs.systems.push(this)}static createIfNoneExists(e){this.didSearchEventSystem||(this.didSearchEventSystem=!0,Xs.systems.length<=0&&Xs.systems.push(...nA.findObjectsOfType(Xs,e)));for(const i of Xs.systems)if(i.context===e)return;const t=new pA;nA.addNewComponent(t,Xs),e.scene.add(t)}static get systems(){const e=Le.Current;return this._eventSystemMap.has(e)||this._eventSystemMap.set(e,[]),this._eventSystemMap.get(e)}static get(e){const t=this._eventSystemMap.get(e);return t&&t.length>0?t[0]:null}static get instance(){return this.systems[0]}static ensureUpdateMeshUI(e,t,i=!1){Ma.update(e,t,i)}static markUIDirty(e){Ma.markDirty()}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}onDestroy(){Xs.systems.splice(Xs.systems.indexOf(this),1)}start(){if(this.raycaster.length<=0&&!nA.findObjectOfType(su,this.context)){const t=nA.addNewComponent(this.context.scene,mo);this.raycaster.push(t),(pe()||Xn)&&console.warn("Added an ObjectRaycaster to the scene because no raycaster was found.")}}register(e){var t;e&&this.raycaster&&!this.raycaster.includes(e)&&((t=this.raycaster)==null||t.push(e))}unregister(e){var i,I;const t=(i=this.raycaster)==null?void 0:i.indexOf(e);t!==void 0&&t!==-1&&((I=this.raycaster)==null||I.splice(t,1))}onEnable(){this._handleInputFn??(this._handleInputFn=this.onPointerEvent.bind(this)),this.context.input.addEventListener(ii.PointerDown,this._handleInputFn),this.context.input.addEventListener(ii.PointerUp,this._handleInputFn),this.context.input.addEventListener(ii.PointerMove,this._handleInputFn)}onDisable(){this.context.input.removeEventListener(ii.PointerDown,this._handleInputFn),this.context.input.removeEventListener(ii.PointerUp,this._handleInputFn),this.context.input.removeEventListener(ii.PointerMove,this._handleInputFn)}onBeforeRender(){this.resetMeshUIStates()}onPointerEvent(e){if(e===void 0||e.propagationStopped)return;const t=new lc(this.context.input,e);this._currentPointerEventName=e.type,t.inputSource=this.context.input,t.isClick=e.isClick,t.isDoubleClick=e.isDoubleClick,t.isDown=e.type==ii.PointerDown,t.isUp=e.type==ii.PointerUp,t.isPressed=this.context.input.getPointerPressed(e.pointerId),Xn&&(t.isDown?console.log("DOWN",t.pointerId):t.isUp&&console.log("UP",t.pointerId),t.isClick&&console.log("CLICK",t.pointerId));const i=new ts;e.hasRay?i.ray=e.ray:i.screenPoint=this.context.input.getPointerPositionRC(e.pointerId);const I=this.performRaycast(i);if(I)for(const s of I)s.event=e,e.intersections.push(s);Xn&&t.isClick&&Gi("EventSystem: "+t.pointerId+" - "+this.context.time.frame+" - Up:"+t.isUp+", Down:"+t.isDown);const o={sender:this,args:t,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:o})),this.handleIntersections(I,t),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:o}))}shouldRaycastObject_AddToYesCache(e){this._testObjectsCache.set(e,!0);for(const t of e.children)this.shouldRaycastObject_AddToYesCache(t)}performRaycast(e){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,e||(e=new ts),e.testObject=this.shouldRaycastObject;for(const t of this.raycaster){if(!t.activeAndEnabled)continue;this._currentlyActiveRaycaster=t;const i=t.performRaycast(e);this._currentlyActiveRaycaster=null,i&&i.length>0&&this._sortedHits.push(...i)}return this._sortedHits.sort((t,i)=>t.distance-i.distance),this._sortedHits}assignHitInformation(e,t){t?(e.intersection=t,e.point=t.point,e.normal=t.normal,e.face=t.face,e.distance=t.distance,e.instanceId=t.instanceId):(e.intersection=void 0,e.point=void 0,e.normal=void 0,e.face=void 0,e.distance=void 0,e.instanceId=void 0)}handleIntersections(e,t){var I;if(e!=null&&e.length){e=this.sortCandidates(e);for(const o of e){if(t.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(t,o),this.handleEventOnObject(o.object,t))return!0}}this.assignHitInformation(t,e==null?void 0:e[0]),this.invokePointerCapture(t);const i=this.hoveredByID.get(t.pointerId);return i&&this.propagatePointerExit(i.obj,i.data,null),this.hoveredByID.delete(t.pointerId),t.isUp&&((I=this.pressedByID.get(t.pointerId))==null||I.handlers.forEach(o=>this.invokeOnPointerUp(t,o)),this.pressedByID.delete(t.pointerId)),!1}sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){const i=e[t],I=i.object;if(I.material&&I.material.depthTest===!1){this._noDepthTestingResults.push(i);continue}this._sortingBuffer.push(i)}for(const t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}handleEventOnObject(e,t){if(!this.testIsVisible(e))return t.isClick&&Xn&&console.log("not allowed",e),!1;if(t.pointerId===void 0)return Xn&&console.error("Event without pointer can't be handled",t),!1;t.object=e;const i=e.parent,I=t.isClick??!1;let o=null;if(i&&i.isUI){const B=(t.isPressed||t.isClick)??!1;if(i[Wo]){const Q=i[Wo].gameObject;if(Q){if(!CS.isInteractable(Q,this.out))return!1;o=this.out.canvasGroup??null,this.handleMeshUIIntersection(e,B),e=Q}}}I&&Xn&&console.log(this.context.time.frame,e);const s=this.hoveredByID.get(t.pointerId),n=s==null?void 0:s.obj;n!==e&&n&&this.propagatePointerExit(n,s.data,e);const a=this.hoveredByID.get(t.pointerId);if(a?(a.obj=e,a.data=t):this.hoveredByID.set(t.pointerId,{obj:e,data:t}),t.isDown){const B=this.pressedByID.get(t.pointerId);B?(B.obj=e,B.data=t):this.pressedByID.set(t.pointerId,{obj:e,data:t,handlers:new Set})}return(o===null||o.interactable)&&this.handleMainInteraction(e,t,n??null),!0}propagate(e,t){for(;e;)nA.foreachComponent(e,i=>{t(i)},!1),e=e.parent}handleMainInteraction(e,t,i){const I=this.pressedByID.get(t.pointerId),o=i!==e;let s=!0;switch(t.event.pointerType){case"mouse":case"touch":const n=this.context.input.getPointerPositionLastFrame(t.pointerId),C=this.context.input.getPointerPosition(t.pointerId);s=n&&!te.approximately(n,C);break}this.propagate(e,n=>{var a;const C=n;C.interactable!==!1&&(!C.activeAndEnabled||!C.enabled||(C.onPointerEnter&&o&&this.handlePointerEnter(C,t),t.isDown&&C.onPointerDown&&(C.onPointerDown(t),I==null||I.handlers.add(C),this.handlePointerCapture(t,C)),C.onPointerMove&&(s&&C.onPointerMove(t),this.handlePointerCapture(t,C)),t.isUp&&(C.onPointerUp&&(this.invokeOnPointerUp(t,C),I==null||I.handlers.delete(C)),C.onPointerExit&&((a=t.event)==null?void 0:a.pointerType)===jw.Touch&&(this.handlePointerExit(C,t),this.hoveredByID.delete(t.pointerId))),t.isClick&&C.onPointerClick&&C.onPointerClick(t)))}),t.isUp&&(I==null||I.handlers.forEach(n=>{this.invokeOnPointerUp(t,n)}),this.pressedByID.delete(t.pointerId))}propagatePointerExit(e,t,i){this.propagate(e,I=>{if(!I.gameObject||I.destroyed)return;const o=I;if(o.onPointerExit){if(i&&this.isChild(i,I.gameObject))return;this.handlePointerExit(o,t)}})}invokeOnPointerUp(e,t){var i;(i=t.onPointerUp)==null||i.call(t,e),this.releasePointerCapture(e,t)}handlePointerEnter(e,t){e.onPointerEnter&&this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!0)&&e.onPointerEnter(t),this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(e,t){e.onPointerExit&&this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!0)&&e.onPointerExit(t),this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(e,t,i,I){let o=e[i];if(I)return o&&o.includes(t)?!1:(o=o||[],o.push(t),e[i]=o,!0);{if(!o||!o.includes(t))return!1;const s=o.indexOf(t);return s!==-1&&o.splice(s,1),!0}}handlePointerCapture(e,t){if(e.z__pointer_ctured){e.z__pointer_ctured=!1;const i=e.pointerId;if(t.onPointerMove){const I=this._capturedPointer[i]||[];I.push(t),this._capturedPointer[i]=I}else pe()&&!t.z__warned_no_pointermove&&(t.z__warned_no_pointermove=!0,console.warn("PointerCapture was requested but the component doesn't implement onPointerMove. It will not receive any pointer events"))}else e.z__pointer_cture_rleased&&(e.z__pointer_cture_rleased=!1,this.releasePointerCapture(e,t))}releasePointerCapture(e,t){const i=e.pointerId;if(this._capturedPointer[i]){const I=this._capturedPointer[i].indexOf(t);I!==-1&&(this._capturedPointer[i].splice(I,1),Xn&&console.log("released pointer capture",i,t,this._capturedPointer))}}invokePointerCapture(e){var t;if(e.event.type===ii.PointerMove){const i=e.pointerId,I=this._capturedPointer[i];if(I){Xn&&console.log("Captured",i,I);for(let o=0;o<I.length;o++){const s=I[o];if(s.destroyed){I.splice(o,1),o--;continue}(t=s.onPointerMove)==null||t.call(s,e)}}}}isChild(e,t){return!e||!t?!1:e===t?!0:e.parent?this.isChild(e.parent,t):!1}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}handleMeshUIIntersection(e,t){const i=Ma.updateState(e,t);return i&&this.currentActiveMeshUIComponents.push(i),i!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&Ma.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){const t=this.currentActiveMeshUIComponents[e];Ma.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?nA.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}};let jI=Xs;r(jI,"_eventSystemMap",new Map),r(jI,"didSearchEventSystem",!1);class Ma{static markDirty(){this.needsUpdate=!0}static update(A,e,t=!1){if(t){A.update();return}const i=e.time.frameCount;for(const I of this.lastUpdateFrame)if(I.context===e){if(i===I.frame)return;I.frame=i;let o=this.needsUpdate||i<1;I.nextUpdate===e.time.frameCount&&(o=!0),o&&(Xn&&console.log("Update threemeshui"),this.needsUpdate=!1,A.update());return}this.lastUpdateFrame=[{context:e,frame:i,nextUpdate:i}],A.update()}static updateState(A,e){let t=null;if(A&&(t=this.findBlockInParent(A),t&&t!==this.lastSelected)){if(t.interactable===!1)return null;this.needsUpdate=!0}return t}static resetLastSelected(){const A=this.lastSelected;A&&(this.lastSelected=null,this.resetState(A))}static resetState(A){A&&(this.needsUpdate=!0)}static findBlockInParent(A){return A?A.isBlock?A:this.findBlockInParent(A.parent):null}}r(Ma,"lastSelected",null),r(Ma,"lastUpdateFrame",[]),r(Ma,"needsUpdate",!1);var $iA=Object.defineProperty,AgA=Object.getOwnPropertyDescriptor,Ri=(g,A,e,t)=>{for(var i=t>1?void 0:t?AgA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&$iA(A,e,i),i};const egA=IA("debugorbit"),Bf=IA("freecam"),cl=IA("debugcamerafit"),Qf=IA("smoothcam"),tgA={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let AM;class Id extends CustomEvent{constructor(A,e){super("target-reached",{detail:{controls:A,type:e}})}}class kt extends UA{constructor(){super(...arguments);r(this,"autoTarget",!0);r(this,"autoFit",!1);r(this,"enableRotate",!0);r(this,"autoRotate",!1);r(this,"autoRotateSpeed",1);r(this,"minAzimuthAngle",1/0);r(this,"maxAzimuthAngle",1/0);r(this,"minPolarAngle",0);r(this,"maxPolarAngle",Math.PI);r(this,"enableKeys",!0);r(this,"enableDamping",!0);r(this,"dampingFactor",.1);r(this,"enableZoom",!0);r(this,"minZoom",0);r(this,"maxZoom",1/0);r(this,"enablePan",!0);r(this,"lookAtConstraint",null);r(this,"lookAtConstraint01",1);r(this,"allowInterrupt",!0);r(this,"middleClickToFocus",!0);r(this,"doubleClickToFocus",!0);r(this,"useSlerp",!0);r(this,"debugLog",!1);r(this,"targetLerpDuration",1);r(this,"_controls",null);r(this,"_cameraObject",null);r(this,"_lookTargetLerpActive",!1);r(this,"_lookTargetStartPosition",new y);r(this,"_lookTargetEndPosition",new y);r(this,"_lookTargetLerp01",0);r(this,"_lookTargetLerpDuration",0);r(this,"_cameraLerpActive",!1);r(this,"_cameraStartPosition",new y);r(this,"_cameraEndPosition",new y);r(this,"_cameraLerp01",0);r(this,"_cameraLerpDuration",0);r(this,"_inputs",0);r(this,"_enableTime",0);r(this,"_startedListeningToKeyEvents",!1);r(this,"_eventSystem");r(this,"_afterHandleInputFn");r(this,"_camera",null);r(this,"_syncedTransform");r(this,"_didStart",!1);r(this,"_didSetTarget",!1);r(this,"targetElement",null);r(this,"onControlsChangeStarted",()=>{this._syncedTransform&&this._syncedTransform.requestOwnership()});r(this,"_shouldDisable",!1);r(this,"_haveAttachedKeyboardEvents",!1)}get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){var t;(t=this.controls)==null||t.addEventListener("start",e)}get targetLerpSpeed(){return 5}set targetLerpSpeed(e){this.targetLerpDuration=1/e}awake(){this._didStart=!1,this._didSetTarget=!1,this._startedListeningToKeyEvents=!1}start(){this._didStart=!0,this._eventSystem=jI.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(vk.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){var e,t;(e=this._controls)==null||e.dispose(),(t=this._eventSystem)==null||t.removeEventListener(vk.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._enableTime=this.context.time.time;const e=nA.getComponent(this.gameObject,Vt);this._camera=e;let t=e==null?void 0:e.cam;if(!t&&this.gameObject instanceof Oe&&(t=this.gameObject),t&&dv(t,this,!0),!this._controls&&t instanceof Oe){this._cameraObject=t;const i=this.targetElement??this.context.renderer.domElement,I=t==null?void 0:t.quaternion.clone();this._controls=new SiA(t,i),t==null||t.quaternion.copy(I),AM===void 0&&(AM={...this._controls.keys})}this._controls&&(Bf&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,kn()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),(t==null?void 0:t.type)==="PerspectiveCamera"?Bf||(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):Bf||(this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom),this._startedListeningToKeyEvents||(this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(window.document.body))),this._syncedTransform=nA.getComponent(this.gameObject,$a)??void 0}onDisable(){var e;(e=this._camera)!=null&&e.cam&&dv(this._camera.cam,this,!1),this._controls&&(this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted))}afterHandleInput(e){e.detail.args.pointerId===0&&(e.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!e.detail.args.isPressed||e.detail.args.isUp)&&(this._shouldDisable=!1))}onBeforeRender(){var t,i;if(!this._controls||this._cameraObject!==this.context.mainCamera)return;this.__handleSetTargetWhenBecomingActiveTheFirstTime(),(this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2)||this.context.input.mouseWheelChanged||this.context.input.getPointerPressed(0)&&((t=this.context.input.getPointerPositionDelta(0))!=null&&t.length())||0>.1)&&(this._inputs+=1),this._inputs>0&&this.allowInterrupt&&(this.enableRotate&&(this.autoRotate=!1),this._cameraLerpActive=!1,this._lookTargetLerpActive=!1),this._inputs=0;let e=this.middleClickToFocus&&this.context.input.getPointerClicked(1);if(e||(e=this.doubleClickToFocus&&this.context.input.getPointerDoubleClicked(0)&&this.context.time.time-this._enableTime>.3),e&&this.setTargetFromRaycast(),this._lookTargetLerpActive||this._cameraLerpActive){if(this._cameraLerpActive&&this._cameraObject)if(this._cameraLerp01+=this.context.time.deltaTime/this._cameraLerpDuration,this._cameraLerp01>=1)this._cameraObject.position.copy(this._cameraEndPosition),this._cameraLerpActive=!1,this.dispatchEvent(new Id(this,"camera"));else{const I=te.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,I)}if(this._lookTargetLerpActive)if(this._lookTargetLerp01+=this.context.time.deltaTime/this._lookTargetLerpDuration,this._lookTargetLerp01>=1)this._controls.target.copy(this._lookTargetEndPosition),this._lookTargetLerpActive=!1,this.dispatchEvent(new Id(this,"lookat"));else{const I=te.easeInOutCubic(this._lookTargetLerp01);this._controls.target.lerpVectors(this._lookTargetStartPosition,this._lookTargetEndPosition,I)}}if(this._controls){if(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!this._shouldDisable&&this._camera===this.context.mainCameraComponent&&!this.context.isInXR,this._controls.keys=this.enableKeys?AM:tgA,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,this._controls.enableDamping=this.enableDamping,this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._controls.enableRotate=this.enableRotate,this._controls.minAzimuthAngle=this.minAzimuthAngle,this._controls.maxAzimuthAngle=this.maxAzimuthAngle,this._controls.minPolarAngle=this.minPolarAngle,this._controls.maxPolarAngle=this.maxPolarAngle,typeof Qf=="number"||Qf===!0){this._controls.enableDamping=!0;const I=typeof Qf=="number"?Qf:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,I))}this.allowInterrupt||(this._lookTargetLerpActive&&(this._controls.enablePan=!1),this._cameraLerpActive&&(this._controls.enableRotate=!1,this._controls.autoRotate=!1),(this._lookTargetLerpActive||this._cameraLerpActive)&&(this._controls.enableZoom=!1)),this.context.isInXR||(!Bf&&((i=this.lookAtConstraint)!=null&&i.locked)&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(),egA&&Ue.DrawWireSphere(this._controls.target,.1,65280))}}__handleSetTargetWhenBecomingActiveTheFirstTime(){if(!this._didSetTarget&&(this._didSetTarget=!0,this.autoTarget)){const e=nA.getComponent(this.gameObject,Vt);if(e&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const i=ve(e.cam).length(),I=new y(0,0,-i).applyMatrix4(e.cam.matrixWorld);this.setLookTargetPosition(I,!0)}if(!this.autoFit&&!this.setLookTargetFromConstraint()){const t=new ts;t.screenPoint=new tA(0,0),t.lineThreshold=.1;const i=this.context.physics.raycast(t);i.length>0&&this.setLookTargetPosition(i[0].point,!0),cl&&console.log("OrbitControls hits",...i)}this.autoFit&&this.fitCamera()}}setCameraAndLookTarget(e){if(!e||!(e instanceof pA))return;const t=ve(e),i=JU(e);this.setTargetFromRaycast(new XI(t,i)),this.setCameraTargetPosition(t)}setCameraTargetPosition(e,t=!1){var i,I;e&&(e instanceof pA&&(e=ve(e)),this._cameraEndPosition||(this._cameraEndPosition=new y),this._cameraEndPosition.copy(e),t===!0?(this._cameraLerpActive=!1,(i=this.controllerObject)==null||i.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy((I=this._cameraObject)==null?void 0:I.position),typeof t=="number"?this._cameraLerpDuration=t:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setLookTargetPosition(e=null,t=!1){this._controls&&e&&(e instanceof pA&&(e=ve(e)),this._lookTargetEndPosition.copy(e),t===!0?this._controls.target.copy(this._lookTargetEndPosition):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof t=="number"?this._lookTargetLerpDuration=t:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(e=0,t=1){var I;if(!this._controls)return!1;const i=(I=this.lookAtConstraint)==null?void 0:I.sources;if(i&&i.length>0){const o=i[e];if(o)return o.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._lookTargetEndPosition,t),!0}return!1}lerpTarget(e,t){return this.lerpLookTarget(e,t)}lerpLookTarget(e,t){this._controls&&(t>=1?this._controls.target.copy(e):this._controls.target.lerp(e,t))}setTargetFromRaycast(e){var i,I;if(!this.controls)return;const t=e?this.context.physics.raycastFromRay(e):this.context.physics.raycast();for(const o of t)if(o.distance>0&&nA.isActiveInHierarchy(o.object)){const s=SN(o.object);if(s){const n=s.canvas;if(n!=null&&n.screenspace)break}if(this.setLookTargetPosition(o.point),this.context.mainCamera){const C=ve(this.context.mainCamera).clone().sub(this.controls.target).add(this._lookTargetEndPosition);(I=(i=this._cameraObject)==null?void 0:i.parent)==null||I.worldToLocal(C),this.setCameraTargetPosition(C)}break}}fitCamera(e,t=1.1,i=!0){const I=this._cameraObject,o=this._controls;if(e!=null&&e.length||(e=this.context.scene.children),e.length<=0||!I||!o)return;const s=new y,n=new y,C=new Ft;C.makeEmpty();const a=[];function B(u){let f=!0;if(u.visible&&MiA(u)!==!1&&!(u.type==="TransformControlsGizmo"||u.type==="TransformControlsPlane")&&(u instanceof NG&&(f=!1),u instanceof Jw&&(f=!1),u instanceof BO&&(f=!1),u.material instanceof mw&&(f=!1),u instanceof dA||(f=!1),u!==I&&u.isUI!==!0)){if(f){cl&&console.log(u.name,u.type,u);const m=u.children;u.children=a;const M=u.position,k=u.scale;if(Number.isNaN(M.x)||Number.isNaN(M.y)||Number.isNaN(M.z)){console.warn(`Object "${u.name}" has NaN values in position or scale.... will ignore it`,M,k);return}C.expandByObject(u,!0),u.children=m}for(const m of u.children)B(m)}}for(const u of e)u.updateMatrixWorld(),B(u);if(I.updateMatrixWorld(),I.updateProjectionMatrix(),C.getCenter(n),C.applyMatrix4(I.matrixWorldInverse),C.getSize(s),C.setFromCenterAndSize(n,s),Number.isNaN(s.x)||Number.isNaN(s.y)||Number.isNaN(s.z)){console.warn("Camera fit size resultet in NaN",I,C,[...e]);return}if(s.length()<=1e-10){cl&&console.warn("Camera fit size is zero",C,[...e]);return}const Q=I.fov,E=2*Math.atan(Math.tan(Q*Math.PI/360/2)*I.aspect)/Math.PI*360,c=s.y/(2*Math.atan(Math.PI*Q/360)),d=s.x/(2*Math.atan(Math.PI*E/360)),h=t*Math.max(c,d)+s.z/2;cl&&console.log("Fit camera to objects",c,d,"distance",h);const l=ve(I),p=o.target.clone().sub(l).normalize().multiplyScalar(h);if(o.maxDistance=h*10,o.minDistance=h*.01,this.setLookTargetPosition(n,i),this.autoTarget=!1,I.near=h/1e3,I.far=h*100,I.updateMatrixWorld(),I.updateProjectionMatrix(),I.parent){const u=I.parent.worldToLocal(o.target.clone().sub(p));this.setCameraTargetPosition(u,i)}else console.error(`Can not fit camera ${I.name} because it has no parent`);if(cl){const u=new NG(C);this.context.scene.add(u),vU(u,_d(I)),this._haveAttachedKeyboardEvents||(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",f=>{f.code==="KeyF"&&this.fitCamera(e)}))}o.update()}}Ri([D()],kt.prototype,"autoTarget",2);Ri([D()],kt.prototype,"autoFit",2);Ri([D()],kt.prototype,"enableRotate",2);Ri([D()],kt.prototype,"autoRotate",2);Ri([D()],kt.prototype,"autoRotateSpeed",2);Ri([D()],kt.prototype,"minAzimuthAngle",2);Ri([D()],kt.prototype,"maxAzimuthAngle",2);Ri([D()],kt.prototype,"minPolarAngle",2);Ri([D()],kt.prototype,"maxPolarAngle",2);Ri([D()],kt.prototype,"enableKeys",2);Ri([D()],kt.prototype,"enableDamping",2);Ri([D()],kt.prototype,"dampingFactor",2);Ri([D()],kt.prototype,"enableZoom",2);Ri([D()],kt.prototype,"minZoom",2);Ri([D()],kt.prototype,"maxZoom",2);Ri([D()],kt.prototype,"enablePan",2);Ri([D(Iu)],kt.prototype,"lookAtConstraint",2);Ri([D()],kt.prototype,"lookAtConstraint01",2);Ri([D()],kt.prototype,"allowInterrupt",2);Ri([D()],kt.prototype,"middleClickToFocus",2);Ri([D()],kt.prototype,"doubleClickToFocus",2);Ri([D()],kt.prototype,"targetLerpDuration",2);var igA=Object.defineProperty,ggA=Object.getOwnPropertyDescriptor,ko=(g,A,e,t)=>{for(var i=t>1?void 0:t?ggA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&igA(A,e,i),i},KB=(g=>(g[g.Skybox=1]="Skybox",g[g.SolidColor=2]="SolidColor",g[g.Uninitialized=4]="Uninitialized",g))(KB||{});const IC=IA("debugcam"),fv=IA("debugscreenpointtoray");var vf;const Tl=(vf=class extends UA{constructor(){super(...arguments);r(this,"_nearClipPlane",.1);r(this,"_farClipPlane",1e3);r(this,"orthographic",!1);r(this,"orthographicSize",5);r(this,"ARBackgroundAlpha",0);r(this,"_cullingMask",4294967295);r(this,"_backgroundBlurriness",0);r(this,"_backgroundIntensity",1);r(this,"_environmentIntensity");r(this,"_targetTexture",null);r(this,"_backgroundColor");r(this,"_fov");r(this,"_cam",null);r(this,"_clearFlags",2);r(this,"_skybox")}get isCamera(){return!0}get aspect(){return this._cam instanceof Oe?this._cam.aspect:this.context.domWidth/this.context.domHeight}get fieldOfView(){return this._cam instanceof Oe?this._cam.fov:this._fov}set fieldOfView(A){const e=this.fieldOfView!=A;if(this._fov=A,e&&this._cam&&this._cam instanceof Oe){if(this._fov===void 0){console.warn("Can not set undefined fov on PerspectiveCamera");return}this._cam.fov=this._fov,this._cam.updateProjectionMatrix()}}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(A){const e=this._nearClipPlane!=A;this._nearClipPlane=A,this._cam&&e&&(this._cam.near=A,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(A){const e=this._farClipPlane!=A;this._farClipPlane=A,this._cam&&e&&(this._cam.far=A,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(A){A!==this._clearFlags&&(this._clearFlags=A,this.applyClearFlagsIfIsActiveCamera())}set cullingMask(A){this._cullingMask=A,this._cam&&(this._cam.layers.mask=A)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}set cullingLayer(A){this.cullingMask=(1<<A|0)>>>0}set backgroundBlurriness(A){A!==this._backgroundBlurriness&&(A===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(A,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}set backgroundIntensity(A){A!==this._backgroundIntensity&&(A===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(A,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}set environmentIntensity(A){this._environmentIntensity=A}get environmentIntensity(){return this._environmentIntensity}get backgroundColor(){return this._backgroundColor??null}set backgroundColor(A){if(A){if(this._backgroundColor)this._backgroundColor.copy(A);else{if(!A.clone)return;this._backgroundColor=A.clone()}A.alpha===void 0&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera()}}set targetTexture(A){this._targetTexture=A}get targetTexture(){return this._targetTexture}get cam(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(A,e,t){const i=this.cam,I=Tl._origin;I.set(A,e,-1),this.context.input.convertScreenspaceToRaycastSpace(I),fv&&console.log("screenPointToRay",A.toFixed(2),e.toFixed(2),"now:",I.x.toFixed(2),I.y.toFixed(2),"isInXR:"+this.context.isInXR),I.z=-1,I.unproject(i);const o=Tl._direction.set(I.x,I.y,I.z),s=ve(i);return o.sub(s),o.normalize(),t?(t.set(s,o),t):new XI(s.clone(),o.clone())}awake(){fv&&window.addEventListener("pointerdown",A=>{const e=A.clientX,t=A.clientY;console.log("touch",e.toFixed(2),t.toFixed(2));const i=this.screenPointToRay(e,t),I="#"+Math.floor(Math.random()*16777215).toString(16);Ue.DrawRay(i.origin,i.direction,I,10)})}onEnable(){IC&&console.log(`Camera enabled: "${this.name}". ClearFlags=${KB[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),ogA(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 A=this.context.renderer;if(A){const e=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,A),e==null||e.applyClearFlags()}}}buildCamera(){if(this._cam)return;const A=this.gameObject.isCamera;let e=null;if(A?(e=this.gameObject,e==null||e.layers.enableAll(),e instanceof Oe&&(this._fov=e.fov)):e=this.gameObject.children[0],e&&e.isCamera)e instanceof Oe&&(this._fov&&(e.fov=this._fov),e.near=this._nearClipPlane,e.far=this._farClipPlane,e.updateProjectionMatrix());else if(!this.orthographic)e=new Oe(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(e.fov=this.fieldOfView),this.gameObject.add(e);else{const t=this.orthographicSize*100;e=new JC(window.innerWidth/-t,window.innerWidth/t,window.innerHeight/t,window.innerHeight/-t,this._nearClipPlane,this._farClipPlane),this.gameObject.add(e)}this._cam=e,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(){this.context.mainCameraComponent===this&&this.applyClearFlags()}applyClearFlags(){if(!this._cam){IC&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this._fov,IC){const A=`Camera "${this.name}" clear flags: ${KB[this._clearFlags]}`;console.debug(A)}switch(this._clearFlags){case 1:if(Tl.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:IC&&console.warn(`Camera "${this.name}" has no background blurriness`),this._backgroundIntensity!==void 0?this.context.scene.backgroundIntensity=this._backgroundIntensity:IC&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor){let A=this._backgroundColor.alpha;Tl.backgroundShouldBeTransparent(this.context)&&(A=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.renderer.setClearColor(this._backgroundColor,A)}else IC&&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 IgA(this)),this._skybox.enable()}static backgroundShouldBeTransparent(A){var I,o,s,n;const e=(I=A.renderer.xr)==null?void 0:I.getSession();if(!e)return!1;if(typeof e._transparent=="boolean")return e._transparent;const t=e.environmentBlendMode;IC&&Gi("Environment blend mode: "+t+" on "+navigator.userAgent);let i=t==="additive"||t==="alpha-blend";return A.isInAR&&t==="opaque"&&((o=navigator.userAgent)!=null&&o.includes("OculusBrowser")||(s=navigator.userAgent)!=null&&s.includes("Mozilla")&&((n=navigator.userAgent)!=null&&n.includes("Mobile WebXRViewer/v2")))&&(i=!0),e._transparent=i,i}},r(vf,"_origin",new y),r(vf,"_direction",new y),vf);let Vt=Tl;ko([D()],Vt.prototype,"fieldOfView",1);ko([D()],Vt.prototype,"nearClipPlane",1);ko([D()],Vt.prototype,"farClipPlane",1);ko([D()],Vt.prototype,"clearFlags",1);ko([D()],Vt.prototype,"orthographic",2);ko([D()],Vt.prototype,"orthographicSize",2);ko([D()],Vt.prototype,"ARBackgroundAlpha",2);ko([D()],Vt.prototype,"cullingMask",1);ko([D()],Vt.prototype,"backgroundBlurriness",1);ko([D()],Vt.prototype,"backgroundIntensity",1);ko([D()],Vt.prototype,"environmentIntensity",1);ko([D(Mt)],Vt.prototype,"backgroundColor",1);ko([D(Ta)],Vt.prototype,"targetTexture",1);class IgA{constructor(A){r(this,"_camera");r(this,"_skybox");this._camera=A}get context(){var A;return(A=this._camera)==null?void 0:A.context}enable(){this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),this._skybox?this.context.scene.background!==this._skybox&&(IC&&console.log(`Camera "${this._camera.name}" set skybox`,this._camera,this._skybox),this._skybox.mapping=Zo,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)),(IC||pe())&&Ii(`Camera "${this._camera.name}" has no skybox texture`))}}function ogA(g){IA("freecam")&&g.context.mainCameraComponent===g&&nA.getOrAddComponent(g.gameObject,kt)}class _a extends UA{constructor(){super(...arguments);r(this,"_listener",null)}get listener(){return this._listener==null&&(this._listener=new TY),this._listener}awake(){hi.registerWaitForAllowAudio(()=>{if(this.destroyed)return;const e=this.listener;if(e==null||e.parent)return;const t=this.context.mainCameraComponent||nA.getComponentInParent(this.gameObject,Vt);t!=null&&t.cam?t.cam.add(e):this.gameObject.add(e)})}}var sgA=Object.defineProperty,ngA=Object.getOwnPropertyDescriptor,aS=(g,A,e,t)=>{for(var i=t>1?void 0:t?ngA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&sgA(A,e,i),i};const CgA=IA("debugsignals");class nu{constructor(){r(this,"guid")}}aS([D()],nu.prototype,"guid",2);class hc{constructor(){r(this,"signal");r(this,"reaction")}}aS([D(nu)],hc.prototype,"signal",2);aS([D(wg)],hc.prototype,"reaction",2);var YM;const $n=(YM=class extends UA{constructor(){super(...arguments);r(this,"events")}static invoke(A){if($n.receivers[A]){const e=$n.receivers[A];if(!e)return;for(const t of e)t.invoke(A)}}awake(){CgA&&console.log("SignalReceiver awake",this)}onEnable(){if(this.events)for(const A of this.events)$n.receivers[A.signal.guid]||($n.receivers[A.signal.guid]=[]),$n.receivers[A.signal.guid].push(this)}onDisable(){if(this.events){for(const A of this.events)if($n.receivers[A.signal.guid]){const e=$n.receivers[A.signal.guid].indexOf(this);e>=0&&$n.receivers[A.signal.guid].splice(e,1)}}}invoke(A){if(!this.events||!Array.isArray(this.events))return;const e=typeof A=="object"?A.guid:A;for(const t of this.events)if(t.signal.guid===e)try{if(t.reaction){if(!t.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",t,this);continue}}else{console.warn("Missing reaction for signal",t,this);continue}t.reaction.invoke()}catch(i){console.error(i)}}},r(YM,"receivers",{}),YM);let dc=$n;aS([D(hc)],dc.prototype,"events",2);var no=(g=>(g.Activation="ActivationTrack",g.Animation="AnimationTrack",g.Audio="AudioTrack",g.Control="ControlTrack",g.Marker="MarkerTrack",g.Signal="SignalTrack",g))(no||{}),Zs=(g=>(g[g.None=0]="None",g[g.Hold=1]="Hold",g[g.Loop=2]="Loop",g[g.PingPong=3]="PingPong",g[g.Continue=4]="Continue",g))(Zs||{}),mN=(g=>(g.Signal="SignalEmitter",g))(mN||{});const Qn=IA("debugtimeline");class Cu{constructor(){r(this,"director");r(this,"track")}get muted(){return this.track.muted}set muted(A){var e;A!==this.track.muted&&(this.track.muted=A,(e=this.onMuteChanged)==null||e.call(this))}*forEachClip(A=!1){var e;if((e=this.track)!=null&&e.clips)if(A)for(let t=this.track.clips.length-1;t>=0;t--)yield this.track.clips[t];else for(const t of this.track.clips)yield t}getClipTime(A,e){return e.clipIn+(A-e.start)*e.timeScale}getClipTimeNormalized(A,e){return(A-e.start)/e.duration}evaluateWeight(A,e,t,i=!0){if(e<0||e>=t.length)return 0;const I=t[e];if(i||A>=I.start&&A<=I.end){let o=1;const s=!1;if(I.easeInDuration>0){const n=Math.min((A-I.start)/I.easeInDuration,1);o*=n}if(I.easeOutDuration>0&&!s){const n=Math.min((I.end-A)/I.easeOutDuration,1);o*=n}return o}return 0}}class agA{constructor(A){r(this,"clip");r(this,"rootPositionOffset");r(this,"rootQuaternionOffset");r(this,"rootStartPosition");r(this,"rootEndPosition");r(this,"rootStartQuaternion");r(this,"rootEndQuaternion");const e=A.getClip();this.clip=e;const t=A.getRoot(),i=t.name+".position",I=t.name+".quaternion";Qn&&console.log(e.name,e.tracks,i);for(const o of e.tracks)if(!(o.times.length<=0)){if(o.name.endsWith(i))this.rootStartPosition=new y().fromArray(o.values,0),this.rootEndPosition=new y().fromArray(o.values,o.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),Qn&&console.log(this.rootPositionOffset);else if(o.name.endsWith(I)&&(this.rootStartQuaternion=new kA().fromArray(o.values,0),this.rootEndQuaternion=new kA().fromArray(o.values,o.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),Qn)){const s=new jt().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",s)}}}get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}}class rS extends Cu{constructor(){super(...arguments);r(this,"models",[]);r(this,"trackOffset");r(this,"target");r(this,"mixer");r(this,"clips",[]);r(this,"actions",[]);r(this,"_actionOffsets",[]);r(this,"_didBind",!1);r(this,"_animator",null);r(this,"_useclipOffsets",!0);r(this,"_totalOffsetPosition",new y);r(this,"_totalOffsetRotation",new kA);r(this,"_totalOffsetPosition2",new y);r(this,"_totalOffsetRotation2",new kA);r(this,"_summedPos",new y);r(this,"_tempPos",new y);r(this,"_summedRot",new kA);r(this,"_tempRot",new kA);r(this,"_clipRotQuat",new kA)}onStateChanged(){this._animator&&Dv(this._animator.gameObject,this,this.director.isPlaying)}createHooks(e,t){var a,B;if(((a=t.tracks)==null?void 0:a.length)<=0){console.warn("No tracks in AnimationClip",t);return}const i=t.tracks[0].name.split("."),I=i[i.length-2],o=I+".position",s=I+".quaternion";let n=!1,C=!1;for(const Q of t.tracks)Q.name.endsWith(o)?(n=!0,this.createPositionInterpolant(t,e,Q)):Q.name.endsWith(s)&&(C=!0,this.createRotationInterpolant(t,e,Q));if(!n||!C){const Q=(B=this.mixer)==null?void 0:B.getRoot(),E=t.tracks[0],c=E.name.lastIndexOf("."),d=E.name.substring(0,c),h=d.substring(d.lastIndexOf(".")+1),l=Q.getObjectByName(h);if(l)if(n){if(!C){const p=t.tracks[0].name.substring(0,c)+".quaternion";Qn&&console.warn("Create quaternion track",h,l);const u=l.quaternion,f=new wn(p,[0,t.duration],[u.x,u.y,u.z,u.w,u.x,u.y,u.z,u.w]);t.tracks.push(f),this.createRotationInterpolant(t,e,f)}}else{const p=d+".position";Qn&&console.warn("Create position track",h,l);const u=l.position,f=new GC(p,[0,t.duration],[u.x,u.y,u.z,u.x,u.y,u.z]);t.tracks.push(f),this.createPositionInterpolant(t,e,f)}}}bind(){if(!this._didBind){this._didBind=!0,Qn&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(const e of this.actions){const t=new agA(e);this._actionOffsets.push(t)}this.target&&(this._animator=nA.getComponent(this.target,Hg)??null,this._animator&&Dv(this._animator.gameObject,this,!0));for(const e of this.models){const t=e.asset,i=t.position,I=t.rotation;i&&i.x!==void 0&&(i.isVector3||(t.position=new y(i.x,i.y,i.z)),I.isQuaternion||(t.rotation=new kA(I.x,I.y,I.z,I.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){const e=this.trackOffset.position;e&&(e.isVector3||(this.trackOffset.position=new y(e.x,e.y,e.z)));const t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new kA(t.x,t.y,t.z,t.w)))}}evaluate(e){var n,C,a,B,Q,E,c;if(this.track.muted||!this.mixer)return;this.bind(),this._totalOffsetPosition.set(0,0,0),this._totalOffsetRotation.set(0,0,0,1),this._totalOffsetPosition2.set(0,0,0),this._totalOffsetRotation2.set(0,0,0,1);let t=0,i=0,I=!1,o=!1,s=0;for(let d=0;d<this.clips.length;d++){const h=this.models[d],l=this.actions[d],p=h.asset;l.weight=0;const u=e>=h.start&&e<=h.end,f=h.preExtrapolationMode,m=h.postExtrapolationMode,M=d<this.clips.length-1?this.models[d+1]:null;let k=u,S=!1;if(!k&&!I&&h.end<e&&m!==Zs.None?(!M||M.start>e)&&(k=!0,I=!0):d==0&&!k&&!o&&h.start>e&&f!==Zs.None&&(!M||M.start<e)&&(k=!0,S=!0,o=!0),k){let F=1;F*=this.evaluateWeight(e,d,this.models,k),F*=this.director.weight;let w=u;if(S)switch(f){case Zs.Hold:break;case Zs.Loop:e+=h.start,w=!0;break;default:e+=h.start,w=!0;break}let R=this.getClipTime(e,h),H=0;const Y=p.duration;if(S&&f===Zs.Hold&&(R=0),w){if(p.loop)for(H+=Math.floor(R/(Y+1e-6));R>Y;)R-=Y}else if(!u&&I)switch(m){case Zs.Hold:R=this.getClipTime(h.end,h);break;case Zs.Loop:R%=Y;break;case Zs.PingPong:const q=Math.floor(R/Y)%2!==0;R%=Y,q&&(R=Y-R);break}h.reversed===!0?l.time=l.getClip().duration-R:l.time=R,l.timeScale=0;const J=Math.max(0,F);if(l.weight=J,s+=J,l.clampWhenFinished=!1,l.isRunning()||l.play(),this._useclipOffsets){const O=t==0?this._totalOffsetPosition:this._totalOffsetPosition2,q=t==0?this._totalOffsetRotation:this._totalOffsetRotation2;t<1&&(i=1-F),t+=1;const b=this._summedPos.set(0,0,0),T=this._tempPos.set(0,0,0),V=this._summedRot.identity(),AA=this._tempRot.identity(),sA=p.rotation;sA&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp(sA,F));const QA=this._actionOffsets[d];if(QA.hasOffsets)for(let FA=0;FA<H;FA++)QA.rootPositionOffset?T.copy(QA.rootPositionOffset):T.set(0,0,0),T.applyQuaternion(V),this._clipRotQuat&&T.applyQuaternion(this._clipRotQuat),QA.rootQuaternionOffset&&(AA.copy(QA.rootQuaternionOffset),V.multiply(AA)),b.add(T);this._clipRotQuat&&q.multiply(this._clipRotQuat),q.multiply(V),p.position&&b.add(p.position),O.add(b)}}}if(this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,i),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,i)),this.__mixerError===void 0&&(Qn||pe())&&((C=(n=this._animator)==null?void 0:n.runtimeAnimatorController)!=null&&C.mixer)&&this.mixer!==((B=(a=this._animator)==null?void 0:a.runtimeAnimatorController)==null?void 0:B.mixer)&&(this.__mixerError=!0,console.error("AnimationTrack mixer is not shared with the animator controller - this might result in the timeline to not animate properly. Please report a bug to the Needle Engine team!",this)),(Q=this._animator)!=null&&Q.runtimeAnimatorController){const d=Math.max(0,1-s);(c=(E=this._animator)==null?void 0:E.runtimeAnimatorController)==null||c.update(d)}else this.mixer.update(e)}createRotationInterpolant(e,t,i){var n;const I=i.createInterpolant.bind(i),o=new kA;this.ensureTrackOffsets();const s=(n=this.trackOffset)==null?void 0:n.rotation;i.createInterpolant=()=>{const C=I(),a=C.evaluate.bind(C);return C.evaluate=B=>{var E;const Q=a(B);if(o.set(Q[0],Q[1],Q[2],Q[3]),o.premultiply(this._totalOffsetRotation),s&&o.premultiply(s),this.director.animationCallbackReceivers)for(const c of this.director.animationCallbackReceivers)(E=c==null?void 0:c.onTimelineRotation)==null||E.call(c,this.director,this.target,B,o);return Q[0]=o.x,Q[1]=o.y,Q[2]=o.z,Q[3]=o.w,Q},C}}createPositionInterpolant(e,t,i){var a,B;const I=i.createInterpolant.bind(i),o=new y;this.ensureTrackOffsets();const s=(a=this.trackOffset)==null?void 0:a.rotation,n=(B=this.trackOffset)==null?void 0:B.position;let C;i.createInterpolant=()=>{const Q=I(),E=Q.evaluate.bind(Q);return Q.evaluate=c=>{var h,l,p;const d=E(c);if(o.set(d[0],d[1],d[2]),t.removeStartOffset&&(C===void 0?(C=null,C=(l=(h=this._actionOffsets.find(u=>u.clip===e))==null?void 0:h.rootStartPosition)==null?void 0:l.clone()):C!=null&&C.isVector3&&o.sub(C)),o.applyQuaternion(this._totalOffsetRotation),o.add(this._totalOffsetPosition),s&&o.applyQuaternion(s),n&&(o.x-=n.x,o.y+=n.y,o.z+=n.z),this.director.animationCallbackReceivers)for(const u of this.director.animationCallbackReceivers)(p=u==null?void 0:u.onTimelinePosition)==null||p.call(u,this.director,this.target,c,o);return d[0]=o.x,d[1]=o.y,d[2]=o.z,d},Q}}}const rgA=IA("mutetimeline"),dE=class extends Cu{constructor(){super(...arguments);r(this,"models",[]);r(this,"listener");r(this,"audio",[]);r(this,"audioContextTimeOffset",[]);r(this,"lastTime",0);r(this,"audioSource");r(this,"_audioLoader",null);r(this,"_playableDirectorResumed",!1)}getAudioFilePath(e){const t=this.director.sourceId;return bC(t,e)}onAllowAudioChanged(e){for(let t=0;t<this.models.length;t++){const i=this.models[t];this.audio[t].setVolume(e?i.asset.volume:0)}}addModel(e){const t=new XR(this.listener);this.audio.push(t);const i=e;i._didTriggerPlay=!1,this.models.push(i)}onDisable(){for(const e of this.audio)e.isPlaying&&e.stop();for(const e of this.models)e._didTriggerPlay=!1}onDestroy(){for(const e of this.audio)e.source&&(e==null||e.disconnect());this.audio.length=0}onMuteChanged(){if(this.muted)for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t!=null&&t.isPlaying&&t.stop()}}stop(){for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t!=null&&t.isPlaying&&t.stop()}for(const e of this.models)e._didTriggerPlay=!1}onPauseChanged(){for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t!=null&&t.isPlaying&&t.stop()}this._playableDirectorResumed=this.director.isPlaying}evaluate(e){if(rgA||this.track.muted||this.director.speed<0)return;const t=this.director.context.application.muted,i=this._playableDirectorResumed;this._playableDirectorResumed=!1;const I=t?.1:0;for(let o=0;o<this.models.length;o++){const s=this.models[o],n=this.audio[o],C=s.asset;if((!n||!n.buffer)&&this.isInTimeRange(s,e-1,e+1)&&this.handleAudioLoading(s,n),hi.userInteractionRegistered!==!1&&!(n===null||!n.buffer))if(n.playbackRate=this.director.context.time.timeScale*this.director.speed,n.loop=C.loop,e>=s.start&&e<=s.end&&e<this.director.duration){if(!n.isPlaying||!this.director.isPlaying)(i||!s._didTriggerPlay&&this.lastTime<e)&&(s.duration*s.timeScale>.3?n.offset=s.clipIn+(e-s.start)*s.timeScale:n.offset=0,Qn&&console.log("Timeline Audio ("+this.track.name+") play with offset "+n.offset+" - "+s.asset.clip),n.play(I),s._didTriggerPlay=!0);else{const B=s.clipIn+(e-s.start)*s.timeScale,Q=n.context.currentTime-n._startedAt+n.offset;Math.abs(B-Q)>.3&&(n.offset=B,n.stop(),n.play(I))}let a=C.volume;if(this.track.volume!==void 0&&(a*=this.track.volume),t&&(a=0),s.easeInDuration>0){const B=Math.min((e-s.start)/s.easeInDuration,1);a*=B}if(s.easeOutDuration>0){const B=Math.min((s.end-e)/s.easeOutDuration,1);a*=B}n.setVolume(a*this.director.weight)}else s._didTriggerPlay=!1,this.director.isPlaying&&n.isPlaying&&n.stop()}this.lastTime=e}loadAudio(e,t=0,i=0){let I=null;const o=e-i,s=e+t;for(const n of this.models)if(this.isInTimeRange(n,o,s)){const C=this.audio[this.models.indexOf(n)],a=this.handleAudioLoading(n,C);a!==null&&(I===null&&(I=[]),I.push(a))}return I!==null?Promise.all(I):null}isInTimeRange(e,t,i){return t<=e.start&&i>=e.end||t>=e.start&&t<=e.end||i>=e.start&&i<=e.end}static dispose(){dE._audioBuffers.clear()}handleAudioLoading(e,t){this._audioLoader||(this._audioLoader=new OD);const i=this.getAudioFilePath(e.asset.clip);if(dE._audioBuffers.get(i)){const o=dE._audioBuffers.get(i);return o.then(s=>{s&&t.setBuffer(s)}),o}Qn&&console.warn("LOAD audio track",i,this.director.sourceId);const I=new Promise((o,s)=>{this._audioLoader.load(i,n=>{t.setBuffer(n),o(n)},void 0,n=>{console.error("Error loading audio",n),o(null)})});return dE._audioBuffers.set(i,I),I}};let pB=dE;r(pB,"_audioBuffers",new Map);class od extends Cu{constructor(){super(...arguments);r(this,"models",[]);r(this,"didTrigger",[]);r(this,"receivers",[])}evaluate(e){var i;if(this.track.muted)return;const t=this.director.context.time.deltaTime*1.5;for(let I=0;I<this.models.length;I++){const o=this.models[I],s=this.didTrigger[I],n=o.time-e;let C=!1;if(o.retroActive)C=n<=1e-6;else{const a=Math.abs(n);(a===0||a>=1e-5&&a<t)&&(C=!0)}if(C){if(!s)if(Qn&&console.log("Trigger signal",e,o.time,o),this.didTrigger[I]=!0,((i=this.receivers)==null?void 0:i.length)<=0)dc.invoke(o.asset);else for(const a of this.receivers)a&&a.invoke(o.asset)}else o.emitOnce||(this.didTrigger[I]=!1)}}}class BS extends Cu{constructor(){super(...arguments);r(this,"models",[]);r(this,"timelines",[]);r(this,"_previousActiveModel",null)}resolveSourceObjects(e){for(let t=this.models.length-1;t>=0;t--){const I=this.models[t].asset;if(!I.sourceObject||typeof I.sourceObject!="object"){console.log("no source object, removing model",t,I),this.models.splice(t,1);continue}else{const o=nA.getComponent(I.sourceObject,mC);this.timelines.push(o),o&&I.updateDirector&&(o.playOnAwake=!1)}}}evaluate(e){var t;this._previousActiveModel=null;for(let i=0;i<this.models.length;i++){const I=this.models[i],o=I.asset;if(e>=I.start&&e<=I.end){this._previousActiveModel=I;const s=this.getClipTime(e,I);if(o.controlActivation){const n=o.sourceObject;n.visible=!0}if(o.updateDirector){const n=this.timelines[i];n&&(n.isPlaying&&n.pause(),n.time=s,n.evaluate())}}else{const s=(t=this._previousActiveModel)==null?void 0:t.asset;if(o.controlActivation){const n=o.sourceObject;(s==null?void 0:s.sourceObject)!==n&&(n.visible=!1)}}}}}const YQ=IA("debugtimeline"),Wy=class extends UA{constructor(){super(...arguments);r(this,"playableAsset");r(this,"playOnAwake");r(this,"extrapolationMode",1);r(this,"waitForAudio",!0);r(this,"_visibilityChangeEvt");r(this,"_clonedPlayableAsset",!1);r(this,"_speed",1);r(this,"_guidsMap");r(this,"_isPlaying",!1);r(this,"_internalUpdateRoutine");r(this,"_isPaused",!1);r(this,"_isStopping",!1);r(this,"_time",0);r(this,"_duration",0);r(this,"_weight",1);r(this,"_animationTracks",[]);r(this,"_audioTracks",[]);r(this,"_signalTracks",[]);r(this,"_controlTracks",[]);r(this,"_customTracks",[]);r(this,"_allTracks",[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks]);r(this,"animationCallbackReceivers",[])}static registerCreateTrack(e,t){this.createTrackFunctions[e]=t}get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(e){typeof e=="number"&&!Number.isNaN(e)?this._time=e:(YQ||ZI())&&console.error("INVALID TIMELINE.TIME VALUE",e,this.name)}get duration(){return this._duration}set duration(e){this._duration=e}get weight(){return this._weight}set weight(e){this._weight=e}get speed(){return this._speed}set speed(e){this._speed=e}awake(){var e,t,i;YQ&&console.log(this,(e=this.playableAsset)==null?void 0:e.tracks),this.rebuildGraph(),this.isValid()||console.warn("PlayableDirector is not valid",this.playableAsset,(t=this.playableAsset)==null?void 0:t.tracks,Array.isArray((i=this.playableAsset)==null?void 0:i.tracks),this)}onEnable(){var e,t,i;for(const I of this._audioTracks)(e=I.onEnable)==null||e.call(I);for(const I of this._customTracks)(t=I.onEnable)==null||t.call(I);for(const I of this._animationTracks)(i=I.onEnable)==null||i.call(I);this.playOnAwake&&this.play(),this._visibilityChangeEvt||(this._visibilityChangeEvt=()=>{switch(document.visibilityState){case"hidden":this.setAudioTracksAllowPlaying(!1);break;case"visible":this.setAudioTracksAllowPlaying(!0);break}}),window.addEventListener("visibilitychange",this._visibilityChangeEvt)}onDisable(){var e,t,i;this.stop();for(const I of this._audioTracks)(e=I.onDisable)==null||e.call(I);for(const I of this._customTracks)(t=I.onDisable)==null||t.call(I);for(const I of this._animationTracks)(i=I.onDisable)==null||i.call(I);this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){var e;for(const t of this._allTracks)for(const i of t)(e=i.onDestroy)==null||e.call(i)}rebuildGraph(){this.isValid()&&(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}async play(){if(!this.isValid())return;const e=this._isPaused==!0;if(this._isPaused=!1,!this._isPlaying){if(this._isPlaying=!0,e&&this.invokePauseChangedMethodsOnTracks(),this.waitForAudio){const t=[];for(const i of this._audioTracks){const I=i.loadAudio(this._time,1,0);I&&t.push(I)}if(t.length>0&&(await Promise.all(t),!this._isPlaying))return;for(;this._audioTracks.length>0&&this._isPlaying&&!hi.userInteractionRegistered&&this.waitForAudio;)await Ns(200)}this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate(),zi.LateUpdate)}}pause(){this.isValid()&&(this._isPlaying=!1,!this._isPaused&&(this._isPaused=!0,this.internalEvaluate(),this.invokePauseChangedMethodsOnTracks(),this.invokeStateChangedMethodsOnTracks()))}stop(){this._isStopping=!0;for(const i of this._audioTracks)i.stop();const e=this._isPaused==!0,t=this._isPlaying;this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.internalEvaluate(),e&&this.invokePauseChangedMethodsOnTracks()),this._isPlaying=!1,this._isPaused=!1,e&&!t&&this.invokePauseChangedMethodsOnTracks(),t&&this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine&&this.stopCoroutine(this._internalUpdateRoutine),this._internalUpdateRoutine=null,this._isStopping=!1}evaluate(){this.internalEvaluate(!0)}isValid(){return this.playableAsset&&this.playableAsset.tracks&&Array.isArray(this.playableAsset.tracks)}*forEachTrack(){for(const e of this._allTracks)for(const t of e)yield t}get audioTracks(){return this._audioTracks}resolveGuids(e){this._guidsMap=e}invokePauseChangedMethodsOnTracks(){var e;for(const t of this.forEachTrack())(e=t.onPauseChanged)==null||e.call(t)}invokeStateChangedMethodsOnTracks(){var e;for(const t of this.forEachTrack())(e=t.onStateChanged)==null||e.call(t,this._isPlaying)}*internalUpdate(){for(;this._isPlaying&&this.activeAndEnabled;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime*this.speed,this.internalEvaluate()),yield}internalEvaluate(e=!1){if(!this.isValid())return;let t=this._time;switch(this.extrapolationMode){case 0:this._speed>0?t=Math.min(t,this._duration):this._speed<0&&(t=Math.max(t,0)),this._time=t;break;case 1:t%=this._duration,this._time=t;break;case 2:if(t>this._duration){this.stop();return}break}const i=this._time;for(const I of this.playableAsset.tracks)if(!I.muted)switch(I.type){case no.Activation:if(!e&&!this._isPlaying)continue;for(let o=0;o<I.outputs.length;o++){const s=I.outputs[o];if(typeof s=="object"){let n=!1;if(I.clips)for(const a of I.clips)a.start<=i&&i<=a.end&&(n=!0);const C=s;C.visible!==void 0&&C.visible!==n&&(C.visible=n,YQ&&console.warn(this.name,"set ActivationTrack-"+o,C.name,n,i))}}break}if(!this._isStopping)for(const I of this._animationTracks)I.evaluate(i);for(const I of this._audioTracks)I.evaluate(i);for(const I of this._signalTracks)I.evaluate(i);for(const I of this._controlTracks)I.evaluate(i);for(const I of this._customTracks)I.evaluate(i)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=vd(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;const e=this.findRoot(this.gameObject);for(const t of this.playableAsset.tracks){for(let i=t.outputs.length-1;i>=0;i--){let I=t.outputs[i];if(typeof I=="string"){this._guidsMap&&this._guidsMap[I]&&(I=this._guidsMap[I]);const o=nA.findByGuid(I,e);o===null||typeof o!="object"?(t.outputs.splice(i,1),console.warn("Failed to resolve binding",I,t.name,t.type)):(YQ&&console.log("Resolved binding",I,"to",o),t.outputs[i]=o)}else if(I===null){if(t.outputs.splice(i,1),Wy.createTrackFunctions[t.type])continue;t.type!==no.Audio&&t.type!==no.Control&&t.type!==no.Marker&&t.type!==no.Signal&&console.warn("Missing binding",I,t.name,t.type,this.name,this.playableAsset.name)}}if(t.type===no.Control&&t.clips)for(let i=0;i<t.clips.length;i++){const I=t.clips[i];let o=I.asset.sourceObject;if(typeof o=="string"){this._guidsMap&&this._guidsMap[o]&&(o=this._guidsMap[o]);const s=nA.findByGuid(o,e);s===null||typeof s!="object"?console.warn("Failed to resolve sourceObject binding",o,t.name,I):(YQ&&console.log("Resolved binding",o,"to",s),I.asset.sourceObject=s)}}}}findRoot(e){return e.parent?this.findRoot(e.parent):e}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const e of this.playableAsset.tracks)if(e.muted!==!0){if(e.clips)for(const t of e.clips)t.end>this._duration&&(this._duration=t.end);if(e.markers)for(const t of e.markers)t.time>this._duration&&(this._duration=t.time+.001)}}}setupAndCreateTrackHandlers(){var t,i,I;if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let e=nA.findObjectOfType(_a,this.context);for(const o of this.playableAsset.tracks){const s=o.type,n=Wy.createTrackFunctions[s];if(n!=null){const C=n(this,o);if(typeof C.evaluate=="function"){C.director=this,C.track=o,this._customTracks.push(C);continue}}if(o.type===no.Animation){if(!o.clips||o.clips.length<=0){YQ&&console.warn("Animation track has no clips",o);continue}for(let C=o.outputs.length-1;C>=0;C--){let a=o.outputs[C];if(a instanceof pA){const Q=nA.getOrAddComponent(a,Hg);Q&&(a=Q)}const B=(t=a==null?void 0:a.gameObject)==null?void 0:t.animations;if(B){const Q=new rS;Q.trackOffset=o.trackOffset,Q.director=this,Q.track=o;for(let E=0;E<o.clips.length;E++){const c=o.clips[E],d=c.asset;if(!d){console.error(`Timeline ${this.name}: clip #${E} on track "${o.name}" has no animation data`);continue}const h=d.clip;let l=h;if((typeof l=="string"||typeof l=="number")&&(l=B.find(u=>u.name===h)),!l){console.warn("Could not find animationClip for model",c,o.name,this.name,(i=this.playableAsset)==null?void 0:i.name);continue}a instanceof Hg&&a.runtimeAnimatorController&&(a.__internalDidAwakeAndStart||a.initializeRuntimeAnimatorController(),a.runtimeAnimatorController.mixer||a.runtimeAnimatorController.bind(a),Q.mixer=a.runtimeAnimatorController.mixer),Q.mixer||(Q.mixer=new Kw(a.gameObject)),Q.clips.push(l),Q.mixer.uncacheAction(l),Q.createHooks(c.asset,l);const p=Q.mixer.clipAction(l);Q.actions.push(p),Q.models.push(c)}this._animationTracks.push(Q)}}}else if(o.type===no.Audio){if(!o.clips||o.clips.length<=0)continue;const C=new pB;C.director=this,C.track=o,C.audioSource=o.outputs.find(a=>a instanceof hi),this._audioTracks.push(C),e||(e=(I=this.context.mainCameraComponent)==null?void 0:I.gameObject.addNewComponent(_a)),C.listener=e.listener;for(let a=0;a<o.clips.length;a++){const B=o.clips[a];C.addModel(B)}}else if(o.type===no.Marker){const C=new od;if(C.director=this,C.track=o,o.markers)for(const a of o.markers)switch(a.type){case mN.Signal:C.models.push(a),C.didTrigger.push(!1);break}if(C!==null&&C.models.length>0){const a=nA.getComponent(this.gameObject,dc);a&&(C.receivers.push(a),this._signalTracks.push(C))}}else if(o.type===no.Signal){const C=new od;if(C.director=this,C.track=o,o.markers)for(const a of o.markers)C.models.push(a),C.didTrigger.push(!1);for(const a of o.outputs)C.receivers.push(a);this._signalTracks.push(C)}else if(o.type===no.Control){const C=new BS;if(C.director=this,C.track=o,o.clips)for(const a of o.clips)C.models.push(a);C.resolveSourceObjects(this.context),this._controlTracks.push(C)}}}setAudioTracksAllowPlaying(e){for(const t of this._audioTracks)t.onAllowAudioChanged(e)}registerAnimationCallback(e){this.animationCallbackReceivers.push(e)}unregisterAnimationCallback(e){const t=this.animationCallbackReceivers.indexOf(e);t!==-1&&this.animationCallbackReceivers.splice(t,1)}};let mC=Wy;r(mC,"createTrackFunctions",{});const cD=Symbol("objectIsAnimatedData");function Dv(g,A,e){if(!g)return;if(g[cD]===void 0){if(!e)return;g[cD]=new Set}const t=g[cD];e?t.add(A):t.has(A)&&t.delete(A)}function BgA(g){if(!g)return!1;const A=g[cD];return A!==void 0&&A.size>0}Bt.registerCallback(vi.ContextCreated,g=>{const A=g.context.domElement.getAttribute("autoplay");if(A!==void 0&&(A===""||A==="true")&&g.files)for(const e of g.files)nA.foreachComponent(e.file.scene,i=>{if(i.enabled!==!1){if(i instanceof qI&&i.playAutomatically||i instanceof Hg||i instanceof mC&&i.playOnAwake===!0)return!0;if(i instanceof qI)return i.playAutomatically=!0,!0;if(i instanceof mC)return i.playOnAwake=!0,!0}},!0)!==!0&&QgA(e.file)});function QgA(g){if(!g||!g.animations)return;for(let e=0;e<g.animations.length;e++){const t=g.animations[e];if(!(!t.tracks||t.tracks.length<=0))for(const i in t.tracks){const I=t.tracks[i],o=I.__objectName??I.name.substring(0,I.name.indexOf("."));let s=g.scene.getObjectByName(o);if(!s&&(s=g.scene.getObjectByProperty("uuid",o),!s))continue;let n=A(s);n||(n=Ya(g.scene,new qI));const C=n.animations=n.animations||[];t.name_animator=n.name,C.indexOf(t)<0&&C.push(t)}}function A(e){var i;if(!e)return;const t=(i=e.userData)==null?void 0:i.components;if(t&&t.length>0)for(let I=0;I<t.length;I++){const o=t[I];if(o instanceof Hg||o instanceof qI)return e}return A(e.parent)}}class EgA{constructor(){r(this,"_context")}get context(){return this._context??Le.Current}get isStateMachineBehaviour(){return!0}}class _l{constructor(A,e,t,i){r(this,"name");r(this,"nameHash");r(this,"normalizedTime");r(this,"length");r(this,"speed");r(this,"action");this.name=A.name,this.nameHash=A.hash,this.normalizedTime=e,this.length=t,this.speed=i,this.action=A.motion.action||null}}function uO(g,A){return{name:"",isLooping:!1,guid:(A==null?void 0:A.generateUUID())??ng.generateUUID(),index:-1,clip:new KI(g,1,[])}}var Da=(g=>(g[g.If=1]="If",g[g.IfNot=2]="IfNot",g[g.Greater=3]="Greater",g[g.Less=4]="Less",g[g.Equals=6]="Equals",g[g.NotEqual=7]="NotEqual",g))(Da||{}),MN=(g=>(g[g.Float=1]="Float",g[g.Int=3]="Int",g[g.Bool=4]="Bool",g[g.Trigger=9]="Trigger",g))(MN||{});const DI=IA("debuganimatorcontroller"),Ef=IA("debugrootmotion");class wo{constructor(A){r(this,"_speed",1);r(this,"normalizedStartOffset",0);r(this,"animator");r(this,"model");r(this,"_mixer");r(this,"_activeState");r(this,"_activeStates",[]);r(this,"rootMotionHandler");this.model=A,DI&&console.log(this)}static createFromClips(A,e={looping:!1,autoTransition:!0,transitionDuration:0}){const t=[];for(let o=0;o<A.length;o++){const s=A[o],n=[];if(e.autoTransition!==!1){const a=e.transitionDuration??0,B=a/s.duration;let Q=o;(e.autoTransition===void 0||e.autoTransition===!0)&&(Q=(o+1)%A.length),n.push({exitTime:1-B,offset:0,duration:a,hasExitTime:!0,destinationState:Q,conditions:[]})}const C={name:s.name,hash:o,motion:{name:s.name,clip:s,isLooping:(e==null?void 0:e.looping)??!1},transitions:n,behaviours:[]};t.push(C)}const i={name:"AnimatorController",guid:new yg(Date.now()).generateUUID(),parameters:[],layers:[{name:"Base Layer",stateMachine:{defaultState:0,states:t}}]};return new wo(i)}play(A,e=-1,t=Number.NEGATIVE_INFINITY,i=0){if(e<0)e=0;else if(e>=this.model.layers.length){console.warn("invalid layer");return}const o=this.model.layers[e].stateMachine;for(const s of o.states)if(s.name===A||s.hash===A){DI&&console.log("transition to ",s),this.transitionTo(s,i,t);return}console.warn("Could not find "+A+" to play")}reset(){this.setStartTransition()}setBool(A,e){var i,I;const t=typeof A=="string"?"name":"hash";return(I=(i=this.model)==null?void 0:i.parameters)==null?void 0:I.filter(o=>o[t]===A).forEach(o=>o.value=e)}getBool(A){var t,i,I;const e=typeof A=="string"?"name":"hash";return((I=(i=(t=this.model)==null?void 0:t.parameters)==null?void 0:i.find(o=>o[e]===A))==null?void 0:I.value)??!1}setFloat(A,e){var I,o;const t=typeof A=="string"?"name":"hash",i=(o=(I=this.model)==null?void 0:I.parameters)==null?void 0:o.filter(s=>s[t]===A);return i.forEach(s=>s.value=e),(i==null?void 0:i.length)>0}getFloat(A){var t,i,I;const e=typeof A=="string"?"name":"hash";return((I=(i=(t=this.model)==null?void 0:t.parameters)==null?void 0:i.find(o=>o[e]===A))==null?void 0:I.value)??0}setInteger(A,e){var i,I;const t=typeof A=="string"?"name":"hash";return(I=(i=this.model)==null?void 0:i.parameters)==null?void 0:I.filter(o=>o[t]===A).forEach(o=>o.value=e)}getInteger(A){var t,i,I;const e=typeof A=="string"?"name":"hash";return((I=(i=(t=this.model)==null?void 0:t.parameters)==null?void 0:i.find(o=>o[e]===A))==null?void 0:I.value)??0}setTrigger(A){var t,i;DI&&console.log("SET TRIGGER",A);const e=typeof A=="string"?"name":"hash";return(i=(t=this.model)==null?void 0:t.parameters)==null?void 0:i.filter(I=>I[e]===A).forEach(I=>I.value=!0)}resetTrigger(A){var t,i;const e=typeof A=="string"?"name":"hash";return(i=(t=this.model)==null?void 0:t.parameters)==null?void 0:i.filter(I=>I[e]===A).forEach(I=>I.value=!1)}getTrigger(A){var t,i,I;const e=typeof A=="string"?"name":"hash";return((I=(i=(t=this.model)==null?void 0:t.parameters)==null?void 0:i.find(o=>o[e]===A))==null?void 0:I.value)??!1}isInTransition(){return this._activeStates.length>1}setSpeed(A){this._speed=A}FindState(A){return this.findState(A)}findState(A){if(!A)return null;if(Array.isArray(this.model.layers)){for(const e of this.model.layers)for(const t of e.stateMachine.states)if(t.name===A||t.hash==A)return t}return null}getCurrentStateInfo(){if(!this._activeState)return null;const A=this._activeState.motion.action;if(!A)return null;const e=this._activeState.motion.clip.duration,t=e<=0?0:Math.abs(A.time/e);return new _l(this._activeState,t,e,this._speed)}get currentAction(){if(!this._activeState)return null;const A=this._activeState.motion.action;return A||null}get context(){var A;return(A=this.animator)==null?void 0:A.context}get mixer(){return this._mixer}bind(A){A?this.animator!==A&&(this.animator=A,this._mixer=new Kw(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;DI&&console.warn("AnimatorController clone()",this.model);const A=vd(this.model,(t,i,I)=>I==null?!0:!(I.type==="Object3D"||I.isObject3D===!0||t2(I)||I.tracks!==void 0||I instanceof wo));return console.assert(A!==this.model),new wo(A)}update(A){var t,i;if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates(A);const e=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&((t=this.rootMotionHandler)==null||t.onBeforeUpdate(A)),this._mixer.update(e),this.animator.applyRootMotion&&((i=this.rootMotionHandler)==null||i.onAfterUpdate(A))}get activeState(){return this._activeState}updateActiveStates(A){for(let e=0;e<this._activeStates.length;e++){const t=this._activeStates[e],i=t.motion;if(!i.action)this._activeStates.splice(e,1),e--;else{const I=i.action;I.weight=A,I.getEffectiveWeight()<=0&&!I.isRunning()&&(DI&&console.debug("REMOVE",t.name,I.getEffectiveWeight(),I.isRunning(),I.isScheduled()),this._activeStates.splice(e,1),e--)}}}setStartTransition(){for(const A of this.model.layers){const e=A.stateMachine;e.defaultState===void 0&&(DI&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",A),e.defaultState=0);const t=e.states[e.defaultState];this.transitionTo(t,0,this.normalizedStartOffset)}}evaluateTransitions(){var I;let A=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;A=!0}const e=this._activeState,t=e.motion.action;for(const o of e.transitions){if(!o.hasExitTime&&o.conditions.length<=0)continue;let s=!0;for(const n of o.conditions)if(!this.evaluateCondition(n)){s=!1;break}if(s)if(t){const n=e.motion.clip.duration,C=n<=0?1:Math.abs(t.time/n);let a=!1;if(o.hasExitTime?t.timeScale>0?a=C>=o.exitTime:t.timeScale<0&&(a=1-C>=o.exitTime):a=!0,a){for(const B of o.conditions){const Q=this.model.parameters.find(E=>E.name===B.parameter);(Q==null?void 0:Q.type)===MN.Trigger&&Q.value&&(Q.value=!1)}t.clampWhenFinished=!0,DI&&console.log("transition to "+o.destinationState,o,C,o.exitTime,o.hasExitTime),this.transitionTo(o.destinationState,o.duration,o.offset);return}}else{this.transitionTo(o.destinationState,o.duration,o.offset);return}}if(t){let o=e.speed??1;e.speedParameter&&(o*=this.getFloat(e.speedParameter)),o!==void 0&&(t.timeScale=o*this._speed)}let i=!1;if(e.motion.isLooping&&t&&(t.time>=t.getClip().duration?(i=!0,t.reset(),t.time=0,t.play()):t.time<=0&&t.timeScale<0&&(i=!0,t.reset(),t.time=t.getClip().duration,t.play())),!i&&e&&!A&&t&&this.animator&&e.behaviours){const o=t==null?void 0:t.getClip().duration,s=t.time/o,n=new _l(this._activeState,s,o,this._speed);for(const C of e.behaviours)C.instance&&((I=C.instance.onStateUpdate)==null||I.call(C.instance,this.animator,n,0))}}getState(A,e){return typeof A=="number"&&(A==-1&&(A=this.model.layers[e].stateMachine.defaultState,A===void 0&&(DI&&console.warn("AnimatorController default state is undefined: ",this.model,"Layer: "+e),A=0)),A=this.model.layers[e].stateMachine.states[A]),A}transitionTo(A,e,t){var C,a,B,Q,E,c,d,h;if(!this.animator)return;const i=0;if(A=this.getState(A,i),!(A!=null&&A.motion)||!A.motion.clip||!(A.motion.clip instanceof KI))return;const I=this._activeState===A;if(I){const l=A.motion;if(!l.action_loopback&&l.clip){const p=this.rootMotionHandler?this.animator.gameObject.matrix.clone():null;this._mixer.uncacheAction(l.clip,this.animator.gameObject),p&&p.decompose(this.animator.gameObject.position,this.animator.gameObject.quaternion,this.animator.gameObject.scale),l.action_loopback=this.createAction(l.clip)}}if((C=this._activeState)!=null&&C.behaviours&&this._activeState.motion.action){const l=(a=this._activeState)==null?void 0:a.motion.clip.duration,p=this._activeState.motion.action.time/l,u=new _l(this._activeState,p,l,this._speed);for(const f of this._activeState.behaviours)(Q=(B=f.instance)==null?void 0:B.onStateExit)==null||Q.call(f.instance,this.animator,u,i)}const o=(E=this._activeState)==null?void 0:E.motion.action;o&&o.fadeOut(e),I&&(A.motion.action=A.motion.action_loopback,A.motion.action_loopback=o);const s=this._activeState;this._activeState=A;const n=(c=A.motion)==null?void 0:c.action;if(n){if(t=Math.max(0,Math.min(1,t)),A.cycleOffsetParameter){let p=this.getFloat(A.cycleOffsetParameter);typeof p=="number"?(p<0&&(p+=1),t+=p,t%=1):DI&&console.warn("AnimatorController cycle offset parameter is not a number",A.cycleOffsetParameter)}else typeof A.cycleOffset=="number"&&(t+=A.cycleOffset,t%=1);n.isRunning()&&n.stop(),n.reset(),n.enabled=!0;const l=A.motion.clip.duration;if(n.time=I?0:t*l,n.timeScale<0&&(n.time=l-n.time),n.clampWhenFinished=!0,n.setLoop(Rh,0),e>0?n.fadeIn(e):n.weight=1,n.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(n),this._activeStates.includes(A)||this._activeStates.push(A),this._activeState.behaviours){const p=new _l(A,t,l,this._speed);for(const u of this._activeState.behaviours)(h=(d=u.instance)==null?void 0:d.onStateEnter)==null||h.call(u.instance,this.animator,p,i)}}else DI&&(A.__warned_no_motion||(A.__warned_no_motion=!0,console.warn("No action",A.motion,this)));DI&&console.log("TRANSITION FROM "+(s==null?void 0:s.name)+" TO "+A.name,e,o,n,n==null?void 0:n.getEffectiveTimeScale(),n==null?void 0:n.getEffectiveWeight(),n==null?void 0:n.isRunning(),n==null?void 0:n.isScheduled(),n==null?void 0:n.paused)}createAction(A){var t,i;if(this._mixer.existingAction(A)&&this._mixer.uncacheAction(A,(t=this.animator)==null?void 0:t.gameObject),(i=this.animator)!=null&&i.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new cgA(this));const I=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,I,A)}else return this._mixer.clipAction(A)}evaluateCondition(A){const e=this.model.parameters.find(t=>t.name===A.parameter);if(!e)return!1;switch(A.mode){case Da.If:return e.value===!0;case Da.IfNot:return e.value===!1;case Da.Greater:return e.value>A.threshold;case Da.Less:return e.value<A.threshold;case Da.Equals:return e.value===A.threshold;case Da.NotEqual:return e.value!==A.threshold}return!1}createActions(A){var e,t,i,I;DI&&console.log("AnimatorController createActions",this.model);for(const o of this.model.layers){const s=o.stateMachine;for(let n=0;n<s.states.length;n++){const C=s.states[n];C.transitions||(C.transitions=[]);for(const a of C.transitions)a.conditions||(a.conditions=[]);if(C.motion||(C.motion=uO(C.name)),this.animator&&C.motion.clips){const a=(e=C.motion.clips)==null?void 0:e.find(B=>{var Q,E;return B.node.name===((E=(Q=this.animator)==null?void 0:Q.gameObject)==null?void 0:E.name)});a?C.motion.clip=a.clip:(DI||pe())&&console.warn('Could not find clip for animator "'+((i=(t=this.animator)==null?void 0:t.gameObject)==null?void 0:i.name)+'"',C.motion.clips.map(B=>B.node.name))}if(!C.motion.clip){const a=new KI(void 0,void 0,[]);C.motion.clip=a}if((I=C.motion)!=null&&I.clip){const a=C.motion.clip;if(a instanceof KI){const B=this.createAction(a);C.motion.action=B}else(DI||pe())&&console.warn("No valid animationclip assigned",C)}if(C.behaviours&&Array.isArray(C.behaviours))for(const a of C.behaviours){if(!(a!=null&&a.typeName))continue;const B=X.get(a.typeName),Q=new B;Q.isStateMachineBehaviour&&(Q._context=this.context??void 0,TE(Q,a.properties),a.instance=Q),DI&&console.log("Created animator controller behaviour",C.name,a.typeName,a.properties,Q)}}}}*enumerateActions(){if(this.model.layers)for(const A of this.model.layers){const e=A.stateMachine;for(let t=0;t<e.states.length;t++){const i=e.states[t];i!=null&&i.motion&&(i.motion.action&&(yield i.motion.action),i.motion.action_loopback&&(yield i.motion.action_loopback))}}}}class yv{constructor(A,e){r(this,"track");r(this,"createdInterpolant");r(this,"originalEvaluate");r(this,"customEvaluate");this.track=A;const t=A,i=t.createInterpolant.bind(A);t.createInterpolant=()=>(t.createInterpolant=i,this.createdInterpolant=i(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=I=>{if(!this.originalEvaluate)return;const o=this.originalEvaluate(I);return e(I,o)},this.createdInterpolant.evaluate=this.customEvaluate,this.createdInterpolant)}dispose(){this.createdInterpolant&&this.originalEvaluate&&(this.createdInterpolant.evaluate=this.originalEvaluate),this.track=void 0,this.createdInterpolant=null,this.originalEvaluate=void 0,this.customEvaluate=void 0}}const Ig=class{constructor(A,e,t,i,I){r(this,"_action");r(this,"root");r(this,"clip");r(this,"positionWrapper",null);r(this,"rotationWrapper",null);r(this,"context");r(this,"positionChange",new y);r(this,"rotationChange",new kA);r(this,"_prevTime",0);if(this.context=A,this.root=e,this.clip=t,Ig.firstKeyframeRotation[this.cacheId]||(Ig.firstKeyframeRotation[this.cacheId]=new kA),I){const o=I.values;Ig.firstKeyframeRotation[this.cacheId].set(o[0],o[1],o[2],o[3])}Ig.spaceRotation[this.cacheId]||(Ig.spaceRotation[this.cacheId]=new kA),Ig.effectiveSpaceRotation[this.cacheId]||(Ig.effectiveSpaceRotation[this.cacheId]=new kA),Ig.clipOffsetRotation[this.cacheId]=new kA,I&&Ig.clipOffsetRotation[this.cacheId].set(I.values[0],I.values[1],I.values[2],I.values[3]).invert(),this.handlePosition(t,i),this.handleRotation(t,I)}set action(A){this._action=A}get action(){return this._action}get cacheId(){return this.root.uuid}onStart(A){if(A.getClip()!==this.clip)return;Ig.lastObjRotation[this.cacheId]||(Ig.lastObjRotation[this.cacheId]=this.root.quaternion.clone());const e=Ig.lastObjRotation[this.cacheId];if(Ig.spaceRotation[this.cacheId].copy(e),Ef){const t=new jt().setFromQuaternion(e);console.log("START",this.clip.name,te.toDegrees(t.y),this.root.position.z)}}getClipRotationOffset(){return Ig.clipOffsetRotation[this.cacheId]}handlePosition(A,e){if(e){const t=this.root;Ef&&t.add(new $o),Ig.lastObjPosition[this.cacheId]||(Ig.lastObjPosition[this.cacheId]=this.root.position.clone());const i=new y,I=new y;this.positionWrapper=new yv(e,(o,s)=>{const n=this.action.getEffectiveWeight();return Ef&&t.position.length()>8&&t.position.set(0,t.position.y,0),o>this._prevTime&&(i.set(s[0],s[1],s[2]),i.sub(I),i.multiplyScalar(n),i.applyQuaternion(this.getClipRotationOffset()),i.applyQuaternion(t.quaternion),this.positionChange.copy(i)),I.fromArray(s),this._prevTime=o,s[0]=0,s[1]=0,s[2]=0,s})}}handleRotation(A,e){if(e){if(Ef){const o=e.values,s=new jt().setFromQuaternion(new kA(o[0],o[1],o[2],o[3]));console.log(A.name,e.name,"FIRST ROTATION IN TRACK",te.toDegrees(s.y));const n=e.values.length-4,C=new kA().set(o[n],o[n+1],o[n+2],o[n+3]),a=new jt().setFromQuaternion(C);console.log(A.name,e.name,"LAST ROTATION IN TRACK",te.toDegrees(a.y))}let t=0;const i=new kA,I=new kA;this.rotationWrapper=new yv(e,(o,s)=>(o>t&&(I.set(s[0],s[1],s[2],s[3]),i.invert(),I.multiply(i),this.rotationChange.copy(I)),i.fromArray(s),t=o,s[0]=0,s[1]=0,s[2]=0,s[3]=1,s))}}onBeforeUpdate(A){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(A){return!this.action||(A*=this.action.getEffectiveWeight(),A<=0)?!1:(this.positionChange.multiplyScalar(A),this.rotationChange.slerp(Ig.identityQuaternion,1-A),!0)}};let js=Ig;r(js,"lastObjPosition",{}),r(js,"lastObjRotation",{}),r(js,"firstKeyframeRotation",{}),r(js,"spaceRotation",{}),r(js,"effectiveSpaceRotation",{}),r(js,"clipOffsetRotation",{}),r(js,"identityQuaternion",new kA);class cgA{constructor(A){r(this,"controller");r(this,"handler",[]);r(this,"root");r(this,"basePosition",new y);r(this,"baseQuaternion",new kA);r(this,"baseRotation",new jt);r(this,"summedPosition",new y);r(this,"summedRotation",new kA);this.controller=A}createClip(A,e,t){this.root=e,e&&"name"in e&&e.name;const i=this.findRootTrack(t,".position"),I=this.findRootTrack(t,".quaternion"),o=new js(this.controller.context,e,t,i,I);this.handler.push(o);const s=A.clipAction(t);return o.action=s,s}onStart(A){for(const e of this.handler)e.onStart(A)}onBeforeUpdate(A){this.basePosition.copy(this.root.position),this.baseQuaternion.copy(this.root.quaternion);for(const e of this.handler)e.onBeforeUpdate(A)}onAfterUpdate(A){if(!(A<=0)){this.root.position.copy(this.basePosition),this.root.quaternion.copy(this.baseQuaternion),this.summedPosition.set(0,0,0),this.summedRotation.set(0,0,0,1);for(const e of this.handler)e.onAfterUpdate(A)&&(this.summedPosition.add(e.positionChange),this.summedRotation.multiply(e.rotationChange));this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation)}}findRootTrack(A,e){const t=A.tracks;if(!t)return null;for(const i of t)if(i.name.endsWith(e))return i;return null}}class lgA extends Rn{onSerialize(A,e){}onDeserialize(A,e){if(e.type===wo&&(A==null?void 0:A.__type)==="AnimatorController")return new wo(A)}}new lgA(wo);var hgA=Object.defineProperty,dgA=Object.getOwnPropertyDescriptor,QS=(g,A,e,t)=>{for(var i=t>1?void 0:t?dgA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&hgA(A,e,i),i};const bo=IA("debuganimator");class Hg extends UA{constructor(){super(...arguments);r(this,"applyRootMotion",!1);r(this,"hasRootMotion",!1);r(this,"keepAnimatorControllerStateOnDisable",!1);r(this,"_parametersAreDirty",!1);r(this,"_isDirty",!1);r(this,"speed",1);r(this,"normalizedStartOffset",0);r(this,"_animatorController",null);r(this,"_initializeWithRuntimeAnimatorController")}set runtimeAnimatorController(e){var t;this._animatorController&&this._animatorController.model===e||(e?e instanceof wo?(e.animator&&e.animator!==this&&(console.warn("AnimatorController can not be bound to multiple animators",(t=e.model)==null?void 0:t.name),e.model||console.error("AnimatorController has no model"),e=new wo(e.model)),this._animatorController=e,this._animatorController.bind(this)):(bo&&console.log("Assign animator controller",e,this),this._animatorController=new wo(e),this.__didAwake&&this._animatorController.bind(this)):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}getCurrentStateInfo(){var e;return(e=this.runtimeAnimatorController)==null?void 0:e.getCurrentStateInfo()}get currentAction(){var e;return((e=this.runtimeAnimatorController)==null?void 0:e.currentAction)||null}get parametersAreDirty(){return this._parametersAreDirty}get isDirty(){return this._isDirty}Play(e,t=-1,i=Number.NEGATIVE_INFINITY,I=0){this.play(e,t,i,I)}play(e,t=-1,i=Number.NEGATIVE_INFINITY,I=0){var o;(o=this.runtimeAnimatorController)==null||o.play(e,t,i,I),this._isDirty=!0}Reset(){this.reset()}reset(){var e;(e=this._animatorController)==null||e.reset(),this._isDirty=!0}SetBool(e,t){this.setBool(e,t)}setBool(e,t){var i,I;bo&&console.log("setBool",e,t),((i=this.runtimeAnimatorController)==null?void 0:i.getBool(e))!==t&&(this._parametersAreDirty=!0),(I=this.runtimeAnimatorController)==null||I.setBool(e,t)}GetBool(e){return this.getBool(e)}getBool(e){var i;const t=((i=this.runtimeAnimatorController)==null?void 0:i.getBool(e))??!1;return bo&&console.log("getBool",e,t),t}toggleBool(e){this.setBool(e,!this.getBool(e))}SetFloat(e,t){this.setFloat(e,t)}setFloat(e,t){var i,I;((i=this.runtimeAnimatorController)==null?void 0:i.getFloat(e))!==t&&(this._parametersAreDirty=!0),bo&&console.log("setFloat",e,t),(I=this.runtimeAnimatorController)==null||I.setFloat(e,t)}GetFloat(e){return this.getFloat(e)}getFloat(e){var i;const t=((i=this.runtimeAnimatorController)==null?void 0:i.getFloat(e))??-1;return bo&&console.log("getFloat",e,t),t}SetInteger(e,t){this.setInteger(e,t)}setInteger(e,t){var i,I;((i=this.runtimeAnimatorController)==null?void 0:i.getInteger(e))!==t&&(this._parametersAreDirty=!0),bo&&console.log("setInteger",e,t),(I=this.runtimeAnimatorController)==null||I.setInteger(e,t)}GetInteger(e){return this.getInteger(e)}getInteger(e){var i;const t=((i=this.runtimeAnimatorController)==null?void 0:i.getInteger(e))??-1;return bo&&console.log("getInteger",e,t),t}SetTrigger(e){this.setTrigger(e)}setTrigger(e){var t;this._parametersAreDirty=!0,bo&&console.log("setTrigger",e),(t=this.runtimeAnimatorController)==null||t.setTrigger(e)}ResetTrigger(e){this.resetTrigger(e)}resetTrigger(e){var t;this._parametersAreDirty=!0,bo&&console.log("resetTrigger",e),(t=this.runtimeAnimatorController)==null||t.resetTrigger(e)}GetTrigger(e){this.getTrigger(e)}getTrigger(e){var i;const t=(i=this.runtimeAnimatorController)==null?void 0:i.getTrigger(e);return bo&&console.log("getTrigger",e,t),t}IsInTransition(){return this.isInTransition()}isInTransition(){var e;return((e=this.runtimeAnimatorController)==null?void 0:e.isInTransition())??!1}SetSpeed(e){return this.setSpeed(e)}setSpeed(e){var t;e!==this.speed&&(bo&&console.log("setSpeed",e),this.speed=e,(t=this._animatorController)==null||t.setSpeed(e))}set minMaxSpeed(e){this.speed=te.lerp(e.x,e.y,Math.random())}set minMaxOffsetNormalized(e){this.normalizedStartOffset=te.lerp(e.x,e.y,Math.random()),this.runtimeAnimatorController&&(this.runtimeAnimatorController.normalizedStartOffset=this.normalizedStartOffset)}awake(){bo&&console.log("ANIMATOR",this.name,this),this.gameObject&&this.initializeRuntimeAnimatorController()}initializeRuntimeAnimatorController(e=!1){const t=e||this.runtimeAnimatorController!==this._initializeWithRuntimeAnimatorController;if(this.runtimeAnimatorController&&t){const i=this.runtimeAnimatorController.clone();this._initializeWithRuntimeAnimatorController=i,i?(console.assert(this.runtimeAnimatorController!==i),this.runtimeAnimatorController=i,console.assert(this.runtimeAnimatorController===i),this.runtimeAnimatorController.bind(this),this.runtimeAnimatorController.setSpeed(this.speed),this.runtimeAnimatorController.normalizedStartOffset=this.normalizedStartOffset):console.warn("Could not clone animator controller",this.runtimeAnimatorController)}}onDisable(){var e;this.keepAnimatorControllerStateOnDisable||(e=this._animatorController)==null||e.reset()}onBeforeRender(){this._isDirty=!1,this._parametersAreDirty=!1,!BgA(this.gameObject)&&this._animatorController&&this._animatorController.update(1)}}QS([D()],Hg.prototype,"applyRootMotion",2);QS([D()],Hg.prototype,"hasRootMotion",2);QS([D()],Hg.prototype,"keepAnimatorControllerStateOnDisable",2);QS([D()],Hg.prototype,"runtimeAnimatorController",1);const nB=IA("debugusdzanimation"),Lk=IA("debugusdzanimationserialization");class ES{constructor(A,e,t){r(this,"_start");r(this,"ext");r(this,"root");r(this,"clip");this.ext=A,this.root=e,this.clip=t}get start(){return this._start===void 0&&(this._start=this.ext.getStartTime01(this.root,this.clip)),this._start}get duration(){return this.clip.duration}}const EK=class{constructor(A,e,t){r(this,"clip");r(this,"pos");r(this,"rot");r(this,"scale");r(this,"root");r(this,"target");r(this,"duration",0);r(this,"useRootMotion",!1);this.root=A,this.target=e,this.clip=t,t?this.duration=t.duration:this.duration=EK.restPoseClipDuration;const i=nA.getComponent(A,Hg);i&&(this.useRootMotion=i.applyRootMotion)}get frameRate(){return 60}addTrack(A){if(!this.clip){console.error("This is a rest clip but you're trying to add tracks to it โ€“ this is likely a bug");return}A.name.endsWith("position")&&(this.pos=A),A.name.endsWith("quaternion")&&(this.rot=A),A.name.endsWith("scale")&&(this.scale=A)}getFrames(){var A,e,t,i,I,o;return this.clip?Math.max(((e=(A=this.pos)==null?void 0:A.times)==null?void 0:e.length)??0,((i=(t=this.rot)==null?void 0:t.times)==null?void 0:i.length)??0,((o=(I=this.scale)==null?void 0:I.times)==null?void 0:o.length)??0):2}getDuration(){return this.duration}getSortedTimesArray(A=!0,e=!0,t=!0){var n,C,a;if(!this.clip)return[0,this.duration];const i=(n=this.pos)==null?void 0:n.times,I=(C=this.rot)==null?void 0:C.times,o=(a=this.scale)==null?void 0:a.times,s=[];if(A&&i)for(const B of i)s.push(B);if(e&&I)for(const B of I)s.push(B);if(t&&o)for(const B of o)s.push(B);return s.includes(0)||s.push(0),s.sort((B,Q)=>B-Q),[...new Set(s)]}*getValues(A,e=!0,t=!0,i=!0){var Q,E,c;const I=new y,o=new kA,s=new y(1,1,1),n=this.target,C=e?(Q=this.pos)==null?void 0:Q.createInterpolant():void 0,a=t?(E=this.rot)==null?void 0:E.createInterpolant():void 0,B=i?(c=this.scale)==null?void 0:c.createInterpolant():void 0;C||I.set(n.position.x,n.position.y,n.position.z),a||o.set(n.quaternion.x,n.quaternion.y,n.quaternion.z,n.quaternion.w),B||s.set(n.scale.x,n.scale.y,n.scale.z);for(let d=0;d<A.length;d++){const h=A[d];if(C){const l=C.evaluate(h);I.set(l[0],l[1],l[2])}if(a){const l=a.evaluate(h);o.set(l[0],l[1],l[2],l[3])}if(B){const l=B.evaluate(h);s.set(l[0],l[1],l[2])}if(this.useRootMotion&&n===this.root){const l=new MA;l.compose(I,o,s),l.multiply(n.matrix),l.decompose(I,o,s)}yield{time:h,translation:I,rotation:o,scale:s,index:d}}}};let fg=EK;r(fg,"animationDurationPadding",1/60),r(fg,"restPoseClipDuration",1/60);class au{constructor(A){r(this,"dict",new Map);r(this,"rootTargetMap",new Map);r(this,"rootAndClipToRegisteredAnimationMap",new Map);r(this,"rootToRegisteredClipCount",new Map);r(this,"serializers",[]);r(this,"injectRestPoses",!1);r(this,"injectImplicitBehaviours",!1);this.injectRestPoses=A,this.injectImplicitBehaviours=A}get extensionName(){return"animation"}getStartTimeCode(){return!this.injectRestPoses||this.rootAndClipToRegisteredAnimationMap.size===0?0:(fg.restPoseClipDuration+fg.animationDurationPadding)*60}getEndTimeCode(){let A=0;for(const[e,t]of this.rootAndClipToRegisteredAnimationMap){const i=t.start+t.duration;i>A&&(A=i)}return A*60}getClipCount(A){let e=this.rootToRegisteredClipCount.get(A);return this.injectRestPoses&&(e=e?e-1:0),e??0}getStartTime01(A,e){const t=this.rootTargetMap.get(A);if(!t)return 0;const i=this.dict.get(t[0]);if(!i)return console.error("Trying to get start time for root that has no animation data",A,e,...this.dict),0;let I=0;for(let o=0;o<i.length&&i[o].clip!==e;o++)I+=i[o].getDuration()+fg.animationDurationPadding;return I}registerAnimation(A,e){if(!e||!A)return null;this.rootTargetMap.has(A)||this.rootTargetMap.set(A,[]);const t=A.uuid+e.uuid;if(this.rootAndClipToRegisteredAnimationMap.has(t))return this.rootAndClipToRegisteredAnimationMap.get(t);nB&&console.log("registerAnimation",A,e);const i=this.injectRestPoses?1:0,I=this.rootToRegisteredClipCount.get(A)??i,o=this.rootTargetMap.get(A),s=new Set(o);if(e.tracks)for(const C of e.tracks){const a=ze.parseTrackName(C.name),B=ze.findNode(A,a.nodeName);if(!B){console.warn("no object found for track",C.name,"using "+A.name+" instead");continue}this.dict.has(B)||this.dict.set(B,[]);const Q=this.dict.get(B);if(!Q){console.warn("no transform data found for target ",B,"at slot "+I+", this is likely a bug");continue}if(s.delete(B),this.injectRestPoses&&!Q[0]){const c=new fg(null,B,void 0);Q[0]=c}let E=Q[I];E||(E=new fg(A,B,e),Q[I]=E),E.addTrack(C),o!=null&&o.includes(B)||o==null||o.push(B)}for(const C of s){const a=this.dict.get(C);if(!a)continue;if(this.injectRestPoses&&!a[0]){const Q=new fg(null,C,void 0);a[0]=Q}let B=a[I];B||(nB&&console.log("Adding padding clip for ",C,e,"at slot",I),B=new fg(A,C,e),a[I]=B)}const n=new ES(this,A,e);return this.rootAndClipToRegisteredAnimationMap.set(t,n),this.rootToRegisteredClipCount.set(A,I+1),n}onAfterHierarchy(A){nB&&console.log("Animation clips per animation target node",this.dict)}onAfterBuildDocument(A){var e,t;for(const i of this.serializers){const I=(e=i.model)==null?void 0:e.parent,o=(I==null?void 0:I.isDynamic)===!0;Lk&&console.log(o,(t=i.model)==null?void 0:t.parent),o&&i.registerCallback(I)}}onExportObject(A,e,t){nA.foreachComponent(A,I=>{const o=I;typeof o.createAnimation=="function"&&o.createAnimation(this,e,t)},!1);const i=new ugA(A,this.dict);this.serializers.push(i),i.registerCallback(e)}}class ugA{constructor(A,e){r(this,"object");r(this,"dict");r(this,"model");r(this,"callback");this.object=A,this.dict=e}registerCallback(A){this.model&&this.callback&&this.model.removeEventListener("serialize",this.callback),this.callback||(this.callback=this.onSerialize.bind(this)),Lk&&console.log("REPARENT",A),this.model=A,this.model.addEventListener("serialize",this.callback)}skinnedMeshExport(A,e){var I;const t=this.model,i=this.dict;if(t&&t.skinnedMesh){let o=function(S){const F=[];for(const[w,R]of S){let H=`${w} : [`;const Y=[];for(const J of R)Y.push(`(${ug(J.x)}, ${ug(J.y)}, ${ug(J.z)})`);H=H.concat(Y.join(", ")),H=H.concat("],"),F.push(H)}return F},s=function(S){const F=[];for(const[w,R]of S){let H=`${w} : [`;const Y=[];for(const J of R)Y.push(`(${ug(J.w)}, ${ug(J.x)}, ${ug(J.y)}, ${ug(J.z)})`);H=H.concat(Y.join(", ")),H=H.concat("],"),F.push(H)}return F},n=function(S){let F,w=!0;const R=new Map;for(const[Y,J]of S){F===void 0&&(F=J.length),F!==J.length&&(w=!1);let O=0;for(const q of J)O++,q||(R.has(Y)||R.set(Y,[]),R.get(Y).push(O))}nB&&console.log("Bone count: ",S.size,"TransformData entries per bone: ",F,"Undefined bone entries: ",R),console.assert(w,"All bones should have the same number of TransformData entries",S),console.assert(R.size===0,"All TransformData entries should be set",R);const H=[];for(const[Y,J]of S){const O=new Array;let q=0;for(let b=0;b<J.length;b++)O.push(q),q+=J[b].getDuration()+fg.animationDurationPadding;for(let b=0;b<J.length;b++){const T=J[b],V=O[b];H.length<=b&&H.push({pos:[],rot:[],scale:[],timeOffset:V});const AA=H[b];AA.pos.push(...T.getSortedTimesArray(!0,!1,!1)),AA.rot.push(...T.getSortedTimesArray(!1,!0,!1)),AA.scale.push(...T.getSortedTimesArray(!1,!1,!0))}}for(const Y of H)Y.pos.sort((J,O)=>J-O),Y.rot.sort((J,O)=>J-O),Y.scale.sort((J,O)=>J-O),Y.pos=[...new Set(Y.pos)],Y.rot=[...new Set(Y.rot)],Y.scale=[...new Set(Y.scale)];return H},C=function(S,F,w){const R=new Map,H=new Map,Y=new Map,J=F.length;for(const O of w){const q=S.get(O);let b;q?console.assert(q.length===J,"We should have the same number of TransformData entries for each bone",q,F):b=new fg(null,O,void 0);for(let T=0;T<J;T++){const V=q?q[T]:b,AA=F[T];for(const{time:sA,translation:QA}of V.getValues(AA.pos,!0,!1,!1)){const iA=(sA+AA.timeOffset)*60;R.has(iA)||R.set(iA,new Array),R.get(iA).push(QA.clone())}for(const{time:sA,rotation:QA}of V.getValues(AA.rot,!1,!0,!1)){const iA=(sA+AA.timeOffset)*60;H.has(iA)||H.set(iA,new Array),H.get(iA).push(QA.clone())}for(const{time:sA,scale:QA}of V.getValues(AA.scale,!1,!1,!0)){const iA=(sA+AA.timeOffset)*60;Y.has(iA)||Y.set(iA,new Array),Y.get(iA).push(QA.clone())}}}return{position:R.size==0?void 0:R,quaternion:H.size==0?void 0:H,scale:Y.size==0?void 0:Y}},a=function(S){const F=[];for(const w of S)F.push(`(${ug(w.x)}, ${ug(w.y)}, ${ug(w.z)})`);return F.join(", ")},B=function(S){const F=[];for(const w of S)F.push(`(${ug(w.w)}, ${ug(w.x)}, ${ug(w.y)}, ${ug(w.z)})`);return F.join(", ")},Q=function(S){const F=new Map;if(nB){const w=new Array;for(const[R,H]of i)w.push(R.uuid+": "+H.length+" "+H.map(Y=>{var J;return(J=Y.clip)==null?void 0:J.uuid.substring(0,6)}).join(" "));console.log(`getPerBoneTransformData
5478
+ Could not find method ${a.method} on object ${Q.name}`,Q,typeof Q[a.method])};if(typeof Q[a.method]!="function"){let u=!1,f=Q;for(;f;){const m=Object.getOwnPropertyDescriptor(f,a.method);if(m&&(m.writable===!0||m.set)){u=!0;break}f=Object.getPrototypeOf(f)}!u&&(pe()||xg)&&l()}}let c=a.argument;c!==void 0?c=B(c):a.arguments!==void 0&&(c=a.arguments.map(B));const d=E?this.createEventMethod(Q,a.method,c):void 0,h=new OE(d,a.enabled);if(h.method||(h[OiA]=(o=e.object)==null?void 0:o.name),!Q||!h.method){const l=e.object?"Current object: "+e.object.name+", "+e.object.guid:null;Q?console.warn('EventList method not found: "'+a.method+'" on',Q):console.warn("EventList is missing target - will be ignored",a.target,l,A)}else s.push(h)}const n=new wg(s);xg&&console.log(n);const C=e.target;return C!==void 0&&e.path!==void 0&&n.setEventTarget(e.path,C),n}}createEventMethod(A,e,t){return(...i)=>{const I=A[e];typeof I=="function"?t!==void 0?Array.isArray(t)?I==null||I.call(A,...t):I==null||I.call(A,t):I==null||I.call(A,...i):A[e]=t}}}const WiA=new PiA;class hO extends Rn{constructor(){super([Ta,Ze])}onSerialize(A,e){}onDeserialize(A,e){if(A instanceof Je&&e.type===Ta){const t=A,i=new Ta(t.image.width,t.image.height,{colorSpace:yt});return i.texture=t,t.isRenderTargetTexture=!0,t.flipY=!0,t.offset.y=1,t.repeat.y=-1,t.needsUpdate=!0,t.mipmaps=[],t instanceof ln&&(t.isCompressedTexture=!1,t.format=RGBAFormat),i}}}new hO;class dO extends Rn{constructor(){super([URL])}onSerialize(A,e){return null}onDeserialize(A,e){if(typeof A=="string"&&A.length>0)return bC(e.gltfId,A)}}new dO;var jiA=Object.defineProperty,ziA=Object.getOwnPropertyDescriptor,ViA=(g,A,e,t)=>{for(var i=t>1?void 0:t?ziA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&jiA(A,e,i),i};class su extends UA{awake(){jI.createIfNoneExists(this.context)}onEnable(){var A;(A=jI.get(this.context))==null||A.register(this)}onDisable(){var A;(A=jI.get(this.context))==null||A.unregister(this)}}class mo extends su{constructor(){super(...arguments);r(this,"targets",null);r(this,"raycastHits",[]);r(this,"ignoreSkinnedMeshes",!1)}start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??(e=new ts),e.targets=this.targets,e.results=this.raycastHits;const t=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=I=>I instanceof Gs?"continue in children":t?t(I):!0);const i=this.context.physics.raycast(e);return e.testObject=t,i}}ViA([D()],mo.prototype,"ignoreSkinnedMeshes",2);class nS extends mo{constructor(){super(),this.ignoreSkinnedMeshes=!0}}class gd extends su{performRaycast(A){if(!he.active||!(A!=null&&A.ray))return null;const e=A.ray.origin,t=.01;return this.context.physics.sphereOverlap(e,t)}}class CS{static getObject(A){const e=A[Wo];return e&&(e.isComponent===!0?A=e.gameObject:A=e),A}static isInteractable(A,e){if(e&&(e.canvasGroup=void 0,e.graphic=void 0),A==null||!A.visible||(A=this.getObject(A),!A.visible))return!1;const t=this.tryFindCanvasGroup(A);if((t==null?void 0:t.isCanvasGroup)===!0&&(e&&(e.canvasGroup=t),t.blocksRaycasts===!1||t.interactable===!1))return!1;const i=FB(A,I=>{if(I.isGraphic===!0)return I},!1);return e&&(i==null?void 0:i.isGraphic)===!0&&(e.graphic=i),!((i==null?void 0:i.raycastTarget)===!1||(i==null?void 0:i.layer)===2)}static tryFindCanvasGroup(A){if(!A)return null;const e=FB(A,t=>{const i=t;if(i.blocksRaycasts!==void 0&&i.interactable!==void 0)return i},!1);return e!==void 0?e:this.tryFindCanvasGroup(A.parent)}}function SN(g){const A=g[Wo];return A||(g.parent?SN(g.parent):null)}function ZiA(g){return g.isUI===!0||typeof g[Wo]=="object"}function py(g,A){if(!g)return;const e=g.material;if((e==null?void 0:e.isMaterial)===!0){const t=g.parent;t&&t.isText,e.side=A.doubleSided??!0?ut:Tg,e.shadowSide=A.doubleSided?ut:Tg,g.castShadow=A.castShadows?A.castShadows:!1,g.receiveShadow=A.receiveShadows?A.receiveShadows:!1}for(const t of g.children)py(t,A)}function XQ(g,A,e){g[A]===void 0&&console.warn("Field",A,"is undefined on",g);const t=Proxy.revocable(g[A],{set(o,s,n,C){const a=o[s],B=Reflect.set(o,s,n,C);return e(n,a),B}}),i=t.revoke,I=g[A];return t.revoke=()=>{g[A]=I,i()},g[A]=t.proxy,t}const pv=Symbol("Scheduled action");function XiA(g,A,e=zi.OnBeforeRender){let t=g[pv];t||(t=g[pv]={});const i=A.name;t[e]||(t[e]={});const I=t[e];if(I[i])return;function*s(){A==null||A.call(g),I[i]=null}const n=g.startCoroutine(s(),e);I[i]=n}const Xn=IA("debugeventsystem");var vk=(g=>(g.BeforeHandleInput="BeforeHandleInput",g.AfterHandleInput="AfterHandleInput",g))(vk||{});const Xs=class extends UA{constructor(){super();r(this,"raycaster",[]);r(this,"_handleInputFn");r(this,"pressedByID",new Map);r(this,"hoveredByID",new Map);r(this,"_sortedHits",[]);r(this,"_testObjectsCache",new Map);r(this,"_currentlyActiveRaycaster",null);r(this,"_currentPointerEventName",null);r(this,"shouldRaycastObject",e=>{var I;let t=null;if(ZiA(e)&&(t=(I=e[Wo])==null?void 0:I.gameObject),this._testObjectsCache.has(e)||t&&this._testObjectsCache.has(t))return this._testObjectsCache.get(e)===!1?"continue in children":!0;{let o=bk(e,this._currentPointerEventName);if(!o&&t&&(o=bk(t,this._currentPointerEventName)),o){this._testObjectsCache.set(e,!0);for(const s of e.children)this.shouldRaycastObject_AddToYesCache(s);return!0}return this._testObjectsCache.set(e,!1),"continue in children"}});r(this,"_sortingBuffer",[]);r(this,"_noDepthTestingResults",[]);r(this,"out",{});r(this,"_capturedPointer",{});r(this,"pointerEnterSymbol",Symbol("pointerEnter"));r(this,"pointerExitSymbol",Symbol("pointerExit"));r(this,"currentActiveMeshUIComponents",[]);Xs.systems.push(this)}static createIfNoneExists(e){this.didSearchEventSystem||(this.didSearchEventSystem=!0,Xs.systems.length<=0&&Xs.systems.push(...nA.findObjectsOfType(Xs,e)));for(const i of Xs.systems)if(i.context===e)return;const t=new pA;nA.addNewComponent(t,Xs),e.scene.add(t)}static get systems(){const e=Le.Current;return this._eventSystemMap.has(e)||this._eventSystemMap.set(e,[]),this._eventSystemMap.get(e)}static get(e){const t=this._eventSystemMap.get(e);return t&&t.length>0?t[0]:null}static get instance(){return this.systems[0]}static ensureUpdateMeshUI(e,t,i=!1){Ma.update(e,t,i)}static markUIDirty(e){Ma.markDirty()}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}onDestroy(){Xs.systems.splice(Xs.systems.indexOf(this),1)}start(){if(this.raycaster.length<=0&&!nA.findObjectOfType(su,this.context)){const t=nA.addNewComponent(this.context.scene,mo);this.raycaster.push(t),(pe()||Xn)&&console.warn("Added an ObjectRaycaster to the scene because no raycaster was found.")}}register(e){var t;e&&this.raycaster&&!this.raycaster.includes(e)&&((t=this.raycaster)==null||t.push(e))}unregister(e){var i,I;const t=(i=this.raycaster)==null?void 0:i.indexOf(e);t!==void 0&&t!==-1&&((I=this.raycaster)==null||I.splice(t,1))}onEnable(){this._handleInputFn??(this._handleInputFn=this.onPointerEvent.bind(this)),this.context.input.addEventListener(ii.PointerDown,this._handleInputFn),this.context.input.addEventListener(ii.PointerUp,this._handleInputFn),this.context.input.addEventListener(ii.PointerMove,this._handleInputFn)}onDisable(){this.context.input.removeEventListener(ii.PointerDown,this._handleInputFn),this.context.input.removeEventListener(ii.PointerUp,this._handleInputFn),this.context.input.removeEventListener(ii.PointerMove,this._handleInputFn)}onBeforeRender(){this.resetMeshUIStates()}onPointerEvent(e){if(e===void 0||e.propagationStopped)return;const t=new lc(this.context.input,e);this._currentPointerEventName=e.type,t.inputSource=this.context.input,t.isClick=e.isClick,t.isDoubleClick=e.isDoubleClick,t.isDown=e.type==ii.PointerDown,t.isUp=e.type==ii.PointerUp,t.isPressed=this.context.input.getPointerPressed(e.pointerId),Xn&&(t.isDown?console.log("DOWN",t.pointerId):t.isUp&&console.log("UP",t.pointerId),t.isClick&&console.log("CLICK",t.pointerId));const i=new ts;e.hasRay?i.ray=e.ray:i.screenPoint=this.context.input.getPointerPositionRC(e.pointerId);const I=this.performRaycast(i);if(I)for(const s of I)s.event=e,e.intersections.push(s);Xn&&t.isClick&&Gi("EventSystem: "+t.pointerId+" - "+this.context.time.frame+" - Up:"+t.isUp+", Down:"+t.isDown);const o={sender:this,args:t,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:o})),this.handleIntersections(I,t),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:o}))}shouldRaycastObject_AddToYesCache(e){this._testObjectsCache.set(e,!0);for(const t of e.children)this.shouldRaycastObject_AddToYesCache(t)}performRaycast(e){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,e||(e=new ts),e.testObject=this.shouldRaycastObject;for(const t of this.raycaster){if(!t.activeAndEnabled)continue;this._currentlyActiveRaycaster=t;const i=t.performRaycast(e);this._currentlyActiveRaycaster=null,i&&i.length>0&&this._sortedHits.push(...i)}return this._sortedHits.sort((t,i)=>t.distance-i.distance),this._sortedHits}assignHitInformation(e,t){t?(e.intersection=t,e.point=t.point,e.normal=t.normal,e.face=t.face,e.distance=t.distance,e.instanceId=t.instanceId):(e.intersection=void 0,e.point=void 0,e.normal=void 0,e.face=void 0,e.distance=void 0,e.instanceId=void 0)}handleIntersections(e,t){var I;if(e!=null&&e.length){e=this.sortCandidates(e);for(const o of e){if(t.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(t,o),this.handleEventOnObject(o.object,t))return!0}}this.assignHitInformation(t,e==null?void 0:e[0]),this.invokePointerCapture(t);const i=this.hoveredByID.get(t.pointerId);return i&&this.propagatePointerExit(i.obj,i.data,null),this.hoveredByID.delete(t.pointerId),t.isUp&&((I=this.pressedByID.get(t.pointerId))==null||I.handlers.forEach(o=>this.invokeOnPointerUp(t,o)),this.pressedByID.delete(t.pointerId)),!1}sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){const i=e[t],I=i.object;if(I.material&&I.material.depthTest===!1){this._noDepthTestingResults.push(i);continue}this._sortingBuffer.push(i)}for(const t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}handleEventOnObject(e,t){if(!this.testIsVisible(e))return t.isClick&&Xn&&console.log("not allowed",e),!1;if(t.pointerId===void 0)return Xn&&console.error("Event without pointer can't be handled",t),!1;t.object=e;const i=e.parent,I=t.isClick??!1;let o=null;if(i&&i.isUI){const B=(t.isPressed||t.isClick)??!1;if(i[Wo]){const Q=i[Wo].gameObject;if(Q){if(!CS.isInteractable(Q,this.out))return!1;o=this.out.canvasGroup??null,this.handleMeshUIIntersection(e,B),e=Q}}}I&&Xn&&console.log(this.context.time.frame,e);const s=this.hoveredByID.get(t.pointerId),n=s==null?void 0:s.obj;n!==e&&n&&this.propagatePointerExit(n,s.data,e);const a=this.hoveredByID.get(t.pointerId);if(a?(a.obj=e,a.data=t):this.hoveredByID.set(t.pointerId,{obj:e,data:t}),t.isDown){const B=this.pressedByID.get(t.pointerId);B?(B.obj=e,B.data=t):this.pressedByID.set(t.pointerId,{obj:e,data:t,handlers:new Set})}return(o===null||o.interactable)&&this.handleMainInteraction(e,t,n??null),!0}propagate(e,t){for(;e;)nA.foreachComponent(e,i=>{t(i)},!1),e=e.parent}handleMainInteraction(e,t,i){const I=this.pressedByID.get(t.pointerId),o=i!==e;let s=!0;switch(t.event.pointerType){case"mouse":case"touch":const n=this.context.input.getPointerPositionLastFrame(t.pointerId),C=this.context.input.getPointerPosition(t.pointerId);s=n&&!te.approximately(n,C);break}this.propagate(e,n=>{var a;const C=n;C.interactable!==!1&&(!C.activeAndEnabled||!C.enabled||(C.onPointerEnter&&o&&this.handlePointerEnter(C,t),t.isDown&&C.onPointerDown&&(C.onPointerDown(t),I==null||I.handlers.add(C),this.handlePointerCapture(t,C)),C.onPointerMove&&(s&&C.onPointerMove(t),this.handlePointerCapture(t,C)),t.isUp&&(C.onPointerUp&&(this.invokeOnPointerUp(t,C),I==null||I.handlers.delete(C)),C.onPointerExit&&((a=t.event)==null?void 0:a.pointerType)===jw.Touch&&(this.handlePointerExit(C,t),this.hoveredByID.delete(t.pointerId))),t.isClick&&C.onPointerClick&&C.onPointerClick(t)))}),t.isUp&&(I==null||I.handlers.forEach(n=>{this.invokeOnPointerUp(t,n)}),this.pressedByID.delete(t.pointerId))}propagatePointerExit(e,t,i){this.propagate(e,I=>{if(!I.gameObject||I.destroyed)return;const o=I;if(o.onPointerExit){if(i&&this.isChild(i,I.gameObject))return;this.handlePointerExit(o,t)}})}invokeOnPointerUp(e,t){var i;(i=t.onPointerUp)==null||i.call(t,e),this.releasePointerCapture(e,t)}handlePointerEnter(e,t){e.onPointerEnter&&this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!0)&&e.onPointerEnter(t),this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(e,t){e.onPointerExit&&this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!0)&&e.onPointerExit(t),this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(e,t,i,I){let o=e[i];if(I)return o&&o.includes(t)?!1:(o=o||[],o.push(t),e[i]=o,!0);{if(!o||!o.includes(t))return!1;const s=o.indexOf(t);return s!==-1&&o.splice(s,1),!0}}handlePointerCapture(e,t){if(e.z__pointer_ctured){e.z__pointer_ctured=!1;const i=e.pointerId;if(t.onPointerMove){const I=this._capturedPointer[i]||[];I.push(t),this._capturedPointer[i]=I}else pe()&&!t.z__warned_no_pointermove&&(t.z__warned_no_pointermove=!0,console.warn("PointerCapture was requested but the component doesn't implement onPointerMove. It will not receive any pointer events"))}else e.z__pointer_cture_rleased&&(e.z__pointer_cture_rleased=!1,this.releasePointerCapture(e,t))}releasePointerCapture(e,t){const i=e.pointerId;if(this._capturedPointer[i]){const I=this._capturedPointer[i].indexOf(t);I!==-1&&(this._capturedPointer[i].splice(I,1),Xn&&console.log("released pointer capture",i,t,this._capturedPointer))}}invokePointerCapture(e){var t;if(e.event.type===ii.PointerMove){const i=e.pointerId,I=this._capturedPointer[i];if(I){Xn&&console.log("Captured",i,I);for(let o=0;o<I.length;o++){const s=I[o];if(s.destroyed){I.splice(o,1),o--;continue}(t=s.onPointerMove)==null||t.call(s,e)}}}}isChild(e,t){return!e||!t?!1:e===t?!0:e.parent?this.isChild(e.parent,t):!1}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}handleMeshUIIntersection(e,t){const i=Ma.updateState(e,t);return i&&this.currentActiveMeshUIComponents.push(i),i!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&Ma.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){const t=this.currentActiveMeshUIComponents[e];Ma.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?nA.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}};let jI=Xs;r(jI,"_eventSystemMap",new Map),r(jI,"didSearchEventSystem",!1);class Ma{static markDirty(){this.needsUpdate=!0}static update(A,e,t=!1){if(t){A.update();return}const i=e.time.frameCount;for(const I of this.lastUpdateFrame)if(I.context===e){if(i===I.frame)return;I.frame=i;let o=this.needsUpdate||i<1;I.nextUpdate===e.time.frameCount&&(o=!0),o&&(Xn&&console.log("Update threemeshui"),this.needsUpdate=!1,A.update());return}this.lastUpdateFrame=[{context:e,frame:i,nextUpdate:i}],A.update()}static updateState(A,e){let t=null;if(A&&(t=this.findBlockInParent(A),t&&t!==this.lastSelected)){if(t.interactable===!1)return null;this.needsUpdate=!0}return t}static resetLastSelected(){const A=this.lastSelected;A&&(this.lastSelected=null,this.resetState(A))}static resetState(A){A&&(this.needsUpdate=!0)}static findBlockInParent(A){return A?A.isBlock?A:this.findBlockInParent(A.parent):null}}r(Ma,"lastSelected",null),r(Ma,"lastUpdateFrame",[]),r(Ma,"needsUpdate",!1);var $iA=Object.defineProperty,AgA=Object.getOwnPropertyDescriptor,Ri=(g,A,e,t)=>{for(var i=t>1?void 0:t?AgA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&$iA(A,e,i),i};const egA=IA("debugorbit"),Bf=IA("freecam"),cl=IA("debugcamerafit"),Qf=IA("smoothcam"),tgA={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let AM;class Id extends CustomEvent{constructor(A,e){super("target-reached",{detail:{controls:A,type:e}})}}class kt extends UA{constructor(){super(...arguments);r(this,"autoTarget",!0);r(this,"autoFit",!1);r(this,"enableRotate",!0);r(this,"autoRotate",!1);r(this,"autoRotateSpeed",1);r(this,"minAzimuthAngle",1/0);r(this,"maxAzimuthAngle",1/0);r(this,"minPolarAngle",0);r(this,"maxPolarAngle",Math.PI);r(this,"enableKeys",!0);r(this,"enableDamping",!0);r(this,"dampingFactor",.1);r(this,"enableZoom",!0);r(this,"minZoom",0);r(this,"maxZoom",1/0);r(this,"enablePan",!0);r(this,"lookAtConstraint",null);r(this,"lookAtConstraint01",1);r(this,"allowInterrupt",!0);r(this,"middleClickToFocus",!0);r(this,"doubleClickToFocus",!0);r(this,"useSlerp",!0);r(this,"debugLog",!1);r(this,"targetLerpDuration",1);r(this,"_controls",null);r(this,"_cameraObject",null);r(this,"_lookTargetLerpActive",!1);r(this,"_lookTargetStartPosition",new y);r(this,"_lookTargetEndPosition",new y);r(this,"_lookTargetLerp01",0);r(this,"_lookTargetLerpDuration",0);r(this,"_cameraLerpActive",!1);r(this,"_cameraStartPosition",new y);r(this,"_cameraEndPosition",new y);r(this,"_cameraLerp01",0);r(this,"_cameraLerpDuration",0);r(this,"_inputs",0);r(this,"_enableTime",0);r(this,"_startedListeningToKeyEvents",!1);r(this,"_eventSystem");r(this,"_afterHandleInputFn");r(this,"_camera",null);r(this,"_syncedTransform");r(this,"_didStart",!1);r(this,"_didSetTarget",!1);r(this,"targetElement",null);r(this,"onControlsChangeStarted",()=>{this._syncedTransform&&this._syncedTransform.requestOwnership()});r(this,"_shouldDisable",!1);r(this,"_haveAttachedKeyboardEvents",!1)}get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){var t;(t=this.controls)==null||t.addEventListener("start",e)}get targetLerpSpeed(){return 5}set targetLerpSpeed(e){this.targetLerpDuration=1/e}awake(){this._didStart=!1,this._didSetTarget=!1,this._startedListeningToKeyEvents=!1}start(){this._didStart=!0,this._eventSystem=jI.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(vk.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){var e,t;(e=this._controls)==null||e.dispose(),(t=this._eventSystem)==null||t.removeEventListener(vk.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._enableTime=this.context.time.time;const e=nA.getComponent(this.gameObject,Vt);this._camera=e;let t=e==null?void 0:e.cam;if(!t&&this.gameObject instanceof Oe&&(t=this.gameObject),t&&dv(t,this,!0),!this._controls&&t instanceof Oe){this._cameraObject=t;const i=this.targetElement??this.context.renderer.domElement,I=t==null?void 0:t.quaternion.clone();this._controls=new SiA(t,i),t==null||t.quaternion.copy(I),AM===void 0&&(AM={...this._controls.keys})}this._controls&&(Bf&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,kn()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),(t==null?void 0:t.type)==="PerspectiveCamera"?Bf||(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):Bf||(this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom),this._startedListeningToKeyEvents||(this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(window.document.body))),this._syncedTransform=nA.getComponent(this.gameObject,$a)??void 0}onDisable(){var e;(e=this._camera)!=null&&e.cam&&dv(this._camera.cam,this,!1),this._controls&&(this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted))}afterHandleInput(e){e.detail.args.pointerId===0&&(e.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!e.detail.args.isPressed||e.detail.args.isUp)&&(this._shouldDisable=!1))}onBeforeRender(){var t,i;if(!this._controls||this._cameraObject!==this.context.mainCamera)return;this.__handleSetTargetWhenBecomingActiveTheFirstTime(),(this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2)||this.context.input.mouseWheelChanged||this.context.input.getPointerPressed(0)&&((t=this.context.input.getPointerPositionDelta(0))!=null&&t.length())||0>.1)&&(this._inputs+=1),this._inputs>0&&this.allowInterrupt&&(this.enableRotate&&(this.autoRotate=!1),this._cameraLerpActive=!1,this._lookTargetLerpActive=!1),this._inputs=0;let e=this.middleClickToFocus&&this.context.input.getPointerClicked(1);if(e||(e=this.doubleClickToFocus&&this.context.input.getPointerDoubleClicked(0)&&this.context.time.time-this._enableTime>.3),e&&this.setTargetFromRaycast(),this._lookTargetLerpActive||this._cameraLerpActive){if(this._cameraLerpActive&&this._cameraObject)if(this._cameraLerp01+=this.context.time.deltaTime/this._cameraLerpDuration,this._cameraLerp01>=1)this._cameraObject.position.copy(this._cameraEndPosition),this._cameraLerpActive=!1,this.dispatchEvent(new Id(this,"camera"));else{const I=te.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,I)}if(this._lookTargetLerpActive)if(this._lookTargetLerp01+=this.context.time.deltaTime/this._lookTargetLerpDuration,this._lookTargetLerp01>=1)this._controls.target.copy(this._lookTargetEndPosition),this._lookTargetLerpActive=!1,this.dispatchEvent(new Id(this,"lookat"));else{const I=te.easeInOutCubic(this._lookTargetLerp01);this._controls.target.lerpVectors(this._lookTargetStartPosition,this._lookTargetEndPosition,I)}}if(this._controls){if(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!this._shouldDisable&&this._camera===this.context.mainCameraComponent&&!this.context.isInXR,this._controls.keys=this.enableKeys?AM:tgA,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,this._controls.enableDamping=this.enableDamping,this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._controls.enableRotate=this.enableRotate,this._controls.minAzimuthAngle=this.minAzimuthAngle,this._controls.maxAzimuthAngle=this.maxAzimuthAngle,this._controls.minPolarAngle=this.minPolarAngle,this._controls.maxPolarAngle=this.maxPolarAngle,typeof Qf=="number"||Qf===!0){this._controls.enableDamping=!0;const I=typeof Qf=="number"?Qf:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,I))}this.allowInterrupt||(this._lookTargetLerpActive&&(this._controls.enablePan=!1),this._cameraLerpActive&&(this._controls.enableRotate=!1,this._controls.autoRotate=!1),(this._lookTargetLerpActive||this._cameraLerpActive)&&(this._controls.enableZoom=!1)),this.context.isInXR||(!Bf&&((i=this.lookAtConstraint)!=null&&i.locked)&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(),egA&&Ue.DrawWireSphere(this._controls.target,.1,65280))}}__handleSetTargetWhenBecomingActiveTheFirstTime(){if(!this._didSetTarget&&(this._didSetTarget=!0,this.autoTarget)){const e=nA.getComponent(this.gameObject,Vt);if(e&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const i=ve(e.cam).length(),I=new y(0,0,-i).applyMatrix4(e.cam.matrixWorld);this.setLookTargetPosition(I,!0)}if(!this.autoFit&&!this.setLookTargetFromConstraint()){const t=new ts;t.screenPoint=new tA(0,0),t.lineThreshold=.1;const i=this.context.physics.raycast(t);i.length>0&&this.setLookTargetPosition(i[0].point,!0),cl&&console.log("OrbitControls hits",...i)}this.autoFit&&this.fitCamera()}}setCameraAndLookTarget(e){if(!e||!(e instanceof pA))return;const t=ve(e),i=JU(e);this.setTargetFromRaycast(new XI(t,i)),this.setCameraTargetPosition(t)}setCameraTargetPosition(e,t=!1){var i,I;e&&(e instanceof pA&&(e=ve(e)),this._cameraEndPosition||(this._cameraEndPosition=new y),this._cameraEndPosition.copy(e),t===!0?(this._cameraLerpActive=!1,(i=this.controllerObject)==null||i.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy((I=this._cameraObject)==null?void 0:I.position),typeof t=="number"?this._cameraLerpDuration=t:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setLookTargetPosition(e=null,t=!1){this._controls&&e&&(e instanceof pA&&(e=ve(e)),this._lookTargetEndPosition.copy(e),t===!0?this._controls.target.copy(this._lookTargetEndPosition):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof t=="number"?this._lookTargetLerpDuration=t:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(e=0,t=1){var I;if(!this._controls)return!1;const i=(I=this.lookAtConstraint)==null?void 0:I.sources;if(i&&i.length>0){const o=i[e];if(o)return o.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._lookTargetEndPosition,t),!0}return!1}lerpTarget(e,t){return this.lerpLookTarget(e,t)}lerpLookTarget(e,t){this._controls&&(t>=1?this._controls.target.copy(e):this._controls.target.lerp(e,t))}setTargetFromRaycast(e){var i,I;if(!this.controls)return;const t=e?this.context.physics.raycastFromRay(e):this.context.physics.raycast();for(const o of t)if(o.distance>0&&nA.isActiveInHierarchy(o.object)){const s=SN(o.object);if(s){const n=s.canvas;if(n!=null&&n.screenspace)break}if(this.setLookTargetPosition(o.point),this.context.mainCamera){const C=ve(this.context.mainCamera).clone().sub(this.controls.target).add(this._lookTargetEndPosition);(I=(i=this._cameraObject)==null?void 0:i.parent)==null||I.worldToLocal(C),this.setCameraTargetPosition(C)}break}}fitCamera(e,t=1.1,i=!0){const I=this._cameraObject,o=this._controls;if(e!=null&&e.length||(e=this.context.scene.children),e.length<=0||!I||!o)return;const s=new y,n=new y,C=new Ft;C.makeEmpty();const a=[];function B(u){let f=!0;if(u.visible&&MiA(u)!==!1&&!(u.type==="TransformControlsGizmo"||u.type==="TransformControlsPlane")&&(u instanceof NG&&(f=!1),u instanceof Jw&&(f=!1),u instanceof BO&&(f=!1),u.material instanceof mw&&(f=!1),u instanceof dA||(f=!1),u!==I&&u.isUI!==!0)){if(f){cl&&console.log(u.name,u.type,u);const m=u.children;u.children=a;const M=u.position,k=u.scale;if(Number.isNaN(M.x)||Number.isNaN(M.y)||Number.isNaN(M.z)){console.warn(`Object "${u.name}" has NaN values in position or scale.... will ignore it`,M,k);return}C.expandByObject(u,!0),u.children=m}for(const m of u.children)B(m)}}for(const u of e)u.updateMatrixWorld(),B(u);if(I.updateMatrixWorld(),I.updateProjectionMatrix(),C.getCenter(n),C.applyMatrix4(I.matrixWorldInverse),C.getSize(s),C.setFromCenterAndSize(n,s),Number.isNaN(s.x)||Number.isNaN(s.y)||Number.isNaN(s.z)){console.warn("Camera fit size resultet in NaN",I,C,[...e]);return}if(s.length()<=1e-10){cl&&console.warn("Camera fit size is zero",C,[...e]);return}const Q=I.fov,E=2*Math.atan(Math.tan(Q*Math.PI/360/2)*I.aspect)/Math.PI*360,c=s.y/(2*Math.atan(Math.PI*Q/360)),d=s.x/(2*Math.atan(Math.PI*E/360)),h=t*Math.max(c,d)+s.z/2;cl&&console.log("Fit camera to objects",c,d,"distance",h);const l=ve(I),p=o.target.clone().sub(l).normalize().multiplyScalar(h);if(o.maxDistance=h*10,o.minDistance=h*.01,this.setLookTargetPosition(n,i),this.autoTarget=!1,I.near=h/1e3,I.far=h*100,I.updateMatrixWorld(),I.updateProjectionMatrix(),I.parent){const u=I.parent.worldToLocal(o.target.clone().sub(p));this.setCameraTargetPosition(u,i)}else console.error(`Can not fit camera ${I.name} because it has no parent`);if(cl){const u=new NG(C);this.context.scene.add(u),vU(u,_d(I)),this._haveAttachedKeyboardEvents||(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",f=>{f.code==="KeyF"&&this.fitCamera(e)}))}o.update()}}Ri([D()],kt.prototype,"autoTarget",2);Ri([D()],kt.prototype,"autoFit",2);Ri([D()],kt.prototype,"enableRotate",2);Ri([D()],kt.prototype,"autoRotate",2);Ri([D()],kt.prototype,"autoRotateSpeed",2);Ri([D()],kt.prototype,"minAzimuthAngle",2);Ri([D()],kt.prototype,"maxAzimuthAngle",2);Ri([D()],kt.prototype,"minPolarAngle",2);Ri([D()],kt.prototype,"maxPolarAngle",2);Ri([D()],kt.prototype,"enableKeys",2);Ri([D()],kt.prototype,"enableDamping",2);Ri([D()],kt.prototype,"dampingFactor",2);Ri([D()],kt.prototype,"enableZoom",2);Ri([D()],kt.prototype,"minZoom",2);Ri([D()],kt.prototype,"maxZoom",2);Ri([D()],kt.prototype,"enablePan",2);Ri([D(Iu)],kt.prototype,"lookAtConstraint",2);Ri([D()],kt.prototype,"lookAtConstraint01",2);Ri([D()],kt.prototype,"allowInterrupt",2);Ri([D()],kt.prototype,"middleClickToFocus",2);Ri([D()],kt.prototype,"doubleClickToFocus",2);Ri([D()],kt.prototype,"targetLerpDuration",2);var igA=Object.defineProperty,ggA=Object.getOwnPropertyDescriptor,ko=(g,A,e,t)=>{for(var i=t>1?void 0:t?ggA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&igA(A,e,i),i},KB=(g=>(g[g.Skybox=1]="Skybox",g[g.SolidColor=2]="SolidColor",g[g.Uninitialized=4]="Uninitialized",g))(KB||{});const IC=IA("debugcam"),fv=IA("debugscreenpointtoray");var vf;const Tl=(vf=class extends UA{constructor(){super(...arguments);r(this,"_nearClipPlane",.1);r(this,"_farClipPlane",1e3);r(this,"orthographic",!1);r(this,"orthographicSize",5);r(this,"ARBackgroundAlpha",0);r(this,"_cullingMask",4294967295);r(this,"_backgroundBlurriness",0);r(this,"_backgroundIntensity",1);r(this,"_environmentIntensity");r(this,"_targetTexture",null);r(this,"_backgroundColor");r(this,"_fov");r(this,"_cam",null);r(this,"_clearFlags",2);r(this,"_skybox")}get isCamera(){return!0}get aspect(){return this._cam instanceof Oe?this._cam.aspect:this.context.domWidth/this.context.domHeight}get fieldOfView(){return this._cam instanceof Oe?this._cam.fov:this._fov}set fieldOfView(A){const e=this.fieldOfView!=A;if(this._fov=A,e&&this._cam&&this._cam instanceof Oe){if(this._fov===void 0){console.warn("Can not set undefined fov on PerspectiveCamera");return}this._cam.fov=this._fov,this._cam.updateProjectionMatrix()}}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(A){const e=this._nearClipPlane!=A;this._nearClipPlane=A,this._cam&&e&&(this._cam.near=A,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(A){const e=this._farClipPlane!=A;this._farClipPlane=A,this._cam&&e&&(this._cam.far=A,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(A){A!==this._clearFlags&&(this._clearFlags=A,this.applyClearFlagsIfIsActiveCamera())}set cullingMask(A){this._cullingMask=A,this._cam&&(this._cam.layers.mask=A)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}set cullingLayer(A){this.cullingMask=(1<<A|0)>>>0}set backgroundBlurriness(A){A!==this._backgroundBlurriness&&(A===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(A,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}set backgroundIntensity(A){A!==this._backgroundIntensity&&(A===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(A,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}set environmentIntensity(A){this._environmentIntensity=A}get environmentIntensity(){return this._environmentIntensity}get backgroundColor(){return this._backgroundColor??null}set backgroundColor(A){if(A){if(this._backgroundColor)this._backgroundColor.copy(A);else{if(!A.clone)return;this._backgroundColor=A.clone()}A.alpha===void 0&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera()}}set targetTexture(A){this._targetTexture=A}get targetTexture(){return this._targetTexture}get cam(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(A,e,t){const i=this.cam,I=Tl._origin;I.set(A,e,-1),this.context.input.convertScreenspaceToRaycastSpace(I),fv&&console.log("screenPointToRay",A.toFixed(2),e.toFixed(2),"now:",I.x.toFixed(2),I.y.toFixed(2),"isInXR:"+this.context.isInXR),I.z=-1,I.unproject(i);const o=Tl._direction.set(I.x,I.y,I.z),s=ve(i);return o.sub(s),o.normalize(),t?(t.set(s,o),t):new XI(s.clone(),o.clone())}awake(){fv&&window.addEventListener("pointerdown",A=>{const e=A.clientX,t=A.clientY;console.log("touch",e.toFixed(2),t.toFixed(2));const i=this.screenPointToRay(e,t),I="#"+Math.floor(Math.random()*16777215).toString(16);Ue.DrawRay(i.origin,i.direction,I,10)})}onEnable(){IC&&console.log(`Camera enabled: "${this.name}". ClearFlags=${KB[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),ogA(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 A=this.context.renderer;if(A){const e=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,A),e==null||e.applyClearFlags()}}}buildCamera(){if(this._cam)return;const A=this.gameObject.isCamera;let e=null;if(A?(e=this.gameObject,e==null||e.layers.enableAll(),e instanceof Oe&&(this._fov=e.fov)):e=this.gameObject.children[0],e&&e.isCamera)e instanceof Oe&&(this._fov&&(e.fov=this._fov),e.near=this._nearClipPlane,e.far=this._farClipPlane,e.updateProjectionMatrix());else if(!this.orthographic)e=new Oe(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(e.fov=this.fieldOfView),this.gameObject.add(e);else{const t=this.orthographicSize*100;e=new JC(window.innerWidth/-t,window.innerWidth/t,window.innerHeight/t,window.innerHeight/-t,this._nearClipPlane,this._farClipPlane),this.gameObject.add(e)}this._cam=e,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(){this.context.mainCameraComponent===this&&this.applyClearFlags()}applyClearFlags(){if(!this._cam){IC&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this._fov,IC){const A=`Camera "${this.name}" clear flags: ${KB[this._clearFlags]}`;console.debug(A)}switch(this._clearFlags){case 1:if(Tl.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:IC&&console.warn(`Camera "${this.name}" has no background blurriness`),this._backgroundIntensity!==void 0?this.context.scene.backgroundIntensity=this._backgroundIntensity:IC&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor){let A=this._backgroundColor.alpha;Tl.backgroundShouldBeTransparent(this.context)&&(A=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.renderer.setClearColor(this._backgroundColor,A)}else IC&&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 IgA(this)),this._skybox.enable()}static backgroundShouldBeTransparent(A){var I,o,s,n;const e=(I=A.renderer.xr)==null?void 0:I.getSession();if(!e)return!1;if(typeof e._transparent=="boolean")return e._transparent;const t=e.environmentBlendMode;IC&&Gi("Environment blend mode: "+t+" on "+navigator.userAgent);let i=t==="additive"||t==="alpha-blend";return A.isInAR&&t==="opaque"&&((o=navigator.userAgent)!=null&&o.includes("OculusBrowser")||(s=navigator.userAgent)!=null&&s.includes("Mozilla")&&((n=navigator.userAgent)!=null&&n.includes("Mobile WebXRViewer/v2")))&&(i=!0),e._transparent=i,i}},r(vf,"_origin",new y),r(vf,"_direction",new y),vf);let Vt=Tl;ko([D()],Vt.prototype,"fieldOfView",1);ko([D()],Vt.prototype,"nearClipPlane",1);ko([D()],Vt.prototype,"farClipPlane",1);ko([D()],Vt.prototype,"clearFlags",1);ko([D()],Vt.prototype,"orthographic",2);ko([D()],Vt.prototype,"orthographicSize",2);ko([D()],Vt.prototype,"ARBackgroundAlpha",2);ko([D()],Vt.prototype,"cullingMask",1);ko([D()],Vt.prototype,"backgroundBlurriness",1);ko([D()],Vt.prototype,"backgroundIntensity",1);ko([D()],Vt.prototype,"environmentIntensity",1);ko([D(Mt)],Vt.prototype,"backgroundColor",1);ko([D(Ta)],Vt.prototype,"targetTexture",1);class IgA{constructor(A){r(this,"_camera");r(this,"_skybox");this._camera=A}get context(){var A;return(A=this._camera)==null?void 0:A.context}enable(){this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),this._skybox?this.context.scene.background!==this._skybox&&(IC&&console.log(`Camera "${this._camera.name}" set skybox`,this._camera,this._skybox),this._skybox.mapping=Zo,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)),(IC||pe())&&Ii(`Camera "${this._camera.name}" has no skybox texture`))}}function ogA(g){IA("freecam")&&g.context.mainCameraComponent===g&&nA.getOrAddComponent(g.gameObject,kt)}class _a extends UA{constructor(){super(...arguments);r(this,"_listener",null)}get listener(){return this._listener==null&&(this._listener=new TY),this._listener}awake(){hi.registerWaitForAllowAudio(()=>{if(this.destroyed)return;const e=this.listener;if(e==null||e.parent)return;const t=this.context.mainCameraComponent||nA.getComponentInParent(this.gameObject,Vt);t!=null&&t.cam?t.cam.add(e):this.gameObject.add(e)})}}var sgA=Object.defineProperty,ngA=Object.getOwnPropertyDescriptor,aS=(g,A,e,t)=>{for(var i=t>1?void 0:t?ngA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&sgA(A,e,i),i};const CgA=IA("debugsignals");class nu{constructor(){r(this,"guid")}}aS([D()],nu.prototype,"guid",2);class hc{constructor(){r(this,"signal");r(this,"reaction")}}aS([D(nu)],hc.prototype,"signal",2);aS([D(wg)],hc.prototype,"reaction",2);var YM;const $n=(YM=class extends UA{constructor(){super(...arguments);r(this,"events")}static invoke(A){if($n.receivers[A]){const e=$n.receivers[A];if(!e)return;for(const t of e)t.invoke(A)}}awake(){CgA&&console.log("SignalReceiver awake",this)}onEnable(){if(this.events)for(const A of this.events)$n.receivers[A.signal.guid]||($n.receivers[A.signal.guid]=[]),$n.receivers[A.signal.guid].push(this)}onDisable(){if(this.events){for(const A of this.events)if($n.receivers[A.signal.guid]){const e=$n.receivers[A.signal.guid].indexOf(this);e>=0&&$n.receivers[A.signal.guid].splice(e,1)}}}invoke(A){if(!this.events||!Array.isArray(this.events))return;const e=typeof A=="object"?A.guid:A;for(const t of this.events)if(t.signal.guid===e)try{if(t.reaction){if(!t.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",t,this);continue}}else{console.warn("Missing reaction for signal",t,this);continue}t.reaction.invoke()}catch(i){console.error(i)}}},r(YM,"receivers",{}),YM);let dc=$n;aS([D(hc)],dc.prototype,"events",2);var no=(g=>(g.Activation="ActivationTrack",g.Animation="AnimationTrack",g.Audio="AudioTrack",g.Control="ControlTrack",g.Marker="MarkerTrack",g.Signal="SignalTrack",g))(no||{}),Zs=(g=>(g[g.None=0]="None",g[g.Hold=1]="Hold",g[g.Loop=2]="Loop",g[g.PingPong=3]="PingPong",g[g.Continue=4]="Continue",g))(Zs||{}),mN=(g=>(g.Signal="SignalEmitter",g))(mN||{});const Qn=IA("debugtimeline");class Cu{constructor(){r(this,"director");r(this,"track")}get muted(){return this.track.muted}set muted(A){var e;A!==this.track.muted&&(this.track.muted=A,(e=this.onMuteChanged)==null||e.call(this))}*forEachClip(A=!1){var e;if((e=this.track)!=null&&e.clips)if(A)for(let t=this.track.clips.length-1;t>=0;t--)yield this.track.clips[t];else for(const t of this.track.clips)yield t}getClipTime(A,e){return e.clipIn+(A-e.start)*e.timeScale}getClipTimeNormalized(A,e){return(A-e.start)/e.duration}evaluateWeight(A,e,t,i=!0){if(e<0||e>=t.length)return 0;const I=t[e];if(i||A>=I.start&&A<=I.end){let o=1;const s=!1;if(I.easeInDuration>0){const n=Math.min((A-I.start)/I.easeInDuration,1);o*=n}if(I.easeOutDuration>0&&!s){const n=Math.min((I.end-A)/I.easeOutDuration,1);o*=n}return o}return 0}}class agA{constructor(A){r(this,"clip");r(this,"rootPositionOffset");r(this,"rootQuaternionOffset");r(this,"rootStartPosition");r(this,"rootEndPosition");r(this,"rootStartQuaternion");r(this,"rootEndQuaternion");const e=A.getClip();this.clip=e;const t=A.getRoot(),i=t.name+".position",I=t.name+".quaternion";Qn&&console.log(e.name,e.tracks,i);for(const o of e.tracks)if(!(o.times.length<=0)){if(o.name.endsWith(i))this.rootStartPosition=new y().fromArray(o.values,0),this.rootEndPosition=new y().fromArray(o.values,o.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),Qn&&console.log(this.rootPositionOffset);else if(o.name.endsWith(I)&&(this.rootStartQuaternion=new kA().fromArray(o.values,0),this.rootEndQuaternion=new kA().fromArray(o.values,o.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),Qn)){const s=new jt().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",s)}}}get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}}class rS extends Cu{constructor(){super(...arguments);r(this,"models",[]);r(this,"trackOffset");r(this,"target");r(this,"mixer");r(this,"clips",[]);r(this,"actions",[]);r(this,"_actionOffsets",[]);r(this,"_didBind",!1);r(this,"_animator",null);r(this,"_useclipOffsets",!0);r(this,"_totalOffsetPosition",new y);r(this,"_totalOffsetRotation",new kA);r(this,"_totalOffsetPosition2",new y);r(this,"_totalOffsetRotation2",new kA);r(this,"_summedPos",new y);r(this,"_tempPos",new y);r(this,"_summedRot",new kA);r(this,"_tempRot",new kA);r(this,"_clipRotQuat",new kA)}onStateChanged(){this._animator&&Dv(this._animator.gameObject,this,this.director.isPlaying)}createHooks(e,t){var a,B;if(((a=t.tracks)==null?void 0:a.length)<=0){console.warn("No tracks in AnimationClip",t);return}const i=t.tracks[0].name.split("."),I=i[i.length-2],o=I+".position",s=I+".quaternion";let n=!1,C=!1;for(const Q of t.tracks)Q.name.endsWith(o)?(n=!0,this.createPositionInterpolant(t,e,Q)):Q.name.endsWith(s)&&(C=!0,this.createRotationInterpolant(t,e,Q));if(!n||!C){const Q=(B=this.mixer)==null?void 0:B.getRoot(),E=t.tracks[0],c=E.name.lastIndexOf("."),d=E.name.substring(0,c),h=d.substring(d.lastIndexOf(".")+1),l=Q.getObjectByName(h);if(l)if(n){if(!C){const p=t.tracks[0].name.substring(0,c)+".quaternion";Qn&&console.warn("Create quaternion track",h,l);const u=l.quaternion,f=new wn(p,[0,t.duration],[u.x,u.y,u.z,u.w,u.x,u.y,u.z,u.w]);t.tracks.push(f),this.createRotationInterpolant(t,e,f)}}else{const p=d+".position";Qn&&console.warn("Create position track",h,l);const u=l.position,f=new GC(p,[0,t.duration],[u.x,u.y,u.z,u.x,u.y,u.z]);t.tracks.push(f),this.createPositionInterpolant(t,e,f)}}}bind(){if(!this._didBind){this._didBind=!0,Qn&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(const e of this.actions){const t=new agA(e);this._actionOffsets.push(t)}this.target&&(this._animator=nA.getComponent(this.target,Hg)??null,this._animator&&Dv(this._animator.gameObject,this,!0));for(const e of this.models){const t=e.asset,i=t.position,I=t.rotation;i&&i.x!==void 0&&(i.isVector3||(t.position=new y(i.x,i.y,i.z)),I.isQuaternion||(t.rotation=new kA(I.x,I.y,I.z,I.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){const e=this.trackOffset.position;e&&(e.isVector3||(this.trackOffset.position=new y(e.x,e.y,e.z)));const t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new kA(t.x,t.y,t.z,t.w)))}}evaluate(e){var n,C,a,B,Q,E,c;if(this.track.muted||!this.mixer)return;this.bind(),this._totalOffsetPosition.set(0,0,0),this._totalOffsetRotation.set(0,0,0,1),this._totalOffsetPosition2.set(0,0,0),this._totalOffsetRotation2.set(0,0,0,1);let t=0,i=0,I=!1,o=!1,s=0;for(let d=0;d<this.clips.length;d++){const h=this.models[d],l=this.actions[d],p=h.asset;l.weight=0;const u=e>=h.start&&e<=h.end,f=h.preExtrapolationMode,m=h.postExtrapolationMode,M=d<this.clips.length-1?this.models[d+1]:null;let k=u,S=!1;if(!k&&!I&&h.end<e&&m!==Zs.None?(!M||M.start>e)&&(k=!0,I=!0):d==0&&!k&&!o&&h.start>e&&f!==Zs.None&&(!M||M.start<e)&&(k=!0,S=!0,o=!0),k){let F=1;F*=this.evaluateWeight(e,d,this.models,k),F*=this.director.weight;let w=u;if(S)switch(f){case Zs.Hold:break;case Zs.Loop:e+=h.start,w=!0;break;default:e+=h.start,w=!0;break}let R=this.getClipTime(e,h),H=0;const Y=p.duration;if(S&&f===Zs.Hold&&(R=0),w){if(p.loop)for(H+=Math.floor(R/(Y+1e-6));R>Y;)R-=Y}else if(!u&&I)switch(m){case Zs.Hold:R=this.getClipTime(h.end,h);break;case Zs.Loop:R%=Y;break;case Zs.PingPong:const q=Math.floor(R/Y)%2!==0;R%=Y,q&&(R=Y-R);break}h.reversed===!0?l.time=l.getClip().duration-R:l.time=R,l.timeScale=0;const J=Math.max(0,F);if(l.weight=J,s+=J,l.clampWhenFinished=!1,l.isRunning()||l.play(),this._useclipOffsets){const O=t==0?this._totalOffsetPosition:this._totalOffsetPosition2,q=t==0?this._totalOffsetRotation:this._totalOffsetRotation2;t<1&&(i=1-F),t+=1;const b=this._summedPos.set(0,0,0),T=this._tempPos.set(0,0,0),V=this._summedRot.identity(),AA=this._tempRot.identity(),sA=p.rotation;sA&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp(sA,F));const QA=this._actionOffsets[d];if(QA.hasOffsets)for(let FA=0;FA<H;FA++)QA.rootPositionOffset?T.copy(QA.rootPositionOffset):T.set(0,0,0),T.applyQuaternion(V),this._clipRotQuat&&T.applyQuaternion(this._clipRotQuat),QA.rootQuaternionOffset&&(AA.copy(QA.rootQuaternionOffset),V.multiply(AA)),b.add(T);this._clipRotQuat&&q.multiply(this._clipRotQuat),q.multiply(V),p.position&&b.add(p.position),O.add(b)}}}if(this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,i),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,i)),this.__mixerError===void 0&&(Qn||pe())&&((C=(n=this._animator)==null?void 0:n.runtimeAnimatorController)!=null&&C.mixer)&&this.mixer!==((B=(a=this._animator)==null?void 0:a.runtimeAnimatorController)==null?void 0:B.mixer)&&(this.__mixerError=!0,console.error("AnimationTrack mixer is not shared with the animator controller - this might result in the timeline to not animate properly. Please report a bug to the Needle Engine team!",this)),(Q=this._animator)!=null&&Q.runtimeAnimatorController){const d=Math.max(0,1-s);(c=(E=this._animator)==null?void 0:E.runtimeAnimatorController)==null||c.update(d)}else this.mixer.update(e)}createRotationInterpolant(e,t,i){var n;const I=i.createInterpolant.bind(i),o=new kA;this.ensureTrackOffsets();const s=(n=this.trackOffset)==null?void 0:n.rotation;i.createInterpolant=()=>{const C=I(),a=C.evaluate.bind(C);return C.evaluate=B=>{var E;const Q=a(B);if(o.set(Q[0],Q[1],Q[2],Q[3]),o.premultiply(this._totalOffsetRotation),s&&o.premultiply(s),this.director.animationCallbackReceivers)for(const c of this.director.animationCallbackReceivers)(E=c==null?void 0:c.onTimelineRotation)==null||E.call(c,this.director,this.target,B,o);return Q[0]=o.x,Q[1]=o.y,Q[2]=o.z,Q[3]=o.w,Q},C}}createPositionInterpolant(e,t,i){var a,B;const I=i.createInterpolant.bind(i),o=new y;this.ensureTrackOffsets();const s=(a=this.trackOffset)==null?void 0:a.rotation,n=(B=this.trackOffset)==null?void 0:B.position;let C;i.createInterpolant=()=>{const Q=I(),E=Q.evaluate.bind(Q);return Q.evaluate=c=>{var h,l,p;const d=E(c);if(o.set(d[0],d[1],d[2]),t.removeStartOffset&&(C===void 0?(C=null,C=(l=(h=this._actionOffsets.find(u=>u.clip===e))==null?void 0:h.rootStartPosition)==null?void 0:l.clone()):C!=null&&C.isVector3&&o.sub(C)),o.applyQuaternion(this._totalOffsetRotation),o.add(this._totalOffsetPosition),s&&o.applyQuaternion(s),n&&(o.x-=n.x,o.y+=n.y,o.z+=n.z),this.director.animationCallbackReceivers)for(const u of this.director.animationCallbackReceivers)(p=u==null?void 0:u.onTimelinePosition)==null||p.call(u,this.director,this.target,c,o);return d[0]=o.x,d[1]=o.y,d[2]=o.z,d},Q}}}const rgA=IA("mutetimeline"),dE=class extends Cu{constructor(){super(...arguments);r(this,"models",[]);r(this,"listener");r(this,"audio",[]);r(this,"audioContextTimeOffset",[]);r(this,"lastTime",0);r(this,"audioSource");r(this,"_audioLoader",null);r(this,"_playableDirectorResumed",!1)}getAudioFilePath(e){const t=this.director.sourceId;return bC(t,e)}onAllowAudioChanged(e){for(let t=0;t<this.models.length;t++){const i=this.models[t];this.audio[t].setVolume(e?i.asset.volume:0)}}addModel(e){const t=new XR(this.listener);this.audio.push(t);const i=e;i._didTriggerPlay=!1,this.models.push(i)}onDisable(){for(const e of this.audio)e.isPlaying&&e.stop();for(const e of this.models)e._didTriggerPlay=!1}onDestroy(){for(const e of this.audio)e.source&&(e==null||e.disconnect());this.audio.length=0}onMuteChanged(){if(this.muted)for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t!=null&&t.isPlaying&&t.stop()}}stop(){for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t!=null&&t.isPlaying&&t.stop()}for(const e of this.models)e._didTriggerPlay=!1}onPauseChanged(){for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t!=null&&t.isPlaying&&t.stop()}this._playableDirectorResumed=this.director.isPlaying}evaluate(e){if(rgA||this.track.muted||this.director.speed<0)return;const t=this.director.context.application.muted,i=this._playableDirectorResumed;this._playableDirectorResumed=!1;const I=t?.1:0;for(let o=0;o<this.models.length;o++){const s=this.models[o],n=this.audio[o],C=s.asset;if((!n||!n.buffer)&&this.isInTimeRange(s,e-1,e+1)&&this.handleAudioLoading(s,n),hi.userInteractionRegistered!==!1&&!(n===null||!n.buffer))if(n.playbackRate=this.director.context.time.timeScale*this.director.speed,n.loop=C.loop,e>=s.start&&e<=s.end&&e<this.director.duration){if(!n.isPlaying||!this.director.isPlaying)(i||!s._didTriggerPlay&&this.lastTime<e)&&(s.duration*s.timeScale>.3?n.offset=s.clipIn+(e-s.start)*s.timeScale:n.offset=0,Qn&&console.log("Timeline Audio ("+this.track.name+") play with offset "+n.offset+" - "+s.asset.clip),n.play(I),s._didTriggerPlay=!0);else{const B=s.clipIn+(e-s.start)*s.timeScale,Q=n.context.currentTime-n._startedAt+n.offset;Math.abs(B-Q)>.3&&(n.offset=B,n.stop(),n.play(I))}let a=C.volume;if(this.track.volume!==void 0&&(a*=this.track.volume),t&&(a=0),s.easeInDuration>0){const B=Math.min((e-s.start)/s.easeInDuration,1);a*=B}if(s.easeOutDuration>0){const B=Math.min((s.end-e)/s.easeOutDuration,1);a*=B}n.setVolume(a*this.director.weight)}else s._didTriggerPlay=!1,this.director.isPlaying&&n.isPlaying&&n.stop()}this.lastTime=e}loadAudio(e,t=0,i=0){let I=null;const o=e-i,s=e+t;for(const n of this.models)if(this.isInTimeRange(n,o,s)){const C=this.audio[this.models.indexOf(n)],a=this.handleAudioLoading(n,C);a!==null&&(I===null&&(I=[]),I.push(a))}return I!==null?Promise.all(I):null}isInTimeRange(e,t,i){return t<=e.start&&i>=e.end||t>=e.start&&t<=e.end||i>=e.start&&i<=e.end}static dispose(){dE._audioBuffers.clear()}handleAudioLoading(e,t){this._audioLoader||(this._audioLoader=new OD);const i=this.getAudioFilePath(e.asset.clip);if(dE._audioBuffers.get(i)){const o=dE._audioBuffers.get(i);return o.then(s=>{s&&t.setBuffer(s)}),o}Qn&&console.warn("LOAD audio track",i,this.director.sourceId);const I=new Promise((o,s)=>{this._audioLoader.load(i,n=>{t.setBuffer(n),o(n)},void 0,n=>{console.error("Error loading audio",n),o(null)})});return dE._audioBuffers.set(i,I),I}};let pB=dE;r(pB,"_audioBuffers",new Map);class od extends Cu{constructor(){super(...arguments);r(this,"models",[]);r(this,"didTrigger",[]);r(this,"receivers",[])}evaluate(e){var i;if(this.track.muted)return;const t=this.director.context.time.deltaTime*1.5;for(let I=0;I<this.models.length;I++){const o=this.models[I],s=this.didTrigger[I],n=o.time-e;let C=!1;if(o.retroActive)C=n<=1e-6;else{const a=Math.abs(n);(a===0||a>=1e-5&&a<t)&&(C=!0)}if(C){if(!s)if(Qn&&console.log("Trigger signal",e,o.time,o),this.didTrigger[I]=!0,((i=this.receivers)==null?void 0:i.length)<=0)dc.invoke(o.asset);else for(const a of this.receivers)a&&a.invoke(o.asset)}else o.emitOnce||(this.didTrigger[I]=!1)}}}class BS extends Cu{constructor(){super(...arguments);r(this,"models",[]);r(this,"timelines",[]);r(this,"_previousActiveModel",null)}resolveSourceObjects(e){for(let t=this.models.length-1;t>=0;t--){const I=this.models[t].asset;if(!I.sourceObject||typeof I.sourceObject!="object"){console.log("no source object, removing model",t,I),this.models.splice(t,1);continue}else{const o=nA.getComponent(I.sourceObject,mC);this.timelines.push(o),o&&I.updateDirector&&(o.playOnAwake=!1)}}}evaluate(e){var t;this._previousActiveModel=null;for(let i=0;i<this.models.length;i++){const I=this.models[i],o=I.asset;if(e>=I.start&&e<=I.end){this._previousActiveModel=I;const s=this.getClipTime(e,I);if(o.controlActivation){const n=o.sourceObject;n.visible=!0}if(o.updateDirector){const n=this.timelines[i];n&&(n.isPlaying&&n.pause(),n.time=s,n.evaluate())}}else{const s=(t=this._previousActiveModel)==null?void 0:t.asset;if(o.controlActivation){const n=o.sourceObject;(s==null?void 0:s.sourceObject)!==n&&(n.visible=!1)}}}}}const YQ=IA("debugtimeline"),Wy=class extends UA{constructor(){super(...arguments);r(this,"playableAsset");r(this,"playOnAwake");r(this,"extrapolationMode",1);r(this,"waitForAudio",!0);r(this,"_visibilityChangeEvt");r(this,"_clonedPlayableAsset",!1);r(this,"_speed",1);r(this,"_guidsMap");r(this,"_isPlaying",!1);r(this,"_internalUpdateRoutine");r(this,"_isPaused",!1);r(this,"_isStopping",!1);r(this,"_time",0);r(this,"_duration",0);r(this,"_weight",1);r(this,"_animationTracks",[]);r(this,"_audioTracks",[]);r(this,"_signalTracks",[]);r(this,"_controlTracks",[]);r(this,"_customTracks",[]);r(this,"_allTracks",[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks]);r(this,"animationCallbackReceivers",[])}static registerCreateTrack(e,t){this.createTrackFunctions[e]=t}get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(e){typeof e=="number"&&!Number.isNaN(e)?this._time=e:(YQ||ZI())&&console.error("INVALID TIMELINE.TIME VALUE",e,this.name)}get duration(){return this._duration}set duration(e){this._duration=e}get weight(){return this._weight}set weight(e){this._weight=e}get speed(){return this._speed}set speed(e){this._speed=e}awake(){var e,t,i;YQ&&console.log(this,(e=this.playableAsset)==null?void 0:e.tracks),this.rebuildGraph(),this.isValid()||console.warn("PlayableDirector is not valid",this.playableAsset,(t=this.playableAsset)==null?void 0:t.tracks,Array.isArray((i=this.playableAsset)==null?void 0:i.tracks),this)}onEnable(){var e,t,i;for(const I of this._audioTracks)(e=I.onEnable)==null||e.call(I);for(const I of this._customTracks)(t=I.onEnable)==null||t.call(I);for(const I of this._animationTracks)(i=I.onEnable)==null||i.call(I);this.playOnAwake&&this.play(),this._visibilityChangeEvt||(this._visibilityChangeEvt=()=>{switch(document.visibilityState){case"hidden":this.setAudioTracksAllowPlaying(!1);break;case"visible":this.setAudioTracksAllowPlaying(!0);break}}),window.addEventListener("visibilitychange",this._visibilityChangeEvt)}onDisable(){var e,t,i;this.stop();for(const I of this._audioTracks)(e=I.onDisable)==null||e.call(I);for(const I of this._customTracks)(t=I.onDisable)==null||t.call(I);for(const I of this._animationTracks)(i=I.onDisable)==null||i.call(I);this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){var e;for(const t of this._allTracks)for(const i of t)(e=i.onDestroy)==null||e.call(i)}rebuildGraph(){this.isValid()&&(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}async play(){if(!this.isValid())return;const e=this._isPaused==!0;if(this._isPaused=!1,!this._isPlaying){if(this._isPlaying=!0,e&&this.invokePauseChangedMethodsOnTracks(),this.waitForAudio){const t=[];for(const i of this._audioTracks){const I=i.loadAudio(this._time,1,0);I&&t.push(I)}if(t.length>0&&(await Promise.all(t),!this._isPlaying))return;for(;this._audioTracks.length>0&&this._isPlaying&&!hi.userInteractionRegistered&&this.waitForAudio;)await Ns(200)}this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate(),zi.LateUpdate)}}pause(){this.isValid()&&(this._isPlaying=!1,!this._isPaused&&(this._isPaused=!0,this.internalEvaluate(),this.invokePauseChangedMethodsOnTracks(),this.invokeStateChangedMethodsOnTracks()))}stop(){this._isStopping=!0;for(const i of this._audioTracks)i.stop();const e=this._isPaused==!0,t=this._isPlaying;this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.internalEvaluate(),e&&this.invokePauseChangedMethodsOnTracks()),this._isPlaying=!1,this._isPaused=!1,e&&!t&&this.invokePauseChangedMethodsOnTracks(),t&&this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine&&this.stopCoroutine(this._internalUpdateRoutine),this._internalUpdateRoutine=null,this._isStopping=!1}evaluate(){this.internalEvaluate(!0)}isValid(){return this.playableAsset&&this.playableAsset.tracks&&Array.isArray(this.playableAsset.tracks)}*forEachTrack(){for(const e of this._allTracks)for(const t of e)yield t}get audioTracks(){return this._audioTracks}resolveGuids(e){this._guidsMap=e}invokePauseChangedMethodsOnTracks(){var e;for(const t of this.forEachTrack())(e=t.onPauseChanged)==null||e.call(t)}invokeStateChangedMethodsOnTracks(){var e;for(const t of this.forEachTrack())(e=t.onStateChanged)==null||e.call(t,this._isPlaying)}*internalUpdate(){for(;this._isPlaying&&this.activeAndEnabled;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime*this.speed,this.internalEvaluate()),yield}internalEvaluate(e=!1){if(!this.isValid())return;let t=this._time;switch(this.extrapolationMode){case 0:this._speed>0?t=Math.min(t,this._duration):this._speed<0&&(t=Math.max(t,0)),this._time=t;break;case 1:t%=this._duration,this._time=t;break;case 2:if(t>this._duration){this.stop();return}break}const i=this._time;for(const I of this.playableAsset.tracks)if(!I.muted)switch(I.type){case no.Activation:if(!e&&!this._isPlaying)continue;for(let o=0;o<I.outputs.length;o++){const s=I.outputs[o];if(typeof s=="object"){let n=!1;if(I.clips)for(const a of I.clips)a.start<=i&&i<=a.end&&(n=!0);const C=s;C.visible!==void 0&&C.visible!==n&&(C.visible=n,YQ&&console.warn(this.name,"set ActivationTrack-"+o,C.name,n,i))}}break}if(!this._isStopping)for(const I of this._animationTracks)I.evaluate(i);for(const I of this._audioTracks)I.evaluate(i);for(const I of this._signalTracks)I.evaluate(i);for(const I of this._controlTracks)I.evaluate(i);for(const I of this._customTracks)I.evaluate(i)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=vd(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;const e=this.findRoot(this.gameObject);for(const t of this.playableAsset.tracks){for(let i=t.outputs.length-1;i>=0;i--){let I=t.outputs[i];if(typeof I=="string"){this._guidsMap&&this._guidsMap[I]&&(I=this._guidsMap[I]);const o=nA.findByGuid(I,e);o===null||typeof o!="object"?(t.outputs.splice(i,1),console.warn("Failed to resolve binding",I,t.name,t.type)):(YQ&&console.log("Resolved binding",I,"to",o),t.outputs[i]=o)}else if(I===null){if(t.outputs.splice(i,1),Wy.createTrackFunctions[t.type])continue;t.type!==no.Audio&&t.type!==no.Control&&t.type!==no.Marker&&t.type!==no.Signal&&console.warn("Missing binding",I,t.name,t.type,this.name,this.playableAsset.name)}}if(t.type===no.Control&&t.clips)for(let i=0;i<t.clips.length;i++){const I=t.clips[i];let o=I.asset.sourceObject;if(typeof o=="string"){this._guidsMap&&this._guidsMap[o]&&(o=this._guidsMap[o]);const s=nA.findByGuid(o,e);s===null||typeof s!="object"?console.warn("Failed to resolve sourceObject binding",o,t.name,I):(YQ&&console.log("Resolved binding",o,"to",s),I.asset.sourceObject=s)}}}}findRoot(e){return e.parent?this.findRoot(e.parent):e}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const e of this.playableAsset.tracks)if(e.muted!==!0){if(e.clips)for(const t of e.clips)t.end>this._duration&&(this._duration=t.end);if(e.markers)for(const t of e.markers)t.time>this._duration&&(this._duration=t.time+.001)}}}setupAndCreateTrackHandlers(){var t,i,I;if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let e=nA.findObjectOfType(_a,this.context);for(const o of this.playableAsset.tracks){const s=o.type,n=Wy.createTrackFunctions[s];if(n!=null){const C=n(this,o);if(typeof C.evaluate=="function"){C.director=this,C.track=o,this._customTracks.push(C);continue}}if(o.type===no.Animation){if(!o.clips||o.clips.length<=0){YQ&&console.warn("Animation track has no clips",o);continue}for(let C=o.outputs.length-1;C>=0;C--){let a=o.outputs[C];if(a instanceof pA){const Q=nA.getOrAddComponent(a,Hg);Q&&(a=Q)}const B=(t=a==null?void 0:a.gameObject)==null?void 0:t.animations;if(B){const Q=new rS;Q.trackOffset=o.trackOffset,Q.director=this,Q.track=o;for(let E=0;E<o.clips.length;E++){const c=o.clips[E],d=c.asset;if(!d){console.error(`Timeline ${this.name}: clip #${E} on track "${o.name}" has no animation data`);continue}const h=d.clip;let l=h;if((typeof l=="string"||typeof l=="number")&&(l=B.find(u=>u.name===h)),!l){console.warn("Could not find animationClip for model",c,o.name,this.name,(i=this.playableAsset)==null?void 0:i.name);continue}a instanceof Hg&&a.runtimeAnimatorController&&(a.__internalDidAwakeAndStart||a.initializeRuntimeAnimatorController(),a.runtimeAnimatorController.mixer||a.runtimeAnimatorController.bind(a),Q.mixer=a.runtimeAnimatorController.mixer),Q.mixer||(Q.mixer=new Kw(a.gameObject)),Q.clips.push(l),Q.mixer.uncacheAction(l),Q.createHooks(c.asset,l);const p=Q.mixer.clipAction(l);Q.actions.push(p),Q.models.push(c)}this._animationTracks.push(Q)}}}else if(o.type===no.Audio){if(!o.clips||o.clips.length<=0)continue;const C=new pB;C.director=this,C.track=o,C.audioSource=o.outputs.find(a=>a instanceof hi),this._audioTracks.push(C),e||(e=(I=this.context.mainCameraComponent)==null?void 0:I.gameObject.addNewComponent(_a)),C.listener=e.listener;for(let a=0;a<o.clips.length;a++){const B=o.clips[a];C.addModel(B)}}else if(o.type===no.Marker){const C=new od;if(C.director=this,C.track=o,o.markers)for(const a of o.markers)switch(a.type){case mN.Signal:C.models.push(a),C.didTrigger.push(!1);break}if(C!==null&&C.models.length>0){const a=nA.getComponent(this.gameObject,dc);a&&(C.receivers.push(a),this._signalTracks.push(C))}}else if(o.type===no.Signal){const C=new od;if(C.director=this,C.track=o,o.markers)for(const a of o.markers)C.models.push(a),C.didTrigger.push(!1);for(const a of o.outputs)C.receivers.push(a);this._signalTracks.push(C)}else if(o.type===no.Control){const C=new BS;if(C.director=this,C.track=o,o.clips)for(const a of o.clips)C.models.push(a);C.resolveSourceObjects(this.context),this._controlTracks.push(C)}}}setAudioTracksAllowPlaying(e){for(const t of this._audioTracks)t.onAllowAudioChanged(e)}registerAnimationCallback(e){this.animationCallbackReceivers.push(e)}unregisterAnimationCallback(e){const t=this.animationCallbackReceivers.indexOf(e);t!==-1&&this.animationCallbackReceivers.splice(t,1)}};let mC=Wy;r(mC,"createTrackFunctions",{});const cD=Symbol("objectIsAnimatedData");function Dv(g,A,e){if(!g)return;if(g[cD]===void 0){if(!e)return;g[cD]=new Set}const t=g[cD];e?t.add(A):t.has(A)&&t.delete(A)}function BgA(g){if(!g)return!1;const A=g[cD];return A!==void 0&&A.size>0}Bt.registerCallback(vi.ContextCreated,g=>{const A=g.context.domElement.getAttribute("autoplay");if(A!==void 0&&(A===""||A==="true")&&g.files)for(const e of g.files)nA.foreachComponent(e.file.scene,i=>{if(i.enabled!==!1){if(i instanceof qI&&i.playAutomatically||i instanceof Hg||i instanceof mC&&i.playOnAwake===!0)return!0;if(i instanceof qI)return i.playAutomatically=!0,!0;if(i instanceof mC)return i.playOnAwake=!0,!0}},!0)!==!0&&QgA(e.file)});function QgA(g){if(!g||!g.animations)return;for(let e=0;e<g.animations.length;e++){const t=g.animations[e];if(!(!t.tracks||t.tracks.length<=0))for(const i in t.tracks){const I=t.tracks[i],o=I.__objectName??I.name.substring(0,I.name.indexOf("."));let s=g.scene.getObjectByName(o);if(!s&&(s=g.scene.getObjectByProperty("uuid",o),!s))continue;let n=A(s);n||(n=Ya(g.scene,new qI));const C=n.animations=n.animations||[];t.name_animator=n.name,C.indexOf(t)<0&&C.push(t)}}function A(e){var i;if(!e)return;const t=(i=e.userData)==null?void 0:i.components;if(t&&t.length>0)for(let I=0;I<t.length;I++){const o=t[I];if(o instanceof Hg||o instanceof qI)return e}return A(e.parent)}}class EgA{constructor(){r(this,"_context")}get context(){return this._context??Le.Current}get isStateMachineBehaviour(){return!0}}class _l{constructor(A,e,t,i){r(this,"name");r(this,"nameHash");r(this,"normalizedTime");r(this,"length");r(this,"speed");r(this,"action");this.name=A.name,this.nameHash=A.hash,this.normalizedTime=e,this.length=t,this.speed=i,this.action=A.motion.action||null}}function uO(g,A){return{name:"",isLooping:!1,guid:(A==null?void 0:A.generateUUID())??ng.generateUUID(),index:-1,clip:new KI(g,1,[])}}var Da=(g=>(g[g.If=1]="If",g[g.IfNot=2]="IfNot",g[g.Greater=3]="Greater",g[g.Less=4]="Less",g[g.Equals=6]="Equals",g[g.NotEqual=7]="NotEqual",g))(Da||{}),MN=(g=>(g[g.Float=1]="Float",g[g.Int=3]="Int",g[g.Bool=4]="Bool",g[g.Trigger=9]="Trigger",g))(MN||{});const DI=IA("debuganimatorcontroller"),Ef=IA("debugrootmotion");class wo{constructor(A){r(this,"_speed",1);r(this,"normalizedStartOffset",0);r(this,"animator");r(this,"model");r(this,"_mixer");r(this,"_activeState");r(this,"_activeStates",[]);r(this,"rootMotionHandler");this.model=A,DI&&console.log(this)}static createFromClips(A,e={looping:!1,autoTransition:!0,transitionDuration:0}){const t=[];for(let o=0;o<A.length;o++){const s=A[o],n=[];if(e.autoTransition!==!1){const a=e.transitionDuration??0,B=a/s.duration;let Q=o;(e.autoTransition===void 0||e.autoTransition===!0)&&(Q=(o+1)%A.length),n.push({exitTime:1-B,offset:0,duration:a,hasExitTime:!0,destinationState:Q,conditions:[]})}const C={name:s.name,hash:o,motion:{name:s.name,clip:s,isLooping:(e==null?void 0:e.looping)??!1},transitions:n,behaviours:[]};t.push(C)}const i={name:"AnimatorController",guid:new yg(Date.now()).generateUUID(),parameters:[],layers:[{name:"Base Layer",stateMachine:{defaultState:0,states:t}}]};return new wo(i)}play(A,e=-1,t=Number.NEGATIVE_INFINITY,i=0){if(e<0)e=0;else if(e>=this.model.layers.length){console.warn("invalid layer");return}const o=this.model.layers[e].stateMachine;for(const s of o.states)if(s.name===A||s.hash===A){DI&&console.log("transition to ",s),this.transitionTo(s,i,t);return}console.warn("Could not find "+A+" to play")}reset(){this.setStartTransition()}setBool(A,e){var i,I;const t=typeof A=="string"?"name":"hash";return(I=(i=this.model)==null?void 0:i.parameters)==null?void 0:I.filter(o=>o[t]===A).forEach(o=>o.value=e)}getBool(A){var t,i,I;const e=typeof A=="string"?"name":"hash";return((I=(i=(t=this.model)==null?void 0:t.parameters)==null?void 0:i.find(o=>o[e]===A))==null?void 0:I.value)??!1}setFloat(A,e){var I,o;const t=typeof A=="string"?"name":"hash",i=(o=(I=this.model)==null?void 0:I.parameters)==null?void 0:o.filter(s=>s[t]===A);return i.forEach(s=>s.value=e),(i==null?void 0:i.length)>0}getFloat(A){var t,i,I;const e=typeof A=="string"?"name":"hash";return((I=(i=(t=this.model)==null?void 0:t.parameters)==null?void 0:i.find(o=>o[e]===A))==null?void 0:I.value)??0}setInteger(A,e){var i,I;const t=typeof A=="string"?"name":"hash";return(I=(i=this.model)==null?void 0:i.parameters)==null?void 0:I.filter(o=>o[t]===A).forEach(o=>o.value=e)}getInteger(A){var t,i,I;const e=typeof A=="string"?"name":"hash";return((I=(i=(t=this.model)==null?void 0:t.parameters)==null?void 0:i.find(o=>o[e]===A))==null?void 0:I.value)??0}setTrigger(A){var t,i;DI&&console.log("SET TRIGGER",A);const e=typeof A=="string"?"name":"hash";return(i=(t=this.model)==null?void 0:t.parameters)==null?void 0:i.filter(I=>I[e]===A).forEach(I=>I.value=!0)}resetTrigger(A){var t,i;const e=typeof A=="string"?"name":"hash";return(i=(t=this.model)==null?void 0:t.parameters)==null?void 0:i.filter(I=>I[e]===A).forEach(I=>I.value=!1)}getTrigger(A){var t,i,I;const e=typeof A=="string"?"name":"hash";return((I=(i=(t=this.model)==null?void 0:t.parameters)==null?void 0:i.find(o=>o[e]===A))==null?void 0:I.value)??!1}isInTransition(){return this._activeStates.length>1}setSpeed(A){this._speed=A}FindState(A){return this.findState(A)}findState(A){if(!A)return null;if(Array.isArray(this.model.layers)){for(const e of this.model.layers)for(const t of e.stateMachine.states)if(t.name===A||t.hash==A)return t}return null}getCurrentStateInfo(){if(!this._activeState)return null;const A=this._activeState.motion.action;if(!A)return null;const e=this._activeState.motion.clip.duration,t=e<=0?0:Math.abs(A.time/e);return new _l(this._activeState,t,e,this._speed)}get currentAction(){if(!this._activeState)return null;const A=this._activeState.motion.action;return A||null}get context(){var A;return(A=this.animator)==null?void 0:A.context}get mixer(){return this._mixer}bind(A){A?this.animator!==A&&(this.animator=A,this._mixer=new Kw(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;DI&&console.warn("AnimatorController clone()",this.model);const A=vd(this.model,(t,i,I)=>I==null?!0:!(I.type==="Object3D"||I.isObject3D===!0||t2(I)||I.tracks!==void 0||I instanceof wo));return console.assert(A!==this.model),new wo(A)}update(A){var t,i;if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates(A);const e=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&((t=this.rootMotionHandler)==null||t.onBeforeUpdate(A)),this._mixer.update(e),this.animator.applyRootMotion&&((i=this.rootMotionHandler)==null||i.onAfterUpdate(A))}get activeState(){return this._activeState}updateActiveStates(A){for(let e=0;e<this._activeStates.length;e++){const t=this._activeStates[e],i=t.motion;if(!i.action)this._activeStates.splice(e,1),e--;else{const I=i.action;I.weight=A,I.getEffectiveWeight()<=0&&!I.isRunning()&&(DI&&console.debug("REMOVE",t.name,I.getEffectiveWeight(),I.isRunning(),I.isScheduled()),this._activeStates.splice(e,1),e--)}}}setStartTransition(){for(const A of this.model.layers){const e=A.stateMachine;e.defaultState===void 0&&(DI&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",A),e.defaultState=0);const t=e.states[e.defaultState];this.transitionTo(t,0,this.normalizedStartOffset)}}evaluateTransitions(){var I;let A=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;A=!0}const e=this._activeState,t=e.motion.action;for(const o of e.transitions){if(!o.hasExitTime&&o.conditions.length<=0)continue;let s=!0;for(const n of o.conditions)if(!this.evaluateCondition(n)){s=!1;break}if(s)if(t){const n=e.motion.clip.duration,C=n<=0?1:Math.abs(t.time/n);let a=!1;if(o.hasExitTime?t.timeScale>0?a=C>=o.exitTime:t.timeScale<0&&(a=1-C>=o.exitTime):a=!0,a){for(const B of o.conditions){const Q=this.model.parameters.find(E=>E.name===B.parameter);(Q==null?void 0:Q.type)===MN.Trigger&&Q.value&&(Q.value=!1)}t.clampWhenFinished=!0,DI&&console.log("transition to "+o.destinationState,o,C,o.exitTime,o.hasExitTime),this.transitionTo(o.destinationState,o.duration,o.offset);return}}else{this.transitionTo(o.destinationState,o.duration,o.offset);return}}if(t){let o=e.speed??1;e.speedParameter&&(o*=this.getFloat(e.speedParameter)),o!==void 0&&(t.timeScale=o*this._speed)}let i=!1;if(e.motion.isLooping&&t&&(t.time>=t.getClip().duration?(i=!0,t.reset(),t.time=0,t.play()):t.time<=0&&t.timeScale<0&&(i=!0,t.reset(),t.time=t.getClip().duration,t.play())),!i&&e&&!A&&t&&this.animator&&e.behaviours){const o=t==null?void 0:t.getClip().duration,s=t.time/o,n=new _l(this._activeState,s,o,this._speed);for(const C of e.behaviours)C.instance&&((I=C.instance.onStateUpdate)==null||I.call(C.instance,this.animator,n,0))}}getState(A,e){return typeof A=="number"&&(A==-1&&(A=this.model.layers[e].stateMachine.defaultState,A===void 0&&(DI&&console.warn("AnimatorController default state is undefined: ",this.model,"Layer: "+e),A=0)),A=this.model.layers[e].stateMachine.states[A]),A}transitionTo(A,e,t){var C,a,B,Q,E,c,d,h;if(!this.animator)return;const i=0;if(A=this.getState(A,i),!(A!=null&&A.motion)||!A.motion.clip||!(A.motion.clip instanceof KI))return;const I=this._activeState===A;if(I){const l=A.motion;if(!l.action_loopback&&l.clip){const p=this.rootMotionHandler?this.animator.gameObject.matrix.clone():null;this._mixer.uncacheAction(l.clip,this.animator.gameObject),p&&p.decompose(this.animator.gameObject.position,this.animator.gameObject.quaternion,this.animator.gameObject.scale),l.action_loopback=this.createAction(l.clip)}}if((C=this._activeState)!=null&&C.behaviours&&this._activeState.motion.action){const l=(a=this._activeState)==null?void 0:a.motion.clip.duration,p=this._activeState.motion.action.time/l,u=new _l(this._activeState,p,l,this._speed);for(const f of this._activeState.behaviours)(Q=(B=f.instance)==null?void 0:B.onStateExit)==null||Q.call(f.instance,this.animator,u,i)}const o=(E=this._activeState)==null?void 0:E.motion.action;o&&o.fadeOut(e),I&&(A.motion.action=A.motion.action_loopback,A.motion.action_loopback=o);const s=this._activeState;this._activeState=A;const n=(c=A.motion)==null?void 0:c.action;if(n){if(t=Math.max(0,Math.min(1,t)),A.cycleOffsetParameter){let p=this.getFloat(A.cycleOffsetParameter);typeof p=="number"?(p<0&&(p+=1),t+=p,t%=1):DI&&console.warn("AnimatorController cycle offset parameter is not a number",A.cycleOffsetParameter)}else typeof A.cycleOffset=="number"&&(t+=A.cycleOffset,t%=1);n.isRunning()&&n.stop(),n.reset(),n.enabled=!0;const l=A.motion.clip.duration;if(n.time=I?0:t*l,n.timeScale<0&&(n.time=l-n.time),n.clampWhenFinished=!0,n.setLoop(Rh,0),e>0?n.fadeIn(e):n.weight=1,n.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(n),this._activeStates.includes(A)||this._activeStates.push(A),this._activeState.behaviours){const p=new _l(A,t,l,this._speed);for(const u of this._activeState.behaviours)(h=(d=u.instance)==null?void 0:d.onStateEnter)==null||h.call(u.instance,this.animator,p,i)}}else DI&&(A.__warned_no_motion||(A.__warned_no_motion=!0,console.warn("No action",A.motion,this)));DI&&console.log("TRANSITION FROM "+(s==null?void 0:s.name)+" TO "+A.name,e,o,n,n==null?void 0:n.getEffectiveTimeScale(),n==null?void 0:n.getEffectiveWeight(),n==null?void 0:n.isRunning(),n==null?void 0:n.isScheduled(),n==null?void 0:n.paused)}createAction(A){var t,i;if(this._mixer.existingAction(A)&&this._mixer.uncacheAction(A,(t=this.animator)==null?void 0:t.gameObject),(i=this.animator)!=null&&i.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new cgA(this));const I=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,I,A)}else return this._mixer.clipAction(A)}evaluateCondition(A){const e=this.model.parameters.find(t=>t.name===A.parameter);if(!e)return!1;switch(A.mode){case Da.If:return e.value===!0;case Da.IfNot:return e.value===!1;case Da.Greater:return e.value>A.threshold;case Da.Less:return e.value<A.threshold;case Da.Equals:return e.value===A.threshold;case Da.NotEqual:return e.value!==A.threshold}return!1}createActions(A){var e,t,i,I;DI&&console.log("AnimatorController createActions",this.model);for(const o of this.model.layers){const s=o.stateMachine;for(let n=0;n<s.states.length;n++){const C=s.states[n];C.transitions||(C.transitions=[]);for(const a of C.transitions)a.conditions||(a.conditions=[]);if(C.motion||(C.motion=uO(C.name)),this.animator&&C.motion.clips){const a=(e=C.motion.clips)==null?void 0:e.find(B=>{var Q,E;return B.node.name===((E=(Q=this.animator)==null?void 0:Q.gameObject)==null?void 0:E.name)});a?C.motion.clip=a.clip:(DI||pe())&&console.warn('Could not find clip for animator "'+((i=(t=this.animator)==null?void 0:t.gameObject)==null?void 0:i.name)+'"',C.motion.clips.map(B=>B.node.name))}if(!C.motion.clip){const a=new KI(void 0,void 0,[]);C.motion.clip=a}if((I=C.motion)!=null&&I.clip){const a=C.motion.clip;if(a instanceof KI){const B=this.createAction(a);C.motion.action=B}else(DI||pe())&&console.warn("No valid animationclip assigned",C)}if(C.behaviours&&Array.isArray(C.behaviours))for(const a of C.behaviours){if(!(a!=null&&a.typeName))continue;const B=X.get(a.typeName),Q=new B;Q.isStateMachineBehaviour&&(Q._context=this.context??void 0,TE(Q,a.properties),a.instance=Q),DI&&console.log("Created animator controller behaviour",C.name,a.typeName,a.properties,Q)}}}}*enumerateActions(){if(this.model.layers)for(const A of this.model.layers){const e=A.stateMachine;for(let t=0;t<e.states.length;t++){const i=e.states[t];i!=null&&i.motion&&(i.motion.action&&(yield i.motion.action),i.motion.action_loopback&&(yield i.motion.action_loopback))}}}}class yv{constructor(A,e){r(this,"track");r(this,"createdInterpolant");r(this,"originalEvaluate");r(this,"customEvaluate");this.track=A;const t=A,i=t.createInterpolant.bind(A);t.createInterpolant=()=>(t.createInterpolant=i,this.createdInterpolant=i(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=I=>{if(!this.originalEvaluate)return;const o=this.originalEvaluate(I);return e(I,o)},this.createdInterpolant.evaluate=this.customEvaluate,this.createdInterpolant)}dispose(){this.createdInterpolant&&this.originalEvaluate&&(this.createdInterpolant.evaluate=this.originalEvaluate),this.track=void 0,this.createdInterpolant=null,this.originalEvaluate=void 0,this.customEvaluate=void 0}}const Ig=class{constructor(A,e,t,i,I){r(this,"_action");r(this,"root");r(this,"clip");r(this,"positionWrapper",null);r(this,"rotationWrapper",null);r(this,"context");r(this,"positionChange",new y);r(this,"rotationChange",new kA);r(this,"_prevTime",0);if(this.context=A,this.root=e,this.clip=t,Ig.firstKeyframeRotation[this.cacheId]||(Ig.firstKeyframeRotation[this.cacheId]=new kA),I){const o=I.values;Ig.firstKeyframeRotation[this.cacheId].set(o[0],o[1],o[2],o[3])}Ig.spaceRotation[this.cacheId]||(Ig.spaceRotation[this.cacheId]=new kA),Ig.effectiveSpaceRotation[this.cacheId]||(Ig.effectiveSpaceRotation[this.cacheId]=new kA),Ig.clipOffsetRotation[this.cacheId]=new kA,I&&Ig.clipOffsetRotation[this.cacheId].set(I.values[0],I.values[1],I.values[2],I.values[3]).invert(),this.handlePosition(t,i),this.handleRotation(t,I)}set action(A){this._action=A}get action(){return this._action}get cacheId(){return this.root.uuid}onStart(A){if(A.getClip()!==this.clip)return;Ig.lastObjRotation[this.cacheId]||(Ig.lastObjRotation[this.cacheId]=this.root.quaternion.clone());const e=Ig.lastObjRotation[this.cacheId];if(Ig.spaceRotation[this.cacheId].copy(e),Ef){const t=new jt().setFromQuaternion(e);console.log("START",this.clip.name,te.toDegrees(t.y),this.root.position.z)}}getClipRotationOffset(){return Ig.clipOffsetRotation[this.cacheId]}handlePosition(A,e){if(e){const t=this.root;Ef&&t.add(new $o),Ig.lastObjPosition[this.cacheId]||(Ig.lastObjPosition[this.cacheId]=this.root.position.clone());const i=new y,I=new y;this.positionWrapper=new yv(e,(o,s)=>{const n=this.action.getEffectiveWeight();return Ef&&t.position.length()>8&&t.position.set(0,t.position.y,0),o>this._prevTime&&(i.set(s[0],s[1],s[2]),i.sub(I),i.multiplyScalar(n),i.applyQuaternion(this.getClipRotationOffset()),i.applyQuaternion(t.quaternion),this.positionChange.copy(i)),I.fromArray(s),this._prevTime=o,s[0]=0,s[1]=0,s[2]=0,s})}}handleRotation(A,e){if(e){if(Ef){const o=e.values,s=new jt().setFromQuaternion(new kA(o[0],o[1],o[2],o[3]));console.log(A.name,e.name,"FIRST ROTATION IN TRACK",te.toDegrees(s.y));const n=e.values.length-4,C=new kA().set(o[n],o[n+1],o[n+2],o[n+3]),a=new jt().setFromQuaternion(C);console.log(A.name,e.name,"LAST ROTATION IN TRACK",te.toDegrees(a.y))}let t=0;const i=new kA,I=new kA;this.rotationWrapper=new yv(e,(o,s)=>(o>t&&(I.set(s[0],s[1],s[2],s[3]),i.invert(),I.multiply(i),this.rotationChange.copy(I)),i.fromArray(s),t=o,s[0]=0,s[1]=0,s[2]=0,s[3]=1,s))}}onBeforeUpdate(A){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(A){return!this.action||(A*=this.action.getEffectiveWeight(),A<=0)?!1:(this.positionChange.multiplyScalar(A),this.rotationChange.slerp(Ig.identityQuaternion,1-A),!0)}};let js=Ig;r(js,"lastObjPosition",{}),r(js,"lastObjRotation",{}),r(js,"firstKeyframeRotation",{}),r(js,"spaceRotation",{}),r(js,"effectiveSpaceRotation",{}),r(js,"clipOffsetRotation",{}),r(js,"identityQuaternion",new kA);class cgA{constructor(A){r(this,"controller");r(this,"handler",[]);r(this,"root");r(this,"basePosition",new y);r(this,"baseQuaternion",new kA);r(this,"baseRotation",new jt);r(this,"summedPosition",new y);r(this,"summedRotation",new kA);this.controller=A}createClip(A,e,t){this.root=e,e&&"name"in e&&e.name;const i=this.findRootTrack(t,".position"),I=this.findRootTrack(t,".quaternion"),o=new js(this.controller.context,e,t,i,I);this.handler.push(o);const s=A.clipAction(t);return o.action=s,s}onStart(A){for(const e of this.handler)e.onStart(A)}onBeforeUpdate(A){this.basePosition.copy(this.root.position),this.baseQuaternion.copy(this.root.quaternion);for(const e of this.handler)e.onBeforeUpdate(A)}onAfterUpdate(A){if(!(A<=0)){this.root.position.copy(this.basePosition),this.root.quaternion.copy(this.baseQuaternion),this.summedPosition.set(0,0,0),this.summedRotation.set(0,0,0,1);for(const e of this.handler)e.onAfterUpdate(A)&&(this.summedPosition.add(e.positionChange),this.summedRotation.multiply(e.rotationChange));this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation)}}findRootTrack(A,e){const t=A.tracks;if(!t)return null;for(const i of t)if(i.name.endsWith(e))return i;return null}}class lgA extends Rn{onSerialize(A,e){}onDeserialize(A,e){if(e.type===wo&&(A==null?void 0:A.__type)==="AnimatorController")return new wo(A)}}new lgA(wo);var hgA=Object.defineProperty,dgA=Object.getOwnPropertyDescriptor,QS=(g,A,e,t)=>{for(var i=t>1?void 0:t?dgA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&hgA(A,e,i),i};const bo=IA("debuganimator");class Hg extends UA{constructor(){super(...arguments);r(this,"applyRootMotion",!1);r(this,"hasRootMotion",!1);r(this,"keepAnimatorControllerStateOnDisable",!1);r(this,"_parametersAreDirty",!1);r(this,"_isDirty",!1);r(this,"_speed",1);r(this,"_normalizedStartOffset",0);r(this,"_animatorController",null);r(this,"_initializeWithRuntimeAnimatorController")}set runtimeAnimatorController(e){var t;this._animatorController&&this._animatorController.model===e||(e?e instanceof wo?(e.animator&&e.animator!==this&&(console.warn("AnimatorController can not be bound to multiple animators",(t=e.model)==null?void 0:t.name),e.model||console.error("AnimatorController has no model"),e=new wo(e.model)),this._animatorController=e,this._animatorController.bind(this)):(bo&&console.log("Assign animator controller",e,this),this._animatorController=new wo(e),this.__didAwake&&this._animatorController.bind(this)):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}getCurrentStateInfo(){var e;return(e=this.runtimeAnimatorController)==null?void 0:e.getCurrentStateInfo()}get currentAction(){var e;return((e=this.runtimeAnimatorController)==null?void 0:e.currentAction)||null}get parametersAreDirty(){return this._parametersAreDirty}get isDirty(){return this._isDirty}Play(e,t=-1,i=Number.NEGATIVE_INFINITY,I=0){this.play(e,t,i,I)}play(e,t=-1,i=Number.NEGATIVE_INFINITY,I=0){var o;(o=this.runtimeAnimatorController)==null||o.play(e,t,i,I),this._isDirty=!0}Reset(){this.reset()}reset(){var e;(e=this._animatorController)==null||e.reset(),this._isDirty=!0}SetBool(e,t){this.setBool(e,t)}setBool(e,t){var i,I;bo&&console.log("setBool",e,t),((i=this.runtimeAnimatorController)==null?void 0:i.getBool(e))!==t&&(this._parametersAreDirty=!0),(I=this.runtimeAnimatorController)==null||I.setBool(e,t)}GetBool(e){return this.getBool(e)}getBool(e){var i;const t=((i=this.runtimeAnimatorController)==null?void 0:i.getBool(e))??!1;return bo&&console.log("getBool",e,t),t}toggleBool(e){this.setBool(e,!this.getBool(e))}SetFloat(e,t){this.setFloat(e,t)}setFloat(e,t){var i,I;((i=this.runtimeAnimatorController)==null?void 0:i.getFloat(e))!==t&&(this._parametersAreDirty=!0),bo&&console.log("setFloat",e,t),(I=this.runtimeAnimatorController)==null||I.setFloat(e,t)}GetFloat(e){return this.getFloat(e)}getFloat(e){var i;const t=((i=this.runtimeAnimatorController)==null?void 0:i.getFloat(e))??-1;return bo&&console.log("getFloat",e,t),t}SetInteger(e,t){this.setInteger(e,t)}setInteger(e,t){var i,I;((i=this.runtimeAnimatorController)==null?void 0:i.getInteger(e))!==t&&(this._parametersAreDirty=!0),bo&&console.log("setInteger",e,t),(I=this.runtimeAnimatorController)==null||I.setInteger(e,t)}GetInteger(e){return this.getInteger(e)}getInteger(e){var i;const t=((i=this.runtimeAnimatorController)==null?void 0:i.getInteger(e))??-1;return bo&&console.log("getInteger",e,t),t}SetTrigger(e){this.setTrigger(e)}setTrigger(e){var t;this._parametersAreDirty=!0,bo&&console.log("setTrigger",e),(t=this.runtimeAnimatorController)==null||t.setTrigger(e)}ResetTrigger(e){this.resetTrigger(e)}resetTrigger(e){var t;this._parametersAreDirty=!0,bo&&console.log("resetTrigger",e),(t=this.runtimeAnimatorController)==null||t.resetTrigger(e)}GetTrigger(e){this.getTrigger(e)}getTrigger(e){var i;const t=(i=this.runtimeAnimatorController)==null?void 0:i.getTrigger(e);return bo&&console.log("getTrigger",e,t),t}IsInTransition(){return this.isInTransition()}isInTransition(){var e;return((e=this.runtimeAnimatorController)==null?void 0:e.isInTransition())??!1}SetSpeed(e){return this.setSpeed(e)}setSpeed(e){var t;e!==this._speed&&(bo&&console.log("setSpeed",e),this._speed=e,((t=this._animatorController)==null?void 0:t.animator)==this&&this._animatorController.setSpeed(e))}set minMaxSpeed(e){var t;this._speed=te.lerp(e.x,e.y,Math.random()),((t=this._animatorController)==null?void 0:t.animator)==this&&this._animatorController.setSpeed(this._speed)}set minMaxOffsetNormalized(e){var t;this._normalizedStartOffset=te.lerp(e.x,e.y,Math.random()),((t=this.runtimeAnimatorController)==null?void 0:t.animator)==this&&(this.runtimeAnimatorController.normalizedStartOffset=this._normalizedStartOffset)}awake(){bo&&console.log("ANIMATOR",this.name,this),this.gameObject&&this.initializeRuntimeAnimatorController()}initializeRuntimeAnimatorController(e=!1){const t=e||this.runtimeAnimatorController!==this._initializeWithRuntimeAnimatorController;if(this.runtimeAnimatorController&&t){const i=this.runtimeAnimatorController.clone();this._initializeWithRuntimeAnimatorController=i,i?(console.assert(this.runtimeAnimatorController!==i),this.runtimeAnimatorController=i,console.assert(this.runtimeAnimatorController===i),this.runtimeAnimatorController.bind(this),this.runtimeAnimatorController.setSpeed(this._speed),this.runtimeAnimatorController.normalizedStartOffset=this._normalizedStartOffset):console.warn("Could not clone animator controller",this.runtimeAnimatorController)}}onDisable(){var e;this.keepAnimatorControllerStateOnDisable||(e=this._animatorController)==null||e.reset()}onBeforeRender(){this._isDirty=!1,this._parametersAreDirty=!1,!BgA(this.gameObject)&&this._animatorController&&this._animatorController.update(1)}}QS([D()],Hg.prototype,"applyRootMotion",2);QS([D()],Hg.prototype,"hasRootMotion",2);QS([D()],Hg.prototype,"keepAnimatorControllerStateOnDisable",2);QS([D()],Hg.prototype,"runtimeAnimatorController",1);const nB=IA("debugusdzanimation"),Lk=IA("debugusdzanimationserialization");class ES{constructor(A,e,t){r(this,"_start");r(this,"ext");r(this,"root");r(this,"clip");this.ext=A,this.root=e,this.clip=t}get start(){return this._start===void 0&&(this._start=this.ext.getStartTime01(this.root,this.clip)),this._start}get duration(){return this.clip.duration}}const EK=class{constructor(A,e,t){r(this,"clip");r(this,"pos");r(this,"rot");r(this,"scale");r(this,"root");r(this,"target");r(this,"duration",0);r(this,"useRootMotion",!1);this.root=A,this.target=e,this.clip=t,t?this.duration=t.duration:this.duration=EK.restPoseClipDuration;const i=nA.getComponent(A,Hg);i&&(this.useRootMotion=i.applyRootMotion)}get frameRate(){return 60}addTrack(A){if(!this.clip){console.error("This is a rest clip but you're trying to add tracks to it โ€“ this is likely a bug");return}A.name.endsWith("position")&&(this.pos=A),A.name.endsWith("quaternion")&&(this.rot=A),A.name.endsWith("scale")&&(this.scale=A)}getFrames(){var A,e,t,i,I,o;return this.clip?Math.max(((e=(A=this.pos)==null?void 0:A.times)==null?void 0:e.length)??0,((i=(t=this.rot)==null?void 0:t.times)==null?void 0:i.length)??0,((o=(I=this.scale)==null?void 0:I.times)==null?void 0:o.length)??0):2}getDuration(){return this.duration}getSortedTimesArray(A=!0,e=!0,t=!0){var n,C,a;if(!this.clip)return[0,this.duration];const i=(n=this.pos)==null?void 0:n.times,I=(C=this.rot)==null?void 0:C.times,o=(a=this.scale)==null?void 0:a.times,s=[];if(A&&i)for(const B of i)s.push(B);if(e&&I)for(const B of I)s.push(B);if(t&&o)for(const B of o)s.push(B);return s.includes(0)||s.push(0),s.sort((B,Q)=>B-Q),[...new Set(s)]}*getValues(A,e=!0,t=!0,i=!0){var Q,E,c;const I=new y,o=new kA,s=new y(1,1,1),n=this.target,C=e?(Q=this.pos)==null?void 0:Q.createInterpolant():void 0,a=t?(E=this.rot)==null?void 0:E.createInterpolant():void 0,B=i?(c=this.scale)==null?void 0:c.createInterpolant():void 0;C||I.set(n.position.x,n.position.y,n.position.z),a||o.set(n.quaternion.x,n.quaternion.y,n.quaternion.z,n.quaternion.w),B||s.set(n.scale.x,n.scale.y,n.scale.z);for(let d=0;d<A.length;d++){const h=A[d];if(C){const l=C.evaluate(h);I.set(l[0],l[1],l[2])}if(a){const l=a.evaluate(h);o.set(l[0],l[1],l[2],l[3])}if(B){const l=B.evaluate(h);s.set(l[0],l[1],l[2])}if(this.useRootMotion&&n===this.root){const l=new MA;l.compose(I,o,s),l.multiply(n.matrix),l.decompose(I,o,s)}yield{time:h,translation:I,rotation:o,scale:s,index:d}}}};let fg=EK;r(fg,"animationDurationPadding",1/60),r(fg,"restPoseClipDuration",1/60);class au{constructor(A){r(this,"dict",new Map);r(this,"rootTargetMap",new Map);r(this,"rootAndClipToRegisteredAnimationMap",new Map);r(this,"rootToRegisteredClipCount",new Map);r(this,"serializers",[]);r(this,"injectRestPoses",!1);r(this,"injectImplicitBehaviours",!1);this.injectRestPoses=A,this.injectImplicitBehaviours=A}get extensionName(){return"animation"}getStartTimeCode(){return!this.injectRestPoses||this.rootAndClipToRegisteredAnimationMap.size===0?0:(fg.restPoseClipDuration+fg.animationDurationPadding)*60}getEndTimeCode(){let A=0;for(const[e,t]of this.rootAndClipToRegisteredAnimationMap){const i=t.start+t.duration;i>A&&(A=i)}return A*60}getClipCount(A){let e=this.rootToRegisteredClipCount.get(A);return this.injectRestPoses&&(e=e?e-1:0),e??0}getStartTime01(A,e){const t=this.rootTargetMap.get(A);if(!t)return 0;const i=this.dict.get(t[0]);if(!i)return console.error("Trying to get start time for root that has no animation data",A,e,...this.dict),0;let I=0;for(let o=0;o<i.length&&i[o].clip!==e;o++)I+=i[o].getDuration()+fg.animationDurationPadding;return I}registerAnimation(A,e){if(!e||!A)return null;this.rootTargetMap.has(A)||this.rootTargetMap.set(A,[]);const t=A.uuid+e.uuid;if(this.rootAndClipToRegisteredAnimationMap.has(t))return this.rootAndClipToRegisteredAnimationMap.get(t);nB&&console.log("registerAnimation",A,e);const i=this.injectRestPoses?1:0,I=this.rootToRegisteredClipCount.get(A)??i,o=this.rootTargetMap.get(A),s=new Set(o);if(e.tracks)for(const C of e.tracks){const a=ze.parseTrackName(C.name),B=ze.findNode(A,a.nodeName);if(!B){console.warn("no object found for track",C.name,"using "+A.name+" instead");continue}this.dict.has(B)||this.dict.set(B,[]);const Q=this.dict.get(B);if(!Q){console.warn("no transform data found for target ",B,"at slot "+I+", this is likely a bug");continue}if(s.delete(B),this.injectRestPoses&&!Q[0]){const c=new fg(null,B,void 0);Q[0]=c}let E=Q[I];E||(E=new fg(A,B,e),Q[I]=E),E.addTrack(C),o!=null&&o.includes(B)||o==null||o.push(B)}for(const C of s){const a=this.dict.get(C);if(!a)continue;if(this.injectRestPoses&&!a[0]){const Q=new fg(null,C,void 0);a[0]=Q}let B=a[I];B||(nB&&console.log("Adding padding clip for ",C,e,"at slot",I),B=new fg(A,C,e),a[I]=B)}const n=new ES(this,A,e);return this.rootAndClipToRegisteredAnimationMap.set(t,n),this.rootToRegisteredClipCount.set(A,I+1),n}onAfterHierarchy(A){nB&&console.log("Animation clips per animation target node",this.dict)}onAfterBuildDocument(A){var e,t;for(const i of this.serializers){const I=(e=i.model)==null?void 0:e.parent,o=(I==null?void 0:I.isDynamic)===!0;Lk&&console.log(o,(t=i.model)==null?void 0:t.parent),o&&i.registerCallback(I)}}onExportObject(A,e,t){nA.foreachComponent(A,I=>{const o=I;typeof o.createAnimation=="function"&&o.createAnimation(this,e,t)},!1);const i=new ugA(A,this.dict);this.serializers.push(i),i.registerCallback(e)}}class ugA{constructor(A,e){r(this,"object");r(this,"dict");r(this,"model");r(this,"callback");this.object=A,this.dict=e}registerCallback(A){this.model&&this.callback&&this.model.removeEventListener("serialize",this.callback),this.callback||(this.callback=this.onSerialize.bind(this)),Lk&&console.log("REPARENT",A),this.model=A,this.model.addEventListener("serialize",this.callback)}skinnedMeshExport(A,e){var I;const t=this.model,i=this.dict;if(t&&t.skinnedMesh){let o=function(S){const F=[];for(const[w,R]of S){let H=`${w} : [`;const Y=[];for(const J of R)Y.push(`(${ug(J.x)}, ${ug(J.y)}, ${ug(J.z)})`);H=H.concat(Y.join(", ")),H=H.concat("],"),F.push(H)}return F},s=function(S){const F=[];for(const[w,R]of S){let H=`${w} : [`;const Y=[];for(const J of R)Y.push(`(${ug(J.w)}, ${ug(J.x)}, ${ug(J.y)}, ${ug(J.z)})`);H=H.concat(Y.join(", ")),H=H.concat("],"),F.push(H)}return F},n=function(S){let F,w=!0;const R=new Map;for(const[Y,J]of S){F===void 0&&(F=J.length),F!==J.length&&(w=!1);let O=0;for(const q of J)O++,q||(R.has(Y)||R.set(Y,[]),R.get(Y).push(O))}nB&&console.log("Bone count: ",S.size,"TransformData entries per bone: ",F,"Undefined bone entries: ",R),console.assert(w,"All bones should have the same number of TransformData entries",S),console.assert(R.size===0,"All TransformData entries should be set",R);const H=[];for(const[Y,J]of S){const O=new Array;let q=0;for(let b=0;b<J.length;b++)O.push(q),q+=J[b].getDuration()+fg.animationDurationPadding;for(let b=0;b<J.length;b++){const T=J[b],V=O[b];H.length<=b&&H.push({pos:[],rot:[],scale:[],timeOffset:V});const AA=H[b];AA.pos.push(...T.getSortedTimesArray(!0,!1,!1)),AA.rot.push(...T.getSortedTimesArray(!1,!0,!1)),AA.scale.push(...T.getSortedTimesArray(!1,!1,!0))}}for(const Y of H)Y.pos.sort((J,O)=>J-O),Y.rot.sort((J,O)=>J-O),Y.scale.sort((J,O)=>J-O),Y.pos=[...new Set(Y.pos)],Y.rot=[...new Set(Y.rot)],Y.scale=[...new Set(Y.scale)];return H},C=function(S,F,w){const R=new Map,H=new Map,Y=new Map,J=F.length;for(const O of w){const q=S.get(O);let b;q?console.assert(q.length===J,"We should have the same number of TransformData entries for each bone",q,F):b=new fg(null,O,void 0);for(let T=0;T<J;T++){const V=q?q[T]:b,AA=F[T];for(const{time:sA,translation:QA}of V.getValues(AA.pos,!0,!1,!1)){const iA=(sA+AA.timeOffset)*60;R.has(iA)||R.set(iA,new Array),R.get(iA).push(QA.clone())}for(const{time:sA,rotation:QA}of V.getValues(AA.rot,!1,!0,!1)){const iA=(sA+AA.timeOffset)*60;H.has(iA)||H.set(iA,new Array),H.get(iA).push(QA.clone())}for(const{time:sA,scale:QA}of V.getValues(AA.scale,!1,!1,!0)){const iA=(sA+AA.timeOffset)*60;Y.has(iA)||Y.set(iA,new Array),Y.get(iA).push(QA.clone())}}}return{position:R.size==0?void 0:R,quaternion:H.size==0?void 0:H,scale:Y.size==0?void 0:Y}},a=function(S){const F=[];for(const w of S)F.push(`(${ug(w.x)}, ${ug(w.y)}, ${ug(w.z)})`);return F.join(", ")},B=function(S){const F=[];for(const w of S)F.push(`(${ug(w.w)}, ${ug(w.x)}, ${ug(w.y)}, ${ug(w.z)})`);return F.join(", ")},Q=function(S){const F=new Map;if(nB){const w=new Array;for(const[R,H]of i)w.push(R.uuid+": "+H.length+" "+H.map(Y=>{var J;return(J=Y.clip)==null?void 0:J.uuid.substring(0,6)}).join(" "));console.log(`getPerBoneTransformData
5479
5479
  `+w.join(`
5480
5480
  `))}for(const w of S){const R=i.get(w);R&&F.set(w,R)}return F},E=function(S){const F=Q(S),w=n(F);return C(F,w,S)};const c=t.skinnedMesh.skeleton,d=new Array;for(const S in c.bones){const F=c.bones[S],w=c.boneInverses[S];d.push({bone:F,inverse:w})}for(const S of tO(c.bones))d.push({bone:S,inverse:S.matrixWorld.clone().invert()});const h=d[0].bone.parent;h||console.error("No bone parent found for skinned mesh during USDZ export",t.skinnedMesh),d.sort((S,F)=>ME(S.bone,h)>ME(F.bone,h)?1:-1);const l=[],p=[],u=[],f=[];for(const{bone:S}of d)l.push(S.matrix.clone()),p.push(S.position),u.push(S.quaternion),f.push(S.scale);const m=d.map(S=>'"'+ME(S.bone,h)+'"').join(", "),M=d.map(S=>rE(S.inverse.clone().invert())).join(", ");A.beginBlock('def Skeleton "Rig"'),A.appendLine(`uniform matrix4d[] bindTransforms = [${M}]`),A.appendLine(`uniform token[] joints = [${m}]`),A.appendLine('uniform token purpose = "guide"'),A.appendLine(`uniform matrix4d[] restTransforms = [${l.map(S=>rE(S)).join(", ")}]`),A.appendLine(`matrix4d xformOp:transform = ${rE(new MA)}`),A.appendLine('uniform token[] xformOpOrder = ["xformOp:transform"]');const k=E(d.map(S=>S.bone));if(nB){let S=1e7,F=0;for(const w of((I=k.position)==null?void 0:I.keys())??[])S=Math.min(S,w),F=Math.max(F,w);console.log("Time samples",S,F,k)}if(A.beginBlock('def SkelAnimation "_anim"'),A.appendLine(`uniform token[] joints = [${m}]`),A.appendLine(`quatf[] rotations = [${B(u)}]`),k&&k.quaternion){A.beginBlock("quatf[] rotations.timeSamples = {","");const S=s(k.quaternion);for(const F of S)A.appendLine(F);A.closeBlock()}if(A.appendLine(`half3[] scales = [${a(f)}]`),k&&k.scale){A.beginBlock("half3[] scales.timeSamples = {","");const S=o(k.scale);for(const F of S)A.appendLine(F);A.closeBlock()}if(A.appendLine(`float3[] translations = [${a(p)}]`),k&&k.position){A.beginBlock("float3[] translations.timeSamples = {","");const S=o(k.position);for(const F of S)A.appendLine(F);A.closeBlock()}A.closeBlock(),A.closeBlock()}}onSerialize(A,e){var C;if(!this.model)return;const t=this.dict.get(this.object);if(t)for(let a=0;a<t.length;a++)t[a]===void 0&&(t[a]=new fg(null,this.object,void 0));this.skinnedMeshExport(A,e);const i=this.object,I=this.dict.get(i);if(!I||i.isSkinnedMesh)return;Lk&&console.log("SERIALIZE",this.model.name,this.object.type,I);const o=new MA;A.appendLine("matrix4d xformOp:transform.timeSamples = {"),A.indent++;const s=new Array;let n=0;for(let a=0;a<I.length;a++){if(s.push(n),I[a]===void 0){console.error("Got an undefined transform data, this is likely a bug.",i,I);continue}n+=I[a].getDuration()+fg.animationDurationPadding}for(let a=0;a<I.length;a++){const B=I[a];if(!B)continue;const Q=s[a];{const E=B.getSortedTimesArray();if(!E||E.length===0){console.error("got an animated object but no time values?",i,B);continue}if(nB){const c=((C=B.clip)==null?void 0:C.name)??"rest",d=B.getDuration();console.log("Write .timeSamples:",c,Q,d,I),A.appendLine("# "+c+": start="+(Q*B.frameRate).toFixed(3)+", length="+(d*B.frameRate).toFixed(3)+", frames="+B.getFrames())}for(const{time:c,translation:d,rotation:h,scale:l}of B.getValues(E)){o.compose(d,h,l);const p=`${(Q+c)*B.frameRate}: ${rE(o)},`;A.appendLine(p)}}}A.indent--,A.appendLine("}")}}var pgA=Object.defineProperty,fgA=Object.getOwnPropertyDescriptor,pO=(g,A,e,t)=>{for(var i=t>1?void 0:t?fgA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&pgA(A,e,i),i};const wv=IA("debugpost");class xe{constructor(A){r(this,"_active",!0);r(this,"_value");r(this,"_valueRaw");r(this,"_defaultValue");r(this,"valueProcessor");r(this,"onValueChanged");this._value=A,this._defaultValue=A,this._valueRaw=A}get overrideState(){return this._active}set overrideState(A){if(this._active===A)return;this._active=A;const e=A?this._valueRaw:this._defaultValue;this.processValue(e,!0)}get value(){return this._valueRaw}set value(A){this.processValue(A,!1)}set defaultValue(A){this._defaultValue=A}__init(){this.processValue(this._valueRaw,!0)}processValue(A,e){if(A==null||!e&&this.testIfValueChanged(A)===!1)return;const t=this._value;if(wv){let i=!0;if(typeof t=="number"&&typeof A=="number"){const I=t==null?void 0:t.toFixed(4),o=A==null?void 0:A.toFixed(4);I!=o?i=!0:i=!1}i&&console.log("VolumeParameter: value changed from",t,"to",A)}!this._active&&this._defaultValue!==void 0?(this._value=this._defaultValue,A=this._defaultValue,this._valueRaw=A):(this._valueRaw=A,this._active&&this.valueProcessor&&(A=this.valueProcessor(A)),this._value=A),this.onValueChanged?this.onValueChanged(A,t,this):wv&&console.log("VolumeParameter: onValueChanged not set")}testIfValueChanged(A){return this._valueRaw!==A}}pO([D()],xe.prototype,"overrideState",1);pO([D()],xe.prototype,"value",1);var DgA=Object.defineProperty,ygA=Object.getOwnPropertyDescriptor,wgA=(g,A,e,t)=>{for(var i=t>1?void 0:t?ygA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&DgA(A,e,i),i};const SgA=IA("debugpost");class QI extends UA{constructor(e=void 0){super();r(this,"active",!0);r(this,"_result");r(this,"_didCreateVolumeParameters",!1);if(e){this.ensureVolumeParameters();for(const t of Object.keys(e)){const i=e[t],I=this[t];I instanceof xe&&(I.value=i)}}}onEnable(){this.__internalDidAwakeAndStart&&(this.active=!0)}onDisable(){this.active=!1}init(){}apply(){var e;return this.ensureVolumeParameters(),this._result||(this._result=(e=this.onCreateEffect)==null?void 0:e.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){SgA&&console.warn("DISPOSE",this),this._result&&(Array.isArray(this._result)?this._result.forEach(e=>e.dispose()):this._result.dispose()),this._result=void 0}initParameters(){const e=Object.keys(this);for(const t of e){const i=this[t];i instanceof xe&&i.__init()}}onAfterDeserialize(e,t){if(typeof e=="object"){const i=this.$serializedTypes;if(i){for(const I of Object.keys(i))if(i[I]===xe){const s=e[I];if(s!==void 0){const n=this[I];n.value=s}}}}}onEditorModification(e){const t=e.propertyName;if(this[t]instanceof xe){const i=e.value;return this[t].value=i,!0}}ensureVolumeParameters(){if(this._didCreateVolumeParameters)return;this._didCreateVolumeParameters=!0;const e=this.$serializedTypes;if(e)for(const t of Object.keys(e))e[t]===xe&&(this[t]||(this[t]=new xe))}}wgA([D()],QI.prototype,"active",2);var mgA=Object.defineProperty,MgA=Object.getOwnPropertyDescriptor,GgA=(g,A,e,t)=>{for(var i=t>1?void 0:t?MgA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&mgA(A,e,i),i};const kgA=IA("debugpost"),xk={};function ss(g,A){xk[g]=A}function RgA(g){return g.__type in xk?xk[g.__type]:(kgA&&g.__type&&console.warn("Unknown postprocessing type",g.__type,g),QI)}class ru{constructor(){r(this,"components",[])}init(){var A;(A=this.components)==null||A.forEach(e=>e.init())}}GgA([cc([g=>RgA(g),QI])],ru.prototype,"components",2);var UgA=Object.defineProperty,NgA=Object.getOwnPropertyDescriptor,FgA=(g,A,e,t)=>{for(var i=t>1?void 0:t?NgA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&UgA(A,e,i),i};class Bu extends QI{constructor(){super(...arguments);r(this,"preset")}get typeName(){return"Antialiasing"}onCreateEffect(){const e=new K2({preset:VQ.HIGH,edgeDetectionMode:OU.DEPTH});return this.preset.onValueChanged=t=>{e.applyPreset(t)},e}}FgA([D(xe)],Bu.prototype,"preset",2);ss("Antialiasing",Bu);const KgA=IA("debugusdz");class Ar{constructor(){r(this,"files",new Array)}static getName(A){var I;const e=A.split(".").pop();let i=(I=A.split(".").slice(0,-1).join(".").split("/").pop())==null?void 0:I.replace(".","_");return i||(i="Audio_"+Math.random().toString(36).substring(2,15)),RC(i)+"."+e}get extensionName(){return"Audio"}onExportObject(A,e,t){const i=nA.getComponents(A,hi);if(i.length)for(const I of i){if(!I.clip||typeof I.clip!="string"||!I.playOnAwake)continue;const o=I.clip.split("/").pop()||"Audio",s=Ar.getName(I.clip),n=RC(s);this.files.some(C=>C.path===I.clip)||this.files.push({path:I.clip,name:s}),t.quickLookCompatible||e.addEventListener("serialize",(C,a)=>{C.appendLine(),C.beginBlock(`def SpatialAudio "${n}"`,"(",!1),C.appendLine(`displayName = "${o}"`),C.closeBlock(")"),C.beginBlock(),C.appendLine(`uniform asset filePath = @audio/${s}@`),C.appendLine(`uniform token auralMode = "${I.spatialBlend>0?"spatial":"nonSpatial"}"`),C.appendLine(`uniform token playbackMode = "${I.loop?"loopFromStage":"onceFromStart"}"`),C.appendLine(`uniform float gain = ${I.volume}`),C.closeBlock()})}}async onAfterSerialize(A){for(const e of this.files){const t="audio/"+e.name;if(A.files[t]){KgA&&console.warn("Audio file with name "+t+" already exists in the context. Skipping.");continue}const o=await(await(await fetch(e.path)).blob()).arrayBuffer(),s=new Uint8Array(o);A.files[t]=s}}}const CB=IA("debugautosync"),eM=Symbol("syncerId");class JgA{constructor(){r(this,"_syncers",{})}getOrCreateSyncer(A){if(!A.guid)return null;if(this._syncers[A.guid])return this._syncers[A.guid];const e=new qgA(A);return e[eM]=A.guid,this._syncers[e[eM]]=e,e}removeSyncer(A){delete this._syncers[A[eM]]}}const GN=new JgA;class qgA{constructor(A){r(this,"comp");r(this,"hasChanges",!1);r(this,"changedProperties",{});r(this,"data",{});r(this,"_boundEvent");r(this,"_handleReceivingMethod");r(this,"_isReceiving",!1);r(this,"_isInit",!1);this.comp=A}get networkingKey(){return this.comp.guid}init(A){if(this._isInit)return;this._isInit=!0,this.comp=A,this._boundEvent=this.onHandleSending.bind(this),this.comp.context.post_render_callbacks.push(this._boundEvent),this._handleReceivingMethod=this.onHandleReceiving.bind(this),this.comp.context.connection.beginListen(this.networkingKey,this._handleReceivingMethod);const e=this.comp.context.connection.tryGetState(this.comp.guid);e&&this.onHandleReceiving(e)}destroy(){this._isInit&&(this._boundEvent&&this.comp.context.post_render_callbacks.splice(this.comp.context.post_render_callbacks.indexOf(this._boundEvent),1),this._handleReceivingMethod&&this.comp.context.connection.stopListen(this.networkingKey,this._handleReceivingMethod),this.comp=null,this._isInit=!1)}notifyChanged(A,e){this._isReceiving||(CB&&console.log("Property changed: "+A,e),this.hasChanges=!0,this.changedProperties[A]=e)}onHandleSending(){if(!this.hasChanges)return;this.hasChanges=!1;const A=this.comp.context.connection;if(!A||!A.isConnected){for(const e in this.changedProperties)delete this.changedProperties[e];return}for(const e in this.data)delete this.data[e];this.data.guid=this.comp.guid;for(const e in this.changedProperties){const t=this.changedProperties[e];delete this.changedProperties[e],this.data[e]=t}A.send(this.networkingKey,this.data)}onHandleReceiving(A){if(CB&&console.log("RECEIVE",this.comp.name,this.comp.guid,A),!this._isInit||!this.comp)return;const e=A.guid;if(!(e&&e!==this.comp.guid)){CB&&console.log("RECEIVED",this.comp.name,this.comp.guid,A);try{this._isReceiving=!0;for(const t in A){if(t==="guid")continue;const i=A[t];this.comp[t]=i,CB&&console.log("SET",t,i)}}catch(t){console.error(t)}finally{this._isReceiving=!1}}}}function bgA(g,A){let e=A!==g;return!e&&g&&A&&(Array.isArray(g)&&Array.isArray(A)||typeof g=="object"&&typeof A=="object")&&(e=!0),e}const ch=Symbol("AutoSyncHandler");function vgA(g){if(g[ch])return g[ch];const A=GN.getOrCreateSyncer(g);return A==null||A.init(g),g[ch]=A,A}function LgA(g){const A=g[ch];A&&(GN.removeSyncer(A),A.destroy(),delete g[ch])}const kN=function(g){return function(A,e){var a;let t="";typeof e=="string"?t=e:t=e.name;let i=null,I;typeof g=="string"?I=A[g]:typeof g=="function"&&(I=g);const o=A,s=o.__internalAwake;if(typeof s!="function"){(CB||pe())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+((a=A==null?void 0:A.constructor)==null?void 0:a.name)+'" is not supported',A);return}CB&&console.log(t);const n=Symbol(t);o.__internalAwake=function(){if(this[n]!==void 0)return;this[n]=this[t],i=GN.getOrCreateSyncer(this);const B=Object.getOwnPropertyDescriptor(this,t);if((B==null?void 0:B.set)===void 0){let Q=!1;Object.defineProperty(this,t,{set:function(E){var d;const c=this[n];if(this[n]=E,Q){pe()&&console.warn("Recursive call detected",t);return}Q=!0;try{const h=bgA(E,c);CB&&console.log("SyncField assignment",t,"changed?",h,E),h&&(I==null?void 0:I.call(this,E,c))!==!1&&((d=vgA(this))==null||d.notifyChanged(t,E))}finally{Q=!1}},get:function(){return this[n]},configurable:!0,enumerable:!0})}i==null||i.init(this),s.call(this)};const C=o.__internalDestroy;o.__internalDestroy=function(){LgA(this),C.call(this)}}};var xgA=Object.defineProperty,YgA=Object.getOwnPropertyDescriptor,cS=(g,A,e,t)=>{for(var i=t>1?void 0:t?YgA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&xgA(A,e,i),i};const ro=IA("debugplayersync");class uc extends UA{constructor(){super(...arguments);r(this,"autoSync",!0);r(this,"asset");r(this,"onPlayerSpawned");r(this,"_localInstance");r(this,"onJoinedRoom",()=>{ro&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()})}awake(){this.watchTabVisible(),this.onPlayerSpawned||(this.onPlayerSpawned=new wg)}onEnable(){this.context.connection.beginListen(gt.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(gt.JoinedRoom,this.onJoinedRoom),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(gt.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(gt.JoinedRoom,this.onJoinedRoom)}async getInstance(){var t,i,I,o,s,n;if(this._localInstance)return this._localInstance;if(ro&&console.log("PlayerSync.createInstance",(t=this.asset)==null?void 0:t.uri),!((i=this.asset)!=null&&i.asset)&&!((I=this.asset)!=null&&I.uri))return console.error('PlayerSync: can not create an instance because "asset" is not set!'),null;this._localInstance=(o=this.asset)==null?void 0:o.instantiateSynced({parent:this.gameObject},!0);const e=await this._localInstance;if(e){const C=nA.getComponent(e,Vo);C?(C.owner=this.context.connection.connectionId,(s=this.onPlayerSpawned)==null||s.invoke(e)):(this._localInstance=void 0,console.error("<strong>Failed finding PlayerState on "+((n=this.asset)==null?void 0:n.uri)+"</strong>: please make sure the asset has a PlayerState component!"),nA.destroySynced(e))}else this._localInstance=void 0,console.warn("PlayerSync: failed instantiating asset!");return this._localInstance}destroyInstance(){var e;(e=this._localInstance)==null||e.then(t=>(ro&&console.log("PlayerSync.destroyInstance",t),nA.destroySynced(t))),this._localInstance=void 0}watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=Vo.all.length-1;t>=0;t--){const i=Vo.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}}cS([D()],uc.prototype,"autoSync",2);cS([D(It)],uc.prototype,"asset",2);cS([D(wg)],uc.prototype,"onPlayerSpawned",2);var fO=(g=>(g.OwnerChanged="ownerChanged",g))(fO||{}),Ml;const Fg=(Ml=class extends UA{constructor(){super(...arguments);r(this,"onOwnerChangeEvent",new wg);r(this,"onFirstOwnerChangeEvent",new wg);r(this,"hasOwner",!1);r(this,"owner");r(this,"dontDestroy",!1);r(this,"onUserLeftRoom",A=>{if(A.userId===this.owner){ro&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}})}static get all(){return Fg._all}static get local(){return Fg._local}static getFor(A){if(A instanceof pA)return nA.getComponentInParent(A,Fg);if(A instanceof UA)return nA.getComponentInParent(A.gameObject,Fg)}static isLocalPlayer(A){const e=Fg.getFor(A);return(e==null?void 0:e.isLocalPlayer)??!1}static addEventListener(A,e){return this._callbacks[A]||(this._callbacks[A]=[]),this._callbacks[A].push(e),e}static removeEventListener(A,e){if(!this._callbacks[A])return;const t=this._callbacks[A].indexOf(e);t>=0&&this._callbacks[A].splice(t,1)}static dispatchEvent(A,e){if(this._callbacks[A])for(const t of this._callbacks[A])t(e)}get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(A,e){var o,s;ro&&console.log("PlayerSync.onOwnerChange",this,"newOwner",A,"oldOwner",e);const t=Fg._local.indexOf(this);t>=0&&Fg._local.splice(t,1);const i={playerState:this,oldValue:e,newValue:A};if(this.hasOwner||(this.hasOwner=!0,(o=this.onFirstOwnerChangeEvent)==null||o.invoke(i)),(s=this.onOwnerChangeEvent)==null||s.invoke(i),this.owner===this.context.connection.connectionId){Fg._local.push(this);const n=new CustomEvent("local-owner-changed",{detail:i});this.dispatchEvent(n)}const I=new CustomEvent("owner-changed",{detail:i});this.dispatchEvent(I),Fg.dispatchEvent("ownerChanged",I)}awake(){Fg.all.push(this),ro&&console.log("Registered new PlayerState",this.guid,Fg.all.length-1,Fg.all),this.context.connection.beginListen(gt.UserLeftRoom,this.onUserLeftRoom)}async start(){ro&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await Ns(300),this.context.connection.userIsInRoom(this.owner)==!1&&(ro&&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||(ro&&console.warn("PlayerState.start โ†’ owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?ro&&console.warn("PlayerState.start โ†’ owner is still undefined but dontDestroy is set to true",this.name):(ro&&console.warn(`PlayerState.start โ†’ owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):ro&&console.log("PlayerState.start โ†’ owner is assigned",this.owner)},2e3))}doDestroy(){ro&&console.log("PlayerSync.doDestroy โ†’ syncDestroy",this.name),AS(this.gameObject,this.context.connection)}onDestroy(){if(this.context.connection.stopListen(gt.UserLeftRoom,this.onUserLeftRoom),Fg.all.splice(Fg.all.indexOf(this),1),this.isLocalPlayer){const A=Fg._local.indexOf(this);A>=0&&Fg._local.splice(A,1)}}},r(Ml,"_all",[]),r(Ml,"_local",[]),r(Ml,"_callbacks",{}),Ml);let Vo=Fg;cS([kN(Vo.prototype.onOwnerChange)],Vo.prototype,"owner",2);const TgA=IA("debugavatar"),us=class extends UA{constructor(){super(...arguments);r(this,"connectionId");r(this,"avatar")}static getAvatar(e){return e>=0&&e<us.instances.length?us.instances[e]:null}static onAvatarMarkerCreated(e){return us._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return us._onAvatarMarkerDestroyed.push(e),e}awake(){us.instances.push(this),TgA&&console.log(this);for(const e of us._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){us.instances.splice(us.instances.indexOf(this),1);for(const e of us._onAvatarMarkerDestroyed)e({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}};let og=us;r(og,"instances",[]),r(og,"_onNewAvatarMarkerAdded",[]),r(og,"_onAvatarMarkerDestroyed",[]);var _gA=Object.defineProperty,HgA=Object.getOwnPropertyDescriptor,OgA=(g,A,e,t)=>{for(var i=t>1?void 0:t?HgA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&_gA(A,e,i),i};const $Q=IA("debugxrflags"),DO=IA("disablexrflags");DO&&console.warn("XRFlags are disabled");var In=(g=>(g[g.Never=0]="Never",g[g.Browser=1]="Browser",g[g.AR=2]="AR",g[g.VR=4]="VR",g[g.FirstPerson=8]="FirstPerson",g[g.ThirdPerson=16]="ThirdPerson",g[g.All=4294967295]="All",g))(In||{});const cK=class{constructor(){r(this,"Mask",17)}Has(A){return(this.Mask&A)!==0}Set(A){$Q&&console.warn("Set XR flag state to",A),this.Mask=A,co.Apply()}Enable(A){this.Mask|=A,co.Apply()}Disable(A){this.Mask&=~A,co.Apply()}Toggle(A){this.Mask^=A,co.Apply()}EnableAll(){this.Mask=-1,co.Apply()}DisableAll(){this.Mask=0,co.Apply()}};let Lg=cK;r(Lg,"Global",new cK);var Gl;const AC=(Gl=class extends UA{constructor(){super(...arguments);r(this,"visibleIn")}static Apply(){for(const A of this.registry)A.UpdateVisible(Lg.Global)}awake(){AC.registry.push(this)}onEnable(){AC.firstApply?this.UpdateVisible(Lg.Global):(AC.firstApply=!0,AC.Apply())}onDestroy(){const A=AC.registry.indexOf(this);A>=0&&AC.registry.splice(A,1)}get isOn(){return this.gameObject.visible}UpdateVisible(A=null){if(DO)return;let e;const t=A;if(t&&typeof t=="number"&&(console.assert(typeof t=="number","XRFlag.UpdateVisible: state must be a number",t),$Q&&console.log(t),AC.buffer.Mask=t,A=AC.buffer),A instanceof Lg?($Q&&console.warn(this.name,"use passed in mask",A.Mask,this.visibleIn),e=A.Has(this.visibleIn)):($Q&&console.log(this.name,"use global mask"),Lg.Global.Has(this.visibleIn)),e!==void 0)if(e)$Q&&console.log(this.name,"is visible",this.gameObject.uuid),nA.setActive(this.gameObject,!0);else{if($Q&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},r(Gl,"registry",[]),r(Gl,"firstApply"),r(Gl,"buffer",new Lg),Gl);let co=AC;OgA([D()],co.prototype,"visibleIn",2);var PgA=Object.defineProperty,WgA=Object.getOwnPropertyDescriptor,RN=(g,A,e,t)=>{for(var i=t>1?void 0:t?WgA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&PgA(A,e,i),i};const ll=IA("debugwebxr"),Sv=new kA().setFromAxisAngle(new y(0,1,0),Math.PI);class OB extends UA{constructor(){super(...arguments);r(this,"head");r(this,"leftHand");r(this,"rightHand");r(this,"_syncTransforms")}async onEnterXR(e){if(!this.activeAndEnabled)return;ll&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const t=Vo.getFor(this);if(t!=null&&t.owner){const i=this.gameObject.addNewComponent(og);i.avatar=this.gameObject,i.connectionId=t.owner}else this.context.connection.isConnected?console.error("No player state found for avatar",this):t&&!this.context.connection.isConnected&&(t.dontDestroy=!0)}onLeaveXR(e){const t=this.gameObject.getComponent(og);t&&t.destroy()}onUpdateXR(e){var n,C;if(!this.activeAndEnabled)return;const t=Vo.isLocalPlayer(this);if(!t)return;const i=e.xr;if(i.rig&&i.rig.gameObject!==this.gameObject.parent&&(this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),this.gameObject.scale.set(1,1,1),i.rig.gameObject.add(this.gameObject)),this._syncTransforms&&t)for(const a of this._syncTransforms)a.fastMode=!0,a.isOwned()||a.requestOwnership();if(this.head&&this.context.mainCamera){const a=this.head.asset;if(a.position.copy(this.context.mainCamera.position),a.quaternion.copy(this.context.mainCamera.quaternion),a.quaternion.x*=-1,this.context.time.frameCount%10===0){const B=nA.getComponentsInChildren(this.head.asset,co);for(const Q of B)Q.enabled=!1,Q.gameObject.visible=!1}}const I=e.xr.leftController,o=(n=this.leftHand)==null?void 0:n.asset;I&&o&&(o.position.copy(I.gripPosition),o.quaternion.copy(I.gripQuaternion),o.quaternion.multiply(Sv),o.visible=I.isTracking);const s=e.xr.rightController;if(s&&((C=this.rightHand)!=null&&C.asset)){const a=this.rightHand.asset;a.position.copy(s.gripPosition),a.quaternion.copy(s.gripQuaternion),a.quaternion.multiply(Sv),a.visible=s.isTracking}}onBeforeRender(){this.context.time.frame%10===0&&this.updateRemoteAvatarVisibility()}updateRemoteAvatarVisibility(){var e,t,i;if(this.context.connection.isConnected){const I=Vo.getFor(this);if(I&&I.isLocalPlayer==!1){const o=he.getXRSync(this.context);if(o&&o.hasState(I.owner)){this.tryFindAvatarObjectsIfMissing();const s=(e=this.leftHand)==null?void 0:e.asset;s&&(s.visible=(o==null?void 0:o.isTracking(I.owner,"left"))??!1);const n=(t=this.rightHand)==null?void 0:t.asset;n&&(n.visible=(o==null?void 0:o.isTracking(I.owner,"right"))??!1)}if((i=this.head)!=null&&i.asset){const s=nA.getComponentsInChildren(this.head.asset,co);for(const n of s)n.enabled=!1,n.gameObject.visible=!0}}}}tryFindAvatarObjectsIfMissing(){if(!this.head||!this.leftHand||!this.rightHand){const e={head:this.head,leftHand:this.leftHand,rightHand:this.rightHand};j_.tryFindAvatarObjects(this.gameObject,this.sourceId||"",e),e.head&&(this.head=e.head),e.leftHand&&(this.leftHand=e.leftHand),e.rightHand&&(this.rightHand=e.rightHand)}}async prepareAvatar(){if(this.tryFindAvatarObjectsIfMissing(),this.head)this.head instanceof pA&&(this.head=new It("",this.sourceId,this.head));else{const e=new pA;e.name="Head";const t=Zd.createPrimitive(UB.Cube);e.add(t),this.gameObject.add(e),this.head=new It("",this.sourceId,e),ll&&console.log("Create head",e)}if(this.rightHand)this.rightHand instanceof pA&&(this.rightHand=new It("",this.sourceId,this.rightHand));else{const e=new pA;e.name="Right Hand",this.gameObject.add(e),this.rightHand=new It("",this.sourceId,e),ll&&console.log("Create right hand",e)}if(this.leftHand)this.leftHand instanceof pA&&(this.leftHand=new It("",this.sourceId,this.leftHand));else{const e=new pA;e.name="Left Hand",this.gameObject.add(e),this.leftHand=new It("",this.sourceId,e),ll&&console.log("Create left hand",e)}await this.loadAvatarObjects(this.head,this.leftHand,this.rightHand),Vo.isLocalPlayer(this.gameObject)&&(this._syncTransforms=nA.getComponentsInChildren(this.gameObject,$a))}async loadAvatarObjects(e,t,i){const I=e.loadAssetAsync(),o=t.loadAssetAsync(),s=i.loadAssetAsync(),n=new Array;I&&n.push(I),o&&n.push(o),s&&n.push(s);const C=await Ld(n);ll&&console.log("Avatar loaded results:",C)}}RN([D(It)],OB.prototype,"head",2);RN([D(It)],OB.prototype,"leftHand",2);RN([D(It)],OB.prototype,"rightHand",2);class fn{static Add(A,e,t=null){if(e){for(const i of this.Pois)if(i.obj===e)return;this.Pois.push({obj:e,avatar:t}),this.LastChangeTime=A.time.time}}static Remove(A,e){var t;if(e){for(const i of this.Pois)if(i.obj===e){this.Pois.splice(this.Pois.indexOf(i),1),this.LastChangeTime=(A==null?void 0:A.time.time)??((t=Le.Current)==null?void 0:t.time.time);return}}}}r(fn,"Pois",[]),r(fn,"LastChangeTime",0);class jgA{constructor(){r(this,"guid");r(this,"position",new y)}}class sd extends UA{constructor(){super(...arguments);r(this,"target",null);r(this,"avatar",null);r(this,"_model",null);r(this,"_targetModel",new jgA);r(this,"_currentTargetObject",null);r(this,"_lastUpdateTime",0);r(this,"_lookDuration",0);r(this,"_lastPoiChangedTime",0)}set controlledTarget(e){this.target=e;const t=X.get("MoveRandom");if(t&&this.target){const i=nA.getComponent(this.target,t);i&&i.destroy()}}awake(){if(this.avatar=nA.getComponentInParent(this.gameObject,og),this.avatar){const e=nA.getComponentInParent(this.gameObject,og);this._model=new aN(this.context.connection,this.guid),e!=null&&e.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",e=>{var t;this.target&&e&&e.guid===((t=this.avatar)==null?void 0:t.guid)&&aI(this.target,e.position)})}update(){var t;if((!this.context.connection.isConnected||(t=this._model)!=null&&t.hasOwnership)&&(fn.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=fn.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){const i=ve(this._currentTargetObject);aI(this.target,i),this.context.connection.isConnected&&this.avatar&&(this.context.connection.send("avatar-look-target-changed",this._targetModel),this._targetModel.guid=this.avatar.guid,this._targetModel.position.copy(i))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;const t=fn.Pois;if(t.length>0){const i=t[Math.floor(Math.random()*t.length)];if(i&&i.obj){if(i.avatar&&i.avatar===this.avatar)return;this._currentTargetObject=i.obj}}}}}const EE=IA("debugnetworkingstreams");var En=(g=>(g.Connected="peer-user-connected",g.StreamReceived="receive-stream",g.StreamEnded="call-ended",g.Disconnected="peer-user-disconnected",g.UserJoined="user-joined",g))(En||{});class yO{constructor(A,e){r(this,"type","call-ended");r(this,"userId");r(this,"direction");this.userId=A,this.direction=e}}class wO{constructor(A,e){r(this,"type","receive-stream");r(this,"stream");r(this,"target");this.stream=A,this.target=e}}class zgA{constructor(A,e){r(this,"guid");r(this,"peerId");r(this,"dontSave",!0);this.guid=A.id,this.peerId=e}}var SO=(g=>(g.Incoming="incoming",g.Outgoing="outgoing",g))(SO||{});class VgA extends Sg{constructor(e,t,i){super();r(this,"userId");r(this,"direction");r(this,"call");r(this,"_stream",null);r(this,"_isDisposed",!1);this.userId=e,this.call=t,this.direction=i,this._stream=null,t.on("stream",I=>{if(EE&&console.log("Receive video",I.getAudioTracks(),I.getVideoTracks()),this._stream=I,i==="incoming"){const o=new wO(I,this);this.dispatchEvent(o)}}),t.on("close",()=>{this.dispatchEvent(new yO(e,i))})}get stream(){return this._stream}close(){this._isDisposed||(this._isDisposed=!0,this.call.close(),pC(this._stream))}get isOpen(){var e;return((e=this.call.peerConnection)==null?void 0:e.connectionState)==="connected"}get isOpening(){var e;return((e=this.call.peerConnection)==null?void 0:e.connectionState)==="connecting"}get isClosed(){return!this.isOpen}}const uE=class extends Sg{constructor(e,t){super();r(this,"id");r(this,"context");r(this,"_peer");r(this,"_incomingCalls",[]);r(this,"_outgoingCalls",[]);r(this,"_enabled",!1);r(this,"_enabledPeer",!1);r(this,"onConnectRoomFn",this.onConnectRoom.bind(this));r(this,"onPeerConnectFn",this.onPeerConnect.bind(this));r(this,"onPeerReceiveCallFn",this.onPeerReceivingCall.bind(this));this.context=e,this.id=t,this.setupPeer(),navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia}static getOrCreate(e,t){if(uE.instances.has(t))return uE.instances.get(t);const i=new uE(e,t);return uE.instances.set(t,i),i}getMyPeerId(){if(this.context.connection.connectionId)return this.getPeerIdFromUserId(this.context.connection.connectionId)}getPeerIdFromUserId(e){return this.id+"-"+e}getUserIdFromPeerId(e){return e.substring(this.id.length+1)}makeCall(e,t){var o;const i={metadata:{userId:this.context.connection.connectionId}},I=(o=this._peer)==null?void 0:o.call(e,t,i);if(I)return this.registerCall(I,"outgoing")}get peer(){return this._peer}enable(){this._enabled||(this._enabled=!0,this.context.connection.beginListen(gt.JoinedRoom,this.onConnectRoomFn),this.subscribePeerEvents())}disable(){this._enabled&&(this._enabled=!1,this.context.connection.stopListen(gt.JoinedRoom,this.onConnectRoomFn),this.unsubscribePeerEvents())}onConnectRoom(){this.setupPeer()}setupPeer(){if(this.context.connection.connectionId&&!this._enabledPeer){if(this._enabledPeer=!0,!this._peer){const e=this.getMyPeerId();e?this._peer=Y_(e):console.error("Failed to setup peerjs because we dont have a connection id",this.context.connection.connectionId)}this._enabled&&this.subscribePeerEvents()}}subscribePeerEvents(){this._peer&&(this._peer.on("open",this.onPeerConnectFn),this._peer.on("call",this.onPeerReceiveCallFn))}unsubscribePeerEvents(){this._peer&&(this._peer.off("open",this.onPeerConnectFn),this._peer.off("call",this.onPeerReceiveCallFn))}onPeerConnect(e){EE&&console.log("Peer connected as",e),this.context.connection.send("peer-user-connected",new zgA(this,e))}onPeerReceivingCall(e){e.answer(),this.registerCall(e,"incoming")}registerCall(e,t){const i=e.metadata;(!i||!i.userId)&&console.error("Missing call metadata",e);const I=i.userId;t==="incoming"&&EE?console.log("Receive call from",e.metadata):EE&&console.log("Make call to",e.metadata);const o=t==="incoming"?this._incomingCalls:this._outgoingCalls,s=new VgA(I,e,t);return o.push(s),e.on("error",n=>{console.error("Call error",n)}),e.on("close",()=>{EE&&console.log("Call ended",e.metadata),e.close();const n=o.indexOf(s);n!==-1&&o.splice(n,1)}),s.addEventListener("call-ended",n=>{this.dispatchEvent(n)}),t==="incoming"&&(s.addEventListener("receive-stream",n=>{this.dispatchEvent(n)}),e.on("stream",()=>{let n=0;const C=setInterval(()=>{const a=n===0;!s.isOpen&&a&&(n+=1,clearInterval(C),s.close())},2e3)})),s}};let GE=uE;r(GE,"instances",new Map);class Qu extends Sg{constructor(e,t){super();r(this,"context");r(this,"peer");r(this,"_sendingStreams",new Map);r(this,"debug",!1);r(this,"onJoinedRoom",e=>{this.debug&&console.log(`${e.userId} joined room and I'm currently sending ${this._sendingStreams.size} streams`),this._sendingStreams.size>0&&this.updateSendingCalls()});r(this,"onReceiveStream",e=>{this.debug&&console.log("RECEIVE STREAM",e),this.dispatchEvent({type:"receive-stream",target:this,stream:e.stream,userId:e.userId})});r(this,"onCallEnded",e=>{this.dispatchEvent(e)});r(this,"onUserConnected",e=>{if(this.peer.id===e.guid){this.debug&&console.log("USER CONNECTED",e.guid,e);const t=this._sendingStreams.keys().next().value;this.peer.makeCall(e.peerId,t)}});r(this,"onUserLeft",e=>{this.stopCallsToUsersThatAreNotInTheRoomAnymore()});this.context=e,this.peer=t,EE&&(this.debug=!0)}static create(e){const t=GE.getOrCreate(e.context,e.context.connection.connectionId);return new Qu(e.context,t)}startSendingStream(e){this._sendingStreams.has(e)?console.warn("Received start sending stream with stream that is already being sent"):(this._sendingStreams.set(e,[]),this.updateSendingCalls())}stopSendingStream(e){if(e){const t=this._sendingStreams.get(e);if(t){this.debug&&console.log("Closing calls",t);for(const i of t)i.close()}this._sendingStreams.delete(e),t&&this.debug&&console.log("Currently sending",this._sendingStreams)}}enable(){this.peer.enable(),this.peer.addEventListener("receive-stream",this.onReceiveStream),this.peer.addEventListener("call-ended",this.onCallEnded),this.context.connection.beginListen("peer-user-connected",this.onUserConnected),this.context.connection.beginListen(gt.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(gt.UserJoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(gt.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(gt.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(gt.UserJoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(gt.UserLeftRoom,this.onUserLeft)}updateSendingCalls(){var i;let e=!1;const t=this.context.connection.connectionId;for(const I of this._sendingStreams.keys()){const o=this._sendingStreams.get(I)||[];for(const s of this.context.connection.usersInRoom()){if(s===t)continue;const n=o.find(C=>C.userId===s);if(!n||((i=n.stream)==null?void 0:i.active)===!1){this.debug&&console.log("Starting call to",s,t);const C=this.peer.makeCall(this.peer.getPeerIdFromUserId(s),I);C&&(e=!0,o.push(C))}}this._sendingStreams.set(I,o)}this.stopCallsToUsersThatAreNotInTheRoomAnymore(),e&&this.debug&&console.log("Currently sending",this._sendingStreams)}stopCallsToUsersThatAreNotInTheRoomAnymore(){for(const e of this._sendingStreams.keys()){const t=this._sendingStreams.get(e);if(t)for(let i=t.length-1;i>=0;i--){const I=t[i];this.context.connection.userIsInRoom(I.userId)||(I.close(),t.splice(i,1))}}}}function pC(g){if(g&&g instanceof MediaStream)for(const A of g.getTracks())A.stop()}var ZgA=Object.defineProperty,XgA=Object.getOwnPropertyDescriptor,mO=(g,A,e,t)=>{for(var i=t>1?void 0:t?XgA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&ZgA(A,e,i),i};const $gA="noVoip",AIA=IA("debugvoip");class PB extends UA{constructor(){super(...arguments);r(this,"autoConnect",!1);r(this,"runInBackground",!0);r(this,"debug",!1);r(this,"_net");r(this,"_outputStream",null);r(this,"onJoinedRoom",async()=>{await Ns(300),this.autoConnect&&!this.isSending&&this.connect()});r(this,"_incomingStreams",new Map);r(this,"onReceiveStream",e=>{const t=e.target.userId,i=e.stream,I=this._incomingStreams.get(t);if(I)I.srcObject=i,I.setAttribute("autoplay","true");else{const o=new Audio;this._incomingStreams.set(t,o),o.setAttribute("autoplay","true"),o.srcObject=i}});r(this,"onStreamEnded",e=>{const t=this._incomingStreams.get(e.userId);pC(t==null?void 0:t.srcObject),this._incomingStreams.delete(e.userId)});r(this,"onEnabledChanged",()=>{for(const e of this._incomingStreams){const t=e[1];t.muted=!this.enabled}});r(this,"onVisibilityChanged",()=>{if(this.runInBackground)return;const t=!(document.visibilityState==="visible");this.setMuted(t);for(const i of this._incomingStreams){const I=i[1];I.muted=t}})}awake(){AIA&&(this.debug=!0),this.debug&&window.addEventListener("keydown",async e=>{e.key==="v"&&(console.log("MUTE?",!this.isMuted),this.setMuted(!this.isMuted))})}onEnable(){this._net||(this._net=Qu.create(this)),this._net.addEventListener(En.StreamReceived,this.onReceiveStream),this._net.addEventListener(En.StreamEnded,this.onStreamEnded),this._net.enable(),this.autoConnect&&(this.context.connection.isConnected?this.connect():this.context.connection.beginListen(gt.JoinedRoom,this.onJoinedRoom)),this.onEnabledChanged(),window.addEventListener("visibilitychange",this.onVisibilityChanged)}onDisable(){var e;this._net.stopSendingStream(this._outputStream),this._net.removeEventListener(En.StreamReceived,this.onReceiveStream),this._net.removeEventListener(En.StreamEnded,this.onStreamEnded),(e=this._net)==null||e.disable(),this.context.connection.stopListen(gt.JoinedRoom,this.onJoinedRoom),this.onEnabledChanged(),window.removeEventListener("visibilitychange",this.onVisibilityChanged)}get isSending(){return this._outputStream!=null&&this._outputStream.active}async connect(e){if(this.context.connection.isConnected){if(!await JG())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),pC(this._outputStream),this._outputStream=await this.getAudioStream(e),this._outputStream?(this._net.startSendingStream(this._outputStream),!0):(await JG()?console.error("VOIP: Could not get audio stream - please make sure to connect an audio device and grant microphone permissions"):I2("Microphone permissions not granted: Please grant microphone permissions to use voice chat"),!1)}disconnect(){this._net.stopSendingStream(this._outputStream),pC(this._outputStream),this._outputStream=null}setMuted(e){var i;const t=(i=this._outputStream)==null?void 0:i.getAudioTracks();if(t)for(const I of t)I.enabled=!e}get isMuted(){var t;if(this._outputStream===null)return!1;const e=(t=this._outputStream)==null?void 0:t.getAudioTracks();if(e){for(const i of e)if(!i.enabled)return!0}return!1}getFrequency(e){return this.unsupported_getfrequency||(this.unsupported_getfrequency=!0,pe()&&Ii("VOIP: getFrequency is currently not supported"),console.warn("VOIP: getFrequency is currently not supported")),null}async getAudioStream(e){return navigator.mediaDevices.getUserMedia?await navigator.mediaDevices.getUserMedia({audio:e??!0,video:!1}).catch(i=>(console.warn("VOIP failed getting audio stream",i),null)):(console.error("No getDisplayMedia support"),null)}}mO([D()],PB.prototype,"autoConnect",2);mO([D()],PB.prototype,"runInBackground",2);var eIA=Object.defineProperty,tIA=Object.getOwnPropertyDescriptor,MO=(g,A,e,t)=>{for(var i=t>1?void 0:t?tIA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&eIA(A,e,i),i};const iIA=IA("debugmouth");class Eu extends UA{constructor(){super(...arguments);r(this,"idle",[]);r(this,"talking",[]);r(this,"marker",null);r(this,"voip",null);r(this,"lastMouthChangeTime",0);r(this,"mouthChangeLength",0)}awake(){setTimeout(()=>{this.voip=nA.findObjectOfType(PB,this.context),this.marker||(this.marker=nA.getComponentInParent(this.gameObject,og))},3e3)}update(){var i;if(!this.voip||this.context.time.frameCount%10!==0)return;let e=((i=this.marker)==null?void 0:i.connectionId)??null;if(!e){iIA&&(e=null);return}const t=this.voip.getFrequency(e)??0;this.updateLips(t)}updateLips(e){if(this.context.time.time-this.lastMouthChangeTime>this.mouthChangeLength){if(this.mouthChangeLength=.05+Math.random()*.1,this.talking&&this.talking.length>0&&e>30){this.lastMouthChangeTime=this.context.time.time;const t=Math.floor(Math.random()*this.talking.length);this.setMouthShapeActive(this.talking,t)}else if(this.idle.length>0&&this.context.time.time-this.lastMouthChangeTime>.5){this.lastMouthChangeTime=this.context.time.time;const t=Math.floor(Math.random()*this.idle.length);this.setMouthShapeActive(this.idle,t)}}}setMouthShapeActive(e,t){if(e){e!=this.idle?this.idle.map(i=>i.visible=!1):this.talking.map(i=>i.visible=!1);for(let i=0;i<e.length;i++){const I=e[i];I&&(I.visible=i===t)}}}}MO([D(pA)],Eu.prototype,"idle",2);MO([D(pA)],Eu.prototype,"talking",2);class UN extends UA{constructor(){super(...arguments);r(this,"voip",null);r(this,"marker",null);r(this,"_startPosition",null)}awake(){this.voip=nA.findObjectOfType(PB,this.context),this.marker=nA.getComponentInParent(this.gameObject,og)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!==0)return;const e=this.marker.connectionId,t=this.voip.getFrequency(e);if(t==null)return;this._startPosition||(this._startPosition=this.gameObject.position.clone());const i=t/100;this.gameObject.position.y=this._startPosition.y+i*.07}}var gIA=Object.defineProperty,IIA=Object.getOwnPropertyDescriptor,lS=(g,A,e,t)=>{for(var i=t>1?void 0:t?IIA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&gIA(A,e,i),i};class WB extends UA{constructor(){super(...arguments);r(this,"eyes",[]);r(this,"lastBlinkTime",0);r(this,"blinkLength",0);r(this,"eyesOpen",!0);r(this,"state",null)}awake(){this.state=nA.getComponentInParent(this.gameObject,co)}update(){if(!this.gameObject||!this.gameObject.visible||!this.eyes||!Array.isArray(this.eyes)||this.eyes.length===0)return;if(this.context.time.time-this.lastBlinkTime>this.blinkLength){if(this.lastBlinkTime=this.context.time.time,this.state&&!this.state.isOn||!this.activeAndEnabled)return;if(this.eyesOpen=!this.eyesOpen,this.blinkLength=Math.random(),this.eyesOpen?(this.blinkLength*=3,this.blinkLength+=.5,Math.random()<.1&&(this.blinkLength=.1+Math.random()*.2)):(this.blinkLength*=Math.random()*.2,this.blinkLength+=.1),Math.random()<.1&&(this.blinkLength*=3),this.blinkLength=Math.max(.2,this.blinkLength),this.blinkLength=Math.min(3,this.blinkLength),this.eyes)for(const t of this.eyes)t&&(t.visible=this.eyesOpen)}}}lS([D(pA)],WB.prototype,"eyes",2);lS([D()],WB.prototype,"lastBlinkTime",2);lS([D()],WB.prototype,"blinkLength",2);lS([D()],WB.prototype,"eyesOpen",2);var oIA=Object.defineProperty,sIA=Object.getOwnPropertyDescriptor,NN=(g,A,e,t)=>{for(var i=t>1?void 0:t?sIA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&oIA(A,e,i),i},TM;const GO=(TM=class extends UA{constructor(){super(...arguments);r(this,"head",null);r(this,"eyes",null);r(this,"target",null);r(this,"brain",null);r(this,"vec",new y);r(this,"currentTargetPoint",new y)}awake(){this.brain||(this.brain=nA.getComponentInParent(this.gameObject,sd)),this.brain||(console.log("No look at brain found, adding it now"),this.brain=nA.addNewComponent(this.gameObject,sd)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}update(){const A=this.target;if(A&&this.head){const e=this.eyes;if(e){const t=ve(A);this.currentTargetPoint.lerp(t,this.context.time.deltaTime/.1);const i=ve(this.head),I=this.vec.copy(this.currentTargetPoint).sub(i).normalize();if(I.length()<.1)return;const o=GO.forward;if(o.set(0,0,1),o.applyQuaternion(Nt(this.head)),o.dot(I)>.45)for(let n=0;n<e.length;n++)e[n].lookAt(this.currentTargetPoint)}}}},r(TM,"forward",new y(0,0,1)),TM);let pc=GO;NN([D(pA)],pc.prototype,"head",2);NN([D(pA)],pc.prototype,"eyes",2);NN([D(pA)],pc.prototype,"target",2);const hl=IA("debugavatar");class hS{constructor(A,e,t,i){r(this,"root");r(this,"head");r(this,"leftHand");r(this,"rigthHand");var I;this.root=A,this.head=e,this.leftHand=t,this.rigthHand=i,(I=this.root)==null||I.traverse(o=>o.layers.set(2))}get isValid(){return this.head!==null&&this.head!==void 0}}class FN{constructor(){r(this,"avatarRegistryUrl",null)}async getOrCreateNewAvatarInstance(A,e){if(!e)return console.error("Can not create avatar: failed to provide id or root object"),null;let t=null;if(typeof e=="string"){if(t=await this.loadAvatar(A,e),!t){const I=new vs;t=nA.instantiate(vE(e,A.scene),I)}}else t=e;if(!t)return null;const i=this.findAvatar(t);return i.isValid?(hl&&console.log("[Custom Avatar] valid config",e,hl?i:""),i):(console.warn("[Custom Avatar] config isn't valid",e,hl?i:""),null)}async loadAvatar(A,e){if(console.assert(e!=null&&typeof e=="string","Avatar id must not be null"),e.length<=0||!e)return null;if(hl&&console.log("[Custom Avatar] "+e+", loading..."),e.endsWith(".glb")||(e+=".glb"),this.avatarRegistryUrl===null){const i=await fetch("./"+e);let I=null;if(i.ok){const s=await i.blob();s&&(I=await s.arrayBuffer())}if(!I&&(I=await $U(e,e,0,"no url here go away",!0),!I))return null;const o=await Us().parseSync(A,I,null,0);return(o==null?void 0:o.scene)??null}const t=new Ec;return iu(t,A),new Promise((i,I)=>{const o=this.avatarRegistryUrl+"/"+e;t.load(o,async s=>{await Us().createBuiltinComponents(A,o,s,null,void 0),i(s.scene)},s=>{hl&&console.log("[Custom Avatar] "+s.loaded/s.total*100+"% loaded of "+s.total/1024+"kB")},s=>{console.error("[Custom Avatar] Error when loading: "+s),i(null)})})}cacheModel(A,e){}findAvatar(A){const e=A;let t=e;t.children.length==1&&(t=A.children[0]);let i=this.findAvatarPart(t,["head"]);const I=this.findAvatarPart(t,["left","hand"]),o=this.findAvatarPart(t,["right","hand"]);if(!i){i=e;const n=new y;new Ft().setFromObject(i).getSize(n);const C=Math.max(n.x,n.y,n.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+C+" meters! Should be < 0.3m"),C>.3&&i.scale.multiplyScalar(1/C*.3)}return new hS(e,i,I,o)}findAvatarPart(A,e){const t=A.name.toLowerCase();let i=!0;for(const I of e){if(!i)break;t.indexOf(I)===-1&&(i=!1)}if(i)return A;if(A.children)for(const I of A.children){const o=this.findAvatarPart(I,e);if(o)return o}return null}handleCustomAvatarErrors(A){if(!A.ok)throw Error(A.statusText);return A}}var nIA=Object.defineProperty,CIA=Object.getOwnPropertyDescriptor,KN=(g,A,e,t)=>{for(var i=t>1?void 0:t?CIA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&nIA(A,e,i),i};class fc extends UA{constructor(){super(...arguments);r(this,"length",1);r(this,"depthTest",!0);r(this,"isGizmo",!0);r(this,"_axes",null)}onEnable(){if(this.isGizmo&&!Wd)return;this._axes||(this._axes=new $o(this.length)),this._axes.layers.disableAll(),this._axes.layers.set(this.layer),this.gameObject.add(this._axes);const e=this._axes.material;e&&e.depthTest!==void 0&&(e.depthTest=this.depthTest)}onDisable(){this._axes&&this.gameObject.remove(this._axes)}}KN([D()],fc.prototype,"length",2);KN([D()],fc.prototype,"depthTest",2);KN([D()],fc.prototype,"isGizmo",2);class JN extends UA{constructor(){super(...arguments);r(this,"from");r(this,"to");r(this,"hint");r(this,"desiredDistance",1)}onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;const e=ve(this.to).clone(),t=ve(this.from).clone(),i=e.distanceTo(t),I=e.clone();I.sub(t);const o=t.clone();o.add(e),o.multiplyScalar(.5);const s=ve(this.hint).clone();s.sub(o);const n=new y;n.crossVectors(s,I),n.crossVectors(I,n),n.normalize();const C=i*.5,a=Math.max(this.desiredDistance,C),B=Math.sqrt(a*a-C*C),Q=n.clone();Q.multiplyScalar(B),Q.add(o),aI(this.gameObject,Q);const E=o.clone();E.sub(n),this.gameObject.lookAt(E)}}const aIA=IA("debugusdzbehaviours");class dS{constructor(){r(this,"behaviours",[]);r(this,"behaviourComponents",[]);r(this,"behaviourComponentsCopy",[])}get extensionName(){return"Behaviour"}addBehavior(A){this.behaviours.push(A)}onBeforeBuildDocument(A){const e=[];return A.root.traverse(t=>{nA.foreachComponent(t,i=>{var o;const I=i;if(typeof I.createBehaviours=="function"||typeof I.beforeCreateDocument=="function"||typeof I.afterCreateDocument=="function"||typeof I.afterSerialize=="function"){this.behaviourComponents.push(I);const s=(o=I.beforeCreateDocument)==null?void 0:o.call(I,this,A);s instanceof Promise&&e.push(s)}},!1)}),Promise.all(e)}onExportObject(A,e,t){var i;for(const I of this.behaviourComponents)(i=I.createBehaviours)==null||i.call(I,this,e,t)}onAfterBuildDocument(A){for(const e of this.behaviourComponents)typeof e.afterCreateDocument=="function"&&e.afterCreateDocument(this,A);this.behaviourComponentsCopy=this.behaviourComponents.slice(),this.behaviourComponents.length=0}onAfterHierarchy(A,e){var t;if((t=this.behaviours)!=null&&t.length){e.beginBlock('def Scope "Behaviors"');for(const i of this.behaviours)i.writeTo(this,A.document,e);e.closeBlock()}}async onAfterSerialize(A){aIA&&console.log("onAfterSerialize behaviours",this.behaviourComponentsCopy);for(const e of this.behaviourComponentsCopy)typeof e.afterSerialize=="function"&&(e.afterSerialize.constructor.name==="AsyncFunction"?await e.afterSerialize(this,A):e.afterSerialize(this,A));this.behaviours.length=0}}var rIA=Object.defineProperty,BIA=Object.getOwnPropertyDescriptor,qN=(g,A,e,t)=>{for(var i=t>1?void 0:t?BIA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&rIA(A,e,i),i},_M;const kO=(_M=class extends QI{constructor(){super(...arguments);r(this,"threshold");r(this,"intensity");r(this,"scatter");r(this,"selectiveBloom")}get typeName(){return"Bloom"}init(){this.threshold.defaultValue=1,this.intensity.defaultValue=0,this.scatter.defaultValue=.2,this.selectiveBloom?(this.threshold.valueProcessor=A=>A,this.intensity.valueProcessor=A=>A,this.scatter.valueProcessor=A=>1*Math.PI*(1-A)):(this.threshold.valueProcessor=A=>A,this.intensity.valueProcessor=A=>A,this.scatter.valueProcessor=A=>100*(1-A))}onCreateEffect(){let A;if(this.selectiveBloom==null&&(this.selectiveBloom=kO.useSelectiveBloom),this.selectiveBloom){const e=A=new F2(this.context.scene,this.context.mainCamera,{blendFunction:Pe.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,intensity:this.intensity.value});e.inverted=!0}else A=new zU({blendFunction:Pe.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,intensity:this.intensity.value});return this.intensity.onValueChanged=e=>{A.intensity=e},this.threshold.onValueChanged=e=>{A.luminanceMaterial.threshold=e},this.scatter.onValueChanged=e=>{A.luminancePass.enabled=!0,A.luminanceMaterial.smoothing=e},A}},r(_M,"useSelectiveBloom",!1),_M);let jB=kO;qN([D(xe)],jB.prototype,"threshold",2);qN([D(xe)],jB.prototype,"intensity",2);qN([D(xe)],jB.prototype,"scatter",2);ss("Bloom",jB);var QIA=Object.defineProperty,EIA=Object.getOwnPropertyDescriptor,$I=(g,A,e,t)=>{for(var i=t>1?void 0:t?EIA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&QIA(A,e,i),i};class ns extends UA{constructor(){super(...arguments);r(this,"attachedRigidbody",null);r(this,"isTrigger",!1);r(this,"sharedMaterial");r(this,"membership",[0]);r(this,"filter");r(this,"updateProperties",()=>{var e;(e=this.context.physics.engine)==null||e.updateProperties(this)})}get isCollider(){return!0}awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(zt))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(zt))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(zt))}onDisable(){var e;(e=this.context.physics.engine)==null||e.removeBody(this)}get body(){var e;return(e=this.context.physics.engine)==null?void 0:e.getBody(this)}updatePhysicsMaterial(){var e;(e=this.context.physics.engine)==null||e.updatePhysicsMaterial(this)}}$I([D(zt)],ns.prototype,"attachedRigidbody",2);$I([D()],ns.prototype,"isTrigger",2);$I([D()],ns.prototype,"sharedMaterial",2);$I([D()],ns.prototype,"membership",2);$I([D()],ns.prototype,"filter",2);class cu extends ns{constructor(){super(...arguments);r(this,"radius",.5);r(this,"center",new y(0,0,0))}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addSphereCollider(this),qw(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),IU(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}}$I([Vg(),D()],cu.prototype,"radius",2);$I([D(y)],cu.prototype,"center",2);class lu extends ns{constructor(){super(...arguments);r(this,"size",new y(1,1,1));r(this,"center",new y(0,0,0))}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addBoxCollider(this,this.size),qw(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),IU(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}}$I([Vg(),D(y)],lu.prototype,"size",2);$I([D(y)],lu.prototype,"center",2);class Dc extends ns{constructor(){super(...arguments);r(this,"sharedMesh");r(this,"convex",!1)}onEnable(){var e,t,i,I,o;if(super.onEnable(),(e=this.sharedMesh)!=null&&e.isMesh||this.gameObject instanceof dA&&(this.sharedMesh=this.gameObject),(t=this.sharedMesh)!=null&&t.isMesh)(i=this.context.physics.engine)==null||i.addMeshCollider(this,this.sharedMesh,this.convex,Ei(this.gameObject));else{const s=this.sharedMesh;if(s!=null&&s.isGroup){console.warn(`MeshCollider mesh is a group "${((I=this.sharedMesh)==null?void 0:I.name)||this.gameObject.name}", adding all children as colliders. This is currently not fully supported (colliders can not be removed from world again)`,this);for(const n in s.children){const C=s.children[n];C.isMesh&&((o=this.context.physics.engine)==null||o.addMeshCollider(this,C,this.convex,Ei(this.gameObject)))}}}}}$I([D()],Dc.prototype,"sharedMesh",2);$I([D()],Dc.prototype,"convex",2);class er extends ns{constructor(){super(...arguments);r(this,"center",new y(0,0,0));r(this,"radius",.5);r(this,"height",2)}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addCapsuleCollider(this,this.height,this.radius)}}$I([D(y)],er.prototype,"center",2);$I([D()],er.prototype,"radius",2);$I([D()],er.prototype,"height",2);var cIA=Object.defineProperty,lIA=Object.getOwnPropertyDescriptor,bN=(g,A,e,t)=>{for(var i=t>1?void 0:t?lIA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&cIA(A,e,i),i};class zB extends UA{constructor(){super(...arguments);r(this,"objectBounds",!1);r(this,"color");r(this,"isGizmo",!0);r(this,"_gizmoObject",null);r(this,"_boxHelper",null)}onEnable(){this.isGizmo&&!Wd||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new tU(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=AN(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),zi.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){var e;for(;this._boxHelper;)(e=this._boxHelper)==null||e.update(),yield}}bN([D()],zB.prototype,"objectBounds",2);bN([D(mA)],zB.prototype,"color",2);bN([D()],zB.prototype,"isGizmo",2);const hIA=IA("gizmos"),dIA=IA("debugboxhelper"),xo=class extends UA{constructor(){super(...arguments);r(this,"box",null);r(this,"_lastMatrixUpdateFrame",-1);r(this,"_helper",null);r(this,"_color",null)}isInBox(e,t){var I;if(!e)return;if(this.box||(this.box=new Ft),e.type==="Mesh")xo.testBox.setFromObject(e);else if(e.type==="Group"){if(xo.testBox.makeEmpty(),e.children.length>0)for(let o=0;o<e.children.length;o++)e.children[o].type==="Mesh"&&xo.testBox.expandByObject(e)}else{const o=ve(e,xo._position),s=Ei(e,xo._size);t!==void 0&&s.multiplyScalar(t),xo.testBox.setFromCenterAndSize(o,s)}this.updateBox();const i=(I=this.box)==null?void 0:I.intersectsBox(xo.testBox);return i&&dIA&&Ue.DrawWireBox3(xo.testBox,16711680,5),i}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){if(this.box||(this.box=new Ft),e||this.context.time.frameCount!=this._lastMatrixUpdateFrame){const t=this._lastMatrixUpdateFrame<0;this._lastMatrixUpdateFrame=this.context.time.frameCount;const i=t,I=ve(this.gameObject,xo._position,i),o=Ei(this.gameObject,xo._size);this.box.setFromCenterAndSize(I,o)}return this.box}awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,t=!1){var i;if(!(!hIA&&!t)){if(this._helper){e&&((i=this._color)==null||i.set(e)),this.gameObject.add(this._helper);return}this._helper=AN(e),this.gameObject.add(this._helper)}}};let jo=xo;r(jo,"testBox",new Ft),r(jo,"_position",new y),r(jo,"_size",new y(.01,.01,.01));class uIA extends A2{constructor(A,e={}){super(A),A._simpleState__activeStates=[],A._simpleState__normalStyles={},A._simpleState__states=e,A._simpleState__statesProperties={};for(const t in e)for(const i in e[t])A._simpleState__statesProperties[i]||(A._simpleState__statesProperties[i]=[]),A._simpleState__statesProperties[i].push(t);for(const t of A._components)A._simpleState__statesProperties[t.id]&&(A._simpleState__normalStyles[t.id]=t.inline?t.inline:t._value);A.__overridedSet=A.set,A.set=this.storeSet.bind(A),A.renderStates=this.renderStates.bind(A),A.setupState=this.setupState.bind(A),A.setState=this.setState.bind(A),A.activatePseudoState=this.activatePseudoState.bind(A),A.deactivatePseudoState=this.deactivatePseudoState.bind(A),A.togglePseudoState=this.togglePseudoState.bind(A)}act(){}attach(){}detach(){}setupState(A,e){this._simpleState__states[A]=e;const t=[];for(const i in e)this._simpleState__statesProperties[i]||(this._simpleState__statesProperties[i]=[],t.push(i)),this._simpleState__statesProperties[i].push(A);for(const i of this._components)t.indexOf(i.id)>-1&&(this._simpleState__normalStyles[i.id]=i.inline?i.inline:i._value)}renderStates(){let A={...this._simpleState__normalStyles};for(const e in this._simpleState__states)this._simpleState__activeStates.indexOf(e)>-1&&(A={...A,...this._simpleState__states[e]});this.set(A,!1)}storeSet(A,e=!0){if(e)for(const t in A)this._simpleState__statesProperties[t]&&(this._simpleState__normalStyles[t]=A[t]);this.__overridedSet(A)}activatePseudoState(A){this._simpleState__activeStates.indexOf(A)===-1&&(this._simpleState__activeStates.push(A),this.renderStates())}deactivatePseudoState(A){const e=this._simpleState__activeStates.indexOf(A);e>-1&&(this._simpleState__activeStates.splice(e,1),this.renderStates())}togglePseudoState(A){const e=this._simpleState__activeStates.indexOf(A);e>-1?this._simpleState__activeStates.splice(e,1):this._simpleState__activeStates.push(A),this.renderStates()}setState(A){Array.isArray(A)?this._simpleState__activeStates=A:this._simpleState__activeStates=[A],this.renderStates()}}const lD="NEEDLE_progressive",ig=IA("debugprogressive"),tM=Symbol("needle-progressive-texture"),fy=new Map;let iM=!1;ig&&window.addEventListener("keyup",g=>{g.key==="p"&&(console.log("Toggle progressive textures",fy),fy.forEach((A,e)=>{Object.entries(A).forEach(([t,i])=>{iM?e[t]=i.lod0:e[t]=i.original,e.needsUpdate=!0})}),iM=!iM)});const Sh=class{constructor(A,e,t){r(this,"parser");r(this,"sourceId");r(this,"context");this.parser=A,this.sourceId=e,this.context=t}get name(){return lD}static assignTextureLOD(A,e,t,i=0){if(!t)return Promise.resolve(null);if(t instanceof Ye){const I=t,o=[];if(I instanceof Jd)for(const s of Object.keys(I.uniforms)){const n=I.uniforms[s].value;if(n instanceof Je){const C=this.assignTextureLODForSlot(A,e,n,i,I,s);o.push(C)}}else for(const s of Object.keys(I)){const n=I[s];if(n instanceof Je){const C=this.assignTextureLODForSlot(A,e,n,i,I,s);o.push(C)}}return Ld(o)}if(t instanceof Je){const I=t;return this.assignTextureLODForSlot(A,e,I,i,null,null)}return Promise.resolve(null)}static assignTextureLODForSlot(A,e,t,i,I,o){return(t==null?void 0:t.isTexture)!==!0?Promise.resolve(null):(ig&&console.log(`-----------
5481
5481
  `,"FIND",I==null?void 0:I.name,o,t==null?void 0:t.name,t==null?void 0:t.userData,t,I),Sh.getOrLoadTexture(A,e,t,i,I,o).then(s=>{if((s==null?void 0:s.isTexture)===!0){if(ig&&console.warn("Assign LOD",I==null?void 0:I.name,o,s.name,s.guid,I,"Prev:",t,"Now:",s,`