hytopia 0.6.5 → 0.6.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/node-server.mjs CHANGED
@@ -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 Vv=process.env.PORT??8080,Hv="0.6.5",zv;(($)=>{$.READY="WEBSERVER.READY";$.STOPPED="WEBSERVER.STOPPED";$.ERROR="WEBSERVER.ERROR";$.UPGRADE="WEBSERVER.UPGRADE"})(zv||={});class TW extends g0{static instance=new TW;_webserver=DO.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:Hv,runtime:typeof Bun!=="undefined"?"bun":"node"})}),this._webserver.use(DO.default.static("assets"));try{this._webserver.use(DO.default.static(Rn1.dirname(g.resolve("/Users/arkdev/Desktop/HYTOPIA/hytopia/assets/release/index.js"))))}catch{}}start(){if(!this._internalHttpServer)this._internalHttpServer=process.env.NODE_ENV==="production"?jn1.createServer(this._webserver):Nn1.createServer({key:PO.existsSync("assets/certs/localhost.key")?PO.readFileSync("assets/certs/localhost.key"):yY0,cert:PO.existsSync("assets/certs/localhost.crt")?PO.readFileSync("assets/certs/localhost.crt"):fY0},this._webserver),this._internalHttpServer.on("upgrade",this._onUpgrade),this._internalHttpServer.on("error",this._onError),this._internalHttpServer.on("close",this._onStopped);else u.warning("WebServer.start(): server already started!");this._internalHttpServer.listen(Vv,this._onStarted),console.info(`WebServer.start(): Server running on port ${Vv}.`)}stop(){if(this._internalHttpServer)return new Promise((Z,J)=>{this._internalHttpServer.close((X)=>{if(X)J(X);else Z(!0)})});else return u.warning("WebServer.stop(): server not started."),Promise.resolve(!1)}_onStarted=()=>{this.emitWithGlobal("WEBSERVER.READY",{})};_onUpgrade=async(Z,J,X)=>{let Y=Mn1.parse(Z.url??"",!0).query,$=Y.connectionId?.toString()??void 0,Q=Y.sessionToken?.toString()??"",K=await I7.instance.getPlayerSession(Q);if($)Z.connectionId=$;if(K)if(!K.error)Z.session=K;else{let W=`${K.error.code}: ${K.error.message}`;J.write(`HTTP/1.1 401 Unauthorized\r
460
+ -----END RSA PRIVATE KEY-----`;var Vv=process.env.PORT??8080,Hv="0.6.6",zv;(($)=>{$.READY="WEBSERVER.READY";$.STOPPED="WEBSERVER.STOPPED";$.ERROR="WEBSERVER.ERROR";$.UPGRADE="WEBSERVER.UPGRADE"})(zv||={});class TW extends g0{static instance=new TW;_webserver=DO.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:Hv,runtime:typeof Bun!=="undefined"?"bun":"node"})}),this._webserver.use(DO.default.static("assets"));try{this._webserver.use(DO.default.static(Rn1.dirname(g.resolve("/Users/arkdev/Desktop/HYTOPIA/hytopia/assets/release/index.js"))))}catch{}}start(){if(!this._internalHttpServer)this._internalHttpServer=process.env.NODE_ENV==="production"?jn1.createServer(this._webserver):Nn1.createServer({key:PO.existsSync("assets/certs/localhost.key")?PO.readFileSync("assets/certs/localhost.key"):yY0,cert:PO.existsSync("assets/certs/localhost.crt")?PO.readFileSync("assets/certs/localhost.crt"):fY0},this._webserver),this._internalHttpServer.on("upgrade",this._onUpgrade),this._internalHttpServer.on("error",this._onError),this._internalHttpServer.on("close",this._onStopped);else u.warning("WebServer.start(): server already started!");this._internalHttpServer.listen(Vv,this._onStarted),console.info(`WebServer.start(): Server running on port ${Vv}.`)}stop(){if(this._internalHttpServer)return new Promise((Z,J)=>{this._internalHttpServer.close((X)=>{if(X)J(X);else Z(!0)})});else return u.warning("WebServer.stop(): server not started."),Promise.resolve(!1)}_onStarted=()=>{this.emitWithGlobal("WEBSERVER.READY",{})};_onUpgrade=async(Z,J,X)=>{let Y=Mn1.parse(Z.url??"",!0).query,$=Y.connectionId?.toString()??void 0,Q=Y.sessionToken?.toString()??"",K=await I7.instance.getPlayerSession(Q);if($)Z.connectionId=$;if(K)if(!K.error)Z.session=K;else{let W=`${K.error.code}: ${K.error.message}`;J.write(`HTTP/1.1 401 Unauthorized\r
461
461
  `),J.write(`Content-Type: text/plain\r
462
462
  `),J.write(`Content-Length: ${W.length}\r
463
463
  `),J.write(`Connection: close\r
@@ -488,4 +488,4 @@ Event: ${VX(Z)}`),!0}return!1}function ta1(Z,J){if(!J?.length)return!1;return Zj
488
488
  `),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(" "),j={};for(let N of q){if(!N)continue;let R=N.indexOf(":");if(R===-1)return Z.destroy(),X(new Error(`Invalid header from proxy CONNECT response: "${N}"`));let D=N.slice(0,R).toLowerCase(),P=N.slice(R+1).trimStart(),C=j[D];if(typeof C==="string")j[D]=[C,P];else if(Array.isArray(C))C.push(P);else j[D]=P}ER("got proxy server response: %o %o",U,j),K(),J({connect:{statusCode:L,statusText:w,headers:j},buffered:F})}Z.on("error",G),Z.on("end",W),Q()})}function Xq(...Z){l.log("[https-proxy-agent]",...Z)}class kR extends My{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??{},Xq("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?xQ1(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:"){Xq("Creating `tls.Socket`: %o",this.connectOpts);let F=this.connectOpts.servername||this.connectOpts.host;Y=Py.connect({...this.connectOpts,servername:F&&WJ.isIP(F)?void 0:F})}else Xq("Creating `net.Socket`: %o",this.connectOpts),Y=WJ.connect(this.connectOpts);let $=typeof this.proxyHeaders==="function"?this.proxyHeaders():{...this.proxyHeaders},Q=WJ.isIPv6(J.host)?`[${J.host}]`:J.host,K=`CONNECT ${Q}:${J.port} HTTP/1.1\r
489
489
  `;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
490
490
  `;let W=AQ1(Y);Y.write(`${K}\r
491
- `);let{connect:G,buffered:V}=await W;if(Z.emit("proxyConnect",G),this.emit("proxyConnect",G,Z),G.statusCode===200){if(Z.once("socket",IZ6),J.secureEndpoint){Xq("Upgrading socket connection to TLS");let F=J.servername||J.host;return Py.connect({...xQ1(J,"host","path","port"),socket:Y,servername:WJ.isIP(F)?void 0:F})}return Y}Y.destroy();let H=new WJ.Socket({writable:!1});return H.readable=!0,Z.once("socket",(F)=>{Xq("Replaying proxy buffer for failed request"),F.push(V),F.push(null)}),H}}kR.__initStatic();function IZ6(Z){Z.resume()}function xQ1(Z,...J){let X={},Y;for(Y in Z)if(!J.includes(Y))X[Y]=Z[Y];return X}var xZ6=32768;function hZ6(Z){return new SZ6({read(){this.push(Z),this.push(null)}})}function hQ1(Z){let J;try{J=new URL(Z.url)}catch(G){return P8(()=>{console.warn("[@sentry/node]: Invalid dsn or tunnel option, will not send any events. The tunnel option must be a full URL when used.")}),fz(Z,()=>Promise.resolve({}))}let X=J.protocol==="https:",Y=fZ6(J,Z.proxy||(X?process.env.https_proxy:void 0)||process.env.http_proxy),$=X?vZ6:_Z6,Q=Z.keepAlive===void 0?!1:Z.keepAlive,K=Y?new kR(Y):new $.Agent({keepAlive:Q,maxSockets:30,timeout:2000}),W=yZ6(Z,Z.httpModule??$,K);return fz(Z,W)}function fZ6(Z,J){let{no_proxy:X}=process.env;if(X?.split(",").some(($)=>Z.host.endsWith($)||Z.hostname.endsWith($)))return;else return J}function yZ6(Z,J,X){let{hostname:Y,pathname:$,port:Q,protocol:K,search:W}=new URL(Z.url);return function G(V){return new Promise((H,F)=>{pO(()=>{let z=hZ6(V.body),q={...Z.headers};if(V.body.length>xZ6)q["content-encoding"]="gzip",z=z.pipe(AZ6());let U=J.request({method:"POST",agent:X,headers:q,hostname:Y,path:`${$}${W}`,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;H({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 bZ6=new Set(["false","f","n","no","off","0"]),gZ6=new Set(["true","t","y","yes","on","1"]);function IR(Z,J){let X=String(Z).toLowerCase();if(bZ6.has(X))return!1;if(gZ6.has(X))return!0;return J?.strict?null:Boolean(Z)}import{posix as mZ6,sep as uZ6}from"node:path";function fQ1(Z){return Z.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}function yQ1(Z=process.argv[1]?WS(process.argv[1]):process.cwd(),J=uZ6==="\\"){let X=J?fQ1(Z):Z;return(Y)=>{if(!Y)return;let $=J?fQ1(Y):Y,{dir:Q,base:K,ext:W}=mZ6.parse($);if(W===".js"||W===".mjs"||W===".cjs")K=K.slice(0,W.length*-1);let G=decodeURIComponent(K);if(!Q)Q=".";let V=Q.lastIndexOf("/node_modules");if(V>-1)return`${Q.slice(V+14).replace(/\//g,".")}:${G}`;if(Q.startsWith(X)){let H=Q.slice(X.length+1).replace(/\//g,".");return H?`${H}:${G}`:G}return G}}function bQ1(Z){if(process.env.SENTRY_RELEASE)return process.env.SENTRY_RELEASE;if(k0.SENTRY_RELEASE?.id)return k0.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 gQ1=bO(GS(yQ1()));var uQ1=r(Z0(),1),dQ1=r(V1(),1);import*as mQ1 from"node:os";import{threadId as dZ6,isMainThread as cZ6}from"worker_threads";var lZ6=60000;class Dy extends Xj{constructor(Z){let J=Z.serverName||global.process.env.SENTRY_NAME||mQ1.hostname(),X={...Z,platform:"node",runtime:{name:"node",version:global.process.version},serverName:J};if(Z.openTelemetryInstrumentations)dQ1.registerInstrumentations({instrumentations:Z.openTelemetryInstrumentations});YS(X,"node"),l.log(`Initializing Sentry: process: ${process.pid}, thread: ${cZ6?"main":`worker-${dZ6}`}.`);super(X);if(this.getOptions()._experiments?.enableLogs){if(this._logOnExitFlushListener=()=>{v$(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=x8,X=uQ1.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&&l.log("Flushing client reports based on interval."),this._flushOutcomes()},Z.clientReportFlushInterval??lZ6).unref(),process.on("beforeExit",this._clientReportOnExitFlushListener)}_getTraceInfoFromScope(Z){if(!Z)return[void 0,void 0];return C61(this,Z)}}var a4=r(Z0(),1),cQ1=r(Eh(),1),lQ1=r(_h(),1),AG=r(v1(),1);var pQ1=r(gx(),1);import pZ6 from"module";var Cy=1e6;function iQ1(Z,J={}){if(Z.getOptions().debug)aZ6();let X=iZ6(Z,J);Z.traceProvider=X}function nQ1(){let[Z=0,J=0]=process.versions.node.split(".").map(Number);if(Z>=21||Z===20&&J>=6||Z===18&&J>=19){if(!k0._sentryEsmLoaderHookRegistered)try{let{addHookMessagePort:X}=pQ1.createAddHookMessageChannel();pZ6.register("import-in-the-middle/hook.mjs",import.meta.url,{data:{addHookMessagePort:X,include:[]},transferList:[X]})}catch(X){l.warn("Failed to register ESM hook",X)}}else P8(()=>{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 iZ6(Z,J={}){let X=new lQ1.BasicTracerProvider({sampler:new oh(Z),resource:new cQ1.Resource({[AG.ATTR_SERVICE_NAME]:"node",[AG.SEMRESATTRS_SERVICE_NAMESPACE]:"sentry",[AG.ATTR_SERVICE_VERSION]:x8}),forceFlushTimeoutMillis:500,spanProcessors:[new sh({timeout:nZ6(Z.getOptions().maxSpanWaitDuration)}),...J.spanProcessors||[]]});return a4.trace.setGlobalTracerProvider(X),a4.propagation.setGlobalPropagator(new lh),a4.context.setGlobalContextManager(new _Q1),X}function nZ6(Z){if(Z==null)return;if(Z>Cy)return m0&&l.warn(`\`maxSpanWaitDuration\` is too high, using the maximum value of ${Cy}`),Cy;else if(Z<=0||Number.isNaN(Z)){m0&&l.warn("`maxSpanWaitDuration` must be a positive number, using default value instead.");return}return Z}function aZ6(){let Z=new Proxy(l,{get(J,X,Y){return Reflect.get(J,X==="verbose"?"debug":X,Y)}});a4.diag.disable(),a4.diag.setLogger(Z,a4.DiagLogLevel.DEBUG)}function sZ6(){return RG()?[T51()]:[]}function aQ1(){return[Kj(),$j(),Wj(),Gj(),Vj(),b61(),K51(),E51(),k51(),L51(),P51(),V51(),BQ1(),vQ1(),...sZ6()]}function sQ1(Z){return[...aQ1(),...K9(Z)?SQ1():[]]}function Ty(Z={}){return oZ6(Z,sQ1)}function oZ6(Z={},J){let X=rZ6(Z,J);if(X.debug===!0)if(m0)l.enable();else P8(()=>{console.warn("[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.")});if(!RG()&&X.registerEsmLoaderHooks!==!1)nQ1();if(E61(),j1().update(X.initialScope),X.spotlight&&!X.integrations.some(({name:Q})=>Q===Uy))X.integrations.push(G$1({sidecarUrl:typeof X.spotlight==="string"?X.spotlight:void 0}));let $=new Dy(X);if(j1().setClient($),$.init(),l.log(`Running in ${RG()?"CommonJS":"ESM"} mode.`),$.startClientReportTracking(),ZJ6(),!X.skipOpenTelemetrySetup)iQ1($,{spanProcessors:X.openTelemetrySpanProcessors}),oQ1();return B61($),T61($),$}function oQ1(){if(!m0)return;let Z=N61(),J=["SentryContextManager","SentryPropagator"];if(K9())J.push("SentrySpanProcessor");for(let X of J)if(!Z.includes(X))l.error(`You have to set up the ${X}. Without this, the OpenTelemetry & Sentry integration will not work properly.`);if(!Z.includes("SentrySampler"))l.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 rZ6(Z,J){let X=tZ6(Z.release),Y=Z.spotlight??IR(process.env.SENTRY_SPOTLIGHT,{strict:!0})??process.env.SENTRY_SPOTLIGHT,$=eZ6(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??hQ1,stackParser:Sv(Z.stackParser||gQ1),release:X,tracesSampleRate:$,spotlight:Y,debug:IR(Z.debug??process.env.SENTRY_DEBUG)},K=Z.integrations,W=Z.defaultIntegrations??J(Q);return{...Q,integrations:sv({defaultIntegrations:W,integrations:K})}}function tZ6(Z){if(Z!==void 0)return Z;let J=bQ1();if(J!==void 0)return J;return}function eZ6(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 ZJ6(){if(IR(process.env.SENTRY_USE_ENVIRONMENT)!==!1){let Z=process.env.SENTRY_TRACE,J=process.env.SENTRY_BAGGAGE,X=Cz(Z,J);j1().setPropagationContext(X)}}if(process.env.NODE_ENV==="production"&&process.env.SENTRY_DSN)Ty({dsn:process.env.SENTRY_DSN,release:Hv,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:(Z)=>{return Z.extra=X8.getProcessStats(),Z},beforeSendTransaction:(Z)=>{if(Z.contexts?.trace?.op==="ticker_tick"){let X=Z?.start_timestamp,Y=Z?.timestamp;if(!X||!Y)return null;if((Y-X)*1000>30)return Z.measurements=X8.getProcessStats(!0),Z}return null}}),console.log("Telemetry: Sentry.io initialized!");class X8{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 startSpan(Z,J){if(tO())return lO({attributes:Z.attributes,name:Z.operation,op:Z.operation},J);else return J()}}var rQ1=new Y$,XJ6=5000;class M$ extends g0{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=o80(),this.onPacket(X0.PacketId.CONNECTION,this._onConnectionPacket),this.onPacket(X0.PacketId.HEARTBEAT,this._onHeartbeatPacket),this.bindWs(Z),F6.emit("CONNECTION.OPENED",{connection:this,req:J})}static serializePackets(Z){for(let X of Z)if(!X0.isValidPacket(X))return u.error(`Connection.serializePackets(): Invalid packet payload: ${JSON.stringify(X)}`);let J=M$._cachedPacketsSerializedBuffer.get(Z);if(J)return J;return X8.startSpan({operation:"serialize_packets",attributes:{packets:Z.length,packetIds:Z.map((X)=>X[0]).join(",")}},(X)=>{let Y=X8.startSpan({operation:"serialize_packets_encode"},()=>rQ1.pack(Z));return X?.setAttribute("serializedBytes",Y.byteLength),M$._cachedPacketsSerializedBuffer.set(Z,Y),Y})}bindWs(Z){let J=this._closeTimeout!==null;if(J)clearTimeout(this._closeTimeout),this._closeTimeout=null;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([X0.createPacket(X0.bidirectionalPackets.connectionPacketDefinition,{i:this.id})],!0,!0),J)this.emitWithGlobal("CONNECTION.RECONNECTED",{connection:this});if(QX.instance.isWrtcEnabled)this._upgradeToWRTC()}closeWrtc(){this._closeWrtcClientServerTransport(),this._closeWrtcServerClientTransport()}disconnect(){try{this._ws.close()}catch(Z){u.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!==Ik.default.OPEN)return;X8.startSpan({operation:"send_packets",attributes:{forceWs:X?"true":"false",wrtcConnected:this._wrtcServerClientTransport?.iceState==="completed"?"true":"false"}},()=>{try{let Y=M$.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){u.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([X0.createPacket(X0.bidirectionalPackets.connectionPacketDefinition,{ca:{i:$}})])}if(Y)for(let $ of Y){let{s:Q,l:K}=$,W=await this._wrtcClientServerTransport.produceData({label:K,sctpStreamParameters:Q}),G=await this._wrtcDirectTransport.consumeData({dataProducerId:W.id});this._wrtcClientServerDataProducers.push(W),this._wrtcClientServerDataConsumers.push(G),G.on("message",(V)=>this._onMessage(V)),this.send([X0.createPacket(X0.bidirectionalPackets.connectionPacketDefinition,{pa:{i:W.id,l:K}})])}};_onHeartbeatPacket=()=>{this.send([X0.createPacket(X0.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){u.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()},XJ6)};_onWsError=(Z)=>{this.emitWithGlobal("CONNECTION.ERROR",{connection:this,error:Z})};_upgradeToWRTC=async()=>{let Z=await QX.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([X0.createPacket(X0.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=rQ1.unpack(Z);if(!J||typeof J!=="object"||typeof J[0]!=="number")return u.error(`Connection._deserialize(): Invalid packet format. Packet: ${JSON.stringify(J)}`);if(!X0.isValidPacket(J))return u.error(`Connection._deserialize(): Invalid packet payload. Packet: ${JSON.stringify(J)}`);return J}}var tQ1;((Y)=>{Y.PLAYER_CONNECTED="PLAYER_MANAGER.PLAYER_CONNECTED";Y.PLAYER_DISCONNECTED="PLAYER_MANAGER.PLAYER_DISCONNECTED";Y.PLAYER_RECONNECTED="PLAYER_MANAGER.PLAYER_RECONNECTED"})(tQ1||={});class Y9{static instance=new Y9;_connectionPlayers=new Map;constructor(){F6.on("CONNECTION.OPENED",({connection:Z,req:J})=>{this._onConnectionOpened(Z,J.session)}),F6.on("CONNECTION.DISCONNECTED",({connection:Z})=>{this._onConnectionDisconnected(Z)}),F6.on("CONNECTION.RECONNECTED",({connection:Z})=>{this._onConnectionReconnected(Z)}),F6.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()})}_onConnectionOpened(Z,J){let X=new xG(Z,J);this._connectionPlayers.set(Z,X),F6.emit("PLAYER_MANAGER.PLAYER_CONNECTED",{player:X})}_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.reconnect(),F6.emit("PLAYER_MANAGER.PLAYER_RECONNECTED",{player:J});else u.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),F6.emit("PLAYER_MANAGER.PLAYER_DISCONNECTED",{player:J});else u.warning(`PlayerManager._onConnectionClosed(): Connection ${Z.id} not in the PlayerManager._connectionPlayers map.`)}}var E8=16,hG=E8-1,eQ1=E8**3,YJ6=[{neighborOffset:[-1,0,0],generateVertices:(Z,J,X)=>[Z+0,J+0,X+0,Z+0,J+0,X+1,Z+0,J+1,X+0,Z+0,J+1,X+0,Z+0,J+0,X+1,Z+0,J+1,X+1]},{neighborOffset:[1,0,0],generateVertices:(Z,J,X)=>[Z+1,J+0,X+0,Z+1,J+1,X+0,Z+1,J+0,X+1,Z+1,J+1,X+0,Z+1,J+1,X+1,Z+1,J+0,X+1]},{neighborOffset:[0,-1,0],generateVertices:(Z,J,X)=>[Z+0,J+0,X+0,Z+1,J+0,X+0,Z+0,J+0,X+1,Z+1,J+0,X+0,Z+1,J+0,X+1,Z+0,J+0,X+1]},{neighborOffset:[0,1,0],generateVertices:(Z,J,X)=>[Z+0,J+1,X+0,Z+0,J+1,X+1,Z+1,J+1,X+0,Z+1,J+1,X+0,Z+0,J+1,X+1,Z+1,J+1,X+1]},{neighborOffset:[0,0,-1],generateVertices:(Z,J,X)=>[Z+0,J+0,X+0,Z+0,J+1,X+0,Z+1,J+0,X+0,Z+0,J+1,X+0,Z+1,J+1,X+0,Z+1,J+0,X+0]},{neighborOffset:[0,0,1],generateVertices:(Z,J,X)=>[Z+0,J+0,X+1,Z+1,J+0,X+1,Z+0,J+1,X+1,Z+0,J+1,X+1,Z+1,J+0,X+1,Z+1,J+1,X+1]}],Ey;((Y)=>{Y.DESPAWN="CHUNK.DESPAWN";Y.SET_BLOCK="CHUNK.SET_BLOCK";Y.SPAWN="CHUNK.SPAWN"})(Ey||={});class u6 extends g0{_blocks;_originCoordinate;_requiresUpdate=!1;_rigidBody;_world;constructor(){super();this._blocks=new Uint8Array(eQ1)}get blocks(){return this._blocks}get requiresUpdate(){return this._requiresUpdate}get isSimulated(){return!!this._rigidBody}get isSpawned(){return!!this._originCoordinate&&!!this._world}get originCoordinate(){return this._originCoordinate}get world(){return this._world}static blockIndexToLocalCoordinate(Z){return{x:Z%E8,y:(Z/E8|0)%E8,z:Z/(E8*E8)|0}}static globalCoordinateToLocalCoordinate(Z){return{x:Z.x&E8-1,y:Z.y&E8-1,z:Z.z&E8-1}}static globalCoordinateToOriginCoordinate(Z){return{x:Z.x&~(E8-1),y:Z.y&~(E8-1),z:Z.z&~(E8-1)}}static isValidOriginCoordinate(Z){return Z.x%E8===0&&Z.y%E8===0&&Z.z%E8===0}spawn(Z,J){if(this.isSpawned){let{x:X,y:Y,z:$}=this.originCoordinate;return u.error(`Chunk.spawn(): Chunk is already spawned at origin ${X}, ${Y}, ${$}!`)}if(!u6.isValidOriginCoordinate(J))return u.error(`Chunk.spawn(): Chunk coordinates must be divisible by ${E8}`);this._originCoordinate=J,this._world=Z,this._world.chunkLattice.registerChunk(this),this._requiresUpdate=!0}despawn(){if(!this.isSpawned)return u.error("Chunk.despawn(): Chunk has not been spawned and cannot be despawned!");this.emitWithWorld(this._world,"CHUNK.DESPAWN",{chunk:this}),this._removeFromSimulation(),this._world.chunkLattice.unregisterChunk(this),this._originCoordinate=void 0,this._world=void 0}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 u.error("Chunk.setBlock(): Block local coordinate is out of bounds");if(this._blocks[this._getIndex(Z)]===J)return;if(this._blocks[this._getIndex(Z)]=J,this.isSpawned&&this.isSimulated){this.emitWithWorld(this._world,"CHUNK.SET_BLOCK",{chunk:this,globalCoordinate:this._getGlobalCoordinate(Z),localCoordinate:Z,blockTypeId:J});let X=this._getGlobalCoordinate(Z),Y=[];if(Z.x===0)Y.push({x:-1,y:0,z:0});if(Z.y===0)Y.push({x:0,y:-1,z:0});if(Z.z===0)Y.push({x:0,y:0,z:-1});if(Z.x===hG)Y.push({x:1,y:0,z:0});if(Z.y===hG)Y.push({x:0,y:1,z:0});if(Z.z===hG)Y.push({x:0,y:0,z:1});for(let $ of Y){let Q={x:X.x+$.x,y:X.y+$.y,z:X.z+$.z},K=u6.globalCoordinateToOriginCoordinate(Q),W=this._world?.chunkLattice.getChunk(K);if(!W?.hasBlock(u6.globalCoordinateToLocalCoordinate(Q)))continue;W.setRequiresUpdate(!0)}}this._requiresUpdate=!0}setRequiresUpdate(Z){this._requiresUpdate=Z}update(){if(!this._requiresUpdate)return;if(!this.isSpawned)return u.error("Chunk.update(): Chunk is not spawned and cannot be updated.");let Z=!this._rigidBody,J=this._world.simulation;if(this._removeFromSimulation(),this._rigidBody=new dY({type:"fixed",position:this._originCoordinate,simulation:this._world.simulation}),this._meshColliders().map(([X,Y])=>{if(!X.isSimulated)X.addToSimulation(J,this._rigidBody);J.colliderMap.setColliderBlockType(X,Y)}),this._requiresUpdate=!1,Z)this.emitWithWorld(this._world,"CHUNK.SPAWN",{chunk:this})}serialize(){return p0.serializeChunk(this)}_meshColliders(){if(!this._world)return u.error("Chunk._meshColliders(): Chunk is not spawned and cannot be meshed."),[];let Z=new Map,J=[];for(let Y=0;Y<eQ1;Y++){if(this._blocks[Y]===0)continue;let $=this._blocks[Y],Q=this._world.blockTypeRegistry.getBlockType($),{x:K,y:W,z:G}=u6.blockIndexToLocalCoordinate(Y);if(!Q.isMeshable){let H=Q.createCollider();H.setRelativePosition({x:K,y:W,z:G}),J.push([H,Q]);continue}let V=Z.get(Q)??{indices:[],vertices:[]};Z.set(Q,V);for(let H of YJ6){let[F,z,q]=H.neighborOffset,U={x:K+F,y:W+z,z:G+q},B=this._getGlobalCoordinate(U),L=this._world.chunkLattice.getBlockType(B);if(L&&!L.isLiquid)continue;let w=V.indices.length;V.indices.push(w,w+1,w+2,w+3,w+4,w+5),V.vertices.push(...H.generateVertices(K,W,G))}}let X=[];return Z.forEach((Y,$)=>{if(!Y.indices.length)return;let Q=$.createCollider(new Uint32Array(Y.indices),new Float32Array(Y.vertices));X.push([Q,$])}),[...J,...X]}_removeFromSimulation(){if(!this._rigidBody||!this._world)return;this._rigidBody.removeFromSimulation(),this._rigidBody=void 0}_getGlobalCoordinate(Z){if(!this.originCoordinate)u.fatalError("Chunk._getGlobalCoordinate(): Chunk is not spawned, calculating global coordinate is impossible.");return{x:this.originCoordinate.x+Z.x,y:this.originCoordinate.y+Z.y,z:this.originCoordinate.z+Z.z}}_getIndex(Z){return Z.x+E8*(Z.y+E8*Z.z)}_isValidLocalCoordinate(Z){return Z.x>=0&&Z.x<=hG&&Z.y>=0&&Z.y<=hG&&Z.z>=0&&Z.z<=hG}}class Yq{_chunks=new Map;_world;constructor(Z){this._world=Z}get chunkCount(){return this._chunks.size}registerChunk(Z){if(!Z.isSpawned)return u.error("ChunkLattice.registerChunk(): Chunk is not spawned.");if(this.hasChunk(Z.originCoordinate)){let{x:J,y:X,z:Y}=Z.originCoordinate;return u.error(`ChunkLattice.registerChunk(): Chunk exists at origin (${J}, ${X}, ${Y}), despawn the current chunk before registering another at the same origin.`)}if(Z.world.id!==this._world.id)return u.error("ChunkLattice.registerChunk(): Chunk world does not match lattice world.");this._chunks.set(this._getChunkKey(Z.originCoordinate),Z)}unregisterChunk(Z){if(!Z.isSpawned)return u.error("ChunkLattice.unregisterChunk(): Chunk is not spawned.");if(Z.world.id!==this._world.id)return u.error("ChunkLattice.unregisterChunk(): Chunk world does not match lattice world.");this._chunks.delete(this._getChunkKey(Z.originCoordinate))}clear(){this._chunks.forEach((Z)=>Z.despawn()),this._chunks.clear()}getBlockId(Z){let J=this.getChunk(u6.globalCoordinateToOriginCoordinate(Z));if(!J)return 0;return J.getBlockId(u6.globalCoordinateToLocalCoordinate(Z))}getBlockType(Z){let J=this.getBlockId(Z);return J?this._world.blockTypeRegistry.getBlockType(J):null}getChunk(Z){if(!u6.isValidOriginCoordinate(Z)){u.error(`ChunkLattice.getChunk(): Chunk coordinates must be divisible by CHUNK_SIZE (${E8})`);return}return this._chunks.get(this._getChunkKey(Z))}getAllChunks(){return Array.from(this._chunks.values())}hasBlock(Z){let J=this.getChunk(u6.globalCoordinateToOriginCoordinate(Z));if(!J)return!1;return J.hasBlock(u6.globalCoordinateToLocalCoordinate(Z))}hasChunk(Z){return this._chunks.has(this._getChunkKey(Z))}setBlock(Z,J){let X=u6.globalCoordinateToLocalCoordinate(Z),Y=u6.globalCoordinateToOriginCoordinate(Z),$=this.getChunk(Y);if(!$)$=new u6,$.spawn(this._world,Y);$.setBlock(X,J)}updateChunks(){this._chunks.forEach((Z)=>{if(Z.requiresUpdate)Z.update()})}_getChunkKey(Z){return`${Z.x},${Z.y},${Z.z}`}}var ZK1={type:"dynamic",softCcdPrediction:1},JK1=0.0025000000000000005,XK1=Math.cos(0.005),$q;((w)=>{w.BLOCK_COLLISION="ENTITY.BLOCK_COLLISION";w.BLOCK_CONTACT_FORCE="ENTITY.BLOCK_CONTACT_FORCE";w.DESPAWN="ENTITY.DESPAWN";w.ENTITY_COLLISION="ENTITY.ENTITY_COLLISION";w.ENTITY_CONTACT_FORCE="ENTITY.ENTITY_CONTACT_FORCE";w.SET_MODEL_ANIMATIONS_PLAYBACK_RATE="ENTITY.SET_MODEL_ANIMATIONS_PLAYBACK_RATE";w.SET_MODEL_HIDDEN_NODES="ENTITY.SET_MODEL_HIDDEN_NODES";w.SET_OPACITY="ENTITY.SET_OPACITY";w.SET_PARENT="ENTITY.SET_PARENT";w.SET_TINT_COLOR="ENTITY.SET_TINT_COLOR";w.SPAWN="ENTITY.SPAWN";w.START_MODEL_LOOPED_ANIMATIONS="ENTITY.START_MODEL_LOOPED_ANIMATIONS";w.START_MODEL_ONESHOT_ANIMATIONS="ENTITY.START_MODEL_ONESHOT_ANIMATIONS";w.STOP_MODEL_ANIMATIONS="ENTITY.STOP_MODEL_ANIMATIONS";w.TICK="ENTITY.TICK";w.UPDATE_POSITION="ENTITY.UPDATE_POSITION";w.UPDATE_ROTATION="ENTITY.UPDATE_ROTATION"})($q||={});class i8 extends dY{_id;_blockHalfExtents;_blockTextureUri;_controller;_modelAnimationsPlaybackRate=1;_modelHiddenNodes=new Set;_modelLoopedAnimations=new Set;_modelOneshotAnimations=new Set;_modelPreferredShape;_modelScale=1;_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;constructor(Z){let J="blockTextureUri"in Z,X="modelUri"in Z;if(!J===!X)u.fatalError("Entity.constructor(): Entity data must include a blockTextureUri or modelUri, but not both.");if(J&&!Z.blockHalfExtents)u.fatalError("Entity.constructor(): Block entity must have blockHalfExtents!");if(Z.parent&&!Z.parent.isSpawned)u.fatalError("Entity.constructor(): Parent entity must be spawned before child entity!");if(Z.parent?.modelUri&&Z.parentNodeName&&!_9.instance.modelHasNode(Z.parent.modelUri,Z.parentNodeName))u.fatalError(`Entity.constructor(): Parent node name ${Z.parentNodeName} not found in parent model ${Z.parent.modelUri}!`);super(Z.rigidBodyOptions??ZK1);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._modelUri=Z.modelUri,Z.modelHiddenNodes?.forEach((Y)=>this._modelHiddenNodes.add(Y.toLowerCase())),Z.modelLoopedAnimations?.forEach((Y)=>this._modelLoopedAnimations.add(Y));if(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,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 height(){return this.isModelEntity?_9.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 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 isModelEntity(){return!!this._modelUri}get isSpawned(){return!!this._world}get world(){return this._world}spawn(Z,J,X){if(this.isSpawned)return u.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 r5(r5.optionsFromBlockHalfExtents(this._blockHalfExtents)));if(this._modelUri&&this.numColliders===0&&this._modelPreferredShape!=="none")this.addChildColliderToSimulation(new r5(r5.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(H4.isDefaultCollisionGroups(Y.collisionGroups))Y.setCollisionGroups({belongsTo:[Y.isSensor?4:2],collidesWith:[65535]})}),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.sceneUIManager.unloadEntityAttachedSceneUIs(this),this._id=void 0,this._world=void 0}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})}setController(Z){if(this._controller===Z)return;if(this._controller)this._controller.detach(this);if(this._controller=Z,this._controller)this._controller.attach(this)}setModelHiddenNodes(Z){if(!this._requireSpawned("setModelHiddenNodes"))return;this._modelHiddenNodes=new Set(Z.map((J)=>J.toLowerCase())),this.emitWithWorld(this._world,"ENTITY.SET_MODEL_HIDDEN_NODES",{entity:this,modelHiddenNodes:this._modelHiddenNodes})}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 u.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(){return p0.serializeEntity(this)}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,this.emitWithWorld(this._world,"ENTITY.UPDATE_ROTATION",{entity:this,rotation:J});if(this._positionExceedsThreshold(Z,this._lastUpdatedPosition))this._lastUpdatedPosition=Z,this.emitWithWorld(this._world,"ENTITY.UPDATE_POSITION",{entity:this,position:Z})}_positionExceedsThreshold(Z,J){let X=Z.x-J.x,Y=Z.y-J.y,$=Z.z-J.z;return X*X+Y*Y+$*$>JK1}_requireSpawned(Z){if(!this.isSpawned)u.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)<XK1}_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)}}var ky;((W)=>{W.LOAD="SCENE_UI.LOAD";W.SET_ATTACHED_TO_ENTITY="SCENE_UI.SET_ATTACHED_TO_ENTITY";W.SET_OFFSET="SCENE_UI.SET_OFFSET";W.SET_POSITION="SCENE_UI.SET_POSITION";W.SET_STATE="SCENE_UI.SET_STATE";W.SET_VIEW_DISTANCE="SCENE_UI.SET_VIEW_DISTANCE";W.UNLOAD="SCENE_UI.UNLOAD"})(ky||={});class Qq extends g0{_id;_attachedToEntity;_offset;_position;_state={};_templateId;_viewDistance;_world;constructor(Z){if(!!Z.attachedToEntity===!!Z.position)u.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 u.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 u.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(){return p0.serializeSceneUI(this)}}class o7 extends i8{player;nametagSceneUI;constructor(Z){super(Z);this.player=Z.player,this.nametagSceneUI=new Qq({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 u.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 Wq{_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)u.fatalError(`EntityManager.registerEntity(): Entity ${Z.name} is already assigned the id ${Z.id}!`);let J=this._nextEntityId;return this._entities.set(J,Z),this._nextEntityId++,J}unregisterEntity(Z){if(Z.id===void 0)return u.error(`EntityManager.unregisterEntity(): Entity ${Z.name} is not assigned an id!`);this._entities.delete(Z.id)}getAllEntities(){return Array.from(this._entities.values())}getAllPlayerEntities(){let Z=[];return this._entities.forEach((J)=>{if(J instanceof o7)Z.push(J)}),Z}getPlayerEntitiesByPlayer(Z){let J=[];return this._entities.forEach((X)=>{if(X instanceof o7&&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){this._entities.forEach((J)=>{J.tick(Z)})}checkAndEmitUpdates(){this._entities.forEach((Z)=>{if(!Z.isSpawned)return;Z.checkAndEmitUpdates()})}}class Gq{_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(){return 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)}}var YK1;((X)=>{X[X.POINTLIGHT=0]="POINTLIGHT";X[X.SPOTLIGHT=1]="SPOTLIGHT"})(YK1||={});var Iy;((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"})(Iy||={});class _y extends g0{_id;_angle;_attachedToEntity;_color;_distance;_intensity;_offset;_penumbra;_position;_trackedEntity;_trackedPosition;_type;_world;constructor(Z){if(!!Z.attachedToEntity===!!Z.position)u.fatalError("Either attachedToEntity or position must be set, but not both");super();u.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 u.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===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===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 u.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 u.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(){return p0.serializeLight(this)}}var $K1;((Y)=>{Y[Y.FIRST_PERSON=0]="FIRST_PERSON";Y[Y.THIRD_PERSON=1]="THIRD_PERSON";Y[Y.SPECTATOR=2]="SPECTATOR"})($K1||={});var vy;((q)=>{q.LOOK_AT_ENTITY="PLAYER_CAMERA.LOOK_AT_ENTITY";q.LOOK_AT_POSITION="PLAYER_CAMERA.LOOK_AT_POSITION";q.SET_ATTACHED_TO_ENTITY="PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY";q.SET_ATTACHED_TO_POSITION="PLAYER_CAMERA.SET_ATTACHED_TO_POSITION";q.SET_FILM_OFFSET="PLAYER_CAMERA.SET_FILM_OFFSET";q.SET_FORWARD_OFFSET="PLAYER_CAMERA.SET_FORWARD_OFFSET";q.SET_FOV="PLAYER_CAMERA.SET_FOV";q.SET_MODEL_HIDDEN_NODES="PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES";q.SET_MODE="PLAYER_CAMERA.SET_MODE";q.SET_OFFSET="PLAYER_CAMERA.SET_OFFSET";q.SET_TRACKED_ENTITY="PLAYER_CAMERA.SET_TRACKED_ENTITY";q.SET_TRACKED_POSITION="PLAYER_CAMERA.SET_TRACKED_POSITION";q.SET_ZOOM="PLAYER_CAMERA.SET_ZOOM"})(vy||={});class Vq extends g0{player;_attachedToEntity;_attachedToPosition;_filmOffset=0;_forwardOffset=0;_fov=75;_modelHiddenNodes=new Set;_mode=1;_offset={x:0,y:0,z:0};_orientation={pitch:0,yaw: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 filmOffset(){return this._filmOffset}get forwardOffset(){return this._forwardOffset}get fov(){return this._fov}get modelHiddenNodes(){return this._modelHiddenNodes}get mode(){return this._mode}get offset(){return this._offset}get orientation(){return this._orientation}get trackedEntity(){return this._trackedEntity}get trackedPosition(){return this._trackedPosition}get zoom(){return this._zoom}lookAtEntity(Z){if(!this._requirePlayerWorld())return;this.emitWithWorld(this.player.world,"PLAYER_CAMERA.LOOK_AT_ENTITY",{playerCamera:this,entity:Z})}lookAtPosition(Z){if(!this._requirePlayerWorld())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())return;if(!Z.isSpawned)return u.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())return;this._attachedToPosition=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_ATTACHED_TO_POSITION",{playerCamera:this,position:Z})}setFilmOffset(Z){if(!this._requirePlayerWorld())return;this._filmOffset=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_FILM_OFFSET",{playerCamera:this,filmOffset:Z})}setForwardOffset(Z){if(!this._requirePlayerWorld())return;this._forwardOffset=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_FORWARD_OFFSET",{playerCamera:this,forwardOffset:Z})}setFov(Z){if(!this._requirePlayerWorld())return;this._fov=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_FOV",{playerCamera:this,fov:Z})}setModelHiddenNodes(Z){if(!this._requirePlayerWorld())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})}setMode(Z){if(!this._requirePlayerWorld())return;this._mode=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_MODE",{playerCamera:this,mode:Z})}setOffset(Z){if(!this._requirePlayerWorld())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}setTrackedEntity(Z){if(!this._requirePlayerWorld())return;this._trackedEntity=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_TRACKED_ENTITY",{playerCamera:this,entity:Z})}setTrackedPosition(Z){if(!this._requirePlayerWorld())return;this._trackedPosition=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_TRACKED_POSITION",{playerCamera:this,position:Z})}setZoom(Z){if(!this._requirePlayerWorld())return;this._zoom=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_ZOOM",{playerCamera:this,zoom:Z})}serialize(){return p0.serializePlayerCamera(this)}_requirePlayerWorld(){if(!this.player.world)u.error(`PlayerCamera._requirePlayerWorld(): Player ${this.player.id} is not in a world!`);return!!this.player.world}}var vR;(($)=>{$.DATA="PLAYER_UI.DATA";$.LOAD="PLAYER_UI.LOAD";$.LOCK_POINTER="PLAYER_UI.LOCK_POINTER";$.SEND_DATA="PLAYER_UI.SEND_DATA"})(vR||={});class Hq extends g0{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 Fq=r(bQ(),1);class zq{_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.keys())this._cleanupBlockTypeColliderHandles.add(Z);if(this._pendingCleanupBlockTypeColliderHandles.size>0)this._pendingCleanupBlockTypeColliderHandles.clear();for(let Z of this._pendingCleanupCollisionCallbackColliderHandles.keys())this._cleanupCollisionCallbackColliderHandles.add(Z);if(this._pendingCleanupCollisionCallbackColliderHandles.size>0)this._pendingCleanupCollisionCallbackColliderHandles.clear();for(let Z of this._pendingCleanupEntityColliderHandles.keys())this._cleanupEntityColliderHandles.add(Z);if(this._pendingCleanupEntityColliderHandles.size>0)this._pendingCleanupEntityColliderHandles.clear()}_requireSimulatedCollider(Z){if(!Z.rawCollider)u.error("ColliderMap._requireSimulatedCollider(): Collider is not in the simulation.");return!!Z.rawCollider}}var $J6={x:0,y:-32,z:0},Sy=60,Ay;(($)=>{$.STEP_START="SIMULATION.STEP_START";$.STEP_END="SIMULATION.STEP_END";$.DEBUG_RAYCAST="SIMULATION.DEBUG_RAYCAST";$.DEBUG_RENDER="SIMULATION.DEBUG_RENDER"})(Ay||={});class qq extends g0{_colliderMap=new zq;_debugRaycastingEnabled=!1;_debugRenderingEnabled=!1;_debugRenderingFilterFlags;_rapierEventQueue;_rapierSimulation;_world;constructor(Z,J=Sy,X=$J6){super();this._rapierEventQueue=new Fq.default.EventQueue(!0),this._rapierSimulation=new Fq.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}raycast(Z,J,X,Y={}){let $=new Fq.default.Ray(Z,J),Q=this._rapierSimulation.castRay($,X,Y.ignoresSensors??!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),W=Q.timeOfImpact,G=Q.collider,V=this._colliderMap.getColliderHandleBlockType(G.handle);if(V)return{hitBlock:TQ.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))},V),hitPoint:K,hitDistance:W};let H=this._colliderMap.getColliderHandleEntity(G.handle);if(H)return{hitEntity:H,hitPoint:K,hitDistance:W};return null}createRawCollider(Z,J){return this._rapierSimulation.createCollider(Z,J)}createRawRigidBody(Z){return this._rapierSimulation.createRigidBody(Z)}enableDebugRaycasting(Z){this._debugRaycastingEnabled=Z}enableDebugRendering(Z,J=Fq.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 W=0;W<Y.numSolverContacts();W++)K.push(Y.solverContactPoint(W));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}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(X8.startSpan({operation:"physics_step"},()=>{this._rapierSimulation.step(this._rapierEventQueue)}),X8.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,W)=>{if(K instanceof t5&&W instanceof i8&&K.hasListeners("BLOCK_TYPE.ENTITY_COLLISION"))K.emit("BLOCK_TYPE.ENTITY_COLLISION",{blockType:K,entity:W,started:X,colliderHandleA:Z,colliderHandleB:J});else if(K instanceof i8&&W instanceof t5&&K.hasListeners("ENTITY.BLOCK_COLLISION"))K.emit("ENTITY.BLOCK_COLLISION",{entity:K,blockType:W,started:X,colliderHandleA:Z,colliderHandleB:J});else if(K instanceof i8&&W instanceof i8&&K.hasListeners("ENTITY.ENTITY_COLLISION"))K.emit("ENTITY.ENTITY_COLLISION",{entity:K,otherEntity:W,started:X,colliderHandleA:Z,colliderHandleB:J});else if(typeof K==="function"&&(W instanceof i8||W instanceof t5))K(W,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 t5&&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 t5&&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 SR{_synchronizedPlayerReliablePackets=new Map;_queuedBroadcasts=[];_queuedAudioSynchronizations={};_queuedBlockSynchronizations={};_queuedBlockTypeSynchronizations={};_queuedChunkSynchronizations={};_queuedDebugRaycastSynchronizations=[];_queuedEntitySynchronizations={};_queuedLightSynchronizations={};_queuedPerPlayerSynchronizations=new Map;_queuedPerPlayerCameraSynchronizations=new Map;_queuedPerPlayerUISynchronizations=new Map;_queuedPerPlayerUIDatasSynchronizations=new Map;_queuedPlayerSynchronizations={};_queuedSceneUISynchronizations={};_queuedWorldSynchronization;_loadedSceneUIs=new Set;_spawnedChunks=new Set;_spawnedEntities=new Set;_world;constructor(Z){this._world=Z,this._subscribeToAudioEvents(),this._subscribeToBlockTypeRegistryEvents(),this._subscribeToChatEvents(),this._subscribeToChunkEvents(),this._subscribeToEntityEvents(),this._subscribeToLightEvents(),this._subscribeToPlayerEvents(),this._subscribeToPlayerCameraEvents(),this._subscribeToPlayerUIEvents(),this._subscribeToSceneUIEvents(),this._subscribeToSimulationEvents(),this._subscribeToWorldEvents()}synchronize(){let Z=[],J=[],X=this._world.loop.currentTick;this._queuedPerPlayerSynchronizations.forEach((z,q)=>{this._createOrGetSynchronizedPlayerReliablePackets(q,Z).push(...z)});let Y=Object.values(this._queuedEntitySynchronizations);if(Y.length>0){let[z,q]=Y.reduce(([U,B],L)=>{for(let w in L)if(w!=="i"&&w!=="p"&&w!=="r")return U.push(L),[U,B];return B.push(L),[U,B]},[[],[]]);if(q.length>0){let U=X0.createPacket(X0.outboundPackets.entitiesPacketDefinition,q,X);J.push(U)}if(z.length>0){let U=X0.createPacket(X0.outboundPackets.entitiesPacketDefinition,z,X);Z.push(U),this._synchronizedPlayerReliablePackets.forEach((B)=>B.push(U))}}let $=Object.values(this._queuedAudioSynchronizations);if($.length>0){let z=X0.createPacket(X0.outboundPackets.audiosPacketDefinition,$,X);Z.push(z),this._synchronizedPlayerReliablePackets.forEach((q)=>q.push(z))}let Q=Object.values(this._queuedBlockTypeSynchronizations);if(Q.length>0){let z=X0.createPacket(X0.outboundPackets.blockTypesPacketDefinition,Q,X);Z.push(z),this._synchronizedPlayerReliablePackets.forEach((q)=>q.push(z))}let K=Object.values(this._queuedBlockSynchronizations);if(K.length>0){let z=X0.createPacket(X0.outboundPackets.blocksPacketDefinition,K,X);Z.push(z),this._synchronizedPlayerReliablePackets.forEach((q)=>q.push(z))}let W=Object.values(this._queuedChunkSynchronizations);if(W.length>0){let z=X0.createPacket(X0.outboundPackets.chunksPacketDefinition,W,X);Z.push(z),this._synchronizedPlayerReliablePackets.forEach((q)=>q.push(z))}let G=Object.values(this._queuedLightSynchronizations);if(G.length>0){let z=X0.createPacket(X0.outboundPackets.lightsPacketDefinition,G,X);Z.push(z),this._synchronizedPlayerReliablePackets.forEach((q)=>q.push(z))}this._queuedPerPlayerUISynchronizations.forEach((z,q)=>{let U=X0.createPacket(X0.outboundPackets.uiPacketDefinition,z,X);this._createOrGetSynchronizedPlayerReliablePackets(q,Z).push(U)}),this._queuedPerPlayerUIDatasSynchronizations.forEach((z,q)=>{let U=X0.createPacket(X0.outboundPackets.uiDatasPacketDefinition,z,X);this._createOrGetSynchronizedPlayerReliablePackets(q,Z).push(U)});let V=Object.values(this._queuedSceneUISynchronizations);if(V.length>0){let z=X0.createPacket(X0.outboundPackets.sceneUIsPacketDefinition,V,X);Z.push(z),this._synchronizedPlayerReliablePackets.forEach((q)=>q.push(z))}if(this._queuedWorldSynchronization){let z=X0.createPacket(X0.outboundPackets.worldPacketDefinition,this._queuedWorldSynchronization,X);Z.push(z),this._synchronizedPlayerReliablePackets.forEach((q)=>q.push(z))}this._queuedPerPlayerCameraSynchronizations.forEach((z,q)=>{let U=X0.createPacket(X0.outboundPackets.cameraPacketDefinition,z,X);this._createOrGetSynchronizedPlayerReliablePackets(q,Z).push(U)});let H=Object.values(this._queuedPlayerSynchronizations);if(H.length>0){let z=X0.createPacket(X0.outboundPackets.playersPacketDefinition,H,X);Z.push(z),this._synchronizedPlayerReliablePackets.forEach((q)=>q.push(z))}this._queuedBroadcasts.forEach((z)=>{Z.push(z),this._synchronizedPlayerReliablePackets.forEach((q)=>q.push(z))});let F=this._queuedDebugRaycastSynchronizations;if(F.length>0){let z=X0.createPacket(X0.outboundPackets.physicsDebugRaycastsPacketDefinition,F,X);Z.push(z),this._synchronizedPlayerReliablePackets.forEach((q)=>q.push(z))}X8.startSpan({operation:"send_all_packets"},()=>{Y9.instance.getConnectedPlayersByWorld(this._world).forEach((z)=>{let q=this._synchronizedPlayerReliablePackets.get(z)??Z;if(q.length>0)z.connection.send(q);if(J.length>0)z.connection.send(J,!1)})}),X8.startSpan({operation:"network_synchronize_cleanup"},()=>{if(this._queuedBroadcasts.length>0)this._queuedBroadcasts=[];if($.length>0)this._queuedAudioSynchronizations={};if(K.length>0)this._queuedBlockSynchronizations={};if(Q.length>0)this._queuedBlockTypeSynchronizations={};if(W.length>0)this._queuedChunkSynchronizations={};if(F.length>0)this._queuedDebugRaycastSynchronizations=[];if(Y.length>0)this._queuedEntitySynchronizations={};if(G.length>0)this._queuedLightSynchronizations={};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(H.length>0)this._queuedPlayerSynchronizations={};if(V.length>0)this._queuedSceneUISynchronizations={};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()})}_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)}_subscribeToChunkEvents(){this._world.final("CHUNK.SPAWN",this._onChunkSpawn),this._world.final("CHUNK.DESPAWN",this._onChunkDespawn),this._world.final("CHUNK.SET_BLOCK",this._onChunkSetBlock)}_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_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)}_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_MODE",this._onPlayerCameraSetMode),this._world.final("PLAYER_CAMERA.SET_OFFSET",this._onPlayerCameraSetOffset),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_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[J.i]=J};_onAudioPlayRestart=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.r=!0,delete J.pa,delete J.pl,this._queuedAudioSynchronizations[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):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[Z.blockType.id]=J};_onChatSendBroadcastMessage=(Z)=>{let{player:J,message:X,color:Y}=Z;this._queuedBroadcasts.push(X0.createPacket(X0.outboundPackets.chatMessagesPacketDefinition,[{m:X,c:Y,p:J?.id}],this._world.loop.currentTick))};_onChatSendPlayerMessage=(Z)=>{let{player:J,message:X,color:Y}=Z,$=this._queuedPerPlayerSynchronizations.get(J)??[];$.push(X0.createPacket(X0.outboundPackets.chatMessagesPacketDefinition,[{m:X,c:Y}],this._world.loop.currentTick)),this._queuedPerPlayerSynchronizations.set(J,$)};_onChunkSpawn=(Z)=>{let J=this._createOrGetQueuedChunkSync(Z.chunk);J.b=Array.from(Z.chunk.blocks),J.rm=void 0,this._spawnedChunks.add(J.c.join(","))};_onChunkDespawn=(Z)=>{let J=this._createOrGetQueuedChunkSync(Z.chunk),X=J.c.join(",");if(this._spawnedChunks.has(X))delete this._queuedChunkSynchronizations[X],this._spawnedChunks.delete(X);else J.rm=!0};_onChunkSetBlock=(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[J.i]=J,this._spawnedEntities.add(J.i)};_onEntityDespawn=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(this._spawnedEntities.has(J.i))delete this._queuedEntitySynchronizations[J.i],this._spawnedEntities.delete(J.i);else J.rm=!0};_onEntitySetModelHiddenNodes=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.h=Array.from(Z.modelHiddenNodes)};_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):void 0};_onEntityStartModelLoopedAnimations=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(J.al=Array.from(new Set([...J.al??[],...Z.animations])),J.as)J.as=J.as.filter((X)=>!Z.animations.has(X)).filter(Boolean)};_onEntityStartModelOneshotAnimations=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(J.ao=Array.from(new Set([...J.ao??[],...Z.animations])),J.as)J.as=J.as.filter((X)=>!Z.animations.has(X)).filter(Boolean)};_onEntityStopModelAnimations=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(J.al)J.al=J.al.filter((X)=>!Z.animations.has(X)).filter(Boolean);if(J.ao)J.ao=J.ao.filter((X)=>!Z.animations.has(X)).filter(Boolean);J.as=Array.from(new Set([...J.as??[],...Z.animations]))};_onEntityUpdateRotation=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.r=[Z.rotation.x,Z.rotation.y,Z.rotation.z,Z.rotation.w]};_onEntityUpdatePosition=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.p=[Z.position.x,Z.position.y,Z.position.z]};_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)};_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):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):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):void 0,J.te=Z.position?void 0:J.te};_onLightSpawn=(Z)=>{let J=Z.light.serialize();this._queuedLightSynchronizations[J.i]=J};_onPlayerCameraLookAtEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pl=p0.serializeVector(Z.entity.position),delete J.et,delete J.pt};_onPlayerCameraLookAtPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pl=Z.position?p0.serializeVector(Z.position):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):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=Array.from(Z.modelHiddenNodes)};_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):void 0};_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):void 0,delete J.et,delete J.pl};_onPlayerCameraSetZoom=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.z=Z.zoom};_onPlayerJoinedWorld=(Z)=>{let{player:J}=Z,X=this._queuedPerPlayerSynchronizations.get(J)??[];X.push(X0.createPacket(X0.outboundPackets.worldPacketDefinition,this._world.serialize(),this._world.loop.currentTick)),X.push(X0.createPacket(X0.outboundPackets.blockTypesPacketDefinition,this._world.blockTypeRegistry.serialize(),this._world.loop.currentTick)),X.push(X0.createPacket(X0.outboundPackets.chunksPacketDefinition,this._world.chunkLattice.getAllChunks().map(($)=>$.serialize()),this._world.loop.currentTick)),X.push(X0.createPacket(X0.outboundPackets.entitiesPacketDefinition,this._world.entityManager.getAllEntities().map(($)=>{if(J.camera.attachedToEntity===void 0&&$ instanceof o7&&$.player===J)J.camera.setAttachedToEntity($);return $.serialize()}),this._world.loop.currentTick)),X.push(X0.createPacket(X0.outboundPackets.audiosPacketDefinition,this._world.audioManager.getAllAudios().map(($)=>$.serialize()),this._world.loop.currentTick)),X.push(X0.createPacket(X0.outboundPackets.lightsPacketDefinition,this._world.lightManager.getAllLights().map(($)=>$.serialize()),this._world.loop.currentTick)),X.push(X0.createPacket(X0.outboundPackets.sceneUIsPacketDefinition,this._world.sceneUIManager.getAllSceneUIs().map(($)=>$.serialize()),this._world.loop.currentTick)),X.push(X0.createPacket(X0.outboundPackets.playersPacketDefinition,Y9.instance.getConnectedPlayers().map(($)=>$.serialize()),this._world.loop.currentTick));let Y=this._createOrGetQueuedPlayerCameraSync(J.camera);this._queuedPerPlayerCameraSynchronizations.set(J,{...J.camera.serialize(),...Y}),this._queuedPerPlayerSynchronizations.set(J,X),this._queuedPlayerSynchronizations[J.id]=J.serialize()};_onPlayerLeftWorld=(Z)=>{let J=this._createOrGetQueuedPlayerSync(Z.player);J.rm=!0};_onPlayerReconnectedWorld=(Z)=>{this._onPlayerJoinedWorld(Z)};_onPlayerRequestSync=(Z)=>{Z.player.connection.send([X0.createPacket(X0.outboundPackets.syncResponsePacketDefinition,{r:Z.receivedAt,s:Date.now(),p:performance.now()-Z.receivedAtMs,n:this._world.loop.nextTickMs},this._world.loop.currentTick)])};_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[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):void 0};_onSceneUISetPosition=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.p=Z.position?p0.serializeVector(Z.position):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))delete this._queuedSceneUISynchronizations[J.i],this._loadedSceneUIs.delete(J.i);else J.rm=!0};_onSimulationDebugRaycast=(Z)=>{this._queuedDebugRaycastSynchronizations.push(p0.serializePhysicsDebugRaycast(Z))};_onSimulationDebugRender=(Z)=>{this._queuedBroadcasts.push(X0.createPacket(X0.outboundPackets.physicsDebugRenderPacketDefinition,{v:Array.from(Z.vertices),c:Array.from(Z.colors)},this._world.loop.currentTick))};_onWorldSetAmbientLightColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.ac=p0.serializeRgbColor(Z.color)};_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)};_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)};_onWorldSetSkyboxIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.si=Z.intensity};_createOrGetQueuedAudioSync(Z){if(Z.id===void 0)u.fatalError("NetworkSynchronizer._createOrGetQueuedAudioSync(): Audio has no id!");return this._queuedAudioSynchronizations[Z.id]??={i:Z.id}}_createOrGetQueuedBlockSync(Z){let{x:J,y:X,z:Y}=Z;return this._queuedBlockSynchronizations[`${J},${X},${Y}`]??={i:0,c:[J,X,Y]}}_createOrGetQueuedChunkSync(Z){if(!Z.originCoordinate)u.fatalError("NetworkSynchronizer._createOrGetQueuedChunkSync(): Chunk has no origin coordinate!");let{x:J,y:X,z:Y}=Z.originCoordinate;return this._queuedChunkSynchronizations[`${J},${X},${Y}`]??={c:[J,X,Y]}}_createOrGetQueuedEntitySync(Z){if(Z.id===void 0)u.fatalError("NetworkSynchronizer._createOrGetQueuedEntitySync(): Entity has no id!");return this._queuedEntitySynchronizations[Z.id]??={i:Z.id}}_createOrGetQueuedLightSync(Z){if(Z.id===void 0)u.fatalError("NetworkSynchronizer._createOrGetQueuedLightSync(): Light has no id!");return this._queuedLightSynchronizations[Z.id]??={i:Z.id}}_createOrGetQueuedPlayerSync(Z){if(Z.id===void 0)u.fatalError("NetworkSynchronizer._createOrGetQueuedPlayerSync(): Player has no id!");return this._queuedPlayerSynchronizations[Z.id]??={i:Z.id}}_createOrGetQueuedPlayerCameraSync(Z){let J=this._queuedPerPlayerCameraSynchronizations.get(Z.player);if(!J)J={},this._queuedPerPlayerCameraSynchronizations.set(Z.player,J);return J}_createOrGetQueuedPlayerUISync(Z){let J=this._queuedPerPlayerUISynchronizations.get(Z.player);if(!J)J={},this._queuedPerPlayerUISynchronizations.set(Z.player,J);return J}_createOrGetQueuedPlayerUIDatasSync(Z){let J=this._queuedPerPlayerUIDatasSynchronizations.get(Z.player);if(!J)J=[],this._queuedPerPlayerUIDatasSynchronizations.set(Z.player,J);return J}_createOrGetQueuedSceneUISync(Z){if(Z.id===void 0)u.fatalError("NetworkSynchronizer._createOrGetQueuedSceneUISync(): SceneUI has no id!");return this._queuedSceneUISynchronizations[Z.id]??={i:Z.id}}_createOrGetQueuedWorldSync(Z){if(Z.id!==this._world.id)u.fatalError("NetworkSynchronizer._createOrGetQueuedWorldSync(): World does not match this network synchronizer world!");return this._queuedWorldSynchronization??={i:Z.id}}_createOrGetSynchronizedPlayerReliablePackets(Z,J){let X=this._synchronizedPlayerReliablePackets.get(Z);if(!X)X=[...J],this._synchronizedPlayerReliablePackets.set(Z,X);return X}}class Uq{_sceneUIs=new Map;_nextSceneUIId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}getAllSceneUIs(){return 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)}}var QJ6=2,KJ6=3;class Lq{_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*KJ6,this._tickFunction=J,this._tickErrorCallback=X}get targetTicksPerSecond(){return this._targetTicksPerSecond}get fixedTimestepMs(){return this._fixedTimestepMs}get fixedTimestepS(){return this._fixedTimestepS}get nextTickMs(){return this._nextTickMs}start(){if(this._tickHandle)return u.warning("Ticker.start(): ticker already running.");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)X8.startSpan({operation:"ticker_tick"},()=>{let Y=0;while(this._accumulatorMs>=this._fixedTimestepMs&&Y<QJ6)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 u.warning("Ticker.stop(): ticker not running.");clearTimeout(this._tickHandle),this._tickHandle=null}_tick(Z){try{this._tickFunction(Z)}catch(J){if(J instanceof Error&&this._tickErrorCallback)this._tickErrorCallback(J);else u.warning(`Ticker._tick(): tick callback threw an error, but it was not an instance of Error. Error: ${J}`)}}}var QK1;((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"})(QK1||={});class Bq extends g0{_currentTick=0;_ticker;_world;constructor(Z,J=Sy){super();this._ticker=new Lq(J,this._tick,this._onTickError),this._world=Z}get currentTick(){return this._currentTick}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();X8.startSpan({operation:"world_tick",attributes:{serverPlayerCount:Y9.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}},()=>{X8.startSpan({operation:"chunks_update"},()=>this._world.chunkLattice.updateChunks()),X8.startSpan({operation:"entities_tick"},()=>this._world.entityManager.tickEntities(Z)),X8.startSpan({operation:"simulation_step"},()=>this._world.simulation.step(Z)),X8.startSpan({operation:"entities_emit_updates"},()=>this._world.entityManager.checkAndEmitUpdates()),X8.startSpan({operation:"network_synchronize"},()=>this._world.networkSynchronizer.synchronize())}),this._currentTick++,this.emitWithWorld(this._world,"WORLD_LOOP.TICK_END",{worldLoop:this,tickDurationMs:performance.now()-J})};_onTickError=(Z)=>{u.error(`WorldLoop._onTickError(): Error: ${Z}`),this.emitWithWorld(this._world,"WORLD_LOOP.TICK_ERROR",{worldLoop:this,error:Z})}}var xy;((G)=>{G.SET_AMBIENT_LIGHT_COLOR="WORLD.SET_AMBIENT_LIGHT_COLOR";G.SET_AMBIENT_LIGHT_INTENSITY="WORLD.SET_AMBIENT_LIGHT_INTENSITY";G.SET_DIRECTIONAL_LIGHT_COLOR="WORLD.SET_DIRECTIONAL_LIGHT_COLOR";G.SET_DIRECTIONAL_LIGHT_INTENSITY="WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY";G.SET_DIRECTIONAL_LIGHT_POSITION="WORLD.SET_DIRECTIONAL_LIGHT_POSITION";G.SET_SKYBOX_INTENSITY="WORLD.SET_SKYBOX_INTENSITY";G.START="WORLD.START";G.STOP="WORLD.STOP"})(xy||={});class wq extends g0{_id;_ambientLightColor;_ambientLightIntensity;_directionalLightColor;_directionalLightIntensity;_directionalLightPosition;_name;_skyboxIntensity;_skyboxUri;_audioManager;_blockTypeRegistry;_chatManager;_chunkLattice;_entityManager;_lightManager;_loop;_networkSynchronizer;_sceneUIManager;_simulation;_tag;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._name=Z.name,this._skyboxIntensity=Z.skyboxIntensity??1,this._skyboxUri=Z.skyboxUri,this._tag=Z.tag,this._audioManager=new uG(this),this._blockTypeRegistry=new xV(this),this._chatManager=new Oq(this),this._chunkLattice=new Yq(this),this._entityManager=new Wq(this),this._lightManager=new Gq(this),this._loop=new Bq(this,Z.tickRate),this._networkSynchronizer=new SR(this),this._sceneUIManager=new Uq(this),this._simulation=new qq(this,Z.tickRate,Z.gravity),Z.map)this.loadMap(Z.map)}get id(){return this._id}get ambientLightColor(){return this._ambientLightColor}get ambientLightIntensity(){return this._ambientLightIntensity}get directionalLightColor(){return this._directionalLightColor}get directionalLightIntensity(){return this._directionalLightIntensity}get directionalLightPosition(){return this._directionalLightPosition}get name(){return this._name}get skyboxIntensity(){return this._skyboxIntensity}get skyboxUri(){return this._skyboxUri}get audioManager(){return this._audioManager}get tag(){return this._tag}get blockTypeRegistry(){return this._blockTypeRegistry}get chatManager(){return this._chatManager}get chunkLattice(){return this._chunkLattice}get entityManager(){return this._entityManager}get lightManager(){return this._lightManager}get loop(){return this._loop}get networkSynchronizer(){return this._networkSynchronizer}get sceneUIManager(){return this._sceneUIManager}get simulation(){return this._simulation}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(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})}setSkyboxIntensity(Z){this._skyboxIntensity=Z,this.emit("WORLD.SET_SKYBOX_INTENSITY",{world:this,intensity:Z})}start(){this._loop.start(),this.emit("WORLD.START",{world:this,startedAtMs:Date.now()})}stop(){this._loop.stop(),this.emit("WORLD.STOP",{world:this,stoppedAtMs:Date.now()})}serialize(){return p0.serializeWorld(this)}}var KK1;((J)=>J.WORLD_CREATED="WORLD_MANAGER.WORLD_CREATED")(KK1||={});class fG{static instance=new fG;_defaultWorld;_nextWorldId=1;_worlds=new Map;createWorld(Z){let J=new wq({...Z,id:this._nextWorldId++});return J.start(),this._worlds.set(J.id,J),F6.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}}Buffer.poolSize=67108864;var GK1;((X)=>{X.START="GAMESERVER.START";X.STOP="GAMESERVER.STOP"})(GK1||={});function WJ6(Z){WK1.default.init().then(()=>{return GJ.instance.modelRegistry.preloadModels()}).then(()=>{if(Z.length>0)Z(GJ.instance.worldManager.getDefaultWorld());else Z();GJ.instance.start()}).catch((J)=>{u.fatalError(`Failed to initialize the game engine, exiting. Error: ${J}`)})}class GJ{static _instance;_modelRegistry=_9.instance;_playerManager=Y9.instance;_socket=QX.instance;_worldManager=fG.instance;_webServer=TW.instance;constructor(){}static get instance(){if(!this._instance)this._instance=new GJ;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(){F6.emit("GAMESERVER.START",{startedAtMs:performance.now()}),this._webServer.start()}}class jQ{static instance=new jQ;constructor(){}async getGlobalData(Z){let J=await I7.instance.getData(Z);if(!J||J.error){if(J?.error)u.warning(`PersistenceManager.getGlobalData(): ${J.error.message}`);return}return J}async getPlayerData(Z){let J=await I7.instance.getData(this._getPlayerKey(Z));if(!J||J.error){if(J?.error)u.warning(`PersistenceManager.getPlayerData(): ${J.error.message}`);return}return J}async setGlobalData(Z,J){let X=await I7.instance.setData(Z,J);if(!X||X.error){if(X?.error)u.warning(`PersistenceManager.setGlobalData(): ${X.error.message}`);return}return X}async setPlayerData(Z,J){let X=await I7.instance.setData(this._getPlayerKey(Z),J);if(!X||X.error){if(X?.error)u.warning(`PersistenceManager.setPlayerData(): ${X.error.message}`);return}return X}_getPlayerKey(Z){return`player-${Z.id}`}}var VK1=["w","a","s","d","sp","sh","tb","ml","mr","q","e","r","f","z","x","c","v","1","2","3","4","5","6","7","8","9","0"],Kq;((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"})(Kq||={});class xG extends g0{static _devNextPlayerId=1;id;username;profilePictureUrl;camera;connection;ui;_input={};_lastUnreliableInputSequenceNumber=0;_world;constructor(Z,J){super();this.id=J?.user.id??`player-${xG._devNextPlayerId++}`,this.username=J?.user.username??this.id,this.profilePictureUrl=J?.user.profilePictureURL??void 0,this.camera=new Vq(this),this.connection=Z,this.ui=new Hq(this),Z.onPacket(X0.PacketId.CHAT_MESSAGE_SEND,this._onChatMessageSendPacket),Z.onPacket(X0.PacketId.DEBUG_CONFIG,this._onDebugConfigPacket),Z.onPacket(X0.PacketId.INPUT,this._onInputPacket),Z.onPacket(X0.PacketId.SYNC_REQUEST,this._onSyncRequestPacket),Z.onPacket(X0.PacketId.UI_DATA_SEND,this._onUIDataSendPacket),this.joinWorld(GJ.instance.worldManager.getDefaultWorld())}get input(){return this._input}get world(){return this._world}disconnect(){this._leaveWorld(),this.connection.disconnect()}async getPersistedData(){return jQ.instance.getPlayerData(this)}joinWorld(Z){if(this._world)this.disconnect();this._world=Z,this.emitWithWorld(this._world,"PLAYER.JOINED_WORLD",{player:this,world:this._world})}reconnect(){if(!this._world)return;this._lastUnreliableInputSequenceNumber=0,this.emitWithWorld(this._world,"PLAYER.RECONNECTED_WORLD",{player:this,world:this._world})}resetInputs(){this._input={}}async setPersistedData(Z){return jQ.instance.setPlayerData(this,Z)}serialize(){return p0.serializePlayer(this)}_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(VK1.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 hy;((X)=>{X.BROADCAST_MESSAGE="CHAT.BROADCAST_MESSAGE";X.PLAYER_MESSAGE="CHAT.PLAYER_MESSAGE"})(hy||={});class Oq extends g0{_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})}}class y1 extends eX{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.335;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;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;_externalImpulse={x:0,y:0,z: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.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)=>{this._externalImpulse.x+=J.x,this._externalImpulse.y+=J.y,this._externalImpulse.z+=J.z},this._stepAudio=new mG({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 u.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]},isSensor:!0,relativePosition:{x:0,y:-Z.height/2,z:0},tag:"groundSensor",onCollision:(J,X)=>{if(!Z.isSpawned)return;if(!(J instanceof t5)||!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]},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:W,c:G,sp:V,sh:H,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||W);let U=H,B=Q&&W&&!$&&!K||$&&K&&!Q&&!W;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){let D=U?this.runLoopedAnimations:this.walkLoopedAnimations;Z.stopAllModelLoopedAnimations(D),Z.startModelLoopedAnimations(D),this._stepAudio?.setPlaybackRate(U?0.75:0.51),this._stepAudio?.play(Z.world,!this._stepAudio?.isPlaying)}else if(this._isFullySubmerged){this._stepAudio?.pause();let D=this._isActivelyMoving?this.swimLoopedAnimations:this.swimIdleLoopedAnimations;Z.stopAllModelLoopedAnimations(D),Z.startModelLoopedAnimations(D)}else this._stepAudio?.pause(),Z.stopAllModelLoopedAnimations(this.idleLoopedAnimations),Z.startModelLoopedAnimations(this.idleLoopedAnimations);let L;if(this.applyDirectionalMovementRotations){if($&&Q&&!W&&!K)L=y1.MOVEMENT_ROTATIONS.wa;else if($&&W&&!Q&&!K)L=y1.MOVEMENT_ROTATIONS.wd;else if(K&&Q&&!$&&!W)L=y1.MOVEMENT_ROTATIONS.sa;else if(K&&W&&!$&&!Q)L=y1.MOVEMENT_ROTATIONS.sd;else if(K&&!$&&!Q&&!W||Q&&K&&W&&!$)L=y1.MOVEMENT_ROTATIONS.s;else if(Q&&!$&&!K&&!W)L=y1.MOVEMENT_ROTATIONS.a;else if(W&&!$&&!Q&&!K)L=y1.MOVEMENT_ROTATIONS.d}if(F)Z.startModelOneshotAnimations(this.interactOneshotAnimations),J.ml=!this.autoCancelMouseLeftClick;if(U&&this.canRun(this)||!U&&this.canWalk(this)){let D=!this.isSwimming?U?this.runVelocity:this.walkVelocity:U?this.swimFastVelocity:this.swimSlowVelocity,P=Math.sin(z),C=Math.cos(z);if($)this._reusableTargetVelocities.x-=D*P,this._reusableTargetVelocities.z-=D*C;if(K)this._reusableTargetVelocities.x+=D*P,this._reusableTargetVelocities.z+=D*C;if(Q)this._reusableTargetVelocities.x-=D*C,this._reusableTargetVelocities.z+=D*P;if(W)this._reusableTargetVelocities.x+=D*C,this._reusableTargetVelocities.z-=D*P;let T=Math.sqrt(this._reusableTargetVelocities.x*this._reusableTargetVelocities.x+this._reusableTargetVelocities.z*this._reusableTargetVelocities.z);if(T>D){let E=D/T;this._reusableTargetVelocities.x*=E,this._reusableTargetVelocities.z*=E}}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(G)this._reusableTargetVelocities.y=-this.swimUpwardVelocity;else if(performance.now()<this._justSubmergedUntil)this._reusableTargetVelocities.y=-this.swimUpwardVelocity*y1.WATER_ENTRY_SINKING_FACTOR;else if(!V)this._reusableTargetVelocities.y=-q.y*y1.SWIMMING_DRAG_FACTOR}if(V&&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 w=this._platform?.linearVelocity??this._reusablePlatformVelocity;this._externalImpulse.x=this._applyTargetDecay(this._externalImpulse.x),this._externalImpulse.y=this._applyTargetDecay(this._externalImpulse.y),this._externalImpulse.z=this._applyTargetDecay(this._externalImpulse.z);let j=this._reusableTargetVelocities.x+this._externalImpulse.x-q.x+w.x,N=this._reusableTargetVelocities.y+this._externalImpulse.y+w.y,R=this._reusableTargetVelocities.z+this._externalImpulse.z-q.z+w.z;if(j!==0||N!==0||R!==0){let D=Z.mass;this._reusableImpulse.x=j*D,this._reusableImpulse.y=N*D,this._reusableImpulse.z=R*D,this._internalApplyImpulse(this._reusableImpulse)}if(z!==void 0){let P=(L!==void 0?z+L:z)/2;Z.setRotation({x:0,y:Math.fround(Math.sin(P)),z:0,w:Math.fround(Math.cos(P))})}}_applyTargetDecay(Z){if(Math.abs(Z)<=0.01)return 0;return Z-Math.min(Math.abs(Z),y1.EXTERNAL_IMPULSE_DECAY_RATE)*Math.sign(Z)}}class fy extends o7{constructor(Z){super({modelUri:"models/players/player.gltf",modelLoopedAnimations:["idle_lower","idle_upper"],...Z});if(!Z.controller)this.setController(new y1)}}var H6=r(MQ(),1);class PQ extends Float32Array{constructor(Z,J,X,Y){super([Z,J,X,Y])}get determinant(){return H6.mat2.determinant(this)}get frobeniusNorm(){return H6.mat2.frob(this)}static create(){let Z=new PQ(0,0,0,0);return H6.mat2.identity(Z),Z}static fromRotation(Z){let J=PQ.create();return H6.mat2.fromRotation(J,Z),J}static fromScaling(Z){let J=PQ.create();return H6.mat2.fromScaling(J,Z),J}add(Z){return H6.mat2.add(this,this,Z),this}adjoint(){return H6.mat2.adjoint(this,this),this}clone(){return new PQ(this[0],this[1],this[2],this[3])}copy(Z){return H6.mat2.copy(this,Z),this}equals(Z){return H6.mat2.equals(this,Z)}exactEquals(Z){return H6.mat2.exactEquals(this,Z)}identity(){return H6.mat2.identity(this),this}invert(){return H6.mat2.invert(this,this),this}multiply(Z){return H6.mat2.mul(this,this,Z),this}multiplyScalar(Z){return H6.mat2.multiplyScalar(this,this,Z),this}rotate(Z){return H6.mat2.rotate(this,this,Z),this}subtract(Z){return H6.mat2.sub(this,this,Z),this}toString(){return`[${this[0]},${this[1]}][${this[2]},${this[3]}]`}transpose(){return H6.mat2.transpose(this,this),this}}var U8=r(MQ(),1);class e7 extends Float32Array{constructor(Z,J,X,Y,$,Q,K,W,G){super([Z,J,X,Y,$,Q,K,W,G])}get determinant(){return U8.mat3.determinant(this)}get frobeniusNorm(){return U8.mat3.frob(this)}static create(){let Z=new e7(0,0,0,0,0,0,0,0,0);return U8.mat3.identity(Z),Z}static fromMatrix4(Z){let J=e7.create();return U8.mat3.fromMat4(J,Z),J}static fromQuaternion(Z){let J=e7.create();return U8.mat3.fromQuat(J,Z),J}static fromRotation(Z){let J=e7.create();return U8.mat3.fromRotation(J,Z),J}static fromScaling(Z){let J=e7.create();return U8.mat3.fromScaling(J,Z),J}static fromTranslation(Z){let J=e7.create();return U8.mat3.fromTranslation(J,Z),J}add(Z){return U8.mat3.add(this,this,Z),this}adjoint(){return U8.mat3.adjoint(this,this),this}clone(){return new e7(this[0],this[1],this[2],this[3],this[4],this[5],this[6],this[7],this[8])}copy(Z){return U8.mat3.copy(this,Z),this}equals(Z){return U8.mat3.equals(this,Z)}exactEquals(Z){return U8.mat3.exactEquals(this,Z)}identity(){return U8.mat3.identity(this),this}invert(){return U8.mat3.invert(this,this),this}multiply(Z){return U8.mat3.mul(this,this,Z),this}multiplyScalar(Z){return U8.mat3.multiplyScalar(this,this,Z),this}transformVector(Z){return Z.transformMatrix3(this)}projection(Z,J){return U8.mat3.projection(this,Z,J),this}rotate(Z){return U8.mat3.rotate(this,this,Z),this}subtract(Z){return U8.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 U8.mat3.transpose(this,this),this}}var e0=r(MQ(),1);class O5 extends Float32Array{constructor(Z,J,X,Y,$,Q,K,W,G,V,H,F,z,q,U,B){super([Z,J,X,Y,$,Q,K,W,G,V,H,F,z,q,U,B])}get determinant(){return e0.mat4.determinant(this)}get frobeniusNorm(){return e0.mat4.frob(this)}static create(){let Z=new O5(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return e0.mat4.identity(Z),Z}static fromQuaternion(Z){let J=O5.create();return e0.mat4.fromQuat(J,Z),J}static fromRotation(Z,J){let X=O5.create();return e0.mat4.fromRotation(X,Z,J),X}static fromRotationTranslation(Z,J){let X=O5.create();return e0.mat4.fromRotationTranslation(X,Z,J),X}static fromRotationTranslationScale(Z,J,X){let Y=O5.create();return e0.mat4.fromRotationTranslationScale(Y,Z,J,X),Y}static fromRotationTranslationScaleOrigin(Z,J,X,Y){let $=O5.create();return e0.mat4.fromRotationTranslationScaleOrigin($,Z,J,X,Y),$}static fromScaling(Z){let J=O5.create();return e0.mat4.fromScaling(J,Z),J}static fromTranslation(Z){let J=O5.create();return e0.mat4.fromTranslation(J,Z),J}static fromXRotation(Z){let J=O5.create();return e0.mat4.fromXRotation(J,Z),J}static fromYRotation(Z){let J=O5.create();return e0.mat4.fromYRotation(J,Z),J}static fromZRotation(Z){let J=O5.create();return e0.mat4.fromZRotation(J,Z),J}add(Z){return e0.mat4.add(this,this,Z),this}adjoint(){return e0.mat4.adjoint(this,this),this}clone(){return new O5(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 e0.mat4.copy(this,Z),this}equals(Z){return e0.mat4.equals(this,Z)}exactEquals(Z){return e0.mat4.exactEquals(this,Z)}frustrum(Z,J,X,Y,$,Q){return e0.mat4.frustum(this,Z,J,X,Y,$,Q),this}identity(){return e0.mat4.identity(this),this}invert(){return e0.mat4.invert(this,this),this}lookAt(Z,J,X){return e0.mat4.lookAt(this,Z,J,X),this}multiply(Z){return e0.mat4.mul(this,this,Z),this}multiplyScalar(Z){return e0.mat4.multiplyScalar(this,this,Z),this}orthographic(Z,J,X,Y,$,Q){return e0.mat4.ortho(this,Z,J,X,Y,$,Q),this}perspective(Z,J,X,Y){return e0.mat4.perspective(this,Z,J,X,Y),this}rotate(Z,J){return e0.mat4.rotate(this,this,Z,J),this}rotateX(Z){return e0.mat4.rotateX(this,this,Z),this}rotateY(Z){return e0.mat4.rotateY(this,this,Z),this}rotateZ(Z){return e0.mat4.rotateZ(this,this,Z),this}scale(Z){return e0.mat4.scale(this,this,Z),this}subtract(Z){return e0.mat4.sub(this,this,Z),this}targetTo(Z,J,X){return e0.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 e0.mat4.translate(this,this,Z),this}transpose(){return e0.mat4.transpose(this,this),this}}var A1=r(MQ(),1);class yG extends Float32Array{constructor(Z,J,X,Y){super([Z,J,X,Y])}get length(){return A1.quat.length(this)}get squaredLength(){return A1.quat.squaredLength(this)}get magnitude(){return A1.quat.length(this)}get squaredMagnitude(){return A1.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=A1.quat.fromEuler(new Float32Array(4),Z,J,X);return new yG(Y[0],Y[1],Y[2],Y[3])}static fromQuaternionLike(Z){return new yG(Z.x,Z.y,Z.z,Z.w)}clone(){return new yG(this.x,this.y,this.z,this.w)}conjugate(){return A1.quat.conjugate(this,this),this}copy(Z){return A1.quat.copy(this,Z),this}dot(Z){return A1.quat.dot(this,Z)}exponential(){return A1.quat.exp(this,this),this}equals(Z){return A1.quat.equals(this,Z)}exactEquals(Z){return A1.quat.exactEquals(this,Z)}getAngle(Z){return A1.quat.getAngle(this,Z)}identity(){return A1.quat.identity(this),this}invert(){return A1.quat.invert(this,this),this}lerp(Z,J){return A1.quat.lerp(this,this,Z,J),this}logarithm(){return A1.quat.ln(this,this),this}multiply(Z){return A1.quat.multiply(this,this,Z),this}transformVector(Z){return Z.transformQuaternion(this)}normalize(){return A1.quat.normalize(this,this),this}power(Z){return A1.quat.pow(this,this,Z),this}randomize(){return A1.quat.random(this),this}rotateX(Z){return A1.quat.rotateX(this,this,Z),this}rotateY(Z){return A1.quat.rotateY(this,this,Z),this}rotateZ(Z){return A1.quat.rotateZ(this,this,Z),this}scale(Z){return A1.quat.scale(this,this,Z),this}setAxisAngle(Z,J){return A1.quat.setAxisAngle(this,Z,J),this}slerp(Z,J){return A1.quat.slerp(this,this,Z,J),this}toString(){return`${this.x},${this.y},${this.z},${this.w}`}}var H1=r(MQ(),1);class jq extends Float32Array{constructor(Z,J){super([Z,J])}get length(){return H1.vec2.length(this)}get squaredLength(){return H1.vec2.squaredLength(this)}get magnitude(){return H1.vec2.length(this)}get squaredMagnitude(){return H1.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 jq(0,0)}add(Z){return H1.vec2.add(this,this,Z),this}angle(Z){return H1.vec2.angle(this,Z)}ceil(){return H1.vec2.ceil(this,this),this}clone(){return new jq(this.x,this.y)}copy(Z){return H1.vec2.copy(this,Z),this}distance(Z){return H1.vec2.distance(this,Z)}divide(Z){return H1.vec2.divide(this,this,Z),this}dot(Z){return H1.vec2.dot(this,Z)}equals(Z){return H1.vec2.equals(this,Z)}exactEquals(Z){return H1.vec2.exactEquals(this,Z)}floor(){return H1.vec2.floor(this,this),this}invert(){return H1.vec2.inverse(this,this),this}lerp(Z,J){return H1.vec2.lerp(this,this,Z,J),this}max(Z){return H1.vec2.max(this,this,Z),this}min(Z){return H1.vec2.min(this,this,Z),this}multiply(Z){return H1.vec2.mul(this,this,Z),this}negate(){return H1.vec2.negate(this,this),this}normalize(){return H1.vec2.normalize(this,this),this}randomize(Z){return H1.vec2.random(this,Z),this}rotate(Z,J){return H1.vec2.rotate(this,this,Z,J),this}round(){return H1.vec2.round(this,this),this}scale(Z){return H1.vec2.scale(this,this,Z),this}scaleAndAdd(Z,J){return H1.vec2.scaleAndAdd(this,this,Z,J),this}subtract(Z){return H1.vec2.sub(this,this,Z),this}toString(){return`${this.x},${this.y}`}transformMatrix2(Z){return H1.vec2.transformMat2(this,this,Z),this}transformMatrix3(Z){return H1.vec2.transformMat3(this,this,Z),this}transformMatrix4(Z){return H1.vec2.transformMat4(this,this,Z),this}zero(){return H1.vec2.zero(this),this}}var $1=r(MQ(),1);class bG extends Float32Array{constructor(Z,J,X){super([Z,J,X])}get length(){return $1.vec3.length(this)}get squaredLength(){return $1.vec3.squaredLength(this)}get magnitude(){return $1.vec3.length(this)}get squaredMagnitude(){return $1.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 bG(0,0,0)}static fromVector3Like(Z){return new bG(Z.x,Z.y,Z.z)}add(Z){return $1.vec3.add(this,this,Z),this}ceil(){return $1.vec3.ceil(this,this),this}clone(){return new bG(this.x,this.y,this.z)}copy(Z){return $1.vec3.copy(this,Z),this}cross(Z){return $1.vec3.cross(this,this,Z),this}distance(Z){return $1.vec3.distance(this,Z)}divide(Z){return $1.vec3.div(this,this,Z),this}dot(Z){return $1.vec3.dot(this,Z)}equals(Z){return $1.vec3.equals(this,Z)}exactEquals(Z){return $1.vec3.exactEquals(this,Z)}floor(){return $1.vec3.floor(this,this),this}invert(){return $1.vec3.inverse(this,this),this}lerp(Z,J){return $1.vec3.lerp(this,this,Z,J),this}max(Z){return $1.vec3.max(this,this,Z),this}min(Z){return $1.vec3.min(this,this,Z),this}multiply(Z){return $1.vec3.mul(this,this,Z),this}negate(){return $1.vec3.negate(this,this),this}normalize(){return $1.vec3.normalize(this,this),this}randomize(Z){return $1.vec3.random(this,Z),this}rotateX(Z,J){return $1.vec3.rotateX(this,this,Z,J),this}rotateY(Z,J){return $1.vec3.rotateY(this,this,Z,J),this}rotateZ(Z,J){return $1.vec3.rotateZ(this,this,Z,J),this}round(){return $1.vec3.round(this,this),this}scale(Z){return $1.vec3.scale(this,this,Z),this}scaleAndAdd(Z,J){return $1.vec3.scaleAndAdd(this,this,Z,J),this}subtract(Z){return $1.vec3.sub(this,this,Z),this}toString(){return`${this.x},${this.y},${this.z}`}transformMatrix3(Z){return $1.vec3.transformMat3(this,this,Z),this}transformMatrix4(Z){return $1.vec3.transformMat4(this,this,Z),this}transformQuaternion(Z){return $1.vec3.transformQuat(this,this,Z),this}zero(){return $1.vec3.zero(this),this}}var oW1=r(sW1(),1);class Nq extends eX{faceSpeed=0;idleLoopedAnimations=[];idleLoopedAnimationsSpeed;jumpOneshotAnimations=[];moveLoopedAnimations=[];moveLoopedAnimationsSpeed;moveSpeed=0;_faceTarget;_jumpHeight=0;_moveTarget;_moveIgnoreAxes={};_moveStartMoveAnimations=!1;_moveStartIdleAnimationsOnCompletion=!0;_onFace;_onFaceComplete;_onMove;_onMoveComplete;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._moveTarget=Z,this._moveIgnoreAxes=X?.moveIgnoreAxes??{},this._moveStartIdleAnimationsOnCompletion=X?.moveStartIdleAnimationsOnCompletion??!0,this._moveStartMoveAnimations=!0,this._onMove=X?.moveCallback,this._onMoveComplete=X?.moveCompleteCallback}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;if(Q>0.1){let K=Math.sqrt(Q),W=this.moveSpeed*X,V=Math.min(K,W)/K,H={x:Y.x+$.x*V,y:Y.y+$.y*V,z:Y.z+$.z*V};if(Z.setPosition(H),this._onMove)this._onMove(H,this._moveTarget)}else{if(this._moveTarget=void 0,this._moveStartIdleAnimationsOnCompletion)this._startIdleAnimations(Z);if(this._onMoveComplete){let K=this._onMoveComplete;this._onMove=void 0,this._onMoveComplete=void 0,K(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,W=Math.atan2(2*(K.w*K.y),1-2*(K.y*K.y)),G=Q-W;while(G>Math.PI)G-=2*Math.PI;while(G<-Math.PI)G+=2*Math.PI;if(Math.abs(G)>0.01){let V=this.faceSpeed*X,H=Math.abs(G)<V?G:Math.sign(G)*V,z=(W+H)/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._onFaceComplete){let V=this._onFaceComplete;this._onFaceComplete=void 0,V(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 py extends Nq{_debug=!1;_entity;_maxFall=0;_maxJump=0;_maxOpenSetIterations=200;_onPathfindAbort;_onPathfindComplete;_onWaypointMoveComplete;_onWaypointMoveSkipped;_speed=0;_target;_verticalPenalty=0;_waypoints=[];_waypointNextIndex=0;_waypointTimeoutMs=2000;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._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}tick(Z,J){super.tick(Z,J)}_calculatePath(){if(!this._target||!this._entity?.world)return u.error("PathfindingEntityController._calculatePath: No target or world"),!1;let Z=this._entity.height,J=this._findGroundedStart();if(!J){if(this._debug)u.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 W=this._coordinateToKey(J),G=new Map,V=new Map([[W,0]]),H=new Map([[W,this._pathfindingHeuristic(J,X)]]),F=new Set,z=new oW1.Heap((N,R)=>{let D=H.get(N[0])??1/0,P=H.get(R[0])??1/0;return D-P});z.push([W,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 N=this._maxJump;N>=this._maxFall;N--){if(N===0)continue;let R=Math.abs(J.y+N-X.y);U.push({y:N,distanceToTargetY:R})}U.sort((N,R)=>N.distanceToTargetY-R.distanceToTargetY);let B=[...q,...U.flatMap(({y:N})=>q.map((R)=>({...R,y:N})))],L=0,w=Math.abs(X.x-J.x)+Math.abs(X.y-J.y)+Math.abs(X.z-J.z),j=Math.min(this._maxOpenSetIterations,w*20);while(!z.isEmpty()&&L<j){L++;let[N,R]=z.pop();if(R.x===X.x&&R.y===X.y&&R.z===X.z){let C=this._reconstructPath(G,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(N);let D=V.get(N),P=new Map;for(let C of B){let T=`${C.x},${C.z}`,E=C.y<0;if(E&&P.has(T))continue;let A={x:R.x+C.x,y:R.y+C.y,z:R.z+C.z};if(Math.abs(X.x-A.x)+Math.abs(X.y-A.y)+Math.abs(X.z-A.z)>w*1.5)continue;let x=this._coordinateToKey(A);if(F.has(x))continue;let I=this._isNeighborCoordinateBlocked(R,A,this._entity.height);if(E&&I){P.set(T,!0);continue}if(I)continue;let _=Math.abs(C.x),y=Math.abs(C.y),p=Math.abs(C.z),n=y===0?0:this._verticalPenalty,o=(Math.max(_,y,p)===1&&_+y+p>1?1.4:1)+n,J0=D+o,Q0=V.get(x)??1/0;if(J0>=Q0)continue;G.set(x,R),V.set(x,J0);let D0=J0+this._pathfindingHeuristic(A,X);H.set(x,D0),z.push([x,A])}}if(L>=j){if(this._onPathfindAbort?.(),this._debug)u.warning(`PathfindingEntityController._calculatePath: Maximum open set iterations reached (${j}), path search aborted. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`)}else if(this._debug)u.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*$),W=Z.x+0.5,G=Z.z+0.5,V=J.x+0.5,H=J.z+0.5,F=V-W,z=H-G,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,{moveStartIdleAnimationsOnCompletion:this._waypointNextIndex===this._waypoints.length-1,moveIgnoreAxes:{y:this._entity.isDynamic},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),W=Math.floor(Z.x),G=Math.floor(Z.z);if(!Y.chunkLattice.hasBlock({x:$,y:Q-1,z:K}))return!0;for(let V=0;V<X;V++)if(Y.chunkLattice.hasBlock({x:$,y:Q+V,z:K}))return!0;if($!==W&&K!==G)for(let V=0;V<X;V++){let H=Y.chunkLattice.hasBlock({x:$,y:Q+V,z:G}),F=Y.chunkLattice.hasBlock({x:W,y:Q+V,z:K});if(H||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{WJ6 as startServer,KK1 as WorldManagerEvent,fG as WorldManager,QK1 as WorldLoopEvent,Bq as WorldLoop,xy as WorldEvent,wq as World,zv as WebServerEvent,TW as WebServer,bG as Vector3,jq as Vector2,Lq as Ticker,Ay as SimulationEvent,qq as Simulation,Nq as SimpleEntityController,Uq as SceneUIManager,ky as SceneUIEvent,Qq as SceneUI,VK1 as SUPPORTED_INPUT_KEYS,SV as RigidBodyType,dY as RigidBody,XK1 as ROTATION_UPDATE_THRESHOLD,yG as Quaternion,vR as PlayerUIEvent,Hq as PlayerUI,tQ1 as PlayerManagerEvent,Y9 as PlayerManager,Kq as PlayerEvent,o7 as PlayerEntity,$K1 as PlayerCameraMode,vy as PlayerCameraEvent,Vq as PlayerCamera,xG as Player,jQ as PersistenceManager,py as PathfindingEntityController,JK1 as POSITION_UPDATE_THRESHOLD_SQ,Vv as PORT,_9 as ModelRegistry,O5 as Matrix4,e7 as Matrix3,PQ as Matrix2,YK1 as LightType,Gq as LightManager,Iy as LightEvent,_y as Light,GK1 as GameServerEvent,GJ as GameServer,g0 as EventRouter,u as ErrorHandler,Wq as EntityManager,$q as EntityEvent,i8 as Entity,y1 as DefaultPlayerEntityController,fy as DefaultPlayerEntity,ZK1 as DEFAULT_ENTITY_RIGID_BODY_OPTIONS,H4 as CollisionGroupsBuilder,KY as CollisionGroup,AV as ColliderShape,zq as ColliderMap,r5 as Collider,yT as CoefficientCombineRule,Yq as ChunkLattice,Ey as ChunkEvent,u6 as Chunk,Oq as ChatManager,hy as ChatEvent,gT as BlockTypeRegistryEvent,xV as BlockTypeRegistry,bT as BlockTypeEvent,t5 as BlockType,TQ as Block,ty as BaseEntityControllerEvent,eX as BaseEntityController,uG as AudioManager,sR as AudioEvent,mG as Audio};
491
+ `);let{connect:G,buffered:V}=await W;if(Z.emit("proxyConnect",G),this.emit("proxyConnect",G,Z),G.statusCode===200){if(Z.once("socket",IZ6),J.secureEndpoint){Xq("Upgrading socket connection to TLS");let F=J.servername||J.host;return Py.connect({...xQ1(J,"host","path","port"),socket:Y,servername:WJ.isIP(F)?void 0:F})}return Y}Y.destroy();let H=new WJ.Socket({writable:!1});return H.readable=!0,Z.once("socket",(F)=>{Xq("Replaying proxy buffer for failed request"),F.push(V),F.push(null)}),H}}kR.__initStatic();function IZ6(Z){Z.resume()}function xQ1(Z,...J){let X={},Y;for(Y in Z)if(!J.includes(Y))X[Y]=Z[Y];return X}var xZ6=32768;function hZ6(Z){return new SZ6({read(){this.push(Z),this.push(null)}})}function hQ1(Z){let J;try{J=new URL(Z.url)}catch(G){return P8(()=>{console.warn("[@sentry/node]: Invalid dsn or tunnel option, will not send any events. The tunnel option must be a full URL when used.")}),fz(Z,()=>Promise.resolve({}))}let X=J.protocol==="https:",Y=fZ6(J,Z.proxy||(X?process.env.https_proxy:void 0)||process.env.http_proxy),$=X?vZ6:_Z6,Q=Z.keepAlive===void 0?!1:Z.keepAlive,K=Y?new kR(Y):new $.Agent({keepAlive:Q,maxSockets:30,timeout:2000}),W=yZ6(Z,Z.httpModule??$,K);return fz(Z,W)}function fZ6(Z,J){let{no_proxy:X}=process.env;if(X?.split(",").some(($)=>Z.host.endsWith($)||Z.hostname.endsWith($)))return;else return J}function yZ6(Z,J,X){let{hostname:Y,pathname:$,port:Q,protocol:K,search:W}=new URL(Z.url);return function G(V){return new Promise((H,F)=>{pO(()=>{let z=hZ6(V.body),q={...Z.headers};if(V.body.length>xZ6)q["content-encoding"]="gzip",z=z.pipe(AZ6());let U=J.request({method:"POST",agent:X,headers:q,hostname:Y,path:`${$}${W}`,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;H({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 bZ6=new Set(["false","f","n","no","off","0"]),gZ6=new Set(["true","t","y","yes","on","1"]);function IR(Z,J){let X=String(Z).toLowerCase();if(bZ6.has(X))return!1;if(gZ6.has(X))return!0;return J?.strict?null:Boolean(Z)}import{posix as mZ6,sep as uZ6}from"node:path";function fQ1(Z){return Z.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}function yQ1(Z=process.argv[1]?WS(process.argv[1]):process.cwd(),J=uZ6==="\\"){let X=J?fQ1(Z):Z;return(Y)=>{if(!Y)return;let $=J?fQ1(Y):Y,{dir:Q,base:K,ext:W}=mZ6.parse($);if(W===".js"||W===".mjs"||W===".cjs")K=K.slice(0,W.length*-1);let G=decodeURIComponent(K);if(!Q)Q=".";let V=Q.lastIndexOf("/node_modules");if(V>-1)return`${Q.slice(V+14).replace(/\//g,".")}:${G}`;if(Q.startsWith(X)){let H=Q.slice(X.length+1).replace(/\//g,".");return H?`${H}:${G}`:G}return G}}function bQ1(Z){if(process.env.SENTRY_RELEASE)return process.env.SENTRY_RELEASE;if(k0.SENTRY_RELEASE?.id)return k0.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 gQ1=bO(GS(yQ1()));var uQ1=r(Z0(),1),dQ1=r(V1(),1);import*as mQ1 from"node:os";import{threadId as dZ6,isMainThread as cZ6}from"worker_threads";var lZ6=60000;class Dy extends Xj{constructor(Z){let J=Z.serverName||global.process.env.SENTRY_NAME||mQ1.hostname(),X={...Z,platform:"node",runtime:{name:"node",version:global.process.version},serverName:J};if(Z.openTelemetryInstrumentations)dQ1.registerInstrumentations({instrumentations:Z.openTelemetryInstrumentations});YS(X,"node"),l.log(`Initializing Sentry: process: ${process.pid}, thread: ${cZ6?"main":`worker-${dZ6}`}.`);super(X);if(this.getOptions()._experiments?.enableLogs){if(this._logOnExitFlushListener=()=>{v$(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=x8,X=uQ1.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&&l.log("Flushing client reports based on interval."),this._flushOutcomes()},Z.clientReportFlushInterval??lZ6).unref(),process.on("beforeExit",this._clientReportOnExitFlushListener)}_getTraceInfoFromScope(Z){if(!Z)return[void 0,void 0];return C61(this,Z)}}var a4=r(Z0(),1),cQ1=r(Eh(),1),lQ1=r(_h(),1),AG=r(v1(),1);var pQ1=r(gx(),1);import pZ6 from"module";var Cy=1e6;function iQ1(Z,J={}){if(Z.getOptions().debug)aZ6();let X=iZ6(Z,J);Z.traceProvider=X}function nQ1(){let[Z=0,J=0]=process.versions.node.split(".").map(Number);if(Z>=21||Z===20&&J>=6||Z===18&&J>=19){if(!k0._sentryEsmLoaderHookRegistered)try{let{addHookMessagePort:X}=pQ1.createAddHookMessageChannel();pZ6.register("import-in-the-middle/hook.mjs",import.meta.url,{data:{addHookMessagePort:X,include:[]},transferList:[X]})}catch(X){l.warn("Failed to register ESM hook",X)}}else P8(()=>{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 iZ6(Z,J={}){let X=new lQ1.BasicTracerProvider({sampler:new oh(Z),resource:new cQ1.Resource({[AG.ATTR_SERVICE_NAME]:"node",[AG.SEMRESATTRS_SERVICE_NAMESPACE]:"sentry",[AG.ATTR_SERVICE_VERSION]:x8}),forceFlushTimeoutMillis:500,spanProcessors:[new sh({timeout:nZ6(Z.getOptions().maxSpanWaitDuration)}),...J.spanProcessors||[]]});return a4.trace.setGlobalTracerProvider(X),a4.propagation.setGlobalPropagator(new lh),a4.context.setGlobalContextManager(new _Q1),X}function nZ6(Z){if(Z==null)return;if(Z>Cy)return m0&&l.warn(`\`maxSpanWaitDuration\` is too high, using the maximum value of ${Cy}`),Cy;else if(Z<=0||Number.isNaN(Z)){m0&&l.warn("`maxSpanWaitDuration` must be a positive number, using default value instead.");return}return Z}function aZ6(){let Z=new Proxy(l,{get(J,X,Y){return Reflect.get(J,X==="verbose"?"debug":X,Y)}});a4.diag.disable(),a4.diag.setLogger(Z,a4.DiagLogLevel.DEBUG)}function sZ6(){return RG()?[T51()]:[]}function aQ1(){return[Kj(),$j(),Wj(),Gj(),Vj(),b61(),K51(),E51(),k51(),L51(),P51(),V51(),BQ1(),vQ1(),...sZ6()]}function sQ1(Z){return[...aQ1(),...K9(Z)?SQ1():[]]}function Ty(Z={}){return oZ6(Z,sQ1)}function oZ6(Z={},J){let X=rZ6(Z,J);if(X.debug===!0)if(m0)l.enable();else P8(()=>{console.warn("[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.")});if(!RG()&&X.registerEsmLoaderHooks!==!1)nQ1();if(E61(),j1().update(X.initialScope),X.spotlight&&!X.integrations.some(({name:Q})=>Q===Uy))X.integrations.push(G$1({sidecarUrl:typeof X.spotlight==="string"?X.spotlight:void 0}));let $=new Dy(X);if(j1().setClient($),$.init(),l.log(`Running in ${RG()?"CommonJS":"ESM"} mode.`),$.startClientReportTracking(),ZJ6(),!X.skipOpenTelemetrySetup)iQ1($,{spanProcessors:X.openTelemetrySpanProcessors}),oQ1();return B61($),T61($),$}function oQ1(){if(!m0)return;let Z=N61(),J=["SentryContextManager","SentryPropagator"];if(K9())J.push("SentrySpanProcessor");for(let X of J)if(!Z.includes(X))l.error(`You have to set up the ${X}. Without this, the OpenTelemetry & Sentry integration will not work properly.`);if(!Z.includes("SentrySampler"))l.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 rZ6(Z,J){let X=tZ6(Z.release),Y=Z.spotlight??IR(process.env.SENTRY_SPOTLIGHT,{strict:!0})??process.env.SENTRY_SPOTLIGHT,$=eZ6(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??hQ1,stackParser:Sv(Z.stackParser||gQ1),release:X,tracesSampleRate:$,spotlight:Y,debug:IR(Z.debug??process.env.SENTRY_DEBUG)},K=Z.integrations,W=Z.defaultIntegrations??J(Q);return{...Q,integrations:sv({defaultIntegrations:W,integrations:K})}}function tZ6(Z){if(Z!==void 0)return Z;let J=bQ1();if(J!==void 0)return J;return}function eZ6(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 ZJ6(){if(IR(process.env.SENTRY_USE_ENVIRONMENT)!==!1){let Z=process.env.SENTRY_TRACE,J=process.env.SENTRY_BAGGAGE,X=Cz(Z,J);j1().setPropagationContext(X)}}if(process.env.NODE_ENV==="production"&&process.env.SENTRY_DSN)Ty({dsn:process.env.SENTRY_DSN,release:Hv,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:(Z)=>{return Z.extra=X8.getProcessStats(),Z},beforeSendTransaction:(Z)=>{if(Z.contexts?.trace?.op==="ticker_tick"){let X=Z?.start_timestamp,Y=Z?.timestamp;if(!X||!Y)return null;if((Y-X)*1000>30)return Z.measurements=X8.getProcessStats(!0),Z}return null}}),console.log("Telemetry: Sentry.io initialized!");class X8{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 startSpan(Z,J){if(tO())return lO({attributes:Z.attributes,name:Z.operation,op:Z.operation},J);else return J()}}var rQ1=new Y$,XJ6=5000;class M$ extends g0{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=o80(),this.onPacket(X0.PacketId.CONNECTION,this._onConnectionPacket),this.onPacket(X0.PacketId.HEARTBEAT,this._onHeartbeatPacket),this.bindWs(Z),F6.emit("CONNECTION.OPENED",{connection:this,req:J})}static serializePackets(Z){for(let X of Z)if(!X0.isValidPacket(X))return u.error(`Connection.serializePackets(): Invalid packet payload: ${JSON.stringify(X)}`);let J=M$._cachedPacketsSerializedBuffer.get(Z);if(J)return J;return X8.startSpan({operation:"serialize_packets",attributes:{packets:Z.length,packetIds:Z.map((X)=>X[0]).join(",")}},(X)=>{let Y=X8.startSpan({operation:"serialize_packets_encode"},()=>rQ1.pack(Z));return X?.setAttribute("serializedBytes",Y.byteLength),M$._cachedPacketsSerializedBuffer.set(Z,Y),Y})}bindWs(Z){let J=this._closeTimeout!==null;if(J)clearTimeout(this._closeTimeout),this._closeTimeout=null;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([X0.createPacket(X0.bidirectionalPackets.connectionPacketDefinition,{i:this.id})],!0,!0),J)this.emitWithGlobal("CONNECTION.RECONNECTED",{connection:this});if(QX.instance.isWrtcEnabled)this._upgradeToWRTC()}closeWrtc(){this._closeWrtcClientServerTransport(),this._closeWrtcServerClientTransport()}disconnect(){try{this._ws.close()}catch(Z){u.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!==Ik.default.OPEN)return;X8.startSpan({operation:"send_packets",attributes:{forceWs:X?"true":"false",wrtcConnected:this._wrtcServerClientTransport?.iceState==="completed"?"true":"false"}},()=>{try{let Y=M$.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){u.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([X0.createPacket(X0.bidirectionalPackets.connectionPacketDefinition,{ca:{i:$}})])}if(Y)for(let $ of Y){let{s:Q,l:K}=$,W=await this._wrtcClientServerTransport.produceData({label:K,sctpStreamParameters:Q}),G=await this._wrtcDirectTransport.consumeData({dataProducerId:W.id});this._wrtcClientServerDataProducers.push(W),this._wrtcClientServerDataConsumers.push(G),G.on("message",(V)=>this._onMessage(V)),this.send([X0.createPacket(X0.bidirectionalPackets.connectionPacketDefinition,{pa:{i:W.id,l:K}})])}};_onHeartbeatPacket=()=>{this.send([X0.createPacket(X0.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){u.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()},XJ6)};_onWsError=(Z)=>{this.emitWithGlobal("CONNECTION.ERROR",{connection:this,error:Z})};_upgradeToWRTC=async()=>{let Z=await QX.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([X0.createPacket(X0.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=rQ1.unpack(Z);if(!J||typeof J!=="object"||typeof J[0]!=="number")return u.error(`Connection._deserialize(): Invalid packet format. Packet: ${JSON.stringify(J)}`);if(!X0.isValidPacket(J))return u.error(`Connection._deserialize(): Invalid packet payload. Packet: ${JSON.stringify(J)}`);return J}}var tQ1;((Y)=>{Y.PLAYER_CONNECTED="PLAYER_MANAGER.PLAYER_CONNECTED";Y.PLAYER_DISCONNECTED="PLAYER_MANAGER.PLAYER_DISCONNECTED";Y.PLAYER_RECONNECTED="PLAYER_MANAGER.PLAYER_RECONNECTED"})(tQ1||={});class Y9{static instance=new Y9;_connectionPlayers=new Map;constructor(){F6.on("CONNECTION.OPENED",({connection:Z,req:J})=>{this._onConnectionOpened(Z,J.session)}),F6.on("CONNECTION.DISCONNECTED",({connection:Z})=>{this._onConnectionDisconnected(Z)}),F6.on("CONNECTION.RECONNECTED",({connection:Z})=>{this._onConnectionReconnected(Z)}),F6.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()})}_onConnectionOpened(Z,J){let X=new xG(Z,J);this._connectionPlayers.set(Z,X),F6.emit("PLAYER_MANAGER.PLAYER_CONNECTED",{player:X})}_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.reconnect(),F6.emit("PLAYER_MANAGER.PLAYER_RECONNECTED",{player:J});else u.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),F6.emit("PLAYER_MANAGER.PLAYER_DISCONNECTED",{player:J});else u.warning(`PlayerManager._onConnectionClosed(): Connection ${Z.id} not in the PlayerManager._connectionPlayers map.`)}}var E8=16,hG=E8-1,eQ1=E8**3,YJ6=[{neighborOffset:[-1,0,0],generateVertices:(Z,J,X)=>[Z+0,J+0,X+0,Z+0,J+0,X+1,Z+0,J+1,X+0,Z+0,J+1,X+0,Z+0,J+0,X+1,Z+0,J+1,X+1]},{neighborOffset:[1,0,0],generateVertices:(Z,J,X)=>[Z+1,J+0,X+0,Z+1,J+1,X+0,Z+1,J+0,X+1,Z+1,J+1,X+0,Z+1,J+1,X+1,Z+1,J+0,X+1]},{neighborOffset:[0,-1,0],generateVertices:(Z,J,X)=>[Z+0,J+0,X+0,Z+1,J+0,X+0,Z+0,J+0,X+1,Z+1,J+0,X+0,Z+1,J+0,X+1,Z+0,J+0,X+1]},{neighborOffset:[0,1,0],generateVertices:(Z,J,X)=>[Z+0,J+1,X+0,Z+0,J+1,X+1,Z+1,J+1,X+0,Z+1,J+1,X+0,Z+0,J+1,X+1,Z+1,J+1,X+1]},{neighborOffset:[0,0,-1],generateVertices:(Z,J,X)=>[Z+0,J+0,X+0,Z+0,J+1,X+0,Z+1,J+0,X+0,Z+0,J+1,X+0,Z+1,J+1,X+0,Z+1,J+0,X+0]},{neighborOffset:[0,0,1],generateVertices:(Z,J,X)=>[Z+0,J+0,X+1,Z+1,J+0,X+1,Z+0,J+1,X+1,Z+0,J+1,X+1,Z+1,J+0,X+1,Z+1,J+1,X+1]}],Ey;((Y)=>{Y.DESPAWN="CHUNK.DESPAWN";Y.SET_BLOCK="CHUNK.SET_BLOCK";Y.SPAWN="CHUNK.SPAWN"})(Ey||={});class u6 extends g0{_blocks;_originCoordinate;_requiresUpdate=!1;_rigidBody;_world;constructor(){super();this._blocks=new Uint8Array(eQ1)}get blocks(){return this._blocks}get requiresUpdate(){return this._requiresUpdate}get isSimulated(){return!!this._rigidBody}get isSpawned(){return!!this._originCoordinate&&!!this._world}get originCoordinate(){return this._originCoordinate}get world(){return this._world}static blockIndexToLocalCoordinate(Z){return{x:Z%E8,y:(Z/E8|0)%E8,z:Z/(E8*E8)|0}}static globalCoordinateToLocalCoordinate(Z){return{x:Z.x&E8-1,y:Z.y&E8-1,z:Z.z&E8-1}}static globalCoordinateToOriginCoordinate(Z){return{x:Z.x&~(E8-1),y:Z.y&~(E8-1),z:Z.z&~(E8-1)}}static isValidOriginCoordinate(Z){return Z.x%E8===0&&Z.y%E8===0&&Z.z%E8===0}spawn(Z,J){if(this.isSpawned){let{x:X,y:Y,z:$}=this.originCoordinate;return u.error(`Chunk.spawn(): Chunk is already spawned at origin ${X}, ${Y}, ${$}!`)}if(!u6.isValidOriginCoordinate(J))return u.error(`Chunk.spawn(): Chunk coordinates must be divisible by ${E8}`);this._originCoordinate=J,this._world=Z,this._world.chunkLattice.registerChunk(this),this._requiresUpdate=!0}despawn(){if(!this.isSpawned)return u.error("Chunk.despawn(): Chunk has not been spawned and cannot be despawned!");this.emitWithWorld(this._world,"CHUNK.DESPAWN",{chunk:this}),this._removeFromSimulation(),this._world.chunkLattice.unregisterChunk(this),this._originCoordinate=void 0,this._world=void 0}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 u.error("Chunk.setBlock(): Block local coordinate is out of bounds");if(this._blocks[this._getIndex(Z)]===J)return;if(this._blocks[this._getIndex(Z)]=J,this.isSpawned&&this.isSimulated){this.emitWithWorld(this._world,"CHUNK.SET_BLOCK",{chunk:this,globalCoordinate:this._getGlobalCoordinate(Z),localCoordinate:Z,blockTypeId:J});let X=this._getGlobalCoordinate(Z),Y=[];if(Z.x===0)Y.push({x:-1,y:0,z:0});if(Z.y===0)Y.push({x:0,y:-1,z:0});if(Z.z===0)Y.push({x:0,y:0,z:-1});if(Z.x===hG)Y.push({x:1,y:0,z:0});if(Z.y===hG)Y.push({x:0,y:1,z:0});if(Z.z===hG)Y.push({x:0,y:0,z:1});for(let $ of Y){let Q={x:X.x+$.x,y:X.y+$.y,z:X.z+$.z},K=u6.globalCoordinateToOriginCoordinate(Q),W=this._world?.chunkLattice.getChunk(K);if(!W?.hasBlock(u6.globalCoordinateToLocalCoordinate(Q)))continue;W.setRequiresUpdate(!0)}}this._requiresUpdate=!0}setRequiresUpdate(Z){this._requiresUpdate=Z}update(){if(!this._requiresUpdate)return;if(!this.isSpawned)return u.error("Chunk.update(): Chunk is not spawned and cannot be updated.");let Z=!this._rigidBody,J=this._world.simulation;if(this._removeFromSimulation(),this._rigidBody=new dY({type:"fixed",position:this._originCoordinate,simulation:this._world.simulation}),this._meshColliders().map(([X,Y])=>{if(!X.isSimulated)X.addToSimulation(J,this._rigidBody);J.colliderMap.setColliderBlockType(X,Y)}),this._requiresUpdate=!1,Z)this.emitWithWorld(this._world,"CHUNK.SPAWN",{chunk:this})}serialize(){return p0.serializeChunk(this)}_meshColliders(){if(!this._world)return u.error("Chunk._meshColliders(): Chunk is not spawned and cannot be meshed."),[];let Z=new Map,J=[];for(let Y=0;Y<eQ1;Y++){if(this._blocks[Y]===0)continue;let $=this._blocks[Y],Q=this._world.blockTypeRegistry.getBlockType($),{x:K,y:W,z:G}=u6.blockIndexToLocalCoordinate(Y);if(!Q.isMeshable){let H=Q.createCollider();H.setRelativePosition({x:K,y:W,z:G}),J.push([H,Q]);continue}let V=Z.get(Q)??{indices:[],vertices:[]};Z.set(Q,V);for(let H of YJ6){let[F,z,q]=H.neighborOffset,U={x:K+F,y:W+z,z:G+q},B=this._getGlobalCoordinate(U),L=this._world.chunkLattice.getBlockType(B);if(L&&!L.isLiquid)continue;let w=V.indices.length;V.indices.push(w,w+1,w+2,w+3,w+4,w+5),V.vertices.push(...H.generateVertices(K,W,G))}}let X=[];return Z.forEach((Y,$)=>{if(!Y.indices.length)return;let Q=$.createCollider(new Uint32Array(Y.indices),new Float32Array(Y.vertices));X.push([Q,$])}),[...J,...X]}_removeFromSimulation(){if(!this._rigidBody||!this._world)return;this._rigidBody.removeFromSimulation(),this._rigidBody=void 0}_getGlobalCoordinate(Z){if(!this.originCoordinate)u.fatalError("Chunk._getGlobalCoordinate(): Chunk is not spawned, calculating global coordinate is impossible.");return{x:this.originCoordinate.x+Z.x,y:this.originCoordinate.y+Z.y,z:this.originCoordinate.z+Z.z}}_getIndex(Z){return Z.x+E8*(Z.y+E8*Z.z)}_isValidLocalCoordinate(Z){return Z.x>=0&&Z.x<=hG&&Z.y>=0&&Z.y<=hG&&Z.z>=0&&Z.z<=hG}}class Yq{_chunks=new Map;_world;constructor(Z){this._world=Z}get chunkCount(){return this._chunks.size}registerChunk(Z){if(!Z.isSpawned)return u.error("ChunkLattice.registerChunk(): Chunk is not spawned.");if(this.hasChunk(Z.originCoordinate)){let{x:J,y:X,z:Y}=Z.originCoordinate;return u.error(`ChunkLattice.registerChunk(): Chunk exists at origin (${J}, ${X}, ${Y}), despawn the current chunk before registering another at the same origin.`)}if(Z.world.id!==this._world.id)return u.error("ChunkLattice.registerChunk(): Chunk world does not match lattice world.");this._chunks.set(this._getChunkKey(Z.originCoordinate),Z)}unregisterChunk(Z){if(!Z.isSpawned)return u.error("ChunkLattice.unregisterChunk(): Chunk is not spawned.");if(Z.world.id!==this._world.id)return u.error("ChunkLattice.unregisterChunk(): Chunk world does not match lattice world.");this._chunks.delete(this._getChunkKey(Z.originCoordinate))}clear(){this._chunks.forEach((Z)=>Z.despawn()),this._chunks.clear()}getBlockId(Z){let J=this.getChunk(u6.globalCoordinateToOriginCoordinate(Z));if(!J)return 0;return J.getBlockId(u6.globalCoordinateToLocalCoordinate(Z))}getBlockType(Z){let J=this.getBlockId(Z);return J?this._world.blockTypeRegistry.getBlockType(J):null}getChunk(Z){if(!u6.isValidOriginCoordinate(Z)){u.error(`ChunkLattice.getChunk(): Chunk coordinates must be divisible by CHUNK_SIZE (${E8})`);return}return this._chunks.get(this._getChunkKey(Z))}getAllChunks(){return Array.from(this._chunks.values())}hasBlock(Z){let J=this.getChunk(u6.globalCoordinateToOriginCoordinate(Z));if(!J)return!1;return J.hasBlock(u6.globalCoordinateToLocalCoordinate(Z))}hasChunk(Z){return this._chunks.has(this._getChunkKey(Z))}setBlock(Z,J){let X=u6.globalCoordinateToLocalCoordinate(Z),Y=u6.globalCoordinateToOriginCoordinate(Z),$=this.getChunk(Y);if(!$)$=new u6,$.spawn(this._world,Y);$.setBlock(X,J)}updateChunks(){this._chunks.forEach((Z)=>{if(Z.requiresUpdate)Z.update()})}_getChunkKey(Z){return`${Z.x},${Z.y},${Z.z}`}}var ZK1={type:"dynamic",softCcdPrediction:1},JK1=0.0025000000000000005,XK1=Math.cos(0.005),$q;((w)=>{w.BLOCK_COLLISION="ENTITY.BLOCK_COLLISION";w.BLOCK_CONTACT_FORCE="ENTITY.BLOCK_CONTACT_FORCE";w.DESPAWN="ENTITY.DESPAWN";w.ENTITY_COLLISION="ENTITY.ENTITY_COLLISION";w.ENTITY_CONTACT_FORCE="ENTITY.ENTITY_CONTACT_FORCE";w.SET_MODEL_ANIMATIONS_PLAYBACK_RATE="ENTITY.SET_MODEL_ANIMATIONS_PLAYBACK_RATE";w.SET_MODEL_HIDDEN_NODES="ENTITY.SET_MODEL_HIDDEN_NODES";w.SET_OPACITY="ENTITY.SET_OPACITY";w.SET_PARENT="ENTITY.SET_PARENT";w.SET_TINT_COLOR="ENTITY.SET_TINT_COLOR";w.SPAWN="ENTITY.SPAWN";w.START_MODEL_LOOPED_ANIMATIONS="ENTITY.START_MODEL_LOOPED_ANIMATIONS";w.START_MODEL_ONESHOT_ANIMATIONS="ENTITY.START_MODEL_ONESHOT_ANIMATIONS";w.STOP_MODEL_ANIMATIONS="ENTITY.STOP_MODEL_ANIMATIONS";w.TICK="ENTITY.TICK";w.UPDATE_POSITION="ENTITY.UPDATE_POSITION";w.UPDATE_ROTATION="ENTITY.UPDATE_ROTATION"})($q||={});class i8 extends dY{_id;_blockHalfExtents;_blockTextureUri;_controller;_modelAnimationsPlaybackRate=1;_modelHiddenNodes=new Set;_modelLoopedAnimations=new Set;_modelOneshotAnimations=new Set;_modelPreferredShape;_modelScale=1;_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;constructor(Z){let J="blockTextureUri"in Z,X="modelUri"in Z;if(!J===!X)u.fatalError("Entity.constructor(): Entity data must include a blockTextureUri or modelUri, but not both.");if(J&&!Z.blockHalfExtents)u.fatalError("Entity.constructor(): Block entity must have blockHalfExtents!");if(Z.parent&&!Z.parent.isSpawned)u.fatalError("Entity.constructor(): Parent entity must be spawned before child entity!");if(Z.parent?.modelUri&&Z.parentNodeName&&!_9.instance.modelHasNode(Z.parent.modelUri,Z.parentNodeName))u.fatalError(`Entity.constructor(): Parent node name ${Z.parentNodeName} not found in parent model ${Z.parent.modelUri}!`);super(Z.rigidBodyOptions??ZK1);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._modelUri=Z.modelUri,Z.modelHiddenNodes?.forEach((Y)=>this._modelHiddenNodes.add(Y.toLowerCase())),Z.modelLoopedAnimations?.forEach((Y)=>this._modelLoopedAnimations.add(Y));if(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,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 height(){return this.isModelEntity?_9.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 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 isModelEntity(){return!!this._modelUri}get isSpawned(){return!!this._world}get world(){return this._world}spawn(Z,J,X){if(this.isSpawned)return u.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 r5(r5.optionsFromBlockHalfExtents(this._blockHalfExtents)));if(this._modelUri&&this.numColliders===0&&this._modelPreferredShape!=="none")this.addChildColliderToSimulation(new r5(r5.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(H4.isDefaultCollisionGroups(Y.collisionGroups))Y.setCollisionGroups({belongsTo:[Y.isSensor?4:2],collidesWith:[65535]})}),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.sceneUIManager.unloadEntityAttachedSceneUIs(this),this._id=void 0,this._world=void 0}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})}setController(Z){if(this._controller===Z)return;if(this._controller)this._controller.detach(this);if(this._controller=Z,this._controller)this._controller.attach(this)}setModelHiddenNodes(Z){if(!this._requireSpawned("setModelHiddenNodes"))return;this._modelHiddenNodes=new Set(Z.map((J)=>J.toLowerCase())),this.emitWithWorld(this._world,"ENTITY.SET_MODEL_HIDDEN_NODES",{entity:this,modelHiddenNodes:this._modelHiddenNodes})}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 u.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(){return p0.serializeEntity(this)}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,this.emitWithWorld(this._world,"ENTITY.UPDATE_ROTATION",{entity:this,rotation:J});if(this._positionExceedsThreshold(Z,this._lastUpdatedPosition))this._lastUpdatedPosition=Z,this.emitWithWorld(this._world,"ENTITY.UPDATE_POSITION",{entity:this,position:Z})}_positionExceedsThreshold(Z,J){let X=Z.x-J.x,Y=Z.y-J.y,$=Z.z-J.z;return X*X+Y*Y+$*$>JK1}_requireSpawned(Z){if(!this.isSpawned)u.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)<XK1}_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)}}var ky;((W)=>{W.LOAD="SCENE_UI.LOAD";W.SET_ATTACHED_TO_ENTITY="SCENE_UI.SET_ATTACHED_TO_ENTITY";W.SET_OFFSET="SCENE_UI.SET_OFFSET";W.SET_POSITION="SCENE_UI.SET_POSITION";W.SET_STATE="SCENE_UI.SET_STATE";W.SET_VIEW_DISTANCE="SCENE_UI.SET_VIEW_DISTANCE";W.UNLOAD="SCENE_UI.UNLOAD"})(ky||={});class Qq extends g0{_id;_attachedToEntity;_offset;_position;_state={};_templateId;_viewDistance;_world;constructor(Z){if(!!Z.attachedToEntity===!!Z.position)u.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 u.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 u.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(){return p0.serializeSceneUI(this)}}class o7 extends i8{player;nametagSceneUI;constructor(Z){super(Z);this.player=Z.player,this.nametagSceneUI=new Qq({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 u.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 Wq{_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)u.fatalError(`EntityManager.registerEntity(): Entity ${Z.name} is already assigned the id ${Z.id}!`);let J=this._nextEntityId;return this._entities.set(J,Z),this._nextEntityId++,J}unregisterEntity(Z){if(Z.id===void 0)return u.error(`EntityManager.unregisterEntity(): Entity ${Z.name} is not assigned an id!`);this._entities.delete(Z.id)}getAllEntities(){return Array.from(this._entities.values())}getAllPlayerEntities(){let Z=[];return this._entities.forEach((J)=>{if(J instanceof o7)Z.push(J)}),Z}getPlayerEntitiesByPlayer(Z){let J=[];return this._entities.forEach((X)=>{if(X instanceof o7&&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){this._entities.forEach((J)=>{J.tick(Z)})}checkAndEmitUpdates(){this._entities.forEach((Z)=>{if(!Z.isSpawned)return;Z.checkAndEmitUpdates()})}}class Gq{_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(){return 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)}}var YK1;((X)=>{X[X.POINTLIGHT=0]="POINTLIGHT";X[X.SPOTLIGHT=1]="SPOTLIGHT"})(YK1||={});var Iy;((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"})(Iy||={});class _y extends g0{_id;_angle;_attachedToEntity;_color;_distance;_intensity;_offset;_penumbra;_position;_trackedEntity;_trackedPosition;_type;_world;constructor(Z){if(!!Z.attachedToEntity===!!Z.position)u.fatalError("Either attachedToEntity or position must be set, but not both");super();u.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 u.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===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===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 u.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 u.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(){return p0.serializeLight(this)}}var $K1;((Y)=>{Y[Y.FIRST_PERSON=0]="FIRST_PERSON";Y[Y.THIRD_PERSON=1]="THIRD_PERSON";Y[Y.SPECTATOR=2]="SPECTATOR"})($K1||={});var vy;((q)=>{q.LOOK_AT_ENTITY="PLAYER_CAMERA.LOOK_AT_ENTITY";q.LOOK_AT_POSITION="PLAYER_CAMERA.LOOK_AT_POSITION";q.SET_ATTACHED_TO_ENTITY="PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY";q.SET_ATTACHED_TO_POSITION="PLAYER_CAMERA.SET_ATTACHED_TO_POSITION";q.SET_FILM_OFFSET="PLAYER_CAMERA.SET_FILM_OFFSET";q.SET_FORWARD_OFFSET="PLAYER_CAMERA.SET_FORWARD_OFFSET";q.SET_FOV="PLAYER_CAMERA.SET_FOV";q.SET_MODEL_HIDDEN_NODES="PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES";q.SET_MODE="PLAYER_CAMERA.SET_MODE";q.SET_OFFSET="PLAYER_CAMERA.SET_OFFSET";q.SET_TRACKED_ENTITY="PLAYER_CAMERA.SET_TRACKED_ENTITY";q.SET_TRACKED_POSITION="PLAYER_CAMERA.SET_TRACKED_POSITION";q.SET_ZOOM="PLAYER_CAMERA.SET_ZOOM"})(vy||={});class Vq extends g0{player;_attachedToEntity;_attachedToPosition;_filmOffset=0;_forwardOffset=0;_fov=75;_modelHiddenNodes=new Set;_mode=1;_offset={x:0,y:0,z:0};_orientation={pitch:0,yaw: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 filmOffset(){return this._filmOffset}get forwardOffset(){return this._forwardOffset}get fov(){return this._fov}get modelHiddenNodes(){return this._modelHiddenNodes}get mode(){return this._mode}get offset(){return this._offset}get orientation(){return this._orientation}get trackedEntity(){return this._trackedEntity}get trackedPosition(){return this._trackedPosition}get zoom(){return this._zoom}lookAtEntity(Z){if(!this._requirePlayerWorld())return;this.emitWithWorld(this.player.world,"PLAYER_CAMERA.LOOK_AT_ENTITY",{playerCamera:this,entity:Z})}lookAtPosition(Z){if(!this._requirePlayerWorld())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())return;if(!Z.isSpawned)return u.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())return;this._attachedToPosition=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_ATTACHED_TO_POSITION",{playerCamera:this,position:Z})}setFilmOffset(Z){if(!this._requirePlayerWorld())return;this._filmOffset=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_FILM_OFFSET",{playerCamera:this,filmOffset:Z})}setForwardOffset(Z){if(!this._requirePlayerWorld())return;this._forwardOffset=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_FORWARD_OFFSET",{playerCamera:this,forwardOffset:Z})}setFov(Z){if(!this._requirePlayerWorld())return;this._fov=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_FOV",{playerCamera:this,fov:Z})}setModelHiddenNodes(Z){if(!this._requirePlayerWorld())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})}setMode(Z){if(!this._requirePlayerWorld())return;this._mode=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_MODE",{playerCamera:this,mode:Z})}setOffset(Z){if(!this._requirePlayerWorld())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}setTrackedEntity(Z){if(!this._requirePlayerWorld())return;this._trackedEntity=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_TRACKED_ENTITY",{playerCamera:this,entity:Z})}setTrackedPosition(Z){if(!this._requirePlayerWorld())return;this._trackedPosition=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_TRACKED_POSITION",{playerCamera:this,position:Z})}setZoom(Z){if(!this._requirePlayerWorld())return;this._zoom=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_ZOOM",{playerCamera:this,zoom:Z})}serialize(){return p0.serializePlayerCamera(this)}_requirePlayerWorld(){if(!this.player.world)u.error(`PlayerCamera._requirePlayerWorld(): Player ${this.player.id} is not in a world!`);return!!this.player.world}}var vR;(($)=>{$.DATA="PLAYER_UI.DATA";$.LOAD="PLAYER_UI.LOAD";$.LOCK_POINTER="PLAYER_UI.LOCK_POINTER";$.SEND_DATA="PLAYER_UI.SEND_DATA"})(vR||={});class Hq extends g0{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 Fq=r(bQ(),1);class zq{_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.keys())this._cleanupBlockTypeColliderHandles.add(Z);if(this._pendingCleanupBlockTypeColliderHandles.size>0)this._pendingCleanupBlockTypeColliderHandles.clear();for(let Z of this._pendingCleanupCollisionCallbackColliderHandles.keys())this._cleanupCollisionCallbackColliderHandles.add(Z);if(this._pendingCleanupCollisionCallbackColliderHandles.size>0)this._pendingCleanupCollisionCallbackColliderHandles.clear();for(let Z of this._pendingCleanupEntityColliderHandles.keys())this._cleanupEntityColliderHandles.add(Z);if(this._pendingCleanupEntityColliderHandles.size>0)this._pendingCleanupEntityColliderHandles.clear()}_requireSimulatedCollider(Z){if(!Z.rawCollider)u.error("ColliderMap._requireSimulatedCollider(): Collider is not in the simulation.");return!!Z.rawCollider}}var $J6={x:0,y:-32,z:0},Sy=60,Ay;(($)=>{$.STEP_START="SIMULATION.STEP_START";$.STEP_END="SIMULATION.STEP_END";$.DEBUG_RAYCAST="SIMULATION.DEBUG_RAYCAST";$.DEBUG_RENDER="SIMULATION.DEBUG_RENDER"})(Ay||={});class qq extends g0{_colliderMap=new zq;_debugRaycastingEnabled=!1;_debugRenderingEnabled=!1;_debugRenderingFilterFlags;_rapierEventQueue;_rapierSimulation;_world;constructor(Z,J=Sy,X=$J6){super();this._rapierEventQueue=new Fq.default.EventQueue(!0),this._rapierSimulation=new Fq.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}raycast(Z,J,X,Y={}){let $=new Fq.default.Ray(Z,J),Q=this._rapierSimulation.castRay($,X,Y.ignoresSensors??!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),W=Q.timeOfImpact,G=Q.collider,V=this._colliderMap.getColliderHandleBlockType(G.handle);if(V)return{hitBlock:TQ.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))},V),hitPoint:K,hitDistance:W};let H=this._colliderMap.getColliderHandleEntity(G.handle);if(H)return{hitEntity:H,hitPoint:K,hitDistance:W};return null}createRawCollider(Z,J){return this._rapierSimulation.createCollider(Z,J)}createRawRigidBody(Z){return this._rapierSimulation.createRigidBody(Z)}enableDebugRaycasting(Z){this._debugRaycastingEnabled=Z}enableDebugRendering(Z,J=Fq.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 W=0;W<Y.numSolverContacts();W++)K.push(Y.solverContactPoint(W));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}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(X8.startSpan({operation:"physics_step"},()=>{this._rapierSimulation.step(this._rapierEventQueue)}),X8.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,W)=>{if(K instanceof t5&&W instanceof i8&&K.hasListeners("BLOCK_TYPE.ENTITY_COLLISION"))K.emit("BLOCK_TYPE.ENTITY_COLLISION",{blockType:K,entity:W,started:X,colliderHandleA:Z,colliderHandleB:J});else if(K instanceof i8&&W instanceof t5&&K.hasListeners("ENTITY.BLOCK_COLLISION"))K.emit("ENTITY.BLOCK_COLLISION",{entity:K,blockType:W,started:X,colliderHandleA:Z,colliderHandleB:J});else if(K instanceof i8&&W instanceof i8&&K.hasListeners("ENTITY.ENTITY_COLLISION"))K.emit("ENTITY.ENTITY_COLLISION",{entity:K,otherEntity:W,started:X,colliderHandleA:Z,colliderHandleB:J});else if(typeof K==="function"&&(W instanceof i8||W instanceof t5))K(W,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 t5&&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 t5&&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 SR{_synchronizedPlayerReliablePackets=new Map;_queuedBroadcasts=[];_queuedAudioSynchronizations={};_queuedBlockSynchronizations={};_queuedBlockTypeSynchronizations={};_queuedChunkSynchronizations={};_queuedDebugRaycastSynchronizations=[];_queuedEntitySynchronizations={};_queuedLightSynchronizations={};_queuedPerPlayerSynchronizations=new Map;_queuedPerPlayerCameraSynchronizations=new Map;_queuedPerPlayerUISynchronizations=new Map;_queuedPerPlayerUIDatasSynchronizations=new Map;_queuedPlayerSynchronizations={};_queuedSceneUISynchronizations={};_queuedWorldSynchronization;_loadedSceneUIs=new Set;_spawnedChunks=new Set;_spawnedEntities=new Set;_world;constructor(Z){this._world=Z,this._subscribeToAudioEvents(),this._subscribeToBlockTypeRegistryEvents(),this._subscribeToChatEvents(),this._subscribeToChunkEvents(),this._subscribeToEntityEvents(),this._subscribeToLightEvents(),this._subscribeToPlayerEvents(),this._subscribeToPlayerCameraEvents(),this._subscribeToPlayerUIEvents(),this._subscribeToSceneUIEvents(),this._subscribeToSimulationEvents(),this._subscribeToWorldEvents()}synchronize(){let Z=[],J=[],X=this._world.loop.currentTick;this._queuedPerPlayerSynchronizations.forEach((z,q)=>{this._createOrGetSynchronizedPlayerReliablePackets(q,Z).push(...z)});let Y=Object.values(this._queuedEntitySynchronizations);if(Y.length>0){let[z,q]=Y.reduce(([U,B],L)=>{for(let w in L)if(w!=="i"&&w!=="p"&&w!=="r")return U.push(L),[U,B];return B.push(L),[U,B]},[[],[]]);if(q.length>0){let U=X0.createPacket(X0.outboundPackets.entitiesPacketDefinition,q,X);J.push(U)}if(z.length>0){let U=X0.createPacket(X0.outboundPackets.entitiesPacketDefinition,z,X);Z.push(U),this._synchronizedPlayerReliablePackets.forEach((B)=>B.push(U))}}let $=Object.values(this._queuedAudioSynchronizations);if($.length>0){let z=X0.createPacket(X0.outboundPackets.audiosPacketDefinition,$,X);Z.push(z),this._synchronizedPlayerReliablePackets.forEach((q)=>q.push(z))}let Q=Object.values(this._queuedBlockTypeSynchronizations);if(Q.length>0){let z=X0.createPacket(X0.outboundPackets.blockTypesPacketDefinition,Q,X);Z.push(z),this._synchronizedPlayerReliablePackets.forEach((q)=>q.push(z))}let K=Object.values(this._queuedBlockSynchronizations);if(K.length>0){let z=X0.createPacket(X0.outboundPackets.blocksPacketDefinition,K,X);Z.push(z),this._synchronizedPlayerReliablePackets.forEach((q)=>q.push(z))}let W=Object.values(this._queuedChunkSynchronizations);if(W.length>0){let z=X0.createPacket(X0.outboundPackets.chunksPacketDefinition,W,X);Z.push(z),this._synchronizedPlayerReliablePackets.forEach((q)=>q.push(z))}let G=Object.values(this._queuedLightSynchronizations);if(G.length>0){let z=X0.createPacket(X0.outboundPackets.lightsPacketDefinition,G,X);Z.push(z),this._synchronizedPlayerReliablePackets.forEach((q)=>q.push(z))}this._queuedPerPlayerUISynchronizations.forEach((z,q)=>{let U=X0.createPacket(X0.outboundPackets.uiPacketDefinition,z,X);this._createOrGetSynchronizedPlayerReliablePackets(q,Z).push(U)}),this._queuedPerPlayerUIDatasSynchronizations.forEach((z,q)=>{let U=X0.createPacket(X0.outboundPackets.uiDatasPacketDefinition,z,X);this._createOrGetSynchronizedPlayerReliablePackets(q,Z).push(U)});let V=Object.values(this._queuedSceneUISynchronizations);if(V.length>0){let z=X0.createPacket(X0.outboundPackets.sceneUIsPacketDefinition,V,X);Z.push(z),this._synchronizedPlayerReliablePackets.forEach((q)=>q.push(z))}if(this._queuedWorldSynchronization){let z=X0.createPacket(X0.outboundPackets.worldPacketDefinition,this._queuedWorldSynchronization,X);Z.push(z),this._synchronizedPlayerReliablePackets.forEach((q)=>q.push(z))}this._queuedPerPlayerCameraSynchronizations.forEach((z,q)=>{let U=X0.createPacket(X0.outboundPackets.cameraPacketDefinition,z,X);this._createOrGetSynchronizedPlayerReliablePackets(q,Z).push(U)});let H=Object.values(this._queuedPlayerSynchronizations);if(H.length>0){let z=X0.createPacket(X0.outboundPackets.playersPacketDefinition,H,X);Z.push(z),this._synchronizedPlayerReliablePackets.forEach((q)=>q.push(z))}this._queuedBroadcasts.forEach((z)=>{Z.push(z),this._synchronizedPlayerReliablePackets.forEach((q)=>q.push(z))});let F=this._queuedDebugRaycastSynchronizations;if(F.length>0){let z=X0.createPacket(X0.outboundPackets.physicsDebugRaycastsPacketDefinition,F,X);Z.push(z),this._synchronizedPlayerReliablePackets.forEach((q)=>q.push(z))}X8.startSpan({operation:"send_all_packets"},()=>{Y9.instance.getConnectedPlayersByWorld(this._world).forEach((z)=>{let q=this._synchronizedPlayerReliablePackets.get(z)??Z;if(q.length>0)z.connection.send(q);if(J.length>0)z.connection.send(J,!1)})}),X8.startSpan({operation:"network_synchronize_cleanup"},()=>{if(this._queuedBroadcasts.length>0)this._queuedBroadcasts=[];if($.length>0)this._queuedAudioSynchronizations={};if(K.length>0)this._queuedBlockSynchronizations={};if(Q.length>0)this._queuedBlockTypeSynchronizations={};if(W.length>0)this._queuedChunkSynchronizations={};if(F.length>0)this._queuedDebugRaycastSynchronizations=[];if(Y.length>0)this._queuedEntitySynchronizations={};if(G.length>0)this._queuedLightSynchronizations={};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(H.length>0)this._queuedPlayerSynchronizations={};if(V.length>0)this._queuedSceneUISynchronizations={};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()})}_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)}_subscribeToChunkEvents(){this._world.final("CHUNK.SPAWN",this._onChunkSpawn),this._world.final("CHUNK.DESPAWN",this._onChunkDespawn),this._world.final("CHUNK.SET_BLOCK",this._onChunkSetBlock)}_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_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)}_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_MODE",this._onPlayerCameraSetMode),this._world.final("PLAYER_CAMERA.SET_OFFSET",this._onPlayerCameraSetOffset),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_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[J.i]=J};_onAudioPlayRestart=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.r=!0,delete J.pa,delete J.pl,this._queuedAudioSynchronizations[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):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[Z.blockType.id]=J};_onChatSendBroadcastMessage=(Z)=>{let{player:J,message:X,color:Y}=Z;this._queuedBroadcasts.push(X0.createPacket(X0.outboundPackets.chatMessagesPacketDefinition,[{m:X,c:Y,p:J?.id}],this._world.loop.currentTick))};_onChatSendPlayerMessage=(Z)=>{let{player:J,message:X,color:Y}=Z,$=this._queuedPerPlayerSynchronizations.get(J)??[];$.push(X0.createPacket(X0.outboundPackets.chatMessagesPacketDefinition,[{m:X,c:Y}],this._world.loop.currentTick)),this._queuedPerPlayerSynchronizations.set(J,$)};_onChunkSpawn=(Z)=>{let J=this._createOrGetQueuedChunkSync(Z.chunk);J.b=Array.from(Z.chunk.blocks),J.rm=void 0,this._spawnedChunks.add(J.c.join(","))};_onChunkDespawn=(Z)=>{let J=this._createOrGetQueuedChunkSync(Z.chunk),X=J.c.join(",");if(this._spawnedChunks.has(X))delete this._queuedChunkSynchronizations[X],this._spawnedChunks.delete(X);else J.rm=!0};_onChunkSetBlock=(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[J.i]=J,this._spawnedEntities.add(J.i)};_onEntityDespawn=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(this._spawnedEntities.has(J.i))delete this._queuedEntitySynchronizations[J.i],this._spawnedEntities.delete(J.i);else J.rm=!0};_onEntitySetModelHiddenNodes=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.h=Array.from(Z.modelHiddenNodes)};_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):void 0};_onEntityStartModelLoopedAnimations=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(J.al=Array.from(new Set([...J.al??[],...Z.animations])),J.as)J.as=J.as.filter((X)=>!Z.animations.has(X)).filter(Boolean)};_onEntityStartModelOneshotAnimations=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(J.ao=Array.from(new Set([...J.ao??[],...Z.animations])),J.as)J.as=J.as.filter((X)=>!Z.animations.has(X)).filter(Boolean)};_onEntityStopModelAnimations=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(J.al)J.al=J.al.filter((X)=>!Z.animations.has(X)).filter(Boolean);if(J.ao)J.ao=J.ao.filter((X)=>!Z.animations.has(X)).filter(Boolean);J.as=Array.from(new Set([...J.as??[],...Z.animations]))};_onEntityUpdateRotation=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.r=[Z.rotation.x,Z.rotation.y,Z.rotation.z,Z.rotation.w]};_onEntityUpdatePosition=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.p=[Z.position.x,Z.position.y,Z.position.z]};_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)};_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):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):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):void 0,J.te=Z.position?void 0:J.te};_onLightSpawn=(Z)=>{let J=Z.light.serialize();this._queuedLightSynchronizations[J.i]=J};_onPlayerCameraLookAtEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pl=p0.serializeVector(Z.entity.position),delete J.et,delete J.pt};_onPlayerCameraLookAtPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pl=Z.position?p0.serializeVector(Z.position):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):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=Array.from(Z.modelHiddenNodes)};_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):void 0};_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):void 0,delete J.et,delete J.pl};_onPlayerCameraSetZoom=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.z=Z.zoom};_onPlayerJoinedWorld=(Z)=>{let{player:J}=Z,X=this._queuedPerPlayerSynchronizations.get(J)??[];X.push(X0.createPacket(X0.outboundPackets.worldPacketDefinition,this._world.serialize(),this._world.loop.currentTick)),X.push(X0.createPacket(X0.outboundPackets.blockTypesPacketDefinition,this._world.blockTypeRegistry.serialize(),this._world.loop.currentTick)),X.push(X0.createPacket(X0.outboundPackets.chunksPacketDefinition,this._world.chunkLattice.getAllChunks().map(($)=>$.serialize()),this._world.loop.currentTick)),X.push(X0.createPacket(X0.outboundPackets.entitiesPacketDefinition,this._world.entityManager.getAllEntities().map(($)=>{if(J.camera.attachedToEntity===void 0&&$ instanceof o7&&$.player===J)J.camera.setAttachedToEntity($);return $.serialize()}),this._world.loop.currentTick)),X.push(X0.createPacket(X0.outboundPackets.audiosPacketDefinition,this._world.audioManager.getAllAudios().map(($)=>$.serialize()),this._world.loop.currentTick)),X.push(X0.createPacket(X0.outboundPackets.lightsPacketDefinition,this._world.lightManager.getAllLights().map(($)=>$.serialize()),this._world.loop.currentTick)),X.push(X0.createPacket(X0.outboundPackets.sceneUIsPacketDefinition,this._world.sceneUIManager.getAllSceneUIs().map(($)=>$.serialize()),this._world.loop.currentTick)),X.push(X0.createPacket(X0.outboundPackets.playersPacketDefinition,Y9.instance.getConnectedPlayers().map(($)=>$.serialize()),this._world.loop.currentTick));let Y=this._createOrGetQueuedPlayerCameraSync(J.camera);this._queuedPerPlayerCameraSynchronizations.set(J,{...J.camera.serialize(),...Y}),this._queuedPerPlayerSynchronizations.set(J,X),this._queuedPlayerSynchronizations[J.id]=J.serialize()};_onPlayerLeftWorld=(Z)=>{let J=this._createOrGetQueuedPlayerSync(Z.player);J.rm=!0};_onPlayerReconnectedWorld=(Z)=>{this._onPlayerJoinedWorld(Z)};_onPlayerRequestSync=(Z)=>{Z.player.connection.send([X0.createPacket(X0.outboundPackets.syncResponsePacketDefinition,{r:Z.receivedAt,s:Date.now(),p:performance.now()-Z.receivedAtMs,n:this._world.loop.nextTickMs},this._world.loop.currentTick)])};_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[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):void 0};_onSceneUISetPosition=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.p=Z.position?p0.serializeVector(Z.position):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))delete this._queuedSceneUISynchronizations[J.i],this._loadedSceneUIs.delete(J.i);else J.rm=!0};_onSimulationDebugRaycast=(Z)=>{this._queuedDebugRaycastSynchronizations.push(p0.serializePhysicsDebugRaycast(Z))};_onSimulationDebugRender=(Z)=>{this._queuedBroadcasts.push(X0.createPacket(X0.outboundPackets.physicsDebugRenderPacketDefinition,{v:Array.from(Z.vertices),c:Array.from(Z.colors)},this._world.loop.currentTick))};_onWorldSetAmbientLightColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.ac=p0.serializeRgbColor(Z.color)};_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)};_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)};_onWorldSetSkyboxIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.si=Z.intensity};_createOrGetQueuedAudioSync(Z){if(Z.id===void 0)u.fatalError("NetworkSynchronizer._createOrGetQueuedAudioSync(): Audio has no id!");return this._queuedAudioSynchronizations[Z.id]??={i:Z.id}}_createOrGetQueuedBlockSync(Z){let{x:J,y:X,z:Y}=Z;return this._queuedBlockSynchronizations[`${J},${X},${Y}`]??={i:0,c:[J,X,Y]}}_createOrGetQueuedChunkSync(Z){if(!Z.originCoordinate)u.fatalError("NetworkSynchronizer._createOrGetQueuedChunkSync(): Chunk has no origin coordinate!");let{x:J,y:X,z:Y}=Z.originCoordinate;return this._queuedChunkSynchronizations[`${J},${X},${Y}`]??={c:[J,X,Y]}}_createOrGetQueuedEntitySync(Z){if(Z.id===void 0)u.fatalError("NetworkSynchronizer._createOrGetQueuedEntitySync(): Entity has no id!");return this._queuedEntitySynchronizations[Z.id]??={i:Z.id}}_createOrGetQueuedLightSync(Z){if(Z.id===void 0)u.fatalError("NetworkSynchronizer._createOrGetQueuedLightSync(): Light has no id!");return this._queuedLightSynchronizations[Z.id]??={i:Z.id}}_createOrGetQueuedPlayerSync(Z){if(Z.id===void 0)u.fatalError("NetworkSynchronizer._createOrGetQueuedPlayerSync(): Player has no id!");return this._queuedPlayerSynchronizations[Z.id]??={i:Z.id}}_createOrGetQueuedPlayerCameraSync(Z){let J=this._queuedPerPlayerCameraSynchronizations.get(Z.player);if(!J)J={},this._queuedPerPlayerCameraSynchronizations.set(Z.player,J);return J}_createOrGetQueuedPlayerUISync(Z){let J=this._queuedPerPlayerUISynchronizations.get(Z.player);if(!J)J={},this._queuedPerPlayerUISynchronizations.set(Z.player,J);return J}_createOrGetQueuedPlayerUIDatasSync(Z){let J=this._queuedPerPlayerUIDatasSynchronizations.get(Z.player);if(!J)J=[],this._queuedPerPlayerUIDatasSynchronizations.set(Z.player,J);return J}_createOrGetQueuedSceneUISync(Z){if(Z.id===void 0)u.fatalError("NetworkSynchronizer._createOrGetQueuedSceneUISync(): SceneUI has no id!");return this._queuedSceneUISynchronizations[Z.id]??={i:Z.id}}_createOrGetQueuedWorldSync(Z){if(Z.id!==this._world.id)u.fatalError("NetworkSynchronizer._createOrGetQueuedWorldSync(): World does not match this network synchronizer world!");return this._queuedWorldSynchronization??={i:Z.id}}_createOrGetSynchronizedPlayerReliablePackets(Z,J){let X=this._synchronizedPlayerReliablePackets.get(Z);if(!X)X=[...J],this._synchronizedPlayerReliablePackets.set(Z,X);return X}}class Uq{_sceneUIs=new Map;_nextSceneUIId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}getAllSceneUIs(){return 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)}}var QJ6=2,KJ6=3;class Lq{_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*KJ6,this._tickFunction=J,this._tickErrorCallback=X}get targetTicksPerSecond(){return this._targetTicksPerSecond}get fixedTimestepMs(){return this._fixedTimestepMs}get fixedTimestepS(){return this._fixedTimestepS}get nextTickMs(){return this._nextTickMs}start(){if(this._tickHandle)return u.warning("Ticker.start(): ticker already running.");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)X8.startSpan({operation:"ticker_tick"},()=>{let Y=0;while(this._accumulatorMs>=this._fixedTimestepMs&&Y<QJ6)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 u.warning("Ticker.stop(): ticker not running.");clearTimeout(this._tickHandle),this._tickHandle=null}_tick(Z){try{this._tickFunction(Z)}catch(J){if(J instanceof Error&&this._tickErrorCallback)this._tickErrorCallback(J);else u.warning(`Ticker._tick(): tick callback threw an error, but it was not an instance of Error. Error: ${J}`)}}}var QK1;((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"})(QK1||={});class Bq extends g0{_currentTick=0;_ticker;_world;constructor(Z,J=Sy){super();this._ticker=new Lq(J,this._tick,this._onTickError),this._world=Z}get currentTick(){return this._currentTick}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();X8.startSpan({operation:"world_tick",attributes:{serverPlayerCount:Y9.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}},()=>{X8.startSpan({operation:"chunks_update"},()=>this._world.chunkLattice.updateChunks()),X8.startSpan({operation:"entities_tick"},()=>this._world.entityManager.tickEntities(Z)),X8.startSpan({operation:"simulation_step"},()=>this._world.simulation.step(Z)),X8.startSpan({operation:"entities_emit_updates"},()=>this._world.entityManager.checkAndEmitUpdates()),X8.startSpan({operation:"network_synchronize"},()=>this._world.networkSynchronizer.synchronize())}),this._currentTick++,this.emitWithWorld(this._world,"WORLD_LOOP.TICK_END",{worldLoop:this,tickDurationMs:performance.now()-J})};_onTickError=(Z)=>{u.error(`WorldLoop._onTickError(): Error: ${Z}`),this.emitWithWorld(this._world,"WORLD_LOOP.TICK_ERROR",{worldLoop:this,error:Z})}}var xy;((G)=>{G.SET_AMBIENT_LIGHT_COLOR="WORLD.SET_AMBIENT_LIGHT_COLOR";G.SET_AMBIENT_LIGHT_INTENSITY="WORLD.SET_AMBIENT_LIGHT_INTENSITY";G.SET_DIRECTIONAL_LIGHT_COLOR="WORLD.SET_DIRECTIONAL_LIGHT_COLOR";G.SET_DIRECTIONAL_LIGHT_INTENSITY="WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY";G.SET_DIRECTIONAL_LIGHT_POSITION="WORLD.SET_DIRECTIONAL_LIGHT_POSITION";G.SET_SKYBOX_INTENSITY="WORLD.SET_SKYBOX_INTENSITY";G.START="WORLD.START";G.STOP="WORLD.STOP"})(xy||={});class wq extends g0{_id;_ambientLightColor;_ambientLightIntensity;_directionalLightColor;_directionalLightIntensity;_directionalLightPosition;_name;_skyboxIntensity;_skyboxUri;_audioManager;_blockTypeRegistry;_chatManager;_chunkLattice;_entityManager;_lightManager;_loop;_networkSynchronizer;_sceneUIManager;_simulation;_tag;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._name=Z.name,this._skyboxIntensity=Z.skyboxIntensity??1,this._skyboxUri=Z.skyboxUri,this._tag=Z.tag,this._audioManager=new uG(this),this._blockTypeRegistry=new xV(this),this._chatManager=new Oq(this),this._chunkLattice=new Yq(this),this._entityManager=new Wq(this),this._lightManager=new Gq(this),this._loop=new Bq(this,Z.tickRate),this._networkSynchronizer=new SR(this),this._sceneUIManager=new Uq(this),this._simulation=new qq(this,Z.tickRate,Z.gravity),Z.map)this.loadMap(Z.map)}get id(){return this._id}get ambientLightColor(){return this._ambientLightColor}get ambientLightIntensity(){return this._ambientLightIntensity}get directionalLightColor(){return this._directionalLightColor}get directionalLightIntensity(){return this._directionalLightIntensity}get directionalLightPosition(){return this._directionalLightPosition}get name(){return this._name}get skyboxIntensity(){return this._skyboxIntensity}get skyboxUri(){return this._skyboxUri}get audioManager(){return this._audioManager}get tag(){return this._tag}get blockTypeRegistry(){return this._blockTypeRegistry}get chatManager(){return this._chatManager}get chunkLattice(){return this._chunkLattice}get entityManager(){return this._entityManager}get lightManager(){return this._lightManager}get loop(){return this._loop}get networkSynchronizer(){return this._networkSynchronizer}get sceneUIManager(){return this._sceneUIManager}get simulation(){return this._simulation}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(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})}setSkyboxIntensity(Z){this._skyboxIntensity=Z,this.emit("WORLD.SET_SKYBOX_INTENSITY",{world:this,intensity:Z})}start(){this._loop.start(),this.emit("WORLD.START",{world:this,startedAtMs:Date.now()})}stop(){this._loop.stop(),this.emit("WORLD.STOP",{world:this,stoppedAtMs:Date.now()})}serialize(){return p0.serializeWorld(this)}}var KK1;((J)=>J.WORLD_CREATED="WORLD_MANAGER.WORLD_CREATED")(KK1||={});class fG{static instance=new fG;_defaultWorld;_nextWorldId=1;_worlds=new Map;createWorld(Z){let J=new wq({...Z,id:this._nextWorldId++});return J.start(),this._worlds.set(J.id,J),F6.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}}Buffer.poolSize=67108864;var GK1;((X)=>{X.START="GAMESERVER.START";X.STOP="GAMESERVER.STOP"})(GK1||={});function WJ6(Z){WK1.default.init().then(()=>{return GJ.instance.modelRegistry.preloadModels()}).then(()=>{if(Z.length>0)Z(GJ.instance.worldManager.getDefaultWorld());else Z();GJ.instance.start()}).catch((J)=>{u.fatalError(`Failed to initialize the game engine, exiting. Error: ${J}`)})}class GJ{static _instance;_modelRegistry=_9.instance;_playerManager=Y9.instance;_socket=QX.instance;_worldManager=fG.instance;_webServer=TW.instance;constructor(){}static get instance(){if(!this._instance)this._instance=new GJ;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(){F6.emit("GAMESERVER.START",{startedAtMs:performance.now()}),this._webServer.start()}}class jQ{static instance=new jQ;constructor(){}async getGlobalData(Z){let J=await I7.instance.getData(Z);if(!J||J.error){if(J?.error)u.warning(`PersistenceManager.getGlobalData(): ${J.error.message}`);return}return J}async getPlayerData(Z){let J=await I7.instance.getData(this._getPlayerKey(Z));if(!J||J.error){if(J?.error)u.warning(`PersistenceManager.getPlayerData(): ${J.error.message}`);return}return J}async setGlobalData(Z,J){let X=await I7.instance.setData(Z,J);if(!X||X.error){if(X?.error)u.warning(`PersistenceManager.setGlobalData(): ${X.error.message}`);return}return X}async setPlayerData(Z,J){let X=await I7.instance.setData(this._getPlayerKey(Z),J);if(!X||X.error){if(X?.error)u.warning(`PersistenceManager.setPlayerData(): ${X.error.message}`);return}return X}_getPlayerKey(Z){return`player-${Z.id}`}}var VK1=["w","a","s","d","sp","sh","tb","ml","mr","q","e","r","f","z","x","c","v","1","2","3","4","5","6","7","8","9","0"],Kq;((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"})(Kq||={});class xG extends g0{static _devNextPlayerId=1;id;username;profilePictureUrl;camera;connection;ui;_input={};_lastUnreliableInputSequenceNumber=0;_world;constructor(Z,J){super();this.id=J?.user.id??`player-${xG._devNextPlayerId++}`,this.username=J?.user.username??this.id,this.profilePictureUrl=J?.user.profilePictureURL??void 0,this.camera=new Vq(this),this.connection=Z,this.ui=new Hq(this),Z.onPacket(X0.PacketId.CHAT_MESSAGE_SEND,this._onChatMessageSendPacket),Z.onPacket(X0.PacketId.DEBUG_CONFIG,this._onDebugConfigPacket),Z.onPacket(X0.PacketId.INPUT,this._onInputPacket),Z.onPacket(X0.PacketId.SYNC_REQUEST,this._onSyncRequestPacket),Z.onPacket(X0.PacketId.UI_DATA_SEND,this._onUIDataSendPacket),this.joinWorld(GJ.instance.worldManager.getDefaultWorld())}get input(){return this._input}get world(){return this._world}disconnect(){this._leaveWorld(),this.connection.disconnect()}async getPersistedData(){return jQ.instance.getPlayerData(this)}joinWorld(Z){if(this._world)this.disconnect();this._world=Z,this.emitWithWorld(this._world,"PLAYER.JOINED_WORLD",{player:this,world:this._world})}reconnect(){if(!this._world)return;this._lastUnreliableInputSequenceNumber=0,this.emitWithWorld(this._world,"PLAYER.RECONNECTED_WORLD",{player:this,world:this._world})}resetInputs(){this._input={}}async setPersistedData(Z){return jQ.instance.setPlayerData(this,Z)}serialize(){return p0.serializePlayer(this)}_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(VK1.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 hy;((X)=>{X.BROADCAST_MESSAGE="CHAT.BROADCAST_MESSAGE";X.PLAYER_MESSAGE="CHAT.PLAYER_MESSAGE"})(hy||={});class Oq extends g0{_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})}}class y1 extends eX{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;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.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 mG({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 u.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]},isSensor:!0,relativePosition:{x:0,y:-Z.height/2,z:0},tag:"groundSensor",onCollision:(J,X)=>{if(!Z.isSpawned)return;if(!(J instanceof t5)||!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]},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:W,c:G,sp:V,sh:H,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||W);let U=H,B=Q&&W&&!$&&!K||$&&K&&!Q&&!W;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){let D=U?this.runLoopedAnimations:this.walkLoopedAnimations;Z.stopAllModelLoopedAnimations(D),Z.startModelLoopedAnimations(D),this._stepAudio?.setPlaybackRate(U?0.75:0.51),this._stepAudio?.play(Z.world,!this._stepAudio?.isPlaying)}else if(this._isFullySubmerged){this._stepAudio?.pause();let D=this._isActivelyMoving?this.swimLoopedAnimations:this.swimIdleLoopedAnimations;Z.stopAllModelLoopedAnimations(D),Z.startModelLoopedAnimations(D)}else this._stepAudio?.pause(),Z.stopAllModelLoopedAnimations(this.idleLoopedAnimations),Z.startModelLoopedAnimations(this.idleLoopedAnimations);let L;if(this.applyDirectionalMovementRotations){if($&&Q&&!W&&!K)L=y1.MOVEMENT_ROTATIONS.wa;else if($&&W&&!Q&&!K)L=y1.MOVEMENT_ROTATIONS.wd;else if(K&&Q&&!$&&!W)L=y1.MOVEMENT_ROTATIONS.sa;else if(K&&W&&!$&&!Q)L=y1.MOVEMENT_ROTATIONS.sd;else if(K&&!$&&!Q&&!W||Q&&K&&W&&!$)L=y1.MOVEMENT_ROTATIONS.s;else if(Q&&!$&&!K&&!W)L=y1.MOVEMENT_ROTATIONS.a;else if(W&&!$&&!Q&&!K)L=y1.MOVEMENT_ROTATIONS.d}if(F)Z.startModelOneshotAnimations(this.interactOneshotAnimations),J.ml=!this.autoCancelMouseLeftClick;if(U&&this.canRun(this)||!U&&this.canWalk(this)){let D=!this.isSwimming?U?this.runVelocity:this.walkVelocity:U?this.swimFastVelocity:this.swimSlowVelocity,P=Math.sin(z),C=Math.cos(z);if($)this._reusableTargetVelocities.x-=D*P,this._reusableTargetVelocities.z-=D*C;if(K)this._reusableTargetVelocities.x+=D*P,this._reusableTargetVelocities.z+=D*C;if(Q)this._reusableTargetVelocities.x-=D*C,this._reusableTargetVelocities.z+=D*P;if(W)this._reusableTargetVelocities.x+=D*C,this._reusableTargetVelocities.z-=D*P;let T=Math.sqrt(this._reusableTargetVelocities.x*this._reusableTargetVelocities.x+this._reusableTargetVelocities.z*this._reusableTargetVelocities.z);if(T>D){let E=D/T;this._reusableTargetVelocities.x*=E,this._reusableTargetVelocities.z*=E}}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(G)this._reusableTargetVelocities.y=-this.swimUpwardVelocity;else if(performance.now()<this._justSubmergedUntil)this._reusableTargetVelocities.y=-this.swimUpwardVelocity*y1.WATER_ENTRY_SINKING_FACTOR;else if(!V)this._reusableTargetVelocities.y=-q.y*y1.SWIMMING_DRAG_FACTOR}if(V&&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 w=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 D=Math.sqrt(this._externalVelocity.x*this._externalVelocity.x+this._magnitudeYTracker*this._magnitudeYTracker+this._externalVelocity.z*this._externalVelocity.z);if(D>0.01){let C=Math.max(0,D-y1.EXTERNAL_IMPULSE_DECAY_RATE)/D;this._externalVelocity.x*=C,this._magnitudeYTracker*=C,this._externalVelocity.z*=C}else this._externalVelocity.x=0,this._externalVelocity.y=0,this._magnitudeYTracker=0,this._externalVelocity.z=0}}let j=this._reusableTargetVelocities.x+this._externalVelocity.x-q.x+w.x,N=this._reusableTargetVelocities.y+this._externalVelocity.y+w.y,R=this._reusableTargetVelocities.z+this._externalVelocity.z-q.z+w.z;if(this._externalVelocity.y=0,j!==0||N!==0||R!==0){let D=Z.mass;this._reusableImpulse.x=j*D,this._reusableImpulse.y=N*D,this._reusableImpulse.z=R*D,this._internalApplyImpulse(this._reusableImpulse)}if(z!==void 0){let P=(L!==void 0?z+L:z)/2;Z.setRotation({x:0,y:Math.fround(Math.sin(P)),z:0,w:Math.fround(Math.cos(P))})}}}class fy extends o7{constructor(Z){super({modelUri:"models/players/player.gltf",modelLoopedAnimations:["idle_lower","idle_upper"],...Z});if(!Z.controller)this.setController(new y1)}}var H6=r(MQ(),1);class PQ extends Float32Array{constructor(Z,J,X,Y){super([Z,J,X,Y])}get determinant(){return H6.mat2.determinant(this)}get frobeniusNorm(){return H6.mat2.frob(this)}static create(){let Z=new PQ(0,0,0,0);return H6.mat2.identity(Z),Z}static fromRotation(Z){let J=PQ.create();return H6.mat2.fromRotation(J,Z),J}static fromScaling(Z){let J=PQ.create();return H6.mat2.fromScaling(J,Z),J}add(Z){return H6.mat2.add(this,this,Z),this}adjoint(){return H6.mat2.adjoint(this,this),this}clone(){return new PQ(this[0],this[1],this[2],this[3])}copy(Z){return H6.mat2.copy(this,Z),this}equals(Z){return H6.mat2.equals(this,Z)}exactEquals(Z){return H6.mat2.exactEquals(this,Z)}identity(){return H6.mat2.identity(this),this}invert(){return H6.mat2.invert(this,this),this}multiply(Z){return H6.mat2.mul(this,this,Z),this}multiplyScalar(Z){return H6.mat2.multiplyScalar(this,this,Z),this}rotate(Z){return H6.mat2.rotate(this,this,Z),this}subtract(Z){return H6.mat2.sub(this,this,Z),this}toString(){return`[${this[0]},${this[1]}][${this[2]},${this[3]}]`}transpose(){return H6.mat2.transpose(this,this),this}}var U8=r(MQ(),1);class e7 extends Float32Array{constructor(Z,J,X,Y,$,Q,K,W,G){super([Z,J,X,Y,$,Q,K,W,G])}get determinant(){return U8.mat3.determinant(this)}get frobeniusNorm(){return U8.mat3.frob(this)}static create(){let Z=new e7(0,0,0,0,0,0,0,0,0);return U8.mat3.identity(Z),Z}static fromMatrix4(Z){let J=e7.create();return U8.mat3.fromMat4(J,Z),J}static fromQuaternion(Z){let J=e7.create();return U8.mat3.fromQuat(J,Z),J}static fromRotation(Z){let J=e7.create();return U8.mat3.fromRotation(J,Z),J}static fromScaling(Z){let J=e7.create();return U8.mat3.fromScaling(J,Z),J}static fromTranslation(Z){let J=e7.create();return U8.mat3.fromTranslation(J,Z),J}add(Z){return U8.mat3.add(this,this,Z),this}adjoint(){return U8.mat3.adjoint(this,this),this}clone(){return new e7(this[0],this[1],this[2],this[3],this[4],this[5],this[6],this[7],this[8])}copy(Z){return U8.mat3.copy(this,Z),this}equals(Z){return U8.mat3.equals(this,Z)}exactEquals(Z){return U8.mat3.exactEquals(this,Z)}identity(){return U8.mat3.identity(this),this}invert(){return U8.mat3.invert(this,this),this}multiply(Z){return U8.mat3.mul(this,this,Z),this}multiplyScalar(Z){return U8.mat3.multiplyScalar(this,this,Z),this}transformVector(Z){return Z.transformMatrix3(this)}projection(Z,J){return U8.mat3.projection(this,Z,J),this}rotate(Z){return U8.mat3.rotate(this,this,Z),this}subtract(Z){return U8.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 U8.mat3.transpose(this,this),this}}var e0=r(MQ(),1);class O5 extends Float32Array{constructor(Z,J,X,Y,$,Q,K,W,G,V,H,F,z,q,U,B){super([Z,J,X,Y,$,Q,K,W,G,V,H,F,z,q,U,B])}get determinant(){return e0.mat4.determinant(this)}get frobeniusNorm(){return e0.mat4.frob(this)}static create(){let Z=new O5(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return e0.mat4.identity(Z),Z}static fromQuaternion(Z){let J=O5.create();return e0.mat4.fromQuat(J,Z),J}static fromRotation(Z,J){let X=O5.create();return e0.mat4.fromRotation(X,Z,J),X}static fromRotationTranslation(Z,J){let X=O5.create();return e0.mat4.fromRotationTranslation(X,Z,J),X}static fromRotationTranslationScale(Z,J,X){let Y=O5.create();return e0.mat4.fromRotationTranslationScale(Y,Z,J,X),Y}static fromRotationTranslationScaleOrigin(Z,J,X,Y){let $=O5.create();return e0.mat4.fromRotationTranslationScaleOrigin($,Z,J,X,Y),$}static fromScaling(Z){let J=O5.create();return e0.mat4.fromScaling(J,Z),J}static fromTranslation(Z){let J=O5.create();return e0.mat4.fromTranslation(J,Z),J}static fromXRotation(Z){let J=O5.create();return e0.mat4.fromXRotation(J,Z),J}static fromYRotation(Z){let J=O5.create();return e0.mat4.fromYRotation(J,Z),J}static fromZRotation(Z){let J=O5.create();return e0.mat4.fromZRotation(J,Z),J}add(Z){return e0.mat4.add(this,this,Z),this}adjoint(){return e0.mat4.adjoint(this,this),this}clone(){return new O5(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 e0.mat4.copy(this,Z),this}equals(Z){return e0.mat4.equals(this,Z)}exactEquals(Z){return e0.mat4.exactEquals(this,Z)}frustrum(Z,J,X,Y,$,Q){return e0.mat4.frustum(this,Z,J,X,Y,$,Q),this}identity(){return e0.mat4.identity(this),this}invert(){return e0.mat4.invert(this,this),this}lookAt(Z,J,X){return e0.mat4.lookAt(this,Z,J,X),this}multiply(Z){return e0.mat4.mul(this,this,Z),this}multiplyScalar(Z){return e0.mat4.multiplyScalar(this,this,Z),this}orthographic(Z,J,X,Y,$,Q){return e0.mat4.ortho(this,Z,J,X,Y,$,Q),this}perspective(Z,J,X,Y){return e0.mat4.perspective(this,Z,J,X,Y),this}rotate(Z,J){return e0.mat4.rotate(this,this,Z,J),this}rotateX(Z){return e0.mat4.rotateX(this,this,Z),this}rotateY(Z){return e0.mat4.rotateY(this,this,Z),this}rotateZ(Z){return e0.mat4.rotateZ(this,this,Z),this}scale(Z){return e0.mat4.scale(this,this,Z),this}subtract(Z){return e0.mat4.sub(this,this,Z),this}targetTo(Z,J,X){return e0.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 e0.mat4.translate(this,this,Z),this}transpose(){return e0.mat4.transpose(this,this),this}}var A1=r(MQ(),1);class yG extends Float32Array{constructor(Z,J,X,Y){super([Z,J,X,Y])}get length(){return A1.quat.length(this)}get squaredLength(){return A1.quat.squaredLength(this)}get magnitude(){return A1.quat.length(this)}get squaredMagnitude(){return A1.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=A1.quat.fromEuler(new Float32Array(4),Z,J,X);return new yG(Y[0],Y[1],Y[2],Y[3])}static fromQuaternionLike(Z){return new yG(Z.x,Z.y,Z.z,Z.w)}clone(){return new yG(this.x,this.y,this.z,this.w)}conjugate(){return A1.quat.conjugate(this,this),this}copy(Z){return A1.quat.copy(this,Z),this}dot(Z){return A1.quat.dot(this,Z)}exponential(){return A1.quat.exp(this,this),this}equals(Z){return A1.quat.equals(this,Z)}exactEquals(Z){return A1.quat.exactEquals(this,Z)}getAngle(Z){return A1.quat.getAngle(this,Z)}identity(){return A1.quat.identity(this),this}invert(){return A1.quat.invert(this,this),this}lerp(Z,J){return A1.quat.lerp(this,this,Z,J),this}logarithm(){return A1.quat.ln(this,this),this}multiply(Z){return A1.quat.multiply(this,this,Z),this}transformVector(Z){return Z.transformQuaternion(this)}normalize(){return A1.quat.normalize(this,this),this}power(Z){return A1.quat.pow(this,this,Z),this}randomize(){return A1.quat.random(this),this}rotateX(Z){return A1.quat.rotateX(this,this,Z),this}rotateY(Z){return A1.quat.rotateY(this,this,Z),this}rotateZ(Z){return A1.quat.rotateZ(this,this,Z),this}scale(Z){return A1.quat.scale(this,this,Z),this}setAxisAngle(Z,J){return A1.quat.setAxisAngle(this,Z,J),this}slerp(Z,J){return A1.quat.slerp(this,this,Z,J),this}toString(){return`${this.x},${this.y},${this.z},${this.w}`}}var H1=r(MQ(),1);class jq extends Float32Array{constructor(Z,J){super([Z,J])}get length(){return H1.vec2.length(this)}get squaredLength(){return H1.vec2.squaredLength(this)}get magnitude(){return H1.vec2.length(this)}get squaredMagnitude(){return H1.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 jq(0,0)}add(Z){return H1.vec2.add(this,this,Z),this}angle(Z){return H1.vec2.angle(this,Z)}ceil(){return H1.vec2.ceil(this,this),this}clone(){return new jq(this.x,this.y)}copy(Z){return H1.vec2.copy(this,Z),this}distance(Z){return H1.vec2.distance(this,Z)}divide(Z){return H1.vec2.divide(this,this,Z),this}dot(Z){return H1.vec2.dot(this,Z)}equals(Z){return H1.vec2.equals(this,Z)}exactEquals(Z){return H1.vec2.exactEquals(this,Z)}floor(){return H1.vec2.floor(this,this),this}invert(){return H1.vec2.inverse(this,this),this}lerp(Z,J){return H1.vec2.lerp(this,this,Z,J),this}max(Z){return H1.vec2.max(this,this,Z),this}min(Z){return H1.vec2.min(this,this,Z),this}multiply(Z){return H1.vec2.mul(this,this,Z),this}negate(){return H1.vec2.negate(this,this),this}normalize(){return H1.vec2.normalize(this,this),this}randomize(Z){return H1.vec2.random(this,Z),this}rotate(Z,J){return H1.vec2.rotate(this,this,Z,J),this}round(){return H1.vec2.round(this,this),this}scale(Z){return H1.vec2.scale(this,this,Z),this}scaleAndAdd(Z,J){return H1.vec2.scaleAndAdd(this,this,Z,J),this}subtract(Z){return H1.vec2.sub(this,this,Z),this}toString(){return`${this.x},${this.y}`}transformMatrix2(Z){return H1.vec2.transformMat2(this,this,Z),this}transformMatrix3(Z){return H1.vec2.transformMat3(this,this,Z),this}transformMatrix4(Z){return H1.vec2.transformMat4(this,this,Z),this}zero(){return H1.vec2.zero(this),this}}var $1=r(MQ(),1);class bG extends Float32Array{constructor(Z,J,X){super([Z,J,X])}get length(){return $1.vec3.length(this)}get squaredLength(){return $1.vec3.squaredLength(this)}get magnitude(){return $1.vec3.length(this)}get squaredMagnitude(){return $1.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 bG(0,0,0)}static fromVector3Like(Z){return new bG(Z.x,Z.y,Z.z)}add(Z){return $1.vec3.add(this,this,Z),this}ceil(){return $1.vec3.ceil(this,this),this}clone(){return new bG(this.x,this.y,this.z)}copy(Z){return $1.vec3.copy(this,Z),this}cross(Z){return $1.vec3.cross(this,this,Z),this}distance(Z){return $1.vec3.distance(this,Z)}divide(Z){return $1.vec3.div(this,this,Z),this}dot(Z){return $1.vec3.dot(this,Z)}equals(Z){return $1.vec3.equals(this,Z)}exactEquals(Z){return $1.vec3.exactEquals(this,Z)}floor(){return $1.vec3.floor(this,this),this}invert(){return $1.vec3.inverse(this,this),this}lerp(Z,J){return $1.vec3.lerp(this,this,Z,J),this}max(Z){return $1.vec3.max(this,this,Z),this}min(Z){return $1.vec3.min(this,this,Z),this}multiply(Z){return $1.vec3.mul(this,this,Z),this}negate(){return $1.vec3.negate(this,this),this}normalize(){return $1.vec3.normalize(this,this),this}randomize(Z){return $1.vec3.random(this,Z),this}rotateX(Z,J){return $1.vec3.rotateX(this,this,Z,J),this}rotateY(Z,J){return $1.vec3.rotateY(this,this,Z,J),this}rotateZ(Z,J){return $1.vec3.rotateZ(this,this,Z,J),this}round(){return $1.vec3.round(this,this),this}scale(Z){return $1.vec3.scale(this,this,Z),this}scaleAndAdd(Z,J){return $1.vec3.scaleAndAdd(this,this,Z,J),this}subtract(Z){return $1.vec3.sub(this,this,Z),this}toString(){return`${this.x},${this.y},${this.z}`}transformMatrix3(Z){return $1.vec3.transformMat3(this,this,Z),this}transformMatrix4(Z){return $1.vec3.transformMat4(this,this,Z),this}transformQuaternion(Z){return $1.vec3.transformQuat(this,this,Z),this}zero(){return $1.vec3.zero(this),this}}var oW1=r(sW1(),1);class Nq extends eX{faceSpeed=0;idleLoopedAnimations=[];idleLoopedAnimationsSpeed;jumpOneshotAnimations=[];moveLoopedAnimations=[];moveLoopedAnimationsSpeed;moveSpeed=0;_faceTarget;_jumpHeight=0;_moveTarget;_moveIgnoreAxes={};_moveStartMoveAnimations=!1;_moveStartIdleAnimationsOnCompletion=!0;_onFace;_onFaceComplete;_onMove;_onMoveComplete;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._moveTarget=Z,this._moveIgnoreAxes=X?.moveIgnoreAxes??{},this._moveStartIdleAnimationsOnCompletion=X?.moveStartIdleAnimationsOnCompletion??!0,this._moveStartMoveAnimations=!0,this._onMove=X?.moveCallback,this._onMoveComplete=X?.moveCompleteCallback}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;if(Q>0.1){let K=Math.sqrt(Q),W=this.moveSpeed*X,V=Math.min(K,W)/K,H={x:Y.x+$.x*V,y:Y.y+$.y*V,z:Y.z+$.z*V};if(Z.setPosition(H),this._onMove)this._onMove(H,this._moveTarget)}else{if(this._moveTarget=void 0,this._moveStartIdleAnimationsOnCompletion)this._startIdleAnimations(Z);if(this._onMoveComplete){let K=this._onMoveComplete;this._onMove=void 0,this._onMoveComplete=void 0,K(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,W=Math.atan2(2*(K.w*K.y),1-2*(K.y*K.y)),G=Q-W;while(G>Math.PI)G-=2*Math.PI;while(G<-Math.PI)G+=2*Math.PI;if(Math.abs(G)>0.01){let V=this.faceSpeed*X,H=Math.abs(G)<V?G:Math.sign(G)*V,z=(W+H)/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._onFaceComplete){let V=this._onFaceComplete;this._onFaceComplete=void 0,V(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 py extends Nq{_debug=!1;_entity;_maxFall=0;_maxJump=0;_maxOpenSetIterations=200;_onPathfindAbort;_onPathfindComplete;_onWaypointMoveComplete;_onWaypointMoveSkipped;_speed=0;_target;_verticalPenalty=0;_waypoints=[];_waypointNextIndex=0;_waypointTimeoutMs=2000;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._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}tick(Z,J){super.tick(Z,J)}_calculatePath(){if(!this._target||!this._entity?.world)return u.error("PathfindingEntityController._calculatePath: No target or world"),!1;let Z=this._entity.height,J=this._findGroundedStart();if(!J){if(this._debug)u.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 W=this._coordinateToKey(J),G=new Map,V=new Map([[W,0]]),H=new Map([[W,this._pathfindingHeuristic(J,X)]]),F=new Set,z=new oW1.Heap((N,R)=>{let D=H.get(N[0])??1/0,P=H.get(R[0])??1/0;return D-P});z.push([W,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 N=this._maxJump;N>=this._maxFall;N--){if(N===0)continue;let R=Math.abs(J.y+N-X.y);U.push({y:N,distanceToTargetY:R})}U.sort((N,R)=>N.distanceToTargetY-R.distanceToTargetY);let B=[...q,...U.flatMap(({y:N})=>q.map((R)=>({...R,y:N})))],L=0,w=Math.abs(X.x-J.x)+Math.abs(X.y-J.y)+Math.abs(X.z-J.z),j=Math.min(this._maxOpenSetIterations,w*20);while(!z.isEmpty()&&L<j){L++;let[N,R]=z.pop();if(R.x===X.x&&R.y===X.y&&R.z===X.z){let C=this._reconstructPath(G,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(N);let D=V.get(N),P=new Map;for(let C of B){let T=`${C.x},${C.z}`,E=C.y<0;if(E&&P.has(T))continue;let A={x:R.x+C.x,y:R.y+C.y,z:R.z+C.z};if(Math.abs(X.x-A.x)+Math.abs(X.y-A.y)+Math.abs(X.z-A.z)>w*1.5)continue;let x=this._coordinateToKey(A);if(F.has(x))continue;let I=this._isNeighborCoordinateBlocked(R,A,this._entity.height);if(E&&I){P.set(T,!0);continue}if(I)continue;let _=Math.abs(C.x),y=Math.abs(C.y),p=Math.abs(C.z),n=y===0?0:this._verticalPenalty,o=(Math.max(_,y,p)===1&&_+y+p>1?1.4:1)+n,J0=D+o,Q0=V.get(x)??1/0;if(J0>=Q0)continue;G.set(x,R),V.set(x,J0);let D0=J0+this._pathfindingHeuristic(A,X);H.set(x,D0),z.push([x,A])}}if(L>=j){if(this._onPathfindAbort?.(),this._debug)u.warning(`PathfindingEntityController._calculatePath: Maximum open set iterations reached (${j}), path search aborted. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`)}else if(this._debug)u.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*$),W=Z.x+0.5,G=Z.z+0.5,V=J.x+0.5,H=J.z+0.5,F=V-W,z=H-G,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,{moveStartIdleAnimationsOnCompletion:this._waypointNextIndex===this._waypoints.length-1,moveIgnoreAxes:{y:this._entity.isDynamic},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),W=Math.floor(Z.x),G=Math.floor(Z.z);if(!Y.chunkLattice.hasBlock({x:$,y:Q-1,z:K}))return!0;for(let V=0;V<X;V++)if(Y.chunkLattice.hasBlock({x:$,y:Q+V,z:K}))return!0;if($!==W&&K!==G)for(let V=0;V<X;V++){let H=Y.chunkLattice.hasBlock({x:$,y:Q+V,z:G}),F=Y.chunkLattice.hasBlock({x:W,y:Q+V,z:K});if(H||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{WJ6 as startServer,KK1 as WorldManagerEvent,fG as WorldManager,QK1 as WorldLoopEvent,Bq as WorldLoop,xy as WorldEvent,wq as World,zv as WebServerEvent,TW as WebServer,bG as Vector3,jq as Vector2,Lq as Ticker,Ay as SimulationEvent,qq as Simulation,Nq as SimpleEntityController,Uq as SceneUIManager,ky as SceneUIEvent,Qq as SceneUI,VK1 as SUPPORTED_INPUT_KEYS,SV as RigidBodyType,dY as RigidBody,XK1 as ROTATION_UPDATE_THRESHOLD,yG as Quaternion,vR as PlayerUIEvent,Hq as PlayerUI,tQ1 as PlayerManagerEvent,Y9 as PlayerManager,Kq as PlayerEvent,o7 as PlayerEntity,$K1 as PlayerCameraMode,vy as PlayerCameraEvent,Vq as PlayerCamera,xG as Player,jQ as PersistenceManager,py as PathfindingEntityController,JK1 as POSITION_UPDATE_THRESHOLD_SQ,Vv as PORT,_9 as ModelRegistry,O5 as Matrix4,e7 as Matrix3,PQ as Matrix2,YK1 as LightType,Gq as LightManager,Iy as LightEvent,_y as Light,GK1 as GameServerEvent,GJ as GameServer,g0 as EventRouter,u as ErrorHandler,Wq as EntityManager,$q as EntityEvent,i8 as Entity,y1 as DefaultPlayerEntityController,fy as DefaultPlayerEntity,ZK1 as DEFAULT_ENTITY_RIGID_BODY_OPTIONS,H4 as CollisionGroupsBuilder,KY as CollisionGroup,AV as ColliderShape,zq as ColliderMap,r5 as Collider,yT as CoefficientCombineRule,Yq as ChunkLattice,Ey as ChunkEvent,u6 as Chunk,Oq as ChatManager,hy as ChatEvent,gT as BlockTypeRegistryEvent,xV as BlockTypeRegistry,bT as BlockTypeEvent,t5 as BlockType,TQ as Block,ty as BaseEntityControllerEvent,eX as BaseEntityController,uG as AudioManager,sR as AudioEvent,mG as Audio};