@needle-tools/engine 3.28.3-beta → 3.28.4-beta

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.
@@ -5093,7 +5093,7 @@ ${o.join(`
5093
5093
 
5094
5094
  }
5095
5095
  `}function l2(t){return`(${t.r}, ${t.g}, ${t.b})`}function d2(t){return`(${t.x}, ${t.y})`}const p2=[1023,33777,33778,33779,35842,35843,37496,37808,37809,37810,37811,37812,37813,37814,37815,37816,37817,37818,37819,37820,37821,36492];CA("debugusdz");const u2=class{constructor(t,A,e){n(this,"id"),n(this,"trigger"),n(this,"action"),n(this,"exclusive",!1),this.id="Behavior_"+qw(t)+"_"+u2.global_id++,this.trigger=A,this.action=e}makeExclusive(t){return this.exclusive=t,this}writeTo(t,A,e){if(!this.trigger||!this.action)return;e.beginBlock(`def Preliminary_Behavior "${this.id}"`),e.appendLine(`rel actions = <${this.action.id}>`),e.appendLine(`uniform bool exclusive = ${this.exclusive}`);let i="";if(Array.isArray(this.trigger)){i="[";for(let g=0;g<this.trigger.length;g++){const I=this.trigger[g];i+="<"+I.id+">",g+1<this.trigger.length&&(i+=", ")}i+="]"}else i=`<${this.trigger.id}>`;if(e.appendLine(`rel triggers = ${i} `),e.appendLine(),Array.isArray(this.trigger))for(const g of this.trigger)g.writeTo(A,e),e.appendLine();else this.trigger.writeTo(A,e);e.appendLine(),this.action.writeTo(A,e),e.closeBlock()}};let yg=u2;n(yg,"global_id",0);function UR(t,A){var e,i;let g="";if(Array.isArray(t)){let I="[ ";for(let o=0;o<t.length;o++){let s=t[o];if(typeof s=="string")I+=s;else if(typeof s=="object"){s.isObject3D&&(s=A.findById(s.uuid));const C=(e=s.getPath)==null?void 0:e.call(s);I+=C}o+1<t.length&&(I+=", ")}I+=" ]",g=I}else typeof t=="object"&&(t.isObject3D&&(t=A.findById(t.uuid)),g=(i=t.getPath)==null?void 0:i.call(t));return g}const D2=class{constructor(t,A){n(this,"id"),n(this,"targetId"),n(this,"tokenId"),n(this,"type"),n(this,"distance"),t&&(this.targetId=t),A?this.id=A:this.id="Trigger_"+D2.global_id++}writeTo(t,A){A.beginBlock(`def Preliminary_Trigger "${this.id}"`),this.targetId&&(typeof this.targetId!="string"&&(this.targetId=UR(this.targetId,t)),A.appendLine("rel affectedObjects = "+this.targetId)),this.tokenId&&A.appendLine(`token info:id = "${this.tokenId}"`),this.type&&A.appendLine(`token type = "${this.type}"`),typeof this.distance=="number"&&A.appendLine(`double distance = ${this.distance}`),A.closeBlock()}};let $r=D2;n($r,"global_id",0);class Sg{static sceneStartTrigger(){const A=new $r;return A.targetId=void 0,A.tokenId="SceneTransition",A.type="enter",A}static tapTrigger(A){const e=new $r(A);return e.tokenId="TapGesture",e}static isTapTrigger(A){return A?.tokenId==="TapGesture"}static proximityToCameraTrigger(A,e){const i=new $r(A);return i.tokenId="ProximityToCamera",i.distance=e,i}}class pn{constructor(A,e){n(this,"id"),n(this,"actions"),n(this,"loops",0),n(this,"performCount",1),n(this,"type","serial"),this.id=A,this.actions=e}static getId(){return this.global_id++}addAction(A){return this.actions.push(A),this}makeParallel(){return this.type="parallel",this}makeSequence(){return this.type="serial",this}makeLooping(){return this.loops=1,this}makeRepeat(A){return this.performCount=A,this}writeTo(A,e){e.beginBlock(`def Preliminary_Action "${this.id}"`),e.beginArray("rel actions");for(const i of this.actions){if(!i)continue;const g=i===this.actions[this.actions.length-1];e.appendLine("<"+i.id+">"+(g?"":", "))}e.closeArray(),e.appendLine(),e.appendLine('token info:id = "Group"'),e.appendLine(`bool loops = ${this.loops} `),e.appendLine(`int performCount = ${this.performCount} `),e.appendLine(`token type = "${this.type}"`),e.appendLine();for(const i of this.actions)i&&(i.writeTo(A,e),e.appendLine());e.closeBlock()}}n(pn,"global_id",0);var NR=(t=>(t[t.pop=0]="pop",t[t.blink=1]="blink",t[t.bounce=2]="bounce",t[t.flip=3]="flip",t[t.float=4]="float",t[t.jiggle=5]="jiggle",t[t.pulse=6]="pulse",t[t.spin=7]="spin",t))(NR||{}),FR=(t=>(t.Relative="relative",t.Absolute="absolute",t))(FR||{}),w2=(t=>(t.Allow="allow",t.Ignore="ignore",t.Stop="stop",t))(w2||{});const KR=class{constructor(t,A){n(this,"id"),n(this,"tokenId"),n(this,"affectedObjects"),n(this,"easeType"),n(this,"motionType"),n(this,"duration"),n(this,"moveDistance"),n(this,"style"),n(this,"type"),n(this,"front"),n(this,"up"),n(this,"start"),n(this,"animationSpeed"),n(this,"reversed"),n(this,"pingPong"),n(this,"xFormTarget"),n(this,"audio"),n(this,"gain"),n(this,"auralMode"),n(this,"multiplePerformOperation"),t&&(this.affectedObjects=t),A?this.id=A:this.id="Action",this.id+="_"+KR.global_id++}clone(){const t=new KR,A=t.id;return Object.assign(t,this),t.id=A,t}writeTo(t,A){A.beginBlock(`def Preliminary_Action "${this.id}"`),this.affectedObjects&&(typeof this.affectedObjects!="string"&&(this.affectedObjects=UR(this.affectedObjects,t)),A.appendLine("rel affectedObjects = "+this.affectedObjects)),typeof this.duration=="number"&&A.appendLine(`double duration = ${this.duration} `),this.easeType&&A.appendLine(`token easeType = "${this.easeType}"`),this.tokenId&&A.appendLine(`token info:id = "${this.tokenId}"`),this.motionType&&A.appendLine(`token motionType = "${this.motionType}"`),typeof this.moveDistance=="number"&&A.appendLine(`double moveDistance = ${this.moveDistance} `),this.style&&A.appendLine(`token style = "${this.style}"`),this.type&&A.appendLine(`token type = "${this.type}"`),this.front&&A.appendLine(`vector3d front = (${this.front.x}, ${this.front.y}, ${this.front.z})`),this.up&&A.appendLine(`vector3d upVector = (${this.up.x}, ${this.up.y}, ${this.up.z})`),typeof this.start=="number"&&A.appendLine(`double start = ${this.start} `),typeof this.animationSpeed=="number"&&A.appendLine(`double animationSpeed = ${this.animationSpeed} `),typeof this.reversed=="boolean"&&A.appendLine(`bool reversed = ${this.reversed}`),typeof this.pingPong=="boolean"&&A.appendLine(`bool reverses = ${this.pingPong}`),this.xFormTarget&&(typeof this.xFormTarget!="string"&&(this.xFormTarget=UR(this.xFormTarget,t)),A.appendLine(`rel xformTarget = ${this.xFormTarget}`)),typeof this.audio=="string"&&A.appendLine(`asset audio = @${this.audio}@`),typeof this.gain=="number"&&A.appendLine(`double gain = ${this.gain}`),typeof this.auralMode=="string"&&A.appendLine(`token auralMode = "${this.auralMode}"`),typeof this.multiplePerformOperation=="string"&&A.appendLine(`token multiplePerformOperation = "${this.multiplePerformOperation}"`),A.closeBlock()}};let Ds=KR;n(Ds,"global_id",0);let nE=class rh{constructor(A,e,i){n(this,"x",0),n(this,"y",0),n(this,"z",0),this.x=A,this.y=e,this.z=i}static get up(){return new rh(0,1,0)}static get right(){return new rh(1,0,0)}static get forward(){return new rh(0,0,1)}static get back(){return new rh(0,0,-1)}static get zero(){return new rh(0,0,0)}};var JR=(t=>(t.Play="play",t.Pause="pause",t.Stop="stop",t))(JR||{}),vR=(t=>(t.Spatial="spatial",t.NonSpatial="nonSpatial",t.Ambient="ambient",t))(vR||{});class Ct{static sequence(...A){return new pn("group_"+pn.getId(),A).makeSequence()}static parallel(...A){return new pn("group_"+pn.getId(),A).makeParallel()}static fadeAction(A,e,i){const g=new Ds(A);return g.tokenId="Visibility",g.type=i?"show":"hide",g.duration=e,g.style="basic",g.motionType="none",g.moveDistance=0,g.easeType="none",g}static startAnimationAction(A,e,i=0,g=1,I=!1,o=!1){const s=new Ds(A);if(s.tokenId="StartAnimation",s.start=e,s.duration=i,s.animationSpeed=g,s.reversed=I,s.pingPong=o,s.multiplePerformOperation="allow",I&&(s.start-=i),o){s.pingPong=!1;const C=s.clone();return C.reversed=!I,C.start=s.start,C.reversed&&(C.start-=i),Ct.sequence(s,C)}return s}static waitAction(A){const e=new Ds;return e.tokenId="Wait",e.duration=A,e}static lookAtCameraAction(A,e=9999999999999,i,g){const I=new Ds(A);return I.tokenId="LookAtCamera",I.duration=e,I.front=i??nE.forward,I.up=g??nE.up,I}static emphasize(A,e,i=2,g=1,I="basic"){const o=new Ds(A);return o.tokenId="Emphasize",o.duration=e,o.style=I??"basic",o.motionType=NR[i],o.moveDistance=g,o}static transformAction(A,e,i,g,I="inout"){const o=new Ds(A);return o.tokenId="Transform",o.duration=i,o.type=g,o.easeType=I,Array.isArray(e)&&console.error("Transform target must not be an array",e),o.xFormTarget=e,o}static playAudioAction(A,e,i="play",g=1,I="spatial"){const o=new Ds(A);return o.tokenId="Audio",o.type=i,o.audio=e,o.gain=g,o.auralMode=I,o.multiplePerformOperation="allow",o}}class niA{constructor(A){n(this,"object"),n(this,"model"),this.object=A}get id(){return this.object.uuid}apply(A){if(!this.model&&(this.model=A.findById(this.object.uuid),!this.model)){console.error("could not find model with id "+this.object.uuid);return}this.onApply(A)}}class qR extends niA{constructor(A,e,i,g){super(A),n(this,"matrix"),n(this,"material"),n(this,"geometry"),n(this,"_enableAction"),n(this,"_disableAction"),this.matrix=e,this.material=i,this.geometry=g}onApply(A){var e,i;const g=this.model;if(!g)return;(e=g.parent)!=null&&e.isDynamic||Ko.createEmptyParent(g);const I=g.clone();this.matrix&&(I.matrix=this.matrix),this.material&&(I.material=this.material),this.geometry&&(I.geometry=this.geometry),(i=g.parent)==null||i.add(I)}enable(){return this._enableAction?this._enableAction:(this._enableAction=Ct.fadeAction(this.object,0,!0),this._enableAction)}disable(){return this._disableAction?this._disableAction:(this._disableAction=Ct.fadeAction(this.object,0,!1),this._disableAction)}}class bR{constructor(A){n(this,"actions"),n(this,"sortedActions"),this.actions=[...A]}organize(){this.sortedActions={};for(const A of this.actions){const e=A.id;this.sortedActions[e]||(this.sortedActions[e]=[]),this.sortedActions[e].push(A)}}getActions(A){return this.sortedActions||this.organize(),this.sortedActions[A.uuid]}}var riA=Object.defineProperty,BiA=Object.getOwnPropertyDescriptor,y2=(t,A,e,i)=>{for(var g=i>1?void 0:i?BiA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&riA(A,e,g),g};class ul extends JA{constructor(){super(...arguments),n(this,"from"),n(this,"to"),n(this,"width",0),n(this,"centered",!0),n(this,"_centerPos")}awake(){this._centerPos=new y}update(){if(!this.from||!this.to)return;const A=he(this.from).clone(),e=he(this.to).clone(),i=A.distanceTo(e);this._centerPos.copy(A),this._centerPos.add(e),this._centerPos.multiplyScalar(.5),ui(this.gameObject,this.centered?this._centerPos:A),this.gameObject.lookAt(he(this.to).clone()),this.gameObject.scale.set(this.width,this.width,i)}}y2([w(iA)],ul.prototype,"from",2),y2([w(iA)],ul.prototype,"to",2);var QiA=Object.defineProperty,EiA=Object.getOwnPropertyDescriptor,Dl=(t,A,e,i)=>{for(var g=i>1?void 0:i?EiA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&QiA(A,e,g),g};const rE=CA("debuganimation");class Ao extends JA{constructor(){super(...arguments),n(this,"playAutomatically",!0),n(this,"randomStartTime",!0),n(this,"minMaxSpeed"),n(this,"minMaxOffsetNormalized"),n(this,"loop",!0),n(this,"clampWhenFinished",!1),n(this,"_tempAnimationClipBeforeGameObjectExisted",null),n(this,"_tempAnimationsArray"),n(this,"mixer"),n(this,"_actions",[]),n(this,"_currentActions",[]),n(this,"_handles",[]),n(this,"_didInit",!1)}get clip(){var A;return(A=this.animations)!=null&&A.length?this.animations[0]:null}set clip(A){if(!this.__didAwake){rE&&console.warn("Assign clip during serialization",A),this._tempAnimationClipBeforeGameObjectExisted=A;return}A&&(this.gameObject.animations||(this.gameObject.animations=[]),!this.animations.includes(A)&&(this.animations.length>0?this.animations.splice(0,0,A):this.animations.push(A)))}set clips(A){this.animations=A}set animations(A){A==null||!Array.isArray(A)||(this.gameObject?this.gameObject.animations=A:this._tempAnimationsArray=A)}get animations(){return this.gameObject.animations||this._tempAnimationsArray||[]}get currentAction(){return this._currentActions[0]}get currentActions(){return this._currentActions}get actions(){return this._actions}set actions(A){this._actions=A}awake(){rE&&console.log("Animation Awake",this.name,this),this._tempAnimationsArray&&(this.animations=this._tempAnimationsArray,this._tempAnimationsArray=void 0),this._tempAnimationClipBeforeGameObjectExisted&&(this.clip=this._tempAnimationClipBeforeGameObjectExisted,this._tempAnimationClipBeforeGameObjectExisted=null),this.playAutomatically&&this.init()}onEnable(){var A;if(this.playAutomatically&&((A=this.animations)==null?void 0:A.length)>0&&this.currentActions.length<=0){const e=Math.floor(Math.random()*this.actions.length);this.play(e)}}start(){this.randomStartTime&&this.currentAction&&(this.currentAction.time=Math.random()*this.currentAction.getClip().duration)}update(){this.mixer&&this.mixer.update(this.context.time.deltaTime)}getAction(A){var e;return(e=this.actions)==null?void 0:e.find(i=>i.getClip().name===A)}get isPlaying(){for(let A=0;A<this.actions.length;A++)if(this.actions[A].isRunning())return!0;return!1}play(A=0,e){if(rE&&console.log("PLAY",A),this.init(),!this.mixer){rE&&console.warn("Missing mixer",this);return}A===void 0&&(A=0);let i=A;if(typeof A=="number"){if(A>=this.animations.length){rE&&console.log("No animation at index",A);return}i=this.animations[A]}else typeof A=="string"&&(i=this.animations.find(I=>I.name===A));if(!i){console.error("Could not find clip",A);return}e||(e={}),e.minMaxOffsetNormalized||(e.minMaxOffsetNormalized=this.minMaxOffsetNormalized),e.minMaxSpeed||(e.minMaxSpeed=this.minMaxSpeed),e.loop===void 0&&(e.loop=this.loop),e.clampWhenFinished===void 0&&(e.clampWhenFinished=this.clampWhenFinished);for(const I of this.actions)if(I.getClip()===i)return this.internalOnPlay(I,e);if(!(i instanceof kI)){console.warn("Clip is no AnimationClip",i,"on object: "+this.name);return}const g=this.mixer.clipAction(i);return this.actions.push(g),this.internalOnPlay(g,e)}internalOnPlay(A,e){var i=this.currentAction;if(i===A&&i.isRunning()&&i.time<i.getClip().duration){const s=this.tryFindHandle(A);if(s)return s.getPromise()}const g=e?.exclusive??!0;e!=null&&e.fadeDuration?(g&&i?.fadeOut(e.fadeDuration),A.fadeIn(e.fadeDuration)):g&&i?.stop(),A.reset(),A.enabled=!0,A.time=0,A.timeScale=1;const I=A.getClip();e!=null&&e.minMaxOffsetNormalized&&(A.time=oe.lerp(e.minMaxOffsetNormalized.x,e.minMaxOffsetNormalized.y,Math.random())*I.duration),e!=null&&e.minMaxSpeed&&(A.timeScale=oe.lerp(e.minMaxSpeed.x,e.minMaxSpeed.y,Math.random())),e!=null&&e.clampWhenFinished&&(A.clampWhenFinished=!0),e?.startTime!==void 0&&(A.time=e.startTime),e?.loop!==void 0?A.loop=e.loop?Uf:Uh:A.loop=Uh,A.play(),rE&&console.log("PLAY",A.getClip().name,A);const o=new hiA(A,this.mixer,e,s=>{this._handles.splice(this._handles.indexOf(o),1)});return this._handles.push(o),o.getPromise()}tryFindHandle(A){for(const e of this._handles)if(e.action===A)return e}init(){this._didInit||(this._didInit=!0,this.gameObject&&(this.actions=[],this.mixer=new Fu(this.gameObject)))}}Dl([w()],Ao.prototype,"playAutomatically",2),Dl([w()],Ao.prototype,"randomStartTime",2),Dl([w()],Ao.prototype,"loop",2),Dl([w()],Ao.prototype,"clampWhenFinished",2),Dl([w(kI)],Ao.prototype,"clips",1);class hiA{constructor(A,e,i,g){n(this,"mixer"),n(this,"action"),n(this,"promise",null),n(this,"resolve",null),n(this,"reject",null),n(this,"_options"),n(this,"_resolveCallback",null),n(this,"_rejectCallback",null),n(this,"_loopCallback"),n(this,"_finishedCallback"),n(this,"_resolvedOrRejectedCallback"),this.action=A,this.mixer=e,this._resolvedOrRejectedCallback=g,this._options=i}getPromise(){return this.promise?this.promise:(this.promise=new Promise((A,e)=>{this._resolveCallback=A,this._rejectCallback=e,this.resolve=this.onResolve.bind(this),this.reject=this.onReject.bind(this)}),this._loopCallback=this.onLoop.bind(this),this._finishedCallback=this.onFinished.bind(this),this.mixer.addEventListener("loop",this._loopCallback),this.mixer.addEventListener("finished",this._finishedCallback),this.promise)}_update(){this._options&&this._options.endTime!==void 0&&this.action.time>this._options.endTime&&(this._options.loop===!0?this.action.time=this._options.startTime??0:(this.action.time=this._options.endTime,this.action.timeScale=0,this.onResolve()))}onResolve(){var A,e;this.dispose(),(A=this._resolvedOrRejectedCallback)==null||A.call(this,this),(e=this._resolveCallback)==null||e.call(this,this.action)}onReject(A){var e,i;this.dispose(),(e=this._resolvedOrRejectedCallback)==null||e.call(this,this),(i=this._rejectCallback)==null||i.call(this,A)}onLoop(A){}onFinished(A){A.action===this.action&&this.onResolve()}dispose(){this._loopCallback&&this.mixer.removeEventListener("loop",this._loopCallback),this._finishedCallback&&this.mixer.removeEventListener("finished",this._finishedCallback),this._loopCallback=void 0,this._finishedCallback=void 0}}var ciA=Object.defineProperty,liA=Object.getOwnPropertyDescriptor,un=(t,A,e,i)=>{for(var g=i>1?void 0:i?liA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&ciA(A,e,g),g};class Dn{constructor(){n(this,"time"),n(this,"value"),n(this,"inTangent"),n(this,"inWeight"),n(this,"outTangent"),n(this,"outWeight"),n(this,"weightedMode")}}un([w()],Dn.prototype,"time",2),un([w()],Dn.prototype,"value",2),un([w()],Dn.prototype,"inTangent",2),un([w()],Dn.prototype,"inWeight",2),un([w()],Dn.prototype,"outTangent",2),un([w()],Dn.prototype,"outWeight",2),un([w()],Dn.prototype,"weightedMode",2);const S2=class{constructor(){n(this,"keys")}get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(t){if(!this.keys||this.keys.length==0)return 0;if(this.keys[0].time>=t)return this.keys[0].value;for(let A=0;A<this.keys.length;A++){const e=this.keys[A];if(e.time<=t)if(A+1<this.keys.length){const i=this.keys[A+1];if(i.time<t)continue;return!isFinite(e.outTangent)||!isFinite(i.inTangent)?e.value:S2.interpolateValue(t,e,i)}else return e.value}return this.keys[this.keys.length-1].value}static interpolateValue(t,A,e){const i=A.time,g=A.value,I=A.outTangent,o=e.time,s=e.value,C=e.inTangent,a=o-i,r=a*a,B=r*a,Q=((I+C)*a-2*(s-g))/B,E=(3*(s-g)-(C+2*I)*a)/r,h=I,d=g,l=t-i,c=l*l,u=c*l;return Q*u+E*c+h*l+d}};let AB=S2;un([w(Dn)],AB.prototype,"keys",2);class diA{constructor(){n(this,"_context")}get context(){return this._context??qe.Current}get isStateMachineBehaviour(){return!0}}class Hw{constructor(A,e,i,g){n(this,"_name"),n(this,"_nameHash"),n(this,"_normalizedTime"),n(this,"_length"),n(this,"_speed"),this._name=A.name,this._nameHash=A.hash,this._normalizedTime=e,this._length=i,this._speed=g}get name(){return this._name}get nameHash(){return this._nameHash}get normalizedTime(){return this._normalizedTime}get length(){return this._length}get speed(){return this._speed}}function f2(t,A){return{name:"",isLooping:!1,guid:A?.generateUUID()??hg.generateUUID(),index:-1,clip:new kI(t,1,[])}}var wn=(t=>(t[t.If=1]="If",t[t.IfNot=2]="IfNot",t[t.Greater=3]="Greater",t[t.Less=4]="Less",t[t.Equals=6]="Equals",t[t.NotEqual=7]="NotEqual",t))(wn||{}),LR=(t=>(t[t.Float=1]="Float",t[t.Int=3]="Int",t[t.Bool=4]="Bool",t[t.Trigger=9]="Trigger",t))(LR||{});const Jo=CA("debuganimatorcontroller"),Ow=CA("debugrootmotion");class Vo{constructor(A){n(this,"normalizedStartOffset",0),n(this,"_speed",1),n(this,"animator"),n(this,"model"),n(this,"_mixer"),n(this,"_activeState"),n(this,"_activeStates",[]),n(this,"rootMotionHandler"),this.model=A,Jo&&console.log(this)}static createFromClips(A,e={looping:!1,autoTransition:!0,transitionDuration:0}){const i=[];for(let I=0;I<A.length;I++){const o=A[I],s=[];if(e.autoTransition!==!1){const a=e.transitionDuration??0,r=a/o.duration;let B=I;(e.autoTransition===void 0||e.autoTransition===!0)&&(B=(I+1)%A.length),s.push({exitTime:1-r,offset:0,duration:a,hasExitTime:!0,destinationState:B,conditions:[]})}const C={name:o.name,hash:I,motion:{name:o.name,clip:o,isLooping:e?.looping??!1},transitions:s,behaviours:[]};i.push(C)}const g={name:"AnimatorController",guid:new AI(Date.now()).generateUUID(),parameters:[],layers:[{name:"Base Layer",stateMachine:{defaultState:0,states:i}}]};return new Vo(g)}play(A,e=-1,i=Number.NEGATIVE_INFINITY,g=0){if(e<0)e=0;else if(e>=this.model.layers.length){console.warn("invalid layer");return}const I=this.model.layers[e].stateMachine;for(const o of I.states)if(o.name===A||o.hash===A){Jo&&console.log("transition to ",o),this.transitionTo(o,g,i);return}console.warn("Could not find "+A+" to play")}reset(){this.setStartTransition()}setBool(A,e){var i,g;const I=typeof A=="string"?"name":"hash";return(g=(i=this.model)==null?void 0:i.parameters)==null?void 0:g.filter(o=>o[I]===A).forEach(o=>o.value=e)}getBool(A){var e,i,g;const I=typeof A=="string"?"name":"hash";return((g=(i=(e=this.model)==null?void 0:e.parameters)==null?void 0:i.find(o=>o[I]===A))==null?void 0:g.value)??!1}setFloat(A,e){var i,g;const I=typeof A=="string"?"name":"hash",o=(g=(i=this.model)==null?void 0:i.parameters)==null?void 0:g.filter(s=>s[I]===A);return o.forEach(s=>s.value=e),o?.length>0}getFloat(A){var e,i,g;const I=typeof A=="string"?"name":"hash";return((g=(i=(e=this.model)==null?void 0:e.parameters)==null?void 0:i.find(o=>o[I]===A))==null?void 0:g.value)??0}setInteger(A,e){var i,g;const I=typeof A=="string"?"name":"hash";return(g=(i=this.model)==null?void 0:i.parameters)==null?void 0:g.filter(o=>o[I]===A).forEach(o=>o.value=e)}getInteger(A){var e,i,g;const I=typeof A=="string"?"name":"hash";return((g=(i=(e=this.model)==null?void 0:e.parameters)==null?void 0:i.find(o=>o[I]===A))==null?void 0:g.value)??0}setTrigger(A){var e,i;Jo&&console.log("SET TRIGGER",A);const g=typeof A=="string"?"name":"hash";return(i=(e=this.model)==null?void 0:e.parameters)==null?void 0:i.filter(I=>I[g]===A).forEach(I=>I.value=!0)}resetTrigger(A){var e,i;const g=typeof A=="string"?"name":"hash";return(i=(e=this.model)==null?void 0:e.parameters)==null?void 0:i.filter(I=>I[g]===A).forEach(I=>I.value=!1)}getTrigger(A){var e,i,g;const I=typeof A=="string"?"name":"hash";return((g=(i=(e=this.model)==null?void 0:e.parameters)==null?void 0:i.find(o=>o[I]===A))==null?void 0:g.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 i of e.stateMachine.states)if(i.name===A||i.hash==A)return i}return 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 Fu(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;const A=Ec(this.model,(e,i,g)=>g==null?!0:!(g.type==="Object3D"||g.isObject3D===!0||Lq(g)||g.tracks!==void 0));return console.assert(A!==this.model),new Vo(A)}update(A){var e,i;if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates(A);const g=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&((e=this.rootMotionHandler)==null||e.onBeforeUpdate(A)),this._mixer.update(g),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 i=this._activeStates[e],g=i.motion;if(!g.action)this._activeStates.splice(e,1),e--;else{const I=g.action;I.weight=A,I.getEffectiveWeight()<=0&&!I.isRunning()&&(Jo&&console.debug("REMOVE",i.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&&(Jo&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",A),e.defaultState=0);const i=e.states[e.defaultState];this.transitionTo(i,0,this.normalizedStartOffset)}}evaluateTransitions(){var A;let e=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;e=!0}const i=this._activeState,g=i.motion.action;for(const o of i.transitions){if(!o.hasExitTime&&o.conditions.length<=0)continue;let s=!0;for(const C of o.conditions)if(!this.evaluateCondition(C)){s=!1;break}if(s)if(g){const C=i.motion.clip.duration,a=C<=0?1:Math.abs(g.time/C);let r=!1;if(o.hasExitTime?g.timeScale>0?r=a>=o.exitTime:g.timeScale<0&&(r=1-a>=o.exitTime):r=!0,r){for(const B of o.conditions){const Q=this.model.parameters.find(E=>E.name===B.parameter);Q?.type===LR.Trigger&&Q.value&&(Q.value=!1)}g.clampWhenFinished=!0,Jo&&console.log("transition to "+o.destinationState,o,a,o.exitTime,o.hasExitTime),this.transitionTo(o.destinationState,o.duration,o.offset);return}}else{this.transitionTo(o.destinationState,o.duration,o.offset);return}}if(g){let o=i.speed??1;i.speedParameter&&(o*=this.getFloat(i.speedParameter)),o!==void 0&&(g.timeScale=o*this._speed)}let I=!1;if(i.motion.isLooping&&g&&(g.time>=g.getClip().duration?(I=!0,g.reset(),g.time=0,g.play()):g.time<=0&&g.timeScale<0&&(I=!0,g.reset(),g.time=g.getClip().duration,g.play())),!I&&i&&!e&&g&&this.animator&&i.behaviours){const o=g?.getClip().duration,s=g.time/o,C=new Hw(this._activeState,s,o,this._speed);for(const a of i.behaviours)a.instance&&((A=a.instance.onStateUpdate)==null||A.call(a.instance,this.animator,C,0))}}getState(A,e){return typeof A=="number"&&(A==-1&&(A=this.model.layers[e].stateMachine.defaultState,A===void 0&&(Jo&&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,i){var g,I,o,s,C,a,r,B;if(!this.animator)return;const Q=0;if(A=this.getState(A,Q),!(A!=null&&A.motion)||!A.motion.clip||!(A.motion.clip instanceof kI))return;const E=this._activeState===A;if(E){const c=A.motion;if(!c.action_loopback&&c.clip){const u=this.rootMotionHandler?this.animator.gameObject.matrix.clone():null;this._mixer.uncacheAction(c.clip,this.animator.gameObject),u&&u.decompose(this.animator.gameObject.position,this.animator.gameObject.quaternion,this.animator.gameObject.scale),c.action_loopback=this.createAction(c.clip)}}if((g=this._activeState)!=null&&g.behaviours&&this._activeState.motion.action){const c=(I=this._activeState)==null?void 0:I.motion.clip.duration,u=this._activeState.motion.action.time/c,p=new Hw(this._activeState,u,c,this._speed);for(const D of this._activeState.behaviours)(s=(o=D.instance)==null?void 0:o.onStateExit)==null||s.call(D.instance,this.animator,p,Q)}const h=(C=this._activeState)==null?void 0:C.motion.action;h&&h.fadeOut(e),E&&(A.motion.action=A.motion.action_loopback,A.motion.action_loopback=h);const d=this._activeState;this._activeState=A;const l=(a=A.motion)==null?void 0:a.action;if(l){if(i=Math.max(0,Math.min(1,i)),A.cycleOffsetParameter){let u=this.getFloat(A.cycleOffsetParameter);typeof u=="number"?(u<0&&(u+=1),i+=u,i%=1):Jo&&console.warn("AnimatorController cycle offset parameter is not a number",A.cycleOffsetParameter)}else typeof A.cycleOffset=="number"&&(i+=A.cycleOffset,i%=1);l.isRunning()&&l.stop(),l.reset(),l.enabled=!0;const c=A.motion.clip.duration;if(l.time=E?0:i*c,l.timeScale<0&&(l.time=c-l.time),l.clampWhenFinished=!0,l.setLoop(Uh,0),e>0?l.fadeIn(e):l.weight=1,l.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(l),this._activeStates.includes(A)||this._activeStates.push(A),this._activeState.behaviours){const u=new Hw(A,i,c,this._speed);for(const p of this._activeState.behaviours)(B=(r=p.instance)==null?void 0:r.onStateEnter)==null||B.call(p.instance,this.animator,u,Q)}}else Jo&&(A.__warned_no_motion||(A.__warned_no_motion=!0,console.warn("No action",A.motion,this)));Jo&&console.log("TRANSITION FROM "+d?.name+" TO "+A.name,e,h,l,l?.getEffectiveTimeScale(),l?.getEffectiveWeight(),l?.isRunning(),l?.isScheduled(),l?.paused)}createAction(A){var e,i;if(this._mixer.existingAction(A)&&this._mixer.uncacheAction(A,(e=this.animator)==null?void 0:e.gameObject),(i=this.animator)!=null&&i.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new piA(this));const g=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,g,A)}else return this._mixer.clipAction(A)}evaluateCondition(A){const e=this.model.parameters.find(i=>i.name===A.parameter);if(!e)return!1;switch(A.mode){case wn.If:return e.value===!0;case wn.IfNot:return e.value===!1;case wn.Greater:return e.value>A.threshold;case wn.Less:return e.value<A.threshold;case wn.Equals:return e.value===A.threshold;case wn.NotEqual:return e.value!==A.threshold}return!1}createActions(A){var e,i;for(const g of this.model.layers){const I=g.stateMachine;for(let o=0;o<I.states.length;o++){const s=I.states[o];s.transitions||(s.transitions=[]);for(const C of s.transitions)C.conditions||(C.conditions=[]);if(s.motion||(s.motion=f2(s.name)),this.animator&&s.motion.clips){const C=(e=s.motion.clips)==null?void 0:e.find(a=>{var r,B;return a.node.name===((B=(r=this.animator)==null?void 0:r.gameObject)==null?void 0:B.name)});s.motion.clip=C?.clip}if(!s.motion.clip){const C=new kI(void 0,void 0,[]);s.motion.clip=C}if((i=s.motion)!=null&&i.clip){const C=s.motion.clip;if(C instanceof kI){const a=this.createAction(C);s.motion.action=a}else(Jo||Ye())&&console.warn("No valid animationclip assigned",s)}if(s.behaviours&&Array.isArray(s.behaviours))for(const C of s.behaviours){if(!(C!=null&&C.typeName))continue;const a=z.get(C.typeName),r=new a;r.isStateMachineBehaviour&&(r._context=this.context??void 0,NQ(r,C.properties),C.instance=r),Jo&&console.log("Created animator controller behaviour",s.name,C.typeName,C.properties,r)}}}}*enumerateActions(){if(this.model.layers)for(const A of this.model.layers){const e=A.stateMachine;for(let i=0;i<e.states.length;i++){const g=e.states[i];g!=null&&g.motion&&(g.motion.action&&(yield g.motion.action),g.motion.action_loopback&&(yield g.motion.action_loopback))}}}}class m2{constructor(A,e){n(this,"track"),n(this,"createdInterpolant"),n(this,"originalEvaluate"),n(this,"customEvaluate"),this.track=A;const i=A,g=i.createInterpolant.bind(A);i.createInterpolant=()=>(i.createInterpolant=g,this.createdInterpolant=g(),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 ag=class{constructor(t,A,e,i,g){if(n(this,"_action"),n(this,"root"),n(this,"clip"),n(this,"positionWrapper",null),n(this,"rotationWrapper",null),n(this,"context"),n(this,"positionChange",new y),n(this,"rotationChange",new UA),n(this,"_prevTime",0),this.context=t,this.root=A,this.clip=e,ag.firstKeyframeRotation[this.cacheId]||(ag.firstKeyframeRotation[this.cacheId]=new UA),g){const I=g.values;ag.firstKeyframeRotation[this.cacheId].set(I[0],I[1],I[2],I[3])}ag.spaceRotation[this.cacheId]||(ag.spaceRotation[this.cacheId]=new UA),ag.effectiveSpaceRotation[this.cacheId]||(ag.effectiveSpaceRotation[this.cacheId]=new UA),ag.clipOffsetRotation[this.cacheId]=new UA,g&&ag.clipOffsetRotation[this.cacheId].set(g.values[0],g.values[1],g.values[2],g.values[3]).invert(),this.handlePosition(e,i),this.handleRotation(e,g)}set action(t){this._action=t}get action(){return this._action}get cacheId(){return this.root.uuid}onStart(t){if(t.getClip()!==this.clip)return;ag.lastObjRotation[this.cacheId]||(ag.lastObjRotation[this.cacheId]=this.root.quaternion.clone());const A=ag.lastObjRotation[this.cacheId];if(ag.spaceRotation[this.cacheId].copy(A),Ow){const e=new Ag().setFromQuaternion(A);console.log("START",this.clip.name,oe.toDegrees(e.y),this.root.position.z)}}getClipRotationOffset(){return ag.clipOffsetRotation[this.cacheId]}handlePosition(t,A){if(A){const e=this.root;Ow&&e.add(new fQ),ag.lastObjPosition[this.cacheId]||(ag.lastObjPosition[this.cacheId]=this.root.position.clone());const i=new y,g=new y;this.positionWrapper=new m2(A,(I,o)=>{const s=this.action.getEffectiveWeight();return Ow&&e.position.length()>8&&e.position.set(0,e.position.y,0),I>this._prevTime&&(i.set(o[0],o[1],o[2]),i.sub(g),i.multiplyScalar(s),i.applyQuaternion(this.getClipRotationOffset()),i.applyQuaternion(e.quaternion),this.positionChange.copy(i)),g.fromArray(o),this._prevTime=I,o[0]=0,o[1]=0,o[2]=0,o})}}handleRotation(t,A){if(A){if(Ow){const I=A.values,o=new Ag().setFromQuaternion(new UA(I[0],I[1],I[2],I[3]));console.log(t.name,A.name,"FIRST ROTATION IN TRACK",oe.toDegrees(o.y));const s=A.values.length-4,C=new UA().set(I[s],I[s+1],I[s+2],I[s+3]),a=new Ag().setFromQuaternion(C);console.log(t.name,A.name,"LAST ROTATION IN TRACK",oe.toDegrees(a.y))}let e=0;const i=new UA,g=new UA;this.rotationWrapper=new m2(A,(I,o)=>(I>e&&(g.set(o[0],o[1],o[2],o[3]),i.invert(),g.multiply(i),this.rotationChange.copy(g)),i.fromArray(o),e=I,o[0]=0,o[1]=0,o[2]=0,o[3]=1,o))}}onBeforeUpdate(t){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(t){return!this.action||(t*=this.action.getEffectiveWeight(),t<=0)?!1:(this.positionChange.multiplyScalar(t),this.rotationChange.slerp(ag.identityQuaternion,1-t),!0)}};let yn=ag;n(yn,"lastObjPosition",{}),n(yn,"lastObjRotation",{}),n(yn,"firstKeyframeRotation",{}),n(yn,"spaceRotation",{}),n(yn,"effectiveSpaceRotation",{}),n(yn,"clipOffsetRotation",{}),n(yn,"identityQuaternion",new UA);class piA{constructor(A){n(this,"controller"),n(this,"handler",[]),n(this,"root"),n(this,"basePosition",new y),n(this,"baseQuaternion",new UA),n(this,"baseRotation",new Ag),n(this,"summedPosition",new y),n(this,"summedRotation",new UA),this.controller=A}createClip(A,e,i){this.root=e,e&&"name"in e&&e.name;const g=this.findRootTrack(i,".position"),I=this.findRootTrack(i,".quaternion"),o=new yn(this.controller.context,e,i,g,I);this.handler.push(o);const s=A.clipAction(i);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 i=A.tracks;if(!i)return null;for(const g of i)if(g.name.endsWith(e))return g;return null}}class uiA extends OC{onSerialize(A,e){}onDeserialize(A,e){if(e.type===Vo&&A?.__type==="AnimatorController")return new Vo(A)}}new uiA(Vo);class DiA extends ci{constructor(A,e=1,i=16,g=2){const I=new le,o=i+g*2,s=new Float32Array((o*3+3)*3);I.setAttribute("position",new te(s,3));const C=new hi({color:65280}),a=new hi({color:16776960});super(I,[a,C]),this.audio=A,this.range=e,this.divisionsInnerAngle=i,this.divisionsOuterAngle=g,this.type="PositionalAudioHelper",this.update()}update(){const A=this.audio,e=this.range,i=this.divisionsInnerAngle,g=this.divisionsOuterAngle,I=hg.degToRad(A.panner.coneInnerAngle),o=hg.degToRad(A.panner.coneOuterAngle),s=I/2,C=o/2;let a=0,r=0,B,Q;const E=this.geometry,h=E.attributes.position;E.clearGroups();function d(l,c,u,p){const D=(c-l)/u;for(h.setXYZ(a,0,0,0),r++,B=l;B<c;B+=D)Q=a+r,h.setXYZ(Q,Math.sin(B)*e,0,Math.cos(B)*e),h.setXYZ(Q+1,Math.sin(Math.min(B+D,c))*e,0,Math.cos(Math.min(B+D,c))*e),h.setXYZ(Q+2,0,0,0),r+=3;E.addGroup(a,r,p),a+=r,r=0}d(-C,-s,g,0),d(-s,s,i,1),d(s,C,g,0),h.needsUpdate=!0,I===o&&(this.material[0].visible=!1)}dispose(){this.geometry.dispose(),this.material[0].dispose(),this.material[1].dispose()}}var wiA=Object.defineProperty,yiA=Object.getOwnPropertyDescriptor,oa=(t,A,e,i)=>{for(var g=i>1?void 0:i?yiA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&wiA(A,e,g),g};const fg=CA("debugaudio");let _w=!1;const Pw=[];function jw(){if(_w)return;Ye()&&console.log("User interaction registered: audio can now be played"),_w=!0;const t=[...Pw];Pw.length=0,t.forEach(A=>A())}document.addEventListener("pointerdown",jw),document.addEventListener("click",jw),document.addEventListener("dragstart",jw),document.addEventListener("touchstart",jw);const sa=class extends JA{constructor(){super(...arguments),n(this,"clip",""),n(this,"playOnAwake",!1),n(this,"_spatialBlend",0),n(this,"_minDistance",1),n(this,"_maxDistance",100),n(this,"_volume",1),n(this,"rollOffMode",0),n(this,"playInBackground",!0),n(this,"_loop",!1),n(this,"sound",null),n(this,"helper",null),n(this,"wasPlaying",!1),n(this,"audioLoader",null),n(this,"shouldPlay",!1),n(this,"_lastClipStartedLoading",null),n(this,"_audioElement",null),n(this,"onVisibilityChanged",()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||KC())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":fg&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,sa.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&sa.userInteractionRegistered&&this.wasPlaying&&this.play();break}}),n(this,"onApplicationMuteChanged",()=>{var t,A;this.context.application.muted?(t=this.sound)==null||t.setVolume(0):(A=this.sound)==null||A.setVolume(this.volume)}),n(this,"lerp",(t,A,e)=>t*(1-e)+A*e),n(this,"createAudio",t=>{fg&&console.log("audio buffer loaded"),sa.registerWaitForAllowAudio(()=>{fg&&console.log("finished loading",t);const A=this.Sound;if(!A){console.warn("Failed getting sound",this.name);return}A.isPlaying&&A.stop(),t&&A.setBuffer(t),A.loop=this._loop,this.context.application.muted?A.setVolume(0):A.setVolume(this.volume),A.autoplay=this.shouldPlay,this.applySpatialDistanceSettings(),A.isPlaying&&A.stop(),fg&&console.log(this.name,this.shouldPlay,sa.userInteractionRegistered,this),this.shouldPlay&&sa.userInteractionRegistered&&this.play()})}),n(this,"_lastContextTime",0),n(this,"_hasEnded",!0),n(this,"_needUpdateSpatialDistanceSettings",!1)}static get userInteractionRegistered(){return _w}static registerWaitForAllowAudio(t){if(t!==null){if(_w){t();return}Pw.indexOf(t)===-1&&Pw.push(t)}}get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(t){this._loop=t,this.sound&&this.sound.setLoop(t)}get spatialBlend(){return this._spatialBlend}set spatialBlend(t){t!==this._spatialBlend&&(this._spatialBlend=t,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(t){this._minDistance!==t&&(this._minDistance=t,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(t){this._maxDistance!==t&&(this._maxDistance=t,this._needUpdateSpatialDistanceSettings=!0)}get volume(){return this._volume}set volume(t){this._volume=t,this.sound&&!this.context.application.muted&&(fg&&console.log(this.name,"audio set volume",t),this.sound.setVolume(t))}get Sound(){if(!this.sound&&sa.userInteractionRegistered){let t=iA.getComponent(this.context.mainCamera,Mn)??iA.findObjectOfType(Mn,this.context);!t&&this.context.mainCamera&&(t=iA.addNewComponent(this.context.mainCamera,Mn)),t!=null&&t.listener?(this.sound=new _v(t.listener),this.gameObject.add(this.sound)):fg&&console.warn("No audio listener found in scene - can not play audio")}return this.sound}get ShouldPlay(){return this.shouldPlay}awake(){fg&&console.log(this),this.audioLoader=new Nu,this.playOnAwake&&(this.shouldPlay=!0)}onEnable(){sa.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():sa.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(VD.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(VD.MuteChanged,this.onApplicationMuteChanged),this.pause()}applySpatialDistanceSettings(){const t=this.sound;if(!t)return;this._needUpdateSpatialDistanceSettings=!1;const A=this.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(fg&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+A),t.setRefDistance(A),t.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:t.setDistanceModel("exponential");break;case 1:t.setDistanceModel("linear");break}this.spatialBlend>0?fg&&!this.helper&&(this.helper=new DiA(t,t.getRefDistance()),t.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}onNewClip(t){if(t&&(this.clip=t),typeof t=="string")if(fg&&console.log(t),t.endsWith(".mp3")||t.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new Nu),this.shouldPlay=!0,this._lastClipStartedLoading===t){fg&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=t,fg&&console.log("load audio",t),this.audioLoader.load(t,this.createAudio,()=>{},console.error)}else console.warn("Unsupported audio clip type",t);else this.shouldPlay=!0,this.createAudio()}play(t=void 0){var A,e;!t&&this.clip&&(t=this.clip),t!==void 0&&typeof t!="string"&&!(t instanceof MediaStream)&&(Ye()&&console.warn("Called play on AudioSource with unknown argument type:",t+`
5096
- Using the assigned clip instead:`,this.clip),t=this.clip);let i=!this.sound||t&&t!==this.clip;if(typeof t=="string"&&!this.audioLoader&&(i=!0),(t instanceof MediaStream||typeof t=="string")&&(this.clip=t),i){this.shouldPlay=!0,this.onNewClip(t);return}if(this.shouldPlay=!0,this._hasEnded=!1,fg&&console.log("play",(A=this.sound)==null?void 0:A.getVolume(),this.sound),this.sound&&!this.sound.isPlaying){const g=this.context.application.muted;g&&this.sound.setVolume(0),this.clip instanceof MediaStream?(this.sound.setMediaStreamSource(this.clip),this._audioElement||(this._audioElement=document.createElement("audio"),this._audioElement.style.display="none"),this._audioElement.parentNode||(e=this.context.domElement.shadowRoot)==null||e.append(this._audioElement),this._audioElement.srcObject=this.clip,this._audioElement.autoplay=!1):(this._audioElement&&this._audioElement.remove(),this.sound.play(g?.1:0))}}pause(){var t,A;fg&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=(t=this.sound)==null?void 0:t.context.currentTime,this.sound.pause()),(A=this._audioElement)==null||A.remove()}stop(){var t,A;fg&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=(t=this.sound)==null?void 0:t.context.currentTime,fg&&console.log(this._lastContextTime),this.sound.stop()),(A=this._audioElement)==null||A.remove()}get isPlaying(){var t;return((t=this.sound)==null?void 0:t.isPlaying)??!1}set isPlaying(t){}get time(){var t,A;return(t=this.sound)!=null&&t.source?((A=this.sound.source)==null?void 0:A.context.currentTime)-this._lastContextTime+this.sound.offset:0}set time(t){if(this.sound){if(t===this.sound.offset)return;const A=this.isPlaying;this.stop(),this.sound.offset=t,A&&this.play()}}update(){this.helper&&(this.isPlaying&&this.helper.update(),this.helper.visible=this.isPlaying),this._needUpdateSpatialDistanceSettings&&this.applySpatialDistanceSettings(),this.sound&&!this.sound.isPlaying&&this.shouldPlay&&!this._hasEnded&&(this._hasEnded=!0,fg&&console.log("Audio clip ended",this.clip),this.sound.dispatchEvent({type:"ended",target:this}))}};let Si=sa;oa([w(URL)],Si.prototype,"clip",2),oa([w()],Si.prototype,"playOnAwake",2),oa([w()],Si.prototype,"loop",1),oa([w()],Si.prototype,"spatialBlend",1),oa([w()],Si.prototype,"minDistance",1),oa([w()],Si.prototype,"maxDistance",1),oa([w()],Si.prototype,"volume",1),oa([w()],Si.prototype,"rollOffMode",2),oa([w()],Si.prototype,"playInBackground",2);var SiA=Object.defineProperty,fiA=Object.getOwnPropertyDescriptor,miA=(t,A,e,i)=>{for(var g=i>1?void 0:i?fiA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&SiA(A,e,g),g};class wl extends JA{constructor(){super(...arguments),n(this,"constraintActive",!0),n(this,"locked",!1),n(this,"sources",[])}}miA([w(fA)],wl.prototype,"sources",2);const k2={type:"change"},xR={type:"start"},G2={type:"end"};let kiA=class extends _i{constructor(t,A){super(),this.object=t,this.domElement=A,this.domElement.style.touchAction="none",this.enabled=!0,this.target=new y,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:gr.ROTATE,MIDDLE:gr.DOLLY,RIGHT:gr.PAN},this.touches={ONE:Ir.ROTATE,TWO:Ir.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this.getPolarAngle=function(){return o.phi},this.getAzimuthalAngle=function(){return o.theta},this.getDistance=function(){return this.object.position.distanceTo(this.target)},this.listenToKeyEvents=function(P){P.addEventListener("keydown",Ee),this._domElementKeyEvents=P},this.stopListenToKeyEvents=function(){this._domElementKeyEvents.removeEventListener("keydown",Ee),this._domElementKeyEvents=null},this.saveState=function(){e.target0.copy(e.target),e.position0.copy(e.object.position),e.zoom0=e.object.zoom},this.reset=function(){e.target.copy(e.target0),e.object.position.copy(e.position0),e.object.zoom=e.zoom0,e.object.updateProjectionMatrix(),e.dispatchEvent(k2),e.update(),g=i.NONE},this.update=function(){const P=new y,SA=new UA().setFromUnitVectors(t.up,new y(0,1,0)),FA=SA.clone().invert(),cA=new y,VA=new UA,ZA=new y,GA=2*Math.PI;return function(){const Ie=e.object.getWorldPosition(t.position);P.copy(Ie).sub(e.target),P.applyQuaternion(SA),o.setFromVector3(P),e.autoRotate&&g===i.NONE&&m(k()),e.enableDamping?(o.theta+=s.theta*e.dampingFactor,o.phi+=s.phi*e.dampingFactor):(o.theta+=s.theta,o.phi+=s.phi);let ee=e.minAzimuthAngle,M=e.maxAzimuthAngle;return isFinite(ee)&&isFinite(M)&&(ee<-Math.PI?ee+=GA:ee>Math.PI&&(ee-=GA),M<-Math.PI?M+=GA:M>Math.PI&&(M-=GA),ee<=M?o.theta=Math.max(ee,Math.min(M,o.theta)):o.theta=o.theta>(ee+M)/2?Math.max(ee,o.theta):Math.min(M,o.theta)),o.phi=Math.max(e.minPolarAngle,Math.min(e.maxPolarAngle,o.phi)),o.makeSafe(),e.enableDamping?a=hg.lerp(a,C,e.dampingFactor):a=C,o.radius*=a,o.radius=Math.max(e.minDistance,Math.min(e.maxDistance,o.radius)),e.enableDamping===!0?e.target.addScaledVector(r,e.dampingFactor):e.target.add(r),P.setFromSpherical(o),P.applyQuaternion(FA),Ie.copy(e.target).add(P),e.object.parent?e.object.parent.worldToLocal(Ie):e.object.position.copy(Ie),e.object.lookAt(e.target),e.enableDamping===!0?(s.theta*=1-e.dampingFactor,s.phi*=1-e.dampingFactor,r.multiplyScalar(1-e.dampingFactor)):(s.set(0,0,0),r.set(0,0,0)),C=1,B||cA.distanceToSquared(e.object.position)>I||8*(1-VA.dot(e.object.quaternion))>I||ZA.distanceToSquared(e.target)>0?(e.dispatchEvent(k2),cA.copy(e.object.position),VA.copy(e.object.quaternion),ZA.copy(e.target),B=!1,!0):!1}}(),this.dispose=function(){e.domElement.removeEventListener("contextmenu",T),e.domElement.removeEventListener("pointerdown",kA),e.domElement.removeEventListener("pointercancel",HA),e.domElement.removeEventListener("wheel",Ce),e.domElement.removeEventListener("pointermove",wA),e.domElement.removeEventListener("pointerup",HA),e._domElementKeyEvents!==null&&(e._domElementKeyEvents.removeEventListener("keydown",Ee),e._domElementKeyEvents=null)};const e=this,i={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6};let g=i.NONE;const I=1e-6,o=new ek,s=new ek;let C=1,a=1;const r=new y;let B=!1;const Q=new eA,E=new eA,h=new eA,d=new eA,l=new eA,c=new eA,u=new eA,p=new eA,D=new eA,S=[],G={};function k(){return 2*Math.PI/60/60*e.autoRotateSpeed}function R(){return Math.pow(.95,e.zoomSpeed)}function m(P){s.theta-=P}function f(P){s.phi-=P}const L=function(){const P=new y;return function(SA,FA){P.setFromMatrixColumn(FA,0),P.multiplyScalar(-SA),r.add(P)}}(),_=function(){const P=new y;return function(SA,FA){e.screenSpacePanning===!0?P.setFromMatrixColumn(FA,1):(P.setFromMatrixColumn(FA,0),P.crossVectors(e.object.up,P)),P.multiplyScalar(SA),r.add(P)}}(),b=function(){const P=new y,SA=new y;return function(FA,cA){const VA=e.domElement;if(e.object.isPerspectiveCamera){e.object.getWorldPosition(SA),P.copy(SA).sub(e.target);let ZA=P.length();ZA*=Math.tan(e.object.fov/2*Math.PI/180),L(2*FA*ZA/VA.clientHeight,e.object.matrixWorld),_(2*cA*ZA/VA.clientHeight,e.object.matrixWorld)}else e.object.isOrthographicCamera?(L(FA*(e.object.right-e.object.left)/e.object.zoom/VA.clientWidth,e.object.matrixWorld),_(cA*(e.object.top-e.object.bottom)/e.object.zoom/VA.clientHeight,e.object.matrixWorld)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),e.enablePan=!1)}}();function H(P){e.object.isPerspectiveCamera?C/=P:e.object.isOrthographicCamera?(e.object.zoom=Math.max(e.minZoom,Math.min(e.maxZoom,e.object.zoom*P)),e.object.updateProjectionMatrix(),B=!0):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),e.enableZoom=!1)}function Z(P){e.object.isPerspectiveCamera?C*=P:e.object.isOrthographicCamera?(e.object.zoom=Math.max(e.minZoom,Math.min(e.maxZoom,e.object.zoom/P)),e.object.updateProjectionMatrix(),B=!0):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),e.enableZoom=!1)}function x(P){Q.set(P.clientX,P.clientY)}function v(P){u.set(P.clientX,P.clientY)}function Y(P){d.set(P.clientX,P.clientY)}function IA(P){E.set(P.clientX,P.clientY),h.subVectors(E,Q).multiplyScalar(e.rotateSpeed);const SA=e.domElement;m(2*Math.PI*h.x/SA.clientHeight),f(2*Math.PI*h.y/SA.clientHeight),Q.copy(E),e.update()}function AA(P){p.set(P.clientX,P.clientY),D.subVectors(p,u),D.y>0?H(R()):D.y<0&&Z(R()),u.copy(p),e.update()}function W(P){l.set(P.clientX,P.clientY),c.subVectors(l,d).multiplyScalar(e.panSpeed),b(c.x,c.y),d.copy(l),e.update()}function gA(P){P.deltaY<0?Z(R()):P.deltaY>0&&H(R()),e.update()}function dA(P){let SA=!1;switch(P.code){case e.keys.UP:P.ctrlKey||P.metaKey||P.shiftKey?f(2*Math.PI*e.rotateSpeed/e.domElement.clientHeight):b(0,e.keyPanSpeed),SA=!0;break;case e.keys.BOTTOM:P.ctrlKey||P.metaKey||P.shiftKey?f(-2*Math.PI*e.rotateSpeed/e.domElement.clientHeight):b(0,-e.keyPanSpeed),SA=!0;break;case e.keys.LEFT:P.ctrlKey||P.metaKey||P.shiftKey?m(2*Math.PI*e.rotateSpeed/e.domElement.clientHeight):b(e.keyPanSpeed,0),SA=!0;break;case e.keys.RIGHT:P.ctrlKey||P.metaKey||P.shiftKey?m(-2*Math.PI*e.rotateSpeed/e.domElement.clientHeight):b(-e.keyPanSpeed,0),SA=!0;break}SA&&(P.preventDefault(),e.update())}function mA(){if(S.length===1)Q.set(S[0].pageX,S[0].pageY);else{const P=.5*(S[0].pageX+S[1].pageX),SA=.5*(S[0].pageY+S[1].pageY);Q.set(P,SA)}}function vA(){if(S.length===1)d.set(S[0].pageX,S[0].pageY);else{const P=.5*(S[0].pageX+S[1].pageX),SA=.5*(S[0].pageY+S[1].pageY);d.set(P,SA)}}function TA(){const P=S[0].pageX-S[1].pageX,SA=S[0].pageY-S[1].pageY,FA=Math.sqrt(P*P+SA*SA);u.set(0,FA)}function WA(){e.enableZoom&&TA(),e.enablePan&&vA()}function $A(){e.enableZoom&&TA(),e.enableRotate&&mA()}function zA(P){if(S.length==1)E.set(P.pageX,P.pageY);else{const FA=bA(P),cA=.5*(P.pageX+FA.x),VA=.5*(P.pageY+FA.y);E.set(cA,VA)}h.subVectors(E,Q).multiplyScalar(e.rotateSpeed);const SA=e.domElement;m(2*Math.PI*h.x/SA.clientHeight),f(2*Math.PI*h.y/SA.clientHeight),Q.copy(E)}function Se(P){if(S.length===1)l.set(P.pageX,P.pageY);else{const SA=bA(P),FA=.5*(P.pageX+SA.x),cA=.5*(P.pageY+SA.y);l.set(FA,cA)}c.subVectors(l,d).multiplyScalar(e.panSpeed),b(c.x,c.y),d.copy(l)}function lA(P){const SA=bA(P),FA=P.pageX-SA.x,cA=P.pageY-SA.y,VA=Math.sqrt(FA*FA+cA*cA);p.set(0,VA),D.set(0,Math.pow(p.y/u.y,e.zoomSpeed)),H(D.y),u.copy(p)}function V(P){e.enableZoom&&lA(P),e.enablePan&&Se(P)}function xA(P){e.enableZoom&&lA(P),e.enableRotate&&zA(P)}function kA(P){e.enabled!==!1&&(S.length===0&&(e.domElement.addEventListener("pointermove",wA),e.domElement.addEventListener("pointerup",HA)),J(P),P.pointerType==="touch"?Xe(P):DA(P))}function wA(P){e.enabled!==!1&&(P.pointerType==="touch"?at(P):XA(P))}function HA(P){hA(P),S.length===0&&(e.domElement.removeEventListener("pointermove",wA),e.domElement.removeEventListener("pointerup",HA)),e.dispatchEvent(G2),g=i.NONE}function DA(P){let SA;switch(P.button){case 0:SA=e.mouseButtons.LEFT;break;case 1:SA=e.mouseButtons.MIDDLE;break;case 2:SA=e.mouseButtons.RIGHT;break;default:SA=-1}switch(SA){case gr.DOLLY:if(e.enableZoom===!1)return;v(P),g=i.DOLLY;break;case gr.ROTATE:if(P.ctrlKey||P.metaKey||P.shiftKey){if(e.enablePan===!1)return;Y(P),g=i.PAN}else{if(e.enableRotate===!1)return;x(P),g=i.ROTATE}break;case gr.PAN:if(P.ctrlKey||P.metaKey||P.shiftKey){if(e.enableRotate===!1)return;x(P),g=i.ROTATE}else{if(e.enablePan===!1)return;Y(P),g=i.PAN}break;default:g=i.NONE}g!==i.NONE&&e.dispatchEvent(xR)}function XA(P){switch(g){case i.ROTATE:if(e.enableRotate===!1)return;IA(P);break;case i.DOLLY:if(e.enableZoom===!1)return;AA(P);break;case i.PAN:if(e.enablePan===!1)return;W(P);break}}function Ce(P){e.enabled===!1||e.enableZoom===!1||g!==i.NONE||(P.preventDefault(),e.dispatchEvent(xR),gA(P),e.dispatchEvent(G2))}function Ee(P){e.enabled===!1||e.enablePan===!1||dA(P)}function Xe(P){switch(qA(P),S.length){case 1:switch(e.touches.ONE){case Ir.ROTATE:if(e.enableRotate===!1)return;mA(),g=i.TOUCH_ROTATE;break;case Ir.PAN:if(e.enablePan===!1)return;vA(),g=i.TOUCH_PAN;break;default:g=i.NONE}break;case 2:switch(e.touches.TWO){case Ir.DOLLY_PAN:if(e.enableZoom===!1&&e.enablePan===!1)return;WA(),g=i.TOUCH_DOLLY_PAN;break;case Ir.DOLLY_ROTATE:if(e.enableZoom===!1&&e.enableRotate===!1)return;$A(),g=i.TOUCH_DOLLY_ROTATE;break;default:g=i.NONE}break;default:g=i.NONE}g!==i.NONE&&e.dispatchEvent(xR)}function at(P){switch(qA(P),g){case i.TOUCH_ROTATE:if(e.enableRotate===!1)return;zA(P),e.update();break;case i.TOUCH_PAN:if(e.enablePan===!1)return;Se(P),e.update();break;case i.TOUCH_DOLLY_PAN:if(e.enableZoom===!1&&e.enablePan===!1)return;V(P),e.update();break;case i.TOUCH_DOLLY_ROTATE:if(e.enableZoom===!1&&e.enableRotate===!1)return;xA(P),e.update();break;default:g=i.NONE}}function T(P){e.enabled!==!1&&P.preventDefault()}function J(P){S.push(P)}function hA(P){delete G[P.pointerId];for(let SA=0;SA<S.length;SA++)if(S[SA].pointerId==P.pointerId){S.splice(SA,1);return}}function qA(P){let SA=G[P.pointerId];SA===void 0&&(SA=new eA,G[P.pointerId]=SA),SA.set(P.pageX,P.pageY)}function bA(P){const SA=P.pointerId===S[0].pointerId?S[1]:S[0];return G[SA.pointerId]}e.domElement.addEventListener("contextmenu",T),e.domElement.addEventListener("pointerdown",kA),e.domElement.addEventListener("pointercancel",HA),e.domElement.addEventListener("wheel",Ce,{passive:!1}),this.update()}};const GiA="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/";class MiA{constructor(A,e,i,g,I=null){this.controller=e,this.handModel=A,this.bones=[],I===null&&(I=new OQ,I.setPath(i||GiA)),I.load(`${g}.glb`,o=>{const s=o.scene.children[0];this.handModel.add(s),s.layers.mask=this.handModel.layers.mask;const C=s.getObjectByProperty("type","SkinnedMesh");C.frustumCulled=!1,C.castShadow=!0,C.receiveShadow=!0,["wrist","thumb-metacarpal","thumb-phalanx-proximal","thumb-phalanx-distal","thumb-tip","index-finger-metacarpal","index-finger-phalanx-proximal","index-finger-phalanx-intermediate","index-finger-phalanx-distal","index-finger-tip","middle-finger-metacarpal","middle-finger-phalanx-proximal","middle-finger-phalanx-intermediate","middle-finger-phalanx-distal","middle-finger-tip","ring-finger-metacarpal","ring-finger-phalanx-proximal","ring-finger-phalanx-intermediate","ring-finger-phalanx-distal","ring-finger-tip","pinky-finger-metacarpal","pinky-finger-phalanx-proximal","pinky-finger-phalanx-intermediate","pinky-finger-phalanx-distal","pinky-finger-tip"].forEach(a=>{const r=s.getObjectByName(a);r!==void 0?r.jointName=a:console.warn(`Couldn't find ${a} in ${g} hand mesh`),this.bones.push(r)})})}updateMesh(){const A=this.controller.joints;for(let e=0;e<this.bones.length;e++){const i=this.bones[e];if(i){const g=A[i.jointName];if(g.visible){const I=g.position;i.position.copy(I),i.quaternion.copy(g.quaternion)}}}}}const RiA=.01,UiA="index-finger-tip";class NiA extends fA{constructor(A,e=null){super(),this.controller=A,this.motionController=null,this.envMap=null,this.loader=e,this.mesh=null,A.addEventListener("connected",i=>{const g=i.data;g.hand&&!this.motionController&&(this.xrInputSource=g,this.motionController=new MiA(this,A,this.path,g.handedness,this.loader))}),A.addEventListener("disconnected",()=>{this.clear(),this.motionController=null})}updateMatrixWorld(A){super.updateMatrixWorld(A),this.motionController&&this.motionController.updateMesh()}getPointerPosition(){const A=this.controller.joints[UiA];return A?A.position:null}intersectBoxObject(A){const e=this.getPointerPosition();if(e){const i=new iI(e,RiA),g=new Fi().setFromObject(A);return i.intersectsBox(g)}else return!1}checkButton(A){this.intersectBoxObject(A)?A.onPress():A.onClear(),A.isPressed()&&A.whilePressed()}}const FiA=.05,M2=.02,Ww=.01,R2=.02,U2=1,BE=.4,KiA=.002,yl=.01,Vw=.003,N2=.035,Ut=16,vo=12,TR=110,JiA=new y(0,1,0),viA=new y(0,0,1),qiA=.02,biA=1.5;class LiA extends fA{constructor(A,e){super(),this.hand=A,this.controller=e,this.motionController=null,this.envMap=null,this.mesh=null,this.pointerGeometry=null,this.pointerMesh=null,this.pointerObject=null,this.pinched=!1,this.attached=!1,this.cursorObject=null,this.raycaster=null,this._onConnected=this._onConnected.bind(this),this._onDisconnected=this._onDisconnected.bind(this),this.hand.addEventListener("connected",this._onConnected),this.hand.addEventListener("disconnected",this._onDisconnected)}_onConnected(A){const e=A.data;e.hand&&(this.visible=!0,this.xrInputSource=e,this.createPointer())}_onDisconnected(){this.visible=!1,this.xrInputSource=null,this.pointerGeometry&&this.pointerGeometry.dispose(),this.pointerMesh&&this.pointerMesh.material&&this.pointerMesh.material.dispose(),this.clear()}_drawVerticesRing(A,e,i){const g=e.clone();for(let I=0;I<Ut;I++){g.applyAxisAngle(viA,Math.PI*2/Ut);const o=i*Ut+I;A[3*o]=g.x,A[3*o+1]=g.y,A[3*o+2]=g.z}}_updatePointerVertices(A){const e=this.pointerGeometry.attributes.position.array,i=new y(KiA,0,-1*(N2-A));this._drawVerticesRing(e,i,0);const g=new y(Math.sin(Math.PI*TR/180)*A,Math.cos(Math.PI*TR/180)*A,0);for(let a=0;a<vo;a++)this._drawVerticesRing(e,g,a+1),g.applyAxisAngle(JiA,Math.PI*TR/180/(vo*-2));const I=Ut*(1+vo),o=Ut*(1+vo)+1,s=new y(0,0,-1*(N2-A));e[I*3]=s.x,e[I*3+1]=s.y,e[I*3+2]=s.z;const C=new y(0,0,A);e[o*3]=C.x,e[o*3+1]=C.y,e[o*3+2]=C.z,this.pointerGeometry.setAttribute("position",new ae(e,3))}createPointer(){let A,e;const i=new Array(((vo+1)*Ut+2)*3).fill(0),g=[];for(this.pointerGeometry=new le,this.pointerGeometry.setAttribute("position",new ae(i,3)),this._updatePointerVertices(yl),A=0;A<vo;A++){for(e=0;e<Ut-1;e++)g.push(A*Ut+e,A*Ut+e+1,(A+1)*Ut+e),g.push(A*Ut+e+1,(A+1)*Ut+e+1,(A+1)*Ut+e);g.push((A+1)*Ut-1,A*Ut,(A+2)*Ut-1),g.push(A*Ut,(A+1)*Ut,(A+2)*Ut-1)}const I=Ut*(1+vo),o=Ut*(1+vo)+1;for(A=0;A<Ut-1;A++)g.push(I,A+1,A),g.push(o,A+Ut*vo,A+Ut*vo+1);g.push(I,0,Ut-1),g.push(o,Ut*(vo+1)-1,Ut*vo);const s=new rt;s.transparent=!0,s.opacity=BE,this.pointerGeometry.setIndex(g),this.pointerMesh=new uA(this.pointerGeometry,s),this.pointerMesh.position.set(0,0,-1*yl),this.pointerObject=new fA,this.pointerObject.add(this.pointerMesh),this.raycaster=new Ur;const C=new Wo(qiA,10,10),a=new rt;a.transparent=!0,a.opacity=BE,this.cursorObject=new uA(C,a),this.pointerObject.add(this.cursorObject),this.add(this.pointerObject),this.pointerObject.layers.mask=this.layers.mask,this.pointerMesh.layers.mask=this.layers.mask}_updateRaycaster(){if(this.raycaster){const A=this.pointerObject.matrixWorld,e=new NA;e.identity().extractRotation(A),this.raycaster.ray.origin.setFromMatrixPosition(A),this.raycaster.ray.direction.set(0,0,-1).applyMatrix4(e)}}_updatePointer(){this.pointerObject.visible=this.controller.visible;const A=this.hand.joints["index-finger-tip"],e=this.hand.joints["thumb-tip"],i=A.position.distanceTo(e.position),g=A.position.clone().add(e.position).multiplyScalar(.5);this.pointerObject.position.copy(g),this.pointerObject.quaternion.copy(this.controller.quaternion),this.pinched=i<=M2;const I=(i-Ww)/(FiA-Ww),o=(i-Ww)/(M2-Ww);if(I>1)this._updatePointerVertices(yl),this.pointerMesh.position.set(0,0,-1*yl),this.pointerMesh.material.opacity=BE;else if(I>0){const s=(yl-Vw)*I+Vw;this._updatePointerVertices(s),o<1?(this.pointerMesh.position.set(0,0,-1*s-(1-o)*R2),this.pointerMesh.material.opacity=BE+(1-o)*(U2-BE)):(this.pointerMesh.position.set(0,0,-1*s),this.pointerMesh.material.opacity=BE)}else this._updatePointerVertices(Vw),this.pointerMesh.position.set(0,0,-1*Vw-R2),this.pointerMesh.material.opacity=U2;this.cursorObject.material.opacity=this.pointerMesh.material.opacity}updateMatrixWorld(A){super.updateMatrixWorld(A),this.pointerGeometry&&(this._updatePointer(),this._updateRaycaster())}isPinched(){return this.pinched}setAttached(A){this.attached=A}isAttached(){return this.attached}intersectObject(A,e=!0){if(this.raycaster)return this.raycaster.intersectObject(A,e)}intersectObjects(A,e=!0){if(this.raycaster)return this.raycaster.intersectObjects(A,e)}checkIntersections(A,e=!1){if(this.raycaster&&!this.attached){const i=this.raycaster.intersectObjects(A,e),g=new y(0,0,-1);if(i.length>0){const I=i[0].distance;this.cursorObject.position.copy(g.multiplyScalar(I))}else this.cursorObject.position.copy(g.multiplyScalar(biA))}}setCursor(A){const e=new y(0,0,-1);this.raycaster&&!this.attached&&this.cursorObject.position.copy(e.multiplyScalar(A))}dispose(){this._onDisconnected(),this.hand.removeEventListener("connected",this._onConnected),this.hand.removeEventListener("disconnected",this._onDisconnected)}}const Ci={Handedness:Object.freeze({NONE:"none",LEFT:"left",RIGHT:"right"}),ComponentState:Object.freeze({DEFAULT:"default",TOUCHED:"touched",PRESSED:"pressed"}),ComponentProperty:Object.freeze({BUTTON:"button",X_AXIS:"xAxis",Y_AXIS:"yAxis",STATE:"state"}),ComponentType:Object.freeze({TRIGGER:"trigger",SQUEEZE:"squeeze",TOUCHPAD:"touchpad",THUMBSTICK:"thumbstick",BUTTON:"button"}),ButtonTouchThreshold:.05,AxisTouchThreshold:.1,VisualResponseProperty:Object.freeze({TRANSFORM:"transform",VISIBILITY:"visibility"})};async function F2(t){const A=await fetch(t);if(A.ok)return A.json();throw new Error(A.statusText)}async function xiA(t){if(!t)throw new Error("No basePath supplied");return await F2(`${t}/profilesList.json`)}async function TiA(t,A,e=null,i=!0){if(!t)throw new Error("No xrInputSource supplied");if(!A)throw new Error("No basePath supplied");const g=await xiA(A);let I;if(t.profiles.some(C=>{const a=g[C];return a&&(I={profileId:C,profilePath:`${A}/${a.path}`,deprecated:!!a.deprecated}),!!I}),!I){if(!e)throw new Error("No matching profile name found");const C=g[e];if(!C)throw new Error(`No matching profile name found and default profile "${e}" missing.`);I={profileId:e,profilePath:`${A}/${C.path}`,deprecated:!!C.deprecated}}const o=await F2(I.profilePath);let s;if(i){let C;if(t.handedness==="any"?C=o.layouts[Object.keys(o.layouts)[0]]:C=o.layouts[t.handedness],!C)throw new Error(`No matching handedness, ${t.handedness}, in profile ${I.profileId}`);C.assetPath&&(s=I.profilePath.replace("profile.json",C.assetPath))}return{profile:o,assetPath:s}}const YiA={xAxis:0,yAxis:0,button:0,state:Ci.ComponentState.DEFAULT};function HiA(t=0,A=0){let e=t,i=A;if(Math.sqrt(t*t+A*A)>1){const g=Math.atan2(A,t);e=Math.cos(g),i=Math.sin(g)}return{normalizedXAxis:e*.5+.5,normalizedYAxis:i*.5+.5}}class OiA{constructor(A){this.componentProperty=A.componentProperty,this.states=A.states,this.valueNodeName=A.valueNodeName,this.valueNodeProperty=A.valueNodeProperty,this.valueNodeProperty===Ci.VisualResponseProperty.TRANSFORM&&(this.minNodeName=A.minNodeName,this.maxNodeName=A.maxNodeName),this.value=0,this.updateFromComponent(YiA)}updateFromComponent({xAxis:A,yAxis:e,button:i,state:g}){const{normalizedXAxis:I,normalizedYAxis:o}=HiA(A,e);switch(this.componentProperty){case Ci.ComponentProperty.X_AXIS:this.value=this.states.includes(g)?I:.5;break;case Ci.ComponentProperty.Y_AXIS:this.value=this.states.includes(g)?o:.5;break;case Ci.ComponentProperty.BUTTON:this.value=this.states.includes(g)?i:0;break;case Ci.ComponentProperty.STATE:this.valueNodeProperty===Ci.VisualResponseProperty.VISIBILITY?this.value=this.states.includes(g):this.value=this.states.includes(g)?1:0;break;default:throw new Error(`Unexpected visualResponse componentProperty ${this.componentProperty}`)}}}class _iA{constructor(A,e){if(!A||!e||!e.visualResponses||!e.gamepadIndices||Object.keys(e.gamepadIndices).length===0)throw new Error("Invalid arguments supplied");this.id=A,this.type=e.type,this.rootNodeName=e.rootNodeName,this.touchPointNodeName=e.touchPointNodeName,this.visualResponses={},Object.keys(e.visualResponses).forEach(i=>{const g=new OiA(e.visualResponses[i]);this.visualResponses[i]=g}),this.gamepadIndices=Object.assign({},e.gamepadIndices),this.values={state:Ci.ComponentState.DEFAULT,button:this.gamepadIndices.button!==void 0?0:void 0,xAxis:this.gamepadIndices.xAxis!==void 0?0:void 0,yAxis:this.gamepadIndices.yAxis!==void 0?0:void 0}}get data(){return{id:this.id,...this.values}}updateFromGamepad(A){if(this.values.state=Ci.ComponentState.DEFAULT,this.gamepadIndices.button!==void 0&&A.buttons.length>this.gamepadIndices.button){const e=A.buttons[this.gamepadIndices.button];this.values.button=e.value,this.values.button=this.values.button<0?0:this.values.button,this.values.button=this.values.button>1?1:this.values.button,e.pressed||this.values.button===1?this.values.state=Ci.ComponentState.PRESSED:(e.touched||this.values.button>Ci.ButtonTouchThreshold)&&(this.values.state=Ci.ComponentState.TOUCHED)}this.gamepadIndices.xAxis!==void 0&&A.axes.length>this.gamepadIndices.xAxis&&(this.values.xAxis=A.axes[this.gamepadIndices.xAxis],this.values.xAxis=this.values.xAxis<-1?-1:this.values.xAxis,this.values.xAxis=this.values.xAxis>1?1:this.values.xAxis,this.values.state===Ci.ComponentState.DEFAULT&&Math.abs(this.values.xAxis)>Ci.AxisTouchThreshold&&(this.values.state=Ci.ComponentState.TOUCHED)),this.gamepadIndices.yAxis!==void 0&&A.axes.length>this.gamepadIndices.yAxis&&(this.values.yAxis=A.axes[this.gamepadIndices.yAxis],this.values.yAxis=this.values.yAxis<-1?-1:this.values.yAxis,this.values.yAxis=this.values.yAxis>1?1:this.values.yAxis,this.values.state===Ci.ComponentState.DEFAULT&&Math.abs(this.values.yAxis)>Ci.AxisTouchThreshold&&(this.values.state=Ci.ComponentState.TOUCHED)),Object.values(this.visualResponses).forEach(e=>{e.updateFromComponent(this.values)})}}class PiA{constructor(A,e,i){if(!A)throw new Error("No xrInputSource supplied");if(!e)throw new Error("No profile supplied");this.xrInputSource=A,this.assetUrl=i,this.id=e.profileId,this.layoutDescription=e.layouts[A.handedness],this.components={},Object.keys(this.layoutDescription.components).forEach(g=>{const I=this.layoutDescription.components[g];this.components[g]=new _iA(g,I)}),this.updateFromGamepad()}get gripSpace(){return this.xrInputSource.gripSpace}get targetRaySpace(){return this.xrInputSource.targetRaySpace}get data(){const A=[];return Object.values(this.components).forEach(e=>{A.push(e.data)}),A}updateFromGamepad(){Object.values(this.components).forEach(A=>{A.updateFromGamepad(this.xrInputSource.gamepad)})}}const jiA="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",WiA="generic-trigger";class ViA extends fA{constructor(){super(),this.motionController=null,this.envMap=null}setEnvironmentMap(A){return this.envMap==A?this:(this.envMap=A,this.traverse(e=>{e.isMesh&&(e.material.envMap=this.envMap,e.material.needsUpdate=!0)}),this)}updateMatrixWorld(A){super.updateMatrixWorld(A),this.motionController&&(this.motionController.updateFromGamepad(),Object.values(this.motionController.components).forEach(e=>{Object.values(e.visualResponses).forEach(i=>{const{valueNode:g,minNode:I,maxNode:o,value:s,valueNodeProperty:C}=i;g&&(C===Ci.VisualResponseProperty.VISIBILITY?g.visible=s:C===Ci.VisualResponseProperty.TRANSFORM&&(g.quaternion.slerpQuaternions(I.quaternion,o.quaternion,s),g.position.lerpVectors(I.position,o.position,s)))})}))}}function ziA(t,A){Object.values(t.components).forEach(e=>{const{type:i,touchPointNodeName:g,visualResponses:I}=e;if(i===Ci.ComponentType.TOUCHPAD)if(e.touchPointNode=A.getObjectByName(g),e.touchPointNode){const o=new Wo(.001),s=new rt({color:255}),C=new uA(o,s);e.touchPointNode.add(C)}else console.warn(`Could not find touch dot, ${e.touchPointNodeName}, in touchpad component ${e.id}`);Object.values(I).forEach(o=>{const{valueNodeName:s,minNodeName:C,maxNodeName:a,valueNodeProperty:r}=o;if(r===Ci.VisualResponseProperty.TRANSFORM){if(o.minNode=A.getObjectByName(C),o.maxNode=A.getObjectByName(a),!o.minNode){console.warn(`Could not find ${C} in the model`);return}if(!o.maxNode){console.warn(`Could not find ${a} in the model`);return}}o.valueNode=A.getObjectByName(s),o.valueNode||console.warn(`Could not find ${s} in the model`)})})}function K2(t,A){ziA(t.motionController,A),t.envMap&&A.traverse(e=>{e.isMesh&&(e.material.envMap=t.envMap,e.material.needsUpdate=!0)}),t.layers.mask!=0&&A.traverse(e=>{e.layers.mask=t.layers.mask}),t.add(A)}class ZiA{constructor(A=null){this.gltfLoader=A,this.path=jiA,this._assetCache={},this.gltfLoader||(this.gltfLoader=new OQ)}createControllerModel(A){const e=new ViA;let i=null;return A.addEventListener("connected",g=>{const I=g.data;I.targetRayMode!=="tracked-pointer"||!I.gamepad||TiA(I,this.path,WiA).then(({profile:o,assetPath:s})=>{e.motionController=new PiA(I,o,s);const C=this._assetCache[e.motionController.assetUrl];if(C)i=C.scene.clone(),K2(e,i);else{if(!this.gltfLoader)throw new Error("GLTFLoader not set.");this.gltfLoader.setPath(""),this.gltfLoader.load(e.motionController.assetUrl,a=>{this._assetCache[e.motionController.assetUrl]=a,i=a.scene.clone(),K2(e,i)},null,()=>{throw new Error(`Asset ${e.motionController.assetUrl} missing or malformed.`)})}}).catch(o=>{console.warn(o)})}),A.addEventListener("disconnected",()=>{e.motionController=null,e.remove(i),i=null}),e}}const Sl=CA("debugavatar");class zw{constructor(A,e,i,g){n(this,"root"),n(this,"head"),n(this,"leftHand"),n(this,"rigthHand");var I;this.root=A,this.head=e,this.leftHand=i,this.rigthHand=g,(I=this.root)==null||I.traverse(o=>o.layers.set(2))}get isValid(){return this.head!==null&&this.head!==void 0}}class Zw{constructor(){n(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 i=null;if(typeof e=="string"){if(i=await this.loadAvatar(A,e),!i){const I=new Ys;i=iA.instantiate(mQ(e,A.scene),I)}}else i=e;if(!i)return null;const g=this.findAvatar(i);return g.isValid?(Sl&&console.log("[Custom Avatar] valid config",e,Sl?g:""),g):(console.warn("[Custom Avatar] config isn't valid",e,Sl?g:""),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(Sl&&console.log("[Custom Avatar] "+e+", loading..."),e.endsWith(".glb")||(e+=".glb"),this.avatarRegistryUrl===null){const g=await fetch("./"+e);let I=null;if(g.ok){const s=await g.blob();s&&(I=await s.arrayBuffer())}if(!I&&(I=await vG(e,e,0,"no url here go away",!0),!I))return null;const o=await rs().parseSync(A,I,null,0);return o?.scene??null}const i=new OQ;return ol(i,A),new Promise((g,I)=>{const o=this.avatarRegistryUrl+"/"+e;i.load(o,async s=>{await rs().createBuiltinComponents(A,o,s,null,void 0),g(s.scene)},s=>{Sl&&console.log("[Custom Avatar] "+s.loaded/s.total*100+"% loaded of "+s.total/1024+"kB")},s=>{console.error("[Custom Avatar] Error when loading: "+s),g(null)})})}cacheModel(A,e){}findAvatar(A){const e=A;let i=e;i.children.length==1&&(i=A.children[0]);let g=this.findAvatarPart(i,["head"]);const I=this.findAvatarPart(i,["left","hand"]),o=this.findAvatarPart(i,["right","hand"]);if(!g){g=e;const s=new y;new Fi().setFromObject(g).getSize(s);const C=Math.max(s.x,s.y,s.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+C+" meters! Should be < 0.3m"),C>.3&&g.scale.multiplyScalar(1/C*.3)}return new zw(e,g,I,o)}findAvatarPart(A,e){const i=A.name.toLowerCase();let g=!0;for(const I of e){if(!g)break;i.indexOf(I)===-1&&(g=!1)}if(g)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 XiA=Object.defineProperty,$iA=Object.getOwnPropertyDescriptor,AgA=(t,A,e,i)=>{for(var g=i>1?void 0:i?$iA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&XiA(A,e,g),g};const QE=CA("debugflags");var fi=(t=>(t[t.Never=0]="Never",t[t.Browser=1]="Browser",t[t.AR=2]="AR",t[t.VR=4]="VR",t[t.FirstPerson=8]="FirstPerson",t[t.ThirdPerson=16]="ThirdPerson",t[t.All=4294967295]="All",t))(fi||{});const J2=class{constructor(){n(this,"Mask",17)}Has(t){return(this.Mask&t)!==0}Set(t){QE&&console.warn("Set XR flag state to",t),this.Mask=t,to.Apply()}Enable(t){this.Mask|=t,to.Apply()}Disable(t){this.Mask&=~t,to.Apply()}Toggle(t){this.Mask^=t,to.Apply()}EnableAll(){this.Mask=-1,to.Apply()}DisableAll(){this.Mask=0,to.Apply()}};let eo=J2;n(eo,"Global",new J2);var fl;const Ca=(fl=class extends JA{constructor(){super(...arguments),n(this,"visibleIn")}static Apply(){for(const t of this.registry)t.UpdateVisible(eo.Global)}awake(){Ca.registry.push(this)}onEnable(){Ca.firstApply?this.UpdateVisible(eo.Global):(Ca.firstApply=!0,Ca.Apply())}onDestroy(){const t=Ca.registry.indexOf(this);t>=0&&Ca.registry.splice(t,1)}get isOn(){return this.gameObject.visible}UpdateVisible(t=null){let A;const e=t;e&&typeof e=="number"&&(console.assert(typeof e=="number","XRFlag.UpdateVisible: state must be a number",e),QE&&console.log(e),Ca.buffer.Mask=e,t=Ca.buffer);const i=t;if(i?(QE&&console.warn(this.name,"use passed in mask",i.Mask,this.visibleIn),A=i.Has(this.visibleIn)):(QE&&console.log(this.name,"use global mask"),eo.Global.Has(this.visibleIn)),A!==void 0)if(A)QE&&console.log(this.name,"is visible",this.gameObject.uuid),iA.setActive(this.gameObject,!0);else{if(QE&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},n(fl,"registry",[]),n(fl,"firstApply"),n(fl,"buffer",new eo),fl);let to=Ca;AgA([w()],to.prototype,"visibleIn",2);const Sn=CA("debugavatar"),Zs=class extends JA{constructor(){super(...arguments),n(this,"connectionId"),n(this,"avatar")}static getAvatar(t){return t>=0&&t<Zs.instances.length?Zs.instances[t]:null}static onAvatarMarkerCreated(t){return Zs._onNewAvatarMarkerAdded.push(t),t}static onAvatarMarkerDestroyed(t){return Zs._onAvatarMarkerDestroyed.push(t),t}awake(){Zs.instances.push(this),Sn&&console.log(this);for(const t of Zs._onNewAvatarMarkerAdded)t({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){Zs.instances.splice(Zs.instances.indexOf(this),1);for(const t of Zs._onAvatarMarkerDestroyed)t({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}setVisible(t){this.avatar&&("setVisible"in this.avatar?this.avatar.setVisible(t):iA.setActive(this.avatar,t))}};let Wg=Zs;n(Wg,"instances",[]),n(Wg,"_onNewAvatarMarkerAdded",[]),n(Wg,"_onAvatarMarkerDestroyed",[]);const Xw=class{constructor(t,A,e){n(this,"_isVisible",!0),n(this,"guid"),n(this,"root",null),n(this,"head",null),n(this,"handLeft",null),n(this,"handRight",null),n(this,"lastUpdate",-1),n(this,"isLocalAvatar",!1),n(this,"flags",null),n(this,"headScale",new y(1,1,1)),n(this,"handLeftScale",new y(1,1,1)),n(this,"handRightScale",new y(1,1,1)),n(this,"webxr"),n(this,"lastAvatarId",null),n(this,"hasAvatarOverride",!1),n(this,"context"),n(this,"avatarMarker",null),n(this,"_headTarget",new fA),n(this,"_handLeftTarget",new fA),n(this,"_handRightTarget",new fA),n(this,"_canInterpolate",!1),this.context=t,this.guid=A,this.webxr=e,this.setupCustomAvatar(this.webxr.defaultAvatar)}setVisible(t){this._isVisible=t,this.updateVisibility()}get isWebXRAvatar(){return!0}updateFlags(){if(!this.flags)return;let t=this.isLocalAvatar?fi.FirstPerson:fi.ThirdPerson;this.context.isInVR?t|=fi.VR:this.context.isInAR?t|=fi.AR:t|=fi.Browser;for(const A of this.flags)A.gameObject.visible=!0,A.UpdateVisible(t)}async setAvatarOverride(t){return this.hasAvatarOverride=t!==null,this.hasAvatarOverride&&this.lastAvatarId!==t&&(this.lastAvatarId=t,t!=null&&t.length>0)?await this.setupCustomAvatar(t):null}tryUpdate(t,A){if(t.guid===this.guid&&(this.lastAvatarId!==t.avatarId&&t.avatarId&&t.avatarId.length>0&&(this.lastAvatarId=t.avatarId,this.setupCustomAvatar(t.avatarId)),this.lastUpdate=t.time,this.head)){const e=this.webxr.IsInAR?Ps.Handheld:Ps.Headset,i=this.head;this.context.players.setPlayerView(t.guid,i,e),Xg.markDirty(this.head),this._canInterpolate=!0;const g=this.isLocalAvatar?this.head:this._headTarget;if(g.position.set(t.position.x,t.position.y,t.position.z),g.quaternion.set(t.rotation.x,t.rotation.y,t.rotation.z,t.rotation.w),g.scale.set(t.scale,t.scale,t.scale),g.scale.multiply(this.headScale),this.handLeft){const I=this.isLocalAvatar?this.handLeft:this._handLeftTarget;I.position.set(t.posLeftHand.x,t.posLeftHand.y,t.posLeftHand.z),I.quaternion.set(t.rotLeftHand._x,t.rotLeftHand._y,t.rotLeftHand._z,t.rotLeftHand._w),I.quaternion.multiply(Xw.invertRotation),I.scale.set(t.scale,t.scale,t.scale),I.scale.multiply(this.handLeftScale),Xg.markDirty(this.handLeft)}if(this.handRight){const I=this.isLocalAvatar?this.handRight:this._handRightTarget;I.position.set(t.posRightHand.x,t.posRightHand.y,t.posRightHand.z),I.quaternion.set(t.rotRightHand._x,t.rotRightHand._y,t.rotRightHand._z,t.rotRightHand._w),I.quaternion.multiply(Xw.invertRotation),I.scale.set(t.scale,t.scale,t.scale),I.scale.multiply(this.handRightScale),Xg.markDirty(this.handRight)}}}update(){if(this.isLocalAvatar||!this._canInterpolate)return;const t=this.context.time.deltaTime/.1;this.head&&(this.head.position.lerp(this._headTarget.position,t),this.head.quaternion.slerp(this._headTarget.quaternion,t),this.head.scale.lerp(this._headTarget.scale,t)),this.handLeft&&this._handLeftTarget&&(this.handLeft.position.lerp(this._handLeftTarget.position,t),this.handLeft.quaternion.slerp(this._handLeftTarget.quaternion,t),this.handLeft.scale.lerp(this._handLeftTarget.scale,t)),this.handRight&&this._handRightTarget&&(this.handRight.position.lerp(this._handRightTarget.position,t),this.handRight.quaternion.slerp(this._handRightTarget.quaternion,t),this.handRight.scale.lerp(this._handRightTarget.scale,t))}destroy(){var t,A;Sn&&console.log("Destroy avatar",this.guid),(t=this.root)==null||t.removeFromParent(),(A=this.avatarMarker)==null||A.destroy(),this.lastAvatarId=null,this.head&&cI.Remove(this.context,this.head)}updateVisibility(){const t=this.root;t&&iA.setActive(t,this._isVisible)}async setupCustomAvatar(t){var A,e,i;if(Sn&&console.log("LOAD",t,this),!t||typeof t=="string"&&t.length<=0)return!1;this.head&&cI.Remove(this.context,this.head);const g=t;if(g?.loadAssetAsync!==void 0){await g.loadAssetAsync();const o=g.asset;iA.setActive(o,!1),t=iA.instantiate(o),iA.setActive(t,!0)}Sn&&console.log(t);const I=await Xw.loader.getOrCreateNewAvatarInstance(this.context,t);if(Sn&&console.log(I,I?.isValid,this.lastAvatarId,t),I!=null&&I.isValid){if(this.root=I.root,this.root.position.set(0,0,0),this.root.quaternion.set(0,0,0,1),this.root.scale.set(1,1,1),this.avatarMarker=iA.addNewComponent(this.root,Wg),this.avatarMarker.connectionId=this.guid,this.avatarMarker.avatar=this,this.head&&this.head!==I.head&&((A=this.head)==null||A.removeFromParent()),this.head=I.head,this.headScale.copy(this.head.scale),this.head&&!this.isLocalAvatar&&cI.Add(this.context,this.head,this.avatarMarker),I.leftHand&&((e=this.handLeft)==null||e.removeFromParent()),this.handLeft=I.leftHand??this.handLeft,this.handLeft?this.handLeftScale.copy(this.handLeft.scale):this.handLeftScale.set(1,1,1),I.rigthHand&&((i=this.handRight)==null||i.removeFromParent()),this.handRight=I.rigthHand??this.handRight,this.handRight?this.handRightScale.copy(this.handRight.scale):this.handRightScale.set(1,1,1),this.context.scene.add(this.root),this.flags==null&&(this.flags=[]),this.flags.length=0,this.flags.push(...iA.getComponentsInChildren(this.root,to)),this.flags.length<=0&&this.head){const o=iA.addNewComponent(this.head,to);o.visibleIn=fi.ThirdPerson|fi.VR,this.flags.push(o),Sn&&console.log("Added flag to head: "+o.visibleIn,this.head.name)}return Sn&&console.log("[Avatar], is Local? ",this.isLocalAvatar,this.root),this.updateFlags(),this.updateVisibility(),!0}else return Sn&&console.warn("build avatar failed"),!1}};let fn=Xw;n(fn,"loader",new Zw),n(fn,"invertRotation",new UA().setFromAxisAngle(new y(0,1,0),Math.PI));class cI{static Add(A,e,i=null){if(e){for(const g of this.Pois)if(g.obj===e)return;this.Pois.push({obj:e,avatar:i}),this.LastChangeTime=A.time.time}}static Remove(A,e){var i;if(e){for(const g of this.Pois)if(g.obj===e){this.Pois.splice(this.Pois.indexOf(g),1),this.LastChangeTime=A?.time.time??((i=qe.Current)==null?void 0:i.time.time);return}}}}n(cI,"Pois",[]),n(cI,"LastChangeTime",0);class egA{constructor(){n(this,"guid"),n(this,"position",new y)}}class ml extends JA{constructor(){super(...arguments),n(this,"target",null),n(this,"avatar",null),n(this,"_model",null),n(this,"_targetModel",new egA),n(this,"_currentTargetObject",null),n(this,"_lastUpdateTime",0),n(this,"_lookDuration",0),n(this,"_lastPoiChangedTime",0)}set controlledTarget(A){this.target=A;const e=z.get("MoveRandom");if(e&&this.target){const i=iA.getComponent(this.target,e);i&&i.destroy()}}awake(){if(this.avatar=iA.getComponentInParent(this.gameObject,Wg),this.avatar){const A=iA.getComponentInParent(this.gameObject,Wg);this._model=new rD(this.context.connection,this.guid),A!=null&&A.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",A=>{var e;this.target&&A&&A.guid===((e=this.avatar)==null?void 0:e.guid)&&ui(this.target,A.position)})}update(){var A;if((!this.context.connection.isConnected||(A=this._model)!=null&&A.hasOwnership)&&(cI.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=cI.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){const e=he(this._currentTargetObject);ui(this.target,e),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(e))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;const A=cI.Pois;if(A.length>0){const e=A[Math.floor(Math.random()*A.length)];if(e&&e.obj){if(e.avatar&&e.avatar===this.avatar)return;this._currentTargetObject=e.obj}}}}}class EE extends JA{constructor(){super(...arguments),n(this,"canGrab",!0)}onPointerClick(A){}}class hE extends JA{constructor(){super(...arguments),n(this,"isUsed",!0),n(this,"usedBy",null)}}var ng=(t=>(t[t.Average=0]="Average",t[t.Multiply=1]="Multiply",t[t.Minimum=2]="Minimum",t[t.Maximum=3]="Maximum",t))(ng||{}),$w=(t=>(t[t.Discrete=0]="Discrete",t[t.Continuous=1]="Continuous",t))($w||{}),mi=(t=>(t[t.None=0]="None",t[t.FreezePositionX=2]="FreezePositionX",t[t.FreezePositionY=4]="FreezePositionY",t[t.FreezePositionZ=8]="FreezePositionZ",t[t.FreezePosition=14]="FreezePosition",t[t.FreezeRotationX=16]="FreezeRotationX",t[t.FreezeRotationY=32]="FreezeRotationY",t[t.FreezeRotationZ=64]="FreezeRotationZ",t[t.FreezeRotation=112]="FreezeRotation",t[t.FreezeAll=126]="FreezeAll",t))(mi||{}),cE=(t=>(t[t.None=0]="None",t[t.X=2]="X",t[t.Y=4]="Y",t[t.Z=8]="Z",t[t.All=-1]="All",t))(cE||{});const mg=function(t,A){return function(e,i,g){tgA(e,i,g,t,A)}};function tgA(t,A,e,i,g){if(!g&&!i&&!t.onValidate)return;if(e!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",t,A,e),di("Invalid usage of validate decorator. Only fields can be validated. Property: "+A,So.Error);return}let I="";if(typeof A=="string"?I=A:I=A.name,t.__internalAwake){const o=Symbol(I),s=t.__internalAwake;t.__internalAwake=function(){var C;if(!this.onValidate){Ye()&&console.warn('Usage of @validate decorate detected but there is no onValidate method in your class: "'+((C=t.constructor)==null?void 0:C.name)+'"');return}if(this[o]===void 0){this[o]=this[I];const a=this[I];if(a instanceof eA||a instanceof y||a instanceof ie||a instanceof UA){const r=this[I];ak(r,()=>{this.onValidate(I)})}Object.defineProperty(this,I,{set:function(r){var B;if(this[rG]===!0)this[o]=r;else{i?.call(this,r);const Q=this[o];this[o]=r,(B=this.onValidate)==null||B.call(this,I,Q)}},get:function(){return g?.call(this),this[o]}})}s.call(this)}}}const igA=function(t){return function(A,e,i){let g="";typeof e=="string"?g=e:g=e.name;const I=t.prototype,o=Object.getOwnPropertyDescriptor(I,g);if(!(o!=null&&o.value)){console.warn("Can not apply prefix: type does not have method named",e,t);return}const s=o.value,C=A[g];Object.defineProperty(I,g,{value:function(...a){const r=C?.call(this,...a);if(r instanceof Promise){r.then(B=>{if(B!==!1)return s.call(this,...a)});return}if(r!==!1)return s.call(this,...a)}})}};var ggA=Object.defineProperty,IgA=Object.getOwnPropertyDescriptor,qo=(t,A,e,i)=>{for(var g=i>1?void 0:i?IgA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&ggA(A,e,g),g};class ogA{constructor(A,e){n(this,"positionChanged",!1),n(this,"rotationChanged",!1),n(this,"position"),n(this,"quaternion"),n(this,"_positionKeys",["x","y","z"]),n(this,"_quaternionKeys",["_x","_y","_z","_w"]),n(this,"mute",!1),n(this,"context"),n(this,"obj"),n(this,"_positionWatch"),n(this,"_rotationWatch"),this.context=e,this.obj=A}get isDirty(){return this.positionChanged||this.rotationChanged}reset(A=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,A){if(this.position)for(const e of this._positionKeys)delete this.position[e];if(this.quaternion)for(const e of this._quaternionKeys)delete this.quaternion[e]}}syncValues(){for(const A of this._positionKeys)this.position[A]=this.obj.position[A];for(const A of this._quaternionKeys)this.quaternion[A]=this.obj.quaternion[A]}applyValues(){if(this.positionChanged&&this.position)for(const A of this._positionKeys){const e=this.position[A];e!==void 0&&(this.obj.position[A]=e)}if(this.rotationChanged&&this.quaternion)for(const A of this._quaternionKeys){const e=this.quaternion[A];e!==void 0&&(this.obj.quaternion[A]=e)}}start(A,e){this.reset(),A&&(this._positionWatch||(this._positionWatch=new Ma(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((I,o)=>{var s;if((s=this.context.physics.engine)!=null&&s.isUpdating||this.mute)return;const C=this.position[o];Math.abs(C-I)<1e-5||(this.position[o]=I,this.positionChanged=!0)})),e&&(this._rotationWatch||(this._rotationWatch=new Ma(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((I,o)=>{var s;if((s=this.context.physics.engine)!=null&&s.isUpdating||this.mute)return;const C=this.quaternion[o];Math.abs(C-I)<1e-5||(this.quaternion[o]=I,this.rotationChanged=!0)}));const i=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),g=new NA;this.obj.matrixWorld.multiplyMatrices=(I,o)=>(g.equals(I)||(this.positionChanged=!0,this.rotationChanged=!0,g.copy(I)),i(I,o))}stop(){var A,e;(A=this._positionWatch)==null||A.revoke(),(e=this._rotationWatch)==null||e.revoke()}}var YR;const HR=(YR=class extends JA{constructor(){super(...arguments),n(this,"autoMass",!0),n(this,"_mass",0),n(this,"useGravity",!0),n(this,"constraints",mi.None),n(this,"isKinematic",!1),n(this,"drag",0),n(this,"angularDrag",1),n(this,"detectCollisions",!0),n(this,"sleepThreshold",.01),n(this,"collisionDetectionMode",$w.Discrete),n(this,"_gravityScale",1),n(this,"dominanceGroup",0),n(this,"_propertiesChanged",!1),n(this,"_currentVelocity",new y),n(this,"_smoothedVelocity",new y),n(this,"_smoothedVelocityGetter",new y),n(this,"_lastPosition",new y),n(this,"_watch")}set mass(t){t!==this._mass&&(this._mass=t,this._propertiesChanged=!0,this.__didAwake&&(this.autoMass=!1))}get mass(){var t,A;return this.autoMass?((A=(t=this.context.physics.engine)==null?void 0:t.getBody(this))==null?void 0:A.mass())??-1:this._mass}get lockPositionX(){return(this.constraints&mi.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&mi.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&mi.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&mi.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&mi.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&mi.FreezeRotationZ)!==0}set lockPositionX(t){t?this.constraints|=mi.FreezePositionX:this.constraints&=~mi.FreezePositionX}set lockPositionY(t){t?this.constraints|=mi.FreezePositionY:this.constraints&=~mi.FreezePositionY}set lockPositionZ(t){t?this.constraints|=mi.FreezePositionZ:this.constraints&=~mi.FreezePositionZ}set lockRotationX(t){t?this.constraints|=mi.FreezeRotationX:this.constraints&=~mi.FreezeRotationX}set lockRotationY(t){t?this.constraints|=mi.FreezeRotationY:this.constraints&=~mi.FreezeRotationY}set lockRotationZ(t){t?this.constraints|=mi.FreezeRotationZ:this.constraints&=~mi.FreezeRotationZ}set gravityScale(t){this._gravityScale=t}get gravityScale(){return this._gravityScale}awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new ogA(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),og.LateUpdate)}onDisable(){var t,A;(t=this._watch)==null||t.stop(),(A=this.context.physics.engine)==null||A.removeBody(this)}onDestroy(){var t;(t=this.context.physics.engine)==null||t.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){for(var t,A,e,i;;)this._propertiesChanged&&(this._propertiesChanged=!1,(t=this.context.physics.engine)==null||t.updateProperties(this)),(A=this._watch)!=null&&A.isDirty?(this._watch.mute=!0,this._watch.applyValues(),(e=this.context.physics.engine)==null||e.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):(i=this._watch)==null||i.syncValues(),this.captureVelocity(),yield}teleport(t,A=!0){var e;(e=this._watch)==null||e.reset(!0),A?this.gameObject.position.set(t.x,t.y,t.z):this.setWorldPosition(t.x,t.y,t.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(t=!0){var A;(A=this.context.physics.engine)==null||A.resetForces(this,t)}resetTorques(t=!0){var A;(A=this.context.physics.engine)==null||A.resetTorques(this,t)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){var t;(t=this.context.physics.engine)==null||t.wakeup(this)}applyForce(t,A,e=!0){var i;(i=this.context.physics.engine)==null||i.addForce(this,t,e)}applyImpulse(t,A=!0){var e;(e=this.context.physics.engine)==null||e.applyImpulse(this,t,A)}setForce(t,A,e,i=!0){var g,I,o;(g=this.context.physics.engine)==null||g.resetForces(this,i),typeof t=="number"?(A??(A=0),e??(e=0),(I=this.context.physics.engine)==null||I.addForce(this,{x:t,y:A,z:e},i)):(o=this.context.physics.engine)==null||o.addForce(this,t,i)}getVelocity(){var t;const A=(t=this.context.physics.engine)==null?void 0:t.getLinearVelocity(this);return A?(this._currentVelocity.x=A.x,this._currentVelocity.y=A.y,this._currentVelocity.z=A.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(t,A,e,i=!0){var g,I;if(t instanceof y){const o=t;(g=this.context.physics.engine)==null||g.setLinearVelocity(this,o,i);return}A===void 0||e===void 0||(I=this.context.physics.engine)==null||I.setLinearVelocity(this,{x:t,y:A,z:e},i)}getAngularVelocity(){var t;const A=(t=this.context.physics.engine)==null?void 0:t.getAngularVelocity(this);return A?(this._currentVelocity.x=A.x,this._currentVelocity.y=A.y,this._currentVelocity.z=A.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setAngularVelocity(t,A,e,i=!0){var g,I;if(t instanceof y){const o=t;(g=this.context.physics.engine)==null||g.setAngularVelocity(this,o,i);return}A===void 0||e===void 0||(I=this.context.physics.engine)==null||I.setAngularVelocity(this,{x:t,y:A,z:e},i)}setTorque(t,A,e){this.setAngularVelocity(t,A,e)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(t=null){}captureVelocity(){const t=he(this.gameObject);HR.tempPosition.copy(t);const A=t.sub(this._lastPosition);this._lastPosition.copy(HR.tempPosition),this._smoothedVelocity.lerp(A,this.context.time.deltaTime/.1)}},n(YR,"tempPosition",new y),YR);let Kt=HR;qo([mg()],Kt.prototype,"autoMass",2),qo([w()],Kt.prototype,"mass",1),qo([mg(),w()],Kt.prototype,"useGravity",2),qo([mg(),w()],Kt.prototype,"constraints",2),qo([mg(),w()],Kt.prototype,"isKinematic",2),qo([mg(),w()],Kt.prototype,"drag",2),qo([mg(),w()],Kt.prototype,"angularDrag",2),qo([mg(),w()],Kt.prototype,"detectCollisions",2),qo([mg(),w()],Kt.prototype,"sleepThreshold",2),qo([mg(),w()],Kt.prototype,"collisionDetectionMode",2),qo([mg()],Kt.prototype,"_gravityScale",2),qo([mg()],Kt.prototype,"dominanceGroup",2);class io{constructor(){n(this,"bb",null),n(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}static sizeOf(){return 12}static createVec3(A,e,i,g){return A.prep(4,12),A.writeFloat32(g),A.writeFloat32(i),A.writeFloat32(e),A.offset()}}class v2{constructor(){n(this,"bb",null),n(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}position(A){return(A||new io).__init(this.bb_pos,this.bb)}rotation(A){return(A||new io).__init(this.bb_pos+12,this.bb)}scale(A){return(A||new io).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(A,e,i,g,I,o,s,C,a,r){return A.prep(4,36),A.prep(4,12),A.writeFloat32(r),A.writeFloat32(a),A.writeFloat32(C),A.prep(4,12),A.writeFloat32(s),A.writeFloat32(o),A.writeFloat32(I),A.prep(4,12),A.writeFloat32(g),A.writeFloat32(i),A.writeFloat32(e),A.offset()}}class Fa{constructor(){n(this,"bb",null),n(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}static getRootAsSyncedTransformModel(A,e){return(e||new Fa).__init(A.readInt32(A.position())+A.position(),A)}static getSizePrefixedRootAsSyncedTransformModel(A,e){return A.setPosition(A.position()+Zu),(e||new Fa).__init(A.readInt32(A.position())+A.position(),A)}guid(A){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,A):null}fast(){const A=this.bb.__offset(this.bb_pos,6);return A?!!this.bb.readInt8(this.bb_pos+A):!1}transform(A){const e=this.bb.__offset(this.bb_pos,8);return e?(A||new v2).__init(this.bb_pos+e,this.bb):null}dontSave(){const A=this.bb.__offset(this.bb_pos,10);return A?!!this.bb.readInt8(this.bb_pos+A):!1}static startSyncedTransformModel(A){A.startObject(4)}static addGuid(A,e){A.addFieldOffset(0,e,0)}static addFast(A,e){A.addFieldInt8(1,+e,0)}static addTransform(A,e){A.addFieldStruct(2,e,0)}static addDontSave(A,e){A.addFieldInt8(3,+e,0)}static endSyncedTransformModel(A){return A.endObject()}static finishSyncedTransformModelBuffer(A,e){A.finish(e)}static finishSizePrefixedSyncedTransformModelBuffer(A,e){A.finish(e,void 0,!0)}}const mn=CA("debugsync"),kl="STRS";$u(kl,Fa.getRootAsSyncedTransformModel);const Xs=new Qh;function q2(t,A,e=!0){Xs.clear();const i=Xs.createString(t);Fa.startSyncedTransformModel(Xs),Fa.addGuid(Xs,i),Fa.addFast(Xs,e);const g=A.worldPosition,I=A.worldEuler,o=A.gameObject.scale;Fa.addTransform(Xs,v2.createTransform(Xs,g.x,g.y,g.z,I.x,I.y,I.z,o.x,o.y,o.z));const s=Fa.endSyncedTransformModel(Xs);return Xs.finish(s,kl),Xs.asUint8Array()}class kn extends JA{constructor(){super(...arguments),n(this,"overridePhysics",!0),n(this,"interpolatePosition",!0),n(this,"interpolateRotation",!0),n(this,"fastMode",!1),n(this,"syncDestroy",!1),n(this,"_model",null),n(this,"_needsUpdate",!0),n(this,"rb",null),n(this,"_wasKinematic",!1),n(this,"_receivedDataBefore",!1),n(this,"_targetPosition"),n(this,"_targetRotation"),n(this,"_receivedFastUpdate",!1),n(this,"_shouldRequestOwnership",!1),n(this,"joinedRoomCallback",null),n(this,"receivedDataCallback",null),n(this,"tempEuler",new Ag),n(this,"receivedUpdate",!1),n(this,"lastWorldPos"),n(this,"lastWorldRotation")}requestOwnership(){mn&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}hasOwnership(){var A;return((A=this._model)==null?void 0:A.hasOwnership)??void 0}isOwned(){var A;return(A=this._model)==null?void 0:A.isOwned}awake(){mn&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new y,this._targetRotation=new UA,this.lastWorldPos=new y,this.lastWorldRotation=new UA,this.rb=iA.getComponentInChildren(this.gameObject,Kt),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new rD(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(Lt.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(kl,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&uL(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(Lt.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(kl,this.receivedDataCallback)}tryGetLastState(){const A=this.context.connection.tryGetState(this.guid);A&&this.onReceivedData(A)}onReceivedData(A){var e;if(!this.destroyed&&typeof A.guid=="function"&&A.guid()===this.guid){mn&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,A),this.receivedUpdate=!0,this._receivedFastUpdate=A.fast();const i=A.transform();if(i){Xg.markDirty(this.gameObject,!0);const g=i.position();g&&(this.interpolatePosition&&((e=this._targetPosition)==null||e.set(g.x(),g.y(),g.z())),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(g.x(),g.y(),g.z()));const I=i.rotation();I&&(this.tempEuler.set(I.x(),I.y(),I.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&Gk(this.gameObject,this.tempEuler))}this._receivedDataBefore=!0}}onEnable(){this.lastWorldPos.copy(this.worldPosition),this.lastWorldRotation.copy(this.worldQuaternion),this._needsUpdate=!0,this._model&&this._model.updateIsOwned()}onDisable(){this._model&&this._model.freeOwnership()}onBeforeRender(){if(!this.activeAndEnabled||!this.context.connection.isConnected)return;if(!this.context.connection.isInRoom||!this._model){mn&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());const A=this.worldPosition,e=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){const I=A.distanceTo(this.lastWorldPos),o=e.angleTo(this.lastWorldRotation),s=this._model.hasOwnership||this.fastMode?1e-4:.001;(I>s||o>s)&&(this._model.hasOwnership?this._needsUpdate=!0:(mn&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastWorldPos),this.worldPosition=this.lastWorldPos,A.copy(this.lastWorldPos),this.worldQuaternion=this.lastWorldRotation,e.copy(this.lastWorldRotation),Xg.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const I=this._receivedFastUpdate||this.fastMode?.5:.3;let o=!1;if(this.interpolatePosition&&this._targetPosition){const s=this.worldPosition;s.lerp(this._targetPosition,I),this.worldPosition=s,o=!0}if(this.interpolateRotation&&this._targetRotation){const s=this.worldQuaternion;s.slerp(this._targetRotation,I),this.worldQuaternion=s,o=!0}o&&Xg.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastWorldPos.copy(A),this.lastWorldRotation.copy(e),!this._model)return;if(!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership){this.rb&&(this.rb.isKinematic=this._model.isOwned??!1,this.rb.setVelocity(0,0,0));return}this.rb&&(this._wasKinematic!==void 0&&(mn&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic),this.gameObject.position.distanceTo(new y(0,0,0))>1e3&&(mn&&console.log("RESET",this.name),this.gameObject.position.set(0,1,0),this.rb.setVelocity(0,0,0)));const i=10,g=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%i===0||g)){mn&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this.overridePhysics&&this.rb,this._needsUpdate=!1;const I=q2(this.guid,this,!!g);this.context.connection.sendBinary(I)}}}const sgA=CA("debugshadowcomponents");uR.prototype.interactable={get(){return this.interactive},set(t){this.interactable=t}};const bo=Symbol("shadowDomOwner");class Ms extends JA{constructor(){super(...arguments),n(this,"shadowComponent",null),n(this,"_controlsChildLayout",!0),n(this,"_root"),n(this,"_parentComponent")}isRoot(){var A;return((A=this.Root)==null?void 0:A.gameObject)===this.gameObject}get canvas(){const A=this.Root;return A!=null&&A.isCanvas?A:null}markDirty(){go.markUIDirty(this.context)}get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(A){this._controlsChildLayout=A,this.shadowComponent&&(this.shadowComponent.autoLayout=A)}get Root(){return this._root===void 0&&(this._root=iA.getComponentInParent(this.gameObject,Gl)),this._root}get Canvas(){return this.canvas}__internalNewInstanceCreated(){super.__internalNewInstanceCreated(),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0}onEnable(){super.onEnable()}addShadowComponent(A,e){var i;this.removeShadowComponent();const g=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=iA.getComponentInParent(g,Ms),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}A.name=this.name+" ("+(this.constructor.name??"UI")+")",A.autoLayout=this._parentComponent.controlsChildLayout,A[bo]=this,this.setShadowComponentOwner(A);let I=!1;if(((i=this.Root)==null?void 0:i.gameObject)===this.gameObject)this.gameObject.add(A);else{const o=this._parentComponent.shadowComponent;o&&(o?.add(A),I=!0)}this.shadowComponent=A,e&&e.shadowComponent&&this.shadowComponent&&e.shadowComponent.add(this.shadowComponent),xc&&A.add(new fQ(.5)),this.onAfterAddedToScene(),I&&jH(),sgA&&console.log(this.shadowComponent)}set(A){}setShadowComponentOwner(A){if(A&&(A[bo]===void 0||A[bo]===this)&&(A[bo]=this,A.children))for(const e of A.children)this.setShadowComponentOwner(e)}traverseOwnedShadowComponents(A,e,i){if(A&&A[bo]===e){i(A);for(const g of A.children)this.traverseOwnedShadowComponents(g,e,i)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(A){this.shadowComponent&&(this.shadowComponent.interactable=A)}}class Gl extends Ms{awake(){super.awake()}}class lE{static getObject(A){const e=A[bo];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 i=this.tryFindCanvasGroup(A);if(i?.isCanvasGroup===!0&&(e&&(e.canvasGroup=i),i.blocksRaycasts===!1||i.interactable===!1))return!1;const g=Yr(A,I=>{if(I.isGraphic===!0)return I},!1);return e&&g?.isGraphic===!0&&(e.graphic=g),!(g?.raycastTarget===!1||g?.layer===2)}static tryFindCanvasGroup(A){if(!A)return null;const e=Yr(A,i=>{const g=i;if(g.blocksRaycasts!==void 0&&g.interactable!==void 0)return g},!1);return e!==void 0?e:this.tryFindCanvasGroup(A.parent)}}const Ml=CA("debugwebxrcontroller");var dE=(t=>(t[t.PhysicalDevice=0]="PhysicalDevice",t[t.Touch=1]="Touch",t))(dE||{}),aa=(t=>(t.SelectStart="select-start",t.SelectEnd="select-end",t.Update="update",t))(aa||{});class Ay extends JA{}const kg=class extends JA{constructor(){super(...arguments),n(this,"webXR"),n(this,"index",-1),n(this,"controllerModel"),n(this,"controller"),n(this,"controllerGrip"),n(this,"hand"),n(this,"handPointerModel"),n(this,"grabbed",null),n(this,"input",null),n(this,"type",0),n(this,"showRaycastLine",!0),n(this,"enableRaycasts",!0),n(this,"enableDefaultControls",!0),n(this,"_wristQuaternion",null),n(this,"movementVector",new y),n(this,"worldRot",new UA),n(this,"joystick",new eA),n(this,"didRotate",!1),n(this,"didTeleport",!1),n(this,"didChangeScale",!1),n(this,"lastHit",null),n(this,"raycastLine",null),n(this,"_raycastHitPoint",null),n(this,"_connnectedCallback",null),n(this,"_disconnectedCallback",null),n(this,"_selectStartEvt",null),n(this,"_selectEndEvt",null),n(this,"_selectionPressed",!1),n(this,"_selectionPressedLastFrame",!1),n(this,"_selectionStartTime",0),n(this,"_selectionEndTime",0),n(this,"_useSmoothing",!0),n(this,"_isConnected",!1),n(this,"rayRotation",new UA),n(this,"_pinchStartTime"),n(this,"selectStartCallback",null),n(this,"lastSelectStartObject",null),n(this,"_didNotEndSelection",!1),n(this,"closeGrabBoundingBoxHelper")}static CreateRaycastLine(){const t=new ci(this.geometry),A=t.material;return A.color=this.raycastColor,t.layers.set(2),t.name="line",t.scale.z=1,t}static CreateRaycastHitPoint(){const t=new Wo(.5,22,22),A=new rt({color:this.raycastColor}),e=new uA(t,A);return e.visible=!1,e.layers.set(2),e}static Create(t,A,e,i){const g=e?iA.addNewComponent(e,kg,!1):new kg;g.webXR=t,g.index=A,g.type=i;const I=t.context;g.controller=I.renderer.xr.getController(A),g.controllerGrip=I.renderer.xr.getControllerGrip(A),g.controllerModel=this.Factory.createControllerModel(g.controller),g.controllerGrip.add(g.controllerModel),g.hand=I.renderer.xr.getHand(A);const o=new OQ;ol(o,I),g.webXR.handModelPath&&g.webXR.handModelPath!==""?o.setPath(FC(t.sourceId,g.webXR.handModelPath)):o.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/");const s=new NiA(g.hand,o);return g.hand.add(s),g.hand.traverse(C=>C.layers.set(2)),g.handPointerModel=new LiA(g.hand,g.controller),g.controller.addEventListener("connected",C=>{g.setControllerLayers(g.controllerModel,2),g.setControllerLayers(g.controllerGrip,2),g.setControllerLayers(g.hand,2),setTimeout(()=>{g.setControllerLayers(g.controllerModel,2),g.setControllerLayers(g.controllerGrip,2),g.setControllerLayers(g.hand,2)},1e3)}),g.hand.addEventListener("connected",C=>{var a;if(C.data.hand){t.Rig&&t.Rig.add(g.hand),g.type=0,g.handPointerModel.traverse(B=>B.layers.set(2)),(a=g.handPointerModel.pointerObject)==null||a.traverse(B=>B.layers.set(2));const r=g.hand.joints;if(r)for(const B of Object.keys(r)){const Q=r[B];Q.parent||g.hand.add(Q)}}}),g}static addEventListener(t,A){const e=this.eventSubs[t]??[];e.push(A),this.eventSubs[t]=e}static removeEventListener(t,A){if(!A)return;const e=this.eventSubs[t]??[],i=e.indexOf(A);i>=0&&e.splice(i,1),this.eventSubs[t]=e}get isUsingHands(){var t;return((t=this.input)==null?void 0:t.hand)!=null}get wrist(){if(!this.hand)return null;const t=this.hand.joints;return t?t.wrist:null}getWristQuaternion(){const t=this.wrist;return t?(this._wristQuaternion||(this._wristQuaternion=new UA),Mt(t).multiply(this._wristQuaternion.setFromEuler(new Ag(-Math.PI/4,0,0)))):null}get selectionDown(){return this._selectionPressed&&!this._selectionPressedLastFrame}get selectionUp(){return!this._selectionPressed&&this._selectionPressedLastFrame}get selectionPressed(){return this._selectionPressed}get selectionClick(){return this._selectionEndTime-this._selectionStartTime<.3}get raycastHitPoint(){return this._raycastHitPoint}get useSmoothing(){return this._useSmoothing}awake(){if(!this.controller){console.warn("WebXRController: Missing controller object.",this);return}this._connnectedCallback=this.onSourceConnected.bind(this),this._disconnectedCallback=this.onSourceDisconnected.bind(this),this._selectStartEvt=this.onSelectStart.bind(this),this._selectEndEvt=this.onSelectEnd.bind(this),this.type===1&&(this.controllerGrip.addEventListener("connected",this._connnectedCallback),this.controllerGrip.addEventListener("disconnected",this._disconnectedCallback),this.controller.addEventListener("selectstart",this._selectStartEvt),this.controller.addEventListener("selectend",this._selectEndEvt)),this.type===0&&(this.controller.addEventListener("selectstart",this._selectStartEvt),this.controller.addEventListener("selectend",this._selectEndEvt))}onDestroy(){var t,A,e;this.type===1&&(this.controllerGrip.removeEventListener("connected",this._connnectedCallback),this.controllerGrip.removeEventListener("disconnected",this._disconnectedCallback),this.controller.removeEventListener("selectstart",this._selectStartEvt),this.controller.removeEventListener("selectend",this._selectEndEvt)),this.type===0&&(this.controller.removeEventListener("selectstart",this._selectStartEvt),this.controller.removeEventListener("selectend",this._selectEndEvt)),(t=this.hand)==null||t.clear(),(A=this.controllerGrip)==null||A.clear(),(e=this.controller)==null||e.clear()}onEnable(){var t,A,e,i,g;if(!this.webXR){console.warn("No WebXR component assigned to WebXRController.");return}this.hand&&(this.hand.name="Hand"),this.controllerGrip&&(this.controllerGrip.name="ControllerGrip"),this.controller&&(this.controller.name="Controller"),this.raycastLine&&(this.raycastLine.name="RaycastLine;"),this.webXR.Controllers.indexOf(this)<0&&this.webXR.Controllers.push(this),this.raycastLine||(this.raycastLine=kg.CreateRaycastLine()),this._raycastHitPoint||(this._raycastHitPoint=kg.CreateRaycastHitPoint()),(t=this.webXR.Rig)==null||t.add(this.hand),(A=this.webXR.Rig)==null||A.add(this.controllerGrip),(e=this.webXR.Rig)==null||e.add(this.controller),(i=this.webXR.Rig)==null||i.add(this.raycastLine),(g=this.raycastLine)==null||g.add(this._raycastHitPoint),this._raycastHitPoint.visible=!1,this.hand.add(this.handPointerModel),Ml&&console.log("ADDED TO RIG",this.webXR.Rig)}onDisable(){var t,A,e,i,g;if((t=this.hand)==null||t.removeFromParent(),(A=this.controllerGrip)==null||A.removeFromParent(),(e=this.controller)==null||e.removeFromParent(),(i=this.raycastLine)==null||i.removeFromParent(),(g=this._raycastHitPoint)==null||g.removeFromParent(),this.webXR){const I=this.webXR.Controllers.indexOf(this);I>=0&&this.webXR.Controllers.splice(I,1)}}onSourceConnected(t){if(this._isConnected){console.warn("Received connected event for controller that is already connected",this.index,t);return}this._isConnected=!0,this.input=t.data,this.type===1&&this.onSelectStart()}onSourceDisconnected(t){if(!this._isConnected){console.warn("Received discnnected event for controller that is not connected",t);return}this._isConnected=!1,this.type===1&&this.onSelectEnd(),this.input=null}createPointerEvent(t){switch(t){case"down":this.context.input.createPointerDown(new qC(pi.PointerDown,null,{clientX:0,clientY:0,button:this.index,pointerType:MQ.Touch}));break;case"move":break;case"up":this.context.input.createPointerUp(new qC(pi.PointerUp,null,{clientX:0,clientY:0,button:this.index,pointerType:MQ.Touch}));break}}raycastUpdate(t,A){const e=this.showRaycastLine&&this.type!==1;if(this.type===1)t.visible=!1;else if(this.isUsingHands){t.visible=!this.grabbed&&e,ui(t,A);const i=this.hand.joints;if(i&&i.wrist&&this.grabbed&&this.grabbed.isCloseGrab){const g=this.getWristQuaternion();g&&this.rayRotation.copy(g)}CI(t,this.rayRotation)}else t.visible=e,CI(t,this.rayRotation),ui(t,A)}update(){if(!this.webXR)return;this.context.time.frameCount%60===0&&(this.setControllerLayers(this.controller,2),this.setControllerLayers(this.controllerGrip,2),this.setControllerLayers(this.hand,2));const t=kg.eventSubs.update;if(t&&t.length>0)for(const i of t)i(this);let A=1;this.type===0?A=this.context.time.deltaTime/.1:this.isUsingHands&&this.handPointerModel.pinched&&(A=this.context.time.deltaTime/.3),this.rayRotation.slerp(Mt(this.controller),this.useSmoothing?A:1);const e=he(this.controller);this.isUsingHands&&this.handPointerModel.cursorObject&&(this.handPointerModel.cursorObject.visible=!1),this.enableRaycasts?(this.raycastLine&&this.raycastUpdate(this.raycastLine,e),this.lastHit=this.updateLastHit(),this.grabbed&&this.grabbed.update()):this.raycastLine&&(this.raycastLine.visible=!1),this._selectionPressedLastFrame=this._selectionPressed,this.selectStartCallback&&this.selectStartCallback()}onUpdate(t){var A,e;if(this.lastHit=null,!t||t.inputSources.length<=this.index){this.input=null;return}if(this.type===0&&(this.input=t.inputSources[this.index]),!this.input)return;const i=this.webXR.Rig;if(!i)return;this._didNotEndSelection&&!this.handPointerModel.pinched&&(this._didNotEndSelection=!1,this.onSelectEnd()),this.updateStick(this.input);const g=(e=(A=this.input)==null?void 0:A.gamepad)==null?void 0:e.buttons;if(this.enableDefaultControls)switch(this.input.handedness){case"left":this.movementUpdate(i,g);break;case"right":this.rotationUpdate(i,g);break}}movementUpdate(t,A){const e=3*kg.MovementSpeedFactor,i=2,g=oe.clamp01(this.joystick.length()*2),I=this.joystick.x>0?1:-1;let o=Math.pow(this.joystick.x,i);o*=I,o*=g;const s=this.joystick.y>0?1:-1;let C=Math.pow(this.joystick.y,i);C*=s,o*=g,t.getWorldQuaternion(this.worldRot),this.movementVector.set(o,0,C),this.movementVector.applyQuaternion(this.webXR.TransformOrientation),this.movementVector.y=0,this.movementVector.applyQuaternion(this.worldRot),this.movementVector.multiplyScalar(e*this.context.time.deltaTime),t.position.add(this.movementVector),this.isUsingHands&&this.runTeleport(t,A)}rotationUpdate(t,A){const e=this.joystick.x,i=Math.abs(e);if(i<.4)this.didRotate=!1;else if(i>.5&&!this.didRotate){const g=e>0?-1:1;t.rotateY(oe.toRadians(30*g)),this.didRotate=!0}this.runTeleport(t,A)}runTeleport(t,A){var e,i;let g=-this.joystick.y;if((e=this.hand)!=null&&e.visible&&!this.grabbed){const r=this.handPointerModel.isPinched();r&&this._pinchStartTime===void 0&&(this._pinchStartTime=this.context.time.time),r&&this._pinchStartTime&&this.context.time.time-this._pinchStartTime>.8&&(g=this.handPointerModel.isPinched()?1:0),r||(this._pinchStartTime=void 0)}else this._pinchStartTime=void 0;const I=this.webXR.IsInVR,o=this.webXR.Rig;let s=g>.5&&I,C=o?((i=o?.scale)==null?void 0:i.x)<.999:!1,a=null;if(A&&this.input&&!this.input.hand)for(let r=0;r<A.length;r++){const B=A[r];if(r===4)if(B.pressed&&!this.didChangeScale&&I){this.didChangeScale=!0;const Q=o;if(Q){const E=this.switchScale(Q,s,C,a);s=E.doTeleport,C=E.isInMiniatureMode,a=E.newRigScale}}else B.pressed||(this.didChangeScale=!1)}if(s){if(!this.didTeleport){const r=this.raycast();if(this.didTeleport=!0,r&&r.length>0){const B=r[0];if(C||this.isValidTeleportTarget(B.object)){const Q=B.point;ui(t,Q)}}}}else g<.1&&(this.didTeleport=!1);a!==null&&(t.scale.set(a,a,a),t.updateMatrixWorld())}isValidTeleportTarget(t){return iA.getComponentInParent(t,Ay)!=null}switchScale(t,A,e,i){if(e){e=!1,t.scale.set(1,1,1),i=1,kg.MovementSpeedFactor=1;const g=this.context.mainCamera;kg.PreviousCameraFarDistance&&(g.far=kg.PreviousCameraFarDistance)}else{e=!0,A=!0,i=.1,kg.MovementSpeedFactor=i*2;const g=this.context.mainCamera;kg.PreviousCameraFarDistance=g.far,g.far/=i}return{doTeleport:A,isInMiniatureMode:e,newRigScale:i}}updateStick(t){var A;!t||!t.gamepad||((A=t.gamepad.axes)==null?void 0:A.length)<4||(this.joystick.x=t.gamepad.axes[2],this.joystick.y=t.gamepad.axes[3])}updateLastHit(){var t;const A=this.raycast(),e=A?A[0]:null;this.lastHit=e;let i=1;if(this.webXR.Rig&&(i/=this.webXR.Rig.scale.x),this.raycastLine){this.raycastLine.scale.z=i*(((t=this.lastHit)==null?void 0:t.distance)??9999);const g=this.raycastLine.material;e!=null?g.color=kg.raycastColor:g.color=kg.raycastNoHitColor}if(this._raycastHitPoint){if(this.lastHit!=null){this._raycastHitPoint.position.z=-1;const g=oe.clamp(this.lastHit.distance*.01*i,.015,.1);this._raycastHitPoint.scale.set(g,g,g)}this._raycastHitPoint.visible=this.lastHit!==null&&this.lastHit!==void 0}return e}onSelectStart(){this.context.connection.allowEditing&&(this.selectStartCallback=()=>this.onHandleSelectStart())}onHandleSelectStart(){this.selectStartCallback=null,this._selectionPressed=!0,this._selectionStartTime=this.context.time.time,this._selectionEndTime=1e3;let t=null,A=!1;if(this.isUsingHands?(t=this.overlap(),t.length<=0?(t=this.raycast(),A=!1):A=!0):t=this.raycast(),Ml&&console.log("onHandleSelectStart","close grab? "+A,"intersections",t),t&&t.length>0)for(const e of t){const i=e.object;this.lastSelectStartObject=i;const g={selected:i,grab:i},I=kg.eventSubs["select-start"];if(I&&I.length>0)for(const o of I)o(this,g);g.grab!==i&&Ml&&console.log("Grabbed object changed","original",i,"new",g.grab),g.grab&&(this.grabbed=$s.TryTake(this,g.grab,e,A));break}else{const e=kg.eventSubs["select-start"],i={selected:null,grab:null};if(e&&e.length>0)for(const g of e)g(this,i)}}onSelectEnd(){var t;if(this.isUsingHands&&this.handPointerModel.pinched){this._didNotEndSelection=!0;return}if(!this._selectionPressed)return;this.selectStartCallback=null,this._selectionPressed=!1,this._selectionEndTime=this.context.time.time;const A={grab:((t=this.grabbed)==null?void 0:t.selected)??this.lastSelectStartObject},e=kg.eventSubs["select-end"];if(e&&e.length>0)for(const i of e)i(this,A);this.grabbed&&(this.grabbed.free(),this.grabbed=null)}testIsVisible(t){return!(!t||iA.isActiveInHierarchy(t)===!1||lE.isInteractable(t)===!1)}setControllerLayers(t,A){var e,i;if(t&&(t.layers.set(A),t.children))for(const g of t.children)((e=this.grabbed)==null?void 0:e.selected)===g||((i=this.grabbed)==null?void 0:i.selectedMesh)===g||this.setControllerLayers(g,A)}getRay(){const t=new As;return t.origin.copy(he(this.controller)),t.direction.set(0,0,-1).applyQuaternion(this.rayRotation),t}overlap(){const t=this.isUsingHands&&this.handPointerModel?this.handPointerModel.pointerObject:this.controllerGrip;if(Ml&&(!this.closeGrabBoundingBoxHelper&&t&&(this.closeGrabBoundingBoxHelper=new Lu(t,16776960),this.scene.add(this.closeGrabBoundingBoxHelper)),this.closeGrabBoundingBoxHelper&&t&&this.closeGrabBoundingBoxHelper.setFromObject(t)),!t)return new Array;const A=he(t).clone();return this.context.physics.sphereOverlap(A,.02)}raycast(){const t=new zI;t.layerMask=new Yg,t.layerMask.enableAll(),t.layerMask.disable(2),t.ray=this.getRay();const A=this.context.physics.raycast(t);for(let e=0;e<A.length;e++){const i=A[e],g=i.object;if(!this.testIsVisible(g)){A.splice(e,1),e--;continue}i.object=lE.getObject(g);break}return A}};let bi=kg;n(bi,"Factory",new ZiA),n(bi,"raycastColor",new yA(.9,.3,.3)),n(bi,"raycastNoHitColor",new yA(.6,.6,.6)),n(bi,"geometry",new le().setFromPoints([new y(0,0,0),new y(0,0,-1)])),n(bi,"handModels",{}),n(bi,"eventSubs",{}),n(bi,"PreviousCameraFarDistance"),n(bi,"MovementSpeedFactor",1);var ey=(t=>(t.WillTake="WillTake",t.DidTake="DidTake",t.WillFree="WillFree",t.DidFree="DidFree",t))(ey||{});const NI=class{constructor(){n(this,"sync",null),n(this,"selected",null),n(this,"selectedParent",null),n(this,"selectedMesh",null),n(this,"controller",null),n(this,"grabTime",0),n(this,"grabUUID",""),n(this,"isCloseGrab",!1),n(this,"originalMaterial",null),n(this,"usageMarker",null),n(this,"rigidbodies",null),n(this,"didReparent",!1),n(this,"grabDistance",0),n(this,"interactable",null),n(this,"positionSource",null),n(this,"grabPoint",new y),n(this,"localPositionOffsetToGrab",null),n(this,"localPositionOffsetToGrab_worldSpace",new y),n(this,"localQuaternionToGrab",new UA(0,0,0,1)),n(this,"targetDir",null),n(this,"quaternionLerp",null),n(this,"controllerDir",new y),n(this,"controllerWorldPos",new y),n(this,"lastControllerWorldPos",new y),n(this,"controllerPosDelta",new y),n(this,"totalChangeAlongDirection",0),n(this,"rigPositionLastFrame",new y)}static AddEventListener(t,A){return NI.Events[t]||(NI.Events[t]=[]),NI.Events[t].push(A),A}static RemoveEventListener(t,A){if(!A||!NI.Events[t])return;const e=NI.Events[t].indexOf(A);e>=0&&NI.Events[t].splice(e,1)}static Register(t){this.Current.find(A=>A===t)||this.Current.push(t)}static Remove(t){const A=this.Current.indexOf(t);A>=0&&this.Current.splice(A,1)}static TryTake(t,A,e,i){const g=iA.getComponentInParent(A,EE);if(g)A=g.gameObject;else return Ml&&console.warn("Prevented taking object that is not interactable",A),null;let I=A;const o=iA.getComponentInParent(A,kn);o&&(o.requestOwnership(),I=o.gameObject);for(const C of this.Current)if(C.selected===I)return C.controller===t||(C.free(),C.Take(t,I,A,o,g,e,i)),C;const s=new NI;return s.Take(t,I,A,o,g,e,i),s}Take(t,A,e,i,g,I,o){var s,C;if(console.assert(A!==null,"Expected object to be taken but was",A),t.isUsingHands?this.positionSource=o?t.wrist:t.controller:this.positionSource=t.controller,!this.positionSource)return console.warn("No position source"),this;const a={controller:t,take:A,hit:e,sync:i,interactable:g};(s=NI.Events.WillTake)==null||s.forEach(h=>h(this,a));const r=e;r!=null&&r.material&&(this.originalMaterial=r.material,Array.isArray(r.material)||(r.material=r.material.clone(),r.material&&r.material.emissive&&(r.material.emissive.b=.2))),this.selected=A,this.selectedParent||(this.selectedParent=A.parent),this.selectedMesh=r,this.controller=t,this.interactable=g,this.isCloseGrab=o,this.didReparent=!1,this.sync=i,this.grabTime=t.context.time.time,this.grabUUID=Date.now().toString(),this.usageMarker=iA.addNewComponent(this.selected,hE),this.rigidbodies=iA.getComponentsInChildren(this.selected,Kt),he(this.positionSource,this.lastControllerWorldPos);const B=()=>o?this.lastControllerWorldPos.clone():I.point.clone();this.grabDistance=B().distanceTo(this.lastControllerWorldPos),this.totalChangeAlongDirection=0,this.localPositionOffsetToGrab=this.selected.worldToLocal(B());const Q=t.isUsingHands&&o?this.controller.getWristQuaternion().clone():t.rayRotation.clone();Mt(this.selected,this.localQuaternionToGrab).premultiply(Q.invert());const E=this.controller.webXR.Rig;return E&&this.rigPositionLastFrame.copy(he(E)),cI.Add(t.context,this.selected),NI.Register(this),this.sync&&(this.sync.fastMode=!0),(C=NI.Events.DidTake)==null||C.forEach(h=>h(this,a)),this}free(){var t,A,e,i;if(!this.selected)return;const g={controller:this.controller,take:this.selected,hit:this.selected,sync:this.sync,interactable:null};(t=NI.Events.WillFree)==null||t.forEach(s=>s(this,g)),cI.Remove(this.controller.context,this.selected),NI.Remove(this),this.sync&&(this.sync.fastMode=!1);const I=this.selectedMesh;I&&this.originalMaterial&&I.material&&(I.material=this.originalMaterial);const o=this.selected;if(this.didReparent&&o.parent){const s=this.selectedParent;s?s.attach(o):(A=this.controller)==null||A.context.scene.attach(o)}if((e=this.usageMarker)==null||e.destroy(),this.controller&&(this.controller.grabbed=null),this.selected=null,this.selectedParent=null,this.selectedMesh=null,this.sync=null,this.rigidbodies)for(const s of this.rigidbodies)s.wakeUp(),s.setVelocity(s.smoothedVelocity);this.rigidbodies=null,this.localPositionOffsetToGrab=null,this.quaternionLerp=null,(i=NI.Events.DidFree)==null||i.forEach(s=>s(this,g))}controllerMovementSinceLastFrame(){if(!this.positionSource||!this.controller)return 0;this.controllerDir.set(0,0,-1),this.controllerDir.applyQuaternion(this.controller.rayRotation),he(this.positionSource,this.controllerWorldPos),this.controllerPosDelta.copy(this.controllerWorldPos),this.controllerPosDelta.sub(this.lastControllerWorldPos),this.lastControllerWorldPos.copy(this.controllerWorldPos);const t=this.controller.webXR.Rig;if(t){const A=he(t),e=this.rigPositionLastFrame.sub(A);this.controllerPosDelta.add(e),this.rigPositionLastFrame.copy(A)}return this.controllerDir.dot(this.controllerPosDelta)}update(){var t;if(this.rigidbodies)for(const A of this.rigidbodies)A.resetVelocities();if(this.sync&&this.controller&&this.controller.context.connection.isInRoom&&this.controller.context.time.time-this.grabTime>3&&this.sync.hasOwnership()===!1&&(console.log("no ownership, will leave",this.sync.guid),this.free()),!(this.interactable&&!this.interactable.canGrab)){if(!this.didReparent&&this.selected&&this.controller){const A=((t=this.controller.webXR.Rig)==null?void 0:t.scale.x)??1;this.totalChangeAlongDirection+=this.controllerMovementSinceLastFrame();let e=1;this.controller.type===0&&(e=Math.max(0,1+this.totalChangeAlongDirection*2/A),e=e*e*e),this.grabDistance/A<.8&&(e=1),this.targetDir||(this.targetDir=new y),this.targetDir.set(0,0,-this.grabDistance*e);const i=this.targetDir.applyQuaternion(this.controller.rayRotation).add(this.controllerWorldPos),g=this.controller.rayRotation.clone().multiplyQuaternions(this.controller.rayRotation,this.localQuaternionToGrab);this.quaternionLerp||(this.quaternionLerp=g.clone()),this.quaternionLerp.slerp(g,this.controller.useSmoothing?this.controller.context.time.deltaTime/.03:1),CI(this.selected,this.quaternionLerp),this.selected.updateWorldMatrix(!1,!1),this.grabPoint.copy(i),this.localPositionOffsetToGrab&&(this.localPositionOffsetToGrab_worldSpace.copy(this.localPositionOffsetToGrab),this.selected.localToWorld(this.localPositionOffsetToGrab_worldSpace).sub(he(this.selected)),i.sub(this.localPositionOffsetToGrab_worldSpace)),ui(this.selected,i)}if(this.rigidbodies!=null)for(const A of this.rigidbodies)A.wakeUp();Xg.markDirty(this.selected,!0)}}};let $s=NI;n($s,"Events",{}),n($s,"Current",[]);class Ra{constructor(A,e){n(this,"used",!1),n(this,"inputSource"),n(this,"object"),n(this,"point"),n(this,"normal"),n(this,"face"),n(this,"distance"),n(this,"instanceId"),n(this,"pointerId"),n(this,"isDown"),n(this,"isUp"),n(this,"isPressed"),n(this,"isClicked"),n(this,"button"),n(this,"input"),n(this,"_event"),this._event=e,this.input=A,this.button=e?.button??0}use(){this.used=!0,this.pointerId!==void 0&&this.input.setPointerUsed(this.pointerId)}stopPropagation(){var A;(A=this._event)==null||A.stopImmediatePropagation()}Use(){this.use()}StopPropagation(){var A;(A=this._event)==null||A.stopImmediatePropagation()}get event(){return this._event}clone(){const A=new Ra(this.input,this._event);return Object.assign(A,this),A}}function OR(t){return iA.foreachComponent(t,A=>{const e=A;if(e.onPointerDown||e.onPointerUp||e.onPointerEnter||e.onPointerExit||e.onPointerClick)return!0},!1)===!0}var CgA=Object.defineProperty,agA=Object.getOwnPropertyDescriptor,ngA=(t,A,e,i)=>{for(var g=i>1?void 0:i?agA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&CgA(A,e,g),g};class Gn extends JA{awake(){go.createIfNoneExists(this.context)}onEnable(){var A;(A=go.get(this.context))==null||A.register(this)}onDisable(){var A;(A=go.get(this.context))==null||A.unregister(this)}performRaycast(A=null){return null}}class ws extends Gn{constructor(){super(...arguments),n(this,"targets",null),n(this,"raycastHits",[]),n(this,"ignoreSkinnedMeshes",!1)}start(){this.targets=[this.gameObject]}performRaycast(A=null){if(!this.targets)return null;A??(A=new zI),A.targets=this.targets,A.results=this.raycastHits;const e=A.testObject;this.ignoreSkinnedMeshes&&(A.testObject=g=>g instanceof gs?"continue in children":e?e(g):!0);const i=this.context.physics.raycast(A);return A.testObject=e,i}}ngA([w()],ws.prototype,"ignoreSkinnedMeshes",2);class ty extends ws{constructor(){super(),this.ignoreSkinnedMeshes=!0}}function iy(t){return t[bo]||(t.parent?iy(t.parent):null)}function rgA(t){return t.isUI===!0||typeof t[bo]=="object"}function gy(t,A){if(!t)return;const e=t.material;if(e?.isMaterial===!0){const i=t.parent;i&&i.isText,e.side=A.doubleSided??!0?yt:Lg,e.shadowSide=A.doubleSided?yt:Lg,t.castShadow=A.castShadows?A.castShadows:!1,t.receiveShadow=A.receiveShadows?A.receiveShadows:!1}for(const i of t.children)gy(i,A)}function pE(t,A,e){t[A]===void 0&&console.warn("Field",A,"is undefined on",t);const i=Proxy.revocable(t[A],{set(o,s,C,a){const r=o[s],B=Reflect.set(o,s,C,a);return e(C,r),B}}),g=i.revoke,I=t[A];return i.revoke=()=>{t[A]=I,g()},t[A]=i.proxy,i}const b2=Symbol("Scheduled action");function BgA(t,A,e=og.OnBeforeRender){let i=t[b2];i||(i=t[b2]={});const g=A.name;i[e]||(i[e]={});const I=i[e];if(I[g])return;function*o(){A?.call(t),I[g]=null}const s=t.startCoroutine(o(),e);I[g]=s}const eB=CA("debugeventsystem");var _R=(t=>(t.BeforeHandleInput="BeforeHandleInput",t.AfterHandleInput="AfterHandleInput",t))(_R||{});const na=class extends JA{constructor(){super(),n(this,"raycaster",[]),n(this,"_selectStartFn"),n(this,"_selectEndFn"),n(this,"_selectUpdateFn"),n(this,"_handleEventCycleFn"),n(this,"_handleInputFn"),n(this,"pressedByID",new Map),n(this,"hoveredByID",new Map),n(this,"_sortedHits",[]),n(this,"_testObjectsCache",new Map),n(this,"shouldRaycastObject",t=>{var A;let e=null;if(rgA(t)&&(e=(A=t[bo])==null?void 0:A.gameObject),this._testObjectsCache.has(t)||e&&this._testObjectsCache.has(e))return this._testObjectsCache.get(t)===!1?"continue in children":!0;{let i=OR(t);return!i&&e&&(i=OR(e)),i?(this._testObjectsCache.set(t,!0),t.traverse(g=>{this._testObjectsCache.set(g,!0)}),!0):(this._testObjectsCache.set(t,!1),"continue in children")}}),n(this,"_sortingBuffer",[]),n(this,"_noDepthTestingResults",[]),n(this,"out",{}),n(this,"currentActiveMeshUIComponents",[]),na.systems.push(this)}static createIfNoneExists(t){this.didSearchEventSystem||(this.didSearchEventSystem=!0,na.systems.length<=0&&na.systems.push(...iA.findObjectsOfType(na,t)));for(const e of na.systems)if(e.context===t)return;const A=new fA;iA.addNewComponent(A,na),t.scene.add(A)}static get systems(){const t=qe.Current;return this._eventSystemMap.has(t)||this._eventSystemMap.set(t,[]),this._eventSystemMap.get(t)}static get(t){const A=this._eventSystemMap.get(t);return A&&A.length>0?A[0]:null}static get instance(){return this.systems[0]}static ensureUpdateMeshUI(t,A,e=!1){ra.update(t,A,e)}static markUIDirty(t){ra.markDirty()}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}onDestroy(){na.systems.splice(na.systems.indexOf(this),1)}start(){if(this.raycaster.length<=0&&!iA.findObjectOfType(Gn,this.context)){const t=iA.addNewComponent(this.context.scene,ws);t.ignoreSkinnedMeshes=!0,this.raycaster.push(t),(Ye()||eB)&&console.warn("Added an ObjectRaycaster to the scene because no raycaster was found. Skinnedmeshes will be ignored for better performance")}}register(t){var A;t&&this.raycaster&&!this.raycaster.includes(t)&&((A=this.raycaster)==null||A.push(t))}unregister(t){var A,e;const i=(A=this.raycaster)==null?void 0:A.indexOf(t);i!==void 0&&i!==-1&&((e=this.raycaster)==null||e.splice(i,1))}onEnable(){const t=new Map;this._selectStartFn??(this._selectStartFn=(e,i)=>{if(!i.grab)return;ra.resetLastSelected();const g=new Ra(this.context.input);g.inputSource=e,g.pointerId=0,g.isDown=e.selectionDown,g.isUp=e.selectionUp,g.isPressed=e.selectionPressed,g.isClicked=!1,t.set(e,i.grab),i.grab&&!this.handleEventOnObject(i.grab,g)&&(i.grab=null)}),this._selectEndFn??(this._selectEndFn=(e,i)=>{var g;if(!i.grab)return;const I=new Ra(this.context.input);I.inputSource=e,I.pointerId=0,I.isDown=e.selectionDown,I.isUp=e.selectionUp,I.isPressed=e.selectionPressed,I.isClicked=e.selectionClick,this.handleEventOnObject(i.grab,I);const o=t.get(e);if(t.set(e,null),o)for(const s of this.pressedByID.keys()){const C=this.pressedByID[s];C.obj===o&&C.handler&&((g=C.handler.onPointerUp)==null||g.call(C.handler,I),this.pressedByID.delete(s))}});const A=new zI;this._selectUpdateFn??(this._selectUpdateFn=e=>{var i;A.ray=e.getRay();const g=this.performRaycast(A);if(!g)return;const I=new Ra(this.context.input);I.inputSource=e,I.pointerId=((i=e.input)==null?void 0:i.handedness)==="right"?0:1,I.isDown=e.selectionDown,I.isUp=e.selectionUp,I.isPressed=e.selectionPressed,I.isClicked=e.selectionClick,this.handleIntersections(g,I)}),bi.addEventListener(aa.SelectStart,this._selectStartFn),bi.addEventListener(aa.SelectEnd,this._selectEndFn),bi.addEventListener(aa.Update,this._selectUpdateFn),this._handleInputFn=this.onPointerEvent.bind(this),this.context.input.addEventListener(pi.PointerDown,this._handleInputFn),this.context.input.addEventListener(pi.PointerUp,this._handleInputFn),this.context.input.addEventListener(pi.PointerMove,this._handleInputFn)}onDisable(){bi.removeEventListener(aa.SelectStart,this._selectStartFn),bi.removeEventListener(aa.SelectEnd,this._selectEndFn),bi.removeEventListener(aa.Update,this._selectUpdateFn),this.context.input.removeEventListener(pi.PointerDown,this._handleInputFn),this.context.input.removeEventListener(pi.PointerUp,this._handleInputFn),this.context.input.removeEventListener(pi.PointerMove,this._handleInputFn)}onBeforeRender(){this.resetMeshUIStates()}onPointerEvent(t){if(t===void 0)return;const A=t.pointerType==MQ.Touch?t.button:0,e=new Ra(this.context.input,t);e.inputSource=this.context.input,e.pointerId=t.button,e.isClicked=t.type==pi.PointerUp&&this.context.input.getPointerClicked(t.button),e.isDown=t.type==pi.PointerDown,e.isUp=t.type==pi.PointerUp,e.isPressed=this.context.input.getPointerPressed(t.button),eB&&e.isClicked&&console.log("CLICK",e.pointerId);const i=new zI;i.screenPoint=this.context.input.getPointerPositionRC(A);const g=this.performRaycast(i);if(!g)return;eB&&e.isClicked&&di("EventSystem: "+e.pointerId+" - "+this.context.time.frame+" - Up:"+e.isUp+", Down:"+e.isDown);const I={sender:this,args:e,hasActiveUI:this.currentActiveMeshUIComponents.length>0};if(this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:I})),!this.handleIntersections(g,e)){const o=this.hoveredByID.get(A);if(o&&this.triggerOnExit(o.obj,o.data),this.hoveredByID.delete(A),e.isUp){const s=this.pressedByID.get(A);s?.handlers.forEach(C=>{var a;return(a=C.onPointerUp)==null?void 0:a.call(C,e)}),this.pressedByID.delete(A)}}this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:I}))}performRaycast(t){if(!this.raycaster)return null;this._sortedHits.length=0,t||(t=new zI),this._testObjectsCache.clear(),t.testObject=this.shouldRaycastObject;for(const A of this.raycaster){if(!A.activeAndEnabled)continue;const e=A.performRaycast(t);e&&e.length>0&&this._sortedHits.push(...e)}return this._sortedHits.sort((A,e)=>A.distance-e.distance),this._sortedHits}handleIntersections(t,A){if(!t||t.length<=0)return!1;t=this.sortCandidates(t);for(const e of t){const{object:i}=e;if(A.point=e.point,A.normal=e.normal,A.face=e.face,A.distance=e.distance,A.instanceId=e.instanceId,this.handleEventOnObject(i,A))return!0}return!1}sortCandidates(t){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let A=0;A<t.length;A++){const e=t[A],i=e.object;if(i.material&&i.material.depthTest===!1){this._noDepthTestingResults.push(e);continue}this._sortingBuffer.push(e)}for(const A of this._sortingBuffer)this._noDepthTestingResults.push(A);return this._noDepthTestingResults}handleEventOnObject(t,A){if(!this.testIsVisible(t))return A.isClicked&&eB&&console.log("not allowed",t),!1;if(A.pointerId===void 0)return eB&&console.warn("Event without pointer can't be handled",A),!1;A.object=t;const e=t.parent;let i=!1;const g=A.isClicked??!1;let I=null;if(e&&e.isUI){const a=(A.isPressed||A.isClicked)??!1;if(e[bo]){const r=e[bo].gameObject;if(r){if(!lE.isInteractable(r,this.out))return!1;I=this.out.canvasGroup??null,this.handleMeshUIIntersection(t,a),t=r,i=!0}}if(!i&&this.handleMeshUiObjectWithoutShadowDom(e,a))return!0}g&&eB&&console.log(this.context.time.frame,t);const o=this.hoveredByID.get(A.pointerId),s=o?.obj!==t;s&&o!=null&&o.obj&&this.triggerOnExit(o.obj,o.data);const C=this.hoveredByID.get(A.pointerId);if(C?(C.obj=t,C.data=A):this.hoveredByID.set(A.pointerId,{obj:t,data:A}),A.isDown){const a=this.pressedByID.get(A.pointerId);a?(a.obj=t,a.data=A):this.pressedByID.set(A.pointerId,{obj:t,data:A,handlers:new Set})}return(I===null||I.interactable)&&this.handleMainInteraction(t,A,s),!0}propagate(t,A,e){for(;;){if(A.used)return;if(iA.foreachComponent(t,i=>{e(i)},!1),!t.parent)break;t=t.parent}}handleMainInteraction(t,A,e){if(A.pointerId===void 0)return;const i=this.pressedByID.get(A.pointerId);this.propagate(t,A,g=>{var I;const o=g;if(o.interactable===!1)return;o.onPointerEnter&&e&&o.onPointerEnter(A),A.isDown&&o.onPointerDown&&(o.onPointerDown(A),i?.handlers.add(o));const s=this.context.input.getPointerPositionLastFrame(A.pointerId),C=this.context.input.getPointerPosition(A.pointerId);s&&!oe.approximately(s,C)&&o.onPointerMove&&o.onPointerMove(A),A.isUp&&(o.onPointerUp&&(o.onPointerUp(A),i?.handlers.delete(o)),o.onPointerExit&&((I=A.event)==null?void 0:I.pointerType)===MQ.Touch&&(o.onPointerExit(A),this.hoveredByID.delete(A.pointerId))),A.isClicked&&o.onPointerClick&&o.onPointerClick(A)}),A.isUp&&(i?.handlers.forEach(g=>{g.onPointerUp&&g.onPointerUp(A)}),this.pressedByID.delete(A.pointerId))}triggerOnExit(t,A){A.used=!1,this.propagate(t,A,e=>{if(!e.gameObject||e.destroyed)return;const i=e;i.onPointerExit&&i.onPointerExit(A)})}handleMeshUiObjectWithoutShadowDom(t,A){return!t||!t.isUI?!0:this.handleMeshUIIntersection(t,A)}handleMeshUIIntersection(t,A){const e=ra.updateState(t,A);return e&&this.currentActiveMeshUIComponents.push(e),e!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&ra.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let t=0;t<this.currentActiveMeshUIComponents.length;t++){const A=this.currentActiveMeshUIComponents[t];ra.resetState(A)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(t){return t?iA.isActiveSelf(t)?this.testIsVisible(t.parent):!1:!0}};let go=na;n(go,"_eventSystemMap",new Map),n(go,"didSearchEventSystem",!1);class ra{static markDirty(){this.needsUpdate=!0}static update(A,e,i=!1){if(i){A.update();return}const g=e.time.frameCount;for(const I of this.lastUpdateFrame)if(I.context===e){if(g===I.frame)return;I.frame=g;let o=this.needsUpdate||g<1;I.nextUpdate===e.time.frameCount&&(o=!0),o&&(eB&&console.log("Update threemeshui"),this.needsUpdate=!1,A.update());return}this.lastUpdateFrame=[{context:e,frame:g,nextUpdate:g}],A.update()}static updateState(A,e){let i=null;if(A&&(i=this.findBlockInParent(A),i&&i!==this.lastSelected)){if(i.interactable===!1)return null;this.needsUpdate=!0}return i}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}}n(ra,"lastSelected",null),n(ra,"lastUpdateFrame",[]),n(ra,"needsUpdate",!1);const Iy=Symbol("cameraController");function QgA(t){return t[Iy]}function L2(t,A,e){e?t[Iy]=A:t[Iy]===A&&(t[Iy]=null)}const x2=Symbol("camera autofit");function EgA(t){return t[x2]===void 0?!0:t[x2]!==!1}class T2 extends uA{constructor(A,e={}){const i=[A.isCubeTexture?"#define ENVMAP_TYPE_CUBE":""],g=`
5096
+ Using the assigned clip instead:`,this.clip),t=this.clip);let i=!this.sound||t&&t!==this.clip;if(typeof t=="string"&&!this.audioLoader&&(i=!0),(t instanceof MediaStream||typeof t=="string")&&(this.clip=t),i){this.shouldPlay=!0,this.onNewClip(t);return}if(this.shouldPlay=!0,this._hasEnded=!1,fg&&console.log("play",(A=this.sound)==null?void 0:A.getVolume(),this.sound),this.sound&&!this.sound.isPlaying){const g=this.context.application.muted;g&&this.sound.setVolume(0),this.clip instanceof MediaStream?(this.sound.setMediaStreamSource(this.clip),this._audioElement||(this._audioElement=document.createElement("audio"),this._audioElement.style.display="none"),this._audioElement.parentNode||(e=this.context.domElement.shadowRoot)==null||e.append(this._audioElement),this._audioElement.srcObject=this.clip,this._audioElement.autoplay=!1):(this._audioElement&&this._audioElement.remove(),this.sound.play(g?.1:0))}}pause(){var t,A;fg&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=(t=this.sound)==null?void 0:t.context.currentTime,this.sound.pause()),(A=this._audioElement)==null||A.remove()}stop(){var t,A;fg&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=(t=this.sound)==null?void 0:t.context.currentTime,fg&&console.log(this._lastContextTime),this.sound.stop()),(A=this._audioElement)==null||A.remove()}get isPlaying(){var t;return((t=this.sound)==null?void 0:t.isPlaying)??!1}set isPlaying(t){}get time(){var t,A;return(t=this.sound)!=null&&t.source?((A=this.sound.source)==null?void 0:A.context.currentTime)-this._lastContextTime+this.sound.offset:0}set time(t){if(this.sound){if(t===this.sound.offset)return;const A=this.isPlaying;this.stop(),this.sound.offset=t,A&&this.play()}}update(){this.helper&&(this.isPlaying&&this.helper.update(),this.helper.visible=this.isPlaying),this._needUpdateSpatialDistanceSettings&&this.applySpatialDistanceSettings(),this.sound&&!this.sound.isPlaying&&this.shouldPlay&&!this._hasEnded&&(this._hasEnded=!0,fg&&console.log("Audio clip ended",this.clip),this.sound.dispatchEvent({type:"ended",target:this}))}};let Si=sa;oa([w(URL)],Si.prototype,"clip",2),oa([w()],Si.prototype,"playOnAwake",2),oa([w()],Si.prototype,"loop",1),oa([w()],Si.prototype,"spatialBlend",1),oa([w()],Si.prototype,"minDistance",1),oa([w()],Si.prototype,"maxDistance",1),oa([w()],Si.prototype,"volume",1),oa([w()],Si.prototype,"rollOffMode",2),oa([w()],Si.prototype,"playInBackground",2);var SiA=Object.defineProperty,fiA=Object.getOwnPropertyDescriptor,miA=(t,A,e,i)=>{for(var g=i>1?void 0:i?fiA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&SiA(A,e,g),g};class wl extends JA{constructor(){super(...arguments),n(this,"constraintActive",!0),n(this,"locked",!1),n(this,"sources",[])}}miA([w(fA)],wl.prototype,"sources",2);const k2={type:"change"},xR={type:"start"},G2={type:"end"};let kiA=class extends _i{constructor(t,A){super(),this.object=t,this.domElement=A,this.domElement.style.touchAction="none",this.enabled=!0,this.target=new y,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:gr.ROTATE,MIDDLE:gr.DOLLY,RIGHT:gr.PAN},this.touches={ONE:Ir.ROTATE,TWO:Ir.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this.getPolarAngle=function(){return o.phi},this.getAzimuthalAngle=function(){return o.theta},this.getDistance=function(){return this.object.position.distanceTo(this.target)},this.listenToKeyEvents=function(P){P.addEventListener("keydown",Ee),this._domElementKeyEvents=P},this.stopListenToKeyEvents=function(){this._domElementKeyEvents.removeEventListener("keydown",Ee),this._domElementKeyEvents=null},this.saveState=function(){e.target0.copy(e.target),e.position0.copy(e.object.position),e.zoom0=e.object.zoom},this.reset=function(){e.target.copy(e.target0),e.object.position.copy(e.position0),e.object.zoom=e.zoom0,e.object.updateProjectionMatrix(),e.dispatchEvent(k2),e.update(),g=i.NONE},this.update=function(){const P=new y,SA=new UA().setFromUnitVectors(t.up,new y(0,1,0)),FA=SA.clone().invert(),cA=new y,VA=new UA,ZA=new y,GA=2*Math.PI;return function(){const Ie=e.object.getWorldPosition(t.position);P.copy(Ie).sub(e.target),P.applyQuaternion(SA),o.setFromVector3(P),e.autoRotate&&g===i.NONE&&m(k()),e.enableDamping?(o.theta+=s.theta*e.dampingFactor,o.phi+=s.phi*e.dampingFactor):(o.theta+=s.theta,o.phi+=s.phi);let ee=e.minAzimuthAngle,M=e.maxAzimuthAngle;return isFinite(ee)&&isFinite(M)&&(ee<-Math.PI?ee+=GA:ee>Math.PI&&(ee-=GA),M<-Math.PI?M+=GA:M>Math.PI&&(M-=GA),ee<=M?o.theta=Math.max(ee,Math.min(M,o.theta)):o.theta=o.theta>(ee+M)/2?Math.max(ee,o.theta):Math.min(M,o.theta)),o.phi=Math.max(e.minPolarAngle,Math.min(e.maxPolarAngle,o.phi)),o.makeSafe(),e.enableDamping?a=hg.lerp(a,C,e.dampingFactor):a=C,o.radius*=a,o.radius=Math.max(e.minDistance,Math.min(e.maxDistance,o.radius)),e.enableDamping===!0?e.target.addScaledVector(r,e.dampingFactor):e.target.add(r),P.setFromSpherical(o),P.applyQuaternion(FA),Ie.copy(e.target).add(P),e.object.parent?e.object.parent.worldToLocal(Ie):e.object.position.copy(Ie),e.object.lookAt(e.target),e.enableDamping===!0?(s.theta*=1-e.dampingFactor,s.phi*=1-e.dampingFactor,r.multiplyScalar(1-e.dampingFactor)):(s.set(0,0,0),r.set(0,0,0)),C=1,B||cA.distanceToSquared(e.object.position)>I||8*(1-VA.dot(e.object.quaternion))>I||ZA.distanceToSquared(e.target)>0?(e.dispatchEvent(k2),cA.copy(e.object.position),VA.copy(e.object.quaternion),ZA.copy(e.target),B=!1,!0):!1}}(),this.dispose=function(){e.domElement.removeEventListener("contextmenu",T),e.domElement.removeEventListener("pointerdown",kA),e.domElement.removeEventListener("pointercancel",HA),e.domElement.removeEventListener("wheel",Ce),e.domElement.removeEventListener("pointermove",wA),e.domElement.removeEventListener("pointerup",HA),e._domElementKeyEvents!==null&&(e._domElementKeyEvents.removeEventListener("keydown",Ee),e._domElementKeyEvents=null)};const e=this,i={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6};let g=i.NONE;const I=1e-6,o=new ek,s=new ek;let C=1,a=1;const r=new y;let B=!1;const Q=new eA,E=new eA,h=new eA,d=new eA,l=new eA,c=new eA,u=new eA,p=new eA,D=new eA,S=[],G={};function k(){return 2*Math.PI/60/60*e.autoRotateSpeed}function R(){return Math.pow(.95,e.zoomSpeed)}function m(P){s.theta-=P}function f(P){s.phi-=P}const L=function(){const P=new y;return function(SA,FA){P.setFromMatrixColumn(FA,0),P.multiplyScalar(-SA),r.add(P)}}(),_=function(){const P=new y;return function(SA,FA){e.screenSpacePanning===!0?P.setFromMatrixColumn(FA,1):(P.setFromMatrixColumn(FA,0),P.crossVectors(e.object.up,P)),P.multiplyScalar(SA),r.add(P)}}(),b=function(){const P=new y,SA=new y;return function(FA,cA){const VA=e.domElement;if(e.object.isPerspectiveCamera){e.object.getWorldPosition(SA),P.copy(SA).sub(e.target);let ZA=P.length();ZA*=Math.tan(e.object.fov/2*Math.PI/180),L(2*FA*ZA/VA.clientHeight,e.object.matrixWorld),_(2*cA*ZA/VA.clientHeight,e.object.matrixWorld)}else e.object.isOrthographicCamera?(L(FA*(e.object.right-e.object.left)/e.object.zoom/VA.clientWidth,e.object.matrixWorld),_(cA*(e.object.top-e.object.bottom)/e.object.zoom/VA.clientHeight,e.object.matrixWorld)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),e.enablePan=!1)}}();function H(P){e.object.isPerspectiveCamera?C/=P:e.object.isOrthographicCamera?(e.object.zoom=Math.max(e.minZoom,Math.min(e.maxZoom,e.object.zoom*P)),e.object.updateProjectionMatrix(),B=!0):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),e.enableZoom=!1)}function Z(P){e.object.isPerspectiveCamera?C*=P:e.object.isOrthographicCamera?(e.object.zoom=Math.max(e.minZoom,Math.min(e.maxZoom,e.object.zoom/P)),e.object.updateProjectionMatrix(),B=!0):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),e.enableZoom=!1)}function x(P){Q.set(P.clientX,P.clientY)}function v(P){u.set(P.clientX,P.clientY)}function Y(P){d.set(P.clientX,P.clientY)}function IA(P){E.set(P.clientX,P.clientY),h.subVectors(E,Q).multiplyScalar(e.rotateSpeed);const SA=e.domElement;m(2*Math.PI*h.x/SA.clientHeight),f(2*Math.PI*h.y/SA.clientHeight),Q.copy(E),e.update()}function AA(P){p.set(P.clientX,P.clientY),D.subVectors(p,u),D.y>0?H(R()):D.y<0&&Z(R()),u.copy(p),e.update()}function W(P){l.set(P.clientX,P.clientY),c.subVectors(l,d).multiplyScalar(e.panSpeed),b(c.x,c.y),d.copy(l),e.update()}function gA(P){P.deltaY<0?Z(R()):P.deltaY>0&&H(R()),e.update()}function dA(P){let SA=!1;switch(P.code){case e.keys.UP:P.ctrlKey||P.metaKey||P.shiftKey?f(2*Math.PI*e.rotateSpeed/e.domElement.clientHeight):b(0,e.keyPanSpeed),SA=!0;break;case e.keys.BOTTOM:P.ctrlKey||P.metaKey||P.shiftKey?f(-2*Math.PI*e.rotateSpeed/e.domElement.clientHeight):b(0,-e.keyPanSpeed),SA=!0;break;case e.keys.LEFT:P.ctrlKey||P.metaKey||P.shiftKey?m(2*Math.PI*e.rotateSpeed/e.domElement.clientHeight):b(e.keyPanSpeed,0),SA=!0;break;case e.keys.RIGHT:P.ctrlKey||P.metaKey||P.shiftKey?m(-2*Math.PI*e.rotateSpeed/e.domElement.clientHeight):b(-e.keyPanSpeed,0),SA=!0;break}SA&&(P.preventDefault(),e.update())}function mA(){if(S.length===1)Q.set(S[0].pageX,S[0].pageY);else{const P=.5*(S[0].pageX+S[1].pageX),SA=.5*(S[0].pageY+S[1].pageY);Q.set(P,SA)}}function vA(){if(S.length===1)d.set(S[0].pageX,S[0].pageY);else{const P=.5*(S[0].pageX+S[1].pageX),SA=.5*(S[0].pageY+S[1].pageY);d.set(P,SA)}}function TA(){const P=S[0].pageX-S[1].pageX,SA=S[0].pageY-S[1].pageY,FA=Math.sqrt(P*P+SA*SA);u.set(0,FA)}function WA(){e.enableZoom&&TA(),e.enablePan&&vA()}function $A(){e.enableZoom&&TA(),e.enableRotate&&mA()}function zA(P){if(S.length==1)E.set(P.pageX,P.pageY);else{const FA=bA(P),cA=.5*(P.pageX+FA.x),VA=.5*(P.pageY+FA.y);E.set(cA,VA)}h.subVectors(E,Q).multiplyScalar(e.rotateSpeed);const SA=e.domElement;m(2*Math.PI*h.x/SA.clientHeight),f(2*Math.PI*h.y/SA.clientHeight),Q.copy(E)}function Se(P){if(S.length===1)l.set(P.pageX,P.pageY);else{const SA=bA(P),FA=.5*(P.pageX+SA.x),cA=.5*(P.pageY+SA.y);l.set(FA,cA)}c.subVectors(l,d).multiplyScalar(e.panSpeed),b(c.x,c.y),d.copy(l)}function lA(P){const SA=bA(P),FA=P.pageX-SA.x,cA=P.pageY-SA.y,VA=Math.sqrt(FA*FA+cA*cA);p.set(0,VA),D.set(0,Math.pow(p.y/u.y,e.zoomSpeed)),H(D.y),u.copy(p)}function V(P){e.enableZoom&&lA(P),e.enablePan&&Se(P)}function xA(P){e.enableZoom&&lA(P),e.enableRotate&&zA(P)}function kA(P){e.enabled!==!1&&(S.length===0&&(e.domElement.addEventListener("pointermove",wA),e.domElement.addEventListener("pointerup",HA)),J(P),P.pointerType==="touch"?Xe(P):DA(P))}function wA(P){e.enabled!==!1&&(P.pointerType==="touch"?at(P):XA(P))}function HA(P){hA(P),S.length===0&&(e.domElement.removeEventListener("pointermove",wA),e.domElement.removeEventListener("pointerup",HA)),e.dispatchEvent(G2),g=i.NONE}function DA(P){let SA;switch(P.button){case 0:SA=e.mouseButtons.LEFT;break;case 1:SA=e.mouseButtons.MIDDLE;break;case 2:SA=e.mouseButtons.RIGHT;break;default:SA=-1}switch(SA){case gr.DOLLY:if(e.enableZoom===!1)return;v(P),g=i.DOLLY;break;case gr.ROTATE:if(P.ctrlKey||P.metaKey||P.shiftKey){if(e.enablePan===!1)return;Y(P),g=i.PAN}else{if(e.enableRotate===!1)return;x(P),g=i.ROTATE}break;case gr.PAN:if(P.ctrlKey||P.metaKey||P.shiftKey){if(e.enableRotate===!1)return;x(P),g=i.ROTATE}else{if(e.enablePan===!1)return;Y(P),g=i.PAN}break;default:g=i.NONE}g!==i.NONE&&e.dispatchEvent(xR)}function XA(P){switch(g){case i.ROTATE:if(e.enableRotate===!1)return;IA(P);break;case i.DOLLY:if(e.enableZoom===!1)return;AA(P);break;case i.PAN:if(e.enablePan===!1)return;W(P);break}}function Ce(P){e.enabled===!1||e.enableZoom===!1||g!==i.NONE||(P.preventDefault(),e.dispatchEvent(xR),gA(P),e.dispatchEvent(G2))}function Ee(P){e.enabled===!1||e.enablePan===!1||dA(P)}function Xe(P){switch(qA(P),S.length){case 1:switch(e.touches.ONE){case Ir.ROTATE:if(e.enableRotate===!1)return;mA(),g=i.TOUCH_ROTATE;break;case Ir.PAN:if(e.enablePan===!1)return;vA(),g=i.TOUCH_PAN;break;default:g=i.NONE}break;case 2:switch(e.touches.TWO){case Ir.DOLLY_PAN:if(e.enableZoom===!1&&e.enablePan===!1)return;WA(),g=i.TOUCH_DOLLY_PAN;break;case Ir.DOLLY_ROTATE:if(e.enableZoom===!1&&e.enableRotate===!1)return;$A(),g=i.TOUCH_DOLLY_ROTATE;break;default:g=i.NONE}break;default:g=i.NONE}g!==i.NONE&&e.dispatchEvent(xR)}function at(P){switch(qA(P),g){case i.TOUCH_ROTATE:if(e.enableRotate===!1)return;zA(P),e.update();break;case i.TOUCH_PAN:if(e.enablePan===!1)return;Se(P),e.update();break;case i.TOUCH_DOLLY_PAN:if(e.enableZoom===!1&&e.enablePan===!1)return;V(P),e.update();break;case i.TOUCH_DOLLY_ROTATE:if(e.enableZoom===!1&&e.enableRotate===!1)return;xA(P),e.update();break;default:g=i.NONE}}function T(P){e.enabled!==!1&&P.preventDefault()}function J(P){S.push(P)}function hA(P){delete G[P.pointerId];for(let SA=0;SA<S.length;SA++)if(S[SA].pointerId==P.pointerId){S.splice(SA,1);return}}function qA(P){let SA=G[P.pointerId];SA===void 0&&(SA=new eA,G[P.pointerId]=SA),SA.set(P.pageX,P.pageY)}function bA(P){const SA=P.pointerId===S[0].pointerId?S[1]:S[0];return G[SA.pointerId]}e.domElement.addEventListener("contextmenu",T),e.domElement.addEventListener("pointerdown",kA),e.domElement.addEventListener("pointercancel",HA),e.domElement.addEventListener("wheel",Ce,{passive:!1}),this.update()}};const GiA="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/";class MiA{constructor(A,e,i,g,I=null){this.controller=e,this.handModel=A,this.bones=[],I===null&&(I=new OQ,I.setPath(i||GiA)),I.load(`${g}.glb`,o=>{const s=o.scene.children[0];this.handModel.add(s),s.layers.mask=this.handModel.layers.mask;const C=s.getObjectByProperty("type","SkinnedMesh");C.frustumCulled=!1,C.castShadow=!0,C.receiveShadow=!0,["wrist","thumb-metacarpal","thumb-phalanx-proximal","thumb-phalanx-distal","thumb-tip","index-finger-metacarpal","index-finger-phalanx-proximal","index-finger-phalanx-intermediate","index-finger-phalanx-distal","index-finger-tip","middle-finger-metacarpal","middle-finger-phalanx-proximal","middle-finger-phalanx-intermediate","middle-finger-phalanx-distal","middle-finger-tip","ring-finger-metacarpal","ring-finger-phalanx-proximal","ring-finger-phalanx-intermediate","ring-finger-phalanx-distal","ring-finger-tip","pinky-finger-metacarpal","pinky-finger-phalanx-proximal","pinky-finger-phalanx-intermediate","pinky-finger-phalanx-distal","pinky-finger-tip"].forEach(a=>{const r=s.getObjectByName(a);r!==void 0?r.jointName=a:console.warn(`Couldn't find ${a} in ${g} hand mesh`),this.bones.push(r)})})}updateMesh(){const A=this.controller.joints;for(let e=0;e<this.bones.length;e++){const i=this.bones[e];if(i){const g=A[i.jointName];if(g.visible){const I=g.position;i.position.copy(I),i.quaternion.copy(g.quaternion)}}}}}const RiA=.01,UiA="index-finger-tip";class NiA extends fA{constructor(A,e=null){super(),this.controller=A,this.motionController=null,this.envMap=null,this.loader=e,this.mesh=null,A.addEventListener("connected",i=>{const g=i.data;g.hand&&!this.motionController&&(this.xrInputSource=g,this.motionController=new MiA(this,A,this.path,g.handedness,this.loader))}),A.addEventListener("disconnected",()=>{this.clear(),this.motionController=null})}updateMatrixWorld(A){super.updateMatrixWorld(A),this.motionController&&this.motionController.updateMesh()}getPointerPosition(){const A=this.controller.joints[UiA];return A?A.position:null}intersectBoxObject(A){const e=this.getPointerPosition();if(e){const i=new iI(e,RiA),g=new Fi().setFromObject(A);return i.intersectsBox(g)}else return!1}checkButton(A){this.intersectBoxObject(A)?A.onPress():A.onClear(),A.isPressed()&&A.whilePressed()}}const FiA=.05,M2=.02,Ww=.01,R2=.02,U2=1,BE=.4,KiA=.002,yl=.01,Vw=.003,N2=.035,Ut=16,vo=12,TR=110,JiA=new y(0,1,0),viA=new y(0,0,1),qiA=.02,biA=1.5;class LiA extends fA{constructor(A,e){super(),this.hand=A,this.controller=e,this.motionController=null,this.envMap=null,this.mesh=null,this.pointerGeometry=null,this.pointerMesh=null,this.pointerObject=null,this.pinched=!1,this.attached=!1,this.cursorObject=null,this.raycaster=null,this._onConnected=this._onConnected.bind(this),this._onDisconnected=this._onDisconnected.bind(this),this.hand.addEventListener("connected",this._onConnected),this.hand.addEventListener("disconnected",this._onDisconnected)}_onConnected(A){const e=A.data;e.hand&&(this.visible=!0,this.xrInputSource=e,this.createPointer())}_onDisconnected(){this.visible=!1,this.xrInputSource=null,this.pointerGeometry&&this.pointerGeometry.dispose(),this.pointerMesh&&this.pointerMesh.material&&this.pointerMesh.material.dispose(),this.clear()}_drawVerticesRing(A,e,i){const g=e.clone();for(let I=0;I<Ut;I++){g.applyAxisAngle(viA,Math.PI*2/Ut);const o=i*Ut+I;A[3*o]=g.x,A[3*o+1]=g.y,A[3*o+2]=g.z}}_updatePointerVertices(A){const e=this.pointerGeometry.attributes.position.array,i=new y(KiA,0,-1*(N2-A));this._drawVerticesRing(e,i,0);const g=new y(Math.sin(Math.PI*TR/180)*A,Math.cos(Math.PI*TR/180)*A,0);for(let a=0;a<vo;a++)this._drawVerticesRing(e,g,a+1),g.applyAxisAngle(JiA,Math.PI*TR/180/(vo*-2));const I=Ut*(1+vo),o=Ut*(1+vo)+1,s=new y(0,0,-1*(N2-A));e[I*3]=s.x,e[I*3+1]=s.y,e[I*3+2]=s.z;const C=new y(0,0,A);e[o*3]=C.x,e[o*3+1]=C.y,e[o*3+2]=C.z,this.pointerGeometry.setAttribute("position",new ae(e,3))}createPointer(){let A,e;const i=new Array(((vo+1)*Ut+2)*3).fill(0),g=[];for(this.pointerGeometry=new le,this.pointerGeometry.setAttribute("position",new ae(i,3)),this._updatePointerVertices(yl),A=0;A<vo;A++){for(e=0;e<Ut-1;e++)g.push(A*Ut+e,A*Ut+e+1,(A+1)*Ut+e),g.push(A*Ut+e+1,(A+1)*Ut+e+1,(A+1)*Ut+e);g.push((A+1)*Ut-1,A*Ut,(A+2)*Ut-1),g.push(A*Ut,(A+1)*Ut,(A+2)*Ut-1)}const I=Ut*(1+vo),o=Ut*(1+vo)+1;for(A=0;A<Ut-1;A++)g.push(I,A+1,A),g.push(o,A+Ut*vo,A+Ut*vo+1);g.push(I,0,Ut-1),g.push(o,Ut*(vo+1)-1,Ut*vo);const s=new rt;s.transparent=!0,s.opacity=BE,this.pointerGeometry.setIndex(g),this.pointerMesh=new uA(this.pointerGeometry,s),this.pointerMesh.position.set(0,0,-1*yl),this.pointerObject=new fA,this.pointerObject.add(this.pointerMesh),this.raycaster=new Ur;const C=new Wo(qiA,10,10),a=new rt;a.transparent=!0,a.opacity=BE,this.cursorObject=new uA(C,a),this.pointerObject.add(this.cursorObject),this.add(this.pointerObject),this.pointerObject.layers.mask=this.layers.mask,this.pointerMesh.layers.mask=this.layers.mask}_updateRaycaster(){if(this.raycaster){const A=this.pointerObject.matrixWorld,e=new NA;e.identity().extractRotation(A),this.raycaster.ray.origin.setFromMatrixPosition(A),this.raycaster.ray.direction.set(0,0,-1).applyMatrix4(e)}}_updatePointer(){this.pointerObject.visible=this.controller.visible;const A=this.hand.joints["index-finger-tip"],e=this.hand.joints["thumb-tip"],i=A.position.distanceTo(e.position),g=A.position.clone().add(e.position).multiplyScalar(.5);this.pointerObject.position.copy(g),this.pointerObject.quaternion.copy(this.controller.quaternion),this.pinched=i<=M2;const I=(i-Ww)/(FiA-Ww),o=(i-Ww)/(M2-Ww);if(I>1)this._updatePointerVertices(yl),this.pointerMesh.position.set(0,0,-1*yl),this.pointerMesh.material.opacity=BE;else if(I>0){const s=(yl-Vw)*I+Vw;this._updatePointerVertices(s),o<1?(this.pointerMesh.position.set(0,0,-1*s-(1-o)*R2),this.pointerMesh.material.opacity=BE+(1-o)*(U2-BE)):(this.pointerMesh.position.set(0,0,-1*s),this.pointerMesh.material.opacity=BE)}else this._updatePointerVertices(Vw),this.pointerMesh.position.set(0,0,-1*Vw-R2),this.pointerMesh.material.opacity=U2;this.cursorObject.material.opacity=this.pointerMesh.material.opacity}updateMatrixWorld(A){super.updateMatrixWorld(A),this.pointerGeometry&&(this._updatePointer(),this._updateRaycaster())}isPinched(){return this.pinched}setAttached(A){this.attached=A}isAttached(){return this.attached}intersectObject(A,e=!0){if(this.raycaster)return this.raycaster.intersectObject(A,e)}intersectObjects(A,e=!0){if(this.raycaster)return this.raycaster.intersectObjects(A,e)}checkIntersections(A,e=!1){if(this.raycaster&&!this.attached){const i=this.raycaster.intersectObjects(A,e),g=new y(0,0,-1);if(i.length>0){const I=i[0].distance;this.cursorObject.position.copy(g.multiplyScalar(I))}else this.cursorObject.position.copy(g.multiplyScalar(biA))}}setCursor(A){const e=new y(0,0,-1);this.raycaster&&!this.attached&&this.cursorObject.position.copy(e.multiplyScalar(A))}dispose(){this._onDisconnected(),this.hand.removeEventListener("connected",this._onConnected),this.hand.removeEventListener("disconnected",this._onDisconnected)}}const Ci={Handedness:Object.freeze({NONE:"none",LEFT:"left",RIGHT:"right"}),ComponentState:Object.freeze({DEFAULT:"default",TOUCHED:"touched",PRESSED:"pressed"}),ComponentProperty:Object.freeze({BUTTON:"button",X_AXIS:"xAxis",Y_AXIS:"yAxis",STATE:"state"}),ComponentType:Object.freeze({TRIGGER:"trigger",SQUEEZE:"squeeze",TOUCHPAD:"touchpad",THUMBSTICK:"thumbstick",BUTTON:"button"}),ButtonTouchThreshold:.05,AxisTouchThreshold:.1,VisualResponseProperty:Object.freeze({TRANSFORM:"transform",VISIBILITY:"visibility"})};async function F2(t){const A=await fetch(t);if(A.ok)return A.json();throw new Error(A.statusText)}async function xiA(t){if(!t)throw new Error("No basePath supplied");return await F2(`${t}/profilesList.json`)}async function TiA(t,A,e=null,i=!0){if(!t)throw new Error("No xrInputSource supplied");if(!A)throw new Error("No basePath supplied");const g=await xiA(A);let I;if(t.profiles.some(C=>{const a=g[C];return a&&(I={profileId:C,profilePath:`${A}/${a.path}`,deprecated:!!a.deprecated}),!!I}),!I){if(!e)throw new Error("No matching profile name found");const C=g[e];if(!C)throw new Error(`No matching profile name found and default profile "${e}" missing.`);I={profileId:e,profilePath:`${A}/${C.path}`,deprecated:!!C.deprecated}}const o=await F2(I.profilePath);let s;if(i){let C;if(t.handedness==="any"?C=o.layouts[Object.keys(o.layouts)[0]]:C=o.layouts[t.handedness],!C)throw new Error(`No matching handedness, ${t.handedness}, in profile ${I.profileId}`);C.assetPath&&(s=I.profilePath.replace("profile.json",C.assetPath))}return{profile:o,assetPath:s}}const YiA={xAxis:0,yAxis:0,button:0,state:Ci.ComponentState.DEFAULT};function HiA(t=0,A=0){let e=t,i=A;if(Math.sqrt(t*t+A*A)>1){const g=Math.atan2(A,t);e=Math.cos(g),i=Math.sin(g)}return{normalizedXAxis:e*.5+.5,normalizedYAxis:i*.5+.5}}class OiA{constructor(A){this.componentProperty=A.componentProperty,this.states=A.states,this.valueNodeName=A.valueNodeName,this.valueNodeProperty=A.valueNodeProperty,this.valueNodeProperty===Ci.VisualResponseProperty.TRANSFORM&&(this.minNodeName=A.minNodeName,this.maxNodeName=A.maxNodeName),this.value=0,this.updateFromComponent(YiA)}updateFromComponent({xAxis:A,yAxis:e,button:i,state:g}){const{normalizedXAxis:I,normalizedYAxis:o}=HiA(A,e);switch(this.componentProperty){case Ci.ComponentProperty.X_AXIS:this.value=this.states.includes(g)?I:.5;break;case Ci.ComponentProperty.Y_AXIS:this.value=this.states.includes(g)?o:.5;break;case Ci.ComponentProperty.BUTTON:this.value=this.states.includes(g)?i:0;break;case Ci.ComponentProperty.STATE:this.valueNodeProperty===Ci.VisualResponseProperty.VISIBILITY?this.value=this.states.includes(g):this.value=this.states.includes(g)?1:0;break;default:throw new Error(`Unexpected visualResponse componentProperty ${this.componentProperty}`)}}}class _iA{constructor(A,e){if(!A||!e||!e.visualResponses||!e.gamepadIndices||Object.keys(e.gamepadIndices).length===0)throw new Error("Invalid arguments supplied");this.id=A,this.type=e.type,this.rootNodeName=e.rootNodeName,this.touchPointNodeName=e.touchPointNodeName,this.visualResponses={},Object.keys(e.visualResponses).forEach(i=>{const g=new OiA(e.visualResponses[i]);this.visualResponses[i]=g}),this.gamepadIndices=Object.assign({},e.gamepadIndices),this.values={state:Ci.ComponentState.DEFAULT,button:this.gamepadIndices.button!==void 0?0:void 0,xAxis:this.gamepadIndices.xAxis!==void 0?0:void 0,yAxis:this.gamepadIndices.yAxis!==void 0?0:void 0}}get data(){return{id:this.id,...this.values}}updateFromGamepad(A){if(this.values.state=Ci.ComponentState.DEFAULT,this.gamepadIndices.button!==void 0&&A.buttons.length>this.gamepadIndices.button){const e=A.buttons[this.gamepadIndices.button];this.values.button=e.value,this.values.button=this.values.button<0?0:this.values.button,this.values.button=this.values.button>1?1:this.values.button,e.pressed||this.values.button===1?this.values.state=Ci.ComponentState.PRESSED:(e.touched||this.values.button>Ci.ButtonTouchThreshold)&&(this.values.state=Ci.ComponentState.TOUCHED)}this.gamepadIndices.xAxis!==void 0&&A.axes.length>this.gamepadIndices.xAxis&&(this.values.xAxis=A.axes[this.gamepadIndices.xAxis],this.values.xAxis=this.values.xAxis<-1?-1:this.values.xAxis,this.values.xAxis=this.values.xAxis>1?1:this.values.xAxis,this.values.state===Ci.ComponentState.DEFAULT&&Math.abs(this.values.xAxis)>Ci.AxisTouchThreshold&&(this.values.state=Ci.ComponentState.TOUCHED)),this.gamepadIndices.yAxis!==void 0&&A.axes.length>this.gamepadIndices.yAxis&&(this.values.yAxis=A.axes[this.gamepadIndices.yAxis],this.values.yAxis=this.values.yAxis<-1?-1:this.values.yAxis,this.values.yAxis=this.values.yAxis>1?1:this.values.yAxis,this.values.state===Ci.ComponentState.DEFAULT&&Math.abs(this.values.yAxis)>Ci.AxisTouchThreshold&&(this.values.state=Ci.ComponentState.TOUCHED)),Object.values(this.visualResponses).forEach(e=>{e.updateFromComponent(this.values)})}}class PiA{constructor(A,e,i){if(!A)throw new Error("No xrInputSource supplied");if(!e)throw new Error("No profile supplied");this.xrInputSource=A,this.assetUrl=i,this.id=e.profileId,this.layoutDescription=e.layouts[A.handedness],this.components={},Object.keys(this.layoutDescription.components).forEach(g=>{const I=this.layoutDescription.components[g];this.components[g]=new _iA(g,I)}),this.updateFromGamepad()}get gripSpace(){return this.xrInputSource.gripSpace}get targetRaySpace(){return this.xrInputSource.targetRaySpace}get data(){const A=[];return Object.values(this.components).forEach(e=>{A.push(e.data)}),A}updateFromGamepad(){Object.values(this.components).forEach(A=>{A.updateFromGamepad(this.xrInputSource.gamepad)})}}const jiA="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",WiA="generic-trigger";class ViA extends fA{constructor(){super(),this.motionController=null,this.envMap=null}setEnvironmentMap(A){return this.envMap==A?this:(this.envMap=A,this.traverse(e=>{e.isMesh&&(e.material.envMap=this.envMap,e.material.needsUpdate=!0)}),this)}updateMatrixWorld(A){super.updateMatrixWorld(A),this.motionController&&(this.motionController.updateFromGamepad(),Object.values(this.motionController.components).forEach(e=>{Object.values(e.visualResponses).forEach(i=>{const{valueNode:g,minNode:I,maxNode:o,value:s,valueNodeProperty:C}=i;g&&(C===Ci.VisualResponseProperty.VISIBILITY?g.visible=s:C===Ci.VisualResponseProperty.TRANSFORM&&(g.quaternion.slerpQuaternions(I.quaternion,o.quaternion,s),g.position.lerpVectors(I.position,o.position,s)))})}))}}function ziA(t,A){Object.values(t.components).forEach(e=>{const{type:i,touchPointNodeName:g,visualResponses:I}=e;if(i===Ci.ComponentType.TOUCHPAD)if(e.touchPointNode=A.getObjectByName(g),e.touchPointNode){const o=new Wo(.001),s=new rt({color:255}),C=new uA(o,s);e.touchPointNode.add(C)}else console.warn(`Could not find touch dot, ${e.touchPointNodeName}, in touchpad component ${e.id}`);Object.values(I).forEach(o=>{const{valueNodeName:s,minNodeName:C,maxNodeName:a,valueNodeProperty:r}=o;if(r===Ci.VisualResponseProperty.TRANSFORM){if(o.minNode=A.getObjectByName(C),o.maxNode=A.getObjectByName(a),!o.minNode){console.warn(`Could not find ${C} in the model`);return}if(!o.maxNode){console.warn(`Could not find ${a} in the model`);return}}o.valueNode=A.getObjectByName(s),o.valueNode||console.warn(`Could not find ${s} in the model`)})})}function K2(t,A){ziA(t.motionController,A),t.envMap&&A.traverse(e=>{e.isMesh&&(e.material.envMap=t.envMap,e.material.needsUpdate=!0)}),t.layers.mask!=0&&A.traverse(e=>{e.layers.mask=t.layers.mask}),t.add(A)}class ZiA{constructor(A=null){this.gltfLoader=A,this.path=jiA,this._assetCache={},this.gltfLoader||(this.gltfLoader=new OQ)}createControllerModel(A){const e=new ViA;let i=null;return A.addEventListener("connected",g=>{const I=g.data;I.targetRayMode!=="tracked-pointer"||!I.gamepad||TiA(I,this.path,WiA).then(({profile:o,assetPath:s})=>{e.motionController=new PiA(I,o,s);const C=this._assetCache[e.motionController.assetUrl];if(C)i=C.scene.clone(),K2(e,i);else{if(!this.gltfLoader)throw new Error("GLTFLoader not set.");this.gltfLoader.setPath(""),this.gltfLoader.load(e.motionController.assetUrl,a=>{this._assetCache[e.motionController.assetUrl]=a,i=a.scene.clone(),K2(e,i)},null,()=>{throw new Error(`Asset ${e.motionController.assetUrl} missing or malformed.`)})}}).catch(o=>{console.warn(o)})}),A.addEventListener("disconnected",()=>{e.motionController=null,e.remove(i),i=null}),e}}const Sl=CA("debugavatar");class zw{constructor(A,e,i,g){n(this,"root"),n(this,"head"),n(this,"leftHand"),n(this,"rigthHand");var I;this.root=A,this.head=e,this.leftHand=i,this.rigthHand=g,(I=this.root)==null||I.traverse(o=>o.layers.set(2))}get isValid(){return this.head!==null&&this.head!==void 0}}class Zw{constructor(){n(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 i=null;if(typeof e=="string"){if(i=await this.loadAvatar(A,e),!i){const I=new Ys;i=iA.instantiate(mQ(e,A.scene),I)}}else i=e;if(!i)return null;const g=this.findAvatar(i);return g.isValid?(Sl&&console.log("[Custom Avatar] valid config",e,Sl?g:""),g):(console.warn("[Custom Avatar] config isn't valid",e,Sl?g:""),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(Sl&&console.log("[Custom Avatar] "+e+", loading..."),e.endsWith(".glb")||(e+=".glb"),this.avatarRegistryUrl===null){const g=await fetch("./"+e);let I=null;if(g.ok){const s=await g.blob();s&&(I=await s.arrayBuffer())}if(!I&&(I=await vG(e,e,0,"no url here go away",!0),!I))return null;const o=await rs().parseSync(A,I,null,0);return o?.scene??null}const i=new OQ;return ol(i,A),new Promise((g,I)=>{const o=this.avatarRegistryUrl+"/"+e;i.load(o,async s=>{await rs().createBuiltinComponents(A,o,s,null,void 0),g(s.scene)},s=>{Sl&&console.log("[Custom Avatar] "+s.loaded/s.total*100+"% loaded of "+s.total/1024+"kB")},s=>{console.error("[Custom Avatar] Error when loading: "+s),g(null)})})}cacheModel(A,e){}findAvatar(A){const e=A;let i=e;i.children.length==1&&(i=A.children[0]);let g=this.findAvatarPart(i,["head"]);const I=this.findAvatarPart(i,["left","hand"]),o=this.findAvatarPart(i,["right","hand"]);if(!g){g=e;const s=new y;new Fi().setFromObject(g).getSize(s);const C=Math.max(s.x,s.y,s.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+C+" meters! Should be < 0.3m"),C>.3&&g.scale.multiplyScalar(1/C*.3)}return new zw(e,g,I,o)}findAvatarPart(A,e){const i=A.name.toLowerCase();let g=!0;for(const I of e){if(!g)break;i.indexOf(I)===-1&&(g=!1)}if(g)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 XiA=Object.defineProperty,$iA=Object.getOwnPropertyDescriptor,AgA=(t,A,e,i)=>{for(var g=i>1?void 0:i?$iA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&XiA(A,e,g),g};const QE=CA("debugflags");var fi=(t=>(t[t.Never=0]="Never",t[t.Browser=1]="Browser",t[t.AR=2]="AR",t[t.VR=4]="VR",t[t.FirstPerson=8]="FirstPerson",t[t.ThirdPerson=16]="ThirdPerson",t[t.All=4294967295]="All",t))(fi||{});const J2=class{constructor(){n(this,"Mask",17)}Has(t){return(this.Mask&t)!==0}Set(t){QE&&console.warn("Set XR flag state to",t),this.Mask=t,to.Apply()}Enable(t){this.Mask|=t,to.Apply()}Disable(t){this.Mask&=~t,to.Apply()}Toggle(t){this.Mask^=t,to.Apply()}EnableAll(){this.Mask=-1,to.Apply()}DisableAll(){this.Mask=0,to.Apply()}};let eo=J2;n(eo,"Global",new J2);var fl;const Ca=(fl=class extends JA{constructor(){super(...arguments),n(this,"visibleIn")}static Apply(){for(const t of this.registry)t.UpdateVisible(eo.Global)}awake(){Ca.registry.push(this)}onEnable(){Ca.firstApply?this.UpdateVisible(eo.Global):(Ca.firstApply=!0,Ca.Apply())}onDestroy(){const t=Ca.registry.indexOf(this);t>=0&&Ca.registry.splice(t,1)}get isOn(){return this.gameObject.visible}UpdateVisible(t=null){let A;const e=t;e&&typeof e=="number"&&(console.assert(typeof e=="number","XRFlag.UpdateVisible: state must be a number",e),QE&&console.log(e),Ca.buffer.Mask=e,t=Ca.buffer);const i=t;if(i?(QE&&console.warn(this.name,"use passed in mask",i.Mask,this.visibleIn),A=i.Has(this.visibleIn)):(QE&&console.log(this.name,"use global mask"),eo.Global.Has(this.visibleIn)),A!==void 0)if(A)QE&&console.log(this.name,"is visible",this.gameObject.uuid),iA.setActive(this.gameObject,!0);else{if(QE&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},n(fl,"registry",[]),n(fl,"firstApply"),n(fl,"buffer",new eo),fl);let to=Ca;AgA([w()],to.prototype,"visibleIn",2);const Sn=CA("debugavatar"),Zs=class extends JA{constructor(){super(...arguments),n(this,"connectionId"),n(this,"avatar")}static getAvatar(t){return t>=0&&t<Zs.instances.length?Zs.instances[t]:null}static onAvatarMarkerCreated(t){return Zs._onNewAvatarMarkerAdded.push(t),t}static onAvatarMarkerDestroyed(t){return Zs._onAvatarMarkerDestroyed.push(t),t}awake(){Zs.instances.push(this),Sn&&console.log(this);for(const t of Zs._onNewAvatarMarkerAdded)t({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){Zs.instances.splice(Zs.instances.indexOf(this),1);for(const t of Zs._onAvatarMarkerDestroyed)t({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}setVisible(t){this.avatar&&("setVisible"in this.avatar?this.avatar.setVisible(t):iA.setActive(this.avatar,t))}};let Wg=Zs;n(Wg,"instances",[]),n(Wg,"_onNewAvatarMarkerAdded",[]),n(Wg,"_onAvatarMarkerDestroyed",[]);const Xw=class{constructor(t,A,e){n(this,"_isVisible",!0),n(this,"guid"),n(this,"root",null),n(this,"head",null),n(this,"handLeft",null),n(this,"handRight",null),n(this,"lastUpdate",-1),n(this,"isLocalAvatar",!1),n(this,"flags",null),n(this,"headScale",new y(1,1,1)),n(this,"handLeftScale",new y(1,1,1)),n(this,"handRightScale",new y(1,1,1)),n(this,"webxr"),n(this,"lastAvatarId",null),n(this,"hasAvatarOverride",!1),n(this,"context"),n(this,"avatarMarker",null),n(this,"_headTarget",new fA),n(this,"_handLeftTarget",new fA),n(this,"_handRightTarget",new fA),n(this,"_canInterpolate",!1),this.context=t,this.guid=A,this.webxr=e,this.setupCustomAvatar(this.webxr.defaultAvatar)}setVisible(t){this._isVisible=t,this.updateVisibility()}get isWebXRAvatar(){return!0}updateFlags(){if(!this.flags)return;let t=this.isLocalAvatar?fi.FirstPerson:fi.ThirdPerson;this.context.isInVR?t|=fi.VR:this.context.isInAR?t|=fi.AR:t|=fi.Browser;for(const A of this.flags)A.gameObject.visible=!0,A.UpdateVisible(t)}async setAvatarOverride(t){return this.hasAvatarOverride=t!==null,this.hasAvatarOverride&&this.lastAvatarId!==t&&(this.lastAvatarId=t,t!=null&&t.length>0)?await this.setupCustomAvatar(t):null}tryUpdate(t,A){if(t.guid===this.guid&&(this.lastAvatarId!==t.avatarId&&t.avatarId&&t.avatarId.length>0&&(this.lastAvatarId=t.avatarId,this.setupCustomAvatar(t.avatarId)),this.lastUpdate=t.time,this.head)){const e=this.webxr.IsInAR?Ps.Handheld:Ps.Headset,i=this.head;this.context.players.setPlayerView(t.guid,i,e),Xg.markDirty(this.head),this._canInterpolate=!0;const g=this.isLocalAvatar?this.head:this._headTarget;if(g.position.set(t.position.x,t.position.y,t.position.z),g.quaternion.set(t.rotation.x,t.rotation.y,t.rotation.z,t.rotation.w),g.scale.set(t.scale,t.scale,t.scale),g.scale.multiply(this.headScale),this.handLeft){const I=this.isLocalAvatar?this.handLeft:this._handLeftTarget;I.position.set(t.posLeftHand.x,t.posLeftHand.y,t.posLeftHand.z),I.quaternion.set(t.rotLeftHand._x,t.rotLeftHand._y,t.rotLeftHand._z,t.rotLeftHand._w),I.quaternion.multiply(Xw.invertRotation),I.scale.set(t.scale,t.scale,t.scale),I.scale.multiply(this.handLeftScale),Xg.markDirty(this.handLeft)}if(this.handRight){const I=this.isLocalAvatar?this.handRight:this._handRightTarget;I.position.set(t.posRightHand.x,t.posRightHand.y,t.posRightHand.z),I.quaternion.set(t.rotRightHand._x,t.rotRightHand._y,t.rotRightHand._z,t.rotRightHand._w),I.quaternion.multiply(Xw.invertRotation),I.scale.set(t.scale,t.scale,t.scale),I.scale.multiply(this.handRightScale),Xg.markDirty(this.handRight)}}}update(){if(this.isLocalAvatar||!this._canInterpolate)return;const t=this.context.time.deltaTime/.1;this.head&&(this.head.position.lerp(this._headTarget.position,t),this.head.quaternion.slerp(this._headTarget.quaternion,t),this.head.scale.lerp(this._headTarget.scale,t)),this.handLeft&&this._handLeftTarget&&(this.handLeft.position.lerp(this._handLeftTarget.position,t),this.handLeft.quaternion.slerp(this._handLeftTarget.quaternion,t),this.handLeft.scale.lerp(this._handLeftTarget.scale,t)),this.handRight&&this._handRightTarget&&(this.handRight.position.lerp(this._handRightTarget.position,t),this.handRight.quaternion.slerp(this._handRightTarget.quaternion,t),this.handRight.scale.lerp(this._handRightTarget.scale,t))}destroy(){var t,A;Sn&&console.log("Destroy avatar",this.guid),(t=this.root)==null||t.removeFromParent(),(A=this.avatarMarker)==null||A.destroy(),this.lastAvatarId=null,this.head&&cI.Remove(this.context,this.head)}updateVisibility(){const t=this.root;t&&iA.setActive(t,this._isVisible)}async setupCustomAvatar(t){var A,e,i;if(Sn&&console.log("LOAD",t,this),!t||typeof t=="string"&&t.length<=0)return!1;this.head&&cI.Remove(this.context,this.head);const g=t;if(g?.loadAssetAsync!==void 0){await g.loadAssetAsync();const o=g.asset;iA.setActive(o,!1),t=iA.instantiate(o),iA.setActive(t,!0)}Sn&&console.log(t);const I=await Xw.loader.getOrCreateNewAvatarInstance(this.context,t);if(Sn&&console.log(I,I?.isValid,this.lastAvatarId,t),I!=null&&I.isValid){if(this.root=I.root,this.root.position.set(0,0,0),this.root.quaternion.set(0,0,0,1),this.root.scale.set(1,1,1),this.avatarMarker=iA.addNewComponent(this.root,Wg),this.avatarMarker.connectionId=this.guid,this.avatarMarker.avatar=this,this.head&&this.head!==I.head&&((A=this.head)==null||A.removeFromParent()),this.head=I.head,this.headScale.copy(this.head.scale),this.head&&!this.isLocalAvatar&&cI.Add(this.context,this.head,this.avatarMarker),I.leftHand&&((e=this.handLeft)==null||e.removeFromParent()),this.handLeft=I.leftHand??this.handLeft,this.handLeft?this.handLeftScale.copy(this.handLeft.scale):this.handLeftScale.set(1,1,1),I.rigthHand&&((i=this.handRight)==null||i.removeFromParent()),this.handRight=I.rigthHand??this.handRight,this.handRight?this.handRightScale.copy(this.handRight.scale):this.handRightScale.set(1,1,1),this.context.scene.add(this.root),this.flags==null&&(this.flags=[]),this.flags.length=0,this.flags.push(...iA.getComponentsInChildren(this.root,to)),this.flags.length<=0&&this.head){const o=iA.addNewComponent(this.head,to);o.visibleIn=fi.ThirdPerson|fi.VR,this.flags.push(o),Sn&&console.log("Added flag to head: "+o.visibleIn,this.head.name)}return Sn&&console.log("[Avatar], is Local? ",this.isLocalAvatar,this.root),this.updateFlags(),this.updateVisibility(),!0}else return Sn&&console.warn("build avatar failed"),!1}};let fn=Xw;n(fn,"loader",new Zw),n(fn,"invertRotation",new UA().setFromAxisAngle(new y(0,1,0),Math.PI));class cI{static Add(A,e,i=null){if(e){for(const g of this.Pois)if(g.obj===e)return;this.Pois.push({obj:e,avatar:i}),this.LastChangeTime=A.time.time}}static Remove(A,e){var i;if(e){for(const g of this.Pois)if(g.obj===e){this.Pois.splice(this.Pois.indexOf(g),1),this.LastChangeTime=A?.time.time??((i=qe.Current)==null?void 0:i.time.time);return}}}}n(cI,"Pois",[]),n(cI,"LastChangeTime",0);class egA{constructor(){n(this,"guid"),n(this,"position",new y)}}class ml extends JA{constructor(){super(...arguments),n(this,"target",null),n(this,"avatar",null),n(this,"_model",null),n(this,"_targetModel",new egA),n(this,"_currentTargetObject",null),n(this,"_lastUpdateTime",0),n(this,"_lookDuration",0),n(this,"_lastPoiChangedTime",0)}set controlledTarget(A){this.target=A;const e=z.get("MoveRandom");if(e&&this.target){const i=iA.getComponent(this.target,e);i&&i.destroy()}}awake(){if(this.avatar=iA.getComponentInParent(this.gameObject,Wg),this.avatar){const A=iA.getComponentInParent(this.gameObject,Wg);this._model=new rD(this.context.connection,this.guid),A!=null&&A.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",A=>{var e;this.target&&A&&A.guid===((e=this.avatar)==null?void 0:e.guid)&&ui(this.target,A.position)})}update(){var A;if((!this.context.connection.isConnected||(A=this._model)!=null&&A.hasOwnership)&&(cI.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=cI.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){const e=he(this._currentTargetObject);ui(this.target,e),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(e))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;const A=cI.Pois;if(A.length>0){const e=A[Math.floor(Math.random()*A.length)];if(e&&e.obj){if(e.avatar&&e.avatar===this.avatar)return;this._currentTargetObject=e.obj}}}}}class EE extends JA{constructor(){super(...arguments),n(this,"canGrab",!0)}onPointerClick(A){}}class hE extends JA{constructor(){super(...arguments),n(this,"isUsed",!0),n(this,"usedBy",null)}}var ng=(t=>(t[t.Average=0]="Average",t[t.Multiply=1]="Multiply",t[t.Minimum=2]="Minimum",t[t.Maximum=3]="Maximum",t))(ng||{}),$w=(t=>(t[t.Discrete=0]="Discrete",t[t.Continuous=1]="Continuous",t))($w||{}),mi=(t=>(t[t.None=0]="None",t[t.FreezePositionX=2]="FreezePositionX",t[t.FreezePositionY=4]="FreezePositionY",t[t.FreezePositionZ=8]="FreezePositionZ",t[t.FreezePosition=14]="FreezePosition",t[t.FreezeRotationX=16]="FreezeRotationX",t[t.FreezeRotationY=32]="FreezeRotationY",t[t.FreezeRotationZ=64]="FreezeRotationZ",t[t.FreezeRotation=112]="FreezeRotation",t[t.FreezeAll=126]="FreezeAll",t))(mi||{}),cE=(t=>(t[t.None=0]="None",t[t.X=2]="X",t[t.Y=4]="Y",t[t.Z=8]="Z",t[t.All=-1]="All",t))(cE||{});const mg=function(t,A){return function(e,i,g){tgA(e,i,g,t,A)}};function tgA(t,A,e,i,g){if(!g&&!i&&!t.onValidate)return;if(e!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",t,A,e),di("Invalid usage of validate decorator. Only fields can be validated. Property: "+A,So.Error);return}let I="";if(typeof A=="string"?I=A:I=A.name,t.__internalAwake){const o=Symbol(I),s=t.__internalAwake;t.__internalAwake=function(){var C;if(!this.onValidate){Ye()&&console.warn('Usage of @validate decorate detected but there is no onValidate method in your class: "'+((C=t.constructor)==null?void 0:C.name)+'"');return}if(this[o]===void 0){this[o]=this[I];const a=this[I];if(a instanceof eA||a instanceof y||a instanceof ie||a instanceof UA){const r=this[I];ak(r,()=>{this.onValidate(I)})}Object.defineProperty(this,I,{set:function(r){var B;if(this[rG]===!0)this[o]=r;else{i?.call(this,r);const Q=this[o];this[o]=r,(B=this.onValidate)==null||B.call(this,I,Q)}},get:function(){return g?.call(this),this[o]}})}s.call(this)}}}const igA=function(t){return function(A,e,i){let g="";typeof e=="string"?g=e:g=e.name;const I=t.prototype,o=Object.getOwnPropertyDescriptor(I,g);if(!(o!=null&&o.value)){console.warn("Can not apply prefix: type does not have method named",e,t);return}const s=o.value,C=A[g];Object.defineProperty(I,g,{value:function(...a){const r=C?.call(this,...a);if(r instanceof Promise){r.then(B=>{if(B!==!1)return s.call(this,...a)});return}if(r!==!1)return s.call(this,...a)}})}};var ggA=Object.defineProperty,IgA=Object.getOwnPropertyDescriptor,qo=(t,A,e,i)=>{for(var g=i>1?void 0:i?IgA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&ggA(A,e,g),g};class ogA{constructor(A,e){n(this,"positionChanged",!1),n(this,"rotationChanged",!1),n(this,"position"),n(this,"quaternion"),n(this,"_positionKeys",["x","y","z"]),n(this,"_quaternionKeys",["_x","_y","_z","_w"]),n(this,"mute",!1),n(this,"context"),n(this,"obj"),n(this,"_positionWatch"),n(this,"_rotationWatch"),this.context=e,this.obj=A}get isDirty(){return this.positionChanged||this.rotationChanged}reset(A=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,A){if(this.position)for(const e of this._positionKeys)delete this.position[e];if(this.quaternion)for(const e of this._quaternionKeys)delete this.quaternion[e]}}syncValues(){for(const A of this._positionKeys)this.position[A]=this.obj.position[A];for(const A of this._quaternionKeys)this.quaternion[A]=this.obj.quaternion[A]}applyValues(){if(this.positionChanged&&this.position)for(const A of this._positionKeys){const e=this.position[A];e!==void 0&&(this.obj.position[A]=e)}if(this.rotationChanged&&this.quaternion)for(const A of this._quaternionKeys){const e=this.quaternion[A];e!==void 0&&(this.obj.quaternion[A]=e)}}start(A,e){this.reset(),A&&(this._positionWatch||(this._positionWatch=new Ma(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((I,o)=>{var s;if((s=this.context.physics.engine)!=null&&s.isUpdating||this.mute)return;const C=this.position[o];Math.abs(C-I)<1e-5||(this.position[o]=I,this.positionChanged=!0)})),e&&(this._rotationWatch||(this._rotationWatch=new Ma(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((I,o)=>{var s;if((s=this.context.physics.engine)!=null&&s.isUpdating||this.mute)return;const C=this.quaternion[o];Math.abs(C-I)<1e-5||(this.quaternion[o]=I,this.rotationChanged=!0)}));const i=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),g=new NA;this.obj.matrixWorld.multiplyMatrices=(I,o)=>(g.equals(I)||(this.positionChanged=!0,this.rotationChanged=!0,g.copy(I)),i(I,o))}stop(){var A,e;(A=this._positionWatch)==null||A.revoke(),(e=this._rotationWatch)==null||e.revoke()}}var YR;const HR=(YR=class extends JA{constructor(){super(...arguments),n(this,"autoMass",!0),n(this,"_mass",0),n(this,"useGravity",!0),n(this,"constraints",mi.None),n(this,"isKinematic",!1),n(this,"drag",0),n(this,"angularDrag",1),n(this,"detectCollisions",!0),n(this,"sleepThreshold",.01),n(this,"collisionDetectionMode",$w.Discrete),n(this,"_gravityScale",1),n(this,"dominanceGroup",0),n(this,"_propertiesChanged",!1),n(this,"_currentVelocity",new y),n(this,"_smoothedVelocity",new y),n(this,"_smoothedVelocityGetter",new y),n(this,"_lastPosition",new y),n(this,"_watch")}set mass(t){t!==this._mass&&(this._mass=t,this._propertiesChanged=!0,this.__didAwake&&(this.autoMass=!1))}get mass(){var t,A;return this.autoMass?((A=(t=this.context.physics.engine)==null?void 0:t.getBody(this))==null?void 0:A.mass())??-1:this._mass}get lockPositionX(){return(this.constraints&mi.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&mi.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&mi.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&mi.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&mi.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&mi.FreezeRotationZ)!==0}set lockPositionX(t){t?this.constraints|=mi.FreezePositionX:this.constraints&=~mi.FreezePositionX}set lockPositionY(t){t?this.constraints|=mi.FreezePositionY:this.constraints&=~mi.FreezePositionY}set lockPositionZ(t){t?this.constraints|=mi.FreezePositionZ:this.constraints&=~mi.FreezePositionZ}set lockRotationX(t){t?this.constraints|=mi.FreezeRotationX:this.constraints&=~mi.FreezeRotationX}set lockRotationY(t){t?this.constraints|=mi.FreezeRotationY:this.constraints&=~mi.FreezeRotationY}set lockRotationZ(t){t?this.constraints|=mi.FreezeRotationZ:this.constraints&=~mi.FreezeRotationZ}set gravityScale(t){this._gravityScale=t}get gravityScale(){return this._gravityScale}awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new ogA(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),og.LateUpdate)}onDisable(){var t,A;(t=this._watch)==null||t.stop(),(A=this.context.physics.engine)==null||A.removeBody(this)}onDestroy(){var t;(t=this.context.physics.engine)==null||t.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){for(var t,A,e,i;;)this._propertiesChanged&&(this._propertiesChanged=!1,(t=this.context.physics.engine)==null||t.updateProperties(this)),(A=this._watch)!=null&&A.isDirty?(this._watch.mute=!0,this._watch.applyValues(),(e=this.context.physics.engine)==null||e.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):(i=this._watch)==null||i.syncValues(),this.captureVelocity(),yield}teleport(t,A=!0){var e;(e=this._watch)==null||e.reset(!0),A?this.gameObject.position.set(t.x,t.y,t.z):this.setWorldPosition(t.x,t.y,t.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(t=!0){var A;(A=this.context.physics.engine)==null||A.resetForces(this,t)}resetTorques(t=!0){var A;(A=this.context.physics.engine)==null||A.resetTorques(this,t)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){var t;(t=this.context.physics.engine)==null||t.wakeup(this)}applyForce(t,A,e=!0){var i;(i=this.context.physics.engine)==null||i.addForce(this,t,e)}applyImpulse(t,A=!0){var e;(e=this.context.physics.engine)==null||e.applyImpulse(this,t,A)}setForce(t,A,e,i=!0){var g,I,o;(g=this.context.physics.engine)==null||g.resetForces(this,i),typeof t=="number"?(A??(A=0),e??(e=0),(I=this.context.physics.engine)==null||I.addForce(this,{x:t,y:A,z:e},i)):(o=this.context.physics.engine)==null||o.addForce(this,t,i)}getVelocity(){var t;const A=(t=this.context.physics.engine)==null?void 0:t.getLinearVelocity(this);return A?(this._currentVelocity.x=A.x,this._currentVelocity.y=A.y,this._currentVelocity.z=A.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(t,A,e,i=!0){var g,I;if(t instanceof y){const o=t;(g=this.context.physics.engine)==null||g.setLinearVelocity(this,o,i);return}A===void 0||e===void 0||(I=this.context.physics.engine)==null||I.setLinearVelocity(this,{x:t,y:A,z:e},i)}getAngularVelocity(){var t;const A=(t=this.context.physics.engine)==null?void 0:t.getAngularVelocity(this);return A?(this._currentVelocity.x=A.x,this._currentVelocity.y=A.y,this._currentVelocity.z=A.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setAngularVelocity(t,A,e,i=!0){var g,I;if(t instanceof y){const o=t;(g=this.context.physics.engine)==null||g.setAngularVelocity(this,o,i);return}A===void 0||e===void 0||(I=this.context.physics.engine)==null||I.setAngularVelocity(this,{x:t,y:A,z:e},i)}setTorque(t,A,e){this.setAngularVelocity(t,A,e)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(t=null){}captureVelocity(){const t=he(this.gameObject);HR.tempPosition.copy(t);const A=t.sub(this._lastPosition);this._lastPosition.copy(HR.tempPosition),this._smoothedVelocity.lerp(A,this.context.time.deltaTime/.1)}},n(YR,"tempPosition",new y),YR);let Kt=HR;qo([mg()],Kt.prototype,"autoMass",2),qo([w()],Kt.prototype,"mass",1),qo([mg(),w()],Kt.prototype,"useGravity",2),qo([mg(),w()],Kt.prototype,"constraints",2),qo([mg(),w()],Kt.prototype,"isKinematic",2),qo([mg(),w()],Kt.prototype,"drag",2),qo([mg(),w()],Kt.prototype,"angularDrag",2),qo([mg(),w()],Kt.prototype,"detectCollisions",2),qo([mg(),w()],Kt.prototype,"sleepThreshold",2),qo([mg(),w()],Kt.prototype,"collisionDetectionMode",2),qo([mg()],Kt.prototype,"_gravityScale",2),qo([mg()],Kt.prototype,"dominanceGroup",2);class io{constructor(){n(this,"bb",null),n(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}static sizeOf(){return 12}static createVec3(A,e,i,g){return A.prep(4,12),A.writeFloat32(g),A.writeFloat32(i),A.writeFloat32(e),A.offset()}}class v2{constructor(){n(this,"bb",null),n(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}position(A){return(A||new io).__init(this.bb_pos,this.bb)}rotation(A){return(A||new io).__init(this.bb_pos+12,this.bb)}scale(A){return(A||new io).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(A,e,i,g,I,o,s,C,a,r){return A.prep(4,36),A.prep(4,12),A.writeFloat32(r),A.writeFloat32(a),A.writeFloat32(C),A.prep(4,12),A.writeFloat32(s),A.writeFloat32(o),A.writeFloat32(I),A.prep(4,12),A.writeFloat32(g),A.writeFloat32(i),A.writeFloat32(e),A.offset()}}class Fa{constructor(){n(this,"bb",null),n(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}static getRootAsSyncedTransformModel(A,e){return(e||new Fa).__init(A.readInt32(A.position())+A.position(),A)}static getSizePrefixedRootAsSyncedTransformModel(A,e){return A.setPosition(A.position()+Zu),(e||new Fa).__init(A.readInt32(A.position())+A.position(),A)}guid(A){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,A):null}fast(){const A=this.bb.__offset(this.bb_pos,6);return A?!!this.bb.readInt8(this.bb_pos+A):!1}transform(A){const e=this.bb.__offset(this.bb_pos,8);return e?(A||new v2).__init(this.bb_pos+e,this.bb):null}dontSave(){const A=this.bb.__offset(this.bb_pos,10);return A?!!this.bb.readInt8(this.bb_pos+A):!1}static startSyncedTransformModel(A){A.startObject(4)}static addGuid(A,e){A.addFieldOffset(0,e,0)}static addFast(A,e){A.addFieldInt8(1,+e,0)}static addTransform(A,e){A.addFieldStruct(2,e,0)}static addDontSave(A,e){A.addFieldInt8(3,+e,0)}static endSyncedTransformModel(A){return A.endObject()}static finishSyncedTransformModelBuffer(A,e){A.finish(e)}static finishSizePrefixedSyncedTransformModelBuffer(A,e){A.finish(e,void 0,!0)}}const mn=CA("debugsync"),kl="STRS";$u(kl,Fa.getRootAsSyncedTransformModel);const Xs=new Qh;function q2(t,A,e=!0){Xs.clear();const i=Xs.createString(t);Fa.startSyncedTransformModel(Xs),Fa.addGuid(Xs,i),Fa.addFast(Xs,e);const g=A.worldPosition,I=A.worldEuler,o=A.gameObject.scale;Fa.addTransform(Xs,v2.createTransform(Xs,g.x,g.y,g.z,I.x,I.y,I.z,o.x,o.y,o.z));const s=Fa.endSyncedTransformModel(Xs);return Xs.finish(s,kl),Xs.asUint8Array()}class kn extends JA{constructor(){super(...arguments),n(this,"overridePhysics",!0),n(this,"interpolatePosition",!0),n(this,"interpolateRotation",!0),n(this,"fastMode",!1),n(this,"syncDestroy",!1),n(this,"_model",null),n(this,"_needsUpdate",!0),n(this,"rb",null),n(this,"_wasKinematic",!1),n(this,"_receivedDataBefore",!1),n(this,"_targetPosition"),n(this,"_targetRotation"),n(this,"_receivedFastUpdate",!1),n(this,"_shouldRequestOwnership",!1),n(this,"joinedRoomCallback",null),n(this,"receivedDataCallback",null),n(this,"tempEuler",new Ag),n(this,"receivedUpdate",!1),n(this,"lastWorldPos"),n(this,"lastWorldRotation")}requestOwnership(){mn&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}hasOwnership(){var A;return((A=this._model)==null?void 0:A.hasOwnership)??void 0}isOwned(){var A;return(A=this._model)==null?void 0:A.isOwned}awake(){mn&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new y,this._targetRotation=new UA,this.lastWorldPos=new y,this.lastWorldRotation=new UA,this.rb=iA.getComponentInChildren(this.gameObject,Kt),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new rD(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(Lt.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(kl,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&uL(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(Lt.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(kl,this.receivedDataCallback)}tryGetLastState(){const A=this.context.connection.tryGetState(this.guid);A&&this.onReceivedData(A)}onReceivedData(A){var e;if(!this.destroyed&&typeof A.guid=="function"&&A.guid()===this.guid){mn&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,A),this.receivedUpdate=!0,this._receivedFastUpdate=A.fast();const i=A.transform();if(i){Xg.markDirty(this.gameObject,!0);const g=i.position();g&&(this.interpolatePosition&&((e=this._targetPosition)==null||e.set(g.x(),g.y(),g.z())),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(g.x(),g.y(),g.z()));const I=i.rotation();I&&(this.tempEuler.set(I.x(),I.y(),I.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&Gk(this.gameObject,this.tempEuler))}this._receivedDataBefore=!0}}onEnable(){this.lastWorldPos.copy(this.worldPosition),this.lastWorldRotation.copy(this.worldQuaternion),this._needsUpdate=!0,this._model&&this._model.updateIsOwned()}onDisable(){this._model&&this._model.freeOwnership()}onBeforeRender(){if(!this.activeAndEnabled||!this.context.connection.isConnected)return;if(!this.context.connection.isInRoom||!this._model){mn&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());const A=this.worldPosition,e=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){const I=A.distanceTo(this.lastWorldPos),o=e.angleTo(this.lastWorldRotation),s=this._model.hasOwnership||this.fastMode?1e-4:.001;(I>s||o>s)&&(this._model.hasOwnership?this._needsUpdate=!0:(mn&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastWorldPos),this.worldPosition=this.lastWorldPos,A.copy(this.lastWorldPos),this.worldQuaternion=this.lastWorldRotation,e.copy(this.lastWorldRotation),Xg.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const I=this._receivedFastUpdate||this.fastMode?.5:.3;let o=!1;if(this.interpolatePosition&&this._targetPosition){const s=this.worldPosition;s.lerp(this._targetPosition,I),this.worldPosition=s,o=!0}if(this.interpolateRotation&&this._targetRotation){const s=this.worldQuaternion;s.slerp(this._targetRotation,I),this.worldQuaternion=s,o=!0}o&&Xg.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastWorldPos.copy(A),this.lastWorldRotation.copy(e),!this._model)return;if(!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership){this.rb&&(this.rb.isKinematic=this._model.isOwned??!1,this.rb.setVelocity(0,0,0));return}this.rb&&(this._wasKinematic!==void 0&&(mn&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic),this.gameObject.position.distanceTo(new y(0,0,0))>1e3&&(mn&&console.log("RESET",this.name),this.gameObject.position.set(0,1,0),this.rb.setVelocity(0,0,0)));const i=10,g=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%i===0||g)){mn&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this.overridePhysics&&this.rb,this._needsUpdate=!1;const I=q2(this.guid,this,!!g);this.context.connection.sendBinary(I)}}}const sgA=CA("debugshadowcomponents");uR.prototype.interactable={get(){return this.interactive},set(t){this.interactable=t}};const bo=Symbol("shadowDomOwner");class Ms extends JA{constructor(){super(...arguments),n(this,"shadowComponent",null),n(this,"_controlsChildLayout",!0),n(this,"_root"),n(this,"_parentComponent")}isRoot(){var A;return((A=this.Root)==null?void 0:A.gameObject)===this.gameObject}get canvas(){const A=this.Root;return A!=null&&A.isCanvas?A:null}markDirty(){go.markUIDirty(this.context)}get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(A){this._controlsChildLayout=A,this.shadowComponent&&(this.shadowComponent.autoLayout=A)}get Root(){return this._root===void 0&&(this._root=iA.getComponentInParent(this.gameObject,Gl)),this._root}get Canvas(){return this.canvas}__internalNewInstanceCreated(){super.__internalNewInstanceCreated(),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0}onEnable(){super.onEnable()}addShadowComponent(A,e){var i;this.removeShadowComponent();const g=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=iA.getComponentInParent(g,Ms),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}A.name=this.name+" ("+(this.constructor.name??"UI")+")",A.autoLayout=this._parentComponent.controlsChildLayout,A[bo]=this,this.setShadowComponentOwner(A);let I=!1;if(((i=this.Root)==null?void 0:i.gameObject)===this.gameObject)this.gameObject.add(A);else{const o=this._parentComponent.shadowComponent;o&&(o?.add(A),I=!0)}this.shadowComponent=A,e&&e.shadowComponent&&this.shadowComponent&&e.shadowComponent.add(this.shadowComponent),xc&&A.add(new fQ(.5)),this.onAfterAddedToScene(),I&&jH(),sgA&&console.log(this.shadowComponent)}set(A){}setShadowComponentOwner(A){if(A&&(A[bo]===void 0||A[bo]===this)&&(A[bo]=this,A.children))for(const e of A.children)this.setShadowComponentOwner(e)}traverseOwnedShadowComponents(A,e,i){if(A&&A[bo]===e){i(A);for(const g of A.children)this.traverseOwnedShadowComponents(g,e,i)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(A){this.shadowComponent&&(this.shadowComponent.interactable=A)}}class Gl extends Ms{awake(){super.awake()}}class lE{static getObject(A){const e=A[bo];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 i=this.tryFindCanvasGroup(A);if(i?.isCanvasGroup===!0&&(e&&(e.canvasGroup=i),i.blocksRaycasts===!1||i.interactable===!1))return!1;const g=Yr(A,I=>{if(I.isGraphic===!0)return I},!1);return e&&g?.isGraphic===!0&&(e.graphic=g),!(g?.raycastTarget===!1||g?.layer===2)}static tryFindCanvasGroup(A){if(!A)return null;const e=Yr(A,i=>{const g=i;if(g.blocksRaycasts!==void 0&&g.interactable!==void 0)return g},!1);return e!==void 0?e:this.tryFindCanvasGroup(A.parent)}}const Ml=CA("debugwebxrcontroller");var dE=(t=>(t[t.PhysicalDevice=0]="PhysicalDevice",t[t.Touch=1]="Touch",t))(dE||{}),aa=(t=>(t.SelectStart="select-start",t.SelectEnd="select-end",t.Update="update",t))(aa||{});class Ay extends JA{}const kg=class extends JA{constructor(){super(...arguments),n(this,"webXR"),n(this,"index",-1),n(this,"controllerModel"),n(this,"controller"),n(this,"controllerGrip"),n(this,"hand"),n(this,"handPointerModel"),n(this,"grabbed",null),n(this,"input",null),n(this,"type",0),n(this,"showRaycastLine",!0),n(this,"enableRaycasts",!0),n(this,"enableDefaultControls",!0),n(this,"_wristQuaternion",null),n(this,"movementVector",new y),n(this,"worldRot",new UA),n(this,"joystick",new eA),n(this,"didRotate",!1),n(this,"didTeleport",!1),n(this,"didChangeScale",!1),n(this,"lastHit",null),n(this,"raycastLine",null),n(this,"_raycastHitPoint",null),n(this,"_connnectedCallback",null),n(this,"_disconnectedCallback",null),n(this,"_selectStartEvt",null),n(this,"_selectEndEvt",null),n(this,"_selectionPressed",!1),n(this,"_selectionPressedLastFrame",!1),n(this,"_selectionStartTime",0),n(this,"_selectionEndTime",0),n(this,"_useSmoothing",!0),n(this,"_isConnected",!1),n(this,"rayRotation",new UA),n(this,"_pinchStartTime"),n(this,"selectStartCallback",null),n(this,"lastSelectStartObject",null),n(this,"_didNotEndSelection",!1),n(this,"closeGrabBoundingBoxHelper")}static CreateRaycastLine(){const t=new ci(this.geometry),A=t.material;return A.color=this.raycastColor,t.layers.set(2),t.name="line",t.scale.z=1,t}static CreateRaycastHitPoint(){const t=new Wo(.5,22,22),A=new rt({color:this.raycastColor}),e=new uA(t,A);return e.visible=!1,e.layers.set(2),e}static Create(t,A,e,i){const g=e?iA.addNewComponent(e,kg,!1):new kg;g.webXR=t,g.index=A,g.type=i;const I=t.context;g.controller=I.renderer.xr.getController(A),g.controllerGrip=I.renderer.xr.getControllerGrip(A),g.controllerModel=this.Factory.createControllerModel(g.controller),g.controllerGrip.add(g.controllerModel),g.hand=I.renderer.xr.getHand(A);const o=new OQ;ol(o,I),g.webXR.handModelPath&&g.webXR.handModelPath!==""?o.setPath(FC(t.sourceId,g.webXR.handModelPath)):o.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/");const s=new NiA(g.hand,o);return g.hand.add(s),g.hand.traverse(C=>C.layers.set(2)),g.handPointerModel=new LiA(g.hand,g.controller),g.controller.addEventListener("connected",C=>{g.setControllerLayers(g.controllerModel,2),g.setControllerLayers(g.controllerGrip,2),g.setControllerLayers(g.hand,2),setTimeout(()=>{g.setControllerLayers(g.controllerModel,2),g.setControllerLayers(g.controllerGrip,2),g.setControllerLayers(g.hand,2)},1e3)}),g.hand.addEventListener("connected",C=>{var a;if(C.data.hand){t.Rig&&t.Rig.add(g.hand),g.type=0,g.handPointerModel.traverse(B=>B.layers.set(2)),(a=g.handPointerModel.pointerObject)==null||a.traverse(B=>B.layers.set(2));const r=g.hand.joints;if(r)for(const B of Object.keys(r)){const Q=r[B];Q.parent||g.hand.add(Q)}}}),g}static addEventListener(t,A){const e=this.eventSubs[t]??[];e.push(A),this.eventSubs[t]=e}static removeEventListener(t,A){if(!A)return;const e=this.eventSubs[t]??[],i=e.indexOf(A);i>=0&&e.splice(i,1),this.eventSubs[t]=e}get isUsingHands(){var t;return((t=this.input)==null?void 0:t.hand)!=null}get wrist(){if(!this.hand)return null;const t=this.hand.joints;return t?t.wrist:null}getWristQuaternion(){const t=this.wrist;return t?(this._wristQuaternion||(this._wristQuaternion=new UA),Mt(t).multiply(this._wristQuaternion.setFromEuler(new Ag(-Math.PI/4,0,0)))):null}get selectionDown(){return this._selectionPressed&&!this._selectionPressedLastFrame}get selectionUp(){return!this._selectionPressed&&this._selectionPressedLastFrame}get selectionPressed(){return this._selectionPressed}get selectionClick(){return this._selectionEndTime-this._selectionStartTime<.3}get raycastHitPoint(){return this._raycastHitPoint}get useSmoothing(){return this._useSmoothing}awake(){if(!this.controller){console.warn("WebXRController: Missing controller object.",this);return}this._connnectedCallback=this.onSourceConnected.bind(this),this._disconnectedCallback=this.onSourceDisconnected.bind(this),this._selectStartEvt=this.onSelectStart.bind(this),this._selectEndEvt=this.onSelectEnd.bind(this),this.type===1&&(this.controllerGrip.addEventListener("connected",this._connnectedCallback),this.controllerGrip.addEventListener("disconnected",this._disconnectedCallback),this.controller.addEventListener("selectstart",this._selectStartEvt),this.controller.addEventListener("selectend",this._selectEndEvt)),this.type===0&&(this.controller.addEventListener("selectstart",this._selectStartEvt),this.controller.addEventListener("selectend",this._selectEndEvt))}onDestroy(){var t,A,e;this.type===1&&(this.controllerGrip.removeEventListener("connected",this._connnectedCallback),this.controllerGrip.removeEventListener("disconnected",this._disconnectedCallback),this.controller.removeEventListener("selectstart",this._selectStartEvt),this.controller.removeEventListener("selectend",this._selectEndEvt)),this.type===0&&(this.controller.removeEventListener("selectstart",this._selectStartEvt),this.controller.removeEventListener("selectend",this._selectEndEvt)),(t=this.hand)==null||t.clear(),(A=this.controllerGrip)==null||A.clear(),(e=this.controller)==null||e.clear()}onEnable(){var t,A,e,i,g;if(!this.webXR){console.warn("No WebXR component assigned to WebXRController.");return}this.hand&&(this.hand.name="Hand"),this.controllerGrip&&(this.controllerGrip.name="ControllerGrip"),this.controller&&(this.controller.name="Controller"),this.raycastLine&&(this.raycastLine.name="RaycastLine;"),this.webXR.Controllers.indexOf(this)<0&&this.webXR.Controllers.push(this),this.raycastLine||(this.raycastLine=kg.CreateRaycastLine()),this._raycastHitPoint||(this._raycastHitPoint=kg.CreateRaycastHitPoint()),(t=this.webXR.Rig)==null||t.add(this.hand),(A=this.webXR.Rig)==null||A.add(this.controllerGrip),(e=this.webXR.Rig)==null||e.add(this.controller),(i=this.webXR.Rig)==null||i.add(this.raycastLine),(g=this.raycastLine)==null||g.add(this._raycastHitPoint),this._raycastHitPoint.visible=!1,this.hand.add(this.handPointerModel),Ml&&console.log("ADDED TO RIG",this.webXR.Rig)}onDisable(){var t,A,e,i,g;if((t=this.hand)==null||t.removeFromParent(),(A=this.controllerGrip)==null||A.removeFromParent(),(e=this.controller)==null||e.removeFromParent(),(i=this.raycastLine)==null||i.removeFromParent(),(g=this._raycastHitPoint)==null||g.removeFromParent(),this.webXR){const I=this.webXR.Controllers.indexOf(this);I>=0&&this.webXR.Controllers.splice(I,1)}}onSourceConnected(t){if(this._isConnected){console.warn("Received connected event for controller that is already connected",this.index,t);return}this._isConnected=!0,this.input=t.data,this.type===1&&this.onSelectStart()}onSourceDisconnected(t){if(!this._isConnected){console.warn("Received discnnected event for controller that is not connected",t);return}this._isConnected=!1,this.type===1&&this.onSelectEnd(),this.input=null}createPointerEvent(t){switch(t){case"down":this.context.input.createPointerDown(new qC(pi.PointerDown,null,{clientX:0,clientY:0,button:this.index,pointerType:MQ.Touch}));break;case"move":break;case"up":this.context.input.createPointerUp(new qC(pi.PointerUp,null,{clientX:0,clientY:0,button:this.index,pointerType:MQ.Touch}));break}}raycastUpdate(t,A){const e=this.showRaycastLine&&this.type!==1;if(this.type===1)t.visible=!1;else if(this.isUsingHands){t.visible=!this.grabbed&&e,ui(t,A);const i=this.hand.joints;if(i&&i.wrist&&this.grabbed&&this.grabbed.isCloseGrab){const g=this.getWristQuaternion();g&&this.rayRotation.copy(g)}CI(t,this.rayRotation)}else t.visible=e,CI(t,this.rayRotation),ui(t,A)}update(){if(!this.webXR)return;this.context.time.frameCount%60===0&&(this.setControllerLayers(this.controller,2),this.setControllerLayers(this.controllerGrip,2),this.setControllerLayers(this.hand,2));const t=kg.eventSubs.update;if(t&&t.length>0)for(const i of t)i(this);let A=1;this.type===0?A=this.context.time.deltaTime/.1:this.isUsingHands&&this.handPointerModel.pinched&&(A=this.context.time.deltaTime/.3),this.rayRotation.slerp(Mt(this.controller),this.useSmoothing?A:1);const e=he(this.controller);this.isUsingHands&&this.handPointerModel.cursorObject&&(this.handPointerModel.cursorObject.visible=!1),this.enableRaycasts?(this.raycastLine&&this.raycastUpdate(this.raycastLine,e),this.lastHit=this.updateLastHit(),this.grabbed&&this.grabbed.update()):this.raycastLine&&(this.raycastLine.visible=!1),this._selectionPressedLastFrame=this._selectionPressed,this.selectStartCallback&&this.selectStartCallback()}onUpdate(t){var A,e;if(this.lastHit=null,!t||t.inputSources.length<=this.index){this.input=null;return}if(this.type===0&&(this.input=t.inputSources[this.index]),!this.input)return;const i=this.webXR.Rig;if(!i)return;this._didNotEndSelection&&!this.handPointerModel.pinched&&(this._didNotEndSelection=!1,this.onSelectEnd()),this.updateStick(this.input);const g=(e=(A=this.input)==null?void 0:A.gamepad)==null?void 0:e.buttons;if(this.enableDefaultControls)switch(this.input.handedness){case"left":this.movementUpdate(i,g);break;case"right":this.rotationUpdate(i,g);break}}movementUpdate(t,A){const e=3*kg.MovementSpeedFactor,i=2,g=oe.clamp01(this.joystick.length()*2),I=this.joystick.x>0?1:-1;let o=Math.pow(this.joystick.x,i);o*=I,o*=g;const s=this.joystick.y>0?1:-1;let C=Math.pow(this.joystick.y,i);C*=s,o*=g,t.getWorldQuaternion(this.worldRot),this.movementVector.set(o,0,C),this.movementVector.applyQuaternion(this.webXR.TransformOrientation),this.movementVector.y=0,this.movementVector.applyQuaternion(this.worldRot),this.movementVector.multiplyScalar(e*this.context.time.deltaTime),t.position.add(this.movementVector),this.isUsingHands&&this.runTeleport(t,A)}rotationUpdate(t,A){const e=this.joystick.x,i=Math.abs(e);if(i<.4)this.didRotate=!1;else if(i>.5&&!this.didRotate){const g=e>0?-1:1;t.rotateY(oe.toRadians(30*g)),this.didRotate=!0}this.runTeleport(t,A)}runTeleport(t,A){var e,i;let g=-this.joystick.y;if((e=this.hand)!=null&&e.visible&&!this.grabbed){const r=this.handPointerModel.isPinched();r&&this._pinchStartTime===void 0&&(this._pinchStartTime=this.context.time.time),r&&this._pinchStartTime&&this.context.time.time-this._pinchStartTime>.8&&(g=this.handPointerModel.isPinched()?1:0),r||(this._pinchStartTime=void 0)}else this._pinchStartTime=void 0;const I=this.webXR.IsInVR,o=this.webXR.Rig;let s=g>.5&&I,C=o?((i=o?.scale)==null?void 0:i.x)<.999:!1,a=null;if(A&&this.input&&!this.input.hand)for(let r=0;r<A.length;r++){const B=A[r];if(r===4)if(B.pressed&&!this.didChangeScale&&I){this.didChangeScale=!0;const Q=o;if(Q){const E=this.switchScale(Q,s,C,a);s=E.doTeleport,C=E.isInMiniatureMode,a=E.newRigScale}}else B.pressed||(this.didChangeScale=!1)}if(s){if(!this.didTeleport){const r=this.raycast();if(this.didTeleport=!0,r&&r.length>0){const B=r[0];if(C||this.isValidTeleportTarget(B.object)){const Q=B.point;ui(t,Q)}}}}else g<.1&&(this.didTeleport=!1);a!==null&&(t.scale.set(a,a,a),t.updateMatrixWorld())}isValidTeleportTarget(t){return iA.getComponentInParent(t,Ay)!=null}switchScale(t,A,e,i){if(e){e=!1,t.scale.set(1,1,1),i=1,kg.MovementSpeedFactor=1;const g=this.context.mainCamera;kg.PreviousCameraFarDistance&&(g.far=kg.PreviousCameraFarDistance)}else{e=!0,A=!0,i=.1,kg.MovementSpeedFactor=i*2;const g=this.context.mainCamera;kg.PreviousCameraFarDistance=g.far,g.far/=i}return{doTeleport:A,isInMiniatureMode:e,newRigScale:i}}updateStick(t){var A;!t||!t.gamepad||((A=t.gamepad.axes)==null?void 0:A.length)<4||(this.joystick.x=t.gamepad.axes[2],this.joystick.y=t.gamepad.axes[3])}updateLastHit(){var t;const A=this.raycast(),e=A?A[0]:null;this.lastHit=e;let i=1;if(this.webXR.Rig&&(i/=this.webXR.Rig.scale.x),this.raycastLine){this.raycastLine.scale.z=i*(((t=this.lastHit)==null?void 0:t.distance)??9999);const g=this.raycastLine.material;e!=null?g.color=kg.raycastColor:g.color=kg.raycastNoHitColor}if(this._raycastHitPoint){if(this.lastHit!=null){this._raycastHitPoint.position.z=-1;const g=oe.clamp(this.lastHit.distance*.01*i,.015,.1);this._raycastHitPoint.scale.set(g,g,g)}this._raycastHitPoint.visible=this.lastHit!==null&&this.lastHit!==void 0}return e}onSelectStart(){this.context.connection.allowEditing&&(this.selectStartCallback=()=>this.onHandleSelectStart())}onHandleSelectStart(){this.selectStartCallback=null,this._selectionPressed=!0,this._selectionStartTime=this.context.time.time,this._selectionEndTime=1e3;let t=null,A=!1;if(this.isUsingHands?(t=this.overlap(),t.length<=0?(t=this.raycast(),A=!1):A=!0):t=this.raycast(),Ml&&console.log("onHandleSelectStart","close grab? "+A,"intersections",t),t&&t.length>0)for(const e of t){const i=e.object;this.lastSelectStartObject=i;const g={selected:i,grab:i},I=kg.eventSubs["select-start"];if(I&&I.length>0)for(const o of I)o(this,g);g.grab!==i&&Ml&&console.log("Grabbed object changed","original",i,"new",g.grab),g.grab&&(this.grabbed=$s.TryTake(this,g.grab,e,A));break}else{const e=kg.eventSubs["select-start"],i={selected:null,grab:null};if(e&&e.length>0)for(const g of e)g(this,i)}}onSelectEnd(){var t;if(this.isUsingHands&&this.handPointerModel.pinched){this._didNotEndSelection=!0;return}if(!this._selectionPressed)return;this.selectStartCallback=null,this._selectionPressed=!1,this._selectionEndTime=this.context.time.time;const A={grab:((t=this.grabbed)==null?void 0:t.selected)??this.lastSelectStartObject},e=kg.eventSubs["select-end"];if(e&&e.length>0)for(const i of e)i(this,A);this.grabbed&&(this.grabbed.free(),this.grabbed=null)}testIsVisible(t){return!(!t||iA.isActiveInHierarchy(t)===!1||lE.isInteractable(t)===!1)}setControllerLayers(t,A){var e,i;if(t&&(t.layers.set(A),t.children))for(const g of t.children)((e=this.grabbed)==null?void 0:e.selected)===g||((i=this.grabbed)==null?void 0:i.selectedMesh)===g||this.setControllerLayers(g,A)}getRay(){const t=new As;return t.origin.copy(he(this.controller)),t.direction.set(0,0,-1).applyQuaternion(this.rayRotation),t}overlap(){const t=this.isUsingHands&&this.handPointerModel?this.handPointerModel.pointerObject:this.controllerGrip;if(Ml&&(!this.closeGrabBoundingBoxHelper&&t&&(this.closeGrabBoundingBoxHelper=new Lu(t,16776960),this.scene.add(this.closeGrabBoundingBoxHelper)),this.closeGrabBoundingBoxHelper&&t&&this.closeGrabBoundingBoxHelper.setFromObject(t)),!t)return new Array;const A=he(t).clone();return this.context.physics.sphereOverlap(A,.02)}raycast(){const t=new zI;t.layerMask=new Yg,t.layerMask.enableAll(),t.layerMask.disable(2),t.ray=this.getRay();const A=this.context.physics.raycast(t);for(let e=0;e<A.length;e++){const i=A[e],g=i.object;if(!this.testIsVisible(g)){A.splice(e,1),e--;continue}i.object=lE.getObject(g);break}return A}};let bi=kg;n(bi,"Factory",new ZiA),n(bi,"raycastColor",new yA(.9,.3,.3)),n(bi,"raycastNoHitColor",new yA(.6,.6,.6)),n(bi,"geometry",new le().setFromPoints([new y(0,0,0),new y(0,0,-1)])),n(bi,"handModels",{}),n(bi,"eventSubs",{}),n(bi,"PreviousCameraFarDistance"),n(bi,"MovementSpeedFactor",1);var ey=(t=>(t.WillTake="WillTake",t.DidTake="DidTake",t.WillFree="WillFree",t.DidFree="DidFree",t))(ey||{});const NI=class{constructor(){n(this,"sync",null),n(this,"selected",null),n(this,"selectedParent",null),n(this,"selectedMesh",null),n(this,"controller",null),n(this,"grabTime",0),n(this,"grabUUID",""),n(this,"isCloseGrab",!1),n(this,"originalMaterial",null),n(this,"usageMarker",null),n(this,"rigidbodies",null),n(this,"didReparent",!1),n(this,"grabDistance",0),n(this,"interactable",null),n(this,"positionSource",null),n(this,"grabPoint",new y),n(this,"localPositionOffsetToGrab",null),n(this,"localPositionOffsetToGrab_worldSpace",new y),n(this,"localQuaternionToGrab",new UA(0,0,0,1)),n(this,"targetDir",null),n(this,"quaternionLerp",null),n(this,"controllerDir",new y),n(this,"controllerWorldPos",new y),n(this,"lastControllerWorldPos",new y),n(this,"controllerPosDelta",new y),n(this,"totalChangeAlongDirection",0),n(this,"rigPositionLastFrame",new y)}static AddEventListener(t,A){return NI.Events[t]||(NI.Events[t]=[]),NI.Events[t].push(A),A}static RemoveEventListener(t,A){if(!A||!NI.Events[t])return;const e=NI.Events[t].indexOf(A);e>=0&&NI.Events[t].splice(e,1)}static Register(t){this.Current.find(A=>A===t)||this.Current.push(t)}static Remove(t){const A=this.Current.indexOf(t);A>=0&&this.Current.splice(A,1)}static TryTake(t,A,e,i){const g=iA.getComponentInParent(A,EE);if(g)A=g.gameObject;else return Ml&&console.warn("Prevented taking object that is not interactable",A),null;let I=A;const o=iA.getComponentInParent(A,kn);o&&(o.requestOwnership(),I=o.gameObject);for(const C of this.Current)if(C.selected===I)return C.controller===t||(C.free(),C.Take(t,I,A,o,g,e,i)),C;const s=new NI;return s.Take(t,I,A,o,g,e,i),s}Take(t,A,e,i,g,I,o){var s,C;if(console.assert(A!==null,"Expected object to be taken but was",A),t.isUsingHands?this.positionSource=o?t.wrist:t.controller:this.positionSource=t.controller,!this.positionSource)return console.warn("No position source"),this;const a={controller:t,take:A,hit:e,sync:i,interactable:g};(s=NI.Events.WillTake)==null||s.forEach(h=>h(this,a));const r=e;r!=null&&r.material&&(this.originalMaterial=r.material,Array.isArray(r.material)||(r.material=r.material.clone(),r.material&&r.material.emissive&&(r.material.emissive.b=.2))),this.selected=A,this.selectedParent||(this.selectedParent=A.parent),this.selectedMesh=r,this.controller=t,this.interactable=g,this.isCloseGrab=o,this.didReparent=!1,this.sync=i,this.grabTime=t.context.time.time,this.grabUUID=Date.now().toString(),this.usageMarker=iA.addNewComponent(this.selected,hE),this.rigidbodies=iA.getComponentsInChildren(this.selected,Kt),he(this.positionSource,this.lastControllerWorldPos);const B=()=>o?this.lastControllerWorldPos.clone():I.point.clone();this.grabDistance=B().distanceTo(this.lastControllerWorldPos),this.totalChangeAlongDirection=0,this.localPositionOffsetToGrab=this.selected.worldToLocal(B());const Q=t.isUsingHands&&o?this.controller.getWristQuaternion().clone():t.rayRotation.clone();Mt(this.selected,this.localQuaternionToGrab).premultiply(Q.invert());const E=this.controller.webXR.Rig;return E&&this.rigPositionLastFrame.copy(he(E)),cI.Add(t.context,this.selected),NI.Register(this),this.sync&&(this.sync.fastMode=!0),(C=NI.Events.DidTake)==null||C.forEach(h=>h(this,a)),this}free(){var t,A,e,i;if(!this.selected)return;const g={controller:this.controller,take:this.selected,hit:this.selected,sync:this.sync,interactable:null};(t=NI.Events.WillFree)==null||t.forEach(s=>s(this,g)),cI.Remove(this.controller.context,this.selected),NI.Remove(this),this.sync&&(this.sync.fastMode=!1);const I=this.selectedMesh;I&&this.originalMaterial&&I.material&&(I.material=this.originalMaterial);const o=this.selected;if(this.didReparent&&o.parent){const s=this.selectedParent;s?s.attach(o):(A=this.controller)==null||A.context.scene.attach(o)}if((e=this.usageMarker)==null||e.destroy(),this.controller&&(this.controller.grabbed=null),this.selected=null,this.selectedParent=null,this.selectedMesh=null,this.sync=null,this.rigidbodies)for(const s of this.rigidbodies)s.wakeUp(),s.setVelocity(s.smoothedVelocity);this.rigidbodies=null,this.localPositionOffsetToGrab=null,this.quaternionLerp=null,(i=NI.Events.DidFree)==null||i.forEach(s=>s(this,g))}controllerMovementSinceLastFrame(){if(!this.positionSource||!this.controller)return 0;this.controllerDir.set(0,0,-1),this.controllerDir.applyQuaternion(this.controller.rayRotation),he(this.positionSource,this.controllerWorldPos),this.controllerPosDelta.copy(this.controllerWorldPos),this.controllerPosDelta.sub(this.lastControllerWorldPos),this.lastControllerWorldPos.copy(this.controllerWorldPos);const t=this.controller.webXR.Rig;if(t){const A=he(t),e=this.rigPositionLastFrame.sub(A);this.controllerPosDelta.add(e),this.rigPositionLastFrame.copy(A)}return this.controllerDir.dot(this.controllerPosDelta)}update(){var t;if(this.rigidbodies)for(const A of this.rigidbodies)A.resetVelocities();if(this.sync&&this.controller&&this.controller.context.connection.isInRoom&&this.controller.context.time.time-this.grabTime>3&&this.sync.hasOwnership()===!1&&(console.log("no ownership, will leave",this.sync.guid),this.free()),!(this.interactable&&!this.interactable.canGrab)){if(!this.didReparent&&this.selected&&this.controller){const A=((t=this.controller.webXR.Rig)==null?void 0:t.scale.x)??1;this.totalChangeAlongDirection+=this.controllerMovementSinceLastFrame();let e=1;this.controller.type===0&&(e=Math.max(0,1+this.totalChangeAlongDirection*2/A),e=e*e*e),this.grabDistance/A<.8&&(e=1),this.targetDir||(this.targetDir=new y),this.targetDir.set(0,0,-this.grabDistance*e);const i=this.targetDir.applyQuaternion(this.controller.rayRotation).add(this.controllerWorldPos),g=this.controller.rayRotation.clone().multiplyQuaternions(this.controller.rayRotation,this.localQuaternionToGrab);this.quaternionLerp||(this.quaternionLerp=g.clone()),this.quaternionLerp.slerp(g,this.controller.useSmoothing?this.controller.context.time.deltaTime/.03:1),CI(this.selected,this.quaternionLerp),this.selected.updateWorldMatrix(!1,!1),this.grabPoint.copy(i),this.localPositionOffsetToGrab&&(this.localPositionOffsetToGrab_worldSpace.copy(this.localPositionOffsetToGrab),this.selected.localToWorld(this.localPositionOffsetToGrab_worldSpace).sub(he(this.selected)),i.sub(this.localPositionOffsetToGrab_worldSpace)),ui(this.selected,i)}if(this.rigidbodies!=null)for(const A of this.rigidbodies)A.wakeUp();Xg.markDirty(this.selected,!0)}}};let $s=NI;n($s,"Events",{}),n($s,"Current",[]);class Ra{constructor(A,e){n(this,"used",!1),n(this,"inputSource"),n(this,"object"),n(this,"point"),n(this,"normal"),n(this,"face"),n(this,"distance"),n(this,"instanceId"),n(this,"pointerId"),n(this,"isDown"),n(this,"isUp"),n(this,"isPressed"),n(this,"isClicked"),n(this,"button"),n(this,"input"),n(this,"_event"),this._event=e,this.input=A,this.button=e?.button??0}use(){this.used=!0,this.pointerId!==void 0&&this.input.setPointerUsed(this.pointerId)}stopPropagation(){var A;(A=this._event)==null||A.stopImmediatePropagation()}Use(){this.use()}StopPropagation(){var A;(A=this._event)==null||A.stopImmediatePropagation()}get event(){return this._event}clone(){const A=new Ra(this.input,this._event);return Object.assign(A,this),A}}function OR(t){return iA.foreachComponent(t,A=>{const e=A;if(e.onPointerDown||e.onPointerUp||e.onPointerEnter||e.onPointerExit||e.onPointerClick)return!0},!1)===!0}var CgA=Object.defineProperty,agA=Object.getOwnPropertyDescriptor,ngA=(t,A,e,i)=>{for(var g=i>1?void 0:i?agA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(g=(i?o(A,e,g):o(g))||g);return i&&g&&CgA(A,e,g),g};class Gn extends JA{awake(){go.createIfNoneExists(this.context)}onEnable(){var A;(A=go.get(this.context))==null||A.register(this)}onDisable(){var A;(A=go.get(this.context))==null||A.unregister(this)}performRaycast(A=null){return null}}class ws extends Gn{constructor(){super(...arguments),n(this,"targets",null),n(this,"raycastHits",[]),n(this,"ignoreSkinnedMeshes",!1)}start(){this.targets=[this.gameObject]}performRaycast(A=null){if(!this.targets)return null;A??(A=new zI),A.targets=this.targets,A.results=this.raycastHits;const e=A.testObject;this.ignoreSkinnedMeshes&&(A.testObject=g=>g instanceof gs?"continue in children":e?e(g):!0);const i=this.context.physics.raycast(A);return A.testObject=e,i}}ngA([w()],ws.prototype,"ignoreSkinnedMeshes",2);class ty extends ws{constructor(){super(),this.ignoreSkinnedMeshes=!0}}function iy(t){return t[bo]||(t.parent?iy(t.parent):null)}function rgA(t){return t.isUI===!0||typeof t[bo]=="object"}function gy(t,A){if(!t)return;const e=t.material;if(e?.isMaterial===!0){const i=t.parent;i&&i.isText,e.side=A.doubleSided??!0?yt:Lg,e.shadowSide=A.doubleSided?yt:Lg,t.castShadow=A.castShadows?A.castShadows:!1,t.receiveShadow=A.receiveShadows?A.receiveShadows:!1}for(const i of t.children)gy(i,A)}function pE(t,A,e){t[A]===void 0&&console.warn("Field",A,"is undefined on",t);const i=Proxy.revocable(t[A],{set(o,s,C,a){const r=o[s],B=Reflect.set(o,s,C,a);return e(C,r),B}}),g=i.revoke,I=t[A];return i.revoke=()=>{t[A]=I,g()},t[A]=i.proxy,i}const b2=Symbol("Scheduled action");function BgA(t,A,e=og.OnBeforeRender){let i=t[b2];i||(i=t[b2]={});const g=A.name;i[e]||(i[e]={});const I=i[e];if(I[g])return;function*o(){A?.call(t),I[g]=null}const s=t.startCoroutine(o(),e);I[g]=s}const eB=CA("debugeventsystem");var _R=(t=>(t.BeforeHandleInput="BeforeHandleInput",t.AfterHandleInput="AfterHandleInput",t))(_R||{});const na=class extends JA{constructor(){super(),n(this,"raycaster",[]),n(this,"_selectStartFn"),n(this,"_selectEndFn"),n(this,"_selectUpdateFn"),n(this,"_handleEventCycleFn"),n(this,"_handleInputFn"),n(this,"pressedByID",new Map),n(this,"hoveredByID",new Map),n(this,"_sortedHits",[]),n(this,"_testObjectsCache",new Map),n(this,"shouldRaycastObject",t=>{var A;let e=null;if(rgA(t)&&(e=(A=t[bo])==null?void 0:A.gameObject),this._testObjectsCache.has(t)||e&&this._testObjectsCache.has(e))return this._testObjectsCache.get(t)===!1?"continue in children":!0;{let i=OR(t);return!i&&e&&(i=OR(e)),i?(this._testObjectsCache.set(t,!0),t.traverse(g=>{this._testObjectsCache.set(g,!0)}),!0):(this._testObjectsCache.set(t,!1),"continue in children")}}),n(this,"_sortingBuffer",[]),n(this,"_noDepthTestingResults",[]),n(this,"out",{}),n(this,"currentActiveMeshUIComponents",[]),na.systems.push(this)}static createIfNoneExists(t){this.didSearchEventSystem||(this.didSearchEventSystem=!0,na.systems.length<=0&&na.systems.push(...iA.findObjectsOfType(na,t)));for(const e of na.systems)if(e.context===t)return;const A=new fA;iA.addNewComponent(A,na),t.scene.add(A)}static get systems(){const t=qe.Current;return this._eventSystemMap.has(t)||this._eventSystemMap.set(t,[]),this._eventSystemMap.get(t)}static get(t){const A=this._eventSystemMap.get(t);return A&&A.length>0?A[0]:null}static get instance(){return this.systems[0]}static ensureUpdateMeshUI(t,A,e=!1){ra.update(t,A,e)}static markUIDirty(t){ra.markDirty()}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}onDestroy(){na.systems.splice(na.systems.indexOf(this),1)}start(){if(this.raycaster.length<=0&&!iA.findObjectOfType(Gn,this.context)){const t=iA.addNewComponent(this.context.scene,ws);t.ignoreSkinnedMeshes=!0,this.raycaster.push(t),(Ye()||eB)&&console.warn("Added an ObjectRaycaster to the scene because no raycaster was found. Skinnedmeshes will be ignored for better performance")}}register(t){var A;t&&this.raycaster&&!this.raycaster.includes(t)&&((A=this.raycaster)==null||A.push(t))}unregister(t){var A,e;const i=(A=this.raycaster)==null?void 0:A.indexOf(t);i!==void 0&&i!==-1&&((e=this.raycaster)==null||e.splice(i,1))}onEnable(){const t=new Map;this._selectStartFn??(this._selectStartFn=(e,i)=>{if(!i.grab)return;ra.resetLastSelected();const g=new Ra(this.context.input);g.inputSource=e,g.pointerId=0,g.isDown=e.selectionDown,g.isUp=e.selectionUp,g.isPressed=e.selectionPressed,g.isClicked=!1,t.set(e,i.grab),i.grab&&!this.handleEventOnObject(i.grab,g)&&(i.grab=null)}),this._selectEndFn??(this._selectEndFn=(e,i)=>{var g;if(!i.grab)return;const I=new Ra(this.context.input);I.inputSource=e,I.pointerId=0,I.isDown=e.selectionDown,I.isUp=e.selectionUp,I.isPressed=e.selectionPressed,I.isClicked=e.selectionClick,this.handleEventOnObject(i.grab,I);const o=t.get(e);if(t.set(e,null),o)for(const s of this.pressedByID.keys()){const C=this.pressedByID[s];C.obj===o&&C.handler&&((g=C.handler.onPointerUp)==null||g.call(C.handler,I),this.pressedByID.delete(s))}});const A=new zI;this._selectUpdateFn??(this._selectUpdateFn=e=>{var i;A.ray=e.getRay();const g=this.performRaycast(A);if(!g)return;const I=new Ra(this.context.input);I.inputSource=e,I.pointerId=((i=e.input)==null?void 0:i.handedness)==="right"?0:1,I.isDown=e.selectionDown,I.isUp=e.selectionUp,I.isPressed=e.selectionPressed,I.isClicked=!1,this.handleIntersections(g,I)}),bi.addEventListener(aa.SelectStart,this._selectStartFn),bi.addEventListener(aa.SelectEnd,this._selectEndFn),bi.addEventListener(aa.Update,this._selectUpdateFn),this._handleInputFn=this.onPointerEvent.bind(this),this.context.input.addEventListener(pi.PointerDown,this._handleInputFn),this.context.input.addEventListener(pi.PointerUp,this._handleInputFn),this.context.input.addEventListener(pi.PointerMove,this._handleInputFn)}onDisable(){bi.removeEventListener(aa.SelectStart,this._selectStartFn),bi.removeEventListener(aa.SelectEnd,this._selectEndFn),bi.removeEventListener(aa.Update,this._selectUpdateFn),this.context.input.removeEventListener(pi.PointerDown,this._handleInputFn),this.context.input.removeEventListener(pi.PointerUp,this._handleInputFn),this.context.input.removeEventListener(pi.PointerMove,this._handleInputFn)}onBeforeRender(){this.resetMeshUIStates()}onPointerEvent(t){if(t===void 0)return;const A=t.pointerType==MQ.Touch?t.button:0,e=new Ra(this.context.input,t);e.inputSource=this.context.input,e.pointerId=t.button,e.isClicked=t.type==pi.PointerUp&&this.context.input.getPointerClicked(t.button),e.isDown=t.type==pi.PointerDown,e.isUp=t.type==pi.PointerUp,e.isPressed=this.context.input.getPointerPressed(t.button),eB&&e.isClicked&&console.log("CLICK",e.pointerId);const i=new zI;i.screenPoint=this.context.input.getPointerPositionRC(A);const g=this.performRaycast(i);if(!g)return;eB&&e.isClicked&&di("EventSystem: "+e.pointerId+" - "+this.context.time.frame+" - Up:"+e.isUp+", Down:"+e.isDown);const I={sender:this,args:e,hasActiveUI:this.currentActiveMeshUIComponents.length>0};if(this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:I})),!this.handleIntersections(g,e)){const o=this.hoveredByID.get(A);if(o&&this.triggerOnExit(o.obj,o.data),this.hoveredByID.delete(A),e.isUp){const s=this.pressedByID.get(A);s?.handlers.forEach(C=>{var a;return(a=C.onPointerUp)==null?void 0:a.call(C,e)}),this.pressedByID.delete(A)}}this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:I}))}performRaycast(t){if(!this.raycaster)return null;this._sortedHits.length=0,t||(t=new zI),this._testObjectsCache.clear(),t.testObject=this.shouldRaycastObject;for(const A of this.raycaster){if(!A.activeAndEnabled)continue;const e=A.performRaycast(t);e&&e.length>0&&this._sortedHits.push(...e)}return this._sortedHits.sort((A,e)=>A.distance-e.distance),this._sortedHits}handleIntersections(t,A){if(!t||t.length<=0)return!1;t=this.sortCandidates(t);for(const e of t){const{object:i}=e;if(A.point=e.point,A.normal=e.normal,A.face=e.face,A.distance=e.distance,A.instanceId=e.instanceId,this.handleEventOnObject(i,A))return!0}return!1}sortCandidates(t){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let A=0;A<t.length;A++){const e=t[A],i=e.object;if(i.material&&i.material.depthTest===!1){this._noDepthTestingResults.push(e);continue}this._sortingBuffer.push(e)}for(const A of this._sortingBuffer)this._noDepthTestingResults.push(A);return this._noDepthTestingResults}handleEventOnObject(t,A){if(!this.testIsVisible(t))return A.isClicked&&eB&&console.log("not allowed",t),!1;if(A.pointerId===void 0)return eB&&console.warn("Event without pointer can't be handled",A),!1;A.object=t;const e=t.parent;let i=!1;const g=A.isClicked??!1;let I=null;if(e&&e.isUI){const a=(A.isPressed||A.isClicked)??!1;if(e[bo]){const r=e[bo].gameObject;if(r){if(!lE.isInteractable(r,this.out))return!1;I=this.out.canvasGroup??null,this.handleMeshUIIntersection(t,a),t=r,i=!0}}if(!i&&this.handleMeshUiObjectWithoutShadowDom(e,a))return!0}g&&eB&&console.log(this.context.time.frame,t);const o=this.hoveredByID.get(A.pointerId),s=o?.obj!==t;s&&o!=null&&o.obj&&this.triggerOnExit(o.obj,o.data);const C=this.hoveredByID.get(A.pointerId);if(C?(C.obj=t,C.data=A):this.hoveredByID.set(A.pointerId,{obj:t,data:A}),A.isDown){const a=this.pressedByID.get(A.pointerId);a?(a.obj=t,a.data=A):this.pressedByID.set(A.pointerId,{obj:t,data:A,handlers:new Set})}return(I===null||I.interactable)&&this.handleMainInteraction(t,A,s),!0}propagate(t,A,e){for(;;){if(A.used)return;if(iA.foreachComponent(t,i=>{e(i)},!1),!t.parent)break;t=t.parent}}handleMainInteraction(t,A,e){if(A.pointerId===void 0)return;const i=this.pressedByID.get(A.pointerId);this.propagate(t,A,g=>{var I;const o=g;if(o.interactable===!1)return;o.onPointerEnter&&e&&o.onPointerEnter(A),A.isDown&&o.onPointerDown&&(o.onPointerDown(A),i?.handlers.add(o));const s=this.context.input.getPointerPositionLastFrame(A.pointerId),C=this.context.input.getPointerPosition(A.pointerId);s&&!oe.approximately(s,C)&&o.onPointerMove&&o.onPointerMove(A),A.isUp&&(o.onPointerUp&&(o.onPointerUp(A),i?.handlers.delete(o)),o.onPointerExit&&((I=A.event)==null?void 0:I.pointerType)===MQ.Touch&&(o.onPointerExit(A),this.hoveredByID.delete(A.pointerId))),A.isClicked&&o.onPointerClick&&o.onPointerClick(A)}),A.isUp&&(i?.handlers.forEach(g=>{g.onPointerUp&&g.onPointerUp(A)}),this.pressedByID.delete(A.pointerId))}triggerOnExit(t,A){A.used=!1,this.propagate(t,A,e=>{if(!e.gameObject||e.destroyed)return;const i=e;i.onPointerExit&&i.onPointerExit(A)})}handleMeshUiObjectWithoutShadowDom(t,A){return!t||!t.isUI?!0:this.handleMeshUIIntersection(t,A)}handleMeshUIIntersection(t,A){const e=ra.updateState(t,A);return e&&this.currentActiveMeshUIComponents.push(e),e!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&ra.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let t=0;t<this.currentActiveMeshUIComponents.length;t++){const A=this.currentActiveMeshUIComponents[t];ra.resetState(A)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(t){return t?iA.isActiveSelf(t)?this.testIsVisible(t.parent):!1:!0}};let go=na;n(go,"_eventSystemMap",new Map),n(go,"didSearchEventSystem",!1);class ra{static markDirty(){this.needsUpdate=!0}static update(A,e,i=!1){if(i){A.update();return}const g=e.time.frameCount;for(const I of this.lastUpdateFrame)if(I.context===e){if(g===I.frame)return;I.frame=g;let o=this.needsUpdate||g<1;I.nextUpdate===e.time.frameCount&&(o=!0),o&&(eB&&console.log("Update threemeshui"),this.needsUpdate=!1,A.update());return}this.lastUpdateFrame=[{context:e,frame:g,nextUpdate:g}],A.update()}static updateState(A,e){let i=null;if(A&&(i=this.findBlockInParent(A),i&&i!==this.lastSelected)){if(i.interactable===!1)return null;this.needsUpdate=!0}return i}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}}n(ra,"lastSelected",null),n(ra,"lastUpdateFrame",[]),n(ra,"needsUpdate",!1);const Iy=Symbol("cameraController");function QgA(t){return t[Iy]}function L2(t,A,e){e?t[Iy]=A:t[Iy]===A&&(t[Iy]=null)}const x2=Symbol("camera autofit");function EgA(t){return t[x2]===void 0?!0:t[x2]!==!1}class T2 extends uA{constructor(A,e={}){const i=[A.isCubeTexture?"#define ENVMAP_TYPE_CUBE":""],g=`
5097
5097
  varying vec3 vWorldPosition;
5098
5098
 
5099
5099
  void main() {