hytopia 0.14.0 → 0.14.1

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.
Files changed (27) hide show
  1. package/README.md +1 -1
  2. package/client-docs/client.hytopiaui.camerafar.md +13 -0
  3. package/client-docs/client.hytopiaui.cameranear.md +13 -0
  4. package/client-docs/client.hytopiaui.filterprofanity.md +56 -0
  5. package/client-docs/client.hytopiaui.getsceneuitemplaterenderer.md +56 -0
  6. package/client-docs/client.hytopiaui.gltfloader.md +13 -0
  7. package/client-docs/client.hytopiaui.hasprofanity.md +56 -0
  8. package/client-docs/client.hytopiaui.hassceneuitemplaterenderer.md +56 -0
  9. package/client-docs/client.hytopiaui.ismobile.md +13 -0
  10. package/client-docs/client.hytopiaui.lockpointer.md +70 -0
  11. package/client-docs/client.hytopiaui.md +374 -0
  12. package/client-docs/client.hytopiaui.offalldata.md +17 -0
  13. package/client-docs/client.hytopiaui.offdata.md +54 -0
  14. package/client-docs/client.hytopiaui.ondata.md +54 -0
  15. package/client-docs/client.hytopiaui.pressinput.md +70 -0
  16. package/client-docs/client.hytopiaui.registersceneuitemplate.md +70 -0
  17. package/client-docs/client.hytopiaui.senddata.md +54 -0
  18. package/client-docs/client.hytopiaui.setentitycolorcorrection.md +74 -0
  19. package/client-docs/client.hytopiaui.setmousesensitivitymultiplier.md +54 -0
  20. package/client-docs/client.hytopiaui.three.md +13 -0
  21. package/client-docs/client.hytopiaui.unregisterloadedsceneuitemplates.md +17 -0
  22. package/client-docs/client.hytopiaui.unregistersceneuitemplate.md +54 -0
  23. package/client-docs/client.md +58 -0
  24. package/client-docs/client.templaterenderer.md +13 -0
  25. package/client-docs/index.md +30 -0
  26. package/package.json +1 -1
  27. package/server.mjs +1 -1
package/server.mjs CHANGED
@@ -551,4 +551,4 @@ wzUfQXDpZndkqxHilERgvPXLEsTTCMF/W+C8gsO9AoGAZWt+CU6zQhqMBB5MMGZf
551
551
  UE5WUS/oOd4jHBqwVxBTLOAPlmnQSp1uiTu2K0NrnnvZ6Zi/+tIsjbtxhomeOmnH
552
552
  +wsk9n+Bif4P7VTvwqc9FY4Ya79PEJK+J/xx/mldUEz3R63RiRXZAaDddO7yCQFX
553
553
  W8eeuIMLKU6dSq0yu22+nyU=
