const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./needle-engine.CE4b2dOg.js","./needle-engine@5.0.3.js","./rolldown-runtime.CYVBeYYp.js","./needle-engine-webxr.Cp-vkXLP.js","./materialx.CnHmG--Y.js","./three@0.169.19.js","./needle-engine-ui.DC9_O2Mo.js","./gltf-progressive.U_EoiMHF.js","./three-examples@0.169.19.js","./three-mesh-ui.CgGzZ3ml.js","./three-examples.extras@0.169.19.js","./needle-engine-particles.ByRryBGL.js","./three-quarks.DALdLWPD.js","./needle-engine.extras.X7Svjxj0.js","./postprocessing.Wy71DpiM.js","./three-mesh-bvh.B-oXEGo2.js"])))=>i.map(i=>d[i]); import{d as e}from"./materialx.CnHmG--Y.js";import{A as t,Ar as n,At as r,D as i,Gn as a,Jt as o,Kn as s,Mr as c,Nr as l,Nt as u,P as d,Q as f,Qn as p,Qt as m,R as ee,S as h,T as g,Tn as te,Xt as _,Z as ne,Zn as re,Zt as v,_ as ie,_n as ae,a as oe,d as se,fn as y,fr as ce,gn as le,gr as ue,i as de,in as fe,jr as pe,jt as me,kr as b,kt as he,nr as ge,s as _e,st as ve,tr as ye,tt as be,u as xe,ur as Se,ut as Ce,vn as we,wn as x,x as Te,y as Ee,yn as De}from"./three@0.169.19.js";import{$i as S,A as C,Aa as Oe,An as ke,Ao as Ae,B as je,Br as Me,C as Ne,D as Pe,Di as Fe,Dr as Ie,E as Le,Ea as Re,F as ze,Fa as Be,Fo as Ve,G as He,Ho as Ue,I as We,Io as Ge,Ir as Ke,Jt as qe,Ka as w,Kr as T,L as E,Lo as Je,Ma as Ye,Mo as Xe,Mr as Ze,Ni as Qe,No as $e,Nr as et,Nt as tt,Ot as nt,P as rt,Q as it,Qi as at,S as ot,T as D,Ua as O,Uo as st,W as ct,Wo as lt,X as k,Xi as A,Z as ut,Zi as j,Zn as dt,_ as ft,_a as M,a as pt,ai as mt,ao as ht,at as gt,ba as _t,co as N,cr as P,ct as F,dn as vt,ea as I,eo as yt,f as bt,fi as xt,fn as St,g as Ct,h as wt,hi as Tt,i as Et,io as Dt,j as Ot,ja as kt,jo as At,k as jt,kt as L,l as Mt,la as Nt,ln as Pt,n as Ft,na as It,ni as Lt,o as Rt,oo as zt,ot as R,p as Bt,pa as z,q as Vt,r as B,ra as Ht,s as Ut,sa as Wt,sn as Gt,t as Kt,tr as qt,u as Jt,un as V,uo as Yt,va as Xt,vr as Zt,wa as Qt,wi as $t,x as en,xr as tn,y as nn,ya as rn,yn as an}from"./needle-engine-ui.DC9_O2Mo.js";import{d as on,l as sn}from"./three-examples.extras@0.169.19.js";import{$t as cn,A as ln,B as un,Bt as dn,C as fn,Ft as pn,G as mn,Gt as hn,H as gn,It as _n,J as vn,K as yn,Kt as bn,L as xn,Lt as Sn,N as Cn,Ot as wn,P as Tn,Qt as En,Rt as Dn,S as On,U as kn,Ut as An,V as jn,Vt as Mn,W as Nn,Wt as Pn,X as Fn,Xt as In,Y as Ln,Yt as Rn,Zt as zn,at as Bn,bt as Vn,cn as Hn,d as Un,dn as Wn,f as Gn,fn as Kn,j as qn,k as Jn,ln as Yn,lt as Xn,m as Zn,mn as Qn,n as $n,nn as er,o as tr,on as nr,pn as rr,q as ir,qt as ar,r as or,rt as sr,sn as cr,st as lr,t as ur,tn as dr,tt as fr,un as pr,w as mr,x as hr,xt as gr,yt as _r}from"./needle-engine-webxr.Cp-vkXLP.js";import{r as vr,t as yr}from"./needle-engine-particles.ByRryBGL.js";import{a as br,c as xr,d as Sr,f as Cr,h as wr,i as Tr,l as Er,m as Dr,o as Or,p as kr,r as Ar,s as jr,t as Mr,u as Nr}from"./needle-engine.extras.X7Svjxj0.js";var Pr=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},Fr=N(`debugsignals`),Ir=class{guid};Pr([A()],Ir.prototype,`guid`,void 0);var Lr=class{signal;reaction};Pr([A(Ir)],Lr.prototype,`signal`,void 0),Pr([A(k)],Lr.prototype,`reaction`,void 0);var Rr=class e extends R{static receivers={};static invoke(t){if(e.receivers[t]){let n=e.receivers[t];if(!n)return;for(let e of n)e.invoke(t)}}events;awake(){Fr&&console.log(`SignalReceiver awake`,this)}onEnable(){if(this.events)for(let t of this.events)e.receivers[t.signal.guid]||(e.receivers[t.signal.guid]=[]),e.receivers[t.signal.guid].push(this)}onDisable(){if(this.events){for(let t of this.events)if(e.receivers[t.signal.guid]){let n=e.receivers[t.signal.guid].indexOf(this);n>=0&&e.receivers[t.signal.guid].splice(n,1)}}}invoke(e){if(!this.events||!Array.isArray(this.events))return;let t=typeof e==`object`?e.guid:e;for(let e of this.events)if(e.signal.guid===t)try{if(!e.reaction){console.warn(`Missing reaction for signal`,e,this);continue}else if(!e.reaction.invoke){console.warn(`Missing invoke - possibly a serialization error`,e,this);continue}e.reaction.invoke()}catch(e){console.error(e)}}};Pr([A(Lr)],Rr.prototype,`events`,void 0);var zr;(function(e){e.Activation=`ActivationTrack`,e.Animation=`AnimationTrack`,e.Audio=`AudioTrack`,e.Control=`ControlTrack`,e.Marker=`MarkerTrack`,e.Signal=`SignalTrack`})(zr||={});var Br;(function(e){e[e.None=0]=`None`,e[e.Hold=1]=`Hold`,e[e.Loop=2]=`Loop`,e[e.PingPong=3]=`PingPong`,e[e.Continue=4]=`Continue`})(Br||={});var Vr;(function(e){e.Signal=`SignalEmitter`})(Vr||={});var Hr=N(`debugtimeline`),Ur=class{director;track;get muted(){return this.track.muted}set muted(e){e!==this.track.muted&&(this.track.muted=e,this.onMuteChanged?.call(this))}*forEachClip(e=!1){if(this.track?.clips)if(e)for(let e=this.track.clips.length-1;e>=0;e--)yield this.track.clips[e];else for(let e of this.track.clips)yield e}getClipTime(e,t){return t.clipIn+(e-t.start)*t.timeScale}getClipTimeNormalized(e,t){return(e-t.start)/t.duration}evaluateWeight(e,t,n,r=!0){if(t<0||t>=n.length)return 0;let i=n[t];if(r||e>=i.start&&e<=i.end){let t=1;if(i.easeInDuration>0){let n=Math.min((e-i.start)/i.easeInDuration,1);t*=n}if(i.easeOutDuration>0){let n=Math.min((i.end-e)/i.easeOutDuration,1);t*=n}return t}return 0}},Wr=class{clip;rootPositionOffset;rootQuaternionOffset;get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}rootStartPosition;rootEndPosition;rootStartQuaternion;rootEndQuaternion;constructor(e){let t=e.getClip();this.clip=t;let r=e.getRoot(),i=r.name+`.position`,a=r.name+`.quaternion`;Hr&&console.log(t.name,t.tracks,i);for(let e of t.tracks)if(!(e.times.length<=0)){if(e.name.endsWith(i))this.rootStartPosition=new n().fromArray(e.values,0),this.rootEndPosition=new n().fromArray(e.values,e.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),Hr&&console.log(this.rootPositionOffset);else if(e.name.endsWith(a)&&(this.rootStartQuaternion=new x().fromArray(e.values,0),this.rootEndQuaternion=new x().fromArray(e.values,e.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),Hr)){let e=new be().setFromQuaternion(this.rootQuaternionOffset);console.log(`ROT`,e)}}}},Gr=class extends Ur{models=[];trackOffset;target;mixer;clips=[];actions=[];weight=1;_actionOffsets=[];_didBind=!1;_animator=null;onDisable(){this.mixer?.stopAllAction()}onDestroy(){this.director.context.animations.unregisterAnimationMixer(this.mixer)}onStateChanged(){this._animator&>(this._animator.gameObject,this,this.director.enabled&&this.director.weight>0)}createHooks(e,t){if(t.tracks?.length<=0){console.warn(`No tracks in AnimationClip`,t);return}let n=!1,r=!1,i=t.tracks.find(e=>e.name.includes(`.position`)||e.name.includes(`.quaternion`))?.name.split(`.`);if(i){let a=i[i.length-2],o=a+`.position`,s=a+`.quaternion`;for(let i of t.tracks)!n&&i.name.endsWith(o)?(n=!0,this.createPositionInterpolant(t,e,i)):!r&&i.name.endsWith(s)&&(r=!0,this.createRotationInterpolant(t,e,i))}if(!n||!r){let i=this.mixer?.getRoot(),a=t.tracks[0],o=a.name.lastIndexOf(`.`),s=a.name.substring(0,o),l=s.substring(s.lastIndexOf(`.`)+1),u=i.getObjectByName(l);if(u){if(!n){let n=s+`.position`;Hr&&console.warn(`Create position track`,l,u);let r=new c(n,[0,t.duration],[0,0,0,0,0,0]);t.tracks.push(r),this.createPositionInterpolant(t,e,r)}else if(!r){let n=t.tracks[0].name.substring(0,o)+`.quaternion`;Hr&&console.warn(`Create quaternion track`,l,u);let r=new te(n,[0,t.duration],[0,0,0,1,0,0,0,1]);t.tracks.push(r),this.createRotationInterpolant(t,e,r)}}}}bind(){if(!this._didBind){this._didBind=!0,Hr&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn(`No mixer was assigned to animation track`);for(let e of this.actions){let t=new Wr(e);this._actionOffsets.push(t)}this.target&&(this._animator=F.getComponent(this.target,it)??null,this._animator&>(this._animator.gameObject,this,!0));for(let e of this.models){let t=e.asset,r=t.position,i=t.rotation;r&&r.x!==void 0&&(r.isVector3||(t.position=new n(r.x,r.y,r.z)),i.isQuaternion||(t.rotation=new x(i.x,i.y,i.z,i.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){let e=this.trackOffset.position;e&&(e.isVector3||(this.trackOffset.position=new n(e.x,e.y,e.z)));let t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new x(t.x,t.y,t.z,t.w)))}}_useclipOffsets=!0;_totalOffsetPosition=new n;_totalOffsetRotation=new x;_totalOffsetPosition2=new n;_totalOffsetRotation2=new x;_summedPos=new n;_tempPos=new n;_summedRot=new x;_tempRot=new x;_clipRotQuat=new x;evaluate(e){if(this.track.muted||!this.mixer)return;this.bind(),this._totalOffsetPosition.set(0,0,0),this._totalOffsetRotation.set(0,0,0,1),this._totalOffsetPosition2.set(0,0,0),this._totalOffsetRotation2.set(0,0,0,1);let t=0,n=0,r=!1,i=!1,a=0;for(let o=0;o=s.start&&e<=s.end,d=s.preExtrapolationMode,f=s.postExtrapolationMode,p=oe)&&(m=!0,r=!0):o==0&&!m&&!i&&s.start>e&&d!==Br.None&&(!p||p.startte;)h-=te}else if(!u&&r)switch(f){case Br.Hold:h=this.getClipTime(s.end,s);break;case Br.Loop:h%=te;break;case Br.PingPong:let e=Math.floor(h/te)%2!=0;h%=te,e&&(h=te-h);break}s.reversed===!0?c.time=c.getClip().duration-h:c.time=h,c.timeScale=0;let _=Math.max(0,i);if(c.weight=_,a+=_,c.clampWhenFinished=!1,c.isRunning()||c.play(),this._useclipOffsets){let e=t==0?this._totalOffsetPosition:this._totalOffsetPosition2,r=t==0?this._totalOffsetRotation:this._totalOffsetRotation2;t<1&&(n=1-i),t+=1;let a=this._summedPos.set(0,0,0),s=this._tempPos.set(0,0,0),c=this._summedRot.identity(),u=this._tempRot.identity(),d=l.rotation;d&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp(d,i));let f=this._actionOffsets[o];if(f.hasOffsets)for(let e=0;e{let e=r(),t=e.evaluate.bind(e);return e.evaluate=e=>{let n=t(e);if(i.set(n[0],n[1],n[2],n[3]),i.premultiply(this._totalOffsetRotation),a&&i.premultiply(a),this.director.animationCallbackReceivers)for(let t of this.director.animationCallbackReceivers)t?.onTimelineRotation?.call(t,this.director,this.target,e,i);return n[0]=i.x,n[1]=i.y,n[2]=i.z,n[3]=i.w,n},e}}createPositionInterpolant(e,t,r){let i=r.createInterpolant.bind(r),a=new n;this.ensureTrackOffsets();let o=this.trackOffset?.rotation,s=this.trackOffset?.position,c;r.createInterpolant=()=>{let n=i(),r=n.evaluate.bind(n);return n.evaluate=n=>{let i=r(n);if(a.set(i[0],i[1],i[2]),t.removeStartOffset&&(c===void 0?(c=null,c=this._actionOffsets.find(t=>t.clip===e)?.rootStartPosition?.clone()):c?.isVector3&&a.sub(c)),a.applyQuaternion(this._totalOffsetRotation),a.add(this._totalOffsetPosition),o&&a.applyQuaternion(o),s&&(a.x-=s.x,a.y+=s.y,a.z+=s.z),this.director.animationCallbackReceivers)for(let e of this.director.animationCallbackReceivers)e?.onTimelinePosition?.call(e,this.director,this.target,n,a);return i[0]=a.x,i[1]=a.y,i[2]=a.z,i},n}}},Kr=N(`mutetimeline`),qr=class e extends Ur{models=[];listener;audio=[];audioContextTimeOffset=[];lastTime=0;audioSource;_audioLoader=null;getAudioFilePath(e){let t=this.director.sourceId;return At(t,e)}onAllowAudioChanged(e){for(let t=0;t=a.start&&e<=a.end&&e.3?o.offset=a.clipIn+(e-a.start)*a.timeScale:o.offset=0,Hr&&console.log(`Timeline Audio (`+this.track.name+`) play with offset `+o.offset+` - `+a.asset.clip),o.play(r),a._didTriggerPlay=!0);else{let t=a.clipIn+(e-a.start)*a.timeScale,n=o.context.currentTime-o._startedAt+o.offset;Math.abs(t-n)>.3&&(o.offset=t,o.stop(),o.play(r))}let i=s.volume;if(this.track.volume!==void 0&&(i*=this.track.volume),t&&(i=0),a.easeInDuration>0){let t=Math.min((e-a.start)/a.easeInDuration,1);i*=t}if(a.easeOutDuration>0){let t=Math.min((a.end-e)/a.easeOutDuration,1);i*=t}o.setVolume(i*this.director.weight)}else a._didTriggerPlay=!1,this.director.isPlaying&&o.isPlaying&&o.stop()}this.lastTime=e}loadAudio(e,t=0,n=0){let r=null,i=e-n,a=e+t;for(let e of this.models)if(this.isInTimeRange(e,i,a)){let t=this.audio[this.models.indexOf(e)],n=this.handleAudioLoading(e,t);n!==null&&(r===null&&(r=[]),r.push(n))}return r===null?null:Promise.all(r)}isInTimeRange(e,t,n){return t<=e.start&&n>=e.end||t>=e.start&&t<=e.end||n>=e.start&&n<=e.end}static _audioBuffers=new Map;static dispose(){e._audioBuffers.clear()}handleAudioLoading(t,n){this._audioLoader||=new xe;let r=this.getAudioFilePath(t.asset.clip);if(e._audioBuffers.get(r)){let t=e._audioBuffers.get(r);return t.then(e=>{e&&n.setBuffer(e)}),t}Hr&&console.warn(`LOAD audio track`,r,this.director.sourceId);let i=new Promise((e,t)=>{this._audioLoader.load(r,t=>{n.setBuffer(t),e(t)},void 0,t=>{console.error(`Error loading audio`,t),e(null)})});return e._audioBuffers.set(r,i),i}},Jr=class extends Ur{models=[];needsSorting=!0;*foreachMarker(e=null){this.needsSorting&&this.sort();for(let t of this.models)t&&t.type===e&&(yield t)}onEnable(){this.needsSorting=!0}evaluate(e){this.needsSorting&&this.sort()}sort(){this.needsSorting=!1,this.models.sort((e,t)=>e.time-t.time)}},Yr=class extends Ur{models=[];didTrigger=[];receivers=[];evaluate(e){if(this.track.muted)return;let t=this.director.context.time.deltaTime*1.5;for(let n=0;n=1e-5&&e=0;e--){let t=this.models[e].asset;if(!t.sourceObject||typeof t.sourceObject!=`object`){console.log(`no source object, removing model`,e,t),this.models.splice(e,1);continue}else{let e=this.director.constructor,n=F.getComponent(t.sourceObject,e);this.timelines.push(n),n&&t.updateDirector&&(n.playOnAwake=!1)}}}_previousActiveModel=null;evaluate(e){this._previousActiveModel=null;for(let t=0;t=n.start&&e<=n.end){this._previousActiveModel=n;let i=this.getClipTime(e,n);if(r.controlActivation){let e=r.sourceObject;e.visible=!0}if(r.updateDirector){let e=this.timelines[t];e&&(e.isPlaying&&e.pause(),e.time=i,e.evaluate())}}else{let e=this._previousActiveModel?.asset;if(r.controlActivation){let t=r.sourceObject;e?.sourceObject!==t&&(t.visible=!1)}}}}},Zr=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},Qr=N(`debugtimeline`),$r;(function(e){e[e.Hold=0]=`Hold`,e[e.Loop=1]=`Loop`,e[e.None=2]=`None`})($r||={});var ei;(function(e){e[e.None=0]=`None`,e[e.Hold=1]=`Hold`,e[e.Loop=2]=`Loop`,e[e.PingPong=3]=`PingPong`,e[e.Continue=4]=`Continue`})(ei||={});var ti=class e extends R{static createTrackFunctions={};static registerCreateTrack(e,t){this.createTrackFunctions[e]=t}playableAsset;playOnAwake;extrapolationMode=$r.Loop;get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(e){typeof e==`number`&&!Number.isNaN(e)?this._time=e:(Qr||Ue())&&console.error(`INVALID TIMELINE.TIME VALUE`,e,this.name)}get duration(){return this._duration}set duration(e){this._duration=e}get weight(){return this._weight}set weight(e){this._weight=e}get speed(){return this._speed}set speed(e){this._speed=e}waitForAudio=!0;_visibilityChangeEvt;_clonedPlayableAsset=!1;_speed=1;awake(){Qr&&console.log(`[Timeline] Awake '${this.name}'`,this),this.rebuildGraph(),!this.isValid()&&(Qr||w())&&(Qr?console.warn(`PlayableDirector is not valid`,`Asset?`,this.playableAsset,`Tracks:`,this.playableAsset?.tracks,`IsArray?`,Array.isArray(this.playableAsset?.tracks),this):this.playableAsset?.tracks?.length?console.warn(`PlayableDirector is not valid`):console.warn(`PlayableDirector has no tracks`))}onEnable(){Qr&&console.log(`[Timeline] OnEnable`,this.name,this.playOnAwake);for(let e of this._audioTracks)e.onEnable?.();for(let e of this._customTracks)e.onEnable?.();for(let e of this._animationTracks)e.onEnable?.();this.playOnAwake&&this.play(),this._visibilityChangeEvt||=()=>{switch(document.visibilityState){case`hidden`:this.setAudioTracksAllowPlaying(!1);break;case`visible`:this.setAudioTracksAllowPlaying(!0);break}},window.addEventListener(`visibilitychange`,this._visibilityChangeEvt)}onDisable(){Qr&&console.log(`[Timeline] OnDisable`,this.name),this.stop();for(let e of this._audioTracks)e.onDisable?.();for(let e of this._customTracks)e.onDisable?.();for(let e of this._animationTracks)e.onDisable?.();this._visibilityChangeEvt&&window.removeEventListener(`visibilitychange`,this._visibilityChangeEvt)}onDestroy(){for(let e of this._allTracks)for(let t of e)t.onDestroy?.()}rebuildGraph(){this.isValid()&&(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}async play(){if(!this.isValid())return;let e=this._isPaused==1;if(this._isPaused=!1,!this._isPlaying){if(this._isPlaying=!0,e&&this.invokePauseChangedMethodsOnTracks(),this.waitForAudio){let e=[];for(let t of this._audioTracks){let n=t.loadAudio(this._time,1,0);n&&e.push(n)}if(e.length>0&&(await Promise.all(e),!this._isPlaying))return;for(;this._audioTracks.length>0&&this._isPlaying&&!Kn.userInteractionRegistered&&this.waitForAudio;)await zt(200)}this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate(),an.LateUpdate)}}pause(){this.isValid()&&(this._isPlaying=!1,!this._isPaused&&(this._isPaused=!0,this.internalEvaluate(),this.invokePauseChangedMethodsOnTracks(),this.invokeStateChangedMethodsOnTracks()))}stop(){this._isStopping=!0;for(let e of this._audioTracks)e.stop();let e=this._isPaused==1,t=this._isPlaying;this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.internalEvaluate(),e&&this.invokePauseChangedMethodsOnTracks()),this._isPlaying=!1,this._isPaused=!1,e&&!t&&this.invokePauseChangedMethodsOnTracks(),t&&this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine&&this.stopCoroutine(this._internalUpdateRoutine),this._internalUpdateRoutine=null,this._isStopping=!1}evaluate(){this.internalEvaluate(!0)}isValid(){return this.playableAsset&&this.playableAsset.tracks&&Array.isArray(this.playableAsset.tracks)}*forEachTrack(){for(let e of this._allTracks)for(let t of e)yield t}get animationTracks(){return this._animationTracks}get audioTracks(){return this._audioTracks}get signalTracks(){return this._signalTracks}get markerTracks(){return this._markerTracks}*foreachMarker(e=null){for(let t of this._markerTracks)for(let n of t.foreachMarker(e))yield n}_guidsMap;resolveGuids(e){this._guidsMap=e}_isPlaying=!1;_internalUpdateRoutine;_isPaused=!1;_isStopping=!1;_time=0;_duration=0;_weight=1;_animationTracks=[];_audioTracks=[];_signalTracks=[];_markerTracks=[];_controlTracks=[];_customTracks=[];_tracksArray=[];get _allTracks(){return this._tracksArray.length=0,this._tracksArray.push(this._animationTracks),this._tracksArray.push(this._audioTracks),this._tracksArray.push(this._signalTracks),this._tracksArray.push(this._markerTracks),this._tracksArray.push(this._controlTracks),this._tracksArray.push(this._customTracks),this._tracksArray}invokePauseChangedMethodsOnTracks(){for(let e of this.forEachTrack())e.onPauseChanged?.call(e)}invokeStateChangedMethodsOnTracks(){for(let e of this.forEachTrack())e.onStateChanged?.call(e,this._isPlaying)}*internalUpdate(){for(;this._isPlaying&&this.activeAndEnabled;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime*this.speed,this.internalEvaluate()),yield}internalEvaluate(e=!1){if(!this.isValid())return;let t=this._time;switch(this.extrapolationMode){case $r.Hold:this._speed>0?t=Math.min(t,this._duration):this._speed<0&&(t=Math.max(t,0)),this._time=t;break;case $r.Loop:t%=this._duration,this._time=t;break;case $r.None:if(t>this._duration){this.stop();return}break}let n=this._time;for(let t of this.playableAsset.tracks)if(!t.muted)switch(t.type){case zr.Activation:if(!e&&!this._isPlaying)continue;for(let e=0;e=0;r--){let i=n.outputs[r];if(typeof i==`string`){this._guidsMap&&this._guidsMap[i]&&(i=this._guidsMap[i]);let e=F.findByGuid(i,t);typeof e!=`object`||!e?(n.outputs.splice(r,1),console.warn(`Failed to resolve binding`,i,n.name,n.type)):(Qr&&console.log(`Resolved binding`,i,`to`,e),n.outputs[r]=e)}else if(i===null){if(n.outputs.splice(r,1),e.createTrackFunctions[n.type])continue;n.type!==zr.Audio&&n.type!==zr.Control&&n.type!==zr.Marker&&n.type!==zr.Signal&&console.warn(`Missing binding`,i,n.name,n.type,this.name,this.playableAsset.name)}}if(n.type===zr.Control&&n.clips)for(let e=0;ethis._duration&&(this._duration=t.end);if(e.markers)for(let t of e.markers)t.time>this._duration&&(this._duration=t.time+.001)}}}setupAndCreateTrackHandlers(){if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let t=F.findObjectOfType(rr,this.context);for(let n of this.playableAsset.tracks){let r=n.type,i=e.createTrackFunctions[r];if(i!=null){let e=i(this,n);if(typeof e.evaluate==`function`){e.director=this,e.track=n,this._customTracks.push(e);continue}}if(n.type===zr.Animation){if(!n.clips||n.clips.length<=0){Qr&&console.warn(`Animation track has no clips`,n);continue}for(let e=n.outputs.length-1;e>=0;e--){let t=n.outputs[e];if(t instanceof y){let e=F.getOrAddComponent(t,it);e&&(t=e)}let r=t?.gameObject?.animations;if(r){let e=new Gr;e.trackOffset=n.trackOffset,e.director=this,e.track=n;for(let i=0;ie.name===s)),Qr&&console.log(o,s,`→`,c),!c){console.warn(`Could not find animationClip for model`,a,n.name,this.name,this.playableAsset?.name,r,t);continue}t instanceof it&&t.runtimeAnimatorController&&(t.__internalDidAwakeAndStart||t.initializeRuntimeAnimatorController(),t.runtimeAnimatorController.mixer||t.runtimeAnimatorController.bind(t),e.mixer=t.runtimeAnimatorController.mixer),e.mixer||(e.mixer=new oe(t.gameObject),this.context.animations.registerAnimationMixer(e.mixer)),e.clips.push(c),e.mixer.uncacheAction(c),e.createHooks(a.asset,c);let l=e.mixer.clipAction(c);e.actions.push(l),e.models.push(a)}this._animationTracks.push(e)}}}else if(n.type===zr.Audio){if(!n.clips||n.clips.length<=0)continue;let e=new qr;e.director=this,e.track=n,e.audioSource=n.outputs.find(e=>e instanceof Kn),this._audioTracks.push(e),t||=this.context.mainCameraComponent?.gameObject.addComponent(rr),e.listener=t.listener;for(let t=0;t0){let t=F.getComponent(this.gameObject,Rr);t&&(e.receivers.push(t),this._signalTracks.push(e))}t!==null&&t.models.length>0&&this._markerTracks.push(t)}}else if(n.type===zr.Signal){let e=new Yr;if(e.director=this,e.track=n,n.markers)for(let t of n.markers)e.models.push(t),e.didTrigger.push(!1);for(let t of n.outputs)e.receivers.push(t);this._signalTracks.push(e)}else if(n.type===zr.Control){let e=new Xr;if(e.director=this,e.track=n,n.clips)for(let t of n.clips)e.models.push(t);e.resolveSourceObjects(this.context),this._controlTracks.push(e)}}}setAudioTracksAllowPlaying(e){for(let t of this._audioTracks)t.onAllowAudioChanged(e)}animationCallbackReceivers=[];registerAnimationCallback(e){this.animationCallbackReceivers.push(e)}unregisterAnimationCallback(e){let t=this.animationCallbackReceivers.indexOf(e);t!==-1&&this.animationCallbackReceivers.splice(t,1)}};Zr([A()],ti.prototype,`playOnAwake`,void 0),Zr([A()],ti.prototype,`extrapolationMode`,void 0);var ni={topLight:{intensity:500,position:[.418,16.199,.3]},room:{position:[-.757,13.219,.717],scale:[31.713,28.305,28.591]},boxes:[{position:[-10.906,2.009,1.846],rotation:-.195,scale:[2.328,7.905,4.651]},{position:[-5.607,-.754,-.758],rotation:.994,scale:[1.97,1.534,3.955]},{position:[6.167,.857,7.803],rotation:.561,scale:[3.927,6.285,3.687]},{position:[-2.017,.018,6.124],rotation:.333,scale:[2.002,4.566,2.064]},{position:[2.291,-.756,-2.621],rotation:-.286,scale:[1.546,1.552,1.496]},{position:[-2.193,-.369,-5.547],rotation:.516,scale:[3.875,3.487,2.986]}],lights:[{intensity:50,position:[-16.116,14.37,8.208],scale:[.1,2.428,2.739]},{intensity:50,position:[-16.109,18.021,-8.207],scale:[.1,2.425,2.751]},{intensity:17,position:[14.904,12.198,-1.832],scale:[.15,4.265,6.331]},{intensity:43,position:[-.462,8.89,14.52],scale:[4.38,5.441,.088]},{intensity:20,position:[3.235,11.486,-12.541],scale:[2.5,2,.1]},{intensity:100,position:[0,20,0],scale:[1,.1,1]}]},ri={topLight:{intensity:400,position:[.5,14,.5]},room:{position:[0,13.2,0],scale:[31.5,28.5,31.5]},boxes:[{position:[-10.906,-1,1.846],rotation:-.195,scale:[2.328,7.905,4.651]},{position:[-5.607,-.754,-.758],rotation:.994,scale:[1.97,1.534,3.955]},{position:[6.167,-.16,7.803],rotation:.561,scale:[3.927,6.285,3.687]},{position:[-2.017,.018,6.124],rotation:.333,scale:[2.002,4.566,2.064]},{position:[2.291,-.756,-2.621],rotation:-.286,scale:[1.546,1.552,1.496]},{position:[-2.193,-.369,-5.547],rotation:.516,scale:[3.875,3.487,2.986]}],lights:[{intensity:80,position:[-14,10,8],scale:[.1,2.5,2.5]},{intensity:80,position:[-14,14,-4],scale:[.1,2.5,2.5]},{intensity:23,position:[14,12,0],scale:[.1,5,5]},{intensity:16,position:[0,9,14],scale:[5,5,.1]},{intensity:80,position:[7,8,-14],scale:[2.5,2.5,.1]},{intensity:80,position:[-7,16,-14],scale:[2.5,2.5,.1]},{intensity:1,position:[0,20,0],scale:[.1,.1,.1]}]},ii=class extends p{constructor(e){super(),this.position.y=-3.5;let t=new Ee;t.deleteAttribute(`uv`);let n=new fe({metalness:0,side:1}),r=new fe({metalness:0}),i=e==`legacy`?ni:ri,a=new De(16777215,i.topLight.intensity,28,2);a.position.set(...i.topLight.position),this.add(a);let o=new v(t,n);o.position.set(...i.room.position),o.scale.set(...i.room.scale),this.add(o);for(let e of i.boxes){let n=new v(t,r);n.position.set(...e.position),n.rotation.set(0,e.rotation,0),n.scale.set(...e.scale),this.add(n)}for(let e of i.lights){let n=new v(t,this.createAreaLightMaterial(e.intensity));n.position.set(...e.position),n.scale.set(...e.scale),this.add(n)}}createAreaLightMaterial(e){let t=new m;return t.color.setScalar(e),t}};async function ai(t){let{NeedleEngineWebComponent:n}=await e(async()=>{let{NeedleEngineWebComponent:e}=await import(`./needle-engine.CE4b2dOg.js`);return{NeedleEngineWebComponent:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]),import.meta.url);n.observedAttributes.includes(t)||n.observedAttributes.push(t)}var H=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},U=N(`debugsceneswitcher`),oi=N(`sceneswitcher:clearscene`),si=`scene`;function ci(){ai(si)}var li=Promise.resolve(!1),W=class extends R{autoLoadFirstScene=!0;scenes=[];loadingScene;queryParameterName=`scene`;useSceneName=!0;clamp=!0;useHistory=!0;useKeyboard=!0;useSwipe=!0;useSceneLighting=!0;useSceneBackground=!0;preloadNext=1;preloadPrevious=1;preloadConcurrent=2;createMenuButtons=!1;get currentIndex(){return this._currentIndex}get currentLoadingProgress(){return this._currentLoadingProgress}get currentlyLoadingScene(){return this._currentlyLoadingScene}get currentlyLoadedScene(){return this._currentScene}sceneLoadingStart=new k;sceneLoadingProgress=new k;sceneLoaded=new k;_currentIndex=-1;_currentScene=void 0;_currentSceneAsset=void 0;_engineElementOverserver=void 0;_preloadScheduler;_menuButtons;__lastSwitchScene;__lastSwitchScenePromise;awake(){this._currentScene=void 0,this._lastLoadingScene=void 0,this.__lastSwitchScenePromise=void 0,this.scenes===void 0&&(this.scenes=[]);for(let e of this.scenes)e&&!e.hasUrl&&e.asset instanceof y?F.remove(e.asset):e instanceof y&&F.remove(e);U&&console.log(`SceneSwitcher`,this)}async onEnable(){if(globalThis.addEventListener(`popstate`,this.onPopState),this.context.input.addEventListener(Ie.KeyDown,this.onInputKeyDown),this.context.input.addEventListener(Ie.PointerMove,this.onInputPointerMove),this.context.input.addEventListener(Ie.PointerUp,this.onInputPointerUp),this._engineElementOverserver||=new MutationObserver(e=>{for(let t of e)if(t.type===`attributes`&&t.attributeName===si){let e=this.context.domElement.getAttribute(si);e!==null&&this.trySelectSceneFromValue(e)}}),this._engineElementOverserver.observe(this.context.domElement,{attributes:!0}),this._preloadScheduler||=new di(this),this._preloadScheduler.maxLoadAhead=this.preloadNext,this._preloadScheduler.maxLoadBehind=this.preloadPrevious,this._preloadScheduler.maxConcurrent=this.preloadConcurrent,this._preloadScheduler.begin(2e3),this.autoLoadFirstScene&&this._currentIndex===-1&&!await this.tryLoadFromQueryParam()){let e=this.context.domElement.getAttribute(si);try{(e===null||!await this.trySelectSceneFromValue(e))&&this._currentIndex===-1&&this.select(0)}finally{}}this.createMenuButtons&&(this._menuButtons??=[],this._menuButtons.push(this.context.menu.appendChild({label:`Previous`,icon:`arrow_back_ios`,onClick:()=>this.selectPrev(),priority:-1005,class:`row2`})),this._menuButtons.push(this.context.menu.appendChild({label:`Next`,icon:`arrow_forward_ios`,iconSide:`right`,onClick:()=>this.selectNext(),priority:-1e3,class:`row2`})))}onDisable(){if(globalThis.removeEventListener(`popstate`,this.onPopState),this.context.input.removeEventListener(Ie.KeyDown,this.onInputKeyDown),this.context.input.removeEventListener(Ie.PointerMove,this.onInputPointerMove),this.context.input.removeEventListener(Ie.PointerUp,this.onInputPointerUp),this._preloadScheduler?.stop(),this._menuButtons){for(let e of this._menuButtons)e.remove();this._menuButtons=void 0}}onPopState=async e=>{if(!this.useHistory)return;let t=this.useHistory;try{this.useHistory=!1;let t=!1;if(this.queryParameterName&&(t=await this.tryLoadFromQueryParam()),!t){let t=e?.state;if(t&&t.startsWith(this.guid)){let e=t.substr(this.guid.length+2);U&&console.log(`PopState`,e),await this.trySelectSceneFromValue(e)}}}finally{this.useHistory=t}};normalizedSwipeThresholdX=.1;_didSwipe=!1;onInputPointerMove=e=>{if(this.useSwipe&&!this._didSwipe&&e.button===0&&e.pointerType===`touch`&&this.context.input.getPointerPressedCount()===1){let t=this.context.input.getPointerPositionDelta(e.button);if(t){let e=t.x/this.context.domWidth;e>=this.normalizedSwipeThresholdX?(this._didSwipe=!0,this.selectPrev()):e<=-this.normalizedSwipeThresholdX&&(this._didSwipe=!0,this.selectNext())}}};onInputPointerUp=e=>{e.button===0&&(this._didSwipe=!1)};onInputKeyDown=e=>{if(!this.useKeyboard||!this.scenes)return;let t=e.key.toLowerCase();if(!t)return;let n=parseInt(t)-1;if(n>=0){this.trySelectSceneFromValue(n);return}switch(t){case`arrowright`:case`d`:this.selectNext();break;case`arrowleft`:case`a`:this.selectPrev();break}};addScene(e){if(typeof e==`string`){let t=this.context.addressables.findAssetReference(e);return t||(t=new Me(e),this.context.addressables.registerAssetReference(t)),this.scenes.push(t),t}return this.scenes.push(e),e}selectNext(){return this.select(this._currentIndex+1)}selectPrev(){return this.select(this._currentIndex-1)}select(e){if(U&&console.log(`[SceneSwitcher] select`,e),typeof e==`object`&&console.warn(`[SceneSwitcher] Switching to "`+e+`" might not work. Please either use an index or a AssetReference (not a scene reference)`),typeof e==`string`){let t=this.scenes?.find(t=>t.url===e);if(!t){let t=Me.getOrCreate(this.sourceId??``,e,this.context);return this.switchScene(t)}if(t)e=this.scenes?.indexOf(t);else return li}if(!this.scenes?.length)return li;if(e<0){if(this.clamp)return li;e=this.scenes.length-1}else if(e>=this.scenes.length){if(this.clamp)return li;e=0}let t=this.scenes[e];return this.switchScene(t)}unload(){return this.__lastSwitchScene=void 0,this.__lastSwitchScenePromise=void 0,this.__unloadCurrentScene()}async reload(){if(this.__lastSwitchScene){let e=this.__lastSwitchScene;return this.__lastSwitchScene=void 0,this.switchScene(e)}return!1}async switchScene(e){if(!(e instanceof Me)){let t=typeof e;if(t===`string`||t===`number`)return this.select(e);if(e&&e instanceof y){let t=this.scenes?.indexOf(e);e=new Me(e.name,void 0,e),t>=0&&(this.scenes[t]=e)}else return console.warn(`[SceneSwitcher] Can't switch to scene of type ${t}`),!1}return e.url===this.sourceId?(console.warn(`[SceneSwitcher] Can't load own scene - prevent recursive loading`,this.sourceId),!1):this.__lastSwitchScene===e&&this.__lastSwitchScenePromise?this.__lastSwitchScenePromise:(this.__lastSwitchScene=e,this.__lastSwitchScenePromise=this.__internalSwitchScene(e),await this.__lastSwitchScenePromise)}async __unloadCurrentScene(){let e=this._currentScene;if(this._currentScene=void 0,e){U&&console.log(`[SceneSwitcher] UNLOAD`,e.url,`HasURL?: `+e.hasUrl);let t=this.tryGetSceneEventListener(e.asset);if(t?.sceneClosing){let e=t.sceneClosing();e instanceof Promise&&await e}e.hasUrl?(e.unload(),this._currentSceneAsset&&L(this._currentSceneAsset,!0,!1)):F.remove(this._currentSceneAsset)}}_currentlyLoadingScene;async __internalSwitchScene(e){await this.__unloadCurrentScene();let t=this._currentIndex=this.scenes?.indexOf(e)??-1;try{U&&console.debug(`${Date.now()} [SceneSwitcher] Loading scene start: ${e.url} (index: ${t})`),this._currentlyLoadingScene=e,this._currentLoadingProgress=new ProgressEvent(`progress`,{loaded:0,total:1});let n=new CustomEvent(`loadscene-start`,{detail:{scene:e,switcher:this,index:t}});this.dispatchEvent(n),this.sceneLoadingStart?.invoke(n.detail),await this.onStartLoading(),await e.loadAssetAsync((t,n)=>{if(U){let t=n.loaded/n.total,r=`[`+`=`.repeat(Math.floor(t*20))+`-`.repeat(20-Math.floor(t*20))+`]`;console.debug(`${Date.now()} [SceneSwitcher] Loading scene progress: ${(t*100).toFixed(1)} % ${r}`,e.url)}this._currentLoadingProgress=n,this.dispatchEvent(n),this.sceneLoadingProgress?.invoke(n)}).catch(console.error),await this.onEndLoading();let r=new CustomEvent(`loadscene-finished`,{detail:{scene:e,switcher:this,index:t}});if(this.dispatchEvent(r),this._currentLoadingProgress=void 0,this._currentlyLoadingScene=void 0,r.defaultPrevented)return U&&console.warn(`[SceneSwitcher] Adding loaded scene prevented:`,e,r),!1;if(!e.asset)return U&&console.warn(`[SceneSwitcher] Failed loading scene:`,e),!1;if(this._currentIndex===t){if(U&&console.log(`[SceneSwitcher] ADD`,e.url),this._currentScene=e,oi){let e=this.context.mainCameraComponent?.gameObject||this.context.mainCamera;e?.removeFromParent();let t=this.gameObject.removeFromParent();L(this.context.scene,!0,!0),this.context.scene=new p,this.context.scene.add(t),e&&this.context.scene.add(e)}if(e.asset.parent?this._currentSceneAsset=tt(e.asset,{parent:this.gameObject}):(this._currentSceneAsset=e.asset,F.add(e.asset,this.gameObject)),this.useSceneLighting&&this.context.sceneLighting.enable(e),this.useSceneBackground){let t=this.context.lightmaps.tryGetSkybox(e.url);t?(t.mapping!==306&&(t.mapping=303),this.context.scene.background=t):U&&console.warn(`[SceneSwitcher] Can't find skybox for scene `+e.url)}if(this.useHistory&&t>=0){let n=t.toString();if(this.useSceneName&&(e instanceof y?n=e.name:e.url&&(n=ui(e.url))),this.queryParameterName?.length)Ve(this.queryParameterName,n,this.useHistory);else{let e=history.state,n=this.guid+`::`+t;e!==n&&history.pushState(n,`unused`,location.href)}}let n=this.tryGetSceneEventListener(e.asset);if(n?.sceneOpened){let e=n.sceneOpened(this);e instanceof Promise&&await e}U&&console.debug(`${Date.now()} [SceneSwitcher] Loading scene finished: ${e.url} (index: ${t})`);let r=new CustomEvent(`scene-opened`,{detail:{scene:e,switcher:this,index:t}});return this.dispatchEvent(r),this.sceneLoaded?.invoke(this),!0}}catch(e){console.error(e)}return!1}preload(e){if(e>=0&&e=0&&t=0&&ee!=null),await this._loadingScenePromise,this._isCurrentlyLoading&&this.loadingScene?.asset)){U&&console.log(`Add loading scene`,this.loadingScene.url,this.loadingScene.asset);let e=this.loadingScene.asset;F.add(e,this.gameObject);let t=this.tryGetSceneEventListener(e);if(t?.sceneOpened){let e=t.sceneOpened(this);e instanceof Promise&&await e}}if(this._isCurrentlyLoading){let e=this.tryGetSceneEventListener(this.gameObject);if(e&&e.sceneOpened){let t=e.sceneOpened(this);t instanceof Promise&&await t}}}async onEndLoading(){if(this._isCurrentlyLoading=!1,this.loadingScene?.asset){U&&console.log(`Remove loading scene`,this.loadingScene.url);let e=this.loadingScene.asset,t=this.tryGetSceneEventListener(e);if(typeof t?.sceneClosing==`function`){let e=t.sceneClosing();e instanceof Promise&&await e}F.remove(e)}if(!this._isCurrentlyLoading){let e=this.tryGetSceneEventListener(this.gameObject);if(e&&e.sceneClosing){let t=e.sceneClosing();t instanceof Promise&&await t}}}tryGetSceneEventListener(e,t=0){if(!e)return null;let n=F.foreachComponent(e,e=>{let t=e;if(t.sceneClosing||t.sceneOpened)return t});if(t===0&&!n&&e.children.length)for(let n of e.children){let e=this.tryGetSceneEventListener(n,t+1);if(e)return e}return n||null}};H([A()],W.prototype,`autoLoadFirstScene`,void 0),H([A(Me)],W.prototype,`scenes`,void 0),H([A(Me)],W.prototype,`loadingScene`,void 0),H([A()],W.prototype,`queryParameterName`,void 0),H([A()],W.prototype,`useSceneName`,void 0),H([A()],W.prototype,`clamp`,void 0),H([A()],W.prototype,`useHistory`,void 0),H([A()],W.prototype,`useKeyboard`,void 0),H([A()],W.prototype,`useSwipe`,void 0),H([A()],W.prototype,`useSceneLighting`,void 0),H([A()],W.prototype,`useSceneBackground`,void 0),H([A()],W.prototype,`preloadNext`,void 0),H([A()],W.prototype,`preloadPrevious`,void 0),H([A()],W.prototype,`preloadConcurrent`,void 0),H([A()],W.prototype,`createMenuButtons`,void 0),H([A(k)],W.prototype,`sceneLoadingStart`,void 0),H([A(k)],W.prototype,`sceneLoadingProgress`,void 0),H([A(k)],W.prototype,`sceneLoaded`,void 0);function ui(e){let t=e.split(`/`).pop()?.split(`.`).shift();return t?.length?t:e}var di=class{maxLoadAhead;maxLoadBehind;maxConcurrent;_isRunning=!1;_switcher;_loadTasks=[];_maxConcurrentLoads=1;constructor(e,t=1,n=1,r=2){this._switcher=e,this.maxLoadAhead=t,this.maxLoadBehind=n,this.maxConcurrent=r}begin(e){if(this._isRunning)return;U&&console.log(`[SceneSwitcher] Preload scheduled`,{delay:e}),this._isRunning=!0;let t=-10,n,r,i=this._switcher.scenes,a=Date.now()+e,o=setInterval(()=>{if(this.allLoaded()&&(U&&console.log(`[SceneSwitcher] All scenes (pre-)loaded`),this.stop()),!this._isRunning){clearInterval(o);return}if(Date.now()s)return;let c=e?t+n:t-n;if(!(c<0)&&!(c<0||c>=i.length)&&!this._loadTasks.some(e=>e.index===c)){let n=i[c];U&&console.log(`[SceneSwitcher] Schedule preload scene`,{roomIndex:c,searchForward:e,lastRoom:t,currentIndex:this._switcher.currentIndex,tasks:this._loadTasks.length},n?.url),new fi(c,n,this._loadTasks)}},200)}stop(){this._isRunning=!1}canLoadNewScene(){return this._loadTasks.length=0&&this.tasks.splice(e,1)}},pi=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},G=N(`debugskybox`);function mi(){ai(`background-image`),ai(`environment-image`)}var hi={studio:{url:`https://cdn.needle.tools/static/skybox/modelviewer-Neutral.pmrem4x4.ktx2?pmrem`,url_low:`https://cdn.needle.tools/static/skybox/modelviewer-Neutral-small.pmrem4x4.ktx2?pmrem`},"blurred-skybox":{url:`https://cdn.needle.tools/static/skybox/blurred-skybox.pmrem4x4.ktx2?pmrem`,url_low:`https://cdn.needle.tools/static/skybox/blurred-skybox-small.pmrem4x4.ktx2?pmrem`},"quicklook-ar":{url:`https://cdn.needle.tools/static/skybox/QuickLook-ARMode.pmrem4x4.ktx2?pmrem`,url_low:`https://cdn.needle.tools/static/skybox/QuickLook-ARMode-small.pmrem4x4.ktx2?pmrem`},quicklook:{url:`https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode.pmrem4x4.ktx2?pmrem`,url_low:`https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode-small.pmrem4x4.ktx2?pmrem`}};function gi(e,t,n,r,i){if(t===`transparent`||t?.startsWith(`rgb`)||t?.startsWith(`#`))return console.warn(`Needle Engine: Invalid ${i} value (${t}). Did you mean to set background-color instead?`),null;let a=new vi;a.sourceId=Je(t),a.allowDrop=!1,a.allowNetworking=!1,a.background=n,a.environment=r,F.addComponent(e.scene,a);let o=t=>{if(G&&console.log(i,`CHANGED TO`,t),t){if(typeof t!=`string`){console.warn(`Invalid attribute value for `+i);return}a.setSkybox(t)}else if(a.sourceId&&(r&&(e.sceneLighting.internalEnableReflection(a.sourceId)||(e.scene.environment=null)),n)){let t=e.lightmaps.tryGetSkybox(a.sourceId);e.scene.background=t}};return Dt(e.domElement,i,o),a.addEventListener(`destroy`,()=>{G&&console.log(`Destroyed attribute remote skybox`,i),Ae(e.domElement,i,o)}),a.setSkybox(t)}var _i=[];lt.registerCallback(st.ContextCreationStart,e=>{let t=e.context,n=t.domElement.getAttribute(`background-image`),r=t.domElement.getAttribute(`environment-image`);if(n){G&&console.log(`Creating RemoteSkybox to load background `+n);let e=gi(t,n,!0,!1,`background-image`);e&&_i.push(e)}if(r){G&&console.log(`Creating RemoteSkybox to load environment `+r);let e=gi(t,r,!1,!0,`environment-image`);e&&_i.push(e)}}),lt.registerCallback(st.ContextCreationStart,()=>Promise.all(_i).finally(()=>{_i.length=0}));var vi=class extends R{url=`studio`;allowDrop=!0;background=!0;environment=!0;allowNetworking=!0;_prevUrl;_prevLoadedEnvironment;_prevEnvironment=null;_prevBackground=null;onEnable(){this.setSkybox(this.url),this.registerDropEvents()}onDisable(){this.context.scene.environment===this._prevLoadedEnvironment&&(this.context.scene.environment=this._prevEnvironment,Ne.backgroundShouldBeTransparent(this.context)||(this.context.scene.background=this._prevBackground),this._prevLoadedEnvironment=void 0),this.unregisterDropEvents(),this.context.mainCameraComponent?.applyClearFlags()}urlChangedSyncField(){this.allowNetworking&&this.url&&(this.isRemoteTexture(this.url)?this.setSkybox(this.url):G&&console.warn(`RemoteSkybox: Not setting skybox: ${this.url} is not a remote texture. If you want to set a local texture, set allowNetworking to false.`))}async setSkybox(e,t){if(!this.activeAndEnabled||(e=yi(e,this.environment,this.background),!e))return!1;if(t??=e,this.isValidTextureType(t)||console.warn(`Potentially invalid skybox URL: "`+t+`" on `+(this.name||this.gameObject?.name||`context`)),G&&console.log(`Set RemoteSkybox url: `+e),this._prevUrl===e&&this._prevLoadedEnvironment)return this.apply(),!0;this._prevLoadedEnvironment?.dispose(),this._prevLoadedEnvironment=void 0,this._prevUrl=e;let n=await pr(e,this.context.renderer);return n?!this.enabled||this.destroyed?(G&&console.warn(`RemoteSkybox: Component is disabled or destroyed`),!1):this._prevUrl===e?(this.url=e,this._prevLoadedEnvironment=n,this.apply(),!0):(G&&console.warn(`RemoteSkybox: URL changed while loading texture, aborting setSkybox`),!1):(G&&console.warn(`RemoteSkybox: Failed to load texture from url`,e),!1)}apply(){let e=this._prevLoadedEnvironment;if(e&&(e instanceof ee||e instanceof d||e.mapping==306||(e.mapping=304,e.needsUpdate=!0),!this.destroyed)){if(!this.context){console.warn(`RemoteSkybox: Context is not available - can not apply skybox.`);return}this.context.scene.background!==e&&(this._prevBackground=this.context.scene.background),this.context.scene.environment!==e&&(this._prevEnvironment=this.context.scene.environment),G&&console.log(`Set RemoteSkybox (`+(this.environment&&this.background?`environment and background`:this.environment?`environment`:this.background?`background`:`none`)+`)`,this.url,!Ne.backgroundShouldBeTransparent(this.context)),this.environment&&(this.context.scene.environment=e),this.background&&!Ne.backgroundShouldBeTransparent(this.context)&&(this.context.scene.background=e),this.context.mainCameraComponent?.backgroundBlurriness!==void 0&&(this.context.scene.backgroundBlurriness=this.context.mainCameraComponent.backgroundBlurriness)}}validProtocols=[`file:`,`blob:`,`data:`];validTextureTypes=[`.ktx2`,`.hdr`,`.exr`,`.jpg`,`.jpeg`,`.png`];isRemoteTexture(e){return e.startsWith(`http://`)||e.startsWith(`https://`)}isValidTextureType(e){for(let t of this.validTextureTypes)if(e.includes(t))return!0;for(let t of this.validProtocols)if(e.startsWith(t))return!0;return!1}registerDropEvents(){this.unregisterDropEvents(),this.context.domElement.addEventListener(`dragover`,this.onDragOverEvent),this.context.domElement.addEventListener(`drop`,this.onDrop)}unregisterDropEvents(){this.context.domElement.removeEventListener(`dragover`,this.onDragOverEvent),this.context.domElement.removeEventListener(`drop`,this.onDrop)}onDragOverEvent=e=>{if(this.allowDrop&&e.dataTransfer)for(let t of e.dataTransfer.types)(t===`text/uri-list`||t===`Files`)&&e.preventDefault()};onDrop=e=>{if(this.allowDrop&&e.dataTransfer){for(let t of e.dataTransfer.types)if(G&&console.log(t),t===`text/uri-list`){let n=e.dataTransfer.getData(t);G&&console.log(t,n);let r=new RegExp(/polyhaven.com\/asset_img\/.+?\/(?.+)\.png/).exec(n)?.groups?.name;if(r||=new RegExp(/polyhaven\.com\/a\/(?.+)/).exec(n)?.groups?.name,G&&console.log(r),r){let t=`https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/`+r+`_1k.exr`;console.log(`[Remote Skybox] Setting skybox from url: ${t}`),e.preventDefault(),this.setSkybox(t);break}else if(this.isValidTextureType(n)){console.log(`[Remote Skybox] Setting skybox from url: `+n),e.preventDefault(),this.setSkybox(n);break}else{console.warn(`[RemoteSkybox] Unknown url ${n}. If you want to load a skybox from a url, make sure it is a valid image url. Url must end with${this.validTextureTypes.join(`, `)}.`);let t=new CustomEvent(`dropped-unknown-url`,{detail:{sender:this,event:e,url:n,apply:t=>{e.preventDefault(),this.setSkybox(t)}}});this.dispatchEvent(t)}}else if(t==`Files`){let n=e.dataTransfer.files.item(0);if(G&&console.log(t,n),!n)continue;if(!this.isValidTextureType(n.name)){console.warn(`[RemoteSkybox]: File \"${n.name}\" is not supported. Supported files are ${this.validTextureTypes.join(`, `)}`);return}e.preventDefault(),this.setSkybox(n.name);break}}}};pi([Wn(vi.prototype.urlChangedSyncField),A(URL)],vi.prototype,`url`,void 0),pi([A()],vi.prototype,`allowDrop`,void 0),pi([A()],vi.prototype,`background`,void 0),pi([A()],vi.prototype,`environment`,void 0),pi([A()],vi.prototype,`allowNetworking`,void 0);function yi(e,t,n){if(e==null)return null;let r=t&&!n,i=hi[e.toLowerCase()];return i?r?i.url_low:i.url:(typeof e==`string`&&e?.length&&(w()||G)&&(e.includes(`/`)||e.includes(`.`)||console.warn(`RemoteSkybox: Unknown magic skybox name "${e}". Valid names are: ${Object.keys(hi).map(e=>`"${e}"`).join(`, `)}`)),e)}var bi=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},xi=class extends R{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new n}update(){if(!this.from||!this.to)return;let e=M(this.from).clone(),t=M(this.to).clone(),n=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),Oe(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(M(this.to).clone()),this.gameObject.scale.set(this.width,this.width,n)}};bi([A(F)],xi.prototype,`from`,void 0),bi([A(F)],xi.prototype,`to`,void 0);var Si=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},Ci=class extends R{length=1;depthTest=!0;isGizmo=!1;_axes=null;onEnable(){if(this.isGizmo&&!Lt)return;this._axes||=new se(this.length),this._axes.layers.disableAll(),this._axes.layers.set(this.layer),this.gameObject.add(this._axes);let e=this._axes.material;e&&e.depthTest!==void 0&&(e.depthTest=this.depthTest)}onDisable(){this._axes&&this.gameObject.remove(this._axes)}};Si([A()],Ci.prototype,`length`,void 0),Si([A()],Ci.prototype,`depthTest`,void 0),Si([A()],Ci.prototype,`isGizmo`,void 0);var wi=class extends R{from;to;hint;desiredDistance=1;onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;let e=M(this.to).clone(),t=M(this.from).clone(),r=e.distanceTo(t),i=e.clone();i.sub(t);let a=t.clone();a.add(e),a.multiplyScalar(.5);let o=M(this.hint).clone();o.sub(a);let s=new n;s.crossVectors(o,i),s.crossVectors(i,s),s.normalize();let c=r*.5,l=Math.max(this.desiredDistance,c),u=Math.sqrt(l*l-c*c),d=s.clone();d.multiplyScalar(u),d.add(a),Oe(this.gameObject,d);let f=a.clone();f.sub(s),this.gameObject.lookAt(f)}},Ti=N(`gizmos`),Ei=N(`debugboxhelper`),Di=class e extends R{box=null;static testBox=new ie;_lastMatrixUpdateFrame=-1;static _position=new n;static _size=new n(.01,.01,.01);static _emptyObjectSize=new n(.01,.01,.01);isInBox(t){if(!t)return;if(this.box||=new ie,Nt([t],void 0,void 0,e.testBox),e.testBox.isEmpty()){let n=M(t,e._position);e.testBox.setFromCenterAndSize(n,e._emptyObjectSize)}this.updateBox();let n=this.box?.intersectsBox(e.testBox);return n&&Ei&&V.DrawWireBox3(e.testBox,16711680,5),n}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(t=!1){if(this.box||=new ie,t||this.context.time.frameCount!=this._lastMatrixUpdateFrame){let t=this._lastMatrixUpdateFrame<0;this._lastMatrixUpdateFrame=this.context.time.frameCount;let n=t,r=M(this.gameObject,e._position,n),i=_t(this.gameObject,e._size);this.box.setFromCenterAndSize(r,i)}return this.box}_helper=null;_color=null;awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,t=!1){if(!(!Ti&&!t)){if(this._helper){e&&this._color?.set(e),this.gameObject.add(this._helper);return}this._helper=Pt(e),this.gameObject.add(this._helper)}}},Oi=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},ki=N(`debugcharactercontroller`),Ai=class extends R{center=new n(0,0,0);radius=.5;height=2;_rigidbody=null;get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(E),this._rigidbody||=this.gameObject.addComponent(E),this.rigidbody)}_activeGroundCollisions;awake(){this._activeGroundCollisions=new Set}onEnable(){let e=this.rigidbody,t=this.gameObject.getComponent(Mn);t||=this.gameObject.addComponent(Mn),t.center.copy(this.center),t.radius=this.radius,t.height=this.height;let r=new n(0,0,1),i=new n(1,0,0),a=new n(0,1,0),o=this.gameObject.getWorldDirection(new n);o.y=0;let s=i.dot(o)<0?-1:1,c=r.angleTo(o)*s;this.gameObject.setRotationFromAxisAngle(a,c),e.lockRotationX=!0,e.lockRotationY=!0,e.lockRotationZ=!0}move(e){this.gameObject.position.add(e)}onCollisionEnter(e){(e.contacts.length==0||e.contacts.some(e=>e.normal.y>.2))&&(this._activeGroundCollisions.add(e),ki&&console.log(`Collision(${this._activeGroundCollisions.size}): ${e.contacts.map(e=>e.normal.y.toFixed(2)).join(`, `)} - ${this.isGrounded}`))}onCollisionExit(e){this._activeGroundCollisions.delete(e),ki&&console.log(`Collision(${this._activeGroundCollisions.size}) - ${this.isGrounded}`)}get isGrounded(){return this._activeGroundCollisions.size>0}_contactVelocity=new n;get contactVelocity(){this._contactVelocity.set(0,0,0);for(let e of this._activeGroundCollisions){let t=this.context.physics.engine?.getLinearVelocity(e.collider);t&&(this._contactVelocity.x+=t.x,this._contactVelocity.y+=t.y,this._contactVelocity.z+=t.z)}return this._contactVelocity}};Oi([A(n)],Ai.prototype,`center`,void 0),Oi([A()],Ai.prototype,`radius`,void 0),Oi([A()],Ai.prototype,`height`,void 0);var ji=class extends R{controller;movementSpeed=2;rotationSpeed=2;jumpForce=1;doubleJumpForce=2;animator;lookForward=!0;awake(){this._currentRotation=new x}update(){let e=this.context.input;e.isKeyPressed(`KeyW`)?this.moveInput.y+=1:e.isKeyPressed(`KeyS`)&&--this.moveInput.y,e.isKeyPressed(`KeyD`)?this.lookInput.x+=1:e.isKeyPressed(`KeyA`)&&--this.lookInput.x,this.jumpInput||=e.isKeyDown(`Space`)}move(e){this.moveInput.add(e)}look(e){this.lookInput.add(e)}jump(){this.jumpInput=!0}lookInput=new b(0,0);moveInput=new b(0,0);jumpInput=!1;onBeforeRender(){this.handleInput(this.moveInput,this.lookInput,this.jumpInput),this.lookInput.set(0,0),this.moveInput.set(0,0),this.jumpInput=!1}_currentSpeed=new n(0,0,0);_currentAngularSpeed=new n(0,0,0);_temp=new n(0,0,0);_jumpCount=0;_currentRotation;handleInput(e,t,r){if(this.controller?.isGrounded&&(this._jumpCount=0,this.doubleJumpForce>0&&this.animator?.setBool(`doubleJump`,!1)),this._currentSpeed.z+=e.y*this.movementSpeed*this.context.time.deltaTime,this.animator?.setBool(`running`,e.length()>.01),this.animator?.setBool(`jumping`,this.controller?.isGrounded===!0&&r),this._temp.copy(this._currentSpeed),this._temp.applyQuaternion(this.gameObject.quaternion),this.controller?this.controller.move(this._temp):this.gameObject.position.add(this._temp),this._currentAngularSpeed.y+=O.toRadians(-t.x*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){let e=this.context.mainCameraComponent.forward;e.y=0,e.normalize(),this._currentRotation.setFromUnitVectors(new n(0,0,1),e),this.gameObject.quaternion.slerp(this._currentRotation,this.context.time.deltaTime*10)}if(this.gameObject.rotateY(this._currentAngularSpeed.y),this._currentSpeed.multiplyScalar(1-this.context.time.deltaTime*10),this._currentAngularSpeed.y*=1-this.context.time.deltaTime*10,this.controller&&r&&this.jumpForce>0){let e=this.controller?.isGrounded;if(this.doubleJumpForce>0&&!this.controller?.isGrounded&&this._jumpCount===1&&(e=!0,this.animator?.setBool(`doubleJump`,!0)),e){this._jumpCount+=1;let e=this.controller.rigidbody,t=this._jumpCount===2?this.doubleJumpForce:this.jumpForce;e.applyImpulse(new n(0,1,0).multiplyScalar(t))}}if(this.controller){let e=this.controller?.rigidbody.getVelocity().y;if(e<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new a),this._raycastOptions.ray.origin.copy(M(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);let t=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);let n=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(t),(n.length&&n[0].distance>2||e<-10)&&this.animator?.setBool(`falling`,!0)}else this.animator?.setBool(`falling`,!1)}}_raycastOptions=new Gt};Oi([A(Ai)],ji.prototype,`controller`,void 0),Oi([A()],ji.prototype,`movementSpeed`,void 0),Oi([A()],ji.prototype,`rotationSpeed`,void 0),Oi([A()],ji.prototype,`jumpForce`,void 0),Oi([A()],ji.prototype,`doubleJumpForce`,void 0),Oi([A(it)],ji.prototype,`animator`,void 0);var Mi=N(`logstats`),Ni=class extends R{onEnable(){console.log(this),Mi&&this.startCoroutine(this.run(),an.OnAfterRender)}*run(){for(;this.enabled;){let e=this.context.renderer.info;console.log(e.memory,e.render,e.programs),yield}}},Pi=class extends R{isUsed=!0;usedBy=null},Fi=class extends R{},Ii=N(`debugdeletable`),Li=class e extends Di{static _instances=[];onEnable(){e._instances.push(this)}onDisable(){let t=e._instances.indexOf(this);t>=0&&e._instances.splice(t,1)}},Ri=class extends R{update(){for(let e of Li._instances){let t=this.gameObject;if(e.isInBox(t)===!0){let t=F.getComponentInParent(this.gameObject,Pi);if(t)Ii&&console.warn(`DeleteBox: Not deleting object with usage marker`,this.guid,t);else{if(Ii)try{if(e.box){let t=e.box,n=Di.testBox;V.DrawWireBox3(t,16711680,5),V.DrawWireBox3(n,255,5),console.log(`DeleteBox: Destroying`,this.gameObject,{deleteBoxArea:t,deletedObjectArea:n})}else console.log(`DeleteBox: Destroying`,this.gameObject)}catch{}xt(this.gameObject,this.context.connection)}}}}},zi=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},Bi;(function(e){e[e.Never=0]=`Never`,e[e.Desktop=1]=`Desktop`,e[e.Mobile=2]=`Mobile`})(Bi||={});var Vi=class extends R{visibleOn;onEnable(){this.apply()}apply(){this.test()||F.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:yt.isMobileDevice()?(this.visibleOn&Bi.Mobile)!==0:(this.visibleOn&Bi.Desktop)!==0}};zi([A()],Vi.prototype,`visibleOn`,void 0);var Hi=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},Ui=N(`debugdrag`),Wi=[],K;(function(e){e[e.XZPlane=0]=`XZPlane`,e[e.Attached=1]=`Attached`,e[e.HitNormal=2]=`HitNormal`,e[e.DynamicViewAngle=3]=`DynamicViewAngle`,e[e.SnapToSurfaces=4]=`SnapToSurfaces`,e[e.None=5]=`None`})(K||={});var Gi=class e extends R{static get HasAnySelected(){return this._active>0}static _active=0;static get CurrentlySelected(){Wi.length=0;for(let e of this._instances)e._isDragging&&Wi.push(e);return Wi}static _instances=[];dragMode=K.DynamicViewAngle;snapGridResolution=0;keepRotation=!0;xrDragMode=K.Attached;xrKeepRotation=!1;xrDistanceDragFactor=1;showGizmo=!1;get draggedObject(){return this._targetObject}setTargetObject(e){this._targetObject=e;for(let t of this._dragHandlers.values())t.setTargetObject(e);let t=`_rigidbody-was-kinematic`;this._rigidbody?.[t]===!1&&(this._rigidbody.isKinematic=!1,this._rigidbody[t]=void 0),this._rigidbody=null,e&&(this._rigidbody=F.getComponentInChildren(e,E),this._rigidbody?.isKinematic===!1&&(this._rigidbody.isKinematic=!0,this._rigidbody[t]=!1))}_rigidbody=null;_targetObject=null;_dragHelper=null;static lastHovered;_draggingRigidbodies=[];_potentialDragStartEvt=null;_dragHandlers=new Map;_totalMovement=new n;_marker=null;_isDragging=!1;_didDrag=!1;awake(){this._potentialDragStartEvt=null,this._dragHandlers=new Map,this._totalMovement=new n,this._marker=null,this._isDragging=!1,this._didDrag=!1,this._dragHelper=null,this._draggingRigidbodies=[]}start(){this.gameObject.getComponentInParent(C)||this.gameObject.addComponent(C)}onEnable(){e._instances.push(this),this.context.accessibility.updateElement(this,{role:`button`,label:`Drag `+(this.gameObject.name||`object`),hidden:!1})}onDisable(){this.context.accessibility.updateElement(this,{hidden:!0}),e._instances=e._instances.filter(e=>e!==this)}onDestroy(){this.context.accessibility.removeElement(this)}allowEdit(e=null){return this.context.connection.allowEditing}onPointerEnter(t){if(!this.allowEdit(this.gameObject)||t.mode!==`screen`||(t.event.mode===`tracked-pointer`||t.event.mode===`transient-pointer`?this.xrDragMode:this.dragMode)===K.None)return;let n=F.getComponentInParent(t.object,e);!n||n!==this||(e.lastHovered=t.object,this.context.domElement.style.cursor=`pointer`,this.context.accessibility.hover(this,`Draggable ${t.object?.name}`))}onPointerMove(e){(this._isDragging||this._potentialDragStartEvt!==null)&&e.use()}onPointerExit(t){this.allowEdit(this.gameObject)&&t.mode===`screen`&&e.lastHovered===t.object&&(this.context.domElement.style.cursor=`auto`)}onPointerDown(t){if(this.allowEdit(this.gameObject)&&!t.used&&(t.mode===`tracked-pointer`||t.mode===`transient-pointer`?this.xrDragMode:this.dragMode)!==K.None&&(e.lastHovered=t.object,t.button===0)){this._dragHandlers.size===0&&(this._didDrag=!1,this._totalMovement.set(0,0,0),this._potentialDragStartEvt=t),this._targetObject||this.setTargetObject(this.gameObject),e._active+=1;let n=new qi(this,this._targetObject);if(this._dragHandlers.set(t.event.space,n),n.onDragStart(t),this._dragHandlers.size===2){let e=this._dragHandlers.values(),n=e.next().value,r=e.next().value;if(n instanceof qi&&r instanceof qi){let e=new Ki(this,this._targetObject,n,r);this._dragHandlers.set(this.gameObject,e),e.onDragStart(t)}else console.error(`Attempting to construct a MultiTouchDragHandler with invalid DragPointerHandlers. This is likely a bug.`,{a:n,b:r})}t.use(),this.context.accessibility.updateElement(this,{role:`button`,label:`Dragging `+(this.gameObject.name||`object`),hidden:!1,busy:!0}),this.context.accessibility.focus(this)}}onPointerUp(t){if(Ui&&V.DrawLabel(t.point??this.gameObject.worldPosition,`POINTERUP:`+t.pointerId+`, `+t.button,.03,3),!this.allowEdit(this.gameObject)||t.button!==0)return;this._potentialDragStartEvt=null;let n=this._dragHandlers.get(t.event.space),r=this._dragHandlers.get(this.gameObject);r&&(r.handlerA===n||r.handlerB===n)&&(this._dragHandlers.delete(this.gameObject),r.onDragEnd(t)),n&&(e._active>0&&--e._active,this.setTargetObject(null),n.onDragEnd&&n.onDragEnd(t),this._dragHandlers.delete(t.event.space),this._dragHandlers.size===0&&this.onLastDragEnd(t),t.use()),this.context.accessibility.unfocus(this),this.context.accessibility.updateElement(this,{busy:!1})}update(){for(let e of this._dragHandlers.values())e.collectMovementInfo&&e.collectMovementInfo(),e.getTotalMovement&&this._totalMovement.add(e.getTotalMovement());if(this._potentialDragStartEvt){if(!this._didDrag)if(this._totalMovement.length()>3e-4)this._didDrag=!0;else return;let e=this._potentialDragStartEvt;this._potentialDragStartEvt=null,this.onFirstDragStart(e)}for(let e of this._dragHandlers.values())e.onDragUpdate&&e.onDragUpdate(this._dragHandlers.size);this._dragHelper&&this._dragHelper.hasSelected&&this.onAnyDragUpdate()}onFirstDragStart(t){if(!t||!t.object)return;let n=F.getComponentInParent(t.object,e);if(!n||n!==this&&n._isDragging)return;let r=this._targetObject||this.gameObject;if(!r)return;this._isDragging=!0;let i=F.getComponentInChildren(r,rt);Ui&&console.log(`DRAG START`,i,r),i&&(i.fastMode=!0,i?.requestOwnership()),this._marker=F.addComponent(r,Pi),this._draggingRigidbodies.length=0;let a=F.getComponentsInChildren(r,E);a&&this._draggingRigidbodies.push(...a),r.matrixAutoUpdate===!1&&!globalThis[`DragControls:MatrixWarningShown`]&&(globalThis[`DragControls:MatrixWarningShown`]=!0,console.warn(`Dragging an object with matrixAutoUpdate=false can lead to unexpected behavior. Consider enabling matrixAutoUpdate or updating the matrix manually during dragging.`))}onAnyDragUpdate(){if(!this._dragHelper)return;this._dragHelper.showGizmo=this.showGizmo,this._dragHelper.onUpdate(this.context);for(let e of this._draggingRigidbodies)e.wakeUp(),e.resetVelocities(),e.resetForcesAndTorques();let e=this._targetObject||this.gameObject;qe.markDirty(e)}onLastDragEnd(e){if(!this||!this._isDragging)return;this._isDragging=!1;for(let e of this._draggingRigidbodies)e.setVelocity(e.smoothedVelocity.multiplyScalar(this.context.time.deltaTime));if(this._draggingRigidbodies.length=0,this._targetObject=null,e?.object){let t=F.getComponentInChildren(e.object,rt);t&&(t.fastMode=!1)}if(this._marker&&this._marker.destroy(),!this._dragHelper)return;let t=this._dragHelper.selected;Ui&&console.log(`DRAG END`,t,t?.visible),this._dragHelper.setSelected(null,this.context)}};Hi([A()],Gi.prototype,`dragMode`,void 0),Hi([A()],Gi.prototype,`snapGridResolution`,void 0),Hi([A()],Gi.prototype,`keepRotation`,void 0),Hi([A()],Gi.prototype,`xrDragMode`,void 0),Hi([A()],Gi.prototype,`xrKeepRotation`,void 0),Hi([A()],Gi.prototype,`xrDistanceDragFactor`,void 0),Hi([A()],Gi.prototype,`showGizmo`,void 0);var Ki=class{handlerA;handlerB;context;settings;gameObject;_handlerAAttachmentPoint=new n;_handlerBAttachmentPoint=new n;_followObject;_manipulatorObject;_deviceMode;_followObjectStartWorldQuaternion=new x;constructor(e,t,n,r){this.context=e.context,this.settings=e,this.gameObject=t,this.handlerA=n,this.handlerB=r,this._followObject=new y,this._manipulatorObject=new y,this.context.scene.add(this._manipulatorObject);let i=St.active?.rig?.gameObject;if(!this.handlerA||!this.handlerB||!this.handlerA.hitPointInLocalSpace||!this.handlerB.hitPointInLocalSpace){console.error(`Invalid: MultiTouchDragHandler needs two valid DragPointerHandlers with hitPointInLocalSpace set.`);return}if(this._tempVec1.copy(this.handlerA.hitPointInLocalSpace),this._tempVec2.copy(this.handlerB.hitPointInLocalSpace),this.gameObject.localToWorld(this._tempVec1),this.gameObject.localToWorld(this._tempVec2),i&&(i.worldToLocal(this._tempVec1),i.worldToLocal(this._tempVec2)),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.02?(Ui&&console.log(`Finding alternative drag attachment points since initial distance is too low: `+this._initialDistance.toFixed(2)),this.handlerA.followObject.parent.getWorldPosition(this._tempVec1),this.handlerB.followObject.parent.getWorldPosition(this._tempVec2),this._handlerAAttachmentPoint.copy(this._tempVec1),this._handlerBAttachmentPoint.copy(this._tempVec2),this.gameObject.worldToLocal(this._handlerAAttachmentPoint),this.gameObject.worldToLocal(this._handlerBAttachmentPoint),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.001&&(console.warn(`Not supported right now – controller drag points for multitouch are too close!`),this._initialDistance=1)):(this._handlerAAttachmentPoint.copy(this.handlerA.hitPointInLocalSpace),this._handlerBAttachmentPoint.copy(this.handlerB.hitPointInLocalSpace)),this._tempVec3.lerpVectors(this._tempVec1,this._tempVec2,.5),this._initialScale.copy(t.scale),Ui){this._followObject.add(new se(2)),this._manipulatorObject.add(new se(5));let e=e=>`${e.x.toFixed(2)}, ${e.y.toFixed(2)}, ${e.z.toFixed(2)}`;V.DrawLine(this._tempVec1,this._tempVec2,65535,0,!1),V.DrawLabel(this._tempVec3,`A:B `+this._initialDistance.toFixed(2)+` `+e(this._tempVec1)+` `+e(this._tempVec2),.03,5)}}onDragStart(e){this.gameObject.add(this._followObject),this._followObject.matrixAutoUpdate=!1,this._followObject.matrix.identity(),this._deviceMode=e.mode,this._followObjectStartWorldQuaternion.copy(this._followObject.worldQuaternion),this.alignManipulator(),this._manipulatorObject.attach(this._followObject),this._manipulatorPosOffset.copy(this._followObject.position),this._manipulatorRotOffset.copy(this._followObject.quaternion),this._manipulatorScaleOffset.copy(this._followObject.scale)}onDragEnd(e){if(!this.handlerA||!this.handlerB){console.error(`onDragEnd called on MultiTouchDragHandler without valid handlers. This is likely a bug.`);return}this.handlerA.recenter(),this.handlerB.recenter(),this._manipulatorObject.removeFromParent(),this._followObject.removeFromParent(),this._manipulatorObject.destroy(),this._followObject.destroy()}_manipulatorPosOffset=new n;_manipulatorRotOffset=new x;_manipulatorScaleOffset=new n;_tempVec1=new n;_tempVec2=new n;_tempVec3=new n;tempLookMatrix=new _;_initialScale=new n;_initialDistance=0;alignManipulator(){if(!this.handlerA||!this.handlerB){console.error(`alignManipulator called on MultiTouchDragHandler without valid handlers. This is likely a bug.`,this);return}if(!this.handlerA.followObject||!this.handlerB.followObject){console.error(`alignManipulator called on MultiTouchDragHandler without valid follow objects. This is likely a bug.`,this.handlerA,this.handlerB);return}this._tempVec1.copy(this._handlerAAttachmentPoint),this._tempVec2.copy(this._handlerBAttachmentPoint),this.handlerA.followObject.localToWorld(this._tempVec1),this.handlerB.followObject.localToWorld(this._tempVec2),this._tempVec3.lerpVectors(this._tempVec1,this._tempVec2,.5),this._manipulatorObject.position.copy(this._tempVec3);let e=this.context.mainCamera;this.tempLookMatrix.lookAt(this._tempVec3,this._tempVec2,e.worldUp),this._manipulatorObject.quaternion.setFromRotationMatrix(this.tempLookMatrix);let t=this._tempVec1.distanceTo(this._tempVec2);this._manipulatorObject.scale.copy(this._initialScale).multiplyScalar(t/this._initialDistance),this._manipulatorObject.updateMatrix(),this._manipulatorObject.updateMatrixWorld(!0),Ui&&(V.DrawLabel(this._tempVec3.clone().add(new n(0,.2,0)),`A:B `+t.toFixed(2),.03),V.DrawLine(this._tempVec1,this._tempVec2,65280,0,!1))}onDragUpdate(){this.alignManipulator(),this._followObject.position.copy(this._manipulatorPosOffset),this._followObject.quaternion.copy(this._manipulatorRotOffset),this._followObject.scale.copy(this._manipulatorScaleOffset);let e=this.gameObject,t=this._followObject;if(!e){console.error(`MultiTouchDragHandler has no dragged object. This is likely a bug.`);return}t.updateMatrix(),t.updateMatrixWorld(!0);let n=this._deviceMode===`tracked-pointer`||this._deviceMode===`transient-pointer`?this.settings.xrKeepRotation:this.settings.keepRotation;if(this.settings.snapGridResolution>0){let e=this._followObject.worldPosition,t=this.settings.snapGridResolution;e.x=Math.round(e.x/t)*t,e.y=Math.round(e.y/t)*t,e.z=Math.round(e.z/t)*t,this._followObject.worldPosition=e,this._followObject.updateMatrix()}n&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());let r=O.clamp01(this.context.time.deltaTime*30*1),i=e.worldPosition;i.lerp(t.worldPosition,r),e.worldPosition=i;let a=e.worldQuaternion;a.slerp(t.worldQuaternion,r),e.worldQuaternion=a;let o=e.worldScale;o.lerp(t.worldScale,r),e.worldScale=o,e.matrixAutoUpdate===!1&&e.updateMatrix()}setTargetObject(e){this.gameObject=e}},qi=class{getTotalMovement(){return this._totalMovement}get followObject(){return this._followObject}get hitPointInLocalSpace(){return this._hitPointInLocalSpace}context;gameObject;settings;_lastRig=void 0;_followObject;_totalMovement=new n;_totalMovementAlongRayDirection=0;_grabStartDistance=0;_deviceMode;_followObjectStartPosition=new n;_followObjectStartQuaternion=new x;_followObjectStartWorldQuaternion=new x;_lastDragPosRigSpace;_tempVec=new n;_tempMat=new _;_hitPointInLocalSpace=new n;_hitNormalInLocalSpace=new n;_bottomCenter=new n;_backCenter=new n;_backBottomCenter=new n;_bounds=new ie;_dragPlane=new ae(new n(0,1,0));_draggedOverObject=null;_draggedOverObjectLastSetUp=null;_draggedOverObjectLastNormal=new n;_draggedOverObjectDuration=0;setTargetObject(e){this.gameObject=e}constructor(e,t){this.settings=e,this.context=e.context,this.gameObject=t,this._followObject=new y}recenter(){if(!this._followObject.parent){console.warn(`Error: space follow object doesn't have parent but recenter() is called. This is likely a bug`);return}if(!this.gameObject){console.warn(`Error: space follow object doesn't have a gameObject`);return}let e=this._followObject.parent;this.gameObject.add(this._followObject),this._followObject.matrixAutoUpdate=!1,this._followObject.position.set(0,0,0),this._followObject.quaternion.set(0,0,0,1),this._followObject.scale.set(1,1,1),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0),e.attach(this._followObject),this._followObjectStartPosition.copy(this._followObject.position),this._followObjectStartQuaternion.copy(this._followObject.quaternion),this._followObjectStartWorldQuaternion.copy(this._followObject.worldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);let t=this._hitPointInLocalSpace.clone();this.gameObject.localToWorld(t),this._grabStartDistance=t.distanceTo(e.worldPosition);let r=(St.active?.rig?.gameObject)?.worldScale.x||1;this._grabStartDistance/=r,this._totalMovementAlongRayDirection=0,this._lastDragPosRigSpace=void 0,Ui&&(V.DrawLine(t,e.worldPosition,65280,.5,!1),V.DrawLabel(e.worldPosition.add(new n(0,.1,0)),this._grabStartDistance.toFixed(2),.03,.5))}onDragStart(e){if(!this.gameObject){console.warn(`Error: space follow object doesn't have a gameObject`);return}if(e.event.space.add(this._followObject),this._lastDragPosRigSpace=void 0,e.point&&e.normal)this._hitPointInLocalSpace.copy(e.point),this.gameObject.worldToLocal(this._hitPointInLocalSpace),this._hitNormalInLocalSpace.copy(e.normal);else if(e){let t=e.event.space,n=t.worldPosition;this.gameObject.worldToLocal(n),this._hitPointInLocalSpace.copy(n);let r=t.worldUp;this._tempMat.copy(this.gameObject.matrixWorld).invert(),r.transformDirection(this._tempMat),this._hitNormalInLocalSpace.copy(r)}this.recenter(),this._totalMovement.set(0,0,0),this._deviceMode=e.mode;let t=this._followObject.parent.worldForward,r=this._deviceMode===`tracked-pointer`||this._deviceMode===`transient-pointer`?this.settings.xrDragMode:this.settings.dragMode,i=this._hitPointInLocalSpace.clone();switch(this.gameObject.localToWorld(i),r){case K.XZPlane:let e=new n(0,1,0);this.gameObject.parent&&e.transformDirection(this.gameObject.parent.matrixWorld.clone().invert()),this._dragPlane.setFromNormalAndCoplanarPoint(e,i);break;case K.HitNormal:let r=this._hitNormalInLocalSpace.clone();r.transformDirection(this.gameObject.matrixWorld),this._dragPlane.setFromNormalAndCoplanarPoint(r,i);break;case K.Attached:this._dragPlane.setFromNormalAndCoplanarPoint(t,i);break;case K.DynamicViewAngle:this.setPlaneViewAligned(i,!0);break;case K.SnapToSurfaces:this.setPlaneViewAligned(i,!1);break;case K.None:break}let a=this.gameObject.parent,o=this.gameObject.position.clone(),s=this.gameObject.quaternion.clone(),c=this.gameObject.scale.clone(),l=this.gameObject.matrixWorld.clone();a&&a.remove(this.gameObject),this.gameObject.position.set(0,0,0),this.gameObject.quaternion.set(0,0,0,1),this.gameObject.scale.set(1,1,1);let u=Nt([this.gameObject]);u.expandByPoint(this.gameObject.worldPosition);let d=new n;u.getCenter(d);let f=new n;u.getSize(f),this._bottomCenter.copy(d.clone().add(new n(0,-f.y/2,0))),this._backCenter.copy(d.clone().add(new n(0,0,f.z/2))),this._backBottomCenter.copy(d.clone().add(new n(0,-f.y/2,f.z/2))),this._bounds.copy(u),a&&a.add(this.gameObject),this.gameObject.position.copy(o),this.gameObject.quaternion.copy(s),this.gameObject.scale.copy(c),this.gameObject.matrixWorld.copy(l),this._draggedOverObject=null,this._draggedOverObjectLastSetUp=null,this._draggedOverObjectLastNormal.set(0,1,0),this._draggedOverObjectDuration=0}collectMovementInfo(){if(!this._followObject.parent)return;let e=this._followObject.parent;this._followObject.updateMatrix();let t=e.worldPosition,n=St.active?.rig?.gameObject;n&&n.worldToLocal(t),(this._lastDragPosRigSpace===void 0||n!=this._lastRig)&&(this._lastDragPosRigSpace=t.clone(),this._lastRig=n),this._tempVec.copy(t).sub(this._lastDragPosRigSpace);let r=e.worldForward;if(n&&(this._tempMat.copy(n.matrixWorld).invert(),r.transformDirection(this._tempMat)),this._totalMovementAlongRayDirection+=r.dot(this._tempVec),this._tempVec.x=Math.abs(this._tempVec.x),this._tempVec.y=Math.abs(this._tempVec.y),this._tempVec.z=Math.abs(this._tempVec.z),this._totalMovement.add(this._tempVec),this._lastDragPosRigSpace.copy(t),Ui){let e=t;n&&(e=e.clone(),e.transformDirection(n.matrixWorld)),V.DrawRay(e,r,255)}}onDragUpdate(e){if(e>1)return;let t=this.gameObject;if(!t||!this._followObject){console.warn(`Warning: DragPointerHandler doesn't have a dragged object. This is likely a bug.`);return}let r=this._followObject.parent;if(!r){console.warn(`Warning: DragPointerHandler doesn't have a drag source. This is likely a bug.`);return}this._followObject.updateMatrix();let i=r.worldPosition,o=r.worldForward,s=this._deviceMode===`tracked-pointer`||this._deviceMode===`transient-pointer`,c=s?this.settings.xrKeepRotation:this.settings.keepRotation,l=s?this.settings.xrDragMode:this.settings.dragMode;if(l===K.None)return;c&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);let u=1,d=2;if(s&&this._grabStartDistance>.5){let e=1+this._totalMovementAlongRayDirection*(2*this.settings.xrDistanceDragFactor);u=Math.max(0,e),u=u*u*u}else this._grabStartDistance<=.5&&(d=3);this._followObject.position.copy(this._followObjectStartPosition),c||this._followObject.quaternion.copy(this._followObjectStartQuaternion),this._followObject.position.multiplyScalar(u),this._followObject.updateMatrix();let f=this._hasLastSurfaceHitPoint;this._hasLastSurfaceHitPoint=!1;let p=new a(i,o);if(l==K.SnapToSurfaces){let e=this.context.physics.raycastFromRay(p,{testObject:e=>e!==this.followObject&&e!==r&&e!==t});if(e.length>0){let t=e[0];if(this._draggedOverObject===t.object?this._draggedOverObjectDuration+=this.context.time.deltaTime:(this._draggedOverObject=t.object,this._draggedOverObjectDuration=0),t.face){this._hasLastSurfaceHitPoint=!0,this._lastSurfaceHitPoint.copy(t.point);let e=this._draggedOverObjectDuration>=.15,n=this._totalMovement.length()>=.001,r=z(t.normal||t.face.normal).applyQuaternion(t.object.worldQuaternion);if((e||n)&&(this._draggedOverObjectLastSetUp!==this._draggedOverObject||this._draggedOverObjectLastNormal.dot(r)<.999999||this.context.time.frame%60==0)){this._draggedOverObjectLastSetUp=this._draggedOverObject,this._draggedOverObjectLastNormal.copy(t.face.normal);let e=z(),n=z();this._bounds.getCenter(e),this._bounds.getSize(n),e.sub(n.multiplyScalar(.5).multiply(r)),this._hitPointInLocalSpace.copy(e),this._hitNormalInLocalSpace.copy(t.face.normal),this._bounds.getCenter(e),this._bounds.getSize(n),e.add(n.multiplyScalar(.5).multiply(t.face.normal));let i=z(this._hitPointInLocalSpace).add(e);this._followObject.localToWorld(i);let a=t.point;this._dragPlane.setFromNormalAndCoplanarPoint(r,a)}else if(!(e||n))return}}else f&&this.gameObject&&this.setPlaneViewAligned(this.gameObject.worldPosition,!1)}if(l!==K.Attached&&p.intersectPlane(this._dragPlane,this._tempVec)){this._followObject.worldPosition=this._tempVec,this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);let e=z(this._hitPointInLocalSpace);this._followObject.localToWorld(e),Ui&&V.DrawLine(e,this._tempVec,65535,0,!1),this._followObject.worldPosition=this._tempVec.multiplyScalar(2).sub(e),this._followObject.updateMatrix(),this._followObject.updateMatrix()}if(this.settings.snapGridResolution>0){let e=this._followObject.worldPosition,t=this.settings.snapGridResolution;e.x=Math.round(e.x/t)*t,e.y=Math.round(e.y/t)*t,e.z=Math.round(e.z/t)*t,this._followObject.worldPosition=e,this._followObject.updateMatrix()}c&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());let m=O.clamp01(this.context.time.deltaTime*10*d),ee=O.clamp01(this.context.time.deltaTime*10*.5*d),h=t.worldPosition;h.lerp(this._followObject.worldPosition,m),t.worldPosition=h;let g=t.worldQuaternion;if(g.slerp(this._followObject.worldQuaternion,ee),t.worldQuaternion=g,t.matrixAutoUpdate===!1&&t.updateMatrix(),Ui){let e=this._hitPointInLocalSpace.clone();t.localToWorld(e),V.DrawSphere(e,.02,16711680);let r=this._hitNormalInLocalSpace.clone();r.applyQuaternion(g),V.DrawRay(e,r,16711680),V.DrawLabel(h.add(new n(0,.25,0)),`Distance: ${this._totalMovement.length().toFixed(2)}\n Along Ray: ${this._totalMovementAlongRayDirection.toFixed(2)}\n Session: ${!!St.active}\n Device: ${this._deviceMode}\n `,.03);let i=this._bottomCenter.clone(),a=this._backCenter.clone(),o=this._backBottomCenter.clone();t.localToWorld(i),t.localToWorld(a),t.localToWorld(o),V.DrawSphere(i,.01,65280,0,!1),V.DrawSphere(a,.01,255,0,!1),V.DrawSphere(o,.01,16711935,0,!1),V.DrawLine(i,o,65535,0,!1),V.DrawLine(o,a,65535,0,!1)}}onDragEnd(e){console.assert(this._followObject.parent===e.event.space,`Drag end: _followObject is not parented to the space object`),this._followObject.removeFromParent(),this._followObject.destroy(),this._lastDragPosRigSpace=void 0}_hasLastSurfaceHitPoint=!1;_lastSurfaceHitPoint=new n;setPlaneViewAligned(e,t){if(!this._followObject.parent)return!1;let n=this._followObject.parent.worldForward,r=z(0,1,0),i=n,a=r.angleTo(i),o=.5;return t&&(a>Math.PI/2+o||ae!==this._selected;let r=this._context.physics.raycastFromRay(t,n);for(let e=0;e{s instanceof y&&s.scale.set(1,e,1)}}}e.addPreview=r;function i(e){let n=t.get(e);n&&(t.delete(e),n.removeFromParent())}e.removePreview=i})(Xi||={});var Zi=[],Qi=[],$i;(function(e){function t(e,t){let n={name:t?.name,priority:t?.priority??0,callback:e};return Zi.push(n),Zi.sort((e,t)=>e.priority===t.priority?0:e.priority>t.priority?-1:1),()=>{let e=Zi.indexOf(n);e>=0&&Zi.splice(e,1)}}e.onCreateCustomModelLoader=t;function n(e){return Qi.push(e),()=>{let t=Qi.indexOf(e);t>=0&&Qi.splice(t,1)}}e.onDetermineModelMimetype=n})($i||={});var q=N(`debugfileformat`);function ea(e){switch((e.split(`.`).pop()||e).toUpperCase()){case`GLTF`:return`model/gltf+json`;case`VRM`:return`model/vrm`;case`GLB`:return`model/gltf-binary`;case`FBX`:return`model/fbx`;case`USD`:return`model/vnd.usd+zip`;case`USDA`:return`model/vnd.usda+zip`;case`USDZ`:return`model/vnd.usdz+zip`;case`OBJ`:return`model/obj`;default:return null}}async function ta(e,t){let{useExtension:n=!0}=t;if(n){let t=new URL(e,globalThis.location.href),n=null,r=t.searchParams.get(`filetype`);switch(r&&(n=r.toUpperCase()),n?.length||(n=t.pathname.split(`.`).pop()?.toUpperCase()),q&&console.warn(`[Needle Engine] Try to use file extension to determine type: '${n}'`),n){case`GLTF`:return`model/gltf+json`;case`VRM`:return`model/vrm`;case`GLB`:return`model/gltf-binary`;case`FBX`:return`model/fbx`;case`USD`:return`model/vnd.usd+zip`;case`USDA`:return`model/vnd.usda+zip`;case`USDZ`:return`model/vnd.usdz+zip`;case`OBJ`:return`model/obj`;case`MTLX`:return`application/materialx+xml`}}let r=e;if(!e.startsWith(`blob:`)){let t=new URL(e,globalThis.location.href);t.searchParams.append(`range`,`true`),e=t.toString()}let i=await fetch(e,{method:`GET`,headers:{range:`bytes=0-32`}}).catch(e=>null);if(i?.ok){let e=na(r,await i.arrayBuffer(),i);return q&&console.log(`[Needle Engine] Determined file type from header: `+e),e}return`unknown`}function na(e,t,n){if(t.byteLength<4)return`unknown`;let r=new Uint8Array(t);q&&q&&console.warn(`[Needle Engine] Trying to determine file type from binary data `,`"`+new TextDecoder().decode(t)+`" `,r);let i=new TextDecoder().decode(t).replace(/\s/g,``);if(i[0]===`{`&&i[1]===`"`)return q&&console.debug(`GLTF detected`),`model/gltf+json`;if(r[0]==103&&r[1]==108&&r[2]==84&&r[3]==70&&(r[4]==10||r[4]===2))return q&&console.debug(`GLTF .bin detected`),`model/gltf+json`;if(r[0]==103&&r[1]==108&&r[2]==84&&r[3]==70&&r[4]==98)return q&&console.debug(`GLB detected`),`model/gltf-binary`;if(r[0]==80&&r[1]==75&&r[2]==3&&r[3]==4)return q&&console.debug(`USDZ detected`),`model/vnd.usdz+zip`;if(r[0]==80&&r[1]==88&&r[2]==82&&r[3]==45&&r[4]==85&&r[5]==83&&r[6]==68&&r[7]==67)return q&&console.debug(`Binary USD detected`),`model/vnd.usd`;if(r[0]==35&&r[1]==117&&r[2]==115&&r[3]==100&&r[4]==97)return q&&console.debug(`ASCII USD detected`),`model/vnd.usda`;if(r[0]==75&&r[1]==97&&r[2]==121&&r[3]==100&&r[4]==97&&r[5]==114&&r[6]==97&&r[7]==32)return q&&console.debug(`Binary FBX detected`),`model/fbx`;if(r[0]==59&&r[1]==32&&r[2]==70&&r[3]==66&&r[4]==88&&r[5]==32)return q&&console.debug(`ASCII FBX detected`),`model/fbx`;if(r[0]==35&&r[1]==32&&r[2]==66&&r[3]==108&&r[4]==101&&r[5]==110&&r[6]==100&&r[7]==101&&r[8]==114&&r[9]==32||r[0]==35&&r[1]==32&&r[2]==65&&r[3]==108&&r[4]==105&&r[5]==97&&r[6]==115&&r[7]==32&&r[8]==79&&r[9]==66&&r[10]==74)return q&&console.debug(`OBJ detected`),`model/obj`;if(n.headers.has(`content-type`)){let e=n.headers.get(`content-type`);if(e?.startsWith(`image/`))return q&&console.debug(`Image detected, not a model file`),`unsupported`;switch(q&&console.debug(`Content-Type: `+e),e){case`model/gltf+json`:case`model/gltf-binary`:case`model/vrm`:case`model/vnd.usdz+zip`:case`model/vnd.usd+zip`:case`model/vnd.usd`:case`model/vnd.usda+zip`:case`model/vnd.usda`:case`model/vnd.usdc`:case`model/fbx`:case`model/vnd.autodesk.fbx`:case`model/obj`:case`application/materialx+xml`:return e;case`text/plain`:break}}if(r[0]==118&&r[1]==32||r[0]==102&&r[1]==32)return q&&console.debug(`OBJ detected (the file has no header and starts with vertex or face)`),`obj`;if(r[0]==35&&r[1]==32&&r[2]==70&&r[3]==105&&r[4]==108&&r[5]==101&&r[6]==32&&r[7]==101&&r[8]==120&&r[9]==112&&r[10]==111&&r[11]==114&&r[12]==116&&r[13]==101&&r[14]==100&&r[15]==32&&r[16]==98&&r[17]==121&&r[18]==32&&r[19]==90&&r[20]==66&&r[21]==114&&r[22]==117&&r[23]==115&&r[24]==104)return q&&console.debug(`OBJ detected (exported by ZBrush)`),`obj`;if(r[0]==109&&r[1]==116&&r[2]==108&&r[3]==108&&r[4]==105&&r[5]==98)return q&&console.debug(`OBJ detected (mtllib)`),`obj`;for(let t of Qi){let i=t({url:e,response:n,contentType:n.headers.get(`content-type`),bytes:r});if(i)return q&&console.debug(`Mimetype callback returned: ${i}`),i}if(w()||q){let e=new TextDecoder().decode(t.slice(0,Math.min(t.byteLength,32)));q&&console.warn(`Could not determine file type.\n\nConsider registering a custom loader via the 'onCreateCustomModelLoader' callback: 'NeedleEngineModelLoader.onCreateCustomModelLoader(args => { })'\n\nContent-Type: \"${n.headers.get(`content-type`)}\"\n\"Text: \"${e}\"\nBinary:`,r)}else q&&console.debug(`Could not determine file type from binary data`);return`unknown`}var ra=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},J=N(`debugdroplistener`),ia;(function(e){e.FileDropped=`file-dropped`,e.ObjectAdded=`object-added`})(ia||={});var aa=class extends CustomEvent{constructor(e){super(ia.ObjectAdded,{detail:e})}},oa=`blob`,sa=class extends R{dropArea;fitIntoVolume=!1;fitVolumeSize=new n(1,1,1);placeAtHitPosition=!0;useNetworking=!1;onDropped=new k;loadFromURL(e,t){return this.addFromUrl(e,{screenposition:new b,point:t?.point,size:t?.size},!1)}forgetObjects(){this.removePreviouslyAddedObjects(!1)}awake(){for(let e of this.gameObject.children)this.dropArea&&e.contains(this.dropArea)||this._addedObjects.push(e)}onEnable(){this.context.renderer.domElement.addEventListener(`dragover`,this.onDrag),this.context.renderer.domElement.addEventListener(`drop`,this.onDrop),window.addEventListener(`paste`,this.handlePaste),this.context.connection.beginListen(`droplistener`,this.onNetworkEvent),w()&&this.dropArea&&(this.dropArea.getComponentInChildren(Vn)||console.warn(`[DropListener] The assigned DropArea does not seem to have a renderer/mesh. Drag and Drop events will not be detected.`))}onDisable(){this.context.renderer.domElement.removeEventListener(`dragover`,this.onDrag),this.context.renderer.domElement.removeEventListener(`drop`,this.onDrop),window.removeEventListener(`paste`,this.handlePaste),this.context.connection.stopListen(`droplistener`,this.onNetworkEvent)}onNetworkEvent=e=>{if(!this.useNetworking){J&&console.debug(`[DropListener] Ignoring networked event because networking is disabled`,e);return}if(e.guid?.startsWith(this.guid)){let t=e.url;if(console.debug(`[DropListener] Received networked event`,e),t)if(Array.isArray(t))for(let n of t)this.addFromUrl(n,{screenposition:new b,point:e.point,size:e.size},!0);else this.addFromUrl(t,{screenposition:new b,point:e.point,size:e.size},!0)}};handlePaste=e=>{this.context.connection.allowEditing!==!1&&(e.defaultPrevented||navigator.clipboard.readText().then(e=>{if(e&&(e.startsWith(`http`)||e.startsWith(`https`)||e.startsWith(`blob`))){let t={screenposition:new b(this.context.input.mousePosition.x,this.context.input.mousePosition.y)};this.testIfIsInDropArea(t)&&this.addFromUrl(e,t,!1)}}).catch(console.warn))};onDrag=e=>{J&&console.debug(`DropListener Drag`,e,this.context.connection.allowEditing),this.context.connection.allowEditing!==!1&&e.preventDefault()};onDrop=async e=>{if(J&&console.debug(`DropListener Drop`,e,this.context.connection.allowEditing),this.context.connection.allowEditing===!1||!e?.dataTransfer||e[`droplistener:handled`])return;e.preventDefault();let t={screenposition:new b(e.offsetX,e.offsetY)};if(this.dropArea&&this.testIfIsInDropArea(t)===!1)return;e[`droplistener:handled`]=!0;let n=e.dataTransfer.items;if(!n)return;let r=[];for(let e in n){let i=n[e];if(i.kind===`file`){let e=i.getAsFile();if(!e)continue;r.push(e)}else i.kind===`string`&&i.type==`text/plain`&&i.getAsString(e=>{this.addFromUrl(e,t,!1)})}r.length>0&&await this.addFromFiles(r,t)};async addFromUrl(e,t,n){J&&console.log(`dropped url`,e);try{if(e.startsWith(`https://github.com/`)){let t=e.split(`/`);e=`https://raw.githubusercontent.com/${t[3]}/${t[4]}/${t[6]}/${t.slice(7).join(`/`)}`}else e.startsWith(`https://polyhaven.com/a`)&&(e=ca(e));if(!e)return null;let r=e.toLowerCase();if(r.endsWith(`.hdr`)||r.endsWith(`.hdri`)||r.endsWith(`.exr`)||r.endsWith(`.png`)||r.endsWith(`.jpg`)||r.endsWith(`.jpeg`))return console.warn(`Fileformat is not supported: ${r}`),null;this.removePreviouslyAddedObjects();let i=await la.loadFileFromURL(new URL(e),{guid:this.guid,context:this.context,parent:this.gameObject,point:t.point,size:t.size});if(i&&this._addedObjects.length<=0)return t.url=e,this.onObjectLoaded(i,t,n)}catch{console.warn(`String is not a valid URL`,e)}return null}_abort=null;async addFromFiles(e,t){if(J&&console.log(`Add files`,e),Array.isArray(e)&&e.length){this.deleteDropEvent(),this.removePreviouslyAddedObjects(),Ve(oa,null),this._abort?.abort(`New files dropped`),this._abort=new AbortController;for(let n of e){if(!n)continue;if(n.type.startsWith(`image/`)){J&&console.warn(`Ignoring dropped image file`,n.name,n.type);continue}else if(n.name.endsWith(`.bin`)){J&&console.warn(`Ignoring dropped binary file`,n.name,n.type);continue}console.debug(`Load file `+n.name+` + `+n.type);let e=await la.loadFile(n,this.context,{guid:this.guid});if(e){this.dispatchEvent(new CustomEvent(ia.FileDropped,{detail:n})),t.file=n;let r=this.onObjectLoaded(e,t,!1);r&&this.context.connection.isConnected&&this.useNetworking&&(console.debug(`Uploading dropped file to blob storage`),Tt.upload(n,{abort:this._abort?.signal}).then(t=>{t?.download_url&&this._addedObjects.includes(r)&&this.sendDropEvent(t.download_url,r,e.contentMD5)}).catch(console.warn));break}}}}_addedObjects=[];_addedModels=[];removePreviouslyAddedObjects(e=!0){if(e)for(let e of this._addedObjects)e.parent===this.gameObject&&e.destroy();this._addedObjects.length=0,this._addedModels.length=0}onObjectLoaded(e,t,r){let{model:i,contentMD5:a}=e;if(J&&console.log(`Dropped ${this.gameObject.name}`,i),!i?.scene)return console.warn(`No object specified to add to scene`,i),null;this.removePreviouslyAddedObjects();let o=i.scene;o.position.copy(this.gameObject.worldPosition);let s=_t(this.gameObject),c=new n(0,0,0);s.x=Math.abs(s.x),s.y=Math.abs(s.y),s.z=Math.abs(s.z);let l=o.scale.clone(),u=new ie().setFromCenterAndSize(new n(0,this.fitVolumeSize.y*s.y*.5,0).add(this.gameObject.worldPosition),this.fitVolumeSize.clone().multiply(s));if(J&&V.DrawWireBox3(u,255,5),this.fitIntoVolume&&(Wt(o,u,{position:!this.placeAtHitPosition}),l=o.scale.clone().divide(s),c=o.worldPosition.clone().sub(this.gameObject.worldPosition).divide(s),J&&V.DrawSphere(c,.1,16711680,5)),this.gameObject.attach(o),o.position.copy(c),o.quaternion.identity(),o.scale.copy(l),J&&V.DrawArrow(this.gameObject.worldPosition,o.getWorldPosition(new n),65280,5),this._addedObjects.push(o),this._addedModels.push(i),this.placeAtHitPosition&&t&&t.screenposition){o.visible=!1;let e=this.context.physics.raycast({screenPoint:this.context.input.convertScreenspaceToRaycastSpace(t.screenposition.clone())});if(o.visible=!0,e&&e.length>0)for(let t of e){let e=t.point.clone();J&&console.log(`Place object at hit`,t),Re(o,e);break}}at.autoplayAnimations(i);let d=new aa({sender:this,gltf:i,model:i,object:o,contentMD5:a,dropped:t.file||(t.url?new URL(t.url):void 0)});return this.dispatchEvent(d),this.onDropped?.invoke(d.detail),!r&&t.url?.startsWith(`http`)&&this.context.connection.isConnected&&o&&this.sendDropEvent(t.url,o,a),o}async sendDropEvent(e,t,r){if(!this.useNetworking){J&&console.debug(`[DropListener] Ignoring networked event because networking is disabled`,e);return}if(this.context.connection.isConnected){console.debug(`Sending drop event "`+t.name+`"`,e);let i=Nt([t]),a={name:t.name,guid:this.guid,url:e,point:t.worldPosition.clone(),size:i.getSize(new n),contentMD5:r};this.context.connection.send(`droplistener`,a)}}deleteDropEvent(){this.context.connection.sendDeleteRemoteState(this.guid)}testIfIsInDropArea(e){let t=this.context.input.convertScreenspaceToRaycastSpace(e.screenposition.clone()),n=this.context.physics.raycast({screenPoint:t,recursive:!0,testObject:e=>!this._addedObjects.some(t=>t.contains(e))});if(!n.length)return w()&&console.log(`Dropped outside of drop area for DropListener \"${this.name}\".`),!1;let r=n[0];return!!(this.dropArea&&this.dropArea.contains(r.object))}};ra([A(y)],sa.prototype,`dropArea`,void 0),ra([A()],sa.prototype,`fitIntoVolume`,void 0),ra([A(n)],sa.prototype,`fitVolumeSize`,void 0),ra([A()],sa.prototype,`placeAtHitPosition`,void 0),ra([A()],sa.prototype,`useNetworking`,void 0),ra([A(k)],sa.prototype,`onDropped`,void 0);function ca(e){if(!e.startsWith(`https://polyhaven.com/`))return e;let t=new URL(e).pathname.split(`/`).pop(),n=`https://dl.polyhaven.org/file/ph-assets/Models/gltf/4k/${t}/${t}_4k.gltf`;return console.log(`Resolved polyhaven asset url`,e,`→`,n),n}var la;(function(e){async function t(e,t,n){let r=n.guid,i=new mt(r),a=new Blob([e],{type:e.type||ea(e.name)||void 0}),o=URL.createObjectURL(a),s=await Fe().loadSync(t,o,e.name,i).catch(t=>(console.error(`Failed to load file "${e.name}" (${e.type}):`,t),null));return URL.revokeObjectURL(o),s?new Promise((t,n)=>{let r=new FileReader;r.readAsArrayBuffer(e),r.onloadend=async e=>{let n=r.result;return t({model:s,contentMD5:Tt.hashMD5(n)})}}):(console.warn(`Failed to load "${e.name}" (${e.type})`),null)}e.loadFile=t;async function n(e,t){return new Promise(async(n,r)=>{let i=new mt(t.guid),a=e.toString();J&&V.DrawWireSphere(t.point,.1,16711680,3);let o=Xi.addPreview({guid:t.guid,parent:t.parent,position:t?.point,size:t?.size}),s=await Fe().loadSync(t.context,a,a,i,e=>{o.onProgress(e.loaded/e.total)}).catch(console.warn);if(s){let e=await fetch(a).then(e=>e.arrayBuffer()),r=Tt.hashMD5(e);J?setTimeout(()=>Xi.removePreview(t.guid),3e3):Xi.removePreview(t.guid),n({model:s,contentMD5:r})}else J?setTimeout(()=>Xi.removePreview(t.guid),3e3):Xi.removePreview(t.guid),console.warn(`Unsupported file type: `+e.toString())})}e.loadFileFromURL=n})(la||={});var ua=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},da=class e extends R{parent=null;object=null;limitCount=60;_currentCount=0;_startPosition=null;_startQuaternion=null;start(){if(this._currentCount=0,this._startPosition=null,this._startQuaternion=null,this.object||=this.gameObject,this.object){if(this.object===this.gameObject){let t=new mt(this.guid);this.object=F.instantiate(this.object,{idProvider:t,keepWorldPosition:!1}),F.getComponent(this.object,e)?.destroy();let n=this.object.getComponentInChildren(Gi);n||(n=this.object.addComponent(Gi,{dragMode:K.SnapToSurfaces}),n.guid=t.generateUUID());let r=F.getComponent(n.gameObject,rt);r||(r=n.gameObject.addComponent(rt),r.guid=t.generateUUID())}this.object.visible=!1;let t=this.gameObject.getComponent(Gi);t&&(t.enabled=!1),this._startPosition=this.object.position?.clone()??new n(0,0,0),this._startQuaternion=this.object.quaternion?.clone()??new x(0,0,0,1)}this.gameObject.getComponentInParent(C)||this.gameObject.addComponent(C)}onEnable(){this.startCoroutine(this.cloneLimitIntervalFn())}_forwardPointerEvents=new Map;onPointerEnter(e){e.used||this.object&&this.context.connection.allowEditing&&e.button===0&&this.context.input.setCursor(`pointer`)}onPointerExit(e){e.used||this.object&&this.context.connection.allowEditing&&e.button===0&&this.context.input.unsetCursor(`pointer`)}onPointerDown(e){if(e.used||!this.object||!this.context.connection.allowEditing||e.button!==0)return;let t=this.handleDuplication();if(t){let n=F.getComponent(t,Gi);n?(n.onPointerDown(e),this._forwardPointerEvents.set(e.event.space,n)):w()&&console.warn(`Duplicated object (${t.name}) does not have DragControls`)}else this._currentCount>=this.limitCount?console.warn(`[Duplicatable] Limit of ${this.limitCount} objects created within a few seconds reached. Please wait a moment before creating more objects.`):console.warn(`[Duplicatable] Could not duplicate object.`)}onPointerUp(e){if(e.used)return;let t=this._forwardPointerEvents.get(e.event.space);t&&(t.onPointerUp(e),this._forwardPointerEvents.delete(e.event.space))}*cloneLimitIntervalFn(){for(;this.activeAndEnabled&&!this.destroyed;)this._currentCount>0?--this._currentCount:this._currentCount<0&&(this._currentCount=0),yield Ke(1)}handleDuplication(){if(!this.object||this.limitCount>0&&this._currentCount>=this.limitCount||this.object===this.gameObject)return null;if(F.isDestroyed(this.object))return this.object=null,null;this.object.matrixAutoUpdate===!1&&(this.object.updateMatrix(),w()&&(console.warn(`Object "${this.object.name}" has matrixAutoUpdate disabled. This can cause duplicated objects to have incorrect position/rotation/scale. Consider enabling matrixAutoUpdate or calling updateMatrix() before duplication.`),Ht(`Duplicatable: Object has matrixAutoUpdate disabled`))),this.object.visible=!0,this._startPosition&&this.object.position.copy(this._startPosition),this._startQuaternion&&this.object.quaternion.copy(this._startQuaternion);let e=new nt;this.parent||=this.gameObject.parent,this.parent&&(e.parent=this.parent.guid??this.parent.userData?.guid,e.keepWorldPosition=!0),e.position=this.worldPosition,e.rotation=this.worldQuaternion,e.context=this.context,this._currentCount+=1;let t=F.instantiateSynced(this.object,e);return console.assert(t!==this.object,`Duplicated object is original`),this.object.visible=!1,this._startPosition&&this.object.position.clone().copy(this._startPosition),this._startQuaternion&&this.object.quaternion.clone().copy(this._startQuaternion),t}};ua([A(y)],da.prototype,`parent`,void 0),ua([A(y)],da.prototype,`object`,void 0),ua([A()],da.prototype,`limitCount`,void 0);var fa;(function(e){e[e.PointerEnter=0]=`PointerEnter`,e[e.PointerExit=1]=`PointerExit`,e[e.PointerDown=2]=`PointerDown`,e[e.PointerUp=3]=`PointerUp`,e[e.PointerClick=4]=`PointerClick`})(fa||={});var pa=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},ma=class{eventID;callback=new k};pa([A()],ma.prototype,`eventID`,void 0),pa([A(k)],ma.prototype,`callback`,void 0);var ha=class extends R{triggers=[];invoke(e){if(this.triggers)for(let t of this.triggers)t.eventID===e&&t.callback?.invoke()}hasTrigger(e){return this.triggers?.some(t=>t.eventID===e)??!1}shouldChangeCursor(){return this.hasTrigger(fa.PointerClick)||this.hasTrigger(fa.PointerDown)||this.hasTrigger(fa.PointerUp)}onPointerClick(e){this.invoke(fa.PointerClick)}onPointerEnter(e){this.shouldChangeCursor()&&this.context.input.setCursor(`pointer`),this.invoke(fa.PointerEnter)}onPointerExit(e){this.shouldChangeCursor()&&this.context.input.unsetCursor(`pointer`),this.invoke(fa.PointerExit)}onPointerDown(e){this.invoke(fa.PointerDown)}onPointerUp(e){this.invoke(fa.PointerUp)}};pa([A(ma)],ha.prototype,`triggers`,void 0);var ga=class{constructor(e){this.writer=e,this.name=`EXT_mesh_gpu_instancing`}writeNode(e,t){if(e.constructor.name!==`InstancedMesh`)return;let r=this.writer,i=r.extensionsUsed,a={};t.extensions=t.extensions||{},t.extensions[this.name]=a;let o=new _,s=[],c=[],l=[];for(let t=0;t=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},Sa=N(`debuggltfexport`),Ca=class extends Di{sceneRoot},wa=class e extends R{binary=!0;objects=[];ext;async exportNow(t,n){Sa&&console.log(`Exporting objects as glTF`,this.objects),t||=`scene`,(!this.objects||this.objects.length<=0)&&(this.objects=[this.context.scene]);let r={binary:this.binary,pivot:e.calculateCenter(this.objects),...n},i=await this.export(this.objects,r).catch(e=>(console.error(e),!1));return i===!1?!1:(this.binary?t.endsWith(`.glb`)||(t+=`.glb`):t.endsWith(`.gltf`)||(t+=`.gltf`),this.binary?e.saveArrayBuffer(i,t):e.saveJson(i,t),!0)}async export(t,n){if(!t||t.length<=0){console.warn(`No objects set to export`);return}let r=new sn;r.register(e=>new ga(e)),r.register(e=>new ya(e)),wn(r,this.context),e.filterTopmostParent(t);let i={trs:!1,onlyVisible:!0,truncateDrawRange:!1,binary:!0,maxTextureSize:1/0,embedImages:!0,includeCustomExtensions:!0,animations:n?.animations||e.collectAnimations(t),...n},a=[],o=new y;n?.pivot&&o.position.sub(n.pivot),Sa&&console.log(`EXPORT`,t),t.forEach(e=>{e&&ba(e)&&(o.children.push(e),e.matrixAutoUpdate=!1,e.matrix.copy(e.matrixWorld),F.getComponentsInChildren(e,Vn).forEach(e=>{F.isActiveInHierarchy(e.gameObject)&&e.setInstancingEnabled(!1)}),e.traverse(e=>{if(!ba(e)){let t=e.parent;e.removeFromParent(),a.push(()=>{t&&t.add(e)})}}))});let s=new T(o);return n?.needleComponents&&(this.ext=new pn),this.ext&&(this.ext.registerExport(r),this.ext.context=s),new Promise((e,t)=>{Sa&&console.log(`Starting glTF export.`);try{r?.parse(o,t=>{c(),e(t)},e=>{c(),t(e)},i)}catch(e){console.error(e),t(e)}finally{a.forEach(e=>e()),Sa&&console.log(`Finished glTF export.`)}});function c(){t.forEach(e=>{e&&(e.matrixAutoUpdate=!0,F.getComponentsInChildren(e,Vn).forEach(e=>{F.isActiveInHierarchy(e.gameObject)&&e.setInstancingEnabled(!1)}))})}}static saveArrayBuffer(e,t){this.save(new Blob([e],{type:`application/octet-stream`}),t)}static saveJson(e,t){this.save(`data: text/json;charset=utf-8,`+encodeURIComponent(JSON.stringify(e)),t)}static save(e,t){let n=document.createElement(`a`);n.style.display=`none`,document.body.appendChild(n),typeof e==`string`?n.href=e:n.href=URL.createObjectURL(e),n.download=t,n.click(),n.remove()}static collectAnimations(e,t){t||=[];for(let n of e)n&&n.traverseVisible(e=>{e.animations&&e.animations.length>0&&t.push(...e.animations)});return t}static calculateCenter(e,t){let r=t||new n;return r.set(0,0,0),e.forEach(e=>{r.add(M(e))}),r.divideScalar(e.length),r}static filterTopmostParent(e){if(!(e.length<=0))for(let t=0;t=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},ka;(function(e){e[e.Linear=1]=`Linear`,e[e.Exponential=2]=`Exponential`,e[e.ExponentialSquared=3]=`ExponentialSquared`})(ka||={});var Aa=class extends R{get fog(){return this._fog||=new ve(0,0,50),this._fog}get mode(){return ka.Linear}set near(e){this.fog.near=e}get near(){return this.fog.near}set far(e){this.fog.far=e}get far(){return this.fog.far}set color(e){this.fog.color.copy(e)}get color(){return this.fog.color}_fog;onEnable(){this.scene.fog=this.fog}onDisable(){this.scene.fog===this._fog&&(this.scene.fog=null)}};Oa([A()],Aa.prototype,`near`,null),Oa([A()],Aa.prototype,`far`,null),Oa([A(t)],Aa.prototype,`color`,null);var ja=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},Ma=class extends R{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!Lt)return;let e=this.size,n=this.divisions;this.gridHelper||(this.gridHelper=new Ce(e,n,this.color0??new t(.4,.4,.4),this.color1??new t(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset)),this.gridHelper&&this.gameObject.add(this.gridHelper)}onDisable(){this.gridHelper&&=(this.gameObject.remove(this.gridHelper),null)}};ja([A()],Ma.prototype,`isGizmo`,void 0),ja([A(t)],Ma.prototype,`color0`,void 0),ja([A(t)],Ma.prototype,`color1`,void 0);var Na=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},Pa=class extends R{connectedBody;get rigidBody(){return this._rigidBody}_rigidBody=null;onEnable(){this._rigidBody||=this.gameObject.getComponent(E),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.activeAndEnabled&&this.createJoint(this.rigidBody,this.connectedBody)}};Na([A(E)],Pa.prototype,`connectedBody`,void 0);var Fa=class extends Pa{createJoint(e,t){this.context.physics.engine?.addFixedJoint(e,t)}},Ia=class extends Pa{anchor;axis;createJoint(e,t){this.axis&&this.anchor&&this.context.physics.engine?.addHingeJoint(e,t,this.anchor,this.axis)}};Na([A(n)],Ia.prototype,`anchor`,void 0),Na([A(n)],Ia.prototype,`axis`,void 0);var La=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a};function Ra(e){return e*Math.PI/180}var za=300,Ba=N(`debuglights`),Va;(function(e){e[e.Spot=0]=`Spot`,e[e.Directional=1]=`Directional`,e[e.Point=2]=`Point`,e[e.Area=3]=`Area`,e[e.Rectangle=3]=`Rectangle`,e[e.Disc=4]=`Disc`})(Va||={});var Ha;(function(e){e[e.Realtime=4]=`Realtime`,e[e.Baked=2]=`Baked`,e[e.Mixed=1]=`Mixed`})(Ha||={});var Ua;(function(e){e[e.None=0]=`None`,e[e.Hard=1]=`Hard`,e[e.Soft=2]=`Soft`})(Ua||={});var Y=class extends R{type=0;get range(){return this._range}set range(e){this._range=e,this.light&&(this.light.type===`SpotLight`||this.light.type===`PointLight`)&&`distance`in this.light&&(this.light.distance=e)}_range=1;get spotAngle(){return this._spotAngle}set spotAngle(e){this._spotAngle=e,this.light&&this.light.type===`SpotLight`&&`angle`in this.light&&(this.light.angle=Ra(e/2))}_spotAngle=30;get innerSpotAngle(){return this._innerSpotAngle}set innerSpotAngle(e){if(this._innerSpotAngle=e,this.light&&this.light.type===`SpotLight`&&`penumbra`in this.light){let t=this.spotAngle,n=1-Ra(e/2)/Ra(t/2);this.light.penumbra=n}}_innerSpotAngle=10;set color(e){this._color=e,this.light!==void 0&&(this.light.color=e)}get color(){return this.light?this.light.color:this._color}_color=new t(16777215);set shadowNearPlane(e){if(e!==this._shadowNearPlane&&(this._shadowNearPlane=e,this.light?.shadow?.camera!==void 0)){let t=this.light.shadow.camera;t.near=e}}get shadowNearPlane(){return this._shadowNearPlane}_shadowNearPlane=.1;set shadowBias(e){e!==this._shadowBias&&(this._shadowBias=e,this.light?.shadow?.bias!==void 0&&(this.light.shadow.bias=e,this.light.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}_shadowBias=0;set shadowNormalBias(e){e!==this._shadowNormalBias&&(this._shadowNormalBias=e,this.light?.shadow?.normalBias!==void 0&&(this.light.shadow.normalBias=e,this.light.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}_shadowNormalBias=0;_overrideShadowBiasSettings=!1;set shadows(e){this._shadows=e,this.light&&(this.light.castShadow=e!==Ua.None,this.updateShadowSoftHard())}get shadows(){return this._shadows}_shadows=1;lightmapBakeType=Ha.Realtime;set intensity(e){this._intensity=e,this.light&&(this.light.intensity=e),Ba&&console.log(`Set light intensity to `+this._intensity,e,this)}get intensity(){return this._intensity}_intensity=-1;get shadowDistance(){let e=this.light;return e?.shadow?e.shadow.camera.far:-1}set shadowDistance(e){this._shadowDistance=e;let t=this.light;if(t?.shadow){let n=t.shadow.camera;n.far=e,n.updateProjectionMatrix()}}_shadowDistance;shadowWidth;shadowHeight;get shadowResolution(){let e=this.light;return e?.shadow?e.shadow.mapSize.x:-1}set shadowResolution(e){if(e===this._shadowResolution)return;this._shadowResolution=e;let t=this.light;t?.shadow&&(t.shadow.mapSize.set(e,e),t.shadow.needsUpdate=!0)}_shadowResolution=void 0;get isBaked(){return this.lightmapBakeType===Ha.Baked}get selfIsLight(){if(this.gameObject.isLight===!0)return!0;switch(this.gameObject.type){case`SpotLight`:case`PointLight`:case`DirectionalLight`:return!0}return!1}light=void 0;getWorldPosition(e){return this.light?this.type===Va.Directional?this.light.getWorldPosition(e).multiplyScalar(1):this.light.getWorldPosition(e):e}awake(){this.color=new t(this.color??16777215),Ba&&console.log(this.name,this)}onEnable(){Ba&&console.log(`ENABLE LIGHT`,this.name),this.createLight(),!this.isBaked&&(this.light&&(this.light.visible=!0,this.light.intensity=this._intensity,Ba&&console.log(`Set light intensity to `+this.light.intensity,this.name),this.selfIsLight||this.light.parent!==this.gameObject&&this.gameObject.add(this.light)),this.type===Va.Directional&&this.startCoroutine(this.updateMainLightRoutine(),an.LateUpdate))}onDisable(){Ba&&console.log(`DISABLE LIGHT`,this.name),this.light&&(this.selfIsLight?this.light.intensity=0:this.light.visible=!1)}createLight(){let e=this.selfIsLight;if(e&&!this.light)switch(this.light=this.gameObject,this.light.name=this.name,this._intensity=this.light.intensity,this.type){case Va.Directional:this.setDirectionalLight(this.light);break}else if(!this.light)switch(this.type){case Va.Directional:let e=new ne(this.color,this.intensity*Math.PI);if(e.position.set(0,0,-za*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(e.target),kt(e.target,0,0,0),this.light=e,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Ba){let e=new f(this.light,.2,this.color);this.context.scene.add(e)}break;case Va.Spot:let t=new ce(this.color,this.intensity*Math.PI,this.range,Ra(this.spotAngle/2),1-Ra(this.innerSpotAngle/2)/Ra(this.spotAngle/2),2);t.position.set(0,0,0),t.rotation.set(0,0,0),this.light=t;let n=t.target;t.add(n),n.position.set(0,0,this.range),n.rotation.set(0,0,0);break;case Va.Point:this.light=new De(this.color,this.intensity*Math.PI,this.range);break}if(this.light){if(this._intensity>=0?this.light.intensity=this._intensity:this._intensity=this.light.intensity,this.shadows===Ua.None?this.light.castShadow=!1:this.light.castShadow=!0,this.light.shadow){this._shadowResolution!==void 0&&this._shadowResolution>4?(this.light.shadow.mapSize.width=this._shadowResolution,this.light.shadow.mapSize.height=this._shadowResolution):(this.light.shadow.mapSize.width=2048,this.light.shadow.mapSize.height=2048),Ba&&console.log(`Override shadow bias?`,this._overrideShadowBiasSettings,this.shadowBias,this.shadowNormalBias),this.light.shadow.bias=this.shadowBias,this.light.shadow.normalBias=this.shadowNormalBias,this.updateShadowSoftHard();let e=this.light.shadow.camera;if(e.near=this.shadowNearPlane,this._shadowDistance!==void 0&&typeof this._shadowDistance==`number`?e.far=this._shadowDistance:e.far=za*Math.abs(this.gameObject.scale.z),this.gameObject.scale.set(1,1,1),this.shadowWidth!==void 0)e.left=-this.shadowWidth/2,e.right=this.shadowWidth/2;else{let t=this.gameObject.scale.x;e.left*=t,e.right*=t}if(this.shadowHeight!==void 0)e.top=this.shadowHeight/2,e.bottom=-this.shadowHeight/2;else{let t=this.gameObject.scale.y;e.top*=t,e.bottom*=t}this.light.shadow.needsUpdate=!0,Ba&&this.context.scene.add(new g(e))}this.isBaked?this.light.removeFromParent():e||this.gameObject.add(this.light)}}*updateMainLightRoutine(){for(;;){this.type===Va.Directional&&((!this.context.mainLight||this.intensity>this.context.mainLight.intensity)&&(this.context.mainLight=this),yield);break}}static allowChangingRendererShadowMapType=!0;updateShadowSoftHard(){this.light&&this.light.shadow&&(this.shadows===Ua.Soft||(this.light.shadow.radius=1,this.light.shadow.blurSamples=1))}onEnterXR(e){this.applyXRScale(e.xr.rigScale)}onUpdateXR(e){this.applyXRScale(e.xr.rigScale)}onLeaveXR(e){this.applyXRScale(1)}applyXRScale(e){this.light&&(this.light.intensity=this._intensity/e,`distance`in this.light&&(this.light.distance=this._range/e))}setDirectionalLight(e){e.add(e.target),e.target.position.set(0,0,-1)}};La([A()],Y.prototype,`type`,void 0),La([A()],Y.prototype,`range`,null),La([A()],Y.prototype,`spotAngle`,null),La([A()],Y.prototype,`innerSpotAngle`,null),La([A(t)],Y.prototype,`color`,null),La([A()],Y.prototype,`shadowNearPlane`,null),La([A()],Y.prototype,`shadowBias`,null),La([A()],Y.prototype,`shadowNormalBias`,null),La([A()],Y.prototype,`shadows`,null),La([A()],Y.prototype,`lightmapBakeType`,void 0),La([A()],Y.prototype,`intensity`,null),La([A()],Y.prototype,`shadowDistance`,null),La([A()],Y.prototype,`shadowResolution`,null),new n(0,0,0);var Wa=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},Ga=N(`debuglods`),Ka=N(`nolods`),qa;(function(e){e[e.None=0]=`None`,e[e.CrossFade=1]=`CrossFade`,e[e.SpeedTree=2]=`SpeedTree`})(qa||={});var Ja=class{screenRelativeTransitionHeight;distance;renderers};Wa([A()],Ja.prototype,`screenRelativeTransitionHeight`,void 0),Wa([A()],Ja.prototype,`distance`,void 0),Wa([A(Vn)],Ja.prototype,`renderers`,void 0);var Ya=class{model;get renderers(){return this.model.renderers}constructor(e){this.model=e}},Xa=class extends R{lodModels=[];_lods=[];_settings=[];_lodsHandler;start(){if(Ga&&console.log(`LODGROUP`,this.name,this.lodModels,this),!Ka&&!this._lodsHandler&&this.gameObject&&this.lodModels&&Array.isArray(this.lodModels)){let e=[];for(let t of this.lodModels){let n=new Ya(t);this._lods.push(n);for(let t of n.renderers)e.includes(t)||e.push(t)}this._lodsHandler=[];for(let t=0;t=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},Qa=N(`debugnestedgltf`),$a=class extends R{filePath;loaded=new k;loadAssetInParent=!0;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){return this.filePath?.preload()||null}async start(){if(this._isLoadingOrDoneLoading)return;Qa&&console.log(this,this.guid);let e=this.gameObject.parent;if(e&&this.filePath){this._isLoadingOrDoneLoading=!0;let t=new nt;t.idProvider=new mt(this.hash(this.guid)),t.parent=this.loadAssetInParent===!1?this.gameObject:e,this.gameObject.updateMatrix();let n=this.gameObject.matrix;Qa&&console.log(`Load nested:`,this.filePath?.url??this.filePath,this.gameObject.position);let r=await this.filePath?.instantiate?.call(this.filePath,t);Qa&&console.log(`Nested loaded:`,this.filePath?.url??this.filePath,r),r&&this.loadAssetInParent!==!1&&(r.matrixAutoUpdate=!1,r.matrix.identity(),r.applyMatrix4(n),r.matrixAutoUpdate=!0,r.layers.disableAll(),r.layers.set(this.layer),this.loaded.invoke({component:this,instance:r,asset:this.filePath})),Qa&&console.log(`Nested loading done:`,this.filePath?.url??this.filePath,r)}}onDestroy(){this.filePath?.unload()}hash(e){let t=0;for(let n=0;n=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},to=N(`debugnet`),no=class e extends R{url=null;urlParameterName=null;localhost=null;awake(){to&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let t=this.url?e.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){let e=N(this.urlParameterName);e&&typeof e==`string`&&(t=e)}if(!t)return null;let n=RegExp(`(((https?)|(?wss?))://)?(www.)?(?.+)`,`gm`).exec(t);return n?.groups?n?.groups.socket_prefix?t:`wss://`+n?.groups.url:null}static GetUrl(t,n){let r=t,i=e.IsLocalNetwork()&&n;if(i&&(r=n),t?.startsWith(`/`)){let e=i?r:window.location.origin;e?.endsWith(`/`)&&t.startsWith(`/`)&&(t=t.substring(1)),r=e+t}return r}static IsLocalNetwork(e=window.location.hostname){return Ue(e)}};eo([A()],no.prototype,`url`,void 0),eo([A()],no.prototype,`urlParameterName`,void 0),eo([A()],no.prototype,`localhost`,void 0);var ro=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},io=class extends R{referenceSpace;from;affectPosition=!1;affectRotation=!1;alignLookDirection=!1;levelLookDirection=!1;levelPosition=!1;positionOffset=new n(0,0,0);rotationOffset=new n(0,0,0);offset=new n(0,0,0);update(){if(!this.from)return;var e=M(this.from),t=Xt(this.from);this.offset.copy(this.positionOffset);let r=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(r),e.add(this.offset),this.levelPosition&&this.referenceSpace){let t=new ae(this.gameObject.up,0),r=M(this.referenceSpace);t.setFromNormalAndCoplanarPoint(this.gameObject.up,r);let i=new n(0,0,0);t.projectPoint(e,i),e.copy(i)}this.affectPosition&&Oe(this.gameObject,e);let i=new be(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),a=new x().setFromEuler(i);this.affectRotation&&Ye(this.gameObject,t.multiply(a));let o=new n;this.from.getWorldDirection(o).multiplyScalar(50),this.levelLookDirection&&(o.y=0),this.alignLookDirection&&this.gameObject.lookAt(o)}};ro([A(F)],io.prototype,`referenceSpace`,void 0),ro([A(F)],io.prototype,`from`,void 0),ro([A(n)],io.prototype,`positionOffset`,void 0),ro([A(n)],io.prototype,`rotationOffset`,void 0);var ao=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},oo=class extends R{strength=1;radius=2;targets=[];update(){let e=this.gameObject.worldPosition,t=-this.strength*this.context.time.deltaTime;this.targets?.forEach(n=>{if(!n)return;let r=n.gameObject.worldPosition.sub(e),i=r.length();if(i>this.radius)return;let a=t;i>1?a/=i*i:a/=Math.max(.05,i),n.applyImpulse(r.multiplyScalar(a))})}};ao([A()],oo.prototype,`strength`,void 0),ao([A()],oo.prototype,`radius`,void 0),ao([A(E)],oo.prototype,`targets`,void 0);var so=class e extends R{_didAssignPlayerColor=!1;onEnable(){this.context.connection.beginListen(P.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(P.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield Ke(.2),!this.tryAssignColor()););}tryAssignColor=()=>{let e=F.getComponentInParent(this.gameObject,qn);if(e&&e.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(e.owner),!0;let t=F.getComponentInParent(this.gameObject,Yn);return t?.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(t.connectionId),!0):!1};assignUserColor(t){let n=e.hashCode(t),r=e.colorFromHashCode(n);if(this.gameObject.type===`Mesh`){let e=this.gameObject;this.assignColor(r,t,e)}else if(this.gameObject.children)for(let e of this.gameObject.children){let n=e;n.material&&n.material.color&&this.assignColor(r,t,n)}}assignColor(e,t,n){let r=n.material;r&&(r._playerMaterial!==t&&(r=r.clone(),r._playerMaterial=t,n.material=r),r.color=e)}static hashCode(e){var t=0,n,r;if(e.length===0)return t;for(n=0;n>16,r=(e&65280)>>8,i=e&255;return new t(n/255,r/255,i/255)}};function co(){return new Promise((e,t)=>{let n=()=>{n!=null&&(document.removeEventListener(`pointerdown`,n),document.removeEventListener(`click`,n),document.removeEventListener(`dragstart`,n),document.removeEventListener(`touchstart`,n),e())};document.addEventListener(`pointerdown`,n),document.addEventListener(`click`,n),document.addEventListener(`dragstart`,n),document.addEventListener(`touchstart`,n)})}async function lo(e){await co(),e()}var uo=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},X=N(`debugvideo`),fo;(function(e){e[e.None=0]=`None`,e[e.AdjustHeight=1]=`AdjustHeight`,e[e.AdjustWidth=2]=`AdjustWidth`})(fo||={});var po;(function(e){e[e.VideoClip=0]=`VideoClip`,e[e.Url=1]=`Url`})(po||={});var mo;(function(e){e[e.None=0]=`None`,e[e.AudioSource=1]=`AudioSource`,e[e.Direct=2]=`Direct`,e[e.APIOnly=3]=`APIOnly`})(mo||={});var ho;(function(e){e[e.CameraFarPlane=0]=`CameraFarPlane`,e[e.CameraNearPlane=1]=`CameraNearPlane`,e[e.RenderTexture=2]=`RenderTexture`,e[e.MaterialOverride=3]=`MaterialOverride`})(ho||={});var Z=class extends R{playOnAwake=!0;aspectMode=fo.None;clip=null;source=po.Url;get url(){return this._url}set url(e){let t=this._url!==e;this.__didAwake?t&&this.setClipURL(e??``):this._url=e}_url=null;renderMode=ho.MaterialOverride;targetMaterialProperty;targetMaterialRenderer;targetTexture;time=0;_playbackSpeed=1;get playbackSpeed(){return this._videoElement?.playbackRate??this._playbackSpeed}set playbackSpeed(e){this._playbackSpeed=e,this._videoElement&&(this._videoElement.playbackRate=e)}_isLooping=!1;get isLooping(){return this._videoElement?.loop??this._isLooping}set isLooping(e){this._isLooping=e,this._videoElement&&(this._videoElement.loop=e)}get currentTime(){return this._videoElement?.currentTime??this.time}set currentTime(e){this._videoElement?this._videoElement.currentTime=e:this.time=e}get isPlaying(){let e=this._videoElement;return!!(e&&(e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>e.HAVE_CURRENT_DATA||e.srcObject&&e.srcObject.active))}get crossOrigin(){return this._videoElement?.crossOrigin??this._crossOrigin}set crossOrigin(e){this._crossOrigin=e,this._videoElement&&(e===null?this._videoElement.removeAttribute(`crossorigin`):this._videoElement.setAttribute(`crossorigin`,e))}get videoMaterial(){return!this._videoMaterial&&!this.create(!1)?null:this._videoMaterial}get videoTexture(){return!this._videoTexture&&!this.create(!1)?null:this._videoTexture}get videoElement(){return!this._videoElement&&!this.create(!1)?null:this._videoElement}requestPictureInPicture(){return this._videoElement?this._videoElement.requestPictureInPicture():null}get muted(){return this._videoElement?.muted??this._muted}set muted(e){this._muted=e,this._videoElement&&(this._videoElement.muted=e)}_muted=!1;get currentVideo(){return this.clip}set audioOutputMode(e){e!==this._audioOutputMode&&(e===mo.AudioSource&&w()&&console.warn(`VideoAudioOutputMode.AudioSource is not yet implemented`),this._audioOutputMode=e,this.updateVideoElementSettings())}get audioOutputMode(){return this._audioOutputMode}_audioOutputMode=mo.Direct;playInBackground=!0;_crossOrigin=`anonymous`;_videoElement=null;_videoTexture=null;_videoMaterial=null;_isPlaying=!1;wasPlaying=!1;preloadVideo(){X&&console.log(`Video Preload: `+this.name,this.clip),this.create(!1)}preload(){this.preloadVideo()}setVideo(e){this.clip=e,this.source=po.VideoClip,this._videoElement?(this._videoElement.srcObject=e,this._isPlaying&&this.play(),this.updateAspect()):this.create(this.playOnAwake)}setClipURL(e){this._url!==e&&(this._url=e,this.source=po.Url,X&&console.log(`set url`,e),this._videoElement?e.endsWith(`.m3u8`)||e.includes(`.m3u`)?this.ensureM3UCanBePlayed():(this._videoElement.src=e,this._isPlaying&&(this.stop(),this.play())):this.create(this.playOnAwake))}onEnable(){X&&console.log(`VideoPlayer.onEnable`,po[this.source],this.clip,this.url,this),window.addEventListener(`visibilitychange`,this.visibilityChanged),this.playOnAwake===!0?this.create(!0):this.preloadVideo(),this.screenspace?this._overlay?.start():this._overlay?.stop()}onDisable(){window.removeEventListener(`visibilitychange`,this.visibilityChanged),this._overlay?.stop(),this.pause()}visibilityChanged=e=>{switch(document.visibilityState){case`hidden`:this.playInBackground||(this.wasPlaying=this._isPlaying,this.pause());break;case`visible`:this.wasPlaying&&!this._isPlaying&&this.play();break}};onDestroy(){this._videoElement&&=(this.videoElement?.remove(),null),this._videoTexture&&=(this._videoTexture.dispose(),null)}_receivedInput=!1;constructor(){super(),lo(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[],N(`videoscreenspace`)&&window.addEventListener(`keydown`,e=>{e.key===`f`&&(this.screenspace=!this.screenspace)})}_playErrors=0;play(){if(this._videoElement||this.create(!1),!this._videoElement){X&&console.warn(`Can not play: no video element found`,this);return}if(!(this._isPlaying&&!this._videoElement?.ended&&!this._videoElement?.paused)){if(this._isPlaying=!0,this._receivedInput||(this._videoElement.muted=!0),this.handleBeginPlaying(!1),this.shouldUseM3U){this.ensureM3UCanBePlayed();return}X&&console.log(`Video Play()`,this.clip,this._videoElement,this.time),this._videoElement.currentTime=this.time,this._videoElement.play().catch(e=>{this._playErrors++<10?console.error(e):this._playErrors===10&&console.error(`Multiple errors playing video, further errors will be suppressed. Use 'debugvideo' param to see all errors.`),X&&console.error(`Error playing video`,e,`CODE=`+e.code,this.videoElement?.src,this),setTimeout(()=>{this._isPlaying&&!this.destroyed&&this.activeAndEnabled&&this.play()},1e3)}),X&&console.log(`play`,this._videoElement,this.time)}}stop(){this._isPlaying=!1,this.time=0,this._videoElement&&(this._videoElement.currentTime=0,this._videoElement.pause(),X&&console.log(`STOP`,this))}pause(){this.time=this._videoElement?.currentTime??0,this._isPlaying=!1,this._videoElement?.pause(),X&&console.log(`PAUSE`,this,this.currentTime)}create(e){let t;switch(this.source){case po.VideoClip:t=this.clip;break;case po.Url:t=this.url,!t?.length&&typeof this.clip==`string`&&(t=this.clip);break}return t?(this._videoElement||(X&&console.warn(`Create VideoElement`,this),this._videoElement=this.createVideoElement(),this.context.domElement.shadowRoot.prepend(this._videoElement),this.updateVideoElementStyles()),typeof t==`string`?(X&&console.log(`Set Video src`,t),this._videoElement.src=t):(X&&console.log(`Set Video srcObject`,t),this._videoElement.srcObject=t),this._videoTexture||=new l(this._videoElement),this._videoTexture.flipY=!1,this._videoTexture.colorSpace=re,e&&this.handleBeginPlaying(e),X&&console.log(`Video: handle playing done...`,t,e),!0):(X&&console.warn(`No video source set`,this),!1)}updateAspect(){this.aspectMode!==fo.None&&this.startCoroutine(this.updateAspectImpl())}_overlay=null;get screenspace(){return this._overlay?.enabled??!1}set screenspace(e){if(e){if(!this._videoTexture)return;this._overlay||=new go(this.context),this._overlay.add(this._videoTexture)}else this._overlay?.remove(this._videoTexture);this._overlay&&(this._overlay.enabled=e)}_targetObjects;createVideoElement(){let e=document.createElement(`video`);return this._crossOrigin&&e.setAttribute(`crossorigin`,this._crossOrigin),X&&console.log(`created video element`,e),e}handleBeginPlaying(e){if(!this.activeAndEnabled||!this._videoElement)return;this._targetObjects.length=0;let t=this.gameObject;switch(this.renderMode){case ho.MaterialOverride:t=this.targetMaterialRenderer?.gameObject,t||=F.getComponent(this.gameObject,Vn)?.gameObject;break;case ho.RenderTexture:console.error(`VideoPlayer renderTexture not implemented yet. Please use material override instead`);return}if(!t){console.error(`Missing target for video material renderer`,this.name,ho[this.renderMode],this);return}let n=t.material;if(n){this._targetObjects.push(t),n!==this._videoMaterial&&(this._videoMaterial=n.clone(),t.material=this._videoMaterial);let e=this._videoMaterial;if(!this.targetMaterialProperty)X&&e.map===void 0&&console.warn(`The target material does not have a 'map' property, video might not render correctly.`),e.map=this._videoTexture;else switch(this.targetMaterialProperty){default:X&&e[this.targetMaterialProperty]===void 0&&console.warn(`The target material does not have a '${this.targetMaterialProperty}' property, video might not render correctly.`),e.map=this._videoTexture;break}}else{console.warn(`Can not play video, no material found, this might be a multimaterial case which is not supported yet`);return}this.updateVideoElementSettings(),this.updateVideoElementStyles(),e&&(this.shouldUseM3U&&this.ensureM3UCanBePlayed(),this.play())}updateVideoElementSettings(){if(!this._videoElement)return;this._videoElement.loop=this._isLooping,this._videoElement.currentTime=this.currentTime,this._videoElement.playbackRate=this._playbackSpeed,this._videoElement.playsInline=!0;let e=!this._receivedInput||this.audioOutputMode===mo.None;!e&&this._muted&&(e=!0),this._videoElement.muted=e,this.playOnAwake&&(this._videoElement.autoplay=!0)}updateVideoElementStyles(){this._videoElement&&(this._videoElement.style.userSelect=`none`,this._videoElement.style.visibility=`hidden`,this._videoElement.style.display=`none`,this.updateAspect())}_updateAspectRoutineId=-1;*updateAspectImpl(){let e=++this._updateAspectRoutineId,t=this.clip;for(;e===this._updateAspectRoutineId&&this.aspectMode!==fo.None&&this.clip&&t===this.clip&&this._isPlaying;){if(!t||typeof t==`string`)return;let e;for(let n of t.getVideoTracks()){let t=n.getSettings();if(t&&t.width&&t.height){e=t.width/t.height;break}else e=this.context.renderer.domElement.clientWidth/this.context.renderer.domElement.clientHeight}if(e===void 0){for(let e=0;e<10;e++)yield;if(!this.isPlaying)break;continue}if(e===void 0){yield;continue}for(let t of this._targetObjects){let n=1;if(t.parent){let e=_t(t.parent);n=e.x/e.y}switch(this.aspectMode){case fo.AdjustHeight:t.scale.y=1/e*t.scale.x*n;break;case fo.AdjustWidth:t.scale.x=e*t.scale.y*n;break}}for(let e=0;e<3;e++)yield}}get shouldUseM3U(){return this.url!=null&&(this.url.endsWith(`.m3u8`)||this.url.endsWith(`.m3u`))&&this.source===po.Url}ensureM3UCanBePlayed(){if(!this.shouldUseM3U)return;let e=document.head.querySelector(`script[data-hls_library]`);e?globalThis.Hls?this.onHlsAvailable():e.addEventListener(`load`,this.onHlsAvailable):(X&&console.log(`HLS: load script`),e=document.createElement(`script`),e.dataset.hls_library=`hls.js`,e.src=`https://cdn.jsdelivr.net/npm/hls.js@1`,e.addEventListener(`load`,this.onHlsAvailable),document.head.append(e))}_hls;onHlsAvailable=()=>{X&&console.log(`HLS: available`,this.clip),!(!this.shouldUseM3U||!this.url)&&(this._hls||=new Hls,this.videoElement.autoplay=!0,this._hls.loadSource(this.url),this._hls.attachMedia(this.videoElement),this._videoElement?.play(),X&&console.log(`HLS: loaded`,this.clip))}};uo([A()],Z.prototype,`playOnAwake`,void 0),uo([A()],Z.prototype,`aspectMode`,void 0),uo([A(URL)],Z.prototype,`clip`,void 0),uo([A()],Z.prototype,`source`,void 0),uo([A(URL)],Z.prototype,`url`,null),uo([A()],Z.prototype,`renderMode`,void 0),uo([A()],Z.prototype,`targetMaterialProperty`,void 0),uo([A(Vn)],Z.prototype,`targetMaterialRenderer`,void 0),uo([A(ue)],Z.prototype,`targetTexture`,void 0),uo([A()],Z.prototype,`time`,void 0),uo([A()],Z.prototype,`playbackSpeed`,null),uo([A()],Z.prototype,`isLooping`,null),uo([A()],Z.prototype,`audioOutputMode`,null);var go=class{context;constructor(e){this.context=e,this._input=new _o(this)}get enabled(){return this._isInScreenspaceMode}set enabled(e){e?this.start():this.stop()}add(e){this._videos.indexOf(e)===-1&&this._videos.push(e)}remove(e){if(!e)return;let t=this._videos.indexOf(e);t>=0&&this._videos.splice(t,1)}start(){if(this._isInScreenspaceMode||this._videos.length<0)return;let e=this._videos[this._videos.length-1];if(!e)return;if(this._isInScreenspaceMode=!0,!this._screenspaceModeQuad){if(this._screenspaceModeQuad=Ze.createPrimitive(et.Quad,{material:new vo(e)}),!this._screenspaceModeQuad)return;this._screenspaceModeQuad.geometry.scale(2,2,2)}let t=this._screenspaceModeQuad;this.context.scene.add(t),this.updateScreenspaceMaterialUniforms();let n=t.material;n?.reset(),this._input?.enable(n)}stop(){this._isInScreenspaceMode=!1,this._screenspaceModeQuad&&(this._input?.disable(),this._screenspaceModeQuad.removeFromParent())}updateScreenspaceMaterialUniforms(){let e=this._screenspaceModeQuad?.material;e&&(e.screenAspect=this.context.domElement.clientWidth/this.context.domElement.clientHeight)}_videos=[];_screenspaceModeQuad;_isInScreenspaceMode=!1;_input},_o=class{_onResizeScreenFn;_onKeyUpFn;_onMouseWheelFn;context;overlay;constructor(e){this.overlay=e,this.context=e.context}_material;enable(e){this._material=e,window.addEventListener(`resize`,this._onResizeScreenFn=()=>{this.overlay.updateScreenspaceMaterialUniforms()}),window.addEventListener(`keyup`,this._onKeyUpFn=e=>{e.key===`Escape`&&this.overlay.stop()}),window.addEventListener(`wheel`,this._onMouseWheelFn=t=>{this.overlay.enabled&&(e.zoom+=t.deltaY*5e-4,t.preventDefault())},{passive:!1});let t=new b;window.addEventListener(`mousemove`,n=>{if(this.overlay.enabled&&this.context.input.getPointerPressed(0)){let r=new b(n.movementX,n.movementY);r.x/=this.context.domElement.clientWidth,r.y/=this.context.domElement.clientHeight,t.set(r.x,r.y),t.multiplyScalar(e.zoom/-this.context.time.deltaTime*.01),e.offset=e.offset.add(t)}}),window.addEventListener(`pointermove`,n=>{this.overlay.enabled&&this.context.input.getPointerPressed(0)&&this.context.input.getTouchesPressedCount()===1&&(t.set(n.movementX,n.movementY),t.multiplyScalar(e.zoom*-this.context.time.deltaTime*.05),e.offset=e.offset.add(t))});let n=0;window.addEventListener(`touchstart`,e=>{if(e.touches.length<2){this.context.time.time-n<.3&&this.overlay.stop(),n=this.context.time.time;return}this._isPinching=!0,this._lastPinch=0}),window.addEventListener(`touchmove`,e=>{if(!this._isPinching||!this._material)return;let t=e.touches[0],n=e.touches[1],r=t.clientX-n.clientX,i=t.clientY-n.clientY,a=Math.sqrt(r*r+i*i);if(this._lastPinch!==0){let e=a-this._lastPinch;this._material.zoom-=e*.004}this._lastPinch=a}),window.addEventListener(`touchend`,()=>{this._isPinching=!1})}_isPinching=!1;_lastPinch=0;disable(){this._onResizeScreenFn&&=(window.removeEventListener(`resize`,this._onResizeScreenFn),void 0),this._onKeyUpFn&&=(window.removeEventListener(`keyup`,this._onKeyUpFn),void 0),this._onMouseWheelFn&&=(window.removeEventListener(`wheel`,this._onMouseWheelFn),void 0)}},vo=class extends ye{set screenAspect(e){this.uniforms.screenAspect.value=e,this.needsUpdate=!0}set offset(e){let t=this.uniforms.offsetScale.value;t.x=e.x,t.y=e.y,this.uniforms.offsetScale.value=t,this.needsUpdate=!0}_offset=new b;get offset(){let e=this.uniforms.offsetScale.value;return this._offset.set(e.x,e.y),this._offset}set zoom(e){let t=this.uniforms.offsetScale.value;e<.001&&(e=.001),t.z=e,this.needsUpdate=!0}get zoom(){return this.uniforms.offsetScale.value.z}reset(){this.offset=this.offset.set(0,0),this.zoom=1,this.needsUpdate=!0}constructor(e){super(),this.uniforms={map:{value:e},screenAspect:{value:1},offsetScale:{value:new pe(0,0,1,1)}},this.vertexShader=` uniform sampler2D map; uniform float screenAspect; uniform vec4 offsetScale; varying vec2 vUv; void main() { gl_Position = vec4( position , 1.0 ); vUv = uv; vUv.y = 1. - vUv.y; // fit into screen ivec2 res = textureSize(map, 0); float videoAspect = float(res.x) / float(res.y); float aspect = videoAspect / screenAspect; if(aspect >= 1.0) { vUv.y = vUv.y * aspect; float offset = (1. - aspect) * .5; vUv.y = vUv.y + offset; } else { vUv.x = vUv.x / aspect; float offset = (1. - 1. / aspect) * .5; vUv.x = vUv.x + offset; } vUv.x -= .5; vUv.y -= .5; vUv.x *= offsetScale.z; vUv.y *= offsetScale.z; vUv.x += offsetScale.x; vUv.y += offsetScale.y; vUv.x += .5; vUv.y += .5; } `,this.fragmentShader=` uniform sampler2D map; varying vec2 vUv; void main() { if(vUv.x < 0. || vUv.x > 1. || vUv.y < 0. || vUv.y > 1.) gl_FragColor = vec4(0., 0., 0., 1.); else { vec4 texcolor = texture2D(map, vUv); gl_FragColor = texcolor; } } `}},yo=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},Q=N(`debugscreensharing`),bo;(function(e){e[e.Screen=0]=`Screen`,e[e.Camera=1]=`Camera`,e[e.Canvas=2]=`Canvas`,e[e.Microphone=3]=`Microphone`})(bo||={});var xo;(function(e){e[e.Idle=0]=`Idle`,e[e.Sending=1]=`Sending`,e[e.Receiving=2]=`Receiving`})(xo||={});var So=class extends R{allowStartOnClick=!0;onPointerEnter(){this.context.connection.allowEditing!=0&&this.allowStartOnClick&&this.context.input.setCursor(`pointer`)}onPointerExit(){this.context.connection.allowEditing!=0&&this.allowStartOnClick&&this.context.input.unsetCursor(`pointer`)}onPointerClick(e){if(this.context.connection.allowEditing!=0&&this.allowStartOnClick&&!(e&&e.pointerId!==0)){if(this.isReceiving&&this.videoPlayer?.isPlaying){this.videoPlayer&&(this.videoPlayer.screenspace=!this.videoPlayer.screenspace);return}if(this.isSending){this.close();return}this.share()}}autoConnect=!1;set videoPlayer(e){this._videoPlayer&&(this.isSending||this.isReceiving)&&this._videoPlayer.stop(),this._videoPlayer=e,this._videoPlayer&&this._currentStream&&(this.isSending||this.isReceiving)&&this._videoPlayer.setVideo(this._currentStream)}get videoPlayer(){return this._videoPlayer}_videoPlayer;_audioSource;get screenspace(){return this.videoPlayer?.screenspace??!1}set screenspace(e){this.videoPlayer&&(this.videoPlayer.screenspace=e)}device=`Screen`;deviceName;deviceFilter;get currentScream(){return this._currentStream}get currentMode(){return this._currentMode}get isSending(){return this._currentStream?.active&&this._currentMode===xo.Sending}get isReceiving(){if(this._currentMode===xo.Receiving){if(!this._currentStream||this._currentStream.active===!1)return!1;let e=this._currentStream.getTracks();for(let t of e)if(t.readyState===`live`)return!0}return!1}get requiresVideoPlayer(){return this.device!==`Microphone`}_net;_requestOpen=!1;_currentStream=null;_currentMode=xo.Idle;awake(){typeof this.device==`number`&&(this.device=bo[this.device]),Q&&console.log(`Screensharing`,this.name,this),Kn.registerWaitForAllowAudio(()=>{this._videoPlayer&&this._currentStream&&this._currentMode===xo.Receiving&&(this._videoPlayer.playInBackground=!0,this._videoPlayer.setVideo(this._currentStream))}),this._net=new er(this)}onEnable(){this._net?.enable(),this._net?.addEventListener(dr.StreamReceived,this.onReceiveStream),this._net?.addEventListener(dr.StreamEnded,this.onCallEnded),this.context.connection.beginListen(P.JoinedRoom,this.onJoinedRoom),this.autoConnect&&zt(1e3).then(()=>(this.enabled&&this.autoConnect&&!this.isReceiving&&!this.isSending&&this.context.connection.isInRoom&&this.share(),0))}onDisable(){this._net?.removeEventListener(dr.StreamReceived,this.onReceiveStream),this._net?.removeEventListener(dr.StreamEnded,this.onCallEnded),this.context.connection.stopListen(P.JoinedRoom,this.onJoinedRoom),this._net?.disable(),this.close()}onJoinedRoom=async()=>{await zt(1e3),this.autoConnect&&!this.isSending&&!this.isReceiving&&this.context.connection.isInRoom&&this.share()};_ensureVideoPlayer(){let e=new Z;e.aspectMode=fo.AdjustWidth,F.addComponent(this.gameObject,e),this._videoPlayer=e}_activeShareRequest=null;async share(e){return this._activeShareRequest?this._activeShareRequest:(this._activeShareRequest=this.internalShare(e),this._activeShareRequest.then(()=>this._activeShareRequest=null))}async internalShare(e){if(this.context.connection.isInRoom===!1){console.warn(`Can not start screensharing: requires network connection`),w()&&Ht(`Can not start screensharing: requires network connection. Add a SyncedRoom component or join a room first.`);return}if(e?.device&&(this.device=e.device),!this.videoPlayer&&this.requiresVideoPlayer&&(this._videoPlayer||=F.getComponent(this.gameObject,Z)??void 0,this.videoPlayer||this._ensureVideoPlayer(),!this.videoPlayer)){console.warn(`Can not share video without a videoPlayer assigned`);return}this._requestOpen=!0;try{let t=e?.constraints??{echoCancellation:!0,autoGainControl:!1},n={video:t,audio:t},r=n.video;switch(r!==void 0&&typeof r!=`boolean`&&(r.width||={max:1920},r.height||={max:1920},r.aspectRatio||={ideal:1.7777777778},r.frameRate||={ideal:24},r.facingMode||={ideal:`user`}),this.device){case`Camera`:this.tryShareUserCamera(n,e);break;case`Screen`:{if(!navigator.mediaDevices.getDisplayMedia){console.error(`No getDisplayMedia support`);return}let e=await navigator.mediaDevices.getDisplayMedia(n);this._requestOpen?this.setStream(e,xo.Sending):nr(e)}break;case`Canvas`:let t=this.context.renderer.domElement.captureStream(0);this.setStream(t,xo.Sending);break;case`Microphone`:{if(!navigator.mediaDevices.getUserMedia){console.error(`No getDisplayMedia support`);return}n.video=!1;let e=await navigator.mediaDevices.getUserMedia(n);this._requestOpen?this.setStream(e,xo.Sending):nr(e)}break;default:console.error(`Can not start screen sharing: Unknown device type`,this.device)}}catch(e){if(e.name===`NotAllowedError`){console.log(`Selection cancelled`),this._requestOpen=!1;return}console.error(`Error opening video`,e)}}close(){this._requestOpen=!1,this._currentStream&&=(Q&&console.warn(`Close current stream / disposing resources, stream was active?`,this._currentStream.active),this._net?.stopSendingStream(this._currentStream),nr(this._currentStream),this._currentMode=xo.Idle,null)}setStream(e,t){if(e===this._currentStream||(this.close(),!e))return;this._currentStream=e,this._requestOpen=!0,this._currentMode=t;let n=this.device!==`Microphone`,r=t===xo.Sending;n?(this._videoPlayer||this._ensureVideoPlayer(),this._videoPlayer?this._videoPlayer.setVideo(e):console.error(`No video player assigned for video stream`)):(this._audioSource||(this._audioSource=new Kn,this._audioSource.spatialBlend=0,this._audioSource.volume=1,this.gameObject.addComponent(this._audioSource)),r||(Q&&console.log(`PLAY`,e.getAudioTracks()),this._audioSource.volume=1,this._audioSource?.play(e))),r&&this._net?.startSendingStream(e),r&&(this._videoPlayer&&(this._videoPlayer.muted=!0),this._audioSource?.stop());for(let t of e.getTracks())t.addEventListener(`ended`,()=>{Q&&console.log(`Track ended`,t),this.close()}),Q&&t.kind===`video`&&console.log(r?`Video →`:`Video ←`,t.getSettings())}onReceiveStream=e=>{e.stream?.active===!0&&this.setStream(e.stream,xo.Receiving)};onCallEnded=e=>{Q&&console.log(`CALL ENDED`,this.isReceiving,this?.screenspace),this.isReceiving&&(this.screenspace=!1)};async tryShareUserCamera(e,t){let n=(await navigator.mediaDevices.enumerateDevices()).filter(e=>e.kind===`videoinput`);Q&&console.log(`Request camera. These are your kind:videoinput devices: `,n);let r=!1;for(let i of n)try{if(!this._requestOpen){Q&&console.log(`Camera selection cancelled`);break}if(i.kind!==`videoinput`){Q&&console.log(`Skipping non-video device`,i);continue}let n=i.deviceId;if(t?.deviceId!=null||t?.deviceFilter!=null){if(t?.deviceId!==void 0&&n!==t.deviceId){Q&&console.log(`Skipping device due to options.deviceId: `+i.label+`; `+i.deviceId);continue}if(t?.deviceFilter&&t.deviceFilter(i)===!1){Q&&console.log(`Skipping device due to options.deviceFilter: `+i.label+`; `+i.deviceId);continue}}else if(this.deviceFilter)if(this.deviceFilter(i)===!1){Q&&console.log(`Skipping device due to ScreenShare.deviceFilter: `+i.label+`; `+i.deviceId);continue}else Q&&console.log(`Selected device by filter`,i);else if(this.deviceName){let e=i.label.toLowerCase(),t=this.deviceName.toLowerCase(),n=e.includes(t),r=i.deviceId===this.deviceName;if(!n&&!r){Q&&console.log(`Skipping device due to ScreenShare.deviceName: `+i.label+`; `+i.deviceId);continue}else Q&&console.log(`Selected device by name`,i)}e.video!==!1&&((e.video===void 0||typeof e.video==`boolean`)&&(e.video={}),e.video.deviceId=n),r=!0;let a=await navigator.mediaDevices.getUserMedia(e).catch(e=>(console.error(`Failed to get user media`,e),null));if(a===null)continue;this._requestOpen?(this.setStream(a,xo.Sending),Q&&console.log(`Selected camera`,i)):(nr(a),Q&&console.log(`Camera selection cancelled`));break}catch(e){if(e.message===`Failed to allocate videosource`||e.message===`Could not start video source`){Ht(`Failed to start video: Try another camera (Code `+e.code+`)`),console.warn(e);continue}else console.error(`Failed to get user media`,e.message,e.code,e)}!r&&w()&&(Ht(`No camera found for sharing. Please connect a camera (see console for more information)`),console.warn(`No camera found for sharing. Please connect a camera`,n,this.deviceName,`Using deviceFilter? `+this.deviceFilter!=null,`Using options? `+t!=null,`Using deviceName? `+this.deviceName!=null,`Using options.deviceId? `+t?.deviceId!=null,`Using options.deviceFilter? `+t?.deviceFilter!=null))}};yo([A()],So.prototype,`allowStartOnClick`,void 0),yo([A()],So.prototype,`autoConnect`,void 0),yo([A(Z)],So.prototype,`videoPlayer`,null),yo([A()],So.prototype,`device`,void 0),yo([A()],So.prototype,`deviceName`,void 0);var Co=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},wo=N(`debugseethrough`),To=0,Eo=class extends R{referencePoint=null;fadeDuration=.05;minAlpha=0;useAlphaHash=!0;set needsUpdate(e){this._needsUpdate=e}get needsUpdate(){return this._needsUpdate}overrideAlpha=-1;autoUpdate=!0;_referencePointVector=new n;_referencePointDir=new n;_distance=0;_renderer=null;_needsUpdate=!0;_id=To++;onEnable(){this._needsUpdate=!0,this._renderer=null}onDisable(){}update(){if(this._needsUpdate?(this._needsUpdate=!1,this._renderer=this.gameObject.getComponentsInChildren(Vn),this.updateDirection()):this.autoUpdate&&(this.context.time.frame+this._id)%20==0&&this.updateDirection(),!this.autoUpdate||!this.referencePoint)return;let e=this._referencePointDir.dot(this.context.mainCamera.worldForward)>.2;if(wo&&this.referencePoint){let t=this.gameObject.worldPosition;V.DrawArrow(z(t),t.sub(this._referencePointDir),e?16711680:65280),V.DrawWireSphere(this.referencePoint.worldPosition,.05,255)}e?this.updateAlpha(this.minAlpha,this.fadeDuration):this.updateAlpha(1,this.fadeDuration)}updateDirection(){this.referencePoint??=this.context.scene,this._referencePointVector.copy(this.gameObject.worldPosition.sub(this.referencePoint.worldPosition)),this._distance=this._referencePointVector.length(),this._referencePointDir.copy(this._referencePointVector).multiply(z(1,.5,1)).normalize()}updateAlpha(e,t=this.fadeDuration){this.overrideAlpha!==void 0&&this.overrideAlpha!==-1&&(e=this.overrideAlpha),this._renderer?.forEach(n=>{e<.9?n.gameObject.raycastAllowed=!1:n.gameObject.raycastAllowed=!0;let r=n.sharedMaterials;if(!r)return;let i=Sn.get(n.gameObject),a=i.getOverride(`opacity`)?.value??r[0].opacity??1,o=O.lerp(a,e,t<=0?1:this.context.time.deltaTime/t);o>=.99?o=1:o<=.01&&(o=0),i.setOverride(`alphaHash`,this.useAlphaHash),i.setOverride(`opacity`,o),i.setOverride(`transparent`,o>=.99999?!1:!this.useAlphaHash)})}};Co([A(y)],Eo.prototype,`referencePoint`,void 0),Co([A()],Eo.prototype,`fadeDuration`,void 0),Co([A()],Eo.prototype,`minAlpha`,void 0),Co([A()],Eo.prototype,`useAlphaHash`,void 0),Co([A()],Eo.prototype,`overrideAlpha`,void 0),Co([A()],Eo.prototype,`autoUpdate`,void 0);var Do=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},Oo;(function(e){e[e.ShadowMask=0]=`ShadowMask`,e[e.Additive=1]=`Additive`,e[e.Occluder=2]=`Occluder`})(Oo||={});var ko=class extends R{mode=Oo.ShadowMask;shadowColor=new vt(0,0,0,1);targetMesh;start(){if(this.gameObject instanceof v)this.gameObject instanceof v&&this.gameObject.material&&(this.gameObject.material=this.gameObject.material.clone(),this.targetMesh=this.gameObject,this.targetMesh.receiveShadow=!0);else{let e=Ze.createPrimitive(et.Quad,{name:`ShadowCatcher`,material:new fe({color:10066329,roughness:1,metalness:0,transparent:!0})});e.receiveShadow=!0,e.geometry.rotateX(-Math.PI/2),this.gameObject.add(e),this.targetMesh=e}if(!this.targetMesh){console.warn(`ShadowCatcher: no mesh to apply shadow catching to. Groups are currently not supported.`);return}switch(this.targetMesh.layers.set(2),this.mode){case Oo.ShadowMask:this.applyShadowMaterial();break;case Oo.Additive:this.applyLightBlendMaterial();break;case Oo.Occluder:this.applyOccluderMaterial();break}}applyLightBlendMaterial(){if(!this.targetMesh)return;let e=this.targetMesh.material;e.blending=2,this.applyMaterialOptions(e),e.onBeforeCompile=e=>{e.fragmentShader=e.fragmentShader.replace(`vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;`,`vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; // diffuse-only lighting with overdrive to somewhat compensate // for the loss of indirect lighting and to make it more visible. vec3 direct = (reflectedLight.directDiffuse + reflectedLight.directSpecular) * 6.6; float max = max(direct.r, max(direct.g, direct.b)); // early out - we're simply returning direct lighting and some alpha based on it so it can // be blended onto the scene. gl_FragColor = vec4(direct, max); return; `)},e.userData.isLightBlendMaterial=!0}applyShadowMaterial(){if(this.targetMesh)if(this.targetMesh.material.type!==`ShadowMaterial`){let e=new ge;e.color=this.shadowColor,e.opacity=this.shadowColor.alpha,this.applyMaterialOptions(e),this.targetMesh.material=e,e.userData.isShadowCatcherMaterial=!0}else{let e=this.targetMesh.material;e.color=this.shadowColor,e.opacity=this.shadowColor.alpha,this.applyMaterialOptions(e),e.userData.isShadowCatcherMaterial=!0}}applyOccluderMaterial(){if(this.targetMesh){let e=this.targetMesh.material;if(!e){let t=new m;this.targetMesh.material=t,e=t}e.depthWrite=!0,e.stencilWrite=!0,e.colorWrite=!1,this.gameObject.renderOrder=-100}}applyMaterialOptions(e){e&&(e.depthWrite=!1,e.stencilWrite=!1)}};Do([A()],ko.prototype,`mode`,void 0),Do([A(vt)],ko.prototype,`shadowColor`,void 0);var Ao=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},jo=class e extends R{target=null;followFactor=.1;rotateFactor=.1;positionAxes=je.All;flipForward=!1;static _invertForward=new x().setFromAxisAngle(new n(0,1,0),Math.PI);_firstUpdate=!0;onBeforeRender(){this.updateNow(!1)}updateNow(t){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){let e=M(this.target),n=this._firstUpdate||t?1:O.clamp01(this.context.time.deltaTime*this.followFactor),r=this.worldPosition;this.positionAxes&je.X&&(r.x=O.lerp(r.x,e.x,n)),this.positionAxes&je.Y&&(r.y=O.lerp(r.y,e.y,n)),this.positionAxes&je.Z&&(r.z=O.lerp(r.z,e.z,n)),this.worldPosition=r}if(this.rotateFactor>0){let n=Xt(this.target);this.flipForward&&n.premultiply(e._invertForward);let r=this._firstUpdate||t?1:O.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(n,r)}this._firstUpdate=!1}}};Ao([A(y)],jo.prototype,`target`,void 0),Ao([A()],jo.prototype,`followFactor`,void 0),Ao([A()],jo.prototype,`rotateFactor`,void 0),Ao([A()],jo.prototype,`positionAxes`,void 0);var Mo=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},No=N(`debugspatialtrigger`),Po=new r,Fo=new r;function Io(e,t){return Po.mask=e,Fo.mask=t,Po.test(Fo)}var Lo=class extends R{triggerMask=0;onEnter;onStay;onExit;start(){No&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(let e of Ro.triggers)Io(e.triggerMask,this.triggerMask)&&e.test(this.gameObject)&&this.currentIntersected.push(e);for(let e=this.lastIntersected.length-1;e>=0;e--){let t=this.lastIntersected[e];this.currentIntersected.indexOf(t)<0&&(this.onExitTrigger(t),this.lastIntersected.splice(e,1))}for(let e of this.currentIntersected)this.lastIntersected.indexOf(e)<0&&this.onEnterTrigger(e),this.onStayTrigger(e);this.lastIntersected.length=0,this.lastIntersected.push(...this.currentIntersected)}currentIntersected=[];lastIntersected=[];onEnterTrigger(e){No&&console.log(`ENTER TRIGGER`,this.name,e.name,this,e),e.raiseOnEnterEvent(this),this.onEnter?.invoke()}onExitTrigger(e){No&&console.log(`EXIT TRIGGER`,this.name,e.name),e.raiseOnExitEvent(this),this.onExit?.invoke()}onStayTrigger(e){e.raiseOnStayEvent(this),this.onStay?.invoke()}};Mo([A()],Lo.prototype,`triggerMask`,void 0),Mo([A(k)],Lo.prototype,`onEnter`,void 0),Mo([A(k)],Lo.prototype,`onStay`,void 0),Mo([A(k)],Lo.prototype,`onExit`,void 0);var Ro=class e extends R{static triggers=[];triggerMask;boxHelper;start(){No&&console.log(this.name,this.triggerMask,this)}onEnable(){e.triggers.push(this),this.boxHelper||(this.boxHelper=F.addComponent(this.gameObject,Di),this.boxHelper?.showHelper(null,No))}onDisable(){e.triggers.splice(e.triggers.indexOf(this),1)}test(e){return this.boxHelper?this.boxHelper.isInBox(e)??!1:!1}raiseOnEnterEvent(e){F.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof Lo&&t.onEnterTrigger(this)},!1)}raiseOnStayEvent(e){F.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof Lo&&t.onStayTrigger(this)},!1)}raiseOnExitEvent(e){F.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof Lo&&t.onExitTrigger(this)},!1)}};Mo([A()],Ro.prototype,`triggerMask`,void 0);var zo=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},Bo;(function(e){e[e.FirstPerson=0]=`FirstPerson`,e[e.ThirdPerson=1]=`ThirdPerson`})(Bo||={});var Vo=N(`debugspectator`),Ho=class extends R{cam=null;useKeys=!0;_mode=Bo.FirstPerson;get mode(){return this._mode}set mode(e){this._mode=e}get isSpectating(){return this._handler?.currentTarget!==void 0}isSpectatingUser(e){return this.target?.userId===e}isFollowedBy(e){return this.followers?.includes(e)}get followers(){return this._networking.followers}stopSpectating(){if(this.context.isInXR){this.followSelf();return}this.target=void 0}get localId(){return this.context.connection.connectionId??`local`}set target(e){if(this._handler){let t=this._handler.currentTarget?.userId,n=this.context.players.getPlayerView(this.localId);e===void 0||this.context.isInXR===!1&&n?.currentObject===e.currentObject?this._handler.currentTarget!==void 0&&(this._handler.disable(),F.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(e,t)):this._handler.currentTarget!==e&&(this._handler.set(e),F.setActive(this.gameObject,!0),this.orbit&&(this.orbit.enabled=!1),this._networking.onSpectatedObjectChanged(e,t))}}get target(){return this._handler?.currentTarget}requestAllFollowMe(){this._networking.onRequestFollowMe()}get isSpectatingSelf(){return this.isSpectating&&this.target?.currentObject===this.context.players.getPlayerView(this.localId)?.currentObject}orbit=null;_handler;eventSub_WebXRRequestStartEvent=null;eventSub_WebXRStartEvent=null;eventSub_WebXREndEvent=null;_debug;_networking;awake(){if(this._debug=new Go(this.context,this),this._networking=new Jo(this.context,this),this._networking.awake(),F.setActive(this.gameObject,!1),this.cam=F.getComponent(this.gameObject,Ne),!this.cam){console.warn(`SpectatorCamera: Spectator camera needs camera component on the same object.`,this);return}!this._handler&&this.cam&&(this._handler=new Uo(this.context,this.cam,this)),this.orbit=F.getComponent(this.context.mainCamera,Le)}onDestroy(){this.stopSpectating(),this._handler?.destroy(),this._networking?.destroy()}isSupportedPlatform(){let e=window.navigator.userAgent,t=/Windows NT/.test(e)&&/Edg/.test(e)&&!/Win64/.test(e);return yt.isDesktop()&&!yt.isMobileDevice()&&!t}onBeforeXR(e){this.isSupportedPlatform()&&F.setActive(this.gameObject,!0)}onEnterXR(e){this.isSupportedPlatform()&&(Vo&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onLeaveXR(e){this.context.removeCamera(this.cam),F.setActive(this.gameObject,!1),this._handler?.set(void 0),this._handler?.disable(),this.isSpectatingSelf&&this.stopSpectating(),this.orbit&&(this.orbit.enabled=!0)}followSelf(){this.target=this.context.players.getPlayerView(this.context.connection.connectionId),this.target||=(this.context.players.setPlayerView(this.localId,this.context.mainCamera,qt.Headset),this.context.players.getPlayerView(this.localId)),Vo&&console.log(`Follow self`,this.target)}onAfterRender(){if(!this.cam)return;let e=this.context.renderer,n=e.xr.enabled;if(!e.xr.isPresenting&&!this._handler?.currentTarget)return;this._handler?.update(this._mode);let r=e.getRenderTarget(),i=null,a=e.state;if(!r||r.isXRRenderTarget===!0){if(!e.state.bindFramebuffer||!a.bindXRFramebuffer)return;i=e._framebuffer,a.bindXRFramebuffer(null)}this.setAvatarFlagsBeforeRender();let o=this.context.mainCameraComponent;if(o){let t=o.backgroundColor;t&&e.setClearColor(t,t.alpha),this.cam.backgroundColor=t,this.cam.clearFlags=o.clearFlags,this.cam.nearClipPlane=o.nearClipPlane,this.cam.farClipPlane=o.farClipPlane}else e.setClearColor(new t(1,1,1));e.setRenderTarget(null),e.xr.enabled=!1;let s=this.cam?.threeCamera;this.context.updateAspect(s);let c=e.xr.isPresenting;e.xr.isPresenting=!1,e.setSize(this.context.domWidth,this.context.domHeight),e.render(this.context.scene,s),e.xr.isPresenting=c,e.xr.enabled=n,r?e.setRenderTarget(r):a.bindXRFramebuffer&&a.bindXRFramebuffer(i),this.resetAvatarFlags()}setAvatarFlagsBeforeRender(){let e=this._mode===Bo.FirstPerson;for(let t of Yn.instances)if(t.avatar&&`isLocalAvatar`in t.avatar&&`flags`in t.avatar){let n=Rn.All;this.isSpectatingSelf&&(n=e&&t.avatar.isLocalAvatar?Rn.FirstPerson:Rn.ThirdPerson);let r=t.avatar.flags;if(!r)continue;for(let e of r)e.UpdateVisible(n)}}resetAvatarFlags(){for(let e of Yn.instances)if(e.avatar&&`flags`in e.avatar){let t=e.avatar.flags;if(!t)continue;for(let n of t)`isLocalAvatar`in e.avatar&&e.avatar?.isLocalAvatar?n.UpdateVisible(Rn.FirstPerson):n.UpdateVisible(Rn.ThirdPerson)}}};zo([A()],Ho.prototype,`useKeys`,void 0);var Uo=class{context;cam;spectator;follow;target;view;currentObject;get currentTarget(){return this.view}constructor(e,t,n){this.context=e,this.cam=t,this.spectator=n}set(e){let t=e?.currentObject;if(!t){this.spectator.stopSpectating();return}t!==this.currentObject&&(this.currentObject=t,this.view=e,this.follow||=F.addComponent(this.cam.gameObject,jo),this.target||=new y,t.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,Vo&&console.log(`FOLLOW`,t),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){Vo&&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(){this.target?.removeFromParent(),this.follow&&F.destroy(this.follow)}update(e){if(this.currentTarget?.isConnected===!1||this.currentTarget?.removed===!0){Vo&&console.log(`Target disconnected or timeout`,this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&this.currentTarget?.currentObject!==this.currentObject&&(Vo&&console.log(`Target changed`,this.currentObject,`to`,this.currentTarget.currentObject),this.set(this.currentTarget));let t=this.context.mainCamera;if(t){let e=this.cam.threeCamera;(e.near!==t.near||e.far!==t.far)&&(e.near=t.near,e.far=t.far,e.updateProjectionMatrix())}let n=this.follow?.target;if(!(!n||!this.follow)){switch(e){case Bo.FirstPerson:this.view?.viewDevice===qt.Browser?(this.follow.followFactor=50,this.follow.rotateFactor=50):(this.follow.followFactor=5,this.follow.rotateFactor=5),n.position.set(0,0,0);break;case Bo.ThirdPerson:this.follow.followFactor=3,this.follow.rotateFactor=2,n.position.set(0,.5,1.5);break}this.follow.flipForward=!1,this.view?.viewDevice===qt.Browser?n.quaternion.identity():n.quaternion.copy(Wo)}}},Wo=new x().setFromAxisAngle(new n(0,1,0),Math.PI),Go=class{context;spectator;constructor(e,t){this.context=e,this.spectator=t,console.log(`[Spectator Camera] Click other avatars or cameras to follow them. Press ESC to exit spectator mode.`),this.context.domElement.addEventListener(`keydown`,e=>{this.spectator.useKeys&&e.key===`Escape`&&this.spectator.stopSpectating()});let n=0;this.context.input.addEventListener(Ie.PointerDown,e=>{n=this.context.time.time}),this.context.input.addEventListener(Ie.PointerUp,e=>{let t=this.context.time.time-n;t>1?this.spectator.stopSpectating():this.context.input.getPointerClicked(0)&&t<.3&&this.trySelectObject()})}trySelectObject(){let e=new Gt;e.setMask(16777215);let t=this.context.physics.raycast(e);if(Vo&&console.log(...t),t?.length)for(let e of t){if(e.distance<.2)continue;let t=e.object,n=qn.getFor(t),r=n?.owner;if(r||=F.getComponentInParent(t,Yn)?.connectionId,r){let e=this.context.players.getPlayerView(r);this.spectator.target=e,Vo&&console.log(`spectate`,r,n);break}}}},Ko=class{guid;dontSave=!0;targetUserId;stoppedFollowing;constructor(e,t,n){this.guid=e,this.targetUserId=t,this.stoppedFollowing=n}},qo=class{guid;userId;constructor(e,t){this.guid=e.guid,this.userId=t}},Jo=class{followers=[];context;spectator;_followerEventMethod;_requestFollowMethod;_joinedRoomMethod;constructor(e,t){this.context=e,this.spectator=t,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(P.JoinedRoom,this._joinedRoomMethod),this.context.domElement.addEventListener(`keydown`,e=>{this.spectator.useKeys&&(e.key===`f`?this.onRequestFollowMe():e.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(P.JoinedRoom,this._joinedRoomMethod)}onSpectatedObjectChanged(e,t){if(Vo&&console.log(this.context.connection.connectionId,`onSpectatedObjectChanged`,e,t),this.context.connection.connectionId){let n=e?.userId===void 0,r=n?t:e?.userId,i=new Ko(this.context.connection.connectionId,r,n);this.context.connection.send(`spectator-follower-changed`,i)}}onRequestFollowMe(e=!1){if(Vo&&console.log(`Request follow`,this.context.connection.connectionId),this.context.connection.connectionId){this.spectator.stopSpectating();let t=e?void 0:this.context.connection.connectionId,n=new qo(this.spectator,t);this.context.connection.send(`spectator-request-follow`,n)}}onUserJoinedRoom(){N(`followme`)&&this.onRequestFollowMe()}onFollowerEvent(e){let t=e.targetUserId,n=e.guid;if(Vo&&console.log(e),t===this.context.connection.connectionId)if(e.stoppedFollowing){let e=this.followers.indexOf(n);e!==-1&&(this.followers.splice(e,1),this.removeDisconnectedFollowers(),console.log(n,`unfollows you`,this.followers.length))}else this.followers.includes(n)||(this.followers.push(n),this.removeDisconnectedFollowers(),console.log(n,`follows you`,this.followers.length))}removeDisconnectedFollowers(){for(let e=this.followers.length-1;e>=0;e--){let t=this.followers[e];this.context.connection.userIsInRoom(t)===!1&&this.followers.splice(e,1)}}_lastRequestFollowUser;onRequestFollowEvent(e){if(this._lastRequestFollowUser=e,e.userId===this.context.connection.connectionId)this.spectator.stopSpectating();else if(e.userId===void 0)this.spectator.stopSpectating();else{let t=this.context.players.getPlayerView(e.userId);if(t)this.spectator.target=t;else return Vo&&console.warn(`Could not find view`,e.userId),this.enforceFollow(),!1}return!0}_enforceFollowInterval;enforceFollow(){this._enforceFollowInterval||=setInterval(()=>{this._lastRequestFollowUser===void 0||this._lastRequestFollowUser.userId&&this.spectator.isFollowedBy(this._lastRequestFollowUser.userId)?(clearInterval(this._enforceFollowInterval),this._enforceFollowInterval=void 0):(Vo&&console.log(`REQUEST FOLLOW AGAIN`,this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3)}},Yo=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},Xo=N(`debugsplines`),Zo=class{position=new n;rotation=new x;tangentIn=new n;tangentOut=new n};Yo([j(n)],Zo.prototype,`position`,void 0),Yo([j(x)],Zo.prototype,`rotation`,void 0),Yo([j(n)],Zo.prototype,`tangentIn`,void 0),Yo([j(n)],Zo.prototype,`tangentOut`,void 0);var Qo=class extends R{addKnot(e){if(e instanceof Zo)this.spline.push(e),this._isDirty=!0;else{let t=new Zo;t.position.copy(e.position),this.spline.push(t),this._isDirty=!0}return this}removeKnot(e){if(typeof e==`number`)this.spline.splice(e,1),this._isDirty=!0;else{let t=this.spline.indexOf(e);t!==-1&&(this.spline.splice(t,1),this._isDirty=!0)}return this}getPointAt(e,t){if(!this.curve)return new n;let r=this.curve.getPointAt(O.clamp01(e),t),i=this.gameObject.matrixWorld??void 0;return i&&r.applyMatrix4(i),r}markDirty(){this._isDirty=!0}getTangentAt(e,t){if(!this.curve)return t??new n;let r=this.gameObject.worldQuaternion;return this.curve.getTangentAt(O.clamp01(e),t).applyQuaternion(r)}set closed(e){this._closed=e,this._isDirty=!0}get closed(){return this._closed}_closed=!1;spline=[];set debug(e){e&&!this._builtCurve&&this.buildCurve(),this._debugLine&&(this._debugLine.visible=e)}get curve(){return this._curve}get isDirty(){return this._isDirty}_isDirty=!1;_curve=null;_builtCurve=!1;_debugLine=null;awake(){Xo&&(console.log(`[Spline] ${this.name}`,this),this.buildCurve())}update(){this._isDirty&&this.buildCurve(!0),this._debugLine&&this._debugLine.parent!==this.gameObject&&this.gameObject.add(this._debugLine)}buildCurve(e=!1){if(!(this._builtCurve&&!e)){if(this._builtCurve=!0,!this.spline){console.error(`[Spline] Can not build curve, no spline data`,this.name);return}this._isDirty=!1,this._curve=$o(this.spline,this.closed),this.buildDebugCurve()}}buildDebugCurve(){if(Xo&&this.spline&&this._curve){this._debugLine?.removeFromParent(),this._debugLine=null;let e=new u({color:6684927}),t=this.spline.length*10,n=this._curve.getPoints(t);this._debugLine=new me(new h().setFromPoints(n),e),this.gameObject?.add(this._debugLine)}}};Yo([j()],Qo.prototype,`closed`,null),Yo([j(Zo)],Qo.prototype,`spline`,void 0);function $o(e,t){let r=e.map(e=>new n(-e.position.x,e.position.y,e.position.z));r.length===1&&r.push(r[0]);let a=e.reduce((e,t)=>e+Math.abs(t.tangentOut.x)+Math.abs(t.tangentOut.y)+Math.abs(t.tangentOut.z),0)/e.length;return new i(r,t,`catmullrom`,O.clamp(O.remap(a,0,.3,0,.5),0,1))}var es=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},ts=class extends R{spline=null;object=void 0;useLookAt=!0;lookAt=null;clamp=!1;get position01(){return this._position01}set position01(e){this._position01=e,this._needsUpdate=!0}reset(){this._position01=0}autoRun=!0;duration=10;pullStrength=1;_position01=0;_needsUpdate=!1;start(){this.object===void 0&&(this.object=this.gameObject),this.updateFromPosition()}onEnable(){window.addEventListener(`pointerdown`,this.onUserInput,{passive:!0}),this.context.domElement.addEventListener(`wheel`,this.onUserInput,{passive:!0})}onDisable(){window.removeEventListener(`pointerdown`,this.onUserInput),this.context.domElement.removeEventListener(`wheel`,this.onUserInput)}onUserInput=()=>{this.object?.contains(this.context.mainCamera)&&(this._needsUpdate=!1,this._performedUpdates+=999)};update(){this.autoRun&&(this._needsUpdate=!0,this._position01+=this.context.time.deltaTime/this.duration),this._needsUpdate&&(this._needsUpdate=!1,this.updateFromPosition())}updateFromPosition(){if(!this.spline||!this.spline.curve||!this.object)return;this.clamp?this._position01=O.clamp01(this._position01):this._position01%=1;let e=this._position01>=1?1:this._position01%1,t=this.spline.getPointAt(e);if(this.pullStrength>=1)this.object.worldPosition=t;else if(this._position01!==this._lastPosition01&&(this._performedUpdates=0),this._requiredUpdates=Math.round(100/this.pullStrength),this._performedUpdates=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},is=`SCAM`;Zt(is,ns.getRootAsSyncedCameraModel);var as=new tn,os=class{userId;guid;constructor(e,t){this.guid=t,this.userId=e}send(e,t){if(e){as.clear();let n=as.createString(this.guid),r=as.createString(this.userId);ns.startSyncedCameraModel(as),ns.addGuid(as,n),ns.addUserId(as,r);let i=M(e),a=rn(e);ns.addPos(as,ct.createVec3(as,i.x,i.y,i.z)),ns.addRot(as,ct.createVec3(as,a.x,a.y,a.z));let o=ns.endSyncedCameraModel(as);as.finish(o,is),t.sendBinary(as.asUint8Array())}}},ss=class e extends R{static instances=[];getCameraObject(e){let t=this.userToCamMap[e];return t?this.remoteCams[t].obj:null}cameraPrefab=null;_lastWorldPosition;_lastWorldQuaternion;_model=null;_needsUpdate=!0;_lastUpdateTime=0;remoteCams={};userToCamMap={};_camTimeoutInSeconds=10;_receiveCallback=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(is,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(is,this._receiveCallback)}update(){for(let t in this.remoteCams){let n=this.remoteCams[t],r=this.context.time.realtimeSinceStartup-n.lastUpdate;if(!n||r>this._camTimeoutInSeconds){w()&&console.log(`Remote cam timeout`,t),n?.obj&&F.destroy(n.obj),delete this.remoteCams[t],n&&delete this.userToCamMap[n.userId],e.instances.push(n),this.context.players.removePlayerView(n.userId,qt.Browser);continue}}if(this.context.isInXR)return;let 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 os(this.context.connection.connectionId,this.context.connection.connectionId+`_camera`));let n=M(t),r=Xt(t);(n.distanceTo(this._lastWorldPosition)>.001||r.angleTo(this._lastWorldQuaternion)>.01)&&(this._needsUpdate=!0),this._lastWorldPosition.copy(n),this._lastWorldQuaternion.copy(r),!((!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,qt.Browser))}onReceivedRemoteCameraInfoBin(t){let n=t.guid();if(!n)return;let r=t.userId();if(!r||!this.context.connection.userIsInRoom(r)||!this.cameraPrefab)return;let i=this.remoteCams[n];if(!i)if(`isObject3D`in this.cameraPrefab){let t=new nt;t.context=this.context;let a=F.instantiate(this.cameraPrefab,t);i=this.remoteCams[n]={obj:a,lastUpdate:this.context.time.realtimeSinceStartup,userId:r},i.obj.visible=!0,this.gameObject.add(a),this.userToCamMap[r]=n,e.instances.push(i);let o=F.getOrAddComponent(a,Yn);o.connectionId=r,o.avatar=a}else return;let a=i.obj;this.context.players.setPlayerView(r,a,qt.Browser),i.lastUpdate=this.context.time.realtimeSinceStartup,qe.markDirty(a);let o=t.pos();o&&kt(a,o.x(),o.y(),o.z());let s=t.rot();s&&Be(a,s.x(),s.y(),s.z())}};rs([A([y,Me])],ss.prototype,`cameraPrefab`,void 0);var cs=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},ls=`view`,us=N(`debugsyncedroom`),ds=class extends R{roomName=``;urlParameterName=`room`;joinRandomRoom;requireRoomParameter=!1;autoRejoin=!0;createJoinButton=!0;createViewOnlyButton=!1;get currentRoomName(){return N(ls)||N(this.urlParameterName)}_lastJoinedRoom;set roomPrefix(e){this._roomPrefix=e}get roomPrefix(){return this._roomPrefix}_roomPrefix=``;awake(){this.joinRandomRoom===void 0&&this.roomName?.length<=0&&(this.joinRandomRoom=!0),us&&console.log(`SyncedRoom roomName:${this.roomName}, urlParamName:${this.urlParameterName}, joinRandomRoom:${this.joinRandomRoom}`)}onEnable(){let e=N(ls);if(e&&typeof e==`string`&&e.length>0){console.log(`Join as viewer`),this.context.connection.joinRoom(e,!0);return}if(this.tryJoinRoom(),this.createJoinButton){let e=this.createRoomButton();this.context.menu.appendChild(e)}this.createViewOnlyButton&&this.onEnableViewOnlyButton()}onDisable(){this._roomButton?.remove(),this.onDisableViewOnlyButton(),this.roomName&&this.roomName.length>0&&this.context.connection.leaveRoom(this.roomName)}onDestroy(){this.destroyRoomButton()}tryJoinRandomRoom(){this.setRandomRoomUrlParameter(),this.tryJoinRoom()}tryJoinRoom(e=0){e===void 0&&(e=0);let t=!1;if(this.urlParameterName?.length>0){let n=N(this.urlParameterName);if(n&&(typeof n==`string`||typeof n==`number`))t=!0,this.roomName=Xe(n.toString());else if(this.joinRandomRoom&&(console.debug(`No room name found in url, generating random one`),this.setRandomRoomUrlParameter(),e<1))return this.tryJoinRoom(e+1)}else this.joinRandomRoom&&(this.roomName===null||this.roomName===void 0||this.roomName.length<=0)&&(this.roomName=this.generateRoomName());return this.requireRoomParameter&&!t?((us||w())&&console.warn(`[SyncedRoom] Missing required room parameter "`+this.urlParameterName+`" in url - will not connect. To allow joining a room without a query parameter you can set "requireRoomParameter" to false.`),!1):(this.context.connection.isConnected||this.context.connection.connect(),this._lastJoinedRoom=this.roomName,this._roomPrefix&&(this.roomName=this._roomPrefix+this.roomName),this.roomName.length<=0?(console.warn(`[SyncedRoom] Room name is not set so we can not join a networked room. Please choose one of the following options to fix this: A) Set a room name in the SyncedRoom component B) Set a room name in the URL parameter "?`+this.urlParameterName+`=my_room" C) Set "joinRandomRoom" to true`),!1):(us&&console.log(`Join `+this.roomName),this._userWantsToBeInARoom=!0,this.context.connection.joinRoom(this.roomName),!0))}_lastPingTime=0;_lastRoomTime=-1;_userWantsToBeInARoom=!1;update(){this.context.connection.isConnected&&(this.context.time.time-this._lastPingTime>3&&(this._lastPingTime=this.context.time.time,this.context.connection.sendPing()),this.context.connection.isInRoom&&(this._lastRoomTime=this.context.time.time)),this._lastRoomTime>0&&this.context.time.time-this._lastRoomTime>.3&&(this._lastRoomTime=-1,this.autoRejoin?this._userWantsToBeInARoom&&(console.log(`Disconnected from networking backend - attempt reconnecting now`),this.tryJoinRoom()):w()&&console.warn(`You are not connected to a room anymore (possibly because the tab was inactive for too long and the server kicked you?)`))}getViewOnlyUrl(){if(this.context.connection.isConnected&&this.context.connection.currentRoomViewId){let e=window.location.search,t=new URLSearchParams(e);return t.has(this.urlParameterName)&&t.delete(this.urlParameterName),t.set(ls,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+`?`+t.toString()}return null}setRandomRoomUrlParameter(){let e=Yt(),t=this.generateRoomName();N(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),Ge(t,e)}generateRoomName(){let e=``;for(let t=0;t<6;t++)e+=Math.floor(Math.random()*10).toFixed(0);return e}_roomButton;_roomButtonIconJoin;_roomButtonIconLeave;createRoomButton(){if(this._roomButton)return this._roomButton;let e=document.createElement(`button`);return this._roomButton=e,e.classList.add(`create-room-button`),e.setAttribute(`priority`,`90`),e.onclick=()=>{if(this.context.connection.isInRoom)this.urlParameterName&&Ve(this.urlParameterName,null),this.context.connection.leaveRoom(),this._userWantsToBeInARoom=!1;else{if(this.urlParameterName){let e=N(this.urlParameterName);(!e||e===!0)&&(this._lastJoinedRoom?Ve(this.urlParameterName,this._lastJoinedRoom):this.setRandomRoomUrlParameter())}this.tryJoinRoom()}},this._roomButtonIconJoin=ke(`group`),this._roomButtonIconLeave=ke(`group_off`),this.updateRoomButtonState(),this.context.connection.beginListen(P.JoinedRoom,this.updateRoomButtonState),this.context.connection.beginListen(P.LeftRoom,this.updateRoomButtonState),e}updateRoomButtonState=()=>{this._roomButton&&(this.context.connection.isInRoom?(this._roomButton.title=`Leave the networked room`,this._roomButton.textContent=`Leave Room`,this._roomButtonIconJoin?.remove(),this._roomButton.prepend(this._roomButtonIconLeave)):(this._roomButton.title=`Create or join a networked room`,this._roomButton.textContent=`Join Room`,this._roomButtonIconLeave?.remove(),this._roomButton.prepend(this._roomButtonIconJoin)))};destroyRoomButton(){this.context.connection.stopListen(P.JoinedRoom,this.updateRoomButtonState),this.context.connection.stopListen(P.LeftRoom,this.updateRoomButtonState)}_viewOnlyButton;onEnableViewOnlyButton(){this.context.connection.isConnected?this.onCreateViewOnlyButton():(this.context.connection.stopListen(P.JoinedRoom,this.onCreateViewOnlyButton),this.context.connection.beginListen(P.JoinedRoom,this.onCreateViewOnlyButton))}onDisableViewOnlyButton(){this.context.connection.stopListen(P.JoinedRoom,this.onCreateViewOnlyButton),this._viewOnlyButton?.remove()}onCreateViewOnlyButton=()=>{if(!this._viewOnlyButton){let e=document.createElement(`button`);this._viewOnlyButton=e,e.classList.add(`view-only-button`),e.setAttribute(`priority`,`90`),e.onclick=()=>{let e=this.getViewOnlyUrl();e?.length?navigator.canShare({url:e})?navigator.share({url:e})?.catch(e=>{console.warn(e)}):(navigator.clipboard.writeText(e),It(`View only URL copied to clipboard`)):Ht(`Could not create view only URL`)},e.title=`Copy the view only URL: A page accessed by the view only URL can not be modified by visiting users.`,e.textContent=`Share View URL`,e.prepend(ke(`visibility`))}this.context.menu.appendChild(this._viewOnlyButton)}};cs([A()],ds.prototype,`roomName`,void 0),cs([A()],ds.prototype,`urlParameterName`,void 0),cs([A()],ds.prototype,`joinRandomRoom`,void 0),cs([A()],ds.prototype,`requireRoomParameter`,void 0),cs([A()],ds.prototype,`autoRejoin`,void 0),cs([A()],ds.prototype,`createJoinButton`,void 0),cs([A()],ds.prototype,`createViewOnlyButton`,void 0),cs([A()],ds.prototype,`roomPrefix`,null);function fs(){let e=N(`testwindowcount`)||0;e&&e>0&&ps(e)}function ps(e){if(N(`testwindow`))return null;let t=new URL(window.location.href);$e(t.searchParams,cn,1),$e(t.searchParams,`testwindow`,1);let n=t.toString(),r=[];window.onbeforeunload=()=>{for(let e of r)e.close()};let i=.05,a=0,o=0;for(let t=0;t=window.innerWidth&&(o+=1,a=0);let e=a*(128*(1+i))+window.screenLeft,s=o*(128*(1+i))+window.screenTop+90+60*o;a+=1;let c=window.open(n,`test window `+t,`popup=yes width=128 height=128 top=${s} left=${e}`);if(!c){console.warn(`Failed to open window`);continue}r.push(c),c.onload=()=>{c.onbeforeunload=()=>{for(let e=0;e{});else{this.models=[];for(let e=0;e=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},vs=class extends R{isGizmo=!1;translationSnap=1;rotationSnapAngle=15;scaleSnap=.25;get control(){return this._control}_control;orbit;onEnable(){if(!(this.isGizmo&&!Lt)&&this.context.mainCamera&&(this._control||(this._control=new on(this.context.mainCamera,this.context.renderer.domElement),this._control.enabled=!0,this._control.getRaycaster().layers.set(2),this._control.size=1,(`_root`in this._control?this._control._root:this._control).traverse(e=>{let t=e;if(t.layers.set(2),t){let e=t.material;e&&(e.opacity=.3)}}),this.orbit=F.getComponentInParent(this.context.mainCamera,Le)??void 0),this._control)){let e=this._control.getHelper();this.context.scene.add(e),this._control.attach(this.gameObject),this._control?.addEventListener(`dragging-changed`,this.onControlChangedEvent),window.addEventListener(`keydown`,this.windowKeyDownListener),window.addEventListener(`keyup`,this.windowKeyUpListener)}}onDisable(){this._control?.getHelper()?.removeFromParent(),this._control?.removeEventListener(`dragging-changed`,this.onControlChangedEvent),window.removeEventListener(`keydown`,this.windowKeyDownListener),window.removeEventListener(`keyup`,this.windowKeyUpListener)}enableSnapping(){this._control&&(this._control.setTranslationSnap(this.translationSnap),this._control.setRotationSnap(o.degToRad(this.rotationSnapAngle)),this._control.setScaleSnap(this.scaleSnap))}disableSnapping(){this._control&&(this._control.setTranslationSnap(null),this._control.setRotationSnap(null),this._control.setScaleSnap(null))}onControlChangedEvent=e=>{let t=this.orbit;if(t&&(t.enabled=!e.value),e.value){let e=this.gameObject.getComponentInParent(rt);e&&(e.fastMode=!0,e.requestOwnership())}else{let e=this.gameObject.getComponentInParent(rt);e&&(e.fastMode=!1)}};windowKeyDownListener=e=>{if(this.enabled&&this._control)switch(e.keyCode){case 81:this._control.setSpace(this._control.space===`local`?`world`:`local`);break;case 16:this.enableSnapping();break;case 87:this._control.setMode(`translate`);break;case 69:this._control.setMode(`rotate`);break;case 82:this._control.setMode(`scale`);break;case 187:case 107:this._control.setSize(this._control.size+.1);break;case 189:case 109:this._control.setSize(Math.max(this._control.size-.1,.1));break;case 88:this._control.showX=!this._control.showX;break;case 89:this._control.showY=!this._control.showY;break;case 90:this._control.showZ=!this._control.showZ;break;case 32:this._control.enabled=!this._control.enabled;break}};windowKeyUpListener=e=>{if(this.enabled)switch(e.keyCode){case 16:this.disableSnapping();break}}};_s([A()],vs.prototype,`isGizmo`,void 0),_s([A()],vs.prototype,`translationSnap`,void 0),_s([A()],vs.prototype,`rotationSnapAngle`,void 0),_s([A()],vs.prototype,`scaleSnap`,void 0);var ys=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},bs=class e extends R{target;invertForward=!1;keepUpDirection=!0;copyTargetRotation=!1;static flipYQuat=new x().setFromAxisAngle(new n(0,1,0),Math.PI);onBeforeRender(){let t=this.target;if(t||(t=this.context.mainCamera,w()&&!this.__did_warn&&(this.__did_warn=!0,console.debug(`[LookAt] No target set on ${this.name}, using main camera as target.`))),!t)return;let n=this.copyTargetRotation;(this.context.isInVR||this.context.isInPassThrough)&&(n=!1),Qt(this.gameObject,t,this.keepUpDirection,n),this.invertForward&&this.gameObject.quaternion.multiply(e.flipYQuat)}createBehaviours(e,t,n){if(t.uuid===this.gameObject.uuid){let n=t;if(this.keepUpDirection){let e=Xn.createEmptyParent(t);n=e;let r=this.invertForward?-1:1;e.setMatrix(e.getMatrix().multiply(new _().makeRotationZ(Math.PI/2*r))),t.setMatrix(t.getMatrix().multiply(new _().makeRotationZ(-Math.PI/2*r)))}let r=new sr(`lookat `+this.name,Bn.sceneStartTrigger(),fr.lookAtCameraAction(n,void 0,this.invertForward?lr.back:lr.forward,this.keepUpDirection?lr.up:lr.zero));e.addBehavior(r)}}};ys([A(y)],bs.prototype,`target`,void 0),ys([A()],bs.prototype,`invertForward`,void 0),ys([A()],bs.prototype,`keepUpDirection`,void 0),ys([A()],bs.prototype,`copyTargetRotation`,void 0);var xs=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},Ss;(function(e){e[e.NewTab=0]=`NewTab`,e[e.SameTab=1]=`SameTab`,e[e.NewWindow=2]=`NewWindow`})(Ss||={});var Cs=class extends R{url;mode=Ss.NewTab;clickable=!0;async open(){if(!this.url){console.warn(`OpenURL: URL is not set, can't open.`,this);return}this._validateUrl();let e=this.url;switch(!e.startsWith(`mailto:`)&&e.includes(`@`)&&(e=`mailto:`+e),this.mode){case Ss.NewTab:yt.isSafari(),globalThis.open(e,`_blank`);break;case Ss.SameTab:yt.isSafari()&&yt.isiOS()?globalThis.open(e,`_top`):globalThis.open(e,`_self`);break;case Ss.NewWindow:yt.isSafari()?globalThis.open(e,`_top`):globalThis.open(e,`_new`);break}}start(){this.gameObject.getComponentInParent(C)||this.gameObject.addComponent(C)}onPointerEnter(e){!e.used&&this.clickable&&this.context.input.setCursor(`pointer`)}onPointerExit(){this.clickable&&this.context.input.unsetCursor(`pointer`)}onPointerClick(e){this.clickable&&!e.used&&this.url?.length&&this.open()}_validateUrl(){this.url&&this.url.startsWith(`www.`)&&(w()&&console.warn(`URL is not valid, adding https:// to the start of the URL`,this.url),this.url=`https://`+this.url)}};xs([A()],Cs.prototype,`url`,void 0),xs([A()],Cs.prototype,`mode`,void 0),xs([A()],Cs.prototype,`clickable`,void 0),$t(e=>{if(t(e.domElement.getAttribute(`clickthrough`))){let n=e.scene.addComponent(ws);Dt(e.domElement,`clickthrough`,()=>{n.enabled=t(e.domElement.getAttribute(`clickthrough`))})}function t(e){return e!==null&&e!==`0`&&e!==`false`}});var ws=class extends R{_previousPointerEvents=`all`;onEnable(){this.context.input.addEventListener(`pointerdown`,this.onPointerEvent),this.context.input.addEventListener(`pointermove`,this.onPointerEvent,{queue:100}),window.addEventListener(`touchstart`,this.onTouchStart,{passive:!0}),window.addEventListener(`touchend`,this.onTouchEnd,{passive:!0}),this._previousPointerEvents=this.context.domElement.style.pointerEvents}onDisable(){this.context.input.removeEventListener(`pointerdown`,this.onPointerEvent),this.context.input.removeEventListener(`pointermove`,this.onPointerEvent),window.removeEventListener(`touchstart`,this.onTouchStart),window.removeEventListener(`touchend`,this.onTouchEnd),this.context.domElement.style.pointerEvents=this._previousPointerEvents}onPointerEnter(){}onPointerEvent=e=>{e.pointerId>0||(e.intersections?.length<=0?this.context.domElement.style.pointerEvents=`none`:this.context.domElement.style.pointerEvents=`all`)};_touchDidHitAnything=!1;onTouchStart=e=>{let t=e.touches[0];if(!t)return;let n=t.clientX/window.innerWidth*2-1,r=-(t.clientY/window.innerHeight)*2+1;this.context.physics.raycast({screenPoint:new b(n,r)}).length>0&&(this._touchDidHitAnything=!0)};onTouchEnd=e=>{let t=this._touchDidHitAnything;this._touchDidHitAnything=!1,setTimeout(()=>{t&&(this.context.domElement.style.pointerEvents=`all`)},100)}},Ts=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},Es=N(`debugcursor`),Ds=class extends R{static NAME=`CursorFollow`;damping=0;useFullPage=!0;keepDistance=!0;snapToSurface=!1;_distance=-1;updateDistance(e=!1){!e&&this.keepDistance&&this._distance!==-1||(this._distance=this.gameObject.worldPosition.distanceTo(this.context.mainCamera.worldPosition))}awake(){this._distance=-1}onEnable(){this._distance=-1,window.addEventListener(`pointermove`,this._onPointerMove)}onDisable(){window.removeEventListener(`pointermove`,this._onPointerMove)}_ndc_x=0;_ndc_y=0;_onPointerMove=e=>{if(!this.useFullPage)return;let t=e.clientX,n=e.clientY,r=this.context.domX,i=this.context.domY,a=this.context.domWidth,o=this.context.domHeight;this._ndc_x=(t-r)/a*2-1,this._ndc_y=-(n-i)/o*2+1};lateUpdate(){this.updateDistance();let e=this.useFullPage?this._ndc_x:this.context.input.mousePositionRC.x,t=this.useFullPage?this._ndc_y:this.context.input.mousePositionRC.y,n=this.context.mainCamera,r=n.worldPosition,i=z(e,t,1).unproject(n);i.sub(r).normalize();let a=z(i).multiplyScalar(this._distance).add(r),o=a;if(this.damping>0){let e=this.gameObject.worldPosition;e.lerp(a,this.context.time.deltaTime/this.damping),this.gameObject.worldPosition=e,o=e}else this.gameObject.worldPosition=a;if(this.snapToSurface){Os.origin=o,Os.direction=i.multiplyScalar(-1);let e=this.context.physics.raycastFromRay(Os);if(e?.length){let t=e[0];this.damping>0?this.gameObject.worldPosition=o.lerp(t.point,this.context.time.deltaTime/this.damping):this.gameObject.worldPosition=t.point,Es&&V.DrawLine(t.point,t.normal.add(t.point),65280)}}}};Ts([A()],Ds.prototype,`damping`,void 0),Ts([A()],Ds.prototype,`useFullPage`,void 0),Ts([A()],Ds.prototype,`keepDistance`,void 0),Ts([A()],Ds.prototype,`snapToSurface`,void 0);var Os=new a,ks=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},As=class extends R{type=`linear`;duration=.1;scaleFactor=1.1;hovered=null;idle=null;animation=null;start(){this.idle||=at.emptyClip(),(!this.hovered||!(this.hovered instanceof de))&&(this.hovered=at.createScaleClip({type:`linear`,duration:this.duration||.1,scale:this.gameObject.scale,scaleFactor:this.scaleFactor||1.1})),this.animation??=this.gameObject.addComponent(Qn),this.animation.playAutomatically=!1,this.playIdle()}onEnable(){this.animation&&(this.animation.enabled=!0),this.playIdle()}onDisable(){this.animation&&(this.animation.enabled=!1),this.playIdle()}onPointerEnter(){this.playHover()}onPointerExit(){this.playIdle()}playIdle(){this.idle&&this.animation?.play(this.idle,{exclusive:!0,fadeDuration:.1,loop:!0})}playHover(){this.hovered&&this.animation?.play(this.hovered,{exclusive:!0,fadeDuration:.1,loop:!1,clampWhenFinished:!0})}};ks([A()],As.prototype,`type`,void 0),ks([A()],As.prototype,`duration`,void 0),ks([A()],As.prototype,`scaleFactor`,void 0),ks([A(de)],As.prototype,`hovered`,void 0),ks([A(de)],As.prototype,`idle`,void 0),As=ks([I],As);var js=Object.defineProperty,Ms=(e,t,n)=>t in e?js(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,$=(e,t,n)=>(Ms(e,typeof t==`symbol`?t:t+``,n),n);(function(){class e{}class t extends e{constructor(e){super(),$(this,`value`),this.value=e}}class n extends e{constructor(e){super(),$(this,`value`),this.value=e}}class r extends e{constructor(e){super(),$(this,`value`),this.value=e}}class i extends e{constructor(e,t=`unrestricted`){super(),$(this,`type`),$(this,`value`),this.value=e,this.type=t}}class a extends e{constructor(e){super(),$(this,`value`),this.value=e}}class o extends e{}class s extends e{constructor(e){super(),$(this,`value`),this.value=e}}class c extends e{}class l extends e{constructor(e){super(),$(this,`value`),this.value=e}}class u extends e{constructor(e,t=`integer`){super(),$(this,`value`),$(this,`type`),this.value=e,this.type=t}}class d extends e{constructor(e){super(),$(this,`value`),this.value=e}}class f extends e{constructor(e,t,n){super(),$(this,`value`),$(this,`type`),$(this,`unit`),this.value=e,this.type=t,this.unit=n}}class p extends e{}class m extends e{}class ee extends e{}class h extends e{}class g extends e{}class te extends e{}class _ extends e{}class ne extends e{}class re extends e{}class v extends e{}class ie extends e{}class ae extends e{}class oe{constructor(e){$(this,`input`),$(this,`index`,0),this.input=e}consume(){let e=this.input.codePointAt(this.index);return e!==void 0&&(this.index+=String.fromCodePoint(e).length),e}reconsume(e){e!==void 0&&(this.index-=String.fromCodePoint(e).length)}peek(){let e=[],t=this.index;for(let n=0;n<3&&t=48&&e<=57}function le(e){return ce(e)||e>=65&&e<=70||e>=97&&e<=102}function ue(e){return function(e){return function(e){return e>=65&&e<=90}(e)||function(e){return e>=97&&e<=122}(e)}(e)||function(e){return e>=128}(e)||e===95}function de(e){return ue(e)||ce(e)||e===45}function fe(e){return e>=0&&e<=8||e===11||e>=14&&e<=31||e===127}function pe(e,t){return e===92&&!se(t)}function me(e,t,n){return e===45?ue(t)||t===45||pe(t,n):!!ue(e)||e===92&&pe(e,t)}function b(e,t,n){return e===43||e===45?ce(t)||t===46&&ce(n):ce(e===46?t:e)}function he(e){let t=e.consume();if(le(t)){let n=[t];for(;le(...e.peek())&&n.length<5;)n.push(e.consume());y(...e.peek())&&e.consume();let r=parseInt(String.fromCodePoint(...n),16);return r===0||r>1114111?65533:r}return t===void 0?65533:t}function ge(e,t){let n=new a(``);for(;;){let r=e.consume();if(r===t||r===void 0)return n;if(r===10)return e.reconsume(r),new o;if(r===92){let t=e.peek()[0];t===void 0||(se(t)?e.consume():n.value+=String.fromCodePoint(he(e)))}else n.value+=String.fromCodePoint(r)}}function _e(e){let t=``;for(;;){let n=e.consume();if(de(n))t+=String.fromCodePoint(n);else{if(!pe(...e.peek()))return e.reconsume(n),t;t+=String.fromCodePoint(he(e))}}}function ve(e){let t=function(e){let t=`integer`,n=``;for([43,45].includes(e.peek()[0])&&(n+=String.fromCodePoint(e.consume()));ce(...e.peek());)n+=String.fromCodePoint(e.consume());if(e.peek()[0]===46&&ce(e.peek()[1]))for(n+=String.fromCodePoint(e.consume(),e.consume()),t=`number`;ce(...e.peek());)n+=String.fromCodePoint(e.consume());return[69,101].includes(e.peek()[0])&&([45,43].includes(e.peek()[1])&&ce(e.peek()[2])?(n+=String.fromCodePoint(e.consume(),e.consume(),e.consume()),t=`number`):ce(e.peek()[1])&&(n+=String.fromCodePoint(e.consume(),e.consume()),t=`number`)),{value:parseFloat(n),type:t}}(e);return me(...e.peek())?new f(t.value,t.type,_e(e)):e.peek()[0]===37?(e.consume(),new d(t.value)):new u(t.value,t.type)}function ye(e){for(;;){let t=e.consume();if(t===41||t===void 0)return;pe(...e.peek())&&he(e)}}function be(e){let r=_e(e);if(r.match(/url/i)&&e.peek()[0]===40){for(e.consume();y(e.peek()[0])&&y(e.peek()[1]);)e.consume();return[34,39].includes(e.peek()[0])||y(e.peek()[0])&&[34,39].includes(e.peek()[1])?new n(r):function(e){let t=new s(``);for(;y(...e.peek());)e.consume();for(;;){let n=e.consume();if(n===41||n===void 0)return t;if(y(n)){for(;y(...e.peek());)e.consume();return e.peek()[0]===41||e.peek()[0]===void 0?(e.consume(),t):(ye(e),new c)}if([34,39,40].includes(n)||fe(n))return ye(e),new c;if(n===92){if(!pe(...e.peek()))return ye(e),new c;t.value+=he(e)}else t.value+=String.fromCodePoint(n)}}(e)}return e.peek()[0]===40?(e.consume(),new n(r)):new t(r)}function xe(e){let t=e.consume(),n=e.peek();if(y(t)){for(;y(...e.peek());)e.consume();return new p}if(t===34)return ge(e,t);if(t===35){if(de(n[0])||pe(...n)){let t=new i;return me(...n)&&(t.type=`id`),t.value=_e(e),t}return new l(String.fromCodePoint(t))}return t===39?ge(e,t):t===40?new re:t===41?new v:t===43?b(...n)?(e.reconsume(t),ve(e)):new l(String.fromCodePoint(t)):t===44?new te:t===45?b(...e.peek())?(e.reconsume(t),ve(e)):e.peek()[0]===45&&e.peek()[1]===62?(e.consume(),e.consume(),new ee):me(...e.peek())?(e.reconsume(t),be(e)):new l(String.fromCodePoint(t)):t===46?b(...e.peek())?(e.reconsume(t),ve(e)):new l(String.fromCodePoint(t)):t===58?new h:t===59?new g:t===60?n[0]===33&&n[1]===45&&n[2]===45?(e.consume(),e.consume(),e.consume(),new m):new l(String.fromCodePoint(t)):t===64?me(...n)?new r(_e(e)):new l(String.fromCodePoint(t)):t===91?new _:t===92?pe(...n)?(e.reconsume(t),be(e)):new l(String.fromCodePoint(t)):t===93?new ne:t===123?new ie:t===125?new ae:ce(t)?(e.reconsume(t),ve(e)):ue(t)?(e.reconsume(t),be(e)):t===void 0?void 0:new l(String.fromCodePoint(t))}let Se=new Set([`px`,`deg`,`s`,`hz`,`dppx`,`number`,`fr`]);function Ce(e){return Se.has(e.toLowerCase())}function we(e,t){if([`x`,`y`].includes(e))return e;if(!t)throw Error(`To determine the normalized axis the computedStyle of the source is required.`);let n=t.writingMode==`horizontal-tb`;if(e===`block`)e=n?`y`:`x`;else{if(e!==`inline`)throw TypeError(`Invalid axis “${e}”`);e=n?`x`:`y`}return e}function x(e){let t=[],n=0;function r(){let t=0,r=n;for(;n(e.has(n[t])?e.get(n[t]).push(n):e.set(n[t],[n]),e)),new Map)}function Ee(e,t){let n=[],r=[];for(let i of e)t(i)?n.push(i):r.push(i);return[n,r]}function De(e,t={}){function n(e){return Array.from(e).map((e=>De(e,t)))}if(e instanceof CSSUnitValue){if(e.unit===`percent`&&t.percentageReference){let n=e.value/100*t.percentageReference.value,r=t.percentageReference.unit;return new CSSUnitValue(n,r)}let n=e.toSum();if(n&&n.values.length===1&&(e=n.values[0]),e instanceof CSSUnitValue&&e.unit===`em`&&t.fontSize&&(e=new CSSUnitValue(e.value*t.fontSize.value,t.fontSize.unit)),e instanceof CSSKeywordValue){if(e.value===`e`)return new CSSUnitValue(Math.E,`number`);if(e.value===`pi`)return new CSSUnitValue(Math.PI,`number`)}return e}if(!e.operator)return e;switch(e.operator){case`sum`:e=new CSSMathSum(...n(e.values));break;case`product`:e=new CSSMathProduct(...n(e.values));break;case`negate`:e=new CSSMathNegate(De(e.value,t));break;case`clamp`:e=new CSSMathClamp(De(e.lower,t),De(e.value,t),De(e.upper,t));break;case`invert`:e=new CSSMathInvert(De(e.value,t));break;case`min`:e=new CSSMathMin(...n(e.values));break;case`max`:e=new CSSMathMax(...n(e.values))}if(e instanceof CSSMathMin||e instanceof CSSMathMax){let t=Array.from(e.values);if(t.every((e=>e instanceof CSSUnitValue&&e.unit!==`percent`&&Ce(e.unit)&&e.unit===t[0].unit))){let n=Math[e.operator].apply(Math,t.map((({value:e})=>e)));return new CSSUnitValue(n,t[0].unit)}}if(e instanceof CSSMathMin||e instanceof CSSMathMax){let t=Array.from(e.values),[n,r]=Ee(t,(e=>e instanceof CSSUnitValue&&e.unit!==`percent`)),i=Array.from(Te(n,`unit`).values());if(i.some((e=>e.length>0))){let t=i.map((t=>{let n=Math[e.operator].apply(Math,t.map((({value:e})=>e)));return new CSSUnitValue(n,t[0].unit)}));e=e instanceof CSSMathMin?new CSSMathMin(...t,...r):new CSSMathMax(...t,...r)}return t.length===1?t[0]:e}if(e instanceof CSSMathNegate)return e.value instanceof CSSUnitValue?new CSSUnitValue(0-e.value.value,e.value.unit):e.value instanceof CSSMathNegate?e.value.value:e;if(e instanceof CSSMathInvert)return e.value instanceof CSSMathInvert?e.value.value:e;if(e instanceof CSSMathSum){let t=function(e){let t=e.filter((e=>e instanceof CSSUnitValue));return[...e.filter((e=>!(e instanceof CSSUnitValue))),...Array.from(Te(t,`unit`).entries()).map((([e,t])=>{let n=t.reduce(((e,{value:t})=>e+t),0);return new CSSUnitValue(n,e)}))]},n=[];for(let t of e.values)t instanceof CSSMathSum?n.push(...t.values):n.push(t);return n=t(n),n.length===1?n[0]:new CSSMathSum(...n)}if(e instanceof CSSMathProduct){let t=[];for(let n of e.values)n instanceof CSSMathProduct?t.push(...n.values):t.push(n);let[n,r]=Ee(t,(e=>e instanceof CSSUnitValue&&e.unit===`number`));if(n.length>1){let e=n.reduce(((e,{value:t})=>e*t),1);t=[new CSSUnitValue(e,`number`),...r]}if(t.length===2){let e,n;for(let r of t)r instanceof CSSUnitValue&&r.unit===`number`?e=r:r instanceof CSSMathSum&&[...r.values].every((e=>e instanceof CSSUnitValue))&&(n=r);if(e&&n)return new CSSMathSum(...[...n.values].map((t=>new CSSUnitValue(t.value*e.value,t.unit))))}if(t.every((e=>e instanceof CSSUnitValue&&Ce(e.unit)||e instanceof CSSMathInvert&&e.value instanceof CSSUnitValue&&Ce(e.value.unit)))){let e=new CSSMathProduct(...t).toSum();if(e&&e.values.length===1)return e.values[0]}return new CSSMathProduct(...t)}return e}let S=[`percent`,`length`,`angle`,`time`,`frequency`,`resolution`,`flex`],C={fontRelativeLengths:{units:new Set([`em`,`rem`,`ex`,`rex`,`cap`,`rcap`,`ch`,`rch`,`ic`,`ric`,`lh`,`rlh`])},viewportRelativeLengths:{units:new Set([`vw`,`lvw`,`svw`,`dvw`,`vh`,`lvh`,`svh`,`dvh`,`vi`,`lvi`,`svi`,`dvi`,`vb`,`lvb`,`svb`,`dvb`,`vmin`,`lvmin`,`svmin`,`dvmin`,`vmax`,`lvmax`,`svmax`,`dvmax`])},absoluteLengths:{units:new Set([`cm`,`mm`,`Q`,`in`,`pt`,`pc`,`px`]),compatible:!0,canonicalUnit:`px`,ratios:{cm:96/2.54,mm:96/2.54/10,Q:96/2.54/40,in:96,pc:16,pt:96/72,px:1}},angle:{units:new Set([`deg`,`grad`,`rad`,`turn`]),compatible:!0,canonicalUnit:`deg`,ratios:{deg:1,grad:.9,rad:180/Math.PI,turn:360}},time:{units:new Set([`s`,`ms`]),compatible:!0,canonicalUnit:`s`,ratios:{s:1,ms:.001}},frequency:{units:new Set([`hz`,`khz`]),compatible:!0,canonicalUnit:`hz`,ratios:{hz:1,khz:1e3}},resolution:{units:new Set([`dpi`,`dpcm`,`dppx`]),compatible:!0,canonicalUnit:`dppx`,ratios:{dpi:1/96,dpcm:2.54/96,dppx:1}}},Oe=new Map;for(let e of Object.values(C))if(e.compatible)for(let t of e.units)Oe.set(t,e);function ke(e){return Oe.get(e)}function Ae(e,t){let n={...e};for(let e of Object.keys(t))n[e]?n[e]+=t[e]:n[e]=t[e];return n}function je(e){return e===`number`?{}:e===`percent`?{percent:1}:C.absoluteLengths.units.has(e)||C.fontRelativeLengths.units.has(e)||C.viewportRelativeLengths.units.has(e)?{length:1}:C.angle.units.has(e)?{angle:1}:C.time.units.has(e)?{time:1}:C.frequency.units.has(e)?{frequency:1}:C.resolution.units.has(e)?{resolution:1}:e===`fr`?{flex:1}:null}function Me(e){if(e instanceof CSSUnitValue){let{unit:t,value:n}=e,r=ke(e.unit);return r&&t!==r.canonicalUnit&&(n*=r.ratios[t],t=r.canonicalUnit),t===`number`?[[n,{}]]:[[n,{[t]:1}]]}if(e instanceof CSSMathInvert){if(!(e.value instanceof CSSUnitValue))throw Error(`Not implemented`);let t=Me(e.value);if(t===null||t.length>1)return null;let n=t[0],r={};for(let[e,t]of Object.entries(n[1]))r[e]=-1*t;return t[0]=[1/n[0],r],t}if(e instanceof CSSMathProduct){let t=[[1,{}]];for(let n of e.values){let e=Me(n),r=[];if(e===null)return null;for(let n of t)for(let t of e)r.push([n[0]*t[0],Ae(n[1],t[1])]);t=r}return t}throw Error(`Not implemented`)}function Ne(e,t){if(je(t)===null)throw SyntaxError(`The string did not match the expected pattern.`);let n=Me(e);if(!n)throw TypeError();if(n.length>1)throw TypeError(`Sum has more than one item`);let r=function(e,t){let n=e.unit,r=e.value,i=ke(n),a=ke(t);return!a||i!==a?null:new CSSUnitValue(r*a.ratios[n]/a.ratios[t],t)}(Pe(n[0]),t);if(r===null)throw TypeError();return r}function Pe(e){let[t,n]=e,r=Object.entries(n);if(r.length>1)return null;if(r.length===0)return new CSSUnitValue(t,`number`);let i=r[0];return i[1]===1?new CSSUnitValue(t,i[0]):null}function Fe(e,...t){if(t&&t.length)throw Error(`Not implemented`);let n=Me(e).map((e=>Pe(e)));if(n.some((e=>e===null)))throw TypeError(`Type error`);return new CSSMathSum(...n)}function Ie(e,t){if(e.percentHint&&t.percentHint&&e.percentHint!==t.percentHint)return null;let n={...e,percentHint:e.percentHint??t.percentHint};for(let e of S)t[e]&&(n[e]??(n[e]=0),n[e]+=t[e]);return n}class Le{constructor(e,t){$(this,`name`),$(this,`values`),this.name=e,this.values=t}}class Re{constructor(e,t){$(this,`value`),$(this,`associatedToken`),this.value=e,this.associatedToken=t}}function ze(e){if(Array.isArray(e))return e;if(typeof e==`string`)return function(e){let t=new oe(e),n=[];for(;;){let e=xe(t);if(e===void 0)return n;n.push(e)}}(e);throw TypeError(`Invalid input type `+typeof e)}function Be(e){let t=e.shift();return t instanceof ie||t instanceof _||t instanceof re?function(e,t){let n;if(t instanceof ie)n=ae;else if(t instanceof re)n=v;else{if(!(t instanceof _))return;n=ne}let r=new Re([],t);for(;;){let t=e.shift();if(t instanceof n||t===void 0)return r;e.unshift(t),r.value.push(Be(e))}}(e,t):t instanceof n?function(e,t){let n=new Le(e.value,[]);for(;;){let e=t.shift();if(e instanceof v||e===void 0)return n;t.unshift(e),n.values.push(Be(t))}}(t,e):t}function Ve(e){if(e instanceof re||e instanceof v)return 6;if(e instanceof l)switch(e.value){case`*`:case`/`:return 4;case`+`:case`-`:return 2}}function He(e){return e[e.length-1]}function Ue(e,t,n){let r=[`+`,`-`].includes(e.value)?`ADDITION`:`MULTIPLICATION`,i=t.type===r?t.values:[t],a=n.type===r?n.values:[n];return e.value===`-`?a[0]={type:`NEGATE`,value:a[0]}:e.value===`/`&&(a[0]={type:`INVERT`,value:a[0]}),{type:r,values:[...i,...a]}}function We(e){if(e.type===`ADDITION`)return new CSSMathSum(...e.values.map((e=>We(e))));if(e.type===`MULTIPLICATION`)return new CSSMathProduct(...e.values.map((e=>We(e))));if(e.type===`NEGATE`)return new CSSMathNegate(We(e.value));if(e.type===`INVERT`)return new CSSMathInvert(We(e.value));if(e instanceof Re)return Ge(new Le(`calc`,e.value));if(e instanceof t){if(e.value===`e`)return new CSSUnitValue(Math.E,`number`);if(e.value===`pi`)return new CSSUnitValue(Math.PI,`number`);throw SyntaxError(`Invalid math expression`)}return Ke(e)}function Ge(e){if(e.name===`min`||e.name===`max`){let t=e.values.filter((e=>!(e instanceof p||e instanceof te))).map((e=>De(Ge(new Le(`calc`,e)))));return e.name===`min`?new CSSMathMin(...t):new CSSMathMax(...t)}if(e.name!==`calc`)return null;let n=We(function(e){let n=[],r=[];for(;e.length;){let i=e.shift();if(i instanceof u||i instanceof f||i instanceof d||i instanceof Le||i instanceof Re||i instanceof t)r.push(i);else if(i instanceof l&&[`*`,`/`,`+`,`-`].includes(i.value)){for(;n.length&&!(He(n)instanceof re)&&Ve(He(n))>Ve(i);){let e=n.pop(),t=r.pop(),i=r.pop();r.push(Ue(e,i,t))}n.push(i)}else if(i instanceof re)n.push(i);else if(i instanceof v){if(!n.length)return null;for(;!(He(n)instanceof re);){let e=n.pop(),t=r.pop(),i=r.pop();r.push(Ue(e,i,t))}if(!(He(n)instanceof re))return null;n.pop()}else if(!(i instanceof p))return null}for(;n.length;){if(He(n)instanceof re)return null;let e=n.pop(),t=r.pop(),i=r.pop();r.push(Ue(e,i,t))}return r[0]}([...e.values])),r;try{r=De(n)}catch{new CSSStyleSheet().insertRule(`error`,0)}return r instanceof CSSUnitValue?new CSSMathSum(r):r}function Ke(e){return e instanceof Le&&[`calc`,`min`,`max`,`clamp`].includes(e.name)?Ge(e):e instanceof u&&e.value===0&&!e.unit?new CSSUnitValue(0,`px`):e instanceof u?new CSSUnitValue(e.value,`number`):e instanceof d?new CSSUnitValue(e.value,`percent`):e instanceof f?new CSSUnitValue(e.value,e.unit):void 0}function qe(e){let t=function(e){let t=ze(e);for(;t[0]instanceof p;)t.shift();if(t[0]===void 0)return null;let n=Be(t);for(;t[0]instanceof p;)t.shift();return t[0]===void 0?n:null}(e);return t===null&&new CSSStyleSheet().insertRule(`error`,0),t instanceof u||t instanceof d||t instanceof f||t instanceof Le||new CSSStyleSheet().insertRule(`error`,0),t instanceof f&&je(t.unit)===null&&new CSSStyleSheet().insertRule(`error`,0),Ke(t)}(function(){let e=new WeakMap;function t(e){let t=[];for(let r=0;re.type())).reduce(Ie)}},CSSMathNegate:class extends r{constructor(e){super([arguments[0]],`negate`,`-`)}get value(){return e.get(this).values[0]}type(){return this.value.type()}},CSSMathInvert:class extends r{constructor(e){super([1,arguments[0]],`invert`,`calc`,` / `)}get value(){return e.get(this).values[1]}type(){return function(e){let t={};for(let n of S)t[n]=-1*e[n];return t}(e.get(this).values[1].type())}},CSSMathMax:class extends r{constructor(){super(arguments,`max`)}},CSSMathMin:class extends r{constructor(){super(arguments,`min`)}}};if(!window.CSS&&!Reflect.defineProperty(window,`CSS`,{value:{}}))throw Error(`Error installing CSSOM support`);window.CSSUnitValue||`number.percent.em.ex.px.cm.mm.in.pt.pc.Q.vw.vh.vmin.vmax.rems.ch.deg.rad.grad.turn.ms.s.Hz.kHz.dppx.dpi.dpcm.fr`.split(`.`).forEach((e=>{if(!Reflect.defineProperty(CSS,e,{value:t=>new CSSUnitValue(t,e)}))throw Error(`Error installing CSS.${e}`)}));for(let[e,t]of Object.entries(i))if(!(e in window)&&!Reflect.defineProperty(window,e,{value:t}))throw Error(`Error installing CSSOM support for ${e}`)})();let w=`block`,T=new WeakMap,E=new WeakMap,Je=[`entry`,`exit`,`cover`,`contain`,`entry-crossing`,`exit-crossing`];function Ye(e){return e===document.scrollingElement?document:e}function Xe(e){$e(e);let t=T.get(e).animations;if(t.length===0)return;let n=e.currentTime;for(let e=0;e{for(let e of t.timelineRefs){let t=e.deref();t&&Xe(t)}t.updateScheduled=!1})),!0)}function it(e,t){let n=T.get(e),r=n.source;if(r!=t){if(r){let t=E.get(r);if(t){t.timelineRefs.delete(e);let n=Array.from(t.timelineRefs).filter((e=>e.deref()===void 0));for(let e of n)t.timelineRefs.delete(e);t.timelineRefs.size===0&&(t.disconnect(),E.delete(r))}}if(n.source=t,t){let r=E.get(t);if(!r){r={timelineRefs:new Set,sourceMeasurements:tt(t)},E.set(t,r);let e=new ResizeObserver((e=>{for(let t of e)rt(n.source)}));e.observe(t);for(let n of t.children)e.observe(n);let i=new MutationObserver((e=>{for(let t of e)rt(t.target)}));i.observe(t,{attributes:!0,attributeFilter:[`style`,`class`]});let a=()=>{r.sourceMeasurements.scrollLeft=t.scrollLeft,r.sourceMeasurements.scrollTop=t.scrollTop;for(let e of r.timelineRefs){let t=e.deref();t&&Xe(t)}};Ye(t).addEventListener(`scroll`,a),r.disconnect=()=>{e.disconnect(),i.disconnect(),Ye(t).removeEventListener(`scroll`,a)}}r.timelineRefs.add(new WeakRef(e))}}}function at(e,t){let n=T.get(e).animations;for(let e=0;e{Xe(e)}))}class D{constructor(e){if(T.set(this,{source:null,axis:w,anonymousSource:e?e.anonymousSource:null,anonymousTarget:e?e.anonymousTarget:null,subject:null,inset:null,animations:[],subjectMeasurements:null}),it(this,e&&e.source!==void 0?e.source:document.scrollingElement),e&&e.axis!==void 0&&e.axis!=w){if(!et(e.axis))throw TypeError(`Invalid axis`);T.get(this).axis=e.axis}Xe(this)}set source(e){it(this,e),Xe(this)}get source(){return T.get(this).source}set axis(e){if(!et(e))throw TypeError(`Invalid axis`);T.get(this).axis=e,Xe(this)}get axis(){return T.get(this).axis}get duration(){return CSS.percent(100)}get phase(){let e=this.source;if(!e)return`inactive`;let t=getComputedStyle(e);return t.display==`none`?`inactive`:e==document.scrollingElement||t.overflow!=`visible`&&t.overflow!=`clip`?`active`:`inactive`}get currentTime(){let e=this.source;if(!e||!e.isConnected||this.phase==`inactive`)return null;let t=getComputedStyle(e);if(t.display===`inline`||t.display===`none`)return null;let n=this.axis,r=Ze(e,n),i=function(e,t){let n=E.get(e).sourceMeasurements,r=getComputedStyle(e).writingMode==`horizontal-tb`;return t===`block`?t=r?`y`:`x`:t===`inline`&&(t=r?`x`:`y`),t===`y`?n.scrollHeight-n.clientHeight:t===`x`?n.scrollWidth-n.clientWidth:void 0}(e,n);return i>0?CSS.percent(100*r/i):CSS.percent(100)}get __polyfill(){return!0}}function O(e,t){let n=e.parentElement;for(;n!=null;){if(t(n))return n;n=n.parentElement}}function st(e,t){switch(e){case`root`:return document.scrollingElement;case`nearest`:return ut(t);case`self`:return t;default:throw TypeError(`Invalid ScrollTimeline Source Type.`)}}function ct(e){switch(getComputedStyle(e).display){case`block`:case`inline-block`:case`list-item`:case`table`:case`table-caption`:case`flow-root`:case`flex`:case`grid`:return!0}return!1}function lt(e){let t=getComputedStyle(e);return t.transform!=`none`||t.perspective!=`none`||t.willChange==`transform`||t.willChange==`perspective`||t.filter!=`none`||t.willChange==`filter`||t.backdropFilter!=`none`}function k(e){return getComputedStyle(e).position!=`static`||lt(e)}function A(e){switch(getComputedStyle(e).position){case`static`:case`relative`:case`sticky`:return O(e,ct);case`absolute`:return O(e,k);case`fixed`:return O(e,lt)}}function ut(e){if(e&&e.isConnected){for(;e=A(e);)switch(getComputedStyle(e)[`overflow-x`]){case`auto`:case`scroll`:case`hidden`:return e==document.body&&getComputedStyle(document.scrollingElement).overflow==`visible`?document.scrollingElement:e}return document.scrollingElement}}function j(e,t){let n=T.get(e),r=n.subjectMeasurements,i=E.get(n.source).sourceMeasurements;return e.phase===`inactive`?null:e instanceof pt?dt(t,i,r,n.axis,n.inset):null}function dt(e,t,n,r,i){let a=t.direction==`rtl`||t.writingMode==`vertical-rl`,o,s,c={fontSize:n.fontSize};we(r,t)===`x`?(o=n.offsetWidth,s=n.left,c.scrollPadding=[t.scrollPaddingLeft,t.scrollPaddingRight],a&&(s+=t.scrollWidth-t.clientWidth,c.scrollPadding=[t.scrollPaddingRight,t.scrollPaddingLeft]),c.containerSize=t.clientWidth):(o=n.offsetHeight,s=n.top,c.scrollPadding=[t.scrollPaddingTop,t.scrollPaddingBottom],c.containerSize=t.clientHeight);let l=function(e,t){let n={start:0,end:0};if(!e)return n;let[r,i]=[e.start,e.end].map(((e,n)=>e===`auto`?t.scrollPadding[n]===`auto`?0:parseFloat(t.scrollPadding[n]):Qe(e,{percentageReference:CSS.px(t.containerSize),fontSize:CSS.px(parseFloat(t.fontSize))})));return{start:r,end:i}}(i,c),u=s-c.containerSize+l.end,d=s+o-l.start,f=u+o,p=d-o,m=Math.min(f,p),ee=Math.max(f,p),h,g,te=o>c.containerSize-l.start-l.end;switch(e){case`cover`:h=u,g=d;break;case`contain`:h=m,g=ee;break;case`entry`:h=u,g=m;break;case`exit`:h=ee,g=d;break;case`entry-crossing`:h=u,g=te?ee:m;break;case`exit-crossing`:h=te?m:ee,g=d}return{start:h,end:g}}function ft(e,t){if(e instanceof pt){let{rangeName:n,offset:r}=t;return M(j(e,n),r,j(e,`cover`),e.subject)}if(e instanceof D){let{axis:n,source:r}=e,{sourceMeasurements:i}=E.get(r),a;return a=we(n,i)===`x`?i.scrollWidth-i.clientWidth:i.scrollHeight-i.clientHeight,Qe(t,{percentageReference:CSS.px(a)})/a}unsupportedTimeline(e)}function M(e,t,n,r){if(!e||!n)return 0;let i=getComputedStyle(r);return(Qe(t,{percentageReference:CSS.px(e.end-e.start),fontSize:CSS.px(parseFloat(i.fontSize))})+e.start-n.start)/(n.end-n.start)}let pt=class extends D{constructor(e){super(e);let t=T.get(this);t.subject=e&&e.subject?e.subject:void 0,e&&e.inset&&(t.inset=function(e){if(!e)return{start:0,end:0};let t;if(t=typeof e==`string`?x(e).map((t=>{if(t===`auto`)return`auto`;try{return CSSNumericValue.parse(t)}catch{throw TypeError(`Could not parse inset "${e}"`)}})):Array.isArray(e)?e:[e],t.length===0||t.length>2)throw TypeError(`Invalid inset`);for(let e of t){if(e===`auto`)continue;let t=e.type();if(t.length!==1&&t.percent!==1)throw TypeError(`Invalid inset`)}return{start:t[0],end:t[1]??t[0]}}(e.inset)),t.subject&&(new ResizeObserver((()=>{rt(t.source)})).observe(t.subject),new MutationObserver((()=>{rt(t.source)})).observe(t.subject,{attributes:!0,attributeFilter:[`class`,`style`]})),$e(this),t.subjectMeasurements=nt(t.source,t.subject),Xe(this)}get source(){return $e(this),T.get(this).source}set source(e){throw Error(`Cannot set the source of a view timeline`)}get subject(){return T.get(this).subject}get axis(){return T.get(this).axis}get currentTime(){let e=Ze(this.source,this.axis);if(e==null)return null;let t=j(this,`cover`);if(!t)return null;let n=(e-t.start)/(t.end-t.start);return CSS.percent(100*n)}get startOffset(){return CSS.px(j(this,`cover`).start)}get endOffset(){return CSS.px(j(this,`cover`).end)}},mt=document.getAnimations,ht=window.Element.prototype.getAnimations,gt=window.Element.prototype.animate,_t=window.Animation;class N{constructor(){this.state=`pending`,this.nativeResolve=this.nativeReject=null,this.promise=new Promise(((e,t)=>{this.nativeResolve=e,this.nativeReject=t}))}resolve(e){this.state=`resolved`,this.nativeResolve(e)}reject(e){this.state=`rejected`,this.promise.catch((()=>{})),this.nativeReject(e)}}function P(e){e.readyPromise=new N,requestAnimationFrame((()=>{(e.timeline?.currentTime??null)!==null&&(Nt(e),e.pendingTask!==`play`||e.startTime===null&&e.holdTime===null?e.pendingTask===`pause`&&bt(e):yt(e))}))}function F(){return new DOMException(`The user aborted a request`,`AbortError`)}function vt(e,t){if(t===null)return t;if(typeof t!=`number`)throw new DOMException(`Unexpected value: ${t}. Cannot convert to CssNumberish`,`InvalidStateError`);let n=e.rangeDuration??100,r=Et(e),i=r?n*t/r:0;return CSS.percent(i)}function I(e,t){if(e.timeline){if(t===null)return t;if(t.unit===`percent`){let n=e.rangeDuration??100,r=Et(e);return t.value*r/n}throw new DOMException(`CSSNumericValue must be a percentage for progress based animations.`,`NotSupportedError`)}{if(t==null||typeof t==`number`)return t;let e=t.to(`ms`);if(e)return e.value;throw new DOMException(`CSSNumericValue must be either a number or a time value for time based animations.`,`InvalidStateError`)}}function yt(e){let t=I(e,e.timeline.currentTime);if(e.holdTime!=null)Ct(e),e.animation.playbackRate==0?e.startTime=t:(e.startTime=t-e.holdTime/e.animation.playbackRate,e.holdTime=null);else if(e.startTime!==null&&e.pendingPlaybackRate!==null){let n=(t-e.startTime)*e.animation.playbackRate;Ct(e);let r=e.animation.playbackRate;r==0?(e.holdTime=null,e.startTime=t):e.startTime=t-n/r}e.readyPromise&&e.readyPromise.state==`pending`&&e.readyPromise.resolve(e.proxy),Tt(e,!1,!1),Dt(e),e.pendingTask=null}function bt(e){let t=I(e,e.timeline.currentTime);e.startTime!=null&&e.holdTime==null&&(e.holdTime=(t-e.startTime)*e.animation.playbackRate),Ct(e),e.startTime=null,e.readyPromise.resolve(e.proxy),Tt(e,!1,!1),Dt(e),e.pendingTask=null}function xt(e){if(!e.finishedPromise||e.finishedPromise.state!=`pending`||e.proxy.playState!=`finished`)return;e.finishedPromise.resolve(e.proxy),e.animation.pause();let t=new CustomEvent(`finish`,{detail:{currentTime:e.proxy.currentTime,timelineTime:e.proxy.timeline.currentTime}});Object.defineProperty(t,`currentTime`,{get:function(){return this.detail.currentTime}}),Object.defineProperty(t,`timelineTime`,{get:function(){return this.detail.timelineTime}}),requestAnimationFrame((()=>{queueMicrotask((()=>{e.animation.dispatchEvent(t)}))}))}function St(e){return e.pendingPlaybackRate===null?e.animation.playbackRate:e.pendingPlaybackRate}function Ct(e){e.pendingPlaybackRate!==null&&(e.animation.playbackRate=e.pendingPlaybackRate,e.pendingPlaybackRate=null)}function wt(e){if(!e.timeline)return null;let t=I(e,e.timeline.currentTime);if(t===null||e.startTime===null)return null;let n=(t-e.startTime)*e.animation.playbackRate;return n==-0&&(n=0),n}function Tt(e,t,n){if(!e.timeline)return;let r=t?I(e,e.proxy.currentTime):wt(e);if(r&&e.startTime!=null&&!e.proxy.pending){let n=St(e),i=Et(e),a=e.previousCurrentTime;n>0&&r>=i&&e.previousCurrentTime!=null?((a===null||a0)&&(a=0),e.holdTime=t?r:a):n!=0&&(t&&e.holdTime!==null&&(e.startTime=function(e,t){if(!e.timeline)return null;let n=I(e,e.timeline.currentTime);return n==null?null:n-t/e.animation.playbackRate}(e,e.holdTime)),e.holdTime=null)}Dt(e),e.previousCurrentTime=I(e,e.proxy.currentTime),e.proxy.playState==`finished`?(e.finishedPromise||=new N,e.finishedPromise.state==`pending`&&(n?xt(e):Promise.resolve().then((()=>{xt(e)})))):(e.finishedPromise&&e.finishedPromise.state==`resolved`&&(e.finishedPromise=new N),e.animation.playState!=`paused`&&e.animation.pause())}function Et(e){let t=function(e){let t=e.proxy.effect.getTiming();return e.normalizedTiming||t}(e),n=t.delay+t.endDelay+t.iterations*t.duration;return Math.max(0,n)}function Dt(e){if(e.timeline)if(e.startTime!==null){let t=e.timeline.currentTime;if(t==null)return;Ot(e,(I(e,t)-e.startTime)*e.animation.playbackRate)}else e.holdTime!==null&&Ot(e,e.holdTime)}function Ot(e,t){let n=e.timeline,r=e.animation.playbackRate,i=n.currentTime&&n.currentTime.value==(r<0?0:100)?r<0?.001:-.001:0;e.animation.currentTime=t+i}function kt(e,t){if(!e.timeline)return;let n=e.proxy.playState==`paused`&&e.proxy.pending,r=!1,i=I(e,e.proxy.currentTime);St(e)==0&&i==null&&(e.holdTime=0),i??(e.autoAlignStartTime=!0),(e.proxy.playState===`finished`||n)&&(e.holdTime=null,e.startTime=null,e.autoAlignStartTime=!0),e.holdTime&&(e.startTime=null),e.pendingTask&&(e.pendingTask=null,r=!0),(e.holdTime!==null||e.autoAlignStartTime||n||e.pendingPlaybackRate!==null)&&(e.readyPromise&&!r&&(e.readyPromise=null),Dt(e),e.readyPromise||P(e),e.pendingTask=`play`,ot(e.timeline,e.animation,At.bind(e.proxy)),Tt(e,!1,!1))}function At(e){let t=L.get(this);if(!t)return;if(e==null)return void(t.proxy.playState!==`paused`&&t.animation.playState!=`idle`&&t.animation.cancel());Nt(t),t.pendingTask&&requestAnimationFrame((()=>{t.pendingTask!==`play`||t.startTime===null&&t.holdTime===null?t.pendingTask===`pause`&&bt(t):yt(t)}));let n=this.playState;(n==`running`||n==`finished`)&&(Ot(t,(I(t,e)-I(t,this.startTime))*this.playbackRate),Tt(t,!1,!1))}function jt(e){e.specifiedTiming=null}let L=new WeakMap;window.addEventListener(`pagehide`,(e=>{L=new WeakMap}),!1);let Mt=new WeakMap;function Nt(e){if(!e.autoAlignStartTime||!e.timeline||!e.timeline.currentTime||e.proxy.playState===`idle`||e.proxy.playState===`paused`&&e.holdTime!==null)return;let t=e.rangeDuration,n,r;try{n=CSS.percent(100*function(e){if(!e.animationRange)return 0;let t=e.animationRange.start===`normal`?Ft(e.timeline):e.animationRange.start;return ft(e.timeline,t)}(e))}catch(t){n=CSS.percent(0),e.animationRange.start=`normal`,console.warn(`Exception when calculating start offset`,t)}try{r=CSS.percent(100*(1-function(e){if(!e.animationRange)return 0;let t=e.animationRange.end===`normal`?It(e.timeline):e.animationRange.end;return 1-ft(e.timeline,t)}(e)))}catch(t){r=CSS.percent(100),e.animationRange.end=`normal`,console.warn(`Exception when calculating end offset`,t)}e.rangeDuration=r.value-n.value,e.startTime=I(e,St(e)>=0?n:r),e.holdTime=null,e.rangeDuration!==t&&jt(e)}function Pt(e){throw Error(`Unsupported timeline class`)}function Ft(e){return e instanceof ViewTimeline?{rangeName:`cover`,offset:CSS.percent(0)}:e instanceof D?CSS.percent(0):void Pt()}function It(e){return e instanceof ViewTimeline?{rangeName:`cover`,offset:CSS.percent(100)}:e instanceof D?CSS.percent(100):void Pt()}function Lt(e,t){if(!t)return{start:`normal`,end:`normal`};let n={start:Ft(e),end:It(e)};if(e instanceof ViewTimeline){let e=x(t),r=[],i=[];if(e.forEach((e=>{if(Je.includes(e))r.push(e);else try{i.push(CSSNumericValue.parse(e))}catch{throw TypeError(`Could not parse range "${t}"`)}})),r.length>2||i.length>2||i.length==1)throw TypeError(`Invalid time range or unsupported time range format.`);return r.length&&(n.start.rangeName=r[0],n.end.rangeName=r.length>1?r[1]:r[0]),i.length>1&&(n.start.offset=i[0],n.end.offset=i[1]),n}if(e instanceof D){let e=t.split(` `);if(e.length!=2)throw TypeError(`Invalid time range or unsupported time range format.`);return n.start=CSSNumericValue.parse(e[0]),n.end=CSSNumericValue.parse(e[1]),n}Pt()}function Rt(e,t,n){if(!t||t===`normal`)return`normal`;if(e instanceof ViewTimeline){let e=`cover`,r=n===`start`?CSS.percent(0):CSS.percent(100);if(t instanceof Object)t.rangeName!==void 0&&(e=t.rangeName),t.offset!==void 0&&(r=t.offset);else{let n=x(t);n.length===1?Je.includes(n[0])?e=n[0]:r=De(CSSNumericValue.parse(n[0]),{}):n.length===2&&(e=n[0],r=De(CSSNumericValue.parse(n[1]),{}))}if(!Je.includes(e))throw TypeError(`Invalid range name`);return{rangeName:e,offset:r}}if(e instanceof D)return CSSNumericValue.parse(t);Pt()}class zt{constructor(e,t,n={}){let r=t instanceof D,i=e instanceof _t?e:new _t(e,r?void 0:t);Mt.set(i,this),L.set(this,{animation:i,timeline:r?t:void 0,playState:r?`idle`:null,readyPromise:null,finishedPromise:null,startTime:null,holdTime:null,rangeDuration:null,previousCurrentTime:null,autoAlignStartTime:!1,pendingPlaybackRate:null,pendingTask:null,specifiedTiming:null,normalizedTiming:null,effect:null,animationRange:r?Lt(t,n[`animation-range`]):null,proxy:this})}get effect(){let e=L.get(this);return e.timeline?(e.effect||=function(e){let t=e.animation.effect,n=t.updateTiming,r={apply:function(n){t.getTiming();let r=n.apply(t);if(e.timeline){let t=e.duration??100;r.localTime=vt(e,r.localTime),r.endTime=vt(e,r.endTime),r.activeDuration=vt(e,r.activeDuration);let n=Et(e),i=r.iterations?(n-r.delay-r.endDelay)/r.iterations:0;r.duration=n?CSS.percent(t*i/n):CSS.percent(0),e.timeline.currentTime===void 0&&(r.localTime=null)}return r}},i={apply:function(r,i){if(e.specifiedTiming)return e.specifiedTiming;e.specifiedTiming=r.apply(t);let a,o=Object.assign({},e.specifiedTiming);if(o.duration===1/0)throw TypeError(`Effect duration cannot be Infinity when used with Scroll Timelines`);return(o.duration===null||o.duration===`auto`||e.autoDurationEffect)&&e.timeline&&(e.autoDurationEffect=!0,o.delay=0,o.endDelay=0,a=o.iterations?1e5:0,o.duration=o.iterations?(a-o.delay-o.endDelay)/o.iterations:0,o.duration<0&&(o.duration=0,o.endDelay=a-o.delay),n.apply(t,[o])),e.normalizedTiming=o,e.specifiedTiming}},a={apply:function(n,r,i){if(i&&i.length){if(e.timeline&&i[0]){let t=i[0],n=t.duration;if(n===1/0)throw TypeError(`Effect duration cannot be Infinity when used with Scroll Timelines`);if(t.iterations===1/0)throw TypeError(`Effect iterations cannot be Infinity when used with Scroll Timelines`);n!==void 0&&n!==`auto`&&(e.autoDurationEffect=null)}e.specifiedTiming&&n.apply(t,[e.specifiedTiming]),n.apply(t,i),jt(e)}}},o=new Proxy(t,{get:function(e,n){let r=e[n];return typeof r==`function`?r.bind(t):r},set:function(e,t,n){return e[t]=n,!0}});return o.getComputedTiming=new Proxy(t.getComputedTiming,r),o.getTiming=new Proxy(t.getTiming,i),o.updateTiming=new Proxy(t.updateTiming,a),o}(e),e.effect):e.animation.effect}set effect(e){let t=L.get(this);t.animation.effect=e,t.effect=null,t.autoDurationEffect=null}get timeline(){let e=L.get(this);return e.timeline||e.animation.timeline}set timeline(e){let t=L.get(this),n=this.timeline;if(n==e)return;let r=this.playState,i=this.currentTime,a,o=Et(t);a=i===null?null:o===0?0:I(t,i)/o;let s=n instanceof D,c=e instanceof D,l=this.pending;if(s&&at(t.timeline,t.animation),c)return t.timeline=e,Ct(t),t.autoAlignStartTime=!0,t.startTime=null,t.holdTime=null,r!==`running`&&r!==`finished`||(t.readyPromise&&t.readyPromise.state!==`resolved`||P(t),t.pendingTask=`play`,ot(t.timeline,t.animation,At.bind(this))),r===`paused`&&a!==null&&(t.holdTime=a*o),l&&(t.readyPromise&&t.readyPromise.state!=`resolved`||P(t),t.pendingTask=r==`paused`?`pause`:`play`),t.startTime!==null&&(t.holdTime=null),void Tt(t,!1,!1);if(t.animation.timeline!=e)throw TypeError(`Unsupported timeline: `+e);if(at(t.timeline,t.animation),t.timeline=null,s)switch(i!==null&&(t.animation.currentTime=a*Et(t)),r){case`paused`:t.animation.pause();break;case`running`:case`finished`:t.animation.play()}}get startTime(){let e=L.get(this);return e.timeline?vt(e,e.startTime):e.animation.startTime}set startTime(e){let t=L.get(this);if(e=I(t,e),!t.timeline)return void(t.animation.startTime=e);t.autoAlignStartTime=!1,I(t,t.timeline.currentTime)==null&&t.startTime!=null&&(t.holdTime=null,Dt(t));let n=I(t,this.currentTime);Ct(t),t.startTime=e,t.startTime!==null&&t.animation.playbackRate!=0?t.holdTime=null:t.holdTime=n,t.pendingTask&&(t.pendingTask=null,t.readyPromise.resolve(this)),Tt(t,!0,!1),Dt(t)}get currentTime(){let e=L.get(this);return e.timeline?e.holdTime==null?vt(e,wt(e)):vt(e,e.holdTime):e.animation.currentTime}set currentTime(e){let t=L.get(this);t.timeline?(function(e,t){if(t==null&&e.currentTime!==null)throw TypeError();t=I(e,t),e.autoAlignStartTime=!1,e.holdTime!==null||e.startTime===null||e.timeline.phase===`inactive`||e.animation.playbackRate===0?e.holdTime=t:e.startTime=I(e,e.timeline.currentTime)-t/e.animation.playbackRate,e.timeline.phase===`inactive`&&(e.startTime=null),e.previousCurrentTime=null}(t,e),t.pendingTask==`pause`&&(t.holdTime=I(t,e),Ct(t),t.startTime=null,t.pendingTask=null,t.readyPromise.resolve(this)),Tt(t,!0,!1)):t.animation.currentTime=e}get playbackRate(){return L.get(this).animation.playbackRate}set playbackRate(e){let t=L.get(this);if(!t.timeline)return void(t.animation.playbackRate=e);t.pendingPlaybackRate=null;let n=this.currentTime;t.animation.playbackRate=e,n!==null&&(this.currentTime=n)}get playState(){let e=L.get(this);if(!e.timeline)return e.animation.playState;let t=I(e,this.currentTime);return t===null&&e.startTime===null&&e.pendingTask==null?`idle`:e.pendingTask==`pause`||e.startTime===null&&e.pendingTask!=`play`?`paused`:t!=null&&(e.animation.playbackRate>0&&t>=Et(e)||e.animation.playbackRate<0&&t<=0)?`finished`:`running`}get rangeStart(){return L.get(this).animationRange?.start??`normal`}set rangeStart(e){let t=L.get(this);if(!t.timeline)return t.animation.rangeStart=e;t.timeline instanceof D&&(t.animationRange.start=Rt(t.timeline,e,`start`),Nt(t),Dt(t))}get rangeEnd(){return L.get(this).animationRange?.end??`normal`}set rangeEnd(e){let t=L.get(this);if(!t.timeline)return t.animation.rangeEnd=e;t.timeline instanceof D&&(t.animationRange.end=Rt(t.timeline,e,`end`),Nt(t),Dt(t))}get replaceState(){return L.get(this).animation.pending}get pending(){let e=L.get(this);return e.timeline?!!e.readyPromise&&e.readyPromise.state==`pending`:e.animation.pending}finish(){let e=L.get(this);if(!e.timeline)return void e.animation.finish();let t=St(e),n=Et(e);if(t==0)throw new DOMException(`Cannot finish Animation with a playbackRate of 0.`,`InvalidStateError`);if(t>0&&n==1/0)throw new DOMException(`Cannot finish Animation with an infinite target effect end.`,`InvalidStateError`);Ct(e);let r=t<0?0:n;this.currentTime=vt(e,r);let i=I(e,e.timeline.currentTime);e.startTime===null&&i!==null&&(e.startTime=i-r/e.animation.playbackRate),e.pendingTask==`pause`&&e.startTime!==null&&(e.holdTime=null,e.pendingTask=null,e.readyPromise.resolve(this)),e.pendingTask==`play`&&e.startTime!==null&&(e.pendingTask=null,e.readyPromise.resolve(this)),Tt(e,!0,!0)}play(){let e=L.get(this);e.timeline?kt(e):e.animation.play()}pause(){let e=L.get(this);e.timeline?this.playState!=`paused`&&(e.animation.currentTime===null&&(e.autoAlignStartTime=!0),e.pendingTask==`play`?e.pendingTask=null:e.readyPromise=null,e.readyPromise||P(e),e.pendingTask=`pause`,ot(e.timeline,e.animation,At.bind(e.proxy))):e.animation.pause()}reverse(){let e=L.get(this),t=St(e),n=I(e,this.currentTime),r=Et(e)==1/0,i=t!=0&&(t<0||n>0||!r);if(!e.timeline||!i)return i&&(e.pendingPlaybackRate=-St(e)),void e.animation.reverse();if(e.timeline.phase==`inactive`)throw new DOMException(`Cannot reverse an animation with no active timeline`,`InvalidStateError`);this.updatePlaybackRate(-t),kt(e)}updatePlaybackRate(e){let t=L.get(this);if(t.pendingPlaybackRate=e,!t.timeline)return void t.animation.updatePlaybackRate(e);let n=this.playState;if(!t.readyPromise||t.readyPromise.state!=`pending`)switch(n){case`idle`:case`paused`:Ct(t);break;case`finished`:let n=I(t,t.timeline.currentTime),r=n===null?null:(n-t.startTime)*t.animation.playbackRate;t.startTime=e==0?n:n!=null&&r!=null?(n-r)/e:null,Ct(t),Tt(t,!1,!1),Dt(t);break;default:kt(t)}}persist(){L.get(this).animation.persist()}get id(){return L.get(this).animation.id}set id(e){L.get(this).animation.id=e}cancel(){let e=L.get(this);e.timeline?(this.playState!=`idle`&&(function(e){e.pendingTask&&(e.pendingTask=null,Ct(e),e.readyPromise.reject(F()),P(e),e.readyPromise.resolve(e.proxy))}(e),e.finishedPromise&&e.finishedPromise.state==`pending`&&e.finishedPromise.reject(F()),e.finishedPromise=new N,e.animation.cancel()),e.startTime=null,e.holdTime=null,at(e.timeline,e.animation)):e.animation.cancel()}get onfinish(){return L.get(this).animation.onfinish}set onfinish(e){L.get(this).animation.onfinish=e}get oncancel(){return L.get(this).animation.oncancel}set oncancel(e){L.get(this).animation.oncancel=e}get onremove(){return L.get(this).animation.onremove}set onremove(e){L.get(this).animation.onremove=e}get finished(){let e=L.get(this);return e.timeline?(e.finishedPromise||=new N,e.finishedPromise.promise):e.animation.finished}get ready(){let e=L.get(this);return e.timeline?(e.readyPromise||(e.readyPromise=new N,e.readyPromise.resolve(this)),e.readyPromise.promise):e.animation.ready}addEventListener(e,t,n){L.get(this).animation.addEventListener(e,t,n)}removeEventListener(e,t,n){L.get(this).animation.removeEventListener(e,t,n)}dispatchEvent(e){L.get(this).animation.dispatchEvent(e)}}function R(e,t){let n=t.timeline;n instanceof D&&delete t.timeline;let r=gt.apply(this,[e,t]),i=new zt(r,n);return n instanceof D&&(r.pause(),L.get(i).animationRange={start:Rt(n,t.rangeStart,`start`),end:Rt(n,t.rangeEnd,`end`)},i.play()),i}function Bt(e){for(let t=0;t=r.sheetSrc.length));){if(this.lookAhead(`/*`,r)){for(;this.lookAhead(`/*`,r);)this.eatComment(r),this.eatWhitespace(r);continue}let e=this.parseQualifiedRule(r);e&&(t?this.parseKeyframesAndSaveNameMapping(e,r):this.handleScrollTimelineProps(e,r))}return r.sheetSrc}getAnimationTimelineOptions(e,t){for(let n=this.cssRulesWithTimelineName.length-1;n>=0;n--){let r=this.cssRulesWithTimelineName[n];try{if(t.matches(r.selector)&&(!r[`animation-name`]||r[`animation-name`]==e))return{"animation-timeline":r[`animation-timeline`],"animation-range":r[`animation-range`]}}catch{}}return null}getAnonymousScrollTimelineOptions(e,t){let n=this.anonymousScrollTimelineOptions.get(e);return n?{anonymousSource:n.source,anonymousTarget:t,source:st(n.source??`nearest`,t),axis:n.axis?n.axis:`block`}:null}getScrollTimelineOptions(e,t){let n=this.getAnonymousScrollTimelineOptions(e,t);if(n)return n;for(let n=this.sourceSelectorToScrollTimeline.length-1;n>=0;n--){let r=this.sourceSelectorToScrollTimeline[n];if(r.name==e){let e=this.findPreviousSiblingOrAncestorMatchingSelector(t,r.selector);if(e)return{source:e,...r.axis?{axis:r.axis}:{}}}}return null}findPreviousSiblingOrAncestorMatchingSelector(e,t){let n=e;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling||n.parentElement}return null}getAnonymousViewTimelineOptions(e,t){let n=this.anonymousViewTimelineOptions.get(e);return n?{subject:t,axis:n.axis?n.axis:`block`,inset:n.inset?n.inset:`auto`}:null}getViewTimelineOptions(e,t){let n=this.getAnonymousViewTimelineOptions(e,t);if(n)return n;for(let n=this.subjectSelectorToViewTimeline.length-1;n>=0;n--){let r=this.subjectSelectorToViewTimeline[n];if(r.name==e){let e=this.findPreviousSiblingOrAncestorMatchingSelector(t,r.selector);if(e)return{subject:e,axis:r.axis,inset:r.inset}}}return null}handleScrollTimelineProps(e,t){if(e.selector.includes(`@keyframes`))return;let n=e.block.contents.includes(`animation-name:`),r=e.block.contents.includes(`animation-timeline:`),i=e.block.contents.includes(`animation:`);if(this.saveSourceSelectorToScrollTimeline(e),this.saveSubjectSelectorToViewTimeline(e),!r&&!n&&!i)return;let a=[],o=[],s=!1;r&&(a=this.extractScrollTimelineNames(e.block.contents)),n&&(o=this.extractMatches(e.block.contents,B.ANIMATION_NAME)),r&&n||(i&&this.extractMatches(e.block.contents,B.ANIMATION).forEach((t=>{let n=this.extractAnimationName(t);n&&r&&o.push(n),r&&(this.hasDuration(t)||(this.hasAutoDuration(t)&&(e.block.contents=e.block.contents.replace(`auto`,` `)),e.block.contents=e.block.contents.replace(t,` 1s `+t),s=!0))})),s&&this.replacePart(e.block.startIndex,e.block.endIndex,e.block.contents,t)),this.saveRelationInList(e,a,o)}saveSourceSelectorToScrollTimeline(e){let t=e.block.contents.includes(`scroll-timeline:`),n=e.block.contents.includes(`scroll-timeline-name:`),r=e.block.contents.includes(`scroll-timeline-axis:`);if(!t&&!n)return;let i=[];if(t){let t=this.extractMatches(e.block.contents,B.SCROLL_TIMELINE);for(let n of t){let t=this.split(n),r={selector:e.selector,name:``};t.length==1?r.name=t[0]:t.length==2&&(Ht.includes(t[0])?(r.axis=t[0],r.name=t[1]):(r.axis=t[1],r.name=t[0])),i.push(r)}}if(n){let t=this.extractMatches(e.block.contents,B.SCROLL_TIMELINE_NAME);for(let n=0;nHt.includes(e))),a.length!=t.length)throw Error(`Invalid axis`)}for(let e=0;eHt.includes(e))),s.length!=t.length)throw Error(`Invalid axis`)}for(let e=0;e{return t=e,B.TIME.exec(t);var t})).length>=1}hasAutoDuration(e){return e.split(` `).filter((e=>e===`auto`)).length>=1}saveRelationInList(e,t,n){let r=[];e.block.contents.includes(`animation-range:`)&&(r=this.extractMatches(e.block.contents,B.ANIMATION_TIME_RANGE));let i=Math.max(t.length,n.length,r.length);for(let a=0;ae.trim())).forEach((e=>{if(function(e){return(e.startsWith(`scroll`)||e.startsWith(`view`))&&e.includes(`(`)}(e)){let t=this.saveAnonymousTimelineName(e);n.push(t)}else n.push(e)})),n}saveAnonymousTimelineName(e){let t=`:t`+ this.nextAnonymousTimelineNameIndex++;return e.startsWith(`scroll(`)?this.anonymousScrollTimelineOptions.set(t,this.parseAnonymousScrollTimeline(e)):this.anonymousViewTimelineOptions.set(t,this.parseAnonymousViewTimeline(e)),t}parseAnonymousScrollTimeline(e){let t=B.ANONYMOUS_SCROLL_TIMELINE.exec(e);if(!t)return null;let n=t[1],r={};return n.split(` `).forEach((e=>{Ht.includes(e)?r.axis=e:Ut.includes(e)&&(r.source=e)})),r}parseAnonymousViewTimeline(e){let t=B.ANONYMOUS_VIEW_TIMELINE.exec(e);if(!t)return null;let n=t[1],r={};return n.split(` `).forEach((e=>{Ht.includes(e)?r.axis=e:r.inset=r.inset?`${r.inset} ${e}`:e})),r}extractAnimationName(e){return this.findMatchingEntryInContainer(e,this.keyframeNamesSelectors)}findMatchingEntryInContainer(e,t){let n=e.split(` `).filter((e=>t.has(e)));return n?n[0]:null}parseIdentifier(e){B.IDENTIFIER.lastIndex=e.index;let t=B.IDENTIFIER.exec(e.sheetSrc);if(!t)throw this.parseError(e,`Expected an identifier`);return e.index+=t[0].length,t[0]}parseKeyframesAndSaveNameMapping(e,t){if(e.selector.startsWith(`@keyframes`)){let n=this.replaceKeyframesAndGetMapping(e,t);e.selector.split(` `).forEach(((e,t)=>{t>0&&this.keyframeNamesSelectors.set(e,n)}))}}replaceKeyframesAndGetMapping(e,t){function n(e){return Je.some((t=>e.startsWith(t)))}let r=e.block.contents,i=function(e){let t=0,n=-1,r=-1,i=[];for(let a=0;a{let t=e.split(` `).map((e=>e.trim())).filter((e=>e!=``)).join(` `),r=a.size;a.set(r,t),c.push(`${r}%`),n(t)&&(o=!0)})),s.push(c.join(`,`)),e==i.length-1?s.push(r.substring(i[e].end)):s.push(r.substring(i[e].end,i[e+1].start))}return o?(e.block.contents=s.join(``),this.replacePart(e.block.startIndex,e.block.endIndex,e.block.contents,t),a):new Map}parseQualifiedRule(e){let t=e.index,n=this.parseSelector(e).trim();if(n)return{selector:n,block:this.eatBlock(e),startIndex:t,endIndex:e.index}}removeEnclosingDoubleQuotes(e){let t=+(e[0]==`"`),n=e[e.length-1]==`"`?e.length-1:e.length;return e.substring(t,n)}assertString(e,t){if(e.sheetSrc.substr(e.index,t.length)!=t)throw this.parseError(e,`Did not find expected sequence ${t}`);e.index+=t.length}replacePart(e,t,n,r){if(r.sheetSrc=r.sheetSrc.slice(0,e)+n+r.sheetSrc.slice(t),r.index>=t){let i=r.index-t;r.index=e+n.length+i}}eatComment(e){this.assertString(e,`/*`),this.eatUntil(`*/`,e,!0),this.assertString(e,`*/`)}eatBlock(e){let t=e.index;this.assertString(e,`{`);let n=1;for(;n!=0;)this.lookAhead(`/*`,e)?this.eatComment(e):(e.sheetSrc[e.index]===`{`?n++:e.sheetSrc[e.index]===`}`&&n--,this.advance(e));let r=e.index;return{startIndex:t,endIndex:r,contents:e.sheetSrc.slice(t,r)}}advance(e){if(e.index++,e.index>e.sheetSrc.length)throw this.parseError(e,`Advanced beyond the end`)}parseError(e,t){return Error(`(${e.name?e.name:``}): ${t}`)}eatUntil(e,t,n=!1){let r=t.index;for(;!this.lookAhead(e,t);)this.advance(t);return n&&(t.sheetSrc=t.sheetSrc.slice(0,r)+` `.repeat(t.index-r)+t.sheetSrc.slice(t.index)),t.sheetSrc.slice(r,t.index)}parseSelector(e){let t=e.index;if(this.eatUntil(`{`,e),t===e.index)throw Error(`Empty selector`);return e.sheetSrc.slice(t,e.index)}eatWhitespace(e){B.WHITE_SPACE.lastIndex=e.index;let t=B.WHITE_SPACE.exec(e.sheetSrc);t&&(e.index+=t[0].length)}lookAhead(e,t){return t.sheetSrc.substr(t.index,e.length)==e}peek(e){return e.sheetSrc[e.index]}extractMatches(e,t,n=`,`){return t.exec(e)[1].trim().split(n).map((e=>e.trim()))}split(e){return e.split(` `).map((e=>e.trim())).filter((e=>e!=``))}};function Gt(e,t,n,r,i,a){let o=tt(t),s=nt(t,n);return M(dt(e,o,s,r,i),a,dt(`cover`,o,s,r,i),n)}function Kt(e,t,n){let r=Wt.getAnimationTimelineOptions(t,n);if(!r)return null;let i=r[`animation-timeline`];if(!i)return null;let a=Wt.getScrollTimelineOptions(i,n)||Wt.getViewTimelineOptions(i,n);return a?(a.subject&&function(e,t){let n=ut(t.subject),r=t.axis||t.axis;function i(e,i){let a=null;for(let[o,s]of e)if(o==100*i.offset){if(s==`from`)a=0;else if(s==`to`)a=100;else{let e=s.split(` `);a=e.length==1?parseFloat(e[0]):100*Gt(e[0],n,t.subject,r,t.inset,CSS.percent(parseFloat(e[1])))}break}return a}let a=Wt.keyframeNamesSelectors.get(e.animationName);if(a&&a.size){let t=[];e.effect.getKeyframes().forEach((e=>{let n=i(a,e);n!==null&&n>=0&&n<=100&&(e.offset=n/100,t.push(e))}));let n=t.sort(((e,t)=>e.offsett.offset)));e.effect.setKeyframes(n)}}(e,a),{timeline:a.source?new D(a):new pt(a),animOptions:r}):null}function qt(){if(CSS.supports(`animation-timeline: --works`))return!0;(function(){function e(e){if(e.innerHTML.trim().length===0||`aphrodite`in e.dataset)return;let t=Wt.transpileStyleSheet(e.innerHTML,!0);t=Wt.transpileStyleSheet(t,!1),e.innerHTML=t}function t(e){e.type!=`text/css`&&e.rel!=`stylesheet`||!e.href||new URL(e.href,document.baseURI).origin==location.origin&&fetch(e.getAttribute(`href`)).then((async t=>{let n=await t.text(),r=Wt.transpileStyleSheet(n,!0);if(r=Wt.transpileStyleSheet(n,!1),r!=n){let t=new Blob([r],{type:`text/css`}),n=URL.createObjectURL(t);e.setAttribute(`href`,n)}}))}new MutationObserver((n=>{for(let r of n)for(let n of r.addedNodes)n instanceof HTMLStyleElement&&e(n),n instanceof HTMLLinkElement&&t(n)})).observe(document.documentElement,{childList:!0,subtree:!0}),document.querySelectorAll(`style`).forEach((t=>e(t))),document.querySelectorAll(`link`).forEach((e=>t(e)))})();let e=CSS.supports;CSS.supports=t=>(t=t.replaceAll(/(animation-timeline|scroll-timeline(-(name|axis))?|view-timeline(-(name|axis|inset))?|timeline-scope)\s*:/g,`--supported-property:`),e(t)),window.addEventListener(`animationstart`,(e=>{e.target.getAnimations().filter((t=>t.animationName===e.animationName)).forEach((t=>{let n=Kt(t,t.animationName,e.target);if(n)if(!n.timeline||t instanceof zt)t.timeline=n.timeline;else{let e=new zt(t,n.timeline,n.animOptions);t.pause(),e.play()}}))}))}(function(){if(!qt()){if(!Reflect.defineProperty(window,`ScrollTimeline`,{value:D}))throw Error(`Error installing ScrollTimeline polyfill: could not attach ScrollTimeline to window`);if(!Reflect.defineProperty(window,`ViewTimeline`,{value:pt}))throw Error(`Error installing ViewTimeline polyfill: could not attach ViewTimeline to window`);if(!Reflect.defineProperty(Element.prototype,`animate`,{value:R}))throw Error(`Error installing ScrollTimeline polyfill: could not attach WAAPI's animate to DOM Element`);if(!Reflect.defineProperty(window,`Animation`,{value:zt}))throw Error(`Error installing Animation constructor.`);if(!Reflect.defineProperty(Element.prototype,`getAnimations`,{value:z}))throw Error(`Error installing ScrollTimeline polyfill: could not attach WAAPI's getAnimations to DOM Element`);if(!Reflect.defineProperty(document,`getAnimations`,{value:Vt}))throw Error(`Error installing ScrollTimeline polyfill: could not attach WAAPI's getAnimations to document`)}})()})();var Ns=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},Ps=N(`debugscroll`),Fs=class extends R{target=null;damping=0;invert=!1;htmlSelector=null;mode=`window`;changed=new k;get currentValue(){return this._current_value}_current_value=0;_target_value=0;_appliedValue=-1;_needsUpdate=!1;_firstUpdate=!1;awake(){this._firstUpdate=!0}onEnable(){window.addEventListener(`wheel`,this.updateCurrentScrollValue,{passive:!0}),this._appliedValue=-1,this._needsUpdate=!0}onDisable(){window.removeEventListener(`wheel`,this.updateCurrentScrollValue)}lateUpdate(){if(this.updateCurrentScrollValue(),this._target_value>=0&&(this.damping>0&&!this._firstUpdate?(this._current_value=O.lerp(this._current_value,this._target_value,this.context.time.deltaTime/this.damping),Math.abs(this._current_value-this._target_value)<.001&&(this._current_value=this._target_value)):this._current_value=this._target_value),this._needsUpdate||this._current_value!==this._appliedValue){this._appliedValue=this._current_value,this._needsUpdate=!1;let e=!1;if(this.changed.listenerCount>0){let t={type:`change`,value:this._current_value,component:this,preventDefault:()=>{t.defaultPrevented=!0},defaultPrevented:!1};this.changed.invoke(t),e=t.defaultPrevented}if(!e){let e=this.invert?1-this._current_value:this._current_value;Array.isArray(this.target)?this.target.forEach(t=>t&&this.applyScroll(t,e)):this.target&&this.applyScroll(this.target,e),Ps&&this.context.time.frame%30==0&&console.debug(`[ScrollFollow] ${this._current_value.toFixed(5)} — ${(this._target_value*100).toFixed(0)}%, targets [${Array.isArray(this.target)?this.target.length:1}]`)}this._firstUpdate=!1}}_lastSelectorValue=null;_lastSelectorElement=null;updateCurrentScrollValue=()=>{switch(this.mode){case`window`:if(this.htmlSelector?.length){if(this.htmlSelector!==this._lastSelectorValue&&(this._lastSelectorElement=document.querySelector(this.htmlSelector),this._lastSelectorValue=this.htmlSelector),this._lastSelectorElement){let e=this._lastSelectorElement.getBoundingClientRect();this._target_value=-e.top/(e.height-window.innerHeight);break}}else if(!(window.document.body.scrollHeight<=window.innerHeight)){let e=window.document.body.scrollHeight-window.innerHeight;this._target_value=window.scrollY/(e||1)}break}(isNaN(this._target_value)||!isFinite(this._target_value))&&(this._target_value=-1)};applyScroll(e,t){if(e)if(e instanceof ti)this.handleTimelineTarget(e,t),e.isPlaying&&e.pause(),e.evaluate();else if(e instanceof it)e.setFloat(`scroll`,t);else if(e instanceof Qn)e.time=t*e.duration;else if(e instanceof Kn){if(!e.duration)return;e.time=t*e.duration}else if(e instanceof ts)e.position01=t;else if(e instanceof Y)e.intensity=t;else if(e instanceof y){let n=e;n[`needle:scrollbounds`]===void 0&&(n[`needle:scrollbounds`]=Nt(e)||null);let r=n[`needle:scrollbounds`];r&&(e.position.y=-r.min.y-t*(r.max.y-r.min.y))}else `scroll`in e&&(typeof e.scroll==`number`?e.scroll=t:typeof e.scroll==`function`&&e.scroll(t))}handleTimelineTarget(e,t){let n=e.duration,r=Is.get(e);if(!r){r=[],Is.set(e,r);let t=0;for(let n of e.foreachMarker(`ScrollMarker`)){let e=t++;if(n.element===void 0||n.needsUpdate===!0||n.element&&!n.element?.parentNode){n.needsUpdate=!1;try{if(n.element=Bs(e),Ps&&console.debug(`ScrollMarker #${e} (${n.time.toFixed(2)}) found`,n.element),!n.element){(Ps||w())&&console.warn(`No HTML element found for ScrollMarker: ${n.name} (index ${e})`);continue}}catch(e){n.element=null,console.error(`ScrollMarker selector is not valid: `+n.name+` `,e)}}n.element&&r.push(n)}r.length<=0&&document.querySelectorAll(`[data-timeline-marker]`).forEach(e=>{let t=e.getAttribute(`data-timeline-marker`),n=parseFloat(t||`NaN`);isNaN(n)?(w()||Ps)&&console.warn(`[ScrollFollow] data-timeline-marker attribute is not a valid number. Supported are numbers only (e.g.
)`):r.push({time:n,element:e})});for(let e of r)e.element&&(e.timeline=new ViewTimeline({subject:e.element,axis:`block`}))}Ls.length=0;let i=0,a=0;for(let e=0;e0&&a<=1){let e=t.time+(s-t.time)*a;Ls.push({name:l,time:e,weight:o}),i+=o}else e===0&&a<=0?(Ls.push({name:l,time:0,weight:1}),i+=1):e===r.length-1&&a>=1&&(Ls.push({name:l,time:n,weight:1}),i+=1)}}if(Ls.length<=0&&a<=0)e.time=t*n;else if(Ls.length>0){let t=Ls[0].time;if(Ls.length>1)for(let e of Ls){let n=e.weight/Math.max(1e-5,i),r=Math.abs(e.time-t);t+=r*n}this.damping<=0||this._firstUpdate?e.time=t:e.time=O.lerp(e.time,t,this.context.time.deltaTime/this.damping),Math.abs(e.time-t)>.001&&(this._needsUpdate=!0),Ps&&this.context.time.frame%30==0&&console.log(`[ScrollFollow ] Timeline ${e.name}: ${t.toFixed(3)}`,Ls.map(e=>`[${e.name} ${(e.weight*100).toFixed(0)}%]`).join(`, `))}}};Ns([A([R,y])],Fs.prototype,`target`,void 0),Ns([A()],Fs.prototype,`damping`,void 0),Ns([A()],Fs.prototype,`invert`,void 0),Ns([A()],Fs.prototype,`htmlSelector`,void 0),Ns([A()],Fs.prototype,`mode`,void 0),Ns([A(k)],Fs.prototype,`changed`,void 0);var Is=new WeakMap,Ls=[],Rs=[],zs=!0;function Bs(e){return zs?(zs=!1,Rs.length=0,document.querySelectorAll(`[data-timeline-marker]`).forEach((e,t)=>{Rs[t]=e}),zs=!1,Bs(e)):Rs[e]||null}function Vs(e){if(!e.source)return 0;let t=e.currentTime,n=e.duration,r=1;return(n.unit===`seconds`||n.unit===`percent`)&&(r=n.value),t.unit===`seconds`?t.value/r:t.value/100}var Hs=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},Us,Ws=N(`debugviewbox`),Gs=new vt(.5,.5,.5,.5),Ks=class extends R{static{Us=this}static instances=[];referenceFieldOfView=-1;get mode(){return this._mode}set mode(e){e!==this._mode&&(this._mode=e,e===`once`&&(this._applyCount=0),(Ws||this.debug)&&console.debug(`[ViewBox] Set mode:`,e))}_mode=`continuous`;debug=!1;onEnable(){(Ws||this.debug||w())&&console.debug(`[ViewBox] Using camera fov:`,this.referenceFieldOfView),Us.instances.push(this),this._applyCount=0,this.removeUpdateCallback(),this.context.pre_render_callbacks.push(this.internalUpdate)}onDisable(){(Ws||this.debug)&&console.debug(`[ViewBox] Disabled`);let e=Us.instances.indexOf(this);e!==-1&&Us.instances.splice(e,1),this._projectedBoxElement?.remove(),this.removeUpdateCallback()}removeUpdateCallback(){let e=this.context.pre_render_callbacks.indexOf(this.internalUpdate);e!==-1&&this.context.pre_render_callbacks.splice(e,1)}static _tempProjectionMatrix=new _;static _tempProjectionMatrixInverse=new _;_applyCount=0;internalUpdate=()=>{if(this.context.isInXR||this.destroyed||!this.activeAndEnabled)return;if(Us.instances[Us.instances.length-1]!==this){(Ws||this.debug)&&V.DrawWireBox(this.gameObject.worldPosition,this.gameObject.worldScale,Gs);return}(Ws||this.debug)&&V.DrawWireBox(this.gameObject.worldPosition,this.gameObject.worldScale,14540032,0,!0,this.gameObject.worldQuaternion);let e=this.context.mainCamera;if(!e||!(e instanceof le))return;if((this.referenceFieldOfView===void 0||this.referenceFieldOfView===-1)&&(this.referenceFieldOfView=e.fov,console.debug(`[ViewBox] No referenceFieldOfView set, using camera fov:`,this.referenceFieldOfView)),this.referenceFieldOfView===void 0||this.referenceFieldOfView<=0){(Ws||this.debug)&&console.warn(`[ViewBox] No valid referenceFieldOfView set, cannot adjust box size:`,this.referenceFieldOfView);return}if(this._applyCount>=1&&this.mode===`once`)return;this._applyCount++;let t=this.context.domWidth,n=this.context.domHeight,r=t,i=n,a=1,o=1,s=this.context.focusRectSize;s&&(r=s.width,i=s.height,a=t/r,o=n/i),Us._tempProjectionMatrix.copy(e.projectionMatrix),Us._tempProjectionMatrixInverse.copy(e.projectionMatrixInverse);let c=e.view,l=e.zoom,u=e.aspect,d=e.fov;e.view=null,e.zoom=1,e.fov=this.referenceFieldOfView,e.updateProjectionMatrix();let f=this.gameObject.worldPosition,p=this.gameObject.worldScale,m=e.worldPosition,ee=m.distanceTo(f),h=Math.max(p.x,p.y,p.z),g=z(m).sub(f);if(eea&&(a=n.x),n.ys&&(s=n.y)}return Ws&&(this._projectedBoxElement||=document.createElement(`div`),this._projectedBoxElement.parentElement!==this.context.domElement&&this.context.domElement.appendChild(this._projectedBoxElement),this._projectedBoxElement.style.position=`fixed`,this._projectedBoxElement.style.outline=`2px dashed rgba(255,0,0,.5)`,this._projectedBoxElement.style.left=(i*.5+.5)*this.context.domWidth+`px`,this._projectedBoxElement.style.top=(-s*.5+.5)*this.context.domHeight+`px`,this._projectedBoxElement.style.width=(a-i)*.5*this.context.domWidth+`px`,this._projectedBoxElement.style.height=(s-o)*.5*this.context.domHeight+`px`,this._projectedBoxElement.style.pointerEvents=`none`,this._projectedBoxElement.style.zIndex=`1000`),{minX:i,maxX:a,minY:o,maxY:s}}_projectedBoxElement=null};Hs([A()],Ks.prototype,`referenceFieldOfView`,void 0),Hs([A()],Ks.prototype,`mode`,null),Hs([A()],Ks.prototype,`debug`,void 0),Ks=Us=Hs([I],Ks);var qs=class extends R{toggleKey=`KeyP`;update(){this.context.input.isKeyDown(this.toggleKey)&&this.context.domElement.classList.toggle(`presentation-mode`)}};function Js(){S.add(`AlignmentConstraint`,xi),S.add(`Animation`,Qn),S.add(`Animator`,it),S.add(`AudioListener`,rr),S.add(`AudioSource`,Kn),S.add(`Avatar_Brain_LookAt`,cr),S.add(`Avatar_MouthShapes`,zn),S.add(`Avatar_MustacheShake`,In),S.add(`AvatarBlink_Simple`,bn),S.add(`AvatarEyeLook_Rotation`,hn),S.add(`AxesHelper`,Ci),S.add(`BasicIKConstraint`,wi),S.add(`BoxHelperComponent`,Di),S.add(`Camera`,Ne),S.add(`CharacterController`,Ai),S.add(`CharacterControllerInput`,ji),S.add(`SphereCollider`,Pn),S.add(`BoxCollider`,dn),S.add(`MeshCollider`,An),S.add(`CapsuleCollider`,Mn),S.add(`ContactShadows`,Dn),S.add(`LogStats`,Ni),S.add(`DeleteBox`,Li),S.add(`Deletable`,Ri),S.add(`DeviceFlag`,Vi),S.add(`DragControls`,Gi),S.add(`DropListener`,sa),S.add(`Duplicatable`,da),S.add(`EventListEvent`,ut),S.add(`EventTrigger`,ha),S.add(`GltfExportBox`,Ca),S.add(`GltfExport`,wa),S.add(`VariantAction`,Ea),S.add(`ChangeTransformOnClick`,jn),S.add(`ChangeMaterialOnClick`,un),S.add(`SetActiveOnClick`,vn),S.add(`HideOnStart`,kn),S.add(`EmphasizeOnClick`,gn),S.add(`PlayAudioOnClick`,mn),S.add(`PlayAnimationOnClick`,Nn),S.add(`PreliminaryAction`,yn),S.add(`PreliminaryTrigger`,ir),S.add(`VisibilityAction`,Fn),S.add(`TapGestureTrigger`,Ln),S.add(`USDZExporter`,Zn),S.add(`Fog`,Aa),S.add(`BoxGizmo`,Gn),S.add(`GridHelper`,Ma),S.add(`GroundProjectedEnv`,Vt),S.add(`UsageMarker`,Pi),S.add(`Interactable`,Fi),S.add(`FixedJoint`,Fa),S.add(`HingeJoint`,Ia),S.add(`Light`,Y),S.add(`LODGroup`,Xa),S.add(`LookAtConstraint`,He),S.add(`NeedleMenu`,ln),S.add(`NestedGltf`,$a),S.add(`Networking`,no),S.add(`OffsetConstraint`,io),S.add(`CameraTargetReachedEvent`,D),S.add(`OrbitControls`,Le),S.add(`ParticleSystemRenderer`,vr),S.add(`ParticleSystem`,yr),S.add(`Attractor`,oo),S.add(`PlayerColor`,so),S.add(`Antialiasing`,wr),S.add(`BloomEffect`,Dr),S.add(`ChromaticAberration`,kr),S.add(`ColorAdjustments`,Sr),S.add(`DepthOfField`,Nr),S.add(`EffectWrapper`,Er),S.add(`PixelationEffect`,xr),S.add(`ScreenSpaceAmbientOcclusion`,jr),S.add(`ScreenSpaceAmbientOcclusionN8`,Or),S.add(`SharpeningEffect`,br),S.add(`TiltShiftEffect`,Tr),S.add(`ToneMappingEffect`,Cr),S.add(`Vignette`,Ar),S.add(`Volume`,Mr),S.add(`ReflectionProbe`,_n),S.add(`Renderer`,Vn),S.add(`MeshRenderer`,_r),S.add(`SkinnedMeshRenderer`,gr),S.add(`Rigidbody`,E),S.add(`SceneSwitcher`,W),S.add(`ScreenCapture`,So),S.add(`SeeThrough`,Eo),S.add(`ShadowCatcher`,ko),S.add(`RemoteSkybox`,vi),S.add(`SmoothFollow`,jo),S.add(`SpatialTriggerReceiver`,Lo),S.add(`SpatialTrigger`,Ro),S.add(`SpectatorCamera`,Ho),S.add(`SplineContainer`,Qo),S.add(`SplineWalker`,ts),S.add(`SpriteRenderer`,xn),S.add(`SyncedCamera`,ss),S.add(`SyncedRoom`,ds),S.add(`SyncedTransform`,rt),S.add(`TestRunner`,ms),S.add(`TestSimulateUserData`,hs),S.add(`PlayableDirector`,ti),S.add(`SignalReceiver`,Rr),S.add(`AnimationTrackHandler`,Gr),S.add(`AudioTrackHandler`,qr),S.add(`MarkerTrackHandler`,Jr),S.add(`SignalTrackHandler`,Yr),S.add(`ControlTrackHandler`,Xr),S.add(`TransformGizmo`,vs),S.add(`BaseUIComponent`,en),S.add(`UIRootComponent`,ot),S.add(`Button`,B),S.add(`Canvas`,Ut),S.add(`CanvasGroup`,Rt),S.add(`EventSystem`,Pe),S.add(`Graphic`,wt),S.add(`MaskableGraphic`,Ct),S.add(`Image`,Et),S.add(`RawImage`,pt),S.add(`InputField`,Ft),S.add(`VerticalLayoutGroup`,bt),S.add(`HorizontalLayoutGroup`,Jt),S.add(`GridLayoutGroup`,Mt),S.add(`Outline`,ft),S.add(`ObjectRaycaster`,C),S.add(`GraphicRaycaster`,jt),S.add(`SpatialGrabRaycaster`,Ot),S.add(`RectTransform`,nn),S.add(`SpatialHtml`,Kt),S.add(`Text`,Bt),S.add(`EnvironmentScene`,ii),S.add(`LookAt`,bs),S.add(`OpenURL`,Cs),S.add(`VideoPlayer`,Z),S.add(`Voip`,En),S.add(`ClickThrough`,ws),S.add(`CursorFollow`,Ds),S.add(`HoverAnimation`,As),S.add(`ScrollFollow`,Fs),S.add(`ViewBox`,Ks),S.add(`Avatar`,Jn),S.add(`XRControllerFollow`,Un),S.add(`XRControllerModel`,mr),S.add(`XRControllerMovement`,On),S.add(`TeleportTarget`,fn),S.add(`WebARCameraBackground`,tr),S.add(`WebARSessionRoot`,Tn),S.add(`WebXR`,hr),S.add(`AvatarMarker`,Yn),S.add(`WebXRImageTracking`,or),S.add(`WebXRPlaneTracking`,$n),S.add(`XRRig`,ur),S.add(`XRFlag`,ar),S.add(`PlayerSync`,Cn),S.add(`PlayerState`,qn),S.add(`PresentationMode`,qs)}export{Yi as $,Xa as A,zr as At,Ca as B,So as C,qr as Ct,io as D,Ur as Dt,oo as E,Yr as Et,Ma as F,ha as G,va as H,Aa as I,ea as J,da as K,Da as L,Y as M,Rr as Mt,Fa as N,Lr as Nt,no as O,Br as Ot,Ia as P,Zi as Q,Ea as R,Eo as S,Gr as St,so as T,Jr as Tt,ya as U,ba as V,ga as W,ta as X,na as Y,$i as Z,Ho as _,mi as _t,Ds as a,Ri as at,jo as b,ii as bt,bs as c,Pi as ct,hs as d,ji as dt,Ji as et,ds as f,Di as ft,Zo as g,vi as gt,Qo as h,xi as ht,As as i,Vi as it,Ja as j,Ir as jt,$a as k,Vr as kt,vs as l,Ni as lt,ts as m,Ci as mt,Ks as n,Gi as nt,ws as o,Li as ot,ss as p,wi as pt,sa as q,Fs as r,K as rt,Cs as s,Fi as st,Js as t,Xi as tt,ms as u,Ai as ut,Ro as v,W as vt,Z as w,Xr as wt,ko as x,ti as xt,Lo as y,ci as yt,wa as z};