@genex-ai/multiplayer 0.17.0 → 0.17.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,14 @@
1
+ "use strict";(()=>{var UE=Object.create;var Wc=Object.defineProperty;var VE=Object.getOwnPropertyDescriptor;var HE=Object.getOwnPropertyNames;var $E=Object.getPrototypeOf,jE=Object.prototype.hasOwnProperty;var am=t=>{throw TypeError(t)};var qE=(t,e,n)=>e in t?Wc(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var at=(t,e)=>()=>(t&&(e=t(t=0)),e);var GE=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Fd=(t,e)=>{for(var n in e)Wc(t,n,{get:e[n],enumerable:!0})},WE=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of HE(e))!jE.call(t,s)&&s!==n&&Wc(t,s,{get:()=>e[s],enumerable:!(r=VE(e,s))||r.enumerable});return t};var YE=(t,e,n)=>(n=t!=null?UE($E(t)):{},WE(e||!t||!t.__esModule?Wc(n,"default",{value:t,enumerable:!0}):n,t));var m=(t,e,n)=>qE(t,typeof e!="symbol"?e+"":e,n),zd=(t,e,n)=>e.has(t)||am("Cannot "+n);var ae=(t,e,n)=>(zd(t,e,"read from private field"),n?n.call(t):e.get(t)),ze=(t,e,n)=>e.has(t)?am("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n),Ue=(t,e,n,r)=>(zd(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n),ks=(t,e,n)=>(zd(t,e,"access private method"),n);var We,Lo,Sf,yu,gu,Ts,ft,hy=at(()=>{"use strict";We={JOIN_ROOM:10,ERROR:11,LEAVE_ROOM:12,ROOM_DATA:13,ROOM_STATE:14,ROOM_STATE_PATCH:15,ROOM_DATA_SCHEMA:16,ROOM_DATA_BYTES:17,PING:18,ROOM_INPUT_RELIABLE:19,ROOM_INPUT_UNRELIABLE:20,ROOM_REQUEST:21,ROOM_RESPONSE:22},Lo={TIMED:128,UNRELIABLE:64},Sf=31,yu={OK:0,REJECTED:1,ERROR:2},gu={INPUT_REFLECTION:1,INPUT_OPTIONS:2},Ts={RENDER_TIME:1,FIXED_TIMESTEP:2,PATCH_RATE:4,SUB_STEPS:8,RECKON_TIME:16},ft={NORMAL_CLOSURE:1e3,GOING_AWAY:1001,NO_STATUS_RECEIVED:1005,ABNORMAL_CLOSURE:1006,CONSENTED:4e3,SERVER_SHUTDOWN:4001,WITH_ERROR:4002,FAILED_TO_RECONNECT:4003,MAY_TRY_RECONNECT:4010}});var yr=at(()=>{"use strict";hy()});function sg(t){Object.defineProperty(t,Symbol.metadata,{value:void 0,writable:!0,configurable:!0,enumerable:!1})}function cg(t,e,n){for(var r=0,s=0,o=e.length;s<o;s++)r=e.charCodeAt(s),r<128?t[n.offset++]=r:r<2048?(t[n.offset]=192|r>>6,t[n.offset+1]=128|r&63,n.offset+=2):r<55296||r>=57344?(t[n.offset]=224|r>>12,t[n.offset+1]=128|r>>6&63,t[n.offset+2]=128|r&63,n.offset+=3):(s++,r=65536+((r&1023)<<10|e.charCodeAt(s)&1023),t[n.offset]=240|r>>18,t[n.offset+1]=128|r>>12&63,t[n.offset+2]=128|r>>6&63,t[n.offset+3]=128|r&63,n.offset+=4)}function ug(t,e,n){t[n.offset++]=e&255}function OR(t,e,n){t[n.offset++]=e&255}function lg(t,e,n){t[n.offset++]=e&255,t[n.offset++]=e>>8&255}function If(t,e,n){t[n.offset++]=e&255,t[n.offset++]=e>>8&255}function xr(t,e,n){t[n.offset++]=e&255,t[n.offset++]=e>>8&255,t[n.offset++]=e>>16&255,t[n.offset++]=e>>24&255}function Os(t,e,n){let r=e>>24,s=e>>16,o=e>>8,i=e;t[n.offset++]=i&255,t[n.offset++]=o&255,t[n.offset++]=s&255,t[n.offset++]=r&255}function dg(t,e,n){let r=Math.floor(e/Math.pow(2,32)),s=e>>>0;Os(t,s,n),Os(t,r,n)}function fg(t,e,n){let r=e/Math.pow(2,32)>>0,s=e>>>0;Os(t,s,n),Os(t,r,n)}function IR(t,e,n){ig[0]=BigInt.asIntN(64,e),xr(t,Cs[0],n),xr(t,Cs[1],n)}function DR(t,e,n){ig[0]=BigInt.asIntN(64,e),xr(t,Cs[0],n),xr(t,Cs[1],n)}function pg(t,e,n){Pf[0]=e,xr(t,Cs[0],n)}function hg(t,e,n){MR[0]=e,xr(t,Cs[0],n),xr(t,Cs[1],n)}function BR(t,e,n){t[n.offset++]=e?1:0}function NR(t,e,n){e||(e="");let r=ag(e,"utf8"),s=0;if(r<32)t[n.offset++]=r|160,s=1;else if(r<256)t[n.offset++]=217,t[n.offset++]=r,s=2;else if(r<65536)t[n.offset++]=218,If(t,r,n),s=3;else if(r<4294967296)t[n.offset++]=219,Os(t,r,n),s=5;else throw new Error("String too long");return cg(t,e,n),s+r}function Af(t,e,n){if(isNaN(e))return Af(t,0,n);if(isFinite(e)){if(e!==(e|0))return Math.abs(e)<=34028235e31&&(Pf[0]=e,Math.abs(Math.abs(Pf[0])-Math.abs(e))<1e-4)?(t[n.offset++]=202,pg(t,e,n),5):(t[n.offset++]=203,hg(t,e,n),9)}else return Af(t,e>0?Number.MAX_SAFE_INTEGER:-Number.MAX_SAFE_INTEGER,n);return e>=0?e<128?(t[n.offset++]=e&255,1):e<256?(t[n.offset++]=204,t[n.offset++]=e&255,2):e<65536?(t[n.offset++]=205,If(t,e,n),3):e<4294967296?(t[n.offset++]=206,Os(t,e,n),5):(t[n.offset++]=207,fg(t,e,n),9):e>=-32?(t[n.offset++]=224|e+32,1):e>=-128?(t[n.offset++]=208,ug(t,e,n),2):e>=-32768?(t[n.offset++]=209,lg(t,e,n),3):e>=-2147483648?(t[n.offset++]=210,xr(t,e,n),5):(t[n.offset++]=211,dg(t,e,n),9)}function mg(t,e,n){n>t.length-e.offset&&(n=t.length-e.offset);for(var r="",s=0,o=e.offset,i=e.offset+n;o<i;o++){var a=t[o];if((a&128)===0){r+=String.fromCharCode(a);continue}if((a&224)===192){r+=String.fromCharCode((a&31)<<6|t[++o]&63);continue}if((a&240)===224){r+=String.fromCharCode((a&15)<<12|(t[++o]&63)<<6|(t[++o]&63)<<0);continue}if((a&248)===240){s=(a&7)<<18|(t[++o]&63)<<12|(t[++o]&63)<<6|(t[++o]&63)<<0,s>=65536?(s-=65536,r+=String.fromCharCode((s>>>10)+55296,(s&1023)+56320)):r+=String.fromCharCode(s);continue}console.error("decode.utf8Read(): Invalid byte "+a+" at offset "+o+". Skip to end of string: "+(e.offset+n));break}return e.offset+=n,r}function yg(t,e){return ya(t,e)<<24>>24}function ya(t,e){return t[e.offset++]}function gg(t,e){return Bu(t,e)<<16>>16}function Bu(t,e){return t[e.offset++]|t[e.offset++]<<8}function On(t,e){return t[e.offset++]|t[e.offset++]<<8|t[e.offset++]<<16|t[e.offset++]<<24}function Uo(t,e){return On(t,e)>>>0}function bg(t,e){return Is[0]=On(t,e),LR[0]}function wg(t,e){return Is[0]=On(t,e),Is[1]=On(t,e),FR[0]}function xg(t,e){let n=Uo(t,e);return On(t,e)*Math.pow(2,32)+n}function Sg(t,e){let n=Uo(t,e);return Uo(t,e)*Math.pow(2,32)+n}function VR(t,e){return Is[0]=On(t,e),Is[1]=On(t,e),UR[0]}function HR(t,e){return Is[0]=On(t,e),Is[1]=On(t,e),zR[0]}function $R(t,e){return ya(t,e)>0}function jR(t,e){let n=t[e.offset++],r;return n<192?r=n&31:n===217?r=ya(t,e):n===218?r=Bu(t,e):n===219&&(r=Uo(t,e)),mg(t,e,r)}function qR(t,e){let n=t[e.offset++];if(n<128)return n;if(n===202)return bg(t,e);if(n===203)return wg(t,e);if(n===204)return ya(t,e);if(n===205)return Bu(t,e);if(n===206)return Uo(t,e);if(n===207)return Sg(t,e);if(n===208)return yg(t,e);if(n===209)return gg(t,e);if(n===210)return On(t,e);if(n===211)return xg(t,e);if(n>223)return(255-n+1)*-1}function GR(t,e){let n=t[e.offset];return n<192&&n>160||n===217||n===218||n===219}function Er(t,e){e.constructor&&(Object.prototype.hasOwnProperty.call(e,"constructor")&&e.constructor[Symbol.metadata]==null&&sg(e.constructor),WR.set(e.constructor,t),Df[t]=e),e.encode&&(be[t]=e.encode),e.decode&&(Re[t]=e.decode)}function Eg(t){return Df[t]}function Sr(){return{pendingByView:new Map,sentByView:new Map,broadcastPending:new Set,sentBroadcast:new Set,broadcastDeletes:new Set,maxPerTick:32}}function Bf(t){return t._stream??(t._stream=Sr())}function Nu(t,e,n){e.activeViews.size===0&&Bf(t).broadcastPending.add(n)}function Lu(t,e,n,r){let s=t._stream;if(s===void 0)return!0;let o=!1;return s.broadcastPending.delete(r)?o=!0:s.sentBroadcast.delete(r)&&s.broadcastDeletes.add(r),e.forEachActiveView(i=>{let a=s.pendingByView.get(i.id);if(a?.has(r)){a.delete(r),o=!0;return}let c=s.sentByView.get(i.id);if(c?.has(r)){c.delete(r);let u=i.changes.get(n);u===void 0&&(u=new Map,i.changes.set(n,u)),u.set(r,B.DELETE)}}),o}function YR(t,e,n){let r=t._stream;if(r!==void 0){r.broadcastPending.clear();for(let s of r.sentBroadcast)r.broadcastDeletes.add(s);r.sentBroadcast.clear(),e.forEachActiveView(s=>{r.pendingByView.get(s.id)?.clear();let o=r.sentByView.get(s.id);if(o!==void 0&&o.size>0){let i=s.changes.get(n);i===void 0&&(i=new Map,s.changes.set(n,i));for(let a of o)i.set(a,B.DELETE);o.clear()}})}}function KR(t,e){let n=t._stream?.pendingByView;if(n===void 0)return!1;for(let[r,s]of n)if(s.size>0&&e.activeViews.get(r)?.deref()!==void 0)return!0;return!1}function XR(t){let e=t._stream;return e!==void 0&&(e.broadcastPending.size>0||e.broadcastDeletes.size>0)}function JR(t,e,n){let r=Bf(t),s=r.pendingByView.get(e);s===void 0&&(s=new Set,r.pendingByView.set(e,s)),s.add(n)}function Fu(t,e){let n=t._stream;n!==void 0&&(n.pendingByView.delete(e),n.sentByView.delete(e),n.priorityByView?.delete(e))}function Nf(t){if(t==null||typeof t!="object")throw new Error("t.quantized(): options object with { min, max } is required.");let{min:e,max:n}=t;if(typeof e!="number"||typeof n!="number"||!(n>e)||!Number.isFinite(e)||!Number.isFinite(n))throw new Error(`t.quantized(): require finite min < max (got min=${e}, max=${n}).`);let r=t.bits??16;if(r!==8&&r!==16&&r!==32)throw new Error(`t.quantized(): bits must be 8, 16 or 32 (got ${r}).`);let s=t.mode??"clamp";if(s!=="clamp"&&s!=="wrap")throw new Error(`t.quantized(): mode must be "clamp" or "wrap" (got ${JSON.stringify(s)}).`);let o=s==="wrap",i=Math.pow(2,r);return{min:e,max:n,bits:r,wrap:o,wire:ZR[r],range:n-e,span:o?i:e===-n?i-2:i-1}}function Ds(t){return t!==null&&typeof t=="object"&&t.quantized!==void 0}function Rg(t,e){if(t.wrap){if(!Number.isFinite(e))return 0;let r=t.range,s=(e-t.min)%r;s<0&&(s+=r);let o=t.span;return Math.floor(s/r*o+.5)%o}if(e!==e)return 0;let n=e<t.min?t.min:e>t.max?t.max:e;return Math.floor((n-t.min)/t.range*t.span+.5)}function kg(t,e){return t.min+e/t.span*t.range}function QR(t){let e=be[t.wire];return(n,r,s)=>e(n,Rg(t,r),s)}function ek(t,e,n){let r=Re[t.wire];return kg(t,r(e,n))}function tk(t){let e=typeof Object.keys(t)[0]=="string"&&Eg(Object.keys(t)[0]);return{complexTypeKlass:e,childType:e?Object.values(t)[0]:t}}function Vo(t){if(Array.isArray(t))return{array:Vo(t[0])};if(Ds(t))return typeof t.quantized.wire=="string"?t:{quantized:Nf(t.quantized)};if(typeof t.type<"u")return t.type;if(nk(t))return Object.keys(t).every(e=>typeof t[e]=="string")?"string":"number";if(typeof t=="object"&&t!==null){let e=Object.keys(t).find(n=>Df[n]!==void 0);if(e)return t[e]=Vo(t[e]),t}return t}function nk(t){if(typeof t=="function"&&t[Symbol.metadata])return!1;let e=Object.keys(t),n=e.filter(r=>/\d+/.test(r));return!!(n.length>0&&n.length===e.length/2&&t[t[n[0]]]==n[0]||e.length>0&&e.every(r=>typeof t[r]=="string"&&t[r]===r))}function wu(t,e,n){t[e]||Object.defineProperty(t,e,{value:[],enumerable:!1,configurable:!0,writable:!0}),t[e].push(n)}function Pu(t){return t=t-(t>>>1&1431655765),t=(t&858993459)+(t>>>2&858993459),(t+(t>>>4)&252645135)*16843009>>>24}function xu(t){if(t===void 0)return 0;let e=0;for(let n=0,r=t.length;n<r;n++){let s=t[n];s<32&&(e|=1<<s)}return e}function sk(t){let e=[],n=[],r=[],s=[],o=t?.[bt];if(o===void 0)return{names:e,types:n,tags:r,encoders:s};let i=t[br];for(let a=0;a<=o;a++){let c=t[a];if(c===void 0){e[a]=void 0,n[a]=void 0,r[a]=void 0,s[a]=void 0;continue}e[a]=c.name,n[a]=c.type,r[a]=c.tag,s[a]=i?.[a]}return{names:e,types:n,tags:r,encoders:s}}function Lf(t){let e=t.constructor;if(Object.prototype.hasOwnProperty.call(e,aa))return e[aa];let n=e[Symbol.metadata],r=Ie.isValidInstance(t),s=(n?.[An]?.length??0)>0,o=sk(n),i=r&&!s?void 0:e[Ns],a={encoder:e[Qn],filter:i,metadata:n,isSchema:r,filterBitmask:r?xu(n?.[An]):0,hasAnyFullStateOnly:(n?.[zo]?.length??0)>0,hasAnyUnreliable:(n?.[Ms]?.length??0)>0,hasAnyStream:(n?.[nn]?.length??0)>0,hasAnyView:s,fullStateOnlyBitmask:xu(n?.[zo]),unreliableBitmask:xu(n?.[Ms]),streamBitmask:xu(n?.[nn]),names:o.names,types:o.types,tags:o.tags,encoders:o.encoders};return Object.defineProperty(e,aa,{value:a,enumerable:!1,writable:!0,configurable:!0}),a}function ok(t,e,n){if(t.parentRef){if(t.parentRef[I]===e[I]){t._parentIndex=n;return}if(Ag(t,(r,s)=>r[I]===e[I])){t._parentIndex=n;return}}t.parentRef===void 0?(t.parentRef=e,t._parentIndex=n):(t.extraParents={ref:t.parentRef,index:t._parentIndex,next:t.extraParents},t.parentRef=e,t._parentIndex=n)}function ik(t,e,n){if(t.extraParents===void 0){t._parentIndex=n;return}if(t.parentRef[I]===e[I]){t._parentIndex=n;return}for(let r=t.extraParents;r!==void 0;r=r.next)if(r.ref[I]===e[I]){r.index=n;return}}function ak(t,e){if(t.parentRef&&t.parentRef[I]===e[I])return t.extraParents?(t.parentRef=t.extraParents.ref,t._parentIndex=t.extraParents.index,t.extraParents=t.extraParents.next):(t.parentRef=void 0,t._parentIndex=void 0),!0;let n=t.extraParents,r=null;for(;n;){if(n.ref[I]===e[I])return r?r.next=n.next:t.extraParents=n.next,!0;r=n,n=n.next}return t.parentRef===void 0}function ck(t,e){if(t.parentRef!==void 0&&e(t.parentRef,t._parentIndex))return{ref:t.parentRef,index:t._parentIndex};for(let n=t.extraParents;n!==void 0;n=n.next)if(e(n.ref,n.index))return{ref:n.ref,index:n.index}}function Ag(t,e){if(t.parentRef!==void 0&&e(t.parentRef,t._parentIndex))return!0;for(let n=t.extraParents;n!==void 0;n=n.next)if(e(n.ref,n.index))return!0;return!1}function uk(t,e){if(t.parentRef&&t.parentRef[I]===e[I])return t._parentIndex;for(let n=t.extraParents;n!==void 0;n=n.next)if(n.ref[I]===e[I])return n.index}function lk(t){let e=[];t.parentRef&&e.push({ref:t.parentRef,index:t._parentIndex});let n=t.extraParents;for(;n;)e.push({ref:n.ref,index:n.index}),n=n.next;return e}function dk(t,e,n){let r=e.refTarget;if(e.isArray){let o=r.items,i=o[n];if(i!==void 0&&i[I]===t)return!0;for(let a=0,c=o.length;a<c;a++){let u=o[a];if(u!==void 0&&u[I]===t)return!0}return!1}let s=e.getValue(n);return s!==void 0&&s[I]===t}function pk(t,e){Ff(t,e,fk)}function Ff(t,e,n){let r=t.refTarget;if(r[ge]!==void 0){if(t.isPatchOnly)return;if(Array.isArray(r.items)){let s=r.items;for(let o=0,i=s.length;o<i;o++)s[o]!==void 0&&n(e,o)}else if(r.journal!==void 0)for(let[s,o]of r.journal.keyByIndex)r.$items.has(o)&&n(e,s);else if(r.$items!==void 0)for(let s of r.$items.keys())n(e,s)}else{let s=t.metadata;if(!s)return;let o=s[bt]??-1,i=s[ku],a=t.encDescriptor.names;for(let c=0;c<=o;c++){let u=a[c];if(u===void 0||i&&i.includes(c))continue;let l=r[u];l!=null&&n(e,c)}}}function Tg(t,e,n,r){hk(t,e,n),!t.isFullStateOnly&&(t.has()&&t.root?.enqueueChangeTree(t),t.unreliableRecorder?.has()&&t.root?.enqueueUnreliable(t),!t.has()&&!t.unreliableRecorder?.has()&&t.root?.enqueueChangeTree(t))}function hk(t,e,n){if(!e)return;let r=e[I],s=!r._isSchema,o;s?(e=r.parent,n=r.parentIndex,o=e?.[I].metadata):o=r.metadata;let i=(o?.[ua]?.includes(n)?ca:0)|(o?.[zo]?.includes(n)?Fo:0),a=r.flags&Pk|i,c=t.flags;if(t.flags=c|a,a&~c&Fo&&(t.reset(),t.unreliableRecorder?.reset()),!t.root?.types?.hasFilters)return;let d=o?.[An]?.includes(n)??!1,f=o?.[nn]?.includes(n)??!1,h=r.isFiltered||d||f;if(t.isFiltered=h,f&&!s){t.isStreamCollection=!0;let p=Bf(t.ref);if(p.priority===void 0){let g=Ie.getStreamPriority(o,n);g!==void 0&&(p.priority=g)}t.root?.registerStream(t.ref)}if(h){let p=Mg(t);t.isVisibilitySharedWithParent=r.isFiltered&&p&&!f&&(!d||s&&o[n].tag!==Hu)}}function gy(t){let e=t.pendingFilterRefresh;for(let n=0;n<e.length;n++){let r=e[n];(r.flags&la)!==0&&zf(r)}e.length=0}function Mg(t){return t._isSchema||typeof t.refTarget[ge]!="string"}function zf(t){t.flags&=~la;let e=t.root;if(e===void 0||t.parentRef===void 0)return;let n=Mg(t),r=by(t,t.parentRef,t._parentIndex,n);for(let o=t.extraParents;o!==void 0&&r!==mk;o=o.next)r|=by(t,o.ref,o.index,n);if(r===0)return;t.isVisibilitySharedWithParent=(r&vu)!==0;let s=(r&Au)===0;s!==t.isFiltered&&(t.isFiltered=s,!s&&!t.isFullStateOnly&&(t.forEachLiveWithCtx(t,vg),t.has()&&e.enqueueChangeTree(t),t.unreliableRecorder?.has()&&e.enqueueUnreliable(t)),t.forEachChildWithCtx(t,yk))}function by(t,e,n,r){let s=e[I];if(s.root!==t.root||!dk(t,s,n))return 0;s.flags&la&&zf(s);let o=Cg;if(s._isSchema)s.encDescriptor.tags[n]!==void 0||s.isFieldStream(n)||(s.isFiltered?r&&(o|=vu):o|=Au);else if(!s.isFiltered)o|=Au;else if(r&&!s.isStreamCollection){let i=s.parent?.[I];(i?._isSchema?i.encDescriptor.tags[s.parentIndex]:void 0)!==Hu&&(o|=vu)}return o}function gk(t,e,n,r){let s=t.subscribedViews;if(s===void 0)return;let o=t.isStreamCollection,i=o?t.ref:void 0,a=o?void 0:n[I];for(let c=0,u=s.length;c<u;c++){let l=s[c];for(;l!==0;){let d=l&-l;l^=d;let f=c*32+(31-Math.clz32(d)),p=r.activeViews.get(f)?.deref();if(p===void 0){s[c]&=~d;continue}o?JR(i,f,e):a!==void 0&&p.markVisible(a)}}}function bk(t,e){t.root=e;let n=e.add(t);Tg(t,t.parent,t.parentIndex),n&&ga(t,e,Ek)}function wk(t,e,n,r){if(t.addParent(e,r),!n)return;let s=n.add(t);n!==t.root&&(t.root=n,Tg(t,e,r));let o=e?.[I];if(o!==void 0&&o.subscribedViews!==void 0&&e[ge]!==void 0&&gk(o,r,t.ref,n),s){let i=wy[Su];i===void 0&&(i={parentRef:void 0,root:void 0},wy[Su]=i),i.parentRef=t.ref,i.root=n,Su++,ga(t,i,_k),Su--}}function xk(t,e){ga(t,e,Sk)}function Sk(t,e,n){t(e,n)}function ga(t,e,n){let r=t.refTarget;if(r[ge]){if(typeof r[ge]!="string"){let s=r.items;if(s!==void 0)for(let o=0,i=s.length;o<i;o++){let a=s[o];a&&n(e,a[I],o)}else{let o=r.$items,i=r._collectionIndexes;for(let a of o.keys()){let c=o.get(a);c&&n(e,c[I],i?.[a]??a)}}}}else{let o=t.metadata?.[Gr];if(!o)return;let i=t.encDescriptor.names;for(let a=0,c=o.length;a<c;a++){let u=o[a],l=r[i[u]];l&&n(e,l[I],u)}}}function Ek(t,e,n){e.root!==t?e.setRoot(t):t.add(e)}function _k(t,e,n){if(e.root===t.root){t.root.add(e),t.root.moveNextToParent(e);return}e.setParent(t.parentRef,t.root,n)}function Rk(t,e,n){let r=(n&3)<<3;return n<4?t>>>r&255:e>>>r&255}function xy(){return{next:void 0,tail:void 0,nextPosition:0}}function Ak(t){return new Mf(t)}function $o(t,e=t){Object.defineProperty(t,I,{value:Ak(e),enumerable:!1,writable:!0})}function zu(t,e,n,r,s,o,i){i!==void 0?i(e,r,o):typeof n=="string"?be[n]?.(e,r,o):n[Symbol.metadata]!=null?(be.number(e,r[Q],o),(s&B.ADD)===B.ADD&&t.tryEncodeTypeId(e,n,r.constructor,o)):be.number(e,r[Q],o)}function Og(t,e,n,r,s,o,i){let a=t.resyncVisited,c=a.get(t.currentRefId);if(c===void 0&&a.set(t.currentRefId,c=new Set),c.add(r),s!==void 0&&n===B.ADD&&s!==o){let u=s[Q];u!==void 0&&(t.root.removeRef(u),i?.push({ref:e,refId:t.currentRefId,op:B.DELETE,dynamicIndex:r,value:void 0,previousValue:s}))}}function Ck(t,e){let n=t.resyncVisited;n.has(e)||n.set(e,new Set)}function Ok(t,e){if(t.resyncDamaged){console.warn("@colyseus/schema: resync sweep skipped \u2014 parts of the payload could not be decoded. Stale entries may persist until the next resync.");return}Hf(t,t.state,new Set,e)}function Hf(t,e,n,r){let s=e[Q];if(s===void 0||n.has(s))return;n.add(s);let o=e.constructor[Symbol.metadata],i=o?.[Gr];if(i===void 0)return;let a=o[ua];for(let c=0;c<i.length;c++){let u=i[c];if(a!==void 0&&a.includes(u))continue;let l=o[u],d=e[l.name];d&&(Ye.is(l.type)?Hf(t,d,n,r):Ik(t,d,n,r))}}function Ik(t,e,n,r){let s=e[rt]??e,o=s[Q];if(o===void 0||n.has(o))return;n.add(o);let i=t.resyncVisited.get(o);if(i===void 0)return;let a=t.root;s[Ho](i,(c,u)=>{r?.push({ref:e,refId:o,op:B.DELETE,dynamicIndex:u,value:void 0,previousValue:c});let l=c?.[Q];l!==void 0&&a.removeRef(l)},c=>{Ye.isSchema(c)&&Hf(t,c,n,r)})}function $f(t,e,n,r,s,o,i,a,c){let u=t.root,l;if((e&B.DELETE)===B.DELETE){let d=s?.[Q];d!==void 0&&u.removeRef(d),e!==B.DELETE_AND_ADD&&n[Cn](r),l=void 0}if(e!==B.DELETE)if(typeof o=="string")l=Re[o](i,a);else if(Ds(o))l=ek(o.quantized,i,a);else if(Ye.is(o)){let d=Re.number(i,a);if(l=u.refs.get(d),(e&B.ADD)===B.ADD){let f=t.getInstanceType(i,a,o);l||(l=t.createInstanceOfType(f)),u.addRef(d,l,l!==s||e===B.DELETE_AND_ADD&&l===s)}}else{let d=Eg(Object.keys(o)[0]),f=Re.number(i,a);t.resyncVisited!==null&&Ck(t,f);let h=u.refs.has(f)?s||u.refs.get(f):d.constructor.initializeForDecoder();if(l=h.clone(!0),l[ge]=Object.values(o)[0],s){let p=s[Q];if(p!==void 0&&f!==p){(e&B.DELETE)!==B.DELETE&&u.removeRef(p);let g=s.entries(),x;for(;(x=g.next())&&!x.done;){let[b,S]=x.value;typeof S=="object"&&(p=S[Q]),c?.push({ref:s,refId:p,op:B.DELETE,field:b,value:void 0,previousValue:S})}}}u.addRef(f,l,h!==s||e===B.DELETE_AND_ADD&&h===s)}return l}function Vu(t,e,n,r){if(!(t instanceof e))throw new da(`a '${e.name}' was expected, but '${t&&t.constructor.name}' was provided in ${n.constructor.name}#${r}`)}function Dg(t){return t!=null&&t[og]===!0}function Ot(t){return(()=>new er(t))}function ba(t){if(Dg(t)){let e=t._type,n=typeof e=="string"?`use the type name instead: t.array("${e}")`:'collections accept a Schema class or a primitive type name ("string", "number", \u2026)';throw new Error(`t.array/map/set/collection(): a t.* builder is not a valid element type \u2014 ${n}.`)}return t}function Ey(t){return new er({quantized:Nf(t)})}function $k(t=Hu){return function(e,n){let r=Ie.initialize(e.constructor);Ie.setTag(r,n,t)}}function jk(t,e){let n=Ie.initialize(t.constructor);Ie.setUnreliable(n,e)}function qk(t,e){let n=Ie.initialize(t.constructor);Ie.setPatchOnly(n,e)}function Wk(t,e,n){let r=Gk[n],s=n==="string",o=n==="boolean";return function(i){let a=this[kt],c=a[e];if(i!==c){if(i!=null){if(!o&&r!==void 0&&typeof i!==r&&!(s&&i===null)){let u=i&&i.constructor?` (${i.constructor.name})`:"";throw new da(`a '${r}' was expected, but '${JSON.stringify(i)}'${u} was provided in ${this.constructor.name}#${t}`)}this.constructor[Zn](this[I],e,B.ADD)}else c!=null&&this[I].delete(e);a[e]=i}}}function Yk(t,e,n){return function(r){let s=this[kt],o=s[e];if(r!==o){if(r!=null){Vu(r,n,this,t);let i=this[I],a=this.constructor;o!=null&&o[I]?(i.root?.remove(o[I]),a[Zn](i,e,B.DELETE_AND_ADD)):a[Zn](i,e,B.ADD),r[I]?.setParent(this,i.root,e)}else o!=null&&this[I].delete(e);s[e]=r}}}function Kk(t,e,n,r){let s=r.constructor===Wr,o=r.constructor===Yr;return function(i){let a=this[kt],c=a[e];if(i!==c){if(i!=null){if(s&&!(i instanceof Wr)){let d=new Wr;d[ge]=n,d.push(...i),i=d}else if(o&&!(i instanceof Yr)){let d=new Yr;if(d[ge]=n,i instanceof Map)i.forEach((f,h)=>d.set(h,f));else for(let f in i)d.set(f,i[f]);i=d}else i[ge]=n;let u=this[I],l=this.constructor;c!=null&&c[I]?(u.root?.remove(c[I]),l[Zn](u,e,B.DELETE_AND_ADD)):l[Zn](u,e,B.ADD),i[I]?.setParent(this,u.root,e)}else c!=null&&this[I].delete(e);a[e]=i}}}function Xk(t,e,n){return function(r){let s=this[kt],o=s[e];if(r!=null){if(typeof r!="number")throw new da(`a 'number' was expected, but '${JSON.stringify(r)}' was provided in ${this.constructor.name}#${t}`);if(r=kg(n,Rg(n,r)),r===o)return;this.constructor[Zn](this[I],e,B.ADD)}else{if(r===o)return;o!=null&&this[I].delete(e)}s[e]=r}}function Jk(t,e,n,r){let s;return r?s=Kk(t,e,n,r):typeof n=="string"?s=Wk(t,e,n):Ds(n)?s=Xk(t,e,n.quantized):s=Yk(t,e,n),{get:function(){return this[kt][e]},set:s,enumerable:!0,configurable:!0}}function Zk(t=!0){return function(e,n){let r=Ie.initialize(e.constructor);Ie.setDeprecated(r,n),t&&(r[tn]??(r[tn]={}),r[tn][n]={get:function(){throw new Error(`${n} is deprecated.`)},set:function(s){},enumerable:!1,configurable:!0},Object.defineProperty(e,n,r[tn][n]))}}function Qk(t){if(t&&typeof t=="object"){if(t.array!==void 0)return()=>new Wr;if(t.map!==void 0)return()=>new Yr;if(t.set!==void 0)return()=>new pa;if(t.collection!==void 0)return()=>new fa;if(t.stream!==void 0)return()=>new Mu}else if(typeof t=="function"&&Ye.is(t)&&(!t.prototype.initialize||t.prototype.initialize.length===0))return()=>new t}function It(t,e,n=Ye){if(t==null||typeof t!="object")throw new Error(`schema(): first argument must be a fields object (got ${typeof t}).`);let r={},s={},o={},i={},a=(M,O)=>{typeof O=="function"?i[M]=O:O&&typeof O.clone=="function"?i[M]=()=>O.clone():o[M]=O},c=(M,O)=>{if(O.hasDefault)a(M,O.default);else if(!O.optional){let z=Qk(O.type);z&&(i[M]=z)}},u={},l=[],d=[],f={},h=[],p=[],g={},x=[];for(let M in t){let O=t[M];if(Dg(O)){let z=O.toDefinition();if(z.noSync){if(z.view!==void 0||z.unreliable||z.patchOnly||z.fullStateOnly||z.stream)throw new Error(`schema(${e?`'${e}'`:""}): field '${M}' uses .noSync() together with a sync-only modifier (.view/.unreliable/.patchOnly/.fullStateOnly/.stream). A local-only field cannot be synchronized.`);c(M,z);continue}if(z.patchOnly&&z.fullStateOnly)throw new Error(`schema(${e?`'${e}'`:""}): field '${M}' uses .patchOnly() together with .fullStateOnly(). Those are the only two delivery channels, so the field would never reach a client \u2014 use .noSync() if that is intended.`);let X=Vo(z.type);if(typeof X=="function"&&!Ye.is(X))throw new Error(`schema(${e?`'${e}'`:""}): field '${M}' is a synced ref to non-Schema class '${X.name||"(anonymous)"}' \u2014 use .noSync(), or Metadata.setFields().`);r[M]=X,z.view!==void 0&&(u[M]=z.view),z.unreliable&&l.push(M),z.patchOnly&&d.push(M),z.deprecated&&(f[M]=z.deprecatedThrows),z.fullStateOnly&&h.push(M),z.stream&&p.push(M),z.streamPriority!==void 0&&(g[M]=z.streamPriority),z.optional&&x.push(M),c(M,z)}else if(typeof O=="function")Ye.is(O)?(r[M]=Vo(O),(!O.prototype.initialize||O.prototype.initialize.length===0)&&(i[M]=()=>new O)):s[M]=O;else throw new Error(`schema(${e?`'${e}'`:""}): field '${M}' must be a t.* builder, Schema subclass, or method (got ${typeof O}).`)}let b=M=>{for(let O in o)M[O]=o[O];for(let O in i)M[O]=i[O]()},S=()=>{let M={};return b(M),M},_=M=>{let O=Object.keys(r),z={};for(let X in M)O.includes(X)||(z[X]=M[X]);return z},P=typeof s.initialize=="function",R=s.initialize??n._initialize,v=class extends n{constructor(...M){let O=M[0];O===void 0?(super(),b(this)):super(Object.assign(S(),P?_(O):O)),R&&new.target===v&&R.apply(this,M)}};e&&Object.defineProperty(v,"name",{value:e}),Ie.setFields(v,r),v._getDefaultValues=S,v._initialize=R,Object.assign(v.prototype,s);for(let M in u)$k(u[M])(v.prototype,M);for(let M of l)jk(v.prototype,M);for(let M of d)qk(v.prototype,M);for(let M in f)Zk(f[M])(v.prototype,M);if(h.length>0||p.length>0){let M=v[Symbol.metadata];for(let O of h)Ie.setFullStateOnly(M,O);for(let O of p)Ie.setStream(M,O);for(let O in g)Ie.setStreamPriority(M,O,g[O])}if(x.length>0){let M=v[Symbol.metadata];for(let O of x)M[M[O]].optional=!0}return v.extend=(M,O)=>It(M,O,v),v}function eP(t){return new Array(t).fill(0).map((e,n)=>n===t-1?"\u2514\u2500 ":" ").join("")}function tP(t,e){if(e===-1||e>=t.length)return!1;let n=t.length-1;for(let r=e;r<n;r++)t[r]=t[r+1];return t.length=n,!0}function nP(t,e,n){let r=~n,s=t.changeTrees;for(let o in s){let i=s[o],a=i.visibleViews;a!==void 0&&e<a.length&&(a[e]&=r);let c=i.subscribedViews;c!==void 0&&e<c.length&&(c[e]&=r);let u=i.tagViews;u!==void 0&&u.forEach(l=>{e<l.length&&(l[e]&=r)})}}function Ry(t){t.structSwitchEmitted||(t.shouldEmitSwitch&&(t.buffer[t.it.offset++]=255,be.number(t.buffer,t.ref[Q],t.it)),t.structSwitchEmitted=!0)}function sP(t,e){Ng(t,e,B.ADD)}function Bg(t,e){if(e._fullSyncGen===t.gen)return;if(e._fullSyncGen=t.gen,!t.hasView||t.view.isChangeTreeVisible(e)){let r=e.encDescriptor;t.changeTree=e,t.ref=e.ref,t.encoder=r.encoder,t.filter=r.filter,t.metadata=r.metadata,t.treeIsFiltered=e.isFiltered,t.isSchema=r.isSchema,t.filterBitmask=r.filterBitmask,t.tags=r.tags,t.structSwitchEmitted=!1,t.shouldEmitSwitch=t.hasView||t.it.offset>t.initialOffset||e!==t.rootChangeTree,e.isArray&&e.collDirty.size>0&&(e.flags|=Uf),Ff(e,t,sP)}ga(e,t,oP)}function oP(t,e,n){Bg(t,e)}function Ng(t,e,n){if(e<0){if(t.treeIsFiltered!==t.emitFiltered)return;Ry(t),t.buffer[t.it.offset++]=Math.abs(e)&255;return}if((t.isSchema?t.treeIsFiltered||(e<32?(t.filterBitmask&1<<e)!==0:t.tags[e]!==void 0):t.treeIsFiltered)!==t.emitFiltered)return;let s=t.isEncodeAll?B.ADD:n;s!==void 0&&(t.filter!==void 0&&!t.filter(t.ref,e,t.view)||(Ry(t),t.encoder(t.self,t.buffer,t.changeTree,e,s,t.it,t.isEncodeAll,t.hasView,t.metadata)))}function kf(t,e){let n=new Uint8Array(t.length+e.length);return n.set(t,0),n.set(e,t.length),n}function Ou(t){let e=t.root,n=e.callbacks,r=new WeakMap,s;t.triggerChanges=function(a){let c=new Set;for(let u=0,l=a.length;u<l;u++){let d=a[u],f=d.refId,h=d.ref,p=n[f];if(p){if((d.op&B.DELETE)===B.DELETE&&Ye.isSchema(d.previousValue)){let g=n[d.previousValue[Q]]?.[B.DELETE];for(let x=g?.length-1;x>=0;x--)g[x]()}if(Ye.isSchema(h)){if(!c.has(f)){let g=p?.[B.REPLACE];for(let x=g?.length-1;x>=0;x--)g[x]()}if(p.hasOwnProperty(d.field)){let g=p[d.field];for(let x=g?.length-1;x>=0;x--)g[x](d.value,d.previousValue)}}else{if((d.op&B.DELETE)===B.DELETE){if(d.previousValue!==void 0){let g=p[B.DELETE];for(let x=g?.length-1;x>=0;x--)g[x](d.previousValue,d.dynamicIndex??d.field)}if((d.op&B.ADD)===B.ADD){let g=p[B.ADD];for(let x=g?.length-1;x>=0;x--)g[x](d.value,d.dynamicIndex??d.field)}}else if((d.op&B.ADD)===B.ADD&&d.previousValue!==d.value){let g=p[B.ADD];for(let x=g?.length-1;x>=0;x--)g[x](d.value,d.dynamicIndex??d.field)}if(d.value!==d.previousValue&&(d.value!==void 0||d.previousValue!==void 0)){let g=p[B.REPLACE];for(let x=g?.length-1;x>=0;x--)g[x](d.value,d.dynamicIndex??d.field)}}c.add(f)}}};function o(a,c){let u=c.instance?.constructor[Symbol.metadata]||a,l=c.instance&&typeof c.instance.forEach=="function"||a&&!Ye.is(a);if(u&&!l){let d=function(f,h,p,g){return g&&c.instance[h]!==void 0&&!r.has(s)&&p(c.instance[h],void 0),e.addCallback(f[Q],h,p)};return new Proxy({listen:function(h,p,g=!0){if(c.instance)return d(c.instance,h,p,g);{let x=()=>{};return c.onInstanceAvailable((b,S)=>{x=d(b,h,p,g&&S&&!r.has(s))}),()=>x()}},onChange:function(h){return e.addCallback(c.instance[Q],B.REPLACE,h)},bindTo:function(h,p){return p||(p=Object.keys(u).map(g=>u[g].name)),e.addCallback(c.instance[Q],B.REPLACE,()=>{p.forEach(g=>h[g]=c.instance[g])})}},{get(f,h){let p=u[u[h]];if(p){let g=c.instance?.[h],x=(b=>{let S=i(c.instance).listen(h,(_,P)=>{b(_,!1),S?.()},!1);g?.[Q]!==void 0&&b(g,!0)});return o(p.type,{instance:g?.[Q]!==void 0&&g,parentInstance:c.instance,onInstanceAvailable:x})}else return f[h]},has(f,h){return u[h]!==void 0},set(f,h,p){throw new Error("not allowed")},deleteProperty(f,h){throw new Error("not allowed")}})}else{let d=function(p,g,x){return x&&p.forEach((b,S)=>g(b,S)),e.addCallback(p[Q],B.ADD,(b,S)=>{r.set(g,!0),s=g,g(b,S),r.delete(g),s=void 0})},f=function(p,g){return e.addCallback(p[Q],B.DELETE,g)},h=function(p,g){return e.addCallback(p[Q],B.REPLACE,g)};return new Proxy({onAdd:function(p,g=!0){if(c.instance)return d(c.instance,p,g&&!r.has(s));if(c.onInstanceAvailable){let x=()=>{};return c.onInstanceAvailable((b,S)=>{x=d(b,p,g&&S&&!r.has(s))}),()=>x()}},onRemove:function(p){if(c.instance)return f(c.instance,p);if(c.onInstanceAvailable){let g=()=>{};return c.onInstanceAvailable(x=>{g=f(x,p)}),()=>g()}},onChange:function(p){if(c.instance)return h(c.instance,p);if(c.onInstanceAvailable){let g=()=>{};return c.onInstanceAvailable(x=>{g=h(x,p)}),()=>g()}}},{get(p,g){if(!p[g])throw new Error(`Can't access '${g}' through callback proxy. access the instance directly.`);return p[g]},has(p,g){return p[g]!==void 0},set(p,g,x){throw new Error("not allowed")},deleteProperty(p,g){throw new Error("not allowed")}})}}function i(a){return o(void 0,{instance:a})}return i}function iP(t,e){t.triggerChanges=e}var B,my,Q,Zn,Qn,Tn,Ns,Qe,Cn,Ho,I,ge,rt,qr,Mn,Ru,kt,og,tn,aa,br,bt,Gr,An,gr,Ms,ua,ku,zo,nn,bu,TR,Du,Cs,Pf,MR,ig,CR,ag,be,ma,Is,LR,FR,zR,UR,Re,Df,WR,_g,ZR,Kn,Bs,yy,rk,Ie,Pg,vf,Tf,vg,fk,Cg,Au,vu,mk,yk,wy,Su,kk,Ef,_f,ia,Rf,ca,Fo,_u,Eu,la,Uf,Pk,Kr,Mf,vk,Tk,Vf,Mk,Ig,vn,Dk,Uu,Bk,da,Nk,Sy,Py,Ay,vy,Ty,My,Cy,Oy,en,Wr,Tu,Iy,Dy,By,Ny,Ly,Xn,Yr,Fy,zy,Uy,Vy,Hy,$r,fa,$y,jy,qy,Gy,Wy,jr,pa,Yy,Ky,Xy,Jy,Zy,wr,Mu,Qy,er,Lk,Fk,zk,Uk,Vk,Hk,q,Hu,Gk,eg,tg,ng,rg,Pn,Ye,_y,Cf,FD,rP,Jn,ha,Cu,ky,Of,In,Lg,Fg,zg,Dn,Iu,jf,wt=at(()=>{"use strict";(function(t){t[t.ADD=128]="ADD",t[t.REPLACE=0]="REPLACE",t[t.DELETE=64]="DELETE",t[t.DELETE_AND_MOVE=96]="DELETE_AND_MOVE",t[t.MOVE_AND_ADD=160]="MOVE_AND_ADD",t[t.DELETE_AND_ADD=192]="DELETE_AND_ADD",t[t.CLEAR=10]="CLEAR",t[t.REVERSE=15]="REVERSE",t[t.MOVE=32]="MOVE",t[t.DELETE_BY_REFID=33]="DELETE_BY_REFID",t[t.ADD_BY_REFID=129]="ADD_BY_REFID"})(B||(B={}));Symbol.metadata??(Symbol.metadata=Symbol.for("Symbol.metadata"));my=(function(){return typeof globalThis<"u"?globalThis:typeof global<"u"?global:typeof self<"u"?self:typeof window<"u"?window:{}})();if(typeof Symbol=="function"&&typeof Symbol.for!="function"){let t="colyseus.symbolRegistry",e=my[t]||(my[t]=Object.create(null));Symbol.for=function(n){return e[n]||(e[n]=Symbol(n))},Symbol.keyFor=function(n){for(let r in e)if(e[r]===n)return r}}Q=Symbol.for("$refId"),Zn="~track",Qn="~encoder",Tn="~decoder",Ns="~filter",Qe="~getByIndex",Cn="~deleteByIndex",Ho="~resyncPrune",I=Symbol.for("$changes"),ge=Symbol.for("$childType"),rt=Symbol.for("$proxyTarget"),qr="~onEncodeEnd",Mn="~reset",Ru="~onDecodeEnd",kt=Symbol.for("$values"),og="~builder",tn="~descriptors",aa="~__encodeDescriptor",br="~encoders",bt="~__numFields",Gr="~__refTypeFieldIndexes",An="~__viewFieldIndexes",gr="$__fieldIndexesByViewTag",Ms="~__unreliableFieldIndexes",ua="~__patchOnlyFieldIndexes",ku="~__fullSyncSkipIndexes",zo="~__fullStateOnlyFieldIndexes",nn="~__streamFieldIndexes",bu="~__streamPriorities";try{TR=new TextEncoder}catch{}Du=new ArrayBuffer(8),Cs=new Int32Array(Du),Pf=new Float32Array(Du),MR=new Float64Array(Du),ig=new BigInt64Array(Du),CR=typeof Buffer<"u"&&Buffer.byteLength,ag=CR?Buffer.byteLength:function(t,e){for(var n=0,r=0,s=0,o=t.length;s<o;s++)n=t.charCodeAt(s),n<128?r+=1:n<2048?r+=2:n<55296||n>=57344?r+=3:(s++,r+=4);return r};be={int8:ug,uint8:OR,int16:lg,uint16:If,int32:xr,uint32:Os,int64:dg,uint64:fg,bigint64:IR,biguint64:DR,float32:pg,float64:hg,boolean:BR,string:NR,number:Af,utf8Write:cg,utf8Length:ag},ma=new ArrayBuffer(8),Is=new Int32Array(ma),LR=new Float32Array(ma),FR=new Float64Array(ma),zR=new BigUint64Array(ma),UR=new BigInt64Array(ma);Re={utf8Read:mg,int8:yg,uint8:ya,int16:gg,uint16:Bu,int32:On,uint32:Uo,float32:bg,float64:wg,int64:xg,uint64:Sg,bigint64:VR,biguint64:HR,boolean:$R,string:jR,number:qR,stringCheck:GR},Df={},WR=new Map;_g="ArraySchema does not support streaming \u2014 positional ops (splice / unshift / reverse) shift subsequent indexes, so holding ADDs back for a later tick under `maxPerTick` would desync the decoder. Use `t.stream(X)` (stable monotonic positions) or `t.map(X).stream()` (stable keys) instead.";ZR={8:"uint8",16:"uint16",32:"uint32"};Kn=class Kn{constructor(e){m(this,"types",{});m(this,"schemas",new Map);m(this,"hasFilters",!1);e&&this.discoverTypes(e)}static register(e){let n=Object.getPrototypeOf(e);if(n!==Ye){let r=Kn.inheritedTypes.get(n);r||(r=new Set,Kn.inheritedTypes.set(n,r)),r.add(e)}}static cache(e){let n=Kn.cachedContexts.get(e);return n||(n=new Kn(e),Kn.cachedContexts.set(e,n)),n}has(e){return this.schemas.has(e)}get(e){return this.types[e]}add(e,n=this.schemas.size){return this.schemas.has(e)?!1:(this.types[n]=e,e[Symbol.metadata]==null&&Ie.initialize(e),this.schemas.set(e,n),!0)}getTypeId(e){return this.schemas.get(e)}discoverTypes(e){if(!this.add(e))return;Kn.inheritedTypes.get(e)?.forEach(s=>{this.discoverTypes(s)});let n=e;for(;(n=Object.getPrototypeOf(n))&&n!==Ye&&n!==Function.prototype;)this.discoverTypes(n);let r=e[Symbol.metadata];(r[An]||r[nn])&&(this.hasFilters=!0);for(let s in r){let i=r[s].type;if(typeof i!="string"&&!Ds(i))if(typeof i=="function")this.discoverTypes(i);else{let a=Object.values(i)[0];if(typeof a=="string")continue;this.discoverTypes(a)}}}debug(){return`TypeContext ->
2
+ Schema types: ${this.schemas.size}
3
+ hasFilters: ${this.hasFilters}`}};m(Kn,"inheritedTypes",new WeakMap),m(Kn,"cachedContexts",new WeakMap);Bs=Kn,yy=63;rk=[Gr,Ms,ua,ku,zo,nn,br];Ie={addField(t,e,n,r,s){if(e>=yy)throw new Error(`Can't define field '${n}'.
4
+ Schema instances may only have up to ${yy} fields.`);t[e]=Object.assign(t[e]||{},{type:Vo(r),index:e,name:n}),Object.defineProperty(t,tn,{value:t[tn]||{},enumerable:!1,configurable:!0}),s?t[tn][n]=s:t[tn][n]={value:void 0,writable:!0,enumerable:!0,configurable:!0},Object.defineProperty(t,bt,{value:e,enumerable:!1,configurable:!0}),Object.defineProperty(t,n,{value:e,enumerable:!1,configurable:!0}),typeof t[e].type!="string"&&!Ds(t[e].type)&&(t[Gr]===void 0&&Object.defineProperty(t,Gr,{value:[],enumerable:!1,configurable:!0}),t[Gr].push(e));let o=t[e].type;if(o&&typeof o=="object"&&o.stream!==void 0){if(o.array!==void 0)throw new Error(_g);t[e].stream=!0,t[nn]||Object.defineProperty(t,nn,{value:[],enumerable:!1,configurable:!0,writable:!0}),t[nn].includes(e)||t[nn].push(e);let i=r?.priority;typeof i=="function"&&Ie.setStreamPriority(t,n,i)}},setTag(t,e,n){let r=t[e],s=t[r];if(s.tag=n,t[An]||(Object.defineProperty(t,An,{value:[],enumerable:!1,configurable:!0}),Object.defineProperty(t,gr,{value:{},enumerable:!1,configurable:!0})),t[An].push(r),n<0)t[gr][n]||(t[gr][n]=[]),t[gr][n].push(r);else for(let o=n;o>0;o&=o-1){let i=o&-o;t[gr][i]||(t[gr][i]=[]),t[gr][i].push(r)}},setUnreliable(t,e){let n=t[e];if(typeof t[n].type!="string")throw new Error(`@unreliable cannot be applied to ref-type field "${e}". For ref-type fields, mark each primitive sub-field with @unreliable instead. See README "Limitations and best practices".`);t[n].unreliable=!0,t[Ms]||Object.defineProperty(t,Ms,{value:[],enumerable:!1,configurable:!0,writable:!0}),t[Ms].push(n)},setPatchOnly(t,e){let n=t[e];if(t[n].fullStateOnly)throw new Error(`field "${e}" cannot be both patchOnly and fullStateOnly \u2014 those are the only two delivery channels, so the field would never reach a client.`);t[n].patchOnly=!0,wu(t,ua,n),wu(t,ku,n)},setDeprecated(t,e){let n=t[e];t[n].deprecated=!0,wu(t,ku,n),Object.defineProperty(t,n,{value:t[n],enumerable:!1,configurable:!0})},setFullStateOnly(t,e){let n=t[e];if(t[n].patchOnly)throw new Error(`field "${e}" cannot be both patchOnly and fullStateOnly \u2014 those are the only two delivery channels, so the field would never reach a client.`);t[n].fullStateOnly=!0,wu(t,zo,n)},setStream(t,e){let n=t[e];t[n].stream=!0,t[nn]||Object.defineProperty(t,nn,{value:[],enumerable:!1,configurable:!0,writable:!0}),t[nn].push(n)},setStreamPriority(t,e,n){let r=t[e];t[bu]||Object.defineProperty(t,bu,{value:{},enumerable:!1,configurable:!0,writable:!0}),t[bu][r]=n},getStreamPriority(t,e){return t?.[bu]?.[e]},defineField(t,e,n,r,s){let o=Vo(s),{complexTypeKlass:i,childType:a}=tk(o);Ie.addField(e,n,r,o,Jk(r,n,a,i)),e[tn][r]&&Object.defineProperty(t.prototype,r,e[tn][r]),(typeof o=="string"||Ds(o))&&(e[br]||Object.defineProperty(e,br,{value:[],enumerable:!1,configurable:!0,writable:!0}),e[br][n]=typeof o=="string"?be[o]:QR(o.quantized))},setFields(t,e){let n=t.prototype.constructor;Bs.register(n);let r=Object.getPrototypeOf(n),s=r&&r[Symbol.metadata],o=Ie.initialize(n);n[Zn]||(n[Zn]=Ye[Zn]),n[Qn]||(n[Qn]=Ye[Qn]),n[Tn]||(n[Tn]=Ye[Tn]),n.prototype.toJSON||(n.prototype.toJSON=Ye.prototype.toJSON);let i=o[bt]??(s&&s[bt])??-1;i++,o[br]||Object.defineProperty(o,br,{value:s?.[br]?[...s[br]]:[],enumerable:!1,configurable:!0,writable:!0});for(let a in e){if(o[a]!==void 0)throw new Error(`@colyseus/schema: Duplicate '${a}' definition on '${n.name||"(anonymous)"}'.`);Ie.defineField(n,o,i,a,e[a]),i++}return t},isDeprecated(t,e){return t[e].deprecated===!0},initialize(t){let e=Object.getPrototypeOf(t),n=e[Symbol.metadata],r=t[Symbol.metadata]??Object.create(null);if(e!==Ye&&r===n&&(r=Object.create(null),n)){Object.setPrototypeOf(r,n),Object.defineProperty(r,bt,{value:n[bt],enumerable:!1,configurable:!0,writable:!0}),n[An]!==void 0&&(Object.defineProperty(r,An,{value:[...n[An]],enumerable:!1,configurable:!0,writable:!0}),Object.defineProperty(r,gr,{value:{...n[gr]},enumerable:!1,configurable:!0,writable:!0}));for(let s of rk){let o=n[s];o!==void 0&&Object.defineProperty(r,s,{value:[...o],enumerable:!1,configurable:!0,writable:!0})}Object.defineProperty(r,tn,{value:{...n[tn]},enumerable:!1,configurable:!0,writable:!0})}return Object.defineProperty(t,Symbol.metadata,{value:r,writable:!1,configurable:!0}),r},isValidInstance(t){return t.constructor[Symbol.metadata]&&Object.prototype.hasOwnProperty.call(t.constructor[Symbol.metadata],bt)},getFields(t){let e=t[Symbol.metadata],n={};for(let r=0;r<=e[bt];r++)n[e[r].name]=e[r].type;return n},hasViewTagAtIndex(t,e){return t?.[An]?.includes(e)},hasUnreliableAtIndex(t,e){return t?.[Ms]?.includes(e)},hasPatchOnlyAtIndex(t,e){return t?.[ua]?.includes(e)},hasFullStateOnlyAtIndex(t,e){return t?.[zo]?.includes(e)},hasStreamAtIndex(t,e){return t?.[nn]?.includes(e)}},Pg=(t,e,n)=>t(e,n),vf=class{constructor(e){m(this,"dirtyLow",0);m(this,"dirtyHigh",0);m(this,"ops");this.ops=new Uint8Array(Math.max(e+1,1))}record(e,n){let r=this.ops[e];r===0?this.ops[e]=n:r===B.DELETE?this.ops[e]=B.DELETE_AND_ADD:r===B.ADD&&n===B.DELETE_AND_ADD&&(this.ops[e]=B.DELETE_AND_ADD),e<32?this.dirtyLow|=1<<e:this.dirtyHigh|=1<<e-32}recordDelete(e,n){this.ops[e]=n,e<32?this.dirtyLow|=1<<e:this.dirtyHigh|=1<<e-32}recordRaw(e,n){this.record(e,n)}operationAt(e){let n=this.ops[e];return n===0?void 0:n}setOperationAt(e,n){this.ops[e]=n}forEach(e){this.forEachWithCtx(e,Pg)}forEachWithCtx(e,n){let r=this.dirtyLow,s=this.dirtyHigh,o=this.ops;for(;r!==0;){let i=r&-r,a=31-Math.clz32(i);r^=i,n(e,a,o[a])}for(;s!==0;){let i=s&-s,a=31-Math.clz32(i)+32;s^=i,n(e,a,o[a])}}size(){return Pu(this.dirtyLow)+Pu(this.dirtyHigh)}has(){return(this.dirtyLow|this.dirtyHigh)!==0}reset(){this.dirtyLow=0,this.dirtyHigh=0,this.ops.fill(0)}},Tf=class{constructor(){m(this,"dirty",new Map);m(this,"pureOps",[])}record(e,n){let r=this.dirty.get(e);r===void 0?this.dirty.set(e,n):r===B.DELETE?this.dirty.set(e,B.DELETE_AND_ADD):r===B.ADD&&n===B.DELETE_AND_ADD&&this.dirty.set(e,B.DELETE_AND_ADD)}recordDelete(e,n){this.dirty.set(e,n)}recordRaw(e,n){this.dirty.set(e,n)}recordPure(e){this.pureOps.push([this.dirty.size,e])}operationAt(e){return this.dirty.get(e)}setOperationAt(e,n){this.dirty.has(e)&&this.dirty.set(e,n)}forEach(e){this.forEachWithCtx(e,Pg)}forEachWithCtx(e,n){let r=this.pureOps;if(r.length>0){let s=0,o=0;for(let[i,a]of this.dirty){for(;s<r.length&&r[s][0]<=o;){let c=r[s++][1];n(e,-c,c)}n(e,i,a),o++}for(;s<r.length;){let i=r[s++][1];n(e,-i,i)}}else for(let[s,o]of this.dirty)n(e,s,o)}size(){return this.dirty.size+this.pureOps.length}has(){return this.dirty.size>0||this.pureOps.length>0}reset(){this.dirty.clear(),this.pureOps.length=0}shift(e){let n=new Map;for(let[r,s]of this.dirty)n.set(r+e,s);this.dirty=n}};vg=(t,e)=>{t.isFieldUnreliable(e)?t.ensureUnreliableRecorder().record(e,B.ADD):t.record(e,B.ADD)},fk=(t,e)=>t(e);Cg=1,Au=2,vu=4,mk=Cg|Au|vu;yk=(t,e,n)=>{zf(e)};wy=[],Su=0;kk=(t,e,n)=>t(e,n);Ef=1,_f=2,ia=4,Rf=8,ca=16,Fo=32,_u=64,Eu=128,la=256,Uf=512,Pk=ca|Fo,Kr=class{constructor(e,n=e){m(this,"ref");m(this,"refTarget");m(this,"metadata");m(this,"encDescriptor");m(this,"root");m(this,"parentRef");m(this,"_parentIndex");m(this,"extraParents");m(this,"flags",ia);m(this,"_fullSyncGen",0);m(this,"_isSchema",!1);m(this,"dirtyLow",0);m(this,"dirtyHigh",0);m(this,"opsLow",0);m(this,"opsHigh",0);m(this,"ops");m(this,"collDirty");m(this,"collPureOps");m(this,"unreliableRecorder");m(this,"paused",!1);m(this,"changesNode");m(this,"unreliableChangesNode");m(this,"visibleViews");m(this,"tagViews");m(this,"subscribedViews");this.ref=e,this.refTarget=n;let r=Lf(e);this.encDescriptor=r,this.metadata=r.metadata;let s=r.isSchema;if(this._isSchema=s,this.ops=void 0,this.collDirty=void 0,this.collPureOps=void 0,s){let o=this.metadata?.[bt]??0;o>7&&(this.ops=new Uint8Array(o+1))}else this.collDirty=new Map}get isArray(){return this.refTarget!==this.ref}get isFiltered(){return(this.flags&Ef)!==0}set isFiltered(e){this.flags=e?this.flags|Ef:this.flags&~Ef}get isVisibilitySharedWithParent(){return(this.flags&_f)!==0}set isVisibilitySharedWithParent(e){this.flags=e?this.flags|_f:this.flags&~_f}get isNew(){return(this.flags&ia)!==0}set isNew(e){this.flags=e?this.flags|ia:this.flags&~ia}get isUnreliable(){return(this.flags&Rf)!==0}set isUnreliable(e){this.flags=e?this.flags|Rf:this.flags&~Rf}get isPatchOnly(){return(this.flags&ca)!==0}set isPatchOnly(e){this.flags=e?this.flags|ca:this.flags&~ca}get isFullStateOnly(){return(this.flags&Fo)!==0}set isFullStateOnly(e){this.flags=e?this.flags|Fo:this.flags&~Fo}get isStreamCollection(){return(this.flags&_u)!==0}set isStreamCollection(e){this.flags=e?this.flags|_u:this.flags&~_u}get needsRestage(){return(this.flags&Eu)!==0}set needsRestage(e){this.flags=e?this.flags|Eu:this.flags&~Eu}get hasFilteredFields(){return this.isFiltered||this.encDescriptor.hasAnyView}ensureUnreliableRecorder(){return this.unreliableRecorder===void 0&&(this.unreliableRecorder=this._isSchema?new vf(this.metadata?.[bt]??0):new Tf),this.unreliableRecorder}isFieldUnreliable(e){let n=this.encDescriptor;return n.hasAnyUnreliable?e<32?(n.unreliableBitmask&1<<e)!==0:Ie.hasUnreliableAtIndex(this.metadata,e):!1}isFieldFullStateOnly(e){if(this.isFullStateOnly)return!0;let n=this.encDescriptor;return n.hasAnyFullStateOnly?e<32?(n.fullStateOnlyBitmask&1<<e)!==0:Ie.hasFullStateOnlyAtIndex(this.metadata,e):!1}isFieldStream(e){let n=this.encDescriptor;return n.hasAnyStream?e<32?(n.streamBitmask&1<<e)!==0:Ie.hasStreamAtIndex(this.metadata,e):!1}_opAt(e){let n=this.ops;if(n!==void 0)return n[e];let r=(e&3)<<3;return e<4?this.opsLow>>>r&255:this.opsHigh>>>r&255}_opPut(e,n){let r=this.ops;if(r!==void 0){r[e]=n;return}let s=(e&3)<<3,o=~(255<<s);e<4?this.opsLow=this.opsLow&o|n<<s:this.opsHigh=this.opsHigh&o|n<<s}_markDirty(e){e<32?this.dirtyLow|=1<<e:this.dirtyHigh|=1<<e-32}record(e,n){if(this._isSchema){let r=this._opAt(e);r===0?this._opPut(e,n):r===B.DELETE?this._opPut(e,B.DELETE_AND_ADD):r===B.ADD&&n===B.DELETE_AND_ADD&&this._opPut(e,B.DELETE_AND_ADD),this._markDirty(e)}else{let r=this.collDirty,s=r.get(e),o;s===void 0?o=n:s===B.DELETE||s===B.ADD&&n===B.DELETE_AND_ADD?o=B.DELETE_AND_ADD:o=s,r.set(e,o)}}recordDelete(e,n){this._isSchema?(this._opPut(e,n),this._markDirty(e)):this.collDirty.set(e,n)}recordRaw(e,n){this._isSchema?(this._opPut(e,n),this._markDirty(e)):this.collDirty.set(e,n)}recordPure(e){if(this._isSchema)throw new Error("ChangeTree (Schema): pure operations are not supported");(this.collPureOps??(this.collPureOps=[])).push([this.collDirty.size,e])}operationAt(e){if(this._isSchema){let n=this._opAt(e);return n===0?void 0:n}return this.collDirty.get(e)}setOperationAt(e,n){if(this._isSchema)this._opPut(e,n);else{let r=this.collDirty;r.has(e)&&r.set(e,n)}}forEach(e){this.forEachWithCtx(e,kk)}forEachWithCtx(e,n){if(this._isSchema){let o=this.dirtyLow,i=this.dirtyHigh,a=this.ops;if(a!==void 0){for(;o!==0;){let c=o&-o,u=31-Math.clz32(c);o^=c,n(e,u,a[u])}for(;i!==0;){let c=i&-i,u=31-Math.clz32(c)+32;i^=c,n(e,u,a[u])}}else{let c=this.opsLow,u=this.opsHigh;for(;o!==0;){let l=o&-o,d=31-Math.clz32(l);o^=l,n(e,d,Rk(c,u,d))}}return}let r=this.collDirty,s=this.collPureOps;if(s!==void 0&&s.length>0){let o=0,i=0;for(let[a,c]of r){for(;o<s.length&&s[o][0]<=i;){let u=s[o++][1];n(e,-u,u)}n(e,a,c),i++}for(;o<s.length;){let a=s[o++][1];n(e,-a,a)}}else for(let[o,i]of r)n(e,o,i)}size(){return this._isSchema?Pu(this.dirtyLow)+Pu(this.dirtyHigh):this.collDirty.size+(this.collPureOps?.length??0)}has(){return this._isSchema?(this.dirtyLow|this.dirtyHigh)!==0:this.collDirty.size>0||this.collPureOps!==void 0&&this.collPureOps.length>0}reset(){if(this._isSchema){this.dirtyLow=0,this.dirtyHigh=0,this.ops!==void 0?this.ops.fill(0):(this.opsLow=0,this.opsHigh=0);return}this.collDirty.clear(),this.collPureOps!==void 0&&(this.collPureOps.length=0),this.flags&=~Uf}recycle(){if(this.root!==void 0)throw new Error(`@colyseus/schema: cannot recycle an attached ChangeTree (${this.ref?.constructor?.name}). Remove the instance from its parent collection before releasing it to a pool.`);this.reset(),this.unreliableRecorder?.reset(),this.flags=ia|Eu,this._fullSyncGen=0,this.parentRef=void 0,this._parentIndex=void 0,this.extraParents=void 0,this.changesNode=void 0,this.unreliableChangesNode=void 0,this.paused=!1,this.visibleViews=void 0,this.tagViews=void 0,this.subscribedViews=void 0}insertAt(e,n){if(this._isSchema)throw new Error("ChangeTree (Schema): insertAt is not supported");let r=this.collDirty,s=new Map,o=!this.paused&&!this.isFullStateOnly;if(e>0)for(let[i,a]of r)i<e&&s.set(i,a);if(o)for(let i=0;i<n;i++)s.set(e+i,B.ADD);for(let[i,a]of r)i>=e&&s.set(i+n,a);this.collDirty=s,o&&this.root?.enqueueChangeTree(this)}removeAt(e,n){if(this._isSchema)throw new Error("ChangeTree (Schema): removeAt is not supported");let r=this.collDirty,s=e+n,o=!1;for(let a of r.keys())if(a>=s){o=!0;break}if(!o){for(let a=e;a<s;a++)r.delete(a);return}let i=new Map;for(let[a,c]of r)a<e?i.set(a,c):a>=s&&i.set(a-n,c);this.collDirty=i}unshift(e){this.insertAt(0,e)}setRoot(e){bk(this,e)}setParent(e,n,r){wk(this,e,n,r)}forEachChild(e){xk(this,e)}forEachChildWithCtx(e,n){ga(this,e,n)}forEachLive(e){pk(this,e)}forEachLiveWithCtx(e,n){Ff(this,e,n)}operation(e){this.paused||this.isFullStateOnly||(this.recordPure(e),this.root?.enqueueChangeTree(this))}_routeAndRecord(e,n,r){if(!(this.paused||this.isFieldFullStateOnly(e))){if(this.isFieldUnreliable(e)&&!this.isNew){let s=this.ensureUnreliableRecorder();r?s.recordRaw(e,n):s.record(e,n),this.root?.enqueueUnreliable(this);return}r?this.recordRaw(e,n):this.record(e,n),this.root?.enqueueChangeTree(this)}}change(e,n=B.ADD){this._routeAndRecord(e,n,!1)}indexedOperation(e,n){this._routeAndRecord(e,n,!0)}getChange(e){return this.operationAt(e)}pause(){this.paused=!0}resume(){this.paused=!1}untracked(e){let n=this.paused;this.paused=!0;try{return e()}finally{this.paused=n}}markDirty(e,n=B.ADD){let r=this.paused;this.paused=!1;try{this.change(e,n)}finally{this.paused=r}}getValue(e,n=!1){return this.refTarget[Qe](e,n)}delete(e,n){if(e===void 0){try{throw new Error(`@colyseus/schema ${this.ref.constructor.name}: trying to delete non-existing index '${e}'`)}catch(o){console.warn(o)}return}if(this.paused||this.isFieldFullStateOnly(e))return this.getValue(e);let r=this.isFieldUnreliable(e)&&!this.isNew;r?this.ensureUnreliableRecorder().recordDelete(e,n??B.DELETE):this.recordDelete(e,n??B.DELETE);let s=this.getValue(e);return s&&s[I]&&this.root?.remove(s[I]),r?this.root?.enqueueUnreliable(this):this.root?.enqueueChangeTree(this),s}endEncode(){this.reset(),this.changesNode=void 0,this._isSchema||this.refTarget[qr]?.(),this.isNew=!1}endEncodeUnreliable(){this.unreliableRecorder?.reset(),this.unreliableChangesNode=void 0,this._isSchema||this.refTarget[qr]?.()}discard(){this._isSchema||this.refTarget[qr]?.(),this.reset(),this.unreliableRecorder?.reset()}discardAll(){let e=n=>{if(n<0)return;let r=this.getValue(n);r&&r[I]&&r[I].discardAll()};this.forEach(e),this.unreliableRecorder?.forEach(e),this.discard()}get changed(){return this.has()||(this.unreliableRecorder?.has()??!1)}get parent(){return this.parentRef}get parentIndex(){return this._parentIndex}addParent(e,n){ok(this,e,n)}setParentIndex(e,n){ik(this,e,n)}removeParent(e=this.parent){return ak(this,e)}findParent(e){return ck(this,e)}hasParent(e){return Ag(this,e)}indexInParent(e){return uk(this,e)}getAllParents(){return lk(this)}},Mf=class{constructor(e){m(this,"ref");m(this,"root");m(this,"parentRef");m(this,"paused",!1);m(this,"isNew",!1);m(this,"flags",0);this.ref=e}change(){}delete(){}indexedOperation(){}operation(){}setParent(){}addParent(){}setParentIndex(){}removeParent(){return!1}getChange(){return 0}discard(){}discardAll(){}pause(){}resume(){}untracked(e){return e()}markDirty(){}forEachChild(e){let n=this.ref;if(n[ge]){if(typeof n[ge]!="string")for(let[i,a]of n.entries())a&&e(a[I],n._collectionIndexes?.[i]??i);return}let s=n.constructor?.[Symbol.metadata];if(!s)return;let o=s[Gr]??[];for(let i=0;i<o.length;i++){let a=o[i],c=n[s[a].name];c&&e(c[I],a)}}forEachChildWithCtx(e,n){this.forEachChild((r,s)=>n(e,r,s))}forEachLive(){}forEachLiveWithCtx(){}forEach(){}};vk=function(t,e,n,r,s,o,i,a){if(e[o.offset++]=(r|s)&255,s===B.DELETE)return;let c=n.encDescriptor,u=n.ref,l=u[kt][r]??u[c.names[r]];zu(t,e,c.types[r],l,s,o,c.encoders[r])},Tk=function(t,e,n,r,s,o){if(e[o.offset++]=s&255,be.number(e,r,o),s===B.DELETE)return;let i=n.ref;if((s&B.ADD)===B.ADD){let a=i.$indexes.get(r);be.string(e,a,o)}zu(t,e,i[ge],i[Qe](r),s,o)},Vf=function(t,e,n,r,s,o){if(e[o.offset++]=s&255,be.number(e,r,o),s===B.DELETE)return;let i=n.ref;zu(t,e,i[ge],i[Qe](r),s,o)},Mk=function(t,e,n,r,s,o,i,a){let c=n.refTarget,u=c[ge],l=typeof u!="string",d=a&&n.isFiltered&&l,f;if(d){let p=c.tmpItems[r];if(!p)return;if(f=p[Q],s===B.DELETE)s=B.DELETE_BY_REFID;else if((s&B.ADD)===B.ADD)s=B.ADD_BY_REFID;else if((s&B.MOVE)===B.MOVE)return}else if(s===B.DELETE&&l){let p=c.tmpItems[r];if(!p)return;f=p[Q],s=B.DELETE_BY_REFID}else f=r;if(e[o.offset++]=s&255,be.number(e,f,o),s===B.DELETE||s===B.DELETE_BY_REFID)return;let h=c[Qe](r,i);zu(t,e,u,h,s,o)};Ig=-1,vn={Map:1,Array:2,Set:3,Collection:4,Stream:5};Dk=function(t,e,n,r,s){let o=e[n.offset++],i=r.constructor[Symbol.metadata],a=o>>6<<6,c=o%(a||255),u=i[c];if(u===void 0)return console.warn("@colyseus/schema: field not defined at",{index:c,ref:r.constructor.name,metadata:i}),Ig;let l=u.deprecated===!0,d=l?void 0:r[Qe](c),f=$f(t,a,r,c,d,u.type,e,n,s);l||(f!=null&&(r[u.name]=f),d!==f&&s?.push({ref:r,refId:t.currentRefId,op:a,field:u.name,value:f,previousValue:d}))},Uu=function(t,e,n,r,s){let o=r[rt]??r,i=e[n.offset++];if(i===B.CLEAR){t.removeChildRefs(o,s),o.clear();return}let a=Re.number(e,n),c=o[ge],u=o.constructor.COLLECTION_KIND,l;(i&B.ADD)===B.ADD?u===vn.Map?(l=Re.string(e,n),o.setIndex(a,l)):l=a:l=o.getIndex(a);let d=o[Qe](a),f=$f(t,i,r,a,d,c,e,n,s);if(t.resyncVisited!==null&&Og(t,r,i,l,d,f,s),f!=null)switch(u){case vn.Map:o.$items.set(l,f);break;case vn.Array:o.$setAt(a,f,t.resyncVisited!==null&&i===B.ADD?B.REPLACE:i);break;case vn.Set:case vn.Collection:case vn.Stream:o.$items.has(a)||(o.$items.set(a,f),typeof o.$refId=="number"&&a>=o.$refId&&(o.$refId=a+1));break;default:console.warn(`@colyseus/schema: missing COLLECTION_KIND on ${o.constructor?.name} \u2014 item at index ${a} was not stored.`);break}d!==f&&s?.push({ref:r,refId:t.currentRefId,op:i,dynamicIndex:l,value:f,previousValue:d})},Bk=function(t,e,n,r,s){let o=r[rt]??r,i=e[n.offset++],a;if(i===B.CLEAR){t.removeChildRefs(o,s),o.clear();return}else if(i===B.REVERSE){o.items.reverse();return}else if(i===B.DELETE_BY_REFID){let f=Re.number(e,n),h=t.root.refs.get(f);if(h===void 0||(t.root.removeRef(f),a=o.findIndex(p=>p===h),a===-1))return;o[Cn](a),s?.push({ref:r,refId:t.currentRefId,op:B.DELETE,dynamicIndex:a,value:void 0,previousValue:h});return}else if(i===B.ADD_BY_REFID){let f=Re.number(e,n),h=t.root.refs.get(f);h&&(a=o.findIndex(p=>p===h)),(a===-1||a===void 0)&&(a=o.length)}else a=Re.number(e,n);let c=o[ge],u=a,l=o.items[a],d=$f(t,i,r,a,l,c,e,n,s);t.resyncVisited!==null&&Og(t,r,i,a,l,d,s),d!=null&&d!==l&&o.$setAt(a,d,t.resyncVisited!==null&&i===B.ADD?B.REPLACE:i),l!==d&&s?.push({ref:r,refId:t.currentRefId,op:i,dynamicIndex:u,value:d,previousValue:l})},da=class extends Error{};Nk=(t,e)=>{let n=t.toString(),r=e.toString();return n<r?-1:n>r?1:0},Sy={get:(t,e)=>typeof e!="symbol"&&!isNaN(e)?t.items[e]:Reflect.get(t,e),set:(t,e,n)=>{if(typeof e!="symbol"&&!isNaN(e)){if(n==null)t.$deleteAt(e);else{let r;if(n[I]){Vu(n,t[ge],t,e);let s=t.items[e];t.isMovingItems?(r=t.$wireIndex(Number(e)),s!==void 0?n[I].isNew?t[I].indexedOperation(r,B.MOVE_AND_ADD):(t[I].getChange(r)&B.DELETE)===B.DELETE?t[I].indexedOperation(r,B.DELETE_AND_MOVE):t[I].indexedOperation(r,B.MOVE):n[I].isNew&&t[I].indexedOperation(r,B.ADD),n[I].setParent(t,t[I].root,r)):r=t.$changeAt(Number(e),n),s!==void 0&&s[I].root?.remove(s[I])}else r=t.$changeAt(Number(e),n);t.items[e]=n,r!==void 0&&(t.tmpItems[r]=n)}return!0}return Reflect.set(t,e,n)},deleteProperty:(t,e)=>(typeof e=="number"?t.$deleteAt(e):delete t[e],!0),has:(t,e)=>typeof e!="symbol"&&!isNaN(Number(e))?Reflect.has(t.items,e):Reflect.has(t,e)},en=class en{constructor(...e){m(this,Oy);m(this,Cy);m(this,My);m(this,Ty);m(this,"items",[]);m(this,"tmpItems",[]);m(this,"deletedIndexes",[]);m(this,"isMovingItems",!1);m(this,"_needsCompaction",!1);m(this,Py);this[ge]=void 0,this[rt]=this;let n=new Proxy(this,Sy);return Object.defineProperty(this,I,{value:new Kr(n,this),enumerable:!1,writable:!0}),e.length>0&&this.push(...e),n}static[(Oy=I,Cy=Q,My=rt,Ty=ge,vy=Qn,Ay=Tn,Ns)](e,n,r){if(!r)return!0;let s=e[rt]??e;return typeof s[ge]=="string"||r.isChangeTreeVisible(s.tmpItems[n]?.[I])}static is(e){return Array.isArray(e)||e.array!==void 0}static from(e){return new en(...Array.from(e))}static initializeForDecoder(){let e=Object.create(en.prototype);e.items=[],e.isMovingItems=!1,e._needsCompaction=!1,e[ge]=void 0,e[rt]=e;let n=new Proxy(e,Sy);return $o(e,n),n}set length(e){e===0?this.clear():e<this.items.length?this.splice(e,this.length-e):console.warn("ArraySchema: can't set .length to a higher value than its length.")}get length(){return this.items.length}pauseTracking(){this[I].pause()}resumeTracking(){this[I].resume()}untracked(e){return this[I].untracked(e)}get isTrackingPaused(){return this[I].paused}push(...e){let n=this[rt],r=n.items,s=n.tmpItems,o=n[I],i=n[ge],a=s.length;for(let c=0,u=e.length;c<u;c++,a++){let l=e[c];if(l==null)return;typeof l=="object"&&i&&Vu(l,i,n,c),o.indexedOperation(a,B.ADD),r.push(l),s.push(l),l[I]?.setParent(this,o.root,a)}return a}pop(){let e=this[rt],n=e.tmpItems,r=e.deletedIndexes,s=-1;for(let i=n.length-1;i>=0;i--)if(r[i]!==!0){s=i;break}if(s<0)return;let o=e.$isUnsentAdd(s);return e[I].delete(s),o?e.$cancelAdd(s):r[s]=!0,e.items.pop()}at(e){return e<0&&(e+=this.length),this.items[e]}$wireIndex(e){let n=this.deletedIndexes;if(n.length===0)return e;let r=this.tmpItems,s=0;for(let o=0;o<r.length;o++)if(n[o]!==!0){if(s===e)return o;s++}return r.length+(e-s)}$isUnsentAdd(e){let n=this[I];return(n.flags&(Uf|_u))===0&&!n.paused&&typeof this[ge]!="string"&&n.operationAt(e)===B.ADD}$cancelAdd(e,n=!0){let r=this[I],s=this.tmpItems[e];this.tmpItems.splice(e,1),this.deletedIndexes.length>0&&this.deletedIndexes.splice(e,1),r.removeAt(e,1);let o=s?.[I];o!==void 0&&o.root===void 0&&o.removeParent(this),n&&this.$reindexChildren(e)}$reindexChildren(e,n){if(!this[I].hasFilteredFields||typeof this[ge]=="string")return;let r=this.tmpItems,s=r.length;if(n!==void 0)for(;e<s&&r[e]===n[e];)e++;for(let o=e;o<s;o++)r[o]?.[I]?.setParentIndex(this,o)}$changeAt(e,n){if(n==null){console.error("ArraySchema items cannot be null nor undefined; Use `splice(index, 1)` instead.");return}if(this.items[e]===n)return;let r=this.items[e]!==void 0?typeof n=="object"?B.DELETE_AND_ADD:B.REPLACE:B.ADD,s=this.$wireIndex(e),o=this[I];return o.change(s,r),n[I]?.setParent(this,o.root,s),s}$deleteAt(e,n){this[I].delete(this.$wireIndex(e),n)}$setAt(e,n,r){r===B.ADD&&this.items[e]!==void 0?this.items.splice(e,0,n):r===B.DELETE_AND_MOVE?(this.items.splice(e,1),this.items[e]=n):(e>this.items.length&&(this._needsCompaction=!0),this.items[e]=n)}clear(){let e=this[rt];if(e.items.length===0)return;let n=e[I];n.forEachChild((r,s)=>{n.root?.remove(r)}),n.discard(),n.operation(B.CLEAR),e.items.length=0,e.tmpItems.length=0}[Mn](){let e=this[rt]??this,n=e[I];if(n.isStreamCollection)throw new Error("@colyseus/schema: cannot reset a streamed ArraySchema (pooling not supported).");let r=e.items;for(let s=0;s<r.length;s++)r[s]?.[Mn]?.();e.items.length=0,e.tmpItems.length=0,e.deletedIndexes.length=0,n.recycle(),e[Q]=void 0}concat(...e){return new en(...this.items.concat(...e))}join(e){return this.items.join(e)}reverse(){let e=this[rt],n=e[I];if(n.has()||e.deletedIndexes.length>0){let r=e.items.slice().reverse();return this.clear(),this.push(...r),this}return n.operation(B.REVERSE),e.items.reverse(),e.tmpItems.reverse(),e.$reindexChildren(0),this}shift(){let e=this[rt],n=e.items;if(n.length===0)return;let r=e[I],s=e.deletedIndexes,o=0;for(;s[o]===!0;)o++;let i=e.$isUnsentAdd(o);return r.delete(o,B.DELETE),i?e.$cancelAdd(o):s[o]=!0,n.shift()}slice(e,n){let r=new en;return r.push(...this.items.slice(e,n)),r}sort(e=Nk){let n=this[rt];n.isMovingItems=!0;let r=n[I];return n.items.sort(e).forEach((o,i)=>r.change(i,B.REPLACE)),n.tmpItems.sort(e),n.$reindexChildren(0),n.isMovingItems=!1,this}splice(e,n,...r){let s=this[rt],o=s[I],i=s.items,a=s.tmpItems,c=s.deletedIndexes,u=i.length,l=a.length,d=r.length,f=[];for(let p=0;p<l;p++)c[p]!==!0&&f.push(p);let h;if(u>e){n===void 0&&(n=u-e);for(let p=e;p<e+n;p++){let g=f[p],x=s.$isUnsentAdd(g);o.delete(g,B.DELETE),x?(h??(h=[])).push(g):c[g]=!0}}else n=0;if(d>0){let p=f[e]??u,g=Math.min(d,n);for(let b=0;b<g;b++){let S=p+b,_,P=h!==void 0?h.indexOf(S):-1;P!==-1?(h.splice(P,1),_=B.ADD):_=c[S]?B.DELETE_AND_ADD:B.ADD,o.indexedOperation(S,_),a[S]=r[b],c[S]=!1,r[b][I]?.setParent(this,o.root,S)}let x=d-g;if(x>0){let b=p+g;o.insertAt(b,x);for(let S=0;S<x;S++)r[g+S][I]?.setParent(this,o.root,b+S);c.length>0&&c.splice(b,0,...new Array(x).fill(!1)),a.splice(b,0,...r.slice(g)),s.$reindexChildren(b+x)}}if(h!==void 0&&h.length>0){for(let p=h.length-1;p>=0;p--)s.$cancelAdd(h[p],!1);s.$reindexChildren(h[0])}return o.root?.enqueueChangeTree(o),i.splice(e,n,...r)}unshift(...e){let n=this[rt],r=n[I];r.unshift(e.length);for(let o=0;o<e.length;o++)e[o]?.[I]?.setParent(this,r.root,o);let s=n.deletedIndexes;return s.length>0&&s.unshift(...new Array(e.length).fill(!1)),n.tmpItems.unshift(...e),n.$reindexChildren(e.length),n.items.unshift(...e)}indexOf(e,n){return this.items.indexOf(e,n)}lastIndexOf(e,n=this.length-1){return this.items.lastIndexOf(e,n)}every(e,n){return this.items.every(e,n)}some(e,n){return this.items.some(e,n)}forEach(e,n){return this.items.forEach(e,n)}map(e,n){return this.items.map(e,n)}filter(e,n){return this.items.filter(e,n)}reduce(e,n){return this.items.reduce.apply(this.items,arguments)}reduceRight(e,n){return this.items.reduceRight.apply(this.items,arguments)}find(e,n){return this.items.find(e,n)}findIndex(e,n){return this.items.findIndex(e,n)}fill(e,n,r){throw new Error("ArraySchema#fill() not implemented")}copyWithin(e,n,r){throw new Error("ArraySchema#copyWithin() not implemented")}toString(){return this.items.toString()}toLocaleString(){return this.items.toLocaleString()}[Symbol.iterator](){return this.items[Symbol.iterator]()}static get[Symbol.species](){return en}entries(){return this.items.entries()}keys(){return this.items.keys()}values(){return this.items.values()}includes(e,n){return this.items.includes(e,n)}flatMap(e,n){throw new Error("ArraySchema#flatMap() is not supported.")}flat(e){throw new Error("ArraySchema#flat() is not supported.")}findLast(){return this.items.findLast.apply(this.items,arguments)}findLastIndex(...e){return this.items.findLastIndex.apply(this.items,arguments)}with(e,n){let r=this.items.slice();return e<0&&(e+=this.length),r[e]=n,new en(...r)}toReversed(){return this.items.slice().reverse()}toSorted(e){return this.items.slice().sort(e)}toSpliced(e,n,...r){let s=this.items.slice();return s.splice.apply(s,arguments),s}shuffle(){return this.move(e=>{let n=this.items.length;for(;n!=0;){let r=Math.floor(Math.random()*n);n--,[this[n],this[r]]=[this[r],this[n]]}})}move(e){return this.isMovingItems=!0,e(this),this.isMovingItems=!1,this}[(Py=Symbol.unscopables,Qe)](e,n=!1){let r=this[rt]??this;return n||r.deletedIndexes[e]?r.items[e]:r.tmpItems[e]||r.items[e]}[Cn](e){let n=this[rt]??this;n.items[e]=void 0,n._needsCompaction=!0}[qr](){let e=this.tmpItems;this.tmpItems=this.items.slice(),this.deletedIndexes.length>0&&(this.$reindexChildren(0,e),this.deletedIndexes.length=0)}[Ru](){let e=this[rt]??this;e._needsCompaction&&(e._needsCompaction=!1,e.items=e.items.filter(n=>n!==void 0))}[Ho](e,n,r){let s=this[rt]??this,o=s.items,i=!1;for(let a=0;a<o.length;a++){let c=o[a];if(e.has(a)){r(c);continue}i=!0,n(c,a),s[Cn](a)}i&&s[Ru]()}toArray(){return this.items.slice(0)}toJSON(){return this.toArray().map(e=>typeof e.toJSON=="function"?e.toJSON():e)}clone(e){let n;return e?(n=new en,n.push(...this.items)):n=new en(...this.map(r=>r[I]?r.clone():r)),n}};m(en,vy,Mk),m(en,Ay,Bk),m(en,"COLLECTION_KIND",vn.Array);Wr=en;Er("array",{constructor:Wr});Tu=class{constructor(){m(this,"keyByIndex",new Map);m(this,"indexByKey",Object.create(null));m(this,"nextIndex",0);m(this,"snapshots")}indexOf(e){let n=this.indexByKey[e];return n===void 0?void 0:n}assign(e){let n=this.nextIndex++;return this.indexByKey[e]=n,this.keyByIndex.set(n,e),n}snapshot(e,n){(this.snapshots??(this.snapshots=new Map)).set(e,n)}forgetSnapshot(e){this.snapshots?.delete(e)}snapshotAt(e){return this.snapshots?.get(e)}setIndex(e,n){this.keyByIndex.set(e,n),this.indexByKey[n]=e}keyOf(e){return this.keyByIndex.get(e)}cleanupAfterEncode(){if(this.snapshots!==void 0){for(let[e]of this.snapshots){let n=this.keyByIndex.get(e);n!==void 0&&(delete this.indexByKey[n],this.keyByIndex.delete(e))}this.snapshots.clear()}}reset(){this.indexByKey=Object.create(null),this.keyByIndex.clear(),this.snapshots?.clear(),this.nextIndex=0}},Xn=class Xn{constructor(e){m(this,Ly);m(this,Ny);m(this,"childType");m(this,By);m(this,"$items",new Map);m(this,"journal",new Tu);m(this,"_stream");if(Object.defineProperty(this,I,{value:new Kr(this),enumerable:!1,writable:!0}),this[ge]=void 0,e)if(e instanceof Map||e instanceof Xn)e.forEach((n,r)=>this.set(r,n));else for(let n in e)this.set(n,e[n])}get maxPerTick(){return this._stream?.maxPerTick??32}set maxPerTick(e){(this._stream??(this._stream=Sr())).maxPerTick=e}get priority(){return this._stream?.priority}set priority(e){(this._stream??(this._stream=Sr())).priority=e}get $indexes(){return this.journal.keyByIndex}get _collectionIndexes(){return this.journal.indexByKey}static[(Ly=I,Ny=Q,By=ge,Dy=Qn,Iy=Tn,Ns)](e,n,r){if(!r||typeof e[ge]=="string")return!0;let s=e[Qe](n)??e.journal.snapshotAt(n);return r.isChangeTreeVisible(s[I])}static is(e){return e.map!==void 0}static initializeForDecoder(){let e=Object.create(Xn.prototype);return e.$items=new Map,e.journal=new Tu,e[ge]=void 0,$o(e),e}[Symbol.iterator](){return this.$items[Symbol.iterator]()}get[Symbol.toStringTag](){return this.$items[Symbol.toStringTag]}static get[Symbol.species](){return Xn}set(e,n){if(n==null)throw new Error(`MapSchema#set('${e}', ${n}): trying to set ${n} value on '${e}'.`);typeof n=="object"&&this[ge]&&Vu(n,this[ge],this,e),e=e.toString();let r=this[I],s=n[I]!==void 0,o=this.journal,i=o.indexOf(e),a;if(i!==void 0){a=B.REPLACE;let c=this.$items.get(e);if(c===n)return;s&&(a=B.DELETE_AND_ADD,c!==void 0&&c[I].root?.remove(c[I])),o.snapshotAt(i)!==void 0&&o.forgetSnapshot(i)}else i=o.assign(e),a=B.ADD;return this.$items.set(e,n),a===B.ADD&&r.isStreamCollection?r.root!==void 0&&Nu(this,r.root,i):r.change(i,a),s&&n[I].setParent(this,r.root,i),this}get(e){return this.$items.get(e)}getOrInsert(e,n){return this.$items.has(e)?this.$items.get(e):(this.set(e,n),n)}getOrInsertComputed(e,n){if(this.$items.has(e))return this.$items.get(e);let r=n(e);return this.set(e,r),r}delete(e){if(!this.$items.has(e))return!1;let n=this.journal.indexOf(e),r=this.$items.get(e),s=this[I];if(s.isStreamCollection){let o=s.root,i=!1;return o!==void 0&&(i=Lu(this,o,this[Q],n)),r?.[I]!==void 0&&o?.remove(r[I]),this.$items.delete(e),i||this.journal.snapshot(n,r),!0}return this.journal.snapshot(n,r),s.delete(n),this.$items.delete(e)}clear(){let e=this[I];e.discard(),e.forEachChild((n,r)=>{e.root?.remove(n)}),this.journal.reset(),this.$items.clear(),e.operation(B.CLEAR)}[Mn](){let e=this[I];if(e.isStreamCollection)throw new Error("@colyseus/schema: cannot reset a streamed MapSchema (pooling not supported).");this.$items.forEach(n=>n?.[Mn]?.()),this.$items.clear(),this.journal.reset(),e.recycle(),this[Q]=void 0}has(e){return this.$items.has(e)}forEach(e){this.$items.forEach(e)}entries(){return this.$items.entries()}keys(){return this.$items.keys()}values(){return this.$items.values()}get size(){return this.$items.size}pauseTracking(){this[I].pause()}resumeTracking(){this[I].resume()}untracked(e){return this[I].untracked(e)}get isTrackingPaused(){return this[I].paused}setIndex(e,n){this.journal.setIndex(e,n)}getIndex(e){return this.journal.keyOf(e)}[Qe](e){let n=this.journal.keyOf(e);return n!==void 0?this.$items.get(n):void 0}[Cn](e){let n=this.journal.keyOf(e);n!==void 0&&(this.$items.delete(n),this.journal.keyByIndex.delete(e))}[Ho](e,n,r){let s=null;if(this.$items.forEach((o,i)=>{if(e.has(i)){r(o);return}(s??(s=new Set)).add(i),n(o,i)}),s!==null){s.forEach(i=>{this.$items.delete(i),delete this.journal.indexByKey[i]});let o=[];this.journal.keyByIndex.forEach((i,a)=>{s.has(i)&&o.push(a)});for(let i=0;i<o.length;i++)this.journal.keyByIndex.delete(o[i])}}[qr](){this.journal.cleanupAfterEncode()}_dropView(e){Fu(this,e)}_unregister(){}toJSON(){return Object.fromEntries(Array.from(this,([n,r])=>[n,typeof r.toJSON=="function"?r.toJSON():r]))}clone(e){let n;return e?n=Object.assign(new Xn,this):(n=new Xn,this.forEach((r,s)=>{r[I]?n.set(s,r.clone()):n.set(s,r)})),n}};m(Xn,Dy,Tk),m(Xn,Iy,Uu),m(Xn,"COLLECTION_KIND",vn.Map);Yr=Xn;Er("map",{constructor:Yr});$r=class $r{constructor(e){m(this,Hy);m(this,Vy);m(this,Uy);m(this,"$items",new Map);m(this,"deletedItems",{});m(this,"$refId",0);m(this,"_stream");Object.defineProperty(this,I,{value:new Kr(this),enumerable:!1,writable:!0}),this[ge]=void 0,e&&e.forEach(n=>this.add(n))}get maxPerTick(){return this._stream?.maxPerTick??32}set maxPerTick(e){(this._stream??(this._stream=Sr())).maxPerTick=e}get priority(){return this._stream?.priority}set priority(e){(this._stream??(this._stream=Sr())).priority=e}static[(Hy=I,Vy=Q,Uy=ge,zy=Qn,Fy=Tn,Ns)](e,n,r){return!r||typeof e[ge]=="string"||r.isChangeTreeVisible((e[Qe](n)??e.deletedItems[n])[I])}static is(e){return e.collection!==void 0}static initializeForDecoder(){let e=Object.create($r.prototype);return e.$items=new Map,e.deletedItems={},e.$refId=0,e[ge]=void 0,$o(e),e}add(e){let n=this.$refId++,r=this[I];return this.$items.set(n,e),r.isStreamCollection?r.root!==void 0&&Nu(this,r.root,n):r.change(n),e[I]!==void 0&&e[I].setParent(this,r.root,n),n}at(e){let n=Array.from(this.$items.keys())[e];return this.$items.get(n)}entries(){return this.$items.entries()}delete(e){let n=this.$items.entries(),r,s;for(;(s=n.next())&&!s.done;)if(e===s.value[1]){r=s.value[0];break}if(r===void 0)return!1;let o=this[I];if(o.isStreamCollection){let i=o.root,a=this.$items.get(r);return i!==void 0&&Lu(this,i,this[Q],r),a?.[I]!==void 0&&i?.remove(a[I]),this.deletedItems[r]=a,this.$items.delete(r)}return this.deletedItems[r]=o.delete(r),this.$items.delete(r)}clear(){let e=this[I];e.discard(),e.forEachChild((n,r)=>{e.root?.remove(n)}),this.$items.clear(),e.operation(B.CLEAR)}[Mn](){let e=this[I];if(e.isStreamCollection)throw new Error("@colyseus/schema: cannot reset a streamed CollectionSchema (pooling not supported).");this.$items.forEach(n=>n?.[Mn]?.()),this.$items.clear(),this.deletedItems={},this.$refId=0,e.recycle(),this[Q]=void 0}has(e){return Array.from(this.$items.values()).some(n=>n===e)}forEach(e){this.$items.forEach((n,r,s)=>e(n,r,this))}values(){return this.$items.values()}get size(){return this.$items.size}pauseTracking(){this[I].pause()}resumeTracking(){this[I].resume()}untracked(e){return this[I].untracked(e)}get isTrackingPaused(){return this[I].paused}[Symbol.iterator](){return this.$items.values()}setIndex(e,n){}getIndex(e){return e}[Qe](e){return this.$items.get(e)}[Cn](e){this.$items.delete(e)}[Ho](e,n,r){let s=null;if(this.$items.forEach((o,i)=>{if(e.has(i)){r(o);return}(s??(s=[])).push(i),n(o,i)}),s!==null)for(let o=0;o<s.length;o++)this[Cn](s[o])}[qr](){for(let e in this.deletedItems)delete this.deletedItems[e]}_dropView(e){Fu(this,e)}_unregister(){}toArray(){return Array.from(this.$items.values())}toJSON(){let e=[];return this.forEach((n,r)=>{e.push(typeof n.toJSON=="function"?n.toJSON():n)}),e}clone(e){let n;return e?n=Object.assign(new $r,this):(n=new $r,this.forEach(r=>{r[I]?n.add(r.clone()):n.add(r)})),n}};m($r,zy,Vf),m($r,Fy,Uu),m($r,"COLLECTION_KIND",vn.Collection);fa=$r;Er("collection",{constructor:fa});jr=class jr{constructor(e){m(this,Wy);m(this,Gy);m(this,qy);m(this,"$items",new Map);m(this,"deletedItems",{});m(this,"$refId",0);m(this,"_stream");Object.defineProperty(this,I,{value:new Kr(this),enumerable:!1,writable:!0}),this[ge]=void 0,e&&e.forEach(n=>this.add(n))}get maxPerTick(){return this._stream?.maxPerTick??32}set maxPerTick(e){(this._stream??(this._stream=Sr())).maxPerTick=e}get priority(){return this._stream?.priority}set priority(e){(this._stream??(this._stream=Sr())).priority=e}static[(Wy=I,Gy=Q,qy=ge,jy=Qn,$y=Tn,Ns)](e,n,r){return!r||typeof e[ge]=="string"||r.isVisible((e[Qe](n)??e.deletedItems[n])[I])}static is(e){return e.set!==void 0}static initializeForDecoder(){let e=Object.create(jr.prototype);return e.$items=new Map,e.deletedItems={},e.$refId=0,e[ge]=void 0,$o(e),e}add(e){if(this.has(e))return!1;let n=this.$refId++,r=this[I];return this.$items.set(n,e),r.isStreamCollection?r.root!==void 0&&Nu(this,r.root,n):r.change(n,B.ADD),e[I]!==void 0&&e[I].setParent(this,r.root,n),n}entries(){return this.$items.entries()}delete(e){let n=this.$items.entries(),r,s;for(;(s=n.next())&&!s.done;)if(e===s.value[1]){r=s.value[0];break}if(r===void 0)return!1;let o=this[I];if(o.isStreamCollection){let i=o.root,a=this.$items.get(r);return i!==void 0&&Lu(this,i,this[Q],r),a?.[I]!==void 0&&i?.remove(a[I]),this.deletedItems[r]=a,this.$items.delete(r)}return this.deletedItems[r]=o.delete(r),this.$items.delete(r)}clear(){let e=this[I];e.discard(),this.$items.clear(),e.operation(B.CLEAR)}[Mn](){let e=this[I];if(e.isStreamCollection)throw new Error("@colyseus/schema: cannot reset a streamed SetSchema (pooling not supported).");this.$items.forEach(n=>n?.[Mn]?.()),this.$items.clear(),this.deletedItems={},this.$refId=0,e.recycle(),this[Q]=void 0}has(e){let n=this.$items.values(),r=!1,s;for(;(s=n.next())&&!s.done;)if(e===s.value){r=!0;break}return r}forEach(e){this.$items.forEach((n,r,s)=>e(n,r,this))}values(){return this.$items.values()}get size(){return this.$items.size}pauseTracking(){this[I].pause()}resumeTracking(){this[I].resume()}untracked(e){return this[I].untracked(e)}get isTrackingPaused(){return this[I].paused}[Symbol.iterator](){return this.$items.values()}setIndex(e,n){}getIndex(e){return e}[Qe](e){return this.$items.get(e)}[Cn](e){this.$items.delete(e)}[Ho](e,n,r){let s=null;if(this.$items.forEach((o,i)=>{if(e.has(i)){r(o);return}(s??(s=[])).push(i),n(o,i)}),s!==null)for(let o=0;o<s.length;o++)this[Cn](s[o])}[qr](){for(let e in this.deletedItems)delete this.deletedItems[e]}_dropView(e){Fu(this,e)}_unregister(){}toArray(){return Array.from(this.$items.values())}toJSON(){let e=[];return this.forEach((n,r)=>{e.push(typeof n.toJSON=="function"?n.toJSON():n)}),e}clone(e){let n;return e?n=Object.assign(new jr,this):(n=new jr,this.forEach(r=>{r[I]?n.add(r.clone()):n.add(r)})),n}};m(jr,jy,Vf),m(jr,$y,Uu),m(jr,"COLLECTION_KIND",vn.Set);pa=jr;Er("set",{constructor:pa});wr=class wr{constructor(){m(this,Zy);m(this,Jy);m(this,Xy);m(this,"$items",new Map);m(this,"$nextPosition",0);m(this,"_itemIndex",new Map);m(this,"_stream");Object.defineProperty(this,I,{value:new Kr(this),enumerable:!1,writable:!0}),this[ge]=void 0}get maxPerTick(){return this._stream?.maxPerTick??32}set maxPerTick(e){(this._stream??(this._stream=Sr())).maxPerTick=e}get priority(){return this._stream?.priority}set priority(e){(this._stream??(this._stream=Sr())).priority=e}static[(Zy=I,Jy=Q,Xy=ge,Ky=Qn,Yy=Tn,Ns)](e,n,r){if(!r)return!0;let s=e[Qe](n);return s===void 0?!1:r.isVisible(s[I])}static is(e){return e&&e.stream!==void 0}static initializeForDecoder(){let e=Object.create(wr.prototype);return e.$items=new Map,e.$nextPosition=0,e._itemIndex=new Map,e[ge]=void 0,$o(e),e}add(e){if(this._itemIndex.has(e))return-1;let n=this.$nextPosition++;this.$items.set(n,e),this._itemIndex.set(e,n);let s=this[I].root;return e[I]!==void 0&&e[I].setParent(this,s,n),s!==void 0&&Nu(this,s,n),n}remove(e){let n=this._itemIndex.get(e);if(n===void 0)return!1;this._itemIndex.delete(e),this.$items.delete(n);let r=this[I].root;return r!==void 0&&(Lu(this,r,this[Q],n),e[I]!==void 0&&r.remove(e[I])),!0}has(e){return this._itemIndex.has(e)}clear(){let e=this[I].root;if(e!==void 0){YR(this,e,this[Q]);for(let n of this.$items.values())n[I]!==void 0&&e.remove(n[I])}this.$items.clear(),this._itemIndex.clear()}forEach(e){for(let[n,r]of this.$items)e(r,n,this)}values(){return this.$items.values()}entries(){return this.$items.entries()}[Symbol.iterator](){return this.$items.values()}get size(){return this.$items.size}get length(){return this.$items.size}setIndex(e,n){}getIndex(e){return e}[Qe](e){return this.$items.get(e)}[Cn](e){let n=this.$items.get(e);n!==void 0&&(this._itemIndex.delete(n),this.$items.delete(e))}[Ho](){}[qr](){}toArray(){return Array.from(this.$items.values())}toJSON(){let e=[];return this.forEach(n=>{e.push(typeof n?.toJSON=="function"?n.toJSON():n)}),e}clone(e){if(e)return Object.assign(new wr,this);let n=new wr;return n.maxPerTick=this.maxPerTick,this.forEach(r=>{n.add(typeof r?.clone=="function"?r.clone():r)}),n}_dropView(e){Fu(this,e)}_unregister(){}};m(wr,"$isStream",!0),m(wr,Ky,Vf),m(wr,Yy,Uu),m(wr,"COLLECTION_KIND",vn.Stream);Mu=wr;Er("stream",{constructor:Mu});Qy=og;er=class{constructor(e){m(this,Qy,!0);m(this,"_type");m(this,"_default");m(this,"_hasDefault",!1);m(this,"_view");m(this,"_unreliable",!1);m(this,"_patchOnly",!1);m(this,"_deprecated",!1);m(this,"_deprecatedThrows",!0);m(this,"_fullStateOnly",!1);m(this,"_stream",!1);m(this,"_optional",!1);m(this,"_noSync",!1);m(this,"_streamPriority");this._type=e}default(e){return this._default=e,this._hasDefault=!0,this}view(e){return this._view=e??-1,this}unreliable(){return this._unreliable=!0,this}patchOnly(){return this._patchOnly=!0,this}fullStateOnly(){return this._fullStateOnly=!0,this}noSync(){return this._noSync=!0,this}stream(){let e=this._type;if(e&&typeof e=="object"&&e.array!==void 0)throw new Error(_g);return this._stream=!0,this}priority(e){return this._streamPriority=e,this}deprecated(e=!0){return this._deprecated=!0,this._deprecatedThrows=e,this}optional(){return this._optional=!0,this}toDefinition(){return{type:this._type,default:this._default,hasDefault:this._hasDefault,view:this._view,unreliable:this._unreliable,patchOnly:this._patchOnly,deprecated:this._deprecated,deprecatedThrows:this._deprecatedThrows,fullStateOnly:this._fullStateOnly,stream:this._stream,optional:this._optional,noSync:this._noSync,streamPriority:this._streamPriority}}};Lk=(t=>new er({array:ba(t)})),Fk=(t=>new er({map:ba(t)})),zk=(t=>new er({set:ba(t)})),Uk=(t=>new er({collection:ba(t)})),Vk=(t=>{let e=new er({stream:ba(t)});return e._stream=!0,e}),Hk=(t=>new er(t));q=Object.freeze({string:Ot("string"),number:Ot("number"),boolean:Ot("boolean"),int8:Ot("int8"),uint8:Ot("uint8"),int16:Ot("int16"),uint16:Ot("uint16"),int32:Ot("int32"),uint32:Ot("uint32"),int64:Ot("int64"),uint64:Ot("uint64"),float32:Ot("float32"),float64:Ot("float64"),bigint64:Ot("bigint64"),biguint64:Ot("biguint64"),ref:Hk,array:Lk,map:Fk,set:zk,collection:Uk,stream:Vk,quantized:Ey,angle:t=>Ey({min:0,max:Math.PI*2,mode:"wrap",bits:t?.bits??16})}),Hu=-1;Gk={number:"number",int8:"number",uint8:"number",int16:"number",uint16:"number",int32:"number",uint32:"number",int64:"number",uint64:"number",float32:"number",float64:"number",bigint64:"bigint",biguint64:"bigint",string:"string",boolean:"boolean"};Pn=class Pn{constructor(e){m(this,tg);m(this,eg);Pn.initialize(this),e&&Pn.assignProps(this,e)}static initialize(e){Object.defineProperty(e,I,{value:new Kr(e),enumerable:!1,writable:!0}),e[kt]=[]}static initializeForDecoder(){let e=Object.create(this.prototype);return $o(e),e[kt]=[],e}static reset(e){let n=e?.[I];if(n===void 0||typeof n.recycle!="function")throw new Error("@colyseus/schema: Schema.reset() requires a tracked (encoder-side) instance.");if(n.extraParents!==void 0)throw new Error(`@colyseus/schema: cannot reset a shared instance (${e.constructor.name}) with multiple parents.`);e[Mn]()}[(rg=Qn,ng=Tn,tg=Q,eg=kt,Mn)](){let n=this.constructor[Symbol.metadata]?.[Gr]??[],r=this[kt];for(let s=0;s<n.length;s++)r[n[s]]?.[Mn]?.();this[I].recycle(),this[Q]=void 0}static is(e){let n=e[Symbol.metadata];return typeof n=="object"&&n!==null}static isSchema(e){return typeof e?.assign=="function"}static[Zn](e,n,r=B.ADD){e.change(n,r)}static[Ns](e,n,r){let o=e.constructor[Symbol.metadata][n]?.tag;return r===void 0?o===void 0:o===void 0?!0:o===Hu?r.isChangeTreeVisible(e[I]):r.hasTagOnTree(e[I],o)}assign(e){return Pn.assignProps(this,e),this}static assignProps(e,n){let r=e.constructor[Symbol.metadata];if(r&&r[bt]!==void 0)for(let o=0;o<=r[bt];o++){let i=r[o];if(!i)continue;let a=n[i.name];a!==void 0&&(e[i.name]=a)}let s=Object.keys(n);for(let o=0;o<s.length;o++){let i=s[o];r&&r[i]!==void 0||(e[i]=n[i])}}restore(e){let n=this.constructor[Symbol.metadata];for(let r in n){let s=n[r],o=s.name,i=s.type,a=e[o];if(a!=null){if(typeof i=="string")this[o]=a;else if(Pn.is(i)){let c=new i;c.restore(a),this[o]=c}else if(typeof i=="object"){let c=Object.keys(i)[0],u=i[c];if(c==="map"){let l=this[o];for(let d in a)if(Pn.is(u)){let f=new u;f.restore(a[d]),l.set(d,f)}else l.set(d,a[d])}else if(c==="array"){let l=this[o];for(let d=0;d<a.length;d++)if(Pn.is(u)){let f=new u;f.restore(a[d]),l.push(f)}else l.push(a[d])}}}}return this}setDirty(e,n){let r=this.constructor[Symbol.metadata];this[I].change(r[r[e]].index,n)}pauseTracking(){this[I].pause()}resumeTracking(){this[I].resume()}untracked(e){return this[I].untracked(e)}get isTrackingPaused(){return this[I].paused}clone(){let e=Object.create(this.constructor.prototype);Pn.initialize(e);let n=this.constructor[Symbol.metadata];for(let r in n){let s=n[r].name;typeof this[s]=="object"&&typeof this[s]?.clone=="function"?e[s]=this[s].clone():e[s]=this[s]}return e}toJSON(){let e={},n=this.constructor[Symbol.metadata];for(let r in n){let s=n[r],o=s.name;!s.deprecated&&this[o]!==null&&typeof this[o]<"u"&&(e[o]=typeof this[o].toJSON=="function"?this[o].toJSON():this[o])}return e}discardAllChanges(){this[I].discardAll()}[Qe](e){let n=this.constructor[Symbol.metadata];return this[n[e].name]}[Cn](e){let n=this.constructor[Symbol.metadata];this[n[e].name]=void 0}static debugRefIds(e,n=!1,r=0,s,o=""){let i=n?` - ${JSON.stringify(e.toJSON())}`:"",a=e[I],c=e[Q],u=s?s.root:a.root,l=u?.refCount?.[c]>1?` [\xD7${u.refCount[c]}]`:"",d=`${eP(r)}${o}${e.constructor.name} (refId: ${c})${l}${i}
5
+ `;return a.forEachChild((f,h)=>{let p=h;typeof h=="number"&&e.$indexes&&(p=e.$indexes.get(h)??h);let g=e.forEach!==void 0&&p!==void 0?`["${p}"]: `:"";d+=this.debugRefIds(f.ref,n,r+1,s,g)}),d}static debugRefIdEncodingOrder(e,n="allChanges"){let r=[],s=e[I];if(n==="changes"){let c=s.root.changes?.next;for(;c;)c.changeTree&&r.push(c.changeTree.ref[Q]),c=c.next;return r}let o=n==="allFilteredChanges",i=new Set,a=c=>{i.has(c)||(i.add(c),c.isFiltered===o&&r.push(c.ref[Q]),c.forEachChild((u,l)=>a(u)))};return a(s),r}static debugRefIdsFromDecoder(e){return this.debugRefIds(e.state,!1,0,e)}static debugChanges(e,n=!1){let r=e[I],s=n?"allChanges":"changes",o=`${e.constructor.name} (${e[Q]}) -> .${s}:
6
+ `;return n?r.forEachLive(i=>{o+=`- [${i}]: ADD (${JSON.stringify(r.getValue(Number(i),!0))})
7
+ `}):r.forEach((i,a)=>{i<0||!a||(o+=`- [${i}]: ${B[a]} (${JSON.stringify(r.getValue(Number(i),!1))})
8
+ `)}),o}};m(Pn,rg,vk),m(Pn,ng,Dk);Ye=Pn;sg(Ye);_y={value:0,enumerable:!1,writable:!0},Cf=class{constructor(e,n=0){m(this,"types");m(this,"nextUniqueId",0);m(this,"refCount",{});m(this,"changeTrees",{});m(this,"changes",xy());m(this,"unreliableChanges",xy());m(this,"pendingFilterRefresh",[]);m(this,"_nodePool",[]);m(this,"_nextViewId",0);m(this,"_freeViewIds",[]);m(this,"activeViews",new Map);m(this,"streamTrees",new Set);this.types=e,this.nextUniqueId=n}enqueueFilterRefresh(e){this.types.hasFilters&&(e.flags&la||(e.flags|=la,this.pendingFilterRefresh.push(e)))}acquireViewId(){return this._freeViewIds.length>0?this._freeViewIds.pop():this._nextViewId++}releaseViewId(e){this._freeViewIds.push(e)}registerView(e){this.activeViews.set(e.id,new WeakRef(e))}unregisterView(e){this.activeViews.delete(e.id);let n=e.id;for(let r of this.streamTrees)r._dropView(n)}forEachActiveView(e){for(let[n,r]of this.activeViews){let s=r.deref();if(s===void 0){this.activeViews.delete(n);for(let o of this.streamTrees)o._dropView(n);continue}e(s)}}registerStream(e){this.streamTrees.add(e)}unregisterStream(e){this.streamTrees.delete(e)}add(e){let n=e.ref;n[Q]===void 0&&(_y.value=this.nextUniqueId++,Object.defineProperty(n,Q,_y));let r=n[Q],s=this.changeTrees[r]===void 0;s&&(this.changeTrees[r]=e);let o=this.refCount[r];return(o===0||e.needsRestage)&&(e.needsRestage=!1,e.forEachLiveWithCtx(e,vg)),this.refCount[r]=(o||0)+1,o>0&&this.enqueueFilterRefresh(e),s}remove(e){let n=e.ref[Q],r=this.refCount[n]-1;if(r<=0){if(e.root=void 0,delete this.changeTrees[n],e.isStreamCollection){let s=e.ref;s._unregister?.(),this.unregisterStream(s)}this.removeFromQueue(e),this.removeFromUnreliableQueue(e),this.refCount[n]=0,e.forEachChild((s,o)=>{s.removeParent(e.ref)&&(s.parentRef===void 0||s.parentRef&&this.refCount[s.ref[Q]]>0?this.remove(s):s.parentRef&&this.moveNextToParent(s))})}else this.refCount[n]=r,this.enqueueFilterRefresh(e),this.recursivelyMoveNextToParent(e);return r}recursivelyMoveNextToParent(e){this.moveNextToParent(e),e.forEachChild((n,r)=>this.recursivelyMoveNextToParent(n))}moveNextToParent(e){e.changesNode&&this._moveNextToParentInList(this.changes,e,e.changesNode,"changesNode"),e.unreliableChangesNode&&this._moveNextToParentInList(this.unreliableChanges,e,e.unreliableChangesNode,"unreliableChangesNode")}_moveNextToParentInList(e,n,r,s){let o=n.parent;if(!o||!o[I])return;let i=o[I][s];!i||i===r||r.position>i.position||(r.prev?r.prev.next=r.next:e.next=r.next,r.next?r.next.prev=r.prev:e.tail=r.prev,r.prev=e.tail,r.next=void 0,e.tail.next=r,e.tail=r,r.position=e.nextPosition++)}enqueueChangeTree(e,n=e.changesNode){n||(e.changesNode=this._appendToList(this.changes,e))}enqueueUnreliable(e,n=e.unreliableChangesNode){n||(e.unreliableChangesNode=this._appendToList(this.unreliableChanges,e))}_appendToList(e,n){let r=this._nodePool,s;return r.length>0?(s=r.pop(),s.changeTree=n,s.next=void 0,s.prev=void 0):s={changeTree:n,next:void 0,prev:void 0,position:0},e.next?(s.prev=e.tail,e.tail.next=s,e.tail=s):(e.nextPosition=0,e.next=s,e.tail=s),s.position=e.nextPosition++,s}releaseNode(e){e.changeTree=void 0,e.prev=void 0,e.next=void 0,this._nodePool.push(e)}removeFromQueue(e){return this._removeNode(this.changes,e,e.changesNode,"changesNode")}removeFromUnreliableQueue(e){return this._removeNode(this.unreliableChanges,e,e.unreliableChangesNode,"unreliableChangesNode")}_removeNode(e,n,r,s){return!r||r.changeTree!==n?!1:(r.prev?r.prev.next=r.next:e.next=r.next,r.next?r.next.prev=r.prev:e.tail=r.prev,n[s]=void 0,this.releaseNode(r),!0)}};FD=new FinalizationRegistry(({root:t,id:e,slot:n,bit:r})=>{nP(t,n,r),t.activeViews.delete(e);for(let s of t.streamTrees)s._dropView(e);t.releaseViewId(e)}),rP=-1;Jn=class Jn{constructor(e,n){m(this,"sharedBuffer",new Uint8Array(Jn.BUFFER_SIZE));m(this,"context");m(this,"state");m(this,"root");m(this,"_encodeCtx",{self:void 0,buffer:void 0,it:void 0,changeTree:void 0,ref:void 0,encoder:void 0,filter:void 0,metadata:void 0,view:void 0,isEncodeAll:!1,hasView:!1,treeIsFiltered:!1,isSchema:!1,emitFiltered:!1,filterBitmask:0,tags:void 0,structSwitchEmitted:!1,isRootTree:!1,shouldEmitSwitch:!1,gen:0,initialOffset:0,rootChangeTree:void 0});m(this,"_fullSyncGen",0);this.context=Bs.cache(e.constructor),this.root=n??new Cf(this.context),this.setState(e)}setState(e){this.state=e,this.state[I].setRoot(this.root)}encode(e={offset:0},n,r=this.sharedBuffer,s=e.offset){return this._encodeChannel(e,n,r,s,!1)}encodeUnreliable(e={offset:0},n,r=this.sharedBuffer,s=e.offset){return this._encodeChannel(e,n,r,s,!0)}_encodeChannel(e,n,r,s,o){this.root.pendingFilterRefresh.length>0&&gy(this.root);let i=n!==void 0,a=this.state[I],c=this._encodeCtx;c.self=this,c.buffer=r,c.it=e,c.view=n,c.isEncodeAll=!1,c.hasView=i,c.emitFiltered=i;let l=o?this.root.unreliableChanges:this.root.changes;for(;l=l.next;){let d=l.changeTree;if(i&&!n.isChangeTreeVisible(d))continue;let f=o?d.unreliableRecorder:d;if(!f||!f.has())continue;let h=d.encDescriptor;c.changeTree=d,c.ref=d.ref,c.encoder=h.encoder,c.filter=h.filter,c.metadata=h.metadata,c.treeIsFiltered=d.isFiltered,c.isSchema=h.isSchema,c.filterBitmask=h.filterBitmask,c.tags=h.tags,c.structSwitchEmitted=!1,c.isRootTree=d===a,c.shouldEmitSwitch=i||e.offset>s||!c.isRootTree,f.forEachWithCtx(c,Ng)}return!o&&!i&&this._isStreamBroadcastMode&&this._emitStreamBroadcast(r,e),e.offset>r.byteLength?(r=this._resizeBuffer(r,e.offset),e.offset=s,this._encodeChannel(e,n,r,s,o)):r.subarray(0,e.offset)}encodeFullSync(e,n,r,s,o=e.offset){this.root.pendingFilterRefresh.length>0&&gy(this.root);let i=s!==void 0,a=this.state[I],c=this._encodeCtx;return c.self=this,c.buffer=n,c.it=e,c.view=s,c.isEncodeAll=!0,c.hasView=i,c.emitFiltered=r,c.gen=++this._fullSyncGen,c.initialOffset=o,c.rootChangeTree=a,Bg(c,a),e.offset>n.byteLength?(n=this._resizeBuffer(n,e.offset),e.offset=o,this.encodeFullSync(e,n,r,s,o)):n.subarray(0,e.offset)}_resizeBuffer(e,n){let r=Math.ceil(n/Jn.BUFFER_SIZE)*Jn.BUFFER_SIZE;console.warn(`@colyseus/schema buffer overflow. Encoded state is higher than default BUFFER_SIZE. Use the following to increase default BUFFER_SIZE:
9
+
10
+ import { Encoder } from "@colyseus/schema";
11
+ Encoder.BUFFER_SIZE = ${Math.round(r/1024)} * 1024; // ${Math.round(r/1024)} KB
12
+ `);let s=new Uint8Array(r);return s.set(e),e===this.sharedBuffer&&(this.sharedBuffer=s),s}encodeAll(e={offset:0},n=this.sharedBuffer){return this.encodeFullSync(e,n,!1)}encodeAllView(e,n,r,s=this.sharedBuffer){let o=r.offset;return s=this.encodeFullSync(r,s,!0,e,o),kf(s.subarray(0,n),s.subarray(o,r.offset))}ensureCapacity(e,n){if(n+Jn.BUFFER_SIZE<=e.byteLength)return e;let r=Math.ceil((n+Jn.BUFFER_SIZE)/Jn.BUFFER_SIZE)*Jn.BUFFER_SIZE,s=new Uint8Array(r);return s.set(e.subarray(0,n)),e===this.sharedBuffer&&(this.sharedBuffer=s),s}encodeView(e,n,r,s=this.sharedBuffer){let o=r.offset;this._emitStreamPriority(e);for(let i of e.changes.keys()){let a=e.changes.get(i),c=this.root.changeTrees[i];if(c===void 0){e.changes.delete(i);continue}if(a.size===0)continue;let u=c.encDescriptor,l=u.encoder,d=u.metadata,f=c.ref,h=c.refTarget;s=this.ensureCapacity(s,r.offset),s[r.offset++]=255,be.number(s,f[Q],r);for(let[p,g]of a){let x;if(p===rP){let _=h.tmpItems,P=h.deletedIndexes;for(let R=0;R<_.length;R++)_[R]===void 0||P[R]===!0||l(this,s,c,R,B.ADD,r,!1,!0,d);continue}if(typeof p=="number")x=p;else{let _=p.indexInParent(f);if(_===void 0)continue;if(x=_,g===B.ADD&&c.getChange(x)===B.DELETE){e.changes.delete(p.ref[Q]);continue}}let S=h[Qe](x)!==void 0&&g||B.DELETE;l(this,s,c,x,S,r,!1,!0,d)}}return e.changes.clear(),s=this.encode(r,e,s),kf(s.subarray(0,n),s.subarray(o,r.offset))}encodeUnreliableView(e,n,r,s=this.sharedBuffer){let o=r.offset;return s=this.encodeUnreliable(r,e,s,o),kf(s.subarray(0,n),s.subarray(o,r.offset))}_emitStreamBroadcast(e,n){let r=this.root.streamTrees;for(let s of r){let o=s,i=o[I],a=o[Q];if(a===void 0)continue;let c=o._stream,u=c.broadcastDeletes,l=c.broadcastPending,d=c.sentBroadcast,f=u.size>0,h=l.size>0,p=i.encDescriptor,g=p.encoder,x=p.metadata;if(f||h){if(e[n.offset++]=255,be.number(e,a,n),f){for(let R of u)g(this,e,i,R,B.DELETE,n,!1,!1,x);u.clear()}let b=c.maxPerTick,S=[],_=0,P=[];for(let R of l){if(_>=b)break;let v=o[Qe](R);if(v===void 0){P.push(R);continue}g(this,e,i,R,B.ADD,n,!1,!1,x),d.add(R),S.push(v),P.push(R),_++}for(let R of P)l.delete(R);for(let R of S){let v=R[I];if(v===void 0)continue;let M=R[Q];if(M===void 0)continue;e[n.offset++]=255,be.number(e,M,n);let O=v.encDescriptor,z=O.encoder,X=O.metadata;v.forEachLive(N=>{Ie.hasUnreliableAtIndex(X,N)||z(this,e,v,N,B.ADD,n,!1,!1,X)})}}for(let b of d){let S=o[Qe](b);if(S===void 0)continue;let _=S[I];if(_===void 0||!_.has())continue;let P=S[Q];if(P===void 0)continue;e[n.offset++]=255,be.number(e,P,n);let R=_.encDescriptor,v=R.encoder,M=R.metadata;_.forEach((O,z)=>{O<0||Ie.hasUnreliableAtIndex(M,O)||v(this,e,_,O,z,n,!1,!1,M)})}}}_emitStreamPriority(e){let n=this.root.streamTrees;if(n.size===0)return;let r=e.id;for(let s of n){let o=s,i=o._stream,a=i.pendingByView.get(r);if(a===void 0||a.size===0)continue;let c=i.priorityByView?.get(r),u=c!==void 0,l=i.priority,d=i.maxPerTick,f=[],h=[];if(u||l!==void 0){let x=[],b=[],S=0;for(let _ of a){let P=o[Qe](_);if(P===void 0){h.push(_);continue}let R=u?c(P):l(e,P);if(S<d){let v=S++;for(;v>0&&b[v-1]<R;)b[v]=b[v-1],x[v]=x[v-1],v--;b[v]=R,x[v]=_}else if(R>b[d-1]){let v=d-1;for(;v>0&&b[v-1]<R;)b[v]=b[v-1],x[v]=x[v-1],v--;b[v]=R,x[v]=_}}for(let _=0;_<S;_++)f.push(x[_])}else for(let x of a){if(f.length>=d)break;f.push(x)}for(let x of h)a.delete(x);let p=f.length,g=i.sentByView.get(r);g===void 0&&(g=new Set,i.sentByView.set(r,g));for(let x=0;x<p;x++){let b=f[x],S=o[Qe](b);if(S===void 0){a.delete(b);continue}e._addImmediate(S);let _=S[I];if(_!==void 0){let P=S[Q],R=e.changes.get(P);R===void 0&&(R=new Map,e.changes.set(P,R));let v=_.metadata;_.forEachLive(M=>{Ie.hasUnreliableAtIndex(v,M)||R.set(M,B.ADD)})}a.delete(b),g.add(b)}}}discardChanges(){let e=this.root.changes,n=e.next,r=this.root;for(;n;){let s=n.next;n.changeTree.endEncode(),r.releaseNode(n),n=s}e.next=void 0,e.tail=void 0}discardUnreliableChanges(){let e=this.root.unreliableChanges,n=e.next,r=this.root;for(;n;){let s=n.next;n.changeTree.endEncodeUnreliable(),r.releaseNode(n),n=s}e.next=void 0,e.tail=void 0}tryEncodeTypeId(e,n,r,s){let o=this.context.getTypeId(n),i=this.context.getTypeId(r);if(i===void 0){console.warn(`@colyseus/schema WARNING: Class "${r.name}" is not registered on TypeRegistry - Please either tag the class with @entity or define a @type() field.`);return}o!==i&&(e[s.offset++]=213,be.number(e,i,s))}get hasChanges(){return this.root.changes.next!==void 0||this._hasStreamBacklog()}get _isStreamBroadcastMode(){return this.root.activeViews.size===0&&this.root.streamTrees.size>0}_hasStreamBacklog(){let e=this.root;if(e.streamTrees.size===0)return!1;let n=e.activeViews.size===0;for(let r of e.streamTrees)if(n?XR(r):KR(r,e))return!0;return!1}get hasUnreliableChanges(){return this.root.unreliableChanges.next!==void 0}};m(Jn,"BUFFER_SIZE",16*1024);ha=Jn,Cu=class extends Error{constructor(e){super(e),this.name="DecodingWarning"}},ky={value:0,enumerable:!1,writable:!0},Of=class{constructor(){m(this,"refs",new Map);m(this,"refCount",{});m(this,"deletedRefs",new Set);m(this,"callbacks",{});m(this,"nextUniqueId",0)}getNextUniqueId(){return this.nextUniqueId++}addRef(e,n,r=!0){this.refs.set(e,n),n[Q]===void 0?(ky.value=e,Object.defineProperty(n,Q,ky)):n[Q]!==e&&(n[Q]=e),r&&(this.refCount[e]=(this.refCount[e]||0)+1),this.deletedRefs.has(e)&&this.deletedRefs.delete(e)}removeRef(e){let n=this.refCount[e];if(n===void 0){try{throw new Cu("trying to remove refId that doesn't exist: "+e)}catch(r){console.warn(r)}return}if(n===0){try{let r=this.refs.get(e);throw new Cu(`trying to remove refId '${e}' with 0 refCount (${r.constructor.name}: ${JSON.stringify(r)})`)}catch(r){console.warn(r)}return}(this.refCount[e]=n-1)<=0&&this.deletedRefs.add(e)}clearRefs(){this.refs.clear(),this.deletedRefs.clear(),this.callbacks={},this.refCount={}}garbageCollectDeletedRefs(){this.deletedRefs.forEach(e=>{if(this.refCount[e]>0)return;let n=this.refs.get(e),r=n.constructor[Symbol.metadata];if(r!=null)for(let s in r){let o=r[s].name,i=n[o];if(typeof i=="object"&&i){let a=i[Q];a!==void 0&&!this.deletedRefs.has(a)&&this.removeRef(a)}}else typeof n[ge]=="function"&&Array.from(n.values()).forEach(s=>{let o=s[Q];o!==void 0&&!this.deletedRefs.has(o)&&this.removeRef(o)});this.refs.delete(e),delete this.refCount[e],delete this.callbacks[e]}),this.deletedRefs.clear()}addCallback(e,n,r){if(e===void 0){let s=typeof n=="number"?B[n]:n;throw new Error(`Can't addCallback on '${s}' (refId is undefined)`)}return this.callbacks[e]||(this.callbacks[e]={}),this.callbacks[e][n]||(this.callbacks[e][n]=[]),this.callbacks[e][n].push(r),()=>this.removeCallback(e,n,r)}removeCallback(e,n,r){let s=this.callbacks?.[e]?.[n]?.indexOf(r);s!==void 0&&s!==-1&&tP(this.callbacks[e][n],s)}},In=class{constructor(e,n){m(this,"context");m(this,"state");m(this,"root");m(this,"currentRefId",0);m(this,"triggerChanges");m(this,"resyncVisited",null);m(this,"resyncDamaged",!1);this.setState(e),this.context=n||new Bs(e.constructor)}setState(e){this.state=e,this.root=new Of,this.root.addRef(0,e)}decode(e,n={offset:0},r=this.state){let s=this.triggerChanges!==void 0?[]:null,o=this.root,i=e.byteLength,a=r.constructor[Tn];for(this.currentRefId=0;n.offset<i;){if(e[n.offset]==255){n.offset++,r[Ru]?.();let u=Re.number(e,n),l=o.refs.get(u);l?(r=l,a=r.constructor[Tn],this.currentRefId=u):(console.error(`"refId" not found: ${u}`,{previousRef:r,previousRefId:this.currentRefId}),console.warn("Please report this issue to the developers."),this.skipCurrentStructure(e,n,i));continue}if(a(this,e,n,r,s)===Ig){console.warn("@colyseus/schema: definition mismatch"),this.skipCurrentStructure(e,n,i);continue}}return r[Ru]?.(),this.resyncVisited!==null&&Ok(this,s),s!==null&&this.triggerChanges?.(s),o.garbageCollectDeletedRefs(),s}decodeResync(e,n={offset:0}){this.resyncVisited=new Map,this.resyncDamaged=!1;try{return this.decode(e,n)}finally{this.resyncVisited=null}}skipCurrentStructure(e,n,r){this.resyncVisited!==null&&(this.resyncDamaged=!0);let s={offset:n.offset};for(;n.offset<r&&!(e[n.offset]===255&&(s.offset=n.offset+1,this.root.refs.has(Re.number(e,s))));)n.offset++}getInstanceType(e,n,r){let s;if(e[n.offset]===213){n.offset++;let o=Re.number(e,n);s=this.context.get(o)}return s||r}createInstanceOfType(e){return e.initializeForDecoder()}removeChildRefs(e,n){let r=typeof e[ge]!="string",s=e[Q];e.forEach((o,i)=>{n?.push({ref:e,refId:s,op:B.DELETE,field:i,value:void 0,previousValue:o}),r&&this.root.removeRef(o[Q])})}},Lg=It({min:q.float64(),max:q.float64(),bits:q.uint8(),mode:q.uint8()},"QuantizedDescriptor"),Fg=It({name:q.string(),type:q.string(),referencedType:q.number(),childPrimitive:q.string(),quantized:q.ref(Lg).optional()},"ReflectionField"),zg=It({id:q.number(),extendsId:q.number(),fields:q.array(Fg)},"ReflectionType"),Dn=It({types:q.array(zg),rootType:q.number()},"Reflection");Dn.encode=function(t,e={offset:0}){let n=t.context,r=new Dn,s=new ha(r),o=n.schemas.get(t.state.constructor);o>0&&(r.rootType=o);let i=new Set,a={},c=l=>{if(l.extendsId===void 0||i.has(l.extendsId)){i.add(l.id),r.types.push(l);let d=a[l.id];d!==void 0&&(delete a[l.id],d.forEach(f=>c(f)))}else a[l.extendsId]===void 0&&(a[l.extendsId]=[]),a[l.extendsId].push(l)};n.schemas.forEach((l,d)=>{let f=new zg;f.id=Number(l);let h=Object.getPrototypeOf(d);h!==Ye&&(f.extendsId=n.schemas.get(h));let p=d[Symbol.metadata];if(p!==h[Symbol.metadata]){let g=p[bt]??-1;for(let x=0;x<=g;x++){let b=p[x];if(b===void 0)continue;let S=b.name;if(!Object.prototype.hasOwnProperty.call(p,S))continue;let _=new Fg;_.name=S;let P;if(typeof b.type=="string")P=b.type;else if(Ds(b.type)){let R=b.type.quantized;P="quantized";let v=new Lg;v.min=R.min,v.max=R.max,v.bits=R.bits,v.mode=R.wrap?1:0,_.quantized=v}else{let R;Ye.is(b.type)?(P="ref",R=b.type):(P=Object.keys(b.type)[0],typeof b.type[P]=="string"?_.childPrimitive=b.type[P]:R=b.type[P]),_.referencedType=R?n.getTypeId(R):-1}_.type=P,f.fields.push(_)}}c(f)});for(let l in a)a[l].forEach(d=>r.types.push(d));return s.encodeAll(e).slice(0,e.offset)};Dn.decode=function(t,e){let n=new Dn;new In(n).decode(t,e);let s=new Bs;n.types.forEach(a=>{let c=s.get(a.extendsId)??Ye,u=class extends c{};Bs.register(u),s.add(u,a.id)},{});let o=(a,c,u)=>{c.fields.forEach((l,d)=>{let f=u+d;if(l.quantized!==void 0){let h=l.quantized;Ie.addField(a,f,l.name,{quantized:Nf({min:h.min,max:h.max,bits:h.bits,mode:h.mode===1?"wrap":"clamp"})})}else if(l.referencedType!==void 0){let h=l.type,p=s.get(l.referencedType)??l.childPrimitive;h==="ref"?Ie.addField(a,f,l.name,p):Ie.addField(a,f,l.name,{[h]:p})}else Ie.addField(a,f,l.name,l.type)})};n.types.forEach(a=>{let c=s.get(a.id),u=Ie.initialize(c),l=[],d=a;do l.push(d),d=n.types.find(h=>h.id===d.extendsId);while(d);let f=0;l.reverse().forEach(h=>{o(u,h,f),f+=h.fields.length})});let i=new(s.get(n.rootType||0));return new In(i,s)};Dn.makeEncodable=function(t){let e=t[Symbol.metadata];if(!e)return t;let n=e[bt];if(n===void 0)return t;for(let r=0;r<=n;r++){let s=e[r];s&&Ie.defineField(t,e,r,s.name,s.type)}return Object.prototype.hasOwnProperty.call(t,aa)&&delete t[aa],t};Iu=class{constructor(e){m(this,"decoder");m(this,"uniqueRefIds",new Set);m(this,"isTriggering",!1);this.decoder=e,this.decoder.triggerChanges=this.triggerChanges.bind(this)}get callbacks(){return this.decoder.root.callbacks}get state(){return this.decoder.state}addCallback(e,n,r){return this.decoder.root.addCallback(e,n,r)}addCallbackOrWaitCollectionAvailable(e,n,r,s,o=!0){let i=()=>{},a=()=>i(),c=e[n];if(!c||c[Q]===void 0){let u;return u=this.addCallback(e[Q],n,(l,d)=>{l!=null&&(u(),i=this.addCallback(l[Q],r,s))}),i=u,a}else return o=o&&this.isTriggering===!1,r===B.ADD&&o&&c.forEach((u,l)=>{s(u,l)}),this.addCallback(c[Q],r,s)}listen(...e){return typeof e[0]=="string"?this.listenInstance(this.state,e[0],e[1],e[2]):this.listenInstance(e[0],e[1],e[2],e[3])}listenInstance(e,n,r,s=!0){s=s&&this.isTriggering===!1;let o=e[n];return s&&o!==null&&o!==void 0&&r(o,void 0),this.addCallback(e[Q],n,r)}onChange(...e){if(e.length===2&&typeof e[0]!="string"){let n=e[0],r=e[1];return this.addCallback(n[Q],B.REPLACE,r)}return typeof e[0]=="string"?this.addCallbackOrWaitCollectionAvailable(this.state,e[0],B.REPLACE,e[1]):this.addCallbackOrWaitCollectionAvailable(e[0],e[1],B.REPLACE,e[2])}onAdd(...e){return typeof e[0]=="string"?this.addCallbackOrWaitCollectionAvailable(this.state,e[0],B.ADD,e[1],e[2]!==!1):this.addCallbackOrWaitCollectionAvailable(e[0],e[1],B.ADD,e[2],e[3]!==!1)}onRemove(...e){return typeof e[0]=="string"?this.addCallbackOrWaitCollectionAvailable(this.state,e[0],B.DELETE,e[1]):this.addCallbackOrWaitCollectionAvailable(e[0],e[1],B.DELETE,e[2])}bindTo(e,n,r,s=!0){let o=e.constructor[Symbol.metadata];r||(r=Object.keys(o).filter(a=>!isNaN(Number(a))).map(a=>o[a].name));let i=()=>{for(let a of r){let c=e[a];c!==void 0&&(n[a]=c)}};return s&&i(),this.addCallback(e[Q],B.REPLACE,i)}triggerChanges(e){this.uniqueRefIds.clear(),this.isTriggering=!0;for(let n=0,r=e.length;n<r;n++){let s=e[n],o=s.refId,i=s.ref,a=this.callbacks[o];if(a){if((s.op&B.DELETE)===B.DELETE&&Ye.isSchema(s.previousValue)){let c=s.previousValue[Q],u=this.callbacks[c]?.[B.DELETE];if(u)for(let l=u.length-1;l>=0;l--)try{u[l]()}catch(d){console.error(d)}}if(Ye.isSchema(i)){if(!this.uniqueRefIds.has(o)){let u=a[B.REPLACE];if(u)for(let l=u.length-1;l>=0;l--)try{u[l]()}catch(d){console.error(d)}}let c=a[s.field];if(c)for(let u=c.length-1;u>=0;u--)try{c[u](s.value,s.previousValue)}catch(l){console.error(l)}}else{let c=s.dynamicIndex??s.field;if((s.op&B.DELETE)===B.DELETE){if(s.previousValue!==void 0){let u=a[B.DELETE];if(u)for(let l=u.length-1;l>=0;l--)try{u[l](s.previousValue,c)}catch(d){console.error(d)}}if((s.op&B.ADD)===B.ADD){let u=a[B.ADD];if(u)for(let l=u.length-1;l>=0;l--)try{u[l](s.value,c)}catch(d){console.error(d)}}}else if((s.op&B.ADD)===B.ADD&&s.previousValue!==s.value){let u=a[B.ADD];if(u)for(let l=u.length-1;l>=0;l--)try{u[l](s.value,c)}catch(d){console.error(d)}}if(s.value!==s.previousValue){let u=a[B.REPLACE];if(u)for(let l=u.length-1;l>=0;l--)try{u[l](c,s.value)}catch(d){console.error(d)}}}this.uniqueRefIds.add(o)}}this.isTriggering=!1}},jf={get(t){if(t instanceof In)return new Iu(t);if("decoder"in t.serializer)return new Iu(t.serializer.decoder);throw new Error("Invalid room or decoder")},getLegacy(t){if(t instanceof In)return Ou(t);if("decoder"in t.serializer)return Ou(t.serializer.decoder);throw new Error("Invalid room or decoder")},getRawChanges(t,e){return iP(t,e)}};Er("map",{constructor:Yr});Er("array",{constructor:Wr});Er("set",{constructor:pa});Er("collection",{constructor:fa})});function Pt(){return typeof performance<"u"?performance.now():Date.now()}var wa=at(()=>{"use strict"});function ju(t,e){let n=globalThis,r=n.__colyseusDebug;if(!r){let s=[];r=n.__colyseusDebug={__buffer:s,publish(o,i){s.push([o,aP(i)]),s.length>cP&&s.shift()}}}r.publish(t,e)}function qu(){if(typeof globalThis>"u")return!1;let t=globalThis.__colyseusDebug;return t!=null&&t.__buffer===void 0}var aP,cP,xa=at(()=>{"use strict";aP=typeof WeakRef<"u"?t=>new WeakRef(t):t=>({deref:()=>t}),cP=64});function zt(t){return t[Q]}function tr(t){return t.constructor[uP]}function Sa(t,e){let n=tr(t)?.[e];return typeof n=="number"?n:-1}function Vg(t){let e=tr(t);if(!e)return[];let n=[];for(let r=0;;r++){let s=e[r];if(!s||typeof s.name!="string")break;typeof s.type=="string"&&n.push(s.name)}return n}function Ea(t){let e=tr(t),n=[],r=[];if(e)for(let s=0;;s++){let o=e[s];if(!o||typeof o.name!="string")break;typeof o.type=="string"&&(n.push(o.name),lP[o.type]===void 0&&r.push(o.name))}return{fields:n,numeric:r}}function fP(t){if(Number.isNaN(t))return 0;if(!Number.isFinite(t))return t>0?Number.MAX_SAFE_INTEGER:-Number.MAX_SAFE_INTEGER;if(t!==(t|0)&&Math.abs(t)<=34028235e31){let e=Math.fround(t);if(Math.abs(Math.abs(e)-Math.abs(t))<1e-4)return e}return t}function Hg(t,e){let n=tr(t),r=n?.[e];switch((typeof r=="number"?n[r]:void 0)?.type){case"float32":return Math.fround;case"number":return fP;default:return dP}}function $g(t){if(t.length>pP){let b=t;return S=>{let _={};for(let P=0;P<b.length;P++)_[b[P]]=S[b[P]];return _}}let e=t[0],n=t[1],r=t[2],s=t[3],o=t[4],i=t[5],a=t[6],c=t[7],u=t[8],l=t[9],d=t[10],f=t[11],h=t[12],p=t[13],g=t[14],x=t[15];return b=>{let S={};return e!==void 0&&(S[e]=b[e]),n!==void 0&&(S[n]=b[n]),r!==void 0&&(S[r]=b[r]),s!==void 0&&(S[s]=b[s]),o!==void 0&&(S[o]=b[o]),i!==void 0&&(S[i]=b[i]),a!==void 0&&(S[a]=b[a]),c!==void 0&&(S[c]=b[c]),u!==void 0&&(S[u]=b[u]),l!==void 0&&(S[l]=b[l]),d!==void 0&&(S[d]=b[d]),f!==void 0&&(S[f]=b[f]),h!==void 0&&(S[h]=b[h]),p!==void 0&&(S[p]=b[p]),g!==void 0&&(S[g]=b[g]),x!==void 0&&(S[x]=b[x]),S}}var uP,Gu,lP,dP,pP,_a=at(()=>{"use strict";wt();uP=Symbol.metadata??Symbol.for("Symbol.metadata"),Gu=kt;lP={string:!0,boolean:!0,bigint64:!0,biguint64:!0};dP=t=>t;pP=16});var Gf,hP,mP,Ut,jo,Wf=at(()=>{"use strict";wt();yr();wa();xa();_a();Gf=9,hP=Gf,mP=(t,e)=>(e?2:1)*(Gf+4+Gf*t),Ut=class Ut{constructor(e,n,r,s){m(this,"data");m(this,"_host");m(this,"_encoder");m(this,"_scratch",new Uint8Array(2048));m(this,"_framed",null);m(this,"_sentCount",0);m(this,"_lastProcessed",0);m(this,"_epoch",0);m(this,"_sendTimes");m(this,"_inputBufferSize");m(this,"_inputBuffer",null);m(this,"_reckonTimes",null);m(this,"_pendingReckon",0);m(this,"_lastStamp",0);m(this,"_stampRing",null);m(this,"_renderDeltaRing",null);m(this,"_ringSlots",0);m(this,"_warnedUnknownKeys",null);m(this,"_stampRender",!1);m(this,"_stampReckon",!1);m(this,"_allowRewind");m(this,"_sendListeners",null);m(this,"_renderDelay",0);m(this,"_renderDelayExplicit",!1);m(this,"_renderDelayProvider");m(this,"_tickRate");m(this,"_patchRate");m(this,"_subSteps",1);this._host=e,this.data=n,this._encoder=r,this._stampRender=s?.stampRender??!1,this._stampReckon=s?.stampReckon??!1,this._allowRewind=s?.allowRewind,this._allowRewind!==void 0&&r.mode==="unreliable"&&!Ut._warnedAllowRewindIgnored&&(Ut._warnedAllowRewindIgnored=!0,console.warn('@colyseus/sdk: `allowRewind` is ignored on `mode:"unreliable"` \u2014 a packet stamps its whole redundancy ring or none of it, so excluding one input would cost bandwidth rather than save it. Use `mode:"reliable"` to gate the lag-comp stamp per input.')),this._renderDelay=s?.renderDelay??0,this._renderDelayExplicit=s?.renderDelay!==void 0,this._tickRate=s?.tickRate,this._patchRate=s?.patchRate,this._subSteps=s?.subSteps??1;let o=this._tickRate?1e3/this._tickRate:1e3/60,i=Ut.BUFFER_RTT_BUDGET_MS+(this._patchRate??0);this._inputBufferSize=Math.max(Ut.BUFFER_FLOOR,Math.ceil(i/o*Ut.BUFFER_HEADROOM)),this._sendTimes=new Float64Array(this._inputBufferSize)}get mode(){return this._encoder.mode}get tickRate(){return this._tickRate}get stepSeconds(){return this._tickRate?1/this._tickRate:void 0}get stepMs(){return this._tickRate?1e3/this._tickRate:void 0}get patchRate(){return this._patchRate}get subSteps(){return this._subSteps}get subStepSeconds(){return this._tickRate?1/this._tickRate/this._subSteps:void 0}get subStepMs(){return this._tickRate?1e3/this._tickRate/this._subSteps:void 0}get lastProcessed(){return this._lastProcessed}get sentCount(){return this._sentCount}get pendingCount(){return this._sentCount-this._lastProcessed}get replayBufferSize(){return this._inputBufferSize}get epoch(){return this._epoch}at(e){if(this._inputBuffer!==null&&!(e<=this._lastProcessed||e>this._sentCount)){if(this._sentCount-e>=this._inputBufferSize){Ut._warnedBufferOverflow||(Ut._warnedBufferOverflow=!0,console.warn(`@colyseus/sdk: input replay buffer (${this._inputBufferSize}) overflowed \u2014 RTT exceeds its budget at this input rate; reconciliation may drift.`));return}return this._inputBuffer[e%this._inputBufferSize]}}reckonTimeAt(e){return this._reckonTimes===null||e<=this._lastProcessed||e>this._sentCount||this._sentCount-e>=this._inputBufferSize?0:this._reckonTimes[e%this._inputBufferSize]}reset(){this._encoder.reset(),this._sentCount=this._lastProcessed=this._encoder.seq,this._framed=null,this._lastStamp=0,this._ringSlots=0,this._sendTimes.fill(0),this._epoch++}bindRenderDelay(e){this._renderDelayExplicit||(this._renderDelayProvider=e)}_resolveRenderDelay(){return this._renderDelayProvider?this._renderDelayProvider():this._renderDelay}_warnUnknownFields(){let e=tr(this.data);if(e)for(let n of Object.keys(this.data))e[n]!==void 0||this._warnedUnknownKeys?.has(n)||((this._warnedUnknownKeys??(this._warnedUnknownKeys=new Set)).add(n),console.warn(`@colyseus/sdk input: "${n}" is not a declared field on ${this.data.constructor.name} \u2014 the write is never encoded or sent. Declare it with @type(...) on the input schema, or remove the write.`))}send(){let e=this._host.connection;if(!e?.isOpen)return 0;qu()&&this._warnUnknownFields();let n=this._encoder.encode(),r=this._encoder.mode==="reliable",s=this._stampReckon||this._stampRender,o=s&&r&&(this._allowRewind===void 0||this._allowRewind(this.data)),i=s&&!r,a=this._stampReckon&&this._stampRender,u=1+(o?hP+(a?2:0):i?mP(this._encoder.historySize,a):0)+n.length;u>this._scratch.byteLength&&(this._scratch=new Uint8Array(Math.max(u,this._scratch.byteLength*2)),this._framed=null),this._scratch[0]=(r?We.ROOM_INPUT_RELIABLE:We.ROOM_INPUT_UNRELIABLE)|(o||i?Lo.TIMED:0);let l={offset:1};if(i)this._writeRingStamps(l);else if(o){let{stamp:p,renderDelta:g}=this._sampleStamp();be.number(this._scratch,p-this._lastStamp,l),this._lastStamp=p,a&&be.uint16(this._scratch,g,l)}else this._pendingReckon=0;this._scratch.set(n,l.offset);let d=l.offset+n.length;(this._framed===null||this._framed.byteLength!==d)&&(this._framed=this._scratch.subarray(0,d));let f=this._framed,h;return r?(e.send(f),h=++this._sentCount):(e.sendUnreliable(f),h=this._sentCount=this._encoder.seq),this._recordSent(h),h}_writeRingStamps(e){let{stamp:n,renderDelta:r}=this._sampleStamp(),s=this._encoder.historySize,o=this._encoder.seq,i=this._ringSlots=Math.min(this._ringSlots+1,s),a=this._stampRing??(this._stampRing=new Float64Array(s));if(a[o%s]=n,be.number(this._scratch,i,e),be.uint32(this._scratch,n,e),this._writeSeriesDeltas(a,o,i,e),this._stampReckon&&this._stampRender){let c=this._renderDeltaRing??(this._renderDeltaRing=new Uint16Array(s));c[o%s]=r,be.uint16(this._scratch,r,e),this._writeSeriesDeltas(c,o,i,e)}}_writeSeriesDeltas(e,n,r,s){let o=e.length;for(let i=1;i<r;i++)be.number(this._scratch,e[(n-i+1)%o]-e[(n-i)%o],s)}_sampleStamp(){let e=this._host.clock,n=(e?.lastServerTime?.()??0)>0,r=n?Math.max(0,Math.round(e.serverNow()))>>>0:0,s=n?Math.min(65535,Math.max(0,Math.round(this._resolveRenderDelay()+(e.smoothedRtt?.()??0)/2))):0;return this._pendingReckon=r,{stamp:this._stampReckon?r:r>s?r-s:0,renderDelta:s}}_recordSent(e){if(this._inputBuffer===null){let r=this.data.constructor;this._inputBuffer=Array.from({length:this._inputBufferSize},()=>new r)}this._encoder.copyInto(this._inputBuffer[e%this._inputBufferSize]),this._sendTimes[e%this._inputBufferSize]=Pt(),this._stampReckon&&((this._reckonTimes??(this._reckonTimes=new Float64Array(this._inputBufferSize)))[e%this._inputBufferSize]=this._pendingReckon);let n=this._sendListeners;if(n!==null)for(let r=0;r<n.length;r++)n[r](e)}onSend(e){let n=this._sendListeners;return this._sendListeners=n!==null?[...n,e]:[e],()=>{let r=this._sendListeners;if(r===null)return;let s=r.indexOf(e);if(s<0)return;let o=r.slice();o.splice(s,1),this._sendListeners=o.length>0?o:null}}ackInput(e){if(e<=this._lastProcessed)return-1;let n=this._sentCount-e>=this._inputBufferSize;if(this._lastProcessed=e,n)return-1;let r=this._sendTimes[e%this._inputBufferSize];return r>0?Pt()-r:-1}};m(Ut,"BUFFER_FLOOR",64),m(Ut,"BUFFER_RTT_BUDGET_MS",1e3),m(Ut,"BUFFER_HEADROOM",1.5),m(Ut,"_warnedBufferOverflow",!1),m(Ut,"_warnedAllowRewindIgnored",!1);jo=Ut});var qo,st,Wu,Yu=at(()=>{"use strict";wa();qo=Object.freeze({now:()=>Pt(),serverNow:()=>Pt(),renderNow:()=>Pt(),rtt:()=>0,smoothedRtt:()=>0,jitter:()=>0,lastServerTime:()=>0,patchInterval:()=>0,setPatchInterval:t=>{},sample:(t,e)=>{}}),st=class st{constructor(){m(this,"_clockOffset",0);m(this,"_clockHasSample",!1);m(this,"_offsetCount",0);m(this,"_rttFloorT",[]);m(this,"_rttFloorV",[]);m(this,"_rtt",0);m(this,"_smoothedRtt",0);m(this,"_rttHasSample",!1);m(this,"_jitter",0);m(this,"_lastRecvTime",-1);m(this,"_lastServerTime",0);m(this,"_patchInterval",0);m(this,"_renderTau",st.RENDER_TAU);m(this,"_renderSn",0);m(this,"_renderSnAt",0)}serverNow(){return Pt()+this._clockOffset}renderNow(){let e=this.serverNow();if(this._renderTau<=0)return e;let n=Pt();if(this._renderSn===0)return this._renderSn=e,this._renderSnAt=n,this._renderSn;let r=Math.min(n-this._renderSnAt,100);return r<.5?this._renderSn:(this._renderSnAt=n,this._renderSn+=r,Math.abs(e-this._renderSn)>st.RENDER_SNAP?(this._renderSn=e,this._renderSn):(this._renderSn+=(e-this._renderSn)*(1-Math.exp(-r/this._renderTau)),this._renderSn))}setRenderTau(e){this._renderTau=e>0?e:0}now(){return Pt()}rtt(){return this._rtt}smoothedRtt(){return this._smoothedRtt}jitter(){return this._jitter}lastServerTime(){return this._lastServerTime}patchInterval(){return this._patchInterval}setPatchInterval(e){this._patchInterval=e>0?e:0}sample(e,n){let r=Pt(),s=st.EMA_ALPHA,o=this._patchInterval;if(this._lastRecvTime>=0&&o>0){let a=r-this._lastRecvTime,c=Math.round(a/o);c>=1&&c<=st.JITTER_STALL_X&&(this._jitter+=(Math.abs(a-c*o)-this._jitter)*st.JITTER_GAIN)}this._lastRecvTime=r,this._lastServerTime=e,(n<0||this._smoothedRtt>0&&n>this._smoothedRtt*st.RTT_OUTLIER_X)&&(n=-1);let i=n>=0?e+n/2-r:e-r;if(!this._clockHasSample)this._clockOffset=i,this._clockHasSample=!0,n>=0&&(this.pushRttFloor(n,r),this._offsetCount=1);else if(n>=0){let a=this.pushRttFloor(n,r),c=this._offsetCount<st.RTT_GATE_WARMUP;this._offsetCount++,(c||n<=a*st.RTT_GATE_FACTOR)&&(this._clockOffset=this._clockOffset*(1-s)+i*s)}n>=0&&(this._rtt=n,this._rttHasSample?this._smoothedRtt=this._smoothedRtt*(1-s)+n*s:(this._smoothedRtt=n,this._rttHasSample=!0))}pushRttFloor(e,n){let r=this._rttFloorT,s=this._rttFloorV;for(;s.length>0&&s[s.length-1]>=e;)s.pop(),r.pop();s.push(e),r.push(n);let o=n-st.RTT_GATE_WINDOW;for(;r.length>0&&r[0]<o;)r.shift(),s.shift();return s[0]}reset(){this._clockOffset=0,this._clockHasSample=!1,this._offsetCount=0,this._rtt=0,this._smoothedRtt=0,this._rttHasSample=!1,this._jitter=0,this._lastRecvTime=-1,this._lastServerTime=0,this._rttFloorT.length=0,this._rttFloorV.length=0,this._renderSn=0,this._renderSnAt=0}};m(st,"EMA_ALPHA",.1),m(st,"RENDER_TAU",250),m(st,"RENDER_SNAP",250),m(st,"RTT_OUTLIER_X",4),m(st,"JITTER_GAIN",1/16),m(st,"JITTER_STALL_X",4),m(st,"RTT_GATE_FACTOR",1.2),m(st,"RTT_GATE_WINDOW",1e4),m(st,"RTT_GATE_WARMUP",30);Wu=st});var mb=GE(($B,hb)=>{"use strict";hb.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});function UP(t,e){return{now:()=>t?.serverNow()??performance.now(),ttlMs:typeof e=="function"?()=>e(t?.smoothedRtt()??0):e}}var $a,pl,mp=at(()=>{"use strict";$a=t=>Math.max(t*2,600),pl=class t{constructor(){m(this,"entries",new Map);m(this,"accepted",new Set);m(this,"cfg",{});m(this,"dead",!1)}static get(e,n={}){let r=new t;return r.configure(UP(e.clock??null,n.ttlMs??$a)),n.onReject&&r.configure({onReject:n.onReject}),r}configure(e){this.cfg={...this.cfg,...e}}predict(e,n){return this.entries.set(e,n??this.cfg.now?.()??performance.now()),{key:e,cancel:()=>{this.entries.delete(e),this.accepted.delete(e)},accept:()=>{this.entries.has(e)&&this.accepted.add(e)}}}has(e){return this.entries.has(e)}confirm(e){this.entries.delete(e),this.accepted.delete(e)}reject(e){this.entries.delete(e)&&(this.accepted.delete(e),this.cfg.onReject?.(e))}prune(e,n){let r=e??this.cfg.now?.()??performance.now(),s=this.cfg.ttlMs,o=n??(typeof s=="function"?s():s)??1/0;for(let[i,a]of this.entries)this.accepted.has(i)||r-a>o&&(this.entries.delete(i),this.cfg.onReject?.(i))}clear(){this.entries.clear(),this.accepted.clear()}get size(){return this.entries.size}dispose(){this.dead=!0,this.entries.clear(),this.accepted.clear()}}});function Ib(){return{ema:0,peak:0}}function yp(t,e){t.ema+=(e-t.ema)*.1,t.peak=Math.max(e,t.peak*.9)}function Db(t){t.ema=0,t.peak=0}function ri(t,e){let n=e!==void 0&&e>Ob?e:Ob;return t.ema>=n?"diverging":t.peak>=n?"jitter":"matched"}var Ob,hl=at(()=>{"use strict";Ob=.001});function ja(){return qu()}function Nb(){console.warn("@colyseus/sdk predict: a predicted value was read BEFORE this frame's input.send() calls. Reads between predict.tick() and the frame's sends are one fixed step stale and stutter on late frames. Send the frame's due inputs right after predict.tick(now) \u2014 tick and pump in your earliest per-frame callback, before anything reads value()/pose(). For game logic (zone checks, hit-reg) read .state/.world instead. See PREDICTION.md \xA74 (frame order).")}function Lb(t,e){console.warn(e===""?`@colyseus/sdk predict: two key-less ctx.memo calls ran in one step (input seq ${t}) \u2014 the key-less form is ONE shared slot per step, so replay returns one frozen value for both (silent re-simulation corruption). Pass distinct keys: ctx.memo("a", \u2026) / ctx.memo("b", \u2026).`:`@colyseus/sdk predict: ctx.memo("${e}") ran twice in one step (input seq ${t}) \u2014 both calls share one slot on replay. Give each call site its own key (include the loop index for a per-iteration memo).`)}function Fb(t,e,n,r){let s=Pt();if(s-Bb<VP)return;Bb=s;let o="",i=-1;for(let c in e){let u=e[c],l=u<0?-u:u;l>i&&(i=l,o=c)}let a=o?e[o]:n;console.warn(`@colyseus/sdk predict: prediction is diverging at input seq ${t} \u2014 rolling drift ${n.toFixed(3)} \u2265 tolerance ${r}; "${o}" currently off by ${a.toFixed(3)}. Most likely the client and server simulations disagree: a different fixed dt, mismatched constants, a step function that isn't shared, or an input the server skipped. See PREDICTION.md \xA75 (Determinism).`)}var Bb,VP,gp=at(()=>{"use strict";wa();xa();Bb=-1/0,VP=1e3});function zb(){return wp>0}var bp,wp,si,ml=at(()=>{"use strict";hl();gp();bp=class{constructor(){m(this,"byTick",new Map);m(this,"diagTick",-1);m(this,"diagKeys",new Set);m(this,"warnedKeys",new Set)}run(e,n,r,s){if(n)return this.byTick.get(e)?.get(r);ja()&&(e!==this.diagTick?(this.diagTick=e,this.diagKeys.clear()):this.diagKeys.has(r)&&!this.warnedKeys.has(r)&&(this.warnedKeys.add(r),Lb(e,r)),this.diagKeys.add(r));let o=s();if(o!==void 0){let i=this.byTick.get(e);i===void 0&&(i=new Map,this.byTick.set(e,i)),i.set(r,o)}return o}prune(e){for(let n of this.byTick.keys())n<=e&&this.byTick.delete(n)}clear(){this.byTick.clear(),this.diagTick=-1,this.diagKeys.clear()}},wp=0;si=class{constructor(e){m(this,"lastCorrection",{});m(this,"lastCorrectionMag",0);m(this,"reconcileSeq",0);m(this,"drift",Ib());m(this,"error",{});m(this,"prev",{});m(this,"renderedBefore",{});m(this,"lastTick",-1);m(this,"lastAcked",0);m(this,"lastEpoch");m(this,"replayFrom",0);m(this,"predictedSeq",0);m(this,"catching",!1);m(this,"unsubscribeSend",()=>{});m(this,"renderAcc",0);m(this,"tickSeq",0);m(this,"clampedReadTick",-1);m(this,"warnedStaleRead",!1);m(this,"stepCtx");m(this,"ackWatermark",()=>this.input_.lastProcessed);m(this,"memos",new bp);m(this,"smoothMs");m(this,"snapThreshold");m(this,"stepMs");m(this,"input_");m(this,"onReconcile");m(this,"warnTolerance");m(this,"clock");m(this,"dead",!1);m(this,"disposedHooks",[]);this.input_=e.input,this.clock=e.clock,this.smoothMs=e.smoothMs??(this.input_.patchRate?this.input_.patchRate:50),this.snapThreshold=e.snap??0;let n=e.stepMs??this.input_.stepMs??(e.stepSeconds!==void 0?e.stepSeconds*1e3:void 0);if(n===void 0)throw new Error("@colyseus/sdk reconciler: fixed simulation step is unknown. The server room must call setFixedTimestep() (or setTimestep()) so the input handle advertises a tick rate, or pass stepMs/stepSeconds explicitly \u2014 a wrong dt silently diverges rollback-replay.");this.stepMs=n;let r=e.stepSeconds??this.input_.stepSeconds??n/1e3,s=e.subSteps??this.input_.subSteps??1;this.stepCtx={dt:r,dtMs:n,tick:0,isReplay:!1,reckonTime:0,lagCompActive:!1,subSteps:s,subDt:r/s,subDtMs:n/s,memo:(o,i)=>typeof o=="string"?this.memos.run(this.stepCtx.tick,this.stepCtx.isReplay,o,i):this.memos.run(this.stepCtx.tick,this.stepCtx.isReplay,"",o),predict:(o,i)=>{this.stepCtx.isReplay||o._predictFromSim(this.stepCtx.tick,i,this.ackWatermark)}},this.onReconcile=e.onReconcile,this.warnTolerance=e.warnOnDivergence,this.lastAcked=this.input_.lastProcessed,this.lastEpoch=this.input_.epoch,this.predictedSeq=this.input_.sentCount,this.unsubscribeSend=this.input_.onSend(()=>this.catchUp())}tick(e){this.tickSeq++;let n=this.lastTick<0?0:e-this.lastTick;this.lastTick=e,n>0&&this.stepMs>0&&(this.renderAcc+=n);let r=this.input_.epoch;r!==this.lastEpoch&&(this.lastEpoch=r,this.reset());let s=this.input_.lastProcessed;if(s>this.lastAcked&&(this.lastAcked=s,this.reconcile(s)),this.markDirty(),n<=0)return;let o=this.smoothMs<=0?1:1-Math.exp(-n/this.smoothMs);for(let i of this.smoothedFields())this.error[i]-=this.error[i]*o}renderAlpha(){if(this.stepMs<=0)return 1;let e=this.renderAcc/this.stepMs;return e<0?0:e>1?1:e}noteRenderRead(){this.catching||this.stepMs<=0||this.renderAcc<this.stepMs||(this.clampedReadTick=this.tickSeq)}catchUp(){let e=this.input_.sentCount;if(!(this.predictedSeq>=e||this.catching)){this.clampedReadTick===this.tickSeq&&!this.warnedStaleRead&&(this.warnedStaleRead=!0,Nb()),this.catching=!0,this.stepCtx.isReplay=!1;for(let n=this.predictedSeq+1;n<=e;n++){let r=this.input_.at(n);r!==void 0&&(this.snapshotPrev(),this.runStep(n,r),this.refreshRender(),this.renderAcc-=this.stepMs,this.renderAcc<0?this.renderAcc=0:this.renderAcc>=this.stepMs&&(this.renderAcc%=this.stepMs)),this.predictedSeq=n}this.catching=!1}}runStep(e,n){this.stepCtx.tick=e;let r=this.input_.reckonTimeAt(e);this.stepCtx.lagCompActive=r>0,this.stepCtx.reckonTime=r>0?r:this.clock!==void 0?this.clock.serverNow():0,this.applyStep(n)}reconcile(e){let n=this.warnTolerance!==void 0||ja();if(this.truthMatchesAt(e)){if(n){for(let u of this.smoothedFields())this.lastCorrection[u]=0;this.lastCorrectionMag=0,yp(this.drift,0)}this.reconcileSeq++,this.memos.prune(e),this.onReconcile?.(e);return}let r=this.renderedBefore;for(let u of this.smoothedFields())r[u]=this.readCurrent(u)+this.error[u];this.adoptTruth();let s=Math.max(e,this.replayFrom);this.stepCtx.isReplay=!0,this.catching=!0,wp++;try{for(let u=s+1;u<=this.input_.sentCount;u++){let l=this.input_.at(u);l!==void 0&&this.runStep(u,l)}}finally{wp--}this.catching=!1,this.refreshRender(),this.predictedSeq=this.input_.sentCount;let o=this.smoothMs<=0,i=n||this.snapThreshold>0,a=0;for(let u of this.smoothedFields()){let l=r[u]-this.readCurrent(u);if(this.error[u]=o?0:l,i){let d=l<0?-l:l;d>a&&(a=d)}n&&(this.lastCorrection[u]=l)}let c=this.snapThreshold>0&&a>this.snapThreshold;if(c)for(let u of this.smoothedFields())this.error[u]=0,this.prev[u]=this.readCurrent(u);this.reconcileSeq++,n&&(this.lastCorrectionMag=a,c||(yp(this.drift,a),this.warnTolerance!==void 0&&ri(this.drift,this.warnTolerance)==="diverging"&&Fb(e,this.lastCorrection,this.drift.ema,this.warnTolerance))),this.memos.prune(e),this.onReconcile?.(e)}get pendingCount(){return this.input_.pendingCount}reset(){this.reseedState(),Db(this.drift),this.replayFrom=this.input_.sentCount,this.predictedSeq=this.input_.sentCount,this.lastAcked=this.input_.lastProcessed,this.renderAcc=0,this.memos.clear(),this.markDirty()}onDisposed(e){this.disposedHooks.push(e)}dispose(){this.dead=!0,this.unsubscribeSend();for(let e of this.disposedHooks.splice(0))e()}truthMatchesAt(e){return!1}refreshRender(){}markDirty(){}}});var HP,xp,oi,Sp=at(()=>{"use strict";mp();ml();HP=0,xp=10,oi=class{constructor(e,n){m(this,"opts");m(this,"store");m(this,"entries",new Map);m(this,"now");m(this,"cooldownUntil",-1/0);m(this,"warnedReplayPredict",!1);m(this,"dead",!1);m(this,"teardowns",[]);this.opts=e,this.now=()=>n?.serverNow()??performance.now(),this.store=pl.get({clock:n},{ttlMs:e.ttlMs??$a,onReject:r=>{let s=this.entries.get(r);this.entries.delete(r),s&&this.opts.onReject?.(s.payload)}})}_predictFromSim(e,n,r){this.add(e,n,r)}predict(e){if(zb()){this.warnedReplayPredict||(this.warnedReplayPredict=!0,console.warn(`@colyseus/sdk: PredictedEventChannel${this.opts.label?` "${this.opts.label}"`:""}.predict() was called during a rollback replay and ignored. Inside a reconciler step, use ctx.predict(channel, payload).`));return}this.add(-1,e)}add(e,n,r){let s=this.opts.uniqueBy!==void 0?this.opts.uniqueBy(n):typeof n=="string"||typeof n=="number"?n:HP;if(this.entries.has(s))return;let o=this.now();if(this.opts.cooldownMs!==void 0){if(o<this.cooldownUntil)return;this.cooldownUntil=o+this.opts.cooldownMs}let i=this.store.predict(s,o);r!==void 0&&i.accept(),this.entries.set(s,{payload:n,seq:e,acked:r}),this.opts.onPredict?.(n)}has(e){return e===void 0?this.entries.size>0:this.entries.has(e)}get pendingCount(){return this.entries.size}confirm(e){let n=0;for(let r of this.settleKeys(e)){let s=this.entries.get(r);s!==void 0&&(this.entries.delete(r),this.store.confirm(r),this.opts.onConfirm?.(s.payload),n++)}return n===0&&this.opts.onUnpredicted?.(e),n}reject(e){let n=0;for(let r of this.settleKeys(e))this.entries.has(r)&&(this.store.reject(r),n++);return n}settleKeys(e){return e!==void 0?[e]:[...this.entries.keys()]}clear(){this.entries.clear(),this.store.clear()}prune(){if(this.entries.size>0){let e=this.opts.graceTicks??xp;for(let[n,r]of[...this.entries])r.acked!==void 0&&r.acked()>=r.seq+e&&this.store.reject(n)}this.store.prune()}_addTeardown(e){this.teardowns.push(e)}dispose(){for(let e of this.teardowns.splice(0))e();this.dead=!0,this.clear(),this.store.dispose()}}});var Hs,yl=at(()=>{"use strict";mp();Hs=class{constructor(e={},n=null){m(this,"opts");m(this,"clock");m(this,"correlate");m(this,"ttl");m(this,"byId",new Map);m(this,"byServer",new Map);m(this,"nextId",1);m(this,"lastTickAt");m(this,"detach");m(this,"dead",!1);m(this,"handleAdd",(e,n)=>{if(this.byServer.has(e))return;let r=this.isOwned(e)?this.takeMatch(e):void 0;if(r)this.confirmEntry(r,e);else{let s={id:this.nextId++,server:e,local:void 0,state:"confirmed",at:void 0,leadMs:0,accepted:!1,data:this.makeData()};this.byId.set(s.id,s),this.byServer.set(e,s)}});m(this,"handleRemove",(e,n)=>{let r=this.byServer.get(e);r&&(this.byServer.delete(e),this.byId.delete(r.id))});m(this,"readServer",(e,n)=>e[n]);this.opts=e,this.clock=n,this.correlate=e.correlate??"fifo",this.ttl=e.ttl??$a}attach(e){this.detach?.(),this.detach=e(this.handleAdd,this.handleRemove)}spawn(e){let n=this.nextId++,r=this.makeData(),s={id:n,server:void 0,local:e,state:"pending",at:this.now(),leadMs:0,accepted:!1,data:r};return this.byId.set(n,s),{id:n,local:e,data:r,cancel:()=>{let o=this.byId.get(n);o&&o.state==="pending"&&this.byId.delete(n)},accept:()=>{let o=this.byId.get(n);o&&(o.accepted=!0)}}}confirmEntry(e,n){e.server=n,e.state="confirmed";let r=this.opts.spawnTime;r!==void 0&&e.at!==void 0&&(e.leadMs=r(n)-e.at),this.byServer.set(n,e)}takeMatch(e){let n=this.correlate;if(typeof n!="function"){for(let r of this.byId.values())if(r.state==="pending")return r;return}for(let r of this.byId.values())if(r.state==="pending"&&n(r.local,e))return r}isOwned(e){return this.opts.owned?this.opts.owned(e):!0}makeData(){return this.opts.data?this.opts.data():void 0}tick(e=performance.now()){let n=this.opts.step,r=this.clock!==null?this.clock.serverNow():e;if(n!==void 0&&this.lastTickAt!==void 0){let s=Math.max(0,(r-this.lastTickAt)/1e3);if(s>0)for(let o of this.byId.values())o.state==="pending"&&n(o.local,s)}this.lastTickAt=r}prune(){if(this.byId.size===0)return;let e=this.now(),n=this.ttl(this.clock?.smoothedRtt()??0);for(let r of this.byId.values())r.state==="pending"&&!r.accepted&&r.at!==void 0&&e-r.at>n&&(this.byId.delete(r.id),this.opts.onReject?.(r.local,r.id))}entries(){return this.byId.values()}entryFor(e){return this.byServer.get(e)}value(e,n){return e.server!==void 0?this.readServer(e.server,n):e.local[n]}bindReader(e){this.readServer=e}alive(e){return this.byId.has(e)}get size(){return this.byId.size}clear(){this.byId.clear(),this.byServer.clear()}dispose(){this.dead=!0,this.detach?.(),this.detach=void 0,this.clear()}now(){return this.clock?.serverNow()??performance.now()}}});var Ub,$s,gl=at(()=>{"use strict";ml();_a();gp();Ub=t=>typeof t=="number"?t:typeof t=="boolean"?t?1:0:NaN,$s=class extends si{constructor(n,r){super(r);m(this,"local",{});m(this,"fields");m(this,"numericFields",[]);m(this,"step");m(this,"instance");m(this,"wireRound",[]);m(this,"history");m(this,"historySeq");m(this,"historySize");m(this,"historyOn");m(this,"undeclared",null);m(this,"devView",null);this.instance=n;let s=r.fields,o=s??Ea(n).fields;if(s===void 0&&o.length===0)throw new Error("predict.reconciler(): no `fields` given and none derivable \u2014 the instance has no schema metadata (a plain object, or a schema with no scalar fields). Pass the decoded instance from room.state, or list `fields` explicitly.");this.fields=o,this.step=r.step;let i=this.fields.length>0;for(let a of this.fields){let c=n[a];this.local[a]=c,typeof c=="number"?(this.numericFields.push(a),this.prev[a]=c,this.error[a]=0):typeof c!="boolean"&&(i=!1),this.wireRound.push(Hg(n,a))}if(this.historyOn=i,this.historySize=this.input_.replayBufferSize??64,this.history=new Float64Array(this.historyOn?this.historySize*this.fields.length:0),this.historySeq=new Float64Array(this.historyOn?this.historySize:0).fill(-1),s!==void 0){let a=new Set(this.fields),c=Ea(n).fields.filter(u=>!a.has(u));c.length>0&&(this.undeclared=new Set(c))}}get state(){return this.local}get boundRegistrations(){return[{source:this.instance,fields:this.numericFields,poseKeys:this.numericFields}]}value(n){this.noteRenderRead();let r=this.local[n];if(typeof r!="number")return r;let s=r+(this.error[n]??0),o=this.prev[n]??s;return o+(s-o)*this.renderAlpha()}smoothedFields(){return this.numericFields}readCurrent(n){return this.local[n]}applyStep(n){let r=this.undeclared!==null&&ja()?this.stepView():this.local;if(this.step(this.stepCtx,r,n),this.historyOn){let s=this.stepCtx.tick,o=s%this.historySize,i=o*this.fields.length;for(let a=0;a<this.fields.length;a++)this.history[i+a]=Ub(this.local[this.fields[a]]);this.historySeq[o]=s}}stepView(){if(this.devView!==null)return this.devView;let n=this.undeclared,r=new Set,s=(o,i)=>{typeof i!="string"||!n.has(i)||r.has(i)||(r.add(i),console.warn(`@colyseus/sdk predict: step ${o} "${i}" \u2014 a schema field NOT in this reconciler's \`fields\` list, so it is never mirrored or replayed: prediction integrates on top of a stale value and rubber-bands under latency. Add "${i}" to \`fields\`, or omit \`fields\` to mirror every scalar field. Read adopt-only fields off the raw instance instead of the predicted state.`))};return this.devView=new Proxy(this.local,{get(o,i,a){return s("read",i),Reflect.get(o,i,a)},set(o,i,a,c){return s("wrote",i),Reflect.set(o,i,a,c)}}),this.devView}truthMatchesAt(n){if(!this.historyOn)return!1;let r=n%this.historySize;if(this.historySeq[r]!==n)return!1;let s=r*this.fields.length,o=this.instance;for(let i=0;i<this.fields.length;i++)if(this.wireRound[i](this.history[s+i])!==Ub(o[this.fields[i]]))return!1;return!0}snapshotPrev(){for(let n of this.numericFields)this.prev[n]=this.local[n]+this.error[n]}adoptTruth(){let n=this.instance;for(let r of this.fields)this.local[r]=n[r]}reseedState(){let n=this.instance;for(let r of this.fields)this.local[r]=n[r];for(let r of this.numericFields)this.prev[r]=this.local[r],this.error[r]=0;this.historySeq.fill(-1)}}});var js,bl=at(()=>{"use strict";ml();_a();js=class extends si{constructor(n){super(n);m(this,"worldHandle");m(this,"bindings",[]);m(this,"curPose",{});m(this,"poseFields",[]);m(this,"customFields",[]);m(this,"fieldsReady",!1);m(this,"poseA",{});m(this,"poseB",{});m(this,"renderPose",{});m(this,"poseDirty",!0);m(this,"step");m(this,"adopt");m(this,"readPose");m(this,"interpolate");let r=n.world;for(let s of Object.keys(r)){let o=r[s];if(o===null||typeof o!="object")continue;if(zt(o)===void 0){if(tr(o)!==void 0)throw new Error(`predict.sim(): world.${s} is a schema instance that hasn't been decoded (no refId). Pass the decoded instance from room.state (e.g. inside onAdd), or a plain object for opaque scratch.`);continue}let{fields:i,numeric:a}=Ea(o);if(i.length===0)throw new Error(`predict.sim(): world.${s} is a decoded ref with no scalar fields to bind. Binding a whole COLLECTION isn't supported (yet) \u2014 spread its children into world parts (one entry per entity, fixed at construction). Nest a scalar-less instance below a plain wrapper if you meant it as an opaque handle.`);let c={};for(let l of i)c[l]=o[l];r[s]=c;let u=a.map(l=>`${s}.${l}`);this.bindings.push({source:o,mirror:c,fields:i,numeric:a,poseKeys:u})}if(this.bindings.length===0&&n.adopt===void 0)throw new Error("predict.sim(): no restore point \u2014 world has no schema-bound entries and no adopt() was provided. Put decoded schema instances in world (auto-bound), or provide adopt().");this.worldHandle=n.world,this.step=n.step,this.adopt=n.adopt,this.readPose=n.pose,this.interpolate=n.interpolate,this.refreshPose();for(let s of this.poseFields)this.prev[s]=this.curPose[s],this.error[s]=0}refreshPose(){let n=this.curPose;for(let r of this.bindings){let{mirror:s,numeric:o,poseKeys:i}=r;for(let a=0;a<o.length;a++)n[i[a]]=s[o[a]]}if(this.readPose!==void 0){let r=this.readPose(this.worldHandle);this.fieldsReady||(this.customFields=Object.keys(r));for(let s of this.customFields)n[s]=r[s]}if(!this.fieldsReady){let r=[];for(let s of this.bindings)for(let o of s.poseKeys)r.push(o);for(let s of this.customFields)r.includes(s)||r.push(s);this.poseFields=r,this.fieldsReady=!0}this.poseDirty=!0}get world(){return this.worldHandle}get boundRegistrations(){return this.bindings.map(n=>({source:n.source,fields:n.numeric,poseKeys:n.poseKeys}))}value(n){if(this.noteRenderRead(),this.interpolate)return this.pose()[n];let r=this.curPose[n]+(this.error[n]??0),s=this.prev[n]??r;return s+(r-s)*this.renderAlpha()}pose(){if(this.noteRenderRead(),!this.poseDirty)return this.renderPose;let n=this.renderAlpha(),r=this.poseA,s=this.poseB;for(let o of this.poseFields)r[o]=this.prev[o]??this.curPose[o],s[o]=this.curPose[o]+(this.error[o]??0);if(this.interpolate){let o=this.interpolate(r,s,n);for(let i of this.poseFields)this.renderPose[i]=o[i]}else for(let o of this.poseFields)this.renderPose[o]=r[o]+(s[o]-r[o])*n;return this.poseDirty=!1,this.renderPose}smoothedFields(){return this.poseFields}readCurrent(n){return this.curPose[n]}applyStep(n){this.step(this.stepCtx,this.worldHandle,n)}adoptTruth(){for(let n of this.bindings){let{source:r,mirror:s,fields:o}=n;for(let i=0;i<o.length;i++)s[o[i]]=r[o[i]]}this.adopt?.(this.worldHandle)}refreshRender(){this.refreshPose()}markDirty(){this.poseDirty=!0}snapshotPrev(){for(let n of this.poseFields)this.prev[n]=this.curPose[n]+this.error[n]}reseedState(){this.adoptTruth(),this.refreshPose();for(let n of this.poseFields)this.prev[n]=this.curPose[n],this.error[n]=0}}});function Vb(t,e,n,r){let s=[];if(n.field!==void 0){let o=new Map;s.push(t.onAdd(n.collection,(i,a)=>{o.has(i)||o.set(i,t.listen(i,n.field,c=>{c===n.equals&&e.confirm(a)},!1))})),s.push(t.onRemove(n.collection,i=>{o.get(i)?.(),o.delete(i)})),s.push(()=>{for(let i of o.values())i();o.clear()})}else n.event==="remove"?s.push(t.onRemove(n.collection,(o,i)=>{e.confirm(i)})):s.push(t.onAdd(n.collection,o=>{n.mine!==void 0&&o[n.mine]!==r?.()||e.confirm()},!1));return()=>{for(let o of s.splice(0))o?.()}}var Hb=at(()=>{"use strict"});function jb(t){return t===null||typeof t!="object"?!1:Array.isArray(t.fields)}function WP(){qb||(qb=!0,console.warn("@colyseus/sdk Predict: room.clock isn't server-synced because the server room didn't call defineInput(). Server-time interpolation and lag compensation fall back to local time. Add defineInput() on the server room to enable them \u2014 or ignore this if you only need local smoothing."))}var ct,rn,mn,kr,Nn,qa,Ga,ii,ai,ci,Wa,vt,$P,jP,$b,Ht,ui,qs,Gs,li,di,fi,pi,ir,Ya,Sl,El,_l,qP,wl,Ep,ts,xl,GP,qb,hi,Ws,_p=at(()=>{"use strict";wt();Sp();yl();gl();bl();Wf();hl();Yu();xa();_a();Hb();ct=16,rn=0,mn=1,kr=2,Nn=3,qa=4,Ga=5,ii=6,ai=7,ci=8,Wa=9,vt=Wa+ct*2,$P=3,jP=1.5,$b=250,Ht=7,ui=0,qs=1,Gs=2,li=3,di=4,fi=5,pi=6,ir=0,Ya=0,Sl=1,El=2,_l=3,qP=4,wl=5,Ep={lerp:Ya,extrapolate:Sl,damped:El,reckon:_l,raw:qP},ts={mode:"lerp",delay:100,smoothMs:50,maxExtrapolate:200,tickInterval:0,snap:0,angle:!1},xl={step:void 0,smoothMs:50,substep:16,snap:0};GP=0,qb=!1;hi=class hi{constructor(e,n){m(this,"callbacks");m(this,"sessionSource");m(this,"slotBuf",new Float64Array(64*vt));m(this,"slotCount",0);m(this,"slotDetach",[]);m(this,"slotAngle",[]);m(this,"freeSlots",[]);m(this,"slotByRef",new Map);m(this,"simByRef",new Map);m(this,"boundBySlot",new Map);m(this,"boundProfileIdx",-1);m(this,"renderTime",0);m(this,"defaultMode");m(this,"reckonDefaults");m(this,"clock");m(this,"useRenderClock",!1);m(this,"fixedStepMs");m(this,"stepAcc",0);m(this,"lastFrameNow",-1);m(this,"profileBuf",new Float64Array(8*Ht));m(this,"profileCount",0);m(this,"profileKeys",new Map);m(this,"profileLabels",[]);m(this,"profileComputers",[]);m(this,"trackListeners",[]);m(this,"name");m(this,"disposeListeners",[]);m(this,"driven",[]);m(this,"computeDamped",e=>{let n=this.slotBuf,r=e*vt,s=this.profileBuf,o=(n[r+Nn]|0)*Ht,i=this.renderTime,a=n[r+rn],c=n[r+kr],u=i-c;n[r+kr]=i;let l=n[r+mn];if(u>0){let d=s[o+Gs],f=d>0?1-Math.exp(-u/d):1;l+=(a-l)*f,n[r+mn]=l}return l});m(this,"computeLerp",e=>{let n=this.computeLerpRaw(e),r=this.slotBuf,s=e*vt,o=this.profileBuf[(r[s+Nn]|0)*Ht+pi],i=this.renderTime;if(o<=0)return r[s+mn]=n,r[s+ci]=n,r[s+kr]=i,n;let a=r[s+kr],c=i-a;if(c<=0)return r[s+mn];let u=r[s+ci],l=r[s+mn],d=c/o,f=(n-u)/d,h=n-f+(l-u+f)*Math.exp(-d);return r[s+mn]=h,r[s+ci]=n,r[s+kr]=i,h});m(this,"computeExtrapolate",e=>{let n=this.slotBuf,r=e*vt,s=this.profileBuf,o=(n[r+Nn]|0)*Ht,i=this.renderTime,a=n[r+ai]|0;if(a===0)return n[r+rn];let c=n[r+ii]|0,u=r+Wa,l=(c-a+ct)%ct,d=(l+a-1)%ct,f=u+d*2,h=n[f],p=n[f+1],g;if(a===1)g=p;else{let P=a>=3?2:1,R=(l+a-1-P+ct)%ct,v=u+R*2,M=n[v],O=n[v+1],z=h-M;if(z<=0)g=p;else{let X=(p-O)/z,N=s[o+li],Y=i-h;Y<0?Y=0:Y>N&&(Y=N),g=p+X*Y}}let x=n[r+kr];n[r+kr]=i;let b=s[o+Gs];if(b<=0)return n[r+mn]=g,g;let S=i-x,_=n[r+mn];if(S>0){let P=1-Math.exp(-S/b);_+=(g-_)*P,n[r+mn]=_}return _});m(this,"computeReckon",e=>{let n=this.slotBuf,r=e*vt,s=n[r+qa],o=n[r+Ga]|0,i=this.simByRef.get(s);if(i!==void 0){let a=o<i.posOf.length?i.posOf[o]:-1;if(a>=0)return this.applySimulation(i,a)}return n[r+rn]});m(this,"computeRaw",e=>this.slotBuf[e*vt+rn]);m(this,"computeBound",e=>{let n=this.boundBySlot.get(e);return n!==void 0?n.ctrl.value(n.key):this.slotBuf[e*vt+rn]});this.callbacks=jf.get(e),this.sessionSource=e;let{clock:r,...s}=n;this.defaultMode=s.mode??"lerp";let o=this.defaultMode!=="reckon"&&this.defaultMode!=="raw",i=o?(()=>{let u=s;return{mode:u.mode??ts.mode,delay:u.delay??ts.delay,smoothMs:u.smoothMs??ts.smoothMs,maxExtrapolate:u.maxExtrapolate??ts.maxExtrapolate,tickInterval:u.tickInterval??ts.tickInterval,snap:u.snap??ts.snap,angle:u.angle??ts.angle}})():{...ts},a=o?s.smoothMs??0:0;if(this.allocProfile(this.defaultMode,i.delay,i.smoothMs,a,i.maxExtrapolate,i.tickInterval,i.snap,!1)!==ir)throw new Error("Predict: defaults profile must be at index 0");if(this.defaultMode==="reckon"){let u=s;this.reckonDefaults={step:u.step,smoothMs:u.smoothMs??xl.smoothMs,substep:u.substep??xl.substep,snap:u.snap??xl.snap}}else this.reckonDefaults={...xl};this.clock=r??e.clock??void 0,this.useRenderClock=s.renderPresent!==!1,this.clock===qo&&WP(),this.name=s.name??`predict#${++GP}`,ju("predict",this.makeCoreHandle())}static get(e,n={}){return new hi(e,n)}get mode(){return this.defaultMode}presentFn(){let e=this.clock;if(e)return this.useRenderClock&&e.renderNow?e.renderNow.bind(e):e.serverNow.bind(e)}makeCoreHandle(){return{name:this.name,mode:()=>this.defaultMode,smoothingDefaults:()=>this.readSmoothingDefaults(),reckonDefaults:()=>({...this.reckonDefaults}),reconcilers:()=>this.snapshotReconcilers(),attachedCount:()=>this.slotByRef.size,setDefaults:e=>this.setDefaults(e),profiles:()=>this.snapshotProfiles(),setProfile:(e,n)=>this.setProfile(e,n),onTrack:e=>(this.trackListeners.push(e),()=>{let n=this.trackListeners.indexOf(e);n>=0&&this.trackListeners.splice(n,1)}),onDispose:e=>(this.disposeListeners.push(e),()=>{let n=this.disposeListeners.indexOf(e);n>=0&&this.disposeListeners.splice(n,1)})}}snapshotReconcilers(){let e=[],n=0;for(let r of this.driven){let s=r;if(!s.drift)continue;let o=s.warnTolerance;e.push({label:`reconciler #${n++}`,status:ri(s.drift,o),severity:o!==void 0&&o>0?s.drift.ema/o:void 0,ema:s.drift.ema,peak:s.drift.peak,lastCorrectionMag:s.lastCorrectionMag??0,reconcileSeq:s.reconcileSeq??0})}return e}readSmoothingDefaults(){let e=this.profileBuf,n=ir*Ht,r=e[n+ui]|0;return{mode:r===Ya?"lerp":r===Sl?"extrapolate":r===El?"damped":r===_l?"reckon":"raw",delay:e[n+qs],smoothMs:e[n+Gs],lerpSmoothMs:e[n+pi],maxExtrapolate:e[n+li],tickInterval:e[n+di],snap:e[n+fi]}}allocProfile(e,n,r,s,o,i,a,c,u){let l=typeof e=="number"?e:Ep[e],d="";if(c){d=`${u??""}|${l}|${n}|${r}|${s}|${o}|${i}|${a}`;let g=this.profileKeys.get(d);if(g!==void 0)return g}let f=this.profileCount++;if((f+1)*Ht>this.profileBuf.length){let g=new Float64Array(this.profileBuf.length*2);g.set(this.profileBuf),this.profileBuf=g}let p=f*Ht;return this.profileBuf[p+ui]=l,this.profileBuf[p+qs]=n,this.profileBuf[p+Gs]=r,this.profileBuf[p+pi]=s,this.profileBuf[p+li]=o,this.profileBuf[p+di]=i,this.profileBuf[p+fi]=a,this.profileLabels[f]=u,this.profileComputers[f]=this.computerForMode(l),c&&this.profileKeys.set(d,f),f}computerForMode(e){return e===Ya?this.computeLerp:e===Sl?this.computeExtrapolate:e===El?this.computeDamped:e===_l?this.computeReckon:e===wl?this.computeBound:this.computeRaw}profileFromOpts(e){if(e.mode===void 0&&e.delay===void 0&&e.smoothMs===void 0&&e.maxExtrapolate===void 0&&e.tickInterval===void 0&&e.snap===void 0)return ir;let n=this.readSmoothingDefaults(),r=e.mode??n.mode,s=e.delay??n.delay,o=e.smoothMs??n.smoothMs,i=e.smoothMs??n.lerpSmoothMs,a=e.maxExtrapolate??n.maxExtrapolate,c=e.tickInterval??n.tickInterval,u=e.snap??n.snap;return r===n.mode&&s===n.delay&&o===n.smoothMs&&i===n.lerpSmoothMs&&a===n.maxExtrapolate&&c===n.tickInterval&&u===n.snap?ir:this.allocProfile(r,s,o,i,a,c,u,!0)}groupProfile(e,n){let r=this.readSmoothingDefaults(),s=e.mode??this.defaultMode;return this.allocProfile(s,e.delay??r.delay,e.smoothMs??r.smoothMs,e.smoothMs??r.lerpSmoothMs,e.maxExtrapolate??r.maxExtrapolate,e.tickInterval??r.tickInterval,e.snap??r.snap,!0,n)}setDefaults(e){let n=e.mode;if(n!==void 0){this.defaultMode=n;let a=ir*Ht,c=Ep[n];this.profileBuf[a+ui]=c,this.profileComputers[ir]=this.computerForMode(c)}let r=e,s=ir*Ht,o=this.profileBuf;r.delay!==void 0&&(o[s+qs]=r.delay),r.smoothMs!==void 0&&(o[s+Gs]=r.smoothMs,o[s+pi]=r.smoothMs),r.maxExtrapolate!==void 0&&(o[s+li]=r.maxExtrapolate),r.tickInterval!==void 0&&(o[s+di]=r.tickInterval),r.snap!==void 0&&(o[s+fi]=r.snap,this.reckonDefaults.snap=r.snap);let i=e;i.step!==void 0&&(this.reckonDefaults.step=i.step),i.smoothMs!==void 0&&(this.reckonDefaults.smoothMs=i.smoothMs),i.substep!==void 0&&(this.reckonDefaults.substep=i.substep)}snapshotProfiles(){let e=[];for(let n=0;n<this.profileCount;n++){let r=n*Ht,s=this.profileBuf[r+ui]|0;if(s===wl)continue;let o=s===Ya?"lerp":s===Sl?"extrapolate":s===El?"damped":s===_l?"reckon":"raw";e.push({id:n,isDefault:n===ir,label:this.profileLabels[n],mode:o,delay:this.profileBuf[r+qs],smoothMs:this.profileBuf[r+(s===Ya?pi:Gs)],maxExtrapolate:this.profileBuf[r+li],tickInterval:this.profileBuf[r+di],snap:this.profileBuf[r+fi]})}return e}setProfile(e,n){if(e<0||e>=this.profileCount)return;let r=e*Ht,s=this.profileBuf;if((s[r+ui]|0)!==wl){if(n.mode!==void 0){let o=Ep[n.mode];s[r+ui]=o,this.profileComputers[e]=this.computerForMode(o),e===ir&&(this.defaultMode=n.mode)}n.delay!==void 0&&(s[r+qs]=n.delay),n.smoothMs!==void 0&&(s[r+Gs]=n.smoothMs,s[r+pi]=n.smoothMs),n.maxExtrapolate!==void 0&&(s[r+li]=n.maxExtrapolate),n.tickInterval!==void 0&&(s[r+di]=n.tickInterval),n.snap!==void 0&&(s[r+fi]=n.snap)}}dispose(){for(let e of new Set([...this.slotByRef.keys(),...this.simByRef.keys()]))this.detachByRef(e);this.trackListeners.length=0;for(let e of this.driven.splice(0))e.dispose?.();for(let e of this.disposeListeners.splice(0))e()}track(e,n,r={}){return this.trackWithProfile(e,n,this.profileFromOpts(r),r.angle??!1)}trackWithProfile(e,n,r,s=!1){let o=zt(e);if(o===void 0)throw new Error("Predict.track(): instance has no refId \u2014 track/attach must run AFTER the decoder delivers the instance (e.g. inside onAdd).");let i=Sa(e,n),a=e[n]??0,c,u=this.slotByRef.get(o)?.get(n);u!==void 0&&(c=this.boundBySlot.get(u),c!==void 0?this.freeStash(c):this.untrackSlot(o,n));let l=this.allocSlot(),d=this.slotBuf,f=l*vt;if(d[f+rn]=a,d[f+mn]=a,d[f+kr]=performance.now(),d[f+ci]=a,d[f+Nn]=r,d[f+qa]=o,d[f+Ga]=i,d[f+ii]=0,d[f+ai]=0,this.slotAngle[l]=s,c!==void 0)c.stash=l;else{let p=this.slotByRef.get(o);p===void 0&&(p=new Map,this.slotByRef.set(o,p)),p.set(n,l)}for(let p=0;p<this.trackListeners.length;p++)this.trackListeners[p](r,n);let h=this.callbacks.listen(e,n,p=>{let g=this.clock&&this.clock.lastServerTime()>0?this.clock.lastServerTime():performance.now(),x=this.slotBuf,b=l*vt;if(s){let N=x[b+rn];p=N+Math.atan2(Math.sin(p-N),Math.cos(p-N))}let S=(x[b+Nn]|0)*Ht,_=this.profileBuf[S+di],P=x[b+ii]|0,R=x[b+ai]|0,v=this.profileBuf[S+fi];v>0&&R>0&&Math.abs(p-x[b+rn])>v&&(P=0,R=0,x[b+mn]=p,x[b+ci]=p);let M=R===0?Number.NEGATIVE_INFINITY:x[b+Wa+(P===0?ct-1:P-1)*2],O=g;if(_>0&&isFinite(M)){let N=g-M,Y=N>0?Math.max(1,Math.round(N/_)):1;O=M+Y*_;let he=g+_;O>he&&(O=he)}x[b+rn]=p;let z=b+Wa;if(R>=2&&isFinite(M)){let N=P===0?ct-1:P-1,Y=N===0?ct-1:N-1,he=M-x[z+Y*2],A=this.clock?.patchInterval?this.clock.patchInterval():0,W=A>0?A:he,G=A>0?jP*A:$P*he;if(W>0&&O-M>G){let $=W<$b?W:$b,j=z+P*2;x[j]=O-$,x[j+1]=x[z+N*2+1],P=P+1>=ct?0:P+1,R<ct&&R++}}let X=z+P*2;x[X]=O,x[X+1]=p,x[b+ii]=P+1>=ct?0:P+1,R<ct&&(x[b+ai]=R+1)},!0);return this.slotDetach[l]=h,()=>this.untrackSlot(o,n)}untrack(e,n){let r=zt(e);r!==void 0&&this.untrackSlot(r,n)}untrackSlot(e,n){let r=this.slotByRef.get(e),s=r?.get(n);if(s===void 0)return;let o=this.boundBySlot.get(s);if(o!==void 0){this.freeStash(o);return}this.slotDetach[s]?.(),this.slotDetach[s]=void 0,this.freeSlots.push(s),r.delete(n),r.size===0&&this.slotByRef.delete(e)}freeStash(e){e.stash<0||(this.slotDetach[e.stash]?.(),this.slotDetach[e.stash]=void 0,this.freeSlots.push(e.stash),e.stash=-1)}allocSlot(){if(this.freeSlots.length>0)return this.freeSlots.pop();let e=this.slotCount++;if((e+1)*vt>this.slotBuf.length){let r=new Float64Array(this.slotBuf.length*2);r.set(this.slotBuf),this.slotBuf=r}return e}registerBound(e,n,r,s,o){let i=zt(n),a=this.slotByRef.get(i);a===void 0&&(a=new Map,this.slotByRef.set(i,a));let c=[];for(let u=0;u<r.length;u++){let l=r[u],d=a.get(l),f=-1;if(d!==void 0){let b=this.boundBySlot.get(d);b!==void 0?(console.warn(`@colyseus/sdk Predict: "${l}" (refId ${i}) is already bound to a controller \u2014 the newer registration wins.`),f=b.stash,this.boundBySlot.delete(d),this.freeSlots.push(d)):f=d}let h=this.allocSlot(),p=this.slotBuf,g=h*vt,x=n[l]??0;p[g+rn]=x,p[g+mn]=x,p[g+kr]=0,p[g+ci]=x,p[g+Nn]=o,p[g+qa]=i,p[g+Ga]=Sa(n,l),p[g+ii]=0,p[g+ai]=0,this.slotAngle[h]=!1,this.boundBySlot.set(h,{ctrl:e,key:s[u],stash:f}),a.set(l,h),c.push(h);for(let b=0;b<this.trackListeners.length;b++)this.trackListeners[b](o,l)}return()=>{for(let u=0;u<c.length;u++){let l=c[u],d=this.boundBySlot.get(l);if(d===void 0||d.ctrl!==e)continue;this.boundBySlot.delete(l),this.freeSlots.push(l);let f=this.slotByRef.get(i);f?.get(r[u])===l&&(d.stash>=0?f.set(r[u],d.stash):(f.delete(r[u]),f.size===0&&this.slotByRef.delete(i)))}}}installBoundOverlay(e){let n=[];for(let r of e.boundRegistrations)r.fields.length===0||zt(r.source)===void 0||(this.boundProfileIdx<0&&(this.boundProfileIdx=this.allocProfile(wl,0,0,0,0,0,0,!1,"bound")),n.push(this.registerBound(e,r.source,r.fields,r.poseKeys,this.boundProfileIdx)));n.length>0&&e.onDisposed(()=>{for(let r of n)r()})}trackStepped(e,n){let r=n.substep??16,s=n.fields,o=s.map(p=>Sa(e,p)),i=n.step,a=this.clock,c=this.presentFn(),u=n.forwardMs??(c?()=>{let p=a.lastServerTime();return p>0?Math.max(0,c()-p):0}:()=>0),l=n.elapsedMs??c??(()=>performance.now()),d=e[Gu],f=n.snapshot===void 0&&Array.isArray(d)&&o.every(p=>p>=0&&p<d.length),h;if(f){let p=new e.constructor,g=p[Gu];h=(x,b,S,_)=>{let P=x[Gu];for(let M=0;M<P.length;M++)g[M]=P[M];let R=b,v=_-b;for(;R>0;){let M=R<r?R:r;v+=M,i(p,M/1e3,v),R-=M}for(let M=0;M<o.length;M++)S[M]=g[o[M]]}}else{let p=Vg(e),g=n.snapshot??(p.length>0?$g(p):b=>({...b})),x=[...s];h=(b,S,_,P)=>{let R=g(b),v=S,M=P-S;for(;v>0;){let O=v<r?v:r;M+=O,i(R,O/1e3,M),v-=O}for(let O=0;O<x.length;O++)_[O]=R[x[O]]}}return this.trackSimulated(e,{fields:s,forwardMs:u,elapsedMs:l,smoothMs:n.smoothMs,snap:n.snap,advance:h})}trackSimulated(e,n){let r=zt(e);if(r===void 0)throw new Error("Predict.trackStepped(): instance has no refId \u2014 must run AFTER the decoder delivers the instance (e.g. inside onAdd).");let s=n.fields,o=s.length,i=s.map(h=>Sa(e,h)),a=0;for(let h of i)h>a&&(a=h);let c=new Int8Array(a+1).fill(-1);for(let h=0;h<o;h++)i[h]>=0&&(c[i[h]]=h);let u=new Float64Array(o);for(let h=0;h<o;h++)u[h]=e[s[h]]??0;let l=this.presentFn(),d=n.elapsedMs??l??(()=>performance.now()),f={instance:e,fieldIds:i,posOf:c,forwardMs:n.forwardMs,elapsedMs:d,advance:n.advance,smoothMs:n.smoothMs??50,snap:n.snap??0,smoothed:u,out:new Float64Array(o),valueOut:new Float64Array(o),offset:new Float64Array(o),outPrev:new Float64Array(o),frameVel:new Float64Array(o),lastBaseT:NaN,lastApplyTime:-1/0};return this.simByRef.set(r,f),()=>this.untrackSimulated(r)}untrackSimulated(e){this.simByRef.delete(e)}attach(e,n){let r=this.makeGroup("(attach)",n);return this.attachWithPlan(e,this.planFor(r,e))}makeGroup(e,n){return{label:e,config:n,basePlan:this.buildGroupPlan(n,e),planByCtor:new Map}}planFor(e,n){let r=n.constructor,s=e.planByCtor.get(r);return s===void 0&&(s=this.resolveCtorPlan(e,n),e.planByCtor.set(r,s)),s}resolveCtorPlan(e,n){let r=tr(n),s=n.constructor?.name||"?",o=e.config;if(!jb(o)){if(r===void 0)return e.basePlan;let c=Object.keys(o).filter(l=>o[l]!==void 0);if(c.every(l=>typeof r[l]=="number"))return e.basePlan;let u={};for(let l of c)typeof r[l]=="number"&&(u[l]=o[l]);return this.buildGroupPlan(u,`${e.label}:${s}`)}let i=o,a=i.fields;if(r!==void 0){let c=a.filter(u=>typeof r[u]=="number");c.length!==a.length&&(a=c)}return a===i.fields?e.basePlan:this.buildGroupPlan({...i,fields:a},`${e.label}:${s}`)}buildGroupPlan(e,n){let r=[];if(jb(e)){let o=e;if(!Array.isArray(o.fields))throw new Error("Predict.attach(): `fields` must be a numeric-key array.");let i=o.mode??this.defaultMode,a=o.step??this.reckonDefaults.step,c=i==="reckon";if(c&&typeof a!="function")throw new Error("Predict.attach(): reckon mode requires a 'step' function. Either pass `step` in the attach config OR construct the Predict with `Predict.get(room, { mode: 'reckon', step: yourStepFn })` so it can be inherited.");let u=this.groupProfile({mode:i,snap:o.snap,smoothMs:o.smoothMs},n);for(let l of o.fields)r.push({field:l,profileIdx:u,angle:o.angle});return{label:n,isReckon:c,reckonFields:c?o.fields:void 0,reckonStep:c?a:void 0,reckonSmoothMs:o.smoothMs??this.reckonDefaults.smoothMs,reckonSubstep:o.substep??this.reckonDefaults.substep,reckonSnap:o.snap??this.reckonDefaults.snap,reckonSnapshot:o.snapshot,fieldProfiles:r}}let s=e;for(let o of Object.keys(s)){let i=s[o];if(i===void 0)continue;let a=typeof i=="string"?{mode:i}:i;r.push({field:o,profileIdx:this.groupProfile(a,n),angle:a.angle})}return{label:n,isReckon:!1,fieldProfiles:r}}attachToGroup(e,n,r){let s=[];n.isReckon&&s.push(this.trackStepped(e,{fields:n.reckonFields,step:n.reckonStep,smoothMs:n.reckonSmoothMs,substep:n.reckonSubstep,snap:n.reckonSnap,snapshot:n.reckonSnapshot,forwardMs:r}));for(let{field:o,profileIdx:i,angle:a}of n.fieldProfiles)s.push(this.trackWithProfile(e,o,i,!!a));return()=>{for(let o of s)o()}}attachWithPlan(e,n){let r=zt(e);if(r===void 0)throw new Error("Predict.attach(): instance has no refId \u2014 attach must run AFTER the decoder delivers the instance (e.g. inside onAdd).");return this.attachToGroup(e,n),()=>this.detachByRef(r)}detach(e){let n=zt(e);n!==void 0&&this.detachByRef(n)}detachByRef(e){let n=this.slotByRef.get(e);if(n){for(let r of[...n.keys()]){let s=n.get(r);if(s===void 0)continue;let o=this.boundBySlot.get(s);o!==void 0?(this.freeStash(o),this.boundBySlot.delete(s),this.freeSlots.push(s),n.delete(r)):this.untrackSlot(e,r)}n.size===0&&this.slotByRef.delete(e)}this.simByRef.delete(e)}attachAll(...e){let n=typeof e[0]=="string",r=n?void 0:e[0],s=n?e[0]:e[1],o=n?e[1]:e[2],i=this.makeGroup(s,o),a=new Set,c=f=>{this.attachWithPlan(f,this.planFor(i,f)),a.add(f)},u=f=>{a.delete(f),this.detach(f)},l=n?this.callbacks.onAdd(s,c):this.callbacks.onAdd(r,s,c),d=n?this.callbacks.onRemove(s,u):this.callbacks.onRemove(r,s,u);return()=>{l?.(),d?.();for(let f of a)this.detach(f);a.clear()}}tick(e=performance.now()){this.renderTime=e;let n=0,r=this.fixedStepMs;if(r!==void 0&&r>0){let i=this.lastFrameNow<0?0:e-this.lastFrameNow;this.stepAcc+=i,n=Math.floor(this.stepAcc/r),n>hi.MAX_STEPS_PER_FRAME?(this.stepAcc=0,n=hi.MAX_STEPS_PER_FRAME):this.stepAcc-=n*r}this.lastFrameNow=e;let s=this.driven,o=0;for(let i=0;i<s.length;i++){let a=s[i];a.dead||(a.tick?.(e),a.prune?.(),o!==i&&(s[o]=a),o++)}return o!==s.length&&(s.length=o),n}defineEvent(e){let{confirmOn:n,...r}=e,s=new oi(r,this.clock??null);if(n!==void 0){if(n.mine!==void 0&&typeof this.sessionSource.sessionId!="string")throw new Error(`Predict.defineEvent: confirmOn.mine ("${n.mine}") requires a Predict built from a Room (it compares against room.sessionId); confirm manually instead.`);s._addTeardown(Vb(this.callbacks,s,n,()=>this.sessionSource.sessionId))}return this.driven.push(s),s}spawns(e,n={}){let r=new Hs(n,this.clock??null),s=n.fields,o=n.step,i=s!==void 0&&o!==void 0?this.makeGroup(String(e),{mode:"reckon",fields:s,step:o,smoothMs:n.smoothMs??0,substep:n.substep}):void 0,a=i!==void 0?new Map:void 0,c=this.clock;return r.attach((u,l)=>{let d=this.callbacks.onAdd(e,(h,p)=>{if(u(h,p),i===void 0||a.has(h))return;let g=r.entryFor(h)?.leadMs??0,x=c?()=>{let b=c.lastServerTime(),S=b>0?Math.max(0,c.serverNow()-b):0;return Math.max(0,S+g)}:()=>Math.max(0,g);a.set(h,this.attachToGroup(h,this.planFor(i,h),x))}),f=this.callbacks.onRemove(e,(h,p)=>{a?.get(h)?.(),a?.delete(h),l(h,p)});return()=>{if(d?.(),f?.(),a!==void 0){for(let h of a.values())h();a.clear()}}}),i!==void 0&&r.bindReader((u,l)=>this.value(u,l)),this.driven.push(r),r}canonicalDelay(){return this.profileBuf[ir*Ht+qs]}bindInputRenderDelay(e){e instanceof jo&&e.bindRenderDelay(()=>this.canonicalDelay())}reconciler(e,n){let r=new $s(e,{...n,clock:n.clock??this.clock});return this.adoptFixedStep(r.stepMs),this.bindInputRenderDelay(n.input),this.installBoundOverlay(r),this.driven.push(r),r}sim(e){let n=new js({...e,clock:e.clock??this.clock});return this.adoptFixedStep(n.stepMs),this.bindInputRenderDelay(e.input),this.installBoundOverlay(n),this.driven.push(n),n}adoptFixedStep(e){if(this.fixedStepMs===void 0){this.fixedStepMs=e,this.stepAcc=0,this.lastFrameNow=-1;return}Math.abs(this.fixedStepMs-e)>1e-6&&console.warn(`@colyseus/sdk Predict: a reconciler's fixed step (${e}ms) differs from this Predict's (${this.fixedStepMs}ms). tick() paces one rate for the whole room; use a separate Predict per rate.`)}value(e,n){let r=zt(e),s=r===void 0?void 0:this.slotByRef.get(r)?.get(n);if(s===void 0)return e[n];let o=this.slotBuf[s*vt+Nn]|0;return this.profileComputers[o](s)}valueAt(e,n,r){let s=zt(e),o=s===void 0?void 0:this.slotByRef.get(s)?.get(n);if(o===void 0)return e[n];let i=o*vt,a=this.slotBuf[i+Nn]|0;if(this.profileComputers[a]!==this.computeReckon)return this.profileComputers[a](o);let c=this.simByRef.get(this.slotBuf[i+qa]);if(c!==void 0){let u=this.slotBuf[i+Ga]|0,l=u<c.posOf.length?c.posOf[u]:-1;if(l>=0){let d=this.clock?.lastServerTime?.()??NaN,f=Number.isNaN(d)?0:Math.max(0,r-d);return c.advance(c.instance,f,c.valueOut,r),c.valueOut[l]}}return this.slotBuf[i+rn]}read(e,n,r){let s=r??{},o=zt(e),i=o===void 0?void 0:this.slotByRef.get(o);for(let a=0;a<n.length;a++){let c=n[a],u=i?.get(c);s[c]=u===void 0?e[c]:this.profileComputers[this.slotBuf[u*vt+Nn]|0](u)}return s}readAt(e,n,r,s){let o=s??{},i=zt(e),a=i===void 0?void 0:this.slotByRef.get(i),c,u=!1;for(let l=0;l<n.length;l++){let d=n[l],f=a?.get(d);if(f===void 0){o[d]=e[d];continue}let h=f*vt,p=this.slotBuf[h+Nn]|0;if(this.profileComputers[p]!==this.computeReckon){o[d]=this.profileComputers[p](f);continue}if(!u&&(u=!0,c=this.simByRef.get(this.slotBuf[h+qa]),c!==void 0)){let g=this.clock?.lastServerTime?.()??NaN,x=Number.isNaN(g)?0:Math.max(0,r-g);c.advance(c.instance,x,c.valueOut,r)}if(c!==void 0){let g=this.slotBuf[h+Ga]|0,x=g<c.posOf.length?c.posOf[g]:-1;if(x>=0){o[d]=c.valueOut[x];continue}}o[d]=this.slotBuf[h+rn]}return o}computeLerpRaw(e){let n=this.slotBuf,r=e*vt,s=this.profileBuf,o=(n[r+Nn]|0)*Ht,i=this.renderTime,a=n[r+ai]|0;if(a===0)return n[r+rn];let c=n[r+ii]|0,u=r+Wa,l=(c-a+ct)%ct,d=(l+a-1)%ct,f=u+d*2;if(a===1)return n[f+1];let h=s[o+qs],p=this.clock&&this.clock.lastServerTime()>0?this.clock.serverNow()-h-this.clock.smoothedRtt()/2:i-h,g=u+l*2;if(p<=n[g])return n[g+1];if(p>=n[f])return n[f+1];let x=a-2,b=(l+x)%ct;for(;x>0&&!(n[u+b*2]<=p);)x--,b=b===0?ct-1:b-1;let S=u+b*2,_=b+1>=ct?0:b+1,P=u+_*2,R=n[S],M=n[P]-R;if(M<=0)return n[P+1];let O=(p-R)/M,z=n[S+1],X=n[P+1];return z+(X-z)*O}applySimulation(e,n){let r=this.renderTime;if(e.lastApplyTime!==r){let s=e.out,o=e.smoothed,i=e.offset,a=o.length,c=this.clock?.lastServerTime?.()??NaN;if(e.advance(e.instance,e.forwardMs(),s,e.elapsedMs()),e.lastApplyTime===-1/0||e.smoothMs<=0)for(let d=0;d<a;d++)i[d]=0,o[d]=s[d];else if(Number.isNaN(c)){let d=Math.max(0,Math.min(r-e.lastApplyTime,100)),f=1-Math.exp(-d/e.smoothMs);for(let h=0;h<a;h++)o[h]+=(s[h]-o[h])*f}else{let d=Math.max(0,Math.min(r-e.lastApplyTime,100));if(c!==e.lastBaseT&&!Number.isNaN(e.lastBaseT)){let h=e.snap,p=e.frameVel;for(let g=0;g<a;g++){let x=o[g]+p[g]*d-s[g];i[g]=h>0&&Math.abs(x)>h?0:x}}else if(d>0){let h=e.outPrev,p=e.frameVel;for(let g=0;g<a;g++)p[g]=(s[g]-h[g])/d}let f=Math.exp(-d/e.smoothMs);for(let h=0;h<a;h++)i[h]*=f,o[h]=s[h]+i[h]}let l=e.outPrev;for(let d=0;d<a;d++)l[d]=s[d];e.lastBaseT=c,e.lastApplyTime=r}return e.smoothed[n]}};m(hi,"MAX_STEPS_PER_FRAME",5);Ws=hi});var p0={};Fd(p0,{DEFAULT_GRACE_TICKS:()=>xp,Predict:()=>Ws,PredictedEventChannel:()=>oi,PredictedSpawns:()=>Hs,Reconciler:()=>$s,SimReconciler:()=>js,classifyDrift:()=>ri});var Mp=at(()=>{"use strict";_p();gl();hl();bl();Sp();yl()});var Xi="genex-native";var Yc="genex_native";var Kc="genex_protocol",Xc="genex_attempt",Jc="genex_nonce",Ud="genex_caps";var ko="genex_";var Vd="genex_r";var Hd="entryRef",$d="genex_hash",jd="genex_referrer",qd="genex_ref";var Zc="__genexNative";var KE=/^[0-9a-f]{32}$/,XE=/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;function hr(t){return typeof t=="string"&&KE.test(t)}function Gd(t){return typeof t=="string"&&XE.test(t)}var Po="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",JE=(()=>{let t=new Array(128).fill(-1);for(let e=0;e<Po.length;e++)t[Po.charCodeAt(e)]=e;return t})();function cm(t){let e=[];for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);if(r>=55296&&r<=56319){let s=n+1<t.length?t.charCodeAt(n+1):0;s>=56320&&s<=57343?(r=65536+(r-55296<<10)+(s-56320),n++):r=65533}else r>=56320&&r<=57343&&(r=65533);r<128?e.push(r):r<2048?e.push(192|r>>6,128|r&63):r<65536?e.push(224|r>>12,128|r>>6&63,128|r&63):e.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|r&63)}return e}function ZE(t){let e="";for(let n=0;n<t.length;){let r=t[n],s,o;if(r<128)s=r,o=1;else if((r&224)===192)s=r&31,o=2;else if((r&240)===224)s=r&15,o=3;else if((r&248)===240)s=r&7,o=4;else return null;if(n+o>t.length)return null;for(let i=1;i<o;i++){let a=t[n+i];if((a&192)!==128)return null;s=s<<6|a&63}if(o===2&&s<128||o===3&&(s<2048||s>=55296&&s<=57343)||o===4&&(s<65536||s>1114111))return null;if(s>65535){let i=s-65536;e+=String.fromCharCode(55296+(i>>10),56320+(i&1023))}else e+=String.fromCharCode(s);n+=o}return e}function Wd(t){return cm(t).length}function Yd(t){let e=cm(JSON.stringify(t)),n="";for(let r=0;r<e.length;r+=3){let s=e[r],o=e[r+1],i=e[r+2];if(n+=Po[s>>2],n+=Po[(s&3)<<4|(o??0)>>4],o===void 0||(n+=Po[(o&15)<<2|(i??0)>>6],i===void 0))break;n+=Po[i&63]}return n}function Kd(t){if(t.length%4===1)return;let e=[],n=0,r=0;for(let o=0;o<t.length;o++){let i=t.charCodeAt(o),a=i<128?JE[i]:-1;if(a<0)return;n=n<<6|a,r+=6,r>=8&&(r-=8,e.push(n>>r&255))}if(r>0&&(n&(1<<r)-1)!==0)return;let s=ZE(e);if(s!==null)try{return JSON.parse(s)}catch{return}}var um=2048,lm=32;var e_=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/;function t_(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Qc(t,e){if(Object.keys(t).length!==e.length)return!1;for(let r of e)if(!Object.prototype.hasOwnProperty.call(t,r))return!1;return!0}var eu=["channel","v","type","slug","attemptId","nonce"];function n_(t){return t.channel===Xi&&t.v===1&&Gd(t.slug)&&hr(t.attemptId)&&hr(t.nonce)}function Xd(t){if(!(!t_(t)||!n_(t)))switch(t.type){case"ticket":return!Qc(t,[...eu,"ticket","expiresAt"])||typeof t.ticket!="string"||t.ticket.length===0||t.ticket.length>um||typeof t.expiresAt!="string"||t.expiresAt.length>lm||!e_.test(t.expiresAt)?void 0:t;case"guest":case"cancel":return Qc(t,eu)?t:void 0;case"foreground":return!Qc(t,[...eu,"active"])||typeof t.active!="boolean"?void 0:t;case"network":return!Qc(t,[...eu,"online"])||typeof t.online!="boolean"?void 0:t;default:return}}function s_(t,e){if(typeof t!="string"||t.length===0)return{ok:!1,reason:"undecodable"};if(Wd(t)>4096)return{ok:!1,reason:"too-large"};let n=Kd(t);if(n===void 0)return{ok:!1,reason:"undecodable"};let r=e(n);return r===void 0?{ok:!1,reason:"invalid"}:{ok:!0,message:r}}function Zd(t){return s_(t,Xd)}function Qd(t){let e=Yd(t);if(!(e.length>4096))return e}function tu(t,e){let n=t.charAt(0)==="?"?t.slice(1):t;if(n.length===0)return null;for(let r of n.split("&")){let s=r.indexOf("=");if(s!==-1&&r.slice(0,s)===e)return r.slice(s+1)}return null}function nu(t){return tu(t,Yc)==="1"}function tf(t){if(!nu(t))return null;let e=tu(t,Xc),n=tu(t,Jc),r=Number(tu(t,Kc));return!hr(e)||!hr(n)||r!==1?null:{attemptId:e,nonce:n,protocol:r}}function mm(t){return t.indexOf("%")===-1?t:t.replace(/%([0-9A-Fa-f]{2})/g,(e,n)=>{let r=parseInt(n,16);return r<128?String.fromCharCode(r):e})}function ym(t){let e=t.indexOf("="),n=e===-1?t:t.slice(0,e);return mm(n.indexOf("+")===-1?n:n.split("+").join(" "))}function ru(t){return gm(t,[Vd])}var i_=[Yc,Kc,Xc,Jc,Ud];function nf(t){return gm(t,i_)}function gm(t,e){let n=t.charAt(0)==="?"?t.slice(1):t;if(n.length===0)return"";let r=n.split("&"),s=r.filter(i=>!e.includes(ym(i)));if(s.length===r.length)return`?${n}`;let o=s.join("&");return o.length===0?"":`?${o}`}var a_=/^[!$-&(-;=?-~]+$/;function su(t,e){if(typeof t!="string")return"";let n=t.charAt(0)==="?"?t.slice(1):t,r=n.indexOf("#");if(r!==-1&&(n=n.slice(0,r)),n.length===0||!a_.test(n))return"";let o=n.split("&").filter(i=>{if(i.length===0)return!1;let a=ym(i);return!a.startsWith(ko)&&!e.includes(a)}).join("&");return o.length>1024?"":o}var c_=/^#[!#-;=?-_a-~]+$/;function ou(t){return typeof t!="string"||t.length<2||t.length>4096||!c_.test(t)||mm(t).includes(ko)?"":t}var u_=/^[a-z0-9._-]+$/,l_=/^\[[0-9a-f:.]+\]$/;function d_(t){return u_.test(t)&&/[a-z0-9]/.test(t)||l_.test(t)}function ef(t){let e=t.slice(0,8).toLowerCase(),n=e==="https://"?"https":e.slice(0,7)==="http://"?"http":null;if(n===null)return null;let r=n.length+3,s=t.length;for(let u=r;u<t.length;u++){let l=t.charAt(u);if(l==="/"||l==="?"||l==="#"||l==="\\"){s=u;break}}if(s-r>255)return null;let o=t.slice(r,s).toLowerCase();if(o.length===0||o.indexOf("@")!==-1)return null;let i=o,a="",c=o.lastIndexOf(":");if(c!==-1&&o.charAt(o.length-1)!=="]"&&(i=o.slice(0,c),a=o.slice(c+1)),!d_(i))return null;if(a.length>0){if(!/^[0-9]{1,5}$/.test(a))return null;let u=Number(a);if(u>65535)return null;a=u===(n==="https"?443:80)?"":`:${u}`}return`${n}://${i}${a}`}function vo(t,e){if(typeof t!="string"||t.length===0)return null;let n=ef(t);return n===null||n.length>255||typeof e=="string"&&ef(e)===n?null:n}var bm=["open","save","fullscreen"];var wm=50*1024*1024,f_=16;function xm(t){return typeof t=="string"&&bm.includes(t)}function rf(t){if(!Array.isArray(t))return[];let e=[],n=Math.min(t.length,f_);for(let r=0;r<n;r++){let s=t[r];xm(s)&&!e.includes(s)&&e.push(s)}return e}var R_=null;function Em(t){R_=t}var P_=null;function _m(t){P_=t}var A_=null;function Rm(t){A_=t}var ea=1,uf="genex:embed:retry",Fm="genex:guest:popover-dismissed",zm="genex:embed:local-auth",Um="genex:embed:entry-referrer",v_="none",km="genex:player",T_="0.35.0",De=null,Fe="pending",Zt=null,Vr=!1,zr=null,To=!1,Ur,Mo,Vm=0,Lt,Hm,lf,$m,jm=!1,Hr=null,qm=[],Oo=!1,As=!1,Zi=!1,Jt=0,Io=1e4,M_=2e3,C_=10*6e4,O_=6e4,Pm=500,I_=3e4,D_=3e4,Ge,Rn,Co,Am=!1,vm,iu=null,Tm=new Set;var Mm=!1,B_=new Map,Gm=[],ta=[],Qi=null,au=null,Ps,sf,of=!1,cu=new Map;function Ze(){return globalThis.window}function df(){return globalThis.document}function na(t,e,n){let r;if(n!==void 0)try{let s=globalThis.AbortSignal;s&&typeof s.timeout=="function"&&(r=s.timeout(n))}catch{}return globalThis.fetch(t,r?{...e,signal:r}:e)}function N_(){try{return Ze()?.sessionStorage?.getItem(uf)==="1"}catch{return!1}}function L_(){try{Ze()?.sessionStorage?.setItem(uf,"1")}catch{}}function ff(){try{Ze()?.sessionStorage?.removeItem(uf)}catch{}}function F_(){try{return Ze()?.sessionStorage?.getItem(zm)==="1"}catch{return!1}}function z_(){try{Ze()?.sessionStorage?.setItem(zm,"1")}catch{}}function U_(){try{let t=Ze()?.sessionStorage?.getItem(Um);return t==null?void 0:vo(t)}catch{return}}function V_(t){try{Ze()?.sessionStorage?.setItem(Um,t??v_)}catch{}}function H_(){try{return Ze()?.sessionStorage?.getItem(Fm)==="1"}catch{return!1}}function $_(){try{Ze()?.sessionStorage?.setItem(Fm,"1")}catch{}}function j_(){try{let t=Ze()?.localStorage;if(!t)return"no-storage";let e=t.getItem(km);return e||(e=typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,t.setItem(km,e)),e}catch{return"no-storage"}}function lu(t){let e=Ze();if(!e||Oo)return;if(Oo=!0,Co!==void 0&&(clearTimeout(Co),Co=void 0),De={slug:t.slug,apiUrl:t.apiUrl.replace(/\/$/,""),dashboardOrigins:[...t.dashboardOrigins]},Fe="pending",Qm(e),_m({apiUrl:De.apiUrl,dashboardOrigins:De.dashboardOrigins,getToken:()=>Lt,getParentOrigin:()=>Hr,isEmbedded:Ft,isNative:fn,isLocalTest:()=>Vr}),Rm({apiUrl:De.apiUrl,dashboardOrigins:De.dashboardOrigins,getToken:()=>Lt,getParentOrigin:()=>Hr,isEmbedded:Ft,isNative:fn,isLocalTest:()=>Vr}),bf(e)){gR(e);return}pu("connecting");let n=ey(e);if(n){oR(e,n);return}Ft()?rR(e):cR(e)}function Ft(){let t=Ze();if(!t)return!1;try{return t.self!==t.top}catch{return!0}}function q_(){let t=Ze();return t?Ft()?"page":fn()||hf(t)?"app":Oo?Vr?"local":"standalone":bf(t,!1)?"local":"standalone":"standalone"}function du(){return jm?{embedToken:fR}:Lt?{embedToken:Lt}:void 0}function Wm(){return Hm??[]}function Ym(){return cy(lf)??[]}function Km(){return mR($m)}function pf(){return(Fe==="authenticated"||Fe==="guest")&&Zt?Promise.resolve({user:Zt,guest:Fe==="guest"}):Fe==="blocked"?Promise.reject(new Error("genex embed auth: blocked")):(G_("waitForPlayer"),new Promise((t,e)=>{ta.push({resolve:t,reject:e})}))}function G_(t){if(!Oo){if(!Am){Am=!0;try{console.error(`[genex] ${t}() called before initEmbed() \u2014 identity can never resolve and the game will sit black. Call initEmbed({ slug, apiUrl, dashboardOrigins }) first (genex-threejs-embed-auth), and draw a frame before you await identity.`)}catch{}}Co===void 0&&(Co=setTimeout(()=>{Co=void 0,Oo||mr("no-identity")},Io))}}var W_=32*1024;async function Xm(){if(!De)throw new Error("genex embed: call initEmbed() first");if(Fe==="pending"&&await pf(),Fe==="blocked")throw new Error("genex embed auth: blocked")}function Jm(t,e={}){let n={Authorization:`Bearer ${Lt}`};return e.body!==void 0&&(n["Content-Type"]="application/json"),e.ifVersion!==void 0&&(n["If-Match"]=String(e.ifVersion)),na(`${De.apiUrl}/api/projects/${encodeURIComponent(De.slug)}${t}`,{method:e.method??"GET",headers:n,body:e.body,keepalive:e.body!==void 0&&e.body.length<=W_?!0:void 0})}async function Y_(t){return t.status!==403?!1:(await t.json().catch(()=>null))?.error==="staging_no_save"}async function K_(t){return t.status===409?{saved:!1,conflict:!0,version:(await t.json().catch(()=>({}))).version}:t.ok?{saved:!0,version:(await t.json()).version}:await Y_(t)?{saved:!1,staging:!0}:(Qt("error",{error:new Error(`genex state save failed (${t.status})`)}),{saved:!1})}async function X_(t,e){return await Xm(),Fe==="guest"?(sf=t,of=!0,{saved:!1,guest:!0,queued:!0}):K_(await Jm("/state/me",{method:"PUT",body:JSON.stringify(t),ifVersion:e?.ifVersion}))}async function J_(t,e){let n=e?.board??"main",r=e?.mode??"max";if(await Xm(),Fe==="guest"){let i=cu.get(n);return(!i||(r==="min"?t<i.score:t>i.score))&&cu.set(n,{score:t,mode:r}),{submitted:!1,guest:!0,queued:!0}}let s=await Jm("/scores",{method:"POST",body:JSON.stringify({score:t,board:n,mode:r})});if(!s.ok)return Qt("error",{error:new Error(`genex score submit failed (${s.status})`)}),{submitted:!1};let o=await s.json();return{submitted:!0,best:o.best,improved:o.improved}}async function Z_(){try{if(of){let e=sf;sf=void 0,of=!1,await X_(e)}let t=[...cu.entries()];cu.clear();for(let[e,{score:n,mode:r}]of t)await J_(n,{board:e,mode:r})}catch(t){Qt("error",{error:t})}}function Qt(t,e){let n=B_.get(t);if(n)for(let r of[...n])try{r(e)}catch{}}var Q_=["embed"];function Zm(t,e){let n={ticket:null,guest:!1,entryHash:"",entryReferrer:null};if(!t||t.length<2)return n;try{let r=new URLSearchParams(t.slice(1));return{ticket:r.get("genex_ticket"),guest:r.get("genex_guest")==="1",entryHash:ou(r.get($d)),entryReferrer:vo(r.get(jd),e)}}catch{return n}}function eR(t,e){try{return new URLSearchParams(t).get(e)}catch{return null}}function Qm(t){if(iu)return iu;let e="",n="",r=null;try{e=t.location.search??"",n=uu??t.location.hash??"",r=t.location.origin??null}catch{}let s=Ft(),o=Zm(n,r),i=!s&&(!!o.ticket||o.guest),a=su(e,Q_);return iu={search:a?`?${a}`:"",hash:i?o.entryHash:n.includes(ko)?"":n,referrer:tR(e,s,i,o.entryReferrer,r)},iu}function tR(t,e,n,r,s){let o=U_();if(o!==void 0)return o;let i;return e?i=vo(eR(t,qd),s):n?i=r:i=vo(df()?.referrer,s),V_(i),i}function nR(){if(!(Mm||Tm.size===0)){Mm=!0;for(let t of[...Tm])try{t()}catch{}}}function rR(t){vm=e=>{sR(e)},t.addEventListener("message",vm),t.parent.postMessage({type:"genex:embed:ready",v:ea},"*"),Ge=setTimeout(()=>{Do()},Io)}function Cm(){return(Fe==="pending"||Fe==="guest")&&!As}async function sR(t){if(!De)return;let e=t.data;if(!e||e.v!==ea)return;let n=e.type==="genex:embed:ticket",r=e.type==="genex:embed:guest";if(!(!n&&!r)&&!(n&&(!Cm()||typeof e.ticket!="string"||!e.ticket))&&!(r&&(Fe!=="pending"||As||Zi))){if(!De.dashboardOrigins.includes(t.origin)){let s=await af();if(n&&!Cm()||r&&(Fe!=="pending"||As||Zi)||!s.includes(t.origin))return}if(Ge!==void 0&&clearTimeout(Ge),Hr=t.origin,qm=rf(e.caps),r){await Do();return}await gf(e.ticket)}}function hf(t){let e=t.ReactNativeWebView;return!e||typeof e!="object"?null:typeof e.postMessage=="function"?e:null}function ey(t){if(Ft())return null;let e;try{e=t.location.search??""}catch{return null}return!nu(e)||!hf(t)?null:tf(e)}function fn(){return zr!==null}function vs(t){let e=Ze();if(!e||!De||!zr)return;let n=hf(e);if(!n)return;let r=Qd({channel:Xi,v:1,slug:De.slug,attemptId:zr.attemptId,nonce:zr.nonce,...t});if(r)try{n.postMessage(r)}catch{}}function ty(t){fn()&&vs({type:"error",code:t})}function oR(t,e){zr=e,Vm=Date.now(),t[Zc]=r=>{iR(r)},vs({type:"ready",sdkVersion:T_,capabilities:["native-ticket","native-guest","heartbeat"]}),Ge=setTimeout(()=>{Do()},Io)}async function iR(t){if(!De||!zr)return;let e=Zd(t);if(!e.ok)return;let n=e.message;if(!(n.slug!==De.slug||n.attemptId!==zr.attemptId||n.nonce!==zr.nonce))switch(n.type){case"ticket":Ge!==void 0&&clearTimeout(Ge),await gf(n.ticket);return;case"guest":Ge!==void 0&&clearTimeout(Ge),await Do();return;case"cancel":ny(),nR();return;case"foreground":case"network":return}}function ny(){Ge!==void 0&&clearTimeout(Ge),Ge=void 0,Rn!==void 0&&clearTimeout(Rn),Rn=void 0,Ur!==void 0&&clearTimeout(Ur),Ur=void 0,Mo!==void 0&&clearInterval(Mo),Mo=void 0}function ry(){!fn()||Mo!==void 0||(Mo=setInterval(()=>{vs({type:"heartbeat",uptimeMs:Math.max(0,Date.now()-Vm)})},D_),Mo.unref?.())}function aR(){!fn()||To||(To=!0,vs({type:"reauth-required"}),Ur=setTimeout(()=>{Ur=void 0,To&&(To=!1,Qt("error",{error:new Error("embed session expired")}),mr("session-expired"))},I_))}function mf(){To=!1,Ur!==void 0&&clearTimeout(Ur),Ur=void 0}function yf(t,e){let n=Ze();if(!(!n||!Ft()))try{n.parent.postMessage(t,e)}catch{}}async function cR(t){let e=sy(t);if(e.ticket){Om(),await gf(e.ticket);return}if(e.guest){Om(),await Do();return}pu("redirecting"),await fu(t,{guestOk:!0})}function Om(){Ge!==void 0&&clearTimeout(Ge),Ge=setTimeout(()=>{Ge=void 0,Fe==="pending"&&mr("no-identity")},Io+M_)}var uu=null;function uR(t){return t.location.pathname+ru(t.location.search)}function sy(t){let e=uu??t.location.hash;uu=null;let{ticket:n,guest:r,entryHash:s}=Zm(e);if(n||r)try{t.history.replaceState(t.history.state??null,"",uR(t)+s)}catch{}return{ticket:n,guest:r}}async function fu(t,e){if(!De||Vr||fn())return;let n=e?.guestOk?De.dashboardOrigins[0]??(await af())[0]:(await af())[0]??De.dashboardOrigins[0];if(!n){mr();return}let r=t.location.origin+t.location.pathname,s=nf(ru(t.location.search));s.length-1<=1024&&r.length+s.length<=2048&&s.indexOf("#")===-1&&(r+=s);let o=e?.guestOk?"&guest=ok":"",i=`${n}/play/authorize?returnTo=${encodeURIComponent(r)}&slug=${encodeURIComponent(De.slug)}${o}`,a=Qm(t).referrer;a&&(i+=`&${Hd}=${encodeURIComponent(a)}`),i+=ou(t.location.hash),t.location.replace(i)}async function af(){if(!De)return[];try{let t=await na(`${De.apiUrl}/api/embed/dashboard-origins`);if(!t.ok)return De.dashboardOrigins;let e=await t.json();if(Array.isArray(e.origins)&&e.origins.every(n=>typeof n=="string"))return e.origins}catch{}return De.dashboardOrigins}async function gf(t){if(!De||Vr||As||Fe!=="pending"&&Fe!=="guest"&&!(To&&Fe==="authenticated"))return;let n=Fe==="guest",r=++Jt;As=!0;try{let s=await na(`${De.apiUrl}/api/embed/session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ticket:t})},Io);if(r!==Jt)return;if(!s.ok){Qt("error",{error:new Error(`ticket redemption failed (${s.status})`)}),n||await Im();return}let o=await s.json();if(r!==Jt)return;Lt=o.embedToken,Zt=o.user,ay(o.colyseus),Fe="authenticated",Ge!==void 0&&clearTimeout(Ge),Ge=void 0,ff(),hu(),xf(),wf(),Ft()&&Hr&&yf({type:"genex:embed:authenticated",v:ea},Hr),fn()&&(mf(),vs({type:"authenticated",guest:!1}),ry()),n&&await Z_();let i={user:Zt};for(let a of Gm.splice(0))a.resolve(i);for(let a of ta.splice(0))a.resolve({user:Zt,guest:!1});Qt("authenticated",i)}catch(s){if(r!==Jt)return;Qt("error",{error:s}),n||await Im()}finally{As=!1}}async function Do(){if(!De||Vr||Zi||As||Fe!=="pending"&&Fe!=="guest")return;let t=++Jt;Zi=!0;try{let e=await na(`${De.apiUrl}/api/embed/guest-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({slug:De.slug,playerId:j_()})},Io);if(t!==Jt)return;if(!e.ok){Qt("error",{error:new Error(`guest session failed (${e.status})`)}),ty("guest-failed"),mr(e.status===404?"not-available":"no-identity");return}let n=await e.json();if(t!==Jt)return;Lt=n.embedToken,Zt=n.user,ay(n.colyseus),lR()}catch(e){if(t!==Jt)return;Qt("error",{error:e}),mr()}finally{Zi=!1}}function lR(){let t=Fe!=="guest";if(Fe="guest",Ge!==void 0&&clearTimeout(Ge),hu(),wf(),Ft()?yf({type:"genex:embed:authenticated",v:ea,guest:!0},Hr??"*"):fn()?(vs({type:"authenticated",guest:!0}),ry()):t&&!H_()&&RR(),Zt){let e={user:Zt};for(let n of ta.splice(0))n.resolve({user:Zt,guest:!0});Qt("guest",e)}}function oy(t){try{let e=new URL(t.location.origin);return e.protocol==="http:"&&iy.has(e.hostname)}catch{return!1}}var iy=new Set(["localhost","127.0.0.1","[::1]"]),dR="genex_authority_url",fR="local:test",pR=64;function hR(t){if(!t||t.length>pR)return null;let e;try{e=new URL(t)}catch{return null}let n=!e.username&&!e.password&&e.pathname==="/"&&!e.search&&!e.hash;return e.protocol!=="ws:"||!iy.has(e.hostname)||!n?null:`ws://${e.host}`}function ay(t){Hm=t?.urls,lf=t?.authorityUrls,$m=t?.authorityRegions}function cy(t){if(Array.isArray(t))return t.filter(e=>typeof e=="string"&&e.length>0)}function mR(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(n===null||typeof n!="object")continue;let{region:r,urls:s}=n,o=cy(s)??[];typeof r=="string"&&r.length>0&&o.length>0&&e.push({region:r,urls:o})}return e}function bf(t,e=!0){if(Ft()||ey(t)||!oy(t))return!1;let n=null;try{n=new URLSearchParams(t.location.search)}catch{}return n?.get("genex_local_test")==="1"?!0:n?.get("genex_auth")==="1"?(e&&z_(),!1):F_()?!1:!yR(t)}function yR(t){let e=uu??t.location.hash;return!!e&&e.includes("genex_")}function gR(t){Vr=!0,sy(t),bR(t);let e={id:"local:test",name:"Local Tester"};Zt=e,Fe="guest",hu();try{console.info("[genex] local test mode \u2014 local visuals and controls only. Auth, saves, leaderboards, and multiplayer are NOT validated here; no Genex credential exists.")}catch{}for(let n of ta.splice(0))n.resolve({user:e,guest:!0});Qt("guest",{user:e})}function bR(t){if(!oy(t))return;let e=null;try{e=new URLSearchParams(t.location.search).get(dR)}catch{return}let n=hR(e);n&&(lf=[n],jm=!0)}async function Im(){let t=Ze();if(Ge!==void 0&&clearTimeout(Ge),Ge=void 0,fn()){mf(),ty("ticket-rejected"),mr();return}if(t&&!Ft()&&!N_()){L_(),pu("redirecting"),await fu(t,{guestOk:!0});return}mr()}function wf(){Rn!==void 0&&clearTimeout(Rn),Rn=setTimeout(()=>{uy()},C_)}async function uy(){if(!De||Fe!=="authenticated"&&Fe!=="guest"||!Lt)return;let t=Jt,e=Lt,n;try{let r=await na(`${De.apiUrl}/api/embed/session/refresh`,{method:"POST",headers:{Authorization:`Bearer ${e}`},keepalive:!0});if(n=r.status,t!==Jt||Lt!==e)return;if(r.ok){let s=await r.json();if(t!==Jt||Lt!==e)return;Lt=s.embedToken,wf();return}}catch{n=void 0}if(!(t!==Jt||Lt!==e)){if(n===401){if(Fe==="guest"){Do();return}if(fn()){aR();return}Qt("error",{error:new Error("embed session expired")}),mr("session-expired");return}Rn!==void 0&&clearTimeout(Rn),Rn=setTimeout(()=>{uy()},O_)}}function mr(t="no-identity"){if(Fe==="blocked")return;Jt++,Fe="blocked",Zt=null,Lt=void 0,Ge!==void 0&&clearTimeout(Ge),Rn!==void 0&&clearTimeout(Rn),xf(),fn()?(ny(),mf(),hu(),vs({type:"blocked",reason:t})):pu(Ft()?"blocked-embedded":"blocked-standalone"),Ft()&&yf({type:"genex:embed:blocked",v:ea},Hr??"*");let e=new Error("genex embed auth: blocked");for(let n of Gm.splice(0))n.reject(e);for(let n of ta.splice(0))n.reject(e);Qt("blocked")}var wR={connecting:{title:"GENEX",wordmark:!0},redirecting:{title:"GENEX",wordmark:!0},"blocked-standalone":{title:"Sign in to play",button:"Sign in",instant:!0},"blocked-embedded":{title:"Sign in on the Genex dashboard to continue",instant:!0}},xR="https://cdn.genex.technology/fonts/GeistMono-variable.woff2",ly="'Geist Mono',ui-monospace,SFMono-Regular,Menlo,monospace",Dm=!1,Bm="!<>-_/[]{}=+*^?#$%&@",dy=50,Nm=10,Lm=[{name:"churn",ticks:5},{name:"settle",ticks:10},{name:"hold",ticks:12},{name:"dissolve",ticks:8}];function cf(t){let e="";for(let n=0;n<t;n++)e+=Bm[Math.floor(Math.random()*Bm.length)];return e}function fy(){try{let t=Ze();return!t||typeof t.matchMedia!="function"?!0:t.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{return!0}}function SR(t,e){if(fy())return t.textContent=e,()=>{};let n=0;t.textContent=cf(e.length);let r=setInterval(()=>{if(n++,n>=Nm){t.textContent=e,clearInterval(r);return}let s=Math.floor(n/Nm*e.length);t.textContent=e.slice(0,s)+cf(e.length-s)},dy);return()=>clearInterval(r)}function ER(t,e){if(fy())return t.textContent=e,()=>{};let n=0,r=0,s=()=>{let i=Lm[n],a;i.name==="churn"?a=0:i.name==="settle"?a=Math.floor(r/i.ticks*e.length):i.name==="hold"?a=e.length:a=e.length-Math.floor(r/i.ticks*e.length),t.textContent=e.slice(0,a)+cf(e.length-a),r++,r>=i.ticks&&(r=0,n=(n+1)%Lm.length)};s();let o=setInterval(s,dy);return()=>clearInterval(o)}function py(t){if(!Dm){Dm=!0;try{let e=Ze()?.FontFace,n=t.fonts;if(!e||!n?.add)return;new e("Geist Mono",`url(${xR}) format('woff2')`,{weight:"100 900",display:"swap"}).load().then(s=>n.add(s)).catch(()=>{})}catch{}}}function pu(t){let e=df();if(e?.createElement)try{Qi||(Qi=_R(e)),Qi.setContent(t)}catch{}}function hu(t=!1){try{let e=Qi;if(Qi=null,!e)return;e.stopText();let n=e.root;if(t||!n.style){n.remove?.();return}n.style.pointerEvents="none",n.style.transition="opacity 180ms ease",n.style.opacity="0",setTimeout(()=>{try{n.remove?.()}catch{}},220)}catch{}}function _R(t){py(t);let e=t.createElement("div");e.setAttribute("data-genex-embed-overlay",""),e.style.cssText=`position:fixed;inset:0;z-index:2147483647;display:flex;align-items:center;justify-content:center;flex-direction:column;gap:14px;background:#000;color:#fff;font-family:${ly};text-align:center;pointer-events:auto;user-select:none`;let n=t.createElement("div");n.style.cssText="font-size:13px;font-weight:400;line-height:1.3;padding:0 24px;opacity:0;min-height:1.3em;font-variant-ligatures:none",e.appendChild(n);let r=t.createElement("button");r.style.cssText="font-family:inherit;font-size:13px;font-weight:500;line-height:1.3;padding:8px 22px;border-radius:9px;border:none;cursor:pointer;background:#4b60bf;color:#fff;display:none",r.addEventListener("mouseenter",()=>{r.style.background="#3f51a8"}),r.addEventListener("mouseleave",()=>{r.style.background="#4b60bf"}),r.addEventListener("click",()=>{let c=Ze();c&&(r.disabled=!0,ff(),fu(c))}),e.appendChild(r);let s=()=>{t.body&&!e.isConnected&&t.body.appendChild(e)};t.body?s():t.addEventListener?.("DOMContentLoaded",s);let o,i,a=()=>{o!==void 0&&(clearTimeout(o),o=void 0),i&&(i(),i=void 0)};return{root:e,stopText:a,setContent(c){let u=wR[c];a(),n.textContent=u.title,n.style.letterSpacing=u.wordmark?"0.22em":"",n.style.marginRight=u.wordmark?"-0.22em":"";let l=()=>{n.style.opacity="1",i=u.wordmark?ER(n,u.title):SR(n,u.title)};u.instant||Pm<=0?l():(n.style.opacity="0",o=setTimeout(()=>{o=void 0,l()},Pm)),r.style.display=u.button?"inline-block":"none",u.button&&(r.textContent=u.button),s()}}}function RR(){let t=df();if(!(!t?.createElement||au))try{au=kR(t)}catch{}}function xf(){Ps!==void 0&&(clearTimeout(Ps),Ps=void 0);try{au?.root?.remove?.()}catch{}au=null}function kR(t){py(t);let e=!1;try{let c=Ze(),u=c?.navigator;if(c&&u){let l=c.matchMedia?.("(pointer: coarse)").matches??!1,d=(u.maxTouchPoints??0)>1,f=u.userAgentData?u.userAgentData.mobile:/Mobi|Android/i.test(u.userAgent??"");e=d&&l||f}}catch{}let n=t.createElement("div");n.setAttribute("data-genex-guest-popover",""),n.style.cssText="position:fixed;top:calc(12px + env(safe-area-inset-top));right:calc(12px + env(safe-area-inset-right));z-index:2147483646;display:flex;justify-content:flex-end;pointer-events:none";let r=t.createElement("div");r.style.cssText=`display:flex;align-items:center;border-radius:12px;background:rgba(0,0,0,0.85);color:#fff;font-family:${ly};box-shadow:0 4px 24px rgba(0,0,0,0.4);pointer-events:auto;user-select:none;`+(e?"gap:8px;padding:8px 8px 8px 12px;font-size:12px;max-width:calc(100vw - 88px)":"gap:12px;padding:10px 12px 10px 16px;font-size:13px"),n.appendChild(r);let s=t.createElement("span");s.textContent=!e&&Zt?.name?`Playing as ${Zt.name} \u2014 sign in to save progress`:"Sign in to save progress",e&&(s.style.cssText="overflow:hidden;text-overflow:ellipsis;white-space:nowrap"),r.appendChild(s);let o=t.createElement("button");o.textContent="Sign in",o.style.cssText="font-family:inherit;font-weight:500;border-radius:9px;border:none;cursor:pointer;background:#4b60bf;color:#fff;"+(e?"font-size:12px;padding:5px 12px":"font-size:13px;padding:6px 16px"),o.addEventListener("mouseenter",()=>{o.style.background="#3f51a8"}),o.addEventListener("mouseleave",()=>{o.style.background="#4b60bf"}),o.addEventListener("click",()=>{let c=Ze();c&&(o.disabled=!0,ff(),fu(c))}),r.appendChild(o);let i=t.createElement("button");if(i.textContent="\xD7",i.setAttribute("aria-label","Dismiss"),i.style.cssText="font-size:16px;line-height:1;padding:6px 8px;border:none;cursor:pointer;background:transparent;color:rgba(255,255,255,0.6)",i.addEventListener("click",()=>{$_(),xf()}),r.appendChild(i),e){let c=t.createElement("button");c.setAttribute("aria-label","Sign in to save progress"),c.style.cssText="display:none;width:44px;height:44px;border-radius:50%;border:none;cursor:pointer;background:rgba(0,0,0,0.55);color:#fff;align-items:center;justify-content:center;-webkit-backdrop-filter:blur(4px);backdrop-filter:blur(4px);pointer-events:auto",c.innerHTML='<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"/><polyline points="10 17 15 12 10 7"/><line x1="15" y1="12" x2="3" y2="12"/></svg>',n.appendChild(c);let u=l=>{r.style.display=l?"none":"flex",c.style.display=l?"flex":"none"};Ps=setTimeout(()=>u(!0),5e3),r.addEventListener("pointerdown",()=>{Ps!==void 0&&clearTimeout(Ps),Ps=void 0}),c.addEventListener("click",()=>u(!1))}let a=()=>{t.body&&!n.isConnected&&t.body.appendChild(n)};return t.body?a():t.addEventListener?.("DOMContentLoaded",a),{root:n}}Em({getShell:q_,isLocalTest:()=>{let t=Ze();return!t||Ft()?!1:Oo?Vr:bf(t,!1)},getConfig:()=>De,getParentOrigin:()=>Hr,getShellCaps:()=>qm});var Bp={};Fd(Bp,{chatSend:()=>QA,claim:()=>ev,claimAsHost:()=>tv,connect:()=>HA,destroy:()=>rv,dispose:()=>$A,drainEventsJson:()=>pv,leave:()=>T0,listen:()=>XA,objectsJson:()=>dv,open:()=>VA,playersJson:()=>lv,release:()=>nv,reportEliminated:()=>sv,reportFinish:()=>iv,reportScore:()=>ov,send:()=>KA,sendInput:()=>JA,serverNow:()=>av,sessionJson:()=>uv,setIdentity:()=>LA,setMe:()=>jA,setObject:()=>WA,setRoomOpen:()=>ZA,setShared:()=>GA,sharedJson:()=>fv,snapMe:()=>qA,snapObject:()=>YA,timeUntil:()=>cv,version:()=>NA});var ra={ready(t){let e=globalThis.__GENEX__;return t&&e&&typeof e.apiUrl=="string"&&Array.isArray(e.dashboardOrigins)&&lu({slug:t,apiUrl:e.apiUrl,dashboardOrigins:e.dashboardOrigins.filter(n=>typeof n=="string")}),pf()},auth:()=>du(),urls:()=>Wm()},PR=4096;function pe(t,e){t.q.length>=PR&&(t.overflowed?t.q.splice(1,1):(t.overflowed=!0,t.q.splice(0,2,{type:"warning",message:"genex bridge: event queue full; drain it every frame (oldest events dropped)"}))),t.q.push(e)}var Bo=t=>({type:"warning",message:`genex bridge: ${t}`});function AR(t){try{return JSON.stringify(t)}catch(e){let n=typeof t.kind=="string"?t.kind:t.type;return JSON.stringify(Bo(`event ${JSON.stringify(n)} dropped: JSON cannot carry it (${Gn(e)})`))}}function mu(t){return t.overflowed=!1,`[${t.q.splice(0).map(AR).join(",")}]`}var kn=t=>!!t&&typeof t=="object"&&!Array.isArray(t),No=t=>{let e=kn(t)||t instanceof Error?t.code:void 0;return typeof e=="number"&&Number.isFinite(e)?e:0},Gn=t=>t instanceof Error?t.message:typeof t=="string"?t:"join failed";function sa(t,e){if(typeof t!="string")throw new TypeError(`genex bridge: ${e} must be a JSON string`);return JSON.parse(t)}function Wn(t,e){let n=sa(t,e);if(!kn(n))throw new TypeError(`genex bridge: ${e} must be a JSON object`);return n}ArrayBuffer.isView||(ArrayBuffer.isView=t=>t!==null&&typeof t=="object"&&t.buffer instanceof ArrayBuffer);typeof globalThis>"u"&&typeof window<"u"&&(window.globalThis=window);typeof FormData>"u"&&(globalThis.FormData=class{});yr();var Yn=class extends Error{constructor(n,r,s){super(r);m(this,"code");m(this,"headers");m(this,"status");m(this,"response");m(this,"data");this.name="ServerError",this.code=n,s&&(this.headers=s.headers,this.status=s.status,this.response=s.response,this.data=s.data)}};var oa=class t extends Error{constructor(n,r){super(n);m(this,"code");this.code=r,this.name="MatchMakeError",Object.setPrototypeOf(this,t.prototype)}};yr();wt();wt();wt();wt();wt();wt();wt();wt();var Ug=256,qf=5,Ls=class Ls{constructor(e,n={}){m(this,"instance");m(this,"mode");m(this,"historySize");m(this,"_desc");m(this,"_numFields");m(this,"_slots");m(this,"_slotLens");m(this,"_slotHead",0);m(this,"_slotCount",0);m(this,"_outBuffer");m(this,"_seq",0);m(this,"_encoder");this.instance=e,this.mode=n.mode??"reliable",this.historySize=this.mode==="unreliable"?Math.max(1,n.historySize??3):1,this._desc=Lf(e);let r=this._desc.metadata?.[bt];if(r===void 0)throw new Error(`InputEncoder: '${e.constructor.name}' has no fields`);this._numFields=r;for(let s=0;s<=r;s++)if(this._desc.names[s]!==void 0&&this._desc.encoders[s]===void 0)throw new Error(`InputEncoder: non-primitive field '${this._desc.names[s]}' on '${e.constructor.name}' is not supported. Use Encoder for state containing refs/collections.`);if(this.mode==="unreliable"){this._slots=new Array(this.historySize),this._slotLens=new Array(this.historySize).fill(0);for(let s=0;s<this.historySize;s++)this._slots[s]=new Uint8Array(Ug);this._outBuffer=new Uint8Array((Ug+qf)*this.historySize)}this._encoder=new ha(e)}get seq(){return this._seq}encode(){let e=this._produceDelta();return this.mode==="reliable"?e:this._pushAndEmitRing(e)}reset(){this._slotHead=0,this._slotCount=0,this._encoder.discardChanges();let e=this.instance[I],n=this.instance[kt];for(let r=0;r<=this._numFields;r++)n[r]===void 0||n[r]===null||e.markDirty(r)}copyInto(e){let n=this.instance[kt],r=e[kt];for(let s=0;s<=this._numFields;s++)r[s]=n[s]}_produceDelta(){let e=this._encoder.encode();return this._encoder.discardChanges(),e}_pushAndEmitRing(e){this._seq++;let n=this._slots[this._slotHead];return e.length>n.byteLength&&(n=this._slots[this._slotHead]=Ls._grow(n,e.length,"unreliable ring slot")),n.set(e),this._slotLens[this._slotHead]=e.length,this._slotHead=(this._slotHead+1)%this.historySize,this._slotCount<this.historySize&&this._slotCount++,this._emitRing()}_emitRing(){let e=this._seq-this._slotCount+1,n=qf;for(let i=0;i<this._slotCount;i++)n+=this._slotLens[i]+qf;let r=this._outBuffer;n>r.byteLength&&(r=this._outBuffer=Ls._grow(r,n,"unreliable output packet"));let s={offset:0};be.number(r,e,s);let o=(this._slotHead-this._slotCount+this.historySize)%this.historySize;for(let i=0;i<this._slotCount;i++){let a=(o+i)%this.historySize,c=this._slotLens[a];be.number(r,c,s),r.set(this._slots[a].subarray(0,c),s.offset),s.offset+=c}return r.subarray(0,s.offset)}static _grow(e,n,r){let s=Math.max(n,e.byteLength*2);return Ls._warned||(Ls._warned=!0,console.warn(`@colyseus/schema/input: InputEncoder buffer overflow in ${r}. Growing to ${s} bytes.`)),new Uint8Array(s)}};m(Ls,"_warned",!1);var $u=Ls;yr();Wf();Yu();var Fs,Bn,Go,Ra,ka,Pa,Aa,va,Ta,Wo,Ma,Ku,jg,Yo=class{constructor(e){ze(this,Ku);ze(this,Fs);ze(this,Bn);ze(this,Go);ze(this,Ra);ze(this,ka,!1);ze(this,Pa);ze(this,Aa,!1);ze(this,va,!1);ze(this,Ta);ze(this,Wo);ze(this,Ma);Ue(this,Fs,e)}get patchRate(){return ae(this,Wo)}applyReflection(e,n,r){let s=Dn.decode(e.subarray(0,r),n);Dn.makeEncodable(s.state.constructor),Ue(this,Pa,s.state.constructor),ae(this,Fs).clock===qo&&(ae(this,Fs).clock=new Wu)}applyOptions(e,n){let r=e[n.offset++];Ue(this,Aa,(r&Ts.RENDER_TIME)!==0),Ue(this,va,(r&Ts.RECKON_TIME)!==0),r&Ts.FIXED_TIMESTEP&&Ue(this,Ta,Re.number(e,n)),r&Ts.PATCH_RATE&&Ue(this,Wo,Re.number(e,n)),r&Ts.SUB_STEPS&&Ue(this,Ma,Re.number(e,n))}ackInput(e){return ae(this,Bn)?ae(this,Bn).ackInput(e):-1}reset(){ae(this,Bn)?.reset()}handle(e){if(ae(this,Bn))return e!==void 0&&ks(this,Ku,jg).call(this,e),ae(this,Bn);let n=e?.type??ae(this,Pa);if(!n)throw new Error("room.input(): no input schema available. The server room must call `defineInput(YourInput)`, or you can pass `{ type: YourInput }` explicitly.");let r=new n,s=new $u(r,e);return Ue(this,Bn,new jo(ae(this,Fs),r,s,{stampRender:ae(this,Aa),stampReckon:ae(this,va),renderDelay:e?.renderDelay,allowRewind:e?.allowRewind,tickRate:ae(this,Ta),patchRate:ae(this,Wo),subSteps:ae(this,Ma)})),Ue(this,Go,e),Ue(this,Ra,s),ae(this,Bn)}};Fs=new WeakMap,Bn=new WeakMap,Go=new WeakMap,Ra=new WeakMap,ka=new WeakMap,Pa=new WeakMap,Aa=new WeakMap,va=new WeakMap,Ta=new WeakMap,Wo=new WeakMap,Ma=new WeakMap,Ku=new WeakSet,jg=function(e){if(ae(this,ka))return;let n=ae(this,Bn),r=[];e.type!==void 0&&e.type!==n.data?.constructor&&r.push("type"),e.mode!==void 0&&e.mode!==n.mode&&r.push("mode"),e.historySize!==void 0&&n.mode==="unreliable"&&e.historySize!==ae(this,Ra).historySize&&r.push("historySize"),e.renderDelay!==void 0&&e.renderDelay!==ae(this,Go)?.renderDelay&&r.push("renderDelay"),e.allowRewind!==void 0!=(ae(this,Go)?.allowRewind!==void 0)&&r.push("allowRewind"),r.length!==0&&(Ue(this,ka,!0),console.warn(`@colyseus/sdk: room.input() options ignored \u2014 the input handle was already created by an earlier call (first call wins). Differing: ${r.join(", ")}.`))};var Kf;try{Kf=new TextDecoder}catch{}var J,hn,C=0;var tb=[],Xf=tb,Jf=0,Be={},ve,Xr,pn=0,nr=0,ht,_r,Vt=[],Ae,qg={useRecords:!1,mapsAsObjects:!0},Ca=class{},Qf=new Ca;Qf.name="MessagePack 0xC1";var Jr=!1,Gg=2;var Zr=class t{constructor(e){e&&(e.useRecords===!1&&e.mapsAsObjects===void 0&&(e.mapsAsObjects=!0),e.sequential&&e.trusted!==!1&&(e.trusted=!0,!e.structures&&e.useRecords!=!1&&(e.structures=[],e.maxSharedStructures||(e.maxSharedStructures=0))),e.structures?e.structures.sharedLength=e.structures.length:e.getStructures&&((e.structures=[]).uninitialized=!0,e.structures.sharedLength=0),e.int64AsNumber&&(e.int64AsType="number")),Object.assign(this,e)}unpack(e,n){if(J)return ib(()=>(Ju(),this?this.unpack(e,n):t.prototype.unpack.call(qg,e,n)));!e.buffer&&e.constructor===ArrayBuffer&&(e=typeof Buffer<"u"?Buffer.from(e):new Uint8Array(e)),typeof n=="object"?(hn=n.end||e.length,C=n.start||0):(C=0,hn=n>-1?n:e.length),Jf=0,nr=0,Xr=null,Xf=tb,ht=null,J=e;try{Ae=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))}catch(r){throw J=null,e instanceof Uint8Array?r:new Error("Source must be a Uint8Array or Buffer but was a "+(e&&typeof e=="object"?e.constructor.name:typeof e))}if(this instanceof t){if(Be=this,this.structures)return ve=this.structures,Xu(n);(!ve||ve.length>0)&&(ve=[])}else Be=qg,(!ve||ve.length>0)&&(ve=[]);return Xu(n)}unpackMultiple(e,n){let r,s=0;try{Jr=!0;let o=e.length,i=this?this.unpack(e,o):Qu.unpack(e,o);if(n){if(n(i,s,C)===!1)return;for(;C<o;)if(s=C,n(Xu(),s,C)===!1)return}else{for(r=[i];C<o;)s=C,r.push(Xu());return r}}catch(o){throw o.lastPosition=s,o.values=r,o}finally{Jr=!1,Ju()}}_mergeStructures(e,n){this._onLoadedStructures&&(e=this._onLoadedStructures(e)),e=e||[],Object.isFrozen(e)&&(e=e.map(r=>r.slice(0)));for(let r=0,s=e.length;r<s;r++){let o=e[r];o&&(o.isShared=!0,r>=32&&(o.highByte=r-32>>5))}e.sharedLength=e.length;for(let r in n||[])if(r>=0){let s=e[r],o=n[r];o&&(s&&((e.restoreStructures||(e.restoreStructures=[]))[r]=s),e[r]=o)}return this.structures=e}decode(e,n){return this.unpack(e,n)}};function Xu(t){try{if(!Be.trusted&&!Jr){let n=ve.sharedLength||0;n<ve.length&&(ve.length=n)}let e;if(Be._readStruct&&J[C]<64&&J[C]>=32?(e=Be._readStruct(J,C,hn),J=null,!(t&&t.lazy)&&e&&(e=e.toJSON()),C=hn):e=et(),ht&&(C=ht.postBundlePosition,ht=null),Jr&&(ve.restoreStructures=null),C==hn)ve&&ve.restoreStructures&&Wg(),ve=null,J=null,_r&&(_r=null);else{if(C>hn)throw new Error("Unexpected end of MessagePack data");if(!Jr){let n;try{n=JSON.stringify(e,(r,s)=>typeof s=="bigint"?`${s}n`:s).slice(0,100)}catch(r){n="(JSON view not available "+r+")"}throw new Error("Data read, but end of buffer not reached "+n)}}return e}catch(e){throw ve&&ve.restoreStructures&&Wg(),Ju(),(e instanceof RangeError||e.message.startsWith("Unexpected end of buffer")||C>hn)&&(e.incomplete=!0),e}}function Wg(){for(let t in ve.restoreStructures)ve[t]=ve.restoreStructures[t];ve.restoreStructures=null}function et(){let t=J[C++];if(t<160)if(t<128){if(t<64)return t;{let e=ve[t&63]||Be.getStructures&&nb()[t&63];return e?(e.read||(e.read=ep(e,t&63)),e.read()):t}}else if(t<144)if(t-=128,Be.mapsAsObjects){let e={};for(let n=0;n<t;n++){let r=sb();r==="__proto__"&&(r="__proto_"),e[r]=et()}return e}else{let e=new Map;for(let n=0;n<t;n++)e.set(et(),et());return e}else{t-=144;let e=new Array(t);for(let n=0;n<t;n++)e[n]=et();return Be.freezeData?Object.freeze(e):e}else if(t<192){let e=t-160;if(nr>=C)return Xr.slice(C-pn,(C+=e)-pn);if(nr==0&&hn<140){let n=e<16?tp(e):rb(e);if(n!=null)return n}return Zf(e)}else{let e;switch(t){case 192:return null;case 193:return ht?(e=et(),e>0?ht[1].slice(ht.position1,ht.position1+=e):ht[0].slice(ht.position0,ht.position0-=e)):Qf;case 194:return!1;case 195:return!0;case 196:if(e=J[C++],e===void 0)throw new Error("Unexpected end of buffer");return Yf(e);case 197:return e=Ae.getUint16(C),C+=2,Yf(e);case 198:return e=Ae.getUint32(C),C+=4,Yf(e);case 199:return zs(J[C++]);case 200:return e=Ae.getUint16(C),C+=2,zs(e);case 201:return e=Ae.getUint32(C),C+=4,zs(e);case 202:if(e=Ae.getFloat32(C),Be.useFloat32>2){let n=Zu[(J[C]&127)<<1|J[C+1]>>7];return C+=4,(n*e+(e>0?.5:-.5)>>0)/n}return C+=4,e;case 203:return e=Ae.getFloat64(C),C+=8,e;case 204:return J[C++];case 205:return e=Ae.getUint16(C),C+=2,e;case 206:return e=Ae.getUint32(C),C+=4,e;case 207:return Be.int64AsType==="number"?(e=Ae.getUint32(C)*4294967296,e+=Ae.getUint32(C+4)):Be.int64AsType==="string"?e=Ae.getBigUint64(C).toString():Be.int64AsType==="auto"?(e=Ae.getBigUint64(C),e<=BigInt(2)<<BigInt(52)&&(e=Number(e))):e=Ae.getBigUint64(C),C+=8,e;case 208:return Ae.getInt8(C++);case 209:return e=Ae.getInt16(C),C+=2,e;case 210:return e=Ae.getInt32(C),C+=4,e;case 211:return Be.int64AsType==="number"?(e=Ae.getInt32(C)*4294967296,e+=Ae.getUint32(C+4)):Be.int64AsType==="string"?e=Ae.getBigInt64(C).toString():Be.int64AsType==="auto"?(e=Ae.getBigInt64(C),e>=BigInt(-2)<<BigInt(52)&&e<=BigInt(2)<<BigInt(52)&&(e=Number(e))):e=Ae.getBigInt64(C),C+=8,e;case 212:if(e=J[C++],e==114)return Qg(J[C++]&63);{let n=Vt[e];if(n)return n.read?(C++,n.read(et())):n.noBuffer?(C++,n()):n(J.subarray(C,++C));throw new Error("Unknown extension "+e)}case 213:return e=J[C],e==114?(C++,Qg(J[C++]&63,J[C++])):zs(2);case 214:return zs(4);case 215:return zs(8);case 216:return zs(16);case 217:return e=J[C++],nr>=C?Xr.slice(C-pn,(C+=e)-pn):gP(e);case 218:return e=Ae.getUint16(C),C+=2,nr>=C?Xr.slice(C-pn,(C+=e)-pn):bP(e);case 219:return e=Ae.getUint32(C),C+=4,nr>=C?Xr.slice(C-pn,(C+=e)-pn):wP(e);case 220:return e=Ae.getUint16(C),C+=2,Kg(e);case 221:return e=Ae.getUint32(C),C+=4,Kg(e);case 222:return e=Ae.getUint16(C),C+=2,Xg(e);case 223:return e=Ae.getUint32(C),C+=4,Xg(e);default:if(t>=224)return t-256;if(t===void 0){let n=new Error("Unexpected end of MessagePack data");throw n.incomplete=!0,n}throw new Error("Unknown MessagePack token "+t)}}}var yP=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function ep(t,e){function n(){if(n.count++>Gg){let s;try{s=t.read=new Function("r","return function(){return "+(Be.freezeData?"Object.freeze":"")+"({"+t.map(o=>o==="__proto__"?"__proto_:r()":yP.test(o)?o+":r()":"["+JSON.stringify(o)+"]:r()").join(",")+"})}")(et)}catch{return Gg=1/0,n()}return t.read0=s,t.highByte===0&&(t.read=Yg(e,t.read)),s()}let r={};for(let s=0,o=t.length;s<o;s++){let i=t[s];i==="__proto__"&&(i="__proto_"),r[i]=et()}return Be.freezeData?Object.freeze(r):r}return n.count=0,t.read0=n,t.highByte===0?Yg(e,n):n}var Yg=(t,e)=>function(){let n=J[C++];if(n===0)return e();let r=t<32?-(t+(n<<5)):t+(n<<5),s=ve[r]||nb()[r];if(!s)throw new Error("Record id is not defined for "+r);return s.read||(s.read=ep(s,t)),s.read()};function nb(){let t=ib(()=>(J=null,Be.getStructures()));return ve=Be._mergeStructures(t,ve)}var Zf=Oa,gP=Oa,bP=Oa,wP=Oa;function Oa(t){let e;if(t<16&&(e=tp(t)))return e;if(t>64&&Kf)return Kf.decode(J.subarray(C,C+=t));let n=C+t,r=[];for(e="";C<n;){let s=J[C++];if((s&128)===0)r.push(s);else if((s&224)===192){let o=J[C++]&63,i=(s&31)<<6|o;i<128?r.push(65533):r.push(i)}else if((s&240)===224){let o=J[C++]&63,i=J[C++]&63,a=(s&31)<<12|o<<6|i;a<2048||a>=55296&&a<=57343?r.push(65533):r.push(a)}else if((s&248)===240){let o=J[C++]&63,i=J[C++]&63,a=J[C++]&63,c=(s&7)<<18|o<<12|i<<6|a;c<65536||c>1114111?r.push(65533):(c>65535&&(c-=65536,r.push(c>>>10&1023|55296),c=56320|c&1023),r.push(c))}else r.push(65533);r.length>=4096&&(e+=pt.apply(String,r),r.length=0)}return r.length>0&&(e+=pt.apply(String,r)),e}function Kg(t){let e=new Array(t);for(let n=0;n<t;n++)e[n]=et();return Be.freezeData?Object.freeze(e):e}function Xg(t){if(Be.mapsAsObjects){let e={};for(let n=0;n<t;n++){let r=sb();r==="__proto__"&&(r="__proto_"),e[r]=et()}return e}else{let e=new Map;for(let n=0;n<t;n++)e.set(et(),et());return e}}var pt=String.fromCharCode;function rb(t){let e=C,n=new Array(t);for(let r=0;r<t;r++){let s=J[C++];if((s&128)>0){C=e;return}n[r]=s}return pt.apply(String,n)}function tp(t){if(t<4)if(t<2){if(t===0)return"";{let e=J[C++];if((e&128)>1){C-=1;return}return pt(e)}}else{let e=J[C++],n=J[C++];if((e&128)>0||(n&128)>0){C-=2;return}if(t<3)return pt(e,n);let r=J[C++];if((r&128)>0){C-=3;return}return pt(e,n,r)}else{let e=J[C++],n=J[C++],r=J[C++],s=J[C++];if((e&128)>0||(n&128)>0||(r&128)>0||(s&128)>0){C-=4;return}if(t<6){if(t===4)return pt(e,n,r,s);{let o=J[C++];if((o&128)>0){C-=5;return}return pt(e,n,r,s,o)}}else if(t<8){let o=J[C++],i=J[C++];if((o&128)>0||(i&128)>0){C-=6;return}if(t<7)return pt(e,n,r,s,o,i);let a=J[C++];if((a&128)>0){C-=7;return}return pt(e,n,r,s,o,i,a)}else{let o=J[C++],i=J[C++],a=J[C++],c=J[C++];if((o&128)>0||(i&128)>0||(a&128)>0||(c&128)>0){C-=8;return}if(t<10){if(t===8)return pt(e,n,r,s,o,i,a,c);{let u=J[C++];if((u&128)>0){C-=9;return}return pt(e,n,r,s,o,i,a,c,u)}}else if(t<12){let u=J[C++],l=J[C++];if((u&128)>0||(l&128)>0){C-=10;return}if(t<11)return pt(e,n,r,s,o,i,a,c,u,l);let d=J[C++];if((d&128)>0){C-=11;return}return pt(e,n,r,s,o,i,a,c,u,l,d)}else{let u=J[C++],l=J[C++],d=J[C++],f=J[C++];if((u&128)>0||(l&128)>0||(d&128)>0||(f&128)>0){C-=12;return}if(t<14){if(t===12)return pt(e,n,r,s,o,i,a,c,u,l,d,f);{let h=J[C++];if((h&128)>0){C-=13;return}return pt(e,n,r,s,o,i,a,c,u,l,d,f,h)}}else{let h=J[C++],p=J[C++];if((h&128)>0||(p&128)>0){C-=14;return}if(t<15)return pt(e,n,r,s,o,i,a,c,u,l,d,f,h,p);let g=J[C++];if((g&128)>0){C-=15;return}return pt(e,n,r,s,o,i,a,c,u,l,d,f,h,p,g)}}}}}function Jg(){let t=J[C++],e;if(t<192)e=t-160;else switch(t){case 217:e=J[C++];break;case 218:e=Ae.getUint16(C),C+=2;break;case 219:e=Ae.getUint32(C),C+=4;break;default:throw new Error("Expected string")}return Oa(e)}function Yf(t){return Be.copyBuffers?Uint8Array.prototype.slice.call(J,C,C+=t):J.subarray(C,C+=t)}function zs(t){let e=J[C++];if(Vt[e]){let n;return Vt[e](J.subarray(C,n=C+=t),r=>{C=r;try{return et()}finally{C=n}})}else throw new Error("Unknown extension type "+e)}var Zg=new Array(4096);function sb(){let t=J[C++];if(t>=160&&t<192){if(t=t-160,nr>=C)return Xr.slice(C-pn,(C+=t)-pn);if(!(nr==0&&hn<180))return Zf(t)}else return C--,ob(et());let e=(t<<5^(t>1?Ae.getUint16(C):t>0?J[C]:0))&4095,n=Zg[e],r=C,s=C+t-3,o,i=0;if(n&&n.bytes==t){for(;r<s;){if(o=Ae.getUint32(r),o!=n[i++]){r=1879048192;break}r+=4}for(s+=3;r<s;)if(o=J[r++],o!=n[i++]){r=1879048192;break}if(r===s)return C=r,n.string;s-=3,r=C}for(n=[],Zg[e]=n,n.bytes=t;r<s;)o=Ae.getUint32(r),n.push(o),r+=4;for(s+=3;r<s;)o=J[r++],n.push(o);let a=t<16?tp(t):rb(t);return a!=null?n.string=a:n.string=Zf(t)}function ob(t){if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return t.toString();if(t==null)return t+"";if(Be.allowArraysInMapKeys&&Array.isArray(t)&&t.flat().every(e=>["string","number","boolean","bigint"].includes(typeof e)))return t.flat().toString();throw new Error(`Invalid property type for record: ${typeof t}`)}var Qg=(t,e)=>{let n=et().map(ob),r=t;e!==void 0&&(t=t<32?-((e<<5)+t):(e<<5)+t,n.highByte=e);let s=ve[t];return s&&(s.isShared||Jr)&&((ve.restoreStructures||(ve.restoreStructures=[]))[t]=s),ve[t]=n,n.read=ep(n,r),(n.read0||n.read)()};Vt[0]=()=>{};Vt[0].noBuffer=!0;Vt[66]=t=>{let e=t.byteLength%8||8,n=BigInt(t[0]&128?t[0]-256:t[0]);for(let r=1;r<e;r++)n<<=BigInt(8),n+=BigInt(t[r]);if(t.byteLength!==e){let r=new DataView(t.buffer,t.byteOffset,t.byteLength),s=(o,i)=>{let a=i-o;if(a<=40){let d=r.getBigUint64(o);for(let f=o+8;f<i;f+=8)d<<=BigInt(64),d|=r.getBigUint64(f);return d}let c=o+(a>>4<<3),u=s(o,c),l=s(c,i);return u<<BigInt((i-c)*8)|l};n=n<<BigInt((r.byteLength-e)*8)|s(e,r.byteLength)}return n};var eb={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError:typeof AggregateError=="function"?AggregateError:null};Vt[101]=()=>{let t=et();if(!eb[t[0]]){let e=Error(t[1],{cause:t[2]});return e.name=t[0],e}return eb[t[0]](t[1],{cause:t[2]})};Vt[105]=t=>{if(Be.structuredClone===!1)throw new Error("Structured clone extension is disabled");let e=Ae.getUint32(C-4);_r||(_r=new Map);let n=J[C],r;n>=144&&n<160||n==220||n==221?r=[]:n>=128&&n<144||n==222||n==223?r=new Map:(n>=199&&n<=201||n>=212&&n<=216)&&J[C+1]===115?r=new Set:r={};let s={target:r};_r.set(e,s);let o=et();if(s.used)Object.assign(r,o);else return s.target=o;if(r instanceof Map)for(let[i,a]of o.entries())r.set(i,a);if(r instanceof Set)for(let i of Array.from(o))r.add(i);return r};Vt[112]=t=>{if(Be.structuredClone===!1)throw new Error("Structured clone extension is disabled");let e=Ae.getUint32(C-4),n=_r.get(e);return n.used=!0,n.target};Vt[115]=()=>new Set(et());var np=["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64","BigInt64","BigUint64"].map(t=>t+"Array"),xP=typeof globalThis=="object"?globalThis:window;Vt[116]=t=>{let e=t[0],n=Uint8Array.prototype.slice.call(t,1).buffer,r=np[e];if(!r){if(e===16)return n;if(e===17)return new DataView(n);throw new Error("Could not find typed array for code "+e)}return new xP[r](n)};Vt[120]=()=>{let t=et();return new RegExp(t[0],t[1])};var SP=[];Vt[98]=t=>{let e=(t[0]<<24)+(t[1]<<16)+(t[2]<<8)+t[3],n=C;return C+=e-t.length,ht=SP,ht=[Jg(),Jg()],ht.position0=0,ht.position1=0,ht.postBundlePosition=C,C=n,et()};Vt[255]=t=>t.length==4?new Date((t[0]*16777216+(t[1]<<16)+(t[2]<<8)+t[3])*1e3):t.length==8?new Date(((t[0]<<22)+(t[1]<<14)+(t[2]<<6)+(t[3]>>2))/1e6+((t[3]&3)*4294967296+t[4]*16777216+(t[5]<<16)+(t[6]<<8)+t[7])*1e3):t.length==12?new Date(((t[0]<<24)+(t[1]<<16)+(t[2]<<8)+t[3])/1e6+((t[4]&128?-281474976710656:0)+t[6]*1099511627776+t[7]*4294967296+t[8]*16777216+(t[9]<<16)+(t[10]<<8)+t[11])*1e3):new Date("invalid");function ib(t){Be&&Be._onSaveState&&Be._onSaveState();let e=hn,n=C,r=Jf,s=pn,o=nr,i=Xr,a=Xf,c=_r,u=ht,l=new Uint8Array(J.slice(0,hn)),d=ve,f=ve.slice(0,ve.length),h=Be,p=Jr,g=t();return hn=e,C=n,Jf=r,pn=s,nr=o,Xr=i,Xf=a,_r=c,ht=u,J=l,Jr=p,ve=d,ve.splice(0,ve.length,...f),Be=h,Ae=new DataView(J.buffer,J.byteOffset,J.byteLength),g}function Ju(){J=null,_r=null,ve=null}var Zu=new Array(147);for(let t=0;t<256;t++)Zu[t]=+("1e"+Math.floor(45.15-t*.30103));var Qu=new Zr({useRecords:!1}),el=Qu.unpack,EP=Qu.unpackMultiple,_P=Qu.unpack,tl={NEVER:0,ALWAYS:1,DECIMAL_ROUND:3,DECIMAL_FIT:4},RP=new Float32Array(1),bB=new Uint8Array(RP.buffer,0,4);Zr.SUPPORTS_STRUCT_HOOKS=!0;var rl;try{rl=new TextEncoder}catch{}var op,ip,Xo=typeof Buffer<"u",nl=Xo?function(t){return Buffer.allocUnsafeSlow(t)}:Uint8Array,lb=Xo?Buffer:Uint8Array,ab=Xo?4294967296:2144337920,L,Ia,Ve,D=0,At,Xe=null,kP=21760,PP=/[\u0080-\uFFFF]/,Ko=Symbol("record-id"),Qr=class extends Zr{constructor(e){super(e),this.offset=0;let n,r,s,o,i,a=lb.prototype.utf8Write?function(A,W){return L.utf8Write(A,W,L.byteLength-W)}:rl&&rl.encodeInto?function(A,W){return rl.encodeInto(A,L.subarray(W)).written}:!1,c=this;e||(e={});let u=e&&e.sequential,l=e.structures||e.saveStructures,d=e.maxSharedStructures;if(d==null&&(d=l?32:0),d>8160)throw new Error("Maximum maxSharedStructure is 8160");e.structuredClone&&e.moreTypes==null&&(this.moreTypes=!0);let f=e.maxOwnStructures;f==null&&(f=l?32:64),!this.structures&&e.useRecords!=!1&&(this.structures=[]);let h=d>32||f+d>64,p=d+64,g=d+f+64;if(g>8256)throw new Error("Maximum maxSharedStructure + maxOwnStructure is 8192");let x=[],b=0,S=0;this.pack=this.encode=function(A,W){if(L||(L=new nl(8192),Ve=L.dataView||(L.dataView=new DataView(L.buffer,0,8192)),D=0),At=L.length-10,At-D<2048?(L=new nl(L.length),Ve=L.dataView||(L.dataView=new DataView(L.buffer,0,L.length)),At=L.length-10,D=0):D=D+7&2147483640,r=D,W&Jo&&(D+=W&255),i=c.structuredClone?new Map:null,c.bundleStrings&&typeof A!="string"?(Xe=[],Xe.size=1/0):Xe=null,o=c.structures,o){o.uninitialized&&(o=c._mergeStructures(c.getStructures()));let $=o.sharedLength||0;if($>d)throw new Error("Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to "+o.sharedLength);if(!o.transitions){o.transitions=Object.create(null);for(let j=0;j<$;j++){let se=o[j];if(!se)continue;let oe,ne=o.transitions;for(let ye=0,ue=se.length;ye<ue;ye++){let yt=se[ye];oe=ne[yt],oe||(oe=ne[yt]=Object.create(null)),ne=oe}ne[Ko]=j+64}this.lastNamedStructuresLength=$}u||(o.nextId=$+64)}s&&(s=!1);let G;try{c._writeStruct&&A&&typeof A=="object"?A.constructor===Object?X(A):A.constructor!==Map&&!Array.isArray(A)&&!ip.some(j=>A instanceof j)?X(A.toJSON?A.toJSON():A):R(A):R(A);let $=Xe;if(Xe&&ub(r,R,0),i&&i.idsToInsert){let j=i.idsToInsert.sort((ye,ue)=>ye.offset>ue.offset?1:-1),se=j.length,oe=-1;for(;$&&se>0;){let ye=j[--se].offset+r;ye<$.stringsPosition+r&&oe===-1&&(oe=0),ye>$.position+r?oe>=0&&(oe+=6):(oe>=0&&(Ve.setUint32($.position+r,Ve.getUint32($.position+r)+oe),oe=-1),$=$.previous,se++)}oe>=0&&$&&Ve.setUint32($.position+r,Ve.getUint32($.position+r)+oe),D+=j.length*6,D>At&&N(D),c.offset=D;let ne=AP(L.subarray(r,D),j);return i=null,ne}return c.offset=D,W&fb?(L.start=r,L.end=D,L):L.subarray(r,D)}catch($){throw G=$,$}finally{if(o&&(_(),s&&c.saveStructures)){let $=o.sharedLength||0,j=L.subarray(r,D),se=(c._prepareStructures||vP)(o,c);if(!G)return c.saveStructures(se,se.isCompatible)===!1?(o.uninitialized=!0,c.pack(A,W)):(c.lastNamedStructuresLength=$,L.length>1073741824&&(L=null),j)}L.length>1073741824&&(L=null),W&pb&&(D=r)}};let _=()=>{S<10&&S++;let A=o.sharedLength||0;if(o.length>A&&!u&&(o.length=A),b>1e4)o.transitions=null,S=0,b=0,x.length>0&&(x=[]);else if(x.length>0&&!u){for(let W=0,G=x.length;W<G;W++)x[W][Ko]=0;x=[]}},P=A=>{var W=A.length;W<16?L[D++]=144|W:W<65536?(L[D++]=220,L[D++]=W>>8,L[D++]=W&255):(L[D++]=221,Ve.setUint32(D,W),D+=4);for(let G=0;G<W;G++)R(A[G])},R=A=>{D>At&&(L=N(D));var W=typeof A,G;if(W==="string"){let $=A.length;if(Xe&&$>=4&&$<4096){if((Xe.size+=$)>kP){let ne,ye=(Xe[0]?Xe[0].length*3+Xe[1].length:0)+10;D+ye>At&&(L=N(D+ye));let ue;Xe.position?(ue=Xe,L[D]=200,D+=3,L[D++]=98,ne=D-r,D+=4,ub(r,R,0),Ve.setUint16(ne+r-3,D-r-ne)):(L[D++]=214,L[D++]=98,ne=D-r,D+=4),Xe=["",""],Xe.previous=ue,Xe.size=0,Xe.position=ne}let oe=PP.test(A);Xe[oe?0:1]+=A,L[D++]=193,R(oe?-$:$);return}let j;$<32?j=1:$<256?j=2:$<65536?j=3:j=5;let se=$*3;if(D+se>At&&(L=N(D+se)),$<64||!a){let oe,ne,ye,ue=D+j;for(oe=0;oe<$;oe++)ne=A.charCodeAt(oe),ne<128?L[ue++]=ne:ne<2048?(L[ue++]=ne>>6|192,L[ue++]=ne&63|128):(ne&64512)===55296&&((ye=A.charCodeAt(oe+1))&64512)===56320?(ne=65536+((ne&1023)<<10)+(ye&1023),oe++,L[ue++]=ne>>18|240,L[ue++]=ne>>12&63|128,L[ue++]=ne>>6&63|128,L[ue++]=ne&63|128):(L[ue++]=ne>>12|224,L[ue++]=ne>>6&63|128,L[ue++]=ne&63|128);G=ue-D-j}else G=a(A,D+j);G<32?L[D++]=160|G:G<256?(j<2&&L.copyWithin(D+2,D+1,D+1+G),L[D++]=217,L[D++]=G):G<65536?(j<3&&L.copyWithin(D+3,D+2,D+2+G),L[D++]=218,L[D++]=G>>8,L[D++]=G&255):(j<5&&L.copyWithin(D+5,D+3,D+3+G),L[D++]=219,Ve.setUint32(D,G),D+=4),D+=G}else if(W==="number")if(A>>>0===A)A<32||A<128&&this.useRecords===!1||A<64&&!this._writeStruct?L[D++]=A:A<256?(L[D++]=204,L[D++]=A):A<65536?(L[D++]=205,L[D++]=A>>8,L[D++]=A&255):(L[D++]=206,Ve.setUint32(D,A),D+=4);else if(A>>0===A)A>=-32?L[D++]=256+A:A>=-128?(L[D++]=208,L[D++]=A+256):A>=-32768?(L[D++]=209,Ve.setInt16(D,A),D+=2):(L[D++]=210,Ve.setInt32(D,A),D+=4);else{let $;if(($=this.useFloat32)>0&&A<4294967296&&A>=-2147483648){L[D++]=202,Ve.setFloat32(D,A);let j;if($<4||(j=A*Zu[(L[D]&127)<<1|L[D+1]>>7])>>0===j){D+=4;return}else D--}L[D++]=203,Ve.setFloat64(D,A),D+=8}else if(W==="object"||W==="function")if(!A)L[D++]=192;else{if(i){let j=i.get(A);if(j){if(!j.id){let se=i.idsToInsert||(i.idsToInsert=[]);j.id=se.push(j)}L[D++]=214,L[D++]=112,Ve.setUint32(D,j.id),D+=4;return}else i.set(A,{offset:D-r})}let $=A.constructor;if($===Object)z(A);else if($===Array)P(A);else if($===Map)if(this.mapAsEmptyObject)L[D++]=128;else{G=A.size,G<16?L[D++]=128|G:G<65536?(L[D++]=222,L[D++]=G>>8,L[D++]=G&255):(L[D++]=223,Ve.setUint32(D,G),D+=4);for(let[j,se]of A)R(j),R(se)}else{for(let j=0,se=op.length;j<se;j++){let oe=ip[j];if(A instanceof oe){let ne=op[j];if(ne.write){ne.type&&(L[D++]=212,L[D++]=ne.type,L[D++]=0);let Hn=ne.write.call(this,A);Hn===A?Array.isArray(A)?P(A):z(A):R(Hn);return}let ye=L,ue=Ve,yt=D;L=null;let Gt;try{Gt=ne.pack.call(this,A,Hn=>(L=ye,ye=null,D+=Hn,D>At&&N(D),{target:L,targetView:Ve,position:D-Hn}),R)}finally{ye&&(L=ye,Ve=ue,D=yt,At=L.length-10)}Gt&&(Gt.length+D>At&&N(Gt.length+D),D=cb(Gt,L,D,ne.type));return}}if(Array.isArray(A))P(A);else{if(A.toJSON){let j=A.toJSON();if(j!==A)return R(j)}if(W==="function")return R(this.writeFunction&&this.writeFunction(A));z(A)}}}else if(W==="boolean")L[D++]=A?195:194;else if(W==="bigint"){if(A<9223372036854776e3&&A>=-9223372036854776e3)L[D++]=211,Ve.setBigInt64(D,A);else if(A<18446744073709552e3&&A>0)L[D++]=207,Ve.setBigUint64(D,A);else if(this.largeBigIntToFloat)L[D++]=203,Ve.setFloat64(D,Number(A));else{if(this.largeBigIntToString)return R(A.toString());if(this.useBigIntExtension||this.moreTypes){let $=A<0?BigInt(-1):BigInt(0),j;if(A>>BigInt(65536)===$){let se=BigInt(18446744073709552e3)-BigInt(1),oe=[];for(;oe.push(A&se),A>>BigInt(63)!==$;)A>>=BigInt(64);j=new Uint8Array(new BigUint64Array(oe).buffer),j.reverse()}else{let se=A<0,oe=(se?~A:A).toString(16);if(oe.length%2?oe="0"+oe:parseInt(oe.charAt(0),16)>=8&&(oe="00"+oe),Xo)j=Buffer.from(oe,"hex");else{j=new Uint8Array(oe.length/2);for(let ne=0;ne<j.length;ne++)j[ne]=parseInt(oe.slice(ne*2,ne*2+2),16)}if(se)for(let ne=0;ne<j.length;ne++)j[ne]=~j[ne]}j.length+D>At&&N(j.length+D),D=cb(j,L,D,66);return}else throw new RangeError(A+" was too large to fit in MessagePack 64-bit integer format, use useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set largeBigIntToString to convert to string")}D+=8}else if(W==="undefined")this.encodeUndefinedAsNil?L[D++]=192:(L[D++]=212,L[D++]=0,L[D++]=0);else throw new Error("Unknown type: "+W)},v=this.variableMapSize||this.coercibleKeyAsNumber||this.skipValues?A=>{let W;if(this.skipValues){W=[];for(let j in A)(typeof A.hasOwnProperty!="function"||A.hasOwnProperty(j))&&!this.skipValues.includes(A[j])&&W.push(j)}else W=Object.keys(A);let G=W.length;G<16?L[D++]=128|G:G<65536?(L[D++]=222,L[D++]=G>>8,L[D++]=G&255):(L[D++]=223,Ve.setUint32(D,G),D+=4);let $;if(this.coercibleKeyAsNumber)for(let j=0;j<G;j++){$=W[j];let se=Number($);R(isNaN(se)?$:se),R(A[$])}else for(let j=0;j<G;j++)R($=W[j]),R(A[$])}:A=>{L[D++]=222;let W=D-r;D+=2;let G=0;for(let $ in A)(typeof A.hasOwnProperty!="function"||A.hasOwnProperty($))&&(R($),R(A[$]),G++);if(G>65535)throw new Error('Object is too large to serialize with fast 16-bit map size, use the "variableMapSize" option to serialize this object');L[W+++r]=G>>8,L[W+r]=G&255},M=this.useRecords===!1?v:e.progressiveRecords&&!h?A=>{let W,G=o.transitions||(o.transitions=Object.create(null)),$=D++-r,j;for(let se in A)if(typeof A.hasOwnProperty!="function"||A.hasOwnProperty(se)){if(W=G[se],W)G=W;else{let oe=Object.keys(A),ne=G;G=o.transitions;let ye=0;for(let ue=0,yt=oe.length;ue<yt;ue++){let Gt=oe[ue];W=G[Gt],W||(W=G[Gt]=Object.create(null),ye++),G=W}$+r+1==D?(D--,Y(G,oe,ye)):he(G,oe,$,ye),j=!0,G=ne[se]}R(A[se])}if(!j){let se=G[Ko];se?L[$+r]=se:he(G,Object.keys(A),$,0)}}:A=>{let W,G=o.transitions||(o.transitions=Object.create(null)),$=0;for(let se in A)(typeof A.hasOwnProperty!="function"||A.hasOwnProperty(se))&&(W=G[se],W||(W=G[se]=Object.create(null),$++),G=W);let j=G[Ko];j?j>=96&&h?(L[D++]=((j-=96)&31)+96,L[D++]=j>>5):L[D++]=j:Y(G,G.__keys__||Object.keys(A),$);for(let se in A)(typeof A.hasOwnProperty!="function"||A.hasOwnProperty(se))&&R(A[se])},O=typeof this.useRecords=="function"&&this.useRecords,z=O?A=>{O(A)?M(A):v(A)}:M,X=A=>{let W=c._writeStruct(A,L,r,D,o,N,(G,$,j)=>{if(j)return s=!0;D=$;let se=L;return R(G),_(),se!==L?{position:D,targetView:Ve,target:L}:D});if(W===0)return z(A);D=W},N=A=>{let W;if(A>16777216){if(A-r>ab)throw new Error("Packed buffer would be larger than maximum buffer size");W=Math.min(ab,Math.round(Math.max((A-r)*(A>67108864?1.25:2),4194304)/4096)*4096)}else W=(Math.max(A-r<<2,L.length-1)>>12)+1<<12;let G=new nl(W);return Ve=G.dataView||(G.dataView=new DataView(G.buffer,0,W)),A=Math.min(A,L.length),L.copy?L.copy(G,0,r,A):G.set(L.slice(r,A)),D-=r,r=0,At=G.length-10,L=G},Y=(A,W,G)=>{let $=o.nextId;$||($=64),$<p&&this.shouldShareStructure&&!this.shouldShareStructure(W)?($=o.nextOwnId,$<g||($=p),o.nextOwnId=$+1):($>=g&&($=p),o.nextId=$+1);let j=W.highByte=$>=96&&h?$-96>>5:-1;A[Ko]=$,A.__keys__=W,o[$-64]=W,$<p?(W.isShared=!0,o.sharedLength=$-63,s=!0,j>=0?(L[D++]=($&31)+96,L[D++]=j):L[D++]=$):(j>=0?(L[D++]=213,L[D++]=114,L[D++]=($&31)+96,L[D++]=j):(L[D++]=212,L[D++]=114,L[D++]=$),G&&(b+=S*G),x.length>=f&&(x.shift()[Ko]=0),x.push(A),R(W))},he=(A,W,G,$)=>{let j=L,se=D,oe=At,ne=r;L=Ia,D=0,r=0,L||(Ia=L=new nl(8192)),At=L.length-10,Y(A,W,$),Ia=L;let ye=D;if(L=j,D=se,At=oe,r=ne,ye>1){let ue=D+ye-1;ue>At&&N(ue);let yt=G+r;L.copyWithin(yt+ye,yt+1,D),L.set(Ia.slice(0,ye),yt),D=ue}else L[G+r]=Ia[0]}}useBuffer(e){L=e,L.dataView||(L.dataView=new DataView(L.buffer,L.byteOffset,L.byteLength)),Ve=L.dataView,D=0}set position(e){D=e}get position(){return D}clearSharedData(){this.structures&&(this.structures=[]),this.typedStructs&&(this.typedStructs=[])}};ip=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,DataView,Ca];op=[{pack(t,e,n){let r=t.getTime()/1e3;if((this.useTimestamp32||t.getMilliseconds()===0)&&r>=0&&r<4294967296){let{target:s,targetView:o,position:i}=e(6);s[i++]=214,s[i++]=255,o.setUint32(i,r)}else if(r>0&&r<4294967296){let{target:s,targetView:o,position:i}=e(10);s[i++]=215,s[i++]=255,o.setUint32(i,t.getMilliseconds()*4e6+(r/1e3/4294967296>>0)),o.setUint32(i+4,r)}else if(isNaN(r)){if(this.onInvalidDate)return e(0),n(this.onInvalidDate());let{target:s,targetView:o,position:i}=e(3);s[i++]=212,s[i++]=255,s[i++]=255}else{let{target:s,targetView:o,position:i}=e(15);s[i++]=199,s[i++]=12,s[i++]=255,o.setUint32(i,t.getMilliseconds()*1e6),o.setBigInt64(i+4,BigInt(Math.floor(r)))}}},{pack(t,e,n){if(this.setAsEmptyObject)return e(0),n({});let r=Array.from(t),{target:s,position:o}=e(this.moreTypes?3:0);this.moreTypes&&(s[o++]=212,s[o++]=115,s[o++]=0),n(r)}},{pack(t,e,n){let{target:r,position:s}=e(this.moreTypes?3:0);this.moreTypes&&(r[s++]=212,r[s++]=101,r[s++]=0),n([t.name,t.message,t.cause])}},{pack(t,e,n){let{target:r,position:s}=e(this.moreTypes?3:0);this.moreTypes&&(r[s++]=212,r[s++]=120,r[s++]=0),n([t.source,t.flags])}},{pack(t,e){this.moreTypes?rp(t,16,e):sp(Xo?Buffer.from(t):new Uint8Array(t),e)}},{pack(t,e){let n=t.constructor;n!==lb&&this.moreTypes?rp(t,np.indexOf(n.name),e):sp(t,e)}},{pack(t,e){this.moreTypes?rp(t,17,e):sp(Xo?Buffer.from(t):new Uint8Array(t),e)}},{pack(t,e){let{target:n,position:r}=e(1);n[r]=193}}];function rp(t,e,n,r){let s=t.byteLength;if(s+1<256){var{target:o,position:i}=n(4+s);o[i++]=199,o[i++]=s+1}else if(s+1<65536){var{target:o,position:i}=n(5+s);o[i++]=200,o[i++]=s+1>>8,o[i++]=s+1&255}else{var{target:o,position:i,targetView:a}=n(7+s);o[i++]=201,a.setUint32(i,s+1),i+=4}o[i++]=116,o[i++]=e,t.buffer||(t=new Uint8Array(t)),o.set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength),i)}function sp(t,e){let n=t.byteLength;var r,s;if(n<256){var{target:r,position:s}=e(n+2);r[s++]=196,r[s++]=n}else if(n<65536){var{target:r,position:s}=e(n+3);r[s++]=197,r[s++]=n>>8,r[s++]=n&255}else{var{target:r,position:s,targetView:o}=e(n+5);r[s++]=198,o.setUint32(s,n),s+=4}r.set(t,s)}function cb(t,e,n,r){let s=t.length;switch(s){case 1:e[n++]=212;break;case 2:e[n++]=213;break;case 4:e[n++]=214;break;case 8:e[n++]=215;break;case 16:e[n++]=216;break;default:s<256?(e[n++]=199,e[n++]=s):s<65536?(e[n++]=200,e[n++]=s>>8,e[n++]=s&255):(e[n++]=201,e[n++]=s>>24,e[n++]=s>>16&255,e[n++]=s>>8&255,e[n++]=s&255)}return e[n++]=r,e.set(t,n),n+=s,n}function AP(t,e){let n,r=e.length*6,s=t.length-r;for(;n=e.pop();){let o=n.offset,i=n.id;t.copyWithin(o+r,o,s),r-=6;let a=o+r;t[a++]=214,t[a++]=105,t[a++]=i>>24,t[a++]=i>>16&255,t[a++]=i>>8&255,t[a++]=i&255,s=o}return t}function ub(t,e,n){if(Xe.length>0){Ve.setUint32(Xe.position+t,D+n-Xe.position-t),Xe.stringsPosition=D-t;let r=Xe;Xe=null,e(r[0]),e(r[1])}}function vP(t,e){return t.isCompatible=n=>{let r=!n||(e.lastNamedStructuresLength||0)===n.length;return r||e._mergeStructures(n),r},t}Qr.SUPPORTS_STRUCT_HOOKS=!0;var db=new Qr({useRecords:!1}),TP=db.pack,MP=db.pack;var{NEVER:CP,ALWAYS:OP,DECIMAL_ROUND:IP,DECIMAL_FIT:DP}=tl,fb=512,pb=1024,Jo=2048;wt();yr();var BP=9,sl=class{constructor(){m(this,"pending",new Uint8Array(0))}push(e){if(!e||e.byteLength===0)return[];let n=this.pending.byteLength===0?e:NP(this.pending,e),r=[],s=0;for(;s<n.byteLength;){let o={offset:s},i;try{i=Re.number(n,o)}catch(c){if(n.byteLength-s<=BP)break;throw c}let a=o.offset+i;if(a>n.byteLength)break;r.push(n.subarray(o.offset,a)),s=a}return this.pending=s<n.byteLength?n.slice(s):new Uint8Array(0),r}};function NP(t,e){let n=new Uint8Array(t.byteLength+e.byteLength);return n.set(t,0),n.set(e,t.byteLength),n}var Da=class{constructor(e){m(this,"wt");m(this,"url");m(this,"isOpen",!1);m(this,"events");m(this,"reader");m(this,"writer");m(this,"unreliableReader");m(this,"unreliableWriter");m(this,"lengthPrefixBuffer",new Uint8Array(9));m(this,"reliableReassembler",new sl);m(this,"unreliableReassembler",new sl);this.events=e}connect(e,n={}){this.url=e;let r=n.fingerprint&&{serverCertificateHashes:[{algorithm:"sha-256",value:new Uint8Array(n.fingerprint)}]}||void 0;this.wt=new WebTransport(e,r),this.wt.ready.then(s=>{console.log("WebTransport ready!",s),this.isOpen=!0,this.unreliableReader=this.wt.datagrams.readable.getReader();let o=this.wt.datagrams;this.unreliableWriter=(o.createWritable?o.createWritable():o.writable).getWriter(),this.wt.incomingBidirectionalStreams.getReader().read().then(a=>{this.reader=a.value.readable.getReader(),this.writer=a.value.writable.getWriter(),this.sendSeatReservation(n.roomId,n.sessionId,n.reconnectionToken,n.skipHandshake),this.readIncomingData(),this.readIncomingUnreliableData()}).catch(a=>{console.error("failed to read incoming stream",a),console.error("TODO: close the connection")})}).catch(s=>{console.log("WebTransport not ready!",s),this._close()}),this.wt.closed.then(s=>{console.log("WebTransport closed w/ success",s),this.events.onclose({code:s.closeCode,reason:s.reason})}).catch(s=>{console.log("WebTransport closed w/ error",s),this.events.onerror(s),this.events.onclose({code:s.closeCode,reason:s.reason})}).finally(()=>{this._close()})}send(e){this.writer.write(this.frame(e))}sendUnreliable(e){this.unreliableWriter.write(this.frame(e))}frame(e){let n=e instanceof Uint8Array?e:new Uint8Array(e),r=be.number(this.lengthPrefixBuffer,n.length,{offset:0}),s=new Uint8Array(r+n.length);return s.set(this.lengthPrefixBuffer.subarray(0,r),0),s.set(n,r),s}close(e,n){this.isOpen=!1;try{let r=this.wt?.close({closeCode:e,reason:n});r&&typeof r.catch=="function"&&r.catch(()=>{})}catch{}}readIncomingData(){return this.readLoop(this.reader,this.reliableReassembler,"reliable")}readIncomingUnreliableData(){return this.readLoop(this.unreliableReader,this.unreliableReassembler,"unreliable")}async readLoop(e,n,r){for(;this.isOpen;){let s;try{s=await e.read()}catch(o){await this.onChannelFailure(r,o);return}if(s.done||!s.value)return;for(let o of n.push(s.value))this.events.onmessage({data:o})}}async onChannelFailure(e,n){await new Promise(r=>setTimeout(r,0)),this.isOpen&&(console.error(`H3Transport: stopped reading the ${e} channel while the session was open`,n),this.close(ft.ABNORMAL_CLOSURE,`h3 ${e} channel failed`))}sendSeatReservation(e,n,r,s){let o={offset:0},i=[];be.string(i,e,o),be.string(i,n,o),r&&be.string(i,r,o),s&&be.boolean(i,1,o),this.writer.write(new Uint8Array(i).buffer)}_close(){this.isOpen=!1}};var gb=YE(mb(),1);yr();var ap=globalThis.WebSocket||gb.default,yb=!1,ol=class{constructor(e){m(this,"ws");m(this,"protocols");m(this,"events");this.events=e}send(e){this.ws.send(e)}sendUnreliable(e){yb||(yb=!0,console.warn('@colyseus/sdk: the WebSocket transport has no unreliable channel \u2014 sending `mode:"unreliable"` traffic reliably instead. Use @colyseus/h3-transport (WebTransport) for datagram delivery.')),this.send(e)}connect(e,n){try{this.ws=new ap(e,{headers:n,protocols:this.protocols})}catch{this.ws=new ap(e,this.protocols)}this.ws.binaryType="arraybuffer",this.ws.onopen=r=>this.events.onopen?.(r),this.ws.onmessage=r=>this.events.onmessage?.(r),this.ws.onclose=r=>this.events.onclose?.(r),this.ws.onerror=r=>this.events.onerror?.(r)}close(e,n){e===ft.MAY_TRY_RECONNECT&&this.events.onclose&&(this.ws.onclose=null,this.events.onclose({code:e,reason:n})),this.ws.close(e,n)}get isOpen(){return this.ws.readyState===ap.OPEN}};yr();var Ba=[],cp=typeof addEventListener=="function"&&typeof removeEventListener=="function";cp&&addEventListener("offline",()=>{console.warn(`@colyseus/sdk: \u{1F6D1} Network offline. Closing ${Ba.length} connection(s)`),Ba.forEach(t=>t())},!1);var Na,Zo=class{constructor(e){m(this,"transport");m(this,"events",{});m(this,"url");m(this,"options");ze(this,Na,cp?()=>this.close(ft.MAY_TRY_RECONNECT):null);e==="h3"?this.transport=new Da(this.events):this.transport=new ol(this.events)}connect(e,n){if(cp){let r=this.events.onopen;this.events.onopen=o=>{Ba.push(ae(this,Na)),r?.(o)};let s=this.events.onclose;this.events.onclose=o=>{Ba.splice(Ba.indexOf(ae(this,Na)),1),s?.(o)}}this.url=e,this.options=n,this.transport.connect(e,n)}send(e){this.transport.send(e)}sendUnreliable(e){this.transport.sendUnreliable(e)}reconnect(e){if(this.transport instanceof Da){this.transport.connect(this.url,{...this.options,...e});return}let n=new URL(this.url);for(let r in e)n.searchParams.set(r,e[r]);this.transport.connect(n.toString(),this.options)}close(e,n){this.transport.close(e,n)}get isOpen(){return this.transport.isOpen}};Na=new WeakMap;var bb={};function up(t,e){bb[t]=e}function lp(t){let e=bb[t];if(!e)throw new Error("missing serializer: "+t);return e}var il=()=>({emit(t,...e){let n=this.events[t]||[];for(let r=0,s=n.length;r<s;r++)n[r](...e)},events:{},on(t,e){return this.events[t]?.push(e)||(this.events[t]=[e]),()=>{this.events[t]=this.events[t]?.filter(n=>e!==n)}}});var wb=new WeakMap,dp=class{constructor(){m(this,"handlers",[])}register(e,n=!1){return this.handlers.push(e),this}invoke(...e){let n=this.handlers;for(let r=0,s=n.length;r<s;r++)n[r].apply(this,e)}invokeAsync(...e){return Promise.all(this.handlers.map(n=>n.apply(this,e)))}remove(e){let n=this.handlers.indexOf(e);n===-1&&(n=this.handlers.findIndex(r=>wb.get(r)===e)),n!==-1&&(this.handlers=this.handlers.filter((r,s)=>s!==n))}clear(){this.handlers=[]}};function Us(){let t=new dp;function e(n){return t.register(n,this===null)}return e.once=n=>{let r=function(...s){t.remove(r),n.apply(this,s)};wb.set(r,n),t.register(r)},e.remove=n=>t.remove(n),e.invoke=(...n)=>t.invoke(...n),e.invokeAsync=(...n)=>t.invokeAsync(...n),e.clear=()=>t.clear(),e}wt();function La(t){try{return Ou(t.serializer.decoder)}catch{return}}var Qo=class{constructor(){m(this,"state");m(this,"decoder")}setState(e,n){this.decoder.root.refs.size>1&&typeof this.decoder.decodeResync=="function"?this.decoder.decodeResync(e,n):this.decoder.decode(e,n)}getState(){return this.state}patch(e,n){return this.decoder.decode(e,n)}teardown(){this.decoder.root.clearRefs()}handshake(e,n){this.state?(Dn.decode(e,n),this.decoder=new In(this.state)):(this.decoder=Dn.decode(e,n),this.state=this.decoder.state)}};Yu();function xb(){return{enabled:!0,retryCount:0,maxRetries:15,delay:100,minDelay:100,maxDelay:5e3,minUptime:5e3,backoff:LP,maxEnqueuedMessages:10,enqueuedMessages:[],isReconnecting:!1}}var LP=(t,e)=>Math.floor(Math.pow(2,t)*e);function al(t,e){t.reconnection.enqueuedMessages.push({data:e}),t.reconnection.enqueuedMessages.length>t.reconnection.maxEnqueuedMessages&&t.reconnection.enqueuedMessages.shift()}function Sb(t,e){if(!e){let r=new Error("request rejected");return r.name="rejected",r.reason=t,r}let n=new Error(t?.message??"request failed");return t?.name&&(n.name=t.name),t?.code!==void 0&&(n.code=t.code),n}wa();var za,ei,ti,rr,sr,ni,or,Eb,_b,Rb,kb,cl=class cl{constructor(e,n){ze(this,or);m(this,"roomId");m(this,"sessionId");m(this,"reconnectionToken");m(this,"name");m(this,"connection");m(this,"onStateChange",Us());m(this,"onError",Us());m(this,"onLeave",Us());m(this,"onReconnect",Us());m(this,"onDrop",Us());m(this,"onJoin",Us());m(this,"serializerId");m(this,"serializer");m(this,"reconnection",xb());m(this,"joinedAtTime",0);m(this,"clock",qo);m(this,"onMessageHandlers",il());m(this,"packr");m(this,"sharedBuffer");ze(this,za,0);ze(this,ei);ze(this,ti,0);ze(this,rr,new Map);ze(this,sr);ze(this,ni,0);if(this.name=e,this.packr=new Qr,this.sharedBuffer=new Uint8Array(8192),n){let r=new(lp("schema"));this.serializer=r;let s=new n;r.state=s,r.decoder=new In(s)}this.onLeave(()=>{this.removeAllListeners(),this.destroy()})}connect(e,n,r){this.connection=new Zo(n.protocol),this.connection.events.onmessage=this.onMessageCallback.bind(this),this.connection.events.onclose=o=>{if(ks(this,or,Rb).call(this,"connection closed before a response was received."),this.joinedAtTime===0){console.warn?.(`Room connection was closed unexpectedly (${o.code}): ${o.reason}`),this.onError.invoke(o.code,o.reason);return}o.code===ft.NO_STATUS_RECEIVED||o.code===ft.ABNORMAL_CLOSURE||o.code===ft.GOING_AWAY||o.code===ft.MAY_TRY_RECONNECT?(this.onDrop.invoke(o.code,o.reason),this.handleReconnection(o.code,o.reason)):this.onLeave.invoke(o.code,o.reason)},this.connection.events.onerror=o=>{this.onError.invoke(o.code,o.reason)};let s=this.serializer?.getState()!==void 0;if(n.protocol==="h3"){let o=new URL(e);this.connection.connect(o.origin,{...n,skipHandshake:s})}else this.connection.connect(`${e}${s?"&skipHandshake=1":""}`,r)}leave(e=!0){return new Promise(n=>{this.onLeave(r=>n(r)),this.connection?e?(this.sharedBuffer[0]=We.LEAVE_ROOM,this.connection.send(this.sharedBuffer.subarray(0,1))):this.connection.close():this.onLeave.invoke(ft.CONSENTED)})}onMessage(e,n){return this.onMessageHandlers.on(this.getMessageHandlerKey(e),n)}ping(e){this.connection?.isOpen&&(Ue(this,za,Pt()),Ue(this,ei,e),this.sharedBuffer[0]=We.PING,this.connection.send(this.sharedBuffer.subarray(0,1)))}send(e,n,r){if(r!==void 0){this.request(e,n).then(a=>r(a,void 0),a=>r(void 0,a));return}let s={offset:1};this.sharedBuffer[0]=We.ROOM_DATA,typeof e=="string"?be.string(this.sharedBuffer,e,s):be.number(this.sharedBuffer,e,s);let o=s.offset,i;n!==void 0?(i=this.packr.pack(n,Jo|o),i.set(this.sharedBuffer.subarray(0,o),0)):i=this.sharedBuffer.subarray(0,o),this.connection.isOpen?this.connection.send(i):al(this,new Uint8Array(i))}request(e,n,r){if(!this.connection.isOpen)return Promise.reject(new Error(`cannot send request "${e}": connection is not open.`));let s=r?.timeout??cl.defaultRequestTimeout;return new Promise((o,i)=>{let a,c=this.sendRequest(e,n,{mode:r?.mode},(u,l,d)=>{clearTimeout(a),u?o(l):i(Sb(l,d))},u=>{clearTimeout(a),i(new Error(u))});a=setTimeout(()=>{this.cancelRequest(c),i(new Error(`request "${e}" timed out after ${s}ms.`))},s)})}sendRequest(e,n,r,s,o){let i=ks(this,or,Eb).call(this),a=ks(this,or,_b).call(this,i,e,n);if(r.mode==="unreliable"){if(!this.connection.isOpen)return-1;this.connection.sendUnreliable(a)}else this.connection.isOpen?this.connection.send(a):al(this,new Uint8Array(a));return ae(this,rr).set(i,{onReply:s,onClose:o}),i}cancelRequest(e){ae(this,rr).delete(e)}sendUnreliable(e,n){if(!this.connection.isOpen)return;let r={offset:1};this.sharedBuffer[0]=We.ROOM_DATA,typeof e=="string"?be.string(this.sharedBuffer,e,r):be.number(this.sharedBuffer,e,r);let s=r.offset,o;n!==void 0?(o=this.packr.pack(n,Jo|s),o.set(this.sharedBuffer.subarray(0,s),0)):o=this.sharedBuffer.subarray(0,s),this.connection.sendUnreliable(o)}sendBytes(e,n){let r={offset:1};this.sharedBuffer[0]=We.ROOM_DATA_BYTES,typeof e=="string"?be.string(this.sharedBuffer,e,r):be.number(this.sharedBuffer,e,r);let s=r.offset;if(s+n.byteLength>this.sharedBuffer.byteLength){let o=new Uint8Array(s+n.byteLength);o.set(this.sharedBuffer.subarray(0,s)),this.sharedBuffer=o}this.sharedBuffer.set(n,s),this.connection.isOpen?this.connection.send(this.sharedBuffer.subarray(0,s+n.byteLength)):al(this,this.sharedBuffer.subarray(0,s+n.byteLength))}input(e){return(ae(this,sr)??Ue(this,sr,new Yo(this))).handle(e)}get state(){return this.serializer.getState()}removeAllListeners(){this.onJoin.clear(),this.onStateChange.clear(),this.onError.clear(),this.onLeave.clear(),this.onReconnect.clear(),this.onDrop.clear(),this.onMessageHandlers.events={},this.serializer instanceof Qo&&(this.serializer.decoder.root.callbacks={})}onMessageCallback(e){ks(this,or,kb).call(this,new Uint8Array(e.data))}dispatchMessage(e,n){let r=this.getMessageHandlerKey(e);this.onMessageHandlers.events[r]?this.onMessageHandlers.emit(r,n):this.onMessageHandlers.events["*"]?this.onMessageHandlers.emit("*",e,n):r.startsWith("__")||console.warn?.(`@colyseus/sdk: onMessage() not registered for type '${e}'.`)}destroy(){this.serializer&&this.serializer.teardown()}getMessageHandlerKey(e){switch(typeof e){case"string":return e;case"number":return`i${e}`;default:throw new Error("invalid message type.")}}handleReconnection(e,n){if(!this.reconnection.enabled){this.onLeave.invoke(e,n);return}if(Date.now()-this.joinedAtTime<this.reconnection.minUptime){console.info(`[Colyseus reconnection]: ${String.fromCodePoint(10060)} Room has not been up for long enough for automatic reconnection. (min uptime: ${this.reconnection.minUptime}ms)`),this.onLeave.invoke(ft.ABNORMAL_CLOSURE,"Room uptime too short for reconnection.");return}this.reconnection.isReconnecting||(this.reconnection.retryCount=0,this.reconnection.isReconnecting=!0,ae(this,sr)?.reset()),this.retryReconnection()}retryReconnection(){if(this.reconnection.retryCount>=this.reconnection.maxRetries){console.info(`[Colyseus reconnection]: ${String.fromCodePoint(10060)} \u274C Reconnection failed after ${this.reconnection.maxRetries} attempts.`),this.reconnection.isReconnecting=!1,this.onLeave.invoke(ft.FAILED_TO_RECONNECT,"No more retries. Reconnection failed.");return}this.reconnection.retryCount++;let e=Math.min(this.reconnection.maxDelay,Math.max(this.reconnection.minDelay,this.reconnection.backoff(this.reconnection.retryCount,this.reconnection.delay)));console.info(`[Colyseus reconnection]: ${String.fromCodePoint(9203)} will retry in ${(e/1e3).toFixed(1)} seconds...`),setTimeout(()=>{try{console.info(`[Colyseus reconnection]: ${String.fromCodePoint(128260)} Re-establishing sessionId '${this.sessionId}' with roomId '${this.roomId}'... (attempt ${this.reconnection.retryCount} of ${this.reconnection.maxRetries})`),this.connection.reconnect({reconnectionToken:this.reconnectionToken.split(":")[1],skipHandshake:!0})}catch{this.retryReconnection()}},e)}};za=new WeakMap,ei=new WeakMap,ti=new WeakMap,rr=new WeakMap,sr=new WeakMap,ni=new WeakMap,or=new WeakSet,Eb=function(){let e=ae(this,ti);return Ue(this,ti,ae(this,ti)+1>>>0),e},_b=function(e,n,r){let s={offset:1};this.sharedBuffer[0]=We.ROOM_REQUEST,be.number(this.sharedBuffer,e,s),typeof n=="string"?be.string(this.sharedBuffer,n,s):be.number(this.sharedBuffer,n,s);let o=s.offset;if(r!==void 0){let i=this.packr.pack(r,Jo|o);return i.set(this.sharedBuffer.subarray(0,o),0),i}return this.sharedBuffer.subarray(0,o)},Rb=function(e){if(ae(this,rr).size!==0){for(let n of ae(this,rr).values())n.onClose?.(e);ae(this,rr).clear()}},kb=function(e){var o;let n={offset:1},r=e[0],s=r&Sf;if(r&Lo.TIMED){let i=Re.uint32(e,n),a=Re.uint32(e,n),c=ae(this,sr)?ae(this,sr).ackInput(a):-1;this.clock.sample(i,c)}if(s===We.JOIN_ROOM){let i=Re.utf8Read(e,n,e[n.offset++]);if(this.serializerId=Re.utf8Read(e,n,e[n.offset++]),!this.serializer){let u=lp(this.serializerId);this.serializer=new u}let a=Re.number(e,n);if(a>0&&this.serializer.handshake){let u=n.offset+a;this.serializer.handshake(e.subarray(0,u),n),n.offset=u}for(;n.offset<e.byteLength;){let u=e[n.offset++],l=Re.number(e,n),d=n.offset+l;u===gu.INPUT_REFLECTION?(ae(this,sr)??Ue(this,sr,new Yo(this))).applyReflection(e,n,d):u===gu.INPUT_OPTIONS&&(ae(this,sr)??Ue(this,sr,new Yo(this))).applyOptions(e,n),n.offset=d}let c=ae(this,sr)?.patchRate;if(c!==void 0&&this.clock.setPatchInterval?.(c),this.joinedAtTime===0?(this.joinedAtTime=Date.now(),this.onJoin.invoke()):(console.info(`[Colyseus reconnection]: ${String.fromCodePoint(9989)} reconnection successful!`),this.reconnection.isReconnecting=!1,this.onReconnect.invoke()),this.reconnectionToken=`${this.roomId}:${i}`,this.sharedBuffer[0]=We.JOIN_ROOM,this.connection.send(this.sharedBuffer.subarray(0,1)),this.reconnection.enqueuedMessages.length>0){for(let u of this.reconnection.enqueuedMessages)this.connection.send(u.data);this.reconnection.enqueuedMessages=[]}}else if(s===We.ERROR){let i=Re.number(e,n),a=Re.string(e,n);this.onError.invoke(i,a)}else if(s===We.LEAVE_ROOM)this.leave();else if(s===We.ROOM_STATE)Ue(this,ni,0),this.serializer.setState(e,n),this.onStateChange.invoke(this.serializer.getState());else if(s===We.ROOM_STATE_PATCH){if(r&Lo.UNRELIABLE){let i=Re.uint16(e,n);if(i-ae(this,ni)<<16>>16<=0)return;Ue(this,ni,i)}this.serializer.patch(e,n),this.onStateChange.invoke(this.serializer.getState())}else if(s===We.ROOM_DATA){let i=Re.stringCheck(e,n)?Re.string(e,n):Re.number(e,n),a=e.byteLength>n.offset?el(e,{start:n.offset}):void 0;this.dispatchMessage(i,a)}else if(s===We.ROOM_DATA_BYTES){let i=Re.stringCheck(e,n)?Re.string(e,n):Re.number(e,n);this.dispatchMessage(i,e.subarray(n.offset))}else if(s===We.ROOM_RESPONSE){let i=Re.number(e,n),a=e[n.offset++],c=e.byteLength>n.offset?el(e,{start:n.offset}):void 0,u=ae(this,rr).get(i);u!==void 0&&(ae(this,rr).delete(i),u.onReply(a===yu.OK,c,a===yu.ERROR))}else s===We.PING&&((o=ae(this,ei))==null||o.call(this,Math.round(Pt()-ae(this,za))),Ue(this,ei,void 0))},m(cl,"defaultRequestTimeout",1e4);var Fa=cl;function Pb(t,e){return new Promise((n,r)=>{let s=new XMLHttpRequest,o=e?.method||"GET";s.open(o,t.toString()),s.withCredentials=e?.credentials==="include",e?.headers&&(e.headers instanceof Headers?e.headers:new Headers(e.headers)).forEach((a,c)=>{s.setRequestHeader(c,a)}),s.onload=()=>{let i=new Headers,a=s.getAllResponseHeaders().trim();if(a)for(let u of a.split(/[\r\n]+/)){let l=u.indexOf(": ");l>0&&i.append(u.substring(0,l),u.substring(l+2))}let c=s.response??s.responseText;n(new fp(c,{status:s.status,statusText:s.statusText,headers:i}))},s.onerror=()=>r(new TypeError("Network request failed")),s.ontimeout=()=>r(new TypeError("Network request timed out")),s.send(e?.body??null)})}var fp=class{constructor(e,n){m(this,"status");m(this,"statusText");m(this,"headers");m(this,"ok");m(this,"body");this.body=e,this.status=n.status,this.statusText=n.statusText,this.headers=n.headers,this.ok=n.status>=200&&n.status<300}async json(){return typeof this.body=="string"?JSON.parse(this.body):this.body}async text(){return typeof this.body=="string"?this.body:JSON.stringify(this.body)}async blob(){return new Blob([this.body])}};function FP(t){if(t===void 0)return!1;let e=typeof t;return e==="string"||e==="number"||e==="boolean"||e===null?!0:e!=="object"?!1:Array.isArray(t)?!0:t.buffer?!1:t.constructor&&t.constructor.name==="Object"||typeof t.toJSON=="function"}function zP(t,e){let{params:n,query:r}=e||{},[s,o]=t.split("?"),i=s;if(n)if(Array.isArray(n)){let u=i.split("/").filter(l=>l.startsWith(":"));for(let[l,d]of u.entries()){let f=n[l];i=i.replace(d,f)}}else for(let[u,l]of Object.entries(n))i=i.replace(`:${u}`,String(l));let a=new URLSearchParams(o);if(r)for(let[u,l]of Object.entries(r))l!=null&&a.set(u,String(l));let c=a.toString();return c=c.length>0?`?${c}`.replace(/\+/g,"%20"):"",`${i}${c}`}var ul=class{constructor(e,n,r){m(this,"authToken");m(this,"options");m(this,"sdk");m(this,"_fetchFn");m(this,"del",this.delete);this.sdk=e,this.options=n,this._fetchFn=r}get fetchFn(){return this._fetchFn||(this._fetchFn=typeof globalThis.fetch<"u"?globalThis.fetch.bind(globalThis):Pb),this._fetchFn}async request(e,n,r){return this.executeRequest(e,n,r)}get(e,n){return this.request("GET",e,n)}post(e,n){return this.request("POST",e,n)}delete(e,n){return this.request("DELETE",e,n)}patch(e,n){return this.request("PATCH",e,n)}put(e,n){return this.request("PUT",e,n)}async executeRequest(e,n,r){let s=this.options.body?{...this.options.body,...r?.body||{}}:r?.body,o=this.options.query?{...this.options.query,...r?.query||{}}:r?.query,i=this.options.params?{...this.options.params,...r?.params||{}}:r?.params,a=new Headers(this.options.headers?{...this.options.headers,...r?.headers||{}}:r?.headers);if(this.authToken&&!a.has("authorization")&&a.set("authorization",`Bearer ${this.authToken}`),FP(s)&&typeof s=="object"&&s!==null){a.has("content-type")||a.set("content-type","application/json");for(let[h,p]of Object.entries(s))p instanceof Date&&(s[h]=p.toISOString());s=JSON.stringify(s)}let c={credentials:r?.credentials||"include",...this.options,...r,query:o,params:i,headers:a,body:s,method:e},u=zP(this.sdk.getHttpEndpoint(n.toString()),c),l;try{l=await this.fetchFn(u,c)}catch(h){if(h.name==="AbortError")throw h;let p=new Yn(h.cause?.code||h.code,h.message);throw p.response=l,p.cause=h.cause,p}let d=l.headers.get("content-type"),f;if(d?.includes("json")?f=await l.json():d?.includes("text")?f=await l.text():f=await l.blob(),!l.ok)throw new Yn(l.status,f.message??f.error??l.statusText,{headers:l.headers,status:l.status,response:l,data:f});return{raw:l,data:f,headers:l.headers,status:l.status,statusText:l.statusText}}};var Vs;function hp(){if(!Vs)try{Vs=typeof cc<"u"&&cc.sys&&cc.sys.localStorage?cc.sys.localStorage:window.localStorage}catch{}return!Vs&&typeof globalThis.indexedDB<"u"&&(Vs=new pp),Vs||(Vs={cache:{},setItem:function(t,e){this.cache[t]=e},getItem:function(t){return this.cache[t]},removeItem:function(t){delete this.cache[t]}}),Vs}function Ab(t,e){hp().setItem(t,e)}function vb(t){hp().removeItem(t)}function Tb(t,e){let n=hp().getItem(t);typeof Promise>"u"||!(n instanceof Promise)?e(n):n.then(r=>e(r))}var pp=class{constructor(){m(this,"dbPromise",new Promise(e=>{let n=indexedDB.open("_colyseus_storage",1);n.onupgradeneeded=()=>n.result.createObjectStore("store"),n.onsuccess=()=>e(n.result)}))}async tx(e,n){let s=(await this.dbPromise).transaction("store",e).objectStore("store");return n(s)}setItem(e,n){return this.tx("readwrite",r=>r.put(n,e)).then()}async getItem(e){let n=await this.tx("readonly",r=>r.get(e));return new Promise(r=>{n.onsuccess=()=>r(n.result)})}removeItem(e){return this.tx("readwrite",n=>n.delete(e)).then()}};var Va,Rr,Ha,Ua=class{constructor(e){m(this,"settings",{path:"/auth",key:"colyseus-auth-token"});ze(this,Va,!1);ze(this,Rr,null);ze(this,Ha,il());m(this,"http");this.http=e,Tb(this.settings.key,n=>this.token=n)}set token(e){this.http.authToken=e}get token(){return this.http.authToken}onChange(e){let n=ae(this,Ha).on("change",e);return ae(this,Va)||this.getUserData().then(r=>{this.emitChange({...r,token:this.token})}).catch(r=>{this.emitChange({user:null,token:void 0})}),Ue(this,Va,!0),n}async getUserData(){if(this.token)return(await this.http.get(`${this.settings.path}/userdata`)).data;throw new Error("missing auth.token")}async registerWithEmailAndPassword(e,n,r){let s=(await this.http.post(`${this.settings.path}/register`,{body:{email:e,password:n,options:r}})).data;return this.emitChange(s),s}async signInWithEmailAndPassword(e,n){let r=(await this.http.post(`${this.settings.path}/login`,{body:{email:e,password:n}})).data;return this.emitChange(r),r}async signInAnonymously(e){let n=(await this.http.post(`${this.settings.path}/anonymous`,{body:{options:e}})).data;return this.emitChange(n),n}async sendPasswordResetEmail(e){return(await this.http.post(`${this.settings.path}/forgot-password`,{body:{email:e}})).data}async signInWithProvider(e,n={}){return new Promise((r,s)=>{let o=n.width||480,i=n.height||768,a=this.token?`?token=${this.token}`:"",c=`Login with ${e[0].toUpperCase()+e.substring(1)}`,u=this.http.sdk.getHttpEndpoint(`${n.prefix||`${this.settings.path}/provider`}/${e}${a}`),l=screen.width/2-o/2,d=screen.height/2-i/2;Ue(this,Rr,window.open(u,c,"toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width="+o+", height="+i+", top="+d+", left="+l));let f=p=>{if(!(p.data.user===void 0&&p.data.token===void 0))if(clearInterval(h),ae(this,Rr)?.close(),Ue(this,Rr,null),window.removeEventListener("message",f),p.data.error!==void 0){let g=new Error(String(p.data.error));g.code=p.data.error,p.data.reason!==void 0&&(g.reason=p.data.reason),p.data.until!==void 0&&(g.until=p.data.until),s(g)}else r(p.data),this.emitChange(p.data)},h=setInterval(()=>{(!ae(this,Rr)||ae(this,Rr).closed)&&(Ue(this,Rr,null),s("cancelled"),window.removeEventListener("message",f))},200);window.addEventListener("message",f)})}async signOut(){this.emitChange({user:null,token:null})}emitChange(e){e.token!==void 0&&(this.token=e.token,e.token===null?vb(this.settings.key):Ab(this.settings.key,e.token)),ae(this,Ha).emit("change",e)}};Va=new WeakMap,Rr=new WeakMap,Ha=new WeakMap;function Mb(t){let e=window?.location?.hostname||"localhost",n=t.hostname.split("."),r=!t.hostname.includes("trycloudflare.com")&&!t.hostname.includes("discordsays.com")&&n.length>2?`/${n[0]}`:"";return t.pathname.startsWith("/.proxy")?`${t.protocol}//${e}${r}${t.pathname}${t.search}`:`${t.protocol}//${e}/.proxy/colyseus${r}${t.pathname}${t.search}`}xa();var Cb=typeof window<"u"&&typeof window?.location?.hostname<"u"?`${window.location.protocol.replace("http","ws")}//${window.location.hostname}${window.location.port&&`:${window.location.port}`}`:"ws://127.0.0.1:2567",dl=class dl{constructor(e=Cb,n){m(this,"http");m(this,"auth");m(this,"settings");m(this,"urlBuilder");if(typeof e=="string"){let r=e.startsWith("/")?new URL(e,Cb):new URL(e),s=r.protocol==="https:"||r.protocol==="wss:",o=Number(r.port||(s?443:80));this.settings={hostname:r.hostname,pathname:r.pathname,port:o,secure:s,searchParams:r.searchParams.toString()||void 0}}else e.port===void 0&&(e.port=e.secure?443:80),e.pathname===void 0&&(e.pathname=""),this.settings=e;this.settings.pathname.endsWith("/")&&(this.settings.pathname=this.settings.pathname.slice(0,-1)),n?.protocol&&(this.settings.protocol=n.protocol),this.http=new ul(this,{headers:n?.headers||{}},n?.fetchFn),this.auth=new Ua(this.http),this.urlBuilder=n?.urlBuilder,!this.urlBuilder&&typeof window<"u"&&window?.location?.hostname?.includes("discordsays.com")&&(this.urlBuilder=Mb,console.log("Colyseus SDK: Discord Embedded SDK detected. Using custom URL builder."))}static async selectByLatency(e,n,r={}){let s=e.map(i=>new dl(i,n)),o=(await Promise.allSettled(s.map((i,a)=>i.getLatency(r).then(c=>{let u=s[a].settings;return console.log(`\u{1F6DC} Endpoint Latency: ${c}ms - ${u.hostname}:${u.port}${u.pathname}`),[a,c]})))).filter(i=>i.status==="fulfilled").map(i=>i.value);if(o.length===0)throw new Error("All endpoints failed to respond");return s[o.sort((i,a)=>i[1]-a[1])[0][0]]}async joinOrCreate(e,n={},r){return await this.createMatchMakeRequest("joinOrCreate",e,n,r)}async create(e,n={},r){return await this.createMatchMakeRequest("create",e,n,r)}async join(e,n={},r){return await this.createMatchMakeRequest("join",e,n,r)}async joinById(e,n={},r){return await this.createMatchMakeRequest("joinById",e,n,r)}async reconnect(e,n){if(typeof e=="string"&&typeof n=="string")throw new Error("DEPRECATED: .reconnect() now only accepts 'reconnectionToken' as argument.\nYou can get this token from previously connected `room.reconnectionToken`");let[r,s]=e.split(":");if(!r||!s)throw new Error(`Invalid reconnection token format.
13
+ The format should be roomId:reconnectionToken`);return await this.createMatchMakeRequest("reconnect",r,{reconnectionToken:s},n)}async consumeSeatReservation(e,n){let r=this.createRoom(e.name,n);r.roomId=e.roomId,r.sessionId=e.sessionId;let s={sessionId:r.sessionId};return e.reconnectionToken&&(s.reconnectionToken=e.reconnectionToken),r.connect(this.buildEndpoint(e,s),{...e,protocol:this.settings.protocol},this.http.options.headers),new Promise((o,i)=>{let a=(c,u)=>i(new Yn(c,u));r.onError.once(a),r.onJoin.once(()=>{r.onError.remove(a),ju("room",r),o(r)})})}getLatency(e={}){let n=e.protocol??"ws",r=e.pingCount??1,s=e.timeout??1500;return new Promise((o,i)=>{let a=new Zo(n),c=[],u=0,l=!1,d,f=p=>{if(!l){l=!0,clearTimeout(d);try{a.close()}catch{}p()}},h=p=>f(()=>i(new Yn(ft.ABNORMAL_CLOSURE,`Failed to get latency: ${p}`)));d=setTimeout(()=>h(`timed out after ${s}ms`),s),a.events.onopen=()=>{u=Date.now(),a.send(new Uint8Array([We.PING]))},a.events.onmessage=p=>{if(c.push(Date.now()-u),c.length<r)u=Date.now(),a.send(new Uint8Array([We.PING]));else{let g=c.reduce((x,b)=>x+b,0)/c.length;f(()=>o(g))}},a.events.onclose=p=>h(`connection closed${p?.code?` (${p.code})`:""}${p?.reason?`: ${p.reason}`:""}`),a.events.onerror=p=>h(p.message);try{a.connect(this.getHttpEndpoint())}catch(p){h(p?.message??"failed to connect")}})}async createMatchMakeRequest(e,n,r={},s){try{if(!n)throw new Error("Must provide a room name");let i=(await this.http.post(`/matchmake/${e}/${n}`,{headers:{Accept:"application/json","Content-Type":"application/json"},body:r})).data;return e==="reconnect"&&(i.reconnectionToken=r.reconnectionToken),await this.consumeSeatReservation(i,s)}catch(o){throw o instanceof Yn?new oa(o.message,o.code):o}}createRoom(e,n){return new Fa(e,n)}buildEndpoint(e,n={}){let r=this.settings.protocol||"ws",s=this.settings.searchParams||"";this.http.authToken&&(n._authToken=this.http.authToken);for(let a in n)n.hasOwnProperty(a)&&(s+=(s?"&":"")+`${a}=${n[a]}`);r==="h3"&&(r="http");let o=this.settings.secure?`${r}s://`:`${r}://`;e.publicAddress?o+=`${e.publicAddress}`:o+=`${this.settings.hostname}${this.getEndpointPort()}${this.settings.pathname}`;let i=`${o}/${e.processId}/${e.roomId}?${s}`;return this.urlBuilder?this.urlBuilder(new URL(i)):i}getHttpEndpoint(e=""){let n=e.startsWith("/")?e:`/${e}`,r=`${this.settings.secure?"https":"http"}://${this.settings.hostname}${this.getEndpointPort()}${this.settings.pathname}${n}`;return this.settings.searchParams&&(r+=`?${this.settings.searchParams}`),this.urlBuilder?this.urlBuilder(new URL(r)):r}getEndpointPort(){return this.settings.port!==80&&this.settings.port!==443?`:${this.settings.port}`:""}};m(dl,"VERSION","0.18");var ll=dl,es=ll;yr();var fl=class{setState(e){}getState(){return null}patch(e){}teardown(){}handshake(e){}};wt();_p();gl();bl();yl();up("schema",Qo);up("none",fl);var KL=Object.freeze({min:3,max:3}),XL=Object.freeze({min:4,max:4});var mi={PLAY:"play",QUEUE:"queue",MATCH:"match",AUTHORITY:"authority"};var Gb={CAPS:"caps"},yn={PHYSICS:"physics@1",PHYSICS_PREDICT:"physics@2",INPUT_REPEAT:"repeat@1",LIFTS:"lifts@1",INPUT_TICK:"tick@1",FAST:"fast@1",MAX_CAPS:16,MAX_CAP_CHARS:32};var YP=["clients","preset","winCondition","config","matchmade"],JL=[...YP,"moduleSha","tickHz","maxPlayers","lagComp","seed","units","leaseId","region"],Ka={BAD_OPTION:400,AUTH_REQUIRED:401,FORBIDDEN:403,PROTOCOL_UNSUPPORTED:426,NOT_ENTITLED:402,ROOM_QUOTA:429,MODULE_UNAVAILABLE:424,AUTHORITY_CAPACITY:503};var le={STATE:"state",STATE_SNAP:"__state:snap",SHARED:"shared",CLAIM:"claim",RELEASE:"release",DESTROY:"destroy",OBJECT:"obj",OBJECT_SNAP:"__object:snap",INPUT:"__input",ROOM_OPEN:"__room:open",CHAT:"__chat",CHAT_HISTORY_REQUEST:"__chat:history:request",VOICE_ICE_REQUEST:"__voice:ice:request",VOICE_JOIN:"__voice:join",VOICE_LEAVE:"__voice:leave",VOICE_SIGNAL:"__voice:signal",MATCH_ELIMINATED:"match:eliminated",MATCH_SCORE:"match:score",MATCH_FINISH:"match:finish",POSE:"__pose",POSE_SNAP:"__pose:snap"},xe={OBJECT_RESULT:"__object:result",INPUT:"__input",ROOM_OPEN:"__room:open",CHAT:"__chat",CHAT_HISTORY:"__chat:history",VOICE_ICE:"__voice:ice",VOICE_SIGNAL:"__voice:signal",VOICE_REJECTED:"__voice:rejected",RATE_DROP:"rate:drop",SERVER_RESTART:"server:restart",MATCH_START:"match:start",MATCH_ENDED:"match:ended",MATCH_REQUEUE:"match:requeue",QUEUE:"queue",SEAT:"seat"},KP=["__","match:","server:","rate:"],XP=["state","shared","claim","release","destroy","obj","queue","seat"];function ns(t){return XP.includes(t)||KP.some(e=>t.startsWith(e))}var Rl="__",ar="__t";var ZL={[le.STATE]:"state",[le.STATE_SNAP]:"state",[le.SHARED]:"bulk",[le.CLAIM]:"control",[le.RELEASE]:"control",[le.DESTROY]:"control",[le.OBJECT]:"bulk",[le.OBJECT_SNAP]:"bulk",[le.INPUT]:"input",[le.ROOM_OPEN]:"control",[le.CHAT]:"chat",[le.CHAT_HISTORY_REQUEST]:"control",[le.VOICE_ICE_REQUEST]:"voice",[le.VOICE_JOIN]:"voice",[le.VOICE_LEAVE]:"voice",[le.VOICE_SIGNAL]:"voice",[le.MATCH_ELIMINATED]:"bulk",[le.MATCH_SCORE]:"bulk",[le.MATCH_FINISH]:"bulk",[le.POSE]:"pose",[le.POSE_SNAP]:"pose"},Xa={GOING_AWAY:1001,NO_STATUS:1005,ABNORMAL:1006,MAY_TRY_RECONNECT:4010,NORMAL:1e3,CONSENTED:4e3,MATCH_BOOT:4e3,SERVER_SHUTDOWN:4001,WITH_ERROR:4002,FAILED_TO_RECONNECT:4003,REVOKED:4401,SUPERSEDED:4409,MODULE_HALTED:4500,MODULE_FAULT:4501},$t={ROOM_MAX_CLIENTS:64,MAX_NAME_CHARS:64,MAX_AVATAR_URL_CHARS:512,MAX_UID_CHARS:64,MAX_STATE_BYTES:16*1024,MAX_SHARED_KEY_CHARS:256,MAX_SHARED_VALUE_BYTES:64*1024,MAX_SHARED_KEYS:256,MAX_OBJECT_ID_CHARS:128,MAX_OBJECT_STATE_BYTES:64*1024,MAX_OBJECTS:128,MAX_REQUEST_ID_CHARS:96,MAX_EVENT_BYTES:16*1024,MAX_EVENT_TYPE_CHARS:128,MAX_JSON_DEPTH:32,MAX_JSON_NODES:4096,MAX_CHAT_CHARS:500,CHAT_HISTORY_MAX:50,CHAT_HISTORY_MAX_BYTES:8*1024,MAX_VOICE_PARTICIPANTS:6,MAX_VOICE_SIGNAL_BYTES:8*1024,MAX_SCORE_DELTA:1e3,CONTROL_RESULTS_PER_SESSION:128,CONTROL_RESULT_TTL_MS:6e4,MAX_TEAMS:8,MAX_ANIM_CHARS:64,MAX_POSE_ABS:1e9},QL={PATCH_INTERVAL_MS:1e3/30,RECONNECT_GRACE_S:30,GOING_AWAY_GRACE_S:5,HOST_FAILOVER_GRACE_MS:1500,MIN_OWNERSHIP_HOLD_MS:300,SHUTDOWN_DRAIN_MS:3e3,REQUEUE_GRACE_MS:5e3,SEAT_RESERVATION_S:15,QUEUE_TICK_MS:1e3,REVOCATION_SWEEP_MS:3e4},rs={TICK_HZ:30,RENDER_DELAY_MS:100,MAX_REWIND_MS:500,INPUT_BUFFER:32,PATCH_INTERVAL_MS:50,INPUT_REPEAT_MAX_MS:100,INPUT_REPEAT_RUN_MS:33},gn={enabled:!0,minUptime:0,delay:125,minDelay:100,maxDelay:4e3,maxRetries:9,maxEnqueuedMessages:0,firstStateTimeoutMs:2e3},Wb=["x","y","z","yaw","vx","vy","vz","anim"],qe={RATIO:1.5,JITTER_SAFETY:1.25,MIN_MS:90,MAX_MS:300,DEFAULT_MS:100,EASE:.1,CLOCK_WINDOW:80,CLOCK_WINDOW_MS:5e3,CLOCK_WINDOW_MAX:4096,INTERVAL_WINDOW:30,MIN_GAP_MS:5,MAX_GAP_MS:2e3,HISTORY_MS:1500,MAX_EXTRAP_MS:250,ROT_EXTRAP_MS:150,SMOOTH_TAU_POS_MS:30,SMOOTH_TAU_ROT_MS:70,POISON_GUARD_MS:2e3,REBASE_AFTER_GAP_MS:1e3,MAX_HOST_TICK_DT_MS:250},Pr={HEARTBEAT_HZ:10,MIN_HEARTBEAT_HZ:5,MAX_HEARTBEAT_HZ:20,HEARTBEAT_DITHER:.15,RELAY_BUFFER:4,WARMUP_ACKS:30};var Ys={SAMPLES:3,TIMEOUT_MS:4e3,GRACE_MS:1e3};async function Yb(t,e={}){let n=t[0];if(n===void 0)throw new Error("genex multiplayer: `urls` must contain at least one relay URL");if(t.length===1)return n;let r=e.probe??Rp,s=Math.max(1,e.samples??Ys.SAMPLES),o=e.timeoutMs??Ys.TIMEOUT_MS,i=e.graceMs??Ys.GRACE_MS,a=t.map(()=>{});await new Promise(u=>{let l=t.length*s,d,f=setTimeout(h,o);function h(){clearTimeout(f),clearTimeout(d),u()}let p=()=>{--l===0&&h()};t.forEach((g,x)=>{for(let b=0;b<s;b++){let S;try{S=r(g,o)}catch(_){S=Promise.reject(_)}S.then(_=>{Number.isFinite(_)&&_>=0&&(a[x]=Math.min(a[x]??1/0,_),d??(d=setTimeout(h,i))),p()},p)}})});let c=-1;return a.forEach((u,l)=>{u!==void 0&&(c<0||u<a[c])&&(c=l)}),c<0?(console.warn(`genex multiplayer: no relay answered the latency probe \u2014 connecting to ${n}`),n):t[c]}var Rp=(t,e)=>new es(t).getLatency({pingCount:1,timeout:e});var JP=t=>typeof t=="function"?t():t;async function Ja(t){return t.url?new es(t.url):new es(await Yb(t.urls))}function Za(t,e,n){return{gameId:t,name:e,embedToken:JP(n)?.embedToken,protocol:3}}var Qa=t=>!!t&&typeof t=="object"&&t.code===Ka.PROTOCOL_UNSUPPORTED,kp=()=>console.error(`[multiplayer] the relay refused protocol ${3} (code 426) \u2014 this game was built with a @genex-ai/multiplayer that this relay no longer serves. Update the package and republish.`),Kb=t=>{throw Qa(t)&&kp(),t};function Xb(t,e){let n=null,r=null;return{request(){return n||(n=new Promise(s=>{let o,i=a=>{r&&(r=null,n=null,o&&clearTimeout(o),s(a))};r=i,o=setTimeout(()=>i(null),e),t()}),n)},deliver(s){r?.(s)},get pending(){return n!==null}}}var Jb=["x","y","z","yaw","vx","vy","vz"],Zb=[["x","vx"],["y","vy"],["z","vz"]],Pp=Math.PI*2,ZP=t=>Wb.includes(t);function Ap(t){if(!Number.isFinite(t))return 0;let e=t%Pp;return e<=-Math.PI?e+=Pp:e>Math.PI&&(e-=Pp),e}var Qb=t=>typeof t=="number"&&Number.isFinite(t)&&Math.abs(t)<=$t.MAX_POSE_ABS;function e0(t){let e={},n={},r=[];for(let s of Object.keys(t)){let o=t[s];if(!ZP(s)){n[s]=o;continue}o!==void 0&&(s==="anim"?typeof o=="string"&&o.length<=$t.MAX_ANIM_CHARS?e.anim=o:r.push(s):Qb(o)?e[s]=o:r.push(s))}return{pose:e,data:n,invalid:r}}function t0(t){for(let e in t)if(t[e]!==void 0)return!0;return!1}function n0(t,e,n){let r={...t},s={t:e},o=n?e-n.t:0,i=n!==void 0&&o>qe.MIN_GAP_MS&&o<qe.MAX_GAP_MS;for(let[a,c]of Zb){let u=t[a];if(u===void 0||(s[a]=u,t[c]!==void 0))continue;let l=n?.[a],d=i&&l!==void 0?(u-l)/o*1e3:0;r[c]=Qb(d)?d:0}return{pose:r,memory:s}}function vl(t){let e=n=>typeof n=="number"&&Number.isFinite(n)?n:0;return{x:e(t.x),y:e(t.y),z:e(t.z),yaw:e(t.yaw),vx:e(t.vx),vy:e(t.vy),vz:e(t.vz),anim:typeof t.anim=="string"?t.anim:""}}var yi=(t,e)=>{let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:0};function r0(t,e){let n=t.length;if(n===0)return;let r=0;for(;r<n&&t[r].t<=e;)r++;if(r===0)return t[0].state;if(r>=n){let u=t[n-1],l={...u.state},d=Math.min(Math.max(0,e-u.t),qe.MAX_EXTRAP_MS)/1e3;for(let[f,h]of Zb)l[f]=yi(u.state,f)+yi(u.state,h)*d;if(n>=2){let f=t[n-2],h=u.t-f.t;if(h>0){let p=Math.min(Math.max(0,e-u.t),qe.ROT_EXTRAP_MS)/h,g=yi(u.state,"yaw");l.yaw=g+Ap(g-yi(f.state,"yaw"))*p}}return l}let s=t[r-1],o=t[r],i=o.t-s.t,a=i>0?(e-s.t)/i:1,c={...s.state};for(let u of Jb){let l=yi(s.state,u),d=yi(o.state,u);c[u]=u==="yaw"?l+Ap(d-l)*a:l+(d-l)*a}return c}function s0(t,e,n,r){let s={...e};for(let o of Jb){let i=t[o],a=e[o];typeof i!="number"||typeof a!="number"||!Number.isFinite(i)||!Number.isFinite(a)||(s[o]=o==="yaw"?i+Ap(a-i)*r:i+(a-i)*n)}return s}var Al=class Al{constructor(){m(this,"pending",[]);m(this,"current")}push(e,n){for(this.pending.push({t:e,state:n});this.pending.length>Al.MAX_PENDING;)this.current=this.pending.shift()?.state}at(e){for(;this.pending.length>0;){let n=this.pending[0];if(this.current!==void 0&&e!==void 0&&n.t!==void 0&&n.t>e)break;this.current=n.state,this.pending.shift()}return this.current}flush(){this.at(void 0)}};m(Al,"MAX_PENDING",64);var Pl=Al;function o0(t){try{let e=t.input();return e&&typeof e.send=="function"?e:null}catch{return null}}function i0(t,e,n=Pr.HEARTBEAT_HZ,r=Math.random){let o=1e3/Math.min(Pr.MAX_HEARTBEAT_HZ,Math.max(Pr.MIN_HEARTBEAT_HZ,n)),i=1e3/Pr.MAX_HEARTBEAT_HZ,a=1e3/Pr.MIN_HEARTBEAT_HZ,c=!1,u=!1,l,d=()=>{if(u)return;if(e()){try{t.send()}catch{}!c&&t.lastProcessed>=Pr.WARMUP_ACKS&&(c=!0)}let f=o*(1+(r()*2-1)*Pr.HEARTBEAT_DITHER);l=setTimeout(d,Math.min(a,Math.max(i,f)))};return d(),{get synced(){return!c&&t.lastProcessed>=Pr.WARMUP_ACKS&&(c=!0),c},stop(){u=!0,l&&clearTimeout(l)}}}function a0(t,e){return e.synced&&e.clockOrigin>0&&e.serverNow!==void 0&&Number.isFinite(e.serverNow)?t-e.clockOrigin-e.serverNow:t-e.wallNow}function Ks(t){let e=t.reconnection;return e.enabled=gn.enabled,e.minUptime=gn.minUptime,e.delay=gn.delay,e.minDelay=gn.minDelay,e.maxDelay=gn.maxDelay,e.maxRetries=gn.maxRetries,e.maxEnqueuedMessages=gn.maxEnqueuedMessages,e.enqueuedMessages.length=0,t}function c0(t){return t.reconnection.enabled=!1,t}function Tl(t,e){return new Promise(n=>{let r=()=>{clearTimeout(s),n(!0)},s=setTimeout(()=>{t.onStateChange.remove(r),n(!1)},e);t.onStateChange.once(r)})}function u0(t,e,n){return t!==e&&n!=null}var QP="The microphone was refused by the page that frames this game, not by the player: the frame was not given it, so the browser never asked. On its Genex page a build is given the microphone only when it declares it. An up-to-date genex CLI declares it at `genex preview` and `genex publish` when the game's own source calls voice.join(); to declare it by hand, add \"microphone\" to genex.capabilities in the game's package.json. Then preview or publish again.",vp=class extends Error{constructor(e){super(QP,{cause:e}),this.name="VoiceNotDelegatedError"}},l0=[{urls:"stun:stun.l.google.com:19302"}],eA=120,d0=.02,tA=.6,Ml=class{constructor(e){m(this,"transport");m(this,"peers",new Map);m(this,"listeners",new Set);m(this,"roster",[]);m(this,"local",null);m(this,"audio",null);m(this,"localAnalyser",null);m(this,"levelTimer",null);m(this,"iceServers",l0);m(this,"spatial",!1);m(this,"threshold",d0);m(this,"micOn",!0);m(this,"selfSpeaking",!1);m(this,"running",!1);m(this,"peeringHeld",!1);this.transport=e}get active(){return this.running}get micEnabled(){return this.micOn}get speaking(){return this.selfSpeaking}get participants(){return[...this.peers.values()].map(e=>({id:e.id,name:this.transport.nameOf(e.id),stream:e.stream,speaking:e.speaking,muted:e.muted,volume:e.volume,connection:e.connection}))}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async start(e={},n=!1){if(!this.running){this.peeringHeld=n,this.iceServers=e.iceServers?.length?e.iceServers:l0,this.spatial=e.spatial===!0,this.threshold=e.speakingThreshold??d0,this.micOn=e.startMuted!==!0;try{this.local=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},video:!1})}catch(r){throw rA(r)}for(let r of this.local.getAudioTracks())r.enabled=this.micOn;this.audio=new AudioContext,this.localAnalyser=this.makeAnalyser(this.local),this.running=!0,this.levelTimer=setInterval(()=>this.pollLevels(),eA)}}stop(){this.running=!1,this.peeringHeld=!1,this.levelTimer&&(clearInterval(this.levelTimer),this.levelTimer=null);for(let e of[...this.peers.keys()])this.destroyPeer(e);for(let e of this.local?.getTracks()??[])e.stop();this.local=null,this.localAnalyser=null,this.audio?.close().catch(()=>{}),this.audio=null,this.roster=[],this.selfSpeaking=!1,this.emit()}setIceServers(e){if(e.length){this.iceServers=e;for(let n of this.peers.values())try{n.pc.setConfiguration({iceServers:e})}catch{}}}releasePeering(){this.peeringHeld&&(this.peeringHeld=!1,this.setRoster(this.roster))}setRoster(e){if(this.roster=e,!this.running||this.peeringHeld)return;let n=this.transport.selfId(),r=new Set(e.filter(s=>s!==n));for(let s of r)this.peers.has(s)||this.createPeer(s);for(let s of[...this.peers.keys()])r.has(s)||this.destroyPeer(s);this.emit()}setMicEnabled(e){this.micOn=e;for(let n of this.local?.getAudioTracks()??[])n.enabled=e;!e&&this.selfSpeaking&&(this.selfSpeaking=!1,this.emit())}mute(e){this.setMuted(e,!0)}unmute(e){this.setMuted(e,!1)}setVolume(e,n){let r=this.peers.get(e);r&&(r.volume=Math.max(0,Math.min(1,n)),r.el&&(r.el.volume=r.volume),this.emit())}async handleSignal(e,n){if(!this.running)return;let r=n;if(!r||typeof r!="object"||typeof r.t!="string")return;let s=this.peers.get(e)??(this.roster.includes(e)?this.createPeer(e):void 0);if(s)try{if(r.t==="offer"){await s.pc.setRemoteDescription(r.sdp),await this.flushIce(s);let o=await s.pc.createAnswer();await s.pc.setLocalDescription(o),this.transport.sendSignal(e,{t:"answer",sdp:o})}else if(r.t==="answer"){if(s.pc.signalingState!=="have-local-offer")return;await s.pc.setRemoteDescription(r.sdp),await this.flushIce(s)}else r.t==="ice"&&(s.pc.remoteDescription?await s.pc.addIceCandidate(r.c):s.pendingIce.push(r.c))}catch(o){console.warn(`[multiplayer] voice signaling failed with ${e}`,o)}}setMuted(e,n){let r=this.peers.get(e);!r||r.muted===n||(r.muted=n,r.el&&(r.el.muted=n||this.spatial),n&&r.speaking&&(r.speaking=!1),this.emit())}createPeer(e){let n=new RTCPeerConnection({iceServers:this.iceServers}),r={id:e,pc:n,el:null,stream:null,analyser:null,pendingIce:[],speaking:!1,muted:!1,volume:1,connection:"connecting"};this.peers.set(e,r);for(let s of this.local?.getAudioTracks()??[])this.local&&n.addTrack(s,this.local);return n.onicecandidate=s=>{s.candidate&&this.transport.sendSignal(e,{t:"ice",c:s.candidate.toJSON()})},n.ontrack=s=>{let o=s.streams[0]??new MediaStream([s.track]);r.stream=o,r.el=this.attachSink(o,r),r.analyser=this.makeAnalyser(o),this.emit()},n.onconnectionstatechange=()=>{let s=n.connectionState,o=s==="connected"?"connected":s==="failed"||s==="closed"?"failed":"connecting";if(o!==r.connection){if(r.connection=o,o==="failed"){let i=this.iceServers.some(a=>sA(a));console.warn(`[multiplayer] voice connection to ${e} failed`+(i?"":" \u2014 no TURN in the ICE list (relay offered none?)"))}this.emit()}},this.transport.selfId()<e&&this.offer(r),r}async offer(e){try{let n=await e.pc.createOffer();await e.pc.setLocalDescription(n),this.transport.sendSignal(e.id,{t:"offer",sdp:n})}catch(n){console.warn(`[multiplayer] voice offer to ${e.id} failed`,n)}}async flushIce(e){let n=e.pendingIce.splice(0);for(let r of n)try{await e.pc.addIceCandidate(r)}catch{}}destroyPeer(e){let n=this.peers.get(e);if(n){this.peers.delete(e),n.pc.onicecandidate=null,n.pc.ontrack=null,n.pc.onconnectionstatechange=null;try{n.pc.close()}catch{}n.el&&(n.el.srcObject=null,n.el.remove())}}attachSink(e,n){let r=document.createElement("audio");return r.autoplay=!0,r.srcObject=e,r.muted=this.spatial||n.muted,r.volume=n.volume,r.style.display="none",document.body.appendChild(r),r.play().catch(s=>{console.warn("[multiplayer] voice playback was blocked \u2014 join voice from a click/tap",s)}),r}makeAnalyser(e){if(!this.audio)return null;try{let n=this.audio.createMediaStreamSource(e),r=this.audio.createAnalyser();return r.fftSize=512,n.connect(r),r}catch{return null}}pollLevels(){let e=!1,n=this.micOn?f0(this.localAnalyser):0,r=this.crossed(n,this.selfSpeaking);r!==this.selfSpeaking&&(this.selfSpeaking=r,e=!0);for(let s of this.peers.values()){let o=s.muted?!1:this.crossed(f0(s.analyser),s.speaking);o!==s.speaking&&(s.speaking=o,e=!0)}e&&this.emit()}crossed(e,n){return e>=(n?this.threshold*tA:this.threshold)}emit(){for(let e of[...this.listeners])try{e()}catch(n){console.error("[multiplayer] a voice listener threw",n)}}};function nA(){try{return window.self!==window.top}catch{return!0}}function rA(t){if(t?.name!=="NotAllowedError")return t;try{if(!nA()||document.featurePolicy?.allowsFeature?.("microphone")!==!1)return t}catch{return t}return new vp(t)}function sA(t){return(Array.isArray(t.urls)?t.urls:[t.urls]).some(n=>typeof n=="string"&&n.startsWith("turn"))}function f0(t){if(!t)return 0;let e=new Uint8Array(t.fftSize);t.getByteTimeDomainData(e);let n=0;for(let r=0;r<e.length;r++){let s=((e[r]??128)-128)/128;n+=s*s}return Math.sqrt(n/e.length)}var Tp=Symbol("genex.roomRef"),Ar=t=>t[Tp]();var oA=qe.RATIO,iA=qe.MIN_MS,aA=qe.MAX_MS,Cl=qe.DEFAULT_MS,cA=qe.JITTER_SAFETY,uA=qe.POISON_GUARD_MS,lA=qe.EASE,dA=qe.MAX_EXTRAP_MS,fA=qe.ROT_EXTRAP_MS,h0=qe.CLOCK_WINDOW,pA=qe.CLOCK_WINDOW_MS,hA=qe.CLOCK_WINDOW_MAX,mA=qe.INTERVAL_WINDOW,yA=qe.MIN_GAP_MS,gA=qe.MAX_GAP_MS,bA=qe.HISTORY_MS,wA=qe.SMOOTH_TAU_POS_MS,xA=qe.SMOOTH_TAU_ROT_MS,m0=qe.MAX_HOST_TICK_DT_MS,SA=qe.REBASE_AFTER_GAP_MS,cr="obj:",EA=3e3,_A=5e3,RA=6e4,kA=2e3;function b0(t){if(t==="predict")return{mode:"lerp"};if(t&&typeof t=="object"&&t.engine==="predict")return{mode:t.mode==="damped"?"damped":"lerp",delay:t.delay,smoothMs:t.smoothMs}}var Dl=async t=>b0(t)?Promise.resolve().then(()=>(Mp(),p0)):void 0;function y0(t){if(!t)return{state:{}};try{let e=JSON.parse(t);if(!e||typeof e!="object")return{state:{}};let n=e,r=n[ar];if(typeof r=="number"&&Number.isFinite(r)){let s={...n};return delete s[ar],{state:s,sendTime:r}}return{state:n}}catch{return{state:{}}}}function Ol(t){if(t!=null)try{return JSON.parse(t)}catch{return}}var PA=(t,e)=>typeof e=="number"?Number.isFinite(e)?e:0:typeof e=="bigint"?Number(e):e;function gi(t){return JSON.parse(JSON.stringify(t,PA))}var Xs=()=>typeof performance<"u"&&performance.now?performance.now():Date.now();function w0(t,e,n){let[r,s,o,i]=e,[a,c,u,l]=t,d=a*r+c*s+u*o+l*i;if(d<0&&(r=-r,s=-s,o=-o,i=-i,d=-d),d>.9995){let x=a+(r-a)*n,b=c+(s-c)*n,S=u+(o-u)*n,_=l+(i-l)*n,P=Math.hypot(x,b,S,_)||1;return[x/P,b/P,S/P,_/P]}let f=Math.acos(d),h=Math.sin(f),p=Math.sin(f-f*n)/h,g=Math.sin(f*n)/h;return[a*p+r*g,c*p+s*g,u*p+o*g,l*p+i*g]}function Il(t){return Array.isArray(t)&&t.length===4&&t.every(e=>typeof e=="number"&&Number.isFinite(e))}function g0(t,e,n,r){let s={},o=n<1;for(let i in e){let a=t[i],c=e[i];typeof a=="number"&&typeof c=="number"&&Number.isFinite(a)&&Number.isFinite(c)?s[i]=a+(c-a)*n:Il(a)&&Il(c)?s[i]=w0(a,c,r):s[i]=o&&i in t?a:c}return s}function AA(t,e,n,r){let s={};for(let o in e){let i=e[o],a=t[o];typeof a=="number"&&typeof i=="number"&&Number.isFinite(a)&&Number.isFinite(i)?s[o]=a+(i-a)*n:Il(a)&&Il(i)?s[o]=w0(a,i,r):s[o]=i}return s}function vA(t,e){let n=t.length;if(n===0)return;if(n===1)return t[0].state;let r=0;for(;r<n&&t[r].t<=e;)r++;if(r===0)return t[0].state;if(r>=n){let c=t[n-2],u=t[n-1],l=u.t-c.t;if(l<=0)return u.state;let d=(Math.min(e,u.t+dA)-c.t)/l,f=(Math.min(e,u.t+fA)-c.t)/l;return g0(c.state,u.state,d,f)}let s=t[r-1],o=t[r],i=o.t-s.t,a=i>0?(e-s.t)/i:1;return g0(s.state,o.state,a,a)}function TA(t){if(t.length===0)return 66;let e=[...t].sort((n,r)=>n-r);return e[e.length>>1]}function MA(t,e){if(t.length===0)return 0;let n=[...t].sort((s,o)=>s-o),r=Math.min(n.length-1,Math.max(0,Math.round(e*(n.length-1))));return n[r]}async function x0(t){let e=await Ja(t),n=await Dl(t.smoothing),r=Ks(await e.joinOrCreate(mi.PLAY,{...Za(t.room,t.name,t.auth),...t.options,protocol:3}).catch(Kb));return Cp(r,{pose:t.pose,smoothing:t.smoothing,predict:n})}var CA=t=>typeof t=="string"&&t.length>0&&t.length<=$t.MAX_EVENT_TYPE_CHARS&&!ns(t),OA=new Set(["join","leave","change","shared","object","host","reconnecting","reconnected","disconnect","room:open","voice","voice:rejected"]),IA=new Set([xe.OBJECT_RESULT,xe.INPUT,xe.ROOM_OPEN,xe.CHAT,xe.CHAT_HISTORY,xe.VOICE_ICE,xe.VOICE_SIGNAL,xe.VOICE_REJECTED,xe.RATE_DROP,...Object.values(le)]),DA=[500,1e3,2e3,4e3,8e3];function Cp(t,e={}){let n=new Map,r=new Map,s=new Map,o=new Map,i=new Map,a=new Map,c=new Set,u=new Map,l=new Map,d=new Map,f=new Map,h,p=new Map,g=new Map,x=new Map,b=new Map,S=new Map,_=new Map,P=new Map,R=new Map,v=new Set,M=new Map,O,z=0,X=new Map,N=w=>{for(let T of X.values())if(T.id===w)return!0;return!1},Y=typeof globalThis<"u"&&globalThis.__GENEX_MP_TEST_SKEW__||0,he=Y?()=>Xs()+Y:Xs,A=(w,T)=>{if(p.get(T)===t.sessionId)return!1;let F=`${w}:${T}`;return v.has(F)||(v.add(F),console.warn(`[multiplayer] objects.${w}('${T}') ignored because this session does not own the object \u2014 await objects.claimConfirmed('${T}') and check accepted before publishing`)),!0},W=(w,T,F,Z)=>{let _e=he(),de=F,Pe=_e-F,re=o.get(Z);re||o.set(Z,re={samples:[],mins:[],n:0});let Oe=++re.n;for(re.samples.push({at:_e,n:Oe});re.mins.length>0&&re.mins[re.mins.length-1].v>=Pe;)re.mins.pop();for(re.mins.push({v:Pe,n:Oe});re.samples.length>hA||re.samples.length>h0&&re.samples[0].at<_e-pA;)re.samples.shift();let Me=re.samples[0].n;for(;re.mins[0].n<Me;)re.mins.shift();s.set(Z,re.mins[0].v);let Je=i.get(w);Je||i.set(w,Je=[]),Je.push(Pe),Je.length>h0&&Je.shift(),a.set(w,Z);let Yt=r.get(w);if(r.set(w,de),Yt!=null){let Rt=de-Yt;if(Rt>yA&&Rt<gA){let Fr=d.get(w);Fr||d.set(w,Fr=[]),Fr.push(Rt),Fr.length>mA&&Fr.shift();let zc=Je.length>=8?Math.max(0,MA(Je,.9)-re.mins[0].v):0,pr=Math.min(aA,Math.max(iA,oA*TA(Fr),cA*zc)),Uc=f.get(w)??Cl;f.set(w,Uc+(pr-Uc)*lA)}}let $e=n.get(w);$e||n.set(w,$e=[]);let _s=M.get(w);if(_s&&$e.length===0){let Rt=f.get(w)??Cl;$e.push({t:de-Math.max(1,Rt),state:_s})}M.delete(w),$e.push({t:de,state:T});let Ct=de-bA;for(;$e.length>2&&$e[0].t<Ct;)$e.shift();for(;$e.length>1&&$e[0].t>$e[$e.length-1].t+uA;)$e.shift()},G=(w,T)=>{let F=a.get(w),Z=F===void 0?void 0:s.get(F);if(Z!==void 0)return T-Z-(f.get(w)??Cl)},$=(w,T)=>{let F=n.get(w),Z=G(w,T)??T-Cl,_e=c.has(w),de=F&&(_e?r0(F,Z):vA(F,Z));if(!de)return u.get(w);let Pe=u.get(w),re;if(Pe){let Oe=Math.min(m0,Math.max(0,T-(l.get(w)??T))),Me=1-Math.exp(-Oe/wA),Je=1-Math.exp(-Oe/xA);re=_e?s0(Pe,de,Me,Je):AA(Pe,de,Me,Je)}else re=de;return u.set(w,re),l.set(w,T),re},j=w=>{n.delete(w),r.delete(w),a.delete(w),u.delete(w),l.delete(w),d.delete(w),f.delete(w),i.delete(w),M.delete(w)},se=w=>{n.delete(w),r.delete(w),a.delete(w),d.delete(w),f.delete(w),i.delete(w)},oe=w=>{s.delete(w),o.delete(w)},ne=new Map,ye=new Set,ue=(w,...T)=>ne.get(w)?.forEach(F=>{try{F(...T)}catch(Z){console.error(`[multiplayer] a '${w}' listener threw:`,Z)}}),yt=new Map,Gt=(w,T)=>{yt.get(T)!==w&&(yt.set(T,w),ue("shared",T,Ol(w)))},Hn=w=>{let T=w||void 0;T!==O&&(O=T,ue("host",O))},Li="",hs=()=>{let w=t.state?.voice?[...t.state.voice.keys()].sort():[],T=w.join(`
14
+ `);T!==Li&&(Li=T,Le.setRoster(w),ue("voice",Le.participants))},ms=(w,T)=>{let F=cr+w,Z=t.sessionId,_e=b.has(w),de=T.owner||void 0,Pe=Number.isFinite(T.seq)?T.seq:0,re=Number.isFinite(T.epoch)?T.epoch:0,Oe=Number.isFinite(T.t)?T.t:0,Me=typeof T.d=="string"?T.d:"",Yt=de!==g.get(w)||_e&&Pe!==b.get(w),$e=x.has(w)&&re!==x.get(w),_s=Oe!==S.get(w);if(b.set(w,Pe),x.set(w,re),S.set(w,Oe),Me!==_.get(w)){_.set(w,Me);let Rt=Me?Ol(Me):void 0;Rt&&typeof Rt=="object"&&!Array.isArray(Rt)&&P.set(w,Rt)}de?g.set(w,de):g.delete(w),(Yt||p.get(w)!==de&&!N(w))&&(de?p.set(w,de):p.delete(w)),$e&&j(F),Yt&&de!==Z&&(R.delete(w),$e||se(F));let Ct=P.get(w);if(Ct&&de!==Z){let Rt=Oe!==0&&_s&&de!==void 0;$e?(u.set(F,Ct),l.set(F,he()),Rt&&W(F,Ct,Oe,de)):(Yt&&M.set(F,u.get(F)??Ct),Rt&&W(F,Ct,Oe,de))}(!_e||Yt)&&ue("object",w)},Fi=w=>{let T=b.has(w)||p.has(w)||P.has(w)||R.has(w);j(cr+w),P.delete(w),p.delete(w),g.delete(w),x.delete(w),b.delete(w),S.delete(w),_.delete(w),R.delete(w),T&&ue("object",w)},zi=new Map,ys=new Map,Ui=new Map,Nr=(w,T)=>{if(!T)return{};let F=zi.get(w);if(F&&F.raw===T)return F.state;let{state:Z}=y0(T);return zi.set(w,{raw:T,state:Z}),Z},Wt=new Map,gs=new Map,Et=e.predict?b0(e.smoothing):void 0,cn,$n=new Map,Rd=(w,T)=>{if(!Et||!e.predict)return;cn??(cn=e.predict.Predict.get(t));let F={mode:Et.mode,delay:Et.delay,smoothMs:Et.smoothMs};cn.attach(T,{x:F,y:F,z:F,vx:F,vy:F,vz:F}),cn.attach(T,{yaw:{...F,angle:!0}}),$n.set(w,T)},Vi=w=>{let T=$n.get(w);T&&cn&&cn.detach(T),$n.delete(w)},Oc=w=>{let T=cn;return{x:T.value(w,"x"),y:T.value(w,"y"),z:T.value(w,"z"),yaw:T.value(w,"yaw"),vx:T.value(w,"vx"),vy:T.value(w,"vy"),vz:T.value(w,"vz"),anim:w.anim??""}},un=!1,tt=!1,xn=!0,bs=!1,ho=0,mo=0,Hi=0,yo=new Set,go=()=>yo.forEach(w=>w()),ws=(w,T)=>{if(X.delete(w.requestId),w.timeout&&clearTimeout(w.timeout),w.abort?.(),w.operation==="claim"&&w.optimistic&&!T.accepted){let F=T.owner??g.get(w.id);F?p.set(w.id,F):p.delete(w.id),F!==t.sessionId&&R.delete(w.id)}w.operation==="claim"&&T.accepted&&(p.set(w.id,t.sessionId),se(cr+w.id)),w.operation==="release"&&T.accepted&&(R.delete(w.id),p.get(w.id)===t.sessionId&&p.delete(w.id),se(cr+w.id)),w.operation==="remove"&&T.accepted&&(R.delete(w.id),P.delete(w.id),p.delete(w.id),j(cr+w.id)),w.resolve(T)},fr=(w,T)=>{let F=t.state?.objects?.get(w.id);return{requestId:w.requestId,operation:w.operation,id:w.id,accepted:!1,owner:F?.owner||void 0,sequence:F&&Number.isFinite(F.seq)?F.seq:0,reason:T}},$i=w=>{for(let T of[...X.values()])ws(T,fr(T,w))},Ic=(w,T=!1)=>{if(!T&&!xn)return;let F=w.operation==="claim"?le.CLAIM:w.operation==="release"?le.RELEASE:le.DESTROY;nt(F,w.payload)},jn=(w,T,F={})=>{let Z=String(T),_e=`${t.sessionId.slice(0,12)}:${Date.now().toString(36)}:${(++z).toString(36)}`,de=Math.max(250,Math.min(F.timeoutMs??_A,RA));return new Promise(Pe=>{let re={operation:w,id:Z,requestId:_e,payload:{id:Z,requestId:_e,...F.authority==="host"?{authority:"host"}:{}},optimistic:w==="claim"&&F.optimistic===!0,resolve:Pe,timeout:null,abort:void 0};if(un||tt){Pe(fr(re,un?"aborted":"disconnected"));return}if(re.optimistic&&p.set(Z,t.sessionId),re.timeout=setTimeout(()=>ws(re,fr(re,"timeout")),de),F.signal){let Oe=()=>ws(re,fr(re,"aborted"));F.signal.addEventListener("abort",Oe,{once:!0}),re.abort=()=>F.signal?.removeEventListener("abort",Oe)}if(X.set(_e,re),F.signal?.aborted){ws(re,fr(re,"aborted"));return}Ic(re)})},xs=0,nt=(w,T,F=!1)=>{if(t.connection?.isOpen)try{return t.send(w,T),!0}catch{}return F&&xs++,!1},bo,Dc=0,Bc,Nc=new Set,Lc=(w,T)=>{let{pose:F,data:Z,invalid:_e}=e0(w);for(let Me of _e)Nc.has(Me)||(Nc.add(Me),console.warn(`[multiplayer] me.set: '${Me}' is a typed pose key (pose: true) and its value is not a `+(Me==="anim"?`string of \u2264${$t.MAX_ANIM_CHARS} chars`:"finite number")+" \u2014 it is not sent."));if(!t0(F))return!1;let de=he(),Pe=n0(F,de,T?void 0:Bc);Bc=Pe.memory;let re=JSON.stringify(Z),Oe=T||re!==bo||de-Dc>=kA;return Oe&&nt(le.STATE,JSON.stringify({...Z,[ar]:de}))?(bo=re,Dc=de):Oe&&(bo=void 0),nt(T?le.POSE_SNAP:le.POSE,{...Pe.pose,t:de})||(bo=void 0),!0},Le=new Ml({selfId:()=>t.sessionId,nameOf:w=>t.state?.players?.get(w)?.name??"",sendSignal:(w,T)=>nt(le.VOICE_SIGNAL,{to:w,data:T},!0)});Le.onChange(()=>ue("voice",Le.participants));let Lr=null,ji=Xb(()=>nt(le.VOICE_ICE_REQUEST,{},!0),EA),ln=()=>{Lr&&clearTimeout(Lr),Lr=null},Fc=w=>{ln(),!(typeof w!="number"||!Number.isFinite(w)||w<=0)&&(Lr=setTimeout(()=>{Le.active&&ji.request().then(T=>{!Le.active||!T?.iceServers?.length||(Le.setIceServers(T.iceServers),Fc(T.ttl))})},Math.max(6e4,Math.floor(w*800))))},Sn=[],wo=new Set,xo=new Set,lt=new Set,kd=w=>!!w&&typeof w=="object"&&typeof w.id=="number"&&typeof w.from=="string"&&typeof w.name=="string"&&typeof w.text=="string",Ss=w=>{if(!kd(w)||wo.has(w.id)||lt.has(w.from))return;wo.add(w.id);let T=Sn[Sn.length-1];if(!T||w.id>T.id)Sn.push(w);else{let F=Sn.length;for(;F>0&&(Sn[F-1]?.id??0)>w.id;)F--;Sn.splice(F,0,w)}for(let F of[...xo])try{F(w)}catch(Z){console.error("[multiplayer] a chat listener threw",Z)}},_t=La(t);if(!_t)throw new Error("genex multiplayer: the relay room has no schema state");let So=(w,T,F)=>{let Z=w===t.sessionId,{state:_e,sendTime:de}=y0(T.data),Pe=Number.isFinite(T.epoch)?T.epoch:0,re=ys.has(w)&&Pe!==ys.get(w);ys.set(w,Pe);let Oe=F||T.data!==Ui.get(w);Ui.set(w,T.data);let Me=Number.isFinite(T.poseT)?T.poseT:0,Je=Me!==(gs.get(w)??0);gs.set(w,Me);let Yt=T.posed===!0;if(!Z&&Yt&&!c.has(w)&&(j(w),c.add(w),Wt.set(w,new Pl)),!Z&&re&&(j(w),$n.has(w)&&Vi(w)),ue(F?"join":"change",w,Yt?{..._e,...vl(T)}:_e),!Z){if(Yt){let $e=Wt.get(w);(Oe||re)&&($e.push(de,_e),(re||Et)&&$e.flush()),Et?$n.has(w)||Rd(w,T):Me!==0&&(Je||re)&&W(w,vl(T),Me,w);return}(Oe||re)&&u0(w,t.sessionId,de)&&W(w,_e,de,w)}};_t(t.state).players.onAdd((w,T)=>{So(T,w,!0),_t(w).onChange(()=>So(T,w,!1))});let qi=w=>{ue("leave",w),j(w),oe(w),Vi(w),zi.delete(w),ys.delete(w),Ui.delete(w),gs.delete(w),c.delete(w),Wt.delete(w)};_t(t.state).players.onRemove((w,T)=>qi(T)),_t(t.state).shared.onAdd(Gt),_t(t.state).shared.onChange(Gt),_t(t.state).objects.onAdd((w,T)=>{ms(T,w),_t(w).onChange(()=>ms(T,w))}),_t(t.state).objects.onRemove((w,T)=>Fi(T)),_t(t.state).listen("host",w=>Hn(w)),_t(t.state).voice.onAdd(hs),_t(t.state).voice.onRemove(hs);let Pd=()=>{let w=t.state;if(w){for(let T of new Set([...p.keys(),...P.keys(),...b.keys()]))w.objects?.has(T)||Fi(T);for(let T of[...ys.keys()])w.players?.has(T)||qi(T);Hn(w.host),hs()}};t.onMessage(xe.VOICE_SIGNAL,w=>{w&&typeof w.from=="string"&&Le.handleSignal(w.from,w.data)}),t.onMessage(xe.VOICE_REJECTED,w=>{ln(),Le.stop(),ue("voice:rejected",w??{reason:"full"})}),t.onMessage(xe.VOICE_ICE,w=>{ji.deliver(w??null)}),t.onMessage(xe.CHAT,w=>Ss(w)),t.onMessage(xe.CHAT_HISTORY,w=>{if(Array.isArray(w?.messages))for(let T of w.messages)Ss(T)}),t.onMessage(xe.OBJECT_RESULT,w=>{if(!w||typeof w.requestId!="string")return;let T=X.get(w.requestId);!T||w.operation!==T.operation||w.id!==T.id||ws(T,w)}),t.onMessage(xe.INPUT,w=>{w&&typeof w.from=="string"&&ue(xe.INPUT,w.from,w.d)}),t.onMessage(xe.ROOM_OPEN,w=>{typeof w?.open=="boolean"&&ue("room:open",{open:w.open})}),t.onMessage(xe.RATE_DROP,w=>{console.warn(`[multiplayer] the relay dropped ${w?.dropped??"some"} of your messages in the last second \u2014 you are publishing over budget. Publish idle/unchanged objects at \u22642Hz keepalive, not every tick (see the multiplayer skill's "message budget" section).`)}),t.onMessage(xe.SERVER_RESTART,()=>{}),nt(le.CHAT_HISTORY_REQUEST,{});let Gi=o0(t),En=Gi?i0(Gi,()=>!tt&&!un):void 0,Eo=()=>En?t.clock.serverNow():void 0,Ad=w=>a0(w,{synced:En?.synced===!0,clockOrigin:Number.isFinite(t.state?.clockOrigin)?t.state?.clockOrigin:0,serverNow:Eo(),wallNow:Date.now()}),_o=()=>{En?.stop(),cn?.dispose(),cn=void 0,$n.clear()};t.onDrop(w=>{if(un||tt)return;Hi++,bs||(bs=!0,ho=0,mo=Xs()),xn=!1,go();let{isReconnecting:T,retryCount:F,maxRetries:Z}=t.reconnection;T&&F>=Z||ue("reconnecting",{attempt:++ho,code:w})}),t.onReconnect(()=>{if(tt)return;if(un){t.leave().catch(()=>{});return}let w=Hi;if((mo?Xs()-mo:0)>SA){for(let F of[...n.keys()])j(F);for(let F of[...o.keys()])oe(F)}(async()=>{if(await Tl(t,gn.firstStateTimeoutMs),!(w!==Hi||tt||un)){Pd();for(let F of[...X.values()])Ic(F,!0);nt(le.CHAT_HISTORY_REQUEST,{}),bs=!1,mo=0,xn=!0,go(),ue("reconnected"),xs>0&&(console.warn(`[multiplayer] ${xs} fire-and-forget event(s)/input(s) were dropped while reconnecting \u2014 they are not buffered; player/object state re-synced automatically.`),xs=0)}})()}),t.onLeave(w=>{tt||(tt=!0,xn=!1,bs=!1,_o(),go(),!un&&($i("disconnected"),ue("disconnect",w??1006)))}),t.onError(()=>{});let Wi=((w,T)=>{let F=ne.get(w);return F||ne.set(w,F=new Set),F.add(T),!OA.has(w)&&!IA.has(w)&&!ye.has(w)&&(ye.add(w),t.onMessage(w,Z=>ue(w,Z))),()=>{F?.delete(T)}}),Es={id:t.sessionId,get players(){let w=new Map,T=he();return cn&&$n.size>0&&cn.tick(Xs()),t.state?.players?.forEach((F,Z)=>{let _e=Nr(Z,F.data),de=_e,Pe=_e,re=Wt.get(Z);if(Z!==t.sessionId&&re){let Oe=vl(F);if(Pe={..._e,...Oe},$n.has(Z))de={...re.at(void 0)??_e,...Oc(F)};else{let Me=$(Z,T)??Oe;de={...re.at(G(Z,T))??_e,...Me}}}else Z===t.sessionId?h&&(de=h,Pe=h):de=$(Z,T)??_e;w.set(Z,{id:Z,name:F.name??"",avatarUrl:F.avatarUrl??"",connected:F.connected!==!1,uid:F.uid??"",team:Number.isFinite(F.team)?F.team:-1,state:de,stateRaw:Pe})}),w},get activePlayers(){return new Map([...Es.players].filter(([,w])=>w.connected))},me:{set(w){ar in w&&console.warn(`[multiplayer] '${ar}' is a reserved field name and will be overwritten by the send timestamp \u2014 rename it.`);let T=gi(w);h=T,!(e.pose&&Lc(T,!1))&&nt(le.STATE,JSON.stringify({...T,[ar]:he()}))},snap(w){ar in w&&console.warn(`[multiplayer] '${ar}' is a reserved field name and will be overwritten by the send timestamp \u2014 rename it.`);let T=gi(w);h=T,!(e.pose&&Lc(T,!0))&&nt(le.STATE_SNAP,JSON.stringify({...T,[ar]:he()}))}},shared:{get(w){return Ol(t.state?.shared?.get(w))},set(w,T){w.startsWith(Rl)||nt(le.SHARED,{key:w,value:JSON.stringify(gi(T))})},keys(){return t.state?.shared?Array.from(t.state.shared.keys()):[]}},objects:{claim(w){jn("claim",w,{optimistic:!0})},claimConfirmed(w,T){return jn("claim",w,T)},release(w){let T=String(w);R.delete(T),p.get(T)===t.sessionId&&p.delete(T),se(cr+T),jn("release",T)},releaseConfirmed(w,T){return jn("release",w,T)},remove(w){let T=String(w);p.get(T)===t.sessionId&&(R.delete(T),P.delete(T),p.delete(T),j(cr+T)),jn("remove",T)},removeConfirmed(w,T){return jn("remove",w,T)},set(w,T){let F=String(w);if(A("set",F))return;let Z=gi(T);p.get(F)===t.sessionId&&R.set(F,Z),nt(le.OBJECT,{id:F,d:Z,t:he()})},snap(w,T){let F=String(w);if(A("snap",F))return;let Z=gi(T);p.get(F)===t.sessionId&&R.set(F,Z),nt(le.OBJECT_SNAP,{id:F,d:Z,t:he()})},get(w){let T=String(w),F=p.get(T),Z=R.get(T);if(F===void 0&&!P.has(T)&&!Z)return;let _e=F!==void 0&&F===t.sessionId,de,Pe;return _e&&Z?(de=Z,Pe=Z,u.set(cr+T,Z),l.set(cr+T,he())):(Pe=P.get(T)??{},de=$(cr+T,he())??Pe),{id:T,epoch:x.get(T)??0,owner:F,isMine:_e,state:de,stateRaw:Pe}},ids(){return[...new Set([...p.keys(),...P.keys(),...R.keys()])]}},get isHost(){return xn&&!un&&!tt&&O!==void 0&&O===t.sessionId},get host(){return O},inputs:{send(w){nt(le.INPUT,gi(w),!0)},on(w){let T=ne.get(xe.INPUT);T||ne.set(xe.INPUT,T=new Set);let F=(Z,_e)=>w(Z,_e);return T.add(F),()=>{T?.delete(F)}}},onHostTick(w,T){let F=null,Z=0,_e=Number.isFinite(w)&&w>0?Math.min(w,100):20,de=Math.max(10,Math.round(1e3/_e)),Pe=()=>{let Oe=xn&&!un&&!tt&&O!==void 0&&O===t.sessionId;Oe&&!F?(Z=Xs(),F=setInterval(()=>{let Me=Xs();T(Math.min(Me-Z,m0)),Z=Me},de)):!Oe&&F&&(clearInterval(F),F=null)},re=Wi("host",Pe);return yo.add(Pe),Pe(),()=>{re(),yo.delete(Pe),F&&clearInterval(F),F=null}},on:Wi,send(w,T){if(!CA(w)){console.warn(`[multiplayer] send('${w}') collides with a relay-internal channel \u2014 use a different event name`);return}nt(w,T,!0)},chat:{send(w){typeof w=="string"&&w.trim()&&nt(le.CHAT,{text:w},!0)},on(w){return xo.add(w),()=>xo.delete(w)},get history(){return[...Sn]},mute(w){typeof w=="string"&&w&&lt.add(w)},unmute(w){lt.delete(w)},get muted(){return[...lt]}},voice:{async join(w){if(await Le.start(w,!0),!w?.iceServers?.length){let T=await ji.request();Le.active&&T?.iceServers?.length&&(Le.setIceServers(T.iceServers),Fc(T.ttl))}Le.active&&(nt(le.VOICE_JOIN,{},!0),Le.releasePeering())},leave(){ln(),nt(le.VOICE_LEAVE,{},!0),Le.stop()},get active(){return Le.active},get participants(){return Le.participants},setMicEnabled(w){Le.setMicEnabled(w===!0)},get micEnabled(){return Le.micEnabled},get speaking(){return Le.speaking},mute(w){Le.mute(w)},unmute(w){Le.unmute(w)},setVolume(w,T){Le.setVolume(w,T)},get muted(){return Le.participants.filter(w=>w.muted).map(w=>w.id)}},setRoomOpen(w){nt(le.ROOM_OPEN,{open:w===!0})},leave(){un=!0,_o(),Le.stop(),ln(),xn=!1,go(),$i("aborted"),t.reconnection.enabled=!1,t.leave().catch(()=>{})},serverNow:Eo,get rtt(){if(!En)return;let w=t.clock.smoothedRtt();return w>0?w:void 0},get clockSynced(){return En?.synced===!0},timeUntil:Ad};return Object.defineProperty(Es,Tp,{value:()=>t,enumerable:!1}),Object.defineProperty(Es,Symbol.for("genex.multiplayer.internals"),{enumerable:!1,value:{senderOf:w=>a.get(w),offsetOf:w=>{let T=a.get(w);return T===void 0?void 0:s.get(T)},offsetSamples:w=>o.get(w)?.samples.length??0,bufferLength:w=>n.get(w)?.length??0}}),Es}var BA=[1e3,2e3,4e3],Op=t=>Za(t.room,t.name,t.auth);function S0(t,e,n=r=>r-Date.now()){let r=t?.state?.match,s=r?Ol(r):null,o=s&&typeof s=="object"?s:null;if(!o)return{status:t?"waiting":"searching",role:"player",queue:e,players:[],connectedPlayers:[],opponents:[],teams:{},myTeam:null,scores:{},config:{},winCondition:"lastStanding",championId:null,challengerId:null,roundId:0,winnerId:null,message:t?"Waiting for players\u2026":"Finding a match\u2026",startsAt:null,endsBy:null,startsInMs:null,endsInMs:null};let i=t?.sessionId,a=o.championId??null,c=o.challengerId??null,u=o.teams??{},l=Array.isArray(o.players)?o.players:[],d=o.connectedPlayers??l,f=i!=null&&l.includes(i),h=f?o.phase:"spectating",p=l.filter(v=>v!==i),g=i?Object.keys(u).find(v=>u[v]?.includes(i))??null:null,{winCondition:x,...b}=o.cfg??{},S=v=>typeof v=="number"&&Number.isFinite(v)&&v>0?v:null,_=S(o.startsAt),P=S(o.endsBy),R=v=>v===null?null:Math.max(0,n(v));return{status:h,role:f?"player":"spectator",queue:{position:0,size:0},players:l,connectedPlayers:d,opponents:p,teams:u,myTeam:g,scores:o.scores??{},config:b,winCondition:x?.type??"lastStanding",championId:a,challengerId:c,roundId:o.roundId??0,winnerId:o.winnerId??null,message:o.message??"",startsAt:_,endsBy:P,startsInMs:R(_),endsInMs:R(P)}}function bi(t,e,n){if(t?.connection?.isOpen)try{t.send(e,n)}catch{}}async function E0(t){let e=await Ja(t),n=await Dl(t.smoothing),r=new Map,s=(v,...M)=>r.get(v)?.forEach(O=>O(...M)),o=((v,M)=>{let O=r.get(v);return O||r.set(v,O=new Set),O.add(M),()=>{O?.delete(M)}}),i=null,a=null,c=null,u={position:0,size:0},l=!1,d=!1,f=0,h=!1,p=!1,g=async()=>{if(l||d)return;d=!0;let v=++f;try{i=null,a=null;for(let M=0;;M++){c&&(c.leave(),c=null),u={position:0,size:0};let O;try{O=c0(await e.joinOrCreate(mi.QUEUE,Op(t)))}catch(z){if(l)return;let X=Qa(z);X&&kp();let N=X?void 0:BA[M];if(N==null){if(M===0&&await new Promise(Y=>setTimeout(Y,0)),l)return;s("error",z);return}if(await new Promise(Y=>setTimeout(Y,N)),l)return;continue}if(l||v!==f){O.leave();return}c=O,O.onMessage(xe.QUEUE,z=>{u={position:z.position,size:z.size},s("queue",z)}),O.onMessage(xe.SEAT,z=>{l||v!==f||c!==O||h||(h=!0,c=null,O.leave(),x(z.reservation,z.role,v))}),O.onLeave(()=>{l||c!==O||(c=null,(async()=>{for(let z of DA)if(await new Promise(X=>setTimeout(X,z)),l||c||i||(await g(),c||i))return})())}),s("searching");return}}finally{d=!1}},x=async(v,M,O)=>{try{let z=Ks(await e.consumeSeatReservation(v));if(l||O!==f){z.leave();return}a=z;let X=Cp(z,{pose:t.pose,smoothing:t.smoothing,predict:n});i=X,X.on(xe.MATCH_START,N=>s("matchStart",N)),X.on(xe.MATCH_ENDED,N=>s("matchEnded",N)),X.on(xe.MATCH_REQUEUE,()=>{i===X&&b()}),X.on("disconnect",N=>{if(!(l||i!==X)){if(N===Xa.SUPERSEDED||N===Xa.REVOKED){f++,h=!1,a=null,i=null,s("disconnect",N);return}b()}}),c&&(c.leave(),c=null),s("matched"),M==="spectator"&&s("spectate")}catch{!l&&O===f&&(h=!1,g())}finally{O===f&&(h=!1)}},b=async()=>{if(!(l||p)){p=!0;try{f++,h=!1,i?.leave(),a=null,i=null,await g()}finally{p=!1}}};g();let S=()=>i?Ar(i):null,_=null,P=null,R=()=>{i!==_&&(_=i,P=null);let v=S(),M=!!v?.state?.match;if(!M&&i&&P)return P;let O=S0(v,u,i?i.timeUntil:void 0);return M&&(P=O),O};return{get session(){return i},get matchmaking(){return R()},on:o,eliminated(){bi(S(),le.MATCH_ELIMINATED,{})},score(v=1){bi(S(),le.MATCH_SCORE,{delta:v})},finish(){bi(S(),le.MATCH_FINISH,{})},retry(){l||d||c||a||g()},cancel(){l=!0,f++,h=!1,i?.leave(),!i&&a&&a.leave(),c&&c.leave(),a=null,c=null,i=null}}}function _0(t,e){let n=new Map,r=(c,...u)=>n.get(c)?.forEach(l=>l(...u)),s=((c,u)=>{let l=n.get(c);return l||n.set(c,l=new Set),l.add(u),()=>{l?.delete(u)}}),o=!0,i=Cp(t,e);i.on(xe.MATCH_START,c=>r("matchStart",c)),i.on(xe.MATCH_ENDED,c=>r("matchEnded",c)),i.on(xe.MATCH_REQUEUE,()=>{o=!1}),i.on("disconnect",()=>{o=!1});let a=()=>o?Ar(i):null;return{get session(){return o?i:null},get matchmaking(){return S0(a(),{position:0,size:0},i.timeUntil)},on:s,eliminated(){bi(a(),le.MATCH_ELIMINATED,{})},score(c=1){bi(a(),le.MATCH_SCORE,{delta:c})},finish(){bi(a(),le.MATCH_FINISH,{})},retry(){},cancel(){i.leave(),o=!1}}}async function R0(t){let e=await Ja(t),n=await Dl(t.smoothing),r=Ks(await e.create(mi.MATCH,Op(t))),s=_0(r,{pose:t.pose,smoothing:t.smoothing,predict:n});return Object.defineProperty(s,"code",{value:r.roomId,enumerable:!0}),s}async function k0(t,e){let n=await Ja(e),r=await Dl(e.smoothing),s=Ks(await n.joinById(t,Op(e)));return _0(s,{pose:e.pose,smoothing:e.smoothing,predict:r})}var NA=2,Bl=ra;function LA(t){Bl=t??ra}function FA(t){let e=JSON.parse(t);if(!kn(e))throw new TypeError("genex bridge: options must be a JSON object");let n=typeof e.gameId=="string"?e.gameId:"";if(!n)throw new TypeError("genex bridge: `gameId` (the game slug) is required");let r=Array.isArray(e.urls)?e.urls.filter(a=>typeof a=="string"&&a!==""):[],s="play";if(e.room==="queue"||e.room==="private")s=e.room;else if(kn(e.room)&&typeof e.room.joinById=="string"&&e.room.joinById)s={joinById:e.room.joinById};else if(e.room!==void 0&&e.room!==null&&e.room!=="play")throw new TypeError('genex bridge: `room` must be "play", "queue", "private" or {"joinById": code}');let o=typeof e.controlTimeoutMs=="number"&&Number.isFinite(e.controlTimeoutMs)?e.controlTimeoutMs:void 0,i=e.smoothing==="genex"||e.smoothing==="predict"||kn(e.smoothing)?e.smoothing:void 0;return{gameId:n,name:typeof e.name=="string"&&e.name?e.name:void 0,urls:r,room:s,pose:e.pose===!0,smoothing:i,controlTimeoutMs:o,options:kn(e.options)?e.options:void 0}}var Ip=new Map,zA=1,Dp=t=>t.closed?null:t.mm?t.mm.session:t.session;function ec(t){t.closed=!0,t.connected=!1;for(let e of t.unwire.splice(0))e();t.wired=null,t.session=null,t.mm=null}function A0(t,e){if(t.wired===e)return;for(let i of t.unwire.splice(0))i();t.wired=e,t.connected=!0,t.lastConnected.clear(),t.lastMatch="";let n=Ar(e);t.sessionId=e.id,t.roomId=n.roomId;let r=t.unwire,s=i=>n.state?.players?.get(i)?.connected!==!1,o=i=>{let a=s(i),c=t.lastConnected.get(i);t.lastConnected.set(i,a),c!==void 0&&c!==a&&pe(t,{type:"playerConnection",id:i,connected:a})};pe(t,{type:"joined",sessionId:e.id}),n.state?.players?.forEach((i,a)=>{t.lastConnected.set(a,s(a)),pe(t,{type:"playerJoined",id:a})});for(let i of e.objects.ids())pe(t,{type:"objectChanged",id:i,owner:e.objects.get(i)?.owner??null});e.host!==void 0&&pe(t,{type:"hostChanged",host:e.host}),r.push(e.on("join",i=>{t.lastConnected.set(i,s(i)),pe(t,{type:"playerJoined",id:i})}),e.on("change",i=>{o(i),t.changed.has(i)||(t.changed.add(i),pe(t,{type:"playerChanged",id:i}))}),e.on("leave",i=>{t.lastConnected.delete(i),pe(t,{type:"playerLeft",id:i})}),e.on("host",i=>pe(t,{type:"hostChanged",host:i??null})),e.on("shared",(i,a)=>pe(t,{type:"sharedChanged",key:i,value:a??null})),e.on("object",i=>{let a=e.objects.get(i);pe(t,a?{type:"objectChanged",id:i,owner:a.owner??null}:{type:"objectRemoved",id:i})}),e.on("room:open",({open:i})=>pe(t,{type:"roomOpen",open:i})),e.on("reconnecting",({attempt:i,code:a})=>{t.connected=!1,pe(t,{type:"reconnecting",code:a,attempt:i})}),e.on("reconnected",()=>{t.connected=!0,pe(t,{type:"reconnected"})}),e.on("disconnect",i=>{t.connected=!1,t.opts.room!=="queue"&&(ec(t),pe(t,{type:"disconnected",code:i,reason:""}))}),e.on(xe.SERVER_RESTART,()=>pe(t,{type:"serverRestart"})),e.on(xe.MATCH_START,i=>pe(t,{type:"matchStart",roundId:kn(i)&&typeof i.roundId=="number"?i.roundId:0})),e.on(xe.MATCH_ENDED,i=>pe(t,{type:"matchEnded",data:i??null})),e.on(xe.MATCH_REQUEUE,i=>pe(t,{type:"matchRequeue",reason:kn(i)&&typeof i.reason=="string"?i.reason:null})),e.inputs.on((i,a)=>pe(t,{type:"input",from:i,data:a??null})),e.chat.on(i=>pe(t,{type:"chat",id:i.id,from:i.from,name:i.name,text:i.text,at:i.at})),n.onMessage(xe.RATE_DROP,i=>pe(t,{type:"rateDrop",dropped:kn(i)&&typeof i.dropped=="number"?i.dropped:0})),n.onMessage("*",(i,a)=>{typeof i=="string"&&!ns(i)&&pe(t,{type:"message",kind:i,data:a??null})}))}function Nl(t){let e=Dp(t);e&&e!==t.wired&&A0(t,e)}async function UA(t){let e=t.opts;if(await Bl.ready(e.gameId),t.closed)return;let n=e.urls.length?e.urls:Bl.urls();if(!n.length)throw Object.assign(new Error("genex bridge: no relay URL (pass urls, or run on a Genex page)"),{code:0});let r=()=>Bl.auth(),s={urls:n,room:e.gameId,name:e.name,auth:r,pose:e.pose,smoothing:e.smoothing};if(e.room==="play"){let a=await x0({...s,options:e.options});if(t.closed)return void a.leave();t.session=a,A0(t,a);return}let o=s,i=e.room==="queue"?await E0(o):e.room==="private"?await R0(o):await k0(e.room.joinById,o);if(t.closed)return void i.cancel();t.mm=i,i.on("queue",a=>{kn(a)&&pe(t,{type:"queue",position:Number(a.position)||0,size:Number(a.size)||0})}),i.on("matched",()=>{pe(t,{type:"seated"}),Nl(t)}),i.on("searching",()=>{if(t.wired){for(let a of t.unwire.splice(0))a();t.wired=null,t.connected=!1}}),i.on("error",a=>{let c=t.mm;ec(t),c?.cancel(),pe(t,{type:"joinFailed",code:No(a),message:Gn(a)})}),i.on("disconnect",a=>{ec(t),pe(t,{type:"disconnected",code:typeof a=="number"?a:0,reason:""})}),Nl(t)}function v0(t){let e=FA(t),n=zA++,r={opts:e,q:[],overflowed:!1,session:null,mm:null,wired:null,unwire:[],changed:new Set,lastConnected:new Map,lastMatch:"",sessionId:"",roomId:"",connected:!1,closed:!1};Ip.set(n,r);let s=UA(r).catch(o=>{throw ec(r),pe(r,{type:"joinFailed",code:No(o),message:Gn(o)}),o});return{handle:n,done:s}}function VA(t){let{handle:e,done:n}=v0(t);return n.catch(()=>{}),e}async function HA(t){let{handle:e,done:n}=v0(t);try{await n}catch(r){let s=new Error(Gn(r));throw s.code=No(r),s}return e}var ss=t=>Ip.get(t),Tt=t=>{let e=ss(t);return e?(Nl(e),Dp(e)):null};function T0(t){let e=ss(t);if(!e||e.closed)return;let{mm:n,session:r}=e;ec(e),n?n.cancel():r?.leave(),pe(e,{type:"disconnected",code:4e3,reason:"left"})}function $A(t){T0(t),typeof t=="number"&&Ip.delete(t)}function jA(t,e){let n=Wn(e,"state"),r=Tt(t);return r?(r.me.set(n),!0):!1}function qA(t,e){let n=Wn(e,"state"),r=Tt(t);return r?(r.me.snap(n),!0):!1}function GA(t,e,n){let r=sa(n,"value");if(typeof e!="string"||!e||e.startsWith(Rl))return!1;let s=Tt(t);return s?(s.shared.set(e,r),!0):!1}function WA(t,e,n){let r=Wn(n,"object state"),s=Tt(t);return!s||!s.objects.get(e)?.isMine?!1:(s.objects.set(e,r),!0)}function YA(t,e,n){let r=Wn(n,"object state"),s=Tt(t);return!s||!s.objects.get(e)?.isMine?!1:(s.objects.snap(e,r),!0)}function KA(t,e,n){let r=sa(n,"event data");if(typeof e!="string"||!e||e.length>$t.MAX_EVENT_TYPE_CHARS||ns(e))return!1;let s=Tt(t);return s?(s.send(e,r),!0):!1}function XA(t,e){}function JA(t,e){let n=sa(e,"input"),r=Tt(t);return r?(r.inputs.send(n),!0):!1}function ZA(t,e){let n=Tt(t);return n?(n.setRoomOpen(e===!0),!0):!1}function QA(t,e){let n=Tt(t);return!n||typeof e!="string"?!1:(n.chat.send(e),!0)}function Ll(t,e,n,r,s=!1){if(typeof n!="string"||!n)throw new TypeError("genex bridge: object id must be a non-empty string");let o=ss(t),i=Tt(t),a=l=>{if(!o)return;let d={type:"controlResult",requestId:String(r),operation:e,id:n,accepted:l.accepted,owner:l.owner??null,sequence:l.sequence,reason:l.reason};typeof l.retryAfterMs=="number"&&(d.retryAfterMs=l.retryAfterMs),pe(o,d)};if(!i){a({accepted:!1,sequence:0,reason:"disconnected"});return}let c={timeoutMs:o?.opts.controlTimeoutMs,...s?{authority:"host"}:{}};(e==="claim"?i.objects.claimConfirmed(n,c):e==="release"?i.objects.releaseConfirmed(n,c):i.objects.removeConfirmed(n,c)).then(a,()=>a({accepted:!1,sequence:0,reason:"disconnected"}))}function ev(t,e,n){Ll(t,"claim",e,n)}function tv(t,e,n){Ll(t,"claim",e,n,!0)}function nv(t,e,n){Ll(t,"release",e,n)}function rv(t,e,n){Ll(t,"remove",e,n)}function sv(t){let e=ss(t);return!e?.mm||e.closed?!1:(e.mm.eliminated(),!0)}function ov(t,e=1){let n=ss(t);return!n?.mm||n.closed||typeof e!="number"||!Number.isFinite(e)?!1:(n.mm.score(e),!0)}function iv(t){let e=ss(t);return!e?.mm||e.closed?!1:(e.mm.finish(),!0)}function av(t){return Tt(t)?.serverNow()??null}function cv(t,e){let n=Tt(t);return n?n.timeUntil(e):e-Date.now()}var P0=t=>typeof t=="number"&&Number.isFinite(t)?t:null;function uv(t){let e=ss(t),n=Tt(t),r=n?Ar(n):null,s=r?.state?.match,o=null;if(s)try{o=JSON.parse(s)}catch{o=null}return JSON.stringify({sessionId:n?.id??e?.sessionId??"",roomId:r?.roomId??e?.roomId??"",hostId:n?.host??null,isHost:n?.isHost??!1,connected:!!n&&!!e?.connected,closed:!e||e.closed,serverNow:P0(n?.serverNow()),rtt:P0(n?.rtt),clockSynced:n?.clockSynced??!1,clockOrigin:r?.state?.clockOrigin??0,matchState:o})}function lv(t){let e=Tt(t);if(!e)return"[]";let n=Ar(e).state?.players,r=[];for(let[s,o]of e.players){let i=n?.get(s);r.push({id:s,name:o.name,uid:o.uid,team:o.team,connected:o.connected,avatarUrl:o.avatarUrl,state:o.state??{},stateRaw:o.stateRaw??{},epoch:i?.epoch??0,isMe:s===e.id,posed:i?.posed===!0})}return JSON.stringify(r)}function dv(t){let e=Tt(t);if(!e)return"[]";let n=Ar(e).state?.objects,r=[];for(let s of e.objects.ids()){let o=e.objects.get(s);o&&r.push({id:s,owner:o.owner??null,isMine:o.isMine,seq:n?.get(s)?.seq??0,epoch:o.epoch,state:o.state??null,stateRaw:o.stateRaw??null})}return JSON.stringify(r)}function fv(t){let e=Tt(t),n={};if(e)for(let r of e.shared.keys())n[r]=e.shared.get(r)??null;return JSON.stringify(n)}function pv(t){let e=ss(t);if(!e)return"[]";try{Nl(e);let n=Dp(e);if(n){let r=Ar(n).state?.match??"";if(r!==e.lastMatch){e.lastMatch=r;let s=null;try{s=r?JSON.parse(r):null}catch{s=null}pe(e,{type:"matchState",state:s})}}e.changed.clear()}catch(n){pe(e,Bo(Gn(n)))}return mu(e)}var Yh={};Fd(Yh,{BODY_F32_STRIDE:()=>jh,BodyF32Flag:()=>qh,authorityJson:()=>xI,bodiesF32:()=>bI,bodyKeysJson:()=>wI,closeAuthority:()=>kE,disposeAuthority:()=>_I,drainAuthorityEventsJson:()=>EI,frame:()=>yI,openAuthority:()=>dI,predictProjectile:()=>pI,setAuthorityIdentity:()=>QO,setAuthorityPhysicsCore:()=>eI,setInput:()=>fI,setWorld:()=>hI,version:()=>ZO});var M0=2*Math.PI,C0=Math.fround(Math.PI),Te=t=>t===0?0:t;function Ln(t){if(typeof t!="number"||!Number.isFinite(t))return 0;let e=t<-1?-1:t>1?1:t;return Te(Math.fround(e))}function os(t){if(typeof t!="number"||!Number.isFinite(t)||Math.abs(t)>1e9)return null;let e=Math.fround(t-M0*Math.floor((t+Math.PI)/M0));return e===C0?-C0:Te(e)}function Js(t){return typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<16777216?t:0}function Fl(t,e){return typeof t!="number"||!Number.isFinite(t)||t<=0?0:t>e?e:t}var sn=(t,e,n)=>t<e?e:t>n?n:t,O0=5734161139222659/2**53,I0=1686629713/2**30,D0=2242054355/2**65,B0=5376105825661043/2**121,N0=-6004799503160649/2**55,L0=0x8888888887c53/2**58,F0=-7320136532976085/2**65,z0=6506786730409597/2**71,U0=-7571127717829867/2**78,V0=0x5764e96b3f55f/2**83,H0=0x5555555555553/2**55,$0=-6405119470031223/2**62,j0=457508533350745/2**64,q0=-5205429506036397/2**74,G0=0x47ba7af6d2c71/2**79,W0=-0x63eba6fa20e35/2**87,FF=Object.freeze({invpio2:O0,pio2_1:I0,pio2_2:D0,pio2_2t:B0,S1:N0,S2:L0,S3:F0,S4:z0,S5:U0,S6:V0,C1:H0,C2:$0,C3:j0,C4:q0,C5:G0,C6:W0});function Dt(t){if(!Number.isFinite(t)||Math.abs(t)>1e9)return[0,1];let e=Math.floor(t*O0+.5),n=e-4*Math.floor(e/4),r=t-e*I0-e*D0-e*B0,s=r*r,o=r+s*r*(N0+s*(L0+s*(F0+s*(z0+s*(U0+s*V0))))),i=.5*s,a=1-i,c=a+(1-a-i+s*(s*(H0+s*($0+s*(j0+s*(q0+s*(G0+s*W0)))))));return n===0?[Te(o),Te(c)]:n===1?[Te(c),Te(-o)]:n===2?[Te(-o),Te(-c)]:[Te(-c),Te(o)]}var Y0=t=>Dt(t)[0],K0=t=>Dt(t)[1];var lr={TOPDOWN:"topdown",FIRSTPERSON:"firstperson",VEHICLE:"vehicle"},Up=.25,hv=Object.freeze({speed:6,arena:20}),mv={speed:{min:0,max:1e3,positive:!1},arena:{min:0,max:1e6,positive:!0}};var Vp=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.getPrototypeOf(t)===Object.prototype;function tw(t,e){if(e===void 0)return!0;let n=oc(t)?.ranges;return n===void 0||!Vp(e)?!1:Object.keys(e).every(r=>{if(!Object.hasOwn(n,r))return!1;let s=n[r],o=e[r];return typeof o!="number"||!Number.isFinite(o)||o<s.min||o>s.max||s.integer===!0&&!Number.isInteger(o)?!1:!s.positive||o>0&&Math.fround(o)>0})}function wi(t,e){let n=oc(t);if(n===void 0)return{};let r={...n.defaults};if(!Vp(e))return r;for(let s of Object.keys(n.ranges))tw(t,{[s]:e[s]})&&(r[s]=e[s]);return r}var Np=t=>Number.isFinite(t)?t:0;function yv(t,e,n,r){let s=Ln(e.moveX),o=Ln(e.moveY),i=Fl(n,Up),a=Math.sqrt(s*s+o*o),c=a>1?1/a:1,u=Np(t.x)+s*c*r.speed*i,l=Np(t.y)+o*c*r.speed*i;return{x:Te(Math.fround(sn(u,-r.arena,r.arena))),y:Te(Math.fround(sn(l,-r.arena,r.arena))),yaw:os(e.yaw)??Te(Math.fround(Np(t.yaw)))}}var nw=2615243109,gv=Object.freeze({maxSpeed:250,walkSpeed:.52,crouchSpeed:.34,accelerate:5.5,airAccelerate:12,airMaxWishSpeed:30,friction:5.2,stopSpeed:80,gravity:800,jumpImpulse:301.993,maxVelocity:3500,radius:16,standHeight:72,crouchHeight:54,duckTime:.4,stepHeight:18,standable:.7,groundTrace:2.5,groundSnap:1,skin:.03,pitchLimit:1.5533430576324463,jumpBit:1,duckBit:2,walkBit:4,substeps:2,world:nw}),Se=(t,e)=>({min:t,max:e,positive:!1}),Qs=t=>({min:0,max:t,positive:!0}),ur=(t,e)=>({min:t,max:e,positive:!1,integer:!0}),bv={maxSpeed:Se(0,1e4),walkSpeed:Se(0,1),crouchSpeed:Se(0,1),accelerate:Se(0,1e3),airAccelerate:Se(0,1e3),airMaxWishSpeed:Se(0,1e4),friction:Se(0,1e3),stopSpeed:Se(0,1e4),gravity:Se(0,1e5),jumpImpulse:Se(0,1e5),maxVelocity:Se(0,1e5),radius:Qs(1e4),standHeight:Qs(1e4),crouchHeight:Qs(1e4),duckTime:Qs(100),stepHeight:Se(0,1e4),standable:Se(0,1),groundTrace:Se(0,1e4),groundSnap:Se(0,1e4),skin:Se(0,100),pitchLimit:Se(0,1.5707963705062866),jumpBit:ur(0,16777215),duckBit:ur(0,16777215),walkBit:ur(0,16777215),substeps:ur(1,8),world:ur(0,2**32-1)};var Bt={ON_GROUND:1,DUCKING:2,JUMP_HELD:4},wv=Bt.ON_GROUND|Bt.DUCKING|Bt.JUMP_HELD,X0={MAX_BOXES:4096,MAX_RAMPS:512,MAX_ABS:1e9},on=class extends RangeError{constructor(n,r){super(`firstperson world: ${n} ${r}`);m(this,"path");this.name="WorldError",this.path=n}},tc=new WeakMap,xv=(t,e)=>{if(typeof t!="number"||!Number.isFinite(t))throw new on(e,"is not a finite number");if(Math.fround(t)!==t)throw new on(e,"is not a float32");if(Math.abs(t)>1e9)throw new on(e,`is past \xB1${1e9}`);return Te(t)};function J0(t,e,n){if(!Array.isArray(t)||t.length!==e)throw new on(n,`is not an array of ${e} numbers`);let r=[];for(let s=0;s<e;s++)r.push(xv(t[s],`${n}[${s}]`));if(!(r[0]<r[3]&&r[1]<r[4]&&r[2]<r[5]))throw new on(n,"needs min < max on every axis");return r}function Z0(t,e,n){if(t===void 0)return[];if(!Array.isArray(t))throw new on(e,"is not an array");if(t.length>n)throw new on(e,`holds more than ${n}`);return t}function Sv(t,e){let n=new DataView(new ArrayBuffer(8+4*(6*t.length+9*e.length)));n.setUint32(0,t.length,!0),n.setUint32(4,e.length,!0);let r=8;for(let o of[...t,...e])for(let i of o)n.setFloat32(r,i,!0),r+=4;let s=2166136261;for(let o=0;o<n.byteLength;o++)s=Math.imul(s^n.getUint8(o),16777619)>>>0;return s}function eo(t,e={}){let n=tc.has(t)?t:void 0;if(n!==void 0&&(e.broadphase===void 0||e.broadphase===n.broadphase))return n;if(t!==void 0&&!Vp(t))throw new on("$","is not an object");let r=t??{},s=Z0(r.boxes,"boxes",X0.MAX_BOXES).map((a,c)=>Object.freeze(J0(a,6,`boxes[${c}]`))),o=Z0(r.ramps,"ramps",X0.MAX_RAMPS).map((a,c)=>{let u=`ramps[${c}]`,l=J0(a,9,u);if(l[6]!==0&&l[6]!==1)throw new on(`${u}[6]`,"is not an axis (0 or 1)");let[d,f,h,p]=[l[2],l[5],l[7],l[8]];if(!(d<=h&&d<=p))throw new on(u,"needs minZ \u2264 lo and minZ \u2264 hi");if(f!==Math.max(h,p))throw new on(u,"needs maxZ = max(lo, hi)");return Object.freeze(l)}),i=Object.freeze({boxes:Object.freeze(s),ramps:Object.freeze(o),hash:Sv(s,o),broadphase:e.broadphase!==!1});return tc.set(i,Ev(i)),i}var rc=eo(void 0),Tr={Box:0,OBox:1,Disc:2},Fp=96,Hp=new Int32Array(Fp);function sc(t){let e=t.length;if(e>Fp)throw new RangeError(`posed solids: at most ${Fp} a tick`);let n=()=>new Float64Array(e),r={count:e,kind:new Uint8Array(e),minX:n(),minY:n(),minZ:n(),maxX:n(),maxY:n(),maxZ:n(),cx:n(),cy:n(),hx:n(),hy:n(),sin:n(),cos:n(),radius:n()};return t.forEach((s,o)=>{if(s.kind==="box"){r.kind[o]=Tr.Box,[r.minX[o],r.minY[o],r.minZ[o]]=s.min,[r.maxX[o],r.maxY[o],r.maxZ[o]]=s.max;return}if(r.cx[o]=s.c[0],r.cy[o]=s.c[1],r.minZ[o]=s.c[2]-(s.kind==="disc"?s.half:s.half[2]),r.maxZ[o]=s.c[2]+(s.kind==="disc"?s.half:s.half[2]),s.kind==="disc"){r.kind[o]=Tr.Disc,r.radius[o]=s.radius,r.minX[o]=s.c[0]-s.radius,r.maxX[o]=s.c[0]+s.radius,r.minY[o]=s.c[1]-s.radius,r.maxY[o]=s.c[1]+s.radius;return}r.kind[o]=Tr.OBox,r.hx[o]=s.half[0],r.hy[o]=s.half[1],r.sin[o]=s.sin,r.cos[o]=s.cos;let i=Math.abs(s.cos),a=Math.abs(s.sin),c=s.half[0]*i+s.half[1]*a,u=s.half[0]*a+s.half[1]*i;r.minX[o]=s.c[0]-c,r.maxX[o]=s.c[0]+c,r.minY[o]=s.c[1]-u,r.maxY[o]=s.c[1]+u}),r}var rw=sc([]);function $p(t){let e=tc.get(t);if(e!==void 0)return e;let n=eo(t,{broadphase:t.broadphase!==!1}),r=tc.get(n);return tc.set(t,r),r}var nc=8;function Ev(t){let e=[...t.boxes,...t.ramps],n=e.length,r=()=>new Float64Array(n),s={boxCount:t.boxes.length,count:n,minX:r(),minY:r(),minZ:r(),maxX:r(),maxY:r(),maxZ:r(),axis:new Uint8Array(n),lo:r(),hi:r(),m0:r(),span:r(),slope:r(),topZ:r()};return e.forEach((o,i)=>{if(s.minX[i]=o[0],s.minY[i]=o[1],s.minZ[i]=o[2],s.maxX[i]=o[3],s.maxY[i]=o[4],s.maxZ[i]=o[5],i<s.boxCount)return;let a=o[6],c=a===0?o[0]:o[1],l=(a===0?o[3]:o[4])-c,d=(o[8]-o[7])/l;s.axis[i]=a,s.lo[i]=o[7],s.hi[i]=o[8],s.m0[i]=c,s.span[i]=l,s.slope[i]=d,s.topZ[i]=1/Math.sqrt(1+d*d)}),{...s,tree:t.broadphase&&n>0?_v(s):null}}function Lp(t){let e=t&1023;return e=(e|e<<16)&50331903,e=(e|e<<8)&50393103,e=(e|e<<4)&51130563,e=(e|e<<2)&153391689,e}function _v(t){let e=t.count,n=1/0,r=1/0,s=1/0,o=-1/0,i=-1/0,a=-1/0;for(let b=0;b<e;b++)n=Math.min(n,t.minX[b]),r=Math.min(r,t.minY[b]),s=Math.min(s,t.minZ[b]),o=Math.max(o,t.maxX[b]),i=Math.max(i,t.maxY[b]),a=Math.max(a,t.maxZ[b]);let c=(b,S,_)=>_>S?Math.min(1023,Math.floor((b-S)/(_-S)*1024)):0,u=new Float64Array(e);for(let b=0;b<e;b++){let S=c((t.minX[b]+t.maxX[b])/2,n,o),_=c((t.minY[b]+t.maxY[b])/2,r,i),P=c((t.minZ[b]+t.maxZ[b])/2,s,a);u[b]=(Lp(S)|Lp(_)<<1|Lp(P)<<2)*8192+b}u.sort();let l=[e];for(;l[l.length-1]>1;)l.push(Math.ceil(l[l.length-1]/nc));let d=l.reduce((b,S)=>b+S,0),f=new Float64Array(d*6),h=new Int32Array(d),p=new Int32Array(l.length);for(let b=0;b<e;b++){let S=u[b]%8192,_=b*6;f[_]=t.minX[S],f[_+1]=t.minY[S],f[_+2]=t.minZ[S],f[_+3]=t.maxX[S],f[_+4]=t.maxY[S],f[_+5]=t.maxZ[S],h[b]=S}p[0]=e;let g=0,x=e;for(let b=1;b<l.length;b++){let S=p[b-1];for(let _=g;_<S;_+=nc){let P=Math.min(_+nc,S),R=1/0,v=1/0,M=1/0,O=-1/0,z=-1/0,X=-1/0;for(let Y=_;Y<P;Y++){let he=Y*6;R=Math.min(R,f[he]),v=Math.min(v,f[he+1]),M=Math.min(M,f[he+2]),O=Math.max(O,f[he+3]),z=Math.max(z,f[he+4]),X=Math.max(X,f[he+5])}let N=x*6;f[N]=R,f[N+1]=v,f[N+2]=M,f[N+3]=O,f[N+4]=z,f[N+5]=X,h[x]=_,x++}g=S,p[b]=x}return{boxes:f,ref:h,levelEnd:p,root:d-1}}var sw=(t,e,n,r,s,o)=>.001+1e-7*(Math.abs(t)+Math.abs(e)+Math.abs(n)+Math.abs(r)+Math.abs(s)+Math.abs(o));function jp(t,e,n,r,s,o,i){Rv(t,e,n,r,s,o,i);let a=t.w.tree;if(a===null){t.nCand=-1;return}let c=sw(e,n,r,s,o,i),u=t.r+c,l=e-u,d=s+u,f=n-u,h=o+u,p=r-c,g=i+c,{boxes:x,ref:b,levelEnd:S}=a,_=S[0],P=t.cand,R=t.stack,v=0,M=0;for(R[M++]=a.root;M>0;){let O=R[--M],z=O*6;if(x[z+3]<l||x[z]>d||x[z+4]<f||x[z+1]>h||x[z+5]<p||x[z+2]>g)continue;if(O<_){P[v++]=b[O];continue}let X=b[O],N=X+nc;for(let Y=0;Y<S.length;Y++)if(X<S[Y]){N=Math.min(N,S[Y]);break}for(let Y=X;Y<N;Y++)R[M++]=Y}t.nCand=v}function Rv(t,e,n,r,s,o,i){let a=t.p,c=0;if(a.count>0){let u=sw(e,n,r,s,o,i),l=t.r+u,d=e-l,f=s+l,h=n-l,p=o+l,g=r-u,x=i+u;for(let b=0;b<a.count;b++)a.maxX[b]<d||a.minX[b]>f||a.maxY[b]<h||a.minY[b]>p||a.maxZ[b]<g||a.minZ[b]>x||(t.pc[c++]=b)}t.nPosed=c}var qp=t=>(t.nCand<0?t.w.count:t.nCand)+t.nPosed,Gp=(t,e)=>{let n=t.nCand<0?t.w.count:t.nCand;return e>=n?t.w.count+t.pc[e-n]:t.nCand<0?e:t.cand[e]},vr=(t,e)=>t.standHeight+(t.crouchHeight-t.standHeight)*e;function kv(t,e,n,r){let s=t.w,o=s.slope[e],i=s.axis[e]===0?n:r,a=o>0?i+t.r:o<0?i-t.r:i;return s.lo[e]+o*sn(a-s.m0[e],0,s.span[e])}function ow(t,e,n,r){let s=t.w;return e<s.boxCount?s.maxZ[e]:e<s.count?kv(t,e,n,r):t.p.maxZ[e-s.count]}var Pv=(t,e)=>e<t.w.count?t.w.minZ[e]:t.p.minZ[e-t.w.count];function iw(t,e,n,r){let s=t.w,o=t.r;return e>=s.count?dw(t,e-s.count,n,r):n+o>s.minX[e]&&n-o<s.maxX[e]&&r+o>s.minY[e]&&r-o<s.maxY[e]}function aw(t,e,n,r,s){let o=t.w;jp(t,e,n,r,e,n,r+s);let i=qp(t);for(let a=0;a<i;a++){let c=Gp(t,a);if(!iw(t,c,e,n)||!(r+s>Pv(t,c)))continue;let u=ow(t,c,e,n);if(r<u-1e-4)return!1}return!0}function jl(t,e,n,r,s,o){let i=t.w;jp(t,e,n,r-s,e,n,r+o);let a=qp(t),c=Number.NaN,u=Number.NaN;for(let l=0;l<a;l++){let d=Gp(t,l);if(!iw(t,d,e,n))continue;let f=ow(t,d,e,n);f<=r+o&&f>=r-s&&(d<i.boxCount||d>=i.count||i.topZ[d]>=t.standable?(c!==c||f>c)&&(c=f):(u!==u||f>u)&&(u=f))}return u>c?Number.NaN:c}function Vl(t){if(t.vz>.1){t.onGround=!1;return}let e=jl(t,t.x,t.y,t.z,t.groundTrace,t.groundSnap);e===e?(t.z=e,t.onGround=!0):t.onGround=!1}function Ul(t,e,n,r,s,o){if(Math.abs(n)<1e-9)return e>r&&e<s;let i=(r-e)/n,a=(s-e)/n,c=-1;if(i>a){let u=i;i=a,a=u,c=1}return i>=t.tMin&&(t.tMin=i,t.ax=o,t.sg=c),a<t.tMax&&(t.tMax=a),!(t.tMin>t.tMax)}var Ke=new Float64Array(4);function Av(t,e,n,r){let s=t.w,o=t.r,i=0,a=0,c=0,u;switch(n){case 0:i=1,u=s.maxX[e]+o;break;case 1:i=-1,u=-s.minX[e]+o;break;case 2:a=1,u=s.maxY[e]+o;break;case 3:a=-1,u=-s.minY[e]+o;break;case 4:c=-1,u=-s.minZ[e]+r;break;case 5:{let l=s.slope[e];s.axis[e]===0?i=-l:a=-l,c=1,u=s.lo[e]-l*s.m0[e]+o*Math.abs(l);break}default:c=1,u=s.maxZ[e]}Ke[0]=i,Ke[1]=a,Ke[2]=c,Ke[3]=u}function Hl(t,e,n,r,s,o){let i=t.w,a=t.r,c=t.skin;if(s>=i.count)return Ov(t,e,n,r,s-i.count,o);if(s<i.boxCount)return e-(i.minX[s]-a)>c&&i.maxX[s]+a-e>c&&n-(i.minY[s]-a)>c&&i.maxY[s]+a-n>c&&r-(i.minZ[s]-o)>c&&i.maxZ[s]-r>c;for(let u=0;u<7;u++){Av(t,s,u,o);let l=Ke[0],d=Ke[1],f=Ke[2];if(!(-(l*e+d*n+f*r-Ke[3])*(1/Math.sqrt(l*l+d*d+f*f))>c))return!1}return!0}function Wp(t,e,n,r,s,o,i,a,c){let u=t.w.count+t.p.count;for(let l=0;l<u;l++)if(l!==a&&Hl(t,e,n,r,l,c)&&!Hl(t,s,o,i,l,c))return!0;return!1}function cw(t,e,n,r,s,o,i,a,c,u){return Wp(t,e+s*a,n+o*a,r+i*a,e,n,r,c,u)}function vv(t,e,n,r,s,o,i,a){let c=t.r,u=t.skin,l=e-(s.minX[o]-c),d=s.maxX[o]+c-e,f=n-(s.minY[o]-c),h=s.maxY[o]+c-n,p=r-(s.minZ[o]-i),g=s.maxZ[o]-r;if(!(l>u&&d>u&&f>u&&h>u&&p>u&&g>u))return!1;let x=l,b=-1,S=0,_=0;return d<x&&([x,b,S,_]=[d,1,0,0]),f<x&&([x,b,S,_]=[f,0,-1,0]),h<x&&([x,b,S,_]=[h,0,1,0]),g<x&&!Wp(t,e,n,r+g,e,n,r,a,i)&&([x,b,S,_]=[g,0,0,1]),t.tMin=0,t.nx=b,t.ny=S,t.nz=_,t.depth=x,!0}function Yp(t,e,n,r,s,o,i,a,c,u=t.w,l=a){let d=t.r;return t.depth=0,vv(t,e,n,r,u,a,c,l)?!0:(t.tMin=0,t.tMax=1,t.ax=-1,t.sg=0,!Ul(t,e,s,u.minX[a]-d,u.maxX[a]+d,0)||!Ul(t,n,o,u.minY[a]-d,u.maxY[a]+d,1)||!Ul(t,r,i,u.minZ[a]-c,u.maxZ[a],2)||t.tMin>=1||t.ax<0?!1:(t.nx=t.ax===0?t.sg:0,t.ny=t.ax===1?t.sg:0,t.nz=t.ax===2?t.sg:0,!0))}function Tv(t,e,n,r,s,o,i,a,c){let u=t.w,l=t.r,d=u.slope[a],f=u.axis[a]===0,h=0,p=1,g=!1,x=!0,b=Number.POSITIVE_INFINITY,S=0,_=0,P=0;t.depth=0;for(let R=0;R<7;R++){let v=0,M=0,O=0,z;switch(R){case 0:v=1,z=u.maxX[a]+l;break;case 1:v=-1,z=-u.minX[a]+l;break;case 2:M=1,z=u.maxY[a]+l;break;case 3:M=-1,z=-u.minY[a]+l;break;case 4:O=-1,z=-u.minZ[a]+c;break;case 5:f?v=-d:M=-d,O=1,z=u.lo[a]-d*u.m0[a]+l*Math.abs(d);break;default:O=1,z=u.maxZ[a]}let X=v*e+M*n+O*r-z,N=v*s+M*o+O*i,Y=1/Math.sqrt(v*v+M*M+O*O),he=-X*Y;if(he>t.skin?R!==4&&he<b&&!(x&&R>=5&&cw(t,e,n,r,v*Y,M*Y,O*Y,he,a,c))&&(b=he,S=v*Y,_=M*Y,P=O*Y):x=!1,Math.abs(N)<1e-9){if(X>0)return!1;continue}let A=N<0&&X<=0&&X>-t.skin?0:-X/N;if(N<0?A>=h&&(h=A,t.nx=v*Y,t.ny=M*Y,t.nz=O*Y,g=!0):p=Math.min(p,A),h>p)return!1}return x?(t.tMin=0,t.nx=S,t.ny=_,t.nz=P,t.depth=b,!0):!g||!(h<1)||!(p>=0)?!1:(t.tMin=h,!0)}function uw(t,e,n,r){let s=t.p,o=s.cos[e],i=s.sin[e],a=s.cx[e],c=s.cy[e],u=s.hx[e],l=s.hy[e],d=t.r,f=d*(Math.abs(o)+Math.abs(i)),h=0,p=0,g=0,x;switch(n){case 0:h=o,p=i,x=o*a+i*c+u+f;break;case 1:h=-o,p=-i,x=-(o*a+i*c)+u+f;break;case 2:h=-i,p=o,x=-i*a+o*c+l+f;break;case 3:h=i,p=-o,x=i*a-o*c+l+f;break;case 4:h=1,x=a+d+u*Math.abs(o)+l*Math.abs(i);break;case 5:h=-1,x=-a+d+u*Math.abs(o)+l*Math.abs(i);break;case 6:p=1,x=c+d+u*Math.abs(i)+l*Math.abs(o);break;case 7:p=-1,x=-c+d+u*Math.abs(i)+l*Math.abs(o);break;case 8:g=-1,x=-s.minZ[e]+r;break;default:g=1,x=s.maxZ[e]}Ke[0]=h,Ke[1]=p,Ke[2]=g,Ke[3]=x}var Mv=10,lw=8,Cv=9;function dw(t,e,n,r){let s=t.p,o=t.r;if(!(n+o>s.minX[e]&&n-o<s.maxX[e]&&r+o>s.minY[e]&&r-o<s.maxY[e]))return!1;let i=s.kind[e];if(i===Tr.Box)return!0;let a=n-s.cx[e],c=r-s.cy[e];if(i===Tr.Disc){let f=Math.max(Math.abs(a)-o,0),h=Math.max(Math.abs(c)-o,0);return f*f+h*h<s.radius[e]*s.radius[e]}let u=s.cos[e],l=s.sin[e],d=o*(Math.abs(u)+Math.abs(l));return Math.abs(u*a+l*c)<s.hx[e]+d&&Math.abs(-l*a+u*c)<s.hy[e]+d}function fw(t,e,n,r){let s=t.p,o=t.r,i=n-s.cx[e],a=r-s.cy[e],c=Math.abs(i),u=Math.abs(a),l=s.radius[e];if(c<=o&&u<=o){let p=c>=u;return Ke[0]=p?i<0?-1:1:0,Ke[1]=p?0:a<0?-1:1,l+o-(p?c:u)}let d=c>o?i<0?-(c-o):c-o:0,f=u>o?a<0?-(u-o):u-o:0,h=Math.sqrt(d*d+f*f);return Ke[0]=d/h,Ke[1]=f/h,l-h}function Ov(t,e,n,r,s,o){let i=t.p,a=t.skin,c=i.kind[s];if(c===Tr.Box){let u=t.r;return e-(i.minX[s]-u)>a&&i.maxX[s]+u-e>a&&n-(i.minY[s]-u)>a&&i.maxY[s]+u-n>a&&r-(i.minZ[s]-o)>a&&i.maxZ[s]-r>a}if(!(r-(i.minZ[s]-o)>a&&i.maxZ[s]-r>a))return!1;if(c===Tr.Disc)return fw(t,s,e,n)>a;for(let u=0;u<lw;u++){uw(t,s,u,o);let l=Ke[0],d=Ke[1];if(!(-(l*e+d*n-Ke[3])*(1/Math.sqrt(l*l+d*d))>a))return!1}return!0}function Iv(t,e,n,r,s,o,i,a,c,u){let l=0,d=1,f=!1,h=!0,p=Number.POSITIVE_INFINITY,g=0,x=0,b=0;t.depth=0;for(let S=0;S<Mv;S++){uw(t,a,S,u);let _=Ke[0],P=Ke[1],R=Ke[2],v=_*e+P*n+R*r-Ke[3],M=_*s+P*o+R*i,O=1/Math.sqrt(_*_+P*P+R*R),z=-v*O;if(z>t.skin?S!==lw&&z<p&&!(h&&S===Cv&&cw(t,e,n,r,_*O,P*O,R*O,z,c,u))&&(p=z,g=_*O,x=P*O,b=R*O):h=!1,Math.abs(M)<1e-9){if(v>0)return!1;continue}let X=M<0&&v<=0&&v>-t.skin?0:-v/M;if(M<0?X>=l&&(l=X,t.nx=_*O,t.ny=P*O,t.nz=R*O,f=!0):d=Math.min(d,X),l>d)return!1}return h?(t.tMin=0,t.nx=g,t.ny=x,t.nz=b,t.depth=p,!0):!f||!(l<1)||!(d>=0)?!1:(t.tMin=l,!0)}function Dv(t,e,n,r,s,o,i,a,c,u,l,d){t.tMin=0,t.tMax=1,t.ax=-1,t.sg=0;let f=e-a,h=n-c,p=s*s+o*o,g=f*f+h*h-u*u;if(p<1e-18){if(!(g<0))return!1}else{let x=f*s+h*o,b=x*x-p*g;if(b<0)return!1;let S=Math.sqrt(b),_=(-x-S)/p,P=(-x+S)/p;if(_>=t.tMin&&(t.tMin=_,t.ax=3),P<t.tMax&&(t.tMax=P),t.tMin>t.tMax)return!1}if(!Ul(t,r,i,l,d,2)||t.tMin>=1||t.ax<0)return!1;if(t.ax===3){let x=f+s*t.tMin,b=h+o*t.tMin,S=Math.sqrt(x*x+b*b);t.nx=x/S,t.ny=b/S,t.nz=0}else t.nx=0,t.ny=0,t.nz=t.sg;return!0}var Fn={minX:new Float64Array(2),minY:new Float64Array(2),minZ:new Float64Array(2),maxX:new Float64Array(2),maxY:new Float64Array(2),maxZ:new Float64Array(2)};function Bv(t,e,n,r,s,o,i,a,c,u){let l=t.p,d=t.r,f=l.radius[a],h=l.cx[a],p=l.cy[a],g=l.minZ[a]-u,x=l.maxZ[a];t.depth=0;let b=fw(t,a,e,n),S=r-g,_=x-r;if(b>t.skin&&S>t.skin&&_>t.skin)return t.tMin=0,_<b&&!Wp(t,e,n,r+_,e,n,r,c,u)?[t.nx,t.ny,t.nz,t.depth]=[0,0,1,_]:[t.nx,t.ny,t.nz,t.depth]=[Ke[0],Ke[1],0,b],!0;let P=!1,R=0,v=0,M=0,O=0;Fn.minX[0]=h-f,Fn.maxX[0]=h+f,Fn.minY[0]=p,Fn.maxY[0]=p,Fn.minX[1]=h,Fn.maxX[1]=h,Fn.minY[1]=p-f,Fn.maxY[1]=p+f;for(let z=0;z<2;z++)Fn.minZ[z]=l.minZ[a],Fn.maxZ[z]=x,Yp(t,e,n,r,s,o,i,z,u,Fn,c)&&(!P||t.tMin<R)&&(P=!0,R=t.tMin,v=t.nx,M=t.ny,O=t.nz);for(let z=0;z<4;z++){let X=z%2===0?h-d:h+d,N=z<2?p-d:p+d;Dv(t,e,n,r,s,o,i,X,N,f,g,x)&&(!P||t.tMin<R)&&(P=!0,R=t.tMin,v=t.nx,M=t.ny,O=t.nz)}return P?(t.tMin=R,t.nx=v,t.ny=M,t.nz=O,t.depth=0,!0):!1}function Nv(t,e,n,r,s,o,i,a,c){let u=a-t.w.count,l=t.p.kind[u];return l===Tr.Box?Yp(t,e,n,r,s,o,i,u,c,t.p,a):l===Tr.OBox?Iv(t,e,n,r,s,o,i,u,a,c):Bv(t,e,n,r,s,o,i,u,a,c)}function Kp(t,e,n,r,s,o,i){let a=t.w,c=vr(t,t.duck),u=e+s,l=n+o,d=r+i;jp(t,e<u?e:u,n<l?n:l,r<d?r:d,e<u?u:e,n<l?l:n,(r<d?d:r)+c);let f=qp(t),h=!1,p=0,g=0,x=0,b=0,S=0,_=0;for(let P=0;P<f;P++){let R=Gp(t,P);(R<a.boxCount?Yp(t,e,n,r,s,o,i,R,c):R<a.count?Tv(t,e,n,r,s,o,i,R,c):Nv(t,e,n,r,s,o,i,R,c))&&(!h||t.tMin<p||t.tMin===p&&R<g)&&(h=!0,p=t.tMin,g=R,x=t.nx,b=t.ny,S=t.nz,_=t.depth)}t.hit=h,h?(t.tMin=Math.max(0,p-1e-4),t.nx=x,t.ny=b,t.nz=S,t.depth=_):(t.tMin=1,t.depth=0)}function $l(t,e,n=!1){let r=e,s=!1,o=0,i=0,a=0;for(let c=0;c<4&&r>1e-6;c++){if(t.vx*t.vx+t.vy*t.vy+t.vz*t.vz<1e-8)return;Kp(t,t.x,t.y,t.z,t.vx*r,t.vy*r,t.vz*r);let u=t.tMin;if(u>0){let g=u*r;t.x=t.x+t.vx*g,t.y=t.y+t.vy*g,t.z=t.z+t.vz*g,r=r-g}if(!t.hit)return;t.depth>0&&(t.x=t.x+t.nx*t.depth,t.y=t.y+t.ny*t.depth,t.z=t.z+t.nz*t.depth);let l=t.nx,d=t.ny,f=t.nz,h=!1;if(n&&f>0)if(f>=t.standable)h=!0;else{let g=1/Math.sqrt(l*l+d*d);l=l*g,d=d*g,f=0}t.x=t.x+l*t.skin,t.y=t.y+d*t.skin,t.z=t.z+f*t.skin;let p=t.vx*l+t.vy*d+t.vz*f;if(p<0&&(h?t.vz=t.vz-p/f:(t.vx=t.vx+l*-p,t.vy=t.vy+d*-p,t.vz=t.vz+f*-p)),s){let g=i*f-a*d,x=a*l-o*f,b=o*d-i*l,S=g*g+x*x+b*b;if(S>1e-6){let _=1/Math.sqrt(S);g=g*_,x=x*_,b=b*_;let P=t.vx*g+t.vy*x+t.vz*b;t.vx=g*P,t.vy=x*P,t.vz=b*P}}if(s=!0,o=l,i=d,a=f,t.vx*t.vx+t.vy*t.vy+t.vz*t.vz<1e-8)return}}function pw(t,e=!1){let n=t.x,r=t.y,s=t.z,o=t.vx,i=t.vy,a=t.vz;$l(t,t.h,e);let c=t.x,u=t.y,l=t.z,d=t.vx,f=t.vy,h=t.vz,p=c-n,g=u-r,x=p*p+g*g;t.x=n,t.y=r,t.z=s,t.vx=o,t.vy=i,t.vz=a;let b=t.stepHeight+t.skin;Kp(t,n,r,s,0,0,b);let S=t.tMin,_=s+b*S;if(S>0&&aw(t,n,r,_,vr(t,t.duck))){t.z=_,$l(t,t.h,e);let P=jl(t,t.x,t.y,t.z,t.stepHeight*2,.001);P===P&&(t.z=P);let R=t.x-n,v=t.y-r,M=R*R+v*v;if(P===P&&M>x+.001){t.vz=0;return}}t.x=c,t.y=u,t.z=l,t.vx=d,t.vy=f,t.vz=h}function hw(t){let e=jl(t,t.x,t.y,t.z,t.stepHeight,t.groundSnap);e===e&&(t.z=e,t.vz=0)}function Lv(t){let e=Math.sqrt(t.vx*t.vx+t.vy*t.vy);if(e<.1){t.vx=0,t.vy=0;return}let r=(e<t.stopSpeed?t.stopSpeed:e)*t.friction*t.h,s=Math.max(0,e-r)/e;t.vx=t.vx*s,t.vy=t.vy*s}function Fv(t){let e=t.wishSpeed-(t.vx*t.dirX+t.vy*t.dirY);if(e<=0)return;let n=t.accelerate*t.h*Math.max(t.wishSpeed,t.maxSpeed);n>e&&(n=e),t.vx=t.vx+n*t.dirX,t.vy=t.vy+n*t.dirY}function Q0(t){let e=Math.min(t.wishSpeed,t.airMaxWishSpeed)-(t.vx*t.dirX+t.vy*t.dirY);if(e<=0)return;let n=t.airAccelerate*t.wishSpeed*t.h;n>e&&(n=e),t.vx=t.vx+n*t.dirX,t.vy=t.vy+n*t.dirY}var bn=t=>Te(Math.fround(sn(t,-1e9,1e9)));function zv(t,e,n){let r=t.h/t.duckTime;if(e){let a=Math.min(1,t.duck+r);t.onGround||(t.z=t.z+(vr(t,t.duck)-vr(t,a))),t.duck=a,t.ducking=!0}else if(t.duck>0){let a=Math.max(0,t.duck-r),c=t.onGround?t.z:t.z-(vr(t,a)-vr(t,t.duck));aw(t,t.x,t.y,c,vr(t,a))&&(t.duck=a,t.z=c,t.duck===0&&(t.ducking=!1))}let s=t.onGround;Vl(t),t.onGround&&!s&&(t.vz=0),t.base=t.maxSpeed*t.cap;let o=t.ducking?t.base*t.crouchSpeed:n?t.base*t.walkSpeed:t.base;t.wishSpeed=t.amount*o,t.onGround?t.pressed?(t.vz=t.jumpImpulse,t.onGround=!1,t.pressed=!1,Q0(t)):(Lv(t),Fv(t),t.vz=0):Q0(t);let i=!t.onGround;i&&(t.vz=t.vz-t.gravity*t.h*.5),t.vx=sn(t.vx,-t.maxVelocity,t.maxVelocity),t.vy=sn(t.vy,-t.maxVelocity,t.maxVelocity),t.vz=sn(t.vz,-t.maxVelocity,t.maxVelocity),t.onGround?(pw(t),hw(t)):$l(t,t.h),Vl(t),i&&!t.onGround?t.vz=t.vz-t.gravity*t.h*.5:t.onGround&&(t.vz=0),t.x=bn(t.x),t.y=bn(t.y),t.z=bn(t.z),t.vx=bn(t.vx),t.vy=bn(t.vy),t.vz=bn(t.vz),t.duck=Te(Math.fround(t.duck))}var xt=(t,e,n,r)=>Te(Math.fround(sn(typeof t=="number"&&Number.isFinite(t)?t:e,n,r))),zp=t=>Te(Math.fround(typeof t=="number"&&Number.isFinite(t)?t:0)),zl={cand:new Int32Array(0),stack:new Int32Array(nc*16)};function Xp(t){return zl.cand.length<t.count&&(zl={cand:new Int32Array(t.count),stack:zl.stack}),zl}function mw(t,e,n=rc){let r=$p(n),s=Math.fround,o=a=>s(t==="vehicle"?e.height:e[a]),i=(a,c)=>{let u=Xp(r);return{w:r,p:sc(c),r:s(e.radius),standHeight:o("standHeight"),crouchHeight:o("crouchHeight"),stepHeight:s(e.stepHeight),standable:s(e.standable),groundTrace:s(e.groundTrace),groundSnap:s(e.groundSnap),skin:s(e.skin),x:a.x,y:a.y,z:a.z,vx:0,vy:0,vz:a.vz??0,duck:t==="vehicle"?0:a.duck??0,onGround:!1,h:0,tMin:0,tMax:0,ax:-1,sg:0,nx:0,ny:0,nz:0,hit:!1,depth:0,cand:u.cand,nCand:-1,pc:Hp,nPosed:0,stack:u.stack}};return{support(a,c){let u=i(a,c);if(u.vz>.1)return-1;let l=jl(u,u.x,u.y,u.z,u.groundTrace,u.groundSnap);if(l!==l)return-1;for(let d=0;d<u.p.count;d++)if(u.p.maxZ[d]===l&&dw(u,d,u.x,u.y))return d;return-1},inside(a,c,u){let l=i(a,c);return Hl(l,l.x,l.y,l.z,r.count+u,vr(l,l.duck))},pushOut(a,c){let u=i(a,c);for(let f=0;f<4&&(Kp(u,u.x,u.y,u.z,0,0,0),!!u.hit);f++)u.x=u.x+u.nx*u.depth,u.y=u.y+u.ny*u.depth,u.z=u.z+u.nz*u.depth,u.x=u.x+u.nx*u.skin,u.y=u.y+u.ny*u.skin,u.z=u.z+u.nz*u.skin;let l=vr(u,u.duck),d=!1;for(let f=0;f<r.count+u.p.count&&!d;f++)d=Hl(u,u.x,u.y,u.z,f,l);return{x:u.x,y:u.y,z:u.z,inside:d}}}}function Uv(t,e,n,r,s=rc,o=rw){let i=$p(s),a=Xp(i),c=Math.fround,u=Js(t.mstate)&wv,l={w:i,p:o,maxSpeed:c(r.maxSpeed),walkSpeed:c(r.walkSpeed),crouchSpeed:c(r.crouchSpeed),accelerate:c(r.accelerate),airAccelerate:c(r.airAccelerate),airMaxWishSpeed:c(r.airMaxWishSpeed),friction:c(r.friction),stopSpeed:c(r.stopSpeed),gravity:c(r.gravity),jumpImpulse:c(r.jumpImpulse),maxVelocity:c(r.maxVelocity),r:c(r.radius),standHeight:c(r.standHeight),crouchHeight:c(r.crouchHeight),duckTime:c(r.duckTime),stepHeight:c(r.stepHeight),standable:c(r.standable),groundTrace:c(r.groundTrace),groundSnap:c(r.groundSnap),skin:c(r.skin),x:xt(t.x,0,-1e9,1e9),y:xt(t.y,0,-1e9,1e9),z:xt(t.z,0,-1e9,1e9),vx:xt(t.vx,0,-1e9,1e9),vy:xt(t.vy,0,-1e9,1e9),vz:xt(t.vz,0,-1e9,1e9),duck:xt(t.duck,0,0,1),cap:xt(t.cap,1,0,4),onGround:(u&Bt.ON_GROUND)!==0,ducking:(u&Bt.DUCKING)!==0,jumpHeld:(u&Bt.JUMP_HELD)!==0,pressed:!1,h:0,dirX:0,dirY:0,amount:0,base:0,wishSpeed:0,tMin:0,tMax:0,ax:-1,sg:0,nx:0,ny:0,nz:0,hit:!1,depth:0,cand:a.cand,nCand:-1,pc:Hp,nPosed:0,stack:a.stack},d=Ln(e.moveX),f=Ln(e.moveY),h=Math.sqrt(d*d+f*f);h>1e-4&&(l.dirX=d/h,l.dirY=f/h,l.amount=Math.min(h,1));let p=Js(e.buttons),g=(p&r.jumpBit)!==0,x=(p&r.duckBit)!==0,b=(p&r.walkBit)!==0,S=Fl(n,Up);l.h=S/r.substeps;let _=os(e.yaw)??zp(t.yaw),P=c(r.pitchLimit),R=Te(sn(os(e.pitch)??zp(t.pitch),-P,P));if(S>0){l.pressed=g&&!l.jumpHeld,l.jumpHeld=g;for(let v=0;v<r.substeps;v++)zv(l,x,b)}return{x:l.x,y:l.y,z:l.z,vx:l.vx,vy:l.vy,vz:l.vz,yaw:_,pitch:R,duck:l.duck,mstate:(l.onGround?Bt.ON_GROUND:0)+(l.ducking?Bt.DUCKING:0)+(l.jumpHeld?Bt.JUMP_HELD:0)}}var Vv=Object.freeze({maxSpeed:1410,accel:1e3,brake:3500,coast:525,boostAccel:1e3,boostMaxSpeed:2300,boostBurn:.3333333432674408,grip:6e3,driftGrip:1500,turnRate:2.2,turnSpeed:400,spinAccel:30,airTurnRate:5.5,airSpinAccel:9,gravity:650,jumpImpulse:450,maxVelocity:6e3,radius:50,height:36,stepHeight:8,standable:.7,groundTrace:4,groundSnap:2,skin:.03,jumpBit:1,boostBit:2,driftBit:4,substeps:2,world:nw}),Hv={maxSpeed:Se(0,1e5),accel:Se(0,1e5),brake:Se(0,1e5),coast:Se(0,1e5),boostAccel:Se(0,1e5),boostMaxSpeed:Se(0,1e5),boostBurn:Se(0,1e3),grip:Se(0,1e5),driftGrip:Se(0,1e5),turnRate:Se(0,100),turnSpeed:Qs(1e5),spinAccel:Se(0,1e4),airTurnRate:Se(0,100),airSpinAccel:Se(0,1e4),gravity:Se(0,1e5),jumpImpulse:Se(0,1e5),maxVelocity:Se(0,1e5),radius:Qs(1e4),height:Qs(1e4),stepHeight:Se(0,1e4),standable:Se(0,1),groundTrace:Se(0,1e4),groundSnap:Se(0,1e4),skin:Se(0,100),jumpBit:ur(0,16777215),boostBit:ur(0,16777215),driftBit:ur(0,16777215),substeps:ur(1,8),world:ur(0,2**32-1)};var $v=Bt.ON_GROUND|Bt.JUMP_HELD,Zs=(t,e,n)=>t<e?Math.min(e,t+n):t>e?Math.max(e,t-n):t,yw=t=>os(t)??0;function jv(t){let e=t.maxSpeed*t.cap,n=t.boosting?1:t.throttle,r=n*e,s=t.f;if(n===0?s=Zs(s,0,t.coast*t.h):n>0&&s<0||n<0&&s>0?s=Zs(s,0,t.brake*t.h):Math.abs(s)<Math.abs(r)?s=Zs(s,r,t.accel*t.h):t.boosting||(s=Zs(s,r,t.coast*t.h)),t.boosting){let a=t.boostMaxSpeed*t.cap;s<a&&(s=Math.min(a,s+t.boostAccel*t.h))}let o=Zs(t.l,0,(t.drift?t.driftGrip:t.grip)*t.h),i=t.steer*t.turnRate*Math.min(1,Math.abs(s)/t.turnSpeed);s<0&&(i=-i),t.spin=Zs(t.spin,i,t.spinAccel*t.h),t.vx=s*t.c-o*t.s,t.vy=s*t.s+o*t.c,t.vz=0,t.f=s,t.l=o}function qv(t){if(t.spin=Zs(t.spin,t.steer*t.airTurnRate,t.airSpinAccel*t.h),t.boosting){let e=t.boostMaxSpeed*t.cap;if(t.f<e){let n=Math.min(t.boostAccel*t.h,e-t.f);t.vx=t.vx+n*t.c,t.vy=t.vy+n*t.s}}}function Gv(t){let e=t.onGround;Vl(t),t.onGround&&!e&&(t.vz=0),t.c=K0(t.yaw),t.s=Y0(t.yaw),t.f=t.vx*t.c+t.vy*t.s,t.l=t.vy*t.c-t.vx*t.s,t.boosting=t.boost&&t.fuel>0,t.boosting&&(t.fuel=Math.max(0,t.fuel-t.boostBurn*t.h)),t.onGround&&t.pressed&&(t.vz=t.jumpImpulse,t.onGround=!1,t.pressed=!1),t.onGround?jv(t):qv(t);let n=!t.onGround;n&&(t.vz-=t.gravity*t.h*.5),t.vx=sn(t.vx,-t.maxVelocity,t.maxVelocity),t.vy=sn(t.vy,-t.maxVelocity,t.maxVelocity),t.vz=sn(t.vz,-t.maxVelocity,t.maxVelocity),t.yaw=yw(t.yaw+t.spin*t.h),t.onGround?(pw(t,!0),hw(t)):$l(t,t.h),Vl(t),n&&!t.onGround?t.vz-=t.gravity*t.h*.5:t.onGround&&(t.vz=0),t.x=bn(t.x),t.y=bn(t.y),t.z=bn(t.z),t.vx=bn(t.vx),t.vy=bn(t.vy),t.vz=bn(t.vz),t.spin=Te(Math.fround(t.spin)),t.fuel=Te(Math.fround(t.fuel))}function Wv(t,e,n,r,s=rc,o=rw){let i=$p(s),a=Xp(i),c=Math.fround,u=Js(t.mstate)&$v,l=c(r.height),d=Te(-Ln(e.moveX)),f=Ln(e.moveY),h=Js(e.buttons),p=(h&r.jumpBit)!==0,g=Fl(n,Up),x=zp(t.yaw),b={w:i,p:o,r:c(r.radius),standHeight:l,crouchHeight:l,stepHeight:c(r.stepHeight),standable:c(r.standable),groundTrace:c(r.groundTrace),groundSnap:c(r.groundSnap),skin:c(r.skin),maxSpeed:c(r.maxSpeed),accel:c(r.accel),brake:c(r.brake),coast:c(r.coast),boostAccel:c(r.boostAccel),boostMaxSpeed:c(r.boostMaxSpeed),boostBurn:c(r.boostBurn),grip:c(r.grip),driftGrip:c(r.driftGrip),turnRate:c(r.turnRate),turnSpeed:c(r.turnSpeed),spinAccel:c(r.spinAccel),airTurnRate:c(r.airTurnRate),airSpinAccel:c(r.airSpinAccel),gravity:c(r.gravity),jumpImpulse:c(r.jumpImpulse),maxVelocity:c(r.maxVelocity),x:xt(t.x,0,-1e9,1e9),y:xt(t.y,0,-1e9,1e9),z:xt(t.z,0,-1e9,1e9),vx:xt(t.vx,0,-1e9,1e9),vy:xt(t.vy,0,-1e9,1e9),vz:xt(t.vz,0,-1e9,1e9),yaw:Math.abs(x)<=1e9?yw(x):0,spin:xt(t.spin,0,-1e3,1e3),fuel:xt(t.fuel,0,0,1),cap:xt(t.cap,1,0,4),duck:0,onGround:(u&Bt.ON_GROUND)!==0,jumpHeld:(u&Bt.JUMP_HELD)!==0,pressed:!1,boosting:!1,steer:d,throttle:f,boost:(h&r.boostBit)!==0,drift:(h&r.driftBit)!==0,h:g/r.substeps,c:1,s:0,f:0,l:0,tMin:0,tMax:0,ax:-1,sg:0,nx:0,ny:0,nz:0,hit:!1,depth:0,cand:a.cand,nCand:-1,pc:Hp,nPosed:0,stack:a.stack};if(g>0){b.pressed=p&&!b.jumpHeld,b.jumpHeld=p;for(let S=0;S<r.substeps;S++)Gv(b)}return{x:b.x,y:b.y,z:b.z,vx:b.vx,vy:b.vy,vz:b.vz,yaw:b.yaw,spin:b.spin,fuel:b.fuel,mstate:(b.onGround?Bt.ON_GROUND:0)+(b.jumpHeld?Bt.JUMP_HELD:0)}}var Yv={defaults:hv,ranges:mv,fields:["x","y","yaw"],reads:[],world:!1,step:(t,e,n,r)=>yv(t,e,n,r)},Kv={defaults:gv,ranges:bv,fields:["x","y","z","vx","vy","vz","yaw","pitch","duck","mstate"],reads:["cap"],world:!0,step:(t,e,n,r,s,o)=>Uv(t,e,n,r,s,o)},Xv={defaults:Vv,ranges:Hv,fields:["x","y","z","vx","vy","vz","yaw","spin","fuel","mstate"],reads:["cap"],world:!0,step:(t,e,n,r,s,o)=>Wv(t,e,n,r,s,o)},ew=Object.freeze({[lr.TOPDOWN]:Object.freeze(Yv),[lr.FIRSTPERSON]:Object.freeze(Kv),[lr.VEHICLE]:Object.freeze(Xv)});function oc(t){return typeof t=="string"&&Object.hasOwn(ew,t)?ew[t]:void 0}Mp();var Jv=2,gw=t=>typeof t=="string"&&t.length>0;function ww(t,e){let n=[],r=new Set;for(let s of Array.isArray(t)?t:[]){if(s===null||typeof s!="object")continue;let{region:o,urls:i}=s;if(typeof o!="string"||o.length===0||r.has(o))continue;let a=Array.isArray(i)?i.filter(gw):[];a.length!==0&&(r.add(o),n.push({region:o,urls:a}))}return n.length>0?n:(Array.isArray(e)?e.filter(gw):[]).map(s=>({region:s,urls:[s]}))}function Zv(t,e){return Array.from({length:e},(n,r)=>t[r%t.length])}var xw=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0;function bw(t,e){let n=[],r=[];return t.forEach((s,o)=>{let i=null,a=s.urls[0];s.urls.forEach((c,u)=>{let l=e[o]?.[u];!xw(l)||i!==null&&l>=i||(i=l,a=c)}),(i===null?r:n).push({index:o,ms:i,pick:{region:s.region,url:a}})}),n.sort((s,o)=>s.ms-o.ms||s.index-o.index),[...n,...r].map(s=>s.pick)}function Sw(t,e,n){let r=t.refused+1;if(r>=Jv&&t.region+1<e){let o=t.region+1;return{attempt:{region:o,waitMs:0},state:{region:o,refused:0,step:t.step}}}let s=n[t.step];return s===void 0?null:{attempt:{region:t.region,waitMs:s},state:{region:t.region,refused:r,step:t.step+1}}}async function Ew(t,e={}){if(t.length===0)return[];if(t.length===1)return bw(t,[]);let n=Math.max(1,e.samples??Ys.SAMPLES),r=t.map(i=>Zv(i.urls,n)),s=await Qv(r,e),o=t.map((i,a)=>i.urls.map(c=>{let u;return r[a]?.forEach((l,d)=>{let f=s[a]?.[d];l===c&&xw(f)&&(u=Math.min(u??Number.POSITIVE_INFINITY,f))}),u}));return bw(t,o)}async function Qv(t,e={}){let n=e.probe??Rp,r=e.timeoutMs??Ys.TIMEOUT_MS,s=e.graceMs??Ys.GRACE_MS,o=t.map(a=>a.map(()=>{})),i=t.reduce((a,c)=>a+c.length,0);return i===0||await new Promise(a=>{let c,u=!1,l=setTimeout(d,r);function d(){u=!0,clearTimeout(l),clearTimeout(c),a()}let f=()=>{--i===0&&d()};t.forEach((h,p)=>{h.forEach((g,x)=>{let b;try{b=n(g,r)}catch(S){b=Promise.reject(S)}b.then(S=>{!u&&Number.isFinite(S)&&S>=0&&(o[p][x]=S,c??(c=setTimeout(d,s))),f()},f)})})}),o}var jt={EXTRAPOLATE:"extrapolate",HOLD:"hold",INPUT_DECAY:"inputDecay"};var tT=Object.freeze({bodies:512,collidersPerBody:8,hullVertices:64,triangles:65536,joints:64,ccdBodies:16,queriesPerStep:64,eventsPerStep:64,heightfieldSamples:1048576,staticPieces:4608,memoryBytes:64*1024*1024,worldExtent:1e5,maxSpeed:1e3,maxAngularSpeed:1e3}),YF=Object.freeze(Object.keys(tT)),KF=Object.freeze(["worldExtent","maxSpeed"]),XF=Object.freeze(["worldExtent","maxSpeed","maxAngularSpeed"]);var _w=Object.freeze({[lr.FIRSTPERSON]:39.37,[lr.VEHICLE]:100}),JF=Object.freeze([10,15,20,30,60]);var dr={DEFAULT_REMOTE_PREDICT:jt.EXTRAPOLATE,DEFAULT_REMOTE_DECAY_MS:50,MAX_REMOTE_DECAY_MS:1e3,DEFAULT_LEAD_MS:250,MIN_LEAD_MS:50,MAX_LEAD_MS:1e3},ZF=Object.values(jt);var Rw=64,kw=64;var QF=Object.freeze({20:3,30:2,60:1,120:1});var nT=Object.freeze(["qx","qy","qz","qw","lvx","lvy","lvz","avx","avy","avz","sleep"]),rT=Object.freeze(["x","y","z",...nT]),ql={BITS:16,SPAN:65534,ORIENTATION:Object.freeze({min:-1,max:1}),VELOCITY:Object.freeze({min:-64,max:64})};function qt(t,e){if(Number.isNaN(t))return 0;let n=t<e.min?e.min:t>e.max?e.max:t;return Math.floor((n-e.min)/(e.max-e.min)*ql.SPAN+.5)}var Pw=250,Aw=1,vw=100,Tw=1;var Qp=[0,0,0,1];function zn(t,e){return[t[3]*e[0]+t[0]*e[3]+t[1]*e[2]-t[2]*e[1],t[3]*e[1]-t[0]*e[2]+t[1]*e[3]+t[2]*e[0],t[3]*e[2]+t[0]*e[1]-t[1]*e[0]+t[2]*e[3],t[3]*e[3]-t[0]*e[0]-t[1]*e[1]-t[2]*e[2]]}function Mr(t){let e=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]+t[3]*t[3]);return e===0?Qp:[t[0]/e,t[1]/e,t[2]/e,t[3]/e]}function Mw(t,e,n,r){let s=Math.sin(r/2);return[t*s,e*s,n*s,Math.cos(r/2)]}function xi(t,e){let n=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);if(n===0)return Qp;let r=2*Math.atan2(n,t[3]);return Mw(t[0]/n,t[1]/n,t[2]/n,e*r)}function Cw(t,e){return{tick:e+1,p:[t.x,t.y,t.z],q:Mr([t.qx,t.qy,t.qz,t.qw]),lv:[t.lvx,t.lvy,t.lvz],av:[t.avx,t.avy,t.avz],sleep:t.sleep,epoch:t.epoch}}function sT(t,e,n){if(t.sleep||!(n.tickHz>0))return 0;let s=((e-n.tickOrigin)*n.tickHz/1e3-t.tick)/n.tickHz,o=-Aw/n.tickHz,i=Pw/1e3;return s<o?o:s>i?i:s}function Ow(t,e,n){let r=sT(t,e,n),s=n.lengthUnit,o=[t.p[0]+t.lv[0]*s*r,t.p[1]+t.lv[1]*s*r,t.p[2]+t.lv[2]*s*r],[i,a,c]=t.av,u=Math.sqrt(i*i+a*a+c*c);return u===0||r===0?{p:o,q:t.q}:{p:o,q:Mr(zn(Mw(i/u,a/u,c/u,u*r),t.q))}}var Jp={SPAWNED:"spawned",EPOCH:"epoch",DISTANCE:"distance"},Zp=(t,e)=>({state:t,arrivedAt:e,dp:[0,0,0],dq:Qp});function eh(t,e,n){let r=Ow(t.state,e,n),s=e-t.arrivedAt,o=Math.exp(-(s<0?0:s)/vw),{dp:i}=t;return{p:[r.p[0]+i[0]*o,r.p[1]+i[1]*o,r.p[2]+i[2]*o],q:zn(xi(t.dq,o),r.q)}}function Iw(t,e,n,r){if(t===null)return{drawing:Zp(e,n),snap:Jp.SPAWNED};if(e.epoch!==t.state.epoch)return{drawing:Zp(e,n),snap:Jp.EPOCH};let s=eh(t,n,r),o=Ow(e,n,r),i=[s.p[0]-o.p[0],s.p[1]-o.p[1],s.p[2]-o.p[2]];if(Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2])>Tw*r.lengthUnit)return{drawing:Zp(e,n),snap:Jp.DISTANCE};let a=zn(s.q,[-o.q[0],-o.q[1],-o.q[2],o.q[3]]),c=a[3]<0?[-a[0],-a[1],-a[2],-a[3]]:a;return{drawing:{state:e,arrivedAt:n,dp:i,dq:c},snap:null}}function Dw(t,e){let n=(r,s)=>r.every((o,i)=>Object.is(o,s[i]));return t.sleep===e.sleep&&t.epoch===e.epoch&&n(t.p,e.p)&&n(t.q,e.q)&&n(t.lv,e.lv)&&n(t.av,e.av)}var Bw=2**32-1,ic=1e3,Cr=t=>typeof t.t0=="number"&&t.t0>0;function th(t,e,n){let r=(e-t.t0)/n,s=Number.isFinite(r)&&r>=0?r:0;return{x:Te(Math.fround(t.x+t.vx*s)),y:Te(Math.fround(t.y+t.vy*s)),z:Te(Math.fround(t.z+t.vz*s-.5*t.g*s*s)),vx:Te(t.vx),vy:Te(t.vy),vz:Te(Math.fround(t.vz-t.g*s))}}function nh(t,e,n){return(t-e)*n/1e3}function Gl(t,e,n){return e+t*1e3/n}var an={Predicted:"predicted",Separate:"separate",Timeline:"timeline"},to={Shared:"shared",Mover:"mover"},Un={Shooter:"shooter",Platformer:"platformer",VehicleArena:"vehicle-arena",PhysicsSandbox:"physics-sandbox",Party:"party"},ot={Stand:"stand",Slide:"slide",Bounce:"bounce",Ghost:"ghost"},Vn={Box:"box",Hull:"hull"},no={Slide:"slide",Carry:"carry"};var rh=(t,e,n)=>({speed:t,step:e,share:n}),ac=t=>({policy:ot.Slide,...t}),uc=(t,e,n)=>({policy:ot.Stand,ride:t,center:e,slide:n}),Si=rh(300,150,1),Or=rh(950,480,1),oT=rh(600,null,.5),iT=.25,i2=Object.freeze({speed:300,step:150}),a2={policy:ot.Bounce,stompMin:150,bounceSpeed:450,jumpBoost:150,slide:Si},Nw={[Un.Shooter]:{character:uc(!1,iT,Si),vehicle:ac(Or),restitution:0,passes:16,vehicleOffWall:Or,stopSpin:!1,drawing:an.Separate,push:to.Mover,headFriction:no.Slide},[Un.Platformer]:{character:uc(!0,null,Si),vehicle:ac(Or),restitution:0,passes:16,vehicleOffWall:Or,stopSpin:!1,drawing:an.Separate,push:to.Mover,headFriction:no.Slide},[Un.VehicleArena]:{character:ac(Si),vehicle:ac(Or),restitution:.6,passes:32,vehicleOffWall:oT,stopSpin:!0,drawing:an.Predicted,push:to.Shared,headFriction:no.Carry},[Un.PhysicsSandbox]:{character:uc(!0,null,Si),vehicle:uc(!0,null,Or),restitution:.2,passes:16,vehicleOffWall:Or,stopSpin:!1,drawing:an.Separate,push:to.Shared,headFriction:no.Carry},[Un.Party]:{character:uc(!0,null,Si),vehicle:ac(Or),restitution:.3,passes:16,vehicleOffWall:Or,stopSpin:!1,drawing:an.Separate,push:to.Shared,headFriction:no.Slide}},c2=Object.freeze({supportCos:.7,entrySpeed:1,entryWindow:1/60,slop:.1,roofSkin:.01});var u2={[ot.Stand]:new Set(["policy","ride","center","slide"]),[ot.Slide]:new Set(["policy","speed","step","share"]),[ot.Bounce]:new Set(["policy","stompMin","bounceSpeed","jumpBoost"]),[ot.Ghost]:new Set(["policy"])};function aT(t,e,n){let[r,s,o,i,a,c]=t;return[[-1,0,0,-(r-e)],[1,0,0,i+e],[0,-1,0,-(s-e)],[0,1,0,a+e],[0,0,1,c],[0,0,-1,-(o-n)]]}function cT(t,e,n){let[r,s,o,i,a,c,u,l,d]=t,f=u===0?r:s,h=(d-l)/((u===0?i:a)-f),p=1/Math.sqrt(h*h+1),g=(l-h*f+e*Math.abs(h))*p,x=u===0?[-h*p,0,p,g]:[0,-h*p,p,g];return[[1,0,0,i+e],[-1,0,0,-r+e],[0,1,0,a+e],[0,-1,0,-s+e],x,[0,0,1,c],[0,0,-1,-o+n]]}function Lw(t,e,n,r){return{planes:t,min:[e[0]-n,e[1]-n,e[2]-r],max:[e[3]+n,e[4]+n,e[5]]}}function Uw(t,e,n,r){let s=(t?.boxes??[]).map(c=>Lw(aT(c,e,n),c,e,n)),o=(t?.ramps??[]).map(c=>Lw(cT(c,e,n),c,e,n)),i=[...s,...o],a=uT(i);return a===null?{solids:i,skin:r}:{solids:i,skin:r,grid:a}}var Fw=t=>Number.isFinite(t.min[0])&&Number.isFinite(t.min[1])&&Number.isFinite(t.max[0])&&Number.isFinite(t.max[1]);function as(t,e,n,r){let s=Math.floor((t-e)/n);return s<0?0:s>r-1?r-1:s}function uT(t){let e=t.filter(Fw);if(e.length<32)return null;let n=Number.POSITIVE_INFINITY,r=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY,o=Number.NEGATIVE_INFINITY;for(let d of e)n=Math.min(n,d.min[0]-1),r=Math.min(r,d.min[1]-1),s=Math.max(s,d.max[0]+1),o=Math.max(o,d.max[1]+1);let i=Math.max(64,(s-n)/32,(o-r)/32),a=Math.min(32,Math.floor((s-n)/i)+1),c=Math.min(32,Math.floor((o-r)/i)+1),u=Array.from({length:a*c},()=>[]),l=[];return t.forEach((d,f)=>{if(!Fw(d)){l.push(f);return}let h=as(d.min[0]-1,n,i,a),p=as(d.max[0]+1,n,i,a),g=as(d.min[1]-1,r,i,c),x=as(d.max[1]+1,r,i,c);if((p-h+1)*(x-g+1)>64){l.push(f);return}for(let b=g;b<=x;b++)for(let S=h;S<=p;S++)u[S+b*a].push(f)}),{x0:n,y0:r,size:i,nx:a,ny:c,cells:u,wide:l}}function lT(t,e){if(e.length===0)return t;let n=[],r=0,s=0;for(;r<t.length||s<e.length;){let o=s>=e.length||r<t.length&&t[r]<=e[s],i=o?t[r]:e[s];o?r+=1:s+=1,n[n.length-1]!==i&&n.push(i)}return n}function dT(t,e,n,r,s){let o=t.grid;if(o===void 0||!(Number.isFinite(e)&&Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(s)))return null;let i=as(e,o.x0,o.size,o.nx),a=as(n,o.x0,o.size,o.nx),c=as(r,o.y0,o.size,o.ny),u=as(s,o.y0,o.size,o.ny);if((a-i+1)*(u-c+1)>16)return null;let l=o.wide;for(let d=c;d<=u;d++)for(let f=i;f<=a;f++)l=lT(l,o.cells[f+d*o.nx]);return l}function lc(t,e,n,r,s){for(let[o,i,a,c]of t)if(!(c-(o*n+i*r+a*s)>e))return!1;return!0}function fT(t,e,n,r){for(let s=0;s<3;s++){let o=e[s],i=o+n[s]*r,a=o<i?o:i;if((o<i?i:o)<t.min[s]-1||a>t.max[s]+1)return!1}return!0}function pT(t,e,n,r,s){for(let o of t.planes){let[i,a,c,u]=o;if(u-(i*n[0]+a*n[1]+c*n[2])<=e&&i*r[0]+a*r[1]+c*r[2]<0&&!s?.(o))return{t:0,face:o}}return null}var Vw=(t,e)=>n=>n[2]>=e&&n[0]*t[0]+n[1]*t[1]+n[2]*t[2]>=e;function hT(t,e,n,r,s,o){if(lc(t.planes,e,n[0],n[1],n[2]))return null;if(lc(t.planes,-e,n[0],n[1],n[2]))return pT(t,e,n,r,o);let i=0,a=s,c=Number.NEGATIVE_INFINITY,u=null;for(let l of t.planes){let[d,f,h,p]=l,g=p+e-(d*n[0]+f*n[1]+h*n[2]),x=d*r[0]+f*r[1]+h*r[2];if(x===0){if(!(g>0))return null;continue}let b=g/x;x>0&&b<a&&(a=b),x<0&&b>c&&(c=b,u=l)}return c>i&&(i=c),u===null||!(i<a)||o?.(u)?null:{t:i,face:u}}function dc(t,e,n,r,s){let o={t:r,face:null};if(!(r>0))return{t:0,face:null};let i=f=>{if(!fT(f,e,n,o.t))return;let h=hT(f,t.skin,e,n,o.t,s);h!==null&&h.t<o.t&&(o=h)},[a,c]=[e[0],e[1]],[u,l]=[a+n[0]*r,c+n[1]*r],d=dT(t,Math.min(a,u),Math.max(a,u),Math.min(c,l),Math.max(c,l));if(d===null)for(let f of t.solids)i(f);else for(let f of d)i(t.solids[f]);return o}function Wl(t,e,n,r,s){if(t===null)return r;let o=dc(t,e,n,r,s).t;return o<0?0:o}var zw=[0,0,1],mT=[0,0,-1];function Hw(t,e,n,r,s){if(t===null)return zw;let o=dc(t,[e,n,r],mT,s);return o.face===null||!(o.face[2]>0)?zw:[o.face[0],o.face[1],o.face[2]]}function yT(t,e,n,r,s,o){let{solids:i,skin:a}=t;for(let c=0;c<i.length;c++){if(c===e)continue;let u=i[c].planes;if(lc(u,a,o[0],o[1],o[2])&&!lc(u,a,n,r,s))return!0}return!1}function gT(t,e,n,r,s,o){let i=null;for(let a=0;a<n.length-1;a++){let[c,u,l,d]=n[a],f=d-(c*r+u*s+l*o);i!==null&&!(f<i[3])||l>0&&yT(t,e,r,s,o,[r+c*f,s+u*f,o+l*f])||(i=[c,u,l,f])}return i}function bT(t,e,n,r){let{solids:s,skin:o}=t;for(let i=0;i<s.length;i++){let a=s[i].planes;if(lc(a,o,e,n,r))return gT(t,i,a,e,n,r)}return null}function $w(t,e,n){let{x:r,y:s,z:o}=e,i=0;for(let a=0;a<4;a++){let c=bT(t,r,s,o);if(c===null)break;n?.(c);let[u,l,d,f]=c;i=Math.max(i,f),r+=u*(f+t.skin),s+=l*(f+t.skin),o+=d*(f+t.skin)}return i>0&&(e.x=r,e.y=s,e.z=o),i}var so={Side:"side",Top:"top"},Xl={Free:"free",LowerYields:"lower-yields",Pinned:"pinned"},wT={Stomp:"stomp"},sh={j:0,way:null,w:null},fc=[0,0,1],Ne=(t,e)=>t[0]*e[0]+t[1]*e[1]+t[2]*e[2],oo=(t,e)=>[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]],it=t=>[-t[0],-t[1],-t[2]];function xT(t,e,n){return n.supportUp!==void 0?n.supportUp(t.x,t.y,t.z):Hw(n.world,t.x,t.y,t.z,e.groundTrace)}function io(t,e,n){let r=e.shape,s=xT(t,e,n);if(r.kind===Vn.Hull)return{b:t,up:fc,support:s,hl:r.radius,hw:r.radius,top:r.height,s:0,c:1};let[o,i]=Dt(t.yaw);return{b:t,up:s,support:s,hl:r.length/2,hw:r.width/2,top:r.top,s:o,c:i}}var Jl=t=>Math.sqrt(t.hl*t.hl+t.hw*t.hw),Yl=(t,e,n)=>t.hl*Math.abs(t.c*e+t.s*n)+t.hw*Math.abs(t.c*n-t.s*e);function ST(t,e){let n=e.b.z-t.b.z+(e.top-t.top)/2,r=(t.top+e.top)/2;if(Math.abs(n)>=r)return null;let s=e.b.x-t.b.x,o=e.b.y-t.b.y,i=Jl(t)+Jl(e);if(Math.abs(s)>=i||Math.abs(o)>=i)return null;let a=[t.c,t.s,-t.s,t.c,e.c,e.s,-e.s,e.c],c=null,u=[];for(let d=0;d<8;d+=2){let f=a[d],h=a[d+1],p=s*f+o*h,g=Yl(t,f,h)+Yl(e,f,h)-Math.abs(p);if(g<=0)return null;let x=p<0?{depth:g,n:[-f,-h,0]}:{depth:g,n:[f,h,0]};u.push(x),(c===null||g<c.depth)&&(c=x)}let l=n<0?[0,0,-1]:fc;return{plane:fc,level:!0,side:c,axes:u,across:{depth:r-Math.abs(n),n:l},d:[s,o,0],half:d=>Yl(t,d[0],d[1])+Yl(e,d[0],d[1])}}function ih(t,e,n){let r=t*n[0]+e*n[1],s=t-r*n[0],o=e-r*n[1],i=-r*n[2],a=Math.sqrt(s*s+o*o+i*i);return a<1e-9&&(s=-n[2]*n[0],o=-n[2]*n[1],i=1-n[2]*n[2],a=Math.sqrt(s*s+o*o+i*i)),[s/a,o/a,i/a]}function ET(t,e){let n=[t.up[0]+e.up[0],t.up[1]+e.up[1],t.up[2]+e.up[2]],r=Math.sqrt(Ne(n,n));if(r<1e-9)return null;let s=[n[0]/r,n[1]/r,n[2]/r],o=t.top/2,i=e.top/2,a=[e.b.x+e.up[0]*i-t.b.x-t.up[0]*o,e.b.y+e.up[1]*i-t.b.y-t.up[1]*o,e.b.z+e.up[2]*i-t.b.z-t.up[2]*o],c=Ne(a,s),u=o+i;if(Math.abs(c)>=u)return null;let l=ih(t.c,t.s,s),d=ih(e.c,e.s,s),f=oo(s,l),h=oo(s,d),p=b=>t.hl*Math.abs(Ne(l,b))+t.hw*Math.abs(Ne(f,b))+(e.hl*Math.abs(Ne(d,b))+e.hw*Math.abs(Ne(h,b))),g=null,x=[];for(let b of[l,f,d,h]){let S=Ne(a,b),_=t.hl*Math.abs(Ne(l,b))+t.hw*Math.abs(Ne(f,b))+(e.hl*Math.abs(Ne(d,b))+e.hw*Math.abs(Ne(h,b)))-Math.abs(S);if(_<=0)return null;let P={depth:_,n:S<0?it(b):b};x.push(P),(g===null||_<g.depth)&&(g=P)}return{plane:s,level:!1,side:g,axes:x,across:{depth:u-Math.abs(c),n:c<0?it(s):s},d:a,half:p}}var _T=1e-6;function jw(t){let e=ih(t.c,t.s,t.up),n=t.top/2;return{c:[t.b.x+t.up[0]*n,t.b.y+t.up[1]*n,t.b.z+t.up[2]*n],axes:[e,oo(t.up,e),t.up],half:[t.hl,t.hw,n]}}function RT(t,e,n){let r=jw(t),s=jw(e),o=[s.c[0]-r.c[0],s.c[1]-r.c[1],s.c[2]-r.c[2]],i=(f,h)=>f.half[0]*Math.abs(Ne(f.axes[0],h))+f.half[1]*Math.abs(Ne(f.axes[1],h))+f.half[2]*Math.abs(Ne(f.axes[2],h)),a=f=>i(r,f)+i(s,f),c=[...r.axes,...s.axes];for(let f of r.axes)for(let h of s.axes){let p=oo(f,h),g=Math.sqrt(Ne(p,p));g>_T&&c.push([p[0]/g,p[1]/g,p[2]/g])}let u=[];for(let f of c){let h=Ne(o,f),p=a(f)-Math.abs(h);if(p<=0)return null;u.push({depth:p,n:h<0?it(f):f})}let l=u.reduce((f,h)=>h.depth<f.depth?h:f),d=Ne(o,n);return{plane:n,level:!1,side:l,axes:u,across:{depth:a(n)-Math.abs(d),n:d<0?it(n):n},d:o,half:a}}function ah(t,e){let n=Jl(t)+Jl(e),r=(t.top+e.top)/2,s=Math.sqrt(n*n+r*r)+r;if(Math.abs(e.b.x-t.b.x)>=s||Math.abs(e.b.y-t.b.y)>=s||Math.abs(e.b.z-t.b.z)>=s)return null;if(t.up[2]===1&&e.up[2]===1)return ST(t,e);if(t.up[0]===e.up[0]&&t.up[1]===e.up[1]&&t.up[2]===e.up[2])return ET(t,e);let o=[t.up[0]+e.up[0],t.up[1]+e.up[1],t.up[2]+e.up[2]],i=Math.sqrt(Ne(o,o));return i<1e-9?null:RT(t,e,[o[0]/i,o[1]/i,o[2]/i])}var Zl=(t,e,n)=>-((e.vx-t.vx)*n[0]+(e.vy-t.vy)*n[1]+((e.vz??0)-(t.vz??0))*n[2]);function kT(t,e,n,r){let s=t.across.depth/Math.max(Zl(e.b,n.b,t.across.n),r.entrySpeed),i=s<=r.entryWindow&&t.across.depth<=(e.top+n.top)/4||!t.level&&t.across.depth<=r.groundTrace;if(!i)return{across:!1,landed:i};let a=t.side.depth/Math.max(Zl(e.b,n.b,t.side.n),r.entrySpeed);return{across:s<a||s===a&&t.across.depth<t.side.depth,landed:i}}function qw(t){let e=[...t.tags??[]],n=t.flags??0;for(let r=0;r<24;r++)Math.floor(n/2**r)%2===1&&e.push(`flag:${r}`);return e}function _i(t,e,n){if(t.pairs.length===0)return t.top;let r=qw(e),s=qw(n),o=i=>r.includes(i.a)&&s.includes(i.b)||r.includes(i.b)&&s.includes(i.a);return t.pairs.find(o)?.top??t.top}function uh(t,e,n){let r=ah(t,e);if(r===null)return PT(t,e,n);let s=kT(r,t,e,n);if(!s.across){let l=Ne(r.d,r.plane)>=0;return{contact:{kind:so.Side,n:r.side.n,depth:r.side.depth,upperIsB:l},g:r}}let o=r.across.n,i=o===r.plane||Ne(o,r.plane)>0,a=i?t:e,c=i?o:it(o);return{contact:{kind:s.landed&&Ne(c,a.support)>=n.supportCos?so.Top:so.Side,n:o,depth:r.across.depth,upperIsB:i},g:r}}function PT(t,e,n){let r=e.b.z>=t.b.z,s=l=>({...l,b:{...l.b,z:l.b.z-n.groundTrace}}),o=r?ah(t,s(e)):ah(s(t),e);if(o===null||!(o.across.depth<o.side.depth))return null;let i=r?o.across.n:it(o.across.n);if(!(Ne(i,o.plane)>0))return null;let a=r?t:e;if(a.support[2]<n.supportCos||Ne(i,a.support)<n.supportCos)return null;let[c,u]=r?[e.b,t.b]:[t.b,e.b];return-Zl(u,c,i)>n.entrySpeed?null:{contact:{kind:so.Top,n:o.across.n,depth:o.across.depth-n.groundTrace,upperIsB:r},g:o}}function AT(t,e,n,r){return lh(t,e,n)?null:uh(io(t,n,r),io(e,n,r),n)?.contact??null}function vT(t){let e=t.shape;return e.kind===Vn.Hull?Math.sqrt(2*e.radius*e.radius+e.height*e.height):Math.sqrt(e.length*e.length/4+e.width*e.width/4+e.top*e.top)}function lh(t,e,n){let r=2*vT(n)+n.groundTrace+1,s=e.x-t.x,o=e.y-t.y,i=e.z-t.z;return s*s+o*o+i*i>r*r}var Zw=t=>e=>{let n=t.maxVelocity;return n===null?e:e<-n?-n:e>n?n:e},Ir=t=>[t.x,t.y,t.z],TT=.7,MT=.5,Gw=.5;function Ei(t,e,n,r,s,o){let i=dc(t,e,n,r,Ne(n,o)<-MT?void 0:s),a=i.t,c=i.face;if(c===null||!(a<r))return{d:n,straight:a,slide:null,cos:1,sep:a};let u=[c[0],c[1],c[2]],l=CT(u,n,o);if(l===null)return{d:n,straight:a,slide:null,cos:1,sep:a};let d=Ne(l,n),f=[e[0]+n[0]*a,e[1]+n[1]*a,e[2]+n[2]*a],h=dc(t,f,l,(r-a)/d,s).t;return{d:n,straight:a,slide:l,cos:d,sep:a+h*d}}function CT(t,e,n){if(Ne(t,n)>=TT){let a=Ne(e,t),c=[e[0]-a*t[0],e[1]-a*t[1],e[2]-a*t[2]],u=Math.hypot(c[0],c[1],c[2]);return u>=Gw?[c[0]/u,c[1]/u,c[2]/u]:null}let r=oo(t,n),s=Math.hypot(r[0],r[1],r[2]),o=s>0?Ne(r,e)/s:0;if(!(Math.abs(o)>=Gw))return null;let i=o>0?1/s:-1/s;return[r[0]*i,r[1]*i,r[2]*i]}function Ww(t,e){let n=t.d;if(t.slide===null||!(e>t.straight))return[n[0]*e,n[1]*e,n[2]*e];let r=(e-t.straight)/t.cos,s=t.slide;return[n[0]*t.straight+s[0]*r,n[1]*t.straight+s[1]*r,n[2]*t.straight+s[2]*r]}function OT(t,e,n=.5){let r=Math.min(e,1-Math.min(t,n));return[Math.min(t,1-r),r]}function IT(t,e,n,r,s,o,i,a=fc,c=fc,u=.5){if(s===null)return[u,1-u];let l=Ei(s,Ir(t),it(n),r,o,a),d=Ei(s,Ir(e),n,r,i,c);return OT(l.sep/r,d.sep/r,u)}function Qw(t,e,n,r){if(r.push!==to.Mover)return .5;let s=t.vx*n[0]+t.vy*n[1],o=e.vx*n[0]+e.vy*n[1];n[2]!==0&&(s+=(t.vz??0)*n[2],o+=(e.vz??0)*n[2]);let i=s>0?s:0,a=o<0?-o:0;return i+a>0?i/(i+a):.5}function ch(t,e,n,r,s,o){let[i,a]=IT(t.b,e.b,n,r,o.world,ro(t,s),ro(e,s),t.support,e.support,Qw(t.b,e.b,n,s));return o.fixed===void 0?[i,a]:t.b.id===o.fixed?[0,o.world===null?1:Ei(o.world,Ir(e.b),n,r,ro(e,s),e.support).sep/r]:e.b.id===o.fixed?[o.world===null?1:Ei(o.world,Ir(t.b),it(n),r,ro(t,s),t.support).sep/r,0]:[i,a]}var ro=(t,e)=>Vw(t.support,e.supportCos);function DT(t,e,n,r,s,o){let i=r.axes.filter(l=>l.n!==n.n).sort((l,d)=>l.depth-d.depth);for(let l of i){let[d,f]=ch(t,e,l.n,l.depth,s,o);if(!(d+f<1))return{n:l.n,depth:l.depth,sa:d,sb:f}}let[a,c]=ch(t,e,n.n,n.depth,s,o),u=1-a-c;return t.b.id===o.fixed?{n:n.n,depth:n.depth,sa:a,sb:c+u}:e.b.id===o.fixed?{n:n.n,depth:n.depth,sa:a+u,sb:c}:{n:n.n,depth:n.depth,sa:a+u/2,sb:c+u/2}}function Yw(t,e){t.x+=e[0],t.y+=e[1],e[2]!==0&&(t.z+=e[2])}function BT(t,e,n,r,s,o,i,a){let[c,u]=[t.b,e.b],l=a.world,d=it(n),f=l===null?{d,straight:r,slide:null,cos:1,sep:r}:Ei(l,Ir(c),d,r,ro(t,i),t.support),h=l===null?{d:n,straight:r,slide:null,cos:1,sep:r}:Ei(l,Ir(u),n,r,ro(e,i),e.support);Yw(c,Ww(f,r*s)),Yw(u,Ww(h,r*o))}function NT(t,e,n,r,s,o,i){let a=Zw(s),[c,u]=[t.b,e.b],[l,d]=ch(t,e,n.n,n.depth,s,o),f=l+d<1?DT(t,e,n,r,s,o):null,{depth:h,n:p,sa:g,sb:x}=f??{depth:n.depth,n:n.n,sa:l,sb:d},[b,S,_]=p,P=(u.vx-c.vx)*b+(u.vy-c.vy)*S;_!==0&&(P+=((u.vz??0)-(c.vz??0))*_);let R=P<0&&!i?-(1+s.restitution)*P/2:0,v=Qw(c,u,p,s),M=2*R*v,O=2*R*(1-v);return BT(t,e,p,h,g,x,s,o),c.vx=a(c.vx-M*b),c.vy=a(c.vy-M*S),s.stopSpin&&(c.spin=0),u.vx=a(u.vx+O*b),u.vy=a(u.vy+O*S),s.stopSpin&&(u.spin=0),_!==0&&(c.vz=a((c.vz??0)-M*_),u.vz=a((u.vz??0)+O*_)),{j:R,n:p,depth:h}}function ex(t,e){let n=e?t.side.n:it(t.side.n),r=e?t.d:it(t.d),s=oo(t.plane,n);return[n,it(n),s,it(s)].map(i=>({w:i,move:t.half(i)-Ne(r,i)})).map((i,a)=>({way:i,k:a})).sort((i,a)=>i.way.move-a.way.move||i.k-a.k).map(i=>i.way)}var Kw=(t,e,n)=>t.half(n)-Ne(e?t.d:it(t.d),n);function LT(t,e,n,r,s){let o=[];for(let i of n){if(i===t.b||i===e||lh(t.b,i,r)||_i(r,t.b,i).policy===ot.Ghost)continue;let a=uh(t,io(i,r,s),r);a!==null&&a.contact.kind===so.Top&&!a.contact.upperIsB&&o.push(a.g)}return o}function FT(t,e,n){if(n.length===0)return ex(t,e);let r=e?t.side.n:it(t.side.n),s=oo(t.plane,r);return[r,it(r),s,it(s)].map(i=>({w:i,move:n.reduce((a,c)=>Math.max(a,Kw(c,!1,i)),Kw(t,e,i))})).map((i,a)=>({way:i,k:a})).sort((i,a)=>i.way.move-a.way.move||i.k-a.k).map(i=>i.way)}var Xw=(t,e,n,r)=>n.move<=0||Wl(t,Ir(e.b),n.w,n.move,ro(e,r))>=n.move;function oh(t,e,n,r){t.vx=r(t.vx+n*e[0]),t.vy=r(t.vy+n*e[1]),e[2]!==0&&(t.vz=r((t.vz??0)+n*e[2]))}function Jw(t,e){if(!(e<t.speed))return 0;let n=t.speed-e;return t.step===null?n:Math.min(n,t.step)}function Kl(t,e,n,r,s,o,i,a){let[c,u]=[t.b,e.b],l=Zw(o),d=ex(n,r),f=FT(n,r,LT(t,u,a,o,i)).find(x=>Xw(i.world,t,x,o));if(f!==void 0){let x=(c.vx-u.vx)*f.w[0]+(c.vy-u.vy)*f.w[1]+((c.vz??0)-(u.vz??0))*f.w[2],b=Jw(s,x);return oh(c,f.w,b*s.share,l),s.share!==1&&oh(u,f.w,-b*(1-s.share),l),{j:b,way:Xl.Free,w:f.w}}let h=d.map(x=>({w:it(x.w),move:x.move})).find(x=>Xw(i.world,e,x,o));if(h===void 0)return{j:0,way:Xl.Pinned,w:null};let p=(u.vx-c.vx)*h.w[0]+(u.vy-c.vy)*h.w[1]+((u.vz??0)-(c.vz??0))*h.w[2],g=Jw(s,p);return oh(u,h.w,g,l),{j:g,way:Xl.LowerYields,w:h.w}}function zT(t,e,n,r,s,o,i,a){let c=r+i.roofSkin;if(!(c>0))return;let u=t.id===a.fixed?0:Wl(a.world,Ir(t),n,c);if(u>=c&&s.level){t.z=e.z+o+i.roofSkin;return}if(t.x+=n[0]*u,t.y+=n[1]*u,t.z+=n[2]*u,u>=c)return;let l=e.id===a.fixed?0:Wl(a.world,Ir(e),it(n),c-u);e.x-=n[0]*l,e.y-=n[1]*l,e.z-=n[2]*l}function UT(t,e,n){let r=t.vx*n[0]+t.vy*n[1]+(t.vz??0)*n[2],s=e.vx*n[0]+e.vy*n[1]+(e.vz??0)*n[2];if(r<s){if(n[0]===0&&n[1]===0){t.vz=e.vz??0;return}t.vx+=n[0]*(s-r),t.vy+=n[1]*(s-r),t.vz=(t.vz??0)+n[2]*(s-r)}}function VT(t,e,n){let r=t.vx*e[0]+t.vy*e[1]+(t.vz??0)*e[2];t.vx+=e[0]*(n-r),t.vy+=e[1]*(n-r),t.vz=(t.vz??0)+e[2]*(n-r)}function dh(t,e,n){let r=t.x-e.x,s=t.y-e.y,o=n.shape;if(o.kind===Vn.Hull)return Math.max(Math.abs(r),Math.abs(s))/o.radius;let[i,a]=Dt(e.yaw);return Math.max(Math.abs(r*a+s*i)/(o.length/2),Math.abs(s*a-r*i)/(o.width/2))}function HT(t,e,n){if(n)return 0;let r=t.x-e.x,s=t.y-e.y,o=Math.sqrt(r*r+s*s);return o>0?-(e.vx*r+e.vy*s)/o:0}var $T=100,cs={Stand:"stand",Release:"release",Slide:"slide"};function tx(t,e,n,r){if(n.center===null)return cs.Stand;let s=dh(t,e,r);return s<=n.center?cs.Stand:(e.vz??0)-(t.vz??0)>$T?cs.Slide:HT(t,e,n.ride)>=(n.slide.step??n.slide.speed)/2?cs.Release:s>1?cs.Slide:cs.Stand}var nx=(t,e,n,r)=>n.policy===ot.Stand&&tx(t,e,n,r)===cs.Stand;function jT(t,e,n,r,s,o,i,a){let[c,u]=n.upperIsB?[e,t]:[t,e],l=c.b,d=u.b,f=n.upperIsB?n.n:it(n.n),h=Zl(d,l,f),p=s.policy===ot.Stand&&tx(l,d,s,o)===cs.Slide;return zT(l,d,f,n.depth,r,u.top,o,i),UT(l,d,f),u.support[2]<o.supportCos?Kl(c,u,r,n.upperIsB,o.offWall,o,i,a):s.policy===ot.Stand?p?Kl(c,u,r,n.upperIsB,s.slide,o,i,a):sh:s.policy===ot.Slide?Kl(c,u,r,n.upperIsB,s,o,i,a):s.policy===ot.Bounce&&h>=s.stompMin?(VT(l,f,s.bounceSpeed+(l.jump?s.jumpBoost:0)),i.onContact?.(l,d,wT.Stomp),sh):s.policy===ot.Bounce?Kl(c,u,r,n.upperIsB,s.slide,o,i,a):sh}function rx(t,e,n,r,s=!1,o=[]){let i=_i(n,t,e);if(i.policy===ot.Ghost||lh(t,e,n))return null;let a=io(t,n,r),c=io(e,n,r),u=uh(a,c,n);if(u===null)return null;let{contact:l,g:d}=u;return l.kind===so.Side?{...l,...NT(a,c,l,d,n,r,s),way:null,w:null}:{...l,...jT(a,c,l,d,i,n,r,o)}}function qT(t,e,n,r,s,o,i){let a=o.cooling?o.cooling(t,e):!1,c=n===0?o.first?.(t,e,a):void 0;return c===void 0?rx(t,e,r,s,a,i):c}var GT=(t,e)=>t!==null&&(t.depth>e.slop||t.kind===so.Top&&t.depth>0);function WT(t,e,n,r,s,o){let i=!1;for(let a=0;a<t.length;a++)for(let c=a+1;c<t.length;c++){let u=t[a],l=t[c];if(e>0&&!GT(AT(u,l,n,r),n))continue;let d=qT(u,l,e,n,r,s,t);d!==null&&(i=!0,d.way===Xl.Pinned&&(o.pinned+=1),s.onPair?.(u,l,d))}return i}function YT(t,e,n,r={}){let s={passes:0,pushed:new Map,walls:new Map,pinned:0};for(let o=0;o<e.passes&&WT(t,o,e,n,r,s);o++)if(s.passes+=1,n.world!==null)for(let i of t){let a=u=>{u[2]<e.supportCos&&u[3]>(s.walls.get(i.id)??0)&&s.walls.set(i.id,u[3])},c=$w(n.world,i,a);c>(s.pushed.get(i.id)??0)&&s.pushed.set(i.id,c)}return s}var fh=(t,e)=>(n,r)=>{rx(n,r,t,e)},sx=(t,e)=>n=>{YT(n,t,e)};function ox(t){return t.top.policy===ot.Stand||t.pairs.some(e=>e.top.policy===ot.Stand)}function KT(t,e,n){let r=t.x+t.vx*n,s=t.y+t.vy*n,o=t.z+(t.vz??0)*n,i=e.shape,a=e.groundTrace;if(i.kind===Vn.Hull){let l=i.radius;return{kind:"box",min:[r-l,s-l,o+i.height-a],max:[r+l,s+l,o+i.height]}}let[c,u]=Dt(t.yaw);return{kind:"obox",c:[r,s,o+i.top-a/2],half:[i.length/2,i.width/2,a/2],sin:c,cos:u}}var ix=t=>t.shape.kind===Vn.Hull?t.shape.height:t.shape.top,ax=2;function XT(t,e,n,r){let s=_i(n,t,e);if(s.policy!==ot.Stand)return!1;let o=ix(n);return t.z<e.z+o-n.groundTrace||t.z>e.z+2*o||!(dh(t,e,n)<ax)||io(e,n,r).support[2]<n.supportCos?!1:nx(t,e,s,n)}var JT=t=>ax*(t.shape.kind===Vn.Hull?t.shape.radius:Math.hypot(t.shape.length,t.shape.width)/2);function ZT(t,e,n=0){let r=ix(e),s=JT(e);for(let o of t)for(let i of t){if(i===o)continue;let a=i.z+(i.vz??0)*n;if(o.z<a+r-e.groundTrace||o.z>a+2*r)continue;let c=(Math.abs(i.vx)+Math.abs(i.vy))*n;if(Math.abs(o.x-i.x)<s+c&&Math.abs(o.y-i.y)<s+c)return!0}return!1}function pc(t,e,n,r){return ZT(t,e)?t.map(s=>{let o=[],i=[];for(let a of t)a===s||!XT(s,a,e,n)||(o.push(KT(a,e,r)),i.push(a.id));return{solids:o,lowers:i}}):t.map(()=>({solids:[],lowers:[]}))}function ph(t,e,n){let[r,s,o]=[e[0],e[1],e[2]],[i,a,c]=[n[0],n[1],n[2]];return t.find(u=>Math.abs(i-u.x)<=r&&Math.abs(a-u.y)<=s&&c>u.z+2*o&&c<=u.z+4*o)}function cx(t,e,n,r){let s=[];for(let o of n){let[i,a]=[o.p[0],o.p[1]],c=ph(t,e,o.p);if(c===void 0)continue;let u=i-c.x,l=a-c.y,d=Math.hypot(u,l),[f,h]=d>0?[u/d,l/d]:[1,0],[p,g,x]=[o.v[0],o.v[1],o.v[2]],b=(p-c.vx)*f+(g-c.vy)*h;if(!(b<r.speed))continue;let S=Math.min(r.step,r.speed-b);s.push({key:o.key,v:[p+f*S,g+h*S,x]})}return s}var ao={Box:"box",Disc:"disc"},ux={PingPong:"pingpong",Loop:"loop"},lx={Linear:"linear",Smooth:"smooth"},dx={All:"all",None:"none"},fx=Object.freeze({platforms:Object.freeze([]),bodies:!1});var S2=2**24;var E2=2*Math.PI;var mx=2*Math.PI,Mt=Math.fround,yx=(t,e)=>(t%e+e)%e;function QT(t,e,n,r,s){if(s===lx.Linear)return[Mt(t[0]+(e[0]-t[0])*n/r),Mt(t[1]+(e[1]-t[1])*n/r),Mt(t[2]+(e[2]-t[2])*n/r)];let o=n/r,i=o*o*(3-2*o);return[Mt(t[0]+(e[0]-t[0])*i),Mt(t[1]+(e[1]-t[1])*i),Mt(t[2]+(e[2]-t[2])*i)]}function eM(t,e){let n=t.legs.length,r=t.mode===ux.Loop,s=r?n:2*n,o=e;for(let i=0;i<s;i++){let a=i,c=i,u=i+1;r?u=(i+1)%n:i>=n&&(a=2*n-1-i,c=a+1,u=a);let l=t.legs[a],d=t.points[u];if(o<l)return QT(t.points[c],d,o,l,t.ease);o-=l;let f=t.waits[u];if(o<f)return d;o-=f}return t.points[0]}function tM(t,e,n,r){return t.called?r===void 0||n<r||n-r>=e.period?0:n-r:yx(n+e.phase,e.period)}function us(t,e,n){let r=t.path===null?t.at:eM(t.path,tM(t,t.path,e,n)),s=t.spin;return s===null?{c:r,yaw:0}:{c:r,yaw:Mt(s.dir*(mx*yx(e+s.phase,s.period)/s.period))}}function px(t,e,n){return t.platforms.map(r=>us(r,e,n?.get(r.id)))}var hh=t=>t.spin===null?0:t.spin.dir*mx/t.spin.period;function ed(t,e,n,r,s){let o=us(t,n,s),i=us(t,n+1,s),a=hh(t),c,u;if(a===0)c=e.x+(i.c[0]-o.c[0]),u=e.y+(i.c[1]-o.c[1]);else{let[d,f]=Dt(a),h=e.x-o.c[0],p=e.y-o.c[1];c=i.c[0]+(f*h-d*p),u=i.c[1]+(d*h+f*p)}let l=e.z+(i.c[2]-o.c[2]);if(t.surface!==null){let[d,f]=t.surface;if(i.yaw===0)c+=d/r,u+=f/r;else{let[h,p]=Dt(i.yaw);c+=(p*d-h*f)/r,u+=(h*d+p*f)/r}}return{x:c,y:u,z:l,yaw:e.yaw+a,v:[(c-e.x)*r,(u-e.y)*r,(l-e.z)*r]}}function Ql(t,e){return t.platforms.map((n,r)=>{let{c:s,yaw:o}=e[r],i=n.shape;if(i.kind===ao.Disc)return{kind:"disc",c:s,radius:i.radius,half:i.half};let a=i.half;if(n.spin===null)return{kind:"box",min:[s[0]-a[0],s[1]-a[1],s[2]-a[2]],max:[s[0]+a[0],s[1]+a[1],s[2]+a[2]]};let[c,u]=Dt(o);return{kind:"obox",c:s,half:a,sin:c,cos:u}})}var gx=4;function td(t,e,n){return{now:Ql(t,px(t,e,n)),next:Ql(t,px(t,e+1,n))}}var bx=(t,e)=>t?.get(e.id);function hx(t,e){t.x=Mt(e.x),t.y=Mt(e.y),t.z=Mt(e.z)}function nM(t,e,n,r,s){let o=[],i=[],a=s===void 0?null:pc(e,s.policy,s.env,0);return e.forEach((c,u)=>{let l=a?.[u];if(n.length===0&&(l===void 0||l.solids.length===0)){o.push(-1),i.push(null);return}let d=l===void 0||l.solids.length===0?r.support(c,n):r.support(c,[...n,...l.solids]),f=d>=t.platforms.length&&l!==void 0?e.find(p=>p.id===l.lowers[d-t.platforms.length])??null:null,h=s!==void 0&&f!==null?_i(s.policy,c,f):null;o.push(d<t.platforms.length?d:-1),i.push(f!==null&&h?.policy==="stand"&&h.ride?f.id:null)}),{bases:o,on:i}}function rM(t,e,n,r,s,o,i){let a=e.map((l,d)=>{let f=n[d];if(f<0)return null;let h=t.platforms[f];return ed(h,l,s,o,bx(i,h))}),c=new Map(e.map((l,d)=>[l.id,d])),u=(l,d)=>{let f=a[l];if(f!=null)return[f.x-e[l].x,f.y-e[l].y,f.z-e[l].z];let h=r[l]===null||r[l]===void 0?void 0:c.get(r[l]);return h===void 0||d>=gx?[0,0,0]:u(h,d+1)};return e.map((l,d)=>{if(a[d]!==null)return a[d];if(r[d]===null)return null;let f=u(d,0);return{x:l.x+f[0],y:l.y+f[1],z:l.z+f[2],yaw:l.yaw,v:[f[0]*o,f[1]*o,f[2]*o]}})}function wx(t,e,n,r,s,o,i,a=td(t,n,s),c){let{now:u,next:l}=a,d=e.map(b=>({...b})),{bases:f,on:h}=nM(t,d,u,o,c),p=rM(t,d,f,h,n,r,s),g=[],x=[];return e.forEach((b,S)=>{let _=f[S],P=p[S]??null;P!==null&&(hx(b,P),i&&_>=0&&(b.yaw=Mt(P.yaw))),g.push(P===null?null:P.v),t.platforms.forEach((R,v)=>{if(v===_||!o.inside(b,l,v))return;let M=ed(R,b,n,r,bx(s,R)),O=o.pushOut({...b,x:M.x,y:M.y,z:M.z},l);hx(b,O),O.inside&&x.push({seat:b.id,lift:R.id})})}),{bases:f,on:h,v:g,crushed:x,from:e.map(b=>[b.x,b.y,b.z])}}function xx(t,e,n){if(e.on.every(c=>c===null))return e;let r=new Map(t.map((c,u)=>[c.id,u])),s=t.map((c,u)=>{let l=e.from[u];return[c.x-l[0],c.y-l[1]]}),o=(c,u)=>{let l=e.on[c],d=l==null?void 0:r.get(l);if(d===void 0||u>=gx)return[0,0];let f=s[d],h=o(d,u+1);return[f[0]+h[0],f[1]+h[1]]},i=t.map((c,u)=>o(u,0)),a=e.v.map((c,u)=>{let l=i[u];return c===null||e.on[u]===null?c:[c[0]+l[0]*n,c[1]+l[1]*n,c[2]]});return t.forEach((c,u)=>{let l=i[u];e.on[u]!==null&&(c.x=Mt(c.x+l[0]),c.y=Mt(c.y+l[1]))}),{...e,v:a}}function sM(t,e,n,r,s,o){let i=pc(t,o.policy,o.env,0)[e];if(i===void 0||i.solids.length===0)return!1;let a=s.support(t[e],[...r,...i.solids]);return a>=r.length&&i.lowers[a-r.length]===n}function Sx(t,e,n,r,s,o,i=td(t,r,s).next,a){if(n.v.every(u=>u===null))return;let c=e.map(u=>({...u}));e.forEach((u,l)=>{let d=n.bases[l]??-1,f=n.v[l],h=n.on[l]??null;if(f!=null){if(h!==null&&a!==void 0){if(sM(c,l,h,i,o,a))return}else if(d<0||t.platforms[d].impart!==dx.All||o.support(u,i)===d)return;u.vx=Mt(u.vx+f[0]),u.vy=Mt(u.vy+f[1]),u.vz=Mt(u.vz+f[2])}})}var hc=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function oM(t){return!hc(t)||!Array.isArray(t.platforms)||typeof t.bodies!="boolean"?!1:t.platforms.every(e=>hc(e)&&typeof e.id=="string"&&hc(e.shape)&&Array.isArray(e.at)&&typeof e.called=="boolean")}function kx(t,e,n,r){if(!t)return null;let s;try{s=JSON.parse(t)}catch{return null}if(!hc(s)||s.name!==lr.FIRSTPERSON&&s.name!==lr.VEHICLE)return null;let o=oM(s.lifts)?s.lifts:null;if(o===null&&n===void 0)return null;let i=wi(s.name,s.params);return{policy:o??fx,ops:mw(s.name,i,e),vehicle:s.name===lr.VEHICLE,heads:n,tickHz:r}}function Px(t){if(!t)return;let e;try{e=JSON.parse(t)}catch{return}if(!hc(e))return;let n=new Map;for(let[r,s]of Object.entries(e))typeof s=="number"&&Number.isInteger(s)&&n.set(r,s);return n}var iM=128,Ri=class{constructor(){m(this,"kept",new Map);m(this,"startsText","")}at(e,n,r){let s=r===void 0?"":JSON.stringify([...r]);s!==this.startsText&&(this.kept.clear(),this.startsText=s);let o=this.kept.get(n);if(o!==void 0)return o;let i=td(e,n,r),a={solids:i,next:sc(i.next)};return this.kept.size>=iM&&this.kept.delete(this.kept.keys().next().value),this.kept.set(n,a),a}};function yc(t,e,n,r,s,o){let{solids:i,next:a}=o.at(t.policy,n,r),c=wx(t.policy,e,n,t.tickHz,r,t.ops,t.vehicle,i,t.heads),u=new Map;return t.heads!==void 0&&pc(e,t.heads.policy,t.heads.env,s).forEach((d,f)=>{d.solids.length>0&&u.set(e[f].id,sc([...i.next,...d.solids]))}),{tick:n,solids:i,report:c,seats:e,posed:u,next:a}}function Ax(t,e){e.report=xx(e.seats,e.report,t.tickHz)}function vx(t,e,n,r){let s=e.report.v;e.report={...e.report,v:s.map((o,i)=>i!==n||o===null?o:[o[0]+r[0]*t.tickHz,o[1]+r[1]*t.tickHz,o[2]])}}var gc=(t,e)=>t.posed.get(e)??t.next;function bc(t,e,n){Sx(t.policy,e.seats,e.report,e.tick,n,t.ops,e.solids.next,t.heads)}function aM(t,e,n){return t.platforms.map((r,s)=>mc(t,s,e,n))}function mc(t,e,n,r){let s=t.platforms[e];if(s===void 0)return{c:[0,0,0],yaw:0};let o=Math.floor(n),i=us(s,o,r?.get(s.id)),a=us(s,o+1,r?.get(s.id)),c=s.spin===null?0:s.spin.dir*2*Math.PI/s.spin.period,u=n-o;return{c:[i.c[0]+(a.c[0]-i.c[0])*u,i.c[1]+(a.c[1]-i.c[1])*u,i.c[2]+(a.c[2]-i.c[2])*u],yaw:i.yaw+c*u}}function wc(t,e,n,r){return t.policy.platforms.length===0?-1:t.ops.support({x:e.x,y:e.y,z:e.z,vz:0,duck:e.duck??0},Ql(t.policy,aM(t.policy,n,r)))}function mh(t,e,n,r,s,o){let i=mc(t,e,r,o),a=mc(t,e,s,o),c=a.yaw-i.yaw,[u,l]=[Math.sin(c),Math.cos(c)],d=n.x-i.c[0],f=n.y-i.c[1];return{x:a.c[0]+l*d-u*f,y:a.c[1]+u*d+l*f,z:n.z+a.c[2]-i.c[2],yaw:n.yaw+c}}function Tx(t,e,n,r){let s=t.platforms.findIndex(i=>i.id===e);if(s<0)return;let o=mc(t,s,n,r);return{x:o.c[0],y:o.c[1],z:o.c[2],yaw:o.yaw}}function yh(t,e,n,r){let s=t.platforms[e];if(s===void 0)return 0;let o=s.shape.kind===ao.Box?s.shape.half[2]:s.shape.half;return mc(t,e,n,r).c[2]+o}var Ex=["x","y","z"],_x=["vx","vy","vz"];function Mx(t,e,n,r,s,o,i){let a={...t,heads:void 0},c={id:"",x:s.x??0,y:s.y??0,z:s.z??0,vx:s.vx??0,vy:s.vy??0,vz:s.vz??0,yaw:s.yaw??0,duck:s.duck??0,flags:0},u=yc(a,[c],o,e,i,n);for(let l of Ex)s[l]=c[l];t.vehicle&&(s.yaw=c.yaw),r(s,gc(u,c.id));for(let l of[...Ex,..._x])c[l]=s[l]??0;bc(a,u,e);for(let l of _x)s[l]=c[l]}var xc=t=>`lift.${t}`,Rx=16;function cM(t){let e=t.surface===null?{}:{friction:0};if(t.shape.kind===ao.Box)return{key:"lift",shape:{kind:"box",half:[t.shape.half[0],t.shape.half[1],t.shape.half[2]]},...e};let{radius:n,half:r}=t.shape,s=[];for(let o=0;o<Rx;o++){let[i,a]=Dt(2*Math.PI*o/Rx);s.push([Math.fround(n*a),Math.fround(n*i),-r],[Math.fround(n*a),Math.fround(n*i),r])}return{key:"lift",shape:{kind:"hull",points:s},...e}}function nd(t,e,n){let r=us(t,e,n?.get(t.id)),[s,o]=Dt(r.yaw/2);return{p:[r.c[0],r.c[1],r.c[2]],q:[0,0,Math.fround(s),Math.fround(o)]}}function Cx(t,e,n){return{key:xc(t.id),type:"kinematic",pose:nd(t,e,n),colliders:[cM(t)]}}var uM=20;function lM(t,e,n,r){let s=n-e.c[0],o=r-e.c[1],[i,a]=e.yaw===0?[0,1]:Dt(e.yaw),c=a*s+i*o,u=a*o-i*s;return t.shape.kind===ao.Disc?c*c+u*u<=t.shape.radius*t.shape.radius:Math.abs(c)<=t.shape.half[0]&&Math.abs(u)<=t.shape.half[1]}var dM=(t,e)=>e+(t.shape.kind===ao.Disc?t.shape.half:t.shape.half[2]);function gh(t,e,n,r){let s=t.platforms.filter(i=>i.surface!==null),o=s.map(i=>us(i,e,n?.get(i.id)));return i=>{let[a,c,u]=[i[0],i[1],i[2]];return s.find((l,d)=>{let f=o[d],h=u-dM(l,f.c[2]);return h>0&&h<=r&&lM(l,f,a,c)})}}function Ox(t,e,n,r,s,o){let i=gh(t,e,n,o),a=Math.min(1,uM/r),c=[];for(let u of s){let[l,d,f]=[u.p[0],u.p[1],u.p[2]],h=i(u.p);if(h===void 0)continue;let p=ed(h,{x:l,y:d,z:f,yaw:0},e,r,n?.get(h.id)),[g,x,b]=[u.v[0],u.v[1],u.v[2]],S=p.v[0]-g,_=p.v[1]-x;S===0&&_===0||c.push({key:u.key,v:[g+S*a,x+_*a,b]})}return c}var co=15,fM=65535;var pM=Object.values(jt),Ix=(t,e,n)=>typeof t=="number"&&Number.isFinite(t)&&t>=e&&t<=n,Dr=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Dx=t=>typeof t=="number"&&Number.isFinite(t)&&t>0;function Ec(t){if(t===void 0||t==="")return null;let e;try{e=JSON.parse(t)}catch{return null}if(!Dr(e)||!Dr(e.world))return null;let{keyframeTicks:n,maxLinear:r,maxAngular:s}=e;if(!(typeof n=="number"&&Number.isInteger(n)&&n>=1)||!Dx(r)||!Dx(s))return null;let i=e.presetBody,a=Dr(i)&&Array.isArray(i.half)&&i.half.length===3?{half:i.half,events:i.events===!0}:null,c=pM.includes(e.remotePredict)?e.remotePredict:dr.DEFAULT_REMOTE_PREDICT,u=e.remoteDecayMs,l=Ix(u,0,dr.MAX_REMOTE_DECAY_MS)?u:dr.DEFAULT_REMOTE_DECAY_MS,d=e.leadMs,f=Ix(d,dr.MIN_LEAD_MS,dr.MAX_LEAD_MS)?d:dr.DEFAULT_LEAD_MS;return{world:e.world,keyframeTicks:n,maxLinear:r,maxAngular:s,presetBody:a,remotePredict:c,remoteDecayMs:l,leadMs:f}}function bh(t){return Math.fround(Math.fround(t.dt)/t.substeps)}function hM(t,e){let n=Math.floor(t/e+.5);return Number.isNaN(n)||n<0?0:Math.min(n,fM)}var Sc=ql.ORIENTATION,ls=ql.VELOCITY,ki=t=>t===0?0:t;function Lx(t,e,n){e[n]=ki(t.x),e[n+1]=ki(t.y),e[n+2]=ki(t.z),e[n+3]=qt(t.qx,Sc),e[n+4]=qt(t.qy,Sc),e[n+5]=qt(t.qz,Sc),e[n+6]=qt(t.qw,Sc),e[n+7]=qt(t.lvx,ls),e[n+8]=qt(t.lvy,ls),e[n+9]=qt(t.lvz,ls),e[n+10]=qt(t.avx,ls),e[n+11]=qt(t.avy,ls),e[n+12]=qt(t.avz,ls),e[n+13]=t.sleep?1:0,e[n+14]=t.rest}function wh(t,e,n,r,s,o){s[o]=ki(t[e]),s[o+1]=ki(t[e+1]),s[o+2]=ki(t[e+2]);for(let i=3;i<7;i++)s[o+i]=qt(t[e+i],Sc);for(let i=7;i<10;i++)s[o+i]=qt(t[e+i]/n,ls);for(let i=10;i<13;i++)s[o+i]=qt(t[e+i],ls);s[o+13]=t[e+13]===1?1:0,s[o+14]=hM(t[e+14],r)}function Fx(t,e,n){let r=[...Array.from(t.p),...Array.from(t.q),...Array.from(t.v),...Array.from(t.w),t.sleeping?1:0,t.rest??0],s=[];return wh(r,0,e,n,s,0),s}function Bx(t,e){let n=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);if(!(n>e))return null;let r=e/n;return[t[0]*r,t[1]*r,t[2]*r]}function zx(t,e,n,r=Rw,s=kw){let o=Bx(t,r*n),i=Bx(e,s);return o===null&&i===null?null:{linvel:o??[t[0],t[1],t[2]],angvel:i??[e[0],e[1],e[2]]}}var V2=16*1024;function Ux(t,e){let n;try{n=JSON.parse(t)}catch{return null}if(!Dr(n)||!Array.isArray(n.colliders))return null;for(let r of n.colliders){if(!Dr(r)||!Dr(r.shape))return null;let s=r.shape.ref;if(s===void 0)continue;let o=typeof s=="string"?e(s):void 0;if(o===void 0)return null;try{r.shape=JSON.parse(o)}catch{return null}}return n}var Vx=.5,rd=t=>{if(!Array.isArray(t)||t.length!==3)return 0;let[e,n,r]=t;return Math.sqrt(e*e+n*n+r*r)},Nx=t=>Array.isArray(t)?t.reduce((e,n)=>Math.max(e,rd(n)),0):0;function mM(t){switch(t.kind){case"box":return rd(t.half);case"sphere":return typeof t.radius=="number"?t.radius:0;case"capsule":return(typeof t.halfHeight=="number"?t.halfHeight:0)+(typeof t.radius=="number"?t.radius:0);case"hull":return Nx(t.points);case"trimesh":return Nx(t.vertices);case"heightfield":return rd(t.size);default:return 0}}function _c(t){let e=Array.isArray(t.colliders)?t.colliders:[],n=0;for(let r of e){if(!Dr(r)||!Dr(r.shape))continue;let s=Dr(r.offset)?rd(r.offset.p):0;n=Math.max(n,s+mM(r.shape))}return n}function Hx(t,e,n){let r=new Map,s=u=>{let l=u;for(;r.get(l)!==l;)l=r.get(l);let d=u;for(;d!==l;){let f=r.get(d);r.set(d,l),d=f}return l},o=(u,l)=>{let d=s(u),f=s(l);d!==f&&(d<f?r.set(f,d):r.set(d,f))};for(let u of t)r.set(u.key,u.key);let i=[...t].sort((u,l)=>u.x-l.x||(u.key<l.key?-1:1)),a=i.reduce((u,l)=>Math.max(u,l.radius),0);for(let u=0;u<i.length;u++){let l=i[u];for(let d=u+1;d<i.length;d++){let f=i[d];if(f.x-l.x>l.radius+a+n)break;let h=f.x-l.x,p=f.y-l.y,g=f.z-l.z,x=l.radius+f.radius+n;h*h+p*p+g*g<=x*x&&o(l.key,f.key)}}for(let[u,l]of e)r.has(u)&&r.has(l)&&o(u,l);let c=new Map;for(let u of t)c.set(u.key,s(u.key));return c}function yM(t,e,n){if(n<=0)return t<=1?1:0;let r=1-(t-1)*(1e3/e)/n;return r<=0?0:r>=1?1:r}function od(t,e,n,r){let s=yM(e,n,r);return{...t,moveX:t.moveX*s,moveY:t.moveY*s,moveZ:t.moveZ*s}}var mt={TAU_SMALL_MS:300,TAU_LARGE_MS:100,SMALL_METRES:.25,LARGE_METRES:1,SNAP_PLAYER_METRES:2,SNAP_OTHER_METRES:6,PLAYER_KINDS:Object.freeze(["player","vehicle"]),SEAT_TAU_MS:70,SEAT_CONTACT_TAU_MS:100,SEAT_SNAP_METRES:6,SEAT_HOLD_MS:120,SEAT_MOVING_UNITS_PER_MS:.2,SEAT_CLOCK_TAU_MS:100,SEAT_CLOCK_SNAP_INPUTS:1.5};function gM(t,e){let n=Math.max(t,0)/e;return(1+n)*Math.exp(-n)}function id(t,e,n,r){let s=Math.max(n,0),o=r/2,i=Math.exp(-s/o),a=e+t/o;return[(t+a*s)*i,(e-a*s/o)*i]}function Pi(t){let{TAU_SMALL_MS:e,TAU_LARGE_MS:n,SMALL_METRES:r,LARGE_METRES:s}=mt;return t<=r?e:t>=s?n:e+(t-r)/(s-r)*(n-e)}var sd=class{constructor(){m(this,"last",null);m(this,"offset",null)}draw(e,n,r,s,o,i){let a=this.last;a===null||a.epoch!==r?this.offset=null:a.predicted!==n&&this.startFrom(a,e,s,o,i);let c=this.apply(e,s);return this.last={p:c.p,q:c.q,predicted:n,epoch:r},c}startFrom(e,n,r,s,o){let i=[e.p[0]-n.p[0],e.p[1]-n.p[1],e.p[2]-n.p[2]],a=Math.hypot(i[0],i[1],i[2])/o;if(a>s){this.offset=null;return}let c=zn(e.q,[-n.q[0],-n.q[1],-n.q[2],n.q[3]]),u=c[3]<0?[-c[0],-c[1],-c[2],-c[3]]:c;this.offset={dp:i,dq:u,since:r,tau:Pi(a)}}apply(e,n){let r=this.offset;if(r===null)return{p:[e.p[0],e.p[1],e.p[2]],q:[e.q[0],e.q[1],e.q[2],e.q[3]]};let s=gM(n-r.since,r.tau);return{p:[e.p[0]+r.dp[0]*s,e.p[1]+r.dp[1]*s,e.p[2]+r.dp[2]*s],q:zn(xi(r.dq,s),e.q)}}};function ad(t){return typeof t=="string"&&mt.PLAYER_KINDS.includes(t)?mt.SNAP_PLAYER_METRES:mt.SNAP_OTHER_METRES}function Wx(t,e,n,r){let s=(n-r.tickOrigin)*r.tickHz/1e3,o=Math.floor(s),i=t(e,o),a=t(e,o+1);if(i===null||a===null)return null;let c=s-o;return{p:[i.p[0]+(a.p[0]-i.p[0])*c,i.p[1]+(a.p[1]-i.p[1])*c,i.p[2]+(a.p[2]-i.p[2])*c],q:Mr([...i.q])}}var bM=.1,wM=30,ud={desktop:4,mobile:5};function Yx(t,e){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:e}var Rh=Object.freeze([128,64,32]),xh=60,xM=20,SM=2,$x=.5,EM=500,_M=4;function RM(t,e){for(let n=t+1;n<Rh.length;n++)if(Rh[n]<e)return n;return null}function jx(t,e){if(t.length===0)return 0;let n=[...t].sort((r,s)=>r-s);return n[Math.min(n.length-1,Math.floor(e*n.length))]}var qx=500,kM=.02,PM=200,He={ON:"on",OFF:"off",LOADING:"loading",UNAVAILABLE:"unavailable",MISMATCH:"mismatch",SELF_TEST:"self_test",DIVERGED:"diverged",CPU:"cpu"},AM=600;function Gx(t,e){return[id(t.dp[0],t.dv[0],e,t.tau),id(t.dp[1],t.dv[1],e,t.tau),id(t.dp[2],t.dv[2],e,t.tau)]}var Rc=[0,0,0,1],vM=[32767,32767,32767,65534,32767,32767,32767,32767,32767,32767,0,0],TM=[32767,32767,32767,32767,32767,32767,0,0],MM=t=>Math.floor((t+1)/2*65534+.5),Ai=[0,0,0],vi=(t,e)=>t<e?-1:t>e?1:0,CM=(t,e)=>{for(let n=0;n<co;n++)if(!Object.is(t[n],e[n]))return!1;return!0},cd=class{constructor(e,n){m(this,"status",He.LOADING);m(this,"core");m(this,"desc");m(this,"tickHz");m(this,"innerDt");m(this,"lengthUnit");m(this,"leadMax");m(this,"budgetMs");m(this,"clock");m(this,"remoteStep");m(this,"hashesKept");m(this,"world",null);m(this,"base",null);m(this,"seq",0);m(this,"simulated",new Map);m(this,"seats",new Map);m(this,"kinematic",new Map);m(this,"joints",new Map);m(this,"ring",new Map);m(this,"pure",new Set);m(this,"drawn",new Map);m(this,"kinds",new Map);m(this,"ruledClock",null);m(this,"ownPose",()=>{});m(this,"ownVelocity",()=>{});m(this,"bodyRule");m(this,"headSlide");m(this,"propStates",null);m(this,"propStale",!1);m(this,"kinematicRule");m(this,"lifts");m(this,"liftBodies",null);m(this,"seatRule");m(this,"seatPose");m(this,"contactPass");m(this,"posedBySeats",!1);m(this,"remoteBodies",new Map);m(this,"setSize",0);m(this,"costs",[]);m(this,"probedAt",Number.NEGATIVE_INFINITY);m(this,"calmProbes",0);m(this,"chosenCount",0);m(this,"fallbacks",0);m(this,"recoveries",0);m(this,"steppedAt",0);m(this,"canary",[]);m(this,"epochs",new Map);m(this,"hashes",[]);m(this,"chosenKeys",new Set);this.core=e,this.desc=n.desc,this.tickHz=n.tickHz,this.innerDt=bh(n.desc.world),this.lengthUnit=Math.fround(n.desc.world.lengthUnit);let r=n.leadMs??n.desc.leadMs;this.leadMax=Math.ceil(r*n.tickHz/1e3)+n.desc.keyframeTicks-1;let s=n.desc.remotePredict===jt.INPUT_DECAY||n.desc.remotePredict===jt.HOLD;this.remoteStep=s?n.remoteStep:void 0,this.seatPose=n.seatPose,this.contactPass=n.contactPass,this.budgetMs=n.budgetMs??ud.desktop,this.clock=n.clock??(()=>performance.now()),this.hashesKept=n.hashesKept??AM,this.bodyRule=n.bodyRule,this.headSlide=n.headSlide??(()=>null),this.kinematicRule=n.kinematicRule,this.lifts=n.lifts??(()=>null),this.seatRule=n.seatRule;let o=e.World.create(n.desc.world);if(!o.ok){this.status=He.MISMATCH;return}let i=o.world,a=n.staticWorld;if(!(a==null||a.boxes.length===0&&a.ramps.length===0)&&!i.addStaticWorld(a).ok){i.free(),this.status=He.MISMATCH;return}if(i.physicsHash()!==n.physicsHash){i.free(),this.status=He.MISMATCH;return}this.world=i}get predicting(){return this.status===He.ON||this.status===He.LOADING}get stopped(){return this.world===null}draws(e){return this.status===He.ON&&(this.drawn.has(e)||this.ruledElsewhere(e))}ruledElsewhere(e){return this.base!==null&&!this.drawn.has(e)&&this.ruled(e)}stateHash(){return this.world?.stateHash()??""}stop(e){this.status=e,this.world?.free(),this.world=null,this.drawn.clear()}adopt(e,n,r,s,o=()=>{}){let i={kind:"none",replayed:0,ms:0,pure:0,mismatched:0},a=this.world;if(a===null)return i;let c=this.status===He.CPU;if(c&&s-this.probedAt<EM||!c&&!this.predicting)return i;this.ownPose=r,this.ownVelocity=o;let u=this.choose(e),l=new Set(u.filter(b=>b.epoch!==void 0&&this.epochs.has(b.key)&&this.epochs.get(b.key)!==b.epoch).map(b=>b.key));for(let b of u)b.epoch!==void 0&&this.epochs.set(b.key,b.epoch);let d=c?{...i,kind:"replay"}:this.compare(e,u,l);if(this.world===null)return{...d,kind:"none"};if(d.kind==="match"){this.base={tick:e.tick,ack:e.ack};for(let b of this.seatsOf(e))this.seats.set(b.key,b);for(let b of u)this.kinematic.has(b.key)&&this.kinematic.set(b.key,Array.from(b.row));return this.prune(e.tick),this.status=He.ON,d}c&&this.drawn.clear();let f=this.snapshotDrawn(s),h=this.clock();if(!this.rebuild(a,e,u))return this.stop(He.MISMATCH),i;this.base={tick:e.tick,ack:e.ack},this.seq=e.ack,this.ring.clear(),this.readAll(a);let p=Math.min(n,e.ack+this.leadMax),g=0;for(let b=e.ack+1;b<=p&&(this.stepOnce(a),this.world!==null);b++,g++);let x=this.clock()-h;return this.world===null?{...d,kind:"replay",replayed:g,ms:x}:(this.steppedAt=s,this.ease(f,s,l),c?this.judgeProbe(x,s):(this.status=He.ON,this.judgeBudget(x)),{...d,kind:"replay",replayed:g,ms:x})}advance(e,n){let r=this.world;r===null||this.base===null||this.status!==He.ON||e!==this.seq+1||e-this.base.ack>this.leadMax||(this.stepOnce(r),this.steppedAt=n)}draw(e,n){if(this.status!==He.ON)return null;let r=this.drawn.get(e);if(r===void 0)return this.ruledElsewhere(e)?this.ruledDrawn(e,n):null;let s=r.sleep?0:Math.min(Math.max((n-this.steppedAt)/1e3,0),1/this.tickHz),o=this.lengthUnit,i=[r.p[0]+r.lv[0]*o*s,r.p[1]+r.lv[1]*o*s,r.p[2]+r.lv[2]*o*s],a=IM(r.q,r.av,s),c=Math.max(n-r.since,0),u=Gx(r,c);return{p:[i[0]+u[0][0],i[1]+u[1][0],i[2]+u[2][0]],q:zn(xi(r.dq,Math.exp(-c/r.tau)),a)}}choose(e){let n=Vx*this.lengthUnit,r=[],s=new Map;for(let p of e.bodies)s.set(p.key,p),r.push({key:p.key,x:p.row[0],y:p.row[1],z:p.row[2],radius:p.desc===null?0:_c(p.desc)});for(let p of e.outside)r.push(p);let o=[];for(let p of e.joints)typeof p.desc.a=="string"&&typeof p.desc.b=="string"&&o.push([p.desc.a,p.desc.b]);let i=Hx(r,o,n),a=new Map;for(let p of r){let g=i.get(p.key),x=a.get(g);x===void 0?a.set(g,[p.key]):x.push(p.key)}let c=e.seats.find(p=>p.own),u=p=>{let g=s.get(p);return c===void 0?0:Math.hypot(g.row[0]-c.x,g.row[1]-c.y,g.row[2]-c.z)},l=[...a.entries()].filter(([,p])=>p.every(g=>s.get(g)?.desc!=null)).map(([p,g])=>({island:p,keys:g,near:Math.min(...g.map(u))})).sort((p,g)=>p.near-g.near||vi(p.island,g.island)),d=Rh[this.setSize],f=[];this.pure.clear();let h=[...e.seats,...this.seats.values()];for(let{keys:p}of l){if(f.length+p.length>d)continue;for(let b of p)f.push(s.get(b));let g=h.some(b=>p.some(S=>OM(s.get(S),b,n,this.desc))),x=p.some(b=>s.get(b).desc?.type==="kinematic");if(!g&&!x)for(let b of p)this.pure.add(b)}return f.sort((p,g)=>vi(p.key,g.key)),this.chosenKeys=new Set(f.map(p=>p.key)),this.chosenCount=l.reduce((p,{keys:g})=>p+g.length,0),f}compare(e,n,r){let s={kind:"replay",replayed:0,ms:0,pure:0,mismatched:0},o=this.base,i=this.ring.get(e.tick);if(o===null||i===void 0)return s;let a=0,c=0,u=!0;for(let p of n){if(p.desc?.type==="kinematic")continue;let g=i.get(p.key),x=g!==void 0&&CM(g,p.row);this.pure.has(p.key)&&!r.has(p.key)&&g!==void 0&&(a++,x||c++),x||(u=!1)}this.noteCanary(a,c);let l=n.length===this.simulated.size&&n.every(p=>this.simulated.get(p.key)?.desc===Sh(p.desc)),d=e.ack===o.ack+(e.tick-o.tick)&&this.seq>=e.ack,f={...s,pure:a,mismatched:c};return u&&l&&d&&this.sameJoints(e)&&this.sameSeats(e,i)?{...f,kind:"match"}:f}sameJoints(e){let n=this.jointsOf(e);if(n.size!==this.joints.size)return!1;for(let[r,s]of n){let o=this.joints.get(r);if(o===void 0||o.desc!==s.desc||o.motor!==s.motor)return!1}return!0}sameSeats(e,n){let r=this.seatsOf(e);return r.length!==this.seats.size?!1:r.every(s=>{let o=n.get(`seat:${s.key}`);if(o===void 0||this.seats.get(s.key)?.epoch!==s.epoch)return!1;let i=this.presetPosition(s.x,s.y,s.z);return o[0]===i[0]&&o[1]===i[1]&&o[2]===i[2]})}noteCanary(e,n){for(let s=0;s<e;s++)this.canary.push(s<n);if(this.canary.length>qx&&this.canary.splice(0,this.canary.length-qx),this.canary.length<PM)return;this.canary.filter(Boolean).length/this.canary.length>kM&&this.stop(He.DIVERGED)}judgeBudget(e){if(this.costs.push(e),this.costs.length>xh&&this.costs.splice(0,this.costs.length-xh),this.costs.length<xM)return;let n=jx(this.costs,.5),r=jx(this.costs,.9);if(n>this.budgetMs||r>SM*this.budgetMs){this.costs=[];let i=RM(this.setSize,this.chosenCount);if(i!==null){this.setSize=i;return}this.fallBack();return}this.costs.length>=xh&&r<=$x*this.budgetMs&&this.setSize>0&&(this.setSize--,this.costs=[])}fallBack(){this.status=He.CPU,this.fallbacks++,this.drawn.clear(),this.probedAt=Number.NEGATIVE_INFINITY,this.calmProbes=0}judgeProbe(e,n){if(this.probedAt=n,this.calmProbes=e<=$x*this.budgetMs?this.calmProbes+1:0,this.calmProbes<_M){this.drawn.clear();return}this.status=He.ON,this.recoveries++,this.costs=[],this.calmProbes=0}jointsOf(e){let n=new Map;for(let r of e.joints){let s=r.desc.a,o=r.desc.b;!this.simulated.has(s)&&!this.chosenHas(s)||o!==null&&!this.simulated.has(o)&&!this.chosenHas(o)||n.set(r.key,{desc:JSON.stringify(r.desc),motor:r.motor===null?"":JSON.stringify(r.motor),parsed:r})}return n}chosenHas(e){return this.chosenKeys.has(e)}seatsOf(e){if(this.desc.presetBody===null)return[];let n=this.desc.world.limits.worldExtent;return e.seats.filter(r=>this.presetPosition(r.x,r.y,r.z).every(s=>Math.abs(s)<=n)).sort((r,s)=>vi(r.key,s.key))}presetPosition(e,n,r){let s=this.desc.presetBody?.half[2]??0;return[Math.fround(e),Math.fround(n),Math.fround(Math.fround(r)+s)]}rebuild(e,n,r){let s=this.jointsOf(n);for(let c of[...this.joints.keys()]){let u=s.get(c);u!==void 0&&u.desc===this.joints.get(c).desc||(e.removeJoint(c),this.joints.delete(c))}for(let[c,u]of[...this.simulated]){let l=r.find(d=>d.key===c);l!==void 0&&Sh(l.desc)===u.desc||(e.remove(c),this.simulated.delete(c),this.kinematic.delete(c),this.drawn.delete(c))}for(let c of r)if(!(this.simulated.has(c.key)||c.desc===null)){if(!e.spawn(c.desc).ok)return!1;this.kinds.set(c.key,c.desc.kind),this.simulated.set(c.key,{type:String(c.desc.type),desc:Sh(c.desc)})}this.kinematic.clear();for(let c of r)c.desc?.type==="kinematic"&&(this.kinematic.set(c.key,Array.from(c.row)),this.ruled(c.key)||this.drawn.delete(c.key));if(this.propStates=null,!this.rebuildSeats(e,n))return!1;let o=this.rebuildLifts(e,n.tick);if(o===null)return!1;for(let[c,u]of s){if(!this.joints.has(c)&&!e.addJoint(u.parsed.desc).ok)return!1;let l=this.joints.get(c);if(u.parsed.motor!==null&&l?.motor!==u.motor&&!e.setMotor(c,u.parsed.motor).ok)return!1;this.joints.set(c,{desc:u.desc,motor:u.motor})}let i=[],a=[];for(let c of r){i.push(c.key);for(let u=0;u<co;u++)a.push(c.row[u])}for(let c of this.seats.values())i.push(c.key),a.push(...this.presetPosition(c.x,c.y,c.z),...vM);for(let[c,u]of o)i.push(c),a.push(...u);return i.length>0&&!e.importWire(i,a).ok?!1:e.canonicalize({quantize:!0}).ok}rebuildLifts(e,n){let r=this.lifts(),s=this.liftBodies;if(s!==null&&s.policy!==r?.policy){for(let o of s.keys)e.remove(o);this.liftBodies=null}if(r===null||r.policy.platforms.length===0)return[];if(this.liftBodies===null){for(let o of r.policy.platforms)if(!e.spawn(Cx(o,n+1,r.starts)).ok)return null;this.liftBodies={policy:r.policy,keys:r.policy.platforms.map(o=>xc(o.id))}}return r.policy.platforms.map(o=>{let{p:i,q:a}=nd(o,n+1,r.starts);return[xc(o.id),[...i,...a.map(MM),...TM]]})}rebuildSeats(e,n){let r=new Map(this.seatsOf(n).map(o=>[o.key,o]));for(let[o,i]of[...this.seats])r.get(o)?.epoch!==i.epoch&&(e.remove(o),this.seats.delete(o));let s=this.desc.presetBody;for(let[o,i]of r){if(!this.seats.has(o)&&s!==null){let a={key:"hull",shape:{kind:"box",half:[...s.half]},events:s.events,...this.headSlide()===null?{}:{friction:0}};if(!e.spawn({key:o,type:"kinematic",pose:{p:this.presetPosition(i.x,i.y,i.z),q:[...Rc]},colliders:[a]}).ok)return!1}this.seats.set(o,i)}return!0}stepOnce(e){let n=this.base,r=this.seq+1,s=n.tick+(r-n.ack),o=[],i=!1;for(let l of this.seats.values())o.push(this.seatAt(l,r,s-n.tick)),i||(i=this.posedBySeats);i||this.passSeats(o);for(let l of o)e.setNextKinematicPose(l.key,{p:this.presetPosition(l.x,l.y,l.z),q:[...Rc]});for(let[l,d]of this.kinematic){let f=this.kinematicRule?.(l,s+1)??null;e.setNextKinematicPose(l,f===null?DM(d):{p:[...f.p],q:[...f.q]})}let a=this.liftBodies===null?null:this.lifts();for(let l of a?.policy.platforms??[])e.setNextKinematicPose(xc(l.id),nd(l,s+1,a?.starts));this.applyBodyRule(e,s,o);let c=e.tick,u=e.step();if(!u.ok){this.stop(He.DIVERGED);return}for(let l of u.escaped)e.remove(l),this.simulated.delete(l),this.drawn.delete(l);this.clamp(e,c),s%this.desc.keyframeTicks===0&&(e.canonicalize({quantize:!0}),this.propStale=!0,this.ring.set(s,this.rowsNow(e))),this.seq=r,this.readDrawn(e,c),this.hashes.push({tick:s,hash:e.stateHash()}),this.hashes.length>this.hashesKept&&this.hashes.splice(0,this.hashes.length-this.hashesKept)}seatAt(e,n,r){this.posedBySeats=!1;let s=e.own?this.ownPose(n):void 0;if(s!==void 0){let f=this.ownVelocity(n)??[e.vx,e.vy,e.vz];return{key:e.key,x:s[0],y:s[1],z:s[2],vx:f[0],vy:f[1],vz:f[2]}}let o=e.own?void 0:this.seatPose?.(e.key,n);if(o!==void 0)return this.posedBySeats=!0,{...o,key:e.key};let i=this.remoteStep;if(e.own||i===void 0||e.input===void 0){let f=r/this.tickHz;return{key:e.key,x:e.x+e.vx*f,y:e.y+e.vy*f,z:e.z+e.vz*f,vx:e.vx,vy:e.vy,vz:e.vz}}let a=this.remoteBodies.get(e.key),c=a!==void 0&&a.from===e&&a.j<=r,u=c?a.body:{...e.body??{},x:e.x,y:e.y,z:e.z},l=1/this.tickHz,d=this.base?.tick??0;for(let f=(c?a.j:0)+1;f<=r;f++){this.seatRule?.(u,d+f);let h=this.desc.remotePredict===jt.HOLD;i(u,h?e.input:od(e.input,f,this.tickHz,this.desc.remoteDecayMs),l,d+f)}return this.remoteBodies.set(e.key,{from:e,j:r,body:u}),{key:e.key,x:u.x,y:u.y,z:u.z,vx:u.vx??e.vx,vy:u.vy??e.vy,vz:u.vz??e.vz,...u.yaw===void 0?{}:{yaw:u.yaw}}}passSeats(e){let n=this.contactPass;if(n===void 0||e.length<2)return;let r=e.map(o=>({id:o.key,x:o.x,y:o.y,z:o.z,vx:o.vx,vy:o.vy,vz:o.vz,yaw:o.yaw??0}));r.sort((o,i)=>vi(o.id,i.id)),n(r);let s=new Map(r.map(o=>[o.id,o]));for(let o of e){let i=s.get(o.key);o.x=i.x,o.y=i.y,o.z=i.z,o.vx=i.vx,o.vy=i.vy,o.vz=i.vz}}applyBodyRule(e,n,r){let s=this.bodyRule,o=this.headSlide(),i=this.liftBodies===null?null:this.lifts(),a=i!==null&&i.policy.platforms.some(d=>d.surface!==null)?i:null;if(s===void 0&&o===null&&a===null)return;r.sort((d,f)=>vi(d.key,f.key));let c=d=>{if(this.simulated.get(d)?.type!=="dynamic")return null;let f=e.exportBodyState(d);return f===null?null:{p:[f.p[0],f.p[1],f.p[2]],v:[f.v[0],f.v[1],f.v[2]]}};for(let d of s?.({tick:n,seats:r,body:c})??[])this.simulated.get(d.key)?.type==="dynamic"&&e.setVelocity(d.key,[d.v[0],d.v[1],d.v[2]]);let u=this.desc.presetBody?.half;if(o===null&&a===null||u===void 0)return;if(this.propStates===null){this.propStates=new Map;for(let d of this.simulated.keys()){let f=c(d);f!==null&&this.propStates.set(d,{key:d,p:f.p,v:f.v})}this.propStale=!1}this.propStale&&this.freshenPicked(r,u,a===null?null:gh(a.policy,n,a.starts,2*u[2]),o!==null,c);let l=[...this.propStates.values()].filter(d=>this.simulated.get(d.key)?.type==="dynamic").sort((d,f)=>vi(d.key,f.key));if(a!==null)for(let d of Ox(a.policy,n,a.starts,this.tickHz,l,2*u[2]))e.setVelocity(d.key,d.v);if(o!==null)for(let d of cx(r,u,l,o))e.setVelocity(d.key,d.v)}freshenPicked(e,n,r,s,o){let i=this.propStates;if(this.propStale=!1,i!==null)for(let[a,c]of i){if(!(s&&ph(e,n,c.p)!==void 0||r!==null&&r(c.p)!==void 0))continue;let l=o(a);l!==null&&i.set(a,{key:a,p:l.p,v:l.v})}}clamp(e,n){let{keys:r,data:s}=e.exportChanged(n,{rest:!0});for(let o=0;o<r.length;o++){let i=r[o];if(this.simulated.get(i)?.type!=="dynamic")continue;let a=o*co,c=[s[a+7],s[a+8],s[a+9]],u=[s[a+10],s[a+11],s[a+12]],l=zx(c,u,this.lengthUnit,this.desc.maxLinear,this.desc.maxAngular);l!==null&&e.setVelocity(i,l.linvel,l.angvel),this.propStates?.set(i,{key:i,p:[s[a],s[a+1],s[a+2]],v:l===null?c:[l.linvel[0],l.linvel[1],l.linvel[2]]})}}rowsNow(e){let n=new Map,r=(s,o)=>{let i=e.exportBodyState(s,{rest:!0});i!==null&&n.set(o,Fx(i,this.lengthUnit,this.innerDt))};for(let s of this.simulated.keys())r(s,s);for(let s of this.seats.keys())r(s,`seat:${s}`);return n}ruledDrawn(e,n){let r=this.kinematicRule,s=this.ruledTick(n);if(r===void 0||s===null)return null;let o=Math.floor(s),i=r(e,o),a=r(e,o+1);if(i===null||a===null)return null;let c=s-o;return{p:[i.p[0]+(a.p[0]-i.p[0])*c,i.p[1]+(a.p[1]-i.p[1])*c,i.p[2]+(a.p[2]-i.p[2])*c],q:Mr([...i.q])}}ruledTick(e){let n=this.base;if(n===null)return null;let r=Math.min(Math.max((e-this.steppedAt)/1e3*this.tickHz,0),1),s=n.tick+(this.seq-n.ack)+1+r,o=this.ruledClock;if(o===null||e<o.at||Math.abs(s-o.tick)>wM)return this.ruledClock={at:e,tick:s},s;let i=(e-o.at)/1e3*this.tickHz,a=o.tick+i,c=bM*i,u=a+Math.min(Math.max(s-a,-c),c);return this.ruledClock={at:e,tick:u},u}ruled(e){if(this.kinematicRule===void 0)return!1;let n=this.base,r=n===null?0:n.tick+(this.seq-n.ack);return this.kinematicRule(e,r)!==null}prune(e){for(let n of this.ring.keys())n<=e&&this.ring.delete(n)}readDrawn(e,n){let{keys:r,data:s}=e.exportChanged(n,{rest:!0});for(let o=0;o<r.length;o++){let i=r[o];if(!this.simulated.has(i)||this.kinematic.has(i)&&!this.ruled(i))continue;let a=o*co,c=this.drawn.get(i);this.drawn.set(i,{p:[s[a],s[a+1],s[a+2]],q:Mr([s[a+3],s[a+4],s[a+5],s[a+6]]),lv:[s[a+7]/this.lengthUnit,s[a+8]/this.lengthUnit,s[a+9]/this.lengthUnit],av:[s[a+10],s[a+11],s[a+12]],sleep:s[a+13]===1,dp:c?.dp??Ai,dv:c?.dv??Ai,dq:c?.dq??Rc,since:c?.since??0,tau:c?.tau??Pi(0),snap:c?.snap??this.snapOf(i)})}}builtInRules(){if(!this.desc.presetBody)return!1;if(this.headSlide()!==null)return!0;let e=this.liftBodies===null?null:this.lifts();return e!==null&&e.policy.platforms.some(n=>n.surface!==null)}readAll(e){let n=this.builtInRules()?new Map:null;for(let r of this.simulated.keys()){let s=this.kinematic.has(r)&&!this.ruled(r)?null:e.exportBodyState(r,{rest:!0});if(s===null)continue;n!==null&&this.simulated.get(r)?.type==="dynamic"&&n.set(r,{key:r,p:[s.p[0],s.p[1],s.p[2]],v:[s.v[0],s.v[1],s.v[2]]});let o=this.drawn.get(r),i=this.lengthUnit;this.drawn.set(r,{p:[s.p[0],s.p[1],s.p[2]],q:Mr([s.q[0],s.q[1],s.q[2],s.q[3]]),lv:[s.v[0]/i,s.v[1]/i,s.v[2]/i],av:[s.w[0],s.w[1],s.w[2]],sleep:s.sleeping,dp:o?.dp??Ai,dv:o?.dv??Ai,dq:o?.dq??Rc,since:o?.since??0,tau:o?.tau??Pi(0),snap:o?.snap??this.snapOf(r)})}n!==null&&(this.propStates=n,this.propStale=!1)}snapshotDrawn(e){let n=new Map;for(let[r,s]of this.drawn){let o=Math.max(e-s.since,0),i=Gx(s,o);n.set(r,{p:[s.p[0]+i[0][0],s.p[1]+i[1][0],s.p[2]+i[2][0]],q:zn(xi(s.dq,Math.exp(-o/s.tau)),s.q),rate:[i[0][1],i[1][1],i[2][1]]})}return n}snapOf(e){return ad(this.kinds.get(e))*this.lengthUnit}ease(e,n,r){for(let[s,o]of this.drawn){let i=e.get(s),a={...o,dp:Ai,dv:Ai,dq:Rc,since:n,tau:Pi(0)};if(i===void 0||r.has(s)){this.drawn.set(s,a);continue}let c=[i.p[0]-o.p[0],i.p[1]-o.p[1],i.p[2]-o.p[2]],u=Math.hypot(c[0],c[1],c[2]);if(u>o.snap){this.drawn.set(s,a);continue}let l=zn(i.q,[-o.q[0],-o.q[1],-o.q[2],o.q[3]]),d=l[3]<0?[-l[0],-l[1],-l[2],-l[3]]:l;this.drawn.set(s,{...o,dp:c,dv:i.rate,dq:d,since:n,tau:Pi(u/this.lengthUnit)})}}},Sh=t=>t===null?"":JSON.stringify(t);function OM(t,e,n,r){let s=r.presetBody?.half??[0,0,0],o=Math.hypot(s[0],s[1],s[2])+(t.desc===null?0:_c(t.desc))+n;return Math.hypot(t.row[0]-e.x,t.row[1]-e.y,t.row[2]-(e.z+s[2]))<=o}function IM(t,e,n){let r=Math.hypot(e[0],e[1],e[2]);if(r===0||n===0)return t;let s=r*n/2,o=Math.sin(s)/r;return Mr(zn([e[0]*o,e[1]*o,e[2]*o,Math.cos(s)],t))}function DM(t){let e=r=>-1+r/65534*2,n=Mr([e(t[3]),e(t[4]),e(t[5]),e(t[6])]);return{p:[t[0],t[1],t[2]],q:[n[0],n[1],n[2],n[3]]}}var Eh={contract:"1.0",dt:1/60,substeps:1,gravity:[0,0,-9.81],upAxis:"z",lengthUnit:1},_h=12;function BM(){let t=(e,n,r)=>({key:e,type:"dynamic",pose:{p:n,q:[0,0,0,1]},linvel:[1,0,0],colliders:[{key:"c",shape:{kind:"box",half:[r,r,r]}}]});return[t("a",[0,0,.5],.5),t("b",[0,0,1.6],.5),{key:"c",type:"dynamic",pose:{p:[2,0,1],q:[0,0,0,1]},angvel:[0,3,0],colliders:[{key:"c",shape:{kind:"sphere",radius:.4}}]}]}function Kx(t){let n=[t.World.create(Eh),t.World.create(Eh)].flatMap(r=>r.ok?[r.world]:[]);try{if(n.length!==2)return!1;let[r,s]=n,o={boxes:[[-20,-20,-1,20,20,0]],ramps:[]};if(!r.addStaticWorld(o).ok||!s.addStaticWorld(o).ok)return!1;for(let l of BM())if(!r.spawn(l).ok||!s.spawn(l).ok)return!1;for(let l=0;l<_h;l++)r.step();s.canonicalize({});for(let l=0;l<_h;l++)s.step();if(!r.canonicalize({quantize:!0}).ok)return!1;let{keys:i,data:a}=r.exportChanged(r.tick,{rest:!0}),c=[],u=bh(Eh);for(let l=0;l<i.length;l++)wh(a,l*co,1,u,c,l*co);if(i.length!==3||!s.importWire(i,c).ok||!s.canonicalize({quantize:!0}).ok)return!1;for(let l=0;l<_h;l++)if(r.step(),s.step(),r.stateHash()!==s.stateHash())return!1;return!0}finally{for(let r of n)r.free()}}var K2=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]);var uo=["x","y","z","vx","vy","vz","yaw","spin"],NM=(t,e)=>t.body.id<e.body.id?-1:t.body.id>e.body.id?1:0,ld=class{constructor(e,n){m(this,"pass",null);m(this,"rule");m(this,"others");this.rule=e,this.others=n}apply(e,n,r,s){(this.pass===null||this.pass.ack!==n||e<=this.pass.last)&&(this.pass={ack:n,last:n,others:this.others().map(u=>({body:{...u},from:0})).sort(NM)});let i=this.pass,a=e-n,c={...r};i.others=i.others.map(u=>{let l=(a-u.from)/s,d=u.body,f={...d,x:d.x+d.vx*l,y:d.y+d.vy*l,z:d.z+d.vz*l},h=JSON.stringify(f);return c.id<f.id?this.rule(c,f):this.rule(f,c),JSON.stringify(f)===h?u:{body:f,from:a}});for(let u of uo){let l=c[u];typeof l=="number"&&l!==r[u]&&(r[u]=Math.fround(l))}i.last=e}seatAt(e,n,r,s){let o=this.pass!==null&&this.pass.ack===n?this.pass.others.find(l=>l.body.id===e):void 0,i=o===void 0?this.others().find(l=>l.id===e):void 0,a=o?.from??0,c=o?.body??i;if(c===void 0)return;let u=(r-a)/s;return{...c,x:c.x+c.vx*u,y:c.y+c.vy*u,z:c.z+c.vz*u}}};function lo(t,e,n){let r={x:n.x,y:n.y,z:n.z};for(let s=0;s<LM;s++){let o={...e,vx:0,vy:0,vz:0},i={...n,...r,vx:0,vy:0,vz:0};o.id<i.id?t(o,i):t(i,o);let a={x:r.x+(i.x-r.x)-(o.x-e.x),y:r.y+(i.y-r.y)-(o.y-e.y),z:r.z+(i.z-r.z)-(o.z-e.z)};if(s>0&&a.x===r.x&&a.y===r.y&&a.z===r.z||(r=a,s===0&&dd(t,e,n,r)<=FM))break}return dd(t,e,n,r)>eS?HM(t,e,n,r):r}var LM=8,FM=.01,eS=.001,zM=30,UM=8,VM=1;function HM(t,e,n,r){let s={x:n.x,y:n.y,z:n.z},o={x:r.x-s.x,y:r.y-s.y,z:r.z-s.z},i=Math.hypot(o.x,o.y,o.z)>0?o:tS(t,e,n,s),a=Math.hypot(i.x,i.y,i.z);if(a===0)return r;let c={x:i.x/a,y:i.y/a,z:i.z/a},u=h=>({x:s.x+c.x*h,y:s.y+c.y*h,z:s.z+c.z*h}),l=h=>dd(t,e,n,u(h))>0,d=a,f=a+Math.max(VM,a);for(let h=0;h<UM&&l(f);h++)d=f,f=a+(f-a)*2;if(l(f))return r;for(let h=0;h<zM;h++){let p=(d+f)/2;l(p)?d=p:f=p}return u(f)}function tS(t,e,n,r){let s={...e,vx:0,vy:0,vz:0},o={...n,...r,vx:0,vy:0,vz:0};return s.id<o.id?t(s,o):t(o,s),{x:o.x-r.x-(s.x-e.x),y:o.y-r.y-(s.y-e.y),z:o.z-r.z-(s.z-e.z)}}function dd(t,e,n,r){let s=tS(t,e,n,r);return Math.hypot(s.x,s.y,s.z)}var $M=3*Math.PI,jM=Math.PI/2,qM=.05,GM=8,Xx=16,WM=30,YM=8,nS=(t,e,n)=>({...e,x:t.x+n.dx,y:t.y+n.dy,z:t.z+n.dz,vx:0,vy:0,vz:0});function Ah(t,e,n,r){let s=nS(e,n,r),o=lo(t,e,s);return Math.hypot(o.x-s.x,o.y-s.y,o.z-s.z)}function fd(t,e,n,r,s){let o=Math.hypot(s.dx-r.dx,s.dy-r.dy,s.dz-r.dz),i=Math.min(o,Math.hypot(r.dx,r.dy,r.dz));if(i===0)return!1;for(let a=1;a<Xx;a++){let c=a/Xx,u={dx:r.dx+(s.dx-r.dx)*c,dy:r.dy+(s.dy-r.dy)*c,dz:r.dz+(s.dz-r.dz)*c};if(Ah(t,e,n,u)>Math.min(qM*i,GM))return!0}return!1}function Ph(t,e,n,r,s,o){let i=Math.cos(r),a=Math.sin(r),c=d=>Ah(t,e,n,{dx:d*i,dy:d*a,dz:s})>0;if(!c(0)||o<=0)return 0;let u=0,l=o;for(let d=0;d<YM&&c(l);d++)u=l,l*=2;for(let d=0;d<WM;d++){let f=(u+l)/2;c(f)?u=f:l=f}return l}var Jx=4,KM=20;function XM(t,e,n){let r=n.z>=e.z?1:-1,s=a=>Ah(t,e,n,{dx:n.x-e.x,dy:n.y-e.y,dz:n.z-e.z+r*a})>0;if(!s(0)||s(Jx))return n;let o=0,i=Jx;for(let a=0;a<KM;a++){let c=(o+i)/2;s(c)?o=c:i=c}return{...n,z:n.z+r*i}}var Zx=2*Math.PI,JM=t=>t-Zx*Math.floor((t+Math.PI)/Zx);function Qx(t,e,n,r,s,o=!1){let i=XM(t,e,n),a=lo(t,e,i),c={dx:a.x-e.x,dy:a.y-e.y,dz:a.z-e.z},u=a.x!==i.x||a.y!==i.y||a.z!==i.z,l=i.x-e.x,d=i.y-e.y,f=(N,Y)=>({x:e.x+N.dx,y:e.y+N.dy,z:e.z+N.dz,side:{...N,held:Y,bx:l,by:d,at:s}}),h=N=>f(ZM(t,e,i,N),!0);if(r===void 0||!(o||fd(t,e,i,r,c)))return f(c,u);let p=Math.hypot(r.dx,r.dy),g=Math.hypot(c.dx,c.dy),x=Math.atan2(r.dy,r.dx);if(!r.held){if(r.dx*c.dx+r.dy*c.dy>=0)return f(c,u);let N=Ph(t,e,i,x,c.dz,Math.max(p,g));return h({dx:N*Math.cos(x),dy:N*Math.sin(x),dz:c.dz})}let b=JM(Math.atan2(c.dy,c.dx)-x),S=p>0?jM*Math.hypot(l-r.bx,d-r.by)/p:0,_=Math.max(S,$M*Math.max(0,s-r.at)/1e3),P=Math.min(Math.abs(b),_),R=b===0?1:P/Math.abs(b),v=x+Math.sign(b)*P,M=c.dz-r.dz,O=_*Math.max(p,g),z=Math.abs(M*R)>O?r.dz+Math.sign(M)*O:r.dz+M*R,X=Math.max(p+(g-p)*R,Ph(t,e,i,v,z,Math.max(p,g)));return h({dx:X*Math.cos(v),dy:X*Math.sin(v),dz:z})}function ZM(t,e,n,r){let s=nS(e,n,r);return dd(t,e,s,s)>eS?Ti(e,lo(t,e,s)):r}function QM(t,e,n,r,s,o,i){let a={dx:i.x-e.x,dy:i.y-e.y,dz:i.z-e.z};for(let c of r){let u=c===n?void 0:s.get(c.id);if(u===void 0)continue;let l={...c,x:e.x+u.dx,y:e.y+u.dy,z:e.z+u.dz,vx:0,vy:0,vz:0},d=f=>({dx:f.dx-u.dx,dy:f.dy-u.dy,dz:f.dz-u.dz});if(fd(t,l,n,d(o),d(a)))return!0}return!1}var kc=(t,e)=>t<e?`${t}\0${e}`:`${e}\0${t}`,eC=12,Br=(t,e)=>({...t,x:e.x,y:e.y,z:e.z,vx:0,vy:0,vz:0}),Ti=(t,e)=>({dx:e.x-t.x,dy:e.y-t.y,dz:e.z-t.z}),pd=(t,e)=>t.x===e.x&&t.y===e.y&&t.z===e.z,tC=720,nC=.1,rC=24,sC=8,oC=64;function vh(t,e,n,r,s){return!pd(lo(t,Br(e,r),Br(n,s)),s)}var rS=(t,e,n,r)=>[{x:t.x-n.nx*r/2,y:t.y-n.ny*r/2,z:t.z},{x:e.x+n.nx*r/2,y:e.y+n.ny*r/2,z:e.z}];function iC(t,e,n,r,s,o,i){let a=l=>vh(t,e,n,...rS(r,s,o,l));if(!a(i))return i;let c=i,u=i+oC;for(let l=0;l<sC&&a(u);l++)c=u,u=i+(u-i)*2;for(let l=0;l<rC;l++){let d=(c+u)/2;a(d)?c=d:u=d}return u}function kh(t,e){let n=Math.hypot(t,e);return n>0?{nx:t/n,ny:e/n}:null}function aC(t,e,n,r,s,o){let i=lo(t,Br(e,r),Br(n,s)),a=(o===void 0?null:kh(o.dx,o.dy))??kh(s.x-r.x,s.y-r.y),c=kh(i.x-s.x,i.y-s.y),u=c!==null&&a!==null&&c.nx*a.nx+c.ny*a.ny<0?-1:1;return{...c===null?a??{nx:1,ny:0}:{nx:u*c.nx,ny:u*c.ny},push:0}}function cC(t,e,n,r){let s=r.get(e.id),o=r.get(n.id),i=lo(t,Br(e,s),Br(n,o));if(pd(i,o))return!1;let a={x:(i.x-o.x)/2,y:(i.y-o.y)/2,z:(i.z-o.z)/2};return r.set(e.id,{x:s.x-a.x,y:s.y-a.y,z:s.z-a.z}),r.set(n.id,{x:o.x+a.x,y:o.y+a.y,z:o.z+a.z}),!0}function sS(t,e,n,r){return r.nx*(n.x-e.x)+r.ny*(n.y-e.y)<0&&!vh(t,e,n,e,n)}var oS=(t,e,n,r,s)=>s.nx*(r.x-n.x-(e.x-t.x))+s.ny*(r.y-n.y-(e.y-t.y));function uC(t,e,n,r,s,o,i){let a=kc(e.id,n.id),c=r.get(e.id),u=r.get(n.id),l=s.get(a),d=0;if(l===void 0){let g=o?.pair;if(g===void 0?!vh(t,e,n,e,n):sS(t,e,n,g))return cC(t,e,n,r);l=g??aC(t,e,n,c,u,o),s.set(a,l);let x=g===void 0?0:g.push-tC*Math.min(i,nC);d=Math.max(0,x-oS(e,n,c,u,l))}let f=iC(t,e,n,c,u,l,d);if(f<=0)return!1;let[h,p]=rS(c,u,l,f);return r.set(e.id,h),r.set(n.id,p),!0}function lC(t,e,n,r,s,o){if(s===void 0)return;let i=r.get(e.id),a=r.get(n.id),c=Ti(i,a);if(s.dx*c.dx+s.dy*c.dy>=0)return;let u=Br(e,i),l=Br(n,a);if(!fd(t,u,l,s,c))return;let d=Math.atan2(s.dy,s.dx),f=Ph(t,u,l,d,s.dz,Math.hypot(s.dx,s.dy)),h={dx:f*Math.cos(d),dy:f*Math.sin(d),dz:s.dz};return o(n.id)>=o(e.id)?(r.set(n.id,{x:i.x+h.dx,y:i.y+h.dy,z:i.z+h.dz}),n.id):(r.set(e.id,{x:a.x-h.dx,y:a.y-h.dy,z:a.z-h.dz}),e.id)}function dC(t,e,n,r,s){let o=Br(n,r),i=lo(t,e,o);return pd(i,r)?r:fd(t,e,o,Ti(e,s),Ti(e,i))?s:i}function fC(t){return t.flatMap((e,n)=>t.slice(n+1).map(r=>[e,r]))}function iS(t,e,n,r,s){let o=[...n].sort((h,p)=>h.id<p.id?-1:h.id>p.id?1:0),i=new Map;for(let h of o){let p=r.get(h.id),g=Qx(t,e,h,p,s),b=p?.held===!0&&!g.side.held&&QM(t,e,h,o,r,p,g)?Qx(t,e,h,p,s,!0):g;i.set(h.id,{x:b.x,y:b.y,z:b.z})}let a=new Map(i),c=h=>{let p=r.get(h),g=a.get(h);return p===void 0?Number.POSITIVE_INFINITY:Math.hypot(g.x-e.x-p.dx,g.y-e.y-p.dy,g.z-e.z-p.dz)},u=fC(o),l=(h,p)=>r.get(kc(h.id,p.id));for(let[h,p]of u){let g=l(h,p);(g?.pair===void 0||sS(t,h,p,g.pair))&&lC(t,h,p,i,g,c)}let d=new Map;for(let h=0;;h++){for(let g of o)i.set(g.id,dC(t,e,g,i.get(g.id),a.get(g.id)));if(h===eC)break;let p=!1;for(let[g,x]of u){let b=l(g,x);p=uC(t,g,x,i,d,b,b===void 0?0:Math.max(0,s-b.at)/1e3)||p}if(!p)break}let f=new Map;for(let h of o){let p=i.get(h.id);f.set(h.id,{...Ti(e,p),held:!pd(p,h),bx:h.x-e.x,by:h.y-e.y,at:s})}for(let[h,p]of u){let g=i.get(h.id),x=kc(h.id,p.id),b=d.get(x),S=b===void 0?0:oS(h,p,g,i.get(p.id),b),_=b!==void 0&&S>0?{pair:{nx:b.nx,ny:b.ny,push:S}}:{};f.set(x,{...Ti(g,i.get(p.id)),held:!1,bx:p.x-h.x,by:p.y-h.y,at:s,..._})}return{drawn:i,sides:f}}var Mi=(t,e,n)=>t+(n-e);var Ci=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function pC(t){if(!Ci(t)||typeof t.preset!="string"||!Object.hasOwn(Nw,t.preset))return!1;let e=t.shape,n=t.hull;return!Ci(e)||e.kind!==Vn.Box&&e.kind!==Vn.Hull||!Ci(n)?!1:Ci(t.top)&&Ci(t.offWall)&&Array.isArray(t.pairs)&&typeof t.passes=="number"}function aS(t,e){if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}let r=Ci(n)?n.contacts:void 0;if(!pC(r))return null;let s={world:Uw(e,r.hull.radius,r.hull.height,r.hull.skin)},o=new Map,i=a=>{let c=o.get(a);if(c!==void 0)return c;let u=fh(r,{...s,fixed:a});return o.set(a,u),u};return{policy:r,rule:fh(r,s),pass:sx(r,s),env:s,drawRule:i}}function cS(t){return Number.isSafeInteger(t)?(t%65536+65536)%65536:0}var mS=500;function hC(t,e,n,r){let s=t.poses.get(n)?.get(e);if(s===void 0)return;let o=t.poses.get(n-1)?.get(e),i=t.poses.get(n-2)?.get(e);if(o===void 0){let h=r/t.tickHz;return{...s,x:s.x+s.vx*h,y:s.y+s.vy*h,z:s.z+s.vz*h}}let a=Math.floor(r),c=h=>h*(h+1)/2,u=(h,p,g)=>{let x=h+p*a+g*c(a),b=h+p*(a+1)+g*c(a+1);return x+(b-x)*(r-a)},l=(h,p,g)=>g===void 0?0:h-2*p+g,d=ds(s.yaw-o.yaw),f=i===void 0?0:d-ds(o.yaw-i.yaw);return{...s,x:u(s.x,s.x-o.x,l(s.x,o.x,i?.x)),y:u(s.y,s.y-o.y,l(s.y,o.y,i?.y)),z:u(s.z,s.z-o.z,l(s.z,o.z,i?.z)),yaw:ds(u(s.yaw,d,f))}}function mC(t,e){let n=t.ack+t.ticks,r=Math.min(Math.max(e,t.ack+1),n),s=Math.floor(r),o=t.own.get(s);if(o===void 0)return;let i=t.own.get(s+1),a=r-s;return i===void 0||a===0?o:{...o,x:o.x+(i.x-o.x)*a,y:o.y+(i.y-o.y)*a,z:o.z+(i.z-o.z)*a,yaw:o.yaw+ds(i.yaw-o.yaw)*a}}var uS=8,yC=3,Th=.5,Mh=(t,e)=>t.id<e.id?-1:t.id>e.id?1:0,Ee=(t,e=0)=>typeof t=="number"&&Number.isFinite(t)?t:e,lS=2*Math.PI,ds=t=>t-lS*Math.floor((t+Math.PI)/lS),dS=t=>({x:Ee(t.x),y:Ee(t.y),z:Ee(t.z),yaw:Ee(t.yaw),vx:Ee(t.vx),vy:Ee(t.vy),vz:Ee(t.vz)}),fS=(t,e)=>({id:t,x:Ee(e.x),y:Ee(e.y),z:Ee(e.z),vx:Ee(e.vx),vy:Ee(e.vy),vz:Ee(e.vz),yaw:Ee(e.yaw),spin:Ee(e.spin),...typeof e.flags=="number"?{flags:e.flags}:{}}),pS=(t,e)=>({id:t,x:Ee(e.x),y:Ee(e.y),z:Ee(e.z),vx:Ee(e.vx),vy:Ee(e.vy),vz:Ee(e.vz),yaw:Ee(e.yaw),duck:Ee(e.duck),flags:Ee(e.flags)}),hS=(t,e)=>uo.every(n=>t[n]===e[n]),md=class{constructor(e){m(this,"options");m(this,"serial",0);m(this,"current",null);m(this,"recent",[]);m(this,"applied",new Map);m(this,"missed",new Set);this.options=e}apply(e,n,r,s,o,i=null){let a=this.current,c=a===null||a.ack!==n||a.stateTick!==r||e<=a.last,u=a,l=c?this.start(n,r,o):a,d=e-n;for(let p=l.ticks+1;p<d;p++)this.tick(l,p,u?.ownIn.get(n+p),!1,u?.ownOn.get(n+p)??null),this.noteMissed(l,n+p);let f=d>l.ticks,h=f?this.tick(l,d,s,!0,i):null;f&&this.applied.set(e,l.touching.get(e)??new Set),l.last=e;for(let p of this.recent)this.extend(p,l,e);return h}takeMissed(){let e=[...this.missed].sort();return this.missed.clear(),e}noteMissed(e,n){let r=this.applied.get(n),s=e.touching.get(n);if(!(r===void 0||s===void 0))for(let o of s)r.has(o)||this.missed.add(o)}extend(e,n,r){let s=r-e.ack;for(let o=e.ticks+1;o<=s;o++)this.tick(e,o,n.ownIn.get(e.ack+o),!1,n.ownOn.get(e.ack+o)??null);e.last=Math.max(e.last,r)}poseAt(e,n,r=this.current){if(r===null)return;let s=Math.max(n,r.ack),o=r.ack+r.ticks,i=Math.min(Math.floor(s),o),a=r.poses.get(i)?.get(e);if(a===void 0)return;let c=i<o?r.poses.get(i+1)?.get(e):void 0,u=s-i;if(c===void 0){if(r===this.current){let l=Math.min(u,1)/r.tickHz;return{...a,x:a.x+a.vx*l,y:a.y+a.vy*l,z:a.z+a.vz*l}}return hC(r,e,i,u)??a}return{x:a.x+(c.x-a.x)*u,y:a.y+(c.y-a.y)*u,z:a.z+(c.z-a.z)*u,yaw:a.yaw+ds(c.yaw-a.yaw)*u,vx:a.vx+(c.vx-a.vx)*u,vy:a.vy+(c.vy-a.vy)*u,vz:a.vz+(c.vz-a.vz)*u}}motionAt(e,n,r=this.current){let s=this.poseAt(e,n,r),o=this.poseAt(e,n-Th,r),i=this.poseAt(e,n+Th,r);if(s===void 0||o===void 0||i===void 0||r===null)return;let a=r.tickHz/1e3/(2*Th);return{pose:s,rate:{vx:(i.x-o.x)*a,vy:(i.y-o.y)*a,vz:(i.z-o.z)*a,vyaw:ds(i.yaw-o.yaw)*a}}}changeAt(e,n,r){if(this.current===null||this.current===r)return;let s=Math.min(n,r.ack+r.ticks),o=this.motionAt(e,s,r),i=this.motionAt(e,s);return o===void 0||i===void 0?void 0:{before:o,after:i}}touchAheadMs(e,n){let r=this.current;if(r===null)return;let s=Math.floor(Math.max(n,r.ack));if(r.touching.get(s)?.has(e)===!0||r.touching.get(s+1)?.has(e)===!0)return 0;let o=r.seats.find(l=>l.id===e),i=this.poseAt(e,n,r),a=mC(r,n);if(o===void 0||i===void 0||a===void 0)return;let c={...fS(e,o.body),x:i.x,y:i.y,z:i.z,yaw:i.yaw,vx:i.vx,vy:i.vy,vz:i.vz},u={x:(i.vx-a.vx)/1e3,y:(i.vy-a.vy)/1e3,z:(i.vz-a.vz)/1e3};for(let l=0;l<=uS;l++){let d=l/uS*mt.SEAT_CLOCK_TAU_MS;if(this.touches(a,{...c,x:c.x+u.x*d,y:c.y+u.y*d,z:c.z+u.z*d}))return d}}touchingAt(e,n){let r=this.current;return r===null?!1:r.touching.get(Math.round(Math.max(n,r.ack)))?.has(e)===!0}stateRate(e){let n=this.current,r=n?.poses.get(n.ack)?.get(e);if(r!==void 0)return{vx:r.vx/1e3,vy:r.vy/1e3,vz:r.vz/1e3,vyaw:0}}start(e,n,r){let s=this.options.others().map(a=>({id:a.id,epoch:a.epoch,body:{...a.body},input:a.input})).sort(Mh),o=new Map([[e,new Map(s.map(a=>[a.id,dS(a.body)]))]]);this.serial+=1,this.current!==null&&(this.recent=[this.current,...this.recent].slice(0,yC));for(let a of this.applied.keys())a<=e&&this.applied.delete(a);let i={id:this.serial,ack:e,stateTick:n,tickHz:r,last:e,ticks:0,seats:s,poses:o,touching:new Map,own:new Map,ownIn:new Map,ownOn:new Map};return this.current=i,i}tick(e,n,r,s,o){let i=Math.ceil(this.options.maxAheadMs()*e.tickHz/1e3),a=n<=i?this.carry(e,n):null;if(n<=i)for(let p of e.seats)this.move(e,p,n,a===null?void 0:gc(a.t,p.id));let c=r===void 0?void 0:{...r};r!==void 0&&(e.ownIn.set(e.ack+n,{...r}),e.ownOn.set(e.ack+n,o));let u=a===null?null:this.ride(e,a,c,o),l=e.seats.map(p=>fS(p.id,p.body)),d=new Set;if(c!==void 0)for(let p of l)this.touches(c,p)&&d.add(p.id);let f=c===void 0?l:[...l,c].sort(Mh);if(this.contactPass(f),e.seats.forEach((p,g)=>{let x=l[g];for(let b of uo)typeof x[b]=="number"&&(p.body[b]=x[b])}),a!==null&&this.impart(e,a,c),r!==void 0&&c!==void 0&&s)for(let p of uo){let g=c[p];typeof g=="number"&&g!==r[p]&&(r[p]=Math.fround(g))}let h=e.ack+n;return e.poses.set(h,new Map(e.seats.map(p=>[p.id,dS(p.body)]))),e.touching.set(h,d),c!==void 0&&e.own.set(h,s&&r!==void 0?{...r}:c),e.ticks=n,u}ride(e,n,r,s){let o=n.t,i=new Map(e.seats.map(h=>[h.id,h.body])),a=h=>r!==void 0&&h===r.id?r:i.get(h);for(let h of o.seats){let p=a(h.id);p!==void 0&&(h.x=Ee(p.x),h.y=Ee(p.y))}Ax(n.l.lifts,o);for(let h of o.seats){let p=i.get(h.id);p!==void 0&&(p.x=h.x,p.y=h.y)}if(r===void 0||s===null)return null;let c=o.seats.find(h=>h.id===r.id),u=o.seats.findIndex(h=>h.id===s);if(c===void 0&&u<0)return null;let l=c===void 0?o.report.from[u]:[r.x,r.y],d=c??o.seats[u],f=[d.x-l[0],d.y-l[1]];return r.x=Math.fround(r.x+f[0]),r.y=Math.fround(r.y+f[1]),f}carry(e,n){let r=this.options.lifts?.()??null;if(r===null)return null;let s=e.own.get(e.ack+n-1),o=e.seats.map(c=>pS(c.id,c.body));s!==void 0&&o.push(pS(s.id,s)),o.sort(Mh);let i=yc(r.lifts,o,e.stateTick+n,r.starts,1/e.tickHz,r.cache),a=new Map(i.seats.map(c=>[c.id,c]));for(let c of e.seats){let u=a.get(c.id);c.body.x=u.x,c.body.y=u.y,c.body.z=u.z,r.lifts.vehicle&&(c.body.yaw=u.yaw)}return{l:r,t:i}}impart(e,n,r){let s=new Map(e.seats.map(i=>[i.id,i.body]));r!==void 0&&s.set(r.id,r);for(let i of n.t.seats){let a=s.get(i.id);a!==void 0&&(i.x=Ee(a.x),i.y=Ee(a.y),i.z=Ee(a.z),i.vx=Ee(a.vx),i.vy=Ee(a.vy),i.vz=Ee(a.vz))}bc(n.l.lifts,n.t,n.l.starts);let o=new Map(n.t.seats.map(i=>[i.id,i]));for(let i of e.seats){let a=o.get(i.id);i.body.vx=a.vx,i.body.vy=a.vy,i.body.vz=a.vz}}move(e,n,r,s){let o=1/e.tickHz,{predict:i,decayMs:a}=this.options.remote(),c=i===jt.EXTRAPOLATE?void 0:this.options.step();if(c===void 0||n.input===void 0){let l=n.body;l.x=Ee(l.x)+Ee(l.vx)*o,l.y=Ee(l.y)+Ee(l.vy)*o,l.z=Ee(l.z)+Ee(l.vz)*o;return}this.options.seatRule?.(n.body,e.stateTick+r);let u=i===jt.INPUT_DECAY?od(n.input,r,e.tickHz,a):n.input;c(n.body,u,o,s)}contactPass(e){if(this.options.pass!==void 0){this.options.pass(e);return}for(let n=0;n<e.length;n++)for(let r=n+1;r<e.length;r++)this.options.rule(e[n],e[r])}touches(e,n){let r={...e},s={...n};return r.id<s.id?this.options.rule(r,s):this.options.rule(s,r),!hS(r,e)||!hS(s,n)}};function yS(t,e,n,r){if(t===void 0||!Number.isFinite(t.seq))return{seq:e,at:n};let s=Math.max(0,n-t.at),o=t.seq+s*r/1e3,i=e-o;if(Math.abs(i)>mt.SEAT_CLOCK_SNAP_INPUTS)return{seq:e,at:n};let a=o+i*(1-Math.exp(-s/mt.SEAT_CLOCK_TAU_MS));return{seq:Math.max(t.seq,a),at:n}}function gS(t,e,n){if(t===void 0||!Number.isFinite(t))return e?1:0;let r=Math.max(0,n)/mt.SEAT_CLOCK_TAU_MS;return e?Math.min(1,t+r):Math.max(0,t-r)}var gC=.01;function bS(t,e){let n=Math.exp(-e/mt.SEAT_TAU_MS),r=Math.max(Math.abs(t.dx),Math.abs(t.dy),Math.abs(t.dz))*n<gC;return{dx:t.dx*n,dy:t.dy*n,dz:t.dz*n,done:r}}var bC=t=>t?mt.SEAT_CONTACT_TAU_MS:mt.SEAT_TAU_MS;function hd(t,e,n,r){let s=1/r,o=Math.exp(-s*n),i=e+s*t;return[(t+i*n)*o,(e-s*i*n)*o]}function wS(t,e,n,r,s,o,i,a,c){let u={ax:s.pose.x,ay:s.pose.y,az:s.pose.z},l={pass:e,epoch:n,dx:0,dy:0,dz:0,dyaw:0,vx:0,vy:0,vz:0,vyaw:0,...u,hx:0,hy:0,hz:0,stillMs:0,stopFound:!1};if(t===void 0||t.epoch!==n)return l;let d=bC(i),f=Math.max(0,o),[h,p]=hd(t.dx,t.vx,f,d),[g,x]=hd(t.dy,t.vy,f,d),[b,S]=hd(t.dz,t.vz,f,d),[_,P]=hd(t.dyaw,t.vyaw,f,d),R=t.pass!==e&&r!==void 0,v=R?r.before:s,M=R?r.after:s,O={x:v.pose.x-M.pose.x,y:v.pose.y-M.pose.y,z:v.pose.z-M.pose.z,yaw:ds(v.pose.yaw-M.pose.yaw)},z={vx:v.rate.vx-M.rate.vx,vy:v.rate.vy-M.rate.vy,vz:v.rate.vz-M.rate.vz,vyaw:v.rate.vyaw-M.rate.vyaw},X={pose:{...s.pose,x:s.pose.x+O.x,y:s.pose.y+O.y,z:s.pose.z+O.z},rate:{vx:s.rate.vx+z.vx,vy:s.rate.vy+z.vy,vz:s.rate.vz+z.vz,vyaw:s.rate.vyaw+z.vyaw}},N=R?wC(t,z)||t.stopFound&&t.stillMs>0:t.stopFound,Y=xC(t,{...t,pass:e,dx:h,dy:g,dz:b,dyaw:_,vx:p,vy:x,vz:S,vyaw:P,stopFound:N},X,s.rate,c),he={dx:Y.dx+O.x,dy:Y.dy+O.y,dz:Y.dz+O.z,dyaw:ds(Y.dyaw+O.yaw)};if(Math.hypot(he.dx,he.dy,he.dz)>a)return l;let A={vx:Y.vx+z.vx,vy:Y.vy+z.vy,vz:Y.vz+z.vz,vyaw:Y.vyaw+z.vyaw};return SC({...Y,...he,...A,...u},s.rate,f)}function wC(t,e){return e.vx*t.hx+e.vy*t.hy+e.vz*t.hz>mt.SEAT_MOVING_UNITS_PER_MS}function xC(t,e,n,r,s){let o={x:t.hx,y:t.hy,z:t.hz},i=_=>_.x*o.x+_.y*o.y+_.z*o.z,a=i({x:n.rate.vx,y:n.rate.vy,z:n.rate.vz}),c=n.pose,l=i({x:c.x-t.ax,y:c.y-t.ay,z:c.z-t.az})+i({x:e.dx-t.dx,y:e.dy-t.dy,z:e.dz-t.dz}),d=i({x:r.vx,y:r.vy,z:r.vz})<0,f=s!==void 0&&i({x:s.vx,y:s.vy,z:s.vz})>mt.SEAT_MOVING_UNITS_PER_MS,h=i({x:t.dx,y:t.dy,z:t.dz})>0,p=e.stopFound&&f&&h;if(t.stillMs>=mt.SEAT_HOLD_MS||d&&!p)return e;let x=a+i({x:e.vx,y:e.vy,z:e.vz});if(l>=0&&x>=0)return e;let b=Math.max(0,-l),S=-x;return{...e,dx:e.dx+b*o.x,dy:e.dy+b*o.y,dz:e.dz+b*o.z,vx:e.vx+S*o.x,vy:e.vy+S*o.y,vz:e.vz+S*o.z}}function SC(t,e,n){let r=e.vx+t.vx,s=e.vy+t.vy,o=e.vz+t.vz,i=Math.hypot(r,s,o);return i>mt.SEAT_MOVING_UNITS_PER_MS?{...t,hx:r/i,hy:s/i,hz:o/i,stillMs:0}:{...t,stillMs:t.stillMs+n}}function EC(t){if(!(t===void 0||typeof t.inMoveX!="number"))return{moveX:St(t.inMoveX),moveY:St(t.inMoveY),moveZ:St(t.inMoveZ),yaw:St(t.inYaw),pitch:St(t.inPitch),buttons:St(t.inButtons)}}var xS=1e3/60,_C=xS,RC=0,St=t=>typeof t=="number"&&Number.isFinite(t)?t:RC;function SS(t){let e={status:t.enabled?He.LOADING:He.OFF,matched:0,replayed:0,peakResimMs:0,lastResimMs:0,slowResims:0,fallbacks:0,recoveries:0},n=null,r=null,s=0,o=0,i=new Map,a,c=t.state,u=new Map,l=S=>{e.status=S,n?.stop(S),n=null},d=()=>{if(r!==null||t.loadCore===void 0){t.loadCore===void 0&&(e.status=He.UNAVAILABLE);return}r=t.loadCore().then(S=>{if(e.status!==He.LOADING)return;if(!Kx(S))return l(He.SELF_TEST);let _=Ec(c.physDesc);if(_===null)return l(He.MISMATCH);let P=t.staticWorld();n=new cd(S,{desc:_,staticWorld:{boxes:P.boxes.map(R=>[...R]),ramps:P.ramps.map(R=>[...R])},physicsHash:c.physics??"",tickHz:t.tickHz(),budgetMs:t.budgetMs,remoteStep:t.remoteStep?.(),bodyRule:t.bodyRule,...t.headSlide===void 0?{}:{headSlide:t.headSlide},kinematicRule:t.kinematicRule,...t.lifts===void 0?{}:{lifts:t.lifts},seatRule:t.seatRule,seatPose:t.seatPose,contactPass:t.contactPass,...t.clock===void 0?{}:{clock:t.clock}}),n.predicting||l(n.status)}).catch(()=>l(He.UNAVAILABLE))},f=()=>{let S=c.entities??new Map,_=N=>c.shapes?.get(N)?.data,P=[],R=[],v=N=>c.bodies?.has(N)===!0;for(let[N,Y]of c.bodies??[]){let he=Y.desc===void 0||Y.desc===""?null:Ux(Y.desc,_),A=S.get(N);if(A===void 0||t.motionKnown?.(N)===!1){let $=u.get(N)??(A===void 0?[0,0,0]:[A.x,A.y,A.z]);R.push({key:N,x:$[0],y:$[1],z:$[2],radius:he===null?0:_c(he)});continue}u.set(N,[A.x,A.y,A.z]);let W=new Array(15),G={x:A.x,y:A.y,z:A.z,qx:St(A.qx),qy:St(A.qy),qz:St(A.qz),qw:St(A.qw),lvx:St(A.lvx),lvy:St(A.lvy),lvz:St(A.lvz),avx:St(A.avx),avy:St(A.avy),avz:St(A.avz),sleep:A.sleep===!0,rest:St(A.rest)};Lx(G,W,0),P.push({key:N,desc:he,row:W,epoch:A.epoch})}for(let N of u.keys())c.bodies?.has(N)!==!0&&u.delete(N);let M=[];for(let[N,Y]of c.joints??[])try{M.push({key:N,desc:JSON.parse(Y.desc),motor:Y.motor===""?null:JSON.parse(Y.motor)})}catch{}let O=[],z=new Set,X=t.ownId();for(let[N,Y]of S){if(Y.owner===""||z.has(Y.owner)||Cr(Y)||v(N)||c.players?.has(Y.owner)!==!0)continue;z.add(Y.owner);let he={...Y};O.push({key:N,x:Y.x,y:Y.y,z:Y.z,vx:Y.vx,vy:Y.vy,vz:Y.vz,epoch:Y.epoch,own:N===X,input:EC(c.players?.get(Y.owner)),body:he})}return{tick:c.keyframe??0,ack:t.acked(),bodies:P,outside:R,joints:M,seats:O}},h=null,p=0,g=t.clock??(()=>performance.now()),x=()=>{let S=h;h=null,p=0,S!==null&&b(S)},b=S=>{if(n===null)return;for(let[P,R]of t.ownPath?.()??[])i.set(P,R);let _=n.adopt(S.keyframe,S.sent,P=>i.get(P)?.p,S.now,P=>i.get(P)?.v);_.kind==="match"&&e.matched++,_.kind==="replay"&&e.replayed++,_.kind==="replay"&&(e.lastResimMs=_.ms,_.ms>xS&&e.slowResims++),e.peakResimMs=Math.max(e.peakResimMs,_.ms),e.fallbacks=n.fallbacks,e.recoveries=n.recoveries,n.stopped?l(n.status):e.status=n.status,o=S.sent};return{status:e,onState(S){if(e.status===He.OFF)return;let _=c.keyframe??0;if(_===0||(c.physDesc??"")==="")return;if(n===null){d();return}if(_===s||c.tick!==_)return;s=_;let P={keyframe:f(),sent:t.sent(),now:S};if(p>=_C){h=P;return}let R=g();b(P),p+=g()-R},settle:x,afterSend(S,_){x();let P=t.sent(),R=a??S,v=P-o;for(let M=1;M<=v;M++){let O=M/v;if(S!==void 0&&R!==void 0){let z=[R.p[0]+(S.p[0]-R.p[0])*O,R.p[1]+(S.p[1]-R.p[1])*O,R.p[2]+(S.p[2]-R.p[2])*O];i.set(o+M,{p:z,v:S.v})}n?.advance(o+M,_)}o=P,a=S;for(let M of i.keys())M<P-256&&i.delete(M)},draw(S,_){return x(),n===null||!n.draws(S)?null:n.draw(S,_)},dispose(){n?.stop(He.OFF),n=null}}}wt();var yd={min:-1,max:1,bits:16,mode:"clamp"},Oi={min:-64,max:64,bits:16,mode:"clamp"},ES=It({moveX:q.float32().default(0),moveY:q.float32().default(0),moveZ:q.float32().default(0),yaw:q.float32().default(0),pitch:q.float32().default(0),buttons:q.number().default(0),tick:q.number().default(0)},"AuthorityInput"),kC=1,_S=t=>({kind:q.string().default(""),owner:q.string().default(""),x:t(q.float32().default(0)),y:t(q.float32().default(0)),z:t(q.float32().default(0)),vx:t(q.float32().default(0)),vy:t(q.float32().default(0)),vz:t(q.float32().default(0)),yaw:t(q.float32().default(0)),hp:q.number().default(0),flags:q.number().default(0),epoch:t(q.number().default(0)),data:q.string().default(""),t0:q.number().default(0),g:q.float32().default(0),src:q.string().default(""),pitch:t(q.float32().default(0)),duck:t(q.float32().default(0)),mstate:t(q.number().default(0)),cap:q.float32().default(1),spin:t(q.float32().default(0)),fuel:t(q.float32().default(0)),qx:t(q.quantized(yd).optional()),qy:t(q.quantized(yd).optional()),qz:t(q.quantized(yd).optional()),qw:t(q.quantized(yd).optional()),lvx:t(q.quantized(Oi).optional()),lvy:t(q.quantized(Oi).optional()),lvz:t(q.quantized(Oi).optional()),avx:t(q.quantized(Oi).optional()),avy:t(q.quantized(Oi).optional()),avz:t(q.quantized(Oi).optional()),sleep:t(q.boolean().optional()),rest:t(q.number().optional())}),PC=It(_S(t=>t),"AuthorityEntity"),AC=It(_S(t=>t.view(kC)),"AuthorityEntity"),vC=It({type:q.string().default(""),kind:q.string().default(""),colliders:q.string().default(""),desc:q.string().optional()},"AuthorityBody"),TC=It({data:q.string().default("")},"AuthorityShape"),MC=It({desc:q.string().default(""),motor:q.string().default("")},"AuthorityJoint"),CC=It({name:q.string().default(""),uid:q.string().default(""),team:q.string().default(""),connected:q.boolean().default(!0),avatarUrl:q.string().default(""),seqBase:q.number().default(0),inMoveX:q.float32().optional(),inMoveY:q.float32().optional(),inMoveZ:q.float32().optional(),inYaw:q.float32().optional(),inPitch:q.float32().optional(),inButtons:q.number().optional(),inRep:q.number().optional(),inStarve:q.number().optional(),inBuf:q.number().optional()},"AuthorityPlayer"),RS={players:q.map(CC),entities:q.map(PC),tick:q.number().default(0),clockOrigin:q.float64().default(0),preset:q.string().default(""),moduleSha:q.string().default(""),tickOrigin:q.float64().default(0),physics:q.string().optional(),lengthUnit:q.float32().optional(),bodies:q.map(vC).optional(),physDesc:q.string().optional(),keyframe:q.number().optional(),shapes:q.map(TC).optional(),joints:q.map(MC).optional(),lifts:q.string().optional()},yz=It(RS,"AuthorityRoomState"),gz=It({...RS,entities:q.map(AC).view()},"AuthorityRoomState");var OC=(t,e)=>t+Math.atan2(Math.sin(e-t),Math.cos(e-t)),IC=(t,e,n)=>({x:t.x+(e.x-t.x)*n,y:t.y+(e.y-t.y)*n,z:t.z+(e.z-t.z)*n,yaw:t.yaw+(e.yaw-t.yaw)*n,pitch:t.pitch+(e.pitch-t.pitch)*n,duck:t.duck+(e.duck-t.duck)*n}),gd=class{constructor(){m(this,"rings",new WeakMap)}push(e,n,r,s,o=0){let i=this.rings.get(e);i===void 0&&(i=[],this.rings.set(e,i));let a=i.at(-1);if(a!==void 0&&n<=a.t)return;let c=a!==void 0&&a.life===o,u=c?OC(a.pose.yaw,r.yaw):r.yaw;c&&n-a.t>s*1.5&&i.push({t:n-s,life:o,pose:a.pose}),i.push({t:n,life:o,pose:{...r,yaw:u}}),i.length>80&&i.splice(0,i.length-80)}at(e,n){let r=this.rings.get(e);if(r===void 0||r.length===0)return;let s=r[0],o=r.at(-1);if(n<=s.t)return s.pose;if(n>=o.t)return o.pose;let i=r.length-2;for(;i>0&&r[i].t>n;)i--;let a=r[i],c=r[i+1];return a.life!==c.life?a.pose:IC(a.pose,c.pose,(n-a.t)/(c.t-a.t))}forget(e){this.rings.delete(e)}};var ut={On:"on",Off:"off"},Ez={[Un.Shooter]:{repeat:ut.On},[Un.Platformer]:{repeat:ut.On},[Un.VehicleArena]:{repeat:ut.Off},[Un.PhysicsSandbox]:{repeat:ut.On},[Un.Party]:{repeat:ut.On}},_z={repeat:ut.On};var kS=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);function PS(t){let e;try{e=JSON.parse(t)}catch{return ut.On}let n=kS(e)?e.inputs:void 0;return kS(n)&&n.repeat===ut.Off?ut.Off:ut.On}var jz={MAX_ENTITIES:256,MAX_ROOM_ENTITIES:1024,MAX_OUTPUT_BYTES:32*1024,MAX_EVENTS_PER_TICK:64,MAX_ENTITY_DATA_BYTES:256,MAX_ENTITY_ID_CHARS:64,MAX_KIND_CHARS:64,MAX_SESSION_ID_CHARS:64,MAX_ABS:1e9,MASK_LIMIT:16777216,MAX_EPOCH:2**32-1,MAX_PROJECTILE_TICK:Bw,MAX_PROJECTILE_G:ic,MAX_LAUNCH_UPDATES:224,MAX_LAUNCH_BYTES:28*1024,MAX_EVENT_TYPE_CHARS:$t.MAX_EVENT_TYPE_CHARS,MAX_EVENT_BYTES:$t.MAX_EVENT_BYTES,MAX_JSON_DEPTH:$t.MAX_JSON_DEPTH,MAX_JSON_NODES:$t.MAX_JSON_NODES,MAX_PLAYERS:$t.ROOM_MAX_CLIENTS,MAX_PHYS_COMMANDS:256,MAX_PHYS_BYTES:32*1024,MAX_PHYSICS_OUTPUT_BYTES:64*1024,MAX_WORLD_TEXT_CHARS:155660};function Ii(t){return{moveX:Ln(t.moveX),moveY:Ln(t.moveY),moveZ:Ln(t.moveZ),yaw:os(t.yaw)??0,pitch:os(t.pitch)??0,buttons:Js(t.buttons)}}var qz=2**31-1;var Zz=rs.INPUT_REPEAT_MAX_MS,Qz=rs.INPUT_REPEAT_RUN_MS;function vS(t,e,n,r=ut.On){return r===ut.Off?t:Math.max(t,Math.min(t+MS(e),n))}function TS(t,e,n=ut.On){return n===ut.Off?t:t+MS(e)}var DC=(t,e,n)=>e<=n?e:Math.min(t,n),MS=t=>typeof t=="number"&&Number.isInteger(t)&&t>0?t:0;function CS(){return{shown:0,heldFrom:null}}function OS(t,e,n,r,s){let o=DC(t.shown,e,n);return o<=t.shown?(o<t.shown&&(t.heldFrom=null),t.shown=o,o):o===n||n-(o+1)<r||s?(t.heldFrom=null,t.shown=o,o):(t.heldFrom??(t.heldFrom=n),n-t.heldFrom<r?t.shown:(t.shown=o,o))}var BC=.03,NC=1,AS=.5;function IS(){return{seenRuns:null,owedMs:0,accMs:0,aheadMs:0}}function DS(t,e,n,r,s=ut.On){if(s===ut.Off||typeof e!="number"||!Number.isFinite(e))return;let o=t.seenRuns!==null&&e>t.seenRuns;if(t.seenRuns=e,!o||!(r>0))return;(typeof n=="number"&&Number.isFinite(n)?n:0)<=NC&&(t.owedMs=Math.max(t.owedMs,r))}function BS(t,e,n,r,s){let o=r>0?n.accMs/r:0;return{raw:t+e+AS*o,at:s+AS*n.aheadMs}}function NS(t,e,n){if(!(n>0)||!(e>0)||t.owedMs<=0)return 0;let r=Math.min(t.owedMs,e*BC);t.owedMs-=r,t.accMs+=r,t.aheadMs+=r;let s=Math.floor(t.accMs/n+.5);return t.accMs-=s*n,s}wt();var US=1,VS=1200,Ih=8,LC=170,FC=3,HS=32,Dh=8;var zC=5e3,UC=32,VC=32,HC=4,$C=1024,$S=1e3,jS=2e3,bd={Bind:"__fast",Off:"__fast:off"},qS={Uplink:1,Snapshot:2},ke={Oversized:"oversized",Truncated:"truncated",Trailing:"trailing",Version:"version",Kind:"kind",Session:"session",Key:"key",Count:"count",Fresh:"fresh",Actions:"actions",Flags:"flags",Order:"order",Field:"field",Ahead:"ahead",Fragment:"fragment",Mismatch:"mismatch",Duplicate:"duplicate",Keyframe:"keyframe",Body:"body",Base:"base",Stale:"stale"};var GS=29,LS=29,wd=24,Bh=1,Nh=2,Lh=4,nU=Bh|Nh|Lh,FS=255,WS=10,jC=4+wd,Pc=4294967295,YS=65536,Ch=1;var Fh=t=>({ok:!0,value:t}),wn=t=>({ok:!1,fault:t}),KS=(t,e)=>Math.ceil(t*(Number.isFinite(e)&&e>0?e:0)/1e3),fo=(t,e)=>typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<=e;function Ac(t){return Math.min(HS,Math.max(FC,KS(LC,t)))}function XS(t){return GS+Dh*(WS+wd)+Ac(t)*jC}var vc=t=>KS(zC,t);function qC(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function GC(t){return/^(?:[0-9a-fA-F]{2})*$/.test(t)?Uint8Array.from(t.match(/../g)??[],e=>Number.parseInt(e,16)):new Uint8Array(0)}var WC=t=>typeof t=="string"&&t.length===2*Ih&&/^[0-9a-f]+$/.test(t),YC=(t,e)=>(e.buttons&~(t?.buttons??0))!==0,KC=t=>[t.moveX,t.moveY,t.moveZ,t.yaw,t.pitch].every(e=>typeof e=="number"&&Number.isFinite(Math.fround(e)))&&fo(t.buttons,Pc),XC=t=>fo(t.seq,Pc)&&t.seq>=1&&fo(t.tick,YS-1)&&fo(t.render,Pc)&&KC(t.input),JC=t=>t.reduce((e,n)=>Math.max(e,n.render),0),ZC=(t,e)=>e.render===0||t-e.render>=FS?FS:t-e.render;function QC(t){let{window:e,actions:n}=t;if(!fo(t.sid,Pc)||!WC(t.key)||!fo(t.ackSnap,Pc)||e.length<1||e.length>HS||n.length>Dh||!fo(t.fresh,e.length)||t.fresh<1||![...n,...e].every(XC))return!1;let r=e.every((o,i)=>i===0||o.seq===e[i-1].seq+1),s=n.every((o,i)=>o.seq<(i+1<n.length?n[i+1].seq:e[0].seq));return r&&s}function Oh(t,e,n){return t.setFloat32(e,n.moveX,!0),t.setFloat32(e+4,n.moveY,!0),t.setFloat32(e+8,n.moveZ,!0),t.setFloat32(e+12,n.yaw,!0),t.setFloat32(e+16,n.pitch,!0),t.setUint32(e+20,n.buttons,!0),e+wd}var zS=t=>{let e=new Uint8Array(wd);return Oh(new DataView(e.buffer),0,t),qC(e)};function eO(t,e){if(t===null)return 0;let n=zS(t.input)===zS(e.input)?Bh:0;return e.tick===t.tick?n|=Nh:e.tick===(t.tick+1)%YS&&(n|=Lh),n}function JS(t){if(!QC(t))return wn(ke.Field);let e=new Uint8Array(VS),n=new DataView(e.buffer);e[0]=US,e[1]=qS.Uplink,n.setUint32(2,t.sid,!0),e.set(GC(t.key),6),n.setUint32(14,t.ackSnap,!0),n.setUint32(18,t.window[t.window.length-1].seq,!0),e[22]=t.window.length,e[23]=t.fresh,e[24]=t.actions.length;let r=JC(t.window);n.setUint32(25,r,!0);let s=GS;for(let o of t.actions)n.setUint32(s,o.seq,!0),n.setUint16(s+4,o.tick,!0),n.setUint32(s+6,o.render,!0),s=Oh(n,s+WS,o.input);return t.window.forEach((o,i)=>{let a=eO(i===0?null:t.window[i-1],o);e[s]=a,s+=1,(a&(Nh|Lh))===0&&(n.setUint16(s,o.tick,!0),s+=2),e[s]=ZC(r,o),s+=1,(a&Bh)===0&&(s=Oh(n,s,o.input))}),Fh(e.slice(0,s))}function tO(t,e,n){return t.length>VS?ke.Oversized:t.length<2?ke.Truncated:t[0]!==US?ke.Version:t[1]!==e?ke.Kind:t.length<n?ke.Truncated:null}function ZS(t,e){let n=t.slice(-Ac(e.tickHz)),r=n.length>0?n[0].seq:Number.POSITIVE_INFINITY,s=t.filter((o,i)=>o.seq>e.inputAck&&o.seq<r&&YC(i>0?t[i-1].input:null,o.input)).slice(0,Dh);return{sid:e.sid,key:e.key,ackSnap:e.ackSnap,fresh:Math.min(e.fresh,n.length),actions:s,window:n}}var nO=t=>[...t].sort((e,n)=>e.key-n.key);function rO(t,e){let n=tO(t,qS.Snapshot,LS);if(n!==null)return wn(n);let r=new DataView(t.buffer,t.byteOffset,t.byteLength);if(r.getUint32(2,!0)!==e)return wn(ke.Session);let s=r.getUint32(6,!0),o=r.getUint32(10,!0),i=t[22],a=t[23],c=t[24];if(c<1||c>VC||a>=c)return wn(ke.Fragment);if(!((i&~Ch)===0&&i===Ch==(o===0))||s<1||o>=s)return wn(ke.Keyframe);let l=t.slice(LS);return Fh({snap:s,base:o,tick:r.getUint32(14,!0),inputAck:r.getUint32(18,!0),sent:r.getUint32(25,!0),keyframe:i===Ch,frag:a,frags:c,chunk:l})}function sO(t){let e=new DataView(t.buffer,t.byteOffset,t.byteLength);if(t.length<2)return wn(ke.Body);let n=e.getUint16(0,!0),r=2,s=[];for(let a=0;a<n;a+=1){if(r+2>t.length)return wn(ke.Body);let c=e.getUint16(r,!0);if(a>0&&c<=s[a-1])return wn(ke.Body);s.push(c),r+=2}if(r+2>t.length)return wn(ke.Body);let o=e.getUint16(r,!0);r+=2;let i=[];for(let a=0;a<o;a+=1){if(r+4>t.length)return wn(ke.Body);let c=e.getUint16(r,!0),u=e.getUint16(r+2,!0);if(u>$C||r+4+u>t.length||a>0&&c<=i[a-1].key)return wn(ke.Body);i.push({key:c,bytes:t.slice(r+4,r+4+u)}),r+=4+u}return r===t.length?Fh({removed:s,records:i}):wn(ke.Body)}function oO(t,e){let n=new Set(e.removed),r=new Map(t.filter(s=>!n.has(s.key)).map(s=>[s.key,s]));for(let s of e.records)r.set(s.key,s);return nO([...r.values()])}var QS=()=>({partials:[],history:[],newest:0}),iO=(t,e)=>t.base===e.base&&t.tick===e.tick&&t.inputAck===e.inputAck&&t.sent===e.sent&&t.keyframe===e.keyframe&&t.frags===e.frags;function eE(t,e,n){let r=rO(e,n);if(!r.ok)return{rx:t,applied:null,fault:r.fault};let s=r.value;if(s.snap<=t.newest)return{rx:t,applied:null,fault:ke.Stale};let o=t.partials.find(u=>u.snap===s.snap);if(o!==void 0&&!iO(o,s))return{rx:t,applied:null,fault:ke.Mismatch};if(o?.chunks[s.frag])return{rx:t,applied:null,fault:ke.Duplicate};let i=o??{snap:s.snap,base:s.base,tick:s.tick,inputAck:s.inputAck,sent:s.sent,keyframe:s.keyframe,frags:s.frags,chunks:Array(s.frags).fill(null)},a={...i,chunks:i.chunks.map((u,l)=>l===s.frag?s.chunk:u)},c=t.partials.filter(u=>u.snap!==s.snap);if(a.chunks.some(u=>u===null)){let u=[...c,a].sort((l,d)=>l.snap-d.snap).slice(-HC);return{rx:{...t,partials:u},applied:null}}return aO({...t,partials:c},t,a)}function aO(t,e,n){let r=t.partials.length===e.partials.length?e:t,s=sO(cO(n.chunks));if(!s.ok)return{rx:r,applied:null,fault:ke.Body};let o=n.keyframe?null:e.history.find(u=>u.snap===n.base);if(o===void 0)return{rx:r,applied:null,fault:ke.Base};if(n.keyframe&&s.value.removed.length>0)return{rx:r,applied:null,fault:ke.Body};let i=oO(o?.records??[],s.value),a=[...e.history,{snap:n.snap,tick:n.tick,inputAck:n.inputAck,sent:n.sent,records:i}].slice(-UC);return{rx:{partials:t.partials.filter(u=>u.snap>n.snap),history:a,newest:n.snap},applied:n.snap}}function cO(t){let e=new Uint8Array(t.reduce((r,s)=>r+s.length,0)),n=0;for(let r of t)e.set(r,n),n+=r.length;return e}var Nt={Entity:1,Seat:2},we={F32:"f32",U32:"u32",U16:"u16",Orientation:"q-orientation",Velocity:"q-velocity",Flag:"flag"},uO=[["x",we.F32],["y",we.F32],["z",we.F32],["vx",we.F32],["vy",we.F32],["vz",we.F32],["yaw",we.F32],["pitch",we.F32],["duck",we.F32],["spin",we.F32],["fuel",we.F32],["epoch",we.U32],["mstate",we.U32],["qx",we.Orientation],["qy",we.Orientation],["qz",we.Orientation],["qw",we.Orientation],["lvx",we.Velocity],["lvy",we.Velocity],["lvz",we.Velocity],["avx",we.Velocity],["avy",we.Velocity],["avz",we.Velocity],["sleep",we.Flag],["rest",we.U16]],lO=[["inMoveX",we.F32],["inMoveY",we.F32],["inMoveZ",we.F32],["inYaw",we.F32],["inPitch",we.F32],["inButtons",we.U32],["inRep",we.U32],["inStarve",we.U32],["inBuf",we.U32],["inAck",we.U32]],dO=64,Tc=2,tE=4;var zh=65534,fO=zh/2,pO={[we.Orientation]:1,[we.Velocity]:64},xd=()=>({x:0,y:0,z:0,vx:0,vy:0,vz:0,yaw:0,pitch:0,duck:0,spin:0,fuel:0,epoch:0,mstate:0,qx:0,qy:0,qz:0,qw:0,lvx:0,lvy:0,lvz:0,avx:0,avy:0,avz:0,sleep:!1,rest:0}),Sd=()=>({inMoveX:0,inMoveY:0,inMoveZ:0,inYaw:0,inPitch:0,inButtons:0,inRep:0,inStarve:0,inBuf:0,inAck:0});var hO=(t,e)=>-t+e/zh*(2*t),mO=t=>t===Nt.Entity?uO:t===Nt.Seat?lO:null;var rE={f32:4,u32:4,u16:2,"q-orientation":2,"q-velocity":2,flag:0};function yO(t,e,n){if(e+rE[n]>t.byteLength)return{ok:!1,fault:ke.Truncated};switch(n){case we.Flag:return{ok:!0,value:!0};case we.F32:{let r=t.getFloat32(e,!0);return Number.isFinite(r)&&r!==0?{ok:!0,value:r}:{ok:!1,fault:ke.Field}}case we.U32:{let r=t.getUint32(e,!0);return r!==0?{ok:!0,value:r}:{ok:!1,fault:ke.Field}}case we.U16:{let r=t.getUint16(e,!0);return r!==0?{ok:!0,value:r}:{ok:!1,fault:ke.Field}}default:{let r=t.getUint16(e,!0);return r!==fO&&r<=zh?{ok:!0,value:hO(pO[n],r)}:{ok:!1,fault:ke.Field}}}}var gO=new TextDecoder("utf-8",{fatal:!0});function bO(t){let e=t[1];if(Tc+e>t.length)return{ok:!1,fault:ke.Truncated};if(e===0)return{ok:!1,fault:ke.Field};try{let n=gO.decode(t.subarray(Tc,Tc+e));return n.length<=dO?{ok:!0,value:n}:{ok:!1,fault:ke.Field}}catch{return{ok:!1,fault:ke.Field}}}function sE(t){if(t.length<Tc)return{ok:!1,fault:ke.Truncated};let e=mO(t[0]);if(e===null)return{ok:!1,fault:ke.Kind};let n=bO(t);if(!n.ok)return n;let r=new DataView(t.buffer,t.byteOffset,t.byteLength),s=Tc+t[1];if(s+tE>t.length)return{ok:!1,fault:ke.Truncated};let o=r.getUint32(s,!0);if(s+=tE,e.length<32&&o>>>e.length)return{ok:!1,fault:ke.Flags};if(t[0]===Nt.Entity){let a=nE(r,s,o,xd(),e);return a.ok?{ok:!0,value:{kind:Nt.Entity,id:n.value,motion:a.value}}:a}let i=nE(r,s,o,Sd(),e);return i.ok?{ok:!0,value:{kind:Nt.Seat,id:n.value,motion:i.value}}:i}function nE(t,e,n,r,s){let o={},i=e;for(let[a,[c,u]]of s.entries()){if((n&1<<a)===0)continue;let l=yO(t,i,u);if(!l.ok)return l;o[c]=l.value,i+=rE[u]}return i!==t.byteLength?{ok:!1,fault:ke.Trailing}:{ok:!0,value:Object.assign(r,o)}}var wO=4294967295,fs={Unreachable:"unreachable",Handshake:"handshake",Stall:"stall",Server:"server"},xO=(t,e)=>typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<=e;function iE(t){if(typeof t!="object"||t===null)return!1;let{sid:e,key:n,url:r}=t,s=typeof n=="string"&&n.length===2*Ih&&/^[0-9a-f]+$/.test(n);return xO(e,wO)&&s&&typeof r=="string"&&r.length>0}function SO(t,e,n){if(t.length===0)return[];let r=t[t.length-1].seq,s=Math.min(e,r-Ac(n)+1),o=Math.max(s,r-vc(n)+1);return t.filter(i=>i.seq>=o)}var oE=(t,e)=>`${t}:${e}`;function aE(t){let e=QS(),n=[],r=new Map,s=0,o=!1,i=null,a=null,c=new Map,u=new Map,l=()=>e.history.at(-1)?.inputAck??0,d=g=>{let x=new Map,b=new Map,S=[];for(let _ of g){let P=c.get(_.key),R=P!==void 0&&(P.bytes===_.bytes||RO(P.bytes,_.bytes)),v=R?P.record:_O(_.bytes);x.set(_.key,{bytes:_.bytes,record:v}),v!==null&&(b.set(oE(v.kind,v.id),v),R||S.push(v))}return c=x,u=b,S};function f(g){if(o)return{applied:null};let x=eE(e,g,t.bind.sid);if(e=x.rx,x.fault!==void 0||x.applied===null)return{applied:null,fault:x.fault};let b=e.history.at(-1);if(b===void 0)return{applied:null};a=t.now(),n=SO(n,b.inputAck,t.tickHz);let S={snap:b.snap,tick:b.tick,inputAck:b.inputAck,sent:b.sent,changed:d(b.records)};return t.onSnapshot?.(S),{applied:S}}let h=t.open(t.bind.url,g=>{f(g)},t.bind);if(h===null)return null;let p=XS(t.tickHz);return{bind:t.bind,get rx(){return e},get lastQueued(){return n.at(-1)?.seq??0},get closed(){return o},queue(g){o||(n.push({seq:g.seq,tick:g.tick,render:g.render,input:{...g.input}}),s+=1)},flush(){if(o||s===0)return;let g=t.now();for(let S of n.slice(-s))r.set(S.seq,g);EO(r,(n.at(-1)?.seq??0)-vc(t.tickHz)+1);let x=Ac(t.tickHz),b=n.length-s;for(s=0;b<n.length;){let S=Math.min(b+x,n.length),_=ZS(n.slice(0,S),{sid:t.bind.sid,key:t.bind.key,ackSnap:e.newest,inputAck:l(),fresh:S-b,tickHz:t.tickHz});b=S;let P=JS(_);P.ok&&(i??(i=g),h.send(P.value))}},inputAt:g=>n.find(x=>x.seq===g),sentAt:g=>r.get(g),motionOf:(g,x)=>u.get(oE(g,x)),due(){if(o)return null;if(h.failed?.()===!0)return fs.Unreachable;let g=h.maxDatagramBytes?.();if(g!==void 0&&g<p)return fs.Unreachable;let x=t.now();return a!==null?x-a>jS?fs.Stall:null:i!==null&&x-i>$S?fs.Handshake:null},receive:f,close(){o||(o=!0,h.close())}}}function EO(t,e){for(let n of t.keys()){if(n>=e)return;t.delete(n)}}function _O(t){let e=sE(t);return e.ok?e.value:null}var RO=(t,e)=>t.length===e.length&&t.every((n,r)=>n===e[r]);var kO=19,PO=31,AO=Object.keys(xd()),vO=Object.keys(Sd()).filter(t=>t!=="inAck"),TO=t=>t===Nt.Entity?AO:vO,MO=["tick","keyframe"];function CO(t){if(typeof t!="object"||t===null)return null;let e=t,n=e._encoder;return typeof e._lastStamp!="number"||typeof n?.reset!="function"?null:t}function OO(t){let e=t;if(typeof e?._sampleStamp!="function")return()=>0;let n=e;return()=>{let r=n._sampleStamp().stamp;return typeof r=="number"&&Number.isInteger(r)&&r>=0&&r<=4294967295?r:0}}function lE(t){let{room:e,handle:n}=t,r={live:!1,snapshots:0,fallback:null},s=null,o=null,i=0,a=[],c=null,u=t.open===void 0?null:BO(e,()=>s?.client??null),l=CO(n),d=OO(n),f=()=>{if(s!==null)return Math.min(n.sentCount,i);if(o===null)return n.lastProcessed;let b=n.lastProcessed-o.wsBefore;return b>0?Math.max(o.ack,o.at+b):o.ack},h=()=>e.state.players?.get(e.sessionId)?.seqBase??0,p=b=>{if(o!==null)return;let S=s,_=s?.seqBase??h();o={at:n.sentCount,wsBefore:s?.wsBefore??n.sentCount,ack:f(),reason:b},s?.client.close(),s=null,a=[],r.live=!1,r.fallback=b,S!==null&&l!==null&&(l._encoder.reset(),l._lastStamp=S.stampAtBind);let P={last:_+n.sentCount};e.send(bd.Off,P),u?.release()},g=b=>{let S=s;if(S===null)return;r.snapshots+=1;let _=S.client.motionOf(Nt.Seat,e.sessionId),P=_?.kind===Nt.Seat?_.motion.inAck:0,R=Math.max(0,Math.min(n.sentCount,P-S.seqBase)),v=-1;if(R>i){let M=S.client.sentAt(S.seqBase+R);M!==void 0&&(v=t.now()-M),i=R}e.clock.sample(b.sent,v),u?.write(b)},x=b=>{if(t.open===void 0||s!==null||o!==null)return;if(!t.stateCurrent()){c=b;return}if(c=null,!iE(b))return p(fs.Unreachable);let S=aE({bind:b,tickHz:t.tickHz(),open:t.open,now:t.now,onSnapshot:g});if(S===null)return p(fs.Unreachable);s={client:S,seqBase:h(),wsBefore:n.sentCount,stampAtBind:l?._lastStamp??0},i=0,r.live=!0;for(let _ of a)S.queue({..._,seq:s.seqBase+_.seq});a=[],S.flush()};return t.open!==void 0&&(e.onMessage(bd.Bind,b=>x(b)),e.onMessage(bd.Off,()=>p(fs.Server)),e.onStateChange(()=>{c!==null&&t.stateCurrent()&&x(c)}),l!==null&&IO(e,()=>s!==null)),{status:r,ack:f,sent(b,S,_){if(t.open===void 0||o!==null)return;let P=d();if(s!==null){s.client.queue({seq:s.seqBase+b,tick:S,render:P,input:_});return}a.push({seq:b,tick:S,render:P,input:{..._}});let R=vc(t.tickHz());a.length>R&&(a=a.slice(-R))},flush(){s?.client.flush()},poll(){let b=s?.client.due()??null;b!==null&&p(b)},motionKnown(b){return s===null||s.client.motionOf(Nt.Entity,b)!==void 0},inputAt(b){if(s===null)return;let S=s.client.inputAt(s.seqBase+b);return S===void 0?void 0:{...S.input,tick:S.tick}},dropped(){s?.client.close(),s=null,u?.forget(),o=null,i=0,a=[],c=null,r.live=!1,r.fallback=null},dispose(){s?.client.close(),s=null,r.live=!1,u?.dispose()}}}function IO(t,e){let n=t.connection;if(n===void 0)return;let r=n.send.bind(n);n.send=s=>{e()&&s.length>0&&(s[0]&PO)===kO||r(s)}}var DO={...xd(),...Sd()};function BO(t,e){let n=t.serializer.decoder,r=t.state,s=new WeakMap,o=new Map,i=!1,a=n.triggerChanges,c=Object.getOwnPropertyDescriptor(n,"decode"),u=n.decode,l=S=>{let _=s.get(S),P=e();return _===void 0||P===null?void 0:P.motionOf(_.kind,_.id)},d=()=>{t.state.entities?.forEach((S,_)=>s.set(S,{kind:Nt.Entity,id:_})),t.state.players?.forEach((S,_)=>s.set(S,{kind:Nt.Seat,id:_}))},f=S=>{if(S===r)return!0;let _=s.get(S);return _===void 0?!1:(_.kind===Nt.Entity?t.state.entities?.get(_.id):t.state.players?.get(_.id))===S},h=(S,_,P,R)=>{let v=o.get(S);v===void 0&&(v=new Map,o.set(S,v));let M=v.get(_);M===void 0?v.set(_,{fast:P,ws:S[_]??DO[_]}):M.fast=P,uE(S,_,P,R)},p=()=>{d();for(let[S,_]of o){if(!f(S)){o.delete(S);continue}for(let[P,R]of _)R.ws!==R.fast&&(S[P]=R.ws)}i=!0},g=()=>{if(i){i=!1;for(let[S,_]of o)for(let[P,R]of _)R.ws!==R.fast&&(S[P]=R.fast)}},x=S=>{let _=S.field;if(_===void 0)return!1;let P=o.get(S.ref)?.get(_);return P===void 0?!1:(P.ws=S.value,!0)},b=S=>{if(e()===null)return a?.(S);d();for(let P of S){let R=P.value;if(P.field!==void 0||typeof R!="object"||R===null)continue;let v=l(R);v!==void 0&&cE(R,v,(M,O,z)=>h(M,O,z,null))}let _=S.filter(P=>!x(P));g(),a?.(_)};return Object.defineProperty(n,"triggerChanges",{configurable:!0,get:()=>b,set:S=>{a=S}}),Object.defineProperty(n,"decode",{configurable:!0,writable:!0,value:(...S)=>{e()!==null&&o.size>0&&p();try{return u.apply(n,S)}finally{g()}}}),{write(S){d();let _=[];for(let R of S.changed){let v=R.kind===Nt.Entity?t.state.entities?.get(R.id):t.state.players?.get(R.id);v!==void 0&&cE(v,R,(M,O,z)=>h(M,O,z,_))}let P=t.state.keyframe===void 0?["tick"]:MO;for(let R of P)h(r,R,S.tick,_);_.length>0&&a?.(_),t.onStateChange.invoke(t.state)},release(){d();let S=[],_=t.state.physics!==void 0;for(let[P,R]of o)if(!(!f(P)||_&&s.get(P)?.kind===Nt.Entity))for(let[v,M]of R)uE(P,v,M.ws,S);o.clear(),S.length!==0&&(a?.(S),t.onStateChange.invoke(t.state))},forget(){o.clear()},dispose(){o.clear(),Object.defineProperty(n,"triggerChanges",{configurable:!0,writable:!0,value:a}),c===void 0?Reflect.deleteProperty(n,"decode"):Object.defineProperty(n,"decode",c)}}}function cE(t,e,n){let r=e.motion;for(let s of TO(e.kind)){let o=r[s];(o===0||o===!1)&&t[s]===void 0||n(t,s,o)}}function uE(t,e,n,r){let s=t[e];s!==n&&(t[e]=n,r?.push({ref:t,refId:t[Q],op:B.REPLACE,field:e,value:n,previousValue:s}))}var NO=.05,dE=100,Ed=["x","y","z","yaw"],LO=.001;function fE(t,e,n,r){if(t===void 0)return[0,0,0,0];let s=t.err.map(o=>o*r);return t.k===e?s:t.shift.map((o,i)=>o+s[i]-n[i])}var Uh=[.5,1,5,20],FO=[1e3,2e3,4e3],pE=8,zO=250,hE=600,UO=["x","y","z","vx","vy","vz","yaw"],VO=new Set(["mstate","cap","spin","fuel"]),HO=new Set(["yaw"]),_d={Reconnecting:"reconnecting",Reconnected:"reconnected",Disconnect:"disconnect"},$O=new Set(Object.values(_d)),mE={protocol:`[multiplayer] the authority server refused protocol ${4} (code 426) \u2014 this game was built with a @genex-ai/multiplayer that the server no longer serves. Update the package and republish.`,notEntitled:"[multiplayer] server-authoritative rooms are not available for this game (code 402): its owner is not entitled to them. This is final; the session does not retry."},wE=t=>t&&typeof t=="object"?t.code:void 0;function jO(t){throw Qa(t)?console.error(mE.protocol):wE(t)===Ka.NOT_ENTITLED&&console.error(mE.notEntitled),t}var xE=t=>t.physicsCore!==void 0&&t.predictPhysics!==!1;function qO(){let t=typeof navigator>"u"?"":String(navigator.userAgent??"");return/Mobi|Android|iPhone|iPad/i.test(t)?ud.mobile:ud.desktop}async function GO(t){if(t.url)return[t.url];let e=ww(t.regions,t.urls);if(e.length===0)throw new Error("genex multiplayer: `urls` must contain at least one authority server URL");return(await Ew(e,t.probe===void 0?{}:{probe:t.probe})).map(r=>r.url)}async function WO(t){let e=await GO(t),n=t.capacityRetryMs??FO,r={region:0,refused:0,step:0};for(;;){let s=e[r.region];try{return{room:await YO(new es(s),t),url:s}}catch(o){let i=wE(o)===Ka.AUTHORITY_CAPACITY?Sw(r,e.length,n):null;i===null&&jO(o);let a=i.attempt.waitMs;a>0&&await new Promise(c=>setTimeout(c,a)),r=i.state}}}function YO(t,e){let n=e.fast===void 0?[]:[yn.FAST];return t.joinOrCreate(mi.AUTHORITY,{...Za(e.room,e.name,e.auth),[Gb.CAPS]:xE(e)?[yn.PHYSICS,yn.PHYSICS_PREDICT,yn.INPUT_REPEAT,yn.LIFTS,yn.INPUT_TICK,...n]:[yn.PHYSICS,yn.INPUT_REPEAT,yn.LIFTS,yn.INPUT_TICK,...n],protocol:4})}function Di(t){if(!t)return null;let e;try{e=JSON.parse(t)}catch{return null}if(!e||typeof e!="object")return null;let n=e.name,r=oc(n);if(r===void 0)return null;let s=wi(n,e.params);return{name:n,definition:r,params:s}}function Vh(t,e){let{definition:n,params:r}=t,s=[...n.fields,...n.reads],o=n.fields;return{fields:s,step:(i,a,c,u)=>{let l=n.step(i,a,c,r,e,u);for(let d of o)i[d]=l[d]}}}var Hh=t=>t!==null&&t.definition.world?t.params.world??null:null,ce=(t,e)=>typeof t=="number"&&Number.isFinite(t)?t:e;function KO(t){if(typeof t.inMoveX=="number")return{moveX:ce(t.inMoveX,0),moveY:ce(t.inMoveY,0),moveZ:ce(t.inMoveZ,0),yaw:ce(t.inYaw,0),pitch:ce(t.inPitch,0),buttons:ce(t.inButtons,0)}}var $h={body:!1,qx:0,qy:0,qz:0,qw:1,sleep:!1},yE=new Map,gE=2*Math.PI,ps=t=>t-gE*Math.floor((t+Math.PI)/gE),qU=[an.Predicted,an.Separate,an.Timeline],XO=an.Predicted,Bi=t=>{let e=t;return typeof e.local=="object"&&typeof e.error=="object"&&typeof e.prev=="object"&&typeof e.renderAlpha=="function"?e:null};async function SE(t){let e=await WO(t);return JO(Ks(e.room),t,e.url)}function JO(t,e,n){let r=t.state,s=()=>r.entities??yE,o=()=>r.players??yE,i=e.renderDelayMs??rs.RENDER_DELAY_MS,a=t.input({type:ES,mode:"reliable",renderDelay:i}),c=lE({room:t,handle:a,open:e.fast,now:e.fastClock??(()=>performance.now()),tickHz:()=>F(),stateCurrent:()=>!$e}),u=null,l=ut.On,d=()=>{let y=r.preset??"";return y!==u&&(u=y,l=PS(y)),l},f=()=>vS(c.ack(),o().get(t.sessionId)?.inRep,a.sentCount,d()),h=y=>a.at(y)??c.inputAt(y),p=CS(),g=()=>{let y=TS(c.ack(),o().get(t.sessionId)?.inRep,d()),E=a.sentCount,k=y<E&&c.inputAt(y+1)!==void 0;return OS(p,y,E,a.replayBufferSize,k)},x=new Map,b=new Proxy(a,{get(y,E){if(E==="lastProcessed")return g();if(E==="pendingCount")return a.sentCount-c.ack();if(E==="at")return h;let k=Reflect.get(y,E,y);if(typeof k!="function")return k;let V=x.get(E);return V===void 0&&(V=k.bind(y),x.set(E,V)),V}}),S=Ws.get(t,{mode:"lerp",delay:i}),_={mode:"lerp",fields:["x","y","z"]},P={mode:"lerp",fields:["yaw"],angle:!0};S.attachAll("entities",_),S.attachAll("entities",P),S.attachAll("entities",{mode:"lerp",fields:["pitch"]}),S.attachAll("entities",{mode:"lerp",fields:["duck"]});let R={moveX:0,moveY:0,moveZ:0,yaw:0,pitch:0,buttons:0},v={inputsSent:0,inputsDropped:0,reconciles:0,visibleCorrections:0,correctionBuckets:Uh.map(()=>0).concat(0),peakCorrection:0,lastCorrection:0,reseeds:0,bodyStates:0,bodySnaps:0,peakBodyCorrection:0,projectilesPredicted:0,projectilesConfirmed:0,projectilesRejected:0,lastProjectileLeadMs:0},M=new Map,O=(y,E)=>{for(let k of M.get(y)??[])k(E)},z=!0,X=!1,N=null,Y=!0,he=()=>{N?.predicted?.reconciler.dispose(),N=null},A=e.world===void 0?rc:eo(e.world),W="no_entity",G="",$=typeof e.physics=="string"?e.physics:"",j="",se=()=>{if(e.predict===!1)return{prediction:null,reason:"off"};if(e.predict)return{prediction:e.predict,reason:""};let y=Di(r.preset);if(y===null)return{prediction:null,reason:"no_preset"};let E=Hh(y);if(E!==null&&E!==A.hash){let k=`${E}/${A.hash}`;return G!==k&&(G=k,console.warn(`[multiplayer] the room's ${y.name} world (hash ${E}) is not this client's (hash ${A.hash}): your own entity is drawn from the server without prediction. Pass the room module's world to session.setWorld().`)),{prediction:null,reason:"world_mismatch"}}return{prediction:Vh(y,A),reason:""}},oe=()=>{let y=[];for(let[E,k]of s())E===N?.id||k.owner===""||Cr(k)||r.bodies?.has(E)===!0||!o().has(k.owner)||y.push({id:E,x:k.x,y:k.y,z:k.z,vx:k.vx,vy:k.vy,vz:k.vz,yaw:k.yaw,spin:ce(k.spin,0)});return y},ne=null,ye=()=>{if(e.contacts!==void 0)return null;let y=r.preset??"";return(ne===null||ne.text!==y||ne.hash!==A.hash)&&(ne={text:y,hash:A.hash,contacts:aS(y,A)}),ne.contacts},ue=()=>e.contacts!==void 0||ye()!==null,yt=e.contacts??((y,E)=>ye()?.rule(y,E)),Gt=e.contactPass??(e.contacts===void 0?y=>ye()?.pass(y):void 0),Hn=new ld(yt,()=>zi(oe())),Li=()=>e.seatDrawing??ye()?.policy.drawing??XO,hs=e.seatDrawing===void 0||e.seatDrawing===an.Predicted?Ui(yt):null,ms=()=>ue()?hs:null,Fi=()=>Li()===an.Predicted?ms():null;function zi(y){return ye()===null?y:y.map(E=>({...E,flags:ce(s().get(E.id)?.flags,0)}))}let ys=(y,E,k=null)=>{if(N===null||!ue())return null;let V={...E,id:N.id,...ye()===null?{}:{flags:ce(N.entity.flags,0)}},H=ms(),U=null;H!==null?U=H.apply(y,f(),r.tick??0,V,F(),k):Hn.apply(y,f(),V,F());for(let te of uo)typeof V[te]=="number"&&(E[te]=V[te]);return U};function Ui(y){let E=null,k=()=>{let H=r.preset??"";if(E!==null&&E.text===H&&E.hash===A.hash)return E;let U=Di(H),te=Hh(U),K=U!==null&&(te===null||te===A.hash)?Vh(U,A):null;return E={text:H,hash:A.hash,fields:U===null?[]:[...U.definition.fields,...U.definition.reads],step:K===null?void 0:(me,ie,fe,dt)=>K.step(me,Ii({...ie}),fe,dt)},E},V=()=>{let{fields:H}=k(),U=[];for(let[te,ee]of s()){if(te===N?.id||ee.owner===""||Cr(ee)||r.bodies?.has(te)===!0)continue;let K=o().get(ee.owner);if(K===void 0)continue;let me=ee,ie={x:ee.x,y:ee.y,z:ee.z,vx:ee.vx,vy:ee.vy,vz:ee.vz,yaw:ee.yaw,spin:ce(ee.spin,0)};for(let fe of H)ie[fe]=ce(me[fe],fe==="cap"?1:0);ye()!==null&&(ie.flags=ce(ee.flags,0)),U.push({id:te,epoch:ee.epoch,body:ie,input:KO(K)})}return U};return new md({rule:y,pass:Gt,others:V,step:()=>k().step,seatRule:e.seatRule,lifts:()=>{let H=Wt();return H===null?null:{lifts:H,starts:Et(),cache:$n}},remote:()=>{let H=Wi();return{predict:H?.remotePredict??jt.HOLD,decayMs:H?.remoteDecayMs??dr.DEFAULT_REMOTE_DECAY_MS}},maxAheadMs:()=>(Wi()?.leadMs??dr.DEFAULT_LEAD_MS)+mS})}let Nr=null,Wt=()=>{let y=r.preset??"",E=ye();if(Nr===null||Nr.text!==y||Nr.hash!==A.hash||Nr.heads!==E){let k=E!==null&&ox(E.policy)?{policy:E.policy,env:E.env}:void 0;Nr={text:y,hash:A.hash,heads:E,lifts:kx(y,A,k,F())}}return Nr.lifts},gs={text:void 0,starts:void 0},Et=()=>{let y=r.lifts;return gs.text!==y&&(gs={text:y,starts:Px(y)}),gs.starts},cn=new Ri,$n=new Ri,Rd=y=>{let E=ms();return oe().map(k=>{let V=E?.poseAt(k.id,y-1),H=ce(s().get(k.id)?.flags,0),U=ce(s().get(k.id)?.duck,0);return V===void 0?{...k,duck:U,flags:H}:{id:k.id,x:V.x,y:V.y,z:V.z,vx:V.vx,vy:V.vy,vz:V.vz,yaw:V.yaw,duck:U,flags:H}})},Vi=["x","y","z"],Oc=["vx","vy","vz"],un=(y,E,k,V,H)=>{if(N===null)return null;let U=V,te={id:N.id,x:U.x??0,y:U.y??0,z:U.z??0,vx:U.vx??0,vy:U.vy??0,vz:U.vz??0,yaw:U.yaw??0,duck:U.duck??0,flags:ce(N.entity.flags,0)},K=[...y.heads===void 0?[]:Rd(E),te].sort((ie,fe)=>ie.id<fe.id?-1:ie.id>fe.id?1:0),me=yc(y,K,k,Et(),H,cn);for(let ie of Vi)U[ie]=te[ie];return y.vehicle&&(U.yaw=te.yaw),{t:me,mine:te}},tt=Number.NaN,xn=null,bs=null,ho=(y,E,k,V,H,U)=>{let te=Mi(r.tick??0,f(),E),ee=Wt(),K=ee===null?null:un(ee,E,U??te,k,H);e.seatRule?.(k,te,E),y(k,Ii(V),H,K===null?void 0:gc(K.t,K.mine.id));let me=K===null?-1:K.t.seats.indexOf(K.mine),ie=K===null?null:K.t.report.on[me]??null,fe=ys(E,k,ie);if(ee===null||K===null)return;fe!==null&&vx(ee,K.t,me,fe);let dt=k;xn=ie;for(let Xt of[...Vi,...Oc])K.mine[Xt]=dt[Xt]??0;bc(ee,K.t,Et());for(let Xt of Oc)dt[Xt]=K.mine[Xt]},mo=new Ri,Hi=(y,E,k,V,H)=>{let U=Wt();U===null||U.policy.platforms.length===0?y(E,k,V):Mx(U,Et(),mo,(te,ee)=>y(te,k,V,ee),E,H,V)},yo=y=>{let{prediction:E,reason:k}=se();if(W=k,!E)return null;let V=E.fields??UO;return{reconciler:S.reconciler(y,{input:b,fields:V,step:(U,te,ee)=>{(U.isReplay||Number.isNaN(tt))&&(tt=Mi(r.tick??0,f(),U.tick)-U.tick),xn=null,ho(E.step,U.tick,te,ee,U.dt,U.tick+tt),bs=xn}}),fields:V,step:E.step}},go=()=>{let y=N?.predicted;if(!N||!y)return null;let E=N.entity,k={};for(let U of y.fields)k[U]=ce(E[U],0);let V=a.stepSeconds??y.reconciler.stepMs/1e3,H=new Map;for(let U=f()+1;U<=a.sentCount;U++){let te=h(U);te!==void 0&&(ho(y.step,U,k,te,V),H.set(U,{p:[k.x??0,k.y??0,k.z??0],v:[k.vx??0,k.vy??0,k.vz??0]}))}return H},ws=y=>{y.predicted&&(v.reseeds++,fr(y))},fr=y=>{y.predicted?.reconciler.dispose();let E=yo(y.entity);if(y.predicted=E,!E)return;let k=E.reconciler.state,V=a.stepSeconds??E.reconciler.stepMs/1e3;tt=Mi(r.tick??0,f(),0);for(let H=f()+1;H<=a.sentCount;H++){let U=h(H);U!==void 0&&ho(E.step,H,k,U,V)}y.reseeded=!0},$i=(y,E)=>E.owner===t.sessionId&&!Cr(E)&&r.bodies?.has(y)!==!0,Ic=y=>s().get(y.id)===y.entity&&$i(y.id,y.entity),jn=()=>{if(N&&Ic(N)){N.entity.epoch!==N.epoch&&(N.epoch=N.entity.epoch,ws(N));return}if(!(!N&&!Y)){he(),Y=!1,W="no_entity";for(let[y,E]of s())if($i(y,E)){N={id:y,entity:E,epoch:E.epoch,predicted:yo(E),reseeded:!1};return}}},xs=y=>{let E=y.reconciler.state;return y.fields.map(k=>E[k]??0)},nt=(y,E,k)=>{if(y.reconciler.reconcileSeq===k)return;let V=xs(y),H=0;if(y.fields.forEach((U,te)=>{if(VO.has(U))return;let ee=(V[te]??0)-(E[te]??0);H=Math.max(H,Math.abs(HO.has(U)?ps(ee):ee))}),v.reconciles++,v.lastCorrection=H,v.peakCorrection=Math.max(v.peakCorrection,H),H>NO){v.visibleCorrections++;let U=Uh.findIndex(te=>H<te);v.correctionBuckets[U<0?Uh.length:U]+=1}},bo=y=>{if(!y.fields.includes("yaw"))return null;let E=Bi(y.reconciler),k=E?.local.yaw;return E&&typeof k=="number"?{local:k,error:E.error.yaw??0}:null},Dc=(y,E,k)=>{if(k===null||y.reconciler.reconcileSeq===E)return;let V=Bi(y.reconciler),H=V?.local.yaw,U=V?.error.yaw;if(!V||typeof H!="number"||typeof U!="number")return;let te=k.local+k.error-H;(te<-Math.PI||te>=Math.PI)&&(V.error.yaw=ps(te)*(U/te))},Bc=y=>{let E=Bi(y.reconciler);if(E===null||Number.isNaN(tt))return null;let k=V=>Object.fromEntries(Ed.map(H=>[H,ce(V[H],0)]));return{offset:tt,local:k(E.local),error:k(E.error),prev:k(E.prev)}},Nc=(y,E,k,V)=>{if(V===null||y.reconciler.reconcileSeq===E||V.offset===tt)return k;let H=Wt(),U=Bi(y.reconciler);if(H===null||H.policy.platforms.length===0||U===null)return k;let te=Et(),ee=a.sentCount+V.offset+1,K=a.sentCount+tt+1,me=je=>({x:je.x??0,y:je.y??0,z:je.z??0,yaw:je.yaw??0,duck:ce(U.local.duck,0)}),ie=wc(H,me(V.local),ee,te);if(ie<0||wc(H,me(U.local),K,te)!==ie)return k;let fe=(je,dn,qn)=>{let _n=mh(H.policy,ie,me(je),dn,qn,te);return{..._n,yaw:H.vehicle?_n.yaw:je.yaw??0}},dt=Object.fromEntries(Ed.map(je=>[je,(V.local[je]??0)+(V.error[je]??0)])),Xt=fe(dt,ee,K),gt=fe(V.prev,ee-1,K-1),Ro=fe(V.local,ee,K);for(let je of Ed){if(typeof U.local[je]!="number")continue;let dn=ce(U.local[je],0),qn=(dt[je]??0)-dn,_n=qn===0?0:(U.error[je]??0)/qn;U.error[je]=(Xt[je]-dn)*_n,U.prev[je]!==void 0&&(U.prev[je]=gt[je])}return y.fields.map((je,dn)=>Ed.includes(je)?Ro[je]:k[dn]??0)},Lc=y=>{let E=N?.entity===y?N.predicted:null;if(!E||!E.fields.includes("yaw"))return;let k=Bi(E.reconciler),V=k?.local.yaw;if(!k||typeof V!="number")return;let H=V+(k.error.yaw??0),U=k.prev.yaw??H;return U+ps(H-U)*k.renderAlpha()},Le=IS(),Lr=Number.NaN,ji=y=>{let E=a.stepMs??0,k=o().get(t.sessionId);DS(Le,k?.inStarve,k?.inBuf,E,d());let V=Number.isNaN(Lr)?0:y-Lr;return Lr=y,NS(Le,V,E)},ln,Fc=y=>{let E=a.stepMs;if(!E)return 0;if(ln===void 0)return ln=y,0;let k=Math.floor((y-ln)/E);return k>pE?(ln=y,pE):(ln+=k*E,k)},Sn=()=>Mi(r.tick??0,f(),0),wo=null,xo=y=>{if(!z)return v.inputsDropped+=y,0;let E=0,k=cS((wo??Sn())+a.sentCount+1);for(let V=0;V<y;V++){let H=Ii({...R});Object.assign(a.data,H),a.data.tick=k;let U=a.send();if(U===0){v.inputsDropped++;continue}E++,c.sent(U,k,H)}return c.flush(),v.inputsSent+=E,E},lt=t.clock,kd=()=>lt.lastServerTime()>0?lt.lastServerTime():performance.now(),Ss=()=>lt.lastServerTime()>0?lt.serverNow()-i-lt.smoothedRtt()/2:performance.now()-i,_t=new WeakMap,So=y=>({x:y.x,y:y.y,z:y.z,yaw:y.yaw,pitch:ce(y.pitch,0),duck:ce(y.duck,0)}),qi=y=>{let E=kd(),k=_t.get(y);if(k===void 0){_t.set(y,{at:E,epoch:y.epoch,pose:So(y),respawns:[]});return}k.epoch!==y.epoch&&y.owner!==t.sessionId&&k.respawns.push({from:k.at,at:E,epoch:k.epoch,pose:k.pose}),k.at=E,k.epoch=y.epoch,k.pose=So(y)},Pd=y=>{let E=_t.get(y)?.respawns;if(E===void 0||E.length===0)return;let k=Ss();for(;E.length>0&&k>=E[0].at;)E.shift();return E[0]},Gi=new gd,En=new Set,Eo={text:"",k:1},Ad=y=>(Eo.text!==y&&(Eo={text:y,k:Ec(y)?.keyframeTicks??1}),Eo.k),_o={text:"\0",desc:null},Wi=()=>{let y=r.physDesc??"";return _o.text!==y&&(_o={text:y,desc:Ec(y)}),_o.desc},Es=()=>e.remoteSamples!=="patch"&&(r.physDesc??"")!=="",w=()=>{if(En.size===0)return;let y=r.tick??0;if(Es()&&y===(r.keyframe??-1)){let k=Gl(y,Z(),F()),V=1e3/F()*Ad(r.physDesc??"");for(let H of En)Gi.push(H,k,So(H),V,H.epoch)}En.clear()},T=La(t);T(r).entities.onAdd(y=>{Y=!0,qi(y),En.add(y),T(y).onChange(()=>{qi(y),En.add(y)})}),t.onStateChange(w),T(r).entities.onRemove(()=>{Y=!0});let F=()=>a.stepMs?Math.round(1e3/a.stepMs):rs.TICK_HZ,Z=()=>r.tickOrigin??0,_e=()=>nh(lt.serverNow(),Z(),F()),de=y=>({x:y.x,y:y.y,z:y.z,vx:y.vx,vy:y.vy,vz:y.vz,g:y.g??0,t0:y.t0??0}),Pe=y=>Gl(y.t0??0,Z(),F()),re=S.spawns("entities",{owned:y=>Cr(y)&&y.src===t.sessionId,correlate:(y,E)=>s().get(y.id)!==E?!1:(Je.delete(y),v.projectilesConfirmed++,v.lastProjectileLeadMs=Pe(E)-y.at,!0),spawnTime:Pe,ttl:y=>{let E=Math.max(2*y,hE);if(!z)return E;let k=performance.now(),V=k-Me.endedAt<E+Me.ms?Me.ms:0;return E+Math.max(k-Oe,V)},onReject:y=>{Je.delete(y),v.projectilesRejected++}}),Oe=performance.now(),Me={ms:0,endedAt:0},Je=new Map,Yt=()=>{if(Je.size===0)return;let y=c.ack();for(let[E,k]of Je)E.epoch!==a.epoch||E.seq>y||s().has(E.id)||(Je.delete(E),k(),v.projectilesRejected++)},$e=!1,_s=()=>{$e=!1;for(let[y,E]of Je)y.epoch!==a.epoch&&(Je.delete(y),E(),v.projectilesRejected++)};t.onStateChange(()=>{let y=performance.now();(y-Oe>Me.ms||y-Me.endedAt>hE+Me.ms)&&(Me={ms:y-Oe,endedAt:y}),Oe=y,$e&&_s(),Yt()});let Ct=new Map,Rt=()=>{let y=ce(r.lengthUnit,0);return{tickHz:F(),tickOrigin:Z(),lengthUnit:y>0?y:1}},Fr=y=>({x:y.x,y:y.y,z:y.z,qx:ce(y.qx,0),qy:ce(y.qy,0),qz:ce(y.qz,0),qw:ce(y.qw,0),lvx:ce(y.lvx,0),lvy:ce(y.lvy,0),lvz:ce(y.lvz,0),avx:ce(y.avx,0),avy:ce(y.avy,0),avz:ce(y.avz,0),sleep:y.sleep===!0,epoch:y.epoch}),zc=()=>{let y=r.bodies;for(let[H,U]of Ct)y?.get(H)!==U.descriptor&&Ct.delete(H);if(y===void 0||y.size===0)return;let E=lt.serverNow(),k=Rt(),V=r.tick??0;for(let[H,U]of y){let te=s().get(H);if(te===void 0)continue;let ee=Ct.get(H),K=Cw(Fr(te),V);if(ee!==void 0&&Dw(ee.last,K)){ee.entity=te;continue}let{drawing:me,snap:ie}=Iw(ee?.drawing??null,K,E,k);v.bodyStates++,ie!==null?v.bodySnaps++:v.peakBodyCorrection=Math.max(v.peakBodyCorrection,Math.hypot(...me.dp)),Ct.set(H,{descriptor:U,entity:te,last:K,drawing:me,handoff:ee?.handoff??new sd})}};t.onStateChange(zc);let pr=SS({enabled:xE(e),loadCore:e.physicsCore,state:r,sessionId:t.sessionId,staticWorld:()=>A,tickHz:F,sent:()=>a.sentCount,acked:()=>f(),ownId:()=>N?.id,ownPath:go,bodyRule:e.bodyRule,headSlide:()=>{let y=ye()?.policy;return y?.headFriction===no.Slide?y.propSlide:null},kinematicRule:e.kinematicRule,lifts:()=>{let y=Wt();return y===null||y.policy.platforms.length===0?null:{policy:y.policy,starts:Et()}},seatRule:e.seatRule,budgetMs:Yx(e.physicsBudgetMs,qO()),contactPass:y=>ye()?.pass(y),motionKnown:y=>c.motionKnown(y),...typeof e.physicsClock=="function"?{clock:e.physicsClock}:{},...hs===null?{}:{seatPose:(y,E)=>{let k=ms()?.poseAt(y,E);return k===void 0?void 0:{key:y,x:k.x,y:k.y,z:k.z,vx:k.vx,vy:k.vy,vz:k.vz}}},remoteStep:()=>{let y=Di(r.preset??"");if(y===null)return;let{step:E}=Vh(y,A);return(k,V,H,U)=>Hi(E,k,Ii({...V}),H,U)}});t.onStateChange(()=>pr.onState(lt.serverNow()));let Uc=()=>{let y=N?.predicted?.reconciler.state;return y===void 0?void 0:{p:[y.x??0,y.y??0,y.z??0],v:[y.vx??0,y.vy??0,y.vz??0]}},Kh=y=>(!Ct.has(y)&&r.bodies?.has(y)===!0&&zc(),Ct.get(y)),vd=(y,E)=>{let k=Rt(),V=lt.serverNow(),H=pr.draw(y,V),U=E.entity,te=E.descriptor?.kind,ee=H===null&&e.kinematicRule!==void 0?Wx(e.kinematicRule,y,V,k):null,K=E.handoff.draw(H??ee??eh(E.drawing,V,k),H!==null,U.epoch,V,ad(te),k.lengthUnit),[me,ie,fe]=E.last.lv;return{id:y,kind:U.kind,owner:U.owner,x:K.p[0],y:K.p[1],z:K.p[2],yaw:ps(U.yaw),vx:me*k.lengthUnit,vy:ie*k.lengthUnit,vz:fe*k.lengthUnit,hp:U.hp,flags:U.flags,epoch:U.epoch,data:U.data,t0:0,g:0,src:"",pitch:0,duck:0,mstate:0,cap:1,spin:0,fuel:0,body:!0,qx:K.q[0],qy:K.q[1],qz:K.q[2],qw:K.q[3],sleep:E.last.sleep,predicted:H!==null}},Vc={epoch:-1,seq:0,n:0},Rs=y=>typeof y=="number"&&Number.isFinite(y)?Te(Math.fround(y)):0,Xh=y=>{let E=th(y.launch,_e(),F());return{id:y.id,kind:y.kind,owner:"",...E,yaw:0,hp:0,flags:0,epoch:0,data:"",t0:y.launch.t0,g:y.launch.g,src:t.sessionId,pitch:0,duck:0,mstate:0,cap:1,spin:0,fuel:0,...$h}},Jh=()=>{let y=new Map;for(let E of re.entries())E.state==="pending"&&E.local&&y.set(E.local.id,E.local);return y};t.onDrop(y=>{c.dropped(),z=!1,$e=!0,O(_d.Reconnecting,{code:y})}),t.onReconnect(()=>{if(X){t.leave(!0).catch(()=>{});return}(async()=>(await Tl(t,gn.firstStateTimeoutMs),!X&&($e&&_s(),N?.predicted&&(N.predicted.reconciler.reset(),v.reseeds++),ln=void 0,z=!0,O(_d.Reconnected))))()});let Zh=()=>{X=!0,z=!1,c.dispose(),he(),S.dispose(),pr.dispose()};t.onLeave(y=>{X||(Zh(),O(_d.Disconnect,y))}),t.onMessage("*",(y,E)=>{typeof y=="string"&&(e.onEvent?.(y,E),$O.has(y)||O(y,E))});let PE=y=>{if(!N?.reseeded||N.entity!==y||!N.predicted)return;let E=N.predicted.reconciler.state;return{x:E.x??y.x,y:E.y??y.y,z:E.z??y.z,yaw:E.yaw??y.yaw,pitch:E.pitch??ce(y.pitch,0),duck:E.duck??ce(y.duck,0),epoch:y.epoch}},AE=()=>{if(N===null||N.predicted===null)return null;let y=im(N.entity);return{id:N.id,x:y.x,y:y.y,z:y.z,vx:0,vy:0,vz:0,yaw:y.yaw}},Qh=y=>{let k=N?.reseeded===!0&&N.predicted===y?1:Bi(y.reconciler)?.renderAlpha()??1;return Math.max(0,a.sentCount-f()-1+k)},Hc=new Map,Kt=0,em=()=>ue()&&Li()!==an.Timeline,Td=y=>N?.entity!==y&&y.owner!==""&&!Cr(y)&&o().has(y.owner),vE=(y,E)=>{let k=Hc.get(y);return k!==void 0&&k.lives===E&&Kt-k.at<=zO?k:void 0},$c=new Map,Md,jc=new Map,Cd=Number.NaN,Yi={tick:Number.NaN,leadMs:Number.NaN},TE=()=>{let y=ce(r.lengthUnit,0);return y>0?y:_w[Di(r.preset??"")?.name??""]??1},ME=()=>{let y=Fi(),E=y?.current??null;if(y===null||E===null||N===null||N.predicted===null)return Yi={tick:Number.NaN,leadMs:Number.NaN},null;let k=f(),V=Qh(N.predicted),H=BS(k,V,Le,a.stepMs??0,Kt);Md=yS(Md,H.raw,H.at,F());let U=Md.seq,te=k+V,ee=Number.isNaN(Cd)?0:Kt-Cd;Cd=Kt;let K=E.stateTick+(U-E.ack);Yi={tick:K,leadMs:Gl(K+1,Z(),F())-lt.serverNow()};let me=mt.SEAT_SNAP_METRES*TE(),ie=new Map;for(let[fe,dt]of s()){if(!Td(dt))continue;let Xt=y.motionAt(fe,U);if(Xt===void 0)continue;let gt=Xt.pose,Ro=$c.get(fe),je=Ro?.pass!=null&&Ro.pass!==E?y.changeAt(fe,U,Ro.pass):void 0,dn=wS(Ro,E,dt.epoch,je,Xt,ee,y.touchingAt(fe,U),me,y.stateRate(fe));$c.set(fe,dn);let qn={x:gt.x+dn.dx,y:gt.y+dn.dy,z:gt.z+dn.dz,yaw:gt.yaw+dn.dyaw,pitch:ce(dt.pitch,0),duck:ce(dt.duck,0),epoch:dt.epoch},_n=gS(jc.get(fe),y.touchAheadMs(fe,te)!==void 0,ee);jc.set(fe,_n);let Ki=_n>0?y.motionAt(fe,te)?.pose:void 0;Ki!==void 0&&(qn.x+=(Ki.x-gt.x)*_n,qn.y+=(Ki.y-gt.y)*_n,qn.z+=(Ki.z-gt.z)*_n,qn.yaw+=ps(Ki.yaw-gt.yaw)*_n),ie.set(fe,{pose:qn,at:gt})}for(let fe of[...$c.keys()])ie.has(fe)||$c.delete(fe);for(let fe of[...jc.keys()])ie.has(fe)||jc.delete(fe);return ie},CE=y=>{if(!ue())return;let E=e.contacts===void 0?ye():null;return E===null||y===null?yt:E.drawRule(y.id)},OE=()=>{let y=new Map,E=em()?AE():null,k=CE(E);if(k===void 0||E===null||N===null||N.predicted===null)return Hc.clear(),Yi={tick:Number.NaN,leadMs:Number.NaN},y;let V=Fi()===null?null:ME(),H=[];for(let[K,me]of s()){if(!Td(me))continue;let ie=V?.get(K)?.pose??Gc(me);y.set(K,ie),H.push({id:K,x:ie.x,y:ie.y,z:ie.z,vx:0,vy:0,vz:0,yaw:ie.yaw,...ye()===null?{}:{flags:ce(me.flags,0)}})}let U=new Map;for(let[K,me]of y)U.set(K,`${N.entity.epoch}/${me.epoch}`);for(let[K,me]of y)for(let[ie,fe]of y)K<ie&&U.set(kc(K,ie),`${me.epoch}/${fe.epoch}`);let te=new Map;for(let[K,me]of U){let ie=vE(K,me);ie!==void 0&&te.set(K,ie)}let ee=iS(k,E,H,te,Kt);Hc.clear();for(let[K,me]of ee.sides)Hc.set(K,{...me,lives:U.get(K)??""});for(let[K,me]of ee.drawn){let ie=y.get(K);if(ie===void 0)continue;let fe=V?.get(K)?.at,dt=fe===void 0?void 0:Math.hypot(me.x-fe.x,me.y-fe.y,me.z-fe.z);y.set(K,{...ie,x:me.x,y:me.y,z:me.z,...dt===void 0?{}:{correction:dt}})}return IE(y,E),y},qc=new Map,IE=(y,E)=>{let k=N?.entity;for(let[V,H]of y){let U=s().get(V),te=V===bs&&k!==void 0&&U!==void 0,ee=te?[E.x-(k.x-U.x)-H.x,E.y-(k.y-U.y)-H.y,E.z-(k.z-U.z)-H.z,0]:[0,0,0,0],K=qc.get(V),me=K===void 0?0:Math.exp(-Math.max(0,Kt-K.at)/dE),ie=fE(K,te?1:0,ee,me);qc.set(V,{k:te?1:0,shift:ee,err:ie,at:Kt}),!(!te&&ie.every(fe=>Math.abs(fe)<LO))&&y.set(V,{...H,x:H.x+ee[0]+ie[0],y:H.y+ee[1]+ie[1],z:H.z+ee[2]+ie[2]})}for(let V of[...qc.keys()])y.has(V)||qc.delete(V)},Od=0;t.onStateChange(()=>{Od++});let tm,nm=()=>{let y=tm;if(y!==void 0&&y.at===Kt&&y.states===Od)return y.seats;let E=OE();return tm={at:Kt,states:Od,seats:E},E},Id=null,rm=()=>N?.predicted?(Number.isNaN(tt)?(r.tick??0)-f():tt)+f()+Qh(N.predicted)+1:sm(),sm=()=>(Ss()-Z())*F()/1e3,om=new WeakMap,DE=(y,E)=>{let k=Wt();if(k===null||k.policy.platforms.length===0||!N?.predicted)return E;let V=sm(),H=rm(),U=Et(),te=(r.tick??0)+1,ee=wc(k,{x:y.x,y:y.y,z:y.z,duck:ce(y.duck,0)},te,U),K=ee<0?E:{...E,...mh(k.policy,ee,E,V,H,U)};ee>=0&&(K.z=yh(k.policy,ee,H,U)+(y.z-yh(k.policy,ee,te,U)));let me=[K.x-E.x,K.y-E.y,K.z-E.z,K.yaw-E.yaw],ie=om.get(y),fe=Kt,dt=ie===void 0?0:Math.max(0,fe-ie.at),Xt=Math.exp(-dt/dE),gt=fE(ie,ee,me,Xt);return om.set(y,{k:ee,shift:me,err:gt,at:fe}),{...E,x:K.x+gt[0],y:K.y+gt[1],z:K.z+gt[2],yaw:K.yaw+gt[3]}},Dd=null,BE=y=>{let E=Gc(y.entity);fr(y);let k=Gc(y.entity);Dd={dx:E.x-k.x,dy:E.y-k.y,dz:E.z-k.z,at:Kt}},Gc=y=>{let E=NE(y),k=N?.entity===y?Dd:null;if(k===null)return E;let V=bS(k,Kt-k.at);return V.done?(Dd=null,E):{...E,x:E.x+V.dx,y:E.y+V.dy,z:E.z+V.dz}},NE=y=>{let E=PE(y);if(E)return E;let k=Pd(y),V=S.value(y,"yaw"),U=(N?.entity!==y&&Es()?Gi.at(y,Ss()):void 0)??{x:S.value(y,"x"),y:S.value(y,"y"),z:S.value(y,"z"),yaw:Lc(y)??V,pitch:ce(S.value(y,"pitch"),ce(y.pitch,0)),duck:ce(S.value(y,"duck"),ce(y.duck,0))};return k===void 0?{...N?.entity===y?U:DE(y,U),epoch:y.epoch}:{...Ss()>k.from?k.pose:U,epoch:k.epoch}},im=(y,E,k)=>(E!==void 0&&em()&&Td(y)?(k??nm()).get(E):void 0)??Gc(y),LE=(y,E)=>{let k=re.entryFor(E),V=k?.local!==void 0&&E.src===t.sessionId?k.leadMs*F()/1e3:0,H=th(de(E),_e()+V,F());return{id:y,kind:E.kind,owner:E.owner,...H,yaw:ps(E.yaw),hp:E.hp,flags:E.flags,epoch:E.epoch,data:E.data,t0:E.t0,g:E.g,src:E.src,pitch:ce(E.pitch,0),duck:ce(E.duck,0),mstate:ce(E.mstate,0),cap:ce(E.cap,1),spin:ce(E.spin,0),fuel:ce(E.fuel,0),...$h}},Bd={text:"",limit:Math.PI},FE=()=>{let y=r.preset??"";if(Bd.text!==y){let E=Di(y)?.params.pitchLimit;Bd={text:y,limit:E===void 0?Math.PI:Math.fround(E)}}return Bd.limit},zE=y=>{let E=FE(),k=ps(y);return k<-E?-E:k>E?E:k},Nd=(y,E,k)=>N?.entity===y&&N.predicted?.fields.includes(E)?ce(N.predicted.reconciler.state[E],k):ce(y[E],k),Ld=(y,E,k)=>{let V=Kh(y);if(V!==void 0)return vd(y,V);if(Cr(E))return LE(y,E);let H=im(E,y,k);return{id:y,kind:E.kind,owner:E.owner,x:H.x,y:H.y,z:H.z,yaw:ps(H.yaw),vx:E.vx,vy:E.vy,vz:E.vz,hp:E.hp,flags:E.flags,epoch:H.epoch,data:E.data,t0:E.t0??0,g:E.g??0,src:E.src??"",pitch:zE(H.pitch),duck:H.duck<0?0:H.duck>1?1:H.duck,mstate:Nd(E,"mstate",0),cap:ce(E.cap,1),spin:Nd(E,"spin",0),fuel:Nd(E,"fuel",0),...$h,...H.correction===void 0?{}:{predicted:!0,correction:H.correction}}};return{id:t.sessionId,url:n,input:R,frame(y=performance.now()){if(X)return 0;Kt=y,c.poll(),pr.settle(),jn();let E=N?.predicted??null,k=E?xs(E):[],V=E?bo(E):null,H=E?Bc(E):null,U=E?.reconciler.reconcileSeq??0,te=ji(y),ee=S.tick(y)+te;if(!E){let me=xo(Fc(y)+te);return pr.afterSend(void 0,lt.serverNow()),wo=Sn(),me}ln=void 0,nt(E,Nc(E,U,k,H),U),Dc(E,U,V);let K=xo(ee);return pr.afterSend(Uc(),lt.serverNow()),wo=Sn(),K>0&&N&&(N.reseeded=!1),(hs?.takeMissed()??[]).length>0&&N!==null&&BE(N),K},me(){return X||jn(),N?Ld(N.id,N.entity):void 0},setWorld(y){let E=eo(y),k=E.hash!==A.hash;return A=E,k&&N&&!X&&fr(N),A.hash},setPhysics(y){if(typeof y!="string")throw new TypeError("setPhysics: the hash is a string (the world's physicsHash)");return $=y,$},get physics(){let y=r.physics??"",E=y!==""&&y!==$;return E&&j!==`${y}/${$}`&&(j=`${y}/${$}`,console.warn(`[multiplayer] the room's physics world (hash ${y}) is not this client's (hash ${$||"none"}): your copy is never stepped from the room's state. Pass your world's physicsHash to session.setPhysics().`)),{reason:E?"physics_mismatch":"",physics:$,roomPhysics:y}},get physicsPrediction(){return pr.status},drawTick(){return Yi.tick},drawLead(){return Yi.leadMs},liftPose(y){let E=Wt();return E===null?void 0:Tx(E.policy,y,rm(),Et())},viewCarry(){let y=Wt(),E=N?.predicted?N.predicted.reconciler.state:void 0;if(y===null||E===void 0)return Id=null,0;let k=Mi(r.tick??0,f(),a.sentCount)+1,V=wc(y,{x:E.x??0,y:E.y??0,z:E.z??0,duck:E.duck??0},k,Et()),H=y.policy.platforms[V],U=Id;return Id=H===void 0?null:{k:V,tick:k},H===void 0||U===null||U.k!==V?0:hh(H)*(k-U.tick)},get prediction(){X||jn();let y=N?.predicted!=null,E=y?"":N?W:e.predict===!1?"off":"no_entity";return{predicting:y,reason:E,world:A.hash,roomWorld:Hh(Di(r.preset??""))}},predictProjectile(y){if(!z)return"";let E=a.sentCount+1;(Vc.epoch!==a.epoch||Vc.seq!==E)&&(Vc={epoch:a.epoch,seq:E,n:0});let k=o().get(t.sessionId)?.seqBase??0,V=`${t.sessionId}.${k+E}.${Vc.n++}`,H=lt.serverNow(),U=Rs(y.g),te={x:Rs(y.x),y:Rs(y.y),z:Rs(y.z),vx:Rs(y.vx),vy:Rs(y.vy),vz:Rs(y.vz),g:U<0?0:U>ic?ic:U,t0:nh(H,Z(),F())},ee={id:V,kind:String(y.kind),launch:te,at:H,seq:E,epoch:a.epoch},K=re.spawn(ee);return Je.set(ee,()=>K.cancel()),v.projectilesPredicted++,V},entity(y){let E=s().get(y);if(E)return Ld(y,E);let k=Kh(y);if(k!==void 0)return vd(y,k);let V=Jh().get(y);return V?Xh(V):void 0},entities(){let y=new Map,E=nm();for(let[k,V]of s())y.set(k,Ld(k,V,E));for(let[k,V]of Ct)y.has(k)||y.set(k,vd(k,V));for(let[k,V]of Jh())y.has(k)||y.set(k,Xh(V));return y},players(){let y=new Map;for(let[E,k]of o())y.set(E,{id:E,name:k.name,uid:k.uid,team:k.team,connected:k.connected,avatarUrl:k.avatarUrl});return y},get tick(){return r.tick??0},get connected(){return z},telemetry:v,fast:c.status,on(y,E){let k=M.get(y)??new Set;M.set(y,k);let V=E;return k.add(V),()=>{k.delete(V)}},async leave(){X||(Zh(),t.reconnection.enabled=!1,await t.leave(!0))}}}var ZO=3,EE={ready:t=>ra.ready(t),auth:()=>du(),urls:()=>Ym(),regions:()=>Km()},Mc=EE;function QO(t){Mc=t??EE}var _E;function eI(t){_E=t??void 0}var tI=rs.MAX_REWIND_MS,nI=5,rI=3e4,sI=["moveX","moveY","moveZ","yaw","pitch","buttons"],Ni=t=>typeof t=="number"&&Number.isFinite(t);function oI(t){return!Array.isArray(t)||t.length>nI?void 0:t.every(n=>Ni(n)&&n>=0&&n<=rI)?t:void 0}function iI(t){let e=Wn(t,"options"),n=typeof e.gameId=="string"?e.gameId:"";if(!n)throw new TypeError("genex bridge: `gameId` (the game slug) is required");let r=e.renderDelayMs,s=Ni(r)&&r>=0&&r<=tI;return{gameId:n,name:typeof e.name=="string"&&e.name?e.name:void 0,urls:Array.isArray(e.urls)?e.urls.filter(o=>typeof o=="string"&&o!==""):[],predict:e.predict!==!1,predictPhysics:e.predictPhysics!==!1,renderDelayMs:s?r:void 0,capacityRetryMs:oI(e.capacityRetryMs)}}var Gh=new Map,aI=2**30,cI=aI,Cc=t=>typeof t=="number"?Gh.get(t):void 0,po=t=>{let e=Cc(t);return e&&!e.closed?e.session:null};function Wh(t){t.closed=!0;for(let e of t.unwire.splice(0))e();t.session=null}function uI(t,e,n){ns(e)?e===xe.SERVER_RESTART&&pe(t,{type:"serverRestart"}):pe(t,{type:"message",kind:e,data:n??null})}async function lI(t){let e=t.opts;if(await Mc.ready(e.gameId),t.closed)return;let n=e.urls.length?e.urls:Mc.urls(),r=e.urls.length?[]:Mc.regions?.()??[];if(!n.length&&!r.length)throw Object.assign(new Error("genex bridge: no authority server URL (pass urls, or run on a Genex page that serves authority rooms)"),{code:0});let s=await SE({urls:n,regions:r,room:e.gameId,name:e.name,auth:()=>Mc.auth(),predict:e.predict?void 0:!1,physicsCore:_E,predictPhysics:e.predictPhysics,renderDelayMs:e.renderDelayMs,capacityRetryMs:e.capacityRetryMs,onEvent:(o,i)=>{t.closed||uI(t,o,i)}});if(t.closed){await s.leave();return}t.session=s,t.sessionId=s.id,t.world&&s.setWorld(t.world),t.unwire.push(s.on("reconnecting",({code:o})=>pe(t,{type:"reconnecting",code:o})),s.on("reconnected",()=>pe(t,{type:"reconnected"})),s.on("disconnect",o=>{Wh(t),pe(t,{type:"disconnected",code:o,reason:""})})),pe(t,{type:"joined",sessionId:s.id})}function dI(t){let e=iI(t),n=++cI,r={opts:e,q:[],overflowed:!1,session:null,unwire:[],roster:new Set,sessionId:"",closed:!1,world:null};return Gh.set(n,r),lI(r).catch(s=>{r.closed||(Wh(r),pe(r,{type:"joinFailed",code:No(s),message:Gn(s)}))}),n}function fI(t,e){let n=Wn(e,"input"),r=po(t);if(!r)return!1;for(let s of sI){let o=n[s];Ni(o)&&(r.input[s]=o)}return!0}function pI(t,e){let n=Wn(e,"projectile"),r=po(t);if(!r)return"";let s=o=>Ni(o)?o:0;return r.predictProjectile({kind:typeof n.kind=="string"?n.kind:"",x:s(n.x),y:s(n.y),z:s(n.z),vx:s(n.vx),vy:s(n.vy),vz:s(n.vz),...Ni(n.g)?{g:n.g}:{}})}function hI(t,e){let n=Wn(e,"world"),r=Cc(t);if(!r||r.closed)return!1;let s;try{s=eo(n)}catch(o){return pe(r,Bo(Gn(o))),!1}return r.world=s,r.session?.setWorld(s),!0}var mI=JSON.stringify({tick:0,sent:0,connected:!1,me:null,entities:[]});function yI(t,e){let n=po(t);if(!n)return mI;let r=n.frame(Ni(e)?e:performance.now());return JSON.stringify({tick:n.tick,sent:r,connected:n.connected,me:n.me()??null,entities:[...n.entities().values()]})}var jh=8,qh={PREDICTED:1,ASLEEP:2},gI=new Float32Array(0);function RE(t){return[...t.entities().values()].filter(e=>e.body).sort((e,n)=>e.id<n.id?-1:e.id>n.id?1:0)}function bI(t){let e=po(t);if(!e)return gI;let n=RE(e),r=new Float32Array(n.length*jh);return n.forEach((s,o)=>{let i=o*jh;r.set([s.x,s.y,s.z,s.qx,s.qy,s.qz,s.qw],i),r[i+7]=(s.predicted?qh.PREDICTED:0)|(s.sleep?qh.ASLEEP:0)}),r}function wI(t){let e=po(t);return JSON.stringify(e?RE(e).map(n=>n.id):[])}function xI(t){let e=Cc(t),n=po(t);return JSON.stringify({sessionId:e?.sessionId??"",connected:!!n&&n.connected,closed:!e||e.closed,tick:n?.tick??0,queued:e?.q.length??0,players:n?[...n.players().values()]:[],telemetry:n?{...n.telemetry}:null,prediction:n?n.prediction:null,physicsPrediction:n?n.physicsPrediction:null})}function SI(t,e){let n=new Set(e.players().keys());for(let r of n)t.roster.has(r)||pe(t,{type:"playerJoined",id:r});for(let r of t.roster)n.has(r)||pe(t,{type:"playerLeft",id:r});t.roster=n}function EI(t){let e=Cc(t);if(!e)return"[]";try{let n=po(t);n&&SI(e,n)}catch(n){pe(e,Bo(Gn(n)))}return mu(e)}function kE(t){let e=Cc(t);if(!e||e.closed)return;let n=e.session;Wh(e),n?.leave().catch(()=>{}),pe(e,{type:"disconnected",code:Xa.CONSENTED,reason:"left"})}function _I(t){kE(t),typeof t=="number"&&Gh.delete(t)}var RI=Object.freeze({...Bp,...Yh,initEmbed:lu});globalThis.GenexMultiplayerBridge=RI;})();