@needle-tools/engine 3.7.1-alpha → 3.7.2-alpha
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +4 -1
- package/dist/needle-engine.js +3 -3
- package/dist/needle-engine.light.js +3 -3
- package/dist/needle-engine.light.min.js +2 -2
- package/dist/needle-engine.light.umd.cjs +2 -2
- package/dist/needle-engine.min.js +2 -2
- package/dist/needle-engine.umd.cjs +2 -2
- package/lib/engine-components/SpectatorCamera.js +1 -1
- package/lib/engine-components/SpectatorCamera.js.map +1 -1
- package/package.json +1 -1
- package/src/engine-components/SpectatorCamera.ts +1 -1
|
@@ -4176,7 +4176,7 @@ ${o.join(`
|
|
|
4176
4176
|
`)}
|
|
4177
4177
|
|
|
4178
4178
|
}
|
|
4179
|
-
`}function Px(t){return`(${t.r}, ${t.g}, ${t.b})`}function jx(t){return`(${t.x}, ${t.y})`}const Wx=class{constructor(t,A,e){r(this,"id"),r(this,"trigger"),r(this,"action"),r(this,"exclusive",!1),this.id="Behavior_"+Im(t)+"_"+Wx.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 g="";if(Array.isArray(this.trigger)){g="[";for(let i=0;i<this.trigger.length;i++){const I=this.trigger[i];g+="<"+I.id+">",i+1<this.trigger.length&&(g+=", ")}g+="]"}else g=`<${this.trigger.id}>`;if(e.appendLine(`rel triggers = ${g} `),e.appendLine(),Array.isArray(this.trigger))for(const i of this.trigger)i.writeTo(A,e),e.appendLine();else this.trigger.writeTo(A,e);e.appendLine(),this.action.writeTo(A,e),e.closeBlock()}};let _i=Wx;r(_i,"global_id",0);function om(t,A){var e,g;let i="";if(Array.isArray(t)){let I="[ ";for(let o=0;o<t.length;o++){let C=t[o];if(typeof C=="string")I+=C;else if(typeof C=="object"){C.isObject3D&&(C=A.findById(C.uuid));const s=(e=C.getPath)==null?void 0:e.call(C);I+=s}o+1<t.length&&(I+=", ")}I+=" ]",i=I}else typeof t=="object"&&(t.isObject3D&&(t=A.findById(t.uuid)),i=(g=t.getPath)==null?void 0:g.call(t));return i=i.replace(A.name,A.name+"/Scenes/Scene"),i}const Vx=class{constructor(t,A){r(this,"id"),r(this,"targetId"),r(this,"tokenId"),r(this,"type"),r(this,"distance"),t&&(this.targetId=t),A?this.id=A:this.id="Trigger_"+Vx.global_id++}writeTo(t,A){A.beginBlock(`def Preliminary_Trigger "${this.id}"`),this.targetId&&(typeof this.targetId!="string"&&(this.targetId=om(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 Sr=Vx;r(Sr,"global_id",0);class nI{static sceneStartTrigger(){const A=new Sr;return A.targetId=void 0,A.tokenId="SceneTransition",A.type="enter",A}static tapTrigger(A){const e=new Sr(A);return e.tokenId="TapGesture",e}static isTapTrigger(A){return A?.tokenId==="TapGesture"}static proximityToCameraTrigger(A,e){const g=new Sr(A);return g.tokenId="ProximityToCamera",g.distance=e,g}}class za{constructor(A,e){r(this,"id"),r(this,"actions"),r(this,"loops",0),r(this,"performCount",1),r(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 g of this.actions)g&&e.appendLine("<"+g.id+">,");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 g of this.actions)g&&(g.writeTo(A,e),e.appendLine());e.closeBlock()}}r(za,"global_id",0);var Cm=(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))(Cm||{}),sm=(t=>(t.Relative="relative",t.Absolute="absolute",t))(sm||{});const am=class{constructor(t,A){r(this,"id"),r(this,"tokenId"),r(this,"affectedObjects"),r(this,"easeType"),r(this,"motionType"),r(this,"duration"),r(this,"moveDistance"),r(this,"style"),r(this,"type"),r(this,"front"),r(this,"up"),r(this,"start"),r(this,"animationSpeed"),r(this,"reversed"),r(this,"pingPong"),r(this,"xFormTarget"),r(this,"audio"),r(this,"gain"),r(this,"auralMode"),r(this,"multiplePerformOperation"),t&&(this.affectedObjects=t),A?this.id=A:this.id="Action",this.id+="_"+am.global_id++}clone(){const t=new am,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=om(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=om(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 To=am;r(To,"global_id",0);let KQ=class KE{constructor(A,e,g){r(this,"x",0),r(this,"y",0),r(this,"z",0),this.x=A,this.y=e,this.z=g}static get up(){return new KE(0,1,0)}static get right(){return new KE(1,0,0)}static get forward(){return new KE(0,0,1)}static get back(){return new KE(0,0,-1)}static get zero(){return new KE(0,0,0)}};var zx=(t=>(t.Play="play",t.Pause="pause",t.Stop="stop",t))(zx||{}),nm=(t=>(t.Spatial="spatial",t.NonSpatial="nonSpatial",t.Ambient="ambient",t))(nm||{});class at{static sequence(...A){return new za("group_"+za.getId(),A).makeSequence()}static parallel(...A){return new za("group_"+za.getId(),A).makeParallel()}static fadeAction(A,e,g){const i=new To(A);return i.tokenId="Visibility",i.type=g?"show":"hide",i.duration=e,i.style="basic",i.motionType="none",i.moveDistance=0,i.easeType="none",i}static startAnimationAction(A,e,g=0,i=1,I=!1,o=!1){const C=new To(A);if(C.tokenId="StartAnimation",C.start=e,C.duration=g,C.animationSpeed=i,C.reversed=I,C.pingPong=o,I&&(C.start-=g),o){C.pingPong=!1;const s=C.clone();return s.reversed=!I,s.start=C.start,s.reversed&&(s.start-=g),at.sequence(C,s)}return C}static waitAction(A){const e=new To;return e.tokenId="Wait",e.duration=A,e}static lookAtCameraAction(A,e=9999999999999,g,i){const I=new To(A);return I.tokenId="LookAtCamera",I.duration=e,I.front=g??KQ.forward,I.up=i??KQ.up,I}static emphasize(A,e,g=2,i=1,I="basic"){const o=new To(A);return o.tokenId="Emphasize",o.duration=e,o.style=I??"basic",o.motionType=Cm[g],o.moveDistance=i,o}static transformAction(A,e,g,i,I="inout"){const o=new To(A);return o.tokenId="Transform",o.duration=g,o.type=i,o.easeType=I,Array.isArray(e)&&console.error("Transform target must not be an array",e),o.xFormTarget=e,o}static playAudioAction(A,e,g="play",i=1,I="spatial"){const o=new To(A);return o.tokenId="Audio",o.type=g,o.audio=e,o.gain=i,o.auralMode=I,o.multiplePerformOperation="allow",o}}class s6{constructor(A){r(this,"object"),r(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 rm extends s6{constructor(A,e,g,i){super(A),r(this,"matrix"),r(this,"material"),r(this,"geometry"),r(this,"_enableAction"),r(this,"_disableAction"),this.matrix=e,this.material=g,this.geometry=i}onApply(A){var e,g;const i=this.model;if(!i)return;(e=i.parent)!=null&&e.isDynamic||pC.createEmptyParent(i);const I=i.clone();this.matrix&&(I.matrix=this.matrix),this.material&&(I.material=this.material),this.geometry&&(I.geometry=this.geometry),(g=i.parent)==null||g.add(I)}enable(){return this._enableAction?this._enableAction:(this._enableAction=at.fadeAction(this.object,0,!0),this._enableAction)}disable(){return this._disableAction?this._disableAction:(this._disableAction=at.fadeAction(this.object,0,!1),this._disableAction)}}class Bm{constructor(A){r(this,"actions"),r(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 a6=Object.defineProperty,n6=Object.getOwnPropertyDescriptor,Zx=(t,A,e,g)=>{for(var i=g>1?void 0:g?n6(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&a6(A,e,i),i};class Uc extends RA{constructor(){super(...arguments),r(this,"from"),r(this,"to"),r(this,"width",0),r(this,"centered",!0),r(this,"_centerPos")}awake(){this._centerPos=new f}update(){if(!this.from||!this.to)return;const A=we(this.from).clone(),e=we(this.to).clone(),g=A.distanceTo(e);this._centerPos.copy(A),this._centerPos.add(e),this._centerPos.multiplyScalar(.5),gg(this.gameObject,this.centered?this._centerPos:A),this.gameObject.lookAt(we(this.to).clone()),this.gameObject.scale.set(this.width,this.width,g)}}Zx([w(eA)],Uc.prototype,"from",2),Zx([w(eA)],Uc.prototype,"to",2);var r6=Object.defineProperty,B6=Object.getOwnPropertyDescriptor,Fc=(t,A,e,g)=>{for(var i=g>1?void 0:g?B6(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&r6(A,e,i),i};const Za=CA("debuganimation");class ao extends RA{constructor(){super(...arguments),r(this,"playAutomatically",!0),r(this,"randomStartTime",!0),r(this,"minMaxSpeed"),r(this,"minMaxOffsetNormalized"),r(this,"loop",!0),r(this,"clampWhenFinished",!1),r(this,"_tempAnimationClipBeforeGameObjectExisted",null),r(this,"mixer"),r(this,"_actions",[]),r(this,"_currentActions",[]),r(this,"_handles",[]),r(this,"_didInit",!1)}get clip(){var A;return(A=this.animations)!=null&&A.length?this.animations[0]:null}set clip(A){if(!this.__didAwake){Za&&console.log("Assign clip during serialization",A),this._tempAnimationClipBeforeGameObjectExisted=A;return}A&&(Za&&console.log("Assign clip",A,!!this.gameObject),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){Za&&console.log("assign animations",A),this.gameObject.animations=A}get animations(){return this.gameObject.animations}get currentAction(){return this._currentActions[0]}get currentActions(){return this._currentActions}get actions(){return this._actions}set actions(A){this._actions=A}awake(){Za&&console.log(this),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(g=>g.getClip().name===A)}get isPlaying(){for(let A=0;A<this._currentActions.length;A++)if(this._currentActions[A].isRunning())return!0;return!1}play(A=0,e){if(Za&&console.log("PLAY",A),this.init(),!this.mixer){Za&&console.warn("Missing mixer",this);return}A===void 0&&(A=0);let g=A;if(typeof A=="number"){if(A>=this.animations.length){Za&&console.log("No animation at index",A);return}g=this.animations[A]}else typeof A=="string"&&(g=this.animations.find(I=>I.name===A));if(!g){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()===g)return this.internalOnPlay(I,e);if(!(g instanceof $I)){console.warn("Clip is no AnimationClip",g,"on object: "+this.name);return}const i=this.mixer.clipAction(g);return this.actions.push(i),this.internalOnPlay(i,e)}internalOnPlay(A,e){var g=this.currentAction;if(g===A&&g.isRunning()&&g.time<g.getClip().duration){const C=this.tryFindHandle(A);if(C)return C.getPromise()}const i=e?.exclusive??!0;e!=null&&e.fadeDuration?(i&&g?.fadeOut(e.fadeDuration),A.fadeIn(e.fadeDuration)):i&&g?.stop(),A.reset(),A.enabled=!0,A.time=0,A.timeScale=1;const I=A.getClip();e!=null&&e.minMaxOffsetNormalized&&(A.time=$A.lerp(e.minMaxOffsetNormalized.x,e.minMaxOffsetNormalized.y,Math.random())*I.duration),e!=null&&e.minMaxSpeed&&(A.timeScale=$A.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?c0:Ch:A.loop=Ch,A.play(),Za&&console.log("PLAY",A.getClip().name,A);const o=new Q6(A,this.mixer,e,C=>{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 iu(this.gameObject)))}}Fc([w()],ao.prototype,"playAutomatically",2),Fc([w()],ao.prototype,"randomStartTime",2),Fc([w()],ao.prototype,"loop",2),Fc([w()],ao.prototype,"clampWhenFinished",2),Fc([w($I)],ao.prototype,"clips",1);class Q6{constructor(A,e,g,i){r(this,"mixer"),r(this,"action"),r(this,"promise",null),r(this,"resolve",null),r(this,"reject",null),r(this,"_options"),r(this,"_resolveCallback",null),r(this,"_rejectCallback",null),r(this,"_loopCallback"),r(this,"_finishedCallback"),r(this,"_resolvedOrRejectedCallback"),this.action=A,this.mixer=e,this._resolvedOrRejectedCallback=i,this._options=g}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,g;this.dispose(),(e=this._resolvedOrRejectedCallback)==null||e.call(this,this),(g=this._rejectCallback)==null||g.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 E6=Object.defineProperty,h6=Object.getOwnPropertyDescriptor,Xa=(t,A,e,g)=>{for(var i=g>1?void 0:g?h6(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&E6(A,e,i),i};class $a{constructor(){r(this,"time"),r(this,"value"),r(this,"inTangent"),r(this,"inWeight"),r(this,"outTangent"),r(this,"outWeight"),r(this,"weightedMode")}}Xa([w()],$a.prototype,"time",2),Xa([w()],$a.prototype,"value",2),Xa([w()],$a.prototype,"inTangent",2),Xa([w()],$a.prototype,"inWeight",2),Xa([w()],$a.prototype,"outTangent",2),Xa([w()],$a.prototype,"outWeight",2),Xa([w()],$a.prototype,"weightedMode",2);const Xx=class{constructor(){r(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 g=this.keys[A+1];if(g.time<t)continue;return!isFinite(e.outTangent)||!isFinite(g.inTangent)?e.value:Xx.interpolateValue(t,e,g)}else return e.value}return this.keys[this.keys.length-1].value}static interpolateValue(t,A,e){const g=A.time,i=A.value,I=A.outTangent,o=e.time,C=e.value,s=e.inTangent,a=o-g,n=a*a,B=n*a,Q=((I+s)*a-2*(C-i))/B,E=(3*(C-i)-(s+2*I)*a)/n,h=I,c=i,l=t-g,d=l*l,u=d*l;return Q*u+E*d+h*l+c}};let fr=Xx;Xa([w($a)],fr.prototype,"keys",2);const JQ=CA("debugusdzanimation");class LD{constructor(A,e,g){r(this,"ext"),r(this,"root"),r(this,"clip"),this.ext=A,this.root=e,this.clip=g}get start(){return this.ext.getStartTime01(this.root,this.clip)}get duration(){return this.clip.duration}}class xD{constructor(A,e,g,i){r(this,"clip"),r(this,"pos"),r(this,"rot"),r(this,"scale"),r(this,"ext"),r(this,"root"),r(this,"target"),this.ext=A,this.root=e,this.target=g,this.clip=i}get frameRate(){return 60}addTrack(A){A.name.endsWith("position")&&(this.pos=A),A.name.endsWith("quaternion")&&(this.rot=A),A.name.endsWith("scale")&&(this.scale=A)}getFrames(){var A,e,g,i,I,o;return Math.max(((e=(A=this.pos)==null?void 0:A.times)==null?void 0:e.length)??0,((i=(g=this.rot)==null?void 0:g.times)==null?void 0:i.length)??0,((o=(I=this.scale)==null?void 0:I.times)==null?void 0:o.length)??0)}getDuration(){var A,e,g;const i=((A=this.pos)==null?void 0:A.times)??((e=this.rot)==null?void 0:e.times)??((g=this.scale)==null?void 0:g.times);return i?i[i.length-1]:0}getStartTime(A){let e=0;for(let g=0;g<A.length;g++){const i=A[g];if(i===this)return e;e+=i.getDuration()}return e}}class YD{constructor(){r(this,"dict",new Map),r(this,"rootTargetMap",new Map),r(this,"serializers",[])}get extensionName(){return"animation"}getStartTime01(A,e){const g=this.rootTargetMap.get(A);if(!g)return 1/0;let i=-1;for(const I of g){const o=this.dict.get(I);let C=0;if(o!=null&&o.length){for(const s of o){if(s.clip===e)break;C+=s.getDuration()}i=Math.max(i,C)}else console.warn("No animation found on root",A,e,o)}return i}registerAnimation(A,e){if(!e||!A)return null;this.rootTargetMap.has(A)||this.rootTargetMap.set(A,[]);for(const g of e.tracks){const i=g.name.split(".")[2],I=A.getObjectByName(i);if(!I){console.warn("no object found for track",g.name,"using "+A.name+" instead");continue}this.dict.has(I)||this.dict.set(I,[]);const o=this.dict.get(I);if(!o)continue;let C=o.find(a=>a.clip===e);C||(C=new xD(this,A,I,e),o.push(C)),C.addTrack(g);const s=this.rootTargetMap.get(A);s!=null&&s.includes(I)||s==null||s.push(I)}return new LD(this,A,e)}onAfterHierarchy(A){JQ&&console.log(this.dict)}onAfterBuildDocument(A){var e,g;for(const i of this.serializers){const I=(e=i.model)==null?void 0:e.parent,o=I?.isDynamic===!0;JQ&&console.log(o,(g=i.model)==null?void 0:g.parent),o&&i.registerCallback(I)}}onExportObject(A,e,g){eA.foreachComponent(A,I=>{const o=I;typeof o.createAnimation=="function"&&o.createAnimation(this,e,g)},!1);const i=new c6(A,this.dict);this.serializers.push(i),i.registerCallback(e)}}class c6{constructor(A,e){r(this,"object"),r(this,"dict"),r(this,"model"),r(this,"callback"),this.object=A,this.dict=e}registerCallback(A){this.model&&this.callback&&this.model.removeEventListener("serialize",this.callback),this.callback||(this.callback=this.onSerialize.bind(this)),JQ&&console.log("REPARENT",A),this.model=A,this.model.addEventListener("serialize",this.callback)}onSerialize(A,e){var g,i,I,o,C,s;if(!this.model)return;JQ&&console.log("SERIALIZE",this.model.name,this.object.type);const a=this.object,n=this.dict.get(a);if(!n)return;const B=new KA,Q=new f,E=new mA,h=new f(1,1,1);A.appendLine("matrix4d xformOp:transform.timeSamples = {"),A.indent++;for(const c of n){let l=(g=c.pos)==null?void 0:g.times,d=(i=c.rot)==null?void 0:i.times,u=(I=c.scale)==null?void 0:I.times,p=[];if(l)for(const S of l)p.push(S);if(d)for(const S of d)p.push(S);if(u)for(const S of u)p.push(S);if(p.sort((S,U)=>S-U),p=[...new Set(p)],!p||p.length===0){console.error("got an animated object but no time values??",a,c);continue}const D=c.getStartTime(n);JQ&&A.appendLine(c.clip.name+": start="+D.toFixed(3)+", length="+c.getDuration().toFixed(3)+", frames="+c.getFrames());const y=(o=c.pos)==null?void 0:o.createInterpolant(),k=(C=c.rot)==null?void 0:C.createInterpolant(),F=(s=c.scale)==null?void 0:s.createInterpolant();y||Q.set(a.position.x,a.position.y,a.position.z),k||E.set(a.quaternion.x,a.quaternion.y,a.quaternion.z,a.quaternion.w),F||h.set(a.scale.x,a.scale.y,a.scale.z);for(let S=0;S<p.length;S++){const U=p[S];if(y){const Y=y.evaluate(U);Q.set(Y[0],Y[1],Y[2])}if(k){const Y=k.evaluate(U);E.set(Y[0],Y[1],Y[2],Y[3])}if(F){const Y=F.evaluate(U);h.set(Y[0],Y[1],Y[2])}B.compose(Q,E,h);let M=`${(D+U)*c.frameRate}: ${Tx(B)},`;JQ&&(M="#"+S+" "+M),A.appendLine(M)}}A.indent--,A.appendLine("}")}}class l6{constructor(){r(this,"_context")}get context(){return this._context??be.Current}get isStateMachineBehaviour(){return!0}}class HD{constructor(A,e,g,i){r(this,"_name"),r(this,"_nameHash"),r(this,"_normalizedTime"),r(this,"_length"),r(this,"_speed"),this._name=A.name,this._nameHash=A.hash,this._normalizedTime=e,this._length=g,this._speed=i}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 $x(t,A){return{name:"",isLooping:!1,guid:A?.generateUUID()??Ji.generateUUID(),index:-1,clip:new $I(t,1,[])}}var An=(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))(An||{}),Qm=(t=>(t[t.Float=1]="Float",t[t.Int=3]="Int",t[t.Bool=4]="Bool",t[t.Trigger=9]="Trigger",t))(Qm||{});const uC=CA("debuganimatorcontroller"),TD=CA("debugrootmotion");class sB{constructor(A){r(this,"normalizedStartOffset",0),r(this,"_speed",1),r(this,"animator"),r(this,"model"),r(this,"_mixer"),r(this,"_activeState"),r(this,"_activeStates",[]),r(this,"rootMotionHandler"),this.model=A,uC&&console.log(this)}play(A,e=-1,g=Number.NEGATIVE_INFINITY,i=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){uC&&console.log("transition to ",o),this.transitionTo(o,i,g);return}console.warn("Could not find "+A+" to play")}reset(){this.setStartTransition()}setBool(A,e){var g,i;const I=typeof A=="string"?"name":"hash";return(i=(g=this.model)==null?void 0:g.parameters)==null?void 0:i.filter(o=>o[I]===A).forEach(o=>o.value=e)}getBool(A){var e,g,i;const I=typeof A=="string"?"name":"hash";return((i=(g=(e=this.model)==null?void 0:e.parameters)==null?void 0:g.find(o=>o[I]===A))==null?void 0:i.value)??!1}setFloat(A,e){var g,i;const I=typeof A=="string"?"name":"hash";return(i=(g=this.model)==null?void 0:g.parameters)==null?void 0:i.filter(o=>o[I]===A).forEach(o=>o.value=e)}getFloat(A){var e,g,i;const I=typeof A=="string"?"name":"hash";return((i=(g=(e=this.model)==null?void 0:e.parameters)==null?void 0:g.find(o=>o[I]===A))==null?void 0:i.value)??0}setInteger(A,e){var g,i;const I=typeof A=="string"?"name":"hash";return(i=(g=this.model)==null?void 0:g.parameters)==null?void 0:i.filter(o=>o[I]===A).forEach(o=>o.value=e)}getInteger(A){var e,g,i;const I=typeof A=="string"?"name":"hash";return((i=(g=(e=this.model)==null?void 0:e.parameters)==null?void 0:g.find(o=>o[I]===A))==null?void 0:i.value)??0}setTrigger(A){var e,g;uC&&console.log("SET TRIGGER",A);const i=typeof A=="string"?"name":"hash";return(g=(e=this.model)==null?void 0:e.parameters)==null?void 0:g.filter(I=>I[i]===A).forEach(I=>I.value=!0)}resetTrigger(A){var e,g;const i=typeof A=="string"?"name":"hash";return(g=(e=this.model)==null?void 0:e.parameters)==null?void 0:g.filter(I=>I[i]===A).forEach(I=>I.value=!1)}isInTransition(){return this._activeStates.length>1}setSpeed(A){this._speed=A}FindState(A){return this.findState(A)}findState(A){if(!A)return null;if(Array.isArray(this.model.layers)){for(const e of this.model.layers)for(const g of e.stateMachine.states)if(g.name===A)return g}return null}get context(){var A;return(A=this.animator)==null?void 0:A.context}bind(A){this.animator=A,this._mixer=new iu(this.animator.gameObject),this.createActions(this.animator)}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=qd(this.model,(e,g,i)=>i==null?!0:!(i.type==="Object3D"||i.isObject3D===!0||NJ(i)||i.tracks!==void 0));return console.assert(A!==this.model),new sB(A)}update(){var A,e;if(!this.animator||(this.evaluateTransitions(),this.updateActiveStates(),!this._activeState))return;const g=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&((A=this.rootMotionHandler)==null||A.onBeforeUpdate()),this._mixer.update(g),this.animator.applyRootMotion&&((e=this.rootMotionHandler)==null||e.onAfterUpdate())}updateActiveStates(){for(let A=0;A<this._activeStates.length;A++){const e=this._activeStates[A],g=e.motion;if(!g.action)this._activeStates.splice(A,1),A--;else{const i=g.action;i.getEffectiveWeight()<=0&&!i.isRunning()&&(uC&&console.debug("REMOVE",e.name,i.getEffectiveWeight(),i.isRunning(),i.isScheduled()),this._activeStates.splice(A,1),A--)}}}setStartTransition(){for(const A of this.model.layers){const e=A.stateMachine;e.defaultState===void 0&&(uC&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",A),e.defaultState=0);const g=e.states[e.defaultState];this.transitionTo(g,0,this.normalizedStartOffset)}}evaluateTransitions(){var A;let e=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;e=!0}const g=this._activeState,i=g.motion.action;for(const o of g.transitions){if(!o.hasExitTime&&o.conditions.length<=0)continue;let C=!0;for(const s of o.conditions)if(!this.evaluateCondition(s)){C=!1;break}if(C){for(const s of o.conditions){const a=this.model.parameters.find(n=>n.name===s.parameter);a?.type===Qm.Trigger&&(a.value=!1)}if(i){const s=g.motion.clip.duration,a=s<=0?1:Math.abs(i.time/s);let n=!1;if(o.hasExitTime?i.timeScale>0?n=a>=o.exitTime:i.timeScale<0&&(n=1-a>=o.exitTime):n=!0,n){i.clampWhenFinished=!0,uC&&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}}}let I=!1;if(g.motion.isLooping&&i&&(i.time>=i.getClip().duration?(I=!0,i.reset(),i.time=0,i.play()):i.time<=0&&i.timeScale<0&&(I=!0,i.reset(),i.time=i.getClip().duration,i.play())),!I&&g&&!e&&i&&this.animator&&g.behaviours){const o=i?.getClip().duration,C=i.time/o,s=new HD(this._activeState,C,o,this._speed);for(const a of g.behaviours)a.instance&&((A=a.instance.onStateUpdate)==null||A.call(a.instance,this.animator,s,0))}}getState(A,e){return typeof A=="number"&&(A==-1&&(A=this.model.layers[e].stateMachine.defaultState,A===void 0&&(uC&&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,g){var i,I,o,C,s,a,n,B;if(!this.animator)return;const Q=0;if(A=this.getState(A,Q),!(A!=null&&A.motion)||!A.motion.clip)return;const E=this._activeState===A;if(E){const d=A.motion;!d.action_loopback&&d.clip&&(this._mixer.uncacheAction(d.clip,this.animator.gameObject),d.action_loopback=this.createAction(d.clip))}if((i=this._activeState)!=null&&i.behaviours&&this._activeState.motion.action){const d=(I=this._activeState)==null?void 0:I.motion.clip.duration,u=this._activeState.motion.action.time/d,p=new HD(this._activeState,u,d,this._speed);for(const D of this._activeState.behaviours)(C=(o=D.instance)==null?void 0:o.onStateExit)==null||C.call(D.instance,this.animator,p,Q)}const h=(s=this._activeState)==null?void 0:s.motion.action;h&&h.fadeOut(e),E&&(A.motion.action=A.motion.action_loopback,A.motion.action_loopback=h);const c=this._activeState;this._activeState=A;const l=(a=A.motion)==null?void 0:a.action;if(l){g=Math.max(0,Math.min(1,g)),l.isRunning()&&l.stop(),l.reset(),l.timeScale=this._speed,A.speed!==void 0&&(l.timeScale*=A.speed),l.enabled=!0;const d=A.motion.clip.duration;if(l.time=g*d,l.timeScale<0&&(l.time=d-l.time),l.clampWhenFinished=!0,l.setLoop(Ch,0),e>0?l.fadeIn(e):l.setEffectiveWeight(1),l.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(l),this._activeStates.includes(A)||this._activeStates.push(A),this._activeState.behaviours){const u=new HD(A,g,d,this._speed);for(const p of this._activeState.behaviours)(B=(n=p.instance)==null?void 0:n.onStateEnter)==null||B.call(p.instance,this.animator,u,Q)}}else uC&&(A.__warned_no_motion||(A.__warned_no_motion=!0,console.warn("No action",A.motion,this)));uC&&console.log("TRANSITION FROM "+c?.name+" TO "+A.name,e,h,l,l?.getEffectiveTimeScale(),l?.getEffectiveWeight(),l?.isRunning(),l?.isScheduled(),l?.paused)}createAction(A){var e,g;if(this._mixer.existingAction(A)&&this._mixer.uncacheAction(A,(e=this.animator)==null?void 0:e.gameObject),(g=this.animator)!=null&&g.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new d6(this));const i=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,i,A)}else return this._mixer.clipAction(A)}evaluateCondition(A){const e=this.model.parameters.find(g=>g.name===A.parameter);if(!e)return!1;switch(A.mode){case An.If:return e.value===!0;case An.IfNot:return e.value===!1;case An.Greater:return e.value>A.threshold;case An.Less:return e.value<A.threshold;case An.Equals:return e.value===A.threshold;case An.NotEqual:return e.value!==A.threshold}return!1}createActions(A){var e,g;for(const i of this.model.layers){const I=i.stateMachine;for(let o=0;o<I.states.length;o++){const C=I.states[o];C.transitions||(C.transitions=[]);for(const s of C.transitions)s.conditions||(s.conditions=[]);if(C.motion||(C.motion=$x(C.name)),this.animator&&C.motion.clips){const s=(e=C.motion.clips)==null?void 0:e.find(a=>{var n,B;return a.node.name===((B=(n=this.animator)==null?void 0:n.gameObject)==null?void 0:B.name)});C.motion.clip=s?.clip}if(!C.motion.clip){const s=new $I(void 0,void 0,[]);C.motion.clip=s}if((g=C.motion)!=null&&g.clip){const s=C.motion.clip,a=this.createAction(s);C.motion.action=a}if(C.behaviours&&Array.isArray(C.behaviours))for(const s of C.behaviours){if(!(s!=null&&s.typeName))continue;const a=T.get(s.typeName),n=new a;n.isStateMachineBehaviour&&(n._context=this.context??void 0,rr(n,s.properties),s.instance=n),uC&&console.log("Created animator controller behaviour",C.name,s.typeName,s.properties,n)}}}}*enumerateActions(){for(const A of this.model.layers){const e=A.stateMachine;for(let g=0;g<e.states.length;g++){const i=e.states[g];i!=null&&i.motion&&(i.motion.action&&(yield i.motion.action),i.motion.action_loopback&&(yield i.motion.action_loopback))}}}}class AY{constructor(A,e){r(this,"track"),r(this,"createdInterpolant"),r(this,"originalEvaluate"),r(this,"customEvaluate"),this.track=A;const g=A,i=g.createInterpolant.bind(A);g.createInterpolant=()=>(g.createInterpolant=i,this.createdInterpolant=i(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=I=>{if(!this.originalEvaluate)return;const o=this.originalEvaluate(I);return e(I,o)},this.createdInterpolant.evaluate=this.customEvaluate,this.createdInterpolant)}evaluate(A){this.customEvaluate&&this.customEvaluate(A)}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 bg=class{constructor(t,A,e,g,i){if(r(this,"_action"),r(this,"root"),r(this,"clip"),r(this,"positionWrapper",null),r(this,"rotationWrapper",null),r(this,"context"),r(this,"positionChange",new f),r(this,"rotationChange",new mA),this.context=t,this.root=A,this.clip=e,bg.firstKeyframeRotation[e.uuid]||(bg.firstKeyframeRotation[e.uuid]=new mA),i){const I=i.values;bg.firstKeyframeRotation[e.uuid].set(I[0],I[1],I[2],I[3])}bg.spaceRotation[e.uuid]||(bg.spaceRotation[e.uuid]=new mA),bg.effectiveSpaceRotation[e.uuid]||(bg.effectiveSpaceRotation[e.uuid]=new mA),bg.clipOffsetRotation[e.uuid]=new mA,i&&bg.clipOffsetRotation[e.uuid].set(i.values[0],i.values[1],i.values[2],i.values[3]).invert(),this.handlePosition(e,g),this.handleRotation(e,i)}set action(t){this._action=t}get action(){return this._action}onStart(t){if(t.getClip()!==this.clip)return;const A=bg.lastObjRotation[this.root.uuid];if(bg.spaceRotation[this.clip.uuid].copy(A),TD){const e=new mg().setFromQuaternion(A);console.log("START",this.clip.name,$A.toDegrees(e.y))}}getClipRotationOffset(){return bg.clipOffsetRotation[this.clip.uuid]}handlePosition(t,A){if(A){const e=this.root;TD&&e.add(new zB),bg.lastObjPosition[e.uuid]||(bg.lastObjPosition[e.uuid]=new f);const g=new f,i=new f;let I=0;this.positionWrapper=new AY(A,(o,C)=>{const s=this.action.getEffectiveWeight();if(TD&&e.position.length()>8&&e.position.set(0,e.position.y,0),o>I){g.set(C[0],C[1],C[2]),g.sub(i),g.multiplyScalar(s),g.applyQuaternion(this.getClipRotationOffset());const a=this.clip.uuid;g.applyQuaternion(bg.spaceRotation[a]),this.positionChange.copy(g)}return i.fromArray(C),I=o,C[0]=0,C[1]=0,C[2]=0,C})}}handleRotation(t,A){if(A){if(TD){const o=A.values,C=new mg().setFromQuaternion(new mA(o[0],o[1],o[2],o[3]));console.log(t.name,A.name,"FIRST ROTATION IN TRACK",$A.toDegrees(C.y));const s=A.values.length-4,a=new mA().set(o[s],o[s+1],o[s+2],o[s+3]),n=new mg().setFromQuaternion(a);console.log(t.name,A.name,"LAST ROTATION IN TRACK",$A.toDegrees(n.y))}const e=this.root;bg.lastObjRotation[e.uuid]||(bg.lastObjRotation[e.uuid]=new mA);let g=0;const i=new mA,I=new mA;this.rotationWrapper=new AY(A,(o,C)=>(o>g&&(I.set(C[0],C[1],C[2],C[3]),i.invert(),I.multiply(i),this.rotationChange.copy(I)),i.fromArray(C),g=o,C[0]=0,C[1]=0,C[2]=0,C[3]=1,C))}}onBeforeUpdate(){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(){if(!this.action)return;const t=this.action.getEffectiveWeight();this.positionChange.multiplyScalar(t),this.rotationChange.slerp(bg.identityQuaternion,1-t)}};let Us=bg;r(Us,"lastObjPosition",{}),r(Us,"lastObjRotation",{}),r(Us,"firstKeyframeRotation",{}),r(Us,"spaceRotation",{}),r(Us,"effectiveSpaceRotation",{}),r(Us,"clipOffsetRotation",{}),r(Us,"identityQuaternion",new mA);class d6{constructor(A){r(this,"controller"),r(this,"handler",[]),r(this,"root"),r(this,"summedPosition",new f),r(this,"summedRotation",new mA),this.controller=A}createClip(A,e,g){this.root=e,e&&"name"in e&&e.name;const i=this.findRootTrack(g,".position"),I=this.findRootTrack(g,".quaternion"),o=new Us(this.controller.context,e,g,i,I);this.handler.push(o);const C=A.clipAction(g);return o.action=C,C}onStart(A){for(const e of this.handler)e.onStart(A)}onBeforeUpdate(){for(const A of this.handler)A.onBeforeUpdate()}onAfterUpdate(){this.summedPosition.set(0,0,0),this.summedRotation.set(0,0,0,1);for(const A of this.handler)A.onAfterUpdate(),this.summedPosition.add(A.positionChange),this.summedRotation.multiply(A.rotationChange);this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation),Us.lastObjRotation[this.root.uuid].copy(this.root.quaternion)}findRootTrack(A,e){const g=A.tracks;if(!g)return null;for(const i of g)if(i.name.endsWith(e))return i;return null}}var p6=Object.defineProperty,u6=Object.getOwnPropertyDescriptor,OD=(t,A,e,g)=>{for(var i=g>1?void 0:g?u6(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&p6(A,e,i),i};const Em=CA("debuganimator");class Pi extends RA{constructor(){super(...arguments),r(this,"applyRootMotion",!1),r(this,"hasRootMotion",!1),r(this,"keepAnimatorControllerStateOnDisable",!1),r(this,"speed",1),r(this,"normalizedStartOffset",0),r(this,"_animatorController",null)}set runtimeAnimatorController(A){this._animatorController&&this._animatorController.model===A||(A?A instanceof sB?this._animatorController=A:(Em&&console.log("Assign animator controller",A,this),this._animatorController=new sB(A)):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}Play(A,e=-1,g=Number.NEGATIVE_INFINITY,i=0){this.play(A,e,g,i)}play(A,e=-1,g=Number.NEGATIVE_INFINITY,i=0){var I;(I=this.runtimeAnimatorController)==null||I.play(A,e,g,i)}Reset(){this.reset()}reset(){var A;(A=this._animatorController)==null||A.reset()}SetBool(A,e){this.setBool(A,e)}setBool(A,e){var g;(g=this.runtimeAnimatorController)==null||g.setBool(A,e)}GetBool(A){return this.getBool(A)}getBool(A){var e;return((e=this.runtimeAnimatorController)==null?void 0:e.getBool(A))??!1}SetFloat(A,e){this.setFloat(A,e)}setFloat(A,e){var g;(g=this.runtimeAnimatorController)==null||g.setFloat(A,e)}GetFloat(A){return this.getFloat(A)}getFloat(A){var e;return((e=this.runtimeAnimatorController)==null?void 0:e.getFloat(A))??-1}SetInteger(A,e){this.setInteger(A,e)}setInteger(A,e){var g;(g=this.runtimeAnimatorController)==null||g.setInteger(A,e)}GetInteger(A){return this.getInteger(A)}getInteger(A){var e;return((e=this.runtimeAnimatorController)==null?void 0:e.getInteger(A))??-1}SetTrigger(A){this.setTrigger(A)}setTrigger(A){var e;Em&&console.log("SetTrigger",A),(e=this.runtimeAnimatorController)==null||e.setTrigger(A)}ResetTrigger(A){this.resetTrigger(A)}resetTrigger(A){var e;(e=this.runtimeAnimatorController)==null||e.resetTrigger(A)}IsInTransition(){return this.isInTransition()}isInTransition(){var A;return((A=this.runtimeAnimatorController)==null?void 0:A.isInTransition())??!1}SetSpeed(A){return this.setSpeed(A)}setSpeed(A){var e;A!==this.speed&&(this.speed=A,(e=this._animatorController)==null||e.setSpeed(A))}set minMaxSpeed(A){this.speed=$A.lerp(A.x,A.y,Math.random())}set minMaxOffsetNormalized(A){this.normalizedStartOffset=$A.lerp(A.x,A.y,Math.random()),this.runtimeAnimatorController&&(this.runtimeAnimatorController.normalizedStartOffset=this.normalizedStartOffset)}awake(){if(Em&&console.log("ANIMATOR",this.name,this),!!this.gameObject&&this.runtimeAnimatorController){const A=this.runtimeAnimatorController.clone();A?(console.assert(this.runtimeAnimatorController!==A),this.runtimeAnimatorController=A,console.assert(this.runtimeAnimatorController===A),this.runtimeAnimatorController.bind(this),this.runtimeAnimatorController.setSpeed(this.speed),this.runtimeAnimatorController.normalizedStartOffset=this.normalizedStartOffset):console.warn("Could not clone animator controller",this.runtimeAnimatorController)}}onDisable(){var A;this.keepAnimatorControllerStateOnDisable||(A=this._animatorController)==null||A.reset()}onBeforeRender(){this._animatorController&&this._animatorController.update()}}OD([w()],Pi.prototype,"applyRootMotion",2),OD([w()],Pi.prototype,"hasRootMotion",2),OD([w()],Pi.prototype,"keepAnimatorControllerStateOnDisable",2),OD([w()],Pi.prototype,"runtimeAnimatorController",1);class D6 extends eg{constructor(A,e=1,g=16,i=2){const I=new le,o=g+i*2,C=new Float32Array((o*3+3)*3);I.setAttribute("position",new ge(C,3));const s=new Ag({color:65280}),a=new Ag({color:16776960});super(I,[a,s]),this.audio=A,this.range=e,this.divisionsInnerAngle=g,this.divisionsOuterAngle=i,this.type="PositionalAudioHelper",this.update()}update(){const A=this.audio,e=this.range,g=this.divisionsInnerAngle,i=this.divisionsOuterAngle,I=Ji.degToRad(A.panner.coneInnerAngle),o=Ji.degToRad(A.panner.coneOuterAngle),C=I/2,s=o/2;let a=0,n=0,B,Q;const E=this.geometry,h=E.attributes.position;E.clearGroups();function c(l,d,u,p){const D=(d-l)/u;for(h.setXYZ(a,0,0,0),n++,B=l;B<d;B+=D)Q=a+n,h.setXYZ(Q,Math.sin(B)*e,0,Math.cos(B)*e),h.setXYZ(Q+1,Math.sin(Math.min(B+D,d))*e,0,Math.cos(Math.min(B+D,d))*e),h.setXYZ(Q+2,0,0,0),n+=3;E.addGroup(a,n,p),a+=n,n=0}c(-s,-C,i,0),c(-C,C,g,1),c(C,s,i,0),h.needsUpdate=!0,I===o&&(this.material[0].visible=!1)}dispose(){this.geometry.dispose(),this.material[0].dispose(),this.material[1].dispose()}}var w6=Object.defineProperty,y6=Object.getOwnPropertyDescriptor,en=(t,A,e,g)=>{for(var i=g>1?void 0:g?y6(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&w6(A,e,i),i};const Si=CA("debugaudio");var Nc;const Pg=(Nc=class extends RA{constructor(){super(...arguments),r(this,"clip",""),r(this,"playOnAwake",!1),r(this,"_spatialBlend",0),r(this,"_minDistance",1),r(this,"_maxDistance",100),r(this,"_volume",1),r(this,"rollOffMode",0),r(this,"playInBackground",!0),r(this,"_loop",!1),r(this,"sound",null),r(this,"helper",null),r(this,"wasPlaying",!1),r(this,"audioLoader",null),r(this,"shouldPlay",!1),r(this,"_lastClipStartedLoading",null),r(this,"onVisibilityChanged",()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||Jn())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":Si&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,Pg._userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&Pg._userInteractionRegistered&&this.wasPlaying&&this.play();break}}),r(this,"onApplicationMuteChanged",()=>{var t,A;this.context.application.muted?(t=this.sound)==null||t.setVolume(0):(A=this.sound)==null||A.setVolume(this.volume)}),r(this,"lerp",(t,A,e)=>t*(1-e)+A*e),r(this,"_lastContextTime",0),r(this,"_hasEnded",!0),r(this,"_needUpdateSpatialDistanceSettings",!1)}static get userInteractionRegistered(){return Pg._didCallBeginWaitForUserInteraction||(Pg._didCallBeginWaitForUserInteraction=!0,Pg._beginWaitForUserInteraction()),Pg._userInteractionRegistered}static registerWaitForAllowAudio(t){if(t!==null){if(this._userInteractionRegistered){t();return}this.callbacks.indexOf(t)===-1&&this.callbacks.push(t),Pg._didCallBeginWaitForUserInteraction||(Pg._didCallBeginWaitForUserInteraction=!0,Pg._beginWaitForUserInteraction())}}static _beginWaitForUserInteraction(t=null){if(this._userInteractionRegistered){t&&t();return}t!==null&&this.registerWaitForAllowAudio(t);const A=(()=>{if(A!=null&&!Pg._userInteractionRegistered){Pg._userInteractionRegistered=!0,Si&&console.log("\u{1F50A} registered interaction, can play audio now"),document.removeEventListener("pointerdown",A),document.removeEventListener("click",A),document.removeEventListener("dragstart",A),document.removeEventListener("touchstart",A);for(const e of this.callbacks)e();this.callbacks.length=0}}).bind(this);document.addEventListener("pointerdown",A),document.addEventListener("click",A),document.addEventListener("dragstart",A),document.addEventListener("touchstart",A)}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&&(Si&&console.log(this.name,"audio set volume",t),this.sound.setVolume(t))}get Sound(){if(!this.sound&&Pg._userInteractionRegistered){const t=eA.getComponent(this.context.mainCamera,XQ)??eA.findObjectOfType(XQ,this.context);t!=null&&t.listener&&(this.sound=new zK(t.listener),this.gameObject.add(this.sound))}return this.sound}get ShouldPlay(){return this.shouldPlay}awake(){this.audioLoader=new eu,this.playOnAwake&&(this.shouldPlay=!0)}onEnable(){Pg._userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():Pg._beginWaitForUserInteraction(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.loadAndPlay(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(ED.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(ED.MuteChanged,this.onApplicationMuteChanged),this.stop()}onLoaded(t){Si&&console.log("audio buffer loaded"),Pg.registerWaitForAllowAudio(()=>{Si&&console.log("finished loading",t);const A=this.Sound;if(!A){console.warn("Failed getting sound",this.name);return}A.isPlaying&&A.stop(),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(),Si&&console.log(this.name,this.shouldPlay,Pg.userInteractionRegistered,this),this.shouldPlay&&Pg._userInteractionRegistered&&this.play()})}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(Si&&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?Si&&!this.helper&&(this.helper=new D6(t,t.getRefDistance()),t.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}loadAndPlay(t){if(t&&(this.clip=t),this.clip&&(Si&&console.log(this.clip),this.clip.endsWith(".mp3")||this.clip.endsWith(".wav"))){if(this.audioLoader||(this.audioLoader=new eu),this.shouldPlay=!0,this._lastClipStartedLoading===this.clip){Si&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=this.clip,Si&&console.log("load audio",this.clip),this.audioLoader.load(this.clip,this.onLoaded.bind(this),()=>{},console.error)}}play(t=void 0){var A;if(!this.audioLoader||!this.sound||t&&t!==this.clip){this.loadAndPlay(t);return}if(this.shouldPlay=!0,this._hasEnded=!1,Si&&console.log("play",(A=this.sound)==null?void 0:A.getVolume(),this.sound),this.sound&&!this.sound.isPlaying){const e=this.context.application.muted;e&&this.sound.setVolume(0),this.sound.play(e?.1:0)}}pause(){var t;Si&&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())}stop(){var t;Si&&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,Si&&console.log(this._lastContextTime),this.sound.stop())}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,Si&&console.log("Audio clip ended",this.clip),this.sound.dispatchEvent({type:"ended",target:this}))}},r(Nc,"_didCallBeginWaitForUserInteraction",!1),r(Nc,"callbacks",[]),r(Nc,"_userInteractionRegistered",!1),Nc);let cg=Pg;en([w(URL)],cg.prototype,"clip",2),en([w()],cg.prototype,"playOnAwake",2),en([w()],cg.prototype,"loop",1),en([w()],cg.prototype,"spatialBlend",1),en([w()],cg.prototype,"minDistance",1),en([w()],cg.prototype,"maxDistance",1),en([w()],cg.prototype,"volume",1),en([w()],cg.prototype,"rollOffMode",2);var S6=Object.defineProperty,f6=Object.getOwnPropertyDescriptor,k6=(t,A,e,g)=>{for(var i=g>1?void 0:g?f6(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&S6(A,e,i),i};class Kc extends RA{constructor(){super(...arguments),r(this,"constraintActive",!0),r(this,"locked",!1),r(this,"sources",[])}}k6([w(UA)],Kc.prototype,"sources",2);const eY={type:"change"},hm={type:"start"},tY={type:"end"};let G6=class extends Ug{constructor(t,A){super(),this.object=t,this.domElement=A,this.domElement.style.touchAction="none",this.enabled=!0,this.target=new f,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:qn.ROTATE,MIDDLE:qn.DOLLY,RIGHT:qn.PAN},this.touches={ONE:vn.ROTATE,TWO:vn.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(H){H.addEventListener("keydown",ot),this._domElementKeyEvents=H},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(eY),e.update(),i=g.NONE},this.update=function(){const H=new f,X=new mA().setFromUnitVectors(t.up,new f(0,1,0)),jA=X.clone().invert(),VA=new f,TA=new mA,pA=2*Math.PI;return function(){const se=e.object.getWorldPosition(t.position);H.copy(se).sub(e.target),H.applyQuaternion(X),o.setFromVector3(H),e.autoRotate&&i===g.NONE&&U(F()),e.enableDamping?(o.theta+=C.theta*e.dampingFactor,o.phi+=C.phi*e.dampingFactor):(o.theta+=C.theta,o.phi+=C.phi);let Re=e.minAzimuthAngle,G=e.maxAzimuthAngle;return isFinite(Re)&&isFinite(G)&&(Re<-Math.PI?Re+=pA:Re>Math.PI&&(Re-=pA),G<-Math.PI?G+=pA:G>Math.PI&&(G-=pA),Re<=G?o.theta=Math.max(Re,Math.min(G,o.theta)):o.theta=o.theta>(Re+G)/2?Math.max(Re,o.theta):Math.min(G,o.theta)),o.phi=Math.max(e.minPolarAngle,Math.min(e.maxPolarAngle,o.phi)),o.makeSafe(),a=Ji.lerp(a,s,e.enableDamping?e.dampingFactor:1),o.radius*=a,o.radius=Math.max(e.minDistance,Math.min(e.maxDistance,o.radius)),e.enableDamping===!0?e.target.addScaledVector(n,e.dampingFactor):e.target.add(n),H.setFromSpherical(o),H.applyQuaternion(jA),se.copy(e.target).add(H),e.object.parent?e.object.parent.worldToLocal(se):e.object.position.copy(se),e.object.lookAt(e.target),e.enableDamping===!0?(C.theta*=1-e.dampingFactor,C.phi*=1-e.dampingFactor,n.multiplyScalar(1-e.dampingFactor)):(C.set(0,0,0),n.set(0,0,0)),s=1,B||VA.distanceToSquared(e.object.position)>I||8*(1-TA.dot(e.object.quaternion))>I?(e.dispatchEvent(eY),VA.copy(e.object.position),TA.copy(e.object.quaternion),B=!1,!0):!1}}(),this.dispose=function(){e.domElement.removeEventListener("contextmenu",BA),e.domElement.removeEventListener("pointerdown",YA),e.domElement.removeEventListener("pointercancel",uA),e.domElement.removeEventListener("wheel",Je),e.domElement.removeEventListener("pointermove",JA),e.domElement.removeEventListener("pointerup",ne),e._domElementKeyEvents!==null&&e._domElementKeyEvents.removeEventListener("keydown",ot)};const e=this,g={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6};let i=g.NONE;const I=1e-6,o=new Of,C=new Of;let s=1,a=1;const n=new f;let B=!1;const Q=new W,E=new W,h=new W,c=new W,l=new W,d=new W,u=new W,p=new W,D=new W,y=[],k={};function F(){return 2*Math.PI/60/60*e.autoRotateSpeed}function S(){return Math.pow(.95,e.zoomSpeed)}function U(H){C.theta-=H}function M(H){C.phi-=H}const Y=function(){const H=new f;return function(X,jA){H.setFromMatrixColumn(jA,0),H.multiplyScalar(-X),n.add(H)}}(),O=function(){const H=new f;return function(X,jA){e.screenSpacePanning===!0?H.setFromMatrixColumn(jA,1):(H.setFromMatrixColumn(jA,0),H.crossVectors(e.object.up,H)),H.multiplyScalar(X),n.add(H)}}(),x=function(){const H=new f,X=new f;return function(jA,VA){const TA=e.domElement;if(e.object.isPerspectiveCamera){e.object.getWorldPosition(X),H.copy(X).sub(e.target);let pA=H.length();pA*=Math.tan(e.object.fov/2*Math.PI/180),Y(2*jA*pA/TA.clientHeight,e.object.matrixWorld),O(2*VA*pA/TA.clientHeight,e.object.matrixWorld)}else e.object.isOrthographicCamera?(Y(jA*(e.object.right-e.object.left)/e.object.zoom/TA.clientWidth,e.object.matrixWorld),O(VA*(e.object.top-e.object.bottom)/e.object.zoom/TA.clientHeight,e.object.matrixWorld)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),e.enablePan=!1)}}();function b(H){e.object.isPerspectiveCamera?s/=H:e.object.isOrthographicCamera?(e.object.zoom=Math.max(e.minZoom,Math.min(e.maxZoom,e.object.zoom*H)),e.object.updateProjectionMatrix(),B=!0):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),e.enableZoom=!1)}function z(H){e.object.isPerspectiveCamera?s*=H:e.object.isOrthographicCamera?(e.object.zoom=Math.max(e.minZoom,Math.min(e.maxZoom,e.object.zoom/H)),e.object.updateProjectionMatrix(),B=!0):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),e.enableZoom=!1)}function gA(H){Q.set(H.clientX,H.clientY)}function sA(H){u.set(H.clientX,H.clientY)}function AA(H){c.set(H.clientX,H.clientY)}function dA(H){E.set(H.clientX,H.clientY),h.subVectors(E,Q).multiplyScalar(e.rotateSpeed);const X=e.domElement;U(2*Math.PI*h.x/X.clientHeight),M(2*Math.PI*h.y/X.clientHeight),Q.copy(E),e.update()}function rA(H){p.set(H.clientX,H.clientY),D.subVectors(p,u),D.y>0?b(S()):D.y<0&&z(S()),u.copy(p),e.update()}function LA(H){l.set(H.clientX,H.clientY),d.subVectors(l,c).multiplyScalar(e.panSpeed),x(d.x,d.y),c.copy(l),e.update()}function MA(H){H.deltaY<0?z(S()):H.deltaY>0&&b(S()),e.update()}function iA(H){let X=!1;switch(H.code){case e.keys.UP:H.ctrlKey||H.metaKey||H.shiftKey?M(2*Math.PI*e.rotateSpeed/e.domElement.clientHeight):x(0,e.keyPanSpeed),X=!0;break;case e.keys.BOTTOM:H.ctrlKey||H.metaKey||H.shiftKey?M(-2*Math.PI*e.rotateSpeed/e.domElement.clientHeight):x(0,-e.keyPanSpeed),X=!0;break;case e.keys.LEFT:H.ctrlKey||H.metaKey||H.shiftKey?U(2*Math.PI*e.rotateSpeed/e.domElement.clientHeight):x(e.keyPanSpeed,0),X=!0;break;case e.keys.RIGHT:H.ctrlKey||H.metaKey||H.shiftKey?U(-2*Math.PI*e.rotateSpeed/e.domElement.clientHeight):x(-e.keyPanSpeed,0),X=!0;break}X&&(H.preventDefault(),e.update())}function QA(){if(y.length===1)Q.set(y[0].pageX,y[0].pageY);else{const H=.5*(y[0].pageX+y[1].pageX),X=.5*(y[0].pageY+y[1].pageY);Q.set(H,X)}}function NA(){if(y.length===1)c.set(y[0].pageX,y[0].pageY);else{const H=.5*(y[0].pageX+y[1].pageX),X=.5*(y[0].pageY+y[1].pageY);c.set(H,X)}}function $(){const H=y[0].pageX-y[1].pageX,X=y[0].pageY-y[1].pageY,jA=Math.sqrt(H*H+X*X);u.set(0,jA)}function OA(){e.enableZoom&&$(),e.enablePan&&NA()}function HA(){e.enableZoom&&$(),e.enableRotate&&QA()}function qA(H){if(y.length==1)E.set(H.pageX,H.pageY);else{const jA=oe(H),VA=.5*(H.pageX+jA.x),TA=.5*(H.pageY+jA.y);E.set(VA,TA)}h.subVectors(E,Q).multiplyScalar(e.rotateSpeed);const X=e.domElement;U(2*Math.PI*h.x/X.clientHeight),M(2*Math.PI*h.y/X.clientHeight),Q.copy(E)}function wA(H){if(y.length===1)l.set(H.pageX,H.pageY);else{const X=oe(H),jA=.5*(H.pageX+X.x),VA=.5*(H.pageY+X.y);l.set(jA,VA)}d.subVectors(l,c).multiplyScalar(e.panSpeed),x(d.x,d.y),c.copy(l)}function cA(H){const X=oe(H),jA=H.pageX-X.x,VA=H.pageY-X.y,TA=Math.sqrt(jA*jA+VA*VA);p.set(0,TA),D.set(0,Math.pow(p.y/u.y,e.zoomSpeed)),b(D.y),u.copy(p)}function yA(H){e.enableZoom&&cA(H),e.enablePan&&wA(H)}function lA(H){e.enableZoom&&cA(H),e.enableRotate&&qA(H)}function YA(H){e.enabled!==!1&&(y.length===0&&(e.domElement.addEventListener("pointermove",JA),e.domElement.addEventListener("pointerup",ne)),FA(H),H.pointerType==="touch"?L(H):re(H))}function JA(H){e.enabled!==!1&&(H.pointerType==="touch"?J(H):Be(H))}function ne(H){vA(H),y.length===0&&(e.domElement.removeEventListener("pointermove",JA),e.domElement.removeEventListener("pointerup",ne)),e.dispatchEvent(tY),i=g.NONE}function uA(H){vA(H)}function re(H){let X;switch(H.button){case 0:X=e.mouseButtons.LEFT;break;case 1:X=e.mouseButtons.MIDDLE;break;case 2:X=e.mouseButtons.RIGHT;break;default:X=-1}switch(X){case qn.DOLLY:if(e.enableZoom===!1)return;sA(H),i=g.DOLLY;break;case qn.ROTATE:if(H.ctrlKey||H.metaKey||H.shiftKey){if(e.enablePan===!1)return;AA(H),i=g.PAN}else{if(e.enableRotate===!1)return;gA(H),i=g.ROTATE}break;case qn.PAN:if(H.ctrlKey||H.metaKey||H.shiftKey){if(e.enableRotate===!1)return;gA(H),i=g.ROTATE}else{if(e.enablePan===!1)return;AA(H),i=g.PAN}break;default:i=g.NONE}i!==g.NONE&&e.dispatchEvent(hm)}function Be(H){switch(i){case g.ROTATE:if(e.enableRotate===!1)return;dA(H);break;case g.DOLLY:if(e.enableZoom===!1)return;rA(H);break;case g.PAN:if(e.enablePan===!1)return;LA(H);break}}function Je(H){e.enabled===!1||e.enableZoom===!1||i!==g.NONE||(H.preventDefault(),e.dispatchEvent(hm),MA(H),e.dispatchEvent(tY))}function ot(H){e.enabled===!1||e.enablePan===!1||iA(H)}function L(H){switch(_A(H),y.length){case 1:switch(e.touches.ONE){case vn.ROTATE:if(e.enableRotate===!1)return;QA(),i=g.TOUCH_ROTATE;break;case vn.PAN:if(e.enablePan===!1)return;NA(),i=g.TOUCH_PAN;break;default:i=g.NONE}break;case 2:switch(e.touches.TWO){case vn.DOLLY_PAN:if(e.enableZoom===!1&&e.enablePan===!1)return;OA(),i=g.TOUCH_DOLLY_PAN;break;case vn.DOLLY_ROTATE:if(e.enableZoom===!1&&e.enableRotate===!1)return;HA(),i=g.TOUCH_DOLLY_ROTATE;break;default:i=g.NONE}break;default:i=g.NONE}i!==g.NONE&&e.dispatchEvent(hm)}function J(H){switch(_A(H),i){case g.TOUCH_ROTATE:if(e.enableRotate===!1)return;qA(H),e.update();break;case g.TOUCH_PAN:if(e.enablePan===!1)return;wA(H),e.update();break;case g.TOUCH_DOLLY_PAN:if(e.enableZoom===!1&&e.enablePan===!1)return;yA(H),e.update();break;case g.TOUCH_DOLLY_ROTATE:if(e.enableZoom===!1&&e.enableRotate===!1)return;lA(H),e.update();break;default:i=g.NONE}}function BA(H){e.enabled!==!1&&H.preventDefault()}function FA(H){y.push(H)}function vA(H){delete k[H.pointerId];for(let X=0;X<y.length;X++)if(y[X].pointerId==H.pointerId){y.splice(X,1);return}}function _A(H){let X=k[H.pointerId];X===void 0&&(X=new W,k[H.pointerId]=X),X.set(H.pageX,H.pageY)}function oe(H){const X=H.pointerId===y[0].pointerId?y[1]:y[0];return k[X.pointerId]}e.domElement.addEventListener("contextmenu",BA),e.domElement.addEventListener("pointerdown",YA),e.domElement.addEventListener("pointercancel",uA),e.domElement.addEventListener("wheel",Je,{passive:!1}),this.update()}};class m6{static createButton(A,e={},g){const i=document.createElement("button");let I=!1;function o(){if(e.optionalFeatures=e.optionalFeatures||[],e.domOverlay===void 0){var n=document.createElement("div");n.style.display="none",document.body.appendChild(n);var B=document.createElementNS("http://www.w3.org/2000/svg","svg");B.setAttribute("width",38),B.setAttribute("height",38),B.style.position="absolute",B.style.right="20px",B.style.top="20px",B.addEventListener("click",function(){E.end()}),n.appendChild(B);var Q=document.createElementNS("http://www.w3.org/2000/svg","path");Q.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),Q.setAttribute("stroke","#fff"),Q.setAttribute("stroke-width",2),B.appendChild(Q),e.optionalFeatures.push("dom-overlay"),e.domOverlay={root:n},I=!0}let E=null,h=null;async function c(d){var u;const p=/WebXRViewer\//i.test(navigator.userAgent),D=e.domOverlay.root;p&&((u=e.domOverlay)!=null&&u.root?(h=D.parentNode,h&&(console.log("Reparent DOM Overlay to body",D,D.style.display),D.style.display="",D.style.visibility="",document.body.appendChild(D))):console.warn("WebXRViewer: No DOM Overlay found")),d.addEventListener("end",l),await A.xr.setSession(d),i.textContent="STOP AR",I&&(e.domOverlay.root.style.display=""),E=d}function l(){E.removeEventListener("end",l),i.textContent="START AR";const d=e.domOverlay.root;h&&h.appendChild(d),I&&(d.style.display="none"),E=null}i.style.display="",i.style.cursor="pointer",i.style.left="calc(50% - 50px)",i.style.width="100px",i.textContent="START AR",i.onmouseenter=function(){i.style.opacity="1.0"},i.onmouseleave=function(){i.style.opacity="0.5"},i.onclick=function(){E===null?(g?.call(this,e),navigator.xr.requestSession("immersive-ar",e).then(c)):E.end()}}function C(){i.disabled=!0,i.style.display="",i.style.cursor="auto",i.style.left="calc(50% - 75px)",i.style.width="150px",i.onmouseenter=null,i.onmouseleave=null,i.onclick=null}function s(){C(),i.textContent="AR NOT SUPPORTED"}function a(n){n.style.position="absolute",n.style.bottom="20px",n.style.padding="12px 6px",n.style.border="1px solid #fff",n.style.borderRadius="4px",n.style.background="rgba(0,0,0,0.1)",n.style.color="#fff",n.style.font="normal 13px sans-serif",n.style.textAlign="center",n.style.opacity="0.5",n.style.outline="none",n.style.zIndex="999"}if("xr"in navigator)return i.id="ARButton",i.style.display="none",a(i),navigator.xr.isSessionSupported("immersive-ar").then(function(n){n?o():s()}).catch(s),i;{const n=document.createElement("a");return window.isSecureContext===!1?(n.href=document.location.href.replace(/^http:/,"https:"),n.innerHTML="WEBXR NEEDS HTTPS"):(n.href="https://immersiveweb.dev/",n.innerHTML="WEBXR NOT AVAILABLE"),n.style.left="calc(50% - 90px)",n.style.width="180px",n.style.textDecoration="none",a(n),n}}}const cm=class{static createButton(t,A){const e=document.createElement("button");function g(){let C=null;async function s(n){n.addEventListener("end",a),await t.xr.setSession(n),e.textContent="EXIT VR",C=n}function a(){C.removeEventListener("end",a),e.textContent="ENTER VR",C=null}e.style.display="",e.style.cursor="pointer",e.style.left="calc(50% - 50px)",e.style.width="100px",e.textContent="ENTER VR",e.onmouseenter=function(){e.style.opacity="1.0"},e.onmouseleave=function(){e.style.opacity="0.5"},e.onclick=function(){if(C===null){const n={optionalFeatures:A.optionalFeatures};navigator.xr.requestSession("immersive-vr",n).then(s)}else C.end()}}function i(){e.disabled=!0,e.style.display="",e.style.cursor="auto",e.style.left="calc(50% - 75px)",e.style.width="150px",e.onmouseenter=null,e.onmouseleave=null,e.onclick=null}function I(){i(),e.textContent="VR NOT SUPPORTED"}function o(C){C.style.position="absolute",C.style.bottom="20px",C.style.padding="12px 6px",C.style.border="1px solid #fff",C.style.borderRadius="4px",C.style.background="rgba(0,0,0,0.1)",C.style.color="#fff",C.style.font="normal 13px sans-serif",C.style.textAlign="center",C.style.opacity="0.5",C.style.outline="none",C.style.zIndex="999"}if("xr"in navigator)return e.id="VRButton",e.style.display="none",o(e),navigator.xr.isSessionSupported("immersive-vr").then(function(C){C?g():I(),cm.xrSessionIsGranted&&(console.log("XR session is granted - will enter immersive web now"),e.click())}),e;{const C=document.createElement("a");return window.isSecureContext===!1?(C.href=document.location.href.replace(/^http:/,"https:"),C.innerHTML="WEBXR NEEDS HTTPS"):(C.href="https://immersiveweb.dev/",C.innerHTML="WEBXR NOT AVAILABLE"),C.style.left="calc(50% - 90px)",C.style.width="180px",C.style.textDecoration="none",o(C),C}}static registerSessionGrantedListener(){if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent))return;navigator.xr.addEventListener("sessiongranted",()=>{cm.xrSessionIsGranted=!0})}}};let lm=cm;r(lm,"xrSessionIsGranted",!1),lm.registerSessionGrantedListener();const _D="noVoip",rI=CA("debugvoip"),M6=CA("voip");class R6{constructor(A){r(this,"id"),this.id=A}}class U6{constructor(A,e,g,i){r(this,"peer"),r(this,"voip"),r(this,"userId"),r(this,"peerId"),r(this,"call",null),r(this,"callErrorListener",null),r(this,"stream",null),this.voip=A,this.peer=e,this.userId=g,this.peerId=i}close(){var A;rI&&console.log("close voip call"),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.open&&this.call.close(),(A=this.stream)==null||A.getTracks().forEach(function(e){e.stop()})}updateMute(A){var e;if(!this.stream)return;const g=(e=this.stream)==null?void 0:e.getAudioTracks();for(const i of g)i.enabled=!A}async startVoipCall(){if(!await ia.HasMicrophonePermissions()){console.warn("no permission to use microphone, can not start call");return}rI&&console.log("start voip call"),this.stream=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),this.updateMute(this.voip.muteOutput),rI&&console.log(this.stream),this.call=this.peer.call(this.peerId,this.stream,{metadata:{userId:this.userId}}),this.call.on("error",A=>{console.error(A)}),this.call.on("stream",A=>{rI&&console.log("received stream from remote again",A)}),this.peer.on("close",this.onCallClose.bind(this)),this.callErrorListener=A=>{var e;A.message.includes(this.peerId)?(console.log("Could not connect to "+this.peerId),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.close(),(e=this.stream)==null||e.getTracks().forEach(function(g){g.stop()}),this.stream=null):console.error(A)},this.peer.on("error",this.callErrorListener)}onCallClose(A){rI&&console.log("call closed",A)}}class F6{constructor(A,e,g){r(this,"voip"),r(this,"call"),r(this,"audio",null),r(this,"stream",null),r(this,"obj"),r(this,"analyzer",null),r(this,"waitingForStart",!1),r(this,"closed",!1),r(this,"audioElement",null),this.voip=A,this.obj=e,this.call=g}get currentStream(){return this.stream}get currentAudio(){return this.audio}get currentAnalyzer(){return this.analyzer}openAudioStream(A){const e=A.getAudioTracks();for(const g of e)if(g.kind==="audio"&&g.readyState==="live"){this.open(g);return}console.warn("failed finding valid audio stream to begin call")}open(A){console.assert(A.kind==="audio","invalid track kind, expected audio but received "+A.kind),!this.waitingForStart&&(this.waitingForStart=!0,cg.userInteractionRegistered||rI&&console.log("Incoming call, waiting for user interaction before opening audio"),cg.registerWaitForAllowAudio(async()=>{if(this.call.open&&!this.closed){rI&&console.log("Setup audio and begin listening"),this.stream=new MediaStream([A]);const e=new xf;this.audio=new gu(e),this.audio.setVolume(this.voip.muteInput?0:1),this.audio.setMediaStreamSource(this.stream);const g=document.createElement("audio");this.audioElement=g,g.style.display="none",document.body.appendChild(g),g.srcObject=this.stream,g.sinkId!==void 0&&navigator.mediaDevices.enumerateDevices().then(i=>{if(g){console.log(i);for(const I of i)if(I.label==="Speakerphone"){g.sinkId=I.deviceId;break}}}),rI&&console.log("call is setup, you should hear something now"),this.analyzer=new ZK(this.audio,32)}}))}close(){var A,e,g;this.closed=!0,(A=this.call)!=null&&A.open&&this.call.close(),(e=this.audio)==null||e.disconnect(),(g=this.stream)==null||g.getTracks().forEach(i=>{i.stop()}),this.stream=null,this.audioElement&&this.audioElement.remove()}}class ia extends RA{constructor(){super(...arguments),r(this,"requireParam",!1),r(this,"peer",null),r(this,"model",null),r(this,"connections",{}),r(this,"currentIncomingCalls",{}),r(this,"_inputMuted",!1),r(this,"_outputMuted",!1)}set muteInput(A){var e;if(A===this._inputMuted||(this._inputMuted=A,!this.currentIncomingCalls))return;const g=this._inputMuted?0:1;for(const i in this.currentIncomingCalls){const I=this.currentIncomingCalls[i];(e=I?.currentAudio)==null||e.setVolume(g)}}get muteInput(){return this._inputMuted}set muteOutput(A){if(A!==this._outputMuted&&(this._outputMuted=A,!!this.connections))for(const e in this.connections){const g=this.connections[e];g?.updateMute(A)}}get muteOutput(){return this._outputMuted}getFrequency(A){if(A===null){for(const g in this.currentIncomingCalls){const i=this.currentIncomingCalls[g];if(i&&i.currentAnalyzer)return i.currentAnalyzer.getAverageFrequency()}return null}const e=this.currentIncomingCalls[A];return e&&e.currentAnalyzer?e.currentAnalyzer.getAverageFrequency():null}awake(){if(CA(_D)){console.log("VOIP is disabled by url parameter: "+_D);return}if(this.requireParam&&!M6){console.debug("VOIP must be enabled explicitly by url parameter");return}if($E()&&WC()){console.log("VOIP is currently not supported on Safari iOS");return}this.peer=new Yu,navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia,this.context.connection.beginListen(Wt.JoinedRoom,A=>{navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}),this.context.connection.beginListen("peer-update-id",A=>{if(A.id!==this.context.connection.connectionId){const e=this.connections[A.id];if(e&&e.close(),this.peer&&this.context.connection.connectionId){const g=new U6(this,this.peer,this.context.connection.connectionId,A.peerId);this.connections[A.id]=g,g.startVoipCall()}}}),this.context.connection.beginListen(Wt.UserLeftRoom,A=>{const{userId:e}=A,g=this.connections[e];this.connections[e]=null,g&&g.close();const i=this.currentIncomingCalls[e];rI&&console.log("UserLeftRoom",A,e,i),i&&(i.close(),this.currentIncomingCalls[e]=null)}),this.peer.on("open",this.onOpenPeerConnection.bind(this))}onEnable(){}onDisable(){console.log("TODO: close all");for(const A in this.currentIncomingCalls)try{const e=this.currentIncomingCalls[A];e?.close();const g=this.connections[A];g?.close()}catch(e){console.error(e)}}async onOpenPeerConnection(A){rI&&console.log("Peer connection established and received id"),this.model=new R6(A),this.context.connection.send("peer-update-id",this.model,oI.OnRoomJoin),this.peer&&(this.peer.on("call",this.onReceiveCall.bind(this)),this.peer.on("connection",function(e){rI&&console.log("CONNECTION",e),e.on("data",function(g){rI&&console.log("Received",g)})}))}async onReceiveCall(A){const{metadata:e}=A;console.assert(e.userId);const{userId:g}=e,i=this.currentIncomingCalls[g];if(i&&i.close(),rI&&console.log("received call"),await ia.HasMicrophonePermissions()){const I=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1});A.answer(I)}else A.answer(null);this.currentIncomingCalls[g]=new F6(this,this.gameObject,A),A.on("stream",I=>{var o;rI&&console.log("receive caller stream, will setup audio now"),(o=this.currentIncomingCalls[g])==null||o.openAudioStream(I)}),A.on("error",console.error)}static async HasMicrophonePermissions(){return(await navigator.permissions.query({name:"microphone"})).state!=="denied"}}var N6=Object.defineProperty,K6=Object.getOwnPropertyDescriptor,gY=(t,A,e,g)=>{for(var i=g>1?void 0:g?K6(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&N6(A,e,i),i};class tn extends RA{constructor(){super(...arguments),r(this,"webAR",null),r(this,"invertForward",!1),r(this,"_initalMatrix",new KA),r(this,"_selectStartFn",this.onSelectStart.bind(this)),r(this,"_selectEndFn",this.onSelectEnd.bind(this)),r(this,"_arScale",5),r(this,"_rig",null),r(this,"_startPose",null),r(this,"_placementPose",null),r(this,"_isTouching",!1),r(this,"_rigStartPose",null),r(this,"_gotFirstHitTestResult",!1)}get rig(){var A;return(A=this.webAR)==null?void 0:A.webxr.Rig}get arScale(){return this._arScale}set arScale(A){A!==this._arScale&&(this._arScale=A,this.setScale(A))}start(){const A=eA.findObjectOfType(Se);A&&(A.Rig.updateMatrix(),this._initalMatrix.copy(A.Rig.matrix))}onBegin(A){var e;this._placementPose=null,this.gameObject.visible=!1,this.gameObject.matrixAutoUpdate=!1,this._startPose=this.gameObject.matrix.clone(),this._rigStartPose=(e=this.rig)==null?void 0:e.matrix.clone(),this._gotFirstHitTestResult=!1,A.addEventListener("selectstart",this._selectStartFn),A.addEventListener("selectend",this._selectEndFn),this.gameObject.visible=!1,this.rig&&(this.rig.matrixAutoUpdate=!0,this._initalMatrix.decompose(this.rig.position,this.rig.quaternion,this.rig.scale)),this.dispatchEvent(new CustomEvent("onBeginSession"))}onUpdate(A,e,g){if(g&&!this._placementPose&&(this._gotFirstHitTestResult||(this._gotFirstHitTestResult=!0,this.dispatchEvent(new CustomEvent("canPlaceSession",{detail:{pose:g}}))),this._isTouching)){const i=new KA().fromArray(g.transform.matrix).invert();return this.dispatchEvent(new CustomEvent("placedSession",{detail:{pose:g,poseMatrix:i}})),this.webAR&&this.webAR.setReticleActive(!1),this.placeAt(A,i),!0}return!1}placeAt(A,e){this._placementPose||(this._placementPose=new KA),this._placementPose.copy(e);const g=this.gameObject.matrixWorld.clone().invert();if(this._placementPose.premultiply(g),A){if(this.invertForward){const i=new KA().makeRotationY(Math.PI);this._placementPose.premultiply(i)}this._rig=A,this.setScale(this.arScale)}else this._rig=null;this.gameObject.visible=!0}onEnd(A,e){this._placementPose=null,this.gameObject.visible=!1,this.gameObject.matrixAutoUpdate=!1,this._startPose&&this.gameObject.matrix.copy(this._startPose),A&&(A.matrixAutoUpdate=!0,this._rigStartPose&&this._rigStartPose.decompose(A.position,A.quaternion,A.scale)),pI.markDirty(this.gameObject,!0),setTimeout(()=>{this.gameObject.matrixAutoUpdate=!0,this.gameObject.visible=!0},100)}onSelectStart(){this._isTouching=!0}onSelectEnd(){this._isTouching=!1}setScale(A){const e=this._rig;!e||!this._placementPose||(this._rigStartPose||(this._rigStartPose=e.matrix.clone()),e.matrixAutoUpdate=!1,e.matrix.multiplyMatrices(new KA().makeScale(A,A,A),this._placementPose),e.matrix.decompose(e.position,e.quaternion,e.scale),e.updateMatrixWorld(),console.log("Place",e.position))}}gY([w()],tn.prototype,"invertForward",2),gY([w()],tn.prototype,"arScale",1);const J6="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/";class q6{constructor(A,e,g,i,I=null){this.controller=e,this.handModel=A,this.bones=[],I===null&&(I=new BQ,I.setPath(g||J6)),I.load(`${i}.glb`,o=>{const C=o.scene.children[0];this.handModel.add(C),C.layers.mask=this.handModel.layers.mask;const s=C.getObjectByProperty("type","SkinnedMesh");s.frustumCulled=!1,s.castShadow=!0,s.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 n=C.getObjectByName(a);n!==void 0?n.jointName=a:console.warn(`Couldn't find ${a} in ${i} hand mesh`),this.bones.push(n)})})}updateMesh(){const A=this.controller.joints;for(let e=0;e<this.bones.length;e++){const g=this.bones[e];if(g){const i=A[g.jointName];if(i.visible){const I=i.position;g.position.copy(I),g.quaternion.copy(i.quaternion)}}}}}const v6=.01,b6="index-finger-tip";class L6 extends UA{constructor(A,e=null){super(),this.controller=A,this.motionController=null,this.envMap=null,this.loader=e,this.mesh=null,A.addEventListener("connected",g=>{const i=g.data;i.hand&&!this.motionController&&(this.xrInputSource=i,this.motionController=new q6(this,A,this.path,i.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[b6];return A?A.position:null}intersectBoxObject(A){const e=this.getPointerPosition();if(e){const g=new Ro(e,v6),i=new li().setFromObject(A);return g.intersectsBox(i)}else return!1}checkButton(A){this.intersectBoxObject(A)?A.onPress():A.onClear(),A.isPressed()&&A.whilePressed()}}const x6=.05,iY=.02,PD=.01,IY=.02,oY=1,qQ=.4,Y6=.002,Jc=.01,jD=.003,CY=.035,yt=16,no=12,dm=110,H6=new f(0,1,0),T6=new f(0,0,1),O6=.02,_6=1.5;class P6 extends UA{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,A.addEventListener("connected",g=>{const i=g.data;i.hand&&(this.visible=!0,this.xrInputSource=i,this.pointerObject===null&&this.createPointer())})}_drawVerticesRing(A,e,g){const i=e.clone();for(let I=0;I<yt;I++){i.applyAxisAngle(T6,Math.PI*2/yt);const o=g*yt+I;A[3*o]=i.x,A[3*o+1]=i.y,A[3*o+2]=i.z}}_updatePointerVertices(A){const e=this.pointerGeometry.attributes.position.array,g=new f(Y6,0,-1*(CY-A));this._drawVerticesRing(e,g,0);const i=new f(Math.sin(Math.PI*dm/180)*A,Math.cos(Math.PI*dm/180)*A,0);for(let a=0;a<no;a++)this._drawVerticesRing(e,i,a+1),i.applyAxisAngle(H6,Math.PI*dm/180/(no*-2));const I=yt*(1+no),o=yt*(1+no)+1,C=new f(0,0,-1*(CY-A));e[I*3]=C.x,e[I*3+1]=C.y,e[I*3+2]=C.z;const s=new f(0,0,A);e[o*3]=s.x,e[o*3+1]=s.y,e[o*3+2]=s.z,this.pointerGeometry.setAttribute("position",new ee(e,3))}createPointer(){let A,e;const g=new Array(((no+1)*yt+2)*3).fill(0),i=[];for(this.pointerGeometry=new le,this.pointerGeometry.setAttribute("position",new ee(g,3)),this._updatePointerVertices(Jc),A=0;A<no;A++){for(e=0;e<yt-1;e++)i.push(A*yt+e,A*yt+e+1,(A+1)*yt+e),i.push(A*yt+e+1,(A+1)*yt+e+1,(A+1)*yt+e);i.push((A+1)*yt-1,A*yt,(A+2)*yt-1),i.push(A*yt,(A+1)*yt,(A+2)*yt-1)}const I=yt*(1+no),o=yt*(1+no)+1;for(A=0;A<yt-1;A++)i.push(I,A+1,A),i.push(o,A+yt*no,A+yt*no+1);i.push(I,0,yt-1),i.push(o,yt*(no+1)-1,yt*no);const C=new dt;C.transparent=!0,C.opacity=qQ,this.pointerGeometry.setIndex(i),this.pointerMesh=new DA(this.pointerGeometry,C),this.pointerMesh.position.set(0,0,-1*Jc),this.pointerObject=new UA,this.pointerObject.add(this.pointerMesh),this.raycaster=new VB;const s=new OI(O6,10,10),a=new dt;a.transparent=!0,a.opacity=qQ,this.cursorObject=new DA(s,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 KA;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"],g=A.position.distanceTo(e.position),i=A.position.clone().add(e.position).multiplyScalar(.5);this.pointerObject.position.copy(i),this.pointerObject.quaternion.copy(this.controller.quaternion),this.pinched=g<=iY;const I=(g-PD)/(x6-PD),o=(g-PD)/(iY-PD);if(I>1)this._updatePointerVertices(Jc),this.pointerMesh.position.set(0,0,-1*Jc),this.pointerMesh.material.opacity=qQ;else if(I>0){const C=(Jc-jD)*I+jD;this._updatePointerVertices(C),o<1?(this.pointerMesh.position.set(0,0,-1*C-(1-o)*IY),this.pointerMesh.material.opacity=qQ+(1-o)*(oY-qQ)):(this.pointerMesh.position.set(0,0,-1*C),this.pointerMesh.material.opacity=qQ)}else this._updatePointerVertices(jD),this.pointerMesh.position.set(0,0,-1*jD-IY),this.pointerMesh.material.opacity=oY;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 g=this.raycaster.intersectObjects(A,e),i=new f(0,0,-1);if(g.length>0){const I=g[0].distance;this.cursorObject.position.copy(i.multiplyScalar(I))}else this.cursorObject.position.copy(i.multiplyScalar(_6))}}setCursor(A){const e=new f(0,0,-1);this.raycaster&&!this.attached&&this.cursorObject.position.copy(e.multiplyScalar(A))}}const Vt={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 sY(t){const A=await fetch(t);if(A.ok)return A.json();throw new Error(A.statusText)}async function j6(t){if(!t)throw new Error("No basePath supplied");return await sY(`${t}/profilesList.json`)}async function W6(t,A,e=null,g=!0){if(!t)throw new Error("No xrInputSource supplied");if(!A)throw new Error("No basePath supplied");const i=await j6(A);let I;if(t.profiles.some(s=>{const a=i[s];return a&&(I={profileId:s,profilePath:`${A}/${a.path}`,deprecated:!!a.deprecated}),!!I}),!I){if(!e)throw new Error("No matching profile name found");const s=i[e];if(!s)throw new Error(`No matching profile name found and default profile "${e}" missing.`);I={profileId:e,profilePath:`${A}/${s.path}`,deprecated:!!s.deprecated}}const o=await sY(I.profilePath);let C;if(g){let s;if(t.handedness==="any"?s=o.layouts[Object.keys(o.layouts)[0]]:s=o.layouts[t.handedness],!s)throw new Error(`No matching handedness, ${t.handedness}, in profile ${I.profileId}`);s.assetPath&&(C=I.profilePath.replace("profile.json",s.assetPath))}return{profile:o,assetPath:C}}const V6={xAxis:0,yAxis:0,button:0,state:Vt.ComponentState.DEFAULT};function z6(t=0,A=0){let e=t,g=A;if(Math.sqrt(t*t+A*A)>1){const i=Math.atan2(A,t);e=Math.cos(i),g=Math.sin(i)}return{normalizedXAxis:e*.5+.5,normalizedYAxis:g*.5+.5}}class Z6{constructor(A){this.componentProperty=A.componentProperty,this.states=A.states,this.valueNodeName=A.valueNodeName,this.valueNodeProperty=A.valueNodeProperty,this.valueNodeProperty===Vt.VisualResponseProperty.TRANSFORM&&(this.minNodeName=A.minNodeName,this.maxNodeName=A.maxNodeName),this.value=0,this.updateFromComponent(V6)}updateFromComponent({xAxis:A,yAxis:e,button:g,state:i}){const{normalizedXAxis:I,normalizedYAxis:o}=z6(A,e);switch(this.componentProperty){case Vt.ComponentProperty.X_AXIS:this.value=this.states.includes(i)?I:.5;break;case Vt.ComponentProperty.Y_AXIS:this.value=this.states.includes(i)?o:.5;break;case Vt.ComponentProperty.BUTTON:this.value=this.states.includes(i)?g:0;break;case Vt.ComponentProperty.STATE:this.valueNodeProperty===Vt.VisualResponseProperty.VISIBILITY?this.value=this.states.includes(i):this.value=this.states.includes(i)?1:0;break;default:throw new Error(`Unexpected visualResponse componentProperty ${this.componentProperty}`)}}}class X6{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(g=>{const i=new Z6(e.visualResponses[g]);this.visualResponses[g]=i}),this.gamepadIndices=Object.assign({},e.gamepadIndices),this.values={state:Vt.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=Vt.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=Vt.ComponentState.PRESSED:(e.touched||this.values.button>Vt.ButtonTouchThreshold)&&(this.values.state=Vt.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===Vt.ComponentState.DEFAULT&&Math.abs(this.values.xAxis)>Vt.AxisTouchThreshold&&(this.values.state=Vt.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===Vt.ComponentState.DEFAULT&&Math.abs(this.values.yAxis)>Vt.AxisTouchThreshold&&(this.values.state=Vt.ComponentState.TOUCHED)),Object.values(this.visualResponses).forEach(e=>{e.updateFromComponent(this.values)})}}class $6{constructor(A,e,g){if(!A)throw new Error("No xrInputSource supplied");if(!e)throw new Error("No profile supplied");this.xrInputSource=A,this.assetUrl=g,this.id=e.profileId,this.layoutDescription=e.layouts[A.handedness],this.components={},Object.keys(this.layoutDescription.components).forEach(i=>{const I=this.layoutDescription.components[i];this.components[i]=new X6(i,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 A7="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",e7="generic-trigger";class t7 extends UA{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(g=>{const{valueNode:i,minNode:I,maxNode:o,value:C,valueNodeProperty:s}=g;i&&(s===Vt.VisualResponseProperty.VISIBILITY?i.visible=C:s===Vt.VisualResponseProperty.TRANSFORM&&(i.quaternion.slerpQuaternions(I.quaternion,o.quaternion,C),i.position.lerpVectors(I.position,o.position,C)))})}))}}function g7(t,A){Object.values(t.components).forEach(e=>{const{type:g,touchPointNodeName:i,visualResponses:I}=e;if(g===Vt.ComponentType.TOUCHPAD)if(e.touchPointNode=A.getObjectByName(i),e.touchPointNode){const o=new OI(.001),C=new dt({color:255}),s=new DA(o,C);e.touchPointNode.add(s)}else console.warn(`Could not find touch dot, ${e.touchPointNodeName}, in touchpad component ${e.id}`);Object.values(I).forEach(o=>{const{valueNodeName:C,minNodeName:s,maxNodeName:a,valueNodeProperty:n}=o;if(n===Vt.VisualResponseProperty.TRANSFORM){if(o.minNode=A.getObjectByName(s),o.maxNode=A.getObjectByName(a),!o.minNode){console.warn(`Could not find ${s} in the model`);return}if(!o.maxNode){console.warn(`Could not find ${a} in the model`);return}}o.valueNode=A.getObjectByName(C),o.valueNode||console.warn(`Could not find ${C} in the model`)})})}function aY(t,A){g7(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 i7{constructor(A=null){this.gltfLoader=A,this.path=A7,this._assetCache={},this.gltfLoader||(this.gltfLoader=new BQ)}createControllerModel(A){const e=new t7;let g=null;return A.addEventListener("connected",i=>{const I=i.data;I.targetRayMode!=="tracked-pointer"||!I.gamepad||W6(I,this.path,e7).then(({profile:o,assetPath:C})=>{e.motionController=new $6(I,o,C);const s=this._assetCache[e.motionController.assetUrl];if(s)g=s.scene.clone(),aY(e,g);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,g=a.scene.clone(),aY(e,g)},null,()=>{throw new Error(`Asset ${e.motionController.assetUrl} missing or malformed.`)})}}).catch(o=>{console.warn(o)})}),A.addEventListener("disconnected",()=>{e.motionController=null,e.remove(g),g=null}),e}}const qc=CA("debugavatar");class WD{constructor(A,e,g,i){r(this,"root"),r(this,"head"),r(this,"leftHand"),r(this,"rigthHand");var I;this.root=A,this.head=e,this.leftHand=g,this.rigthHand=i,(I=this.root)==null||I.traverse(o=>o.layers.set(2))}get isValid(){return this.head!==null&&this.head!==void 0}}class VD{constructor(){r(this,"avatarRegistryUrl",null)}async getOrCreateNewAvatarInstance(A,e){if(!e)return console.error("Can not create avatar: failed to provide id or root object"),null;let g=null;if(typeof e=="string"){if(g=await this.loadAvatar(A,e),!g){const I=new rC;g=eA.instantiate(BB(e,A.scene),I)}}else g=e;if(!g)return null;const i=this.findAvatar(g);return i.isValid?(qc&&console.log("[Custom Avatar] valid config",e,qc?i:""),i):(console.warn("[Custom Avatar] config isn't valid",e,qc?i:""),null)}async loadAvatar(A,e){if(console.assert(e!=null&&typeof e=="string","Avatar id must not be null"),e.length<=0||!e)return null;if(qc&&console.log("[Custom Avatar] "+e+", loading..."),e.endsWith(".glb")||(e+=".glb"),this.avatarRegistryUrl===null){const i=await fetch("./"+e);let I=null;if(i.ok){const C=await i.blob();C&&(I=await C.arrayBuffer())}if(!I&&(I=await $k(e,e,0,"no url here go away",!0),!I))return null;const o=await bo().parseSync(A,I,null,0);return o?.scene??null}const g=new BQ;return lc(g,A),new Promise((i,I)=>{const o=this.avatarRegistryUrl+"/"+e;g.load(o,async C=>{await bo().createBuiltinComponents(A,o,C,null,void 0),i(C.scene)},C=>{qc&&console.log("[Custom Avatar] "+C.loaded/C.total*100+"% loaded of "+C.total/1024+"kB")},C=>{console.error("[Custom Avatar] Error when loading: "+C),i(null)})})}cacheModel(A,e){}findAvatar(A){const e=A;let g=e;g.children.length==1&&(g=A.children[0]);let i=this.findAvatarPart(g,["head"]);const I=this.findAvatarPart(g,["left","hand"]),o=this.findAvatarPart(g,["right","hand"]);if(!i){i=e;const C=new f;new li().setFromObject(i).getSize(C);const s=Math.max(C.x,C.y,C.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+s+" meters! Should be < 0.3m"),s>.3&&i.scale.multiplyScalar(1/s*.3)}return new WD(e,i,I,o)}findAvatarPart(A,e){const g=A.name.toLowerCase();let i=!0;for(const I of e){if(!i)break;g.indexOf(I)===-1&&(i=!1)}if(i)return A;if(A.children)for(const I of A.children){const o=this.findAvatarPart(I,e);if(o)return o}return null}handleCustomAvatarErrors(A){if(!A.ok)throw Error(A.statusText);return A}}const vQ=CA("debugflags");var lg=(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))(lg||{});const nY=class{constructor(){r(this,"Mask",17)}Has(t){return(this.Mask&t)!==0}Set(t){vQ&&console.warn("Set XR flag state to",t),this.Mask=t,ji.Apply()}Enable(t){this.Mask|=t,ji.Apply()}Disable(t){this.Mask&=~t,ji.Apply()}Toggle(t){this.Mask^=t,ji.Apply()}EnableAll(){this.Mask=-1,ji.Apply()}DisableAll(){this.Mask=0,ji.Apply()}};let DC=nY;r(DC,"Global",new nY);const Fs=class extends RA{constructor(){super(...arguments),r(this,"visibleIn")}static Apply(){for(const t of this.registry)t.UpdateVisible(DC.Global)}awake(){Fs.registry.push(this)}onEnable(){Fs.firstApply?this.UpdateVisible(DC.Global):(Fs.firstApply=!0,Fs.Apply())}onDestroy(){const t=Fs.registry.indexOf(this);t>=0&&Fs.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),vQ&&console.log(e),Fs.buffer.Mask=e,t=Fs.buffer);const g=t;if(g?(vQ&&console.warn(this.name,"use passed in mask",g.Mask,this.visibleIn),A=g.Has(this.visibleIn)):(vQ&&console.log(this.name,"use global mask"),DC.Global.Has(this.visibleIn)),A!==void 0)if(A)vQ&&console.log(this.name,"is visible",this.gameObject.uuid),eA.setActive(this.gameObject,!0);else{if(vQ&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}};let ji=Fs;r(ji,"registry",[]),r(ji,"firstApply"),r(ji,"buffer",new DC);const gn=CA("debugavatar"),wC=class extends RA{constructor(){super(...arguments),r(this,"connectionId"),r(this,"avatar")}static getAvatar(t){return t>=0&&t<wC.instances.length?wC.instances[t]:null}static onAvatarMarkerCreated(t){return wC._onNewAvatarMarkerAdded.push(t),t}static onAvatarMarkerDestroyed(t){return wC._onAvatarMarkerDestroyed.push(t),t}awake(){wC.instances.push(this),gn&&console.log(this);for(const t of wC._onNewAvatarMarkerAdded)t({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){wC.instances.splice(wC.instances.indexOf(this),1);for(const t of wC._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):eA.setActive(this.avatar,t))}};let fi=wC;r(fi,"instances",[]),r(fi,"_onNewAvatarMarkerAdded",[]),r(fi,"_onAvatarMarkerDestroyed",[]);const zD=class{constructor(t,A,e){r(this,"_isVisible",!0),r(this,"guid"),r(this,"root",null),r(this,"head",null),r(this,"handLeft",null),r(this,"handRight",null),r(this,"lastUpdate",-1),r(this,"isLocalAvatar",!1),r(this,"flags",null),r(this,"headScale",new f(1,1,1)),r(this,"handLeftScale",new f(1,1,1)),r(this,"handRightScale",new f(1,1,1)),r(this,"webxr"),r(this,"lastAvatarId",null),r(this,"hasAvatarOverride",!1),r(this,"context"),r(this,"avatarMarker",null),r(this,"_headTarget",new UA),r(this,"_handLeftTarget",new UA),r(this,"_handRightTarget",new UA),r(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?lg.FirstPerson:lg.ThirdPerson;this.context.isInVR?t|=lg.VR:this.context.isInAR?t|=lg.AR:t|=lg.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?QC.Handheld:QC.Headset;let g=this.head;this.context.players.setPlayerView(t.guid,g,e),pI.markDirty(this.head),this._canInterpolate=!0;const i=this.isLocalAvatar?this.head:this._headTarget;if(i.position.set(t.position.x,t.position.y,t.position.z),i.quaternion.set(t.rotation.x,t.rotation.y,t.rotation.z,t.rotation.w),i.scale.set(t.scale,t.scale,t.scale),i.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(zD.invertRotation),I.scale.set(t.scale,t.scale,t.scale),I.scale.multiply(this.handLeftScale),pI.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(zD.invertRotation),I.scale.set(t.scale,t.scale,t.scale),I.scale.multiply(this.handRightScale),pI.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;gn&&console.log("Destroy avatar",this.guid),(t=this.root)==null||t.removeFromParent(),(A=this.avatarMarker)==null||A.destroy(),this.lastAvatarId=null,this.head&&Wi.Remove(this.context,this.head)}updateVisibility(){const t=this.root;t&&eA.setActive(t,this._isVisible)}async setupCustomAvatar(t){var A,e,g;if(gn&&console.log("LOAD",t,this),!t||typeof t=="string"&&t.length<=0)return!1;this.head&&Wi.Remove(this.context,this.head);const i=t;if(i?.loadAssetAsync!==void 0){await i.loadAssetAsync();const o=i.asset;eA.setActive(o,!1),t=eA.instantiate(o),eA.setActive(t,!0)}gn&&console.log(t);const I=await zD.loader.getOrCreateNewAvatarInstance(this.context,t);if(gn&&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=eA.addNewComponent(this.root,fi),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&&Wi.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&&((g=this.handRight)==null||g.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(...eA.getComponentsInChildren(this.root,ji)),this.flags.length<=0&&this.head){const o=eA.addNewComponent(this.head,ji);o.visibleIn=lg.ThirdPerson|lg.VR,this.flags.push(o),gn&&console.log("Added flag to head: "+o.visibleIn,this.head.name)}return gn&&console.log("[Avatar], is Local? ",this.isLocalAvatar,this.root),this.updateFlags(),this.updateVisibility(),!0}else return gn&&console.warn("build avatar failed"),!1}};let In=zD;r(In,"loader",new VD),r(In,"invertRotation",new mA().setFromAxisAngle(new f(0,1,0),Math.PI));class Wi{static Add(A,e,g=null){if(e){for(const i of this.Pois)if(i.obj===e)return;this.Pois.push({obj:e,avatar:g}),this.LastChangeTime=A.time.time}}static Remove(A,e){var g;if(e){for(const i of this.Pois)if(i.obj===e){this.Pois.splice(this.Pois.indexOf(i),1),this.LastChangeTime=A?.time.time??((g=be.Current)==null?void 0:g.time.time);return}}}}r(Wi,"Pois",[]),r(Wi,"LastChangeTime",0);class I7{constructor(){r(this,"guid"),r(this,"position",new f)}}class vc extends RA{constructor(){super(...arguments),r(this,"target",null),r(this,"avatar",null),r(this,"_model",null),r(this,"_targetModel",new I7),r(this,"_currentTargetObject",null),r(this,"_lastUpdateTime",0),r(this,"_lookDuration",0),r(this,"_lastPoiChangedTime",0)}set controlledTarget(A){this.target=A;const e=T.get("MoveRandom");if(e&&this.target){const g=eA.getComponent(this.target,e);g&&g.destroy()}}awake(){if(this.avatar=eA.getComponentInParent(this.gameObject,fi),this.avatar){const A=eA.getComponentInParent(this.gameObject,fi);this._model=new Hu(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)&&gg(this.target,A.position)})}update(){var A;if((!this.context.connection.isConnected||(A=this._model)!=null&&A.hasOwnership)&&(Wi.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=Wi.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){const e=we(this._currentTargetObject);gg(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=Wi.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 bQ extends RA{constructor(){super(...arguments),r(this,"canGrab",!0)}onPointerClick(A){}}class LQ extends RA{constructor(){super(...arguments),r(this,"isUsed",!0),r(this,"usedBy",null)}}var yC=(t=>(t[t.Average=0]="Average",t[t.Multiply=1]="Multiply",t[t.Minimum=2]="Minimum",t[t.Maximum=3]="Maximum",t))(yC||{}),ZD=(t=>(t[t.Discrete=0]="Discrete",t[t.Continuous=1]="Continuous",t))(ZD||{}),og=(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))(og||{}),xQ=(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))(xQ||{});const RI=function(t,A){return function(e,g,i){o7(e,g,i,t,A)}};function o7(t,A,e,g,i){if(!(!i&&!g&&!t.onValidate)){if(e!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",t,A,e),Qg("Invalid usage of validate decorator. Only fields can be validated. Property: "+A,ko.Error);return}if(t.__internalAwake){const I=Symbol(A),o=t.__internalAwake;t.__internalAwake=function(){this[I]===void 0&&(this[I]=this[A],Object.defineProperty(this,A,{set:function(C){var s;if(this[ik]===!0)this[I]=C;else{g?.call(this,C);const a=this[I];this[I]=C,(s=this.onValidate)==null||s.call(this,A,a)}},get:function(){return i?.call(this),this[I]}})),o.call(this)}}}}const C7=function(t){return function(A,e,g){const i=t.prototype,I=Object.getOwnPropertyDescriptor(i,e);if(!(I!=null&&I.value)){console.warn("Can not apply prefix: type does not have method named",e,t);return}const o=I.value,C=A[e];Object.defineProperty(i,e,{value:function(...s){const a=C?.call(this,...s);if(a instanceof Promise){a.then(n=>{if(n!==!1)return o.call(this,...s)});return}if(a!==!1)return o.call(this,...s)}})}};var s7=Object.defineProperty,a7=Object.getOwnPropertyDescriptor,Ns=(t,A,e,g)=>{for(var i=g>1?void 0:g?a7(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&s7(A,e,i),i};class n7{constructor(A,e){r(this,"positionChanged",!1),r(this,"rotationChanged",!1),r(this,"position"),r(this,"quaternion"),r(this,"_positionKeys",["x","y","z"]),r(this,"_quaternionKeys",["_x","_y","_z","_w"]),r(this,"mute",!1),r(this,"context"),r(this,"obj"),r(this,"_positionWatch"),r(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 JE(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((I,o)=>{var C;if((C=this.context.physics.engine)!=null&&C.isUpdating||this.mute)return;const s=this.position[o];Math.abs(s-I)<1e-5||(this.position[o]=I,this.positionChanged=!0)})),e&&(this._rotationWatch||(this._rotationWatch=new JE(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((I,o)=>{var C;if((C=this.context.physics.engine)!=null&&C.isUpdating||this.mute)return;const s=this.quaternion[o];Math.abs(s-I)<1e-5||(this.quaternion[o]=I,this.rotationChanged=!0)}));const g=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),i=new KA;this.obj.matrixWorld.multiplyMatrices=(I,o)=>(i.equals(I)||(this.positionChanged=!0,this.rotationChanged=!0,i.copy(I)),g(I,o))}stop(){var A,e;(A=this._positionWatch)==null||A.revoke(),(e=this._rotationWatch)==null||e.revoke()}}var pm;const um=(pm=class extends RA{constructor(){super(...arguments),r(this,"mass",1),r(this,"useGravity",!0),r(this,"constraints",og.None),r(this,"isKinematic",!1),r(this,"drag",0),r(this,"angularDrag",1),r(this,"detectCollisions",!0),r(this,"sleepThreshold",.01),r(this,"collisionDetectionMode",ZD.Discrete),r(this,"_gravityScale",1),r(this,"_propertiesChanged",!1),r(this,"_currentVelocity",new f),r(this,"_smoothedVelocity",new f),r(this,"_smoothedVelocityGetter",new f),r(this,"_lastPosition",new f),r(this,"_watch")}get lockPositionX(){return(this.constraints&og.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&og.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&og.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&og.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&og.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&og.FreezeRotationZ)!==0}set lockPositionX(t){t?this.constraints|=og.FreezePositionX:this.constraints&=~og.FreezePositionX}set lockPositionY(t){t?this.constraints|=og.FreezePositionY:this.constraints&=~og.FreezePositionY}set lockPositionZ(t){t?this.constraints|=og.FreezePositionZ:this.constraints&=~og.FreezePositionZ}set lockRotationX(t){t?this.constraints|=og.FreezeRotationX:this.constraints&=~og.FreezeRotationX}set lockRotationY(t){t?this.constraints|=og.FreezeRotationY:this.constraints&=~og.FreezeRotationY}set lockRotationZ(t){t?this.constraints|=og.FreezeRotationZ:this.constraints&=~og.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 n7(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),MI.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,g;;)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()):(g=this._watch)==null||g.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(){var t;(t=this.context.physics.engine)==null||t.resetForces(this,!0)}resetTorques(){var t;(t=this.context.physics.engine)==null||t.resetTorques(this,!0)}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){var e;(e=this.context.physics.engine)==null||e.addForce(this,t,!0)}applyImpulse(t){var A;(A=this.context.physics.engine)==null||A.applyImpulse(this,t,!0)}setForce(t,A,e){var g,i;(g=this.context.physics.engine)==null||g.resetForces(this,!0),(i=this.context.physics.engine)==null||i.addForce(this,{x:t,y:A,z:e},!0)}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){var g,i;if(t instanceof f){const I=t;(g=this.context.physics.engine)==null||g.setLinearVelocity(this,I,!0);return}A===void 0||e===void 0||(i=this.context.physics.engine)==null||i.setLinearVelocity(this,{x:t,y:A,z:e},!0)}setAngularVelocity(t,A,e){var g,i;if(t instanceof f){const I=t;(g=this.context.physics.engine)==null||g.setAngularVelocity(this,I,!0);return}A===void 0||e===void 0||(i=this.context.physics.engine)==null||i.setAngularVelocity(this,{x:t,y:A,z:e},!0)}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)}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=we(this.gameObject);um.tempPosition.copy(t);const A=t.sub(this._lastPosition);this._lastPosition.copy(um.tempPosition),this._smoothedVelocity.lerp(A,this.context.time.deltaTime/.1)}},r(pm,"tempPosition",new f),pm);let _t=um;Ns([RI(),w()],_t.prototype,"mass",2),Ns([RI(),w()],_t.prototype,"useGravity",2),Ns([RI(),w()],_t.prototype,"constraints",2),Ns([RI(),w()],_t.prototype,"isKinematic",2),Ns([RI(),w()],_t.prototype,"drag",2),Ns([RI(),w()],_t.prototype,"angularDrag",2),Ns([RI(),w()],_t.prototype,"detectCollisions",2),Ns([RI(),w()],_t.prototype,"sleepThreshold",2),Ns([RI(),w()],_t.prototype,"collisionDetectionMode",2);class UI{constructor(){r(this,"bb",null),r(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,g,i){return A.prep(4,12),A.writeFloat32(i),A.writeFloat32(g),A.writeFloat32(e),A.offset()}}class rY{constructor(){r(this,"bb",null),r(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}position(A){return(A||new UI).__init(this.bb_pos,this.bb)}rotation(A){return(A||new UI).__init(this.bb_pos+12,this.bb)}scale(A){return(A||new UI).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(A,e,g,i,I,o,C,s,a,n){return A.prep(4,36),A.prep(4,12),A.writeFloat32(n),A.writeFloat32(a),A.writeFloat32(s),A.prep(4,12),A.writeFloat32(C),A.writeFloat32(o),A.writeFloat32(I),A.prep(4,12),A.writeFloat32(i),A.writeFloat32(g),A.writeFloat32(e),A.offset()}}class Ca{constructor(){r(this,"bb",null),r(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}static getRootAsSyncedTransformModel(A,e){return(e||new Ca).__init(A.readInt32(A.position())+A.position(),A)}static getSizePrefixedRootAsSyncedTransformModel(A,e){return A.setPosition(A.position()+Mu),(e||new Ca).__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 rY).__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 on=CA("debugsync"),bc="STRS";Bk(bc,Ca.getRootAsSyncedTransformModel);const SC=new xE;function BY(t,A,e=!0){SC.clear();const g=SC.createString(t);Ca.startSyncedTransformModel(SC),Ca.addGuid(SC,g),Ca.addFast(SC,e);const i=A.worldPosition,I=A.worldEuler,o=A.gameObject.scale;Ca.addTransform(SC,rY.createTransform(SC,i.x,i.y,i.z,I.x,I.y,I.z,o.x,o.y,o.z));const C=Ca.endSyncedTransformModel(SC);return SC.finish(C,bc),SC.asUint8Array()}class Cn extends RA{constructor(){super(...arguments),r(this,"overridePhysics",!0),r(this,"interpolatePosition",!0),r(this,"interpolateRotation",!0),r(this,"fastMode",!1),r(this,"syncDestroy",!1),r(this,"_model",null),r(this,"_needsUpdate",!0),r(this,"rb",null),r(this,"_wasKinematic",!1),r(this,"_receivedDataBefore",!1),r(this,"_targetPosition"),r(this,"_targetRotation"),r(this,"_receivedFastUpdate",!1),r(this,"_shouldRequestOwnership",!1),r(this,"joinedRoomCallback",null),r(this,"receivedDataCallback",null),r(this,"tempEuler",new mg),r(this,"receivedUpdate",!1),r(this,"lastWorldPos"),r(this,"lastWorldRotation")}requestOwnership(){on&&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(){on&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new f,this._targetRotation=new mA,this.lastWorldPos=new f,this.lastWorldRotation=new mA,this.rb=eA.getComponentInChildren(this.gameObject,_t),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new Hu(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(Wt.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(bc,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&hv(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(Wt.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(bc,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){on&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,A),this.receivedUpdate=!0,this._receivedFastUpdate=A.fast();const g=A.transform();if(g){pI.markDirty(this.gameObject,!0);const i=g.position();i&&(this.interpolatePosition&&((e=this._targetPosition)==null||e.set(i.x(),i.y(),i.z())),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(i.x(),i.y(),i.z()));const I=g.rotation();I&&(this.tempEuler.set(I.x(),I.y(),I.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&UJ(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){on&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());let A=this.worldPosition,e=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){const I=A.distanceTo(this.lastWorldPos),o=e.angleTo(this.lastWorldRotation),C=this._model.hasOwnership||this.fastMode?1e-4:.001;(I>C||o>C)&&(this._model.hasOwnership?this._needsUpdate=!0:(on&&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),pI.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 C=this.worldPosition;C.lerp(this._targetPosition,I),this.worldPosition=C,o=!0}if(this.interpolateRotation&&this._targetRotation){const C=this.worldQuaternion;C.slerp(this._targetRotation,I),this.worldQuaternion=C,o=!0}o&&pI.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&&(on&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic),this.gameObject.position.distanceTo(new f(0,0,0))>1e3&&(on&&console.log("RESET",this.name),this.gameObject.position.set(0,1,0),this.rb.setVelocity(0,0,0)));const g=10,i=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%g===0||i)){on&&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=BY(this.guid,this,!!i);this.context.connection.sendBinary(I)}}}var Oo={};Oo.d=(t,A)=>{for(var e in A)Oo.o(A,e)&&!Oo.o(t,e)&&Object.defineProperty(t,e,{enumerable:!0,get:A[e]})},Oo.o=(t,A)=>Object.prototype.hasOwnProperty.call(t,A),Oo.r=t=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var dg={};Oo.d(dg,{w8:()=>Qt,cg:()=>HH,gO:()=>Ud,wb:()=>Dm,zV:()=>Gr,HS:()=>Lc,Ec:()=>kr,gF:()=>jE,ol:()=>Nd,pz:()=>mY,tx:()=>So,hj:()=>wm,FV:()=>jc,sV:()=>uH,xv:()=>Fd,mx:()=>fY,gE:()=>kY,ZP:()=>$eA,Vx:()=>TH});var Dm={};Oo.r(Dm),Oo.d(Dm,{get:()=>QY,set:()=>r7});var wm={};Oo.r(wm),Oo.d(wm,{alphaTestTransformer:()=>tw,asPreprocessorValueTransformer:()=>MY,toPreprocessorTriggerTransformer:()=>Jm,toUserDataTransformer:()=>D$,uniformOrUserDataTransformer:()=>ro});const ym={fontFamily:null,fontSize:.05,fontKerning:"normal",fontStyle:"normal",fontWeight:"400",offset:.005,lineHeight:1.2,lineBreak:`- ,.:?!
|
|
4179
|
+
`}function Px(t){return`(${t.r}, ${t.g}, ${t.b})`}function jx(t){return`(${t.x}, ${t.y})`}const Wx=class{constructor(t,A,e){r(this,"id"),r(this,"trigger"),r(this,"action"),r(this,"exclusive",!1),this.id="Behavior_"+Im(t)+"_"+Wx.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 g="";if(Array.isArray(this.trigger)){g="[";for(let i=0;i<this.trigger.length;i++){const I=this.trigger[i];g+="<"+I.id+">",i+1<this.trigger.length&&(g+=", ")}g+="]"}else g=`<${this.trigger.id}>`;if(e.appendLine(`rel triggers = ${g} `),e.appendLine(),Array.isArray(this.trigger))for(const i of this.trigger)i.writeTo(A,e),e.appendLine();else this.trigger.writeTo(A,e);e.appendLine(),this.action.writeTo(A,e),e.closeBlock()}};let _i=Wx;r(_i,"global_id",0);function om(t,A){var e,g;let i="";if(Array.isArray(t)){let I="[ ";for(let o=0;o<t.length;o++){let C=t[o];if(typeof C=="string")I+=C;else if(typeof C=="object"){C.isObject3D&&(C=A.findById(C.uuid));const s=(e=C.getPath)==null?void 0:e.call(C);I+=s}o+1<t.length&&(I+=", ")}I+=" ]",i=I}else typeof t=="object"&&(t.isObject3D&&(t=A.findById(t.uuid)),i=(g=t.getPath)==null?void 0:g.call(t));return i=i.replace(A.name,A.name+"/Scenes/Scene"),i}const Vx=class{constructor(t,A){r(this,"id"),r(this,"targetId"),r(this,"tokenId"),r(this,"type"),r(this,"distance"),t&&(this.targetId=t),A?this.id=A:this.id="Trigger_"+Vx.global_id++}writeTo(t,A){A.beginBlock(`def Preliminary_Trigger "${this.id}"`),this.targetId&&(typeof this.targetId!="string"&&(this.targetId=om(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 Sr=Vx;r(Sr,"global_id",0);class nI{static sceneStartTrigger(){const A=new Sr;return A.targetId=void 0,A.tokenId="SceneTransition",A.type="enter",A}static tapTrigger(A){const e=new Sr(A);return e.tokenId="TapGesture",e}static isTapTrigger(A){return A?.tokenId==="TapGesture"}static proximityToCameraTrigger(A,e){const g=new Sr(A);return g.tokenId="ProximityToCamera",g.distance=e,g}}class za{constructor(A,e){r(this,"id"),r(this,"actions"),r(this,"loops",0),r(this,"performCount",1),r(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 g of this.actions)g&&e.appendLine("<"+g.id+">,");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 g of this.actions)g&&(g.writeTo(A,e),e.appendLine());e.closeBlock()}}r(za,"global_id",0);var Cm=(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))(Cm||{}),sm=(t=>(t.Relative="relative",t.Absolute="absolute",t))(sm||{});const am=class{constructor(t,A){r(this,"id"),r(this,"tokenId"),r(this,"affectedObjects"),r(this,"easeType"),r(this,"motionType"),r(this,"duration"),r(this,"moveDistance"),r(this,"style"),r(this,"type"),r(this,"front"),r(this,"up"),r(this,"start"),r(this,"animationSpeed"),r(this,"reversed"),r(this,"pingPong"),r(this,"xFormTarget"),r(this,"audio"),r(this,"gain"),r(this,"auralMode"),r(this,"multiplePerformOperation"),t&&(this.affectedObjects=t),A?this.id=A:this.id="Action",this.id+="_"+am.global_id++}clone(){const t=new am,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=om(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=om(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 To=am;r(To,"global_id",0);let KQ=class KE{constructor(A,e,g){r(this,"x",0),r(this,"y",0),r(this,"z",0),this.x=A,this.y=e,this.z=g}static get up(){return new KE(0,1,0)}static get right(){return new KE(1,0,0)}static get forward(){return new KE(0,0,1)}static get back(){return new KE(0,0,-1)}static get zero(){return new KE(0,0,0)}};var zx=(t=>(t.Play="play",t.Pause="pause",t.Stop="stop",t))(zx||{}),nm=(t=>(t.Spatial="spatial",t.NonSpatial="nonSpatial",t.Ambient="ambient",t))(nm||{});class at{static sequence(...A){return new za("group_"+za.getId(),A).makeSequence()}static parallel(...A){return new za("group_"+za.getId(),A).makeParallel()}static fadeAction(A,e,g){const i=new To(A);return i.tokenId="Visibility",i.type=g?"show":"hide",i.duration=e,i.style="basic",i.motionType="none",i.moveDistance=0,i.easeType="none",i}static startAnimationAction(A,e,g=0,i=1,I=!1,o=!1){const C=new To(A);if(C.tokenId="StartAnimation",C.start=e,C.duration=g,C.animationSpeed=i,C.reversed=I,C.pingPong=o,I&&(C.start-=g),o){C.pingPong=!1;const s=C.clone();return s.reversed=!I,s.start=C.start,s.reversed&&(s.start-=g),at.sequence(C,s)}return C}static waitAction(A){const e=new To;return e.tokenId="Wait",e.duration=A,e}static lookAtCameraAction(A,e=9999999999999,g,i){const I=new To(A);return I.tokenId="LookAtCamera",I.duration=e,I.front=g??KQ.forward,I.up=i??KQ.up,I}static emphasize(A,e,g=2,i=1,I="basic"){const o=new To(A);return o.tokenId="Emphasize",o.duration=e,o.style=I??"basic",o.motionType=Cm[g],o.moveDistance=i,o}static transformAction(A,e,g,i,I="inout"){const o=new To(A);return o.tokenId="Transform",o.duration=g,o.type=i,o.easeType=I,Array.isArray(e)&&console.error("Transform target must not be an array",e),o.xFormTarget=e,o}static playAudioAction(A,e,g="play",i=1,I="spatial"){const o=new To(A);return o.tokenId="Audio",o.type=g,o.audio=e,o.gain=i,o.auralMode=I,o.multiplePerformOperation="allow",o}}class s6{constructor(A){r(this,"object"),r(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 rm extends s6{constructor(A,e,g,i){super(A),r(this,"matrix"),r(this,"material"),r(this,"geometry"),r(this,"_enableAction"),r(this,"_disableAction"),this.matrix=e,this.material=g,this.geometry=i}onApply(A){var e,g;const i=this.model;if(!i)return;(e=i.parent)!=null&&e.isDynamic||pC.createEmptyParent(i);const I=i.clone();this.matrix&&(I.matrix=this.matrix),this.material&&(I.material=this.material),this.geometry&&(I.geometry=this.geometry),(g=i.parent)==null||g.add(I)}enable(){return this._enableAction?this._enableAction:(this._enableAction=at.fadeAction(this.object,0,!0),this._enableAction)}disable(){return this._disableAction?this._disableAction:(this._disableAction=at.fadeAction(this.object,0,!1),this._disableAction)}}class Bm{constructor(A){r(this,"actions"),r(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 a6=Object.defineProperty,n6=Object.getOwnPropertyDescriptor,Zx=(t,A,e,g)=>{for(var i=g>1?void 0:g?n6(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&a6(A,e,i),i};class Uc extends RA{constructor(){super(...arguments),r(this,"from"),r(this,"to"),r(this,"width",0),r(this,"centered",!0),r(this,"_centerPos")}awake(){this._centerPos=new f}update(){if(!this.from||!this.to)return;const A=we(this.from).clone(),e=we(this.to).clone(),g=A.distanceTo(e);this._centerPos.copy(A),this._centerPos.add(e),this._centerPos.multiplyScalar(.5),gg(this.gameObject,this.centered?this._centerPos:A),this.gameObject.lookAt(we(this.to).clone()),this.gameObject.scale.set(this.width,this.width,g)}}Zx([w(eA)],Uc.prototype,"from",2),Zx([w(eA)],Uc.prototype,"to",2);var r6=Object.defineProperty,B6=Object.getOwnPropertyDescriptor,Fc=(t,A,e,g)=>{for(var i=g>1?void 0:g?B6(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&r6(A,e,i),i};const Za=CA("debuganimation");class ao extends RA{constructor(){super(...arguments),r(this,"playAutomatically",!0),r(this,"randomStartTime",!0),r(this,"minMaxSpeed"),r(this,"minMaxOffsetNormalized"),r(this,"loop",!0),r(this,"clampWhenFinished",!1),r(this,"_tempAnimationClipBeforeGameObjectExisted",null),r(this,"mixer"),r(this,"_actions",[]),r(this,"_currentActions",[]),r(this,"_handles",[]),r(this,"_didInit",!1)}get clip(){var A;return(A=this.animations)!=null&&A.length?this.animations[0]:null}set clip(A){if(!this.__didAwake){Za&&console.log("Assign clip during serialization",A),this._tempAnimationClipBeforeGameObjectExisted=A;return}A&&(Za&&console.log("Assign clip",A,!!this.gameObject),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){Za&&console.log("assign animations",A),this.gameObject.animations=A}get animations(){return this.gameObject.animations}get currentAction(){return this._currentActions[0]}get currentActions(){return this._currentActions}get actions(){return this._actions}set actions(A){this._actions=A}awake(){Za&&console.log(this),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(g=>g.getClip().name===A)}get isPlaying(){for(let A=0;A<this._currentActions.length;A++)if(this._currentActions[A].isRunning())return!0;return!1}play(A=0,e){if(Za&&console.log("PLAY",A),this.init(),!this.mixer){Za&&console.warn("Missing mixer",this);return}A===void 0&&(A=0);let g=A;if(typeof A=="number"){if(A>=this.animations.length){Za&&console.log("No animation at index",A);return}g=this.animations[A]}else typeof A=="string"&&(g=this.animations.find(I=>I.name===A));if(!g){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()===g)return this.internalOnPlay(I,e);if(!(g instanceof $I)){console.warn("Clip is no AnimationClip",g,"on object: "+this.name);return}const i=this.mixer.clipAction(g);return this.actions.push(i),this.internalOnPlay(i,e)}internalOnPlay(A,e){var g=this.currentAction;if(g===A&&g.isRunning()&&g.time<g.getClip().duration){const C=this.tryFindHandle(A);if(C)return C.getPromise()}const i=e?.exclusive??!0;e!=null&&e.fadeDuration?(i&&g?.fadeOut(e.fadeDuration),A.fadeIn(e.fadeDuration)):i&&g?.stop(),A.reset(),A.enabled=!0,A.time=0,A.timeScale=1;const I=A.getClip();e!=null&&e.minMaxOffsetNormalized&&(A.time=$A.lerp(e.minMaxOffsetNormalized.x,e.minMaxOffsetNormalized.y,Math.random())*I.duration),e!=null&&e.minMaxSpeed&&(A.timeScale=$A.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?c0:Ch:A.loop=Ch,A.play(),Za&&console.log("PLAY",A.getClip().name,A);const o=new Q6(A,this.mixer,e,C=>{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 iu(this.gameObject)))}}Fc([w()],ao.prototype,"playAutomatically",2),Fc([w()],ao.prototype,"randomStartTime",2),Fc([w()],ao.prototype,"loop",2),Fc([w()],ao.prototype,"clampWhenFinished",2),Fc([w($I)],ao.prototype,"clips",1);class Q6{constructor(A,e,g,i){r(this,"mixer"),r(this,"action"),r(this,"promise",null),r(this,"resolve",null),r(this,"reject",null),r(this,"_options"),r(this,"_resolveCallback",null),r(this,"_rejectCallback",null),r(this,"_loopCallback"),r(this,"_finishedCallback"),r(this,"_resolvedOrRejectedCallback"),this.action=A,this.mixer=e,this._resolvedOrRejectedCallback=i,this._options=g}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,g;this.dispose(),(e=this._resolvedOrRejectedCallback)==null||e.call(this,this),(g=this._rejectCallback)==null||g.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 E6=Object.defineProperty,h6=Object.getOwnPropertyDescriptor,Xa=(t,A,e,g)=>{for(var i=g>1?void 0:g?h6(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&E6(A,e,i),i};class $a{constructor(){r(this,"time"),r(this,"value"),r(this,"inTangent"),r(this,"inWeight"),r(this,"outTangent"),r(this,"outWeight"),r(this,"weightedMode")}}Xa([w()],$a.prototype,"time",2),Xa([w()],$a.prototype,"value",2),Xa([w()],$a.prototype,"inTangent",2),Xa([w()],$a.prototype,"inWeight",2),Xa([w()],$a.prototype,"outTangent",2),Xa([w()],$a.prototype,"outWeight",2),Xa([w()],$a.prototype,"weightedMode",2);const Xx=class{constructor(){r(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 g=this.keys[A+1];if(g.time<t)continue;return!isFinite(e.outTangent)||!isFinite(g.inTangent)?e.value:Xx.interpolateValue(t,e,g)}else return e.value}return this.keys[this.keys.length-1].value}static interpolateValue(t,A,e){const g=A.time,i=A.value,I=A.outTangent,o=e.time,C=e.value,s=e.inTangent,a=o-g,n=a*a,B=n*a,Q=((I+s)*a-2*(C-i))/B,E=(3*(C-i)-(s+2*I)*a)/n,h=I,c=i,l=t-g,d=l*l,u=d*l;return Q*u+E*d+h*l+c}};let fr=Xx;Xa([w($a)],fr.prototype,"keys",2);const JQ=CA("debugusdzanimation");class LD{constructor(A,e,g){r(this,"ext"),r(this,"root"),r(this,"clip"),this.ext=A,this.root=e,this.clip=g}get start(){return this.ext.getStartTime01(this.root,this.clip)}get duration(){return this.clip.duration}}class xD{constructor(A,e,g,i){r(this,"clip"),r(this,"pos"),r(this,"rot"),r(this,"scale"),r(this,"ext"),r(this,"root"),r(this,"target"),this.ext=A,this.root=e,this.target=g,this.clip=i}get frameRate(){return 60}addTrack(A){A.name.endsWith("position")&&(this.pos=A),A.name.endsWith("quaternion")&&(this.rot=A),A.name.endsWith("scale")&&(this.scale=A)}getFrames(){var A,e,g,i,I,o;return Math.max(((e=(A=this.pos)==null?void 0:A.times)==null?void 0:e.length)??0,((i=(g=this.rot)==null?void 0:g.times)==null?void 0:i.length)??0,((o=(I=this.scale)==null?void 0:I.times)==null?void 0:o.length)??0)}getDuration(){var A,e,g;const i=((A=this.pos)==null?void 0:A.times)??((e=this.rot)==null?void 0:e.times)??((g=this.scale)==null?void 0:g.times);return i?i[i.length-1]:0}getStartTime(A){let e=0;for(let g=0;g<A.length;g++){const i=A[g];if(i===this)return e;e+=i.getDuration()}return e}}class YD{constructor(){r(this,"dict",new Map),r(this,"rootTargetMap",new Map),r(this,"serializers",[])}get extensionName(){return"animation"}getStartTime01(A,e){const g=this.rootTargetMap.get(A);if(!g)return 1/0;let i=-1;for(const I of g){const o=this.dict.get(I);let C=0;if(o!=null&&o.length){for(const s of o){if(s.clip===e)break;C+=s.getDuration()}i=Math.max(i,C)}else console.warn("No animation found on root",A,e,o)}return i}registerAnimation(A,e){if(!e||!A)return null;this.rootTargetMap.has(A)||this.rootTargetMap.set(A,[]);for(const g of e.tracks){const i=g.name.split(".")[2],I=A.getObjectByName(i);if(!I){console.warn("no object found for track",g.name,"using "+A.name+" instead");continue}this.dict.has(I)||this.dict.set(I,[]);const o=this.dict.get(I);if(!o)continue;let C=o.find(a=>a.clip===e);C||(C=new xD(this,A,I,e),o.push(C)),C.addTrack(g);const s=this.rootTargetMap.get(A);s!=null&&s.includes(I)||s==null||s.push(I)}return new LD(this,A,e)}onAfterHierarchy(A){JQ&&console.log(this.dict)}onAfterBuildDocument(A){var e,g;for(const i of this.serializers){const I=(e=i.model)==null?void 0:e.parent,o=I?.isDynamic===!0;JQ&&console.log(o,(g=i.model)==null?void 0:g.parent),o&&i.registerCallback(I)}}onExportObject(A,e,g){eA.foreachComponent(A,I=>{const o=I;typeof o.createAnimation=="function"&&o.createAnimation(this,e,g)},!1);const i=new c6(A,this.dict);this.serializers.push(i),i.registerCallback(e)}}class c6{constructor(A,e){r(this,"object"),r(this,"dict"),r(this,"model"),r(this,"callback"),this.object=A,this.dict=e}registerCallback(A){this.model&&this.callback&&this.model.removeEventListener("serialize",this.callback),this.callback||(this.callback=this.onSerialize.bind(this)),JQ&&console.log("REPARENT",A),this.model=A,this.model.addEventListener("serialize",this.callback)}onSerialize(A,e){var g,i,I,o,C,s;if(!this.model)return;JQ&&console.log("SERIALIZE",this.model.name,this.object.type);const a=this.object,n=this.dict.get(a);if(!n)return;const B=new KA,Q=new f,E=new mA,h=new f(1,1,1);A.appendLine("matrix4d xformOp:transform.timeSamples = {"),A.indent++;for(const c of n){let l=(g=c.pos)==null?void 0:g.times,d=(i=c.rot)==null?void 0:i.times,u=(I=c.scale)==null?void 0:I.times,p=[];if(l)for(const S of l)p.push(S);if(d)for(const S of d)p.push(S);if(u)for(const S of u)p.push(S);if(p.sort((S,U)=>S-U),p=[...new Set(p)],!p||p.length===0){console.error("got an animated object but no time values??",a,c);continue}const D=c.getStartTime(n);JQ&&A.appendLine(c.clip.name+": start="+D.toFixed(3)+", length="+c.getDuration().toFixed(3)+", frames="+c.getFrames());const y=(o=c.pos)==null?void 0:o.createInterpolant(),k=(C=c.rot)==null?void 0:C.createInterpolant(),F=(s=c.scale)==null?void 0:s.createInterpolant();y||Q.set(a.position.x,a.position.y,a.position.z),k||E.set(a.quaternion.x,a.quaternion.y,a.quaternion.z,a.quaternion.w),F||h.set(a.scale.x,a.scale.y,a.scale.z);for(let S=0;S<p.length;S++){const U=p[S];if(y){const Y=y.evaluate(U);Q.set(Y[0],Y[1],Y[2])}if(k){const Y=k.evaluate(U);E.set(Y[0],Y[1],Y[2],Y[3])}if(F){const Y=F.evaluate(U);h.set(Y[0],Y[1],Y[2])}B.compose(Q,E,h);let M=`${(D+U)*c.frameRate}: ${Tx(B)},`;JQ&&(M="#"+S+" "+M),A.appendLine(M)}}A.indent--,A.appendLine("}")}}class l6{constructor(){r(this,"_context")}get context(){return this._context??be.Current}get isStateMachineBehaviour(){return!0}}class HD{constructor(A,e,g,i){r(this,"_name"),r(this,"_nameHash"),r(this,"_normalizedTime"),r(this,"_length"),r(this,"_speed"),this._name=A.name,this._nameHash=A.hash,this._normalizedTime=e,this._length=g,this._speed=i}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 $x(t,A){return{name:"",isLooping:!1,guid:A?.generateUUID()??Ji.generateUUID(),index:-1,clip:new $I(t,1,[])}}var An=(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))(An||{}),Qm=(t=>(t[t.Float=1]="Float",t[t.Int=3]="Int",t[t.Bool=4]="Bool",t[t.Trigger=9]="Trigger",t))(Qm||{});const uC=CA("debuganimatorcontroller"),TD=CA("debugrootmotion");class sB{constructor(A){r(this,"normalizedStartOffset",0),r(this,"_speed",1),r(this,"animator"),r(this,"model"),r(this,"_mixer"),r(this,"_activeState"),r(this,"_activeStates",[]),r(this,"rootMotionHandler"),this.model=A,uC&&console.log(this)}play(A,e=-1,g=Number.NEGATIVE_INFINITY,i=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){uC&&console.log("transition to ",o),this.transitionTo(o,i,g);return}console.warn("Could not find "+A+" to play")}reset(){this.setStartTransition()}setBool(A,e){var g,i;const I=typeof A=="string"?"name":"hash";return(i=(g=this.model)==null?void 0:g.parameters)==null?void 0:i.filter(o=>o[I]===A).forEach(o=>o.value=e)}getBool(A){var e,g,i;const I=typeof A=="string"?"name":"hash";return((i=(g=(e=this.model)==null?void 0:e.parameters)==null?void 0:g.find(o=>o[I]===A))==null?void 0:i.value)??!1}setFloat(A,e){var g,i;const I=typeof A=="string"?"name":"hash";return(i=(g=this.model)==null?void 0:g.parameters)==null?void 0:i.filter(o=>o[I]===A).forEach(o=>o.value=e)}getFloat(A){var e,g,i;const I=typeof A=="string"?"name":"hash";return((i=(g=(e=this.model)==null?void 0:e.parameters)==null?void 0:g.find(o=>o[I]===A))==null?void 0:i.value)??0}setInteger(A,e){var g,i;const I=typeof A=="string"?"name":"hash";return(i=(g=this.model)==null?void 0:g.parameters)==null?void 0:i.filter(o=>o[I]===A).forEach(o=>o.value=e)}getInteger(A){var e,g,i;const I=typeof A=="string"?"name":"hash";return((i=(g=(e=this.model)==null?void 0:e.parameters)==null?void 0:g.find(o=>o[I]===A))==null?void 0:i.value)??0}setTrigger(A){var e,g;uC&&console.log("SET TRIGGER",A);const i=typeof A=="string"?"name":"hash";return(g=(e=this.model)==null?void 0:e.parameters)==null?void 0:g.filter(I=>I[i]===A).forEach(I=>I.value=!0)}resetTrigger(A){var e,g;const i=typeof A=="string"?"name":"hash";return(g=(e=this.model)==null?void 0:e.parameters)==null?void 0:g.filter(I=>I[i]===A).forEach(I=>I.value=!1)}isInTransition(){return this._activeStates.length>1}setSpeed(A){this._speed=A}FindState(A){return this.findState(A)}findState(A){if(!A)return null;if(Array.isArray(this.model.layers)){for(const e of this.model.layers)for(const g of e.stateMachine.states)if(g.name===A)return g}return null}get context(){var A;return(A=this.animator)==null?void 0:A.context}bind(A){this.animator=A,this._mixer=new iu(this.animator.gameObject),this.createActions(this.animator)}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=qd(this.model,(e,g,i)=>i==null?!0:!(i.type==="Object3D"||i.isObject3D===!0||NJ(i)||i.tracks!==void 0));return console.assert(A!==this.model),new sB(A)}update(){var A,e;if(!this.animator||(this.evaluateTransitions(),this.updateActiveStates(),!this._activeState))return;const g=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&((A=this.rootMotionHandler)==null||A.onBeforeUpdate()),this._mixer.update(g),this.animator.applyRootMotion&&((e=this.rootMotionHandler)==null||e.onAfterUpdate())}updateActiveStates(){for(let A=0;A<this._activeStates.length;A++){const e=this._activeStates[A],g=e.motion;if(!g.action)this._activeStates.splice(A,1),A--;else{const i=g.action;i.getEffectiveWeight()<=0&&!i.isRunning()&&(uC&&console.debug("REMOVE",e.name,i.getEffectiveWeight(),i.isRunning(),i.isScheduled()),this._activeStates.splice(A,1),A--)}}}setStartTransition(){for(const A of this.model.layers){const e=A.stateMachine;e.defaultState===void 0&&(uC&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",A),e.defaultState=0);const g=e.states[e.defaultState];this.transitionTo(g,0,this.normalizedStartOffset)}}evaluateTransitions(){var A;let e=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;e=!0}const g=this._activeState,i=g.motion.action;for(const o of g.transitions){if(!o.hasExitTime&&o.conditions.length<=0)continue;let C=!0;for(const s of o.conditions)if(!this.evaluateCondition(s)){C=!1;break}if(C){for(const s of o.conditions){const a=this.model.parameters.find(n=>n.name===s.parameter);a?.type===Qm.Trigger&&(a.value=!1)}if(i){const s=g.motion.clip.duration,a=s<=0?1:Math.abs(i.time/s);let n=!1;if(o.hasExitTime?i.timeScale>0?n=a>=o.exitTime:i.timeScale<0&&(n=1-a>=o.exitTime):n=!0,n){i.clampWhenFinished=!0,uC&&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}}}let I=!1;if(g.motion.isLooping&&i&&(i.time>=i.getClip().duration?(I=!0,i.reset(),i.time=0,i.play()):i.time<=0&&i.timeScale<0&&(I=!0,i.reset(),i.time=i.getClip().duration,i.play())),!I&&g&&!e&&i&&this.animator&&g.behaviours){const o=i?.getClip().duration,C=i.time/o,s=new HD(this._activeState,C,o,this._speed);for(const a of g.behaviours)a.instance&&((A=a.instance.onStateUpdate)==null||A.call(a.instance,this.animator,s,0))}}getState(A,e){return typeof A=="number"&&(A==-1&&(A=this.model.layers[e].stateMachine.defaultState,A===void 0&&(uC&&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,g){var i,I,o,C,s,a,n,B;if(!this.animator)return;const Q=0;if(A=this.getState(A,Q),!(A!=null&&A.motion)||!A.motion.clip)return;const E=this._activeState===A;if(E){const d=A.motion;!d.action_loopback&&d.clip&&(this._mixer.uncacheAction(d.clip,this.animator.gameObject),d.action_loopback=this.createAction(d.clip))}if((i=this._activeState)!=null&&i.behaviours&&this._activeState.motion.action){const d=(I=this._activeState)==null?void 0:I.motion.clip.duration,u=this._activeState.motion.action.time/d,p=new HD(this._activeState,u,d,this._speed);for(const D of this._activeState.behaviours)(C=(o=D.instance)==null?void 0:o.onStateExit)==null||C.call(D.instance,this.animator,p,Q)}const h=(s=this._activeState)==null?void 0:s.motion.action;h&&h.fadeOut(e),E&&(A.motion.action=A.motion.action_loopback,A.motion.action_loopback=h);const c=this._activeState;this._activeState=A;const l=(a=A.motion)==null?void 0:a.action;if(l){g=Math.max(0,Math.min(1,g)),l.isRunning()&&l.stop(),l.reset(),l.timeScale=this._speed,A.speed!==void 0&&(l.timeScale*=A.speed),l.enabled=!0;const d=A.motion.clip.duration;if(l.time=g*d,l.timeScale<0&&(l.time=d-l.time),l.clampWhenFinished=!0,l.setLoop(Ch,0),e>0?l.fadeIn(e):l.setEffectiveWeight(1),l.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(l),this._activeStates.includes(A)||this._activeStates.push(A),this._activeState.behaviours){const u=new HD(A,g,d,this._speed);for(const p of this._activeState.behaviours)(B=(n=p.instance)==null?void 0:n.onStateEnter)==null||B.call(p.instance,this.animator,u,Q)}}else uC&&(A.__warned_no_motion||(A.__warned_no_motion=!0,console.warn("No action",A.motion,this)));uC&&console.log("TRANSITION FROM "+c?.name+" TO "+A.name,e,h,l,l?.getEffectiveTimeScale(),l?.getEffectiveWeight(),l?.isRunning(),l?.isScheduled(),l?.paused)}createAction(A){var e,g;if(this._mixer.existingAction(A)&&this._mixer.uncacheAction(A,(e=this.animator)==null?void 0:e.gameObject),(g=this.animator)!=null&&g.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new d6(this));const i=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,i,A)}else return this._mixer.clipAction(A)}evaluateCondition(A){const e=this.model.parameters.find(g=>g.name===A.parameter);if(!e)return!1;switch(A.mode){case An.If:return e.value===!0;case An.IfNot:return e.value===!1;case An.Greater:return e.value>A.threshold;case An.Less:return e.value<A.threshold;case An.Equals:return e.value===A.threshold;case An.NotEqual:return e.value!==A.threshold}return!1}createActions(A){var e,g;for(const i of this.model.layers){const I=i.stateMachine;for(let o=0;o<I.states.length;o++){const C=I.states[o];C.transitions||(C.transitions=[]);for(const s of C.transitions)s.conditions||(s.conditions=[]);if(C.motion||(C.motion=$x(C.name)),this.animator&&C.motion.clips){const s=(e=C.motion.clips)==null?void 0:e.find(a=>{var n,B;return a.node.name===((B=(n=this.animator)==null?void 0:n.gameObject)==null?void 0:B.name)});C.motion.clip=s?.clip}if(!C.motion.clip){const s=new $I(void 0,void 0,[]);C.motion.clip=s}if((g=C.motion)!=null&&g.clip){const s=C.motion.clip,a=this.createAction(s);C.motion.action=a}if(C.behaviours&&Array.isArray(C.behaviours))for(const s of C.behaviours){if(!(s!=null&&s.typeName))continue;const a=T.get(s.typeName),n=new a;n.isStateMachineBehaviour&&(n._context=this.context??void 0,rr(n,s.properties),s.instance=n),uC&&console.log("Created animator controller behaviour",C.name,s.typeName,s.properties,n)}}}}*enumerateActions(){for(const A of this.model.layers){const e=A.stateMachine;for(let g=0;g<e.states.length;g++){const i=e.states[g];i!=null&&i.motion&&(i.motion.action&&(yield i.motion.action),i.motion.action_loopback&&(yield i.motion.action_loopback))}}}}class AY{constructor(A,e){r(this,"track"),r(this,"createdInterpolant"),r(this,"originalEvaluate"),r(this,"customEvaluate"),this.track=A;const g=A,i=g.createInterpolant.bind(A);g.createInterpolant=()=>(g.createInterpolant=i,this.createdInterpolant=i(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=I=>{if(!this.originalEvaluate)return;const o=this.originalEvaluate(I);return e(I,o)},this.createdInterpolant.evaluate=this.customEvaluate,this.createdInterpolant)}evaluate(A){this.customEvaluate&&this.customEvaluate(A)}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 bg=class{constructor(t,A,e,g,i){if(r(this,"_action"),r(this,"root"),r(this,"clip"),r(this,"positionWrapper",null),r(this,"rotationWrapper",null),r(this,"context"),r(this,"positionChange",new f),r(this,"rotationChange",new mA),this.context=t,this.root=A,this.clip=e,bg.firstKeyframeRotation[e.uuid]||(bg.firstKeyframeRotation[e.uuid]=new mA),i){const I=i.values;bg.firstKeyframeRotation[e.uuid].set(I[0],I[1],I[2],I[3])}bg.spaceRotation[e.uuid]||(bg.spaceRotation[e.uuid]=new mA),bg.effectiveSpaceRotation[e.uuid]||(bg.effectiveSpaceRotation[e.uuid]=new mA),bg.clipOffsetRotation[e.uuid]=new mA,i&&bg.clipOffsetRotation[e.uuid].set(i.values[0],i.values[1],i.values[2],i.values[3]).invert(),this.handlePosition(e,g),this.handleRotation(e,i)}set action(t){this._action=t}get action(){return this._action}onStart(t){if(t.getClip()!==this.clip)return;const A=bg.lastObjRotation[this.root.uuid];if(bg.spaceRotation[this.clip.uuid].copy(A),TD){const e=new mg().setFromQuaternion(A);console.log("START",this.clip.name,$A.toDegrees(e.y))}}getClipRotationOffset(){return bg.clipOffsetRotation[this.clip.uuid]}handlePosition(t,A){if(A){const e=this.root;TD&&e.add(new zB),bg.lastObjPosition[e.uuid]||(bg.lastObjPosition[e.uuid]=new f);const g=new f,i=new f;let I=0;this.positionWrapper=new AY(A,(o,C)=>{const s=this.action.getEffectiveWeight();if(TD&&e.position.length()>8&&e.position.set(0,e.position.y,0),o>I){g.set(C[0],C[1],C[2]),g.sub(i),g.multiplyScalar(s),g.applyQuaternion(this.getClipRotationOffset());const a=this.clip.uuid;g.applyQuaternion(bg.spaceRotation[a]),this.positionChange.copy(g)}return i.fromArray(C),I=o,C[0]=0,C[1]=0,C[2]=0,C})}}handleRotation(t,A){if(A){if(TD){const o=A.values,C=new mg().setFromQuaternion(new mA(o[0],o[1],o[2],o[3]));console.log(t.name,A.name,"FIRST ROTATION IN TRACK",$A.toDegrees(C.y));const s=A.values.length-4,a=new mA().set(o[s],o[s+1],o[s+2],o[s+3]),n=new mg().setFromQuaternion(a);console.log(t.name,A.name,"LAST ROTATION IN TRACK",$A.toDegrees(n.y))}const e=this.root;bg.lastObjRotation[e.uuid]||(bg.lastObjRotation[e.uuid]=new mA);let g=0;const i=new mA,I=new mA;this.rotationWrapper=new AY(A,(o,C)=>(o>g&&(I.set(C[0],C[1],C[2],C[3]),i.invert(),I.multiply(i),this.rotationChange.copy(I)),i.fromArray(C),g=o,C[0]=0,C[1]=0,C[2]=0,C[3]=1,C))}}onBeforeUpdate(){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(){if(!this.action)return;const t=this.action.getEffectiveWeight();this.positionChange.multiplyScalar(t),this.rotationChange.slerp(bg.identityQuaternion,1-t)}};let Us=bg;r(Us,"lastObjPosition",{}),r(Us,"lastObjRotation",{}),r(Us,"firstKeyframeRotation",{}),r(Us,"spaceRotation",{}),r(Us,"effectiveSpaceRotation",{}),r(Us,"clipOffsetRotation",{}),r(Us,"identityQuaternion",new mA);class d6{constructor(A){r(this,"controller"),r(this,"handler",[]),r(this,"root"),r(this,"summedPosition",new f),r(this,"summedRotation",new mA),this.controller=A}createClip(A,e,g){this.root=e,e&&"name"in e&&e.name;const i=this.findRootTrack(g,".position"),I=this.findRootTrack(g,".quaternion"),o=new Us(this.controller.context,e,g,i,I);this.handler.push(o);const C=A.clipAction(g);return o.action=C,C}onStart(A){for(const e of this.handler)e.onStart(A)}onBeforeUpdate(){for(const A of this.handler)A.onBeforeUpdate()}onAfterUpdate(){this.summedPosition.set(0,0,0),this.summedRotation.set(0,0,0,1);for(const A of this.handler)A.onAfterUpdate(),this.summedPosition.add(A.positionChange),this.summedRotation.multiply(A.rotationChange);this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation),Us.lastObjRotation[this.root.uuid].copy(this.root.quaternion)}findRootTrack(A,e){const g=A.tracks;if(!g)return null;for(const i of g)if(i.name.endsWith(e))return i;return null}}var p6=Object.defineProperty,u6=Object.getOwnPropertyDescriptor,OD=(t,A,e,g)=>{for(var i=g>1?void 0:g?u6(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&p6(A,e,i),i};const Em=CA("debuganimator");class Pi extends RA{constructor(){super(...arguments),r(this,"applyRootMotion",!1),r(this,"hasRootMotion",!1),r(this,"keepAnimatorControllerStateOnDisable",!1),r(this,"speed",1),r(this,"normalizedStartOffset",0),r(this,"_animatorController",null)}set runtimeAnimatorController(A){this._animatorController&&this._animatorController.model===A||(A?A instanceof sB?this._animatorController=A:(Em&&console.log("Assign animator controller",A,this),this._animatorController=new sB(A)):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}Play(A,e=-1,g=Number.NEGATIVE_INFINITY,i=0){this.play(A,e,g,i)}play(A,e=-1,g=Number.NEGATIVE_INFINITY,i=0){var I;(I=this.runtimeAnimatorController)==null||I.play(A,e,g,i)}Reset(){this.reset()}reset(){var A;(A=this._animatorController)==null||A.reset()}SetBool(A,e){this.setBool(A,e)}setBool(A,e){var g;(g=this.runtimeAnimatorController)==null||g.setBool(A,e)}GetBool(A){return this.getBool(A)}getBool(A){var e;return((e=this.runtimeAnimatorController)==null?void 0:e.getBool(A))??!1}SetFloat(A,e){this.setFloat(A,e)}setFloat(A,e){var g;(g=this.runtimeAnimatorController)==null||g.setFloat(A,e)}GetFloat(A){return this.getFloat(A)}getFloat(A){var e;return((e=this.runtimeAnimatorController)==null?void 0:e.getFloat(A))??-1}SetInteger(A,e){this.setInteger(A,e)}setInteger(A,e){var g;(g=this.runtimeAnimatorController)==null||g.setInteger(A,e)}GetInteger(A){return this.getInteger(A)}getInteger(A){var e;return((e=this.runtimeAnimatorController)==null?void 0:e.getInteger(A))??-1}SetTrigger(A){this.setTrigger(A)}setTrigger(A){var e;Em&&console.log("SetTrigger",A),(e=this.runtimeAnimatorController)==null||e.setTrigger(A)}ResetTrigger(A){this.resetTrigger(A)}resetTrigger(A){var e;(e=this.runtimeAnimatorController)==null||e.resetTrigger(A)}IsInTransition(){return this.isInTransition()}isInTransition(){var A;return((A=this.runtimeAnimatorController)==null?void 0:A.isInTransition())??!1}SetSpeed(A){return this.setSpeed(A)}setSpeed(A){var e;A!==this.speed&&(this.speed=A,(e=this._animatorController)==null||e.setSpeed(A))}set minMaxSpeed(A){this.speed=$A.lerp(A.x,A.y,Math.random())}set minMaxOffsetNormalized(A){this.normalizedStartOffset=$A.lerp(A.x,A.y,Math.random()),this.runtimeAnimatorController&&(this.runtimeAnimatorController.normalizedStartOffset=this.normalizedStartOffset)}awake(){if(Em&&console.log("ANIMATOR",this.name,this),!!this.gameObject&&this.runtimeAnimatorController){const A=this.runtimeAnimatorController.clone();A?(console.assert(this.runtimeAnimatorController!==A),this.runtimeAnimatorController=A,console.assert(this.runtimeAnimatorController===A),this.runtimeAnimatorController.bind(this),this.runtimeAnimatorController.setSpeed(this.speed),this.runtimeAnimatorController.normalizedStartOffset=this.normalizedStartOffset):console.warn("Could not clone animator controller",this.runtimeAnimatorController)}}onDisable(){var A;this.keepAnimatorControllerStateOnDisable||(A=this._animatorController)==null||A.reset()}onBeforeRender(){this._animatorController&&this._animatorController.update()}}OD([w()],Pi.prototype,"applyRootMotion",2),OD([w()],Pi.prototype,"hasRootMotion",2),OD([w()],Pi.prototype,"keepAnimatorControllerStateOnDisable",2),OD([w()],Pi.prototype,"runtimeAnimatorController",1);class D6 extends eg{constructor(A,e=1,g=16,i=2){const I=new le,o=g+i*2,C=new Float32Array((o*3+3)*3);I.setAttribute("position",new ge(C,3));const s=new Ag({color:65280}),a=new Ag({color:16776960});super(I,[a,s]),this.audio=A,this.range=e,this.divisionsInnerAngle=g,this.divisionsOuterAngle=i,this.type="PositionalAudioHelper",this.update()}update(){const A=this.audio,e=this.range,g=this.divisionsInnerAngle,i=this.divisionsOuterAngle,I=Ji.degToRad(A.panner.coneInnerAngle),o=Ji.degToRad(A.panner.coneOuterAngle),C=I/2,s=o/2;let a=0,n=0,B,Q;const E=this.geometry,h=E.attributes.position;E.clearGroups();function c(l,d,u,p){const D=(d-l)/u;for(h.setXYZ(a,0,0,0),n++,B=l;B<d;B+=D)Q=a+n,h.setXYZ(Q,Math.sin(B)*e,0,Math.cos(B)*e),h.setXYZ(Q+1,Math.sin(Math.min(B+D,d))*e,0,Math.cos(Math.min(B+D,d))*e),h.setXYZ(Q+2,0,0,0),n+=3;E.addGroup(a,n,p),a+=n,n=0}c(-s,-C,i,0),c(-C,C,g,1),c(C,s,i,0),h.needsUpdate=!0,I===o&&(this.material[0].visible=!1)}dispose(){this.geometry.dispose(),this.material[0].dispose(),this.material[1].dispose()}}var w6=Object.defineProperty,y6=Object.getOwnPropertyDescriptor,en=(t,A,e,g)=>{for(var i=g>1?void 0:g?y6(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&w6(A,e,i),i};const Si=CA("debugaudio");var Nc;const Pg=(Nc=class extends RA{constructor(){super(...arguments),r(this,"clip",""),r(this,"playOnAwake",!1),r(this,"_spatialBlend",0),r(this,"_minDistance",1),r(this,"_maxDistance",100),r(this,"_volume",1),r(this,"rollOffMode",0),r(this,"playInBackground",!0),r(this,"_loop",!1),r(this,"sound",null),r(this,"helper",null),r(this,"wasPlaying",!1),r(this,"audioLoader",null),r(this,"shouldPlay",!1),r(this,"_lastClipStartedLoading",null),r(this,"onVisibilityChanged",()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||Jn())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":Si&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,Pg._userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&Pg._userInteractionRegistered&&this.wasPlaying&&this.play();break}}),r(this,"onApplicationMuteChanged",()=>{var t,A;this.context.application.muted?(t=this.sound)==null||t.setVolume(0):(A=this.sound)==null||A.setVolume(this.volume)}),r(this,"lerp",(t,A,e)=>t*(1-e)+A*e),r(this,"_lastContextTime",0),r(this,"_hasEnded",!0),r(this,"_needUpdateSpatialDistanceSettings",!1)}static get userInteractionRegistered(){return Pg._didCallBeginWaitForUserInteraction||(Pg._didCallBeginWaitForUserInteraction=!0,Pg._beginWaitForUserInteraction()),Pg._userInteractionRegistered}static registerWaitForAllowAudio(t){if(t!==null){if(this._userInteractionRegistered){t();return}this.callbacks.indexOf(t)===-1&&this.callbacks.push(t),Pg._didCallBeginWaitForUserInteraction||(Pg._didCallBeginWaitForUserInteraction=!0,Pg._beginWaitForUserInteraction())}}static _beginWaitForUserInteraction(t=null){if(this._userInteractionRegistered){t&&t();return}t!==null&&this.registerWaitForAllowAudio(t);const A=(()=>{if(A!=null&&!Pg._userInteractionRegistered){Pg._userInteractionRegistered=!0,Si&&console.log("\u{1F50A} registered interaction, can play audio now"),document.removeEventListener("pointerdown",A),document.removeEventListener("click",A),document.removeEventListener("dragstart",A),document.removeEventListener("touchstart",A);for(const e of this.callbacks)e();this.callbacks.length=0}}).bind(this);document.addEventListener("pointerdown",A),document.addEventListener("click",A),document.addEventListener("dragstart",A),document.addEventListener("touchstart",A)}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&&(Si&&console.log(this.name,"audio set volume",t),this.sound.setVolume(t))}get Sound(){if(!this.sound&&Pg._userInteractionRegistered){const t=eA.getComponent(this.context.mainCamera,XQ)??eA.findObjectOfType(XQ,this.context);t!=null&&t.listener&&(this.sound=new zK(t.listener),this.gameObject.add(this.sound))}return this.sound}get ShouldPlay(){return this.shouldPlay}awake(){this.audioLoader=new eu,this.playOnAwake&&(this.shouldPlay=!0)}onEnable(){Pg._userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():Pg._beginWaitForUserInteraction(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.loadAndPlay(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(ED.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(ED.MuteChanged,this.onApplicationMuteChanged),this.stop()}onLoaded(t){Si&&console.log("audio buffer loaded"),Pg.registerWaitForAllowAudio(()=>{Si&&console.log("finished loading",t);const A=this.Sound;if(!A){console.warn("Failed getting sound",this.name);return}A.isPlaying&&A.stop(),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(),Si&&console.log(this.name,this.shouldPlay,Pg.userInteractionRegistered,this),this.shouldPlay&&Pg._userInteractionRegistered&&this.play()})}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(Si&&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?Si&&!this.helper&&(this.helper=new D6(t,t.getRefDistance()),t.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}loadAndPlay(t){if(t&&(this.clip=t),this.clip&&(Si&&console.log(this.clip),this.clip.endsWith(".mp3")||this.clip.endsWith(".wav"))){if(this.audioLoader||(this.audioLoader=new eu),this.shouldPlay=!0,this._lastClipStartedLoading===this.clip){Si&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=this.clip,Si&&console.log("load audio",this.clip),this.audioLoader.load(this.clip,this.onLoaded.bind(this),()=>{},console.error)}}play(t=void 0){var A;if(!this.audioLoader||!this.sound||t&&t!==this.clip){this.loadAndPlay(t);return}if(this.shouldPlay=!0,this._hasEnded=!1,Si&&console.log("play",(A=this.sound)==null?void 0:A.getVolume(),this.sound),this.sound&&!this.sound.isPlaying){const e=this.context.application.muted;e&&this.sound.setVolume(0),this.sound.play(e?.1:0)}}pause(){var t;Si&&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())}stop(){var t;Si&&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,Si&&console.log(this._lastContextTime),this.sound.stop())}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,Si&&console.log("Audio clip ended",this.clip),this.sound.dispatchEvent({type:"ended",target:this}))}},r(Nc,"_didCallBeginWaitForUserInteraction",!1),r(Nc,"callbacks",[]),r(Nc,"_userInteractionRegistered",!1),Nc);let cg=Pg;en([w(URL)],cg.prototype,"clip",2),en([w()],cg.prototype,"playOnAwake",2),en([w()],cg.prototype,"loop",1),en([w()],cg.prototype,"spatialBlend",1),en([w()],cg.prototype,"minDistance",1),en([w()],cg.prototype,"maxDistance",1),en([w()],cg.prototype,"volume",1),en([w()],cg.prototype,"rollOffMode",2);var S6=Object.defineProperty,f6=Object.getOwnPropertyDescriptor,k6=(t,A,e,g)=>{for(var i=g>1?void 0:g?f6(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&S6(A,e,i),i};class Kc extends RA{constructor(){super(...arguments),r(this,"constraintActive",!0),r(this,"locked",!1),r(this,"sources",[])}}k6([w(UA)],Kc.prototype,"sources",2);const eY={type:"change"},hm={type:"start"},tY={type:"end"};let G6=class extends Ug{constructor(t,A){super(),this.object=t,this.domElement=A,this.domElement.style.touchAction="none",this.enabled=!0,this.target=new f,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:qn.ROTATE,MIDDLE:qn.DOLLY,RIGHT:qn.PAN},this.touches={ONE:vn.ROTATE,TWO:vn.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(H){H.addEventListener("keydown",ot),this._domElementKeyEvents=H},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(eY),e.update(),i=g.NONE},this.update=function(){const H=new f,X=new mA().setFromUnitVectors(t.up,new f(0,1,0)),jA=X.clone().invert(),VA=new f,TA=new mA,pA=2*Math.PI;return function(){const se=e.object.getWorldPosition(t.position);H.copy(se).sub(e.target),H.applyQuaternion(X),o.setFromVector3(H),e.autoRotate&&i===g.NONE&&U(F()),e.enableDamping?(o.theta+=C.theta*e.dampingFactor,o.phi+=C.phi*e.dampingFactor):(o.theta+=C.theta,o.phi+=C.phi);let Re=e.minAzimuthAngle,G=e.maxAzimuthAngle;return isFinite(Re)&&isFinite(G)&&(Re<-Math.PI?Re+=pA:Re>Math.PI&&(Re-=pA),G<-Math.PI?G+=pA:G>Math.PI&&(G-=pA),Re<=G?o.theta=Math.max(Re,Math.min(G,o.theta)):o.theta=o.theta>(Re+G)/2?Math.max(Re,o.theta):Math.min(G,o.theta)),o.phi=Math.max(e.minPolarAngle,Math.min(e.maxPolarAngle,o.phi)),o.makeSafe(),e.enableDamping?a=Ji.lerp(a,s,e.dampingFactor):a=s,o.radius*=a,o.radius=Math.max(e.minDistance,Math.min(e.maxDistance,o.radius)),e.enableDamping===!0?e.target.addScaledVector(n,e.dampingFactor):e.target.add(n),H.setFromSpherical(o),H.applyQuaternion(jA),se.copy(e.target).add(H),e.object.parent?e.object.parent.worldToLocal(se):e.object.position.copy(se),e.object.lookAt(e.target),e.enableDamping===!0?(C.theta*=1-e.dampingFactor,C.phi*=1-e.dampingFactor,n.multiplyScalar(1-e.dampingFactor)):(C.set(0,0,0),n.set(0,0,0)),s=1,B||VA.distanceToSquared(e.object.position)>I||8*(1-TA.dot(e.object.quaternion))>I?(e.dispatchEvent(eY),VA.copy(e.object.position),TA.copy(e.object.quaternion),B=!1,!0):!1}}(),this.dispose=function(){e.domElement.removeEventListener("contextmenu",BA),e.domElement.removeEventListener("pointerdown",YA),e.domElement.removeEventListener("pointercancel",uA),e.domElement.removeEventListener("wheel",Je),e.domElement.removeEventListener("pointermove",JA),e.domElement.removeEventListener("pointerup",ne),e._domElementKeyEvents!==null&&e._domElementKeyEvents.removeEventListener("keydown",ot)};const e=this,g={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6};let i=g.NONE;const I=1e-6,o=new Of,C=new Of;let s=1,a=1;const n=new f;let B=!1;const Q=new W,E=new W,h=new W,c=new W,l=new W,d=new W,u=new W,p=new W,D=new W,y=[],k={};function F(){return 2*Math.PI/60/60*e.autoRotateSpeed}function S(){return Math.pow(.95,e.zoomSpeed)}function U(H){C.theta-=H}function M(H){C.phi-=H}const Y=function(){const H=new f;return function(X,jA){H.setFromMatrixColumn(jA,0),H.multiplyScalar(-X),n.add(H)}}(),O=function(){const H=new f;return function(X,jA){e.screenSpacePanning===!0?H.setFromMatrixColumn(jA,1):(H.setFromMatrixColumn(jA,0),H.crossVectors(e.object.up,H)),H.multiplyScalar(X),n.add(H)}}(),x=function(){const H=new f,X=new f;return function(jA,VA){const TA=e.domElement;if(e.object.isPerspectiveCamera){e.object.getWorldPosition(X),H.copy(X).sub(e.target);let pA=H.length();pA*=Math.tan(e.object.fov/2*Math.PI/180),Y(2*jA*pA/TA.clientHeight,e.object.matrixWorld),O(2*VA*pA/TA.clientHeight,e.object.matrixWorld)}else e.object.isOrthographicCamera?(Y(jA*(e.object.right-e.object.left)/e.object.zoom/TA.clientWidth,e.object.matrixWorld),O(VA*(e.object.top-e.object.bottom)/e.object.zoom/TA.clientHeight,e.object.matrixWorld)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),e.enablePan=!1)}}();function b(H){e.object.isPerspectiveCamera?s/=H:e.object.isOrthographicCamera?(e.object.zoom=Math.max(e.minZoom,Math.min(e.maxZoom,e.object.zoom*H)),e.object.updateProjectionMatrix(),B=!0):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),e.enableZoom=!1)}function z(H){e.object.isPerspectiveCamera?s*=H:e.object.isOrthographicCamera?(e.object.zoom=Math.max(e.minZoom,Math.min(e.maxZoom,e.object.zoom/H)),e.object.updateProjectionMatrix(),B=!0):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),e.enableZoom=!1)}function gA(H){Q.set(H.clientX,H.clientY)}function sA(H){u.set(H.clientX,H.clientY)}function AA(H){c.set(H.clientX,H.clientY)}function dA(H){E.set(H.clientX,H.clientY),h.subVectors(E,Q).multiplyScalar(e.rotateSpeed);const X=e.domElement;U(2*Math.PI*h.x/X.clientHeight),M(2*Math.PI*h.y/X.clientHeight),Q.copy(E),e.update()}function rA(H){p.set(H.clientX,H.clientY),D.subVectors(p,u),D.y>0?b(S()):D.y<0&&z(S()),u.copy(p),e.update()}function LA(H){l.set(H.clientX,H.clientY),d.subVectors(l,c).multiplyScalar(e.panSpeed),x(d.x,d.y),c.copy(l),e.update()}function MA(H){H.deltaY<0?z(S()):H.deltaY>0&&b(S()),e.update()}function iA(H){let X=!1;switch(H.code){case e.keys.UP:H.ctrlKey||H.metaKey||H.shiftKey?M(2*Math.PI*e.rotateSpeed/e.domElement.clientHeight):x(0,e.keyPanSpeed),X=!0;break;case e.keys.BOTTOM:H.ctrlKey||H.metaKey||H.shiftKey?M(-2*Math.PI*e.rotateSpeed/e.domElement.clientHeight):x(0,-e.keyPanSpeed),X=!0;break;case e.keys.LEFT:H.ctrlKey||H.metaKey||H.shiftKey?U(2*Math.PI*e.rotateSpeed/e.domElement.clientHeight):x(e.keyPanSpeed,0),X=!0;break;case e.keys.RIGHT:H.ctrlKey||H.metaKey||H.shiftKey?U(-2*Math.PI*e.rotateSpeed/e.domElement.clientHeight):x(-e.keyPanSpeed,0),X=!0;break}X&&(H.preventDefault(),e.update())}function QA(){if(y.length===1)Q.set(y[0].pageX,y[0].pageY);else{const H=.5*(y[0].pageX+y[1].pageX),X=.5*(y[0].pageY+y[1].pageY);Q.set(H,X)}}function NA(){if(y.length===1)c.set(y[0].pageX,y[0].pageY);else{const H=.5*(y[0].pageX+y[1].pageX),X=.5*(y[0].pageY+y[1].pageY);c.set(H,X)}}function $(){const H=y[0].pageX-y[1].pageX,X=y[0].pageY-y[1].pageY,jA=Math.sqrt(H*H+X*X);u.set(0,jA)}function OA(){e.enableZoom&&$(),e.enablePan&&NA()}function HA(){e.enableZoom&&$(),e.enableRotate&&QA()}function qA(H){if(y.length==1)E.set(H.pageX,H.pageY);else{const jA=oe(H),VA=.5*(H.pageX+jA.x),TA=.5*(H.pageY+jA.y);E.set(VA,TA)}h.subVectors(E,Q).multiplyScalar(e.rotateSpeed);const X=e.domElement;U(2*Math.PI*h.x/X.clientHeight),M(2*Math.PI*h.y/X.clientHeight),Q.copy(E)}function wA(H){if(y.length===1)l.set(H.pageX,H.pageY);else{const X=oe(H),jA=.5*(H.pageX+X.x),VA=.5*(H.pageY+X.y);l.set(jA,VA)}d.subVectors(l,c).multiplyScalar(e.panSpeed),x(d.x,d.y),c.copy(l)}function cA(H){const X=oe(H),jA=H.pageX-X.x,VA=H.pageY-X.y,TA=Math.sqrt(jA*jA+VA*VA);p.set(0,TA),D.set(0,Math.pow(p.y/u.y,e.zoomSpeed)),b(D.y),u.copy(p)}function yA(H){e.enableZoom&&cA(H),e.enablePan&&wA(H)}function lA(H){e.enableZoom&&cA(H),e.enableRotate&&qA(H)}function YA(H){e.enabled!==!1&&(y.length===0&&(e.domElement.addEventListener("pointermove",JA),e.domElement.addEventListener("pointerup",ne)),FA(H),H.pointerType==="touch"?L(H):re(H))}function JA(H){e.enabled!==!1&&(H.pointerType==="touch"?J(H):Be(H))}function ne(H){vA(H),y.length===0&&(e.domElement.removeEventListener("pointermove",JA),e.domElement.removeEventListener("pointerup",ne)),e.dispatchEvent(tY),i=g.NONE}function uA(H){vA(H)}function re(H){let X;switch(H.button){case 0:X=e.mouseButtons.LEFT;break;case 1:X=e.mouseButtons.MIDDLE;break;case 2:X=e.mouseButtons.RIGHT;break;default:X=-1}switch(X){case qn.DOLLY:if(e.enableZoom===!1)return;sA(H),i=g.DOLLY;break;case qn.ROTATE:if(H.ctrlKey||H.metaKey||H.shiftKey){if(e.enablePan===!1)return;AA(H),i=g.PAN}else{if(e.enableRotate===!1)return;gA(H),i=g.ROTATE}break;case qn.PAN:if(H.ctrlKey||H.metaKey||H.shiftKey){if(e.enableRotate===!1)return;gA(H),i=g.ROTATE}else{if(e.enablePan===!1)return;AA(H),i=g.PAN}break;default:i=g.NONE}i!==g.NONE&&e.dispatchEvent(hm)}function Be(H){switch(i){case g.ROTATE:if(e.enableRotate===!1)return;dA(H);break;case g.DOLLY:if(e.enableZoom===!1)return;rA(H);break;case g.PAN:if(e.enablePan===!1)return;LA(H);break}}function Je(H){e.enabled===!1||e.enableZoom===!1||i!==g.NONE||(H.preventDefault(),e.dispatchEvent(hm),MA(H),e.dispatchEvent(tY))}function ot(H){e.enabled===!1||e.enablePan===!1||iA(H)}function L(H){switch(_A(H),y.length){case 1:switch(e.touches.ONE){case vn.ROTATE:if(e.enableRotate===!1)return;QA(),i=g.TOUCH_ROTATE;break;case vn.PAN:if(e.enablePan===!1)return;NA(),i=g.TOUCH_PAN;break;default:i=g.NONE}break;case 2:switch(e.touches.TWO){case vn.DOLLY_PAN:if(e.enableZoom===!1&&e.enablePan===!1)return;OA(),i=g.TOUCH_DOLLY_PAN;break;case vn.DOLLY_ROTATE:if(e.enableZoom===!1&&e.enableRotate===!1)return;HA(),i=g.TOUCH_DOLLY_ROTATE;break;default:i=g.NONE}break;default:i=g.NONE}i!==g.NONE&&e.dispatchEvent(hm)}function J(H){switch(_A(H),i){case g.TOUCH_ROTATE:if(e.enableRotate===!1)return;qA(H),e.update();break;case g.TOUCH_PAN:if(e.enablePan===!1)return;wA(H),e.update();break;case g.TOUCH_DOLLY_PAN:if(e.enableZoom===!1&&e.enablePan===!1)return;yA(H),e.update();break;case g.TOUCH_DOLLY_ROTATE:if(e.enableZoom===!1&&e.enableRotate===!1)return;lA(H),e.update();break;default:i=g.NONE}}function BA(H){e.enabled!==!1&&H.preventDefault()}function FA(H){y.push(H)}function vA(H){delete k[H.pointerId];for(let X=0;X<y.length;X++)if(y[X].pointerId==H.pointerId){y.splice(X,1);return}}function _A(H){let X=k[H.pointerId];X===void 0&&(X=new W,k[H.pointerId]=X),X.set(H.pageX,H.pageY)}function oe(H){const X=H.pointerId===y[0].pointerId?y[1]:y[0];return k[X.pointerId]}e.domElement.addEventListener("contextmenu",BA),e.domElement.addEventListener("pointerdown",YA),e.domElement.addEventListener("pointercancel",uA),e.domElement.addEventListener("wheel",Je,{passive:!1}),this.update()}};class m6{static createButton(A,e={},g){const i=document.createElement("button");let I=!1;function o(){if(e.optionalFeatures=e.optionalFeatures||[],e.domOverlay===void 0){var n=document.createElement("div");n.style.display="none",document.body.appendChild(n);var B=document.createElementNS("http://www.w3.org/2000/svg","svg");B.setAttribute("width",38),B.setAttribute("height",38),B.style.position="absolute",B.style.right="20px",B.style.top="20px",B.addEventListener("click",function(){E.end()}),n.appendChild(B);var Q=document.createElementNS("http://www.w3.org/2000/svg","path");Q.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),Q.setAttribute("stroke","#fff"),Q.setAttribute("stroke-width",2),B.appendChild(Q),e.optionalFeatures.push("dom-overlay"),e.domOverlay={root:n},I=!0}let E=null,h=null;async function c(d){var u;const p=/WebXRViewer\//i.test(navigator.userAgent),D=e.domOverlay.root;p&&((u=e.domOverlay)!=null&&u.root?(h=D.parentNode,h&&(console.log("Reparent DOM Overlay to body",D,D.style.display),D.style.display="",D.style.visibility="",document.body.appendChild(D))):console.warn("WebXRViewer: No DOM Overlay found")),d.addEventListener("end",l),await A.xr.setSession(d),i.textContent="STOP AR",I&&(e.domOverlay.root.style.display=""),E=d}function l(){E.removeEventListener("end",l),i.textContent="START AR";const d=e.domOverlay.root;h&&h.appendChild(d),I&&(d.style.display="none"),E=null}i.style.display="",i.style.cursor="pointer",i.style.left="calc(50% - 50px)",i.style.width="100px",i.textContent="START AR",i.onmouseenter=function(){i.style.opacity="1.0"},i.onmouseleave=function(){i.style.opacity="0.5"},i.onclick=function(){E===null?(g?.call(this,e),navigator.xr.requestSession("immersive-ar",e).then(c)):E.end()}}function C(){i.disabled=!0,i.style.display="",i.style.cursor="auto",i.style.left="calc(50% - 75px)",i.style.width="150px",i.onmouseenter=null,i.onmouseleave=null,i.onclick=null}function s(){C(),i.textContent="AR NOT SUPPORTED"}function a(n){n.style.position="absolute",n.style.bottom="20px",n.style.padding="12px 6px",n.style.border="1px solid #fff",n.style.borderRadius="4px",n.style.background="rgba(0,0,0,0.1)",n.style.color="#fff",n.style.font="normal 13px sans-serif",n.style.textAlign="center",n.style.opacity="0.5",n.style.outline="none",n.style.zIndex="999"}if("xr"in navigator)return i.id="ARButton",i.style.display="none",a(i),navigator.xr.isSessionSupported("immersive-ar").then(function(n){n?o():s()}).catch(s),i;{const n=document.createElement("a");return window.isSecureContext===!1?(n.href=document.location.href.replace(/^http:/,"https:"),n.innerHTML="WEBXR NEEDS HTTPS"):(n.href="https://immersiveweb.dev/",n.innerHTML="WEBXR NOT AVAILABLE"),n.style.left="calc(50% - 90px)",n.style.width="180px",n.style.textDecoration="none",a(n),n}}}const cm=class{static createButton(t,A){const e=document.createElement("button");function g(){let C=null;async function s(n){n.addEventListener("end",a),await t.xr.setSession(n),e.textContent="EXIT VR",C=n}function a(){C.removeEventListener("end",a),e.textContent="ENTER VR",C=null}e.style.display="",e.style.cursor="pointer",e.style.left="calc(50% - 50px)",e.style.width="100px",e.textContent="ENTER VR",e.onmouseenter=function(){e.style.opacity="1.0"},e.onmouseleave=function(){e.style.opacity="0.5"},e.onclick=function(){if(C===null){const n={optionalFeatures:A.optionalFeatures};navigator.xr.requestSession("immersive-vr",n).then(s)}else C.end()}}function i(){e.disabled=!0,e.style.display="",e.style.cursor="auto",e.style.left="calc(50% - 75px)",e.style.width="150px",e.onmouseenter=null,e.onmouseleave=null,e.onclick=null}function I(){i(),e.textContent="VR NOT SUPPORTED"}function o(C){C.style.position="absolute",C.style.bottom="20px",C.style.padding="12px 6px",C.style.border="1px solid #fff",C.style.borderRadius="4px",C.style.background="rgba(0,0,0,0.1)",C.style.color="#fff",C.style.font="normal 13px sans-serif",C.style.textAlign="center",C.style.opacity="0.5",C.style.outline="none",C.style.zIndex="999"}if("xr"in navigator)return e.id="VRButton",e.style.display="none",o(e),navigator.xr.isSessionSupported("immersive-vr").then(function(C){C?g():I(),cm.xrSessionIsGranted&&(console.log("XR session is granted - will enter immersive web now"),e.click())}),e;{const C=document.createElement("a");return window.isSecureContext===!1?(C.href=document.location.href.replace(/^http:/,"https:"),C.innerHTML="WEBXR NEEDS HTTPS"):(C.href="https://immersiveweb.dev/",C.innerHTML="WEBXR NOT AVAILABLE"),C.style.left="calc(50% - 90px)",C.style.width="180px",C.style.textDecoration="none",o(C),C}}static registerSessionGrantedListener(){if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent))return;navigator.xr.addEventListener("sessiongranted",()=>{cm.xrSessionIsGranted=!0})}}};let lm=cm;r(lm,"xrSessionIsGranted",!1),lm.registerSessionGrantedListener();const _D="noVoip",rI=CA("debugvoip"),M6=CA("voip");class R6{constructor(A){r(this,"id"),this.id=A}}class U6{constructor(A,e,g,i){r(this,"peer"),r(this,"voip"),r(this,"userId"),r(this,"peerId"),r(this,"call",null),r(this,"callErrorListener",null),r(this,"stream",null),this.voip=A,this.peer=e,this.userId=g,this.peerId=i}close(){var A;rI&&console.log("close voip call"),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.open&&this.call.close(),(A=this.stream)==null||A.getTracks().forEach(function(e){e.stop()})}updateMute(A){var e;if(!this.stream)return;const g=(e=this.stream)==null?void 0:e.getAudioTracks();for(const i of g)i.enabled=!A}async startVoipCall(){if(!await ia.HasMicrophonePermissions()){console.warn("no permission to use microphone, can not start call");return}rI&&console.log("start voip call"),this.stream=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),this.updateMute(this.voip.muteOutput),rI&&console.log(this.stream),this.call=this.peer.call(this.peerId,this.stream,{metadata:{userId:this.userId}}),this.call.on("error",A=>{console.error(A)}),this.call.on("stream",A=>{rI&&console.log("received stream from remote again",A)}),this.peer.on("close",this.onCallClose.bind(this)),this.callErrorListener=A=>{var e;A.message.includes(this.peerId)?(console.log("Could not connect to "+this.peerId),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.close(),(e=this.stream)==null||e.getTracks().forEach(function(g){g.stop()}),this.stream=null):console.error(A)},this.peer.on("error",this.callErrorListener)}onCallClose(A){rI&&console.log("call closed",A)}}class F6{constructor(A,e,g){r(this,"voip"),r(this,"call"),r(this,"audio",null),r(this,"stream",null),r(this,"obj"),r(this,"analyzer",null),r(this,"waitingForStart",!1),r(this,"closed",!1),r(this,"audioElement",null),this.voip=A,this.obj=e,this.call=g}get currentStream(){return this.stream}get currentAudio(){return this.audio}get currentAnalyzer(){return this.analyzer}openAudioStream(A){const e=A.getAudioTracks();for(const g of e)if(g.kind==="audio"&&g.readyState==="live"){this.open(g);return}console.warn("failed finding valid audio stream to begin call")}open(A){console.assert(A.kind==="audio","invalid track kind, expected audio but received "+A.kind),!this.waitingForStart&&(this.waitingForStart=!0,cg.userInteractionRegistered||rI&&console.log("Incoming call, waiting for user interaction before opening audio"),cg.registerWaitForAllowAudio(async()=>{if(this.call.open&&!this.closed){rI&&console.log("Setup audio and begin listening"),this.stream=new MediaStream([A]);const e=new xf;this.audio=new gu(e),this.audio.setVolume(this.voip.muteInput?0:1),this.audio.setMediaStreamSource(this.stream);const g=document.createElement("audio");this.audioElement=g,g.style.display="none",document.body.appendChild(g),g.srcObject=this.stream,g.sinkId!==void 0&&navigator.mediaDevices.enumerateDevices().then(i=>{if(g){console.log(i);for(const I of i)if(I.label==="Speakerphone"){g.sinkId=I.deviceId;break}}}),rI&&console.log("call is setup, you should hear something now"),this.analyzer=new ZK(this.audio,32)}}))}close(){var A,e,g;this.closed=!0,(A=this.call)!=null&&A.open&&this.call.close(),(e=this.audio)==null||e.disconnect(),(g=this.stream)==null||g.getTracks().forEach(i=>{i.stop()}),this.stream=null,this.audioElement&&this.audioElement.remove()}}class ia extends RA{constructor(){super(...arguments),r(this,"requireParam",!1),r(this,"peer",null),r(this,"model",null),r(this,"connections",{}),r(this,"currentIncomingCalls",{}),r(this,"_inputMuted",!1),r(this,"_outputMuted",!1)}set muteInput(A){var e;if(A===this._inputMuted||(this._inputMuted=A,!this.currentIncomingCalls))return;const g=this._inputMuted?0:1;for(const i in this.currentIncomingCalls){const I=this.currentIncomingCalls[i];(e=I?.currentAudio)==null||e.setVolume(g)}}get muteInput(){return this._inputMuted}set muteOutput(A){if(A!==this._outputMuted&&(this._outputMuted=A,!!this.connections))for(const e in this.connections){const g=this.connections[e];g?.updateMute(A)}}get muteOutput(){return this._outputMuted}getFrequency(A){if(A===null){for(const g in this.currentIncomingCalls){const i=this.currentIncomingCalls[g];if(i&&i.currentAnalyzer)return i.currentAnalyzer.getAverageFrequency()}return null}const e=this.currentIncomingCalls[A];return e&&e.currentAnalyzer?e.currentAnalyzer.getAverageFrequency():null}awake(){if(CA(_D)){console.log("VOIP is disabled by url parameter: "+_D);return}if(this.requireParam&&!M6){console.debug("VOIP must be enabled explicitly by url parameter");return}if($E()&&WC()){console.log("VOIP is currently not supported on Safari iOS");return}this.peer=new Yu,navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia,this.context.connection.beginListen(Wt.JoinedRoom,A=>{navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}),this.context.connection.beginListen("peer-update-id",A=>{if(A.id!==this.context.connection.connectionId){const e=this.connections[A.id];if(e&&e.close(),this.peer&&this.context.connection.connectionId){const g=new U6(this,this.peer,this.context.connection.connectionId,A.peerId);this.connections[A.id]=g,g.startVoipCall()}}}),this.context.connection.beginListen(Wt.UserLeftRoom,A=>{const{userId:e}=A,g=this.connections[e];this.connections[e]=null,g&&g.close();const i=this.currentIncomingCalls[e];rI&&console.log("UserLeftRoom",A,e,i),i&&(i.close(),this.currentIncomingCalls[e]=null)}),this.peer.on("open",this.onOpenPeerConnection.bind(this))}onEnable(){}onDisable(){console.log("TODO: close all");for(const A in this.currentIncomingCalls)try{const e=this.currentIncomingCalls[A];e?.close();const g=this.connections[A];g?.close()}catch(e){console.error(e)}}async onOpenPeerConnection(A){rI&&console.log("Peer connection established and received id"),this.model=new R6(A),this.context.connection.send("peer-update-id",this.model,oI.OnRoomJoin),this.peer&&(this.peer.on("call",this.onReceiveCall.bind(this)),this.peer.on("connection",function(e){rI&&console.log("CONNECTION",e),e.on("data",function(g){rI&&console.log("Received",g)})}))}async onReceiveCall(A){const{metadata:e}=A;console.assert(e.userId);const{userId:g}=e,i=this.currentIncomingCalls[g];if(i&&i.close(),rI&&console.log("received call"),await ia.HasMicrophonePermissions()){const I=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1});A.answer(I)}else A.answer(null);this.currentIncomingCalls[g]=new F6(this,this.gameObject,A),A.on("stream",I=>{var o;rI&&console.log("receive caller stream, will setup audio now"),(o=this.currentIncomingCalls[g])==null||o.openAudioStream(I)}),A.on("error",console.error)}static async HasMicrophonePermissions(){return(await navigator.permissions.query({name:"microphone"})).state!=="denied"}}var N6=Object.defineProperty,K6=Object.getOwnPropertyDescriptor,gY=(t,A,e,g)=>{for(var i=g>1?void 0:g?K6(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&N6(A,e,i),i};class tn extends RA{constructor(){super(...arguments),r(this,"webAR",null),r(this,"invertForward",!1),r(this,"_initalMatrix",new KA),r(this,"_selectStartFn",this.onSelectStart.bind(this)),r(this,"_selectEndFn",this.onSelectEnd.bind(this)),r(this,"_arScale",5),r(this,"_rig",null),r(this,"_startPose",null),r(this,"_placementPose",null),r(this,"_isTouching",!1),r(this,"_rigStartPose",null),r(this,"_gotFirstHitTestResult",!1)}get rig(){var A;return(A=this.webAR)==null?void 0:A.webxr.Rig}get arScale(){return this._arScale}set arScale(A){A!==this._arScale&&(this._arScale=A,this.setScale(A))}start(){const A=eA.findObjectOfType(Se);A&&(A.Rig.updateMatrix(),this._initalMatrix.copy(A.Rig.matrix))}onBegin(A){var e;this._placementPose=null,this.gameObject.visible=!1,this.gameObject.matrixAutoUpdate=!1,this._startPose=this.gameObject.matrix.clone(),this._rigStartPose=(e=this.rig)==null?void 0:e.matrix.clone(),this._gotFirstHitTestResult=!1,A.addEventListener("selectstart",this._selectStartFn),A.addEventListener("selectend",this._selectEndFn),this.gameObject.visible=!1,this.rig&&(this.rig.matrixAutoUpdate=!0,this._initalMatrix.decompose(this.rig.position,this.rig.quaternion,this.rig.scale)),this.dispatchEvent(new CustomEvent("onBeginSession"))}onUpdate(A,e,g){if(g&&!this._placementPose&&(this._gotFirstHitTestResult||(this._gotFirstHitTestResult=!0,this.dispatchEvent(new CustomEvent("canPlaceSession",{detail:{pose:g}}))),this._isTouching)){const i=new KA().fromArray(g.transform.matrix).invert();return this.dispatchEvent(new CustomEvent("placedSession",{detail:{pose:g,poseMatrix:i}})),this.webAR&&this.webAR.setReticleActive(!1),this.placeAt(A,i),!0}return!1}placeAt(A,e){this._placementPose||(this._placementPose=new KA),this._placementPose.copy(e);const g=this.gameObject.matrixWorld.clone().invert();if(this._placementPose.premultiply(g),A){if(this.invertForward){const i=new KA().makeRotationY(Math.PI);this._placementPose.premultiply(i)}this._rig=A,this.setScale(this.arScale)}else this._rig=null;this.gameObject.visible=!0}onEnd(A,e){this._placementPose=null,this.gameObject.visible=!1,this.gameObject.matrixAutoUpdate=!1,this._startPose&&this.gameObject.matrix.copy(this._startPose),A&&(A.matrixAutoUpdate=!0,this._rigStartPose&&this._rigStartPose.decompose(A.position,A.quaternion,A.scale)),pI.markDirty(this.gameObject,!0),setTimeout(()=>{this.gameObject.matrixAutoUpdate=!0,this.gameObject.visible=!0},100)}onSelectStart(){this._isTouching=!0}onSelectEnd(){this._isTouching=!1}setScale(A){const e=this._rig;!e||!this._placementPose||(this._rigStartPose||(this._rigStartPose=e.matrix.clone()),e.matrixAutoUpdate=!1,e.matrix.multiplyMatrices(new KA().makeScale(A,A,A),this._placementPose),e.matrix.decompose(e.position,e.quaternion,e.scale),e.updateMatrixWorld(),console.log("Place",e.position))}}gY([w()],tn.prototype,"invertForward",2),gY([w()],tn.prototype,"arScale",1);const J6="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/";class q6{constructor(A,e,g,i,I=null){this.controller=e,this.handModel=A,this.bones=[],I===null&&(I=new BQ,I.setPath(g||J6)),I.load(`${i}.glb`,o=>{const C=o.scene.children[0];this.handModel.add(C),C.layers.mask=this.handModel.layers.mask;const s=C.getObjectByProperty("type","SkinnedMesh");s.frustumCulled=!1,s.castShadow=!0,s.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 n=C.getObjectByName(a);n!==void 0?n.jointName=a:console.warn(`Couldn't find ${a} in ${i} hand mesh`),this.bones.push(n)})})}updateMesh(){const A=this.controller.joints;for(let e=0;e<this.bones.length;e++){const g=this.bones[e];if(g){const i=A[g.jointName];if(i.visible){const I=i.position;g.position.copy(I),g.quaternion.copy(i.quaternion)}}}}}const v6=.01,b6="index-finger-tip";class L6 extends UA{constructor(A,e=null){super(),this.controller=A,this.motionController=null,this.envMap=null,this.loader=e,this.mesh=null,A.addEventListener("connected",g=>{const i=g.data;i.hand&&!this.motionController&&(this.xrInputSource=i,this.motionController=new q6(this,A,this.path,i.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[b6];return A?A.position:null}intersectBoxObject(A){const e=this.getPointerPosition();if(e){const g=new Ro(e,v6),i=new li().setFromObject(A);return g.intersectsBox(i)}else return!1}checkButton(A){this.intersectBoxObject(A)?A.onPress():A.onClear(),A.isPressed()&&A.whilePressed()}}const x6=.05,iY=.02,PD=.01,IY=.02,oY=1,qQ=.4,Y6=.002,Jc=.01,jD=.003,CY=.035,yt=16,no=12,dm=110,H6=new f(0,1,0),T6=new f(0,0,1),O6=.02,_6=1.5;class P6 extends UA{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,A.addEventListener("connected",g=>{const i=g.data;i.hand&&(this.visible=!0,this.xrInputSource=i,this.pointerObject===null&&this.createPointer())})}_drawVerticesRing(A,e,g){const i=e.clone();for(let I=0;I<yt;I++){i.applyAxisAngle(T6,Math.PI*2/yt);const o=g*yt+I;A[3*o]=i.x,A[3*o+1]=i.y,A[3*o+2]=i.z}}_updatePointerVertices(A){const e=this.pointerGeometry.attributes.position.array,g=new f(Y6,0,-1*(CY-A));this._drawVerticesRing(e,g,0);const i=new f(Math.sin(Math.PI*dm/180)*A,Math.cos(Math.PI*dm/180)*A,0);for(let a=0;a<no;a++)this._drawVerticesRing(e,i,a+1),i.applyAxisAngle(H6,Math.PI*dm/180/(no*-2));const I=yt*(1+no),o=yt*(1+no)+1,C=new f(0,0,-1*(CY-A));e[I*3]=C.x,e[I*3+1]=C.y,e[I*3+2]=C.z;const s=new f(0,0,A);e[o*3]=s.x,e[o*3+1]=s.y,e[o*3+2]=s.z,this.pointerGeometry.setAttribute("position",new ee(e,3))}createPointer(){let A,e;const g=new Array(((no+1)*yt+2)*3).fill(0),i=[];for(this.pointerGeometry=new le,this.pointerGeometry.setAttribute("position",new ee(g,3)),this._updatePointerVertices(Jc),A=0;A<no;A++){for(e=0;e<yt-1;e++)i.push(A*yt+e,A*yt+e+1,(A+1)*yt+e),i.push(A*yt+e+1,(A+1)*yt+e+1,(A+1)*yt+e);i.push((A+1)*yt-1,A*yt,(A+2)*yt-1),i.push(A*yt,(A+1)*yt,(A+2)*yt-1)}const I=yt*(1+no),o=yt*(1+no)+1;for(A=0;A<yt-1;A++)i.push(I,A+1,A),i.push(o,A+yt*no,A+yt*no+1);i.push(I,0,yt-1),i.push(o,yt*(no+1)-1,yt*no);const C=new dt;C.transparent=!0,C.opacity=qQ,this.pointerGeometry.setIndex(i),this.pointerMesh=new DA(this.pointerGeometry,C),this.pointerMesh.position.set(0,0,-1*Jc),this.pointerObject=new UA,this.pointerObject.add(this.pointerMesh),this.raycaster=new VB;const s=new OI(O6,10,10),a=new dt;a.transparent=!0,a.opacity=qQ,this.cursorObject=new DA(s,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 KA;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"],g=A.position.distanceTo(e.position),i=A.position.clone().add(e.position).multiplyScalar(.5);this.pointerObject.position.copy(i),this.pointerObject.quaternion.copy(this.controller.quaternion),this.pinched=g<=iY;const I=(g-PD)/(x6-PD),o=(g-PD)/(iY-PD);if(I>1)this._updatePointerVertices(Jc),this.pointerMesh.position.set(0,0,-1*Jc),this.pointerMesh.material.opacity=qQ;else if(I>0){const C=(Jc-jD)*I+jD;this._updatePointerVertices(C),o<1?(this.pointerMesh.position.set(0,0,-1*C-(1-o)*IY),this.pointerMesh.material.opacity=qQ+(1-o)*(oY-qQ)):(this.pointerMesh.position.set(0,0,-1*C),this.pointerMesh.material.opacity=qQ)}else this._updatePointerVertices(jD),this.pointerMesh.position.set(0,0,-1*jD-IY),this.pointerMesh.material.opacity=oY;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 g=this.raycaster.intersectObjects(A,e),i=new f(0,0,-1);if(g.length>0){const I=g[0].distance;this.cursorObject.position.copy(i.multiplyScalar(I))}else this.cursorObject.position.copy(i.multiplyScalar(_6))}}setCursor(A){const e=new f(0,0,-1);this.raycaster&&!this.attached&&this.cursorObject.position.copy(e.multiplyScalar(A))}}const Vt={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 sY(t){const A=await fetch(t);if(A.ok)return A.json();throw new Error(A.statusText)}async function j6(t){if(!t)throw new Error("No basePath supplied");return await sY(`${t}/profilesList.json`)}async function W6(t,A,e=null,g=!0){if(!t)throw new Error("No xrInputSource supplied");if(!A)throw new Error("No basePath supplied");const i=await j6(A);let I;if(t.profiles.some(s=>{const a=i[s];return a&&(I={profileId:s,profilePath:`${A}/${a.path}`,deprecated:!!a.deprecated}),!!I}),!I){if(!e)throw new Error("No matching profile name found");const s=i[e];if(!s)throw new Error(`No matching profile name found and default profile "${e}" missing.`);I={profileId:e,profilePath:`${A}/${s.path}`,deprecated:!!s.deprecated}}const o=await sY(I.profilePath);let C;if(g){let s;if(t.handedness==="any"?s=o.layouts[Object.keys(o.layouts)[0]]:s=o.layouts[t.handedness],!s)throw new Error(`No matching handedness, ${t.handedness}, in profile ${I.profileId}`);s.assetPath&&(C=I.profilePath.replace("profile.json",s.assetPath))}return{profile:o,assetPath:C}}const V6={xAxis:0,yAxis:0,button:0,state:Vt.ComponentState.DEFAULT};function z6(t=0,A=0){let e=t,g=A;if(Math.sqrt(t*t+A*A)>1){const i=Math.atan2(A,t);e=Math.cos(i),g=Math.sin(i)}return{normalizedXAxis:e*.5+.5,normalizedYAxis:g*.5+.5}}class Z6{constructor(A){this.componentProperty=A.componentProperty,this.states=A.states,this.valueNodeName=A.valueNodeName,this.valueNodeProperty=A.valueNodeProperty,this.valueNodeProperty===Vt.VisualResponseProperty.TRANSFORM&&(this.minNodeName=A.minNodeName,this.maxNodeName=A.maxNodeName),this.value=0,this.updateFromComponent(V6)}updateFromComponent({xAxis:A,yAxis:e,button:g,state:i}){const{normalizedXAxis:I,normalizedYAxis:o}=z6(A,e);switch(this.componentProperty){case Vt.ComponentProperty.X_AXIS:this.value=this.states.includes(i)?I:.5;break;case Vt.ComponentProperty.Y_AXIS:this.value=this.states.includes(i)?o:.5;break;case Vt.ComponentProperty.BUTTON:this.value=this.states.includes(i)?g:0;break;case Vt.ComponentProperty.STATE:this.valueNodeProperty===Vt.VisualResponseProperty.VISIBILITY?this.value=this.states.includes(i):this.value=this.states.includes(i)?1:0;break;default:throw new Error(`Unexpected visualResponse componentProperty ${this.componentProperty}`)}}}class X6{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(g=>{const i=new Z6(e.visualResponses[g]);this.visualResponses[g]=i}),this.gamepadIndices=Object.assign({},e.gamepadIndices),this.values={state:Vt.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=Vt.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=Vt.ComponentState.PRESSED:(e.touched||this.values.button>Vt.ButtonTouchThreshold)&&(this.values.state=Vt.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===Vt.ComponentState.DEFAULT&&Math.abs(this.values.xAxis)>Vt.AxisTouchThreshold&&(this.values.state=Vt.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===Vt.ComponentState.DEFAULT&&Math.abs(this.values.yAxis)>Vt.AxisTouchThreshold&&(this.values.state=Vt.ComponentState.TOUCHED)),Object.values(this.visualResponses).forEach(e=>{e.updateFromComponent(this.values)})}}class $6{constructor(A,e,g){if(!A)throw new Error("No xrInputSource supplied");if(!e)throw new Error("No profile supplied");this.xrInputSource=A,this.assetUrl=g,this.id=e.profileId,this.layoutDescription=e.layouts[A.handedness],this.components={},Object.keys(this.layoutDescription.components).forEach(i=>{const I=this.layoutDescription.components[i];this.components[i]=new X6(i,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 A7="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",e7="generic-trigger";class t7 extends UA{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(g=>{const{valueNode:i,minNode:I,maxNode:o,value:C,valueNodeProperty:s}=g;i&&(s===Vt.VisualResponseProperty.VISIBILITY?i.visible=C:s===Vt.VisualResponseProperty.TRANSFORM&&(i.quaternion.slerpQuaternions(I.quaternion,o.quaternion,C),i.position.lerpVectors(I.position,o.position,C)))})}))}}function g7(t,A){Object.values(t.components).forEach(e=>{const{type:g,touchPointNodeName:i,visualResponses:I}=e;if(g===Vt.ComponentType.TOUCHPAD)if(e.touchPointNode=A.getObjectByName(i),e.touchPointNode){const o=new OI(.001),C=new dt({color:255}),s=new DA(o,C);e.touchPointNode.add(s)}else console.warn(`Could not find touch dot, ${e.touchPointNodeName}, in touchpad component ${e.id}`);Object.values(I).forEach(o=>{const{valueNodeName:C,minNodeName:s,maxNodeName:a,valueNodeProperty:n}=o;if(n===Vt.VisualResponseProperty.TRANSFORM){if(o.minNode=A.getObjectByName(s),o.maxNode=A.getObjectByName(a),!o.minNode){console.warn(`Could not find ${s} in the model`);return}if(!o.maxNode){console.warn(`Could not find ${a} in the model`);return}}o.valueNode=A.getObjectByName(C),o.valueNode||console.warn(`Could not find ${C} in the model`)})})}function aY(t,A){g7(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 i7{constructor(A=null){this.gltfLoader=A,this.path=A7,this._assetCache={},this.gltfLoader||(this.gltfLoader=new BQ)}createControllerModel(A){const e=new t7;let g=null;return A.addEventListener("connected",i=>{const I=i.data;I.targetRayMode!=="tracked-pointer"||!I.gamepad||W6(I,this.path,e7).then(({profile:o,assetPath:C})=>{e.motionController=new $6(I,o,C);const s=this._assetCache[e.motionController.assetUrl];if(s)g=s.scene.clone(),aY(e,g);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,g=a.scene.clone(),aY(e,g)},null,()=>{throw new Error(`Asset ${e.motionController.assetUrl} missing or malformed.`)})}}).catch(o=>{console.warn(o)})}),A.addEventListener("disconnected",()=>{e.motionController=null,e.remove(g),g=null}),e}}const qc=CA("debugavatar");class WD{constructor(A,e,g,i){r(this,"root"),r(this,"head"),r(this,"leftHand"),r(this,"rigthHand");var I;this.root=A,this.head=e,this.leftHand=g,this.rigthHand=i,(I=this.root)==null||I.traverse(o=>o.layers.set(2))}get isValid(){return this.head!==null&&this.head!==void 0}}class VD{constructor(){r(this,"avatarRegistryUrl",null)}async getOrCreateNewAvatarInstance(A,e){if(!e)return console.error("Can not create avatar: failed to provide id or root object"),null;let g=null;if(typeof e=="string"){if(g=await this.loadAvatar(A,e),!g){const I=new rC;g=eA.instantiate(BB(e,A.scene),I)}}else g=e;if(!g)return null;const i=this.findAvatar(g);return i.isValid?(qc&&console.log("[Custom Avatar] valid config",e,qc?i:""),i):(console.warn("[Custom Avatar] config isn't valid",e,qc?i:""),null)}async loadAvatar(A,e){if(console.assert(e!=null&&typeof e=="string","Avatar id must not be null"),e.length<=0||!e)return null;if(qc&&console.log("[Custom Avatar] "+e+", loading..."),e.endsWith(".glb")||(e+=".glb"),this.avatarRegistryUrl===null){const i=await fetch("./"+e);let I=null;if(i.ok){const C=await i.blob();C&&(I=await C.arrayBuffer())}if(!I&&(I=await $k(e,e,0,"no url here go away",!0),!I))return null;const o=await bo().parseSync(A,I,null,0);return o?.scene??null}const g=new BQ;return lc(g,A),new Promise((i,I)=>{const o=this.avatarRegistryUrl+"/"+e;g.load(o,async C=>{await bo().createBuiltinComponents(A,o,C,null,void 0),i(C.scene)},C=>{qc&&console.log("[Custom Avatar] "+C.loaded/C.total*100+"% loaded of "+C.total/1024+"kB")},C=>{console.error("[Custom Avatar] Error when loading: "+C),i(null)})})}cacheModel(A,e){}findAvatar(A){const e=A;let g=e;g.children.length==1&&(g=A.children[0]);let i=this.findAvatarPart(g,["head"]);const I=this.findAvatarPart(g,["left","hand"]),o=this.findAvatarPart(g,["right","hand"]);if(!i){i=e;const C=new f;new li().setFromObject(i).getSize(C);const s=Math.max(C.x,C.y,C.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+s+" meters! Should be < 0.3m"),s>.3&&i.scale.multiplyScalar(1/s*.3)}return new WD(e,i,I,o)}findAvatarPart(A,e){const g=A.name.toLowerCase();let i=!0;for(const I of e){if(!i)break;g.indexOf(I)===-1&&(i=!1)}if(i)return A;if(A.children)for(const I of A.children){const o=this.findAvatarPart(I,e);if(o)return o}return null}handleCustomAvatarErrors(A){if(!A.ok)throw Error(A.statusText);return A}}const vQ=CA("debugflags");var lg=(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))(lg||{});const nY=class{constructor(){r(this,"Mask",17)}Has(t){return(this.Mask&t)!==0}Set(t){vQ&&console.warn("Set XR flag state to",t),this.Mask=t,ji.Apply()}Enable(t){this.Mask|=t,ji.Apply()}Disable(t){this.Mask&=~t,ji.Apply()}Toggle(t){this.Mask^=t,ji.Apply()}EnableAll(){this.Mask=-1,ji.Apply()}DisableAll(){this.Mask=0,ji.Apply()}};let DC=nY;r(DC,"Global",new nY);const Fs=class extends RA{constructor(){super(...arguments),r(this,"visibleIn")}static Apply(){for(const t of this.registry)t.UpdateVisible(DC.Global)}awake(){Fs.registry.push(this)}onEnable(){Fs.firstApply?this.UpdateVisible(DC.Global):(Fs.firstApply=!0,Fs.Apply())}onDestroy(){const t=Fs.registry.indexOf(this);t>=0&&Fs.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),vQ&&console.log(e),Fs.buffer.Mask=e,t=Fs.buffer);const g=t;if(g?(vQ&&console.warn(this.name,"use passed in mask",g.Mask,this.visibleIn),A=g.Has(this.visibleIn)):(vQ&&console.log(this.name,"use global mask"),DC.Global.Has(this.visibleIn)),A!==void 0)if(A)vQ&&console.log(this.name,"is visible",this.gameObject.uuid),eA.setActive(this.gameObject,!0);else{if(vQ&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}};let ji=Fs;r(ji,"registry",[]),r(ji,"firstApply"),r(ji,"buffer",new DC);const gn=CA("debugavatar"),wC=class extends RA{constructor(){super(...arguments),r(this,"connectionId"),r(this,"avatar")}static getAvatar(t){return t>=0&&t<wC.instances.length?wC.instances[t]:null}static onAvatarMarkerCreated(t){return wC._onNewAvatarMarkerAdded.push(t),t}static onAvatarMarkerDestroyed(t){return wC._onAvatarMarkerDestroyed.push(t),t}awake(){wC.instances.push(this),gn&&console.log(this);for(const t of wC._onNewAvatarMarkerAdded)t({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){wC.instances.splice(wC.instances.indexOf(this),1);for(const t of wC._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):eA.setActive(this.avatar,t))}};let fi=wC;r(fi,"instances",[]),r(fi,"_onNewAvatarMarkerAdded",[]),r(fi,"_onAvatarMarkerDestroyed",[]);const zD=class{constructor(t,A,e){r(this,"_isVisible",!0),r(this,"guid"),r(this,"root",null),r(this,"head",null),r(this,"handLeft",null),r(this,"handRight",null),r(this,"lastUpdate",-1),r(this,"isLocalAvatar",!1),r(this,"flags",null),r(this,"headScale",new f(1,1,1)),r(this,"handLeftScale",new f(1,1,1)),r(this,"handRightScale",new f(1,1,1)),r(this,"webxr"),r(this,"lastAvatarId",null),r(this,"hasAvatarOverride",!1),r(this,"context"),r(this,"avatarMarker",null),r(this,"_headTarget",new UA),r(this,"_handLeftTarget",new UA),r(this,"_handRightTarget",new UA),r(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?lg.FirstPerson:lg.ThirdPerson;this.context.isInVR?t|=lg.VR:this.context.isInAR?t|=lg.AR:t|=lg.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?QC.Handheld:QC.Headset;let g=this.head;this.context.players.setPlayerView(t.guid,g,e),pI.markDirty(this.head),this._canInterpolate=!0;const i=this.isLocalAvatar?this.head:this._headTarget;if(i.position.set(t.position.x,t.position.y,t.position.z),i.quaternion.set(t.rotation.x,t.rotation.y,t.rotation.z,t.rotation.w),i.scale.set(t.scale,t.scale,t.scale),i.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(zD.invertRotation),I.scale.set(t.scale,t.scale,t.scale),I.scale.multiply(this.handLeftScale),pI.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(zD.invertRotation),I.scale.set(t.scale,t.scale,t.scale),I.scale.multiply(this.handRightScale),pI.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;gn&&console.log("Destroy avatar",this.guid),(t=this.root)==null||t.removeFromParent(),(A=this.avatarMarker)==null||A.destroy(),this.lastAvatarId=null,this.head&&Wi.Remove(this.context,this.head)}updateVisibility(){const t=this.root;t&&eA.setActive(t,this._isVisible)}async setupCustomAvatar(t){var A,e,g;if(gn&&console.log("LOAD",t,this),!t||typeof t=="string"&&t.length<=0)return!1;this.head&&Wi.Remove(this.context,this.head);const i=t;if(i?.loadAssetAsync!==void 0){await i.loadAssetAsync();const o=i.asset;eA.setActive(o,!1),t=eA.instantiate(o),eA.setActive(t,!0)}gn&&console.log(t);const I=await zD.loader.getOrCreateNewAvatarInstance(this.context,t);if(gn&&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=eA.addNewComponent(this.root,fi),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&&Wi.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&&((g=this.handRight)==null||g.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(...eA.getComponentsInChildren(this.root,ji)),this.flags.length<=0&&this.head){const o=eA.addNewComponent(this.head,ji);o.visibleIn=lg.ThirdPerson|lg.VR,this.flags.push(o),gn&&console.log("Added flag to head: "+o.visibleIn,this.head.name)}return gn&&console.log("[Avatar], is Local? ",this.isLocalAvatar,this.root),this.updateFlags(),this.updateVisibility(),!0}else return gn&&console.warn("build avatar failed"),!1}};let In=zD;r(In,"loader",new VD),r(In,"invertRotation",new mA().setFromAxisAngle(new f(0,1,0),Math.PI));class Wi{static Add(A,e,g=null){if(e){for(const i of this.Pois)if(i.obj===e)return;this.Pois.push({obj:e,avatar:g}),this.LastChangeTime=A.time.time}}static Remove(A,e){var g;if(e){for(const i of this.Pois)if(i.obj===e){this.Pois.splice(this.Pois.indexOf(i),1),this.LastChangeTime=A?.time.time??((g=be.Current)==null?void 0:g.time.time);return}}}}r(Wi,"Pois",[]),r(Wi,"LastChangeTime",0);class I7{constructor(){r(this,"guid"),r(this,"position",new f)}}class vc extends RA{constructor(){super(...arguments),r(this,"target",null),r(this,"avatar",null),r(this,"_model",null),r(this,"_targetModel",new I7),r(this,"_currentTargetObject",null),r(this,"_lastUpdateTime",0),r(this,"_lookDuration",0),r(this,"_lastPoiChangedTime",0)}set controlledTarget(A){this.target=A;const e=T.get("MoveRandom");if(e&&this.target){const g=eA.getComponent(this.target,e);g&&g.destroy()}}awake(){if(this.avatar=eA.getComponentInParent(this.gameObject,fi),this.avatar){const A=eA.getComponentInParent(this.gameObject,fi);this._model=new Hu(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)&&gg(this.target,A.position)})}update(){var A;if((!this.context.connection.isConnected||(A=this._model)!=null&&A.hasOwnership)&&(Wi.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=Wi.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){const e=we(this._currentTargetObject);gg(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=Wi.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 bQ extends RA{constructor(){super(...arguments),r(this,"canGrab",!0)}onPointerClick(A){}}class LQ extends RA{constructor(){super(...arguments),r(this,"isUsed",!0),r(this,"usedBy",null)}}var yC=(t=>(t[t.Average=0]="Average",t[t.Multiply=1]="Multiply",t[t.Minimum=2]="Minimum",t[t.Maximum=3]="Maximum",t))(yC||{}),ZD=(t=>(t[t.Discrete=0]="Discrete",t[t.Continuous=1]="Continuous",t))(ZD||{}),og=(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))(og||{}),xQ=(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))(xQ||{});const RI=function(t,A){return function(e,g,i){o7(e,g,i,t,A)}};function o7(t,A,e,g,i){if(!(!i&&!g&&!t.onValidate)){if(e!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",t,A,e),Qg("Invalid usage of validate decorator. Only fields can be validated. Property: "+A,ko.Error);return}if(t.__internalAwake){const I=Symbol(A),o=t.__internalAwake;t.__internalAwake=function(){this[I]===void 0&&(this[I]=this[A],Object.defineProperty(this,A,{set:function(C){var s;if(this[ik]===!0)this[I]=C;else{g?.call(this,C);const a=this[I];this[I]=C,(s=this.onValidate)==null||s.call(this,A,a)}},get:function(){return i?.call(this),this[I]}})),o.call(this)}}}}const C7=function(t){return function(A,e,g){const i=t.prototype,I=Object.getOwnPropertyDescriptor(i,e);if(!(I!=null&&I.value)){console.warn("Can not apply prefix: type does not have method named",e,t);return}const o=I.value,C=A[e];Object.defineProperty(i,e,{value:function(...s){const a=C?.call(this,...s);if(a instanceof Promise){a.then(n=>{if(n!==!1)return o.call(this,...s)});return}if(a!==!1)return o.call(this,...s)}})}};var s7=Object.defineProperty,a7=Object.getOwnPropertyDescriptor,Ns=(t,A,e,g)=>{for(var i=g>1?void 0:g?a7(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&s7(A,e,i),i};class n7{constructor(A,e){r(this,"positionChanged",!1),r(this,"rotationChanged",!1),r(this,"position"),r(this,"quaternion"),r(this,"_positionKeys",["x","y","z"]),r(this,"_quaternionKeys",["_x","_y","_z","_w"]),r(this,"mute",!1),r(this,"context"),r(this,"obj"),r(this,"_positionWatch"),r(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 JE(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((I,o)=>{var C;if((C=this.context.physics.engine)!=null&&C.isUpdating||this.mute)return;const s=this.position[o];Math.abs(s-I)<1e-5||(this.position[o]=I,this.positionChanged=!0)})),e&&(this._rotationWatch||(this._rotationWatch=new JE(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((I,o)=>{var C;if((C=this.context.physics.engine)!=null&&C.isUpdating||this.mute)return;const s=this.quaternion[o];Math.abs(s-I)<1e-5||(this.quaternion[o]=I,this.rotationChanged=!0)}));const g=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),i=new KA;this.obj.matrixWorld.multiplyMatrices=(I,o)=>(i.equals(I)||(this.positionChanged=!0,this.rotationChanged=!0,i.copy(I)),g(I,o))}stop(){var A,e;(A=this._positionWatch)==null||A.revoke(),(e=this._rotationWatch)==null||e.revoke()}}var pm;const um=(pm=class extends RA{constructor(){super(...arguments),r(this,"mass",1),r(this,"useGravity",!0),r(this,"constraints",og.None),r(this,"isKinematic",!1),r(this,"drag",0),r(this,"angularDrag",1),r(this,"detectCollisions",!0),r(this,"sleepThreshold",.01),r(this,"collisionDetectionMode",ZD.Discrete),r(this,"_gravityScale",1),r(this,"_propertiesChanged",!1),r(this,"_currentVelocity",new f),r(this,"_smoothedVelocity",new f),r(this,"_smoothedVelocityGetter",new f),r(this,"_lastPosition",new f),r(this,"_watch")}get lockPositionX(){return(this.constraints&og.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&og.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&og.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&og.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&og.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&og.FreezeRotationZ)!==0}set lockPositionX(t){t?this.constraints|=og.FreezePositionX:this.constraints&=~og.FreezePositionX}set lockPositionY(t){t?this.constraints|=og.FreezePositionY:this.constraints&=~og.FreezePositionY}set lockPositionZ(t){t?this.constraints|=og.FreezePositionZ:this.constraints&=~og.FreezePositionZ}set lockRotationX(t){t?this.constraints|=og.FreezeRotationX:this.constraints&=~og.FreezeRotationX}set lockRotationY(t){t?this.constraints|=og.FreezeRotationY:this.constraints&=~og.FreezeRotationY}set lockRotationZ(t){t?this.constraints|=og.FreezeRotationZ:this.constraints&=~og.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 n7(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),MI.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,g;;)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()):(g=this._watch)==null||g.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(){var t;(t=this.context.physics.engine)==null||t.resetForces(this,!0)}resetTorques(){var t;(t=this.context.physics.engine)==null||t.resetTorques(this,!0)}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){var e;(e=this.context.physics.engine)==null||e.addForce(this,t,!0)}applyImpulse(t){var A;(A=this.context.physics.engine)==null||A.applyImpulse(this,t,!0)}setForce(t,A,e){var g,i;(g=this.context.physics.engine)==null||g.resetForces(this,!0),(i=this.context.physics.engine)==null||i.addForce(this,{x:t,y:A,z:e},!0)}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){var g,i;if(t instanceof f){const I=t;(g=this.context.physics.engine)==null||g.setLinearVelocity(this,I,!0);return}A===void 0||e===void 0||(i=this.context.physics.engine)==null||i.setLinearVelocity(this,{x:t,y:A,z:e},!0)}setAngularVelocity(t,A,e){var g,i;if(t instanceof f){const I=t;(g=this.context.physics.engine)==null||g.setAngularVelocity(this,I,!0);return}A===void 0||e===void 0||(i=this.context.physics.engine)==null||i.setAngularVelocity(this,{x:t,y:A,z:e},!0)}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)}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=we(this.gameObject);um.tempPosition.copy(t);const A=t.sub(this._lastPosition);this._lastPosition.copy(um.tempPosition),this._smoothedVelocity.lerp(A,this.context.time.deltaTime/.1)}},r(pm,"tempPosition",new f),pm);let _t=um;Ns([RI(),w()],_t.prototype,"mass",2),Ns([RI(),w()],_t.prototype,"useGravity",2),Ns([RI(),w()],_t.prototype,"constraints",2),Ns([RI(),w()],_t.prototype,"isKinematic",2),Ns([RI(),w()],_t.prototype,"drag",2),Ns([RI(),w()],_t.prototype,"angularDrag",2),Ns([RI(),w()],_t.prototype,"detectCollisions",2),Ns([RI(),w()],_t.prototype,"sleepThreshold",2),Ns([RI(),w()],_t.prototype,"collisionDetectionMode",2);class UI{constructor(){r(this,"bb",null),r(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,g,i){return A.prep(4,12),A.writeFloat32(i),A.writeFloat32(g),A.writeFloat32(e),A.offset()}}class rY{constructor(){r(this,"bb",null),r(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}position(A){return(A||new UI).__init(this.bb_pos,this.bb)}rotation(A){return(A||new UI).__init(this.bb_pos+12,this.bb)}scale(A){return(A||new UI).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(A,e,g,i,I,o,C,s,a,n){return A.prep(4,36),A.prep(4,12),A.writeFloat32(n),A.writeFloat32(a),A.writeFloat32(s),A.prep(4,12),A.writeFloat32(C),A.writeFloat32(o),A.writeFloat32(I),A.prep(4,12),A.writeFloat32(i),A.writeFloat32(g),A.writeFloat32(e),A.offset()}}class Ca{constructor(){r(this,"bb",null),r(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}static getRootAsSyncedTransformModel(A,e){return(e||new Ca).__init(A.readInt32(A.position())+A.position(),A)}static getSizePrefixedRootAsSyncedTransformModel(A,e){return A.setPosition(A.position()+Mu),(e||new Ca).__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 rY).__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 on=CA("debugsync"),bc="STRS";Bk(bc,Ca.getRootAsSyncedTransformModel);const SC=new xE;function BY(t,A,e=!0){SC.clear();const g=SC.createString(t);Ca.startSyncedTransformModel(SC),Ca.addGuid(SC,g),Ca.addFast(SC,e);const i=A.worldPosition,I=A.worldEuler,o=A.gameObject.scale;Ca.addTransform(SC,rY.createTransform(SC,i.x,i.y,i.z,I.x,I.y,I.z,o.x,o.y,o.z));const C=Ca.endSyncedTransformModel(SC);return SC.finish(C,bc),SC.asUint8Array()}class Cn extends RA{constructor(){super(...arguments),r(this,"overridePhysics",!0),r(this,"interpolatePosition",!0),r(this,"interpolateRotation",!0),r(this,"fastMode",!1),r(this,"syncDestroy",!1),r(this,"_model",null),r(this,"_needsUpdate",!0),r(this,"rb",null),r(this,"_wasKinematic",!1),r(this,"_receivedDataBefore",!1),r(this,"_targetPosition"),r(this,"_targetRotation"),r(this,"_receivedFastUpdate",!1),r(this,"_shouldRequestOwnership",!1),r(this,"joinedRoomCallback",null),r(this,"receivedDataCallback",null),r(this,"tempEuler",new mg),r(this,"receivedUpdate",!1),r(this,"lastWorldPos"),r(this,"lastWorldRotation")}requestOwnership(){on&&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(){on&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new f,this._targetRotation=new mA,this.lastWorldPos=new f,this.lastWorldRotation=new mA,this.rb=eA.getComponentInChildren(this.gameObject,_t),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new Hu(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(Wt.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(bc,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&hv(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(Wt.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(bc,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){on&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,A),this.receivedUpdate=!0,this._receivedFastUpdate=A.fast();const g=A.transform();if(g){pI.markDirty(this.gameObject,!0);const i=g.position();i&&(this.interpolatePosition&&((e=this._targetPosition)==null||e.set(i.x(),i.y(),i.z())),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(i.x(),i.y(),i.z()));const I=g.rotation();I&&(this.tempEuler.set(I.x(),I.y(),I.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&UJ(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){on&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());let A=this.worldPosition,e=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){const I=A.distanceTo(this.lastWorldPos),o=e.angleTo(this.lastWorldRotation),C=this._model.hasOwnership||this.fastMode?1e-4:.001;(I>C||o>C)&&(this._model.hasOwnership?this._needsUpdate=!0:(on&&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),pI.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 C=this.worldPosition;C.lerp(this._targetPosition,I),this.worldPosition=C,o=!0}if(this.interpolateRotation&&this._targetRotation){const C=this.worldQuaternion;C.slerp(this._targetRotation,I),this.worldQuaternion=C,o=!0}o&&pI.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&&(on&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic),this.gameObject.position.distanceTo(new f(0,0,0))>1e3&&(on&&console.log("RESET",this.name),this.gameObject.position.set(0,1,0),this.rb.setVelocity(0,0,0)));const g=10,i=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%g===0||i)){on&&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=BY(this.guid,this,!!i);this.context.connection.sendBinary(I)}}}var Oo={};Oo.d=(t,A)=>{for(var e in A)Oo.o(A,e)&&!Oo.o(t,e)&&Object.defineProperty(t,e,{enumerable:!0,get:A[e]})},Oo.o=(t,A)=>Object.prototype.hasOwnProperty.call(t,A),Oo.r=t=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var dg={};Oo.d(dg,{w8:()=>Qt,cg:()=>HH,gO:()=>Ud,wb:()=>Dm,zV:()=>Gr,HS:()=>Lc,Ec:()=>kr,gF:()=>jE,ol:()=>Nd,pz:()=>mY,tx:()=>So,hj:()=>wm,FV:()=>jc,sV:()=>uH,xv:()=>Fd,mx:()=>fY,gE:()=>kY,ZP:()=>$eA,Vx:()=>TH});var Dm={};Oo.r(Dm),Oo.d(Dm,{get:()=>QY,set:()=>r7});var wm={};Oo.r(wm),Oo.d(wm,{alphaTestTransformer:()=>tw,asPreprocessorValueTransformer:()=>MY,toPreprocessorTriggerTransformer:()=>Jm,toUserDataTransformer:()=>D$,uniformOrUserDataTransformer:()=>ro});const ym={fontFamily:null,fontSize:.05,fontKerning:"normal",fontStyle:"normal",fontWeight:"400",offset:.005,lineHeight:1.2,lineBreak:`- ,.:?!
|
|
4180
4180
|
`,whiteSpace:"pre-line",flexDirection:"column",justifyContent:"start",alignItems:"start",backgroundImage:null,textAlign:"left",boxSizing:"content-box",position:"static",color:16777215,fontColor:16777215,fontOpacity:1,opacity:1,fontPXRange:4,fontSupersampling:!0,fontSmooth:"antialiased",borderRadius:0,borderWidth:0,borderColor:"black",borderOpacity:1,backgroundSize:"cover",backgroundColor:0,backgroundOpacity:0,overflow:"visible",letterSpacing:0,invertAlpha:!1,segments:1},r7=function(t){for(const A in t)ym[A]=t[A]},QY=function(t){return Object.prototype.hasOwnProperty.call(ym,t)||console.warn(`ThreeMeshUI::DefaultValues is trying to retrieve non-existing property '${t}'`),ym[t]};class Qt{constructor(A,e=null,g=!0){this._id=A,this._value=e,this._needsUpdate=!0,this._needsProcess=!1,this._needsRender=!1,this._isPrimitive=g}get id(){return this._id}get value(){return this._value}set value(A){this.isValid(A)&&this._value!==A&&(this._value=A,this._needsUpdate=!0)}update(A,e){this.output(e)}output(A){}_outputValue(A){A[this._id]=this._value}process(A){}render(A){}getInheritedInput(A){if(this._value!=="inherit")return this._value;const e=A._parent._value;return e&&e[`_${this._id}`]?e[`_${this._id}`].getInheritedInput(e):this.getDefaultValue()}getDefaultValue(){return QY(this._id)}isValid(A){return!0}emptyStrategyLogic(){throw new Error(`ThreeMeshUI::${this.constructor.name} has empty strategy. Update has not been processed.`)}requestUpdate(){this._needsUpdate=!0}requestProcess(){this._needsProcess=!1}requestRender(){this._needsRender=!1}}class B7 extends Qt{constructor(){super("renderOrder","auto",!0),this.output=this._outputValue,this._actualValue=0}set value(A){this.isValid(A)&&(this._value=A,this._needsUpdate=!0)}update(A,e){if(this._value!=="auto")this._actualValue=this._value;else{const g=A._parent._value;if(g!==null){const i=g._renderOrder._actualValue,I=1+g._children._uis.indexOf(A);this._actualValue=i+I}}for(const g of A._children._uis)g._renderOrder._value==="auto"&&(g._renderOrder._needsUpdate=!0);this._outputValue(e)}_outputValue(A){A[this._id]=this._actualValue}get value(){return this._value}}class kr extends Qt{constructor(A,e=null,g=!0){super(A,e,g),this.output=this._outputValue,this._notInheritedValue=null}update(A,e){this._notInheritedValue=this._value,this._notInheritedValue==="inherit"&&(this._notInheritedValue=this.getInheritedInput(A)),this.propagate(A),this._outputValue(e)}propagate(A){for(const e of A._children._uis){const g=e[`_${this._id}`];g!==void 0&&g._value==="inherit"&&(e[`_${this._id}`]._needsUpdate=!0)}}_outputValue(A){A[this._id]=this._notInheritedValue}set value(A){this.isValid(A)&&this._value!==A&&(this._value=A,this._needsUpdate=!0)}get value(){return this._value==="inherit"?this._notInheritedValue:this._value}}class Q7 extends kr{constructor(){super("offset","inherit",!1)}update(A,e){super.update(A,e),A._parent._value!==null&&(A.position.z=this._notInheritedValue)}}class E7 extends kr{constructor(){super("fontSmooth","inherit",!0),this._needsUpdate=!1,this.isValid=c7,this.output=this._outputValue}}const h7=["inherit","none","antialiased"];function c7(t){return h7.indexOf(t)===-1?(console.warn(`.fontSmoothing value '${t}' is not valid. Aborted`),!1):!0}var l7=t=>{var A={};return Oo.d(A,t),A};const XA=l7({BackSide:()=>Mg,BufferAttribute:()=>ge,BufferGeometry:()=>le,Color:()=>SA,DoubleSide:()=>ft,EventDispatcher:()=>Ug,FileLoader:()=>Jg,FrontSide:()=>Ni,LinearFilter:()=>Ne,Mesh:()=>DA,Object3D:()=>UA,Plane:()=>VI,PlaneGeometry:()=>Zg,ShaderMaterial:()=>Ke,Texture:()=>Le,TextureLoader:()=>Ma,Vector2:()=>W,Vector3:()=>f,Vector4:()=>Ie});class qt extends Qt{constructor(A,e,g=!0){super(A,"unset",g),this._input="inherit",this._allowsInherit=!0,this._inheritedInput=void 0,this._inline=void 0}update(A,e){this._allowsInherit||(this._inheritedInput=this.getInheritedInput(A)),this.computeOutputValue(A);for(const g of A._children._uis){const i=g[`_${this._id}`];(i._input?i._input:i._value)==="inherit"&&(g[`_${this._id}`]._needsUpdate=!0)}this.output(e)}computeOutputValue(A){this._value=this._input}_computeFromInherited(A){this._value=this._inheritedInput}set value(A){console.warn(".(style) sub-property cannot be directly set. It must comes from inline or computed setter.")}set inline(A){this.isValidValue(A)&&A!==this._inline&&(this._input=this._inline=A,this._needsUpdate=!0)}get inline(){return this._inline}isValidValue(A){return!0}getInheritedInput(A){if(this._input!=="inherit")return this._input;const e=A._parent._value;return e?e[`_${this._id}`].getInheritedInput(e):this.getDefaultValue()}}class XD extends qt{constructor(A,e){super(A,e,!1),this._input=new XA.Vector4(0,0,0,0),this._inline=null,this._value=new XA.Vector4(0,0,0,0)}get value(){return this._value}computeOutputValue(A){this._vector4ValueSetter(this._value,this._input)}set inline(A){this._vector4ValueSetter(this._input,A),!this._input.equals(this._value)&&(this._needsUpdate=!0)}set top(A){this._input.x!==A&&(this._input.x=A,this._needsUpdate=!0)}get top(){return this._input.x}set right(A){this._input.y!==A&&(this._input.y=A,this._needsUpdate=!0)}get right(){return this._input.y}set bottom(A){this._input.z!==A&&(this._input.z=A,this._needsUpdate=!0)}get bottom(){return this._input.z}set left(A){this._input.w!==A&&(this._input.w=A,this._needsUpdate=!0)}get left(){return this._input.w}dispose(){this._computed=null,this._inline=null,this._input=null,this._output=null}_vector4ValueSetter(A,e){if(e instanceof XA.Vector4){A.copy(e);return}if((typeof e=="string"||e instanceof String)&&(e=e.split(" ")),Array.isArray(e))switch(e=e.map(g=>parseFloat(g)),e.length){case 1:A.setScalar(e[0]);return;case 2:A.x=A.z=e[0],A.y=A.w=e[1];return;case 3:A.x=e[0],A.y=e[1],A.z=e[2];return;case 4:A.x=e[0],A.y=e[1],A.z=e[2],A.w=e[3];return;default:console.error("StyleVector4Property::set() Four Dimension property had more than four values");return}isNaN(e)||A.setScalar(e)}}class d7 extends XD{constructor(){super("padding",new XA.Vector4(0,0,0,0))}computeOutputValue(A){super.computeOutputValue(A),A._bounds._needsUpdate=!0,A._bounds._needsRender=!0,A._layouter._needsProcess=!0,A._renderer._needsRender=!0,A._parent._value&&(A._parent._value._layouter._needsProcess=!0)}}class p7 extends XD{constructor(){super("margin",new XA.Vector4(0,0,0,0))}computeOutputValue(A){super.computeOutputValue(A),A._renderer._needsRender=!0,A._parent._value&&(A._parent._value._flexDirection._needsProcess=!0)}}const EY=function(t,A,e){t[A]=e},u7=function(t,A,e){e!==null&&(t[A]=e)};class $D{constructor(A){this._definition=A}set definition(A){this._definition=A}mediate(A,e,g,i=null){for(const I in this._definition){const o=this._definition[I];if(g[I]!==void 0){const C=o.t?o.t:EY;C(e,o.m,g[I]),i&&C(i,o.m,g[I])}}}static mediate(A,e,g,i,I=null){if(e)for(const o in i){const C=i[o];if(g[o]!==void 0){const s=C.t?C.t:EY;s(e,C.m,g[o]),I&&s(I,C.m,g[o])}}}}class D7 extends Qt{constructor(){super("parent",null,!1)}update(A,e){A.parent&&A.parent.isUI?this._value=A.parent:this._value=null}set value(A){console.warn("ParentProperty is readonly")}get value(){return this._value}find(A){return this._value?A(this._value)?this._value:this._value._parent.find(A):null}dispose(){this._value=null}}const Sm=function(t,A,e=6){return t.toFixed(e)===A.toFixed(e)};class hY extends Qt{constructor(A,e){super(A,e,!0),this.output=this._outputValue}set value(A){this.isValid(A)&&(Sm(this._value,A)||(this._value=A,this._needsUpdate=!0))}get value(){return this._value}}class cY extends kr{constructor(A){super(A,"inherit",!0),this.isValid=y7}}const w7=[XA.FrontSide,XA.BackSide,XA.DoubleSide];function y7(t){return w7.indexOf(t)===-1?(console.warn(`SideProperty value '${t}' is not valid. Abort`),!1):!0}class S7 extends XA.EventDispatcher{constructor(A,e){super(),this._isReady=!1,this._weight=A,this._style=e,this._size=42,this._lineHeight=42,this._lineBase=42,this._font=null}get typographic(){return this._font}get isReady(){return this._isReady}get weight(){return this._weight}get style(){return this._style}get texture(){return this._texture}set fontMaterial(A){throw Error(`FontVariant('${this.id}')::fontMaterial - is abstract.`)}get fontMaterial(){throw Error(`FontVariant('${this.id}')::fontMaterial - is abstract.`)}get id(){return`${this._name}(w:${this.weight},s:${this.style})`}getTypographicGlyph(A){let e=this._chars[A];if(e)return e;if(A.match(/\s/))return this._chars[" "];const g=this._getFallbackCharacter(A);if(g&&(e=this._chars[g],e))return e;throw Error(`FontVariant('${this.id}')::getTypographicGlyph() - character('${A}') and/or fallback character were not found in provided msdf charset.`)}_getFallbackCharacter(A){throw new Error(`FontVariant(${typeof this})::_getFallbackCharacter() is abstract and should therefore be overridden.`)}getGeometricGlyph(A,e){throw new Error(`FontVariant(${typeof this})::getGeometryCharacter() is abstract and should therefore be overridden.`)}getKerningAmount(A){return this._kernings[A]?this._kernings[A]:0}adjustTypographicGlyphs(A){for(const e in A){const g=this.getTypographicGlyph(e),i=A[e];for(const I in i)g["_"+I]=A[e][I]}}_checkReadiness(){this._readyCondition()&&k7(this)}_alterElementProperties(A){throw new Error(`FontVariant(${typeof this})::_alterElementProperties() is abstract and should therefore be overridden.`)}_readyCondition(){throw new Error(`FontVariant(${typeof this})::_readyCondition() is abstract and should therefore be overridden.`)}}const f7={type:"ready"};function k7(t){t._isReady=!0,t.dispatchEvent(f7)}const Lc=S7;class G7 extends Qt{constructor(A=null){super("font",A,!1),this._needsUpdate=!1,this._fontVariant=null,this._handleFontReadyClosure=null,this.isValid=m7}output(A){A[this._id]=this._fontVariant}update(A,e){if(this._fontVariant&&!this._fontVariant.isReady&&this._fontVariant.removeEventListener("ready",this._handleFontReadyClosure),this._value&&this._value instanceof Lc)this._fontVariant=this._value;else{const g=A._fontFamily._value;g&&(this._fontVariant=g.getVariant(A._fontWeight._value,A._fontStyle._value))}this._fontVariant&&(this._fontVariant._alterElementProperties(A),this._handleFontReadyClosure=M7(A,this),this._fontVariant.isReady?this._handleFontReadyClosure():this._fontVariant.addEventListener("ready",this._handleFontReadyClosure),(!A._fontMaterial._defaultMaterial||!(A._fontMaterial._defaultMaterial instanceof this._fontVariant.fontMaterial))&&(A._fontMaterial._defaultMaterial=new this._fontVariant.fontMaterial,A._fontMaterial._needsUpdate=!0))}set value(A){this.isValid(A)&&this._value!==A&&(this._value=A,this._needsUpdate=!0)}get value(){return this._value}get fontVariant(){return this._fontVariant}dispose(){this._handleFontReadyClosure&&(this._fontVariant.removeEventListener("ready",this._handleFontReadyClosure),this._handleFontReadyClosure=null),this._value=null,this._fontVariant=null}}function m7(t){return t instanceof Lc?!0:(console.warn(`.font value '${t}' is not valid. It requires a FontVariant instance. Aborted`),!1)}function M7(t,A){return function(){A._needsUpdate=!0,t._glyphs._needsProcess=!0,A._fontVariant.removeEventListener("ready",A._handleFontReadyClosure),A._handleFontReadyClosure=null}}class R7 extends qt{constructor(A){super("display",A),this._value="flex",this._allowsInherit=!1,this._needsUpdate=!1,this.isValidValue=F7}computeOutputValue(A){A._visible._value=this._output!=="none"}}const U7=["none","flex"];function F7(t){return U7.indexOf(t)===-1?(console.warn(`(.style) display value '${t}' is not valid. Aborted`),!1):!0}class N7 extends qt{constructor(A){super("boxSizing",A),this._allowsInherit=!1,this.isValidValue=J7}computeOutputValue(A){this._value=this._inheritedInput,A._bounds._needsUpdate=!0}}const K7=["border-box","content-box"];function J7(t){return K7.indexOf(t)===-1?(console.warn(`(.style) boxSizing value '${t}' is not valid. Aborted`),!1):!0}class xc extends qt{constructor(A,e){super(A,e,!1),this._value=new XA.Color,this.output=this._outputValue}computeOutputValue(A){this._input!=="inherit"&&this._value.set(this._input)}set inline(A){this._input=this._inline=A,this._needsUpdate=!0}}class fm extends qt{constructor(A,e){super(A,e,!0),this.isValidValue=q7,this._allowsInherit=!1,this._input=e,this._value=e,this.output=this._outputValue,this.computeOutputValue=this._computeFromInherited}_outputValue(A){A[this._id]=this._inheritedInput}}function q7(t){return t<0&&t>1?(console.warn(`(.style) styleFactorProperty('${this.id}') value '${t}' is not valid)`),!1):!0}class v7 extends qt{constructor(A){super("backgroundImage",A,!0),this._input=null,this._allowsInherit=!1,this._textureSize=new XA.Vector2(1,1),this.isValidValue=b7}get value(){return this._value}output(A){A[this._id]=this._value,A.tSize=this._textureSize}computeOutputValue(A){if(this._value=this._inheritedInput,this._value instanceof XA.Texture&&!this._value.image){console.warn("ThreeMeshUI - .backgroundImage :: Please provide preloaded texture in order to have accurate sizing.");return}this._needsProcess=!0}process(A){this._value?this._textureSize.set(this._value.image.width,this._value.image.height):this._textureSize.set(1,1)}}function b7(t){return!0}class L7 extends qt{constructor(A){super("backgroundSize",A,!0),this.isValidValue=Y7,this.output=this._outputValue}}const x7=["cover","contain","stretch"];function Y7(t){return x7.indexOf(t)===-1?(console.warn(`(.style) backgroundSize value '${t}' is not valid. Aborted`),!1):!0}class H7 extends qt{constructor(A){super("overflow",A,!0),this.isValidValue=O7,this._clippingPlanes=null,this._renderStrategy=this._emptyRender}update(A,e){this._inline!==void 0&&this._inline!=="unset"?this._input=this._inline:this._computed!==void 0&&(this._input=this._computed),this._allowsInherit||(this._inheritedInput=this.getInheritedInput(A)),this.computeOutputValue(A);for(const g of A._children._uis)g._overflow._needsUpdate=!0;this.output(e)}output(A){A.clippingPlanes=this._clippingPlanes}computeOutputValue(A){super.computeOutputValue(A),this._value==="hidden"?this._renderStrategy=this._propagateRender:(this._renderStrategy=this._emptyRender,this._clippingPlanes=null);const e=A._parent._value;if(e!==null){const g=e._overflow;if((g._value==="hidden"||g._clippingPlanes!==null)&&!this._clippingPlanes){this._clippingPlanes=[new XA.Plane(new XA.Vector3(0,-1,0),1),new XA.Plane(new XA.Vector3(-1,0,0),1),new XA.Plane(new XA.Vector3(0,1,0),1),new XA.Plane(new XA.Vector3(1,0,0),1)];for(let i=0;i<this._clippingPlanes.length;i++)this._clippingPlanes[i].parent=e;g._clippingPlanes!==null&&this._clippingPlanes.push(...g._clippingPlanes),this._renderStrategy=this._hiddenRender,this._needsRender=!0}else(g._value==="visible"||g._clippingPlanes===null)&&this._clippingPlanes!==null&&(this._clippingPlanes=null,this._renderStrategy=this._emptyRender,this._needsRender=!0)}}render(A){this._renderStrategy(A)}_emptyRender(A){}_hiddenRender(A){const e=A._parent._value,g=e._bounds._offsetHeight,i=e._bounds._offsetWidth,I=e._padding._value,o=e._borderWidth._value;for(let C=0;C<4&&C<this._clippingPlanes.length;C++){const s=this._clippingPlanes[C];switch(C%4){case 0:s.constant=g/2-(I.x+o.x);break;case 1:s.constant=i/2-(I.y+o.y);break;case 2:s.constant=g/2-(I.z+o.z);break;case 3:s.constant=i/2-(I.w+o.w);break}s.applyMatrix4(e.matrixWorld)}for(let C=0;C<A._children._uis.length;C++){const s=A._children._uis[C];s._overflow._needsRender=!0}}_propagateRender(A){for(let e=0;e<A._children._uis.length;e++){const g=A._children._uis[e];g._overflow._needsRender=!0}}}const T7=["visible","hidden"];function O7(t){return T7.indexOf(t)===-1?(console.warn(`(.style) overflow value '${t}' is not valid. Aborted`),!1):!0}const YQ="rem",lY="em",Aw="%",_7=[YQ,lY,Aw],dY=function(t){return _7.indexOf(t)===-1?YQ:t};class P7 extends XD{constructor(A){super("borderRadius",A),this._valueUV=this._value.clone(),this._input=new XA.Vector4(0,0,0,0),this._mediation=!0,this._cornerTL=new XA.Vector2(0,1),this._cornerTR=new XA.Vector2(1,1),this._cornerBR=new XA.Vector2(1,0),this._cornerBL=new XA.Vector2(0,0);const e=new ew(this._valueUV,["x","y"]),g=new ew(this._valueUV,["z","w"]),i=new ew(this._valueUV,["x","w"]),I=new ew(this._valueUV,["y","z"]);e.complementaryMediation=g,g.complementaryMediation=e,i.complementaryMediation=I,I.complementaryMediation=i,this._sideMediators=[e,g,i,I],this._units=YQ}set units(A){this._units=dY(A),this._needsProcess=!0}get units(){return this._units}set mediation(A){A!==this._mediation&&(this._mediation=A,this._needsUpdate=!0)}get mediation(){return this._mediation}output(A){A.cornerTL=this._cornerTL,A.cornerTR=this._cornerTR,A.cornerBR=this._cornerBR,A.cornerBL=this._cornerBL}computeOutputValue(A){this._vector4ValueSetter(this._value,this._input),this._needsProcess=!0}process(A){this._needsRender=!0}render(A){this._valueUV.copy(this._value);const e=A._bounds._offsetWidth,g=A._bounds._offsetHeight;if(this._units===Aw&&this._valueUV.divideScalar(100),this._units===YQ&&this._valueUV.divideScalar(Math.min(e,g)),this._mediation)do this._sideMediators.forEach(o=>o.computeValue()),this._sideMediators.sort((o,C)=>o.value<C.value?1:-1),this._sideMediators[0].value>1&&this._sideMediators[0].mediate();while(this._sideMediators[0].value>1);let i=e>g?g/e:1,I=e<g?e/g:1;this._units===Aw&&(i=I=1),this._cornerTL.x=this._valueUV.x*i,this._cornerTL.y=1-this._valueUV.x*I,this._cornerTR.x=1-this._valueUV.y*i,this._cornerTR.y=1-this._valueUV.y*I,this._cornerBR.x=1-this._valueUV.z*i,this._cornerBR.y=this._valueUV.z*I,this._cornerBL.x=this._valueUV.w*i,this._cornerBL.y=this._valueUV.w*I}dispose(){for(const A of this._sideMediators)A.dispose();this._sideMediators=null,this._cornerTL=null,this._cornerTR=null,this._cornerBR=null,this._cornerBL=null,super.dispose()}set topLeft(A){this._input.x!==A&&(this._input.x=A,this._needsUpdate=!0)}get topLeft(){return this._input.x}set topRight(A){this._input.y!==A&&(this._input.y=A,this._needsUpdate=!0)}get topRight(){return this._input.y}set bottomRight(A){this._input.z!==A&&(this._input.z=A,this._needsUpdate=!0)}get bottomRight(){return this._input.z}set bottomLeft(A){this._input.w!==A&&(this._input.w=A,this._needsUpdate=!0)}get bottomLeft(){return this._input.w}set top(A){this._input.x===A&&this._input.y===A||(this._input.x=this._input.y=A,this._needsUpdate=!0)}get top(){return(this._input.x+this._input.y)/2}set right(A){this._input.y===A&&this._input.z===A||(this._input.y=this._input.z=A,this._needsUpdate=!0)}get right(){return(this._input.y+this._input.z)/2}set bottom(A){this._input.z===A&&this._input.w===A||(this._input.z=this._input.w=A,this._needsUpdate=!0)}get bottom(){return(this._input.z+this._input.w)/2}set left(A){this._input.w===A&&this._input.x===A||(this._input.w=this._input.x=A,this._needsUpdate=!0)}get left(){return(this._input.w+this._input.x)/2}}class ew{constructor(A,e){this._borderRadiuses=A,this._sideProperties=e,this._complementaryMediation=null,this._value=0}get value(){return this._value}set complementaryMediation(A){this._complementaryMediation=A}computeValue(){let A=0;for(const e of this._sideProperties)A+=this._borderRadiuses[e];this._value=A}mediate(A=!0){if(!(this._value<1)){for(const e of this._sideProperties)this._borderRadiuses[e]/=this._value;A&&this._complementaryMediation.mediate(!1)}}dispose(){this._complementaryMediation=null,this._borderRadiuses=null}}class j7 extends XD{constructor(A){super("borderWidth",A,!1),this._valueUV=this._value.clone(),this.output=this._outputValue,this._units=YQ}set units(A){this._units=dY(A),this._needsUpdate=!0}get units(){return this._units}computeOutputValue(A){this._vector4ValueSetter(this._value,this._input),this._needsProcess=!0,A._bounds._needsUpdate=!0,A._layouter._needsUpdate=!0}_outputValue(A){A[this._id]=this._valueUV}process(A){this._needsRender=!0,A._borderRadius._needsRender=!0}render(A){this._valueUV.copy(this._value);const e=A._bounds._offsetWidth,g=A._bounds._offsetHeight;if(this._units===Aw&&(console.log("Percent"),console.log(this._valueUV)),this._units===YQ)e!==0&&(this._valueUV.w/=e,this._valueUV.y/=e),g!==0&&(this._valueUV.x/=g,this._valueUV.z/=g);else if(this._units===lY){if(e!==0){const i=e>g?g/e:1;this._valueUV.y*=i,this._valueUV.w*=i}if(g!==0){const i=e<g?e/g:1;this._valueUV.x*=i,this._valueUV.z*=i}}}}class W7 extends Qt{constructor(A,e=!0){super("visible",e,!0),this._needsUpdate=!1}update(A,e){A.visible=this._value,A._parent._value&&(A._parent._value._children._needsUpdate=!0)}set value(A){this.isValid(A)&&this._value!==A&&(this._value=A,this._needsUpdate=!0)}get value(){return this._value}}class pY extends xc{constructor(A){super("backgroundColor",A,!1),this._input="transparent",this._allowsInherit=!1}computeOutputValue(A){A._backgroundMesh.visible=!(this._input==="none"||this._input==="transparent"),this._input==="inherit"?this._value.set(this.getInheritedInput(A)):this._input==="transparent"||this._input==="none"||this._value.set(this._input)}}class Ks extends Qt{constructor(A="untitled"){super(A,void 0,!1)}update(A,e){}output(A){}}class V7 extends Qt{constructor(){super("inlineJustificator",null,!1),this._value=null}update(A,e){}process(A){const e=A._bounds._innerHeight,g=A._layouter._value,i=Math.abs(g.height);let I=(()=>{switch(A._alignItems._value){case"inherit":case"start":return e/2;case"end":return i-e/2;case"stretch":case"center":return i/2}})();const o=A._padding._value,C=A._borderWidth._value;I+=(-o.x+o.z)/2+(-C.x+C.z)/2,g.forEach(s=>{s.y+=I,s.forEach(a=>{a.offsetY+=I})})}}const z7=["start","center","end","stretch"],Z7=function(t){return z7.indexOf(t)===-1?(console.warn(`(.style) alignItems value '${t}' is not valid. Aborted`),!1):!0};class km extends qt{constructor(){super("alignItems","inherit",!0),this.isValidValue=Z7}}class Gm extends qt{constructor(){super("textAlign","inherit",!0),this.isValidValue=$7}}const X7=["left","right","center","justify","justify-left","justify-right","justify-center"],$7=function(t){return X7.indexOf(t)===-1?(console.warn(`(.style) textAlign value '${t}' is not valid. Aborted`),!1):!0};class mm extends qt{constructor(){super("flexDirection","inherit",!0),this.isValid=e$}}const A$=["row","row-reverse","column","column-reverse"];function e$(t){return A$.indexOf(t)===-1?(console.warn(`(.style) flexDirection value '${t}' is not valid. Aborted`),!1):!0}class Mm extends qt{constructor(){super("justifyContent","inherit",!0),this.isValidValue=g$}}const t$=["start","center","end","space-between","space-around","space-evenly"];function g$(t){return t$.indexOf(t)===-1?(console.warn(`(.style) justifyContent value '${t}' is not valid. Aborted`),!1):!0}class i$ extends qt{constructor(){super("order",0,!0),this._value=0,this._input=0,this._allowsInherit=!1}computeOutputValue(A){this._value=this._inheritedInput,A._parent._value&&(A._parent._value._children._needsProcess=!0)}}class uY extends qt{constructor(){super("position","static",!0),this._allowsInherit=!1,this._value="static",this._needsUpdate=!1,this.computeOutputValue=this._computeFromInherited,this.isValidValue=o$}_computeFromInherited(A){super._computeFromInherited(A),A._parent._value&&(A._parent._value._children._needsProcess=!0)}}const I$=["static","absolute"];function o$(t){return I$.indexOf(t)===-1?(console.warn(`(.style) position value '${t}' is not valid. Aborted`),!1):!0}class DY extends qt{constructor(A,e=null){super(A,e,!0),this._input="auto",this._auto=!0,this._relative=!1,this._updateRequired=!0}set inline(A){this.isValidValue(A)&&A!==this._inline&&(this._inline=A,this._input!==this._inline&&this._parseInput())}get inline(){return this._inline}_parseInput(){let A=!0;if(this._inline!==void 0&&this._inline!=="unset"?this._input=this._inline:this._computed!==void 0?(this._computed===this._input&&(A=!1),this._input=this._computed):A=this._input==="inherit",A){if(this._auto=!this._input||this._input==="auto",this._auto)this._relative=!1;else if((typeof this._input=="string"||this._input instanceof String)&&this._input.endsWith("%")){this._relative=!0,this._value=0;const e=parseFloat(this._input.replace("%","").trim());isNaN(e)||(this._value=e/100)}else this._relative=!1,this._value=this._input;this._needsUpdate=this._updateRequired=A}}update(A,e){if(this._updateRequired){this._updateRequired=!1,this._allowsInherit||(this._inheritedInput=this.getInheritedInput(A)),this.computeOutputValue(A);for(const g of A._children._uis)g[`_${this._id}`]._needsUpdate=!0;this.output(e),A._parent._value&&(A._parent._value._layouter._needsProcess=!0)}}computeOutputValue(A){A._bounds._needsUpdate=!0,A._renderer._needsRender=!0}getInheritedInput(A){if(this._input!=="inherit"&&!this._auto)return this._input;const e=A._parent._value;return e?e[`_${this._id}`].getInheritedInput(e):this.getDefaultValue()}getDefaultValue(){return 0}get value(){return this._value}}class C$ extends DY{constructor(){super("width")}}class s$ extends DY{constructor(){super("height")}computeOutputValue(A){super.computeOutputValue(A)}}class wY extends Ks{constructor(){super("textContent"),this._needsUpdate=!1}set value(A){}process(A){let e="";for(let g=0;g<A.children.length;g++){const i=A.children[g];i.isUI&&(e+=i.textContent)}this._value=e}}class yY extends qt{constructor(A){super("fontStyle",A,!0),this.isValidValue=n$}}const a$=["normal","italic"];function n$(t){return a$.indexOf(t)===-1?(console.warn(`(.style) fontStyle value '${t}' is not valid. Aborted`),!1):!0}class SY extends qt{constructor(){super("fontWeight","inherit",!0),this.isValid=B$}}const r$=["100","200","300","400","500","600","700","800","900","light","normal","bold","bolder"];function B$(t){return r$.indexOf(t.toString())===-1?(console.warn(`(.style) fontWeight value '${t}' is not valid. Aborted`),!1):!0}class fY{constructor(){this._size=42,this._lineHeight=42,this._lineBase=38,this._name="-",this._charset=""}get size(){return this._size}get lineHeight(){return this._lineHeight}get lineBase(){return this._lineBase}get name(){return this._name}get charset(){return this._charset}}class Q$ extends fY{constructor(A){super(),this._size=A.info.size,this._lineHeight=A.common.lineHeight,this._lineBase=A.common.base,this._name=A.info.face,this._textureWidth=A.common.scaleW,this._textureHeight=A.common.scaleH,this._charset=A.chars.map(e=>e.char).join("")}get textureWidth(){return this._textureWidth}get textureHeight(){return this._textureHeight}}class kY{constructor(A){this._char="",this._width=1,this._heigth=1,this._xadvance=1,this._xoffset=0,this._yoffset=0,this._font=A}get font(){return this._font}get char(){return this._char}get width(){return this._width}get height(){return this._heigth}get xadvance(){return this._xadvance}get xoffset(){return this._xoffset}get yoffset(){return this._yoffset}set yoffset(A){this._yoffset=A}clone(A){throw new Error("Abstract... Need to be implemented")}asInlineGlyph(){throw new Error("Abstract... Need to be implemented")}}class GY{constructor(){this._offsetX=0,this._offsetY=0,this._lineBreak=null,this._kerning=0,this._fontFactor=1,this._fontSize=0,this._cumulativeWidth=0,this._paddingLeft=0,this._paddingRight=0,this._marginLeft=0,this._marginRight=0}resetOffsets(){this._offsetX=this._offsetY=0,this._cumulativeWidth=0}get xadvance(){return 0}get xoffset(){return 0}get yoffset(){return 0}get width(){return 0}get height(){return 0}set lineBreak(A){this._lineBreak=A}get lineBreak(){return this._lineBreak}get anchor(){return 0}get kerning(){return this._kerning*this._fontFactor}set kerning(A){this._kerning=A}get fontSize(){return this._fontSize}set fontSize(A){this._fontSize=A}get lineHeight(){return 0}get offsetX(){return this._offsetX}set offsetX(A){this._offsetX=A}get offsetY(){return this._offsetY}set offsetY(A){this._offsetY=A}get cumulativeWidth(){return this._cumulativeWidth}set cumulativeWidth(A){this._cumulativeWidth=A}get marginLeft(){return this._marginLeft}set marginLeft(A){this._marginLeft=A}get marginRight(){return this._marginRight}set marginRight(A){this._marginRight=A}get paddingLeft(){return this._paddingLeft}set paddingLeft(A){this._paddingLeft=A}get paddingRight(){return this._paddingRight}set paddingRight(A){this._paddingRight=A}get lineBase(){return 0}set fontFactor(A){this._fontFactor=A}get fontFactor(){return this._fontFactor}}class mY extends GY{constructor(A){super(),this._typographic=A}get typographic(){return this._typographic}get xadvance(){return this._typographic.xadvance*this._fontFactor}get xoffset(){return this._typographic.xoffset*this._fontFactor}get yoffset(){return this._typographic.yoffset*this._fontFactor}get width(){return this._typographic.width*this._fontFactor}get height(){return this._typographic.height*this._fontFactor}get char(){return this._typographic.char}get anchor(){return this.yoffset}get lineHeight(){return this._typographic.font.lineHeight*this._fontFactor}get lineBase(){return this._typographic.font.lineBase*this._fontFactor}}class E$ extends mY{constructor(A){super(A)}get uv(){return this.typographic.uv}}class hS extends kY{constructor(A,e){super(A),this._char=e.char,this._width=e.width,this._heigth=e.height,this._xadvance=e.xadvance?e.xadvance:this._width,this._xoffset=e.xoffset?e.xoffset:0,this._yoffset=e.yoffset?e.yoffset:0,this._uv=e.uv?e.uv:null,isNaN(e.x)||(this._uv={left:e.x/A.textureWidth,right:(e.x+e.width)/A.textureWidth,top:1-(e.y+e.height)/A.textureHeight,bottom:1-e.y/A.textureHeight})}get uv(){return this._uv}clone(A){return new hS(this._font,{char:A,width:this._width,height:this._heigth,xadvance:this._xadvance,xoffset:this._xoffset,yoffset:this._yoffset,uv:null})}asInlineGlyph(){return new E$(this)}}class h$ extends XA.PlaneGeometry{constructor(A,e){let g=1,i=1;const I=A.typographic.font.size,o=e._segments.value;g=Math.ceil(A.typographic.width/I*o),i=Math.ceil(A.typographic.height/I*o),super(A.width,A.height,g,i),A.uv?(this._mapUVs(A),this._transformGeometry(A)):(this._nullifyUVs(),this.scale(0,0,1),this.translate(0,A.fontSize/2,0)),this.name="GlyphGeometry"}_mapUVs(A){const e=A.uv.right-A.uv.left,g=A.uv.bottom-A.uv.top,i=this.getAttribute("uv").array.slice(),I=[];for(let o=0;o<i.length;o+=2){const C=i[o],s=i[o+1];I.push(A.uv.left+e*C),I.push(A.uv.top+g*s)}this.setAttribute("uvG",new XA.BufferAttribute(new Float32Array(I),2))}_nullifyUVs(){const A=[],e=this.getAttribute("uv").array.length;for(let g=0;g<e;g++)A.push(0);this.setAttribute("uvG",new XA.BufferAttribute(new Float32Array(A),2))}_transformGeometry(A){this.translate(A.width/2,-A.height/2,0)}}const c$=`
|
|
4181
4181
|
attribute vec2 uvG;
|
|
4182
4182
|
varying vec2 vUvG;
|
|
@@ -5435,7 +5435,7 @@ void main() {
|
|
|
5435
5435
|
// be blended onto the scene.
|
|
5436
5436
|
gl_FragColor = vec4(direct, max);
|
|
5437
5437
|
return;
|
|
5438
|
-
`)}}}applyShadowMaterial(){var A;const e=eA.getComponent(this.gameObject,Jt);if(e)if(((A=e.sharedMaterial)==null?void 0:A.type)!=="ShadowMaterial"){const g=new kf;g.color=this.shadowColor,g.opacity=this.shadowColor.alpha,this.applyMaterialOptions(g),e.sharedMaterial=g}else{const g=e.sharedMaterial;g.color=this.shadowColor,g.opacity=this.shadowColor.alpha,this.applyMaterialOptions(g)}}applyOccluderMaterial(){const A=eA.getComponent(this.gameObject,Jt);if(A){const e=A.sharedMaterial;e.depthWrite=!0,e.stencilWrite=!0,e.colorWrite=!1,this.gameObject.renderOrder=-100}}applyMaterialOptions(A){A&&(A.depthWrite=!1,A.stencilWrite=!1)}}f2([w()],Ol.prototype,"mode",2),f2([w(wt)],Ol.prototype,"shadowColor",2);var YoA=Object.defineProperty,HoA=Object.getOwnPropertyDescriptor,ly=(t,A,e,g)=>{for(var i=g>1?void 0:g?HoA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&YoA(A,e,i),i},UR;const k2=(UR=class extends RA{constructor(){super(...arguments),r(this,"target",null),r(this,"followFactor",.1),r(this,"rotateFactor",.1),r(this,"positionAxes",xQ.All),r(this,"flipForward",!1),r(this,"_firstUpdate",!0)}onBeforeRender(){this.updateNow(!1)}updateNow(t){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){const A=we(this.target),e=this._firstUpdate||t?1:$A.clamp01(this.context.time.deltaTime*this.followFactor),g=this.worldPosition;this.positionAxes&xQ.X&&(g.x=$A.lerp(g.x,A.x,e)),this.positionAxes&xQ.Y&&(g.y=$A.lerp(g.y,A.y,e)),this.positionAxes&xQ.Z&&(g.z=$A.lerp(g.z,A.z,e)),this.worldPosition=g}if(this.rotateFactor>0){const A=qg(this.target);this.flipForward&&A.premultiply(k2._invertForward);const e=this._firstUpdate||t?1:$A.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(A,e)}this._firstUpdate=!1}}},r(UR,"_invertForward",new mA().setFromAxisAngle(new f(0,1,0),Math.PI)),UR);let Sn=k2;ly([w(UA)],Sn.prototype,"target",2),ly([w()],Sn.prototype,"followFactor",2),ly([w()],Sn.prototype,"rotateFactor",2),ly([w()],Sn.prototype,"positionAxes",2);class ToA extends DA{constructor(A){const e=new OoA(A),g=new Zg(e.image.width*.001,e.image.height*.001),i=new dt({map:e,toneMapped:!1,transparent:!0});super(g,i);function I(o){i.map.dispatchDOMEvent(o)}this.addEventListener("mousedown",I),this.addEventListener("mousemove",I),this.addEventListener("mouseup",I),this.addEventListener("click",I),this.dispose=function(){g.dispose(),i.dispose(),i.map.dispose(),FR.delete(A),this.removeEventListener("mousedown",I),this.removeEventListener("mousemove",I),this.removeEventListener("mouseup",I),this.removeEventListener("click",I)}}}class OoA extends rK{constructor(A){super(G2(A)),this.dom=A,this.anisotropy=16,this.encoding=ue,this.minFilter=Ne,this.magFilter=Ne;const e=new MutationObserver(()=>{this.scheduleUpdate||(this.scheduleUpdate=setTimeout(()=>this.update(),16))}),g={attributes:!0,childList:!0,subtree:!0,characterData:!0};e.observe(A,g),this.observer=e}dispatchDOMEvent(A){A.data&&_oA(this.dom,A.type,A.data.x,A.data.y)}update(){this.image=G2(this.dom),this.needsUpdate=!0,this.scheduleUpdate=null}dispose(){this.observer&&this.observer.disconnect(),this.scheduleUpdate=clearTimeout(this.scheduleUpdate),super.dispose()}}const FR=new WeakMap;function G2(t){const A=document.createRange(),e=new SA;function g(Q){const E=[];let h=!1;function c(){if(h&&(h=!1,Q.restore()),E.length===0)return;let l=-1/0,d=-1/0,u=1/0,p=1/0;for(let D=0;D<E.length;D++){const y=E[D];l=Math.max(l,y.x),d=Math.max(d,y.y),u=Math.min(u,y.x+y.width),p=Math.min(p,y.y+y.height)}Q.save(),Q.beginPath(),Q.rect(l,d,u-l,p-d),Q.clip(),h=!0}return{add:function(l){E.push(l),c()},remove:function(){E.pop(),c()}}}function i(Q,E,h,c){c!==""&&(Q.textTransform==="uppercase"&&(c=c.toUpperCase()),n.font=Q.fontWeight+" "+Q.fontSize+" "+Q.fontFamily,n.textBaseline="top",n.fillStyle=Q.color,n.fillText(c,E,h+parseFloat(Q.fontSize)*.1))}function I(Q,E,h,c,l){h<2*l&&(l=h/2),c<2*l&&(l=c/2),n.beginPath(),n.moveTo(Q+l,E),n.arcTo(Q+h,E,Q+h,E+c,l),n.arcTo(Q+h,E+c,Q,E+c,l),n.arcTo(Q,E+c,Q,E,l),n.arcTo(Q,E,Q+h,E,l),n.closePath()}function o(Q,E,h,c,l,d){const u=Q[E+"Width"],p=Q[E+"Style"],D=Q[E+"Color"];u!=="0px"&&p!=="none"&&D!=="transparent"&&D!=="rgba(0, 0, 0, 0)"&&(n.strokeStyle=D,n.lineWidth=parseFloat(u),n.beginPath(),n.moveTo(h,c),n.lineTo(h+l,c+d),n.stroke())}function C(Q,E){let h=0,c=0,l=0,d=0;if(Q.nodeType===Node.TEXT_NODE){A.selectNode(Q);const p=A.getBoundingClientRect();h=p.left-s.left-.5,c=p.top-s.top-.5,l=p.width,d=p.height,i(E,h,c,Q.nodeValue.trim())}else{if(Q.nodeType===Node.COMMENT_NODE)return;if(Q instanceof HTMLCanvasElement){if(Q.style.display==="none")return;n.save();const p=window.devicePixelRatio;n.scale(1/p,1/p),n.drawImage(Q,0,0),n.restore()}else{if(Q.style.display==="none")return;const p=Q.getBoundingClientRect();h=p.left-s.left-.5,c=p.top-s.top-.5,l=p.width,d=p.height,E=window.getComputedStyle(Q),I(h,c,l,d,parseFloat(E.borderRadius));const D=E.backgroundColor;D!=="transparent"&&D!=="rgba(0, 0, 0, 0)"&&(n.fillStyle=D,n.fill());const y=["borderTop","borderLeft","borderBottom","borderRight"];let k=!0,F=null;for(const S of y){if(F!==null&&(k=E[S+"Width"]===E[F+"Width"]&&E[S+"Color"]===E[F+"Color"]&&E[S+"Style"]===E[F+"Style"]),k===!1)break;F=S}if(k===!0){const S=parseFloat(E.borderTopWidth);E.borderTopWidth!=="0px"&&E.borderTopStyle!=="none"&&E.borderTopColor!=="transparent"&&E.borderTopColor!=="rgba(0, 0, 0, 0)"&&(n.strokeStyle=E.borderTopColor,n.lineWidth=S,n.stroke())}else o(E,"borderTop",h,c,l,0),o(E,"borderLeft",h,c,0,d),o(E,"borderBottom",h,c+d,l,0),o(E,"borderRight",h+l,c,0,d);if(Q instanceof HTMLInputElement){let S=E.accentColor;(S===void 0||S==="auto")&&(S=E.color),e.set(S);const U=Math.sqrt(.299*e.r**2+.587*e.g**2+.114*e.b**2)<.5?"white":"#111111";if(Q.type==="radio"&&(I(h,c,l,d,d),n.fillStyle="white",n.strokeStyle=S,n.lineWidth=1,n.fill(),n.stroke(),Q.checked&&(I(h+2,c+2,l-4,d-4,d),n.fillStyle=S,n.strokeStyle=U,n.lineWidth=2,n.fill(),n.stroke())),Q.type==="checkbox"&&(I(h,c,l,d,2),n.fillStyle=Q.checked?S:"white",n.strokeStyle=Q.checked?U:S,n.lineWidth=1,n.stroke(),n.fill(),Q.checked)){const M=n.textAlign;n.textAlign="center";const Y={color:U,fontFamily:E.fontFamily,fontSize:d+"px",fontWeight:"bold"};i(Y,h+l/2,c,"\u2714"),n.textAlign=M}if(Q.type==="range"){const[M,Y,O]=["min","max","value"].map(b=>parseFloat(Q[b])),x=(O-M)/(Y-M)*(l-d);I(h,c+d/4,l,d/2,d/4),n.fillStyle=U,n.strokeStyle=S,n.lineWidth=1,n.fill(),n.stroke(),I(h,c+d/4,x+d/2,d/2,d/4),n.fillStyle=S,n.fill(),I(h+x,c,d,d,d/2),n.fillStyle=S,n.fill()}(Q.type==="color"||Q.type==="text"||Q.type==="number")&&(B.add({x:h,y:c,width:l,height:d}),i(E,h+parseInt(E.paddingLeft),c+parseInt(E.paddingTop),Q.value),B.remove())}}}const u=E.overflow==="auto"||E.overflow==="hidden";u&&B.add({x:h,y:c,width:l,height:d});for(let p=0;p<Q.childNodes.length;p++)C(Q.childNodes[p],E);u&&B.remove()}const s=t.getBoundingClientRect();let a=FR.get(t);a===void 0&&(a=document.createElement("canvas"),a.width=s.width,a.height=s.height,FR.set(t,a));const n=a.getContext("2d"),B=new g(n);return C(t),a}function _oA(t,A,e,g){const i={clientX:e*t.offsetWidth+t.offsetLeft,clientY:g*t.offsetHeight+t.offsetTop,view:t.ownerDocument.defaultView};window.dispatchEvent(new MouseEvent(A,i));const I=t.getBoundingClientRect();e=e*I.width+I.left,g=g*I.height+I.top;function o(C){if(C.nodeType!==Node.TEXT_NODE&&C.nodeType!==Node.COMMENT_NODE){const s=C.getBoundingClientRect();if(e>s.left&&e<s.right&&g>s.top&&g<s.bottom&&(C.dispatchEvent(new MouseEvent(A,i)),C instanceof HTMLInputElement&&C.type==="range"&&(A==="mousedown"||A==="click"))){const[a,n]=["min","max"].map(E=>parseFloat(C[E])),B=s.width,Q=(e-s.x)/B;C.value=a+(n-a)*Q,C.dispatchEvent(new InputEvent("input",{bubbles:!0}))}for(let a=0;a<C.childNodes.length;a++)o(C.childNodes[a])}}o(t)}const dy=new W,fE={type:"",data:dy};class PoA extends zI{constructor(A,e){super();const g=this,i=new VB,I=new KA,o=A.domElement;function C(Q){Q.stopPropagation();const E=A.domElement.getBoundingClientRect();dy.x=(Q.clientX-E.left)/E.width*2-1,dy.y=-(Q.clientY-E.top)/E.height*2+1,i.setFromCamera(dy,e);const h=i.intersectObjects(g.children,!1);if(h.length>0){const c=h[0],l=c.object,d=c.uv;fE.type=Q.type,fE.data.set(d.x,1-d.y),l.dispatchEvent(fE)}}o.addEventListener("pointerdown",C),o.addEventListener("pointerup",C),o.addEventListener("pointermove",C),o.addEventListener("mousedown",C),o.addEventListener("mouseup",C),o.addEventListener("mousemove",C),o.addEventListener("click",C);const s={move:"mousemove",select:"click",selectstart:"mousedown",selectend:"mouseup"};function a(Q){const E=Q.target;I.identity().extractRotation(E.matrixWorld),i.ray.origin.setFromMatrixPosition(E.matrixWorld),i.ray.direction.set(0,0,-1).applyMatrix4(I);const h=i.intersectObjects(g.children,!1);if(h.length>0){const c=h[0],l=c.object,d=c.uv;fE.type=s[Q.type],fE.data.set(d.x,1-d.y),l.dispatchEvent(fE)}}const n=A.xr.getController(0);n.addEventListener("move",a),n.addEventListener("select",a),n.addEventListener("selectstart",a),n.addEventListener("selectend",a);const B=A.xr.getController(1);B.addEventListener("move",a),B.addEventListener("select",a),B.addEventListener("selectstart",a),B.addEventListener("selectend",a)}}class NR extends RA{constructor(){super(...arguments),r(this,"id",null),r(this,"keepAspect",!1)}start(){if(!this.id||!this.context.mainCamera)return;const A=document.getElementById(this.id);if(!A){console.warn('Could not find element with id "'+this.id+'"');return}A.style.display="block",A.style.visibility="hidden";const e=new PoA(this.context.renderer,this.context.mainCamera);this.gameObject.add(e);const g=new ToA(A);e.add(g),g.visible=!1,console.log(g);const i=g.material;i.transparent=!0,setTimeout(()=>{g.visible=!0;const I=du(this.gameObject).clone();pu(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();const o=new li;o.setFromObject(e),this.setWorldRotation(I.x,I.y,I.z);const C=o.max.x-o.min.x,s=o.max.y-o.min.y;if(this.keepAspect){const n=C/s;C>s?g.scale.set(1/C,1/s/n,1):g.scale.set(1/C*n,1/s,1)}else g.scale.set(1/C,1/s,1);const a=this.gameObject.scale;g.scale.multiply(a)},1)}}var joA=Object.defineProperty,WoA=Object.getOwnPropertyDescriptor,_l=(t,A,e,g)=>{for(var i=g>1?void 0:g?WoA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&joA(A,e,i),i};const Pl=CA("debugspatialtrigger"),m2=new jI,M2=new jI;function VoA(t,A){return m2.mask=t,M2.mask=A,m2.test(M2)}class JC extends RA{constructor(){super(...arguments),r(this,"triggerMask",0),r(this,"onEnter"),r(this,"onStay"),r(this,"onExit"),r(this,"currentIntersected",[]),r(this,"lastIntersected",[])}start(){Pl&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(const A of jl.triggers)VoA(A.triggerMask,this.triggerMask)&&A.test(this.gameObject)&&this.currentIntersected.push(A);for(let A=this.lastIntersected.length-1;A>=0;A--){const e=this.lastIntersected[A];this.currentIntersected.indexOf(e)<0&&(this.onExitTrigger(e),this.lastIntersected.splice(A,1))}for(const A of this.currentIntersected)this.lastIntersected.indexOf(A)<0&&this.onEnterTrigger(A),this.onStayTrigger(A);this.lastIntersected.length=0,this.lastIntersected.push(...this.currentIntersected)}onEnterTrigger(A){var e;Pl&&console.log("ENTER TRIGGER",this.name,A.name,this,A),A.raiseOnEnterEvent(this),(e=this.onEnter)==null||e.invoke(this,A)}onExitTrigger(A){var e;Pl&&console.log("EXIT TRIGGER",this.name,A.name,this,A),A.raiseOnExitEvent(this),(e=this.onExit)==null||e.invoke(this,A)}onStayTrigger(A){var e;A.raiseOnStayEvent(this),(e=this.onStay)==null||e.invoke(this,A)}}_l([w()],JC.prototype,"triggerMask",2),_l([w(aI)],JC.prototype,"onEnter",2),_l([w(aI)],JC.prototype,"onStay",2),_l([w(aI)],JC.prototype,"onExit",2);var KR;const py=(KR=class extends RA{constructor(){super(...arguments),r(this,"triggerMask"),r(this,"boxHelper")}start(){Pl&&console.log(this.name,this.triggerMask,this)}onEnable(){var t;py.triggers.push(this),this.boxHelper||(this.boxHelper=eA.addNewComponent(this.gameObject,dC),(t=this.boxHelper)==null||t.showHelper(null,Pl))}onDisable(){py.triggers.splice(py.triggers.indexOf(this),1)}test(t){return this.boxHelper?this.boxHelper.isInBox(t)??!1:!1}raiseOnEnterEvent(t){eA.foreachComponent(this.gameObject,A=>{A!==t&&A instanceof JC&&A.onEnterTrigger(this)},!1)}raiseOnStayEvent(t){eA.foreachComponent(this.gameObject,A=>{A!==t&&A instanceof JC&&A.onStayTrigger(this)},!1)}raiseOnExitEvent(t){eA.foreachComponent(this.gameObject,A=>{A!==t&&A instanceof JC&&A.onExitTrigger(this)},!1)}},r(KR,"triggers",[]),KR);let jl=py;_l([w()],jl.prototype,"triggerMask",2);var zoA=Object.defineProperty,ZoA=Object.getOwnPropertyDescriptor,XoA=(t,A,e,g)=>{for(var i=g>1?void 0:g?ZoA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&zoA(A,e,i),i};const YI=CA("debugspectator");class uy extends RA{constructor(){super(...arguments),r(this,"cam",null),r(this,"useKeys",!0),r(this,"_mode",0),r(this,"orbit",null),r(this,"_handler"),r(this,"eventSub_WebXRRequestStartEvent",null),r(this,"eventSub_WebXRStartEvent",null),r(this,"eventSub_WebXREndEvent",null),r(this,"_debug"),r(this,"_networking")}get mode(){return this._mode}set mode(A){this._mode=A}get isSpectating(){var A;return((A=this._handler)==null?void 0:A.currentTarget)!==void 0}isSpectatingUser(A){var e;return((e=this.target)==null?void 0:e.userId)===A}isFollowedBy(A){var e;return(e=this.followers)==null?void 0:e.includes(A)}get followers(){return this._networking.followers}stopSpectating(){if(this.context.isInXR){this.followSelf();return}this.target=void 0}get localId(){return this.context.connection.connectionId??"local"}set target(A){var e;if(this._handler){const g=(e=this._handler.currentTarget)==null?void 0:e.userId,i=this.context.players.getPlayerView(this.localId);A===void 0||this.context.isInXR===!1&&i?.currentObject===A.currentObject?this._handler.currentTarget!==void 0&&(this._handler.disable(),eA.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(A,g)):this._handler.currentTarget!==A&&(this._handler.set(A),eA.setActive(this.gameObject,!0),this.orbit&&(this.orbit.enabled=!1),this._networking.onSpectatedObjectChanged(A,g))}}get target(){var A;return(A=this._handler)==null?void 0:A.currentTarget}requestAllFollowMe(){this._networking.onRequestFollowMe()}get isSpectatingSelf(){var A,e;return this.isSpectating&&((A=this.target)==null?void 0:A.currentObject)===((e=this.context.players.getPlayerView(this.localId))==null?void 0:e.currentObject)}awake(){if(this._debug=new eCA(this.context,this),this._networking=new iCA(this.context,this),this._networking.awake(),eA.setActive(this.gameObject,!1),this.cam=eA.getComponent(this.gameObject,bt),!this.cam){console.error("Spectator camera needs camera component",this);return}!this._handler&&this.cam&&(this._handler=new $oA(this.context,this.cam,this)),this.eventSub_WebXRRequestStartEvent=this.onXRSessionRequestStart.bind(this),this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),Se.addEventListener(kt.RequestVRSession,this.eventSub_WebXRRequestStartEvent),Se.addEventListener(kt.XRStarted,this.eventSub_WebXRStartEvent),Se.addEventListener(kt.XRStopped,this.eventSub_WebXREndEvent),this.orbit=eA.getComponent(this.context.mainCamera,Ts)}onDestroy(){var A;this.stopSpectating(),Se.removeEventListener(kt.RequestVRSession,this.eventSub_WebXRStartEvent),Se.removeEventListener(kt.XRStarted,this.eventSub_WebXRStartEvent),Se.removeEventListener(kt.XRStopped,this.eventSub_WebXREndEvent),(A=this._handler)==null||A.destroy(),this._networking.destroy()}isSupportedPlatform(){const A=window.navigator.userAgent,e=/Windows|MacOS/.test(A),g=/Windows NT/.test(A)&&/Edg/.test(A)&&!/Win64/.test(A);return e&&!g}onXRSessionRequestStart(A){this.isSupportedPlatform()&&eA.setActive(this.gameObject,!0)}onXRSessionStart(A){this.isSupportedPlatform()&&(YI&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onXRSessionEnded(A){var e,g;this.context.removeCamera(this.cam),eA.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),(e=this._handler)==null||e.set(void 0),(g=this._handler)==null||g.disable(),this.isSpectatingSelf&&this.stopSpectating()}followSelf(){this.target=this.context.players.getPlayerView(this.context.connection.connectionId),this.target||(this.context.players.setPlayerView(this.localId,this.context.mainCamera,QC.Headset),this.target=this.context.players.getPlayerView(this.localId)),YI&&console.log("Follow self",this.target)}onAfterRender(){var A,e,g;if(!this.cam)return;const i=this.context.renderer,I=i.xr.enabled;if(!i.xr.isPresenting&&!((A=this._handler)!=null&&A.currentTarget))return;(e=this._handler)==null||e.update(this._mode);const o=i.getRenderTarget();let C=null;if(!o){if(!i.state.bindFramebuffer||!i.state.bindXRFramebuffer)return;C=i._framebuffer,i.state.bindXRFramebuffer(null)}this.setAvatarFlagsBeforeRender();const s=this.context.mainCameraComponent;if(s){const B=s.backgroundColor;B&&i.setClearColor(B,B.alpha),this.cam.backgroundColor=B,this.cam.clearFlags=s.clearFlags,this.cam.nearClipPlane=s.nearClipPlane,this.cam.farClipPlane=s.farClipPlane}else i.setClearColor(new SA(1,1,1));i.setRenderTarget(null),i.xr.enabled=!1;const a=(g=this.cam)==null?void 0:g.cam;this.context.updateAspect(a);const n=i.xr.isPresenting;i.xr.isPresenting=!1,i.setSize(this.context.domWidth,this.context.domHeight),i.render(this.context.scene,a),i.xr.isPresenting=n,i.xr.enabled=I,o?i.setRenderTarget(o):i.state.bindXRFramebuffer(C),this.resetAvatarFlags()}setAvatarFlagsBeforeRender(){const A=this._mode===0;for(const e of fi.instances)if(e.avatar&&"isLocalAvatar"in e.avatar){let g=lg.All;this.isSpectatingSelf&&(g=A&&e.avatar.isLocalAvatar?lg.FirstPerson:lg.ThirdPerson);const i=e.avatar.flags;if(!i)continue;for(const I of i)I.UpdateVisible(g)}}resetAvatarFlags(){var A;for(const e of fi.instances)if(e.avatar&&"flags"in e.avatar){const g=e.avatar.flags;if(!g)continue;for(const i of g)(A=e.avatar)!=null&&A.isLocalAvatar?i.UpdateVisible(lg.FirstPerson):i.UpdateVisible(lg.ThirdPerson)}}}XoA([w()],uy.prototype,"useKeys",2);class $oA{constructor(A,e,g){r(this,"context"),r(this,"cam"),r(this,"spectator"),r(this,"follow"),r(this,"target"),r(this,"view"),r(this,"currentObject"),this.context=A,this.cam=e,this.spectator=g}get currentTarget(){return this.view}set(A){const e=A?.currentObject;if(!e){this.spectator.stopSpectating();return}e!==this.currentObject&&(this.currentObject=e,this.view=A,this.follow||(this.follow=eA.addNewComponent(this.cam.gameObject,Sn)),this.target||(this.target=new UA),e.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,YI&&console.log("FOLLOW",e),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){YI&&console.log("STOP FOLLOW",this.currentObject),this.view=void 0,this.currentObject=void 0,this.context.removeCamera(this.cam),this.follow&&(this.follow.enabled=!1)}destroy(){var A;(A=this.target)==null||A.removeFromParent(),this.follow&&eA.destroy(this.follow)}update(A){var e,g,i,I,o,C;if(((e=this.currentTarget)==null?void 0:e.isConnected)===!1||((g=this.currentTarget)==null?void 0:g.removed)===!0){YI&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&((i=this.currentTarget)==null?void 0:i.currentObject)!==this.currentObject&&(YI&&console.log("Target changed",this.currentObject,"to",this.currentTarget.currentObject),this.set(this.currentTarget));const s=this.context.mainCamera;s&&(this.cam.cam.near!==s.near||this.cam.cam.far!==s.far)&&(this.cam.cam.near=s.near,this.cam.cam.far=s.far,this.cam.cam.updateProjectionMatrix());const a=(I=this.follow)==null?void 0:I.target;if(!(!a||!this.follow)){switch(A){case 0:((o=this.view)==null?void 0:o.viewDevice)!==QC.Browser?(this.follow.followFactor=5,this.follow.rotateFactor=5):(this.follow.followFactor=50,this.follow.rotateFactor=50),a.position.set(0,0,0);break;case 1:this.follow.followFactor=3,this.follow.rotateFactor=2,a.position.set(0,.5,1.5);break}this.follow.flipForward=!1,((C=this.view)==null?void 0:C.viewDevice)!==QC.Browser?a.quaternion.copy(ACA):a.quaternion.identity()}}}const ACA=new mA().setFromAxisAngle(new f(0,1,0),Math.PI);class eCA{constructor(A,e){r(this,"context"),r(this,"spectator"),this.context=A,this.spectator=e,console.log("Click other avatars or cameras to follow them. Press ESC to exit spectator mode."),this.context.domElement.addEventListener("keydown",i=>{!this.spectator.useKeys||i.key==="Escape"&&this.spectator.stopSpectating()});let g=0;this.context.input.addEventListener(sC.PointerDown,i=>{g=this.context.time.time}),this.context.input.addEventListener(sC.PointerUp,i=>{const I=this.context.time.time-g;I>1?this.spectator.stopSpectating():this.context.input.getPointerClicked(0)&&I<.3&&this.trySelectObject()})}trySelectObject(){const A=new Jo;A.setMask(16777215);const e=this.context.physics.raycast(A);if(YI&&console.log(...e),e!=null&&e.length)for(const g of e){if(g.distance<.2)continue;const i=g.object,I=eA.getComponentInParent(i,fi),o=I?.connectionId;if(o){const C=this.context.players.getPlayerView(o);this.spectator.target=C,YI&&console.log("spectate",o,I);break}}}}class tCA{constructor(A,e,g){r(this,"guid"),r(this,"dontSave",!0),r(this,"targetUserId"),r(this,"stoppedFollowing"),this.guid=A,this.targetUserId=e,this.stoppedFollowing=g}}class gCA{constructor(A,e){r(this,"guid"),r(this,"userId"),this.guid=A.guid,this.userId=e}}class iCA{constructor(A,e){r(this,"followers",[]),r(this,"context"),r(this,"spectator"),r(this,"_followerEventMethod"),r(this,"_requestFollowMethod"),r(this,"_joinedRoomMethod"),r(this,"_lastRequestFollowUser"),r(this,"_enforceFollowInterval"),this.context=A,this.spectator=e,this._followerEventMethod=this.onFollowerEvent.bind(this),this._requestFollowMethod=this.onRequestFollowEvent.bind(this),this._joinedRoomMethod=this.onUserJoinedRoom.bind(this)}awake(){this.context.connection.beginListen("spectator-follower-changed",this._followerEventMethod),this.context.connection.beginListen("spectator-request-follow",this._requestFollowMethod),this.context.connection.beginListen(Wt.JoinedRoom,this._joinedRoomMethod),this.context.domElement.addEventListener("keydown",A=>{this.spectator.useKeys&&(A.key==="f"?this.onRequestFollowMe():A.key==="Escape"&&this.onRequestFollowMe(!0))})}destroy(){this.context.connection.stopListen("spectator-follower-changed",this._followerEventMethod),this.context.connection.stopListen("spectator-request-follow",this._requestFollowMethod),this.context.connection.stopListen(Wt.JoinedRoom,this._joinedRoomMethod)}onSpectatedObjectChanged(A,e){if(YI&&console.log(this.context.connection.connectionId,"onSpectatedObjectChanged",A,e),this.context.connection.connectionId){const g=A?.userId===void 0,i=g?e:A?.userId,I=new tCA(this.context.connection.connectionId,i,g);this.context.connection.send("spectator-follower-changed",I)}}onRequestFollowMe(A=!1){if(YI&&console.log("Request follow",this.context.connection.connectionId),this.context.connection.connectionId){this.spectator.stopSpectating();const e=A?void 0:this.context.connection.connectionId,g=new gCA(this.spectator,e);this.context.connection.send("spectator-request-follow",g)}}onUserJoinedRoom(){CA("followme")&&this.onRequestFollowMe()}onFollowerEvent(A){const e=A.targetUserId,g=A.guid;if(YI&&console.log(A),e===this.context.connection.connectionId)if(A.stoppedFollowing){const i=this.followers.indexOf(g);i!==-1&&(this.followers.splice(i,1),this.removeDisconnectedFollowers(),console.log(g,"unfollows you",this.followers.length))}else this.followers.includes(g)||(this.followers.push(g),this.removeDisconnectedFollowers(),console.log(g,"follows you",this.followers.length))}removeDisconnectedFollowers(){for(let A=this.followers.length-1;A>=0;A--){const e=this.followers[A];this.context.connection.userIsInRoom(e)===!1&&this.followers.splice(A,1)}}onRequestFollowEvent(A){if(this._lastRequestFollowUser=A,A.userId===this.context.connection.connectionId)this.spectator.stopSpectating();else if(A.userId===void 0)this.spectator.stopSpectating();else{const e=this.context.players.getPlayerView(A.userId);if(e)this.spectator.target=e;else return YI&&console.warn("Could not find view",A.userId),this.enforceFollow(),!1}return!0}enforceFollow(){this._enforceFollowInterval||(this._enforceFollowInterval=setInterval(()=>{this._lastRequestFollowUser===void 0||this._lastRequestFollowUser.userId&&this.spectator.isFollowedBy(this._lastRequestFollowUser.userId)?(clearInterval(this._enforceFollowInterval),this._enforceFollowInterval=void 0):(YI&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}}var ICA=Object.defineProperty,oCA=Object.getOwnPropertyDescriptor,$i=(t,A,e,g)=>{for(var i=g>1?void 0:g?oCA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&ICA(A,e,i),i};const JR=CA("debugspriterenderer"),CCA=CA("wireframe"),qR=class{static getOrCreateGeometry(t){if(t._geometry)return t._geometry;if(t.guid&&qR.cache[t.guid])return JR&&console.log("Take cached geometry for sprite",t.guid),qR.cache[t.guid];const A=new le;t._geometry=A;const e=new Float32Array(t.triangles.length*3),g=new Float32Array(t.triangles.length*2);for(let i=0;i<t.triangles.length;i+=1){const I=t.triangles[i];e[i*3]=-t.vertices[I].x,e[i*3+1]=t.vertices[I].y,e[i*3+2]=0;const o=t.uv[I];g[i*2]=o.x,g[i*2+1]=1-o.y}return A.setAttribute("position",new ge(e,3)),A.setAttribute("uv",new ge(g,2)),t.guid&&(this.cache[t.guid]=A),JR&&console.log("Built sprite geometry",t,A),A}};let vR=qR;r(vR,"cache",{});class $s{constructor(){r(this,"guid"),r(this,"texture"),r(this,"triangles"),r(this,"uv"),r(this,"vertices"),r(this,"_geometry")}}$i([w()],$s.prototype,"guid",2),$i([w(Le)],$s.prototype,"texture",2),$i([mQ()],$s.prototype,"triangles",2),$i([mQ()],$s.prototype,"uv",2),$i([mQ()],$s.prototype,"vertices",2);const bR=Symbol("spriteOwner");class Wl{constructor(){r(this,"sprites")}}$i([w($s)],Wl.prototype,"sprites",2);class kE{constructor(){r(this,"spriteSheet"),r(this,"index",0)}update(){if(!this.spriteSheet)return;const A=this.index;if(A<0||A>=this.spriteSheet.sprites.length)return;const e=this.spriteSheet.sprites[A];let g=e?.texture;g&&(g.encoding=ue,g.minFilter==Ve&&g.magFilter==Ve&&(g.anisotropy=1),g.needsUpdate=!0)}}$i([w(Wl)],kE.prototype,"spriteSheet",2),$i([w()],kE.prototype,"index",2);class qC extends RA{constructor(){super(...arguments),r(this,"drawMode",0),r(this,"size",{x:1,y:1}),r(this,"color"),r(this,"sharedMaterial"),r(this,"_spriteSheet"),r(this,"_currentSprite"),r(this,"transparent",!0),r(this,"cutoutThreshold",0),r(this,"castShadows",!1)}get sprite(){return this._spriteSheet}set sprite(A){if(A!==this._spriteSheet)if(typeof A=="number"){const e=Math.floor(A);e===A&&(this.spriteIndex=e);return}else this._spriteSheet=A,this.updateSprite()}set spriteIndex(A){this._spriteSheet&&(this._spriteSheet.index=A,this.updateSprite())}get spriteIndex(){var A;return((A=this._spriteSheet)==null?void 0:A.index)??0}get spriteFrames(){var A,e;return((e=(A=this._spriteSheet)==null?void 0:A.spriteSheet)==null?void 0:e.sprites.length)??0}awake(){this._currentSprite=void 0,JR&&console.log("Awake",this.name,this,this.sprite)}start(){this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(){var A,e,g;if(!this.__didAwake||!((e=(A=this.sprite)==null?void 0:A.spriteSheet)!=null&&e.sprites))return;const i=this.sprite.spriteSheet.sprites[this.spriteIndex];if(this._currentSprite)this._currentSprite.geometry=vR.getOrCreateGeometry(i),this._currentSprite.material.map=i.texture;else{const I=new dt({color:16777215,side:ft});if(!I)return;if(CCA&&(I.wireframe=!0),this.color&&(I.color||(I.color=new SA),I.color.copy(this.color),I.opacity=this.color.alpha),I.transparent=!0,i.texture&&!I.wireframe){let o=i.texture;o[bR]!==void 0&&o[bR]!==this&&this.spriteFrames>1&&(o=i.texture=o.clone()),o[bR]=this,I.map=o}this.sharedMaterial=I,this._currentSprite=new DA(vR.getOrCreateGeometry(i),I)}this._currentSprite.parent!==this.gameObject&&(this.drawMode===2&&this._currentSprite.scale.set(this.size.x,this.size.y,1),this.gameObject&&this.gameObject.add(this._currentSprite)),this._currentSprite&&this._currentSprite.layers.set(this.layer),this.sharedMaterial&&(this.sharedMaterial.alphaTest=this.cutoutThreshold,this.sharedMaterial.transparent=this.transparent),this._currentSprite.castShadow=this.castShadows,(g=this._spriteSheet)==null||g.update()}}$i([w()],qC.prototype,"drawMode",2),$i([w(wt)],qC.prototype,"color",2),$i([w(Ue)],qC.prototype,"sharedMaterial",2),$i([w(kE)],qC.prototype,"sprite",1),$i([w()],qC.prototype,"transparent",2),$i([w()],qC.prototype,"cutoutThreshold",2),$i([w()],qC.prototype,"castShadows",2);class OC{constructor(){r(this,"bb",null),r(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}static getRootAsSyncedCameraModel(A,e){return(e||new OC).__init(A.readInt32(A.position())+A.position(),A)}static getSizePrefixedRootAsSyncedCameraModel(A,e){return A.setPosition(A.position()+Mu),(e||new OC).__init(A.readInt32(A.position())+A.position(),A)}userId(A){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,A):null}guid(A){const e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,A):null}dontSave(){const A=this.bb.__offset(this.bb_pos,8);return A?!!this.bb.readInt8(this.bb_pos+A):!1}pos(A){const e=this.bb.__offset(this.bb_pos,10);return e?(A||new UI).__init(this.bb_pos+e,this.bb):null}rot(A){const e=this.bb.__offset(this.bb_pos,12);return e?(A||new UI).__init(this.bb_pos+e,this.bb):null}static startSyncedCameraModel(A){A.startObject(5)}static addUserId(A,e){A.addFieldOffset(0,e,0)}static addGuid(A,e){A.addFieldOffset(1,e,0)}static addDontSave(A,e){A.addFieldInt8(2,+e,0)}static addPos(A,e){A.addFieldStruct(3,e,0)}static addRot(A,e){A.addFieldStruct(4,e,0)}static endSyncedCameraModel(A){return A.endObject()}static finishSyncedCameraModelBuffer(A,e){A.finish(e)}static finishSizePrefixedSyncedCameraModelBuffer(A,e){A.finish(e,void 0,!0)}}var sCA=Object.defineProperty,aCA=Object.getOwnPropertyDescriptor,nCA=(t,A,e,g)=>{for(var i=g>1?void 0:g?aCA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&sCA(A,e,i),i};const Dy="SCAM";Bk(Dy,OC.getRootAsSyncedCameraModel);const HI=new xE;class rCA{constructor(A,e){r(this,"userId"),r(this,"guid"),this.guid=e,this.userId=A}send(A,e){if(A){HI.clear();const g=HI.createString(this.guid),i=HI.createString(this.userId);OC.startSyncedCameraModel(HI),OC.addGuid(HI,g),OC.addUserId(HI,i);const I=we(A),o=du(A);OC.addPos(HI,UI.createVec3(HI,I.x,I.y,I.z)),OC.addRot(HI,UI.createVec3(HI,o.x,o.y,o.z));const C=OC.endSyncedCameraModel(HI);HI.finish(C,Dy),e.sendBinary(HI.asUint8Array())}}}var LR;const xR=(LR=class extends RA{constructor(){super(...arguments),r(this,"cameraPrefab",null),r(this,"_lastWorldPosition"),r(this,"_lastWorldQuaternion"),r(this,"_model",null),r(this,"_needsUpdate",!0),r(this,"_lastUpdateTime",0),r(this,"remoteCams",{}),r(this,"userToCamMap",{}),r(this,"_camTimeoutInSeconds",10),r(this,"_receiveCallback",null)}getCameraObject(t){const A=this.userToCamMap[t];return A?this.remoteCams[A].obj:null}async awake(){this._lastWorldPosition=this.worldPosition.clone(),this._lastWorldQuaternion=this.worldQuaternion.clone(),this.cameraPrefab&&("uri"in this.cameraPrefab&&(this.cameraPrefab=await this.cameraPrefab.instantiate(this.gameObject)),this.cameraPrefab&&"isObject3D"in this.cameraPrefab&&(this.cameraPrefab.visible=!1))}onEnable(){this._receiveCallback=this.context.connection.beginListenBinary(Dy,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(Dy,this._receiveCallback)}update(){for(const g in this.remoteCams){const i=this.remoteCams[g],I=this.context.time.realtimeSinceStartup-i.lastUpdate;if(!i||I>this._camTimeoutInSeconds){console.log("Remote cam timeout",i,I),i!=null&&i.obj&&eA.destroy(i.obj),delete this.remoteCams[g],i&&delete this.userToCamMap[i.userId],xR.instances.push(i),this.context.players.removePlayerView(i.userId,QC.Browser);continue}}if(Se.IsInWebXR)return;const t=this.context.mainCamera;if(t===null){this.enabled=!1;return}if(!this.context.connection.isConnected||this.context.connection.connectionId===null)return;this._model===null&&(this._model=new rCA(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));const A=we(t),e=qg(t);(A.distanceTo(this._lastWorldPosition)>.001||e.angleTo(this._lastWorldQuaternion)>.01)&&(this._needsUpdate=!0),this._lastWorldPosition.copy(A),this._lastWorldQuaternion.copy(e),!((!this._needsUpdate||this.context.time.frameCount%2!==0)&&!(this.context.time.realtimeSinceStartup-this._lastUpdateTime>this._camTimeoutInSeconds*.5))&&(this._lastUpdateTime=this.context.time.realtimeSinceStartup,this._needsUpdate=!1,this._model.send(t,this.context.connection),this.context.isInXR||this.context.players.setPlayerView(this.context.connection.connectionId,t,QC.Browser))}onReceivedRemoteCameraInfoBin(t){const A=t.guid();if(!A)return;const e=t.userId();if(!e||!this.context.connection.userIsInRoom(e)||!this.cameraPrefab)return;let g=this.remoteCams[A];if(!g)if("isObject3D"in this.cameraPrefab){const C=new rC;C.context=this.context;const s=eA.instantiate(this.cameraPrefab,C);g=this.remoteCams[A]={obj:s,lastUpdate:this.context.time.realtimeSinceStartup,userId:e},g.obj.visible=!0,this.gameObject.add(s),this.userToCamMap[e]=A,xR.instances.push(g);const a=eA.getOrAddComponent(s,fi);a.connectionId=e,a.avatar=s}else return;const i=g.obj;this.context.players.setPlayerView(e,i,QC.Browser),g.lastUpdate=this.context.time.realtimeSinceStartup,pI.markDirty(i);const I=t.pos();I&&ZB(i,I.x(),I.y(),I.z());const o=t.rot();o&&pu(i,o.x(),o.y(),o.z())}},r(LR,"instances",[]),LR);let wy=xR;nCA([w([UA,yi])],wy.prototype,"cameraPrefab",2);var BCA=Object.defineProperty,QCA=Object.getOwnPropertyDescriptor,Vl=(t,A,e,g)=>{for(var i=g>1?void 0:g?QCA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&BCA(A,e,i),i};const YR="view",HR=CA("debugsyncedroom");class fn extends RA{constructor(){super(...arguments),r(this,"roomName"),r(this,"urlParameterName","room"),r(this,"joinRandomRoom",!0),r(this,"requireRoomParameter",!1),r(this,"autoRejoin",!0),r(this,"_roomPrefix"),r(this,"_lastPingTime",0),r(this,"_lastRoomTime",-1)}get RoomPrefix(){return this._roomPrefix}awake(){HR&&console.log("Room",this.roomName,this.urlParameterName,this.joinRandomRoom,this.requireRoomParameter,this.autoRejoin),this._roomPrefix===void 0&&(this._roomPrefix=this.roomName,this.roomName="")}onEnable(){const A=CA(YR);if(A&&typeof A=="string"&&A.length>0){console.log("Join as viewer"),this.context.connection.joinRoom(A,!0);return}(this.joinRandomRoom||CA(this.urlParameterName))&&this.tryJoinRoom()}onDisable(){this.roomName&&this.roomName.length>0&&this.context.connection.leaveRoom(this.roomName)}tryJoinRandomRoom(){this.setRandomRoomUrlParameter(),this.tryJoinRoom()}tryJoinRoom(A=0){A===void 0&&(A=0);let e=!1;if(this.urlParameterName){const g=CA(this.urlParameterName);if(g&&typeof g=="string"){e=!0;const i=zU(g);this.roomName=i}else if(this.joinRandomRoom&&(console.log("No room name found in url, generating random one"),this.setRandomRoomUrlParameter(),A<1))return this.tryJoinRoom(A+1)}else this.joinRandomRoom&&(this.roomName===null||this.roomName===void 0||this.roomName.length<=0)&&(console.log("generate room name"),this.roomName=this.generateRoomName());return this.requireRoomParameter&&!e?(HR&&console.log('No required room parameter "'+this.urlParameterName+'" in url - will not connect to networking backend.'),!1):(this.context.connection.isConnected||this.context.connection.connect(),HR&&console.log("Join "+this.roomName),this._roomPrefix&&(this.roomName=this._roomPrefix+this.roomName),this.context.connection.joinRoom(this.roomName),!0)}update(){this.context.connection.isConnected&&(this.context.time.time-this._lastPingTime>3&&(this._lastPingTime=this.context.time.time,this.context.connection.sendPing()),this.context.connection.isInRoom&&(this._lastRoomTime=this.context.time.time)),this._lastRoomTime>0&&this.context.time.time-this._lastRoomTime>.3&&(this._lastRoomTime=-1,this.autoRejoin?(console.log("Disconnected from networking backend - attempt reconnecting now"),this.tryJoinRoom()):console.warn("You are not connected to a room anymore (possibly because the tab was inactive for too long and the server kicked you)"))}get currentRoomName(){return CA(YR)||CA(this.urlParameterName)}setRandomRoomUrlParameter(){const A=zE(),e=this.generateRoomName();CA(this.urlParameterName)?A.set(this.urlParameterName,e):A.append(this.urlParameterName,e),KS(e,A)}generateRoomName(){return VU()+"_"+PU(100,999)}getViewOnlyUrl(){if(this.context.connection.isConnected&&this.context.connection.currentRoomViewId){const A=window.location.search,e=new URLSearchParams(A);return e.has(this.urlParameterName)&&e.delete(this.urlParameterName),e.set(YR,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+e.toString()}return null}}Vl([w()],fn.prototype,"roomName",2),Vl([w()],fn.prototype,"urlParameterName",2),Vl([w()],fn.prototype,"joinRandomRoom",2),Vl([w()],fn.prototype,"requireRoomParameter",2),Vl([w()],fn.prototype,"autoRejoin",2);function ECA(){const t=CA("testwindowcount")||0;t&&t>0&&hCA(t)}function hCA(t){if(CA("testwindow"))return null;const A=new URL(window.location.href);ZE(A.searchParams,_D,1),ZE(A.searchParams,"testwindow",1);const e=A.toString(),g=[];window.onbeforeunload=()=>{for(const s of g)s.close()};const i=.05,I=128;let o=0,C=0;for(let s=0;s<t;s++){o*I+I*.01>=window.innerWidth&&(C+=1,o=0);const a=o*(I*(1+i))+window.screenLeft,n=C*(I*(1+i))+window.screenTop+90+60*C;o+=1;const B=window.open(e,"test window "+s,`popup=yes width=${I} height=${I} top=${n} left=${a}`);if(!B){console.warn("Failed to open window");continue}g.push(B),B.onload=()=>{B.onbeforeunload=()=>{for(let Q=0;Q<g.length;Q++){const E=g[Q];E!==B&&E.close()}g.length=0}}}return g}class TR extends RA{awake(){ECA()}}class OR extends RA{constructor(){super(...arguments),r(this,"transformsPerFrame",10),r(this,"interval",0),r(this,"useFlatbuffers",!0),r(this,"builder",null),r(this,"models",null)}awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinary(bc,A=>{});else{this.models=[];for(let A=0;A<this.transformsPerFrame;A++)this.models.push(new R2(this.context.connection.connectionId+"_simulatedTransform_"+A,this))}}update(){if(this.context.connection.isConnected){if(this.useFlatbuffers){if(!this.context.connection.connectionId||this.context.time.frameCount%this.interval!==0)return;this.builder===null&&(this.builder=new xE(1024));const A=this.builder;for(let e=0;e<this.transformsPerFrame;e++){A.clear();const g=BY(this.context.connection.connectionId,this);this.context.connection.sendBinary(g)}}else if(this.models)for(let A=0;A<this.models.length;A++){const e=this.models[A];e.dontSave=!0,e.update(this,null),this.context.connection.send("TestSimulateUserData-"+A,e)}}}}class R2{constructor(A,e){r(this,"guid"),r(this,"fast",!1),r(this,"position"),r(this,"rotation"),r(this,"velocity"),r(this,"dontSave"),this.guid=A,this.position={x:0,y:0,z:0},this.rotation={x:0,y:0,z:0,w:0},this.update(e,null)}isValid(){return this.fast!==void 0||this.position!==void 0||this.rotation!==void 0||this.velocity!==void 0}update(A,e){const g=A.worldPosition;this.position.x=g.x,this.position.y=g.y,this.position.z=g.z;const i=A.worldQuaternion;if(this.rotation.x=i.x,this.rotation.y=i.y,this.rotation.z=i.z,this.rotation.w=i.w,this.fast=!1,e){const I=e.getVelocity();this.velocity===void 0&&(this.velocity={x:0,y:0,z:0}),this.velocity.x=I.x,this.velocity.y=I.y,this.velocity.z=I.z}}}r(R2,"temp",new f);var cCA=Object.defineProperty,lCA=Object.getOwnPropertyDescriptor,GE=(t,A,e,g)=>{for(var i=g>1?void 0:g?lCA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&cCA(A,e,i),i};class vC extends ki{constructor(){super(...arguments),r(this,"offset"),r(this,"rotation"),r(this,"focusArea"),r(this,"feather"),r(this,"kernelSize"),r(this,"resolutionScale")}get typeName(){return"TiltShiftEffect"}init(){this.offset.defaultValue=0,this.rotation.defaultValue=0,this.focusArea.defaultValue=.4,this.feather.defaultValue=.3,this.kernelSize.defaultValue=ws.MEDIUM,this.resolutionScale.defaultValue=1/window.devicePixelRatio}onCreateEffect(){console.log(this);const A=new lZ({kernelSize:ws.VERY_LARGE});return this.offset.onValueChanged=e=>A.offset=e,this.rotation.onValueChanged=e=>A.rotation=e,this.focusArea.onValueChanged=e=>A.focusArea=e,this.feather.onValueChanged=e=>A.feather=e,this.kernelSize.onValueChanged=e=>A.blurPass.kernelSize=e,this.resolutionScale.onValueChanged=e=>A.resolution.scale=e/window.devicePixelRatio,A}}GE([w(Ge)],vC.prototype,"offset",2),GE([w(Ge)],vC.prototype,"rotation",2),GE([w(Ge)],vC.prototype,"focusArea",2),GE([w(Ge)],vC.prototype,"feather",2),GE([w(Ge)],vC.prototype,"kernelSize",2),GE([w(Ge)],vC.prototype,"resolutionScale",2),po("TiltShiftEffect",vC);var dCA=Object.defineProperty,pCA=Object.getOwnPropertyDescriptor,uCA=(t,A,e,g)=>{for(var i=g>1?void 0:g?pCA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&dCA(A,e,i),i};class zl extends ki{constructor(){super(...arguments),r(this,"mode")}get typeName(){return"ToneMapping"}get isToneMapping(){return!0}init(){this.mode.defaultValue=Ki}apply(){this.mode.onValueChanged=this._apply.bind(this),this._apply(this.mode.value)}unapply(){this.context.renderer.toneMapping=Ki}_apply(A){switch(A){case 0:this.context.renderer.toneMapping=gh;break;case 1:this.context.renderer.toneMapping=ZS;break;case 2:this.context.renderer.toneMapping=XS;break}}}uCA([w(Ge)],zl.prototype,"mode",2),po("Tonemapping",zl);const AB=new VB,cI=new f,kn=new f,xt=new mA,U2={X:new f(1,0,0),Y:new f(0,1,0),Z:new f(0,0,1)},_R={type:"change"},F2={type:"mouseDown"},N2={type:"mouseUp",mode:null},K2={type:"objectChange"};class DCA extends UA{constructor(A,e){super(),e===void 0&&(console.warn('THREE.TransformControls: The second parameter "domElement" is now mandatory.'),e=document),this.isTransformControls=!0,this.visible=!1,this.domElement=e,this.domElement.style.touchAction="none";const g=new GCA;this._gizmo=g,this.add(g);const i=new mCA;this._plane=i,this.add(i);const I=this;function o(u,p){let D=p;Object.defineProperty(I,u,{get:function(){return D!==void 0?D:p},set:function(y){D!==y&&(D=y,i[u]=y,g[u]=y,I.dispatchEvent({type:u+"-changed",value:y}),I.dispatchEvent(_R))}}),I[u]=p,i[u]=p,g[u]=p}o("camera",A),o("object",void 0),o("enabled",!0),o("axis",null),o("mode","translate"),o("translationSnap",null),o("rotationSnap",null),o("scaleSnap",null),o("space","world"),o("size",1),o("dragging",!1),o("showX",!0),o("showY",!0),o("showZ",!0);const C=new f,s=new f,a=new mA,n=new mA,B=new f,Q=new mA,E=new f,h=new f,c=new f,l=0,d=new f;o("worldPosition",C),o("worldPositionStart",s),o("worldQuaternion",a),o("worldQuaternionStart",n),o("cameraPosition",B),o("cameraQuaternion",Q),o("pointStart",E),o("pointEnd",h),o("rotationAxis",c),o("rotationAngle",l),o("eye",d),this._offset=new f,this._startNorm=new f,this._endNorm=new f,this._cameraScale=new f,this._parentPosition=new f,this._parentQuaternion=new mA,this._parentQuaternionInv=new mA,this._parentScale=new f,this._worldScaleStart=new f,this._worldQuaternionInv=new mA,this._worldScale=new f,this._positionStart=new f,this._quaternionStart=new mA,this._scaleStart=new f,this._getPointer=wCA.bind(this),this._onPointerDown=SCA.bind(this),this._onPointerHover=yCA.bind(this),this._onPointerMove=fCA.bind(this),this._onPointerUp=kCA.bind(this),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointermove",this._onPointerHover),this.domElement.addEventListener("pointerup",this._onPointerUp)}updateMatrixWorld(){this.object!==void 0&&(this.object.updateMatrixWorld(),this.object.parent===null?console.error("TransformControls: The attached 3D object must be a part of the scene graph."):this.object.parent.matrixWorld.decompose(this._parentPosition,this._parentQuaternion,this._parentScale),this.object.matrixWorld.decompose(this.worldPosition,this.worldQuaternion,this._worldScale),this._parentQuaternionInv.copy(this._parentQuaternion).invert(),this._worldQuaternionInv.copy(this.worldQuaternion).invert()),this.camera.updateMatrixWorld(),this.camera.matrixWorld.decompose(this.cameraPosition,this.cameraQuaternion,this._cameraScale),this.camera.isOrthographicCamera?this.camera.getWorldDirection(this.eye).negate():this.eye.copy(this.cameraPosition).sub(this.worldPosition).normalize(),super.updateMatrixWorld(this)}pointerHover(A){if(this.object===void 0||this.dragging===!0)return;AB.setFromCamera(A,this.camera);const e=PR(this._gizmo.picker[this.mode],AB);e?this.axis=e.object.name:this.axis=null}pointerDown(A){if(!(this.object===void 0||this.dragging===!0||A.button!==0)&&this.axis!==null){AB.setFromCamera(A,this.camera);const e=PR(this._plane,AB,!0);e&&(this.object.updateMatrixWorld(),this.object.parent.updateMatrixWorld(),this._positionStart.copy(this.object.position),this._quaternionStart.copy(this.object.quaternion),this._scaleStart.copy(this.object.scale),this.object.matrixWorld.decompose(this.worldPositionStart,this.worldQuaternionStart,this._worldScaleStart),this.pointStart.copy(e.point).sub(this.worldPositionStart)),this.dragging=!0,F2.mode=this.mode,this.dispatchEvent(F2)}}pointerMove(A){const e=this.axis,g=this.mode,i=this.object;let I=this.space;if(g==="scale"?I="local":(e==="E"||e==="XYZE"||e==="XYZ")&&(I="world"),i===void 0||e===null||this.dragging===!1||A.button!==-1)return;AB.setFromCamera(A,this.camera);const o=PR(this._plane,AB,!0);if(o){if(this.pointEnd.copy(o.point).sub(this.worldPositionStart),g==="translate")this._offset.copy(this.pointEnd).sub(this.pointStart),I==="local"&&e!=="XYZ"&&this._offset.applyQuaternion(this._worldQuaternionInv),e.indexOf("X")===-1&&(this._offset.x=0),e.indexOf("Y")===-1&&(this._offset.y=0),e.indexOf("Z")===-1&&(this._offset.z=0),I==="local"&&e!=="XYZ"?this._offset.applyQuaternion(this._quaternionStart).divide(this._parentScale):this._offset.applyQuaternion(this._parentQuaternionInv).divide(this._parentScale),i.position.copy(this._offset).add(this._positionStart),this.translationSnap&&(I==="local"&&(i.position.applyQuaternion(xt.copy(this._quaternionStart).invert()),e.search("X")!==-1&&(i.position.x=Math.round(i.position.x/this.translationSnap)*this.translationSnap),e.search("Y")!==-1&&(i.position.y=Math.round(i.position.y/this.translationSnap)*this.translationSnap),e.search("Z")!==-1&&(i.position.z=Math.round(i.position.z/this.translationSnap)*this.translationSnap),i.position.applyQuaternion(this._quaternionStart)),I==="world"&&(i.parent&&i.position.add(cI.setFromMatrixPosition(i.parent.matrixWorld)),e.search("X")!==-1&&(i.position.x=Math.round(i.position.x/this.translationSnap)*this.translationSnap),e.search("Y")!==-1&&(i.position.y=Math.round(i.position.y/this.translationSnap)*this.translationSnap),e.search("Z")!==-1&&(i.position.z=Math.round(i.position.z/this.translationSnap)*this.translationSnap),i.parent&&i.position.sub(cI.setFromMatrixPosition(i.parent.matrixWorld))));else if(g==="scale"){if(e.search("XYZ")!==-1){let C=this.pointEnd.length()/this.pointStart.length();this.pointEnd.dot(this.pointStart)<0&&(C*=-1),kn.set(C,C,C)}else cI.copy(this.pointStart),kn.copy(this.pointEnd),cI.applyQuaternion(this._worldQuaternionInv),kn.applyQuaternion(this._worldQuaternionInv),kn.divide(cI),e.search("X")===-1&&(kn.x=1),e.search("Y")===-1&&(kn.y=1),e.search("Z")===-1&&(kn.z=1);i.scale.copy(this._scaleStart).multiply(kn),this.scaleSnap&&(e.search("X")!==-1&&(i.scale.x=Math.round(i.scale.x/this.scaleSnap)*this.scaleSnap||this.scaleSnap),e.search("Y")!==-1&&(i.scale.y=Math.round(i.scale.y/this.scaleSnap)*this.scaleSnap||this.scaleSnap),e.search("Z")!==-1&&(i.scale.z=Math.round(i.scale.z/this.scaleSnap)*this.scaleSnap||this.scaleSnap))}else if(g==="rotate"){this._offset.copy(this.pointEnd).sub(this.pointStart);const C=20/this.worldPosition.distanceTo(cI.setFromMatrixPosition(this.camera.matrixWorld));e==="E"?(this.rotationAxis.copy(this.eye),this.rotationAngle=this.pointEnd.angleTo(this.pointStart),this._startNorm.copy(this.pointStart).normalize(),this._endNorm.copy(this.pointEnd).normalize(),this.rotationAngle*=this._endNorm.cross(this._startNorm).dot(this.eye)<0?1:-1):e==="XYZE"?(this.rotationAxis.copy(this._offset).cross(this.eye).normalize(),this.rotationAngle=this._offset.dot(cI.copy(this.rotationAxis).cross(this.eye))*C):(e==="X"||e==="Y"||e==="Z")&&(this.rotationAxis.copy(U2[e]),cI.copy(U2[e]),I==="local"&&cI.applyQuaternion(this.worldQuaternion),this.rotationAngle=this._offset.dot(cI.cross(this.eye).normalize())*C),this.rotationSnap&&(this.rotationAngle=Math.round(this.rotationAngle/this.rotationSnap)*this.rotationSnap),I==="local"&&e!=="E"&&e!=="XYZE"?(i.quaternion.copy(this._quaternionStart),i.quaternion.multiply(xt.setFromAxisAngle(this.rotationAxis,this.rotationAngle)).normalize()):(this.rotationAxis.applyQuaternion(this._parentQuaternionInv),i.quaternion.copy(xt.setFromAxisAngle(this.rotationAxis,this.rotationAngle)),i.quaternion.multiply(this._quaternionStart).normalize())}this.dispatchEvent(_R),this.dispatchEvent(K2)}}pointerUp(A){A.button===0&&(this.dragging&&this.axis!==null&&(N2.mode=this.mode,this.dispatchEvent(N2)),this.dragging=!1,this.axis=null)}dispose(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerHover),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.traverse(function(A){A.geometry&&A.geometry.dispose(),A.material&&A.material.dispose()})}attach(A){return this.object=A,this.visible=!0,this}detach(){return this.object=void 0,this.visible=!1,this.axis=null,this}reset(){this.enabled&&this.dragging&&(this.object.position.copy(this._positionStart),this.object.quaternion.copy(this._quaternionStart),this.object.scale.copy(this._scaleStart),this.dispatchEvent(_R),this.dispatchEvent(K2),this.pointStart.copy(this.pointEnd))}getRaycaster(){return AB}getMode(){return this.mode}setMode(A){this.mode=A}setTranslationSnap(A){this.translationSnap=A}setRotationSnap(A){this.rotationSnap=A}setScaleSnap(A){this.scaleSnap=A}setSize(A){this.size=A}setSpace(A){this.space=A}}function wCA(t){if(this.domElement.ownerDocument.pointerLockElement)return{x:0,y:0,button:t.button};{const A=this.domElement.getBoundingClientRect();return{x:(t.clientX-A.left)/A.width*2-1,y:-(t.clientY-A.top)/A.height*2+1,button:t.button}}}function yCA(t){if(this.enabled)switch(t.pointerType){case"mouse":case"pen":this.pointerHover(this._getPointer(t));break}}function SCA(t){this.enabled&&(document.pointerLockElement||this.domElement.setPointerCapture(t.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.pointerHover(this._getPointer(t)),this.pointerDown(this._getPointer(t)))}function fCA(t){this.enabled&&this.pointerMove(this._getPointer(t))}function kCA(t){this.enabled&&(this.domElement.releasePointerCapture(t.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.pointerUp(this._getPointer(t)))}function PR(t,A,e){const g=A.intersectObject(t,!0);for(let i=0;i<g.length;i++)if(g[i].object.visible||e)return g[i];return!1}const yy=new mg,St=new f(0,1,0),J2=new f(0,0,0),q2=new KA,Sy=new mA,fy=new mA,bC=new f,v2=new KA,Zl=new f(1,0,0),eB=new f(0,1,0),Xl=new f(0,0,1),ky=new f,$l=new f,Ad=new f;class GCA extends UA{constructor(){super(),this.isTransformControlsGizmo=!0,this.type="TransformControlsGizmo";const A=new dt({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),e=new Ag({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),g=A.clone();g.opacity=.15;const i=e.clone();i.opacity=.5;const I=A.clone();I.color.setHex(16711680);const o=A.clone();o.color.setHex(65280);const C=A.clone();C.color.setHex(255);const s=A.clone();s.color.setHex(16711680),s.opacity=.5;const a=A.clone();a.color.setHex(65280),a.opacity=.5;const n=A.clone();n.color.setHex(255),n.opacity=.5;const B=A.clone();B.opacity=.25;const Q=A.clone();Q.color.setHex(16776960),Q.opacity=.25,A.clone().color.setHex(16776960);const E=A.clone();E.color.setHex(7895160);const h=new Zt(0,.04,.1,12);h.translate(0,.05,0);const c=new ct(.08,.08,.08);c.translate(0,.04,0);const l=new le;l.setAttribute("position",new ee([0,0,0,1,0,0],3));const d=new Zt(.0075,.0075,.5,3);d.translate(0,.25,0);function u(b,z){const gA=new HC(b,.0075,3,64,z*Math.PI*2);return gA.rotateY(Math.PI/2),gA.rotateX(Math.PI/2),gA}function p(){const b=new le;return b.setAttribute("position",new ee([0,0,0,1,1,1],3)),b}const D={X:[[new DA(h,I),[.5,0,0],[0,0,-Math.PI/2]],[new DA(h,I),[-.5,0,0],[0,0,Math.PI/2]],[new DA(d,I),[0,0,0],[0,0,-Math.PI/2]]],Y:[[new DA(h,o),[0,.5,0]],[new DA(h,o),[0,-.5,0],[Math.PI,0,0]],[new DA(d,o)]],Z:[[new DA(h,C),[0,0,.5],[Math.PI/2,0,0]],[new DA(h,C),[0,0,-.5],[-Math.PI/2,0,0]],[new DA(d,C),null,[Math.PI/2,0,0]]],XYZ:[[new DA(new YC(.1,0),B.clone()),[0,0,0]]],XY:[[new DA(new ct(.15,.15,.01),n.clone()),[.15,.15,0]]],YZ:[[new DA(new ct(.15,.15,.01),s.clone()),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new DA(new ct(.15,.15,.01),a.clone()),[.15,0,.15],[-Math.PI/2,0,0]]]},y={X:[[new DA(new Zt(.2,0,.6,4),g),[.3,0,0],[0,0,-Math.PI/2]],[new DA(new Zt(.2,0,.6,4),g),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new DA(new Zt(.2,0,.6,4),g),[0,.3,0]],[new DA(new Zt(.2,0,.6,4),g),[0,-.3,0],[0,0,Math.PI]]],Z:[[new DA(new Zt(.2,0,.6,4),g),[0,0,.3],[Math.PI/2,0,0]],[new DA(new Zt(.2,0,.6,4),g),[0,0,-.3],[-Math.PI/2,0,0]]],XYZ:[[new DA(new YC(.2,0),g)]],XY:[[new DA(new ct(.2,.2,.01),g),[.15,.15,0]]],YZ:[[new DA(new ct(.2,.2,.01),g),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new DA(new ct(.2,.2,.01),g),[.15,0,.15],[-Math.PI/2,0,0]]]},k={START:[[new DA(new YC(.01,2),i),null,null,null,"helper"]],END:[[new DA(new YC(.01,2),i),null,null,null,"helper"]],DELTA:[[new eg(p(),i),null,null,null,"helper"]],X:[[new eg(l,i.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new eg(l,i.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new eg(l,i.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},F={XYZE:[[new DA(u(.5,1),E),null,[0,Math.PI/2,0]]],X:[[new DA(u(.5,.5),I)]],Y:[[new DA(u(.5,.5),o),null,[0,0,-Math.PI/2]]],Z:[[new DA(u(.5,.5),C),null,[0,Math.PI/2,0]]],E:[[new DA(u(.75,1),Q),null,[0,Math.PI/2,0]]]},S={AXIS:[[new eg(l,i.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]]},U={XYZE:[[new DA(new OI(.25,10,8),g)]],X:[[new DA(new HC(.5,.1,4,24),g),[0,0,0],[0,-Math.PI/2,-Math.PI/2]]],Y:[[new DA(new HC(.5,.1,4,24),g),[0,0,0],[Math.PI/2,0,0]]],Z:[[new DA(new HC(.5,.1,4,24),g),[0,0,0],[0,0,-Math.PI/2]]],E:[[new DA(new HC(.75,.1,2,24),g)]]},M={X:[[new DA(c,I),[.5,0,0],[0,0,-Math.PI/2]],[new DA(d,I),[0,0,0],[0,0,-Math.PI/2]],[new DA(c,I),[-.5,0,0],[0,0,Math.PI/2]]],Y:[[new DA(c,o),[0,.5,0]],[new DA(d,o)],[new DA(c,o),[0,-.5,0],[0,0,Math.PI]]],Z:[[new DA(c,C),[0,0,.5],[Math.PI/2,0,0]],[new DA(d,C),[0,0,0],[Math.PI/2,0,0]],[new DA(c,C),[0,0,-.5],[-Math.PI/2,0,0]]],XY:[[new DA(new ct(.15,.15,.01),n),[.15,.15,0]]],YZ:[[new DA(new ct(.15,.15,.01),s),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new DA(new ct(.15,.15,.01),a),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new DA(new ct(.1,.1,.1),B.clone())]]},Y={X:[[new DA(new Zt(.2,0,.6,4),g),[.3,0,0],[0,0,-Math.PI/2]],[new DA(new Zt(.2,0,.6,4),g),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new DA(new Zt(.2,0,.6,4),g),[0,.3,0]],[new DA(new Zt(.2,0,.6,4),g),[0,-.3,0],[0,0,Math.PI]]],Z:[[new DA(new Zt(.2,0,.6,4),g),[0,0,.3],[Math.PI/2,0,0]],[new DA(new Zt(.2,0,.6,4),g),[0,0,-.3],[-Math.PI/2,0,0]]],XY:[[new DA(new ct(.2,.2,.01),g),[.15,.15,0]]],YZ:[[new DA(new ct(.2,.2,.01),g),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new DA(new ct(.2,.2,.01),g),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new DA(new ct(.2,.2,.2),g),[0,0,0]]]},O={X:[[new eg(l,i.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new eg(l,i.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new eg(l,i.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]};function x(b){const z=new UA;for(const gA in b)for(let sA=b[gA].length;sA--;){const AA=b[gA][sA][0].clone(),dA=b[gA][sA][1],rA=b[gA][sA][2],LA=b[gA][sA][3],MA=b[gA][sA][4];AA.name=gA,AA.tag=MA,dA&&AA.position.set(dA[0],dA[1],dA[2]),rA&&AA.rotation.set(rA[0],rA[1],rA[2]),LA&&AA.scale.set(LA[0],LA[1],LA[2]),AA.updateMatrix();const iA=AA.geometry.clone();iA.applyMatrix4(AA.matrix),AA.geometry=iA,AA.renderOrder=1/0,AA.position.set(0,0,0),AA.rotation.set(0,0,0),AA.scale.set(1,1,1),z.add(AA)}return z}this.gizmo={},this.picker={},this.helper={},this.add(this.gizmo.translate=x(D)),this.add(this.gizmo.rotate=x(F)),this.add(this.gizmo.scale=x(M)),this.add(this.picker.translate=x(y)),this.add(this.picker.rotate=x(U)),this.add(this.picker.scale=x(Y)),this.add(this.helper.translate=x(k)),this.add(this.helper.rotate=x(S)),this.add(this.helper.scale=x(O)),this.picker.translate.visible=!1,this.picker.rotate.visible=!1,this.picker.scale.visible=!1}updateMatrixWorld(A){const e=(this.mode==="scale"?"local":this.space)==="local"?this.worldQuaternion:fy;this.gizmo.translate.visible=this.mode==="translate",this.gizmo.rotate.visible=this.mode==="rotate",this.gizmo.scale.visible=this.mode==="scale",this.helper.translate.visible=this.mode==="translate",this.helper.rotate.visible=this.mode==="rotate",this.helper.scale.visible=this.mode==="scale";let g=[];g=g.concat(this.picker[this.mode].children),g=g.concat(this.gizmo[this.mode].children),g=g.concat(this.helper[this.mode].children);for(let i=0;i<g.length;i++){const I=g[i];I.visible=!0,I.rotation.set(0,0,0),I.position.copy(this.worldPosition);let o;if(this.camera.isOrthographicCamera?o=(this.camera.top-this.camera.bottom)/this.camera.zoom:o=this.worldPosition.distanceTo(this.cameraPosition)*Math.min(1.9*Math.tan(Math.PI*this.camera.fov/360)/this.camera.zoom,7),I.scale.set(1,1,1).multiplyScalar(o*this.size/4),I.tag==="helper"){I.visible=!1,I.name==="AXIS"?(I.position.copy(this.worldPositionStart),I.visible=!!this.axis,this.axis==="X"&&(xt.setFromEuler(yy.set(0,0,0)),I.quaternion.copy(e).multiply(xt),Math.abs(St.copy(Zl).applyQuaternion(e).dot(this.eye))>.9&&(I.visible=!1)),this.axis==="Y"&&(xt.setFromEuler(yy.set(0,0,Math.PI/2)),I.quaternion.copy(e).multiply(xt),Math.abs(St.copy(eB).applyQuaternion(e).dot(this.eye))>.9&&(I.visible=!1)),this.axis==="Z"&&(xt.setFromEuler(yy.set(0,Math.PI/2,0)),I.quaternion.copy(e).multiply(xt),Math.abs(St.copy(Xl).applyQuaternion(e).dot(this.eye))>.9&&(I.visible=!1)),this.axis==="XYZE"&&(xt.setFromEuler(yy.set(0,Math.PI/2,0)),St.copy(this.rotationAxis),I.quaternion.setFromRotationMatrix(q2.lookAt(J2,St,eB)),I.quaternion.multiply(xt),I.visible=this.dragging),this.axis==="E"&&(I.visible=!1)):I.name==="START"?(I.position.copy(this.worldPositionStart),I.visible=this.dragging):I.name==="END"?(I.position.copy(this.worldPosition),I.visible=this.dragging):I.name==="DELTA"?(I.position.copy(this.worldPositionStart),I.quaternion.copy(this.worldQuaternionStart),cI.set(1e-10,1e-10,1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1),cI.applyQuaternion(this.worldQuaternionStart.clone().invert()),I.scale.copy(cI),I.visible=this.dragging):(I.quaternion.copy(e),this.dragging?I.position.copy(this.worldPositionStart):I.position.copy(this.worldPosition),this.axis&&(I.visible=this.axis.search(I.name)!==-1));continue}I.quaternion.copy(e),this.mode==="translate"||this.mode==="scale"?(I.name==="X"&&Math.abs(St.copy(Zl).applyQuaternion(e).dot(this.eye))>.99&&(I.scale.set(1e-10,1e-10,1e-10),I.visible=!1),I.name==="Y"&&Math.abs(St.copy(eB).applyQuaternion(e).dot(this.eye))>.99&&(I.scale.set(1e-10,1e-10,1e-10),I.visible=!1),I.name==="Z"&&Math.abs(St.copy(Xl).applyQuaternion(e).dot(this.eye))>.99&&(I.scale.set(1e-10,1e-10,1e-10),I.visible=!1),I.name==="XY"&&Math.abs(St.copy(Xl).applyQuaternion(e).dot(this.eye))<.2&&(I.scale.set(1e-10,1e-10,1e-10),I.visible=!1),I.name==="YZ"&&Math.abs(St.copy(Zl).applyQuaternion(e).dot(this.eye))<.2&&(I.scale.set(1e-10,1e-10,1e-10),I.visible=!1),I.name==="XZ"&&Math.abs(St.copy(eB).applyQuaternion(e).dot(this.eye))<.2&&(I.scale.set(1e-10,1e-10,1e-10),I.visible=!1)):this.mode==="rotate"&&(Sy.copy(e),St.copy(this.eye).applyQuaternion(xt.copy(e).invert()),I.name.search("E")!==-1&&I.quaternion.setFromRotationMatrix(q2.lookAt(this.eye,J2,eB)),I.name==="X"&&(xt.setFromAxisAngle(Zl,Math.atan2(-St.y,St.z)),xt.multiplyQuaternions(Sy,xt),I.quaternion.copy(xt)),I.name==="Y"&&(xt.setFromAxisAngle(eB,Math.atan2(St.x,St.z)),xt.multiplyQuaternions(Sy,xt),I.quaternion.copy(xt)),I.name==="Z"&&(xt.setFromAxisAngle(Xl,Math.atan2(St.y,St.x)),xt.multiplyQuaternions(Sy,xt),I.quaternion.copy(xt))),I.visible=I.visible&&(I.name.indexOf("X")===-1||this.showX),I.visible=I.visible&&(I.name.indexOf("Y")===-1||this.showY),I.visible=I.visible&&(I.name.indexOf("Z")===-1||this.showZ),I.visible=I.visible&&(I.name.indexOf("E")===-1||this.showX&&this.showY&&this.showZ),I.material._color=I.material._color||I.material.color.clone(),I.material._opacity=I.material._opacity||I.material.opacity,I.material.color.copy(I.material._color),I.material.opacity=I.material._opacity,this.enabled&&this.axis&&(I.name===this.axis||this.axis.split("").some(function(C){return I.name===C}))&&(I.material.color.setHex(16776960),I.material.opacity=1)}super.updateMatrixWorld(A)}}class mCA extends DA{constructor(){super(new Zg(1e5,1e5,2,2),new dt({visible:!1,wireframe:!0,side:ft,transparent:!0,opacity:.1,toneMapped:!1})),this.isTransformControlsPlane=!0,this.type="TransformControlsPlane"}updateMatrixWorld(A){let e=this.space;switch(this.position.copy(this.worldPosition),this.mode==="scale"&&(e="local"),ky.copy(Zl).applyQuaternion(e==="local"?this.worldQuaternion:fy),$l.copy(eB).applyQuaternion(e==="local"?this.worldQuaternion:fy),Ad.copy(Xl).applyQuaternion(e==="local"?this.worldQuaternion:fy),St.copy($l),this.mode){case"translate":case"scale":switch(this.axis){case"X":St.copy(this.eye).cross(ky),bC.copy(ky).cross(St);break;case"Y":St.copy(this.eye).cross($l),bC.copy($l).cross(St);break;case"Z":St.copy(this.eye).cross(Ad),bC.copy(Ad).cross(St);break;case"XY":bC.copy(Ad);break;case"YZ":bC.copy(ky);break;case"XZ":St.copy(Ad),bC.copy($l);break;case"XYZ":case"E":bC.set(0,0,0);break}break;case"rotate":default:bC.set(0,0,0)}bC.length()===0?this.quaternion.copy(this.cameraQuaternion):(v2.lookAt(cI.set(0,0,0),bC,St),this.quaternion.setFromRotationMatrix(v2)),super.updateMatrixWorld(A)}}var MCA=Object.defineProperty,RCA=Object.getOwnPropertyDescriptor,Gy=(t,A,e,g)=>{for(var i=g>1?void 0:g?RCA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&MCA(A,e,i),i};class tB extends RA{constructor(){super(...arguments),r(this,"isGizmo",!1),r(this,"translationSnap",1),r(this,"rotationSnapAngle",15),r(this,"scaleSnap",.25),r(this,"control"),r(this,"orbit"),r(this,"changeEventListener"),r(this,"windowKeyDownListener"),r(this,"windowKeyUpListener")}onEnable(){var A;this.isGizmo&&!vh||this.context.mainCamera&&(this.control||(this.control=new DCA(this.context.mainCamera,this.context.domElement),this.control.visible=!0,this.control.enabled=!0,this.control.getRaycaster().layers.set(2),this.control.size=1,this.control.traverse(e=>{const g=e;if(g.layers.set(2),g){const i=g.material;i&&(i.opacity=.3)}}),this.orbit=eA.getComponentInParent(this.context.mainCamera,Ts)??void 0),this.control&&(this.context.scene.add(this.control),this.control.attach(this.gameObject),this.changeEventListener=this.onControlChangedEvent.bind(this),(A=this.control)==null||A.addEventListener("dragging-changed",this.changeEventListener),this.addWindowEvents()))}onDisable(){var A,e;(A=this.control)==null||A.removeFromParent(),this.changeEventListener&&((e=this.control)==null||e.removeEventListener("dragging-changed",this.changeEventListener)),this.removeWindowEvents()}enableSnapping(){this.control&&(this.control.setTranslationSnap(this.translationSnap),this.control.setRotationSnap(Ji.degToRad(this.rotationSnapAngle)),this.control.setScaleSnap(this.scaleSnap))}disableSnapping(){this.control&&(this.control.setTranslationSnap(null),this.control.setRotationSnap(null),this.control.setScaleSnap(null))}onControlChangedEvent(A){const e=this.orbit;if(e&&(e.enabled=!A.value),A.value){const g=eA.getComponentInParent(this.gameObject,Cn);g&&g.requestOwnership()}}addWindowEvents(){const A=this.control;A&&(this.windowKeyDownListener||(this.windowKeyDownListener=e=>{if(this.enabled)switch(e.keyCode){case 81:A.setSpace(A.space==="local"?"world":"local");break;case 16:this.enableSnapping();break;case 87:A.setMode("translate");break;case 69:A.setMode("rotate");break;case 82:A.setMode("scale");break;case 187:case 107:A.setSize(A.size+.1);break;case 189:case 109:A.setSize(Math.max(A.size-.1,.1));break;case 88:A.showX=!A.showX;break;case 89:A.showY=!A.showY;break;case 90:A.showZ=!A.showZ;break;case 32:A.enabled=!A.enabled;break}}),this.windowKeyUpListener||(this.windowKeyUpListener=e=>{if(this.enabled)switch(e.keyCode){case 16:this.disableSnapping();break}}),window.addEventListener("keydown",this.windowKeyDownListener),window.addEventListener("keyup",this.windowKeyUpListener))}removeWindowEvents(){window.removeEventListener("keydown",this.windowKeyDownListener),window.removeEventListener("keyup",this.windowKeyUpListener)}}Gy([w()],tB.prototype,"isGizmo",2),Gy([w()],tB.prototype,"translationSnap",2),Gy([w()],tB.prototype,"rotationSnapAngle",2),Gy([w()],tB.prototype,"scaleSnap",2);var UCA=Object.defineProperty,FCA=Object.getOwnPropertyDescriptor,jR=(t,A,e,g)=>{for(var i=g>1?void 0:g?FCA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&UCA(A,e,i),i};class gB extends ki{constructor(){super(...arguments),r(this,"color"),r(this,"intensity"),r(this,"center")}get typeName(){return"Vignette"}init(){this.color.defaultValue={r:0,g:0,b:0,a:1},this.intensity.defaultValue=0,this.center.defaultValue={x:.5,y:.5}}onCreateEffect(){const A=new lb;return this.intensity.onValueChanged=e=>{A.offset=e,this.updateDarkness(A)},this.color.onValueChanged=e=>{this.updateDarkness(A)},A}updateDarkness(A){const e=this.intensity.value;A.darkness=e}}jR([w(Ge)],gB.prototype,"color",2),jR([w(Ge)],gB.prototype,"intensity",2),jR([w(Ge)],gB.prototype,"center",2),po("Vignette",gB);var NCA=Object.defineProperty,KCA=Object.getOwnPropertyDescriptor,JCA=(t,A,e,g)=>{for(var i=g>1?void 0:g?KCA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&NCA(A,e,i),i};const WR=CA("debugpost");class my extends RA{constructor(){super(...arguments),r(this,"sharedProfile"),r(this,"_postprocessing"),r(this,"_effects",[]),r(this,"_lastApplyTime"),r(this,"_rapidApplyCount",0),r(this,"_isDirty",!1),r(this,"_modificationQueue"),r(this,"_recreateId",-1)}markDirty(){this._isDirty=!0}awake(){var A;(A=this.sharedProfile)==null||A.init(),WR&&(console.log(this),console.log("Press P to toggle post processing"),window.addEventListener("keydown",e=>{e.key==="p"&&(console.log("Toggle volume: "+this.name,!this.enabled),this.enabled=!this.enabled)}))}onDisable(){var A;(A=this._postprocessing)==null||A.unapply()}onBeforeRender(){if(!this.context.isInXR){if(this.context.composer&&!(this.context.composer instanceof jk))return;this.context.mainCamera&&(!this._postprocessing||!this._postprocessing.isActive||this._isDirty)&&this.apply(),this.context.composer&&(this.context.composer.setRenderer(this.context.renderer),this.context.composer.setMainScene(this.context.scene),this.context.mainCamera&&this.context.composer.setMainCamera(this.context.mainCamera))}}onDestroy(){var A;(A=this._postprocessing)==null||A.dispose()}apply(){var A,e;WR&&console.log("Apply PostProcessing",this,(A=this.context.mainCamera)==null?void 0:A.name),pi()&&(this._lastApplyTime!==void 0&&Date.now()-this._lastApplyTime<100&&(this._rapidApplyCount++,this._rapidApplyCount===5&&console.warn("Detected rapid post processing modifications - this might be a bug",this)),this._lastApplyTime=Date.now()),this._isDirty=!1,this.unapply(),this._effects.length=0,(e=this.sharedProfile)!=null&&e.components&&this._effects.push(...this.sharedProfile.components);const g=this.gameObject.getComponentsInChildren(ki);if(WR&&g!=null&&g.length&&console.log("Additional",g),g)for(const i of g)i.active&&this._effects.push(i);this._effects.length>0&&(this._postprocessing||(this._postprocessing=new By(this.context)),this._postprocessing.apply(this._effects),this._applyPostQueue())}unapply(){var A;(A=this._postprocessing)==null||A.unapply()}_applyPostQueue(){if(this._modificationQueue){for(const A of this._modificationQueue.values())this.onEditorModification(A);this._modificationQueue.clear()}}onEditorModification(A){var e,g;if(A.propertyName.startsWith("postprocessing.")){if(!this._postprocessing)return this._modificationQueue||(this._modificationQueue=new Map),this._modificationQueue.set(A.propertyName,A),!0;if(!((e=this._effects)!=null&&e.length))return;const i=A.propertyName.split(".");if(i.length===3||i.length===4){const I=i[1],o=i[2];for(const C of this._effects)if(((g=C.typeName)==null?void 0:g.toLowerCase())===I.toLowerCase()){if(o==="active"){C.active=A.value,this.scheduleRecreate();return}if(!My.has(I)){const s=new Array;My.set(I,s);const a=Object.keys(C);for(const n of a)C[n]instanceof Ge&&s.push(n)}if(My.has(I)){const s=o.toLowerCase(),a=My.get(I);for(const n of a)if(n.toLowerCase()===s){const B=C[n];B instanceof Ge&&(i.length===4&&i[3]==="active"?(B.overrideState=A.value,this.scheduleRecreate()):B&&B.value!==void 0&&(B.value=A.value));return}}console.warn("Unknown modification",o);return}}return!0}return!1}scheduleRecreate(){const A=++this._recreateId;setTimeout(()=>{A===this._recreateId&&(this.onDisable(),this.onEnable())},200)}}JCA([mQ(rl)],my.prototype,"sharedProfile",2);const My=new Map;var qCA=Object.defineProperty,vCA=Object.getOwnPropertyDescriptor,bCA=(t,A,e,g)=>{for(var i=g>1?void 0:g?vCA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&qCA(A,e,i),i};class Ry extends RA{constructor(){super(...arguments),r(this,"backgroundTint",new wt(1,1,1,1)),r(this,"_preRender"),r(this,"backgroundPlane"),r(this,"threeTexture"),r(this,"forceTextureInitialization",function(){const A=new dt,e=new Zg,g=new gI;g.add(new DA(e,A));const i=new Vn;return function(I,o){A.map=o,I.render(g,i)}}())}awake(){Se.OptionalFeatures_AR.push("camera-access")}get background(){return this.backgroundPlane}onEnable(){this._preRender=this.preRender.bind(this),this.context.pre_render_callbacks.push(this._preRender),this.backgroundPlane&&(this.gameObject.add(this.backgroundPlane),this.backgroundPlane.visible=!1)}onDisable(){this.context.pre_render_callbacks=this.context.pre_render_callbacks.filter(A=>A!==this._preRender),this.backgroundPlane&&this.gameObject.remove(this.backgroundPlane)}preRender(){if(!this||!this.gameObject)return;const A=this.context.renderer.xr.getFrame();A&&(!this.threeTexture&&this.context.renderer&&(this.threeTexture=new Le,this.forceTextureInitialization(this.context.renderer,this.threeTexture)),this.backgroundPlane===void 0&&(this.backgroundPlane=xCA(this.backgroundTint),this.gameObject.add(this.backgroundPlane)),this.updateFromFrame(A))}onBeforeRender(A){this.updateFromFrame(A)}updateFromFrame(A){if(!A)return;const e=A.getViewerPose(this.context.renderer.xr.getReferenceSpace());if(e){for(const g of e.views)if("camera"in g&&g.camera){let i=this.context.renderer.xr.getBinding();if(i||(i=new XRWebGLBinding(A.session,this.context.renderer.getContext())),i){let I=null;if("getCameraImage"in i){I=i.getCameraImage(g.camera);const o=this.context.renderer.properties.get(this.threeTexture);o.__webglTexture=I,this.backgroundPlane&&(this.backgroundPlane.setTexture(this.threeTexture),this.backgroundPlane.visible=!0)}}}}}}bCA([w()],Ry.prototype,"backgroundTint",2);let LCA=`
|
|
5438
|
+
`)}}}applyShadowMaterial(){var A;const e=eA.getComponent(this.gameObject,Jt);if(e)if(((A=e.sharedMaterial)==null?void 0:A.type)!=="ShadowMaterial"){const g=new kf;g.color=this.shadowColor,g.opacity=this.shadowColor.alpha,this.applyMaterialOptions(g),e.sharedMaterial=g}else{const g=e.sharedMaterial;g.color=this.shadowColor,g.opacity=this.shadowColor.alpha,this.applyMaterialOptions(g)}}applyOccluderMaterial(){const A=eA.getComponent(this.gameObject,Jt);if(A){const e=A.sharedMaterial;e.depthWrite=!0,e.stencilWrite=!0,e.colorWrite=!1,this.gameObject.renderOrder=-100}}applyMaterialOptions(A){A&&(A.depthWrite=!1,A.stencilWrite=!1)}}f2([w()],Ol.prototype,"mode",2),f2([w(wt)],Ol.prototype,"shadowColor",2);var YoA=Object.defineProperty,HoA=Object.getOwnPropertyDescriptor,ly=(t,A,e,g)=>{for(var i=g>1?void 0:g?HoA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&YoA(A,e,i),i},UR;const k2=(UR=class extends RA{constructor(){super(...arguments),r(this,"target",null),r(this,"followFactor",.1),r(this,"rotateFactor",.1),r(this,"positionAxes",xQ.All),r(this,"flipForward",!1),r(this,"_firstUpdate",!0)}onBeforeRender(){this.updateNow(!1)}updateNow(t){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){const A=we(this.target),e=this._firstUpdate||t?1:$A.clamp01(this.context.time.deltaTime*this.followFactor),g=this.worldPosition;this.positionAxes&xQ.X&&(g.x=$A.lerp(g.x,A.x,e)),this.positionAxes&xQ.Y&&(g.y=$A.lerp(g.y,A.y,e)),this.positionAxes&xQ.Z&&(g.z=$A.lerp(g.z,A.z,e)),this.worldPosition=g}if(this.rotateFactor>0){const A=qg(this.target);this.flipForward&&A.premultiply(k2._invertForward);const e=this._firstUpdate||t?1:$A.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(A,e)}this._firstUpdate=!1}}},r(UR,"_invertForward",new mA().setFromAxisAngle(new f(0,1,0),Math.PI)),UR);let Sn=k2;ly([w(UA)],Sn.prototype,"target",2),ly([w()],Sn.prototype,"followFactor",2),ly([w()],Sn.prototype,"rotateFactor",2),ly([w()],Sn.prototype,"positionAxes",2);class ToA extends DA{constructor(A){const e=new OoA(A),g=new Zg(e.image.width*.001,e.image.height*.001),i=new dt({map:e,toneMapped:!1,transparent:!0});super(g,i);function I(o){i.map.dispatchDOMEvent(o)}this.addEventListener("mousedown",I),this.addEventListener("mousemove",I),this.addEventListener("mouseup",I),this.addEventListener("click",I),this.dispose=function(){g.dispose(),i.dispose(),i.map.dispose(),FR.delete(A),this.removeEventListener("mousedown",I),this.removeEventListener("mousemove",I),this.removeEventListener("mouseup",I),this.removeEventListener("click",I)}}}class OoA extends rK{constructor(A){super(G2(A)),this.dom=A,this.anisotropy=16,this.encoding=ue,this.minFilter=Ne,this.magFilter=Ne;const e=new MutationObserver(()=>{this.scheduleUpdate||(this.scheduleUpdate=setTimeout(()=>this.update(),16))}),g={attributes:!0,childList:!0,subtree:!0,characterData:!0};e.observe(A,g),this.observer=e}dispatchDOMEvent(A){A.data&&_oA(this.dom,A.type,A.data.x,A.data.y)}update(){this.image=G2(this.dom),this.needsUpdate=!0,this.scheduleUpdate=null}dispose(){this.observer&&this.observer.disconnect(),this.scheduleUpdate=clearTimeout(this.scheduleUpdate),super.dispose()}}const FR=new WeakMap;function G2(t){const A=document.createRange(),e=new SA;function g(Q){const E=[];let h=!1;function c(){if(h&&(h=!1,Q.restore()),E.length===0)return;let l=-1/0,d=-1/0,u=1/0,p=1/0;for(let D=0;D<E.length;D++){const y=E[D];l=Math.max(l,y.x),d=Math.max(d,y.y),u=Math.min(u,y.x+y.width),p=Math.min(p,y.y+y.height)}Q.save(),Q.beginPath(),Q.rect(l,d,u-l,p-d),Q.clip(),h=!0}return{add:function(l){E.push(l),c()},remove:function(){E.pop(),c()}}}function i(Q,E,h,c){c!==""&&(Q.textTransform==="uppercase"&&(c=c.toUpperCase()),n.font=Q.fontWeight+" "+Q.fontSize+" "+Q.fontFamily,n.textBaseline="top",n.fillStyle=Q.color,n.fillText(c,E,h+parseFloat(Q.fontSize)*.1))}function I(Q,E,h,c,l){h<2*l&&(l=h/2),c<2*l&&(l=c/2),n.beginPath(),n.moveTo(Q+l,E),n.arcTo(Q+h,E,Q+h,E+c,l),n.arcTo(Q+h,E+c,Q,E+c,l),n.arcTo(Q,E+c,Q,E,l),n.arcTo(Q,E,Q+h,E,l),n.closePath()}function o(Q,E,h,c,l,d){const u=Q[E+"Width"],p=Q[E+"Style"],D=Q[E+"Color"];u!=="0px"&&p!=="none"&&D!=="transparent"&&D!=="rgba(0, 0, 0, 0)"&&(n.strokeStyle=D,n.lineWidth=parseFloat(u),n.beginPath(),n.moveTo(h,c),n.lineTo(h+l,c+d),n.stroke())}function C(Q,E){let h=0,c=0,l=0,d=0;if(Q.nodeType===Node.TEXT_NODE){A.selectNode(Q);const p=A.getBoundingClientRect();h=p.left-s.left-.5,c=p.top-s.top-.5,l=p.width,d=p.height,i(E,h,c,Q.nodeValue.trim())}else{if(Q.nodeType===Node.COMMENT_NODE)return;if(Q instanceof HTMLCanvasElement){if(Q.style.display==="none")return;n.save();const p=window.devicePixelRatio;n.scale(1/p,1/p),n.drawImage(Q,0,0),n.restore()}else{if(Q.style.display==="none")return;const p=Q.getBoundingClientRect();h=p.left-s.left-.5,c=p.top-s.top-.5,l=p.width,d=p.height,E=window.getComputedStyle(Q),I(h,c,l,d,parseFloat(E.borderRadius));const D=E.backgroundColor;D!=="transparent"&&D!=="rgba(0, 0, 0, 0)"&&(n.fillStyle=D,n.fill());const y=["borderTop","borderLeft","borderBottom","borderRight"];let k=!0,F=null;for(const S of y){if(F!==null&&(k=E[S+"Width"]===E[F+"Width"]&&E[S+"Color"]===E[F+"Color"]&&E[S+"Style"]===E[F+"Style"]),k===!1)break;F=S}if(k===!0){const S=parseFloat(E.borderTopWidth);E.borderTopWidth!=="0px"&&E.borderTopStyle!=="none"&&E.borderTopColor!=="transparent"&&E.borderTopColor!=="rgba(0, 0, 0, 0)"&&(n.strokeStyle=E.borderTopColor,n.lineWidth=S,n.stroke())}else o(E,"borderTop",h,c,l,0),o(E,"borderLeft",h,c,0,d),o(E,"borderBottom",h,c+d,l,0),o(E,"borderRight",h+l,c,0,d);if(Q instanceof HTMLInputElement){let S=E.accentColor;(S===void 0||S==="auto")&&(S=E.color),e.set(S);const U=Math.sqrt(.299*e.r**2+.587*e.g**2+.114*e.b**2)<.5?"white":"#111111";if(Q.type==="radio"&&(I(h,c,l,d,d),n.fillStyle="white",n.strokeStyle=S,n.lineWidth=1,n.fill(),n.stroke(),Q.checked&&(I(h+2,c+2,l-4,d-4,d),n.fillStyle=S,n.strokeStyle=U,n.lineWidth=2,n.fill(),n.stroke())),Q.type==="checkbox"&&(I(h,c,l,d,2),n.fillStyle=Q.checked?S:"white",n.strokeStyle=Q.checked?U:S,n.lineWidth=1,n.stroke(),n.fill(),Q.checked)){const M=n.textAlign;n.textAlign="center";const Y={color:U,fontFamily:E.fontFamily,fontSize:d+"px",fontWeight:"bold"};i(Y,h+l/2,c,"\u2714"),n.textAlign=M}if(Q.type==="range"){const[M,Y,O]=["min","max","value"].map(b=>parseFloat(Q[b])),x=(O-M)/(Y-M)*(l-d);I(h,c+d/4,l,d/2,d/4),n.fillStyle=U,n.strokeStyle=S,n.lineWidth=1,n.fill(),n.stroke(),I(h,c+d/4,x+d/2,d/2,d/4),n.fillStyle=S,n.fill(),I(h+x,c,d,d,d/2),n.fillStyle=S,n.fill()}(Q.type==="color"||Q.type==="text"||Q.type==="number")&&(B.add({x:h,y:c,width:l,height:d}),i(E,h+parseInt(E.paddingLeft),c+parseInt(E.paddingTop),Q.value),B.remove())}}}const u=E.overflow==="auto"||E.overflow==="hidden";u&&B.add({x:h,y:c,width:l,height:d});for(let p=0;p<Q.childNodes.length;p++)C(Q.childNodes[p],E);u&&B.remove()}const s=t.getBoundingClientRect();let a=FR.get(t);a===void 0&&(a=document.createElement("canvas"),a.width=s.width,a.height=s.height,FR.set(t,a));const n=a.getContext("2d"),B=new g(n);return C(t),a}function _oA(t,A,e,g){const i={clientX:e*t.offsetWidth+t.offsetLeft,clientY:g*t.offsetHeight+t.offsetTop,view:t.ownerDocument.defaultView};window.dispatchEvent(new MouseEvent(A,i));const I=t.getBoundingClientRect();e=e*I.width+I.left,g=g*I.height+I.top;function o(C){if(C.nodeType!==Node.TEXT_NODE&&C.nodeType!==Node.COMMENT_NODE){const s=C.getBoundingClientRect();if(e>s.left&&e<s.right&&g>s.top&&g<s.bottom&&(C.dispatchEvent(new MouseEvent(A,i)),C instanceof HTMLInputElement&&C.type==="range"&&(A==="mousedown"||A==="click"))){const[a,n]=["min","max"].map(E=>parseFloat(C[E])),B=s.width,Q=(e-s.x)/B;C.value=a+(n-a)*Q,C.dispatchEvent(new InputEvent("input",{bubbles:!0}))}for(let a=0;a<C.childNodes.length;a++)o(C.childNodes[a])}}o(t)}const dy=new W,fE={type:"",data:dy};class PoA extends zI{constructor(A,e){super();const g=this,i=new VB,I=new KA,o=A.domElement;function C(Q){Q.stopPropagation();const E=A.domElement.getBoundingClientRect();dy.x=(Q.clientX-E.left)/E.width*2-1,dy.y=-(Q.clientY-E.top)/E.height*2+1,i.setFromCamera(dy,e);const h=i.intersectObjects(g.children,!1);if(h.length>0){const c=h[0],l=c.object,d=c.uv;fE.type=Q.type,fE.data.set(d.x,1-d.y),l.dispatchEvent(fE)}}o.addEventListener("pointerdown",C),o.addEventListener("pointerup",C),o.addEventListener("pointermove",C),o.addEventListener("mousedown",C),o.addEventListener("mouseup",C),o.addEventListener("mousemove",C),o.addEventListener("click",C);const s={move:"mousemove",select:"click",selectstart:"mousedown",selectend:"mouseup"};function a(Q){const E=Q.target;I.identity().extractRotation(E.matrixWorld),i.ray.origin.setFromMatrixPosition(E.matrixWorld),i.ray.direction.set(0,0,-1).applyMatrix4(I);const h=i.intersectObjects(g.children,!1);if(h.length>0){const c=h[0],l=c.object,d=c.uv;fE.type=s[Q.type],fE.data.set(d.x,1-d.y),l.dispatchEvent(fE)}}const n=A.xr.getController(0);n.addEventListener("move",a),n.addEventListener("select",a),n.addEventListener("selectstart",a),n.addEventListener("selectend",a);const B=A.xr.getController(1);B.addEventListener("move",a),B.addEventListener("select",a),B.addEventListener("selectstart",a),B.addEventListener("selectend",a)}}class NR extends RA{constructor(){super(...arguments),r(this,"id",null),r(this,"keepAspect",!1)}start(){if(!this.id||!this.context.mainCamera)return;const A=document.getElementById(this.id);if(!A){console.warn('Could not find element with id "'+this.id+'"');return}A.style.display="block",A.style.visibility="hidden";const e=new PoA(this.context.renderer,this.context.mainCamera);this.gameObject.add(e);const g=new ToA(A);e.add(g),g.visible=!1,console.log(g);const i=g.material;i.transparent=!0,setTimeout(()=>{g.visible=!0;const I=du(this.gameObject).clone();pu(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();const o=new li;o.setFromObject(e),this.setWorldRotation(I.x,I.y,I.z);const C=o.max.x-o.min.x,s=o.max.y-o.min.y;if(this.keepAspect){const n=C/s;C>s?g.scale.set(1/C,1/s/n,1):g.scale.set(1/C*n,1/s,1)}else g.scale.set(1/C,1/s,1);const a=this.gameObject.scale;g.scale.multiply(a)},1)}}var joA=Object.defineProperty,WoA=Object.getOwnPropertyDescriptor,_l=(t,A,e,g)=>{for(var i=g>1?void 0:g?WoA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&joA(A,e,i),i};const Pl=CA("debugspatialtrigger"),m2=new jI,M2=new jI;function VoA(t,A){return m2.mask=t,M2.mask=A,m2.test(M2)}class JC extends RA{constructor(){super(...arguments),r(this,"triggerMask",0),r(this,"onEnter"),r(this,"onStay"),r(this,"onExit"),r(this,"currentIntersected",[]),r(this,"lastIntersected",[])}start(){Pl&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(const A of jl.triggers)VoA(A.triggerMask,this.triggerMask)&&A.test(this.gameObject)&&this.currentIntersected.push(A);for(let A=this.lastIntersected.length-1;A>=0;A--){const e=this.lastIntersected[A];this.currentIntersected.indexOf(e)<0&&(this.onExitTrigger(e),this.lastIntersected.splice(A,1))}for(const A of this.currentIntersected)this.lastIntersected.indexOf(A)<0&&this.onEnterTrigger(A),this.onStayTrigger(A);this.lastIntersected.length=0,this.lastIntersected.push(...this.currentIntersected)}onEnterTrigger(A){var e;Pl&&console.log("ENTER TRIGGER",this.name,A.name,this,A),A.raiseOnEnterEvent(this),(e=this.onEnter)==null||e.invoke(this,A)}onExitTrigger(A){var e;Pl&&console.log("EXIT TRIGGER",this.name,A.name,this,A),A.raiseOnExitEvent(this),(e=this.onExit)==null||e.invoke(this,A)}onStayTrigger(A){var e;A.raiseOnStayEvent(this),(e=this.onStay)==null||e.invoke(this,A)}}_l([w()],JC.prototype,"triggerMask",2),_l([w(aI)],JC.prototype,"onEnter",2),_l([w(aI)],JC.prototype,"onStay",2),_l([w(aI)],JC.prototype,"onExit",2);var KR;const py=(KR=class extends RA{constructor(){super(...arguments),r(this,"triggerMask"),r(this,"boxHelper")}start(){Pl&&console.log(this.name,this.triggerMask,this)}onEnable(){var t;py.triggers.push(this),this.boxHelper||(this.boxHelper=eA.addNewComponent(this.gameObject,dC),(t=this.boxHelper)==null||t.showHelper(null,Pl))}onDisable(){py.triggers.splice(py.triggers.indexOf(this),1)}test(t){return this.boxHelper?this.boxHelper.isInBox(t)??!1:!1}raiseOnEnterEvent(t){eA.foreachComponent(this.gameObject,A=>{A!==t&&A instanceof JC&&A.onEnterTrigger(this)},!1)}raiseOnStayEvent(t){eA.foreachComponent(this.gameObject,A=>{A!==t&&A instanceof JC&&A.onStayTrigger(this)},!1)}raiseOnExitEvent(t){eA.foreachComponent(this.gameObject,A=>{A!==t&&A instanceof JC&&A.onExitTrigger(this)},!1)}},r(KR,"triggers",[]),KR);let jl=py;_l([w()],jl.prototype,"triggerMask",2);var zoA=Object.defineProperty,ZoA=Object.getOwnPropertyDescriptor,XoA=(t,A,e,g)=>{for(var i=g>1?void 0:g?ZoA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&zoA(A,e,i),i};const YI=CA("debugspectator");class uy extends RA{constructor(){super(...arguments),r(this,"cam",null),r(this,"useKeys",!0),r(this,"_mode",0),r(this,"orbit",null),r(this,"_handler"),r(this,"eventSub_WebXRRequestStartEvent",null),r(this,"eventSub_WebXRStartEvent",null),r(this,"eventSub_WebXREndEvent",null),r(this,"_debug"),r(this,"_networking")}get mode(){return this._mode}set mode(A){this._mode=A}get isSpectating(){var A;return((A=this._handler)==null?void 0:A.currentTarget)!==void 0}isSpectatingUser(A){var e;return((e=this.target)==null?void 0:e.userId)===A}isFollowedBy(A){var e;return(e=this.followers)==null?void 0:e.includes(A)}get followers(){return this._networking.followers}stopSpectating(){if(this.context.isInXR){this.followSelf();return}this.target=void 0}get localId(){return this.context.connection.connectionId??"local"}set target(A){var e;if(this._handler){const g=(e=this._handler.currentTarget)==null?void 0:e.userId,i=this.context.players.getPlayerView(this.localId);A===void 0||this.context.isInXR===!1&&i?.currentObject===A.currentObject?this._handler.currentTarget!==void 0&&(this._handler.disable(),eA.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(A,g)):this._handler.currentTarget!==A&&(this._handler.set(A),eA.setActive(this.gameObject,!0),this.orbit&&(this.orbit.enabled=!1),this._networking.onSpectatedObjectChanged(A,g))}}get target(){var A;return(A=this._handler)==null?void 0:A.currentTarget}requestAllFollowMe(){this._networking.onRequestFollowMe()}get isSpectatingSelf(){var A,e;return this.isSpectating&&((A=this.target)==null?void 0:A.currentObject)===((e=this.context.players.getPlayerView(this.localId))==null?void 0:e.currentObject)}awake(){if(this._debug=new eCA(this.context,this),this._networking=new iCA(this.context,this),this._networking.awake(),eA.setActive(this.gameObject,!1),this.cam=eA.getComponent(this.gameObject,bt),!this.cam){console.error("Spectator camera needs camera component",this);return}!this._handler&&this.cam&&(this._handler=new $oA(this.context,this.cam,this)),this.eventSub_WebXRRequestStartEvent=this.onXRSessionRequestStart.bind(this),this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),Se.addEventListener(kt.RequestVRSession,this.eventSub_WebXRRequestStartEvent),Se.addEventListener(kt.XRStarted,this.eventSub_WebXRStartEvent),Se.addEventListener(kt.XRStopped,this.eventSub_WebXREndEvent),this.orbit=eA.getComponent(this.context.mainCamera,Ts)}onDestroy(){var A,e;this.stopSpectating(),Se.removeEventListener(kt.RequestVRSession,this.eventSub_WebXRStartEvent),Se.removeEventListener(kt.XRStarted,this.eventSub_WebXRStartEvent),Se.removeEventListener(kt.XRStopped,this.eventSub_WebXREndEvent),(A=this._handler)==null||A.destroy(),(e=this._networking)==null||e.destroy()}isSupportedPlatform(){const A=window.navigator.userAgent,e=/Windows|MacOS/.test(A),g=/Windows NT/.test(A)&&/Edg/.test(A)&&!/Win64/.test(A);return e&&!g}onXRSessionRequestStart(A){this.isSupportedPlatform()&&eA.setActive(this.gameObject,!0)}onXRSessionStart(A){this.isSupportedPlatform()&&(YI&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onXRSessionEnded(A){var e,g;this.context.removeCamera(this.cam),eA.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),(e=this._handler)==null||e.set(void 0),(g=this._handler)==null||g.disable(),this.isSpectatingSelf&&this.stopSpectating()}followSelf(){this.target=this.context.players.getPlayerView(this.context.connection.connectionId),this.target||(this.context.players.setPlayerView(this.localId,this.context.mainCamera,QC.Headset),this.target=this.context.players.getPlayerView(this.localId)),YI&&console.log("Follow self",this.target)}onAfterRender(){var A,e,g;if(!this.cam)return;const i=this.context.renderer,I=i.xr.enabled;if(!i.xr.isPresenting&&!((A=this._handler)!=null&&A.currentTarget))return;(e=this._handler)==null||e.update(this._mode);const o=i.getRenderTarget();let C=null;if(!o){if(!i.state.bindFramebuffer||!i.state.bindXRFramebuffer)return;C=i._framebuffer,i.state.bindXRFramebuffer(null)}this.setAvatarFlagsBeforeRender();const s=this.context.mainCameraComponent;if(s){const B=s.backgroundColor;B&&i.setClearColor(B,B.alpha),this.cam.backgroundColor=B,this.cam.clearFlags=s.clearFlags,this.cam.nearClipPlane=s.nearClipPlane,this.cam.farClipPlane=s.farClipPlane}else i.setClearColor(new SA(1,1,1));i.setRenderTarget(null),i.xr.enabled=!1;const a=(g=this.cam)==null?void 0:g.cam;this.context.updateAspect(a);const n=i.xr.isPresenting;i.xr.isPresenting=!1,i.setSize(this.context.domWidth,this.context.domHeight),i.render(this.context.scene,a),i.xr.isPresenting=n,i.xr.enabled=I,o?i.setRenderTarget(o):i.state.bindXRFramebuffer(C),this.resetAvatarFlags()}setAvatarFlagsBeforeRender(){const A=this._mode===0;for(const e of fi.instances)if(e.avatar&&"isLocalAvatar"in e.avatar){let g=lg.All;this.isSpectatingSelf&&(g=A&&e.avatar.isLocalAvatar?lg.FirstPerson:lg.ThirdPerson);const i=e.avatar.flags;if(!i)continue;for(const I of i)I.UpdateVisible(g)}}resetAvatarFlags(){var A;for(const e of fi.instances)if(e.avatar&&"flags"in e.avatar){const g=e.avatar.flags;if(!g)continue;for(const i of g)(A=e.avatar)!=null&&A.isLocalAvatar?i.UpdateVisible(lg.FirstPerson):i.UpdateVisible(lg.ThirdPerson)}}}XoA([w()],uy.prototype,"useKeys",2);class $oA{constructor(A,e,g){r(this,"context"),r(this,"cam"),r(this,"spectator"),r(this,"follow"),r(this,"target"),r(this,"view"),r(this,"currentObject"),this.context=A,this.cam=e,this.spectator=g}get currentTarget(){return this.view}set(A){const e=A?.currentObject;if(!e){this.spectator.stopSpectating();return}e!==this.currentObject&&(this.currentObject=e,this.view=A,this.follow||(this.follow=eA.addNewComponent(this.cam.gameObject,Sn)),this.target||(this.target=new UA),e.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,YI&&console.log("FOLLOW",e),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){YI&&console.log("STOP FOLLOW",this.currentObject),this.view=void 0,this.currentObject=void 0,this.context.removeCamera(this.cam),this.follow&&(this.follow.enabled=!1)}destroy(){var A;(A=this.target)==null||A.removeFromParent(),this.follow&&eA.destroy(this.follow)}update(A){var e,g,i,I,o,C;if(((e=this.currentTarget)==null?void 0:e.isConnected)===!1||((g=this.currentTarget)==null?void 0:g.removed)===!0){YI&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&((i=this.currentTarget)==null?void 0:i.currentObject)!==this.currentObject&&(YI&&console.log("Target changed",this.currentObject,"to",this.currentTarget.currentObject),this.set(this.currentTarget));const s=this.context.mainCamera;s&&(this.cam.cam.near!==s.near||this.cam.cam.far!==s.far)&&(this.cam.cam.near=s.near,this.cam.cam.far=s.far,this.cam.cam.updateProjectionMatrix());const a=(I=this.follow)==null?void 0:I.target;if(!(!a||!this.follow)){switch(A){case 0:((o=this.view)==null?void 0:o.viewDevice)!==QC.Browser?(this.follow.followFactor=5,this.follow.rotateFactor=5):(this.follow.followFactor=50,this.follow.rotateFactor=50),a.position.set(0,0,0);break;case 1:this.follow.followFactor=3,this.follow.rotateFactor=2,a.position.set(0,.5,1.5);break}this.follow.flipForward=!1,((C=this.view)==null?void 0:C.viewDevice)!==QC.Browser?a.quaternion.copy(ACA):a.quaternion.identity()}}}const ACA=new mA().setFromAxisAngle(new f(0,1,0),Math.PI);class eCA{constructor(A,e){r(this,"context"),r(this,"spectator"),this.context=A,this.spectator=e,console.log("Click other avatars or cameras to follow them. Press ESC to exit spectator mode."),this.context.domElement.addEventListener("keydown",i=>{!this.spectator.useKeys||i.key==="Escape"&&this.spectator.stopSpectating()});let g=0;this.context.input.addEventListener(sC.PointerDown,i=>{g=this.context.time.time}),this.context.input.addEventListener(sC.PointerUp,i=>{const I=this.context.time.time-g;I>1?this.spectator.stopSpectating():this.context.input.getPointerClicked(0)&&I<.3&&this.trySelectObject()})}trySelectObject(){const A=new Jo;A.setMask(16777215);const e=this.context.physics.raycast(A);if(YI&&console.log(...e),e!=null&&e.length)for(const g of e){if(g.distance<.2)continue;const i=g.object,I=eA.getComponentInParent(i,fi),o=I?.connectionId;if(o){const C=this.context.players.getPlayerView(o);this.spectator.target=C,YI&&console.log("spectate",o,I);break}}}}class tCA{constructor(A,e,g){r(this,"guid"),r(this,"dontSave",!0),r(this,"targetUserId"),r(this,"stoppedFollowing"),this.guid=A,this.targetUserId=e,this.stoppedFollowing=g}}class gCA{constructor(A,e){r(this,"guid"),r(this,"userId"),this.guid=A.guid,this.userId=e}}class iCA{constructor(A,e){r(this,"followers",[]),r(this,"context"),r(this,"spectator"),r(this,"_followerEventMethod"),r(this,"_requestFollowMethod"),r(this,"_joinedRoomMethod"),r(this,"_lastRequestFollowUser"),r(this,"_enforceFollowInterval"),this.context=A,this.spectator=e,this._followerEventMethod=this.onFollowerEvent.bind(this),this._requestFollowMethod=this.onRequestFollowEvent.bind(this),this._joinedRoomMethod=this.onUserJoinedRoom.bind(this)}awake(){this.context.connection.beginListen("spectator-follower-changed",this._followerEventMethod),this.context.connection.beginListen("spectator-request-follow",this._requestFollowMethod),this.context.connection.beginListen(Wt.JoinedRoom,this._joinedRoomMethod),this.context.domElement.addEventListener("keydown",A=>{this.spectator.useKeys&&(A.key==="f"?this.onRequestFollowMe():A.key==="Escape"&&this.onRequestFollowMe(!0))})}destroy(){this.context.connection.stopListen("spectator-follower-changed",this._followerEventMethod),this.context.connection.stopListen("spectator-request-follow",this._requestFollowMethod),this.context.connection.stopListen(Wt.JoinedRoom,this._joinedRoomMethod)}onSpectatedObjectChanged(A,e){if(YI&&console.log(this.context.connection.connectionId,"onSpectatedObjectChanged",A,e),this.context.connection.connectionId){const g=A?.userId===void 0,i=g?e:A?.userId,I=new tCA(this.context.connection.connectionId,i,g);this.context.connection.send("spectator-follower-changed",I)}}onRequestFollowMe(A=!1){if(YI&&console.log("Request follow",this.context.connection.connectionId),this.context.connection.connectionId){this.spectator.stopSpectating();const e=A?void 0:this.context.connection.connectionId,g=new gCA(this.spectator,e);this.context.connection.send("spectator-request-follow",g)}}onUserJoinedRoom(){CA("followme")&&this.onRequestFollowMe()}onFollowerEvent(A){const e=A.targetUserId,g=A.guid;if(YI&&console.log(A),e===this.context.connection.connectionId)if(A.stoppedFollowing){const i=this.followers.indexOf(g);i!==-1&&(this.followers.splice(i,1),this.removeDisconnectedFollowers(),console.log(g,"unfollows you",this.followers.length))}else this.followers.includes(g)||(this.followers.push(g),this.removeDisconnectedFollowers(),console.log(g,"follows you",this.followers.length))}removeDisconnectedFollowers(){for(let A=this.followers.length-1;A>=0;A--){const e=this.followers[A];this.context.connection.userIsInRoom(e)===!1&&this.followers.splice(A,1)}}onRequestFollowEvent(A){if(this._lastRequestFollowUser=A,A.userId===this.context.connection.connectionId)this.spectator.stopSpectating();else if(A.userId===void 0)this.spectator.stopSpectating();else{const e=this.context.players.getPlayerView(A.userId);if(e)this.spectator.target=e;else return YI&&console.warn("Could not find view",A.userId),this.enforceFollow(),!1}return!0}enforceFollow(){this._enforceFollowInterval||(this._enforceFollowInterval=setInterval(()=>{this._lastRequestFollowUser===void 0||this._lastRequestFollowUser.userId&&this.spectator.isFollowedBy(this._lastRequestFollowUser.userId)?(clearInterval(this._enforceFollowInterval),this._enforceFollowInterval=void 0):(YI&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}}var ICA=Object.defineProperty,oCA=Object.getOwnPropertyDescriptor,$i=(t,A,e,g)=>{for(var i=g>1?void 0:g?oCA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&ICA(A,e,i),i};const JR=CA("debugspriterenderer"),CCA=CA("wireframe"),qR=class{static getOrCreateGeometry(t){if(t._geometry)return t._geometry;if(t.guid&&qR.cache[t.guid])return JR&&console.log("Take cached geometry for sprite",t.guid),qR.cache[t.guid];const A=new le;t._geometry=A;const e=new Float32Array(t.triangles.length*3),g=new Float32Array(t.triangles.length*2);for(let i=0;i<t.triangles.length;i+=1){const I=t.triangles[i];e[i*3]=-t.vertices[I].x,e[i*3+1]=t.vertices[I].y,e[i*3+2]=0;const o=t.uv[I];g[i*2]=o.x,g[i*2+1]=1-o.y}return A.setAttribute("position",new ge(e,3)),A.setAttribute("uv",new ge(g,2)),t.guid&&(this.cache[t.guid]=A),JR&&console.log("Built sprite geometry",t,A),A}};let vR=qR;r(vR,"cache",{});class $s{constructor(){r(this,"guid"),r(this,"texture"),r(this,"triangles"),r(this,"uv"),r(this,"vertices"),r(this,"_geometry")}}$i([w()],$s.prototype,"guid",2),$i([w(Le)],$s.prototype,"texture",2),$i([mQ()],$s.prototype,"triangles",2),$i([mQ()],$s.prototype,"uv",2),$i([mQ()],$s.prototype,"vertices",2);const bR=Symbol("spriteOwner");class Wl{constructor(){r(this,"sprites")}}$i([w($s)],Wl.prototype,"sprites",2);class kE{constructor(){r(this,"spriteSheet"),r(this,"index",0)}update(){if(!this.spriteSheet)return;const A=this.index;if(A<0||A>=this.spriteSheet.sprites.length)return;const e=this.spriteSheet.sprites[A];let g=e?.texture;g&&(g.encoding=ue,g.minFilter==Ve&&g.magFilter==Ve&&(g.anisotropy=1),g.needsUpdate=!0)}}$i([w(Wl)],kE.prototype,"spriteSheet",2),$i([w()],kE.prototype,"index",2);class qC extends RA{constructor(){super(...arguments),r(this,"drawMode",0),r(this,"size",{x:1,y:1}),r(this,"color"),r(this,"sharedMaterial"),r(this,"_spriteSheet"),r(this,"_currentSprite"),r(this,"transparent",!0),r(this,"cutoutThreshold",0),r(this,"castShadows",!1)}get sprite(){return this._spriteSheet}set sprite(A){if(A!==this._spriteSheet)if(typeof A=="number"){const e=Math.floor(A);e===A&&(this.spriteIndex=e);return}else this._spriteSheet=A,this.updateSprite()}set spriteIndex(A){this._spriteSheet&&(this._spriteSheet.index=A,this.updateSprite())}get spriteIndex(){var A;return((A=this._spriteSheet)==null?void 0:A.index)??0}get spriteFrames(){var A,e;return((e=(A=this._spriteSheet)==null?void 0:A.spriteSheet)==null?void 0:e.sprites.length)??0}awake(){this._currentSprite=void 0,JR&&console.log("Awake",this.name,this,this.sprite)}start(){this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(){var A,e,g;if(!this.__didAwake||!((e=(A=this.sprite)==null?void 0:A.spriteSheet)!=null&&e.sprites))return;const i=this.sprite.spriteSheet.sprites[this.spriteIndex];if(this._currentSprite)this._currentSprite.geometry=vR.getOrCreateGeometry(i),this._currentSprite.material.map=i.texture;else{const I=new dt({color:16777215,side:ft});if(!I)return;if(CCA&&(I.wireframe=!0),this.color&&(I.color||(I.color=new SA),I.color.copy(this.color),I.opacity=this.color.alpha),I.transparent=!0,i.texture&&!I.wireframe){let o=i.texture;o[bR]!==void 0&&o[bR]!==this&&this.spriteFrames>1&&(o=i.texture=o.clone()),o[bR]=this,I.map=o}this.sharedMaterial=I,this._currentSprite=new DA(vR.getOrCreateGeometry(i),I)}this._currentSprite.parent!==this.gameObject&&(this.drawMode===2&&this._currentSprite.scale.set(this.size.x,this.size.y,1),this.gameObject&&this.gameObject.add(this._currentSprite)),this._currentSprite&&this._currentSprite.layers.set(this.layer),this.sharedMaterial&&(this.sharedMaterial.alphaTest=this.cutoutThreshold,this.sharedMaterial.transparent=this.transparent),this._currentSprite.castShadow=this.castShadows,(g=this._spriteSheet)==null||g.update()}}$i([w()],qC.prototype,"drawMode",2),$i([w(wt)],qC.prototype,"color",2),$i([w(Ue)],qC.prototype,"sharedMaterial",2),$i([w(kE)],qC.prototype,"sprite",1),$i([w()],qC.prototype,"transparent",2),$i([w()],qC.prototype,"cutoutThreshold",2),$i([w()],qC.prototype,"castShadows",2);class OC{constructor(){r(this,"bb",null),r(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}static getRootAsSyncedCameraModel(A,e){return(e||new OC).__init(A.readInt32(A.position())+A.position(),A)}static getSizePrefixedRootAsSyncedCameraModel(A,e){return A.setPosition(A.position()+Mu),(e||new OC).__init(A.readInt32(A.position())+A.position(),A)}userId(A){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,A):null}guid(A){const e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,A):null}dontSave(){const A=this.bb.__offset(this.bb_pos,8);return A?!!this.bb.readInt8(this.bb_pos+A):!1}pos(A){const e=this.bb.__offset(this.bb_pos,10);return e?(A||new UI).__init(this.bb_pos+e,this.bb):null}rot(A){const e=this.bb.__offset(this.bb_pos,12);return e?(A||new UI).__init(this.bb_pos+e,this.bb):null}static startSyncedCameraModel(A){A.startObject(5)}static addUserId(A,e){A.addFieldOffset(0,e,0)}static addGuid(A,e){A.addFieldOffset(1,e,0)}static addDontSave(A,e){A.addFieldInt8(2,+e,0)}static addPos(A,e){A.addFieldStruct(3,e,0)}static addRot(A,e){A.addFieldStruct(4,e,0)}static endSyncedCameraModel(A){return A.endObject()}static finishSyncedCameraModelBuffer(A,e){A.finish(e)}static finishSizePrefixedSyncedCameraModelBuffer(A,e){A.finish(e,void 0,!0)}}var sCA=Object.defineProperty,aCA=Object.getOwnPropertyDescriptor,nCA=(t,A,e,g)=>{for(var i=g>1?void 0:g?aCA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&sCA(A,e,i),i};const Dy="SCAM";Bk(Dy,OC.getRootAsSyncedCameraModel);const HI=new xE;class rCA{constructor(A,e){r(this,"userId"),r(this,"guid"),this.guid=e,this.userId=A}send(A,e){if(A){HI.clear();const g=HI.createString(this.guid),i=HI.createString(this.userId);OC.startSyncedCameraModel(HI),OC.addGuid(HI,g),OC.addUserId(HI,i);const I=we(A),o=du(A);OC.addPos(HI,UI.createVec3(HI,I.x,I.y,I.z)),OC.addRot(HI,UI.createVec3(HI,o.x,o.y,o.z));const C=OC.endSyncedCameraModel(HI);HI.finish(C,Dy),e.sendBinary(HI.asUint8Array())}}}var LR;const xR=(LR=class extends RA{constructor(){super(...arguments),r(this,"cameraPrefab",null),r(this,"_lastWorldPosition"),r(this,"_lastWorldQuaternion"),r(this,"_model",null),r(this,"_needsUpdate",!0),r(this,"_lastUpdateTime",0),r(this,"remoteCams",{}),r(this,"userToCamMap",{}),r(this,"_camTimeoutInSeconds",10),r(this,"_receiveCallback",null)}getCameraObject(t){const A=this.userToCamMap[t];return A?this.remoteCams[A].obj:null}async awake(){this._lastWorldPosition=this.worldPosition.clone(),this._lastWorldQuaternion=this.worldQuaternion.clone(),this.cameraPrefab&&("uri"in this.cameraPrefab&&(this.cameraPrefab=await this.cameraPrefab.instantiate(this.gameObject)),this.cameraPrefab&&"isObject3D"in this.cameraPrefab&&(this.cameraPrefab.visible=!1))}onEnable(){this._receiveCallback=this.context.connection.beginListenBinary(Dy,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(Dy,this._receiveCallback)}update(){for(const g in this.remoteCams){const i=this.remoteCams[g],I=this.context.time.realtimeSinceStartup-i.lastUpdate;if(!i||I>this._camTimeoutInSeconds){console.log("Remote cam timeout",i,I),i!=null&&i.obj&&eA.destroy(i.obj),delete this.remoteCams[g],i&&delete this.userToCamMap[i.userId],xR.instances.push(i),this.context.players.removePlayerView(i.userId,QC.Browser);continue}}if(Se.IsInWebXR)return;const t=this.context.mainCamera;if(t===null){this.enabled=!1;return}if(!this.context.connection.isConnected||this.context.connection.connectionId===null)return;this._model===null&&(this._model=new rCA(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));const A=we(t),e=qg(t);(A.distanceTo(this._lastWorldPosition)>.001||e.angleTo(this._lastWorldQuaternion)>.01)&&(this._needsUpdate=!0),this._lastWorldPosition.copy(A),this._lastWorldQuaternion.copy(e),!((!this._needsUpdate||this.context.time.frameCount%2!==0)&&!(this.context.time.realtimeSinceStartup-this._lastUpdateTime>this._camTimeoutInSeconds*.5))&&(this._lastUpdateTime=this.context.time.realtimeSinceStartup,this._needsUpdate=!1,this._model.send(t,this.context.connection),this.context.isInXR||this.context.players.setPlayerView(this.context.connection.connectionId,t,QC.Browser))}onReceivedRemoteCameraInfoBin(t){const A=t.guid();if(!A)return;const e=t.userId();if(!e||!this.context.connection.userIsInRoom(e)||!this.cameraPrefab)return;let g=this.remoteCams[A];if(!g)if("isObject3D"in this.cameraPrefab){const C=new rC;C.context=this.context;const s=eA.instantiate(this.cameraPrefab,C);g=this.remoteCams[A]={obj:s,lastUpdate:this.context.time.realtimeSinceStartup,userId:e},g.obj.visible=!0,this.gameObject.add(s),this.userToCamMap[e]=A,xR.instances.push(g);const a=eA.getOrAddComponent(s,fi);a.connectionId=e,a.avatar=s}else return;const i=g.obj;this.context.players.setPlayerView(e,i,QC.Browser),g.lastUpdate=this.context.time.realtimeSinceStartup,pI.markDirty(i);const I=t.pos();I&&ZB(i,I.x(),I.y(),I.z());const o=t.rot();o&&pu(i,o.x(),o.y(),o.z())}},r(LR,"instances",[]),LR);let wy=xR;nCA([w([UA,yi])],wy.prototype,"cameraPrefab",2);var BCA=Object.defineProperty,QCA=Object.getOwnPropertyDescriptor,Vl=(t,A,e,g)=>{for(var i=g>1?void 0:g?QCA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&BCA(A,e,i),i};const YR="view",HR=CA("debugsyncedroom");class fn extends RA{constructor(){super(...arguments),r(this,"roomName"),r(this,"urlParameterName","room"),r(this,"joinRandomRoom",!0),r(this,"requireRoomParameter",!1),r(this,"autoRejoin",!0),r(this,"_roomPrefix"),r(this,"_lastPingTime",0),r(this,"_lastRoomTime",-1)}get RoomPrefix(){return this._roomPrefix}awake(){HR&&console.log("Room",this.roomName,this.urlParameterName,this.joinRandomRoom,this.requireRoomParameter,this.autoRejoin),this._roomPrefix===void 0&&(this._roomPrefix=this.roomName,this.roomName="")}onEnable(){const A=CA(YR);if(A&&typeof A=="string"&&A.length>0){console.log("Join as viewer"),this.context.connection.joinRoom(A,!0);return}(this.joinRandomRoom||CA(this.urlParameterName))&&this.tryJoinRoom()}onDisable(){this.roomName&&this.roomName.length>0&&this.context.connection.leaveRoom(this.roomName)}tryJoinRandomRoom(){this.setRandomRoomUrlParameter(),this.tryJoinRoom()}tryJoinRoom(A=0){A===void 0&&(A=0);let e=!1;if(this.urlParameterName){const g=CA(this.urlParameterName);if(g&&typeof g=="string"){e=!0;const i=zU(g);this.roomName=i}else if(this.joinRandomRoom&&(console.log("No room name found in url, generating random one"),this.setRandomRoomUrlParameter(),A<1))return this.tryJoinRoom(A+1)}else this.joinRandomRoom&&(this.roomName===null||this.roomName===void 0||this.roomName.length<=0)&&(console.log("generate room name"),this.roomName=this.generateRoomName());return this.requireRoomParameter&&!e?(HR&&console.log('No required room parameter "'+this.urlParameterName+'" in url - will not connect to networking backend.'),!1):(this.context.connection.isConnected||this.context.connection.connect(),HR&&console.log("Join "+this.roomName),this._roomPrefix&&(this.roomName=this._roomPrefix+this.roomName),this.context.connection.joinRoom(this.roomName),!0)}update(){this.context.connection.isConnected&&(this.context.time.time-this._lastPingTime>3&&(this._lastPingTime=this.context.time.time,this.context.connection.sendPing()),this.context.connection.isInRoom&&(this._lastRoomTime=this.context.time.time)),this._lastRoomTime>0&&this.context.time.time-this._lastRoomTime>.3&&(this._lastRoomTime=-1,this.autoRejoin?(console.log("Disconnected from networking backend - attempt reconnecting now"),this.tryJoinRoom()):console.warn("You are not connected to a room anymore (possibly because the tab was inactive for too long and the server kicked you)"))}get currentRoomName(){return CA(YR)||CA(this.urlParameterName)}setRandomRoomUrlParameter(){const A=zE(),e=this.generateRoomName();CA(this.urlParameterName)?A.set(this.urlParameterName,e):A.append(this.urlParameterName,e),KS(e,A)}generateRoomName(){return VU()+"_"+PU(100,999)}getViewOnlyUrl(){if(this.context.connection.isConnected&&this.context.connection.currentRoomViewId){const A=window.location.search,e=new URLSearchParams(A);return e.has(this.urlParameterName)&&e.delete(this.urlParameterName),e.set(YR,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+e.toString()}return null}}Vl([w()],fn.prototype,"roomName",2),Vl([w()],fn.prototype,"urlParameterName",2),Vl([w()],fn.prototype,"joinRandomRoom",2),Vl([w()],fn.prototype,"requireRoomParameter",2),Vl([w()],fn.prototype,"autoRejoin",2);function ECA(){const t=CA("testwindowcount")||0;t&&t>0&&hCA(t)}function hCA(t){if(CA("testwindow"))return null;const A=new URL(window.location.href);ZE(A.searchParams,_D,1),ZE(A.searchParams,"testwindow",1);const e=A.toString(),g=[];window.onbeforeunload=()=>{for(const s of g)s.close()};const i=.05,I=128;let o=0,C=0;for(let s=0;s<t;s++){o*I+I*.01>=window.innerWidth&&(C+=1,o=0);const a=o*(I*(1+i))+window.screenLeft,n=C*(I*(1+i))+window.screenTop+90+60*C;o+=1;const B=window.open(e,"test window "+s,`popup=yes width=${I} height=${I} top=${n} left=${a}`);if(!B){console.warn("Failed to open window");continue}g.push(B),B.onload=()=>{B.onbeforeunload=()=>{for(let Q=0;Q<g.length;Q++){const E=g[Q];E!==B&&E.close()}g.length=0}}}return g}class TR extends RA{awake(){ECA()}}class OR extends RA{constructor(){super(...arguments),r(this,"transformsPerFrame",10),r(this,"interval",0),r(this,"useFlatbuffers",!0),r(this,"builder",null),r(this,"models",null)}awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinary(bc,A=>{});else{this.models=[];for(let A=0;A<this.transformsPerFrame;A++)this.models.push(new R2(this.context.connection.connectionId+"_simulatedTransform_"+A,this))}}update(){if(this.context.connection.isConnected){if(this.useFlatbuffers){if(!this.context.connection.connectionId||this.context.time.frameCount%this.interval!==0)return;this.builder===null&&(this.builder=new xE(1024));const A=this.builder;for(let e=0;e<this.transformsPerFrame;e++){A.clear();const g=BY(this.context.connection.connectionId,this);this.context.connection.sendBinary(g)}}else if(this.models)for(let A=0;A<this.models.length;A++){const e=this.models[A];e.dontSave=!0,e.update(this,null),this.context.connection.send("TestSimulateUserData-"+A,e)}}}}class R2{constructor(A,e){r(this,"guid"),r(this,"fast",!1),r(this,"position"),r(this,"rotation"),r(this,"velocity"),r(this,"dontSave"),this.guid=A,this.position={x:0,y:0,z:0},this.rotation={x:0,y:0,z:0,w:0},this.update(e,null)}isValid(){return this.fast!==void 0||this.position!==void 0||this.rotation!==void 0||this.velocity!==void 0}update(A,e){const g=A.worldPosition;this.position.x=g.x,this.position.y=g.y,this.position.z=g.z;const i=A.worldQuaternion;if(this.rotation.x=i.x,this.rotation.y=i.y,this.rotation.z=i.z,this.rotation.w=i.w,this.fast=!1,e){const I=e.getVelocity();this.velocity===void 0&&(this.velocity={x:0,y:0,z:0}),this.velocity.x=I.x,this.velocity.y=I.y,this.velocity.z=I.z}}}r(R2,"temp",new f);var cCA=Object.defineProperty,lCA=Object.getOwnPropertyDescriptor,GE=(t,A,e,g)=>{for(var i=g>1?void 0:g?lCA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&cCA(A,e,i),i};class vC extends ki{constructor(){super(...arguments),r(this,"offset"),r(this,"rotation"),r(this,"focusArea"),r(this,"feather"),r(this,"kernelSize"),r(this,"resolutionScale")}get typeName(){return"TiltShiftEffect"}init(){this.offset.defaultValue=0,this.rotation.defaultValue=0,this.focusArea.defaultValue=.4,this.feather.defaultValue=.3,this.kernelSize.defaultValue=ws.MEDIUM,this.resolutionScale.defaultValue=1/window.devicePixelRatio}onCreateEffect(){console.log(this);const A=new lZ({kernelSize:ws.VERY_LARGE});return this.offset.onValueChanged=e=>A.offset=e,this.rotation.onValueChanged=e=>A.rotation=e,this.focusArea.onValueChanged=e=>A.focusArea=e,this.feather.onValueChanged=e=>A.feather=e,this.kernelSize.onValueChanged=e=>A.blurPass.kernelSize=e,this.resolutionScale.onValueChanged=e=>A.resolution.scale=e/window.devicePixelRatio,A}}GE([w(Ge)],vC.prototype,"offset",2),GE([w(Ge)],vC.prototype,"rotation",2),GE([w(Ge)],vC.prototype,"focusArea",2),GE([w(Ge)],vC.prototype,"feather",2),GE([w(Ge)],vC.prototype,"kernelSize",2),GE([w(Ge)],vC.prototype,"resolutionScale",2),po("TiltShiftEffect",vC);var dCA=Object.defineProperty,pCA=Object.getOwnPropertyDescriptor,uCA=(t,A,e,g)=>{for(var i=g>1?void 0:g?pCA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&dCA(A,e,i),i};class zl extends ki{constructor(){super(...arguments),r(this,"mode")}get typeName(){return"ToneMapping"}get isToneMapping(){return!0}init(){this.mode.defaultValue=Ki}apply(){this.mode.onValueChanged=this._apply.bind(this),this._apply(this.mode.value)}unapply(){this.context.renderer.toneMapping=Ki}_apply(A){switch(A){case 0:this.context.renderer.toneMapping=gh;break;case 1:this.context.renderer.toneMapping=ZS;break;case 2:this.context.renderer.toneMapping=XS;break}}}uCA([w(Ge)],zl.prototype,"mode",2),po("Tonemapping",zl);const AB=new VB,cI=new f,kn=new f,xt=new mA,U2={X:new f(1,0,0),Y:new f(0,1,0),Z:new f(0,0,1)},_R={type:"change"},F2={type:"mouseDown"},N2={type:"mouseUp",mode:null},K2={type:"objectChange"};class DCA extends UA{constructor(A,e){super(),e===void 0&&(console.warn('THREE.TransformControls: The second parameter "domElement" is now mandatory.'),e=document),this.isTransformControls=!0,this.visible=!1,this.domElement=e,this.domElement.style.touchAction="none";const g=new GCA;this._gizmo=g,this.add(g);const i=new mCA;this._plane=i,this.add(i);const I=this;function o(u,p){let D=p;Object.defineProperty(I,u,{get:function(){return D!==void 0?D:p},set:function(y){D!==y&&(D=y,i[u]=y,g[u]=y,I.dispatchEvent({type:u+"-changed",value:y}),I.dispatchEvent(_R))}}),I[u]=p,i[u]=p,g[u]=p}o("camera",A),o("object",void 0),o("enabled",!0),o("axis",null),o("mode","translate"),o("translationSnap",null),o("rotationSnap",null),o("scaleSnap",null),o("space","world"),o("size",1),o("dragging",!1),o("showX",!0),o("showY",!0),o("showZ",!0);const C=new f,s=new f,a=new mA,n=new mA,B=new f,Q=new mA,E=new f,h=new f,c=new f,l=0,d=new f;o("worldPosition",C),o("worldPositionStart",s),o("worldQuaternion",a),o("worldQuaternionStart",n),o("cameraPosition",B),o("cameraQuaternion",Q),o("pointStart",E),o("pointEnd",h),o("rotationAxis",c),o("rotationAngle",l),o("eye",d),this._offset=new f,this._startNorm=new f,this._endNorm=new f,this._cameraScale=new f,this._parentPosition=new f,this._parentQuaternion=new mA,this._parentQuaternionInv=new mA,this._parentScale=new f,this._worldScaleStart=new f,this._worldQuaternionInv=new mA,this._worldScale=new f,this._positionStart=new f,this._quaternionStart=new mA,this._scaleStart=new f,this._getPointer=wCA.bind(this),this._onPointerDown=SCA.bind(this),this._onPointerHover=yCA.bind(this),this._onPointerMove=fCA.bind(this),this._onPointerUp=kCA.bind(this),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointermove",this._onPointerHover),this.domElement.addEventListener("pointerup",this._onPointerUp)}updateMatrixWorld(){this.object!==void 0&&(this.object.updateMatrixWorld(),this.object.parent===null?console.error("TransformControls: The attached 3D object must be a part of the scene graph."):this.object.parent.matrixWorld.decompose(this._parentPosition,this._parentQuaternion,this._parentScale),this.object.matrixWorld.decompose(this.worldPosition,this.worldQuaternion,this._worldScale),this._parentQuaternionInv.copy(this._parentQuaternion).invert(),this._worldQuaternionInv.copy(this.worldQuaternion).invert()),this.camera.updateMatrixWorld(),this.camera.matrixWorld.decompose(this.cameraPosition,this.cameraQuaternion,this._cameraScale),this.camera.isOrthographicCamera?this.camera.getWorldDirection(this.eye).negate():this.eye.copy(this.cameraPosition).sub(this.worldPosition).normalize(),super.updateMatrixWorld(this)}pointerHover(A){if(this.object===void 0||this.dragging===!0)return;AB.setFromCamera(A,this.camera);const e=PR(this._gizmo.picker[this.mode],AB);e?this.axis=e.object.name:this.axis=null}pointerDown(A){if(!(this.object===void 0||this.dragging===!0||A.button!==0)&&this.axis!==null){AB.setFromCamera(A,this.camera);const e=PR(this._plane,AB,!0);e&&(this.object.updateMatrixWorld(),this.object.parent.updateMatrixWorld(),this._positionStart.copy(this.object.position),this._quaternionStart.copy(this.object.quaternion),this._scaleStart.copy(this.object.scale),this.object.matrixWorld.decompose(this.worldPositionStart,this.worldQuaternionStart,this._worldScaleStart),this.pointStart.copy(e.point).sub(this.worldPositionStart)),this.dragging=!0,F2.mode=this.mode,this.dispatchEvent(F2)}}pointerMove(A){const e=this.axis,g=this.mode,i=this.object;let I=this.space;if(g==="scale"?I="local":(e==="E"||e==="XYZE"||e==="XYZ")&&(I="world"),i===void 0||e===null||this.dragging===!1||A.button!==-1)return;AB.setFromCamera(A,this.camera);const o=PR(this._plane,AB,!0);if(o){if(this.pointEnd.copy(o.point).sub(this.worldPositionStart),g==="translate")this._offset.copy(this.pointEnd).sub(this.pointStart),I==="local"&&e!=="XYZ"&&this._offset.applyQuaternion(this._worldQuaternionInv),e.indexOf("X")===-1&&(this._offset.x=0),e.indexOf("Y")===-1&&(this._offset.y=0),e.indexOf("Z")===-1&&(this._offset.z=0),I==="local"&&e!=="XYZ"?this._offset.applyQuaternion(this._quaternionStart).divide(this._parentScale):this._offset.applyQuaternion(this._parentQuaternionInv).divide(this._parentScale),i.position.copy(this._offset).add(this._positionStart),this.translationSnap&&(I==="local"&&(i.position.applyQuaternion(xt.copy(this._quaternionStart).invert()),e.search("X")!==-1&&(i.position.x=Math.round(i.position.x/this.translationSnap)*this.translationSnap),e.search("Y")!==-1&&(i.position.y=Math.round(i.position.y/this.translationSnap)*this.translationSnap),e.search("Z")!==-1&&(i.position.z=Math.round(i.position.z/this.translationSnap)*this.translationSnap),i.position.applyQuaternion(this._quaternionStart)),I==="world"&&(i.parent&&i.position.add(cI.setFromMatrixPosition(i.parent.matrixWorld)),e.search("X")!==-1&&(i.position.x=Math.round(i.position.x/this.translationSnap)*this.translationSnap),e.search("Y")!==-1&&(i.position.y=Math.round(i.position.y/this.translationSnap)*this.translationSnap),e.search("Z")!==-1&&(i.position.z=Math.round(i.position.z/this.translationSnap)*this.translationSnap),i.parent&&i.position.sub(cI.setFromMatrixPosition(i.parent.matrixWorld))));else if(g==="scale"){if(e.search("XYZ")!==-1){let C=this.pointEnd.length()/this.pointStart.length();this.pointEnd.dot(this.pointStart)<0&&(C*=-1),kn.set(C,C,C)}else cI.copy(this.pointStart),kn.copy(this.pointEnd),cI.applyQuaternion(this._worldQuaternionInv),kn.applyQuaternion(this._worldQuaternionInv),kn.divide(cI),e.search("X")===-1&&(kn.x=1),e.search("Y")===-1&&(kn.y=1),e.search("Z")===-1&&(kn.z=1);i.scale.copy(this._scaleStart).multiply(kn),this.scaleSnap&&(e.search("X")!==-1&&(i.scale.x=Math.round(i.scale.x/this.scaleSnap)*this.scaleSnap||this.scaleSnap),e.search("Y")!==-1&&(i.scale.y=Math.round(i.scale.y/this.scaleSnap)*this.scaleSnap||this.scaleSnap),e.search("Z")!==-1&&(i.scale.z=Math.round(i.scale.z/this.scaleSnap)*this.scaleSnap||this.scaleSnap))}else if(g==="rotate"){this._offset.copy(this.pointEnd).sub(this.pointStart);const C=20/this.worldPosition.distanceTo(cI.setFromMatrixPosition(this.camera.matrixWorld));e==="E"?(this.rotationAxis.copy(this.eye),this.rotationAngle=this.pointEnd.angleTo(this.pointStart),this._startNorm.copy(this.pointStart).normalize(),this._endNorm.copy(this.pointEnd).normalize(),this.rotationAngle*=this._endNorm.cross(this._startNorm).dot(this.eye)<0?1:-1):e==="XYZE"?(this.rotationAxis.copy(this._offset).cross(this.eye).normalize(),this.rotationAngle=this._offset.dot(cI.copy(this.rotationAxis).cross(this.eye))*C):(e==="X"||e==="Y"||e==="Z")&&(this.rotationAxis.copy(U2[e]),cI.copy(U2[e]),I==="local"&&cI.applyQuaternion(this.worldQuaternion),this.rotationAngle=this._offset.dot(cI.cross(this.eye).normalize())*C),this.rotationSnap&&(this.rotationAngle=Math.round(this.rotationAngle/this.rotationSnap)*this.rotationSnap),I==="local"&&e!=="E"&&e!=="XYZE"?(i.quaternion.copy(this._quaternionStart),i.quaternion.multiply(xt.setFromAxisAngle(this.rotationAxis,this.rotationAngle)).normalize()):(this.rotationAxis.applyQuaternion(this._parentQuaternionInv),i.quaternion.copy(xt.setFromAxisAngle(this.rotationAxis,this.rotationAngle)),i.quaternion.multiply(this._quaternionStart).normalize())}this.dispatchEvent(_R),this.dispatchEvent(K2)}}pointerUp(A){A.button===0&&(this.dragging&&this.axis!==null&&(N2.mode=this.mode,this.dispatchEvent(N2)),this.dragging=!1,this.axis=null)}dispose(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerHover),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.traverse(function(A){A.geometry&&A.geometry.dispose(),A.material&&A.material.dispose()})}attach(A){return this.object=A,this.visible=!0,this}detach(){return this.object=void 0,this.visible=!1,this.axis=null,this}reset(){this.enabled&&this.dragging&&(this.object.position.copy(this._positionStart),this.object.quaternion.copy(this._quaternionStart),this.object.scale.copy(this._scaleStart),this.dispatchEvent(_R),this.dispatchEvent(K2),this.pointStart.copy(this.pointEnd))}getRaycaster(){return AB}getMode(){return this.mode}setMode(A){this.mode=A}setTranslationSnap(A){this.translationSnap=A}setRotationSnap(A){this.rotationSnap=A}setScaleSnap(A){this.scaleSnap=A}setSize(A){this.size=A}setSpace(A){this.space=A}}function wCA(t){if(this.domElement.ownerDocument.pointerLockElement)return{x:0,y:0,button:t.button};{const A=this.domElement.getBoundingClientRect();return{x:(t.clientX-A.left)/A.width*2-1,y:-(t.clientY-A.top)/A.height*2+1,button:t.button}}}function yCA(t){if(this.enabled)switch(t.pointerType){case"mouse":case"pen":this.pointerHover(this._getPointer(t));break}}function SCA(t){this.enabled&&(document.pointerLockElement||this.domElement.setPointerCapture(t.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.pointerHover(this._getPointer(t)),this.pointerDown(this._getPointer(t)))}function fCA(t){this.enabled&&this.pointerMove(this._getPointer(t))}function kCA(t){this.enabled&&(this.domElement.releasePointerCapture(t.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.pointerUp(this._getPointer(t)))}function PR(t,A,e){const g=A.intersectObject(t,!0);for(let i=0;i<g.length;i++)if(g[i].object.visible||e)return g[i];return!1}const yy=new mg,St=new f(0,1,0),J2=new f(0,0,0),q2=new KA,Sy=new mA,fy=new mA,bC=new f,v2=new KA,Zl=new f(1,0,0),eB=new f(0,1,0),Xl=new f(0,0,1),ky=new f,$l=new f,Ad=new f;class GCA extends UA{constructor(){super(),this.isTransformControlsGizmo=!0,this.type="TransformControlsGizmo";const A=new dt({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),e=new Ag({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),g=A.clone();g.opacity=.15;const i=e.clone();i.opacity=.5;const I=A.clone();I.color.setHex(16711680);const o=A.clone();o.color.setHex(65280);const C=A.clone();C.color.setHex(255);const s=A.clone();s.color.setHex(16711680),s.opacity=.5;const a=A.clone();a.color.setHex(65280),a.opacity=.5;const n=A.clone();n.color.setHex(255),n.opacity=.5;const B=A.clone();B.opacity=.25;const Q=A.clone();Q.color.setHex(16776960),Q.opacity=.25,A.clone().color.setHex(16776960);const E=A.clone();E.color.setHex(7895160);const h=new Zt(0,.04,.1,12);h.translate(0,.05,0);const c=new ct(.08,.08,.08);c.translate(0,.04,0);const l=new le;l.setAttribute("position",new ee([0,0,0,1,0,0],3));const d=new Zt(.0075,.0075,.5,3);d.translate(0,.25,0);function u(b,z){const gA=new HC(b,.0075,3,64,z*Math.PI*2);return gA.rotateY(Math.PI/2),gA.rotateX(Math.PI/2),gA}function p(){const b=new le;return b.setAttribute("position",new ee([0,0,0,1,1,1],3)),b}const D={X:[[new DA(h,I),[.5,0,0],[0,0,-Math.PI/2]],[new DA(h,I),[-.5,0,0],[0,0,Math.PI/2]],[new DA(d,I),[0,0,0],[0,0,-Math.PI/2]]],Y:[[new DA(h,o),[0,.5,0]],[new DA(h,o),[0,-.5,0],[Math.PI,0,0]],[new DA(d,o)]],Z:[[new DA(h,C),[0,0,.5],[Math.PI/2,0,0]],[new DA(h,C),[0,0,-.5],[-Math.PI/2,0,0]],[new DA(d,C),null,[Math.PI/2,0,0]]],XYZ:[[new DA(new YC(.1,0),B.clone()),[0,0,0]]],XY:[[new DA(new ct(.15,.15,.01),n.clone()),[.15,.15,0]]],YZ:[[new DA(new ct(.15,.15,.01),s.clone()),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new DA(new ct(.15,.15,.01),a.clone()),[.15,0,.15],[-Math.PI/2,0,0]]]},y={X:[[new DA(new Zt(.2,0,.6,4),g),[.3,0,0],[0,0,-Math.PI/2]],[new DA(new Zt(.2,0,.6,4),g),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new DA(new Zt(.2,0,.6,4),g),[0,.3,0]],[new DA(new Zt(.2,0,.6,4),g),[0,-.3,0],[0,0,Math.PI]]],Z:[[new DA(new Zt(.2,0,.6,4),g),[0,0,.3],[Math.PI/2,0,0]],[new DA(new Zt(.2,0,.6,4),g),[0,0,-.3],[-Math.PI/2,0,0]]],XYZ:[[new DA(new YC(.2,0),g)]],XY:[[new DA(new ct(.2,.2,.01),g),[.15,.15,0]]],YZ:[[new DA(new ct(.2,.2,.01),g),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new DA(new ct(.2,.2,.01),g),[.15,0,.15],[-Math.PI/2,0,0]]]},k={START:[[new DA(new YC(.01,2),i),null,null,null,"helper"]],END:[[new DA(new YC(.01,2),i),null,null,null,"helper"]],DELTA:[[new eg(p(),i),null,null,null,"helper"]],X:[[new eg(l,i.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new eg(l,i.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new eg(l,i.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},F={XYZE:[[new DA(u(.5,1),E),null,[0,Math.PI/2,0]]],X:[[new DA(u(.5,.5),I)]],Y:[[new DA(u(.5,.5),o),null,[0,0,-Math.PI/2]]],Z:[[new DA(u(.5,.5),C),null,[0,Math.PI/2,0]]],E:[[new DA(u(.75,1),Q),null,[0,Math.PI/2,0]]]},S={AXIS:[[new eg(l,i.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]]},U={XYZE:[[new DA(new OI(.25,10,8),g)]],X:[[new DA(new HC(.5,.1,4,24),g),[0,0,0],[0,-Math.PI/2,-Math.PI/2]]],Y:[[new DA(new HC(.5,.1,4,24),g),[0,0,0],[Math.PI/2,0,0]]],Z:[[new DA(new HC(.5,.1,4,24),g),[0,0,0],[0,0,-Math.PI/2]]],E:[[new DA(new HC(.75,.1,2,24),g)]]},M={X:[[new DA(c,I),[.5,0,0],[0,0,-Math.PI/2]],[new DA(d,I),[0,0,0],[0,0,-Math.PI/2]],[new DA(c,I),[-.5,0,0],[0,0,Math.PI/2]]],Y:[[new DA(c,o),[0,.5,0]],[new DA(d,o)],[new DA(c,o),[0,-.5,0],[0,0,Math.PI]]],Z:[[new DA(c,C),[0,0,.5],[Math.PI/2,0,0]],[new DA(d,C),[0,0,0],[Math.PI/2,0,0]],[new DA(c,C),[0,0,-.5],[-Math.PI/2,0,0]]],XY:[[new DA(new ct(.15,.15,.01),n),[.15,.15,0]]],YZ:[[new DA(new ct(.15,.15,.01),s),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new DA(new ct(.15,.15,.01),a),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new DA(new ct(.1,.1,.1),B.clone())]]},Y={X:[[new DA(new Zt(.2,0,.6,4),g),[.3,0,0],[0,0,-Math.PI/2]],[new DA(new Zt(.2,0,.6,4),g),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new DA(new Zt(.2,0,.6,4),g),[0,.3,0]],[new DA(new Zt(.2,0,.6,4),g),[0,-.3,0],[0,0,Math.PI]]],Z:[[new DA(new Zt(.2,0,.6,4),g),[0,0,.3],[Math.PI/2,0,0]],[new DA(new Zt(.2,0,.6,4),g),[0,0,-.3],[-Math.PI/2,0,0]]],XY:[[new DA(new ct(.2,.2,.01),g),[.15,.15,0]]],YZ:[[new DA(new ct(.2,.2,.01),g),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new DA(new ct(.2,.2,.01),g),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new DA(new ct(.2,.2,.2),g),[0,0,0]]]},O={X:[[new eg(l,i.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new eg(l,i.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new eg(l,i.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]};function x(b){const z=new UA;for(const gA in b)for(let sA=b[gA].length;sA--;){const AA=b[gA][sA][0].clone(),dA=b[gA][sA][1],rA=b[gA][sA][2],LA=b[gA][sA][3],MA=b[gA][sA][4];AA.name=gA,AA.tag=MA,dA&&AA.position.set(dA[0],dA[1],dA[2]),rA&&AA.rotation.set(rA[0],rA[1],rA[2]),LA&&AA.scale.set(LA[0],LA[1],LA[2]),AA.updateMatrix();const iA=AA.geometry.clone();iA.applyMatrix4(AA.matrix),AA.geometry=iA,AA.renderOrder=1/0,AA.position.set(0,0,0),AA.rotation.set(0,0,0),AA.scale.set(1,1,1),z.add(AA)}return z}this.gizmo={},this.picker={},this.helper={},this.add(this.gizmo.translate=x(D)),this.add(this.gizmo.rotate=x(F)),this.add(this.gizmo.scale=x(M)),this.add(this.picker.translate=x(y)),this.add(this.picker.rotate=x(U)),this.add(this.picker.scale=x(Y)),this.add(this.helper.translate=x(k)),this.add(this.helper.rotate=x(S)),this.add(this.helper.scale=x(O)),this.picker.translate.visible=!1,this.picker.rotate.visible=!1,this.picker.scale.visible=!1}updateMatrixWorld(A){const e=(this.mode==="scale"?"local":this.space)==="local"?this.worldQuaternion:fy;this.gizmo.translate.visible=this.mode==="translate",this.gizmo.rotate.visible=this.mode==="rotate",this.gizmo.scale.visible=this.mode==="scale",this.helper.translate.visible=this.mode==="translate",this.helper.rotate.visible=this.mode==="rotate",this.helper.scale.visible=this.mode==="scale";let g=[];g=g.concat(this.picker[this.mode].children),g=g.concat(this.gizmo[this.mode].children),g=g.concat(this.helper[this.mode].children);for(let i=0;i<g.length;i++){const I=g[i];I.visible=!0,I.rotation.set(0,0,0),I.position.copy(this.worldPosition);let o;if(this.camera.isOrthographicCamera?o=(this.camera.top-this.camera.bottom)/this.camera.zoom:o=this.worldPosition.distanceTo(this.cameraPosition)*Math.min(1.9*Math.tan(Math.PI*this.camera.fov/360)/this.camera.zoom,7),I.scale.set(1,1,1).multiplyScalar(o*this.size/4),I.tag==="helper"){I.visible=!1,I.name==="AXIS"?(I.position.copy(this.worldPositionStart),I.visible=!!this.axis,this.axis==="X"&&(xt.setFromEuler(yy.set(0,0,0)),I.quaternion.copy(e).multiply(xt),Math.abs(St.copy(Zl).applyQuaternion(e).dot(this.eye))>.9&&(I.visible=!1)),this.axis==="Y"&&(xt.setFromEuler(yy.set(0,0,Math.PI/2)),I.quaternion.copy(e).multiply(xt),Math.abs(St.copy(eB).applyQuaternion(e).dot(this.eye))>.9&&(I.visible=!1)),this.axis==="Z"&&(xt.setFromEuler(yy.set(0,Math.PI/2,0)),I.quaternion.copy(e).multiply(xt),Math.abs(St.copy(Xl).applyQuaternion(e).dot(this.eye))>.9&&(I.visible=!1)),this.axis==="XYZE"&&(xt.setFromEuler(yy.set(0,Math.PI/2,0)),St.copy(this.rotationAxis),I.quaternion.setFromRotationMatrix(q2.lookAt(J2,St,eB)),I.quaternion.multiply(xt),I.visible=this.dragging),this.axis==="E"&&(I.visible=!1)):I.name==="START"?(I.position.copy(this.worldPositionStart),I.visible=this.dragging):I.name==="END"?(I.position.copy(this.worldPosition),I.visible=this.dragging):I.name==="DELTA"?(I.position.copy(this.worldPositionStart),I.quaternion.copy(this.worldQuaternionStart),cI.set(1e-10,1e-10,1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1),cI.applyQuaternion(this.worldQuaternionStart.clone().invert()),I.scale.copy(cI),I.visible=this.dragging):(I.quaternion.copy(e),this.dragging?I.position.copy(this.worldPositionStart):I.position.copy(this.worldPosition),this.axis&&(I.visible=this.axis.search(I.name)!==-1));continue}I.quaternion.copy(e),this.mode==="translate"||this.mode==="scale"?(I.name==="X"&&Math.abs(St.copy(Zl).applyQuaternion(e).dot(this.eye))>.99&&(I.scale.set(1e-10,1e-10,1e-10),I.visible=!1),I.name==="Y"&&Math.abs(St.copy(eB).applyQuaternion(e).dot(this.eye))>.99&&(I.scale.set(1e-10,1e-10,1e-10),I.visible=!1),I.name==="Z"&&Math.abs(St.copy(Xl).applyQuaternion(e).dot(this.eye))>.99&&(I.scale.set(1e-10,1e-10,1e-10),I.visible=!1),I.name==="XY"&&Math.abs(St.copy(Xl).applyQuaternion(e).dot(this.eye))<.2&&(I.scale.set(1e-10,1e-10,1e-10),I.visible=!1),I.name==="YZ"&&Math.abs(St.copy(Zl).applyQuaternion(e).dot(this.eye))<.2&&(I.scale.set(1e-10,1e-10,1e-10),I.visible=!1),I.name==="XZ"&&Math.abs(St.copy(eB).applyQuaternion(e).dot(this.eye))<.2&&(I.scale.set(1e-10,1e-10,1e-10),I.visible=!1)):this.mode==="rotate"&&(Sy.copy(e),St.copy(this.eye).applyQuaternion(xt.copy(e).invert()),I.name.search("E")!==-1&&I.quaternion.setFromRotationMatrix(q2.lookAt(this.eye,J2,eB)),I.name==="X"&&(xt.setFromAxisAngle(Zl,Math.atan2(-St.y,St.z)),xt.multiplyQuaternions(Sy,xt),I.quaternion.copy(xt)),I.name==="Y"&&(xt.setFromAxisAngle(eB,Math.atan2(St.x,St.z)),xt.multiplyQuaternions(Sy,xt),I.quaternion.copy(xt)),I.name==="Z"&&(xt.setFromAxisAngle(Xl,Math.atan2(St.y,St.x)),xt.multiplyQuaternions(Sy,xt),I.quaternion.copy(xt))),I.visible=I.visible&&(I.name.indexOf("X")===-1||this.showX),I.visible=I.visible&&(I.name.indexOf("Y")===-1||this.showY),I.visible=I.visible&&(I.name.indexOf("Z")===-1||this.showZ),I.visible=I.visible&&(I.name.indexOf("E")===-1||this.showX&&this.showY&&this.showZ),I.material._color=I.material._color||I.material.color.clone(),I.material._opacity=I.material._opacity||I.material.opacity,I.material.color.copy(I.material._color),I.material.opacity=I.material._opacity,this.enabled&&this.axis&&(I.name===this.axis||this.axis.split("").some(function(C){return I.name===C}))&&(I.material.color.setHex(16776960),I.material.opacity=1)}super.updateMatrixWorld(A)}}class mCA extends DA{constructor(){super(new Zg(1e5,1e5,2,2),new dt({visible:!1,wireframe:!0,side:ft,transparent:!0,opacity:.1,toneMapped:!1})),this.isTransformControlsPlane=!0,this.type="TransformControlsPlane"}updateMatrixWorld(A){let e=this.space;switch(this.position.copy(this.worldPosition),this.mode==="scale"&&(e="local"),ky.copy(Zl).applyQuaternion(e==="local"?this.worldQuaternion:fy),$l.copy(eB).applyQuaternion(e==="local"?this.worldQuaternion:fy),Ad.copy(Xl).applyQuaternion(e==="local"?this.worldQuaternion:fy),St.copy($l),this.mode){case"translate":case"scale":switch(this.axis){case"X":St.copy(this.eye).cross(ky),bC.copy(ky).cross(St);break;case"Y":St.copy(this.eye).cross($l),bC.copy($l).cross(St);break;case"Z":St.copy(this.eye).cross(Ad),bC.copy(Ad).cross(St);break;case"XY":bC.copy(Ad);break;case"YZ":bC.copy(ky);break;case"XZ":St.copy(Ad),bC.copy($l);break;case"XYZ":case"E":bC.set(0,0,0);break}break;case"rotate":default:bC.set(0,0,0)}bC.length()===0?this.quaternion.copy(this.cameraQuaternion):(v2.lookAt(cI.set(0,0,0),bC,St),this.quaternion.setFromRotationMatrix(v2)),super.updateMatrixWorld(A)}}var MCA=Object.defineProperty,RCA=Object.getOwnPropertyDescriptor,Gy=(t,A,e,g)=>{for(var i=g>1?void 0:g?RCA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&MCA(A,e,i),i};class tB extends RA{constructor(){super(...arguments),r(this,"isGizmo",!1),r(this,"translationSnap",1),r(this,"rotationSnapAngle",15),r(this,"scaleSnap",.25),r(this,"control"),r(this,"orbit"),r(this,"changeEventListener"),r(this,"windowKeyDownListener"),r(this,"windowKeyUpListener")}onEnable(){var A;this.isGizmo&&!vh||this.context.mainCamera&&(this.control||(this.control=new DCA(this.context.mainCamera,this.context.domElement),this.control.visible=!0,this.control.enabled=!0,this.control.getRaycaster().layers.set(2),this.control.size=1,this.control.traverse(e=>{const g=e;if(g.layers.set(2),g){const i=g.material;i&&(i.opacity=.3)}}),this.orbit=eA.getComponentInParent(this.context.mainCamera,Ts)??void 0),this.control&&(this.context.scene.add(this.control),this.control.attach(this.gameObject),this.changeEventListener=this.onControlChangedEvent.bind(this),(A=this.control)==null||A.addEventListener("dragging-changed",this.changeEventListener),this.addWindowEvents()))}onDisable(){var A,e;(A=this.control)==null||A.removeFromParent(),this.changeEventListener&&((e=this.control)==null||e.removeEventListener("dragging-changed",this.changeEventListener)),this.removeWindowEvents()}enableSnapping(){this.control&&(this.control.setTranslationSnap(this.translationSnap),this.control.setRotationSnap(Ji.degToRad(this.rotationSnapAngle)),this.control.setScaleSnap(this.scaleSnap))}disableSnapping(){this.control&&(this.control.setTranslationSnap(null),this.control.setRotationSnap(null),this.control.setScaleSnap(null))}onControlChangedEvent(A){const e=this.orbit;if(e&&(e.enabled=!A.value),A.value){const g=eA.getComponentInParent(this.gameObject,Cn);g&&g.requestOwnership()}}addWindowEvents(){const A=this.control;A&&(this.windowKeyDownListener||(this.windowKeyDownListener=e=>{if(this.enabled)switch(e.keyCode){case 81:A.setSpace(A.space==="local"?"world":"local");break;case 16:this.enableSnapping();break;case 87:A.setMode("translate");break;case 69:A.setMode("rotate");break;case 82:A.setMode("scale");break;case 187:case 107:A.setSize(A.size+.1);break;case 189:case 109:A.setSize(Math.max(A.size-.1,.1));break;case 88:A.showX=!A.showX;break;case 89:A.showY=!A.showY;break;case 90:A.showZ=!A.showZ;break;case 32:A.enabled=!A.enabled;break}}),this.windowKeyUpListener||(this.windowKeyUpListener=e=>{if(this.enabled)switch(e.keyCode){case 16:this.disableSnapping();break}}),window.addEventListener("keydown",this.windowKeyDownListener),window.addEventListener("keyup",this.windowKeyUpListener))}removeWindowEvents(){window.removeEventListener("keydown",this.windowKeyDownListener),window.removeEventListener("keyup",this.windowKeyUpListener)}}Gy([w()],tB.prototype,"isGizmo",2),Gy([w()],tB.prototype,"translationSnap",2),Gy([w()],tB.prototype,"rotationSnapAngle",2),Gy([w()],tB.prototype,"scaleSnap",2);var UCA=Object.defineProperty,FCA=Object.getOwnPropertyDescriptor,jR=(t,A,e,g)=>{for(var i=g>1?void 0:g?FCA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&UCA(A,e,i),i};class gB extends ki{constructor(){super(...arguments),r(this,"color"),r(this,"intensity"),r(this,"center")}get typeName(){return"Vignette"}init(){this.color.defaultValue={r:0,g:0,b:0,a:1},this.intensity.defaultValue=0,this.center.defaultValue={x:.5,y:.5}}onCreateEffect(){const A=new lb;return this.intensity.onValueChanged=e=>{A.offset=e,this.updateDarkness(A)},this.color.onValueChanged=e=>{this.updateDarkness(A)},A}updateDarkness(A){const e=this.intensity.value;A.darkness=e}}jR([w(Ge)],gB.prototype,"color",2),jR([w(Ge)],gB.prototype,"intensity",2),jR([w(Ge)],gB.prototype,"center",2),po("Vignette",gB);var NCA=Object.defineProperty,KCA=Object.getOwnPropertyDescriptor,JCA=(t,A,e,g)=>{for(var i=g>1?void 0:g?KCA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&NCA(A,e,i),i};const WR=CA("debugpost");class my extends RA{constructor(){super(...arguments),r(this,"sharedProfile"),r(this,"_postprocessing"),r(this,"_effects",[]),r(this,"_lastApplyTime"),r(this,"_rapidApplyCount",0),r(this,"_isDirty",!1),r(this,"_modificationQueue"),r(this,"_recreateId",-1)}markDirty(){this._isDirty=!0}awake(){var A;(A=this.sharedProfile)==null||A.init(),WR&&(console.log(this),console.log("Press P to toggle post processing"),window.addEventListener("keydown",e=>{e.key==="p"&&(console.log("Toggle volume: "+this.name,!this.enabled),this.enabled=!this.enabled)}))}onDisable(){var A;(A=this._postprocessing)==null||A.unapply()}onBeforeRender(){if(!this.context.isInXR){if(this.context.composer&&!(this.context.composer instanceof jk))return;this.context.mainCamera&&(!this._postprocessing||!this._postprocessing.isActive||this._isDirty)&&this.apply(),this.context.composer&&(this.context.composer.setRenderer(this.context.renderer),this.context.composer.setMainScene(this.context.scene),this.context.mainCamera&&this.context.composer.setMainCamera(this.context.mainCamera))}}onDestroy(){var A;(A=this._postprocessing)==null||A.dispose()}apply(){var A,e;WR&&console.log("Apply PostProcessing",this,(A=this.context.mainCamera)==null?void 0:A.name),pi()&&(this._lastApplyTime!==void 0&&Date.now()-this._lastApplyTime<100&&(this._rapidApplyCount++,this._rapidApplyCount===5&&console.warn("Detected rapid post processing modifications - this might be a bug",this)),this._lastApplyTime=Date.now()),this._isDirty=!1,this.unapply(),this._effects.length=0,(e=this.sharedProfile)!=null&&e.components&&this._effects.push(...this.sharedProfile.components);const g=this.gameObject.getComponentsInChildren(ki);if(WR&&g!=null&&g.length&&console.log("Additional",g),g)for(const i of g)i.active&&this._effects.push(i);this._effects.length>0&&(this._postprocessing||(this._postprocessing=new By(this.context)),this._postprocessing.apply(this._effects),this._applyPostQueue())}unapply(){var A;(A=this._postprocessing)==null||A.unapply()}_applyPostQueue(){if(this._modificationQueue){for(const A of this._modificationQueue.values())this.onEditorModification(A);this._modificationQueue.clear()}}onEditorModification(A){var e,g;if(A.propertyName.startsWith("postprocessing.")){if(!this._postprocessing)return this._modificationQueue||(this._modificationQueue=new Map),this._modificationQueue.set(A.propertyName,A),!0;if(!((e=this._effects)!=null&&e.length))return;const i=A.propertyName.split(".");if(i.length===3||i.length===4){const I=i[1],o=i[2];for(const C of this._effects)if(((g=C.typeName)==null?void 0:g.toLowerCase())===I.toLowerCase()){if(o==="active"){C.active=A.value,this.scheduleRecreate();return}if(!My.has(I)){const s=new Array;My.set(I,s);const a=Object.keys(C);for(const n of a)C[n]instanceof Ge&&s.push(n)}if(My.has(I)){const s=o.toLowerCase(),a=My.get(I);for(const n of a)if(n.toLowerCase()===s){const B=C[n];B instanceof Ge&&(i.length===4&&i[3]==="active"?(B.overrideState=A.value,this.scheduleRecreate()):B&&B.value!==void 0&&(B.value=A.value));return}}console.warn("Unknown modification",o);return}}return!0}return!1}scheduleRecreate(){const A=++this._recreateId;setTimeout(()=>{A===this._recreateId&&(this.onDisable(),this.onEnable())},200)}}JCA([mQ(rl)],my.prototype,"sharedProfile",2);const My=new Map;var qCA=Object.defineProperty,vCA=Object.getOwnPropertyDescriptor,bCA=(t,A,e,g)=>{for(var i=g>1?void 0:g?vCA(A,e):A,I=t.length-1,o;I>=0;I--)(o=t[I])&&(i=(g?o(A,e,i):o(i))||i);return g&&i&&qCA(A,e,i),i};class Ry extends RA{constructor(){super(...arguments),r(this,"backgroundTint",new wt(1,1,1,1)),r(this,"_preRender"),r(this,"backgroundPlane"),r(this,"threeTexture"),r(this,"forceTextureInitialization",function(){const A=new dt,e=new Zg,g=new gI;g.add(new DA(e,A));const i=new Vn;return function(I,o){A.map=o,I.render(g,i)}}())}awake(){Se.OptionalFeatures_AR.push("camera-access")}get background(){return this.backgroundPlane}onEnable(){this._preRender=this.preRender.bind(this),this.context.pre_render_callbacks.push(this._preRender),this.backgroundPlane&&(this.gameObject.add(this.backgroundPlane),this.backgroundPlane.visible=!1)}onDisable(){this.context.pre_render_callbacks=this.context.pre_render_callbacks.filter(A=>A!==this._preRender),this.backgroundPlane&&this.gameObject.remove(this.backgroundPlane)}preRender(){if(!this||!this.gameObject)return;const A=this.context.renderer.xr.getFrame();A&&(!this.threeTexture&&this.context.renderer&&(this.threeTexture=new Le,this.forceTextureInitialization(this.context.renderer,this.threeTexture)),this.backgroundPlane===void 0&&(this.backgroundPlane=xCA(this.backgroundTint),this.gameObject.add(this.backgroundPlane)),this.updateFromFrame(A))}onBeforeRender(A){this.updateFromFrame(A)}updateFromFrame(A){if(!A)return;const e=A.getViewerPose(this.context.renderer.xr.getReferenceSpace());if(e){for(const g of e.views)if("camera"in g&&g.camera){let i=this.context.renderer.xr.getBinding();if(i||(i=new XRWebGLBinding(A.session,this.context.renderer.getContext())),i){let I=null;if("getCameraImage"in i){I=i.getCameraImage(g.camera);const o=this.context.renderer.properties.get(this.threeTexture);o.__webglTexture=I,this.backgroundPlane&&(this.backgroundPlane.setTexture(this.threeTexture),this.backgroundPlane.visible=!0)}}}}}}bCA([w()],Ry.prototype,"backgroundTint",2);let LCA=`
|
|
5439
5439
|
uniform sampler2D t2D;
|
|
5440
5440
|
|
|
5441
5441
|
varying vec2 vUv;
|