hytopia 0.7.6 → 0.7.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bun-server.mjs +4 -4
- package/docs/server.chunklatticeevent.md +14 -0
- package/docs/server.chunklatticeeventpayloads._chunk_lattice.add_chunk_.md +16 -0
- package/docs/server.chunklatticeeventpayloads.md +19 -0
- package/node-server.mjs +3 -3
- package/package.json +1 -1
- package/server.api.json +75 -0
- package/server.d.ts +6 -0
package/node-server.mjs
CHANGED
|
@@ -412,7 +412,7 @@ Instead, \`yield\` should either be called with a value, or not be called at all
|
|
|
412
412
|
if (condition) { yield value; }`)};import{Buffer as EL1}from"node:buffer";import{StringDecoder as kL1}from"node:string_decoder";var VB=(Z,J,X)=>{if(X)return;if(Z)return{transform:IL1.bind(void 0,new TextEncoder)};let Y=new kL1(J);return{transform:_L1.bind(void 0,Y),final:SL1.bind(void 0,Y)}},IL1=function*(Z,J){if(EL1.isBuffer(J))yield MZ(J);else if(typeof J==="string")yield Z.encode(J);else yield J},_L1=function*(Z,J){yield d8(J)?Z.write(J):J},SL1=function*(Z){let J=Z.end();if(J!=="")yield J};import{callbackify as Wp}from"node:util";var oD=Wp(async(Z,J,X,Y)=>{J.currentIterable=Z(...X);try{for await(let $ of J.currentIterable)Y.push($)}finally{delete J.currentIterable}}),zB=async function*(Z,J,X){if(X===J.length){yield Z;return}let{transform:Y=AL1}=J[X];for await(let $ of Y(Z))yield*zB($,J,X+1)},Hp=async function*(Z){for(let[J,{final:X}]of Object.entries(Z))yield*vL1(X,Number(J),Z)},vL1=async function*(Z,J,X){if(Z===void 0)return;for await(let Y of Z())yield*zB(Y,X,J+1)},Vp=Wp(async({currentIterable:Z},J)=>{if(Z!==void 0){await(J?Z.throw(J):Z.return());return}if(J)throw J}),AL1=function*(Z){yield Z};var rD=(Z,J,X,Y)=>{try{for(let $ of Z(...J))X.push($);Y()}catch($){Y($)}},zp=(Z,J)=>[...J.flatMap((X)=>[...dY(X,Z,0)]),...LH(Z)],dY=function*(Z,J,X){if(X===J.length){yield Z;return}let{transform:Y=hL1}=J[X];for(let $ of Y(Z))yield*dY($,J,X+1)},LH=function*(Z){for(let[J,{final:X}]of Object.entries(Z))yield*xL1(X,Number(J),Z)},xL1=function*(Z,J,X){if(Z===void 0)return;for(let Y of Z())yield*dY(Y,X,J+1)},hL1=function*(Z){yield Z};var tD=({value:Z,value:{transform:J,final:X,writableObjectMode:Y,readableObjectMode:$},optionName:Q},{encoding:K})=>{let G={},W=qp(Z,K,Q),H=uY(J),V=uY(X),F=H?oD.bind(void 0,zB,G):rD.bind(void 0,dY),z=H||V?oD.bind(void 0,Hp,G):rD.bind(void 0,LH),q=H||V?Vp.bind(void 0,G):void 0;return{stream:new fL1({writableObjectMode:Y,writableHighWaterMark:Fp(Y),readableObjectMode:$,readableHighWaterMark:Fp($),transform(B,L,w){F([B,W,0],this,w)},flush(B){z([W],this,B)},destroy:q})}},FB=(Z,J,X,Y)=>{let $=J.filter(({type:K})=>K==="generator"),Q=Y?$.reverse():$;for(let{value:K,optionName:G}of Q){let W=qp(K,X,G);Z=zp(W,Z)}return Z},qp=({transform:Z,final:J,binary:X,writableObjectMode:Y,readableObjectMode:$,preserveNewlines:Q},K,G)=>{let W={};return[{transform:Qp(Y,G)},VB(X,K,Y),HB(X,Q,Y,W),{transform:Z,final:J},{transform:Kp($,G)},$p({binary:X,preserveNewlines:Q,readableObjectMode:$,state:W})].filter(Boolean)};var Up=(Z,J)=>{for(let X of yL1(Z))bL1(Z,X,J)},yL1=(Z)=>new Set(Object.entries(Z).filter(([,{direction:J}])=>J==="input").map(([J])=>Number(J))),bL1=(Z,J,X)=>{let{stdioItems:Y}=Z[J],$=Y.filter(({contents:G})=>G!==void 0);if($.length===0)return;if(J!==0){let[{type:G,optionName:W}]=$;throw new TypeError(`Only the \`stdin\` option, not \`${W}\`, can be ${mJ[G]} with synchronous methods.`)}let K=$.map(({contents:G})=>G).map((G)=>gL1(G,Y));X.input=GH(K)},gL1=(Z,J)=>{let X=FB(Z,J,"utf8",!0);return mL1(X),GH(X)},mL1=(Z)=>{let J=Z.find((X)=>typeof X!=="string"&&!d8(X));if(J!==void 0)throw new TypeError(`The \`stdin\` option is invalid: when passing objects as input, a transform must be used to serialize them to strings or Uint8Arrays: ${J}.`)};import{writeFileSync as lL1,appendFileSync as pL1}from"node:fs";var qB=({stdioItems:Z,encoding:J,verboseInfo:X,fdNumber:Y})=>Y!=="all"&&TK(X,Y)&&!r5.has(J)&&uL1(Y)&&(Z.some(({type:$,value:Q})=>$==="native"&&dL1.has(Q))||Z.every(({type:$})=>S9.has($))),uL1=(Z)=>Z===1||Z===2,dL1=new Set(["pipe","overlapped"]),Lp=async(Z,J,X,Y)=>{for await(let $ of Z)if(!cL1(J))wp($,X,Y)},Bp=(Z,J,X)=>{for(let Y of Z)wp(Y,J,X)},cL1=(Z)=>Z._readableState.pipes.length>0,wp=(Z,J,X)=>{let Y=DL(Z);B7({type:"output",verboseMessage:Y,fdNumber:J,verboseInfo:X})};var jp=({fileDescriptors:Z,syncResult:{output:J},options:X,isMaxBuffer:Y,verboseInfo:$})=>{if(J===null)return{output:Array.from({length:3})};let Q={},K=new Set([]);return{output:J.map((W,H)=>iL1({result:W,fileDescriptors:Z,fdNumber:H,state:Q,outputFiles:K,isMaxBuffer:Y,verboseInfo:$},X)),...Q}},iL1=({result:Z,fileDescriptors:J,fdNumber:X,state:Y,outputFiles:$,isMaxBuffer:Q,verboseInfo:K},{buffer:G,encoding:W,lines:H,stripFinalNewline:V,maxBuffer:F})=>{if(Z===null)return;let z=Ol(Z,Q,F),q=MZ(z),{stdioItems:U,objectMode:B}=J[X],L=nL1([q],U,W,Y),{serializedResult:w,finalResult:O=w}=aL1({chunks:L,objectMode:B,encoding:W,lines:H,stripFinalNewline:V,fdNumber:X});sL1({serializedResult:w,fdNumber:X,state:Y,verboseInfo:K,encoding:W,stdioItems:U,objectMode:B});let M=G[X]?O:void 0;try{if(Y.error===void 0)oL1(w,U,$);return M}catch(R){return Y.error=R,M}},nL1=(Z,J,X,Y)=>{try{return FB(Z,J,X,!1)}catch($){return Y.error=$,Z}},aL1=({chunks:Z,objectMode:J,encoding:X,lines:Y,stripFinalNewline:$,fdNumber:Q})=>{if(J)return{serializedResult:Z};if(X==="buffer")return{serializedResult:GH(Z)};let K=Au(Z,X);if(Y[Q])return{serializedResult:K,finalResult:sD(K,!$[Q],J)};return{serializedResult:K}},sL1=({serializedResult:Z,fdNumber:J,state:X,verboseInfo:Y,encoding:$,stdioItems:Q,objectMode:K})=>{if(!qB({stdioItems:Q,encoding:$,verboseInfo:Y,fdNumber:J}))return;let G=sD(Z,!1,K);try{Bp(G,J,Y)}catch(W){X.error??=W}},oL1=(Z,J,X)=>{for(let{path:Y,append:$}of J.filter(({type:Q})=>GB.has(Q))){let Q=typeof Y==="string"?Y:Y.toString();if($||X.has(Q))pL1(Y,Z);else X.add(Q),lL1(Y,Z)}};var Op=([,Z,J],X)=>{if(!X.all)return;if(Z===void 0)return J;if(J===void 0)return Z;if(Array.isArray(Z))return Array.isArray(J)?[...Z,...J]:[...Z,DZ(J,X,"all")];if(Array.isArray(J))return[DZ(Z,X,"all"),...J];if(d8(Z)&&d8(J))return $D([Z,J]);return`${Z}${J}`};import{once as eD}from"node:events";var Mp=async(Z,J)=>{let[X,Y]=await rL1(Z);return J.isForcefullyTerminated??=!1,[X,Y]},rL1=async(Z)=>{let[J,X]=await Promise.allSettled([eD(Z,"spawn"),eD(Z,"exit")]);if(J.status==="rejected")return[];return X.status==="rejected"?Rp(Z):X.value},Rp=async(Z)=>{try{return await eD(Z,"exit")}catch{return Rp(Z)}},Np=async(Z)=>{let[J,X]=await Z;if(!tL1(J,X)&&ZC(J,X))throw new w7;return[J,X]},tL1=(Z,J)=>Z===void 0&&J===void 0,ZC=(Z,J)=>Z!==0||J!==null;var Pp=({error:Z,status:J,signal:X,output:Y},{maxBuffer:$})=>{let Q=eL1(Z,J,X),K=Q?.code==="ETIMEDOUT",G=jl(Q,Y,$);return{resultError:Q,exitCode:J,signal:X,timedOut:K,isMaxBuffer:G}},eL1=(Z,J,X)=>{if(Z!==void 0)return Z;return ZC(J,X)?new w7:void 0};var Dp=(Z,J,X)=>{let{file:Y,commandArguments:$,command:Q,escapedCommand:K,startTime:G,verboseInfo:W,options:H,fileDescriptors:V}=JB1(Z,J,X),F=$B1({file:Y,commandArguments:$,options:H,command:Q,escapedCommand:K,verboseInfo:W,fileDescriptors:V,startTime:G});return hK(F,W,H)},JB1=(Z,J,X)=>{let{command:Y,escapedCommand:$,startTime:Q,verboseInfo:K}=TL(Z,J,X),G=XB1(X),{file:W,commandArguments:H,options:V}=sL(Z,J,G);YB1(V);let F=Zp(V,K);return{file:W,commandArguments:H,command:Y,escapedCommand:$,startTime:Q,verboseInfo:K,options:V,fileDescriptors:F}},XB1=(Z)=>Z.node&&!Z.ipc?{...Z,ipc:!1}:Z,YB1=({ipc:Z,ipcInput:J,detached:X,cancelSignal:Y})=>{if(J)UB("ipcInput");if(Z)UB("ipc: true");if(X)UB("detached: true");if(Y)UB("cancelSignal")},UB=(Z)=>{throw new TypeError(`The "${Z}" option cannot be used with synchronous methods.`)},$B1=({file:Z,commandArguments:J,options:X,command:Y,escapedCommand:$,verboseInfo:Q,fileDescriptors:K,startTime:G})=>{let W=QB1({file:Z,commandArguments:J,options:X,command:Y,escapedCommand:$,fileDescriptors:K,startTime:G});if(W.failed)return W;let{resultError:H,exitCode:V,signal:F,timedOut:z,isMaxBuffer:q}=Pp(W,X),{output:U,error:B=H}=jp({fileDescriptors:K,syncResult:W,options:X,isMaxBuffer:q,verboseInfo:Q}),L=U.map((O,M)=>DZ(O,X,M)),w=DZ(Op(U,X),X,"all");return GB1({error:B,exitCode:V,signal:F,timedOut:z,isMaxBuffer:q,stdio:L,all:w,options:X,command:Y,escapedCommand:$,startTime:G})},QB1=({file:Z,commandArguments:J,options:X,command:Y,escapedCommand:$,fileDescriptors:Q,startTime:K})=>{try{Up(Q,X);let G=KB1(X);return ZB1(Z,J,G)}catch(G){return xK({error:G,command:Y,escapedCommand:$,fileDescriptors:Q,options:X,startTime:K,isSync:!0})}},KB1=({encoding:Z,maxBuffer:J,...X})=>({...X,encoding:"buffer",maxBuffer:YB(J)}),GB1=({error:Z,exitCode:J,signal:X,timedOut:Y,isMaxBuffer:$,stdio:Q,all:K,options:G,command:W,escapedCommand:H,startTime:V})=>Z===void 0?$B({command:W,escapedCommand:H,stdio:Q,all:K,ipcOutput:[],options:G,startTime:V}):UH({error:Z,command:W,escapedCommand:H,timedOut:Y,isCanceled:!1,isGracefullyCanceled:!1,isMaxBuffer:$,isForcefullyTerminated:!1,exitCode:J,signal:X,stdio:Q,all:K,ipcOutput:[],options:G,startTime:V,isSync:!0});import{setMaxListeners as a21}from"node:events";import{spawn as s21}from"node:child_process";import Ip from"node:process";import{once as JC,on as WB1}from"node:events";var Cp=({anyProcess:Z,channel:J,isSubprocess:X,ipc:Y},{reference:$=!0,filter:Q}={})=>{return IK({methodName:"getOneMessage",isSubprocess:X,ipc:Y,isConnected:cL(Z)}),HB1({anyProcess:Z,channel:J,isSubprocess:X,filter:Q,reference:$})},HB1=async({anyProcess:Z,channel:J,isSubprocess:X,filter:Y,reference:$})=>{gL(J,$);let Q=gJ(Z,J,X),K=new AbortController;try{return await Promise.race([VB1(Q,Y,K),zB1(Q,X,K),FB1(Q,X,K)])}catch(G){throw _K(Z),G}finally{K.abort(),mL(J,$)}},VB1=async(Z,J,{signal:X})=>{if(J===void 0){let[Y]=await JC(Z,"message",{signal:X});return Y}for await(let[Y]of WB1(Z,"message",{signal:X}))if(J(Y))return Y},zB1=async(Z,J,{signal:X})=>{await JC(Z,"disconnect",{signal:X}),Vc(J)},FB1=async(Z,J,{signal:X})=>{let[Y]=await JC(Z,"strict:error",{signal:X});throw fL(Y,J)};import{once as Ep,on as qB1}from"node:events";var kp=({anyProcess:Z,channel:J,isSubprocess:X,ipc:Y},{reference:$=!0}={})=>XC({anyProcess:Z,channel:J,isSubprocess:X,ipc:Y,shouldAwait:!X,reference:$}),XC=({anyProcess:Z,channel:J,isSubprocess:X,ipc:Y,shouldAwait:$,reference:Q})=>{IK({methodName:"getEachMessage",isSubprocess:X,ipc:Y,isConnected:cL(Z)}),gL(J,Q);let K=gJ(Z,J,X),G=new AbortController,W={};return UB1(Z,K,G),LB1({ipcEmitter:K,isSubprocess:X,controller:G,state:W}),BB1({anyProcess:Z,channel:J,ipcEmitter:K,isSubprocess:X,shouldAwait:$,controller:G,state:W,reference:Q})},UB1=async(Z,J,X)=>{try{await Ep(J,"disconnect",{signal:X.signal}),X.abort()}catch{}},LB1=async({ipcEmitter:Z,isSubprocess:J,controller:X,state:Y})=>{try{let[$]=await Ep(Z,"strict:error",{signal:X.signal});Y.error=fL($,J),X.abort()}catch{}},BB1=async function*({anyProcess:Z,channel:J,ipcEmitter:X,isSubprocess:Y,shouldAwait:$,controller:Q,state:K,reference:G}){try{for await(let[W]of qB1(X,"message",{signal:Q.signal}))Tp(K),yield W}catch{Tp(K)}finally{if(Q.abort(),mL(J,G),!Y)_K(Z);if($)await Z}},Tp=({error:Z})=>{if(Z)throw Z};var _p=(Z,{ipc:J})=>{Object.assign(Z,vp(Z,!1,J))},Sp=()=>{let Z=Ip,J=!0,X=Ip.channel!==void 0;return{...vp(Z,!0,X),getCancelSignal:yc.bind(void 0,{anyProcess:Z,channel:Z.channel,isSubprocess:!0,ipc:X})}},vp=(Z,J,X)=>({sendMessage:nL.bind(void 0,{anyProcess:Z,channel:Z.channel,isSubprocess:J,ipc:X}),getOneMessage:Cp.bind(void 0,{anyProcess:Z,channel:Z.channel,isSubprocess:J,ipc:X}),getEachMessage:kp.bind(void 0,{anyProcess:Z,channel:Z.channel,isSubprocess:J,ipc:X})});import{ChildProcess as wB1}from"node:child_process";import{PassThrough as jB1,Readable as OB1,Writable as MB1,Duplex as RB1}from"node:stream";var Ap=({error:Z,command:J,escapedCommand:X,fileDescriptors:Y,options:$,startTime:Q,verboseInfo:K})=>{iD(Y);let G=new wB1;NB1(G,Y),Object.assign(G,{readable:PB1,writable:DB1,duplex:CB1});let W=xK({error:Z,command:J,escapedCommand:X,fileDescriptors:Y,options:$,startTime:Q,isSync:!1}),H=TB1(W,K,$);return{subprocess:G,promise:H}},NB1=(Z,J)=>{let X=BH(),Y=BH(),$=BH(),Q=Array.from({length:J.length-3},BH),K=BH(),G=[X,Y,$,...Q];Object.assign(Z,{stdin:X,stdout:Y,stderr:$,all:K,stdio:G})},BH=()=>{let Z=new jB1;return Z.end(),Z},PB1=()=>new OB1({read(){}}),DB1=()=>new MB1({write(){}}),CB1=()=>new RB1({read(){},write(){}}),TB1=async(Z,J,X)=>hK(Z,J,X);import{createReadStream as xp,createWriteStream as hp}from"node:fs";import{Buffer as EB1}from"node:buffer";import{Readable as wH,Writable as kB1,Duplex as IB1}from"node:stream";var yp=(Z,J)=>WB(_B1,Z,J,!1),jH=({type:Z,optionName:J})=>{throw new TypeError(`The \`${J}\` option cannot be ${mJ[Z]}.`)},fp={fileNumber:jH,generator:tD,asyncGenerator:tD,nodeStream:({value:Z})=>({stream:Z}),webTransform({value:{transform:Z,writableObjectMode:J,readableObjectMode:X}}){let Y=J||X;return{stream:IB1.fromWeb(Z,{objectMode:Y})}},duplex:({value:{transform:Z}})=>({stream:Z}),native(){}},_B1={input:{...fp,fileUrl:({value:Z})=>({stream:xp(Z)}),filePath:({value:{file:Z}})=>({stream:xp(Z)}),webStream:({value:Z})=>({stream:wH.fromWeb(Z)}),iterable:({value:Z})=>({stream:wH.from(Z)}),asyncIterable:({value:Z})=>({stream:wH.from(Z)}),string:({value:Z})=>({stream:wH.from(Z)}),uint8Array:({value:Z})=>({stream:wH.from(EB1.from(Z))})},output:{...fp,fileUrl:({value:Z})=>({stream:hp(Z)}),filePath:({value:{file:Z,append:J}})=>({stream:hp(Z,J?{flags:"a"}:{})}),webStream:({value:Z})=>({stream:kB1.fromWeb(Z)}),iterable:jH,asyncIterable:jH,string:jH,uint8Array:jH}};import{on as SB1,once as bp}from"node:events";import{PassThrough as vB1,getDefaultHighWaterMark as AB1}from"node:stream";import{finished as up}from"node:stream/promises";function cY(Z){if(!Array.isArray(Z))throw new TypeError(`Expected an array, got \`${typeof Z}\`.`);for(let $ of Z)YC($);let J=Z.some(({readableObjectMode:$})=>$),X=xB1(Z,J),Y=new dp({objectMode:J,writableHighWaterMark:X,readableHighWaterMark:X});for(let $ of Z)Y.add($);return Y}var xB1=(Z,J)=>{if(Z.length===0)return AB1(J);let X=Z.filter(({readableObjectMode:Y})=>Y===J).map(({readableHighWaterMark:Y})=>Y);return Math.max(...X)};class dp extends vB1{#Z=new Set([]);#J=new Set([]);#Y=new Set([]);#X;#$=Symbol("unpipe");#V=new WeakMap;add(Z){if(YC(Z),this.#Z.has(Z))return;this.#Z.add(Z),this.#X??=hB1(this,this.#Z,this.#$);let J=bB1({passThroughStream:this,stream:Z,streams:this.#Z,ended:this.#J,aborted:this.#Y,onFinished:this.#X,unpipeEvent:this.#$});this.#V.set(Z,J),Z.pipe(this,{end:!1})}async remove(Z){if(YC(Z),!this.#Z.has(Z))return!1;let J=this.#V.get(Z);if(J===void 0)return!1;return this.#V.delete(Z),Z.unpipe(this),await J,!0}}var hB1=async(Z,J,X)=>{LB(Z,gp);let Y=new AbortController;try{await Promise.race([fB1(Z,Y),yB1(Z,J,X,Y)])}finally{Y.abort(),LB(Z,-gp)}},fB1=async(Z,{signal:J})=>{try{await up(Z,{signal:J,cleanup:!0})}catch(X){throw cp(Z,X),X}},yB1=async(Z,J,X,{signal:Y})=>{for await(let[$]of SB1(Z,"unpipe",{signal:Y}))if(J.has($))$.emit(X)},YC=(Z)=>{if(typeof Z?.pipe!=="function")throw new TypeError(`Expected a readable stream, got: \`${typeof Z}\`.`)},bB1=async({passThroughStream:Z,stream:J,streams:X,ended:Y,aborted:$,onFinished:Q,unpipeEvent:K})=>{LB(Z,mp);let G=new AbortController;try{await Promise.race([gB1(Q,J,G),mB1({passThroughStream:Z,stream:J,streams:X,ended:Y,aborted:$,controller:G}),uB1({stream:J,streams:X,ended:Y,aborted:$,unpipeEvent:K,controller:G})])}finally{G.abort(),LB(Z,-mp)}if(X.size>0&&X.size===Y.size+$.size)if(Y.size===0&&$.size>0)$C(Z);else dB1(Z)},gB1=async(Z,J,{signal:X})=>{try{if(await Z,!X.aborted)$C(J)}catch(Y){if(!X.aborted)cp(J,Y)}},mB1=async({passThroughStream:Z,stream:J,streams:X,ended:Y,aborted:$,controller:{signal:Q}})=>{try{if(await up(J,{signal:Q,cleanup:!0,readable:!0,writable:!1}),X.has(J))Y.add(J)}catch(K){if(Q.aborted||!X.has(J))return;if(lp(K))$.add(J);else pp(Z,K)}},uB1=async({stream:Z,streams:J,ended:X,aborted:Y,unpipeEvent:$,controller:{signal:Q}})=>{if(await bp(Z,$,{signal:Q}),!Z.readable)return bp(Q,"abort",{signal:Q});J.delete(Z),X.delete(Z),Y.delete(Z)},dB1=(Z)=>{if(Z.writable)Z.end()},cp=(Z,J)=>{if(lp(J))$C(Z);else pp(Z,J)},lp=(Z)=>Z?.code==="ERR_STREAM_PREMATURE_CLOSE",$C=(Z)=>{if(Z.readable||Z.writable)Z.destroy()},pp=(Z,J)=>{if(!Z.destroyed)Z.once("error",cB1),Z.destroy(J)},cB1=()=>{},LB=(Z,J)=>{let X=Z.getMaxListeners();if(X!==0&&X!==Number.POSITIVE_INFINITY)Z.setMaxListeners(X+J)},gp=2,mp=1;import{finished as ip}from"node:stream/promises";var yK=(Z,J)=>{Z.pipe(J),lB1(Z,J),pB1(Z,J)},lB1=async(Z,J)=>{if(E4(Z)||E4(J))return;try{await ip(Z,{cleanup:!0,readable:!0,writable:!1})}catch{}QC(J)},QC=(Z)=>{if(Z.writable)Z.end()},pB1=async(Z,J)=>{if(E4(Z)||E4(J))return;try{await ip(J,{cleanup:!0,readable:!1,writable:!0})}catch{}KC(Z)},KC=(Z)=>{if(Z.readable)Z.destroy()};var np=(Z,J,X)=>{let Y=new Map;for(let[$,{stdioItems:Q,direction:K}]of Object.entries(J)){for(let{stream:G}of Q.filter(({type:W})=>S9.has(W)))iB1(Z,G,K,$);for(let{stream:G}of Q.filter(({type:W})=>!S9.has(W)))aB1({subprocess:Z,stream:G,direction:K,fdNumber:$,pipeGroups:Y,controller:X})}for(let[$,Q]of Y.entries()){let K=Q.length===1?Q[0]:cY(Q);yK(K,$)}},iB1=(Z,J,X,Y)=>{if(X==="output")yK(Z.stdio[Y],J);else yK(J,Z.stdio[Y]);let $=nB1[Y];if($!==void 0)Z[$]=J;Z.stdio[Y]=J},nB1=["stdin","stdout","stderr"],aB1=({subprocess:Z,stream:J,direction:X,fdNumber:Y,pipeGroups:$,controller:Q})=>{if(J===void 0)return;sB1(J,Q);let[K,G]=X==="output"?[J,Z.stdio[Y]]:[Z.stdio[Y],J],W=$.get(K)??[];$.set(K,[...W,G])},sB1=(Z,{signal:J})=>{if(E4(Z))gY(Z,oB1,J)},oB1=2;import{addAbortListener as eB1}from"node:events";var lY=[];lY.push("SIGHUP","SIGINT","SIGTERM");if(process.platform!=="win32")lY.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(process.platform==="linux")lY.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var BB=(Z)=>!!Z&&typeof Z==="object"&&typeof Z.removeListener==="function"&&typeof Z.emit==="function"&&typeof Z.reallyExit==="function"&&typeof Z.listeners==="function"&&typeof Z.kill==="function"&&typeof Z.pid==="number"&&typeof Z.on==="function",GC=Symbol.for("signal-exit emitter"),WC=globalThis,rB1=Object.defineProperty.bind(Object);class ap{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(WC[GC])return WC[GC];rB1(WC,GC,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(Z,J){this.listeners[Z].push(J)}removeListener(Z,J){let X=this.listeners[Z],Y=X.indexOf(J);if(Y===-1)return;if(Y===0&&X.length===1)X.length=0;else X.splice(Y,1)}emit(Z,J,X){if(this.emitted[Z])return!1;this.emitted[Z]=!0;let Y=!1;for(let $ of this.listeners[Z])Y=$(J,X)===!0||Y;if(Z==="exit")Y=this.emit("afterExit",J,X)||Y;return Y}}class VC{}var tB1=(Z)=>{return{onExit(J,X){return Z.onExit(J,X)},load(){return Z.load()},unload(){return Z.unload()}}};class sp extends VC{onExit(){return()=>{}}load(){}unload(){}}class op extends VC{#Z=HC.platform==="win32"?"SIGINT":"SIGHUP";#J=new ap;#Y;#X;#$;#V={};#F=!1;constructor(Z){super();this.#Y=Z,this.#V={};for(let J of lY)this.#V[J]=()=>{let X=this.#Y.listeners(J),{count:Y}=this.#J,$=Z;if(typeof $.__signal_exit_emitter__==="object"&&typeof $.__signal_exit_emitter__.count==="number")Y+=$.__signal_exit_emitter__.count;if(X.length===Y){this.unload();let Q=this.#J.emit("exit",null,J),K=J==="SIGHUP"?this.#Z:J;if(!Q)Z.kill(Z.pid,K)}};this.#$=Z.reallyExit,this.#X=Z.emit}onExit(Z,J){if(!BB(this.#Y))return()=>{};if(this.#F===!1)this.load();let X=J?.alwaysLast?"afterExit":"exit";return this.#J.on(X,Z),()=>{if(this.#J.removeListener(X,Z),this.#J.listeners.exit.length===0&&this.#J.listeners.afterExit.length===0)this.unload()}}load(){if(this.#F)return;this.#F=!0,this.#J.count+=1;for(let Z of lY)try{let J=this.#V[Z];if(J)this.#Y.on(Z,J)}catch(J){}this.#Y.emit=(Z,...J)=>{return this.#W(Z,...J)},this.#Y.reallyExit=(Z)=>{return this.#G(Z)}}unload(){if(!this.#F)return;this.#F=!1,lY.forEach((Z)=>{let J=this.#V[Z];if(!J)throw new Error("Listener not defined for signal: "+Z);try{this.#Y.removeListener(Z,J)}catch(X){}}),this.#Y.emit=this.#X,this.#Y.reallyExit=this.#$,this.#J.count-=1}#G(Z){if(!BB(this.#Y))return 0;return this.#Y.exitCode=Z||0,this.#J.emit("exit",this.#Y.exitCode,null),this.#$.call(this.#Y,this.#Y.exitCode)}#W(Z,...J){let X=this.#X;if(Z==="exit"&&BB(this.#Y)){if(typeof J[0]==="number")this.#Y.exitCode=J[0];let Y=X.call(this.#Y,Z,...J);return this.#J.emit("exit",this.#Y.exitCode,null),Y}else return X.call(this.#Y,Z,...J)}}var HC=globalThis.process,{onExit:rp,load:VT6,unload:zT6}=tB1(BB(HC)?new op(HC):new sp);var tp=(Z,{cleanup:J,detached:X},{signal:Y})=>{if(!J||X)return;let $=rp(()=>{Z.kill()});eB1(Y,()=>{$()})};var Zi=({source:Z,sourcePromise:J,boundOptions:X,createNested:Y},...$)=>{let Q=CL(),{destination:K,destinationStream:G,destinationError:W,from:H,unpipeSignal:V}=Z21(X,Y,$),{sourceStream:F,sourceError:z}=X21(Z,H),{options:q,fileDescriptors:U}=O7.get(Z);return{sourcePromise:J,sourceStream:F,sourceOptions:q,sourceError:z,destination:K,destinationStream:G,destinationError:W,unpipeSignal:V,fileDescriptors:U,startTime:Q}},Z21=(Z,J,X)=>{try{let{destination:Y,pipeOptions:{from:$,to:Q,unpipeSignal:K}={}}=J21(Z,J,...X),G=bL(Y,Q);return{destination:Y,destinationStream:G,from:$,unpipeSignal:K}}catch(Y){return{destinationError:Y}}},J21=(Z,J,X,...Y)=>{if(Array.isArray(X))return{destination:J(ep,Z)(X,...Y),pipeOptions:Z};if(typeof X==="string"||X instanceof URL||XD(X)){if(Object.keys(Z).length>0)throw new TypeError('Please use .pipe("file", ..., options) or .pipe(execa("file", ..., options)) instead of .pipe(options)("file", ...).');let[$,Q,K]=LL(X,...Y);return{destination:J(ep)($,Q,K),pipeOptions:K}}if(O7.has(X)){if(Object.keys(Z).length>0)throw new TypeError("Please use .pipe(options)`command` or .pipe($(options)`command`) instead of .pipe(options)($`command`).");return{destination:X,pipeOptions:Y[0]}}throw new TypeError(`The first argument must be a template string, an options object, or an Execa subprocess: ${X}`)},ep=({options:Z})=>({options:{...Z,stdin:"pipe",piped:!0}}),X21=(Z,J)=>{try{return{sourceStream:SK(Z,J)}}catch(X){return{sourceError:X}}};var Xi=({sourceStream:Z,sourceError:J,destinationStream:X,destinationError:Y,fileDescriptors:$,sourceOptions:Q,startTime:K})=>{let G=Y21({sourceStream:Z,sourceError:J,destinationStream:X,destinationError:Y});if(G!==void 0)throw zC({error:G,fileDescriptors:$,sourceOptions:Q,startTime:K})},Y21=({sourceStream:Z,sourceError:J,destinationStream:X,destinationError:Y})=>{if(J!==void 0&&Y!==void 0)return Y;if(Y!==void 0)return KC(Z),Y;if(J!==void 0)return QC(X),J},zC=({error:Z,fileDescriptors:J,sourceOptions:X,startTime:Y})=>xK({error:Z,command:Ji,escapedCommand:Ji,fileDescriptors:J,options:X,startTime:Y,isSync:!1}),Ji="source.pipe(destination)";var Yi=async(Z)=>{let[{status:J,reason:X,value:Y=X},{status:$,reason:Q,value:K=Q}]=await Z;if(!K.pipedFrom.includes(Y))K.pipedFrom.push(Y);if($==="rejected")throw K;if(J==="rejected")throw Y;return K};import{finished as $21}from"node:stream/promises";var $i=(Z,J,X)=>{let Y=wB.has(J)?K21(Z,J):Q21(Z,J);return gY(Z,W21,X.signal),gY(J,H21,X.signal),G21(J),Y},Q21=(Z,J)=>{let X=cY([Z]);return yK(X,J),wB.set(J,X),X},K21=(Z,J)=>{let X=wB.get(J);return X.add(Z),X},G21=async(Z)=>{try{await $21(Z,{cleanup:!0,readable:!1,writable:!0})}catch{}wB.delete(Z)},wB=new WeakMap,W21=2,H21=1;import{aborted as V21}from"node:util";var Qi=(Z,J)=>Z===void 0?[]:[z21(Z,J)],z21=async(Z,{sourceStream:J,mergedStream:X,fileDescriptors:Y,sourceOptions:$,startTime:Q})=>{await V21(Z,J),await X.remove(J);let K=new Error("Pipe canceled by `unpipeSignal` option.");throw zC({error:K,fileDescriptors:Y,sourceOptions:$,startTime:Q})};var jB=(Z,...J)=>{if(P8(J[0]))return jB.bind(void 0,{...Z,boundOptions:{...Z.boundOptions,...J[0]}});let{destination:X,...Y}=Zi(Z,...J),$=F21({...Y,destination:X});return $.pipe=jB.bind(void 0,{...Z,source:X,sourcePromise:$,boundOptions:{}}),$},F21=async({sourcePromise:Z,sourceStream:J,sourceOptions:X,sourceError:Y,destination:$,destinationStream:Q,destinationError:K,unpipeSignal:G,fileDescriptors:W,startTime:H})=>{let V=q21(Z,$);Xi({sourceStream:J,sourceError:Y,destinationStream:Q,destinationError:K,fileDescriptors:W,sourceOptions:X,startTime:H});let F=new AbortController;try{let z=$i(J,Q,F);return await Promise.race([Yi(V),...Qi(G,{sourceStream:J,mergedStream:z,sourceOptions:X,fileDescriptors:W,startTime:H})])}finally{F.abort()}},q21=(Z,J)=>Promise.allSettled([Z,J]);import{setImmediate as M21}from"node:timers/promises";import{on as U21}from"node:events";import{getDefaultHighWaterMark as L21}from"node:stream";var OB=({subprocessStdout:Z,subprocess:J,binary:X,shouldEncode:Y,encoding:$,preserveNewlines:Q})=>{let K=new AbortController;return B21(J,K),Gi({stream:Z,controller:K,binary:X,shouldEncode:!Z.readableObjectMode&&Y,encoding:$,shouldSplit:!Z.readableObjectMode,preserveNewlines:Q})},B21=async(Z,J)=>{try{await Z}catch{}finally{J.abort()}},FC=({stream:Z,onStreamEnd:J,lines:X,encoding:Y,stripFinalNewline:$,allMixed:Q})=>{let K=new AbortController;w21(J,K,Z);let G=Z.readableObjectMode&&!Q;return Gi({stream:Z,controller:K,binary:Y==="buffer",shouldEncode:!G,encoding:Y,shouldSplit:!G&&X,preserveNewlines:!$})},w21=async(Z,J,X)=>{try{await Z}catch{X.destroy()}finally{J.abort()}},Gi=({stream:Z,controller:J,binary:X,shouldEncode:Y,encoding:$,shouldSplit:Q,preserveNewlines:K})=>{let G=U21(Z,"data",{signal:J.signal,highWaterMark:Ki,highWatermark:Ki});return j21({onStdoutChunk:G,controller:J,binary:X,shouldEncode:Y,encoding:$,shouldSplit:Q,preserveNewlines:K})},qC=L21(!0),Ki=qC,j21=async function*({onStdoutChunk:Z,controller:J,binary:X,shouldEncode:Y,encoding:$,shouldSplit:Q,preserveNewlines:K}){let G=O21({binary:X,shouldEncode:Y,encoding:$,shouldSplit:Q,preserveNewlines:K});try{for await(let[W]of Z)yield*dY(W,G,0)}catch(W){if(!J.signal.aborted)throw W}finally{yield*LH(G)}},O21=({binary:Z,shouldEncode:J,encoding:X,shouldSplit:Y,preserveNewlines:$})=>[VB(Z,X,!J),HB(Z,$,!Y,{})].filter(Boolean);var Wi=async({stream:Z,onStreamEnd:J,fdNumber:X,encoding:Y,buffer:$,maxBuffer:Q,lines:K,allMixed:G,stripFinalNewline:W,verboseInfo:H,streamInfo:V})=>{let F=R21({stream:Z,onStreamEnd:J,fdNumber:X,encoding:Y,allMixed:G,verboseInfo:H,streamInfo:V});if(!$){await Promise.all([N21(Z),F]);return}let z=nD(W,X),q=FC({stream:Z,onStreamEnd:J,lines:K,encoding:Y,stripFinalNewline:z,allMixed:G}),[U]=await Promise.all([P21({stream:Z,iterable:q,fdNumber:X,encoding:Y,maxBuffer:Q,lines:K}),F]);return U},R21=async({stream:Z,onStreamEnd:J,fdNumber:X,encoding:Y,allMixed:$,verboseInfo:Q,streamInfo:{fileDescriptors:K}})=>{if(!qB({stdioItems:K[X]?.stdioItems,encoding:Y,verboseInfo:Q,fdNumber:X}))return;let G=FC({stream:Z,onStreamEnd:J,lines:!0,encoding:Y,stripFinalNewline:!0,allMixed:$});await Lp(G,Z,X,Q)},N21=async(Z)=>{if(await M21(),Z.readableFlowing===null)Z.resume()},P21=async({stream:Z,stream:{readableObjectMode:J},iterable:X,fdNumber:Y,encoding:$,maxBuffer:Q,lines:K})=>{try{if(J||K)return await eL(X,{maxBuffer:Q});if($==="buffer")return new Uint8Array(await ZB(X,{maxBuffer:Q}));return await XB(X,{maxBuffer:Q})}catch(G){return Hi(Ll({error:G,stream:Z,readableObjectMode:J,lines:K,encoding:$,fdNumber:Y}))}},UC=async(Z)=>{try{return await Z}catch(J){return Hi(J)}},Hi=({bufferedData:Z})=>Su(Z)?new Uint8Array(Z):Z;import{finished as D21}from"node:stream/promises";var OH=async(Z,J,X,{isSameDirection:Y,stopOnExit:$=!1}={})=>{let Q=C21(Z,X),K=new AbortController;try{await Promise.race([...$?[X.exitPromise]:[],D21(Z,{cleanup:!0,signal:K.signal})])}catch(G){if(!Q.stdinCleanedUp)k21(G,J,X,Y)}finally{K.abort()}},C21=(Z,{originalStreams:[J],subprocess:X})=>{let Y={stdinCleanedUp:!1};if(Z===J)T21(Z,X,Y);return Y},T21=(Z,J,X)=>{let{_destroy:Y}=Z;Z._destroy=(...$)=>{E21(J,X),Y.call(Z,...$)}},E21=({exitCode:Z,signalCode:J},X)=>{if(Z!==null||J!==null)X.stdinCleanedUp=!0},k21=(Z,J,X,Y)=>{if(!I21(Z,J,X,Y))throw Z},I21=(Z,J,X,Y=!0)=>{if(X.propagating)return Vi(Z)||MB(Z);return X.propagating=!0,LC(X,J)===Y?Vi(Z):MB(Z)},LC=({fileDescriptors:Z},J)=>J!=="all"&&Z[J].direction==="input",MB=(Z)=>Z?.code==="ERR_STREAM_PREMATURE_CLOSE",Vi=(Z)=>Z?.code==="EPIPE";var zi=({subprocess:Z,encoding:J,buffer:X,maxBuffer:Y,lines:$,stripFinalNewline:Q,verboseInfo:K,streamInfo:G})=>Z.stdio.map((W,H)=>BC({stream:W,fdNumber:H,encoding:J,buffer:X[H],maxBuffer:Y[H],lines:$[H],allMixed:!1,stripFinalNewline:Q,verboseInfo:K,streamInfo:G})),BC=async({stream:Z,fdNumber:J,encoding:X,buffer:Y,maxBuffer:$,lines:Q,allMixed:K,stripFinalNewline:G,verboseInfo:W,streamInfo:H})=>{if(!Z)return;let V=OH(Z,J,H);if(LC(H,J)){await V;return}let[F]=await Promise.all([Wi({stream:Z,onStreamEnd:V,fdNumber:J,encoding:X,buffer:Y,maxBuffer:$,lines:Q,allMixed:K,stripFinalNewline:G,verboseInfo:W,streamInfo:H}),V]);return F};var Fi=({stdout:Z,stderr:J},{all:X})=>X&&(Z||J)?cY([Z,J].filter(Boolean)):void 0,qi=({subprocess:Z,encoding:J,buffer:X,maxBuffer:Y,lines:$,stripFinalNewline:Q,verboseInfo:K,streamInfo:G})=>BC({..._21(Z,X),fdNumber:"all",encoding:J,maxBuffer:Y[1]+Y[2],lines:$[1]||$[2],allMixed:S21(Z),stripFinalNewline:Q,verboseInfo:K,streamInfo:G}),_21=({stdout:Z,stderr:J,all:X},[,Y,$])=>{let Q=Y||$;if(!Q)return{stream:X,buffer:Q};if(!Y)return{stream:J,buffer:Q};if(!$)return{stream:Z,buffer:Q};return{stream:X,buffer:Q}},S21=({all:Z,stdout:J,stderr:X})=>Z&&J&&X&&J.readableObjectMode!==X.readableObjectMode;import{once as v21}from"node:events";var Ui=(Z)=>TK(Z,"ipc"),Li=(Z,J)=>{let X=DL(Z);B7({type:"ipc",verboseMessage:X,fdNumber:"ipc",verboseInfo:J})};var Bi=async({subprocess:Z,buffer:J,maxBuffer:X,ipc:Y,ipcOutput:$,verboseInfo:Q})=>{if(!Y)return $;let K=Ui(Q),G=RZ(J,"ipc"),W=RZ(X,"ipc");for await(let H of XC({anyProcess:Z,channel:Z.channel,isSubprocess:!1,ipc:Y,shouldAwait:!1,reference:!0})){if(G)Bl(Z,$,W),$.push(H);if(K)Li(H,Q)}return $},wi=async(Z,J)=>{return await Promise.allSettled([Z]),J};var ji=async({subprocess:Z,options:{encoding:J,buffer:X,maxBuffer:Y,lines:$,timeoutDuration:Q,cancelSignal:K,gracefulCancel:G,forceKillAfterDelay:W,stripFinalNewline:H,ipc:V,ipcInput:F},context:z,verboseInfo:q,fileDescriptors:U,originalStreams:B,onInternalError:L,controller:w})=>{let O=Mp(Z,z),M={originalStreams:B,fileDescriptors:U,subprocess:Z,exitPromise:O,propagating:!1},R=zi({subprocess:Z,encoding:J,buffer:X,maxBuffer:Y,lines:$,stripFinalNewline:H,verboseInfo:q,streamInfo:M}),D=qi({subprocess:Z,encoding:J,buffer:X,maxBuffer:Y,lines:$,stripFinalNewline:H,verboseInfo:q,streamInfo:M}),N=[],C=Bi({subprocess:Z,buffer:X,maxBuffer:Y,ipc:V,ipcOutput:N,verboseInfo:q}),T=A21(B,Z,M),E=x21(U,M);try{return await Promise.race([Promise.all([{},Np(O),Promise.all(R),D,C,nc(Z,F),...T,...E]),L,h21(Z,w),...dc(Z,Q,z,w),...Hc({subprocess:Z,cancelSignal:K,gracefulCancel:G,context:z,controller:w}),...mc({subprocess:Z,cancelSignal:K,gracefulCancel:G,forceKillAfterDelay:W,context:z,controller:w})])}catch(x){return z.terminationReason??="other",Promise.all([{error:x},O,Promise.all(R.map((S)=>UC(S))),UC(D),wi(C,N),Promise.allSettled(T),Promise.allSettled(E)])}},A21=(Z,J,X)=>Z.map((Y,$)=>Y===J.stdio[$]?void 0:OH(Y,$,X)),x21=(Z,J)=>Z.flatMap(({stdioItems:X},Y)=>X.filter(({value:$,stream:Q=$})=>I4(Q,{checkOpen:!1})&&!E4(Q)).map(({type:$,value:Q,stream:K=Q})=>OH(K,Y,J,{isSameDirection:S9.has($),stopOnExit:$==="native"}))),h21=async(Z,{signal:J})=>{let[X]=await v21(Z,"error",{signal:J});throw X};var Oi=()=>({readableDestroy:new WeakMap,writableFinal:new WeakMap,writableDestroy:new WeakMap}),MH=(Z,J,X)=>{let Y=Z[X];if(!Y.has(J))Y.set(J,[]);let $=Y.get(J),Q=j7();return $.push(Q),{resolve:Q.resolve.bind(Q),promises:$}},bK=async({resolve:Z,promises:J},X)=>{Z();let[Y]=await Promise.race([Promise.allSettled([!0,X]),Promise.all([!1,...J])]);return!Y};import{Readable as f21}from"node:stream";import{callbackify as y21}from"node:util";import{finished as Mi}from"node:stream/promises";var wC=async(Z)=>{if(Z===void 0)return;try{await jC(Z)}catch{}},Ri=async(Z)=>{if(Z===void 0)return;try{await OC(Z)}catch{}},jC=async(Z)=>{await Mi(Z,{cleanup:!0,readable:!1,writable:!0})},OC=async(Z)=>{await Mi(Z,{cleanup:!0,readable:!0,writable:!1})},RB=async(Z,J)=>{if(await Z,J)throw J},NB=(Z,J,X)=>{if(X&&!MB(X))Z.destroy(X);else if(J)Z.destroy()};var Ni=({subprocess:Z,concurrentStreams:J,encoding:X},{from:Y,binary:$=!0,preserveNewlines:Q=!0}={})=>{let K=$||r5.has(X),{subprocessStdout:G,waitReadableDestroy:W}=MC(Z,Y,J),{readableEncoding:H,readableObjectMode:V,readableHighWaterMark:F}=RC(G,K),{read:z,onStdoutDataDone:q}=NC({subprocessStdout:G,subprocess:Z,binary:K,encoding:X,preserveNewlines:Q}),U=new f21({read:z,destroy:y21(DC.bind(void 0,{subprocessStdout:G,subprocess:Z,waitReadableDestroy:W})),highWaterMark:F,objectMode:V,encoding:H});return PC({subprocessStdout:G,onStdoutDataDone:q,readable:U,subprocess:Z}),U},MC=(Z,J,X)=>{let Y=SK(Z,J),$=MH(X,Y,"readableDestroy");return{subprocessStdout:Y,waitReadableDestroy:$}},RC=({readableEncoding:Z,readableObjectMode:J,readableHighWaterMark:X},Y)=>Y?{readableEncoding:Z,readableObjectMode:J,readableHighWaterMark:X}:{readableEncoding:Z,readableObjectMode:!0,readableHighWaterMark:qC},NC=({subprocessStdout:Z,subprocess:J,binary:X,encoding:Y,preserveNewlines:$})=>{let Q=j7(),K=OB({subprocessStdout:Z,subprocess:J,binary:X,shouldEncode:!X,encoding:Y,preserveNewlines:$});return{read(){b21(this,K,Q)},onStdoutDataDone:Q}},b21=async(Z,J,X)=>{try{let{value:Y,done:$}=await J.next();if($)X.resolve();else Z.push(Y)}catch{}},PC=async({subprocessStdout:Z,onStdoutDataDone:J,readable:X,subprocess:Y,subprocessStdin:$})=>{try{if(await OC(Z),await Y,await wC($),await J,X.readable)X.push(null)}catch(Q){await wC($),Pi(X,Q)}},DC=async({subprocessStdout:Z,subprocess:J,waitReadableDestroy:X},Y)=>{if(await bK(X,J))Pi(Z,Y),await RB(J,Y)},Pi=(Z,J)=>{NB(Z,Z.readable,J)};import{Writable as g21}from"node:stream";import{callbackify as Di}from"node:util";var Ci=({subprocess:Z,concurrentStreams:J},{to:X}={})=>{let{subprocessStdin:Y,waitWritableFinal:$,waitWritableDestroy:Q}=CC(Z,X,J),K=new g21({...TC(Y,Z,$),destroy:Di(kC.bind(void 0,{subprocessStdin:Y,subprocess:Z,waitWritableFinal:$,waitWritableDestroy:Q})),highWaterMark:Y.writableHighWaterMark,objectMode:Y.writableObjectMode});return EC(Y,K),K},CC=(Z,J,X)=>{let Y=bL(Z,J),$=MH(X,Y,"writableFinal"),Q=MH(X,Y,"writableDestroy");return{subprocessStdin:Y,waitWritableFinal:$,waitWritableDestroy:Q}},TC=(Z,J,X)=>({write:m21.bind(void 0,Z),final:Di(u21.bind(void 0,Z,J,X))}),m21=(Z,J,X,Y)=>{if(Z.write(J,X))Y();else Z.once("drain",Y)},u21=async(Z,J,X)=>{if(await bK(X,J)){if(Z.writable)Z.end();await J}},EC=async(Z,J,X)=>{try{if(await jC(Z),J.writable)J.end()}catch(Y){await Ri(X),Ti(J,Y)}},kC=async({subprocessStdin:Z,subprocess:J,waitWritableFinal:X,waitWritableDestroy:Y},$)=>{if(await bK(X,J),await bK(Y,J))Ti(Z,$),await RB(J,$)},Ti=(Z,J)=>{NB(Z,Z.writable,J)};import{Duplex as d21}from"node:stream";import{callbackify as c21}from"node:util";var Ei=({subprocess:Z,concurrentStreams:J,encoding:X},{from:Y,to:$,binary:Q=!0,preserveNewlines:K=!0}={})=>{let G=Q||r5.has(X),{subprocessStdout:W,waitReadableDestroy:H}=MC(Z,Y,J),{subprocessStdin:V,waitWritableFinal:F,waitWritableDestroy:z}=CC(Z,$,J),{readableEncoding:q,readableObjectMode:U,readableHighWaterMark:B}=RC(W,G),{read:L,onStdoutDataDone:w}=NC({subprocessStdout:W,subprocess:Z,binary:G,encoding:X,preserveNewlines:K}),O=new d21({read:L,...TC(V,Z,F),destroy:c21(l21.bind(void 0,{subprocessStdout:W,subprocessStdin:V,subprocess:Z,waitReadableDestroy:H,waitWritableFinal:F,waitWritableDestroy:z})),readableHighWaterMark:B,writableHighWaterMark:V.writableHighWaterMark,readableObjectMode:U,writableObjectMode:V.writableObjectMode,encoding:q});return PC({subprocessStdout:W,onStdoutDataDone:w,readable:O,subprocess:Z,subprocessStdin:V}),EC(V,O,W),O},l21=async({subprocessStdout:Z,subprocessStdin:J,subprocess:X,waitReadableDestroy:Y,waitWritableFinal:$,waitWritableDestroy:Q},K)=>{await Promise.all([DC({subprocessStdout:Z,subprocess:X,waitReadableDestroy:Y},K),kC({subprocessStdin:J,subprocess:X,waitWritableFinal:$,waitWritableDestroy:Q},K)])};var IC=(Z,J,{from:X,binary:Y=!1,preserveNewlines:$=!1}={})=>{let Q=Y||r5.has(J),K=SK(Z,X),G=OB({subprocessStdout:K,subprocess:Z,binary:Q,shouldEncode:!0,encoding:J,preserveNewlines:$});return p21(G,K,Z)},p21=async function*(Z,J,X){try{yield*Z}finally{if(J.readable)J.destroy();await X}};var ki=(Z,{encoding:J})=>{let X=Oi();Z.readable=Ni.bind(void 0,{subprocess:Z,concurrentStreams:X,encoding:J}),Z.writable=Ci.bind(void 0,{subprocess:Z,concurrentStreams:X}),Z.duplex=Ei.bind(void 0,{subprocess:Z,concurrentStreams:X,encoding:J}),Z.iterable=IC.bind(void 0,Z,J),Z[Symbol.asyncIterator]=IC.bind(void 0,Z,J,{})};var Ii=(Z,J)=>{for(let[X,Y]of n21){let $=Y.value.bind(J);Reflect.defineProperty(Z,X,{...Y,value:$})}},i21=(async()=>{})().constructor.prototype,n21=["then","catch","finally"].map((Z)=>[Z,Reflect.getOwnPropertyDescriptor(i21,Z)]);var _i=(Z,J,X,Y)=>{let{file:$,commandArguments:Q,command:K,escapedCommand:G,startTime:W,verboseInfo:H,options:V,fileDescriptors:F}=o21(Z,J,X),{subprocess:z,promise:q}=t21({file:$,commandArguments:Q,options:V,startTime:W,verboseInfo:H,command:K,escapedCommand:G,fileDescriptors:F});return z.pipe=jB.bind(void 0,{source:z,sourcePromise:q,boundOptions:{},createNested:Y}),Ii(z,q),O7.set(z,{options:V,fileDescriptors:F}),z},o21=(Z,J,X)=>{let{command:Y,escapedCommand:$,startTime:Q,verboseInfo:K}=TL(Z,J,X),{file:G,commandArguments:W,options:H}=sL(Z,J,X),V=r21(H),F=yp(V,K);return{file:G,commandArguments:W,command:Y,escapedCommand:$,startTime:Q,verboseInfo:K,options:V,fileDescriptors:F}},r21=({timeout:Z,signal:J,...X})=>{if(J!==void 0)throw new TypeError('The "signal" option has been renamed to "cancelSignal" instead.');return{...X,timeoutDuration:Z}},t21=({file:Z,commandArguments:J,options:X,startTime:Y,verboseInfo:$,command:Q,escapedCommand:K,fileDescriptors:G})=>{let W;try{W=s21(Z,J,X)}catch(U){return Ap({error:U,command:Q,escapedCommand:K,fileDescriptors:G,options:X,startTime:Y,verboseInfo:$})}let H=new AbortController;a21(Number.POSITIVE_INFINITY,H.signal);let V=[...W.stdio];np(W,G,H),tp(W,X,H);let F={},z=j7();W.kill=Gc.bind(void 0,{kill:W.kill.bind(W),options:X,onInternalError:z,context:F,controller:H}),W.all=Fi(W,X),ki(W,X),_p(W,X);let q=e21({subprocess:W,options:X,startTime:Y,verboseInfo:$,fileDescriptors:G,originalStreams:V,command:Q,escapedCommand:K,context:F,onInternalError:z,controller:H});return{subprocess:W,promise:q}},e21=async({subprocess:Z,options:J,startTime:X,verboseInfo:Y,fileDescriptors:$,originalStreams:Q,command:K,escapedCommand:G,context:W,onInternalError:H,controller:V})=>{let[F,[z,q],U,B,L]=await ji({subprocess:Z,options:J,context:W,verboseInfo:Y,fileDescriptors:$,originalStreams:Q,onInternalError:H,controller:V});V.abort(),H.resolve();let w=U.map((R,D)=>DZ(R,J,D)),O=DZ(B,J,"all"),M=Zw1({errorInfo:F,exitCode:z,signal:q,stdio:w,all:O,ipcOutput:L,context:W,options:J,command:K,escapedCommand:G,startTime:X});return hK(M,Y,J)},Zw1=({errorInfo:Z,exitCode:J,signal:X,stdio:Y,all:$,ipcOutput:Q,context:K,options:G,command:W,escapedCommand:H,startTime:V})=>("error"in Z)?UH({error:Z.error,command:W,escapedCommand:H,timedOut:K.terminationReason==="timeout",isCanceled:K.terminationReason==="cancel"||K.terminationReason==="gracefulCancel",isGracefullyCanceled:K.terminationReason==="gracefulCancel",isMaxBuffer:Z.error instanceof NZ,isForcefullyTerminated:K.isForcefullyTerminated,exitCode:J,signal:X,stdio:Y,all:$,ipcOutput:Q,options:G,startTime:V,isSync:!1}):$B({command:W,escapedCommand:H,stdio:Y,all:$,ipcOutput:Q,options:G,startTime:V});var PB=(Z,J)=>{let X=Object.fromEntries(Object.entries(J).map(([Y,$])=>[Y,Jw1(Y,Z[Y],$)]));return{...Z,...X}},Jw1=(Z,J,X)=>{if(Xw1.has(Z)&&P8(J)&&P8(X))return{...J,...X};return X},Xw1=new Set(["env",...WD]);var uJ=(Z,J,X,Y)=>{let $=(K,G,W)=>uJ(K,G,X,W),Q=(...K)=>Yw1({mapArguments:Z,deepOptions:X,boundOptions:J,setBoundExeca:Y,createNested:$},...K);if(Y!==void 0)Y(Q,$,J);return Q},Yw1=({mapArguments:Z,deepOptions:J={},boundOptions:X={},setBoundExeca:Y,createNested:$},Q,...K)=>{if(P8(Q))return $(Z,PB(X,Q),Y);let{file:G,commandArguments:W,options:H,isSync:V}=$w1({mapArguments:Z,firstArgument:Q,nextArguments:K,deepOptions:J,boundOptions:X});return V?Dp(G,W,H):_i(G,W,H,$)},$w1=({mapArguments:Z,firstArgument:J,nextArguments:X,deepOptions:Y,boundOptions:$})=>{let Q=yu(J)?bu(J,X):[J,...X],[K,G,W]=LL(...Q),H=PB(PB(Y,$),W),{file:V=K,commandArguments:F=G,options:z=H,isSync:q=!1}=Z({file:K,commandArguments:G,options:H});return{file:V,commandArguments:F,options:z,isSync:q}};var Si=({file:Z,commandArguments:J})=>Ai(Z,J),vi=({file:Z,commandArguments:J})=>({...Ai(Z,J),isSync:!0}),Ai=(Z,J)=>{if(J.length>0)throw new TypeError(`The command and its arguments must be passed as a single string: ${Z} ${J}.`);let[X,...Y]=Qw1(Z);return{file:X,commandArguments:Y}},Qw1=(Z)=>{if(typeof Z!=="string")throw new TypeError(`The command must be a string: ${String(Z)}.`);let J=Z.trim();if(J==="")return[];let X=[];for(let Y of J.split(Kw1)){let $=X.at(-1);if($&&$.endsWith("\\"))X[X.length-1]=`${$.slice(0,-1)} ${Y}`;else X.push(Y)}return X},Kw1=/ +/g;var xi=(Z,J,X)=>{Z.sync=J(Gw1,X),Z.s=Z.sync},hi=({options:Z})=>fi(Z),Gw1=({options:Z})=>({...fi(Z),isSync:!0}),fi=(Z)=>({options:{...Ww1(Z),...Z}}),Ww1=({input:Z,inputFile:J,stdio:X})=>Z===void 0&&J===void 0&&X===void 0?{stdin:"inherit"}:{},yi={preferLocal:!0};var bi=uJ(()=>({})),ek6=uJ(()=>({isSync:!0})),ZI6=uJ(Si),JI6=uJ(vi),XI6=uJ(lc),YI6=uJ(hi,{},yi,xi),{sendMessage:$I6,getOneMessage:QI6,getEachMessage:KI6,getCancelSignal:GI6}=Sp();var $n=r(oi(),1);var NH=(Z)=>{if(typeof Z!=="string")throw new TypeError("invalid pattern");if(Z.length>65536)throw new TypeError("pattern is too long")};var Bw1={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},PH=(Z)=>Z.replace(/[[\]\\-]/g,"\\$&"),ww1=(Z)=>Z.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),ri=(Z)=>Z.join(""),ti=(Z,J)=>{let X=J;if(Z.charAt(X)!=="[")throw new Error("not in a brace expression");let Y=[],$=[],Q=X+1,K=!1,G=!1,W=!1,H=!1,V=X,F="";Z:while(Q<Z.length){let B=Z.charAt(Q);if((B==="!"||B==="^")&&Q===X+1){H=!0,Q++;continue}if(B==="]"&&K&&!W){V=Q+1;break}if(K=!0,B==="\\"){if(!W){W=!0,Q++;continue}}if(B==="["&&!W){for(let[L,[w,O,M]]of Object.entries(Bw1))if(Z.startsWith(L,Q)){if(F)return["$.",!1,Z.length-X,!0];if(Q+=L.length,M)$.push(w);else Y.push(w);G=G||O;continue Z}}if(W=!1,F){if(B>F)Y.push(PH(F)+"-"+PH(B));else if(B===F)Y.push(PH(B));F="",Q++;continue}if(Z.startsWith("-]",Q+1)){Y.push(PH(B+"-")),Q+=2;continue}if(Z.startsWith("-",Q+1)){F=B,Q+=2;continue}Y.push(PH(B)),Q++}if(V<Q)return["",!1,0,!1];if(!Y.length&&!$.length)return["$.",!1,Z.length-X,!0];if($.length===0&&Y.length===1&&/^\\?.$/.test(Y[0])&&!H){let B=Y[0].length===2?Y[0].slice(-1):Y[0];return[ww1(B),!1,V-X,!1]}let z="["+(H?"^":"")+ri(Y)+"]",q="["+(H?"":"^")+ri($)+"]";return[Y.length&&$.length?"("+z+"|"+q+")":Y.length?z:q,G,V-X,!0]};var _4=(Z,{windowsPathsNoEscape:J=!1}={})=>{return J?Z.replace(/\[([^\/\\])\]/g,"$1"):Z.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1")};var jw1=new Set(["!","?","+","*","@"]),ei=(Z)=>jw1.has(Z),Ow1="(?!(?:^|/)\\.\\.?(?:$|/))",DB="(?!\\.)",Mw1=new Set(["[","."]),Rw1=new Set(["..","."]),Nw1=new Set("().*{}+?[]^$\\!"),Pw1=(Z)=>Z.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),AC="[^/]",Zn=AC+"*?",Jn=AC+"+?";class L6{type;#Z;#J;#Y=!1;#X=[];#$;#V;#F;#G=!1;#W;#H;#z=!1;constructor(Z,J,X={}){if(this.type=Z,Z)this.#J=!0;if(this.#$=J,this.#Z=this.#$?this.#$.#Z:this,this.#W=this.#Z===this?X:this.#Z.#W,this.#F=this.#Z===this?[]:this.#Z.#F,Z==="!"&&!this.#Z.#G)this.#F.push(this);this.#V=this.#$?this.#$.#X.length:0}get hasMagic(){if(this.#J!==void 0)return this.#J;for(let Z of this.#X){if(typeof Z==="string")continue;if(Z.type||Z.hasMagic)return this.#J=!0}return this.#J}toString(){if(this.#H!==void 0)return this.#H;if(!this.type)return this.#H=this.#X.map((Z)=>String(Z)).join("");else return this.#H=this.type+"("+this.#X.map((Z)=>String(Z)).join("|")+")"}#Q(){if(this!==this.#Z)throw new Error("should only call on root");if(this.#G)return this;this.toString(),this.#G=!0;let Z;while(Z=this.#F.pop()){if(Z.type!=="!")continue;let J=Z,X=J.#$;while(X){for(let Y=J.#V+1;!X.type&&Y<X.#X.length;Y++)for(let $ of Z.#X){if(typeof $==="string")throw new Error("string part in extglob AST??");$.copyIn(X.#X[Y])}J=X,X=J.#$}}return this}push(...Z){for(let J of Z){if(J==="")continue;if(typeof J!=="string"&&!(J instanceof L6&&J.#$===this))throw new Error("invalid part: "+J);this.#X.push(J)}}toJSON(){let Z=this.type===null?this.#X.slice().map((J)=>typeof J==="string"?J:J.toJSON()):[this.type,...this.#X.map((J)=>J.toJSON())];if(this.isStart()&&!this.type)Z.unshift([]);if(this.isEnd()&&(this===this.#Z||this.#Z.#G&&this.#$?.type==="!"))Z.push({});return Z}isStart(){if(this.#Z===this)return!0;if(!this.#$?.isStart())return!1;if(this.#V===0)return!0;let Z=this.#$;for(let J=0;J<this.#V;J++){let X=Z.#X[J];if(!(X instanceof L6&&X.type==="!"))return!1}return!0}isEnd(){if(this.#Z===this)return!0;if(this.#$?.type==="!")return!0;if(!this.#$?.isEnd())return!1;if(!this.type)return this.#$?.isEnd();let Z=this.#$?this.#$.#X.length:0;return this.#V===Z-1}copyIn(Z){if(typeof Z==="string")this.push(Z);else this.push(Z.clone(this))}clone(Z){let J=new L6(this.type,Z);for(let X of this.#X)J.copyIn(X);return J}static#U(Z,J,X,Y){let $=!1,Q=!1,K=-1,G=!1;if(J.type===null){let z=X,q="";while(z<Z.length){let U=Z.charAt(z++);if($||U==="\\"){$=!$,q+=U;continue}if(Q){if(z===K+1){if(U==="^"||U==="!")G=!0}else if(U==="]"&&!(z===K+2&&G))Q=!1;q+=U;continue}else if(U==="["){Q=!0,K=z,G=!1,q+=U;continue}if(!Y.noext&&ei(U)&&Z.charAt(z)==="("){J.push(q),q="";let B=new L6(U,J);z=L6.#U(Z,B,z,Y),J.push(B);continue}q+=U}return J.push(q),z}let W=X+1,H=new L6(null,J),V=[],F="";while(W<Z.length){let z=Z.charAt(W++);if($||z==="\\"){$=!$,F+=z;continue}if(Q){if(W===K+1){if(z==="^"||z==="!")G=!0}else if(z==="]"&&!(W===K+2&&G))Q=!1;F+=z;continue}else if(z==="["){Q=!0,K=W,G=!1,F+=z;continue}if(ei(z)&&Z.charAt(W)==="("){H.push(F),F="";let q=new L6(z,H);H.push(q),W=L6.#U(Z,q,W,Y);continue}if(z==="|"){H.push(F),F="",V.push(H),H=new L6(null,J);continue}if(z===")"){if(F===""&&J.#X.length===0)J.#z=!0;return H.push(F),F="",J.push(...V,H),W}F+=z}return J.type=null,J.#J=void 0,J.#X=[Z.substring(X-1)],W}static fromGlob(Z,J={}){let X=new L6(null,void 0,J);return L6.#U(Z,X,0,J),X}toMMPattern(){if(this!==this.#Z)return this.#Z.toMMPattern();let Z=this.toString(),[J,X,Y,$]=this.toRegExpSource();if(!(Y||this.#J||this.#W.nocase&&!this.#W.nocaseMagicOnly&&Z.toUpperCase()!==Z.toLowerCase()))return X;let K=(this.#W.nocase?"i":"")+($?"u":"");return Object.assign(new RegExp(`^${J}$`,K),{_src:J,_glob:Z})}get options(){return this.#W}toRegExpSource(Z){let J=Z??!!this.#W.dot;if(this.#Z===this)this.#Q();if(!this.type){let G=this.isStart()&&this.isEnd(),W=this.#X.map((z)=>{let[q,U,B,L]=typeof z==="string"?L6.#L(z,this.#J,G):z.toRegExpSource(Z);return this.#J=this.#J||B,this.#Y=this.#Y||L,q}).join(""),H="";if(this.isStart()){if(typeof this.#X[0]==="string"){if(!(this.#X.length===1&&Rw1.has(this.#X[0]))){let q=Mw1,U=J&&q.has(W.charAt(0))||W.startsWith("\\.")&&q.has(W.charAt(2))||W.startsWith("\\.\\.")&&q.has(W.charAt(4)),B=!J&&!Z&&q.has(W.charAt(0));H=U?Ow1:B?DB:""}}}let V="";if(this.isEnd()&&this.#Z.#G&&this.#$?.type==="!")V="(?:$|\\/)";return[H+W+V,_4(W),this.#J=!!this.#J,this.#Y]}let X=this.type==="*"||this.type==="+",Y=this.type==="!"?"(?:(?!(?:":"(?:",$=this.#B(J);if(this.isStart()&&this.isEnd()&&!$&&this.type!=="!"){let G=this.toString();return this.#X=[G],this.type=null,this.#J=void 0,[G,_4(this.toString()),!1,!1]}let Q=!X||Z||J||!DB?"":this.#B(!0);if(Q===$)Q="";if(Q)$=`(?:${$})(?:${Q})*?`;let K="";if(this.type==="!"&&this.#z)K=(this.isStart()&&!J?DB:"")+Jn;else{let G=this.type==="!"?"))"+(this.isStart()&&!J&&!Z?DB:"")+Zn+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&Q?")":this.type==="*"&&Q?")?":`)${this.type}`;K=Y+$+G}return[K,_4($),this.#J=!!this.#J,this.#Y]}#B(Z){return this.#X.map((J)=>{if(typeof J==="string")throw new Error("string type in extglob ast??");let[X,Y,$,Q]=J.toRegExpSource(Z);return this.#Y=this.#Y||Q,X}).filter((J)=>!(this.isStart()&&this.isEnd())||!!J).join("|")}static#L(Z,J,X=!1){let Y=!1,$="",Q=!1;for(let K=0;K<Z.length;K++){let G=Z.charAt(K);if(Y){Y=!1,$+=(Nw1.has(G)?"\\":"")+G;continue}if(G==="\\"){if(K===Z.length-1)$+="\\\\";else Y=!0;continue}if(G==="["){let[W,H,V,F]=ti(Z,K);if(V){$+=W,Q=Q||H,K+=V-1,J=J||F;continue}}if(G==="*"){if(X&&Z==="*")$+=Jn;else $+=Zn;J=!0;continue}if(G==="?"){$+=AC,J=!0;continue}$+=Pw1(G)}return[$,_4(Z),!!J,Q]}}var gK=(Z,{windowsPathsNoEscape:J=!1}={})=>{return J?Z.replace(/[?*()[\]]/g,"[$&]"):Z.replace(/[?*()[\]\\]/g,"\\$&")};var a6=(Z,J,X={})=>{if(NH(J),!X.nocomment&&J.charAt(0)==="#")return!1;return new A9(J,X).match(Z)},Dw1=/^\*+([^+@!?\*\[\(]*)$/,Cw1=(Z)=>(J)=>!J.startsWith(".")&&J.endsWith(Z),Tw1=(Z)=>(J)=>J.endsWith(Z),Ew1=(Z)=>{return Z=Z.toLowerCase(),(J)=>!J.startsWith(".")&&J.toLowerCase().endsWith(Z)},kw1=(Z)=>{return Z=Z.toLowerCase(),(J)=>J.toLowerCase().endsWith(Z)},Iw1=/^\*+\.\*+$/,_w1=(Z)=>!Z.startsWith(".")&&Z.includes("."),Sw1=(Z)=>Z!=="."&&Z!==".."&&Z.includes("."),vw1=/^\.\*+$/,Aw1=(Z)=>Z!=="."&&Z!==".."&&Z.startsWith("."),xw1=/^\*+$/,hw1=(Z)=>Z.length!==0&&!Z.startsWith("."),fw1=(Z)=>Z.length!==0&&Z!=="."&&Z!=="..",yw1=/^\?+([^+@!?\*\[\(]*)?$/,bw1=([Z,J=""])=>{let X=Qn([Z]);if(!J)return X;return J=J.toLowerCase(),(Y)=>X(Y)&&Y.toLowerCase().endsWith(J)},gw1=([Z,J=""])=>{let X=Kn([Z]);if(!J)return X;return J=J.toLowerCase(),(Y)=>X(Y)&&Y.toLowerCase().endsWith(J)},mw1=([Z,J=""])=>{let X=Kn([Z]);return!J?X:(Y)=>X(Y)&&Y.endsWith(J)},uw1=([Z,J=""])=>{let X=Qn([Z]);return!J?X:(Y)=>X(Y)&&Y.endsWith(J)},Qn=([Z])=>{let J=Z.length;return(X)=>X.length===J&&!X.startsWith(".")},Kn=([Z])=>{let J=Z.length;return(X)=>X.length===J&&X!=="."&&X!==".."},Gn=typeof process==="object"&&process?typeof process.env==="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",Xn={win32:{sep:"\\"},posix:{sep:"/"}},dw1=Gn==="win32"?Xn.win32.sep:Xn.posix.sep;a6.sep=dw1;var B6=Symbol("globstar **");a6.GLOBSTAR=B6;var cw1="[^/]",lw1=cw1+"*?",pw1="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",iw1="(?:(?!(?:\\/|^)\\.).)*?",nw1=(Z,J={})=>(X)=>a6(X,Z,J);a6.filter=nw1;var v9=(Z,J={})=>Object.assign({},Z,J),aw1=(Z)=>{if(!Z||typeof Z!=="object"||!Object.keys(Z).length)return a6;let J=a6;return Object.assign((Y,$,Q={})=>J(Y,$,v9(Z,Q)),{Minimatch:class Y extends J.Minimatch{constructor($,Q={}){super($,v9(Z,Q))}static defaults($){return J.defaults(v9(Z,$)).Minimatch}},AST:class Y extends J.AST{constructor($,Q,K={}){super($,Q,v9(Z,K))}static fromGlob($,Q={}){return J.AST.fromGlob($,v9(Z,Q))}},unescape:(Y,$={})=>J.unescape(Y,v9(Z,$)),escape:(Y,$={})=>J.escape(Y,v9(Z,$)),filter:(Y,$={})=>J.filter(Y,v9(Z,$)),defaults:(Y)=>J.defaults(v9(Z,Y)),makeRe:(Y,$={})=>J.makeRe(Y,v9(Z,$)),braceExpand:(Y,$={})=>J.braceExpand(Y,v9(Z,$)),match:(Y,$,Q={})=>J.match(Y,$,v9(Z,Q)),sep:J.sep,GLOBSTAR:B6})};a6.defaults=aw1;var Wn=(Z,J={})=>{if(NH(Z),J.nobrace||!/\{(?:(?!\{).)*\}/.test(Z))return[Z];return $n.default(Z)};a6.braceExpand=Wn;var sw1=(Z,J={})=>new A9(Z,J).makeRe();a6.makeRe=sw1;var ow1=(Z,J,X={})=>{let Y=new A9(J,X);if(Z=Z.filter(($)=>Y.match($)),Y.options.nonull&&!Z.length)Z.push(J);return Z};a6.match=ow1;var Yn=/[?*]|[+@!]\(.*?\)|\[|\]/,rw1=(Z)=>Z.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");class A9{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(Z,J={}){if(NH(Z),J=J||{},this.options=J,this.pattern=Z,this.platform=J.platform||Gn,this.isWindows=this.platform==="win32",this.windowsPathsNoEscape=!!J.windowsPathsNoEscape||J.allowWindowsEscape===!1,this.windowsPathsNoEscape)this.pattern=this.pattern.replace(/\\/g,"/");this.preserveMultipleSlashes=!!J.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!J.nonegate,this.comment=!1,this.empty=!1,this.partial=!!J.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=J.windowsNoMagicRoot!==void 0?J.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let Z of this.set)for(let J of Z)if(typeof J!=="string")return!0;return!1}debug(...Z){}make(){let Z=this.pattern,J=this.options;if(!J.nocomment&&Z.charAt(0)==="#"){this.comment=!0;return}if(!Z){this.empty=!0;return}if(this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],J.debug)this.debug=(...$)=>console.error(...$);this.debug(this.pattern,this.globSet);let X=this.globSet.map(($)=>this.slashSplit($));this.globParts=this.preprocess(X),this.debug(this.pattern,this.globParts);let Y=this.globParts.map(($,Q,K)=>{if(this.isWindows&&this.windowsNoMagicRoot){let G=$[0]===""&&$[1]===""&&($[2]==="?"||!Yn.test($[2]))&&!Yn.test($[3]),W=/^[a-z]:/i.test($[0]);if(G)return[...$.slice(0,4),...$.slice(4).map((H)=>this.parse(H))];else if(W)return[$[0],...$.slice(1).map((H)=>this.parse(H))]}return $.map((G)=>this.parse(G))});if(this.debug(this.pattern,Y),this.set=Y.filter(($)=>$.indexOf(!1)===-1),this.isWindows)for(let $=0;$<this.set.length;$++){let Q=this.set[$];if(Q[0]===""&&Q[1]===""&&this.globParts[$][2]==="?"&&typeof Q[3]==="string"&&/^[a-z]:$/i.test(Q[3]))Q[2]="?"}this.debug(this.pattern,this.set)}preprocess(Z){if(this.options.noglobstar){for(let X=0;X<Z.length;X++)for(let Y=0;Y<Z[X].length;Y++)if(Z[X][Y]==="**")Z[X][Y]="*"}let{optimizationLevel:J=1}=this.options;if(J>=2)Z=this.firstPhasePreProcess(Z),Z=this.secondPhasePreProcess(Z);else if(J>=1)Z=this.levelOneOptimize(Z);else Z=this.adjascentGlobstarOptimize(Z);return Z}adjascentGlobstarOptimize(Z){return Z.map((J)=>{let X=-1;while((X=J.indexOf("**",X+1))!==-1){let Y=X;while(J[Y+1]==="**")Y++;if(Y!==X)J.splice(X,Y-X)}return J})}levelOneOptimize(Z){return Z.map((J)=>{return J=J.reduce((X,Y)=>{let $=X[X.length-1];if(Y==="**"&&$==="**")return X;if(Y===".."){if($&&$!==".."&&$!=="."&&$!=="**")return X.pop(),X}return X.push(Y),X},[]),J.length===0?[""]:J})}levelTwoFileOptimize(Z){if(!Array.isArray(Z))Z=this.slashSplit(Z);let J=!1;do{if(J=!1,!this.preserveMultipleSlashes){for(let Y=1;Y<Z.length-1;Y++){let $=Z[Y];if(Y===1&&$===""&&Z[0]==="")continue;if($==="."||$==="")J=!0,Z.splice(Y,1),Y--}if(Z[0]==="."&&Z.length===2&&(Z[1]==="."||Z[1]===""))J=!0,Z.pop()}let X=0;while((X=Z.indexOf("..",X+1))!==-1){let Y=Z[X-1];if(Y&&Y!=="."&&Y!==".."&&Y!=="**")J=!0,Z.splice(X-1,2),X-=2}}while(J);return Z.length===0?[""]:Z}firstPhasePreProcess(Z){let J=!1;do{J=!1;for(let X of Z){let Y=-1;while((Y=X.indexOf("**",Y+1))!==-1){let Q=Y;while(X[Q+1]==="**")Q++;if(Q>Y)X.splice(Y+1,Q-Y);let K=X[Y+1],G=X[Y+2],W=X[Y+3];if(K!=="..")continue;if(!G||G==="."||G===".."||!W||W==="."||W==="..")continue;J=!0,X.splice(Y,1);let H=X.slice(0);H[Y]="**",Z.push(H),Y--}if(!this.preserveMultipleSlashes){for(let Q=1;Q<X.length-1;Q++){let K=X[Q];if(Q===1&&K===""&&X[0]==="")continue;if(K==="."||K==="")J=!0,X.splice(Q,1),Q--}if(X[0]==="."&&X.length===2&&(X[1]==="."||X[1]===""))J=!0,X.pop()}let $=0;while(($=X.indexOf("..",$+1))!==-1){let Q=X[$-1];if(Q&&Q!=="."&&Q!==".."&&Q!=="**"){J=!0;let G=$===1&&X[$+1]==="**"?["."]:[];if(X.splice($-1,2,...G),X.length===0)X.push("");$-=2}}}}while(J);return Z}secondPhasePreProcess(Z){for(let J=0;J<Z.length-1;J++)for(let X=J+1;X<Z.length;X++){let Y=this.partsMatch(Z[J],Z[X],!this.preserveMultipleSlashes);if(Y){Z[J]=[],Z[X]=Y;break}}return Z.filter((J)=>J.length)}partsMatch(Z,J,X=!1){let Y=0,$=0,Q=[],K="";while(Y<Z.length&&$<J.length)if(Z[Y]===J[$])Q.push(K==="b"?J[$]:Z[Y]),Y++,$++;else if(X&&Z[Y]==="**"&&J[$]===Z[Y+1])Q.push(Z[Y]),Y++;else if(X&&J[$]==="**"&&Z[Y]===J[$+1])Q.push(J[$]),$++;else if(Z[Y]==="*"&&J[$]&&(this.options.dot||!J[$].startsWith("."))&&J[$]!=="**"){if(K==="b")return!1;K="a",Q.push(Z[Y]),Y++,$++}else if(J[$]==="*"&&Z[Y]&&(this.options.dot||!Z[Y].startsWith("."))&&Z[Y]!=="**"){if(K==="a")return!1;K="b",Q.push(J[$]),Y++,$++}else return!1;return Z.length===J.length&&Q}parseNegate(){if(this.nonegate)return;let Z=this.pattern,J=!1,X=0;for(let Y=0;Y<Z.length&&Z.charAt(Y)==="!";Y++)J=!J,X++;if(X)this.pattern=Z.slice(X);this.negate=J}matchOne(Z,J,X=!1){let Y=this.options;if(this.isWindows){let U=typeof Z[0]==="string"&&/^[a-z]:$/i.test(Z[0]),B=!U&&Z[0]===""&&Z[1]===""&&Z[2]==="?"&&/^[a-z]:$/i.test(Z[3]),L=typeof J[0]==="string"&&/^[a-z]:$/i.test(J[0]),w=!L&&J[0]===""&&J[1]===""&&J[2]==="?"&&typeof J[3]==="string"&&/^[a-z]:$/i.test(J[3]),O=B?3:U?0:void 0,M=w?3:L?0:void 0;if(typeof O==="number"&&typeof M==="number"){let[R,D]=[Z[O],J[M]];if(R.toLowerCase()===D.toLowerCase()){if(J[M]=R,M>O)J=J.slice(M);else if(O>M)Z=Z.slice(O)}}}let{optimizationLevel:$=1}=this.options;if($>=2)Z=this.levelTwoFileOptimize(Z);this.debug("matchOne",this,{file:Z,pattern:J}),this.debug("matchOne",Z.length,J.length);for(var Q=0,K=0,G=Z.length,W=J.length;Q<G&&K<W;Q++,K++){this.debug("matchOne loop");var H=J[K],V=Z[Q];if(this.debug(J,H,V),H===!1)return!1;if(H===B6){this.debug("GLOBSTAR",[J,H,V]);var F=Q,z=K+1;if(z===W){this.debug("** at the end");for(;Q<G;Q++)if(Z[Q]==="."||Z[Q]===".."||!Y.dot&&Z[Q].charAt(0)===".")return!1;return!0}while(F<G){var q=Z[F];if(this.debug(`
|
|
413
413
|
globstar while`,Z,F,J,z,q),this.matchOne(Z.slice(F),J.slice(z),X))return this.debug("globstar found match!",F,G,q),!0;else{if(q==="."||q===".."||!Y.dot&&q.charAt(0)==="."){this.debug("dot detected!",Z,F,J,z);break}this.debug("globstar swallow a segment, and continue"),F++}}if(X){if(this.debug(`
|
|
414
414
|
>>> no match, partial?`,Z,F,J,z),F===G)return!0}return!1}let U;if(typeof H==="string")U=V===H,this.debug("string match",H,V,U);else U=H.test(V),this.debug("pattern match",H,V,U);if(!U)return!1}if(Q===G&&K===W)return!0;else if(Q===G)return X;else if(K===W)return Q===G-1&&Z[Q]==="";else throw new Error("wtf?")}braceExpand(){return Wn(this.pattern,this.options)}parse(Z){NH(Z);let J=this.options;if(Z==="**")return B6;if(Z==="")return"";let X,Y=null;if(X=Z.match(xw1))Y=J.dot?fw1:hw1;else if(X=Z.match(Dw1))Y=(J.nocase?J.dot?kw1:Ew1:J.dot?Tw1:Cw1)(X[1]);else if(X=Z.match(yw1))Y=(J.nocase?J.dot?gw1:bw1:J.dot?mw1:uw1)(X);else if(X=Z.match(Iw1))Y=J.dot?Sw1:_w1;else if(X=Z.match(vw1))Y=Aw1;let $=L6.fromGlob(Z,this.options).toMMPattern();if(Y&&typeof $==="object")Reflect.defineProperty($,"test",{value:Y});return $}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let Z=this.set;if(!Z.length)return this.regexp=!1,this.regexp;let J=this.options,X=J.noglobstar?lw1:J.dot?pw1:iw1,Y=new Set(J.nocase?["i"]:[]),$=Z.map((G)=>{let W=G.map((H)=>{if(H instanceof RegExp)for(let V of H.flags.split(""))Y.add(V);return typeof H==="string"?rw1(H):H===B6?B6:H._src});return W.forEach((H,V)=>{let F=W[V+1],z=W[V-1];if(H!==B6||z===B6)return;if(z===void 0)if(F!==void 0&&F!==B6)W[V+1]="(?:\\/|"+X+"\\/)?"+F;else W[V]=X;else if(F===void 0)W[V-1]=z+"(?:\\/|"+X+")?";else if(F!==B6)W[V-1]=z+"(?:\\/|\\/"+X+"\\/)"+F,W[V+1]=B6}),W.filter((H)=>H!==B6).join("/")}).join("|"),[Q,K]=Z.length>1?["(?:",")"]:["",""];if($="^"+Q+$+K+"$",this.negate)$="^(?!"+$+").+$";try{this.regexp=new RegExp($,[...Y].join(""))}catch(G){this.regexp=!1}return this.regexp}slashSplit(Z){if(this.preserveMultipleSlashes)return Z.split("/");else if(this.isWindows&&/^\/\/[^\/]+/.test(Z))return["",...Z.split(/\/+/)];else return Z.split(/\/+/)}match(Z,J=this.partial){if(this.debug("match",Z,this.pattern),this.comment)return!1;if(this.empty)return Z==="";if(Z==="/"&&J)return!0;let X=this.options;if(this.isWindows)Z=Z.split("\\").join("/");let Y=this.slashSplit(Z);this.debug(this.pattern,"split",Y);let $=this.set;this.debug(this.pattern,"set",$);let Q=Y[Y.length-1];if(!Q)for(let K=Y.length-2;!Q&&K>=0;K--)Q=Y[K];for(let K=0;K<$.length;K++){let G=$[K],W=Y;if(X.matchBase&&G.length===1)W=[Q];if(this.matchOne(W,G,J)){if(X.flipNegate)return!0;return!this.negate}}if(X.flipNegate)return!1;return this.negate}static defaults(Z){return a6.defaults(Z).Minimatch}}a6.AST=L6;a6.Minimatch=A9;a6.escape=gK;a6.unescape=_4;import{fileURLToPath as Ij1}from"node:url";var mK=typeof performance==="object"&&performance&&typeof performance.now==="function"?performance:Date,Vn=new Set,xC=typeof process==="object"&&!!process?process:{},zn=(Z,J,X,Y)=>{typeof xC.emitWarning==="function"?xC.emitWarning(Z,J,X,Y):console.error(`[${X}] ${J}: ${Z}`)},CB=globalThis.AbortController,Hn=globalThis.AbortSignal;if(typeof CB==="undefined"){Hn=class X{onabort;_onabort=[];reason;aborted=!1;addEventListener(Y,$){this._onabort.push($)}},CB=class X{constructor(){J()}signal=new Hn;abort(Y){if(this.signal.aborted)return;this.signal.reason=Y,this.signal.aborted=!0;for(let $ of this.signal._onabort)$(Y);this.signal.onabort?.(Y)}};let Z=xC.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",J=()=>{if(!Z)return;Z=!1,zn("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",J)}}var tw1=(Z)=>!Vn.has(Z),TI6=Symbol("type"),dJ=(Z)=>Z&&Z===Math.floor(Z)&&Z>0&&isFinite(Z),Fn=(Z)=>!dJ(Z)?null:Z<=Math.pow(2,8)?Uint8Array:Z<=Math.pow(2,16)?Uint16Array:Z<=Math.pow(2,32)?Uint32Array:Z<=Number.MAX_SAFE_INTEGER?DH:null;class DH extends Array{constructor(Z){super(Z);this.fill(0)}}class uK{heap;length;static#Z=!1;static create(Z){let J=Fn(Z);if(!J)return[];uK.#Z=!0;let X=new uK(Z,J);return uK.#Z=!1,X}constructor(Z,J){if(!uK.#Z)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new J(Z),this.length=0}push(Z){this.heap[this.length++]=Z}pop(){return this.heap[--this.length]}}class CH{#Z;#J;#Y;#X;#$;#V;#F;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#G;#W;#H;#z;#Q;#U;#B;#L;#j;#E;#O;#k;#N;#R;#M;#C;#w;#_;static unsafeExposeInternals(Z){return{starts:Z.#N,ttls:Z.#R,sizes:Z.#k,keyMap:Z.#H,keyList:Z.#z,valList:Z.#Q,next:Z.#U,prev:Z.#B,get head(){return Z.#L},get tail(){return Z.#j},free:Z.#E,isBackgroundFetch:(J)=>Z.#q(J),backgroundFetch:(J,X,Y,$)=>Z.#h(J,X,Y,$),moveToTail:(J)=>Z.#b(J),indexes:(J)=>Z.#T(J),rindexes:(J)=>Z.#I(J),isStale:(J)=>Z.#D(J)}}get max(){return this.#Z}get maxSize(){return this.#J}get calculatedSize(){return this.#W}get size(){return this.#G}get fetchMethod(){return this.#V}get memoMethod(){return this.#F}get dispose(){return this.#Y}get onInsert(){return this.#X}get disposeAfter(){return this.#$}constructor(Z){let{max:J=0,ttl:X,ttlResolution:Y=1,ttlAutopurge:$,updateAgeOnGet:Q,updateAgeOnHas:K,allowStale:G,dispose:W,onInsert:H,disposeAfter:V,noDisposeOnSet:F,noUpdateTTL:z,maxSize:q=0,maxEntrySize:U=0,sizeCalculation:B,fetchMethod:L,memoMethod:w,noDeleteOnFetchRejection:O,noDeleteOnStaleGet:M,allowStaleOnFetchRejection:R,allowStaleOnFetchAbort:D,ignoreFetchAbort:N}=Z;if(J!==0&&!dJ(J))throw new TypeError("max option must be a nonnegative integer");let C=J?Fn(J):Array;if(!C)throw new Error("invalid max value: "+J);if(this.#Z=J,this.#J=q,this.maxEntrySize=U||this.#J,this.sizeCalculation=B,this.sizeCalculation){if(!this.#J&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!=="function")throw new TypeError("sizeCalculation set to non-function")}if(w!==void 0&&typeof w!=="function")throw new TypeError("memoMethod must be a function if defined");if(this.#F=w,L!==void 0&&typeof L!=="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#V=L,this.#C=!!L,this.#H=new Map,this.#z=new Array(J).fill(void 0),this.#Q=new Array(J).fill(void 0),this.#U=new C(J),this.#B=new C(J),this.#L=0,this.#j=0,this.#E=uK.create(J),this.#G=0,this.#W=0,typeof W==="function")this.#Y=W;if(typeof H==="function")this.#X=H;if(typeof V==="function")this.#$=V,this.#O=[];else this.#$=void 0,this.#O=void 0;if(this.#M=!!this.#Y,this.#_=!!this.#X,this.#w=!!this.#$,this.noDisposeOnSet=!!F,this.noUpdateTTL=!!z,this.noDeleteOnFetchRejection=!!O,this.allowStaleOnFetchRejection=!!R,this.allowStaleOnFetchAbort=!!D,this.ignoreFetchAbort=!!N,this.maxEntrySize!==0){if(this.#J!==0){if(!dJ(this.#J))throw new TypeError("maxSize must be a positive integer if specified")}if(!dJ(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#m()}if(this.allowStale=!!G,this.noDeleteOnStaleGet=!!M,this.updateAgeOnGet=!!Q,this.updateAgeOnHas=!!K,this.ttlResolution=dJ(Y)||Y===0?Y:1,this.ttlAutopurge=!!$,this.ttl=X||0,this.ttl){if(!dJ(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#K()}if(this.#Z===0&&this.ttl===0&&this.#J===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#Z&&!this.#J){if(tw1("LRU_CACHE_UNBOUNDED"))Vn.add("LRU_CACHE_UNBOUNDED"),zn("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning","LRU_CACHE_UNBOUNDED",CH)}}getRemainingTTL(Z){return this.#H.has(Z)?1/0:0}#K(){let Z=new DH(this.#Z),J=new DH(this.#Z);this.#R=Z,this.#N=J,this.#S=($,Q,K=mK.now())=>{if(J[$]=Q!==0?K:0,Z[$]=Q,Q!==0&&this.ttlAutopurge){let G=setTimeout(()=>{if(this.#D($))this.#v(this.#z[$],"expire")},Q+1);if(G.unref)G.unref()}},this.#A=($)=>{J[$]=Z[$]!==0?mK.now():0},this.#P=($,Q)=>{if(Z[Q]){let K=Z[Q],G=J[Q];if(!K||!G)return;$.ttl=K,$.start=G,$.now=X||Y();let W=$.now-G;$.remainingTTL=K-W}};let X=0,Y=()=>{let $=mK.now();if(this.ttlResolution>0){X=$;let Q=setTimeout(()=>X=0,this.ttlResolution);if(Q.unref)Q.unref()}return $};this.getRemainingTTL=($)=>{let Q=this.#H.get($);if(Q===void 0)return 0;let K=Z[Q],G=J[Q];if(!K||!G)return 1/0;let W=(X||Y())-G;return K-W},this.#D=($)=>{let Q=J[$],K=Z[$];return!!K&&!!Q&&(X||Y())-Q>K}}#A=()=>{};#P=()=>{};#S=()=>{};#D=()=>!1;#m(){let Z=new DH(this.#Z);this.#W=0,this.#k=Z,this.#x=(J)=>{this.#W-=Z[J],Z[J]=0},this.#u=(J,X,Y,$)=>{if(this.#q(X))return 0;if(!dJ(Y))if($){if(typeof $!=="function")throw new TypeError("sizeCalculation must be a function");if(Y=$(X,J),!dJ(Y))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return Y},this.#f=(J,X,Y)=>{if(Z[J]=X,this.#J){let $=this.#J-Z[J];while(this.#W>$)this.#y(!0)}if(this.#W+=Z[J],Y)Y.entrySize=X,Y.totalCalculatedSize=this.#W}}#x=(Z)=>{};#f=(Z,J,X)=>{};#u=(Z,J,X,Y)=>{if(X||Y)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#T({allowStale:Z=this.allowStale}={}){if(this.#G)for(let J=this.#j;;){if(!this.#d(J))break;if(Z||!this.#D(J))yield J;if(J===this.#L)break;else J=this.#B[J]}}*#I({allowStale:Z=this.allowStale}={}){if(this.#G)for(let J=this.#L;;){if(!this.#d(J))break;if(Z||!this.#D(J))yield J;if(J===this.#j)break;else J=this.#U[J]}}#d(Z){return Z!==void 0&&this.#H.get(this.#z[Z])===Z}*entries(){for(let Z of this.#T())if(this.#Q[Z]!==void 0&&this.#z[Z]!==void 0&&!this.#q(this.#Q[Z]))yield[this.#z[Z],this.#Q[Z]]}*rentries(){for(let Z of this.#I())if(this.#Q[Z]!==void 0&&this.#z[Z]!==void 0&&!this.#q(this.#Q[Z]))yield[this.#z[Z],this.#Q[Z]]}*keys(){for(let Z of this.#T()){let J=this.#z[Z];if(J!==void 0&&!this.#q(this.#Q[Z]))yield J}}*rkeys(){for(let Z of this.#I()){let J=this.#z[Z];if(J!==void 0&&!this.#q(this.#Q[Z]))yield J}}*values(){for(let Z of this.#T())if(this.#Q[Z]!==void 0&&!this.#q(this.#Q[Z]))yield this.#Q[Z]}*rvalues(){for(let Z of this.#I())if(this.#Q[Z]!==void 0&&!this.#q(this.#Q[Z]))yield this.#Q[Z]}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(Z,J={}){for(let X of this.#T()){let Y=this.#Q[X],$=this.#q(Y)?Y.__staleWhileFetching:Y;if($===void 0)continue;if(Z($,this.#z[X],this))return this.get(this.#z[X],J)}}forEach(Z,J=this){for(let X of this.#T()){let Y=this.#Q[X],$=this.#q(Y)?Y.__staleWhileFetching:Y;if($===void 0)continue;Z.call(J,$,this.#z[X],this)}}rforEach(Z,J=this){for(let X of this.#I()){let Y=this.#Q[X],$=this.#q(Y)?Y.__staleWhileFetching:Y;if($===void 0)continue;Z.call(J,$,this.#z[X],this)}}purgeStale(){let Z=!1;for(let J of this.#I({allowStale:!0}))if(this.#D(J))this.#v(this.#z[J],"expire"),Z=!0;return Z}info(Z){let J=this.#H.get(Z);if(J===void 0)return;let X=this.#Q[J],Y=this.#q(X)?X.__staleWhileFetching:X;if(Y===void 0)return;let $={value:Y};if(this.#R&&this.#N){let Q=this.#R[J],K=this.#N[J];if(Q&&K){let G=Q-(mK.now()-K);$.ttl=G,$.start=Date.now()}}if(this.#k)$.size=this.#k[J];return $}dump(){let Z=[];for(let J of this.#T({allowStale:!0})){let X=this.#z[J],Y=this.#Q[J],$=this.#q(Y)?Y.__staleWhileFetching:Y;if($===void 0||X===void 0)continue;let Q={value:$};if(this.#R&&this.#N){Q.ttl=this.#R[J];let K=mK.now()-this.#N[J];Q.start=Math.floor(Date.now()-K)}if(this.#k)Q.size=this.#k[J];Z.unshift([X,Q])}return Z}load(Z){this.clear();for(let[J,X]of Z){if(X.start){let Y=Date.now()-X.start;X.start=mK.now()-Y}this.set(J,X.value,X)}}set(Z,J,X={}){if(J===void 0)return this.delete(Z),this;let{ttl:Y=this.ttl,start:$,noDisposeOnSet:Q=this.noDisposeOnSet,sizeCalculation:K=this.sizeCalculation,status:G}=X,{noUpdateTTL:W=this.noUpdateTTL}=X,H=this.#u(Z,J,X.size||0,K);if(this.maxEntrySize&&H>this.maxEntrySize){if(G)G.set="miss",G.maxEntrySizeExceeded=!0;return this.#v(Z,"set"),this}let V=this.#G===0?void 0:this.#H.get(Z);if(V===void 0){if(V=this.#G===0?this.#j:this.#E.length!==0?this.#E.pop():this.#G===this.#Z?this.#y(!1):this.#G,this.#z[V]=Z,this.#Q[V]=J,this.#H.set(Z,V),this.#U[this.#j]=V,this.#B[V]=this.#j,this.#j=V,this.#G++,this.#f(V,H,G),G)G.set="add";if(W=!1,this.#_)this.#X?.(J,Z,"add")}else{this.#b(V);let F=this.#Q[V];if(J!==F){if(this.#C&&this.#q(F)){F.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:z}=F;if(z!==void 0&&!Q){if(this.#M)this.#Y?.(z,Z,"set");if(this.#w)this.#O?.push([z,Z,"set"])}}else if(!Q){if(this.#M)this.#Y?.(F,Z,"set");if(this.#w)this.#O?.push([F,Z,"set"])}if(this.#x(V),this.#f(V,H,G),this.#Q[V]=J,G){G.set="replace";let z=F&&this.#q(F)?F.__staleWhileFetching:F;if(z!==void 0)G.oldValue=z}}else if(G)G.set="update";if(this.#_)this.onInsert?.(J,Z,J===F?"update":"replace")}if(Y!==0&&!this.#R)this.#K();if(this.#R){if(!W)this.#S(V,Y,$);if(G)this.#P(G,V)}if(!Q&&this.#w&&this.#O){let F=this.#O,z;while(z=F?.shift())this.#$?.(...z)}return this}pop(){try{while(this.#G){let Z=this.#Q[this.#L];if(this.#y(!0),this.#q(Z)){if(Z.__staleWhileFetching)return Z.__staleWhileFetching}else if(Z!==void 0)return Z}}finally{if(this.#w&&this.#O){let Z=this.#O,J;while(J=Z?.shift())this.#$?.(...J)}}}#y(Z){let J=this.#L,X=this.#z[J],Y=this.#Q[J];if(this.#C&&this.#q(Y))Y.__abortController.abort(new Error("evicted"));else if(this.#M||this.#w){if(this.#M)this.#Y?.(Y,X,"evict");if(this.#w)this.#O?.push([Y,X,"evict"])}if(this.#x(J),Z)this.#z[J]=void 0,this.#Q[J]=void 0,this.#E.push(J);if(this.#G===1)this.#L=this.#j=0,this.#E.length=0;else this.#L=this.#U[J];return this.#H.delete(X),this.#G--,J}has(Z,J={}){let{updateAgeOnHas:X=this.updateAgeOnHas,status:Y}=J,$=this.#H.get(Z);if($!==void 0){let Q=this.#Q[$];if(this.#q(Q)&&Q.__staleWhileFetching===void 0)return!1;if(!this.#D($)){if(X)this.#A($);if(Y)Y.has="hit",this.#P(Y,$);return!0}else if(Y)Y.has="stale",this.#P(Y,$)}else if(Y)Y.has="miss";return!1}peek(Z,J={}){let{allowStale:X=this.allowStale}=J,Y=this.#H.get(Z);if(Y===void 0||!X&&this.#D(Y))return;let $=this.#Q[Y];return this.#q($)?$.__staleWhileFetching:$}#h(Z,J,X,Y){let $=J===void 0?void 0:this.#Q[J];if(this.#q($))return $;let Q=new CB,{signal:K}=X;K?.addEventListener("abort",()=>Q.abort(K.reason),{signal:Q.signal});let G={signal:Q.signal,options:X,context:Y},W=(U,B=!1)=>{let{aborted:L}=Q.signal,w=X.ignoreFetchAbort&&U!==void 0;if(X.status)if(L&&!B){if(X.status.fetchAborted=!0,X.status.fetchError=Q.signal.reason,w)X.status.fetchAbortIgnored=!0}else X.status.fetchResolved=!0;if(L&&!w&&!B)return V(Q.signal.reason);let O=z;if(this.#Q[J]===z)if(U===void 0)if(O.__staleWhileFetching)this.#Q[J]=O.__staleWhileFetching;else this.#v(Z,"fetch");else{if(X.status)X.status.fetchUpdated=!0;this.set(Z,U,G.options)}return U},H=(U)=>{if(X.status)X.status.fetchRejected=!0,X.status.fetchError=U;return V(U)},V=(U)=>{let{aborted:B}=Q.signal,L=B&&X.allowStaleOnFetchAbort,w=L||X.allowStaleOnFetchRejection,O=w||X.noDeleteOnFetchRejection,M=z;if(this.#Q[J]===z){if(!O||M.__staleWhileFetching===void 0)this.#v(Z,"fetch");else if(!L)this.#Q[J]=M.__staleWhileFetching}if(w){if(X.status&&M.__staleWhileFetching!==void 0)X.status.returnedStale=!0;return M.__staleWhileFetching}else if(M.__returned===M)throw U},F=(U,B)=>{let L=this.#V?.(Z,$,G);if(L&&L instanceof Promise)L.then((w)=>U(w===void 0?void 0:w),B);Q.signal.addEventListener("abort",()=>{if(!X.ignoreFetchAbort||X.allowStaleOnFetchAbort){if(U(void 0),X.allowStaleOnFetchAbort)U=(w)=>W(w,!0)}})};if(X.status)X.status.fetchDispatched=!0;let z=new Promise(F).then(W,H),q=Object.assign(z,{__abortController:Q,__staleWhileFetching:$,__returned:void 0});if(J===void 0)this.set(Z,q,{...G.options,status:void 0}),J=this.#H.get(Z);else this.#Q[J]=q;return q}#q(Z){if(!this.#C)return!1;let J=Z;return!!J&&J instanceof Promise&&J.hasOwnProperty("__staleWhileFetching")&&J.__abortController instanceof CB}async fetch(Z,J={}){let{allowStale:X=this.allowStale,updateAgeOnGet:Y=this.updateAgeOnGet,noDeleteOnStaleGet:$=this.noDeleteOnStaleGet,ttl:Q=this.ttl,noDisposeOnSet:K=this.noDisposeOnSet,size:G=0,sizeCalculation:W=this.sizeCalculation,noUpdateTTL:H=this.noUpdateTTL,noDeleteOnFetchRejection:V=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:F=this.allowStaleOnFetchRejection,ignoreFetchAbort:z=this.ignoreFetchAbort,allowStaleOnFetchAbort:q=this.allowStaleOnFetchAbort,context:U,forceRefresh:B=!1,status:L,signal:w}=J;if(!this.#C){if(L)L.fetch="get";return this.get(Z,{allowStale:X,updateAgeOnGet:Y,noDeleteOnStaleGet:$,status:L})}let O={allowStale:X,updateAgeOnGet:Y,noDeleteOnStaleGet:$,ttl:Q,noDisposeOnSet:K,size:G,sizeCalculation:W,noUpdateTTL:H,noDeleteOnFetchRejection:V,allowStaleOnFetchRejection:F,allowStaleOnFetchAbort:q,ignoreFetchAbort:z,status:L,signal:w},M=this.#H.get(Z);if(M===void 0){if(L)L.fetch="miss";let R=this.#h(Z,M,O,U);return R.__returned=R}else{let R=this.#Q[M];if(this.#q(R)){let E=X&&R.__staleWhileFetching!==void 0;if(L){if(L.fetch="inflight",E)L.returnedStale=!0}return E?R.__staleWhileFetching:R.__returned=R}let D=this.#D(M);if(!B&&!D){if(L)L.fetch="hit";if(this.#b(M),Y)this.#A(M);if(L)this.#P(L,M);return R}let N=this.#h(Z,M,O,U),T=N.__staleWhileFetching!==void 0&&X;if(L){if(L.fetch=D?"stale":"refresh",T&&D)L.returnedStale=!0}return T?N.__staleWhileFetching:N.__returned=N}}async forceFetch(Z,J={}){let X=await this.fetch(Z,J);if(X===void 0)throw new Error("fetch() returned undefined");return X}memo(Z,J={}){let X=this.#F;if(!X)throw new Error("no memoMethod provided to constructor");let{context:Y,forceRefresh:$,...Q}=J,K=this.get(Z,Q);if(!$&&K!==void 0)return K;let G=X(Z,K,{options:Q,context:Y});return this.set(Z,G,Q),G}get(Z,J={}){let{allowStale:X=this.allowStale,updateAgeOnGet:Y=this.updateAgeOnGet,noDeleteOnStaleGet:$=this.noDeleteOnStaleGet,status:Q}=J,K=this.#H.get(Z);if(K!==void 0){let G=this.#Q[K],W=this.#q(G);if(Q)this.#P(Q,K);if(this.#D(K)){if(Q)Q.get="stale";if(!W){if(!$)this.#v(Z,"expire");if(Q&&X)Q.returnedStale=!0;return X?G:void 0}else{if(Q&&X&&G.__staleWhileFetching!==void 0)Q.returnedStale=!0;return X?G.__staleWhileFetching:void 0}}else{if(Q)Q.get="hit";if(W)return G.__staleWhileFetching;if(this.#b(K),Y)this.#A(K);return G}}else if(Q)Q.get="miss"}#c(Z,J){this.#B[J]=Z,this.#U[Z]=J}#b(Z){if(Z!==this.#j){if(Z===this.#L)this.#L=this.#U[Z];else this.#c(this.#B[Z],this.#U[Z]);this.#c(this.#j,Z),this.#j=Z}}delete(Z){return this.#v(Z,"delete")}#v(Z,J){let X=!1;if(this.#G!==0){let Y=this.#H.get(Z);if(Y!==void 0)if(X=!0,this.#G===1)this.#g(J);else{this.#x(Y);let $=this.#Q[Y];if(this.#q($))$.__abortController.abort(new Error("deleted"));else if(this.#M||this.#w){if(this.#M)this.#Y?.($,Z,J);if(this.#w)this.#O?.push([$,Z,J])}if(this.#H.delete(Z),this.#z[Y]=void 0,this.#Q[Y]=void 0,Y===this.#j)this.#j=this.#B[Y];else if(Y===this.#L)this.#L=this.#U[Y];else{let Q=this.#B[Y];this.#U[Q]=this.#U[Y];let K=this.#U[Y];this.#B[K]=this.#B[Y]}this.#G--,this.#E.push(Y)}}if(this.#w&&this.#O?.length){let Y=this.#O,$;while($=Y?.shift())this.#$?.(...$)}return X}clear(){return this.#g("delete")}#g(Z){for(let J of this.#I({allowStale:!0})){let X=this.#Q[J];if(this.#q(X))X.__abortController.abort(new Error("deleted"));else{let Y=this.#z[J];if(this.#M)this.#Y?.(X,Y,Z);if(this.#w)this.#O?.push([X,Y,Z])}}if(this.#H.clear(),this.#Q.fill(void 0),this.#z.fill(void 0),this.#R&&this.#N)this.#R.fill(0),this.#N.fill(0);if(this.#k)this.#k.fill(0);if(this.#L=0,this.#j=0,this.#E.length=0,this.#W=0,this.#G=0,this.#w&&this.#O){let J=this.#O,X;while(X=J?.shift())this.#$?.(...X)}}}import{posix as Hj1,win32 as lC}from"node:path";import{fileURLToPath as Vj1}from"node:url";import{lstatSync as zj1,readdir as Fj1,readdirSync as qj1,readlinkSync as Uj1,realpathSync as Lj1}from"fs";import*as Bj1 from"node:fs";import{lstat as jj1,readdir as Oj1,readlink as Mj1,realpath as Rj1}from"node:fs/promises";import{EventEmitter as mC}from"node:events";import wn from"node:stream";import{StringDecoder as ew1}from"node:string_decoder";var qn=typeof process==="object"&&process?process:{stdout:null,stderr:null},Zj1=(Z)=>!!Z&&typeof Z==="object"&&(Z instanceof iY||Z instanceof wn||Jj1(Z)||Xj1(Z)),Jj1=(Z)=>!!Z&&typeof Z==="object"&&Z instanceof mC&&typeof Z.pipe==="function"&&Z.pipe!==wn.Writable.prototype.pipe,Xj1=(Z)=>!!Z&&typeof Z==="object"&&Z instanceof mC&&typeof Z.write==="function"&&typeof Z.end==="function",CZ=Symbol("EOF"),TZ=Symbol("maybeEmitEnd"),cJ=Symbol("emittedEnd"),TB=Symbol("emittingEnd"),TH=Symbol("emittedError"),EB=Symbol("closed"),Un=Symbol("read"),kB=Symbol("flush"),Ln=Symbol("flushChunk"),S4=Symbol("encoding"),dK=Symbol("decoder"),t8=Symbol("flowing"),EH=Symbol("paused"),cK=Symbol("resume"),e8=Symbol("buffer"),s6=Symbol("pipes"),Z6=Symbol("bufferLength"),hC=Symbol("bufferPush"),IB=Symbol("bufferShift"),k6=Symbol("objectMode"),D8=Symbol("destroyed"),fC=Symbol("error"),yC=Symbol("emitData"),Bn=Symbol("emitEnd"),bC=Symbol("emitEnd2"),R7=Symbol("async"),gC=Symbol("abort"),_B=Symbol("aborted"),kH=Symbol("signal"),pY=Symbol("dataListeners"),t5=Symbol("discarded"),IH=(Z)=>Promise.resolve().then(Z),Yj1=(Z)=>Z(),$j1=(Z)=>Z==="end"||Z==="finish"||Z==="prefinish",Qj1=(Z)=>Z instanceof ArrayBuffer||!!Z&&typeof Z==="object"&&Z.constructor&&Z.constructor.name==="ArrayBuffer"&&Z.byteLength>=0,Kj1=(Z)=>!Buffer.isBuffer(Z)&&ArrayBuffer.isView(Z);class uC{src;dest;opts;ondrain;constructor(Z,J,X){this.src=Z,this.dest=J,this.opts=X,this.ondrain=()=>Z[cK](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(Z){}end(){if(this.unpipe(),this.opts.end)this.dest.end()}}class jn extends uC{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(Z,J,X){super(Z,J,X);this.proxyErrors=(Y)=>J.emit("error",Y),Z.on("error",this.proxyErrors)}}var Gj1=(Z)=>!!Z.objectMode,Wj1=(Z)=>!Z.objectMode&&!!Z.encoding&&Z.encoding!=="buffer";class iY extends mC{[t8]=!1;[EH]=!1;[s6]=[];[e8]=[];[k6];[S4];[R7];[dK];[CZ]=!1;[cJ]=!1;[TB]=!1;[EB]=!1;[TH]=null;[Z6]=0;[D8]=!1;[kH];[_B]=!1;[pY]=0;[t5]=!1;writable=!0;readable=!0;constructor(...Z){let J=Z[0]||{};super();if(J.objectMode&&typeof J.encoding==="string")throw new TypeError("Encoding and objectMode may not be used together");if(Gj1(J))this[k6]=!0,this[S4]=null;else if(Wj1(J))this[S4]=J.encoding,this[k6]=!1;else this[k6]=!1,this[S4]=null;if(this[R7]=!!J.async,this[dK]=this[S4]?new ew1(this[S4]):null,J&&J.debugExposeBuffer===!0)Object.defineProperty(this,"buffer",{get:()=>this[e8]});if(J&&J.debugExposePipes===!0)Object.defineProperty(this,"pipes",{get:()=>this[s6]});let{signal:X}=J;if(X)if(this[kH]=X,X.aborted)this[gC]();else X.addEventListener("abort",()=>this[gC]())}get bufferLength(){return this[Z6]}get encoding(){return this[S4]}set encoding(Z){throw new Error("Encoding must be set at instantiation time")}setEncoding(Z){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[k6]}set objectMode(Z){throw new Error("objectMode must be set at instantiation time")}get["async"](){return this[R7]}set["async"](Z){this[R7]=this[R7]||!!Z}[gC](){this[_B]=!0,this.emit("abort",this[kH]?.reason),this.destroy(this[kH]?.reason)}get aborted(){return this[_B]}set aborted(Z){}write(Z,J,X){if(this[_B])return!1;if(this[CZ])throw new Error("write after end");if(this[D8])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;if(typeof J==="function")X=J,J="utf8";if(!J)J="utf8";let Y=this[R7]?IH:Yj1;if(!this[k6]&&!Buffer.isBuffer(Z)){if(Kj1(Z))Z=Buffer.from(Z.buffer,Z.byteOffset,Z.byteLength);else if(Qj1(Z))Z=Buffer.from(Z);else if(typeof Z!=="string")throw new Error("Non-contiguous data written to non-objectMode stream")}if(this[k6]){if(this[t8]&&this[Z6]!==0)this[kB](!0);if(this[t8])this.emit("data",Z);else this[hC](Z);if(this[Z6]!==0)this.emit("readable");if(X)Y(X);return this[t8]}if(!Z.length){if(this[Z6]!==0)this.emit("readable");if(X)Y(X);return this[t8]}if(typeof Z==="string"&&!(J===this[S4]&&!this[dK]?.lastNeed))Z=Buffer.from(Z,J);if(Buffer.isBuffer(Z)&&this[S4])Z=this[dK].write(Z);if(this[t8]&&this[Z6]!==0)this[kB](!0);if(this[t8])this.emit("data",Z);else this[hC](Z);if(this[Z6]!==0)this.emit("readable");if(X)Y(X);return this[t8]}read(Z){if(this[D8])return null;if(this[t5]=!1,this[Z6]===0||Z===0||Z&&Z>this[Z6])return this[TZ](),null;if(this[k6])Z=null;if(this[e8].length>1&&!this[k6])this[e8]=[this[S4]?this[e8].join(""):Buffer.concat(this[e8],this[Z6])];let J=this[Un](Z||null,this[e8][0]);return this[TZ](),J}[Un](Z,J){if(this[k6])this[IB]();else{let X=J;if(Z===X.length||Z===null)this[IB]();else if(typeof X==="string")this[e8][0]=X.slice(Z),J=X.slice(0,Z),this[Z6]-=Z;else this[e8][0]=X.subarray(Z),J=X.subarray(0,Z),this[Z6]-=Z}if(this.emit("data",J),!this[e8].length&&!this[CZ])this.emit("drain");return J}end(Z,J,X){if(typeof Z==="function")X=Z,Z=void 0;if(typeof J==="function")X=J,J="utf8";if(Z!==void 0)this.write(Z,J);if(X)this.once("end",X);if(this[CZ]=!0,this.writable=!1,this[t8]||!this[EH])this[TZ]();return this}[cK](){if(this[D8])return;if(!this[pY]&&!this[s6].length)this[t5]=!0;if(this[EH]=!1,this[t8]=!0,this.emit("resume"),this[e8].length)this[kB]();else if(this[CZ])this[TZ]();else this.emit("drain")}resume(){return this[cK]()}pause(){this[t8]=!1,this[EH]=!0,this[t5]=!1}get destroyed(){return this[D8]}get flowing(){return this[t8]}get paused(){return this[EH]}[hC](Z){if(this[k6])this[Z6]+=1;else this[Z6]+=Z.length;this[e8].push(Z)}[IB](){if(this[k6])this[Z6]-=1;else this[Z6]-=this[e8][0].length;return this[e8].shift()}[kB](Z=!1){do;while(this[Ln](this[IB]())&&this[e8].length);if(!Z&&!this[e8].length&&!this[CZ])this.emit("drain")}[Ln](Z){return this.emit("data",Z),this[t8]}pipe(Z,J){if(this[D8])return Z;this[t5]=!1;let X=this[cJ];if(J=J||{},Z===qn.stdout||Z===qn.stderr)J.end=!1;else J.end=J.end!==!1;if(J.proxyErrors=!!J.proxyErrors,X){if(J.end)Z.end()}else if(this[s6].push(!J.proxyErrors?new uC(this,Z,J):new jn(this,Z,J)),this[R7])IH(()=>this[cK]());else this[cK]();return Z}unpipe(Z){let J=this[s6].find((X)=>X.dest===Z);if(J){if(this[s6].length===1){if(this[t8]&&this[pY]===0)this[t8]=!1;this[s6]=[]}else this[s6].splice(this[s6].indexOf(J),1);J.unpipe()}}addListener(Z,J){return this.on(Z,J)}on(Z,J){let X=super.on(Z,J);if(Z==="data"){if(this[t5]=!1,this[pY]++,!this[s6].length&&!this[t8])this[cK]()}else if(Z==="readable"&&this[Z6]!==0)super.emit("readable");else if($j1(Z)&&this[cJ])super.emit(Z),this.removeAllListeners(Z);else if(Z==="error"&&this[TH]){let Y=J;if(this[R7])IH(()=>Y.call(this,this[TH]));else Y.call(this,this[TH])}return X}removeListener(Z,J){return this.off(Z,J)}off(Z,J){let X=super.off(Z,J);if(Z==="data"){if(this[pY]=this.listeners("data").length,this[pY]===0&&!this[t5]&&!this[s6].length)this[t8]=!1}return X}removeAllListeners(Z){let J=super.removeAllListeners(Z);if(Z==="data"||Z===void 0){if(this[pY]=0,!this[t5]&&!this[s6].length)this[t8]=!1}return J}get emittedEnd(){return this[cJ]}[TZ](){if(!this[TB]&&!this[cJ]&&!this[D8]&&this[e8].length===0&&this[CZ]){if(this[TB]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[EB])this.emit("close");this[TB]=!1}}emit(Z,...J){let X=J[0];if(Z!=="error"&&Z!=="close"&&Z!==D8&&this[D8])return!1;else if(Z==="data")return!this[k6]&&!X?!1:this[R7]?(IH(()=>this[yC](X)),!0):this[yC](X);else if(Z==="end")return this[Bn]();else if(Z==="close"){if(this[EB]=!0,!this[cJ]&&!this[D8])return!1;let $=super.emit("close");return this.removeAllListeners("close"),$}else if(Z==="error"){this[TH]=X,super.emit(fC,X);let $=!this[kH]||this.listeners("error").length?super.emit("error",X):!1;return this[TZ](),$}else if(Z==="resume"){let $=super.emit("resume");return this[TZ](),$}else if(Z==="finish"||Z==="prefinish"){let $=super.emit(Z);return this.removeAllListeners(Z),$}let Y=super.emit(Z,...J);return this[TZ](),Y}[yC](Z){for(let X of this[s6])if(X.dest.write(Z)===!1)this.pause();let J=this[t5]?!1:super.emit("data",Z);return this[TZ](),J}[Bn](){if(this[cJ])return!1;return this[cJ]=!0,this.readable=!1,this[R7]?(IH(()=>this[bC]()),!0):this[bC]()}[bC](){if(this[dK]){let J=this[dK].end();if(J){for(let X of this[s6])X.dest.write(J);if(!this[t5])super.emit("data",J)}}for(let J of this[s6])J.end();let Z=super.emit("end");return this.removeAllListeners("end"),Z}async collect(){let Z=Object.assign([],{dataLength:0});if(!this[k6])Z.dataLength=0;let J=this.promise();return this.on("data",(X)=>{if(Z.push(X),!this[k6])Z.dataLength+=X.length}),await J,Z}async concat(){if(this[k6])throw new Error("cannot concat in objectMode");let Z=await this.collect();return this[S4]?Z.join(""):Buffer.concat(Z,Z.dataLength)}async promise(){return new Promise((Z,J)=>{this.on(D8,()=>J(new Error("stream destroyed"))),this.on("error",(X)=>J(X)),this.on("end",()=>Z())})}[Symbol.asyncIterator](){this[t5]=!1;let Z=!1,J=async()=>{return this.pause(),Z=!0,{value:void 0,done:!0}};return{next:()=>{if(Z)return J();let Y=this.read();if(Y!==null)return Promise.resolve({done:!1,value:Y});if(this[CZ])return J();let $,Q,K=(V)=>{this.off("data",G),this.off("end",W),this.off(D8,H),J(),Q(V)},G=(V)=>{this.off("error",K),this.off("end",W),this.off(D8,H),this.pause(),$({value:V,done:!!this[CZ]})},W=()=>{this.off("error",K),this.off("data",G),this.off(D8,H),J(),$({done:!0,value:void 0})},H=()=>K(new Error("stream destroyed"));return new Promise((V,F)=>{Q=F,$=V,this.once(D8,H),this.once("error",K),this.once("end",W),this.once("data",G)})},throw:J,return:J,[Symbol.asyncIterator](){return this}}}[Symbol.iterator](){this[t5]=!1;let Z=!1,J=()=>{return this.pause(),this.off(fC,J),this.off(D8,J),this.off("end",J),Z=!0,{done:!0,value:void 0}},X=()=>{if(Z)return J();let Y=this.read();return Y===null?J():{done:!1,value:Y}};return this.once("end",J),this.once(fC,J),this.once(D8,J),{next:X,throw:J,return:J,[Symbol.iterator](){return this}}}destroy(Z){if(this[D8]){if(Z)this.emit("error",Z);else this.emit(D8);return this}this[D8]=!0,this[t5]=!0,this[e8].length=0,this[Z6]=0;let J=this;if(typeof J.close==="function"&&!this[EB])J.close();if(Z)this.emit("error",Z);else this.emit(D8);return this}static get isStream(){return Zj1}}var wj1=Lj1.native,SH={lstatSync:zj1,readdir:Fj1,readdirSync:qj1,readlinkSync:Uj1,realpathSync:wj1,promises:{lstat:jj1,readdir:Oj1,readlink:Mj1,realpath:Rj1}},Pn=(Z)=>!Z||Z===SH||Z===Bj1?SH:{...SH,...Z,promises:{...SH.promises,...Z.promises||{}}},Dn=/^\\\\\?\\([a-z]:)\\?$/i,Nj1=(Z)=>Z.replace(/\//g,"\\").replace(Dn,"$1\\"),Pj1=/[\\\/]/,h9=0,Cn=1,Tn=2,N7=4,En=6,kn=8,nY=10,In=12,x9=15,_H=~x9,dC=16,On=32,vH=64,v4=128,SB=256,AB=512,Mn=vH|v4|AB,Dj1=1023,cC=(Z)=>Z.isFile()?kn:Z.isDirectory()?N7:Z.isSymbolicLink()?nY:Z.isCharacterDevice()?Tn:Z.isBlockDevice()?En:Z.isSocket()?In:Z.isFIFO()?Cn:h9,Rn=new Map,AH=(Z)=>{let J=Rn.get(Z);if(J)return J;let X=Z.normalize("NFKD");return Rn.set(Z,X),X},Nn=new Map,vB=(Z)=>{let J=Nn.get(Z);if(J)return J;let X=AH(Z.toLowerCase());return Nn.set(Z,X),X};class pC extends CH{constructor(){super({max:256})}}class _n extends CH{constructor(Z=16384){super({maxSize:Z,sizeCalculation:(J)=>J.length+1})}}var Sn=Symbol("PathScurry setAsCwd");class o6{name;root;roots;parent;nocase;isCWD=!1;#Z;#J;get dev(){return this.#J}#Y;get mode(){return this.#Y}#X;get nlink(){return this.#X}#$;get uid(){return this.#$}#V;get gid(){return this.#V}#F;get rdev(){return this.#F}#G;get blksize(){return this.#G}#W;get ino(){return this.#W}#H;get size(){return this.#H}#z;get blocks(){return this.#z}#Q;get atimeMs(){return this.#Q}#U;get mtimeMs(){return this.#U}#B;get ctimeMs(){return this.#B}#L;get birthtimeMs(){return this.#L}#j;get atime(){return this.#j}#E;get mtime(){return this.#E}#O;get ctime(){return this.#O}#k;get birthtime(){return this.#k}#N;#R;#M;#C;#w;#_;#K;#A;#P;#S;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(Z,J=h9,X,Y,$,Q,K){if(this.name=Z,this.#N=$?vB(Z):AH(Z),this.#K=J&Dj1,this.nocase=$,this.roots=Y,this.root=X||this,this.#A=Q,this.#M=K.fullpath,this.#w=K.relative,this.#_=K.relativePosix,this.parent=K.parent,this.parent)this.#Z=this.parent.#Z;else this.#Z=Pn(K.fs)}depth(){if(this.#R!==void 0)return this.#R;if(!this.parent)return this.#R=0;return this.#R=this.parent.depth()+1}childrenCache(){return this.#A}resolve(Z){if(!Z)return this;let J=this.getRootString(Z),Y=Z.substring(J.length).split(this.splitSep);return J?this.getRoot(J).#D(Y):this.#D(Y)}#D(Z){let J=this;for(let X of Z)J=J.child(X);return J}children(){let Z=this.#A.get(this);if(Z)return Z;let J=Object.assign([],{provisional:0});return this.#A.set(this,J),this.#K&=~dC,J}child(Z,J){if(Z===""||Z===".")return this;if(Z==="..")return this.parent||this;let X=this.children(),Y=this.nocase?vB(Z):AH(Z);for(let G of X)if(G.#N===Y)return G;let $=this.parent?this.sep:"",Q=this.#M?this.#M+$+Z:void 0,K=this.newChild(Z,h9,{...J,parent:this,fullpath:Q});if(!this.canReaddir())K.#K|=v4;return X.push(K),K}relative(){if(this.isCWD)return"";if(this.#w!==void 0)return this.#w;let Z=this.name,J=this.parent;if(!J)return this.#w=this.name;let X=J.relative();return X+(!X||!J.parent?"":this.sep)+Z}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return"";if(this.#_!==void 0)return this.#_;let Z=this.name,J=this.parent;if(!J)return this.#_=this.fullpathPosix();let X=J.relativePosix();return X+(!X||!J.parent?"":"/")+Z}fullpath(){if(this.#M!==void 0)return this.#M;let Z=this.name,J=this.parent;if(!J)return this.#M=this.name;let Y=J.fullpath()+(!J.parent?"":this.sep)+Z;return this.#M=Y}fullpathPosix(){if(this.#C!==void 0)return this.#C;if(this.sep==="/")return this.#C=this.fullpath();if(!this.parent){let Y=this.fullpath().replace(/\\/g,"/");if(/^[a-z]:\//i.test(Y))return this.#C=`//?/${Y}`;else return this.#C=Y}let Z=this.parent,J=Z.fullpathPosix(),X=J+(!J||!Z.parent?"":"/")+this.name;return this.#C=X}isUnknown(){return(this.#K&x9)===h9}isType(Z){return this[`is${Z}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return(this.#K&x9)===kn}isDirectory(){return(this.#K&x9)===N7}isCharacterDevice(){return(this.#K&x9)===Tn}isBlockDevice(){return(this.#K&x9)===En}isFIFO(){return(this.#K&x9)===Cn}isSocket(){return(this.#K&x9)===In}isSymbolicLink(){return(this.#K&nY)===nY}lstatCached(){return this.#K&On?this:void 0}readlinkCached(){return this.#P}realpathCached(){return this.#S}readdirCached(){let Z=this.children();return Z.slice(0,Z.provisional)}canReadlink(){if(this.#P)return!0;if(!this.parent)return!1;let Z=this.#K&x9;return!(Z!==h9&&Z!==nY||this.#K&SB||this.#K&v4)}calledReaddir(){return!!(this.#K&dC)}isENOENT(){return!!(this.#K&v4)}isNamed(Z){return!this.nocase?this.#N===AH(Z):this.#N===vB(Z)}async readlink(){let Z=this.#P;if(Z)return Z;if(!this.canReadlink())return;if(!this.parent)return;try{let J=await this.#Z.promises.readlink(this.fullpath()),X=(await this.parent.realpath())?.resolve(J);if(X)return this.#P=X}catch(J){this.#y(J.code);return}}readlinkSync(){let Z=this.#P;if(Z)return Z;if(!this.canReadlink())return;if(!this.parent)return;try{let J=this.#Z.readlinkSync(this.fullpath()),X=this.parent.realpathSync()?.resolve(J);if(X)return this.#P=X}catch(J){this.#y(J.code);return}}#m(Z){this.#K|=dC;for(let J=Z.provisional;J<Z.length;J++){let X=Z[J];if(X)X.#x()}}#x(){if(this.#K&v4)return;this.#K=(this.#K|v4)&_H,this.#f()}#f(){let Z=this.children();Z.provisional=0;for(let J of Z)J.#x()}#u(){this.#K|=AB,this.#T()}#T(){if(this.#K&vH)return;let Z=this.#K;if((Z&x9)===N7)Z&=_H;this.#K=Z|vH,this.#f()}#I(Z=""){if(Z==="ENOTDIR"||Z==="EPERM")this.#T();else if(Z==="ENOENT")this.#x();else this.children().provisional=0}#d(Z=""){if(Z==="ENOTDIR")this.parent.#T();else if(Z==="ENOENT")this.#x()}#y(Z=""){let J=this.#K;if(J|=SB,Z==="ENOENT")J|=v4;if(Z==="EINVAL"||Z==="UNKNOWN")J&=_H;if(this.#K=J,Z==="ENOTDIR"&&this.parent)this.parent.#T()}#h(Z,J){return this.#c(Z,J)||this.#q(Z,J)}#q(Z,J){let X=cC(Z),Y=this.newChild(Z.name,X,{parent:this}),$=Y.#K&x9;if($!==N7&&$!==nY&&$!==h9)Y.#K|=vH;return J.unshift(Y),J.provisional++,Y}#c(Z,J){for(let X=J.provisional;X<J.length;X++){let Y=J[X];if((this.nocase?vB(Z.name):AH(Z.name))!==Y.#N)continue;return this.#b(Z,Y,X,J)}}#b(Z,J,X,Y){let $=J.name;if(J.#K=J.#K&_H|cC(Z),$!==Z.name)J.name=Z.name;if(X!==Y.provisional){if(X===Y.length-1)Y.pop();else Y.splice(X,1);Y.unshift(J)}return Y.provisional++,J}async lstat(){if((this.#K&v4)===0)try{return this.#v(await this.#Z.promises.lstat(this.fullpath())),this}catch(Z){this.#d(Z.code)}}lstatSync(){if((this.#K&v4)===0)try{return this.#v(this.#Z.lstatSync(this.fullpath())),this}catch(Z){this.#d(Z.code)}}#v(Z){let{atime:J,atimeMs:X,birthtime:Y,birthtimeMs:$,blksize:Q,blocks:K,ctime:G,ctimeMs:W,dev:H,gid:V,ino:F,mode:z,mtime:q,mtimeMs:U,nlink:B,rdev:L,size:w,uid:O}=Z;this.#j=J,this.#Q=X,this.#k=Y,this.#L=$,this.#G=Q,this.#z=K,this.#O=G,this.#B=W,this.#J=H,this.#V=V,this.#W=F,this.#Y=z,this.#E=q,this.#U=U,this.#X=B,this.#F=L,this.#H=w,this.#$=O;let M=cC(Z);if(this.#K=this.#K&_H|M|On,M!==h9&&M!==N7&&M!==nY)this.#K|=vH}#g=[];#p=!1;#i(Z){this.#p=!1;let J=this.#g.slice();this.#g.length=0,J.forEach((X)=>X(null,Z))}readdirCB(Z,J=!1){if(!this.canReaddir()){if(J)Z(null,[]);else queueMicrotask(()=>Z(null,[]));return}let X=this.children();if(this.calledReaddir()){let $=X.slice(0,X.provisional);if(J)Z(null,$);else queueMicrotask(()=>Z(null,$));return}if(this.#g.push(Z),this.#p)return;this.#p=!0;let Y=this.fullpath();this.#Z.readdir(Y,{withFileTypes:!0},($,Q)=>{if($)this.#I($.code),X.provisional=0;else{for(let K of Q)this.#h(K,X);this.#m(X)}this.#i(X.slice(0,X.provisional));return})}#l;async readdir(){if(!this.canReaddir())return[];let Z=this.children();if(this.calledReaddir())return Z.slice(0,Z.provisional);let J=this.fullpath();if(this.#l)await this.#l;else{let X=()=>{};this.#l=new Promise((Y)=>X=Y);try{for(let Y of await this.#Z.promises.readdir(J,{withFileTypes:!0}))this.#h(Y,Z);this.#m(Z)}catch(Y){this.#I(Y.code),Z.provisional=0}this.#l=void 0,X()}return Z.slice(0,Z.provisional)}readdirSync(){if(!this.canReaddir())return[];let Z=this.children();if(this.calledReaddir())return Z.slice(0,Z.provisional);let J=this.fullpath();try{for(let X of this.#Z.readdirSync(J,{withFileTypes:!0}))this.#h(X,Z);this.#m(Z)}catch(X){this.#I(X.code),Z.provisional=0}return Z.slice(0,Z.provisional)}canReaddir(){if(this.#K&Mn)return!1;let Z=x9&this.#K;if(!(Z===h9||Z===N7||Z===nY))return!1;return!0}shouldWalk(Z,J){return(this.#K&N7)===N7&&!(this.#K&Mn)&&!Z.has(this)&&(!J||J(this))}async realpath(){if(this.#S)return this.#S;if((AB|SB|v4)&this.#K)return;try{let Z=await this.#Z.promises.realpath(this.fullpath());return this.#S=this.resolve(Z)}catch(Z){this.#u()}}realpathSync(){if(this.#S)return this.#S;if((AB|SB|v4)&this.#K)return;try{let Z=this.#Z.realpathSync(this.fullpath());return this.#S=this.resolve(Z)}catch(Z){this.#u()}}[Sn](Z){if(Z===this)return;Z.isCWD=!1,this.isCWD=!0;let J=new Set([]),X=[],Y=this;while(Y&&Y.parent)J.add(Y),Y.#w=X.join(this.sep),Y.#_=X.join("/"),Y=Y.parent,X.push("..");Y=Z;while(Y&&Y.parent&&!J.has(Y))Y.#w=void 0,Y.#_=void 0,Y=Y.parent}}class xB extends o6{sep="\\";splitSep=Pj1;constructor(Z,J=h9,X,Y,$,Q,K){super(Z,J,X,Y,$,Q,K)}newChild(Z,J=h9,X={}){return new xB(Z,J,this.root,this.roots,this.nocase,this.childrenCache(),X)}getRootString(Z){return lC.parse(Z).root}getRoot(Z){if(Z=Nj1(Z.toUpperCase()),Z===this.root.name)return this.root;for(let[J,X]of Object.entries(this.roots))if(this.sameRoot(Z,J))return this.roots[Z]=X;return this.roots[Z]=new xH(Z,this).root}sameRoot(Z,J=this.root.name){return Z=Z.toUpperCase().replace(/\//g,"\\").replace(Dn,"$1\\"),Z===J}}class hB extends o6{splitSep="/";sep="/";constructor(Z,J=h9,X,Y,$,Q,K){super(Z,J,X,Y,$,Q,K)}getRootString(Z){return Z.startsWith("/")?"/":""}getRoot(Z){return this.root}newChild(Z,J=h9,X={}){return new hB(Z,J,this.root,this.roots,this.nocase,this.childrenCache(),X)}}class iC{root;rootPath;roots;cwd;#Z;#J;#Y;nocase;#X;constructor(Z=process.cwd(),J,X,{nocase:Y,childrenCacheSize:$=16384,fs:Q=SH}={}){if(this.#X=Pn(Q),Z instanceof URL||Z.startsWith("file://"))Z=Vj1(Z);let K=J.resolve(Z);this.roots=Object.create(null),this.rootPath=this.parseRootPath(K),this.#Z=new pC,this.#J=new pC,this.#Y=new _n($);let G=K.substring(this.rootPath.length).split(X);if(G.length===1&&!G[0])G.pop();if(Y===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=Y,this.root=this.newRoot(this.#X),this.roots[this.rootPath]=this.root;let W=this.root,H=G.length-1,V=J.sep,F=this.rootPath,z=!1;for(let q of G){let U=H--;W=W.child(q,{relative:new Array(U).fill("..").join(V),relativePosix:new Array(U).fill("..").join("/"),fullpath:F+=(z?"":V)+q}),z=!0}this.cwd=W}depth(Z=this.cwd){if(typeof Z==="string")Z=this.cwd.resolve(Z);return Z.depth()}childrenCache(){return this.#Y}resolve(...Z){let J="";for(let $=Z.length-1;$>=0;$--){let Q=Z[$];if(!Q||Q===".")continue;if(J=J?`${Q}/${J}`:Q,this.isAbsolute(Q))break}let X=this.#Z.get(J);if(X!==void 0)return X;let Y=this.cwd.resolve(J).fullpath();return this.#Z.set(J,Y),Y}resolvePosix(...Z){let J="";for(let $=Z.length-1;$>=0;$--){let Q=Z[$];if(!Q||Q===".")continue;if(J=J?`${Q}/${J}`:Q,this.isAbsolute(Q))break}let X=this.#J.get(J);if(X!==void 0)return X;let Y=this.cwd.resolve(J).fullpathPosix();return this.#J.set(J,Y),Y}relative(Z=this.cwd){if(typeof Z==="string")Z=this.cwd.resolve(Z);return Z.relative()}relativePosix(Z=this.cwd){if(typeof Z==="string")Z=this.cwd.resolve(Z);return Z.relativePosix()}basename(Z=this.cwd){if(typeof Z==="string")Z=this.cwd.resolve(Z);return Z.name}dirname(Z=this.cwd){if(typeof Z==="string")Z=this.cwd.resolve(Z);return(Z.parent||Z).fullpath()}async readdir(Z=this.cwd,J={withFileTypes:!0}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof o6))J=Z,Z=this.cwd;let{withFileTypes:X}=J;if(!Z.canReaddir())return[];else{let Y=await Z.readdir();return X?Y:Y.map(($)=>$.name)}}readdirSync(Z=this.cwd,J={withFileTypes:!0}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof o6))J=Z,Z=this.cwd;let{withFileTypes:X=!0}=J;if(!Z.canReaddir())return[];else if(X)return Z.readdirSync();else return Z.readdirSync().map((Y)=>Y.name)}async lstat(Z=this.cwd){if(typeof Z==="string")Z=this.cwd.resolve(Z);return Z.lstat()}lstatSync(Z=this.cwd){if(typeof Z==="string")Z=this.cwd.resolve(Z);return Z.lstatSync()}async readlink(Z=this.cwd,{withFileTypes:J}={withFileTypes:!1}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof o6))J=Z.withFileTypes,Z=this.cwd;let X=await Z.readlink();return J?X:X?.fullpath()}readlinkSync(Z=this.cwd,{withFileTypes:J}={withFileTypes:!1}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof o6))J=Z.withFileTypes,Z=this.cwd;let X=Z.readlinkSync();return J?X:X?.fullpath()}async realpath(Z=this.cwd,{withFileTypes:J}={withFileTypes:!1}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof o6))J=Z.withFileTypes,Z=this.cwd;let X=await Z.realpath();return J?X:X?.fullpath()}realpathSync(Z=this.cwd,{withFileTypes:J}={withFileTypes:!1}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof o6))J=Z.withFileTypes,Z=this.cwd;let X=Z.realpathSync();return J?X:X?.fullpath()}async walk(Z=this.cwd,J={}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof o6))J=Z,Z=this.cwd;let{withFileTypes:X=!0,follow:Y=!1,filter:$,walkFilter:Q}=J,K=[];if(!$||$(Z))K.push(X?Z:Z.fullpath());let G=new Set,W=(V,F)=>{G.add(V),V.readdirCB((z,q)=>{if(z)return F(z);let U=q.length;if(!U)return F();let B=()=>{if(--U===0)F()};for(let L of q){if(!$||$(L))K.push(X?L:L.fullpath());if(Y&&L.isSymbolicLink())L.realpath().then((w)=>w?.isUnknown()?w.lstat():w).then((w)=>w?.shouldWalk(G,Q)?W(w,B):B());else if(L.shouldWalk(G,Q))W(L,B);else B()}},!0)},H=Z;return new Promise((V,F)=>{W(H,(z)=>{if(z)return F(z);V(K)})})}walkSync(Z=this.cwd,J={}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof o6))J=Z,Z=this.cwd;let{withFileTypes:X=!0,follow:Y=!1,filter:$,walkFilter:Q}=J,K=[];if(!$||$(Z))K.push(X?Z:Z.fullpath());let G=new Set([Z]);for(let W of G){let H=W.readdirSync();for(let V of H){if(!$||$(V))K.push(X?V:V.fullpath());let F=V;if(V.isSymbolicLink()){if(!(Y&&(F=V.realpathSync())))continue;if(F.isUnknown())F.lstatSync()}if(F.shouldWalk(G,Q))G.add(F)}}return K}[Symbol.asyncIterator](){return this.iterate()}iterate(Z=this.cwd,J={}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof o6))J=Z,Z=this.cwd;return this.stream(Z,J)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(Z=this.cwd,J={}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof o6))J=Z,Z=this.cwd;let{withFileTypes:X=!0,follow:Y=!1,filter:$,walkFilter:Q}=J;if(!$||$(Z))yield X?Z:Z.fullpath();let K=new Set([Z]);for(let G of K){let W=G.readdirSync();for(let H of W){if(!$||$(H))yield X?H:H.fullpath();let V=H;if(H.isSymbolicLink()){if(!(Y&&(V=H.realpathSync())))continue;if(V.isUnknown())V.lstatSync()}if(V.shouldWalk(K,Q))K.add(V)}}}stream(Z=this.cwd,J={}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof o6))J=Z,Z=this.cwd;let{withFileTypes:X=!0,follow:Y=!1,filter:$,walkFilter:Q}=J,K=new iY({objectMode:!0});if(!$||$(Z))K.write(X?Z:Z.fullpath());let G=new Set,W=[Z],H=0,V=()=>{let F=!1;while(!F){let z=W.shift();if(!z){if(H===0)K.end();return}H++,G.add(z);let q=(B,L,w=!1)=>{if(B)return K.emit("error",B);if(Y&&!w){let O=[];for(let M of L)if(M.isSymbolicLink())O.push(M.realpath().then((R)=>R?.isUnknown()?R.lstat():R));if(O.length){Promise.all(O).then(()=>q(null,L,!0));return}}for(let O of L)if(O&&(!$||$(O))){if(!K.write(X?O:O.fullpath()))F=!0}H--;for(let O of L){let M=O.realpathCached()||O;if(M.shouldWalk(G,Q))W.push(M)}if(F&&!K.flowing)K.once("drain",V);else if(!U)V()},U=!0;z.readdirCB(q,!0),U=!1}};return V(),K}streamSync(Z=this.cwd,J={}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof o6))J=Z,Z=this.cwd;let{withFileTypes:X=!0,follow:Y=!1,filter:$,walkFilter:Q}=J,K=new iY({objectMode:!0}),G=new Set;if(!$||$(Z))K.write(X?Z:Z.fullpath());let W=[Z],H=0,V=()=>{let F=!1;while(!F){let z=W.shift();if(!z){if(H===0)K.end();return}H++,G.add(z);let q=z.readdirSync();for(let U of q)if(!$||$(U)){if(!K.write(X?U:U.fullpath()))F=!0}H--;for(let U of q){let B=U;if(U.isSymbolicLink()){if(!(Y&&(B=U.realpathSync())))continue;if(B.isUnknown())B.lstatSync()}if(B.shouldWalk(G,Q))W.push(B)}}if(F&&!K.flowing)K.once("drain",V)};return V(),K}chdir(Z=this.cwd){let J=this.cwd;this.cwd=typeof Z==="string"?this.cwd.resolve(Z):Z,this.cwd[Sn](J)}}class xH extends iC{sep="\\";constructor(Z=process.cwd(),J={}){let{nocase:X=!0}=J;super(Z,lC,"\\",{...J,nocase:X});this.nocase=X;for(let Y=this.cwd;Y;Y=Y.parent)Y.nocase=this.nocase}parseRootPath(Z){return lC.parse(Z).root.toUpperCase()}newRoot(Z){return new xB(this.rootPath,N7,void 0,this.roots,this.nocase,this.childrenCache(),{fs:Z})}isAbsolute(Z){return Z.startsWith("/")||Z.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(Z)}}class hH extends iC{sep="/";constructor(Z=process.cwd(),J={}){let{nocase:X=!1}=J;super(Z,Hj1,"/",{...J,nocase:X});this.nocase=X}parseRootPath(Z){return"/"}newRoot(Z){return new hB(this.rootPath,N7,void 0,this.roots,this.nocase,this.childrenCache(),{fs:Z})}isAbsolute(Z){return Z.startsWith("/")}}class fB extends hH{constructor(Z=process.cwd(),J={}){let{nocase:X=!0}=J;super(Z,{...J,nocase:X})}}var bI6=process.platform==="win32"?xB:hB,vn=process.platform==="win32"?xH:process.platform==="darwin"?fB:hH;var Cj1=(Z)=>Z.length>=1,Tj1=(Z)=>Z.length>=1;class lK{#Z;#J;#Y;length;#X;#$;#V;#F;#G;#W;#H=!0;constructor(Z,J,X,Y){if(!Cj1(Z))throw new TypeError("empty pattern list");if(!Tj1(J))throw new TypeError("empty glob list");if(J.length!==Z.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=Z.length,X<0||X>=this.length)throw new TypeError("index out of range");if(this.#Z=Z,this.#J=J,this.#Y=X,this.#X=Y,this.#Y===0){if(this.isUNC()){let[$,Q,K,G,...W]=this.#Z,[H,V,F,z,...q]=this.#J;if(W[0]==="")W.shift(),q.shift();let U=[$,Q,K,G,""].join("/"),B=[H,V,F,z,""].join("/");this.#Z=[U,...W],this.#J=[B,...q],this.length=this.#Z.length}else if(this.isDrive()||this.isAbsolute()){let[$,...Q]=this.#Z,[K,...G]=this.#J;if(Q[0]==="")Q.shift(),G.shift();let W=$+"/",H=K+"/";this.#Z=[W,...Q],this.#J=[H,...G],this.length=this.#Z.length}}}pattern(){return this.#Z[this.#Y]}isString(){return typeof this.#Z[this.#Y]==="string"}isGlobstar(){return this.#Z[this.#Y]===B6}isRegExp(){return this.#Z[this.#Y]instanceof RegExp}globString(){return this.#V=this.#V||(this.#Y===0?this.isAbsolute()?this.#J[0]+this.#J.slice(1).join("/"):this.#J.join("/"):this.#J.slice(this.#Y).join("/"))}hasMore(){return this.length>this.#Y+1}rest(){if(this.#$!==void 0)return this.#$;if(!this.hasMore())return this.#$=null;return this.#$=new lK(this.#Z,this.#J,this.#Y+1,this.#X),this.#$.#W=this.#W,this.#$.#G=this.#G,this.#$.#F=this.#F,this.#$}isUNC(){let Z=this.#Z;return this.#G!==void 0?this.#G:this.#G=this.#X==="win32"&&this.#Y===0&&Z[0]===""&&Z[1]===""&&typeof Z[2]==="string"&&!!Z[2]&&typeof Z[3]==="string"&&!!Z[3]}isDrive(){let Z=this.#Z;return this.#F!==void 0?this.#F:this.#F=this.#X==="win32"&&this.#Y===0&&this.length>1&&typeof Z[0]==="string"&&/^[a-z]:$/i.test(Z[0])}isAbsolute(){let Z=this.#Z;return this.#W!==void 0?this.#W:this.#W=Z[0]===""&&Z.length>1||this.isDrive()||this.isUNC()}root(){let Z=this.#Z[0];return typeof Z==="string"&&this.isAbsolute()&&this.#Y===0?Z:""}checkFollowGlobstar(){return!(this.#Y===0||!this.isGlobstar()||!this.#H)}markFollowGlobstar(){if(this.#Y===0||!this.isGlobstar()||!this.#H)return!1;return this.#H=!1,!0}}var Ej1=typeof process==="object"&&process&&typeof process.platform==="string"?process.platform:"linux";class fH{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(Z,{nobrace:J,nocase:X,noext:Y,noglobstar:$,platform:Q=Ej1}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=Q,this.mmopts={dot:!0,nobrace:J,nocase:X,noext:Y,noglobstar:$,optimizationLevel:2,platform:Q,nocomment:!0,nonegate:!0};for(let K of Z)this.add(K)}add(Z){let J=new A9(Z,this.mmopts);for(let X=0;X<J.set.length;X++){let Y=J.set[X],$=J.globParts[X];if(!Y||!$)throw new Error("invalid pattern object");while(Y[0]==="."&&$[0]===".")Y.shift(),$.shift();let Q=new lK(Y,$,0,this.platform),K=new A9(Q.globString(),this.mmopts),G=$[$.length-1]==="**",W=Q.isAbsolute();if(W)this.absolute.push(K);else this.relative.push(K);if(G)if(W)this.absoluteChildren.push(K);else this.relativeChildren.push(K)}}ignored(Z){let J=Z.fullpath(),X=`${J}/`,Y=Z.relative()||".",$=`${Y}/`;for(let Q of this.relative)if(Q.match(Y)||Q.match($))return!0;for(let Q of this.absolute)if(Q.match(J)||Q.match(X))return!0;return!1}childrenIgnored(Z){let J=Z.fullpath()+"/",X=(Z.relative()||".")+"/";for(let Y of this.relativeChildren)if(Y.match(X))return!0;for(let Y of this.absoluteChildren)if(Y.match(J))return!0;return!1}}class nC{store;constructor(Z=new Map){this.store=Z}copy(){return new nC(new Map(this.store))}hasWalked(Z,J){return this.store.get(Z.fullpath())?.has(J.globString())}storeWalked(Z,J){let X=Z.fullpath(),Y=this.store.get(X);if(Y)Y.add(J.globString());else this.store.set(X,new Set([J.globString()]))}}class An{store=new Map;add(Z,J,X){let Y=(J?2:0)|(X?1:0),$=this.store.get(Z);this.store.set(Z,$===void 0?Y:Y&$)}entries(){return[...this.store.entries()].map(([Z,J])=>[Z,!!(J&2),!!(J&1)])}}class xn{store=new Map;add(Z,J){if(!Z.canReaddir())return;let X=this.store.get(Z);if(X){if(!X.find((Y)=>Y.globString()===J.globString()))X.push(J)}else this.store.set(Z,[J])}get(Z){let J=this.store.get(Z);if(!J)throw new Error("attempting to walk unknown path");return J}entries(){return this.keys().map((Z)=>[Z,this.store.get(Z)])}keys(){return[...this.store.keys()].filter((Z)=>Z.canReaddir())}}class yH{hasWalkedCache;matches=new An;subwalks=new xn;patterns;follow;dot;opts;constructor(Z,J){this.opts=Z,this.follow=!!Z.follow,this.dot=!!Z.dot,this.hasWalkedCache=J?J.copy():new nC}processPatterns(Z,J){this.patterns=J;let X=J.map((Y)=>[Z,Y]);for(let[Y,$]of X){this.hasWalkedCache.storeWalked(Y,$);let Q=$.root(),K=$.isAbsolute()&&this.opts.absolute!==!1;if(Q){Y=Y.resolve(Q==="/"&&this.opts.root!==void 0?this.opts.root:Q);let V=$.rest();if(!V){this.matches.add(Y,!0,!1);continue}else $=V}if(Y.isENOENT())continue;let G,W,H=!1;while(typeof(G=$.pattern())==="string"&&(W=$.rest()))Y=Y.resolve(G),$=W,H=!0;if(G=$.pattern(),W=$.rest(),H){if(this.hasWalkedCache.hasWalked(Y,$))continue;this.hasWalkedCache.storeWalked(Y,$)}if(typeof G==="string"){let V=G===".."||G===""||G===".";this.matches.add(Y.resolve(G),K,V);continue}else if(G===B6){if(!Y.isSymbolicLink()||this.follow||$.checkFollowGlobstar())this.subwalks.add(Y,$);let V=W?.pattern(),F=W?.rest();if(!W||(V===""||V===".")&&!F)this.matches.add(Y,K,V===""||V===".");else if(V===".."){let z=Y.parent||Y;if(!F)this.matches.add(z,K,!0);else if(!this.hasWalkedCache.hasWalked(z,F))this.subwalks.add(z,F)}}else if(G instanceof RegExp)this.subwalks.add(Y,$)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new yH(this.opts,this.hasWalkedCache)}filterEntries(Z,J){let X=this.subwalks.get(Z),Y=this.child();for(let $ of J)for(let Q of X){let K=Q.isAbsolute(),G=Q.pattern(),W=Q.rest();if(G===B6)Y.testGlobstar($,Q,W,K);else if(G instanceof RegExp)Y.testRegExp($,G,W,K);else Y.testString($,G,W,K)}return Y}testGlobstar(Z,J,X,Y){if(this.dot||!Z.name.startsWith(".")){if(!J.hasMore())this.matches.add(Z,Y,!1);if(Z.canReaddir()){if(this.follow||!Z.isSymbolicLink())this.subwalks.add(Z,J);else if(Z.isSymbolicLink()){if(X&&J.checkFollowGlobstar())this.subwalks.add(Z,X);else if(J.markFollowGlobstar())this.subwalks.add(Z,J)}}}if(X){let $=X.pattern();if(typeof $==="string"&&$!==".."&&$!==""&&$!==".")this.testString(Z,$,X.rest(),Y);else if($===".."){let Q=Z.parent||Z;this.subwalks.add(Q,X)}else if($ instanceof RegExp)this.testRegExp(Z,$,X.rest(),Y)}}testRegExp(Z,J,X,Y){if(!J.test(Z.name))return;if(!X)this.matches.add(Z,Y,!1);else this.subwalks.add(Z,X)}testString(Z,J,X,Y){if(!Z.isNamed(J))return;if(!X)this.matches.add(Z,Y,!1);else this.subwalks.add(Z,X)}}var kj1=(Z,J)=>typeof Z==="string"?new fH([Z],J):Array.isArray(Z)?new fH(Z,J):Z;class aC{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#Z=[];#J;#Y;signal;maxDepth;includeChildMatches;constructor(Z,J,X){if(this.patterns=Z,this.path=J,this.opts=X,this.#Y=!X.posix&&X.platform==="win32"?"\\":"/",this.includeChildMatches=X.includeChildMatches!==!1,X.ignore||!this.includeChildMatches){if(this.#J=kj1(X.ignore??[],X),!this.includeChildMatches&&typeof this.#J.add!=="function")throw new Error("cannot ignore child matches, ignore lacks add() method.")}if(this.maxDepth=X.maxDepth||1/0,X.signal)this.signal=X.signal,this.signal.addEventListener("abort",()=>{this.#Z.length=0})}#X(Z){return this.seen.has(Z)||!!this.#J?.ignored?.(Z)}#$(Z){return!!this.#J?.childrenIgnored?.(Z)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;this.paused=!1;let Z=void 0;while(!this.paused&&(Z=this.#Z.shift()))Z()}onResume(Z){if(this.signal?.aborted)return;if(!this.paused)Z();else this.#Z.push(Z)}async matchCheck(Z,J){if(J&&this.opts.nodir)return;let X;if(this.opts.realpath){if(X=Z.realpathCached()||await Z.realpath(),!X)return;Z=X}let $=Z.isUnknown()||this.opts.stat?await Z.lstat():Z;if(this.opts.follow&&this.opts.nodir&&$?.isSymbolicLink()){let Q=await $.realpath();if(Q&&(Q.isUnknown()||this.opts.stat))await Q.lstat()}return this.matchCheckTest($,J)}matchCheckTest(Z,J){return Z&&(this.maxDepth===1/0||Z.depth()<=this.maxDepth)&&(!J||Z.canReaddir())&&(!this.opts.nodir||!Z.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!Z.isSymbolicLink()||!Z.realpathCached()?.isDirectory())&&!this.#X(Z)?Z:void 0}matchCheckSync(Z,J){if(J&&this.opts.nodir)return;let X;if(this.opts.realpath){if(X=Z.realpathCached()||Z.realpathSync(),!X)return;Z=X}let $=Z.isUnknown()||this.opts.stat?Z.lstatSync():Z;if(this.opts.follow&&this.opts.nodir&&$?.isSymbolicLink()){let Q=$.realpathSync();if(Q&&(Q?.isUnknown()||this.opts.stat))Q.lstatSync()}return this.matchCheckTest($,J)}matchFinish(Z,J){if(this.#X(Z))return;if(!this.includeChildMatches&&this.#J?.add){let $=`${Z.relativePosix()}/**`;this.#J.add($)}let X=this.opts.absolute===void 0?J:this.opts.absolute;this.seen.add(Z);let Y=this.opts.mark&&Z.isDirectory()?this.#Y:"";if(this.opts.withFileTypes)this.matchEmit(Z);else if(X){let $=this.opts.posix?Z.fullpathPosix():Z.fullpath();this.matchEmit($+Y)}else{let $=this.opts.posix?Z.relativePosix():Z.relative(),Q=this.opts.dotRelative&&!$.startsWith(".."+this.#Y)?"."+this.#Y:"";this.matchEmit(!$?"."+Y:Q+$+Y)}}async match(Z,J,X){let Y=await this.matchCheck(Z,X);if(Y)this.matchFinish(Y,J)}matchSync(Z,J,X){let Y=this.matchCheckSync(Z,X);if(Y)this.matchFinish(Y,J)}walkCB(Z,J,X){if(this.signal?.aborted)X();this.walkCB2(Z,J,new yH(this.opts),X)}walkCB2(Z,J,X,Y){if(this.#$(Z))return Y();if(this.signal?.aborted)Y();if(this.paused){this.onResume(()=>this.walkCB2(Z,J,X,Y));return}X.processPatterns(Z,J);let $=1,Q=()=>{if(--$===0)Y()};for(let[K,G,W]of X.matches.entries()){if(this.#X(K))continue;$++,this.match(K,G,W).then(()=>Q())}for(let K of X.subwalkTargets()){if(this.maxDepth!==1/0&&K.depth()>=this.maxDepth)continue;$++;let G=K.readdirCached();if(K.calledReaddir())this.walkCB3(K,G,X,Q);else K.readdirCB((W,H)=>this.walkCB3(K,H,X,Q),!0)}Q()}walkCB3(Z,J,X,Y){X=X.filterEntries(Z,J);let $=1,Q=()=>{if(--$===0)Y()};for(let[K,G,W]of X.matches.entries()){if(this.#X(K))continue;$++,this.match(K,G,W).then(()=>Q())}for(let[K,G]of X.subwalks.entries())$++,this.walkCB2(K,G,X.child(),Q);Q()}walkCBSync(Z,J,X){if(this.signal?.aborted)X();this.walkCB2Sync(Z,J,new yH(this.opts),X)}walkCB2Sync(Z,J,X,Y){if(this.#$(Z))return Y();if(this.signal?.aborted)Y();if(this.paused){this.onResume(()=>this.walkCB2Sync(Z,J,X,Y));return}X.processPatterns(Z,J);let $=1,Q=()=>{if(--$===0)Y()};for(let[K,G,W]of X.matches.entries()){if(this.#X(K))continue;this.matchSync(K,G,W)}for(let K of X.subwalkTargets()){if(this.maxDepth!==1/0&&K.depth()>=this.maxDepth)continue;$++;let G=K.readdirSync();this.walkCB3Sync(K,G,X,Q)}Q()}walkCB3Sync(Z,J,X,Y){X=X.filterEntries(Z,J);let $=1,Q=()=>{if(--$===0)Y()};for(let[K,G,W]of X.matches.entries()){if(this.#X(K))continue;this.matchSync(K,G,W)}for(let[K,G]of X.subwalks.entries())$++,this.walkCB2Sync(K,G,X.child(),Q);Q()}}class yB extends aC{matches=new Set;constructor(Z,J,X){super(Z,J,X)}matchEmit(Z){this.matches.add(Z)}async walk(){if(this.signal?.aborted)throw this.signal.reason;if(this.path.isUnknown())await this.path.lstat();return await new Promise((Z,J)=>{this.walkCB(this.path,this.patterns,()=>{if(this.signal?.aborted)J(this.signal.reason);else Z(this.matches)})}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;if(this.path.isUnknown())this.path.lstatSync();return this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}}class bB extends aC{results;constructor(Z,J,X){super(Z,J,X);this.results=new iY({signal:this.signal,objectMode:!0}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume())}matchEmit(Z){if(this.results.write(Z),!this.results.flowing)this.pause()}stream(){let Z=this.path;if(Z.isUnknown())Z.lstat().then(()=>{this.walkCB(Z,this.patterns,()=>this.results.end())});else this.walkCB(Z,this.patterns,()=>this.results.end());return this.results}streamSync(){if(this.path.isUnknown())this.path.lstatSync();return this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}}var _j1=typeof process==="object"&&process&&typeof process.platform==="string"?process.platform:"linux";class P7{absolute;cwd;root;dot;dotRelative;follow;ignore;magicalBraces;mark;matchBase;maxDepth;nobrace;nocase;nodir;noext;noglobstar;pattern;platform;realpath;scurry;stat;signal;windowsPathsNoEscape;withFileTypes;includeChildMatches;opts;patterns;constructor(Z,J){if(!J)throw new TypeError("glob options required");if(this.withFileTypes=!!J.withFileTypes,this.signal=J.signal,this.follow=!!J.follow,this.dot=!!J.dot,this.dotRelative=!!J.dotRelative,this.nodir=!!J.nodir,this.mark=!!J.mark,!J.cwd)this.cwd="";else if(J.cwd instanceof URL||J.cwd.startsWith("file://"))J.cwd=Ij1(J.cwd);if(this.cwd=J.cwd||"",this.root=J.root,this.magicalBraces=!!J.magicalBraces,this.nobrace=!!J.nobrace,this.noext=!!J.noext,this.realpath=!!J.realpath,this.absolute=J.absolute,this.includeChildMatches=J.includeChildMatches!==!1,this.noglobstar=!!J.noglobstar,this.matchBase=!!J.matchBase,this.maxDepth=typeof J.maxDepth==="number"?J.maxDepth:1/0,this.stat=!!J.stat,this.ignore=J.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof Z==="string")Z=[Z];if(this.windowsPathsNoEscape=!!J.windowsPathsNoEscape||J.allowWindowsEscape===!1,this.windowsPathsNoEscape)Z=Z.map((G)=>G.replace(/\\/g,"/"));if(this.matchBase){if(J.noglobstar)throw new TypeError("base matching requires globstar");Z=Z.map((G)=>G.includes("/")?G:`./**/${G}`)}if(this.pattern=Z,this.platform=J.platform||_j1,this.opts={...J,platform:this.platform},J.scurry){if(this.scurry=J.scurry,J.nocase!==void 0&&J.nocase!==J.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else{let G=J.platform==="win32"?xH:J.platform==="darwin"?fB:J.platform?hH:vn;this.scurry=new G(this.cwd,{nocase:J.nocase,fs:J.fs})}this.nocase=this.scurry.nocase;let X=this.platform==="darwin"||this.platform==="win32",Y={...J,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:X,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},$=this.pattern.map((G)=>new A9(G,Y)),[Q,K]=$.reduce((G,W)=>{return G[0].push(...W.set),G[1].push(...W.globParts),G},[[],[]]);this.patterns=Q.map((G,W)=>{let H=K[W];if(!H)throw new Error("invalid pattern object");return new lK(G,H,0,this.platform)})}async walk(){return[...await new yB(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()]}walkSync(){return[...new yB(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()]}stream(){return new bB(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new bB(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}}var sC=(Z,J={})=>{if(!Array.isArray(Z))Z=[Z];for(let X of Z)if(new A9(X,J).hasMagic())return!0;return!1};function mB(Z,J={}){return new P7(Z,J).streamSync()}function fn(Z,J={}){return new P7(Z,J).stream()}function yn(Z,J={}){return new P7(Z,J).walkSync()}async function hn(Z,J={}){return new P7(Z,J).walk()}function uB(Z,J={}){return new P7(Z,J).iterateSync()}function bn(Z,J={}){return new P7(Z,J).iterate()}var Sj1=mB,vj1=Object.assign(fn,{sync:mB}),Aj1=uB,xj1=Object.assign(bn,{sync:uB}),hj1=Object.assign(yn,{stream:mB,iterate:uB}),gB=Object.assign(hn,{glob:hn,globSync:yn,sync:hj1,globStream:fn,stream:vj1,globStreamSync:mB,streamSync:Sj1,globIterate:bn,iterate:xj1,globIterateSync:uB,iterateSync:Aj1,Glob:P7,hasMagic:sC,escape:gK,unescape:_4});gB.glob=gB;class oC{constructor(){this._listeners={}}addEventListener(Z,J){let X=this._listeners;if(X[Z]===void 0)X[Z]=[];if(X[Z].indexOf(J)===-1)X[Z].push(J);return this}removeEventListener(Z,J){let Y=this._listeners[Z];if(Y!==void 0){let $=Y.indexOf(J);if($!==-1)Y.splice($,1)}return this}dispatchEvent(Z){let X=this._listeners[Z.type];if(X!==void 0){let Y=X.slice(0);for(let $=0,Q=Y.length;$<Q;$++)Y[$].call(this,Z)}return this}dispose(){for(let Z in this._listeners)delete this._listeners[Z]}}class T5{constructor(Z,J,X,Y={}){if(this._name=void 0,this._parent=void 0,this._child=void 0,this._attributes=void 0,this._disposed=!1,this._name=Z,this._parent=J,this._child=X,this._attributes=Y,!J.isOnGraph(X))throw new Error("Cannot connect disconnected graphs.")}getName(){return this._name}getParent(){return this._parent}getChild(){return this._child}setChild(Z){return this._child=Z,this}getAttributes(){return this._attributes}dispose(){if(this._disposed)return;this._parent._destroyRef(this),this._disposed=!0}isDisposed(){return this._disposed}}class pK extends oC{constructor(...Z){super(...Z);this._emptySet=new Set,this._edges=new Set,this._parentEdges=new Map,this._childEdges=new Map}listEdges(){return Array.from(this._edges)}listParentEdges(Z){return Array.from(this._childEdges.get(Z)||this._emptySet)}listParents(Z){let J=new Set;for(let X of this.listParentEdges(Z))J.add(X.getParent());return Array.from(J)}listChildEdges(Z){return Array.from(this._parentEdges.get(Z)||this._emptySet)}listChildren(Z){let J=new Set;for(let X of this.listChildEdges(Z))J.add(X.getChild());return Array.from(J)}disconnectParents(Z,J){for(let X of this.listParentEdges(Z))if(!J||J(X.getParent()))X.dispose();return this}_createEdge(Z,J,X,Y){let $=new T5(Z,J,X,Y);this._edges.add($);let Q=$.getParent();if(!this._parentEdges.has(Q))this._parentEdges.set(Q,new Set);this._parentEdges.get(Q).add($);let K=$.getChild();if(!this._childEdges.has(K))this._childEdges.set(K,new Set);return this._childEdges.get(K).add($),$}_destroyEdge(Z){return this._edges.delete(Z),this._parentEdges.get(Z.getParent()).delete(Z),this._childEdges.get(Z.getChild()).delete(Z),this}}function bH(){return bH=Object.assign||function(Z){for(var J=1;J<arguments.length;J++){var X=arguments[J];for(var Y in X)if(Object.prototype.hasOwnProperty.call(X,Y))Z[Y]=X[Y]}return Z},bH.apply(this,arguments)}class I6{constructor(Z){if(this.list=[],Z)for(let J of Z)this.list.push(J)}add(Z){this.list.push(Z)}remove(Z){let J=this.list.indexOf(Z);if(J>=0)this.list.splice(J,1)}removeChild(Z){let J=[];for(let X of this.list)if(X.getChild()===Z)J.push(X);for(let X of J)this.remove(X);return J}listRefsByChild(Z){let J=[];for(let X of this.list)if(X.getChild()===Z)J.push(X);return J}values(){return this.list}}class E0{constructor(Z){if(this.set=new Set,this.map=new Map,Z)for(let J of Z)this.add(J)}add(Z){let J=Z.getChild();this.removeChild(J),this.set.add(Z),this.map.set(J,Z)}remove(Z){this.set.delete(Z),this.map.delete(Z.getChild())}removeChild(Z){let J=this.map.get(Z)||null;if(J)this.remove(J);return J}getRefByChild(Z){return this.map.get(Z)||null}values(){return Array.from(this.set)}}class Z8{constructor(Z){if(this.map={},Z)Object.assign(this.map,Z)}set(Z,J){this.map[Z]=J}delete(Z){delete this.map[Z]}get(Z){return this.map[Z]||null}keys(){return Object.keys(this.map)}values(){return Object.values(this.map)}}var y0=Symbol("attributes"),A4=Symbol("immutableKeys");class iK extends oC{constructor(Z){super();this._disposed=!1,this.graph=void 0,this[y0]=void 0,this[A4]=void 0,this.graph=Z,this[A4]=new Set,this[y0]=this._createAttributes()}getDefaults(){return{}}_createAttributes(){let Z=this.getDefaults(),J={};for(let X in Z){let Y=Z[X];if(Y instanceof iK){let $=this.graph._createEdge(X,this,Y);this[A4].add(X),J[X]=$}else J[X]=Y}return J}isOnGraph(Z){return this.graph===Z.graph}isDisposed(){return this._disposed}dispose(){if(this._disposed)return;this.graph.listChildEdges(this).forEach((Z)=>Z.dispose()),this.graph.disconnectParents(this),this._disposed=!0,this.dispatchEvent({type:"dispose"})}detach(){return this.graph.disconnectParents(this),this}swap(Z,J){for(let X in this[y0]){let Y=this[y0][X];if(Y instanceof T5){let $=Y;if($.getChild()===Z)this.setRef(X,J,$.getAttributes())}else if(Y instanceof I6)for(let $ of Y.listRefsByChild(Z)){let Q=$.getAttributes();this.removeRef(X,Z),this.addRef(X,J,Q)}else if(Y instanceof E0){let $=Y.getRefByChild(Z);if($){let Q=$.getAttributes();this.removeRef(X,Z),this.addRef(X,J,Q)}}else if(Y instanceof Z8)for(let $ of Y.keys()){let Q=Y.get($);if(Q.getChild()===Z)this.setRefMap(X,$,J,Q.getAttributes())}}return this}get(Z){return this[y0][Z]}set(Z,J){return this[y0][Z]=J,this.dispatchEvent({type:"change",attribute:Z})}getRef(Z){let J=this[y0][Z];return J?J.getChild():null}setRef(Z,J,X){if(this[A4].has(Z))throw new Error(`Cannot overwrite immutable attribute, "${Z}".`);let Y=this[y0][Z];if(Y)Y.dispose();if(!J)return this;let $=this.graph._createEdge(Z,this,J,X);return this[y0][Z]=$,this.dispatchEvent({type:"change",attribute:Z})}listRefs(Z){return this.assertRefList(Z).values().map((X)=>X.getChild())}addRef(Z,J,X){let Y=this.graph._createEdge(Z,this,J,X);return this.assertRefList(Z).add(Y),this.dispatchEvent({type:"change",attribute:Z})}removeRef(Z,J){let X=this.assertRefList(Z);if(X instanceof I6)for(let Y of X.listRefsByChild(J))Y.dispose();else{let Y=X.getRefByChild(J);if(Y)Y.dispose()}return this}assertRefList(Z){let J=this[y0][Z];if(J instanceof I6||J instanceof E0)return J;throw new Error(`Expected RefList or RefSet for attribute "${Z}"`)}listRefMapKeys(Z){return this.assertRefMap(Z).keys()}listRefMapValues(Z){return this.assertRefMap(Z).values().map((J)=>J.getChild())}getRefMap(Z,J){let Y=this.assertRefMap(Z).get(J);return Y?Y.getChild():null}setRefMap(Z,J,X,Y){let $=this.assertRefMap(Z),Q=$.get(J);if(Q)Q.dispose();if(!X)return this;Y=Object.assign(Y||{},{key:J});let K=this.graph._createEdge(Z,this,X,bH({},Y,{key:J}));return $.set(J,K),this.dispatchEvent({type:"change",attribute:Z,key:J})}assertRefMap(Z){let J=this[y0][Z];if(J instanceof Z8)return J;throw new Error(`Expected RefMap for attribute "${Z}"`)}dispatchEvent(Z){return super.dispatchEvent(bH({},Z,{target:this})),this.graph.dispatchEvent(bH({},Z,{target:this,type:`node:${Z.type}`})),this}_destroyRef(Z){let J=Z.getName();if(this[y0][J]===Z){if(this[y0][J]=null,this[A4].has(J))Z.getChild().dispose()}else if(this[y0][J]instanceof I6)this[y0][J].remove(Z);else if(this[y0][J]instanceof E0)this[y0][J].remove(Z);else if(this[y0][J]instanceof Z8){let X=this[y0][J];for(let Y of X.keys())if(X.get(Y)===Z)X.delete(Y)}else return;this.graph._destroyEdge(Z),this.dispatchEvent({type:"change",attribute:J})}}var pn="v4.1.1",nB="@glb.bin",a;(function(Z){Z.ACCESSOR="Accessor",Z.ANIMATION="Animation",Z.ANIMATION_CHANNEL="AnimationChannel",Z.ANIMATION_SAMPLER="AnimationSampler",Z.BUFFER="Buffer",Z.CAMERA="Camera",Z.MATERIAL="Material",Z.MESH="Mesh",Z.PRIMITIVE="Primitive",Z.PRIMITIVE_TARGET="PrimitiveTarget",Z.NODE="Node",Z.ROOT="Root",Z.SCENE="Scene",Z.SKIN="Skin",Z.TEXTURE="Texture",Z.TEXTURE_INFO="TextureInfo"})(a||(a={}));var aB;(function(Z){Z.INTERLEAVED="interleaved",Z.SEPARATE="separate"})(aB||(aB={}));var e5;(function(Z){Z.ARRAY_BUFFER="ARRAY_BUFFER",Z.ELEMENT_ARRAY_BUFFER="ELEMENT_ARRAY_BUFFER",Z.INVERSE_BIND_MATRICES="INVERSE_BIND_MATRICES",Z.OTHER="OTHER",Z.SPARSE="SPARSE"})(e5||(e5={}));var sB;(function(Z){Z[Z.R=4096]="R",Z[Z.G=256]="G",Z[Z.B=16]="B",Z[Z.A=1]="A"})(sB||(sB={}));var EZ;(function(Z){Z.GLTF="GLTF",Z.GLB="GLB"})(EZ||(EZ={}));var iJ={"5120":Int8Array,"5121":Uint8Array,"5122":Int16Array,"5123":Uint16Array,"5125":Uint32Array,"5126":Float32Array},tC=typeof Float32Array!=="undefined"?Float32Array:Array;if(!Math.hypot)Math.hypot=function(){var Z=0,J=arguments.length;while(J--)Z+=arguments[J]*arguments[J];return Math.sqrt(Z)};function fj1(){var Z=new tC(3);if(tC!=Float32Array)Z[0]=0,Z[1]=0,Z[2]=0;return Z}function rC(Z){var J=Z[0],X=Z[1],Y=Z[2];return Math.hypot(J,X,Y)}function yj1(Z,J,X){var Y=J[0],$=J[1],Q=J[2],K=X[3]*Y+X[7]*$+X[11]*Q+X[15];return K=K||1,Z[0]=(X[0]*Y+X[4]*$+X[8]*Q+X[12])/K,Z[1]=(X[1]*Y+X[5]*$+X[9]*Q+X[13])/K,Z[2]=(X[2]*Y+X[6]*$+X[10]*Q+X[14])/K,Z}(function(){var Z=fj1();return function(J,X,Y,$,Q,K){var G,W;if(!X)X=3;if(!Y)Y=0;if($)W=Math.min($*X+Y,J.length);else W=J.length;for(G=Y;G<W;G+=X)Z[0]=J[G],Z[1]=J[G+1],Z[2]=J[G+2],Q(Z,Z,K),J[G]=Z[0],J[G+1]=Z[1],J[G+2]=Z[2];return J}})();function XT(Z){let J=nn(),X=Z.propertyType===a.NODE?[Z]:Z.listChildren();for(let Y of X)Y.traverse(($)=>{let Q=$.getMesh();if(!Q)return;let K=bj1(Q,$.getWorldMatrix());if(K.min.every(isFinite)&&K.max.every(isFinite))eC(K.min,J),eC(K.max,J)});return J}function bj1(Z,J){let X=nn();for(let Y of Z.listPrimitives()){let $=Y.getAttribute("POSITION"),Q=Y.getIndices();if(!$)continue;let K=[0,0,0],G=[0,0,0];for(let W=0,H=Q?Q.getCount():$.getCount();W<H;W++){let V=Q?Q.getScalar(W):W;K=$.getElement(V,K),G=yj1(G,K,J),eC(G,X)}}return X}function eC(Z,J){for(let X=0;X<3;X++)J.min[X]=Math.min(Z[X],J.min[X]),J.max[X]=Math.max(Z[X],J.max[X])}function nn(){return{min:[1/0,1/0,1/0],max:[-1/0,-1/0,-1/0]}}class o0{static createBufferFromDataURI(Z){if(typeof Buffer==="undefined"){let J=atob(Z.split(",")[1]),X=new Uint8Array(J.length);for(let Y=0;Y<J.length;Y++)X[Y]=J.charCodeAt(Y);return X}else{let J=Z.split(",")[1],X=Z.indexOf("base64")>=0;return Buffer.from(J,X?"base64":"utf8")}}static encodeText(Z){return new TextEncoder().encode(Z)}static decodeText(Z){return new TextDecoder().decode(Z)}static concat(Z){let J=0;for(let $ of Z)J+=$.byteLength;let X=new Uint8Array(J),Y=0;for(let $ of Z)X.set($,Y),Y+=$.byteLength;return X}static pad(Z,J=0){let X=this.padNumber(Z.byteLength);if(X===Z.byteLength)return Z;let Y=new Uint8Array(X);if(Y.set(Z),J!==0)for(let $=Z.byteLength;$<X;$++)Y[$]=J;return Y}static padNumber(Z){return Math.ceil(Z/4)*4}static equals(Z,J){if(Z===J)return!0;if(Z.byteLength!==J.byteLength)return!1;let X=Z.byteLength;while(X--)if(Z[X]!==J[X])return!1;return!0}static toView(Z,J=0,X=1/0){return new Uint8Array(Z.buffer,Z.byteOffset+J,Math.min(Z.byteLength,X))}static assertView(Z){if(Z&&!ArrayBuffer.isView(Z))throw new Error(`Method requires Uint8Array parameter; received "${typeof Z}".`);return Z}}class YT{static hexToFactor(Z,J){Z=Math.floor(Z);let X=J;return X[0]=(Z>>16&255)/255,X[1]=(Z>>8&255)/255,X[2]=(Z&255)/255,this.convertSRGBToLinear(J,J)}static factorToHex(Z){let J=[...Z],[X,Y,$]=this.convertLinearToSRGB(Z,J);return X*255<<16^Y*255<<8^$*255<<0}static convertSRGBToLinear(Z,J){let X=Z,Y=J;for(let $=0;$<3;$++)Y[$]=X[$]<0.04045?X[$]*0.0773993808:Math.pow(X[$]*0.9478672986+0.0521327014,2.4);return J}static convertLinearToSRGB(Z,J){let X=Z,Y=J;for(let $=0;$<3;$++)Y[$]=X[$]<0.0031308?X[$]*12.92:1.055*Math.pow(X[$],0.41666)-0.055;return J}}class an{match(Z){return Z.length>=3&&Z[0]===255&&Z[1]===216&&Z[2]===255}getSize(Z){let J=new DataView(Z.buffer,Z.byteOffset+4),X,Y;while(J.byteLength){if(X=J.getUint16(0,!1),gj1(J,X),Y=J.getUint8(X+1),Y===192||Y===193||Y===194)return[J.getUint16(X+7,!1),J.getUint16(X+5,!1)];J=new DataView(Z.buffer,J.byteOffset+X+2)}throw new TypeError("Invalid JPG, no size found")}getChannels(Z){return 3}}class tB{match(Z){return Z.length>=8&&Z[0]===137&&Z[1]===80&&Z[2]===78&&Z[3]===71&&Z[4]===13&&Z[5]===10&&Z[6]===26&&Z[7]===10}getSize(Z){let J=new DataView(Z.buffer,Z.byteOffset);if(o0.decodeText(Z.slice(12,16))===tB.PNG_FRIED_CHUNK_NAME)return[J.getUint32(32,!1),J.getUint32(36,!1)];return[J.getUint32(16,!1),J.getUint32(20,!1)]}getChannels(Z){return 4}}tB.PNG_FRIED_CHUNK_NAME="CgBI";class kZ{static registerFormat(Z,J){this.impls[Z]=J}static getMimeType(Z){for(let J in this.impls)if(this.impls[J].match(Z))return J;return null}static getSize(Z,J){if(!this.impls[J])return null;return this.impls[J].getSize(Z)}static getChannels(Z,J){if(!this.impls[J])return null;return this.impls[J].getChannels(Z)}static getVRAMByteLength(Z,J){if(!this.impls[J])return null;if(this.impls[J].getVRAMByteLength)return this.impls[J].getVRAMByteLength(Z);let X=0,Y=4,$=this.getSize(Z,J);if(!$)return null;while($[0]>1||$[1]>1)X+=$[0]*$[1]*Y,$[0]=Math.max(Math.floor($[0]/2),1),$[1]=Math.max(Math.floor($[1]/2),1);return X+=1*Y,X}static mimeTypeToExtension(Z){if(Z==="image/jpeg")return"jpg";return Z.split("/").pop()}static extensionToMimeType(Z){if(Z==="jpg")return"image/jpeg";if(!Z)return"";return`image/${Z}`}}kZ.impls={"image/jpeg":new an,"image/png":new tB};function gj1(Z,J){if(J>Z.byteLength)throw new TypeError("Corrupt JPG, exceeded buffer limits");if(Z.getUint8(J)!==255)throw new TypeError("Invalid JPG, marker table corrupted");return Z}class IZ{static basename(Z){let J=Z.split(/[\\/]/).pop();return J.substring(0,J.lastIndexOf("."))}static extension(Z){if(Z.startsWith("data:image/")){let J=Z.match(/data:(image\/\w+)/)[1];return kZ.mimeTypeToExtension(J)}else if(Z.startsWith("data:model/gltf+json"))return"gltf";else if(Z.startsWith("data:model/gltf-binary"))return"glb";else if(Z.startsWith("data:application/"))return"bin";return Z.split(/[\\/]/).pop().split(/[.]/).pop()}}function gn(Z){return Object.prototype.toString.call(Z)==="[object Object]"}function aY(Z){if(gn(Z)===!1)return!1;let J=Z.constructor;if(J===void 0)return!0;let X=J.prototype;if(gn(X)===!1)return!1;if(Object.prototype.hasOwnProperty.call(X,"isPrototypeOf")===!1)return!1;return!0}var ZT,gH;(function(Z){Z[Z.SILENT=4]="SILENT",Z[Z.ERROR=3]="ERROR",Z[Z.WARN=2]="WARN",Z[Z.INFO=1]="INFO",Z[Z.DEBUG=0]="DEBUG"})(gH||(gH={}));class k5{constructor(Z){this.verbosity=void 0,this.verbosity=Z}debug(Z){if(this.verbosity<=k5.Verbosity.DEBUG)console.debug(Z)}info(Z){if(this.verbosity<=k5.Verbosity.INFO)console.info(Z)}warn(Z){if(this.verbosity<=k5.Verbosity.WARN)console.warn(Z)}error(Z){if(this.verbosity<=k5.Verbosity.ERROR)console.error(Z)}}ZT=k5;k5.Verbosity=gH;k5.DEFAULT_INSTANCE=new ZT(ZT.Verbosity.INFO);function mj1(Z){var J=Z[0],X=Z[1],Y=Z[2],$=Z[3],Q=Z[4],K=Z[5],G=Z[6],W=Z[7],H=Z[8],V=Z[9],F=Z[10],z=Z[11],q=Z[12],U=Z[13],B=Z[14],L=Z[15],w=J*K-X*Q,O=J*G-Y*Q,M=J*W-$*Q,R=X*G-Y*K,D=X*W-$*K,N=Y*W-$*G,C=H*U-V*q,T=H*B-F*q,E=H*L-z*q,x=V*B-F*U,S=V*L-z*U,h=F*L-z*B;return w*h-O*S+M*x+R*E-D*T+N*C}function uj1(Z,J,X){var Y=J[0],$=J[1],Q=J[2],K=J[3],G=J[4],W=J[5],H=J[6],V=J[7],F=J[8],z=J[9],q=J[10],U=J[11],B=J[12],L=J[13],w=J[14],O=J[15],M=X[0],R=X[1],D=X[2],N=X[3];return Z[0]=M*Y+R*G+D*F+N*B,Z[1]=M*$+R*W+D*z+N*L,Z[2]=M*Q+R*H+D*q+N*w,Z[3]=M*K+R*V+D*U+N*O,M=X[4],R=X[5],D=X[6],N=X[7],Z[4]=M*Y+R*G+D*F+N*B,Z[5]=M*$+R*W+D*z+N*L,Z[6]=M*Q+R*H+D*q+N*w,Z[7]=M*K+R*V+D*U+N*O,M=X[8],R=X[9],D=X[10],N=X[11],Z[8]=M*Y+R*G+D*F+N*B,Z[9]=M*$+R*W+D*z+N*L,Z[10]=M*Q+R*H+D*q+N*w,Z[11]=M*K+R*V+D*U+N*O,M=X[12],R=X[13],D=X[14],N=X[15],Z[12]=M*Y+R*G+D*F+N*B,Z[13]=M*$+R*W+D*z+N*L,Z[14]=M*Q+R*H+D*q+N*w,Z[15]=M*K+R*V+D*U+N*O,Z}function dj1(Z,J){var X=J[0],Y=J[1],$=J[2],Q=J[4],K=J[5],G=J[6],W=J[8],H=J[9],V=J[10];return Z[0]=Math.hypot(X,Y,$),Z[1]=Math.hypot(Q,K,G),Z[2]=Math.hypot(W,H,V),Z}function cj1(Z,J){var X=new tC(3);dj1(X,J);var Y=1/X[0],$=1/X[1],Q=1/X[2],K=J[0]*Y,G=J[1]*$,W=J[2]*Q,H=J[4]*Y,V=J[5]*$,F=J[6]*Q,z=J[8]*Y,q=J[9]*$,U=J[10]*Q,B=K+V+U,L=0;if(B>0)L=Math.sqrt(B+1)*2,Z[3]=0.25*L,Z[0]=(F-q)/L,Z[1]=(z-W)/L,Z[2]=(G-H)/L;else if(K>V&&K>U)L=Math.sqrt(1+K-V-U)*2,Z[3]=(F-q)/L,Z[0]=0.25*L,Z[1]=(G+H)/L,Z[2]=(z+W)/L;else if(V>U)L=Math.sqrt(1+V-K-U)*2,Z[3]=(z-W)/L,Z[0]=(G+H)/L,Z[1]=0.25*L,Z[2]=(F+q)/L;else L=Math.sqrt(1+U-K-V)*2,Z[3]=(G-H)/L,Z[0]=(z+W)/L,Z[1]=(F+q)/L,Z[2]=0.25*L;return Z}class i0{static identity(Z){return Z}static eq(Z,J,X=0.00001){if(Z.length!==J.length)return!1;for(let Y=0;Y<Z.length;Y++)if(Math.abs(Z[Y]-J[Y])>X)return!1;return!0}static clamp(Z,J,X){if(Z<J)return J;if(Z>X)return X;return Z}static decodeNormalizedInt(Z,J){switch(J){case 5126:return Z;case 5123:return Z/65535;case 5121:return Z/255;case 5122:return Math.max(Z/32767,-1);case 5120:return Math.max(Z/127,-1);default:throw new Error("Invalid component type.")}}static encodeNormalizedInt(Z,J){switch(J){case 5126:return Z;case 5123:return Math.round(i0.clamp(Z,0,1)*65535);case 5121:return Math.round(i0.clamp(Z,0,1)*255);case 5122:return Math.round(i0.clamp(Z,-1,1)*32767);case 5120:return Math.round(i0.clamp(Z,-1,1)*127);default:throw new Error("Invalid component type.")}}static decompose(Z,J,X,Y){let $=rC([Z[0],Z[1],Z[2]]),Q=rC([Z[4],Z[5],Z[6]]),K=rC([Z[8],Z[9],Z[10]]);if(mj1(Z)<0)$=-$;J[0]=Z[12],J[1]=Z[13],J[2]=Z[14];let W=Z.slice(),H=1/$,V=1/Q,F=1/K;W[0]*=H,W[1]*=H,W[2]*=H,W[4]*=V,W[5]*=V,W[6]*=V,W[8]*=F,W[9]*=F,W[10]*=F,cj1(X,W),Y[0]=$,Y[1]=Q,Y[2]=K}static compose(Z,J,X,Y){let $=Y,Q=J[0],K=J[1],G=J[2],W=J[3],H=Q+Q,V=K+K,F=G+G,z=Q*H,q=Q*V,U=Q*F,B=K*V,L=K*F,w=G*F,O=W*H,M=W*V,R=W*F,D=X[0],N=X[1],C=X[2];return $[0]=(1-(B+w))*D,$[1]=(q+R)*D,$[2]=(U-M)*D,$[3]=0,$[4]=(q-R)*N,$[5]=(1-(z+w))*N,$[6]=(L+O)*N,$[7]=0,$[8]=(U+M)*C,$[9]=(L-O)*C,$[10]=(1-(z+B))*C,$[11]=0,$[12]=Z[0],$[13]=Z[1],$[14]=Z[2],$[15]=1,$}}function lj1(Z,J){if(!!Z!==!!J)return!1;let X=Z.getChild(),Y=J.getChild();return X===Y||X.equals(Y)}function pj1(Z,J){if(!!Z!==!!J)return!1;let X=Z.values(),Y=J.values();if(X.length!==Y.length)return!1;for(let $=0;$<X.length;$++){let Q=X[$],K=Y[$];if(Q.getChild()===K.getChild())continue;if(!Q.getChild().equals(K.getChild()))return!1}return!0}function ij1(Z,J){if(!!Z!==!!J)return!1;let X=Z.keys(),Y=J.keys();if(X.length!==Y.length)return!1;for(let $ of X){let Q=Z.get($),K=J.get($);if(!!Q!==!!K)return!1;let G=Q.getChild(),W=K.getChild();if(G===W)continue;if(!G.equals(W))return!1}return!0}function sn(Z,J){if(Z===J)return!0;if(!!Z!==!!J||!Z||!J)return!1;if(Z.length!==J.length)return!1;for(let X=0;X<Z.length;X++)if(Z[X]!==J[X])return!1;return!0}function on(Z,J){if(Z===J)return!0;if(!!Z!==!!J)return!1;if(!aY(Z)||!aY(J))return Z===J;let X=Z,Y=J,$=0,Q=0,K;for(K in X)$++;for(K in Y)Q++;if($!==Q)return!1;for(K in X){let G=X[K],W=Y[K];if(oB(G)&&oB(W)){if(!sn(G,W))return!1}else if(aY(G)&&aY(W)){if(!on(G,W))return!1}else if(G!==W)return!1}return!0}function oB(Z){return Array.isArray(Z)||ArrayBuffer.isView(Z)}var mn="23456789abdegjkmnpqrvwxyzABDEGJKMNPQRVWXYZ",nj1=999,aj1=6,un=new Set,sj1=function Z(){let J="";for(let X=0;X<aj1;X++)J+=mn.charAt(Math.floor(Math.random()*mn.length));return J},rn=function Z(){for(let J=0;J<nj1;J++){let X=sj1();if(!un.has(X))return un.add(X),X}return""},dn="https://null.example";class f9{static dirname(Z){let J=Z.lastIndexOf("/");if(J===-1)return"./";return Z.substring(0,J+1)}static basename(Z){return IZ.basename(new URL(Z,dn).pathname)}static extension(Z){return IZ.extension(new URL(Z,dn).pathname)}static resolve(Z,J){if(!this.isRelativePath(J))return J;let X=Z.split("/"),Y=J.split("/");X.pop();for(let $=0;$<Y.length;$++){if(Y[$]===".")continue;if(Y[$]==="..")X.pop();else X.push(Y[$])}return X.join("/")}static isAbsoluteURL(Z){return this.PROTOCOL_REGEXP.test(Z)}static isRelativePath(Z){return!/^(?:[a-zA-Z]+:)?\//.test(Z)}}f9.DEFAULT_INIT={};f9.PROTOCOL_REGEXP=/^[a-zA-Z]+:\/\//;var pJ=(Z)=>Z,oj1=new Set;class eB extends iK{constructor(Z,J=""){super(Z);this[y0].name=J,this.init(),this.dispatchEvent({type:"create"})}getGraph(){return this.graph}getDefaults(){return Object.assign(super.getDefaults(),{name:"",extras:{}})}set(Z,J){if(Array.isArray(J))J=J.slice();return super.set(Z,J)}getName(){return this.get("name")}setName(Z){return this.set("name",Z)}getExtras(){return this.get("extras")}setExtras(Z){return this.set("extras",Z)}clone(){return new this.constructor(this.graph).copy(this,pJ)}copy(Z,J=pJ){for(let X in this[y0]){let Y=this[y0][X];if(Y instanceof T5){if(!this[A4].has(X))Y.dispose()}else if(Y instanceof I6||Y instanceof E0)for(let $ of Y.values())$.dispose();else if(Y instanceof Z8)for(let $ of Y.values())$.dispose()}for(let X in Z[y0]){let Y=this[y0][X],$=Z[y0][X];if($ instanceof T5)if(this[A4].has(X))Y.getChild().copy(J($.getChild()),J);else this.setRef(X,J($.getChild()),$.getAttributes());else if($ instanceof E0||$ instanceof I6)for(let Q of $.values())this.addRef(X,J(Q.getChild()),Q.getAttributes());else if($ instanceof Z8)for(let Q of $.keys()){let K=$.get(Q);this.setRefMap(X,Q,J(K.getChild()),K.getAttributes())}else if(aY($))this[y0][X]=JSON.parse(JSON.stringify($));else if(Array.isArray($)||$ instanceof ArrayBuffer||ArrayBuffer.isView($))this[y0][X]=$.slice();else this[y0][X]=$}return this}equals(Z,J=oj1){if(this===Z)return!0;if(this.propertyType!==Z.propertyType)return!1;for(let X in this[y0]){if(J.has(X))continue;let Y=this[y0][X],$=Z[y0][X];if(Y instanceof T5||$ instanceof T5){if(!lj1(Y,$))return!1}else if(Y instanceof E0||$ instanceof E0||Y instanceof I6||$ instanceof I6){if(!pj1(Y,$))return!1}else if(Y instanceof Z8||$ instanceof Z8){if(!ij1(Y,$))return!1}else if(aY(Y)||aY($)){if(!on(Y,$))return!1}else if(oB(Y)||oB($)){if(!sn(Y,$))return!1}else if(Y!==$)return!1}return!0}detach(){return this.graph.disconnectParents(this,(Z)=>Z.propertyType!=="Root"),this}listParents(){return this.graph.listParents(this)}}class S6 extends eB{getDefaults(){return Object.assign(super.getDefaults(),{extensions:new Z8})}getExtension(Z){return this.getRefMap("extensions",Z)}setExtension(Z,J){if(J)J._validateParent(this);return this.setRefMap("extensions",Z,J)}listExtensions(){return this.listRefMapValues("extensions")}}class x0 extends S6{init(){this.propertyType=a.ACCESSOR}getDefaults(){return Object.assign(super.getDefaults(),{array:null,type:x0.Type.SCALAR,componentType:x0.ComponentType.FLOAT,normalized:!1,sparse:!1,buffer:null})}static getElementSize(Z){switch(Z){case x0.Type.SCALAR:return 1;case x0.Type.VEC2:return 2;case x0.Type.VEC3:return 3;case x0.Type.VEC4:return 4;case x0.Type.MAT2:return 4;case x0.Type.MAT3:return 9;case x0.Type.MAT4:return 16;default:throw new Error("Unexpected type: "+Z)}}static getComponentSize(Z){switch(Z){case x0.ComponentType.BYTE:return 1;case x0.ComponentType.UNSIGNED_BYTE:return 1;case x0.ComponentType.SHORT:return 2;case x0.ComponentType.UNSIGNED_SHORT:return 2;case x0.ComponentType.UNSIGNED_INT:return 4;case x0.ComponentType.FLOAT:return 4;default:throw new Error("Unexpected component type: "+Z)}}getMinNormalized(Z){let J=this.getNormalized(),X=this.getElementSize(),Y=this.getComponentType();if(this.getMin(Z),J)for(let $=0;$<X;$++)Z[$]=i0.decodeNormalizedInt(Z[$],Y);return Z}getMin(Z){let J=this.getArray(),X=this.getCount(),Y=this.getElementSize();for(let $=0;$<Y;$++)Z[$]=1/0;for(let $=0;$<X*Y;$+=Y)for(let Q=0;Q<Y;Q++){let K=J[$+Q];if(Number.isFinite(K))Z[Q]=Math.min(Z[Q],K)}return Z}getMaxNormalized(Z){let J=this.getNormalized(),X=this.getElementSize(),Y=this.getComponentType();if(this.getMax(Z),J)for(let $=0;$<X;$++)Z[$]=i0.decodeNormalizedInt(Z[$],Y);return Z}getMax(Z){let J=this.get("array"),X=this.getCount(),Y=this.getElementSize();for(let $=0;$<Y;$++)Z[$]=-1/0;for(let $=0;$<X*Y;$+=Y)for(let Q=0;Q<Y;Q++){let K=J[$+Q];if(Number.isFinite(K))Z[Q]=Math.max(Z[Q],K)}return Z}getCount(){let Z=this.get("array");return Z?Z.length/this.getElementSize():0}getType(){return this.get("type")}setType(Z){return this.set("type",Z)}getElementSize(){return x0.getElementSize(this.get("type"))}getComponentSize(){return this.get("array").BYTES_PER_ELEMENT}getComponentType(){return this.get("componentType")}getNormalized(){return this.get("normalized")}setNormalized(Z){return this.set("normalized",Z)}getScalar(Z){let J=this.getElementSize(),X=this.getComponentType(),Y=this.getArray();if(this.getNormalized())return i0.decodeNormalizedInt(Y[Z*J],X);return Y[Z*J]}setScalar(Z,J){let X=this.getElementSize(),Y=this.getComponentType(),$=this.getArray();if(this.getNormalized())$[Z*X]=i0.encodeNormalizedInt(J,Y);else $[Z*X]=J;return this}getElement(Z,J){let X=this.getNormalized(),Y=this.getElementSize(),$=this.getComponentType(),Q=this.getArray();for(let K=0;K<Y;K++)if(X)J[K]=i0.decodeNormalizedInt(Q[Z*Y+K],$);else J[K]=Q[Z*Y+K];return J}setElement(Z,J){let X=this.getNormalized(),Y=this.getElementSize(),$=this.getComponentType(),Q=this.getArray();for(let K=0;K<Y;K++)if(X)Q[Z*Y+K]=i0.encodeNormalizedInt(J[K],$);else Q[Z*Y+K]=J[K];return this}getSparse(){return this.get("sparse")}setSparse(Z){return this.set("sparse",Z)}getBuffer(){return this.getRef("buffer")}setBuffer(Z){return this.setRef("buffer",Z)}getArray(){return this.get("array")}setArray(Z){return this.set("componentType",Z?rj1(Z):x0.ComponentType.FLOAT),this.set("array",Z),this}getByteLength(){let Z=this.get("array");return Z?Z.byteLength:0}}x0.Type={SCALAR:"SCALAR",VEC2:"VEC2",VEC3:"VEC3",VEC4:"VEC4",MAT2:"MAT2",MAT3:"MAT3",MAT4:"MAT4"};x0.ComponentType={BYTE:5120,UNSIGNED_BYTE:5121,SHORT:5122,UNSIGNED_SHORT:5123,UNSIGNED_INT:5125,FLOAT:5126};function rj1(Z){switch(Z.constructor){case Float32Array:return x0.ComponentType.FLOAT;case Uint32Array:return x0.ComponentType.UNSIGNED_INT;case Uint16Array:return x0.ComponentType.UNSIGNED_SHORT;case Uint8Array:return x0.ComponentType.UNSIGNED_BYTE;case Int16Array:return x0.ComponentType.SHORT;case Int8Array:return x0.ComponentType.BYTE;default:throw new Error("Unknown accessor componentType.")}}class $T extends S6{init(){this.propertyType=a.ANIMATION}getDefaults(){return Object.assign(super.getDefaults(),{channels:new E0,samplers:new E0})}addChannel(Z){return this.addRef("channels",Z)}removeChannel(Z){return this.removeRef("channels",Z)}listChannels(){return this.listRefs("channels")}addSampler(Z){return this.addRef("samplers",Z)}removeSampler(Z){return this.removeRef("samplers",Z)}listSamplers(){return this.listRefs("samplers")}}class sY extends S6{init(){this.propertyType=a.ANIMATION_CHANNEL}getDefaults(){return Object.assign(super.getDefaults(),{targetPath:null,targetNode:null,sampler:null})}getTargetPath(){return this.get("targetPath")}setTargetPath(Z){return this.set("targetPath",Z)}getTargetNode(){return this.getRef("targetNode")}setTargetNode(Z){return this.setRef("targetNode",Z)}getSampler(){return this.getRef("sampler")}setSampler(Z){return this.setRef("sampler",Z)}}sY.TargetPath={TRANSLATION:"translation",ROTATION:"rotation",SCALE:"scale",WEIGHTS:"weights"};class nK extends S6{init(){this.propertyType=a.ANIMATION_SAMPLER}getDefaultAttributes(){return Object.assign(super.getDefaults(),{interpolation:nK.Interpolation.LINEAR,input:null,output:null})}getInterpolation(){return this.get("interpolation")}setInterpolation(Z){return this.set("interpolation",Z)}getInput(){return this.getRef("input")}setInput(Z){return this.setRef("input",Z,{usage:e5.OTHER})}getOutput(){return this.getRef("output")}setOutput(Z){return this.setRef("output",Z,{usage:e5.OTHER})}}nK.Interpolation={LINEAR:"LINEAR",STEP:"STEP",CUBICSPLINE:"CUBICSPLINE"};class QT extends S6{init(){this.propertyType=a.BUFFER}getDefaults(){return Object.assign(super.getDefaults(),{uri:""})}getURI(){return this.get("uri")}setURI(Z){return this.set("uri",Z)}}class oY extends S6{init(){this.propertyType=a.CAMERA}getDefaults(){return Object.assign(super.getDefaults(),{type:oY.Type.PERSPECTIVE,znear:0.1,zfar:100,aspectRatio:null,yfov:Math.PI*2*50/360,xmag:1,ymag:1})}getType(){return this.get("type")}setType(Z){return this.set("type",Z)}getZNear(){return this.get("znear")}setZNear(Z){return this.set("znear",Z)}getZFar(){return this.get("zfar")}setZFar(Z){return this.set("zfar",Z)}getAspectRatio(){return this.get("aspectRatio")}setAspectRatio(Z){return this.set("aspectRatio",Z)}getYFov(){return this.get("yfov")}setYFov(Z){return this.set("yfov",Z)}getXMag(){return this.get("xmag")}setXMag(Z){return this.set("xmag",Z)}getYMag(){return this.get("ymag")}setYMag(Z){return this.set("ymag",Z)}}oY.Type={PERSPECTIVE:"perspective",ORTHOGRAPHIC:"orthographic"};class aK extends eB{_validateParent(Z){if(!this.parentTypes.includes(Z.propertyType))throw new Error(`Parent "${Z.propertyType}" invalid for child "${this.propertyType}".`)}}aK.EXTENSION_NAME=void 0;class E5 extends S6{init(){this.propertyType=a.TEXTURE_INFO}getDefaults(){return Object.assign(super.getDefaults(),{texCoord:0,magFilter:null,minFilter:null,wrapS:E5.WrapMode.REPEAT,wrapT:E5.WrapMode.REPEAT})}getTexCoord(){return this.get("texCoord")}setTexCoord(Z){return this.set("texCoord",Z)}getMagFilter(){return this.get("magFilter")}setMagFilter(Z){return this.set("magFilter",Z)}getMinFilter(){return this.get("minFilter")}setMinFilter(Z){return this.set("minFilter",Z)}getWrapS(){return this.get("wrapS")}setWrapS(Z){return this.set("wrapS",Z)}getWrapT(){return this.get("wrapT")}setWrapT(Z){return this.set("wrapT",Z)}}E5.WrapMode={CLAMP_TO_EDGE:33071,MIRRORED_REPEAT:33648,REPEAT:10497};E5.MagFilter={NEAREST:9728,LINEAR:9729};E5.MinFilter={NEAREST:9728,LINEAR:9729,NEAREST_MIPMAP_NEAREST:9984,LINEAR_MIPMAP_NEAREST:9985,NEAREST_MIPMAP_LINEAR:9986,LINEAR_MIPMAP_LINEAR:9987};var{R:dB,G:cB,B:lB,A:tj1}=sB;class D7 extends S6{init(){this.propertyType=a.MATERIAL}getDefaults(){return Object.assign(super.getDefaults(),{alphaMode:D7.AlphaMode.OPAQUE,alphaCutoff:0.5,doubleSided:!1,baseColorFactor:[1,1,1,1],baseColorTexture:null,baseColorTextureInfo:new E5(this.graph,"baseColorTextureInfo"),emissiveFactor:[0,0,0],emissiveTexture:null,emissiveTextureInfo:new E5(this.graph,"emissiveTextureInfo"),normalScale:1,normalTexture:null,normalTextureInfo:new E5(this.graph,"normalTextureInfo"),occlusionStrength:1,occlusionTexture:null,occlusionTextureInfo:new E5(this.graph,"occlusionTextureInfo"),roughnessFactor:1,metallicFactor:1,metallicRoughnessTexture:null,metallicRoughnessTextureInfo:new E5(this.graph,"metallicRoughnessTextureInfo")})}getDoubleSided(){return this.get("doubleSided")}setDoubleSided(Z){return this.set("doubleSided",Z)}getAlpha(){return this.get("baseColorFactor")[3]}setAlpha(Z){let J=this.get("baseColorFactor").slice();return J[3]=Z,this.set("baseColorFactor",J)}getAlphaMode(){return this.get("alphaMode")}setAlphaMode(Z){return this.set("alphaMode",Z)}getAlphaCutoff(){return this.get("alphaCutoff")}setAlphaCutoff(Z){return this.set("alphaCutoff",Z)}getBaseColorFactor(){return this.get("baseColorFactor")}setBaseColorFactor(Z){return this.set("baseColorFactor",Z)}getBaseColorTexture(){return this.getRef("baseColorTexture")}getBaseColorTextureInfo(){return this.getRef("baseColorTexture")?this.getRef("baseColorTextureInfo"):null}setBaseColorTexture(Z){return this.setRef("baseColorTexture",Z,{channels:dB|cB|lB|tj1,isColor:!0})}getEmissiveFactor(){return this.get("emissiveFactor")}setEmissiveFactor(Z){return this.set("emissiveFactor",Z)}getEmissiveTexture(){return this.getRef("emissiveTexture")}getEmissiveTextureInfo(){return this.getRef("emissiveTexture")?this.getRef("emissiveTextureInfo"):null}setEmissiveTexture(Z){return this.setRef("emissiveTexture",Z,{channels:dB|cB|lB,isColor:!0})}getNormalScale(){return this.get("normalScale")}setNormalScale(Z){return this.set("normalScale",Z)}getNormalTexture(){return this.getRef("normalTexture")}getNormalTextureInfo(){return this.getRef("normalTexture")?this.getRef("normalTextureInfo"):null}setNormalTexture(Z){return this.setRef("normalTexture",Z,{channels:dB|cB|lB})}getOcclusionStrength(){return this.get("occlusionStrength")}setOcclusionStrength(Z){return this.set("occlusionStrength",Z)}getOcclusionTexture(){return this.getRef("occlusionTexture")}getOcclusionTextureInfo(){return this.getRef("occlusionTexture")?this.getRef("occlusionTextureInfo"):null}setOcclusionTexture(Z){return this.setRef("occlusionTexture",Z,{channels:dB})}getRoughnessFactor(){return this.get("roughnessFactor")}setRoughnessFactor(Z){return this.set("roughnessFactor",Z)}getMetallicFactor(){return this.get("metallicFactor")}setMetallicFactor(Z){return this.set("metallicFactor",Z)}getMetallicRoughnessTexture(){return this.getRef("metallicRoughnessTexture")}getMetallicRoughnessTextureInfo(){return this.getRef("metallicRoughnessTexture")?this.getRef("metallicRoughnessTextureInfo"):null}setMetallicRoughnessTexture(Z){return this.setRef("metallicRoughnessTexture",Z,{channels:cB|lB})}}D7.AlphaMode={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};class uH extends S6{init(){this.propertyType=a.MESH}getDefaults(){return Object.assign(super.getDefaults(),{weights:[],primitives:new E0})}addPrimitive(Z){return this.addRef("primitives",Z)}removePrimitive(Z){return this.removeRef("primitives",Z)}listPrimitives(){return this.listRefs("primitives")}getWeights(){return this.get("weights")}setWeights(Z){return this.set("weights",Z)}}class Z2 extends S6{init(){this.propertyType=a.NODE}getDefaults(){return Object.assign(super.getDefaults(),{translation:[0,0,0],rotation:[0,0,0,1],scale:[1,1,1],weights:[],camera:null,mesh:null,skin:null,children:new E0})}copy(Z,J=pJ){if(J===pJ)throw new Error("Node cannot be copied.");return super.copy(Z,J)}getTranslation(){return this.get("translation")}getRotation(){return this.get("rotation")}getScale(){return this.get("scale")}setTranslation(Z){return this.set("translation",Z)}setRotation(Z){return this.set("rotation",Z)}setScale(Z){return this.set("scale",Z)}getMatrix(){return i0.compose(this.get("translation"),this.get("rotation"),this.get("scale"),[])}setMatrix(Z){let J=this.get("translation").slice(),X=this.get("rotation").slice(),Y=this.get("scale").slice();return i0.decompose(Z,J,X,Y),this.set("translation",J).set("rotation",X).set("scale",Y)}getWorldTranslation(){let Z=[0,0,0];return i0.decompose(this.getWorldMatrix(),Z,[0,0,0,1],[1,1,1]),Z}getWorldRotation(){let Z=[0,0,0,1];return i0.decompose(this.getWorldMatrix(),[0,0,0],Z,[1,1,1]),Z}getWorldScale(){let Z=[1,1,1];return i0.decompose(this.getWorldMatrix(),[0,0,0],[0,0,0,1],Z),Z}getWorldMatrix(){let Z=[];for(let Y=this;Y!=null;Y=Y.getParentNode())Z.push(Y);let J,X=Z.pop().getMatrix();while(J=Z.pop())uj1(X,X,J.getMatrix());return X}addChild(Z){let J=Z.getParentNode();if(J)J.removeChild(Z);for(let X of Z.listParents())if(X.propertyType===a.SCENE)X.removeChild(Z);return this.addRef("children",Z)}removeChild(Z){return this.removeRef("children",Z)}listChildren(){return this.listRefs("children")}getParentNode(){for(let Z of this.listParents())if(Z.propertyType===a.NODE)return Z;return null}getMesh(){return this.getRef("mesh")}setMesh(Z){return this.setRef("mesh",Z)}getCamera(){return this.getRef("camera")}setCamera(Z){return this.setRef("camera",Z)}getSkin(){return this.getRef("skin")}setSkin(Z){return this.setRef("skin",Z)}getWeights(){return this.get("weights")}setWeights(Z){return this.set("weights",Z)}traverse(Z){Z(this);for(let J of this.listChildren())J.traverse(Z);return this}}class C8 extends S6{init(){this.propertyType=a.PRIMITIVE}getDefaults(){return Object.assign(super.getDefaults(),{mode:C8.Mode.TRIANGLES,material:null,indices:null,attributes:new Z8,targets:new E0})}getIndices(){return this.getRef("indices")}setIndices(Z){return this.setRef("indices",Z,{usage:e5.ELEMENT_ARRAY_BUFFER})}getAttribute(Z){return this.getRefMap("attributes",Z)}setAttribute(Z,J){return this.setRefMap("attributes",Z,J,{usage:e5.ARRAY_BUFFER})}listAttributes(){return this.listRefMapValues("attributes")}listSemantics(){return this.listRefMapKeys("attributes")}getMaterial(){return this.getRef("material")}setMaterial(Z){return this.setRef("material",Z)}getMode(){return this.get("mode")}setMode(Z){return this.set("mode",Z)}listTargets(){return this.listRefs("targets")}addTarget(Z){return this.addRef("targets",Z)}removeTarget(Z){return this.removeRef("targets",Z)}}C8.Mode={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6};class KT extends eB{init(){this.propertyType=a.PRIMITIVE_TARGET}getDefaults(){return Object.assign(super.getDefaults(),{attributes:new Z8})}getAttribute(Z){return this.getRefMap("attributes",Z)}setAttribute(Z,J){return this.setRefMap("attributes",Z,J,{usage:e5.ARRAY_BUFFER})}listAttributes(){return this.listRefMapValues("attributes")}listSemantics(){return this.listRefMapKeys("attributes")}}function r6(){return r6=Object.assign?Object.assign.bind():function(Z){for(var J=1;J<arguments.length;J++){var X=arguments[J];for(var Y in X)({}).hasOwnProperty.call(X,Y)&&(Z[Y]=X[Y])}return Z},r6.apply(null,arguments)}class sK extends S6{init(){this.propertyType=a.SCENE}getDefaults(){return Object.assign(super.getDefaults(),{children:new E0})}copy(Z,J=pJ){if(J===pJ)throw new Error("Scene cannot be copied.");return super.copy(Z,J)}addChild(Z){let J=Z.getParentNode();if(J)J.removeChild(Z);return this.addRef("children",Z)}removeChild(Z){return this.removeRef("children",Z)}listChildren(){return this.listRefs("children")}traverse(Z){for(let J of this.listChildren())J.traverse(Z);return this}}class GT extends S6{init(){this.propertyType=a.SKIN}getDefaults(){return Object.assign(super.getDefaults(),{skeleton:null,inverseBindMatrices:null,joints:new E0})}getSkeleton(){return this.getRef("skeleton")}setSkeleton(Z){return this.setRef("skeleton",Z)}getInverseBindMatrices(){return this.getRef("inverseBindMatrices")}setInverseBindMatrices(Z){return this.setRef("inverseBindMatrices",Z,{usage:e5.INVERSE_BIND_MATRICES})}addJoint(Z){return this.addRef("joints",Z)}removeJoint(Z){return this.removeRef("joints",Z)}listJoints(){return this.listRefs("joints")}}class rY extends S6{init(){this.propertyType=a.TEXTURE}getDefaults(){return Object.assign(super.getDefaults(),{image:null,mimeType:"",uri:""})}getMimeType(){return this.get("mimeType")||kZ.extensionToMimeType(IZ.extension(this.get("uri")))}setMimeType(Z){return this.set("mimeType",Z)}getURI(){return this.get("uri")}setURI(Z){this.set("uri",Z);let J=kZ.extensionToMimeType(IZ.extension(Z));if(J)this.set("mimeType",J);return this}getImage(){return this.get("image")}setImage(Z){return this.set("image",o0.assertView(Z))}getSize(){let Z=this.get("image");if(!Z)return null;return kZ.getSize(Z,this.getMimeType())}}class tY extends S6{init(){this.propertyType=a.ROOT}getDefaults(){return Object.assign(super.getDefaults(),{asset:{generator:`glTF-Transform ${pn}`,version:"2.0"},defaultScene:null,accessors:new E0,animations:new E0,buffers:new E0,cameras:new E0,materials:new E0,meshes:new E0,nodes:new E0,scenes:new E0,skins:new E0,textures:new E0})}constructor(Z){super(Z);this._extensions=new Set,Z.addEventListener("node:create",(J)=>{this._addChildOfRoot(J.target)})}clone(){throw new Error("Root cannot be cloned.")}copy(Z,J=pJ){if(J===pJ)throw new Error("Root cannot be copied.");this.set("asset",r6({},Z.get("asset"))),this.setName(Z.getName()),this.setExtras(r6({},Z.getExtras())),this.setDefaultScene(Z.getDefaultScene()?J(Z.getDefaultScene()):null);for(let X of Z.listRefMapKeys("extensions")){let Y=Z.getExtension(X);this.setExtension(X,J(Y))}return this}_addChildOfRoot(Z){if(Z instanceof sK)this.addRef("scenes",Z);else if(Z instanceof Z2)this.addRef("nodes",Z);else if(Z instanceof oY)this.addRef("cameras",Z);else if(Z instanceof GT)this.addRef("skins",Z);else if(Z instanceof uH)this.addRef("meshes",Z);else if(Z instanceof D7)this.addRef("materials",Z);else if(Z instanceof rY)this.addRef("textures",Z);else if(Z instanceof $T)this.addRef("animations",Z);else if(Z instanceof x0)this.addRef("accessors",Z);else if(Z instanceof QT)this.addRef("buffers",Z);return this}getAsset(){return this.get("asset")}listExtensionsUsed(){return Array.from(this._extensions)}listExtensionsRequired(){return this.listExtensionsUsed().filter((Z)=>Z.isRequired())}_enableExtension(Z){return this._extensions.add(Z),this}_disableExtension(Z){return this._extensions.delete(Z),this}listScenes(){return this.listRefs("scenes")}setDefaultScene(Z){return this.setRef("defaultScene",Z)}getDefaultScene(){return this.getRef("defaultScene")}listNodes(){return this.listRefs("nodes")}listCameras(){return this.listRefs("cameras")}listSkins(){return this.listRefs("skins")}listMeshes(){return this.listRefs("meshes")}listMaterials(){return this.listRefs("materials")}listTextures(){return this.listRefs("textures")}listAnimations(){return this.listRefs("animations")}listAccessors(){return this.listRefs("accessors")}listBuffers(){return this.listRefs("buffers")}}class _6{static fromGraph(Z){return _6._GRAPH_DOCUMENTS.get(Z)||null}constructor(){this._graph=new pK,this._root=new tY(this._graph),this._logger=k5.DEFAULT_INSTANCE,_6._GRAPH_DOCUMENTS.set(this._graph,this)}getRoot(){return this._root}getGraph(){return this._graph}getLogger(){return this._logger}setLogger(Z){return this._logger=Z,this}clone(){throw new Error("Use 'cloneDocument(source)' from '@gltf-transform/functions'.")}merge(Z){throw new Error("Use 'mergeDocuments(target, source)' from '@gltf-transform/functions'.")}async transform(...Z){let J=Z.map((X)=>X.name);for(let X of Z)await X(this,{stack:J});return this}createExtension(Z){let J=Z.EXTENSION_NAME;return this.getRoot().listExtensionsUsed().find((Y)=>Y.extensionName===J)||new Z(this)}createScene(Z=""){return new sK(this._graph,Z)}createNode(Z=""){return new Z2(this._graph,Z)}createCamera(Z=""){return new oY(this._graph,Z)}createSkin(Z=""){return new GT(this._graph,Z)}createMesh(Z=""){return new uH(this._graph,Z)}createPrimitive(){return new C8(this._graph)}createPrimitiveTarget(Z=""){return new KT(this._graph,Z)}createMaterial(Z=""){return new D7(this._graph,Z)}createTexture(Z=""){return new rY(this._graph,Z)}createAnimation(Z=""){return new $T(this._graph,Z)}createAnimationChannel(Z=""){return new sY(this._graph,Z)}createAnimationSampler(Z=""){return new nK(this._graph,Z)}createAccessor(Z="",J=null){if(!J)J=this.getRoot().listBuffers()[0];return new x0(this._graph,Z).setBuffer(J)}createBuffer(Z=""){return new QT(this._graph,Z)}}_6._GRAPH_DOCUMENTS=new WeakMap;class tn{constructor(Z){this.extensionName="",this.prereadTypes=[],this.prewriteTypes=[],this.readDependencies=[],this.writeDependencies=[],this.document=void 0,this.required=!1,this.properties=new Set,this._listener=void 0,this.document=Z,Z.getRoot()._enableExtension(this),this._listener=(X)=>{let Y=X,$=Y.target;if($ instanceof aK&&$.extensionName===this.extensionName){if(Y.type==="node:create")this._addExtensionProperty($);if(Y.type==="node:dispose")this._removeExtensionProperty($)}};let J=Z.getGraph();J.addEventListener("node:create",this._listener),J.addEventListener("node:dispose",this._listener)}dispose(){this.document.getRoot()._disableExtension(this);let Z=this.document.getGraph();Z.removeEventListener("node:create",this._listener),Z.removeEventListener("node:dispose",this._listener);for(let J of this.properties)J.dispose()}static register(){}isRequired(){return this.required}setRequired(Z){return this.required=Z,this}listProperties(){return Array.from(this.properties)}_addExtensionProperty(Z){return this.properties.add(Z),this}_removeExtensionProperty(Z){return this.properties.delete(Z),this}install(Z,J){return this}preread(Z,J){return this}prewrite(Z,J){return this}}tn.EXTENSION_NAME=void 0;class en{constructor(Z){this.jsonDoc=void 0,this.buffers=[],this.bufferViews=[],this.bufferViewBuffers=[],this.accessors=[],this.textures=[],this.textureInfos=new Map,this.materials=[],this.meshes=[],this.cameras=[],this.nodes=[],this.skins=[],this.animations=[],this.scenes=[],this.jsonDoc=Z}setTextureInfo(Z,J){if(this.textureInfos.set(Z,J),J.texCoord!==void 0)Z.setTexCoord(J.texCoord);if(J.extras!==void 0)Z.setExtras(J.extras);let X=this.jsonDoc.json.textures[J.index];if(X.sampler===void 0)return;let Y=this.jsonDoc.json.samplers[X.sampler];if(Y.magFilter!==void 0)Z.setMagFilter(Y.magFilter);if(Y.minFilter!==void 0)Z.setMinFilter(Y.minFilter);if(Y.wrapS!==void 0)Z.setWrapS(Y.wrapS);if(Y.wrapT!==void 0)Z.setWrapT(Y.wrapT)}}var cn={logger:k5.DEFAULT_INSTANCE,extensions:[],dependencies:{}},ej1=new Set([a.BUFFER,a.TEXTURE,a.MATERIAL,a.MESH,a.PRIMITIVE,a.NODE,a.SCENE]);class Za{static read(Z,J=cn){let X=r6({},cn,J),{json:Y}=Z,$=new _6().setLogger(X.logger);this.validate(Z,X);let Q=new en(Z),K=Y.asset,G=$.getRoot().getAsset();if(K.copyright)G.copyright=K.copyright;if(K.extras)G.extras=K.extras;if(Y.extras!==void 0)$.getRoot().setExtras(r6({},Y.extras));let W=Y.extensionsUsed||[],H=Y.extensionsRequired||[];X.extensions.sort((N,C)=>N.EXTENSION_NAME>C.EXTENSION_NAME?1:-1);for(let N of X.extensions)if(W.includes(N.EXTENSION_NAME)){let C=$.createExtension(N).setRequired(H.includes(N.EXTENSION_NAME)),T=C.prereadTypes.filter((E)=>!ej1.has(E));if(T.length)X.logger.warn(`Preread hooks for some types (${T.join()}), requested by extension ${C.extensionName}, are unsupported. Please file an issue or a PR.`);for(let E of C.readDependencies)C.install(E,X.dependencies[E])}let V=Y.buffers||[];$.getRoot().listExtensionsUsed().filter((N)=>N.prereadTypes.includes(a.BUFFER)).forEach((N)=>N.preread(Q,a.BUFFER)),Q.buffers=V.map((N)=>{let C=$.createBuffer(N.name);if(N.extras)C.setExtras(N.extras);if(N.uri&&N.uri.indexOf("__")!==0)C.setURI(N.uri);return C});let F=Y.bufferViews||[];Q.bufferViewBuffers=F.map((N,C)=>{if(!Q.bufferViews[C]){let T=Z.json.buffers[N.buffer],E=T.uri?Z.resources[T.uri]:Z.resources[nB],x=N.byteOffset||0;Q.bufferViews[C]=o0.toView(E,x,N.byteLength)}return Q.buffers[N.buffer]});let z=Y.accessors||[];Q.accessors=z.map((N)=>{let C=Q.bufferViewBuffers[N.bufferView],T=$.createAccessor(N.name,C).setType(N.type);if(N.extras)T.setExtras(N.extras);if(N.normalized!==void 0)T.setNormalized(N.normalized);if(N.bufferView===void 0)return T;return T.setArray(iB(N,Q)),T});let q=Y.images||[],U=Y.textures||[];$.getRoot().listExtensionsUsed().filter((N)=>N.prereadTypes.includes(a.TEXTURE)).forEach((N)=>N.preread(Q,a.TEXTURE)),Q.textures=q.map((N)=>{let C=$.createTexture(N.name);if(N.extras)C.setExtras(N.extras);if(N.bufferView!==void 0){let T=Y.bufferViews[N.bufferView],E=Z.json.buffers[T.buffer],x=E.uri?Z.resources[E.uri]:Z.resources[nB],S=T.byteOffset||0,h=T.byteLength,I=x.slice(S,S+h);C.setImage(I)}else if(N.uri!==void 0){if(C.setImage(Z.resources[N.uri]),N.uri.indexOf("__")!==0)C.setURI(N.uri)}if(N.mimeType!==void 0)C.setMimeType(N.mimeType);else if(N.uri){let T=IZ.extension(N.uri);C.setMimeType(kZ.extensionToMimeType(T))}return C}),$.getRoot().listExtensionsUsed().filter((N)=>N.prereadTypes.includes(a.MATERIAL)).forEach((N)=>N.preread(Q,a.MATERIAL));let B=Y.materials||[];Q.materials=B.map((N)=>{let C=$.createMaterial(N.name);if(N.extras)C.setExtras(N.extras);if(N.alphaMode!==void 0)C.setAlphaMode(N.alphaMode);if(N.alphaCutoff!==void 0)C.setAlphaCutoff(N.alphaCutoff);if(N.doubleSided!==void 0)C.setDoubleSided(N.doubleSided);let T=N.pbrMetallicRoughness||{};if(T.baseColorFactor!==void 0)C.setBaseColorFactor(T.baseColorFactor);if(N.emissiveFactor!==void 0)C.setEmissiveFactor(N.emissiveFactor);if(T.metallicFactor!==void 0)C.setMetallicFactor(T.metallicFactor);if(T.roughnessFactor!==void 0)C.setRoughnessFactor(T.roughnessFactor);if(T.baseColorTexture!==void 0){let E=T.baseColorTexture,x=Q.textures[U[E.index].source];C.setBaseColorTexture(x),Q.setTextureInfo(C.getBaseColorTextureInfo(),E)}if(N.emissiveTexture!==void 0){let E=N.emissiveTexture,x=Q.textures[U[E.index].source];C.setEmissiveTexture(x),Q.setTextureInfo(C.getEmissiveTextureInfo(),E)}if(N.normalTexture!==void 0){let E=N.normalTexture,x=Q.textures[U[E.index].source];if(C.setNormalTexture(x),Q.setTextureInfo(C.getNormalTextureInfo(),E),N.normalTexture.scale!==void 0)C.setNormalScale(N.normalTexture.scale)}if(N.occlusionTexture!==void 0){let E=N.occlusionTexture,x=Q.textures[U[E.index].source];if(C.setOcclusionTexture(x),Q.setTextureInfo(C.getOcclusionTextureInfo(),E),N.occlusionTexture.strength!==void 0)C.setOcclusionStrength(N.occlusionTexture.strength)}if(T.metallicRoughnessTexture!==void 0){let E=T.metallicRoughnessTexture,x=Q.textures[U[E.index].source];C.setMetallicRoughnessTexture(x),Q.setTextureInfo(C.getMetallicRoughnessTextureInfo(),E)}return C}),$.getRoot().listExtensionsUsed().filter((N)=>N.prereadTypes.includes(a.MESH)).forEach((N)=>N.preread(Q,a.MESH));let L=Y.meshes||[];$.getRoot().listExtensionsUsed().filter((N)=>N.prereadTypes.includes(a.PRIMITIVE)).forEach((N)=>N.preread(Q,a.PRIMITIVE)),Q.meshes=L.map((N)=>{let C=$.createMesh(N.name);if(N.extras)C.setExtras(N.extras);if(N.weights!==void 0)C.setWeights(N.weights);return(N.primitives||[]).forEach((E)=>{let x=$.createPrimitive();if(E.extras)x.setExtras(E.extras);if(E.material!==void 0)x.setMaterial(Q.materials[E.material]);if(E.mode!==void 0)x.setMode(E.mode);for(let[I,_]of Object.entries(E.attributes||{}))x.setAttribute(I,Q.accessors[_]);if(E.indices!==void 0)x.setIndices(Q.accessors[E.indices]);let S=N.extras&&N.extras.targetNames||[];(E.targets||[]).forEach((I,_)=>{let A=S[_]||_.toString(),p=$.createPrimitiveTarget(A);for(let[n,o]of Object.entries(I))p.setAttribute(n,Q.accessors[o]);x.addTarget(p)}),C.addPrimitive(x)}),C});let w=Y.cameras||[];Q.cameras=w.map((N)=>{let C=$.createCamera(N.name).setType(N.type);if(N.extras)C.setExtras(N.extras);if(N.type===oY.Type.PERSPECTIVE){let T=N.perspective;if(C.setYFov(T.yfov),C.setZNear(T.znear),T.zfar!==void 0)C.setZFar(T.zfar);if(T.aspectRatio!==void 0)C.setAspectRatio(T.aspectRatio)}else{let T=N.orthographic;C.setZNear(T.znear).setZFar(T.zfar).setXMag(T.xmag).setYMag(T.ymag)}return C});let O=Y.nodes||[];$.getRoot().listExtensionsUsed().filter((N)=>N.prereadTypes.includes(a.NODE)).forEach((N)=>N.preread(Q,a.NODE)),Q.nodes=O.map((N)=>{let C=$.createNode(N.name);if(N.extras)C.setExtras(N.extras);if(N.translation!==void 0)C.setTranslation(N.translation);if(N.rotation!==void 0)C.setRotation(N.rotation);if(N.scale!==void 0)C.setScale(N.scale);if(N.matrix!==void 0){let T=[0,0,0],E=[0,0,0,1],x=[1,1,1];i0.decompose(N.matrix,T,E,x),C.setTranslation(T),C.setRotation(E),C.setScale(x)}if(N.weights!==void 0)C.setWeights(N.weights);return C});let M=Y.skins||[];Q.skins=M.map((N)=>{let C=$.createSkin(N.name);if(N.extras)C.setExtras(N.extras);if(N.inverseBindMatrices!==void 0)C.setInverseBindMatrices(Q.accessors[N.inverseBindMatrices]);if(N.skeleton!==void 0)C.setSkeleton(Q.nodes[N.skeleton]);for(let T of N.joints)C.addJoint(Q.nodes[T]);return C}),O.map((N,C)=>{let T=Q.nodes[C];if((N.children||[]).forEach((x)=>T.addChild(Q.nodes[x])),N.mesh!==void 0)T.setMesh(Q.meshes[N.mesh]);if(N.camera!==void 0)T.setCamera(Q.cameras[N.camera]);if(N.skin!==void 0)T.setSkin(Q.skins[N.skin])});let R=Y.animations||[];Q.animations=R.map((N)=>{let C=$.createAnimation(N.name);if(N.extras)C.setExtras(N.extras);let E=(N.samplers||[]).map((S)=>{let h=$.createAnimationSampler().setInput(Q.accessors[S.input]).setOutput(Q.accessors[S.output]).setInterpolation(S.interpolation||nK.Interpolation.LINEAR);if(S.extras)h.setExtras(S.extras);return C.addSampler(h),h});return(N.channels||[]).forEach((S)=>{let h=$.createAnimationChannel().setSampler(E[S.sampler]).setTargetPath(S.target.path);if(S.target.node!==void 0)h.setTargetNode(Q.nodes[S.target.node]);if(S.extras)h.setExtras(S.extras);C.addChannel(h)}),C});let D=Y.scenes||[];if($.getRoot().listExtensionsUsed().filter((N)=>N.prereadTypes.includes(a.SCENE)).forEach((N)=>N.preread(Q,a.SCENE)),Q.scenes=D.map((N)=>{let C=$.createScene(N.name);if(N.extras)C.setExtras(N.extras);return(N.nodes||[]).map((E)=>Q.nodes[E]).forEach((E)=>C.addChild(E)),C}),Y.scene!==void 0)$.getRoot().setDefaultScene(Q.scenes[Y.scene]);return $.getRoot().listExtensionsUsed().forEach((N)=>N.read(Q)),z.forEach((N,C)=>{let T=Q.accessors[C],E=!!N.sparse,x=!N.bufferView&&!T.getArray();if(E||x)T.setSparse(!0).setArray(JO1(N,Q))}),$}static validate(Z,J){let X=Z.json;if(X.asset.version!=="2.0")throw new Error(`Unsupported glTF version, "${X.asset.version}".`);if(X.extensionsRequired){for(let Y of X.extensionsRequired)if(!J.extensions.find(($)=>$.EXTENSION_NAME===Y))throw new Error(`Missing required extension, "${Y}".`)}if(X.extensionsUsed){for(let Y of X.extensionsUsed)if(!J.extensions.find(($)=>$.EXTENSION_NAME===Y))J.logger.warn(`Missing optional extension, "${Y}".`)}}}function ZO1(Z,J){let X=J.jsonDoc,Y=J.bufferViews[Z.bufferView],$=X.json.bufferViews[Z.bufferView],Q=iJ[Z.componentType],K=x0.getElementSize(Z.type),G=Q.BYTES_PER_ELEMENT,W=Z.byteOffset||0,H=new Q(Z.count*K),V=new DataView(Y.buffer,Y.byteOffset,Y.byteLength),F=$.byteStride;for(let z=0;z<Z.count;z++)for(let q=0;q<K;q++){let U=W+z*F+q*G,B;switch(Z.componentType){case x0.ComponentType.FLOAT:B=V.getFloat32(U,!0);break;case x0.ComponentType.UNSIGNED_INT:B=V.getUint32(U,!0);break;case x0.ComponentType.UNSIGNED_SHORT:B=V.getUint16(U,!0);break;case x0.ComponentType.UNSIGNED_BYTE:B=V.getUint8(U);break;case x0.ComponentType.SHORT:B=V.getInt16(U,!0);break;case x0.ComponentType.BYTE:B=V.getInt8(U);break;default:throw new Error(`Unexpected componentType "${Z.componentType}".`)}H[z*K+q]=B}return H}function iB(Z,J){let X=J.jsonDoc,Y=J.bufferViews[Z.bufferView],$=X.json.bufferViews[Z.bufferView],Q=iJ[Z.componentType],K=x0.getElementSize(Z.type),G=Q.BYTES_PER_ELEMENT,W=K*G;if($.byteStride!==void 0&&$.byteStride!==W)return ZO1(Z,J);let H=Y.byteOffset+(Z.byteOffset||0),V=Z.count*K*G;return new Q(Y.buffer.slice(H,H+V))}function JO1(Z,J){let X=iJ[Z.componentType],Y=x0.getElementSize(Z.type),$;if(Z.bufferView!==void 0)$=iB(Z,J);else $=new X(Z.count*Y);let Q=Z.sparse;if(!Q)return $;let K=Q.count,G=r6({},Z,Q.indices,{count:K,type:"SCALAR"}),W=r6({},Z,Q.values,{count:K}),H=iB(G,J),V=iB(W,J);for(let F=0;F<G.count;F++)for(let z=0;z<Y;z++)$[H[F]*Y+z]=V[F*Y+z];return $}var mH;(function(Z){Z[Z.ARRAY_BUFFER=34962]="ARRAY_BUFFER",Z[Z.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER"})(mH||(mH={}));class lJ{constructor(Z,J,X){this._doc=void 0,this.jsonDoc=void 0,this.options=void 0,this.accessorIndexMap=new Map,this.animationIndexMap=new Map,this.bufferIndexMap=new Map,this.cameraIndexMap=new Map,this.skinIndexMap=new Map,this.materialIndexMap=new Map,this.meshIndexMap=new Map,this.nodeIndexMap=new Map,this.imageIndexMap=new Map,this.textureDefIndexMap=new Map,this.textureInfoDefMap=new Map,this.samplerDefIndexMap=new Map,this.sceneIndexMap=new Map,this.imageBufferViews=[],this.otherBufferViews=new Map,this.otherBufferViewsIndexMap=new Map,this.extensionData={},this.bufferURIGenerator=void 0,this.imageURIGenerator=void 0,this.logger=void 0,this._accessorUsageMap=new Map,this.accessorUsageGroupedByParent=new Set(["ARRAY_BUFFER"]),this.accessorParents=new Map,this._doc=Z,this.jsonDoc=J,this.options=X;let Y=Z.getRoot(),$=Y.listBuffers().length,Q=Y.listTextures().length;this.bufferURIGenerator=new JT($>1,()=>X.basename||"buffer"),this.imageURIGenerator=new JT(Q>1,(K)=>XO1(Z,K)||X.basename||"texture"),this.logger=Z.getLogger()}createTextureInfoDef(Z,J){let X={magFilter:J.getMagFilter()||void 0,minFilter:J.getMinFilter()||void 0,wrapS:J.getWrapS(),wrapT:J.getWrapT()},Y=JSON.stringify(X);if(!this.samplerDefIndexMap.has(Y))this.samplerDefIndexMap.set(Y,this.jsonDoc.json.samplers.length),this.jsonDoc.json.samplers.push(X);let $={source:this.imageIndexMap.get(Z),sampler:this.samplerDefIndexMap.get(Y)},Q=JSON.stringify($);if(!this.textureDefIndexMap.has(Q))this.textureDefIndexMap.set(Q,this.jsonDoc.json.textures.length),this.jsonDoc.json.textures.push($);let K={index:this.textureDefIndexMap.get(Q)};if(J.getTexCoord()!==0)K.texCoord=J.getTexCoord();if(Object.keys(J.getExtras()).length>0)K.extras=J.getExtras();return this.textureInfoDefMap.set(J,K),K}createPropertyDef(Z){let J={};if(Z.getName())J.name=Z.getName();if(Object.keys(Z.getExtras()).length>0)J.extras=Z.getExtras();return J}createAccessorDef(Z){let J=this.createPropertyDef(Z);if(J.type=Z.getType(),J.componentType=Z.getComponentType(),J.count=Z.getCount(),this._doc.getGraph().listParentEdges(Z).some((Y)=>Y.getName()==="attributes"&&Y.getAttributes().key==="POSITION"||Y.getName()==="input"))J.max=Z.getMax([]).map(Math.fround),J.min=Z.getMin([]).map(Math.fround);if(Z.getNormalized())J.normalized=Z.getNormalized();return J}createImageData(Z,J,X){if(this.options.format===EZ.GLB)this.imageBufferViews.push(J),Z.bufferView=this.jsonDoc.json.bufferViews.length,this.jsonDoc.json.bufferViews.push({buffer:0,byteOffset:-1,byteLength:J.byteLength});else{let Y=kZ.mimeTypeToExtension(X.getMimeType());Z.uri=this.imageURIGenerator.createURI(X,Y),this.assignResourceURI(Z.uri,J,!1)}}assignResourceURI(Z,J,X){let Y=this.jsonDoc.resources;if(!(Z in Y)){Y[Z]=J;return}if(J===Y[Z]){this.logger.warn(`Duplicate resource URI, "${Z}".`);return}let $=`Resource URI "${Z}" already assigned to different data.`;if(!X){this.logger.warn($);return}throw new Error($)}getAccessorUsage(Z){let J=this._accessorUsageMap.get(Z);if(J)return J;if(Z.getSparse())return e5.SPARSE;for(let X of this._doc.getGraph().listParentEdges(Z)){let{usage:Y}=X.getAttributes();if(Y)return Y;if(X.getParent().propertyType!==a.ROOT)this.logger.warn(`Missing attribute ".usage" on edge, "${X.getName()}".`)}return e5.OTHER}addAccessorToUsageGroup(Z,J){let X=this._accessorUsageMap.get(Z);if(X&&X!==J)throw new Error(`Accessor with usage "${X}" cannot be reused as "${J}".`);return this._accessorUsageMap.set(Z,J),this}}lJ.BufferViewTarget=mH;lJ.BufferViewUsage=e5;lJ.USAGE_TO_TARGET={[e5.ARRAY_BUFFER]:mH.ARRAY_BUFFER,[e5.ELEMENT_ARRAY_BUFFER]:mH.ELEMENT_ARRAY_BUFFER};class JT{constructor(Z,J){this.multiple=void 0,this.basename=void 0,this.counter={},this.multiple=Z,this.basename=J}createURI(Z,J){if(Z.getURI())return Z.getURI();else if(!this.multiple)return`${this.basename(Z)}.${J}`;else{let X=this.basename(Z);return this.counter[X]=this.counter[X]||1,`${X}_${this.counter[X]++}.${J}`}}}function XO1(Z,J){let X=Z.getGraph().listParentEdges(J).find((Y)=>Y.getParent()!==Z.getRoot());return X?X.getName().replace(/texture$/i,""):""}var{BufferViewUsage:pB}=lJ,{UNSIGNED_INT:YO1,UNSIGNED_SHORT:$O1,UNSIGNED_BYTE:QO1}=x0.ComponentType,KO1=new Set([a.ACCESSOR,a.BUFFER,a.MATERIAL,a.MESH]);class Ja{static write(Z,J){let X=Z.getGraph(),Y=Z.getRoot(),$={asset:r6({generator:`glTF-Transform ${pn}`},Y.getAsset()),extras:r6({},Y.getExtras())},Q={json:$,resources:{}},K=new lJ(Z,Q,J),G=J.logger||k5.DEFAULT_INSTANCE,W=new Set(J.extensions.map((L)=>L.EXTENSION_NAME)),H=Z.getRoot().listExtensionsUsed().filter((L)=>W.has(L.extensionName)).sort((L,w)=>L.extensionName>w.extensionName?1:-1),V=Z.getRoot().listExtensionsRequired().filter((L)=>W.has(L.extensionName)).sort((L,w)=>L.extensionName>w.extensionName?1:-1);if(H.length<Z.getRoot().listExtensionsUsed().length)G.warn("Some extensions were not registered for I/O, and will not be written.");for(let L of H){let w=L.prewriteTypes.filter((O)=>!KO1.has(O));if(w.length)G.warn(`Prewrite hooks for some types (${w.join()}), requested by extension ${L.extensionName}, are unsupported. Please file an issue or a PR.`);for(let O of L.writeDependencies)L.install(O,J.dependencies[O])}function F(L,w,O,M){let R=[],D=0;for(let T of L){let E=K.createAccessorDef(T);E.bufferView=$.bufferViews.length;let x=T.getArray(),S=o0.pad(o0.toView(x));E.byteOffset=D,D+=S.byteLength,R.push(S),K.accessorIndexMap.set(T,$.accessors.length),$.accessors.push(E)}let N=o0.concat(R),C={buffer:w,byteOffset:O,byteLength:N.byteLength};if(M)C.target=M;return $.bufferViews.push(C),{buffers:R,byteLength:D}}function z(L,w,O){let M=L[0].getCount(),R=0;for(let E of L){let x=K.createAccessorDef(E);x.bufferView=$.bufferViews.length,x.byteOffset=R;let S=E.getElementSize(),h=E.getComponentSize();R+=o0.padNumber(S*h),K.accessorIndexMap.set(E,$.accessors.length),$.accessors.push(x)}let D=M*R,N=new ArrayBuffer(D),C=new DataView(N);for(let E=0;E<M;E++){let x=0;for(let S of L){let h=S.getElementSize(),I=S.getComponentSize(),_=S.getComponentType(),A=S.getArray();for(let p=0;p<h;p++){let n=E*R+x+p*I,o=A[E*h+p];switch(_){case x0.ComponentType.FLOAT:C.setFloat32(n,o,!0);break;case x0.ComponentType.BYTE:C.setInt8(n,o);break;case x0.ComponentType.SHORT:C.setInt16(n,o,!0);break;case x0.ComponentType.UNSIGNED_BYTE:C.setUint8(n,o);break;case x0.ComponentType.UNSIGNED_SHORT:C.setUint16(n,o,!0);break;case x0.ComponentType.UNSIGNED_INT:C.setUint32(n,o,!0);break;default:throw new Error("Unexpected component type: "+_)}}x+=o0.padNumber(h*I)}}let T={buffer:w,byteOffset:O,byteLength:D,byteStride:R,target:lJ.BufferViewTarget.ARRAY_BUFFER};return $.bufferViews.push(T),{byteLength:D,buffers:[new Uint8Array(N)]}}function q(L,w,O){let M=[],R=0,D=new Map,N=-1/0,C=!1;for(let _ of L){let A=K.createAccessorDef(_);$.accessors.push(A),K.accessorIndexMap.set(_,$.accessors.length-1);let p=[],n=[],o=[],Q0=new Array(_.getElementSize()).fill(0);for(let r0=0,A8=_.getCount();r0<A8;r0++){if(_.getElement(r0,o),i0.eq(o,Q0,0))continue;N=Math.max(r0,N),p.push(r0);for(let t1=0;t1<o.length;t1++)n.push(o[t1])}let G0=p.length,S0={accessorDef:A,count:G0};if(D.set(_,S0),G0===0)continue;if(G0>_.getCount()/2)C=!0;let v0=iJ[_.getComponentType()];S0.indices=p,S0.values=new v0(n)}if(!Number.isFinite(N))return{buffers:M,byteLength:R};if(C)G.warn("Some sparse accessors have >50% non-zero elements, which may increase file size.");let T=N<255?Uint8Array:N<65535?Uint16Array:Uint32Array,E=N<255?QO1:N<65535?$O1:YO1,x={buffer:w,byteOffset:O+R,byteLength:0};for(let _ of L){let A=D.get(_);if(A.count===0)continue;A.indicesByteOffset=x.byteLength;let p=o0.pad(o0.toView(new T(A.indices)));M.push(p),R+=p.byteLength,x.byteLength+=p.byteLength}$.bufferViews.push(x);let S=$.bufferViews.length-1,h={buffer:w,byteOffset:O+R,byteLength:0};for(let _ of L){let A=D.get(_);if(A.count===0)continue;A.valuesByteOffset=h.byteLength;let p=o0.pad(o0.toView(A.values));M.push(p),R+=p.byteLength,h.byteLength+=p.byteLength}$.bufferViews.push(h);let I=$.bufferViews.length-1;for(let _ of L){let A=D.get(_);if(A.count===0)continue;A.accessorDef.sparse={count:A.count,indices:{bufferView:S,byteOffset:A.indicesByteOffset,componentType:E},values:{bufferView:I,byteOffset:A.valuesByteOffset}}}return{buffers:M,byteLength:R}}if($.accessors=[],$.bufferViews=[],$.samplers=[],$.textures=[],$.images=Y.listTextures().map((L,w)=>{let O=K.createPropertyDef(L);if(L.getMimeType())O.mimeType=L.getMimeType();let M=L.getImage();if(M)K.createImageData(O,M,L);return K.imageIndexMap.set(L,w),O}),H.filter((L)=>L.prewriteTypes.includes(a.ACCESSOR)).forEach((L)=>L.prewrite(K,a.ACCESSOR)),Y.listAccessors().forEach((L)=>{let{accessorUsageGroupedByParent:w,accessorParents:O}=K;if(K.accessorIndexMap.has(L))return;let M=K.getAccessorUsage(L);if(K.addAccessorToUsageGroup(L,M),w.has(M)){let R=X.listParents(L).find((D)=>D.propertyType!==a.ROOT);O.set(L,R)}}),H.filter((L)=>L.prewriteTypes.includes(a.BUFFER)).forEach((L)=>L.prewrite(K,a.BUFFER)),(Y.listAccessors().length>0||K.otherBufferViews.size>0||Y.listTextures().length>0&&J.format===EZ.GLB)&&Y.listBuffers().length===0)throw new Error("Buffer required for Document resources, but none was found.");if($.buffers=[],Y.listBuffers().forEach((L,w)=>{let O=K.createPropertyDef(L),M=K.accessorUsageGroupedByParent,R=L.listParents().filter((h)=>h instanceof x0),D=new Set(R.map((h)=>K.accessorParents.get(h))),N=new Map(Array.from(D).map((h,I)=>[h,I])),C={};for(let h of R){var T;if(K.accessorIndexMap.has(h))continue;let I=K.getAccessorUsage(h),_=I;if(M.has(I)){let A=K.accessorParents.get(h);_+=`:${N.get(A)}`}C[T=_]||(C[T]={usage:I,accessors:[]}),C[_].accessors.push(h)}let E=[],x=$.buffers.length,S=0;for(let{usage:h,accessors:I}of Object.values(C))if(h===pB.ARRAY_BUFFER&&J.vertexLayout===aB.INTERLEAVED){let _=z(I,x,S);S+=_.byteLength;for(let A of _.buffers)E.push(A)}else if(h===pB.ARRAY_BUFFER)for(let _ of I){let A=z([_],x,S);S+=A.byteLength;for(let p of A.buffers)E.push(p)}else if(h===pB.SPARSE){let _=q(I,x,S);S+=_.byteLength;for(let A of _.buffers)E.push(A)}else if(h===pB.ELEMENT_ARRAY_BUFFER){let _=lJ.BufferViewTarget.ELEMENT_ARRAY_BUFFER,A=F(I,x,S,_);S+=A.byteLength;for(let p of A.buffers)E.push(p)}else{let _=F(I,x,S);S+=_.byteLength;for(let A of _.buffers)E.push(A)}if(K.imageBufferViews.length&&w===0){for(let h=0;h<K.imageBufferViews.length;h++)if($.bufferViews[$.images[h].bufferView].byteOffset=S,S+=K.imageBufferViews[h].byteLength,E.push(K.imageBufferViews[h]),S%8){let I=8-S%8;S+=I,E.push(new Uint8Array(I))}}if(K.otherBufferViews.has(L))for(let h of K.otherBufferViews.get(L))$.bufferViews.push({buffer:x,byteOffset:S,byteLength:h.byteLength}),K.otherBufferViewsIndexMap.set(h,$.bufferViews.length-1),S+=h.byteLength,E.push(h);if(S){let h;if(J.format===EZ.GLB)h=nB;else h=K.bufferURIGenerator.createURI(L,"bin"),O.uri=h;O.byteLength=S,K.assignResourceURI(h,o0.concat(E),!0)}$.buffers.push(O),K.bufferIndexMap.set(L,w)}),Y.listAccessors().find((L)=>!L.getBuffer()))G.warn("Skipped writing one or more Accessors: no Buffer assigned.");H.filter((L)=>L.prewriteTypes.includes(a.MATERIAL)).forEach((L)=>L.prewrite(K,a.MATERIAL)),$.materials=Y.listMaterials().map((L,w)=>{let O=K.createPropertyDef(L);if(L.getAlphaMode()!==D7.AlphaMode.OPAQUE)O.alphaMode=L.getAlphaMode();if(L.getAlphaMode()===D7.AlphaMode.MASK)O.alphaCutoff=L.getAlphaCutoff();if(L.getDoubleSided())O.doubleSided=!0;if(O.pbrMetallicRoughness={},!i0.eq(L.getBaseColorFactor(),[1,1,1,1]))O.pbrMetallicRoughness.baseColorFactor=L.getBaseColorFactor();if(!i0.eq(L.getEmissiveFactor(),[0,0,0]))O.emissiveFactor=L.getEmissiveFactor();if(L.getRoughnessFactor()!==1)O.pbrMetallicRoughness.roughnessFactor=L.getRoughnessFactor();if(L.getMetallicFactor()!==1)O.pbrMetallicRoughness.metallicFactor=L.getMetallicFactor();if(L.getBaseColorTexture()){let M=L.getBaseColorTexture(),R=L.getBaseColorTextureInfo();O.pbrMetallicRoughness.baseColorTexture=K.createTextureInfoDef(M,R)}if(L.getEmissiveTexture()){let M=L.getEmissiveTexture(),R=L.getEmissiveTextureInfo();O.emissiveTexture=K.createTextureInfoDef(M,R)}if(L.getNormalTexture()){let M=L.getNormalTexture(),R=L.getNormalTextureInfo(),D=K.createTextureInfoDef(M,R);if(L.getNormalScale()!==1)D.scale=L.getNormalScale();O.normalTexture=D}if(L.getOcclusionTexture()){let M=L.getOcclusionTexture(),R=L.getOcclusionTextureInfo(),D=K.createTextureInfoDef(M,R);if(L.getOcclusionStrength()!==1)D.strength=L.getOcclusionStrength();O.occlusionTexture=D}if(L.getMetallicRoughnessTexture()){let M=L.getMetallicRoughnessTexture(),R=L.getMetallicRoughnessTextureInfo();O.pbrMetallicRoughness.metallicRoughnessTexture=K.createTextureInfoDef(M,R)}return K.materialIndexMap.set(L,w),O}),H.filter((L)=>L.prewriteTypes.includes(a.MESH)).forEach((L)=>L.prewrite(K,a.MESH)),$.meshes=Y.listMeshes().map((L,w)=>{let O=K.createPropertyDef(L),M=null;if(O.primitives=L.listPrimitives().map((R)=>{let D={attributes:{}};D.mode=R.getMode();let N=R.getMaterial();if(N)D.material=K.materialIndexMap.get(N);if(Object.keys(R.getExtras()).length)D.extras=R.getExtras();let C=R.getIndices();if(C)D.indices=K.accessorIndexMap.get(C);for(let T of R.listSemantics())D.attributes[T]=K.accessorIndexMap.get(R.getAttribute(T));for(let T of R.listTargets()){let E={};for(let x of T.listSemantics())E[x]=K.accessorIndexMap.get(T.getAttribute(x));D.targets=D.targets||[],D.targets.push(E)}if(R.listTargets().length&&!M)M=R.listTargets().map((T)=>T.getName());return D}),L.getWeights().length)O.weights=L.getWeights();if(M)O.extras=O.extras||{},O.extras.targetNames=M;return K.meshIndexMap.set(L,w),O}),$.cameras=Y.listCameras().map((L,w)=>{let O=K.createPropertyDef(L);if(O.type=L.getType(),O.type===oY.Type.PERSPECTIVE){O.perspective={znear:L.getZNear(),zfar:L.getZFar(),yfov:L.getYFov()};let M=L.getAspectRatio();if(M!==null)O.perspective.aspectRatio=M}else O.orthographic={znear:L.getZNear(),zfar:L.getZFar(),xmag:L.getXMag(),ymag:L.getYMag()};return K.cameraIndexMap.set(L,w),O}),$.nodes=Y.listNodes().map((L,w)=>{let O=K.createPropertyDef(L);if(!i0.eq(L.getTranslation(),[0,0,0]))O.translation=L.getTranslation();if(!i0.eq(L.getRotation(),[0,0,0,1]))O.rotation=L.getRotation();if(!i0.eq(L.getScale(),[1,1,1]))O.scale=L.getScale();if(L.getWeights().length)O.weights=L.getWeights();return K.nodeIndexMap.set(L,w),O}),$.skins=Y.listSkins().map((L,w)=>{let O=K.createPropertyDef(L),M=L.getInverseBindMatrices();if(M)O.inverseBindMatrices=K.accessorIndexMap.get(M);let R=L.getSkeleton();if(R)O.skeleton=K.nodeIndexMap.get(R);return O.joints=L.listJoints().map((D)=>K.nodeIndexMap.get(D)),K.skinIndexMap.set(L,w),O}),Y.listNodes().forEach((L,w)=>{let O=$.nodes[w],M=L.getMesh();if(M)O.mesh=K.meshIndexMap.get(M);let R=L.getCamera();if(R)O.camera=K.cameraIndexMap.get(R);let D=L.getSkin();if(D)O.skin=K.skinIndexMap.get(D);if(L.listChildren().length>0)O.children=L.listChildren().map((N)=>K.nodeIndexMap.get(N))}),$.animations=Y.listAnimations().map((L,w)=>{let O=K.createPropertyDef(L),M=new Map;return O.samplers=L.listSamplers().map((R,D)=>{let N=K.createPropertyDef(R);return N.input=K.accessorIndexMap.get(R.getInput()),N.output=K.accessorIndexMap.get(R.getOutput()),N.interpolation=R.getInterpolation(),M.set(R,D),N}),O.channels=L.listChannels().map((R)=>{let D=K.createPropertyDef(R);return D.sampler=M.get(R.getSampler()),D.target={node:K.nodeIndexMap.get(R.getTargetNode()),path:R.getTargetPath()},D}),K.animationIndexMap.set(L,w),O}),$.scenes=Y.listScenes().map((L,w)=>{let O=K.createPropertyDef(L);return O.nodes=L.listChildren().map((M)=>K.nodeIndexMap.get(M)),K.sceneIndexMap.set(L,w),O});let B=Y.getDefaultScene();if(B)$.scene=Y.listScenes().indexOf(B);return $.extensionsUsed=H.map((L)=>L.extensionName),$.extensionsRequired=V.map((L)=>L.extensionName),H.forEach((L)=>L.write(K)),GO1($),Q}}function GO1(Z){let J=[];for(let X in Z){let Y=Z[X];if(Array.isArray(Y)&&Y.length===0)J.push(X);else if(Y===null||Y==="")J.push(X);else if(Y&&typeof Y==="object"&&Object.keys(Y).length===0)J.push(X)}for(let X of J)delete Z[X]}var rB;(function(Z){Z[Z.JSON=1313821514]="JSON",Z[Z.BIN=5130562]="BIN"})(rB||(rB={}));class Xa{constructor(){this._logger=k5.DEFAULT_INSTANCE,this._extensions=new Set,this._dependencies={},this._vertexLayout=aB.INTERLEAVED,this.lastReadBytes=0,this.lastWriteBytes=0}setLogger(Z){return this._logger=Z,this}registerExtensions(Z){for(let J of Z)this._extensions.add(J),J.register();return this}registerDependencies(Z){return Object.assign(this._dependencies,Z),this}setVertexLayout(Z){return this._vertexLayout=Z,this}async read(Z){return await this.readJSON(await this.readAsJSON(Z))}async readAsJSON(Z){let J=await this.readURI(Z,"view");this.lastReadBytes=J.byteLength;let X=ln(J)?this._binaryToJSON(J):{json:JSON.parse(o0.decodeText(J)),resources:{}};return await this._readResourcesExternal(X,this.dirname(Z)),this._readResourcesInternal(X),X}async readJSON(Z){return Z=this._copyJSON(Z),this._readResourcesInternal(Z),Za.read(Z,{extensions:Array.from(this._extensions),dependencies:this._dependencies,logger:this._logger})}async binaryToJSON(Z){let J=this._binaryToJSON(o0.assertView(Z));this._readResourcesInternal(J);let X=J.json;if(X.buffers&&X.buffers.some((Y)=>WO1(J,Y)))throw new Error("Cannot resolve external buffers with binaryToJSON().");else if(X.images&&X.images.some((Y)=>HO1(J,Y)))throw new Error("Cannot resolve external images with binaryToJSON().");return J}async readBinary(Z){return this.readJSON(await this.binaryToJSON(o0.assertView(Z)))}async writeJSON(Z,J={}){if(J.format===EZ.GLB&&Z.getRoot().listBuffers().length>1)throw new Error("GLB must have 0–1 buffers.");return Ja.write(Z,{format:J.format||EZ.GLTF,basename:J.basename||"",logger:this._logger,vertexLayout:this._vertexLayout,dependencies:r6({},this._dependencies),extensions:Array.from(this._extensions)})}async writeBinary(Z){let{json:J,resources:X}=await this.writeJSON(Z,{format:EZ.GLB}),Y=new Uint32Array([1179937895,2,12]),$=JSON.stringify(J),Q=o0.pad(o0.encodeText($),32),K=o0.toView(new Uint32Array([Q.byteLength,1313821514])),G=o0.concat([K,Q]);Y[Y.length-1]+=G.byteLength;let W=Object.values(X)[0];if(!W||!W.byteLength)return o0.concat([o0.toView(Y),G]);let H=o0.pad(W,0),V=o0.toView(new Uint32Array([H.byteLength,5130562])),F=o0.concat([V,H]);return Y[Y.length-1]+=F.byteLength,o0.concat([o0.toView(Y),G,F])}async _readResourcesExternal(Z,J){var X=this;let Y=Z.json.images||[],$=Z.json.buffers||[],Q=[...Y,...$].map(async function(K){let G=K.uri;if(!G||G.match(/data:/))return Promise.resolve();Z.resources[G]=await X.readURI(X.resolve(J,G),"view"),X.lastReadBytes+=Z.resources[G].byteLength});await Promise.all(Q)}_readResourcesInternal(Z){function J($){if(!$.uri)return;if($.uri in Z.resources){o0.assertView(Z.resources[$.uri]);return}if($.uri.match(/data:/)){let Q=`__${rn()}.${IZ.extension($.uri)}`;Z.resources[Q]=o0.createBufferFromDataURI($.uri),$.uri=Q}}(Z.json.images||[]).forEach(($)=>{if($.bufferView===void 0&&$.uri===void 0)throw new Error("Missing resource URI or buffer view.");J($)}),(Z.json.buffers||[]).forEach(J)}_copyJSON(Z){let{images:J,buffers:X}=Z.json;if(Z={json:r6({},Z.json),resources:r6({},Z.resources)},J)Z.json.images=J.map((Y)=>r6({},Y));if(X)Z.json.buffers=X.map((Y)=>r6({},Y));return Z}_binaryToJSON(Z){if(!ln(Z))throw new Error("Invalid glTF 2.0 binary.");let J=new Uint32Array(Z.buffer,Z.byteOffset+12,2);if(J[1]!==rB.JSON)throw new Error("Missing required GLB JSON chunk.");let X=20,Y=J[0],$=o0.decodeText(o0.toView(Z,X,Y)),Q=JSON.parse($),K=X+Y;if(Z.byteLength<=K)return{json:Q,resources:{}};let G=new Uint32Array(Z.buffer,Z.byteOffset+K,2);if(G[1]!==rB.BIN)return{json:Q,resources:{}};let W=G[0],H=o0.toView(Z,K+8,W);return{json:Q,resources:{[nB]:H}}}}function WO1(Z,J){return J.uri!==void 0&&!(J.uri in Z.resources)}function HO1(Z,J){return J.uri!==void 0&&!(J.uri in Z.resources)&&J.bufferView===void 0}function ln(Z){if(Z.byteLength<3*Uint32Array.BYTES_PER_ELEMENT)return!1;let J=new Uint32Array(Z.buffer,Z.byteOffset,3);return J[0]===1179937895&&J[1]===2}class WT extends Xa{constructor(Z=null,J=f9.DEFAULT_INIT){super();this._fetch=void 0,this._fetchConfig=void 0,this._init=void 0,this._fetchEnabled=!1,this._fetch=Z,this._fetchConfig=J,this._init=this.init()}async init(){if(this._init)return this._init;return Promise.all([import("fs"),import("path")]).then(([Z,J])=>{this._fs=Z.promises,this._path=J})}setAllowNetwork(Z){if(Z&&!this._fetch)throw new Error("NodeIO requires a Fetch API implementation for HTTP requests.");return this._fetchEnabled=Z,this}async readURI(Z,J){if(await this.init(),f9.isAbsoluteURL(Z)){if(!this._fetchEnabled||!this._fetch)throw new Error("Network request blocked. Allow HTTP requests explicitly, if needed.");let X=await this._fetch(Z,this._fetchConfig);switch(J){case"view":return new Uint8Array(await X.arrayBuffer());case"text":return X.text()}}else switch(J){case"view":return this._fs.readFile(Z);case"text":return this._fs.readFile(Z,"utf8")}}resolve(Z,J){if(f9.isAbsoluteURL(Z)||f9.isAbsoluteURL(J))return f9.resolve(Z,J);return this._path.resolve(Z,decodeURIComponent(J))}dirname(Z){if(f9.isAbsoluteURL(Z))return f9.dirname(Z);return this._path.dirname(Z)}async write(Z,J){await this.init(),await(!!Z.match(/\.glb$/)?this._writeGLB(Z,J):this._writeGLTF(Z,J))}async _writeGLTF(Z,J){var X=this;this.lastWriteBytes=0;let{json:Y,resources:$}=await this.writeJSON(J,{format:EZ.GLTF,basename:IZ.basename(Z)}),{_fs:Q,_path:K}=this,G=K.dirname(Z),W=JSON.stringify(Y,null,2);await Q.writeFile(Z,W),this.lastWriteBytes+=W.length;for(let H of VO1(Object.keys($),10))await Promise.all(H.map(async function(V){if(f9.isAbsoluteURL(V)){if(f9.extension(V)==="bin")throw new Error(`Cannot write buffer to path "${V}".`);return}let F=K.join(G,decodeURIComponent(V));await Q.mkdir(K.dirname(F),{recursive:!0}),await Q.writeFile(F,$[V]),X.lastWriteBytes+=$[V].byteLength}))}async _writeGLB(Z,J){let X=await this.writeBinary(J);await this._fs.writeFile(Z,X),this.lastWriteBytes=X.byteLength}}function VO1(Z,J){let X=[];for(let Y=0,$=Z.length;Y<$;Y+=J){let Q=[];for(let K=0;K<J&&Y+K<$;K++)Q.push(Z[Y+K]);X.push(Q)}return X}var eo=r(HT(),1),Zr=r(ho(),1),JD1=r(to(),1);async function XD1(Z,J){if(!(Z instanceof Uint8Array))throw new Error("[ndarray-pixels] Input must be Uint8Array or Buffer.");let{data:X,info:Y}=await Zr.default(Z).ensureAlpha().raw().toBuffer({resolveWithObject:!0});return eo.default(new Uint8Array(X),[Y.width,Y.height,4],[4,4*Y.width|0,1],0)}async function Jr(Z,J){return XD1(Z)}var YD1="v4.1.3",uT="@glb.bin",s;(function(Z){Z.ACCESSOR="Accessor",Z.ANIMATION="Animation",Z.ANIMATION_CHANNEL="AnimationChannel",Z.ANIMATION_SAMPLER="AnimationSampler",Z.BUFFER="Buffer",Z.CAMERA="Camera",Z.MATERIAL="Material",Z.MESH="Mesh",Z.PRIMITIVE="Primitive",Z.PRIMITIVE_TARGET="PrimitiveTarget",Z.NODE="Node",Z.ROOT="Root",Z.SCENE="Scene",Z.SKIN="Skin",Z.TEXTURE="Texture",Z.TEXTURE_INFO="TextureInfo"})(s||(s={}));var Xr;(function(Z){Z.INTERLEAVED="interleaved",Z.SEPARATE="separate"})(Xr||(Xr={}));var X9;(function(Z){Z.ARRAY_BUFFER="ARRAY_BUFFER",Z.ELEMENT_ARRAY_BUFFER="ELEMENT_ARRAY_BUFFER",Z.INVERSE_BIND_MATRICES="INVERSE_BIND_MATRICES",Z.OTHER="OTHER",Z.SPARSE="SPARSE"})(X9||(X9={}));var Y9;(function(Z){Z[Z.R=4096]="R",Z[Z.G=256]="G",Z[Z.B=16]="B",Z[Z.A=1]="A"})(Y9||(Y9={}));var hT;(function(Z){Z.GLTF="GLTF",Z.GLB="GLB"})(hT||(hT={}));var fT=typeof Float32Array!=="undefined"?Float32Array:Array;if(!Math.hypot)Math.hypot=function(){var Z=0,J=arguments.length;while(J--)Z+=arguments[J]*arguments[J];return Math.sqrt(Z)};function $D1(){var Z=new fT(3);if(fT!=Float32Array)Z[0]=0,Z[1]=0,Z[2]=0;return Z}function xT(Z){var J=Z[0],X=Z[1],Y=Z[2];return Math.hypot(J,X,Y)}function QD1(Z,J,X){var Y=J[0],$=J[1],Q=J[2],K=X[3]*Y+X[7]*$+X[11]*Q+X[15];return K=K||1,Z[0]=(X[0]*Y+X[4]*$+X[8]*Q+X[12])/K,Z[1]=(X[1]*Y+X[5]*$+X[9]*Q+X[13])/K,Z[2]=(X[2]*Y+X[6]*$+X[10]*Q+X[14])/K,Z}(function(){var Z=$D1();return function(J,X,Y,$,Q,K){var G,W;if(!X)X=3;if(!Y)Y=0;if($)W=Math.min($*X+Y,J.length);else W=J.length;for(G=Y;G<W;G+=X)Z[0]=J[G],Z[1]=J[G+1],Z[2]=J[G+2],Q(Z,Z,K),J[G]=Z[0],J[G+1]=Z[1],J[G+2]=Z[2];return J}})();function Kr(Z){let J=Gr(),X=Z.propertyType===s.NODE?[Z]:Z.listChildren();for(let Y of X)Y.traverse(($)=>{let Q=$.getMesh();if(!Q)return;let K=KD1(Q,$.getWorldMatrix());if(K.min.every(isFinite)&&K.max.every(isFinite))yT(K.min,J),yT(K.max,J)});return J}function KD1(Z,J){let X=Gr();for(let Y of Z.listPrimitives()){let $=Y.getAttribute("POSITION"),Q=Y.getIndices();if(!$)continue;let K=[0,0,0],G=[0,0,0];for(let W=0,H=Q?Q.getCount():$.getCount();W<H;W++){let V=Q?Q.getScalar(W):W;K=$.getElement(V,K),G=QD1(G,K,J),yT(G,X)}}return X}function yT(Z,J){for(let X=0;X<3;X++)J.min[X]=Math.min(Z[X],J.min[X]),J.max[X]=Math.max(Z[X],J.max[X])}function Gr(){return{min:[1/0,1/0,1/0],max:[-1/0,-1/0,-1/0]}}class v6{static createBufferFromDataURI(Z){if(typeof Buffer==="undefined"){let J=atob(Z.split(",")[1]),X=new Uint8Array(J.length);for(let Y=0;Y<J.length;Y++)X[Y]=J.charCodeAt(Y);return X}else{let J=Z.split(",")[1],X=Z.indexOf("base64")>=0;return Buffer.from(J,X?"base64":"utf8")}}static encodeText(Z){return new TextEncoder().encode(Z)}static decodeText(Z){return new TextDecoder().decode(Z)}static concat(Z){let J=0;for(let $ of Z)J+=$.byteLength;let X=new Uint8Array(J),Y=0;for(let $ of Z)X.set($,Y),Y+=$.byteLength;return X}static pad(Z,J=0){let X=this.padNumber(Z.byteLength);if(X===Z.byteLength)return Z;let Y=new Uint8Array(X);if(Y.set(Z),J!==0)for(let $=Z.byteLength;$<X;$++)Y[$]=J;return Y}static padNumber(Z){return Math.ceil(Z/4)*4}static equals(Z,J){if(Z===J)return!0;if(Z.byteLength!==J.byteLength)return!1;let X=Z.byteLength;while(X--)if(Z[X]!==J[X])return!1;return!0}static toView(Z,J=0,X=1/0){return new Uint8Array(Z.buffer,Z.byteOffset+J,Math.min(Z.byteLength,X))}static assertView(Z){if(Z&&!ArrayBuffer.isView(Z))throw new Error(`Method requires Uint8Array parameter; received "${typeof Z}".`);return Z}}class Wr{match(Z){return Z.length>=3&&Z[0]===255&&Z[1]===216&&Z[2]===255}getSize(Z){let J=new DataView(Z.buffer,Z.byteOffset+4),X,Y;while(J.byteLength){if(X=J.getUint16(0,!1),GD1(J,X),Y=J.getUint8(X+1),Y===192||Y===193||Y===194)return[J.getUint16(X+7,!1),J.getUint16(X+5,!1)];J=new DataView(Z.buffer,J.byteOffset+X+2)}throw new TypeError("Invalid JPG, no size found")}getChannels(Z){return 3}}class I2{match(Z){return Z.length>=8&&Z[0]===137&&Z[1]===80&&Z[2]===78&&Z[3]===71&&Z[4]===13&&Z[5]===10&&Z[6]===26&&Z[7]===10}getSize(Z){let J=new DataView(Z.buffer,Z.byteOffset);if(v6.decodeText(Z.slice(12,16))===I2.PNG_FRIED_CHUNK_NAME)return[J.getUint32(32,!1),J.getUint32(36,!1)];return[J.getUint32(16,!1),J.getUint32(20,!1)]}getChannels(Z){return 4}}I2.PNG_FRIED_CHUNK_NAME="CgBI";class h4{static registerFormat(Z,J){this.impls[Z]=J}static getMimeType(Z){for(let J in this.impls)if(this.impls[J].match(Z))return J;return null}static getSize(Z,J){if(!this.impls[J])return null;return this.impls[J].getSize(Z)}static getChannels(Z,J){if(!this.impls[J])return null;return this.impls[J].getChannels(Z)}static getVRAMByteLength(Z,J){if(!this.impls[J])return null;if(this.impls[J].getVRAMByteLength)return this.impls[J].getVRAMByteLength(Z);let X=0,Y=4,$=this.getSize(Z,J);if(!$)return null;while($[0]>1||$[1]>1)X+=$[0]*$[1]*Y,$[0]=Math.max(Math.floor($[0]/2),1),$[1]=Math.max(Math.floor($[1]/2),1);return X+=1*Y,X}static mimeTypeToExtension(Z){if(Z==="image/jpeg")return"jpg";return Z.split("/").pop()}static extensionToMimeType(Z){if(Z==="jpg")return"image/jpeg";if(!Z)return"";return`image/${Z}`}}h4.impls={"image/jpeg":new Wr,"image/png":new I2};function GD1(Z,J){if(J>Z.byteLength)throw new TypeError("Corrupt JPG, exceeded buffer limits");if(Z.getUint8(J)!==255)throw new TypeError("Invalid JPG, marker table corrupted");return Z}class rH{static basename(Z){let J=Z.split(/[\\/]/).pop();return J.substring(0,J.lastIndexOf("."))}static extension(Z){if(Z.startsWith("data:image/")){let J=Z.match(/data:(image\/\w+)/)[1];return h4.mimeTypeToExtension(J)}else if(Z.startsWith("data:model/gltf+json"))return"gltf";else if(Z.startsWith("data:model/gltf-binary"))return"glb";else if(Z.startsWith("data:application/"))return"bin";return Z.split(/[\\/]/).pop().split(/[.]/).pop()}}function Yr(Z){return Object.prototype.toString.call(Z)==="[object Object]"}function X$(Z){if(Yr(Z)===!1)return!1;let J=Z.constructor;if(J===void 0)return!0;let X=J.prototype;if(Yr(X)===!1)return!1;if(Object.prototype.hasOwnProperty.call(X,"isPrototypeOf")===!1)return!1;return!0}var bT,gT;(function(Z){Z[Z.SILENT=4]="SILENT",Z[Z.ERROR=3]="ERROR",Z[Z.WARN=2]="WARN",Z[Z.INFO=1]="INFO",Z[Z.DEBUG=0]="DEBUG"})(gT||(gT={}));class _7{constructor(Z){this.verbosity=void 0,this.verbosity=Z}debug(Z){if(this.verbosity<=_7.Verbosity.DEBUG)console.debug(Z)}info(Z){if(this.verbosity<=_7.Verbosity.INFO)console.info(Z)}warn(Z){if(this.verbosity<=_7.Verbosity.WARN)console.warn(Z)}error(Z){if(this.verbosity<=_7.Verbosity.ERROR)console.error(Z)}}bT=_7;_7.Verbosity=gT;_7.DEFAULT_INSTANCE=new bT(bT.Verbosity.INFO);function WD1(Z){var J=Z[0],X=Z[1],Y=Z[2],$=Z[3],Q=Z[4],K=Z[5],G=Z[6],W=Z[7],H=Z[8],V=Z[9],F=Z[10],z=Z[11],q=Z[12],U=Z[13],B=Z[14],L=Z[15],w=J*K-X*Q,O=J*G-Y*Q,M=J*W-$*Q,R=X*G-Y*K,D=X*W-$*K,N=Y*W-$*G,C=H*U-V*q,T=H*B-F*q,E=H*L-z*q,x=V*B-F*U,S=V*L-z*U,h=F*L-z*B;return w*h-O*S+M*x+R*E-D*T+N*C}function HD1(Z,J,X){var Y=J[0],$=J[1],Q=J[2],K=J[3],G=J[4],W=J[5],H=J[6],V=J[7],F=J[8],z=J[9],q=J[10],U=J[11],B=J[12],L=J[13],w=J[14],O=J[15],M=X[0],R=X[1],D=X[2],N=X[3];return Z[0]=M*Y+R*G+D*F+N*B,Z[1]=M*$+R*W+D*z+N*L,Z[2]=M*Q+R*H+D*q+N*w,Z[3]=M*K+R*V+D*U+N*O,M=X[4],R=X[5],D=X[6],N=X[7],Z[4]=M*Y+R*G+D*F+N*B,Z[5]=M*$+R*W+D*z+N*L,Z[6]=M*Q+R*H+D*q+N*w,Z[7]=M*K+R*V+D*U+N*O,M=X[8],R=X[9],D=X[10],N=X[11],Z[8]=M*Y+R*G+D*F+N*B,Z[9]=M*$+R*W+D*z+N*L,Z[10]=M*Q+R*H+D*q+N*w,Z[11]=M*K+R*V+D*U+N*O,M=X[12],R=X[13],D=X[14],N=X[15],Z[12]=M*Y+R*G+D*F+N*B,Z[13]=M*$+R*W+D*z+N*L,Z[14]=M*Q+R*H+D*q+N*w,Z[15]=M*K+R*V+D*U+N*O,Z}function VD1(Z,J){var X=J[0],Y=J[1],$=J[2],Q=J[4],K=J[5],G=J[6],W=J[8],H=J[9],V=J[10];return Z[0]=Math.hypot(X,Y,$),Z[1]=Math.hypot(Q,K,G),Z[2]=Math.hypot(W,H,V),Z}function zD1(Z,J){var X=new fT(3);VD1(X,J);var Y=1/X[0],$=1/X[1],Q=1/X[2],K=J[0]*Y,G=J[1]*$,W=J[2]*Q,H=J[4]*Y,V=J[5]*$,F=J[6]*Q,z=J[8]*Y,q=J[9]*$,U=J[10]*Q,B=K+V+U,L=0;if(B>0)L=Math.sqrt(B+1)*2,Z[3]=0.25*L,Z[0]=(F-q)/L,Z[1]=(z-W)/L,Z[2]=(G-H)/L;else if(K>V&&K>U)L=Math.sqrt(1+K-V-U)*2,Z[3]=(F-q)/L,Z[0]=0.25*L,Z[1]=(G+H)/L,Z[2]=(z+W)/L;else if(V>U)L=Math.sqrt(1+V-K-U)*2,Z[3]=(z-W)/L,Z[0]=(G+H)/L,Z[1]=0.25*L,Z[2]=(F+q)/L;else L=Math.sqrt(1+U-K-V)*2,Z[3]=(G-H)/L,Z[0]=(z+W)/L,Z[1]=(F+q)/L,Z[2]=0.25*L;return Z}class z8{static identity(Z){return Z}static eq(Z,J,X=0.00001){if(Z.length!==J.length)return!1;for(let Y=0;Y<Z.length;Y++)if(Math.abs(Z[Y]-J[Y])>X)return!1;return!0}static clamp(Z,J,X){if(Z<J)return J;if(Z>X)return X;return Z}static decodeNormalizedInt(Z,J){switch(J){case 5126:return Z;case 5123:return Z/65535;case 5121:return Z/255;case 5122:return Math.max(Z/32767,-1);case 5120:return Math.max(Z/127,-1);default:throw new Error("Invalid component type.")}}static encodeNormalizedInt(Z,J){switch(J){case 5126:return Z;case 5123:return Math.round(z8.clamp(Z,0,1)*65535);case 5121:return Math.round(z8.clamp(Z,0,1)*255);case 5122:return Math.round(z8.clamp(Z,-1,1)*32767);case 5120:return Math.round(z8.clamp(Z,-1,1)*127);default:throw new Error("Invalid component type.")}}static decompose(Z,J,X,Y){let $=xT([Z[0],Z[1],Z[2]]),Q=xT([Z[4],Z[5],Z[6]]),K=xT([Z[8],Z[9],Z[10]]);if(WD1(Z)<0)$=-$;J[0]=Z[12],J[1]=Z[13],J[2]=Z[14];let W=Z.slice(),H=1/$,V=1/Q,F=1/K;W[0]*=H,W[1]*=H,W[2]*=H,W[4]*=V,W[5]*=V,W[6]*=V,W[8]*=F,W[9]*=F,W[10]*=F,zD1(X,W),Y[0]=$,Y[1]=Q,Y[2]=K}static compose(Z,J,X,Y){let $=Y,Q=J[0],K=J[1],G=J[2],W=J[3],H=Q+Q,V=K+K,F=G+G,z=Q*H,q=Q*V,U=Q*F,B=K*V,L=K*F,w=G*F,O=W*H,M=W*V,R=W*F,D=X[0],N=X[1],C=X[2];return $[0]=(1-(B+w))*D,$[1]=(q+R)*D,$[2]=(U-M)*D,$[3]=0,$[4]=(q-R)*N,$[5]=(1-(z+w))*N,$[6]=(L+O)*N,$[7]=0,$[8]=(U+M)*C,$[9]=(L-O)*C,$[10]=(1-(z+B))*C,$[11]=0,$[12]=Z[0],$[13]=Z[1],$[14]=Z[2],$[15]=1,$}}function FD1(Z,J){if(!!Z!==!!J)return!1;let X=Z.getChild(),Y=J.getChild();return X===Y||X.equals(Y)}function qD1(Z,J){if(!!Z!==!!J)return!1;let X=Z.values(),Y=J.values();if(X.length!==Y.length)return!1;for(let $=0;$<X.length;$++){let Q=X[$],K=Y[$];if(Q.getChild()===K.getChild())continue;if(!Q.getChild().equals(K.getChild()))return!1}return!0}function UD1(Z,J){if(!!Z!==!!J)return!1;let X=Z.keys(),Y=J.keys();if(X.length!==Y.length)return!1;for(let $ of X){let Q=Z.get($),K=J.get($);if(!!Q!==!!K)return!1;let G=Q.getChild(),W=K.getChild();if(G===W)continue;if(!G.equals(W))return!1}return!0}function Hr(Z,J){if(Z===J)return!0;if(!!Z!==!!J||!Z||!J)return!1;if(Z.length!==J.length)return!1;for(let X=0;X<Z.length;X++)if(Z[X]!==J[X])return!1;return!0}function Vr(Z,J){if(Z===J)return!0;if(!!Z!==!!J)return!1;if(!X$(Z)||!X$(J))return Z===J;let X=Z,Y=J,$=0,Q=0,K;for(K in X)$++;for(K in Y)Q++;if($!==Q)return!1;for(K in X){let G=X[K],W=Y[K];if(T2(G)&&T2(W)){if(!Hr(G,W))return!1}else if(X$(G)&&X$(W)){if(!Vr(G,W))return!1}else if(G!==W)return!1}return!0}function T2(Z){return Array.isArray(Z)||ArrayBuffer.isView(Z)}var $r="https://null.example";class dT{static dirname(Z){let J=Z.lastIndexOf("/");if(J===-1)return"./";return Z.substring(0,J+1)}static basename(Z){return rH.basename(new URL(Z,$r).pathname)}static extension(Z){return rH.extension(new URL(Z,$r).pathname)}static resolve(Z,J){if(!this.isRelativePath(J))return J;let X=Z.split("/"),Y=J.split("/");X.pop();for(let $=0;$<Y.length;$++){if(Y[$]===".")continue;if(Y[$]==="..")X.pop();else X.push(Y[$])}return X.join("/")}static isAbsoluteURL(Z){return this.PROTOCOL_REGEXP.test(Z)}static isRelativePath(Z){return!/^(?:[a-zA-Z]+:)?\//.test(Z)}}dT.DEFAULT_INIT={};dT.PROTOCOL_REGEXP=/^[a-zA-Z]+:\/\//;var tJ=(Z)=>Z,LD1=new Set;class _2 extends iK{constructor(Z,J=""){super(Z);this[y0].name=J,this.init(),this.dispatchEvent({type:"create"})}getGraph(){return this.graph}getDefaults(){return Object.assign(super.getDefaults(),{name:"",extras:{}})}set(Z,J){if(Array.isArray(J))J=J.slice();return super.set(Z,J)}getName(){return this.get("name")}setName(Z){return this.set("name",Z)}getExtras(){return this.get("extras")}setExtras(Z){return this.set("extras",Z)}clone(){return new this.constructor(this.graph).copy(this,tJ)}copy(Z,J=tJ){for(let X in this[y0]){let Y=this[y0][X];if(Y instanceof T5){if(!this[A4].has(X))Y.dispose()}else if(Y instanceof I6||Y instanceof E0)for(let $ of Y.values())$.dispose();else if(Y instanceof Z8)for(let $ of Y.values())$.dispose()}for(let X in Z[y0]){let Y=this[y0][X],$=Z[y0][X];if($ instanceof T5)if(this[A4].has(X))Y.getChild().copy(J($.getChild()),J);else this.setRef(X,J($.getChild()),$.getAttributes());else if($ instanceof E0||$ instanceof I6)for(let Q of $.values())this.addRef(X,J(Q.getChild()),Q.getAttributes());else if($ instanceof Z8)for(let Q of $.keys()){let K=$.get(Q);this.setRefMap(X,Q,J(K.getChild()),K.getAttributes())}else if(X$($))this[y0][X]=JSON.parse(JSON.stringify($));else if(Array.isArray($)||$ instanceof ArrayBuffer||ArrayBuffer.isView($))this[y0][X]=$.slice();else this[y0][X]=$}return this}equals(Z,J=LD1){if(this===Z)return!0;if(this.propertyType!==Z.propertyType)return!1;for(let X in this[y0]){if(J.has(X))continue;let Y=this[y0][X],$=Z[y0][X];if(Y instanceof T5||$ instanceof T5){if(!FD1(Y,$))return!1}else if(Y instanceof E0||$ instanceof E0||Y instanceof I6||$ instanceof I6){if(!qD1(Y,$))return!1}else if(Y instanceof Z8||$ instanceof Z8){if(!UD1(Y,$))return!1}else if(X$(Y)||X$($)){if(!Vr(Y,$))return!1}else if(T2(Y)||T2($)){if(!Hr(Y,$))return!1}else if(Y!==$)return!1}return!0}detach(){return this.graph.disconnectParents(this,(Z)=>Z.propertyType!=="Root"),this}listParents(){return this.graph.listParents(this)}}class A6 extends _2{getDefaults(){return Object.assign(super.getDefaults(),{extensions:new Z8})}getExtension(Z){return this.getRefMap("extensions",Z)}setExtension(Z,J){if(J)J._validateParent(this);return this.setRefMap("extensions",Z,J)}listExtensions(){return this.listRefMapValues("extensions")}}class T0 extends A6{init(){this.propertyType=s.ACCESSOR}getDefaults(){return Object.assign(super.getDefaults(),{array:null,type:T0.Type.SCALAR,componentType:T0.ComponentType.FLOAT,normalized:!1,sparse:!1,buffer:null})}static getElementSize(Z){switch(Z){case T0.Type.SCALAR:return 1;case T0.Type.VEC2:return 2;case T0.Type.VEC3:return 3;case T0.Type.VEC4:return 4;case T0.Type.MAT2:return 4;case T0.Type.MAT3:return 9;case T0.Type.MAT4:return 16;default:throw new Error("Unexpected type: "+Z)}}static getComponentSize(Z){switch(Z){case T0.ComponentType.BYTE:return 1;case T0.ComponentType.UNSIGNED_BYTE:return 1;case T0.ComponentType.SHORT:return 2;case T0.ComponentType.UNSIGNED_SHORT:return 2;case T0.ComponentType.UNSIGNED_INT:return 4;case T0.ComponentType.FLOAT:return 4;default:throw new Error("Unexpected component type: "+Z)}}getMinNormalized(Z){let J=this.getNormalized(),X=this.getElementSize(),Y=this.getComponentType();if(this.getMin(Z),J)for(let $=0;$<X;$++)Z[$]=z8.decodeNormalizedInt(Z[$],Y);return Z}getMin(Z){let J=this.getArray(),X=this.getCount(),Y=this.getElementSize();for(let $=0;$<Y;$++)Z[$]=1/0;for(let $=0;$<X*Y;$+=Y)for(let Q=0;Q<Y;Q++){let K=J[$+Q];if(Number.isFinite(K))Z[Q]=Math.min(Z[Q],K)}return Z}getMaxNormalized(Z){let J=this.getNormalized(),X=this.getElementSize(),Y=this.getComponentType();if(this.getMax(Z),J)for(let $=0;$<X;$++)Z[$]=z8.decodeNormalizedInt(Z[$],Y);return Z}getMax(Z){let J=this.get("array"),X=this.getCount(),Y=this.getElementSize();for(let $=0;$<Y;$++)Z[$]=-1/0;for(let $=0;$<X*Y;$+=Y)for(let Q=0;Q<Y;Q++){let K=J[$+Q];if(Number.isFinite(K))Z[Q]=Math.max(Z[Q],K)}return Z}getCount(){let Z=this.get("array");return Z?Z.length/this.getElementSize():0}getType(){return this.get("type")}setType(Z){return this.set("type",Z)}getElementSize(){return T0.getElementSize(this.get("type"))}getComponentSize(){return this.get("array").BYTES_PER_ELEMENT}getComponentType(){return this.get("componentType")}getNormalized(){return this.get("normalized")}setNormalized(Z){return this.set("normalized",Z)}getScalar(Z){let J=this.getElementSize(),X=this.getComponentType(),Y=this.getArray();if(this.getNormalized())return z8.decodeNormalizedInt(Y[Z*J],X);return Y[Z*J]}setScalar(Z,J){let X=this.getElementSize(),Y=this.getComponentType(),$=this.getArray();if(this.getNormalized())$[Z*X]=z8.encodeNormalizedInt(J,Y);else $[Z*X]=J;return this}getElement(Z,J){let X=this.getNormalized(),Y=this.getElementSize(),$=this.getComponentType(),Q=this.getArray();for(let K=0;K<Y;K++)if(X)J[K]=z8.decodeNormalizedInt(Q[Z*Y+K],$);else J[K]=Q[Z*Y+K];return J}setElement(Z,J){let X=this.getNormalized(),Y=this.getElementSize(),$=this.getComponentType(),Q=this.getArray();for(let K=0;K<Y;K++)if(X)Q[Z*Y+K]=z8.encodeNormalizedInt(J[K],$);else Q[Z*Y+K]=J[K];return this}getSparse(){return this.get("sparse")}setSparse(Z){return this.set("sparse",Z)}getBuffer(){return this.getRef("buffer")}setBuffer(Z){return this.setRef("buffer",Z)}getArray(){return this.get("array")}setArray(Z){return this.set("componentType",Z?BD1(Z):T0.ComponentType.FLOAT),this.set("array",Z),this}getByteLength(){let Z=this.get("array");return Z?Z.byteLength:0}}T0.Type={SCALAR:"SCALAR",VEC2:"VEC2",VEC3:"VEC3",VEC4:"VEC4",MAT2:"MAT2",MAT3:"MAT3",MAT4:"MAT4"};T0.ComponentType={BYTE:5120,UNSIGNED_BYTE:5121,SHORT:5122,UNSIGNED_SHORT:5123,UNSIGNED_INT:5125,FLOAT:5126};function BD1(Z){switch(Z.constructor){case Float32Array:return T0.ComponentType.FLOAT;case Uint32Array:return T0.ComponentType.UNSIGNED_INT;case Uint16Array:return T0.ComponentType.UNSIGNED_SHORT;case Uint8Array:return T0.ComponentType.UNSIGNED_BYTE;case Int16Array:return T0.ComponentType.SHORT;case Int8Array:return T0.ComponentType.BYTE;default:throw new Error("Unknown accessor componentType.")}}class cT extends A6{init(){this.propertyType=s.ANIMATION}getDefaults(){return Object.assign(super.getDefaults(),{channels:new E0,samplers:new E0})}addChannel(Z){return this.addRef("channels",Z)}removeChannel(Z){return this.removeRef("channels",Z)}listChannels(){return this.listRefs("channels")}addSampler(Z){return this.addRef("samplers",Z)}removeSampler(Z){return this.removeRef("samplers",Z)}listSamplers(){return this.listRefs("samplers")}}class eH extends A6{init(){this.propertyType=s.ANIMATION_CHANNEL}getDefaults(){return Object.assign(super.getDefaults(),{targetPath:null,targetNode:null,sampler:null})}getTargetPath(){return this.get("targetPath")}setTargetPath(Z){return this.set("targetPath",Z)}getTargetNode(){return this.getRef("targetNode")}setTargetNode(Z){return this.setRef("targetNode",Z)}getSampler(){return this.getRef("sampler")}setSampler(Z){return this.setRef("sampler",Z)}}eH.TargetPath={TRANSLATION:"translation",ROTATION:"rotation",SCALE:"scale",WEIGHTS:"weights"};class QG extends A6{init(){this.propertyType=s.ANIMATION_SAMPLER}getDefaultAttributes(){return Object.assign(super.getDefaults(),{interpolation:QG.Interpolation.LINEAR,input:null,output:null})}getInterpolation(){return this.get("interpolation")}setInterpolation(Z){return this.set("interpolation",Z)}getInput(){return this.getRef("input")}setInput(Z){return this.setRef("input",Z,{usage:X9.OTHER})}getOutput(){return this.getRef("output")}setOutput(Z){return this.setRef("output",Z,{usage:X9.OTHER})}}QG.Interpolation={LINEAR:"LINEAR",STEP:"STEP",CUBICSPLINE:"CUBICSPLINE"};class lT extends A6{init(){this.propertyType=s.BUFFER}getDefaults(){return Object.assign(super.getDefaults(),{uri:""})}getURI(){return this.get("uri")}setURI(Z){return this.set("uri",Z)}}class ZV extends A6{init(){this.propertyType=s.CAMERA}getDefaults(){return Object.assign(super.getDefaults(),{type:ZV.Type.PERSPECTIVE,znear:0.1,zfar:100,aspectRatio:null,yfov:Math.PI*2*50/360,xmag:1,ymag:1})}getType(){return this.get("type")}setType(Z){return this.set("type",Z)}getZNear(){return this.get("znear")}setZNear(Z){return this.set("znear",Z)}getZFar(){return this.get("zfar")}setZFar(Z){return this.set("zfar",Z)}getAspectRatio(){return this.get("aspectRatio")}setAspectRatio(Z){return this.set("aspectRatio",Z)}getYFov(){return this.get("yfov")}setYFov(Z){return this.set("yfov",Z)}getXMag(){return this.get("xmag")}setXMag(Z){return this.set("xmag",Z)}getYMag(){return this.get("ymag")}setYMag(Z){return this.set("ymag",Z)}}ZV.Type={PERSPECTIVE:"perspective",ORTHOGRAPHIC:"orthographic"};class s1 extends _2{_validateParent(Z){if(!this.parentTypes.includes(Z.propertyType))throw new Error(`Parent "${Z.propertyType}" invalid for child "${this.propertyType}".`)}}s1.EXTENSION_NAME=void 0;class T1 extends A6{init(){this.propertyType=s.TEXTURE_INFO}getDefaults(){return Object.assign(super.getDefaults(),{texCoord:0,magFilter:null,minFilter:null,wrapS:T1.WrapMode.REPEAT,wrapT:T1.WrapMode.REPEAT})}getTexCoord(){return this.get("texCoord")}setTexCoord(Z){return this.set("texCoord",Z)}getMagFilter(){return this.get("magFilter")}setMagFilter(Z){return this.set("magFilter",Z)}getMinFilter(){return this.get("minFilter")}setMinFilter(Z){return this.set("minFilter",Z)}getWrapS(){return this.get("wrapS")}setWrapS(Z){return this.set("wrapS",Z)}getWrapT(){return this.get("wrapT")}setWrapT(Z){return this.set("wrapT",Z)}}T1.WrapMode={CLAMP_TO_EDGE:33071,MIRRORED_REPEAT:33648,REPEAT:10497};T1.MagFilter={NEAREST:9728,LINEAR:9729};T1.MinFilter={NEAREST:9728,LINEAR:9729,NEAREST_MIPMAP_NEAREST:9984,LINEAR_MIPMAP_NEAREST:9985,NEAREST_MIPMAP_LINEAR:9986,LINEAR_MIPMAP_LINEAR:9987};var{R:P2,G:D2,B:C2,A:wD1}=Y9;class JV extends A6{init(){this.propertyType=s.MATERIAL}getDefaults(){return Object.assign(super.getDefaults(),{alphaMode:JV.AlphaMode.OPAQUE,alphaCutoff:0.5,doubleSided:!1,baseColorFactor:[1,1,1,1],baseColorTexture:null,baseColorTextureInfo:new T1(this.graph,"baseColorTextureInfo"),emissiveFactor:[0,0,0],emissiveTexture:null,emissiveTextureInfo:new T1(this.graph,"emissiveTextureInfo"),normalScale:1,normalTexture:null,normalTextureInfo:new T1(this.graph,"normalTextureInfo"),occlusionStrength:1,occlusionTexture:null,occlusionTextureInfo:new T1(this.graph,"occlusionTextureInfo"),roughnessFactor:1,metallicFactor:1,metallicRoughnessTexture:null,metallicRoughnessTextureInfo:new T1(this.graph,"metallicRoughnessTextureInfo")})}getDoubleSided(){return this.get("doubleSided")}setDoubleSided(Z){return this.set("doubleSided",Z)}getAlpha(){return this.get("baseColorFactor")[3]}setAlpha(Z){let J=this.get("baseColorFactor").slice();return J[3]=Z,this.set("baseColorFactor",J)}getAlphaMode(){return this.get("alphaMode")}setAlphaMode(Z){return this.set("alphaMode",Z)}getAlphaCutoff(){return this.get("alphaCutoff")}setAlphaCutoff(Z){return this.set("alphaCutoff",Z)}getBaseColorFactor(){return this.get("baseColorFactor")}setBaseColorFactor(Z){return this.set("baseColorFactor",Z)}getBaseColorTexture(){return this.getRef("baseColorTexture")}getBaseColorTextureInfo(){return this.getRef("baseColorTexture")?this.getRef("baseColorTextureInfo"):null}setBaseColorTexture(Z){return this.setRef("baseColorTexture",Z,{channels:P2|D2|C2|wD1,isColor:!0})}getEmissiveFactor(){return this.get("emissiveFactor")}setEmissiveFactor(Z){return this.set("emissiveFactor",Z)}getEmissiveTexture(){return this.getRef("emissiveTexture")}getEmissiveTextureInfo(){return this.getRef("emissiveTexture")?this.getRef("emissiveTextureInfo"):null}setEmissiveTexture(Z){return this.setRef("emissiveTexture",Z,{channels:P2|D2|C2,isColor:!0})}getNormalScale(){return this.get("normalScale")}setNormalScale(Z){return this.set("normalScale",Z)}getNormalTexture(){return this.getRef("normalTexture")}getNormalTextureInfo(){return this.getRef("normalTexture")?this.getRef("normalTextureInfo"):null}setNormalTexture(Z){return this.setRef("normalTexture",Z,{channels:P2|D2|C2})}getOcclusionStrength(){return this.get("occlusionStrength")}setOcclusionStrength(Z){return this.set("occlusionStrength",Z)}getOcclusionTexture(){return this.getRef("occlusionTexture")}getOcclusionTextureInfo(){return this.getRef("occlusionTexture")?this.getRef("occlusionTextureInfo"):null}setOcclusionTexture(Z){return this.setRef("occlusionTexture",Z,{channels:P2})}getRoughnessFactor(){return this.get("roughnessFactor")}setRoughnessFactor(Z){return this.set("roughnessFactor",Z)}getMetallicFactor(){return this.get("metallicFactor")}setMetallicFactor(Z){return this.set("metallicFactor",Z)}getMetallicRoughnessTexture(){return this.getRef("metallicRoughnessTexture")}getMetallicRoughnessTextureInfo(){return this.getRef("metallicRoughnessTexture")?this.getRef("metallicRoughnessTextureInfo"):null}setMetallicRoughnessTexture(Z){return this.setRef("metallicRoughnessTexture",Z,{channels:D2|C2})}}JV.AlphaMode={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};class pT extends A6{init(){this.propertyType=s.MESH}getDefaults(){return Object.assign(super.getDefaults(),{weights:[],primitives:new E0})}addPrimitive(Z){return this.addRef("primitives",Z)}removePrimitive(Z){return this.removeRef("primitives",Z)}listPrimitives(){return this.listRefs("primitives")}getWeights(){return this.get("weights")}setWeights(Z){return this.set("weights",Z)}}class iT extends A6{init(){this.propertyType=s.NODE}getDefaults(){return Object.assign(super.getDefaults(),{translation:[0,0,0],rotation:[0,0,0,1],scale:[1,1,1],weights:[],camera:null,mesh:null,skin:null,children:new E0})}copy(Z,J=tJ){if(J===tJ)throw new Error("Node cannot be copied.");return super.copy(Z,J)}getTranslation(){return this.get("translation")}getRotation(){return this.get("rotation")}getScale(){return this.get("scale")}setTranslation(Z){return this.set("translation",Z)}setRotation(Z){return this.set("rotation",Z)}setScale(Z){return this.set("scale",Z)}getMatrix(){return z8.compose(this.get("translation"),this.get("rotation"),this.get("scale"),[])}setMatrix(Z){let J=this.get("translation").slice(),X=this.get("rotation").slice(),Y=this.get("scale").slice();return z8.decompose(Z,J,X,Y),this.set("translation",J).set("rotation",X).set("scale",Y)}getWorldTranslation(){let Z=[0,0,0];return z8.decompose(this.getWorldMatrix(),Z,[0,0,0,1],[1,1,1]),Z}getWorldRotation(){let Z=[0,0,0,1];return z8.decompose(this.getWorldMatrix(),[0,0,0],Z,[1,1,1]),Z}getWorldScale(){let Z=[1,1,1];return z8.decompose(this.getWorldMatrix(),[0,0,0],[0,0,0,1],Z),Z}getWorldMatrix(){let Z=[];for(let Y=this;Y!=null;Y=Y.getParentNode())Z.push(Y);let J,X=Z.pop().getMatrix();while(J=Z.pop())HD1(X,X,J.getMatrix());return X}addChild(Z){let J=Z.getParentNode();if(J)J.removeChild(Z);for(let X of Z.listParents())if(X.propertyType===s.SCENE)X.removeChild(Z);return this.addRef("children",Z)}removeChild(Z){return this.removeRef("children",Z)}listChildren(){return this.listRefs("children")}getParentNode(){for(let Z of this.listParents())if(Z.propertyType===s.NODE)return Z;return null}getMesh(){return this.getRef("mesh")}setMesh(Z){return this.setRef("mesh",Z)}getCamera(){return this.getRef("camera")}setCamera(Z){return this.setRef("camera",Z)}getSkin(){return this.getRef("skin")}setSkin(Z){return this.setRef("skin",Z)}getWeights(){return this.get("weights")}setWeights(Z){return this.set("weights",Z)}traverse(Z){Z(this);for(let J of this.listChildren())J.traverse(Z);return this}}class eJ extends A6{init(){this.propertyType=s.PRIMITIVE}getDefaults(){return Object.assign(super.getDefaults(),{mode:eJ.Mode.TRIANGLES,material:null,indices:null,attributes:new Z8,targets:new E0})}getIndices(){return this.getRef("indices")}setIndices(Z){return this.setRef("indices",Z,{usage:X9.ELEMENT_ARRAY_BUFFER})}getAttribute(Z){return this.getRefMap("attributes",Z)}setAttribute(Z,J){return this.setRefMap("attributes",Z,J,{usage:X9.ARRAY_BUFFER})}listAttributes(){return this.listRefMapValues("attributes")}listSemantics(){return this.listRefMapKeys("attributes")}getMaterial(){return this.getRef("material")}setMaterial(Z){return this.setRef("material",Z)}getMode(){return this.get("mode")}setMode(Z){return this.set("mode",Z)}listTargets(){return this.listRefs("targets")}addTarget(Z){return this.addRef("targets",Z)}removeTarget(Z){return this.removeRef("targets",Z)}}eJ.Mode={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6};class zr extends _2{init(){this.propertyType=s.PRIMITIVE_TARGET}getDefaults(){return Object.assign(super.getDefaults(),{attributes:new Z8})}getAttribute(Z){return this.getRefMap("attributes",Z)}setAttribute(Z,J){return this.setRefMap("attributes",Z,J,{usage:X9.ARRAY_BUFFER})}listAttributes(){return this.listRefMapValues("attributes")}listSemantics(){return this.listRefMapKeys("attributes")}}function E2(){return E2=Object.assign?Object.assign.bind():function(Z){for(var J=1;J<arguments.length;J++){var X=arguments[J];for(var Y in X)({}).hasOwnProperty.call(X,Y)&&(Z[Y]=X[Y])}return Z},E2.apply(null,arguments)}class nT extends A6{init(){this.propertyType=s.SCENE}getDefaults(){return Object.assign(super.getDefaults(),{children:new E0})}copy(Z,J=tJ){if(J===tJ)throw new Error("Scene cannot be copied.");return super.copy(Z,J)}addChild(Z){let J=Z.getParentNode();if(J)J.removeChild(Z);return this.addRef("children",Z)}removeChild(Z){return this.removeRef("children",Z)}listChildren(){return this.listRefs("children")}traverse(Z){for(let J of this.listChildren())J.traverse(Z);return this}}class aT extends A6{init(){this.propertyType=s.SKIN}getDefaults(){return Object.assign(super.getDefaults(),{skeleton:null,inverseBindMatrices:null,joints:new E0})}getSkeleton(){return this.getRef("skeleton")}setSkeleton(Z){return this.setRef("skeleton",Z)}getInverseBindMatrices(){return this.getRef("inverseBindMatrices")}setInverseBindMatrices(Z){return this.setRef("inverseBindMatrices",Z,{usage:X9.INVERSE_BIND_MATRICES})}addJoint(Z){return this.addRef("joints",Z)}removeJoint(Z){return this.removeRef("joints",Z)}listJoints(){return this.listRefs("joints")}}class sT extends A6{init(){this.propertyType=s.TEXTURE}getDefaults(){return Object.assign(super.getDefaults(),{image:null,mimeType:"",uri:""})}getMimeType(){return this.get("mimeType")||h4.extensionToMimeType(rH.extension(this.get("uri")))}setMimeType(Z){return this.set("mimeType",Z)}getURI(){return this.get("uri")}setURI(Z){this.set("uri",Z);let J=h4.extensionToMimeType(rH.extension(Z));if(J)this.set("mimeType",J);return this}getImage(){return this.get("image")}setImage(Z){return this.set("image",v6.assertView(Z))}getSize(){let Z=this.get("image");if(!Z)return null;return h4.getSize(Z,this.getMimeType())}}class S2 extends A6{init(){this.propertyType=s.ROOT}getDefaults(){return Object.assign(super.getDefaults(),{asset:{generator:`glTF-Transform ${YD1}`,version:"2.0"},defaultScene:null,accessors:new E0,animations:new E0,buffers:new E0,cameras:new E0,materials:new E0,meshes:new E0,nodes:new E0,scenes:new E0,skins:new E0,textures:new E0})}constructor(Z){super(Z);this._extensions=new Set,Z.addEventListener("node:create",(J)=>{this._addChildOfRoot(J.target)})}clone(){throw new Error("Root cannot be cloned.")}copy(Z,J=tJ){if(J===tJ)throw new Error("Root cannot be copied.");this.set("asset",E2({},Z.get("asset"))),this.setName(Z.getName()),this.setExtras(E2({},Z.getExtras())),this.setDefaultScene(Z.getDefaultScene()?J(Z.getDefaultScene()):null);for(let X of Z.listRefMapKeys("extensions")){let Y=Z.getExtension(X);this.setExtension(X,J(Y))}return this}_addChildOfRoot(Z){if(Z instanceof nT)this.addRef("scenes",Z);else if(Z instanceof iT)this.addRef("nodes",Z);else if(Z instanceof ZV)this.addRef("cameras",Z);else if(Z instanceof aT)this.addRef("skins",Z);else if(Z instanceof pT)this.addRef("meshes",Z);else if(Z instanceof JV)this.addRef("materials",Z);else if(Z instanceof sT)this.addRef("textures",Z);else if(Z instanceof cT)this.addRef("animations",Z);else if(Z instanceof T0)this.addRef("accessors",Z);else if(Z instanceof lT)this.addRef("buffers",Z);return this}getAsset(){return this.get("asset")}listExtensionsUsed(){return Array.from(this._extensions)}listExtensionsRequired(){return this.listExtensionsUsed().filter((Z)=>Z.isRequired())}_enableExtension(Z){return this._extensions.add(Z),this}_disableExtension(Z){return this._extensions.delete(Z),this}listScenes(){return this.listRefs("scenes")}setDefaultScene(Z){return this.setRef("defaultScene",Z)}getDefaultScene(){return this.getRef("defaultScene")}listNodes(){return this.listRefs("nodes")}listCameras(){return this.listRefs("cameras")}listSkins(){return this.listRefs("skins")}listMeshes(){return this.listRefs("meshes")}listMaterials(){return this.listRefs("materials")}listTextures(){return this.listRefs("textures")}listAnimations(){return this.listRefs("animations")}listAccessors(){return this.listRefs("accessors")}listBuffers(){return this.listRefs("buffers")}}class k2{static fromGraph(Z){return k2._GRAPH_DOCUMENTS.get(Z)||null}constructor(){this._graph=new pK,this._root=new S2(this._graph),this._logger=_7.DEFAULT_INSTANCE,k2._GRAPH_DOCUMENTS.set(this._graph,this)}getRoot(){return this._root}getGraph(){return this._graph}getLogger(){return this._logger}setLogger(Z){return this._logger=Z,this}clone(){throw new Error("Use 'cloneDocument(source)' from '@gltf-transform/functions'.")}merge(Z){throw new Error("Use 'mergeDocuments(target, source)' from '@gltf-transform/functions'.")}async transform(...Z){let J=Z.map((X)=>X.name);for(let X of Z)await X(this,{stack:J});return this}createExtension(Z){let J=Z.EXTENSION_NAME;return this.getRoot().listExtensionsUsed().find((Y)=>Y.extensionName===J)||new Z(this)}createScene(Z=""){return new nT(this._graph,Z)}createNode(Z=""){return new iT(this._graph,Z)}createCamera(Z=""){return new ZV(this._graph,Z)}createSkin(Z=""){return new aT(this._graph,Z)}createMesh(Z=""){return new pT(this._graph,Z)}createPrimitive(){return new eJ(this._graph)}createPrimitiveTarget(Z=""){return new zr(this._graph,Z)}createMaterial(Z=""){return new JV(this._graph,Z)}createTexture(Z=""){return new sT(this._graph,Z)}createAnimation(Z=""){return new cT(this._graph,Z)}createAnimationChannel(Z=""){return new eH(this._graph,Z)}createAnimationSampler(Z=""){return new QG(this._graph,Z)}createAccessor(Z="",J=null){if(!J)J=this.getRoot().listBuffers()[0];return new T0(this._graph,Z).setBuffer(J)}createBuffer(Z=""){return new lT(this._graph,Z)}}k2._GRAPH_DOCUMENTS=new WeakMap;class I1{constructor(Z){this.extensionName="",this.prereadTypes=[],this.prewriteTypes=[],this.readDependencies=[],this.writeDependencies=[],this.document=void 0,this.required=!1,this.properties=new Set,this._listener=void 0,this.document=Z,Z.getRoot()._enableExtension(this),this._listener=(X)=>{let Y=X,$=Y.target;if($ instanceof s1&&$.extensionName===this.extensionName){if(Y.type==="node:create")this._addExtensionProperty($);if(Y.type==="node:dispose")this._removeExtensionProperty($)}};let J=Z.getGraph();J.addEventListener("node:create",this._listener),J.addEventListener("node:dispose",this._listener)}dispose(){this.document.getRoot()._disableExtension(this);let Z=this.document.getGraph();Z.removeEventListener("node:create",this._listener),Z.removeEventListener("node:dispose",this._listener);for(let J of this.properties)J.dispose()}static register(){}isRequired(){return this.required}setRequired(Z){return this.required=Z,this}listProperties(){return Array.from(this.properties)}_addExtensionProperty(Z){return this.properties.add(Z),this}_removeExtensionProperty(Z){return this.properties.delete(Z),this}install(Z,J){return this}preread(Z,J){return this}prewrite(Z,J){return this}}I1.EXTENSION_NAME=void 0;var OS6={logger:_7.DEFAULT_INSTANCE,extensions:[],dependencies:{}},MS6=new Set([s.BUFFER,s.TEXTURE,s.MATERIAL,s.MESH,s.PRIMITIVE,s.NODE,s.SCENE]);var tH;(function(Z){Z[Z.ARRAY_BUFFER=34962]="ARRAY_BUFFER",Z[Z.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER"})(tH||(tH={}));class ZX{constructor(Z,J,X){this._doc=void 0,this.jsonDoc=void 0,this.options=void 0,this.accessorIndexMap=new Map,this.animationIndexMap=new Map,this.bufferIndexMap=new Map,this.cameraIndexMap=new Map,this.skinIndexMap=new Map,this.materialIndexMap=new Map,this.meshIndexMap=new Map,this.nodeIndexMap=new Map,this.imageIndexMap=new Map,this.textureDefIndexMap=new Map,this.textureInfoDefMap=new Map,this.samplerDefIndexMap=new Map,this.sceneIndexMap=new Map,this.imageBufferViews=[],this.otherBufferViews=new Map,this.otherBufferViewsIndexMap=new Map,this.extensionData={},this.bufferURIGenerator=void 0,this.imageURIGenerator=void 0,this.logger=void 0,this._accessorUsageMap=new Map,this.accessorUsageGroupedByParent=new Set(["ARRAY_BUFFER"]),this.accessorParents=new Map,this._doc=Z,this.jsonDoc=J,this.options=X;let Y=Z.getRoot(),$=Y.listBuffers().length,Q=Y.listTextures().length;this.bufferURIGenerator=new mT($>1,()=>X.basename||"buffer"),this.imageURIGenerator=new mT(Q>1,(K)=>jD1(Z,K)||X.basename||"texture"),this.logger=Z.getLogger()}createTextureInfoDef(Z,J){let X={magFilter:J.getMagFilter()||void 0,minFilter:J.getMinFilter()||void 0,wrapS:J.getWrapS(),wrapT:J.getWrapT()},Y=JSON.stringify(X);if(!this.samplerDefIndexMap.has(Y))this.samplerDefIndexMap.set(Y,this.jsonDoc.json.samplers.length),this.jsonDoc.json.samplers.push(X);let $={source:this.imageIndexMap.get(Z),sampler:this.samplerDefIndexMap.get(Y)},Q=JSON.stringify($);if(!this.textureDefIndexMap.has(Q))this.textureDefIndexMap.set(Q,this.jsonDoc.json.textures.length),this.jsonDoc.json.textures.push($);let K={index:this.textureDefIndexMap.get(Q)};if(J.getTexCoord()!==0)K.texCoord=J.getTexCoord();if(Object.keys(J.getExtras()).length>0)K.extras=J.getExtras();return this.textureInfoDefMap.set(J,K),K}createPropertyDef(Z){let J={};if(Z.getName())J.name=Z.getName();if(Object.keys(Z.getExtras()).length>0)J.extras=Z.getExtras();return J}createAccessorDef(Z){let J=this.createPropertyDef(Z);if(J.type=Z.getType(),J.componentType=Z.getComponentType(),J.count=Z.getCount(),this._doc.getGraph().listParentEdges(Z).some((Y)=>Y.getName()==="attributes"&&Y.getAttributes().key==="POSITION"||Y.getName()==="input"))J.max=Z.getMax([]).map(Math.fround),J.min=Z.getMin([]).map(Math.fround);if(Z.getNormalized())J.normalized=Z.getNormalized();return J}createImageData(Z,J,X){if(this.options.format===hT.GLB)this.imageBufferViews.push(J),Z.bufferView=this.jsonDoc.json.bufferViews.length,this.jsonDoc.json.bufferViews.push({buffer:0,byteOffset:-1,byteLength:J.byteLength});else{let Y=h4.mimeTypeToExtension(X.getMimeType());Z.uri=this.imageURIGenerator.createURI(X,Y),this.assignResourceURI(Z.uri,J,!1)}}assignResourceURI(Z,J,X){let Y=this.jsonDoc.resources;if(!(Z in Y)){Y[Z]=J;return}if(J===Y[Z]){this.logger.warn(`Duplicate resource URI, "${Z}".`);return}let $=`Resource URI "${Z}" already assigned to different data.`;if(!X){this.logger.warn($);return}throw new Error($)}getAccessorUsage(Z){let J=this._accessorUsageMap.get(Z);if(J)return J;if(Z.getSparse())return X9.SPARSE;for(let X of this._doc.getGraph().listParentEdges(Z)){let{usage:Y}=X.getAttributes();if(Y)return Y;if(X.getParent().propertyType!==s.ROOT)this.logger.warn(`Missing attribute ".usage" on edge, "${X.getName()}".`)}return X9.OTHER}addAccessorToUsageGroup(Z,J){let X=this._accessorUsageMap.get(Z);if(X&&X!==J)throw new Error(`Accessor with usage "${X}" cannot be reused as "${J}".`);return this._accessorUsageMap.set(Z,J),this}}ZX.BufferViewTarget=tH;ZX.BufferViewUsage=X9;ZX.USAGE_TO_TARGET={[X9.ARRAY_BUFFER]:tH.ARRAY_BUFFER,[X9.ELEMENT_ARRAY_BUFFER]:tH.ELEMENT_ARRAY_BUFFER};class mT{constructor(Z,J){this.multiple=void 0,this.basename=void 0,this.counter={},this.multiple=Z,this.basename=J}createURI(Z,J){if(Z.getURI())return Z.getURI();else if(!this.multiple)return`${this.basename(Z)}.${J}`;else{let X=this.basename(Z);return this.counter[X]=this.counter[X]||1,`${X}_${this.counter[X]++}.${J}`}}}function jD1(Z,J){let X=Z.getGraph().listParentEdges(J).find((Y)=>Y.getParent()!==Z.getRoot());return X?X.getName().replace(/texture$/i,""):""}var{UNSIGNED_INT:RS6,UNSIGNED_SHORT:NS6,UNSIGNED_BYTE:PS6}=T0.ComponentType,DS6=new Set([s.ACCESSOR,s.BUFFER,s.MATERIAL,s.MESH]);var Qr;(function(Z){Z[Z.JSON=1313821514]="JSON",Z[Z.BIN=5130562]="BIN"})(Qr||(Qr={}));var qr=163,Ur=166;function OD1(){return{vkFormat:0,typeSize:1,pixelWidth:0,pixelHeight:0,pixelDepth:0,layerCount:0,faceCount:1,supercompressionScheme:0,levels:[],dataFormatDescriptor:[{vendorId:0,descriptorType:0,versionNumber:2,colorModel:0,colorPrimaries:1,transferFunction:2,flags:0,texelBlockDimension:[0,0,0,0],bytesPlane:[0,0,0,0,0,0,0,0],samples:[]}],keyValue:{},globalData:null}}class KG{constructor(Z,J,X,Y){this._dataView=void 0,this._littleEndian=void 0,this._offset=void 0,this._dataView=new DataView(Z.buffer,Z.byteOffset+J,X),this._littleEndian=Y,this._offset=0}_nextUint8(){let Z=this._dataView.getUint8(this._offset);return this._offset+=1,Z}_nextUint16(){let Z=this._dataView.getUint16(this._offset,this._littleEndian);return this._offset+=2,Z}_nextUint32(){let Z=this._dataView.getUint32(this._offset,this._littleEndian);return this._offset+=4,Z}_nextUint64(){let Z=this._dataView.getUint32(this._offset,this._littleEndian),J=this._dataView.getUint32(this._offset+4,this._littleEndian),X=Z+4294967296*J;return this._offset+=8,X}_nextInt32(){let Z=this._dataView.getInt32(this._offset,this._littleEndian);return this._offset+=4,Z}_nextUint8Array(Z){let J=new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+this._offset,Z);return this._offset+=Z,J}_skip(Z){return this._offset+=Z,this}_scan(Z,J=0){let X=this._offset,Y=0;while(this._dataView.getUint8(this._offset)!==J&&Y<Z)Y++,this._offset++;if(Y<Z)this._offset++;return new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+X,Y)}}var ES6=new Uint8Array([0]),J5=[171,75,84,88,32,50,48,187,13,10,26,10];function Fr(Z){return new TextDecoder().decode(Z)}function v2(Z){let J=new Uint8Array(Z.buffer,Z.byteOffset,J5.length);if(J[0]!==J5[0]||J[1]!==J5[1]||J[2]!==J5[2]||J[3]!==J5[3]||J[4]!==J5[4]||J[5]!==J5[5]||J[6]!==J5[6]||J[7]!==J5[7]||J[8]!==J5[8]||J[9]!==J5[9]||J[10]!==J5[10]||J[11]!==J5[11])throw new Error("Missing KTX 2.0 identifier.");let X=OD1(),Y=17*Uint32Array.BYTES_PER_ELEMENT,$=new KG(Z,J5.length,Y,!0);X.vkFormat=$._nextUint32(),X.typeSize=$._nextUint32(),X.pixelWidth=$._nextUint32(),X.pixelHeight=$._nextUint32(),X.pixelDepth=$._nextUint32(),X.layerCount=$._nextUint32(),X.faceCount=$._nextUint32();let Q=$._nextUint32();X.supercompressionScheme=$._nextUint32();let K=$._nextUint32(),G=$._nextUint32(),W=$._nextUint32(),H=$._nextUint32(),V=$._nextUint64(),F=$._nextUint64(),z=Q*3*8,q=new KG(Z,J5.length+Y,z,!0);for(let q6=0;q6<Q;q6++)X.levels.push({levelData:new Uint8Array(Z.buffer,Z.byteOffset+q._nextUint64(),q._nextUint64()),uncompressedByteLength:q._nextUint64()});let U=new KG(Z,K,G,!0);U._skip(4);let B=U._nextUint16(),L=U._nextUint16(),w=U._nextUint16(),O=U._nextUint16(),M=U._nextUint8(),R=U._nextUint8(),D=U._nextUint8(),N=U._nextUint8(),C=[U._nextUint8(),U._nextUint8(),U._nextUint8(),U._nextUint8()],T=[U._nextUint8(),U._nextUint8(),U._nextUint8(),U._nextUint8(),U._nextUint8(),U._nextUint8(),U._nextUint8(),U._nextUint8()],x={vendorId:B,descriptorType:L,versionNumber:w,colorModel:M,colorPrimaries:R,transferFunction:D,flags:N,texelBlockDimension:C,bytesPlane:T,samples:[]},S=6,h=4,I=(O/4-S)/h;for(let q6=0;q6<I;q6++){let LZ={bitOffset:U._nextUint16(),bitLength:U._nextUint8(),channelType:U._nextUint8(),samplePosition:[U._nextUint8(),U._nextUint8(),U._nextUint8(),U._nextUint8()],sampleLower:Number.NEGATIVE_INFINITY,sampleUpper:Number.POSITIVE_INFINITY};if(LZ.channelType&64)LZ.sampleLower=U._nextInt32(),LZ.sampleUpper=U._nextInt32();else LZ.sampleLower=U._nextUint32(),LZ.sampleUpper=U._nextUint32();x.samples[q6]=LZ}X.dataFormatDescriptor.length=0,X.dataFormatDescriptor.push(x);let _=new KG(Z,W,H,!0);while(_._offset<H){let q6=_._nextUint32(),LZ=_._scan(q6),OU=Fr(LZ);if(X.keyValue[OU]=_._nextUint8Array(q6-LZ.byteLength-1),OU.match(/^ktx/i)){let xm=Fr(X.keyValue[OU]);X.keyValue[OU]=xm.substring(0,xm.lastIndexOf("\x00"))}let PV1=q6%4?4-q6%4:0;_._skip(PV1)}if(F<=0)return X;let A=new KG(Z,V,F,!0),p=A._nextUint16(),n=A._nextUint16(),o=A._nextUint32(),Q0=A._nextUint32(),G0=A._nextUint32(),S0=A._nextUint32(),v0=[];for(let q6=0;q6<Q;q6++)v0.push({imageFlags:A._nextUint32(),rgbSliceByteOffset:A._nextUint32(),rgbSliceByteLength:A._nextUint32(),alphaSliceByteOffset:A._nextUint32(),alphaSliceByteLength:A._nextUint32()});let r0=V+A._offset,A8=r0+o,t1=A8+Q0,U7=t1+G0,N4=new Uint8Array(Z.buffer,Z.byteOffset+r0,o),HK=new Uint8Array(Z.buffer,Z.byteOffset+A8,Q0),VK=new Uint8Array(Z.buffer,Z.byteOffset+t1,G0),IY=new Uint8Array(Z.buffer,Z.byteOffset+U7,S0);return X.globalData={endpointCount:p,selectorCount:n,imageDescs:v0,endpointsData:N4,selectorsData:HK,tablesData:VK,extendedData:IY},X}var ZE="EXT_mesh_gpu_instancing",rT="EXT_meshopt_compression",MD1="EXT_texture_webp",RD1="EXT_texture_avif",kr="KHR_draco_mesh_compression",JE="KHR_lights_punctual",XE="KHR_materials_anisotropy",YE="KHR_materials_clearcoat",$E="KHR_materials_diffuse_transmission",QE="KHR_materials_dispersion",KE="KHR_materials_emissive_strength",GE="KHR_materials_ior",WE="KHR_materials_iridescence",HE="KHR_materials_pbrSpecularGlossiness",VE="KHR_materials_sheen",zE="KHR_materials_specular",FE="KHR_materials_transmission",qE="KHR_materials_unlit",UE="KHR_materials_volume",w$="KHR_materials_variants",ND1="KHR_mesh_quantization",PD1="KHR_texture_basisu",LE="KHR_texture_transform",A2="KHR_xmp_json_ld",tT="INSTANCE_ATTRIBUTE";class BE extends s1{init(){this.extensionName=ZE,this.propertyType="InstancedMesh",this.parentTypes=[s.NODE]}getDefaults(){return Object.assign(super.getDefaults(),{attributes:new Z8})}getAttribute(Z){return this.getRefMap("attributes",Z)}setAttribute(Z,J){return this.setRefMap("attributes",Z,J,{usage:tT})}listAttributes(){return this.listRefMapValues("attributes")}listSemantics(){return this.listRefMapKeys("attributes")}}BE.EXTENSION_NAME=ZE;var Y$=ZE;class f2 extends I1{constructor(...Z){super(...Z);this.extensionName=Y$,this.provideTypes=[s.NODE],this.prewriteTypes=[s.ACCESSOR]}createInstancedMesh(){return new BE(this.document.getGraph())}read(Z){return(Z.jsonDoc.json.nodes||[]).forEach((Y,$)=>{if(!Y.extensions||!Y.extensions[Y$])return;let Q=Y.extensions[Y$],K=this.createInstancedMesh();for(let G in Q.attributes)K.setAttribute(G,Z.accessors[Q.attributes[G]]);Z.nodes[$].setExtension(Y$,K)}),this}prewrite(Z){Z.accessorUsageGroupedByParent.add(tT);for(let J of this.properties)for(let X of J.listAttributes())Z.addAccessorToUsageGroup(X,tT);return this}write(Z){let J=Z.jsonDoc;return this.document.getRoot().listNodes().forEach((X)=>{let Y=X.getExtension(Y$);if(Y){let $=Z.nodeIndexMap.get(X),Q=J.json.nodes[$],K={attributes:{}};Y.listSemantics().forEach((G)=>{let W=Y.getAttribute(G);K.attributes[G]=Z.accessorIndexMap.get(W)}),Q.extensions=Q.extensions||{},Q.extensions[Y$]=K}}),this}}f2.EXTENSION_NAME=Y$;function AZ(){return AZ=Object.assign?Object.assign.bind():function(Z){for(var J=1;J<arguments.length;J++){var X=arguments[J];for(var Y in X)({}).hasOwnProperty.call(X,Y)&&(Z[Y]=X[Y])}return Z},AZ.apply(null,arguments)}var QV;(function(Z){Z.QUANTIZE="quantize",Z.FILTER="filter"})(QV||(QV={}));var WG;(function(Z){Z.ATTRIBUTES="ATTRIBUTES",Z.TRIANGLES="TRIANGLES",Z.INDICES="INDICES"})(WG||(WG={}));var F8;(function(Z){Z.NONE="NONE",Z.OCTAHEDRAL="OCTAHEDRAL",Z.QUATERNION="QUATERNION",Z.EXPONENTIAL="EXPONENTIAL"})(F8||(F8={}));var{BYTE:DD1,SHORT:Lr,FLOAT:CD1}=T0.ComponentType,{encodeNormalizedInt:Br,decodeNormalizedInt:eT}=z8;function TD1(Z,J,X,Y){let{filter:$,bits:Q}=Y,K={array:Z.getArray(),byteStride:Z.getElementSize()*Z.getComponentSize(),componentType:Z.getComponentType(),normalized:Z.getNormalized()};if(X!==WG.ATTRIBUTES)return K;if($!==F8.NONE){let G=Z.getNormalized()?ED1(Z):new Float32Array(K.array);switch($){case F8.EXPONENTIAL:K.byteStride=Z.getElementSize()*4,K.componentType=CD1,K.normalized=!1,K.array=J.encodeFilterExp(G,Z.getCount(),K.byteStride,Q);break;case F8.OCTAHEDRAL:K.byteStride=Q>8?8:4,K.componentType=Q>8?Lr:DD1,K.normalized=!0,G=Z.getElementSize()===3?ID1(G):G,K.array=J.encodeFilterOct(G,Z.getCount(),K.byteStride,Q);break;case F8.QUATERNION:K.byteStride=8,K.componentType=Lr,K.normalized=!0,K.array=J.encodeFilterQuat(G,Z.getCount(),K.byteStride,Q);break;default:throw new Error("Invalid filter.")}if(K.min=Z.getMin([]),K.max=Z.getMax([]),Z.getNormalized())K.min=K.min.map((W)=>eT(W,Z.getComponentType())),K.max=K.max.map((W)=>eT(W,Z.getComponentType()));if(K.normalized)K.min=K.min.map((W)=>Br(W,K.componentType)),K.max=K.max.map((W)=>Br(W,K.componentType))}else if(K.byteStride%4)K.array=kD1(K.array,Z.getElementSize()),K.byteStride=K.array.byteLength/Z.getCount();return K}function ED1(Z){let J=Z.getComponentType(),X=Z.getArray(),Y=new Float32Array(X.length);for(let $=0;$<X.length;$++)Y[$]=eT(X[$],J);return Y}function kD1(Z,J){let Y=v6.padNumber(Z.BYTES_PER_ELEMENT*J)/Z.BYTES_PER_ELEMENT,$=Z.length/J,Q=new Z.constructor($*Y);for(let K=0;K*J<Z.length;K++)for(let G=0;G<J;G++)Q[K*Y+G]=Z[K*J+G];return Q}function ID1(Z){let J=new Float32Array(Z.length*4/3);for(let X=0,Y=Z.length/3;X<Y;X++)J[X*4]=Z[X*3],J[X*4+1]=Z[X*3+1],J[X*4+2]=Z[X*3+2];return J}function _D1(Z,J){if(J===ZX.BufferViewUsage.ELEMENT_ARRAY_BUFFER)return Z.listParents().some((Y)=>{return Y instanceof eJ&&Y.getMode()===eJ.Mode.TRIANGLES})?WG.TRIANGLES:WG.INDICES;return WG.ATTRIBUTES}function SD1(Z,J){let X=J.getGraph().listParentEdges(Z).filter((Y)=>!(Y.getParent()instanceof S2));for(let Y of X){let $=Y.getName(),Q=Y.getAttributes().key||"",K=Y.getParent().propertyType===s.PRIMITIVE_TARGET;if($==="indices")return{filter:F8.NONE};if($==="attributes"){if(Q==="POSITION")return{filter:F8.NONE};if(Q==="TEXCOORD_0")return{filter:F8.NONE};if(Q.startsWith("JOINTS_"))return{filter:F8.NONE};if(Q.startsWith("WEIGHTS_"))return{filter:F8.NONE};if(Q==="NORMAL"||Q==="TANGENT")return K?{filter:F8.NONE}:{filter:F8.OCTAHEDRAL,bits:8}}if($==="output"){let G=Ir(Z);if(G==="rotation")return{filter:F8.QUATERNION,bits:16};if(G==="translation")return{filter:F8.EXPONENTIAL,bits:12};if(G==="scale")return{filter:F8.EXPONENTIAL,bits:12};return{filter:F8.NONE}}if($==="input")return{filter:F8.NONE};if($==="inverseBindMatrices")return{filter:F8.NONE}}return{filter:F8.NONE}}function Ir(Z){for(let J of Z.listParents()){if(!(J instanceof QG))continue;for(let X of J.listParents()){if(!(X instanceof eH))continue;return X.getTargetPath()}}return null}function vD1(Z){if(!Z.extensions||!Z.extensions[rT])return!1;return!!Z.extensions[rT].fallback}var X5=rT,wr={method:QV.QUANTIZE};class GV extends I1{constructor(...Z){super(...Z);this.extensionName=X5,this.prereadTypes=[s.BUFFER,s.PRIMITIVE],this.prewriteTypes=[s.BUFFER,s.ACCESSOR],this.readDependencies=["meshopt.decoder"],this.writeDependencies=["meshopt.encoder"],this._decoder=null,this._decoderFallbackBufferMap=new Map,this._encoder=null,this._encoderOptions=wr,this._encoderFallbackBuffer=null,this._encoderBufferViews={},this._encoderBufferViewData={},this._encoderBufferViewAccessors={}}install(Z,J){if(Z==="meshopt.decoder")this._decoder=J;if(Z==="meshopt.encoder")this._encoder=J;return this}setEncoderOptions(Z){return this._encoderOptions=AZ({},wr,Z),this}preread(Z,J){if(!this._decoder){if(!this.isRequired())return this;throw new Error(`[${X5}] Please install extension dependency, "meshopt.decoder".`)}if(!this._decoder.supported){if(!this.isRequired())return this;throw new Error(`[${X5}]: Missing WASM support.`)}if(J===s.BUFFER)this._prereadBuffers(Z);else if(J===s.PRIMITIVE)this._prereadPrimitives(Z);return this}_prereadBuffers(Z){let J=Z.jsonDoc;(J.json.bufferViews||[]).forEach((Y,$)=>{if(!Y.extensions||!Y.extensions[X5])return;let Q=Y.extensions[X5],K=Q.byteOffset||0,G=Q.byteLength||0,W=Q.count,H=Q.byteStride,V=new Uint8Array(W*H),F=J.json.buffers[Q.buffer],z=F.uri?J.resources[F.uri]:J.resources[uT],q=v6.toView(z,K,G);this._decoder.decodeGltfBuffer(V,W,H,q,Q.mode,Q.filter),Z.bufferViews[$]=V})}_prereadPrimitives(Z){let J=Z.jsonDoc;(J.json.bufferViews||[]).forEach((Y)=>{if(!Y.extensions||!Y.extensions[X5])return;let $=Y.extensions[X5],Q=Z.buffers[$.buffer],K=Z.buffers[Y.buffer],G=J.json.buffers[Y.buffer];if(vD1(G))this._decoderFallbackBufferMap.set(K,Q)})}read(Z){if(!this.isRequired())return this;for(let[J,X]of this._decoderFallbackBufferMap){for(let Y of J.listParents())if(Y instanceof T0)Y.swap(J,X);J.dispose()}return this}prewrite(Z,J){if(J===s.ACCESSOR)this._prewriteAccessors(Z);else if(J===s.BUFFER)this._prewriteBuffers(Z);return this}_prewriteAccessors(Z){let J=Z.jsonDoc.json,X=this._encoder,Y=this._encoderOptions,$=this.document.getGraph(),Q=this.document.createBuffer(),K=this.document.getRoot().listBuffers().indexOf(Q),G=1,W=new Map,H=(V)=>{for(let F of $.listParents(V)){if(F.propertyType===s.ROOT)continue;let z=W.get(V);if(z===void 0)W.set(V,z=G++);return z}return-1};this._encoderFallbackBuffer=Q,this._encoderBufferViews={},this._encoderBufferViewData={},this._encoderBufferViewAccessors={};for(let V of this.document.getRoot().listAccessors()){if(Ir(V)==="weights")continue;if(V.getSparse())continue;let F=Z.getAccessorUsage(V),z=Z.accessorUsageGroupedByParent.has(F)?H(V):null,q=_D1(V,F),U=Y.method===QV.FILTER?SD1(V,this.document):{filter:F8.NONE},B=TD1(V,X,q,U),{array:L,byteStride:w}=B,O=V.getBuffer();if(!O)throw new Error(`${X5}: Missing buffer for accessor.`);let M=this.document.getRoot().listBuffers().indexOf(O),R=[F,z,q,U.filter,w,M].join(":"),D=this._encoderBufferViews[R],N=this._encoderBufferViewData[R],C=this._encoderBufferViewAccessors[R];if(!D||!N)C=this._encoderBufferViewAccessors[R]=[],N=this._encoderBufferViewData[R]=[],D=this._encoderBufferViews[R]={buffer:K,target:ZX.USAGE_TO_TARGET[F],byteOffset:0,byteLength:0,byteStride:F===ZX.BufferViewUsage.ARRAY_BUFFER?w:void 0,extensions:{[X5]:{buffer:M,byteOffset:0,byteLength:0,mode:q,filter:U.filter!==F8.NONE?U.filter:void 0,byteStride:w,count:0}}};let T=Z.createAccessorDef(V);if(T.componentType=B.componentType,T.normalized=B.normalized,T.byteOffset=D.byteLength,T.min&&B.min)T.min=B.min;if(T.max&&B.max)T.max=B.max;Z.accessorIndexMap.set(V,J.accessors.length),J.accessors.push(T),C.push(T),N.push(new Uint8Array(L.buffer,L.byteOffset,L.byteLength)),D.byteLength+=L.byteLength,D.extensions.EXT_meshopt_compression.count+=V.getCount()}}_prewriteBuffers(Z){let J=this._encoder;for(let X in this._encoderBufferViews){let Y=this._encoderBufferViews[X],$=this._encoderBufferViewData[X],Q=this.document.getRoot().listBuffers()[Y.extensions[X5].buffer],K=Z.otherBufferViews.get(Q)||[],{count:G,byteStride:W,mode:H}=Y.extensions[X5],V=v6.concat($),F=J.encodeGltfBuffer(V,G,W,H),z=v6.pad(F);Y.extensions[X5].byteLength=F.byteLength,$.length=0,$.push(z),K.push(z),Z.otherBufferViews.set(Q,K)}}write(Z){let J=0;for(let Q in this._encoderBufferViews){let K=this._encoderBufferViews[Q],G=this._encoderBufferViewData[Q][0],W=Z.otherBufferViewsIndexMap.get(G),H=this._encoderBufferViewAccessors[Q];for(let q of H)q.bufferView=W;let V=Z.jsonDoc.json.bufferViews[W],F=V.byteOffset||0;Object.assign(V,K),V.byteOffset=J;let z=V.extensions[X5];z.byteOffset=F,J+=v6.padNumber(K.byteLength)}let X=this._encoderFallbackBuffer,Y=Z.bufferIndexMap.get(X),$=Z.jsonDoc.json.buffers[Y];return $.byteLength=J,$.extensions={[X5]:{fallback:!0}},X.dispose(),this}}GV.EXTENSION_NAME=X5;GV.EncoderMethod=QV;var XV=RD1;class _r{match(Z){return Z.length>=12&&v6.decodeText(Z.slice(4,12))==="ftypavif"}getSize(Z){if(!this.match(Z))return null;let J=new DataView(Z.buffer,Z.byteOffset,Z.byteLength),X=jr(J,0);if(!X)return null;let Y=X.end;while(X=jr(J,Y))if(X.type==="meta")Y=X.start+4;else if(X.type==="iprp"||X.type==="ipco")Y=X.start;else if(X.type==="ispe")return[J.getUint32(X.start+4),J.getUint32(X.start+8)];else if(X.type==="mdat")break;else Y=X.end;return null}getChannels(Z){return 4}}class y2 extends I1{constructor(...Z){super(...Z);this.extensionName=XV,this.prereadTypes=[s.TEXTURE]}static register(){h4.registerFormat("image/avif",new _r)}preread(Z){return(Z.jsonDoc.json.textures||[]).forEach((X)=>{if(X.extensions&&X.extensions[XV])X.source=X.extensions[XV].source}),this}read(Z){return this}write(Z){let J=Z.jsonDoc;return this.document.getRoot().listTextures().forEach((X)=>{if(X.getMimeType()==="image/avif"){let Y=Z.imageIndexMap.get(X);(J.json.textures||[]).forEach((Q)=>{if(Q.source===Y)Q.extensions=Q.extensions||{},Q.extensions[XV]={source:Q.source},delete Q.source})}}),this}}y2.EXTENSION_NAME=XV;function jr(Z,J){if(Z.byteLength<4+J)return null;let X=Z.getUint32(J);if(Z.byteLength<X+J||X<8)return null;return{type:v6.decodeText(new Uint8Array(Z.buffer,Z.byteOffset+J+4,4)),start:J+8,end:J+X}}var YV=MD1;class Sr{match(Z){return Z.length>=12&&Z[8]===87&&Z[9]===69&&Z[10]===66&&Z[11]===80}getSize(Z){let J=v6.decodeText(Z.slice(0,4)),X=v6.decodeText(Z.slice(8,12));if(J!=="RIFF"||X!=="WEBP")return null;let Y=new DataView(Z.buffer,Z.byteOffset),$=12;while($<Y.byteLength){let Q=v6.decodeText(new Uint8Array([Y.getUint8($),Y.getUint8($+1),Y.getUint8($+2),Y.getUint8($+3)])),K=Y.getUint32($+4,!0);if(Q==="VP8 "){let G=Y.getInt16($+14,!0)&16383,W=Y.getInt16($+16,!0)&16383;return[G,W]}else if(Q==="VP8L"){let G=Y.getUint8($+9),W=Y.getUint8($+10),H=Y.getUint8($+11),V=Y.getUint8($+12),F=1+((W&63)<<8|G),z=1+((V&15)<<10|H<<2|(W&192)>>6);return[F,z]}$+=8+K+K%2}return null}getChannels(Z){return 4}}class b2 extends I1{constructor(...Z){super(...Z);this.extensionName=YV,this.prereadTypes=[s.TEXTURE]}static register(){h4.registerFormat("image/webp",new Sr)}preread(Z){return(Z.jsonDoc.json.textures||[]).forEach((X)=>{if(X.extensions&&X.extensions[YV])X.source=X.extensions[YV].source}),this}read(Z){return this}write(Z){let J=Z.jsonDoc;return this.document.getRoot().listTextures().forEach((X)=>{if(X.getMimeType()==="image/webp"){let Y=Z.imageIndexMap.get(X);(J.json.textures||[]).forEach((Q)=>{if(Q.source===Y)Q.extensions=Q.extensions||{},Q.extensions[YV]={source:Q.source},delete Q.source})}}),this}}b2.EXTENSION_NAME=YV;var Or=kr,l8,vr,Ar;function AD1(Z,J){let X=new l8.DecoderBuffer;try{if(X.Init(J,J.length),Z.GetEncodedGeometryType(X)!==l8.TRIANGULAR_MESH)throw new Error(`[${Or}] Unknown geometry type.`);let $=new l8.Mesh;if(!Z.DecodeBufferToMesh(X,$).ok()||$.ptr===0)throw new Error(`[${Or}] Decoding failure.`);return $}finally{l8.destroy(X)}}function xD1(Z,J){let Y=J.num_faces()*3,$,Q;if(J.num_points()<=65534){let K=Y*Uint16Array.BYTES_PER_ELEMENT;$=l8._malloc(K),Z.GetTrianglesUInt16Array(J,K,$),Q=new Uint16Array(l8.HEAPU16.buffer,$,Y).slice()}else{let K=Y*Uint32Array.BYTES_PER_ELEMENT;$=l8._malloc(K),Z.GetTrianglesUInt32Array(J,K,$),Q=new Uint32Array(l8.HEAPU32.buffer,$,Y).slice()}return l8._free($),Q}function hD1(Z,J,X,Y){let $=Ar[Y.componentType],Q=vr[Y.componentType],K=X.num_components(),W=J.num_points()*K,H=W*Q.BYTES_PER_ELEMENT,V=l8._malloc(H);Z.GetAttributeDataArrayForAllPoints(J,X,$,H,V);let F=new Q(l8.HEAPF32.buffer,V,W).slice();return l8._free(V),F}function fD1(Z){l8=Z,vr={[T0.ComponentType.FLOAT]:Float32Array,[T0.ComponentType.UNSIGNED_INT]:Uint32Array,[T0.ComponentType.UNSIGNED_SHORT]:Uint16Array,[T0.ComponentType.UNSIGNED_BYTE]:Uint8Array,[T0.ComponentType.SHORT]:Int16Array,[T0.ComponentType.BYTE]:Int8Array},Ar={[T0.ComponentType.FLOAT]:l8.DT_FLOAT32,[T0.ComponentType.UNSIGNED_INT]:l8.DT_UINT32,[T0.ComponentType.UNSIGNED_SHORT]:l8.DT_UINT16,[T0.ComponentType.UNSIGNED_BYTE]:l8.DT_UINT8,[T0.ComponentType.SHORT]:l8.DT_INT16,[T0.ComponentType.BYTE]:l8.DT_INT8}}var b9,KV;(function(Z){Z[Z.EDGEBREAKER=1]="EDGEBREAKER",Z[Z.SEQUENTIAL=0]="SEQUENTIAL"})(KV||(KV={}));var g9;(function(Z){Z.POSITION="POSITION",Z.NORMAL="NORMAL",Z.COLOR="COLOR",Z.TEX_COORD="TEX_COORD",Z.GENERIC="GENERIC"})(g9||(g9={}));var xr={[g9.POSITION]:14,[g9.NORMAL]:10,[g9.COLOR]:8,[g9.TEX_COORD]:12,[g9.GENERIC]:12},Mr={decodeSpeed:5,encodeSpeed:5,method:KV.EDGEBREAKER,quantizationBits:xr,quantizationVolume:"mesh"};function yD1(Z){b9=Z}function bD1(Z,J=Mr){let X=AZ({},Mr,J);X.quantizationBits=AZ({},xr,J.quantizationBits);let Y=new b9.MeshBuilder,$=new b9.Mesh,Q=new b9.ExpertEncoder($),K={},G=new b9.DracoInt8Array,W=Z.listTargets().length>0,H=!1;for(let B of Z.listSemantics()){let L=Z.getAttribute(B);if(L.getSparse()){H=!0;continue}let w=gD1(B),O=mD1(Y,L.getComponentType(),$,b9[w],L.getCount(),L.getElementSize(),L.getArray());if(O===-1)throw new Error(`Error compressing "${B}" attribute.`);if(K[B]=O,X.quantizationVolume==="mesh"||B!=="POSITION")Q.SetAttributeQuantization(O,X.quantizationBits[w]);else if(typeof X.quantizationVolume==="object"){let{quantizationVolume:M}=X,R=Math.max(M.max[0]-M.min[0],M.max[1]-M.min[1],M.max[2]-M.min[2]);Q.SetAttributeExplicitQuantization(O,X.quantizationBits[w],L.getElementSize(),M.min,R)}else throw new Error("Invalid quantization volume state.")}let V=Z.getIndices();if(!V)throw new x2("Primitive must have indices.");if(Y.AddFacesToMesh($,V.getCount()/3,V.getArray()),Q.SetSpeedOptions(X.encodeSpeed,X.decodeSpeed),Q.SetTrackEncodedProperties(!0),X.method===KV.SEQUENTIAL||W||H)Q.SetEncodingMethod(b9.MESH_SEQUENTIAL_ENCODING);else Q.SetEncodingMethod(b9.MESH_EDGEBREAKER_ENCODING);let F=Q.EncodeToDracoBuffer(!(W||H),G);if(F<=0)throw new x2("Error applying Draco compression.");let z=new Uint8Array(F);for(let B=0;B<F;++B)z[B]=G.GetValue(B);let q=Q.GetNumberOfEncodedPoints(),U=Q.GetNumberOfEncodedFaces()*3;return b9.destroy(G),b9.destroy($),b9.destroy(Y),b9.destroy(Q),{numVertices:q,numIndices:U,data:z,attributeIDs:K}}function gD1(Z){if(Z==="POSITION")return g9.POSITION;else if(Z==="NORMAL")return g9.NORMAL;else if(Z.startsWith("COLOR_"))return g9.COLOR;else if(Z.startsWith("TEXCOORD_"))return g9.TEX_COORD;return g9.GENERIC}function mD1(Z,J,X,Y,$,Q,K){switch(J){case T0.ComponentType.UNSIGNED_BYTE:return Z.AddUInt8Attribute(X,Y,$,Q,K);case T0.ComponentType.BYTE:return Z.AddInt8Attribute(X,Y,$,Q,K);case T0.ComponentType.UNSIGNED_SHORT:return Z.AddUInt16Attribute(X,Y,$,Q,K);case T0.ComponentType.SHORT:return Z.AddInt16Attribute(X,Y,$,Q,K);case T0.ComponentType.UNSIGNED_INT:return Z.AddUInt32Attribute(X,Y,$,Q,K);case T0.ComponentType.FLOAT:return Z.AddFloatAttribute(X,Y,$,Q,K);default:throw new Error(`Unexpected component type, "${J}".`)}}class x2 extends Error{}var E8=kr;class WV extends I1{constructor(...Z){super(...Z);this.extensionName=E8,this.prereadTypes=[s.PRIMITIVE],this.prewriteTypes=[s.ACCESSOR],this.readDependencies=["draco3d.decoder"],this.writeDependencies=["draco3d.encoder"],this._decoderModule=null,this._encoderModule=null,this._encoderOptions={}}install(Z,J){if(Z==="draco3d.decoder")this._decoderModule=J,fD1(this._decoderModule);if(Z==="draco3d.encoder")this._encoderModule=J,yD1(this._encoderModule);return this}setEncoderOptions(Z){return this._encoderOptions=Z,this}preread(Z){if(!this._decoderModule)throw new Error(`[${E8}] Please install extension dependency, "draco3d.decoder".`);let J=this.document.getLogger(),X=Z.jsonDoc,Y=new Map;try{let $=X.json.meshes||[];for(let Q of $)for(let K of Q.primitives){if(!K.extensions||!K.extensions[E8])continue;let G=K.extensions[E8],[W,H]=Y.get(G.bufferView)||[];if(!H||!W){let V=X.json.bufferViews[G.bufferView],F=X.json.buffers[V.buffer],z=F.uri?X.resources[F.uri]:X.resources[uT],q=V.byteOffset||0,U=V.byteLength,B=v6.toView(z,q,U);W=new this._decoderModule.Decoder,H=AD1(W,B),Y.set(G.bufferView,[W,H]),J.debug(`[${E8}] Decompressed ${B.byteLength} bytes.`)}for(let V in G.attributes){let F=Z.jsonDoc.json.accessors[K.attributes[V]],z=W.GetAttributeByUniqueId(H,G.attributes[V]),q=hD1(W,H,z,F);Z.accessors[K.attributes[V]].setArray(q)}if(K.indices!==void 0)Z.accessors[K.indices].setArray(xD1(W,H))}}finally{for(let[$,Q]of Array.from(Y.values()))this._decoderModule.destroy($),this._decoderModule.destroy(Q)}return this}read(Z){return this}prewrite(Z,J){if(!this._encoderModule)throw new Error(`[${E8}] Please install extension dependency, "draco3d.encoder".`);let X=this.document.getLogger();X.debug(`[${E8}] Compression options: ${JSON.stringify(this._encoderOptions)}`);let Y=uD1(this.document),$=new Map,Q="mesh";if(this._encoderOptions.quantizationVolume==="scene")if(this.document.getRoot().listScenes().length!==1)X.warn(`[${E8}]: quantizationVolume=scene requires exactly 1 scene.`);else Q=Kr(this.document.getRoot().listScenes().pop());for(let K of Array.from(Y.keys())){let G=Y.get(K);if(!G)throw new Error("Unexpected primitive.");if($.has(G)){$.set(G,$.get(G));continue}let W=K.getIndices(),H=Z.jsonDoc.json.accessors,V;try{V=bD1(K,AZ({},this._encoderOptions,{quantizationVolume:Q}))}catch(q){if(q instanceof x2){X.warn(`[${E8}]: ${q.message} Skipping primitive compression.`);continue}throw q}$.set(G,V);let F=Z.createAccessorDef(W);if(F.count=V.numIndices,Z.accessorIndexMap.set(W,H.length),H.push(F),V.numVertices>65534&&T0.getComponentSize(F.componentType)<=2)F.componentType=T0.ComponentType.UNSIGNED_INT;else if(V.numVertices>254&&T0.getComponentSize(F.componentType)<=1)F.componentType=T0.ComponentType.UNSIGNED_SHORT;for(let q of K.listSemantics()){let U=K.getAttribute(q);if(V.attributeIDs[q]===void 0)continue;let B=Z.createAccessorDef(U);B.count=V.numVertices,Z.accessorIndexMap.set(U,H.length),H.push(B)}let z=K.getAttribute("POSITION").getBuffer()||this.document.getRoot().listBuffers()[0];if(!Z.otherBufferViews.has(z))Z.otherBufferViews.set(z,[]);Z.otherBufferViews.get(z).push(V.data)}return X.debug(`[${E8}] Compressed ${Y.size} primitives.`),Z.extensionData[E8]={primitiveHashMap:Y,primitiveEncodingMap:$},this}write(Z){let J=Z.extensionData[E8];for(let X of this.document.getRoot().listMeshes()){let Y=Z.jsonDoc.json.meshes[Z.meshIndexMap.get(X)];for(let $=0;$<X.listPrimitives().length;$++){let Q=X.listPrimitives()[$],K=Y.primitives[$],G=J.primitiveHashMap.get(Q);if(!G)continue;let W=J.primitiveEncodingMap.get(G);if(!W)continue;K.extensions=K.extensions||{},K.extensions[E8]={bufferView:Z.otherBufferViewsIndexMap.get(W.data),attributes:W.attributeIDs}}}if(!J.primitiveHashMap.size){let X=Z.jsonDoc.json;X.extensionsUsed=(X.extensionsUsed||[]).filter((Y)=>Y!==E8),X.extensionsRequired=(X.extensionsRequired||[]).filter((Y)=>Y!==E8)}return this}}WV.EXTENSION_NAME=E8;WV.EncoderMethod=KV;function uD1(Z){let J=Z.getLogger(),X=new Set,Y=new Set,$=0,Q=0;for(let F of Z.getRoot().listMeshes())for(let z of F.listPrimitives())if(!z.getIndices())Y.add(z),$++;else if(z.getMode()!==eJ.Mode.TRIANGLES)Y.add(z),Q++;else X.add(z);if($>0)J.warn(`[${E8}] Skipping Draco compression of ${$} non-indexed primitives.`);if(Q>0)J.warn(`[${E8}] Skipping Draco compression of ${Q} non-TRIANGLES primitives.`);let K=Z.getRoot().listAccessors(),G=new Map;for(let F=0;F<K.length;F++)G.set(K[F],F);let W=new Map,H=new Set,V=new Map;for(let F of Array.from(X)){let z=Rr(F,G);if(H.has(z)){V.set(F,z);continue}if(W.has(F.getIndices())){let q=F.getIndices(),U=q.clone();G.set(U,Z.getRoot().listAccessors().length-1),F.swap(q,U)}for(let q of F.listAttributes())if(W.has(q)){let U=q.clone();G.set(U,Z.getRoot().listAccessors().length-1),F.swap(q,U)}z=Rr(F,G),H.add(z),V.set(F,z),W.set(F.getIndices(),z);for(let q of F.listAttributes())W.set(q,z)}for(let F of Array.from(W.keys())){let z=new Set(F.listParents().map((q)=>q.propertyType));if(z.size!==2||!z.has(s.PRIMITIVE)||!z.has(s.ROOT))throw new Error(`[${E8}] Compressed accessors must only be used as indices or vertex attributes.`)}for(let F of Array.from(X)){let z=V.get(F),q=F.getIndices();if(W.get(q)!==z||F.listAttributes().some((U)=>W.get(U)!==z))throw new Error(`[${E8}] Draco primitives must share all, or no, accessors.`)}for(let F of Array.from(Y)){let z=F.getIndices();if(W.has(z)||F.listAttributes().some((q)=>W.has(q)))throw new Error(`[${E8}] Accessor cannot be shared by compressed and uncompressed primitives.`)}return V}function Rr(Z,J){let X=[],Y=Z.getIndices();X.push(J.get(Y));for(let $ of Z.listAttributes())X.push(J.get($));return X.sort().join("|")}class HG extends s1{init(){this.extensionName=JE,this.propertyType="Light",this.parentTypes=[s.NODE]}getDefaults(){return Object.assign(super.getDefaults(),{color:[1,1,1],intensity:1,type:HG.Type.POINT,range:null,innerConeAngle:0,outerConeAngle:Math.PI/4})}getColor(){return this.get("color")}setColor(Z){return this.set("color",Z)}getIntensity(){return this.get("intensity")}setIntensity(Z){return this.set("intensity",Z)}getType(){return this.get("type")}setType(Z){return this.set("type",Z)}getRange(){return this.get("range")}setRange(Z){return this.set("range",Z)}getInnerConeAngle(){return this.get("innerConeAngle")}setInnerConeAngle(Z){return this.set("innerConeAngle",Z)}getOuterConeAngle(){return this.get("outerConeAngle")}setOuterConeAngle(Z){return this.set("outerConeAngle",Z)}}HG.EXTENSION_NAME=JE;HG.Type={POINT:"point",SPOT:"spot",DIRECTIONAL:"directional"};var S7=JE;class wE extends I1{constructor(...Z){super(...Z);this.extensionName=S7}createLight(Z=""){return new HG(this.document.getGraph(),Z)}read(Z){let J=Z.jsonDoc;if(!J.json.extensions||!J.json.extensions[S7])return this;let $=(J.json.extensions[S7].lights||[]).map((Q)=>{var K,G;let W=this.createLight().setName(Q.name||"").setType(Q.type);if(Q.color!==void 0)W.setColor(Q.color);if(Q.intensity!==void 0)W.setIntensity(Q.intensity);if(Q.range!==void 0)W.setRange(Q.range);if(((K=Q.spot)==null?void 0:K.innerConeAngle)!==void 0)W.setInnerConeAngle(Q.spot.innerConeAngle);if(((G=Q.spot)==null?void 0:G.outerConeAngle)!==void 0)W.setOuterConeAngle(Q.spot.outerConeAngle);return W});return J.json.nodes.forEach((Q,K)=>{if(!Q.extensions||!Q.extensions[S7])return;let G=Q.extensions[S7];Z.nodes[K].setExtension(S7,$[G.light])}),this}write(Z){let J=Z.jsonDoc;if(this.properties.size===0)return this;let X=[],Y=new Map;for(let $ of this.properties){let Q=$,K={type:Q.getType()};if(!z8.eq(Q.getColor(),[1,1,1]))K.color=Q.getColor();if(Q.getIntensity()!==1)K.intensity=Q.getIntensity();if(Q.getRange()!=null)K.range=Q.getRange();if(Q.getName())K.name=Q.getName();if(Q.getType()===HG.Type.SPOT)K.spot={innerConeAngle:Q.getInnerConeAngle(),outerConeAngle:Q.getOuterConeAngle()};X.push(K),Y.set(Q,X.length-1)}return this.document.getRoot().listNodes().forEach(($)=>{let Q=$.getExtension(S7);if(Q){let K=Z.nodeIndexMap.get($),G=J.json.nodes[K];G.extensions=G.extensions||{},G.extensions[S7]={light:Y.get(Q)}}}),J.json.extensions=J.json.extensions||{},J.json.extensions[S7]={lights:X},this}}wE.EXTENSION_NAME=S7;var{R:dD1,G:cD1,B:lD1}=Y9;class jE extends s1{init(){this.extensionName=XE,this.propertyType="Anisotropy",this.parentTypes=[s.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{anisotropyStrength:0,anisotropyRotation:0,anisotropyTexture:null,anisotropyTextureInfo:new T1(this.graph,"anisotropyTextureInfo")})}getAnisotropyStrength(){return this.get("anisotropyStrength")}setAnisotropyStrength(Z){return this.set("anisotropyStrength",Z)}getAnisotropyRotation(){return this.get("anisotropyRotation")}setAnisotropyRotation(Z){return this.set("anisotropyRotation",Z)}getAnisotropyTexture(){return this.getRef("anisotropyTexture")}getAnisotropyTextureInfo(){return this.getRef("anisotropyTexture")?this.getRef("anisotropyTextureInfo"):null}setAnisotropyTexture(Z){return this.setRef("anisotropyTexture",Z,{channels:dD1|cD1|lD1})}}jE.EXTENSION_NAME=XE;var $$=XE;class OE extends I1{constructor(...Z){super(...Z);this.extensionName=$$,this.prereadTypes=[s.MESH],this.prewriteTypes=[s.MESH]}createAnisotropy(){return new jE(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],Y=J.json.textures||[];return X.forEach(($,Q)=>{if($.extensions&&$.extensions[$$]){let K=this.createAnisotropy();Z.materials[Q].setExtension($$,K);let G=$.extensions[$$];if(G.anisotropyStrength!==void 0)K.setAnisotropyStrength(G.anisotropyStrength);if(G.anisotropyRotation!==void 0)K.setAnisotropyRotation(G.anisotropyRotation);if(G.anisotropyTexture!==void 0){let W=G.anisotropyTexture,H=Z.textures[Y[W.index].source];K.setAnisotropyTexture(H),Z.setTextureInfo(K.getAnisotropyTextureInfo(),W)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let Y=X.getExtension($$);if(Y){let $=Z.materialIndexMap.get(X),Q=J.json.materials[$];Q.extensions=Q.extensions||{};let K=Q.extensions[$$]={};if(Y.getAnisotropyStrength()>0)K.anisotropyStrength=Y.getAnisotropyStrength();if(Y.getAnisotropyRotation()!==0)K.anisotropyRotation=Y.getAnisotropyRotation();if(Y.getAnisotropyTexture()){let G=Y.getAnisotropyTexture(),W=Y.getAnisotropyTextureInfo();K.anisotropyTexture=Z.createTextureInfoDef(G,W)}}}),this}}OE.EXTENSION_NAME=$$;var{R:Nr,G:Pr,B:pD1}=Y9;class ME extends s1{init(){this.extensionName=YE,this.propertyType="Clearcoat",this.parentTypes=[s.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{clearcoatFactor:0,clearcoatTexture:null,clearcoatTextureInfo:new T1(this.graph,"clearcoatTextureInfo"),clearcoatRoughnessFactor:0,clearcoatRoughnessTexture:null,clearcoatRoughnessTextureInfo:new T1(this.graph,"clearcoatRoughnessTextureInfo"),clearcoatNormalScale:1,clearcoatNormalTexture:null,clearcoatNormalTextureInfo:new T1(this.graph,"clearcoatNormalTextureInfo")})}getClearcoatFactor(){return this.get("clearcoatFactor")}setClearcoatFactor(Z){return this.set("clearcoatFactor",Z)}getClearcoatTexture(){return this.getRef("clearcoatTexture")}getClearcoatTextureInfo(){return this.getRef("clearcoatTexture")?this.getRef("clearcoatTextureInfo"):null}setClearcoatTexture(Z){return this.setRef("clearcoatTexture",Z,{channels:Nr})}getClearcoatRoughnessFactor(){return this.get("clearcoatRoughnessFactor")}setClearcoatRoughnessFactor(Z){return this.set("clearcoatRoughnessFactor",Z)}getClearcoatRoughnessTexture(){return this.getRef("clearcoatRoughnessTexture")}getClearcoatRoughnessTextureInfo(){return this.getRef("clearcoatRoughnessTexture")?this.getRef("clearcoatRoughnessTextureInfo"):null}setClearcoatRoughnessTexture(Z){return this.setRef("clearcoatRoughnessTexture",Z,{channels:Pr})}getClearcoatNormalScale(){return this.get("clearcoatNormalScale")}setClearcoatNormalScale(Z){return this.set("clearcoatNormalScale",Z)}getClearcoatNormalTexture(){return this.getRef("clearcoatNormalTexture")}getClearcoatNormalTextureInfo(){return this.getRef("clearcoatNormalTexture")?this.getRef("clearcoatNormalTextureInfo"):null}setClearcoatNormalTexture(Z){return this.setRef("clearcoatNormalTexture",Z,{channels:Nr|Pr|pD1})}}ME.EXTENSION_NAME=YE;var Q$=YE;class RE extends I1{constructor(...Z){super(...Z);this.extensionName=Q$,this.prereadTypes=[s.MESH],this.prewriteTypes=[s.MESH]}createClearcoat(){return new ME(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],Y=J.json.textures||[];return X.forEach(($,Q)=>{if($.extensions&&$.extensions[Q$]){let K=this.createClearcoat();Z.materials[Q].setExtension(Q$,K);let G=$.extensions[Q$];if(G.clearcoatFactor!==void 0)K.setClearcoatFactor(G.clearcoatFactor);if(G.clearcoatRoughnessFactor!==void 0)K.setClearcoatRoughnessFactor(G.clearcoatRoughnessFactor);if(G.clearcoatTexture!==void 0){let W=G.clearcoatTexture,H=Z.textures[Y[W.index].source];K.setClearcoatTexture(H),Z.setTextureInfo(K.getClearcoatTextureInfo(),W)}if(G.clearcoatRoughnessTexture!==void 0){let W=G.clearcoatRoughnessTexture,H=Z.textures[Y[W.index].source];K.setClearcoatRoughnessTexture(H),Z.setTextureInfo(K.getClearcoatRoughnessTextureInfo(),W)}if(G.clearcoatNormalTexture!==void 0){let W=G.clearcoatNormalTexture,H=Z.textures[Y[W.index].source];if(K.setClearcoatNormalTexture(H),Z.setTextureInfo(K.getClearcoatNormalTextureInfo(),W),W.scale!==void 0)K.setClearcoatNormalScale(W.scale)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let Y=X.getExtension(Q$);if(Y){let $=Z.materialIndexMap.get(X),Q=J.json.materials[$];Q.extensions=Q.extensions||{};let K=Q.extensions[Q$]={clearcoatFactor:Y.getClearcoatFactor(),clearcoatRoughnessFactor:Y.getClearcoatRoughnessFactor()};if(Y.getClearcoatTexture()){let G=Y.getClearcoatTexture(),W=Y.getClearcoatTextureInfo();K.clearcoatTexture=Z.createTextureInfoDef(G,W)}if(Y.getClearcoatRoughnessTexture()){let G=Y.getClearcoatRoughnessTexture(),W=Y.getClearcoatRoughnessTextureInfo();K.clearcoatRoughnessTexture=Z.createTextureInfoDef(G,W)}if(Y.getClearcoatNormalTexture()){let G=Y.getClearcoatNormalTexture(),W=Y.getClearcoatNormalTextureInfo();if(K.clearcoatNormalTexture=Z.createTextureInfoDef(G,W),Y.getClearcoatNormalScale()!==1)K.clearcoatNormalTexture.scale=Y.getClearcoatNormalScale()}}}),this}}RE.EXTENSION_NAME=Q$;var{R:iD1,G:nD1,B:aD1,A:sD1}=Y9;class NE extends s1{init(){this.extensionName=$E,this.propertyType="DiffuseTransmission",this.parentTypes=[s.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{diffuseTransmissionFactor:0,diffuseTransmissionTexture:null,diffuseTransmissionTextureInfo:new T1(this.graph,"diffuseTransmissionTextureInfo"),diffuseTransmissionColorFactor:[1,1,1],diffuseTransmissionColorTexture:null,diffuseTransmissionColorTextureInfo:new T1(this.graph,"diffuseTransmissionColorTextureInfo")})}getDiffuseTransmissionFactor(){return this.get("diffuseTransmissionFactor")}setDiffuseTransmissionFactor(Z){return this.set("diffuseTransmissionFactor",Z)}getDiffuseTransmissionTexture(){return this.getRef("diffuseTransmissionTexture")}getDiffuseTransmissionTextureInfo(){return this.getRef("diffuseTransmissionTexture")?this.getRef("diffuseTransmissionTextureInfo"):null}setDiffuseTransmissionTexture(Z){return this.setRef("diffuseTransmissionTexture",Z,{channels:sD1})}getDiffuseTransmissionColorFactor(){return this.get("diffuseTransmissionColorFactor")}setDiffuseTransmissionColorFactor(Z){return this.set("diffuseTransmissionColorFactor",Z)}getDiffuseTransmissionColorTexture(){return this.getRef("diffuseTransmissionColorTexture")}getDiffuseTransmissionColorTextureInfo(){return this.getRef("diffuseTransmissionColorTexture")?this.getRef("diffuseTransmissionColorTextureInfo"):null}setDiffuseTransmissionColorTexture(Z){return this.setRef("diffuseTransmissionColorTexture",Z,{channels:iD1|nD1|aD1})}}NE.EXTENSION_NAME=$E;var K$=$E;class PE extends I1{constructor(...Z){super(...Z);this.extensionName=K$}createDiffuseTransmission(){return new NE(this.document.getGraph())}read(Z){let J=Z.jsonDoc,X=J.json.materials||[],Y=J.json.textures||[];return X.forEach(($,Q)=>{if($.extensions&&$.extensions[K$]){let K=this.createDiffuseTransmission();Z.materials[Q].setExtension(K$,K);let G=$.extensions[K$];if(G.diffuseTransmissionFactor!==void 0)K.setDiffuseTransmissionFactor(G.diffuseTransmissionFactor);if(G.diffuseTransmissionColorFactor!==void 0)K.setDiffuseTransmissionColorFactor(G.diffuseTransmissionColorFactor);if(G.diffuseTransmissionTexture!==void 0){let W=G.diffuseTransmissionTexture,H=Z.textures[Y[W.index].source];K.setDiffuseTransmissionTexture(H),Z.setTextureInfo(K.getDiffuseTransmissionTextureInfo(),W)}if(G.diffuseTransmissionColorTexture!==void 0){let W=G.diffuseTransmissionColorTexture,H=Z.textures[Y[W.index].source];K.setDiffuseTransmissionColorTexture(H),Z.setTextureInfo(K.getDiffuseTransmissionColorTextureInfo(),W)}}}),this}write(Z){let J=Z.jsonDoc;for(let X of this.document.getRoot().listMaterials()){let Y=X.getExtension(K$);if(!Y)continue;let $=Z.materialIndexMap.get(X),Q=J.json.materials[$];Q.extensions=Q.extensions||{};let K=Q.extensions[K$]={diffuseTransmissionFactor:Y.getDiffuseTransmissionFactor(),diffuseTransmissionColorFactor:Y.getDiffuseTransmissionColorFactor()};if(Y.getDiffuseTransmissionTexture()){let G=Y.getDiffuseTransmissionTexture(),W=Y.getDiffuseTransmissionTextureInfo();K.diffuseTransmissionTexture=Z.createTextureInfoDef(G,W)}if(Y.getDiffuseTransmissionColorTexture()){let G=Y.getDiffuseTransmissionColorTexture(),W=Y.getDiffuseTransmissionColorTextureInfo();K.diffuseTransmissionColorTexture=Z.createTextureInfoDef(G,W)}}return this}}PE.EXTENSION_NAME=K$;class DE extends s1{init(){this.extensionName=QE,this.propertyType="Dispersion",this.parentTypes=[s.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{dispersion:0})}getDispersion(){return this.get("dispersion")}setDispersion(Z){return this.set("dispersion",Z)}}DE.EXTENSION_NAME=QE;var G$=QE;class CE extends I1{constructor(...Z){super(...Z);this.extensionName=G$,this.prereadTypes=[s.MESH],this.prewriteTypes=[s.MESH]}createDispersion(){return new DE(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){return(Z.jsonDoc.json.materials||[]).forEach((Y,$)=>{if(Y.extensions&&Y.extensions[G$]){let Q=this.createDispersion();Z.materials[$].setExtension(G$,Q);let K=Y.extensions[G$];if(K.dispersion!==void 0)Q.setDispersion(K.dispersion)}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let Y=X.getExtension(G$);if(Y){let $=Z.materialIndexMap.get(X),Q=J.json.materials[$];Q.extensions=Q.extensions||{},Q.extensions[G$]={dispersion:Y.getDispersion()}}}),this}}CE.EXTENSION_NAME=G$;class TE extends s1{init(){this.extensionName=KE,this.propertyType="EmissiveStrength",this.parentTypes=[s.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{emissiveStrength:1})}getEmissiveStrength(){return this.get("emissiveStrength")}setEmissiveStrength(Z){return this.set("emissiveStrength",Z)}}TE.EXTENSION_NAME=KE;var W$=KE;class EE extends I1{constructor(...Z){super(...Z);this.extensionName=W$,this.prereadTypes=[s.MESH],this.prewriteTypes=[s.MESH]}createEmissiveStrength(){return new TE(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){return(Z.jsonDoc.json.materials||[]).forEach((Y,$)=>{if(Y.extensions&&Y.extensions[W$]){let Q=this.createEmissiveStrength();Z.materials[$].setExtension(W$,Q);let K=Y.extensions[W$];if(K.emissiveStrength!==void 0)Q.setEmissiveStrength(K.emissiveStrength)}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let Y=X.getExtension(W$);if(Y){let $=Z.materialIndexMap.get(X),Q=J.json.materials[$];Q.extensions=Q.extensions||{},Q.extensions[W$]={emissiveStrength:Y.getEmissiveStrength()}}}),this}}EE.EXTENSION_NAME=W$;class kE extends s1{init(){this.extensionName=GE,this.propertyType="IOR",this.parentTypes=[s.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{ior:1.5})}getIOR(){return this.get("ior")}setIOR(Z){return this.set("ior",Z)}}kE.EXTENSION_NAME=GE;var H$=GE;class g2 extends I1{constructor(...Z){super(...Z);this.extensionName=H$,this.prereadTypes=[s.MESH],this.prewriteTypes=[s.MESH]}createIOR(){return new kE(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){return(Z.jsonDoc.json.materials||[]).forEach((Y,$)=>{if(Y.extensions&&Y.extensions[H$]){let Q=this.createIOR();Z.materials[$].setExtension(H$,Q);let K=Y.extensions[H$];if(K.ior!==void 0)Q.setIOR(K.ior)}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let Y=X.getExtension(H$);if(Y){let $=Z.materialIndexMap.get(X),Q=J.json.materials[$];Q.extensions=Q.extensions||{},Q.extensions[H$]={ior:Y.getIOR()}}}),this}}g2.EXTENSION_NAME=H$;var{R:oD1,G:rD1}=Y9;class IE extends s1{init(){this.extensionName=WE,this.propertyType="Iridescence",this.parentTypes=[s.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{iridescenceFactor:0,iridescenceTexture:null,iridescenceTextureInfo:new T1(this.graph,"iridescenceTextureInfo"),iridescenceIOR:1.3,iridescenceThicknessMinimum:100,iridescenceThicknessMaximum:400,iridescenceThicknessTexture:null,iridescenceThicknessTextureInfo:new T1(this.graph,"iridescenceThicknessTextureInfo")})}getIridescenceFactor(){return this.get("iridescenceFactor")}setIridescenceFactor(Z){return this.set("iridescenceFactor",Z)}getIridescenceTexture(){return this.getRef("iridescenceTexture")}getIridescenceTextureInfo(){return this.getRef("iridescenceTexture")?this.getRef("iridescenceTextureInfo"):null}setIridescenceTexture(Z){return this.setRef("iridescenceTexture",Z,{channels:oD1})}getIridescenceIOR(){return this.get("iridescenceIOR")}setIridescenceIOR(Z){return this.set("iridescenceIOR",Z)}getIridescenceThicknessMinimum(){return this.get("iridescenceThicknessMinimum")}setIridescenceThicknessMinimum(Z){return this.set("iridescenceThicknessMinimum",Z)}getIridescenceThicknessMaximum(){return this.get("iridescenceThicknessMaximum")}setIridescenceThicknessMaximum(Z){return this.set("iridescenceThicknessMaximum",Z)}getIridescenceThicknessTexture(){return this.getRef("iridescenceThicknessTexture")}getIridescenceThicknessTextureInfo(){return this.getRef("iridescenceThicknessTexture")?this.getRef("iridescenceThicknessTextureInfo"):null}setIridescenceThicknessTexture(Z){return this.setRef("iridescenceThicknessTexture",Z,{channels:rD1})}}IE.EXTENSION_NAME=WE;var V$=WE;class _E extends I1{constructor(...Z){super(...Z);this.extensionName=V$,this.prereadTypes=[s.MESH],this.prewriteTypes=[s.MESH]}createIridescence(){return new IE(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],Y=J.json.textures||[];return X.forEach(($,Q)=>{if($.extensions&&$.extensions[V$]){let K=this.createIridescence();Z.materials[Q].setExtension(V$,K);let G=$.extensions[V$];if(G.iridescenceFactor!==void 0)K.setIridescenceFactor(G.iridescenceFactor);if(G.iridescenceIor!==void 0)K.setIridescenceIOR(G.iridescenceIor);if(G.iridescenceThicknessMinimum!==void 0)K.setIridescenceThicknessMinimum(G.iridescenceThicknessMinimum);if(G.iridescenceThicknessMaximum!==void 0)K.setIridescenceThicknessMaximum(G.iridescenceThicknessMaximum);if(G.iridescenceTexture!==void 0){let W=G.iridescenceTexture,H=Z.textures[Y[W.index].source];K.setIridescenceTexture(H),Z.setTextureInfo(K.getIridescenceTextureInfo(),W)}if(G.iridescenceThicknessTexture!==void 0){let W=G.iridescenceThicknessTexture,H=Z.textures[Y[W.index].source];K.setIridescenceThicknessTexture(H),Z.setTextureInfo(K.getIridescenceThicknessTextureInfo(),W)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let Y=X.getExtension(V$);if(Y){let $=Z.materialIndexMap.get(X),Q=J.json.materials[$];Q.extensions=Q.extensions||{};let K=Q.extensions[V$]={};if(Y.getIridescenceFactor()>0)K.iridescenceFactor=Y.getIridescenceFactor();if(Y.getIridescenceIOR()!==1.3)K.iridescenceIor=Y.getIridescenceIOR();if(Y.getIridescenceThicknessMinimum()!==100)K.iridescenceThicknessMinimum=Y.getIridescenceThicknessMinimum();if(Y.getIridescenceThicknessMaximum()!==400)K.iridescenceThicknessMaximum=Y.getIridescenceThicknessMaximum();if(Y.getIridescenceTexture()){let G=Y.getIridescenceTexture(),W=Y.getIridescenceTextureInfo();K.iridescenceTexture=Z.createTextureInfoDef(G,W)}if(Y.getIridescenceThicknessTexture()){let G=Y.getIridescenceThicknessTexture(),W=Y.getIridescenceThicknessTextureInfo();K.iridescenceThicknessTexture=Z.createTextureInfoDef(G,W)}}}),this}}_E.EXTENSION_NAME=V$;var{R:Dr,G:Cr,B:Tr,A:Er}=Y9;class SE extends s1{init(){this.extensionName=HE,this.propertyType="PBRSpecularGlossiness",this.parentTypes=[s.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{diffuseFactor:[1,1,1,1],diffuseTexture:null,diffuseTextureInfo:new T1(this.graph,"diffuseTextureInfo"),specularFactor:[1,1,1],glossinessFactor:1,specularGlossinessTexture:null,specularGlossinessTextureInfo:new T1(this.graph,"specularGlossinessTextureInfo")})}getDiffuseFactor(){return this.get("diffuseFactor")}setDiffuseFactor(Z){return this.set("diffuseFactor",Z)}getDiffuseTexture(){return this.getRef("diffuseTexture")}getDiffuseTextureInfo(){return this.getRef("diffuseTexture")?this.getRef("diffuseTextureInfo"):null}setDiffuseTexture(Z){return this.setRef("diffuseTexture",Z,{channels:Dr|Cr|Tr|Er,isColor:!0})}getSpecularFactor(){return this.get("specularFactor")}setSpecularFactor(Z){return this.set("specularFactor",Z)}getGlossinessFactor(){return this.get("glossinessFactor")}setGlossinessFactor(Z){return this.set("glossinessFactor",Z)}getSpecularGlossinessTexture(){return this.getRef("specularGlossinessTexture")}getSpecularGlossinessTextureInfo(){return this.getRef("specularGlossinessTexture")?this.getRef("specularGlossinessTextureInfo"):null}setSpecularGlossinessTexture(Z){return this.setRef("specularGlossinessTexture",Z,{channels:Dr|Cr|Tr|Er})}}SE.EXTENSION_NAME=HE;var z$=HE;class m2 extends I1{constructor(...Z){super(...Z);this.extensionName=z$,this.prereadTypes=[s.MESH],this.prewriteTypes=[s.MESH]}createPBRSpecularGlossiness(){return new SE(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],Y=J.json.textures||[];return X.forEach(($,Q)=>{if($.extensions&&$.extensions[z$]){let K=this.createPBRSpecularGlossiness();Z.materials[Q].setExtension(z$,K);let G=$.extensions[z$];if(G.diffuseFactor!==void 0)K.setDiffuseFactor(G.diffuseFactor);if(G.specularFactor!==void 0)K.setSpecularFactor(G.specularFactor);if(G.glossinessFactor!==void 0)K.setGlossinessFactor(G.glossinessFactor);if(G.diffuseTexture!==void 0){let W=G.diffuseTexture,H=Z.textures[Y[W.index].source];K.setDiffuseTexture(H),Z.setTextureInfo(K.getDiffuseTextureInfo(),W)}if(G.specularGlossinessTexture!==void 0){let W=G.specularGlossinessTexture,H=Z.textures[Y[W.index].source];K.setSpecularGlossinessTexture(H),Z.setTextureInfo(K.getSpecularGlossinessTextureInfo(),W)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let Y=X.getExtension(z$);if(Y){let $=Z.materialIndexMap.get(X),Q=J.json.materials[$];Q.extensions=Q.extensions||{};let K=Q.extensions[z$]={diffuseFactor:Y.getDiffuseFactor(),specularFactor:Y.getSpecularFactor(),glossinessFactor:Y.getGlossinessFactor()};if(Y.getDiffuseTexture()){let G=Y.getDiffuseTexture(),W=Y.getDiffuseTextureInfo();K.diffuseTexture=Z.createTextureInfoDef(G,W)}if(Y.getSpecularGlossinessTexture()){let G=Y.getSpecularGlossinessTexture(),W=Y.getSpecularGlossinessTextureInfo();K.specularGlossinessTexture=Z.createTextureInfoDef(G,W)}}}),this}}m2.EXTENSION_NAME=z$;var{R:tD1,G:eD1,B:ZC1,A:JC1}=Y9;class vE extends s1{init(){this.extensionName=VE,this.propertyType="Sheen",this.parentTypes=[s.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{sheenColorFactor:[0,0,0],sheenColorTexture:null,sheenColorTextureInfo:new T1(this.graph,"sheenColorTextureInfo"),sheenRoughnessFactor:0,sheenRoughnessTexture:null,sheenRoughnessTextureInfo:new T1(this.graph,"sheenRoughnessTextureInfo")})}getSheenColorFactor(){return this.get("sheenColorFactor")}setSheenColorFactor(Z){return this.set("sheenColorFactor",Z)}getSheenColorTexture(){return this.getRef("sheenColorTexture")}getSheenColorTextureInfo(){return this.getRef("sheenColorTexture")?this.getRef("sheenColorTextureInfo"):null}setSheenColorTexture(Z){return this.setRef("sheenColorTexture",Z,{channels:tD1|eD1|ZC1,isColor:!0})}getSheenRoughnessFactor(){return this.get("sheenRoughnessFactor")}setSheenRoughnessFactor(Z){return this.set("sheenRoughnessFactor",Z)}getSheenRoughnessTexture(){return this.getRef("sheenRoughnessTexture")}getSheenRoughnessTextureInfo(){return this.getRef("sheenRoughnessTexture")?this.getRef("sheenRoughnessTextureInfo"):null}setSheenRoughnessTexture(Z){return this.setRef("sheenRoughnessTexture",Z,{channels:JC1})}}vE.EXTENSION_NAME=VE;var F$=VE;class AE extends I1{constructor(...Z){super(...Z);this.extensionName=F$,this.prereadTypes=[s.MESH],this.prewriteTypes=[s.MESH]}createSheen(){return new vE(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],Y=J.json.textures||[];return X.forEach(($,Q)=>{if($.extensions&&$.extensions[F$]){let K=this.createSheen();Z.materials[Q].setExtension(F$,K);let G=$.extensions[F$];if(G.sheenColorFactor!==void 0)K.setSheenColorFactor(G.sheenColorFactor);if(G.sheenRoughnessFactor!==void 0)K.setSheenRoughnessFactor(G.sheenRoughnessFactor);if(G.sheenColorTexture!==void 0){let W=G.sheenColorTexture,H=Z.textures[Y[W.index].source];K.setSheenColorTexture(H),Z.setTextureInfo(K.getSheenColorTextureInfo(),W)}if(G.sheenRoughnessTexture!==void 0){let W=G.sheenRoughnessTexture,H=Z.textures[Y[W.index].source];K.setSheenRoughnessTexture(H),Z.setTextureInfo(K.getSheenRoughnessTextureInfo(),W)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let Y=X.getExtension(F$);if(Y){let $=Z.materialIndexMap.get(X),Q=J.json.materials[$];Q.extensions=Q.extensions||{};let K=Q.extensions[F$]={sheenColorFactor:Y.getSheenColorFactor(),sheenRoughnessFactor:Y.getSheenRoughnessFactor()};if(Y.getSheenColorTexture()){let G=Y.getSheenColorTexture(),W=Y.getSheenColorTextureInfo();K.sheenColorTexture=Z.createTextureInfoDef(G,W)}if(Y.getSheenRoughnessTexture()){let G=Y.getSheenRoughnessTexture(),W=Y.getSheenRoughnessTextureInfo();K.sheenRoughnessTexture=Z.createTextureInfoDef(G,W)}}}),this}}AE.EXTENSION_NAME=F$;var{R:XC1,G:YC1,B:$C1,A:QC1}=Y9;class xE extends s1{init(){this.extensionName=zE,this.propertyType="Specular",this.parentTypes=[s.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{specularFactor:1,specularTexture:null,specularTextureInfo:new T1(this.graph,"specularTextureInfo"),specularColorFactor:[1,1,1],specularColorTexture:null,specularColorTextureInfo:new T1(this.graph,"specularColorTextureInfo")})}getSpecularFactor(){return this.get("specularFactor")}setSpecularFactor(Z){return this.set("specularFactor",Z)}getSpecularColorFactor(){return this.get("specularColorFactor")}setSpecularColorFactor(Z){return this.set("specularColorFactor",Z)}getSpecularTexture(){return this.getRef("specularTexture")}getSpecularTextureInfo(){return this.getRef("specularTexture")?this.getRef("specularTextureInfo"):null}setSpecularTexture(Z){return this.setRef("specularTexture",Z,{channels:QC1})}getSpecularColorTexture(){return this.getRef("specularColorTexture")}getSpecularColorTextureInfo(){return this.getRef("specularColorTexture")?this.getRef("specularColorTextureInfo"):null}setSpecularColorTexture(Z){return this.setRef("specularColorTexture",Z,{channels:XC1|YC1|$C1,isColor:!0})}}xE.EXTENSION_NAME=zE;var q$=zE;class u2 extends I1{constructor(...Z){super(...Z);this.extensionName=q$,this.prereadTypes=[s.MESH],this.prewriteTypes=[s.MESH]}createSpecular(){return new xE(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],Y=J.json.textures||[];return X.forEach(($,Q)=>{if($.extensions&&$.extensions[q$]){let K=this.createSpecular();Z.materials[Q].setExtension(q$,K);let G=$.extensions[q$];if(G.specularFactor!==void 0)K.setSpecularFactor(G.specularFactor);if(G.specularColorFactor!==void 0)K.setSpecularColorFactor(G.specularColorFactor);if(G.specularTexture!==void 0){let W=G.specularTexture,H=Z.textures[Y[W.index].source];K.setSpecularTexture(H),Z.setTextureInfo(K.getSpecularTextureInfo(),W)}if(G.specularColorTexture!==void 0){let W=G.specularColorTexture,H=Z.textures[Y[W.index].source];K.setSpecularColorTexture(H),Z.setTextureInfo(K.getSpecularColorTextureInfo(),W)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let Y=X.getExtension(q$);if(Y){let $=Z.materialIndexMap.get(X),Q=J.json.materials[$];Q.extensions=Q.extensions||{};let K=Q.extensions[q$]={};if(Y.getSpecularFactor()!==1)K.specularFactor=Y.getSpecularFactor();if(!z8.eq(Y.getSpecularColorFactor(),[1,1,1]))K.specularColorFactor=Y.getSpecularColorFactor();if(Y.getSpecularTexture()){let G=Y.getSpecularTexture(),W=Y.getSpecularTextureInfo();K.specularTexture=Z.createTextureInfoDef(G,W)}if(Y.getSpecularColorTexture()){let G=Y.getSpecularColorTexture(),W=Y.getSpecularColorTextureInfo();K.specularColorTexture=Z.createTextureInfoDef(G,W)}}}),this}}u2.EXTENSION_NAME=q$;var{R:KC1}=Y9;class hE extends s1{init(){this.extensionName=FE,this.propertyType="Transmission",this.parentTypes=[s.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{transmissionFactor:0,transmissionTexture:null,transmissionTextureInfo:new T1(this.graph,"transmissionTextureInfo")})}getTransmissionFactor(){return this.get("transmissionFactor")}setTransmissionFactor(Z){return this.set("transmissionFactor",Z)}getTransmissionTexture(){return this.getRef("transmissionTexture")}getTransmissionTextureInfo(){return this.getRef("transmissionTexture")?this.getRef("transmissionTextureInfo"):null}setTransmissionTexture(Z){return this.setRef("transmissionTexture",Z,{channels:KC1})}}hE.EXTENSION_NAME=FE;var U$=FE;class fE extends I1{constructor(...Z){super(...Z);this.extensionName=U$,this.prereadTypes=[s.MESH],this.prewriteTypes=[s.MESH]}createTransmission(){return new hE(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],Y=J.json.textures||[];return X.forEach(($,Q)=>{if($.extensions&&$.extensions[U$]){let K=this.createTransmission();Z.materials[Q].setExtension(U$,K);let G=$.extensions[U$];if(G.transmissionFactor!==void 0)K.setTransmissionFactor(G.transmissionFactor);if(G.transmissionTexture!==void 0){let W=G.transmissionTexture,H=Z.textures[Y[W.index].source];K.setTransmissionTexture(H),Z.setTextureInfo(K.getTransmissionTextureInfo(),W)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let Y=X.getExtension(U$);if(Y){let $=Z.materialIndexMap.get(X),Q=J.json.materials[$];Q.extensions=Q.extensions||{};let K=Q.extensions[U$]={transmissionFactor:Y.getTransmissionFactor()};if(Y.getTransmissionTexture()){let G=Y.getTransmissionTexture(),W=Y.getTransmissionTextureInfo();K.transmissionTexture=Z.createTextureInfoDef(G,W)}}}),this}}fE.EXTENSION_NAME=U$;class yE extends s1{init(){this.extensionName=qE,this.propertyType="Unlit",this.parentTypes=[s.MATERIAL]}}yE.EXTENSION_NAME=qE;var GG=qE;class d2 extends I1{constructor(...Z){super(...Z);this.extensionName=GG,this.prereadTypes=[s.MESH],this.prewriteTypes=[s.MESH]}createUnlit(){return new yE(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){return(Z.jsonDoc.json.materials||[]).forEach((X,Y)=>{if(X.extensions&&X.extensions[GG])Z.materials[Y].setExtension(GG,this.createUnlit())}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{if(X.getExtension(GG)){let Y=Z.materialIndexMap.get(X),$=J.json.materials[Y];$.extensions=$.extensions||{},$.extensions[GG]={}}}),this}}d2.EXTENSION_NAME=GG;class bE extends s1{init(){this.extensionName=w$,this.propertyType="Mapping",this.parentTypes=["MappingList"]}getDefaults(){return Object.assign(super.getDefaults(),{material:null,variants:new E0})}getMaterial(){return this.getRef("material")}setMaterial(Z){return this.setRef("material",Z)}addVariant(Z){return this.addRef("variants",Z)}removeVariant(Z){return this.removeRef("variants",Z)}listVariants(){return this.listRefs("variants")}}bE.EXTENSION_NAME=w$;class gE extends s1{init(){this.extensionName=w$,this.propertyType="MappingList",this.parentTypes=[s.PRIMITIVE]}getDefaults(){return Object.assign(super.getDefaults(),{mappings:new E0})}addMapping(Z){return this.addRef("mappings",Z)}removeMapping(Z){return this.removeRef("mappings",Z)}listMappings(){return this.listRefs("mappings")}}gE.EXTENSION_NAME=w$;class h2 extends s1{init(){this.extensionName=w$,this.propertyType="Variant",this.parentTypes=["MappingList"]}}h2.EXTENSION_NAME=w$;var v7=w$;class mE extends I1{constructor(...Z){super(...Z);this.extensionName=v7}createMappingList(){return new gE(this.document.getGraph())}createVariant(Z=""){return new h2(this.document.getGraph(),Z)}createMapping(){return new bE(this.document.getGraph())}listVariants(){return Array.from(this.properties).filter((Z)=>Z instanceof h2)}read(Z){let J=Z.jsonDoc;if(!J.json.extensions||!J.json.extensions[v7])return this;let $=(J.json.extensions[v7].variants||[]).map((K)=>this.createVariant().setName(K.name||""));return(J.json.meshes||[]).forEach((K,G)=>{let W=Z.meshes[G];(K.primitives||[]).forEach((V,F)=>{if(!V.extensions||!V.extensions[v7])return;let z=this.createMappingList(),q=V.extensions[v7];for(let U of q.mappings){let B=this.createMapping();if(U.material!==void 0)B.setMaterial(Z.materials[U.material]);for(let L of U.variants||[])B.addVariant($[L]);z.addMapping(B)}W.listPrimitives()[F].setExtension(v7,z)})}),this}write(Z){let J=Z.jsonDoc,X=this.listVariants();if(!X.length)return this;let Y=[],$=new Map;for(let Q of X)$.set(Q,Y.length),Y.push(Z.createPropertyDef(Q));for(let Q of this.document.getRoot().listMeshes()){let K=Z.meshIndexMap.get(Q);Q.listPrimitives().forEach((G,W)=>{let H=G.getExtension(v7);if(!H)return;let V=Z.jsonDoc.json.meshes[K].primitives[W],F=H.listMappings().map((z)=>{let q=Z.createPropertyDef(z),U=z.getMaterial();if(U)q.material=Z.materialIndexMap.get(U);return q.variants=z.listVariants().map((B)=>$.get(B)),q});V.extensions=V.extensions||{},V.extensions[v7]={mappings:F}})}return J.json.extensions=J.json.extensions||{},J.json.extensions[v7]={variants:Y},this}}mE.EXTENSION_NAME=v7;var{G:GC1}=Y9;class uE extends s1{init(){this.extensionName=UE,this.propertyType="Volume",this.parentTypes=[s.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{thicknessFactor:0,thicknessTexture:null,thicknessTextureInfo:new T1(this.graph,"thicknessTexture"),attenuationDistance:1/0,attenuationColor:[1,1,1]})}getThicknessFactor(){return this.get("thicknessFactor")}setThicknessFactor(Z){return this.set("thicknessFactor",Z)}getThicknessTexture(){return this.getRef("thicknessTexture")}getThicknessTextureInfo(){return this.getRef("thicknessTexture")?this.getRef("thicknessTextureInfo"):null}setThicknessTexture(Z){return this.setRef("thicknessTexture",Z,{channels:GC1})}getAttenuationDistance(){return this.get("attenuationDistance")}setAttenuationDistance(Z){return this.set("attenuationDistance",Z)}getAttenuationColor(){return this.get("attenuationColor")}setAttenuationColor(Z){return this.set("attenuationColor",Z)}}uE.EXTENSION_NAME=UE;var L$=UE;class dE extends I1{constructor(...Z){super(...Z);this.extensionName=L$,this.prereadTypes=[s.MESH],this.prewriteTypes=[s.MESH]}createVolume(){return new uE(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],Y=J.json.textures||[];return X.forEach(($,Q)=>{if($.extensions&&$.extensions[L$]){let K=this.createVolume();Z.materials[Q].setExtension(L$,K);let G=$.extensions[L$];if(G.thicknessFactor!==void 0)K.setThicknessFactor(G.thicknessFactor);if(G.attenuationDistance!==void 0)K.setAttenuationDistance(G.attenuationDistance);if(G.attenuationColor!==void 0)K.setAttenuationColor(G.attenuationColor);if(G.thicknessTexture!==void 0){let W=G.thicknessTexture,H=Z.textures[Y[W.index].source];K.setThicknessTexture(H),Z.setTextureInfo(K.getThicknessTextureInfo(),W)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let Y=X.getExtension(L$);if(Y){let $=Z.materialIndexMap.get(X),Q=J.json.materials[$];Q.extensions=Q.extensions||{};let K=Q.extensions[L$]={};if(Y.getThicknessFactor()>0)K.thicknessFactor=Y.getThicknessFactor();if(Number.isFinite(Y.getAttenuationDistance()))K.attenuationDistance=Y.getAttenuationDistance();if(!z8.eq(Y.getAttenuationColor(),[1,1,1]))K.attenuationColor=Y.getAttenuationColor();if(Y.getThicknessTexture()){let G=Y.getThicknessTexture(),W=Y.getThicknessTextureInfo();K.thicknessTexture=Z.createTextureInfoDef(G,W)}}}),this}}dE.EXTENSION_NAME=L$;var hr=ND1;class HV extends I1{constructor(...Z){super(...Z);this.extensionName=hr}read(Z){return this}write(Z){return this}}HV.EXTENSION_NAME=hr;var $V=PD1;class fr{match(Z){return Z[0]===171&&Z[1]===75&&Z[2]===84&&Z[3]===88&&Z[4]===32&&Z[5]===50&&Z[6]===48&&Z[7]===187&&Z[8]===13&&Z[9]===10&&Z[10]===26&&Z[11]===10}getSize(Z){let J=v2(Z);return[J.pixelWidth,J.pixelHeight]}getChannels(Z){let X=v2(Z).dataFormatDescriptor[0];if(X.colorModel===qr)return X.samples.length===2&&(X.samples[1].channelType&15)===15?4:3;else if(X.colorModel===Ur)return(X.samples[0].channelType&15)===3?4:3;throw new Error(`Unexpected KTX2 colorModel, "${X.colorModel}".`)}getVRAMByteLength(Z){let J=v2(Z),X=this.getChannels(Z)>3,Y=0;for(let $=0;$<J.levels.length;$++){let Q=J.levels[$];if(Q.uncompressedByteLength)Y+=Q.uncompressedByteLength;else{let K=Math.max(1,Math.floor(J.pixelWidth/Math.pow(2,$))),G=Math.max(1,Math.floor(J.pixelHeight/Math.pow(2,$))),W=X?16:8;Y+=K/4*(G/4)*W}}return Y}}class cE extends I1{constructor(...Z){super(...Z);this.extensionName=$V,this.prereadTypes=[s.TEXTURE]}static register(){h4.registerFormat("image/ktx2",new fr)}preread(Z){return Z.jsonDoc.json.textures.forEach((J)=>{if(J.extensions&&J.extensions[$V]){let X=J.extensions[$V];J.source=X.source}}),this}read(Z){return this}write(Z){let J=Z.jsonDoc;return this.document.getRoot().listTextures().forEach((X)=>{if(X.getMimeType()==="image/ktx2"){let Y=Z.imageIndexMap.get(X);J.json.textures.forEach(($)=>{if($.source===Y)$.extensions=$.extensions||{},$.extensions[$V]={source:$.source},delete $.source})}}),this}}cE.EXTENSION_NAME=$V;class lE extends s1{init(){this.extensionName=LE,this.propertyType="Transform",this.parentTypes=[s.TEXTURE_INFO]}getDefaults(){return Object.assign(super.getDefaults(),{offset:[0,0],rotation:0,scale:[1,1],texCoord:null})}getOffset(){return this.get("offset")}setOffset(Z){return this.set("offset",Z)}getRotation(){return this.get("rotation")}setRotation(Z){return this.set("rotation",Z)}getScale(){return this.get("scale")}setScale(Z){return this.set("scale",Z)}getTexCoord(){return this.get("texCoord")}setTexCoord(Z){return this.set("texCoord",Z)}}lE.EXTENSION_NAME=LE;var B$=LE;class pE extends I1{constructor(...Z){super(...Z);this.extensionName=B$}createTransform(){return new lE(this.document.getGraph())}read(Z){for(let[J,X]of Array.from(Z.textureInfos.entries())){if(!X.extensions||!X.extensions[B$])continue;let Y=this.createTransform(),$=X.extensions[B$];if($.offset!==void 0)Y.setOffset($.offset);if($.rotation!==void 0)Y.setRotation($.rotation);if($.scale!==void 0)Y.setScale($.scale);if($.texCoord!==void 0)Y.setTexCoord($.texCoord);J.setExtension(B$,Y)}return this}write(Z){let J=Array.from(Z.textureInfoDefMap.entries());for(let[X,Y]of J){let $=X.getExtension(B$);if(!$)continue;Y.extensions=Y.extensions||{};let Q={},K=z8.eq;if(!K($.getOffset(),[0,0]))Q.offset=$.getOffset();if($.getRotation()!==0)Q.rotation=$.getRotation();if(!K($.getScale(),[1,1]))Q.scale=$.getScale();if($.getTexCoord()!=null)Q.texCoord=$.getTexCoord();Y.extensions[B$]=Q}return this}}pE.EXTENSION_NAME=B$;var WC1=[s.ROOT,s.SCENE,s.NODE,s.MESH,s.MATERIAL,s.TEXTURE,s.ANIMATION];class iE extends s1{init(){this.extensionName=A2,this.propertyType="Packet",this.parentTypes=WC1}getDefaults(){return Object.assign(super.getDefaults(),{context:{},properties:{}})}getContext(){return this.get("context")}setContext(Z){return this.set("context",AZ({},Z))}listProperties(){return Object.keys(this.get("properties"))}getProperty(Z){let J=this.get("properties");return Z in J?J[Z]:null}setProperty(Z,J){this._assertContext(Z);let X=AZ({},this.get("properties"));if(J)X[Z]=J;else delete X[Z];return this.set("properties",X)}toJSONLD(){let Z=oT(this.get("context")),J=oT(this.get("properties"));return AZ({"@context":Z},J)}fromJSONLD(Z){Z=oT(Z);let J=Z["@context"];if(J)this.set("context",J);return delete Z["@context"],this.set("properties",Z)}_assertContext(Z){if(!(Z.split(":")[0]in this.get("context")))throw new Error(`${A2}: Missing context for term, "${Z}".`)}}iE.EXTENSION_NAME=A2;function oT(Z){return JSON.parse(JSON.stringify(Z))}var vZ=A2;class nE extends I1{constructor(...Z){super(...Z);this.extensionName=vZ}createPacket(){return new iE(this.document.getGraph())}listPackets(){return Array.from(this.properties)}read(Z){var J;let X=(J=Z.jsonDoc.json.extensions)==null?void 0:J[vZ];if(!X||!X.packets)return this;let Y=Z.jsonDoc.json,$=this.document.getRoot(),Q=X.packets.map((W)=>this.createPacket().fromJSONLD(W)),K=[[Y.asset],Y.scenes,Y.nodes,Y.meshes,Y.materials,Y.images,Y.animations],G=[[$],$.listScenes(),$.listNodes(),$.listMeshes(),$.listMaterials(),$.listTextures(),$.listAnimations()];for(let W=0;W<K.length;W++){let H=K[W]||[];for(let V=0;V<H.length;V++){let F=H[V];if(F.extensions&&F.extensions[vZ]){let z=F.extensions[vZ];G[W][V].setExtension(vZ,Q[z.packet])}}}return this}write(Z){let{json:J}=Z.jsonDoc,X=[];for(let Y of this.properties){X.push(Y.toJSONLD());for(let $ of Y.listParents()){let Q;switch($.propertyType){case s.ROOT:Q=J.asset;break;case s.SCENE:Q=J.scenes[Z.sceneIndexMap.get($)];break;case s.NODE:Q=J.nodes[Z.nodeIndexMap.get($)];break;case s.MESH:Q=J.meshes[Z.meshIndexMap.get($)];break;case s.MATERIAL:Q=J.materials[Z.materialIndexMap.get($)];break;case s.TEXTURE:Q=J.images[Z.imageIndexMap.get($)];break;case s.ANIMATION:Q=J.animations[Z.animationIndexMap.get($)];break;default:Q=null,this.document.getLogger().warn(`[${vZ}]: Unsupported parent property, "${$.propertyType}"`);break}if(!Q)continue;Q.extensions=Q.extensions||{},Q.extensions[vZ]={packet:X.length-1}}}if(X.length>0)J.extensions=J.extensions||{},J.extensions[vZ]={packets:X};return this}}nE.EXTENSION_NAME=vZ;var HC1=[WV,wE,OE,RE,PE,CE,EE,g2,_E,m2,u2,AE,fE,d2,mE,dE,HV,cE,pE,nE],SS6=[f2,GV,y2,b2,...HC1];var VC1=r(HT(),1);function FG(){return FG=Object.assign?Object.assign.bind():function(Z){for(var J=1;J<arguments.length;J++){var X=arguments[J];for(var Y in X)({}).hasOwnProperty.call(X,Y)&&(Z[Y]=X[Y])}return Z},FG.apply(null,arguments)}var{POINTS:yr,LINES:c2,LINE_STRIP:zC1,LINE_LOOP:FC1,TRIANGLES:l2,TRIANGLE_STRIP:qC1,TRIANGLE_FAN:UC1}=C8.Mode;function $X(Z,J){return Object.defineProperty(J,"name",{value:Z}),J}function A7(Z,J){let X=FG({},Z);for(let Y in J)if(J[Y]!==void 0)X[Y]=J[Y];return X}function Yt(Z){let J=Z.getIndices(),X=Z.getAttribute("POSITION");switch(Z.getMode()){case C8.Mode.POINTS:return J?J.getCount():X.getCount();case C8.Mode.LINES:return J?J.getCount()/2:X.getCount()/2;case C8.Mode.LINE_LOOP:return J?J.getCount():X.getCount();case C8.Mode.LINE_STRIP:return J?J.getCount()-1:X.getCount()-1;case C8.Mode.TRIANGLES:return J?J.getCount()/3:X.getCount()/3;case C8.Mode.TRIANGLE_STRIP:case C8.Mode.TRIANGLE_FAN:return J?J.getCount()-2:X.getCount()-2;default:throw new Error("Unexpected mode: "+Z.getMode())}}var LC1=new Intl.NumberFormat(void 0,{maximumFractionDigits:0});function rE(Z){return LC1.format(Z)}function BC1(Z,J,X=2){let Y=Z>J?"–":"+",$="%";return Y+(Math.abs(Z-J)/Z*100).toFixed(X)+"%"}function s2(Z,J){return`${rE(Z)} → ${rE(J)} (${BC1(Z,J)})`}function $k(Z){let J=[];for(let X of Z.listAttributes())J.push(X);for(let X of Z.listTargets())for(let Y of X.listAttributes())J.push(Y);return Array.from(new Set(J))}function wC1(Z,J,X){Z.swap(J,X);for(let Y of Z.listTargets())Y.swap(J,X)}function jC1(Z,J){if(Z==null&&J==null)return!0;if(Z==null||J==null)return!1;if(Z.length!==J.length)return!1;for(let X=0;X<Z.length;X++)if(Z[X]!==J[X])return!1;return!0}function xZ(Z,J){return Z.createAccessor(J.getName()).setArray(J.getArray()).setType(J.getType()).setBuffer(J.getBuffer()).setNormalized(J.getNormalized()).setSparse(J.getSparse())}function OC1(Z,J=Z){let X=Qk(Z,J);for(let Y=0;Y<X.length;Y++)X[Y]=Y;return X}function Qk(Z,J=Z){return J<=65534?new Uint16Array(Z):new Uint32Array(Z)}function MC1(Z){return Z.listParents().some((J)=>J.propertyType!==a.ROOT)}function $t(Z){for(let J in Z)return!1;return!0}function Qt(Z){let J=_6.fromGraph(Z.getGraph()),X=Z.getMaterial(),Y=J.getRoot().listMaterials().indexOf(X),$=NC1[Z.getMode()],Q=!!Z.getIndices(),K=Z.listSemantics().sort().map((W)=>{let H=Z.getAttribute(W),V=H.getElementSize(),F=H.getComponentType();return`${W}:${V}:${F}`}).join("+"),G=Z.listTargets().map((W)=>{return W.listSemantics().sort().map((H)=>{let V=Z.getAttribute(H),F=V.getElementSize(),z=V.getComponentType();return`${H}:${F}:${z}`}).join("+")}).join("~");return`${Y}|${$}|${Q}|${K}|${G}`}function RC1(Z){return Math.pow(2,Math.ceil(Math.log(Z)/Math.LN2))}var NC1={[yr]:yr,[c2]:c2,[zC1]:c2,[FC1]:c2,[l2]:l2,[qC1]:l2,[UC1]:l2},VG="center",br={pivot:"center"};function Kt(Z=br){let J=A7(br,Z);return $X(VG,(X)=>{let Y=X.getLogger(),$=X.getRoot(),Q=$.listAnimations().length>0||$.listSkins().length>0;X.getRoot().listScenes().forEach((K,G)=>{Y.debug(`${VG}: Scene ${G+1} / ${$.listScenes().length}.`);let W;if(typeof J.pivot==="string"){let V=XT(K);if(W=[(V.max[0]-V.min[0])/2+V.min[0],(V.max[1]-V.min[1])/2+V.min[1],(V.max[2]-V.min[2])/2+V.min[2]],J.pivot==="above")W[1]=V.max[1];if(J.pivot==="below")W[1]=V.min[1]}else W=J.pivot;Y.debug(`${VG}: Pivot "${W.join(", ")}".`);let H=[-1*W[0],-1*W[1],-1*W[2]];if(Q){Y.debug(`${VG}: Model contains animation or skin. Adding a wrapper node.`);let V=X.createNode("Pivot").setTranslation(H);K.listChildren().forEach((F)=>V.addChild(F)),K.addChild(V)}else Y.debug(`${VG}: Skipping wrapper, offsetting all root nodes.`),K.listChildren().forEach((V)=>{let F=V.getTranslation();V.setTranslation([F[0]+H[0],F[1]+H[1],F[2]+H[2]])})}),Y.debug(`${VG}: Complete.`)})}function PC1(Z){let J=new Set,X=Z,Y;while(Y=X.getParentNode()){if(J.has(Y))throw new Error("Circular dependency in scene graph.");J.add(Y),X=Y}return X.listParents().filter(($)=>$ instanceof sK)}function DC1(Z){let J=PC1(Z),X=Z.getParentNode();if(!X)return Z;Z.setMatrix(Z.getWorldMatrix()),X.removeChild(Z);for(let Y of J)Y.addChild(Z);return Z}var qG=typeof Float32Array!=="undefined"?Float32Array:Array;if(!Math.hypot)Math.hypot=function(){var Z=0,J=arguments.length;while(J--)Z+=arguments[J]*arguments[J];return Math.sqrt(Z)};function CC1(Z,J){var X=J[0],Y=J[1],$=J[2],Q=J[3],K=J[4],G=J[5],W=J[6],H=J[7],V=J[8],F=J[9],z=J[10],q=J[11],U=J[12],B=J[13],L=J[14],w=J[15],O=X*G-Y*K,M=X*W-$*K,R=X*H-Q*K,D=Y*W-$*G,N=Y*H-Q*G,C=$*H-Q*W,T=V*B-F*U,E=V*L-z*U,x=V*w-q*U,S=F*L-z*B,h=F*w-q*B,I=z*w-q*L,_=O*I-M*h+R*S+D*x-N*E+C*T;if(!_)return null;return _=1/_,Z[0]=(G*I-W*h+H*S)*_,Z[1]=($*h-Y*I-Q*S)*_,Z[2]=(B*C-L*N+w*D)*_,Z[3]=(z*N-F*C-q*D)*_,Z[4]=(W*x-K*I-H*E)*_,Z[5]=(X*I-$*x+Q*E)*_,Z[6]=(L*R-U*C-w*M)*_,Z[7]=(V*C-z*R+q*M)*_,Z[8]=(K*h-G*x+H*T)*_,Z[9]=(Y*x-X*h-Q*T)*_,Z[10]=(U*N-B*R+w*O)*_,Z[11]=(F*R-V*N-q*O)*_,Z[12]=(G*E-K*S-W*T)*_,Z[13]=(X*S-Y*E+$*T)*_,Z[14]=(B*M-U*D-L*O)*_,Z[15]=(V*D-F*M+z*O)*_,Z}function TC1(Z){var J=Z[0],X=Z[1],Y=Z[2],$=Z[3],Q=Z[4],K=Z[5],G=Z[6],W=Z[7],H=Z[8],V=Z[9],F=Z[10],z=Z[11],q=Z[12],U=Z[13],B=Z[14],L=Z[15],w=J*K-X*Q,O=J*G-Y*Q,M=J*W-$*Q,R=X*G-Y*K,D=X*W-$*K,N=Y*W-$*G,C=H*U-V*q,T=H*B-F*q,E=H*L-z*q,x=V*B-F*U,S=V*L-z*U,h=F*L-z*B;return w*h-O*S+M*x+R*E-D*T+N*C}function Gt(Z,J,X){var Y=J[0],$=J[1],Q=J[2],K=J[3],G=J[4],W=J[5],H=J[6],V=J[7],F=J[8],z=J[9],q=J[10],U=J[11],B=J[12],L=J[13],w=J[14],O=J[15],M=X[0],R=X[1],D=X[2],N=X[3];return Z[0]=M*Y+R*G+D*F+N*B,Z[1]=M*$+R*W+D*z+N*L,Z[2]=M*Q+R*H+D*q+N*w,Z[3]=M*K+R*V+D*U+N*O,M=X[4],R=X[5],D=X[6],N=X[7],Z[4]=M*Y+R*G+D*F+N*B,Z[5]=M*$+R*W+D*z+N*L,Z[6]=M*Q+R*H+D*q+N*w,Z[7]=M*K+R*V+D*U+N*O,M=X[8],R=X[9],D=X[10],N=X[11],Z[8]=M*Y+R*G+D*F+N*B,Z[9]=M*$+R*W+D*z+N*L,Z[10]=M*Q+R*H+D*q+N*w,Z[11]=M*K+R*V+D*U+N*O,M=X[12],R=X[13],D=X[14],N=X[15],Z[12]=M*Y+R*G+D*F+N*B,Z[13]=M*$+R*W+D*z+N*L,Z[14]=M*Q+R*H+D*q+N*w,Z[15]=M*K+R*V+D*U+N*O,Z}function EC1(){var Z=new qG(9);if(qG!=Float32Array)Z[1]=0,Z[2]=0,Z[3]=0,Z[5]=0,Z[6]=0,Z[7]=0;return Z[0]=1,Z[4]=1,Z[8]=1,Z}function kC1(Z,J){return Z[0]=J[0],Z[1]=J[1],Z[2]=J[2],Z[3]=J[4],Z[4]=J[5],Z[5]=J[6],Z[6]=J[8],Z[7]=J[9],Z[8]=J[10],Z}function IC1(Z,J){if(Z===J){var X=J[1],Y=J[2],$=J[5];Z[1]=J[3],Z[2]=J[6],Z[3]=X,Z[5]=J[7],Z[6]=Y,Z[7]=$}else Z[0]=J[0],Z[1]=J[3],Z[2]=J[6],Z[3]=J[1],Z[4]=J[4],Z[5]=J[7],Z[6]=J[2],Z[7]=J[5],Z[8]=J[8];return Z}function _C1(Z,J){var X=J[0],Y=J[1],$=J[2],Q=J[3],K=J[4],G=J[5],W=J[6],H=J[7],V=J[8],F=V*K-G*H,z=-V*Q+G*W,q=H*Q-K*W,U=X*F+Y*z+$*q;if(!U)return null;return U=1/U,Z[0]=F*U,Z[1]=(-V*Y+$*H)*U,Z[2]=(G*Y-$*K)*U,Z[3]=z*U,Z[4]=(V*X-$*W)*U,Z[5]=(-G*X+$*Q)*U,Z[6]=q*U,Z[7]=(-H*X+Y*W)*U,Z[8]=(K*X-Y*Q)*U,Z}function o2(){var Z=new qG(3);if(qG!=Float32Array)Z[0]=0,Z[1]=0,Z[2]=0;return Z}function SC1(Z,J,X){return Z[0]=J[0]*X[0],Z[1]=J[1]*X[1],Z[2]=J[2]*X[2],Z}function Wt(Z,J){var X=J[0],Y=J[1],$=J[2],Q=X*X+Y*Y+$*$;if(Q>0)Q=1/Math.sqrt(Q);return Z[0]=J[0]*Q,Z[1]=J[1]*Q,Z[2]=J[2]*Q,Z}function vC1(Z,J,X){var Y=J[0],$=J[1],Q=J[2],K=X[3]*Y+X[7]*$+X[11]*Q+X[15];return K=K||1,Z[0]=(X[0]*Y+X[4]*$+X[8]*Q+X[12])/K,Z[1]=(X[1]*Y+X[5]*$+X[9]*Q+X[13])/K,Z[2]=(X[2]*Y+X[6]*$+X[10]*Q+X[14])/K,Z}function AC1(Z,J,X){var Y=J[0],$=J[1],Q=J[2];return Z[0]=Y*X[0]+$*X[3]+Q*X[6],Z[1]=Y*X[1]+$*X[4]+Q*X[7],Z[2]=Y*X[2]+$*X[5]+Q*X[8],Z}var xC1=SC1;(function(){var Z=o2();return function(J,X,Y,$,Q,K){var G,W;if(!X)X=3;if(!Y)Y=0;if($)W=Math.min($*X+Y,J.length);else W=J.length;for(G=Y;G<W;G+=X)Z[0]=J[G],Z[1]=J[G+1],Z[2]=J[G+2],Q(Z,Z,K),J[G]=Z[0],J[G+1]=Z[1],J[G+2]=Z[2];return J}})();var XX="dedup",aE={keepUniqueNames:!1,propertyTypes:[a.ACCESSOR,a.MESH,a.TEXTURE,a.MATERIAL,a.SKIN]};function Ht(Z=aE){let J=A7(aE,Z),X=new Set(J.propertyTypes);for(let Y of J.propertyTypes)if(!aE.propertyTypes.includes(Y))throw new Error(`${XX}: Unsupported deduplication on type "${Y}".`);return $X(XX,(Y)=>{let $=Y.getLogger();if(X.has(a.ACCESSOR))hC1(Y);if(X.has(a.TEXTURE))yC1(Y,J);if(X.has(a.MATERIAL))bC1(Y,J);if(X.has(a.MESH))fC1(Y,J);if(X.has(a.SKIN))gC1(Y,J);$.debug(`${XX}: Complete.`)})}function hC1(Z){let J=Z.getLogger(),X=new Map,Y=new Map,$=new Map,Q=new Map,K=Z.getRoot().listMeshes();K.forEach((F)=>{F.listPrimitives().forEach((z)=>{z.listAttributes().forEach((q)=>G(q,Y)),G(z.getIndices(),X)})});for(let F of Z.getRoot().listAnimations())for(let z of F.listSamplers())G(z.getInput(),$),G(z.getOutput(),Q);function G(F,z){if(!F)return;let q=[F.getCount(),F.getType(),F.getComponentType(),F.getNormalized(),F.getSparse()].join(":"),U=z.get(q);if(!U)z.set(q,U=new Set);U.add(F)}function W(F,z){for(let q=0;q<F.length;q++){let U=F[q],B=o0.toView(U.getArray());if(z.has(U))continue;for(let L=q+1;L<F.length;L++){let w=F[L];if(z.has(w))continue;if(o0.equals(B,o0.toView(w.getArray())))z.set(w,U)}}}let H=0,V=new Map;for(let F of[Y,X,$,Q])for(let z of F.values())H+=z.size,W(Array.from(z),V);J.debug(`${XX}: Merged ${V.size} of ${H} accessors.`),K.forEach((F)=>{F.listPrimitives().forEach((z)=>{z.listAttributes().forEach((U)=>{if(V.has(U))z.swap(U,V.get(U))});let q=z.getIndices();if(q&&V.has(q))z.swap(q,V.get(q))})});for(let F of Z.getRoot().listAnimations())for(let z of F.listSamplers()){let q=z.getInput(),U=z.getOutput();if(q&&V.has(q))z.swap(q,V.get(q));if(U&&V.has(U))z.swap(U,V.get(U))}Array.from(V.keys()).forEach((F)=>F.dispose())}function fC1(Z,J){let X=Z.getLogger(),Y=Z.getRoot(),$=new Map;Y.listAccessors().forEach((G,W)=>$.set(G,W)),Y.listMaterials().forEach((G,W)=>$.set(G,W));let Q=Y.listMeshes().length,K=new Map;for(let G of Y.listMeshes()){let W=[];for(let V of G.listPrimitives())W.push(Vt(V,$));let H="";if(J.keepUniqueNames)H+=G.getName()+";";if(H+=W.join(";"),K.has(H)){let V=K.get(H);G.listParents().forEach((F)=>{if(F.propertyType!==a.ROOT)F.swap(G,V)}),G.dispose()}else K.set(H,G)}X.debug(`${XX}: Merged ${Q-K.size} of ${Q} meshes.`)}function yC1(Z,J){let X=Z.getLogger(),Y=Z.getRoot(),$=Y.listTextures(),Q=new Map;for(let K=0;K<$.length;K++){let G=$[K],W=G.getImage();if(Q.has(G))continue;for(let H=K+1;H<$.length;H++){let V=$[H],F=V.getImage();if(Q.has(V))continue;if(G.getMimeType()!==V.getMimeType())continue;if(J.keepUniqueNames&&G.getName()!==V.getName())continue;let z=G.getSize(),q=V.getSize();if(!z||!q)continue;if(z[0]!==q[0])continue;if(z[1]!==q[1])continue;if(!W||!F)continue;if(o0.equals(W,F))Q.set(V,G)}}X.debug(`${XX}: Merged ${Q.size} of ${Y.listTextures().length} textures.`),Array.from(Q.entries()).forEach(([K,G])=>{K.listParents().forEach((W)=>{if(!(W instanceof tY))W.swap(K,G)}),K.dispose()})}function bC1(Z,J){let X=Z.getLogger(),$=Z.getRoot().listMaterials(),Q=new Map,K=new Map,G=new Set;if(!J.keepUniqueNames)G.add("name");for(let W=0;W<$.length;W++){let H=$[W];if(Q.has(H))continue;if(gr(H,K))continue;for(let V=W+1;V<$.length;V++){let F=$[V];if(Q.has(F))continue;if(gr(F,K))continue;if(H.equals(F,G))Q.set(F,H)}}X.debug(`${XX}: Merged ${Q.size} of ${$.length} materials.`),Array.from(Q.entries()).forEach(([W,H])=>{W.listParents().forEach((V)=>{if(!(V instanceof tY))V.swap(W,H)}),W.dispose()})}function gC1(Z,J){let X=Z.getLogger(),$=Z.getRoot().listSkins(),Q=new Map,K=new Set(["joints"]);if(!J.keepUniqueNames)K.add("name");for(let G=0;G<$.length;G++){let W=$[G];if(Q.has(W))continue;for(let H=G+1;H<$.length;H++){let V=$[H];if(Q.has(V))continue;if(W.equals(V,K)&&jC1(W.listJoints(),V.listJoints()))Q.set(V,W)}}X.debug(`${XX}: Merged ${Q.size} of ${$.length} skins.`),Array.from(Q.entries()).forEach(([G,W])=>{G.listParents().forEach((H)=>{if(!(H instanceof tY))H.swap(G,W)}),G.dispose()})}function Vt(Z,J){let X=[];for(let Y of Z.listSemantics()){let $=Z.getAttribute(Y);X.push(Y+":"+J.get($))}if(Z instanceof C8){let Y=Z.getIndices();if(Y)X.push("indices:"+J.get(Y));let $=Z.getMaterial();if($)X.push("material:"+J.get($));X.push("mode:"+Z.getMode());for(let Q of Z.listTargets())X.push("target:"+Vt(Q,J))}return X.join(",")}function gr(Z,J){if(J.has(Z))return J.get(Z);let X=Z.getGraph(),Y=new Set,$=X.listParentEdges(Z);while($.length>0){let Q=$.pop();if(Q.getAttributes().modifyChild===!0)return J.set(Z,!0),!0;let K=Q.getChild();if(Y.has(K))continue;for(let G of X.listChildEdges(K))$.push(G)}return J.set(Z,!1),!1}function zt(){var Z=new qG(4);if(qG!=Float32Array)Z[0]=0,Z[1]=0,Z[2]=0,Z[3]=0;return Z}function mC1(Z,J,X){return Z[0]=J[0]+X[0],Z[1]=J[1]+X[1],Z[2]=J[2]+X[2],Z[3]=J[3]+X[3],Z}function uC1(Z,J,X){return Z[0]=J[0]-X[0],Z[1]=J[1]-X[1],Z[2]=J[2]-X[2],Z[3]=J[3]-X[3],Z}function dC1(Z,J,X){return Z[0]=J[0]*X[0],Z[1]=J[1]*X[1],Z[2]=J[2]*X[2],Z[3]=J[3]*X[3],Z}function cC1(Z,J,X){return Z[0]=J[0]*X,Z[1]=J[1]*X,Z[2]=J[2]*X,Z[3]=J[3]*X,Z}function lC1(Z){var J=Z[0],X=Z[1],Y=Z[2],$=Z[3];return Math.hypot(J,X,Y,$)}var Ft=uC1,pC1=dC1,qt=lC1;(function(){var Z=zt();return function(J,X,Y,$,Q,K){var G,W;if(!X)X=4;if(!Y)Y=0;if($)W=Math.min($*X+Y,J.length);else W=J.length;for(G=Y;G<W;G+=X)Z[0]=J[G],Z[1]=J[G+1],Z[2]=J[G+2],Z[3]=J[G+3],Q(Z,Z,K),J[G]=Z[0],J[G+1]=Z[1],J[G+2]=Z[2],J[G+3]=Z[3];return J}})();var iC1=/color|emissive|diffuse/i;function nC1(Z){return Z.getGraph().listParentEdges(Z).some(($)=>{return $.getAttributes().isColor||iC1.test($.getName())})?"srgb":null}function aC1(Z){let J=Z.getGraph(),X=new Set,Y=new Set;function $(Q){let K=new Set;for(let G of J.listChildEdges(Q))if(G.getChild()instanceof rY)K.add(G.getName()+"Info");for(let G of J.listChildEdges(Q)){let W=G.getChild();if(X.has(W))continue;if(X.add(W),W instanceof E5&&K.has(G.getName()))Y.add(W);else if(W instanceof aK)$(W)}}return $(Z),Array.from(Y)}function sC1(Z){let X=_6.fromGraph(Z.getGraph()).getRoot(),Y=Z.getGraph().listParentEdges(Z).filter(($)=>$.getParent()!==X).map(($)=>$.getName());return Array.from(new Set(Y))}var zG="prune",tE=0.011764705882352941,mr={propertyTypes:[a.NODE,a.SKIN,a.MESH,a.CAMERA,a.PRIMITIVE,a.PRIMITIVE_TARGET,a.ANIMATION,a.MATERIAL,a.TEXTURE,a.ACCESSOR,a.BUFFER],keepLeaves:!1,keepAttributes:!1,keepIndices:!1,keepSolidTextures:!1,keepExtras:!1};function r2(Z=mr){let J=A7(mr,Z),X=new Set(J.propertyTypes),Y=J.keepExtras;return $X(zG,async($)=>{let Q=$.getLogger(),K=$.getRoot(),G=$.getGraph(),W=new Ut,H=(V)=>W.dispose(V.target);if(G.addEventListener("node:dispose",H),X.has(a.MESH))for(let V of K.listMeshes()){if(V.listPrimitives().length>0)continue;V.dispose()}if(X.has(a.NODE)){if(!J.keepLeaves)for(let V of K.listScenes())Lt(G,V,Y);for(let V of K.listNodes())m9(V,Y)}if(X.has(a.SKIN))for(let V of K.listSkins())m9(V,Y);if(X.has(a.MESH))for(let V of K.listMeshes())m9(V,Y);if(X.has(a.CAMERA))for(let V of K.listCameras())m9(V,Y);if(X.has(a.PRIMITIVE))ur(G,a.PRIMITIVE,Y);if(X.has(a.PRIMITIVE_TARGET))ur(G,a.PRIMITIVE_TARGET,Y);if(!J.keepAttributes&&X.has(a.ACCESSOR)){let V=new Map;for(let F of K.listMeshes())for(let z of F.listPrimitives()){let q=z.getMaterial();if(!q)continue;let U=Bt($,z,q),B=rC1(z,U);dr(z,B),z.listTargets().forEach((L)=>dr(L,B)),V.has(q)?V.get(q).add(z):V.set(q,new Set([z]))}for(let[F,z]of V)tC1(F,Array.from(z))}if(!J.keepIndices&&X.has(a.ACCESSOR))for(let V of K.listMeshes())for(let F of V.listPrimitives())oC1(F);if(X.has(a.ANIMATION))for(let V of K.listAnimations()){for(let F of V.listChannels())if(!F.getTargetNode())F.dispose();if(!V.listChannels().length){let F=V.listSamplers();m9(V,Y),F.forEach((z)=>m9(z,Y))}else V.listSamplers().forEach((F)=>m9(F,Y))}if(X.has(a.MATERIAL))K.listMaterials().forEach((V)=>m9(V,Y));if(X.has(a.TEXTURE)){if(K.listTextures().forEach((V)=>m9(V,Y)),!J.keepSolidTextures)await eC1($)}if(X.has(a.ACCESSOR))K.listAccessors().forEach((V)=>m9(V,Y));if(X.has(a.BUFFER))K.listBuffers().forEach((V)=>m9(V,Y));if(G.removeEventListener("node:dispose",H),!W.empty()){let V=W.entries().map(([F,z])=>`${F} (${z})`).join(", ");Q.info(`${zG}: Removed types... ${V}`)}else Q.debug(`${zG}: No unused properties found.`);Q.debug(`${zG}: Complete.`)})}class Ut{constructor(){this.disposed={}}empty(){for(let Z in this.disposed)return!1;return!0}entries(){return Object.entries(this.disposed)}dispose(Z){this.disposed[Z.propertyType]=this.disposed[Z.propertyType]||0,this.disposed[Z.propertyType]++}}function m9(Z,J){let X=Z.listParents().filter(($)=>!($ instanceof tY||$ instanceof sY)),Y=J&&!$t(Z.getExtras());if(!X.length&&!Y)Z.dispose()}function ur(Z,J,X){for(let Y of Z.listEdges()){let $=Y.getParent();if($.propertyType===J)m9($,X)}}function Lt(Z,J,X){if(J.listChildren().forEach((K)=>Lt(Z,K,X)),J instanceof sK)return;let Y=Z.listParentEdges(J).some((K)=>{let G=K.getParent().propertyType;return G!==a.ROOT&&G!==a.SCENE&&G!==a.NODE}),$=Z.listChildren(J).length===0,Q=X&&!$t(J.getExtras());if($&&!Y&&!Q)J.dispose()}function dr(Z,J){for(let X of J)Z.setAttribute(X,null)}function oC1(Z){let J=Z.getIndices(),X=J&&J.getArray(),Y=Z.listAttributes()[0];if(!X||!Y)return;if(J.getCount()!==Y.getCount())return;for(let $=0,Q=X.length;$<Q;$++)if($!==X[$])return;Z.setIndices(null)}function rC1(Z,J){let X=[];for(let Y of Z.listSemantics())if(Y==="NORMAL"&&!J.has(Y))X.push(Y);else if(Y==="TANGENT"&&!J.has(Y))X.push(Y);else if(Y.startsWith("TEXCOORD_")&&!J.has(Y))X.push(Y);else if(Y.startsWith("COLOR_")&&Y!=="COLOR_0")X.push(Y);return X}function Bt(Z,J,X,Y=new Set){let Q=Z.getGraph().listChildEdges(X),K=new Set;for(let H of Q)if(H.getChild()instanceof rY)K.add(H.getName());for(let H of Q){let V=H.getName(),F=H.getChild();if(F instanceof E5){if(K.has(V.replace(/Info$/,"")))Y.add(`TEXCOORD_${F.getTexCoord()}`)}if(F instanceof rY&&V.match(/normalTexture/i))Y.add("TANGENT");if(F instanceof aK)Bt(Z,J,F,Y)}let G=X instanceof D7&&!X.getExtension("KHR_materials_unlit"),W=J.getMode()===C8.Mode.POINTS;if(G&&!W)Y.add("NORMAL");return Y}function tC1(Z,J){let X=aC1(Z),Y=new Set(X.map((W)=>W.getTexCoord())),$=Array.from(Y).sort(),Q=new Map($.map((W,H)=>[W,H])),K=new Map($.map((W,H)=>[`TEXCOORD_${W}`,`TEXCOORD_${H}`]));for(let W of X){let H=W.getTexCoord();W.setTexCoord(Q.get(H))}for(let W of J){let H=W.listSemantics().filter((V)=>V.startsWith("TEXCOORD_")).sort();G(W,H),W.listTargets().forEach((V)=>G(V,H))}function G(W,H){for(let V of H){let F=W.getAttribute(V);if(!F)continue;let z=K.get(V);if(z===V)continue;W.setAttribute(z,F),W.setAttribute(V,null)}}}async function eC1(Z){let J=Z.getRoot(),X=Z.getGraph(),Y=Z.getLogger(),Q=J.listTextures().map(async(K)=>{var G;let W=await JT1(K);if(!W)return;if(nC1(K)==="srgb")YT.convertSRGBToLinear(W,W);let H=K.getName()||K.getURI(),V=(G=K.getSize())==null?void 0:G.join("x"),F=sC1(K);for(let z of X.listParentEdges(K)){let q=z.getParent();if(q!==J&&ZT1(q,W,z.getName(),Y))z.dispose()}if(K.listParents().length===1)K.dispose(),Y.debug(`${zG}: Removed solid-color texture "${H}" (${V}px ${F.join(", ")})`)});await Promise.all(Q)}function ZT1(Z,J,X,Y){if(Z instanceof D7)switch(X){case"baseColorTexture":return Z.setBaseColorFactor(pC1(J,J,Z.getBaseColorFactor())),!0;case"emissiveTexture":return Z.setEmissiveFactor(xC1([0,0,0],J.slice(0,3),Z.getEmissiveFactor())),!0;case"occlusionTexture":return Math.abs(J[0]-1)<=tE;case"metallicRoughnessTexture":return Z.setRoughnessFactor(J[1]*Z.getRoughnessFactor()),Z.setMetallicFactor(J[2]*Z.getMetallicFactor()),!0;case"normalTexture":return qt(Ft(zt(),J,[0.5,0.5,1,1]))<=tE}return Y.warn(`${zG}: Detected single-color ${X} texture. Pruning ${X} not yet supported.`),!1}async function JT1(Z){let J=await XT1(Z);if(!J)return null;let X=[1/0,1/0,1/0,1/0],Y=[-1/0,-1/0,-1/0,-1/0],$=[0,0,0,0],[Q,K]=J.shape;for(let G=0;G<Q;G++){for(let W=0;W<K;W++)for(let H=0;H<4;H++)X[H]=Math.min(X[H],J.get(G,W,H)),Y[H]=Math.max(Y[H],J.get(G,W,H));if(qt(Ft($,Y,X))/255>tE)return null}return cC1($,mC1($,Y,X),0.00196078431372549)}async function XT1(Z){try{return await Jr(Z.getImage(),Z.getMimeType())}catch(J){return null}}var JX=4294967295;class wt{constructor(Z){this.attributes=[],this.u8=void 0,this.u32=void 0;let J=0;for(let X of $k(Z))J+=this._initAttribute(X);this.u8=new Uint8Array(J),this.u32=new Uint32Array(this.u8.buffer)}_initAttribute(Z){let J=Z.getArray(),X=new Uint8Array(J.buffer,J.byteOffset,J.byteLength),Y=Z.getElementSize()*Z.getComponentSize(),$=o0.padNumber(Y);return this.attributes.push({u8:X,byteStride:Y,paddedByteStride:$}),$}hash(Z){let J=0;for(let{u8:X,byteStride:Y,paddedByteStride:$}of this.attributes){for(let Q=0;Q<$;Q++)if(Q<Y)this.u8[J+Q]=X[Z*Y+Q];else this.u8[J+Q]=0;J+=$}return YT1(0,this.u32)}equal(Z,J){for(let{u8:X,byteStride:Y}of this.attributes)for(let $=0;$<Y;$++)if(X[Z*Y+$]!==X[J*Y+$])return!1;return!0}}function YT1(Z,J){for(let $=0,Q=J.length;$<Q;$++){let K=J[$];K=Math.imul(K,1540483477)>>>0,K=(K^K>>24)>>>0,K=Math.imul(K,1540483477)>>>0,Z=Math.imul(Z,1540483477)>>>0,Z=(Z^K)>>>0}return Z}function $T1(Z,J,X,Y,$=JX){let Q=J-1,G=X.hash(Y)&Q;for(let W=0;W<=Q;W++){let H=Z[G];if(H===$||X.equal(H,Y))return G;G=G+W+1&Q}throw new Error("Hash table full.")}var w6;(function(Z){Z.RENDER="render",Z.RENDER_CACHED="render-cached",Z.UPLOAD="upload",Z.UPLOAD_NAIVE="upload-naive",Z.DISTINCT="distinct",Z.DISTINCT_POSITION="distinct-position",Z.UNUSED="unused"})(w6||(w6={}));function YX(Z,J){let X=Z.getAttribute("POSITION"),Y=Z.getIndices();switch(J){case w6.RENDER:return Y?Y.getCount():X.getCount();case w6.RENDER_CACHED:return Y?new Set(Y.getArray()).size:X.getCount();case w6.UPLOAD_NAIVE:case w6.UPLOAD:return X.getCount();case w6.DISTINCT:case w6.DISTINCT_POSITION:return QT1(J);case w6.UNUSED:return Y?X.getCount()-new Set(Y.getArray()).size:0;default:return KT1(J)}}function QT1(Z){throw new Error(`Not implemented: ${Z}`)}function KT1(Z){throw new Error(`Unexpected value: ${Z}`)}function zV(Z,J,X){let Y=_6.fromGraph(Z.getGraph());if(!J||!X)[J,X]=GT1(Z);let $=Z.getIndices(),Q=$?$.getArray():null,K=YX(Z,w6.RENDER),G=Y.createAccessor(),W=K,H=Qk(W,X);for(let F=0;F<W;F++)H[F]=J[Q?Q[F]:F];Z.setIndices(G.setArray(H));let V=$k(Z);for(let F of Z.listAttributes()){let z=xZ(Y,F);eE(F,$,J,z,X),Z.swap(F,z)}for(let F of Z.listTargets())for(let z of F.listAttributes()){let q=xZ(Y,z);eE(z,$,J,q,X),F.swap(z,q)}if($&&$.listParents().length===1)$.dispose();for(let F of V)if(F.listParents().length===1)F.dispose();return Z}function eE(Z,J,X,Y,$){let Q=Z.getElementSize(),K=Z.getArray(),G=J?J.getArray():null,W=J?J.getCount():Z.getCount(),H=new K.constructor($*Q),V=new Uint8Array($);for(let F=0;F<W;F++){let z=G?G[F]:F,q=X[z];if(V[q])continue;for(let U=0;U<Q;U++)H[q*Q+U]=K[z*Q+U];V[q]=1}return Y.setArray(H)}function GT1(Z){let J=YX(Z,w6.UPLOAD),X=Z.getIndices(),Y=X?X.getArray():null;if(!X||!Y)return[OC1(J,1e6),J];let $=new Uint32Array(J).fill(JX),Q=0;for(let K=0;K<Y.length;K++){let G=Y[K];if($[G]===JX)$[G]=Q++}return[$,Q]}var Zk="weld",i2={overwrite:!0,cleanup:!0};function Kk(Z=i2){let J=A7(i2,Z);return $X(Zk,async(X)=>{let Y=X.getLogger();for(let $ of X.getRoot().listMeshes()){for(let Q of $.listPrimitives())if(t2(Q,J),YX(Q,w6.RENDER)===0)Q.dispose();if($.listPrimitives().length===0)$.dispose()}if(J.cleanup)await X.transform(r2({propertyTypes:[a.ACCESSOR,a.NODE],keepAttributes:!0,keepIndices:!0,keepLeaves:!1}),Ht({propertyTypes:[a.ACCESSOR]}));Y.debug(`${Zk}: Complete.`)})}function t2(Z,J=i2){let X=Z.getGraph(),$=_6.fromGraph(X).getLogger(),Q=FG({},i2,J);if(Z.getIndices()&&!Q.overwrite)return;if(Z.getMode()===C8.Mode.POINTS)return;let K=Z.getAttribute("POSITION").getCount(),G=Z.getIndices(),W=G==null?void 0:G.getArray(),H=G?G.getCount():K,V=new wt(Z),F=RC1(K+K/4),z=new Uint32Array(F).fill(JX),q=new Uint32Array(K).fill(JX),U=0;for(let B=0;B<H;B++){let L=W?W[B]:B;if(q[L]!==JX)continue;let w=$T1(z,F,V,L,JX),O=z[w];if(O===JX)z[w]=L,q[L]=U++;else q[L]=q[O]}$.debug(`${Zk}: ${s2(K,U)} vertices.`),zV(Z,q,U)}var{FLOAT:WT1}=x0.ComponentType;function jt(Z,J){let X=Z.getAttribute("POSITION");if(X)cr(J,X);let Y=Z.getAttribute("NORMAL");if(Y)lr(J,Y);let $=Z.getAttribute("TANGENT");if($)pr(J,$);for(let Q of Z.listTargets()){let K=Q.getAttribute("POSITION");if(K)cr(J,K);let G=Q.getAttribute("NORMAL");if(G)lr(J,G);let W=Q.getAttribute("TANGENT");if(W)pr(J,W)}if(TC1(J)<0)HT1(Z)}function cr(Z,J){let X=J.getComponentType(),Y=J.getNormalized(),$=J.getArray(),Q=X===WT1?$:new Float32Array($.length),K=o2();for(let G=0,W=J.getCount();G<W;G++){if(Y)K[0]=i0.decodeNormalizedInt($[G*3],X),K[1]=i0.decodeNormalizedInt($[G*3+1],X),K[2]=i0.decodeNormalizedInt($[G*3+2],X);else K[0]=$[G*3],K[1]=$[G*3+1],K[2]=$[G*3+2];vC1(K,K,Z),Q[G*3]=K[0],Q[G*3+1]=K[1],Q[G*3+2]=K[2]}J.setArray(Q).setNormalized(!1)}function lr(Z,J){let X=J.getArray(),Y=J.getNormalized(),$=J.getComponentType(),Q=EC1();kC1(Q,Z),_C1(Q,Q),IC1(Q,Q);let K=o2();for(let G=0,W=J.getCount();G<W;G++){if(Y)K[0]=i0.decodeNormalizedInt(X[G*3],$),K[1]=i0.decodeNormalizedInt(X[G*3+1],$),K[2]=i0.decodeNormalizedInt(X[G*3+2],$);else K[0]=X[G*3],K[1]=X[G*3+1],K[2]=X[G*3+2];if(AC1(K,K,Q),Wt(K,K),Y)X[G*3]=i0.decodeNormalizedInt(K[0],$),X[G*3+1]=i0.decodeNormalizedInt(K[1],$),X[G*3+2]=i0.decodeNormalizedInt(K[2],$);else X[G*3]=K[0],X[G*3+1]=K[1],X[G*3+2]=K[2]}}function pr(Z,J){let X=J.getArray(),Y=J.getNormalized(),$=J.getComponentType(),Q=o2();for(let K=0,G=J.getCount();K<G;K++){if(Y)Q[0]=i0.decodeNormalizedInt(X[K*4],$),Q[1]=i0.decodeNormalizedInt(X[K*4+1],$),Q[2]=i0.decodeNormalizedInt(X[K*4+2],$);else Q[0]=X[K*4],Q[1]=X[K*4+1],Q[2]=X[K*4+2];if(Q[0]=Z[0]*Q[0]+Z[4]*Q[1]+Z[8]*Q[2],Q[1]=Z[1]*Q[0]+Z[5]*Q[1]+Z[9]*Q[2],Q[2]=Z[2]*Q[0]+Z[6]*Q[1]+Z[10]*Q[2],Wt(Q,Q),Y)X[K*4]=i0.decodeNormalizedInt(Q[0],$),X[K*4+1]=i0.decodeNormalizedInt(Q[1],$),X[K*4+2]=i0.decodeNormalizedInt(Q[2],$);else X[K*4]=Q[0],X[K*4+1]=Q[1],X[K*4+2]=Q[2]}}function HT1(Z){if(Z.getMode()!==C8.Mode.TRIANGLES)return;if(!Z.getIndices())t2(Z);let J=Z.getIndices();for(let X=0,Y=J.getCount();X<Y;X+=3){let $=J.getScalar(X),Q=J.getScalar(X+2);J.setScalar(X,Q),J.setScalar(X+2,$)}}function VT1(Z,J){for(let X of Z.listPrimitives()){let Y=zT1(X,Z);if(X!==Y)Z.removePrimitive(X).addPrimitive(Y)}for(let X of Z.listPrimitives())zV(X),jt(X,J)}function zT1(Z,J){if(Z.listParents().some((Y)=>Y instanceof uH&&Y!==J))Z=Z.clone();for(let Y of Z.listTargets())if(Y.listParents().some((Q)=>Q instanceof C8&&Q!==Z))Z.removeTarget(Y).addTarget(Y.clone());return Z}var ir=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];function Ot(Z){let J=Z.getMesh(),X=Z.getMatrix();if(J&&!i0.eq(X,ir))VT1(J,X);for(let Y of Z.listChildren()){let $=Y.getMatrix();Gt($,$,X),Y.setMatrix($)}return Z.setMatrix(ir)}var{LINES:FT1,LINE_STRIP:qT1,LINE_LOOP:UT1,TRIANGLES:LT1,TRIANGLE_STRIP:BT1,TRIANGLE_FAN:wT1}=C8.Mode;function jT1(Z){let J=Z.getGraph(),X=_6.fromGraph(J);if(!Z.getIndices())t2(Z);let Y=Z.getIndices(),$=Y.getArray(),Q=Yt(Z),G=new iJ[Y.getComponentType()](Q*2),W=Z.getMode();if(W===qT1)for(let V=0;V<Q;V++)G[V*2]=$[V],G[V*2+1]=$[V+1];else if(W===UT1)for(let V=0;V<Q;V++)if(V<Q-1)G[V*2]=$[V],G[V*2+1]=$[V+1];else G[V*2]=$[V],G[V*2+1]=$[0];else throw new Error("Only LINE_STRIP and LINE_LOOP may be converted to LINES.");Z.setMode(FT1);let H=X.getRoot();if(Y.listParents().some((V)=>V!==H&&V!==Z))Z.setIndices(xZ(X,Y).setArray(G));else Y.setArray(G)}function Mt(Z){let J=Z.getGraph(),X=_6.fromGraph(J);if(!Z.getIndices())t2(Z);let Y=Z.getIndices(),$=Y.getArray(),Q=Yt(Z),G=new iJ[Y.getComponentType()](Q*3),W=Z.getMode();if(W===BT1)for(let V=0,F=$.length;V<F-2;V++)if(V%2)G[V*3]=$[V+1],G[V*3+1]=$[V],G[V*3+2]=$[V+2];else G[V*3]=$[V],G[V*3+1]=$[V+1],G[V*3+2]=$[V+2];else if(W===wT1)for(let V=0;V<Q;V++)G[V*3]=$[0],G[V*3+1]=$[V+1],G[V*3+2]=$[V+2];else throw new Error("Only TRIANGLE_STRIP and TRIANGLE_FAN may be converted to TRIANGLES.");Z.setMode(LT1);let H=X.getRoot();if(Y.listParents().some((V)=>V!==H&&V!==Z))Z.setIndices(xZ(X,Y).setArray(G));else Y.setArray(G)}var nr="dequantize",n2={pattern:/^((?!JOINTS_).)*$/};function Rt(Z=n2){let J=A7(n2,Z);return $X(nr,(X)=>{let Y=X.getLogger();for(let $ of X.getRoot().listMeshes())for(let Q of $.listPrimitives())OT1(Q,J);X.createExtension(HV).dispose(),Y.debug(`${nr}: Complete.`)})}function OT1(Z,J=n2){let X=A7(n2,J);for(let Y of Z.listSemantics())if(X.pattern.test(Y))Jk(Z.getAttribute(Y));for(let Y of Z.listTargets())for(let $ of Y.listSemantics())if(X.pattern.test($))Jk(Y.getAttribute($))}function Jk(Z){let J=Z.getArray();if(!J)return;let X=a2(J,Z.getComponentType(),Z.getNormalized());Z.setArray(X).setNormalized(!1)}function a2(Z,J,X){let Y=new Float32Array(Z.length);for(let $=0,Q=Z.length;$<Q;$++)if(X)Y[$]=i0.decodeNormalizedInt(Z[$],J);else Y[$]=Z[$];return Y}var{TEXTURE_INFO:Nt,ROOT:yS6}=a;function Pt(Z){let J=new _6().setLogger(Z.getLogger()),X=Gk(J,Z);return MT1(J,Z,X),J.getRoot().copy(Z.getRoot(),X),J}function MT1(Z,J,X){X||(X=Gk(Z,J));for(let Y of J.getRoot().listExtensionsUsed()){let $=Z.createExtension(Y.constructor);if(Y.isRequired())$.setRequired(!0)}return RT1(Z,J,NT1(J),X)}function RT1(Z,J,X,Y){Y||(Y=Gk(Z,J));let $=new Map;for(let Q of X)if(!$.has(Q)&&Q.propertyType!==Nt)$.set(Q,Y(Q));for(let[Q,K]of $.entries())K.copy(Q,Y);return $}function Gk(Z,J){let X=new Map([[J.getRoot(),Z.getRoot()]]);return(Y)=>{if(Y.propertyType===Nt)return Y;let $=X.get(Y);if(!$)$=new Y.constructor(Z.getGraph()),X.set(Y,$);return $}}function NT1(Z){let J=new Set;for(let X of Z.getGraph().listEdges())J.add(X.getChild());return Array.from(J)}var sE="flatten",ar={cleanup:!0};function Dt(Z=ar){let J=A7(ar,Z);return $X(sE,async(X)=>{let Y=X.getRoot(),$=X.getLogger(),Q=new Set;for(let H of Y.listSkins())for(let V of H.listJoints())Q.add(V);let K=new Set;for(let H of Y.listAnimations())for(let V of H.listChannels()){let F=V.getTargetNode();if(F&&V.getTargetPath()!=="weights")K.add(F)}let G=new Set,W=new Set;for(let H of Y.listScenes())H.traverse((V)=>{let F=V.getParentNode();if(!F)return;if(Q.has(F)||G.has(F))G.add(V);if(K.has(F)||W.has(F))W.add(V)});for(let H of Y.listScenes())H.traverse((V)=>{if(K.has(V))return;if(G.has(V))return;if(W.has(V))return;DC1(V)});if(K.size)$.debug(`${sE}: Flattening node hierarchies with TRS animation not yet supported.`);if(J.cleanup)await X.transform(r2({propertyTypes:[a.NODE],keepLeaves:!1}));$.debug(`${sE}: Complete.`)})}function Ct(Z){return XT(Z)}var PT1={skipValidation:!1},sr=4294967295,{LINE_STRIP:DT1,LINE_LOOP:CT1,TRIANGLE_STRIP:TT1,TRIANGLE_FAN:ET1}=C8.Mode;function kT1(Z,J={}){let X=A7(PT1,J),Y=Z[0],$=_6.fromGraph(Y.getGraph());if(!X.skipValidation&&new Set(Z.map(Qt)).size>1)throw new Error("Requires >=2 Primitives, sharing the same Material and Mode, with compatible vertex attributes and indices.");for(let q of Z)switch(q.getMode()){case DT1:case CT1:jT1(q);break;case TT1:case ET1:Mt(q);break}let Q=[],K=new Uint32Array(Z.length),G=0,W=0;for(let q=0;q<Z.length;q++){let U=Z[q],B=U.getIndices(),L=U.getAttribute("POSITION").getCount(),w=B?B.getArray():null,O=B?B.getCount():L,M=new Uint32Array(L).fill(sr);for(let R=0;R<O;R++){let D=w?w[R]:R;if(M[D]===sr)M[D]=G++,K[q]++}Q.push(M),W+=O}let H=$.createPrimitive().setMode(Y.getMode()).setMaterial(Y.getMaterial());for(let q of Y.listSemantics()){let U=Y.getAttribute(q),B=iJ[U.getComponentType()],L=xZ($,U).setArray(new B(G*U.getElementSize()));H.setAttribute(q,L)}let V=Y.getIndices(),F=V?xZ($,V).setArray(Qk(W,G)):null;H.setIndices(F);let z=0;for(let q=0;q<Q.length;q++){let U=Z[q],B=U.getIndices(),L=B?B.getCount():-1,w=Q[q];if(B&&F)_T1(B,w,F,z),z+=L;for(let O of H.listSemantics()){let M=U.getAttribute(O),R=H.getAttribute(O);IT1(M,B,w,R)}}return H}function IT1(Z,J,X,Y){let $=Z.getElementSize(),Q=J?J.getArray():null,K=Z.getCount(),G=Z.getArray(),W=Y.getArray(),H=new Uint8Array(Z.getCount());for(let V=0,F=J?J.getCount():K;V<F;V++){let z=Q?Q[V]:V,q=X[z];if(H[q])continue;for(let U=0;U<$;U++)W[q*$+U]=G[z*$+U];H[q]=1}}function _T1(Z,J,X,Y){let $=Z.getCount(),Q=Z.getArray(),K=X.getArray();for(let G=0;G<$;G++){let W=Q[G],H=J[W];K[Y+G]=H}}var Xk="join",{ROOT:ST1,NODE:vT1,MESH:AT1,PRIMITIVE:xT1,ACCESSOR:hT1}=a,oE=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],or={keepMeshes:!1,keepNamed:!1,cleanup:!0};function Tt(Z=or){let J=A7(or,Z);return $X(Xk,async(X)=>{let Y=X.getRoot(),$=X.getLogger();for(let Q of Y.listScenes())rr(X,Q,J),Q.traverse((K)=>rr(X,K,J));if(J.cleanup)await X.transform(r2({propertyTypes:[vT1,AT1,xT1,hT1],keepAttributes:!0,keepIndices:!0,keepLeaves:!1}));$.debug(`${Xk}: Complete.`)})}function rr(Z,J,X){let Y=Z.getLogger(),$={},Q=J.listChildren();for(let W=0;W<Q.length;W++){let H=Q[W];if(H.listParents().some((z)=>z instanceof sY))continue;let F=H.getMesh();if(!F)continue;if(H.getExtension("EXT_mesh_gpu_instancing"))continue;if(H.getSkin())continue;for(let z of F.listPrimitives()){if(z.listTargets().length>0)continue;let q=z.getMaterial();if(q&&q.getExtension("KHR_materials_volume"))continue;zV(z),yT1(z);let U=Qt(z),B=F.getName()||H.getName();if(X.keepMeshes||X.keepNamed&&B)U+=`|${W}`;if(!(U in $))$[U]={prims:[],primMeshes:[],primNodes:[],dstNode:H,dstMesh:void 0};let L=$[U];L.prims.push(z),L.primNodes.push(H)}}let K=Object.values($).filter(({prims:W})=>W.length>1),G=new Set(K.flatMap((W)=>W.primNodes));for(let W of G){let H=W.getMesh();if(H.listParents().some((F)=>{return F.propertyType!==ST1&&W!==F}))W.setMesh(H.clone())}for(let W of K){let{dstNode:H,primNodes:V}=W;W.dstMesh=H.getMesh(),W.primMeshes=V.map((F)=>F.getMesh())}for(let W of K){let{prims:H,primNodes:V,primMeshes:F,dstNode:z,dstMesh:q}=W,U=z.getMatrix();for(let w=0;w<H.length;w++){let O=V[w],M=F[w],R=H[w];if(M.removePrimitive(R),MC1(R))R=H[w]=fT1(H[w]);if(O!==z)Gt(oE,CC1(oE,U),O.getMatrix()),jt(R,oE)}let B=kT1(H),L=B.listAttributes()[0].getCount();q.addPrimitive(B),Y.debug(`${Xk}: Joined Primitives (${H.length}) containing ${rE(L)} vertices under Node "${z.getName()}".`)}}function fT1(Z){let J=Z.clone();for(let Y of J.listSemantics())J.setAttribute(Y,J.getAttribute(Y).clone());let X=J.getIndices();if(X)J.setIndices(X.clone());return J}function yT1(Z){for(let J of["POSITION","NORMAL","TANGENT"]){let X=Z.getAttribute(J);if(X)Jk(X)}}var{TRANSLATION:bS6,ROTATION:gS6,SCALE:mS6,WEIGHTS:uS6}=sY.TargetPath;var bT1={pattern:/.*/,quantizationVolume:"mesh",quantizePosition:14,quantizeNormal:10,quantizeTexcoord:12,quantizeColor:8,quantizeWeight:8,quantizeGeneric:12,normalizeWeights:!0,cleanup:!0};var dS6=FG({level:"high"},bT1);var gT1="unweld";function mT1(Z,J=new Map){let X=Z.getIndices();if(!X)return;let Y=Z.getGraph(),$=_6.fromGraph(Y),Q=$.getLogger(),K=Z.getAttribute("POSITION").getCount();for(let W of Z.listAttributes())if(Z.swap(W,tr($,W,X,J)),W.listParents().length===1)W.dispose();for(let W of Z.listTargets())for(let H of W.listAttributes())if(W.swap(H,tr($,H,X,J)),H.listParents().length===1)H.dispose();let G=Z.getAttribute("POSITION").getCount();if(Q.debug(`${gT1}: ${s2(K,G)} vertices.`),Z.setIndices(null),X.listParents().length===1)X.dispose()}function tr(Z,J,X,Y){if(Y.has(J)&&Y.get(J).has(X))return Y.get(J).get(X);let $=J.getArray(),K=new $.constructor(X.getCount()*J.getElementSize()),G=X.getArray(),W=J.getElementSize();for(let V=0,F=X.getCount();V<F;V++)for(let z=0;z<W;z++)K[V*W+z]=$[G[V]*W+z];if(!Y.has(J))Y.set(J,new Map);let H=xZ(Z,J).setArray(K);return Y.get(J).set(X,H),H}var er;(function(Z){Z[Z.STEP=0]="STEP",Z[Z.LERP=1]="LERP",Z[Z.SLERP=2]="SLERP"})(er||(er={}));var uT1=0.000001;function dT1(Z,J,X,Y=0.0001){let $=J.length/Z.length,Q=new Array($).fill(0),K=new Array($).fill(0),G=new Array($).fill(0),W=new Array($).fill(0),H=Z.length-1,V=1;for(let F=1;F<H;++F){let z=Z[V-1],q=Z[F],U=Z[F+1],B=(q-z)/(U-z),L=!1;if(q!==U&&(F!==1||q!==Z[0])){if(VV(J,V-1,W),VV(J,F,K),VV(J,F+1,G),X==="slerp"){let w=pT1(Q,W,G,B),O=Jt(W,K)+Jt(K,G);L=!p2(K,w,Y)||O+Number.EPSILON>=Math.PI}else if(X==="lerp"){let w=lT1(Q,W,G,B);L=!p2(K,w,Y)}else if(X==="step")L=!p2(K,W)||!p2(K,G)}if(L){if(F!==V)Z[V]=Z[F],Zt(J,V,VV(J,F,Q));V++}}if(H>0)Z[V]=Z[H],Zt(J,V,VV(J,H,Q)),V++;return V}function VV(Z,J,X){for(let Y=0,$=X.length;Y<$;Y++)X[Y]=Z[J*$+Y];return X}function Zt(Z,J,X){for(let Y=0,$=X.length;Y<$;Y++)Z[J*$+Y]=X[Y]}function p2(Z,J,X=0){if(Z.length!==J.length)return!1;for(let Y=0;Y<Z.length;Y++)if(Math.abs(Z[Y]-J[Y])>X)return!1;return!0}function cT1(Z,J,X){return Z*(1-X)+J*X}function lT1(Z,J,X,Y){for(let $=0;$<J.length;$++)Z[$]=cT1(J[$],X[$],Y);return Z}function pT1(Z,J,X,Y){let $=J[0],Q=J[1],K=J[2],G=J[3],W=X[0],H=X[1],V=X[2],F=X[3],z,q,U,B,L;if(q=$*W+Q*H+K*V+G*F,q<0)q=-q,W=-W,H=-H,V=-V,F=-F;if(1-q>uT1)z=Math.acos(q),U=Math.sin(z),B=Math.sin((1-Y)*z)/U,L=Math.sin(Y*z)/U;else B=1-Y,L=Y;return Z[0]=B*$+L*W,Z[1]=B*Q+L*H,Z[2]=B*K+L*V,Z[3]=B*G+L*F,Z}function Jt(Z,J){let X=iT1(Z,J);return Math.acos(2*X*X-1)}function iT1(Z,J){return Z[0]*J[0]+Z[1]*J[1]+Z[2]*J[2]+Z[3]*J[3]}var cS6=new Float32Array(0),lS6={ready:Promise.resolve(),resample:dT1,tolerance:0.0001,cleanup:!0};var j$="simplify",{POINTS:Et,LINES:nT1,LINE_STRIP:aT1,LINE_LOOP:sT1,TRIANGLES:oT1,TRIANGLE_STRIP:kt,TRIANGLE_FAN:It}=C8.Mode,_t={ratio:0,error:0.0001,lockBorder:!1,cleanup:!0};function St(Z){let J=A7(_t,Z),X=J.simplifier;if(!X)throw new Error(`${j$}: simplifier dependency required — install "meshoptimizer".`);return $X(j$,async(Y)=>{let $=Y.getLogger();await X.ready,await Y.transform(Kk({overwrite:!1,cleanup:J.cleanup}));let Q=0;for(let K of Y.getRoot().listMeshes()){for(let G of K.listPrimitives()){let W=G.getMode();if(W===oT1||W===kt||W===It){if(Xt(G,J),YX(G,w6.RENDER)===0)G.dispose()}else if(G.getMode()===Et&&!!X.simplifyPoints){if(Xt(G,J),YX(G,w6.RENDER)===0)G.dispose()}else Q++}if(K.listPrimitives().length===0)K.dispose()}if(Q>0)$.warn(`${j$}: Skipping simplification of ${Q} primitives: Unsupported draw mode.`);if(J.cleanup)await Y.transform(r2({propertyTypes:[a.ACCESSOR,a.NODE],keepAttributes:!0,keepIndices:!0,keepLeaves:!1}),Ht({propertyTypes:[a.ACCESSOR]}));$.debug(`${j$}: Complete.`)})}function Xt(Z,J){let X=FG({},_t,J),Y=X.simplifier,$=Z.getGraph(),Q=_6.fromGraph($),K=Q.getLogger();switch(Z.getMode()){case Et:return rT1(Q,Z,X);case nT1:case aT1:case sT1:return K.warn(`${j$}: Skipping primitive simplification: Unsupported draw mode.`),Z;case kt:case It:Mt(Z);break}let G=YX(Z,w6.UPLOAD),W=YX(Z,w6.RENDER);if(W<G/2)zV(Z);let H=Z.getAttribute("POSITION"),V=Z.getIndices(),F=H.getArray(),z=V.getArray();if(!(F instanceof Float32Array))F=a2(F,H.getComponentType(),H.getNormalized());if(!(z instanceof Uint32Array))z=new Uint32Array(z);let q=Math.floor(X.ratio*W/3)*3,U=X.lockBorder?["LockBorder"]:[],[B,L]=Y.simplify(z,F,3,q,X.error,U);if(Z.setIndices(xZ(Q,V).setArray(B)),V.listParents().length===1)V.dispose();zV(Z);let w=YX(Z,w6.UPLOAD);if(w<=65534)Z.getIndices().setArray(new Uint16Array(Z.getIndices().getArray()));return K.debug(`${j$}: ${s2(G,w)} vertices, error: ${L.toFixed(4)}.`),Z}function rT1(Z,J,X){let Y=X.simplifier,$=Z.getLogger();if(J.getIndices())mT1(J);let K=J.getAttribute("POSITION"),G=J.getAttribute("COLOR_0"),W=K.getCount(),H=K.getArray(),V=G?G.getArray():void 0,F=G?G.getComponentSize():void 0;if(!(H instanceof Float32Array))H=a2(H,K.getComponentType(),K.getNormalized());if(V&&!(V instanceof Float32Array))V=a2(V,K.getComponentType(),K.getNormalized());Y.useExperimentalFeatures=!0;let z=Math.floor(X.ratio*W),q=Y.simplifyPoints(H,3,z,V,F);Y.useExperimentalFeatures=!1;let[U,B]=Y.compactMesh(q);$.debug(`${j$}: ${s2(K.getCount(),B)} vertices.`);for(let L of $k(J)){let w=xZ(Z,L);if(eE(L,null,U,w,B),wC1(J,L,w),L.listParents().length===1)L.dispose()}return J}var Yk;(function(Z){Z.LANCZOS3="lanczos3",Z.LANCZOS2="lanczos2"})(Yk||(Yk={}));var pS6={resizeFilter:Yk.LANCZOS3,pattern:void 0,formats:void 0,slots:void 0,quality:void 0,effort:void 0,lossless:!1,nearLossless:!1,limitInputPixels:!0};var bt=r(yt(),1);var UG={OPTIMIZED_DIR:".optimized",CHECKSUM_EXT:".md5",DIRECTORIES:[(()=>{try{return $9.dirname(m.resolve("@hytopia.com/assets"))}catch{return null}})(),$9.resolve(process.cwd(),"assets")].filter(Boolean),OPTIMIZER_RUNS:[{suffix:"",options:["--compress","false","--instance","false","--simplify","false"]},{suffix:"-named-nodes",options:["--compress","false","--instance","false","--simplify","false","--join","true","--join-named","false"]}]};class S5{static instance=new S5;optimize=!0;optimizeEveryStart=!1;_modelUriDocuments=new Map;_modelUriBoundingBoxes=new Map;_modelUriNodeNames=new Map;_modelUriTrimeshes=new Map;constructor(){}async preloadModels(){let Z=await this._getAbsoluteModelPaths();console.log(`ModelRegistry.preloadModels(): Preloading ${Z.length} models...`);for(let J of Z){if(this.optimize)await this._resolveOptimizedModelPath(J);await this._loadModelData(J)}console.log(`ModelRegistry.preloadModels(): Preloaded ${Z.length} models!`)}getAnimationNames(Z){let J=this._modelUriDocuments.get(Z);if(!J)d.fatalError(`ModelRegistry.getAnimationNames(): Model ${Z} not found!`);return J.getRoot().listAnimations().map((Y)=>Y.getName())}getBoundingBox(Z){let J=this._modelUriBoundingBoxes.get(Z);if(!J)d.fatalError(`ModelRegistry.getBoundingBox(): Model ${Z} not found!`);return J}getDepth(Z){let J=this.getBoundingBox(Z);return J.max.z-J.min.z}getHeight(Z){let J=this.getBoundingBox(Z);return J.max.y-J.min.y}getNodeNames(Z){let J=this._modelUriNodeNames.get(Z);if(!J)d.fatalError(`ModelRegistry.getNodeNames(): Model ${Z} not found!`);return J}getTrimesh(Z,J=1){let X=this._modelUriTrimeshes.get(Z);if(!X){d.error(`ModelRegistry.getTrimesh(): Model ${Z} not found!`);return}let Y=X.vertices;if(J!==1){Y=new Float32Array(Y.length);for(let $=0;$<Y.length;$++)Y[$]=X.vertices[$]*J}return{vertices:Y,indices:X.indices}}getWidth(Z){let J=this.getBoundingBox(Z);return J.max.x-J.min.x}modelHasNode(Z,J){let X=this._modelUriNodeNames.get(Z);if(!X)d.fatalError(`ModelRegistry.modelHasNode(): Model ${Z} not found!`);return X.includes(J)}_absoluteModelPathToModelUri(Z){let J=$9.normalize(Z);for(let X of UG.DIRECTORIES){let Y=$9.normalize(X);if(J.startsWith(Y))return $9.relative(Y,J).replace(/\\/g,"/")}return $9.basename(J)}async _getAbsoluteModelPaths(){let Z=[];for(let J of UG.DIRECTORIES){let X=$9.resolve(process.cwd(),J);if(!QX.existsSync(X))continue;let Y=await gB("**/*.{gltf,glb}",{cwd:X,follow:!0});for(let $ of Y)Z.push($9.join(X,$))}return Z}async _loadModelData(Z){let J=await new WT().read(Z),X=Ct(J.getRoot().listScenes()[0]),Y=J.getRoot().listNodes().map((Q)=>Q.getName()),$=this._absoluteModelPathToModelUri(Z);this._modelUriDocuments.set($,J),this._modelUriBoundingBoxes.set($,{min:{x:X.min[0],y:X.min[1],z:X.min[2]},max:{x:X.max[0],y:X.max[1],z:X.max[2]}}),this._modelUriNodeNames.set($,Y),this._modelUriTrimeshes.set($,await this._buildTrimesh($))}async _resolveOptimizedModelPath(Z){let J=this._buildOptimizedModelPath(Z);if(!this.optimizeEveryStart&&this._isOptimizedVersionValid(Z))return J;return await this._optimizeModel(Z,J)}_isOptimizedVersionValid(Z){let J=`${this._buildOptimizedModelPath(Z)}${UG.CHECKSUM_EXT}`;if(!QX.existsSync(J))return!1;let X=this._calculateChecksum(Z),Y=QX.readFileSync(J,"utf8");return X===Y}_calculateChecksum(Z){if(!QX.existsSync(Z))return"";let J=QX.readFileSync(Z);return XE1.createHash("sha256").update(J.toString("base64")).digest("hex")}_buildOptimizedModelPath(Z){let J=$9.basename(Z),X=J.replace(/\.[^/.]+$/,""),Y=$9.dirname(Z),$=$9.join(Y,UG.OPTIMIZED_DIR,X);return $9.join($,J)}async _buildTrimesh(Z,J=1,X=0.001){let Y=this._modelUriDocuments.get(Z);if(!Y)d.fatalError(`ModelRegistry._buildTrimesh(): Model ${Z} not found!`);let $=Pt(Y);$.setLogger(new k5(gH.WARN)),await $.transform(Kt({pivot:"center"}),Dt(),Tt(),Kk(),St({simplifier:bt.MeshoptSimplifier,ratio:J,error:X}),Rt());for(let H of $.getRoot().listScenes())for(let V of H.listChildren())Ot(V);let Q=$.getRoot().listMeshes()[0];if(!Q){d.error(`ModelRegistry._buildTrimesh(): Model ${Z} has no root mesh!`);return}let K=Q.listPrimitives()[0];if(!K){d.error(`ModelRegistry._buildTrimesh(): Model ${Z} has no root primitive!`);return}let G=K.getAttribute("POSITION"),W=K.getIndices();if(!G||!W){d.error(`ModelRegistry._buildTrimesh(): Model ${Z} missing required geometry data!`);return}return{vertices:G.getArray(),indices:W.getArray()}}async _optimizeModel(Z,J){let X=$9.dirname(J);QX.rmSync(X,{recursive:!0,force:!0}),QX.mkdirSync(X,{recursive:!0}),console.log(`ModelRegistry: Optimizing model ${this._absoluteModelPathToModelUri(Z)}...`);for(let Y of UG.OPTIMIZER_RUNS){let $=J.replace(/(\.[^/.]+)$/,`${Y.suffix}$1`),{stderr:Q}=await bi("npx",["gltf-transform","optimize",Z,$,...Y.options]);if(Q)return d.warning(`ModelRegistry._optimizeModel(): Error optimizing model ${this._absoluteModelPathToModelUri(Z)}, defaulting to unoptimized model. Error: ${Q}`),Z}return QX.writeFileSync(`${J}${UG.CHECKSUM_EXT}`,this._calculateChecksum(Z)),J}}var hZ=r(KH(),1);var BV;(($)=>{$.DYNAMIC="dynamic";$.FIXED="fixed";$.KINEMATIC_POSITION="kinematic_position";$.KINEMATIC_VELOCITY="kinematic_velocity"})(BV||={});var Fk=0.001,gt="dynamic";class O$ extends O0{_additionalMass=0;_colliders=new Set;_explicitSleep=!1;_enabledPositions={x:!0,y:!0,z:!0};_enabledRotations={x:!0,y:!0,z:!0};_rigidBody;_rigidBodyDesc;_rigidBodyType;_simulation;constructor(Z){super();Z.type??=gt,this._rigidBodyDesc=this._createRigidBodyDesc(Z),this._rigidBodyType=Z.type,this._applyRigidBodyOptions(Z),this._autoAddToSimulation(Z)}get additionalMass(){if(!this._requireNotRemoved("additionalMass"))return 0;return this._additionalMass}get additionalSolverIterations(){if(!this._requireNotRemoved("additionalSolverIterations"))return 0;return this._rigidBody?this._rigidBody.additionalSolverIterations():this._rigidBodyDesc.additionalSolverIterations}get angularDamping(){if(!this._requireNotRemoved("angularDamping"))return 0;return this._rigidBody?this._rigidBody.angularDamping():this._rigidBodyDesc.angularDamping}get angularVelocity(){if(!this._requireNotRemoved("angularVelocity"))return{x:0,y:0,z:0};return this._rigidBody?this._rigidBody.angvel():this._rigidBodyDesc.angvel}get colliders(){return this._colliders}get dominanceGroup(){if(!this._requireNotRemoved("dominanceGroup"))return 0;return this._rigidBody?this._rigidBody.dominanceGroup():this._rigidBodyDesc.dominanceGroup}get directionFromRotation(){let{x:Z,y:J,z:X,w:Y}=this.rotation;return{x:-2*(Z*X+Y*J),y:-2*(J*X-Y*Z),z:-(1-2*(Z*Z+J*J))}}get effectiveAngularInertia(){if(!this._requireNotRemoved("effectiveAngularInertia"))return;return this._rigidBody?this._rigidBody.effectiveAngularInertia():void 0}get effectiveInverseMass(){if(!this._requireNotRemoved("effectiveInverseMass"))return;return this._rigidBody?this._rigidBody.effectiveInvMass():void 0}get effectiveWorldInversePrincipalAngularInertiaSqrt(){if(!this._requireNotRemoved("effectiveWorldInversePrincipalAngularInertiaSqrt"))return;return this._rigidBody?this._rigidBody.effectiveWorldInvInertiaSqrt():void 0}get enabledRotations(){if(!this._requireNotRemoved("enabledRotations"))return{x:!0,y:!0,z:!0};return this._enabledRotations}get enabledPositions(){if(!this._requireNotRemoved("enabledPositions"))return{x:!0,y:!0,z:!0};return this._enabledPositions}get gravityScale(){if(!this._requireNotRemoved("gravityScale"))return 0;return this._rigidBody?this._rigidBody.gravityScale():this._rigidBodyDesc.gravityScale}get inverseMass(){if(!this._requireNotRemoved("inverseMass"))return;return this._rigidBody?this._rigidBody.invMass():void 0}get inversePrincipalAngularInertiaSqrt(){if(!this._requireNotRemoved("inversePrincipalAngularInertiaSqrt"))return;return this._rigidBody?this._rigidBody.invPrincipalInertiaSqrt():void 0}get isCcdEnabled(){if(!this._requireNotRemoved("isCcdEnabled"))return!1;return this._rigidBody?this._rigidBody.isCcdEnabled():this._rigidBodyDesc.ccdEnabled}get isDynamic(){if(!this._requireNotRemoved("isDynamic"))return!1;return this._rigidBodyType==="dynamic"}get isEnabled(){if(!this._requireNotRemoved("isEnabled"))return!1;return this._rigidBody?this._rigidBody.isEnabled():this._rigidBodyDesc.enabled}get isFixed(){if(!this._requireNotRemoved("isFixed"))return!1;return this._rigidBodyType==="fixed"}get isKinematic(){if(!this._requireNotRemoved("isKinematic"))return!1;return["kinematic_position","kinematic_velocity"].includes(this._rigidBodyType)}get isKinematicPositionBased(){if(!this._requireNotRemoved("isKinematicPositionBased"))return!1;return this._rigidBodyType==="kinematic_position"}get isKinematicVelocityBased(){if(!this._requireNotRemoved("isKinematicVelocityBased"))return!1;return this._rigidBodyType==="kinematic_velocity"}get isMoving(){if(!this._requireNotRemoved("isMoving"))return!1;return this._rigidBody?this._rigidBody.isMoving():!1}get isRemoved(){return!this._rigidBody&&!this._rigidBodyDesc}get isSimulated(){if(!this._requireNotRemoved("isSimulated"))return!1;return this._rigidBody?!0:!1}get isSleeping(){if(!this._requireNotRemoved("isSleeping"))return!1;return this._rigidBody?this._rigidBody.isSleeping():this._rigidBodyDesc.sleeping}get linearDamping(){if(!this._requireNotRemoved("linearDamping"))return 0;return this._rigidBody?this._rigidBody.linearDamping():this._rigidBodyDesc.linearDamping}get linearVelocity(){if(!this._requireNotRemoved("linearVelocity"))return{x:0,y:0,z:0};return this._rigidBody?this._rigidBody.linvel():this._rigidBodyDesc.linvel}get localCenterOfMass(){if(!this._requireNotRemoved("localCenterOfMass"))return{x:0,y:0,z:0};return this._rigidBody?this._rigidBody.localCom():this._rigidBodyDesc.centerOfMass}get mass(){if(!this._requireNotRemoved("mass"))return 0;return this._rigidBody?this._rigidBody.mass():this._rigidBodyDesc.mass}get nextKinematicRotation(){if(!this._requireNotRemoved("nextKinematicRotation"))return{x:0,y:0,z:0,w:1};return this._rigidBody?this._rigidBody.nextRotation():this._rigidBodyDesc.rotation}get nextKinematicPosition(){if(!this._requireNotRemoved("nextKinematicPosition"))return{x:0,y:0,z:0};return this._rigidBody?this._rigidBody.nextTranslation():this._rigidBodyDesc.translation}get numColliders(){return this._colliders.size}get principalAngularInertia(){if(!this._requireNotRemoved("principalAngularInertia"))return{x:0,y:0,z:0};return this._rigidBody?this._rigidBody.principalInertia():this._rigidBodyDesc.principalAngularInertia}get principalAngularInertiaLocalFrame(){if(!this._requireNotRemoved("principalAngularInertiaLocalFrame"))return;return this._rigidBody?this._rigidBody.principalInertiaLocalFrame():void 0}get position(){if(!this._requireNotRemoved("position"))return{x:0,y:0,z:0};return this._rigidBody?this._rigidBody.translation():this._rigidBodyDesc.translation}get rawRigidBody(){if(!this._requireNotRemoved("rawRigidBody"))return;return this._rigidBody}get rotation(){if(!this._requireNotRemoved("rotation"))return{x:0,y:0,z:0,w:1};return this._rigidBody?this._rigidBody.rotation():this._rigidBodyDesc.rotation}get softCcdPrediction(){if(!this._requireNotRemoved("softCcdPrediction"))return 0;return this._rigidBody?this._rigidBody.softCcdPrediction():this._rigidBodyDesc.softCcdPrediction}get type(){if(!this._requireNotRemoved("type"))return"dynamic";return this._rigidBodyType}get worldCenterOfMass(){if(!this._requireNotRemoved("worldCenterOfMass"))return;return this._rigidBody?this._rigidBody.worldCom():void 0}setAdditionalMass(Z){if(!this._requireDynamic("setAdditionalMass"))return;if(!this._requireNotRemoved("setAdditionalMass"))return;this._rigidBody?this._rigidBody.setAdditionalMass(Z,!this._explicitSleep):this._rigidBodyDesc.setAdditionalMass(Z)}setAdditionalMassProperties(Z){if(!this._requireDynamic("setAdditionalMassProperties"))return;if(!this._requireNotRemoved("setAdditionalMassProperties"))return;let{additionalMass:J,centerOfMass:X,principalAngularInertia:Y,principalAngularInertiaLocalFrame:$}=Z;this._rigidBody?this._rigidBody.setAdditionalMassProperties(J,X,Y,$,!this._explicitSleep):this._rigidBodyDesc.setAdditionalMassProperties(J,X,Y,$)}setAdditionalSolverIterations(Z){if(!this._requireDynamic("setAdditionalSolverIterations"))return;if(!this._requireNotRemoved("setAdditionalSolverIterations"))return;this._rigidBody?this._rigidBody.setAdditionalSolverIterations(Z):this._rigidBodyDesc.setAdditionalSolverIterations(Z)}setAngularDamping(Z){if(!this._requireDynamic("setAngularDamping"))return;if(!this._requireNotRemoved("setAngularDamping"))return;this._rigidBody?this._rigidBody.setAngularDamping(Z):this._rigidBodyDesc.setAngularDamping(Z)}setAngularVelocity(Z){if(!this._requireNotKinematicPositionBased("setAngularVelocity"))return;if(!this._requireNotRemoved("setAngularVelocity"))return;this._rigidBody?this._rigidBody.setAngvel(Z,!this._explicitSleep):this._rigidBodyDesc.setAngvel(Z)}setCcdEnabled(Z){if(!this._requireDynamic("setCcdEnabled"))return;if(!this._requireNotRemoved("setCcdEnabled"))return;this._rigidBody?this._rigidBody.enableCcd(Z):this._rigidBodyDesc.setCcdEnabled(Z)}setDominanceGroup(Z){if(!this._requireDynamic("setDominanceGroup"))return;if(!this._requireNotRemoved("setDominanceGroup"))return;this._rigidBody?this._rigidBody.setDominanceGroup(Z):this._rigidBodyDesc.setDominanceGroup(Z)}setEnabled(Z){if(!this._requireNotRemoved("setEnabled"))return;this._rigidBody?this._rigidBody.setEnabled(Z):this._rigidBodyDesc.setEnabled(Z)}setEnabledPositions(Z){if(!this._requireDynamic("setEnabledPositions"))return;if(!this._requireNotRemoved("setEnabledPositions"))return;this._rigidBody?this._rigidBody.setEnabledTranslations(Z.x,Z.y,Z.z,!this._explicitSleep):this._rigidBodyDesc.enabledTranslations(Z.x,Z.y,Z.z),this._enabledPositions=Z}setEnabledRotations(Z){if(!this._requireDynamic("setEnabledRotations"))return;if(!this._requireNotRemoved("setEnabledRotations"))return;this._rigidBody?this._rigidBody.setEnabledRotations(Z.x,Z.y,Z.z,!this._explicitSleep):this._rigidBodyDesc.enabledRotations(Z.x,Z.y,Z.z),this._enabledRotations=Z}setGravityScale(Z){if(!this._requireDynamic("setGravityScale"))return;if(!this._requireNotRemoved("setGravityScale"))return;this._rigidBody?this._rigidBody.setGravityScale(Z,!this._explicitSleep):this._rigidBodyDesc.setGravityScale(Z)}setLinearDamping(Z){if(!this._requireDynamic("setLinearDamping"))return;if(!this._requireNotRemoved("setLinearDamping"))return;this._rigidBody?this._rigidBody.setLinearDamping(Z):this._rigidBodyDesc.setLinearDamping(Z)}setLinearVelocity(Z){if(!this._requireNotKinematicPositionBased("setLinearVelocity"))return;if(!this._requireNotRemoved("setLinearVelocity"))return;this._rigidBody?this._rigidBody.setLinvel(Z,!this._explicitSleep):this._rigidBodyDesc.setLinvel(Z.x,Z.y,Z.z)}setNextKinematicRotation(Z){if(!this._requireKinematic("setNextKinematicRotation"))return;if(!this._requireNotRemoved("setNextKinematicRotation"))return;this._rigidBody?this._rigidBody.setNextKinematicRotation(Z):this._rigidBodyDesc.setRotation(Z)}setNextKinematicPosition(Z){if(!this._requireKinematic("setNextKinematicPosition"))return;if(!this._requireNotRemoved("setNextKinematicPosition"))return;this._rigidBody?this._rigidBody.setNextKinematicTranslation(Z):this._rigidBodyDesc.setTranslation(Z.x,Z.y,Z.z)}setPosition(Z){if(!this._requireNotRemoved("setPosition"))return;this._rigidBody?this._rigidBody.setTranslation(Z,!this._explicitSleep):this._rigidBodyDesc.setTranslation(Z.x,Z.y,Z.z)}setRotation(Z){if(!this._requireNotRemoved("setRotation"))return;this._rigidBody?this._rigidBody.setRotation(Z,!this._explicitSleep):this._rigidBodyDesc.setRotation(Z)}setSleeping(Z){if(!this._requireDynamic("setSleeping"))return;if(!this._requireNotRemoved("setSleeping"))return;this._rigidBody?Z?this._rigidBody.sleep():this._rigidBody.wakeUp():this._rigidBodyDesc.sleeping=Z,this._explicitSleep=Z}setSoftCcdPrediction(Z){if(!this._requireDynamic("setSoftCcdPrediction"))return;if(!this._requireNotRemoved("setSoftCcdPrediction"))return;this._rigidBody?this._rigidBody.setSoftCcdPrediction(Z):this._rigidBodyDesc.setSoftCcdPrediction(Z)}setCollisionGroupsForSolidColliders(Z){if(!this._requireNotRemoved("setCollisionGroupsForSolidColliders"))return;this._colliders.forEach((J)=>{if(J.isSensor)return;J.setCollisionGroups(Z)})}setCollisionGroupsForSensorColliders(Z){if(!this._requireNotRemoved("setCollisionGroupsForSensorColliders"))return;this._colliders.forEach((J)=>{if(!J.isSensor)return;J.setCollisionGroups(Z)})}setType(Z){if(!this._requireNotRemoved("setType"))return;let X={["dynamic"]:hZ.default.RigidBodyType.Dynamic,["fixed"]:hZ.default.RigidBodyType.Fixed,["kinematic_position"]:hZ.default.RigidBodyType.KinematicPositionBased,["kinematic_velocity"]:hZ.default.RigidBodyType.KinematicVelocityBased}[Z];if(X===void 0)return d.error(`Invalid RigidBodyType: ${Z}`);this._rigidBody?this._rigidBody.setBodyType(X,!this._explicitSleep):this._rigidBodyDesc.status=X,this._rigidBodyType=Z}addForce(Z){if(!this._requireNotRemoved("addForce"))return;if(!this._requireCreated("addForce"))return;if(!this._requireDynamic("addForce"))return;if(this._isNegligibleVector(Z))return;this._rigidBody.addForce(Z,!this._explicitSleep)}addTorque(Z){if(!this._requireNotRemoved("addTorque"))return;if(!this._requireCreated("addTorque"))return;if(!this._requireDynamic("addTorque"))return;if(this._isNegligibleVector(Z))return;this._rigidBody.addTorque(Z,!this._explicitSleep)}addChildColliderToSimulation(Z){if(!this._requireNotRemoved("addChildColliderToSimulation"))return;if(!this._requireCreated("addChildColliderToSimulation"))return;Z.addToSimulation(this._simulation,this)}addToSimulation(Z){if(!this._requireNotRemoved("addToSimulation"))return;if(this._rigidBody)return d.error("RigidBody.addToSimulation(): Rigid body already exists in the simulation!");this._simulation=Z,this._rigidBody=this._simulation.createRawRigidBody(this._rigidBodyDesc),this._colliders.forEach((J)=>{if(!J.isSimulated)J.addToSimulation(Z,this)})}applyImpulse(Z){if(!this._requireNotRemoved("applyImpulse"))return;if(!this._requireCreated("applyImpulse"))return;if(!this._requireDynamic("applyImpulse"))return;if(this._isNegligibleVector(Z))return;this._rigidBody.applyImpulse(Z,!this._explicitSleep)}applyImpulseAtPoint(Z,J){if(!this._requireNotRemoved("applyImpulseAtPoint"))return;if(!this._requireCreated("applyImpulseAtPoint"))return;if(!this._requireDynamic("applyImpulseAtPoint"))return;if(this._isNegligibleVector(Z))return;this._rigidBody.applyImpulseAtPoint(Z,J,!this._explicitSleep)}applyTorqueImpulse(Z){if(!this._requireNotRemoved("applyTorqueImpulse"))return;if(!this._requireCreated("applyTorqueImpulse"))return;if(!this._requireDynamic("applyTorqueImpulse"))return;this._rigidBody.applyTorqueImpulse(Z,!this._explicitSleep)}createAndAddChildCollider(Z){if(!this._requireNotRemoved("createAndAddChildCollider"))return null;return this._simulation?new Q9({...Z,parentRigidBody:this,simulation:this._simulation}):this._createAndAddPendingChildCollider(Z)}createAndAddChildColliders(Z){let J=[];return Z.forEach((X)=>{let Y=this.createAndAddChildCollider(X);if(Y)J.push(Y)}),J}getCollidersByTag(Z){let J=[];for(let X of this._colliders)if(X.tag===Z)J.push(X);return J}linkCollider(Z){if(!this._requireNotRemoved("linkCollider"))return;if(Z.parentRigidBody!==this)return d.error("RigidBody.linkCollider(): Collider cannot be linked because it is not a child of this rigid body!");this._colliders.add(Z)}lockAllRotations(){if(!this._requireNotRemoved("lockAllRotations"))return;this.setEnabledRotations({x:!1,y:!1,z:!1})}lockAllPositions(){if(!this._requireNotRemoved("lockAllPositions"))return;this.setEnabledPositions({x:!1,y:!1,z:!1})}removeFromSimulation(){if(!this._requireNotRemoved("removeFromSimulation"))return;if(!this._rigidBody)return d.error("RigidBody.removeFromSimulation(): Rigid body does not exist in the simulation!");this._colliders.forEach((Z)=>{Z.removeFromSimulation()}),this._simulation.removeRawRigidBody(this._rigidBody),this._simulation=void 0,this._rigidBody=void 0}unlinkCollider(Z){if(!this._requireNotRemoved("unlinkCollider"))return;if(!Z.isRemoved)return d.error("RigidBody.unlinkCollider(): Collider is still simulated and therefore cannot be unlinked from this rigid body!");this._colliders.delete(Z)}resetAngularVelocity(){if(!this._requireNotRemoved("resetAngularVelocity"))return;if(!this._requireCreated("resetAngularVelocity"))return;this.setAngularVelocity({x:0,y:0,z:0})}resetForces(){if(!this._requireNotRemoved("resetForces"))return;if(!this._requireCreated("resetForces"))return;this._rigidBody.resetForces(!this._explicitSleep)}resetLinearVelocity(){if(!this._requireNotRemoved("resetLinearVelocity"))return;if(!this._requireCreated("resetLinearVelocity"))return;this.setLinearVelocity({x:0,y:0,z:0})}resetTorques(){if(!this._requireNotRemoved("resetTorques"))return;if(!this._requireCreated("resetTorques"))return;this._rigidBody.resetTorques(!this._explicitSleep)}sleep(){if(!this._requireNotRemoved("sleep"))return;this.setSleeping(!0)}wakeUp(){if(!this._requireNotRemoved("wakeUp"))return;this.setSleeping(!1)}_applyRigidBodyOptions(Z){[["additionalMass",this.setAdditionalMass.bind(this)],["additionalMassProperties",this.setAdditionalMassProperties.bind(this)],["additionalSolverIterations",this.setAdditionalSolverIterations.bind(this)],["angularDamping",this.setAngularDamping.bind(this)],["angularVelocity",this.setAngularVelocity.bind(this)],["dominanceGroup",this.setDominanceGroup.bind(this)],["ccdEnabled",this.setCcdEnabled.bind(this)],["enabled",this.setEnabled.bind(this)],["enabledPositions",this.setEnabledPositions.bind(this)],["enabledRotations",this.setEnabledRotations.bind(this)],["gravityScale",this.setGravityScale.bind(this)],["linearDamping",this.setLinearDamping.bind(this)],["linearVelocity",this.setLinearVelocity.bind(this)],["position",this.setPosition.bind(this)],["rotation",this.setRotation.bind(this)],["sleeping",this.setSleeping.bind(this)],["softCcdPrediction",this.setSoftCcdPrediction.bind(this)]].forEach(([X,Y])=>{if(X in Z)Y(Z[X])})}_autoAddToSimulation(Z){if(Z.colliders)this._createAndAddPendingChildColliders(Z.colliders);if(Z.simulation)this.addToSimulation(Z.simulation)}_createAndAddPendingChildCollider(Z){if(!this._requireNotRemoved("createAndAddPendingChildCollider"))return null;if(!this._requireNotSimulated("createAndAddPendingChildCollider"))return null;let J=new Q9(Z);return this._colliders.add(J),J}_createAndAddPendingChildColliders(Z){let J=[];return Z.forEach((X)=>{let Y=this._createAndAddPendingChildCollider(X);if(Y)J.push(Y)}),J}_createRigidBodyDesc(Z){let J=Z.type??gt;return{["dynamic"]:()=>hZ.default.RigidBodyDesc.dynamic(),["fixed"]:()=>hZ.default.RigidBodyDesc.fixed(),["kinematic_position"]:()=>hZ.default.RigidBodyDesc.kinematicPositionBased(),["kinematic_velocity"]:()=>hZ.default.RigidBodyDesc.kinematicVelocityBased()}[J]()}_requireCreated(Z){if(!this._rigidBody||!this._simulation)d.error(`RigidBody._requireCreated(): Rigid body has not been created and therefore does not support the invoked method: ${Z}()`);return!!this._rigidBody&&!!this._simulation}_requireDynamic(Z){if(!this.isDynamic)d.error(`RigidBody._requireDynamic(): Rigid body is not dynamic and therefore does not support the invoked method: ${Z}()`);return this.isDynamic}_requireKinematic(Z){if(!this.isKinematic)d.error(`RigidBody._requireKinematic(): Rigid body is not kinematic and therefore does not support the invoked method: ${Z}()`);return this.isKinematic}_requireNotKinematicPositionBased(Z){if(this.isKinematicPositionBased)d.error(`RigidBody._requireNotKinematicPositionBased(): Rigid body is kinematic position based and therefore does not support the invoked method: ${Z}()`);return!this.isKinematicPositionBased}_requireNotRemoved(Z){if(!this._rigidBody&&!this._rigidBodyDesc)d.error(`RigidBody._requireNotRemoved(): Rigid body has been removed and therefore does not support the invoked method: ${Z}()`);return!!this._rigidBody||!!this._rigidBodyDesc}_requireNotSimulated(Z){if(this.isSimulated)d.error(`RigidBody._requireNotSimulated(): Rigid body is simulated and therefore does not support the invoked method: ${Z}()`);return!this.isSimulated}_isNegligibleVector(Z){return Math.abs(Z.x)<Fk&&Math.abs(Z.y)<Fk&&Math.abs(Z.z)<Fk}}var qk;(($)=>{$[$.Average=0]="Average";$[$.Min=1]="Min";$[$.Multiply=2]="Multiply";$[$.Max=3]="Max"})(qk||={});var wV;((V)=>{V.NONE="none";V.BALL="ball";V.BLOCK="block";V.CAPSULE="capsule";V.CONE="cone";V.CYLINDER="cylinder";V.ROUND_CYLINDER="round-cylinder";V.TRIMESH="trimesh";V.VOXELS="voxels";V.WEDGE="wedge"})(wV||={});class Q9 extends O0{_collider;_colliderDesc;_onCollision;_parentRigidBody;_relativePosition={x:0,y:0,z:0};_relativeRotation={x:0,y:0,z:0,w:1};_shape;_simulation;_tag;constructor(Z){super();this._colliderDesc=this._createColliderDesc(Z),this._shape=Z.shape,this._applyColliderOptions(Z),this._autoAddToSimulation(Z)}static optionsFromBlockHalfExtents(Z){return{shape:"block",halfExtents:Z}}static optionsFromModelUri(Z,J=1,X){let Y=S5.instance.getBoundingBox(Z),$=Y.max.x-Y.min.x,Q=Y.max.y-Y.min.y,K=Y.max.z-Y.min.z,G=Math.max($,K),W=Math.min($,K),H=G/W,V=G/Q,F=G*J/2,z=(O)=>Math.max(0.01,O),q=()=>({shape:"block",halfExtents:{x:z($*J/2),y:z(Q*J/2),z:z(K*J/2)}}),U=()=>({shape:"round-cylinder",radius:z(F),halfHeight:z(Q*J/2),borderRadius:z(F*0.1)}),B=()=>{let O=S5.instance.getTrimesh(Z,J);if(!O)return;return{shape:"trimesh",vertices:O.vertices,indices:O.indices}},L=()=>({shape:"wedge",extents:{x:$*J,y:Q*J,z:K*J}}),w=()=>({shape:"capsule",radius:z(F),halfHeight:z(Q*J/2-F)});if(X)switch(X){case"block":return q();case"capsule":return w();case"round-cylinder":return U();case"trimesh":{let O=B();if(!O){d.error(`Collider.optionsFromModelUri(): Failed to create trimesh options for model ${Z}, falling back to generic shape!`);break}return O}case"wedge":return L();default:d.warning(`Collider.optionsFromModelUri(): Preferred shape ${X} is not yet supported with Collider.optionsFromModelUri(), defaulting to generic shape!`)}if(H>2)return q();if(V>1.5)return U();return w()}get bounciness(){if(!this._requireNotRemoved("bounciness"))return 0;return this._collider?this._collider.restitution():this._colliderDesc.restitution}get bouncinessCombineRule(){if(!this._requireNotRemoved("bouncinessCombineRule"))return 0;return this._collider?this._collider.restitutionCombineRule():this._colliderDesc.restitutionCombineRule}get collisionGroups(){if(!this._requireNotRemoved("collisionGroups"))return{belongsTo:[],collidesWith:[]};return this._collider?T4.decodeRawCollisionGroups(this._collider.collisionGroups()):T4.decodeRawCollisionGroups(this._colliderDesc.collisionGroups)}get friction(){if(!this._requireNotRemoved("friction"))return 0;return this._collider?this._collider.friction():this._colliderDesc.friction}get frictionCombineRule(){if(!this._requireNotRemoved("frictionCombineRule"))return 0;return this._collider?this._collider.frictionCombineRule():this._colliderDesc.frictionCombineRule}get isEnabled(){if(!this._requireNotRemoved("isEnabled"))return!1;return this._collider?this._collider.isEnabled():this._colliderDesc.enabled}get isRemoved(){return!this._collider&&!this._colliderDesc}get isSensor(){if(!this._requireNotRemoved("isSensor"))return!1;return this._collider?this._collider.isSensor():this._colliderDesc.isSensor}get isSimulated(){if(!this._requireNotRemoved("isSimulated"))return!1;return!!this._collider}get parentRigidBody(){if(!this._requireNotRemoved("parentRigidBody"))return;return this._parentRigidBody}get rawCollider(){if(!this._requireNotRemoved("rawCollider"))return;return this._collider}get rawShape(){if(!this._requireNotRemoved("rawShape"))return;return this._collider?this._collider.shape:this._colliderDesc.shape}get relativePosition(){if(!this._requireNotRemoved("relativePosition"))return{x:0,y:0,z:0};return this._relativePosition}get relativeRotation(){if(!this._requireNotRemoved("relativeRotation"))return{x:0,y:0,z:0,w:1};return this._relativeRotation}get shape(){if(!this._requireNotRemoved("shape"))return"none";return this._shape}get tag(){if(!this._requireNotRemoved("tag"))return;return this._tag}setBounciness(Z){if(!this._requireNotRemoved("setBounciness"))return;this._collider?this._collider.setRestitution(Z):this._colliderDesc.setRestitution(Z)}setBouncinessCombineRule(Z){if(!this._requireNotRemoved("setBouncinessCombineRule"))return;this._collider?this._collider.setRestitutionCombineRule(Z):this._colliderDesc.setRestitutionCombineRule(Z)}setCollisionGroups(Z){if(!this._requireNotRemoved("setCollisionGroups"))return;let J=T4.buildRawCollisionGroups(Z);this._collider?this._collider.setCollisionGroups(J):this._colliderDesc.setCollisionGroups(J)}setEnabled(Z){if(!this._requireNotRemoved("setEnabled"))return;this._collider?this._collider.setEnabled(Z):this._colliderDesc.setEnabled(Z)}setFriction(Z){if(!this._requireNotRemoved("setFriction"))return;this._collider?this._collider.setFriction(Z):this._colliderDesc.setFriction(Z)}setFrictionCombineRule(Z){if(!this._requireNotRemoved("setFrictionCombineRule"))return;this._collider?this._collider.setFrictionCombineRule(Z):this._colliderDesc.setFrictionCombineRule(Z)}setMass(Z){if(!this._requireNotRemoved("setMass"))return;this._collider?this._collider.setMass(Z):this._colliderDesc.setMass(Z)}setOnCollision(Z){if(!this._requireNotRemoved("setOnCollision"))return;if(this._onCollision=Z,this.isSimulated)if(this.enableCollisionEvents(!!Z),Z)this._simulation.colliderMap.setColliderCollisionCallback(this,Z);else this._simulation.colliderMap.removeColliderCollisionCallback(this)}setRelativeRotation(Z){if(!this._requireNotRemoved("setRelativeRotation"))return;this._relativeRotation=Z,this._collider?this._collider.parent()?this._collider.setRotationWrtParent(Z):this._collider.setRotation(Z):this._colliderDesc.setRotation(Z)}setRelativePosition(Z){if(!this._requireNotRemoved("setRelativePosition"))return;this._relativePosition=Z,this._collider?this._collider.parent()?this._collider.setTranslationWrtParent(Z):this._collider.setTranslation(Z):this._colliderDesc.setTranslation(Z.x,Z.y,Z.z)}setSensor(Z){if(!this._requireNotRemoved("setSensor"))return;this._collider?this._collider.setSensor(Z):this._colliderDesc.setSensor(Z)}setTag(Z){if(!this._requireNotRemoved("setTag"))return;this._tag=Z}setVoxel(Z,J){if(!this._requireNotRemoved("setVoxel"))return;if(!this._requireSimulated("setVoxel"))return;if(this.shape!=="voxels")return d.error("Collider.setVoxel(): Collider is not a voxels collider!");this._collider.setVoxel(Z.x,Z.y,Z.z,J)}addToSimulation(Z,J){if(!this._requireNotRemoved("addToSimulation"))return;if(!this._requireUnsimulated("addToSimulation"))return;if(J){if(!J.isSimulated)return d.error("Collider.addToSimulation(): Rigid body must be simulated before adding a collider to it!");if(J.type==="dynamic"&&this.shape==="trimesh")d.warning("Collider.addToSimulation(): Trimesh colliders are strongly discouraged to be used with dynamic rigid bodies, they will not contribute any mass!")}if(this._simulation=Z,this._parentRigidBody=J,this._collider=this._simulation.createRawCollider(this._colliderDesc,J?.rawRigidBody),this._colliderDesc=void 0,J)J.linkCollider(this);if(this._onCollision)this.setOnCollision(this._onCollision)}combineVoxelStates(Z){if(!this._requireNotRemoved("combineVoxelStates"))return;if(!this._requireSimulated("combineVoxelStates"))return;if(!Z.isSimulated)return d.error("Collider.combineVoxelStates(): Other collider is not simulated!");if(this.shape!=="voxels")return d.error("Collider.combineVoxelStates(): Collider is not a voxels collider!");if(Z.shape!=="voxels")return d.error("Collider.combineVoxelStates(): Other collider is not a voxels collider!");this._collider.combineVoxelStates(Z.rawCollider,0,0,0)}enableCollisionEvents(Z){if(!this._requireNotRemoved("enableCollisionEvents"))return;let J=this._collider?this._collider.activeEvents():this._colliderDesc.activeEvents,X=Z?J|p8.default.ActiveEvents.COLLISION_EVENTS:J&~p8.default.ActiveEvents.COLLISION_EVENTS;(this._collider??this._colliderDesc).setActiveEvents(X),this._setActiveCollisionTypes()}enableContactForceEvents(Z){if(!this._requireNotRemoved("enableContactForceEvents"))return;let J=this._collider?this._collider.activeEvents():this._colliderDesc.activeEvents,X=Z?J|p8.default.ActiveEvents.CONTACT_FORCE_EVENTS:J&~p8.default.ActiveEvents.CONTACT_FORCE_EVENTS;(this._collider??this._colliderDesc).setActiveEvents(X),this._setActiveCollisionTypes()}propagateVoxelChange(Z,J){if(!this._requireNotRemoved("propagateVoxelChange"))return;if(!this._requireSimulated("propagateVoxelChange"))return;if(!Z.isSimulated)return d.error("Collider.propagateVoxelChange(): Other collider is not simulated!");if(this.shape!=="voxels")return d.error("Collider.propagateVoxelChange(): Collider is not a voxels collider!");if(Z.shape!=="voxels")return d.error("Collider.propagateVoxelChange(): Other collider is not a voxels collider!");this._collider.propagateVoxelChange(Z.rawCollider,J.x,J.y,J.z,0,0,0)}removeFromSimulation(){if(!this._requireNotRemoved("removeFromSimulation"))return;if(!this._requireSimulated("removeFromSimulation"))return;if(this._simulation.removeRawCollider(this._collider),this._simulation=void 0,this._collider=void 0,this._parentRigidBody)this._parentRigidBody.unlinkCollider(this);this._parentRigidBody=void 0}scale(Z){if(!this._requireNotRemoved("scale"))return;switch(this.setRelativePosition({x:this.relativePosition.x*Z,y:this.relativePosition.y*Z,z:this.relativePosition.z*Z}),this._shape){case"ball":{if(this._collider)this._collider.setRadius(this._collider.radius()*Z);else this._colliderDesc.shape.radius*=Z;return}case"block":{if(this._collider){let J=this._collider.halfExtents();this._collider.setHalfExtents({x:J.x*Z,y:J.y*Z,z:J.z*Z})}else this._colliderDesc.shape.halfExtents.x*=Z,this._colliderDesc.shape.halfExtents.y*=Z,this._colliderDesc.shape.halfExtents.z*=Z;return}case"capsule":{if(this._collider)this._collider.setHalfHeight(this._collider.halfHeight()*Z),this._collider.setRadius(this._collider.radius()*Z);else this._colliderDesc.shape.halfHeight*=Z,this._colliderDesc.shape.radius*=Z;return}case"cone":{if(this._collider)this._collider.setHalfHeight(this._collider.halfHeight()*Z),this._collider.setRadius(this._collider.radius()*Z);else this._colliderDesc.shape.halfHeight*=Z,this._colliderDesc.shape.radius*=Z;return}case"cylinder":{if(this._collider)this._collider.setHalfHeight(this._collider.halfHeight()*Z),this._collider.setRadius(this._collider.radius()*Z);else this._colliderDesc.shape.halfHeight*=Z,this._colliderDesc.shape.radius*=Z;return}case"round-cylinder":{if(this._collider)this._collider.setHalfHeight(this._collider.halfHeight()*Z),this._collider.setRoundRadius(this._collider.roundRadius()*Z),this._collider.setRadius(this._collider.radius()*Z);else this._colliderDesc.shape.halfHeight=this._colliderDesc.shape.halfHeight*Z,this._colliderDesc.shape.borderRadius=this._colliderDesc.shape.borderRadius*Z,this._colliderDesc.shape.radius=this._colliderDesc.shape.radius*Z;return}case"trimesh":{d.error("Collider.setScale(): Trimesh colliders cannot be scaled!");return}case"voxels":{d.error("Collider.setScale(): Voxels colliders cannot be scaled!");return}case"wedge":{d.error("Collider.setScale(): Wedge colliders cannot be scaled!");return}default:d.fatalError(`Collider.setScale(): ${this._shape} is not a valid collider shape!`)}}_applyColliderOptions(Z){[["bounciness",this.setBounciness.bind(this)],["bouncinessCombineRule",this.setBouncinessCombineRule.bind(this)],["collisionGroups",this.setCollisionGroups.bind(this)],["enabled",this.setEnabled.bind(this)],["friction",this.setFriction.bind(this)],["frictionCombineRule",this.setFrictionCombineRule.bind(this)],["isSensor",this.setSensor.bind(this)],["mass",this.setMass.bind(this)],["onCollision",this.setOnCollision.bind(this)],["relativePosition",this.setRelativePosition.bind(this)],["relativeRotation",this.setRelativeRotation.bind(this)],["tag",this.setTag.bind(this)]].forEach(([X,Y])=>{if(Z[X]!==void 0)Y.call(this,Z[X])})}_autoAddToSimulation(Z){if(Z.simulation)this.addToSimulation(Z.simulation,Z.parentRigidBody)}_buildWedgeConvexHullVertices(Z){let{x:J,y:X,z:Y}=Z,$=J/2,Q=Y/2,K=X/2;return new Float32Array([-$,0-K,-Q,$,0-K,-Q,$,0-K,Q,-$,0-K,Q,-$,X-K,-Q,$,X-K,-Q])}_createColliderDesc(Z){let{shape:J,flags:X}=Z;switch(J){case"ball":{if(!Z.radius)d.fatalError("Ball collider must have a radius!");return p8.default.ColliderDesc.ball(Z.radius)}case"block":{if(!Z.halfExtents)d.fatalError("Block collider must have halfExtents!");return p8.default.ColliderDesc.cuboid(Z.halfExtents.x,Z.halfExtents.y,Z.halfExtents.z)}case"capsule":{if(!Z.halfHeight||!Z.radius)d.fatalError("Capsule collider must have halfHeight and radius!");return p8.default.ColliderDesc.capsule(Z.halfHeight,Z.radius)}case"cone":{if(!Z.radius||!Z.halfHeight)d.fatalError("Cone collider must have radius and halfHeight!");return p8.default.ColliderDesc.cone(Z.halfHeight,Z.radius)}case"cylinder":{if(!Z.radius||!Z.halfHeight)d.fatalError("Cylinder collider must have radius and halfHeight!");return p8.default.ColliderDesc.cylinder(Z.halfHeight,Z.radius)}case"round-cylinder":{if(!Z.radius||!Z.halfHeight||!Z.borderRadius)d.fatalError("Round cylinder collider must have radius, halfHeight, and borderRadius!");return p8.default.ColliderDesc.roundCylinder(Z.halfHeight,Z.radius,Z.borderRadius)}case"trimesh":{if(!Z.indices||!Z.vertices)d.fatalError("Trimesh collider must have vertices and indices!");return p8.default.ColliderDesc.trimesh(Z.vertices,Z.indices,X)}case"voxels":{if(!Z.coordinates||!Z.size)d.fatalError("Voxels collider must have coordinates and size!");return p8.default.ColliderDesc.voxels(this._coordinatesToInt32Array(Z.coordinates),Z.size)}case"wedge":{if(!Z.extents)d.fatalError("Wedge collider must have extents!");let Y=this._buildWedgeConvexHullVertices(Z.extents),$=p8.default.ColliderDesc.convexHull(Y);if(!$)throw d.fatalError("Failed to create convex hull for wedge collider!"),new Error("Convex hull creation failed");return $}default:d.fatalError(`Collider._createColliderDesc(): ${J} is not a valid collider shape!`)}}_requireSimulated(Z){if(!this.isSimulated)d.error(`Collider._requireSimulated(): Collider is not simulated, invoked method: ${Z}()`);return this.isSimulated}_requireUnsimulated(Z){if(this.isSimulated)d.error(`Collider._requireUnsimulated(): Collider is already simulated, invoked method: ${Z}()`);return!this.isSimulated}_requireNotRemoved(Z){if(this.isRemoved)d.error(`Collider._requireNotRemoved(): Collider is removed, invoked method: ${Z}()`);return!this.isRemoved}_setActiveCollisionTypes(){(this._collider??this._colliderDesc).setActiveCollisionTypes(p8.default.ActiveCollisionTypes.DYNAMIC_DYNAMIC|p8.default.ActiveCollisionTypes.DYNAMIC_KINEMATIC|p8.default.ActiveCollisionTypes.DYNAMIC_FIXED|p8.default.ActiveCollisionTypes.KINEMATIC_KINEMATIC|p8.default.ActiveCollisionTypes.KINEMATIC_FIXED)}_coordinatesToInt32Array(Z){let J=new Int32Array(Z.length*3);for(let X=0;X<Z.length;X++){let Y=Z[X],$=X*3;J[$]=Math.floor(Y.x),J[$+1]=Math.floor(Y.y),J[$+2]=Math.floor(Y.z)}return J}}var YE1={shape:"voxels"},Uk;((X)=>{X.ENTITY_COLLISION="BLOCK_TYPE.ENTITY_COLLISION";X.ENTITY_CONTACT_FORCE="BLOCK_TYPE.ENTITY_CONTACT_FORCE"})(Uk||={});class K9 extends O0{_id;_blockTypeRegistry;_customColliderOptions;_halfExtents;_isLiquid;_name;_textureUri;constructor(Z,J={id:-1,textureUri:"textures/missing.png",name:"Unknown"}){if(J.id<0)d.fatalError("BlockType.constructor(): BlockType id not set.");super();this._id=J.id,this._blockTypeRegistry=Z,this._customColliderOptions=J.customColliderOptions,this._halfExtents=J.halfExtents??{x:0.5,y:0.5,z:0.5},this._isLiquid=J.isLiquid??!1,this._name=J.name,this._textureUri=J.textureUri}get id(){return this._id}get blockTypeRegistry(){return this._blockTypeRegistry}get colliderOptions(){return{...this._customColliderOptions,...YE1}}get halfExtents(){return this._halfExtents}get isLiquid(){return this._isLiquid}get isMeshable(){return!this._customColliderOptions}get name(){return this._name}get size(){return{x:this._halfExtents.x*2,y:this._halfExtents.y*2,z:this._halfExtents.z*2}}get textureUri(){return this._textureUri}createCollider(Z){let J=new Q9({...this.colliderOptions,coordinates:Z,size:this.size});if(this.isLiquid)J.setSensor(!0);if(this.hasListeners("BLOCK_TYPE.ENTITY_COLLISION")||this.isLiquid)J.enableCollisionEvents(!0);if(this.hasListeners("BLOCK_TYPE.ENTITY_CONTACT_FORCE"))J.enableContactForceEvents(!0);if(T4.isDefaultCollisionGroups(J.collisionGroups))J.setCollisionGroups({belongsTo:[1],collidesWith:[65535&~1]});return J}serialize(){return P0.serializeBlockType(this,this._blockTypeRegistry.world.tickAllocator)}}var Lk;((J)=>J.REGISTER_BLOCK_TYPE="BLOCK_TYPE_REGISTRY.REGISTER_BLOCK_TYPE")(Lk||={});class jV extends O0{_blockTypes=new Map;_world;constructor(Z){super();this._world=Z}get world(){return this._world}getAllBlockTypes(Z=!1){return Z?this._world.tickAllocator.getArray(this._blockTypes.values()):Array.from(this._blockTypes.values())}getBlockType(Z){let J=this._blockTypes.get(Z);if(!J)d.fatalError(`BlockTypeRegistry.getBlockType(): BlockType with id ${Z} not found.`);return J}registerGenericBlockType(Z){let X=new class extends K9{constructor(Y,$){super(Y,$)}}(this,Z);return this.registerBlockType(X),X}registerBlockType(Z){this._blockTypes.set(Z.id,Z),this.emitWithWorld(this._world,"BLOCK_TYPE_REGISTRY.REGISTER_BLOCK_TYPE",{blockTypeRegistry:this,id:Z.id,blockType:Z})}serialize(){return P0.serializeBlockTypeRegistry(this,this._world.tickAllocator)}}var iI={};zK(iI,{worldSchema:()=>pI,worldPacketDefinition:()=>v60,vectorSchema:()=>W1,vectorBooleanSchema:()=>Jh1,uiSchema:()=>cI,uiPacketDefinition:()=>_60,uiDatasSchema:()=>lI,uiDatasPacketDefinition:()=>S60,uiDataSendPacketDefinition:()=>L60,uiDataSchema:()=>dV,syncResponseSchema:()=>dI,syncResponsePacketDefinition:()=>I60,syncRequestSchema:()=>BI,syncRequestPacketDefinition:()=>U60,stateRequestSchema:()=>LI,stateRequestPacketDefinition:()=>q60,sceneUIsSchema:()=>uI,sceneUIsPacketDefinition:()=>k60,sceneUISchema:()=>mI,rgbColorSchema:()=>h6,registeredPackets:()=>dw,quaternionSchema:()=>kI,playersSchema:()=>gI,playersPacketDefinition:()=>E60,playerSchema:()=>bI,physicsDebugRenderSchema:()=>yI,physicsDebugRenderPacketDefinition:()=>C60,physicsDebugRaycastsSchema:()=>fI,physicsDebugRaycastsPacketDefinition:()=>T60,physicsDebugRaycastSchema:()=>hI,particleEmittersSchema:()=>xI,particleEmittersPacketDefinition:()=>D60,particleEmitterSchema:()=>AI,outboundPackets:()=>uw,modelNodeOverrideSchema:()=>EI,lightsSchema:()=>vI,lightsPacketDefinition:()=>P60,lightSchema:()=>SI,isValidPacket:()=>Yh1,inputSchema:()=>UI,inputPacketDefinition:()=>F60,inboundPackets:()=>mw,hexColorSchema:()=>FI,heartbeatSchema:()=>zI,heartbeatPacketDefinition:()=>H60,entitySchema:()=>II,entitiesSchema:()=>_I,entitiesPacketDefinition:()=>N60,definePacket:()=>I0,debugConfigSchema:()=>qI,debugConfigPacketDefinition:()=>z60,createPacket:()=>px1,connectionSchema:()=>VI,connectionPacketDefinition:()=>W60,chunksSchema:()=>TI,chunksPacketDefinition:()=>R60,chunkSchema:()=>CI,chatMessagesSchema:()=>DI,chatMessagesPacketDefinition:()=>M60,chatMessageSendPacketDefinition:()=>V60,chatMessageSchema:()=>uV,cameraSchema:()=>PI,cameraPacketDefinition:()=>O60,blocksSchema:()=>MI,blocksPacketDefinition:()=>w60,blockTypesSchema:()=>NI,blockTypesPacketDefinition:()=>j60,blockTypeSchema:()=>RI,blockSchema:()=>OI,bidirectionalPackets:()=>gw,audiosSchema:()=>jI,audiosPacketDefinition:()=>B60,audioSchema:()=>wI,PacketId:()=>S1});var gw={};zK(gw,{heartbeatPacketDefinition:()=>H60,connectionPacketDefinition:()=>W60});var WI=r(K60(),1);class HI extends WI.default{static instance=new WI.default}var S1;((E)=>{E[E.SYNC_REQUEST=0]="SYNC_REQUEST";E[E.INPUT=1]="INPUT";E[E.STATE_REQUEST=2]="STATE_REQUEST";E[E.CHAT_MESSAGE_SEND=3]="CHAT_MESSAGE_SEND";E[E.UI_DATA_SEND=4]="UI_DATA_SEND";E[E.SYNC_RESPONSE=32]="SYNC_RESPONSE";E[E.AUDIOS=33]="AUDIOS";E[E.BLOCKS=34]="BLOCKS";E[E.BLOCK_TYPES=35]="BLOCK_TYPES";E[E.CHAT_MESSAGES=36]="CHAT_MESSAGES";E[E.CHUNKS=37]="CHUNKS";E[E.ENTITIES=38]="ENTITIES";E[E.WORLD=39]="WORLD";E[E.CAMERA=40]="CAMERA";E[E.UI=41]="UI";E[E.UI_DATAS=42]="UI_DATAS";E[E.SCENE_UIS=43]="SCENE_UIS";E[E.LIGHTS=44]="LIGHTS";E[E.PLAYERS=45]="PLAYERS";E[E.PARTICLE_EMITTERS=46]="PARTICLE_EMITTERS";E[E.CONNECTION=116]="CONNECTION";E[E.HEARTBEAT=117]="HEARTBEAT";E[E.DEBUG_CONFIG=128]="DEBUG_CONFIG";E[E.PHYSICS_DEBUG_RENDER=192]="PHYSICS_DEBUG_RENDER";E[E.PHYSICS_DEBUG_RAYCASTS=193]="PHYSICS_DEBUG_RAYCASTS"})(S1||={});function px1(Z,J,X,Y){if(!Z.validate(J))throw new Error(`Invalid payload for packet with id ${Z.id}. Error: ${HI.instance.errorsText(Z.validate.errors)}`);let $=Y??[];if($[0]=Z.id,$[1]=J,typeof X==="number")$.push(X);return $}function I0(Z,J){return{id:Z,schema:J,validate:HI.instance.compile(J)}}var ix1={type:"object",properties:{i:{type:"string"}},required:["i"],additionalProperties:!1},G60={type:"object",properties:{role:{type:"string",enum:["auto","client","server"],nullable:!0},fingerprints:{type:"array",items:{type:"object",properties:{algorithm:{type:"string",enum:["sha-1","sha-224","sha-256","sha-384","sha-512"]},value:{type:"string"}},required:["algorithm","value"]}}},required:["fingerprints"],additionalProperties:!1},nx1={type:"object",properties:{foundation:{type:"string"},priority:{type:"number"},ip:{type:"string"},address:{type:"string"},protocol:{type:"string",enum:["udp","tcp"]},port:{type:"number"},type:{type:"string",enum:["host"]},tcpType:{type:"string",enum:["passive"],nullable:!0}},required:["foundation","priority","ip","address","protocol","port","type"],additionalProperties:!1},ax1={type:"object",properties:{usernameFragment:{type:"string"},password:{type:"string"},iceLite:{type:"boolean",nullable:!0}},required:["usernameFragment","password"],additionalProperties:!1},sx1={type:"object",properties:{i:{type:"string"},l:{type:"string"}},required:["i","l"],additionalProperties:!1},ox1={type:"object",properties:{port:{type:"number"},OS:{type:"number"},MIS:{type:"number"},maxMessageSize:{type:"number"}},required:["port","OS","MIS","maxMessageSize"],additionalProperties:!0},rx1={type:"object",properties:{streamId:{type:"number"},ordered:{type:"boolean",nullable:!0},maxPacketLifeTime:{type:"number",nullable:!0},maxRetransmits:{type:"number",nullable:!0}},required:["streamId"],additionalProperties:!1},tx1={type:"object",properties:{i:{type:"string"},f:{type:"string",enum:["cs","sc"]},ip:ax1,ic:{type:"array",items:nx1},d:G60,s:ox1},required:["i","f","ip","ic","d","s"],additionalProperties:!1},ex1={type:"object",properties:{i:{type:"string"},d:G60},required:["i","d"],additionalProperties:!1},Zh1={type:"object",properties:{i:{type:"string",nullable:!0},pi:{type:"string",nullable:!0},l:{type:"string"},s:rx1},required:["l","s"],additionalProperties:!1},VI={type:"object",properties:{i:{type:"string",nullable:!0},k:{type:"boolean",nullable:!0},c:{...ex1,nullable:!0},ca:{...ix1,nullable:!0},d:{type:"array",items:{...Zh1},nullable:!0},pa:{...sx1,nullable:!0},t:{type:"array",items:{...tx1},nullable:!0}},additionalProperties:!1};var W60=I0(116,VI);var zI={type:"null",nullable:!0};var H60=I0(117,zI);var mw={};zK(mw,{uiDataSendPacketDefinition:()=>L60,syncRequestPacketDefinition:()=>U60,stateRequestPacketDefinition:()=>q60,inputPacketDefinition:()=>F60,debugConfigPacketDefinition:()=>z60,chatMessageSendPacketDefinition:()=>V60});var FI={type:"string",pattern:"^[0-9A-Fa-f]{6}$"};var uV={type:"object",properties:{m:{type:"string"},c:{...FI,nullable:!0},p:{type:"string",nullable:!0}},required:["m"],additionalProperties:!1};var V60=I0(3,uV);var qI={type:"object",properties:{pdr:{type:"boolean",nullable:!0}},additionalProperties:!1};var z60=I0(128,qI);var UI={type:"object",properties:{"1":{type:"boolean",nullable:!0},"2":{type:"boolean",nullable:!0},"3":{type:"boolean",nullable:!0},"4":{type:"boolean",nullable:!0},"5":{type:"boolean",nullable:!0},"6":{type:"boolean",nullable:!0},"7":{type:"boolean",nullable:!0},"8":{type:"boolean",nullable:!0},"9":{type:"boolean",nullable:!0},"0":{type:"boolean",nullable:!0},w:{type:"boolean",nullable:!0},a:{type:"boolean",nullable:!0},s:{type:"boolean",nullable:!0},d:{type:"boolean",nullable:!0},q:{type:"boolean",nullable:!0},e:{type:"boolean",nullable:!0},r:{type:"boolean",nullable:!0},f:{type:"boolean",nullable:!0},z:{type:"boolean",nullable:!0},x:{type:"boolean",nullable:!0},c:{type:"boolean",nullable:!0},v:{type:"boolean",nullable:!0},u:{type:"boolean",nullable:!0},i:{type:"boolean",nullable:!0},o:{type:"boolean",nullable:!0},j:{type:"boolean",nullable:!0},k:{type:"boolean",nullable:!0},l:{type:"boolean",nullable:!0},n:{type:"boolean",nullable:!0},m:{type:"boolean",nullable:!0},sp:{type:"boolean",nullable:!0},sh:{type:"boolean",nullable:!0},tb:{type:"boolean",nullable:!0},ml:{type:"boolean",nullable:!0},mr:{type:"boolean",nullable:!0},cp:{type:"number",nullable:!0},cy:{type:"number",nullable:!0},sq:{type:"number",nullable:!0}},additionalProperties:!1};var F60=I0(1,UI);var LI={type:"object",properties:{},additionalProperties:!1};var q60=I0(2,LI);var BI={type:"null",nullable:!0};var U60=I0(0,BI);var dV={type:"object",properties:{},additionalProperties:!0};var L60=I0(4,dV);var uw={};zK(uw,{worldPacketDefinition:()=>v60,uiPacketDefinition:()=>_60,uiDatasPacketDefinition:()=>S60,syncResponsePacketDefinition:()=>I60,sceneUIsPacketDefinition:()=>k60,playersPacketDefinition:()=>E60,physicsDebugRenderPacketDefinition:()=>C60,physicsDebugRaycastsPacketDefinition:()=>T60,particleEmittersPacketDefinition:()=>D60,lightsPacketDefinition:()=>P60,entitiesPacketDefinition:()=>N60,chunksPacketDefinition:()=>R60,chatMessagesPacketDefinition:()=>M60,cameraPacketDefinition:()=>O60,blocksPacketDefinition:()=>w60,blockTypesPacketDefinition:()=>j60,audiosPacketDefinition:()=>B60});var W1={type:"array",items:[{type:"number"},{type:"number"},{type:"number"}],minItems:3,maxItems:3};var wI={type:"object",properties:{i:{type:"number"},a:{type:"string",nullable:!0},cd:{type:"number",nullable:!0},d:{type:"number",nullable:!0},de:{type:"number",nullable:!0},di:{type:"number",minimum:0,nullable:!0},e:{type:"number",nullable:!0},l:{type:"boolean",nullable:!0},o:{type:"number",nullable:!0},p:{...W1,nullable:!0},pa:{type:"boolean",nullable:!0},pl:{type:"boolean",nullable:!0},pr:{type:"number",minimum:0,nullable:!0},r:{type:"boolean",nullable:!0},rd:{type:"number",nullable:!0},s:{type:"number",nullable:!0},v:{type:"number",minimum:0,maximum:1,nullable:!0}},required:["i"],additionalProperties:!1};var jI={type:"array",items:{...wI}};var B60=I0(33,jI);var OI={type:"object",properties:{i:{type:"number"},c:W1},required:["i","c"],additionalProperties:!1};var MI={type:"array",items:{...OI}};var w60=I0(34,MI);var RI={type:"object",properties:{i:{type:"number"},l:{type:"boolean",nullable:!0},n:{type:"string",nullable:!0},t:{type:"string",nullable:!0}},required:["i"],additionalProperties:!1};var NI={type:"array",items:{...RI}};var j60=I0(35,NI);var PI={type:"object",properties:{m:{type:"number",nullable:!0},e:{type:"number",nullable:!0},et:{type:"number",nullable:!0},fo:{type:"number",nullable:!0},ffo:{type:"number",nullable:!0},fv:{type:"number",nullable:!0},h:{type:"array",items:{type:"string"},nullable:!0},o:{...W1,nullable:!0},p:{...W1,nullable:!0},pt:{...W1,nullable:!0},pl:{...W1,nullable:!0},s:{type:"array",items:{type:"string"},nullable:!0},sa:{type:"number",nullable:!0},z:{type:"number",nullable:!0}},additionalProperties:!1};var DI={type:"array",items:{...uV}};var CI={type:"object",properties:{c:W1,b:{type:"array",items:{type:"number",minimum:0,maximum:255},minItems:4096,maxItems:4096,nullable:!0},rm:{type:"boolean",nullable:!0}},required:["c"],additionalProperties:!1};var TI={type:"array",items:{...CI}};var h6={type:"array",items:[{type:"number",minimum:0,maximum:255},{type:"number",minimum:0,maximum:255},{type:"number",minimum:0,maximum:255}],minItems:3,maxItems:3};var EI={type:"object",properties:{n:{type:"string"},h:{type:"boolean",nullable:!0},o:{type:"number",minimum:0,maximum:1,nullable:!0},r:{type:"boolean",nullable:!0},s:{type:"number",nullable:!0},t:{...h6,nullable:!0}},required:["n"],additionalProperties:!1};var kI={type:"array",items:[{type:"number"},{type:"number"},{type:"number"},{type:"number"}],minItems:4,maxItems:4};var II={type:"object",properties:{i:{type:"number"},al:{type:"array",items:{type:"string"},nullable:!0},ao:{type:"array",items:{type:"string"},nullable:!0},ap:{type:"number",nullable:!0},as:{type:"array",items:{type:"string"},nullable:!0},bh:{...W1,nullable:!0},bt:{type:"string",nullable:!0},h:{type:"array",items:{type:"string"},nullable:!0},m:{type:"string",nullable:!0},mo:{type:"array",items:{...EI},nullable:!0},mt:{type:"string",nullable:!0},n:{type:"string",nullable:!0},o:{type:"number",nullable:!0},p:{...W1,nullable:!0},pe:{type:"number",nullable:!0},pn:{type:"string",nullable:!0},r:{...kI,nullable:!0},rm:{type:"boolean",nullable:!0},s:{type:"number",nullable:!0},sn:{type:"array",items:{type:"string"},nullable:!0},t:{...h6,nullable:!0}},required:["i"],additionalProperties:!1};var _I={type:"array",items:{...II}};var SI={type:"object",properties:{i:{type:"number"},a:{type:"number",nullable:!0},e:{type:"number",nullable:!0},c:{...h6,nullable:!0},d:{type:"number",nullable:!0},n:{type:"number",nullable:!0},o:{...W1,nullable:!0},p:{...W1,nullable:!0},pe:{type:"number",minimum:0,maximum:1,nullable:!0},rm:{type:"boolean",nullable:!0},t:{type:"number",nullable:!0},te:{type:"number",nullable:!0},tp:{...W1,nullable:!0}},required:["i"],additionalProperties:!1};var vI={type:"array",items:{...SI}};var AI={type:"object",properties:{i:{type:"number"},at:{type:"number",nullable:!0},ce:{...h6,nullable:!0},cev:{...h6,nullable:!0},cs:{...h6,nullable:!0},csv:{...h6,nullable:!0},e:{type:"number",nullable:!0},en:{type:"string",nullable:!0},g:{...W1,nullable:!0},l:{type:"number",nullable:!0},lv:{type:"number",nullable:!0},mp:{type:"number",nullable:!0},o:{...W1,nullable:!0},oe:{type:"number",nullable:!0},oev:{type:"number",nullable:!0},os:{type:"number",nullable:!0},osv:{type:"number",nullable:!0},p:{...W1,nullable:!0},pa:{type:"boolean",nullable:!0},pv:{...W1,nullable:!0},r:{type:"number",nullable:!0},rv:{type:"number",nullable:!0},rm:{type:"boolean",nullable:!0},se:{type:"number",nullable:!0},sev:{type:"number",nullable:!0},ss:{type:"number",nullable:!0},ssv:{type:"number",nullable:!0},t:{type:"boolean",nullable:!0},tu:{type:"string",nullable:!0},v:{...W1,nullable:!0},vv:{...W1,nullable:!0}},required:["i"],additionalProperties:!1};var xI={type:"array",items:{...AI}};var hI={type:"object",properties:{o:{...W1},d:{...W1},l:{type:"number"},h:{type:"boolean"}},required:["o","d","l","h"],additionalProperties:!1};var fI={type:"array",items:{...hI}};var yI={type:"object",properties:{v:{type:"array",items:{type:"number"}},c:{type:"array",items:{type:"number"}}},required:["v","c"],additionalProperties:!1};var bI={type:"object",properties:{i:{type:"string"},p:{type:"string",nullable:!0},rm:{type:"boolean",nullable:!0},u:{type:"string",nullable:!0}},required:["i"],additionalProperties:!1};var gI={type:"array",items:{...bI}};var mI={type:"object",properties:{i:{type:"number"},e:{type:"number",nullable:!0},o:{...W1,nullable:!0},p:{...W1,nullable:!0},rm:{type:"boolean",nullable:!0},s:{type:"object",nullable:!0},t:{type:"string",nullable:!0},v:{type:"number",nullable:!0}},required:["i"],additionalProperties:!1};var uI={type:"array",items:{...mI}};var dI={type:"object",properties:{r:{type:"number"},s:{type:"number"},p:{type:"number"},n:{type:"number"}},required:["r","s","p","n"],additionalProperties:!1};var cI={type:"object",properties:{p:{type:"boolean",nullable:!0},u:{type:"string",nullable:!0}},additionalProperties:!1};var lI={type:"array",items:{...dV}};var Jh1={type:"array",items:[{type:"boolean"},{type:"boolean"},{type:"boolean"}],minItems:3,maxItems:3};var pI={type:"object",properties:{i:{type:"number"},ac:{...h6,nullable:!0},ai:{type:"number",nullable:!0},dc:{...h6,nullable:!0},di:{type:"number",nullable:!0},dp:{...W1,nullable:!0},fc:{...h6,nullable:!0},ff:{type:"number",nullable:!0},fn:{type:"number",nullable:!0},n:{type:"string",nullable:!0},s:{type:"string",nullable:!0},si:{type:"number",nullable:!0},t:{type:"number",nullable:!0}},required:["i"],additionalProperties:!1};var O60=I0(40,PI);var M60=I0(36,DI);var R60=I0(37,TI);var N60=I0(38,_I);var P60=I0(44,vI);var D60=I0(46,xI);var C60=I0(192,yI);var T60=I0(193,fI);var E60=I0(45,gI);var k60=I0(43,uI);var I60=I0(32,dI);var _60=I0(41,cI);var S60=I0(42,lI);var v60=I0(39,pI);var dw=new Map,Xh1={...gw,...mw,...uw};for(let Z of Object.values(Xh1))if("id"in Z&&"schema"in Z){let J=Z;if(dw.has(J.id))throw new Error(`Packet with id ${J.id} is already registered.`);dw.set(J.id,J)}function Yh1(Z){if(typeof Z!=="object"||Z===null||typeof Z[0]!=="number"||Z[0]<0||Z[1]===void 0||Z[2]!==void 0&&(typeof Z[2]!=="number"||Z[2]<0))return!1;let J=dw.get(Z[0]);return!!J&&J.validate(Z[1])}var Y0=iI;var Y50=r(J50(),1);import T$ from"fs";import X50 from"path";var lV="./dev/persistence";class f7{static instance=new f7;gameId=process.env.HYTOPIA_GAME_ID;lobbyId=process.env.HYTOPIA_LOBBY_ID;_creativeGateway;constructor(){try{this._creativeGateway=new Y50.CreativeGateway}catch{console.warn(["━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━","\uD83D\uDEA8 HYTOPIA PLATFORM GATEWAY IS NOT INITIALIZED \uD83D\uDEA8","","\uD83D\uDD27 Local development is still possible, but these features will be disabled:"," • \uD83D\uDC64 Player Accounts"," • \uD83C\uDFAD Player Cosmetics"," • \uD83D\uDC1B Crash Analytics & Debug Logs","","\uD83D\uDCA1 These features will be enabled but modified:"," • \uD83D\uDCBE Player & Global Persisted Data - Data will be persisted"," locally in the ./dev/persistence directory of your project."," Player ids for data persistence will begin at 1 for the first "," player to join your local server, and increments for each"," additional player. This means that if you restart your"," server, the first player id will be 1 again. This is to ensure"," that data persistence across server restarts can be easily"," tested and debugged in local development.","","To enable the HYTOPIA Platform Gateway locally:"," 1. Set these environment variables:"," HYTOPIA_API_KEY, HYTOPIA_GAME_ID, HYTOPIA_LOBBY_ID"," 2. You can find these values at: https://create.hytopia.com","","Note: In production, these environment variables will be auto-populated ","& the HYTOPIA Platform Gateway will automatically be initialized \uD83D\uDE80","━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",""].join(`
|
|
415
|
-
`))}}get isGatewayAvailable(){return!!this._creativeGateway}async getData(Z){if(!this._creativeGateway&&process.env.NODE_ENV==="production")return d.warning("PlatformGateway.getData(): You are running in production mode, but the Platform Gateway is not initialized! No data will be returned.");return this._creativeGateway?await this._creativeGateway.kv.get(Z):this._readDevDataLocally(Z)}async getPlayerLoadout(Z){if(!this._creativeGateway)return;return await this._creativeGateway.getLoadout(Z)}async getPlayerSession(Z){if(!this._creativeGateway)return;return await this._creativeGateway.getSession(Z)}async setData(Z,J){if(J.error)return d.warning("PlatformGateway.setData(): Cannot set data with an error property.");if(!this._creativeGateway&&process.env.NODE_ENV==="production")return d.warning("PlatformGateway.setData(): You are running in production mode, but the Platform Gateway is not initialized! No data will be set.");return this._creativeGateway?await this._creativeGateway.kv.set(Z,J):this._writeDevDataLocally(Z,J)}_readDevDataLocally(Z){try{if(!T$.existsSync(lV))return;let J=X50.join(lV,`${Z}.json`);return JSON.parse(T$.readFileSync(J,"utf8"))}catch(J){d.warning(`PlatformGateway._readDevDataLocally(): Failed to read data for key "${Z}": ${J}`)}}_writeDevDataLocally(Z,J){try{if(!T$.existsSync(lV))T$.mkdirSync(lV,{recursive:!0});let X=X50.join(lV,`${Z}.json`),Y={};if(T$.existsSync(X))Y=JSON.parse(T$.readFileSync(X,"utf8"));let $={...Y,...J};T$.writeFileSync(X,JSON.stringify($,null,2),"utf8")}catch(X){d.warning(`PlatformGateway._writeDevDataLocally(): Failed to write data for key "${Z}": ${X}`)}}}class E${static instance=new E$;constructor(){}async getGlobalData(Z){let J=await f7.instance.getData(Z);if(!J||J.error){if(J?.error)d.warning(`PersistenceManager.getGlobalData(): ${J.error.message}`);return}return J}async getPlayerData(Z){let J=await f7.instance.getData(this._getPlayerKey(Z));if(!J||J.error){if(J?.error)d.warning(`PersistenceManager.getPlayerData(): ${J.error.message}`);return}return J}async setGlobalData(Z,J){let X=await f7.instance.setData(Z,J);if(!X||X.error){if(X?.error)d.warning(`PersistenceManager.setGlobalData(): ${X.error.message}`);return}return X}async setPlayerData(Z,J){let X=await f7.instance.setData(this._getPlayerKey(Z),J);if(!X||X.error){if(X?.error)d.warning(`PersistenceManager.setPlayerData(): ${X.error.message}`);return}return X}_getPlayerKey(Z){return`player-${Z.id}`}}var $50;((Y)=>{Y[Y.FIRST_PERSON=0]="FIRST_PERSON";Y[Y.THIRD_PERSON=1]="THIRD_PERSON";Y[Y.SPECTATOR=2]="SPECTATOR"})($50||={});var aI;((B)=>{B.LOOK_AT_ENTITY="PLAYER_CAMERA.LOOK_AT_ENTITY";B.LOOK_AT_POSITION="PLAYER_CAMERA.LOOK_AT_POSITION";B.SET_ATTACHED_TO_ENTITY="PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY";B.SET_ATTACHED_TO_POSITION="PLAYER_CAMERA.SET_ATTACHED_TO_POSITION";B.SET_FILM_OFFSET="PLAYER_CAMERA.SET_FILM_OFFSET";B.SET_FORWARD_OFFSET="PLAYER_CAMERA.SET_FORWARD_OFFSET";B.SET_FOV="PLAYER_CAMERA.SET_FOV";B.SET_MODEL_HIDDEN_NODES="PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES";B.SET_MODEL_SHOWN_NODES="PLAYER_CAMERA.SET_MODEL_SHOWN_NODES";B.SET_MODE="PLAYER_CAMERA.SET_MODE";B.SET_OFFSET="PLAYER_CAMERA.SET_OFFSET";B.SET_SHOULDER_ANGLE="PLAYER_CAMERA.SET_SHOULDER_ANGLE";B.SET_TRACKED_ENTITY="PLAYER_CAMERA.SET_TRACKED_ENTITY";B.SET_TRACKED_POSITION="PLAYER_CAMERA.SET_TRACKED_POSITION";B.SET_ZOOM="PLAYER_CAMERA.SET_ZOOM"})(aI||={});class pV extends O0{player;_attachedToEntity;_attachedToPosition;_filmOffset=0;_forwardOffset=0;_fov=75;_modelHiddenNodes=new Set;_modelShownNodes=new Set;_mode=1;_offset={x:0,y:0,z:0};_orientation={pitch:0,yaw:0};_shoulderAngle=0;_trackedEntity;_trackedPosition;_zoom=1;constructor(Z){super();this.player=Z}get attachedToEntity(){return this._attachedToEntity}get attachedToPosition(){return this._attachedToPosition}get facingDirection(){return{x:-Math.sin(this._orientation.yaw)*Math.cos(this._orientation.pitch),y:Math.sin(this._orientation.pitch),z:-Math.cos(this._orientation.yaw)*Math.cos(this._orientation.pitch)}}get facingQuaternion(){let Z=this._orientation.pitch*0.5,J=this._orientation.yaw*0.5,X=Math.cos(Z),Y=Math.sin(Z),$=Math.cos(J),Q=Math.sin(J);return{x:Y*$,y:X*Q,z:-Y*Q,w:X*$}}get filmOffset(){return this._filmOffset}get forwardOffset(){return this._forwardOffset}get fov(){return this._fov}get modelHiddenNodes(){return this._modelHiddenNodes}get modelShownNodes(){return this._modelShownNodes}get mode(){return this._mode}get offset(){return this._offset}get orientation(){return this._orientation}get shoulderAngle(){return this._shoulderAngle}get trackedEntity(){return this._trackedEntity}get trackedPosition(){return this._trackedPosition}get zoom(){return this._zoom}lookAtEntity(Z){if(!this._requirePlayerWorld("lookAtEntity"))return;this.emitWithWorld(this.player.world,"PLAYER_CAMERA.LOOK_AT_ENTITY",{playerCamera:this,entity:Z})}lookAtPosition(Z){if(!this._requirePlayerWorld("lookAtPosition"))return;this.emitWithWorld(this.player.world,"PLAYER_CAMERA.LOOK_AT_POSITION",{playerCamera:this,position:Z})}reset(){this._attachedToEntity=void 0,this._attachedToPosition=void 0,this._orientation={pitch:0,yaw:0},this._trackedEntity=void 0,this._trackedPosition=void 0}setAttachedToEntity(Z){if(!this._requirePlayerWorld("setAttachedToEntity"))return;if(!Z.isSpawned)return d.error(`PlayerCamera.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);this._attachedToEntity=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY",{playerCamera:this,entity:Z})}setAttachedToPosition(Z){if(!this._requirePlayerWorld("setAttachedToPosition"))return;this._attachedToPosition=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_ATTACHED_TO_POSITION",{playerCamera:this,position:Z})}setFilmOffset(Z){if(!this._requirePlayerWorld("setFilmOffset"))return;this._filmOffset=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_FILM_OFFSET",{playerCamera:this,filmOffset:Z})}setForwardOffset(Z){if(!this._requirePlayerWorld("setForwardOffset"))return;this._forwardOffset=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_FORWARD_OFFSET",{playerCamera:this,forwardOffset:Z})}setFov(Z){if(!this._requirePlayerWorld("setFov"))return;this._fov=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_FOV",{playerCamera:this,fov:Z})}setModelHiddenNodes(Z){if(!this._requirePlayerWorld("setModelHiddenNodes"))return;this._modelHiddenNodes=new Set(Z.map((J)=>J.toLowerCase())),this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES",{playerCamera:this,modelHiddenNodes:this._modelHiddenNodes})}setModelShownNodes(Z){if(!this._requirePlayerWorld("setModelShownNodes"))return;this._modelShownNodes=new Set(Z.map((J)=>J.toLowerCase())),this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_MODEL_SHOWN_NODES",{playerCamera:this,modelShownNodes:this._modelShownNodes})}setMode(Z){if(!this._requirePlayerWorld("setMode"))return;this._mode=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_MODE",{playerCamera:this,mode:Z})}setOffset(Z){if(!this._requirePlayerWorld("setOffset"))return;this._offset=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_OFFSET",{playerCamera:this,offset:Z})}setOrientationPitch(Z){this._orientation.pitch=Z}setOrientationYaw(Z){this._orientation.yaw=Z}setShoulderAngle(Z){if(!this._requirePlayerWorld("setShoulderAngle"))return;this._shoulderAngle=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_SHOULDER_ANGLE",{playerCamera:this,shoulderAngle:Z})}setTrackedEntity(Z){if(!this._requirePlayerWorld("setTrackedEntity"))return;this._trackedEntity=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_TRACKED_ENTITY",{playerCamera:this,entity:Z})}setTrackedPosition(Z){if(!this._requirePlayerWorld("setTrackedPosition"))return;this._trackedPosition=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_TRACKED_POSITION",{playerCamera:this,position:Z})}setZoom(Z){if(!this._requirePlayerWorld("setZoom"))return;this._zoom=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_ZOOM",{playerCamera:this,zoom:Z})}serialize(){if(!this.player.world)d.fatalError("PlayerCamera.serialize(): PlayerCamera player is not in a world and cannot be serialized!");return P0.serializePlayerCamera(this,this.player.world.tickAllocator)}_requirePlayerWorld(Z){if(!this.player.world)d.error(`PlayerCamera._requirePlayerWorld(): Player ${this.player.id} is not in a world, invoked method: ${Z}()`);return!!this.player.world}}var lw;(($)=>{$.DATA="PLAYER_UI.DATA";$.LOAD="PLAYER_UI.LOAD";$.LOCK_POINTER="PLAYER_UI.LOCK_POINTER";$.SEND_DATA="PLAYER_UI.SEND_DATA"})(lw||={});class iV extends O0{player;constructor(Z){super();this.player=Z}load(Z){if(!this.player.world)return;this.emitWithWorld(this.player.world,"PLAYER_UI.LOAD",{playerUI:this,htmlUri:Z})}lockPointer(Z){if(!this.player.world)return;this.emitWithWorld(this.player.world,"PLAYER_UI.LOCK_POINTER",{playerUI:this,lock:Z})}sendData(Z){if(!this.player.world)return;this.emitWithWorld(this.player.world,"PLAYER_UI.SEND_DATA",{playerUI:this,data:Z})}}var Q50=["w","a","s","d","sp","sh","tb","ml","mr","q","e","r","f","z","x","c","v","u","i","o","j","k","l","n","m","1","2","3","4","5","6","7","8","9","0"],nV;((Q)=>{Q.CHAT_MESSAGE_SEND="PLAYER.CHAT_MESSAGE_SEND";Q.JOINED_WORLD="PLAYER.JOINED_WORLD";Q.LEFT_WORLD="PLAYER.LEFT_WORLD";Q.RECONNECTED_WORLD="PLAYER.RECONNECTED_WORLD";Q.REQUEST_SYNC="PLAYER.REQUEST_SYNC"})(nV||={});class CG extends O0{static _devNextPlayerId=1;id;username;profilePictureUrl;camera;connection;ui;_input={};_lastUnreliableInputSequenceNumber=0;_persistedData;_world;_worldSwitched=!1;constructor(Z,J){super();this.id=J?.user.id??`player-${CG._devNextPlayerId++}`,this.username=J?.user.username??this.id,this.profilePictureUrl=J?.user.profilePictureURL??void 0,this.camera=new pV(this),this.connection=Z,this.ui=new iV(this),Z.onPacket(Y0.PacketId.CHAT_MESSAGE_SEND,this._onChatMessageSendPacket),Z.onPacket(Y0.PacketId.DEBUG_CONFIG,this._onDebugConfigPacket),Z.onPacket(Y0.PacketId.INPUT,this._onInputPacket),Z.onPacket(Y0.PacketId.SYNC_REQUEST,this._onSyncRequestPacket),Z.onPacket(Y0.PacketId.UI_DATA_SEND,this._onUIDataSendPacket)}get input(){return this._input}get world(){return this._world}disconnect(){this._leaveWorld(),this.connection.disconnect()}getPersistedData(){return this._persistedData}joinWorld(Z){if(this._world===Z)return;if(!this._world)this._world=Z,this.emitWithWorld(this._world,"PLAYER.JOINED_WORLD",{player:this,world:this._world});else{for(let J of this._world.entityManager.getPlayerEntitiesByPlayer(this))if(J.isSpawned)J.despawn();this.disconnect(),this._world=Z,this._worldSwitched=!0}}async loadInitialPersistedData(){if(this._persistedData)return;this._persistedData=await E$.instance.getPlayerData(this)??void 0}reconnected(){if(!this._world)return;if(this._lastUnreliableInputSequenceNumber=0,!this._worldSwitched)this.emitWithWorld(this._world,"PLAYER.RECONNECTED_WORLD",{player:this,world:this._world});else this._worldSwitched=!1,this.emitWithWorld(this._world,"PLAYER.JOINED_WORLD",{player:this,world:this._world})}resetInputs(){this._input={}}setPersistedData(Z){return this._persistedData={...this._persistedData,...Z},E$.instance.setPlayerData(this,Z).catch((J)=>{}),this._persistedData}serialize(){if(!this._world)d.fatalError("Player.serialize(): Player is not in a world and cannot be serialized!");return P0.serializePlayer(this,this._world.tickAllocator)}_leaveWorld(){if(!this._world)return;this.emitWithWorld(this._world,"PLAYER.LEFT_WORLD",{player:this,world:this._world}),this._world=void 0}_onChatMessageSendPacket=(Z)=>{if(this._world)this.emitWithWorld(this._world,"PLAYER.CHAT_MESSAGE_SEND",{player:this,message:Z[1].m})};_onDebugConfigPacket=(Z)=>{console.log(Z)};_onInputPacket=(Z)=>{let J=Z[1];if(J.sq!==void 0){if(J.sq<this._lastUnreliableInputSequenceNumber)return;this._lastUnreliableInputSequenceNumber=J.sq}if(Q50.forEach((X)=>{let Y=X;if(J[Y]!==void 0)this._input[Y]=Boolean(J[Y])}),J.cp!==void 0)this.camera.setOrientationPitch(J.cp);if(J.cy!==void 0)this.camera.setOrientationYaw(J.cy)};_onSyncRequestPacket=()=>{if(this._world)this.emitWithWorld(this._world,"PLAYER.REQUEST_SYNC",{player:this,receivedAt:Date.now(),receivedAtMs:performance.now()})};_onUIDataSendPacket=(Z)=>{this.ui.emit("PLAYER_UI.DATA",{playerUI:this.ui,data:Z[1]})}}var sI;((X)=>{X.BROADCAST_MESSAGE="CHAT.BROADCAST_MESSAGE";X.PLAYER_MESSAGE="CHAT.PLAYER_MESSAGE"})(sI||={});class aV extends O0{_commandCallbacks={};_world;constructor(Z){super();this._world=Z,this._subscribeToPlayerEvents()}registerCommand(Z,J){this._commandCallbacks[Z]=J}unregisterCommand(Z){delete this._commandCallbacks[Z]}sendBroadcastMessage(Z,J){this._sendBroadcastMessage(void 0,Z,J)}sendPlayerMessage(Z,J,X){this.emitWithWorld(this._world,"CHAT.PLAYER_MESSAGE",{player:Z,message:J,color:X})}_subscribeToPlayerEvents(){this._world.on("PLAYER.CHAT_MESSAGE_SEND",(Z)=>{let{player:J,message:X}=Z,[Y,...$]=X.split(" "),Q=this._commandCallbacks[Y];if(Q){Q(J,$,X);return}this._sendBroadcastMessage(J,X)})}_sendBroadcastMessage(Z,J,X){this.emitWithWorld(this._world,"CHAT.BROADCAST_MESSAGE",{player:Z,message:J,color:X})}}var G9=16,oI=G9-1,kh1=G9**3;class W9{_blocks;_chunkLattice;_originCoordinate;constructor(Z,J){this._blocks=new Uint8Array(kh1),this._chunkLattice=Z,this._originCoordinate=J}get blocks(){return this._blocks}get chunkLattice(){return this._chunkLattice}get originCoordinate(){return this._originCoordinate}static blockIndexToLocalCoordinate(Z){return{x:Z%G9,y:(Z/G9|0)%G9,z:Z/(G9*G9)|0}}static globalCoordinateToLocalCoordinate(Z){return{x:Z.x&G9-1,y:Z.y&G9-1,z:Z.z&G9-1}}static globalCoordinateToOriginCoordinate(Z){return{x:Z.x&~(G9-1),y:Z.y&~(G9-1),z:Z.z&~(G9-1)}}getBlockId(Z){return this._blocks[this._getIndex(Z)]}hasBlock(Z){return this._blocks[this._getIndex(Z)]!==0}setBlock(Z,J){if(!this._isValidLocalCoordinate(Z))return d.error("Chunk.setBlock(): Block local coordinate is out of bounds");let X=this._getIndex(Z);this._blocks[X]=J}serialize(){return P0.serializeChunk(this,this._chunkLattice.world.tickAllocator)}_getIndex(Z){return Z.x+(Z.y<<4)+(Z.z<<8)}_isValidLocalCoordinate(Z){return Z.x>=0&&Z.x<=oI&&Z.y>=0&&Z.y<=oI&&Z.z>=0&&Z.z<=oI}}var rI;((X)=>{X.REMOVE_CHUNK="CHUNK_LATTICE.REMOVE_CHUNK";X.SET_BLOCK="CHUNK_LATTICE.SET_BLOCK"})(rI||={});class sV extends O0{_blockTypeColliders=new Map;_blockTypeCounts=new Map;_chunks=new Map;_rigidBody;_world;constructor(Z){super();this._world=Z}get chunkCount(){return this._chunks.size}get world(){return this._world}clear(){for(let Z of this._blockTypeColliders.values())this._world.simulation.colliderMap.removeColliderBlockType(Z),Z.removeFromSimulation();this._chunks.forEach((Z)=>{this.emitWithWorld(this._world,"CHUNK_LATTICE.REMOVE_CHUNK",{chunkLattice:this,chunk:Z})}),this._blockTypeColliders.clear(),this._blockTypeCounts.clear(),this._chunks.clear()}getBlockId(Z){let J=this.getChunk(W9.globalCoordinateToOriginCoordinate(Z));if(!J)return 0;return J.getBlockId(W9.globalCoordinateToLocalCoordinate(Z))}getBlockTypeCollider(Z){return this._blockTypeColliders.get(Z)}getBlockType(Z){let J=this.getBlockId(Z);return J?this._world.blockTypeRegistry.getBlockType(J):null}getBlockTypeCount(Z){return this._blockTypeCounts.get(Z)??0}getChunk(Z){return this._chunks.get(this._getChunkKey(W9.globalCoordinateToOriginCoordinate(Z)))}getOrCreateBlockTypeCollider(Z,J){let X=this._blockTypeColliders.get(Z);if(X)return X;let $=this._world.blockTypeRegistry.getBlockType(Z).createCollider(J);return this._blockTypeColliders.set(Z,$),$}getOrCreateChunk(Z){let J=W9.globalCoordinateToOriginCoordinate(Z),X=this._chunks.get(this._getChunkKey(J));if(X)return X;return X=new W9(this,J),this._chunks.set(this._getChunkKey(J),X),X}getAllChunks(Z=!1){return Z?this._world.tickAllocator.getArray(this._chunks.values()):Array.from(this._chunks.values())}hasBlock(Z){let J=this.getChunk(W9.globalCoordinateToOriginCoordinate(Z));if(!J)return!1;return J.hasBlock(W9.globalCoordinateToLocalCoordinate(Z))}hasChunk(Z){let J=W9.globalCoordinateToOriginCoordinate(Z);return this._chunks.has(this._getChunkKey(J))}setBlock(Z,J){let X=W9.globalCoordinateToLocalCoordinate(Z),Y=this.getOrCreateChunk(Z),$=Y.getBlockId(X);if($===J)return;if(Y.setBlock(X,J),!this._rigidBody)this._rigidBody=new O$({type:"fixed"}),this._rigidBody.addToSimulation(this._world.simulation);if($!==0){let Q=Math.max(0,(this._blockTypeCounts.get($)??0)-1),K=this.getBlockTypeCollider($);if(K)if(Q===0)this._world.simulation.colliderMap.removeColliderBlockType(K),K.removeFromSimulation(),this._blockTypeColliders.delete($);else K.setVoxel(Z,!1),this._propagateVoxelChange(K,Z);this._blockTypeCounts.set($,Q)}if(J!==0){let Q=(this._blockTypeCounts.get(J)??0)+1,K=this.getOrCreateBlockTypeCollider(J,[Z]);if(Q===1){let G=this._world.blockTypeRegistry.getBlockType(J);K.addToSimulation(this._world.simulation,this._rigidBody),this._world.simulation.colliderMap.setColliderBlockType(K,G),this._combineVoxelStates(K)}else K.setVoxel(Z,!0),this._propagateVoxelChange(K,Z);this._blockTypeCounts.set(J,Q)}this.emitWithWorld(this._world,"CHUNK_LATTICE.SET_BLOCK",{chunkLattice:this,chunk:Y,globalCoordinate:Z,localCoordinate:X,blockTypeId:J})}_combineVoxelStates(Z){if(Z.isSensor)return;for(let J of this._blockTypeColliders.values()){if(J===Z||J.isSensor)continue;Z.combineVoxelStates(J)}}_getChunkKey(Z){return`${Z.x},${Z.y},${Z.z}`}_propagateVoxelChange(Z,J){if(Z.isSensor)return;for(let X of this._blockTypeColliders.values()){if(X===Z||X.isSensor)continue;Z.propagateVoxelChange(X,J)}}}class oV{_colliderHandleBlockTypeMap=new Map;_colliderHandleCollisionCallbackMap=new Map;_colliderHandleEntityMap=new Map;_cleanupBlockTypeColliderHandles=new Set;_pendingCleanupBlockTypeColliderHandles=new Set;_cleanupCollisionCallbackColliderHandles=new Set;_pendingCleanupCollisionCallbackColliderHandles=new Set;_cleanupEntityColliderHandles=new Set;_pendingCleanupEntityColliderHandles=new Set;getColliderBlockType(Z){if(!this._requireSimulatedCollider(Z))return;return this._colliderHandleBlockTypeMap.get(Z.rawCollider.handle)}getColliderCollisionCallback(Z){if(!this._requireSimulatedCollider(Z))return;return this._colliderHandleCollisionCallbackMap.get(Z.rawCollider.handle)}getColliderEntity(Z){if(!this._requireSimulatedCollider(Z))return;return this._colliderHandleEntityMap.get(Z.rawCollider.handle)}getColliderHandleBlockType(Z){return this._colliderHandleBlockTypeMap.get(Z)}getColliderHandleCollisionCallback(Z){return this._colliderHandleCollisionCallbackMap.get(Z)}getColliderHandleEntity(Z){return this._colliderHandleEntityMap.get(Z)}removeColliderBlockType(Z){if(!this._requireSimulatedCollider(Z))return;this.removeColliderHandleBlockType(Z.rawCollider.handle)}removeColliderCollisionCallback(Z){if(!this._requireSimulatedCollider(Z))return;this.removeColliderHandleCollisionCallback(Z.rawCollider.handle)}removeColliderEntity(Z){if(!this._requireSimulatedCollider(Z))return;this.removeColliderHandleEntity(Z.rawCollider.handle)}removeColliderHandleBlockType(Z){this._colliderHandleBlockTypeMap.delete(Z)}removeColliderHandleCollisionCallback(Z){this._colliderHandleCollisionCallbackMap.delete(Z)}removeColliderHandleEntity(Z){this._colliderHandleEntityMap.delete(Z)}setColliderBlockType(Z,J){if(!this._requireSimulatedCollider(Z))return;this.setColliderHandleBlockType(Z.rawCollider.handle,J)}setColliderCollisionCallback(Z,J){if(!this._requireSimulatedCollider(Z))return;this.setColliderHandleCollisionCallback(Z.rawCollider.handle,J)}setColliderEntity(Z,J){if(!this._requireSimulatedCollider(Z))return;this.setColliderHandleEntity(Z.rawCollider.handle,J)}setColliderHandleBlockType(Z,J){this._colliderHandleBlockTypeMap.set(Z,J),this._cleanupBlockTypeColliderHandles.delete(Z),this._pendingCleanupBlockTypeColliderHandles.delete(Z)}setColliderHandleCollisionCallback(Z,J){this._colliderHandleCollisionCallbackMap.set(Z,J),this._cleanupCollisionCallbackColliderHandles.delete(Z),this._pendingCleanupCollisionCallbackColliderHandles.delete(Z)}setColliderHandleEntity(Z,J){this._colliderHandleEntityMap.set(Z,J),this._cleanupEntityColliderHandles.delete(Z),this._pendingCleanupEntityColliderHandles.delete(Z)}queueColliderHandleForCleanup(Z){if(this._colliderHandleBlockTypeMap.has(Z))this._pendingCleanupBlockTypeColliderHandles.add(Z);if(this._colliderHandleCollisionCallbackMap.has(Z))this._pendingCleanupCollisionCallbackColliderHandles.add(Z);if(this._colliderHandleEntityMap.has(Z))this._pendingCleanupEntityColliderHandles.add(Z)}cleanup(){for(let Z of this._cleanupBlockTypeColliderHandles)this._colliderHandleBlockTypeMap.delete(Z);if(this._cleanupBlockTypeColliderHandles.size>0)this._cleanupBlockTypeColliderHandles.clear();for(let Z of this._cleanupCollisionCallbackColliderHandles)this._colliderHandleCollisionCallbackMap.delete(Z);if(this._cleanupCollisionCallbackColliderHandles.size>0)this._cleanupCollisionCallbackColliderHandles.clear();for(let Z of this._cleanupEntityColliderHandles)this._colliderHandleEntityMap.delete(Z);if(this._cleanupEntityColliderHandles.size>0)this._cleanupEntityColliderHandles.clear();for(let Z of this._pendingCleanupBlockTypeColliderHandles)this._cleanupBlockTypeColliderHandles.add(Z);if(this._pendingCleanupBlockTypeColliderHandles.size>0)this._pendingCleanupBlockTypeColliderHandles.clear();for(let Z of this._pendingCleanupCollisionCallbackColliderHandles)this._cleanupCollisionCallbackColliderHandles.add(Z);if(this._pendingCleanupCollisionCallbackColliderHandles.size>0)this._pendingCleanupCollisionCallbackColliderHandles.clear();for(let Z of this._pendingCleanupEntityColliderHandles)this._cleanupEntityColliderHandles.add(Z);if(this._pendingCleanupEntityColliderHandles.size>0)this._pendingCleanupEntityColliderHandles.clear()}_requireSimulatedCollider(Z){if(!Z.rawCollider)d.error("ColliderMap._requireSimulatedCollider(): Collider is not in the simulation.");return!!Z.rawCollider}}var K50={type:"dynamic",softCcdPrediction:1},G50=0.015625,W50=Math.cos(0.026),rV;((R)=>{R.BLOCK_COLLISION="ENTITY.BLOCK_COLLISION";R.BLOCK_CONTACT_FORCE="ENTITY.BLOCK_CONTACT_FORCE";R.DESPAWN="ENTITY.DESPAWN";R.ENTITY_COLLISION="ENTITY.ENTITY_COLLISION";R.ENTITY_CONTACT_FORCE="ENTITY.ENTITY_CONTACT_FORCE";R.SET_MODEL_ANIMATIONS_PLAYBACK_RATE="ENTITY.SET_MODEL_ANIMATIONS_PLAYBACK_RATE";R.SET_MODEL_HIDDEN_NODES="ENTITY.SET_MODEL_HIDDEN_NODES";R.SET_MODEL_SCALE="ENTITY.SET_MODEL_SCALE";R.SET_MODEL_SHOWN_NODES="ENTITY.SET_MODEL_SHOWN_NODES";R.SET_MODEL_TEXTURE_URI="ENTITY.SET_MODEL_TEXTURE_URI";R.SET_OPACITY="ENTITY.SET_OPACITY";R.SET_PARENT="ENTITY.SET_PARENT";R.SET_TINT_COLOR="ENTITY.SET_TINT_COLOR";R.SPAWN="ENTITY.SPAWN";R.START_MODEL_LOOPED_ANIMATIONS="ENTITY.START_MODEL_LOOPED_ANIMATIONS";R.START_MODEL_ONESHOT_ANIMATIONS="ENTITY.START_MODEL_ONESHOT_ANIMATIONS";R.STOP_MODEL_ANIMATIONS="ENTITY.STOP_MODEL_ANIMATIONS";R.TICK="ENTITY.TICK";R.UPDATE_POSITION="ENTITY.UPDATE_POSITION";R.UPDATE_ROTATION="ENTITY.UPDATE_ROTATION"})(rV||={});class i8 extends O${_id;_blockHalfExtents;_blockTextureUri;_controller;_isEnvironmental=!1;_modelAnimationsPlaybackRate=1;_modelHiddenNodes=new Set;_modelLoopedAnimations=new Set;_modelOneshotAnimations=new Set;_modelPreferredShape;_modelScale=1;_modelShownNodes=new Set;_modelTextureUri;_modelUri;_name;_opacity;_parent;_parentNodeName;_tag;_tintColor;_lastUpdatedPosition={x:0,y:0,z:0};_lastUpdatedRotation={x:0,y:0,z:0,w:1};_lastParentlessType="dynamic";_world;_positionUpdateThresholdSq;_rotationUpdateThreshold;constructor(Z){let J="blockTextureUri"in Z,X="modelUri"in Z;if(!J===!X)d.fatalError("Entity.constructor(): Entity data must include a blockTextureUri or modelUri, but not both.");if(J&&!Z.blockHalfExtents)d.fatalError("Entity.constructor(): Block entity must have blockHalfExtents!");if(Z.parent&&!Z.parent.isSpawned)d.fatalError("Entity.constructor(): Parent entity must be spawned before child entity!");if(Z.parent?.modelUri&&Z.parentNodeName&&!S5.instance.modelHasNode(Z.parent.modelUri,Z.parentNodeName))d.fatalError(`Entity.constructor(): Parent node name ${Z.parentNodeName} not found in parent model ${Z.parent.modelUri}!`);super(Z.rigidBodyOptions??K50);if(J)this._blockHalfExtents=Z.blockHalfExtents,this._blockTextureUri=Z.blockTextureUri;if(X)this._modelAnimationsPlaybackRate=Z.modelAnimationsPlaybackRate??1,this._modelPreferredShape=Z.modelPreferredShape,this._modelScale=Z.modelScale??1,this._modelTextureUri=Z.modelTextureUri,this._modelUri=Z.modelUri,Z.modelHiddenNodes?.forEach((Y)=>this._modelHiddenNodes.add(Y.toLowerCase())),Z.modelLoopedAnimations?.forEach((Y)=>this._modelLoopedAnimations.add(Y)),Z.modelShownNodes?.forEach((Y)=>this._modelShownNodes.add(Y.toLowerCase()));if(this._isEnvironmental=Z.isEnvironmental??!1,this._name=Z.name??"Nameless",this._opacity=Z.opacity??1,this._parent=Z.parent,this._parentNodeName=Z.parentNodeName,this._tag=Z.tag,this._tintColor=Z.tintColor,this._positionUpdateThresholdSq=G50,this._rotationUpdateThreshold=W50,Z.controller)this.setController(Z.controller)}get id(){return this._id}get blockHalfExtents(){return this._blockHalfExtents}get blockTextureUri(){return this._blockTextureUri}get controller(){return this._controller}get depth(){return this.isModelEntity?S5.instance.getDepth(this._modelUri)*(this._modelScale??1):this._blockHalfExtents.z*2}get height(){return this.isModelEntity?S5.instance.getHeight(this._modelUri)*(this._modelScale??1):this._blockHalfExtents.y*2}get modelAnimationsPlaybackRate(){return this._modelAnimationsPlaybackRate}get modelHiddenNodes(){return this._modelHiddenNodes}get modelLoopedAnimations(){return this._modelLoopedAnimations}get modelPreferredShape(){return this._modelPreferredShape}get modelScale(){return this._modelScale}get modelShownNodes(){return this._modelShownNodes}get modelTextureUri(){return this._modelTextureUri}get modelUri(){return this._modelUri}get name(){return this._name}get opacity(){return this._opacity}get parent(){return this._parent}get parentNodeName(){return this._parentNodeName}get tag(){return this._tag}get tintColor(){return this._tintColor}get isBlockEntity(){return!!this._blockTextureUri}get isEnvironmental(){return this._isEnvironmental}get isModelEntity(){return!!this._modelUri}get isSpawned(){return!!this._world}get width(){return this.isModelEntity?S5.instance.getWidth(this._modelUri)*(this._modelScale??1):this._blockHalfExtents.x*2}get world(){return this._world}spawn(Z,J,X){if(this.isSpawned)return d.error(`Entity.spawn(): Entity ${this._name} is already spawned with id ${this._id}!`);if(!this.isSimulated)this.addToSimulation(Z.simulation);if(this._blockTextureUri&&this._blockHalfExtents&&this.numColliders===0)this.addChildColliderToSimulation(new Q9(Q9.optionsFromBlockHalfExtents(this._blockHalfExtents)));if(this._modelUri&&this.numColliders===0&&this._modelPreferredShape!=="none")this.addChildColliderToSimulation(new Q9(Q9.optionsFromModelUri(this._modelUri,this._modelScale,this._modelPreferredShape)));if(this.colliders.forEach((Y)=>{if(this.hasListeners("ENTITY.BLOCK_COLLISION")||this.hasListeners("ENTITY.ENTITY_COLLISION"))Y.enableCollisionEvents(!0);if(this.hasListeners("ENTITY.BLOCK_CONTACT_FORCE")||this.hasListeners("ENTITY.ENTITY_CONTACT_FORCE"))Y.enableContactForceEvents(!0);if(T4.isDefaultCollisionGroups(Y.collisionGroups)){let $=this.isEnvironmental?[8]:[Y.isSensor?4:2],Q=this.isEnvironmental?[65535&~8&~1]:[65535];Y.setCollisionGroups({belongsTo:$,collidesWith:Q})}}),this.setPosition(J),X)this.setRotation(X);if(this._id=Z.entityManager.registerEntity(this),this._world=Z,this._controller)this._controller.spawn(this);if(this._parent)this.setParent(this._parent,this._parentNodeName,J,X);this.colliders.forEach((Y)=>{Z.simulation.colliderMap.setColliderEntity(Y,this)}),this.emitWithWorld(Z,"ENTITY.SPAWN",{entity:this})}despawn(){if(!this._requireSpawned("despawn"))return;if(this._world.entityManager.getEntityChildren(this).forEach((Z)=>{Z.despawn()}),this._controller)this._controller.detach(this),this._controller.despawn(this);if(this.emitWithWorld(this._world,"ENTITY.DESPAWN",{entity:this}),this.isSimulated)this.removeFromSimulation();this._world.entityManager.unregisterEntity(this),this._world.audioManager.unregisterEntityAttachedAudios(this),this._world.lightManager.despawnEntityAttachedLights(this),this._world.particleEmitterManager.despawnEntityAttachedParticleEmitters(this),this._world.sceneUIManager.unloadEntityAttachedSceneUIs(this),this._id=void 0,this._world=void 0}setController(Z){if(this._controller===Z)return;if(this._controller)this._controller.detach(this);if(this._controller=Z,this._controller)this._controller.attach(this)}setModelAnimationsPlaybackRate(Z){if(!this._requireSpawned("setModelAnimationsPlaybackRate"))return;if(!this.isModelEntity||this._modelAnimationsPlaybackRate===Z)return;this._modelAnimationsPlaybackRate=Z,this.emitWithWorld(this._world,"ENTITY.SET_MODEL_ANIMATIONS_PLAYBACK_RATE",{entity:this,playbackRate:Z})}setModelHiddenNodes(Z){if(!this._requireSpawned("setModelHiddenNodes"))return;if(!this.isModelEntity)return;this._modelHiddenNodes=new Set(Z.map((J)=>J.toLowerCase())),this.emitWithWorld(this._world,"ENTITY.SET_MODEL_HIDDEN_NODES",{entity:this,modelHiddenNodes:this._modelHiddenNodes})}setModelScale(Z){if(!this._requireSpawned("setModelScale"))return;if(!this.isModelEntity||this._modelScale===Z)return;let J=Z/this._modelScale;this._modelScale=Z,this.colliders.forEach((X)=>X.scale(J)),this.emitWithWorld(this._world,"ENTITY.SET_MODEL_SCALE",{entity:this,modelScale:Z})}setModelShownNodes(Z){if(!this._requireSpawned("setModelShownNodes"))return;if(!this.isModelEntity)return;this._modelShownNodes=new Set(Z.map((J)=>J.toLowerCase())),this.emitWithWorld(this._world,"ENTITY.SET_MODEL_SHOWN_NODES",{entity:this,modelShownNodes:this._modelShownNodes})}setModelTextureUri(Z){if(!this._requireSpawned("setModelTextureUri"))return;if(!this.isModelEntity||this._modelTextureUri===Z)return;this._modelTextureUri=Z,this.emitWithWorld(this._world,"ENTITY.SET_MODEL_TEXTURE_URI",{entity:this,modelTextureUri:Z})}setOpacity(Z){if(!this._requireSpawned("setOpacity"))return;if(this._opacity===Z)return;this._opacity=Z,this.emitWithWorld(this._world,"ENTITY.SET_OPACITY",{entity:this,opacity:Z})}setParent(Z,J,X,Y){if(!this._requireSpawned("setParent"))return;if(Z&&!Z.isSpawned)return d.error("Entity.setParent(): Parent entity is not spawned, cannot set parent!");if(!this._parent&&Z)this._lastParentlessType=this.type;if(this._parent=Z,this._parentNodeName=J,this.colliders.forEach(($)=>$.setEnabled(!Z)),this.setType(!Z?this._lastParentlessType:"kinematic_velocity"),this.setPosition(X??{x:0,y:0,z:0}),this.setRotation(Y??{x:0,y:0,z:0,w:1}),!this.isKinematicPositionBased)this.resetAngularVelocity(),this.resetForces(),this.resetLinearVelocity(),this.resetTorques();this.emitWithWorld(this._world,"ENTITY.SET_PARENT",{entity:this,parent:Z,parentNodeName:J})}setTintColor(Z){if(!this._requireSpawned("setTintColor"))return;if(!Z&&!this._tintColor||Z&&this._tintColor&&Z.r===this._tintColor.r&&Z.g===this._tintColor.g&&Z.b===this._tintColor.b)return;this._tintColor=Z,this.emitWithWorld(this._world,"ENTITY.SET_TINT_COLOR",{entity:this,tintColor:Z})}startModelLoopedAnimations(Z){if(!this._requireSpawned("startModelLoopedAnimations"))return;if(!this.isModelEntity||!Z.length)return;if(!Z.some((J)=>!this._modelLoopedAnimations.has(J)))return;Z.forEach((J)=>{this._modelLoopedAnimations.add(J)}),this.emitWithWorld(this._world,"ENTITY.START_MODEL_LOOPED_ANIMATIONS",{entity:this,animations:new Set(Z)})}startModelOneshotAnimations(Z){if(!this._requireSpawned("startModelOneshotAnimations"))return;if(!this.isModelEntity||!Z.length)return;Z.forEach((J)=>{this._modelOneshotAnimations.add(J)}),this.emitWithWorld(this._world,"ENTITY.START_MODEL_ONESHOT_ANIMATIONS",{entity:this,animations:new Set(Z)})}stopAllModelAnimations(Z=[]){if(!this._requireSpawned("stopAllModelAnimations"))return;this._stopAnimationsFromSets([this._modelLoopedAnimations,this._modelOneshotAnimations],Z)}stopAllModelLoopedAnimations(Z=[]){if(!this._requireSpawned("stopAllModelLoopedAnimations"))return;this._stopAnimationsFromSets([this._modelLoopedAnimations],Z)}stopAllModelOneshotAnimations(Z=[]){if(!this._requireSpawned("stopAllModelOneshotAnimations"))return;this._stopAnimationsFromSets([this._modelOneshotAnimations],Z)}stopModelAnimations(Z){if(!this._requireSpawned("stopModelAnimations"))return;if(!this.isModelEntity||!Z.length)return;if(!Z.some((J)=>this._modelLoopedAnimations.has(J))&&!Z.some((J)=>this._modelOneshotAnimations.has(J)))return;Z.forEach((J)=>{this._modelLoopedAnimations.delete(J),this._modelOneshotAnimations.delete(J)}),this.emitWithWorld(this._world,"ENTITY.STOP_MODEL_ANIMATIONS",{entity:this,animations:new Set(Z)})}serialize(){if(!this._world)d.fatalError("Entity.serialize(): Entity is not in a world and cannot be serialized!");return P0.serializeEntity(this,this._world.tickAllocator)}tick(Z){if(this.emit("ENTITY.TICK",{entity:this,tickDeltaMs:Z}),this._controller)this._controller.tick(this,Z)}checkAndEmitUpdates(){if(!this._requireSpawned("checkAndEmitUpdates"))return;let Z=this.position,J=this.rotation;if(this._rotationExceedsThreshold(J,this._lastUpdatedRotation)){this._lastUpdatedRotation=J;let X=this._world.tickAllocator.getObject();X.entity=this,X.rotation=J,this.emitWithWorld(this._world,"ENTITY.UPDATE_ROTATION",X)}if(this._positionExceedsThreshold(Z,this._lastUpdatedPosition)){this._lastUpdatedPosition=Z;let X=this._world.tickAllocator.getObject();X.entity=this,X.position=Z,this.emitWithWorld(this._world,"ENTITY.UPDATE_POSITION",X)}}_positionExceedsThreshold(Z,J){let X=Z.x-J.x,Y=Z.y-J.y,$=Z.z-J.z;return X*X+Y*Y+$*$>this._positionUpdateThresholdSq}_requireSpawned(Z){if(!this.isSpawned)d.error(`Entity._requireSpawned(): Entity ${this._name} is not spawned, cannot invoke ${Z}()!`);return this.isSpawned}_rotationExceedsThreshold(Z,J){return Math.abs(Z.x*J.x+Z.y*J.y+Z.z*J.z+Z.w*J.w)<this._rotationUpdateThreshold}_stopAnimationsFromSets(Z,J=[]){if(!this.isModelEntity)return;let X=new Set(J),Y=[];for(let $ of Z)for(let Q of $)if(!X.has(Q))Y.push(Q);if(Y.length>0)this.stopModelAnimations(Y)}}class y1 extends _Y{static BASE_ENTITY_HEIGHT=1.5;static GROUND_SENSOR_HEIGHT_SCALE=0.125;static GROUND_SENSOR_RADIUS_SCALE=0.23;static JUMP_LAND_HEAVY_VELOCITY_THRESHOLD=-12;static WALL_COLLIDER_HEIGHT_SCALE=0.33;static WALL_COLLIDER_RADIUS_SCALE=0.4;static MOVEMENT_ROTATIONS={wa:Math.PI/4,wd:-Math.PI/4,sa:Math.PI-Math.PI/4,sd:Math.PI+Math.PI/4,s:Math.PI,asd:Math.PI,a:Math.PI/2,d:-Math.PI/2};static EXTERNAL_IMPULSE_DECAY_RATE=0.253;static SWIM_UPWARD_COOLDOWN_MS=600;static SWIMMING_DRAG_FACTOR=0.05;static WATER_ENTRY_SINKING_FACTOR=0.8;static WATER_ENTRY_SINKING_MS=250;applyDirectionalMovementRotations=!0;autoCancelMouseLeftClick=!0;canJump=()=>!0;canRun=()=>!0;canSwim=()=>!0;canWalk=()=>!0;faceForwardOnStop=!0;idleLoopedAnimations=["idle-upper","idle-lower"];interactOneshotAnimations=["simple-interact"];jumpLandHeavyOneshotAnimations=["jump-post-heavy"];jumpLandLightOneshotAnimations=["jump-post-light"];jumpOneshotAnimations=["jump-loop"];jumpVelocity=10;runLoopedAnimations=["run-upper","run-lower"];runVelocity=8;sticksToPlatforms=!0;swimFastVelocity=5;swimGravity=0;swimIdleLoopedAnimations=["swim-idle"];swimLoopedAnimations=["swim-forward"];swimMaxGravityVelocity=-1;swimSlowVelocity=3;swimUpwardVelocity=2;walkLoopedAnimations=["walk-upper","walk-lower"];walkVelocity=4;_externalVelocity={x:0,y:0,z:0};_magnitudeYTracker=0;_groundContactCount=0;_internalApplyImpulse=()=>{};_isActivelyMoving=!1;_isFullySubmerged=!1;_justSubmergedUntil=0;_liquidContactCount=0;_platform;_reusableImpulse={x:0,y:0,z:0};_reusablePlatformVelocity={x:0,y:0,z:0};_reusableTargetVelocities={x:0,y:0,z:0};_reusableVelocityClamp={x:0,y:0,z:0};_stepAudio;_swimUpwardCooldownAt=0;constructor(Z={}){super();this.applyDirectionalMovementRotations=Z.applyDirectionalMovementRotations??this.applyDirectionalMovementRotations,this.autoCancelMouseLeftClick=Z.autoCancelMouseLeftClick??this.autoCancelMouseLeftClick,this.faceForwardOnStop=Z.faceForwardOnStop??this.faceForwardOnStop,this.sticksToPlatforms=Z.sticksToPlatforms??this.sticksToPlatforms,this.canJump=Z.canJump??this.canJump,this.canRun=Z.canRun??this.canRun,this.canSwim=Z.canSwim??this.canSwim,this.canWalk=Z.canWalk??this.canWalk,this.jumpVelocity=Z.jumpVelocity??this.jumpVelocity,this.runVelocity=Z.runVelocity??this.runVelocity,this.walkVelocity=Z.walkVelocity??this.walkVelocity,this.swimFastVelocity=Z.swimFastVelocity??this.swimFastVelocity,this.swimSlowVelocity=Z.swimSlowVelocity??this.swimSlowVelocity,this.swimUpwardVelocity=Z.swimUpwardVelocity??this.swimUpwardVelocity,this.swimGravity=Z.swimGravity??this.swimGravity,this.swimMaxGravityVelocity=Z.swimMaxGravityVelocity??this.swimMaxGravityVelocity,this.idleLoopedAnimations=Z.idleLoopedAnimations??this.idleLoopedAnimations,this.interactOneshotAnimations=Z.interactOneshotAnimations??this.interactOneshotAnimations,this.jumpOneshotAnimations=Z.jumpOneshotAnimations??this.jumpOneshotAnimations,this.jumpLandHeavyOneshotAnimations=Z.jumpLandHeavyOneshotAnimations??this.jumpLandHeavyOneshotAnimations,this.jumpLandLightOneshotAnimations=Z.jumpLandLightOneshotAnimations??this.jumpLandLightOneshotAnimations,this.runLoopedAnimations=Z.runLoopedAnimations??this.runLoopedAnimations,this.swimLoopedAnimations=Z.swimLoopedAnimations??this.swimLoopedAnimations,this.swimIdleLoopedAnimations=Z.swimIdleLoopedAnimations??this.swimIdleLoopedAnimations,this.walkLoopedAnimations=Z.walkLoopedAnimations??this.walkLoopedAnimations}get isActivelyMoving(){return this._isActivelyMoving}get isGrounded(){return this._groundContactCount>0}get isOnPlatform(){return!!this._platform}get isSwimming(){return this._liquidContactCount>0}get platform(){return this._platform}attach(Z){super.attach(Z),this._internalApplyImpulse=Z.applyImpulse.bind(Z),Z.applyImpulse=(J)=>{let X=Z.mass||1;this._externalVelocity.x+=J.x/X,this._externalVelocity.y+=J.y/X,this._externalVelocity.z+=J.z/X},this._stepAudio=new P3({uri:"audio/sfx/step/stone/stone-step-04.mp3",loop:!0,volume:0.1,referenceDistance:2,cutoffDistance:15,attachedToEntity:Z}),Z.setCcdEnabled(!0),Z.lockAllRotations(),Z.on("ENTITY.BLOCK_COLLISION",({blockType:J,started:X})=>{if(!J.isLiquid||!this.canSwim(this))return;if(this._liquidContactCount<=0&&X){let Y=Z.linearVelocity;Z.setLinearVelocity({x:Y.x*this.swimGravity,y:Y.y*this.swimGravity,z:Y.z*this.swimGravity})}if(this._liquidContactCount+=X?1:-1,this._liquidContactCount>0)Z.setGravityScale(this.swimGravity),Z.stopAllModelLoopedAnimations(this.swimLoopedAnimations),this._swimUpwardCooldownAt=performance.now()+y1.SWIM_UPWARD_COOLDOWN_MS;else Z.setGravityScale(1),Z.stopModelAnimations(this.swimLoopedAnimations)})}spawn(Z){if(!Z.isSpawned)return d.error("DefaultPlayerEntityController.spawn(): Entity is not spawned!");Z.createAndAddChildCollider({shape:"cylinder",radius:y1.GROUND_SENSOR_RADIUS_SCALE*(Z.height/y1.BASE_ENTITY_HEIGHT),halfHeight:y1.GROUND_SENSOR_HEIGHT_SCALE*(Z.height/y1.BASE_ENTITY_HEIGHT),collisionGroups:{belongsTo:[4],collidesWith:[1,2,8]},isSensor:!0,relativePosition:{x:0,y:-Z.height/2,z:0},tag:"groundSensor",onCollision:(J,X)=>{if(!Z.isSpawned)return;if(!(J instanceof K9)||!J.isLiquid){if(X&&this._groundContactCount===0&&Z.linearVelocity.y<-1)if(Z.linearVelocity.y<y1.JUMP_LAND_HEAVY_VELOCITY_THRESHOLD)Z.startModelOneshotAnimations(this.jumpLandHeavyOneshotAnimations);else Z.startModelOneshotAnimations(this.jumpLandLightOneshotAnimations);this._groundContactCount+=X?1:-1}if(!this._groundContactCount&&!this.isSwimming)Z.startModelOneshotAnimations(this.jumpOneshotAnimations);else Z.stopModelAnimations(this.jumpOneshotAnimations);if(!(J instanceof i8))return;if(X&&this.sticksToPlatforms)this._platform=J;else if(J===this._platform&&!X)this._platform=void 0}}),Z.createAndAddChildCollider({shape:"capsule",halfHeight:y1.WALL_COLLIDER_HEIGHT_SCALE*(Z.height/y1.BASE_ENTITY_HEIGHT),radius:y1.WALL_COLLIDER_RADIUS_SCALE*(Z.height/y1.BASE_ENTITY_HEIGHT),collisionGroups:{belongsTo:[4],collidesWith:[1,2,8]},friction:0,frictionCombineRule:1,tag:"wallCollider"})}tickWithPlayerInput(Z,J,X,Y){if(!Z.isSpawned||!Z.world)return;if(super.tickWithPlayerInput(Z,J,X,Y),Z.parent)return;let{w:$,a:Q,s:K,d:G,c:W,sp:H,sh:V,ml:F}=J,{yaw:z}=X,q=Z.linearVelocity;this._reusableTargetVelocities.x=0,this._reusableTargetVelocities.y=0,this._reusableTargetVelocities.z=0,this._isActivelyMoving=!!($||Q||K||G);let U=V,B=Q&&G&&!$&&!K||$&&K&&!Q&&!G,L=U&&this.canRun(this)||!U&&this.canWalk(this);if(this.isSwimming&&!this._isFullySubmerged)this._isFullySubmerged=!0,this._justSubmergedUntil=performance.now()+y1.WATER_ENTRY_SINKING_MS;else if(!this.isSwimming)this._isFullySubmerged=!1,this._justSubmergedUntil=0;if(this.isGrounded&&!this.isSwimming&&this._isActivelyMoving&&!B&&L){let N=U?this.runLoopedAnimations:this.walkLoopedAnimations;Z.stopAllModelLoopedAnimations(N),Z.startModelLoopedAnimations(N),this._stepAudio?.setPlaybackRate(U?0.75:0.51),this._stepAudio?.play(Z.world,!this._stepAudio?.isPlaying)}else if(this._isFullySubmerged&&this.canSwim(this))if(this._stepAudio?.pause(),this._isActivelyMoving)Z.stopAllModelLoopedAnimations(this.swimLoopedAnimations),Z.startModelLoopedAnimations(this.swimLoopedAnimations);else Z.stopAllModelLoopedAnimations(this.swimIdleLoopedAnimations),Z.startModelLoopedAnimations(this.swimIdleLoopedAnimations);else this._stepAudio?.pause(),Z.stopAllModelLoopedAnimations(this.idleLoopedAnimations),Z.startModelLoopedAnimations(this.idleLoopedAnimations);let w;if(this.applyDirectionalMovementRotations&&L){if($&&Q&&!G&&!K)w=y1.MOVEMENT_ROTATIONS.wa;else if($&&G&&!Q&&!K)w=y1.MOVEMENT_ROTATIONS.wd;else if(K&&Q&&!$&&!G)w=y1.MOVEMENT_ROTATIONS.sa;else if(K&&G&&!$&&!Q)w=y1.MOVEMENT_ROTATIONS.sd;else if(K&&!$&&!Q&&!G||Q&&K&&G&&!$)w=y1.MOVEMENT_ROTATIONS.s;else if(Q&&!$&&!K&&!G)w=y1.MOVEMENT_ROTATIONS.a;else if(G&&!$&&!Q&&!K)w=y1.MOVEMENT_ROTATIONS.d}if(F)Z.startModelOneshotAnimations(this.interactOneshotAnimations),J.ml=!this.autoCancelMouseLeftClick;if(L){let N=!this.isSwimming?U?this.runVelocity:this.walkVelocity:U?this.swimFastVelocity:this.swimSlowVelocity,C=Math.sin(z),T=Math.cos(z);if($)this._reusableTargetVelocities.x-=N*C,this._reusableTargetVelocities.z-=N*T;if(K)this._reusableTargetVelocities.x+=N*C,this._reusableTargetVelocities.z+=N*T;if(Q)this._reusableTargetVelocities.x-=N*T,this._reusableTargetVelocities.z+=N*C;if(G)this._reusableTargetVelocities.x+=N*T,this._reusableTargetVelocities.z-=N*C;let E=Math.sqrt(this._reusableTargetVelocities.x*this._reusableTargetVelocities.x+this._reusableTargetVelocities.z*this._reusableTargetVelocities.z);if(E>N){let x=N/E;this._reusableTargetVelocities.x*=x,this._reusableTargetVelocities.z*=x}}if(this.isSwimming){if(q.y<this.swimMaxGravityVelocity)this._reusableVelocityClamp.x=q.x,this._reusableVelocityClamp.y=this.swimMaxGravityVelocity,this._reusableVelocityClamp.z=q.z,Z.setLinearVelocity(this._reusableVelocityClamp);if(q.y>this.swimUpwardVelocity*2)this._reusableVelocityClamp.x=q.x,this._reusableVelocityClamp.y=this.swimUpwardVelocity*2,this._reusableVelocityClamp.z=q.z,Z.setLinearVelocity(this._reusableVelocityClamp);if(W)this._reusableTargetVelocities.y=-this.swimUpwardVelocity;else if(performance.now()<this._justSubmergedUntil)this._reusableTargetVelocities.y=-this.swimUpwardVelocity*y1.WATER_ENTRY_SINKING_FACTOR;else if(!H)this._reusableTargetVelocities.y=-q.y*y1.SWIMMING_DRAG_FACTOR}if(H&&this.canJump(this)){if(this.isGrounded&&!this.isSwimming&&q.y>-0.001&&q.y<=3)this._reusableTargetVelocities.y=this.jumpVelocity;else if(this.isSwimming&&performance.now()>this._swimUpwardCooldownAt)this._reusableTargetVelocities.y=this.swimUpwardVelocity}let O=this._platform?.linearVelocity??this._reusablePlatformVelocity;if(this._externalVelocity.y!==0)this._magnitudeYTracker+=this._externalVelocity.y;if(this._externalVelocity.x!==0||this._externalVelocity.y!==0||this._externalVelocity.z!==0){if(this.isGrounded){let N=Math.sqrt(this._externalVelocity.x*this._externalVelocity.x+this._magnitudeYTracker*this._magnitudeYTracker+this._externalVelocity.z*this._externalVelocity.z);if(N>0.01){let T=Math.max(0,N-y1.EXTERNAL_IMPULSE_DECAY_RATE)/N;this._externalVelocity.x*=T,this._magnitudeYTracker*=T,this._externalVelocity.z*=T}else this._externalVelocity.x=0,this._externalVelocity.y=0,this._magnitudeYTracker=0,this._externalVelocity.z=0}}let M=this._reusableTargetVelocities.x+this._externalVelocity.x-q.x+O.x,R=this._reusableTargetVelocities.y+this._externalVelocity.y+O.y,D=this._reusableTargetVelocities.z+this._externalVelocity.z-q.z+O.z;if(this._externalVelocity.y=0,M!==0||R!==0||D!==0){let N=Z.mass;this._reusableImpulse.x=M*N,this._reusableImpulse.y=R*N,this._reusableImpulse.z=D*N,this._internalApplyImpulse(this._reusableImpulse)}if(z!==void 0&&(this.faceForwardOnStop||this.isActivelyMoving)){let C=(w!==void 0?z+w:z)*0.5;Z.setRotation({x:0,y:Math.sin(C),z:0,w:Math.cos(C)})}}}var tI;((G)=>{G.LOAD="SCENE_UI.LOAD";G.SET_ATTACHED_TO_ENTITY="SCENE_UI.SET_ATTACHED_TO_ENTITY";G.SET_OFFSET="SCENE_UI.SET_OFFSET";G.SET_POSITION="SCENE_UI.SET_POSITION";G.SET_STATE="SCENE_UI.SET_STATE";G.SET_VIEW_DISTANCE="SCENE_UI.SET_VIEW_DISTANCE";G.UNLOAD="SCENE_UI.UNLOAD"})(tI||={});class tV extends O0{_id;_attachedToEntity;_offset;_position;_state={};_templateId;_viewDistance;_world;constructor(Z){if(!!Z.attachedToEntity===!!Z.position)d.fatalError("Either attachedToEntity or position must be set, but not both");super();this._attachedToEntity=Z.attachedToEntity,this._offset=Z.offset,this._position=Z.position,this._state=Z.state??{},this._templateId=Z.templateId,this._viewDistance=Z.viewDistance}get id(){return this._id}get attachedToEntity(){return this._attachedToEntity}get isLoaded(){return this._id!==void 0}get offset(){return this._offset}get position(){return this._position}get state(){return this._state}get templateId(){return this._templateId}get viewDistance(){return this._viewDistance}get world(){return this._world}load(Z){if(this.isLoaded)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return d.error(`SceneUI.load(): Attached entity ${this._attachedToEntity.id} must be spawned before loading SceneUI!`);this._id=Z.sceneUIManager.registerSceneUI(this),this._world=Z,this.emitWithWorld(Z,"SCENE_UI.LOAD",{sceneUI:this})}setAttachedToEntity(Z){if(!Z.isSpawned)return d.error(`SceneUI.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);if(this._attachedToEntity===Z)return;if(this._attachedToEntity=Z,this._position=void 0,this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_ATTACHED_TO_ENTITY",{sceneUI:this,entity:Z})}setOffset(Z){if(this._offset===Z)return;if(this._offset=Z,this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_OFFSET",{sceneUI:this,offset:Z})}setPosition(Z){if(this._position===Z)return;if(this._attachedToEntity=void 0,this._position=Z,this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_POSITION",{sceneUI:this,position:Z})}setState(Z){if(this._state={...this._state,...Z},this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_STATE",{sceneUI:this,state:this._state})}setViewDistance(Z){if(this._viewDistance=Z,this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_VIEW_DISTANCE",{sceneUI:this,viewDistance:Z})}unload(){if(!this.isLoaded||!this._world)return;this._world.sceneUIManager.unregisterSceneUI(this),this.emitWithWorld(this._world,"SCENE_UI.UNLOAD",{sceneUI:this}),this._id=void 0,this._world=void 0}serialize(){if(!this._world)d.fatalError("SceneUI.serialize(): SceneUI is not in a world and cannot be serialized!");return P0.serializeSceneUI(this,this._world.tickAllocator)}}var H50=0.010000000000000002,V50=Math.cos(0.026);class y7 extends i8{player;nametagSceneUI;constructor(Z){super(Z);this._positionUpdateThresholdSq=H50,this._rotationUpdateThreshold=V50,this.player=Z.player,this.nametagSceneUI=new tV({templateId:"hytopia:nametag",attachedToEntity:this,offset:{x:0,y:1,z:0},viewDistance:15,state:{username:this.player.username,profilePictureUrl:this.player.profilePictureUrl}})}spawn(Z,J,X){super.spawn(Z,J,X),this.nametagSceneUI.load(Z),this.player.on("PLAYER.CHAT_MESSAGE_SEND",({message:Y})=>{this.nametagSceneUI.setState({chat:Y})})}tick(Z){if(!this.isSpawned||!this.world)return;if(!this.controller)return d.error(`PlayerEntity.tick(): PlayerEntity "${this.name}" must have a controller.`);let{input:J,camera:X}=this.player;this.controller.tickWithPlayerInput(this,J,X.orientation,Z),super.tick(Z)}}class eI extends y7{constructor(Z){super({modelUri:"models/players/player.gltf",modelLoopedAnimations:["idle_lower","idle_upper"],modelHiddenNodes:["hair-"],modelShownNodes:["hair-0003"],...Z});if(!Z.controller)this.setController(new y1)}}class eV{_activeEntities=new Set;_entities=new Map;_nextEntityId=1;_world;constructor(Z){this._world=Z}get entityCount(){return this._entities.size}get world(){return this._world}registerEntity(Z){if(Z.id!==void 0)d.fatalError(`EntityManager.registerEntity(): Entity ${Z.name} is already assigned the id ${Z.id}!`);let J=this._nextEntityId;if(this._entities.set(J,Z),this._nextEntityId++,!Z.isEnvironmental)this._activeEntities.add(Z);return J}unregisterEntity(Z){if(Z.id===void 0)return d.error(`EntityManager.unregisterEntity(): Entity ${Z.name} is not assigned an id!`);if(this._entities.delete(Z.id),!Z.isEnvironmental)this._activeEntities.delete(Z)}getAllEntities(Z=!1){return Z?this._world.tickAllocator.getArray(this._entities.values()):Array.from(this._entities.values())}getAllPlayerEntities(){let Z=[];return this._entities.forEach((J)=>{if(J instanceof y7)Z.push(J)}),Z}getPlayerEntitiesByPlayer(Z){let J=[];return this._entities.forEach((X)=>{if(X instanceof y7&&X.player===Z)J.push(X)}),J}getEntity(Z){return this._entities.get(Z)}getEntitiesByTag(Z){let J=[];return this._entities.forEach((X)=>{if(X.tag===Z)J.push(X)}),J}getEntitiesByTagSubstring(Z){let J=[];return this._entities.forEach((X)=>{if(X.tag?.includes(Z))J.push(X)}),J}getEntityChildren(Z){let J=[];return this._entities.forEach((X)=>{if(X.parent===Z)J.push(X)}),J}tickEntities(Z){for(let J of this._activeEntities)J.tick(Z)}checkAndEmitUpdates(){for(let Z of this._activeEntities)Z.checkAndEmitUpdates()}}var A31=r(KH(),1);var if1=r(Q90(),1),nf1=r(Q_(),1),af1=r(G_(),1),U_=r(Jj(),1),L_=r(F90(),1);var Q5=r(B40(),1),lm6=Q5.default.v1,pm6=Q5.default.v1ToV6,im6=Q5.default.v3,w40=Q5.default.v4,nm6=Q5.default.v5,am6=Q5.default.v6,sm6=Q5.default.v6ToV1,om6=Q5.default.v7,rm6=Q5.default.NIL,tm6=Q5.default.MAX,em6=Q5.default.version,Zu6=Q5.default.validate,Ju6=Q5.default.stringify,Xu6=Q5.default.parse;var P_;try{P_=new TextDecoder}catch(Z){}var J0,z9,b=0;var E_=[],A$=E_,Vz=0,v1={},Q1,pZ,V9=0,l9=0,n8,iZ,y5=[],J1,j40={useRecords:!1,mapsAsObjects:!0};class Vj{}var k_=new Vj;k_.name="MessagePack 0xC1";var BX=!1,T40=2,D_,C_,T_;try{new Function("")}catch(Z){T40=1/0}class nZ{constructor(Z){if(Z){if(Z.useRecords===!1&&Z.mapsAsObjects===void 0)Z.mapsAsObjects=!0;if(Z.sequential&&Z.trusted!==!1){if(Z.trusted=!0,!Z.structures&&Z.useRecords!=!1){if(Z.structures=[],!Z.maxSharedStructures)Z.maxSharedStructures=0}}if(Z.structures)Z.structures.sharedLength=Z.structures.length;else if(Z.getStructures)(Z.structures=[]).uninitialized=!0,Z.structures.sharedLength=0;if(Z.int64AsNumber)Z.int64AsType="number"}Object.assign(this,Z)}unpack(Z,J){if(J0)return y40(()=>{return Hj(),this?this.unpack(Z,J):nZ.prototype.unpack.call(j40,Z,J)});if(!Z.buffer&&Z.constructor===ArrayBuffer)Z=typeof Buffer!=="undefined"?Buffer.from(Z):new Uint8Array(Z);if(typeof J==="object")z9=J.end||Z.length,b=J.start||0;else b=0,z9=J>-1?J:Z.length;Vz=0,l9=0,pZ=null,A$=E_,n8=null,J0=Z;try{J1=Z.dataView||(Z.dataView=new DataView(Z.buffer,Z.byteOffset,Z.byteLength))}catch(X){if(J0=null,Z instanceof Uint8Array)throw X;throw new Error("Source must be a Uint8Array or Buffer but was a "+(Z&&typeof Z=="object"?Z.constructor.name:typeof Z))}if(this instanceof nZ){if(v1=this,this.structures)return Q1=this.structures,Gj(J);else if(!Q1||Q1.length>0)Q1=[]}else if(v1=j40,!Q1||Q1.length>0)Q1=[];return Gj(J)}unpackMultiple(Z,J){let X,Y=0;try{BX=!0;let $=Z.length,Q=this?this.unpack(Z,$):zj.unpack(Z,$);if(J){if(J(Q,Y,b)===!1)return;while(b<$)if(Y=b,J(Gj(),Y,b)===!1)return}else{X=[Q];while(b<$)Y=b,X.push(Gj());return X}}catch($){throw $.lastPosition=Y,$.values=X,$}finally{BX=!1,Hj()}}_mergeStructures(Z,J){if(C_)Z=C_.call(this,Z);if(Z=Z||[],Object.isFrozen(Z))Z=Z.map((X)=>X.slice(0));for(let X=0,Y=Z.length;X<Y;X++){let $=Z[X];if($){if($.isShared=!0,X>=32)$.highByte=X-32>>5}}Z.sharedLength=Z.length;for(let X in J||[])if(X>=0){let Y=Z[X],$=J[X];if($){if(Y)(Z.restoreStructures||(Z.restoreStructures=[]))[X]=Y;Z[X]=$}}return this.structures=Z}decode(Z,J){return this.unpack(Z,J)}}function Gj(Z){try{if(!v1.trusted&&!BX){let X=Q1.sharedLength||0;if(X<Q1.length)Q1.length=X}let J;if(v1.randomAccessStructure&&J0[b]<64&&J0[b]>=32&&D_){if(J=D_(J0,b,z9,v1),J0=null,!(Z&&Z.lazy)&&J)J=J.toJSON();b=z9}else J=I8();if(n8)b=n8.postBundlePosition,n8=null;if(BX)Q1.restoreStructures=null;if(b==z9){if(Q1&&Q1.restoreStructures)O40();if(Q1=null,J0=null,iZ)iZ=null}else if(b>z9)throw new Error("Unexpected end of MessagePack data");else if(!BX){let X;try{X=JSON.stringify(J,(Y,$)=>typeof $==="bigint"?`${$}n`:$).slice(0,100)}catch(Y){X="(JSON view not available "+Y+")"}throw new Error("Data read, but end of buffer not reached "+X)}return J}catch(J){if(Q1&&Q1.restoreStructures)O40();if(Hj(),J instanceof RangeError||J.message.startsWith("Unexpected end of buffer")||b>z9)J.incomplete=!0;throw J}}function O40(){for(let Z in Q1.restoreStructures)Q1[Z]=Q1.restoreStructures[Z];Q1.restoreStructures=null}function I8(){let Z=J0[b++];if(Z<160)if(Z<128)if(Z<64)return Z;else{let J=Q1[Z&63]||v1.getStructures&&E40()[Z&63];if(J){if(!J.read)J.read=I_(J,Z&63);return J.read()}else return Z}else if(Z<144)if(Z-=128,v1.mapsAsObjects){let J={};for(let X=0;X<Z;X++){let Y=h40();if(Y==="__proto__")Y="__proto_";J[Y]=I8()}return J}else{let J=new Map;for(let X=0;X<Z;X++)J.set(I8(),I8());return J}else{Z-=144;let J=new Array(Z);for(let X=0;X<Z;X++)J[X]=I8();if(v1.freezeData)return Object.freeze(J);return J}else if(Z<192){let J=Z-160;if(l9>=b)return pZ.slice(b-V9,(b+=J)-V9);if(l9==0&&z9<140){let X=J<16?__(J):x40(J);if(X!=null)return X}return Wj(J)}else{let J;switch(Z){case 192:return null;case 193:if(n8)if(J=I8(),J>0)return n8[1].slice(n8.position1,n8.position1+=J);else return n8[0].slice(n8.position0,n8.position0-=J);return k_;case 194:return!1;case 195:return!0;case 196:if(J=J0[b++],J===void 0)throw new Error("Unexpected end of buffer");return N_(J);case 197:return J=J1.getUint16(b),b+=2,N_(J);case 198:return J=J1.getUint32(b),b+=4,N_(J);case 199:return v$(J0[b++]);case 200:return J=J1.getUint16(b),b+=2,v$(J);case 201:return J=J1.getUint32(b),b+=4,v$(J);case 202:if(J=J1.getFloat32(b),v1.useFloat32>2){let X=h$[(J0[b]&127)<<1|J0[b+1]>>7];return b+=4,(X*J+(J>0?0.5:-0.5)>>0)/X}return b+=4,J;case 203:return J=J1.getFloat64(b),b+=8,J;case 204:return J0[b++];case 205:return J=J1.getUint16(b),b+=2,J;case 206:return J=J1.getUint32(b),b+=4,J;case 207:if(v1.int64AsType==="number")J=J1.getUint32(b)*4294967296,J+=J1.getUint32(b+4);else if(v1.int64AsType==="string")J=J1.getBigUint64(b).toString();else if(v1.int64AsType==="auto"){if(J=J1.getBigUint64(b),J<=BigInt(2)<<BigInt(52))J=Number(J)}else J=J1.getBigUint64(b);return b+=8,J;case 208:return J1.getInt8(b++);case 209:return J=J1.getInt16(b),b+=2,J;case 210:return J=J1.getInt32(b),b+=4,J;case 211:if(v1.int64AsType==="number")J=J1.getInt32(b)*4294967296,J+=J1.getUint32(b+4);else if(v1.int64AsType==="string")J=J1.getBigInt64(b).toString();else if(v1.int64AsType==="auto"){if(J=J1.getBigInt64(b),J>=BigInt(-2)<<BigInt(52)&&J<=BigInt(2)<<BigInt(52))J=Number(J)}else J=J1.getBigInt64(b);return b+=8,J;case 212:if(J=J0[b++],J==114)return C40(J0[b++]&63);else{let X=y5[J];if(X)if(X.read)return b++,X.read(I8());else if(X.noBuffer)return b++,X();else return X(J0.subarray(b,++b));else throw new Error("Unknown extension "+J)}case 213:if(J=J0[b],J==114)return b++,C40(J0[b++]&63,J0[b++]);else return v$(2);case 214:return v$(4);case 215:return v$(8);case 216:return v$(16);case 217:if(J=J0[b++],l9>=b)return pZ.slice(b-V9,(b+=J)-V9);return k40(J);case 218:if(J=J1.getUint16(b),b+=2,l9>=b)return pZ.slice(b-V9,(b+=J)-V9);return I40(J);case 219:if(J=J1.getUint32(b),b+=4,l9>=b)return pZ.slice(b-V9,(b+=J)-V9);return _40(J);case 220:return J=J1.getUint16(b),b+=2,R40(J);case 221:return J=J1.getUint32(b),b+=4,R40(J);case 222:return J=J1.getUint16(b),b+=2,N40(J);case 223:return J=J1.getUint32(b),b+=4,N40(J);default:if(Z>=224)return Z-256;if(Z===void 0){let X=new Error("Unexpected end of MessagePack data");throw X.incomplete=!0,X}throw new Error("Unknown MessagePack token "+Z)}}}var Pb1=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function I_(Z,J){function X(){if(X.count++>T40){let $=Z.read=new Function("r","return function(){return "+(v1.freezeData?"Object.freeze":"")+"({"+Z.map((Q)=>Q==="__proto__"?"__proto_:r()":Pb1.test(Q)?Q+":r()":"["+JSON.stringify(Q)+"]:r()").join(",")+"})}")(I8);if(Z.highByte===0)Z.read=M40(J,Z.read);return $()}let Y={};for(let $=0,Q=Z.length;$<Q;$++){let K=Z[$];if(K==="__proto__")K="__proto_";Y[K]=I8()}if(v1.freezeData)return Object.freeze(Y);return Y}if(X.count=0,Z.highByte===0)return M40(J,X);return X}var M40=(Z,J)=>{return function(){let X=J0[b++];if(X===0)return J();let Y=Z<32?-(Z+(X<<5)):Z+(X<<5),$=Q1[Y]||E40()[Y];if(!$)throw new Error("Record id is not defined for "+Y);if(!$.read)$.read=I_($,Z);return $.read()}};function E40(){let Z=y40(()=>{return J0=null,v1.getStructures()});return Q1=v1._mergeStructures(Z,Q1)}var Wj=x$,k40=x$,I40=x$,_40=x$,S40=!1;function v40(Z){S40=!0,Wj=J(1),k40=J(2),I40=J(3),_40=J(5);function J(X){return function Y($){let Q=A$[Vz++];if(Q==null){if(n8)return x$($);let G=J0.byteOffset,W=Z(b-X+G,z9+G,J0.buffer);if(typeof W=="string")Q=W,A$=E_;else if(A$=W,Vz=1,l9=1,Q=A$[0],Q===void 0)throw new Error("Unexpected end of buffer")}let K=Q.length;if(K<=$)return b+=$,Q;return pZ=Q,V9=b,l9=b+K,b+=$,Q.slice(0,$)}}}function x$(Z){let J;if(Z<16){if(J=__(Z))return J}if(Z>64&&P_)return P_.decode(J0.subarray(b,b+=Z));let X=b+Z,Y=[];J="";while(b<X){let $=J0[b++];if(($&128)===0)Y.push($);else if(($&224)===192){let Q=J0[b++]&63;Y.push(($&31)<<6|Q)}else if(($&240)===224){let Q=J0[b++]&63,K=J0[b++]&63;Y.push(($&31)<<12|Q<<6|K)}else if(($&248)===240){let Q=J0[b++]&63,K=J0[b++]&63,G=J0[b++]&63,W=($&7)<<18|Q<<12|K<<6|G;if(W>65535)W-=65536,Y.push(W>>>10&1023|55296),W=56320|W&1023;Y.push(W)}else Y.push($);if(Y.length>=4096)J+=Y6.apply(String,Y),Y.length=0}if(Y.length>0)J+=Y6.apply(String,Y);return J}function A40(Z,J,X){let Y=J0;J0=Z,b=J;try{return x$(X)}finally{J0=Y}}function R40(Z){let J=new Array(Z);for(let X=0;X<Z;X++)J[X]=I8();if(v1.freezeData)return Object.freeze(J);return J}function N40(Z){if(v1.mapsAsObjects){let J={};for(let X=0;X<Z;X++){let Y=h40();if(Y==="__proto__")Y="__proto_";J[Y]=I8()}return J}else{let J=new Map;for(let X=0;X<Z;X++)J.set(I8(),I8());return J}}var Y6=String.fromCharCode;function x40(Z){let J=b,X=new Array(Z);for(let Y=0;Y<Z;Y++){let $=J0[b++];if(($&128)>0){b=J;return}X[Y]=$}return Y6.apply(String,X)}function __(Z){if(Z<4)if(Z<2)if(Z===0)return"";else{let J=J0[b++];if((J&128)>1){b-=1;return}return Y6(J)}else{let J=J0[b++],X=J0[b++];if((J&128)>0||(X&128)>0){b-=2;return}if(Z<3)return Y6(J,X);let Y=J0[b++];if((Y&128)>0){b-=3;return}return Y6(J,X,Y)}else{let J=J0[b++],X=J0[b++],Y=J0[b++],$=J0[b++];if((J&128)>0||(X&128)>0||(Y&128)>0||($&128)>0){b-=4;return}if(Z<6)if(Z===4)return Y6(J,X,Y,$);else{let Q=J0[b++];if((Q&128)>0){b-=5;return}return Y6(J,X,Y,$,Q)}else if(Z<8){let Q=J0[b++],K=J0[b++];if((Q&128)>0||(K&128)>0){b-=6;return}if(Z<7)return Y6(J,X,Y,$,Q,K);let G=J0[b++];if((G&128)>0){b-=7;return}return Y6(J,X,Y,$,Q,K,G)}else{let Q=J0[b++],K=J0[b++],G=J0[b++],W=J0[b++];if((Q&128)>0||(K&128)>0||(G&128)>0||(W&128)>0){b-=8;return}if(Z<10)if(Z===8)return Y6(J,X,Y,$,Q,K,G,W);else{let H=J0[b++];if((H&128)>0){b-=9;return}return Y6(J,X,Y,$,Q,K,G,W,H)}else if(Z<12){let H=J0[b++],V=J0[b++];if((H&128)>0||(V&128)>0){b-=10;return}if(Z<11)return Y6(J,X,Y,$,Q,K,G,W,H,V);let F=J0[b++];if((F&128)>0){b-=11;return}return Y6(J,X,Y,$,Q,K,G,W,H,V,F)}else{let H=J0[b++],V=J0[b++],F=J0[b++],z=J0[b++];if((H&128)>0||(V&128)>0||(F&128)>0||(z&128)>0){b-=12;return}if(Z<14)if(Z===12)return Y6(J,X,Y,$,Q,K,G,W,H,V,F,z);else{let q=J0[b++];if((q&128)>0){b-=13;return}return Y6(J,X,Y,$,Q,K,G,W,H,V,F,z,q)}else{let q=J0[b++],U=J0[b++];if((q&128)>0||(U&128)>0){b-=14;return}if(Z<15)return Y6(J,X,Y,$,Q,K,G,W,H,V,F,z,q,U);let B=J0[b++];if((B&128)>0){b-=15;return}return Y6(J,X,Y,$,Q,K,G,W,H,V,F,z,q,U,B)}}}}}function P40(){let Z=J0[b++],J;if(Z<192)J=Z-160;else switch(Z){case 217:J=J0[b++];break;case 218:J=J1.getUint16(b),b+=2;break;case 219:J=J1.getUint32(b),b+=4;break;default:throw new Error("Expected string")}return x$(J)}function N_(Z){return v1.copyBuffers?Uint8Array.prototype.slice.call(J0,b,b+=Z):J0.subarray(b,b+=Z)}function v$(Z){let J=J0[b++];if(y5[J]){let X;return y5[J](J0.subarray(b,X=b+=Z),(Y)=>{b=Y;try{return I8()}finally{b=X}})}else throw new Error("Unknown extension type "+J)}var D40=new Array(4096);function h40(){let Z=J0[b++];if(Z>=160&&Z<192){if(Z=Z-160,l9>=b)return pZ.slice(b-V9,(b+=Z)-V9);else if(!(l9==0&&z9<180))return Wj(Z)}else return b--,f40(I8());let J=(Z<<5^(Z>1?J1.getUint16(b):Z>0?J0[b]:0))&4095,X=D40[J],Y=b,$=b+Z-3,Q,K=0;if(X&&X.bytes==Z){while(Y<$){if(Q=J1.getUint32(Y),Q!=X[K++]){Y=1879048192;break}Y+=4}$+=3;while(Y<$)if(Q=J0[Y++],Q!=X[K++]){Y=1879048192;break}if(Y===$)return b=Y,X.string;$-=3,Y=b}X=[],D40[J]=X,X.bytes=Z;while(Y<$)Q=J1.getUint32(Y),X.push(Q),Y+=4;$+=3;while(Y<$)Q=J0[Y++],X.push(Q);let G=Z<16?__(Z):x40(Z);if(G!=null)return X.string=G;return X.string=Wj(Z)}function f40(Z){if(typeof Z==="string")return Z;if(typeof Z==="number"||typeof Z==="boolean"||typeof Z==="bigint")return Z.toString();if(Z==null)return Z+"";if(v1.allowArraysInMapKeys&&Array.isArray(Z)&&Z.flat().every((J)=>["string","number","boolean","bigint"].includes(typeof J)))return Z.flat().toString();throw new Error(`Invalid property type for record: ${typeof Z}`)}var C40=(Z,J)=>{let X=I8().map(f40),Y=Z;if(J!==void 0)Z=Z<32?-((J<<5)+Z):(J<<5)+Z,X.highByte=J;let $=Q1[Z];if($&&($.isShared||BX))(Q1.restoreStructures||(Q1.restoreStructures=[]))[Z]=$;return Q1[Z]=X,X.read=I_(X,Y),X.read()};y5[0]=()=>{};y5[0].noBuffer=!0;y5[66]=(Z)=>{let J=Z.length,X=BigInt(Z[0]&128?Z[0]-256:Z[0]);for(let Y=1;Y<J;Y++)X<<=BigInt(8),X+=BigInt(Z[Y]);return X};var Db1={Error,TypeError,ReferenceError};y5[101]=()=>{let Z=I8();return(Db1[Z[0]]||Error)(Z[1],{cause:Z[2]})};y5[105]=(Z)=>{if(v1.structuredClone===!1)throw new Error("Structured clone extension is disabled");let J=J1.getUint32(b-4);if(!iZ)iZ=new Map;let X=J0[b],Y;if(X>=144&&X<160||X==220||X==221)Y=[];else if(X>=128&&X<144||X==222||X==223)Y=new Map;else if((X>=199&&X<=201||X>=212&&X<=216)&&J0[b+1]===115)Y=new Set;else Y={};let $={target:Y};iZ.set(J,$);let Q=I8();if(!$.used)return $.target=Q;else Object.assign(Y,Q);if(Y instanceof Map)for(let[K,G]of Q.entries())Y.set(K,G);if(Y instanceof Set)for(let K of Array.from(Q))Y.add(K);return Y};y5[112]=(Z)=>{if(v1.structuredClone===!1)throw new Error("Structured clone extension is disabled");let J=J1.getUint32(b-4),X=iZ.get(J);return X.used=!0,X.target};y5[115]=()=>new Set(I8());var S_=["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64","BigInt64","BigUint64"].map((Z)=>Z+"Array"),Cb1=typeof globalThis==="object"?globalThis:window;y5[116]=(Z)=>{let J=Z[0],X=Uint8Array.prototype.slice.call(Z,1).buffer,Y=S_[J];if(!Y){if(J===16)return X;if(J===17)return new DataView(X);throw new Error("Could not find typed array for code "+J)}return new Cb1[Y](X)};y5[120]=()=>{let Z=I8();return new RegExp(Z[0],Z[1])};var Tb1=[];y5[98]=(Z)=>{let J=(Z[0]<<24)+(Z[1]<<16)+(Z[2]<<8)+Z[3],X=b;return b+=J-Z.length,n8=Tb1,n8=[P40(),P40()],n8.position0=0,n8.position1=0,n8.postBundlePosition=b,b=X,I8()};y5[255]=(Z)=>{if(Z.length==4)return new Date((Z[0]*16777216+(Z[1]<<16)+(Z[2]<<8)+Z[3])*1000);else if(Z.length==8)return new Date(((Z[0]<<22)+(Z[1]<<14)+(Z[2]<<6)+(Z[3]>>2))/1e6+((Z[3]&3)*4294967296+Z[4]*16777216+(Z[5]<<16)+(Z[6]<<8)+Z[7])*1000);else if(Z.length==12)return new Date(((Z[0]<<24)+(Z[1]<<16)+(Z[2]<<8)+Z[3])/1e6+((Z[4]&128?-281474976710656:0)+Z[6]*1099511627776+Z[7]*4294967296+Z[8]*16777216+(Z[9]<<16)+(Z[10]<<8)+Z[11])*1000);else return new Date("invalid")};function y40(Z){if(T_)T_();let J=z9,X=b,Y=Vz,$=V9,Q=l9,K=pZ,G=A$,W=iZ,H=n8,V=new Uint8Array(J0.slice(0,z9)),F=Q1,z=Q1.slice(0,Q1.length),q=v1,U=BX,B=Z();return z9=J,b=X,Vz=Y,V9=$,l9=Q,pZ=K,A$=G,iZ=W,n8=H,J0=V,BX=U,Q1=F,Q1.splice(0,Q1.length,...z),v1=q,J1=new DataView(J0.buffer,J0.byteOffset,J0.byteLength),B}function Hj(){J0=null,iZ=null,Q1=null}var h$=new Array(147);for(let Z=0;Z<256;Z++)h$[Z]=+("1e"+Math.floor(45.15-Z*0.30103));var zj=new nZ({useRecords:!1}),Eb1=zj.unpack,kb1=zj.unpackMultiple,Ib1=zj.unpack;var _b1=new Float32Array(1),$u6=new Uint8Array(_b1.buffer,0,4);function b40(Z,J,X){D_=Z,C_=J,T_=X}var qj;try{qj=new TextEncoder}catch(Z){}var x_,d40,Fz=typeof Buffer!=="undefined",Fj=Fz?function(Z){return Buffer.allocUnsafeSlow(Z)}:Uint8Array,c40=Fz?Buffer:Uint8Array,g40=Fz?4294967296:2144337920,l,zz,b1,u=0,K5,X8=null,l40,Sb1=21760,vb1=/[\u0080-\uFFFF]/,g7=Symbol("record-id");class f$ extends nZ{constructor(Z){super(Z);this.offset=0;let J,X,Y,$,Q,K=c40.prototype.utf8Write?function(I,_){return l.utf8Write(I,_,l.byteLength-_)}:qj&&qj.encodeInto?function(I,_){return qj.encodeInto(I,l.subarray(_)).written}:!1,G=this;if(!Z)Z={};let W=Z&&Z.sequential,H=Z.structures||Z.saveStructures,V=Z.maxSharedStructures;if(V==null)V=H?32:0;if(V>8160)throw new Error("Maximum maxSharedStructure is 8160");if(Z.structuredClone&&Z.moreTypes==null)this.moreTypes=!0;let F=Z.maxOwnStructures;if(F==null)F=H?32:64;if(!this.structures&&Z.useRecords!=!1)this.structures=[];let z=V>32||F+V>64,q=V+64,U=V+F+64;if(U>8256)throw new Error("Maximum maxSharedStructure + maxOwnStructure is 8192");let B=[],L=0,w=0;this.pack=this.encode=function(I,_){if(!l)l=new Fj(8192),b1=l.dataView||(l.dataView=new DataView(l.buffer,0,8192)),u=0;if(K5=l.length-10,K5-u<2048)l=new Fj(l.length),b1=l.dataView||(l.dataView=new DataView(l.buffer,0,l.length)),K5=l.length-10,u=0;else u=u+7&2147483640;if(X=u,_&gb1)u+=_&255;if(Q=G.structuredClone?new Map:null,G.bundleStrings&&typeof I!=="string")X8=[],X8.size=1/0;else X8=null;if($=G.structures,$){if($.uninitialized)$=G._mergeStructures(G.getStructures());let p=$.sharedLength||0;if(p>V)throw new Error("Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to "+$.sharedLength);if(!$.transitions){$.transitions=Object.create(null);for(let n=0;n<p;n++){let o=$[n];if(!o)continue;let Q0,G0=$.transitions;for(let S0=0,v0=o.length;S0<v0;S0++){let r0=o[S0];if(Q0=G0[r0],!Q0)Q0=G0[r0]=Object.create(null);G0=Q0}G0[g7]=n+64}this.lastNamedStructuresLength=p}if(!W)$.nextId=p+64}if(Y)Y=!1;let A;try{if(G.randomAccessStructure&&I&&I.constructor&&I.constructor===Object)h(I);else R(I);let p=X8;if(X8)m40(X,R,0);if(Q&&Q.idsToInsert){let n=Q.idsToInsert.sort((S0,v0)=>S0.offset>v0.offset?1:-1),o=n.length,Q0=-1;while(p&&o>0){let S0=n[--o].offset+X;if(S0<p.stringsPosition+X&&Q0===-1)Q0=0;if(S0>p.position+X){if(Q0>=0)Q0+=6}else{if(Q0>=0)b1.setUint32(p.position+X,b1.getUint32(p.position+X)+Q0),Q0=-1;p=p.previous,o++}}if(Q0>=0&&p)b1.setUint32(p.position+X,b1.getUint32(p.position+X)+Q0);if(u+=n.length*6,u>K5)E(u);G.offset=u;let G0=xb1(l.subarray(X,u),n);return Q=null,G0}if(G.offset=u,_&yb1)return l.start=X,l.end=u,l;return l.subarray(X,u)}catch(p){throw A=p,p}finally{if($){if(O(),Y&&G.saveStructures){let p=$.sharedLength||0,n=l.subarray(X,u),o=p40($,G);if(!A){if(G.saveStructures(o,o.isCompatible)===!1)return G.pack(I,_);if(G.lastNamedStructuresLength=p,l.length>1073741824)l=null;return n}}}if(l.length>1073741824)l=null;if(_&bb1)u=X}};let O=()=>{if(w<10)w++;let I=$.sharedLength||0;if($.length>I&&!W)$.length=I;if(L>1e4){if($.transitions=null,w=0,L=0,B.length>0)B=[]}else if(B.length>0&&!W){for(let _=0,A=B.length;_<A;_++)B[_][g7]=0;B=[]}},M=(I)=>{var _=I.length;if(_<16)l[u++]=144|_;else if(_<65536)l[u++]=220,l[u++]=_>>8,l[u++]=_&255;else l[u++]=221,b1.setUint32(u,_),u+=4;for(let A=0;A<_;A++)R(I[A])},R=(I)=>{if(u>K5)l=E(u);var _=typeof I,A;if(_==="string"){let p=I.length;if(X8&&p>=4&&p<4096){if((X8.size+=p)>Sb1){let G0,S0=(X8[0]?X8[0].length*3+X8[1].length:0)+10;if(u+S0>K5)l=E(u+S0);let v0;if(X8.position)v0=X8,l[u]=200,u+=3,l[u++]=98,G0=u-X,u+=4,m40(X,R,0),b1.setUint16(G0+X-3,u-X-G0);else l[u++]=214,l[u++]=98,G0=u-X,u+=4;X8=["",""],X8.previous=v0,X8.size=0,X8.position=G0}let Q0=vb1.test(I);X8[Q0?0:1]+=I,l[u++]=193,R(Q0?-p:p);return}let n;if(p<32)n=1;else if(p<256)n=2;else if(p<65536)n=3;else n=5;let o=p*3;if(u+o>K5)l=E(u+o);if(p<64||!K){let Q0,G0,S0,v0=u+n;for(Q0=0;Q0<p;Q0++)if(G0=I.charCodeAt(Q0),G0<128)l[v0++]=G0;else if(G0<2048)l[v0++]=G0>>6|192,l[v0++]=G0&63|128;else if((G0&64512)===55296&&((S0=I.charCodeAt(Q0+1))&64512)===56320)G0=65536+((G0&1023)<<10)+(S0&1023),Q0++,l[v0++]=G0>>18|240,l[v0++]=G0>>12&63|128,l[v0++]=G0>>6&63|128,l[v0++]=G0&63|128;else l[v0++]=G0>>12|224,l[v0++]=G0>>6&63|128,l[v0++]=G0&63|128;A=v0-u-n}else A=K(I,u+n);if(A<32)l[u++]=160|A;else if(A<256){if(n<2)l.copyWithin(u+2,u+1,u+1+A);l[u++]=217,l[u++]=A}else if(A<65536){if(n<3)l.copyWithin(u+3,u+2,u+2+A);l[u++]=218,l[u++]=A>>8,l[u++]=A&255}else{if(n<5)l.copyWithin(u+5,u+3,u+3+A);l[u++]=219,b1.setUint32(u,A),u+=4}u+=A}else if(_==="number")if(I>>>0===I)if(I<32||I<128&&this.useRecords===!1||I<64&&!this.randomAccessStructure)l[u++]=I;else if(I<256)l[u++]=204,l[u++]=I;else if(I<65536)l[u++]=205,l[u++]=I>>8,l[u++]=I&255;else l[u++]=206,b1.setUint32(u,I),u+=4;else if(I>>0===I)if(I>=-32)l[u++]=256+I;else if(I>=-128)l[u++]=208,l[u++]=I+256;else if(I>=-32768)l[u++]=209,b1.setInt16(u,I),u+=2;else l[u++]=210,b1.setInt32(u,I),u+=4;else{let p;if((p=this.useFloat32)>0&&I<4294967296&&I>=-2147483648){l[u++]=202,b1.setFloat32(u,I);let n;if(p<4||(n=I*h$[(l[u]&127)<<1|l[u+1]>>7])>>0===n){u+=4;return}else u--}l[u++]=203,b1.setFloat64(u,I),u+=8}else if(_==="object"||_==="function")if(!I)l[u++]=192;else{if(Q){let n=Q.get(I);if(n){if(!n.id){let o=Q.idsToInsert||(Q.idsToInsert=[]);n.id=o.push(n)}l[u++]=214,l[u++]=112,b1.setUint32(u,n.id),u+=4;return}else Q.set(I,{offset:u-X})}let p=I.constructor;if(p===Object)T(I);else if(p===Array)M(I);else if(p===Map)if(this.mapAsEmptyObject)l[u++]=128;else{if(A=I.size,A<16)l[u++]=128|A;else if(A<65536)l[u++]=222,l[u++]=A>>8,l[u++]=A&255;else l[u++]=223,b1.setUint32(u,A),u+=4;for(let[n,o]of I)R(n),R(o)}else{for(let n=0,o=x_.length;n<o;n++){let Q0=d40[n];if(I instanceof Q0){let G0=x_[n];if(G0.write){if(G0.type)l[u++]=212,l[u++]=G0.type,l[u++]=0;let t1=G0.write.call(this,I);if(t1===I)if(Array.isArray(I))M(I);else T(I);else R(t1);return}let S0=l,v0=b1,r0=u;l=null;let A8;try{A8=G0.pack.call(this,I,(t1)=>{if(l=S0,S0=null,u+=t1,u>K5)E(u);return{target:l,targetView:b1,position:u-t1}},R)}finally{if(S0)l=S0,b1=v0,u=r0,K5=l.length-10}if(A8){if(A8.length+u>K5)E(A8.length+u);u=Ab1(A8,l,u,G0.type)}return}}if(Array.isArray(I))M(I);else{if(I.toJSON){let n=I.toJSON();if(n!==I)return R(n)}if(_==="function")return R(this.writeFunction&&this.writeFunction(I));T(I)}}}else if(_==="boolean")l[u++]=I?195:194;else if(_==="bigint"){if(I<9223372036854776000&&I>=-9223372036854776000)l[u++]=211,b1.setBigInt64(u,I);else if(I<18446744073709552000&&I>0)l[u++]=207,b1.setBigUint64(u,I);else if(this.largeBigIntToFloat)l[u++]=203,b1.setFloat64(u,Number(I));else if(this.largeBigIntToString)return R(I.toString());else if((this.useBigIntExtension||this.moreTypes)&&I<BigInt(2)**BigInt(1023)&&I>-(BigInt(2)**BigInt(1023))){l[u++]=199,u++,l[u++]=66;let p=[],n;do{let o=I&BigInt(255);n=(o&BigInt(128))===(I<BigInt(0)?BigInt(128):BigInt(0)),p.push(o),I>>=BigInt(8)}while(!((I===BigInt(0)||I===BigInt(-1))&&n));l[u-2]=p.length;for(let o=p.length;o>0;)l[u++]=Number(p[--o]);return}else throw new RangeError(I+" 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");u+=8}else if(_==="undefined")if(this.encodeUndefinedAsNil)l[u++]=192;else l[u++]=212,l[u++]=0,l[u++]=0;else throw new Error("Unknown type: "+_)},D=this.variableMapSize||this.coercibleKeyAsNumber||this.skipValues?(I)=>{let _;if(this.skipValues){_=[];for(let n in I)if((typeof I.hasOwnProperty!=="function"||I.hasOwnProperty(n))&&!this.skipValues.includes(I[n]))_.push(n)}else _=Object.keys(I);let A=_.length;if(A<16)l[u++]=128|A;else if(A<65536)l[u++]=222,l[u++]=A>>8,l[u++]=A&255;else l[u++]=223,b1.setUint32(u,A),u+=4;let p;if(this.coercibleKeyAsNumber)for(let n=0;n<A;n++){p=_[n];let o=Number(p);R(isNaN(o)?p:o),R(I[p])}else for(let n=0;n<A;n++)R(p=_[n]),R(I[p])}:(I)=>{l[u++]=222;let _=u-X;u+=2;let A=0;for(let p in I)if(typeof I.hasOwnProperty!=="function"||I.hasOwnProperty(p))R(p),R(I[p]),A++;if(A>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[_+++X]=A>>8,l[_+X]=A&255},N=this.useRecords===!1?D:Z.progressiveRecords&&!z?(I)=>{let _,A=$.transitions||($.transitions=Object.create(null)),p=u++-X,n;for(let o in I)if(typeof I.hasOwnProperty!=="function"||I.hasOwnProperty(o)){if(_=A[o],_)A=_;else{let Q0=Object.keys(I),G0=A;A=$.transitions;let S0=0;for(let v0=0,r0=Q0.length;v0<r0;v0++){let A8=Q0[v0];if(_=A[A8],!_)_=A[A8]=Object.create(null),S0++;A=_}if(p+X+1==u)u--,x(A,Q0,S0);else S(A,Q0,p,S0);n=!0,A=G0[o]}R(I[o])}if(!n){let o=A[g7];if(o)l[p+X]=o;else S(A,Object.keys(I),p,0)}}:(I)=>{let _,A=$.transitions||($.transitions=Object.create(null)),p=0;for(let o in I)if(typeof I.hasOwnProperty!=="function"||I.hasOwnProperty(o)){if(_=A[o],!_)_=A[o]=Object.create(null),p++;A=_}let n=A[g7];if(n)if(n>=96&&z)l[u++]=((n-=96)&31)+96,l[u++]=n>>5;else l[u++]=n;else x(A,A.__keys__||Object.keys(I),p);for(let o in I)if(typeof I.hasOwnProperty!=="function"||I.hasOwnProperty(o))R(I[o])},C=typeof this.useRecords=="function"&&this.useRecords,T=C?(I)=>{C(I)?N(I):D(I)}:N,E=(I)=>{let _;if(I>16777216){if(I-X>g40)throw new Error("Packed buffer would be larger than maximum buffer size");_=Math.min(g40,Math.round(Math.max((I-X)*(I>67108864?1.25:2),4194304)/4096)*4096)}else _=(Math.max(I-X<<2,l.length-1)>>12)+1<<12;let A=new Fj(_);if(b1=A.dataView||(A.dataView=new DataView(A.buffer,0,_)),I=Math.min(I,l.length),l.copy)l.copy(A,0,X,I);else A.set(l.slice(X,I));return u-=X,X=0,K5=A.length-10,l=A},x=(I,_,A)=>{let p=$.nextId;if(!p)p=64;if(p<q&&this.shouldShareStructure&&!this.shouldShareStructure(_)){if(p=$.nextOwnId,!(p<U))p=q;$.nextOwnId=p+1}else{if(p>=U)p=q;$.nextId=p+1}let n=_.highByte=p>=96&&z?p-96>>5:-1;if(I[g7]=p,I.__keys__=_,$[p-64]=_,p<q)if(_.isShared=!0,$.sharedLength=p-63,Y=!0,n>=0)l[u++]=(p&31)+96,l[u++]=n;else l[u++]=p;else{if(n>=0)l[u++]=213,l[u++]=114,l[u++]=(p&31)+96,l[u++]=n;else l[u++]=212,l[u++]=114,l[u++]=p;if(A)L+=w*A;if(B.length>=F)B.shift()[g7]=0;B.push(I),R(_)}},S=(I,_,A,p)=>{let n=l,o=u,Q0=K5,G0=X;if(l=zz,u=0,X=0,!l)zz=l=new Fj(8192);K5=l.length-10,x(I,_,p),zz=l;let S0=u;if(l=n,u=o,K5=Q0,X=G0,S0>1){let v0=u+S0-1;if(v0>K5)E(v0);let r0=A+X;l.copyWithin(r0+S0,r0+1,u),l.set(zz.slice(0,S0),r0),u=v0}else l[A+X]=zz[0]},h=(I)=>{let _=l40(I,l,X,u,$,E,(A,p,n)=>{if(n)return Y=!0;u=p;let o=l;if(R(A),O(),o!==l)return{position:u,targetView:b1,target:l};return u},this);if(_===0)return T(I);u=_}}useBuffer(Z){l=Z,l.dataView||(l.dataView=new DataView(l.buffer,l.byteOffset,l.byteLength)),u=0}set position(Z){u=Z}get position(){return u}clearSharedData(){if(this.structures)this.structures=[];if(this.typedStructs)this.typedStructs=[]}}d40=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,DataView,Vj];x_=[{pack(Z,J,X){let Y=Z.getTime()/1000;if((this.useTimestamp32||Z.getMilliseconds()===0)&&Y>=0&&Y<4294967296){let{target:$,targetView:Q,position:K}=J(6);$[K++]=214,$[K++]=255,Q.setUint32(K,Y)}else if(Y>0&&Y<4294967296){let{target:$,targetView:Q,position:K}=J(10);$[K++]=215,$[K++]=255,Q.setUint32(K,Z.getMilliseconds()*4000000+(Y/1000/4294967296>>0)),Q.setUint32(K+4,Y)}else if(isNaN(Y)){if(this.onInvalidDate)return J(0),X(this.onInvalidDate());let{target:$,targetView:Q,position:K}=J(3);$[K++]=212,$[K++]=255,$[K++]=255}else{let{target:$,targetView:Q,position:K}=J(15);$[K++]=199,$[K++]=12,$[K++]=255,Q.setUint32(K,Z.getMilliseconds()*1e6),Q.setBigInt64(K+4,BigInt(Math.floor(Y)))}}},{pack(Z,J,X){if(this.setAsEmptyObject)return J(0),X({});let Y=Array.from(Z),{target:$,position:Q}=J(this.moreTypes?3:0);if(this.moreTypes)$[Q++]=212,$[Q++]=115,$[Q++]=0;X(Y)}},{pack(Z,J,X){let{target:Y,position:$}=J(this.moreTypes?3:0);if(this.moreTypes)Y[$++]=212,Y[$++]=101,Y[$++]=0;X([Z.name,Z.message,Z.cause])}},{pack(Z,J,X){let{target:Y,position:$}=J(this.moreTypes?3:0);if(this.moreTypes)Y[$++]=212,Y[$++]=120,Y[$++]=0;X([Z.source,Z.flags])}},{pack(Z,J){if(this.moreTypes)v_(Z,16,J);else A_(Fz?Buffer.from(Z):new Uint8Array(Z),J)}},{pack(Z,J){let X=Z.constructor;if(X!==c40&&this.moreTypes)v_(Z,S_.indexOf(X.name),J);else A_(Z,J)}},{pack(Z,J){if(this.moreTypes)v_(Z,17,J);else A_(Fz?Buffer.from(Z):new Uint8Array(Z),J)}},{pack(Z,J){let{target:X,position:Y}=J(1);X[Y]=193}}];function v_(Z,J,X,Y){let $=Z.byteLength;if($+1<256){var{target:Q,position:K}=X(4+$);Q[K++]=199,Q[K++]=$+1}else if($+1<65536){var{target:Q,position:K}=X(5+$);Q[K++]=200,Q[K++]=$+1>>8,Q[K++]=$+1&255}else{var{target:Q,position:K,targetView:G}=X(7+$);Q[K++]=201,G.setUint32(K,$+1),K+=4}if(Q[K++]=116,Q[K++]=J,!Z.buffer)Z=new Uint8Array(Z);Q.set(new Uint8Array(Z.buffer,Z.byteOffset,Z.byteLength),K)}function A_(Z,J){let X=Z.byteLength;var Y,$;if(X<256){var{target:Y,position:$}=J(X+2);Y[$++]=196,Y[$++]=X}else if(X<65536){var{target:Y,position:$}=J(X+3);Y[$++]=197,Y[$++]=X>>8,Y[$++]=X&255}else{var{target:Y,position:$,targetView:Q}=J(X+5);Y[$++]=198,Q.setUint32($,X),$+=4}Y.set(Z,$)}function Ab1(Z,J,X,Y){let $=Z.length;switch($){case 1:J[X++]=212;break;case 2:J[X++]=213;break;case 4:J[X++]=214;break;case 8:J[X++]=215;break;case 16:J[X++]=216;break;default:if($<256)J[X++]=199,J[X++]=$;else if($<65536)J[X++]=200,J[X++]=$>>8,J[X++]=$&255;else J[X++]=201,J[X++]=$>>24,J[X++]=$>>16&255,J[X++]=$>>8&255,J[X++]=$&255}return J[X++]=Y,J.set(Z,X),X+=$,X}function xb1(Z,J){let X,Y=J.length*6,$=Z.length-Y;while(X=J.pop()){let{offset:Q,id:K}=X;Z.copyWithin(Q+Y,Q,$),Y-=6;let G=Q+Y;Z[G++]=214,Z[G++]=105,Z[G++]=K>>24,Z[G++]=K>>16&255,Z[G++]=K>>8&255,Z[G++]=K&255,$=Q}return Z}function m40(Z,J,X){if(X8.length>0){b1.setUint32(X8.position+Z,u+X-X8.position-Z),X8.stringsPosition=u-Z;let Y=X8;X8=null,J(Y[0]),J(Y[1])}}function p40(Z,J){return Z.isCompatible=(X)=>{let Y=!X||(J.lastNamedStructuresLength||0)===X.length;if(!Y)J._mergeStructures(X);return Y},Z}function i40(Z,J){l40=Z,p40=J}var n40=new f$({useRecords:!1}),hb1=n40.pack,fb1=n40.pack;var yb1=512,bb1=1024,gb1=2048;var h_=3,xG=0,qz=2,Uj=1,y_=16,s40=["num","object","string","ascii"];s40[y_]="date";var ub1=[!1,!0,!0,!1,!1,!0,!0,!1],o40;try{new Function(""),o40=!0}catch(Z){}var y$,db1=typeof Buffer!=="undefined",Lj,m7;try{Lj=new TextEncoder}catch(Z){}var cb1=db1?function(Z,J,X){return Z.utf8Write(J,X,Z.byteLength-X)}:Lj&&Lj.encodeInto?function(Z,J,X){return Lj.encodeInto(J,Z.subarray(X)).written}:!1,qu6=Symbol("type"),Uu6=Symbol("parent");i40(r40,ab1);function r40(Z,J,X,Y,$,Q,K,G){let W=G.typedStructs||(G.typedStructs=[]),H=J.dataView,V=(W.lastStringStart||100)+Y,F=J.length-10,z=Y;if(Y>F)J=Q(Y),H=J.dataView,Y-=X,z-=X,V-=X,X=0,F=J.length-10;let q,U=V,B=W.transitions||(W.transitions=Object.create(null)),L=W.nextId||W.length,w=L<15?1:L<240?2:L<61440?3:L<15728640?4:0;if(w===0)return 0;Y+=w;let O=[],M,R=0;for(let N in Z){let C=Z[N],T=B[N];if(!T)B[N]=T={key:N,parent:B,enumerationOffset:0,ascii0:null,ascii8:null,num8:null,string16:null,object16:null,num32:null,float64:null,date64:null};if(Y>F)J=Q(Y),H=J.dataView,Y-=X,z-=X,V-=X,U-=X,X=0,F=J.length-10;switch(typeof C){case"number":let E=C;if(L<200||!T.num64){if(E>>0===E&&E<536870912&&E>-520093696){if(E<246&&E>=0&&(T.num8&&!(L>200&&T.num32)||E<32&&!T.num32))B=T.num8||b5(T,xG,1),J[Y++]=E;else B=T.num32||b5(T,xG,4),H.setUint32(Y,E,!0),Y+=4;break}else if(E<4294967296&&E>=-2147483648){if(H.setFloat32(Y,E,!0),ub1[J[Y+3]>>>5]){let I;if((I=E*h$[(J[Y+3]&127)<<1|J[Y+2]>>7])>>0===I){B=T.num32||b5(T,xG,4),Y+=4;break}}}}B=T.num64||b5(T,xG,8),H.setFloat64(Y,E,!0),Y+=8;break;case"string":let x=C.length;if(q=U-V,(x<<2)+U>F)J=Q((x<<2)+U),H=J.dataView,Y-=X,z-=X,V-=X,U-=X,X=0,F=J.length-10;if(x>65280+q>>2){O.push(N,C,Y-z);break}let S,h=U;if(x<64){let I,_,A;for(I=0;I<x;I++)if(_=C.charCodeAt(I),_<128)J[U++]=_;else if(_<2048)S=!0,J[U++]=_>>6|192,J[U++]=_&63|128;else if((_&64512)===55296&&((A=C.charCodeAt(I+1))&64512)===56320)S=!0,_=65536+((_&1023)<<10)+(A&1023),I++,J[U++]=_>>18|240,J[U++]=_>>12&63|128,J[U++]=_>>6&63|128,J[U++]=_&63|128;else S=!0,J[U++]=_>>12|224,J[U++]=_>>6&63|128,J[U++]=_&63|128}else U+=cb1(J,C,U),S=U-h>x;if(q<160||q<246&&(T.ascii8||T.string8)){if(S){if(!(B=T.string8))if(W.length>10&&(B=T.ascii8))B.__type=qz,T.ascii8=null,T.string8=B,K(null,0,!0);else B=b5(T,qz,1)}else if(q===0&&!M){M=!0,B=T.ascii0||b5(T,h_,0);break}else if(!(B=T.ascii8)&&!(W.length>10&&(B=T.string8)))B=b5(T,h_,1);J[Y++]=q}else B=T.string16||b5(T,qz,2),H.setUint16(Y,q,!0),Y+=2;break;case"object":if(C){if(C.constructor===Date)B=T.date64||b5(T,y_,8),H.setFloat64(Y,C.getTime(),!0),Y+=8;else O.push(N,C,R);break}else if(T=a40(T,Y,H,-10),T)B=T,Y=y$;else O.push(N,C,R);break;case"boolean":B=T.num8||T.ascii8||b5(T,xG,1),J[Y++]=C?249:248;break;case"undefined":if(T=a40(T,Y,H,-9),T)B=T,Y=y$;else O.push(N,C,R);break;default:O.push(N,C,R)}R++}for(let N=0,C=O.length;N<C;){let T=O[N++],E=O[N++],x=O[N++],S=B[T];if(!S)B[T]=S={key:T,parent:B,enumerationOffset:x-R,ascii0:null,ascii8:null,num8:null,string16:null,object16:null,num32:null,float64:null};let h;if(E){let I;if(q=U-V,q<65280)if(B=S.object16,B)I=2;else if(B=S.object32)I=4;else B=b5(S,Uj,2),I=2;else B=S.object32||b5(S,Uj,4),I=4;if(h=K(E,U),typeof h==="object")U=h.position,H=h.targetView,J=h.target,V-=X,Y-=X,z-=X,X=0;else U=h;if(I===2)H.setUint16(Y,q,!0),Y+=2;else H.setUint32(Y,q,!0),Y+=4}else B=S.object16||b5(S,Uj,2),H.setInt16(Y,E===null?-10:-9,!0),Y+=2;R++}let D=B[g7];if(D==null){D=G.typedStructs.length;let N=[],C=B,T,E;while((E=C.__type)!==void 0){let x=C.__size;C=C.__parent,T=C.key;let S=[E,x,T];if(C.enumerationOffset)S.push(C.enumerationOffset);N.push(S),C=C.parent}N.reverse(),B[g7]=D,G.typedStructs[D]=N,K(null,0,!0)}switch(w){case 1:if(D>=16)return 0;J[z]=D+32;break;case 2:if(D>=256)return 0;J[z]=56,J[z+1]=D;break;case 3:if(D>=65536)return 0;J[z]=57,H.setUint16(z+1,D,!0);break;case 4:if(D>=16777216)return 0;H.setUint32(z,(D<<8)+58,!0);break}if(Y<V){if(V===U)return Y;J.copyWithin(Y,V,U),U+=Y-V,W.lastStringStart=Y-z}else if(Y>V){if(V===U)return Y;return W.lastStringStart=Y-z,r40(Z,J,X,z,$,Q,K,G)}return U}function a40(Z,J,X,Y){let $;if($=Z.ascii8||Z.num8)return X.setInt8(J,Y,!0),y$=J+1,$;if($=Z.string16||Z.object16)return X.setInt16(J,Y,!0),y$=J+2,$;if($=Z.num32)return X.setUint32(J,3758096640+Y,!0),y$=J+4,$;if($=Z.num64)return X.setFloat64(J,NaN,!0),X.setInt8(J,Y),y$=J+8,$;y$=J;return}function b5(Z,J,X){let Y=s40[J]+(X<<3),$=Z[Y]||(Z[Y]=Object.create(null));return $.__type=J,$.__size=X,$.__parent=Z,$}function lb1(Z){if(!(Z instanceof Map))return Z;let J=Z.get("typed")||[];if(Object.isFrozen(J))J=J.map(($)=>$.slice(0));let X=Z.get("named"),Y=Object.create(null);for(let $=0,Q=J.length;$<Q;$++){let K=J[$],G=Y;for(let[W,H,V]of K){let F=G[V];if(!F)G[V]=F={key:V,parent:G,enumerationOffset:0,ascii0:null,ascii8:null,num8:null,string16:null,object16:null,num32:null,float64:null,date64:null};G=b5(F,W,H)}G[g7]=$}return J.transitions=Y,this.typedStructs=J,this.lastTypedStructuresLength=J.length,X}var f_=Symbol.for("source");function pb1(Z,J,X,Y){let $=Z[J++]-32;if($>=24)switch($){case 24:$=Z[J++];break;case 25:$=Z[J++]+(Z[J++]<<8);break;case 26:$=Z[J++]+(Z[J++]<<8)+(Z[J++]<<16);break;case 27:$=Z[J++]+(Z[J++]<<8)+(Z[J++]<<16)+(Z[J++]<<24);break}let Q=Y.typedStructs&&Y.typedStructs[$];if(!Q){if(Z=Uint8Array.prototype.slice.call(Z,J,X),X-=J,J=0,!Y.getStructures)throw new Error(`Reference to shared structure ${$} without getStructures method`);if(Y._mergeStructures(Y.getStructures()),!Y.typedStructs)throw new Error("Could not find any shared typed structures");if(Y.lastTypedStructuresLength=Y.typedStructs.length,Q=Y.typedStructs[$],!Q)throw new Error("Could not find typed structure "+$)}var{construct:K,fullConstruct:G}=Q;if(!K){K=Q.construct=function q(){},G=Q.fullConstruct=function q(){},G.prototype=Y.structPrototype??{};var W=K.prototype=Y.structPrototype?Object.create(Y.structPrototype):{};let V=[],F=0,z;for(let q=0,U=Q.length;q<U;q++){let B=Q[q],[L,w,O,M]=B;if(O==="__proto__")O="__proto_";let R={key:O,offset:F};if(M)V.splice(q+M,0,R);else V.push(R);let D;switch(w){case 0:D=()=>0;break;case 1:D=(C,T)=>{let E=C.bytes[T+R.offset];return E>=246?AG(E):E};break;case 2:D=(C,T)=>{let E=C.bytes,S=(E.dataView||(E.dataView=new DataView(E.buffer,E.byteOffset,E.byteLength))).getUint16(T+R.offset,!0);return S>=65280?AG(S&255):S};break;case 4:D=(C,T)=>{let E=C.bytes,S=(E.dataView||(E.dataView=new DataView(E.buffer,E.byteOffset,E.byteLength))).getUint32(T+R.offset,!0);return S>=4294967040?AG(S&255):S};break}R.getRef=D,F+=w;let N;switch(L){case h_:if(z&&!z.next)z.next=R;z=R,R.multiGetCount=0,N=function(C){let{bytes:T,position:E}=C,x=F+E,S=D(C,E);if(typeof S!=="number")return S;let h,I=R.next;while(I){if(h=I.getRef(C,E),typeof h==="number")break;else h=null;I=I.next}if(h==null)h=C.bytesEnd-x;if(C.srcString)return C.srcString.slice(S,h);return A40(T,S+x,h-S)};break;case qz:case Uj:if(z&&!z.next)z.next=R;z=R,N=function(C){let T=C.position,E=F+T,x=D(C,T);if(typeof x!=="number")return x;let S=C.bytes,h,I=R.next;while(I){if(h=I.getRef(C,T),typeof h==="number")break;else h=null;I=I.next}if(h==null)h=C.bytesEnd-E;if(L===qz)return S.toString("utf8",x+E,h+E);else{m7=C;try{return Y.unpack(S,{start:x+E,end:h+E})}finally{m7=null}}};break;case xG:switch(w){case 4:N=function(C){let T=C.bytes,E=T.dataView||(T.dataView=new DataView(T.buffer,T.byteOffset,T.byteLength)),x=C.position+R.offset,S=E.getInt32(x,!0);if(S<536870912){if(S>-520093696)return S;if(S>-536870912)return AG(S&255)}let h=E.getFloat32(x,!0),I=h$[(T[x+3]&127)<<1|T[x+2]>>7];return(I*h+(h>0?0.5:-0.5)>>0)/I};break;case 8:N=function(C){let T=C.bytes,x=(T.dataView||(T.dataView=new DataView(T.buffer,T.byteOffset,T.byteLength))).getFloat64(C.position+R.offset,!0);if(isNaN(x)){let S=T[C.position+R.offset];if(S>=246)return AG(S)}return x};break;case 1:N=function(C){let E=C.bytes[C.position+R.offset];return E<246?E:AG(E)};break}break;case y_:N=function(C){let T=C.bytes,E=T.dataView||(T.dataView=new DataView(T.buffer,T.byteOffset,T.byteLength));return new Date(E.getFloat64(C.position+R.offset,!0))};break}R.get=N}if(o40){let q=[],U=[],B=0,L;for(let O of V){if(Y.alwaysLazyProperty&&Y.alwaysLazyProperty(O.key)){L=!0;continue}Object.defineProperty(W,O.key,{get:ib1(O.get),enumerable:!0});let M="v"+B++;U.push(M),q.push("o["+JSON.stringify(O.key)+"]="+M+"(s)")}if(L)q.push("__proto__:this");let w=new Function(...U,"var c=this;return function(s){var o=new c();"+q.join(";")+";return o;}").apply(G,V.map((O)=>O.get));Object.defineProperty(W,"toJSON",{value(O){return w.call(this,this[f_])}})}else Object.defineProperty(W,"toJSON",{value(q){let U={};for(let B=0,L=V.length;B<L;B++){let w=V[B].key;U[w]=this[w]}return U}})}var H=new K;return H[f_]={bytes:Z,position:J,srcString:"",bytesEnd:X},H}function AG(Z){switch(Z){case 246:return null;case 247:return;case 248:return!1;case 249:return!0}throw new Error("Unknown constant")}function ib1(Z){return function(){return Z(this[f_])}}function nb1(){if(m7)m7.bytes=Uint8Array.prototype.slice.call(m7.bytes,m7.position,m7.bytesEnd),m7.position=0,m7.bytesEnd=m7.bytes.length}function ab1(Z,J){if(J.typedStructs){let Y=new Map;Y.set("named",Z),Y.set("typed",J.typedStructs),Z=Y}let X=J.lastTypedStructuresLength||0;return Z.isCompatible=(Y)=>{let $=!0;if(Y instanceof Map){if((Y.get("named")||[]).length!==(J.lastNamedStructuresLength||0))$=!1;if((Y.get("typed")||[]).length!==X)$=!1}else if(Y instanceof Array||Array.isArray(Y)){if(Y.length!==(J.lastNamedStructuresLength||0))$=!1}if(!$)J._mergeStructures(Y);return $},J.lastTypedStructuresLength=J.typedStructs&&J.typedStructs.length,Z}b40(pb1,lb1,nb1);var rb1=process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED!==void 0&&process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED.toLowerCase()==="true";if(!rb1){let Z;try{if(Z=m("msgpackr-extract"),Z)v40(Z.extractStrings)}catch(J){}}import ao1 from"mediasoup";var NO=r(SK0(),1);import lo1 from"http";import po1 from"https";import RO from"fs";import io1 from"path";import no1 from"url";var vK0=`-----BEGIN CERTIFICATE-----
|
|
415
|
+
`))}}get isGatewayAvailable(){return!!this._creativeGateway}async getData(Z){if(!this._creativeGateway&&process.env.NODE_ENV==="production")return d.warning("PlatformGateway.getData(): You are running in production mode, but the Platform Gateway is not initialized! No data will be returned.");return this._creativeGateway?await this._creativeGateway.kv.get(Z):this._readDevDataLocally(Z)}async getPlayerLoadout(Z){if(!this._creativeGateway)return;return await this._creativeGateway.getLoadout(Z)}async getPlayerSession(Z){if(!this._creativeGateway)return;return await this._creativeGateway.getSession(Z)}async setData(Z,J){if(J.error)return d.warning("PlatformGateway.setData(): Cannot set data with an error property.");if(!this._creativeGateway&&process.env.NODE_ENV==="production")return d.warning("PlatformGateway.setData(): You are running in production mode, but the Platform Gateway is not initialized! No data will be set.");return this._creativeGateway?await this._creativeGateway.kv.set(Z,J):this._writeDevDataLocally(Z,J)}_readDevDataLocally(Z){try{if(!T$.existsSync(lV))return;let J=X50.join(lV,`${Z}.json`);return JSON.parse(T$.readFileSync(J,"utf8"))}catch(J){d.warning(`PlatformGateway._readDevDataLocally(): Failed to read data for key "${Z}": ${J}`)}}_writeDevDataLocally(Z,J){try{if(!T$.existsSync(lV))T$.mkdirSync(lV,{recursive:!0});let X=X50.join(lV,`${Z}.json`),Y={};if(T$.existsSync(X))Y=JSON.parse(T$.readFileSync(X,"utf8"));let $={...Y,...J};T$.writeFileSync(X,JSON.stringify($,null,2),"utf8")}catch(X){d.warning(`PlatformGateway._writeDevDataLocally(): Failed to write data for key "${Z}": ${X}`)}}}class E${static instance=new E$;constructor(){}async getGlobalData(Z){let J=await f7.instance.getData(Z);if(!J||J.error){if(J?.error)d.warning(`PersistenceManager.getGlobalData(): ${J.error.message}`);return}return J}async getPlayerData(Z){let J=await f7.instance.getData(this._getPlayerKey(Z));if(!J||J.error){if(J?.error)d.warning(`PersistenceManager.getPlayerData(): ${J.error.message}`);return}return J}async setGlobalData(Z,J){let X=await f7.instance.setData(Z,J);if(!X||X.error){if(X?.error)d.warning(`PersistenceManager.setGlobalData(): ${X.error.message}`);return}return X}async setPlayerData(Z,J){let X=await f7.instance.setData(this._getPlayerKey(Z),J);if(!X||X.error){if(X?.error)d.warning(`PersistenceManager.setPlayerData(): ${X.error.message}`);return}return X}_getPlayerKey(Z){return`player-${Z.id}`}}var $50;((Y)=>{Y[Y.FIRST_PERSON=0]="FIRST_PERSON";Y[Y.THIRD_PERSON=1]="THIRD_PERSON";Y[Y.SPECTATOR=2]="SPECTATOR"})($50||={});var aI;((B)=>{B.LOOK_AT_ENTITY="PLAYER_CAMERA.LOOK_AT_ENTITY";B.LOOK_AT_POSITION="PLAYER_CAMERA.LOOK_AT_POSITION";B.SET_ATTACHED_TO_ENTITY="PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY";B.SET_ATTACHED_TO_POSITION="PLAYER_CAMERA.SET_ATTACHED_TO_POSITION";B.SET_FILM_OFFSET="PLAYER_CAMERA.SET_FILM_OFFSET";B.SET_FORWARD_OFFSET="PLAYER_CAMERA.SET_FORWARD_OFFSET";B.SET_FOV="PLAYER_CAMERA.SET_FOV";B.SET_MODEL_HIDDEN_NODES="PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES";B.SET_MODEL_SHOWN_NODES="PLAYER_CAMERA.SET_MODEL_SHOWN_NODES";B.SET_MODE="PLAYER_CAMERA.SET_MODE";B.SET_OFFSET="PLAYER_CAMERA.SET_OFFSET";B.SET_SHOULDER_ANGLE="PLAYER_CAMERA.SET_SHOULDER_ANGLE";B.SET_TRACKED_ENTITY="PLAYER_CAMERA.SET_TRACKED_ENTITY";B.SET_TRACKED_POSITION="PLAYER_CAMERA.SET_TRACKED_POSITION";B.SET_ZOOM="PLAYER_CAMERA.SET_ZOOM"})(aI||={});class pV extends O0{player;_attachedToEntity;_attachedToPosition;_filmOffset=0;_forwardOffset=0;_fov=75;_modelHiddenNodes=new Set;_modelShownNodes=new Set;_mode=1;_offset={x:0,y:0,z:0};_orientation={pitch:0,yaw:0};_shoulderAngle=0;_trackedEntity;_trackedPosition;_zoom=1;constructor(Z){super();this.player=Z}get attachedToEntity(){return this._attachedToEntity}get attachedToPosition(){return this._attachedToPosition}get facingDirection(){return{x:-Math.sin(this._orientation.yaw)*Math.cos(this._orientation.pitch),y:Math.sin(this._orientation.pitch),z:-Math.cos(this._orientation.yaw)*Math.cos(this._orientation.pitch)}}get facingQuaternion(){let Z=this._orientation.pitch*0.5,J=this._orientation.yaw*0.5,X=Math.cos(Z),Y=Math.sin(Z),$=Math.cos(J),Q=Math.sin(J);return{x:Y*$,y:X*Q,z:-Y*Q,w:X*$}}get filmOffset(){return this._filmOffset}get forwardOffset(){return this._forwardOffset}get fov(){return this._fov}get modelHiddenNodes(){return this._modelHiddenNodes}get modelShownNodes(){return this._modelShownNodes}get mode(){return this._mode}get offset(){return this._offset}get orientation(){return this._orientation}get shoulderAngle(){return this._shoulderAngle}get trackedEntity(){return this._trackedEntity}get trackedPosition(){return this._trackedPosition}get zoom(){return this._zoom}lookAtEntity(Z){if(!this._requirePlayerWorld("lookAtEntity"))return;this.emitWithWorld(this.player.world,"PLAYER_CAMERA.LOOK_AT_ENTITY",{playerCamera:this,entity:Z})}lookAtPosition(Z){if(!this._requirePlayerWorld("lookAtPosition"))return;this.emitWithWorld(this.player.world,"PLAYER_CAMERA.LOOK_AT_POSITION",{playerCamera:this,position:Z})}reset(){this._attachedToEntity=void 0,this._attachedToPosition=void 0,this._orientation={pitch:0,yaw:0},this._trackedEntity=void 0,this._trackedPosition=void 0}setAttachedToEntity(Z){if(!this._requirePlayerWorld("setAttachedToEntity"))return;if(!Z.isSpawned)return d.error(`PlayerCamera.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);this._attachedToEntity=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY",{playerCamera:this,entity:Z})}setAttachedToPosition(Z){if(!this._requirePlayerWorld("setAttachedToPosition"))return;this._attachedToPosition=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_ATTACHED_TO_POSITION",{playerCamera:this,position:Z})}setFilmOffset(Z){if(!this._requirePlayerWorld("setFilmOffset"))return;this._filmOffset=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_FILM_OFFSET",{playerCamera:this,filmOffset:Z})}setForwardOffset(Z){if(!this._requirePlayerWorld("setForwardOffset"))return;this._forwardOffset=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_FORWARD_OFFSET",{playerCamera:this,forwardOffset:Z})}setFov(Z){if(!this._requirePlayerWorld("setFov"))return;this._fov=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_FOV",{playerCamera:this,fov:Z})}setModelHiddenNodes(Z){if(!this._requirePlayerWorld("setModelHiddenNodes"))return;this._modelHiddenNodes=new Set(Z.map((J)=>J.toLowerCase())),this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES",{playerCamera:this,modelHiddenNodes:this._modelHiddenNodes})}setModelShownNodes(Z){if(!this._requirePlayerWorld("setModelShownNodes"))return;this._modelShownNodes=new Set(Z.map((J)=>J.toLowerCase())),this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_MODEL_SHOWN_NODES",{playerCamera:this,modelShownNodes:this._modelShownNodes})}setMode(Z){if(!this._requirePlayerWorld("setMode"))return;this._mode=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_MODE",{playerCamera:this,mode:Z})}setOffset(Z){if(!this._requirePlayerWorld("setOffset"))return;this._offset=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_OFFSET",{playerCamera:this,offset:Z})}setOrientationPitch(Z){this._orientation.pitch=Z}setOrientationYaw(Z){this._orientation.yaw=Z}setShoulderAngle(Z){if(!this._requirePlayerWorld("setShoulderAngle"))return;this._shoulderAngle=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_SHOULDER_ANGLE",{playerCamera:this,shoulderAngle:Z})}setTrackedEntity(Z){if(!this._requirePlayerWorld("setTrackedEntity"))return;this._trackedEntity=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_TRACKED_ENTITY",{playerCamera:this,entity:Z})}setTrackedPosition(Z){if(!this._requirePlayerWorld("setTrackedPosition"))return;this._trackedPosition=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_TRACKED_POSITION",{playerCamera:this,position:Z})}setZoom(Z){if(!this._requirePlayerWorld("setZoom"))return;this._zoom=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_ZOOM",{playerCamera:this,zoom:Z})}serialize(){if(!this.player.world)d.fatalError("PlayerCamera.serialize(): PlayerCamera player is not in a world and cannot be serialized!");return P0.serializePlayerCamera(this,this.player.world.tickAllocator)}_requirePlayerWorld(Z){if(!this.player.world)d.error(`PlayerCamera._requirePlayerWorld(): Player ${this.player.id} is not in a world, invoked method: ${Z}()`);return!!this.player.world}}var lw;(($)=>{$.DATA="PLAYER_UI.DATA";$.LOAD="PLAYER_UI.LOAD";$.LOCK_POINTER="PLAYER_UI.LOCK_POINTER";$.SEND_DATA="PLAYER_UI.SEND_DATA"})(lw||={});class iV extends O0{player;constructor(Z){super();this.player=Z}load(Z){if(!this.player.world)return;this.emitWithWorld(this.player.world,"PLAYER_UI.LOAD",{playerUI:this,htmlUri:Z})}lockPointer(Z){if(!this.player.world)return;this.emitWithWorld(this.player.world,"PLAYER_UI.LOCK_POINTER",{playerUI:this,lock:Z})}sendData(Z){if(!this.player.world)return;this.emitWithWorld(this.player.world,"PLAYER_UI.SEND_DATA",{playerUI:this,data:Z})}}var Q50=["w","a","s","d","sp","sh","tb","ml","mr","q","e","r","f","z","x","c","v","u","i","o","j","k","l","n","m","1","2","3","4","5","6","7","8","9","0"],nV;((Q)=>{Q.CHAT_MESSAGE_SEND="PLAYER.CHAT_MESSAGE_SEND";Q.JOINED_WORLD="PLAYER.JOINED_WORLD";Q.LEFT_WORLD="PLAYER.LEFT_WORLD";Q.RECONNECTED_WORLD="PLAYER.RECONNECTED_WORLD";Q.REQUEST_SYNC="PLAYER.REQUEST_SYNC"})(nV||={});class CG extends O0{static _devNextPlayerId=1;id;username;profilePictureUrl;camera;connection;ui;_input={};_lastUnreliableInputSequenceNumber=0;_persistedData;_world;_worldSwitched=!1;constructor(Z,J){super();this.id=J?.user.id??`player-${CG._devNextPlayerId++}`,this.username=J?.user.username??this.id,this.profilePictureUrl=J?.user.profilePictureURL??void 0,this.camera=new pV(this),this.connection=Z,this.ui=new iV(this),Z.onPacket(Y0.PacketId.CHAT_MESSAGE_SEND,this._onChatMessageSendPacket),Z.onPacket(Y0.PacketId.DEBUG_CONFIG,this._onDebugConfigPacket),Z.onPacket(Y0.PacketId.INPUT,this._onInputPacket),Z.onPacket(Y0.PacketId.SYNC_REQUEST,this._onSyncRequestPacket),Z.onPacket(Y0.PacketId.UI_DATA_SEND,this._onUIDataSendPacket)}get input(){return this._input}get world(){return this._world}disconnect(){this._leaveWorld(),this.connection.disconnect()}getPersistedData(){return this._persistedData}joinWorld(Z){if(this._world===Z)return;if(!this._world)this._world=Z,this.emitWithWorld(this._world,"PLAYER.JOINED_WORLD",{player:this,world:this._world});else{for(let J of this._world.entityManager.getPlayerEntitiesByPlayer(this))if(J.isSpawned)J.despawn();this.disconnect(),this._world=Z,this._worldSwitched=!0}}async loadInitialPersistedData(){if(this._persistedData)return;this._persistedData=await E$.instance.getPlayerData(this)??void 0}reconnected(){if(!this._world)return;if(this._lastUnreliableInputSequenceNumber=0,!this._worldSwitched)this.emitWithWorld(this._world,"PLAYER.RECONNECTED_WORLD",{player:this,world:this._world});else this._worldSwitched=!1,this.emitWithWorld(this._world,"PLAYER.JOINED_WORLD",{player:this,world:this._world})}resetInputs(){this._input={}}setPersistedData(Z){return this._persistedData={...this._persistedData,...Z},E$.instance.setPlayerData(this,Z).catch((J)=>{}),this._persistedData}serialize(){if(!this._world)d.fatalError("Player.serialize(): Player is not in a world and cannot be serialized!");return P0.serializePlayer(this,this._world.tickAllocator)}_leaveWorld(){if(!this._world)return;this.emitWithWorld(this._world,"PLAYER.LEFT_WORLD",{player:this,world:this._world}),this._world=void 0}_onChatMessageSendPacket=(Z)=>{if(this._world)this.emitWithWorld(this._world,"PLAYER.CHAT_MESSAGE_SEND",{player:this,message:Z[1].m})};_onDebugConfigPacket=(Z)=>{console.log(Z)};_onInputPacket=(Z)=>{let J=Z[1];if(J.sq!==void 0){if(J.sq<this._lastUnreliableInputSequenceNumber)return;this._lastUnreliableInputSequenceNumber=J.sq}if(Q50.forEach((X)=>{let Y=X;if(J[Y]!==void 0)this._input[Y]=Boolean(J[Y])}),J.cp!==void 0)this.camera.setOrientationPitch(J.cp);if(J.cy!==void 0)this.camera.setOrientationYaw(J.cy)};_onSyncRequestPacket=()=>{if(this._world)this.emitWithWorld(this._world,"PLAYER.REQUEST_SYNC",{player:this,receivedAt:Date.now(),receivedAtMs:performance.now()})};_onUIDataSendPacket=(Z)=>{this.ui.emit("PLAYER_UI.DATA",{playerUI:this.ui,data:Z[1]})}}var sI;((X)=>{X.BROADCAST_MESSAGE="CHAT.BROADCAST_MESSAGE";X.PLAYER_MESSAGE="CHAT.PLAYER_MESSAGE"})(sI||={});class aV extends O0{_commandCallbacks={};_world;constructor(Z){super();this._world=Z,this._subscribeToPlayerEvents()}registerCommand(Z,J){this._commandCallbacks[Z]=J}unregisterCommand(Z){delete this._commandCallbacks[Z]}sendBroadcastMessage(Z,J){this._sendBroadcastMessage(void 0,Z,J)}sendPlayerMessage(Z,J,X){this.emitWithWorld(this._world,"CHAT.PLAYER_MESSAGE",{player:Z,message:J,color:X})}_subscribeToPlayerEvents(){this._world.on("PLAYER.CHAT_MESSAGE_SEND",(Z)=>{let{player:J,message:X}=Z,[Y,...$]=X.split(" "),Q=this._commandCallbacks[Y];if(Q){Q(J,$,X);return}this._sendBroadcastMessage(J,X)})}_sendBroadcastMessage(Z,J,X){this.emitWithWorld(this._world,"CHAT.BROADCAST_MESSAGE",{player:Z,message:J,color:X})}}var G9=16,oI=G9-1,kh1=G9**3;class W9{_blocks;_chunkLattice;_originCoordinate;constructor(Z,J){this._blocks=new Uint8Array(kh1),this._chunkLattice=Z,this._originCoordinate=J}get blocks(){return this._blocks}get chunkLattice(){return this._chunkLattice}get originCoordinate(){return this._originCoordinate}static blockIndexToLocalCoordinate(Z){return{x:Z%G9,y:(Z/G9|0)%G9,z:Z/(G9*G9)|0}}static globalCoordinateToLocalCoordinate(Z){return{x:Z.x&G9-1,y:Z.y&G9-1,z:Z.z&G9-1}}static globalCoordinateToOriginCoordinate(Z){return{x:Z.x&~(G9-1),y:Z.y&~(G9-1),z:Z.z&~(G9-1)}}getBlockId(Z){return this._blocks[this._getIndex(Z)]}hasBlock(Z){return this._blocks[this._getIndex(Z)]!==0}setBlock(Z,J){if(!this._isValidLocalCoordinate(Z))return d.error("Chunk.setBlock(): Block local coordinate is out of bounds");let X=this._getIndex(Z);this._blocks[X]=J}serialize(){return P0.serializeChunk(this,this._chunkLattice.world.tickAllocator)}_getIndex(Z){return Z.x+(Z.y<<4)+(Z.z<<8)}_isValidLocalCoordinate(Z){return Z.x>=0&&Z.x<=oI&&Z.y>=0&&Z.y<=oI&&Z.z>=0&&Z.z<=oI}}var rI;((Y)=>{Y.ADD_CHUNK="CHUNK_LATTICE.ADD_CHUNK";Y.REMOVE_CHUNK="CHUNK_LATTICE.REMOVE_CHUNK";Y.SET_BLOCK="CHUNK_LATTICE.SET_BLOCK"})(rI||={});class sV extends O0{_blockTypeColliders=new Map;_blockTypeCounts=new Map;_chunks=new Map;_rigidBody;_world;constructor(Z){super();this._world=Z}get chunkCount(){return this._chunks.size}get world(){return this._world}clear(){for(let Z of this._blockTypeColliders.values())this._world.simulation.colliderMap.removeColliderBlockType(Z),Z.removeFromSimulation();this._chunks.forEach((Z)=>{this.emitWithWorld(this._world,"CHUNK_LATTICE.REMOVE_CHUNK",{chunkLattice:this,chunk:Z})}),this._blockTypeColliders.clear(),this._blockTypeCounts.clear(),this._chunks.clear()}getBlockId(Z){let J=this.getChunk(W9.globalCoordinateToOriginCoordinate(Z));if(!J)return 0;return J.getBlockId(W9.globalCoordinateToLocalCoordinate(Z))}getBlockTypeCollider(Z){return this._blockTypeColliders.get(Z)}getBlockType(Z){let J=this.getBlockId(Z);return J?this._world.blockTypeRegistry.getBlockType(J):null}getBlockTypeCount(Z){return this._blockTypeCounts.get(Z)??0}getChunk(Z){return this._chunks.get(this._getChunkKey(W9.globalCoordinateToOriginCoordinate(Z)))}getOrCreateBlockTypeCollider(Z,J){let X=this._blockTypeColliders.get(Z);if(X)return X;let $=this._world.blockTypeRegistry.getBlockType(Z).createCollider(J);return this._blockTypeColliders.set(Z,$),$}getOrCreateChunk(Z){let J=W9.globalCoordinateToOriginCoordinate(Z),X=this._chunks.get(this._getChunkKey(J));if(X)return X;return X=new W9(this,J),this._chunks.set(this._getChunkKey(J),X),this.emitWithWorld(this._world,"CHUNK_LATTICE.ADD_CHUNK",{chunkLattice:this,chunk:X}),X}getAllChunks(Z=!1){return Z?this._world.tickAllocator.getArray(this._chunks.values()):Array.from(this._chunks.values())}hasBlock(Z){let J=this.getChunk(W9.globalCoordinateToOriginCoordinate(Z));if(!J)return!1;return J.hasBlock(W9.globalCoordinateToLocalCoordinate(Z))}hasChunk(Z){let J=W9.globalCoordinateToOriginCoordinate(Z);return this._chunks.has(this._getChunkKey(J))}setBlock(Z,J){let X=W9.globalCoordinateToLocalCoordinate(Z),Y=this.getOrCreateChunk(Z),$=Y.getBlockId(X);if($===J)return;if(Y.setBlock(X,J),!this._rigidBody)this._rigidBody=new O$({type:"fixed"}),this._rigidBody.addToSimulation(this._world.simulation);if($!==0){let Q=Math.max(0,(this._blockTypeCounts.get($)??0)-1),K=this.getBlockTypeCollider($);if(K)if(Q===0)this._world.simulation.colliderMap.removeColliderBlockType(K),K.removeFromSimulation(),this._blockTypeColliders.delete($);else K.setVoxel(Z,!1),this._propagateVoxelChange(K,Z);this._blockTypeCounts.set($,Q)}if(J!==0){let Q=(this._blockTypeCounts.get(J)??0)+1,K=this.getOrCreateBlockTypeCollider(J,[Z]);if(Q===1){let G=this._world.blockTypeRegistry.getBlockType(J);K.addToSimulation(this._world.simulation,this._rigidBody),this._world.simulation.colliderMap.setColliderBlockType(K,G),this._combineVoxelStates(K)}else K.setVoxel(Z,!0),this._propagateVoxelChange(K,Z);this._blockTypeCounts.set(J,Q)}this.emitWithWorld(this._world,"CHUNK_LATTICE.SET_BLOCK",{chunkLattice:this,chunk:Y,globalCoordinate:Z,localCoordinate:X,blockTypeId:J})}_combineVoxelStates(Z){if(Z.isSensor)return;for(let J of this._blockTypeColliders.values()){if(J===Z||J.isSensor)continue;Z.combineVoxelStates(J)}}_getChunkKey(Z){return`${Z.x},${Z.y},${Z.z}`}_propagateVoxelChange(Z,J){if(Z.isSensor)return;for(let X of this._blockTypeColliders.values()){if(X===Z||X.isSensor)continue;Z.propagateVoxelChange(X,J)}}}class oV{_colliderHandleBlockTypeMap=new Map;_colliderHandleCollisionCallbackMap=new Map;_colliderHandleEntityMap=new Map;_cleanupBlockTypeColliderHandles=new Set;_pendingCleanupBlockTypeColliderHandles=new Set;_cleanupCollisionCallbackColliderHandles=new Set;_pendingCleanupCollisionCallbackColliderHandles=new Set;_cleanupEntityColliderHandles=new Set;_pendingCleanupEntityColliderHandles=new Set;getColliderBlockType(Z){if(!this._requireSimulatedCollider(Z))return;return this._colliderHandleBlockTypeMap.get(Z.rawCollider.handle)}getColliderCollisionCallback(Z){if(!this._requireSimulatedCollider(Z))return;return this._colliderHandleCollisionCallbackMap.get(Z.rawCollider.handle)}getColliderEntity(Z){if(!this._requireSimulatedCollider(Z))return;return this._colliderHandleEntityMap.get(Z.rawCollider.handle)}getColliderHandleBlockType(Z){return this._colliderHandleBlockTypeMap.get(Z)}getColliderHandleCollisionCallback(Z){return this._colliderHandleCollisionCallbackMap.get(Z)}getColliderHandleEntity(Z){return this._colliderHandleEntityMap.get(Z)}removeColliderBlockType(Z){if(!this._requireSimulatedCollider(Z))return;this.removeColliderHandleBlockType(Z.rawCollider.handle)}removeColliderCollisionCallback(Z){if(!this._requireSimulatedCollider(Z))return;this.removeColliderHandleCollisionCallback(Z.rawCollider.handle)}removeColliderEntity(Z){if(!this._requireSimulatedCollider(Z))return;this.removeColliderHandleEntity(Z.rawCollider.handle)}removeColliderHandleBlockType(Z){this._colliderHandleBlockTypeMap.delete(Z)}removeColliderHandleCollisionCallback(Z){this._colliderHandleCollisionCallbackMap.delete(Z)}removeColliderHandleEntity(Z){this._colliderHandleEntityMap.delete(Z)}setColliderBlockType(Z,J){if(!this._requireSimulatedCollider(Z))return;this.setColliderHandleBlockType(Z.rawCollider.handle,J)}setColliderCollisionCallback(Z,J){if(!this._requireSimulatedCollider(Z))return;this.setColliderHandleCollisionCallback(Z.rawCollider.handle,J)}setColliderEntity(Z,J){if(!this._requireSimulatedCollider(Z))return;this.setColliderHandleEntity(Z.rawCollider.handle,J)}setColliderHandleBlockType(Z,J){this._colliderHandleBlockTypeMap.set(Z,J),this._cleanupBlockTypeColliderHandles.delete(Z),this._pendingCleanupBlockTypeColliderHandles.delete(Z)}setColliderHandleCollisionCallback(Z,J){this._colliderHandleCollisionCallbackMap.set(Z,J),this._cleanupCollisionCallbackColliderHandles.delete(Z),this._pendingCleanupCollisionCallbackColliderHandles.delete(Z)}setColliderHandleEntity(Z,J){this._colliderHandleEntityMap.set(Z,J),this._cleanupEntityColliderHandles.delete(Z),this._pendingCleanupEntityColliderHandles.delete(Z)}queueColliderHandleForCleanup(Z){if(this._colliderHandleBlockTypeMap.has(Z))this._pendingCleanupBlockTypeColliderHandles.add(Z);if(this._colliderHandleCollisionCallbackMap.has(Z))this._pendingCleanupCollisionCallbackColliderHandles.add(Z);if(this._colliderHandleEntityMap.has(Z))this._pendingCleanupEntityColliderHandles.add(Z)}cleanup(){for(let Z of this._cleanupBlockTypeColliderHandles)this._colliderHandleBlockTypeMap.delete(Z);if(this._cleanupBlockTypeColliderHandles.size>0)this._cleanupBlockTypeColliderHandles.clear();for(let Z of this._cleanupCollisionCallbackColliderHandles)this._colliderHandleCollisionCallbackMap.delete(Z);if(this._cleanupCollisionCallbackColliderHandles.size>0)this._cleanupCollisionCallbackColliderHandles.clear();for(let Z of this._cleanupEntityColliderHandles)this._colliderHandleEntityMap.delete(Z);if(this._cleanupEntityColliderHandles.size>0)this._cleanupEntityColliderHandles.clear();for(let Z of this._pendingCleanupBlockTypeColliderHandles)this._cleanupBlockTypeColliderHandles.add(Z);if(this._pendingCleanupBlockTypeColliderHandles.size>0)this._pendingCleanupBlockTypeColliderHandles.clear();for(let Z of this._pendingCleanupCollisionCallbackColliderHandles)this._cleanupCollisionCallbackColliderHandles.add(Z);if(this._pendingCleanupCollisionCallbackColliderHandles.size>0)this._pendingCleanupCollisionCallbackColliderHandles.clear();for(let Z of this._pendingCleanupEntityColliderHandles)this._cleanupEntityColliderHandles.add(Z);if(this._pendingCleanupEntityColliderHandles.size>0)this._pendingCleanupEntityColliderHandles.clear()}_requireSimulatedCollider(Z){if(!Z.rawCollider)d.error("ColliderMap._requireSimulatedCollider(): Collider is not in the simulation.");return!!Z.rawCollider}}var K50={type:"dynamic",softCcdPrediction:1},G50=0.015625,W50=Math.cos(0.026),rV;((R)=>{R.BLOCK_COLLISION="ENTITY.BLOCK_COLLISION";R.BLOCK_CONTACT_FORCE="ENTITY.BLOCK_CONTACT_FORCE";R.DESPAWN="ENTITY.DESPAWN";R.ENTITY_COLLISION="ENTITY.ENTITY_COLLISION";R.ENTITY_CONTACT_FORCE="ENTITY.ENTITY_CONTACT_FORCE";R.SET_MODEL_ANIMATIONS_PLAYBACK_RATE="ENTITY.SET_MODEL_ANIMATIONS_PLAYBACK_RATE";R.SET_MODEL_HIDDEN_NODES="ENTITY.SET_MODEL_HIDDEN_NODES";R.SET_MODEL_SCALE="ENTITY.SET_MODEL_SCALE";R.SET_MODEL_SHOWN_NODES="ENTITY.SET_MODEL_SHOWN_NODES";R.SET_MODEL_TEXTURE_URI="ENTITY.SET_MODEL_TEXTURE_URI";R.SET_OPACITY="ENTITY.SET_OPACITY";R.SET_PARENT="ENTITY.SET_PARENT";R.SET_TINT_COLOR="ENTITY.SET_TINT_COLOR";R.SPAWN="ENTITY.SPAWN";R.START_MODEL_LOOPED_ANIMATIONS="ENTITY.START_MODEL_LOOPED_ANIMATIONS";R.START_MODEL_ONESHOT_ANIMATIONS="ENTITY.START_MODEL_ONESHOT_ANIMATIONS";R.STOP_MODEL_ANIMATIONS="ENTITY.STOP_MODEL_ANIMATIONS";R.TICK="ENTITY.TICK";R.UPDATE_POSITION="ENTITY.UPDATE_POSITION";R.UPDATE_ROTATION="ENTITY.UPDATE_ROTATION"})(rV||={});class i8 extends O${_id;_blockHalfExtents;_blockTextureUri;_controller;_isEnvironmental=!1;_modelAnimationsPlaybackRate=1;_modelHiddenNodes=new Set;_modelLoopedAnimations=new Set;_modelOneshotAnimations=new Set;_modelPreferredShape;_modelScale=1;_modelShownNodes=new Set;_modelTextureUri;_modelUri;_name;_opacity;_parent;_parentNodeName;_tag;_tintColor;_lastUpdatedPosition={x:0,y:0,z:0};_lastUpdatedRotation={x:0,y:0,z:0,w:1};_lastParentlessType="dynamic";_world;_positionUpdateThresholdSq;_rotationUpdateThreshold;constructor(Z){let J="blockTextureUri"in Z,X="modelUri"in Z;if(!J===!X)d.fatalError("Entity.constructor(): Entity data must include a blockTextureUri or modelUri, but not both.");if(J&&!Z.blockHalfExtents)d.fatalError("Entity.constructor(): Block entity must have blockHalfExtents!");if(Z.parent&&!Z.parent.isSpawned)d.fatalError("Entity.constructor(): Parent entity must be spawned before child entity!");if(Z.parent?.modelUri&&Z.parentNodeName&&!S5.instance.modelHasNode(Z.parent.modelUri,Z.parentNodeName))d.fatalError(`Entity.constructor(): Parent node name ${Z.parentNodeName} not found in parent model ${Z.parent.modelUri}!`);super(Z.rigidBodyOptions??K50);if(J)this._blockHalfExtents=Z.blockHalfExtents,this._blockTextureUri=Z.blockTextureUri;if(X)this._modelAnimationsPlaybackRate=Z.modelAnimationsPlaybackRate??1,this._modelPreferredShape=Z.modelPreferredShape,this._modelScale=Z.modelScale??1,this._modelTextureUri=Z.modelTextureUri,this._modelUri=Z.modelUri,Z.modelHiddenNodes?.forEach((Y)=>this._modelHiddenNodes.add(Y.toLowerCase())),Z.modelLoopedAnimations?.forEach((Y)=>this._modelLoopedAnimations.add(Y)),Z.modelShownNodes?.forEach((Y)=>this._modelShownNodes.add(Y.toLowerCase()));if(this._isEnvironmental=Z.isEnvironmental??!1,this._name=Z.name??"Nameless",this._opacity=Z.opacity??1,this._parent=Z.parent,this._parentNodeName=Z.parentNodeName,this._tag=Z.tag,this._tintColor=Z.tintColor,this._positionUpdateThresholdSq=G50,this._rotationUpdateThreshold=W50,Z.controller)this.setController(Z.controller)}get id(){return this._id}get blockHalfExtents(){return this._blockHalfExtents}get blockTextureUri(){return this._blockTextureUri}get controller(){return this._controller}get depth(){return this.isModelEntity?S5.instance.getDepth(this._modelUri)*(this._modelScale??1):this._blockHalfExtents.z*2}get height(){return this.isModelEntity?S5.instance.getHeight(this._modelUri)*(this._modelScale??1):this._blockHalfExtents.y*2}get modelAnimationsPlaybackRate(){return this._modelAnimationsPlaybackRate}get modelHiddenNodes(){return this._modelHiddenNodes}get modelLoopedAnimations(){return this._modelLoopedAnimations}get modelPreferredShape(){return this._modelPreferredShape}get modelScale(){return this._modelScale}get modelShownNodes(){return this._modelShownNodes}get modelTextureUri(){return this._modelTextureUri}get modelUri(){return this._modelUri}get name(){return this._name}get opacity(){return this._opacity}get parent(){return this._parent}get parentNodeName(){return this._parentNodeName}get tag(){return this._tag}get tintColor(){return this._tintColor}get isBlockEntity(){return!!this._blockTextureUri}get isEnvironmental(){return this._isEnvironmental}get isModelEntity(){return!!this._modelUri}get isSpawned(){return!!this._world}get width(){return this.isModelEntity?S5.instance.getWidth(this._modelUri)*(this._modelScale??1):this._blockHalfExtents.x*2}get world(){return this._world}spawn(Z,J,X){if(this.isSpawned)return d.error(`Entity.spawn(): Entity ${this._name} is already spawned with id ${this._id}!`);if(!this.isSimulated)this.addToSimulation(Z.simulation);if(this._blockTextureUri&&this._blockHalfExtents&&this.numColliders===0)this.addChildColliderToSimulation(new Q9(Q9.optionsFromBlockHalfExtents(this._blockHalfExtents)));if(this._modelUri&&this.numColliders===0&&this._modelPreferredShape!=="none")this.addChildColliderToSimulation(new Q9(Q9.optionsFromModelUri(this._modelUri,this._modelScale,this._modelPreferredShape)));if(this.colliders.forEach((Y)=>{if(this.hasListeners("ENTITY.BLOCK_COLLISION")||this.hasListeners("ENTITY.ENTITY_COLLISION"))Y.enableCollisionEvents(!0);if(this.hasListeners("ENTITY.BLOCK_CONTACT_FORCE")||this.hasListeners("ENTITY.ENTITY_CONTACT_FORCE"))Y.enableContactForceEvents(!0);if(T4.isDefaultCollisionGroups(Y.collisionGroups)){let $=this.isEnvironmental?[8]:[Y.isSensor?4:2],Q=this.isEnvironmental?[65535&~8&~1]:[65535];Y.setCollisionGroups({belongsTo:$,collidesWith:Q})}}),this.setPosition(J),X)this.setRotation(X);if(this._id=Z.entityManager.registerEntity(this),this._world=Z,this._controller)this._controller.spawn(this);if(this._parent)this.setParent(this._parent,this._parentNodeName,J,X);this.colliders.forEach((Y)=>{Z.simulation.colliderMap.setColliderEntity(Y,this)}),this.emitWithWorld(Z,"ENTITY.SPAWN",{entity:this})}despawn(){if(!this._requireSpawned("despawn"))return;if(this._world.entityManager.getEntityChildren(this).forEach((Z)=>{Z.despawn()}),this._controller)this._controller.detach(this),this._controller.despawn(this);if(this.emitWithWorld(this._world,"ENTITY.DESPAWN",{entity:this}),this.isSimulated)this.removeFromSimulation();this._world.entityManager.unregisterEntity(this),this._world.audioManager.unregisterEntityAttachedAudios(this),this._world.lightManager.despawnEntityAttachedLights(this),this._world.particleEmitterManager.despawnEntityAttachedParticleEmitters(this),this._world.sceneUIManager.unloadEntityAttachedSceneUIs(this),this._id=void 0,this._world=void 0}setController(Z){if(this._controller===Z)return;if(this._controller)this._controller.detach(this);if(this._controller=Z,this._controller)this._controller.attach(this)}setModelAnimationsPlaybackRate(Z){if(!this._requireSpawned("setModelAnimationsPlaybackRate"))return;if(!this.isModelEntity||this._modelAnimationsPlaybackRate===Z)return;this._modelAnimationsPlaybackRate=Z,this.emitWithWorld(this._world,"ENTITY.SET_MODEL_ANIMATIONS_PLAYBACK_RATE",{entity:this,playbackRate:Z})}setModelHiddenNodes(Z){if(!this._requireSpawned("setModelHiddenNodes"))return;if(!this.isModelEntity)return;this._modelHiddenNodes=new Set(Z.map((J)=>J.toLowerCase())),this.emitWithWorld(this._world,"ENTITY.SET_MODEL_HIDDEN_NODES",{entity:this,modelHiddenNodes:this._modelHiddenNodes})}setModelScale(Z){if(!this._requireSpawned("setModelScale"))return;if(!this.isModelEntity||this._modelScale===Z)return;let J=Z/this._modelScale;this._modelScale=Z,this.colliders.forEach((X)=>X.scale(J)),this.emitWithWorld(this._world,"ENTITY.SET_MODEL_SCALE",{entity:this,modelScale:Z})}setModelShownNodes(Z){if(!this._requireSpawned("setModelShownNodes"))return;if(!this.isModelEntity)return;this._modelShownNodes=new Set(Z.map((J)=>J.toLowerCase())),this.emitWithWorld(this._world,"ENTITY.SET_MODEL_SHOWN_NODES",{entity:this,modelShownNodes:this._modelShownNodes})}setModelTextureUri(Z){if(!this._requireSpawned("setModelTextureUri"))return;if(!this.isModelEntity||this._modelTextureUri===Z)return;this._modelTextureUri=Z,this.emitWithWorld(this._world,"ENTITY.SET_MODEL_TEXTURE_URI",{entity:this,modelTextureUri:Z})}setOpacity(Z){if(!this._requireSpawned("setOpacity"))return;if(this._opacity===Z)return;this._opacity=Z,this.emitWithWorld(this._world,"ENTITY.SET_OPACITY",{entity:this,opacity:Z})}setParent(Z,J,X,Y){if(!this._requireSpawned("setParent"))return;if(Z&&!Z.isSpawned)return d.error("Entity.setParent(): Parent entity is not spawned, cannot set parent!");if(!this._parent&&Z)this._lastParentlessType=this.type;if(this._parent=Z,this._parentNodeName=J,this.colliders.forEach(($)=>$.setEnabled(!Z)),this.setType(!Z?this._lastParentlessType:"kinematic_velocity"),this.setPosition(X??{x:0,y:0,z:0}),this.setRotation(Y??{x:0,y:0,z:0,w:1}),!this.isKinematicPositionBased)this.resetAngularVelocity(),this.resetForces(),this.resetLinearVelocity(),this.resetTorques();this.emitWithWorld(this._world,"ENTITY.SET_PARENT",{entity:this,parent:Z,parentNodeName:J})}setTintColor(Z){if(!this._requireSpawned("setTintColor"))return;if(!Z&&!this._tintColor||Z&&this._tintColor&&Z.r===this._tintColor.r&&Z.g===this._tintColor.g&&Z.b===this._tintColor.b)return;this._tintColor=Z,this.emitWithWorld(this._world,"ENTITY.SET_TINT_COLOR",{entity:this,tintColor:Z})}startModelLoopedAnimations(Z){if(!this._requireSpawned("startModelLoopedAnimations"))return;if(!this.isModelEntity||!Z.length)return;if(!Z.some((J)=>!this._modelLoopedAnimations.has(J)))return;Z.forEach((J)=>{this._modelLoopedAnimations.add(J)}),this.emitWithWorld(this._world,"ENTITY.START_MODEL_LOOPED_ANIMATIONS",{entity:this,animations:new Set(Z)})}startModelOneshotAnimations(Z){if(!this._requireSpawned("startModelOneshotAnimations"))return;if(!this.isModelEntity||!Z.length)return;Z.forEach((J)=>{this._modelOneshotAnimations.add(J)}),this.emitWithWorld(this._world,"ENTITY.START_MODEL_ONESHOT_ANIMATIONS",{entity:this,animations:new Set(Z)})}stopAllModelAnimations(Z=[]){if(!this._requireSpawned("stopAllModelAnimations"))return;this._stopAnimationsFromSets([this._modelLoopedAnimations,this._modelOneshotAnimations],Z)}stopAllModelLoopedAnimations(Z=[]){if(!this._requireSpawned("stopAllModelLoopedAnimations"))return;this._stopAnimationsFromSets([this._modelLoopedAnimations],Z)}stopAllModelOneshotAnimations(Z=[]){if(!this._requireSpawned("stopAllModelOneshotAnimations"))return;this._stopAnimationsFromSets([this._modelOneshotAnimations],Z)}stopModelAnimations(Z){if(!this._requireSpawned("stopModelAnimations"))return;if(!this.isModelEntity||!Z.length)return;if(!Z.some((J)=>this._modelLoopedAnimations.has(J))&&!Z.some((J)=>this._modelOneshotAnimations.has(J)))return;Z.forEach((J)=>{this._modelLoopedAnimations.delete(J),this._modelOneshotAnimations.delete(J)}),this.emitWithWorld(this._world,"ENTITY.STOP_MODEL_ANIMATIONS",{entity:this,animations:new Set(Z)})}serialize(){if(!this._world)d.fatalError("Entity.serialize(): Entity is not in a world and cannot be serialized!");return P0.serializeEntity(this,this._world.tickAllocator)}tick(Z){if(this.emit("ENTITY.TICK",{entity:this,tickDeltaMs:Z}),this._controller)this._controller.tick(this,Z)}checkAndEmitUpdates(){if(!this._requireSpawned("checkAndEmitUpdates"))return;let Z=this.position,J=this.rotation;if(this._rotationExceedsThreshold(J,this._lastUpdatedRotation)){this._lastUpdatedRotation=J;let X=this._world.tickAllocator.getObject();X.entity=this,X.rotation=J,this.emitWithWorld(this._world,"ENTITY.UPDATE_ROTATION",X)}if(this._positionExceedsThreshold(Z,this._lastUpdatedPosition)){this._lastUpdatedPosition=Z;let X=this._world.tickAllocator.getObject();X.entity=this,X.position=Z,this.emitWithWorld(this._world,"ENTITY.UPDATE_POSITION",X)}}_positionExceedsThreshold(Z,J){let X=Z.x-J.x,Y=Z.y-J.y,$=Z.z-J.z;return X*X+Y*Y+$*$>this._positionUpdateThresholdSq}_requireSpawned(Z){if(!this.isSpawned)d.error(`Entity._requireSpawned(): Entity ${this._name} is not spawned, cannot invoke ${Z}()!`);return this.isSpawned}_rotationExceedsThreshold(Z,J){return Math.abs(Z.x*J.x+Z.y*J.y+Z.z*J.z+Z.w*J.w)<this._rotationUpdateThreshold}_stopAnimationsFromSets(Z,J=[]){if(!this.isModelEntity)return;let X=new Set(J),Y=[];for(let $ of Z)for(let Q of $)if(!X.has(Q))Y.push(Q);if(Y.length>0)this.stopModelAnimations(Y)}}class y1 extends _Y{static BASE_ENTITY_HEIGHT=1.5;static GROUND_SENSOR_HEIGHT_SCALE=0.125;static GROUND_SENSOR_RADIUS_SCALE=0.23;static JUMP_LAND_HEAVY_VELOCITY_THRESHOLD=-12;static WALL_COLLIDER_HEIGHT_SCALE=0.33;static WALL_COLLIDER_RADIUS_SCALE=0.4;static MOVEMENT_ROTATIONS={wa:Math.PI/4,wd:-Math.PI/4,sa:Math.PI-Math.PI/4,sd:Math.PI+Math.PI/4,s:Math.PI,asd:Math.PI,a:Math.PI/2,d:-Math.PI/2};static EXTERNAL_IMPULSE_DECAY_RATE=0.253;static SWIM_UPWARD_COOLDOWN_MS=600;static SWIMMING_DRAG_FACTOR=0.05;static WATER_ENTRY_SINKING_FACTOR=0.8;static WATER_ENTRY_SINKING_MS=250;applyDirectionalMovementRotations=!0;autoCancelMouseLeftClick=!0;canJump=()=>!0;canRun=()=>!0;canSwim=()=>!0;canWalk=()=>!0;faceForwardOnStop=!0;idleLoopedAnimations=["idle-upper","idle-lower"];interactOneshotAnimations=["simple-interact"];jumpLandHeavyOneshotAnimations=["jump-post-heavy"];jumpLandLightOneshotAnimations=["jump-post-light"];jumpOneshotAnimations=["jump-loop"];jumpVelocity=10;runLoopedAnimations=["run-upper","run-lower"];runVelocity=8;sticksToPlatforms=!0;swimFastVelocity=5;swimGravity=0;swimIdleLoopedAnimations=["swim-idle"];swimLoopedAnimations=["swim-forward"];swimMaxGravityVelocity=-1;swimSlowVelocity=3;swimUpwardVelocity=2;walkLoopedAnimations=["walk-upper","walk-lower"];walkVelocity=4;_externalVelocity={x:0,y:0,z:0};_magnitudeYTracker=0;_groundContactCount=0;_internalApplyImpulse=()=>{};_isActivelyMoving=!1;_isFullySubmerged=!1;_justSubmergedUntil=0;_liquidContactCount=0;_platform;_reusableImpulse={x:0,y:0,z:0};_reusablePlatformVelocity={x:0,y:0,z:0};_reusableTargetVelocities={x:0,y:0,z:0};_reusableVelocityClamp={x:0,y:0,z:0};_stepAudio;_swimUpwardCooldownAt=0;constructor(Z={}){super();this.applyDirectionalMovementRotations=Z.applyDirectionalMovementRotations??this.applyDirectionalMovementRotations,this.autoCancelMouseLeftClick=Z.autoCancelMouseLeftClick??this.autoCancelMouseLeftClick,this.faceForwardOnStop=Z.faceForwardOnStop??this.faceForwardOnStop,this.sticksToPlatforms=Z.sticksToPlatforms??this.sticksToPlatforms,this.canJump=Z.canJump??this.canJump,this.canRun=Z.canRun??this.canRun,this.canSwim=Z.canSwim??this.canSwim,this.canWalk=Z.canWalk??this.canWalk,this.jumpVelocity=Z.jumpVelocity??this.jumpVelocity,this.runVelocity=Z.runVelocity??this.runVelocity,this.walkVelocity=Z.walkVelocity??this.walkVelocity,this.swimFastVelocity=Z.swimFastVelocity??this.swimFastVelocity,this.swimSlowVelocity=Z.swimSlowVelocity??this.swimSlowVelocity,this.swimUpwardVelocity=Z.swimUpwardVelocity??this.swimUpwardVelocity,this.swimGravity=Z.swimGravity??this.swimGravity,this.swimMaxGravityVelocity=Z.swimMaxGravityVelocity??this.swimMaxGravityVelocity,this.idleLoopedAnimations=Z.idleLoopedAnimations??this.idleLoopedAnimations,this.interactOneshotAnimations=Z.interactOneshotAnimations??this.interactOneshotAnimations,this.jumpOneshotAnimations=Z.jumpOneshotAnimations??this.jumpOneshotAnimations,this.jumpLandHeavyOneshotAnimations=Z.jumpLandHeavyOneshotAnimations??this.jumpLandHeavyOneshotAnimations,this.jumpLandLightOneshotAnimations=Z.jumpLandLightOneshotAnimations??this.jumpLandLightOneshotAnimations,this.runLoopedAnimations=Z.runLoopedAnimations??this.runLoopedAnimations,this.swimLoopedAnimations=Z.swimLoopedAnimations??this.swimLoopedAnimations,this.swimIdleLoopedAnimations=Z.swimIdleLoopedAnimations??this.swimIdleLoopedAnimations,this.walkLoopedAnimations=Z.walkLoopedAnimations??this.walkLoopedAnimations}get isActivelyMoving(){return this._isActivelyMoving}get isGrounded(){return this._groundContactCount>0}get isOnPlatform(){return!!this._platform}get isSwimming(){return this._liquidContactCount>0}get platform(){return this._platform}attach(Z){super.attach(Z),this._internalApplyImpulse=Z.applyImpulse.bind(Z),Z.applyImpulse=(J)=>{let X=Z.mass||1;this._externalVelocity.x+=J.x/X,this._externalVelocity.y+=J.y/X,this._externalVelocity.z+=J.z/X},this._stepAudio=new P3({uri:"audio/sfx/step/stone/stone-step-04.mp3",loop:!0,volume:0.1,referenceDistance:2,cutoffDistance:15,attachedToEntity:Z}),Z.setCcdEnabled(!0),Z.lockAllRotations(),Z.on("ENTITY.BLOCK_COLLISION",({blockType:J,started:X})=>{if(!J.isLiquid||!this.canSwim(this))return;if(this._liquidContactCount<=0&&X){let Y=Z.linearVelocity;Z.setLinearVelocity({x:Y.x*this.swimGravity,y:Y.y*this.swimGravity,z:Y.z*this.swimGravity})}if(this._liquidContactCount+=X?1:-1,this._liquidContactCount>0)Z.setGravityScale(this.swimGravity),Z.stopAllModelLoopedAnimations(this.swimLoopedAnimations),this._swimUpwardCooldownAt=performance.now()+y1.SWIM_UPWARD_COOLDOWN_MS;else Z.setGravityScale(1),Z.stopModelAnimations(this.swimLoopedAnimations)})}spawn(Z){if(!Z.isSpawned)return d.error("DefaultPlayerEntityController.spawn(): Entity is not spawned!");Z.createAndAddChildCollider({shape:"cylinder",radius:y1.GROUND_SENSOR_RADIUS_SCALE*(Z.height/y1.BASE_ENTITY_HEIGHT),halfHeight:y1.GROUND_SENSOR_HEIGHT_SCALE*(Z.height/y1.BASE_ENTITY_HEIGHT),collisionGroups:{belongsTo:[4],collidesWith:[1,2,8]},isSensor:!0,relativePosition:{x:0,y:-Z.height/2,z:0},tag:"groundSensor",onCollision:(J,X)=>{if(!Z.isSpawned)return;if(!(J instanceof K9)||!J.isLiquid){if(X&&this._groundContactCount===0&&Z.linearVelocity.y<-1)if(Z.linearVelocity.y<y1.JUMP_LAND_HEAVY_VELOCITY_THRESHOLD)Z.startModelOneshotAnimations(this.jumpLandHeavyOneshotAnimations);else Z.startModelOneshotAnimations(this.jumpLandLightOneshotAnimations);this._groundContactCount+=X?1:-1}if(!this._groundContactCount&&!this.isSwimming)Z.startModelOneshotAnimations(this.jumpOneshotAnimations);else Z.stopModelAnimations(this.jumpOneshotAnimations);if(!(J instanceof i8))return;if(X&&this.sticksToPlatforms)this._platform=J;else if(J===this._platform&&!X)this._platform=void 0}}),Z.createAndAddChildCollider({shape:"capsule",halfHeight:y1.WALL_COLLIDER_HEIGHT_SCALE*(Z.height/y1.BASE_ENTITY_HEIGHT),radius:y1.WALL_COLLIDER_RADIUS_SCALE*(Z.height/y1.BASE_ENTITY_HEIGHT),collisionGroups:{belongsTo:[4],collidesWith:[1,2,8]},friction:0,frictionCombineRule:1,tag:"wallCollider"})}tickWithPlayerInput(Z,J,X,Y){if(!Z.isSpawned||!Z.world)return;if(super.tickWithPlayerInput(Z,J,X,Y),Z.parent)return;let{w:$,a:Q,s:K,d:G,c:W,sp:H,sh:V,ml:F}=J,{yaw:z}=X,q=Z.linearVelocity;this._reusableTargetVelocities.x=0,this._reusableTargetVelocities.y=0,this._reusableTargetVelocities.z=0,this._isActivelyMoving=!!($||Q||K||G);let U=V,B=Q&&G&&!$&&!K||$&&K&&!Q&&!G,L=U&&this.canRun(this)||!U&&this.canWalk(this);if(this.isSwimming&&!this._isFullySubmerged)this._isFullySubmerged=!0,this._justSubmergedUntil=performance.now()+y1.WATER_ENTRY_SINKING_MS;else if(!this.isSwimming)this._isFullySubmerged=!1,this._justSubmergedUntil=0;if(this.isGrounded&&!this.isSwimming&&this._isActivelyMoving&&!B&&L){let N=U?this.runLoopedAnimations:this.walkLoopedAnimations;Z.stopAllModelLoopedAnimations(N),Z.startModelLoopedAnimations(N),this._stepAudio?.setPlaybackRate(U?0.75:0.51),this._stepAudio?.play(Z.world,!this._stepAudio?.isPlaying)}else if(this._isFullySubmerged&&this.canSwim(this))if(this._stepAudio?.pause(),this._isActivelyMoving)Z.stopAllModelLoopedAnimations(this.swimLoopedAnimations),Z.startModelLoopedAnimations(this.swimLoopedAnimations);else Z.stopAllModelLoopedAnimations(this.swimIdleLoopedAnimations),Z.startModelLoopedAnimations(this.swimIdleLoopedAnimations);else this._stepAudio?.pause(),Z.stopAllModelLoopedAnimations(this.idleLoopedAnimations),Z.startModelLoopedAnimations(this.idleLoopedAnimations);let w;if(this.applyDirectionalMovementRotations&&L){if($&&Q&&!G&&!K)w=y1.MOVEMENT_ROTATIONS.wa;else if($&&G&&!Q&&!K)w=y1.MOVEMENT_ROTATIONS.wd;else if(K&&Q&&!$&&!G)w=y1.MOVEMENT_ROTATIONS.sa;else if(K&&G&&!$&&!Q)w=y1.MOVEMENT_ROTATIONS.sd;else if(K&&!$&&!Q&&!G||Q&&K&&G&&!$)w=y1.MOVEMENT_ROTATIONS.s;else if(Q&&!$&&!K&&!G)w=y1.MOVEMENT_ROTATIONS.a;else if(G&&!$&&!Q&&!K)w=y1.MOVEMENT_ROTATIONS.d}if(F)Z.startModelOneshotAnimations(this.interactOneshotAnimations),J.ml=!this.autoCancelMouseLeftClick;if(L){let N=!this.isSwimming?U?this.runVelocity:this.walkVelocity:U?this.swimFastVelocity:this.swimSlowVelocity,C=Math.sin(z),T=Math.cos(z);if($)this._reusableTargetVelocities.x-=N*C,this._reusableTargetVelocities.z-=N*T;if(K)this._reusableTargetVelocities.x+=N*C,this._reusableTargetVelocities.z+=N*T;if(Q)this._reusableTargetVelocities.x-=N*T,this._reusableTargetVelocities.z+=N*C;if(G)this._reusableTargetVelocities.x+=N*T,this._reusableTargetVelocities.z-=N*C;let E=Math.sqrt(this._reusableTargetVelocities.x*this._reusableTargetVelocities.x+this._reusableTargetVelocities.z*this._reusableTargetVelocities.z);if(E>N){let x=N/E;this._reusableTargetVelocities.x*=x,this._reusableTargetVelocities.z*=x}}if(this.isSwimming){if(q.y<this.swimMaxGravityVelocity)this._reusableVelocityClamp.x=q.x,this._reusableVelocityClamp.y=this.swimMaxGravityVelocity,this._reusableVelocityClamp.z=q.z,Z.setLinearVelocity(this._reusableVelocityClamp);if(q.y>this.swimUpwardVelocity*2)this._reusableVelocityClamp.x=q.x,this._reusableVelocityClamp.y=this.swimUpwardVelocity*2,this._reusableVelocityClamp.z=q.z,Z.setLinearVelocity(this._reusableVelocityClamp);if(W)this._reusableTargetVelocities.y=-this.swimUpwardVelocity;else if(performance.now()<this._justSubmergedUntil)this._reusableTargetVelocities.y=-this.swimUpwardVelocity*y1.WATER_ENTRY_SINKING_FACTOR;else if(!H)this._reusableTargetVelocities.y=-q.y*y1.SWIMMING_DRAG_FACTOR}if(H&&this.canJump(this)){if(this.isGrounded&&!this.isSwimming&&q.y>-0.001&&q.y<=3)this._reusableTargetVelocities.y=this.jumpVelocity;else if(this.isSwimming&&performance.now()>this._swimUpwardCooldownAt)this._reusableTargetVelocities.y=this.swimUpwardVelocity}let O=this._platform?.linearVelocity??this._reusablePlatformVelocity;if(this._externalVelocity.y!==0)this._magnitudeYTracker+=this._externalVelocity.y;if(this._externalVelocity.x!==0||this._externalVelocity.y!==0||this._externalVelocity.z!==0){if(this.isGrounded){let N=Math.sqrt(this._externalVelocity.x*this._externalVelocity.x+this._magnitudeYTracker*this._magnitudeYTracker+this._externalVelocity.z*this._externalVelocity.z);if(N>0.01){let T=Math.max(0,N-y1.EXTERNAL_IMPULSE_DECAY_RATE)/N;this._externalVelocity.x*=T,this._magnitudeYTracker*=T,this._externalVelocity.z*=T}else this._externalVelocity.x=0,this._externalVelocity.y=0,this._magnitudeYTracker=0,this._externalVelocity.z=0}}let M=this._reusableTargetVelocities.x+this._externalVelocity.x-q.x+O.x,R=this._reusableTargetVelocities.y+this._externalVelocity.y+O.y,D=this._reusableTargetVelocities.z+this._externalVelocity.z-q.z+O.z;if(this._externalVelocity.y=0,M!==0||R!==0||D!==0){let N=Z.mass;this._reusableImpulse.x=M*N,this._reusableImpulse.y=R*N,this._reusableImpulse.z=D*N,this._internalApplyImpulse(this._reusableImpulse)}if(z!==void 0&&(this.faceForwardOnStop||this.isActivelyMoving)){let C=(w!==void 0?z+w:z)*0.5;Z.setRotation({x:0,y:Math.sin(C),z:0,w:Math.cos(C)})}}}var tI;((G)=>{G.LOAD="SCENE_UI.LOAD";G.SET_ATTACHED_TO_ENTITY="SCENE_UI.SET_ATTACHED_TO_ENTITY";G.SET_OFFSET="SCENE_UI.SET_OFFSET";G.SET_POSITION="SCENE_UI.SET_POSITION";G.SET_STATE="SCENE_UI.SET_STATE";G.SET_VIEW_DISTANCE="SCENE_UI.SET_VIEW_DISTANCE";G.UNLOAD="SCENE_UI.UNLOAD"})(tI||={});class tV extends O0{_id;_attachedToEntity;_offset;_position;_state={};_templateId;_viewDistance;_world;constructor(Z){if(!!Z.attachedToEntity===!!Z.position)d.fatalError("Either attachedToEntity or position must be set, but not both");super();this._attachedToEntity=Z.attachedToEntity,this._offset=Z.offset,this._position=Z.position,this._state=Z.state??{},this._templateId=Z.templateId,this._viewDistance=Z.viewDistance}get id(){return this._id}get attachedToEntity(){return this._attachedToEntity}get isLoaded(){return this._id!==void 0}get offset(){return this._offset}get position(){return this._position}get state(){return this._state}get templateId(){return this._templateId}get viewDistance(){return this._viewDistance}get world(){return this._world}load(Z){if(this.isLoaded)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return d.error(`SceneUI.load(): Attached entity ${this._attachedToEntity.id} must be spawned before loading SceneUI!`);this._id=Z.sceneUIManager.registerSceneUI(this),this._world=Z,this.emitWithWorld(Z,"SCENE_UI.LOAD",{sceneUI:this})}setAttachedToEntity(Z){if(!Z.isSpawned)return d.error(`SceneUI.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);if(this._attachedToEntity===Z)return;if(this._attachedToEntity=Z,this._position=void 0,this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_ATTACHED_TO_ENTITY",{sceneUI:this,entity:Z})}setOffset(Z){if(this._offset===Z)return;if(this._offset=Z,this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_OFFSET",{sceneUI:this,offset:Z})}setPosition(Z){if(this._position===Z)return;if(this._attachedToEntity=void 0,this._position=Z,this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_POSITION",{sceneUI:this,position:Z})}setState(Z){if(this._state={...this._state,...Z},this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_STATE",{sceneUI:this,state:this._state})}setViewDistance(Z){if(this._viewDistance=Z,this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_VIEW_DISTANCE",{sceneUI:this,viewDistance:Z})}unload(){if(!this.isLoaded||!this._world)return;this._world.sceneUIManager.unregisterSceneUI(this),this.emitWithWorld(this._world,"SCENE_UI.UNLOAD",{sceneUI:this}),this._id=void 0,this._world=void 0}serialize(){if(!this._world)d.fatalError("SceneUI.serialize(): SceneUI is not in a world and cannot be serialized!");return P0.serializeSceneUI(this,this._world.tickAllocator)}}var H50=0.010000000000000002,V50=Math.cos(0.026);class y7 extends i8{player;nametagSceneUI;constructor(Z){super(Z);this._positionUpdateThresholdSq=H50,this._rotationUpdateThreshold=V50,this.player=Z.player,this.nametagSceneUI=new tV({templateId:"hytopia:nametag",attachedToEntity:this,offset:{x:0,y:1,z:0},viewDistance:15,state:{username:this.player.username,profilePictureUrl:this.player.profilePictureUrl}})}spawn(Z,J,X){super.spawn(Z,J,X),this.nametagSceneUI.load(Z),this.player.on("PLAYER.CHAT_MESSAGE_SEND",({message:Y})=>{this.nametagSceneUI.setState({chat:Y})})}tick(Z){if(!this.isSpawned||!this.world)return;if(!this.controller)return d.error(`PlayerEntity.tick(): PlayerEntity "${this.name}" must have a controller.`);let{input:J,camera:X}=this.player;this.controller.tickWithPlayerInput(this,J,X.orientation,Z),super.tick(Z)}}class eI extends y7{constructor(Z){super({modelUri:"models/players/player.gltf",modelLoopedAnimations:["idle_lower","idle_upper"],modelHiddenNodes:["hair-"],modelShownNodes:["hair-0003"],...Z});if(!Z.controller)this.setController(new y1)}}class eV{_activeEntities=new Set;_entities=new Map;_nextEntityId=1;_world;constructor(Z){this._world=Z}get entityCount(){return this._entities.size}get world(){return this._world}registerEntity(Z){if(Z.id!==void 0)d.fatalError(`EntityManager.registerEntity(): Entity ${Z.name} is already assigned the id ${Z.id}!`);let J=this._nextEntityId;if(this._entities.set(J,Z),this._nextEntityId++,!Z.isEnvironmental)this._activeEntities.add(Z);return J}unregisterEntity(Z){if(Z.id===void 0)return d.error(`EntityManager.unregisterEntity(): Entity ${Z.name} is not assigned an id!`);if(this._entities.delete(Z.id),!Z.isEnvironmental)this._activeEntities.delete(Z)}getAllEntities(Z=!1){return Z?this._world.tickAllocator.getArray(this._entities.values()):Array.from(this._entities.values())}getAllPlayerEntities(){let Z=[];return this._entities.forEach((J)=>{if(J instanceof y7)Z.push(J)}),Z}getPlayerEntitiesByPlayer(Z){let J=[];return this._entities.forEach((X)=>{if(X instanceof y7&&X.player===Z)J.push(X)}),J}getEntity(Z){return this._entities.get(Z)}getEntitiesByTag(Z){let J=[];return this._entities.forEach((X)=>{if(X.tag===Z)J.push(X)}),J}getEntitiesByTagSubstring(Z){let J=[];return this._entities.forEach((X)=>{if(X.tag?.includes(Z))J.push(X)}),J}getEntityChildren(Z){let J=[];return this._entities.forEach((X)=>{if(X.parent===Z)J.push(X)}),J}tickEntities(Z){for(let J of this._activeEntities)J.tick(Z)}checkAndEmitUpdates(){for(let Z of this._activeEntities)Z.checkAndEmitUpdates()}}var A31=r(KH(),1);var if1=r(Q90(),1),nf1=r(Q_(),1),af1=r(G_(),1),U_=r(Jj(),1),L_=r(F90(),1);var Q5=r(B40(),1),lm6=Q5.default.v1,pm6=Q5.default.v1ToV6,im6=Q5.default.v3,w40=Q5.default.v4,nm6=Q5.default.v5,am6=Q5.default.v6,sm6=Q5.default.v6ToV1,om6=Q5.default.v7,rm6=Q5.default.NIL,tm6=Q5.default.MAX,em6=Q5.default.version,Zu6=Q5.default.validate,Ju6=Q5.default.stringify,Xu6=Q5.default.parse;var P_;try{P_=new TextDecoder}catch(Z){}var J0,z9,b=0;var E_=[],A$=E_,Vz=0,v1={},Q1,pZ,V9=0,l9=0,n8,iZ,y5=[],J1,j40={useRecords:!1,mapsAsObjects:!0};class Vj{}var k_=new Vj;k_.name="MessagePack 0xC1";var BX=!1,T40=2,D_,C_,T_;try{new Function("")}catch(Z){T40=1/0}class nZ{constructor(Z){if(Z){if(Z.useRecords===!1&&Z.mapsAsObjects===void 0)Z.mapsAsObjects=!0;if(Z.sequential&&Z.trusted!==!1){if(Z.trusted=!0,!Z.structures&&Z.useRecords!=!1){if(Z.structures=[],!Z.maxSharedStructures)Z.maxSharedStructures=0}}if(Z.structures)Z.structures.sharedLength=Z.structures.length;else if(Z.getStructures)(Z.structures=[]).uninitialized=!0,Z.structures.sharedLength=0;if(Z.int64AsNumber)Z.int64AsType="number"}Object.assign(this,Z)}unpack(Z,J){if(J0)return y40(()=>{return Hj(),this?this.unpack(Z,J):nZ.prototype.unpack.call(j40,Z,J)});if(!Z.buffer&&Z.constructor===ArrayBuffer)Z=typeof Buffer!=="undefined"?Buffer.from(Z):new Uint8Array(Z);if(typeof J==="object")z9=J.end||Z.length,b=J.start||0;else b=0,z9=J>-1?J:Z.length;Vz=0,l9=0,pZ=null,A$=E_,n8=null,J0=Z;try{J1=Z.dataView||(Z.dataView=new DataView(Z.buffer,Z.byteOffset,Z.byteLength))}catch(X){if(J0=null,Z instanceof Uint8Array)throw X;throw new Error("Source must be a Uint8Array or Buffer but was a "+(Z&&typeof Z=="object"?Z.constructor.name:typeof Z))}if(this instanceof nZ){if(v1=this,this.structures)return Q1=this.structures,Gj(J);else if(!Q1||Q1.length>0)Q1=[]}else if(v1=j40,!Q1||Q1.length>0)Q1=[];return Gj(J)}unpackMultiple(Z,J){let X,Y=0;try{BX=!0;let $=Z.length,Q=this?this.unpack(Z,$):zj.unpack(Z,$);if(J){if(J(Q,Y,b)===!1)return;while(b<$)if(Y=b,J(Gj(),Y,b)===!1)return}else{X=[Q];while(b<$)Y=b,X.push(Gj());return X}}catch($){throw $.lastPosition=Y,$.values=X,$}finally{BX=!1,Hj()}}_mergeStructures(Z,J){if(C_)Z=C_.call(this,Z);if(Z=Z||[],Object.isFrozen(Z))Z=Z.map((X)=>X.slice(0));for(let X=0,Y=Z.length;X<Y;X++){let $=Z[X];if($){if($.isShared=!0,X>=32)$.highByte=X-32>>5}}Z.sharedLength=Z.length;for(let X in J||[])if(X>=0){let Y=Z[X],$=J[X];if($){if(Y)(Z.restoreStructures||(Z.restoreStructures=[]))[X]=Y;Z[X]=$}}return this.structures=Z}decode(Z,J){return this.unpack(Z,J)}}function Gj(Z){try{if(!v1.trusted&&!BX){let X=Q1.sharedLength||0;if(X<Q1.length)Q1.length=X}let J;if(v1.randomAccessStructure&&J0[b]<64&&J0[b]>=32&&D_){if(J=D_(J0,b,z9,v1),J0=null,!(Z&&Z.lazy)&&J)J=J.toJSON();b=z9}else J=I8();if(n8)b=n8.postBundlePosition,n8=null;if(BX)Q1.restoreStructures=null;if(b==z9){if(Q1&&Q1.restoreStructures)O40();if(Q1=null,J0=null,iZ)iZ=null}else if(b>z9)throw new Error("Unexpected end of MessagePack data");else if(!BX){let X;try{X=JSON.stringify(J,(Y,$)=>typeof $==="bigint"?`${$}n`:$).slice(0,100)}catch(Y){X="(JSON view not available "+Y+")"}throw new Error("Data read, but end of buffer not reached "+X)}return J}catch(J){if(Q1&&Q1.restoreStructures)O40();if(Hj(),J instanceof RangeError||J.message.startsWith("Unexpected end of buffer")||b>z9)J.incomplete=!0;throw J}}function O40(){for(let Z in Q1.restoreStructures)Q1[Z]=Q1.restoreStructures[Z];Q1.restoreStructures=null}function I8(){let Z=J0[b++];if(Z<160)if(Z<128)if(Z<64)return Z;else{let J=Q1[Z&63]||v1.getStructures&&E40()[Z&63];if(J){if(!J.read)J.read=I_(J,Z&63);return J.read()}else return Z}else if(Z<144)if(Z-=128,v1.mapsAsObjects){let J={};for(let X=0;X<Z;X++){let Y=h40();if(Y==="__proto__")Y="__proto_";J[Y]=I8()}return J}else{let J=new Map;for(let X=0;X<Z;X++)J.set(I8(),I8());return J}else{Z-=144;let J=new Array(Z);for(let X=0;X<Z;X++)J[X]=I8();if(v1.freezeData)return Object.freeze(J);return J}else if(Z<192){let J=Z-160;if(l9>=b)return pZ.slice(b-V9,(b+=J)-V9);if(l9==0&&z9<140){let X=J<16?__(J):x40(J);if(X!=null)return X}return Wj(J)}else{let J;switch(Z){case 192:return null;case 193:if(n8)if(J=I8(),J>0)return n8[1].slice(n8.position1,n8.position1+=J);else return n8[0].slice(n8.position0,n8.position0-=J);return k_;case 194:return!1;case 195:return!0;case 196:if(J=J0[b++],J===void 0)throw new Error("Unexpected end of buffer");return N_(J);case 197:return J=J1.getUint16(b),b+=2,N_(J);case 198:return J=J1.getUint32(b),b+=4,N_(J);case 199:return v$(J0[b++]);case 200:return J=J1.getUint16(b),b+=2,v$(J);case 201:return J=J1.getUint32(b),b+=4,v$(J);case 202:if(J=J1.getFloat32(b),v1.useFloat32>2){let X=h$[(J0[b]&127)<<1|J0[b+1]>>7];return b+=4,(X*J+(J>0?0.5:-0.5)>>0)/X}return b+=4,J;case 203:return J=J1.getFloat64(b),b+=8,J;case 204:return J0[b++];case 205:return J=J1.getUint16(b),b+=2,J;case 206:return J=J1.getUint32(b),b+=4,J;case 207:if(v1.int64AsType==="number")J=J1.getUint32(b)*4294967296,J+=J1.getUint32(b+4);else if(v1.int64AsType==="string")J=J1.getBigUint64(b).toString();else if(v1.int64AsType==="auto"){if(J=J1.getBigUint64(b),J<=BigInt(2)<<BigInt(52))J=Number(J)}else J=J1.getBigUint64(b);return b+=8,J;case 208:return J1.getInt8(b++);case 209:return J=J1.getInt16(b),b+=2,J;case 210:return J=J1.getInt32(b),b+=4,J;case 211:if(v1.int64AsType==="number")J=J1.getInt32(b)*4294967296,J+=J1.getUint32(b+4);else if(v1.int64AsType==="string")J=J1.getBigInt64(b).toString();else if(v1.int64AsType==="auto"){if(J=J1.getBigInt64(b),J>=BigInt(-2)<<BigInt(52)&&J<=BigInt(2)<<BigInt(52))J=Number(J)}else J=J1.getBigInt64(b);return b+=8,J;case 212:if(J=J0[b++],J==114)return C40(J0[b++]&63);else{let X=y5[J];if(X)if(X.read)return b++,X.read(I8());else if(X.noBuffer)return b++,X();else return X(J0.subarray(b,++b));else throw new Error("Unknown extension "+J)}case 213:if(J=J0[b],J==114)return b++,C40(J0[b++]&63,J0[b++]);else return v$(2);case 214:return v$(4);case 215:return v$(8);case 216:return v$(16);case 217:if(J=J0[b++],l9>=b)return pZ.slice(b-V9,(b+=J)-V9);return k40(J);case 218:if(J=J1.getUint16(b),b+=2,l9>=b)return pZ.slice(b-V9,(b+=J)-V9);return I40(J);case 219:if(J=J1.getUint32(b),b+=4,l9>=b)return pZ.slice(b-V9,(b+=J)-V9);return _40(J);case 220:return J=J1.getUint16(b),b+=2,R40(J);case 221:return J=J1.getUint32(b),b+=4,R40(J);case 222:return J=J1.getUint16(b),b+=2,N40(J);case 223:return J=J1.getUint32(b),b+=4,N40(J);default:if(Z>=224)return Z-256;if(Z===void 0){let X=new Error("Unexpected end of MessagePack data");throw X.incomplete=!0,X}throw new Error("Unknown MessagePack token "+Z)}}}var Pb1=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function I_(Z,J){function X(){if(X.count++>T40){let $=Z.read=new Function("r","return function(){return "+(v1.freezeData?"Object.freeze":"")+"({"+Z.map((Q)=>Q==="__proto__"?"__proto_:r()":Pb1.test(Q)?Q+":r()":"["+JSON.stringify(Q)+"]:r()").join(",")+"})}")(I8);if(Z.highByte===0)Z.read=M40(J,Z.read);return $()}let Y={};for(let $=0,Q=Z.length;$<Q;$++){let K=Z[$];if(K==="__proto__")K="__proto_";Y[K]=I8()}if(v1.freezeData)return Object.freeze(Y);return Y}if(X.count=0,Z.highByte===0)return M40(J,X);return X}var M40=(Z,J)=>{return function(){let X=J0[b++];if(X===0)return J();let Y=Z<32?-(Z+(X<<5)):Z+(X<<5),$=Q1[Y]||E40()[Y];if(!$)throw new Error("Record id is not defined for "+Y);if(!$.read)$.read=I_($,Z);return $.read()}};function E40(){let Z=y40(()=>{return J0=null,v1.getStructures()});return Q1=v1._mergeStructures(Z,Q1)}var Wj=x$,k40=x$,I40=x$,_40=x$,S40=!1;function v40(Z){S40=!0,Wj=J(1),k40=J(2),I40=J(3),_40=J(5);function J(X){return function Y($){let Q=A$[Vz++];if(Q==null){if(n8)return x$($);let G=J0.byteOffset,W=Z(b-X+G,z9+G,J0.buffer);if(typeof W=="string")Q=W,A$=E_;else if(A$=W,Vz=1,l9=1,Q=A$[0],Q===void 0)throw new Error("Unexpected end of buffer")}let K=Q.length;if(K<=$)return b+=$,Q;return pZ=Q,V9=b,l9=b+K,b+=$,Q.slice(0,$)}}}function x$(Z){let J;if(Z<16){if(J=__(Z))return J}if(Z>64&&P_)return P_.decode(J0.subarray(b,b+=Z));let X=b+Z,Y=[];J="";while(b<X){let $=J0[b++];if(($&128)===0)Y.push($);else if(($&224)===192){let Q=J0[b++]&63;Y.push(($&31)<<6|Q)}else if(($&240)===224){let Q=J0[b++]&63,K=J0[b++]&63;Y.push(($&31)<<12|Q<<6|K)}else if(($&248)===240){let Q=J0[b++]&63,K=J0[b++]&63,G=J0[b++]&63,W=($&7)<<18|Q<<12|K<<6|G;if(W>65535)W-=65536,Y.push(W>>>10&1023|55296),W=56320|W&1023;Y.push(W)}else Y.push($);if(Y.length>=4096)J+=Y6.apply(String,Y),Y.length=0}if(Y.length>0)J+=Y6.apply(String,Y);return J}function A40(Z,J,X){let Y=J0;J0=Z,b=J;try{return x$(X)}finally{J0=Y}}function R40(Z){let J=new Array(Z);for(let X=0;X<Z;X++)J[X]=I8();if(v1.freezeData)return Object.freeze(J);return J}function N40(Z){if(v1.mapsAsObjects){let J={};for(let X=0;X<Z;X++){let Y=h40();if(Y==="__proto__")Y="__proto_";J[Y]=I8()}return J}else{let J=new Map;for(let X=0;X<Z;X++)J.set(I8(),I8());return J}}var Y6=String.fromCharCode;function x40(Z){let J=b,X=new Array(Z);for(let Y=0;Y<Z;Y++){let $=J0[b++];if(($&128)>0){b=J;return}X[Y]=$}return Y6.apply(String,X)}function __(Z){if(Z<4)if(Z<2)if(Z===0)return"";else{let J=J0[b++];if((J&128)>1){b-=1;return}return Y6(J)}else{let J=J0[b++],X=J0[b++];if((J&128)>0||(X&128)>0){b-=2;return}if(Z<3)return Y6(J,X);let Y=J0[b++];if((Y&128)>0){b-=3;return}return Y6(J,X,Y)}else{let J=J0[b++],X=J0[b++],Y=J0[b++],$=J0[b++];if((J&128)>0||(X&128)>0||(Y&128)>0||($&128)>0){b-=4;return}if(Z<6)if(Z===4)return Y6(J,X,Y,$);else{let Q=J0[b++];if((Q&128)>0){b-=5;return}return Y6(J,X,Y,$,Q)}else if(Z<8){let Q=J0[b++],K=J0[b++];if((Q&128)>0||(K&128)>0){b-=6;return}if(Z<7)return Y6(J,X,Y,$,Q,K);let G=J0[b++];if((G&128)>0){b-=7;return}return Y6(J,X,Y,$,Q,K,G)}else{let Q=J0[b++],K=J0[b++],G=J0[b++],W=J0[b++];if((Q&128)>0||(K&128)>0||(G&128)>0||(W&128)>0){b-=8;return}if(Z<10)if(Z===8)return Y6(J,X,Y,$,Q,K,G,W);else{let H=J0[b++];if((H&128)>0){b-=9;return}return Y6(J,X,Y,$,Q,K,G,W,H)}else if(Z<12){let H=J0[b++],V=J0[b++];if((H&128)>0||(V&128)>0){b-=10;return}if(Z<11)return Y6(J,X,Y,$,Q,K,G,W,H,V);let F=J0[b++];if((F&128)>0){b-=11;return}return Y6(J,X,Y,$,Q,K,G,W,H,V,F)}else{let H=J0[b++],V=J0[b++],F=J0[b++],z=J0[b++];if((H&128)>0||(V&128)>0||(F&128)>0||(z&128)>0){b-=12;return}if(Z<14)if(Z===12)return Y6(J,X,Y,$,Q,K,G,W,H,V,F,z);else{let q=J0[b++];if((q&128)>0){b-=13;return}return Y6(J,X,Y,$,Q,K,G,W,H,V,F,z,q)}else{let q=J0[b++],U=J0[b++];if((q&128)>0||(U&128)>0){b-=14;return}if(Z<15)return Y6(J,X,Y,$,Q,K,G,W,H,V,F,z,q,U);let B=J0[b++];if((B&128)>0){b-=15;return}return Y6(J,X,Y,$,Q,K,G,W,H,V,F,z,q,U,B)}}}}}function P40(){let Z=J0[b++],J;if(Z<192)J=Z-160;else switch(Z){case 217:J=J0[b++];break;case 218:J=J1.getUint16(b),b+=2;break;case 219:J=J1.getUint32(b),b+=4;break;default:throw new Error("Expected string")}return x$(J)}function N_(Z){return v1.copyBuffers?Uint8Array.prototype.slice.call(J0,b,b+=Z):J0.subarray(b,b+=Z)}function v$(Z){let J=J0[b++];if(y5[J]){let X;return y5[J](J0.subarray(b,X=b+=Z),(Y)=>{b=Y;try{return I8()}finally{b=X}})}else throw new Error("Unknown extension type "+J)}var D40=new Array(4096);function h40(){let Z=J0[b++];if(Z>=160&&Z<192){if(Z=Z-160,l9>=b)return pZ.slice(b-V9,(b+=Z)-V9);else if(!(l9==0&&z9<180))return Wj(Z)}else return b--,f40(I8());let J=(Z<<5^(Z>1?J1.getUint16(b):Z>0?J0[b]:0))&4095,X=D40[J],Y=b,$=b+Z-3,Q,K=0;if(X&&X.bytes==Z){while(Y<$){if(Q=J1.getUint32(Y),Q!=X[K++]){Y=1879048192;break}Y+=4}$+=3;while(Y<$)if(Q=J0[Y++],Q!=X[K++]){Y=1879048192;break}if(Y===$)return b=Y,X.string;$-=3,Y=b}X=[],D40[J]=X,X.bytes=Z;while(Y<$)Q=J1.getUint32(Y),X.push(Q),Y+=4;$+=3;while(Y<$)Q=J0[Y++],X.push(Q);let G=Z<16?__(Z):x40(Z);if(G!=null)return X.string=G;return X.string=Wj(Z)}function f40(Z){if(typeof Z==="string")return Z;if(typeof Z==="number"||typeof Z==="boolean"||typeof Z==="bigint")return Z.toString();if(Z==null)return Z+"";if(v1.allowArraysInMapKeys&&Array.isArray(Z)&&Z.flat().every((J)=>["string","number","boolean","bigint"].includes(typeof J)))return Z.flat().toString();throw new Error(`Invalid property type for record: ${typeof Z}`)}var C40=(Z,J)=>{let X=I8().map(f40),Y=Z;if(J!==void 0)Z=Z<32?-((J<<5)+Z):(J<<5)+Z,X.highByte=J;let $=Q1[Z];if($&&($.isShared||BX))(Q1.restoreStructures||(Q1.restoreStructures=[]))[Z]=$;return Q1[Z]=X,X.read=I_(X,Y),X.read()};y5[0]=()=>{};y5[0].noBuffer=!0;y5[66]=(Z)=>{let J=Z.length,X=BigInt(Z[0]&128?Z[0]-256:Z[0]);for(let Y=1;Y<J;Y++)X<<=BigInt(8),X+=BigInt(Z[Y]);return X};var Db1={Error,TypeError,ReferenceError};y5[101]=()=>{let Z=I8();return(Db1[Z[0]]||Error)(Z[1],{cause:Z[2]})};y5[105]=(Z)=>{if(v1.structuredClone===!1)throw new Error("Structured clone extension is disabled");let J=J1.getUint32(b-4);if(!iZ)iZ=new Map;let X=J0[b],Y;if(X>=144&&X<160||X==220||X==221)Y=[];else if(X>=128&&X<144||X==222||X==223)Y=new Map;else if((X>=199&&X<=201||X>=212&&X<=216)&&J0[b+1]===115)Y=new Set;else Y={};let $={target:Y};iZ.set(J,$);let Q=I8();if(!$.used)return $.target=Q;else Object.assign(Y,Q);if(Y instanceof Map)for(let[K,G]of Q.entries())Y.set(K,G);if(Y instanceof Set)for(let K of Array.from(Q))Y.add(K);return Y};y5[112]=(Z)=>{if(v1.structuredClone===!1)throw new Error("Structured clone extension is disabled");let J=J1.getUint32(b-4),X=iZ.get(J);return X.used=!0,X.target};y5[115]=()=>new Set(I8());var S_=["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64","BigInt64","BigUint64"].map((Z)=>Z+"Array"),Cb1=typeof globalThis==="object"?globalThis:window;y5[116]=(Z)=>{let J=Z[0],X=Uint8Array.prototype.slice.call(Z,1).buffer,Y=S_[J];if(!Y){if(J===16)return X;if(J===17)return new DataView(X);throw new Error("Could not find typed array for code "+J)}return new Cb1[Y](X)};y5[120]=()=>{let Z=I8();return new RegExp(Z[0],Z[1])};var Tb1=[];y5[98]=(Z)=>{let J=(Z[0]<<24)+(Z[1]<<16)+(Z[2]<<8)+Z[3],X=b;return b+=J-Z.length,n8=Tb1,n8=[P40(),P40()],n8.position0=0,n8.position1=0,n8.postBundlePosition=b,b=X,I8()};y5[255]=(Z)=>{if(Z.length==4)return new Date((Z[0]*16777216+(Z[1]<<16)+(Z[2]<<8)+Z[3])*1000);else if(Z.length==8)return new Date(((Z[0]<<22)+(Z[1]<<14)+(Z[2]<<6)+(Z[3]>>2))/1e6+((Z[3]&3)*4294967296+Z[4]*16777216+(Z[5]<<16)+(Z[6]<<8)+Z[7])*1000);else if(Z.length==12)return new Date(((Z[0]<<24)+(Z[1]<<16)+(Z[2]<<8)+Z[3])/1e6+((Z[4]&128?-281474976710656:0)+Z[6]*1099511627776+Z[7]*4294967296+Z[8]*16777216+(Z[9]<<16)+(Z[10]<<8)+Z[11])*1000);else return new Date("invalid")};function y40(Z){if(T_)T_();let J=z9,X=b,Y=Vz,$=V9,Q=l9,K=pZ,G=A$,W=iZ,H=n8,V=new Uint8Array(J0.slice(0,z9)),F=Q1,z=Q1.slice(0,Q1.length),q=v1,U=BX,B=Z();return z9=J,b=X,Vz=Y,V9=$,l9=Q,pZ=K,A$=G,iZ=W,n8=H,J0=V,BX=U,Q1=F,Q1.splice(0,Q1.length,...z),v1=q,J1=new DataView(J0.buffer,J0.byteOffset,J0.byteLength),B}function Hj(){J0=null,iZ=null,Q1=null}var h$=new Array(147);for(let Z=0;Z<256;Z++)h$[Z]=+("1e"+Math.floor(45.15-Z*0.30103));var zj=new nZ({useRecords:!1}),Eb1=zj.unpack,kb1=zj.unpackMultiple,Ib1=zj.unpack;var _b1=new Float32Array(1),$u6=new Uint8Array(_b1.buffer,0,4);function b40(Z,J,X){D_=Z,C_=J,T_=X}var qj;try{qj=new TextEncoder}catch(Z){}var x_,d40,Fz=typeof Buffer!=="undefined",Fj=Fz?function(Z){return Buffer.allocUnsafeSlow(Z)}:Uint8Array,c40=Fz?Buffer:Uint8Array,g40=Fz?4294967296:2144337920,l,zz,b1,u=0,K5,X8=null,l40,Sb1=21760,vb1=/[\u0080-\uFFFF]/,g7=Symbol("record-id");class f$ extends nZ{constructor(Z){super(Z);this.offset=0;let J,X,Y,$,Q,K=c40.prototype.utf8Write?function(I,_){return l.utf8Write(I,_,l.byteLength-_)}:qj&&qj.encodeInto?function(I,_){return qj.encodeInto(I,l.subarray(_)).written}:!1,G=this;if(!Z)Z={};let W=Z&&Z.sequential,H=Z.structures||Z.saveStructures,V=Z.maxSharedStructures;if(V==null)V=H?32:0;if(V>8160)throw new Error("Maximum maxSharedStructure is 8160");if(Z.structuredClone&&Z.moreTypes==null)this.moreTypes=!0;let F=Z.maxOwnStructures;if(F==null)F=H?32:64;if(!this.structures&&Z.useRecords!=!1)this.structures=[];let z=V>32||F+V>64,q=V+64,U=V+F+64;if(U>8256)throw new Error("Maximum maxSharedStructure + maxOwnStructure is 8192");let B=[],L=0,w=0;this.pack=this.encode=function(I,_){if(!l)l=new Fj(8192),b1=l.dataView||(l.dataView=new DataView(l.buffer,0,8192)),u=0;if(K5=l.length-10,K5-u<2048)l=new Fj(l.length),b1=l.dataView||(l.dataView=new DataView(l.buffer,0,l.length)),K5=l.length-10,u=0;else u=u+7&2147483640;if(X=u,_&gb1)u+=_&255;if(Q=G.structuredClone?new Map:null,G.bundleStrings&&typeof I!=="string")X8=[],X8.size=1/0;else X8=null;if($=G.structures,$){if($.uninitialized)$=G._mergeStructures(G.getStructures());let p=$.sharedLength||0;if(p>V)throw new Error("Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to "+$.sharedLength);if(!$.transitions){$.transitions=Object.create(null);for(let n=0;n<p;n++){let o=$[n];if(!o)continue;let Q0,G0=$.transitions;for(let S0=0,v0=o.length;S0<v0;S0++){let r0=o[S0];if(Q0=G0[r0],!Q0)Q0=G0[r0]=Object.create(null);G0=Q0}G0[g7]=n+64}this.lastNamedStructuresLength=p}if(!W)$.nextId=p+64}if(Y)Y=!1;let A;try{if(G.randomAccessStructure&&I&&I.constructor&&I.constructor===Object)h(I);else R(I);let p=X8;if(X8)m40(X,R,0);if(Q&&Q.idsToInsert){let n=Q.idsToInsert.sort((S0,v0)=>S0.offset>v0.offset?1:-1),o=n.length,Q0=-1;while(p&&o>0){let S0=n[--o].offset+X;if(S0<p.stringsPosition+X&&Q0===-1)Q0=0;if(S0>p.position+X){if(Q0>=0)Q0+=6}else{if(Q0>=0)b1.setUint32(p.position+X,b1.getUint32(p.position+X)+Q0),Q0=-1;p=p.previous,o++}}if(Q0>=0&&p)b1.setUint32(p.position+X,b1.getUint32(p.position+X)+Q0);if(u+=n.length*6,u>K5)E(u);G.offset=u;let G0=xb1(l.subarray(X,u),n);return Q=null,G0}if(G.offset=u,_&yb1)return l.start=X,l.end=u,l;return l.subarray(X,u)}catch(p){throw A=p,p}finally{if($){if(O(),Y&&G.saveStructures){let p=$.sharedLength||0,n=l.subarray(X,u),o=p40($,G);if(!A){if(G.saveStructures(o,o.isCompatible)===!1)return G.pack(I,_);if(G.lastNamedStructuresLength=p,l.length>1073741824)l=null;return n}}}if(l.length>1073741824)l=null;if(_&bb1)u=X}};let O=()=>{if(w<10)w++;let I=$.sharedLength||0;if($.length>I&&!W)$.length=I;if(L>1e4){if($.transitions=null,w=0,L=0,B.length>0)B=[]}else if(B.length>0&&!W){for(let _=0,A=B.length;_<A;_++)B[_][g7]=0;B=[]}},M=(I)=>{var _=I.length;if(_<16)l[u++]=144|_;else if(_<65536)l[u++]=220,l[u++]=_>>8,l[u++]=_&255;else l[u++]=221,b1.setUint32(u,_),u+=4;for(let A=0;A<_;A++)R(I[A])},R=(I)=>{if(u>K5)l=E(u);var _=typeof I,A;if(_==="string"){let p=I.length;if(X8&&p>=4&&p<4096){if((X8.size+=p)>Sb1){let G0,S0=(X8[0]?X8[0].length*3+X8[1].length:0)+10;if(u+S0>K5)l=E(u+S0);let v0;if(X8.position)v0=X8,l[u]=200,u+=3,l[u++]=98,G0=u-X,u+=4,m40(X,R,0),b1.setUint16(G0+X-3,u-X-G0);else l[u++]=214,l[u++]=98,G0=u-X,u+=4;X8=["",""],X8.previous=v0,X8.size=0,X8.position=G0}let Q0=vb1.test(I);X8[Q0?0:1]+=I,l[u++]=193,R(Q0?-p:p);return}let n;if(p<32)n=1;else if(p<256)n=2;else if(p<65536)n=3;else n=5;let o=p*3;if(u+o>K5)l=E(u+o);if(p<64||!K){let Q0,G0,S0,v0=u+n;for(Q0=0;Q0<p;Q0++)if(G0=I.charCodeAt(Q0),G0<128)l[v0++]=G0;else if(G0<2048)l[v0++]=G0>>6|192,l[v0++]=G0&63|128;else if((G0&64512)===55296&&((S0=I.charCodeAt(Q0+1))&64512)===56320)G0=65536+((G0&1023)<<10)+(S0&1023),Q0++,l[v0++]=G0>>18|240,l[v0++]=G0>>12&63|128,l[v0++]=G0>>6&63|128,l[v0++]=G0&63|128;else l[v0++]=G0>>12|224,l[v0++]=G0>>6&63|128,l[v0++]=G0&63|128;A=v0-u-n}else A=K(I,u+n);if(A<32)l[u++]=160|A;else if(A<256){if(n<2)l.copyWithin(u+2,u+1,u+1+A);l[u++]=217,l[u++]=A}else if(A<65536){if(n<3)l.copyWithin(u+3,u+2,u+2+A);l[u++]=218,l[u++]=A>>8,l[u++]=A&255}else{if(n<5)l.copyWithin(u+5,u+3,u+3+A);l[u++]=219,b1.setUint32(u,A),u+=4}u+=A}else if(_==="number")if(I>>>0===I)if(I<32||I<128&&this.useRecords===!1||I<64&&!this.randomAccessStructure)l[u++]=I;else if(I<256)l[u++]=204,l[u++]=I;else if(I<65536)l[u++]=205,l[u++]=I>>8,l[u++]=I&255;else l[u++]=206,b1.setUint32(u,I),u+=4;else if(I>>0===I)if(I>=-32)l[u++]=256+I;else if(I>=-128)l[u++]=208,l[u++]=I+256;else if(I>=-32768)l[u++]=209,b1.setInt16(u,I),u+=2;else l[u++]=210,b1.setInt32(u,I),u+=4;else{let p;if((p=this.useFloat32)>0&&I<4294967296&&I>=-2147483648){l[u++]=202,b1.setFloat32(u,I);let n;if(p<4||(n=I*h$[(l[u]&127)<<1|l[u+1]>>7])>>0===n){u+=4;return}else u--}l[u++]=203,b1.setFloat64(u,I),u+=8}else if(_==="object"||_==="function")if(!I)l[u++]=192;else{if(Q){let n=Q.get(I);if(n){if(!n.id){let o=Q.idsToInsert||(Q.idsToInsert=[]);n.id=o.push(n)}l[u++]=214,l[u++]=112,b1.setUint32(u,n.id),u+=4;return}else Q.set(I,{offset:u-X})}let p=I.constructor;if(p===Object)T(I);else if(p===Array)M(I);else if(p===Map)if(this.mapAsEmptyObject)l[u++]=128;else{if(A=I.size,A<16)l[u++]=128|A;else if(A<65536)l[u++]=222,l[u++]=A>>8,l[u++]=A&255;else l[u++]=223,b1.setUint32(u,A),u+=4;for(let[n,o]of I)R(n),R(o)}else{for(let n=0,o=x_.length;n<o;n++){let Q0=d40[n];if(I instanceof Q0){let G0=x_[n];if(G0.write){if(G0.type)l[u++]=212,l[u++]=G0.type,l[u++]=0;let t1=G0.write.call(this,I);if(t1===I)if(Array.isArray(I))M(I);else T(I);else R(t1);return}let S0=l,v0=b1,r0=u;l=null;let A8;try{A8=G0.pack.call(this,I,(t1)=>{if(l=S0,S0=null,u+=t1,u>K5)E(u);return{target:l,targetView:b1,position:u-t1}},R)}finally{if(S0)l=S0,b1=v0,u=r0,K5=l.length-10}if(A8){if(A8.length+u>K5)E(A8.length+u);u=Ab1(A8,l,u,G0.type)}return}}if(Array.isArray(I))M(I);else{if(I.toJSON){let n=I.toJSON();if(n!==I)return R(n)}if(_==="function")return R(this.writeFunction&&this.writeFunction(I));T(I)}}}else if(_==="boolean")l[u++]=I?195:194;else if(_==="bigint"){if(I<9223372036854776000&&I>=-9223372036854776000)l[u++]=211,b1.setBigInt64(u,I);else if(I<18446744073709552000&&I>0)l[u++]=207,b1.setBigUint64(u,I);else if(this.largeBigIntToFloat)l[u++]=203,b1.setFloat64(u,Number(I));else if(this.largeBigIntToString)return R(I.toString());else if((this.useBigIntExtension||this.moreTypes)&&I<BigInt(2)**BigInt(1023)&&I>-(BigInt(2)**BigInt(1023))){l[u++]=199,u++,l[u++]=66;let p=[],n;do{let o=I&BigInt(255);n=(o&BigInt(128))===(I<BigInt(0)?BigInt(128):BigInt(0)),p.push(o),I>>=BigInt(8)}while(!((I===BigInt(0)||I===BigInt(-1))&&n));l[u-2]=p.length;for(let o=p.length;o>0;)l[u++]=Number(p[--o]);return}else throw new RangeError(I+" 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");u+=8}else if(_==="undefined")if(this.encodeUndefinedAsNil)l[u++]=192;else l[u++]=212,l[u++]=0,l[u++]=0;else throw new Error("Unknown type: "+_)},D=this.variableMapSize||this.coercibleKeyAsNumber||this.skipValues?(I)=>{let _;if(this.skipValues){_=[];for(let n in I)if((typeof I.hasOwnProperty!=="function"||I.hasOwnProperty(n))&&!this.skipValues.includes(I[n]))_.push(n)}else _=Object.keys(I);let A=_.length;if(A<16)l[u++]=128|A;else if(A<65536)l[u++]=222,l[u++]=A>>8,l[u++]=A&255;else l[u++]=223,b1.setUint32(u,A),u+=4;let p;if(this.coercibleKeyAsNumber)for(let n=0;n<A;n++){p=_[n];let o=Number(p);R(isNaN(o)?p:o),R(I[p])}else for(let n=0;n<A;n++)R(p=_[n]),R(I[p])}:(I)=>{l[u++]=222;let _=u-X;u+=2;let A=0;for(let p in I)if(typeof I.hasOwnProperty!=="function"||I.hasOwnProperty(p))R(p),R(I[p]),A++;if(A>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[_+++X]=A>>8,l[_+X]=A&255},N=this.useRecords===!1?D:Z.progressiveRecords&&!z?(I)=>{let _,A=$.transitions||($.transitions=Object.create(null)),p=u++-X,n;for(let o in I)if(typeof I.hasOwnProperty!=="function"||I.hasOwnProperty(o)){if(_=A[o],_)A=_;else{let Q0=Object.keys(I),G0=A;A=$.transitions;let S0=0;for(let v0=0,r0=Q0.length;v0<r0;v0++){let A8=Q0[v0];if(_=A[A8],!_)_=A[A8]=Object.create(null),S0++;A=_}if(p+X+1==u)u--,x(A,Q0,S0);else S(A,Q0,p,S0);n=!0,A=G0[o]}R(I[o])}if(!n){let o=A[g7];if(o)l[p+X]=o;else S(A,Object.keys(I),p,0)}}:(I)=>{let _,A=$.transitions||($.transitions=Object.create(null)),p=0;for(let o in I)if(typeof I.hasOwnProperty!=="function"||I.hasOwnProperty(o)){if(_=A[o],!_)_=A[o]=Object.create(null),p++;A=_}let n=A[g7];if(n)if(n>=96&&z)l[u++]=((n-=96)&31)+96,l[u++]=n>>5;else l[u++]=n;else x(A,A.__keys__||Object.keys(I),p);for(let o in I)if(typeof I.hasOwnProperty!=="function"||I.hasOwnProperty(o))R(I[o])},C=typeof this.useRecords=="function"&&this.useRecords,T=C?(I)=>{C(I)?N(I):D(I)}:N,E=(I)=>{let _;if(I>16777216){if(I-X>g40)throw new Error("Packed buffer would be larger than maximum buffer size");_=Math.min(g40,Math.round(Math.max((I-X)*(I>67108864?1.25:2),4194304)/4096)*4096)}else _=(Math.max(I-X<<2,l.length-1)>>12)+1<<12;let A=new Fj(_);if(b1=A.dataView||(A.dataView=new DataView(A.buffer,0,_)),I=Math.min(I,l.length),l.copy)l.copy(A,0,X,I);else A.set(l.slice(X,I));return u-=X,X=0,K5=A.length-10,l=A},x=(I,_,A)=>{let p=$.nextId;if(!p)p=64;if(p<q&&this.shouldShareStructure&&!this.shouldShareStructure(_)){if(p=$.nextOwnId,!(p<U))p=q;$.nextOwnId=p+1}else{if(p>=U)p=q;$.nextId=p+1}let n=_.highByte=p>=96&&z?p-96>>5:-1;if(I[g7]=p,I.__keys__=_,$[p-64]=_,p<q)if(_.isShared=!0,$.sharedLength=p-63,Y=!0,n>=0)l[u++]=(p&31)+96,l[u++]=n;else l[u++]=p;else{if(n>=0)l[u++]=213,l[u++]=114,l[u++]=(p&31)+96,l[u++]=n;else l[u++]=212,l[u++]=114,l[u++]=p;if(A)L+=w*A;if(B.length>=F)B.shift()[g7]=0;B.push(I),R(_)}},S=(I,_,A,p)=>{let n=l,o=u,Q0=K5,G0=X;if(l=zz,u=0,X=0,!l)zz=l=new Fj(8192);K5=l.length-10,x(I,_,p),zz=l;let S0=u;if(l=n,u=o,K5=Q0,X=G0,S0>1){let v0=u+S0-1;if(v0>K5)E(v0);let r0=A+X;l.copyWithin(r0+S0,r0+1,u),l.set(zz.slice(0,S0),r0),u=v0}else l[A+X]=zz[0]},h=(I)=>{let _=l40(I,l,X,u,$,E,(A,p,n)=>{if(n)return Y=!0;u=p;let o=l;if(R(A),O(),o!==l)return{position:u,targetView:b1,target:l};return u},this);if(_===0)return T(I);u=_}}useBuffer(Z){l=Z,l.dataView||(l.dataView=new DataView(l.buffer,l.byteOffset,l.byteLength)),u=0}set position(Z){u=Z}get position(){return u}clearSharedData(){if(this.structures)this.structures=[];if(this.typedStructs)this.typedStructs=[]}}d40=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,DataView,Vj];x_=[{pack(Z,J,X){let Y=Z.getTime()/1000;if((this.useTimestamp32||Z.getMilliseconds()===0)&&Y>=0&&Y<4294967296){let{target:$,targetView:Q,position:K}=J(6);$[K++]=214,$[K++]=255,Q.setUint32(K,Y)}else if(Y>0&&Y<4294967296){let{target:$,targetView:Q,position:K}=J(10);$[K++]=215,$[K++]=255,Q.setUint32(K,Z.getMilliseconds()*4000000+(Y/1000/4294967296>>0)),Q.setUint32(K+4,Y)}else if(isNaN(Y)){if(this.onInvalidDate)return J(0),X(this.onInvalidDate());let{target:$,targetView:Q,position:K}=J(3);$[K++]=212,$[K++]=255,$[K++]=255}else{let{target:$,targetView:Q,position:K}=J(15);$[K++]=199,$[K++]=12,$[K++]=255,Q.setUint32(K,Z.getMilliseconds()*1e6),Q.setBigInt64(K+4,BigInt(Math.floor(Y)))}}},{pack(Z,J,X){if(this.setAsEmptyObject)return J(0),X({});let Y=Array.from(Z),{target:$,position:Q}=J(this.moreTypes?3:0);if(this.moreTypes)$[Q++]=212,$[Q++]=115,$[Q++]=0;X(Y)}},{pack(Z,J,X){let{target:Y,position:$}=J(this.moreTypes?3:0);if(this.moreTypes)Y[$++]=212,Y[$++]=101,Y[$++]=0;X([Z.name,Z.message,Z.cause])}},{pack(Z,J,X){let{target:Y,position:$}=J(this.moreTypes?3:0);if(this.moreTypes)Y[$++]=212,Y[$++]=120,Y[$++]=0;X([Z.source,Z.flags])}},{pack(Z,J){if(this.moreTypes)v_(Z,16,J);else A_(Fz?Buffer.from(Z):new Uint8Array(Z),J)}},{pack(Z,J){let X=Z.constructor;if(X!==c40&&this.moreTypes)v_(Z,S_.indexOf(X.name),J);else A_(Z,J)}},{pack(Z,J){if(this.moreTypes)v_(Z,17,J);else A_(Fz?Buffer.from(Z):new Uint8Array(Z),J)}},{pack(Z,J){let{target:X,position:Y}=J(1);X[Y]=193}}];function v_(Z,J,X,Y){let $=Z.byteLength;if($+1<256){var{target:Q,position:K}=X(4+$);Q[K++]=199,Q[K++]=$+1}else if($+1<65536){var{target:Q,position:K}=X(5+$);Q[K++]=200,Q[K++]=$+1>>8,Q[K++]=$+1&255}else{var{target:Q,position:K,targetView:G}=X(7+$);Q[K++]=201,G.setUint32(K,$+1),K+=4}if(Q[K++]=116,Q[K++]=J,!Z.buffer)Z=new Uint8Array(Z);Q.set(new Uint8Array(Z.buffer,Z.byteOffset,Z.byteLength),K)}function A_(Z,J){let X=Z.byteLength;var Y,$;if(X<256){var{target:Y,position:$}=J(X+2);Y[$++]=196,Y[$++]=X}else if(X<65536){var{target:Y,position:$}=J(X+3);Y[$++]=197,Y[$++]=X>>8,Y[$++]=X&255}else{var{target:Y,position:$,targetView:Q}=J(X+5);Y[$++]=198,Q.setUint32($,X),$+=4}Y.set(Z,$)}function Ab1(Z,J,X,Y){let $=Z.length;switch($){case 1:J[X++]=212;break;case 2:J[X++]=213;break;case 4:J[X++]=214;break;case 8:J[X++]=215;break;case 16:J[X++]=216;break;default:if($<256)J[X++]=199,J[X++]=$;else if($<65536)J[X++]=200,J[X++]=$>>8,J[X++]=$&255;else J[X++]=201,J[X++]=$>>24,J[X++]=$>>16&255,J[X++]=$>>8&255,J[X++]=$&255}return J[X++]=Y,J.set(Z,X),X+=$,X}function xb1(Z,J){let X,Y=J.length*6,$=Z.length-Y;while(X=J.pop()){let{offset:Q,id:K}=X;Z.copyWithin(Q+Y,Q,$),Y-=6;let G=Q+Y;Z[G++]=214,Z[G++]=105,Z[G++]=K>>24,Z[G++]=K>>16&255,Z[G++]=K>>8&255,Z[G++]=K&255,$=Q}return Z}function m40(Z,J,X){if(X8.length>0){b1.setUint32(X8.position+Z,u+X-X8.position-Z),X8.stringsPosition=u-Z;let Y=X8;X8=null,J(Y[0]),J(Y[1])}}function p40(Z,J){return Z.isCompatible=(X)=>{let Y=!X||(J.lastNamedStructuresLength||0)===X.length;if(!Y)J._mergeStructures(X);return Y},Z}function i40(Z,J){l40=Z,p40=J}var n40=new f$({useRecords:!1}),hb1=n40.pack,fb1=n40.pack;var yb1=512,bb1=1024,gb1=2048;var h_=3,xG=0,qz=2,Uj=1,y_=16,s40=["num","object","string","ascii"];s40[y_]="date";var ub1=[!1,!0,!0,!1,!1,!0,!0,!1],o40;try{new Function(""),o40=!0}catch(Z){}var y$,db1=typeof Buffer!=="undefined",Lj,m7;try{Lj=new TextEncoder}catch(Z){}var cb1=db1?function(Z,J,X){return Z.utf8Write(J,X,Z.byteLength-X)}:Lj&&Lj.encodeInto?function(Z,J,X){return Lj.encodeInto(J,Z.subarray(X)).written}:!1,qu6=Symbol("type"),Uu6=Symbol("parent");i40(r40,ab1);function r40(Z,J,X,Y,$,Q,K,G){let W=G.typedStructs||(G.typedStructs=[]),H=J.dataView,V=(W.lastStringStart||100)+Y,F=J.length-10,z=Y;if(Y>F)J=Q(Y),H=J.dataView,Y-=X,z-=X,V-=X,X=0,F=J.length-10;let q,U=V,B=W.transitions||(W.transitions=Object.create(null)),L=W.nextId||W.length,w=L<15?1:L<240?2:L<61440?3:L<15728640?4:0;if(w===0)return 0;Y+=w;let O=[],M,R=0;for(let N in Z){let C=Z[N],T=B[N];if(!T)B[N]=T={key:N,parent:B,enumerationOffset:0,ascii0:null,ascii8:null,num8:null,string16:null,object16:null,num32:null,float64:null,date64:null};if(Y>F)J=Q(Y),H=J.dataView,Y-=X,z-=X,V-=X,U-=X,X=0,F=J.length-10;switch(typeof C){case"number":let E=C;if(L<200||!T.num64){if(E>>0===E&&E<536870912&&E>-520093696){if(E<246&&E>=0&&(T.num8&&!(L>200&&T.num32)||E<32&&!T.num32))B=T.num8||b5(T,xG,1),J[Y++]=E;else B=T.num32||b5(T,xG,4),H.setUint32(Y,E,!0),Y+=4;break}else if(E<4294967296&&E>=-2147483648){if(H.setFloat32(Y,E,!0),ub1[J[Y+3]>>>5]){let I;if((I=E*h$[(J[Y+3]&127)<<1|J[Y+2]>>7])>>0===I){B=T.num32||b5(T,xG,4),Y+=4;break}}}}B=T.num64||b5(T,xG,8),H.setFloat64(Y,E,!0),Y+=8;break;case"string":let x=C.length;if(q=U-V,(x<<2)+U>F)J=Q((x<<2)+U),H=J.dataView,Y-=X,z-=X,V-=X,U-=X,X=0,F=J.length-10;if(x>65280+q>>2){O.push(N,C,Y-z);break}let S,h=U;if(x<64){let I,_,A;for(I=0;I<x;I++)if(_=C.charCodeAt(I),_<128)J[U++]=_;else if(_<2048)S=!0,J[U++]=_>>6|192,J[U++]=_&63|128;else if((_&64512)===55296&&((A=C.charCodeAt(I+1))&64512)===56320)S=!0,_=65536+((_&1023)<<10)+(A&1023),I++,J[U++]=_>>18|240,J[U++]=_>>12&63|128,J[U++]=_>>6&63|128,J[U++]=_&63|128;else S=!0,J[U++]=_>>12|224,J[U++]=_>>6&63|128,J[U++]=_&63|128}else U+=cb1(J,C,U),S=U-h>x;if(q<160||q<246&&(T.ascii8||T.string8)){if(S){if(!(B=T.string8))if(W.length>10&&(B=T.ascii8))B.__type=qz,T.ascii8=null,T.string8=B,K(null,0,!0);else B=b5(T,qz,1)}else if(q===0&&!M){M=!0,B=T.ascii0||b5(T,h_,0);break}else if(!(B=T.ascii8)&&!(W.length>10&&(B=T.string8)))B=b5(T,h_,1);J[Y++]=q}else B=T.string16||b5(T,qz,2),H.setUint16(Y,q,!0),Y+=2;break;case"object":if(C){if(C.constructor===Date)B=T.date64||b5(T,y_,8),H.setFloat64(Y,C.getTime(),!0),Y+=8;else O.push(N,C,R);break}else if(T=a40(T,Y,H,-10),T)B=T,Y=y$;else O.push(N,C,R);break;case"boolean":B=T.num8||T.ascii8||b5(T,xG,1),J[Y++]=C?249:248;break;case"undefined":if(T=a40(T,Y,H,-9),T)B=T,Y=y$;else O.push(N,C,R);break;default:O.push(N,C,R)}R++}for(let N=0,C=O.length;N<C;){let T=O[N++],E=O[N++],x=O[N++],S=B[T];if(!S)B[T]=S={key:T,parent:B,enumerationOffset:x-R,ascii0:null,ascii8:null,num8:null,string16:null,object16:null,num32:null,float64:null};let h;if(E){let I;if(q=U-V,q<65280)if(B=S.object16,B)I=2;else if(B=S.object32)I=4;else B=b5(S,Uj,2),I=2;else B=S.object32||b5(S,Uj,4),I=4;if(h=K(E,U),typeof h==="object")U=h.position,H=h.targetView,J=h.target,V-=X,Y-=X,z-=X,X=0;else U=h;if(I===2)H.setUint16(Y,q,!0),Y+=2;else H.setUint32(Y,q,!0),Y+=4}else B=S.object16||b5(S,Uj,2),H.setInt16(Y,E===null?-10:-9,!0),Y+=2;R++}let D=B[g7];if(D==null){D=G.typedStructs.length;let N=[],C=B,T,E;while((E=C.__type)!==void 0){let x=C.__size;C=C.__parent,T=C.key;let S=[E,x,T];if(C.enumerationOffset)S.push(C.enumerationOffset);N.push(S),C=C.parent}N.reverse(),B[g7]=D,G.typedStructs[D]=N,K(null,0,!0)}switch(w){case 1:if(D>=16)return 0;J[z]=D+32;break;case 2:if(D>=256)return 0;J[z]=56,J[z+1]=D;break;case 3:if(D>=65536)return 0;J[z]=57,H.setUint16(z+1,D,!0);break;case 4:if(D>=16777216)return 0;H.setUint32(z,(D<<8)+58,!0);break}if(Y<V){if(V===U)return Y;J.copyWithin(Y,V,U),U+=Y-V,W.lastStringStart=Y-z}else if(Y>V){if(V===U)return Y;return W.lastStringStart=Y-z,r40(Z,J,X,z,$,Q,K,G)}return U}function a40(Z,J,X,Y){let $;if($=Z.ascii8||Z.num8)return X.setInt8(J,Y,!0),y$=J+1,$;if($=Z.string16||Z.object16)return X.setInt16(J,Y,!0),y$=J+2,$;if($=Z.num32)return X.setUint32(J,3758096640+Y,!0),y$=J+4,$;if($=Z.num64)return X.setFloat64(J,NaN,!0),X.setInt8(J,Y),y$=J+8,$;y$=J;return}function b5(Z,J,X){let Y=s40[J]+(X<<3),$=Z[Y]||(Z[Y]=Object.create(null));return $.__type=J,$.__size=X,$.__parent=Z,$}function lb1(Z){if(!(Z instanceof Map))return Z;let J=Z.get("typed")||[];if(Object.isFrozen(J))J=J.map(($)=>$.slice(0));let X=Z.get("named"),Y=Object.create(null);for(let $=0,Q=J.length;$<Q;$++){let K=J[$],G=Y;for(let[W,H,V]of K){let F=G[V];if(!F)G[V]=F={key:V,parent:G,enumerationOffset:0,ascii0:null,ascii8:null,num8:null,string16:null,object16:null,num32:null,float64:null,date64:null};G=b5(F,W,H)}G[g7]=$}return J.transitions=Y,this.typedStructs=J,this.lastTypedStructuresLength=J.length,X}var f_=Symbol.for("source");function pb1(Z,J,X,Y){let $=Z[J++]-32;if($>=24)switch($){case 24:$=Z[J++];break;case 25:$=Z[J++]+(Z[J++]<<8);break;case 26:$=Z[J++]+(Z[J++]<<8)+(Z[J++]<<16);break;case 27:$=Z[J++]+(Z[J++]<<8)+(Z[J++]<<16)+(Z[J++]<<24);break}let Q=Y.typedStructs&&Y.typedStructs[$];if(!Q){if(Z=Uint8Array.prototype.slice.call(Z,J,X),X-=J,J=0,!Y.getStructures)throw new Error(`Reference to shared structure ${$} without getStructures method`);if(Y._mergeStructures(Y.getStructures()),!Y.typedStructs)throw new Error("Could not find any shared typed structures");if(Y.lastTypedStructuresLength=Y.typedStructs.length,Q=Y.typedStructs[$],!Q)throw new Error("Could not find typed structure "+$)}var{construct:K,fullConstruct:G}=Q;if(!K){K=Q.construct=function q(){},G=Q.fullConstruct=function q(){},G.prototype=Y.structPrototype??{};var W=K.prototype=Y.structPrototype?Object.create(Y.structPrototype):{};let V=[],F=0,z;for(let q=0,U=Q.length;q<U;q++){let B=Q[q],[L,w,O,M]=B;if(O==="__proto__")O="__proto_";let R={key:O,offset:F};if(M)V.splice(q+M,0,R);else V.push(R);let D;switch(w){case 0:D=()=>0;break;case 1:D=(C,T)=>{let E=C.bytes[T+R.offset];return E>=246?AG(E):E};break;case 2:D=(C,T)=>{let E=C.bytes,S=(E.dataView||(E.dataView=new DataView(E.buffer,E.byteOffset,E.byteLength))).getUint16(T+R.offset,!0);return S>=65280?AG(S&255):S};break;case 4:D=(C,T)=>{let E=C.bytes,S=(E.dataView||(E.dataView=new DataView(E.buffer,E.byteOffset,E.byteLength))).getUint32(T+R.offset,!0);return S>=4294967040?AG(S&255):S};break}R.getRef=D,F+=w;let N;switch(L){case h_:if(z&&!z.next)z.next=R;z=R,R.multiGetCount=0,N=function(C){let{bytes:T,position:E}=C,x=F+E,S=D(C,E);if(typeof S!=="number")return S;let h,I=R.next;while(I){if(h=I.getRef(C,E),typeof h==="number")break;else h=null;I=I.next}if(h==null)h=C.bytesEnd-x;if(C.srcString)return C.srcString.slice(S,h);return A40(T,S+x,h-S)};break;case qz:case Uj:if(z&&!z.next)z.next=R;z=R,N=function(C){let T=C.position,E=F+T,x=D(C,T);if(typeof x!=="number")return x;let S=C.bytes,h,I=R.next;while(I){if(h=I.getRef(C,T),typeof h==="number")break;else h=null;I=I.next}if(h==null)h=C.bytesEnd-E;if(L===qz)return S.toString("utf8",x+E,h+E);else{m7=C;try{return Y.unpack(S,{start:x+E,end:h+E})}finally{m7=null}}};break;case xG:switch(w){case 4:N=function(C){let T=C.bytes,E=T.dataView||(T.dataView=new DataView(T.buffer,T.byteOffset,T.byteLength)),x=C.position+R.offset,S=E.getInt32(x,!0);if(S<536870912){if(S>-520093696)return S;if(S>-536870912)return AG(S&255)}let h=E.getFloat32(x,!0),I=h$[(T[x+3]&127)<<1|T[x+2]>>7];return(I*h+(h>0?0.5:-0.5)>>0)/I};break;case 8:N=function(C){let T=C.bytes,x=(T.dataView||(T.dataView=new DataView(T.buffer,T.byteOffset,T.byteLength))).getFloat64(C.position+R.offset,!0);if(isNaN(x)){let S=T[C.position+R.offset];if(S>=246)return AG(S)}return x};break;case 1:N=function(C){let E=C.bytes[C.position+R.offset];return E<246?E:AG(E)};break}break;case y_:N=function(C){let T=C.bytes,E=T.dataView||(T.dataView=new DataView(T.buffer,T.byteOffset,T.byteLength));return new Date(E.getFloat64(C.position+R.offset,!0))};break}R.get=N}if(o40){let q=[],U=[],B=0,L;for(let O of V){if(Y.alwaysLazyProperty&&Y.alwaysLazyProperty(O.key)){L=!0;continue}Object.defineProperty(W,O.key,{get:ib1(O.get),enumerable:!0});let M="v"+B++;U.push(M),q.push("o["+JSON.stringify(O.key)+"]="+M+"(s)")}if(L)q.push("__proto__:this");let w=new Function(...U,"var c=this;return function(s){var o=new c();"+q.join(";")+";return o;}").apply(G,V.map((O)=>O.get));Object.defineProperty(W,"toJSON",{value(O){return w.call(this,this[f_])}})}else Object.defineProperty(W,"toJSON",{value(q){let U={};for(let B=0,L=V.length;B<L;B++){let w=V[B].key;U[w]=this[w]}return U}})}var H=new K;return H[f_]={bytes:Z,position:J,srcString:"",bytesEnd:X},H}function AG(Z){switch(Z){case 246:return null;case 247:return;case 248:return!1;case 249:return!0}throw new Error("Unknown constant")}function ib1(Z){return function(){return Z(this[f_])}}function nb1(){if(m7)m7.bytes=Uint8Array.prototype.slice.call(m7.bytes,m7.position,m7.bytesEnd),m7.position=0,m7.bytesEnd=m7.bytes.length}function ab1(Z,J){if(J.typedStructs){let Y=new Map;Y.set("named",Z),Y.set("typed",J.typedStructs),Z=Y}let X=J.lastTypedStructuresLength||0;return Z.isCompatible=(Y)=>{let $=!0;if(Y instanceof Map){if((Y.get("named")||[]).length!==(J.lastNamedStructuresLength||0))$=!1;if((Y.get("typed")||[]).length!==X)$=!1}else if(Y instanceof Array||Array.isArray(Y)){if(Y.length!==(J.lastNamedStructuresLength||0))$=!1}if(!$)J._mergeStructures(Y);return $},J.lastTypedStructuresLength=J.typedStructs&&J.typedStructs.length,Z}b40(pb1,lb1,nb1);var rb1=process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED!==void 0&&process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED.toLowerCase()==="true";if(!rb1){let Z;try{if(Z=m("msgpackr-extract"),Z)v40(Z.extractStrings)}catch(J){}}import ao1 from"mediasoup";var NO=r(SK0(),1);import lo1 from"http";import po1 from"https";import RO from"fs";import io1 from"path";import no1 from"url";var vK0=`-----BEGIN CERTIFICATE-----
|
|
416
416
|
MIIDRjCCAi6gAwIBAgIFOTEzNTIwDQYJKoZIhvcNAQELBQAwWDEQMA4GA1UEAxMH
|
|
417
417
|
SFlUT1BJQTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0b24xEDAOBgNV
|
|
418
418
|
BAcTB1NlYXR0bGUxEDAOBgNVBAoTB0hZVE9QSUEwHhcNMjQxMTEzMjIyMjEwWhcN
|
|
@@ -457,7 +457,7 @@ qYGMwU/HBVHkLAn5XvT2a9xM0mzZ558d+ahbw8qAgRxg7BZ+2PW/bf7F2WRBUk1f
|
|
|
457
457
|
xauhAoGBALEspoxQozwohGQnP7EMF0/0JoKNpdNv0b0qCVvNiMo0+N297lI2mFQp
|
|
458
458
|
6xYlW/1l9afLokklF/J2IsyBrTCZoY7SaEk/lMMrQSyra+y0z71ogZ8A4ny9fxsj
|
|
459
459
|
0dDYJZGllL+3E/MQfd7k+KnOM/+A+cPoAnci76+L3vdkUb2P8SJk
|
|
460
|
-
-----END RSA PRIVATE KEY-----`;var nv=process.env.PORT??8080,av="0.7.
|
|
460
|
+
-----END RSA PRIVATE KEY-----`;var nv=process.env.PORT??8080,av="0.7.7",sv;(($)=>{$.READY="WEBSERVER.READY";$.STOPPED="WEBSERVER.STOPPED";$.ERROR="WEBSERVER.ERROR";$.UPGRADE="WEBSERVER.UPGRADE"})(sv||={});class FW extends O0{static instance=new FW;_webserver=NO.default();_internalHttpServer;constructor(){super();this._webserver.use((Z,J,X)=>{J.header("Access-Control-Allow-Origin","*"),X()}),this._webserver.get("/",(Z,J)=>{J.json({status:"OK",version:av,runtime:typeof Bun!=="undefined"?"bun":"node"})}),this._webserver.use(NO.default.static("assets"));try{this._webserver.use(NO.default.static(io1.dirname(m.resolve("/Users/arkdev/Desktop/HYTOPIA/hytopia/assets/release/index.js"))))}catch{}}start(){if(!this._internalHttpServer)this._internalHttpServer=process.env.NODE_ENV==="production"?lo1.createServer(this._webserver):po1.createServer({key:RO.existsSync("assets/certs/localhost.key")?RO.readFileSync("assets/certs/localhost.key"):AK0,cert:RO.existsSync("assets/certs/localhost.crt")?RO.readFileSync("assets/certs/localhost.crt"):vK0},this._webserver),this._internalHttpServer.on("upgrade",this._onUpgrade),this._internalHttpServer.on("error",this._onError),this._internalHttpServer.on("close",this._onStopped);else d.warning("WebServer.start(): server already started!");this._internalHttpServer.listen(nv,this._onStarted),console.info(`WebServer.start(): Server running on port ${nv}.`)}stop(){if(this._internalHttpServer)return new Promise((Z,J)=>{this._internalHttpServer.close((X)=>{if(X)J(X);else Z(!0)})});else return d.warning("WebServer.stop(): server not started."),Promise.resolve(!1)}_onStarted=()=>{this.emitWithGlobal("WEBSERVER.READY",{})};_onUpgrade=async(Z,J,X)=>{let Y=no1.parse(Z.url??"",!0).query,$=Y.connectionId?.toString(),Q=Y.sessionToken?.toString()??"";if($&&a7.instance.isValidConnectionId($))Z.connectionId=$;else{let K=await f7.instance.getPlayerSession(Q);if(K?.error){let G=`${K.error.code}: ${K.error.message}`;J.write(`HTTP/1.1 401 Unauthorized\r
|
|
461
461
|
Content-Type: text/plain\r
|
|
462
462
|
Content-Length: ${G.length}\r
|
|
463
463
|
Connection: close\r
|
|
@@ -490,4 +490,4 @@ ${$.stack}`:"unknown"}}}}}var we1=(Z={})=>{let J=Z.limit??Ve1;return{name:ze1,pr
|
|
|
490
490
|
`),U=q.shift();if(!U)return Z.destroy(),X(new Error("No header received from proxy CONNECT response"));let B=U.split(" "),L=+(B[1]||0),w=B.slice(2).join(" "),O={};for(let M of q){if(!M)continue;let R=M.indexOf(":");if(R===-1)return Z.destroy(),X(new Error(`Invalid header from proxy CONNECT response: "${M}"`));let D=M.slice(0,R).toLowerCase(),N=M.slice(R+1).trimStart(),C=O[D];if(typeof C==="string")O[D]=[C,N];else if(Array.isArray(C))C.push(N);else O[D]=N}eN("got proxy server response: %o %o",U,O),K(),J({connect:{statusCode:L,statusText:w,headers:O},buffered:F})}Z.on("error",W),Z.on("end",G),Q()})}function KU(...Z){g.log("[https-proxy-agent]",...Z)}class ZP extends Vm{static __initStatic(){this.protocols=["http","https"]}constructor(Z,J){super(J);this.options={},this.proxy=typeof Z==="string"?new URL(Z):Z,this.proxyHeaders=J?.headers??{},KU("Creating new HttpsProxyAgent instance: %o",this.proxy.href);let X=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),Y=this.proxy.port?parseInt(this.proxy.port,10):this.proxy.protocol==="https:"?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...J?z31(J,"headers"):null,host:X,port:Y}}async connect(Z,J){let{proxy:X}=this;if(!J.host)throw new TypeError('No "host" provided');let Y;if(X.protocol==="https:"){KU("Creating `tls.Socket`: %o",this.connectOpts);let F=this.connectOpts.servername||this.connectOpts.host;Y=zm.connect({...this.connectOpts,servername:F&&kJ.isIP(F)?void 0:F})}else KU("Creating `net.Socket`: %o",this.connectOpts),Y=kJ.connect(this.connectOpts);let $=typeof this.proxyHeaders==="function"?this.proxyHeaders():{...this.proxyHeaders},Q=kJ.isIPv6(J.host)?`[${J.host}]`:J.host,K=`CONNECT ${Q}:${J.port} HTTP/1.1\r
|
|
491
491
|
`;if(X.username||X.password){let F=`${decodeURIComponent(X.username)}:${decodeURIComponent(X.password)}`;$["Proxy-Authorization"]=`Basic ${Buffer.from(F).toString("base64")}`}if($.Host=`${Q}:${J.port}`,!$["Proxy-Connection"])$["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close";for(let F of Object.keys($))K+=`${F}: ${$[F]}\r
|
|
492
492
|
`;let G=V31(Y);Y.write(`${K}\r
|
|
493
|
-
`);let{connect:W,buffered:H}=await G;if(Z.emit("proxyConnect",W),this.emit("proxyConnect",W,Z),W.statusCode===200){if(Z.once("socket",DQ6),J.secureEndpoint){KU("Upgrading socket connection to TLS");let F=J.servername||J.host;return zm.connect({...z31(J,"host","path","port"),socket:Y,servername:kJ.isIP(F)?void 0:F})}return Y}Y.destroy();let V=new kJ.Socket({writable:!1});return V.readable=!0,Z.once("socket",(F)=>{KU("Replaying proxy buffer for failed request"),F.push(H),F.push(null)}),V}}ZP.__initStatic();function DQ6(Z){Z.resume()}function z31(Z,...J){let X={},Y;for(Y in Z)if(!J.includes(Y))X[Y]=Z[Y];return X}var IQ6=32768;function _Q6(Z){return new EQ6({read(){this.push(Z),this.push(null)}})}function JP(Z){let J;try{J=new URL(Z.url)}catch(W){return $8(()=>{console.warn("[@sentry/node]: Invalid dsn or tunnel option, will not send any events. The tunnel option must be a full URL when used.")}),EW(Z,()=>Promise.resolve({}))}let X=J.protocol==="https:",Y=SQ6(J,Z.proxy||(X?process.env.https_proxy:void 0)||process.env.http_proxy),$=X?TQ6:CQ6,Q=Z.keepAlive===void 0?!1:Z.keepAlive,K=Y?new ZP(Y):new $.Agent({keepAlive:Q,maxSockets:30,timeout:2000}),G=vQ6(Z,Z.httpModule??$,K);return EW(Z,G)}function SQ6(Z,J){let{no_proxy:X}=process.env;if(X?.split(",").some(($)=>Z.host.endsWith($)||Z.hostname.endsWith($)))return;else return J}function vQ6(Z,J,X){let{hostname:Y,pathname:$,port:Q,protocol:K,search:G}=new URL(Z.url);return function W(H){return new Promise((V,F)=>{EF(()=>{let z=_Q6(H.body),q={...Z.headers};if(H.body.length>IQ6)q["content-encoding"]="gzip",z=z.pipe(kQ6());let U=J.request({method:"POST",agent:X,headers:q,hostname:Y,path:`${$}${G}`,port:Q,protocol:K,ca:Z.caCerts},(B)=>{B.on("data",()=>{}),B.on("end",()=>{}),B.setEncoding("utf8");let L=B.headers["retry-after"]??null,w=B.headers["x-sentry-rate-limits"]??null;V({statusCode:B.statusCode,headers:{"retry-after":L,"x-sentry-rate-limits":Array.isArray(w)?w[0]||null:w}})});U.on("error",F),z.pipe(U)})})}}var AQ6=new Set(["false","f","n","no","off","0"]),xQ6=new Set(["true","t","y","yes","on","1"]);function XP(Z,J){let X=String(Z).toLowerCase();if(AQ6.has(X))return!1;if(xQ6.has(X))return!0;return J?.strict?null:Boolean(Z)}import{posix as hQ6,sep as fQ6}from"node:path";function F31(Z){return Z.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}function YP(Z=process.argv[1]?qx(process.argv[1]):process.cwd(),J=fQ6==="\\"){let X=J?F31(Z):Z;return(Y)=>{if(!Y)return;let $=J?F31(Y):Y,{dir:Q,base:K,ext:G}=hQ6.parse($);if(G===".js"||G===".mjs"||G===".cjs")K=K.slice(0,G.length*-1);let W=decodeURIComponent(K);if(!Q)Q=".";let H=Q.lastIndexOf("/node_modules");if(H>-1)return`${Q.slice(H+14).replace(/\//g,".")}:${W}`;if(Q.startsWith(X)){let V=Q.slice(X.length+1).replace(/\//g,".");return V?`${V}:${W}`:W}return W}}function $P(Z){if(process.env.SENTRY_RELEASE)return process.env.SENTRY_RELEASE;if(j0.SENTRY_RELEASE?.id)return j0.SENTRY_RELEASE.id;let J=process.env.GITHUB_SHA||process.env.CI_MERGE_REQUEST_SOURCE_BRANCH_SHA||process.env.CI_BUILD_REF||process.env.CI_COMMIT_SHA||process.env.BITBUCKET_COMMIT,X=process.env.APPVEYOR_PULL_REQUEST_HEAD_COMMIT||process.env.APPVEYOR_REPO_COMMIT||process.env.CODEBUILD_RESOLVED_SOURCE_VERSION||process.env.AWS_COMMIT_ID||process.env.BUILD_SOURCEVERSION||process.env.GIT_CLONE_COMMIT_HASH||process.env.BUDDY_EXECUTION_REVISION||process.env.BUILDKITE_COMMIT||process.env.CIRCLE_SHA1||process.env.CIRRUS_CHANGE_IN_REPO||process.env.CF_REVISION||process.env.CM_COMMIT||process.env.CF_PAGES_COMMIT_SHA||process.env.DRONE_COMMIT_SHA||process.env.FC_GIT_COMMIT_SHA||process.env.HEROKU_TEST_RUN_COMMIT_VERSION||process.env.HEROKU_SLUG_COMMIT||process.env.RAILWAY_GIT_COMMIT_SHA||process.env.RENDER_GIT_COMMIT||process.env.SEMAPHORE_GIT_SHA||process.env.TRAVIS_PULL_REQUEST_SHA||process.env.VERCEL_GIT_COMMIT_SHA||process.env.VERCEL_GITHUB_COMMIT_SHA||process.env.VERCEL_GITLAB_COMMIT_SHA||process.env.VERCEL_BITBUCKET_COMMIT_SHA||process.env.ZEIT_GITHUB_COMMIT_SHA||process.env.ZEIT_GITLAB_COMMIT_SHA||process.env.ZEIT_BITBUCKET_COMMIT_SHA,Y=process.env.CI_COMMIT_ID||process.env.SOURCE_COMMIT||process.env.SOURCE_VERSION||process.env.GIT_COMMIT||process.env.COMMIT_REF||process.env.BUILD_VCS_NUMBER||process.env.CI_COMMIT_SHA;return J||X||Y||Z}var QP=AO(Cx(YP()));var U31=r(X0(),1),L31=r(K1(),1);import*as q31 from"node:os";import{threadId as yQ6,isMainThread as bQ6}from"worker_threads";var gQ6=60000;class GU extends aO{constructor(Z){let J=Z.serverName||global.process.env.SENTRY_NAME||q31.hostname(),X={...Z,platform:"node",runtime:{name:"node",version:global.process.version},serverName:J};if(Z.openTelemetryInstrumentations)L31.registerInstrumentations({instrumentations:Z.openTelemetryInstrumentations});$x(X,"node"),g.log(`Initializing Sentry: process: ${process.pid}, thread: ${bQ6?"main":`worker-${yQ6}`}.`);super(X);if(this.getOptions()._experiments?.enableLogs){if(this._logOnExitFlushListener=()=>{yX(this)},J)this.on("beforeCaptureLog",(Y)=>{Y.attributes={...Y.attributes,"server.address":J}});process.on("beforeExit",this._logOnExitFlushListener)}}get tracer(){if(this._tracer)return this._tracer;let Z="@sentry/node",J=L8,X=U31.trace.getTracer(Z,J);return this._tracer=X,X}async flush(Z){let X=this.traceProvider?.activeSpanProcessor;if(X)await X.forceFlush();if(this.getOptions().sendClientReports)this._flushOutcomes();return super.flush(Z)}close(Z){if(this._clientReportInterval)clearInterval(this._clientReportInterval);if(this._clientReportOnExitFlushListener)process.off("beforeExit",this._clientReportOnExitFlushListener);if(this._logOnExitFlushListener)process.off("beforeExit",this._logOnExitFlushListener);return super.close(Z)}startClientReportTracking(){let Z=this.getOptions();if(Z.sendClientReports)this._clientReportOnExitFlushListener=()=>{this._flushOutcomes()},this._clientReportInterval=setInterval(()=>{m0&&g.log("Flushing client reports based on interval."),this._flushOutcomes()},Z.clientReportFlushInterval??gQ6).unref(),process.on("beforeExit",this._clientReportOnExitFlushListener)}_getTraceInfoFromScope(Z){if(!Z)return[void 0,void 0];return h41(this,Z)}}var F7=r(X0(),1),B31=r(iy(),1),w31=r(sy(),1),O3=r(P1(),1);var j31=r($y(),1);import mQ6 from"module";var Fm=1e6;function KP(Z,J={}){if(Z.getOptions().debug)M31();let X=dQ6(Z,J);Z.traceProvider=X}function qm(){let[Z=0,J=0]=process.versions.node.split(".").map(Number);if(Z>=21||Z===20&&J>=6||Z===18&&J>=19){if(!j0._sentryEsmLoaderHookRegistered)try{let{addHookMessagePort:X}=j31.createAddHookMessageChannel();mQ6.register("import-in-the-middle/hook.mjs",import.meta.url,{data:{addHookMessagePort:X,include:[]},transferList:[X]})}catch(X){g.warn("Failed to register ESM hook",X)}}else $8(()=>{console.warn(`[Sentry] You are using Node.js v${process.versions.node} in ESM mode ("import syntax"). The Sentry Node.js SDK is not compatible with ESM in Node.js versions before 18.19.0 or before 20.6.0. Please either build your application with CommonJS ("require() syntax"), or upgrade your Node.js version.`)})}function O31(Z={}){let{debug:J}=Z;if(J)g.enable(),M31();if(!U4())qm();uQ6(Z.integrations).forEach((X)=>{if(X(),J)g.log(`[Sentry] Preloaded ${X.id} instrumentation`)})}function uQ6(Z){let J=H31();if(!Z)return J;return J.filter((X)=>Z.includes(X.id))}function dQ6(Z,J={}){let X=new w31.BasicTracerProvider({sampler:new Lb(Z),resource:new B31.Resource({[O3.ATTR_SERVICE_NAME]:"node",[O3.SEMRESATTRS_SERVICE_NAMESPACE]:"sentry",[O3.ATTR_SERVICE_VERSION]:L8}),forceFlushTimeoutMillis:500,spanProcessors:[new Ub({timeout:cQ6(Z.getOptions().maxSpanWaitDuration)}),...J.spanProcessors||[]]});return F7.trace.setGlobalTracerProvider(X),F7.propagation.setGlobalPropagator(new Hb),F7.context.setGlobalContextManager(new rN),X}function cQ6(Z){if(Z==null)return;if(Z>Fm)return m0&&g.warn(`\`maxSpanWaitDuration\` is too high, using the maximum value of ${Fm}`),Fm;else if(Z<=0||Number.isNaN(Z)){m0&&g.warn("`maxSpanWaitDuration` must be a positive number, using default value instead.");return}return Z}function M31(){let Z=new Proxy(g,{get(J,X,Y){return Reflect.get(J,X==="verbose"?"debug":X,Y)}});F7.diag.disable(),F7.diag.setLogger(Z,F7.DiagLogLevel.DEBUG)}function lQ6(){return U4()?[cR()]:[]}function Um(){return[fF(),hF(),yF(),bF(),gF(),SR(),hR(),lR(),pR(),gR(),dR(),bR(),sN(),W31(),...lQ6()]}function Lm(Z){return[...Um(),...z5(Z)?tN():[]]}function GP(Z={}){return N31(Z,Lm)}function R31(Z={}){return N31(Z,()=>[])}function N31(Z={},J){let X=pQ6(Z,J);if(X.debug===!0)if(m0)g.enable();else $8(()=>{console.warn("[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.")});if(!U4()&&X.registerEsmLoaderHooks!==!1)qm();if(ER(),l0().update(X.initialScope),X.spotlight&&!X.integrations.some(({name:Q})=>Q===og))X.integrations.push(yN({sidecarUrl:typeof X.spotlight==="string"?X.spotlight:void 0}));let $=new GU(X);if(l0().setClient($),$.init(),g.log(`Running in ${U4()?"CommonJS":"ESM"} mode.`),$.startClientReportTracking(),aQ6(),!X.skipOpenTelemetrySetup)KP($,{spanProcessors:X.openTelemetrySpanProcessors}),Bm();return T41($),f41($),$}function Bm(){if(!m0)return;let Z=_41(),J=["SentryContextManager","SentryPropagator"];if(z5())J.push("SentrySpanProcessor");for(let X of J)if(!Z.includes(X))g.error(`You have to set up the ${X}. Without this, the OpenTelemetry & Sentry integration will not work properly.`);if(!Z.includes("SentrySampler"))g.warn("You have to set up the SentrySampler. Without this, the OpenTelemetry & Sentry integration may still work, but sample rates set for the Sentry SDK will not be respected. If you use a custom sampler, make sure to use `wrapSamplingDecision`.")}function pQ6(Z,J){let X=iQ6(Z.release),Y=Z.spotlight??XP(process.env.SENTRY_SPOTLIGHT,{strict:!0})??process.env.SENTRY_SPOTLIGHT,$=nQ6(Z.tracesSampleRate),Q={...Z,dsn:Z.dsn??process.env.SENTRY_DSN,environment:Z.environment??process.env.SENTRY_ENVIRONMENT,sendClientReports:Z.sendClientReports??!0,transport:Z.transport??JP,stackParser:UA(Z.stackParser||QP),release:X,tracesSampleRate:$,spotlight:Y,debug:XP(Z.debug??process.env.SENTRY_DEBUG)},K=Z.integrations,G=Z.defaultIntegrations??J(Q);return{...Q,integrations:nA({defaultIntegrations:G,integrations:K})}}function iQ6(Z){if(Z!==void 0)return Z;let J=$P();if(J!==void 0)return J;return}function nQ6(Z){if(Z!==void 0)return Z;let J=process.env.SENTRY_TRACES_SAMPLE_RATE;if(!J)return;let X=parseFloat(J);return isFinite(X)?X:void 0}function aQ6(){if(XP(process.env.SENTRY_USE_ENVIRONMENT)!==!1){let Z=process.env.SENTRY_TRACE,J=process.env.SENTRY_BAGGAGE,X=QQ(Z,J);l0().setPropagationContext(X)}}var sQ6=[["january","1"],["february","2"],["march","3"],["april","4"],["may","5"],["june","6"],["july","7"],["august","8"],["september","9"],["october","10"],["november","11"],["december","12"],["jan","1"],["feb","2"],["mar","3"],["apr","4"],["may","5"],["jun","6"],["jul","7"],["aug","8"],["sep","9"],["oct","10"],["nov","11"],["dec","12"],["sunday","0"],["monday","1"],["tuesday","2"],["wednesday","3"],["thursday","4"],["friday","5"],["saturday","6"],["sun","0"],["mon","1"],["tue","2"],["wed","3"],["thu","4"],["fri","5"],["sat","6"]];function XK(Z){return sQ6.reduce((J,[X,Y])=>J.replace(new RegExp(X,"gi"),Y),Z)}var P31="Automatic instrumentation of CronJob only supports crontab string";function D31(Z,J){let X=!1;return new Proxy(Z,{construct(Y,$){let[Q,K,G,W,H,...V]=$;if(typeof Q!=="string")throw new Error(P31);if(X)throw new Error(`A job named '${J}' has already been scheduled`);X=!0;let F=XK(Q);async function z(q,U){return o7(J,async()=>{try{await K(q,U)}catch(B){throw F1(B),B}},{schedule:{type:"crontab",value:F},timezone:H||void 0})}return new Y(Q,z,G,W,H,...V)},get(Y,$){if($==="from")return(Q)=>{let{cronTime:K,onTick:G,timeZone:W}=Q;if(typeof K!=="string")throw new Error(P31);if(X)throw new Error(`A job named '${J}' has already been scheduled`);X=!0;let H=XK(K);return Q.onTick=async(V,F)=>{return o7(J,async()=>{try{await G(V,F)}catch(z){throw F1(z),z}},{schedule:{type:"crontab",value:H},timezone:W||void 0})},Y.from(Q)};else return Y[$]}})}function C31(Z){return new Proxy(Z,{get(J,X){if(X==="schedule"&&J.schedule)return new Proxy(J.schedule,{apply(Y,$,Q){let[K,G,W]=Q,H=W?.name,V=W?.timezone;if(!H)throw new Error('Missing "name" for scheduled job. A name is required for Sentry check-in monitoring.');let F=async()=>{return o7(H,async()=>{try{return await G()}catch(z){throw F1(z),z}},{schedule:{type:"crontab",value:XK(K)},timezone:V})};return Y.apply($,[K,F,W])}});else return J[X]}})}function T31(Z){return new Proxy(Z,{get(J,X){if(X==="scheduleJob")return new Proxy(J.scheduleJob,{apply(Y,$,Q){let[K,G,W]=Q;if(typeof K!=="string"||typeof G!=="string"||typeof W!=="function")throw new Error("Automatic instrumentation of 'node-schedule' requires the first parameter of 'scheduleJob' to be a job name string and the second parameter to be a crontab string");let H=K,V=G;async function F(){return o7(H,async()=>{await W?.()},{schedule:{type:"crontab",value:XK(V)}})}return Y.apply($,[H,V,F])}});return J[X]}})}var E31={instrumentCron:D31,instrumentNodeCron:C31,instrumentNodeSchedule:T31};var YK;((L)=>{L.BUILD_PACKETS="build_packets";L.ENTITIES_EMIT_UPDATES="entities_emit_updates";L.ENTITIES_TICK="entities_tick";L.NETWORK_SYNCHRONIZE="network_synchronize";L.NETWORK_SYNCHRONIZE_CLEANUP="network_synchronize_cleanup";L.PHYSICS_CLEANUP="physics_cleanup";L.PHYSICS_STEP="physics_step";L.RELEASE_TICK_ALLOCATION="release_tick_allocation";L.SEND_ALL_PACKETS="send_all_packets";L.SEND_PACKETS="send_packets";L.SERIALIZE_FREE_BUFFERS="serialize_free_buffers";L.SERIALIZE_PACKETS="serialize_packets";L.SERIALIZE_PACKETS_ENCODE="serialize_packets_encode";L.SIMULATION_STEP="simulation_step";L.TICKER_TICK="ticker_tick";L.WORLD_TICK="world_tick"})(YK||={});class r1{static getProcessStats(Z=!1){let J=process.memoryUsage(),X={jsHeapSizeMb:{value:J.heapUsed/1024/1024,unit:"megabyte"},jsHeapCapacityMb:{value:J.heapTotal/1024/1024,unit:"megabyte"},jsHeapUsagePercent:{value:J.heapUsed/J.heapTotal,unit:"percent"},processHeapSizeMb:{value:J.heapUsed/1024/1024,unit:"megabyte"},rssSizeMb:{value:J.rss/1024/1024,unit:"megabyte"}};if(Z)return X;return Object.fromEntries(Object.entries(X).map(([Y,$])=>[Y,$.value]))}static initializeSentry(Z,J=50){GP({dsn:Z,release:av,environment:process.env.NODE_ENV||"development",tracesSampleRate:1,initialScope:{tags:{gameId:process.env.HYTOPIA_GAME_ID??"unknown",gameSlug:process.env.HYTOPIA_GAME_SLUG??"unknown",lobbyId:process.env.HYTOPIA_LOBBY_ID??"unknown",region:process.env.REGION??"unknown"}},beforeSend:(X)=>{return X.extra=r1.getProcessStats(),X},beforeSendTransaction:(X)=>{if(X.contexts?.trace?.op==="ticker_tick"){let $=X?.start_timestamp,Q=X?.timestamp;if(!$||!Q)return null;if((Q-$)*1000>J)return X.measurements=r1.getProcessStats(!0),X}return null}})}static startSpan(Z,J){if(vF())return e9({attributes:Z.attributes,name:Z.operation,op:Z.operation},J);else return J()}static sentry(){return wm}}var k31=new f$,oQ6=5000;class i4 extends O0{static _cachedPacketsSerializedBuffer=new Map;_closeTimeout=null;_wrtcDirectTransport=null;_wrtcClientServerTransport=null;_wrtcClientServerDataProducers=[];_wrtcClientServerDataConsumers=[];_wrtcServerClientTransport=null;_wrtcServerClientReliableDataProducer=null;_wrtcServerClientUnreliableDataProducer=null;_wrtcServerClientDataConsumers=[];_ws;id;constructor(Z,J){super();this.id=w40(),this.onPacket(Y0.PacketId.CONNECTION,this._onConnectionPacket),this.onPacket(Y0.PacketId.HEARTBEAT,this._onHeartbeatPacket),this.bindWs(Z),O0.globalInstance.emit("CONNECTION.OPENED",{connection:this,req:J})}static clearCachedPacketsSerializedBuffers(){if(i4._cachedPacketsSerializedBuffer.size>0)i4._cachedPacketsSerializedBuffer.clear()}static serializePackets(Z){for(let X of Z)if(!Y0.isValidPacket(X))return d.error(`Connection.serializePackets(): Invalid packet payload: ${JSON.stringify(X)}`);let J=i4._cachedPacketsSerializedBuffer.get(Z);if(J)return J;return r1.startSpan({operation:"serialize_packets",attributes:{packets:Z.length,packetIds:Z.map((X)=>X[0]).join(",")}},(X)=>{let Y=r1.startSpan({operation:"serialize_packets_encode"},()=>k31.pack(Z));return X?.setAttribute("serializedBytes",Y.byteLength),i4._cachedPacketsSerializedBuffer.set(Z,Y),Y})}bindWs(Z){let J=!!this._ws;if(J&&this._closeTimeout)clearTimeout(this._closeTimeout),this._closeTimeout=null;if(this._ws)this._ws.onmessage=()=>{},this._ws.onclose=()=>{},this._ws.onerror=()=>{},this.send([Y0.createPacket(Y0.bidirectionalPackets.connectionPacketDefinition,{k:!0})]);if(this._ws=Z,this._ws.binaryType="nodebuffer",this._ws.onmessage=(X)=>this._onMessage(X.data),this._ws.onclose=this._onWsClose,this._ws.onerror=this._onWsError,this.send([Y0.createPacket(Y0.bidirectionalPackets.connectionPacketDefinition,{i:this.id})],!0,!0),J)this.emitWithGlobal("CONNECTION.RECONNECTED",{connection:this});if(a7.instance.isWrtcEnabled)this._upgradeToWRTC()}closeWrtc(){this._closeWrtcClientServerTransport(),this._closeWrtcServerClientTransport()}disconnect(){try{this._ws.close()}catch(Z){d.error(`Connection.disconnect(): Connection disconnect failed. Error: ${Z}`)}}onPacket(Z,J){this.on("CONNECTION.PACKET_RECEIVED",({packet:X})=>{if(X[0]===Z)J(X)})}send(Z,J=!0,X=!1){if(this._closeTimeout)return;if(this._ws.readyState!==U_.default.OPEN)return;r1.startSpan({operation:"send_packets",attributes:{forceWs:X?"true":"false",wrtcConnected:this._wrtcServerClientTransport?.iceState==="completed"?"true":"false"}},()=>{try{let Y=i4.serializePackets(Z);if(!Y)return;if(this._wrtcServerClientTransport?.iceState==="completed"&&Y.length<(this._wrtcServerClientTransport?.sctpParameters?.maxMessageSize??0)&&!X)try{(J?this._wrtcServerClientReliableDataProducer:this._wrtcServerClientUnreliableDataProducer).send(Y)}catch{this._ws.send(Y)}else this._ws.send(Y);this.emitWithGlobal("CONNECTION.PACKETS_SENT",{connection:this,packets:Z})}catch(Y){d.error(`Connection.send(): Packet send failed. Error: ${Y}`)}})}_closeWrtcClientServerTransport(){this._wrtcDirectTransport?.close(),this._wrtcDirectTransport=null,this._wrtcClientServerTransport?.close(),this._wrtcClientServerTransport=null,this._wrtcClientServerDataProducers.forEach((Z)=>Z.close()),this._wrtcClientServerDataProducers=[],this._wrtcClientServerDataConsumers.forEach((Z)=>Z.close()),this._wrtcClientServerDataConsumers=[]}_closeWrtcServerClientTransport(){this._wrtcServerClientTransport?.close(),this._wrtcServerClientTransport=null,this._wrtcServerClientDataConsumers.forEach((Z)=>Z.close()),this._wrtcServerClientDataConsumers=[],this._wrtcServerClientReliableDataProducer?.close(),this._wrtcServerClientReliableDataProducer=null,this._wrtcServerClientUnreliableDataProducer?.close(),this._wrtcServerClientUnreliableDataProducer=null}_onConnectionPacket=async(Z)=>{let J=Z[1],X=J.c,Y=J.d;if(X){let{i:$,d:Q}=X,K=!1;if($==this._wrtcClientServerTransport?.id)await this._wrtcClientServerTransport.connect({dtlsParameters:Q}),K=!0;if($==this._wrtcServerClientTransport?.id)await this._wrtcServerClientTransport.connect({dtlsParameters:Q}),K=!0;if(K)this.send([Y0.createPacket(Y0.bidirectionalPackets.connectionPacketDefinition,{ca:{i:$}})])}if(Y)for(let $ of Y){let{s:Q,l:K}=$,G=await this._wrtcClientServerTransport.produceData({label:K,sctpStreamParameters:Q}),W=await this._wrtcDirectTransport.consumeData({dataProducerId:G.id});this._wrtcClientServerDataProducers.push(G),this._wrtcClientServerDataConsumers.push(W),W.on("message",(H)=>this._onMessage(H)),this.send([Y0.createPacket(Y0.bidirectionalPackets.connectionPacketDefinition,{pa:{i:G.id,l:K}})])}};_onHeartbeatPacket=()=>{this.send([Y0.createPacket(Y0.bidirectionalPackets.heartbeatPacketDefinition,null)],!0,!0)};_onMessage=(Z)=>{try{let J=this._deserialize(Z);if(!J)return;this.emitWithGlobal("CONNECTION.PACKET_RECEIVED",{connection:this,packet:J})}catch(J){d.error(`Connection._ws.onmessage(): Error: ${J}`)}};_onWrtcIceStateChange=(Z,J)=>{if(["disconnected","closed"].includes(J)){if(Z==this._wrtcClientServerTransport)this._closeWrtcClientServerTransport();else if(Z==this._wrtcServerClientTransport)this._closeWrtcServerClientTransport()}};_onWsClose=()=>{this.closeWrtc(),this.emitWithGlobal("CONNECTION.DISCONNECTED",{connection:this}),this._closeTimeout=setTimeout(()=>{this.emitWithGlobal("CONNECTION.CLOSED",{connection:this}),this.offAll()},oQ6)};_onWsError=(Z)=>{this.emitWithGlobal("CONNECTION.ERROR",{connection:this,error:Z})};_upgradeToWRTC=async()=>{let Z=await a7.instance.createWrtcTransports();if(!Z)return!1;let{directTransport:J,clientServerTransport:X,serverClientTransport:Y}=Z;this._wrtcDirectTransport=J,this._wrtcClientServerTransport=X,this._wrtcClientServerTransport.on("icestatechange",(K)=>{this._onWrtcIceStateChange(this._wrtcClientServerTransport,K)}),this._wrtcServerClientTransport=Y,this._wrtcServerClientTransport.on("icestatechange",(K)=>{this._onWrtcIceStateChange(this._wrtcServerClientTransport,K)}),this._wrtcServerClientReliableDataProducer=await this._wrtcServerClientTransport.produceData({label:"scr",sctpStreamParameters:{streamId:0,ordered:!0}}),this._wrtcServerClientUnreliableDataProducer=await this._wrtcServerClientTransport.produceData({label:"scu",sctpStreamParameters:{streamId:1,ordered:!1,maxPacketLifeTime:35}});let $=await this._wrtcServerClientTransport.consumeData({dataProducerId:this._wrtcServerClientReliableDataProducer.id}),Q=await this._wrtcServerClientTransport.consumeData({dataProducerId:this._wrtcServerClientUnreliableDataProducer.id});return this._wrtcServerClientDataConsumers.push($,Q),this.send([Y0.createPacket(Y0.bidirectionalPackets.connectionPacketDefinition,{d:[{i:$.id,pi:$.dataProducerId,l:"scr",s:$.sctpStreamParameters},{i:Q.id,pi:Q.dataProducerId,l:"scu",s:Q.sctpStreamParameters}],t:[{i:this._wrtcClientServerTransport.id,f:"cs",d:this._wrtcClientServerTransport.dtlsParameters,ic:this._wrtcClientServerTransport.iceCandidates,ip:this._wrtcClientServerTransport.iceParameters,s:this._wrtcClientServerTransport.sctpParameters},{i:this._wrtcServerClientTransport.id,f:"sc",d:this._wrtcServerClientTransport.dtlsParameters,ic:this._wrtcServerClientTransport.iceCandidates,ip:this._wrtcServerClientTransport.iceParameters,s:this._wrtcServerClientTransport.sctpParameters}]})]),!0};_deserialize(Z){let J=k31.unpack(Z);if(!J||typeof J!=="object"||typeof J[0]!=="number")return d.error(`Connection._deserialize(): Invalid packet format. Packet: ${JSON.stringify(J)}`);if(!Y0.isValidPacket(J))return d.error(`Connection._deserialize(): Invalid packet payload. Packet: ${JSON.stringify(J)}`);return J}}class WU{_lights=new Map;_nextLightId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}despawnEntityAttachedLights(Z){this.getAllEntityAttachedLights(Z).forEach((J)=>{J.despawn()})}getAllLights(Z=!1){return Z?this._world.tickAllocator.getArray(this._lights.values()):Array.from(this._lights.values())}getAllEntityAttachedLights(Z){return this.getAllLights().filter((J)=>J.attachedToEntity===Z)}registerLight(Z){if(Z.id!==void 0)return Z.id;let J=this._nextLightId;return this._lights.set(J,Z),this._nextLightId++,J}unregisterLight(Z){if(Z.id===void 0)return;this._lights.delete(Z.id)}}class z6{_map=new Map;_values=[];_isDirty=!1;get size(){return this._map.size}get valuesArray(){if(this._isDirty)this._syncArray();return this._values}get(Z){return this._map.get(Z)}set(Z,J){let X=this._map.has(Z);if(this._map.set(Z,J),!X)this._values.push(J);else this._isDirty=!0;return this}has(Z){return this._map.has(Z)}delete(Z){let J=this._map.delete(Z);if(J)this._isDirty=!0;return J}clear(){this._map.clear(),this._values.length=0,this._isDirty=!1}forEach(Z,J){this._map.forEach((X,Y)=>{Z.call(J,X,Y,this)})}keys(){return this._map.keys()}values(){return this._map.values()}entries(){return this._map.entries()}[Symbol.iterator](){return this._map[Symbol.iterator]()}_syncArray(){this._values.length=0;for(let Z of this._map.values())this._values.push(Z);this._isDirty=!1}}var I31;((X)=>{X[X.POINTLIGHT=0]="POINTLIGHT";X[X.SPOTLIGHT=1]="SPOTLIGHT"})(I31||={});var jm;((z)=>{z.DESPAWN="LIGHT.DESPAWN";z.SET_ANGLE="LIGHT.SET_ANGLE";z.SET_ATTACHED_TO_ENTITY="LIGHT.SET_ATTACHED_TO_ENTITY";z.SET_COLOR="LIGHT.SET_COLOR";z.SET_DISTANCE="LIGHT.SET_DISTANCE";z.SET_INTENSITY="LIGHT.SET_INTENSITY";z.SET_OFFSET="LIGHT.SET_OFFSET";z.SET_PENUMBRA="LIGHT.SET_PENUMBRA";z.SET_POSITION="LIGHT.SET_POSITION";z.SET_TRACKED_ENTITY="LIGHT.SET_TRACKED_ENTITY";z.SET_TRACKED_POSITION="LIGHT.SET_TRACKED_POSITION";z.SPAWN="LIGHT.SPAWN"})(jm||={});class Om extends O0{_id;_angle;_attachedToEntity;_color;_distance;_intensity;_offset;_penumbra;_position;_trackedEntity;_trackedPosition;_type;_world;constructor(Z){if(!!Z.attachedToEntity===!!Z.position)d.fatalError("Either attachedToEntity or position must be set, but not both.");super();d.warning("WARNING: Lights are poorly optimized at this time. Using more than a few lights in your game can cause extremely bad performance (FPS) issues. Use lights sparingly!"),this._angle=Z.angle,this._attachedToEntity=Z.attachedToEntity,this._color=Z.color??{r:255,g:255,b:255},this._distance=Z.distance,this._intensity=Z.intensity??1,this._offset=Z.offset,this._penumbra=Z.penumbra,this._position=Z.position,this._trackedEntity=Z.trackedEntity,this._trackedPosition=Z.trackedPosition,this._type=Z.type??0}get id(){return this._id}get angle(){return this._angle}get attachedToEntity(){return this._attachedToEntity}get color(){return this._color}get distance(){return this._distance}get intensity(){return this._intensity}get isSpawned(){return this._id!==void 0}get offset(){return this._offset}get penumbra(){return this._penumbra}get position(){return this._position}get trackedEntity(){return this._trackedEntity}get trackedPosition(){return this._trackedPosition}get type(){return this._type}get world(){return this._world}setAngle(Z){if(this._angle===Z)return;if(this._angle=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ANGLE",{light:this,angle:Z})}setAttachedToEntity(Z){if(!Z.isSpawned)return d.error(`Light.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);if(this._attachedToEntity===Z)return;if(this._attachedToEntity=Z,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ATTACHED_TO_ENTITY",{light:this,entity:Z})}setColor(Z){if(this._color.r===Z.r&&this._color.g===Z.g&&this._color.b===Z.b)return;if(this._color=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_COLOR",{light:this,color:Z})}setDistance(Z){if(this._distance===Z)return;if(this._distance=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_DISTANCE",{light:this,distance:Z})}setIntensity(Z){if(this._intensity===Z)return;if(this._intensity=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_INTENSITY",{light:this,intensity:Z})}setOffset(Z){if(this._offset&&this._offset.x===Z.x&&this._offset.y===Z.y&&this._offset.z===Z.z)return;if(this._offset=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_OFFSET",{light:this,offset:Z})}setPenumbra(Z){if(this._penumbra===Z)return;if(this._penumbra=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_PENUMBRA",{light:this,penumbra:Z})}setPosition(Z){if(this._position&&this._position.x===Z.x&&this._position.y===Z.y&&this._position.z===Z.z)return;if(this._position=Z,this._attachedToEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_POSITION",{light:this,position:Z})}setTrackedEntity(Z){if(!Z.isSpawned)return d.error(`Light.setTrackedEntity(): Entity ${Z.id} is not spawned!`);if(this._trackedEntity===Z)return;if(this._trackedEntity=Z,this._trackedPosition=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_ENTITY",{light:this,entity:Z})}setTrackedPosition(Z){if(this._trackedPosition===Z)return;if(this._trackedPosition=Z,this._trackedEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_POSITION",{light:this,position:Z})}despawn(){if(!this.isSpawned||!this._world)return;this._world.lightManager.unregisterLight(this),this.emitWithWorld(this._world,"LIGHT.DESPAWN",{light:this}),this._id=void 0,this._world=void 0}spawn(Z){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return d.error(`Light.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning Light!`);this._id=Z.lightManager.registerLight(this),this._world=Z,this.emitWithWorld(Z,"LIGHT.SPAWN",{light:this})}serialize(){if(!this._world)d.fatalError("Light.serialize(): Light is not in a world and cannot be serialized!");return P0.serializeLight(this,this._world.tickAllocator)}}var Mm;((A)=>{A.DESPAWN="PARTICLE_EMITTER.DESPAWN";A.SET_ALPHA_TEST="PARTICLE_EMITTER.SET_ALPHA_TEST";A.SET_ATTACHED_TO_ENTITY="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY";A.SET_ATTACHED_TO_ENTITY_NODE_NAME="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME";A.SET_COLOR_END="PARTICLE_EMITTER.SET_COLOR_END";A.SET_COLOR_END_VARIANCE="PARTICLE_EMITTER.SET_COLOR_END_VARIANCE";A.SET_COLOR_START="PARTICLE_EMITTER.SET_COLOR_START";A.SET_COLOR_START_VARIANCE="PARTICLE_EMITTER.SET_COLOR_START_VARIANCE";A.SET_GRAVITY="PARTICLE_EMITTER.SET_GRAVITY";A.SET_LIFETIME="PARTICLE_EMITTER.SET_LIFETIME";A.SET_LIFETIME_VARIANCE="PARTICLE_EMITTER.SET_LIFETIME_VARIANCE";A.SET_MAX_PARTICLES="PARTICLE_EMITTER.SET_MAX_PARTICLES";A.SET_OFFSET="PARTICLE_EMITTER.SET_OFFSET";A.SET_OPACITY_END="PARTICLE_EMITTER.SET_OPACITY_END";A.SET_OPACITY_END_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE";A.SET_OPACITY_START="PARTICLE_EMITTER.SET_OPACITY_START";A.SET_OPACITY_START_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE";A.SET_PAUSED="PARTICLE_EMITTER.SET_PAUSED";A.SET_POSITION="PARTICLE_EMITTER.SET_POSITION";A.SET_POSITION_VARIANCE="PARTICLE_EMITTER.SET_POSITION_VARIANCE";A.SET_RATE="PARTICLE_EMITTER.SET_RATE";A.SET_RATE_VARIANCE="PARTICLE_EMITTER.SET_RATE_VARIANCE";A.SET_SIZE_END="PARTICLE_EMITTER.SET_SIZE_END";A.SET_SIZE_END_VARIANCE="PARTICLE_EMITTER.SET_SIZE_END_VARIANCE";A.SET_SIZE_START="PARTICLE_EMITTER.SET_SIZE_START";A.SET_SIZE_START_VARIANCE="PARTICLE_EMITTER.SET_SIZE_START_VARIANCE";A.SET_TEXTURE_URI="PARTICLE_EMITTER.SET_TEXTURE_URI";A.SET_TRANSPARENT="PARTICLE_EMITTER.SET_TRANSPARENT";A.SET_VELOCITY="PARTICLE_EMITTER.SET_VELOCITY";A.SET_VELOCITY_VARIANCE="PARTICLE_EMITTER.SET_VELOCITY_VARIANCE";A.SPAWN="PARTICLE_EMITTER.SPAWN"})(Mm||={});class Rm extends O0{_id;_alphaTest;_attachedToEntity;_attachedToEntityNodeName;_colorEnd;_colorEndVariance;_colorStart;_colorStartVariance;_gravity;_lifetime;_lifetimeVariance;_maxParticles;_offset;_opacityEnd;_opacityEndVariance;_opacityStart;_opacityStartVariance;_paused;_position;_positionVariance;_rate;_rateVariance;_sizeEnd;_sizeEndVariance;_sizeStart;_sizeStartVariance;_sizeVariance;_textureUri;_transparent;_velocity;_velocityVariance;_world;constructor(Z){if(!!Z.attachedToEntity===!!Z.position)d.fatalError("Either attachedToEntity or position must be set, but not both.");if(!Z.textureUri)d.fatalError("ParticleEmitter.constructor(): textureUri must be provided.");super();this._alphaTest=Z.alphaTest??0.5,this._attachedToEntity=Z.attachedToEntity,this._attachedToEntityNodeName=Z.attachedToEntityNodeName,this._colorEnd=Z.colorEnd,this._colorEndVariance=Z.colorEndVariance,this._colorStart=Z.colorStart,this._colorStartVariance=Z.colorStartVariance,this._gravity=Z.gravity,this._lifetime=Z.lifetime,this._lifetimeVariance=Z.lifetimeVariance,this._maxParticles=Z.maxParticles,this._offset=Z.offset,this._opacityEnd=Z.opacityEnd,this._opacityEndVariance=Z.opacityEndVariance,this._opacityStart=Z.opacityStart,this._opacityStartVariance=Z.opacityStartVariance,this._paused=!1,this._position=Z.position,this._positionVariance=Z.positionVariance,this._rate=Z.rate,this._rateVariance=Z.rateVariance,this._sizeEnd=Z.sizeEnd,this._sizeEndVariance=Z.sizeEndVariance,this._sizeStart=Z.sizeStart,this._sizeStartVariance=Z.sizeStartVariance,this._textureUri=Z.textureUri,this._transparent=Z.transparent,this._velocity=Z.velocity,this._velocityVariance=Z.velocityVariance}get id(){return this._id}get alphaTest(){return this._alphaTest}get attachedToEntity(){return this._attachedToEntity}get attachedToEntityNodeName(){return this._attachedToEntityNodeName}get colorEnd(){return this._colorEnd}get colorEndVariance(){return this._colorEndVariance}get colorStart(){return this._colorStart}get colorStartVariance(){return this._colorStartVariance}get gravity(){return this._gravity}get isSpawned(){return this._id!==void 0}get lifetime(){return this._lifetime}get lifetimeVariance(){return this._lifetimeVariance}get maxParticles(){return this._maxParticles}get offset(){return this._offset}get opacityEnd(){return this._opacityEnd}get opacityEndVariance(){return this._opacityEndVariance}get opacityStart(){return this._opacityStart}get opacityStartVariance(){return this._opacityStartVariance}get paused(){return this._paused}get position(){return this._position}get positionVariance(){return this._positionVariance}get rate(){return this._rate}get rateVariance(){return this._rateVariance}get sizeEnd(){return this._sizeEnd}get sizeEndVariance(){return this._sizeEndVariance}get sizeStart(){return this._sizeStart}get sizeStartVariance(){return this._sizeStartVariance}get sizeVariance(){return this._sizeVariance}get textureUri(){return this._textureUri}get transparent(){return this._transparent}get velocity(){return this._velocity}get velocityVariance(){return this._velocityVariance}get world(){return this._world}setAlphaTest(Z){if(this._alphaTest===Z)return;if(this._alphaTest=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ALPHA_TEST",{particleEmitter:this,alphaTest:Z})}setAttachedToEntity(Z){if(!Z.isSpawned)return d.error(`ParticleEmitter.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);if(this._attachedToEntity===Z)return;if(this._attachedToEntity=Z,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY",{particleEmitter:this,entity:Z})}setAttachedToEntityNodeName(Z){if(this._attachedToEntityNodeName===Z)return;if(this._attachedToEntityNodeName=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME",{particleEmitter:this,attachedToEntityNodeName:Z})}setColorEnd(Z){if(this._colorEnd&&this._colorEnd.r===Z.r&&this._colorEnd.g===Z.g&&this._colorEnd.b===Z.b)return;if(this._colorEnd=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_END",{particleEmitter:this,colorEnd:Z})}setColorEndVariance(Z){if(this._colorEndVariance&&this._colorEndVariance.r===Z.r&&this._colorEndVariance.g===Z.g&&this._colorEndVariance.b===Z.b)return;if(this._colorEndVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_END_VARIANCE",{particleEmitter:this,colorEndVariance:Z})}setColorStart(Z){if(this._colorStart&&this._colorStart.r===Z.r&&this._colorStart.g===Z.g&&this._colorStart.b===Z.b)return;if(this._colorStart=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_START",{particleEmitter:this,colorStart:Z})}setColorStartVariance(Z){if(this._colorStartVariance&&this._colorStartVariance.r===Z.r&&this._colorStartVariance.g===Z.g&&this._colorStartVariance.b===Z.b)return;if(this._colorStartVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_START_VARIANCE",{particleEmitter:this,colorStartVariance:Z})}setGravity(Z){if(this._gravity&&this._gravity.x===Z.x&&this._gravity.y===Z.y&&this._gravity.z===Z.z)return;if(this._gravity=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_GRAVITY",{particleEmitter:this,gravity:Z})}setLifetime(Z){if(this._lifetime===Z)return;if(this._lifetime=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_LIFETIME",{particleEmitter:this,lifetime:Z})}setLifetimeVariance(Z){if(this._lifetimeVariance===Z)return;if(this._lifetimeVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_LIFETIME_VARIANCE",{particleEmitter:this,lifetimeVariance:Z})}setMaxParticles(Z){if(this._maxParticles===Z)return;if(this._maxParticles=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_MAX_PARTICLES",{particleEmitter:this,maxParticles:Z})}setOffset(Z){if(this._offset&&this._offset.x===Z.x&&this._offset.y===Z.y&&this._offset.z===Z.z)return;if(this._offset=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OFFSET",{particleEmitter:this,offset:Z})}setOpacityEnd(Z){if(this._opacityEnd===Z)return;if(this._opacityEnd=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_END",{particleEmitter:this,opacityEnd:Z})}setOpacityEndVariance(Z){if(this._opacityEndVariance===Z)return;if(this._opacityEndVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE",{particleEmitter:this,opacityEndVariance:Z})}setOpacityStart(Z){if(this._opacityStart===Z)return;if(this._opacityStart=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_START",{particleEmitter:this,opacityStart:Z})}setOpacityStartVariance(Z){if(this._opacityStartVariance===Z)return;if(this._opacityStartVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE",{particleEmitter:this,opacityStartVariance:Z})}setPosition(Z){if(this._position&&this._position.x===Z.x&&this._position.y===Z.y&&this._position.z===Z.z)return;if(this._position=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_POSITION",{particleEmitter:this,position:Z})}setPositionVariance(Z){if(this._positionVariance&&this._positionVariance.x===Z.x&&this._positionVariance.y===Z.y&&this._positionVariance.z===Z.z)return;if(this._positionVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_POSITION_VARIANCE",{particleEmitter:this,positionVariance:Z})}setRate(Z){if(this._rate===Z)return;if(this._rate=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_RATE",{particleEmitter:this,rate:Z})}setRateVariance(Z){if(this._rateVariance===Z)return;if(this._rateVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_RATE_VARIANCE",{particleEmitter:this,rateVariance:Z})}setSizeEnd(Z){if(this._sizeEnd===Z)return;if(this._sizeEnd=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_END",{particleEmitter:this,sizeEnd:Z})}setSizeEndVariance(Z){if(this._sizeEndVariance===Z)return;if(this._sizeEndVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_END_VARIANCE",{particleEmitter:this,sizeEndVariance:Z})}setSizeStart(Z){if(this._sizeStart===Z)return;if(this._sizeStart=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_START",{particleEmitter:this,sizeStart:Z})}setSizeStartVariance(Z){if(this._sizeStartVariance===Z)return;if(this._sizeStartVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_START_VARIANCE",{particleEmitter:this,sizeStartVariance:Z})}setTextureUri(Z){if(this._textureUri===Z)return;if(this._textureUri=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_TEXTURE_URI",{particleEmitter:this,textureUri:Z})}setTransparent(Z){if(this._transparent===Z)return;if(this._transparent=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_TRANSPARENT",{particleEmitter:this,transparent:Z})}setVelocity(Z){if(this._velocity&&this._velocity.x===Z.x&&this._velocity.y===Z.y&&this._velocity.z===Z.z)return;if(this._velocity=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_VELOCITY",{particleEmitter:this,velocity:Z})}setVelocityVariance(Z){if(this._velocityVariance&&this._velocityVariance.x===Z.x&&this._velocityVariance.y===Z.y&&this._velocityVariance.z===Z.z)return;if(this._velocityVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_VELOCITY_VARIANCE",{particleEmitter:this,velocityVariance:Z})}despawn(){if(!this.isSpawned||!this._world)return;this._world.particleEmitterManager.unregisterParticleEmitter(this),this.emitWithWorld(this._world,"PARTICLE_EMITTER.DESPAWN",{particleEmitter:this}),this._id=void 0,this._world=void 0}restart(){if(!this._paused)return;if(this._paused=!1,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_PAUSED",{particleEmitter:this,paused:this._paused})}stop(){if(this._paused)return;if(this._paused=!0,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_PAUSED",{particleEmitter:this,paused:this._paused})}spawn(Z){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return d.error(`ParticleEmitter.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning ParticleEmitter!`);this._id=Z.particleEmitterManager.registerParticleEmitter(this),this._world=Z,this.emitWithWorld(Z,"PARTICLE_EMITTER.SPAWN",{particleEmitter:this})}serialize(){if(!this._world)d.fatalError("ParticleEmitter.serialize(): ParticleEmitter is not in a world and cannot be serialized!");return P0.serializeParticleEmitter(this,this._world.tickAllocator)}}var HU=r(KH(),1);var rQ6={x:0,y:-32,z:0},Nm=60,Pm;(($)=>{$.STEP_START="SIMULATION.STEP_START";$.STEP_END="SIMULATION.STEP_END";$.DEBUG_RAYCAST="SIMULATION.DEBUG_RAYCAST";$.DEBUG_RENDER="SIMULATION.DEBUG_RENDER"})(Pm||={});class VU extends O0{_colliderMap=new oV;_debugRaycastingEnabled=!1;_debugRenderingEnabled=!1;_debugRenderingFilterFlags;_rapierEventQueue;_rapierSimulation;_world;constructor(Z,J=Nm,X=rQ6){super();this._rapierEventQueue=new HU.default.EventQueue(!0),this._rapierSimulation=new HU.default.World(X),this._rapierSimulation.timestep=Math.fround(1/J),this._world=Z}get colliderMap(){return this._colliderMap}get isDebugRaycastingEnabled(){return this._debugRaycastingEnabled}get isDebugRenderingEnabled(){return this._debugRenderingEnabled}get gravity(){return this._rapierSimulation.gravity}get timestepS(){return this._rapierSimulation.timestep}get world(){return this._world}createRawCollider(Z,J){return this._rapierSimulation.createCollider(Z,J)}createRawRigidBody(Z){return this._rapierSimulation.createRigidBody(Z)}enableDebugRaycasting(Z){this._debugRaycastingEnabled=Z}enableDebugRendering(Z,J=HU.default.QueryFilterFlags.EXCLUDE_FIXED){this._debugRenderingEnabled=Z,this._debugRenderingFilterFlags=J}getContactManifolds(Z,J){let X=[];return this._rapierSimulation.narrowPhase.contactPair(Z,J,(Y,$)=>{if(Y.numContacts()===0)return;let Q=Y.normal(),K=[];for(let G=0;G<Y.numSolverContacts();G++)K.push(Y.solverContactPoint(G));X.push({contactPoints:K,localNormalA:!$?Y.localNormal1():Y.localNormal2(),localNormalB:!$?Y.localNormal2():Y.localNormal1(),normal:!$?Q:{x:-Q.x,y:-Q.y,z:-Q.z}})}),X}intersectionsWithRawShape(Z,J,X,Y={}){let $=new Set,Q=[];return this._rapierSimulation.intersectionsWithShape(J,X,Z,(K)=>{let G=this._colliderMap.getColliderHandleBlockType(K.handle);if(G&&!$.has(G))return $.add(G),Q.push({intersectedBlockType:G}),!0;let W=this._colliderMap.getColliderHandleEntity(K.handle);if(W&&!$.has(W))return $.add(W),Q.push({intersectedEntity:W}),!0;return!0},Y.filterFlags,Y.filterGroups,Y.filterExcludeCollider,Y.filterExcludeRigidBody,Y.filterPredicate),Q}raycast(Z,J,X,Y={}){let $=new HU.default.Ray(Z,J),Q=this._rapierSimulation.castRay($,X,Y.solidMode??!0,Y.filterFlags,Y.filterGroups,Y.filterExcludeCollider,Y.filterExcludeRigidBody,Y.filterPredicate);if(this._debugRaycastingEnabled)this.emitWithWorld(this._world,"SIMULATION.DEBUG_RAYCAST",{simulation:this,origin:Z,direction:J,length:X,hit:!!Q});if(!Q)return null;let K=$.pointAt(Q.timeOfImpact),G=Q.timeOfImpact,W=Q.collider,H=this._colliderMap.getColliderHandleBlockType(W.handle);if(H)return{hitBlock:FK.fromGlobalCoordinate({x:Math.floor(K.x-($.dir.x<0?0.0001:-0.0001)),y:Math.floor(K.y-($.dir.y<0?0.0001:-0.0001)),z:Math.floor(K.z-($.dir.z<0?0.0001:-0.0001))},H),hitPoint:K,hitDistance:G};let V=this._colliderMap.getColliderHandleEntity(W.handle);if(V)return{hitEntity:V,hitPoint:K,hitDistance:G};return null}removeRawCollider(Z){this._colliderMap.queueColliderHandleForCleanup(Z.handle),this._rapierSimulation.removeCollider(Z,!1)}removeRawRigidBody(Z){this._rapierSimulation.removeRigidBody(Z)}setGravity(Z){this._rapierSimulation.gravity=Z}step=(Z)=>{this.emitWithWorld(this._world,"SIMULATION.STEP_START",{simulation:this,tickDeltaMs:Z});let J=performance.now();if(r1.startSpan({operation:"physics_step"},()=>{this._rapierSimulation.step(this._rapierEventQueue)}),r1.startSpan({operation:"physics_cleanup"},()=>{this._rapierEventQueue.drainContactForceEvents(this._onContactForceEvent),this._rapierEventQueue.drainCollisionEvents(this._onCollisionEvent),this._colliderMap.cleanup()}),this.emitWithWorld(this._world,"SIMULATION.STEP_END",{simulation:this,stepDurationMs:performance.now()-J}),this._debugRenderingEnabled)this.emitWithWorld(this._world,"SIMULATION.DEBUG_RENDER",{simulation:this,...this._rapierSimulation.debugRender(this._debugRenderingFilterFlags)})};_onCollisionEvent=(Z,J,X)=>{let[Y,$]=this._getCollisionObjects(Z,J);if(!Y||!$)return;let Q=(K,G)=>{if(K instanceof K9&&G instanceof i8&&K.hasListeners("BLOCK_TYPE.ENTITY_COLLISION"))K.emit("BLOCK_TYPE.ENTITY_COLLISION",{blockType:K,entity:G,started:X,colliderHandleA:Z,colliderHandleB:J});else if(K instanceof i8&&G instanceof K9&&K.hasListeners("ENTITY.BLOCK_COLLISION"))K.emit("ENTITY.BLOCK_COLLISION",{entity:K,blockType:G,started:X,colliderHandleA:Z,colliderHandleB:J});else if(K instanceof i8&&G instanceof i8&&K.hasListeners("ENTITY.ENTITY_COLLISION"))K.emit("ENTITY.ENTITY_COLLISION",{entity:K,otherEntity:G,started:X,colliderHandleA:Z,colliderHandleB:J});else if(typeof K==="function"&&(G instanceof i8||G instanceof K9))K(G,X,Z,J)};Q(Y,$),Q($,Y)};_onContactForceEvent=(Z)=>{let[J,X]=this._getCollisionObjects(Z.collider1(),Z.collider2());if(!J||typeof J==="function"||!X||typeof X==="function")return;let Y={totalForce:Z.totalForce(),totalForceMagnitude:Z.totalForceMagnitude(),maxForceDirection:Z.maxForceDirection(),maxForceMagnitude:Z.maxForceMagnitude()},$=(Q,K)=>{if(Q instanceof K9&&K instanceof i8&&Q.hasListeners("BLOCK_TYPE.ENTITY_CONTACT_FORCE"))Q.emit("BLOCK_TYPE.ENTITY_CONTACT_FORCE",{blockType:Q,entity:K,contactForceData:Y});else if(Q instanceof i8&&K instanceof K9&&Q.hasListeners("ENTITY.BLOCK_CONTACT_FORCE"))Q.emit("ENTITY.BLOCK_CONTACT_FORCE",{entity:Q,blockType:K,contactForceData:Y});else if(Q instanceof i8&&K instanceof i8&&Q.hasListeners("ENTITY.ENTITY_CONTACT_FORCE"))Q.emit("ENTITY.ENTITY_CONTACT_FORCE",{entity:Q,otherEntity:K,contactForceData:Y})};$(J,X),$(X,J)};_getCollisionObjects(Z,J){let X=this._colliderMap.getColliderHandleBlockType(Z)??this._colliderMap.getColliderHandleCollisionCallback(Z)??this._colliderMap.getColliderHandleEntity(Z),Y=this._colliderMap.getColliderHandleBlockType(J)??this._colliderMap.getColliderHandleCollisionCallback(J)??this._colliderMap.getColliderHandleEntity(J);return[X,Y]}}class WP{_synchronizedPlayerReliablePackets=new z6;_queuedBroadcasts=[];_queuedAudioSynchronizations=new z6;_queuedBlockSynchronizations=new z6;_queuedBlockTypeSynchronizations=new z6;_queuedChunkSynchronizations=new z6;_queuedDebugRaycastSynchronizations=[];_queuedEntitySynchronizations=new z6;_queuedLightSynchronizations=new z6;_queuedParticleEmitterSynchronizations=new z6;_queuedPerPlayerSynchronizations=new z6;_queuedPerPlayerCameraSynchronizations=new z6;_queuedPerPlayerUISynchronizations=new z6;_queuedPerPlayerUIDatasSynchronizations=new z6;_queuedPlayerSynchronizations=new z6;_queuedSceneUISynchronizations=new z6;_queuedWorldSynchronization;_loadedSceneUIs=new Set;_spawnedChunks=new Set;_spawnedEntities=new Set;_world;constructor(Z){this._world=Z,this._subscribeToAudioEvents(),this._subscribeToBlockTypeRegistryEvents(),this._subscribeToChatEvents(),this._subscribeToChunkLatticeEvents(),this._subscribeToEntityEvents(),this._subscribeToLightEvents(),this._subscribeToParticleEmitterEvents(),this._subscribeToPlayerEvents(),this._subscribeToPlayerCameraEvents(),this._subscribeToPlayerUIEvents(),this._subscribeToSceneUIEvents(),this._subscribeToSimulationEvents(),this._subscribeToWorldEvents()}synchronize(){let Z=this._world.tickAllocator,J=this._world.tickAllocator.getArray(),X=this._world.tickAllocator.getArray(),Y=this._world.loop.currentTick;if(this._queuedPerPlayerSynchronizations.size>0)for(let[$,Q]of this._queuedPerPlayerSynchronizations)this._createOrGetSynchronizedPlayerReliablePackets($,J).push(...Q);if(this._queuedEntitySynchronizations.size>0){let $=this._world.tickAllocator.getArray(),Q=this._world.tickAllocator.getArray();for(let K of this._queuedEntitySynchronizations.valuesArray){let G=!1;for(let W in K)if(W!=="i"&&W!=="p"&&W!=="r"){G=!0;break}if(G)$.push(K);else Q.push(K)}if(Q.length>0){let K=Y0.createPacket(Y0.outboundPackets.entitiesPacketDefinition,Q,Y,Z.getArray());X.push(K)}if($.length>0){let K=Y0.createPacket(Y0.outboundPackets.entitiesPacketDefinition,$,Y,Z.getArray());J.push(K);for(let G of this._synchronizedPlayerReliablePackets.valuesArray)G.push(K)}}if(this._queuedAudioSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.audiosPacketDefinition,this._queuedAudioSynchronizations.valuesArray,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedBlockTypeSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.blockTypesPacketDefinition,this._queuedBlockTypeSynchronizations.valuesArray,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedBlockSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.blocksPacketDefinition,this._queuedBlockSynchronizations.valuesArray,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedChunkSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.chunksPacketDefinition,this._queuedChunkSynchronizations.valuesArray,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedLightSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.lightsPacketDefinition,this._queuedLightSynchronizations.valuesArray,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedParticleEmitterSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.particleEmittersPacketDefinition,this._queuedParticleEmitterSynchronizations.valuesArray,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedPerPlayerUISynchronizations.size>0)for(let[$,Q]of this._queuedPerPlayerUISynchronizations){let K=Y0.createPacket(Y0.outboundPackets.uiPacketDefinition,Q,Y,Z.getArray());this._createOrGetSynchronizedPlayerReliablePackets($,J).push(K)}if(this._queuedPerPlayerUIDatasSynchronizations.size>0)for(let[$,Q]of this._queuedPerPlayerUIDatasSynchronizations){let K=Y0.createPacket(Y0.outboundPackets.uiDatasPacketDefinition,Q,Y,Z.getArray());this._createOrGetSynchronizedPlayerReliablePackets($,J).push(K)}if(this._queuedSceneUISynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.sceneUIsPacketDefinition,this._queuedSceneUISynchronizations.valuesArray,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedWorldSynchronization){let $=Y0.createPacket(Y0.outboundPackets.worldPacketDefinition,this._queuedWorldSynchronization,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedPerPlayerCameraSynchronizations.size>0)for(let[$,Q]of this._queuedPerPlayerCameraSynchronizations){let K=Y0.createPacket(Y0.outboundPackets.cameraPacketDefinition,Q,Y,Z.getArray());this._createOrGetSynchronizedPlayerReliablePackets($,J).push(K)}if(this._queuedPlayerSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.playersPacketDefinition,this._queuedPlayerSynchronizations.valuesArray,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedBroadcasts.length>0)for(let $ of this._queuedBroadcasts){J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedDebugRaycastSynchronizations.length>0){let $=Y0.createPacket(Y0.outboundPackets.physicsDebugRaycastsPacketDefinition,this._queuedDebugRaycastSynchronizations,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}r1.startSpan({operation:"send_all_packets"},()=>{for(let $ of q9.instance.getConnectedPlayersByWorld(this._world)){let Q=this._synchronizedPlayerReliablePackets.get($)??J;if(Q.length>0)$.connection.send(Q);if(X.length>0)$.connection.send(X,!1)}}),r1.startSpan({operation:"network_synchronize_cleanup"},()=>{if(this._queuedBroadcasts.length>0)this._queuedBroadcasts.length=0;if(this._queuedAudioSynchronizations.size>0)this._queuedAudioSynchronizations.clear();if(this._queuedBlockSynchronizations.size>0)this._queuedBlockSynchronizations.clear();if(this._queuedBlockTypeSynchronizations.size>0)this._queuedBlockTypeSynchronizations.clear();if(this._queuedChunkSynchronizations.size>0)this._queuedChunkSynchronizations.clear();if(this._queuedDebugRaycastSynchronizations.length>0)this._queuedDebugRaycastSynchronizations.length=0;if(this._queuedEntitySynchronizations.size>0)this._queuedEntitySynchronizations.clear();if(this._queuedLightSynchronizations.size>0)this._queuedLightSynchronizations.clear();if(this._queuedParticleEmitterSynchronizations.size>0)this._queuedParticleEmitterSynchronizations.clear();if(this._queuedPerPlayerSynchronizations.size>0)this._queuedPerPlayerSynchronizations.clear();if(this._queuedPerPlayerCameraSynchronizations.size>0)this._queuedPerPlayerCameraSynchronizations.clear();if(this._queuedPerPlayerUISynchronizations.size>0)this._queuedPerPlayerUISynchronizations.clear();if(this._queuedPerPlayerUIDatasSynchronizations.size>0)this._queuedPerPlayerUIDatasSynchronizations.clear();if(this._queuedPlayerSynchronizations.size>0)this._queuedPlayerSynchronizations.clear();if(this._queuedSceneUISynchronizations.size>0)this._queuedSceneUISynchronizations.clear();if(this._queuedWorldSynchronization)this._queuedWorldSynchronization=void 0;if(this._loadedSceneUIs.size>0)this._loadedSceneUIs.clear();if(this._spawnedChunks.size>0)this._spawnedChunks.clear();if(this._spawnedEntities.size>0)this._spawnedEntities.clear();if(this._synchronizedPlayerReliablePackets.size>0)this._synchronizedPlayerReliablePackets.clear();i4.clearCachedPacketsSerializedBuffers()})}_subscribeToAudioEvents(){this._world.final("AUDIO.PAUSE",this._onAudioPause),this._world.final("AUDIO.PLAY",this._onAudioPlay),this._world.final("AUDIO.PLAY_RESTART",this._onAudioPlayRestart),this._world.final("AUDIO.SET_ATTACHED_TO_ENTITY",this._onAudioSetAttachedToEntity),this._world.final("AUDIO.SET_CUTOFF_DISTANCE",this._onAudioSetCutoffDistance),this._world.final("AUDIO.SET_DETUNE",this._onAudioSetDetune),this._world.final("AUDIO.SET_DISTORTION",this._onAudioSetDistortion),this._world.final("AUDIO.SET_POSITION",this._onAudioSetPosition),this._world.final("AUDIO.SET_PLAYBACK_RATE",this._onAudioSetPlaybackRate),this._world.final("AUDIO.SET_REFERENCE_DISTANCE",this._onAudioSetReferenceDistance),this._world.final("AUDIO.SET_VOLUME",this._onAudioSetVolume)}_subscribeToBlockTypeRegistryEvents(){this._world.final("BLOCK_TYPE_REGISTRY.REGISTER_BLOCK_TYPE",this._onBlockTypeRegistryRegisterBlockType)}_subscribeToChatEvents(){this._world.final("CHAT.BROADCAST_MESSAGE",this._onChatSendBroadcastMessage),this._world.final("CHAT.PLAYER_MESSAGE",this._onChatSendPlayerMessage)}_subscribeToChunkLatticeEvents(){this._world.final("CHUNK_LATTICE.REMOVE_CHUNK",this._onChunkLatticeRemoveChunk),this._world.final("CHUNK_LATTICE.SET_BLOCK",this._onChunkLatticeSetBlock)}_subscribeToEntityEvents(){this._world.final("ENTITY.SPAWN",this._onEntitySpawn),this._world.final("ENTITY.DESPAWN",this._onEntityDespawn),this._world.final("ENTITY.SET_MODEL_ANIMATIONS_PLAYBACK_RATE",this._onEntitySetModelAnimationsPlaybackRate),this._world.final("ENTITY.SET_MODEL_HIDDEN_NODES",this._onEntitySetModelHiddenNodes),this._world.final("ENTITY.SET_MODEL_SCALE",this._onEntitySetModelScale),this._world.final("ENTITY.SET_MODEL_SHOWN_NODES",this._onEntitySetModelShownNodes),this._world.final("ENTITY.SET_MODEL_TEXTURE_URI",this._onEntitySetModelTextureUri),this._world.final("ENTITY.SET_OPACITY",this._onEntitySetOpacity),this._world.final("ENTITY.SET_PARENT",this._onEntitySetParent),this._world.final("ENTITY.SET_TINT_COLOR",this._onEntitySetTintColor),this._world.final("ENTITY.START_MODEL_LOOPED_ANIMATIONS",this._onEntityStartModelLoopedAnimations),this._world.final("ENTITY.START_MODEL_ONESHOT_ANIMATIONS",this._onEntityStartModelOneshotAnimations),this._world.final("ENTITY.STOP_MODEL_ANIMATIONS",this._onEntityStopModelAnimations),this._world.final("ENTITY.UPDATE_POSITION",this._onEntityUpdatePosition),this._world.final("ENTITY.UPDATE_ROTATION",this._onEntityUpdateRotation)}_subscribeToLightEvents(){this._world.final("LIGHT.DESPAWN",this._onLightDespawn),this._world.final("LIGHT.SET_ANGLE",this._onLightSetAngle),this._world.final("LIGHT.SET_ATTACHED_TO_ENTITY",this._onLightSetAttachedToEntity),this._world.final("LIGHT.SET_COLOR",this._onLightSetColor),this._world.final("LIGHT.SET_DISTANCE",this._onLightSetDistance),this._world.final("LIGHT.SET_INTENSITY",this._onLightSetIntensity),this._world.final("LIGHT.SET_OFFSET",this._onLightSetOffset),this._world.final("LIGHT.SET_PENUMBRA",this._onLightSetPenumbra),this._world.final("LIGHT.SET_POSITION",this._onLightSetPosition),this._world.final("LIGHT.SET_TRACKED_ENTITY",this._onLightSetTrackedEntity),this._world.final("LIGHT.SET_TRACKED_POSITION",this._onLightSetTrackedPosition),this._world.final("LIGHT.SPAWN",this._onLightSpawn)}_subscribeToParticleEmitterEvents(){this._world.final("PARTICLE_EMITTER.DESPAWN",this._onParticleEmitterDespawn),this._world.final("PARTICLE_EMITTER.SET_ALPHA_TEST",this._onParticleEmitterSetAlphaTest),this._world.final("PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY",this._onParticleEmitterSetAttachedToEntity),this._world.final("PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME",this._onParticleEmitterSetAttachedToEntityNodeName),this._world.final("PARTICLE_EMITTER.SET_COLOR_END",this._onParticleEmitterSetColorEnd),this._world.final("PARTICLE_EMITTER.SET_COLOR_END_VARIANCE",this._onParticleEmitterSetColorEndVariance),this._world.final("PARTICLE_EMITTER.SET_COLOR_START",this._onParticleEmitterSetColorStart),this._world.final("PARTICLE_EMITTER.SET_COLOR_START_VARIANCE",this._onParticleEmitterSetColorStartVariance),this._world.final("PARTICLE_EMITTER.SET_GRAVITY",this._onParticleEmitterSetGravity),this._world.final("PARTICLE_EMITTER.SET_LIFETIME",this._onParticleEmitterSetLifetime),this._world.final("PARTICLE_EMITTER.SET_LIFETIME_VARIANCE",this._onParticleEmitterSetLifetimeVariance),this._world.final("PARTICLE_EMITTER.SET_MAX_PARTICLES",this._onParticleEmitterSetMaxParticles),this._world.final("PARTICLE_EMITTER.SET_OFFSET",this._onParticleEmitterSetOffset),this._world.final("PARTICLE_EMITTER.SET_OPACITY_END",this._onParticleEmitterSetOpacityEnd),this._world.final("PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE",this._onParticleEmitterSetOpacityEndVariance),this._world.final("PARTICLE_EMITTER.SET_OPACITY_START",this._onParticleEmitterSetOpacityStart),this._world.final("PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE",this._onParticleEmitterSetOpacityStartVariance),this._world.final("PARTICLE_EMITTER.SET_PAUSED",this._onParticleEmitterSetPaused),this._world.final("PARTICLE_EMITTER.SET_POSITION",this._onParticleEmitterSetPosition),this._world.final("PARTICLE_EMITTER.SET_POSITION_VARIANCE",this._onParticleEmitterSetPositionVariance),this._world.final("PARTICLE_EMITTER.SET_RATE",this._onParticleEmitterSetRate),this._world.final("PARTICLE_EMITTER.SET_RATE_VARIANCE",this._onParticleEmitterSetRateVariance),this._world.final("PARTICLE_EMITTER.SET_SIZE_END",this._onParticleEmitterSetSizeEnd),this._world.final("PARTICLE_EMITTER.SET_SIZE_END_VARIANCE",this._onParticleEmitterSetSizeEndVariance),this._world.final("PARTICLE_EMITTER.SET_SIZE_START",this._onParticleEmitterSetSizeStart),this._world.final("PARTICLE_EMITTER.SET_SIZE_START_VARIANCE",this._onParticleEmitterSetSizeStartVariance),this._world.final("PARTICLE_EMITTER.SET_TEXTURE_URI",this._onParticleEmitterSetTextureUri),this._world.final("PARTICLE_EMITTER.SET_TRANSPARENT",this._onParticleEmitterSetTransparent),this._world.final("PARTICLE_EMITTER.SET_VELOCITY",this._onParticleEmitterSetVelocity),this._world.final("PARTICLE_EMITTER.SET_VELOCITY_VARIANCE",this._onParticleEmitterSetVelocityVariance),this._world.final("PARTICLE_EMITTER.SPAWN",this._onParticleEmitterSpawn)}_subscribeToPlayerEvents(){this._world.final("PLAYER.JOINED_WORLD",this._onPlayerJoinedWorld),this._world.final("PLAYER.LEFT_WORLD",this._onPlayerLeftWorld),this._world.final("PLAYER.RECONNECTED_WORLD",this._onPlayerReconnectedWorld),this._world.final("PLAYER.REQUEST_SYNC",this._onPlayerRequestSync)}_subscribeToPlayerCameraEvents(){this._world.final("PLAYER_CAMERA.LOOK_AT_ENTITY",this._onPlayerCameraLookAtEntity),this._world.final("PLAYER_CAMERA.LOOK_AT_POSITION",this._onPlayerCameraLookAtPosition),this._world.final("PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY",this._onPlayerCameraSetAttachedToEntity),this._world.final("PLAYER_CAMERA.SET_ATTACHED_TO_POSITION",this._onPlayerCameraSetAttachedToPosition),this._world.final("PLAYER_CAMERA.SET_FILM_OFFSET",this._onPlayerCameraSetFilmOffset),this._world.final("PLAYER_CAMERA.SET_FORWARD_OFFSET",this._onPlayerCameraSetForwardOffset),this._world.final("PLAYER_CAMERA.SET_FOV",this._onPlayerCameraSetFov),this._world.final("PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES",this._onPlayerCameraSetModelHiddenNodes),this._world.final("PLAYER_CAMERA.SET_MODEL_SHOWN_NODES",this._onPlayerCameraSetModelShownNodes),this._world.final("PLAYER_CAMERA.SET_MODE",this._onPlayerCameraSetMode),this._world.final("PLAYER_CAMERA.SET_OFFSET",this._onPlayerCameraSetOffset),this._world.final("PLAYER_CAMERA.SET_SHOULDER_ANGLE",this._onPlayerCameraSetShoulderAngle),this._world.final("PLAYER_CAMERA.SET_TRACKED_ENTITY",this._onPlayerCameraSetTrackedEntity),this._world.final("PLAYER_CAMERA.SET_TRACKED_POSITION",this._onPlayerCameraSetTrackedPosition),this._world.final("PLAYER_CAMERA.SET_ZOOM",this._onPlayerCameraSetZoom)}_subscribeToPlayerUIEvents(){this._world.final("PLAYER_UI.LOAD",this._onPlayerUILoad),this._world.final("PLAYER_UI.LOCK_POINTER",this._onPlayerUILockPointer),this._world.final("PLAYER_UI.SEND_DATA",this._onPlayerUISendData)}_subscribeToSceneUIEvents(){this._world.final("SCENE_UI.LOAD",this._onSceneUILoad),this._world.final("SCENE_UI.SET_ATTACHED_TO_ENTITY",this._onSceneUISetAttachedToEntity),this._world.final("SCENE_UI.SET_OFFSET",this._onSceneUISetOffset),this._world.final("SCENE_UI.SET_POSITION",this._onSceneUISetPosition),this._world.final("SCENE_UI.SET_STATE",this._onSceneUISetState),this._world.final("SCENE_UI.SET_VIEW_DISTANCE",this._onSceneUISetViewDistance),this._world.final("SCENE_UI.UNLOAD",this._onSceneUIUnload)}_subscribeToSimulationEvents(){this._world.final("SIMULATION.DEBUG_RAYCAST",this._onSimulationDebugRaycast),this._world.final("SIMULATION.DEBUG_RENDER",this._onSimulationDebugRender)}_subscribeToWorldEvents(){this._world.final("WORLD.SET_AMBIENT_LIGHT_COLOR",this._onWorldSetAmbientLightColor),this._world.final("WORLD.SET_AMBIENT_LIGHT_INTENSITY",this._onWorldSetAmbientLightIntensity),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_COLOR",this._onWorldSetDirectionalLightColor),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY",this._onWorldSetDirectionalLightIntensity),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_POSITION",this._onWorldSetDirectionalLightPosition),this._world.final("WORLD.SET_FOG_COLOR",this._onWorldSetFogColor),this._world.final("WORLD.SET_FOG_FAR",this._onWorldSetFogFar),this._world.final("WORLD.SET_FOG_NEAR",this._onWorldSetFogNear),this._world.final("WORLD.SET_SKYBOX_INTENSITY",this._onWorldSetSkyboxIntensity)}_onAudioPause=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.pa=!0,delete J.pl,delete J.r};_onAudioPlay=(Z)=>{let J=Z.audio.serialize();J.pl=!0,delete J.pa,delete J.r,this._queuedAudioSynchronizations.set(J.i,J)};_onAudioPlayRestart=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.r=!0,delete J.pa,delete J.pl,this._queuedAudioSynchronizations.set(J.i,J)};_onAudioSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onAudioSetCutoffDistance=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.cd=Z.cutoffDistance};_onAudioSetDetune=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.de=Z.detune};_onAudioSetDistortion=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.di=Z.distortion};_onAudioSetPosition=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.e=Z.position?void 0:J.e,J.p=Z.position?P0.serializeVector(Z.position,this._world.tickAllocator):void 0};_onAudioSetPlaybackRate=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.pr=Z.playbackRate};_onAudioSetReferenceDistance=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.rd=Z.referenceDistance};_onAudioSetVolume=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.v=Z.volume};_onBlockTypeRegistryRegisterBlockType=(Z)=>{let J=Z.blockType.serialize();this._queuedBlockTypeSynchronizations.set(Z.blockType.id,J)};_onChatSendBroadcastMessage=(Z)=>{let J=this._world.tickAllocator,{player:X,message:Y,color:$}=Z,Q=J.getObject();Q.m=Y,Q.c=$,Q.p=X?.id;let K=J.getArray();K.push(Q),this._queuedBroadcasts.push(Y0.createPacket(Y0.outboundPackets.chatMessagesPacketDefinition,K,this._world.loop.currentTick,J.getArray()))};_onChatSendPlayerMessage=(Z)=>{let J=this._world.tickAllocator,{player:X,message:Y,color:$}=Z,Q=this._queuedPerPlayerSynchronizations.get(X)??[],K=J.getObject();K.m=Y,K.c=$;let G=J.getArray();G.push(K),Q.push(Y0.createPacket(Y0.outboundPackets.chatMessagesPacketDefinition,G,this._world.loop.currentTick,this._world.tickAllocator.getArray())),this._queuedPerPlayerSynchronizations.set(X,Q)};_onChunkLatticeRemoveChunk=(Z)=>{let J=this._createOrGetQueuedChunkSync(Z.chunk),X=J.c.join(",");if(this._spawnedChunks.has(X))this._queuedChunkSynchronizations.delete(X),this._spawnedChunks.delete(X);else J.rm=!0};_onChunkLatticeSetBlock=(Z)=>{let J=this._createOrGetQueuedBlockSync(Z.globalCoordinate);J.i=Z.blockTypeId};_onEntitySetModelAnimationsPlaybackRate=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.ap=Z.playbackRate};_onEntitySpawn=(Z)=>{let J=Z.entity.serialize();this._queuedEntitySynchronizations.set(J.i,J),this._spawnedEntities.add(J.i)};_onEntityDespawn=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(this._spawnedEntities.has(J.i))this._queuedEntitySynchronizations.delete(J.i),this._spawnedEntities.delete(J.i);else J.rm=!0};_onEntitySetModelHiddenNodes=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.h=this._world.tickAllocator.getArray(Z.modelHiddenNodes)};_onEntitySetModelScale=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.s=Z.modelScale};_onEntitySetModelShownNodes=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.sn=this._world.tickAllocator.getArray(Z.modelShownNodes)};_onEntitySetModelTextureUri=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.mt=Z.modelTextureUri};_onEntitySetOpacity=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.o=Z.opacity};_onEntitySetParent=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.pe=Z.parent?Z.parent.id:void 0,J.pn=Z.parentNodeName};_onEntitySetTintColor=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.t=Z.tintColor?P0.serializeRgbColor(Z.tintColor,this._world.tickAllocator):void 0};_onEntityStartModelLoopedAnimations=(Z)=>{let J=this._world.tickAllocator,X=this._createOrGetQueuedEntitySync(Z.entity),Y=J.getSet(X.al,Z.animations);if(X.al=J.getArray(Y),X.as){let $=J.getArray();for(let Q of X.as)!Y.has(Q)&&$.push(Q);X.as=$}};_onEntityStartModelOneshotAnimations=(Z)=>{let J=this._world.tickAllocator,X=this._createOrGetQueuedEntitySync(Z.entity),Y=J.getSet(X.ao,Z.animations);if(X.ao=J.getArray(Y),X.as){let $=J.getArray();for(let Q of X.as)!Y.has(Q)&&$.push(Q);X.as=$}};_onEntityStopModelAnimations=(Z)=>{let J=this._world.tickAllocator,X=this._createOrGetQueuedEntitySync(Z.entity);if(X.al){let Y=J.getSet(X.al);for(let $ of Z.animations)Y.delete($);X.al=J.getArray(Y)}if(X.ao){let Y=J.getSet(X.ao);for(let $ of Z.animations)Y.delete($);X.ao=J.getArray(Y)}X.as=J.getArray(J.getSet(X.as,Z.animations))};_onEntityUpdateRotation=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.r=P0.serializeQuaternion(Z.rotation,this._world.tickAllocator)};_onEntityUpdatePosition=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.p=P0.serializeVector(Z.position,this._world.tickAllocator)};_onLightDespawn=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.rm=!0};_onLightSetAngle=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.a=Z.angle};_onLightSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onLightSetColor=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.c=P0.serializeRgbColor(Z.color,this._world.tickAllocator)};_onLightSetDistance=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.d=Z.distance};_onLightSetIntensity=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.n=Z.intensity};_onLightSetOffset=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.o=Z.offset?P0.serializeVector(Z.offset,this._world.tickAllocator):void 0};_onLightSetPenumbra=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.pe=Z.penumbra};_onLightSetPosition=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.p=Z.position?P0.serializeVector(Z.position,this._world.tickAllocator):void 0,J.e=Z.position?void 0:J.e};_onLightSetTrackedEntity=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.te=Z.entity?Z.entity.id:void 0,J.tp=Z.entity?void 0:J.tp};_onLightSetTrackedPosition=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.tp=Z.position?P0.serializeVector(Z.position,this._world.tickAllocator):void 0,J.te=Z.position?void 0:J.te};_onLightSpawn=(Z)=>{let J=Z.light.serialize();this._queuedLightSynchronizations.set(J.i,J)};_onParticleEmitterDespawn=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.rm=!0};_onParticleEmitterSetAlphaTest=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.at=Z.alphaTest};_onParticleEmitterSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onParticleEmitterSetAttachedToEntityNodeName=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.en=Z.attachedToEntityNodeName};_onParticleEmitterSetColorEnd=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.ce=Z.colorEnd?P0.serializeRgbColor(Z.colorEnd,this._world.tickAllocator):void 0};_onParticleEmitterSetColorEndVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.cev=Z.colorEndVariance?P0.serializeRgbColor(Z.colorEndVariance,this._world.tickAllocator):void 0};_onParticleEmitterSetColorStart=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.cs=Z.colorStart?P0.serializeRgbColor(Z.colorStart,this._world.tickAllocator):void 0};_onParticleEmitterSetColorStartVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.csv=Z.colorStartVariance?P0.serializeRgbColor(Z.colorStartVariance,this._world.tickAllocator):void 0};_onParticleEmitterSetGravity=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.g=Z.gravity?P0.serializeVector(Z.gravity,this._world.tickAllocator):void 0};_onParticleEmitterSetLifetime=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.l=Z.lifetime};_onParticleEmitterSetLifetimeVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.lv=Z.lifetimeVariance};_onParticleEmitterSetMaxParticles=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.mp=Z.maxParticles};_onParticleEmitterSetOffset=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.o=Z.offset?P0.serializeVector(Z.offset,this._world.tickAllocator):void 0};_onParticleEmitterSetOpacityEnd=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.oe=Z.opacityEnd};_onParticleEmitterSetOpacityEndVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.oev=Z.opacityEndVariance};_onParticleEmitterSetOpacityStart=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.os=Z.opacityStart};_onParticleEmitterSetOpacityStartVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.osv=Z.opacityStartVariance};_onParticleEmitterSetPaused=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.pa=Z.paused};_onParticleEmitterSetPosition=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.p=Z.position?P0.serializeVector(Z.position,this._world.tickAllocator):void 0,J.e=Z.position?void 0:J.e,J.en=Z.position?void 0:J.en};_onParticleEmitterSetPositionVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.pv=Z.positionVariance?P0.serializeVector(Z.positionVariance,this._world.tickAllocator):void 0};_onParticleEmitterSetRate=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.r=Z.rate};_onParticleEmitterSetRateVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.rv=Z.rateVariance};_onParticleEmitterSetSizeEnd=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.se=Z.sizeEnd};_onParticleEmitterSetSizeEndVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.sev=Z.sizeEndVariance};_onParticleEmitterSetSizeStart=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.ss=Z.sizeStart};_onParticleEmitterSetSizeStartVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.ssv=Z.sizeStartVariance};_onParticleEmitterSetTextureUri=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.tu=Z.textureUri};_onParticleEmitterSetTransparent=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.t=Z.transparent};_onParticleEmitterSetVelocity=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.v=Z.velocity?P0.serializeVector(Z.velocity,this._world.tickAllocator):void 0};_onParticleEmitterSetVelocityVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.vv=Z.velocityVariance?P0.serializeVector(Z.velocityVariance,this._world.tickAllocator):void 0};_onParticleEmitterSpawn=(Z)=>{let J=Z.particleEmitter.serialize();this._queuedParticleEmitterSynchronizations.set(J.i,J)};_onPlayerCameraLookAtEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pl=P0.serializeVector(Z.entity.position,this._world.tickAllocator),delete J.et,delete J.pt};_onPlayerCameraLookAtPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pl=Z.position?P0.serializeVector(Z.position,this._world.tickAllocator):void 0,delete J.et,delete J.pt};_onPlayerCameraSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.e=Z.entity.id,delete J.p};_onPlayerCameraSetAttachedToPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.p=Z.position?P0.serializeVector(Z.position,this._world.tickAllocator):void 0,delete J.e};_onPlayerCameraSetFilmOffset=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.fo=Z.filmOffset};_onPlayerCameraSetForwardOffset=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.ffo=Z.forwardOffset};_onPlayerCameraSetFov=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.fv=Z.fov};_onPlayerCameraSetModelHiddenNodes=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.h=this._world.tickAllocator.getArray(Z.modelHiddenNodes)};_onPlayerCameraSetModelShownNodes=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.s=this._world.tickAllocator.getArray(Z.modelShownNodes)};_onPlayerCameraSetMode=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.m=Z.mode};_onPlayerCameraSetOffset=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.o=Z.offset?P0.serializeVector(Z.offset,this._world.tickAllocator):void 0};_onPlayerCameraSetShoulderAngle=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.sa=Z.shoulderAngle};_onPlayerCameraSetTrackedEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.et=Z.entity?Z.entity.id:void 0,delete J.pl,delete J.pt};_onPlayerCameraSetTrackedPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pt=Z.position?P0.serializeVector(Z.position,this._world.tickAllocator):void 0,delete J.et,delete J.pl};_onPlayerCameraSetZoom=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.z=Z.zoom};_onPlayerJoinedWorld=(Z)=>{let J=this._world.tickAllocator,{player:X}=Z,Y=this._queuedPerPlayerSynchronizations.get(X)??J.getArray();Y.push(Y0.createPacket(Y0.outboundPackets.worldPacketDefinition,this._world.serialize(),this._world.loop.currentTick,J.getArray())),Y.push(Y0.createPacket(Y0.outboundPackets.blockTypesPacketDefinition,this._world.blockTypeRegistry.serialize(),this._world.loop.currentTick,J.getArray())),Y.push(Y0.createPacket(Y0.outboundPackets.chunksPacketDefinition,J.map(this._world.chunkLattice.getAllChunks(!0),(Q)=>Q.serialize()),this._world.loop.currentTick,J.getArray())),Y.push(Y0.createPacket(Y0.outboundPackets.entitiesPacketDefinition,J.map(this._world.entityManager.getAllEntities(!0),(Q)=>{if(X.camera.attachedToEntity===void 0&&Q instanceof y7&&Q.player===X)X.camera.setAttachedToEntity(Q);return Q.serialize()}),this._world.loop.currentTick,J.getArray())),Y.push(Y0.createPacket(Y0.outboundPackets.audiosPacketDefinition,J.map(this._world.audioManager.getAllAudios(!0),(Q)=>Q.serialize()),this._world.loop.currentTick,J.getArray())),Y.push(Y0.createPacket(Y0.outboundPackets.lightsPacketDefinition,J.map(this._world.lightManager.getAllLights(!0),(Q)=>Q.serialize()),this._world.loop.currentTick,J.getArray())),Y.push(Y0.createPacket(Y0.outboundPackets.particleEmittersPacketDefinition,J.map(this._world.particleEmitterManager.getAllParticleEmitters(!0),(Q)=>Q.serialize()),this._world.loop.currentTick,J.getArray())),Y.push(Y0.createPacket(Y0.outboundPackets.sceneUIsPacketDefinition,J.map(this._world.sceneUIManager.getAllSceneUIs(!0),(Q)=>Q.serialize()),this._world.loop.currentTick,J.getArray())),Y.push(Y0.createPacket(Y0.outboundPackets.playersPacketDefinition,J.map(q9.instance.getConnectedPlayers(),(Q)=>Q.serialize()),this._world.loop.currentTick,J.getArray()));let $=this._createOrGetQueuedPlayerCameraSync(X.camera);this._queuedPerPlayerCameraSynchronizations.set(X,J.getObject(X.camera.serialize(),$)),this._queuedPerPlayerSynchronizations.set(X,Y),this._queuedPlayerSynchronizations.set(X.id,X.serialize())};_onPlayerLeftWorld=(Z)=>{let J=this._createOrGetQueuedPlayerSync(Z.player);J.rm=!0};_onPlayerReconnectedWorld=(Z)=>{this._onPlayerJoinedWorld(Z)};_onPlayerRequestSync=(Z)=>{let J=this._world.tickAllocator,X=J.getObject();X.r=Z.receivedAt,X.s=Date.now(),X.p=performance.now()-Z.receivedAtMs,X.n=this._world.loop.nextTickMs,Z.player.connection.send([Y0.createPacket(Y0.outboundPackets.syncResponsePacketDefinition,X,this._world.loop.currentTick,J.getArray())])};_onPlayerUILoad=(Z)=>{let J=this._createOrGetQueuedPlayerUISync(Z.playerUI);J.u=Z.htmlUri};_onPlayerUILockPointer=(Z)=>{let J=this._createOrGetQueuedPlayerUISync(Z.playerUI);J.p=Z.lock};_onPlayerUISendData=(Z)=>{this._createOrGetQueuedPlayerUIDatasSync(Z.playerUI).push(Z.data)};_onSceneUILoad=(Z)=>{let J=Z.sceneUI.serialize();this._queuedSceneUISynchronizations.set(J.i,J),this._loadedSceneUIs.add(J.i)};_onSceneUISetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onSceneUISetOffset=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.o=Z.offset?P0.serializeVector(Z.offset,this._world.tickAllocator):void 0};_onSceneUISetPosition=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.p=Z.position?P0.serializeVector(Z.position,this._world.tickAllocator):void 0,J.e=Z.position?void 0:J.e};_onSceneUISetState=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.s=Z.state};_onSceneUISetViewDistance=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.v=Z.viewDistance};_onSceneUIUnload=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);if(this._loadedSceneUIs.has(J.i))this._queuedSceneUISynchronizations.delete(J.i),this._loadedSceneUIs.delete(J.i);else J.rm=!0};_onSimulationDebugRaycast=(Z)=>{this._queuedDebugRaycastSynchronizations.push(P0.serializePhysicsDebugRaycast(Z,this._world.tickAllocator))};_onSimulationDebugRender=(Z)=>{this._queuedBroadcasts.push(Y0.createPacket(Y0.outboundPackets.physicsDebugRenderPacketDefinition,{v:Array.from(Z.vertices),c:Array.from(Z.colors)},this._world.loop.currentTick,this._world.tickAllocator.getArray()))};_onWorldSetAmbientLightColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.ac=P0.serializeRgbColor(Z.color,this._world.tickAllocator)};_onWorldSetAmbientLightIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.ai=Z.intensity};_onWorldSetDirectionalLightColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.dc=P0.serializeRgbColor(Z.color,this._world.tickAllocator)};_onWorldSetDirectionalLightIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.di=Z.intensity};_onWorldSetDirectionalLightPosition=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.dp=P0.serializeVector(Z.position,this._world.tickAllocator)};_onWorldSetFogColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.fc=P0.serializeRgbColor(Z.color,this._world.tickAllocator)};_onWorldSetFogFar=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.ff=Z.far};_onWorldSetFogNear=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.fn=Z.near};_onWorldSetSkyboxIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.si=Z.intensity};_createOrGetQueuedAudioSync(Z){if(Z.id===void 0)d.fatalError("NetworkSynchronizer._createOrGetQueuedAudioSync(): Audio has no id!");let J=this._queuedAudioSynchronizations.get(Z.id);if(!J)J=this._world.tickAllocator.getObject(),J.i=Z.id,this._queuedAudioSynchronizations.set(Z.id,J);return J}_createOrGetQueuedBlockSync(Z){let{x:J,y:X,z:Y}=Z,$=`${J},${X},${Y}`,Q=this._queuedBlockSynchronizations.get($);if(!Q)Q=this._world.tickAllocator.getObject(),Q.i=0,Q.c=[J,X,Y],this._queuedBlockSynchronizations.set($,Q);return Q}_createOrGetQueuedChunkSync(Z){if(!Z.originCoordinate)d.fatalError("NetworkSynchronizer._createOrGetQueuedChunkSync(): Chunk has no origin coordinate!");let{x:J,y:X,z:Y}=Z.originCoordinate,$=`${J},${X},${Y}`,Q=this._queuedChunkSynchronizations.get($);if(!Q)Q=this._world.tickAllocator.getObject(),Q.c=[J,X,Y],this._queuedChunkSynchronizations.set($,Q);return Q}_createOrGetQueuedEntitySync(Z){if(Z.id===void 0)d.fatalError("NetworkSynchronizer._createOrGetQueuedEntitySync(): Entity has no id!");let J=this._queuedEntitySynchronizations.get(Z.id);if(!J)J=this._world.tickAllocator.getObject(),J.i=Z.id,this._queuedEntitySynchronizations.set(Z.id,J);return J}_createOrGetQueuedLightSync(Z){if(Z.id===void 0)d.fatalError("NetworkSynchronizer._createOrGetQueuedLightSync(): Light has no id!");let J=this._queuedLightSynchronizations.get(Z.id);if(!J)J=this._world.tickAllocator.getObject(),J.i=Z.id,this._queuedLightSynchronizations.set(Z.id,J);return J}_createOrGetQueuedParticleEmitterSync(Z){if(Z.id===void 0)d.fatalError("NetworkSynchronizer._createOrGetQueuedParticleEmitterSync(): ParticleEmitter has no id!");let J=this._queuedParticleEmitterSynchronizations.get(Z.id);if(!J)J=this._world.tickAllocator.getObject(),J.i=Z.id,this._queuedParticleEmitterSynchronizations.set(Z.id,J);return J}_createOrGetQueuedPlayerSync(Z){if(Z.id===void 0)d.fatalError("NetworkSynchronizer._createOrGetQueuedPlayerSync(): Player has no id!");let J=this._queuedPlayerSynchronizations.get(Z.id);if(!J)J=this._world.tickAllocator.getObject(),J.i=Z.id,this._queuedPlayerSynchronizations.set(Z.id,J);return J}_createOrGetQueuedPlayerCameraSync(Z){let J=this._queuedPerPlayerCameraSynchronizations.get(Z.player);if(!J)J=this._world.tickAllocator.getObject(),this._queuedPerPlayerCameraSynchronizations.set(Z.player,J);return J}_createOrGetQueuedPlayerUISync(Z){let J=this._queuedPerPlayerUISynchronizations.get(Z.player);if(!J)J=this._world.tickAllocator.getObject(),this._queuedPerPlayerUISynchronizations.set(Z.player,J);return J}_createOrGetQueuedPlayerUIDatasSync(Z){let J=this._queuedPerPlayerUIDatasSynchronizations.get(Z.player);if(!J)J=this._world.tickAllocator.getArray(),this._queuedPerPlayerUIDatasSynchronizations.set(Z.player,J);return J}_createOrGetQueuedSceneUISync(Z){if(Z.id===void 0)d.fatalError("NetworkSynchronizer._createOrGetQueuedSceneUISync(): SceneUI has no id!");let J=this._queuedSceneUISynchronizations.get(Z.id);if(!J)J=this._world.tickAllocator.getObject(),J.i=Z.id,this._queuedSceneUISynchronizations.set(Z.id,J);return J}_createOrGetQueuedWorldSync(Z){if(Z.id!==this._world.id)d.fatalError("NetworkSynchronizer._createOrGetQueuedWorldSync(): World does not match this network synchronizer world!");return this._queuedWorldSynchronization??=this._world.tickAllocator.getObject(),this._queuedWorldSynchronization.i=Z.id,this._queuedWorldSynchronization}_createOrGetSynchronizedPlayerReliablePackets(Z,J){let X=this._synchronizedPlayerReliablePackets.get(Z);if(!X)X=this._world.tickAllocator.getArray(J),this._synchronizedPlayerReliablePackets.set(Z,X);return X}}class zU{_particleEmitters=new Map;_nextParticleEmitterId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}despawnEntityAttachedParticleEmitters(Z){this.getAllEntityAttachedParticleEmitters(Z).forEach((J)=>{J.despawn()})}getAllParticleEmitters(Z=!1){return Z?this._world.tickAllocator.getArray(this._particleEmitters.values()):Array.from(this._particleEmitters.values())}getAllEntityAttachedParticleEmitters(Z){return this.getAllParticleEmitters().filter((J)=>J.attachedToEntity===Z)}registerParticleEmitter(Z){if(Z.id!==void 0)return Z.id;let J=this._nextParticleEmitterId;return this._particleEmitters.set(J,Z),this._nextParticleEmitterId++,J}unregisterParticleEmitter(Z){if(Z.id===void 0)return;this._particleEmitters.delete(Z.id)}}class FU{_sceneUIs=new Map;_nextSceneUIId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}getAllSceneUIs(Z=!1){return Z?this._world.tickAllocator.getArray(this._sceneUIs.values()):Array.from(this._sceneUIs.values())}getAllEntityAttachedSceneUIs(Z){return this.getAllSceneUIs().filter((J)=>J.attachedToEntity===Z)}getSceneUIById(Z){return this._sceneUIs.get(Z)}registerSceneUI(Z){if(Z.id!==void 0)return Z.id;let J=this._nextSceneUIId;return this._sceneUIs.set(J,Z),this._nextSceneUIId++,J}unloadEntityAttachedSceneUIs(Z){this.getAllEntityAttachedSceneUIs(Z).forEach((J)=>{J.unload()})}unregisterSceneUI(Z){if(Z.id===void 0)return;this._sceneUIs.delete(Z.id)}}class qU{_allocatedArrays=[];_allocatedArray3Numbers=[];_allocatedArray4Numbers=[];_allocatedObjects=[];_allocatedSets=[];_arrayPool=[];_array3NumberPool=[];_array4NumberPool=[];_objectPool=[];_setPool=[];getArray(Z,J){let X=this._arrayPool.pop()??[];X.length=0;let Y=0;if(Z)for(let $ of Z)X[Y++]=$;if(J)for(let $ of J)X[Y++]=$;return this._allocatedArrays.push(X),X}getArray3Number(Z){let J=this._array3NumberPool.pop()??[0,0,0];if(J[0]=J[1]=J[2]=0,Z){let X=0;for(let Y of Z){if(X>=3)break;J[X++]=Y}}return this._allocatedArray3Numbers.push(J),J}getArray4Number(Z){let J=this._array4NumberPool.pop()??[0,0,0,0];if(J[0]=J[1]=J[2]=J[3]=0,Z){let X=0;for(let Y of Z){if(X>=4)break;J[X++]=Y}}return this._allocatedArray4Numbers.push(J),J}getObject(Z,J){let X=this._objectPool.pop()??Object.create(null);for(let Y in X)delete X[Y];if(Z)Object.assign(X,Z);if(J)Object.assign(X,J);return this._allocatedObjects.push(X),X}getSet(Z,J){let X=this._setPool.pop()??new Set;if(X.clear(),Z)for(let Y of Z)X.add(Y);if(J)for(let Y of J)X.add(Y);return this._allocatedSets.push(X),X}map(Z,J){let X=this.getArray();X.length=Z.length;for(let Y=0;Y<Z.length;Y++)X[Y]=J(Z[Y],Y,Z);return X}reset(){for(let Z=0;Z<this._allocatedArrays.length;Z++)if(this._arrayPool.length<4096)this._arrayPool.push(this._allocatedArrays[Z]);for(let Z=0;Z<this._allocatedArray3Numbers.length;Z++)if(this._array3NumberPool.length<4096)this._array3NumberPool.push(this._allocatedArray3Numbers[Z]);for(let Z=0;Z<this._allocatedArray4Numbers.length;Z++)if(this._array4NumberPool.length<4096)this._array4NumberPool.push(this._allocatedArray4Numbers[Z]);for(let Z=0;Z<this._allocatedObjects.length;Z++)if(this._objectPool.length<4096)this._objectPool.push(this._allocatedObjects[Z]);for(let Z=0;Z<this._allocatedSets.length;Z++)if(this._setPool.length<1024)this._setPool.push(this._allocatedSets[Z]);this._allocatedArrays.length=0,this._allocatedArray3Numbers.length=0,this._allocatedArray4Numbers.length=0,this._allocatedObjects.length=0,this._allocatedSets.length=0}}var tQ6=2,eQ6=3;class UU{_accumulatorMs=0;_targetTicksPerSecond;_fixedTimestepMs;_fixedTimestepS;_maxAccumulatorMs;_nextTickMs=0;_lastLoopTimeMs=0;_tickFunction;_tickErrorCallback;_tickHandle=null;constructor(Z,J,X){this._targetTicksPerSecond=Z,this._fixedTimestepS=Math.fround(1/Z),this._fixedTimestepMs=Math.fround(this._fixedTimestepS*1000),this._maxAccumulatorMs=this._fixedTimestepMs*eQ6,this._tickFunction=J,this._tickErrorCallback=X}get targetTicksPerSecond(){return this._targetTicksPerSecond}get fixedTimestepMs(){return this._fixedTimestepMs}get fixedTimestepS(){return this._fixedTimestepS}get isStarted(){return!!this._tickHandle}get nextTickMs(){return this._nextTickMs}start(){if(this._tickHandle)return;this._lastLoopTimeMs=performance.now();let Z=()=>{let J=performance.now(),X=J-this._lastLoopTimeMs;if(this._lastLoopTimeMs=J,this._accumulatorMs+=X,this._accumulatorMs>this._maxAccumulatorMs)this._accumulatorMs=this._maxAccumulatorMs;if(this._accumulatorMs>=this._fixedTimestepMs)r1.startSpan({operation:"ticker_tick"},()=>{let Y=0;while(this._accumulatorMs>=this._fixedTimestepMs&&Y<tQ6)this._tick(this._fixedTimestepMs),this._accumulatorMs-=this._fixedTimestepMs,Y++;this._nextTickMs=Math.max(0,this._fixedTimestepMs-this._accumulatorMs)});this._tickHandle=setTimeout(Z,this._nextTickMs)};Z()}stop(){if(!this._tickHandle)return;clearTimeout(this._tickHandle),this._tickHandle=null}_tick(Z){try{this._tickFunction(Z)}catch(J){if(J instanceof Error&&this._tickErrorCallback)this._tickErrorCallback(J);else d.warning(`Ticker._tick(): tick callback threw an error, but it was not an instance of Error. Error: ${J}`)}}}var _31;((Q)=>{Q.START="WORLD_LOOP.START";Q.STOP="WORLD_LOOP.STOP";Q.TICK_START="WORLD_LOOP.TICK_START";Q.TICK_END="WORLD_LOOP.TICK_END";Q.TICK_ERROR="WORLD_LOOP.TICK_ERROR"})(_31||={});class LU extends O0{_currentTick=0;_ticker;_world;constructor(Z,J=Nm){super();this._ticker=new UU(J,this._tick,this._onTickError),this._world=Z}get currentTick(){return this._currentTick}get isStarted(){return this._ticker.isStarted}get nextTickMs(){return this._ticker.nextTickMs}get timestepS(){return this._ticker.fixedTimestepS}get world(){return this._world}start(){this._ticker.start(),this.emitWithWorld(this._world,"WORLD_LOOP.START",{worldLoop:this})}stop(){this._ticker.stop(),this.emitWithWorld(this._world,"WORLD_LOOP.STOP",{worldLoop:this})}_tick=(Z)=>{this.emitWithWorld(this._world,"WORLD_LOOP.TICK_START",{worldLoop:this,tickDeltaMs:Z});let J=performance.now();r1.startSpan({operation:"world_tick",attributes:{serverPlayerCount:q9.instance.playerCount,targetTickRate:this._ticker.targetTicksPerSecond,targetTickRateMs:this._ticker.fixedTimestepMs,worldId:this._world.id,worldName:this._world.name,worldChunkCount:this._world.chunkLattice.chunkCount,worldEntityCount:this._world.entityManager.entityCount,worldLoopTick:this._currentTick}},()=>{r1.startSpan({operation:"entities_tick"},()=>this._world.entityManager.tickEntities(Z)),r1.startSpan({operation:"simulation_step"},()=>this._world.simulation.step(Z)),r1.startSpan({operation:"entities_emit_updates"},()=>this._world.entityManager.checkAndEmitUpdates()),r1.startSpan({operation:"network_synchronize"},()=>this._world.networkSynchronizer.synchronize()),r1.startSpan({operation:"release_tick_allocation"},()=>this._world.tickAllocator.reset())}),this._currentTick++,this.emitWithWorld(this._world,"WORLD_LOOP.TICK_END",{worldLoop:this,tickDurationMs:performance.now()-J})};_onTickError=(Z)=>{d.error(`WorldLoop._onTickError(): Error: ${Z}`),this.emitWithWorld(this._world,"WORLD_LOOP.TICK_ERROR",{worldLoop:this,error:Z})}}var Dm;((F)=>{F.SET_AMBIENT_LIGHT_COLOR="WORLD.SET_AMBIENT_LIGHT_COLOR";F.SET_AMBIENT_LIGHT_INTENSITY="WORLD.SET_AMBIENT_LIGHT_INTENSITY";F.SET_DIRECTIONAL_LIGHT_COLOR="WORLD.SET_DIRECTIONAL_LIGHT_COLOR";F.SET_DIRECTIONAL_LIGHT_INTENSITY="WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY";F.SET_DIRECTIONAL_LIGHT_POSITION="WORLD.SET_DIRECTIONAL_LIGHT_POSITION";F.SET_FOG_COLOR="WORLD.SET_FOG_COLOR";F.SET_FOG_FAR="WORLD.SET_FOG_FAR";F.SET_FOG_NEAR="WORLD.SET_FOG_NEAR";F.SET_SKYBOX_INTENSITY="WORLD.SET_SKYBOX_INTENSITY";F.START="WORLD.START";F.STOP="WORLD.STOP"})(Dm||={});class BU extends O0{_id;_ambientLightColor;_ambientLightIntensity;_audioManager;_blockTypeRegistry;_chatManager;_chunkLattice;_directionalLightColor;_directionalLightIntensity;_directionalLightPosition;_entityManager;_fogColor;_fogFar;_fogNear;_lightManager;_loop;_name;_networkSynchronizer;_particleEmitterManager;_sceneUIManager;_simulation;_skyboxIntensity;_skyboxUri;_tag;_tickAllocator;constructor(Z){super();if(this._id=Z.id,this._ambientLightColor=Z.ambientLightColor??{r:255,g:255,b:255},this._ambientLightIntensity=Z.ambientLightIntensity??1,this._directionalLightColor=Z.directionalLightColor??{r:255,g:255,b:255},this._directionalLightIntensity=Z.directionalLightIntensity??3,this._directionalLightPosition=Z.directionalLightPosition??{x:100,y:150,z:100},this._fogColor=Z.fogColor,this._fogFar=Z.fogFar??550,this._fogNear=Z.fogNear??500,this._name=Z.name,this._skyboxIntensity=Z.skyboxIntensity??1,this._skyboxUri=Z.skyboxUri,this._tag=Z.tag,this._audioManager=new D3(this),this._blockTypeRegistry=new jV(this),this._chatManager=new aV(this),this._chunkLattice=new sV(this),this._entityManager=new eV(this),this._lightManager=new WU(this),this._loop=new LU(this,Z.tickRate),this._networkSynchronizer=new WP(this),this._particleEmitterManager=new zU(this),this._sceneUIManager=new FU(this),this._simulation=new VU(this,Z.tickRate,Z.gravity),this._tickAllocator=new qU,Z.map)this.loadMap(Z.map)}get id(){return this._id}get ambientLightColor(){return this._ambientLightColor}get ambientLightIntensity(){return this._ambientLightIntensity}get blockTypeRegistry(){return this._blockTypeRegistry}get chatManager(){return this._chatManager}get chunkLattice(){return this._chunkLattice}get directionalLightColor(){return this._directionalLightColor}get directionalLightIntensity(){return this._directionalLightIntensity}get directionalLightPosition(){return this._directionalLightPosition}get entityManager(){return this._entityManager}get fogColor(){return this._fogColor}get fogFar(){return this._fogFar}get fogNear(){return this._fogNear}get lightManager(){return this._lightManager}get loop(){return this._loop}get name(){return this._name}get networkSynchronizer(){return this._networkSynchronizer}get particleEmitterManager(){return this._particleEmitterManager}get sceneUIManager(){return this._sceneUIManager}get simulation(){return this._simulation}get skyboxIntensity(){return this._skyboxIntensity}get skyboxUri(){return this._skyboxUri}get audioManager(){return this._audioManager}get tag(){return this._tag}get tickAllocator(){return this._tickAllocator}loadMap(Z){if(this.chunkLattice.clear(),Z.blockTypes)for(let J of Z.blockTypes)this.blockTypeRegistry.registerGenericBlockType({id:J.id,isLiquid:J.isLiquid,name:J.name,textureUri:J.textureUri});if(Z.blocks)for(let[J,X]of Object.entries(Z.blocks)){let[Y,$,Q]=J.split(",").map(Number);this.chunkLattice.setBlock({x:Y,y:$,z:Q},X)}if(Z.entities)for(let[J,X]of Object.entries(Z.entities)){let[Y,$,Q]=J.split(",").map(Number);new i8({isEnvironmental:!0,...X}).spawn(this,{x:Y,y:$,z:Q})}}setAmbientLightColor(Z){this._ambientLightColor=Z,this.emit("WORLD.SET_AMBIENT_LIGHT_COLOR",{world:this,color:Z})}setAmbientLightIntensity(Z){this._ambientLightIntensity=Z,this.emit("WORLD.SET_AMBIENT_LIGHT_INTENSITY",{world:this,intensity:Z})}setDirectionalLightColor(Z){this._directionalLightColor=Z,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_COLOR",{world:this,color:Z})}setDirectionalLightIntensity(Z){this._directionalLightIntensity=Z,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY",{world:this,intensity:Z})}setDirectionalLightPosition(Z){this._directionalLightPosition=Z,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_POSITION",{world:this,position:Z})}setFogColor(Z){this._fogColor=Z,this.emit("WORLD.SET_FOG_COLOR",{world:this,color:Z})}setFogFar(Z){this._fogFar=Z,this.emit("WORLD.SET_FOG_FAR",{world:this,far:Z})}setFogNear(Z){this._fogNear=Z,this.emit("WORLD.SET_FOG_NEAR",{world:this,near:Z})}setSkyboxIntensity(Z){this._skyboxIntensity=Z,this.emit("WORLD.SET_SKYBOX_INTENSITY",{world:this,intensity:Z})}start(){if(this._loop.isStarted)return;this._loop.start(),this.emit("WORLD.START",{world:this,startedAtMs:Date.now()})}stop(){if(!this._loop.isStarted)return;this._loop.stop(),this.emit("WORLD.STOP",{world:this,stoppedAtMs:Date.now()})}serialize(){return P0.serializeWorld(this,this._tickAllocator)}}var S31;((J)=>J.WORLD_CREATED="WORLD_MANAGER.WORLD_CREATED")(S31||={});class EY{static instance=new EY;_defaultWorld;_nextWorldId=1;_worlds=new Map;createWorld(Z){let J=new BU({...Z,id:this._nextWorldId++});return J.start(),this._worlds.set(J.id,J),O0.globalInstance.emit("WORLD_MANAGER.WORLD_CREATED",{world:J}),J}getAllWorlds(){return Array.from(this._worlds.values())}getDefaultWorld(){return this._defaultWorld??=this.createWorld({name:"Default World",skyboxUri:"skyboxes/partly-cloudy"}),this._defaultWorld}getWorldsByTag(Z){let J=[];return this._worlds.forEach((X)=>{if(X.tag===Z)J.push(X)}),J}getWorld(Z){return this._worlds.get(Z)}setDefaultWorld(Z){this._defaultWorld=Z}}var v31;((Y)=>{Y.PLAYER_CONNECTED="PLAYER_MANAGER.PLAYER_CONNECTED";Y.PLAYER_DISCONNECTED="PLAYER_MANAGER.PLAYER_DISCONNECTED";Y.PLAYER_RECONNECTED="PLAYER_MANAGER.PLAYER_RECONNECTED"})(v31||={});class q9{static instance=new q9;worldSelectionHandler;_connectionPlayers=new Map;constructor(){O0.globalInstance.on("CONNECTION.OPENED",({connection:Z,req:J})=>{this._onConnectionOpened(Z,J.session)}),O0.globalInstance.on("CONNECTION.DISCONNECTED",({connection:Z})=>{this._onConnectionDisconnected(Z)}),O0.globalInstance.on("CONNECTION.RECONNECTED",({connection:Z})=>{this._onConnectionReconnected(Z)}),O0.globalInstance.on("CONNECTION.CLOSED",({connection:Z})=>{this._onConnectionClosed(Z)})}get playerCount(){return this._connectionPlayers.size}getConnectedPlayers(){return Array.from(this._connectionPlayers.values())}getConnectedPlayersByWorld(Z){return this.getConnectedPlayers().filter((J)=>J.world===Z)}getConnectedPlayerByUsername(Z){return Array.from(this._connectionPlayers.values()).find((J)=>{return J.username.toLowerCase()===Z.toLowerCase()})}async _onConnectionOpened(Z,J){let X=new CG(Z,J);await X.loadInitialPersistedData(),this._connectionPlayers.set(Z,X),O0.globalInstance.emit("PLAYER_MANAGER.PLAYER_CONNECTED",{player:X});let Y=await this.worldSelectionHandler?.(X);X.joinWorld(Y??EY.instance.getDefaultWorld())}_onConnectionDisconnected(Z){let J=this._connectionPlayers.get(Z);if(J)J.resetInputs(),J.camera.reset()}_onConnectionReconnected(Z){let J=this._connectionPlayers.get(Z);if(J)J.reconnected(),O0.globalInstance.emit("PLAYER_MANAGER.PLAYER_RECONNECTED",{player:J});else d.warning(`PlayerManager._onConnectionReconnected(): Connection ${Z.id} not in the PlayerManager._connectionPlayers map.`)}_onConnectionClosed(Z){let J=this._connectionPlayers.get(Z);if(J)J.disconnect(),this._connectionPlayers.delete(Z),O0.globalInstance.emit("PLAYER_MANAGER.PLAYER_DISCONNECTED",{player:J});else d.warning(`PlayerManager._onConnectionClosed(): Connection ${Z.id} not in the PlayerManager._connectionPlayers map.`)}}Buffer.poolSize=134217728;var x31;((X)=>{X.START="GAMESERVER.START";X.STOP="GAMESERVER.STOP"})(x31||={});function ZK6(Z){A31.default.init().then(()=>{return $K.instance.modelRegistry.preloadModels()}).then(()=>{if(Z.length>0)Z($K.instance.worldManager.getDefaultWorld());else Z();$K.instance.start()}).catch((J)=>{d.fatalError(`Failed to initialize the game engine, exiting. Error: ${J}`)})}class $K{static _instance;_modelRegistry=S5.instance;_playerManager=q9.instance;_socket=a7.instance;_worldManager=EY.instance;_webServer=FW.instance;constructor(){}static get instance(){if(!this._instance)this._instance=new $K;return this._instance}get modelRegistry(){return this._modelRegistry}get playerManager(){return this._playerManager}get socket(){return this._socket}get webServer(){return this._webServer}get worldManager(){return this._worldManager}start(){O0.globalInstance.emit("GAMESERVER.START",{startedAtMs:performance.now()}),this._webServer.start()}}var F6=r(GK(),1);class WK extends Float32Array{constructor(Z,J,X,Y){super([Z,J,X,Y])}get determinant(){return F6.mat2.determinant(this)}get frobeniusNorm(){return F6.mat2.frob(this)}static create(){let Z=new WK(0,0,0,0);return F6.mat2.identity(Z),Z}static fromRotation(Z){let J=WK.create();return F6.mat2.fromRotation(J,Z),J}static fromScaling(Z){let J=WK.create();return F6.mat2.fromScaling(J,Z),J}add(Z){return F6.mat2.add(this,this,Z),this}adjoint(){return F6.mat2.adjoint(this,this),this}clone(){return new WK(this[0],this[1],this[2],this[3])}copy(Z){return F6.mat2.copy(this,Z),this}equals(Z){return F6.mat2.equals(this,Z)}exactEquals(Z){return F6.mat2.exactEquals(this,Z)}identity(){return F6.mat2.identity(this),this}invert(){return F6.mat2.invert(this,this),this}multiply(Z){return F6.mat2.mul(this,this,Z),this}multiplyScalar(Z){return F6.mat2.multiplyScalar(this,this,Z),this}rotate(Z){return F6.mat2.rotate(this,this,Z),this}subtract(Z){return F6.mat2.sub(this,this,Z),this}toString(){return`[${this[0]},${this[1]}][${this[2]},${this[3]}]`}transpose(){return F6.mat2.transpose(this,this),this}}var R8=r(GK(),1);class UZ extends Float32Array{constructor(Z,J,X,Y,$,Q,K,G,W){super([Z,J,X,Y,$,Q,K,G,W])}get determinant(){return R8.mat3.determinant(this)}get frobeniusNorm(){return R8.mat3.frob(this)}static create(){let Z=new UZ(0,0,0,0,0,0,0,0,0);return R8.mat3.identity(Z),Z}static fromMatrix4(Z){let J=UZ.create();return R8.mat3.fromMat4(J,Z),J}static fromQuaternion(Z){let J=UZ.create();return R8.mat3.fromQuat(J,Z),J}static fromRotation(Z){let J=UZ.create();return R8.mat3.fromRotation(J,Z),J}static fromScaling(Z){let J=UZ.create();return R8.mat3.fromScaling(J,Z),J}static fromTranslation(Z){let J=UZ.create();return R8.mat3.fromTranslation(J,Z),J}add(Z){return R8.mat3.add(this,this,Z),this}adjoint(){return R8.mat3.adjoint(this,this),this}clone(){return new UZ(this[0],this[1],this[2],this[3],this[4],this[5],this[6],this[7],this[8])}copy(Z){return R8.mat3.copy(this,Z),this}equals(Z){return R8.mat3.equals(this,Z)}exactEquals(Z){return R8.mat3.exactEquals(this,Z)}identity(){return R8.mat3.identity(this),this}invert(){return R8.mat3.invert(this,this),this}multiply(Z){return R8.mat3.mul(this,this,Z),this}multiplyScalar(Z){return R8.mat3.multiplyScalar(this,this,Z),this}transformVector(Z){return Z.transformMatrix3(this)}projection(Z,J){return R8.mat3.projection(this,Z,J),this}rotate(Z){return R8.mat3.rotate(this,this,Z),this}subtract(Z){return R8.mat3.sub(this,this,Z),this}toString(){return`[${this[0]},${this[1]},${this[2]}][${this[3]},${this[4]},${this[5]}][${this[6]},${this[7]},${this[8]}]`}transpose(){return R8.mat3.transpose(this,this),this}}var X1=r(GK(),1);class P5 extends Float32Array{constructor(Z,J,X,Y,$,Q,K,G,W,H,V,F,z,q,U,B){super([Z,J,X,Y,$,Q,K,G,W,H,V,F,z,q,U,B])}get determinant(){return X1.mat4.determinant(this)}get frobeniusNorm(){return X1.mat4.frob(this)}static create(){let Z=new P5(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return X1.mat4.identity(Z),Z}static fromQuaternion(Z){let J=P5.create();return X1.mat4.fromQuat(J,Z),J}static fromRotation(Z,J){let X=P5.create();return X1.mat4.fromRotation(X,Z,J),X}static fromRotationTranslation(Z,J){let X=P5.create();return X1.mat4.fromRotationTranslation(X,Z,J),X}static fromRotationTranslationScale(Z,J,X){let Y=P5.create();return X1.mat4.fromRotationTranslationScale(Y,Z,J,X),Y}static fromRotationTranslationScaleOrigin(Z,J,X,Y){let $=P5.create();return X1.mat4.fromRotationTranslationScaleOrigin($,Z,J,X,Y),$}static fromScaling(Z){let J=P5.create();return X1.mat4.fromScaling(J,Z),J}static fromTranslation(Z){let J=P5.create();return X1.mat4.fromTranslation(J,Z),J}static fromXRotation(Z){let J=P5.create();return X1.mat4.fromXRotation(J,Z),J}static fromYRotation(Z){let J=P5.create();return X1.mat4.fromYRotation(J,Z),J}static fromZRotation(Z){let J=P5.create();return X1.mat4.fromZRotation(J,Z),J}add(Z){return X1.mat4.add(this,this,Z),this}adjoint(){return X1.mat4.adjoint(this,this),this}clone(){return new P5(this[0],this[1],this[2],this[3],this[4],this[5],this[6],this[7],this[8],this[9],this[10],this[11],this[12],this[13],this[14],this[15])}copy(Z){return X1.mat4.copy(this,Z),this}equals(Z){return X1.mat4.equals(this,Z)}exactEquals(Z){return X1.mat4.exactEquals(this,Z)}frustrum(Z,J,X,Y,$,Q){return X1.mat4.frustum(this,Z,J,X,Y,$,Q),this}identity(){return X1.mat4.identity(this),this}invert(){return X1.mat4.invert(this,this),this}lookAt(Z,J,X){return X1.mat4.lookAt(this,Z,J,X),this}multiply(Z){return X1.mat4.mul(this,this,Z),this}multiplyScalar(Z){return X1.mat4.multiplyScalar(this,this,Z),this}orthographic(Z,J,X,Y,$,Q){return X1.mat4.ortho(this,Z,J,X,Y,$,Q),this}perspective(Z,J,X,Y){return X1.mat4.perspective(this,Z,J,X,Y),this}rotate(Z,J){return X1.mat4.rotate(this,this,Z,J),this}rotateX(Z){return X1.mat4.rotateX(this,this,Z),this}rotateY(Z){return X1.mat4.rotateY(this,this,Z),this}rotateZ(Z){return X1.mat4.rotateZ(this,this,Z),this}scale(Z){return X1.mat4.scale(this,this,Z),this}subtract(Z){return X1.mat4.sub(this,this,Z),this}targetTo(Z,J,X){return X1.mat4.targetTo(this,Z,J,X),this}toString(){return`[${this[0]},${this[1]},${this[2]},${this[3]}][${this[4]},${this[5]},${this[6]},${this[7]}][${this[8]},${this[9]},${this[10]},${this[11]}][${this[12]},${this[13]},${this[14]},${this[15]}]`}translate(Z){return X1.mat4.translate(this,this,Z),this}transpose(){return X1.mat4.transpose(this,this),this}}var f1=r(GK(),1);class M3 extends Float32Array{constructor(Z,J,X,Y){super([Z,J,X,Y])}get length(){return f1.quat.length(this)}get squaredLength(){return f1.quat.squaredLength(this)}get magnitude(){return f1.quat.length(this)}get squaredMagnitude(){return f1.quat.squaredLength(this)}get x(){return this[0]}set x(Z){this[0]=Z}get y(){return this[1]}set y(Z){this[1]=Z}get z(){return this[2]}set z(Z){this[2]=Z}get w(){return this[3]}set w(Z){this[3]=Z}static fromEuler(Z,J,X){let Y=f1.quat.fromEuler(new Float32Array(4),Z,J,X);return new M3(Y[0],Y[1],Y[2],Y[3])}static fromQuaternionLike(Z){return new M3(Z.x,Z.y,Z.z,Z.w)}clone(){return new M3(this.x,this.y,this.z,this.w)}conjugate(){return f1.quat.conjugate(this,this),this}copy(Z){return f1.quat.copy(this,Z),this}dot(Z){return f1.quat.dot(this,Z)}exponential(){return f1.quat.exp(this,this),this}equals(Z){return f1.quat.equals(this,Z)}exactEquals(Z){return f1.quat.exactEquals(this,Z)}getAngle(Z){return f1.quat.getAngle(this,Z)}identity(){return f1.quat.identity(this),this}invert(){return f1.quat.invert(this,this),this}lerp(Z,J){return f1.quat.lerp(this,this,Z,J),this}logarithm(){return f1.quat.ln(this,this),this}multiply(Z){return f1.quat.multiply(this,this,Z),this}transformVector(Z){return Z.transformQuaternion(this)}normalize(){return f1.quat.normalize(this,this),this}power(Z){return f1.quat.pow(this,this,Z),this}randomize(){return f1.quat.random(this),this}rotateX(Z){return f1.quat.rotateX(this,this,Z),this}rotateY(Z){return f1.quat.rotateY(this,this,Z),this}rotateZ(Z){return f1.quat.rotateZ(this,this,Z),this}scale(Z){return f1.quat.scale(this,this,Z),this}setAxisAngle(Z,J){return f1.quat.setAxisAngle(this,Z,J),this}slerp(Z,J){return f1.quat.slerp(this,this,Z,J),this}toString(){return`${this.x},${this.y},${this.z},${this.w}`}}var q1=r(GK(),1);class wU extends Float32Array{constructor(Z,J){super([Z,J])}get length(){return q1.vec2.length(this)}get squaredLength(){return q1.vec2.squaredLength(this)}get magnitude(){return q1.vec2.length(this)}get squaredMagnitude(){return q1.vec2.squaredLength(this)}get x(){return this[0]}set x(Z){this[0]=Z}get y(){return this[1]}set y(Z){this[1]=Z}static create(){return new wU(0,0)}add(Z){return q1.vec2.add(this,this,Z),this}angle(Z){return q1.vec2.angle(this,Z)}ceil(){return q1.vec2.ceil(this,this),this}clone(){return new wU(this.x,this.y)}copy(Z){return q1.vec2.copy(this,Z),this}distance(Z){return q1.vec2.distance(this,Z)}divide(Z){return q1.vec2.divide(this,this,Z),this}dot(Z){return q1.vec2.dot(this,Z)}equals(Z){return q1.vec2.equals(this,Z)}exactEquals(Z){return q1.vec2.exactEquals(this,Z)}floor(){return q1.vec2.floor(this,this),this}invert(){return q1.vec2.inverse(this,this),this}lerp(Z,J){return q1.vec2.lerp(this,this,Z,J),this}max(Z){return q1.vec2.max(this,this,Z),this}min(Z){return q1.vec2.min(this,this,Z),this}multiply(Z){return q1.vec2.mul(this,this,Z),this}negate(){return q1.vec2.negate(this,this),this}normalize(){return q1.vec2.normalize(this,this),this}randomize(Z){return q1.vec2.random(this,Z),this}rotate(Z,J){return q1.vec2.rotate(this,this,Z,J),this}round(){return q1.vec2.round(this,this),this}scale(Z){return q1.vec2.scale(this,this,Z),this}scaleAndAdd(Z,J){return q1.vec2.scaleAndAdd(this,this,Z,J),this}subtract(Z){return q1.vec2.sub(this,this,Z),this}toString(){return`${this.x},${this.y}`}transformMatrix2(Z){return q1.vec2.transformMat2(this,this,Z),this}transformMatrix3(Z){return q1.vec2.transformMat3(this,this,Z),this}transformMatrix4(Z){return q1.vec2.transformMat4(this,this,Z),this}zero(){return q1.vec2.zero(this),this}}var V1=r(GK(),1);class R3 extends Float32Array{constructor(Z,J,X){super([Z,J,X])}get length(){return V1.vec3.length(this)}get squaredLength(){return V1.vec3.squaredLength(this)}get magnitude(){return V1.vec3.length(this)}get squaredMagnitude(){return V1.vec3.squaredLength(this)}get x(){return this[0]}set x(Z){this[0]=Z}get y(){return this[1]}set y(Z){this[1]=Z}get z(){return this[2]}set z(Z){this[2]=Z}static create(){return new R3(0,0,0)}static fromVector3Like(Z){return new R3(Z.x,Z.y,Z.z)}add(Z){return V1.vec3.add(this,this,Z),this}ceil(){return V1.vec3.ceil(this,this),this}clone(){return new R3(this.x,this.y,this.z)}copy(Z){return V1.vec3.copy(this,Z),this}cross(Z){return V1.vec3.cross(this,this,Z),this}distance(Z){return V1.vec3.distance(this,Z)}divide(Z){return V1.vec3.div(this,this,Z),this}dot(Z){return V1.vec3.dot(this,Z)}equals(Z){return V1.vec3.equals(this,Z)}exactEquals(Z){return V1.vec3.exactEquals(this,Z)}floor(){return V1.vec3.floor(this,this),this}invert(){return V1.vec3.inverse(this,this),this}lerp(Z,J){return V1.vec3.lerp(this,this,Z,J),this}max(Z){return V1.vec3.max(this,this,Z),this}min(Z){return V1.vec3.min(this,this,Z),this}multiply(Z){return V1.vec3.mul(this,this,Z),this}negate(){return V1.vec3.negate(this,this),this}normalize(){return V1.vec3.normalize(this,this),this}randomize(Z){return V1.vec3.random(this,Z),this}rotateX(Z,J){return V1.vec3.rotateX(this,this,Z,J),this}rotateY(Z,J){return V1.vec3.rotateY(this,this,Z,J),this}rotateZ(Z,J){return V1.vec3.rotateZ(this,this,Z,J),this}round(){return V1.vec3.round(this,this),this}scale(Z){return V1.vec3.scale(this,this,Z),this}scaleAndAdd(Z,J){return V1.vec3.scaleAndAdd(this,this,Z,J),this}subtract(Z){return V1.vec3.sub(this,this,Z),this}toString(){return`${this.x},${this.y},${this.z}`}transformMatrix3(Z){return V1.vec3.transformMat3(this,this,Z),this}transformMatrix4(Z){return V1.vec3.transformMat4(this,this,Z),this}transformQuaternion(Z){return V1.vec3.transformQuat(this,this,Z),this}zero(){return V1.vec3.zero(this),this}}var NV1=r(MV1(),1);var RV1=0.099856;class jU extends _Y{faceSpeed=0;idleLoopedAnimations=[];idleLoopedAnimationsSpeed;jumpOneshotAnimations=[];moveLoopedAnimations=[];moveLoopedAnimationsSpeed;moveSpeed=0;_faceTarget;_jumpHeight=0;_moveCompletesWhenStuck=!1;_moveIgnoreAxes={};_moveStartMoveAnimations=!1;_moveStartIdleAnimationsOnCompletion=!0;_moveStoppingDistanceSquared=RV1;_moveStuckAccumulatorMs=0;_moveStuckLastPosition;_moveTarget;_onFace;_onFaceComplete;_onMove;_onMoveComplete;_stopFaceRequested=!1;_stopMoveRequested=!1;constructor(Z={}){super();this.idleLoopedAnimations=Z.idleLoopedAnimations??this.idleLoopedAnimations,this.idleLoopedAnimationsSpeed=Z.idleLoopedAnimationsSpeed??this.idleLoopedAnimationsSpeed,this.jumpOneshotAnimations=Z.jumpOneshotAnimations??this.jumpOneshotAnimations,this.moveLoopedAnimations=Z.moveLoopedAnimations??this.moveLoopedAnimations,this.moveLoopedAnimationsSpeed=Z.moveLoopedAnimationsSpeed??this.moveLoopedAnimationsSpeed}spawn(Z){super.spawn(Z),this._startIdleAnimations(Z)}face(Z,J,X){this._faceTarget=Z,this.faceSpeed=J,this._onFace=X?.faceCallback,this._onFaceComplete=X?.faceCompleteCallback}jump(Z){this._jumpHeight=Z}move(Z,J,X){this.moveSpeed=J,this._moveCompletesWhenStuck=X?.moveCompletesWhenStuck??!1,this._moveIgnoreAxes=X?.moveIgnoreAxes??{},this._moveStartIdleAnimationsOnCompletion=X?.moveStartIdleAnimationsOnCompletion??!0,this._moveStartMoveAnimations=!0,this._moveStoppingDistanceSquared=X?.moveStoppingDistance?X.moveStoppingDistance**2:RV1,this._moveTarget=Z,this._onMove=X?.moveCallback,this._onMoveComplete=X?.moveCompleteCallback,this._moveStuckAccumulatorMs=0,this._moveStuckLastPosition=void 0}stopFace(){this._stopFaceRequested=!0}stopMove(){this._stopMoveRequested=!0}tick(Z,J){if(super.tick(Z,J),!this._moveTarget&&!this._faceTarget&&!this._jumpHeight)return;if(this._moveStartMoveAnimations)this._startMoveAnimations(Z),this._moveStartMoveAnimations=!1;let X=J/1000,Y=Z.position;if(Z.isDynamic&&this._jumpHeight>0){let $=Math.abs(Z.world.simulation.gravity.y),Q=Math.sqrt(2*$*this._jumpHeight);Z.applyImpulse({x:0,y:Q*Z.mass,z:0}),this._jumpHeight=0,this._startJumpAnimations(Z)}if(this._moveTarget){let $={x:this._moveIgnoreAxes.x?0:this._moveTarget.x-Y.x,y:this._moveIgnoreAxes.y?0:this._moveTarget.y-Y.y,z:this._moveIgnoreAxes.z?0:this._moveTarget.z-Y.z},Q=$.x*$.x+$.y*$.y+$.z*$.z,K=!1;if(this._moveCompletesWhenStuck){if(this._moveStuckAccumulatorMs+=J,this._moveStuckAccumulatorMs>=500){if(this._moveStuckLastPosition){let G=Y.x-this._moveStuckLastPosition.x,W=Y.y-this._moveStuckLastPosition.y,H=Y.z-this._moveStuckLastPosition.z;K=Math.sqrt(G*G+W*W+H*H)<this.moveSpeed*0.1}this._moveStuckLastPosition=Y,this._moveStuckAccumulatorMs=0}}if(Q>this._moveStoppingDistanceSquared&&!this._stopMoveRequested&&!K){let G=Math.sqrt(Q),W=this.moveSpeed*X,V=Math.min(G,W)/G,F={x:Y.x+$.x*V,y:Y.y+$.y*V,z:Y.z+$.z*V};if(Z.setPosition(F),this._onMove)this._onMove(F,this._moveTarget)}else{if(this._moveStuckAccumulatorMs=0,this._moveStuckLastPosition=void 0,this._moveTarget=void 0,this._stopMoveRequested=!1,this._moveStartIdleAnimationsOnCompletion)this._startIdleAnimations(Z);if(this._onMoveComplete){let G=this._onMoveComplete;this._onMove=void 0,this._onMoveComplete=void 0,G(Y)}}}if(this._faceTarget){let $={x:this._faceTarget.x-Y.x,z:this._faceTarget.z-Y.z},Q=Math.atan2(-$.x,-$.z),K=Z.rotation,G=Math.atan2(2*(K.w*K.y),1-2*(K.y*K.y)),W=Q-G;while(W>Math.PI)W-=2*Math.PI;while(W<-Math.PI)W+=2*Math.PI;if(Math.abs(W)>0.01&&!this._stopFaceRequested){let H=this.faceSpeed*X,V=Math.abs(W)<H?W:Math.sign(W)*H,z=(G+V)/2,q={x:0,y:Math.fround(Math.sin(z)),z:0,w:Math.fround(Math.cos(z))};if(Z.setRotation(q),this._onFace)this._onFace(K,q)}else if(this._faceTarget=void 0,this._stopFaceRequested=!1,this._onFaceComplete){let H=this._onFaceComplete;this._onFace=void 0,this._onFaceComplete=void 0,H(Z.rotation)}}}_startIdleAnimations(Z){if(this.idleLoopedAnimationsSpeed)Z.setModelAnimationsPlaybackRate(this.idleLoopedAnimationsSpeed);Z.stopModelAnimations(this.moveLoopedAnimations),Z.stopModelAnimations(this.jumpOneshotAnimations),Z.startModelLoopedAnimations(this.idleLoopedAnimations)}_startJumpAnimations(Z){Z.stopModelAnimations(this.moveLoopedAnimations),Z.stopModelAnimations(this.idleLoopedAnimations),Z.startModelOneshotAnimations(this.jumpOneshotAnimations)}_startMoveAnimations(Z){if(this.moveLoopedAnimationsSpeed)Z.setModelAnimationsPlaybackRate(this.moveLoopedAnimationsSpeed);Z.stopModelAnimations(this.jumpOneshotAnimations),Z.stopModelAnimations(this.idleLoopedAnimations),Z.startModelLoopedAnimations(this.moveLoopedAnimations)}}class Am extends jU{_debug=!1;_entity;_maxFall=0;_maxJump=0;_maxOpenSetIterations=200;_onPathfindAbort;_onPathfindComplete;_onWaypointMoveComplete;_onWaypointMoveSkipped;_speed=0;_target;_verticalPenalty=0;_waypoints=[];_waypointNextIndex=0;_waypointStoppingDistance;_waypointTimeoutMs=2000;constructor(Z={}){super(Z)}get debug(){return this._debug}get maxFall(){return this._maxFall}get maxJump(){return this._maxJump}get maxOpenSetIterations(){return this._maxOpenSetIterations}get speed(){return this._speed}get target(){return this._target}get verticalPenalty(){return this._verticalPenalty}get waypoints(){return this._waypoints}get waypointNextIndex(){return this._waypointNextIndex}get waypointTimeoutMs(){return this._waypointTimeoutMs}pathfind(Z,J,X){if(this._target=Z,this._speed=J,this._debug=X?.debug??!1,this._maxFall=X?.maxFall?-Math.abs(X.maxFall):0,this._maxJump=X?.maxJump?Math.abs(X.maxJump):0,this._maxOpenSetIterations=X?.maxOpenSetIterations??200,this._onPathfindAbort=X?.pathfindAbortCallback,this._onPathfindComplete=X?.pathfindCompleteCallback,this._onWaypointMoveComplete=X?.waypointMoveCompleteCallback,this._onWaypointMoveSkipped=X?.waypointMoveSkippedCallback,this._verticalPenalty=X?.verticalPenalty??0,this._waypoints=[],this._waypointNextIndex=0,this._waypointStoppingDistance=X?.waypointStoppingDistance,this._waypointTimeoutMs=X?.waypointTimeoutMs??2000/J,!this._calculatePath())return!1;return this._moveToNextWaypoint(),!0}attach(Z){super.attach(Z),this._entity=Z}detach(Z){super.detach(Z),this._entity=void 0}_calculatePath(){if(!this._target||!this._entity?.world)return d.error("PathfindingEntityController._calculatePath: No target or world"),!1;let Z=this._entity.height,J=this._findGroundedStart();if(!J){if(this._debug)d.warning(`PathfindingEntityController._calculatePath: No valid grounded start found within maxFall distance, path search aborted. Start: ${this._coordinateToKey(this._target)}, Target: ${this._coordinateToKey(this._target)}`);return!1}let X={x:Math.floor(this._target.x),y:Math.floor(this._target.y),z:Math.floor(this._target.z)},Y=Math.abs(X.x-J.x),$=Math.abs(X.y-J.y),Q=Math.abs(X.z-J.z);if(Y<=2&&$<=2&&Q<=2&&!this._isNeighborCoordinateBlocked(J,X,this._entity.height))return this._waypoints=[{x:J.x+0.5,y:J.y+Z/2,z:J.z+0.5},{x:X.x+0.5,y:X.y+Z/2,z:X.z+0.5}],!0;if(J.x===X.x&&J.y===X.y&&J.z===X.z)return this._waypoints=[{x:J.x+0.5,y:J.y+Z/2,z:J.z+0.5}],!0;let G=this._coordinateToKey(J),W=new Map,H=new Map([[G,0]]),V=new Map([[G,this._pathfindingHeuristic(J,X)]]),F=new Set,z=new NV1.Heap((M,R)=>{let D=V.get(M[0])??1/0,N=V.get(R[0])??1/0;return D-N});z.push([G,J]);let q=[{x:0,y:0,z:1},{x:1,y:0,z:0},{x:0,y:0,z:-1},{x:-1,y:0,z:0},{x:1,y:0,z:1},{x:1,y:0,z:-1},{x:-1,y:0,z:1},{x:-1,y:0,z:-1}],U=[];for(let M=this._maxJump;M>=this._maxFall;M--){if(M===0)continue;let R=Math.abs(J.y+M-X.y);U.push({y:M,distanceToTargetY:R})}U.sort((M,R)=>M.distanceToTargetY-R.distanceToTargetY);let B=[...q,...U.flatMap(({y:M})=>q.map((R)=>({...R,y:M})))],L=0,w=Math.abs(X.x-J.x)+Math.abs(X.y-J.y)+Math.abs(X.z-J.z),O=Math.min(this._maxOpenSetIterations,w*20);while(!z.isEmpty()&&L<O){L++;let[M,R]=z.pop();if(R.x===X.x&&R.y===X.y&&R.z===X.z){let C=this._reconstructPath(W,R);if(this._waypoints=C.map((T)=>({x:T.x+0.5,y:T.y+Z/2,z:T.z+0.5})),this._debug)console.log(`PathfindingEntityController._calculatePath: Path found after ${L} open set iterations. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`);return!0}F.add(M);let D=H.get(M),N=new Map;for(let C of B){let T=`${C.x},${C.z}`,E=C.y<0;if(E&&N.has(T))continue;let x={x:R.x+C.x,y:R.y+C.y,z:R.z+C.z};if(Math.abs(X.x-x.x)+Math.abs(X.y-x.y)+Math.abs(X.z-x.z)>w*1.5)continue;let h=this._coordinateToKey(x);if(F.has(h))continue;let I=this._isNeighborCoordinateBlocked(R,x,this._entity.height);if(E&&I){N.set(T,!0);continue}if(I)continue;let _=Math.abs(C.x),A=Math.abs(C.y),p=Math.abs(C.z),n=A===0?0:this._verticalPenalty,o=(Math.max(_,A,p)===1&&_+A+p>1?1.4:1)+n,Q0=D+o,G0=H.get(h)??1/0;if(Q0>=G0)continue;W.set(h,R),H.set(h,Q0);let S0=Q0+this._pathfindingHeuristic(x,X);V.set(h,S0),z.push([h,x])}}if(L>=O){if(this._onPathfindAbort?.(),this._debug)d.warning(`PathfindingEntityController._calculatePath: Maximum open set iterations reached (${O}), path search aborted. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`)}else if(this._debug)d.warning(`PathfindingEntityController._calculatePath: No valid path found. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`);return this._target=void 0,this._waypoints=[],!1}_reconstructPath(Z,J){let X=[J],Y=J;while(Z.has(this._coordinateToKey(Y)))Y=Z.get(this._coordinateToKey(Y)),X.unshift(Y);return X}_coordinateToKey(Z){return`${Z.x},${Z.y},${Z.z}`}_moveToNextWaypoint(){let Z=this._waypointNextIndex>0?this._waypoints[this._waypointNextIndex-1]:void 0,J=this._waypoints[this._waypointNextIndex];if(!J||!this._entity)return;let X=0;if(this._entity.isDynamic&&Z&&J.y>Z.y){let Y=J.y-Z.y,$=Math.min(Y,this._maxJump)+0.75;this.jump($);let Q=Math.abs(this._entity.world.simulation.gravity.y),K=Math.sqrt(2*Q*$),G=Z.x+0.5,W=Z.z+0.5,H=J.x+0.5,V=J.z+0.5,F=H-G,z=V-W,q=Math.sqrt(F*F+z*z),U=K/Q,B=q/this._speed;X=Math.min(U*0.8,B)*1000}setTimeout(()=>{if(!this._entity)return;let Y=Date.now();this.face(J,this._speed),this.move(J,this._speed,{moveCompletesWhenStuck:!0,moveIgnoreAxes:{y:this._entity.isDynamic},moveStartIdleAnimationsOnCompletion:this._waypointNextIndex===this._waypoints.length-1,moveStoppingDistance:this._waypointStoppingDistance,moveCallback:()=>{if(Date.now()-Y>this._waypointTimeoutMs&&this._waypointNextIndex<this._waypoints.length-1)this._onWaypointMoveSkipped?.(J,this._waypointNextIndex),this._waypointNextIndex++,this._moveToNextWaypoint()},moveCompleteCallback:()=>{if(this._waypointNextIndex<this._waypoints.length-1)this._onWaypointMoveComplete?.(J,this._waypointNextIndex),this._waypointNextIndex++,this._moveToNextWaypoint();else this._onPathfindComplete?.()}})},X)}_pathfindingHeuristic(Z,J){return Math.abs(Z.x-J.x)+Math.abs(Z.y-J.y)+Math.abs(Z.z-J.z)}_isNeighborCoordinateBlocked(Z,J,X){if(!this._entity?.world)return!1;let Y=this._entity.world,$=Math.floor(J.x),Q=Math.floor(J.y),K=Math.floor(J.z),G=Math.floor(Z.x),W=Math.floor(Z.z);if(!Y.chunkLattice.hasBlock({x:$,y:Q-1,z:K}))return!0;for(let H=0;H<X;H++)if(Y.chunkLattice.hasBlock({x:$,y:Q+H,z:K}))return!0;if($!==G&&K!==W)for(let H=0;H<X;H++){let V=Y.chunkLattice.hasBlock({x:$,y:Q+H,z:W}),F=Y.chunkLattice.hasBlock({x:G,y:Q+H,z:K});if(V||F)return!0}return!1}_findGroundedStart(){if(!this._entity?.world)return;let{x:Z,y:J,z:X}=this._entity.position,Y={x:Math.floor(Z),y:Math.floor(J),z:Math.floor(X)};for(let $=0;$<=Math.abs(this._maxFall);$++)if(this._entity.world.chunkLattice.hasBlock({...Y,y:Y.y-$-1}))return{...Y,y:Y.y-$};return}}export{ZK6 as startServer,S31 as WorldManagerEvent,EY as WorldManager,_31 as WorldLoopEvent,LU as WorldLoop,Dm as WorldEvent,BU as World,sv as WebServerEvent,FW as WebServer,R3 as Vector3,wU as Vector2,UU as Ticker,qU as TickAllocator,YK as TelemetrySpanOperation,r1 as Telemetry,Pm as SimulationEvent,VU as Simulation,jU as SimpleEntityController,FU as SceneUIManager,tI as SceneUIEvent,tV as SceneUI,Q50 as SUPPORTED_INPUT_KEYS,BV as RigidBodyType,O$ as RigidBody,M3 as Quaternion,lw as PlayerUIEvent,iV as PlayerUI,v31 as PlayerManagerEvent,q9 as PlayerManager,nV as PlayerEvent,y7 as PlayerEntity,$50 as PlayerCameraMode,aI as PlayerCameraEvent,pV as PlayerCamera,CG as Player,E$ as PersistenceManager,Am as PathfindingEntityController,zU as ParticleEmitterManager,Mm as ParticleEmitterEvent,Rm as ParticleEmitter,nv as PORT,V50 as PLAYER_ROTATION_UPDATE_THRESHOLD,H50 as PLAYER_POSITION_UPDATE_THRESHOLD_SQ,S5 as ModelRegistry,P5 as Matrix4,UZ as Matrix3,WK as Matrix2,I31 as LightType,WU as LightManager,jm as LightEvent,Om as Light,z6 as IterationMap,x31 as GameServerEvent,$K as GameServer,O0 as EventRouter,d as ErrorHandler,eV as EntityManager,rV as EntityEvent,i8 as Entity,W50 as ENTITY_ROTATION_UPDATE_THRESHOLD,G50 as ENTITY_POSITION_UPDATE_THRESHOLD_SQ,y1 as DefaultPlayerEntityController,eI as DefaultPlayerEntity,K50 as DEFAULT_ENTITY_RIGID_BODY_OPTIONS,T4 as CollisionGroupsBuilder,yY as CollisionGroup,wV as ColliderShape,oV as ColliderMap,Q9 as Collider,qk as CoefficientCombineRule,rI as ChunkLatticeEvent,sV as ChunkLattice,W9 as Chunk,aV as ChatManager,sI as ChatEvent,Lk as BlockTypeRegistryEvent,jV as BlockTypeRegistry,Uk as BlockTypeEvent,K9 as BlockType,FK as Block,mm as BaseEntityControllerEvent,_Y as BaseEntityController,D3 as AudioManager,CP as AudioEvent,P3 as Audio};
|
|
493
|
+
`);let{connect:W,buffered:H}=await G;if(Z.emit("proxyConnect",W),this.emit("proxyConnect",W,Z),W.statusCode===200){if(Z.once("socket",DQ6),J.secureEndpoint){KU("Upgrading socket connection to TLS");let F=J.servername||J.host;return zm.connect({...z31(J,"host","path","port"),socket:Y,servername:kJ.isIP(F)?void 0:F})}return Y}Y.destroy();let V=new kJ.Socket({writable:!1});return V.readable=!0,Z.once("socket",(F)=>{KU("Replaying proxy buffer for failed request"),F.push(H),F.push(null)}),V}}ZP.__initStatic();function DQ6(Z){Z.resume()}function z31(Z,...J){let X={},Y;for(Y in Z)if(!J.includes(Y))X[Y]=Z[Y];return X}var IQ6=32768;function _Q6(Z){return new EQ6({read(){this.push(Z),this.push(null)}})}function JP(Z){let J;try{J=new URL(Z.url)}catch(W){return $8(()=>{console.warn("[@sentry/node]: Invalid dsn or tunnel option, will not send any events. The tunnel option must be a full URL when used.")}),EW(Z,()=>Promise.resolve({}))}let X=J.protocol==="https:",Y=SQ6(J,Z.proxy||(X?process.env.https_proxy:void 0)||process.env.http_proxy),$=X?TQ6:CQ6,Q=Z.keepAlive===void 0?!1:Z.keepAlive,K=Y?new ZP(Y):new $.Agent({keepAlive:Q,maxSockets:30,timeout:2000}),G=vQ6(Z,Z.httpModule??$,K);return EW(Z,G)}function SQ6(Z,J){let{no_proxy:X}=process.env;if(X?.split(",").some(($)=>Z.host.endsWith($)||Z.hostname.endsWith($)))return;else return J}function vQ6(Z,J,X){let{hostname:Y,pathname:$,port:Q,protocol:K,search:G}=new URL(Z.url);return function W(H){return new Promise((V,F)=>{EF(()=>{let z=_Q6(H.body),q={...Z.headers};if(H.body.length>IQ6)q["content-encoding"]="gzip",z=z.pipe(kQ6());let U=J.request({method:"POST",agent:X,headers:q,hostname:Y,path:`${$}${G}`,port:Q,protocol:K,ca:Z.caCerts},(B)=>{B.on("data",()=>{}),B.on("end",()=>{}),B.setEncoding("utf8");let L=B.headers["retry-after"]??null,w=B.headers["x-sentry-rate-limits"]??null;V({statusCode:B.statusCode,headers:{"retry-after":L,"x-sentry-rate-limits":Array.isArray(w)?w[0]||null:w}})});U.on("error",F),z.pipe(U)})})}}var AQ6=new Set(["false","f","n","no","off","0"]),xQ6=new Set(["true","t","y","yes","on","1"]);function XP(Z,J){let X=String(Z).toLowerCase();if(AQ6.has(X))return!1;if(xQ6.has(X))return!0;return J?.strict?null:Boolean(Z)}import{posix as hQ6,sep as fQ6}from"node:path";function F31(Z){return Z.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}function YP(Z=process.argv[1]?qx(process.argv[1]):process.cwd(),J=fQ6==="\\"){let X=J?F31(Z):Z;return(Y)=>{if(!Y)return;let $=J?F31(Y):Y,{dir:Q,base:K,ext:G}=hQ6.parse($);if(G===".js"||G===".mjs"||G===".cjs")K=K.slice(0,G.length*-1);let W=decodeURIComponent(K);if(!Q)Q=".";let H=Q.lastIndexOf("/node_modules");if(H>-1)return`${Q.slice(H+14).replace(/\//g,".")}:${W}`;if(Q.startsWith(X)){let V=Q.slice(X.length+1).replace(/\//g,".");return V?`${V}:${W}`:W}return W}}function $P(Z){if(process.env.SENTRY_RELEASE)return process.env.SENTRY_RELEASE;if(j0.SENTRY_RELEASE?.id)return j0.SENTRY_RELEASE.id;let J=process.env.GITHUB_SHA||process.env.CI_MERGE_REQUEST_SOURCE_BRANCH_SHA||process.env.CI_BUILD_REF||process.env.CI_COMMIT_SHA||process.env.BITBUCKET_COMMIT,X=process.env.APPVEYOR_PULL_REQUEST_HEAD_COMMIT||process.env.APPVEYOR_REPO_COMMIT||process.env.CODEBUILD_RESOLVED_SOURCE_VERSION||process.env.AWS_COMMIT_ID||process.env.BUILD_SOURCEVERSION||process.env.GIT_CLONE_COMMIT_HASH||process.env.BUDDY_EXECUTION_REVISION||process.env.BUILDKITE_COMMIT||process.env.CIRCLE_SHA1||process.env.CIRRUS_CHANGE_IN_REPO||process.env.CF_REVISION||process.env.CM_COMMIT||process.env.CF_PAGES_COMMIT_SHA||process.env.DRONE_COMMIT_SHA||process.env.FC_GIT_COMMIT_SHA||process.env.HEROKU_TEST_RUN_COMMIT_VERSION||process.env.HEROKU_SLUG_COMMIT||process.env.RAILWAY_GIT_COMMIT_SHA||process.env.RENDER_GIT_COMMIT||process.env.SEMAPHORE_GIT_SHA||process.env.TRAVIS_PULL_REQUEST_SHA||process.env.VERCEL_GIT_COMMIT_SHA||process.env.VERCEL_GITHUB_COMMIT_SHA||process.env.VERCEL_GITLAB_COMMIT_SHA||process.env.VERCEL_BITBUCKET_COMMIT_SHA||process.env.ZEIT_GITHUB_COMMIT_SHA||process.env.ZEIT_GITLAB_COMMIT_SHA||process.env.ZEIT_BITBUCKET_COMMIT_SHA,Y=process.env.CI_COMMIT_ID||process.env.SOURCE_COMMIT||process.env.SOURCE_VERSION||process.env.GIT_COMMIT||process.env.COMMIT_REF||process.env.BUILD_VCS_NUMBER||process.env.CI_COMMIT_SHA;return J||X||Y||Z}var QP=AO(Cx(YP()));var U31=r(X0(),1),L31=r(K1(),1);import*as q31 from"node:os";import{threadId as yQ6,isMainThread as bQ6}from"worker_threads";var gQ6=60000;class GU extends aO{constructor(Z){let J=Z.serverName||global.process.env.SENTRY_NAME||q31.hostname(),X={...Z,platform:"node",runtime:{name:"node",version:global.process.version},serverName:J};if(Z.openTelemetryInstrumentations)L31.registerInstrumentations({instrumentations:Z.openTelemetryInstrumentations});$x(X,"node"),g.log(`Initializing Sentry: process: ${process.pid}, thread: ${bQ6?"main":`worker-${yQ6}`}.`);super(X);if(this.getOptions()._experiments?.enableLogs){if(this._logOnExitFlushListener=()=>{yX(this)},J)this.on("beforeCaptureLog",(Y)=>{Y.attributes={...Y.attributes,"server.address":J}});process.on("beforeExit",this._logOnExitFlushListener)}}get tracer(){if(this._tracer)return this._tracer;let Z="@sentry/node",J=L8,X=U31.trace.getTracer(Z,J);return this._tracer=X,X}async flush(Z){let X=this.traceProvider?.activeSpanProcessor;if(X)await X.forceFlush();if(this.getOptions().sendClientReports)this._flushOutcomes();return super.flush(Z)}close(Z){if(this._clientReportInterval)clearInterval(this._clientReportInterval);if(this._clientReportOnExitFlushListener)process.off("beforeExit",this._clientReportOnExitFlushListener);if(this._logOnExitFlushListener)process.off("beforeExit",this._logOnExitFlushListener);return super.close(Z)}startClientReportTracking(){let Z=this.getOptions();if(Z.sendClientReports)this._clientReportOnExitFlushListener=()=>{this._flushOutcomes()},this._clientReportInterval=setInterval(()=>{m0&&g.log("Flushing client reports based on interval."),this._flushOutcomes()},Z.clientReportFlushInterval??gQ6).unref(),process.on("beforeExit",this._clientReportOnExitFlushListener)}_getTraceInfoFromScope(Z){if(!Z)return[void 0,void 0];return h41(this,Z)}}var F7=r(X0(),1),B31=r(iy(),1),w31=r(sy(),1),O3=r(P1(),1);var j31=r($y(),1);import mQ6 from"module";var Fm=1e6;function KP(Z,J={}){if(Z.getOptions().debug)M31();let X=dQ6(Z,J);Z.traceProvider=X}function qm(){let[Z=0,J=0]=process.versions.node.split(".").map(Number);if(Z>=21||Z===20&&J>=6||Z===18&&J>=19){if(!j0._sentryEsmLoaderHookRegistered)try{let{addHookMessagePort:X}=j31.createAddHookMessageChannel();mQ6.register("import-in-the-middle/hook.mjs",import.meta.url,{data:{addHookMessagePort:X,include:[]},transferList:[X]})}catch(X){g.warn("Failed to register ESM hook",X)}}else $8(()=>{console.warn(`[Sentry] You are using Node.js v${process.versions.node} in ESM mode ("import syntax"). The Sentry Node.js SDK is not compatible with ESM in Node.js versions before 18.19.0 or before 20.6.0. Please either build your application with CommonJS ("require() syntax"), or upgrade your Node.js version.`)})}function O31(Z={}){let{debug:J}=Z;if(J)g.enable(),M31();if(!U4())qm();uQ6(Z.integrations).forEach((X)=>{if(X(),J)g.log(`[Sentry] Preloaded ${X.id} instrumentation`)})}function uQ6(Z){let J=H31();if(!Z)return J;return J.filter((X)=>Z.includes(X.id))}function dQ6(Z,J={}){let X=new w31.BasicTracerProvider({sampler:new Lb(Z),resource:new B31.Resource({[O3.ATTR_SERVICE_NAME]:"node",[O3.SEMRESATTRS_SERVICE_NAMESPACE]:"sentry",[O3.ATTR_SERVICE_VERSION]:L8}),forceFlushTimeoutMillis:500,spanProcessors:[new Ub({timeout:cQ6(Z.getOptions().maxSpanWaitDuration)}),...J.spanProcessors||[]]});return F7.trace.setGlobalTracerProvider(X),F7.propagation.setGlobalPropagator(new Hb),F7.context.setGlobalContextManager(new rN),X}function cQ6(Z){if(Z==null)return;if(Z>Fm)return m0&&g.warn(`\`maxSpanWaitDuration\` is too high, using the maximum value of ${Fm}`),Fm;else if(Z<=0||Number.isNaN(Z)){m0&&g.warn("`maxSpanWaitDuration` must be a positive number, using default value instead.");return}return Z}function M31(){let Z=new Proxy(g,{get(J,X,Y){return Reflect.get(J,X==="verbose"?"debug":X,Y)}});F7.diag.disable(),F7.diag.setLogger(Z,F7.DiagLogLevel.DEBUG)}function lQ6(){return U4()?[cR()]:[]}function Um(){return[fF(),hF(),yF(),bF(),gF(),SR(),hR(),lR(),pR(),gR(),dR(),bR(),sN(),W31(),...lQ6()]}function Lm(Z){return[...Um(),...z5(Z)?tN():[]]}function GP(Z={}){return N31(Z,Lm)}function R31(Z={}){return N31(Z,()=>[])}function N31(Z={},J){let X=pQ6(Z,J);if(X.debug===!0)if(m0)g.enable();else $8(()=>{console.warn("[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.")});if(!U4()&&X.registerEsmLoaderHooks!==!1)qm();if(ER(),l0().update(X.initialScope),X.spotlight&&!X.integrations.some(({name:Q})=>Q===og))X.integrations.push(yN({sidecarUrl:typeof X.spotlight==="string"?X.spotlight:void 0}));let $=new GU(X);if(l0().setClient($),$.init(),g.log(`Running in ${U4()?"CommonJS":"ESM"} mode.`),$.startClientReportTracking(),aQ6(),!X.skipOpenTelemetrySetup)KP($,{spanProcessors:X.openTelemetrySpanProcessors}),Bm();return T41($),f41($),$}function Bm(){if(!m0)return;let Z=_41(),J=["SentryContextManager","SentryPropagator"];if(z5())J.push("SentrySpanProcessor");for(let X of J)if(!Z.includes(X))g.error(`You have to set up the ${X}. Without this, the OpenTelemetry & Sentry integration will not work properly.`);if(!Z.includes("SentrySampler"))g.warn("You have to set up the SentrySampler. Without this, the OpenTelemetry & Sentry integration may still work, but sample rates set for the Sentry SDK will not be respected. If you use a custom sampler, make sure to use `wrapSamplingDecision`.")}function pQ6(Z,J){let X=iQ6(Z.release),Y=Z.spotlight??XP(process.env.SENTRY_SPOTLIGHT,{strict:!0})??process.env.SENTRY_SPOTLIGHT,$=nQ6(Z.tracesSampleRate),Q={...Z,dsn:Z.dsn??process.env.SENTRY_DSN,environment:Z.environment??process.env.SENTRY_ENVIRONMENT,sendClientReports:Z.sendClientReports??!0,transport:Z.transport??JP,stackParser:UA(Z.stackParser||QP),release:X,tracesSampleRate:$,spotlight:Y,debug:XP(Z.debug??process.env.SENTRY_DEBUG)},K=Z.integrations,G=Z.defaultIntegrations??J(Q);return{...Q,integrations:nA({defaultIntegrations:G,integrations:K})}}function iQ6(Z){if(Z!==void 0)return Z;let J=$P();if(J!==void 0)return J;return}function nQ6(Z){if(Z!==void 0)return Z;let J=process.env.SENTRY_TRACES_SAMPLE_RATE;if(!J)return;let X=parseFloat(J);return isFinite(X)?X:void 0}function aQ6(){if(XP(process.env.SENTRY_USE_ENVIRONMENT)!==!1){let Z=process.env.SENTRY_TRACE,J=process.env.SENTRY_BAGGAGE,X=QQ(Z,J);l0().setPropagationContext(X)}}var sQ6=[["january","1"],["february","2"],["march","3"],["april","4"],["may","5"],["june","6"],["july","7"],["august","8"],["september","9"],["october","10"],["november","11"],["december","12"],["jan","1"],["feb","2"],["mar","3"],["apr","4"],["may","5"],["jun","6"],["jul","7"],["aug","8"],["sep","9"],["oct","10"],["nov","11"],["dec","12"],["sunday","0"],["monday","1"],["tuesday","2"],["wednesday","3"],["thursday","4"],["friday","5"],["saturday","6"],["sun","0"],["mon","1"],["tue","2"],["wed","3"],["thu","4"],["fri","5"],["sat","6"]];function XK(Z){return sQ6.reduce((J,[X,Y])=>J.replace(new RegExp(X,"gi"),Y),Z)}var P31="Automatic instrumentation of CronJob only supports crontab string";function D31(Z,J){let X=!1;return new Proxy(Z,{construct(Y,$){let[Q,K,G,W,H,...V]=$;if(typeof Q!=="string")throw new Error(P31);if(X)throw new Error(`A job named '${J}' has already been scheduled`);X=!0;let F=XK(Q);async function z(q,U){return o7(J,async()=>{try{await K(q,U)}catch(B){throw F1(B),B}},{schedule:{type:"crontab",value:F},timezone:H||void 0})}return new Y(Q,z,G,W,H,...V)},get(Y,$){if($==="from")return(Q)=>{let{cronTime:K,onTick:G,timeZone:W}=Q;if(typeof K!=="string")throw new Error(P31);if(X)throw new Error(`A job named '${J}' has already been scheduled`);X=!0;let H=XK(K);return Q.onTick=async(V,F)=>{return o7(J,async()=>{try{await G(V,F)}catch(z){throw F1(z),z}},{schedule:{type:"crontab",value:H},timezone:W||void 0})},Y.from(Q)};else return Y[$]}})}function C31(Z){return new Proxy(Z,{get(J,X){if(X==="schedule"&&J.schedule)return new Proxy(J.schedule,{apply(Y,$,Q){let[K,G,W]=Q,H=W?.name,V=W?.timezone;if(!H)throw new Error('Missing "name" for scheduled job. A name is required for Sentry check-in monitoring.');let F=async()=>{return o7(H,async()=>{try{return await G()}catch(z){throw F1(z),z}},{schedule:{type:"crontab",value:XK(K)},timezone:V})};return Y.apply($,[K,F,W])}});else return J[X]}})}function T31(Z){return new Proxy(Z,{get(J,X){if(X==="scheduleJob")return new Proxy(J.scheduleJob,{apply(Y,$,Q){let[K,G,W]=Q;if(typeof K!=="string"||typeof G!=="string"||typeof W!=="function")throw new Error("Automatic instrumentation of 'node-schedule' requires the first parameter of 'scheduleJob' to be a job name string and the second parameter to be a crontab string");let H=K,V=G;async function F(){return o7(H,async()=>{await W?.()},{schedule:{type:"crontab",value:XK(V)}})}return Y.apply($,[H,V,F])}});return J[X]}})}var E31={instrumentCron:D31,instrumentNodeCron:C31,instrumentNodeSchedule:T31};var YK;((L)=>{L.BUILD_PACKETS="build_packets";L.ENTITIES_EMIT_UPDATES="entities_emit_updates";L.ENTITIES_TICK="entities_tick";L.NETWORK_SYNCHRONIZE="network_synchronize";L.NETWORK_SYNCHRONIZE_CLEANUP="network_synchronize_cleanup";L.PHYSICS_CLEANUP="physics_cleanup";L.PHYSICS_STEP="physics_step";L.RELEASE_TICK_ALLOCATION="release_tick_allocation";L.SEND_ALL_PACKETS="send_all_packets";L.SEND_PACKETS="send_packets";L.SERIALIZE_FREE_BUFFERS="serialize_free_buffers";L.SERIALIZE_PACKETS="serialize_packets";L.SERIALIZE_PACKETS_ENCODE="serialize_packets_encode";L.SIMULATION_STEP="simulation_step";L.TICKER_TICK="ticker_tick";L.WORLD_TICK="world_tick"})(YK||={});class r1{static getProcessStats(Z=!1){let J=process.memoryUsage(),X={jsHeapSizeMb:{value:J.heapUsed/1024/1024,unit:"megabyte"},jsHeapCapacityMb:{value:J.heapTotal/1024/1024,unit:"megabyte"},jsHeapUsagePercent:{value:J.heapUsed/J.heapTotal,unit:"percent"},processHeapSizeMb:{value:J.heapUsed/1024/1024,unit:"megabyte"},rssSizeMb:{value:J.rss/1024/1024,unit:"megabyte"}};if(Z)return X;return Object.fromEntries(Object.entries(X).map(([Y,$])=>[Y,$.value]))}static initializeSentry(Z,J=50){GP({dsn:Z,release:av,environment:process.env.NODE_ENV||"development",tracesSampleRate:1,initialScope:{tags:{gameId:process.env.HYTOPIA_GAME_ID??"unknown",gameSlug:process.env.HYTOPIA_GAME_SLUG??"unknown",lobbyId:process.env.HYTOPIA_LOBBY_ID??"unknown",region:process.env.REGION??"unknown"}},beforeSend:(X)=>{return X.extra=r1.getProcessStats(),X},beforeSendTransaction:(X)=>{if(X.contexts?.trace?.op==="ticker_tick"){let $=X?.start_timestamp,Q=X?.timestamp;if(!$||!Q)return null;if((Q-$)*1000>J)return X.measurements=r1.getProcessStats(!0),X}return null}})}static startSpan(Z,J){if(vF())return e9({attributes:Z.attributes,name:Z.operation,op:Z.operation},J);else return J()}static sentry(){return wm}}var k31=new f$,oQ6=5000;class i4 extends O0{static _cachedPacketsSerializedBuffer=new Map;_closeTimeout=null;_wrtcDirectTransport=null;_wrtcClientServerTransport=null;_wrtcClientServerDataProducers=[];_wrtcClientServerDataConsumers=[];_wrtcServerClientTransport=null;_wrtcServerClientReliableDataProducer=null;_wrtcServerClientUnreliableDataProducer=null;_wrtcServerClientDataConsumers=[];_ws;id;constructor(Z,J){super();this.id=w40(),this.onPacket(Y0.PacketId.CONNECTION,this._onConnectionPacket),this.onPacket(Y0.PacketId.HEARTBEAT,this._onHeartbeatPacket),this.bindWs(Z),O0.globalInstance.emit("CONNECTION.OPENED",{connection:this,req:J})}static clearCachedPacketsSerializedBuffers(){if(i4._cachedPacketsSerializedBuffer.size>0)i4._cachedPacketsSerializedBuffer.clear()}static serializePackets(Z){for(let X of Z)if(!Y0.isValidPacket(X))return d.error(`Connection.serializePackets(): Invalid packet payload: ${JSON.stringify(X)}`);let J=i4._cachedPacketsSerializedBuffer.get(Z);if(J)return J;return r1.startSpan({operation:"serialize_packets",attributes:{packets:Z.length,packetIds:Z.map((X)=>X[0]).join(",")}},(X)=>{let Y=r1.startSpan({operation:"serialize_packets_encode"},()=>k31.pack(Z));return X?.setAttribute("serializedBytes",Y.byteLength),i4._cachedPacketsSerializedBuffer.set(Z,Y),Y})}bindWs(Z){let J=!!this._ws;if(J&&this._closeTimeout)clearTimeout(this._closeTimeout),this._closeTimeout=null;if(this._ws)this._ws.onmessage=()=>{},this._ws.onclose=()=>{},this._ws.onerror=()=>{},this.send([Y0.createPacket(Y0.bidirectionalPackets.connectionPacketDefinition,{k:!0})]);if(this._ws=Z,this._ws.binaryType="nodebuffer",this._ws.onmessage=(X)=>this._onMessage(X.data),this._ws.onclose=this._onWsClose,this._ws.onerror=this._onWsError,this.send([Y0.createPacket(Y0.bidirectionalPackets.connectionPacketDefinition,{i:this.id})],!0,!0),J)this.emitWithGlobal("CONNECTION.RECONNECTED",{connection:this});if(a7.instance.isWrtcEnabled)this._upgradeToWRTC()}closeWrtc(){this._closeWrtcClientServerTransport(),this._closeWrtcServerClientTransport()}disconnect(){try{this._ws.close()}catch(Z){d.error(`Connection.disconnect(): Connection disconnect failed. Error: ${Z}`)}}onPacket(Z,J){this.on("CONNECTION.PACKET_RECEIVED",({packet:X})=>{if(X[0]===Z)J(X)})}send(Z,J=!0,X=!1){if(this._closeTimeout)return;if(this._ws.readyState!==U_.default.OPEN)return;r1.startSpan({operation:"send_packets",attributes:{forceWs:X?"true":"false",wrtcConnected:this._wrtcServerClientTransport?.iceState==="completed"?"true":"false"}},()=>{try{let Y=i4.serializePackets(Z);if(!Y)return;if(this._wrtcServerClientTransport?.iceState==="completed"&&Y.length<(this._wrtcServerClientTransport?.sctpParameters?.maxMessageSize??0)&&!X)try{(J?this._wrtcServerClientReliableDataProducer:this._wrtcServerClientUnreliableDataProducer).send(Y)}catch{this._ws.send(Y)}else this._ws.send(Y);this.emitWithGlobal("CONNECTION.PACKETS_SENT",{connection:this,packets:Z})}catch(Y){d.error(`Connection.send(): Packet send failed. Error: ${Y}`)}})}_closeWrtcClientServerTransport(){this._wrtcDirectTransport?.close(),this._wrtcDirectTransport=null,this._wrtcClientServerTransport?.close(),this._wrtcClientServerTransport=null,this._wrtcClientServerDataProducers.forEach((Z)=>Z.close()),this._wrtcClientServerDataProducers=[],this._wrtcClientServerDataConsumers.forEach((Z)=>Z.close()),this._wrtcClientServerDataConsumers=[]}_closeWrtcServerClientTransport(){this._wrtcServerClientTransport?.close(),this._wrtcServerClientTransport=null,this._wrtcServerClientDataConsumers.forEach((Z)=>Z.close()),this._wrtcServerClientDataConsumers=[],this._wrtcServerClientReliableDataProducer?.close(),this._wrtcServerClientReliableDataProducer=null,this._wrtcServerClientUnreliableDataProducer?.close(),this._wrtcServerClientUnreliableDataProducer=null}_onConnectionPacket=async(Z)=>{let J=Z[1],X=J.c,Y=J.d;if(X){let{i:$,d:Q}=X,K=!1;if($==this._wrtcClientServerTransport?.id)await this._wrtcClientServerTransport.connect({dtlsParameters:Q}),K=!0;if($==this._wrtcServerClientTransport?.id)await this._wrtcServerClientTransport.connect({dtlsParameters:Q}),K=!0;if(K)this.send([Y0.createPacket(Y0.bidirectionalPackets.connectionPacketDefinition,{ca:{i:$}})])}if(Y)for(let $ of Y){let{s:Q,l:K}=$,G=await this._wrtcClientServerTransport.produceData({label:K,sctpStreamParameters:Q}),W=await this._wrtcDirectTransport.consumeData({dataProducerId:G.id});this._wrtcClientServerDataProducers.push(G),this._wrtcClientServerDataConsumers.push(W),W.on("message",(H)=>this._onMessage(H)),this.send([Y0.createPacket(Y0.bidirectionalPackets.connectionPacketDefinition,{pa:{i:G.id,l:K}})])}};_onHeartbeatPacket=()=>{this.send([Y0.createPacket(Y0.bidirectionalPackets.heartbeatPacketDefinition,null)],!0,!0)};_onMessage=(Z)=>{try{let J=this._deserialize(Z);if(!J)return;this.emitWithGlobal("CONNECTION.PACKET_RECEIVED",{connection:this,packet:J})}catch(J){d.error(`Connection._ws.onmessage(): Error: ${J}`)}};_onWrtcIceStateChange=(Z,J)=>{if(["disconnected","closed"].includes(J)){if(Z==this._wrtcClientServerTransport)this._closeWrtcClientServerTransport();else if(Z==this._wrtcServerClientTransport)this._closeWrtcServerClientTransport()}};_onWsClose=()=>{this.closeWrtc(),this.emitWithGlobal("CONNECTION.DISCONNECTED",{connection:this}),this._closeTimeout=setTimeout(()=>{this.emitWithGlobal("CONNECTION.CLOSED",{connection:this}),this.offAll()},oQ6)};_onWsError=(Z)=>{this.emitWithGlobal("CONNECTION.ERROR",{connection:this,error:Z})};_upgradeToWRTC=async()=>{let Z=await a7.instance.createWrtcTransports();if(!Z)return!1;let{directTransport:J,clientServerTransport:X,serverClientTransport:Y}=Z;this._wrtcDirectTransport=J,this._wrtcClientServerTransport=X,this._wrtcClientServerTransport.on("icestatechange",(K)=>{this._onWrtcIceStateChange(this._wrtcClientServerTransport,K)}),this._wrtcServerClientTransport=Y,this._wrtcServerClientTransport.on("icestatechange",(K)=>{this._onWrtcIceStateChange(this._wrtcServerClientTransport,K)}),this._wrtcServerClientReliableDataProducer=await this._wrtcServerClientTransport.produceData({label:"scr",sctpStreamParameters:{streamId:0,ordered:!0}}),this._wrtcServerClientUnreliableDataProducer=await this._wrtcServerClientTransport.produceData({label:"scu",sctpStreamParameters:{streamId:1,ordered:!1,maxPacketLifeTime:35}});let $=await this._wrtcServerClientTransport.consumeData({dataProducerId:this._wrtcServerClientReliableDataProducer.id}),Q=await this._wrtcServerClientTransport.consumeData({dataProducerId:this._wrtcServerClientUnreliableDataProducer.id});return this._wrtcServerClientDataConsumers.push($,Q),this.send([Y0.createPacket(Y0.bidirectionalPackets.connectionPacketDefinition,{d:[{i:$.id,pi:$.dataProducerId,l:"scr",s:$.sctpStreamParameters},{i:Q.id,pi:Q.dataProducerId,l:"scu",s:Q.sctpStreamParameters}],t:[{i:this._wrtcClientServerTransport.id,f:"cs",d:this._wrtcClientServerTransport.dtlsParameters,ic:this._wrtcClientServerTransport.iceCandidates,ip:this._wrtcClientServerTransport.iceParameters,s:this._wrtcClientServerTransport.sctpParameters},{i:this._wrtcServerClientTransport.id,f:"sc",d:this._wrtcServerClientTransport.dtlsParameters,ic:this._wrtcServerClientTransport.iceCandidates,ip:this._wrtcServerClientTransport.iceParameters,s:this._wrtcServerClientTransport.sctpParameters}]})]),!0};_deserialize(Z){let J=k31.unpack(Z);if(!J||typeof J!=="object"||typeof J[0]!=="number")return d.error(`Connection._deserialize(): Invalid packet format. Packet: ${JSON.stringify(J)}`);if(!Y0.isValidPacket(J))return d.error(`Connection._deserialize(): Invalid packet payload. Packet: ${JSON.stringify(J)}`);return J}}class WU{_lights=new Map;_nextLightId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}despawnEntityAttachedLights(Z){this.getAllEntityAttachedLights(Z).forEach((J)=>{J.despawn()})}getAllLights(Z=!1){return Z?this._world.tickAllocator.getArray(this._lights.values()):Array.from(this._lights.values())}getAllEntityAttachedLights(Z){return this.getAllLights().filter((J)=>J.attachedToEntity===Z)}registerLight(Z){if(Z.id!==void 0)return Z.id;let J=this._nextLightId;return this._lights.set(J,Z),this._nextLightId++,J}unregisterLight(Z){if(Z.id===void 0)return;this._lights.delete(Z.id)}}class z6{_map=new Map;_values=[];_isDirty=!1;get size(){return this._map.size}get valuesArray(){if(this._isDirty)this._syncArray();return this._values}get(Z){return this._map.get(Z)}set(Z,J){let X=this._map.has(Z);if(this._map.set(Z,J),!X)this._values.push(J);else this._isDirty=!0;return this}has(Z){return this._map.has(Z)}delete(Z){let J=this._map.delete(Z);if(J)this._isDirty=!0;return J}clear(){this._map.clear(),this._values.length=0,this._isDirty=!1}forEach(Z,J){this._map.forEach((X,Y)=>{Z.call(J,X,Y,this)})}keys(){return this._map.keys()}values(){return this._map.values()}entries(){return this._map.entries()}[Symbol.iterator](){return this._map[Symbol.iterator]()}_syncArray(){this._values.length=0;for(let Z of this._map.values())this._values.push(Z);this._isDirty=!1}}var I31;((X)=>{X[X.POINTLIGHT=0]="POINTLIGHT";X[X.SPOTLIGHT=1]="SPOTLIGHT"})(I31||={});var jm;((z)=>{z.DESPAWN="LIGHT.DESPAWN";z.SET_ANGLE="LIGHT.SET_ANGLE";z.SET_ATTACHED_TO_ENTITY="LIGHT.SET_ATTACHED_TO_ENTITY";z.SET_COLOR="LIGHT.SET_COLOR";z.SET_DISTANCE="LIGHT.SET_DISTANCE";z.SET_INTENSITY="LIGHT.SET_INTENSITY";z.SET_OFFSET="LIGHT.SET_OFFSET";z.SET_PENUMBRA="LIGHT.SET_PENUMBRA";z.SET_POSITION="LIGHT.SET_POSITION";z.SET_TRACKED_ENTITY="LIGHT.SET_TRACKED_ENTITY";z.SET_TRACKED_POSITION="LIGHT.SET_TRACKED_POSITION";z.SPAWN="LIGHT.SPAWN"})(jm||={});class Om extends O0{_id;_angle;_attachedToEntity;_color;_distance;_intensity;_offset;_penumbra;_position;_trackedEntity;_trackedPosition;_type;_world;constructor(Z){if(!!Z.attachedToEntity===!!Z.position)d.fatalError("Either attachedToEntity or position must be set, but not both.");super();d.warning("WARNING: Lights are poorly optimized at this time. Using more than a few lights in your game can cause extremely bad performance (FPS) issues. Use lights sparingly!"),this._angle=Z.angle,this._attachedToEntity=Z.attachedToEntity,this._color=Z.color??{r:255,g:255,b:255},this._distance=Z.distance,this._intensity=Z.intensity??1,this._offset=Z.offset,this._penumbra=Z.penumbra,this._position=Z.position,this._trackedEntity=Z.trackedEntity,this._trackedPosition=Z.trackedPosition,this._type=Z.type??0}get id(){return this._id}get angle(){return this._angle}get attachedToEntity(){return this._attachedToEntity}get color(){return this._color}get distance(){return this._distance}get intensity(){return this._intensity}get isSpawned(){return this._id!==void 0}get offset(){return this._offset}get penumbra(){return this._penumbra}get position(){return this._position}get trackedEntity(){return this._trackedEntity}get trackedPosition(){return this._trackedPosition}get type(){return this._type}get world(){return this._world}setAngle(Z){if(this._angle===Z)return;if(this._angle=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ANGLE",{light:this,angle:Z})}setAttachedToEntity(Z){if(!Z.isSpawned)return d.error(`Light.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);if(this._attachedToEntity===Z)return;if(this._attachedToEntity=Z,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ATTACHED_TO_ENTITY",{light:this,entity:Z})}setColor(Z){if(this._color.r===Z.r&&this._color.g===Z.g&&this._color.b===Z.b)return;if(this._color=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_COLOR",{light:this,color:Z})}setDistance(Z){if(this._distance===Z)return;if(this._distance=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_DISTANCE",{light:this,distance:Z})}setIntensity(Z){if(this._intensity===Z)return;if(this._intensity=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_INTENSITY",{light:this,intensity:Z})}setOffset(Z){if(this._offset&&this._offset.x===Z.x&&this._offset.y===Z.y&&this._offset.z===Z.z)return;if(this._offset=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_OFFSET",{light:this,offset:Z})}setPenumbra(Z){if(this._penumbra===Z)return;if(this._penumbra=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_PENUMBRA",{light:this,penumbra:Z})}setPosition(Z){if(this._position&&this._position.x===Z.x&&this._position.y===Z.y&&this._position.z===Z.z)return;if(this._position=Z,this._attachedToEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_POSITION",{light:this,position:Z})}setTrackedEntity(Z){if(!Z.isSpawned)return d.error(`Light.setTrackedEntity(): Entity ${Z.id} is not spawned!`);if(this._trackedEntity===Z)return;if(this._trackedEntity=Z,this._trackedPosition=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_ENTITY",{light:this,entity:Z})}setTrackedPosition(Z){if(this._trackedPosition===Z)return;if(this._trackedPosition=Z,this._trackedEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_POSITION",{light:this,position:Z})}despawn(){if(!this.isSpawned||!this._world)return;this._world.lightManager.unregisterLight(this),this.emitWithWorld(this._world,"LIGHT.DESPAWN",{light:this}),this._id=void 0,this._world=void 0}spawn(Z){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return d.error(`Light.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning Light!`);this._id=Z.lightManager.registerLight(this),this._world=Z,this.emitWithWorld(Z,"LIGHT.SPAWN",{light:this})}serialize(){if(!this._world)d.fatalError("Light.serialize(): Light is not in a world and cannot be serialized!");return P0.serializeLight(this,this._world.tickAllocator)}}var Mm;((A)=>{A.DESPAWN="PARTICLE_EMITTER.DESPAWN";A.SET_ALPHA_TEST="PARTICLE_EMITTER.SET_ALPHA_TEST";A.SET_ATTACHED_TO_ENTITY="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY";A.SET_ATTACHED_TO_ENTITY_NODE_NAME="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME";A.SET_COLOR_END="PARTICLE_EMITTER.SET_COLOR_END";A.SET_COLOR_END_VARIANCE="PARTICLE_EMITTER.SET_COLOR_END_VARIANCE";A.SET_COLOR_START="PARTICLE_EMITTER.SET_COLOR_START";A.SET_COLOR_START_VARIANCE="PARTICLE_EMITTER.SET_COLOR_START_VARIANCE";A.SET_GRAVITY="PARTICLE_EMITTER.SET_GRAVITY";A.SET_LIFETIME="PARTICLE_EMITTER.SET_LIFETIME";A.SET_LIFETIME_VARIANCE="PARTICLE_EMITTER.SET_LIFETIME_VARIANCE";A.SET_MAX_PARTICLES="PARTICLE_EMITTER.SET_MAX_PARTICLES";A.SET_OFFSET="PARTICLE_EMITTER.SET_OFFSET";A.SET_OPACITY_END="PARTICLE_EMITTER.SET_OPACITY_END";A.SET_OPACITY_END_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE";A.SET_OPACITY_START="PARTICLE_EMITTER.SET_OPACITY_START";A.SET_OPACITY_START_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE";A.SET_PAUSED="PARTICLE_EMITTER.SET_PAUSED";A.SET_POSITION="PARTICLE_EMITTER.SET_POSITION";A.SET_POSITION_VARIANCE="PARTICLE_EMITTER.SET_POSITION_VARIANCE";A.SET_RATE="PARTICLE_EMITTER.SET_RATE";A.SET_RATE_VARIANCE="PARTICLE_EMITTER.SET_RATE_VARIANCE";A.SET_SIZE_END="PARTICLE_EMITTER.SET_SIZE_END";A.SET_SIZE_END_VARIANCE="PARTICLE_EMITTER.SET_SIZE_END_VARIANCE";A.SET_SIZE_START="PARTICLE_EMITTER.SET_SIZE_START";A.SET_SIZE_START_VARIANCE="PARTICLE_EMITTER.SET_SIZE_START_VARIANCE";A.SET_TEXTURE_URI="PARTICLE_EMITTER.SET_TEXTURE_URI";A.SET_TRANSPARENT="PARTICLE_EMITTER.SET_TRANSPARENT";A.SET_VELOCITY="PARTICLE_EMITTER.SET_VELOCITY";A.SET_VELOCITY_VARIANCE="PARTICLE_EMITTER.SET_VELOCITY_VARIANCE";A.SPAWN="PARTICLE_EMITTER.SPAWN"})(Mm||={});class Rm extends O0{_id;_alphaTest;_attachedToEntity;_attachedToEntityNodeName;_colorEnd;_colorEndVariance;_colorStart;_colorStartVariance;_gravity;_lifetime;_lifetimeVariance;_maxParticles;_offset;_opacityEnd;_opacityEndVariance;_opacityStart;_opacityStartVariance;_paused;_position;_positionVariance;_rate;_rateVariance;_sizeEnd;_sizeEndVariance;_sizeStart;_sizeStartVariance;_sizeVariance;_textureUri;_transparent;_velocity;_velocityVariance;_world;constructor(Z){if(!!Z.attachedToEntity===!!Z.position)d.fatalError("Either attachedToEntity or position must be set, but not both.");if(!Z.textureUri)d.fatalError("ParticleEmitter.constructor(): textureUri must be provided.");super();this._alphaTest=Z.alphaTest??0.5,this._attachedToEntity=Z.attachedToEntity,this._attachedToEntityNodeName=Z.attachedToEntityNodeName,this._colorEnd=Z.colorEnd,this._colorEndVariance=Z.colorEndVariance,this._colorStart=Z.colorStart,this._colorStartVariance=Z.colorStartVariance,this._gravity=Z.gravity,this._lifetime=Z.lifetime,this._lifetimeVariance=Z.lifetimeVariance,this._maxParticles=Z.maxParticles,this._offset=Z.offset,this._opacityEnd=Z.opacityEnd,this._opacityEndVariance=Z.opacityEndVariance,this._opacityStart=Z.opacityStart,this._opacityStartVariance=Z.opacityStartVariance,this._paused=!1,this._position=Z.position,this._positionVariance=Z.positionVariance,this._rate=Z.rate,this._rateVariance=Z.rateVariance,this._sizeEnd=Z.sizeEnd,this._sizeEndVariance=Z.sizeEndVariance,this._sizeStart=Z.sizeStart,this._sizeStartVariance=Z.sizeStartVariance,this._textureUri=Z.textureUri,this._transparent=Z.transparent,this._velocity=Z.velocity,this._velocityVariance=Z.velocityVariance}get id(){return this._id}get alphaTest(){return this._alphaTest}get attachedToEntity(){return this._attachedToEntity}get attachedToEntityNodeName(){return this._attachedToEntityNodeName}get colorEnd(){return this._colorEnd}get colorEndVariance(){return this._colorEndVariance}get colorStart(){return this._colorStart}get colorStartVariance(){return this._colorStartVariance}get gravity(){return this._gravity}get isSpawned(){return this._id!==void 0}get lifetime(){return this._lifetime}get lifetimeVariance(){return this._lifetimeVariance}get maxParticles(){return this._maxParticles}get offset(){return this._offset}get opacityEnd(){return this._opacityEnd}get opacityEndVariance(){return this._opacityEndVariance}get opacityStart(){return this._opacityStart}get opacityStartVariance(){return this._opacityStartVariance}get paused(){return this._paused}get position(){return this._position}get positionVariance(){return this._positionVariance}get rate(){return this._rate}get rateVariance(){return this._rateVariance}get sizeEnd(){return this._sizeEnd}get sizeEndVariance(){return this._sizeEndVariance}get sizeStart(){return this._sizeStart}get sizeStartVariance(){return this._sizeStartVariance}get sizeVariance(){return this._sizeVariance}get textureUri(){return this._textureUri}get transparent(){return this._transparent}get velocity(){return this._velocity}get velocityVariance(){return this._velocityVariance}get world(){return this._world}setAlphaTest(Z){if(this._alphaTest===Z)return;if(this._alphaTest=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ALPHA_TEST",{particleEmitter:this,alphaTest:Z})}setAttachedToEntity(Z){if(!Z.isSpawned)return d.error(`ParticleEmitter.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);if(this._attachedToEntity===Z)return;if(this._attachedToEntity=Z,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY",{particleEmitter:this,entity:Z})}setAttachedToEntityNodeName(Z){if(this._attachedToEntityNodeName===Z)return;if(this._attachedToEntityNodeName=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME",{particleEmitter:this,attachedToEntityNodeName:Z})}setColorEnd(Z){if(this._colorEnd&&this._colorEnd.r===Z.r&&this._colorEnd.g===Z.g&&this._colorEnd.b===Z.b)return;if(this._colorEnd=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_END",{particleEmitter:this,colorEnd:Z})}setColorEndVariance(Z){if(this._colorEndVariance&&this._colorEndVariance.r===Z.r&&this._colorEndVariance.g===Z.g&&this._colorEndVariance.b===Z.b)return;if(this._colorEndVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_END_VARIANCE",{particleEmitter:this,colorEndVariance:Z})}setColorStart(Z){if(this._colorStart&&this._colorStart.r===Z.r&&this._colorStart.g===Z.g&&this._colorStart.b===Z.b)return;if(this._colorStart=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_START",{particleEmitter:this,colorStart:Z})}setColorStartVariance(Z){if(this._colorStartVariance&&this._colorStartVariance.r===Z.r&&this._colorStartVariance.g===Z.g&&this._colorStartVariance.b===Z.b)return;if(this._colorStartVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_START_VARIANCE",{particleEmitter:this,colorStartVariance:Z})}setGravity(Z){if(this._gravity&&this._gravity.x===Z.x&&this._gravity.y===Z.y&&this._gravity.z===Z.z)return;if(this._gravity=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_GRAVITY",{particleEmitter:this,gravity:Z})}setLifetime(Z){if(this._lifetime===Z)return;if(this._lifetime=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_LIFETIME",{particleEmitter:this,lifetime:Z})}setLifetimeVariance(Z){if(this._lifetimeVariance===Z)return;if(this._lifetimeVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_LIFETIME_VARIANCE",{particleEmitter:this,lifetimeVariance:Z})}setMaxParticles(Z){if(this._maxParticles===Z)return;if(this._maxParticles=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_MAX_PARTICLES",{particleEmitter:this,maxParticles:Z})}setOffset(Z){if(this._offset&&this._offset.x===Z.x&&this._offset.y===Z.y&&this._offset.z===Z.z)return;if(this._offset=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OFFSET",{particleEmitter:this,offset:Z})}setOpacityEnd(Z){if(this._opacityEnd===Z)return;if(this._opacityEnd=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_END",{particleEmitter:this,opacityEnd:Z})}setOpacityEndVariance(Z){if(this._opacityEndVariance===Z)return;if(this._opacityEndVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE",{particleEmitter:this,opacityEndVariance:Z})}setOpacityStart(Z){if(this._opacityStart===Z)return;if(this._opacityStart=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_START",{particleEmitter:this,opacityStart:Z})}setOpacityStartVariance(Z){if(this._opacityStartVariance===Z)return;if(this._opacityStartVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE",{particleEmitter:this,opacityStartVariance:Z})}setPosition(Z){if(this._position&&this._position.x===Z.x&&this._position.y===Z.y&&this._position.z===Z.z)return;if(this._position=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_POSITION",{particleEmitter:this,position:Z})}setPositionVariance(Z){if(this._positionVariance&&this._positionVariance.x===Z.x&&this._positionVariance.y===Z.y&&this._positionVariance.z===Z.z)return;if(this._positionVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_POSITION_VARIANCE",{particleEmitter:this,positionVariance:Z})}setRate(Z){if(this._rate===Z)return;if(this._rate=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_RATE",{particleEmitter:this,rate:Z})}setRateVariance(Z){if(this._rateVariance===Z)return;if(this._rateVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_RATE_VARIANCE",{particleEmitter:this,rateVariance:Z})}setSizeEnd(Z){if(this._sizeEnd===Z)return;if(this._sizeEnd=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_END",{particleEmitter:this,sizeEnd:Z})}setSizeEndVariance(Z){if(this._sizeEndVariance===Z)return;if(this._sizeEndVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_END_VARIANCE",{particleEmitter:this,sizeEndVariance:Z})}setSizeStart(Z){if(this._sizeStart===Z)return;if(this._sizeStart=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_START",{particleEmitter:this,sizeStart:Z})}setSizeStartVariance(Z){if(this._sizeStartVariance===Z)return;if(this._sizeStartVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_START_VARIANCE",{particleEmitter:this,sizeStartVariance:Z})}setTextureUri(Z){if(this._textureUri===Z)return;if(this._textureUri=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_TEXTURE_URI",{particleEmitter:this,textureUri:Z})}setTransparent(Z){if(this._transparent===Z)return;if(this._transparent=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_TRANSPARENT",{particleEmitter:this,transparent:Z})}setVelocity(Z){if(this._velocity&&this._velocity.x===Z.x&&this._velocity.y===Z.y&&this._velocity.z===Z.z)return;if(this._velocity=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_VELOCITY",{particleEmitter:this,velocity:Z})}setVelocityVariance(Z){if(this._velocityVariance&&this._velocityVariance.x===Z.x&&this._velocityVariance.y===Z.y&&this._velocityVariance.z===Z.z)return;if(this._velocityVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_VELOCITY_VARIANCE",{particleEmitter:this,velocityVariance:Z})}despawn(){if(!this.isSpawned||!this._world)return;this._world.particleEmitterManager.unregisterParticleEmitter(this),this.emitWithWorld(this._world,"PARTICLE_EMITTER.DESPAWN",{particleEmitter:this}),this._id=void 0,this._world=void 0}restart(){if(!this._paused)return;if(this._paused=!1,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_PAUSED",{particleEmitter:this,paused:this._paused})}stop(){if(this._paused)return;if(this._paused=!0,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_PAUSED",{particleEmitter:this,paused:this._paused})}spawn(Z){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return d.error(`ParticleEmitter.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning ParticleEmitter!`);this._id=Z.particleEmitterManager.registerParticleEmitter(this),this._world=Z,this.emitWithWorld(Z,"PARTICLE_EMITTER.SPAWN",{particleEmitter:this})}serialize(){if(!this._world)d.fatalError("ParticleEmitter.serialize(): ParticleEmitter is not in a world and cannot be serialized!");return P0.serializeParticleEmitter(this,this._world.tickAllocator)}}var HU=r(KH(),1);var rQ6={x:0,y:-32,z:0},Nm=60,Pm;(($)=>{$.STEP_START="SIMULATION.STEP_START";$.STEP_END="SIMULATION.STEP_END";$.DEBUG_RAYCAST="SIMULATION.DEBUG_RAYCAST";$.DEBUG_RENDER="SIMULATION.DEBUG_RENDER"})(Pm||={});class VU extends O0{_colliderMap=new oV;_debugRaycastingEnabled=!1;_debugRenderingEnabled=!1;_debugRenderingFilterFlags;_rapierEventQueue;_rapierSimulation;_world;constructor(Z,J=Nm,X=rQ6){super();this._rapierEventQueue=new HU.default.EventQueue(!0),this._rapierSimulation=new HU.default.World(X),this._rapierSimulation.timestep=Math.fround(1/J),this._world=Z}get colliderMap(){return this._colliderMap}get isDebugRaycastingEnabled(){return this._debugRaycastingEnabled}get isDebugRenderingEnabled(){return this._debugRenderingEnabled}get gravity(){return this._rapierSimulation.gravity}get timestepS(){return this._rapierSimulation.timestep}get world(){return this._world}createRawCollider(Z,J){return this._rapierSimulation.createCollider(Z,J)}createRawRigidBody(Z){return this._rapierSimulation.createRigidBody(Z)}enableDebugRaycasting(Z){this._debugRaycastingEnabled=Z}enableDebugRendering(Z,J=HU.default.QueryFilterFlags.EXCLUDE_FIXED){this._debugRenderingEnabled=Z,this._debugRenderingFilterFlags=J}getContactManifolds(Z,J){let X=[];return this._rapierSimulation.narrowPhase.contactPair(Z,J,(Y,$)=>{if(Y.numContacts()===0)return;let Q=Y.normal(),K=[];for(let G=0;G<Y.numSolverContacts();G++)K.push(Y.solverContactPoint(G));X.push({contactPoints:K,localNormalA:!$?Y.localNormal1():Y.localNormal2(),localNormalB:!$?Y.localNormal2():Y.localNormal1(),normal:!$?Q:{x:-Q.x,y:-Q.y,z:-Q.z}})}),X}intersectionsWithRawShape(Z,J,X,Y={}){let $=new Set,Q=[];return this._rapierSimulation.intersectionsWithShape(J,X,Z,(K)=>{let G=this._colliderMap.getColliderHandleBlockType(K.handle);if(G&&!$.has(G))return $.add(G),Q.push({intersectedBlockType:G}),!0;let W=this._colliderMap.getColliderHandleEntity(K.handle);if(W&&!$.has(W))return $.add(W),Q.push({intersectedEntity:W}),!0;return!0},Y.filterFlags,Y.filterGroups,Y.filterExcludeCollider,Y.filterExcludeRigidBody,Y.filterPredicate),Q}raycast(Z,J,X,Y={}){let $=new HU.default.Ray(Z,J),Q=this._rapierSimulation.castRay($,X,Y.solidMode??!0,Y.filterFlags,Y.filterGroups,Y.filterExcludeCollider,Y.filterExcludeRigidBody,Y.filterPredicate);if(this._debugRaycastingEnabled)this.emitWithWorld(this._world,"SIMULATION.DEBUG_RAYCAST",{simulation:this,origin:Z,direction:J,length:X,hit:!!Q});if(!Q)return null;let K=$.pointAt(Q.timeOfImpact),G=Q.timeOfImpact,W=Q.collider,H=this._colliderMap.getColliderHandleBlockType(W.handle);if(H)return{hitBlock:FK.fromGlobalCoordinate({x:Math.floor(K.x-($.dir.x<0?0.0001:-0.0001)),y:Math.floor(K.y-($.dir.y<0?0.0001:-0.0001)),z:Math.floor(K.z-($.dir.z<0?0.0001:-0.0001))},H),hitPoint:K,hitDistance:G};let V=this._colliderMap.getColliderHandleEntity(W.handle);if(V)return{hitEntity:V,hitPoint:K,hitDistance:G};return null}removeRawCollider(Z){this._colliderMap.queueColliderHandleForCleanup(Z.handle),this._rapierSimulation.removeCollider(Z,!1)}removeRawRigidBody(Z){this._rapierSimulation.removeRigidBody(Z)}setGravity(Z){this._rapierSimulation.gravity=Z}step=(Z)=>{this.emitWithWorld(this._world,"SIMULATION.STEP_START",{simulation:this,tickDeltaMs:Z});let J=performance.now();if(r1.startSpan({operation:"physics_step"},()=>{this._rapierSimulation.step(this._rapierEventQueue)}),r1.startSpan({operation:"physics_cleanup"},()=>{this._rapierEventQueue.drainContactForceEvents(this._onContactForceEvent),this._rapierEventQueue.drainCollisionEvents(this._onCollisionEvent),this._colliderMap.cleanup()}),this.emitWithWorld(this._world,"SIMULATION.STEP_END",{simulation:this,stepDurationMs:performance.now()-J}),this._debugRenderingEnabled)this.emitWithWorld(this._world,"SIMULATION.DEBUG_RENDER",{simulation:this,...this._rapierSimulation.debugRender(this._debugRenderingFilterFlags)})};_onCollisionEvent=(Z,J,X)=>{let[Y,$]=this._getCollisionObjects(Z,J);if(!Y||!$)return;let Q=(K,G)=>{if(K instanceof K9&&G instanceof i8&&K.hasListeners("BLOCK_TYPE.ENTITY_COLLISION"))K.emit("BLOCK_TYPE.ENTITY_COLLISION",{blockType:K,entity:G,started:X,colliderHandleA:Z,colliderHandleB:J});else if(K instanceof i8&&G instanceof K9&&K.hasListeners("ENTITY.BLOCK_COLLISION"))K.emit("ENTITY.BLOCK_COLLISION",{entity:K,blockType:G,started:X,colliderHandleA:Z,colliderHandleB:J});else if(K instanceof i8&&G instanceof i8&&K.hasListeners("ENTITY.ENTITY_COLLISION"))K.emit("ENTITY.ENTITY_COLLISION",{entity:K,otherEntity:G,started:X,colliderHandleA:Z,colliderHandleB:J});else if(typeof K==="function"&&(G instanceof i8||G instanceof K9))K(G,X,Z,J)};Q(Y,$),Q($,Y)};_onContactForceEvent=(Z)=>{let[J,X]=this._getCollisionObjects(Z.collider1(),Z.collider2());if(!J||typeof J==="function"||!X||typeof X==="function")return;let Y={totalForce:Z.totalForce(),totalForceMagnitude:Z.totalForceMagnitude(),maxForceDirection:Z.maxForceDirection(),maxForceMagnitude:Z.maxForceMagnitude()},$=(Q,K)=>{if(Q instanceof K9&&K instanceof i8&&Q.hasListeners("BLOCK_TYPE.ENTITY_CONTACT_FORCE"))Q.emit("BLOCK_TYPE.ENTITY_CONTACT_FORCE",{blockType:Q,entity:K,contactForceData:Y});else if(Q instanceof i8&&K instanceof K9&&Q.hasListeners("ENTITY.BLOCK_CONTACT_FORCE"))Q.emit("ENTITY.BLOCK_CONTACT_FORCE",{entity:Q,blockType:K,contactForceData:Y});else if(Q instanceof i8&&K instanceof i8&&Q.hasListeners("ENTITY.ENTITY_CONTACT_FORCE"))Q.emit("ENTITY.ENTITY_CONTACT_FORCE",{entity:Q,otherEntity:K,contactForceData:Y})};$(J,X),$(X,J)};_getCollisionObjects(Z,J){let X=this._colliderMap.getColliderHandleBlockType(Z)??this._colliderMap.getColliderHandleCollisionCallback(Z)??this._colliderMap.getColliderHandleEntity(Z),Y=this._colliderMap.getColliderHandleBlockType(J)??this._colliderMap.getColliderHandleCollisionCallback(J)??this._colliderMap.getColliderHandleEntity(J);return[X,Y]}}class WP{_synchronizedPlayerReliablePackets=new z6;_queuedBroadcasts=[];_queuedAudioSynchronizations=new z6;_queuedBlockSynchronizations=new z6;_queuedBlockTypeSynchronizations=new z6;_queuedChunkSynchronizations=new z6;_queuedDebugRaycastSynchronizations=[];_queuedEntitySynchronizations=new z6;_queuedLightSynchronizations=new z6;_queuedParticleEmitterSynchronizations=new z6;_queuedPerPlayerSynchronizations=new z6;_queuedPerPlayerCameraSynchronizations=new z6;_queuedPerPlayerUISynchronizations=new z6;_queuedPerPlayerUIDatasSynchronizations=new z6;_queuedPlayerSynchronizations=new z6;_queuedSceneUISynchronizations=new z6;_queuedWorldSynchronization;_loadedSceneUIs=new Set;_spawnedChunks=new Set;_spawnedEntities=new Set;_world;constructor(Z){this._world=Z,this._subscribeToAudioEvents(),this._subscribeToBlockTypeRegistryEvents(),this._subscribeToChatEvents(),this._subscribeToChunkLatticeEvents(),this._subscribeToEntityEvents(),this._subscribeToLightEvents(),this._subscribeToParticleEmitterEvents(),this._subscribeToPlayerEvents(),this._subscribeToPlayerCameraEvents(),this._subscribeToPlayerUIEvents(),this._subscribeToSceneUIEvents(),this._subscribeToSimulationEvents(),this._subscribeToWorldEvents()}synchronize(){let Z=this._world.tickAllocator,J=this._world.tickAllocator.getArray(),X=this._world.tickAllocator.getArray(),Y=this._world.loop.currentTick;if(this._queuedPerPlayerSynchronizations.size>0)for(let[$,Q]of this._queuedPerPlayerSynchronizations)this._createOrGetSynchronizedPlayerReliablePackets($,J).push(...Q);if(this._queuedEntitySynchronizations.size>0){let $=this._world.tickAllocator.getArray(),Q=this._world.tickAllocator.getArray();for(let K of this._queuedEntitySynchronizations.valuesArray){let G=!1;for(let W in K)if(W!=="i"&&W!=="p"&&W!=="r"){G=!0;break}if(G)$.push(K);else Q.push(K)}if(Q.length>0){let K=Y0.createPacket(Y0.outboundPackets.entitiesPacketDefinition,Q,Y,Z.getArray());X.push(K)}if($.length>0){let K=Y0.createPacket(Y0.outboundPackets.entitiesPacketDefinition,$,Y,Z.getArray());J.push(K);for(let G of this._synchronizedPlayerReliablePackets.valuesArray)G.push(K)}}if(this._queuedAudioSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.audiosPacketDefinition,this._queuedAudioSynchronizations.valuesArray,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedBlockTypeSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.blockTypesPacketDefinition,this._queuedBlockTypeSynchronizations.valuesArray,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedChunkSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.chunksPacketDefinition,this._queuedChunkSynchronizations.valuesArray,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedBlockSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.blocksPacketDefinition,this._queuedBlockSynchronizations.valuesArray,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedLightSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.lightsPacketDefinition,this._queuedLightSynchronizations.valuesArray,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedParticleEmitterSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.particleEmittersPacketDefinition,this._queuedParticleEmitterSynchronizations.valuesArray,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedPerPlayerUISynchronizations.size>0)for(let[$,Q]of this._queuedPerPlayerUISynchronizations){let K=Y0.createPacket(Y0.outboundPackets.uiPacketDefinition,Q,Y,Z.getArray());this._createOrGetSynchronizedPlayerReliablePackets($,J).push(K)}if(this._queuedPerPlayerUIDatasSynchronizations.size>0)for(let[$,Q]of this._queuedPerPlayerUIDatasSynchronizations){let K=Y0.createPacket(Y0.outboundPackets.uiDatasPacketDefinition,Q,Y,Z.getArray());this._createOrGetSynchronizedPlayerReliablePackets($,J).push(K)}if(this._queuedSceneUISynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.sceneUIsPacketDefinition,this._queuedSceneUISynchronizations.valuesArray,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedWorldSynchronization){let $=Y0.createPacket(Y0.outboundPackets.worldPacketDefinition,this._queuedWorldSynchronization,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedPerPlayerCameraSynchronizations.size>0)for(let[$,Q]of this._queuedPerPlayerCameraSynchronizations){let K=Y0.createPacket(Y0.outboundPackets.cameraPacketDefinition,Q,Y,Z.getArray());this._createOrGetSynchronizedPlayerReliablePackets($,J).push(K)}if(this._queuedPlayerSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.playersPacketDefinition,this._queuedPlayerSynchronizations.valuesArray,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedBroadcasts.length>0)for(let $ of this._queuedBroadcasts){J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedDebugRaycastSynchronizations.length>0){let $=Y0.createPacket(Y0.outboundPackets.physicsDebugRaycastsPacketDefinition,this._queuedDebugRaycastSynchronizations,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}r1.startSpan({operation:"send_all_packets"},()=>{for(let $ of q9.instance.getConnectedPlayersByWorld(this._world)){let Q=this._synchronizedPlayerReliablePackets.get($)??J;if(Q.length>0)$.connection.send(Q);if(X.length>0)$.connection.send(X,!1)}}),r1.startSpan({operation:"network_synchronize_cleanup"},()=>{if(this._queuedBroadcasts.length>0)this._queuedBroadcasts.length=0;if(this._queuedAudioSynchronizations.size>0)this._queuedAudioSynchronizations.clear();if(this._queuedBlockSynchronizations.size>0)this._queuedBlockSynchronizations.clear();if(this._queuedBlockTypeSynchronizations.size>0)this._queuedBlockTypeSynchronizations.clear();if(this._queuedChunkSynchronizations.size>0)this._queuedChunkSynchronizations.clear();if(this._queuedDebugRaycastSynchronizations.length>0)this._queuedDebugRaycastSynchronizations.length=0;if(this._queuedEntitySynchronizations.size>0)this._queuedEntitySynchronizations.clear();if(this._queuedLightSynchronizations.size>0)this._queuedLightSynchronizations.clear();if(this._queuedParticleEmitterSynchronizations.size>0)this._queuedParticleEmitterSynchronizations.clear();if(this._queuedPerPlayerSynchronizations.size>0)this._queuedPerPlayerSynchronizations.clear();if(this._queuedPerPlayerCameraSynchronizations.size>0)this._queuedPerPlayerCameraSynchronizations.clear();if(this._queuedPerPlayerUISynchronizations.size>0)this._queuedPerPlayerUISynchronizations.clear();if(this._queuedPerPlayerUIDatasSynchronizations.size>0)this._queuedPerPlayerUIDatasSynchronizations.clear();if(this._queuedPlayerSynchronizations.size>0)this._queuedPlayerSynchronizations.clear();if(this._queuedSceneUISynchronizations.size>0)this._queuedSceneUISynchronizations.clear();if(this._queuedWorldSynchronization)this._queuedWorldSynchronization=void 0;if(this._loadedSceneUIs.size>0)this._loadedSceneUIs.clear();if(this._spawnedChunks.size>0)this._spawnedChunks.clear();if(this._spawnedEntities.size>0)this._spawnedEntities.clear();if(this._synchronizedPlayerReliablePackets.size>0)this._synchronizedPlayerReliablePackets.clear();i4.clearCachedPacketsSerializedBuffers()})}_subscribeToAudioEvents(){this._world.final("AUDIO.PAUSE",this._onAudioPause),this._world.final("AUDIO.PLAY",this._onAudioPlay),this._world.final("AUDIO.PLAY_RESTART",this._onAudioPlayRestart),this._world.final("AUDIO.SET_ATTACHED_TO_ENTITY",this._onAudioSetAttachedToEntity),this._world.final("AUDIO.SET_CUTOFF_DISTANCE",this._onAudioSetCutoffDistance),this._world.final("AUDIO.SET_DETUNE",this._onAudioSetDetune),this._world.final("AUDIO.SET_DISTORTION",this._onAudioSetDistortion),this._world.final("AUDIO.SET_POSITION",this._onAudioSetPosition),this._world.final("AUDIO.SET_PLAYBACK_RATE",this._onAudioSetPlaybackRate),this._world.final("AUDIO.SET_REFERENCE_DISTANCE",this._onAudioSetReferenceDistance),this._world.final("AUDIO.SET_VOLUME",this._onAudioSetVolume)}_subscribeToBlockTypeRegistryEvents(){this._world.final("BLOCK_TYPE_REGISTRY.REGISTER_BLOCK_TYPE",this._onBlockTypeRegistryRegisterBlockType)}_subscribeToChatEvents(){this._world.final("CHAT.BROADCAST_MESSAGE",this._onChatSendBroadcastMessage),this._world.final("CHAT.PLAYER_MESSAGE",this._onChatSendPlayerMessage)}_subscribeToChunkLatticeEvents(){this._world.final("CHUNK_LATTICE.ADD_CHUNK",this._onChunkLatticeAddChunk),this._world.final("CHUNK_LATTICE.REMOVE_CHUNK",this._onChunkLatticeRemoveChunk),this._world.final("CHUNK_LATTICE.SET_BLOCK",this._onChunkLatticeSetBlock)}_subscribeToEntityEvents(){this._world.final("ENTITY.SPAWN",this._onEntitySpawn),this._world.final("ENTITY.DESPAWN",this._onEntityDespawn),this._world.final("ENTITY.SET_MODEL_ANIMATIONS_PLAYBACK_RATE",this._onEntitySetModelAnimationsPlaybackRate),this._world.final("ENTITY.SET_MODEL_HIDDEN_NODES",this._onEntitySetModelHiddenNodes),this._world.final("ENTITY.SET_MODEL_SCALE",this._onEntitySetModelScale),this._world.final("ENTITY.SET_MODEL_SHOWN_NODES",this._onEntitySetModelShownNodes),this._world.final("ENTITY.SET_MODEL_TEXTURE_URI",this._onEntitySetModelTextureUri),this._world.final("ENTITY.SET_OPACITY",this._onEntitySetOpacity),this._world.final("ENTITY.SET_PARENT",this._onEntitySetParent),this._world.final("ENTITY.SET_TINT_COLOR",this._onEntitySetTintColor),this._world.final("ENTITY.START_MODEL_LOOPED_ANIMATIONS",this._onEntityStartModelLoopedAnimations),this._world.final("ENTITY.START_MODEL_ONESHOT_ANIMATIONS",this._onEntityStartModelOneshotAnimations),this._world.final("ENTITY.STOP_MODEL_ANIMATIONS",this._onEntityStopModelAnimations),this._world.final("ENTITY.UPDATE_POSITION",this._onEntityUpdatePosition),this._world.final("ENTITY.UPDATE_ROTATION",this._onEntityUpdateRotation)}_subscribeToLightEvents(){this._world.final("LIGHT.DESPAWN",this._onLightDespawn),this._world.final("LIGHT.SET_ANGLE",this._onLightSetAngle),this._world.final("LIGHT.SET_ATTACHED_TO_ENTITY",this._onLightSetAttachedToEntity),this._world.final("LIGHT.SET_COLOR",this._onLightSetColor),this._world.final("LIGHT.SET_DISTANCE",this._onLightSetDistance),this._world.final("LIGHT.SET_INTENSITY",this._onLightSetIntensity),this._world.final("LIGHT.SET_OFFSET",this._onLightSetOffset),this._world.final("LIGHT.SET_PENUMBRA",this._onLightSetPenumbra),this._world.final("LIGHT.SET_POSITION",this._onLightSetPosition),this._world.final("LIGHT.SET_TRACKED_ENTITY",this._onLightSetTrackedEntity),this._world.final("LIGHT.SET_TRACKED_POSITION",this._onLightSetTrackedPosition),this._world.final("LIGHT.SPAWN",this._onLightSpawn)}_subscribeToParticleEmitterEvents(){this._world.final("PARTICLE_EMITTER.DESPAWN",this._onParticleEmitterDespawn),this._world.final("PARTICLE_EMITTER.SET_ALPHA_TEST",this._onParticleEmitterSetAlphaTest),this._world.final("PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY",this._onParticleEmitterSetAttachedToEntity),this._world.final("PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME",this._onParticleEmitterSetAttachedToEntityNodeName),this._world.final("PARTICLE_EMITTER.SET_COLOR_END",this._onParticleEmitterSetColorEnd),this._world.final("PARTICLE_EMITTER.SET_COLOR_END_VARIANCE",this._onParticleEmitterSetColorEndVariance),this._world.final("PARTICLE_EMITTER.SET_COLOR_START",this._onParticleEmitterSetColorStart),this._world.final("PARTICLE_EMITTER.SET_COLOR_START_VARIANCE",this._onParticleEmitterSetColorStartVariance),this._world.final("PARTICLE_EMITTER.SET_GRAVITY",this._onParticleEmitterSetGravity),this._world.final("PARTICLE_EMITTER.SET_LIFETIME",this._onParticleEmitterSetLifetime),this._world.final("PARTICLE_EMITTER.SET_LIFETIME_VARIANCE",this._onParticleEmitterSetLifetimeVariance),this._world.final("PARTICLE_EMITTER.SET_MAX_PARTICLES",this._onParticleEmitterSetMaxParticles),this._world.final("PARTICLE_EMITTER.SET_OFFSET",this._onParticleEmitterSetOffset),this._world.final("PARTICLE_EMITTER.SET_OPACITY_END",this._onParticleEmitterSetOpacityEnd),this._world.final("PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE",this._onParticleEmitterSetOpacityEndVariance),this._world.final("PARTICLE_EMITTER.SET_OPACITY_START",this._onParticleEmitterSetOpacityStart),this._world.final("PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE",this._onParticleEmitterSetOpacityStartVariance),this._world.final("PARTICLE_EMITTER.SET_PAUSED",this._onParticleEmitterSetPaused),this._world.final("PARTICLE_EMITTER.SET_POSITION",this._onParticleEmitterSetPosition),this._world.final("PARTICLE_EMITTER.SET_POSITION_VARIANCE",this._onParticleEmitterSetPositionVariance),this._world.final("PARTICLE_EMITTER.SET_RATE",this._onParticleEmitterSetRate),this._world.final("PARTICLE_EMITTER.SET_RATE_VARIANCE",this._onParticleEmitterSetRateVariance),this._world.final("PARTICLE_EMITTER.SET_SIZE_END",this._onParticleEmitterSetSizeEnd),this._world.final("PARTICLE_EMITTER.SET_SIZE_END_VARIANCE",this._onParticleEmitterSetSizeEndVariance),this._world.final("PARTICLE_EMITTER.SET_SIZE_START",this._onParticleEmitterSetSizeStart),this._world.final("PARTICLE_EMITTER.SET_SIZE_START_VARIANCE",this._onParticleEmitterSetSizeStartVariance),this._world.final("PARTICLE_EMITTER.SET_TEXTURE_URI",this._onParticleEmitterSetTextureUri),this._world.final("PARTICLE_EMITTER.SET_TRANSPARENT",this._onParticleEmitterSetTransparent),this._world.final("PARTICLE_EMITTER.SET_VELOCITY",this._onParticleEmitterSetVelocity),this._world.final("PARTICLE_EMITTER.SET_VELOCITY_VARIANCE",this._onParticleEmitterSetVelocityVariance),this._world.final("PARTICLE_EMITTER.SPAWN",this._onParticleEmitterSpawn)}_subscribeToPlayerEvents(){this._world.final("PLAYER.JOINED_WORLD",this._onPlayerJoinedWorld),this._world.final("PLAYER.LEFT_WORLD",this._onPlayerLeftWorld),this._world.final("PLAYER.RECONNECTED_WORLD",this._onPlayerReconnectedWorld),this._world.final("PLAYER.REQUEST_SYNC",this._onPlayerRequestSync)}_subscribeToPlayerCameraEvents(){this._world.final("PLAYER_CAMERA.LOOK_AT_ENTITY",this._onPlayerCameraLookAtEntity),this._world.final("PLAYER_CAMERA.LOOK_AT_POSITION",this._onPlayerCameraLookAtPosition),this._world.final("PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY",this._onPlayerCameraSetAttachedToEntity),this._world.final("PLAYER_CAMERA.SET_ATTACHED_TO_POSITION",this._onPlayerCameraSetAttachedToPosition),this._world.final("PLAYER_CAMERA.SET_FILM_OFFSET",this._onPlayerCameraSetFilmOffset),this._world.final("PLAYER_CAMERA.SET_FORWARD_OFFSET",this._onPlayerCameraSetForwardOffset),this._world.final("PLAYER_CAMERA.SET_FOV",this._onPlayerCameraSetFov),this._world.final("PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES",this._onPlayerCameraSetModelHiddenNodes),this._world.final("PLAYER_CAMERA.SET_MODEL_SHOWN_NODES",this._onPlayerCameraSetModelShownNodes),this._world.final("PLAYER_CAMERA.SET_MODE",this._onPlayerCameraSetMode),this._world.final("PLAYER_CAMERA.SET_OFFSET",this._onPlayerCameraSetOffset),this._world.final("PLAYER_CAMERA.SET_SHOULDER_ANGLE",this._onPlayerCameraSetShoulderAngle),this._world.final("PLAYER_CAMERA.SET_TRACKED_ENTITY",this._onPlayerCameraSetTrackedEntity),this._world.final("PLAYER_CAMERA.SET_TRACKED_POSITION",this._onPlayerCameraSetTrackedPosition),this._world.final("PLAYER_CAMERA.SET_ZOOM",this._onPlayerCameraSetZoom)}_subscribeToPlayerUIEvents(){this._world.final("PLAYER_UI.LOAD",this._onPlayerUILoad),this._world.final("PLAYER_UI.LOCK_POINTER",this._onPlayerUILockPointer),this._world.final("PLAYER_UI.SEND_DATA",this._onPlayerUISendData)}_subscribeToSceneUIEvents(){this._world.final("SCENE_UI.LOAD",this._onSceneUILoad),this._world.final("SCENE_UI.SET_ATTACHED_TO_ENTITY",this._onSceneUISetAttachedToEntity),this._world.final("SCENE_UI.SET_OFFSET",this._onSceneUISetOffset),this._world.final("SCENE_UI.SET_POSITION",this._onSceneUISetPosition),this._world.final("SCENE_UI.SET_STATE",this._onSceneUISetState),this._world.final("SCENE_UI.SET_VIEW_DISTANCE",this._onSceneUISetViewDistance),this._world.final("SCENE_UI.UNLOAD",this._onSceneUIUnload)}_subscribeToSimulationEvents(){this._world.final("SIMULATION.DEBUG_RAYCAST",this._onSimulationDebugRaycast),this._world.final("SIMULATION.DEBUG_RENDER",this._onSimulationDebugRender)}_subscribeToWorldEvents(){this._world.final("WORLD.SET_AMBIENT_LIGHT_COLOR",this._onWorldSetAmbientLightColor),this._world.final("WORLD.SET_AMBIENT_LIGHT_INTENSITY",this._onWorldSetAmbientLightIntensity),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_COLOR",this._onWorldSetDirectionalLightColor),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY",this._onWorldSetDirectionalLightIntensity),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_POSITION",this._onWorldSetDirectionalLightPosition),this._world.final("WORLD.SET_FOG_COLOR",this._onWorldSetFogColor),this._world.final("WORLD.SET_FOG_FAR",this._onWorldSetFogFar),this._world.final("WORLD.SET_FOG_NEAR",this._onWorldSetFogNear),this._world.final("WORLD.SET_SKYBOX_INTENSITY",this._onWorldSetSkyboxIntensity)}_onAudioPause=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.pa=!0,delete J.pl,delete J.r};_onAudioPlay=(Z)=>{let J=Z.audio.serialize();J.pl=!0,delete J.pa,delete J.r,this._queuedAudioSynchronizations.set(J.i,J)};_onAudioPlayRestart=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.r=!0,delete J.pa,delete J.pl,this._queuedAudioSynchronizations.set(J.i,J)};_onAudioSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onAudioSetCutoffDistance=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.cd=Z.cutoffDistance};_onAudioSetDetune=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.de=Z.detune};_onAudioSetDistortion=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.di=Z.distortion};_onAudioSetPosition=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.e=Z.position?void 0:J.e,J.p=Z.position?P0.serializeVector(Z.position,this._world.tickAllocator):void 0};_onAudioSetPlaybackRate=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.pr=Z.playbackRate};_onAudioSetReferenceDistance=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.rd=Z.referenceDistance};_onAudioSetVolume=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.v=Z.volume};_onBlockTypeRegistryRegisterBlockType=(Z)=>{let J=Z.blockType.serialize();this._queuedBlockTypeSynchronizations.set(Z.blockType.id,J)};_onChatSendBroadcastMessage=(Z)=>{let J=this._world.tickAllocator,{player:X,message:Y,color:$}=Z,Q=J.getObject();Q.m=Y,Q.c=$,Q.p=X?.id;let K=J.getArray();K.push(Q),this._queuedBroadcasts.push(Y0.createPacket(Y0.outboundPackets.chatMessagesPacketDefinition,K,this._world.loop.currentTick,J.getArray()))};_onChatSendPlayerMessage=(Z)=>{let J=this._world.tickAllocator,{player:X,message:Y,color:$}=Z,Q=this._queuedPerPlayerSynchronizations.get(X)??[],K=J.getObject();K.m=Y,K.c=$;let G=J.getArray();G.push(K),Q.push(Y0.createPacket(Y0.outboundPackets.chatMessagesPacketDefinition,G,this._world.loop.currentTick,this._world.tickAllocator.getArray())),this._queuedPerPlayerSynchronizations.set(X,Q)};_onChunkLatticeAddChunk=(Z)=>{let J=this._createOrGetQueuedChunkSync(Z.chunk);J.b=this._world.tickAllocator.getArray(Z.chunk.blocks),J.rm=void 0,this._spawnedChunks.add(J.c.join(","))};_onChunkLatticeRemoveChunk=(Z)=>{let J=this._createOrGetQueuedChunkSync(Z.chunk),X=J.c.join(",");if(this._spawnedChunks.has(X))this._queuedChunkSynchronizations.delete(X),this._spawnedChunks.delete(X);else J.rm=!0};_onChunkLatticeSetBlock=(Z)=>{let J=this._createOrGetQueuedBlockSync(Z.globalCoordinate);J.i=Z.blockTypeId};_onEntitySetModelAnimationsPlaybackRate=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.ap=Z.playbackRate};_onEntitySpawn=(Z)=>{let J=Z.entity.serialize();this._queuedEntitySynchronizations.set(J.i,J),this._spawnedEntities.add(J.i)};_onEntityDespawn=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(this._spawnedEntities.has(J.i))this._queuedEntitySynchronizations.delete(J.i),this._spawnedEntities.delete(J.i);else J.rm=!0};_onEntitySetModelHiddenNodes=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.h=this._world.tickAllocator.getArray(Z.modelHiddenNodes)};_onEntitySetModelScale=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.s=Z.modelScale};_onEntitySetModelShownNodes=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.sn=this._world.tickAllocator.getArray(Z.modelShownNodes)};_onEntitySetModelTextureUri=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.mt=Z.modelTextureUri};_onEntitySetOpacity=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.o=Z.opacity};_onEntitySetParent=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.pe=Z.parent?Z.parent.id:void 0,J.pn=Z.parentNodeName};_onEntitySetTintColor=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.t=Z.tintColor?P0.serializeRgbColor(Z.tintColor,this._world.tickAllocator):void 0};_onEntityStartModelLoopedAnimations=(Z)=>{let J=this._world.tickAllocator,X=this._createOrGetQueuedEntitySync(Z.entity),Y=J.getSet(X.al,Z.animations);if(X.al=J.getArray(Y),X.as){let $=J.getArray();for(let Q of X.as)!Y.has(Q)&&$.push(Q);X.as=$}};_onEntityStartModelOneshotAnimations=(Z)=>{let J=this._world.tickAllocator,X=this._createOrGetQueuedEntitySync(Z.entity),Y=J.getSet(X.ao,Z.animations);if(X.ao=J.getArray(Y),X.as){let $=J.getArray();for(let Q of X.as)!Y.has(Q)&&$.push(Q);X.as=$}};_onEntityStopModelAnimations=(Z)=>{let J=this._world.tickAllocator,X=this._createOrGetQueuedEntitySync(Z.entity);if(X.al){let Y=J.getSet(X.al);for(let $ of Z.animations)Y.delete($);X.al=J.getArray(Y)}if(X.ao){let Y=J.getSet(X.ao);for(let $ of Z.animations)Y.delete($);X.ao=J.getArray(Y)}X.as=J.getArray(J.getSet(X.as,Z.animations))};_onEntityUpdateRotation=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.r=P0.serializeQuaternion(Z.rotation,this._world.tickAllocator)};_onEntityUpdatePosition=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.p=P0.serializeVector(Z.position,this._world.tickAllocator)};_onLightDespawn=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.rm=!0};_onLightSetAngle=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.a=Z.angle};_onLightSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onLightSetColor=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.c=P0.serializeRgbColor(Z.color,this._world.tickAllocator)};_onLightSetDistance=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.d=Z.distance};_onLightSetIntensity=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.n=Z.intensity};_onLightSetOffset=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.o=Z.offset?P0.serializeVector(Z.offset,this._world.tickAllocator):void 0};_onLightSetPenumbra=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.pe=Z.penumbra};_onLightSetPosition=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.p=Z.position?P0.serializeVector(Z.position,this._world.tickAllocator):void 0,J.e=Z.position?void 0:J.e};_onLightSetTrackedEntity=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.te=Z.entity?Z.entity.id:void 0,J.tp=Z.entity?void 0:J.tp};_onLightSetTrackedPosition=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.tp=Z.position?P0.serializeVector(Z.position,this._world.tickAllocator):void 0,J.te=Z.position?void 0:J.te};_onLightSpawn=(Z)=>{let J=Z.light.serialize();this._queuedLightSynchronizations.set(J.i,J)};_onParticleEmitterDespawn=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.rm=!0};_onParticleEmitterSetAlphaTest=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.at=Z.alphaTest};_onParticleEmitterSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onParticleEmitterSetAttachedToEntityNodeName=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.en=Z.attachedToEntityNodeName};_onParticleEmitterSetColorEnd=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.ce=Z.colorEnd?P0.serializeRgbColor(Z.colorEnd,this._world.tickAllocator):void 0};_onParticleEmitterSetColorEndVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.cev=Z.colorEndVariance?P0.serializeRgbColor(Z.colorEndVariance,this._world.tickAllocator):void 0};_onParticleEmitterSetColorStart=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.cs=Z.colorStart?P0.serializeRgbColor(Z.colorStart,this._world.tickAllocator):void 0};_onParticleEmitterSetColorStartVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.csv=Z.colorStartVariance?P0.serializeRgbColor(Z.colorStartVariance,this._world.tickAllocator):void 0};_onParticleEmitterSetGravity=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.g=Z.gravity?P0.serializeVector(Z.gravity,this._world.tickAllocator):void 0};_onParticleEmitterSetLifetime=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.l=Z.lifetime};_onParticleEmitterSetLifetimeVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.lv=Z.lifetimeVariance};_onParticleEmitterSetMaxParticles=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.mp=Z.maxParticles};_onParticleEmitterSetOffset=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.o=Z.offset?P0.serializeVector(Z.offset,this._world.tickAllocator):void 0};_onParticleEmitterSetOpacityEnd=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.oe=Z.opacityEnd};_onParticleEmitterSetOpacityEndVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.oev=Z.opacityEndVariance};_onParticleEmitterSetOpacityStart=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.os=Z.opacityStart};_onParticleEmitterSetOpacityStartVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.osv=Z.opacityStartVariance};_onParticleEmitterSetPaused=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.pa=Z.paused};_onParticleEmitterSetPosition=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.p=Z.position?P0.serializeVector(Z.position,this._world.tickAllocator):void 0,J.e=Z.position?void 0:J.e,J.en=Z.position?void 0:J.en};_onParticleEmitterSetPositionVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.pv=Z.positionVariance?P0.serializeVector(Z.positionVariance,this._world.tickAllocator):void 0};_onParticleEmitterSetRate=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.r=Z.rate};_onParticleEmitterSetRateVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.rv=Z.rateVariance};_onParticleEmitterSetSizeEnd=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.se=Z.sizeEnd};_onParticleEmitterSetSizeEndVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.sev=Z.sizeEndVariance};_onParticleEmitterSetSizeStart=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.ss=Z.sizeStart};_onParticleEmitterSetSizeStartVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.ssv=Z.sizeStartVariance};_onParticleEmitterSetTextureUri=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.tu=Z.textureUri};_onParticleEmitterSetTransparent=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.t=Z.transparent};_onParticleEmitterSetVelocity=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.v=Z.velocity?P0.serializeVector(Z.velocity,this._world.tickAllocator):void 0};_onParticleEmitterSetVelocityVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.vv=Z.velocityVariance?P0.serializeVector(Z.velocityVariance,this._world.tickAllocator):void 0};_onParticleEmitterSpawn=(Z)=>{let J=Z.particleEmitter.serialize();this._queuedParticleEmitterSynchronizations.set(J.i,J)};_onPlayerCameraLookAtEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pl=P0.serializeVector(Z.entity.position,this._world.tickAllocator),delete J.et,delete J.pt};_onPlayerCameraLookAtPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pl=Z.position?P0.serializeVector(Z.position,this._world.tickAllocator):void 0,delete J.et,delete J.pt};_onPlayerCameraSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.e=Z.entity.id,delete J.p};_onPlayerCameraSetAttachedToPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.p=Z.position?P0.serializeVector(Z.position,this._world.tickAllocator):void 0,delete J.e};_onPlayerCameraSetFilmOffset=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.fo=Z.filmOffset};_onPlayerCameraSetForwardOffset=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.ffo=Z.forwardOffset};_onPlayerCameraSetFov=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.fv=Z.fov};_onPlayerCameraSetModelHiddenNodes=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.h=this._world.tickAllocator.getArray(Z.modelHiddenNodes)};_onPlayerCameraSetModelShownNodes=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.s=this._world.tickAllocator.getArray(Z.modelShownNodes)};_onPlayerCameraSetMode=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.m=Z.mode};_onPlayerCameraSetOffset=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.o=Z.offset?P0.serializeVector(Z.offset,this._world.tickAllocator):void 0};_onPlayerCameraSetShoulderAngle=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.sa=Z.shoulderAngle};_onPlayerCameraSetTrackedEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.et=Z.entity?Z.entity.id:void 0,delete J.pl,delete J.pt};_onPlayerCameraSetTrackedPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pt=Z.position?P0.serializeVector(Z.position,this._world.tickAllocator):void 0,delete J.et,delete J.pl};_onPlayerCameraSetZoom=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.z=Z.zoom};_onPlayerJoinedWorld=(Z)=>{let J=this._world.tickAllocator,{player:X}=Z,Y=this._queuedPerPlayerSynchronizations.get(X)??J.getArray();Y.push(Y0.createPacket(Y0.outboundPackets.worldPacketDefinition,this._world.serialize(),this._world.loop.currentTick,J.getArray())),Y.push(Y0.createPacket(Y0.outboundPackets.blockTypesPacketDefinition,this._world.blockTypeRegistry.serialize(),this._world.loop.currentTick,J.getArray())),Y.push(Y0.createPacket(Y0.outboundPackets.chunksPacketDefinition,J.map(this._world.chunkLattice.getAllChunks(!0),(Q)=>Q.serialize()),this._world.loop.currentTick,J.getArray())),Y.push(Y0.createPacket(Y0.outboundPackets.entitiesPacketDefinition,J.map(this._world.entityManager.getAllEntities(!0),(Q)=>{if(X.camera.attachedToEntity===void 0&&Q instanceof y7&&Q.player===X)X.camera.setAttachedToEntity(Q);return Q.serialize()}),this._world.loop.currentTick,J.getArray())),Y.push(Y0.createPacket(Y0.outboundPackets.audiosPacketDefinition,J.map(this._world.audioManager.getAllAudios(!0),(Q)=>Q.serialize()),this._world.loop.currentTick,J.getArray())),Y.push(Y0.createPacket(Y0.outboundPackets.lightsPacketDefinition,J.map(this._world.lightManager.getAllLights(!0),(Q)=>Q.serialize()),this._world.loop.currentTick,J.getArray())),Y.push(Y0.createPacket(Y0.outboundPackets.particleEmittersPacketDefinition,J.map(this._world.particleEmitterManager.getAllParticleEmitters(!0),(Q)=>Q.serialize()),this._world.loop.currentTick,J.getArray())),Y.push(Y0.createPacket(Y0.outboundPackets.sceneUIsPacketDefinition,J.map(this._world.sceneUIManager.getAllSceneUIs(!0),(Q)=>Q.serialize()),this._world.loop.currentTick,J.getArray())),Y.push(Y0.createPacket(Y0.outboundPackets.playersPacketDefinition,J.map(q9.instance.getConnectedPlayers(),(Q)=>Q.serialize()),this._world.loop.currentTick,J.getArray()));let $=this._createOrGetQueuedPlayerCameraSync(X.camera);this._queuedPerPlayerCameraSynchronizations.set(X,J.getObject(X.camera.serialize(),$)),this._queuedPerPlayerSynchronizations.set(X,Y),this._queuedPlayerSynchronizations.set(X.id,X.serialize())};_onPlayerLeftWorld=(Z)=>{let J=this._createOrGetQueuedPlayerSync(Z.player);J.rm=!0};_onPlayerReconnectedWorld=(Z)=>{this._onPlayerJoinedWorld(Z)};_onPlayerRequestSync=(Z)=>{let J=this._world.tickAllocator,X=J.getObject();X.r=Z.receivedAt,X.s=Date.now(),X.p=performance.now()-Z.receivedAtMs,X.n=this._world.loop.nextTickMs,Z.player.connection.send([Y0.createPacket(Y0.outboundPackets.syncResponsePacketDefinition,X,this._world.loop.currentTick,J.getArray())])};_onPlayerUILoad=(Z)=>{let J=this._createOrGetQueuedPlayerUISync(Z.playerUI);J.u=Z.htmlUri};_onPlayerUILockPointer=(Z)=>{let J=this._createOrGetQueuedPlayerUISync(Z.playerUI);J.p=Z.lock};_onPlayerUISendData=(Z)=>{this._createOrGetQueuedPlayerUIDatasSync(Z.playerUI).push(Z.data)};_onSceneUILoad=(Z)=>{let J=Z.sceneUI.serialize();this._queuedSceneUISynchronizations.set(J.i,J),this._loadedSceneUIs.add(J.i)};_onSceneUISetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onSceneUISetOffset=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.o=Z.offset?P0.serializeVector(Z.offset,this._world.tickAllocator):void 0};_onSceneUISetPosition=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.p=Z.position?P0.serializeVector(Z.position,this._world.tickAllocator):void 0,J.e=Z.position?void 0:J.e};_onSceneUISetState=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.s=Z.state};_onSceneUISetViewDistance=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.v=Z.viewDistance};_onSceneUIUnload=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);if(this._loadedSceneUIs.has(J.i))this._queuedSceneUISynchronizations.delete(J.i),this._loadedSceneUIs.delete(J.i);else J.rm=!0};_onSimulationDebugRaycast=(Z)=>{this._queuedDebugRaycastSynchronizations.push(P0.serializePhysicsDebugRaycast(Z,this._world.tickAllocator))};_onSimulationDebugRender=(Z)=>{this._queuedBroadcasts.push(Y0.createPacket(Y0.outboundPackets.physicsDebugRenderPacketDefinition,{v:Array.from(Z.vertices),c:Array.from(Z.colors)},this._world.loop.currentTick,this._world.tickAllocator.getArray()))};_onWorldSetAmbientLightColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.ac=P0.serializeRgbColor(Z.color,this._world.tickAllocator)};_onWorldSetAmbientLightIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.ai=Z.intensity};_onWorldSetDirectionalLightColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.dc=P0.serializeRgbColor(Z.color,this._world.tickAllocator)};_onWorldSetDirectionalLightIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.di=Z.intensity};_onWorldSetDirectionalLightPosition=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.dp=P0.serializeVector(Z.position,this._world.tickAllocator)};_onWorldSetFogColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.fc=P0.serializeRgbColor(Z.color,this._world.tickAllocator)};_onWorldSetFogFar=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.ff=Z.far};_onWorldSetFogNear=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.fn=Z.near};_onWorldSetSkyboxIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.si=Z.intensity};_createOrGetQueuedAudioSync(Z){if(Z.id===void 0)d.fatalError("NetworkSynchronizer._createOrGetQueuedAudioSync(): Audio has no id!");let J=this._queuedAudioSynchronizations.get(Z.id);if(!J)J=this._world.tickAllocator.getObject(),J.i=Z.id,this._queuedAudioSynchronizations.set(Z.id,J);return J}_createOrGetQueuedBlockSync(Z){let{x:J,y:X,z:Y}=Z,$=`${J},${X},${Y}`,Q=this._queuedBlockSynchronizations.get($);if(!Q)Q=this._world.tickAllocator.getObject(),Q.i=0,Q.c=[J,X,Y],this._queuedBlockSynchronizations.set($,Q);return Q}_createOrGetQueuedChunkSync(Z){if(!Z.originCoordinate)d.fatalError("NetworkSynchronizer._createOrGetQueuedChunkSync(): Chunk has no origin coordinate!");let{x:J,y:X,z:Y}=Z.originCoordinate,$=`${J},${X},${Y}`,Q=this._queuedChunkSynchronizations.get($);if(!Q)Q=this._world.tickAllocator.getObject(),Q.c=[J,X,Y],this._queuedChunkSynchronizations.set($,Q);return Q}_createOrGetQueuedEntitySync(Z){if(Z.id===void 0)d.fatalError("NetworkSynchronizer._createOrGetQueuedEntitySync(): Entity has no id!");let J=this._queuedEntitySynchronizations.get(Z.id);if(!J)J=this._world.tickAllocator.getObject(),J.i=Z.id,this._queuedEntitySynchronizations.set(Z.id,J);return J}_createOrGetQueuedLightSync(Z){if(Z.id===void 0)d.fatalError("NetworkSynchronizer._createOrGetQueuedLightSync(): Light has no id!");let J=this._queuedLightSynchronizations.get(Z.id);if(!J)J=this._world.tickAllocator.getObject(),J.i=Z.id,this._queuedLightSynchronizations.set(Z.id,J);return J}_createOrGetQueuedParticleEmitterSync(Z){if(Z.id===void 0)d.fatalError("NetworkSynchronizer._createOrGetQueuedParticleEmitterSync(): ParticleEmitter has no id!");let J=this._queuedParticleEmitterSynchronizations.get(Z.id);if(!J)J=this._world.tickAllocator.getObject(),J.i=Z.id,this._queuedParticleEmitterSynchronizations.set(Z.id,J);return J}_createOrGetQueuedPlayerSync(Z){if(Z.id===void 0)d.fatalError("NetworkSynchronizer._createOrGetQueuedPlayerSync(): Player has no id!");let J=this._queuedPlayerSynchronizations.get(Z.id);if(!J)J=this._world.tickAllocator.getObject(),J.i=Z.id,this._queuedPlayerSynchronizations.set(Z.id,J);return J}_createOrGetQueuedPlayerCameraSync(Z){let J=this._queuedPerPlayerCameraSynchronizations.get(Z.player);if(!J)J=this._world.tickAllocator.getObject(),this._queuedPerPlayerCameraSynchronizations.set(Z.player,J);return J}_createOrGetQueuedPlayerUISync(Z){let J=this._queuedPerPlayerUISynchronizations.get(Z.player);if(!J)J=this._world.tickAllocator.getObject(),this._queuedPerPlayerUISynchronizations.set(Z.player,J);return J}_createOrGetQueuedPlayerUIDatasSync(Z){let J=this._queuedPerPlayerUIDatasSynchronizations.get(Z.player);if(!J)J=this._world.tickAllocator.getArray(),this._queuedPerPlayerUIDatasSynchronizations.set(Z.player,J);return J}_createOrGetQueuedSceneUISync(Z){if(Z.id===void 0)d.fatalError("NetworkSynchronizer._createOrGetQueuedSceneUISync(): SceneUI has no id!");let J=this._queuedSceneUISynchronizations.get(Z.id);if(!J)J=this._world.tickAllocator.getObject(),J.i=Z.id,this._queuedSceneUISynchronizations.set(Z.id,J);return J}_createOrGetQueuedWorldSync(Z){if(Z.id!==this._world.id)d.fatalError("NetworkSynchronizer._createOrGetQueuedWorldSync(): World does not match this network synchronizer world!");return this._queuedWorldSynchronization??=this._world.tickAllocator.getObject(),this._queuedWorldSynchronization.i=Z.id,this._queuedWorldSynchronization}_createOrGetSynchronizedPlayerReliablePackets(Z,J){let X=this._synchronizedPlayerReliablePackets.get(Z);if(!X)X=this._world.tickAllocator.getArray(J),this._synchronizedPlayerReliablePackets.set(Z,X);return X}}class zU{_particleEmitters=new Map;_nextParticleEmitterId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}despawnEntityAttachedParticleEmitters(Z){this.getAllEntityAttachedParticleEmitters(Z).forEach((J)=>{J.despawn()})}getAllParticleEmitters(Z=!1){return Z?this._world.tickAllocator.getArray(this._particleEmitters.values()):Array.from(this._particleEmitters.values())}getAllEntityAttachedParticleEmitters(Z){return this.getAllParticleEmitters().filter((J)=>J.attachedToEntity===Z)}registerParticleEmitter(Z){if(Z.id!==void 0)return Z.id;let J=this._nextParticleEmitterId;return this._particleEmitters.set(J,Z),this._nextParticleEmitterId++,J}unregisterParticleEmitter(Z){if(Z.id===void 0)return;this._particleEmitters.delete(Z.id)}}class FU{_sceneUIs=new Map;_nextSceneUIId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}getAllSceneUIs(Z=!1){return Z?this._world.tickAllocator.getArray(this._sceneUIs.values()):Array.from(this._sceneUIs.values())}getAllEntityAttachedSceneUIs(Z){return this.getAllSceneUIs().filter((J)=>J.attachedToEntity===Z)}getSceneUIById(Z){return this._sceneUIs.get(Z)}registerSceneUI(Z){if(Z.id!==void 0)return Z.id;let J=this._nextSceneUIId;return this._sceneUIs.set(J,Z),this._nextSceneUIId++,J}unloadEntityAttachedSceneUIs(Z){this.getAllEntityAttachedSceneUIs(Z).forEach((J)=>{J.unload()})}unregisterSceneUI(Z){if(Z.id===void 0)return;this._sceneUIs.delete(Z.id)}}class qU{_allocatedArrays=[];_allocatedArray3Numbers=[];_allocatedArray4Numbers=[];_allocatedObjects=[];_allocatedSets=[];_arrayPool=[];_array3NumberPool=[];_array4NumberPool=[];_objectPool=[];_setPool=[];getArray(Z,J){let X=this._arrayPool.pop()??[];X.length=0;let Y=0;if(Z)for(let $ of Z)X[Y++]=$;if(J)for(let $ of J)X[Y++]=$;return this._allocatedArrays.push(X),X}getArray3Number(Z){let J=this._array3NumberPool.pop()??[0,0,0];if(J[0]=J[1]=J[2]=0,Z){let X=0;for(let Y of Z){if(X>=3)break;J[X++]=Y}}return this._allocatedArray3Numbers.push(J),J}getArray4Number(Z){let J=this._array4NumberPool.pop()??[0,0,0,0];if(J[0]=J[1]=J[2]=J[3]=0,Z){let X=0;for(let Y of Z){if(X>=4)break;J[X++]=Y}}return this._allocatedArray4Numbers.push(J),J}getObject(Z,J){let X=this._objectPool.pop()??Object.create(null);for(let Y in X)delete X[Y];if(Z)Object.assign(X,Z);if(J)Object.assign(X,J);return this._allocatedObjects.push(X),X}getSet(Z,J){let X=this._setPool.pop()??new Set;if(X.clear(),Z)for(let Y of Z)X.add(Y);if(J)for(let Y of J)X.add(Y);return this._allocatedSets.push(X),X}map(Z,J){let X=this.getArray();X.length=Z.length;for(let Y=0;Y<Z.length;Y++)X[Y]=J(Z[Y],Y,Z);return X}reset(){for(let Z=0;Z<this._allocatedArrays.length;Z++)if(this._arrayPool.length<4096)this._arrayPool.push(this._allocatedArrays[Z]);for(let Z=0;Z<this._allocatedArray3Numbers.length;Z++)if(this._array3NumberPool.length<4096)this._array3NumberPool.push(this._allocatedArray3Numbers[Z]);for(let Z=0;Z<this._allocatedArray4Numbers.length;Z++)if(this._array4NumberPool.length<4096)this._array4NumberPool.push(this._allocatedArray4Numbers[Z]);for(let Z=0;Z<this._allocatedObjects.length;Z++)if(this._objectPool.length<4096)this._objectPool.push(this._allocatedObjects[Z]);for(let Z=0;Z<this._allocatedSets.length;Z++)if(this._setPool.length<1024)this._setPool.push(this._allocatedSets[Z]);this._allocatedArrays.length=0,this._allocatedArray3Numbers.length=0,this._allocatedArray4Numbers.length=0,this._allocatedObjects.length=0,this._allocatedSets.length=0}}var tQ6=2,eQ6=3;class UU{_accumulatorMs=0;_targetTicksPerSecond;_fixedTimestepMs;_fixedTimestepS;_maxAccumulatorMs;_nextTickMs=0;_lastLoopTimeMs=0;_tickFunction;_tickErrorCallback;_tickHandle=null;constructor(Z,J,X){this._targetTicksPerSecond=Z,this._fixedTimestepS=Math.fround(1/Z),this._fixedTimestepMs=Math.fround(this._fixedTimestepS*1000),this._maxAccumulatorMs=this._fixedTimestepMs*eQ6,this._tickFunction=J,this._tickErrorCallback=X}get targetTicksPerSecond(){return this._targetTicksPerSecond}get fixedTimestepMs(){return this._fixedTimestepMs}get fixedTimestepS(){return this._fixedTimestepS}get isStarted(){return!!this._tickHandle}get nextTickMs(){return this._nextTickMs}start(){if(this._tickHandle)return;this._lastLoopTimeMs=performance.now();let Z=()=>{let J=performance.now(),X=J-this._lastLoopTimeMs;if(this._lastLoopTimeMs=J,this._accumulatorMs+=X,this._accumulatorMs>this._maxAccumulatorMs)this._accumulatorMs=this._maxAccumulatorMs;if(this._accumulatorMs>=this._fixedTimestepMs)r1.startSpan({operation:"ticker_tick"},()=>{let Y=0;while(this._accumulatorMs>=this._fixedTimestepMs&&Y<tQ6)this._tick(this._fixedTimestepMs),this._accumulatorMs-=this._fixedTimestepMs,Y++;this._nextTickMs=Math.max(0,this._fixedTimestepMs-this._accumulatorMs)});this._tickHandle=setTimeout(Z,this._nextTickMs)};Z()}stop(){if(!this._tickHandle)return;clearTimeout(this._tickHandle),this._tickHandle=null}_tick(Z){try{this._tickFunction(Z)}catch(J){if(J instanceof Error&&this._tickErrorCallback)this._tickErrorCallback(J);else d.warning(`Ticker._tick(): tick callback threw an error, but it was not an instance of Error. Error: ${J}`)}}}var _31;((Q)=>{Q.START="WORLD_LOOP.START";Q.STOP="WORLD_LOOP.STOP";Q.TICK_START="WORLD_LOOP.TICK_START";Q.TICK_END="WORLD_LOOP.TICK_END";Q.TICK_ERROR="WORLD_LOOP.TICK_ERROR"})(_31||={});class LU extends O0{_currentTick=0;_ticker;_world;constructor(Z,J=Nm){super();this._ticker=new UU(J,this._tick,this._onTickError),this._world=Z}get currentTick(){return this._currentTick}get isStarted(){return this._ticker.isStarted}get nextTickMs(){return this._ticker.nextTickMs}get timestepS(){return this._ticker.fixedTimestepS}get world(){return this._world}start(){this._ticker.start(),this.emitWithWorld(this._world,"WORLD_LOOP.START",{worldLoop:this})}stop(){this._ticker.stop(),this.emitWithWorld(this._world,"WORLD_LOOP.STOP",{worldLoop:this})}_tick=(Z)=>{this.emitWithWorld(this._world,"WORLD_LOOP.TICK_START",{worldLoop:this,tickDeltaMs:Z});let J=performance.now();r1.startSpan({operation:"world_tick",attributes:{serverPlayerCount:q9.instance.playerCount,targetTickRate:this._ticker.targetTicksPerSecond,targetTickRateMs:this._ticker.fixedTimestepMs,worldId:this._world.id,worldName:this._world.name,worldChunkCount:this._world.chunkLattice.chunkCount,worldEntityCount:this._world.entityManager.entityCount,worldLoopTick:this._currentTick}},()=>{r1.startSpan({operation:"entities_tick"},()=>this._world.entityManager.tickEntities(Z)),r1.startSpan({operation:"simulation_step"},()=>this._world.simulation.step(Z)),r1.startSpan({operation:"entities_emit_updates"},()=>this._world.entityManager.checkAndEmitUpdates()),r1.startSpan({operation:"network_synchronize"},()=>this._world.networkSynchronizer.synchronize()),r1.startSpan({operation:"release_tick_allocation"},()=>this._world.tickAllocator.reset())}),this._currentTick++,this.emitWithWorld(this._world,"WORLD_LOOP.TICK_END",{worldLoop:this,tickDurationMs:performance.now()-J})};_onTickError=(Z)=>{d.error(`WorldLoop._onTickError(): Error: ${Z}`),this.emitWithWorld(this._world,"WORLD_LOOP.TICK_ERROR",{worldLoop:this,error:Z})}}var Dm;((F)=>{F.SET_AMBIENT_LIGHT_COLOR="WORLD.SET_AMBIENT_LIGHT_COLOR";F.SET_AMBIENT_LIGHT_INTENSITY="WORLD.SET_AMBIENT_LIGHT_INTENSITY";F.SET_DIRECTIONAL_LIGHT_COLOR="WORLD.SET_DIRECTIONAL_LIGHT_COLOR";F.SET_DIRECTIONAL_LIGHT_INTENSITY="WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY";F.SET_DIRECTIONAL_LIGHT_POSITION="WORLD.SET_DIRECTIONAL_LIGHT_POSITION";F.SET_FOG_COLOR="WORLD.SET_FOG_COLOR";F.SET_FOG_FAR="WORLD.SET_FOG_FAR";F.SET_FOG_NEAR="WORLD.SET_FOG_NEAR";F.SET_SKYBOX_INTENSITY="WORLD.SET_SKYBOX_INTENSITY";F.START="WORLD.START";F.STOP="WORLD.STOP"})(Dm||={});class BU extends O0{_id;_ambientLightColor;_ambientLightIntensity;_audioManager;_blockTypeRegistry;_chatManager;_chunkLattice;_directionalLightColor;_directionalLightIntensity;_directionalLightPosition;_entityManager;_fogColor;_fogFar;_fogNear;_lightManager;_loop;_name;_networkSynchronizer;_particleEmitterManager;_sceneUIManager;_simulation;_skyboxIntensity;_skyboxUri;_tag;_tickAllocator;constructor(Z){super();if(this._id=Z.id,this._ambientLightColor=Z.ambientLightColor??{r:255,g:255,b:255},this._ambientLightIntensity=Z.ambientLightIntensity??1,this._directionalLightColor=Z.directionalLightColor??{r:255,g:255,b:255},this._directionalLightIntensity=Z.directionalLightIntensity??3,this._directionalLightPosition=Z.directionalLightPosition??{x:100,y:150,z:100},this._fogColor=Z.fogColor,this._fogFar=Z.fogFar??550,this._fogNear=Z.fogNear??500,this._name=Z.name,this._skyboxIntensity=Z.skyboxIntensity??1,this._skyboxUri=Z.skyboxUri,this._tag=Z.tag,this._audioManager=new D3(this),this._blockTypeRegistry=new jV(this),this._chatManager=new aV(this),this._chunkLattice=new sV(this),this._entityManager=new eV(this),this._lightManager=new WU(this),this._loop=new LU(this,Z.tickRate),this._networkSynchronizer=new WP(this),this._particleEmitterManager=new zU(this),this._sceneUIManager=new FU(this),this._simulation=new VU(this,Z.tickRate,Z.gravity),this._tickAllocator=new qU,Z.map)this.loadMap(Z.map)}get id(){return this._id}get ambientLightColor(){return this._ambientLightColor}get ambientLightIntensity(){return this._ambientLightIntensity}get blockTypeRegistry(){return this._blockTypeRegistry}get chatManager(){return this._chatManager}get chunkLattice(){return this._chunkLattice}get directionalLightColor(){return this._directionalLightColor}get directionalLightIntensity(){return this._directionalLightIntensity}get directionalLightPosition(){return this._directionalLightPosition}get entityManager(){return this._entityManager}get fogColor(){return this._fogColor}get fogFar(){return this._fogFar}get fogNear(){return this._fogNear}get lightManager(){return this._lightManager}get loop(){return this._loop}get name(){return this._name}get networkSynchronizer(){return this._networkSynchronizer}get particleEmitterManager(){return this._particleEmitterManager}get sceneUIManager(){return this._sceneUIManager}get simulation(){return this._simulation}get skyboxIntensity(){return this._skyboxIntensity}get skyboxUri(){return this._skyboxUri}get audioManager(){return this._audioManager}get tag(){return this._tag}get tickAllocator(){return this._tickAllocator}loadMap(Z){if(this.chunkLattice.clear(),Z.blockTypes)for(let J of Z.blockTypes)this.blockTypeRegistry.registerGenericBlockType({id:J.id,isLiquid:J.isLiquid,name:J.name,textureUri:J.textureUri});if(Z.blocks)for(let[J,X]of Object.entries(Z.blocks)){let[Y,$,Q]=J.split(",").map(Number);this.chunkLattice.setBlock({x:Y,y:$,z:Q},X)}if(Z.entities)for(let[J,X]of Object.entries(Z.entities)){let[Y,$,Q]=J.split(",").map(Number);new i8({isEnvironmental:!0,...X}).spawn(this,{x:Y,y:$,z:Q})}}setAmbientLightColor(Z){this._ambientLightColor=Z,this.emit("WORLD.SET_AMBIENT_LIGHT_COLOR",{world:this,color:Z})}setAmbientLightIntensity(Z){this._ambientLightIntensity=Z,this.emit("WORLD.SET_AMBIENT_LIGHT_INTENSITY",{world:this,intensity:Z})}setDirectionalLightColor(Z){this._directionalLightColor=Z,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_COLOR",{world:this,color:Z})}setDirectionalLightIntensity(Z){this._directionalLightIntensity=Z,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY",{world:this,intensity:Z})}setDirectionalLightPosition(Z){this._directionalLightPosition=Z,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_POSITION",{world:this,position:Z})}setFogColor(Z){this._fogColor=Z,this.emit("WORLD.SET_FOG_COLOR",{world:this,color:Z})}setFogFar(Z){this._fogFar=Z,this.emit("WORLD.SET_FOG_FAR",{world:this,far:Z})}setFogNear(Z){this._fogNear=Z,this.emit("WORLD.SET_FOG_NEAR",{world:this,near:Z})}setSkyboxIntensity(Z){this._skyboxIntensity=Z,this.emit("WORLD.SET_SKYBOX_INTENSITY",{world:this,intensity:Z})}start(){if(this._loop.isStarted)return;this._loop.start(),this.emit("WORLD.START",{world:this,startedAtMs:Date.now()})}stop(){if(!this._loop.isStarted)return;this._loop.stop(),this.emit("WORLD.STOP",{world:this,stoppedAtMs:Date.now()})}serialize(){return P0.serializeWorld(this,this._tickAllocator)}}var S31;((J)=>J.WORLD_CREATED="WORLD_MANAGER.WORLD_CREATED")(S31||={});class EY{static instance=new EY;_defaultWorld;_nextWorldId=1;_worlds=new Map;createWorld(Z){let J=new BU({...Z,id:this._nextWorldId++});return J.start(),this._worlds.set(J.id,J),O0.globalInstance.emit("WORLD_MANAGER.WORLD_CREATED",{world:J}),J}getAllWorlds(){return Array.from(this._worlds.values())}getDefaultWorld(){return this._defaultWorld??=this.createWorld({name:"Default World",skyboxUri:"skyboxes/partly-cloudy"}),this._defaultWorld}getWorldsByTag(Z){let J=[];return this._worlds.forEach((X)=>{if(X.tag===Z)J.push(X)}),J}getWorld(Z){return this._worlds.get(Z)}setDefaultWorld(Z){this._defaultWorld=Z}}var v31;((Y)=>{Y.PLAYER_CONNECTED="PLAYER_MANAGER.PLAYER_CONNECTED";Y.PLAYER_DISCONNECTED="PLAYER_MANAGER.PLAYER_DISCONNECTED";Y.PLAYER_RECONNECTED="PLAYER_MANAGER.PLAYER_RECONNECTED"})(v31||={});class q9{static instance=new q9;worldSelectionHandler;_connectionPlayers=new Map;constructor(){O0.globalInstance.on("CONNECTION.OPENED",({connection:Z,req:J})=>{this._onConnectionOpened(Z,J.session)}),O0.globalInstance.on("CONNECTION.DISCONNECTED",({connection:Z})=>{this._onConnectionDisconnected(Z)}),O0.globalInstance.on("CONNECTION.RECONNECTED",({connection:Z})=>{this._onConnectionReconnected(Z)}),O0.globalInstance.on("CONNECTION.CLOSED",({connection:Z})=>{this._onConnectionClosed(Z)})}get playerCount(){return this._connectionPlayers.size}getConnectedPlayers(){return Array.from(this._connectionPlayers.values())}getConnectedPlayersByWorld(Z){return this.getConnectedPlayers().filter((J)=>J.world===Z)}getConnectedPlayerByUsername(Z){return Array.from(this._connectionPlayers.values()).find((J)=>{return J.username.toLowerCase()===Z.toLowerCase()})}async _onConnectionOpened(Z,J){let X=new CG(Z,J);await X.loadInitialPersistedData(),this._connectionPlayers.set(Z,X),O0.globalInstance.emit("PLAYER_MANAGER.PLAYER_CONNECTED",{player:X});let Y=await this.worldSelectionHandler?.(X);X.joinWorld(Y??EY.instance.getDefaultWorld())}_onConnectionDisconnected(Z){let J=this._connectionPlayers.get(Z);if(J)J.resetInputs(),J.camera.reset()}_onConnectionReconnected(Z){let J=this._connectionPlayers.get(Z);if(J)J.reconnected(),O0.globalInstance.emit("PLAYER_MANAGER.PLAYER_RECONNECTED",{player:J});else d.warning(`PlayerManager._onConnectionReconnected(): Connection ${Z.id} not in the PlayerManager._connectionPlayers map.`)}_onConnectionClosed(Z){let J=this._connectionPlayers.get(Z);if(J)J.disconnect(),this._connectionPlayers.delete(Z),O0.globalInstance.emit("PLAYER_MANAGER.PLAYER_DISCONNECTED",{player:J});else d.warning(`PlayerManager._onConnectionClosed(): Connection ${Z.id} not in the PlayerManager._connectionPlayers map.`)}}Buffer.poolSize=134217728;var x31;((X)=>{X.START="GAMESERVER.START";X.STOP="GAMESERVER.STOP"})(x31||={});function ZK6(Z){A31.default.init().then(()=>{return $K.instance.modelRegistry.preloadModels()}).then(()=>{if(Z.length>0)Z($K.instance.worldManager.getDefaultWorld());else Z();$K.instance.start()}).catch((J)=>{d.fatalError(`Failed to initialize the game engine, exiting. Error: ${J}`)})}class $K{static _instance;_modelRegistry=S5.instance;_playerManager=q9.instance;_socket=a7.instance;_worldManager=EY.instance;_webServer=FW.instance;constructor(){}static get instance(){if(!this._instance)this._instance=new $K;return this._instance}get modelRegistry(){return this._modelRegistry}get playerManager(){return this._playerManager}get socket(){return this._socket}get webServer(){return this._webServer}get worldManager(){return this._worldManager}start(){O0.globalInstance.emit("GAMESERVER.START",{startedAtMs:performance.now()}),this._webServer.start()}}var F6=r(GK(),1);class WK extends Float32Array{constructor(Z,J,X,Y){super([Z,J,X,Y])}get determinant(){return F6.mat2.determinant(this)}get frobeniusNorm(){return F6.mat2.frob(this)}static create(){let Z=new WK(0,0,0,0);return F6.mat2.identity(Z),Z}static fromRotation(Z){let J=WK.create();return F6.mat2.fromRotation(J,Z),J}static fromScaling(Z){let J=WK.create();return F6.mat2.fromScaling(J,Z),J}add(Z){return F6.mat2.add(this,this,Z),this}adjoint(){return F6.mat2.adjoint(this,this),this}clone(){return new WK(this[0],this[1],this[2],this[3])}copy(Z){return F6.mat2.copy(this,Z),this}equals(Z){return F6.mat2.equals(this,Z)}exactEquals(Z){return F6.mat2.exactEquals(this,Z)}identity(){return F6.mat2.identity(this),this}invert(){return F6.mat2.invert(this,this),this}multiply(Z){return F6.mat2.mul(this,this,Z),this}multiplyScalar(Z){return F6.mat2.multiplyScalar(this,this,Z),this}rotate(Z){return F6.mat2.rotate(this,this,Z),this}subtract(Z){return F6.mat2.sub(this,this,Z),this}toString(){return`[${this[0]},${this[1]}][${this[2]},${this[3]}]`}transpose(){return F6.mat2.transpose(this,this),this}}var R8=r(GK(),1);class UZ extends Float32Array{constructor(Z,J,X,Y,$,Q,K,G,W){super([Z,J,X,Y,$,Q,K,G,W])}get determinant(){return R8.mat3.determinant(this)}get frobeniusNorm(){return R8.mat3.frob(this)}static create(){let Z=new UZ(0,0,0,0,0,0,0,0,0);return R8.mat3.identity(Z),Z}static fromMatrix4(Z){let J=UZ.create();return R8.mat3.fromMat4(J,Z),J}static fromQuaternion(Z){let J=UZ.create();return R8.mat3.fromQuat(J,Z),J}static fromRotation(Z){let J=UZ.create();return R8.mat3.fromRotation(J,Z),J}static fromScaling(Z){let J=UZ.create();return R8.mat3.fromScaling(J,Z),J}static fromTranslation(Z){let J=UZ.create();return R8.mat3.fromTranslation(J,Z),J}add(Z){return R8.mat3.add(this,this,Z),this}adjoint(){return R8.mat3.adjoint(this,this),this}clone(){return new UZ(this[0],this[1],this[2],this[3],this[4],this[5],this[6],this[7],this[8])}copy(Z){return R8.mat3.copy(this,Z),this}equals(Z){return R8.mat3.equals(this,Z)}exactEquals(Z){return R8.mat3.exactEquals(this,Z)}identity(){return R8.mat3.identity(this),this}invert(){return R8.mat3.invert(this,this),this}multiply(Z){return R8.mat3.mul(this,this,Z),this}multiplyScalar(Z){return R8.mat3.multiplyScalar(this,this,Z),this}transformVector(Z){return Z.transformMatrix3(this)}projection(Z,J){return R8.mat3.projection(this,Z,J),this}rotate(Z){return R8.mat3.rotate(this,this,Z),this}subtract(Z){return R8.mat3.sub(this,this,Z),this}toString(){return`[${this[0]},${this[1]},${this[2]}][${this[3]},${this[4]},${this[5]}][${this[6]},${this[7]},${this[8]}]`}transpose(){return R8.mat3.transpose(this,this),this}}var X1=r(GK(),1);class P5 extends Float32Array{constructor(Z,J,X,Y,$,Q,K,G,W,H,V,F,z,q,U,B){super([Z,J,X,Y,$,Q,K,G,W,H,V,F,z,q,U,B])}get determinant(){return X1.mat4.determinant(this)}get frobeniusNorm(){return X1.mat4.frob(this)}static create(){let Z=new P5(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return X1.mat4.identity(Z),Z}static fromQuaternion(Z){let J=P5.create();return X1.mat4.fromQuat(J,Z),J}static fromRotation(Z,J){let X=P5.create();return X1.mat4.fromRotation(X,Z,J),X}static fromRotationTranslation(Z,J){let X=P5.create();return X1.mat4.fromRotationTranslation(X,Z,J),X}static fromRotationTranslationScale(Z,J,X){let Y=P5.create();return X1.mat4.fromRotationTranslationScale(Y,Z,J,X),Y}static fromRotationTranslationScaleOrigin(Z,J,X,Y){let $=P5.create();return X1.mat4.fromRotationTranslationScaleOrigin($,Z,J,X,Y),$}static fromScaling(Z){let J=P5.create();return X1.mat4.fromScaling(J,Z),J}static fromTranslation(Z){let J=P5.create();return X1.mat4.fromTranslation(J,Z),J}static fromXRotation(Z){let J=P5.create();return X1.mat4.fromXRotation(J,Z),J}static fromYRotation(Z){let J=P5.create();return X1.mat4.fromYRotation(J,Z),J}static fromZRotation(Z){let J=P5.create();return X1.mat4.fromZRotation(J,Z),J}add(Z){return X1.mat4.add(this,this,Z),this}adjoint(){return X1.mat4.adjoint(this,this),this}clone(){return new P5(this[0],this[1],this[2],this[3],this[4],this[5],this[6],this[7],this[8],this[9],this[10],this[11],this[12],this[13],this[14],this[15])}copy(Z){return X1.mat4.copy(this,Z),this}equals(Z){return X1.mat4.equals(this,Z)}exactEquals(Z){return X1.mat4.exactEquals(this,Z)}frustrum(Z,J,X,Y,$,Q){return X1.mat4.frustum(this,Z,J,X,Y,$,Q),this}identity(){return X1.mat4.identity(this),this}invert(){return X1.mat4.invert(this,this),this}lookAt(Z,J,X){return X1.mat4.lookAt(this,Z,J,X),this}multiply(Z){return X1.mat4.mul(this,this,Z),this}multiplyScalar(Z){return X1.mat4.multiplyScalar(this,this,Z),this}orthographic(Z,J,X,Y,$,Q){return X1.mat4.ortho(this,Z,J,X,Y,$,Q),this}perspective(Z,J,X,Y){return X1.mat4.perspective(this,Z,J,X,Y),this}rotate(Z,J){return X1.mat4.rotate(this,this,Z,J),this}rotateX(Z){return X1.mat4.rotateX(this,this,Z),this}rotateY(Z){return X1.mat4.rotateY(this,this,Z),this}rotateZ(Z){return X1.mat4.rotateZ(this,this,Z),this}scale(Z){return X1.mat4.scale(this,this,Z),this}subtract(Z){return X1.mat4.sub(this,this,Z),this}targetTo(Z,J,X){return X1.mat4.targetTo(this,Z,J,X),this}toString(){return`[${this[0]},${this[1]},${this[2]},${this[3]}][${this[4]},${this[5]},${this[6]},${this[7]}][${this[8]},${this[9]},${this[10]},${this[11]}][${this[12]},${this[13]},${this[14]},${this[15]}]`}translate(Z){return X1.mat4.translate(this,this,Z),this}transpose(){return X1.mat4.transpose(this,this),this}}var f1=r(GK(),1);class M3 extends Float32Array{constructor(Z,J,X,Y){super([Z,J,X,Y])}get length(){return f1.quat.length(this)}get squaredLength(){return f1.quat.squaredLength(this)}get magnitude(){return f1.quat.length(this)}get squaredMagnitude(){return f1.quat.squaredLength(this)}get x(){return this[0]}set x(Z){this[0]=Z}get y(){return this[1]}set y(Z){this[1]=Z}get z(){return this[2]}set z(Z){this[2]=Z}get w(){return this[3]}set w(Z){this[3]=Z}static fromEuler(Z,J,X){let Y=f1.quat.fromEuler(new Float32Array(4),Z,J,X);return new M3(Y[0],Y[1],Y[2],Y[3])}static fromQuaternionLike(Z){return new M3(Z.x,Z.y,Z.z,Z.w)}clone(){return new M3(this.x,this.y,this.z,this.w)}conjugate(){return f1.quat.conjugate(this,this),this}copy(Z){return f1.quat.copy(this,Z),this}dot(Z){return f1.quat.dot(this,Z)}exponential(){return f1.quat.exp(this,this),this}equals(Z){return f1.quat.equals(this,Z)}exactEquals(Z){return f1.quat.exactEquals(this,Z)}getAngle(Z){return f1.quat.getAngle(this,Z)}identity(){return f1.quat.identity(this),this}invert(){return f1.quat.invert(this,this),this}lerp(Z,J){return f1.quat.lerp(this,this,Z,J),this}logarithm(){return f1.quat.ln(this,this),this}multiply(Z){return f1.quat.multiply(this,this,Z),this}transformVector(Z){return Z.transformQuaternion(this)}normalize(){return f1.quat.normalize(this,this),this}power(Z){return f1.quat.pow(this,this,Z),this}randomize(){return f1.quat.random(this),this}rotateX(Z){return f1.quat.rotateX(this,this,Z),this}rotateY(Z){return f1.quat.rotateY(this,this,Z),this}rotateZ(Z){return f1.quat.rotateZ(this,this,Z),this}scale(Z){return f1.quat.scale(this,this,Z),this}setAxisAngle(Z,J){return f1.quat.setAxisAngle(this,Z,J),this}slerp(Z,J){return f1.quat.slerp(this,this,Z,J),this}toString(){return`${this.x},${this.y},${this.z},${this.w}`}}var q1=r(GK(),1);class wU extends Float32Array{constructor(Z,J){super([Z,J])}get length(){return q1.vec2.length(this)}get squaredLength(){return q1.vec2.squaredLength(this)}get magnitude(){return q1.vec2.length(this)}get squaredMagnitude(){return q1.vec2.squaredLength(this)}get x(){return this[0]}set x(Z){this[0]=Z}get y(){return this[1]}set y(Z){this[1]=Z}static create(){return new wU(0,0)}add(Z){return q1.vec2.add(this,this,Z),this}angle(Z){return q1.vec2.angle(this,Z)}ceil(){return q1.vec2.ceil(this,this),this}clone(){return new wU(this.x,this.y)}copy(Z){return q1.vec2.copy(this,Z),this}distance(Z){return q1.vec2.distance(this,Z)}divide(Z){return q1.vec2.divide(this,this,Z),this}dot(Z){return q1.vec2.dot(this,Z)}equals(Z){return q1.vec2.equals(this,Z)}exactEquals(Z){return q1.vec2.exactEquals(this,Z)}floor(){return q1.vec2.floor(this,this),this}invert(){return q1.vec2.inverse(this,this),this}lerp(Z,J){return q1.vec2.lerp(this,this,Z,J),this}max(Z){return q1.vec2.max(this,this,Z),this}min(Z){return q1.vec2.min(this,this,Z),this}multiply(Z){return q1.vec2.mul(this,this,Z),this}negate(){return q1.vec2.negate(this,this),this}normalize(){return q1.vec2.normalize(this,this),this}randomize(Z){return q1.vec2.random(this,Z),this}rotate(Z,J){return q1.vec2.rotate(this,this,Z,J),this}round(){return q1.vec2.round(this,this),this}scale(Z){return q1.vec2.scale(this,this,Z),this}scaleAndAdd(Z,J){return q1.vec2.scaleAndAdd(this,this,Z,J),this}subtract(Z){return q1.vec2.sub(this,this,Z),this}toString(){return`${this.x},${this.y}`}transformMatrix2(Z){return q1.vec2.transformMat2(this,this,Z),this}transformMatrix3(Z){return q1.vec2.transformMat3(this,this,Z),this}transformMatrix4(Z){return q1.vec2.transformMat4(this,this,Z),this}zero(){return q1.vec2.zero(this),this}}var V1=r(GK(),1);class R3 extends Float32Array{constructor(Z,J,X){super([Z,J,X])}get length(){return V1.vec3.length(this)}get squaredLength(){return V1.vec3.squaredLength(this)}get magnitude(){return V1.vec3.length(this)}get squaredMagnitude(){return V1.vec3.squaredLength(this)}get x(){return this[0]}set x(Z){this[0]=Z}get y(){return this[1]}set y(Z){this[1]=Z}get z(){return this[2]}set z(Z){this[2]=Z}static create(){return new R3(0,0,0)}static fromVector3Like(Z){return new R3(Z.x,Z.y,Z.z)}add(Z){return V1.vec3.add(this,this,Z),this}ceil(){return V1.vec3.ceil(this,this),this}clone(){return new R3(this.x,this.y,this.z)}copy(Z){return V1.vec3.copy(this,Z),this}cross(Z){return V1.vec3.cross(this,this,Z),this}distance(Z){return V1.vec3.distance(this,Z)}divide(Z){return V1.vec3.div(this,this,Z),this}dot(Z){return V1.vec3.dot(this,Z)}equals(Z){return V1.vec3.equals(this,Z)}exactEquals(Z){return V1.vec3.exactEquals(this,Z)}floor(){return V1.vec3.floor(this,this),this}invert(){return V1.vec3.inverse(this,this),this}lerp(Z,J){return V1.vec3.lerp(this,this,Z,J),this}max(Z){return V1.vec3.max(this,this,Z),this}min(Z){return V1.vec3.min(this,this,Z),this}multiply(Z){return V1.vec3.mul(this,this,Z),this}negate(){return V1.vec3.negate(this,this),this}normalize(){return V1.vec3.normalize(this,this),this}randomize(Z){return V1.vec3.random(this,Z),this}rotateX(Z,J){return V1.vec3.rotateX(this,this,Z,J),this}rotateY(Z,J){return V1.vec3.rotateY(this,this,Z,J),this}rotateZ(Z,J){return V1.vec3.rotateZ(this,this,Z,J),this}round(){return V1.vec3.round(this,this),this}scale(Z){return V1.vec3.scale(this,this,Z),this}scaleAndAdd(Z,J){return V1.vec3.scaleAndAdd(this,this,Z,J),this}subtract(Z){return V1.vec3.sub(this,this,Z),this}toString(){return`${this.x},${this.y},${this.z}`}transformMatrix3(Z){return V1.vec3.transformMat3(this,this,Z),this}transformMatrix4(Z){return V1.vec3.transformMat4(this,this,Z),this}transformQuaternion(Z){return V1.vec3.transformQuat(this,this,Z),this}zero(){return V1.vec3.zero(this),this}}var NV1=r(MV1(),1);var RV1=0.099856;class jU extends _Y{faceSpeed=0;idleLoopedAnimations=[];idleLoopedAnimationsSpeed;jumpOneshotAnimations=[];moveLoopedAnimations=[];moveLoopedAnimationsSpeed;moveSpeed=0;_faceTarget;_jumpHeight=0;_moveCompletesWhenStuck=!1;_moveIgnoreAxes={};_moveStartMoveAnimations=!1;_moveStartIdleAnimationsOnCompletion=!0;_moveStoppingDistanceSquared=RV1;_moveStuckAccumulatorMs=0;_moveStuckLastPosition;_moveTarget;_onFace;_onFaceComplete;_onMove;_onMoveComplete;_stopFaceRequested=!1;_stopMoveRequested=!1;constructor(Z={}){super();this.idleLoopedAnimations=Z.idleLoopedAnimations??this.idleLoopedAnimations,this.idleLoopedAnimationsSpeed=Z.idleLoopedAnimationsSpeed??this.idleLoopedAnimationsSpeed,this.jumpOneshotAnimations=Z.jumpOneshotAnimations??this.jumpOneshotAnimations,this.moveLoopedAnimations=Z.moveLoopedAnimations??this.moveLoopedAnimations,this.moveLoopedAnimationsSpeed=Z.moveLoopedAnimationsSpeed??this.moveLoopedAnimationsSpeed}spawn(Z){super.spawn(Z),this._startIdleAnimations(Z)}face(Z,J,X){this._faceTarget=Z,this.faceSpeed=J,this._onFace=X?.faceCallback,this._onFaceComplete=X?.faceCompleteCallback}jump(Z){this._jumpHeight=Z}move(Z,J,X){this.moveSpeed=J,this._moveCompletesWhenStuck=X?.moveCompletesWhenStuck??!1,this._moveIgnoreAxes=X?.moveIgnoreAxes??{},this._moveStartIdleAnimationsOnCompletion=X?.moveStartIdleAnimationsOnCompletion??!0,this._moveStartMoveAnimations=!0,this._moveStoppingDistanceSquared=X?.moveStoppingDistance?X.moveStoppingDistance**2:RV1,this._moveTarget=Z,this._onMove=X?.moveCallback,this._onMoveComplete=X?.moveCompleteCallback,this._moveStuckAccumulatorMs=0,this._moveStuckLastPosition=void 0}stopFace(){this._stopFaceRequested=!0}stopMove(){this._stopMoveRequested=!0}tick(Z,J){if(super.tick(Z,J),!this._moveTarget&&!this._faceTarget&&!this._jumpHeight)return;if(this._moveStartMoveAnimations)this._startMoveAnimations(Z),this._moveStartMoveAnimations=!1;let X=J/1000,Y=Z.position;if(Z.isDynamic&&this._jumpHeight>0){let $=Math.abs(Z.world.simulation.gravity.y),Q=Math.sqrt(2*$*this._jumpHeight);Z.applyImpulse({x:0,y:Q*Z.mass,z:0}),this._jumpHeight=0,this._startJumpAnimations(Z)}if(this._moveTarget){let $={x:this._moveIgnoreAxes.x?0:this._moveTarget.x-Y.x,y:this._moveIgnoreAxes.y?0:this._moveTarget.y-Y.y,z:this._moveIgnoreAxes.z?0:this._moveTarget.z-Y.z},Q=$.x*$.x+$.y*$.y+$.z*$.z,K=!1;if(this._moveCompletesWhenStuck){if(this._moveStuckAccumulatorMs+=J,this._moveStuckAccumulatorMs>=500){if(this._moveStuckLastPosition){let G=Y.x-this._moveStuckLastPosition.x,W=Y.y-this._moveStuckLastPosition.y,H=Y.z-this._moveStuckLastPosition.z;K=Math.sqrt(G*G+W*W+H*H)<this.moveSpeed*0.1}this._moveStuckLastPosition=Y,this._moveStuckAccumulatorMs=0}}if(Q>this._moveStoppingDistanceSquared&&!this._stopMoveRequested&&!K){let G=Math.sqrt(Q),W=this.moveSpeed*X,V=Math.min(G,W)/G,F={x:Y.x+$.x*V,y:Y.y+$.y*V,z:Y.z+$.z*V};if(Z.setPosition(F),this._onMove)this._onMove(F,this._moveTarget)}else{if(this._moveStuckAccumulatorMs=0,this._moveStuckLastPosition=void 0,this._moveTarget=void 0,this._stopMoveRequested=!1,this._moveStartIdleAnimationsOnCompletion)this._startIdleAnimations(Z);if(this._onMoveComplete){let G=this._onMoveComplete;this._onMove=void 0,this._onMoveComplete=void 0,G(Y)}}}if(this._faceTarget){let $={x:this._faceTarget.x-Y.x,z:this._faceTarget.z-Y.z},Q=Math.atan2(-$.x,-$.z),K=Z.rotation,G=Math.atan2(2*(K.w*K.y),1-2*(K.y*K.y)),W=Q-G;while(W>Math.PI)W-=2*Math.PI;while(W<-Math.PI)W+=2*Math.PI;if(Math.abs(W)>0.01&&!this._stopFaceRequested){let H=this.faceSpeed*X,V=Math.abs(W)<H?W:Math.sign(W)*H,z=(G+V)/2,q={x:0,y:Math.fround(Math.sin(z)),z:0,w:Math.fround(Math.cos(z))};if(Z.setRotation(q),this._onFace)this._onFace(K,q)}else if(this._faceTarget=void 0,this._stopFaceRequested=!1,this._onFaceComplete){let H=this._onFaceComplete;this._onFace=void 0,this._onFaceComplete=void 0,H(Z.rotation)}}}_startIdleAnimations(Z){if(this.idleLoopedAnimationsSpeed)Z.setModelAnimationsPlaybackRate(this.idleLoopedAnimationsSpeed);Z.stopModelAnimations(this.moveLoopedAnimations),Z.stopModelAnimations(this.jumpOneshotAnimations),Z.startModelLoopedAnimations(this.idleLoopedAnimations)}_startJumpAnimations(Z){Z.stopModelAnimations(this.moveLoopedAnimations),Z.stopModelAnimations(this.idleLoopedAnimations),Z.startModelOneshotAnimations(this.jumpOneshotAnimations)}_startMoveAnimations(Z){if(this.moveLoopedAnimationsSpeed)Z.setModelAnimationsPlaybackRate(this.moveLoopedAnimationsSpeed);Z.stopModelAnimations(this.jumpOneshotAnimations),Z.stopModelAnimations(this.idleLoopedAnimations),Z.startModelLoopedAnimations(this.moveLoopedAnimations)}}class Am extends jU{_debug=!1;_entity;_maxFall=0;_maxJump=0;_maxOpenSetIterations=200;_onPathfindAbort;_onPathfindComplete;_onWaypointMoveComplete;_onWaypointMoveSkipped;_speed=0;_target;_verticalPenalty=0;_waypoints=[];_waypointNextIndex=0;_waypointStoppingDistance;_waypointTimeoutMs=2000;constructor(Z={}){super(Z)}get debug(){return this._debug}get maxFall(){return this._maxFall}get maxJump(){return this._maxJump}get maxOpenSetIterations(){return this._maxOpenSetIterations}get speed(){return this._speed}get target(){return this._target}get verticalPenalty(){return this._verticalPenalty}get waypoints(){return this._waypoints}get waypointNextIndex(){return this._waypointNextIndex}get waypointTimeoutMs(){return this._waypointTimeoutMs}pathfind(Z,J,X){if(this._target=Z,this._speed=J,this._debug=X?.debug??!1,this._maxFall=X?.maxFall?-Math.abs(X.maxFall):0,this._maxJump=X?.maxJump?Math.abs(X.maxJump):0,this._maxOpenSetIterations=X?.maxOpenSetIterations??200,this._onPathfindAbort=X?.pathfindAbortCallback,this._onPathfindComplete=X?.pathfindCompleteCallback,this._onWaypointMoveComplete=X?.waypointMoveCompleteCallback,this._onWaypointMoveSkipped=X?.waypointMoveSkippedCallback,this._verticalPenalty=X?.verticalPenalty??0,this._waypoints=[],this._waypointNextIndex=0,this._waypointStoppingDistance=X?.waypointStoppingDistance,this._waypointTimeoutMs=X?.waypointTimeoutMs??2000/J,!this._calculatePath())return!1;return this._moveToNextWaypoint(),!0}attach(Z){super.attach(Z),this._entity=Z}detach(Z){super.detach(Z),this._entity=void 0}_calculatePath(){if(!this._target||!this._entity?.world)return d.error("PathfindingEntityController._calculatePath: No target or world"),!1;let Z=this._entity.height,J=this._findGroundedStart();if(!J){if(this._debug)d.warning(`PathfindingEntityController._calculatePath: No valid grounded start found within maxFall distance, path search aborted. Start: ${this._coordinateToKey(this._target)}, Target: ${this._coordinateToKey(this._target)}`);return!1}let X={x:Math.floor(this._target.x),y:Math.floor(this._target.y),z:Math.floor(this._target.z)},Y=Math.abs(X.x-J.x),$=Math.abs(X.y-J.y),Q=Math.abs(X.z-J.z);if(Y<=2&&$<=2&&Q<=2&&!this._isNeighborCoordinateBlocked(J,X,this._entity.height))return this._waypoints=[{x:J.x+0.5,y:J.y+Z/2,z:J.z+0.5},{x:X.x+0.5,y:X.y+Z/2,z:X.z+0.5}],!0;if(J.x===X.x&&J.y===X.y&&J.z===X.z)return this._waypoints=[{x:J.x+0.5,y:J.y+Z/2,z:J.z+0.5}],!0;let G=this._coordinateToKey(J),W=new Map,H=new Map([[G,0]]),V=new Map([[G,this._pathfindingHeuristic(J,X)]]),F=new Set,z=new NV1.Heap((M,R)=>{let D=V.get(M[0])??1/0,N=V.get(R[0])??1/0;return D-N});z.push([G,J]);let q=[{x:0,y:0,z:1},{x:1,y:0,z:0},{x:0,y:0,z:-1},{x:-1,y:0,z:0},{x:1,y:0,z:1},{x:1,y:0,z:-1},{x:-1,y:0,z:1},{x:-1,y:0,z:-1}],U=[];for(let M=this._maxJump;M>=this._maxFall;M--){if(M===0)continue;let R=Math.abs(J.y+M-X.y);U.push({y:M,distanceToTargetY:R})}U.sort((M,R)=>M.distanceToTargetY-R.distanceToTargetY);let B=[...q,...U.flatMap(({y:M})=>q.map((R)=>({...R,y:M})))],L=0,w=Math.abs(X.x-J.x)+Math.abs(X.y-J.y)+Math.abs(X.z-J.z),O=Math.min(this._maxOpenSetIterations,w*20);while(!z.isEmpty()&&L<O){L++;let[M,R]=z.pop();if(R.x===X.x&&R.y===X.y&&R.z===X.z){let C=this._reconstructPath(W,R);if(this._waypoints=C.map((T)=>({x:T.x+0.5,y:T.y+Z/2,z:T.z+0.5})),this._debug)console.log(`PathfindingEntityController._calculatePath: Path found after ${L} open set iterations. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`);return!0}F.add(M);let D=H.get(M),N=new Map;for(let C of B){let T=`${C.x},${C.z}`,E=C.y<0;if(E&&N.has(T))continue;let x={x:R.x+C.x,y:R.y+C.y,z:R.z+C.z};if(Math.abs(X.x-x.x)+Math.abs(X.y-x.y)+Math.abs(X.z-x.z)>w*1.5)continue;let h=this._coordinateToKey(x);if(F.has(h))continue;let I=this._isNeighborCoordinateBlocked(R,x,this._entity.height);if(E&&I){N.set(T,!0);continue}if(I)continue;let _=Math.abs(C.x),A=Math.abs(C.y),p=Math.abs(C.z),n=A===0?0:this._verticalPenalty,o=(Math.max(_,A,p)===1&&_+A+p>1?1.4:1)+n,Q0=D+o,G0=H.get(h)??1/0;if(Q0>=G0)continue;W.set(h,R),H.set(h,Q0);let S0=Q0+this._pathfindingHeuristic(x,X);V.set(h,S0),z.push([h,x])}}if(L>=O){if(this._onPathfindAbort?.(),this._debug)d.warning(`PathfindingEntityController._calculatePath: Maximum open set iterations reached (${O}), path search aborted. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`)}else if(this._debug)d.warning(`PathfindingEntityController._calculatePath: No valid path found. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`);return this._target=void 0,this._waypoints=[],!1}_reconstructPath(Z,J){let X=[J],Y=J;while(Z.has(this._coordinateToKey(Y)))Y=Z.get(this._coordinateToKey(Y)),X.unshift(Y);return X}_coordinateToKey(Z){return`${Z.x},${Z.y},${Z.z}`}_moveToNextWaypoint(){let Z=this._waypointNextIndex>0?this._waypoints[this._waypointNextIndex-1]:void 0,J=this._waypoints[this._waypointNextIndex];if(!J||!this._entity)return;let X=0;if(this._entity.isDynamic&&Z&&J.y>Z.y){let Y=J.y-Z.y,$=Math.min(Y,this._maxJump)+0.75;this.jump($);let Q=Math.abs(this._entity.world.simulation.gravity.y),K=Math.sqrt(2*Q*$),G=Z.x+0.5,W=Z.z+0.5,H=J.x+0.5,V=J.z+0.5,F=H-G,z=V-W,q=Math.sqrt(F*F+z*z),U=K/Q,B=q/this._speed;X=Math.min(U*0.8,B)*1000}setTimeout(()=>{if(!this._entity)return;let Y=Date.now();this.face(J,this._speed),this.move(J,this._speed,{moveCompletesWhenStuck:!0,moveIgnoreAxes:{y:this._entity.isDynamic},moveStartIdleAnimationsOnCompletion:this._waypointNextIndex===this._waypoints.length-1,moveStoppingDistance:this._waypointStoppingDistance,moveCallback:()=>{if(Date.now()-Y>this._waypointTimeoutMs&&this._waypointNextIndex<this._waypoints.length-1)this._onWaypointMoveSkipped?.(J,this._waypointNextIndex),this._waypointNextIndex++,this._moveToNextWaypoint()},moveCompleteCallback:()=>{if(this._waypointNextIndex<this._waypoints.length-1)this._onWaypointMoveComplete?.(J,this._waypointNextIndex),this._waypointNextIndex++,this._moveToNextWaypoint();else this._onPathfindComplete?.()}})},X)}_pathfindingHeuristic(Z,J){return Math.abs(Z.x-J.x)+Math.abs(Z.y-J.y)+Math.abs(Z.z-J.z)}_isNeighborCoordinateBlocked(Z,J,X){if(!this._entity?.world)return!1;let Y=this._entity.world,$=Math.floor(J.x),Q=Math.floor(J.y),K=Math.floor(J.z),G=Math.floor(Z.x),W=Math.floor(Z.z);if(!Y.chunkLattice.hasBlock({x:$,y:Q-1,z:K}))return!0;for(let H=0;H<X;H++)if(Y.chunkLattice.hasBlock({x:$,y:Q+H,z:K}))return!0;if($!==G&&K!==W)for(let H=0;H<X;H++){let V=Y.chunkLattice.hasBlock({x:$,y:Q+H,z:W}),F=Y.chunkLattice.hasBlock({x:G,y:Q+H,z:K});if(V||F)return!0}return!1}_findGroundedStart(){if(!this._entity?.world)return;let{x:Z,y:J,z:X}=this._entity.position,Y={x:Math.floor(Z),y:Math.floor(J),z:Math.floor(X)};for(let $=0;$<=Math.abs(this._maxFall);$++)if(this._entity.world.chunkLattice.hasBlock({...Y,y:Y.y-$-1}))return{...Y,y:Y.y-$};return}}export{ZK6 as startServer,S31 as WorldManagerEvent,EY as WorldManager,_31 as WorldLoopEvent,LU as WorldLoop,Dm as WorldEvent,BU as World,sv as WebServerEvent,FW as WebServer,R3 as Vector3,wU as Vector2,UU as Ticker,qU as TickAllocator,YK as TelemetrySpanOperation,r1 as Telemetry,Pm as SimulationEvent,VU as Simulation,jU as SimpleEntityController,FU as SceneUIManager,tI as SceneUIEvent,tV as SceneUI,Q50 as SUPPORTED_INPUT_KEYS,BV as RigidBodyType,O$ as RigidBody,M3 as Quaternion,lw as PlayerUIEvent,iV as PlayerUI,v31 as PlayerManagerEvent,q9 as PlayerManager,nV as PlayerEvent,y7 as PlayerEntity,$50 as PlayerCameraMode,aI as PlayerCameraEvent,pV as PlayerCamera,CG as Player,E$ as PersistenceManager,Am as PathfindingEntityController,zU as ParticleEmitterManager,Mm as ParticleEmitterEvent,Rm as ParticleEmitter,nv as PORT,V50 as PLAYER_ROTATION_UPDATE_THRESHOLD,H50 as PLAYER_POSITION_UPDATE_THRESHOLD_SQ,S5 as ModelRegistry,P5 as Matrix4,UZ as Matrix3,WK as Matrix2,I31 as LightType,WU as LightManager,jm as LightEvent,Om as Light,z6 as IterationMap,x31 as GameServerEvent,$K as GameServer,O0 as EventRouter,d as ErrorHandler,eV as EntityManager,rV as EntityEvent,i8 as Entity,W50 as ENTITY_ROTATION_UPDATE_THRESHOLD,G50 as ENTITY_POSITION_UPDATE_THRESHOLD_SQ,y1 as DefaultPlayerEntityController,eI as DefaultPlayerEntity,K50 as DEFAULT_ENTITY_RIGID_BODY_OPTIONS,T4 as CollisionGroupsBuilder,yY as CollisionGroup,wV as ColliderShape,oV as ColliderMap,Q9 as Collider,qk as CoefficientCombineRule,rI as ChunkLatticeEvent,sV as ChunkLattice,W9 as Chunk,aV as ChatManager,sI as ChatEvent,Lk as BlockTypeRegistryEvent,jV as BlockTypeRegistry,Uk as BlockTypeEvent,K9 as BlockType,FK as Block,mm as BaseEntityControllerEvent,_Y as BaseEntityController,D3 as AudioManager,CP as AudioEvent,P3 as Audio};
|