554
- -----END PRIVATE KEY-----`;var SC=process.env.PORT??8080,ni="0.14.0",ai;((Q)=>{Q.READY="WEBSERVER.READY";Q.STOPPED="WEBSERVER.STOPPED";Q.ERROR="WEBSERVER.ERROR";Q.UPGRADE="WEBSERVER.UPGRADE"})(ai||={});class Qz extends $1{static instance=new Qz;_webserver=IC.default();_internalHttpServer;constructor(){super();this._webserver.use(($,X,Y)=>{X.header("Access-Control-Allow-Origin","*"),Y()}),this._webserver.get("/",($,X)=>{X.json({status:"OK",version:ni,runtime:"node"})}),this._webserver.use(IC.default.static("assets",{dotfiles:"allow"}));let J=dK.instance.assetsLibraryPath;if(process.env.NODE_ENV!=="production"&&J)this._webserver.use(($,X,Y)=>{let Q=kC6.join(J,$.path);dK.instance.syncAsset(Q),Y()}),this._webserver.use(IC.default.static(J,{dotfiles:"allow"}))}start(){if(!this._internalHttpServer)this._internalHttpServer=TC6.createServer({key:EC,cert:kC},this._webserver),this._internalHttpServer.on("upgrade",this._onUpgrade),this._internalHttpServer.on("error",this._onError),this._internalHttpServer.on("close",this._onStopped);else n.warning("WebServer.start(): server already started!");this._internalHttpServer.listen(SC,this._onStarted),console.info(`WebServer.start(): Server running on port ${SC}.`)}stop(){if(this._internalHttpServer)return new Promise((J,$)=>{this._internalHttpServer.close((X)=>{if(X)$(X);else J(!0)})});else return n.warning("WebServer.stop(): server not started."),Promise.resolve(!1)}_onStarted=()=>{this.emitWithGlobal("WEBSERVER.READY",{})};_onUpgrade=(J,$,X)=>{this.emitWithGlobal("WEBSERVER.UPGRADE",{req:J,socket:$,head:X})};_onError=(J)=>{n.error(`WebServer._onError(): ${J.message}`),this.emitWithGlobal("WEBSERVER.ERROR",{error:J})};_onStopped=()=>{this.emitWithGlobal("WEBSERVER.STOPPED",{})}}var B3;((U)=>{U.BUILD_PACKETS="build_packets";U.ENTITIES_EMIT_UPDATES="entities_emit_updates";U.ENTITIES_TICK="entities_tick";U.NETWORK_SYNCHRONIZE="network_synchronize";U.NETWORK_SYNCHRONIZE_CLEANUP="network_synchronize_cleanup";U.PHYSICS_CLEANUP="physics_cleanup";U.PHYSICS_STEP="physics_step";U.SEND_ALL_PACKETS="send_all_packets";U.SEND_PACKETS="send_packets";U.SERIALIZE_FREE_BUFFERS="serialize_free_buffers";U.SERIALIZE_PACKETS="serialize_packets";U.SERIALIZE_PACKETS_ENCODE="serialize_packets_encode";U.SIMULATION_STEP="simulation_step";U.TICKER_TICK="ticker_tick";U.WORLD_TICK="world_tick"})(B3||={});class T6{static getProcessStats(J=!1){let $=process.memoryUsage(),X={jsHeapSizeMb:{value:$.heapUsed/1024/1024,unit:"megabyte"},jsHeapCapacityMb:{value:$.heapTotal/1024/1024,unit:"megabyte"},jsHeapUsagePercent:{value:$.heapUsed/$.heapTotal,unit:"percent"},processHeapSizeMb:{value:$.heapUsed/1024/1024,unit:"megabyte"},rssSizeMb:{value:$.rss/1024/1024,unit:"megabyte"}};if(J)return X;return Object.fromEntries(Object.entries(X).map(([Y,Q])=>[Y,Q.value]))}static initializeSentry(J,$=50){_P({dsn:J,release:ni,environment:process.env.NODE_ENV||"development",tracesSampleRate:1,initialScope:{tags:{gameId:process.env.HYTOPIA_GAME_ID??"unknown",gameSlug:process.env.HYTOPIA_GAME_SLUG??"unknown",lobbyId:process.env.HYTOPIA_LOBBY_ID??"unknown",region:process.env.REGION??"unknown"}},beforeSend:(X)=>{return X.extra=T6.getProcessStats(),X},beforeSendTransaction:(X)=>{if(X.contexts?.trace?.op==="ticker_tick"){let Q=X?.start_timestamp,W=X?.timestamp;if(!Q||!W)return null;if((W-Q)*1000>$)return X.measurements=T6.getProcessStats(!0),X}return null}})}static startSpan(J,$){if(nU())return h7({attributes:J.attributes,name:J.operation,op:J.operation},$);else return $()}static sentry(){return hp}}if(!gO)console.warn("Connection: msgpackr native acceleration is not enabled, using fallback implementation.");var tN1=new aZ({useFloat32:RU.ALWAYS}),IC6=5000;class v$ extends $1{static _cachedPacketsSerializedBuffer=new Map;_closeTimeout=null;_ws;_wsBinding=!1;_wt;_wtBinding=!1;_wtReliableReader;_wtReliableWriter;_wtUnreliableReader;_wtUnreliableWriter;id;constructor(J,$,X){super();this.id=TH0(),this.onPacket(_0.PacketId.HEARTBEAT,this._onHeartbeatPacket);let Y=()=>{$1.globalInstance.emit("CONNECTION.OPENED",{connection:this,session:X})};if(J)this.bindWs(J),Y();else if($)this.bindWt($).then(Y).catch((Q)=>{this._onClose(),n.error(`Connection.constructor(): Failed to bind WebTransport. Error: ${Q}`)})}static clearCachedPacketsSerializedBuffers(){if(v$._cachedPacketsSerializedBuffer.size>0)v$._cachedPacketsSerializedBuffer.clear()}static serializePackets(J){for(let X of J)if(!_0.isValidPacket(X))return n.error(`Connection.serializePackets(): Invalid packet payload: ${JSON.stringify(X)}`);let $=v$._cachedPacketsSerializedBuffer.get(J);if($)return $;return T6.startSpan({operation:"serialize_packets",attributes:{packets:J.length,packetIds:J.map((X)=>X[0]).join(",")}},(X)=>{let Y=tN1.pack(J);if(Y.byteLength>65536)Y=EC6(Y,{level:1});return X?.setAttribute("serializedBytes",Y.byteLength),v$._cachedPacketsSerializedBuffer.set(J,Y),Y})}bindWs(J){this._wsBinding=!0;let $=this._handleReconnect();if(this._cleanupConnections(),this._ws=J,this._ws.binaryType="nodebuffer",this._ws.onmessage=(X)=>this._onMessage(X.data),this._ws.onclose=this._onClose,this._ws.onerror=this._onError,this._wsBinding=!1,this._signalConnectionId(),$)this.emitWithGlobal("CONNECTION.RECONNECTED",{connection:this})}async bindWt(J){this._wtBinding=!0;let $=this._handleReconnect();this._cleanupConnections(),J.userData.onclose=this._onClose,J.closed.catch(()=>{}).finally(()=>J.userData.onclose?.()),this._wt=J,await this._wt.ready;let X=this._wt.incomingBidirectionalStreams.getReader();try{let{value:Y}=await X.read();if(Y)this._wtReliableReader=Y.readable,this._wtReliableWriter=Y.writable.getWriter()}finally{X.releaseLock()}if(this._wtUnreliableReader=this._wt.datagrams.readable,this._wtUnreliableWriter=this._wt.datagrams.createWritable().getWriter(),(async()=>{if(!this._wtReliableReader)return;let Y=this._wt,Q=_0.createPacketBufferUnframer();for await(let W of this._wtReliableReader){if(Y!==this._wt)return;for(let K of Q(W))this._onMessage(K)}})().catch(()=>this._wt?.close()),(async()=>{if(!this._wtUnreliableReader)return;let Y=this._wt;for await(let Q of this._wtUnreliableReader){if(Y!==this._wt)return;this._onMessage(Q)}})().catch(()=>this._wt?.close()),this._wtBinding=!1,this._signalConnectionId(),$)this.emitWithGlobal("CONNECTION.RECONNECTED",{connection:this})}disconnect(){try{this._ws?.close(),this._wt?.close()}catch(J){n.error(`Connection.disconnect(): Connection disconnect failed. Error: ${J}`)}}onPacket(J,$){this.on("CONNECTION.PACKET_RECEIVED",({packet:X})=>{if(X[0]===J)$(X)})}send(J,$=!0){if(this._closeTimeout||this._wsBinding||this._wtBinding)return;if(!this._ws&&!this._wt)return;let X=this._ws&&this._ws.readyState===Cq.default.OPEN,Y=this._wt&&(this._wt.state==="connected"||this._wt.state==="draining");if(!X&&!Y)return;T6.startSpan({operation:"send_packets"},()=>{try{let Q=v$.serializePackets(J);if(!Q)return;if(Y)if($)this._wtReliableWriter?.write(_0.framePacketBuffer(Q)).catch(()=>{n.error("Connection.send(): WebTransport reliable write failed, connection closing?")});else this._wtUnreliableWriter?.write(Q).catch(()=>{n.error("Connection.send(): WebTransport unreliable write failed, connection closing?")});else this._ws.send(Q);this.emitWithGlobal("CONNECTION.PACKETS_SENT",{connection:this,packets:J})}catch(Q){n.error(`Connection.send(): Packet send failed. Error: ${Q}`)}})}_onHeartbeatPacket=()=>{this.send([_0.createPacket(_0.bidirectionalPackets.heartbeatPacketDefinition,null)],!0)};_onMessage=(J)=>{try{let $=this._deserialize(J);if(!$)return;this.emitWithGlobal("CONNECTION.PACKET_RECEIVED",{connection:this,packet:$})}catch($){n.error(`Connection._ws.onmessage(): Error: ${$}`)}};_onClose=()=>{this.emitWithGlobal("CONNECTION.DISCONNECTED",{connection:this}),this._closeTimeout=setTimeout(()=>{this.emitWithGlobal("CONNECTION.CLOSED",{connection:this}),this.offAll()},IC6)};_onError=(J)=>{this.emitWithGlobal("CONNECTION.ERROR",{connection:this,error:J})};_cleanupConnections(){if(this._ws)this._ws.onmessage=()=>{},this._ws.onclose=()=>{},this._ws.onerror=()=>{};if(this._wt)this._wt.userData.onclose=()=>{};this._signalKill(),this._ws=void 0,this._wt=void 0,this._wtReliableReader=void 0,this._wtReliableWriter=void 0,this._wtUnreliableReader=void 0,this._wtUnreliableWriter=void 0}_deserialize(J){let $=tN1.unpack(J);if(!$||typeof $!=="object"||typeof $[0]!=="number")return n.error(`Connection._deserialize(): Invalid packet format. Packet: ${JSON.stringify($)}`);if(!_0.isValidPacket($))return n.error(`Connection._deserialize(): Invalid packet payload. Packet: ${JSON.stringify($)}`);return $}_handleReconnect(){let J=!!this._ws||!!this._wt;if(J&&this._closeTimeout)clearTimeout(this._closeTimeout),this._closeTimeout=null;return J}_signalConnectionId(){this.send([_0.createPacket(_0.bidirectionalPackets.connectionPacketDefinition,{i:this.id})])}_signalKill(){this.send([_0.createPacket(_0.bidirectionalPackets.connectionPacketDefinition,{k:!0})])}}class JB{_lights=new Map;_nextLightId=1;_world;constructor(J){this._world=J}get world(){return this._world}despawnEntityAttachedLights(J){this.getAllEntityAttachedLights(J).forEach(($)=>{$.despawn()})}getAllLights(){return Array.from(this._lights.values())}getAllEntityAttachedLights(J){return this.getAllLights().filter(($)=>$.attachedToEntity===J)}registerLight(J){if(J.id!==void 0)return J.id;let $=this._nextLightId;return this._lights.set($,J),this._nextLightId++,$}unregisterLight(J){if(J.id===void 0)return;this._lights.delete(J.id)}}class w5{_map=new Map;_values=[];_isDirty=!1;get size(){return this._map.size}get valuesArray(){if(this._isDirty)this._syncArray();return this._values}get(J){return this._map.get(J)}set(J,$){let X=this._map.has(J);if(this._map.set(J,$),!X)this._values.push($);else this._isDirty=!0;return this}has(J){return this._map.has(J)}delete(J){let $=this._map.delete(J);if($)this._isDirty=!0;return $}clear(){this._map.clear(),this._values.length=0,this._isDirty=!1}forEach(J,$){this._map.forEach((X,Y)=>{J.call($,X,Y,this)})}keys(){return this._map.keys()}values(){return this._map.values()}entries(){return this._map.entries()}[Symbol.iterator](){return this._map[Symbol.iterator]()}_syncArray(){this._values.length=0;for(let J of this._map.values())this._values.push(J);this._isDirty=!1}}var eN1;((X)=>{X[X.POINTLIGHT=0]="POINTLIGHT";X[X.SPOTLIGHT=1]="SPOTLIGHT"})(eN1||={});var si;((H)=>{H.DESPAWN="LIGHT.DESPAWN";H.SET_ANGLE="LIGHT.SET_ANGLE";H.SET_ATTACHED_TO_ENTITY="LIGHT.SET_ATTACHED_TO_ENTITY";H.SET_COLOR="LIGHT.SET_COLOR";H.SET_DISTANCE="LIGHT.SET_DISTANCE";H.SET_INTENSITY="LIGHT.SET_INTENSITY";H.SET_OFFSET="LIGHT.SET_OFFSET";H.SET_PENUMBRA="LIGHT.SET_PENUMBRA";H.SET_POSITION="LIGHT.SET_POSITION";H.SET_TRACKED_ENTITY="LIGHT.SET_TRACKED_ENTITY";H.SET_TRACKED_POSITION="LIGHT.SET_TRACKED_POSITION";H.SPAWN="LIGHT.SPAWN"})(si||={});class oi extends $1{_id;_angle;_attachedToEntity;_color;_distance;_intensity;_offset;_penumbra;_position;_trackedEntity;_trackedPosition;_type;_world;constructor(J){if(!!J.attachedToEntity===!!J.position)n.fatalError("Either attachedToEntity or position must be set, but not both.");super();n.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=J.angle,this._attachedToEntity=J.attachedToEntity,this._color=J.color??{r:255,g:255,b:255},this._distance=J.distance,this._intensity=J.intensity??1,this._offset=J.offset,this._penumbra=J.penumbra,this._position=J.position,this._trackedEntity=J.trackedEntity,this._trackedPosition=J.trackedPosition,this._type=J.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(J){if(this._angle===J)return;if(this._angle=J,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ANGLE",{light:this,angle:J})}setAttachedToEntity(J){if(!J.isSpawned)return n.error(`Light.setAttachedToEntity(): Entity ${J.id} is not spawned!`);if(this._attachedToEntity===J)return;if(this._attachedToEntity=J,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ATTACHED_TO_ENTITY",{light:this,entity:J})}setColor(J){if(this._color.r===J.r&&this._color.g===J.g&&this._color.b===J.b)return;if(this._color=J,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_COLOR",{light:this,color:J})}setDistance(J){if(this._distance===J)return;if(this._distance=J,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_DISTANCE",{light:this,distance:J})}setIntensity(J){if(this._intensity===J)return;if(this._intensity=J,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_INTENSITY",{light:this,intensity:J})}setOffset(J){if(this._offset&&this._offset.x===J.x&&this._offset.y===J.y&&this._offset.z===J.z)return;if(this._offset=J,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_OFFSET",{light:this,offset:J})}setPenumbra(J){if(this._penumbra===J)return;if(this._penumbra=J,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_PENUMBRA",{light:this,penumbra:J})}setPosition(J){if(this._position&&this._position.x===J.x&&this._position.y===J.y&&this._position.z===J.z)return;if(this._position=J,this._attachedToEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_POSITION",{light:this,position:J})}setTrackedEntity(J){if(!J.isSpawned)return n.error(`Light.setTrackedEntity(): Entity ${J.id} is not spawned!`);if(this._trackedEntity===J)return;if(this._trackedEntity=J,this._trackedPosition=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_ENTITY",{light:this,entity:J})}setTrackedPosition(J){if(this._trackedPosition===J)return;if(this._trackedPosition=J,this._trackedEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_POSITION",{light:this,position:J})}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(J){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return n.error(`Light.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning Light!`);this._id=J.lightManager.registerLight(this),this._world=J,this.emitWithWorld(J,"LIGHT.SPAWN",{light:this})}serialize(){return V1.serializeLight(this)}}var ri;((A)=>{A.BURST="PARTICLE_EMITTER.BURST";A.DESPAWN="PARTICLE_EMITTER.DESPAWN";A.SET_ALPHA_TEST="PARTICLE_EMITTER.SET_ALPHA_TEST";A.SET_ATTACHED_TO_ENTITY="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY";A.SET_ATTACHED_TO_ENTITY_NODE_NAME="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME";A.SET_COLOR_END="PARTICLE_EMITTER.SET_COLOR_END";A.SET_COLOR_END_VARIANCE="PARTICLE_EMITTER.SET_COLOR_END_VARIANCE";A.SET_COLOR_START="PARTICLE_EMITTER.SET_COLOR_START";A.SET_COLOR_START_VARIANCE="PARTICLE_EMITTER.SET_COLOR_START_VARIANCE";A.SET_GRAVITY="PARTICLE_EMITTER.SET_GRAVITY";A.SET_LIFETIME="PARTICLE_EMITTER.SET_LIFETIME";A.SET_LIFETIME_VARIANCE="PARTICLE_EMITTER.SET_LIFETIME_VARIANCE";A.SET_MAX_PARTICLES="PARTICLE_EMITTER.SET_MAX_PARTICLES";A.SET_OFFSET="PARTICLE_EMITTER.SET_OFFSET";A.SET_OPACITY_END="PARTICLE_EMITTER.SET_OPACITY_END";A.SET_OPACITY_END_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE";A.SET_OPACITY_START="PARTICLE_EMITTER.SET_OPACITY_START";A.SET_OPACITY_START_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE";A.SET_PAUSED="PARTICLE_EMITTER.SET_PAUSED";A.SET_POSITION="PARTICLE_EMITTER.SET_POSITION";A.SET_POSITION_VARIANCE="PARTICLE_EMITTER.SET_POSITION_VARIANCE";A.SET_RATE="PARTICLE_EMITTER.SET_RATE";A.SET_RATE_VARIANCE="PARTICLE_EMITTER.SET_RATE_VARIANCE";A.SET_SIZE_END="PARTICLE_EMITTER.SET_SIZE_END";A.SET_SIZE_END_VARIANCE="PARTICLE_EMITTER.SET_SIZE_END_VARIANCE";A.SET_SIZE_START="PARTICLE_EMITTER.SET_SIZE_START";A.SET_SIZE_START_VARIANCE="PARTICLE_EMITTER.SET_SIZE_START_VARIANCE";A.SET_TEXTURE_URI="PARTICLE_EMITTER.SET_TEXTURE_URI";A.SET_TRANSPARENT="PARTICLE_EMITTER.SET_TRANSPARENT";A.SET_VELOCITY="PARTICLE_EMITTER.SET_VELOCITY";A.SET_VELOCITY_VARIANCE="PARTICLE_EMITTER.SET_VELOCITY_VARIANCE";A.SPAWN="PARTICLE_EMITTER.SPAWN"})(ri||={});class ti extends $1{_id;_alphaTest;_attachedToEntity;_attachedToEntityNodeName;_colorEnd;_colorEndVariance;_colorStart;_colorStartVariance;_gravity;_lifetime;_lifetimeVariance;_maxParticles;_offset;_opacityEnd;_opacityEndVariance;_opacityStart;_opacityStartVariance;_paused;_position;_positionVariance;_rate;_rateVariance;_sizeEnd;_sizeEndVariance;_sizeStart;_sizeStartVariance;_sizeVariance;_textureUri;_transparent;_velocity;_velocityVariance;_world;constructor(J){if(!!J.attachedToEntity===!!J.position)n.fatalError("Either attachedToEntity or position must be set, but not both.");if(!J.textureUri)n.fatalError("ParticleEmitter.constructor(): textureUri must be provided.");super();this._alphaTest=J.alphaTest??0.05,this._attachedToEntity=J.attachedToEntity,this._attachedToEntityNodeName=J.attachedToEntityNodeName,this._colorEnd=J.colorEnd,this._colorEndVariance=J.colorEndVariance,this._colorStart=J.colorStart,this._colorStartVariance=J.colorStartVariance,this._gravity=J.gravity,this._lifetime=J.lifetime,this._lifetimeVariance=J.lifetimeVariance,this._maxParticles=J.maxParticles,this._offset=J.offset,this._opacityEnd=J.opacityEnd,this._opacityEndVariance=J.opacityEndVariance,this._opacityStart=J.opacityStart,this._opacityStartVariance=J.opacityStartVariance,this._paused=!1,this._position=J.position,this._positionVariance=J.positionVariance,this._rate=J.rate,this._rateVariance=J.rateVariance,this._sizeEnd=J.sizeEnd,this._sizeEndVariance=J.sizeEndVariance,this._sizeStart=J.sizeStart,this._sizeStartVariance=J.sizeStartVariance,this._textureUri=J.textureUri,this._transparent=J.transparent,this._velocity=J.velocity,this._velocityVariance=J.velocityVariance}get id(){return this._id}get alphaTest(){return this._alphaTest}get attachedToEntity(){return this._attachedToEntity}get attachedToEntityNodeName(){return this._attachedToEntityNodeName}get colorEnd(){return this._colorEnd}get colorEndVariance(){return this._colorEndVariance}get colorStart(){return this._colorStart}get colorStartVariance(){return this._colorStartVariance}get gravity(){return this._gravity}get isSpawned(){return this._id!==void 0}get lifetime(){return this._lifetime}get lifetimeVariance(){return this._lifetimeVariance}get maxParticles(){return this._maxParticles}get offset(){return this._offset}get opacityEnd(){return this._opacityEnd}get opacityEndVariance(){return this._opacityEndVariance}get opacityStart(){return this._opacityStart}get opacityStartVariance(){return this._opacityStartVariance}get paused(){return this._paused}get position(){return this._position}get positionVariance(){return this._positionVariance}get rate(){return this._rate}get rateVariance(){return this._rateVariance}get sizeEnd(){return this._sizeEnd}get sizeEndVariance(){return this._sizeEndVariance}get sizeStart(){return this._sizeStart}get sizeStartVariance(){return this._sizeStartVariance}get sizeVariance(){return this._sizeVariance}get textureUri(){return this._textureUri}get transparent(){return this._transparent}get velocity(){return this._velocity}get velocityVariance(){return this._velocityVariance}get world(){return this._world}setAlphaTest(J){if(this._alphaTest===J)return;if(this._alphaTest=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ALPHA_TEST",{particleEmitter:this,alphaTest:J})}setAttachedToEntity(J){if(!J.isSpawned)return n.error(`ParticleEmitter.setAttachedToEntity(): Entity ${J.id} is not spawned!`);if(this._attachedToEntity===J)return;if(this._attachedToEntity=J,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY",{particleEmitter:this,entity:J})}setAttachedToEntityNodeName(J){if(this._attachedToEntityNodeName===J)return;if(this._attachedToEntityNodeName=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME",{particleEmitter:this,attachedToEntityNodeName:J})}setColorEnd(J){if(this._colorEnd&&this._colorEnd.r===J.r&&this._colorEnd.g===J.g&&this._colorEnd.b===J.b)return;if(this._colorEnd=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_END",{particleEmitter:this,colorEnd:J})}setColorEndVariance(J){if(this._colorEndVariance&&this._colorEndVariance.r===J.r&&this._colorEndVariance.g===J.g&&this._colorEndVariance.b===J.b)return;if(this._colorEndVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_END_VARIANCE",{particleEmitter:this,colorEndVariance:J})}setColorStart(J){if(this._colorStart&&this._colorStart.r===J.r&&this._colorStart.g===J.g&&this._colorStart.b===J.b)return;if(this._colorStart=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_START",{particleEmitter:this,colorStart:J})}setColorStartVariance(J){if(this._colorStartVariance&&this._colorStartVariance.r===J.r&&this._colorStartVariance.g===J.g&&this._colorStartVariance.b===J.b)return;if(this._colorStartVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_START_VARIANCE",{particleEmitter:this,colorStartVariance:J})}setGravity(J){if(this._gravity&&this._gravity.x===J.x&&this._gravity.y===J.y&&this._gravity.z===J.z)return;if(this._gravity=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_GRAVITY",{particleEmitter:this,gravity:J})}setLifetime(J){if(this._lifetime===J)return;if(this._lifetime=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_LIFETIME",{particleEmitter:this,lifetime:J})}setLifetimeVariance(J){if(this._lifetimeVariance===J)return;if(this._lifetimeVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_LIFETIME_VARIANCE",{particleEmitter:this,lifetimeVariance:J})}setMaxParticles(J){if(this._maxParticles===J)return;if(this._maxParticles=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_MAX_PARTICLES",{particleEmitter:this,maxParticles:J})}setOffset(J){if(this._offset&&this._offset.x===J.x&&this._offset.y===J.y&&this._offset.z===J.z)return;if(this._offset=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OFFSET",{particleEmitter:this,offset:J})}setOpacityEnd(J){if(this._opacityEnd===J)return;if(this._opacityEnd=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_END",{particleEmitter:this,opacityEnd:J})}setOpacityEndVariance(J){if(this._opacityEndVariance===J)return;if(this._opacityEndVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE",{particleEmitter:this,opacityEndVariance:J})}setOpacityStart(J){if(this._opacityStart===J)return;if(this._opacityStart=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_START",{particleEmitter:this,opacityStart:J})}setOpacityStartVariance(J){if(this._opacityStartVariance===J)return;if(this._opacityStartVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE",{particleEmitter:this,opacityStartVariance:J})}setPosition(J){if(this._position&&this._position.x===J.x&&this._position.y===J.y&&this._position.z===J.z)return;if(this._position=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_POSITION",{particleEmitter:this,position:J})}setPositionVariance(J){if(this._positionVariance&&this._positionVariance.x===J.x&&this._positionVariance.y===J.y&&this._positionVariance.z===J.z)return;if(this._positionVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_POSITION_VARIANCE",{particleEmitter:this,positionVariance:J})}setRate(J){if(this._rate===J)return;if(this._rate=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_RATE",{particleEmitter:this,rate:J})}setRateVariance(J){if(this._rateVariance===J)return;if(this._rateVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_RATE_VARIANCE",{particleEmitter:this,rateVariance:J})}setSizeEnd(J){if(this._sizeEnd===J)return;if(this._sizeEnd=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_END",{particleEmitter:this,sizeEnd:J})}setSizeEndVariance(J){if(this._sizeEndVariance===J)return;if(this._sizeEndVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_END_VARIANCE",{particleEmitter:this,sizeEndVariance:J})}setSizeStart(J){if(this._sizeStart===J)return;if(this._sizeStart=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_START",{particleEmitter:this,sizeStart:J})}setSizeStartVariance(J){if(this._sizeStartVariance===J)return;if(this._sizeStartVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_START_VARIANCE",{particleEmitter:this,sizeStartVariance:J})}setTextureUri(J){if(this._textureUri===J)return;if(this._textureUri=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_TEXTURE_URI",{particleEmitter:this,textureUri:J})}setTransparent(J){if(this._transparent===J)return;if(this._transparent=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_TRANSPARENT",{particleEmitter:this,transparent:J})}setVelocity(J){if(this._velocity&&this._velocity.x===J.x&&this._velocity.y===J.y&&this._velocity.z===J.z)return;if(this._velocity=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_VELOCITY",{particleEmitter:this,velocity:J})}setVelocityVariance(J){if(this._velocityVariance&&this._velocityVariance.x===J.x&&this._velocityVariance.y===J.y&&this._velocityVariance.z===J.z)return;if(this._velocityVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_VELOCITY_VARIANCE",{particleEmitter:this,velocityVariance:J})}burst(J){if(this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.BURST",{particleEmitter:this,count:J})}despawn(){if(!this.isSpawned||!this._world)return;this._world.particleEmitterManager.unregisterParticleEmitter(this),this.emitWithWorld(this._world,"PARTICLE_EMITTER.DESPAWN",{particleEmitter:this}),this._id=void 0,this._world=void 0}restart(){if(!this._paused)return;if(this._paused=!1,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_PAUSED",{particleEmitter:this,paused:this._paused})}stop(){if(this._paused)return;if(this._paused=!0,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_PAUSED",{particleEmitter:this,paused:this._paused})}spawn(J){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return n.error(`ParticleEmitter.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning ParticleEmitter!`);this._id=J.particleEmitterManager.registerParticleEmitter(this),this._world=J,this.emitWithWorld(J,"PARTICLE_EMITTER.SPAWN",{particleEmitter:this})}serialize(){return V1.serializeParticleEmitter(this)}}var SC6={x:0,y:-32,z:0},ei=60,Jn;((Q)=>{Q.STEP_START="SIMULATION.STEP_START";Q.STEP_END="SIMULATION.STEP_END";Q.DEBUG_RAYCAST="SIMULATION.DEBUG_RAYCAST";Q.DEBUG_RENDER="SIMULATION.DEBUG_RENDER"})(Jn||={});class $B extends $1{_colliderMap=new jU;_debugRaycastingEnabled=!1;_debugRenderingEnabled=!1;_debugRenderingFilterFlags;_rapierEventQueue;_rapierSimulation;_world;constructor(J,$=ei,X=SC6){super();this._rapierEventQueue=new W8.EventQueue(!0),this._rapierSimulation=new W8.World(X),this._rapierSimulation.timestep=Math.fround(1/$),this._world=J}get colliderMap(){return this._colliderMap}get isDebugRaycastingEnabled(){return this._debugRaycastingEnabled}get isDebugRenderingEnabled(){return this._debugRenderingEnabled}get gravity(){return this._rapierSimulation.gravity}get timestepS(){return this._rapierSimulation.timestep}get world(){return this._world}createRawCollider(J,$){return this._rapierSimulation.createCollider(J,$)}createRawRigidBody(J){return this._rapierSimulation.createRigidBody(J)}enableDebugRaycasting(J){this._debugRaycastingEnabled=J}enableDebugRendering(J,$=W8.QueryFilterFlags.EXCLUDE_FIXED){this._debugRenderingEnabled=J,this._debugRenderingFilterFlags=$}getContactManifolds(J,$){let X=[];return this._rapierSimulation.narrowPhase.contactPair(J,$,(Y,Q)=>{if(Y.numContacts()===0)return;let W=Y.normal(),K=[];for(let Z=0;Z<Y.numSolverContacts();Z++)K.push(Y.solverContactPoint(Z));X.push({contactPoints:K,localNormalA:!Q?Y.localNormal1():Y.localNormal2(),localNormalB:!Q?Y.localNormal2():Y.localNormal1(),normal:!Q?W:{x:-W.x,y:-W.y,z:-W.z}})}),X}intersectionsWithRawShape(J,$,X,Y={}){let Q=new Set,W=[];return this._rapierSimulation.intersectionsWithShape($,X,J,(K)=>{let Z=this._colliderMap.getColliderHandleBlockType(K.handle);if(Z&&!Q.has(Z))return Q.add(Z),W.push({intersectedBlockType:Z}),!0;let G=this._colliderMap.getColliderHandleEntity(K.handle);if(G&&!Q.has(G))return Q.add(G),W.push({intersectedEntity:G}),!0;return!0},Y.filterFlags,Y.filterGroups,Y.filterExcludeCollider,Y.filterExcludeRigidBody,Y.filterPredicate),W}raycast(J,$,X,Y={}){let Q=new W8.Ray(J,$),W=this._rapierSimulation.castRay(Q,X,Y.solidMode??!0,Y.filterFlags,Y.filterGroups,Y.filterExcludeCollider,Y.filterExcludeRigidBody,Y.filterPredicate);if(this._debugRaycastingEnabled)this.emitWithWorld(this._world,"SIMULATION.DEBUG_RAYCAST",{simulation:this,origin:J,direction:$,length:X,hit:!!W});if(!W)return null;let K=Q.pointAt(W.timeOfImpact),Z=W.timeOfImpact,G=W.collider,V=this._colliderMap.getColliderHandleBlockType(G.handle);if(V)return{hitBlock:R3.fromGlobalCoordinate({x:Math.floor(K.x-(Q.dir.x<0?0.0001:-0.0001)),y:Math.floor(K.y-(Q.dir.y<0?0.0001:-0.0001)),z:Math.floor(K.z-(Q.dir.z<0?0.0001:-0.0001))},V),hitPoint:K,hitDistance:Z};let q=this._colliderMap.getColliderHandleEntity(G.handle);if(q)return{hitEntity:q,hitPoint:K,hitDistance:Z};return null}removeRawCollider(J){this._colliderMap.queueColliderHandleForCleanup(J.handle),this._rapierSimulation.removeCollider(J,!1)}removeRawRigidBody(J){this._rapierSimulation.removeRigidBody(J)}setGravity(J){this._rapierSimulation.gravity=J}step=(J)=>{this.emitWithWorld(this._world,"SIMULATION.STEP_START",{simulation:this,tickDeltaMs:J});let $=performance.now();if(T6.startSpan({operation:"physics_step"},()=>{this._rapierSimulation.step(this._rapierEventQueue)}),T6.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()-$}),this._debugRenderingEnabled)this.emitWithWorld(this._world,"SIMULATION.DEBUG_RENDER",{simulation:this,...this._rapierSimulation.debugRender(this._debugRenderingFilterFlags)})};_onCollisionEvent=(J,$,X)=>{let[Y,Q]=this._getCollisionObjects(J,$);if(!Y||!Q)return;let W=(K,Z)=>{if(K instanceof A9&&Z instanceof b6&&K.hasListeners("BLOCK_TYPE.ENTITY_COLLISION"))K.emit("BLOCK_TYPE.ENTITY_COLLISION",{blockType:K,entity:Z,started:X,colliderHandleA:J,colliderHandleB:$});else if(K instanceof b6&&Z instanceof A9&&K.hasListeners("ENTITY.BLOCK_COLLISION"))K.emit("ENTITY.BLOCK_COLLISION",{entity:K,blockType:Z,started:X,colliderHandleA:J,colliderHandleB:$});else if(K instanceof b6&&Z instanceof b6&&K.hasListeners("ENTITY.ENTITY_COLLISION"))K.emit("ENTITY.ENTITY_COLLISION",{entity:K,otherEntity:Z,started:X,colliderHandleA:J,colliderHandleB:$});else if(typeof K==="function"&&(Z instanceof b6||Z instanceof A9))K(Z,X,J,$)};W(Y,Q),W(Q,Y)};_onContactForceEvent=(J)=>{let[$,X]=this._getCollisionObjects(J.collider1(),J.collider2());if(!$||typeof $==="function"||!X||typeof X==="function")return;let Y={totalForce:J.totalForce(),totalForceMagnitude:J.totalForceMagnitude(),maxForceDirection:J.maxForceDirection(),maxForceMagnitude:J.maxForceMagnitude()},Q=(W,K)=>{if(W instanceof A9&&K instanceof b6&&W.hasListeners("BLOCK_TYPE.ENTITY_CONTACT_FORCE"))W.emit("BLOCK_TYPE.ENTITY_CONTACT_FORCE",{blockType:W,entity:K,contactForceData:Y});else if(W instanceof b6&&K instanceof A9&&W.hasListeners("ENTITY.BLOCK_CONTACT_FORCE"))W.emit("ENTITY.BLOCK_CONTACT_FORCE",{entity:W,blockType:K,contactForceData:Y});else if(W instanceof b6&&K instanceof b6&&W.hasListeners("ENTITY.ENTITY_CONTACT_FORCE"))W.emit("ENTITY.ENTITY_CONTACT_FORCE",{entity:W,otherEntity:K,contactForceData:Y})};Q($,X),Q(X,$)};_getCollisionObjects(J,$){let X=this._colliderMap.getColliderHandleBlockType(J)??this._colliderMap.getColliderHandleCollisionCallback(J)??this._colliderMap.getColliderHandleEntity(J),Y=this._colliderMap.getColliderHandleBlockType($)??this._colliderMap.getColliderHandleCollisionCallback($)??this._colliderMap.getColliderHandleEntity($);return[X,Y]}}class AC{_synchronizedPlayerReliablePackets=new w5;_queuedBroadcasts=[];_queuedAudioSynchronizations=new w5;_queuedBlockSynchronizations=new w5;_queuedBlockTypeSynchronizations=new w5;_queuedChunkSynchronizations=new w5;_queuedDebugRaycastSynchronizations=[];_queuedEntitySynchronizations=new w5;_queuedLightSynchronizations=new w5;_queuedParticleEmitterSynchronizations=new w5;_queuedPerPlayerSynchronizations=new w5;_queuedPerPlayerCameraSynchronizations=new w5;_queuedPerPlayerUISynchronizations=new w5;_queuedPerPlayerUIDatasSynchronizations=new w5;_queuedPlayerSynchronizations=new w5;_queuedSceneUISynchronizations=new w5;_queuedWorldSynchronization;_loadedSceneUIs=new Set;_spawnedChunks=new Set;_spawnedEntities=new Set;_world;constructor(J){this._world=J,this._subscribeToAudioEvents(),this._subscribeToBlockTypeRegistryEvents(),this._subscribeToChatEvents(),this._subscribeToChunkLatticeEvents(),this._subscribeToEntityEvents(),this._subscribeToLightEvents(),this._subscribeToParticleEmitterEvents(),this._subscribeToPlayerEvents(),this._subscribeToPlayerCameraEvents(),this._subscribeToPlayerUIEvents(),this._subscribeToSceneUIEvents(),this._subscribeToSimulationEvents(),this._subscribeToWorldEvents()}synchronize(){let J=[],$=[],X=this._world.loop.currentTick;if(this._queuedPerPlayerSynchronizations.size>0)for(let[Y,Q]of this._queuedPerPlayerSynchronizations)this._createOrGetSynchronizedPlayerReliablePackets(Y,J).push(...Q);if(this._queuedEntitySynchronizations.size>0){let Y=[],Q=[];for(let W of this._queuedEntitySynchronizations.valuesArray){let K=!1;for(let Z in W)if(Z!=="i"&&Z!=="p"&&Z!=="r"){K=!0;break}if(K)Y.push(W);else Q.push(W)}if(Q.length>0){let W=_0.createPacket(_0.outboundPackets.entitiesPacketDefinition,Q,X);$.push(W)}if(Y.length>0){let W=_0.createPacket(_0.outboundPackets.entitiesPacketDefinition,Y,X);J.push(W);for(let K of this._synchronizedPlayerReliablePackets.valuesArray)K.push(W)}}if(this._queuedAudioSynchronizations.size>0){let Y=_0.createPacket(_0.outboundPackets.audiosPacketDefinition,this._queuedAudioSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedBlockTypeSynchronizations.size>0){let Y=_0.createPacket(_0.outboundPackets.blockTypesPacketDefinition,this._queuedBlockTypeSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedChunkSynchronizations.size>0){let Y=_0.createPacket(_0.outboundPackets.chunksPacketDefinition,this._queuedChunkSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedBlockSynchronizations.size>0){let Y=_0.createPacket(_0.outboundPackets.blocksPacketDefinition,this._queuedBlockSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedLightSynchronizations.size>0){let Y=_0.createPacket(_0.outboundPackets.lightsPacketDefinition,this._queuedLightSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedParticleEmitterSynchronizations.size>0){let Y=_0.createPacket(_0.outboundPackets.particleEmittersPacketDefinition,this._queuedParticleEmitterSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedPerPlayerUISynchronizations.size>0)for(let[Y,Q]of this._queuedPerPlayerUISynchronizations){let W=_0.createPacket(_0.outboundPackets.uiPacketDefinition,Q,X);this._createOrGetSynchronizedPlayerReliablePackets(Y,J).push(W)}if(this._queuedPerPlayerUIDatasSynchronizations.size>0)for(let[Y,Q]of this._queuedPerPlayerUIDatasSynchronizations){let W=_0.createPacket(_0.outboundPackets.uiDatasPacketDefinition,Q,X);this._createOrGetSynchronizedPlayerReliablePackets(Y,J).push(W)}if(this._queuedSceneUISynchronizations.size>0){let Y=_0.createPacket(_0.outboundPackets.sceneUIsPacketDefinition,this._queuedSceneUISynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedWorldSynchronization){let Y=_0.createPacket(_0.outboundPackets.worldPacketDefinition,this._queuedWorldSynchronization,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedPerPlayerCameraSynchronizations.size>0)for(let[Y,Q]of this._queuedPerPlayerCameraSynchronizations){let W=_0.createPacket(_0.outboundPackets.cameraPacketDefinition,Q,X);this._createOrGetSynchronizedPlayerReliablePackets(Y,J).push(W)}if(this._queuedPlayerSynchronizations.size>0){let Y=_0.createPacket(_0.outboundPackets.playersPacketDefinition,this._queuedPlayerSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedBroadcasts.length>0)for(let Y of this._queuedBroadcasts){J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedDebugRaycastSynchronizations.length>0){let Y=_0.createPacket(_0.outboundPackets.physicsDebugRaycastsPacketDefinition,this._queuedDebugRaycastSynchronizations,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}T6.startSpan({operation:"send_all_packets"},()=>{for(let Y of F$.instance.getConnectedPlayersByWorld(this._world)){let Q=this._synchronizedPlayerReliablePackets.get(Y)??J;if(Q.length>0)Y.connection.send(Q);if($.length>0)Y.connection.send($,!1)}}),T6.startSpan({operation:"network_synchronize_cleanup"},()=>{if(this._queuedBroadcasts.length>0)this._queuedBroadcasts.length=0;if(this._queuedAudioSynchronizations.size>0)this._queuedAudioSynchronizations.clear();if(this._queuedBlockSynchronizations.size>0)this._queuedBlockSynchronizations.clear();if(this._queuedBlockTypeSynchronizations.size>0)this._queuedBlockTypeSynchronizations.clear();if(this._queuedChunkSynchronizations.size>0)this._queuedChunkSynchronizations.clear();if(this._queuedDebugRaycastSynchronizations.length>0)this._queuedDebugRaycastSynchronizations.length=0;if(this._queuedEntitySynchronizations.size>0)this._queuedEntitySynchronizations.clear();if(this._queuedLightSynchronizations.size>0)this._queuedLightSynchronizations.clear();if(this._queuedParticleEmitterSynchronizations.size>0)this._queuedParticleEmitterSynchronizations.clear();if(this._queuedPerPlayerSynchronizations.size>0)this._queuedPerPlayerSynchronizations.clear();if(this._queuedPerPlayerCameraSynchronizations.size>0)this._queuedPerPlayerCameraSynchronizations.clear();if(this._queuedPerPlayerUISynchronizations.size>0)this._queuedPerPlayerUISynchronizations.clear();if(this._queuedPerPlayerUIDatasSynchronizations.size>0)this._queuedPerPlayerUIDatasSynchronizations.clear();if(this._queuedPlayerSynchronizations.size>0)this._queuedPlayerSynchronizations.clear();if(this._queuedSceneUISynchronizations.size>0)this._queuedSceneUISynchronizations.clear();if(this._queuedWorldSynchronization)this._queuedWorldSynchronization=void 0;if(this._loadedSceneUIs.size>0)this._loadedSceneUIs.clear();if(this._spawnedChunks.size>0)this._spawnedChunks.clear();if(this._spawnedEntities.size>0)this._spawnedEntities.clear();if(this._synchronizedPlayerReliablePackets.size>0)this._synchronizedPlayerReliablePackets.clear();v$.clearCachedPacketsSerializedBuffers()})}_subscribeToAudioEvents(){this._world.final("AUDIO.PAUSE",this._onAudioPause),this._world.final("AUDIO.PLAY",this._onAudioPlay),this._world.final("AUDIO.PLAY_RESTART",this._onAudioPlayRestart),this._world.final("AUDIO.SET_ATTACHED_TO_ENTITY",this._onAudioSetAttachedToEntity),this._world.final("AUDIO.SET_CUTOFF_DISTANCE",this._onAudioSetCutoffDistance),this._world.final("AUDIO.SET_DETUNE",this._onAudioSetDetune),this._world.final("AUDIO.SET_DISTORTION",this._onAudioSetDistortion),this._world.final("AUDIO.SET_POSITION",this._onAudioSetPosition),this._world.final("AUDIO.SET_PLAYBACK_RATE",this._onAudioSetPlaybackRate),this._world.final("AUDIO.SET_REFERENCE_DISTANCE",this._onAudioSetReferenceDistance),this._world.final("AUDIO.SET_VOLUME",this._onAudioSetVolume)}_subscribeToBlockTypeRegistryEvents(){this._world.final("BLOCK_TYPE_REGISTRY.REGISTER_BLOCK_TYPE",this._onBlockTypeRegistryRegisterBlockType)}_subscribeToChatEvents(){this._world.final("CHAT.BROADCAST_MESSAGE",this._onChatSendBroadcastMessage),this._world.final("CHAT.PLAYER_MESSAGE",this._onChatSendPlayerMessage)}_subscribeToChunkLatticeEvents(){this._world.final("CHUNK_LATTICE.ADD_CHUNK",this._onChunkLatticeAddChunk),this._world.final("CHUNK_LATTICE.REMOVE_CHUNK",this._onChunkLatticeRemoveChunk),this._world.final("CHUNK_LATTICE.SET_BLOCK",this._onChunkLatticeSetBlock)}_subscribeToEntityEvents(){this._world.final("ENTITY.SPAWN",this._onEntitySpawn),this._world.final("ENTITY.DESPAWN",this._onEntityDespawn),this._world.final("ENTITY.SET_MODEL_ANIMATIONS_PLAYBACK_RATE",this._onEntitySetModelAnimationsPlaybackRate),this._world.final("ENTITY.SET_MODEL_HIDDEN_NODES",this._onEntitySetModelHiddenNodes),this._world.final("ENTITY.SET_MODEL_SCALE",this._onEntitySetModelScale),this._world.final("ENTITY.SET_MODEL_SHOWN_NODES",this._onEntitySetModelShownNodes),this._world.final("ENTITY.SET_MODEL_TEXTURE_URI",this._onEntitySetModelTextureUri),this._world.final("ENTITY.SET_OPACITY",this._onEntitySetOpacity),this._world.final("ENTITY.SET_PARENT",this._onEntitySetParent),this._world.final("ENTITY.SET_TINT_COLOR",this._onEntitySetTintColor),this._world.final("ENTITY.START_MODEL_LOOPED_ANIMATIONS",this._onEntityStartModelLoopedAnimations),this._world.final("ENTITY.START_MODEL_ONESHOT_ANIMATIONS",this._onEntityStartModelOneshotAnimations),this._world.final("ENTITY.STOP_MODEL_ANIMATIONS",this._onEntityStopModelAnimations),this._world.final("ENTITY.UPDATE_POSITION",this._onEntityUpdatePosition),this._world.final("ENTITY.UPDATE_ROTATION",this._onEntityUpdateRotation)}_subscribeToLightEvents(){this._world.final("LIGHT.DESPAWN",this._onLightDespawn),this._world.final("LIGHT.SET_ANGLE",this._onLightSetAngle),this._world.final("LIGHT.SET_ATTACHED_TO_ENTITY",this._onLightSetAttachedToEntity),this._world.final("LIGHT.SET_COLOR",this._onLightSetColor),this._world.final("LIGHT.SET_DISTANCE",this._onLightSetDistance),this._world.final("LIGHT.SET_INTENSITY",this._onLightSetIntensity),this._world.final("LIGHT.SET_OFFSET",this._onLightSetOffset),this._world.final("LIGHT.SET_PENUMBRA",this._onLightSetPenumbra),this._world.final("LIGHT.SET_POSITION",this._onLightSetPosition),this._world.final("LIGHT.SET_TRACKED_ENTITY",this._onLightSetTrackedEntity),this._world.final("LIGHT.SET_TRACKED_POSITION",this._onLightSetTrackedPosition),this._world.final("LIGHT.SPAWN",this._onLightSpawn)}_subscribeToParticleEmitterEvents(){this._world.final("PARTICLE_EMITTER.DESPAWN",this._onParticleEmitterDespawn),this._world.final("PARTICLE_EMITTER.BURST",this._onParticleEmitterBurst),this._world.final("PARTICLE_EMITTER.SET_ALPHA_TEST",this._onParticleEmitterSetAlphaTest),this._world.final("PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY",this._onParticleEmitterSetAttachedToEntity),this._world.final("PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME",this._onParticleEmitterSetAttachedToEntityNodeName),this._world.final("PARTICLE_EMITTER.SET_COLOR_END",this._onParticleEmitterSetColorEnd),this._world.final("PARTICLE_EMITTER.SET_COLOR_END_VARIANCE",this._onParticleEmitterSetColorEndVariance),this._world.final("PARTICLE_EMITTER.SET_COLOR_START",this._onParticleEmitterSetColorStart),this._world.final("PARTICLE_EMITTER.SET_COLOR_START_VARIANCE",this._onParticleEmitterSetColorStartVariance),this._world.final("PARTICLE_EMITTER.SET_GRAVITY",this._onParticleEmitterSetGravity),this._world.final("PARTICLE_EMITTER.SET_LIFETIME",this._onParticleEmitterSetLifetime),this._world.final("PARTICLE_EMITTER.SET_LIFETIME_VARIANCE",this._onParticleEmitterSetLifetimeVariance),this._world.final("PARTICLE_EMITTER.SET_MAX_PARTICLES",this._onParticleEmitterSetMaxParticles),this._world.final("PARTICLE_EMITTER.SET_OFFSET",this._onParticleEmitterSetOffset),this._world.final("PARTICLE_EMITTER.SET_OPACITY_END",this._onParticleEmitterSetOpacityEnd),this._world.final("PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE",this._onParticleEmitterSetOpacityEndVariance),this._world.final("PARTICLE_EMITTER.SET_OPACITY_START",this._onParticleEmitterSetOpacityStart),this._world.final("PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE",this._onParticleEmitterSetOpacityStartVariance),this._world.final("PARTICLE_EMITTER.SET_PAUSED",this._onParticleEmitterSetPaused),this._world.final("PARTICLE_EMITTER.SET_POSITION",this._onParticleEmitterSetPosition),this._world.final("PARTICLE_EMITTER.SET_POSITION_VARIANCE",this._onParticleEmitterSetPositionVariance),this._world.final("PARTICLE_EMITTER.SET_RATE",this._onParticleEmitterSetRate),this._world.final("PARTICLE_EMITTER.SET_RATE_VARIANCE",this._onParticleEmitterSetRateVariance),this._world.final("PARTICLE_EMITTER.SET_SIZE_END",this._onParticleEmitterSetSizeEnd),this._world.final("PARTICLE_EMITTER.SET_SIZE_END_VARIANCE",this._onParticleEmitterSetSizeEndVariance),this._world.final("PARTICLE_EMITTER.SET_SIZE_START",this._onParticleEmitterSetSizeStart),this._world.final("PARTICLE_EMITTER.SET_SIZE_START_VARIANCE",this._onParticleEmitterSetSizeStartVariance),this._world.final("PARTICLE_EMITTER.SET_TEXTURE_URI",this._onParticleEmitterSetTextureUri),this._world.final("PARTICLE_EMITTER.SET_TRANSPARENT",this._onParticleEmitterSetTransparent),this._world.final("PARTICLE_EMITTER.SET_VELOCITY",this._onParticleEmitterSetVelocity),this._world.final("PARTICLE_EMITTER.SET_VELOCITY_VARIANCE",this._onParticleEmitterSetVelocityVariance),this._world.final("PARTICLE_EMITTER.SPAWN",this._onParticleEmitterSpawn)}_subscribeToPlayerEvents(){this._world.final("PLAYER.JOINED_WORLD",this._onPlayerJoinedWorld),this._world.final("PLAYER.LEFT_WORLD",this._onPlayerLeftWorld),this._world.final("PLAYER.RECONNECTED_WORLD",this._onPlayerReconnectedWorld),this._world.final("PLAYER.REQUEST_NOTIFICATION_PERMISSION",this._onPlayerRequestNotificationPermission),this._world.final("PLAYER.REQUEST_SYNC",this._onPlayerRequestSync)}_subscribeToPlayerCameraEvents(){this._world.final("PLAYER_CAMERA.LOOK_AT_ENTITY",this._onPlayerCameraLookAtEntity),this._world.final("PLAYER_CAMERA.LOOK_AT_POSITION",this._onPlayerCameraLookAtPosition),this._world.final("PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY",this._onPlayerCameraSetAttachedToEntity),this._world.final("PLAYER_CAMERA.SET_ATTACHED_TO_POSITION",this._onPlayerCameraSetAttachedToPosition),this._world.final("PLAYER_CAMERA.SET_FILM_OFFSET",this._onPlayerCameraSetFilmOffset),this._world.final("PLAYER_CAMERA.SET_FORWARD_OFFSET",this._onPlayerCameraSetForwardOffset),this._world.final("PLAYER_CAMERA.SET_FOV",this._onPlayerCameraSetFov),this._world.final("PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES",this._onPlayerCameraSetModelHiddenNodes),this._world.final("PLAYER_CAMERA.SET_MODEL_SHOWN_NODES",this._onPlayerCameraSetModelShownNodes),this._world.final("PLAYER_CAMERA.SET_MODE",this._onPlayerCameraSetMode),this._world.final("PLAYER_CAMERA.SET_OFFSET",this._onPlayerCameraSetOffset),this._world.final("PLAYER_CAMERA.SET_SHOULDER_ANGLE",this._onPlayerCameraSetShoulderAngle),this._world.final("PLAYER_CAMERA.SET_TRACKED_ENTITY",this._onPlayerCameraSetTrackedEntity),this._world.final("PLAYER_CAMERA.SET_TRACKED_POSITION",this._onPlayerCameraSetTrackedPosition),this._world.final("PLAYER_CAMERA.SET_ZOOM",this._onPlayerCameraSetZoom)}_subscribeToPlayerUIEvents(){this._world.final("PLAYER_UI.LOAD",this._onPlayerUILoad),this._world.final("PLAYER_UI.LOCK_POINTER",this._onPlayerUILockPointer),this._world.final("PLAYER_UI.SEND_DATA",this._onPlayerUISendData)}_subscribeToSceneUIEvents(){this._world.final("SCENE_UI.LOAD",this._onSceneUILoad),this._world.final("SCENE_UI.SET_ATTACHED_TO_ENTITY",this._onSceneUISetAttachedToEntity),this._world.final("SCENE_UI.SET_OFFSET",this._onSceneUISetOffset),this._world.final("SCENE_UI.SET_POSITION",this._onSceneUISetPosition),this._world.final("SCENE_UI.SET_STATE",this._onSceneUISetState),this._world.final("SCENE_UI.SET_VIEW_DISTANCE",this._onSceneUISetViewDistance),this._world.final("SCENE_UI.UNLOAD",this._onSceneUIUnload)}_subscribeToSimulationEvents(){this._world.final("SIMULATION.DEBUG_RAYCAST",this._onSimulationDebugRaycast),this._world.final("SIMULATION.DEBUG_RENDER",this._onSimulationDebugRender)}_subscribeToWorldEvents(){this._world.final("WORLD.SET_AMBIENT_LIGHT_COLOR",this._onWorldSetAmbientLightColor),this._world.final("WORLD.SET_AMBIENT_LIGHT_INTENSITY",this._onWorldSetAmbientLightIntensity),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_COLOR",this._onWorldSetDirectionalLightColor),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY",this._onWorldSetDirectionalLightIntensity),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_POSITION",this._onWorldSetDirectionalLightPosition),this._world.final("WORLD.SET_FOG_COLOR",this._onWorldSetFogColor),this._world.final("WORLD.SET_FOG_FAR",this._onWorldSetFogFar),this._world.final("WORLD.SET_FOG_NEAR",this._onWorldSetFogNear),this._world.final("WORLD.SET_SKYBOX_INTENSITY",this._onWorldSetSkyboxIntensity),this._world.final("WORLD.SET_SKYBOX_URI",this._onWorldSetSkyboxUri)}_onAudioPause=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.pa=!0,delete $.pl,delete $.r};_onAudioPlay=(J)=>{let $=J.audio.serialize();$.pl=!0,delete $.pa,delete $.r,this._queuedAudioSynchronizations.set($.i,$)};_onAudioPlayRestart=(J)=>{let $=J.audio.serialize();$.r=!0,delete $.pa,delete $.pl,this._queuedAudioSynchronizations.set($.i,$)};_onAudioSetAttachedToEntity=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.e=J.entity?J.entity.id:void 0,$.p=J.entity?void 0:$.p};_onAudioSetCutoffDistance=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.cd=J.cutoffDistance};_onAudioSetDetune=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.de=J.detune};_onAudioSetDistortion=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.di=J.distortion};_onAudioSetPosition=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.e=J.position?void 0:$.e,$.p=J.position?V1.serializeVector(J.position):void 0};_onAudioSetPlaybackRate=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.pr=J.playbackRate};_onAudioSetReferenceDistance=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.rd=J.referenceDistance};_onAudioSetVolume=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.v=J.volume};_onBlockTypeRegistryRegisterBlockType=(J)=>{let $=J.blockType.serialize();this._queuedBlockTypeSynchronizations.set(J.blockType.id,$)};_onChatSendBroadcastMessage=(J)=>{let{player:$,message:X,color:Y}=J;this._queuedBroadcasts.push(_0.createPacket(_0.outboundPackets.chatMessagesPacketDefinition,[{m:X,c:Y,p:$?.id}],this._world.loop.currentTick))};_onChatSendPlayerMessage=(J)=>{let{player:$,message:X,color:Y}=J,Q=this._queuedPerPlayerSynchronizations.get($)??[];Q.push(_0.createPacket(_0.outboundPackets.chatMessagesPacketDefinition,[{m:X,c:Y}],this._world.loop.currentTick)),this._queuedPerPlayerSynchronizations.set($,Q)};_onChunkLatticeAddChunk=(J)=>{let $=this._createOrGetQueuedChunkSync(J.chunk);$.b=Array.from(J.chunk.blocks),$.rm=void 0,this._spawnedChunks.add($.c.join(","))};_onChunkLatticeRemoveChunk=(J)=>{let $=this._createOrGetQueuedChunkSync(J.chunk),X=$.c.join(",");if(this._spawnedChunks.has(X))this._queuedChunkSynchronizations.delete(X),this._spawnedChunks.delete(X);else $.rm=!0};_onChunkLatticeSetBlock=(J)=>{let $=this._createOrGetQueuedBlockSync(J.globalCoordinate);$.i=J.blockTypeId};_onEntitySetModelAnimationsPlaybackRate=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.ap=J.playbackRate};_onEntitySpawn=(J)=>{let $=J.entity.serialize();this._queuedEntitySynchronizations.set($.i,$),this._spawnedEntities.add($.i)};_onEntityDespawn=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);if(this._spawnedEntities.has($.i))this._queuedEntitySynchronizations.delete($.i),this._spawnedEntities.delete($.i);else $.rm=!0};_onEntitySetModelHiddenNodes=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.h=Array.from(J.modelHiddenNodes)};_onEntitySetModelScale=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.sv=J.modelScale?V1.serializeVector(J.modelScale):void 0};_onEntitySetModelShownNodes=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.sn=Array.from(J.modelShownNodes)};_onEntitySetModelTextureUri=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.mt=J.modelTextureUri};_onEntitySetOpacity=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.o=J.opacity};_onEntitySetParent=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.pe=J.parent?J.parent.id:void 0,$.pn=J.parentNodeName};_onEntitySetTintColor=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.t=J.tintColor?V1.serializeRgbColor(J.tintColor):void 0};_onEntityStartModelLoopedAnimations=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);if($.al=Array.from(new Set([...$.al??[],...J.animations])),$.as)$.as=$.as.filter((X)=>!J.animations.has(X)).filter(Boolean)};_onEntityStartModelOneshotAnimations=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);if($.ao=Array.from(new Set([...$.ao??[],...J.animations])),$.as)$.as=$.as.filter((X)=>!J.animations.has(X)).filter(Boolean)};_onEntityStopModelAnimations=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);if($.al)$.al=$.al.filter((X)=>!J.animations.has(X)).filter(Boolean);if($.ao)$.ao=$.ao.filter((X)=>!J.animations.has(X)).filter(Boolean);$.as=Array.from(new Set([...$.as??[],...J.animations]))};_onEntityUpdateRotation=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.r=[J.rotation.x,J.rotation.y,J.rotation.z,J.rotation.w]};_onEntityUpdatePosition=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.p=[J.position.x,J.position.y,J.position.z]};_onLightDespawn=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.rm=!0};_onLightSetAngle=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.a=J.angle};_onLightSetAttachedToEntity=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.e=J.entity?J.entity.id:void 0,$.p=J.entity?void 0:$.p};_onLightSetColor=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.c=V1.serializeRgbColor(J.color)};_onLightSetDistance=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.d=J.distance};_onLightSetIntensity=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.n=J.intensity};_onLightSetOffset=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.o=J.offset?V1.serializeVector(J.offset):void 0};_onLightSetPenumbra=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.pe=J.penumbra};_onLightSetPosition=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.p=J.position?V1.serializeVector(J.position):void 0,$.e=J.position?void 0:$.e};_onLightSetTrackedEntity=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.te=J.entity?J.entity.id:void 0,$.tp=J.entity?void 0:$.tp};_onLightSetTrackedPosition=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.tp=J.position?V1.serializeVector(J.position):void 0,$.te=J.position?void 0:$.te};_onLightSpawn=(J)=>{let $=J.light.serialize();this._queuedLightSynchronizations.set($.i,$)};_onParticleEmitterBurst=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.b=J.count};_onParticleEmitterDespawn=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.rm=!0};_onParticleEmitterSetAlphaTest=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.at=J.alphaTest};_onParticleEmitterSetAttachedToEntity=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.e=J.entity?J.entity.id:void 0,$.p=J.entity?void 0:$.p};_onParticleEmitterSetAttachedToEntityNodeName=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.en=J.attachedToEntityNodeName};_onParticleEmitterSetColorEnd=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.ce=J.colorEnd?V1.serializeRgbColor(J.colorEnd):void 0};_onParticleEmitterSetColorEndVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.cev=J.colorEndVariance?V1.serializeRgbColor(J.colorEndVariance):void 0};_onParticleEmitterSetColorStart=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.cs=J.colorStart?V1.serializeRgbColor(J.colorStart):void 0};_onParticleEmitterSetColorStartVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.csv=J.colorStartVariance?V1.serializeRgbColor(J.colorStartVariance):void 0};_onParticleEmitterSetGravity=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.g=J.gravity?V1.serializeVector(J.gravity):void 0};_onParticleEmitterSetLifetime=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.l=J.lifetime};_onParticleEmitterSetLifetimeVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.lv=J.lifetimeVariance};_onParticleEmitterSetMaxParticles=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.mp=J.maxParticles};_onParticleEmitterSetOffset=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.o=J.offset?V1.serializeVector(J.offset):void 0};_onParticleEmitterSetOpacityEnd=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.oe=J.opacityEnd};_onParticleEmitterSetOpacityEndVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.oev=J.opacityEndVariance};_onParticleEmitterSetOpacityStart=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.os=J.opacityStart};_onParticleEmitterSetOpacityStartVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.osv=J.opacityStartVariance};_onParticleEmitterSetPaused=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.pa=J.paused};_onParticleEmitterSetPosition=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.p=J.position?V1.serializeVector(J.position):void 0,$.e=J.position?void 0:$.e,$.en=J.position?void 0:$.en};_onParticleEmitterSetPositionVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.pv=J.positionVariance?V1.serializeVector(J.positionVariance):void 0};_onParticleEmitterSetRate=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.r=J.rate};_onParticleEmitterSetRateVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.rv=J.rateVariance};_onParticleEmitterSetSizeEnd=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.se=J.sizeEnd};_onParticleEmitterSetSizeEndVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.sev=J.sizeEndVariance};_onParticleEmitterSetSizeStart=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.ss=J.sizeStart};_onParticleEmitterSetSizeStartVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.ssv=J.sizeStartVariance};_onParticleEmitterSetTextureUri=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.tu=J.textureUri};_onParticleEmitterSetTransparent=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.t=J.transparent};_onParticleEmitterSetVelocity=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.v=J.velocity?V1.serializeVector(J.velocity):void 0};_onParticleEmitterSetVelocityVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.vv=J.velocityVariance?V1.serializeVector(J.velocityVariance):void 0};_onParticleEmitterSpawn=(J)=>{let $=J.particleEmitter.serialize();this._queuedParticleEmitterSynchronizations.set($.i,$)};_onPlayerCameraLookAtEntity=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.pl=V1.serializeVector(J.entity.position),delete $.et,delete $.pt};_onPlayerCameraLookAtPosition=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.pl=J.position?V1.serializeVector(J.position):void 0,delete $.et,delete $.pt};_onPlayerCameraSetAttachedToEntity=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.e=J.entity.id,delete $.p};_onPlayerCameraSetAttachedToPosition=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.p=J.position?V1.serializeVector(J.position):void 0,delete $.e};_onPlayerCameraSetFilmOffset=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.fo=J.filmOffset};_onPlayerCameraSetForwardOffset=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.ffo=J.forwardOffset};_onPlayerCameraSetFov=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.fv=J.fov};_onPlayerCameraSetModelHiddenNodes=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.h=Array.from(J.modelHiddenNodes)};_onPlayerCameraSetModelShownNodes=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.s=Array.from(J.modelShownNodes)};_onPlayerCameraSetMode=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.m=J.mode};_onPlayerCameraSetOffset=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.o=J.offset?V1.serializeVector(J.offset):void 0};_onPlayerCameraSetShoulderAngle=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.sa=J.shoulderAngle};_onPlayerCameraSetTrackedEntity=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.et=J.entity?J.entity.id:void 0,delete $.pl,delete $.pt};_onPlayerCameraSetTrackedPosition=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.pt=J.position?V1.serializeVector(J.position):void 0,delete $.et,delete $.pl};_onPlayerCameraSetZoom=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.z=J.zoom};_onPlayerJoinedWorld=(J)=>{let{player:$}=J,X=this._queuedPerPlayerSynchronizations.get($)??[];X.push(_0.createPacket(_0.outboundPackets.entitiesPacketDefinition,this._world.entityManager.getAllEntities().map((Q)=>{if($.camera.attachedToEntity===void 0&&Q instanceof o$&&Q.player===$)$.camera.setAttachedToEntity(Q);return Q.serialize()}),this._world.loop.currentTick)),X.push(_0.createPacket(_0.outboundPackets.audiosPacketDefinition,this._world.audioManager.getAllAudios().map((Q)=>Q.serialize()),this._world.loop.currentTick)),X.push(_0.createPacket(_0.outboundPackets.blockTypesPacketDefinition,this._world.blockTypeRegistry.serialize(),this._world.loop.currentTick)),X.push(_0.createPacket(_0.outboundPackets.chunksPacketDefinition,this._world.chunkLattice.getAllChunks().map((Q)=>Q.serialize()),this._world.loop.currentTick)),X.push(_0.createPacket(_0.outboundPackets.lightsPacketDefinition,this._world.lightManager.getAllLights().map((Q)=>Q.serialize()),this._world.loop.currentTick)),X.push(_0.createPacket(_0.outboundPackets.particleEmittersPacketDefinition,this._world.particleEmitterManager.getAllParticleEmitters().map((Q)=>Q.serialize()),this._world.loop.currentTick)),X.push(_0.createPacket(_0.outboundPackets.sceneUIsPacketDefinition,this._world.sceneUIManager.getAllSceneUIs().map((Q)=>Q.serialize()),this._world.loop.currentTick)),X.push(_0.createPacket(_0.outboundPackets.worldPacketDefinition,this._world.serialize(),this._world.loop.currentTick)),X.push(_0.createPacket(_0.outboundPackets.playersPacketDefinition,F$.instance.getConnectedPlayers().map((Q)=>Q.serialize()),this._world.loop.currentTick));let Y=this._createOrGetQueuedPlayerCameraSync($.camera);this._queuedPerPlayerCameraSynchronizations.set($,{...$.camera.serialize(),...Y}),this._queuedPerPlayerSynchronizations.set($,X),this._queuedPlayerSynchronizations.set($.id,$.serialize())};_onPlayerLeftWorld=(J)=>{let $=this._createOrGetQueuedPlayerSync(J.player);$.rm=!0};_onPlayerReconnectedWorld=(J)=>{this._onPlayerJoinedWorld(J)};_onPlayerRequestNotificationPermission=(J)=>{let{player:$}=J,X=this._queuedPerPlayerSynchronizations.get($)??[];X.push(_0.createPacket(_0.outboundPackets.notificationPermissionRequestPacketDefinition,null,this._world.loop.currentTick)),this._queuedPerPlayerSynchronizations.set($,X)};_onPlayerRequestSync=(J)=>{J.player.connection.send([_0.createPacket(_0.outboundPackets.syncResponsePacketDefinition,{r:J.receivedAt,s:Date.now(),p:performance.now()-J.receivedAtMs,n:this._world.loop.nextTickMs},this._world.loop.currentTick)])};_onPlayerUILoad=(J)=>{let $=this._createOrGetQueuedPlayerUISync(J.playerUI);$.u=J.htmlUri};_onPlayerUILockPointer=(J)=>{let $=this._createOrGetQueuedPlayerUISync(J.playerUI);$.p=J.lock};_onPlayerUISendData=(J)=>{this._createOrGetQueuedPlayerUIDatasSync(J.playerUI).push(J.data)};_onSceneUILoad=(J)=>{let $=J.sceneUI.serialize();this._queuedSceneUISynchronizations.set($.i,$),this._loadedSceneUIs.add($.i)};_onSceneUISetAttachedToEntity=(J)=>{let $=this._createOrGetQueuedSceneUISync(J.sceneUI);$.e=J.entity?J.entity.id:void 0,$.p=J.entity?void 0:$.p};_onSceneUISetOffset=(J)=>{let $=this._createOrGetQueuedSceneUISync(J.sceneUI);$.o=J.offset?V1.serializeVector(J.offset):void 0};_onSceneUISetPosition=(J)=>{let $=this._createOrGetQueuedSceneUISync(J.sceneUI);$.p=J.position?V1.serializeVector(J.position):void 0,$.e=J.position?void 0:$.e};_onSceneUISetState=(J)=>{let $=this._createOrGetQueuedSceneUISync(J.sceneUI);$.s=J.state};_onSceneUISetViewDistance=(J)=>{let $=this._createOrGetQueuedSceneUISync(J.sceneUI);$.v=J.viewDistance};_onSceneUIUnload=(J)=>{let $=this._createOrGetQueuedSceneUISync(J.sceneUI);if(this._loadedSceneUIs.has($.i))this._queuedSceneUISynchronizations.delete($.i),this._loadedSceneUIs.delete($.i);else $.rm=!0};_onSimulationDebugRaycast=(J)=>{this._queuedDebugRaycastSynchronizations.push(V1.serializePhysicsDebugRaycast(J))};_onSimulationDebugRender=(J)=>{this._queuedBroadcasts.push(_0.createPacket(_0.outboundPackets.physicsDebugRenderPacketDefinition,{v:Array.from(J.vertices),c:Array.from(J.colors)},this._world.loop.currentTick))};_onWorldSetAmbientLightColor=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.ac=V1.serializeRgbColor(J.color)};_onWorldSetAmbientLightIntensity=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.ai=J.intensity};_onWorldSetDirectionalLightColor=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.dc=V1.serializeRgbColor(J.color)};_onWorldSetDirectionalLightIntensity=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.di=J.intensity};_onWorldSetDirectionalLightPosition=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.dp=V1.serializeVector(J.position)};_onWorldSetFogColor=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.fc=V1.serializeRgbColor(J.color)};_onWorldSetFogFar=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.ff=J.far};_onWorldSetFogNear=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.fn=J.near};_onWorldSetSkyboxIntensity=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.si=J.intensity};_onWorldSetSkyboxUri=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.s=J.uri};_createOrGetQueuedAudioSync(J){if(J.id===void 0)n.fatalError("NetworkSynchronizer._createOrGetQueuedAudioSync(): Audio has no id!");let $=this._queuedAudioSynchronizations.get(J.id);if(!$)$={i:J.id},this._queuedAudioSynchronizations.set(J.id,$);return $}_createOrGetQueuedBlockSync(J){let{x:$,y:X,z:Y}=J,Q=`${$},${X},${Y}`,W=this._queuedBlockSynchronizations.get(Q);if(!W)W={i:0,c:[$,X,Y]},this._queuedBlockSynchronizations.set(Q,W);return W}_createOrGetQueuedChunkSync(J){if(!J.originCoordinate)n.fatalError("NetworkSynchronizer._createOrGetQueuedChunkSync(): Chunk has no origin coordinate!");let{x:$,y:X,z:Y}=J.originCoordinate,Q=`${$},${X},${Y}`,W=this._queuedChunkSynchronizations.get(Q);if(!W)W={c:[$,X,Y]},this._queuedChunkSynchronizations.set(Q,W);return W}_createOrGetQueuedEntitySync(J){if(J.id===void 0)n.fatalError("NetworkSynchronizer._createOrGetQueuedEntitySync(): Entity has no id!");let $=this._queuedEntitySynchronizations.get(J.id);if(!$)$={i:J.id},this._queuedEntitySynchronizations.set(J.id,$);return $}_createOrGetQueuedLightSync(J){if(J.id===void 0)n.fatalError("NetworkSynchronizer._createOrGetQueuedLightSync(): Light has no id!");let $=this._queuedLightSynchronizations.get(J.id);if(!$)$={i:J.id},this._queuedLightSynchronizations.set(J.id,$);return $}_createOrGetQueuedParticleEmitterSync(J){if(J.id===void 0)n.fatalError("NetworkSynchronizer._createOrGetQueuedParticleEmitterSync(): ParticleEmitter has no id!");let $=this._queuedParticleEmitterSynchronizations.get(J.id);if(!$)$={i:J.id},this._queuedParticleEmitterSynchronizations.set(J.id,$);return $}_createOrGetQueuedPlayerSync(J){if(J.id===void 0)n.fatalError("NetworkSynchronizer._createOrGetQueuedPlayerSync(): Player has no id!");let $=this._queuedPlayerSynchronizations.get(J.id);if(!$)$={i:J.id},this._queuedPlayerSynchronizations.set(J.id,$);return $}_createOrGetQueuedPlayerCameraSync(J){let $=this._queuedPerPlayerCameraSynchronizations.get(J.player);if(!$)$={},this._queuedPerPlayerCameraSynchronizations.set(J.player,$);return $}_createOrGetQueuedPlayerUISync(J){let $=this._queuedPerPlayerUISynchronizations.get(J.player);if(!$)$={},this._queuedPerPlayerUISynchronizations.set(J.player,$);return $}_createOrGetQueuedPlayerUIDatasSync(J){let $=this._queuedPerPlayerUIDatasSynchronizations.get(J.player);if(!$)$=[],this._queuedPerPlayerUIDatasSynchronizations.set(J.player,$);return $}_createOrGetQueuedSceneUISync(J){if(J.id===void 0)n.fatalError("NetworkSynchronizer._createOrGetQueuedSceneUISync(): SceneUI has no id!");let $=this._queuedSceneUISynchronizations.get(J.id);if(!$)$={i:J.id},this._queuedSceneUISynchronizations.set(J.id,$);return $}_createOrGetQueuedWorldSync(J){if(J.id!==this._world.id)n.fatalError("NetworkSynchronizer._createOrGetQueuedWorldSync(): World does not match this network synchronizer world!");return this._queuedWorldSynchronization??={i:J.id}}_createOrGetSynchronizedPlayerReliablePackets(J,$){let X=this._synchronizedPlayerReliablePackets.get(J);if(!X)X=[...$],this._synchronizedPlayerReliablePackets.set(J,X);return X}}class XB{_particleEmitters=new Map;_nextParticleEmitterId=1;_world;constructor(J){this._world=J}get world(){return this._world}despawnEntityAttachedParticleEmitters(J){this.getAllEntityAttachedParticleEmitters(J).forEach(($)=>{$.despawn()})}getAllParticleEmitters(){return Array.from(this._particleEmitters.values())}getAllEntityAttachedParticleEmitters(J){return this.getAllParticleEmitters().filter(($)=>$.attachedToEntity===J)}registerParticleEmitter(J){if(J.id!==void 0)return J.id;let $=this._nextParticleEmitterId;return this._particleEmitters.set($,J),this._nextParticleEmitterId++,$}unregisterParticleEmitter(J){if(J.id===void 0)return;this._particleEmitters.delete(J.id)}}class YB{_sceneUIs=new Map;_nextSceneUIId=1;_world;constructor(J){this._world=J}get world(){return this._world}getAllSceneUIs(){return Array.from(this._sceneUIs.values())}getAllEntityAttachedSceneUIs(J){return this.getAllSceneUIs().filter(($)=>$.attachedToEntity===J)}getSceneUIById(J){return this._sceneUIs.get(J)}registerSceneUI(J){if(J.id!==void 0)return J.id;let $=this._nextSceneUIId;return this._sceneUIs.set($,J),this._nextSceneUIId++,$}unloadEntityAttachedSceneUIs(J){this.getAllEntityAttachedSceneUIs(J).forEach(($)=>{$.unload()})}unregisterSceneUI(J){if(J.id===void 0)return;this._sceneUIs.delete(J.id)}}var AC6=2,cC6=3;class QB{_accumulatorMs=0;_targetTicksPerSecond;_fixedTimestepMs;_fixedTimestepS;_maxAccumulatorMs;_nextTickMs=0;_lastLoopTimeMs=0;_tickFunction;_tickErrorCallback;_tickHandle=null;constructor(J,$,X){this._targetTicksPerSecond=J,this._fixedTimestepS=Math.fround(1/J),this._fixedTimestepMs=Math.fround(this._fixedTimestepS*1000),this._maxAccumulatorMs=this._fixedTimestepMs*cC6,this._tickFunction=$,this._tickErrorCallback=X}get targetTicksPerSecond(){return this._targetTicksPerSecond}get fixedTimestepMs(){return this._fixedTimestepMs}get fixedTimestepS(){return this._fixedTimestepS}get isStarted(){return!!this._tickHandle}get nextTickMs(){return this._nextTickMs}start(){if(this._tickHandle)return;this._lastLoopTimeMs=performance.now();let J=()=>{let $=performance.now(),X=$-this._lastLoopTimeMs;if(this._lastLoopTimeMs=$,this._accumulatorMs+=X,this._accumulatorMs>this._maxAccumulatorMs)this._accumulatorMs=this._maxAccumulatorMs;if(this._accumulatorMs>=this._fixedTimestepMs)T6.startSpan({operation:"ticker_tick"},()=>{let Y=0;while(this._accumulatorMs>=this._fixedTimestepMs&&Y<AC6)this._tick(this._fixedTimestepMs),this._accumulatorMs-=this._fixedTimestepMs,Y++});this._nextTickMs=Math.max(0,this._fixedTimestepMs-this._accumulatorMs),this._tickHandle=setTimeout(J,this._nextTickMs)};J()}stop(){if(!this._tickHandle)return;clearTimeout(this._tickHandle),this._tickHandle=null}_tick(J){try{this._tickFunction(J)}catch($){if($ instanceof Error&&this._tickErrorCallback)this._tickErrorCallback($);else n.warning(`Ticker._tick(): tick callback threw an error, but it was not an instance of Error. Error: ${$}`)}}}var JO1;((W)=>{W.START="WORLD_LOOP.START";W.STOP="WORLD_LOOP.STOP";W.TICK_START="WORLD_LOOP.TICK_START";W.TICK_END="WORLD_LOOP.TICK_END";W.TICK_ERROR="WORLD_LOOP.TICK_ERROR"})(JO1||={});class WB extends $1{_currentTick=0;_ticker;_world;constructor(J,$=ei){super();this._ticker=new QB($,this._tick,this._onTickError),this._world=J}get currentTick(){return this._currentTick}get isStarted(){return this._ticker.isStarted}get nextTickMs(){return this._ticker.nextTickMs}get timestepS(){return this._ticker.fixedTimestepS}get world(){return this._world}start(){this._ticker.start(),this.emitWithWorld(this._world,"WORLD_LOOP.START",{worldLoop:this})}stop(){this._ticker.stop(),this.emitWithWorld(this._world,"WORLD_LOOP.STOP",{worldLoop:this})}_tick=(J)=>{this.emitWithWorld(this._world,"WORLD_LOOP.TICK_START",{worldLoop:this,tickDeltaMs:J});let $=performance.now();T6.startSpan({operation:"world_tick",attributes:{serverPlayerCount:F$.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}},()=>{T6.startSpan({operation:"entities_tick"},()=>this._world.entityManager.tickEntities(J)),T6.startSpan({operation:"simulation_step"},()=>this._world.simulation.step(J)),T6.startSpan({operation:"entities_emit_updates"},()=>this._world.entityManager.checkAndEmitUpdates()),T6.startSpan({operation:"network_synchronize"},()=>this._world.networkSynchronizer.synchronize())}),this._currentTick++,this.emitWithWorld(this._world,"WORLD_LOOP.TICK_END",{worldLoop:this,tickDurationMs:performance.now()-$})};_onTickError=(J)=>{n.error(`WorldLoop._onTickError(): Error: ${J}`),this.emitWithWorld(this._world,"WORLD_LOOP.TICK_ERROR",{worldLoop:this,error:J})}}var $n;((H)=>{H.SET_AMBIENT_LIGHT_COLOR="WORLD.SET_AMBIENT_LIGHT_COLOR";H.SET_AMBIENT_LIGHT_INTENSITY="WORLD.SET_AMBIENT_LIGHT_INTENSITY";H.SET_DIRECTIONAL_LIGHT_COLOR="WORLD.SET_DIRECTIONAL_LIGHT_COLOR";H.SET_DIRECTIONAL_LIGHT_INTENSITY="WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY";H.SET_DIRECTIONAL_LIGHT_POSITION="WORLD.SET_DIRECTIONAL_LIGHT_POSITION";H.SET_FOG_COLOR="WORLD.SET_FOG_COLOR";H.SET_FOG_FAR="WORLD.SET_FOG_FAR";H.SET_FOG_NEAR="WORLD.SET_FOG_NEAR";H.SET_SKYBOX_INTENSITY="WORLD.SET_SKYBOX_INTENSITY";H.SET_SKYBOX_URI="WORLD.SET_SKYBOX_URI";H.START="WORLD.START";H.STOP="WORLD.STOP"})($n||={});class KB extends $1{_id;_ambientLightColor;_ambientLightIntensity;_audioManager;_blockTypeRegistry;_chatManager;_chunkLattice;_directionalLightColor;_directionalLightIntensity;_directionalLightPosition;_entityManager;_fogColor;_fogFar;_fogNear;_lightManager;_loop;_name;_networkSynchronizer;_particleEmitterManager;_sceneUIManager;_simulation;_skyboxIntensity;_skyboxUri;_tag;constructor(J){super();if(this._id=J.id,this._ambientLightColor=J.ambientLightColor??{r:255,g:255,b:255},this._ambientLightIntensity=J.ambientLightIntensity??1,this._directionalLightColor=J.directionalLightColor??{r:255,g:255,b:255},this._directionalLightIntensity=J.directionalLightIntensity??3,this._directionalLightPosition=J.directionalLightPosition??{x:100,y:150,z:100},this._fogColor=J.fogColor,this._fogFar=J.fogFar??550,this._fogNear=J.fogNear??500,this._name=J.name,this._skyboxIntensity=J.skyboxIntensity??1,this._skyboxUri=J.skyboxUri,this._tag=J.tag,this._audioManager=new vz(this),this._blockTypeRegistry=new EF(this),this._chatManager=new FU(this),this._chunkLattice=new UU(this),this._entityManager=new LU(this),this._lightManager=new JB(this),this._loop=new WB(this,J.tickRate),this._networkSynchronizer=new AC(this),this._particleEmitterManager=new XB(this),this._sceneUIManager=new YB(this),this._simulation=new $B(this,J.tickRate,J.gravity),J.map)this.loadMap(J.map)}get id(){return this._id}get ambientLightColor(){return this._ambientLightColor}get ambientLightIntensity(){return this._ambientLightIntensity}get blockTypeRegistry(){return this._blockTypeRegistry}get chatManager(){return this._chatManager}get chunkLattice(){return this._chunkLattice}get directionalLightColor(){return this._directionalLightColor}get directionalLightIntensity(){return this._directionalLightIntensity}get directionalLightPosition(){return this._directionalLightPosition}get entityManager(){return this._entityManager}get fogColor(){return this._fogColor}get fogFar(){return this._fogFar}get fogNear(){return this._fogNear}get lightManager(){return this._lightManager}get loop(){return this._loop}get name(){return this._name}get networkSynchronizer(){return this._networkSynchronizer}get particleEmitterManager(){return this._particleEmitterManager}get sceneUIManager(){return this._sceneUIManager}get simulation(){return this._simulation}get skyboxIntensity(){return this._skyboxIntensity}get skyboxUri(){return this._skyboxUri}get audioManager(){return this._audioManager}get tag(){return this._tag}loadMap(J){if(this.chunkLattice.clear(),J.blockTypes)for(let $ of J.blockTypes)this.blockTypeRegistry.registerGenericBlockType({id:$.id,isLiquid:$.isLiquid,lightLevel:$.lightLevel,name:$.name,textureUri:$.textureUri});if(J.blocks){let $={};for(let X in J.blocks){let Y=J.blocks[X],Q=X.indexOf(","),W=X.indexOf(",",Q+1),K=Number(X.slice(0,Q)),Z=Number(X.slice(Q+1,W)),G=Number(X.slice(W+1));if(!$[Y])$[Y]=[];$[Y].push({x:K,y:Z,z:G})}this.chunkLattice.initializeBlocks($)}if(J.entities)for(let $ in J.entities){let X=J.entities[$],Y=$.indexOf(","),Q=$.indexOf(",",Y+1),W=Number($.slice(0,Y)),K=Number($.slice(Y+1,Q)),Z=Number($.slice(Q+1));new b6({isEnvironmental:!0,...X}).spawn(this,{x:W,y:K,z:Z})}}setAmbientLightColor(J){this._ambientLightColor=J,this.emit("WORLD.SET_AMBIENT_LIGHT_COLOR",{world:this,color:J})}setAmbientLightIntensity(J){this._ambientLightIntensity=J,this.emit("WORLD.SET_AMBIENT_LIGHT_INTENSITY",{world:this,intensity:J})}setDirectionalLightColor(J){this._directionalLightColor=J,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_COLOR",{world:this,color:J})}setDirectionalLightIntensity(J){this._directionalLightIntensity=J,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY",{world:this,intensity:J})}setDirectionalLightPosition(J){this._directionalLightPosition=J,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_POSITION",{world:this,position:J})}setFogColor(J){this._fogColor=J,this.emit("WORLD.SET_FOG_COLOR",{world:this,color:J})}setFogFar(J){this._fogFar=J,this.emit("WORLD.SET_FOG_FAR",{world:this,far:J})}setFogNear(J){this._fogNear=J,this.emit("WORLD.SET_FOG_NEAR",{world:this,near:J})}setSkyboxIntensity(J){this._skyboxIntensity=J,this.emit("WORLD.SET_SKYBOX_INTENSITY",{world:this,intensity:J})}setSkyboxUri(J){this._skyboxUri=J,this.emit("WORLD.SET_SKYBOX_URI",{world:this,uri:J})}start(){if(this._loop.isStarted)return;this._loop.start(),this.emit("WORLD.START",{world:this,startedAtMs:Date.now()})}stop(){if(!this._loop.isStarted)return;this._loop.stop(),this.emit("WORLD.STOP",{world:this,stoppedAtMs:Date.now()})}serialize(){return V1.serializeWorld(this)}}var $O1;(($)=>$.WORLD_CREATED="WORLD_MANAGER.WORLD_CREATED")($O1||={});class bK{static instance=new bK;_defaultWorld;_nextWorldId=1;_worlds=new Map;createWorld(J){let $=new KB({...J,id:this._nextWorldId++});return $.start(),this._worlds.set($.id,$),$1.globalInstance.emit("WORLD_MANAGER.WORLD_CREATED",{world:$}),$}getAllWorlds(){return Array.from(this._worlds.values())}getDefaultWorld(){return this._defaultWorld??=this.createWorld({name:"Default World",skyboxUri:"skyboxes/partly-cloudy"}),this._defaultWorld}getWorldsByTag(J){let $=[];return this._worlds.forEach((X)=>{if(X.tag===J)$.push(X)}),$}getWorld(J){return this._worlds.get(J)}setDefaultWorld(J){this._defaultWorld=J}}var XO1;((Y)=>{Y.PLAYER_CONNECTED="PLAYER_MANAGER.PLAYER_CONNECTED";Y.PLAYER_DISCONNECTED="PLAYER_MANAGER.PLAYER_DISCONNECTED";Y.PLAYER_RECONNECTED="PLAYER_MANAGER.PLAYER_RECONNECTED"})(XO1||={});class F${static instance=new F$;worldSelectionHandler;_connectionPlayers=new Map;constructor(){$1.globalInstance.on("CONNECTION.OPENED",({connection:J,session:$})=>{this._onConnectionOpened(J,$)}),$1.globalInstance.on("CONNECTION.DISCONNECTED",({connection:J})=>{this._onConnectionDisconnected(J)}),$1.globalInstance.on("CONNECTION.RECONNECTED",({connection:J})=>{this._onConnectionReconnected(J)}),$1.globalInstance.on("CONNECTION.CLOSED",({connection:J})=>{this._onConnectionClosed(J)})}get playerCount(){return this._connectionPlayers.size}getConnectedPlayers(){return Array.from(this._connectionPlayers.values())}getConnectedPlayersByWorld(J){return this.getConnectedPlayers().filter(($)=>$.world===J)}getConnectedPlayerByUsername(J){return Array.from(this._connectionPlayers.values()).find(($)=>{return $.username.toLowerCase()===J.toLowerCase()})}async _onConnectionOpened(J,$){let X=new kq(J,$);await X.loadInitialPersistedData(),$1.globalInstance.emit("PLAYER_MANAGER.PLAYER_CONNECTED",{player:X});let Y=await this.worldSelectionHandler?.(X);X.joinWorld(Y??bK.instance.getDefaultWorld()),this._connectionPlayers.set(J,X)}_onConnectionDisconnected(J){let $=this._connectionPlayers.get(J);if($)$.resetInputs(),$.camera.reset()}_onConnectionReconnected(J){let $=this._connectionPlayers.get(J);if($)$.reconnected(),$1.globalInstance.emit("PLAYER_MANAGER.PLAYER_RECONNECTED",{player:$});else n.warning(`PlayerManager._onConnectionReconnected(): Connection ${J.id} not in the PlayerManager._connectionPlayers map.`)}_onConnectionClosed(J){let $=this._connectionPlayers.get(J);if($)$.disconnect(),this._connectionPlayers.delete(J),CW.instance.unloadPlayerData($).catch((X)=>{n.warning(`PlayerManager._onConnectionClosed(): Failed to unload player data for player ${$.id}. Error: ${X}`)}),$1.globalInstance.emit("PLAYER_MANAGER.PLAYER_DISCONNECTED",{player:$});else n.warning(`PlayerManager._onConnectionClosed(): Connection ${J.id} not in the PlayerManager._connectionPlayers map.`)}}import{randomBytes as hC6}from"crypto";import{Http3Server as fC6}from"@fails-components/webtransport";class ZB extends $1{static instance=new ZB;_connectionIdConnections=new Map;_userIdConnections=new Map;_wss;_wts;constructor(){super();this._wss=new Ch.default({noServer:!0}),this._wss.on("connection",(J,$)=>this._onConnection(J,void 0,$.connectionId,$.session)),this._wts=new fC6({port:SC,host:"0.0.0.0",secret:hC6(32).toString("hex"),cert:kC,privKey:EC,defaultDatagramsReadableMode:"bytes"}),this._wts.setRequestCallback(this._onWebTransportRequest),this._startWebTransport().catch((J)=>{n.error(`Socket: WebTransport server failed to start or crashed while listening for sessions. Error: ${J}`)}),$1.globalInstance.on("WEBSERVER.UPGRADE",async({req:J,socket:$,head:X})=>{await this._authorizeAndConnectWebsocket(J,$,X)})}async _authorizeAndConnectWebsocket(J,$,X){let Y=await this._authorizeConnection(J.url??"");if(Y.error){$.end();return}J.connectionId=Y.connectionId,J.session=Y.session,$.setNoDelay(!0),this._wss.handleUpgrade(J,$,X,(Q)=>{if(Q.readyState!==Cq.default.OPEN)Q.once("open",()=>this._wss.emit("connection",Q,J));else this._wss.emit("connection",Q,J)})}async _authorizeConnection(J){let $=J.includes("?")?J.slice(J.indexOf("?")):"",X=new URLSearchParams($),Y=X.get("connectionId")??void 0,Q=X.get("sessionToken")??"";if(Y&&this._isValidConnectionId(Y))return{connectionId:Y};else{let W=await k7.instance.getPlayerSession(Q);if(W?.error)return{error:W.error};else if(W)return{session:W}}return{}}_isValidConnectionId(J){return this._connectionIdConnections.has(J)}_onConnection=(J,$,X,Y)=>{let Q=Y?.user.id,W=(X&&this._connectionIdConnections.get(X))??(Q&&this._userIdConnections.get(Q));if(W){if(J)W.bindWs(J);if($)W.bindWt($).catch((K)=>{n.error(`Socket._onConnection(): WebTransport binding failed. Error: ${K}`)})}else{let K=new v$(J,$,Y);if(K.on("CONNECTION.CLOSED",()=>{if(this._connectionIdConnections.delete(K.id),Q)this._userIdConnections.delete(Q)}),this._connectionIdConnections.set(K.id,K),Q)this._userIdConnections.set(Q,K)}};_onWebTransportRequest=async({header:J})=>{let{connectionId:$,session:X,error:Y}=await this._authorizeConnection(J[":path"]??"");return{status:Y?401:200,path:"/",userData:{connectionId:$,session:X}}};async _startWebTransport(){this._wts.startServer();for await(let J of this._wts.sessionStream("/"))try{let{connectionId:$,session:X}=J.userData;this._onConnection(void 0,J,$,X)}catch($){n.error(`Socket._startWebTransport(): WebTransport connection failed. Error: ${$}`)}}}Buffer.poolSize=134217728;var YO1;((X)=>{X.START="GAMESERVER.START";X.STOP="GAMESERVER.STOP"})(YO1||={});function bC6(J){W8.init().then(()=>{return yK.instance.blockTextureRegistry.preloadAtlas()}).then(()=>{return yK.instance.modelRegistry.preloadModels()}).then(()=>{if(J.length>0)J(yK.instance.worldManager.getDefaultWorld());else J();yK.instance.start()}).catch(($)=>{n.fatalError(`Failed to initialize the game engine, exiting. Error: ${$}`)})}class yK{static _instance;_blockTextureRegistry=eQ.instance;_modelRegistry=k5.instance;_playerManager=F$.instance;_socket=ZB.instance;_worldManager=bK.instance;_webServer=Qz.instance;constructor(){}static get instance(){if(!this._instance)this._instance=new yK;return this._instance}get blockTextureRegistry(){return this._blockTextureRegistry}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(){if($1.globalInstance.emit("GAMESERVER.START",{startedAtMs:performance.now()}),this._webServer.start(),process.env.NODE_ENV!=="production")console.log("---"),console.log("\uD83D\uDFE2 Server Running: You can test & play it at: https://hytopia.com/play")}}var L5=M0(M3(),1);class N3 extends Float32Array{constructor(J,$,X,Y){super([J,$,X,Y])}get determinant(){return L5.mat2.determinant(this)}get frobeniusNorm(){return L5.mat2.frob(this)}static create(){let J=new N3(0,0,0,0);return L5.mat2.identity(J),J}static fromRotation(J){let $=N3.create();return L5.mat2.fromRotation($,J),$}static fromScaling(J){let $=N3.create();return L5.mat2.fromScaling($,J),$}add(J){return L5.mat2.add(this,this,J),this}adjoint(){return L5.mat2.adjoint(this,this),this}clone(){return new N3(this[0],this[1],this[2],this[3])}copy(J){return L5.mat2.copy(this,J),this}equals(J){return L5.mat2.equals(this,J)}exactEquals(J){return L5.mat2.exactEquals(this,J)}identity(){return L5.mat2.identity(this),this}invert(){return L5.mat2.invert(this,this),this}multiply(J){return L5.mat2.mul(this,this,J),this}multiplyScalar(J){return L5.mat2.multiplyScalar(this,this,J),this}rotate(J){return L5.mat2.rotate(this,this,J),this}subtract(J){return L5.mat2.sub(this,this,J),this}toString(){return`[${this[0]},${this[1]}][${this[2]},${this[3]}]`}transpose(){return L5.mat2.transpose(this,this),this}}var k6=M0(M3(),1);class xX extends Float32Array{constructor(J,$,X,Y,Q,W,K,Z,G){super([J,$,X,Y,Q,W,K,Z,G])}get determinant(){return k6.mat3.determinant(this)}get frobeniusNorm(){return k6.mat3.frob(this)}static create(){let J=new xX(0,0,0,0,0,0,0,0,0);return k6.mat3.identity(J),J}static fromMatrix4(J){let $=xX.create();return k6.mat3.fromMat4($,J),$}static fromQuaternion(J){let $=xX.create();return k6.mat3.fromQuat($,J),$}static fromRotation(J){let $=xX.create();return k6.mat3.fromRotation($,J),$}static fromScaling(J){let $=xX.create();return k6.mat3.fromScaling($,J),$}static fromTranslation(J){let $=xX.create();return k6.mat3.fromTranslation($,J),$}add(J){return k6.mat3.add(this,this,J),this}adjoint(){return k6.mat3.adjoint(this,this),this}clone(){return new xX(this[0],this[1],this[2],this[3],this[4],this[5],this[6],this[7],this[8])}copy(J){return k6.mat3.copy(this,J),this}equals(J){return k6.mat3.equals(this,J)}exactEquals(J){return k6.mat3.exactEquals(this,J)}identity(){return k6.mat3.identity(this),this}invert(){return k6.mat3.invert(this,this),this}multiply(J){return k6.mat3.mul(this,this,J),this}multiplyScalar(J){return k6.mat3.multiplyScalar(this,this,J),this}transformVector(J){return J.transformMatrix3(this)}projection(J,$){return k6.mat3.projection(this,J,$),this}rotate(J){return k6.mat3.rotate(this,this,J),this}subtract(J){return k6.mat3.sub(this,this,J),this}toString(){return`[${this[0]},${this[1]},${this[2]}][${this[3]},${this[4]},${this[5]}][${this[6]},${this[7]},${this[8]}]`}transpose(){return k6.mat3.transpose(this,this),this}}var $8=M0(M3(),1);class u4 extends Float32Array{constructor(J,$,X,Y,Q,W,K,Z,G,V,q,z,H,v,F,U){super([J,$,X,Y,Q,W,K,Z,G,V,q,z,H,v,F,U])}get determinant(){return $8.mat4.determinant(this)}get frobeniusNorm(){return $8.mat4.frob(this)}static create(){let J=new u4(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return $8.mat4.identity(J),J}static fromQuaternion(J){let $=u4.create();return $8.mat4.fromQuat($,J),$}static fromRotation(J,$){let X=u4.create();return $8.mat4.fromRotation(X,J,$),X}static fromRotationTranslation(J,$){let X=u4.create();return $8.mat4.fromRotationTranslation(X,J,$),X}static fromRotationTranslationScale(J,$,X){let Y=u4.create();return $8.mat4.fromRotationTranslationScale(Y,J,$,X),Y}static fromRotationTranslationScaleOrigin(J,$,X,Y){let Q=u4.create();return $8.mat4.fromRotationTranslationScaleOrigin(Q,J,$,X,Y),Q}static fromScaling(J){let $=u4.create();return $8.mat4.fromScaling($,J),$}static fromTranslation(J){let $=u4.create();return $8.mat4.fromTranslation($,J),$}static fromXRotation(J){let $=u4.create();return $8.mat4.fromXRotation($,J),$}static fromYRotation(J){let $=u4.create();return $8.mat4.fromYRotation($,J),$}static fromZRotation(J){let $=u4.create();return $8.mat4.fromZRotation($,J),$}add(J){return $8.mat4.add(this,this,J),this}adjoint(){return $8.mat4.adjoint(this,this),this}clone(){return new u4(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(J){return $8.mat4.copy(this,J),this}equals(J){return $8.mat4.equals(this,J)}exactEquals(J){return $8.mat4.exactEquals(this,J)}frustrum(J,$,X,Y,Q,W){return $8.mat4.frustum(this,J,$,X,Y,Q,W),this}identity(){return $8.mat4.identity(this),this}invert(){return $8.mat4.invert(this,this),this}lookAt(J,$,X){return $8.mat4.lookAt(this,J,$,X),this}multiply(J){return $8.mat4.mul(this,this,J),this}multiplyScalar(J){return $8.mat4.multiplyScalar(this,this,J),this}orthographic(J,$,X,Y,Q,W){return $8.mat4.ortho(this,J,$,X,Y,Q,W),this}perspective(J,$,X,Y){return $8.mat4.perspective(this,J,$,X,Y),this}rotate(J,$){return $8.mat4.rotate(this,this,J,$),this}rotateX(J){return $8.mat4.rotateX(this,this,J),this}rotateY(J){return $8.mat4.rotateY(this,this,J),this}rotateZ(J){return $8.mat4.rotateZ(this,this,J),this}scale(J){return $8.mat4.scale(this,this,J),this}subtract(J){return $8.mat4.sub(this,this,J),this}targetTo(J,$,X){return $8.mat4.targetTo(this,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(J){return $8.mat4.translate(this,this,J),this}transpose(){return $8.mat4.transpose(this,this),this}}var b8=M0(M3(),1);class Wz extends Float32Array{constructor(J,$,X,Y){super([J,$,X,Y])}get length(){return b8.quat.length(this)}get squaredLength(){return b8.quat.squaredLength(this)}get magnitude(){return b8.quat.length(this)}get squaredMagnitude(){return b8.quat.squaredLength(this)}get x(){return this[0]}set x(J){this[0]=J}get y(){return this[1]}set y(J){this[1]=J}get z(){return this[2]}set z(J){this[2]=J}get w(){return this[3]}set w(J){this[3]=J}static fromEuler(J,$,X){let Y=b8.quat.fromEuler(new Float32Array(4),J,$,X);return new Wz(Y[0],Y[1],Y[2],Y[3])}static fromQuaternionLike(J){return new Wz(J.x,J.y,J.z,J.w)}clone(){return new Wz(this.x,this.y,this.z,this.w)}conjugate(){return b8.quat.conjugate(this,this),this}copy(J){return b8.quat.copy(this,J),this}dot(J){return b8.quat.dot(this,J)}exponential(){return b8.quat.exp(this,this),this}equals(J){return b8.quat.equals(this,J)}exactEquals(J){return b8.quat.exactEquals(this,J)}getAngle(J){return b8.quat.getAngle(this,J)}identity(){return b8.quat.identity(this),this}invert(){return b8.quat.invert(this,this),this}lerp(J,$){return b8.quat.lerp(this,this,J,$),this}logarithm(){return b8.quat.ln(this,this),this}multiply(J){return b8.quat.multiply(this,this,J),this}transformVector(J){return J.transformQuaternion(this)}normalize(){return b8.quat.normalize(this,this),this}power(J){return b8.quat.pow(this,this,J),this}randomize(){return b8.quat.random(this),this}rotateX(J){return b8.quat.rotateX(this,this,J),this}rotateY(J){return b8.quat.rotateY(this,this,J),this}rotateZ(J){return b8.quat.rotateZ(this,this,J),this}scale(J){return b8.quat.scale(this,this,J),this}setAxisAngle(J,$){return b8.quat.setAxisAngle(this,J,$),this}slerp(J,$){return b8.quat.slerp(this,this,J,$),this}toString(){return`${this.x},${this.y},${this.z},${this.w}`}}var w8=M0(M3(),1);class GB extends Float32Array{constructor(J,$){super([J,$])}get length(){return w8.vec2.length(this)}get squaredLength(){return w8.vec2.squaredLength(this)}get magnitude(){return w8.vec2.length(this)}get squaredMagnitude(){return w8.vec2.squaredLength(this)}get x(){return this[0]}set x(J){this[0]=J}get y(){return this[1]}set y(J){this[1]=J}static create(){return new GB(0,0)}add(J){return w8.vec2.add(this,this,J),this}angle(J){return w8.vec2.angle(this,J)}ceil(){return w8.vec2.ceil(this,this),this}clone(){return new GB(this.x,this.y)}copy(J){return w8.vec2.copy(this,J),this}distance(J){return w8.vec2.distance(this,J)}divide(J){return w8.vec2.divide(this,this,J),this}dot(J){return w8.vec2.dot(this,J)}equals(J){return w8.vec2.equals(this,J)}exactEquals(J){return w8.vec2.exactEquals(this,J)}floor(){return w8.vec2.floor(this,this),this}invert(){return w8.vec2.inverse(this,this),this}lerp(J,$){return w8.vec2.lerp(this,this,J,$),this}max(J){return w8.vec2.max(this,this,J),this}min(J){return w8.vec2.min(this,this,J),this}multiply(J){return w8.vec2.mul(this,this,J),this}negate(){return w8.vec2.negate(this,this),this}normalize(){return w8.vec2.normalize(this,this),this}randomize(J){return w8.vec2.random(this,J),this}rotate(J,$){return w8.vec2.rotate(this,this,J,$),this}round(){return w8.vec2.round(this,this),this}scale(J){return w8.vec2.scale(this,this,J),this}scaleAndAdd(J,$){return w8.vec2.scaleAndAdd(this,this,J,$),this}subtract(J){return w8.vec2.sub(this,this,J),this}toString(){return`${this.x},${this.y}`}transformMatrix2(J){return w8.vec2.transformMat2(this,this,J),this}transformMatrix3(J){return w8.vec2.transformMat3(this,this,J),this}transformMatrix4(J){return w8.vec2.transformMat4(this,this,J),this}zero(){return w8.vec2.zero(this),this}}var z8=M0(M3(),1);class Kz extends Float32Array{constructor(J,$,X){super([J,$,X])}get length(){return z8.vec3.length(this)}get squaredLength(){return z8.vec3.squaredLength(this)}get magnitude(){return z8.vec3.length(this)}get squaredMagnitude(){return z8.vec3.squaredLength(this)}get x(){return this[0]}set x(J){this[0]=J}get y(){return this[1]}set y(J){this[1]=J}get z(){return this[2]}set z(J){this[2]=J}static create(){return new Kz(0,0,0)}static fromVector3Like(J){return new Kz(J.x,J.y,J.z)}add(J){return z8.vec3.add(this,this,J),this}ceil(){return z8.vec3.ceil(this,this),this}clone(){return new Kz(this.x,this.y,this.z)}copy(J){return z8.vec3.copy(this,J),this}cross(J){return z8.vec3.cross(this,this,J),this}distance(J){return z8.vec3.distance(this,J)}divide(J){return z8.vec3.div(this,this,J),this}dot(J){return z8.vec3.dot(this,J)}equals(J){return z8.vec3.equals(this,J)}exactEquals(J){return z8.vec3.exactEquals(this,J)}floor(){return z8.vec3.floor(this,this),this}invert(){return z8.vec3.inverse(this,this),this}lerp(J,$){return z8.vec3.lerp(this,this,J,$),this}max(J){return z8.vec3.max(this,this,J),this}min(J){return z8.vec3.min(this,this,J),this}multiply(J){return z8.vec3.mul(this,this,J),this}negate(){return z8.vec3.negate(this,this),this}normalize(){return z8.vec3.normalize(this,this),this}randomize(J){return z8.vec3.random(this,J),this}rotateX(J,$){return z8.vec3.rotateX(this,this,J,$),this}rotateY(J,$){return z8.vec3.rotateY(this,this,J,$),this}rotateZ(J,$){return z8.vec3.rotateZ(this,this,J,$),this}round(){return z8.vec3.round(this,this),this}scale(J){return z8.vec3.scale(this,this,J),this}scaleAndAdd(J,$){return z8.vec3.scaleAndAdd(this,this,J,$),this}subtract(J){return z8.vec3.sub(this,this,J),this}toString(){return`${this.x},${this.y},${this.z}`}transformMatrix3(J){return z8.vec3.transformMat3(this,this,J),this}transformMatrix4(J){return z8.vec3.transformMat4(this,this,J),this}transformQuaternion(J){return z8.vec3.transformQuat(this,this,J),this}zero(){return z8.vec3.zero(this),this}}var dR1=M0(gR1(),1);var pR1=0.099856;class VB extends iK{faceSpeed=0;idleLoopedAnimations=[];idleLoopedAnimationsSpeed;jumpOneshotAnimations=[];moveLoopedAnimations=[];moveLoopedAnimationsSpeed;moveSpeed=0;_faceTarget;_jumpHeight=0;_moveCompletesWhenStuck=!1;_moveIgnoreAxes={};_moveStartMoveAnimations=!1;_moveStartIdleAnimationsOnCompletion=!0;_moveStoppingDistanceSquared=pR1;_moveStuckAccumulatorMs=0;_moveStuckLastPosition;_moveTarget;_onFace;_onFaceComplete;_onMove;_onMoveComplete;_stopFaceRequested=!1;_stopMoveRequested=!1;constructor(J={}){super();this.idleLoopedAnimations=J.idleLoopedAnimations??this.idleLoopedAnimations,this.idleLoopedAnimationsSpeed=J.idleLoopedAnimationsSpeed??this.idleLoopedAnimationsSpeed,this.jumpOneshotAnimations=J.jumpOneshotAnimations??this.jumpOneshotAnimations,this.moveLoopedAnimations=J.moveLoopedAnimations??this.moveLoopedAnimations,this.moveLoopedAnimationsSpeed=J.moveLoopedAnimationsSpeed??this.moveLoopedAnimationsSpeed}spawn(J){super.spawn(J),this._startIdleAnimations(J)}face(J,$,X){this._faceTarget=J,this.faceSpeed=$,this._onFace=X?.faceCallback,this._onFaceComplete=X?.faceCompleteCallback}jump(J){this._jumpHeight=J}move(J,$,X){this.moveSpeed=$,this._moveCompletesWhenStuck=X?.moveCompletesWhenStuck??!1,this._moveIgnoreAxes=X?.moveIgnoreAxes??{},this._moveStartIdleAnimationsOnCompletion=X?.moveStartIdleAnimationsOnCompletion??!0,this._moveStartMoveAnimations=!0,this._moveStoppingDistanceSquared=X?.moveStoppingDistance?X.moveStoppingDistance**2:pR1,this._moveTarget=J,this._onMove=X?.moveCallback,this._onMoveComplete=X?.moveCompleteCallback,this._moveStuckAccumulatorMs=0,this._moveStuckLastPosition=void 0}stopFace(){this._stopFaceRequested=!0}stopMove(){this._stopMoveRequested=!0}tick(J,$){if(super.tick(J,$),!this._moveTarget&&!this._faceTarget&&!this._jumpHeight)return;if(this._moveStartMoveAnimations)this._startMoveAnimations(J),this._moveStartMoveAnimations=!1;let X=$/1000,Y=J.position;if(J.isDynamic&&this._jumpHeight>0){let Q=Math.abs(J.world.simulation.gravity.y),W=Math.sqrt(2*Q*this._jumpHeight);J.applyImpulse({x:0,y:W*J.mass,z:0}),this._jumpHeight=0,this._startJumpAnimations(J)}if(this._moveTarget){let Q={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},W=Q.x*Q.x+Q.y*Q.y+Q.z*Q.z,K=!1;if(this._moveCompletesWhenStuck){if(this._moveStuckAccumulatorMs+=$,this._moveStuckAccumulatorMs>=500){if(this._moveStuckLastPosition){let Z=Y.x-this._moveStuckLastPosition.x,G=Y.y-this._moveStuckLastPosition.y,V=Y.z-this._moveStuckLastPosition.z;K=Math.sqrt(Z*Z+G*G+V*V)<this.moveSpeed*0.1}this._moveStuckLastPosition=Y,this._moveStuckAccumulatorMs=0}}if(W>this._moveStoppingDistanceSquared&&!this._stopMoveRequested&&!K){let Z=Math.sqrt(W),G=this.moveSpeed*X,q=Math.min(Z,G)/Z,z={x:Y.x+Q.x*q,y:Y.y+Q.y*q,z:Y.z+Q.z*q};if(J.setPosition(z),this._onMove)this._onMove(z,this._moveTarget)}else{if(this._moveStuckAccumulatorMs=0,this._moveStuckLastPosition=void 0,this._moveTarget=void 0,this._stopMoveRequested=!1,this._moveStartIdleAnimationsOnCompletion)this._startIdleAnimations(J);if(this._onMoveComplete){let Z=this._onMoveComplete;this._onMove=void 0,this._onMoveComplete=void 0,Z(Y)}}}if(this._faceTarget){let Q={x:this._faceTarget.x-Y.x,z:this._faceTarget.z-Y.z},W=Math.atan2(-Q.x,-Q.z),K=J.rotation,Z=Math.atan2(2*(K.w*K.y),1-2*(K.y*K.y)),G=W-Z;while(G>Math.PI)G-=2*Math.PI;while(G<-Math.PI)G+=2*Math.PI;if(Math.abs(G)>0.01&&!this._stopFaceRequested){let V=this.faceSpeed*X,q=Math.abs(G)<V?G:Math.sign(G)*V,H=(Z+q)/2,v={x:0,y:Math.fround(Math.sin(H)),z:0,w:Math.fround(Math.cos(H))};if(J.setRotation(v),this._onFace)this._onFace(K,v)}else if(this._faceTarget=void 0,this._stopFaceRequested=!1,this._onFaceComplete){let V=this._onFaceComplete;this._onFace=void 0,this._onFaceComplete=void 0,V(J.rotation)}}}_startIdleAnimations(J){if(this.idleLoopedAnimationsSpeed)J.setModelAnimationsPlaybackRate(this.idleLoopedAnimationsSpeed);J.stopModelAnimations(this.moveLoopedAnimations),J.stopModelAnimations(this.jumpOneshotAnimations),J.startModelLoopedAnimations(this.idleLoopedAnimations)}_startJumpAnimations(J){J.stopModelAnimations(this.moveLoopedAnimations),J.stopModelAnimations(this.idleLoopedAnimations),J.startModelOneshotAnimations(this.jumpOneshotAnimations)}_startMoveAnimations(J){if(this.moveLoopedAnimationsSpeed)J.setModelAnimationsPlaybackRate(this.moveLoopedAnimationsSpeed);J.stopModelAnimations(this.jumpOneshotAnimations),J.stopModelAnimations(this.idleLoopedAnimations),J.startModelLoopedAnimations(this.moveLoopedAnimations)}}class qn extends VB{_debug=!1;_entity;_maxFall=0;_maxJump=0;_maxOpenSetIterations=200;_onPathfindAbort;_onPathfindComplete;_onWaypointMoveComplete;_onWaypointMoveSkipped;_speed=0;_target;_verticalPenalty=0;_waypoints=[];_waypointNextIndex=0;_waypointStoppingDistance;_waypointTimeoutMs=2000;constructor(J={}){super(J)}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(J,$,X){if(this._target=J,this._speed=$,this._debug=X?.debug??!1,this._maxFall=X?.maxFall?-Math.abs(X.maxFall):0,this._maxJump=X?.maxJump?Math.abs(X.maxJump):0,this._maxOpenSetIterations=X?.maxOpenSetIterations??200,this._onPathfindAbort=X?.pathfindAbortCallback,this._onPathfindComplete=X?.pathfindCompleteCallback,this._onWaypointMoveComplete=X?.waypointMoveCompleteCallback,this._onWaypointMoveSkipped=X?.waypointMoveSkippedCallback,this._verticalPenalty=X?.verticalPenalty??0,this._waypoints=[],this._waypointNextIndex=0,this._waypointStoppingDistance=X?.waypointStoppingDistance,this._waypointTimeoutMs=X?.waypointTimeoutMs??2000/$,!this._calculatePath())return!1;return this._moveToNextWaypoint(),!0}attach(J){super.attach(J),this._entity=J}detach(J){super.detach(J),this._entity=void 0}_calculatePath(){if(!this._target||!this._entity?.world)return n.error("PathfindingEntityController._calculatePath: No target or world"),!1;let J=this._entity.height,$=this._findGroundedStart();if(!$){if(this._debug)n.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-$.x),Q=Math.abs(X.y-$.y),W=Math.abs(X.z-$.z);if(Y<=2&&Q<=2&&W<=2&&!this._isNeighborCoordinateBlocked($,X,this._entity.height))return this._waypoints=[{x:$.x+0.5,y:$.y+J/2,z:$.z+0.5},{x:X.x+0.5,y:X.y+J/2,z:X.z+0.5}],!0;if($.x===X.x&&$.y===X.y&&$.z===X.z)return this._waypoints=[{x:$.x+0.5,y:$.y+J/2,z:$.z+0.5}],!0;let Z=this._coordinateToKey($),G=new Map,V=new Map([[Z,0]]),q=new Map([[Z,this._pathfindingHeuristic($,X)]]),z=new Set,H=new dR1.Heap((M,R)=>{let N=q.get(M[0])??1/0,L=q.get(R[0])??1/0;return N-L});H.push([Z,$]);let v=[{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}],F=[];for(let M=this._maxJump;M>=this._maxFall;M--){if(M===0)continue;let R=Math.abs($.y+M-X.y);F.push({y:M,distanceToTargetY:R})}F.sort((M,R)=>M.distanceToTargetY-R.distanceToTargetY);let U=[...v,...F.flatMap(({y:M})=>v.map((R)=>({...R,y:M})))],j=0,B=Math.abs(X.x-$.x)+Math.abs(X.y-$.y)+Math.abs(X.z-$.z),w=Math.min(this._maxOpenSetIterations,B*20);while(!H.isEmpty()&&j<w){j++;let[M,R]=H.pop();if(R.x===X.x&&R.y===X.y&&R.z===X.z){let O=this._reconstructPath(G,R);if(this._waypoints=O.map((x)=>({x:x.x+0.5,y:x.y+J/2,z:x.z+0.5})),this._debug)console.log(`PathfindingEntityController._calculatePath: Path found after ${j} open set iterations. Start: ${this._coordinateToKey($)}, Target: ${this._coordinateToKey(this._target)}`);return!0}z.add(M);let N=V.get(M),L=new Map;for(let O of U){let x=`${O.x},${O.z}`,T=O.y<0;if(T&&L.has(x))continue;let S={x:R.x+O.x,y:R.y+O.y,z:R.z+O.z};if(Math.abs(X.x-S.x)+Math.abs(X.y-S.y)+Math.abs(X.z-S.z)>B*1.5)continue;let I=this._coordinateToKey(S);if(z.has(I))continue;let k=this._isNeighborCoordinateBlocked(R,S,this._entity.height);if(T&&k){L.set(x,!0);continue}if(k)continue;let E=Math.abs(O.x),c=Math.abs(O.y),A=Math.abs(O.z),h=c===0?0:this._verticalPenalty,_=(Math.max(E,c,A)===1&&E+c+A>1?1.4:1)+h,m=N+_,p=V.get(I)??1/0;if(m>=p)continue;G.set(I,R),V.set(I,m);let g=m+this._pathfindingHeuristic(S,X);q.set(I,g),H.push([I,S])}}if(j>=w){if(this._onPathfindAbort?.(),this._debug)n.warning(`PathfindingEntityController._calculatePath: Maximum open set iterations reached (${w}), path search aborted. Start: ${this._coordinateToKey($)}, Target: ${this._coordinateToKey(this._target)}`)}else if(this._debug)n.warning(`PathfindingEntityController._calculatePath: No valid path found. Start: ${this._coordinateToKey($)}, Target: ${this._coordinateToKey(this._target)}`);return this._target=void 0,this._waypoints=[],!1}_reconstructPath(J,$){let X=[$],Y=$;while(J.has(this._coordinateToKey(Y)))Y=J.get(this._coordinateToKey(Y)),X.unshift(Y);return X}_coordinateToKey(J){return`${J.x},${J.y},${J.z}`}_moveToNextWaypoint(){let J=this._waypointNextIndex>0?this._waypoints[this._waypointNextIndex-1]:void 0,$=this._waypoints[this._waypointNextIndex];if(!$||!this._entity)return;let X=0;if(this._entity.isDynamic&&J&&$.y>J.y){let Y=$.y-J.y,Q=Math.min(Y,this._maxJump)+0.75;this.jump(Q);let W=Math.abs(this._entity.world.simulation.gravity.y),K=Math.sqrt(2*W*Q),Z=J.x+0.5,G=J.z+0.5,V=$.x+0.5,q=$.z+0.5,z=V-Z,H=q-G,v=Math.sqrt(z*z+H*H),F=K/W,U=v/this._speed;X=Math.min(F*0.8,U)*1000}setTimeout(()=>{if(!this._entity)return;let Y=Date.now();this.face($,this._speed),this.move($,this._speed,{moveCompletesWhenStuck:!0,moveIgnoreAxes:{y:this._entity.isDynamic},moveStartIdleAnimationsOnCompletion:this._waypointNextIndex===this._waypoints.length-1,moveStoppingDistance:this._waypointStoppingDistance,moveCallback:()=>{if(Date.now()-Y>this._waypointTimeoutMs&&this._waypointNextIndex<this._waypoints.length-1)this._onWaypointMoveSkipped?.($,this._waypointNextIndex),this._waypointNextIndex++,this._moveToNextWaypoint()},moveCompleteCallback:()=>{if(this._waypointNextIndex<this._waypoints.length-1)this._onWaypointMoveComplete?.($,this._waypointNextIndex),this._waypointNextIndex++,this._moveToNextWaypoint();else this._onPathfindComplete?.()}})},X)}_pathfindingHeuristic(J,$){return Math.abs(J.x-$.x)+Math.abs(J.y-$.y)+Math.abs(J.z-$.z)}_isNeighborCoordinateBlocked(J,$,X){if(!this._entity?.world)return!1;let Y=this._entity.world,Q=Math.floor($.x),W=Math.floor($.y),K=Math.floor($.z),Z=Math.floor(J.x),G=Math.floor(J.z);if(!Y.chunkLattice.hasBlock({x:Q,y:W-1,z:K}))return!0;for(let V=0;V<X;V++)if(Y.chunkLattice.hasBlock({x:Q,y:W+V,z:K}))return!0;if(Q!==Z&&K!==G)for(let V=0;V<X;V++){let q=Y.chunkLattice.hasBlock({x:Q,y:W+V,z:G}),z=Y.chunkLattice.hasBlock({x:Z,y:W+V,z:K});if(q||z)return!0}return!1}_findGroundedStart(){if(!this._entity?.world)return;let{x:J,y:$,z:X}=this._entity.position,Y={x:Math.floor(J),y:Math.floor($),z:Math.floor(X)};for(let Q=0;Q<=Math.abs(this._maxFall);Q++)if(this._entity.world.chunkLattice.hasBlock({...Y,y:Y.y-Q-1}))return{...Y,y:Y.y-Q};return}}export{bC6 as startServer,$O1 as WorldManagerEvent,bK as WorldManager,JO1 as WorldLoopEvent,WB as WorldLoop,$n as WorldEvent,KB as World,ai as WebServerEvent,Qz as WebServer,Kz as Vector3,GB as Vector2,QB as Ticker,B3 as TelemetrySpanOperation,T6 as Telemetry,Jn as SimulationEvent,$B as Simulation,VB as SimpleEntityController,YB as SceneUIManager,hh as SceneUIEvent,wU as SceneUI,x78 as SUPPORTED_INPUTS,kF as RigidBodyType,FW as RigidBody,Wz as Quaternion,cO as PlayerUIEvent,zU as PlayerUI,XO1 as PlayerManagerEvent,F$ as PlayerManager,vU as PlayerEvent,o$ as PlayerEntity,Bq0 as PlayerCameraMode,Sh as PlayerCameraEvent,HU as PlayerCamera,kq as Player,CW as PersistenceManager,qn as PathfindingEntityController,XB as ParticleEmitterManager,ri as ParticleEmitterEvent,ti as ParticleEmitter,Oq0 as PLAYER_ROTATION_UPDATE_THRESHOLD,Nq0 as PLAYER_POSITION_UPDATE_THRESHOLD_SQ,k5 as ModelRegistry,u4 as Matrix4,xX as Matrix3,N3 as Matrix2,eN1 as LightType,JB as LightManager,si as LightEvent,oi as Light,w5 as IterationMap,YO1 as GameServerEvent,yK as GameServer,$1 as EventRouter,n as ErrorHandler,LU as EntityManager,BU as EntityEvent,b6 as Entity,Mq0 as ENTITY_ROTATION_UPDATE_THRESHOLD,Lq0 as ENTITY_POSITION_UPDATE_THRESHOLD_SQ,m8 as DefaultPlayerEntityController,fh as DefaultPlayerEntity,wq0 as DEFAULT_ENTITY_RIGID_BODY_OPTIONS,cJ as CollisionGroupsBuilder,OZ as CollisionGroup,Gq as ColliderShape,jU as ColliderMap,S9 as Collider,Cc as CoefficientCombineRule,_h as ChunkLatticeEvent,UU as ChunkLattice,X9 as Chunk,FU as ChatManager,Ah as ChatEvent,kc as BlockTypeRegistryEvent,EF as BlockTypeRegistry,Tc as BlockTypeEvent,A9 as BlockType,eQ as BlockTextureRegistry,R3 as Block,Nn as BaseEntityControllerEvent,iK as BaseEntityController,vz as AudioManager,rC as AudioEvent,zz as Audio,dK as AssetsLibrary};
554
+ -----END PRIVATE KEY-----`;var SC=process.env.PORT??8080,ni="0.14.1",ai;((Q)=>{Q.READY="WEBSERVER.READY";Q.STOPPED="WEBSERVER.STOPPED";Q.ERROR="WEBSERVER.ERROR";Q.UPGRADE="WEBSERVER.UPGRADE"})(ai||={});class Qz extends $1{static instance=new Qz;_webserver=IC.default();_internalHttpServer;constructor(){super();this._webserver.use(($,X,Y)=>{X.header("Access-Control-Allow-Origin","*"),Y()}),this._webserver.get("/",($,X)=>{X.json({status:"OK",version:ni,runtime:"node"})}),this._webserver.use(IC.default.static("assets",{dotfiles:"allow"}));let J=dK.instance.assetsLibraryPath;if(process.env.NODE_ENV!=="production"&&J)this._webserver.use(($,X,Y)=>{let Q=kC6.join(J,$.path);dK.instance.syncAsset(Q),Y()}),this._webserver.use(IC.default.static(J,{dotfiles:"allow"}))}start(){if(!this._internalHttpServer)this._internalHttpServer=TC6.createServer({key:EC,cert:kC},this._webserver),this._internalHttpServer.on("upgrade",this._onUpgrade),this._internalHttpServer.on("error",this._onError),this._internalHttpServer.on("close",this._onStopped);else n.warning("WebServer.start(): server already started!");this._internalHttpServer.listen(SC,this._onStarted),console.info(`WebServer.start(): Server running on port ${SC}.`)}stop(){if(this._internalHttpServer)return new Promise((J,$)=>{this._internalHttpServer.close((X)=>{if(X)$(X);else J(!0)})});else return n.warning("WebServer.stop(): server not started."),Promise.resolve(!1)}_onStarted=()=>{this.emitWithGlobal("WEBSERVER.READY",{})};_onUpgrade=(J,$,X)=>{this.emitWithGlobal("WEBSERVER.UPGRADE",{req:J,socket:$,head:X})};_onError=(J)=>{n.error(`WebServer._onError(): ${J.message}`),this.emitWithGlobal("WEBSERVER.ERROR",{error:J})};_onStopped=()=>{this.emitWithGlobal("WEBSERVER.STOPPED",{})}}var B3;((U)=>{U.BUILD_PACKETS="build_packets";U.ENTITIES_EMIT_UPDATES="entities_emit_updates";U.ENTITIES_TICK="entities_tick";U.NETWORK_SYNCHRONIZE="network_synchronize";U.NETWORK_SYNCHRONIZE_CLEANUP="network_synchronize_cleanup";U.PHYSICS_CLEANUP="physics_cleanup";U.PHYSICS_STEP="physics_step";U.SEND_ALL_PACKETS="send_all_packets";U.SEND_PACKETS="send_packets";U.SERIALIZE_FREE_BUFFERS="serialize_free_buffers";U.SERIALIZE_PACKETS="serialize_packets";U.SERIALIZE_PACKETS_ENCODE="serialize_packets_encode";U.SIMULATION_STEP="simulation_step";U.TICKER_TICK="ticker_tick";U.WORLD_TICK="world_tick"})(B3||={});class T6{static getProcessStats(J=!1){let $=process.memoryUsage(),X={jsHeapSizeMb:{value:$.heapUsed/1024/1024,unit:"megabyte"},jsHeapCapacityMb:{value:$.heapTotal/1024/1024,unit:"megabyte"},jsHeapUsagePercent:{value:$.heapUsed/$.heapTotal,unit:"percent"},processHeapSizeMb:{value:$.heapUsed/1024/1024,unit:"megabyte"},rssSizeMb:{value:$.rss/1024/1024,unit:"megabyte"}};if(J)return X;return Object.fromEntries(Object.entries(X).map(([Y,Q])=>[Y,Q.value]))}static initializeSentry(J,$=50){_P({dsn:J,release:ni,environment:process.env.NODE_ENV||"development",tracesSampleRate:1,initialScope:{tags:{gameId:process.env.HYTOPIA_GAME_ID??"unknown",gameSlug:process.env.HYTOPIA_GAME_SLUG??"unknown",lobbyId:process.env.HYTOPIA_LOBBY_ID??"unknown",region:process.env.REGION??"unknown"}},beforeSend:(X)=>{return X.extra=T6.getProcessStats(),X},beforeSendTransaction:(X)=>{if(X.contexts?.trace?.op==="ticker_tick"){let Q=X?.start_timestamp,W=X?.timestamp;if(!Q||!W)return null;if((W-Q)*1000>$)return X.measurements=T6.getProcessStats(!0),X}return null}})}static startSpan(J,$){if(nU())return h7({attributes:J.attributes,name:J.operation,op:J.operation},$);else return $()}static sentry(){return hp}}if(!gO)console.warn("Connection: msgpackr native acceleration is not enabled, using fallback implementation.");var tN1=new aZ({useFloat32:RU.ALWAYS}),IC6=5000;class v$ extends $1{static _cachedPacketsSerializedBuffer=new Map;_closeTimeout=null;_ws;_wsBinding=!1;_wt;_wtBinding=!1;_wtReliableReader;_wtReliableWriter;_wtUnreliableReader;_wtUnreliableWriter;id;constructor(J,$,X){super();this.id=TH0(),this.onPacket(_0.PacketId.HEARTBEAT,this._onHeartbeatPacket);let Y=()=>{$1.globalInstance.emit("CONNECTION.OPENED",{connection:this,session:X})};if(J)this.bindWs(J),Y();else if($)this.bindWt($).then(Y).catch((Q)=>{this._onClose(),n.error(`Connection.constructor(): Failed to bind WebTransport. Error: ${Q}`)})}static clearCachedPacketsSerializedBuffers(){if(v$._cachedPacketsSerializedBuffer.size>0)v$._cachedPacketsSerializedBuffer.clear()}static serializePackets(J){for(let X of J)if(!_0.isValidPacket(X))return n.error(`Connection.serializePackets(): Invalid packet payload: ${JSON.stringify(X)}`);let $=v$._cachedPacketsSerializedBuffer.get(J);if($)return $;return T6.startSpan({operation:"serialize_packets",attributes:{packets:J.length,packetIds:J.map((X)=>X[0]).join(",")}},(X)=>{let Y=tN1.pack(J);if(Y.byteLength>65536)Y=EC6(Y,{level:1});return X?.setAttribute("serializedBytes",Y.byteLength),v$._cachedPacketsSerializedBuffer.set(J,Y),Y})}bindWs(J){this._wsBinding=!0;let $=this._handleReconnect();if(this._cleanupConnections(),this._ws=J,this._ws.binaryType="nodebuffer",this._ws.onmessage=(X)=>this._onMessage(X.data),this._ws.onclose=this._onClose,this._ws.onerror=this._onError,this._wsBinding=!1,this._signalConnectionId(),$)this.emitWithGlobal("CONNECTION.RECONNECTED",{connection:this})}async bindWt(J){this._wtBinding=!0;let $=this._handleReconnect();this._cleanupConnections(),J.userData.onclose=this._onClose,J.closed.catch(()=>{}).finally(()=>J.userData.onclose?.()),this._wt=J,await this._wt.ready;let X=this._wt.incomingBidirectionalStreams.getReader();try{let{value:Y}=await X.read();if(Y)this._wtReliableReader=Y.readable,this._wtReliableWriter=Y.writable.getWriter()}finally{X.releaseLock()}if(this._wtUnreliableReader=this._wt.datagrams.readable,this._wtUnreliableWriter=this._wt.datagrams.createWritable().getWriter(),(async()=>{if(!this._wtReliableReader)return;let Y=this._wt,Q=_0.createPacketBufferUnframer();for await(let W of this._wtReliableReader){if(Y!==this._wt)return;for(let K of Q(W))this._onMessage(K)}})().catch(()=>this._wt?.close()),(async()=>{if(!this._wtUnreliableReader)return;let Y=this._wt;for await(let Q of this._wtUnreliableReader){if(Y!==this._wt)return;this._onMessage(Q)}})().catch(()=>this._wt?.close()),this._wtBinding=!1,this._signalConnectionId(),$)this.emitWithGlobal("CONNECTION.RECONNECTED",{connection:this})}disconnect(){try{this._ws?.close(),this._wt?.close()}catch(J){n.error(`Connection.disconnect(): Connection disconnect failed. Error: ${J}`)}}onPacket(J,$){this.on("CONNECTION.PACKET_RECEIVED",({packet:X})=>{if(X[0]===J)$(X)})}send(J,$=!0){if(this._closeTimeout||this._wsBinding||this._wtBinding)return;if(!this._ws&&!this._wt)return;let X=this._ws&&this._ws.readyState===Cq.default.OPEN,Y=this._wt&&(this._wt.state==="connected"||this._wt.state==="draining");if(!X&&!Y)return;T6.startSpan({operation:"send_packets"},()=>{try{let Q=v$.serializePackets(J);if(!Q)return;if(Y)if($)this._wtReliableWriter?.write(_0.framePacketBuffer(Q)).catch(()=>{n.error("Connection.send(): WebTransport reliable write failed, connection closing?")});else this._wtUnreliableWriter?.write(Q).catch(()=>{n.error("Connection.send(): WebTransport unreliable write failed, connection closing?")});else this._ws.send(Q);this.emitWithGlobal("CONNECTION.PACKETS_SENT",{connection:this,packets:J})}catch(Q){n.error(`Connection.send(): Packet send failed. Error: ${Q}`)}})}_onHeartbeatPacket=()=>{this.send([_0.createPacket(_0.bidirectionalPackets.heartbeatPacketDefinition,null)],!0)};_onMessage=(J)=>{try{let $=this._deserialize(J);if(!$)return;this.emitWithGlobal("CONNECTION.PACKET_RECEIVED",{connection:this,packet:$})}catch($){n.error(`Connection._ws.onmessage(): Error: ${$}`)}};_onClose=()=>{this.emitWithGlobal("CONNECTION.DISCONNECTED",{connection:this}),this._closeTimeout=setTimeout(()=>{this.emitWithGlobal("CONNECTION.CLOSED",{connection:this}),this.offAll()},IC6)};_onError=(J)=>{this.emitWithGlobal("CONNECTION.ERROR",{connection:this,error:J})};_cleanupConnections(){if(this._ws)this._ws.onmessage=()=>{},this._ws.onclose=()=>{},this._ws.onerror=()=>{};if(this._wt)this._wt.userData.onclose=()=>{};this._signalKill(),this._ws=void 0,this._wt=void 0,this._wtReliableReader=void 0,this._wtReliableWriter=void 0,this._wtUnreliableReader=void 0,this._wtUnreliableWriter=void 0}_deserialize(J){let $=tN1.unpack(J);if(!$||typeof $!=="object"||typeof $[0]!=="number")return n.error(`Connection._deserialize(): Invalid packet format. Packet: ${JSON.stringify($)}`);if(!_0.isValidPacket($))return n.error(`Connection._deserialize(): Invalid packet payload. Packet: ${JSON.stringify($)}`);return $}_handleReconnect(){let J=!!this._ws||!!this._wt;if(J&&this._closeTimeout)clearTimeout(this._closeTimeout),this._closeTimeout=null;return J}_signalConnectionId(){this.send([_0.createPacket(_0.bidirectionalPackets.connectionPacketDefinition,{i:this.id})])}_signalKill(){this.send([_0.createPacket(_0.bidirectionalPackets.connectionPacketDefinition,{k:!0})])}}class JB{_lights=new Map;_nextLightId=1;_world;constructor(J){this._world=J}get world(){return this._world}despawnEntityAttachedLights(J){this.getAllEntityAttachedLights(J).forEach(($)=>{$.despawn()})}getAllLights(){return Array.from(this._lights.values())}getAllEntityAttachedLights(J){return this.getAllLights().filter(($)=>$.attachedToEntity===J)}registerLight(J){if(J.id!==void 0)return J.id;let $=this._nextLightId;return this._lights.set($,J),this._nextLightId++,$}unregisterLight(J){if(J.id===void 0)return;this._lights.delete(J.id)}}class w5{_map=new Map;_values=[];_isDirty=!1;get size(){return this._map.size}get valuesArray(){if(this._isDirty)this._syncArray();return this._values}get(J){return this._map.get(J)}set(J,$){let X=this._map.has(J);if(this._map.set(J,$),!X)this._values.push($);else this._isDirty=!0;return this}has(J){return this._map.has(J)}delete(J){let $=this._map.delete(J);if($)this._isDirty=!0;return $}clear(){this._map.clear(),this._values.length=0,this._isDirty=!1}forEach(J,$){this._map.forEach((X,Y)=>{J.call($,X,Y,this)})}keys(){return this._map.keys()}values(){return this._map.values()}entries(){return this._map.entries()}[Symbol.iterator](){return this._map[Symbol.iterator]()}_syncArray(){this._values.length=0;for(let J of this._map.values())this._values.push(J);this._isDirty=!1}}var eN1;((X)=>{X[X.POINTLIGHT=0]="POINTLIGHT";X[X.SPOTLIGHT=1]="SPOTLIGHT"})(eN1||={});var si;((H)=>{H.DESPAWN="LIGHT.DESPAWN";H.SET_ANGLE="LIGHT.SET_ANGLE";H.SET_ATTACHED_TO_ENTITY="LIGHT.SET_ATTACHED_TO_ENTITY";H.SET_COLOR="LIGHT.SET_COLOR";H.SET_DISTANCE="LIGHT.SET_DISTANCE";H.SET_INTENSITY="LIGHT.SET_INTENSITY";H.SET_OFFSET="LIGHT.SET_OFFSET";H.SET_PENUMBRA="LIGHT.SET_PENUMBRA";H.SET_POSITION="LIGHT.SET_POSITION";H.SET_TRACKED_ENTITY="LIGHT.SET_TRACKED_ENTITY";H.SET_TRACKED_POSITION="LIGHT.SET_TRACKED_POSITION";H.SPAWN="LIGHT.SPAWN"})(si||={});class oi extends $1{_id;_angle;_attachedToEntity;_color;_distance;_intensity;_offset;_penumbra;_position;_trackedEntity;_trackedPosition;_type;_world;constructor(J){if(!!J.attachedToEntity===!!J.position)n.fatalError("Either attachedToEntity or position must be set, but not both.");super();n.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=J.angle,this._attachedToEntity=J.attachedToEntity,this._color=J.color??{r:255,g:255,b:255},this._distance=J.distance,this._intensity=J.intensity??1,this._offset=J.offset,this._penumbra=J.penumbra,this._position=J.position,this._trackedEntity=J.trackedEntity,this._trackedPosition=J.trackedPosition,this._type=J.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(J){if(this._angle===J)return;if(this._angle=J,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ANGLE",{light:this,angle:J})}setAttachedToEntity(J){if(!J.isSpawned)return n.error(`Light.setAttachedToEntity(): Entity ${J.id} is not spawned!`);if(this._attachedToEntity===J)return;if(this._attachedToEntity=J,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ATTACHED_TO_ENTITY",{light:this,entity:J})}setColor(J){if(this._color.r===J.r&&this._color.g===J.g&&this._color.b===J.b)return;if(this._color=J,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_COLOR",{light:this,color:J})}setDistance(J){if(this._distance===J)return;if(this._distance=J,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_DISTANCE",{light:this,distance:J})}setIntensity(J){if(this._intensity===J)return;if(this._intensity=J,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_INTENSITY",{light:this,intensity:J})}setOffset(J){if(this._offset&&this._offset.x===J.x&&this._offset.y===J.y&&this._offset.z===J.z)return;if(this._offset=J,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_OFFSET",{light:this,offset:J})}setPenumbra(J){if(this._penumbra===J)return;if(this._penumbra=J,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_PENUMBRA",{light:this,penumbra:J})}setPosition(J){if(this._position&&this._position.x===J.x&&this._position.y===J.y&&this._position.z===J.z)return;if(this._position=J,this._attachedToEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_POSITION",{light:this,position:J})}setTrackedEntity(J){if(!J.isSpawned)return n.error(`Light.setTrackedEntity(): Entity ${J.id} is not spawned!`);if(this._trackedEntity===J)return;if(this._trackedEntity=J,this._trackedPosition=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_ENTITY",{light:this,entity:J})}setTrackedPosition(J){if(this._trackedPosition===J)return;if(this._trackedPosition=J,this._trackedEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_POSITION",{light:this,position:J})}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(J){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return n.error(`Light.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning Light!`);this._id=J.lightManager.registerLight(this),this._world=J,this.emitWithWorld(J,"LIGHT.SPAWN",{light:this})}serialize(){return V1.serializeLight(this)}}var ri;((A)=>{A.BURST="PARTICLE_EMITTER.BURST";A.DESPAWN="PARTICLE_EMITTER.DESPAWN";A.SET_ALPHA_TEST="PARTICLE_EMITTER.SET_ALPHA_TEST";A.SET_ATTACHED_TO_ENTITY="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY";A.SET_ATTACHED_TO_ENTITY_NODE_NAME="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME";A.SET_COLOR_END="PARTICLE_EMITTER.SET_COLOR_END";A.SET_COLOR_END_VARIANCE="PARTICLE_EMITTER.SET_COLOR_END_VARIANCE";A.SET_COLOR_START="PARTICLE_EMITTER.SET_COLOR_START";A.SET_COLOR_START_VARIANCE="PARTICLE_EMITTER.SET_COLOR_START_VARIANCE";A.SET_GRAVITY="PARTICLE_EMITTER.SET_GRAVITY";A.SET_LIFETIME="PARTICLE_EMITTER.SET_LIFETIME";A.SET_LIFETIME_VARIANCE="PARTICLE_EMITTER.SET_LIFETIME_VARIANCE";A.SET_MAX_PARTICLES="PARTICLE_EMITTER.SET_MAX_PARTICLES";A.SET_OFFSET="PARTICLE_EMITTER.SET_OFFSET";A.SET_OPACITY_END="PARTICLE_EMITTER.SET_OPACITY_END";A.SET_OPACITY_END_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE";A.SET_OPACITY_START="PARTICLE_EMITTER.SET_OPACITY_START";A.SET_OPACITY_START_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE";A.SET_PAUSED="PARTICLE_EMITTER.SET_PAUSED";A.SET_POSITION="PARTICLE_EMITTER.SET_POSITION";A.SET_POSITION_VARIANCE="PARTICLE_EMITTER.SET_POSITION_VARIANCE";A.SET_RATE="PARTICLE_EMITTER.SET_RATE";A.SET_RATE_VARIANCE="PARTICLE_EMITTER.SET_RATE_VARIANCE";A.SET_SIZE_END="PARTICLE_EMITTER.SET_SIZE_END";A.SET_SIZE_END_VARIANCE="PARTICLE_EMITTER.SET_SIZE_END_VARIANCE";A.SET_SIZE_START="PARTICLE_EMITTER.SET_SIZE_START";A.SET_SIZE_START_VARIANCE="PARTICLE_EMITTER.SET_SIZE_START_VARIANCE";A.SET_TEXTURE_URI="PARTICLE_EMITTER.SET_TEXTURE_URI";A.SET_TRANSPARENT="PARTICLE_EMITTER.SET_TRANSPARENT";A.SET_VELOCITY="PARTICLE_EMITTER.SET_VELOCITY";A.SET_VELOCITY_VARIANCE="PARTICLE_EMITTER.SET_VELOCITY_VARIANCE";A.SPAWN="PARTICLE_EMITTER.SPAWN"})(ri||={});class ti extends $1{_id;_alphaTest;_attachedToEntity;_attachedToEntityNodeName;_colorEnd;_colorEndVariance;_colorStart;_colorStartVariance;_gravity;_lifetime;_lifetimeVariance;_maxParticles;_offset;_opacityEnd;_opacityEndVariance;_opacityStart;_opacityStartVariance;_paused;_position;_positionVariance;_rate;_rateVariance;_sizeEnd;_sizeEndVariance;_sizeStart;_sizeStartVariance;_sizeVariance;_textureUri;_transparent;_velocity;_velocityVariance;_world;constructor(J){if(!!J.attachedToEntity===!!J.position)n.fatalError("Either attachedToEntity or position must be set, but not both.");if(!J.textureUri)n.fatalError("ParticleEmitter.constructor(): textureUri must be provided.");super();this._alphaTest=J.alphaTest??0.05,this._attachedToEntity=J.attachedToEntity,this._attachedToEntityNodeName=J.attachedToEntityNodeName,this._colorEnd=J.colorEnd,this._colorEndVariance=J.colorEndVariance,this._colorStart=J.colorStart,this._colorStartVariance=J.colorStartVariance,this._gravity=J.gravity,this._lifetime=J.lifetime,this._lifetimeVariance=J.lifetimeVariance,this._maxParticles=J.maxParticles,this._offset=J.offset,this._opacityEnd=J.opacityEnd,this._opacityEndVariance=J.opacityEndVariance,this._opacityStart=J.opacityStart,this._opacityStartVariance=J.opacityStartVariance,this._paused=!1,this._position=J.position,this._positionVariance=J.positionVariance,this._rate=J.rate,this._rateVariance=J.rateVariance,this._sizeEnd=J.sizeEnd,this._sizeEndVariance=J.sizeEndVariance,this._sizeStart=J.sizeStart,this._sizeStartVariance=J.sizeStartVariance,this._textureUri=J.textureUri,this._transparent=J.transparent,this._velocity=J.velocity,this._velocityVariance=J.velocityVariance}get id(){return this._id}get alphaTest(){return this._alphaTest}get attachedToEntity(){return this._attachedToEntity}get attachedToEntityNodeName(){return this._attachedToEntityNodeName}get colorEnd(){return this._colorEnd}get colorEndVariance(){return this._colorEndVariance}get colorStart(){return this._colorStart}get colorStartVariance(){return this._colorStartVariance}get gravity(){return this._gravity}get isSpawned(){return this._id!==void 0}get lifetime(){return this._lifetime}get lifetimeVariance(){return this._lifetimeVariance}get maxParticles(){return this._maxParticles}get offset(){return this._offset}get opacityEnd(){return this._opacityEnd}get opacityEndVariance(){return this._opacityEndVariance}get opacityStart(){return this._opacityStart}get opacityStartVariance(){return this._opacityStartVariance}get paused(){return this._paused}get position(){return this._position}get positionVariance(){return this._positionVariance}get rate(){return this._rate}get rateVariance(){return this._rateVariance}get sizeEnd(){return this._sizeEnd}get sizeEndVariance(){return this._sizeEndVariance}get sizeStart(){return this._sizeStart}get sizeStartVariance(){return this._sizeStartVariance}get sizeVariance(){return this._sizeVariance}get textureUri(){return this._textureUri}get transparent(){return this._transparent}get velocity(){return this._velocity}get velocityVariance(){return this._velocityVariance}get world(){return this._world}setAlphaTest(J){if(this._alphaTest===J)return;if(this._alphaTest=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ALPHA_TEST",{particleEmitter:this,alphaTest:J})}setAttachedToEntity(J){if(!J.isSpawned)return n.error(`ParticleEmitter.setAttachedToEntity(): Entity ${J.id} is not spawned!`);if(this._attachedToEntity===J)return;if(this._attachedToEntity=J,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY",{particleEmitter:this,entity:J})}setAttachedToEntityNodeName(J){if(this._attachedToEntityNodeName===J)return;if(this._attachedToEntityNodeName=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME",{particleEmitter:this,attachedToEntityNodeName:J})}setColorEnd(J){if(this._colorEnd&&this._colorEnd.r===J.r&&this._colorEnd.g===J.g&&this._colorEnd.b===J.b)return;if(this._colorEnd=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_END",{particleEmitter:this,colorEnd:J})}setColorEndVariance(J){if(this._colorEndVariance&&this._colorEndVariance.r===J.r&&this._colorEndVariance.g===J.g&&this._colorEndVariance.b===J.b)return;if(this._colorEndVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_END_VARIANCE",{particleEmitter:this,colorEndVariance:J})}setColorStart(J){if(this._colorStart&&this._colorStart.r===J.r&&this._colorStart.g===J.g&&this._colorStart.b===J.b)return;if(this._colorStart=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_START",{particleEmitter:this,colorStart:J})}setColorStartVariance(J){if(this._colorStartVariance&&this._colorStartVariance.r===J.r&&this._colorStartVariance.g===J.g&&this._colorStartVariance.b===J.b)return;if(this._colorStartVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_START_VARIANCE",{particleEmitter:this,colorStartVariance:J})}setGravity(J){if(this._gravity&&this._gravity.x===J.x&&this._gravity.y===J.y&&this._gravity.z===J.z)return;if(this._gravity=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_GRAVITY",{particleEmitter:this,gravity:J})}setLifetime(J){if(this._lifetime===J)return;if(this._lifetime=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_LIFETIME",{particleEmitter:this,lifetime:J})}setLifetimeVariance(J){if(this._lifetimeVariance===J)return;if(this._lifetimeVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_LIFETIME_VARIANCE",{particleEmitter:this,lifetimeVariance:J})}setMaxParticles(J){if(this._maxParticles===J)return;if(this._maxParticles=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_MAX_PARTICLES",{particleEmitter:this,maxParticles:J})}setOffset(J){if(this._offset&&this._offset.x===J.x&&this._offset.y===J.y&&this._offset.z===J.z)return;if(this._offset=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OFFSET",{particleEmitter:this,offset:J})}setOpacityEnd(J){if(this._opacityEnd===J)return;if(this._opacityEnd=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_END",{particleEmitter:this,opacityEnd:J})}setOpacityEndVariance(J){if(this._opacityEndVariance===J)return;if(this._opacityEndVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE",{particleEmitter:this,opacityEndVariance:J})}setOpacityStart(J){if(this._opacityStart===J)return;if(this._opacityStart=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_START",{particleEmitter:this,opacityStart:J})}setOpacityStartVariance(J){if(this._opacityStartVariance===J)return;if(this._opacityStartVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE",{particleEmitter:this,opacityStartVariance:J})}setPosition(J){if(this._position&&this._position.x===J.x&&this._position.y===J.y&&this._position.z===J.z)return;if(this._position=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_POSITION",{particleEmitter:this,position:J})}setPositionVariance(J){if(this._positionVariance&&this._positionVariance.x===J.x&&this._positionVariance.y===J.y&&this._positionVariance.z===J.z)return;if(this._positionVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_POSITION_VARIANCE",{particleEmitter:this,positionVariance:J})}setRate(J){if(this._rate===J)return;if(this._rate=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_RATE",{particleEmitter:this,rate:J})}setRateVariance(J){if(this._rateVariance===J)return;if(this._rateVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_RATE_VARIANCE",{particleEmitter:this,rateVariance:J})}setSizeEnd(J){if(this._sizeEnd===J)return;if(this._sizeEnd=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_END",{particleEmitter:this,sizeEnd:J})}setSizeEndVariance(J){if(this._sizeEndVariance===J)return;if(this._sizeEndVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_END_VARIANCE",{particleEmitter:this,sizeEndVariance:J})}setSizeStart(J){if(this._sizeStart===J)return;if(this._sizeStart=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_START",{particleEmitter:this,sizeStart:J})}setSizeStartVariance(J){if(this._sizeStartVariance===J)return;if(this._sizeStartVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_START_VARIANCE",{particleEmitter:this,sizeStartVariance:J})}setTextureUri(J){if(this._textureUri===J)return;if(this._textureUri=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_TEXTURE_URI",{particleEmitter:this,textureUri:J})}setTransparent(J){if(this._transparent===J)return;if(this._transparent=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_TRANSPARENT",{particleEmitter:this,transparent:J})}setVelocity(J){if(this._velocity&&this._velocity.x===J.x&&this._velocity.y===J.y&&this._velocity.z===J.z)return;if(this._velocity=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_VELOCITY",{particleEmitter:this,velocity:J})}setVelocityVariance(J){if(this._velocityVariance&&this._velocityVariance.x===J.x&&this._velocityVariance.y===J.y&&this._velocityVariance.z===J.z)return;if(this._velocityVariance=J,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_VELOCITY_VARIANCE",{particleEmitter:this,velocityVariance:J})}burst(J){if(this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.BURST",{particleEmitter:this,count:J})}despawn(){if(!this.isSpawned||!this._world)return;this._world.particleEmitterManager.unregisterParticleEmitter(this),this.emitWithWorld(this._world,"PARTICLE_EMITTER.DESPAWN",{particleEmitter:this}),this._id=void 0,this._world=void 0}restart(){if(!this._paused)return;if(this._paused=!1,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_PAUSED",{particleEmitter:this,paused:this._paused})}stop(){if(this._paused)return;if(this._paused=!0,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_PAUSED",{particleEmitter:this,paused:this._paused})}spawn(J){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return n.error(`ParticleEmitter.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning ParticleEmitter!`);this._id=J.particleEmitterManager.registerParticleEmitter(this),this._world=J,this.emitWithWorld(J,"PARTICLE_EMITTER.SPAWN",{particleEmitter:this})}serialize(){return V1.serializeParticleEmitter(this)}}var SC6={x:0,y:-32,z:0},ei=60,Jn;((Q)=>{Q.STEP_START="SIMULATION.STEP_START";Q.STEP_END="SIMULATION.STEP_END";Q.DEBUG_RAYCAST="SIMULATION.DEBUG_RAYCAST";Q.DEBUG_RENDER="SIMULATION.DEBUG_RENDER"})(Jn||={});class $B extends $1{_colliderMap=new jU;_debugRaycastingEnabled=!1;_debugRenderingEnabled=!1;_debugRenderingFilterFlags;_rapierEventQueue;_rapierSimulation;_world;constructor(J,$=ei,X=SC6){super();this._rapierEventQueue=new W8.EventQueue(!0),this._rapierSimulation=new W8.World(X),this._rapierSimulation.timestep=Math.fround(1/$),this._world=J}get colliderMap(){return this._colliderMap}get isDebugRaycastingEnabled(){return this._debugRaycastingEnabled}get isDebugRenderingEnabled(){return this._debugRenderingEnabled}get gravity(){return this._rapierSimulation.gravity}get timestepS(){return this._rapierSimulation.timestep}get world(){return this._world}createRawCollider(J,$){return this._rapierSimulation.createCollider(J,$)}createRawRigidBody(J){return this._rapierSimulation.createRigidBody(J)}enableDebugRaycasting(J){this._debugRaycastingEnabled=J}enableDebugRendering(J,$=W8.QueryFilterFlags.EXCLUDE_FIXED){this._debugRenderingEnabled=J,this._debugRenderingFilterFlags=$}getContactManifolds(J,$){let X=[];return this._rapierSimulation.narrowPhase.contactPair(J,$,(Y,Q)=>{if(Y.numContacts()===0)return;let W=Y.normal(),K=[];for(let Z=0;Z<Y.numSolverContacts();Z++)K.push(Y.solverContactPoint(Z));X.push({contactPoints:K,localNormalA:!Q?Y.localNormal1():Y.localNormal2(),localNormalB:!Q?Y.localNormal2():Y.localNormal1(),normal:!Q?W:{x:-W.x,y:-W.y,z:-W.z}})}),X}intersectionsWithRawShape(J,$,X,Y={}){let Q=new Set,W=[];return this._rapierSimulation.intersectionsWithShape($,X,J,(K)=>{let Z=this._colliderMap.getColliderHandleBlockType(K.handle);if(Z&&!Q.has(Z))return Q.add(Z),W.push({intersectedBlockType:Z}),!0;let G=this._colliderMap.getColliderHandleEntity(K.handle);if(G&&!Q.has(G))return Q.add(G),W.push({intersectedEntity:G}),!0;return!0},Y.filterFlags,Y.filterGroups,Y.filterExcludeCollider,Y.filterExcludeRigidBody,Y.filterPredicate),W}raycast(J,$,X,Y={}){let Q=new W8.Ray(J,$),W=this._rapierSimulation.castRay(Q,X,Y.solidMode??!0,Y.filterFlags,Y.filterGroups,Y.filterExcludeCollider,Y.filterExcludeRigidBody,Y.filterPredicate);if(this._debugRaycastingEnabled)this.emitWithWorld(this._world,"SIMULATION.DEBUG_RAYCAST",{simulation:this,origin:J,direction:$,length:X,hit:!!W});if(!W)return null;let K=Q.pointAt(W.timeOfImpact),Z=W.timeOfImpact,G=W.collider,V=this._colliderMap.getColliderHandleBlockType(G.handle);if(V)return{hitBlock:R3.fromGlobalCoordinate({x:Math.floor(K.x-(Q.dir.x<0?0.0001:-0.0001)),y:Math.floor(K.y-(Q.dir.y<0?0.0001:-0.0001)),z:Math.floor(K.z-(Q.dir.z<0?0.0001:-0.0001))},V),hitPoint:K,hitDistance:Z};let q=this._colliderMap.getColliderHandleEntity(G.handle);if(q)return{hitEntity:q,hitPoint:K,hitDistance:Z};return null}removeRawCollider(J){this._colliderMap.queueColliderHandleForCleanup(J.handle),this._rapierSimulation.removeCollider(J,!1)}removeRawRigidBody(J){this._rapierSimulation.removeRigidBody(J)}setGravity(J){this._rapierSimulation.gravity=J}step=(J)=>{this.emitWithWorld(this._world,"SIMULATION.STEP_START",{simulation:this,tickDeltaMs:J});let $=performance.now();if(T6.startSpan({operation:"physics_step"},()=>{this._rapierSimulation.step(this._rapierEventQueue)}),T6.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()-$}),this._debugRenderingEnabled)this.emitWithWorld(this._world,"SIMULATION.DEBUG_RENDER",{simulation:this,...this._rapierSimulation.debugRender(this._debugRenderingFilterFlags)})};_onCollisionEvent=(J,$,X)=>{let[Y,Q]=this._getCollisionObjects(J,$);if(!Y||!Q)return;let W=(K,Z)=>{if(K instanceof A9&&Z instanceof b6&&K.hasListeners("BLOCK_TYPE.ENTITY_COLLISION"))K.emit("BLOCK_TYPE.ENTITY_COLLISION",{blockType:K,entity:Z,started:X,colliderHandleA:J,colliderHandleB:$});else if(K instanceof b6&&Z instanceof A9&&K.hasListeners("ENTITY.BLOCK_COLLISION"))K.emit("ENTITY.BLOCK_COLLISION",{entity:K,blockType:Z,started:X,colliderHandleA:J,colliderHandleB:$});else if(K instanceof b6&&Z instanceof b6&&K.hasListeners("ENTITY.ENTITY_COLLISION"))K.emit("ENTITY.ENTITY_COLLISION",{entity:K,otherEntity:Z,started:X,colliderHandleA:J,colliderHandleB:$});else if(typeof K==="function"&&(Z instanceof b6||Z instanceof A9))K(Z,X,J,$)};W(Y,Q),W(Q,Y)};_onContactForceEvent=(J)=>{let[$,X]=this._getCollisionObjects(J.collider1(),J.collider2());if(!$||typeof $==="function"||!X||typeof X==="function")return;let Y={totalForce:J.totalForce(),totalForceMagnitude:J.totalForceMagnitude(),maxForceDirection:J.maxForceDirection(),maxForceMagnitude:J.maxForceMagnitude()},Q=(W,K)=>{if(W instanceof A9&&K instanceof b6&&W.hasListeners("BLOCK_TYPE.ENTITY_CONTACT_FORCE"))W.emit("BLOCK_TYPE.ENTITY_CONTACT_FORCE",{blockType:W,entity:K,contactForceData:Y});else if(W instanceof b6&&K instanceof A9&&W.hasListeners("ENTITY.BLOCK_CONTACT_FORCE"))W.emit("ENTITY.BLOCK_CONTACT_FORCE",{entity:W,blockType:K,contactForceData:Y});else if(W instanceof b6&&K instanceof b6&&W.hasListeners("ENTITY.ENTITY_CONTACT_FORCE"))W.emit("ENTITY.ENTITY_CONTACT_FORCE",{entity:W,otherEntity:K,contactForceData:Y})};Q($,X),Q(X,$)};_getCollisionObjects(J,$){let X=this._colliderMap.getColliderHandleBlockType(J)??this._colliderMap.getColliderHandleCollisionCallback(J)??this._colliderMap.getColliderHandleEntity(J),Y=this._colliderMap.getColliderHandleBlockType($)??this._colliderMap.getColliderHandleCollisionCallback($)??this._colliderMap.getColliderHandleEntity($);return[X,Y]}}class AC{_synchronizedPlayerReliablePackets=new w5;_queuedBroadcasts=[];_queuedAudioSynchronizations=new w5;_queuedBlockSynchronizations=new w5;_queuedBlockTypeSynchronizations=new w5;_queuedChunkSynchronizations=new w5;_queuedDebugRaycastSynchronizations=[];_queuedEntitySynchronizations=new w5;_queuedLightSynchronizations=new w5;_queuedParticleEmitterSynchronizations=new w5;_queuedPerPlayerSynchronizations=new w5;_queuedPerPlayerCameraSynchronizations=new w5;_queuedPerPlayerUISynchronizations=new w5;_queuedPerPlayerUIDatasSynchronizations=new w5;_queuedPlayerSynchronizations=new w5;_queuedSceneUISynchronizations=new w5;_queuedWorldSynchronization;_loadedSceneUIs=new Set;_spawnedChunks=new Set;_spawnedEntities=new Set;_world;constructor(J){this._world=J,this._subscribeToAudioEvents(),this._subscribeToBlockTypeRegistryEvents(),this._subscribeToChatEvents(),this._subscribeToChunkLatticeEvents(),this._subscribeToEntityEvents(),this._subscribeToLightEvents(),this._subscribeToParticleEmitterEvents(),this._subscribeToPlayerEvents(),this._subscribeToPlayerCameraEvents(),this._subscribeToPlayerUIEvents(),this._subscribeToSceneUIEvents(),this._subscribeToSimulationEvents(),this._subscribeToWorldEvents()}synchronize(){let J=[],$=[],X=this._world.loop.currentTick;if(this._queuedPerPlayerSynchronizations.size>0)for(let[Y,Q]of this._queuedPerPlayerSynchronizations)this._createOrGetSynchronizedPlayerReliablePackets(Y,J).push(...Q);if(this._queuedEntitySynchronizations.size>0){let Y=[],Q=[];for(let W of this._queuedEntitySynchronizations.valuesArray){let K=!1;for(let Z in W)if(Z!=="i"&&Z!=="p"&&Z!=="r"){K=!0;break}if(K)Y.push(W);else Q.push(W)}if(Q.length>0){let W=_0.createPacket(_0.outboundPackets.entitiesPacketDefinition,Q,X);$.push(W)}if(Y.length>0){let W=_0.createPacket(_0.outboundPackets.entitiesPacketDefinition,Y,X);J.push(W);for(let K of this._synchronizedPlayerReliablePackets.valuesArray)K.push(W)}}if(this._queuedAudioSynchronizations.size>0){let Y=_0.createPacket(_0.outboundPackets.audiosPacketDefinition,this._queuedAudioSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedBlockTypeSynchronizations.size>0){let Y=_0.createPacket(_0.outboundPackets.blockTypesPacketDefinition,this._queuedBlockTypeSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedChunkSynchronizations.size>0){let Y=_0.createPacket(_0.outboundPackets.chunksPacketDefinition,this._queuedChunkSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedBlockSynchronizations.size>0){let Y=_0.createPacket(_0.outboundPackets.blocksPacketDefinition,this._queuedBlockSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedLightSynchronizations.size>0){let Y=_0.createPacket(_0.outboundPackets.lightsPacketDefinition,this._queuedLightSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedParticleEmitterSynchronizations.size>0){let Y=_0.createPacket(_0.outboundPackets.particleEmittersPacketDefinition,this._queuedParticleEmitterSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedPerPlayerUISynchronizations.size>0)for(let[Y,Q]of this._queuedPerPlayerUISynchronizations){let W=_0.createPacket(_0.outboundPackets.uiPacketDefinition,Q,X);this._createOrGetSynchronizedPlayerReliablePackets(Y,J).push(W)}if(this._queuedPerPlayerUIDatasSynchronizations.size>0)for(let[Y,Q]of this._queuedPerPlayerUIDatasSynchronizations){let W=_0.createPacket(_0.outboundPackets.uiDatasPacketDefinition,Q,X);this._createOrGetSynchronizedPlayerReliablePackets(Y,J).push(W)}if(this._queuedSceneUISynchronizations.size>0){let Y=_0.createPacket(_0.outboundPackets.sceneUIsPacketDefinition,this._queuedSceneUISynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedWorldSynchronization){let Y=_0.createPacket(_0.outboundPackets.worldPacketDefinition,this._queuedWorldSynchronization,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedPerPlayerCameraSynchronizations.size>0)for(let[Y,Q]of this._queuedPerPlayerCameraSynchronizations){let W=_0.createPacket(_0.outboundPackets.cameraPacketDefinition,Q,X);this._createOrGetSynchronizedPlayerReliablePackets(Y,J).push(W)}if(this._queuedPlayerSynchronizations.size>0){let Y=_0.createPacket(_0.outboundPackets.playersPacketDefinition,this._queuedPlayerSynchronizations.valuesArray,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedBroadcasts.length>0)for(let Y of this._queuedBroadcasts){J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}if(this._queuedDebugRaycastSynchronizations.length>0){let Y=_0.createPacket(_0.outboundPackets.physicsDebugRaycastsPacketDefinition,this._queuedDebugRaycastSynchronizations,X);J.push(Y);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push(Y)}T6.startSpan({operation:"send_all_packets"},()=>{for(let Y of F$.instance.getConnectedPlayersByWorld(this._world)){let Q=this._synchronizedPlayerReliablePackets.get(Y)??J;if(Q.length>0)Y.connection.send(Q);if($.length>0)Y.connection.send($,!1)}}),T6.startSpan({operation:"network_synchronize_cleanup"},()=>{if(this._queuedBroadcasts.length>0)this._queuedBroadcasts.length=0;if(this._queuedAudioSynchronizations.size>0)this._queuedAudioSynchronizations.clear();if(this._queuedBlockSynchronizations.size>0)this._queuedBlockSynchronizations.clear();if(this._queuedBlockTypeSynchronizations.size>0)this._queuedBlockTypeSynchronizations.clear();if(this._queuedChunkSynchronizations.size>0)this._queuedChunkSynchronizations.clear();if(this._queuedDebugRaycastSynchronizations.length>0)this._queuedDebugRaycastSynchronizations.length=0;if(this._queuedEntitySynchronizations.size>0)this._queuedEntitySynchronizations.clear();if(this._queuedLightSynchronizations.size>0)this._queuedLightSynchronizations.clear();if(this._queuedParticleEmitterSynchronizations.size>0)this._queuedParticleEmitterSynchronizations.clear();if(this._queuedPerPlayerSynchronizations.size>0)this._queuedPerPlayerSynchronizations.clear();if(this._queuedPerPlayerCameraSynchronizations.size>0)this._queuedPerPlayerCameraSynchronizations.clear();if(this._queuedPerPlayerUISynchronizations.size>0)this._queuedPerPlayerUISynchronizations.clear();if(this._queuedPerPlayerUIDatasSynchronizations.size>0)this._queuedPerPlayerUIDatasSynchronizations.clear();if(this._queuedPlayerSynchronizations.size>0)this._queuedPlayerSynchronizations.clear();if(this._queuedSceneUISynchronizations.size>0)this._queuedSceneUISynchronizations.clear();if(this._queuedWorldSynchronization)this._queuedWorldSynchronization=void 0;if(this._loadedSceneUIs.size>0)this._loadedSceneUIs.clear();if(this._spawnedChunks.size>0)this._spawnedChunks.clear();if(this._spawnedEntities.size>0)this._spawnedEntities.clear();if(this._synchronizedPlayerReliablePackets.size>0)this._synchronizedPlayerReliablePackets.clear();v$.clearCachedPacketsSerializedBuffers()})}_subscribeToAudioEvents(){this._world.final("AUDIO.PAUSE",this._onAudioPause),this._world.final("AUDIO.PLAY",this._onAudioPlay),this._world.final("AUDIO.PLAY_RESTART",this._onAudioPlayRestart),this._world.final("AUDIO.SET_ATTACHED_TO_ENTITY",this._onAudioSetAttachedToEntity),this._world.final("AUDIO.SET_CUTOFF_DISTANCE",this._onAudioSetCutoffDistance),this._world.final("AUDIO.SET_DETUNE",this._onAudioSetDetune),this._world.final("AUDIO.SET_DISTORTION",this._onAudioSetDistortion),this._world.final("AUDIO.SET_POSITION",this._onAudioSetPosition),this._world.final("AUDIO.SET_PLAYBACK_RATE",this._onAudioSetPlaybackRate),this._world.final("AUDIO.SET_REFERENCE_DISTANCE",this._onAudioSetReferenceDistance),this._world.final("AUDIO.SET_VOLUME",this._onAudioSetVolume)}_subscribeToBlockTypeRegistryEvents(){this._world.final("BLOCK_TYPE_REGISTRY.REGISTER_BLOCK_TYPE",this._onBlockTypeRegistryRegisterBlockType)}_subscribeToChatEvents(){this._world.final("CHAT.BROADCAST_MESSAGE",this._onChatSendBroadcastMessage),this._world.final("CHAT.PLAYER_MESSAGE",this._onChatSendPlayerMessage)}_subscribeToChunkLatticeEvents(){this._world.final("CHUNK_LATTICE.ADD_CHUNK",this._onChunkLatticeAddChunk),this._world.final("CHUNK_LATTICE.REMOVE_CHUNK",this._onChunkLatticeRemoveChunk),this._world.final("CHUNK_LATTICE.SET_BLOCK",this._onChunkLatticeSetBlock)}_subscribeToEntityEvents(){this._world.final("ENTITY.SPAWN",this._onEntitySpawn),this._world.final("ENTITY.DESPAWN",this._onEntityDespawn),this._world.final("ENTITY.SET_MODEL_ANIMATIONS_PLAYBACK_RATE",this._onEntitySetModelAnimationsPlaybackRate),this._world.final("ENTITY.SET_MODEL_HIDDEN_NODES",this._onEntitySetModelHiddenNodes),this._world.final("ENTITY.SET_MODEL_SCALE",this._onEntitySetModelScale),this._world.final("ENTITY.SET_MODEL_SHOWN_NODES",this._onEntitySetModelShownNodes),this._world.final("ENTITY.SET_MODEL_TEXTURE_URI",this._onEntitySetModelTextureUri),this._world.final("ENTITY.SET_OPACITY",this._onEntitySetOpacity),this._world.final("ENTITY.SET_PARENT",this._onEntitySetParent),this._world.final("ENTITY.SET_TINT_COLOR",this._onEntitySetTintColor),this._world.final("ENTITY.START_MODEL_LOOPED_ANIMATIONS",this._onEntityStartModelLoopedAnimations),this._world.final("ENTITY.START_MODEL_ONESHOT_ANIMATIONS",this._onEntityStartModelOneshotAnimations),this._world.final("ENTITY.STOP_MODEL_ANIMATIONS",this._onEntityStopModelAnimations),this._world.final("ENTITY.UPDATE_POSITION",this._onEntityUpdatePosition),this._world.final("ENTITY.UPDATE_ROTATION",this._onEntityUpdateRotation)}_subscribeToLightEvents(){this._world.final("LIGHT.DESPAWN",this._onLightDespawn),this._world.final("LIGHT.SET_ANGLE",this._onLightSetAngle),this._world.final("LIGHT.SET_ATTACHED_TO_ENTITY",this._onLightSetAttachedToEntity),this._world.final("LIGHT.SET_COLOR",this._onLightSetColor),this._world.final("LIGHT.SET_DISTANCE",this._onLightSetDistance),this._world.final("LIGHT.SET_INTENSITY",this._onLightSetIntensity),this._world.final("LIGHT.SET_OFFSET",this._onLightSetOffset),this._world.final("LIGHT.SET_PENUMBRA",this._onLightSetPenumbra),this._world.final("LIGHT.SET_POSITION",this._onLightSetPosition),this._world.final("LIGHT.SET_TRACKED_ENTITY",this._onLightSetTrackedEntity),this._world.final("LIGHT.SET_TRACKED_POSITION",this._onLightSetTrackedPosition),this._world.final("LIGHT.SPAWN",this._onLightSpawn)}_subscribeToParticleEmitterEvents(){this._world.final("PARTICLE_EMITTER.DESPAWN",this._onParticleEmitterDespawn),this._world.final("PARTICLE_EMITTER.BURST",this._onParticleEmitterBurst),this._world.final("PARTICLE_EMITTER.SET_ALPHA_TEST",this._onParticleEmitterSetAlphaTest),this._world.final("PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY",this._onParticleEmitterSetAttachedToEntity),this._world.final("PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME",this._onParticleEmitterSetAttachedToEntityNodeName),this._world.final("PARTICLE_EMITTER.SET_COLOR_END",this._onParticleEmitterSetColorEnd),this._world.final("PARTICLE_EMITTER.SET_COLOR_END_VARIANCE",this._onParticleEmitterSetColorEndVariance),this._world.final("PARTICLE_EMITTER.SET_COLOR_START",this._onParticleEmitterSetColorStart),this._world.final("PARTICLE_EMITTER.SET_COLOR_START_VARIANCE",this._onParticleEmitterSetColorStartVariance),this._world.final("PARTICLE_EMITTER.SET_GRAVITY",this._onParticleEmitterSetGravity),this._world.final("PARTICLE_EMITTER.SET_LIFETIME",this._onParticleEmitterSetLifetime),this._world.final("PARTICLE_EMITTER.SET_LIFETIME_VARIANCE",this._onParticleEmitterSetLifetimeVariance),this._world.final("PARTICLE_EMITTER.SET_MAX_PARTICLES",this._onParticleEmitterSetMaxParticles),this._world.final("PARTICLE_EMITTER.SET_OFFSET",this._onParticleEmitterSetOffset),this._world.final("PARTICLE_EMITTER.SET_OPACITY_END",this._onParticleEmitterSetOpacityEnd),this._world.final("PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE",this._onParticleEmitterSetOpacityEndVariance),this._world.final("PARTICLE_EMITTER.SET_OPACITY_START",this._onParticleEmitterSetOpacityStart),this._world.final("PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE",this._onParticleEmitterSetOpacityStartVariance),this._world.final("PARTICLE_EMITTER.SET_PAUSED",this._onParticleEmitterSetPaused),this._world.final("PARTICLE_EMITTER.SET_POSITION",this._onParticleEmitterSetPosition),this._world.final("PARTICLE_EMITTER.SET_POSITION_VARIANCE",this._onParticleEmitterSetPositionVariance),this._world.final("PARTICLE_EMITTER.SET_RATE",this._onParticleEmitterSetRate),this._world.final("PARTICLE_EMITTER.SET_RATE_VARIANCE",this._onParticleEmitterSetRateVariance),this._world.final("PARTICLE_EMITTER.SET_SIZE_END",this._onParticleEmitterSetSizeEnd),this._world.final("PARTICLE_EMITTER.SET_SIZE_END_VARIANCE",this._onParticleEmitterSetSizeEndVariance),this._world.final("PARTICLE_EMITTER.SET_SIZE_START",this._onParticleEmitterSetSizeStart),this._world.final("PARTICLE_EMITTER.SET_SIZE_START_VARIANCE",this._onParticleEmitterSetSizeStartVariance),this._world.final("PARTICLE_EMITTER.SET_TEXTURE_URI",this._onParticleEmitterSetTextureUri),this._world.final("PARTICLE_EMITTER.SET_TRANSPARENT",this._onParticleEmitterSetTransparent),this._world.final("PARTICLE_EMITTER.SET_VELOCITY",this._onParticleEmitterSetVelocity),this._world.final("PARTICLE_EMITTER.SET_VELOCITY_VARIANCE",this._onParticleEmitterSetVelocityVariance),this._world.final("PARTICLE_EMITTER.SPAWN",this._onParticleEmitterSpawn)}_subscribeToPlayerEvents(){this._world.final("PLAYER.JOINED_WORLD",this._onPlayerJoinedWorld),this._world.final("PLAYER.LEFT_WORLD",this._onPlayerLeftWorld),this._world.final("PLAYER.RECONNECTED_WORLD",this._onPlayerReconnectedWorld),this._world.final("PLAYER.REQUEST_NOTIFICATION_PERMISSION",this._onPlayerRequestNotificationPermission),this._world.final("PLAYER.REQUEST_SYNC",this._onPlayerRequestSync)}_subscribeToPlayerCameraEvents(){this._world.final("PLAYER_CAMERA.LOOK_AT_ENTITY",this._onPlayerCameraLookAtEntity),this._world.final("PLAYER_CAMERA.LOOK_AT_POSITION",this._onPlayerCameraLookAtPosition),this._world.final("PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY",this._onPlayerCameraSetAttachedToEntity),this._world.final("PLAYER_CAMERA.SET_ATTACHED_TO_POSITION",this._onPlayerCameraSetAttachedToPosition),this._world.final("PLAYER_CAMERA.SET_FILM_OFFSET",this._onPlayerCameraSetFilmOffset),this._world.final("PLAYER_CAMERA.SET_FORWARD_OFFSET",this._onPlayerCameraSetForwardOffset),this._world.final("PLAYER_CAMERA.SET_FOV",this._onPlayerCameraSetFov),this._world.final("PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES",this._onPlayerCameraSetModelHiddenNodes),this._world.final("PLAYER_CAMERA.SET_MODEL_SHOWN_NODES",this._onPlayerCameraSetModelShownNodes),this._world.final("PLAYER_CAMERA.SET_MODE",this._onPlayerCameraSetMode),this._world.final("PLAYER_CAMERA.SET_OFFSET",this._onPlayerCameraSetOffset),this._world.final("PLAYER_CAMERA.SET_SHOULDER_ANGLE",this._onPlayerCameraSetShoulderAngle),this._world.final("PLAYER_CAMERA.SET_TRACKED_ENTITY",this._onPlayerCameraSetTrackedEntity),this._world.final("PLAYER_CAMERA.SET_TRACKED_POSITION",this._onPlayerCameraSetTrackedPosition),this._world.final("PLAYER_CAMERA.SET_ZOOM",this._onPlayerCameraSetZoom)}_subscribeToPlayerUIEvents(){this._world.final("PLAYER_UI.LOAD",this._onPlayerUILoad),this._world.final("PLAYER_UI.LOCK_POINTER",this._onPlayerUILockPointer),this._world.final("PLAYER_UI.SEND_DATA",this._onPlayerUISendData)}_subscribeToSceneUIEvents(){this._world.final("SCENE_UI.LOAD",this._onSceneUILoad),this._world.final("SCENE_UI.SET_ATTACHED_TO_ENTITY",this._onSceneUISetAttachedToEntity),this._world.final("SCENE_UI.SET_OFFSET",this._onSceneUISetOffset),this._world.final("SCENE_UI.SET_POSITION",this._onSceneUISetPosition),this._world.final("SCENE_UI.SET_STATE",this._onSceneUISetState),this._world.final("SCENE_UI.SET_VIEW_DISTANCE",this._onSceneUISetViewDistance),this._world.final("SCENE_UI.UNLOAD",this._onSceneUIUnload)}_subscribeToSimulationEvents(){this._world.final("SIMULATION.DEBUG_RAYCAST",this._onSimulationDebugRaycast),this._world.final("SIMULATION.DEBUG_RENDER",this._onSimulationDebugRender)}_subscribeToWorldEvents(){this._world.final("WORLD.SET_AMBIENT_LIGHT_COLOR",this._onWorldSetAmbientLightColor),this._world.final("WORLD.SET_AMBIENT_LIGHT_INTENSITY",this._onWorldSetAmbientLightIntensity),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_COLOR",this._onWorldSetDirectionalLightColor),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY",this._onWorldSetDirectionalLightIntensity),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_POSITION",this._onWorldSetDirectionalLightPosition),this._world.final("WORLD.SET_FOG_COLOR",this._onWorldSetFogColor),this._world.final("WORLD.SET_FOG_FAR",this._onWorldSetFogFar),this._world.final("WORLD.SET_FOG_NEAR",this._onWorldSetFogNear),this._world.final("WORLD.SET_SKYBOX_INTENSITY",this._onWorldSetSkyboxIntensity),this._world.final("WORLD.SET_SKYBOX_URI",this._onWorldSetSkyboxUri)}_onAudioPause=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.pa=!0,delete $.pl,delete $.r};_onAudioPlay=(J)=>{let $=J.audio.serialize();$.pl=!0,delete $.pa,delete $.r,this._queuedAudioSynchronizations.set($.i,$)};_onAudioPlayRestart=(J)=>{let $=J.audio.serialize();$.r=!0,delete $.pa,delete $.pl,this._queuedAudioSynchronizations.set($.i,$)};_onAudioSetAttachedToEntity=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.e=J.entity?J.entity.id:void 0,$.p=J.entity?void 0:$.p};_onAudioSetCutoffDistance=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.cd=J.cutoffDistance};_onAudioSetDetune=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.de=J.detune};_onAudioSetDistortion=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.di=J.distortion};_onAudioSetPosition=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.e=J.position?void 0:$.e,$.p=J.position?V1.serializeVector(J.position):void 0};_onAudioSetPlaybackRate=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.pr=J.playbackRate};_onAudioSetReferenceDistance=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.rd=J.referenceDistance};_onAudioSetVolume=(J)=>{let $=this._createOrGetQueuedAudioSync(J.audio);$.v=J.volume};_onBlockTypeRegistryRegisterBlockType=(J)=>{let $=J.blockType.serialize();this._queuedBlockTypeSynchronizations.set(J.blockType.id,$)};_onChatSendBroadcastMessage=(J)=>{let{player:$,message:X,color:Y}=J;this._queuedBroadcasts.push(_0.createPacket(_0.outboundPackets.chatMessagesPacketDefinition,[{m:X,c:Y,p:$?.id}],this._world.loop.currentTick))};_onChatSendPlayerMessage=(J)=>{let{player:$,message:X,color:Y}=J,Q=this._queuedPerPlayerSynchronizations.get($)??[];Q.push(_0.createPacket(_0.outboundPackets.chatMessagesPacketDefinition,[{m:X,c:Y}],this._world.loop.currentTick)),this._queuedPerPlayerSynchronizations.set($,Q)};_onChunkLatticeAddChunk=(J)=>{let $=this._createOrGetQueuedChunkSync(J.chunk);$.b=Array.from(J.chunk.blocks),$.rm=void 0,this._spawnedChunks.add($.c.join(","))};_onChunkLatticeRemoveChunk=(J)=>{let $=this._createOrGetQueuedChunkSync(J.chunk),X=$.c.join(",");if(this._spawnedChunks.has(X))this._queuedChunkSynchronizations.delete(X),this._spawnedChunks.delete(X);else $.rm=!0};_onChunkLatticeSetBlock=(J)=>{let $=this._createOrGetQueuedBlockSync(J.globalCoordinate);$.i=J.blockTypeId};_onEntitySetModelAnimationsPlaybackRate=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.ap=J.playbackRate};_onEntitySpawn=(J)=>{let $=J.entity.serialize();this._queuedEntitySynchronizations.set($.i,$),this._spawnedEntities.add($.i)};_onEntityDespawn=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);if(this._spawnedEntities.has($.i))this._queuedEntitySynchronizations.delete($.i),this._spawnedEntities.delete($.i);else $.rm=!0};_onEntitySetModelHiddenNodes=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.h=Array.from(J.modelHiddenNodes)};_onEntitySetModelScale=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.sv=J.modelScale?V1.serializeVector(J.modelScale):void 0};_onEntitySetModelShownNodes=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.sn=Array.from(J.modelShownNodes)};_onEntitySetModelTextureUri=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.mt=J.modelTextureUri};_onEntitySetOpacity=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.o=J.opacity};_onEntitySetParent=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.pe=J.parent?J.parent.id:void 0,$.pn=J.parentNodeName};_onEntitySetTintColor=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.t=J.tintColor?V1.serializeRgbColor(J.tintColor):void 0};_onEntityStartModelLoopedAnimations=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);if($.al=Array.from(new Set([...$.al??[],...J.animations])),$.as)$.as=$.as.filter((X)=>!J.animations.has(X)).filter(Boolean)};_onEntityStartModelOneshotAnimations=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);if($.ao=Array.from(new Set([...$.ao??[],...J.animations])),$.as)$.as=$.as.filter((X)=>!J.animations.has(X)).filter(Boolean)};_onEntityStopModelAnimations=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);if($.al)$.al=$.al.filter((X)=>!J.animations.has(X)).filter(Boolean);if($.ao)$.ao=$.ao.filter((X)=>!J.animations.has(X)).filter(Boolean);$.as=Array.from(new Set([...$.as??[],...J.animations]))};_onEntityUpdateRotation=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.r=[J.rotation.x,J.rotation.y,J.rotation.z,J.rotation.w]};_onEntityUpdatePosition=(J)=>{let $=this._createOrGetQueuedEntitySync(J.entity);$.p=[J.position.x,J.position.y,J.position.z]};_onLightDespawn=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.rm=!0};_onLightSetAngle=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.a=J.angle};_onLightSetAttachedToEntity=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.e=J.entity?J.entity.id:void 0,$.p=J.entity?void 0:$.p};_onLightSetColor=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.c=V1.serializeRgbColor(J.color)};_onLightSetDistance=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.d=J.distance};_onLightSetIntensity=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.n=J.intensity};_onLightSetOffset=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.o=J.offset?V1.serializeVector(J.offset):void 0};_onLightSetPenumbra=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.pe=J.penumbra};_onLightSetPosition=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.p=J.position?V1.serializeVector(J.position):void 0,$.e=J.position?void 0:$.e};_onLightSetTrackedEntity=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.te=J.entity?J.entity.id:void 0,$.tp=J.entity?void 0:$.tp};_onLightSetTrackedPosition=(J)=>{let $=this._createOrGetQueuedLightSync(J.light);$.tp=J.position?V1.serializeVector(J.position):void 0,$.te=J.position?void 0:$.te};_onLightSpawn=(J)=>{let $=J.light.serialize();this._queuedLightSynchronizations.set($.i,$)};_onParticleEmitterBurst=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.b=J.count};_onParticleEmitterDespawn=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.rm=!0};_onParticleEmitterSetAlphaTest=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.at=J.alphaTest};_onParticleEmitterSetAttachedToEntity=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.e=J.entity?J.entity.id:void 0,$.p=J.entity?void 0:$.p};_onParticleEmitterSetAttachedToEntityNodeName=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.en=J.attachedToEntityNodeName};_onParticleEmitterSetColorEnd=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.ce=J.colorEnd?V1.serializeRgbColor(J.colorEnd):void 0};_onParticleEmitterSetColorEndVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.cev=J.colorEndVariance?V1.serializeRgbColor(J.colorEndVariance):void 0};_onParticleEmitterSetColorStart=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.cs=J.colorStart?V1.serializeRgbColor(J.colorStart):void 0};_onParticleEmitterSetColorStartVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.csv=J.colorStartVariance?V1.serializeRgbColor(J.colorStartVariance):void 0};_onParticleEmitterSetGravity=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.g=J.gravity?V1.serializeVector(J.gravity):void 0};_onParticleEmitterSetLifetime=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.l=J.lifetime};_onParticleEmitterSetLifetimeVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.lv=J.lifetimeVariance};_onParticleEmitterSetMaxParticles=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.mp=J.maxParticles};_onParticleEmitterSetOffset=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.o=J.offset?V1.serializeVector(J.offset):void 0};_onParticleEmitterSetOpacityEnd=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.oe=J.opacityEnd};_onParticleEmitterSetOpacityEndVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.oev=J.opacityEndVariance};_onParticleEmitterSetOpacityStart=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.os=J.opacityStart};_onParticleEmitterSetOpacityStartVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.osv=J.opacityStartVariance};_onParticleEmitterSetPaused=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.pa=J.paused};_onParticleEmitterSetPosition=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.p=J.position?V1.serializeVector(J.position):void 0,$.e=J.position?void 0:$.e,$.en=J.position?void 0:$.en};_onParticleEmitterSetPositionVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.pv=J.positionVariance?V1.serializeVector(J.positionVariance):void 0};_onParticleEmitterSetRate=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.r=J.rate};_onParticleEmitterSetRateVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.rv=J.rateVariance};_onParticleEmitterSetSizeEnd=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.se=J.sizeEnd};_onParticleEmitterSetSizeEndVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.sev=J.sizeEndVariance};_onParticleEmitterSetSizeStart=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.ss=J.sizeStart};_onParticleEmitterSetSizeStartVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.ssv=J.sizeStartVariance};_onParticleEmitterSetTextureUri=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.tu=J.textureUri};_onParticleEmitterSetTransparent=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.t=J.transparent};_onParticleEmitterSetVelocity=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.v=J.velocity?V1.serializeVector(J.velocity):void 0};_onParticleEmitterSetVelocityVariance=(J)=>{let $=this._createOrGetQueuedParticleEmitterSync(J.particleEmitter);$.vv=J.velocityVariance?V1.serializeVector(J.velocityVariance):void 0};_onParticleEmitterSpawn=(J)=>{let $=J.particleEmitter.serialize();this._queuedParticleEmitterSynchronizations.set($.i,$)};_onPlayerCameraLookAtEntity=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.pl=V1.serializeVector(J.entity.position),delete $.et,delete $.pt};_onPlayerCameraLookAtPosition=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.pl=J.position?V1.serializeVector(J.position):void 0,delete $.et,delete $.pt};_onPlayerCameraSetAttachedToEntity=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.e=J.entity.id,delete $.p};_onPlayerCameraSetAttachedToPosition=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.p=J.position?V1.serializeVector(J.position):void 0,delete $.e};_onPlayerCameraSetFilmOffset=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.fo=J.filmOffset};_onPlayerCameraSetForwardOffset=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.ffo=J.forwardOffset};_onPlayerCameraSetFov=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.fv=J.fov};_onPlayerCameraSetModelHiddenNodes=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.h=Array.from(J.modelHiddenNodes)};_onPlayerCameraSetModelShownNodes=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.s=Array.from(J.modelShownNodes)};_onPlayerCameraSetMode=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.m=J.mode};_onPlayerCameraSetOffset=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.o=J.offset?V1.serializeVector(J.offset):void 0};_onPlayerCameraSetShoulderAngle=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.sa=J.shoulderAngle};_onPlayerCameraSetTrackedEntity=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.et=J.entity?J.entity.id:void 0,delete $.pl,delete $.pt};_onPlayerCameraSetTrackedPosition=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.pt=J.position?V1.serializeVector(J.position):void 0,delete $.et,delete $.pl};_onPlayerCameraSetZoom=(J)=>{let $=this._createOrGetQueuedPlayerCameraSync(J.playerCamera);$.z=J.zoom};_onPlayerJoinedWorld=(J)=>{let{player:$}=J,X=this._queuedPerPlayerSynchronizations.get($)??[];X.push(_0.createPacket(_0.outboundPackets.entitiesPacketDefinition,this._world.entityManager.getAllEntities().map((Q)=>{if($.camera.attachedToEntity===void 0&&Q instanceof o$&&Q.player===$)$.camera.setAttachedToEntity(Q);return Q.serialize()}),this._world.loop.currentTick)),X.push(_0.createPacket(_0.outboundPackets.audiosPacketDefinition,this._world.audioManager.getAllAudios().map((Q)=>Q.serialize()),this._world.loop.currentTick)),X.push(_0.createPacket(_0.outboundPackets.blockTypesPacketDefinition,this._world.blockTypeRegistry.serialize(),this._world.loop.currentTick)),X.push(_0.createPacket(_0.outboundPackets.chunksPacketDefinition,this._world.chunkLattice.getAllChunks().map((Q)=>Q.serialize()),this._world.loop.currentTick)),X.push(_0.createPacket(_0.outboundPackets.lightsPacketDefinition,this._world.lightManager.getAllLights().map((Q)=>Q.serialize()),this._world.loop.currentTick)),X.push(_0.createPacket(_0.outboundPackets.particleEmittersPacketDefinition,this._world.particleEmitterManager.getAllParticleEmitters().map((Q)=>Q.serialize()),this._world.loop.currentTick)),X.push(_0.createPacket(_0.outboundPackets.sceneUIsPacketDefinition,this._world.sceneUIManager.getAllSceneUIs().map((Q)=>Q.serialize()),this._world.loop.currentTick)),X.push(_0.createPacket(_0.outboundPackets.worldPacketDefinition,this._world.serialize(),this._world.loop.currentTick)),X.push(_0.createPacket(_0.outboundPackets.playersPacketDefinition,F$.instance.getConnectedPlayers().map((Q)=>Q.serialize()),this._world.loop.currentTick));let Y=this._createOrGetQueuedPlayerCameraSync($.camera);this._queuedPerPlayerCameraSynchronizations.set($,{...$.camera.serialize(),...Y}),this._queuedPerPlayerSynchronizations.set($,X),this._queuedPlayerSynchronizations.set($.id,$.serialize())};_onPlayerLeftWorld=(J)=>{let $=this._createOrGetQueuedPlayerSync(J.player);$.rm=!0};_onPlayerReconnectedWorld=(J)=>{this._onPlayerJoinedWorld(J)};_onPlayerRequestNotificationPermission=(J)=>{let{player:$}=J,X=this._queuedPerPlayerSynchronizations.get($)??[];X.push(_0.createPacket(_0.outboundPackets.notificationPermissionRequestPacketDefinition,null,this._world.loop.currentTick)),this._queuedPerPlayerSynchronizations.set($,X)};_onPlayerRequestSync=(J)=>{J.player.connection.send([_0.createPacket(_0.outboundPackets.syncResponsePacketDefinition,{r:J.receivedAt,s:Date.now(),p:performance.now()-J.receivedAtMs,n:this._world.loop.nextTickMs},this._world.loop.currentTick)])};_onPlayerUILoad=(J)=>{let $=this._createOrGetQueuedPlayerUISync(J.playerUI);$.u=J.htmlUri};_onPlayerUILockPointer=(J)=>{let $=this._createOrGetQueuedPlayerUISync(J.playerUI);$.p=J.lock};_onPlayerUISendData=(J)=>{this._createOrGetQueuedPlayerUIDatasSync(J.playerUI).push(J.data)};_onSceneUILoad=(J)=>{let $=J.sceneUI.serialize();this._queuedSceneUISynchronizations.set($.i,$),this._loadedSceneUIs.add($.i)};_onSceneUISetAttachedToEntity=(J)=>{let $=this._createOrGetQueuedSceneUISync(J.sceneUI);$.e=J.entity?J.entity.id:void 0,$.p=J.entity?void 0:$.p};_onSceneUISetOffset=(J)=>{let $=this._createOrGetQueuedSceneUISync(J.sceneUI);$.o=J.offset?V1.serializeVector(J.offset):void 0};_onSceneUISetPosition=(J)=>{let $=this._createOrGetQueuedSceneUISync(J.sceneUI);$.p=J.position?V1.serializeVector(J.position):void 0,$.e=J.position?void 0:$.e};_onSceneUISetState=(J)=>{let $=this._createOrGetQueuedSceneUISync(J.sceneUI);$.s=J.state};_onSceneUISetViewDistance=(J)=>{let $=this._createOrGetQueuedSceneUISync(J.sceneUI);$.v=J.viewDistance};_onSceneUIUnload=(J)=>{let $=this._createOrGetQueuedSceneUISync(J.sceneUI);if(this._loadedSceneUIs.has($.i))this._queuedSceneUISynchronizations.delete($.i),this._loadedSceneUIs.delete($.i);else $.rm=!0};_onSimulationDebugRaycast=(J)=>{this._queuedDebugRaycastSynchronizations.push(V1.serializePhysicsDebugRaycast(J))};_onSimulationDebugRender=(J)=>{this._queuedBroadcasts.push(_0.createPacket(_0.outboundPackets.physicsDebugRenderPacketDefinition,{v:Array.from(J.vertices),c:Array.from(J.colors)},this._world.loop.currentTick))};_onWorldSetAmbientLightColor=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.ac=V1.serializeRgbColor(J.color)};_onWorldSetAmbientLightIntensity=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.ai=J.intensity};_onWorldSetDirectionalLightColor=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.dc=V1.serializeRgbColor(J.color)};_onWorldSetDirectionalLightIntensity=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.di=J.intensity};_onWorldSetDirectionalLightPosition=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.dp=V1.serializeVector(J.position)};_onWorldSetFogColor=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.fc=V1.serializeRgbColor(J.color)};_onWorldSetFogFar=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.ff=J.far};_onWorldSetFogNear=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.fn=J.near};_onWorldSetSkyboxIntensity=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.si=J.intensity};_onWorldSetSkyboxUri=(J)=>{let $=this._createOrGetQueuedWorldSync(J.world);$.s=J.uri};_createOrGetQueuedAudioSync(J){if(J.id===void 0)n.fatalError("NetworkSynchronizer._createOrGetQueuedAudioSync(): Audio has no id!");let $=this._queuedAudioSynchronizations.get(J.id);if(!$)$={i:J.id},this._queuedAudioSynchronizations.set(J.id,$);return $}_createOrGetQueuedBlockSync(J){let{x:$,y:X,z:Y}=J,Q=`${$},${X},${Y}`,W=this._queuedBlockSynchronizations.get(Q);if(!W)W={i:0,c:[$,X,Y]},this._queuedBlockSynchronizations.set(Q,W);return W}_createOrGetQueuedChunkSync(J){if(!J.originCoordinate)n.fatalError("NetworkSynchronizer._createOrGetQueuedChunkSync(): Chunk has no origin coordinate!");let{x:$,y:X,z:Y}=J.originCoordinate,Q=`${$},${X},${Y}`,W=this._queuedChunkSynchronizations.get(Q);if(!W)W={c:[$,X,Y]},this._queuedChunkSynchronizations.set(Q,W);return W}_createOrGetQueuedEntitySync(J){if(J.id===void 0)n.fatalError("NetworkSynchronizer._createOrGetQueuedEntitySync(): Entity has no id!");let $=this._queuedEntitySynchronizations.get(J.id);if(!$)$={i:J.id},this._queuedEntitySynchronizations.set(J.id,$);return $}_createOrGetQueuedLightSync(J){if(J.id===void 0)n.fatalError("NetworkSynchronizer._createOrGetQueuedLightSync(): Light has no id!");let $=this._queuedLightSynchronizations.get(J.id);if(!$)$={i:J.id},this._queuedLightSynchronizations.set(J.id,$);return $}_createOrGetQueuedParticleEmitterSync(J){if(J.id===void 0)n.fatalError("NetworkSynchronizer._createOrGetQueuedParticleEmitterSync(): ParticleEmitter has no id!");let $=this._queuedParticleEmitterSynchronizations.get(J.id);if(!$)$={i:J.id},this._queuedParticleEmitterSynchronizations.set(J.id,$);return $}_createOrGetQueuedPlayerSync(J){if(J.id===void 0)n.fatalError("NetworkSynchronizer._createOrGetQueuedPlayerSync(): Player has no id!");let $=this._queuedPlayerSynchronizations.get(J.id);if(!$)$={i:J.id},this._queuedPlayerSynchronizations.set(J.id,$);return $}_createOrGetQueuedPlayerCameraSync(J){let $=this._queuedPerPlayerCameraSynchronizations.get(J.player);if(!$)$={},this._queuedPerPlayerCameraSynchronizations.set(J.player,$);return $}_createOrGetQueuedPlayerUISync(J){let $=this._queuedPerPlayerUISynchronizations.get(J.player);if(!$)$={},this._queuedPerPlayerUISynchronizations.set(J.player,$);return $}_createOrGetQueuedPlayerUIDatasSync(J){let $=this._queuedPerPlayerUIDatasSynchronizations.get(J.player);if(!$)$=[],this._queuedPerPlayerUIDatasSynchronizations.set(J.player,$);return $}_createOrGetQueuedSceneUISync(J){if(J.id===void 0)n.fatalError("NetworkSynchronizer._createOrGetQueuedSceneUISync(): SceneUI has no id!");let $=this._queuedSceneUISynchronizations.get(J.id);if(!$)$={i:J.id},this._queuedSceneUISynchronizations.set(J.id,$);return $}_createOrGetQueuedWorldSync(J){if(J.id!==this._world.id)n.fatalError("NetworkSynchronizer._createOrGetQueuedWorldSync(): World does not match this network synchronizer world!");return this._queuedWorldSynchronization??={i:J.id}}_createOrGetSynchronizedPlayerReliablePackets(J,$){let X=this._synchronizedPlayerReliablePackets.get(J);if(!X)X=[...$],this._synchronizedPlayerReliablePackets.set(J,X);return X}}class XB{_particleEmitters=new Map;_nextParticleEmitterId=1;_world;constructor(J){this._world=J}get world(){return this._world}despawnEntityAttachedParticleEmitters(J){this.getAllEntityAttachedParticleEmitters(J).forEach(($)=>{$.despawn()})}getAllParticleEmitters(){return Array.from(this._particleEmitters.values())}getAllEntityAttachedParticleEmitters(J){return this.getAllParticleEmitters().filter(($)=>$.attachedToEntity===J)}registerParticleEmitter(J){if(J.id!==void 0)return J.id;let $=this._nextParticleEmitterId;return this._particleEmitters.set($,J),this._nextParticleEmitterId++,$}unregisterParticleEmitter(J){if(J.id===void 0)return;this._particleEmitters.delete(J.id)}}class YB{_sceneUIs=new Map;_nextSceneUIId=1;_world;constructor(J){this._world=J}get world(){return this._world}getAllSceneUIs(){return Array.from(this._sceneUIs.values())}getAllEntityAttachedSceneUIs(J){return this.getAllSceneUIs().filter(($)=>$.attachedToEntity===J)}getSceneUIById(J){return this._sceneUIs.get(J)}registerSceneUI(J){if(J.id!==void 0)return J.id;let $=this._nextSceneUIId;return this._sceneUIs.set($,J),this._nextSceneUIId++,$}unloadEntityAttachedSceneUIs(J){this.getAllEntityAttachedSceneUIs(J).forEach(($)=>{$.unload()})}unregisterSceneUI(J){if(J.id===void 0)return;this._sceneUIs.delete(J.id)}}var AC6=2,cC6=3;class QB{_accumulatorMs=0;_targetTicksPerSecond;_fixedTimestepMs;_fixedTimestepS;_maxAccumulatorMs;_nextTickMs=0;_lastLoopTimeMs=0;_tickFunction;_tickErrorCallback;_tickHandle=null;constructor(J,$,X){this._targetTicksPerSecond=J,this._fixedTimestepS=Math.fround(1/J),this._fixedTimestepMs=Math.fround(this._fixedTimestepS*1000),this._maxAccumulatorMs=this._fixedTimestepMs*cC6,this._tickFunction=$,this._tickErrorCallback=X}get targetTicksPerSecond(){return this._targetTicksPerSecond}get fixedTimestepMs(){return this._fixedTimestepMs}get fixedTimestepS(){return this._fixedTimestepS}get isStarted(){return!!this._tickHandle}get nextTickMs(){return this._nextTickMs}start(){if(this._tickHandle)return;this._lastLoopTimeMs=performance.now();let J=()=>{let $=performance.now(),X=$-this._lastLoopTimeMs;if(this._lastLoopTimeMs=$,this._accumulatorMs+=X,this._accumulatorMs>this._maxAccumulatorMs)this._accumulatorMs=this._maxAccumulatorMs;if(this._accumulatorMs>=this._fixedTimestepMs)T6.startSpan({operation:"ticker_tick"},()=>{let Y=0;while(this._accumulatorMs>=this._fixedTimestepMs&&Y<AC6)this._tick(this._fixedTimestepMs),this._accumulatorMs-=this._fixedTimestepMs,Y++});this._nextTickMs=Math.max(0,this._fixedTimestepMs-this._accumulatorMs),this._tickHandle=setTimeout(J,this._nextTickMs)};J()}stop(){if(!this._tickHandle)return;clearTimeout(this._tickHandle),this._tickHandle=null}_tick(J){try{this._tickFunction(J)}catch($){if($ instanceof Error&&this._tickErrorCallback)this._tickErrorCallback($);else n.warning(`Ticker._tick(): tick callback threw an error, but it was not an instance of Error. Error: ${$}`)}}}var JO1;((W)=>{W.START="WORLD_LOOP.START";W.STOP="WORLD_LOOP.STOP";W.TICK_START="WORLD_LOOP.TICK_START";W.TICK_END="WORLD_LOOP.TICK_END";W.TICK_ERROR="WORLD_LOOP.TICK_ERROR"})(JO1||={});class WB extends $1{_currentTick=0;_ticker;_world;constructor(J,$=ei){super();this._ticker=new QB($,this._tick,this._onTickError),this._world=J}get currentTick(){return this._currentTick}get isStarted(){return this._ticker.isStarted}get nextTickMs(){return this._ticker.nextTickMs}get timestepS(){return this._ticker.fixedTimestepS}get world(){return this._world}start(){this._ticker.start(),this.emitWithWorld(this._world,"WORLD_LOOP.START",{worldLoop:this})}stop(){this._ticker.stop(),this.emitWithWorld(this._world,"WORLD_LOOP.STOP",{worldLoop:this})}_tick=(J)=>{this.emitWithWorld(this._world,"WORLD_LOOP.TICK_START",{worldLoop:this,tickDeltaMs:J});let $=performance.now();T6.startSpan({operation:"world_tick",attributes:{serverPlayerCount:F$.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}},()=>{T6.startSpan({operation:"entities_tick"},()=>this._world.entityManager.tickEntities(J)),T6.startSpan({operation:"simulation_step"},()=>this._world.simulation.step(J)),T6.startSpan({operation:"entities_emit_updates"},()=>this._world.entityManager.checkAndEmitUpdates()),T6.startSpan({operation:"network_synchronize"},()=>this._world.networkSynchronizer.synchronize())}),this._currentTick++,this.emitWithWorld(this._world,"WORLD_LOOP.TICK_END",{worldLoop:this,tickDurationMs:performance.now()-$})};_onTickError=(J)=>{n.error(`WorldLoop._onTickError(): Error: ${J}`),this.emitWithWorld(this._world,"WORLD_LOOP.TICK_ERROR",{worldLoop:this,error:J})}}var $n;((H)=>{H.SET_AMBIENT_LIGHT_COLOR="WORLD.SET_AMBIENT_LIGHT_COLOR";H.SET_AMBIENT_LIGHT_INTENSITY="WORLD.SET_AMBIENT_LIGHT_INTENSITY";H.SET_DIRECTIONAL_LIGHT_COLOR="WORLD.SET_DIRECTIONAL_LIGHT_COLOR";H.SET_DIRECTIONAL_LIGHT_INTENSITY="WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY";H.SET_DIRECTIONAL_LIGHT_POSITION="WORLD.SET_DIRECTIONAL_LIGHT_POSITION";H.SET_FOG_COLOR="WORLD.SET_FOG_COLOR";H.SET_FOG_FAR="WORLD.SET_FOG_FAR";H.SET_FOG_NEAR="WORLD.SET_FOG_NEAR";H.SET_SKYBOX_INTENSITY="WORLD.SET_SKYBOX_INTENSITY";H.SET_SKYBOX_URI="WORLD.SET_SKYBOX_URI";H.START="WORLD.START";H.STOP="WORLD.STOP"})($n||={});class KB extends $1{_id;_ambientLightColor;_ambientLightIntensity;_audioManager;_blockTypeRegistry;_chatManager;_chunkLattice;_directionalLightColor;_directionalLightIntensity;_directionalLightPosition;_entityManager;_fogColor;_fogFar;_fogNear;_lightManager;_loop;_name;_networkSynchronizer;_particleEmitterManager;_sceneUIManager;_simulation;_skyboxIntensity;_skyboxUri;_tag;constructor(J){super();if(this._id=J.id,this._ambientLightColor=J.ambientLightColor??{r:255,g:255,b:255},this._ambientLightIntensity=J.ambientLightIntensity??1,this._directionalLightColor=J.directionalLightColor??{r:255,g:255,b:255},this._directionalLightIntensity=J.directionalLightIntensity??3,this._directionalLightPosition=J.directionalLightPosition??{x:100,y:150,z:100},this._fogColor=J.fogColor,this._fogFar=J.fogFar??550,this._fogNear=J.fogNear??500,this._name=J.name,this._skyboxIntensity=J.skyboxIntensity??1,this._skyboxUri=J.skyboxUri,this._tag=J.tag,this._audioManager=new vz(this),this._blockTypeRegistry=new EF(this),this._chatManager=new FU(this),this._chunkLattice=new UU(this),this._entityManager=new LU(this),this._lightManager=new JB(this),this._loop=new WB(this,J.tickRate),this._networkSynchronizer=new AC(this),this._particleEmitterManager=new XB(this),this._sceneUIManager=new YB(this),this._simulation=new $B(this,J.tickRate,J.gravity),J.map)this.loadMap(J.map)}get id(){return this._id}get ambientLightColor(){return this._ambientLightColor}get ambientLightIntensity(){return this._ambientLightIntensity}get blockTypeRegistry(){return this._blockTypeRegistry}get chatManager(){return this._chatManager}get chunkLattice(){return this._chunkLattice}get directionalLightColor(){return this._directionalLightColor}get directionalLightIntensity(){return this._directionalLightIntensity}get directionalLightPosition(){return this._directionalLightPosition}get entityManager(){return this._entityManager}get fogColor(){return this._fogColor}get fogFar(){return this._fogFar}get fogNear(){return this._fogNear}get lightManager(){return this._lightManager}get loop(){return this._loop}get name(){return this._name}get networkSynchronizer(){return this._networkSynchronizer}get particleEmitterManager(){return this._particleEmitterManager}get sceneUIManager(){return this._sceneUIManager}get simulation(){return this._simulation}get skyboxIntensity(){return this._skyboxIntensity}get skyboxUri(){return this._skyboxUri}get audioManager(){return this._audioManager}get tag(){return this._tag}loadMap(J){if(this.chunkLattice.clear(),J.blockTypes)for(let $ of J.blockTypes)this.blockTypeRegistry.registerGenericBlockType({id:$.id,isLiquid:$.isLiquid,lightLevel:$.lightLevel,name:$.name,textureUri:$.textureUri});if(J.blocks){let $={};for(let X in J.blocks){let Y=J.blocks[X],Q=X.indexOf(","),W=X.indexOf(",",Q+1),K=Number(X.slice(0,Q)),Z=Number(X.slice(Q+1,W)),G=Number(X.slice(W+1));if(!$[Y])$[Y]=[];$[Y].push({x:K,y:Z,z:G})}this.chunkLattice.initializeBlocks($)}if(J.entities)for(let $ in J.entities){let X=J.entities[$],Y=$.indexOf(","),Q=$.indexOf(",",Y+1),W=Number($.slice(0,Y)),K=Number($.slice(Y+1,Q)),Z=Number($.slice(Q+1));new b6({isEnvironmental:!0,...X}).spawn(this,{x:W,y:K,z:Z})}}setAmbientLightColor(J){this._ambientLightColor=J,this.emit("WORLD.SET_AMBIENT_LIGHT_COLOR",{world:this,color:J})}setAmbientLightIntensity(J){this._ambientLightIntensity=J,this.emit("WORLD.SET_AMBIENT_LIGHT_INTENSITY",{world:this,intensity:J})}setDirectionalLightColor(J){this._directionalLightColor=J,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_COLOR",{world:this,color:J})}setDirectionalLightIntensity(J){this._directionalLightIntensity=J,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY",{world:this,intensity:J})}setDirectionalLightPosition(J){this._directionalLightPosition=J,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_POSITION",{world:this,position:J})}setFogColor(J){this._fogColor=J,this.emit("WORLD.SET_FOG_COLOR",{world:this,color:J})}setFogFar(J){this._fogFar=J,this.emit("WORLD.SET_FOG_FAR",{world:this,far:J})}setFogNear(J){this._fogNear=J,this.emit("WORLD.SET_FOG_NEAR",{world:this,near:J})}setSkyboxIntensity(J){this._skyboxIntensity=J,this.emit("WORLD.SET_SKYBOX_INTENSITY",{world:this,intensity:J})}setSkyboxUri(J){this._skyboxUri=J,this.emit("WORLD.SET_SKYBOX_URI",{world:this,uri:J})}start(){if(this._loop.isStarted)return;this._loop.start(),this.emit("WORLD.START",{world:this,startedAtMs:Date.now()})}stop(){if(!this._loop.isStarted)return;this._loop.stop(),this.emit("WORLD.STOP",{world:this,stoppedAtMs:Date.now()})}serialize(){return V1.serializeWorld(this)}}var $O1;(($)=>$.WORLD_CREATED="WORLD_MANAGER.WORLD_CREATED")($O1||={});class bK{static instance=new bK;_defaultWorld;_nextWorldId=1;_worlds=new Map;createWorld(J){let $=new KB({...J,id:this._nextWorldId++});return $.start(),this._worlds.set($.id,$),$1.globalInstance.emit("WORLD_MANAGER.WORLD_CREATED",{world:$}),$}getAllWorlds(){return Array.from(this._worlds.values())}getDefaultWorld(){return this._defaultWorld??=this.createWorld({name:"Default World",skyboxUri:"skyboxes/partly-cloudy"}),this._defaultWorld}getWorldsByTag(J){let $=[];return this._worlds.forEach((X)=>{if(X.tag===J)$.push(X)}),$}getWorld(J){return this._worlds.get(J)}setDefaultWorld(J){this._defaultWorld=J}}var XO1;((Y)=>{Y.PLAYER_CONNECTED="PLAYER_MANAGER.PLAYER_CONNECTED";Y.PLAYER_DISCONNECTED="PLAYER_MANAGER.PLAYER_DISCONNECTED";Y.PLAYER_RECONNECTED="PLAYER_MANAGER.PLAYER_RECONNECTED"})(XO1||={});class F${static instance=new F$;worldSelectionHandler;_connectionPlayers=new Map;constructor(){$1.globalInstance.on("CONNECTION.OPENED",({connection:J,session:$})=>{this._onConnectionOpened(J,$)}),$1.globalInstance.on("CONNECTION.DISCONNECTED",({connection:J})=>{this._onConnectionDisconnected(J)}),$1.globalInstance.on("CONNECTION.RECONNECTED",({connection:J})=>{this._onConnectionReconnected(J)}),$1.globalInstance.on("CONNECTION.CLOSED",({connection:J})=>{this._onConnectionClosed(J)})}get playerCount(){return this._connectionPlayers.size}getConnectedPlayers(){return Array.from(this._connectionPlayers.values())}getConnectedPlayersByWorld(J){return this.getConnectedPlayers().filter(($)=>$.world===J)}getConnectedPlayerByUsername(J){return Array.from(this._connectionPlayers.values()).find(($)=>{return $.username.toLowerCase()===J.toLowerCase()})}async _onConnectionOpened(J,$){let X=new kq(J,$);await X.loadInitialPersistedData(),$1.globalInstance.emit("PLAYER_MANAGER.PLAYER_CONNECTED",{player:X});let Y=await this.worldSelectionHandler?.(X);X.joinWorld(Y??bK.instance.getDefaultWorld()),this._connectionPlayers.set(J,X)}_onConnectionDisconnected(J){let $=this._connectionPlayers.get(J);if($)$.resetInputs(),$.camera.reset()}_onConnectionReconnected(J){let $=this._connectionPlayers.get(J);if($)$.reconnected(),$1.globalInstance.emit("PLAYER_MANAGER.PLAYER_RECONNECTED",{player:$});else n.warning(`PlayerManager._onConnectionReconnected(): Connection ${J.id} not in the PlayerManager._connectionPlayers map.`)}_onConnectionClosed(J){let $=this._connectionPlayers.get(J);if($)$.disconnect(),this._connectionPlayers.delete(J),CW.instance.unloadPlayerData($).catch((X)=>{n.warning(`PlayerManager._onConnectionClosed(): Failed to unload player data for player ${$.id}. Error: ${X}`)}),$1.globalInstance.emit("PLAYER_MANAGER.PLAYER_DISCONNECTED",{player:$});else n.warning(`PlayerManager._onConnectionClosed(): Connection ${J.id} not in the PlayerManager._connectionPlayers map.`)}}import{randomBytes as hC6}from"crypto";import{Http3Server as fC6}from"@fails-components/webtransport";class ZB extends $1{static instance=new ZB;_connectionIdConnections=new Map;_userIdConnections=new Map;_wss;_wts;constructor(){super();this._wss=new Ch.default({noServer:!0}),this._wss.on("connection",(J,$)=>this._onConnection(J,void 0,$.connectionId,$.session)),this._wts=new fC6({port:SC,host:"0.0.0.0",secret:hC6(32).toString("hex"),cert:kC,privKey:EC,defaultDatagramsReadableMode:"bytes",initialStreamFlowControlWindow:1048576,streamShouldAutoTuneReceiveWindow:!0,streamFlowControlWindowSizeLimit:6291456,initialSessionFlowControlWindow:2097152,sessionShouldAutoTuneReceiveWindow:!0,sessionFlowControlWindowSizeLimit:15728640}),this._wts.setRequestCallback(this._onWebTransportRequest),this._startWebTransport().catch((J)=>{n.error(`Socket: WebTransport server failed to start or crashed while listening for sessions. Error: ${J}`)}),$1.globalInstance.on("WEBSERVER.UPGRADE",async({req:J,socket:$,head:X})=>{await this._authorizeAndConnectWebsocket(J,$,X)})}async _authorizeAndConnectWebsocket(J,$,X){let Y=await this._authorizeConnection(J.url??"");if(Y.error){$.end();return}J.connectionId=Y.connectionId,J.session=Y.session,$.setNoDelay(!0),this._wss.handleUpgrade(J,$,X,(Q)=>{if(Q.readyState!==Cq.default.OPEN)Q.once("open",()=>this._wss.emit("connection",Q,J));else this._wss.emit("connection",Q,J)})}async _authorizeConnection(J){let $=J.includes("?")?J.slice(J.indexOf("?")):"",X=new URLSearchParams($),Y=X.get("connectionId")??void 0,Q=X.get("sessionToken")??"";if(Y&&this._isValidConnectionId(Y))return{connectionId:Y};else{let W=await k7.instance.getPlayerSession(Q);if(W?.error)return{error:W.error};else if(W)return{session:W}}return{}}_isValidConnectionId(J){return this._connectionIdConnections.has(J)}_onConnection=(J,$,X,Y)=>{let Q=Y?.user.id,W=(X&&this._connectionIdConnections.get(X))??(Q&&this._userIdConnections.get(Q));if(W){if(J)W.bindWs(J);if($)W.bindWt($).catch((K)=>{n.error(`Socket._onConnection(): WebTransport binding failed. Error: ${K}`)})}else{let K=new v$(J,$,Y);if(K.on("CONNECTION.CLOSED",()=>{if(this._connectionIdConnections.delete(K.id),Q)this._userIdConnections.delete(Q)}),this._connectionIdConnections.set(K.id,K),Q)this._userIdConnections.set(Q,K)}};_onWebTransportRequest=async({header:J})=>{let{connectionId:$,session:X,error:Y}=await this._authorizeConnection(J[":path"]??"");return{status:Y?401:200,path:"/",userData:{connectionId:$,session:X}}};async _startWebTransport(){this._wts.startServer();for await(let J of this._wts.sessionStream("/"))try{let{connectionId:$,session:X}=J.userData;this._onConnection(void 0,J,$,X)}catch($){n.error(`Socket._startWebTransport(): WebTransport connection failed. Error: ${$}`)}}}Buffer.poolSize=134217728;var YO1;((X)=>{X.START="GAMESERVER.START";X.STOP="GAMESERVER.STOP"})(YO1||={});function bC6(J){W8.init().then(()=>{return yK.instance.blockTextureRegistry.preloadAtlas()}).then(()=>{return yK.instance.modelRegistry.preloadModels()}).then(()=>{if(J.length>0)J(yK.instance.worldManager.getDefaultWorld());else J();yK.instance.start()}).catch(($)=>{n.fatalError(`Failed to initialize the game engine, exiting. Error: ${$}`)})}class yK{static _instance;_blockTextureRegistry=eQ.instance;_modelRegistry=k5.instance;_playerManager=F$.instance;_socket=ZB.instance;_worldManager=bK.instance;_webServer=Qz.instance;constructor(){}static get instance(){if(!this._instance)this._instance=new yK;return this._instance}get blockTextureRegistry(){return this._blockTextureRegistry}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(){if($1.globalInstance.emit("GAMESERVER.START",{startedAtMs:performance.now()}),this._webServer.start(),process.env.NODE_ENV!=="production")console.log("---"),console.log("\uD83D\uDFE2 Server Running: You can test & play it at: https://hytopia.com/play")}}var L5=M0(M3(),1);class N3 extends Float32Array{constructor(J,$,X,Y){super([J,$,X,Y])}get determinant(){return L5.mat2.determinant(this)}get frobeniusNorm(){return L5.mat2.frob(this)}static create(){let J=new N3(0,0,0,0);return L5.mat2.identity(J),J}static fromRotation(J){let $=N3.create();return L5.mat2.fromRotation($,J),$}static fromScaling(J){let $=N3.create();return L5.mat2.fromScaling($,J),$}add(J){return L5.mat2.add(this,this,J),this}adjoint(){return L5.mat2.adjoint(this,this),this}clone(){return new N3(this[0],this[1],this[2],this[3])}copy(J){return L5.mat2.copy(this,J),this}equals(J){return L5.mat2.equals(this,J)}exactEquals(J){return L5.mat2.exactEquals(this,J)}identity(){return L5.mat2.identity(this),this}invert(){return L5.mat2.invert(this,this),this}multiply(J){return L5.mat2.mul(this,this,J),this}multiplyScalar(J){return L5.mat2.multiplyScalar(this,this,J),this}rotate(J){return L5.mat2.rotate(this,this,J),this}subtract(J){return L5.mat2.sub(this,this,J),this}toString(){return`[${this[0]},${this[1]}][${this[2]},${this[3]}]`}transpose(){return L5.mat2.transpose(this,this),this}}var k6=M0(M3(),1);class xX extends Float32Array{constructor(J,$,X,Y,Q,W,K,Z,G){super([J,$,X,Y,Q,W,K,Z,G])}get determinant(){return k6.mat3.determinant(this)}get frobeniusNorm(){return k6.mat3.frob(this)}static create(){let J=new xX(0,0,0,0,0,0,0,0,0);return k6.mat3.identity(J),J}static fromMatrix4(J){let $=xX.create();return k6.mat3.fromMat4($,J),$}static fromQuaternion(J){let $=xX.create();return k6.mat3.fromQuat($,J),$}static fromRotation(J){let $=xX.create();return k6.mat3.fromRotation($,J),$}static fromScaling(J){let $=xX.create();return k6.mat3.fromScaling($,J),$}static fromTranslation(J){let $=xX.create();return k6.mat3.fromTranslation($,J),$}add(J){return k6.mat3.add(this,this,J),this}adjoint(){return k6.mat3.adjoint(this,this),this}clone(){return new xX(this[0],this[1],this[2],this[3],this[4],this[5],this[6],this[7],this[8])}copy(J){return k6.mat3.copy(this,J),this}equals(J){return k6.mat3.equals(this,J)}exactEquals(J){return k6.mat3.exactEquals(this,J)}identity(){return k6.mat3.identity(this),this}invert(){return k6.mat3.invert(this,this),this}multiply(J){return k6.mat3.mul(this,this,J),this}multiplyScalar(J){return k6.mat3.multiplyScalar(this,this,J),this}transformVector(J){return J.transformMatrix3(this)}projection(J,$){return k6.mat3.projection(this,J,$),this}rotate(J){return k6.mat3.rotate(this,this,J),this}subtract(J){return k6.mat3.sub(this,this,J),this}toString(){return`[${this[0]},${this[1]},${this[2]}][${this[3]},${this[4]},${this[5]}][${this[6]},${this[7]},${this[8]}]`}transpose(){return k6.mat3.transpose(this,this),this}}var $8=M0(M3(),1);class u4 extends Float32Array{constructor(J,$,X,Y,Q,W,K,Z,G,V,q,z,H,v,F,U){super([J,$,X,Y,Q,W,K,Z,G,V,q,z,H,v,F,U])}get determinant(){return $8.mat4.determinant(this)}get frobeniusNorm(){return $8.mat4.frob(this)}static create(){let J=new u4(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return $8.mat4.identity(J),J}static fromQuaternion(J){let $=u4.create();return $8.mat4.fromQuat($,J),$}static fromRotation(J,$){let X=u4.create();return $8.mat4.fromRotation(X,J,$),X}static fromRotationTranslation(J,$){let X=u4.create();return $8.mat4.fromRotationTranslation(X,J,$),X}static fromRotationTranslationScale(J,$,X){let Y=u4.create();return $8.mat4.fromRotationTranslationScale(Y,J,$,X),Y}static fromRotationTranslationScaleOrigin(J,$,X,Y){let Q=u4.create();return $8.mat4.fromRotationTranslationScaleOrigin(Q,J,$,X,Y),Q}static fromScaling(J){let $=u4.create();return $8.mat4.fromScaling($,J),$}static fromTranslation(J){let $=u4.create();return $8.mat4.fromTranslation($,J),$}static fromXRotation(J){let $=u4.create();return $8.mat4.fromXRotation($,J),$}static fromYRotation(J){let $=u4.create();return $8.mat4.fromYRotation($,J),$}static fromZRotation(J){let $=u4.create();return $8.mat4.fromZRotation($,J),$}add(J){return $8.mat4.add(this,this,J),this}adjoint(){return $8.mat4.adjoint(this,this),this}clone(){return new u4(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(J){return $8.mat4.copy(this,J),this}equals(J){return $8.mat4.equals(this,J)}exactEquals(J){return $8.mat4.exactEquals(this,J)}frustrum(J,$,X,Y,Q,W){return $8.mat4.frustum(this,J,$,X,Y,Q,W),this}identity(){return $8.mat4.identity(this),this}invert(){return $8.mat4.invert(this,this),this}lookAt(J,$,X){return $8.mat4.lookAt(this,J,$,X),this}multiply(J){return $8.mat4.mul(this,this,J),this}multiplyScalar(J){return $8.mat4.multiplyScalar(this,this,J),this}orthographic(J,$,X,Y,Q,W){return $8.mat4.ortho(this,J,$,X,Y,Q,W),this}perspective(J,$,X,Y){return $8.mat4.perspective(this,J,$,X,Y),this}rotate(J,$){return $8.mat4.rotate(this,this,J,$),this}rotateX(J){return $8.mat4.rotateX(this,this,J),this}rotateY(J){return $8.mat4.rotateY(this,this,J),this}rotateZ(J){return $8.mat4.rotateZ(this,this,J),this}scale(J){return $8.mat4.scale(this,this,J),this}subtract(J){return $8.mat4.sub(this,this,J),this}targetTo(J,$,X){return $8.mat4.targetTo(this,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(J){return $8.mat4.translate(this,this,J),this}transpose(){return $8.mat4.transpose(this,this),this}}var b8=M0(M3(),1);class Wz extends Float32Array{constructor(J,$,X,Y){super([J,$,X,Y])}get length(){return b8.quat.length(this)}get squaredLength(){return b8.quat.squaredLength(this)}get magnitude(){return b8.quat.length(this)}get squaredMagnitude(){return b8.quat.squaredLength(this)}get x(){return this[0]}set x(J){this[0]=J}get y(){return this[1]}set y(J){this[1]=J}get z(){return this[2]}set z(J){this[2]=J}get w(){return this[3]}set w(J){this[3]=J}static fromEuler(J,$,X){let Y=b8.quat.fromEuler(new Float32Array(4),J,$,X);return new Wz(Y[0],Y[1],Y[2],Y[3])}static fromQuaternionLike(J){return new Wz(J.x,J.y,J.z,J.w)}clone(){return new Wz(this.x,this.y,this.z,this.w)}conjugate(){return b8.quat.conjugate(this,this),this}copy(J){return b8.quat.copy(this,J),this}dot(J){return b8.quat.dot(this,J)}exponential(){return b8.quat.exp(this,this),this}equals(J){return b8.quat.equals(this,J)}exactEquals(J){return b8.quat.exactEquals(this,J)}getAngle(J){return b8.quat.getAngle(this,J)}identity(){return b8.quat.identity(this),this}invert(){return b8.quat.invert(this,this),this}lerp(J,$){return b8.quat.lerp(this,this,J,$),this}logarithm(){return b8.quat.ln(this,this),this}multiply(J){return b8.quat.multiply(this,this,J),this}transformVector(J){return J.transformQuaternion(this)}normalize(){return b8.quat.normalize(this,this),this}power(J){return b8.quat.pow(this,this,J),this}randomize(){return b8.quat.random(this),this}rotateX(J){return b8.quat.rotateX(this,this,J),this}rotateY(J){return b8.quat.rotateY(this,this,J),this}rotateZ(J){return b8.quat.rotateZ(this,this,J),this}scale(J){return b8.quat.scale(this,this,J),this}setAxisAngle(J,$){return b8.quat.setAxisAngle(this,J,$),this}slerp(J,$){return b8.quat.slerp(this,this,J,$),this}toString(){return`${this.x},${this.y},${this.z},${this.w}`}}var w8=M0(M3(),1);class GB extends Float32Array{constructor(J,$){super([J,$])}get length(){return w8.vec2.length(this)}get squaredLength(){return w8.vec2.squaredLength(this)}get magnitude(){return w8.vec2.length(this)}get squaredMagnitude(){return w8.vec2.squaredLength(this)}get x(){return this[0]}set x(J){this[0]=J}get y(){return this[1]}set y(J){this[1]=J}static create(){return new GB(0,0)}add(J){return w8.vec2.add(this,this,J),this}angle(J){return w8.vec2.angle(this,J)}ceil(){return w8.vec2.ceil(this,this),this}clone(){return new GB(this.x,this.y)}copy(J){return w8.vec2.copy(this,J),this}distance(J){return w8.vec2.distance(this,J)}divide(J){return w8.vec2.divide(this,this,J),this}dot(J){return w8.vec2.dot(this,J)}equals(J){return w8.vec2.equals(this,J)}exactEquals(J){return w8.vec2.exactEquals(this,J)}floor(){return w8.vec2.floor(this,this),this}invert(){return w8.vec2.inverse(this,this),this}lerp(J,$){return w8.vec2.lerp(this,this,J,$),this}max(J){return w8.vec2.max(this,this,J),this}min(J){return w8.vec2.min(this,this,J),this}multiply(J){return w8.vec2.mul(this,this,J),this}negate(){return w8.vec2.negate(this,this),this}normalize(){return w8.vec2.normalize(this,this),this}randomize(J){return w8.vec2.random(this,J),this}rotate(J,$){return w8.vec2.rotate(this,this,J,$),this}round(){return w8.vec2.round(this,this),this}scale(J){return w8.vec2.scale(this,this,J),this}scaleAndAdd(J,$){return w8.vec2.scaleAndAdd(this,this,J,$),this}subtract(J){return w8.vec2.sub(this,this,J),this}toString(){return`${this.x},${this.y}`}transformMatrix2(J){return w8.vec2.transformMat2(this,this,J),this}transformMatrix3(J){return w8.vec2.transformMat3(this,this,J),this}transformMatrix4(J){return w8.vec2.transformMat4(this,this,J),this}zero(){return w8.vec2.zero(this),this}}var z8=M0(M3(),1);class Kz extends Float32Array{constructor(J,$,X){super([J,$,X])}get length(){return z8.vec3.length(this)}get squaredLength(){return z8.vec3.squaredLength(this)}get magnitude(){return z8.vec3.length(this)}get squaredMagnitude(){return z8.vec3.squaredLength(this)}get x(){return this[0]}set x(J){this[0]=J}get y(){return this[1]}set y(J){this[1]=J}get z(){return this[2]}set z(J){this[2]=J}static create(){return new Kz(0,0,0)}static fromVector3Like(J){return new Kz(J.x,J.y,J.z)}add(J){return z8.vec3.add(this,this,J),this}ceil(){return z8.vec3.ceil(this,this),this}clone(){return new Kz(this.x,this.y,this.z)}copy(J){return z8.vec3.copy(this,J),this}cross(J){return z8.vec3.cross(this,this,J),this}distance(J){return z8.vec3.distance(this,J)}divide(J){return z8.vec3.div(this,this,J),this}dot(J){return z8.vec3.dot(this,J)}equals(J){return z8.vec3.equals(this,J)}exactEquals(J){return z8.vec3.exactEquals(this,J)}floor(){return z8.vec3.floor(this,this),this}invert(){return z8.vec3.inverse(this,this),this}lerp(J,$){return z8.vec3.lerp(this,this,J,$),this}max(J){return z8.vec3.max(this,this,J),this}min(J){return z8.vec3.min(this,this,J),this}multiply(J){return z8.vec3.mul(this,this,J),this}negate(){return z8.vec3.negate(this,this),this}normalize(){return z8.vec3.normalize(this,this),this}randomize(J){return z8.vec3.random(this,J),this}rotateX(J,$){return z8.vec3.rotateX(this,this,J,$),this}rotateY(J,$){return z8.vec3.rotateY(this,this,J,$),this}rotateZ(J,$){return z8.vec3.rotateZ(this,this,J,$),this}round(){return z8.vec3.round(this,this),this}scale(J){return z8.vec3.scale(this,this,J),this}scaleAndAdd(J,$){return z8.vec3.scaleAndAdd(this,this,J,$),this}subtract(J){return z8.vec3.sub(this,this,J),this}toString(){return`${this.x},${this.y},${this.z}`}transformMatrix3(J){return z8.vec3.transformMat3(this,this,J),this}transformMatrix4(J){return z8.vec3.transformMat4(this,this,J),this}transformQuaternion(J){return z8.vec3.transformQuat(this,this,J),this}zero(){return z8.vec3.zero(this),this}}var dR1=M0(gR1(),1);var pR1=0.099856;class VB extends iK{faceSpeed=0;idleLoopedAnimations=[];idleLoopedAnimationsSpeed;jumpOneshotAnimations=[];moveLoopedAnimations=[];moveLoopedAnimationsSpeed;moveSpeed=0;_faceTarget;_jumpHeight=0;_moveCompletesWhenStuck=!1;_moveIgnoreAxes={};_moveStartMoveAnimations=!1;_moveStartIdleAnimationsOnCompletion=!0;_moveStoppingDistanceSquared=pR1;_moveStuckAccumulatorMs=0;_moveStuckLastPosition;_moveTarget;_onFace;_onFaceComplete;_onMove;_onMoveComplete;_stopFaceRequested=!1;_stopMoveRequested=!1;constructor(J={}){super();this.idleLoopedAnimations=J.idleLoopedAnimations??this.idleLoopedAnimations,this.idleLoopedAnimationsSpeed=J.idleLoopedAnimationsSpeed??this.idleLoopedAnimationsSpeed,this.jumpOneshotAnimations=J.jumpOneshotAnimations??this.jumpOneshotAnimations,this.moveLoopedAnimations=J.moveLoopedAnimations??this.moveLoopedAnimations,this.moveLoopedAnimationsSpeed=J.moveLoopedAnimationsSpeed??this.moveLoopedAnimationsSpeed}spawn(J){super.spawn(J),this._startIdleAnimations(J)}face(J,$,X){this._faceTarget=J,this.faceSpeed=$,this._onFace=X?.faceCallback,this._onFaceComplete=X?.faceCompleteCallback}jump(J){this._jumpHeight=J}move(J,$,X){this.moveSpeed=$,this._moveCompletesWhenStuck=X?.moveCompletesWhenStuck??!1,this._moveIgnoreAxes=X?.moveIgnoreAxes??{},this._moveStartIdleAnimationsOnCompletion=X?.moveStartIdleAnimationsOnCompletion??!0,this._moveStartMoveAnimations=!0,this._moveStoppingDistanceSquared=X?.moveStoppingDistance?X.moveStoppingDistance**2:pR1,this._moveTarget=J,this._onMove=X?.moveCallback,this._onMoveComplete=X?.moveCompleteCallback,this._moveStuckAccumulatorMs=0,this._moveStuckLastPosition=void 0}stopFace(){this._stopFaceRequested=!0}stopMove(){this._stopMoveRequested=!0}tick(J,$){if(super.tick(J,$),!this._moveTarget&&!this._faceTarget&&!this._jumpHeight)return;if(this._moveStartMoveAnimations)this._startMoveAnimations(J),this._moveStartMoveAnimations=!1;let X=$/1000,Y=J.position;if(J.isDynamic&&this._jumpHeight>0){let Q=Math.abs(J.world.simulation.gravity.y),W=Math.sqrt(2*Q*this._jumpHeight);J.applyImpulse({x:0,y:W*J.mass,z:0}),this._jumpHeight=0,this._startJumpAnimations(J)}if(this._moveTarget){let Q={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},W=Q.x*Q.x+Q.y*Q.y+Q.z*Q.z,K=!1;if(this._moveCompletesWhenStuck){if(this._moveStuckAccumulatorMs+=$,this._moveStuckAccumulatorMs>=500){if(this._moveStuckLastPosition){let Z=Y.x-this._moveStuckLastPosition.x,G=Y.y-this._moveStuckLastPosition.y,V=Y.z-this._moveStuckLastPosition.z;K=Math.sqrt(Z*Z+G*G+V*V)<this.moveSpeed*0.1}this._moveStuckLastPosition=Y,this._moveStuckAccumulatorMs=0}}if(W>this._moveStoppingDistanceSquared&&!this._stopMoveRequested&&!K){let Z=Math.sqrt(W),G=this.moveSpeed*X,q=Math.min(Z,G)/Z,z={x:Y.x+Q.x*q,y:Y.y+Q.y*q,z:Y.z+Q.z*q};if(J.setPosition(z),this._onMove)this._onMove(z,this._moveTarget)}else{if(this._moveStuckAccumulatorMs=0,this._moveStuckLastPosition=void 0,this._moveTarget=void 0,this._stopMoveRequested=!1,this._moveStartIdleAnimationsOnCompletion)this._startIdleAnimations(J);if(this._onMoveComplete){let Z=this._onMoveComplete;this._onMove=void 0,this._onMoveComplete=void 0,Z(Y)}}}if(this._faceTarget){let Q={x:this._faceTarget.x-Y.x,z:this._faceTarget.z-Y.z},W=Math.atan2(-Q.x,-Q.z),K=J.rotation,Z=Math.atan2(2*(K.w*K.y),1-2*(K.y*K.y)),G=W-Z;while(G>Math.PI)G-=2*Math.PI;while(G<-Math.PI)G+=2*Math.PI;if(Math.abs(G)>0.01&&!this._stopFaceRequested){let V=this.faceSpeed*X,q=Math.abs(G)<V?G:Math.sign(G)*V,H=(Z+q)/2,v={x:0,y:Math.fround(Math.sin(H)),z:0,w:Math.fround(Math.cos(H))};if(J.setRotation(v),this._onFace)this._onFace(K,v)}else if(this._faceTarget=void 0,this._stopFaceRequested=!1,this._onFaceComplete){let V=this._onFaceComplete;this._onFace=void 0,this._onFaceComplete=void 0,V(J.rotation)}}}_startIdleAnimations(J){if(this.idleLoopedAnimationsSpeed)J.setModelAnimationsPlaybackRate(this.idleLoopedAnimationsSpeed);J.stopModelAnimations(this.moveLoopedAnimations),J.stopModelAnimations(this.jumpOneshotAnimations),J.startModelLoopedAnimations(this.idleLoopedAnimations)}_startJumpAnimations(J){J.stopModelAnimations(this.moveLoopedAnimations),J.stopModelAnimations(this.idleLoopedAnimations),J.startModelOneshotAnimations(this.jumpOneshotAnimations)}_startMoveAnimations(J){if(this.moveLoopedAnimationsSpeed)J.setModelAnimationsPlaybackRate(this.moveLoopedAnimationsSpeed);J.stopModelAnimations(this.jumpOneshotAnimations),J.stopModelAnimations(this.idleLoopedAnimations),J.startModelLoopedAnimations(this.moveLoopedAnimations)}}class qn extends VB{_debug=!1;_entity;_maxFall=0;_maxJump=0;_maxOpenSetIterations=200;_onPathfindAbort;_onPathfindComplete;_onWaypointMoveComplete;_onWaypointMoveSkipped;_speed=0;_target;_verticalPenalty=0;_waypoints=[];_waypointNextIndex=0;_waypointStoppingDistance;_waypointTimeoutMs=2000;constructor(J={}){super(J)}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(J,$,X){if(this._target=J,this._speed=$,this._debug=X?.debug??!1,this._maxFall=X?.maxFall?-Math.abs(X.maxFall):0,this._maxJump=X?.maxJump?Math.abs(X.maxJump):0,this._maxOpenSetIterations=X?.maxOpenSetIterations??200,this._onPathfindAbort=X?.pathfindAbortCallback,this._onPathfindComplete=X?.pathfindCompleteCallback,this._onWaypointMoveComplete=X?.waypointMoveCompleteCallback,this._onWaypointMoveSkipped=X?.waypointMoveSkippedCallback,this._verticalPenalty=X?.verticalPenalty??0,this._waypoints=[],this._waypointNextIndex=0,this._waypointStoppingDistance=X?.waypointStoppingDistance,this._waypointTimeoutMs=X?.waypointTimeoutMs??2000/$,!this._calculatePath())return!1;return this._moveToNextWaypoint(),!0}attach(J){super.attach(J),this._entity=J}detach(J){super.detach(J),this._entity=void 0}_calculatePath(){if(!this._target||!this._entity?.world)return n.error("PathfindingEntityController._calculatePath: No target or world"),!1;let J=this._entity.height,$=this._findGroundedStart();if(!$){if(this._debug)n.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-$.x),Q=Math.abs(X.y-$.y),W=Math.abs(X.z-$.z);if(Y<=2&&Q<=2&&W<=2&&!this._isNeighborCoordinateBlocked($,X,this._entity.height))return this._waypoints=[{x:$.x+0.5,y:$.y+J/2,z:$.z+0.5},{x:X.x+0.5,y:X.y+J/2,z:X.z+0.5}],!0;if($.x===X.x&&$.y===X.y&&$.z===X.z)return this._waypoints=[{x:$.x+0.5,y:$.y+J/2,z:$.z+0.5}],!0;let Z=this._coordinateToKey($),G=new Map,V=new Map([[Z,0]]),q=new Map([[Z,this._pathfindingHeuristic($,X)]]),z=new Set,H=new dR1.Heap((M,R)=>{let N=q.get(M[0])??1/0,L=q.get(R[0])??1/0;return N-L});H.push([Z,$]);let v=[{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}],F=[];for(let M=this._maxJump;M>=this._maxFall;M--){if(M===0)continue;let R=Math.abs($.y+M-X.y);F.push({y:M,distanceToTargetY:R})}F.sort((M,R)=>M.distanceToTargetY-R.distanceToTargetY);let U=[...v,...F.flatMap(({y:M})=>v.map((R)=>({...R,y:M})))],j=0,B=Math.abs(X.x-$.x)+Math.abs(X.y-$.y)+Math.abs(X.z-$.z),w=Math.min(this._maxOpenSetIterations,B*20);while(!H.isEmpty()&&j<w){j++;let[M,R]=H.pop();if(R.x===X.x&&R.y===X.y&&R.z===X.z){let O=this._reconstructPath(G,R);if(this._waypoints=O.map((x)=>({x:x.x+0.5,y:x.y+J/2,z:x.z+0.5})),this._debug)console.log(`PathfindingEntityController._calculatePath: Path found after ${j} open set iterations. Start: ${this._coordinateToKey($)}, Target: ${this._coordinateToKey(this._target)}`);return!0}z.add(M);let N=V.get(M),L=new Map;for(let O of U){let x=`${O.x},${O.z}`,T=O.y<0;if(T&&L.has(x))continue;let S={x:R.x+O.x,y:R.y+O.y,z:R.z+O.z};if(Math.abs(X.x-S.x)+Math.abs(X.y-S.y)+Math.abs(X.z-S.z)>B*1.5)continue;let I=this._coordinateToKey(S);if(z.has(I))continue;let k=this._isNeighborCoordinateBlocked(R,S,this._entity.height);if(T&&k){L.set(x,!0);continue}if(k)continue;let E=Math.abs(O.x),c=Math.abs(O.y),A=Math.abs(O.z),h=c===0?0:this._verticalPenalty,_=(Math.max(E,c,A)===1&&E+c+A>1?1.4:1)+h,m=N+_,p=V.get(I)??1/0;if(m>=p)continue;G.set(I,R),V.set(I,m);let g=m+this._pathfindingHeuristic(S,X);q.set(I,g),H.push([I,S])}}if(j>=w){if(this._onPathfindAbort?.(),this._debug)n.warning(`PathfindingEntityController._calculatePath: Maximum open set iterations reached (${w}), path search aborted. Start: ${this._coordinateToKey($)}, Target: ${this._coordinateToKey(this._target)}`)}else if(this._debug)n.warning(`PathfindingEntityController._calculatePath: No valid path found. Start: ${this._coordinateToKey($)}, Target: ${this._coordinateToKey(this._target)}`);return this._target=void 0,this._waypoints=[],!1}_reconstructPath(J,$){let X=[$],Y=$;while(J.has(this._coordinateToKey(Y)))Y=J.get(this._coordinateToKey(Y)),X.unshift(Y);return X}_coordinateToKey(J){return`${J.x},${J.y},${J.z}`}_moveToNextWaypoint(){let J=this._waypointNextIndex>0?this._waypoints[this._waypointNextIndex-1]:void 0,$=this._waypoints[this._waypointNextIndex];if(!$||!this._entity)return;let X=0;if(this._entity.isDynamic&&J&&$.y>J.y){let Y=$.y-J.y,Q=Math.min(Y,this._maxJump)+0.75;this.jump(Q);let W=Math.abs(this._entity.world.simulation.gravity.y),K=Math.sqrt(2*W*Q),Z=J.x+0.5,G=J.z+0.5,V=$.x+0.5,q=$.z+0.5,z=V-Z,H=q-G,v=Math.sqrt(z*z+H*H),F=K/W,U=v/this._speed;X=Math.min(F*0.8,U)*1000}setTimeout(()=>{if(!this._entity)return;let Y=Date.now();this.face($,this._speed),this.move($,this._speed,{moveCompletesWhenStuck:!0,moveIgnoreAxes:{y:this._entity.isDynamic},moveStartIdleAnimationsOnCompletion:this._waypointNextIndex===this._waypoints.length-1,moveStoppingDistance:this._waypointStoppingDistance,moveCallback:()=>{if(Date.now()-Y>this._waypointTimeoutMs&&this._waypointNextIndex<this._waypoints.length-1)this._onWaypointMoveSkipped?.($,this._waypointNextIndex),this._waypointNextIndex++,this._moveToNextWaypoint()},moveCompleteCallback:()=>{if(this._waypointNextIndex<this._waypoints.length-1)this._onWaypointMoveComplete?.($,this._waypointNextIndex),this._waypointNextIndex++,this._moveToNextWaypoint();else this._onPathfindComplete?.()}})},X)}_pathfindingHeuristic(J,$){return Math.abs(J.x-$.x)+Math.abs(J.y-$.y)+Math.abs(J.z-$.z)}_isNeighborCoordinateBlocked(J,$,X){if(!this._entity?.world)return!1;let Y=this._entity.world,Q=Math.floor($.x),W=Math.floor($.y),K=Math.floor($.z),Z=Math.floor(J.x),G=Math.floor(J.z);if(!Y.chunkLattice.hasBlock({x:Q,y:W-1,z:K}))return!0;for(let V=0;V<X;V++)if(Y.chunkLattice.hasBlock({x:Q,y:W+V,z:K}))return!0;if(Q!==Z&&K!==G)for(let V=0;V<X;V++){let q=Y.chunkLattice.hasBlock({x:Q,y:W+V,z:G}),z=Y.chunkLattice.hasBlock({x:Z,y:W+V,z:K});if(q||z)return!0}return!1}_findGroundedStart(){if(!this._entity?.world)return;let{x:J,y:$,z:X}=this._entity.position,Y={x:Math.floor(J),y:Math.floor($),z:Math.floor(X)};for(let Q=0;Q<=Math.abs(this._maxFall);Q++)if(this._entity.world.chunkLattice.hasBlock({...Y,y:Y.y-Q-1}))return{...Y,y:Y.y-Q};return}}export{bC6 as startServer,$O1 as WorldManagerEvent,bK as WorldManager,JO1 as WorldLoopEvent,WB as WorldLoop,$n as WorldEvent,KB as World,ai as WebServerEvent,Qz as WebServer,Kz as Vector3,GB as Vector2,QB as Ticker,B3 as TelemetrySpanOperation,T6 as Telemetry,Jn as SimulationEvent,$B as Simulation,VB as SimpleEntityController,YB as SceneUIManager,hh as SceneUIEvent,wU as SceneUI,x78 as SUPPORTED_INPUTS,kF as RigidBodyType,FW as RigidBody,Wz as Quaternion,cO as PlayerUIEvent,zU as PlayerUI,XO1 as PlayerManagerEvent,F$ as PlayerManager,vU as PlayerEvent,o$ as PlayerEntity,Bq0 as PlayerCameraMode,Sh as PlayerCameraEvent,HU as PlayerCamera,kq as Player,CW as PersistenceManager,qn as PathfindingEntityController,XB as ParticleEmitterManager,ri as ParticleEmitterEvent,ti as ParticleEmitter,Oq0 as PLAYER_ROTATION_UPDATE_THRESHOLD,Nq0 as PLAYER_POSITION_UPDATE_THRESHOLD_SQ,k5 as ModelRegistry,u4 as Matrix4,xX as Matrix3,N3 as Matrix2,eN1 as LightType,JB as LightManager,si as LightEvent,oi as Light,w5 as IterationMap,YO1 as GameServerEvent,yK as GameServer,$1 as EventRouter,n as ErrorHandler,LU as EntityManager,BU as EntityEvent,b6 as Entity,Mq0 as ENTITY_ROTATION_UPDATE_THRESHOLD,Lq0 as ENTITY_POSITION_UPDATE_THRESHOLD_SQ,m8 as DefaultPlayerEntityController,fh as DefaultPlayerEntity,wq0 as DEFAULT_ENTITY_RIGID_BODY_OPTIONS,cJ as CollisionGroupsBuilder,OZ as CollisionGroup,Gq as ColliderShape,jU as ColliderMap,S9 as Collider,Cc as CoefficientCombineRule,_h as ChunkLatticeEvent,UU as ChunkLattice,X9 as Chunk,FU as ChatManager,Ah as ChatEvent,kc as BlockTypeRegistryEvent,EF as BlockTypeRegistry,Tc as BlockTypeEvent,A9 as BlockType,eQ as BlockTextureRegistry,R3 as Block,Nn as BaseEntityControllerEvent,iK as BaseEntityController,vz as AudioManager,rC as AudioEvent,zz as Audio,dK as AssetsLibrary};