hytopia 0.10.16 → 0.10.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/server.mjs CHANGED
@@ -402,7 +402,7 @@ globstar while`,Z,H,J,V,q),this.matchOne(Z.slice(H),J.slice(V),X))return this.de
402
402
  characterSettings { skinTone hairColor eyeColor hairStyle }
403
403
  equippedItems { slot item { slots { flags type modelUrl textureUrl } } }
404
404
  }
405
- }`});try{let $=(await J.next()).value?.data?.userById;if(!$)return p.warning(`PlatformGateway.getPlayerCosmetics(): No cosmetic data returned for user id "${Z}".`);let Y=$.equippedItems.map((W)=>({slot:W.slot,item:W.item.slots.find((G)=>G.type===W.slot)})).filter((W)=>!!W.item),Q=Number($.characterSettings?.hairStyle?.split("_")[1]||1),K=`https://d3qkovarww0lj1.cloudfront.net/?skin_tone=${$.characterSettings?.skinTone||"SKIN_COLOR_1"}&clothing=${$.characterSettings?.clothing||"CLOTHING_1"}&hair_style=${$.characterSettings?.hairStyle||"HAIR_STYLE_1"}&hair_color=${$.characterSettings?.hairColor||"HAIR_COLOR_1"}&eye_color=${$.characterSettings?.eyeColor||"00FF00"}`;return{equippedItems:Y,hairStyle:Q,skinTextureUri:K}}finally{await J.return?.()}}async getPlayerSession(Z){if(!this._creativeGateway)return;return await this._creativeGateway.getSession(Z)}async setData(Z,J){if(J.error)return p.warning("PlatformGateway.setData(): Cannot set data with an error property.");if(!this._creativeGateway&&process.env.NODE_ENV==="production")return p.warning("PlatformGateway.setData(): You are running in production mode, but the Platform Gateway is not initialized! No data will be set.");return this._creativeGateway?await this._creativeGateway.kv.set(Z,J):this._writeDevDataLocally(Z,J)}_readDevDataLocally(Z){try{if(!t$.existsSync(kz))return{error:{code:"keyNotFound",message:"Local data directory not found."}};let J=D80.join(kz,`${Z}.json`);return JSON.parse(t$.readFileSync(J,"utf8"))}catch(J){return p.warning(`PlatformGateway._readDevDataLocally(): Failed to read data for key "${Z}": ${J}`),{error:{code:"gatewayError",message:"Failed to read data for key."}}}}_writeDevDataLocally(Z,J){try{if(!t$.existsSync(kz))t$.mkdirSync(kz,{recursive:!0});let X=D80.join(kz,`${Z}.json`),$={};if(t$.existsSync(X))$=JSON.parse(t$.readFileSync(X,"utf8"));let Y={...$,...J};t$.writeFileSync(X,JSON.stringify(Y,null,2),"utf8")}catch(X){p.warning(`PlatformGateway._writeDevDataLocally(): Failed to write data for key "${Z}": ${X}`)}}}class e${static instance=new e$;constructor(){}async getGlobalData(Z,J=3){for(let X=0;X<=J;X++){let $=await O4.instance.getData(Z);if($&&!$.error)return $;if(X<J)await new Promise((Y)=>setTimeout(Y,500))}p.warning(`PersistenceManager.getGlobalData(): Failed to get global data after ${J} attempts.`);return}async getPlayerData(Z,J=3){for(let X=0;X<=J;X++){let $=await O4.instance.getData(this._getPlayerKey(Z));if($&&!$.error)return $;if(X<J)await new Promise((Y)=>setTimeout(Y,500))}p.warning(`PersistenceManager.getPlayerData(): Failed to get player data after ${J} attempts.`);return}async setGlobalData(Z,J){let X=await O4.instance.setData(Z,J);if(!X||X.error){if(X?.error)p.warning(`PersistenceManager.setGlobalData(): ${X.error.message}`);return}return X}async setPlayerData(Z,J){let X=await O4.instance.setData(this._getPlayerKey(Z),J);if(!X||X.error){if(X?.error)p.warning(`PersistenceManager.setPlayerData(): ${X.error.message}`);return}return X}_getPlayerKey(Z){return`player-${Z.id}`}}var R80;(($)=>{$[$.FIRST_PERSON=0]="FIRST_PERSON";$[$.THIRD_PERSON=1]="THIRD_PERSON";$[$.SPECTATOR=2]="SPECTATOR"})(R80||={});var uP;((x)=>{x.LOOK_AT_ENTITY="PLAYER_CAMERA.LOOK_AT_ENTITY";x.LOOK_AT_POSITION="PLAYER_CAMERA.LOOK_AT_POSITION";x.SET_ATTACHED_TO_ENTITY="PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY";x.SET_ATTACHED_TO_POSITION="PLAYER_CAMERA.SET_ATTACHED_TO_POSITION";x.SET_FILM_OFFSET="PLAYER_CAMERA.SET_FILM_OFFSET";x.SET_FORWARD_OFFSET="PLAYER_CAMERA.SET_FORWARD_OFFSET";x.SET_FOV="PLAYER_CAMERA.SET_FOV";x.SET_MODEL_HIDDEN_NODES="PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES";x.SET_MODEL_SHOWN_NODES="PLAYER_CAMERA.SET_MODEL_SHOWN_NODES";x.SET_MODE="PLAYER_CAMERA.SET_MODE";x.SET_OFFSET="PLAYER_CAMERA.SET_OFFSET";x.SET_SHOULDER_ANGLE="PLAYER_CAMERA.SET_SHOULDER_ANGLE";x.SET_TRACKED_ENTITY="PLAYER_CAMERA.SET_TRACKED_ENTITY";x.SET_TRACKED_POSITION="PLAYER_CAMERA.SET_TRACKED_POSITION";x.SET_ZOOM="PLAYER_CAMERA.SET_ZOOM"})(uP||={});class Ez extends B0{player;_attachedToEntity;_attachedToPosition;_filmOffset=0;_forwardOffset=0;_fov=75;_modelHiddenNodes=new Set;_modelShownNodes=new Set;_mode=1;_offset={x:0,y:0,z:0};_orientation={pitch:0,yaw:0};_shoulderAngle=0;_trackedEntity;_trackedPosition;_zoom=1;constructor(Z){super();this.player=Z}get attachedToEntity(){return this._attachedToEntity}get attachedToPosition(){return this._attachedToPosition}get facingDirection(){return{x:-Math.sin(this._orientation.yaw)*Math.cos(this._orientation.pitch),y:Math.sin(this._orientation.pitch),z:-Math.cos(this._orientation.yaw)*Math.cos(this._orientation.pitch)}}get facingQuaternion(){let Z=this._orientation.pitch*0.5,J=this._orientation.yaw*0.5,X=Math.cos(Z),$=Math.sin(Z),Y=Math.cos(J),Q=Math.sin(J);return{x:$*Y,y:X*Q,z:-$*Q,w:X*Y}}get filmOffset(){return this._filmOffset}get forwardOffset(){return this._forwardOffset}get fov(){return this._fov}get modelHiddenNodes(){return this._modelHiddenNodes}get modelShownNodes(){return this._modelShownNodes}get mode(){return this._mode}get offset(){return this._offset}get orientation(){return this._orientation}get shoulderAngle(){return this._shoulderAngle}get trackedEntity(){return this._trackedEntity}get trackedPosition(){return this._trackedPosition}get zoom(){return this._zoom}lookAtEntity(Z){if(!this._requirePlayerWorld("lookAtEntity"))return;this.emitWithWorld(this.player.world,"PLAYER_CAMERA.LOOK_AT_ENTITY",{playerCamera:this,entity:Z})}lookAtPosition(Z){if(!this._requirePlayerWorld("lookAtPosition"))return;this.emitWithWorld(this.player.world,"PLAYER_CAMERA.LOOK_AT_POSITION",{playerCamera:this,position:Z})}reset(){this._attachedToEntity=void 0,this._attachedToPosition=void 0,this._orientation={pitch:0,yaw:0},this._trackedEntity=void 0,this._trackedPosition=void 0}setAttachedToEntity(Z){if(!this._requirePlayerWorld("setAttachedToEntity"))return;if(!Z.isSpawned)return p.error(`PlayerCamera.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);this._attachedToEntity=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY",{playerCamera:this,entity:Z})}setAttachedToPosition(Z){if(!this._requirePlayerWorld("setAttachedToPosition"))return;this._attachedToPosition=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_ATTACHED_TO_POSITION",{playerCamera:this,position:Z})}setFilmOffset(Z){if(!this._requirePlayerWorld("setFilmOffset"))return;this._filmOffset=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_FILM_OFFSET",{playerCamera:this,filmOffset:Z})}setForwardOffset(Z){if(!this._requirePlayerWorld("setForwardOffset"))return;this._forwardOffset=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_FORWARD_OFFSET",{playerCamera:this,forwardOffset:Z})}setFov(Z){if(!this._requirePlayerWorld("setFov"))return;this._fov=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_FOV",{playerCamera:this,fov:Z})}setModelHiddenNodes(Z){if(!this._requirePlayerWorld("setModelHiddenNodes"))return;this._modelHiddenNodes=new Set(Z.map((J)=>J.toLowerCase())),this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES",{playerCamera:this,modelHiddenNodes:this._modelHiddenNodes})}setModelShownNodes(Z){if(!this._requirePlayerWorld("setModelShownNodes"))return;this._modelShownNodes=new Set(Z.map((J)=>J.toLowerCase())),this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_MODEL_SHOWN_NODES",{playerCamera:this,modelShownNodes:this._modelShownNodes})}setMode(Z){if(!this._requirePlayerWorld("setMode"))return;this._mode=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_MODE",{playerCamera:this,mode:Z})}setOffset(Z){if(!this._requirePlayerWorld("setOffset"))return;this._offset=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_OFFSET",{playerCamera:this,offset:Z})}setOrientationPitch(Z){this._orientation.pitch=Z}setOrientationYaw(Z){this._orientation.yaw=Z}setShoulderAngle(Z){if(!this._requirePlayerWorld("setShoulderAngle"))return;this._shoulderAngle=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_SHOULDER_ANGLE",{playerCamera:this,shoulderAngle:Z})}setTrackedEntity(Z){if(!this._requirePlayerWorld("setTrackedEntity"))return;this._trackedEntity=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_TRACKED_ENTITY",{playerCamera:this,entity:Z})}setTrackedPosition(Z){if(!this._requirePlayerWorld("setTrackedPosition"))return;this._trackedPosition=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_TRACKED_POSITION",{playerCamera:this,position:Z})}setZoom(Z){if(!this._requirePlayerWorld("setZoom"))return;this._zoom=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_ZOOM",{playerCamera:this,zoom:Z})}serialize(){return T0.serializePlayerCamera(this)}_requirePlayerWorld(Z){if(!this.player.world)p.error(`PlayerCamera._requirePlayerWorld(): Player ${this.player.id} is not in a world, invoked method: ${Z}()`);return!!this.player.world}}var gc;((Y)=>{Y.DATA="PLAYER_UI.DATA";Y.LOAD="PLAYER_UI.LOAD";Y.LOCK_POINTER="PLAYER_UI.LOCK_POINTER";Y.SEND_DATA="PLAYER_UI.SEND_DATA"})(gc||={});class Iz extends B0{player;constructor(Z){super();this.player=Z}load(Z){if(!this.player.world)return;this.emitWithWorld(this.player.world,"PLAYER_UI.LOAD",{playerUI:this,htmlUri:Z})}lockPointer(Z){if(!this.player.world)return;this.emitWithWorld(this.player.world,"PLAYER_UI.LOCK_POINTER",{playerUI:this,lock:Z})}sendData(Z){if(!this.player.world)return;this.emitWithWorld(this.player.world,"PLAYER_UI.SEND_DATA",{playerUI:this,data:Z})}}var N80=["w","a","s","d","sp","sh","tb","ml","mr","q","e","r","f","z","x","c","v","u","i","o","j","k","l","n","m","1","2","3","4","5","6","7","8","9","0"],_z;((Q)=>{Q.CHAT_MESSAGE_SEND="PLAYER.CHAT_MESSAGE_SEND";Q.JOINED_WORLD="PLAYER.JOINED_WORLD";Q.LEFT_WORLD="PLAYER.LEFT_WORLD";Q.RECONNECTED_WORLD="PLAYER.RECONNECTED_WORLD";Q.REQUEST_SYNC="PLAYER.REQUEST_SYNC"})(_z||={});class g3 extends B0{static _devNextPlayerId=1;id;username;profilePictureUrl;camera;connection;cosmetics;ui;_input={};_lastUnreliableInputSequenceNumber=0;_persistedData;_world;_worldSwitched=!1;constructor(Z,J){super();this.id=J?.user.id??`player-${g3._devNextPlayerId++}`,this.username=J?.user.username??this.id,this.profilePictureUrl=J?.user.profilePictureURL??void 0,this.camera=new Ez(this),this.connection=Z,this.cosmetics=O4.instance.getPlayerCosmetics(this.id),this.ui=new Iz(this),Z.onPacket(Y0.PacketId.CHAT_MESSAGE_SEND,this._onChatMessageSendPacket),Z.onPacket(Y0.PacketId.DEBUG_CONFIG,this._onDebugConfigPacket),Z.onPacket(Y0.PacketId.INPUT,this._onInputPacket),Z.onPacket(Y0.PacketId.SYNC_REQUEST,this._onSyncRequestPacket),Z.onPacket(Y0.PacketId.UI_DATA_SEND,this._onUIDataSendPacket)}get input(){return this._input}get world(){return this._world}disconnect(){this._leaveWorld(),this.connection.disconnect()}getPersistedData(){return this._persistedData}joinWorld(Z){if(this._world===Z)return;if(!this._world)this._world=Z,this.emitWithWorld(this._world,"PLAYER.JOINED_WORLD",{player:this,world:this._world});else{for(let J of this._world.entityManager.getPlayerEntitiesByPlayer(this))if(J.isSpawned)J.despawn();this.disconnect(),this._world=Z,this._worldSwitched=!0}}async loadInitialPersistedData(){if(this._persistedData)return;this._persistedData=await e$.instance.getPlayerData(this)}reconnected(){if(!this._world)return;if(this._lastUnreliableInputSequenceNumber=0,!this._worldSwitched)this.emitWithWorld(this._world,"PLAYER.RECONNECTED_WORLD",{player:this,world:this._world});else this._worldSwitched=!1,this.emitWithWorld(this._world,"PLAYER.JOINED_WORLD",{player:this,world:this._world})}resetInputs(){this._input={}}setPersistedData(Z){return this._persistedData={...this._persistedData,...Z},e$.instance.setPlayerData(this,Z).catch((J)=>{}),this._persistedData}serialize(){return T0.serializePlayer(this)}_leaveWorld(){if(!this._world)return;this.emitWithWorld(this._world,"PLAYER.LEFT_WORLD",{player:this,world:this._world}),this._world=void 0}_onChatMessageSendPacket=(Z)=>{if(!this._world)return;let J=Z[1].m;if(this._world.chatManager.handleCommand(this,J)){this._world.chatManager.sendPlayerMessage(this,`Command Entered: ${J}`,"CCCCCC");return}if(this.id.startsWith("guest")){this._world.chatManager.sendPlayerMessage(this,"You need to create a HYTOPIA account to send messages in chat.","FFAA00");return}this.emitWithWorld(this._world,"PLAYER.CHAT_MESSAGE_SEND",{player:this,message:J})};_onDebugConfigPacket=(Z)=>{console.log(Z)};_onInputPacket=(Z)=>{let J=Z[1];if(J.sq!==void 0){if(J.sq<this._lastUnreliableInputSequenceNumber)return;this._lastUnreliableInputSequenceNumber=J.sq}if(N80.forEach((X)=>{let $=X;if(J[$]!==void 0)this._input[$]=Boolean(J[$])}),J.cp!==void 0)this.camera.setOrientationPitch(J.cp);if(J.cy!==void 0)this.camera.setOrientationYaw(J.cy)};_onSyncRequestPacket=()=>{if(this._world)this.emitWithWorld(this._world,"PLAYER.REQUEST_SYNC",{player:this,receivedAt:Date.now(),receivedAtMs:performance.now()})};_onUIDataSendPacket=(Z)=>{this.ui.emit("PLAYER_UI.DATA",{playerUI:this.ui,data:Z[1]})}}var lP;((X)=>{X.BROADCAST_MESSAGE="CHAT.BROADCAST_MESSAGE";X.PLAYER_MESSAGE="CHAT.PLAYER_MESSAGE"})(lP||={});class bz extends B0{_commandCallbacks={};_world;constructor(Z){super();this._world=Z,this._subscribeToPlayerEvents()}registerCommand(Z,J){this._commandCallbacks[Z]=J}unregisterCommand(Z){delete this._commandCallbacks[Z]}sendBroadcastMessage(Z,J){this._sendBroadcastMessage(void 0,Z,J)}handleCommand(Z,J){let[X,...$]=J.split(" "),Y=this._commandCallbacks[X];if(Y)return Y(Z,$,J),!0;return!1}sendPlayerMessage(Z,J,X){this.emitWithWorld(this._world,"CHAT.PLAYER_MESSAGE",{player:Z,message:J,color:X})}_subscribeToPlayerEvents(){this._world.on("PLAYER.CHAT_MESSAGE_SEND",(Z)=>{let{player:J,message:X}=Z;this._sendBroadcastMessage(J,X)})}_sendBroadcastMessage(Z,J,X){this.emitWithWorld(this._world,"CHAT.BROADCAST_MESSAGE",{player:Z,message:J,color:X})}}var y5=16,yP=y5-1,dI1=y5**3;class p5{_blocks;_originCoordinate;constructor(Z){this._blocks=new Uint8Array(dI1),this._originCoordinate=Z}get blocks(){return this._blocks}get originCoordinate(){return this._originCoordinate}static blockIndexToLocalCoordinate(Z){return{x:Z%y5,y:(Z/y5|0)%y5,z:Z/(y5*y5)|0}}static globalCoordinateToLocalCoordinate(Z){return{x:Z.x&y5-1,y:Z.y&y5-1,z:Z.z&y5-1}}static globalCoordinateToOriginCoordinate(Z){return{x:Z.x&~(y5-1),y:Z.y&~(y5-1),z:Z.z&~(y5-1)}}getBlockId(Z){return this._blocks[this._getIndex(Z)]}hasBlock(Z){return this._blocks[this._getIndex(Z)]!==0}setBlock(Z,J){if(!this._isValidLocalCoordinate(Z))return p.error("Chunk.setBlock(): Block local coordinate is out of bounds");let X=this._getIndex(Z);this._blocks[X]=J}serialize(){return T0.serializeChunk(this)}_getIndex(Z){return Z.x+(Z.y<<4)+(Z.z<<8)}_isValidLocalCoordinate(Z){return Z.x>=0&&Z.x<=yP&&Z.y>=0&&Z.y<=yP&&Z.z>=0&&Z.z<=yP}}var pP;(($)=>{$.ADD_CHUNK="CHUNK_LATTICE.ADD_CHUNK";$.REMOVE_CHUNK="CHUNK_LATTICE.REMOVE_CHUNK";$.SET_BLOCK="CHUNK_LATTICE.SET_BLOCK"})(pP||={});class hz extends B0{_blockTypeColliders=new Map;_blockTypeCounts=new Map;_chunks=new Map;_rigidBody;_world;constructor(Z){super();this._world=Z}get chunkCount(){return this._chunks.size}clear(){for(let Z of this._blockTypeColliders.values())this._world.simulation.colliderMap.removeColliderBlockType(Z),Z.removeFromSimulation();this._chunks.forEach((Z)=>{this.emitWithWorld(this._world,"CHUNK_LATTICE.REMOVE_CHUNK",{chunkLattice:this,chunk:Z})}),this._blockTypeColliders.clear(),this._blockTypeCounts.clear(),this._chunks.clear()}getBlockId(Z){let J=this.getChunk(p5.globalCoordinateToOriginCoordinate(Z));if(!J)return 0;return J.getBlockId(p5.globalCoordinateToLocalCoordinate(Z))}getBlockTypeCollider(Z){return this._blockTypeColliders.get(Z)}getBlockType(Z){let J=this.getBlockId(Z);return J?this._world.blockTypeRegistry.getBlockType(J):null}getBlockTypeCount(Z){return this._blockTypeCounts.get(Z)??0}getChunk(Z){return this._chunks.get(this._getChunkKey(p5.globalCoordinateToOriginCoordinate(Z)))}getOrCreateBlockTypeCollider(Z,J){let X=this._blockTypeColliders.get(Z);if(X)return X;let Y=this._world.blockTypeRegistry.getBlockType(Z).createCollider(J);return this._blockTypeColliders.set(Z,Y),Y}getOrCreateChunk(Z){let J=p5.globalCoordinateToOriginCoordinate(Z),X=this._chunks.get(this._getChunkKey(J));if(X)return X;return X=new p5(J),this._chunks.set(this._getChunkKey(J),X),this.emitWithWorld(this._world,"CHUNK_LATTICE.ADD_CHUNK",{chunkLattice:this,chunk:X}),X}getAllChunks(){return Array.from(this._chunks.values())}hasBlock(Z){let J=this.getChunk(p5.globalCoordinateToOriginCoordinate(Z));if(!J)return!1;return J.hasBlock(p5.globalCoordinateToLocalCoordinate(Z))}hasChunk(Z){let J=p5.globalCoordinateToOriginCoordinate(Z);return this._chunks.has(this._getChunkKey(J))}setBlock(Z,J){let X=p5.globalCoordinateToLocalCoordinate(Z),$=this.getOrCreateChunk(Z),Y=$.getBlockId(X);if(Y===J)return;if($.setBlock(X,J),!this._rigidBody)this._rigidBody=new u$({type:"fixed"}),this._rigidBody.addToSimulation(this._world.simulation);if(Y!==0){let Q=Math.max(0,(this._blockTypeCounts.get(Y)??0)-1),K=this.getBlockTypeCollider(Y);if(K)if(Q===0)this._world.simulation.colliderMap.removeColliderBlockType(K),K.removeFromSimulation(),this._blockTypeColliders.delete(Y);else K.setVoxel(Z,!1),this._propagateVoxelChange(K,Z);this._blockTypeCounts.set(Y,Q)}if(J!==0){let Q=(this._blockTypeCounts.get(J)??0)+1,K=this.getOrCreateBlockTypeCollider(J,[Z]);if(Q===1){let W=this._world.blockTypeRegistry.getBlockType(J);K.addToSimulation(this._world.simulation,this._rigidBody),this._world.simulation.colliderMap.setColliderBlockType(K,W),this._combineVoxelStates(K)}else K.setVoxel(Z,!0),this._propagateVoxelChange(K,Z);this._blockTypeCounts.set(J,Q)}this.emitWithWorld(this._world,"CHUNK_LATTICE.SET_BLOCK",{chunkLattice:this,chunk:$,globalCoordinate:Z,localCoordinate:X,blockTypeId:J})}_combineVoxelStates(Z){if(Z.isSensor)return;for(let J of this._blockTypeColliders.values()){if(J===Z||J.isSensor)continue;Z.combineVoxelStates(J)}}_getChunkKey(Z){return`${Z.x},${Z.y},${Z.z}`}_propagateVoxelChange(Z,J){if(Z.isSensor)return;for(let X of this._blockTypeColliders.values()){if(X===Z||X.isSensor)continue;Z.propagateVoxelChange(X,J)}}}class Sz{_colliderHandleBlockTypeMap=new Map;_colliderHandleCollisionCallbackMap=new Map;_colliderHandleEntityMap=new Map;_cleanupBlockTypeColliderHandles=new Set;_pendingCleanupBlockTypeColliderHandles=new Set;_cleanupCollisionCallbackColliderHandles=new Set;_pendingCleanupCollisionCallbackColliderHandles=new Set;_cleanupEntityColliderHandles=new Set;_pendingCleanupEntityColliderHandles=new Set;getColliderBlockType(Z){if(!this._requireSimulatedCollider(Z))return;return this._colliderHandleBlockTypeMap.get(Z.rawCollider.handle)}getColliderCollisionCallback(Z){if(!this._requireSimulatedCollider(Z))return;return this._colliderHandleCollisionCallbackMap.get(Z.rawCollider.handle)}getColliderEntity(Z){if(!this._requireSimulatedCollider(Z))return;return this._colliderHandleEntityMap.get(Z.rawCollider.handle)}getColliderHandleBlockType(Z){return this._colliderHandleBlockTypeMap.get(Z)}getColliderHandleCollisionCallback(Z){return this._colliderHandleCollisionCallbackMap.get(Z)}getColliderHandleEntity(Z){return this._colliderHandleEntityMap.get(Z)}removeColliderBlockType(Z){if(!this._requireSimulatedCollider(Z))return;this.removeColliderHandleBlockType(Z.rawCollider.handle)}removeColliderCollisionCallback(Z){if(!this._requireSimulatedCollider(Z))return;this.removeColliderHandleCollisionCallback(Z.rawCollider.handle)}removeColliderEntity(Z){if(!this._requireSimulatedCollider(Z))return;this.removeColliderHandleEntity(Z.rawCollider.handle)}removeColliderHandleBlockType(Z){this._colliderHandleBlockTypeMap.delete(Z)}removeColliderHandleCollisionCallback(Z){this._colliderHandleCollisionCallbackMap.delete(Z)}removeColliderHandleEntity(Z){this._colliderHandleEntityMap.delete(Z)}setColliderBlockType(Z,J){if(!this._requireSimulatedCollider(Z))return;this.setColliderHandleBlockType(Z.rawCollider.handle,J)}setColliderCollisionCallback(Z,J){if(!this._requireSimulatedCollider(Z))return;this.setColliderHandleCollisionCallback(Z.rawCollider.handle,J)}setColliderEntity(Z,J){if(!this._requireSimulatedCollider(Z))return;this.setColliderHandleEntity(Z.rawCollider.handle,J)}setColliderHandleBlockType(Z,J){this._colliderHandleBlockTypeMap.set(Z,J),this._cleanupBlockTypeColliderHandles.delete(Z),this._pendingCleanupBlockTypeColliderHandles.delete(Z)}setColliderHandleCollisionCallback(Z,J){this._colliderHandleCollisionCallbackMap.set(Z,J),this._cleanupCollisionCallbackColliderHandles.delete(Z),this._pendingCleanupCollisionCallbackColliderHandles.delete(Z)}setColliderHandleEntity(Z,J){this._colliderHandleEntityMap.set(Z,J),this._cleanupEntityColliderHandles.delete(Z),this._pendingCleanupEntityColliderHandles.delete(Z)}queueColliderHandleForCleanup(Z){if(this._colliderHandleBlockTypeMap.has(Z))this._pendingCleanupBlockTypeColliderHandles.add(Z);if(this._colliderHandleCollisionCallbackMap.has(Z))this._pendingCleanupCollisionCallbackColliderHandles.add(Z);if(this._colliderHandleEntityMap.has(Z))this._pendingCleanupEntityColliderHandles.add(Z)}cleanup(){for(let Z of this._cleanupBlockTypeColliderHandles)this._colliderHandleBlockTypeMap.delete(Z);if(this._cleanupBlockTypeColliderHandles.size>0)this._cleanupBlockTypeColliderHandles.clear();for(let Z of this._cleanupCollisionCallbackColliderHandles)this._colliderHandleCollisionCallbackMap.delete(Z);if(this._cleanupCollisionCallbackColliderHandles.size>0)this._cleanupCollisionCallbackColliderHandles.clear();for(let Z of this._cleanupEntityColliderHandles)this._colliderHandleEntityMap.delete(Z);if(this._cleanupEntityColliderHandles.size>0)this._cleanupEntityColliderHandles.clear();for(let Z of this._pendingCleanupBlockTypeColliderHandles)this._cleanupBlockTypeColliderHandles.add(Z);if(this._pendingCleanupBlockTypeColliderHandles.size>0)this._pendingCleanupBlockTypeColliderHandles.clear();for(let Z of this._pendingCleanupCollisionCallbackColliderHandles)this._cleanupCollisionCallbackColliderHandles.add(Z);if(this._pendingCleanupCollisionCallbackColliderHandles.size>0)this._pendingCleanupCollisionCallbackColliderHandles.clear();for(let Z of this._pendingCleanupEntityColliderHandles)this._cleanupEntityColliderHandles.add(Z);if(this._pendingCleanupEntityColliderHandles.size>0)this._pendingCleanupEntityColliderHandles.clear()}_requireSimulatedCollider(Z){if(!Z.rawCollider)p.error("ColliderMap._requireSimulatedCollider(): Collider is not in the simulation.");return!!Z.rawCollider}}var O80={type:"dynamic",softCcdPrediction:1},P80=0.015625,T80=Math.cos(0.026),Az;((L)=>{L.BLOCK_COLLISION="ENTITY.BLOCK_COLLISION";L.BLOCK_CONTACT_FORCE="ENTITY.BLOCK_CONTACT_FORCE";L.DESPAWN="ENTITY.DESPAWN";L.ENTITY_COLLISION="ENTITY.ENTITY_COLLISION";L.ENTITY_CONTACT_FORCE="ENTITY.ENTITY_CONTACT_FORCE";L.SET_MODEL_ANIMATIONS_PLAYBACK_RATE="ENTITY.SET_MODEL_ANIMATIONS_PLAYBACK_RATE";L.SET_MODEL_HIDDEN_NODES="ENTITY.SET_MODEL_HIDDEN_NODES";L.SET_MODEL_SCALE="ENTITY.SET_MODEL_SCALE";L.SET_MODEL_SHOWN_NODES="ENTITY.SET_MODEL_SHOWN_NODES";L.SET_MODEL_TEXTURE_URI="ENTITY.SET_MODEL_TEXTURE_URI";L.SET_OPACITY="ENTITY.SET_OPACITY";L.SET_PARENT="ENTITY.SET_PARENT";L.SET_TINT_COLOR="ENTITY.SET_TINT_COLOR";L.SPAWN="ENTITY.SPAWN";L.START_MODEL_LOOPED_ANIMATIONS="ENTITY.START_MODEL_LOOPED_ANIMATIONS";L.START_MODEL_ONESHOT_ANIMATIONS="ENTITY.START_MODEL_ONESHOT_ANIMATIONS";L.STOP_MODEL_ANIMATIONS="ENTITY.STOP_MODEL_ANIMATIONS";L.TICK="ENTITY.TICK";L.UPDATE_POSITION="ENTITY.UPDATE_POSITION";L.UPDATE_ROTATION="ENTITY.UPDATE_ROTATION"})(Az||={});class j8 extends u${_id;_blockHalfExtents;_blockTextureUri;_controller;_isEnvironmental=!1;_modelAnimationsPlaybackRate=1;_modelHiddenNodes=new Set;_modelLoopedAnimations=new Set;_modelOneshotAnimations=new Set;_modelPreferredShape;_modelScale=1;_modelShownNodes=new Set;_modelTextureUri;_modelUri;_name;_opacity;_parent;_parentNodeName;_tag;_tintColor;_lastUpdatedPosition={x:0,y:0,z:0};_lastUpdatedRotation={x:0,y:0,z:0,w:1};_lastParentlessType="dynamic";_world;_positionUpdateThresholdSq;_rotationUpdateThreshold;constructor(Z){let J="blockTextureUri"in Z,X="modelUri"in Z;if(!J===!X)p.fatalError("Entity.constructor(): Entity data must include a blockTextureUri or modelUri, but not both.");if(J&&!Z.blockHalfExtents)p.fatalError("Entity.constructor(): Block entity must have blockHalfExtents!");if(Z.parent&&!Z.parent.isSpawned)p.fatalError("Entity.constructor(): Parent entity must be spawned before child entity!");if(Z.parent?.modelUri&&Z.parentNodeName&&!j6.instance.modelHasNode(Z.parent.modelUri,Z.parentNodeName))p.fatalError(`Entity.constructor(): Parent node name ${Z.parentNodeName} not found in parent model ${Z.parent.modelUri}!`);super(Z.rigidBodyOptions??O80);if(J)this._blockHalfExtents=Z.blockHalfExtents,this._blockTextureUri=Z.blockTextureUri;if(X)this._modelAnimationsPlaybackRate=Z.modelAnimationsPlaybackRate??1,this._modelPreferredShape=Z.modelPreferredShape,this._modelScale=Z.modelScale??1,this._modelTextureUri=Z.modelTextureUri,this._modelUri=Z.modelUri,Z.modelHiddenNodes?.forEach(($)=>this._modelHiddenNodes.add($.toLowerCase())),Z.modelLoopedAnimations?.forEach(($)=>this._modelLoopedAnimations.add($)),Z.modelShownNodes?.forEach(($)=>this._modelShownNodes.add($.toLowerCase()));if(this._isEnvironmental=Z.isEnvironmental??!1,this._name=Z.name??"Nameless",this._opacity=Z.opacity??1,this._parent=Z.parent,this._parentNodeName=Z.parentNodeName,this._tag=Z.tag,this._tintColor=Z.tintColor,this._positionUpdateThresholdSq=P80,this._rotationUpdateThreshold=T80,Z.controller)this.setController(Z.controller)}get id(){return this._id}get blockHalfExtents(){return this._blockHalfExtents}get blockTextureUri(){return this._blockTextureUri}get controller(){return this._controller}get depth(){return this.isModelEntity?j6.instance.getDepth(this._modelUri)*(this._modelScale??1):this._blockHalfExtents.z*2}get height(){return this.isModelEntity?j6.instance.getHeight(this._modelUri)*(this._modelScale??1):this._blockHalfExtents.y*2}get modelAnimationsPlaybackRate(){return this._modelAnimationsPlaybackRate}get modelHiddenNodes(){return this._modelHiddenNodes}get modelLoopedAnimations(){return this._modelLoopedAnimations}get modelPreferredShape(){return this._modelPreferredShape}get modelScale(){return this._modelScale}get modelShownNodes(){return this._modelShownNodes}get modelTextureUri(){return this._modelTextureUri}get modelUri(){return this._modelUri}get name(){return this._name}get opacity(){return this._opacity}get parent(){return this._parent}get parentNodeName(){return this._parentNodeName}get tag(){return this._tag}get tintColor(){return this._tintColor}get isBlockEntity(){return!!this._blockTextureUri}get isEnvironmental(){return this._isEnvironmental}get isModelEntity(){return!!this._modelUri}get isSpawned(){return!!this._world}get width(){return this.isModelEntity?j6.instance.getWidth(this._modelUri)*(this._modelScale??1):this._blockHalfExtents.x*2}get world(){return this._world}spawn(Z,J,X){if(this.isSpawned)return p.error(`Entity.spawn(): Entity ${this._name} is already spawned with id ${this._id}!`);if(!this.isSimulated)this.addToSimulation(Z.simulation);if(this._blockTextureUri&&this._blockHalfExtents&&this.numColliders===0)this.addChildColliderToSimulation(new S5(S5.optionsFromBlockHalfExtents(this._blockHalfExtents)));if(this._modelUri&&this.numColliders===0&&this._modelPreferredShape!=="none")this.addChildColliderToSimulation(new S5(S5.optionsFromModelUri(this._modelUri,this._modelScale,this._modelPreferredShape)));if(this.colliders.forEach(($)=>{if(this.hasListeners("ENTITY.BLOCK_COLLISION")||this.hasListeners("ENTITY.ENTITY_COLLISION"))$.enableCollisionEvents(!0);if(this.hasListeners("ENTITY.BLOCK_CONTACT_FORCE")||this.hasListeners("ENTITY.ENTITY_CONTACT_FORCE"))$.enableContactForceEvents(!0);if(v9.isDefaultCollisionGroups($.collisionGroups)){let Y=this.isEnvironmental?[8]:[$.isSensor?4:2],Q=this.isEnvironmental?[65535&~8&~1]:[65535];$.setCollisionGroups({belongsTo:Y,collidesWith:Q})}}),this.setPosition(J),X)this.setRotation(X);if(this._id=Z.entityManager.registerEntity(this),this._world=Z,this._controller)this._controller.spawn(this);if(this._parent)this.setParent(this._parent,this._parentNodeName,J,X);this.colliders.forEach(($)=>{Z.simulation.colliderMap.setColliderEntity($,this)}),this.emitWithWorld(Z,"ENTITY.SPAWN",{entity:this})}despawn(){if(!this._requireSpawned("despawn"))return;if(this._world.entityManager.getEntityChildren(this).forEach((Z)=>{Z.despawn()}),this._controller)this._controller.detach(this),this._controller.despawn(this);if(this.emitWithWorld(this._world,"ENTITY.DESPAWN",{entity:this}),this.isSimulated)this.removeFromSimulation();this._world.entityManager.unregisterEntity(this),this._world.audioManager.unregisterEntityAttachedAudios(this),this._world.lightManager.despawnEntityAttachedLights(this),this._world.particleEmitterManager.despawnEntityAttachedParticleEmitters(this),this._world.sceneUIManager.unloadEntityAttachedSceneUIs(this),this._id=void 0,this._world=void 0}setController(Z){if(this._controller===Z)return;if(this._controller)this._controller.detach(this);if(this._controller=Z,this._controller)this._controller.attach(this)}setModelAnimationsPlaybackRate(Z){if(!this._requireSpawned("setModelAnimationsPlaybackRate"))return;if(!this.isModelEntity||this._modelAnimationsPlaybackRate===Z)return;this._modelAnimationsPlaybackRate=Z,this.emitWithWorld(this._world,"ENTITY.SET_MODEL_ANIMATIONS_PLAYBACK_RATE",{entity:this,playbackRate:Z})}setModelHiddenNodes(Z){if(!this._requireSpawned("setModelHiddenNodes"))return;if(!this.isModelEntity)return;this._modelHiddenNodes=new Set(Z.map((J)=>J.toLowerCase())),this.emitWithWorld(this._world,"ENTITY.SET_MODEL_HIDDEN_NODES",{entity:this,modelHiddenNodes:this._modelHiddenNodes})}setModelScale(Z){if(!this._requireSpawned("setModelScale"))return;if(!this.isModelEntity||this._modelScale===Z)return;let J=Z/this._modelScale;this._modelScale=Z,this.colliders.forEach((X)=>X.scale(J)),this.emitWithWorld(this._world,"ENTITY.SET_MODEL_SCALE",{entity:this,modelScale:Z})}setModelShownNodes(Z){if(!this._requireSpawned("setModelShownNodes"))return;if(!this.isModelEntity)return;this._modelShownNodes=new Set(Z.map((J)=>J.toLowerCase())),this.emitWithWorld(this._world,"ENTITY.SET_MODEL_SHOWN_NODES",{entity:this,modelShownNodes:this._modelShownNodes})}setModelTextureUri(Z){if(!this._requireSpawned("setModelTextureUri"))return;if(!this.isModelEntity||this._modelTextureUri===Z)return;this._modelTextureUri=Z,this.emitWithWorld(this._world,"ENTITY.SET_MODEL_TEXTURE_URI",{entity:this,modelTextureUri:Z})}setOpacity(Z){if(!this._requireSpawned("setOpacity"))return;if(this._opacity===Z)return;this._opacity=Z,this.emitWithWorld(this._world,"ENTITY.SET_OPACITY",{entity:this,opacity:Z})}setParent(Z,J,X,$){if(!this._requireSpawned("setParent"))return;if(Z&&!Z.isSpawned)return p.error("Entity.setParent(): Parent entity is not spawned, cannot set parent!");if(!this._parent&&Z)this._lastParentlessType=this.type;if(this._parent=Z,this._parentNodeName=J,this.colliders.forEach((Y)=>Y.setEnabled(!Z)),this.setType(!Z?this._lastParentlessType:"kinematic_velocity"),this.setPosition(X??{x:0,y:0,z:0}),this.setRotation($??{x:0,y:0,z:0,w:1}),!this.isKinematicPositionBased)this.resetAngularVelocity(),this.resetForces(),this.resetLinearVelocity(),this.resetTorques();this.emitWithWorld(this._world,"ENTITY.SET_PARENT",{entity:this,parent:Z,parentNodeName:J})}setTintColor(Z){if(!this._requireSpawned("setTintColor"))return;if(!Z&&!this._tintColor||Z&&this._tintColor&&Z.r===this._tintColor.r&&Z.g===this._tintColor.g&&Z.b===this._tintColor.b)return;this._tintColor=Z,this.emitWithWorld(this._world,"ENTITY.SET_TINT_COLOR",{entity:this,tintColor:Z})}startModelLoopedAnimations(Z){if(!this._requireSpawned("startModelLoopedAnimations"))return;if(!this.isModelEntity||!Z.length)return;if(!Z.some((J)=>!this._modelLoopedAnimations.has(J)))return;Z.forEach((J)=>{this._modelLoopedAnimations.add(J)}),this.emitWithWorld(this._world,"ENTITY.START_MODEL_LOOPED_ANIMATIONS",{entity:this,animations:new Set(Z)})}startModelOneshotAnimations(Z){if(!this._requireSpawned("startModelOneshotAnimations"))return;if(!this.isModelEntity||!Z.length)return;Z.forEach((J)=>{this._modelOneshotAnimations.add(J)}),this.emitWithWorld(this._world,"ENTITY.START_MODEL_ONESHOT_ANIMATIONS",{entity:this,animations:new Set(Z)})}stopAllModelAnimations(Z=[]){if(!this._requireSpawned("stopAllModelAnimations"))return;this._stopAnimationsFromSets([this._modelLoopedAnimations,this._modelOneshotAnimations],Z)}stopAllModelLoopedAnimations(Z=[]){if(!this._requireSpawned("stopAllModelLoopedAnimations"))return;this._stopAnimationsFromSets([this._modelLoopedAnimations],Z)}stopAllModelOneshotAnimations(Z=[]){if(!this._requireSpawned("stopAllModelOneshotAnimations"))return;this._stopAnimationsFromSets([this._modelOneshotAnimations],Z)}stopModelAnimations(Z){if(!this._requireSpawned("stopModelAnimations"))return;if(!this.isModelEntity||!Z.length)return;if(!Z.some((J)=>this._modelLoopedAnimations.has(J))&&!Z.some((J)=>this._modelOneshotAnimations.has(J)))return;Z.forEach((J)=>{this._modelLoopedAnimations.delete(J),this._modelOneshotAnimations.delete(J)}),this.emitWithWorld(this._world,"ENTITY.STOP_MODEL_ANIMATIONS",{entity:this,animations:new Set(Z)})}serialize(){return T0.serializeEntity(this)}tick(Z){if(this.emit("ENTITY.TICK",{entity:this,tickDeltaMs:Z}),this._controller)this._controller.tick(this,Z)}checkAndEmitUpdates(){if(!this._requireSpawned("checkAndEmitUpdates"))return;let Z=this.position,J=this.rotation;if(this._rotationExceedsThreshold(J,this._lastUpdatedRotation))this._lastUpdatedRotation=J,this.emitWithWorld(this._world,"ENTITY.UPDATE_ROTATION",{entity:this,rotation:J});if(this._positionExceedsThreshold(Z,this._lastUpdatedPosition))this._lastUpdatedPosition=Z,this.emitWithWorld(this._world,"ENTITY.UPDATE_POSITION",{entity:this,position:Z})}_positionExceedsThreshold(Z,J){let X=Z.x-J.x,$=Z.y-J.y,Y=Z.z-J.z;return X*X+$*$+Y*Y>this._positionUpdateThresholdSq}_requireSpawned(Z){if(!this.isSpawned)p.error(`Entity._requireSpawned(): Entity ${this._name} is not spawned, cannot invoke ${Z}()!`);return this.isSpawned}_rotationExceedsThreshold(Z,J){return Math.abs(Z.x*J.x+Z.y*J.y+Z.z*J.z+Z.w*J.w)<this._rotationUpdateThreshold}_stopAnimationsFromSets(Z,J=[]){if(!this.isModelEntity)return;let X=new Set(J),$=[];for(let Y of Z)for(let Q of Y)if(!X.has(Q))$.push(Q);if($.length>0)this.stopModelAnimations($)}}class b1 extends x${static BASE_ENTITY_HEIGHT=1.5;static GROUND_SENSOR_HEIGHT_SCALE=0.125;static GROUND_SENSOR_RADIUS_SCALE=0.23;static JUMP_LAND_HEAVY_VELOCITY_THRESHOLD=-12;static WALL_COLLIDER_HEIGHT_SCALE=0.33;static WALL_COLLIDER_RADIUS_SCALE=0.4;static MOVEMENT_ROTATIONS={wa:Math.PI/4,wd:-Math.PI/4,sa:Math.PI-Math.PI/4,sd:Math.PI+Math.PI/4,s:Math.PI,asd:Math.PI,a:Math.PI/2,d:-Math.PI/2};static EXTERNAL_IMPULSE_DECAY_RATE=0.253;static SWIM_UPWARD_COOLDOWN_MS=600;static SWIMMING_DRAG_FACTOR=0.05;static WATER_ENTRY_SINKING_FACTOR=0.8;static WATER_ENTRY_SINKING_MS=250;applyDirectionalMovementRotations=!0;autoCancelMouseLeftClick=!0;canJump=()=>!0;canRun=()=>!0;canSwim=()=>!0;canWalk=()=>!0;faceForwardOnStop=!0;idleLoopedAnimations=["idle-upper","idle-lower"];interactOneshotAnimations=["simple-interact"];jumpLandHeavyOneshotAnimations=["jump-post-heavy"];jumpLandLightOneshotAnimations=["jump-post-light"];jumpOneshotAnimations=["jump-loop"];jumpVelocity=10;runLoopedAnimations=["run-upper","run-lower"];runVelocity=8;sticksToPlatforms=!0;swimFastVelocity=5;swimGravity=0;swimIdleLoopedAnimations=["swim-idle"];swimLoopedAnimations=["swim-forward"];swimMaxGravityVelocity=-1;swimSlowVelocity=3;swimUpwardVelocity=2;walkLoopedAnimations=["walk-upper","walk-lower"];walkVelocity=4;_externalVelocity={x:0,y:0,z:0};_magnitudeYTracker=0;_groundContactCount=0;_internalApplyImpulse=()=>{};_isActivelyMoving=!1;_isFullySubmerged=!1;_justSubmergedUntil=0;_liquidContactCount=0;_platform;_reusableImpulse={x:0,y:0,z:0};_reusablePlatformVelocity={x:0,y:0,z:0};_reusableTargetVelocities={x:0,y:0,z:0};_reusableVelocityClamp={x:0,y:0,z:0};_stepAudio;_swimUpwardCooldownAt=0;constructor(Z={}){super();this.applyDirectionalMovementRotations=Z.applyDirectionalMovementRotations??this.applyDirectionalMovementRotations,this.autoCancelMouseLeftClick=Z.autoCancelMouseLeftClick??this.autoCancelMouseLeftClick,this.faceForwardOnStop=Z.faceForwardOnStop??this.faceForwardOnStop,this.sticksToPlatforms=Z.sticksToPlatforms??this.sticksToPlatforms,this.canJump=Z.canJump??this.canJump,this.canRun=Z.canRun??this.canRun,this.canSwim=Z.canSwim??this.canSwim,this.canWalk=Z.canWalk??this.canWalk,this.jumpVelocity=Z.jumpVelocity??this.jumpVelocity,this.runVelocity=Z.runVelocity??this.runVelocity,this.walkVelocity=Z.walkVelocity??this.walkVelocity,this.swimFastVelocity=Z.swimFastVelocity??this.swimFastVelocity,this.swimSlowVelocity=Z.swimSlowVelocity??this.swimSlowVelocity,this.swimUpwardVelocity=Z.swimUpwardVelocity??this.swimUpwardVelocity,this.swimGravity=Z.swimGravity??this.swimGravity,this.swimMaxGravityVelocity=Z.swimMaxGravityVelocity??this.swimMaxGravityVelocity,this.idleLoopedAnimations=Z.idleLoopedAnimations??this.idleLoopedAnimations,this.interactOneshotAnimations=Z.interactOneshotAnimations??this.interactOneshotAnimations,this.jumpOneshotAnimations=Z.jumpOneshotAnimations??this.jumpOneshotAnimations,this.jumpLandHeavyOneshotAnimations=Z.jumpLandHeavyOneshotAnimations??this.jumpLandHeavyOneshotAnimations,this.jumpLandLightOneshotAnimations=Z.jumpLandLightOneshotAnimations??this.jumpLandLightOneshotAnimations,this.runLoopedAnimations=Z.runLoopedAnimations??this.runLoopedAnimations,this.swimLoopedAnimations=Z.swimLoopedAnimations??this.swimLoopedAnimations,this.swimIdleLoopedAnimations=Z.swimIdleLoopedAnimations??this.swimIdleLoopedAnimations,this.walkLoopedAnimations=Z.walkLoopedAnimations??this.walkLoopedAnimations}get isActivelyMoving(){return this._isActivelyMoving}get isGrounded(){return this._groundContactCount>0}get isOnPlatform(){return!!this._platform}get isSwimming(){return this._liquidContactCount>0}get platform(){return this._platform}attach(Z){super.attach(Z),this._internalApplyImpulse=Z.applyImpulse.bind(Z),Z.applyImpulse=(J)=>{let X=Z.mass||1;this._externalVelocity.x+=J.x/X,this._externalVelocity.y+=J.y/X,this._externalVelocity.z+=J.z/X},this._stepAudio=new RW({uri:"audio/sfx/step/stone/stone-step-04.mp3",loop:!0,volume:0.1,referenceDistance:2,cutoffDistance:15,attachedToEntity:Z}),Z.setCcdEnabled(!0),Z.lockAllRotations(),Z.on("ENTITY.BLOCK_COLLISION",({blockType:J,started:X})=>{if(!J.isLiquid||!this.canSwim(this))return;if(this._liquidContactCount<=0&&X){let $=Z.linearVelocity;Z.setLinearVelocity({x:$.x*this.swimGravity,y:$.y*this.swimGravity,z:$.z*this.swimGravity})}if(this._liquidContactCount+=X?1:-1,this._liquidContactCount>0)Z.setGravityScale(this.swimGravity),Z.stopAllModelLoopedAnimations(this.swimLoopedAnimations),this._swimUpwardCooldownAt=performance.now()+b1.SWIM_UPWARD_COOLDOWN_MS;else Z.setGravityScale(1),Z.stopModelAnimations(this.swimLoopedAnimations)})}spawn(Z){if(!Z.isSpawned)return p.error("DefaultPlayerEntityController.spawn(): Entity is not spawned!");Z.createAndAddChildCollider({shape:"cylinder",radius:b1.GROUND_SENSOR_RADIUS_SCALE*(Z.height/b1.BASE_ENTITY_HEIGHT),halfHeight:b1.GROUND_SENSOR_HEIGHT_SCALE*(Z.height/b1.BASE_ENTITY_HEIGHT),collisionGroups:{belongsTo:[4],collidesWith:[1,2,8]},isSensor:!0,relativePosition:{x:0,y:-Z.height/2,z:0},tag:"groundSensor",onCollision:(J,X)=>{if(!Z.isSpawned)return;if(!(J instanceof A5)||!J.isLiquid){if(X&&this._groundContactCount===0&&Z.linearVelocity.y<-1)if(Z.linearVelocity.y<b1.JUMP_LAND_HEAVY_VELOCITY_THRESHOLD)Z.startModelOneshotAnimations(this.jumpLandHeavyOneshotAnimations);else Z.startModelOneshotAnimations(this.jumpLandLightOneshotAnimations);this._groundContactCount+=X?1:-1}if(!this._groundContactCount&&!this.isSwimming)Z.startModelOneshotAnimations(this.jumpOneshotAnimations);else Z.stopModelAnimations(this.jumpOneshotAnimations);if(!(J instanceof j8))return;if(X&&this.sticksToPlatforms)this._platform=J;else if(J===this._platform&&!X)this._platform=void 0}}),Z.createAndAddChildCollider({shape:"capsule",halfHeight:b1.WALL_COLLIDER_HEIGHT_SCALE*(Z.height/b1.BASE_ENTITY_HEIGHT),radius:b1.WALL_COLLIDER_RADIUS_SCALE*(Z.height/b1.BASE_ENTITY_HEIGHT),collisionGroups:{belongsTo:[4],collidesWith:[1,2,8]},friction:0,frictionCombineRule:1,tag:"wallCollider"})}tickWithPlayerInput(Z,J,X,$){if(!Z.isSpawned||!Z.world)return;if(super.tickWithPlayerInput(Z,J,X,$),Z.parent)return;let{w:Y,a:Q,s:K,d:W,c:G,sp:z,sh:v,ml:H}=J,{yaw:V}=X,q=Z.linearVelocity;this._reusableTargetVelocities.x=0,this._reusableTargetVelocities.y=0,this._reusableTargetVelocities.z=0,this._isActivelyMoving=!!(Y||Q||K||W);let F=v,x=Q&&W&&!Y&&!K||Y&&K&&!Q&&!W,c=F&&this.canRun(this)||!F&&this.canWalk(this);if(this.isSwimming&&!this._isFullySubmerged)this._isFullySubmerged=!0,this._justSubmergedUntil=performance.now()+b1.WATER_ENTRY_SINKING_MS;else if(!this.isSwimming)this._isFullySubmerged=!1,this._justSubmergedUntil=0;if(this.isGrounded&&!this.isSwimming&&this._isActivelyMoving&&!x&&c){let M=F?this.runLoopedAnimations:this.walkLoopedAnimations;Z.stopAllModelLoopedAnimations(M),Z.startModelLoopedAnimations(M),this._stepAudio?.setPlaybackRate(F?0.75:0.51),this._stepAudio?.play(Z.world,!this._stepAudio?.isPlaying)}else if(this._isFullySubmerged&&this.canSwim(this))if(this._stepAudio?.pause(),this._isActivelyMoving)Z.stopAllModelLoopedAnimations(this.swimLoopedAnimations),Z.startModelLoopedAnimations(this.swimLoopedAnimations);else Z.stopAllModelLoopedAnimations(this.swimIdleLoopedAnimations),Z.startModelLoopedAnimations(this.swimIdleLoopedAnimations);else this._stepAudio?.pause(),Z.stopAllModelLoopedAnimations(this.idleLoopedAnimations),Z.startModelLoopedAnimations(this.idleLoopedAnimations);let w;if(this.applyDirectionalMovementRotations&&c){if(Y&&Q&&!W&&!K)w=b1.MOVEMENT_ROTATIONS.wa;else if(Y&&W&&!Q&&!K)w=b1.MOVEMENT_ROTATIONS.wd;else if(K&&Q&&!Y&&!W)w=b1.MOVEMENT_ROTATIONS.sa;else if(K&&W&&!Y&&!Q)w=b1.MOVEMENT_ROTATIONS.sd;else if(K&&!Y&&!Q&&!W||Q&&K&&W&&!Y)w=b1.MOVEMENT_ROTATIONS.s;else if(Q&&!Y&&!K&&!W)w=b1.MOVEMENT_ROTATIONS.a;else if(W&&!Y&&!Q&&!K)w=b1.MOVEMENT_ROTATIONS.d}if(H)Z.startModelOneshotAnimations(this.interactOneshotAnimations),J.ml=!this.autoCancelMouseLeftClick;if(c){let M=!this.isSwimming?F?this.runVelocity:this.walkVelocity:F?this.swimFastVelocity:this.swimSlowVelocity,N=Math.sin(V),P=Math.cos(V);if(Y)this._reusableTargetVelocities.x-=M*N,this._reusableTargetVelocities.z-=M*P;if(K)this._reusableTargetVelocities.x+=M*N,this._reusableTargetVelocities.z+=M*P;if(Q)this._reusableTargetVelocities.x-=M*P,this._reusableTargetVelocities.z+=M*N;if(W)this._reusableTargetVelocities.x+=M*P,this._reusableTargetVelocities.z-=M*N;let O=Math.sqrt(this._reusableTargetVelocities.x*this._reusableTargetVelocities.x+this._reusableTargetVelocities.z*this._reusableTargetVelocities.z);if(O>M){let _=M/O;this._reusableTargetVelocities.x*=_,this._reusableTargetVelocities.z*=_}}if(this.isSwimming){if(q.y<this.swimMaxGravityVelocity)this._reusableVelocityClamp.x=q.x,this._reusableVelocityClamp.y=this.swimMaxGravityVelocity,this._reusableVelocityClamp.z=q.z,Z.setLinearVelocity(this._reusableVelocityClamp);if(q.y>this.swimUpwardVelocity*2)this._reusableVelocityClamp.x=q.x,this._reusableVelocityClamp.y=this.swimUpwardVelocity*2,this._reusableVelocityClamp.z=q.z,Z.setLinearVelocity(this._reusableVelocityClamp);if(G)this._reusableTargetVelocities.y=-this.swimUpwardVelocity;else if(performance.now()<this._justSubmergedUntil)this._reusableTargetVelocities.y=-this.swimUpwardVelocity*b1.WATER_ENTRY_SINKING_FACTOR;else if(!z)this._reusableTargetVelocities.y=-q.y*b1.SWIMMING_DRAG_FACTOR}if(z&&this.canJump(this)){if(this.isGrounded&&!this.isSwimming&&q.y>-0.001&&q.y<=3)this._reusableTargetVelocities.y=this.jumpVelocity;else if(this.isSwimming&&performance.now()>this._swimUpwardCooldownAt)this._reusableTargetVelocities.y=this.swimUpwardVelocity}let B=this._platform?.linearVelocity??this._reusablePlatformVelocity;if(this._externalVelocity.y!==0)this._magnitudeYTracker+=this._externalVelocity.y;if(this._externalVelocity.x!==0||this._externalVelocity.y!==0||this._externalVelocity.z!==0){if(this.isGrounded){let M=Math.sqrt(this._externalVelocity.x*this._externalVelocity.x+this._magnitudeYTracker*this._magnitudeYTracker+this._externalVelocity.z*this._externalVelocity.z);if(M>0.01){let P=Math.max(0,M-b1.EXTERNAL_IMPULSE_DECAY_RATE)/M;this._externalVelocity.x*=P,this._magnitudeYTracker*=P,this._externalVelocity.z*=P}else this._externalVelocity.x=0,this._externalVelocity.y=0,this._magnitudeYTracker=0,this._externalVelocity.z=0}}let j=this._reusableTargetVelocities.x+this._externalVelocity.x-q.x+B.x,L=this._reusableTargetVelocities.y+this._externalVelocity.y+B.y,R=this._reusableTargetVelocities.z+this._externalVelocity.z-q.z+B.z;if(this._externalVelocity.y=0,j!==0||L!==0||R!==0){let M=Z.mass;this._reusableImpulse.x=j*M,this._reusableImpulse.y=L*M,this._reusableImpulse.z=R*M,this._internalApplyImpulse(this._reusableImpulse)}if(V!==void 0&&(this.faceForwardOnStop||this.isActivelyMoving)){let N=(w!==void 0?V+w:V)*0.5;Z.setRotation({x:0,y:Math.sin(N),z:0,w:Math.cos(N)})}}}var iP;((W)=>{W.LOAD="SCENE_UI.LOAD";W.SET_ATTACHED_TO_ENTITY="SCENE_UI.SET_ATTACHED_TO_ENTITY";W.SET_OFFSET="SCENE_UI.SET_OFFSET";W.SET_POSITION="SCENE_UI.SET_POSITION";W.SET_STATE="SCENE_UI.SET_STATE";W.SET_VIEW_DISTANCE="SCENE_UI.SET_VIEW_DISTANCE";W.UNLOAD="SCENE_UI.UNLOAD"})(iP||={});class mz extends B0{_id;_attachedToEntity;_offset;_position;_state={};_templateId;_viewDistance;_world;constructor(Z){if(!!Z.attachedToEntity===!!Z.position)p.fatalError("Either attachedToEntity or position must be set, but not both");super();this._attachedToEntity=Z.attachedToEntity,this._offset=Z.offset,this._position=Z.position,this._state=Z.state??{},this._templateId=Z.templateId,this._viewDistance=Z.viewDistance}get id(){return this._id}get attachedToEntity(){return this._attachedToEntity}get isLoaded(){return this._id!==void 0}get offset(){return this._offset}get position(){return this._position}get state(){return this._state}get templateId(){return this._templateId}get viewDistance(){return this._viewDistance}get world(){return this._world}load(Z){if(this.isLoaded)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return p.error(`SceneUI.load(): Attached entity ${this._attachedToEntity.id} must be spawned before loading SceneUI!`);this._id=Z.sceneUIManager.registerSceneUI(this),this._world=Z,this.emitWithWorld(Z,"SCENE_UI.LOAD",{sceneUI:this})}setAttachedToEntity(Z){if(!Z.isSpawned)return p.error(`SceneUI.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);if(this._attachedToEntity===Z)return;if(this._attachedToEntity=Z,this._position=void 0,this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_ATTACHED_TO_ENTITY",{sceneUI:this,entity:Z})}setOffset(Z){if(this._offset===Z)return;if(this._offset=Z,this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_OFFSET",{sceneUI:this,offset:Z})}setPosition(Z){if(this._position===Z)return;if(this._attachedToEntity=void 0,this._position=Z,this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_POSITION",{sceneUI:this,position:Z})}setState(Z){if(this._state={...this._state,...Z},this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_STATE",{sceneUI:this,state:this._state})}setViewDistance(Z){if(this._viewDistance=Z,this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_VIEW_DISTANCE",{sceneUI:this,viewDistance:Z})}unload(){if(!this.isLoaded||!this._world)return;this._world.sceneUIManager.unregisterSceneUI(this),this.emitWithWorld(this._world,"SCENE_UI.UNLOAD",{sceneUI:this}),this._id=void 0,this._world=void 0}serialize(){return T0.serializeSceneUI(this)}}var C80=0.010000000000000002,f80=Math.cos(0.026);class F7 extends j8{player;nametagSceneUI;constructor(Z){super(Z);this._positionUpdateThresholdSq=C80,this._rotationUpdateThreshold=f80,this.player=Z.player,this.nametagSceneUI=new mz({templateId:"hytopia:nametag",attachedToEntity:this,offset:{x:0,y:1,z:0},viewDistance:15,state:{username:this.player.username,profilePictureUrl:this.player.profilePictureUrl}})}spawn(Z,J,X){super.spawn(Z,J,X),this.nametagSceneUI.load(Z),this.player.on("PLAYER.CHAT_MESSAGE_SEND",({message:$})=>{this.nametagSceneUI.setState({chat:$})})}tick(Z){if(!this.isSpawned||!this.world)return;if(!this.controller)return p.error(`PlayerEntity.tick(): PlayerEntity "${this.name}" must have a controller.`);let{input:J,camera:X}=this.player;this.controller.tickWithPlayerInput(this,J,X.orientation,Z),super.tick(Z)}}var k80="models/players/player.gltf",aI1={BACK:"back-anchor",HEAD:"head-anchor",LEFT_ARM:"arm-left-anchor",LEFT_FOOT:"foot-left-anchor",LEFT_HAND:"hand-left-anchor",LEFT_ITEM:"hand-left-anchor",LEFT_LEG:"leg-left-anchor",RIGHT_ARM:"arm-right-anchor",RIGHT_FOOT:"foot-right-anchor",RIGHT_HAND:"hand-right-anchor",RIGHT_ITEM:"hand-right-anchor",RIGHT_LEG:"leg-right-anchor",TORSO:"torso-anchor"};class gP extends F7{_cosmeticHiddenSlots;constructor(Z){super({modelUri:k80,modelLoopedAnimations:["idle_lower","idle_upper"],modelHiddenNodes:["hair-"],modelShownNodes:["hair-0003"],...Z});if(this._cosmeticHiddenSlots=Z.cosmeticHiddenSlots??[],!Z.controller)this.setController(new b1)}get cosmeticHiddenSlots(){return this._cosmeticHiddenSlots}spawn(Z,J,X){super.spawn(Z,J,X),this.player.cosmetics.then(($)=>{if(!$||!this.modelUri)return;let Y=this.modelShownNodes.values().toArray().filter((W)=>!W.includes("hair-"));if(!($.equippedItems.some((W)=>W.item.flags.includes("HIDES_HAIR"))&&!this._cosmeticHiddenSlots.includes("ALL")&&!this._cosmeticHiddenSlots.includes("HEAD")))Y.push(`hair-${String($.hairStyle).padStart(4,"0")}`);if(this.setModelShownNodes(Y),this.modelUri===k80)this.setModelTextureUri($.skinTextureUri);if(this._cosmeticHiddenSlots.includes("ALL"))return;let K=[];for(let W of $.equippedItems){let{item:G,slot:z}=W;if(this._cosmeticHiddenSlots.includes(z))continue;let v=aI1[z];if(!v||!j6.instance.modelHasNode(this.modelUri,v))continue;if(G.flags.includes("REPLACES_LIMB")){let V=v.split("-").slice(0,-1).join("-");K.push(`${V}-clothing`,`${V}-geometry`)}new j8({modelUri:G.modelUrl,modelPreferredShape:"none",parent:this,parentNodeName:v}).spawn(Z,{x:0,y:0,z:0})}if(K.length>0)this.setModelHiddenNodes([...this.modelHiddenNodes.values().toArray(),...K])}).catch(($)=>p.warning(`DefaultPlayerEntity.spawn(): Failed to get player cosmetics: ${$}`))}}class uz{_activeEntities=new Set;_entities=new Map;_nextEntityId=1;_world;constructor(Z){this._world=Z}get entityCount(){return this._entities.size}get world(){return this._world}registerEntity(Z){if(Z.id!==void 0)p.fatalError(`EntityManager.registerEntity(): Entity ${Z.name} is already assigned the id ${Z.id}!`);let J=this._nextEntityId;if(this._entities.set(J,Z),this._nextEntityId++,!Z.isEnvironmental)this._activeEntities.add(Z);return J}unregisterEntity(Z){if(Z.id===void 0)return p.error(`EntityManager.unregisterEntity(): Entity ${Z.name} is not assigned an id!`);if(this._entities.delete(Z.id),!Z.isEnvironmental)this._activeEntities.delete(Z)}getAllEntities(){return Array.from(this._entities.values())}getAllPlayerEntities(){let Z=[];return this._entities.forEach((J)=>{if(J instanceof F7)Z.push(J)}),Z}getPlayerEntitiesByPlayer(Z){let J=[];return this._entities.forEach((X)=>{if(X instanceof F7&&X.player===Z)J.push(X)}),J}getEntity(Z){return this._entities.get(Z)}getEntitiesByTag(Z){let J=[];return this._entities.forEach((X)=>{if(X.tag===Z)J.push(X)}),J}getEntitiesByTagSubstring(Z){let J=[];return this._entities.forEach((X)=>{if(X.tag?.includes(Z))J.push(X)}),J}getEntityChildren(Z){let J=[];return this._entities.forEach((X)=>{if(X.parent===Z)J.push(X)}),J}tickEntities(Z){for(let J of this._activeEntities)J.tick(Z)}checkAndEmitUpdates(){for(let Z of this._activeEntities)Z.checkAndEmitUpdates()}}import{gzipSync as gJ6}from"zlib";var d6=t(b60(),1),Ub6=d6.default.v1,Bb6=d6.default.v1ToV6,jb6=d6.default.v3,h60=d6.default.v4,Lb6=d6.default.v5,Db6=d6.default.v6,Mb6=d6.default.v6ToV1,Rb6=d6.default.v7,Nb6=d6.default.NIL,Ob6=d6.default.MAX,Pb6=d6.default.version,Tb6=d6.default.validate,Cb6=d6.default.stringify,fb6=d6.default.parse;var eP;try{eP=new TextDecoder}catch(Z){}var X0,g5,m=0;var $T=[],JY=$T,pz=0,f1={},Y1,_Z,i5=0,P4=0,S8,bZ,B5=[],e0,S60={useRecords:!1,mapsAsObjects:!0};class ec{}var YT=new ec;YT.name="MessagePack 0xC1";var $X=!1,g60=2,ZT,JT,XT;try{new Function("")}catch(Z){g60=1/0}class hZ{constructor(Z){if(Z){if(Z.useRecords===!1&&Z.mapsAsObjects===void 0)Z.mapsAsObjects=!0;if(Z.sequential&&Z.trusted!==!1){if(Z.trusted=!0,!Z.structures&&Z.useRecords!=!1){if(Z.structures=[],!Z.maxSharedStructures)Z.maxSharedStructures=0}}if(Z.structures)Z.structures.sharedLength=Z.structures.length;else if(Z.getStructures)(Z.structures=[]).uninitialized=!0,Z.structures.sharedLength=0;if(Z.int64AsNumber)Z.int64AsType="number"}Object.assign(this,Z)}unpack(Z,J){if(X0)return X50(()=>{return tc(),this?this.unpack(Z,J):hZ.prototype.unpack.call(S60,Z,J)});if(!Z.buffer&&Z.constructor===ArrayBuffer)Z=typeof Buffer!=="undefined"?Buffer.from(Z):new Uint8Array(Z);if(typeof J==="object")g5=J.end||Z.length,m=J.start||0;else m=0,g5=J>-1?J:Z.length;pz=0,P4=0,_Z=null,JY=$T,S8=null,X0=Z;try{e0=Z.dataView||(Z.dataView=new DataView(Z.buffer,Z.byteOffset,Z.byteLength))}catch(X){if(X0=null,Z instanceof Uint8Array)throw X;throw new Error("Source must be a Uint8Array or Buffer but was a "+(Z&&typeof Z=="object"?Z.constructor.name:typeof Z))}if(this instanceof hZ){if(f1=this,this.structures)return Y1=this.structures,oc(J);else if(!Y1||Y1.length>0)Y1=[]}else if(f1=S60,!Y1||Y1.length>0)Y1=[];return oc(J)}unpackMultiple(Z,J){let X,$=0;try{$X=!0;let Y=Z.length,Q=this?this.unpack(Z,Y):Zw.unpack(Z,Y);if(J){if(J(Q,$,m)===!1)return;while(m<Y)if($=m,J(oc(),$,m)===!1)return}else{X=[Q];while(m<Y)$=m,X.push(oc());return X}}catch(Y){throw Y.lastPosition=$,Y.values=X,Y}finally{$X=!1,tc()}}_mergeStructures(Z,J){if(JT)Z=JT.call(this,Z);if(Z=Z||[],Object.isFrozen(Z))Z=Z.map((X)=>X.slice(0));for(let X=0,$=Z.length;X<$;X++){let Y=Z[X];if(Y){if(Y.isShared=!0,X>=32)Y.highByte=X-32>>5}}Z.sharedLength=Z.length;for(let X in J||[])if(X>=0){let $=Z[X],Y=J[X];if(Y){if($)(Z.restoreStructures||(Z.restoreStructures=[]))[X]=$;Z[X]=Y}}return this.structures=Z}decode(Z,J){return this.unpack(Z,J)}}function oc(Z){try{if(!f1.trusted&&!$X){let X=Y1.sharedLength||0;if(X<Y1.length)Y1.length=X}let J;if(f1.randomAccessStructure&&X0[m]<64&&X0[m]>=32&&ZT){if(J=ZT(X0,m,g5,f1),X0=null,!(Z&&Z.lazy)&&J)J=J.toJSON();m=g5}else J=L8();if(S8)m=S8.postBundlePosition,S8=null;if($X)Y1.restoreStructures=null;if(m==g5){if(Y1&&Y1.restoreStructures)A60();if(Y1=null,X0=null,bZ)bZ=null}else if(m>g5)throw new Error("Unexpected end of MessagePack data");else if(!$X){let X;try{X=JSON.stringify(J,($,Y)=>typeof Y==="bigint"?`${Y}n`:Y).slice(0,100)}catch($){X="(JSON view not available "+$+")"}throw new Error("Data read, but end of buffer not reached "+X)}return J}catch(J){if(Y1&&Y1.restoreStructures)A60();if(tc(),J instanceof RangeError||J.message.startsWith("Unexpected end of buffer")||m>g5)J.incomplete=!0;throw J}}function A60(){for(let Z in Y1.restoreStructures)Y1[Z]=Y1.restoreStructures[Z];Y1.restoreStructures=null}function L8(){let Z=X0[m++];if(Z<160)if(Z<128)if(Z<64)return Z;else{let J=Y1[Z&63]||f1.getStructures&&d60()[Z&63];if(J){if(!J.read)J.read=QT(J,Z&63);return J.read()}else return Z}else if(Z<144)if(Z-=128,f1.mapsAsObjects){let J={};for(let X=0;X<Z;X++){let $=Z50();if($==="__proto__")$="__proto_";J[$]=L8()}return J}else{let J=new Map;for(let X=0;X<Z;X++)J.set(L8(),L8());return J}else{Z-=144;let J=new Array(Z);for(let X=0;X<Z;X++)J[X]=L8();if(f1.freezeData)return Object.freeze(J);return J}else if(Z<192){let J=Z-160;if(P4>=m)return _Z.slice(m-i5,(m+=J)-i5);if(P4==0&&g5<140){let X=J<16?KT(J):e60(J);if(X!=null)return X}return rc(J)}else{let J;switch(Z){case 192:return null;case 193:if(S8)if(J=L8(),J>0)return S8[1].slice(S8.position1,S8.position1+=J);else return S8[0].slice(S8.position0,S8.position0-=J);return YT;case 194:return!1;case 195:return!0;case 196:if(J=X0[m++],J===void 0)throw new Error("Unexpected end of buffer");return tP(J);case 197:return J=e0.getUint16(m),m+=2,tP(J);case 198:return J=e0.getUint32(m),m+=4,tP(J);case 199:return ZY(X0[m++]);case 200:return J=e0.getUint16(m),m+=2,ZY(J);case 201:return J=e0.getUint32(m),m+=4,ZY(J);case 202:if(J=e0.getFloat32(m),f1.useFloat32>2){let X=$Y[(X0[m]&127)<<1|X0[m+1]>>7];return m+=4,(X*J+(J>0?0.5:-0.5)>>0)/X}return m+=4,J;case 203:return J=e0.getFloat64(m),m+=8,J;case 204:return X0[m++];case 205:return J=e0.getUint16(m),m+=2,J;case 206:return J=e0.getUint32(m),m+=4,J;case 207:if(f1.int64AsType==="number")J=e0.getUint32(m)*4294967296,J+=e0.getUint32(m+4);else if(f1.int64AsType==="string")J=e0.getBigUint64(m).toString();else if(f1.int64AsType==="auto"){if(J=e0.getBigUint64(m),J<=BigInt(2)<<BigInt(52))J=Number(J)}else J=e0.getBigUint64(m);return m+=8,J;case 208:return e0.getInt8(m++);case 209:return J=e0.getInt16(m),m+=2,J;case 210:return J=e0.getInt32(m),m+=4,J;case 211:if(f1.int64AsType==="number")J=e0.getInt32(m)*4294967296,J+=e0.getUint32(m+4);else if(f1.int64AsType==="string")J=e0.getBigInt64(m).toString();else if(f1.int64AsType==="auto"){if(J=e0.getBigInt64(m),J>=BigInt(-2)<<BigInt(52)&&J<=BigInt(2)<<BigInt(52))J=Number(J)}else J=e0.getBigInt64(m);return m+=8,J;case 212:if(J=X0[m++],J==114)return i60(X0[m++]&63);else{let X=B5[J];if(X)if(X.read)return m++,X.read(L8());else if(X.noBuffer)return m++,X();else return X(X0.subarray(m,++m));else throw new Error("Unknown extension "+J)}case 213:if(J=X0[m],J==114)return m++,i60(X0[m++]&63,X0[m++]);else return ZY(2);case 214:return ZY(4);case 215:return ZY(8);case 216:return ZY(16);case 217:if(J=X0[m++],P4>=m)return _Z.slice(m-i5,(m+=J)-i5);return a60(J);case 218:if(J=e0.getUint16(m),m+=2,P4>=m)return _Z.slice(m-i5,(m+=J)-i5);return n60(J);case 219:if(J=e0.getUint32(m),m+=4,P4>=m)return _Z.slice(m-i5,(m+=J)-i5);return s60(J);case 220:return J=e0.getUint16(m),m+=2,u60(J);case 221:return J=e0.getUint32(m),m+=4,u60(J);case 222:return J=e0.getUint16(m),m+=2,l60(J);case 223:return J=e0.getUint32(m),m+=4,l60(J);default:if(Z>=224)return Z-256;if(Z===void 0){let X=new Error("Unexpected end of MessagePack data");throw X.incomplete=!0,X}throw new Error("Unknown MessagePack token "+Z)}}}var Db1=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function QT(Z,J){function X(){if(X.count++>g60){let Y=Z.read=new Function("r","return function(){return "+(f1.freezeData?"Object.freeze":"")+"({"+Z.map((Q)=>Q==="__proto__"?"__proto_:r()":Db1.test(Q)?Q+":r()":"["+JSON.stringify(Q)+"]:r()").join(",")+"})}")(L8);if(Z.highByte===0)Z.read=m60(J,Z.read);return Y()}let $={};for(let Y=0,Q=Z.length;Y<Q;Y++){let K=Z[Y];if(K==="__proto__")K="__proto_";$[K]=L8()}if(f1.freezeData)return Object.freeze($);return $}if(X.count=0,Z.highByte===0)return m60(J,X);return X}var m60=(Z,J)=>{return function(){let X=X0[m++];if(X===0)return J();let $=Z<32?-(Z+(X<<5)):Z+(X<<5),Y=Y1[$]||d60()[$];if(!Y)throw new Error("Record id is not defined for "+$);if(!Y.read)Y.read=QT(Y,Z);return Y.read()}};function d60(){let Z=X50(()=>{return X0=null,f1.getStructures()});return Y1=f1._mergeStructures(Z,Y1)}var rc=XY,a60=XY,n60=XY,s60=XY,o60=!1;function r60(Z){o60=!0,rc=J(1),a60=J(2),n60=J(3),s60=J(5);function J(X){return function $(Y){let Q=JY[pz++];if(Q==null){if(S8)return XY(Y);let W=X0.byteOffset,G=Z(m-X+W,g5+W,X0.buffer);if(typeof G=="string")Q=G,JY=$T;else if(JY=G,pz=1,P4=1,Q=JY[0],Q===void 0)throw new Error("Unexpected end of buffer")}let K=Q.length;if(K<=Y)return m+=Y,Q;return _Z=Q,i5=m,P4=m+K,m+=Y,Q.slice(0,Y)}}}function XY(Z){let J;if(Z<16){if(J=KT(Z))return J}if(Z>64&&eP)return eP.decode(X0.subarray(m,m+=Z));let X=m+Z,$=[];J="";while(m<X){let Y=X0[m++];if((Y&128)===0)$.push(Y);else if((Y&224)===192){let Q=X0[m++]&63;$.push((Y&31)<<6|Q)}else if((Y&240)===224){let Q=X0[m++]&63,K=X0[m++]&63;$.push((Y&31)<<12|Q<<6|K)}else if((Y&248)===240){let Q=X0[m++]&63,K=X0[m++]&63,W=X0[m++]&63,G=(Y&7)<<18|Q<<12|K<<6|W;if(G>65535)G-=65536,$.push(G>>>10&1023|55296),G=56320|G&1023;$.push(G)}else $.push(Y);if($.length>=4096)J+=a8.apply(String,$),$.length=0}if($.length>0)J+=a8.apply(String,$);return J}function t60(Z,J,X){let $=X0;X0=Z,m=J;try{return XY(X)}finally{X0=$}}function u60(Z){let J=new Array(Z);for(let X=0;X<Z;X++)J[X]=L8();if(f1.freezeData)return Object.freeze(J);return J}function l60(Z){if(f1.mapsAsObjects){let J={};for(let X=0;X<Z;X++){let $=Z50();if($==="__proto__")$="__proto_";J[$]=L8()}return J}else{let J=new Map;for(let X=0;X<Z;X++)J.set(L8(),L8());return J}}var a8=String.fromCharCode;function e60(Z){let J=m,X=new Array(Z);for(let $=0;$<Z;$++){let Y=X0[m++];if((Y&128)>0){m=J;return}X[$]=Y}return a8.apply(String,X)}function KT(Z){if(Z<4)if(Z<2)if(Z===0)return"";else{let J=X0[m++];if((J&128)>1){m-=1;return}return a8(J)}else{let J=X0[m++],X=X0[m++];if((J&128)>0||(X&128)>0){m-=2;return}if(Z<3)return a8(J,X);let $=X0[m++];if(($&128)>0){m-=3;return}return a8(J,X,$)}else{let J=X0[m++],X=X0[m++],$=X0[m++],Y=X0[m++];if((J&128)>0||(X&128)>0||($&128)>0||(Y&128)>0){m-=4;return}if(Z<6)if(Z===4)return a8(J,X,$,Y);else{let Q=X0[m++];if((Q&128)>0){m-=5;return}return a8(J,X,$,Y,Q)}else if(Z<8){let Q=X0[m++],K=X0[m++];if((Q&128)>0||(K&128)>0){m-=6;return}if(Z<7)return a8(J,X,$,Y,Q,K);let W=X0[m++];if((W&128)>0){m-=7;return}return a8(J,X,$,Y,Q,K,W)}else{let Q=X0[m++],K=X0[m++],W=X0[m++],G=X0[m++];if((Q&128)>0||(K&128)>0||(W&128)>0||(G&128)>0){m-=8;return}if(Z<10)if(Z===8)return a8(J,X,$,Y,Q,K,W,G);else{let z=X0[m++];if((z&128)>0){m-=9;return}return a8(J,X,$,Y,Q,K,W,G,z)}else if(Z<12){let z=X0[m++],v=X0[m++];if((z&128)>0||(v&128)>0){m-=10;return}if(Z<11)return a8(J,X,$,Y,Q,K,W,G,z,v);let H=X0[m++];if((H&128)>0){m-=11;return}return a8(J,X,$,Y,Q,K,W,G,z,v,H)}else{let z=X0[m++],v=X0[m++],H=X0[m++],V=X0[m++];if((z&128)>0||(v&128)>0||(H&128)>0||(V&128)>0){m-=12;return}if(Z<14)if(Z===12)return a8(J,X,$,Y,Q,K,W,G,z,v,H,V);else{let q=X0[m++];if((q&128)>0){m-=13;return}return a8(J,X,$,Y,Q,K,W,G,z,v,H,V,q)}else{let q=X0[m++],F=X0[m++];if((q&128)>0||(F&128)>0){m-=14;return}if(Z<15)return a8(J,X,$,Y,Q,K,W,G,z,v,H,V,q,F);let x=X0[m++];if((x&128)>0){m-=15;return}return a8(J,X,$,Y,Q,K,W,G,z,v,H,V,q,F,x)}}}}}function y60(){let Z=X0[m++],J;if(Z<192)J=Z-160;else switch(Z){case 217:J=X0[m++];break;case 218:J=e0.getUint16(m),m+=2;break;case 219:J=e0.getUint32(m),m+=4;break;default:throw new Error("Expected string")}return XY(J)}function tP(Z){return f1.copyBuffers?Uint8Array.prototype.slice.call(X0,m,m+=Z):X0.subarray(m,m+=Z)}function ZY(Z){let J=X0[m++];if(B5[J]){let X;return B5[J](X0.subarray(m,X=m+=Z),($)=>{m=$;try{return L8()}finally{m=X}})}else throw new Error("Unknown extension type "+J)}var p60=new Array(4096);function Z50(){let Z=X0[m++];if(Z>=160&&Z<192){if(Z=Z-160,P4>=m)return _Z.slice(m-i5,(m+=Z)-i5);else if(!(P4==0&&g5<180))return rc(Z)}else return m--,J50(L8());let J=(Z<<5^(Z>1?e0.getUint16(m):Z>0?X0[m]:0))&4095,X=p60[J],$=m,Y=m+Z-3,Q,K=0;if(X&&X.bytes==Z){while($<Y){if(Q=e0.getUint32($),Q!=X[K++]){$=1879048192;break}$+=4}Y+=3;while($<Y)if(Q=X0[$++],Q!=X[K++]){$=1879048192;break}if($===Y)return m=$,X.string;Y-=3,$=m}X=[],p60[J]=X,X.bytes=Z;while($<Y)Q=e0.getUint32($),X.push(Q),$+=4;Y+=3;while($<Y)Q=X0[$++],X.push(Q);let W=Z<16?KT(Z):e60(Z);if(W!=null)return X.string=W;return X.string=rc(Z)}function J50(Z){if(typeof Z==="string")return Z;if(typeof Z==="number"||typeof Z==="boolean"||typeof Z==="bigint")return Z.toString();if(Z==null)return Z+"";if(f1.allowArraysInMapKeys&&Array.isArray(Z)&&Z.flat().every((J)=>["string","number","boolean","bigint"].includes(typeof J)))return Z.flat().toString();throw new Error(`Invalid property type for record: ${typeof Z}`)}var i60=(Z,J)=>{let X=L8().map(J50),$=Z;if(J!==void 0)Z=Z<32?-((J<<5)+Z):(J<<5)+Z,X.highByte=J;let Y=Y1[Z];if(Y&&(Y.isShared||$X))(Y1.restoreStructures||(Y1.restoreStructures=[]))[Z]=Y;return Y1[Z]=X,X.read=QT(X,$),X.read()};B5[0]=()=>{};B5[0].noBuffer=!0;B5[66]=(Z)=>{let J=Z.length,X=BigInt(Z[0]&128?Z[0]-256:Z[0]);for(let $=1;$<J;$++)X<<=BigInt(8),X+=BigInt(Z[$]);return X};var Mb1={Error,TypeError,ReferenceError};B5[101]=()=>{let Z=L8();return(Mb1[Z[0]]||Error)(Z[1],{cause:Z[2]})};B5[105]=(Z)=>{if(f1.structuredClone===!1)throw new Error("Structured clone extension is disabled");let J=e0.getUint32(m-4);if(!bZ)bZ=new Map;let X=X0[m],$;if(X>=144&&X<160||X==220||X==221)$=[];else if(X>=128&&X<144||X==222||X==223)$=new Map;else if((X>=199&&X<=201||X>=212&&X<=216)&&X0[m+1]===115)$=new Set;else $={};let Y={target:$};bZ.set(J,Y);let Q=L8();if(!Y.used)return Y.target=Q;else Object.assign($,Q);if($ instanceof Map)for(let[K,W]of Q.entries())$.set(K,W);if($ instanceof Set)for(let K of Array.from(Q))$.add(K);return $};B5[112]=(Z)=>{if(f1.structuredClone===!1)throw new Error("Structured clone extension is disabled");let J=e0.getUint32(m-4),X=bZ.get(J);return X.used=!0,X.target};B5[115]=()=>new Set(L8());var WT=["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64","BigInt64","BigUint64"].map((Z)=>Z+"Array"),Rb1=typeof globalThis==="object"?globalThis:window;B5[116]=(Z)=>{let J=Z[0],X=Uint8Array.prototype.slice.call(Z,1).buffer,$=WT[J];if(!$){if(J===16)return X;if(J===17)return new DataView(X);throw new Error("Could not find typed array for code "+J)}return new Rb1[$](X)};B5[120]=()=>{let Z=L8();return new RegExp(Z[0],Z[1])};var Nb1=[];B5[98]=(Z)=>{let J=(Z[0]<<24)+(Z[1]<<16)+(Z[2]<<8)+Z[3],X=m;return m+=J-Z.length,S8=Nb1,S8=[y60(),y60()],S8.position0=0,S8.position1=0,S8.postBundlePosition=m,m=X,L8()};B5[255]=(Z)=>{if(Z.length==4)return new Date((Z[0]*16777216+(Z[1]<<16)+(Z[2]<<8)+Z[3])*1000);else if(Z.length==8)return new Date(((Z[0]<<22)+(Z[1]<<14)+(Z[2]<<6)+(Z[3]>>2))/1e6+((Z[3]&3)*4294967296+Z[4]*16777216+(Z[5]<<16)+(Z[6]<<8)+Z[7])*1000);else if(Z.length==12)return new Date(((Z[0]<<24)+(Z[1]<<16)+(Z[2]<<8)+Z[3])/1e6+((Z[4]&128?-281474976710656:0)+Z[6]*1099511627776+Z[7]*4294967296+Z[8]*16777216+(Z[9]<<16)+(Z[10]<<8)+Z[11])*1000);else return new Date("invalid")};function X50(Z){if(XT)XT();let J=g5,X=m,$=pz,Y=i5,Q=P4,K=_Z,W=JY,G=bZ,z=S8,v=new Uint8Array(X0.slice(0,g5)),H=Y1,V=Y1.slice(0,Y1.length),q=f1,F=$X,x=Z();return g5=J,m=X,pz=$,i5=Y,P4=Q,_Z=K,JY=W,bZ=G,S8=z,X0=v,$X=F,Y1=H,Y1.splice(0,Y1.length,...V),f1=q,e0=new DataView(X0.buffer,X0.byteOffset,X0.byteLength),x}function tc(){X0=null,bZ=null,Y1=null}var $Y=new Array(147);for(let Z=0;Z<256;Z++)$Y[Z]=+("1e"+Math.floor(45.15-Z*0.30103));var Zw=new hZ({useRecords:!1}),Ob1=Zw.unpack,Pb1=Zw.unpackMultiple,Tb1=Zw.unpack,iz={NEVER:0,ALWAYS:1,DECIMAL_ROUND:3,DECIMAL_FIT:4},Cb1=new Float32Array(1),Eb6=new Uint8Array(Cb1.buffer,0,4);function $50(Z,J,X){ZT=Z,JT=J,XT=X}var Xw;try{Xw=new TextEncoder}catch(Z){}var vT,K50,dz=typeof Buffer!=="undefined",Jw=dz?function(Z){return Buffer.allocUnsafeSlow(Z)}:Uint8Array,W50=dz?Buffer:Uint8Array,Y50=dz?4294967296:2144337920,n,gz,h1,y=0,a6,o1=null,G50,fb1=21760,kb1=/[\u0080-\uFFFF]/,x7=Symbol("record-id");class YY extends hZ{constructor(Z){super(Z);this.offset=0;let J,X,$,Y,Q,K=W50.prototype.utf8Write?function(f,C){return n.utf8Write(f,C,n.byteLength-C)}:Xw&&Xw.encodeInto?function(f,C){return Xw.encodeInto(f,n.subarray(C)).written}:!1,W=this;if(!Z)Z={};let G=Z&&Z.sequential,z=Z.structures||Z.saveStructures,v=Z.maxSharedStructures;if(v==null)v=z?32:0;if(v>8160)throw new Error("Maximum maxSharedStructure is 8160");if(Z.structuredClone&&Z.moreTypes==null)this.moreTypes=!0;let H=Z.maxOwnStructures;if(H==null)H=z?32:64;if(!this.structures&&Z.useRecords!=!1)this.structures=[];let V=v>32||H+v>64,q=v+64,F=v+H+64;if(F>8256)throw new Error("Maximum maxSharedStructure + maxOwnStructure is 8192");let x=[],c=0,w=0;this.pack=this.encode=function(f,C){if(!n)n=new Jw(8192),h1=n.dataView||(n.dataView=new DataView(n.buffer,0,8192)),y=0;if(a6=n.length-10,a6-y<2048)n=new Jw(n.length),h1=n.dataView||(n.dataView=new DataView(n.buffer,0,n.length)),a6=n.length-10,y=0;else y=y+7&2147483640;if(X=y,C&Ab1)y+=C&255;if(Q=W.structuredClone?new Map:null,W.bundleStrings&&typeof f!=="string")o1=[],o1.size=1/0;else o1=null;if(Y=W.structures,Y){if(Y.uninitialized)Y=W._mergeStructures(W.getStructures());let I=Y.sharedLength||0;if(I>v)throw new Error("Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to "+Y.sharedLength);if(!Y.transitions){Y.transitions=Object.create(null);for(let a=0;a<I;a++){let s=Y[a];if(!s)continue;let Z0,o=Y.transitions;for(let M0=0,R0=s.length;M0<R0;M0++){let m0=s[M0];if(Z0=o[m0],!Z0)Z0=o[m0]=Object.create(null);o=Z0}o[x7]=a+64}this.lastNamedStructuresLength=I}if(!G)Y.nextId=I+64}if($)$=!1;let b;try{if(W.randomAccessStructure&&f&&f.constructor&&f.constructor===Object)h(f);else L(f);let I=o1;if(o1)Q50(X,L,0);if(Q&&Q.idsToInsert){let a=Q.idsToInsert.sort((M0,R0)=>M0.offset>R0.offset?1:-1),s=a.length,Z0=-1;while(I&&s>0){let M0=a[--s].offset+X;if(M0<I.stringsPosition+X&&Z0===-1)Z0=0;if(M0>I.position+X){if(Z0>=0)Z0+=6}else{if(Z0>=0)h1.setUint32(I.position+X,h1.getUint32(I.position+X)+Z0),Z0=-1;I=I.previous,s++}}if(Z0>=0&&I)h1.setUint32(I.position+X,h1.getUint32(I.position+X)+Z0);if(y+=a.length*6,y>a6)O(y);W.offset=y;let o=Ib1(n.subarray(X,y),a);return Q=null,o}if(W.offset=y,C&hb1)return n.start=X,n.end=y,n;return n.subarray(X,y)}catch(I){throw b=I,I}finally{if(Y){if(B(),$&&W.saveStructures){let I=Y.sharedLength||0,a=n.subarray(X,y),s=z50(Y,W);if(!b){if(W.saveStructures(s,s.isCompatible)===!1)return W.pack(f,C);if(W.lastNamedStructuresLength=I,n.length>1073741824)n=null;return a}}}if(n.length>1073741824)n=null;if(C&Sb1)y=X}};let B=()=>{if(w<10)w++;let f=Y.sharedLength||0;if(Y.length>f&&!G)Y.length=f;if(c>1e4){if(Y.transitions=null,w=0,c=0,x.length>0)x=[]}else if(x.length>0&&!G){for(let C=0,b=x.length;C<b;C++)x[C][x7]=0;x=[]}},j=(f)=>{var C=f.length;if(C<16)n[y++]=144|C;else if(C<65536)n[y++]=220,n[y++]=C>>8,n[y++]=C&255;else n[y++]=221,h1.setUint32(y,C),y+=4;for(let b=0;b<C;b++)L(f[b])},L=(f)=>{if(y>a6)n=O(y);var C=typeof f,b;if(C==="string"){let I=f.length;if(o1&&I>=4&&I<4096){if((o1.size+=I)>fb1){let o,M0=(o1[0]?o1[0].length*3+o1[1].length:0)+10;if(y+M0>a6)n=O(y+M0);let R0;if(o1.position)R0=o1,n[y]=200,y+=3,n[y++]=98,o=y-X,y+=4,Q50(X,L,0),h1.setUint16(o+X-3,y-X-o);else n[y++]=214,n[y++]=98,o=y-X,y+=4;o1=["",""],o1.previous=R0,o1.size=0,o1.position=o}let Z0=kb1.test(f);o1[Z0?0:1]+=f,n[y++]=193,L(Z0?-I:I);return}let a;if(I<32)a=1;else if(I<256)a=2;else if(I<65536)a=3;else a=5;let s=I*3;if(y+s>a6)n=O(y+s);if(I<64||!K){let Z0,o,M0,R0=y+a;for(Z0=0;Z0<I;Z0++)if(o=f.charCodeAt(Z0),o<128)n[R0++]=o;else if(o<2048)n[R0++]=o>>6|192,n[R0++]=o&63|128;else if((o&64512)===55296&&((M0=f.charCodeAt(Z0+1))&64512)===56320)o=65536+((o&1023)<<10)+(M0&1023),Z0++,n[R0++]=o>>18|240,n[R0++]=o>>12&63|128,n[R0++]=o>>6&63|128,n[R0++]=o&63|128;else n[R0++]=o>>12|224,n[R0++]=o>>6&63|128,n[R0++]=o&63|128;b=R0-y-a}else b=K(f,y+a);if(b<32)n[y++]=160|b;else if(b<256){if(a<2)n.copyWithin(y+2,y+1,y+1+b);n[y++]=217,n[y++]=b}else if(b<65536){if(a<3)n.copyWithin(y+3,y+2,y+2+b);n[y++]=218,n[y++]=b>>8,n[y++]=b&255}else{if(a<5)n.copyWithin(y+5,y+3,y+3+b);n[y++]=219,h1.setUint32(y,b),y+=4}y+=b}else if(C==="number")if(f>>>0===f)if(f<32||f<128&&this.useRecords===!1||f<64&&!this.randomAccessStructure)n[y++]=f;else if(f<256)n[y++]=204,n[y++]=f;else if(f<65536)n[y++]=205,n[y++]=f>>8,n[y++]=f&255;else n[y++]=206,h1.setUint32(y,f),y+=4;else if(f>>0===f)if(f>=-32)n[y++]=256+f;else if(f>=-128)n[y++]=208,n[y++]=f+256;else if(f>=-32768)n[y++]=209,h1.setInt16(y,f),y+=2;else n[y++]=210,h1.setInt32(y,f),y+=4;else{let I;if((I=this.useFloat32)>0&&f<4294967296&&f>=-2147483648){n[y++]=202,h1.setFloat32(y,f);let a;if(I<4||(a=f*$Y[(n[y]&127)<<1|n[y+1]>>7])>>0===a){y+=4;return}else y--}n[y++]=203,h1.setFloat64(y,f),y+=8}else if(C==="object"||C==="function")if(!f)n[y++]=192;else{if(Q){let a=Q.get(f);if(a){if(!a.id){let s=Q.idsToInsert||(Q.idsToInsert=[]);a.id=s.push(a)}n[y++]=214,n[y++]=112,h1.setUint32(y,a.id),y+=4;return}else Q.set(f,{offset:y-X})}let I=f.constructor;if(I===Object)P(f);else if(I===Array)j(f);else if(I===Map)if(this.mapAsEmptyObject)n[y++]=128;else{if(b=f.size,b<16)n[y++]=128|b;else if(b<65536)n[y++]=222,n[y++]=b>>8,n[y++]=b&255;else n[y++]=223,h1.setUint32(y,b),y+=4;for(let[a,s]of f)L(a),L(s)}else{for(let a=0,s=vT.length;a<s;a++){let Z0=K50[a];if(f instanceof Z0){let o=vT[a];if(o.write){if(o.type)n[y++]=212,n[y++]=o.type,n[y++]=0;let s0=o.write.call(this,f);if(s0===f)if(Array.isArray(f))j(f);else P(f);else L(s0);return}let M0=n,R0=h1,m0=y;n=null;let N1;try{N1=o.pack.call(this,f,(s0)=>{if(n=M0,M0=null,y+=s0,y>a6)O(y);return{target:n,targetView:h1,position:y-s0}},L)}finally{if(M0)n=M0,h1=R0,y=m0,a6=n.length-10}if(N1){if(N1.length+y>a6)O(N1.length+y);y=Eb1(N1,n,y,o.type)}return}}if(Array.isArray(f))j(f);else{if(f.toJSON){let a=f.toJSON();if(a!==f)return L(a)}if(C==="function")return L(this.writeFunction&&this.writeFunction(f));P(f)}}}else if(C==="boolean")n[y++]=f?195:194;else if(C==="bigint"){if(f<9223372036854776000&&f>=-9223372036854776000)n[y++]=211,h1.setBigInt64(y,f);else if(f<18446744073709552000&&f>0)n[y++]=207,h1.setBigUint64(y,f);else if(this.largeBigIntToFloat)n[y++]=203,h1.setFloat64(y,Number(f));else if(this.largeBigIntToString)return L(f.toString());else if((this.useBigIntExtension||this.moreTypes)&&f<BigInt(2)**BigInt(1023)&&f>-(BigInt(2)**BigInt(1023))){n[y++]=199,y++,n[y++]=66;let I=[],a;do{let s=f&BigInt(255);a=(s&BigInt(128))===(f<BigInt(0)?BigInt(128):BigInt(0)),I.push(s),f>>=BigInt(8)}while(!((f===BigInt(0)||f===BigInt(-1))&&a));n[y-2]=I.length;for(let s=I.length;s>0;)n[y++]=Number(I[--s]);return}else throw new RangeError(f+" was too large to fit in MessagePack 64-bit integer format, use useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set largeBigIntToString to convert to string");y+=8}else if(C==="undefined")if(this.encodeUndefinedAsNil)n[y++]=192;else n[y++]=212,n[y++]=0,n[y++]=0;else throw new Error("Unknown type: "+C)},R=this.variableMapSize||this.coercibleKeyAsNumber||this.skipValues?(f)=>{let C;if(this.skipValues){C=[];for(let a in f)if((typeof f.hasOwnProperty!=="function"||f.hasOwnProperty(a))&&!this.skipValues.includes(f[a]))C.push(a)}else C=Object.keys(f);let b=C.length;if(b<16)n[y++]=128|b;else if(b<65536)n[y++]=222,n[y++]=b>>8,n[y++]=b&255;else n[y++]=223,h1.setUint32(y,b),y+=4;let I;if(this.coercibleKeyAsNumber)for(let a=0;a<b;a++){I=C[a];let s=Number(I);L(isNaN(s)?I:s),L(f[I])}else for(let a=0;a<b;a++)L(I=C[a]),L(f[I])}:(f)=>{n[y++]=222;let C=y-X;y+=2;let b=0;for(let I in f)if(typeof f.hasOwnProperty!=="function"||f.hasOwnProperty(I))L(I),L(f[I]),b++;if(b>65535)throw new Error('Object is too large to serialize with fast 16-bit map size, use the "variableMapSize" option to serialize this object');n[C+++X]=b>>8,n[C+X]=b&255},M=this.useRecords===!1?R:Z.progressiveRecords&&!V?(f)=>{let C,b=Y.transitions||(Y.transitions=Object.create(null)),I=y++-X,a;for(let s in f)if(typeof f.hasOwnProperty!=="function"||f.hasOwnProperty(s)){if(C=b[s],C)b=C;else{let Z0=Object.keys(f),o=b;b=Y.transitions;let M0=0;for(let R0=0,m0=Z0.length;R0<m0;R0++){let N1=Z0[R0];if(C=b[N1],!C)C=b[N1]=Object.create(null),M0++;b=C}if(I+X+1==y)y--,_(b,Z0,M0);else k(b,Z0,I,M0);a=!0,b=o[s]}L(f[s])}if(!a){let s=b[x7];if(s)n[I+X]=s;else k(b,Object.keys(f),I,0)}}:(f)=>{let C,b=Y.transitions||(Y.transitions=Object.create(null)),I=0;for(let s in f)if(typeof f.hasOwnProperty!=="function"||f.hasOwnProperty(s)){if(C=b[s],!C)C=b[s]=Object.create(null),I++;b=C}let a=b[x7];if(a)if(a>=96&&V)n[y++]=((a-=96)&31)+96,n[y++]=a>>5;else n[y++]=a;else _(b,b.__keys__||Object.keys(f),I);for(let s in f)if(typeof f.hasOwnProperty!=="function"||f.hasOwnProperty(s))L(f[s])},N=typeof this.useRecords=="function"&&this.useRecords,P=N?(f)=>{N(f)?M(f):R(f)}:M,O=(f)=>{let C;if(f>16777216){if(f-X>Y50)throw new Error("Packed buffer would be larger than maximum buffer size");C=Math.min(Y50,Math.round(Math.max((f-X)*(f>67108864?1.25:2),4194304)/4096)*4096)}else C=(Math.max(f-X<<2,n.length-1)>>12)+1<<12;let b=new Jw(C);if(h1=b.dataView||(b.dataView=new DataView(b.buffer,0,C)),f=Math.min(f,n.length),n.copy)n.copy(b,0,X,f);else b.set(n.slice(X,f));return y-=X,X=0,a6=b.length-10,n=b},_=(f,C,b)=>{let I=Y.nextId;if(!I)I=64;if(I<q&&this.shouldShareStructure&&!this.shouldShareStructure(C)){if(I=Y.nextOwnId,!(I<F))I=q;Y.nextOwnId=I+1}else{if(I>=F)I=q;Y.nextId=I+1}let a=C.highByte=I>=96&&V?I-96>>5:-1;if(f[x7]=I,f.__keys__=C,Y[I-64]=C,I<q)if(C.isShared=!0,Y.sharedLength=I-63,$=!0,a>=0)n[y++]=(I&31)+96,n[y++]=a;else n[y++]=I;else{if(a>=0)n[y++]=213,n[y++]=114,n[y++]=(I&31)+96,n[y++]=a;else n[y++]=212,n[y++]=114,n[y++]=I;if(b)c+=w*b;if(x.length>=H)x.shift()[x7]=0;x.push(f),L(C)}},k=(f,C,b,I)=>{let a=n,s=y,Z0=a6,o=X;if(n=gz,y=0,X=0,!n)gz=n=new Jw(8192);a6=n.length-10,_(f,C,I),gz=n;let M0=y;if(n=a,y=s,a6=Z0,X=o,M0>1){let R0=y+M0-1;if(R0>a6)O(R0);let m0=b+X;n.copyWithin(m0+M0,m0+1,y),n.set(gz.slice(0,M0),m0),y=R0}else n[b+X]=gz[0]},h=(f)=>{let C=G50(f,n,X,y,Y,O,(b,I,a)=>{if(a)return $=!0;y=I;let s=n;if(L(b),B(),s!==n)return{position:y,targetView:h1,target:n};return y},this);if(C===0)return P(f);y=C}}useBuffer(Z){n=Z,n.dataView||(n.dataView=new DataView(n.buffer,n.byteOffset,n.byteLength)),y=0}set position(Z){y=Z}get position(){return y}clearSharedData(){if(this.structures)this.structures=[];if(this.typedStructs)this.typedStructs=[]}}K50=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,DataView,ec];vT=[{pack(Z,J,X){let $=Z.getTime()/1000;if((this.useTimestamp32||Z.getMilliseconds()===0)&&$>=0&&$<4294967296){let{target:Y,targetView:Q,position:K}=J(6);Y[K++]=214,Y[K++]=255,Q.setUint32(K,$)}else if($>0&&$<4294967296){let{target:Y,targetView:Q,position:K}=J(10);Y[K++]=215,Y[K++]=255,Q.setUint32(K,Z.getMilliseconds()*4000000+($/1000/4294967296>>0)),Q.setUint32(K+4,$)}else if(isNaN($)){if(this.onInvalidDate)return J(0),X(this.onInvalidDate());let{target:Y,targetView:Q,position:K}=J(3);Y[K++]=212,Y[K++]=255,Y[K++]=255}else{let{target:Y,targetView:Q,position:K}=J(15);Y[K++]=199,Y[K++]=12,Y[K++]=255,Q.setUint32(K,Z.getMilliseconds()*1e6),Q.setBigInt64(K+4,BigInt(Math.floor($)))}}},{pack(Z,J,X){if(this.setAsEmptyObject)return J(0),X({});let $=Array.from(Z),{target:Y,position:Q}=J(this.moreTypes?3:0);if(this.moreTypes)Y[Q++]=212,Y[Q++]=115,Y[Q++]=0;X($)}},{pack(Z,J,X){let{target:$,position:Y}=J(this.moreTypes?3:0);if(this.moreTypes)$[Y++]=212,$[Y++]=101,$[Y++]=0;X([Z.name,Z.message,Z.cause])}},{pack(Z,J,X){let{target:$,position:Y}=J(this.moreTypes?3:0);if(this.moreTypes)$[Y++]=212,$[Y++]=120,$[Y++]=0;X([Z.source,Z.flags])}},{pack(Z,J){if(this.moreTypes)GT(Z,16,J);else zT(dz?Buffer.from(Z):new Uint8Array(Z),J)}},{pack(Z,J){let X=Z.constructor;if(X!==W50&&this.moreTypes)GT(Z,WT.indexOf(X.name),J);else zT(Z,J)}},{pack(Z,J){if(this.moreTypes)GT(Z,17,J);else zT(dz?Buffer.from(Z):new Uint8Array(Z),J)}},{pack(Z,J){let{target:X,position:$}=J(1);X[$]=193}}];function GT(Z,J,X,$){let Y=Z.byteLength;if(Y+1<256){var{target:Q,position:K}=X(4+Y);Q[K++]=199,Q[K++]=Y+1}else if(Y+1<65536){var{target:Q,position:K}=X(5+Y);Q[K++]=200,Q[K++]=Y+1>>8,Q[K++]=Y+1&255}else{var{target:Q,position:K,targetView:W}=X(7+Y);Q[K++]=201,W.setUint32(K,Y+1),K+=4}if(Q[K++]=116,Q[K++]=J,!Z.buffer)Z=new Uint8Array(Z);Q.set(new Uint8Array(Z.buffer,Z.byteOffset,Z.byteLength),K)}function zT(Z,J){let X=Z.byteLength;var $,Y;if(X<256){var{target:$,position:Y}=J(X+2);$[Y++]=196,$[Y++]=X}else if(X<65536){var{target:$,position:Y}=J(X+3);$[Y++]=197,$[Y++]=X>>8,$[Y++]=X&255}else{var{target:$,position:Y,targetView:Q}=J(X+5);$[Y++]=198,Q.setUint32(Y,X),Y+=4}$.set(Z,Y)}function Eb1(Z,J,X,$){let Y=Z.length;switch(Y){case 1:J[X++]=212;break;case 2:J[X++]=213;break;case 4:J[X++]=214;break;case 8:J[X++]=215;break;case 16:J[X++]=216;break;default:if(Y<256)J[X++]=199,J[X++]=Y;else if(Y<65536)J[X++]=200,J[X++]=Y>>8,J[X++]=Y&255;else J[X++]=201,J[X++]=Y>>24,J[X++]=Y>>16&255,J[X++]=Y>>8&255,J[X++]=Y&255}return J[X++]=$,J.set(Z,X),X+=Y,X}function Ib1(Z,J){let X,$=J.length*6,Y=Z.length-$;while(X=J.pop()){let{offset:Q,id:K}=X;Z.copyWithin(Q+$,Q,Y),$-=6;let W=Q+$;Z[W++]=214,Z[W++]=105,Z[W++]=K>>24,Z[W++]=K>>16&255,Z[W++]=K>>8&255,Z[W++]=K&255,Y=Q}return Z}function Q50(Z,J,X){if(o1.length>0){h1.setUint32(o1.position+Z,y+X-o1.position-Z),o1.stringsPosition=y-Z;let $=o1;o1=null,J($[0]),J($[1])}}function z50(Z,J){return Z.isCompatible=(X)=>{let $=!X||(J.lastNamedStructuresLength||0)===X.length;if(!$)J._mergeStructures(X);return $},Z}function v50(Z,J){G50=Z,z50=J}var V50=new YY({useRecords:!1}),_b1=V50.pack,bb1=V50.pack;var hb1=512,Sb1=1024,Ab1=2048;var VT=3,a3=0,az=2,$w=1,qT=16,q50=["num","object","string","ascii"];q50[qT]="date";var ub1=[!1,!0,!0,!1,!1,!0,!0,!1],F50;try{new Function(""),F50=!0}catch(Z){}var QY,lb1=typeof Buffer!=="undefined",Yw,c7;try{Yw=new TextEncoder}catch(Z){}var yb1=lb1?function(Z,J,X){return Z.utf8Write(J,X,Z.byteLength-X)}:Yw&&Yw.encodeInto?function(Z,J,X){return Yw.encodeInto(J,Z.subarray(X)).written}:!1,lb6=Symbol("type"),yb6=Symbol("parent");v50(x50,ab1);function x50(Z,J,X,$,Y,Q,K,W){let G=W.typedStructs||(W.typedStructs=[]),z=J.dataView,v=(G.lastStringStart||100)+$,H=J.length-10,V=$;if($>H)J=Q($),z=J.dataView,$-=X,V-=X,v-=X,X=0,H=J.length-10;let q,F=v,x=G.transitions||(G.transitions=Object.create(null)),c=G.nextId||G.length,w=c<15?1:c<240?2:c<61440?3:c<15728640?4:0;if(w===0)return 0;$+=w;let B=[],j,L=0;for(let M in Z){let N=Z[M],P=x[M];if(!P)x[M]=P={key:M,parent:x,enumerationOffset:0,ascii0:null,ascii8:null,num8:null,string16:null,object16:null,num32:null,float64:null,date64:null};if($>H)J=Q($),z=J.dataView,$-=X,V-=X,v-=X,F-=X,X=0,H=J.length-10;switch(typeof N){case"number":let O=N;if(c<200||!P.num64){if(O>>0===O&&O<536870912&&O>-520093696){if(O<246&&O>=0&&(P.num8&&!(c>200&&P.num32)||O<32&&!P.num32))x=P.num8||j5(P,a3,1),J[$++]=O;else x=P.num32||j5(P,a3,4),z.setUint32($,O,!0),$+=4;break}else if(O<4294967296&&O>=-2147483648){if(z.setFloat32($,O,!0),ub1[J[$+3]>>>5]){let f;if((f=O*$Y[(J[$+3]&127)<<1|J[$+2]>>7])>>0===f){x=P.num32||j5(P,a3,4),$+=4;break}}}}x=P.num64||j5(P,a3,8),z.setFloat64($,O,!0),$+=8;break;case"string":let _=N.length;if(q=F-v,(_<<2)+F>H)J=Q((_<<2)+F),z=J.dataView,$-=X,V-=X,v-=X,F-=X,X=0,H=J.length-10;if(_>65280+q>>2){B.push(M,N,$-V);break}let k,h=F;if(_<64){let f,C,b;for(f=0;f<_;f++)if(C=N.charCodeAt(f),C<128)J[F++]=C;else if(C<2048)k=!0,J[F++]=C>>6|192,J[F++]=C&63|128;else if((C&64512)===55296&&((b=N.charCodeAt(f+1))&64512)===56320)k=!0,C=65536+((C&1023)<<10)+(b&1023),f++,J[F++]=C>>18|240,J[F++]=C>>12&63|128,J[F++]=C>>6&63|128,J[F++]=C&63|128;else k=!0,J[F++]=C>>12|224,J[F++]=C>>6&63|128,J[F++]=C&63|128}else F+=yb1(J,N,F),k=F-h>_;if(q<160||q<246&&(P.ascii8||P.string8)){if(k){if(!(x=P.string8))if(G.length>10&&(x=P.ascii8))x.__type=az,P.ascii8=null,P.string8=x,K(null,0,!0);else x=j5(P,az,1)}else if(q===0&&!j){j=!0,x=P.ascii0||j5(P,VT,0);break}else if(!(x=P.ascii8)&&!(G.length>10&&(x=P.string8)))x=j5(P,VT,1);J[$++]=q}else x=P.string16||j5(P,az,2),z.setUint16($,q,!0),$+=2;break;case"object":if(N){if(N.constructor===Date)x=P.date64||j5(P,qT,8),z.setFloat64($,N.getTime(),!0),$+=8;else B.push(M,N,L);break}else if(P=H50(P,$,z,-10),P)x=P,$=QY;else B.push(M,N,L);break;case"boolean":x=P.num8||P.ascii8||j5(P,a3,1),J[$++]=N?249:248;break;case"undefined":if(P=H50(P,$,z,-9),P)x=P,$=QY;else B.push(M,N,L);break;default:B.push(M,N,L)}L++}for(let M=0,N=B.length;M<N;){let P=B[M++],O=B[M++],_=B[M++],k=x[P];if(!k)x[P]=k={key:P,parent:x,enumerationOffset:_-L,ascii0:null,ascii8:null,num8:null,string16:null,object16:null,num32:null,float64:null};let h;if(O){let f;if(q=F-v,q<65280)if(x=k.object16,x)f=2;else if(x=k.object32)f=4;else x=j5(k,$w,2),f=2;else x=k.object32||j5(k,$w,4),f=4;if(h=K(O,F),typeof h==="object")F=h.position,z=h.targetView,J=h.target,v-=X,$-=X,V-=X,X=0;else F=h;if(f===2)z.setUint16($,q,!0),$+=2;else z.setUint32($,q,!0),$+=4}else x=k.object16||j5(k,$w,2),z.setInt16($,O===null?-10:-9,!0),$+=2;L++}let R=x[x7];if(R==null){R=W.typedStructs.length;let M=[],N=x,P,O;while((O=N.__type)!==void 0){let _=N.__size;N=N.__parent,P=N.key;let k=[O,_,P];if(N.enumerationOffset)k.push(N.enumerationOffset);M.push(k),N=N.parent}M.reverse(),x[x7]=R,W.typedStructs[R]=M,K(null,0,!0)}switch(w){case 1:if(R>=16)return 0;J[V]=R+32;break;case 2:if(R>=256)return 0;J[V]=56,J[V+1]=R;break;case 3:if(R>=65536)return 0;J[V]=57,z.setUint16(V+1,R,!0);break;case 4:if(R>=16777216)return 0;z.setUint32(V,(R<<8)+58,!0);break}if($<v){if(v===F)return $;J.copyWithin($,v,F),F+=$-v,G.lastStringStart=$-V}else if($>v){if(v===F)return $;return G.lastStringStart=$-V,x50(Z,J,X,V,Y,Q,K,W)}return F}function H50(Z,J,X,$){let Y;if(Y=Z.ascii8||Z.num8)return X.setInt8(J,$,!0),QY=J+1,Y;if(Y=Z.string16||Z.object16)return X.setInt16(J,$,!0),QY=J+2,Y;if(Y=Z.num32)return X.setUint32(J,3758096640+$,!0),QY=J+4,Y;if(Y=Z.num64)return X.setFloat64(J,NaN,!0),X.setInt8(J,$),QY=J+8,Y;QY=J;return}function j5(Z,J,X){let $=q50[J]+(X<<3),Y=Z[$]||(Z[$]=Object.create(null));return Y.__type=J,Y.__size=X,Y.__parent=Z,Y}function pb1(Z){if(!(Z instanceof Map))return Z;let J=Z.get("typed")||[];if(Object.isFrozen(J))J=J.map((Y)=>Y.slice(0));let X=Z.get("named"),$=Object.create(null);for(let Y=0,Q=J.length;Y<Q;Y++){let K=J[Y],W=$;for(let[G,z,v]of K){let H=W[v];if(!H)W[v]=H={key:v,parent:W,enumerationOffset:0,ascii0:null,ascii8:null,num8:null,string16:null,object16:null,num32:null,float64:null,date64:null};W=j5(H,G,z)}W[x7]=Y}return J.transitions=$,this.typedStructs=J,this.lastTypedStructuresLength=J.length,X}var HT=Symbol.for("source");function ib1(Z,J,X,$){let Y=Z[J++]-32;if(Y>=24)switch(Y){case 24:Y=Z[J++];break;case 25:Y=Z[J++]+(Z[J++]<<8);break;case 26:Y=Z[J++]+(Z[J++]<<8)+(Z[J++]<<16);break;case 27:Y=Z[J++]+(Z[J++]<<8)+(Z[J++]<<16)+(Z[J++]<<24);break}let Q=$.typedStructs&&$.typedStructs[Y];if(!Q){if(Z=Uint8Array.prototype.slice.call(Z,J,X),X-=J,J=0,!$.getStructures)throw new Error(`Reference to shared structure ${Y} without getStructures method`);if($._mergeStructures($.getStructures()),!$.typedStructs)throw new Error("Could not find any shared typed structures");if($.lastTypedStructuresLength=$.typedStructs.length,Q=$.typedStructs[Y],!Q)throw new Error("Could not find typed structure "+Y)}var{construct:K,fullConstruct:W}=Q;if(!K){K=Q.construct=function q(){},W=Q.fullConstruct=function q(){},W.prototype=$.structPrototype??{};var G=K.prototype=$.structPrototype?Object.create($.structPrototype):{};let v=[],H=0,V;for(let q=0,F=Q.length;q<F;q++){let x=Q[q],[c,w,B,j]=x;if(B==="__proto__")B="__proto_";let L={key:B,offset:H};if(j)v.splice(q+j,0,L);else v.push(L);let R;switch(w){case 0:R=()=>0;break;case 1:R=(N,P)=>{let O=N.bytes[P+L.offset];return O>=246?d3(O):O};break;case 2:R=(N,P)=>{let O=N.bytes,k=(O.dataView||(O.dataView=new DataView(O.buffer,O.byteOffset,O.byteLength))).getUint16(P+L.offset,!0);return k>=65280?d3(k&255):k};break;case 4:R=(N,P)=>{let O=N.bytes,k=(O.dataView||(O.dataView=new DataView(O.buffer,O.byteOffset,O.byteLength))).getUint32(P+L.offset,!0);return k>=4294967040?d3(k&255):k};break}L.getRef=R,H+=w;let M;switch(c){case VT:if(V&&!V.next)V.next=L;V=L,L.multiGetCount=0,M=function(N){let{bytes:P,position:O}=N,_=H+O,k=R(N,O);if(typeof k!=="number")return k;let h,f=L.next;while(f){if(h=f.getRef(N,O),typeof h==="number")break;else h=null;f=f.next}if(h==null)h=N.bytesEnd-_;if(N.srcString)return N.srcString.slice(k,h);return t60(P,k+_,h-k)};break;case az:case $w:if(V&&!V.next)V.next=L;V=L,M=function(N){let P=N.position,O=H+P,_=R(N,P);if(typeof _!=="number")return _;let k=N.bytes,h,f=L.next;while(f){if(h=f.getRef(N,P),typeof h==="number")break;else h=null;f=f.next}if(h==null)h=N.bytesEnd-O;if(c===az)return k.toString("utf8",_+O,h+O);else{c7=N;try{return $.unpack(k,{start:_+O,end:h+O})}finally{c7=null}}};break;case a3:switch(w){case 4:M=function(N){let P=N.bytes,O=P.dataView||(P.dataView=new DataView(P.buffer,P.byteOffset,P.byteLength)),_=N.position+L.offset,k=O.getInt32(_,!0);if(k<536870912){if(k>-520093696)return k;if(k>-536870912)return d3(k&255)}let h=O.getFloat32(_,!0),f=$Y[(P[_+3]&127)<<1|P[_+2]>>7];return(f*h+(h>0?0.5:-0.5)>>0)/f};break;case 8:M=function(N){let P=N.bytes,_=(P.dataView||(P.dataView=new DataView(P.buffer,P.byteOffset,P.byteLength))).getFloat64(N.position+L.offset,!0);if(isNaN(_)){let k=P[N.position+L.offset];if(k>=246)return d3(k)}return _};break;case 1:M=function(N){let O=N.bytes[N.position+L.offset];return O<246?O:d3(O)};break}break;case qT:M=function(N){let P=N.bytes,O=P.dataView||(P.dataView=new DataView(P.buffer,P.byteOffset,P.byteLength));return new Date(O.getFloat64(N.position+L.offset,!0))};break}L.get=M}if(F50){let q=[],F=[],x=0,c;for(let B of v){if($.alwaysLazyProperty&&$.alwaysLazyProperty(B.key)){c=!0;continue}Object.defineProperty(G,B.key,{get:gb1(B.get),enumerable:!0});let j="v"+x++;F.push(j),q.push("o["+JSON.stringify(B.key)+"]="+j+"(s)")}if(c)q.push("__proto__:this");let w=new Function(...F,"var c=this;return function(s){var o=new c();"+q.join(";")+";return o;}").apply(W,v.map((B)=>B.get));Object.defineProperty(G,"toJSON",{value(B){return w.call(this,this[HT])}})}else Object.defineProperty(G,"toJSON",{value(q){let F={};for(let x=0,c=v.length;x<c;x++){let w=v[x].key;F[w]=this[w]}return F}})}var z=new K;return z[HT]={bytes:Z,position:J,srcString:"",bytesEnd:X},z}function d3(Z){switch(Z){case 246:return null;case 247:return;case 248:return!1;case 249:return!0}throw new Error("Unknown constant")}function gb1(Z){return function(){return Z(this[HT])}}function db1(){if(c7)c7.bytes=Uint8Array.prototype.slice.call(c7.bytes,c7.position,c7.bytesEnd),c7.position=0,c7.bytesEnd=c7.bytes.length}function ab1(Z,J){if(J.typedStructs){let $=new Map;$.set("named",Z),$.set("typed",J.typedStructs),Z=$}let X=J.lastTypedStructuresLength||0;return Z.isCompatible=($)=>{let Y=!0;if($ instanceof Map){if(($.get("named")||[]).length!==(J.lastNamedStructuresLength||0))Y=!1;if(($.get("typed")||[]).length!==X)Y=!1}else if($ instanceof Array||Array.isArray($)){if($.length!==(J.lastNamedStructuresLength||0))Y=!1}if(!Y)J._mergeStructures($);return Y},J.lastTypedStructuresLength=J.typedStructs&&J.typedStructs.length,Z}$50(ib1,pb1,db1);var ob1=process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED!==void 0&&process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED.toLowerCase()==="true";if(!ob1){let Z;try{if(Z=g("msgpackr-extract"),Z)r60(Z.extractStrings)}catch(J){}}var YU=t(WY0(),1);import Ua1 from"http";import Ba1 from"https";import $U from"fs";import ja1 from"path";import La1 from"url";var GY0=`-----BEGIN CERTIFICATE-----
405
+ }`});try{let $=(await J.next()).value?.data?.userById;if(!$)return p.warning(`PlatformGateway.getPlayerCosmetics(): No cosmetic data returned for user id "${Z}".`);let Y=$.equippedItems.map((W)=>({slot:W.slot,item:W.item.slots.find((G)=>G.type===W.slot)})).filter((W)=>!!W.item),Q=Number($.characterSettings?.hairStyle?.split("_")[1]||1),K=`https://d3qkovarww0lj1.cloudfront.net/?skin_tone=${$.characterSettings?.skinTone||"SKIN_COLOR_1"}&clothing=${$.characterSettings?.clothing||"CLOTHING_1"}&hair_style=${$.characterSettings?.hairStyle||"HAIR_STYLE_1"}&hair_color=${$.characterSettings?.hairColor||"HAIR_COLOR_1"}&eye_color=${$.characterSettings?.eyeColor||"00FF00"}`;return{equippedItems:Y,hairStyle:Q,skinTextureUri:K}}finally{await J.return?.()}}async getPlayerSession(Z){if(!this._creativeGateway)return;return await this._creativeGateway.getSession(Z)}async setData(Z,J){if(J.error)return p.warning("PlatformGateway.setData(): Cannot set data with an error property.");if(!this._creativeGateway&&process.env.NODE_ENV==="production")return p.warning("PlatformGateway.setData(): You are running in production mode, but the Platform Gateway is not initialized! No data will be set.");return this._creativeGateway?await this._creativeGateway.kv.set(Z,J):this._writeDevDataLocally(Z,J)}_readDevDataLocally(Z){try{if(!t$.existsSync(kz))return{error:{code:"keyNotFound",message:"Local data directory not found."}};let J=D80.join(kz,`${Z}.json`);return JSON.parse(t$.readFileSync(J,"utf8"))}catch(J){return p.warning(`PlatformGateway._readDevDataLocally(): Failed to read data for key "${Z}": ${J}`),{error:{code:"gatewayError",message:"Failed to read data for key."}}}}_writeDevDataLocally(Z,J){try{if(!t$.existsSync(kz))t$.mkdirSync(kz,{recursive:!0});let X=D80.join(kz,`${Z}.json`),$={};if(t$.existsSync(X))$=JSON.parse(t$.readFileSync(X,"utf8"));let Y={...$,...J};t$.writeFileSync(X,JSON.stringify(Y,null,2),"utf8")}catch(X){p.warning(`PlatformGateway._writeDevDataLocally(): Failed to write data for key "${Z}": ${X}`)}}}class e${static instance=new e$;constructor(){}async getGlobalData(Z,J=3){for(let X=0;X<=J;X++){let $=await O4.instance.getData(Z);if($&&!$.error)return $;if($.error.code==="keyNotFound")return{};if(X<J)p.warning(`PersistenceManager.getGlobalData(): Failed to get global data, retrying. Response: ${JSON.stringify($)}`),await new Promise((Y)=>setTimeout(Y,500))}p.warning(`PersistenceManager.getGlobalData(): Failed to get global data after ${J} attempts.`);return}async getPlayerData(Z,J=3){for(let X=0;X<=J;X++){let $=await O4.instance.getData(this._getPlayerKey(Z));if($&&!$.error)return $;if($.error.code==="keyNotFound")return{};if(X<J)p.warning(`PersistenceManager.getPlayerData(): Failed to get player data, retrying. Response: ${JSON.stringify($)}`),await new Promise((Y)=>setTimeout(Y,500))}p.warning(`PersistenceManager.getPlayerData(): Failed to get player data after ${J} attempts.`);return}async setGlobalData(Z,J){let X=await O4.instance.setData(Z,J);if(!X||X.error){if(X?.error)p.warning(`PersistenceManager.setGlobalData(): ${X.error.message}`);return}return X}async setPlayerData(Z,J){let X=await O4.instance.setData(this._getPlayerKey(Z),J);if(!X||X.error){if(X?.error)p.warning(`PersistenceManager.setPlayerData(): ${X.error.message}`);return}return X}_getPlayerKey(Z){return`player-${Z.id}`}}var R80;(($)=>{$[$.FIRST_PERSON=0]="FIRST_PERSON";$[$.THIRD_PERSON=1]="THIRD_PERSON";$[$.SPECTATOR=2]="SPECTATOR"})(R80||={});var uP;((x)=>{x.LOOK_AT_ENTITY="PLAYER_CAMERA.LOOK_AT_ENTITY";x.LOOK_AT_POSITION="PLAYER_CAMERA.LOOK_AT_POSITION";x.SET_ATTACHED_TO_ENTITY="PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY";x.SET_ATTACHED_TO_POSITION="PLAYER_CAMERA.SET_ATTACHED_TO_POSITION";x.SET_FILM_OFFSET="PLAYER_CAMERA.SET_FILM_OFFSET";x.SET_FORWARD_OFFSET="PLAYER_CAMERA.SET_FORWARD_OFFSET";x.SET_FOV="PLAYER_CAMERA.SET_FOV";x.SET_MODEL_HIDDEN_NODES="PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES";x.SET_MODEL_SHOWN_NODES="PLAYER_CAMERA.SET_MODEL_SHOWN_NODES";x.SET_MODE="PLAYER_CAMERA.SET_MODE";x.SET_OFFSET="PLAYER_CAMERA.SET_OFFSET";x.SET_SHOULDER_ANGLE="PLAYER_CAMERA.SET_SHOULDER_ANGLE";x.SET_TRACKED_ENTITY="PLAYER_CAMERA.SET_TRACKED_ENTITY";x.SET_TRACKED_POSITION="PLAYER_CAMERA.SET_TRACKED_POSITION";x.SET_ZOOM="PLAYER_CAMERA.SET_ZOOM"})(uP||={});class Ez extends B0{player;_attachedToEntity;_attachedToPosition;_filmOffset=0;_forwardOffset=0;_fov=75;_modelHiddenNodes=new Set;_modelShownNodes=new Set;_mode=1;_offset={x:0,y:0,z:0};_orientation={pitch:0,yaw:0};_shoulderAngle=0;_trackedEntity;_trackedPosition;_zoom=1;constructor(Z){super();this.player=Z}get attachedToEntity(){return this._attachedToEntity}get attachedToPosition(){return this._attachedToPosition}get facingDirection(){return{x:-Math.sin(this._orientation.yaw)*Math.cos(this._orientation.pitch),y:Math.sin(this._orientation.pitch),z:-Math.cos(this._orientation.yaw)*Math.cos(this._orientation.pitch)}}get facingQuaternion(){let Z=this._orientation.pitch*0.5,J=this._orientation.yaw*0.5,X=Math.cos(Z),$=Math.sin(Z),Y=Math.cos(J),Q=Math.sin(J);return{x:$*Y,y:X*Q,z:-$*Q,w:X*Y}}get filmOffset(){return this._filmOffset}get forwardOffset(){return this._forwardOffset}get fov(){return this._fov}get modelHiddenNodes(){return this._modelHiddenNodes}get modelShownNodes(){return this._modelShownNodes}get mode(){return this._mode}get offset(){return this._offset}get orientation(){return this._orientation}get shoulderAngle(){return this._shoulderAngle}get trackedEntity(){return this._trackedEntity}get trackedPosition(){return this._trackedPosition}get zoom(){return this._zoom}lookAtEntity(Z){if(!this._requirePlayerWorld("lookAtEntity"))return;this.emitWithWorld(this.player.world,"PLAYER_CAMERA.LOOK_AT_ENTITY",{playerCamera:this,entity:Z})}lookAtPosition(Z){if(!this._requirePlayerWorld("lookAtPosition"))return;this.emitWithWorld(this.player.world,"PLAYER_CAMERA.LOOK_AT_POSITION",{playerCamera:this,position:Z})}reset(){this._attachedToEntity=void 0,this._attachedToPosition=void 0,this._orientation={pitch:0,yaw:0},this._trackedEntity=void 0,this._trackedPosition=void 0}setAttachedToEntity(Z){if(!this._requirePlayerWorld("setAttachedToEntity"))return;if(!Z.isSpawned)return p.error(`PlayerCamera.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);this._attachedToEntity=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY",{playerCamera:this,entity:Z})}setAttachedToPosition(Z){if(!this._requirePlayerWorld("setAttachedToPosition"))return;this._attachedToPosition=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_ATTACHED_TO_POSITION",{playerCamera:this,position:Z})}setFilmOffset(Z){if(!this._requirePlayerWorld("setFilmOffset"))return;this._filmOffset=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_FILM_OFFSET",{playerCamera:this,filmOffset:Z})}setForwardOffset(Z){if(!this._requirePlayerWorld("setForwardOffset"))return;this._forwardOffset=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_FORWARD_OFFSET",{playerCamera:this,forwardOffset:Z})}setFov(Z){if(!this._requirePlayerWorld("setFov"))return;this._fov=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_FOV",{playerCamera:this,fov:Z})}setModelHiddenNodes(Z){if(!this._requirePlayerWorld("setModelHiddenNodes"))return;this._modelHiddenNodes=new Set(Z.map((J)=>J.toLowerCase())),this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES",{playerCamera:this,modelHiddenNodes:this._modelHiddenNodes})}setModelShownNodes(Z){if(!this._requirePlayerWorld("setModelShownNodes"))return;this._modelShownNodes=new Set(Z.map((J)=>J.toLowerCase())),this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_MODEL_SHOWN_NODES",{playerCamera:this,modelShownNodes:this._modelShownNodes})}setMode(Z){if(!this._requirePlayerWorld("setMode"))return;this._mode=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_MODE",{playerCamera:this,mode:Z})}setOffset(Z){if(!this._requirePlayerWorld("setOffset"))return;this._offset=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_OFFSET",{playerCamera:this,offset:Z})}setOrientationPitch(Z){this._orientation.pitch=Z}setOrientationYaw(Z){this._orientation.yaw=Z}setShoulderAngle(Z){if(!this._requirePlayerWorld("setShoulderAngle"))return;this._shoulderAngle=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_SHOULDER_ANGLE",{playerCamera:this,shoulderAngle:Z})}setTrackedEntity(Z){if(!this._requirePlayerWorld("setTrackedEntity"))return;this._trackedEntity=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_TRACKED_ENTITY",{playerCamera:this,entity:Z})}setTrackedPosition(Z){if(!this._requirePlayerWorld("setTrackedPosition"))return;this._trackedPosition=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_TRACKED_POSITION",{playerCamera:this,position:Z})}setZoom(Z){if(!this._requirePlayerWorld("setZoom"))return;this._zoom=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_ZOOM",{playerCamera:this,zoom:Z})}serialize(){return T0.serializePlayerCamera(this)}_requirePlayerWorld(Z){if(!this.player.world)p.error(`PlayerCamera._requirePlayerWorld(): Player ${this.player.id} is not in a world, invoked method: ${Z}()`);return!!this.player.world}}var gc;((Y)=>{Y.DATA="PLAYER_UI.DATA";Y.LOAD="PLAYER_UI.LOAD";Y.LOCK_POINTER="PLAYER_UI.LOCK_POINTER";Y.SEND_DATA="PLAYER_UI.SEND_DATA"})(gc||={});class Iz extends B0{player;constructor(Z){super();this.player=Z}load(Z){if(!this.player.world)return;this.emitWithWorld(this.player.world,"PLAYER_UI.LOAD",{playerUI:this,htmlUri:Z})}lockPointer(Z){if(!this.player.world)return;this.emitWithWorld(this.player.world,"PLAYER_UI.LOCK_POINTER",{playerUI:this,lock:Z})}sendData(Z){if(!this.player.world)return;this.emitWithWorld(this.player.world,"PLAYER_UI.SEND_DATA",{playerUI:this,data:Z})}}var N80=["w","a","s","d","sp","sh","tb","ml","mr","q","e","r","f","z","x","c","v","u","i","o","j","k","l","n","m","1","2","3","4","5","6","7","8","9","0"],_z;((Q)=>{Q.CHAT_MESSAGE_SEND="PLAYER.CHAT_MESSAGE_SEND";Q.JOINED_WORLD="PLAYER.JOINED_WORLD";Q.LEFT_WORLD="PLAYER.LEFT_WORLD";Q.RECONNECTED_WORLD="PLAYER.RECONNECTED_WORLD";Q.REQUEST_SYNC="PLAYER.REQUEST_SYNC"})(_z||={});class g3 extends B0{static _devNextPlayerId=1;id;username;profilePictureUrl;camera;connection;cosmetics;ui;_input={};_lastUnreliableInputSequenceNumber=0;_persistedData;_world;_worldSwitched=!1;constructor(Z,J){super();this.id=J?.user.id??`player-${g3._devNextPlayerId++}`,this.username=J?.user.username??this.id,this.profilePictureUrl=J?.user.profilePictureURL??void 0,this.camera=new Ez(this),this.connection=Z,this.cosmetics=O4.instance.getPlayerCosmetics(this.id),this.ui=new Iz(this),Z.onPacket(Y0.PacketId.CHAT_MESSAGE_SEND,this._onChatMessageSendPacket),Z.onPacket(Y0.PacketId.DEBUG_CONFIG,this._onDebugConfigPacket),Z.onPacket(Y0.PacketId.INPUT,this._onInputPacket),Z.onPacket(Y0.PacketId.SYNC_REQUEST,this._onSyncRequestPacket),Z.onPacket(Y0.PacketId.UI_DATA_SEND,this._onUIDataSendPacket)}get input(){return this._input}get world(){return this._world}disconnect(){this._leaveWorld(),this.connection.disconnect()}getPersistedData(){return this._persistedData}joinWorld(Z){if(this._world===Z)return;if(!this._world)this._world=Z,this.emitWithWorld(this._world,"PLAYER.JOINED_WORLD",{player:this,world:this._world});else{for(let J of this._world.entityManager.getPlayerEntitiesByPlayer(this))if(J.isSpawned)J.despawn();this.disconnect(),this._world=Z,this._worldSwitched=!0}}async loadInitialPersistedData(){if(this._persistedData)return;this._persistedData=await e$.instance.getPlayerData(this)}reconnected(){if(!this._world)return;if(this._lastUnreliableInputSequenceNumber=0,!this._worldSwitched)this.emitWithWorld(this._world,"PLAYER.RECONNECTED_WORLD",{player:this,world:this._world});else this._worldSwitched=!1,this.emitWithWorld(this._world,"PLAYER.JOINED_WORLD",{player:this,world:this._world})}resetInputs(){this._input={}}setPersistedData(Z){return this._persistedData={...this._persistedData,...Z},e$.instance.setPlayerData(this,Z).catch((J)=>{}),this._persistedData}serialize(){return T0.serializePlayer(this)}_leaveWorld(){if(!this._world)return;this.emitWithWorld(this._world,"PLAYER.LEFT_WORLD",{player:this,world:this._world}),this._world=void 0}_onChatMessageSendPacket=(Z)=>{if(!this._world)return;let J=Z[1].m;if(this._world.chatManager.handleCommand(this,J)){this._world.chatManager.sendPlayerMessage(this,`Command Entered: ${J}`,"CCCCCC");return}if(this.id.startsWith("guest")){this._world.chatManager.sendPlayerMessage(this,"You need to create a HYTOPIA account to send messages in chat.","FFAA00");return}this.emitWithWorld(this._world,"PLAYER.CHAT_MESSAGE_SEND",{player:this,message:J})};_onDebugConfigPacket=(Z)=>{console.log(Z)};_onInputPacket=(Z)=>{let J=Z[1];if(J.sq!==void 0){if(J.sq<this._lastUnreliableInputSequenceNumber)return;this._lastUnreliableInputSequenceNumber=J.sq}if(N80.forEach((X)=>{let $=X;if(J[$]!==void 0)this._input[$]=Boolean(J[$])}),J.cp!==void 0)this.camera.setOrientationPitch(J.cp);if(J.cy!==void 0)this.camera.setOrientationYaw(J.cy)};_onSyncRequestPacket=()=>{if(this._world)this.emitWithWorld(this._world,"PLAYER.REQUEST_SYNC",{player:this,receivedAt:Date.now(),receivedAtMs:performance.now()})};_onUIDataSendPacket=(Z)=>{this.ui.emit("PLAYER_UI.DATA",{playerUI:this.ui,data:Z[1]})}}var lP;((X)=>{X.BROADCAST_MESSAGE="CHAT.BROADCAST_MESSAGE";X.PLAYER_MESSAGE="CHAT.PLAYER_MESSAGE"})(lP||={});class bz extends B0{_commandCallbacks={};_world;constructor(Z){super();this._world=Z,this._subscribeToPlayerEvents()}registerCommand(Z,J){this._commandCallbacks[Z]=J}unregisterCommand(Z){delete this._commandCallbacks[Z]}sendBroadcastMessage(Z,J){this._sendBroadcastMessage(void 0,Z,J)}handleCommand(Z,J){let[X,...$]=J.split(" "),Y=this._commandCallbacks[X];if(Y)return Y(Z,$,J),!0;return!1}sendPlayerMessage(Z,J,X){this.emitWithWorld(this._world,"CHAT.PLAYER_MESSAGE",{player:Z,message:J,color:X})}_subscribeToPlayerEvents(){this._world.on("PLAYER.CHAT_MESSAGE_SEND",(Z)=>{let{player:J,message:X}=Z;this._sendBroadcastMessage(J,X)})}_sendBroadcastMessage(Z,J,X){this.emitWithWorld(this._world,"CHAT.BROADCAST_MESSAGE",{player:Z,message:J,color:X})}}var y5=16,yP=y5-1,dI1=y5**3;class p5{_blocks;_originCoordinate;constructor(Z){this._blocks=new Uint8Array(dI1),this._originCoordinate=Z}get blocks(){return this._blocks}get originCoordinate(){return this._originCoordinate}static blockIndexToLocalCoordinate(Z){return{x:Z%y5,y:(Z/y5|0)%y5,z:Z/(y5*y5)|0}}static globalCoordinateToLocalCoordinate(Z){return{x:Z.x&y5-1,y:Z.y&y5-1,z:Z.z&y5-1}}static globalCoordinateToOriginCoordinate(Z){return{x:Z.x&~(y5-1),y:Z.y&~(y5-1),z:Z.z&~(y5-1)}}getBlockId(Z){return this._blocks[this._getIndex(Z)]}hasBlock(Z){return this._blocks[this._getIndex(Z)]!==0}setBlock(Z,J){if(!this._isValidLocalCoordinate(Z))return p.error("Chunk.setBlock(): Block local coordinate is out of bounds");let X=this._getIndex(Z);this._blocks[X]=J}serialize(){return T0.serializeChunk(this)}_getIndex(Z){return Z.x+(Z.y<<4)+(Z.z<<8)}_isValidLocalCoordinate(Z){return Z.x>=0&&Z.x<=yP&&Z.y>=0&&Z.y<=yP&&Z.z>=0&&Z.z<=yP}}var pP;(($)=>{$.ADD_CHUNK="CHUNK_LATTICE.ADD_CHUNK";$.REMOVE_CHUNK="CHUNK_LATTICE.REMOVE_CHUNK";$.SET_BLOCK="CHUNK_LATTICE.SET_BLOCK"})(pP||={});class hz extends B0{_blockTypeColliders=new Map;_blockTypeCounts=new Map;_chunks=new Map;_rigidBody;_world;constructor(Z){super();this._world=Z}get chunkCount(){return this._chunks.size}clear(){for(let Z of this._blockTypeColliders.values())this._world.simulation.colliderMap.removeColliderBlockType(Z),Z.removeFromSimulation();this._chunks.forEach((Z)=>{this.emitWithWorld(this._world,"CHUNK_LATTICE.REMOVE_CHUNK",{chunkLattice:this,chunk:Z})}),this._blockTypeColliders.clear(),this._blockTypeCounts.clear(),this._chunks.clear()}getBlockId(Z){let J=this.getChunk(p5.globalCoordinateToOriginCoordinate(Z));if(!J)return 0;return J.getBlockId(p5.globalCoordinateToLocalCoordinate(Z))}getBlockTypeCollider(Z){return this._blockTypeColliders.get(Z)}getBlockType(Z){let J=this.getBlockId(Z);return J?this._world.blockTypeRegistry.getBlockType(J):null}getBlockTypeCount(Z){return this._blockTypeCounts.get(Z)??0}getChunk(Z){return this._chunks.get(this._getChunkKey(p5.globalCoordinateToOriginCoordinate(Z)))}getOrCreateBlockTypeCollider(Z,J){let X=this._blockTypeColliders.get(Z);if(X)return X;let Y=this._world.blockTypeRegistry.getBlockType(Z).createCollider(J);return this._blockTypeColliders.set(Z,Y),Y}getOrCreateChunk(Z){let J=p5.globalCoordinateToOriginCoordinate(Z),X=this._chunks.get(this._getChunkKey(J));if(X)return X;return X=new p5(J),this._chunks.set(this._getChunkKey(J),X),this.emitWithWorld(this._world,"CHUNK_LATTICE.ADD_CHUNK",{chunkLattice:this,chunk:X}),X}getAllChunks(){return Array.from(this._chunks.values())}hasBlock(Z){let J=this.getChunk(p5.globalCoordinateToOriginCoordinate(Z));if(!J)return!1;return J.hasBlock(p5.globalCoordinateToLocalCoordinate(Z))}hasChunk(Z){let J=p5.globalCoordinateToOriginCoordinate(Z);return this._chunks.has(this._getChunkKey(J))}setBlock(Z,J){let X=p5.globalCoordinateToLocalCoordinate(Z),$=this.getOrCreateChunk(Z),Y=$.getBlockId(X);if(Y===J)return;if($.setBlock(X,J),!this._rigidBody)this._rigidBody=new u$({type:"fixed"}),this._rigidBody.addToSimulation(this._world.simulation);if(Y!==0){let Q=Math.max(0,(this._blockTypeCounts.get(Y)??0)-1),K=this.getBlockTypeCollider(Y);if(K)if(Q===0)this._world.simulation.colliderMap.removeColliderBlockType(K),K.removeFromSimulation(),this._blockTypeColliders.delete(Y);else K.setVoxel(Z,!1),this._propagateVoxelChange(K,Z);this._blockTypeCounts.set(Y,Q)}if(J!==0){let Q=(this._blockTypeCounts.get(J)??0)+1,K=this.getOrCreateBlockTypeCollider(J,[Z]);if(Q===1){let W=this._world.blockTypeRegistry.getBlockType(J);K.addToSimulation(this._world.simulation,this._rigidBody),this._world.simulation.colliderMap.setColliderBlockType(K,W),this._combineVoxelStates(K)}else K.setVoxel(Z,!0),this._propagateVoxelChange(K,Z);this._blockTypeCounts.set(J,Q)}this.emitWithWorld(this._world,"CHUNK_LATTICE.SET_BLOCK",{chunkLattice:this,chunk:$,globalCoordinate:Z,localCoordinate:X,blockTypeId:J})}_combineVoxelStates(Z){if(Z.isSensor)return;for(let J of this._blockTypeColliders.values()){if(J===Z||J.isSensor)continue;Z.combineVoxelStates(J)}}_getChunkKey(Z){return`${Z.x},${Z.y},${Z.z}`}_propagateVoxelChange(Z,J){if(Z.isSensor)return;for(let X of this._blockTypeColliders.values()){if(X===Z||X.isSensor)continue;Z.propagateVoxelChange(X,J)}}}class Sz{_colliderHandleBlockTypeMap=new Map;_colliderHandleCollisionCallbackMap=new Map;_colliderHandleEntityMap=new Map;_cleanupBlockTypeColliderHandles=new Set;_pendingCleanupBlockTypeColliderHandles=new Set;_cleanupCollisionCallbackColliderHandles=new Set;_pendingCleanupCollisionCallbackColliderHandles=new Set;_cleanupEntityColliderHandles=new Set;_pendingCleanupEntityColliderHandles=new Set;getColliderBlockType(Z){if(!this._requireSimulatedCollider(Z))return;return this._colliderHandleBlockTypeMap.get(Z.rawCollider.handle)}getColliderCollisionCallback(Z){if(!this._requireSimulatedCollider(Z))return;return this._colliderHandleCollisionCallbackMap.get(Z.rawCollider.handle)}getColliderEntity(Z){if(!this._requireSimulatedCollider(Z))return;return this._colliderHandleEntityMap.get(Z.rawCollider.handle)}getColliderHandleBlockType(Z){return this._colliderHandleBlockTypeMap.get(Z)}getColliderHandleCollisionCallback(Z){return this._colliderHandleCollisionCallbackMap.get(Z)}getColliderHandleEntity(Z){return this._colliderHandleEntityMap.get(Z)}removeColliderBlockType(Z){if(!this._requireSimulatedCollider(Z))return;this.removeColliderHandleBlockType(Z.rawCollider.handle)}removeColliderCollisionCallback(Z){if(!this._requireSimulatedCollider(Z))return;this.removeColliderHandleCollisionCallback(Z.rawCollider.handle)}removeColliderEntity(Z){if(!this._requireSimulatedCollider(Z))return;this.removeColliderHandleEntity(Z.rawCollider.handle)}removeColliderHandleBlockType(Z){this._colliderHandleBlockTypeMap.delete(Z)}removeColliderHandleCollisionCallback(Z){this._colliderHandleCollisionCallbackMap.delete(Z)}removeColliderHandleEntity(Z){this._colliderHandleEntityMap.delete(Z)}setColliderBlockType(Z,J){if(!this._requireSimulatedCollider(Z))return;this.setColliderHandleBlockType(Z.rawCollider.handle,J)}setColliderCollisionCallback(Z,J){if(!this._requireSimulatedCollider(Z))return;this.setColliderHandleCollisionCallback(Z.rawCollider.handle,J)}setColliderEntity(Z,J){if(!this._requireSimulatedCollider(Z))return;this.setColliderHandleEntity(Z.rawCollider.handle,J)}setColliderHandleBlockType(Z,J){this._colliderHandleBlockTypeMap.set(Z,J),this._cleanupBlockTypeColliderHandles.delete(Z),this._pendingCleanupBlockTypeColliderHandles.delete(Z)}setColliderHandleCollisionCallback(Z,J){this._colliderHandleCollisionCallbackMap.set(Z,J),this._cleanupCollisionCallbackColliderHandles.delete(Z),this._pendingCleanupCollisionCallbackColliderHandles.delete(Z)}setColliderHandleEntity(Z,J){this._colliderHandleEntityMap.set(Z,J),this._cleanupEntityColliderHandles.delete(Z),this._pendingCleanupEntityColliderHandles.delete(Z)}queueColliderHandleForCleanup(Z){if(this._colliderHandleBlockTypeMap.has(Z))this._pendingCleanupBlockTypeColliderHandles.add(Z);if(this._colliderHandleCollisionCallbackMap.has(Z))this._pendingCleanupCollisionCallbackColliderHandles.add(Z);if(this._colliderHandleEntityMap.has(Z))this._pendingCleanupEntityColliderHandles.add(Z)}cleanup(){for(let Z of this._cleanupBlockTypeColliderHandles)this._colliderHandleBlockTypeMap.delete(Z);if(this._cleanupBlockTypeColliderHandles.size>0)this._cleanupBlockTypeColliderHandles.clear();for(let Z of this._cleanupCollisionCallbackColliderHandles)this._colliderHandleCollisionCallbackMap.delete(Z);if(this._cleanupCollisionCallbackColliderHandles.size>0)this._cleanupCollisionCallbackColliderHandles.clear();for(let Z of this._cleanupEntityColliderHandles)this._colliderHandleEntityMap.delete(Z);if(this._cleanupEntityColliderHandles.size>0)this._cleanupEntityColliderHandles.clear();for(let Z of this._pendingCleanupBlockTypeColliderHandles)this._cleanupBlockTypeColliderHandles.add(Z);if(this._pendingCleanupBlockTypeColliderHandles.size>0)this._pendingCleanupBlockTypeColliderHandles.clear();for(let Z of this._pendingCleanupCollisionCallbackColliderHandles)this._cleanupCollisionCallbackColliderHandles.add(Z);if(this._pendingCleanupCollisionCallbackColliderHandles.size>0)this._pendingCleanupCollisionCallbackColliderHandles.clear();for(let Z of this._pendingCleanupEntityColliderHandles)this._cleanupEntityColliderHandles.add(Z);if(this._pendingCleanupEntityColliderHandles.size>0)this._pendingCleanupEntityColliderHandles.clear()}_requireSimulatedCollider(Z){if(!Z.rawCollider)p.error("ColliderMap._requireSimulatedCollider(): Collider is not in the simulation.");return!!Z.rawCollider}}var O80={type:"dynamic",softCcdPrediction:1},P80=0.015625,T80=Math.cos(0.026),Az;((L)=>{L.BLOCK_COLLISION="ENTITY.BLOCK_COLLISION";L.BLOCK_CONTACT_FORCE="ENTITY.BLOCK_CONTACT_FORCE";L.DESPAWN="ENTITY.DESPAWN";L.ENTITY_COLLISION="ENTITY.ENTITY_COLLISION";L.ENTITY_CONTACT_FORCE="ENTITY.ENTITY_CONTACT_FORCE";L.SET_MODEL_ANIMATIONS_PLAYBACK_RATE="ENTITY.SET_MODEL_ANIMATIONS_PLAYBACK_RATE";L.SET_MODEL_HIDDEN_NODES="ENTITY.SET_MODEL_HIDDEN_NODES";L.SET_MODEL_SCALE="ENTITY.SET_MODEL_SCALE";L.SET_MODEL_SHOWN_NODES="ENTITY.SET_MODEL_SHOWN_NODES";L.SET_MODEL_TEXTURE_URI="ENTITY.SET_MODEL_TEXTURE_URI";L.SET_OPACITY="ENTITY.SET_OPACITY";L.SET_PARENT="ENTITY.SET_PARENT";L.SET_TINT_COLOR="ENTITY.SET_TINT_COLOR";L.SPAWN="ENTITY.SPAWN";L.START_MODEL_LOOPED_ANIMATIONS="ENTITY.START_MODEL_LOOPED_ANIMATIONS";L.START_MODEL_ONESHOT_ANIMATIONS="ENTITY.START_MODEL_ONESHOT_ANIMATIONS";L.STOP_MODEL_ANIMATIONS="ENTITY.STOP_MODEL_ANIMATIONS";L.TICK="ENTITY.TICK";L.UPDATE_POSITION="ENTITY.UPDATE_POSITION";L.UPDATE_ROTATION="ENTITY.UPDATE_ROTATION"})(Az||={});class j8 extends u${_id;_blockHalfExtents;_blockTextureUri;_controller;_isEnvironmental=!1;_modelAnimationsPlaybackRate=1;_modelHiddenNodes=new Set;_modelLoopedAnimations=new Set;_modelOneshotAnimations=new Set;_modelPreferredShape;_modelScale=1;_modelShownNodes=new Set;_modelTextureUri;_modelUri;_name;_opacity;_parent;_parentNodeName;_tag;_tintColor;_lastUpdatedPosition={x:0,y:0,z:0};_lastUpdatedRotation={x:0,y:0,z:0,w:1};_lastParentlessType="dynamic";_world;_positionUpdateThresholdSq;_rotationUpdateThreshold;constructor(Z){let J="blockTextureUri"in Z,X="modelUri"in Z;if(!J===!X)p.fatalError("Entity.constructor(): Entity data must include a blockTextureUri or modelUri, but not both.");if(J&&!Z.blockHalfExtents)p.fatalError("Entity.constructor(): Block entity must have blockHalfExtents!");if(Z.parent&&!Z.parent.isSpawned)p.fatalError("Entity.constructor(): Parent entity must be spawned before child entity!");if(Z.parent?.modelUri&&Z.parentNodeName&&!j6.instance.modelHasNode(Z.parent.modelUri,Z.parentNodeName))p.fatalError(`Entity.constructor(): Parent node name ${Z.parentNodeName} not found in parent model ${Z.parent.modelUri}!`);super(Z.rigidBodyOptions??O80);if(J)this._blockHalfExtents=Z.blockHalfExtents,this._blockTextureUri=Z.blockTextureUri;if(X)this._modelAnimationsPlaybackRate=Z.modelAnimationsPlaybackRate??1,this._modelPreferredShape=Z.modelPreferredShape,this._modelScale=Z.modelScale??1,this._modelTextureUri=Z.modelTextureUri,this._modelUri=Z.modelUri,Z.modelHiddenNodes?.forEach(($)=>this._modelHiddenNodes.add($.toLowerCase())),Z.modelLoopedAnimations?.forEach(($)=>this._modelLoopedAnimations.add($)),Z.modelShownNodes?.forEach(($)=>this._modelShownNodes.add($.toLowerCase()));if(this._isEnvironmental=Z.isEnvironmental??!1,this._name=Z.name??"Nameless",this._opacity=Z.opacity??1,this._parent=Z.parent,this._parentNodeName=Z.parentNodeName,this._tag=Z.tag,this._tintColor=Z.tintColor,this._positionUpdateThresholdSq=P80,this._rotationUpdateThreshold=T80,Z.controller)this.setController(Z.controller)}get id(){return this._id}get blockHalfExtents(){return this._blockHalfExtents}get blockTextureUri(){return this._blockTextureUri}get controller(){return this._controller}get depth(){return this.isModelEntity?j6.instance.getDepth(this._modelUri)*(this._modelScale??1):this._blockHalfExtents.z*2}get height(){return this.isModelEntity?j6.instance.getHeight(this._modelUri)*(this._modelScale??1):this._blockHalfExtents.y*2}get modelAnimationsPlaybackRate(){return this._modelAnimationsPlaybackRate}get modelHiddenNodes(){return this._modelHiddenNodes}get modelLoopedAnimations(){return this._modelLoopedAnimations}get modelPreferredShape(){return this._modelPreferredShape}get modelScale(){return this._modelScale}get modelShownNodes(){return this._modelShownNodes}get modelTextureUri(){return this._modelTextureUri}get modelUri(){return this._modelUri}get name(){return this._name}get opacity(){return this._opacity}get parent(){return this._parent}get parentNodeName(){return this._parentNodeName}get tag(){return this._tag}get tintColor(){return this._tintColor}get isBlockEntity(){return!!this._blockTextureUri}get isEnvironmental(){return this._isEnvironmental}get isModelEntity(){return!!this._modelUri}get isSpawned(){return!!this._world}get width(){return this.isModelEntity?j6.instance.getWidth(this._modelUri)*(this._modelScale??1):this._blockHalfExtents.x*2}get world(){return this._world}spawn(Z,J,X){if(this.isSpawned)return p.error(`Entity.spawn(): Entity ${this._name} is already spawned with id ${this._id}!`);if(!this.isSimulated)this.addToSimulation(Z.simulation);if(this._blockTextureUri&&this._blockHalfExtents&&this.numColliders===0)this.addChildColliderToSimulation(new S5(S5.optionsFromBlockHalfExtents(this._blockHalfExtents)));if(this._modelUri&&this.numColliders===0&&this._modelPreferredShape!=="none")this.addChildColliderToSimulation(new S5(S5.optionsFromModelUri(this._modelUri,this._modelScale,this._modelPreferredShape)));if(this.colliders.forEach(($)=>{if(this.hasListeners("ENTITY.BLOCK_COLLISION")||this.hasListeners("ENTITY.ENTITY_COLLISION"))$.enableCollisionEvents(!0);if(this.hasListeners("ENTITY.BLOCK_CONTACT_FORCE")||this.hasListeners("ENTITY.ENTITY_CONTACT_FORCE"))$.enableContactForceEvents(!0);if(v9.isDefaultCollisionGroups($.collisionGroups)){let Y=this.isEnvironmental?[8]:[$.isSensor?4:2],Q=this.isEnvironmental?[65535&~8&~1]:[65535];$.setCollisionGroups({belongsTo:Y,collidesWith:Q})}}),this.setPosition(J),X)this.setRotation(X);if(this._id=Z.entityManager.registerEntity(this),this._world=Z,this._controller)this._controller.spawn(this);if(this._parent)this.setParent(this._parent,this._parentNodeName,J,X);this.colliders.forEach(($)=>{Z.simulation.colliderMap.setColliderEntity($,this)}),this.emitWithWorld(Z,"ENTITY.SPAWN",{entity:this})}despawn(){if(!this._requireSpawned("despawn"))return;if(this._world.entityManager.getEntityChildren(this).forEach((Z)=>{Z.despawn()}),this._controller)this._controller.detach(this),this._controller.despawn(this);if(this.emitWithWorld(this._world,"ENTITY.DESPAWN",{entity:this}),this.isSimulated)this.removeFromSimulation();this._world.entityManager.unregisterEntity(this),this._world.audioManager.unregisterEntityAttachedAudios(this),this._world.lightManager.despawnEntityAttachedLights(this),this._world.particleEmitterManager.despawnEntityAttachedParticleEmitters(this),this._world.sceneUIManager.unloadEntityAttachedSceneUIs(this),this._id=void 0,this._world=void 0}setController(Z){if(this._controller===Z)return;if(this._controller)this._controller.detach(this);if(this._controller=Z,this._controller)this._controller.attach(this)}setModelAnimationsPlaybackRate(Z){if(!this._requireSpawned("setModelAnimationsPlaybackRate"))return;if(!this.isModelEntity||this._modelAnimationsPlaybackRate===Z)return;this._modelAnimationsPlaybackRate=Z,this.emitWithWorld(this._world,"ENTITY.SET_MODEL_ANIMATIONS_PLAYBACK_RATE",{entity:this,playbackRate:Z})}setModelHiddenNodes(Z){if(!this._requireSpawned("setModelHiddenNodes"))return;if(!this.isModelEntity)return;this._modelHiddenNodes=new Set(Z.map((J)=>J.toLowerCase())),this.emitWithWorld(this._world,"ENTITY.SET_MODEL_HIDDEN_NODES",{entity:this,modelHiddenNodes:this._modelHiddenNodes})}setModelScale(Z){if(!this._requireSpawned("setModelScale"))return;if(!this.isModelEntity||this._modelScale===Z)return;let J=Z/this._modelScale;this._modelScale=Z,this.colliders.forEach((X)=>X.scale(J)),this.emitWithWorld(this._world,"ENTITY.SET_MODEL_SCALE",{entity:this,modelScale:Z})}setModelShownNodes(Z){if(!this._requireSpawned("setModelShownNodes"))return;if(!this.isModelEntity)return;this._modelShownNodes=new Set(Z.map((J)=>J.toLowerCase())),this.emitWithWorld(this._world,"ENTITY.SET_MODEL_SHOWN_NODES",{entity:this,modelShownNodes:this._modelShownNodes})}setModelTextureUri(Z){if(!this._requireSpawned("setModelTextureUri"))return;if(!this.isModelEntity||this._modelTextureUri===Z)return;this._modelTextureUri=Z,this.emitWithWorld(this._world,"ENTITY.SET_MODEL_TEXTURE_URI",{entity:this,modelTextureUri:Z})}setOpacity(Z){if(!this._requireSpawned("setOpacity"))return;if(this._opacity===Z)return;this._opacity=Z,this.emitWithWorld(this._world,"ENTITY.SET_OPACITY",{entity:this,opacity:Z})}setParent(Z,J,X,$){if(!this._requireSpawned("setParent"))return;if(Z&&!Z.isSpawned)return p.error("Entity.setParent(): Parent entity is not spawned, cannot set parent!");if(!this._parent&&Z)this._lastParentlessType=this.type;if(this._parent=Z,this._parentNodeName=J,this.colliders.forEach((Y)=>Y.setEnabled(!Z)),this.setType(!Z?this._lastParentlessType:"kinematic_velocity"),this.setPosition(X??{x:0,y:0,z:0}),this.setRotation($??{x:0,y:0,z:0,w:1}),!this.isKinematicPositionBased)this.resetAngularVelocity(),this.resetForces(),this.resetLinearVelocity(),this.resetTorques();this.emitWithWorld(this._world,"ENTITY.SET_PARENT",{entity:this,parent:Z,parentNodeName:J})}setTintColor(Z){if(!this._requireSpawned("setTintColor"))return;if(!Z&&!this._tintColor||Z&&this._tintColor&&Z.r===this._tintColor.r&&Z.g===this._tintColor.g&&Z.b===this._tintColor.b)return;this._tintColor=Z,this.emitWithWorld(this._world,"ENTITY.SET_TINT_COLOR",{entity:this,tintColor:Z})}startModelLoopedAnimations(Z){if(!this._requireSpawned("startModelLoopedAnimations"))return;if(!this.isModelEntity||!Z.length)return;if(!Z.some((J)=>!this._modelLoopedAnimations.has(J)))return;Z.forEach((J)=>{this._modelLoopedAnimations.add(J)}),this.emitWithWorld(this._world,"ENTITY.START_MODEL_LOOPED_ANIMATIONS",{entity:this,animations:new Set(Z)})}startModelOneshotAnimations(Z){if(!this._requireSpawned("startModelOneshotAnimations"))return;if(!this.isModelEntity||!Z.length)return;Z.forEach((J)=>{this._modelOneshotAnimations.add(J)}),this.emitWithWorld(this._world,"ENTITY.START_MODEL_ONESHOT_ANIMATIONS",{entity:this,animations:new Set(Z)})}stopAllModelAnimations(Z=[]){if(!this._requireSpawned("stopAllModelAnimations"))return;this._stopAnimationsFromSets([this._modelLoopedAnimations,this._modelOneshotAnimations],Z)}stopAllModelLoopedAnimations(Z=[]){if(!this._requireSpawned("stopAllModelLoopedAnimations"))return;this._stopAnimationsFromSets([this._modelLoopedAnimations],Z)}stopAllModelOneshotAnimations(Z=[]){if(!this._requireSpawned("stopAllModelOneshotAnimations"))return;this._stopAnimationsFromSets([this._modelOneshotAnimations],Z)}stopModelAnimations(Z){if(!this._requireSpawned("stopModelAnimations"))return;if(!this.isModelEntity||!Z.length)return;if(!Z.some((J)=>this._modelLoopedAnimations.has(J))&&!Z.some((J)=>this._modelOneshotAnimations.has(J)))return;Z.forEach((J)=>{this._modelLoopedAnimations.delete(J),this._modelOneshotAnimations.delete(J)}),this.emitWithWorld(this._world,"ENTITY.STOP_MODEL_ANIMATIONS",{entity:this,animations:new Set(Z)})}serialize(){return T0.serializeEntity(this)}tick(Z){if(this.emit("ENTITY.TICK",{entity:this,tickDeltaMs:Z}),this._controller)this._controller.tick(this,Z)}checkAndEmitUpdates(){if(!this._requireSpawned("checkAndEmitUpdates"))return;let Z=this.position,J=this.rotation;if(this._rotationExceedsThreshold(J,this._lastUpdatedRotation))this._lastUpdatedRotation=J,this.emitWithWorld(this._world,"ENTITY.UPDATE_ROTATION",{entity:this,rotation:J});if(this._positionExceedsThreshold(Z,this._lastUpdatedPosition))this._lastUpdatedPosition=Z,this.emitWithWorld(this._world,"ENTITY.UPDATE_POSITION",{entity:this,position:Z})}_positionExceedsThreshold(Z,J){let X=Z.x-J.x,$=Z.y-J.y,Y=Z.z-J.z;return X*X+$*$+Y*Y>this._positionUpdateThresholdSq}_requireSpawned(Z){if(!this.isSpawned)p.error(`Entity._requireSpawned(): Entity ${this._name} is not spawned, cannot invoke ${Z}()!`);return this.isSpawned}_rotationExceedsThreshold(Z,J){return Math.abs(Z.x*J.x+Z.y*J.y+Z.z*J.z+Z.w*J.w)<this._rotationUpdateThreshold}_stopAnimationsFromSets(Z,J=[]){if(!this.isModelEntity)return;let X=new Set(J),$=[];for(let Y of Z)for(let Q of Y)if(!X.has(Q))$.push(Q);if($.length>0)this.stopModelAnimations($)}}class b1 extends x${static BASE_ENTITY_HEIGHT=1.5;static GROUND_SENSOR_HEIGHT_SCALE=0.125;static GROUND_SENSOR_RADIUS_SCALE=0.23;static JUMP_LAND_HEAVY_VELOCITY_THRESHOLD=-12;static WALL_COLLIDER_HEIGHT_SCALE=0.33;static WALL_COLLIDER_RADIUS_SCALE=0.4;static MOVEMENT_ROTATIONS={wa:Math.PI/4,wd:-Math.PI/4,sa:Math.PI-Math.PI/4,sd:Math.PI+Math.PI/4,s:Math.PI,asd:Math.PI,a:Math.PI/2,d:-Math.PI/2};static EXTERNAL_IMPULSE_DECAY_RATE=0.253;static SWIM_UPWARD_COOLDOWN_MS=600;static SWIMMING_DRAG_FACTOR=0.05;static WATER_ENTRY_SINKING_FACTOR=0.8;static WATER_ENTRY_SINKING_MS=250;applyDirectionalMovementRotations=!0;autoCancelMouseLeftClick=!0;canJump=()=>!0;canRun=()=>!0;canSwim=()=>!0;canWalk=()=>!0;faceForwardOnStop=!0;idleLoopedAnimations=["idle-upper","idle-lower"];interactOneshotAnimations=["simple-interact"];jumpLandHeavyOneshotAnimations=["jump-post-heavy"];jumpLandLightOneshotAnimations=["jump-post-light"];jumpOneshotAnimations=["jump-loop"];jumpVelocity=10;runLoopedAnimations=["run-upper","run-lower"];runVelocity=8;sticksToPlatforms=!0;swimFastVelocity=5;swimGravity=0;swimIdleLoopedAnimations=["swim-idle"];swimLoopedAnimations=["swim-forward"];swimMaxGravityVelocity=-1;swimSlowVelocity=3;swimUpwardVelocity=2;walkLoopedAnimations=["walk-upper","walk-lower"];walkVelocity=4;_externalVelocity={x:0,y:0,z:0};_magnitudeYTracker=0;_groundContactCount=0;_internalApplyImpulse=()=>{};_isActivelyMoving=!1;_isFullySubmerged=!1;_justSubmergedUntil=0;_liquidContactCount=0;_platform;_reusableImpulse={x:0,y:0,z:0};_reusablePlatformVelocity={x:0,y:0,z:0};_reusableTargetVelocities={x:0,y:0,z:0};_reusableVelocityClamp={x:0,y:0,z:0};_stepAudio;_swimUpwardCooldownAt=0;constructor(Z={}){super();this.applyDirectionalMovementRotations=Z.applyDirectionalMovementRotations??this.applyDirectionalMovementRotations,this.autoCancelMouseLeftClick=Z.autoCancelMouseLeftClick??this.autoCancelMouseLeftClick,this.faceForwardOnStop=Z.faceForwardOnStop??this.faceForwardOnStop,this.sticksToPlatforms=Z.sticksToPlatforms??this.sticksToPlatforms,this.canJump=Z.canJump??this.canJump,this.canRun=Z.canRun??this.canRun,this.canSwim=Z.canSwim??this.canSwim,this.canWalk=Z.canWalk??this.canWalk,this.jumpVelocity=Z.jumpVelocity??this.jumpVelocity,this.runVelocity=Z.runVelocity??this.runVelocity,this.walkVelocity=Z.walkVelocity??this.walkVelocity,this.swimFastVelocity=Z.swimFastVelocity??this.swimFastVelocity,this.swimSlowVelocity=Z.swimSlowVelocity??this.swimSlowVelocity,this.swimUpwardVelocity=Z.swimUpwardVelocity??this.swimUpwardVelocity,this.swimGravity=Z.swimGravity??this.swimGravity,this.swimMaxGravityVelocity=Z.swimMaxGravityVelocity??this.swimMaxGravityVelocity,this.idleLoopedAnimations=Z.idleLoopedAnimations??this.idleLoopedAnimations,this.interactOneshotAnimations=Z.interactOneshotAnimations??this.interactOneshotAnimations,this.jumpOneshotAnimations=Z.jumpOneshotAnimations??this.jumpOneshotAnimations,this.jumpLandHeavyOneshotAnimations=Z.jumpLandHeavyOneshotAnimations??this.jumpLandHeavyOneshotAnimations,this.jumpLandLightOneshotAnimations=Z.jumpLandLightOneshotAnimations??this.jumpLandLightOneshotAnimations,this.runLoopedAnimations=Z.runLoopedAnimations??this.runLoopedAnimations,this.swimLoopedAnimations=Z.swimLoopedAnimations??this.swimLoopedAnimations,this.swimIdleLoopedAnimations=Z.swimIdleLoopedAnimations??this.swimIdleLoopedAnimations,this.walkLoopedAnimations=Z.walkLoopedAnimations??this.walkLoopedAnimations}get isActivelyMoving(){return this._isActivelyMoving}get isGrounded(){return this._groundContactCount>0}get isOnPlatform(){return!!this._platform}get isSwimming(){return this._liquidContactCount>0}get platform(){return this._platform}attach(Z){super.attach(Z),this._internalApplyImpulse=Z.applyImpulse.bind(Z),Z.applyImpulse=(J)=>{let X=Z.mass||1;this._externalVelocity.x+=J.x/X,this._externalVelocity.y+=J.y/X,this._externalVelocity.z+=J.z/X},this._stepAudio=new RW({uri:"audio/sfx/step/stone/stone-step-04.mp3",loop:!0,volume:0.1,referenceDistance:2,cutoffDistance:15,attachedToEntity:Z}),Z.setCcdEnabled(!0),Z.lockAllRotations(),Z.on("ENTITY.BLOCK_COLLISION",({blockType:J,started:X})=>{if(!J.isLiquid||!this.canSwim(this))return;if(this._liquidContactCount<=0&&X){let $=Z.linearVelocity;Z.setLinearVelocity({x:$.x*this.swimGravity,y:$.y*this.swimGravity,z:$.z*this.swimGravity})}if(this._liquidContactCount+=X?1:-1,this._liquidContactCount>0)Z.setGravityScale(this.swimGravity),Z.stopAllModelLoopedAnimations(this.swimLoopedAnimations),this._swimUpwardCooldownAt=performance.now()+b1.SWIM_UPWARD_COOLDOWN_MS;else Z.setGravityScale(1),Z.stopModelAnimations(this.swimLoopedAnimations)})}spawn(Z){if(!Z.isSpawned)return p.error("DefaultPlayerEntityController.spawn(): Entity is not spawned!");Z.createAndAddChildCollider({shape:"cylinder",radius:b1.GROUND_SENSOR_RADIUS_SCALE*(Z.height/b1.BASE_ENTITY_HEIGHT),halfHeight:b1.GROUND_SENSOR_HEIGHT_SCALE*(Z.height/b1.BASE_ENTITY_HEIGHT),collisionGroups:{belongsTo:[4],collidesWith:[1,2,8]},isSensor:!0,relativePosition:{x:0,y:-Z.height/2,z:0},tag:"groundSensor",onCollision:(J,X)=>{if(!Z.isSpawned)return;if(!(J instanceof A5)||!J.isLiquid){if(X&&this._groundContactCount===0&&Z.linearVelocity.y<-1)if(Z.linearVelocity.y<b1.JUMP_LAND_HEAVY_VELOCITY_THRESHOLD)Z.startModelOneshotAnimations(this.jumpLandHeavyOneshotAnimations);else Z.startModelOneshotAnimations(this.jumpLandLightOneshotAnimations);this._groundContactCount+=X?1:-1}if(!this._groundContactCount&&!this.isSwimming)Z.startModelOneshotAnimations(this.jumpOneshotAnimations);else Z.stopModelAnimations(this.jumpOneshotAnimations);if(!(J instanceof j8))return;if(X&&this.sticksToPlatforms)this._platform=J;else if(J===this._platform&&!X)this._platform=void 0}}),Z.createAndAddChildCollider({shape:"capsule",halfHeight:b1.WALL_COLLIDER_HEIGHT_SCALE*(Z.height/b1.BASE_ENTITY_HEIGHT),radius:b1.WALL_COLLIDER_RADIUS_SCALE*(Z.height/b1.BASE_ENTITY_HEIGHT),collisionGroups:{belongsTo:[4],collidesWith:[1,2,8]},friction:0,frictionCombineRule:1,tag:"wallCollider"})}tickWithPlayerInput(Z,J,X,$){if(!Z.isSpawned||!Z.world)return;if(super.tickWithPlayerInput(Z,J,X,$),Z.parent)return;let{w:Y,a:Q,s:K,d:W,c:G,sp:z,sh:v,ml:H}=J,{yaw:V}=X,q=Z.linearVelocity;this._reusableTargetVelocities.x=0,this._reusableTargetVelocities.y=0,this._reusableTargetVelocities.z=0,this._isActivelyMoving=!!(Y||Q||K||W);let F=v,x=Q&&W&&!Y&&!K||Y&&K&&!Q&&!W,c=F&&this.canRun(this)||!F&&this.canWalk(this);if(this.isSwimming&&!this._isFullySubmerged)this._isFullySubmerged=!0,this._justSubmergedUntil=performance.now()+b1.WATER_ENTRY_SINKING_MS;else if(!this.isSwimming)this._isFullySubmerged=!1,this._justSubmergedUntil=0;if(this.isGrounded&&!this.isSwimming&&this._isActivelyMoving&&!x&&c){let M=F?this.runLoopedAnimations:this.walkLoopedAnimations;Z.stopAllModelLoopedAnimations(M),Z.startModelLoopedAnimations(M),this._stepAudio?.setPlaybackRate(F?0.75:0.51),this._stepAudio?.play(Z.world,!this._stepAudio?.isPlaying)}else if(this._isFullySubmerged&&this.canSwim(this))if(this._stepAudio?.pause(),this._isActivelyMoving)Z.stopAllModelLoopedAnimations(this.swimLoopedAnimations),Z.startModelLoopedAnimations(this.swimLoopedAnimations);else Z.stopAllModelLoopedAnimations(this.swimIdleLoopedAnimations),Z.startModelLoopedAnimations(this.swimIdleLoopedAnimations);else this._stepAudio?.pause(),Z.stopAllModelLoopedAnimations(this.idleLoopedAnimations),Z.startModelLoopedAnimations(this.idleLoopedAnimations);let w;if(this.applyDirectionalMovementRotations&&c){if(Y&&Q&&!W&&!K)w=b1.MOVEMENT_ROTATIONS.wa;else if(Y&&W&&!Q&&!K)w=b1.MOVEMENT_ROTATIONS.wd;else if(K&&Q&&!Y&&!W)w=b1.MOVEMENT_ROTATIONS.sa;else if(K&&W&&!Y&&!Q)w=b1.MOVEMENT_ROTATIONS.sd;else if(K&&!Y&&!Q&&!W||Q&&K&&W&&!Y)w=b1.MOVEMENT_ROTATIONS.s;else if(Q&&!Y&&!K&&!W)w=b1.MOVEMENT_ROTATIONS.a;else if(W&&!Y&&!Q&&!K)w=b1.MOVEMENT_ROTATIONS.d}if(H)Z.startModelOneshotAnimations(this.interactOneshotAnimations),J.ml=!this.autoCancelMouseLeftClick;if(c){let M=!this.isSwimming?F?this.runVelocity:this.walkVelocity:F?this.swimFastVelocity:this.swimSlowVelocity,N=Math.sin(V),P=Math.cos(V);if(Y)this._reusableTargetVelocities.x-=M*N,this._reusableTargetVelocities.z-=M*P;if(K)this._reusableTargetVelocities.x+=M*N,this._reusableTargetVelocities.z+=M*P;if(Q)this._reusableTargetVelocities.x-=M*P,this._reusableTargetVelocities.z+=M*N;if(W)this._reusableTargetVelocities.x+=M*P,this._reusableTargetVelocities.z-=M*N;let O=Math.sqrt(this._reusableTargetVelocities.x*this._reusableTargetVelocities.x+this._reusableTargetVelocities.z*this._reusableTargetVelocities.z);if(O>M){let _=M/O;this._reusableTargetVelocities.x*=_,this._reusableTargetVelocities.z*=_}}if(this.isSwimming){if(q.y<this.swimMaxGravityVelocity)this._reusableVelocityClamp.x=q.x,this._reusableVelocityClamp.y=this.swimMaxGravityVelocity,this._reusableVelocityClamp.z=q.z,Z.setLinearVelocity(this._reusableVelocityClamp);if(q.y>this.swimUpwardVelocity*2)this._reusableVelocityClamp.x=q.x,this._reusableVelocityClamp.y=this.swimUpwardVelocity*2,this._reusableVelocityClamp.z=q.z,Z.setLinearVelocity(this._reusableVelocityClamp);if(G)this._reusableTargetVelocities.y=-this.swimUpwardVelocity;else if(performance.now()<this._justSubmergedUntil)this._reusableTargetVelocities.y=-this.swimUpwardVelocity*b1.WATER_ENTRY_SINKING_FACTOR;else if(!z)this._reusableTargetVelocities.y=-q.y*b1.SWIMMING_DRAG_FACTOR}if(z&&this.canJump(this)){if(this.isGrounded&&!this.isSwimming&&q.y>-0.001&&q.y<=3)this._reusableTargetVelocities.y=this.jumpVelocity;else if(this.isSwimming&&performance.now()>this._swimUpwardCooldownAt)this._reusableTargetVelocities.y=this.swimUpwardVelocity}let B=this._platform?.linearVelocity??this._reusablePlatformVelocity;if(this._externalVelocity.y!==0)this._magnitudeYTracker+=this._externalVelocity.y;if(this._externalVelocity.x!==0||this._externalVelocity.y!==0||this._externalVelocity.z!==0){if(this.isGrounded){let M=Math.sqrt(this._externalVelocity.x*this._externalVelocity.x+this._magnitudeYTracker*this._magnitudeYTracker+this._externalVelocity.z*this._externalVelocity.z);if(M>0.01){let P=Math.max(0,M-b1.EXTERNAL_IMPULSE_DECAY_RATE)/M;this._externalVelocity.x*=P,this._magnitudeYTracker*=P,this._externalVelocity.z*=P}else this._externalVelocity.x=0,this._externalVelocity.y=0,this._magnitudeYTracker=0,this._externalVelocity.z=0}}let j=this._reusableTargetVelocities.x+this._externalVelocity.x-q.x+B.x,L=this._reusableTargetVelocities.y+this._externalVelocity.y+B.y,R=this._reusableTargetVelocities.z+this._externalVelocity.z-q.z+B.z;if(this._externalVelocity.y=0,j!==0||L!==0||R!==0){let M=Z.mass;this._reusableImpulse.x=j*M,this._reusableImpulse.y=L*M,this._reusableImpulse.z=R*M,this._internalApplyImpulse(this._reusableImpulse)}if(V!==void 0&&(this.faceForwardOnStop||this.isActivelyMoving)){let N=(w!==void 0?V+w:V)*0.5;Z.setRotation({x:0,y:Math.sin(N),z:0,w:Math.cos(N)})}}}var iP;((W)=>{W.LOAD="SCENE_UI.LOAD";W.SET_ATTACHED_TO_ENTITY="SCENE_UI.SET_ATTACHED_TO_ENTITY";W.SET_OFFSET="SCENE_UI.SET_OFFSET";W.SET_POSITION="SCENE_UI.SET_POSITION";W.SET_STATE="SCENE_UI.SET_STATE";W.SET_VIEW_DISTANCE="SCENE_UI.SET_VIEW_DISTANCE";W.UNLOAD="SCENE_UI.UNLOAD"})(iP||={});class mz extends B0{_id;_attachedToEntity;_offset;_position;_state={};_templateId;_viewDistance;_world;constructor(Z){if(!!Z.attachedToEntity===!!Z.position)p.fatalError("Either attachedToEntity or position must be set, but not both");super();this._attachedToEntity=Z.attachedToEntity,this._offset=Z.offset,this._position=Z.position,this._state=Z.state??{},this._templateId=Z.templateId,this._viewDistance=Z.viewDistance}get id(){return this._id}get attachedToEntity(){return this._attachedToEntity}get isLoaded(){return this._id!==void 0}get offset(){return this._offset}get position(){return this._position}get state(){return this._state}get templateId(){return this._templateId}get viewDistance(){return this._viewDistance}get world(){return this._world}load(Z){if(this.isLoaded)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return p.error(`SceneUI.load(): Attached entity ${this._attachedToEntity.id} must be spawned before loading SceneUI!`);this._id=Z.sceneUIManager.registerSceneUI(this),this._world=Z,this.emitWithWorld(Z,"SCENE_UI.LOAD",{sceneUI:this})}setAttachedToEntity(Z){if(!Z.isSpawned)return p.error(`SceneUI.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);if(this._attachedToEntity===Z)return;if(this._attachedToEntity=Z,this._position=void 0,this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_ATTACHED_TO_ENTITY",{sceneUI:this,entity:Z})}setOffset(Z){if(this._offset===Z)return;if(this._offset=Z,this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_OFFSET",{sceneUI:this,offset:Z})}setPosition(Z){if(this._position===Z)return;if(this._attachedToEntity=void 0,this._position=Z,this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_POSITION",{sceneUI:this,position:Z})}setState(Z){if(this._state={...this._state,...Z},this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_STATE",{sceneUI:this,state:this._state})}setViewDistance(Z){if(this._viewDistance=Z,this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_VIEW_DISTANCE",{sceneUI:this,viewDistance:Z})}unload(){if(!this.isLoaded||!this._world)return;this._world.sceneUIManager.unregisterSceneUI(this),this.emitWithWorld(this._world,"SCENE_UI.UNLOAD",{sceneUI:this}),this._id=void 0,this._world=void 0}serialize(){return T0.serializeSceneUI(this)}}var C80=0.010000000000000002,f80=Math.cos(0.026);class F7 extends j8{player;nametagSceneUI;constructor(Z){super(Z);this._positionUpdateThresholdSq=C80,this._rotationUpdateThreshold=f80,this.player=Z.player,this.nametagSceneUI=new mz({templateId:"hytopia:nametag",attachedToEntity:this,offset:{x:0,y:1,z:0},viewDistance:15,state:{username:this.player.username,profilePictureUrl:this.player.profilePictureUrl}})}spawn(Z,J,X){super.spawn(Z,J,X),this.nametagSceneUI.load(Z),this.player.on("PLAYER.CHAT_MESSAGE_SEND",({message:$})=>{this.nametagSceneUI.setState({chat:$})})}tick(Z){if(!this.isSpawned||!this.world)return;if(!this.controller)return p.error(`PlayerEntity.tick(): PlayerEntity "${this.name}" must have a controller.`);let{input:J,camera:X}=this.player;this.controller.tickWithPlayerInput(this,J,X.orientation,Z),super.tick(Z)}}var k80="models/players/player.gltf",aI1={BACK:"back-anchor",HEAD:"head-anchor",LEFT_ARM:"arm-left-anchor",LEFT_FOOT:"foot-left-anchor",LEFT_HAND:"hand-left-anchor",LEFT_ITEM:"hand-left-anchor",LEFT_LEG:"leg-left-anchor",RIGHT_ARM:"arm-right-anchor",RIGHT_FOOT:"foot-right-anchor",RIGHT_HAND:"hand-right-anchor",RIGHT_ITEM:"hand-right-anchor",RIGHT_LEG:"leg-right-anchor",TORSO:"torso-anchor"};class gP extends F7{_cosmeticHiddenSlots;constructor(Z){super({modelUri:k80,modelLoopedAnimations:["idle_lower","idle_upper"],modelHiddenNodes:["hair-"],modelShownNodes:["hair-0003"],...Z});if(this._cosmeticHiddenSlots=Z.cosmeticHiddenSlots??[],!Z.controller)this.setController(new b1)}get cosmeticHiddenSlots(){return this._cosmeticHiddenSlots}spawn(Z,J,X){super.spawn(Z,J,X),this.player.cosmetics.then(($)=>{if(!$||!this.modelUri)return;let Y=this.modelShownNodes.values().toArray().filter((W)=>!W.includes("hair-"));if(!($.equippedItems.some((W)=>W.item.flags.includes("HIDES_HAIR"))&&!this._cosmeticHiddenSlots.includes("ALL")&&!this._cosmeticHiddenSlots.includes("HEAD")))Y.push(`hair-${String($.hairStyle).padStart(4,"0")}`);if(this.setModelShownNodes(Y),this.modelUri===k80)this.setModelTextureUri($.skinTextureUri);if(this._cosmeticHiddenSlots.includes("ALL"))return;let K=[];for(let W of $.equippedItems){let{item:G,slot:z}=W;if(this._cosmeticHiddenSlots.includes(z))continue;let v=aI1[z];if(!v||!j6.instance.modelHasNode(this.modelUri,v))continue;if(G.flags.includes("REPLACES_LIMB")){let V=v.split("-").slice(0,-1).join("-");K.push(`${V}-clothing`,`${V}-geometry`)}new j8({modelUri:G.modelUrl,modelPreferredShape:"none",parent:this,parentNodeName:v}).spawn(Z,{x:0,y:0,z:0})}if(K.length>0)this.setModelHiddenNodes([...this.modelHiddenNodes.values().toArray(),...K])}).catch(($)=>p.warning(`DefaultPlayerEntity.spawn(): Failed to get player cosmetics: ${$}`))}}class uz{_activeEntities=new Set;_entities=new Map;_nextEntityId=1;_world;constructor(Z){this._world=Z}get entityCount(){return this._entities.size}get world(){return this._world}registerEntity(Z){if(Z.id!==void 0)p.fatalError(`EntityManager.registerEntity(): Entity ${Z.name} is already assigned the id ${Z.id}!`);let J=this._nextEntityId;if(this._entities.set(J,Z),this._nextEntityId++,!Z.isEnvironmental)this._activeEntities.add(Z);return J}unregisterEntity(Z){if(Z.id===void 0)return p.error(`EntityManager.unregisterEntity(): Entity ${Z.name} is not assigned an id!`);if(this._entities.delete(Z.id),!Z.isEnvironmental)this._activeEntities.delete(Z)}getAllEntities(){return Array.from(this._entities.values())}getAllPlayerEntities(){let Z=[];return this._entities.forEach((J)=>{if(J instanceof F7)Z.push(J)}),Z}getPlayerEntitiesByPlayer(Z){let J=[];return this._entities.forEach((X)=>{if(X instanceof F7&&X.player===Z)J.push(X)}),J}getEntity(Z){return this._entities.get(Z)}getEntitiesByTag(Z){let J=[];return this._entities.forEach((X)=>{if(X.tag===Z)J.push(X)}),J}getEntitiesByTagSubstring(Z){let J=[];return this._entities.forEach((X)=>{if(X.tag?.includes(Z))J.push(X)}),J}getEntityChildren(Z){let J=[];return this._entities.forEach((X)=>{if(X.parent===Z)J.push(X)}),J}tickEntities(Z){for(let J of this._activeEntities)J.tick(Z)}checkAndEmitUpdates(){for(let Z of this._activeEntities)Z.checkAndEmitUpdates()}}import{gzipSync as gJ6}from"zlib";var d6=t(b60(),1),Ub6=d6.default.v1,Bb6=d6.default.v1ToV6,jb6=d6.default.v3,h60=d6.default.v4,Lb6=d6.default.v5,Db6=d6.default.v6,Mb6=d6.default.v6ToV1,Rb6=d6.default.v7,Nb6=d6.default.NIL,Ob6=d6.default.MAX,Pb6=d6.default.version,Tb6=d6.default.validate,Cb6=d6.default.stringify,fb6=d6.default.parse;var eP;try{eP=new TextDecoder}catch(Z){}var X0,g5,m=0;var $T=[],JY=$T,pz=0,f1={},Y1,_Z,i5=0,P4=0,S8,bZ,B5=[],e0,S60={useRecords:!1,mapsAsObjects:!0};class ec{}var YT=new ec;YT.name="MessagePack 0xC1";var $X=!1,g60=2,ZT,JT,XT;try{new Function("")}catch(Z){g60=1/0}class hZ{constructor(Z){if(Z){if(Z.useRecords===!1&&Z.mapsAsObjects===void 0)Z.mapsAsObjects=!0;if(Z.sequential&&Z.trusted!==!1){if(Z.trusted=!0,!Z.structures&&Z.useRecords!=!1){if(Z.structures=[],!Z.maxSharedStructures)Z.maxSharedStructures=0}}if(Z.structures)Z.structures.sharedLength=Z.structures.length;else if(Z.getStructures)(Z.structures=[]).uninitialized=!0,Z.structures.sharedLength=0;if(Z.int64AsNumber)Z.int64AsType="number"}Object.assign(this,Z)}unpack(Z,J){if(X0)return X50(()=>{return tc(),this?this.unpack(Z,J):hZ.prototype.unpack.call(S60,Z,J)});if(!Z.buffer&&Z.constructor===ArrayBuffer)Z=typeof Buffer!=="undefined"?Buffer.from(Z):new Uint8Array(Z);if(typeof J==="object")g5=J.end||Z.length,m=J.start||0;else m=0,g5=J>-1?J:Z.length;pz=0,P4=0,_Z=null,JY=$T,S8=null,X0=Z;try{e0=Z.dataView||(Z.dataView=new DataView(Z.buffer,Z.byteOffset,Z.byteLength))}catch(X){if(X0=null,Z instanceof Uint8Array)throw X;throw new Error("Source must be a Uint8Array or Buffer but was a "+(Z&&typeof Z=="object"?Z.constructor.name:typeof Z))}if(this instanceof hZ){if(f1=this,this.structures)return Y1=this.structures,oc(J);else if(!Y1||Y1.length>0)Y1=[]}else if(f1=S60,!Y1||Y1.length>0)Y1=[];return oc(J)}unpackMultiple(Z,J){let X,$=0;try{$X=!0;let Y=Z.length,Q=this?this.unpack(Z,Y):Zw.unpack(Z,Y);if(J){if(J(Q,$,m)===!1)return;while(m<Y)if($=m,J(oc(),$,m)===!1)return}else{X=[Q];while(m<Y)$=m,X.push(oc());return X}}catch(Y){throw Y.lastPosition=$,Y.values=X,Y}finally{$X=!1,tc()}}_mergeStructures(Z,J){if(JT)Z=JT.call(this,Z);if(Z=Z||[],Object.isFrozen(Z))Z=Z.map((X)=>X.slice(0));for(let X=0,$=Z.length;X<$;X++){let Y=Z[X];if(Y){if(Y.isShared=!0,X>=32)Y.highByte=X-32>>5}}Z.sharedLength=Z.length;for(let X in J||[])if(X>=0){let $=Z[X],Y=J[X];if(Y){if($)(Z.restoreStructures||(Z.restoreStructures=[]))[X]=$;Z[X]=Y}}return this.structures=Z}decode(Z,J){return this.unpack(Z,J)}}function oc(Z){try{if(!f1.trusted&&!$X){let X=Y1.sharedLength||0;if(X<Y1.length)Y1.length=X}let J;if(f1.randomAccessStructure&&X0[m]<64&&X0[m]>=32&&ZT){if(J=ZT(X0,m,g5,f1),X0=null,!(Z&&Z.lazy)&&J)J=J.toJSON();m=g5}else J=L8();if(S8)m=S8.postBundlePosition,S8=null;if($X)Y1.restoreStructures=null;if(m==g5){if(Y1&&Y1.restoreStructures)A60();if(Y1=null,X0=null,bZ)bZ=null}else if(m>g5)throw new Error("Unexpected end of MessagePack data");else if(!$X){let X;try{X=JSON.stringify(J,($,Y)=>typeof Y==="bigint"?`${Y}n`:Y).slice(0,100)}catch($){X="(JSON view not available "+$+")"}throw new Error("Data read, but end of buffer not reached "+X)}return J}catch(J){if(Y1&&Y1.restoreStructures)A60();if(tc(),J instanceof RangeError||J.message.startsWith("Unexpected end of buffer")||m>g5)J.incomplete=!0;throw J}}function A60(){for(let Z in Y1.restoreStructures)Y1[Z]=Y1.restoreStructures[Z];Y1.restoreStructures=null}function L8(){let Z=X0[m++];if(Z<160)if(Z<128)if(Z<64)return Z;else{let J=Y1[Z&63]||f1.getStructures&&d60()[Z&63];if(J){if(!J.read)J.read=QT(J,Z&63);return J.read()}else return Z}else if(Z<144)if(Z-=128,f1.mapsAsObjects){let J={};for(let X=0;X<Z;X++){let $=Z50();if($==="__proto__")$="__proto_";J[$]=L8()}return J}else{let J=new Map;for(let X=0;X<Z;X++)J.set(L8(),L8());return J}else{Z-=144;let J=new Array(Z);for(let X=0;X<Z;X++)J[X]=L8();if(f1.freezeData)return Object.freeze(J);return J}else if(Z<192){let J=Z-160;if(P4>=m)return _Z.slice(m-i5,(m+=J)-i5);if(P4==0&&g5<140){let X=J<16?KT(J):e60(J);if(X!=null)return X}return rc(J)}else{let J;switch(Z){case 192:return null;case 193:if(S8)if(J=L8(),J>0)return S8[1].slice(S8.position1,S8.position1+=J);else return S8[0].slice(S8.position0,S8.position0-=J);return YT;case 194:return!1;case 195:return!0;case 196:if(J=X0[m++],J===void 0)throw new Error("Unexpected end of buffer");return tP(J);case 197:return J=e0.getUint16(m),m+=2,tP(J);case 198:return J=e0.getUint32(m),m+=4,tP(J);case 199:return ZY(X0[m++]);case 200:return J=e0.getUint16(m),m+=2,ZY(J);case 201:return J=e0.getUint32(m),m+=4,ZY(J);case 202:if(J=e0.getFloat32(m),f1.useFloat32>2){let X=$Y[(X0[m]&127)<<1|X0[m+1]>>7];return m+=4,(X*J+(J>0?0.5:-0.5)>>0)/X}return m+=4,J;case 203:return J=e0.getFloat64(m),m+=8,J;case 204:return X0[m++];case 205:return J=e0.getUint16(m),m+=2,J;case 206:return J=e0.getUint32(m),m+=4,J;case 207:if(f1.int64AsType==="number")J=e0.getUint32(m)*4294967296,J+=e0.getUint32(m+4);else if(f1.int64AsType==="string")J=e0.getBigUint64(m).toString();else if(f1.int64AsType==="auto"){if(J=e0.getBigUint64(m),J<=BigInt(2)<<BigInt(52))J=Number(J)}else J=e0.getBigUint64(m);return m+=8,J;case 208:return e0.getInt8(m++);case 209:return J=e0.getInt16(m),m+=2,J;case 210:return J=e0.getInt32(m),m+=4,J;case 211:if(f1.int64AsType==="number")J=e0.getInt32(m)*4294967296,J+=e0.getUint32(m+4);else if(f1.int64AsType==="string")J=e0.getBigInt64(m).toString();else if(f1.int64AsType==="auto"){if(J=e0.getBigInt64(m),J>=BigInt(-2)<<BigInt(52)&&J<=BigInt(2)<<BigInt(52))J=Number(J)}else J=e0.getBigInt64(m);return m+=8,J;case 212:if(J=X0[m++],J==114)return i60(X0[m++]&63);else{let X=B5[J];if(X)if(X.read)return m++,X.read(L8());else if(X.noBuffer)return m++,X();else return X(X0.subarray(m,++m));else throw new Error("Unknown extension "+J)}case 213:if(J=X0[m],J==114)return m++,i60(X0[m++]&63,X0[m++]);else return ZY(2);case 214:return ZY(4);case 215:return ZY(8);case 216:return ZY(16);case 217:if(J=X0[m++],P4>=m)return _Z.slice(m-i5,(m+=J)-i5);return a60(J);case 218:if(J=e0.getUint16(m),m+=2,P4>=m)return _Z.slice(m-i5,(m+=J)-i5);return n60(J);case 219:if(J=e0.getUint32(m),m+=4,P4>=m)return _Z.slice(m-i5,(m+=J)-i5);return s60(J);case 220:return J=e0.getUint16(m),m+=2,u60(J);case 221:return J=e0.getUint32(m),m+=4,u60(J);case 222:return J=e0.getUint16(m),m+=2,l60(J);case 223:return J=e0.getUint32(m),m+=4,l60(J);default:if(Z>=224)return Z-256;if(Z===void 0){let X=new Error("Unexpected end of MessagePack data");throw X.incomplete=!0,X}throw new Error("Unknown MessagePack token "+Z)}}}var Db1=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function QT(Z,J){function X(){if(X.count++>g60){let Y=Z.read=new Function("r","return function(){return "+(f1.freezeData?"Object.freeze":"")+"({"+Z.map((Q)=>Q==="__proto__"?"__proto_:r()":Db1.test(Q)?Q+":r()":"["+JSON.stringify(Q)+"]:r()").join(",")+"})}")(L8);if(Z.highByte===0)Z.read=m60(J,Z.read);return Y()}let $={};for(let Y=0,Q=Z.length;Y<Q;Y++){let K=Z[Y];if(K==="__proto__")K="__proto_";$[K]=L8()}if(f1.freezeData)return Object.freeze($);return $}if(X.count=0,Z.highByte===0)return m60(J,X);return X}var m60=(Z,J)=>{return function(){let X=X0[m++];if(X===0)return J();let $=Z<32?-(Z+(X<<5)):Z+(X<<5),Y=Y1[$]||d60()[$];if(!Y)throw new Error("Record id is not defined for "+$);if(!Y.read)Y.read=QT(Y,Z);return Y.read()}};function d60(){let Z=X50(()=>{return X0=null,f1.getStructures()});return Y1=f1._mergeStructures(Z,Y1)}var rc=XY,a60=XY,n60=XY,s60=XY,o60=!1;function r60(Z){o60=!0,rc=J(1),a60=J(2),n60=J(3),s60=J(5);function J(X){return function $(Y){let Q=JY[pz++];if(Q==null){if(S8)return XY(Y);let W=X0.byteOffset,G=Z(m-X+W,g5+W,X0.buffer);if(typeof G=="string")Q=G,JY=$T;else if(JY=G,pz=1,P4=1,Q=JY[0],Q===void 0)throw new Error("Unexpected end of buffer")}let K=Q.length;if(K<=Y)return m+=Y,Q;return _Z=Q,i5=m,P4=m+K,m+=Y,Q.slice(0,Y)}}}function XY(Z){let J;if(Z<16){if(J=KT(Z))return J}if(Z>64&&eP)return eP.decode(X0.subarray(m,m+=Z));let X=m+Z,$=[];J="";while(m<X){let Y=X0[m++];if((Y&128)===0)$.push(Y);else if((Y&224)===192){let Q=X0[m++]&63;$.push((Y&31)<<6|Q)}else if((Y&240)===224){let Q=X0[m++]&63,K=X0[m++]&63;$.push((Y&31)<<12|Q<<6|K)}else if((Y&248)===240){let Q=X0[m++]&63,K=X0[m++]&63,W=X0[m++]&63,G=(Y&7)<<18|Q<<12|K<<6|W;if(G>65535)G-=65536,$.push(G>>>10&1023|55296),G=56320|G&1023;$.push(G)}else $.push(Y);if($.length>=4096)J+=a8.apply(String,$),$.length=0}if($.length>0)J+=a8.apply(String,$);return J}function t60(Z,J,X){let $=X0;X0=Z,m=J;try{return XY(X)}finally{X0=$}}function u60(Z){let J=new Array(Z);for(let X=0;X<Z;X++)J[X]=L8();if(f1.freezeData)return Object.freeze(J);return J}function l60(Z){if(f1.mapsAsObjects){let J={};for(let X=0;X<Z;X++){let $=Z50();if($==="__proto__")$="__proto_";J[$]=L8()}return J}else{let J=new Map;for(let X=0;X<Z;X++)J.set(L8(),L8());return J}}var a8=String.fromCharCode;function e60(Z){let J=m,X=new Array(Z);for(let $=0;$<Z;$++){let Y=X0[m++];if((Y&128)>0){m=J;return}X[$]=Y}return a8.apply(String,X)}function KT(Z){if(Z<4)if(Z<2)if(Z===0)return"";else{let J=X0[m++];if((J&128)>1){m-=1;return}return a8(J)}else{let J=X0[m++],X=X0[m++];if((J&128)>0||(X&128)>0){m-=2;return}if(Z<3)return a8(J,X);let $=X0[m++];if(($&128)>0){m-=3;return}return a8(J,X,$)}else{let J=X0[m++],X=X0[m++],$=X0[m++],Y=X0[m++];if((J&128)>0||(X&128)>0||($&128)>0||(Y&128)>0){m-=4;return}if(Z<6)if(Z===4)return a8(J,X,$,Y);else{let Q=X0[m++];if((Q&128)>0){m-=5;return}return a8(J,X,$,Y,Q)}else if(Z<8){let Q=X0[m++],K=X0[m++];if((Q&128)>0||(K&128)>0){m-=6;return}if(Z<7)return a8(J,X,$,Y,Q,K);let W=X0[m++];if((W&128)>0){m-=7;return}return a8(J,X,$,Y,Q,K,W)}else{let Q=X0[m++],K=X0[m++],W=X0[m++],G=X0[m++];if((Q&128)>0||(K&128)>0||(W&128)>0||(G&128)>0){m-=8;return}if(Z<10)if(Z===8)return a8(J,X,$,Y,Q,K,W,G);else{let z=X0[m++];if((z&128)>0){m-=9;return}return a8(J,X,$,Y,Q,K,W,G,z)}else if(Z<12){let z=X0[m++],v=X0[m++];if((z&128)>0||(v&128)>0){m-=10;return}if(Z<11)return a8(J,X,$,Y,Q,K,W,G,z,v);let H=X0[m++];if((H&128)>0){m-=11;return}return a8(J,X,$,Y,Q,K,W,G,z,v,H)}else{let z=X0[m++],v=X0[m++],H=X0[m++],V=X0[m++];if((z&128)>0||(v&128)>0||(H&128)>0||(V&128)>0){m-=12;return}if(Z<14)if(Z===12)return a8(J,X,$,Y,Q,K,W,G,z,v,H,V);else{let q=X0[m++];if((q&128)>0){m-=13;return}return a8(J,X,$,Y,Q,K,W,G,z,v,H,V,q)}else{let q=X0[m++],F=X0[m++];if((q&128)>0||(F&128)>0){m-=14;return}if(Z<15)return a8(J,X,$,Y,Q,K,W,G,z,v,H,V,q,F);let x=X0[m++];if((x&128)>0){m-=15;return}return a8(J,X,$,Y,Q,K,W,G,z,v,H,V,q,F,x)}}}}}function y60(){let Z=X0[m++],J;if(Z<192)J=Z-160;else switch(Z){case 217:J=X0[m++];break;case 218:J=e0.getUint16(m),m+=2;break;case 219:J=e0.getUint32(m),m+=4;break;default:throw new Error("Expected string")}return XY(J)}function tP(Z){return f1.copyBuffers?Uint8Array.prototype.slice.call(X0,m,m+=Z):X0.subarray(m,m+=Z)}function ZY(Z){let J=X0[m++];if(B5[J]){let X;return B5[J](X0.subarray(m,X=m+=Z),($)=>{m=$;try{return L8()}finally{m=X}})}else throw new Error("Unknown extension type "+J)}var p60=new Array(4096);function Z50(){let Z=X0[m++];if(Z>=160&&Z<192){if(Z=Z-160,P4>=m)return _Z.slice(m-i5,(m+=Z)-i5);else if(!(P4==0&&g5<180))return rc(Z)}else return m--,J50(L8());let J=(Z<<5^(Z>1?e0.getUint16(m):Z>0?X0[m]:0))&4095,X=p60[J],$=m,Y=m+Z-3,Q,K=0;if(X&&X.bytes==Z){while($<Y){if(Q=e0.getUint32($),Q!=X[K++]){$=1879048192;break}$+=4}Y+=3;while($<Y)if(Q=X0[$++],Q!=X[K++]){$=1879048192;break}if($===Y)return m=$,X.string;Y-=3,$=m}X=[],p60[J]=X,X.bytes=Z;while($<Y)Q=e0.getUint32($),X.push(Q),$+=4;Y+=3;while($<Y)Q=X0[$++],X.push(Q);let W=Z<16?KT(Z):e60(Z);if(W!=null)return X.string=W;return X.string=rc(Z)}function J50(Z){if(typeof Z==="string")return Z;if(typeof Z==="number"||typeof Z==="boolean"||typeof Z==="bigint")return Z.toString();if(Z==null)return Z+"";if(f1.allowArraysInMapKeys&&Array.isArray(Z)&&Z.flat().every((J)=>["string","number","boolean","bigint"].includes(typeof J)))return Z.flat().toString();throw new Error(`Invalid property type for record: ${typeof Z}`)}var i60=(Z,J)=>{let X=L8().map(J50),$=Z;if(J!==void 0)Z=Z<32?-((J<<5)+Z):(J<<5)+Z,X.highByte=J;let Y=Y1[Z];if(Y&&(Y.isShared||$X))(Y1.restoreStructures||(Y1.restoreStructures=[]))[Z]=Y;return Y1[Z]=X,X.read=QT(X,$),X.read()};B5[0]=()=>{};B5[0].noBuffer=!0;B5[66]=(Z)=>{let J=Z.length,X=BigInt(Z[0]&128?Z[0]-256:Z[0]);for(let $=1;$<J;$++)X<<=BigInt(8),X+=BigInt(Z[$]);return X};var Mb1={Error,TypeError,ReferenceError};B5[101]=()=>{let Z=L8();return(Mb1[Z[0]]||Error)(Z[1],{cause:Z[2]})};B5[105]=(Z)=>{if(f1.structuredClone===!1)throw new Error("Structured clone extension is disabled");let J=e0.getUint32(m-4);if(!bZ)bZ=new Map;let X=X0[m],$;if(X>=144&&X<160||X==220||X==221)$=[];else if(X>=128&&X<144||X==222||X==223)$=new Map;else if((X>=199&&X<=201||X>=212&&X<=216)&&X0[m+1]===115)$=new Set;else $={};let Y={target:$};bZ.set(J,Y);let Q=L8();if(!Y.used)return Y.target=Q;else Object.assign($,Q);if($ instanceof Map)for(let[K,W]of Q.entries())$.set(K,W);if($ instanceof Set)for(let K of Array.from(Q))$.add(K);return $};B5[112]=(Z)=>{if(f1.structuredClone===!1)throw new Error("Structured clone extension is disabled");let J=e0.getUint32(m-4),X=bZ.get(J);return X.used=!0,X.target};B5[115]=()=>new Set(L8());var WT=["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64","BigInt64","BigUint64"].map((Z)=>Z+"Array"),Rb1=typeof globalThis==="object"?globalThis:window;B5[116]=(Z)=>{let J=Z[0],X=Uint8Array.prototype.slice.call(Z,1).buffer,$=WT[J];if(!$){if(J===16)return X;if(J===17)return new DataView(X);throw new Error("Could not find typed array for code "+J)}return new Rb1[$](X)};B5[120]=()=>{let Z=L8();return new RegExp(Z[0],Z[1])};var Nb1=[];B5[98]=(Z)=>{let J=(Z[0]<<24)+(Z[1]<<16)+(Z[2]<<8)+Z[3],X=m;return m+=J-Z.length,S8=Nb1,S8=[y60(),y60()],S8.position0=0,S8.position1=0,S8.postBundlePosition=m,m=X,L8()};B5[255]=(Z)=>{if(Z.length==4)return new Date((Z[0]*16777216+(Z[1]<<16)+(Z[2]<<8)+Z[3])*1000);else if(Z.length==8)return new Date(((Z[0]<<22)+(Z[1]<<14)+(Z[2]<<6)+(Z[3]>>2))/1e6+((Z[3]&3)*4294967296+Z[4]*16777216+(Z[5]<<16)+(Z[6]<<8)+Z[7])*1000);else if(Z.length==12)return new Date(((Z[0]<<24)+(Z[1]<<16)+(Z[2]<<8)+Z[3])/1e6+((Z[4]&128?-281474976710656:0)+Z[6]*1099511627776+Z[7]*4294967296+Z[8]*16777216+(Z[9]<<16)+(Z[10]<<8)+Z[11])*1000);else return new Date("invalid")};function X50(Z){if(XT)XT();let J=g5,X=m,$=pz,Y=i5,Q=P4,K=_Z,W=JY,G=bZ,z=S8,v=new Uint8Array(X0.slice(0,g5)),H=Y1,V=Y1.slice(0,Y1.length),q=f1,F=$X,x=Z();return g5=J,m=X,pz=$,i5=Y,P4=Q,_Z=K,JY=W,bZ=G,S8=z,X0=v,$X=F,Y1=H,Y1.splice(0,Y1.length,...V),f1=q,e0=new DataView(X0.buffer,X0.byteOffset,X0.byteLength),x}function tc(){X0=null,bZ=null,Y1=null}var $Y=new Array(147);for(let Z=0;Z<256;Z++)$Y[Z]=+("1e"+Math.floor(45.15-Z*0.30103));var Zw=new hZ({useRecords:!1}),Ob1=Zw.unpack,Pb1=Zw.unpackMultiple,Tb1=Zw.unpack,iz={NEVER:0,ALWAYS:1,DECIMAL_ROUND:3,DECIMAL_FIT:4},Cb1=new Float32Array(1),Eb6=new Uint8Array(Cb1.buffer,0,4);function $50(Z,J,X){ZT=Z,JT=J,XT=X}var Xw;try{Xw=new TextEncoder}catch(Z){}var vT,K50,dz=typeof Buffer!=="undefined",Jw=dz?function(Z){return Buffer.allocUnsafeSlow(Z)}:Uint8Array,W50=dz?Buffer:Uint8Array,Y50=dz?4294967296:2144337920,n,gz,h1,y=0,a6,o1=null,G50,fb1=21760,kb1=/[\u0080-\uFFFF]/,x7=Symbol("record-id");class YY extends hZ{constructor(Z){super(Z);this.offset=0;let J,X,$,Y,Q,K=W50.prototype.utf8Write?function(f,C){return n.utf8Write(f,C,n.byteLength-C)}:Xw&&Xw.encodeInto?function(f,C){return Xw.encodeInto(f,n.subarray(C)).written}:!1,W=this;if(!Z)Z={};let G=Z&&Z.sequential,z=Z.structures||Z.saveStructures,v=Z.maxSharedStructures;if(v==null)v=z?32:0;if(v>8160)throw new Error("Maximum maxSharedStructure is 8160");if(Z.structuredClone&&Z.moreTypes==null)this.moreTypes=!0;let H=Z.maxOwnStructures;if(H==null)H=z?32:64;if(!this.structures&&Z.useRecords!=!1)this.structures=[];let V=v>32||H+v>64,q=v+64,F=v+H+64;if(F>8256)throw new Error("Maximum maxSharedStructure + maxOwnStructure is 8192");let x=[],c=0,w=0;this.pack=this.encode=function(f,C){if(!n)n=new Jw(8192),h1=n.dataView||(n.dataView=new DataView(n.buffer,0,8192)),y=0;if(a6=n.length-10,a6-y<2048)n=new Jw(n.length),h1=n.dataView||(n.dataView=new DataView(n.buffer,0,n.length)),a6=n.length-10,y=0;else y=y+7&2147483640;if(X=y,C&Ab1)y+=C&255;if(Q=W.structuredClone?new Map:null,W.bundleStrings&&typeof f!=="string")o1=[],o1.size=1/0;else o1=null;if(Y=W.structures,Y){if(Y.uninitialized)Y=W._mergeStructures(W.getStructures());let I=Y.sharedLength||0;if(I>v)throw new Error("Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to "+Y.sharedLength);if(!Y.transitions){Y.transitions=Object.create(null);for(let a=0;a<I;a++){let s=Y[a];if(!s)continue;let Z0,o=Y.transitions;for(let M0=0,R0=s.length;M0<R0;M0++){let m0=s[M0];if(Z0=o[m0],!Z0)Z0=o[m0]=Object.create(null);o=Z0}o[x7]=a+64}this.lastNamedStructuresLength=I}if(!G)Y.nextId=I+64}if($)$=!1;let b;try{if(W.randomAccessStructure&&f&&f.constructor&&f.constructor===Object)h(f);else L(f);let I=o1;if(o1)Q50(X,L,0);if(Q&&Q.idsToInsert){let a=Q.idsToInsert.sort((M0,R0)=>M0.offset>R0.offset?1:-1),s=a.length,Z0=-1;while(I&&s>0){let M0=a[--s].offset+X;if(M0<I.stringsPosition+X&&Z0===-1)Z0=0;if(M0>I.position+X){if(Z0>=0)Z0+=6}else{if(Z0>=0)h1.setUint32(I.position+X,h1.getUint32(I.position+X)+Z0),Z0=-1;I=I.previous,s++}}if(Z0>=0&&I)h1.setUint32(I.position+X,h1.getUint32(I.position+X)+Z0);if(y+=a.length*6,y>a6)O(y);W.offset=y;let o=Ib1(n.subarray(X,y),a);return Q=null,o}if(W.offset=y,C&hb1)return n.start=X,n.end=y,n;return n.subarray(X,y)}catch(I){throw b=I,I}finally{if(Y){if(B(),$&&W.saveStructures){let I=Y.sharedLength||0,a=n.subarray(X,y),s=z50(Y,W);if(!b){if(W.saveStructures(s,s.isCompatible)===!1)return W.pack(f,C);if(W.lastNamedStructuresLength=I,n.length>1073741824)n=null;return a}}}if(n.length>1073741824)n=null;if(C&Sb1)y=X}};let B=()=>{if(w<10)w++;let f=Y.sharedLength||0;if(Y.length>f&&!G)Y.length=f;if(c>1e4){if(Y.transitions=null,w=0,c=0,x.length>0)x=[]}else if(x.length>0&&!G){for(let C=0,b=x.length;C<b;C++)x[C][x7]=0;x=[]}},j=(f)=>{var C=f.length;if(C<16)n[y++]=144|C;else if(C<65536)n[y++]=220,n[y++]=C>>8,n[y++]=C&255;else n[y++]=221,h1.setUint32(y,C),y+=4;for(let b=0;b<C;b++)L(f[b])},L=(f)=>{if(y>a6)n=O(y);var C=typeof f,b;if(C==="string"){let I=f.length;if(o1&&I>=4&&I<4096){if((o1.size+=I)>fb1){let o,M0=(o1[0]?o1[0].length*3+o1[1].length:0)+10;if(y+M0>a6)n=O(y+M0);let R0;if(o1.position)R0=o1,n[y]=200,y+=3,n[y++]=98,o=y-X,y+=4,Q50(X,L,0),h1.setUint16(o+X-3,y-X-o);else n[y++]=214,n[y++]=98,o=y-X,y+=4;o1=["",""],o1.previous=R0,o1.size=0,o1.position=o}let Z0=kb1.test(f);o1[Z0?0:1]+=f,n[y++]=193,L(Z0?-I:I);return}let a;if(I<32)a=1;else if(I<256)a=2;else if(I<65536)a=3;else a=5;let s=I*3;if(y+s>a6)n=O(y+s);if(I<64||!K){let Z0,o,M0,R0=y+a;for(Z0=0;Z0<I;Z0++)if(o=f.charCodeAt(Z0),o<128)n[R0++]=o;else if(o<2048)n[R0++]=o>>6|192,n[R0++]=o&63|128;else if((o&64512)===55296&&((M0=f.charCodeAt(Z0+1))&64512)===56320)o=65536+((o&1023)<<10)+(M0&1023),Z0++,n[R0++]=o>>18|240,n[R0++]=o>>12&63|128,n[R0++]=o>>6&63|128,n[R0++]=o&63|128;else n[R0++]=o>>12|224,n[R0++]=o>>6&63|128,n[R0++]=o&63|128;b=R0-y-a}else b=K(f,y+a);if(b<32)n[y++]=160|b;else if(b<256){if(a<2)n.copyWithin(y+2,y+1,y+1+b);n[y++]=217,n[y++]=b}else if(b<65536){if(a<3)n.copyWithin(y+3,y+2,y+2+b);n[y++]=218,n[y++]=b>>8,n[y++]=b&255}else{if(a<5)n.copyWithin(y+5,y+3,y+3+b);n[y++]=219,h1.setUint32(y,b),y+=4}y+=b}else if(C==="number")if(f>>>0===f)if(f<32||f<128&&this.useRecords===!1||f<64&&!this.randomAccessStructure)n[y++]=f;else if(f<256)n[y++]=204,n[y++]=f;else if(f<65536)n[y++]=205,n[y++]=f>>8,n[y++]=f&255;else n[y++]=206,h1.setUint32(y,f),y+=4;else if(f>>0===f)if(f>=-32)n[y++]=256+f;else if(f>=-128)n[y++]=208,n[y++]=f+256;else if(f>=-32768)n[y++]=209,h1.setInt16(y,f),y+=2;else n[y++]=210,h1.setInt32(y,f),y+=4;else{let I;if((I=this.useFloat32)>0&&f<4294967296&&f>=-2147483648){n[y++]=202,h1.setFloat32(y,f);let a;if(I<4||(a=f*$Y[(n[y]&127)<<1|n[y+1]>>7])>>0===a){y+=4;return}else y--}n[y++]=203,h1.setFloat64(y,f),y+=8}else if(C==="object"||C==="function")if(!f)n[y++]=192;else{if(Q){let a=Q.get(f);if(a){if(!a.id){let s=Q.idsToInsert||(Q.idsToInsert=[]);a.id=s.push(a)}n[y++]=214,n[y++]=112,h1.setUint32(y,a.id),y+=4;return}else Q.set(f,{offset:y-X})}let I=f.constructor;if(I===Object)P(f);else if(I===Array)j(f);else if(I===Map)if(this.mapAsEmptyObject)n[y++]=128;else{if(b=f.size,b<16)n[y++]=128|b;else if(b<65536)n[y++]=222,n[y++]=b>>8,n[y++]=b&255;else n[y++]=223,h1.setUint32(y,b),y+=4;for(let[a,s]of f)L(a),L(s)}else{for(let a=0,s=vT.length;a<s;a++){let Z0=K50[a];if(f instanceof Z0){let o=vT[a];if(o.write){if(o.type)n[y++]=212,n[y++]=o.type,n[y++]=0;let s0=o.write.call(this,f);if(s0===f)if(Array.isArray(f))j(f);else P(f);else L(s0);return}let M0=n,R0=h1,m0=y;n=null;let N1;try{N1=o.pack.call(this,f,(s0)=>{if(n=M0,M0=null,y+=s0,y>a6)O(y);return{target:n,targetView:h1,position:y-s0}},L)}finally{if(M0)n=M0,h1=R0,y=m0,a6=n.length-10}if(N1){if(N1.length+y>a6)O(N1.length+y);y=Eb1(N1,n,y,o.type)}return}}if(Array.isArray(f))j(f);else{if(f.toJSON){let a=f.toJSON();if(a!==f)return L(a)}if(C==="function")return L(this.writeFunction&&this.writeFunction(f));P(f)}}}else if(C==="boolean")n[y++]=f?195:194;else if(C==="bigint"){if(f<9223372036854776000&&f>=-9223372036854776000)n[y++]=211,h1.setBigInt64(y,f);else if(f<18446744073709552000&&f>0)n[y++]=207,h1.setBigUint64(y,f);else if(this.largeBigIntToFloat)n[y++]=203,h1.setFloat64(y,Number(f));else if(this.largeBigIntToString)return L(f.toString());else if((this.useBigIntExtension||this.moreTypes)&&f<BigInt(2)**BigInt(1023)&&f>-(BigInt(2)**BigInt(1023))){n[y++]=199,y++,n[y++]=66;let I=[],a;do{let s=f&BigInt(255);a=(s&BigInt(128))===(f<BigInt(0)?BigInt(128):BigInt(0)),I.push(s),f>>=BigInt(8)}while(!((f===BigInt(0)||f===BigInt(-1))&&a));n[y-2]=I.length;for(let s=I.length;s>0;)n[y++]=Number(I[--s]);return}else throw new RangeError(f+" was too large to fit in MessagePack 64-bit integer format, use useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set largeBigIntToString to convert to string");y+=8}else if(C==="undefined")if(this.encodeUndefinedAsNil)n[y++]=192;else n[y++]=212,n[y++]=0,n[y++]=0;else throw new Error("Unknown type: "+C)},R=this.variableMapSize||this.coercibleKeyAsNumber||this.skipValues?(f)=>{let C;if(this.skipValues){C=[];for(let a in f)if((typeof f.hasOwnProperty!=="function"||f.hasOwnProperty(a))&&!this.skipValues.includes(f[a]))C.push(a)}else C=Object.keys(f);let b=C.length;if(b<16)n[y++]=128|b;else if(b<65536)n[y++]=222,n[y++]=b>>8,n[y++]=b&255;else n[y++]=223,h1.setUint32(y,b),y+=4;let I;if(this.coercibleKeyAsNumber)for(let a=0;a<b;a++){I=C[a];let s=Number(I);L(isNaN(s)?I:s),L(f[I])}else for(let a=0;a<b;a++)L(I=C[a]),L(f[I])}:(f)=>{n[y++]=222;let C=y-X;y+=2;let b=0;for(let I in f)if(typeof f.hasOwnProperty!=="function"||f.hasOwnProperty(I))L(I),L(f[I]),b++;if(b>65535)throw new Error('Object is too large to serialize with fast 16-bit map size, use the "variableMapSize" option to serialize this object');n[C+++X]=b>>8,n[C+X]=b&255},M=this.useRecords===!1?R:Z.progressiveRecords&&!V?(f)=>{let C,b=Y.transitions||(Y.transitions=Object.create(null)),I=y++-X,a;for(let s in f)if(typeof f.hasOwnProperty!=="function"||f.hasOwnProperty(s)){if(C=b[s],C)b=C;else{let Z0=Object.keys(f),o=b;b=Y.transitions;let M0=0;for(let R0=0,m0=Z0.length;R0<m0;R0++){let N1=Z0[R0];if(C=b[N1],!C)C=b[N1]=Object.create(null),M0++;b=C}if(I+X+1==y)y--,_(b,Z0,M0);else k(b,Z0,I,M0);a=!0,b=o[s]}L(f[s])}if(!a){let s=b[x7];if(s)n[I+X]=s;else k(b,Object.keys(f),I,0)}}:(f)=>{let C,b=Y.transitions||(Y.transitions=Object.create(null)),I=0;for(let s in f)if(typeof f.hasOwnProperty!=="function"||f.hasOwnProperty(s)){if(C=b[s],!C)C=b[s]=Object.create(null),I++;b=C}let a=b[x7];if(a)if(a>=96&&V)n[y++]=((a-=96)&31)+96,n[y++]=a>>5;else n[y++]=a;else _(b,b.__keys__||Object.keys(f),I);for(let s in f)if(typeof f.hasOwnProperty!=="function"||f.hasOwnProperty(s))L(f[s])},N=typeof this.useRecords=="function"&&this.useRecords,P=N?(f)=>{N(f)?M(f):R(f)}:M,O=(f)=>{let C;if(f>16777216){if(f-X>Y50)throw new Error("Packed buffer would be larger than maximum buffer size");C=Math.min(Y50,Math.round(Math.max((f-X)*(f>67108864?1.25:2),4194304)/4096)*4096)}else C=(Math.max(f-X<<2,n.length-1)>>12)+1<<12;let b=new Jw(C);if(h1=b.dataView||(b.dataView=new DataView(b.buffer,0,C)),f=Math.min(f,n.length),n.copy)n.copy(b,0,X,f);else b.set(n.slice(X,f));return y-=X,X=0,a6=b.length-10,n=b},_=(f,C,b)=>{let I=Y.nextId;if(!I)I=64;if(I<q&&this.shouldShareStructure&&!this.shouldShareStructure(C)){if(I=Y.nextOwnId,!(I<F))I=q;Y.nextOwnId=I+1}else{if(I>=F)I=q;Y.nextId=I+1}let a=C.highByte=I>=96&&V?I-96>>5:-1;if(f[x7]=I,f.__keys__=C,Y[I-64]=C,I<q)if(C.isShared=!0,Y.sharedLength=I-63,$=!0,a>=0)n[y++]=(I&31)+96,n[y++]=a;else n[y++]=I;else{if(a>=0)n[y++]=213,n[y++]=114,n[y++]=(I&31)+96,n[y++]=a;else n[y++]=212,n[y++]=114,n[y++]=I;if(b)c+=w*b;if(x.length>=H)x.shift()[x7]=0;x.push(f),L(C)}},k=(f,C,b,I)=>{let a=n,s=y,Z0=a6,o=X;if(n=gz,y=0,X=0,!n)gz=n=new Jw(8192);a6=n.length-10,_(f,C,I),gz=n;let M0=y;if(n=a,y=s,a6=Z0,X=o,M0>1){let R0=y+M0-1;if(R0>a6)O(R0);let m0=b+X;n.copyWithin(m0+M0,m0+1,y),n.set(gz.slice(0,M0),m0),y=R0}else n[b+X]=gz[0]},h=(f)=>{let C=G50(f,n,X,y,Y,O,(b,I,a)=>{if(a)return $=!0;y=I;let s=n;if(L(b),B(),s!==n)return{position:y,targetView:h1,target:n};return y},this);if(C===0)return P(f);y=C}}useBuffer(Z){n=Z,n.dataView||(n.dataView=new DataView(n.buffer,n.byteOffset,n.byteLength)),y=0}set position(Z){y=Z}get position(){return y}clearSharedData(){if(this.structures)this.structures=[];if(this.typedStructs)this.typedStructs=[]}}K50=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,DataView,ec];vT=[{pack(Z,J,X){let $=Z.getTime()/1000;if((this.useTimestamp32||Z.getMilliseconds()===0)&&$>=0&&$<4294967296){let{target:Y,targetView:Q,position:K}=J(6);Y[K++]=214,Y[K++]=255,Q.setUint32(K,$)}else if($>0&&$<4294967296){let{target:Y,targetView:Q,position:K}=J(10);Y[K++]=215,Y[K++]=255,Q.setUint32(K,Z.getMilliseconds()*4000000+($/1000/4294967296>>0)),Q.setUint32(K+4,$)}else if(isNaN($)){if(this.onInvalidDate)return J(0),X(this.onInvalidDate());let{target:Y,targetView:Q,position:K}=J(3);Y[K++]=212,Y[K++]=255,Y[K++]=255}else{let{target:Y,targetView:Q,position:K}=J(15);Y[K++]=199,Y[K++]=12,Y[K++]=255,Q.setUint32(K,Z.getMilliseconds()*1e6),Q.setBigInt64(K+4,BigInt(Math.floor($)))}}},{pack(Z,J,X){if(this.setAsEmptyObject)return J(0),X({});let $=Array.from(Z),{target:Y,position:Q}=J(this.moreTypes?3:0);if(this.moreTypes)Y[Q++]=212,Y[Q++]=115,Y[Q++]=0;X($)}},{pack(Z,J,X){let{target:$,position:Y}=J(this.moreTypes?3:0);if(this.moreTypes)$[Y++]=212,$[Y++]=101,$[Y++]=0;X([Z.name,Z.message,Z.cause])}},{pack(Z,J,X){let{target:$,position:Y}=J(this.moreTypes?3:0);if(this.moreTypes)$[Y++]=212,$[Y++]=120,$[Y++]=0;X([Z.source,Z.flags])}},{pack(Z,J){if(this.moreTypes)GT(Z,16,J);else zT(dz?Buffer.from(Z):new Uint8Array(Z),J)}},{pack(Z,J){let X=Z.constructor;if(X!==W50&&this.moreTypes)GT(Z,WT.indexOf(X.name),J);else zT(Z,J)}},{pack(Z,J){if(this.moreTypes)GT(Z,17,J);else zT(dz?Buffer.from(Z):new Uint8Array(Z),J)}},{pack(Z,J){let{target:X,position:$}=J(1);X[$]=193}}];function GT(Z,J,X,$){let Y=Z.byteLength;if(Y+1<256){var{target:Q,position:K}=X(4+Y);Q[K++]=199,Q[K++]=Y+1}else if(Y+1<65536){var{target:Q,position:K}=X(5+Y);Q[K++]=200,Q[K++]=Y+1>>8,Q[K++]=Y+1&255}else{var{target:Q,position:K,targetView:W}=X(7+Y);Q[K++]=201,W.setUint32(K,Y+1),K+=4}if(Q[K++]=116,Q[K++]=J,!Z.buffer)Z=new Uint8Array(Z);Q.set(new Uint8Array(Z.buffer,Z.byteOffset,Z.byteLength),K)}function zT(Z,J){let X=Z.byteLength;var $,Y;if(X<256){var{target:$,position:Y}=J(X+2);$[Y++]=196,$[Y++]=X}else if(X<65536){var{target:$,position:Y}=J(X+3);$[Y++]=197,$[Y++]=X>>8,$[Y++]=X&255}else{var{target:$,position:Y,targetView:Q}=J(X+5);$[Y++]=198,Q.setUint32(Y,X),Y+=4}$.set(Z,Y)}function Eb1(Z,J,X,$){let Y=Z.length;switch(Y){case 1:J[X++]=212;break;case 2:J[X++]=213;break;case 4:J[X++]=214;break;case 8:J[X++]=215;break;case 16:J[X++]=216;break;default:if(Y<256)J[X++]=199,J[X++]=Y;else if(Y<65536)J[X++]=200,J[X++]=Y>>8,J[X++]=Y&255;else J[X++]=201,J[X++]=Y>>24,J[X++]=Y>>16&255,J[X++]=Y>>8&255,J[X++]=Y&255}return J[X++]=$,J.set(Z,X),X+=Y,X}function Ib1(Z,J){let X,$=J.length*6,Y=Z.length-$;while(X=J.pop()){let{offset:Q,id:K}=X;Z.copyWithin(Q+$,Q,Y),$-=6;let W=Q+$;Z[W++]=214,Z[W++]=105,Z[W++]=K>>24,Z[W++]=K>>16&255,Z[W++]=K>>8&255,Z[W++]=K&255,Y=Q}return Z}function Q50(Z,J,X){if(o1.length>0){h1.setUint32(o1.position+Z,y+X-o1.position-Z),o1.stringsPosition=y-Z;let $=o1;o1=null,J($[0]),J($[1])}}function z50(Z,J){return Z.isCompatible=(X)=>{let $=!X||(J.lastNamedStructuresLength||0)===X.length;if(!$)J._mergeStructures(X);return $},Z}function v50(Z,J){G50=Z,z50=J}var V50=new YY({useRecords:!1}),_b1=V50.pack,bb1=V50.pack;var hb1=512,Sb1=1024,Ab1=2048;var VT=3,a3=0,az=2,$w=1,qT=16,q50=["num","object","string","ascii"];q50[qT]="date";var ub1=[!1,!0,!0,!1,!1,!0,!0,!1],F50;try{new Function(""),F50=!0}catch(Z){}var QY,lb1=typeof Buffer!=="undefined",Yw,c7;try{Yw=new TextEncoder}catch(Z){}var yb1=lb1?function(Z,J,X){return Z.utf8Write(J,X,Z.byteLength-X)}:Yw&&Yw.encodeInto?function(Z,J,X){return Yw.encodeInto(J,Z.subarray(X)).written}:!1,lb6=Symbol("type"),yb6=Symbol("parent");v50(x50,ab1);function x50(Z,J,X,$,Y,Q,K,W){let G=W.typedStructs||(W.typedStructs=[]),z=J.dataView,v=(G.lastStringStart||100)+$,H=J.length-10,V=$;if($>H)J=Q($),z=J.dataView,$-=X,V-=X,v-=X,X=0,H=J.length-10;let q,F=v,x=G.transitions||(G.transitions=Object.create(null)),c=G.nextId||G.length,w=c<15?1:c<240?2:c<61440?3:c<15728640?4:0;if(w===0)return 0;$+=w;let B=[],j,L=0;for(let M in Z){let N=Z[M],P=x[M];if(!P)x[M]=P={key:M,parent:x,enumerationOffset:0,ascii0:null,ascii8:null,num8:null,string16:null,object16:null,num32:null,float64:null,date64:null};if($>H)J=Q($),z=J.dataView,$-=X,V-=X,v-=X,F-=X,X=0,H=J.length-10;switch(typeof N){case"number":let O=N;if(c<200||!P.num64){if(O>>0===O&&O<536870912&&O>-520093696){if(O<246&&O>=0&&(P.num8&&!(c>200&&P.num32)||O<32&&!P.num32))x=P.num8||j5(P,a3,1),J[$++]=O;else x=P.num32||j5(P,a3,4),z.setUint32($,O,!0),$+=4;break}else if(O<4294967296&&O>=-2147483648){if(z.setFloat32($,O,!0),ub1[J[$+3]>>>5]){let f;if((f=O*$Y[(J[$+3]&127)<<1|J[$+2]>>7])>>0===f){x=P.num32||j5(P,a3,4),$+=4;break}}}}x=P.num64||j5(P,a3,8),z.setFloat64($,O,!0),$+=8;break;case"string":let _=N.length;if(q=F-v,(_<<2)+F>H)J=Q((_<<2)+F),z=J.dataView,$-=X,V-=X,v-=X,F-=X,X=0,H=J.length-10;if(_>65280+q>>2){B.push(M,N,$-V);break}let k,h=F;if(_<64){let f,C,b;for(f=0;f<_;f++)if(C=N.charCodeAt(f),C<128)J[F++]=C;else if(C<2048)k=!0,J[F++]=C>>6|192,J[F++]=C&63|128;else if((C&64512)===55296&&((b=N.charCodeAt(f+1))&64512)===56320)k=!0,C=65536+((C&1023)<<10)+(b&1023),f++,J[F++]=C>>18|240,J[F++]=C>>12&63|128,J[F++]=C>>6&63|128,J[F++]=C&63|128;else k=!0,J[F++]=C>>12|224,J[F++]=C>>6&63|128,J[F++]=C&63|128}else F+=yb1(J,N,F),k=F-h>_;if(q<160||q<246&&(P.ascii8||P.string8)){if(k){if(!(x=P.string8))if(G.length>10&&(x=P.ascii8))x.__type=az,P.ascii8=null,P.string8=x,K(null,0,!0);else x=j5(P,az,1)}else if(q===0&&!j){j=!0,x=P.ascii0||j5(P,VT,0);break}else if(!(x=P.ascii8)&&!(G.length>10&&(x=P.string8)))x=j5(P,VT,1);J[$++]=q}else x=P.string16||j5(P,az,2),z.setUint16($,q,!0),$+=2;break;case"object":if(N){if(N.constructor===Date)x=P.date64||j5(P,qT,8),z.setFloat64($,N.getTime(),!0),$+=8;else B.push(M,N,L);break}else if(P=H50(P,$,z,-10),P)x=P,$=QY;else B.push(M,N,L);break;case"boolean":x=P.num8||P.ascii8||j5(P,a3,1),J[$++]=N?249:248;break;case"undefined":if(P=H50(P,$,z,-9),P)x=P,$=QY;else B.push(M,N,L);break;default:B.push(M,N,L)}L++}for(let M=0,N=B.length;M<N;){let P=B[M++],O=B[M++],_=B[M++],k=x[P];if(!k)x[P]=k={key:P,parent:x,enumerationOffset:_-L,ascii0:null,ascii8:null,num8:null,string16:null,object16:null,num32:null,float64:null};let h;if(O){let f;if(q=F-v,q<65280)if(x=k.object16,x)f=2;else if(x=k.object32)f=4;else x=j5(k,$w,2),f=2;else x=k.object32||j5(k,$w,4),f=4;if(h=K(O,F),typeof h==="object")F=h.position,z=h.targetView,J=h.target,v-=X,$-=X,V-=X,X=0;else F=h;if(f===2)z.setUint16($,q,!0),$+=2;else z.setUint32($,q,!0),$+=4}else x=k.object16||j5(k,$w,2),z.setInt16($,O===null?-10:-9,!0),$+=2;L++}let R=x[x7];if(R==null){R=W.typedStructs.length;let M=[],N=x,P,O;while((O=N.__type)!==void 0){let _=N.__size;N=N.__parent,P=N.key;let k=[O,_,P];if(N.enumerationOffset)k.push(N.enumerationOffset);M.push(k),N=N.parent}M.reverse(),x[x7]=R,W.typedStructs[R]=M,K(null,0,!0)}switch(w){case 1:if(R>=16)return 0;J[V]=R+32;break;case 2:if(R>=256)return 0;J[V]=56,J[V+1]=R;break;case 3:if(R>=65536)return 0;J[V]=57,z.setUint16(V+1,R,!0);break;case 4:if(R>=16777216)return 0;z.setUint32(V,(R<<8)+58,!0);break}if($<v){if(v===F)return $;J.copyWithin($,v,F),F+=$-v,G.lastStringStart=$-V}else if($>v){if(v===F)return $;return G.lastStringStart=$-V,x50(Z,J,X,V,Y,Q,K,W)}return F}function H50(Z,J,X,$){let Y;if(Y=Z.ascii8||Z.num8)return X.setInt8(J,$,!0),QY=J+1,Y;if(Y=Z.string16||Z.object16)return X.setInt16(J,$,!0),QY=J+2,Y;if(Y=Z.num32)return X.setUint32(J,3758096640+$,!0),QY=J+4,Y;if(Y=Z.num64)return X.setFloat64(J,NaN,!0),X.setInt8(J,$),QY=J+8,Y;QY=J;return}function j5(Z,J,X){let $=q50[J]+(X<<3),Y=Z[$]||(Z[$]=Object.create(null));return Y.__type=J,Y.__size=X,Y.__parent=Z,Y}function pb1(Z){if(!(Z instanceof Map))return Z;let J=Z.get("typed")||[];if(Object.isFrozen(J))J=J.map((Y)=>Y.slice(0));let X=Z.get("named"),$=Object.create(null);for(let Y=0,Q=J.length;Y<Q;Y++){let K=J[Y],W=$;for(let[G,z,v]of K){let H=W[v];if(!H)W[v]=H={key:v,parent:W,enumerationOffset:0,ascii0:null,ascii8:null,num8:null,string16:null,object16:null,num32:null,float64:null,date64:null};W=j5(H,G,z)}W[x7]=Y}return J.transitions=$,this.typedStructs=J,this.lastTypedStructuresLength=J.length,X}var HT=Symbol.for("source");function ib1(Z,J,X,$){let Y=Z[J++]-32;if(Y>=24)switch(Y){case 24:Y=Z[J++];break;case 25:Y=Z[J++]+(Z[J++]<<8);break;case 26:Y=Z[J++]+(Z[J++]<<8)+(Z[J++]<<16);break;case 27:Y=Z[J++]+(Z[J++]<<8)+(Z[J++]<<16)+(Z[J++]<<24);break}let Q=$.typedStructs&&$.typedStructs[Y];if(!Q){if(Z=Uint8Array.prototype.slice.call(Z,J,X),X-=J,J=0,!$.getStructures)throw new Error(`Reference to shared structure ${Y} without getStructures method`);if($._mergeStructures($.getStructures()),!$.typedStructs)throw new Error("Could not find any shared typed structures");if($.lastTypedStructuresLength=$.typedStructs.length,Q=$.typedStructs[Y],!Q)throw new Error("Could not find typed structure "+Y)}var{construct:K,fullConstruct:W}=Q;if(!K){K=Q.construct=function q(){},W=Q.fullConstruct=function q(){},W.prototype=$.structPrototype??{};var G=K.prototype=$.structPrototype?Object.create($.structPrototype):{};let v=[],H=0,V;for(let q=0,F=Q.length;q<F;q++){let x=Q[q],[c,w,B,j]=x;if(B==="__proto__")B="__proto_";let L={key:B,offset:H};if(j)v.splice(q+j,0,L);else v.push(L);let R;switch(w){case 0:R=()=>0;break;case 1:R=(N,P)=>{let O=N.bytes[P+L.offset];return O>=246?d3(O):O};break;case 2:R=(N,P)=>{let O=N.bytes,k=(O.dataView||(O.dataView=new DataView(O.buffer,O.byteOffset,O.byteLength))).getUint16(P+L.offset,!0);return k>=65280?d3(k&255):k};break;case 4:R=(N,P)=>{let O=N.bytes,k=(O.dataView||(O.dataView=new DataView(O.buffer,O.byteOffset,O.byteLength))).getUint32(P+L.offset,!0);return k>=4294967040?d3(k&255):k};break}L.getRef=R,H+=w;let M;switch(c){case VT:if(V&&!V.next)V.next=L;V=L,L.multiGetCount=0,M=function(N){let{bytes:P,position:O}=N,_=H+O,k=R(N,O);if(typeof k!=="number")return k;let h,f=L.next;while(f){if(h=f.getRef(N,O),typeof h==="number")break;else h=null;f=f.next}if(h==null)h=N.bytesEnd-_;if(N.srcString)return N.srcString.slice(k,h);return t60(P,k+_,h-k)};break;case az:case $w:if(V&&!V.next)V.next=L;V=L,M=function(N){let P=N.position,O=H+P,_=R(N,P);if(typeof _!=="number")return _;let k=N.bytes,h,f=L.next;while(f){if(h=f.getRef(N,P),typeof h==="number")break;else h=null;f=f.next}if(h==null)h=N.bytesEnd-O;if(c===az)return k.toString("utf8",_+O,h+O);else{c7=N;try{return $.unpack(k,{start:_+O,end:h+O})}finally{c7=null}}};break;case a3:switch(w){case 4:M=function(N){let P=N.bytes,O=P.dataView||(P.dataView=new DataView(P.buffer,P.byteOffset,P.byteLength)),_=N.position+L.offset,k=O.getInt32(_,!0);if(k<536870912){if(k>-520093696)return k;if(k>-536870912)return d3(k&255)}let h=O.getFloat32(_,!0),f=$Y[(P[_+3]&127)<<1|P[_+2]>>7];return(f*h+(h>0?0.5:-0.5)>>0)/f};break;case 8:M=function(N){let P=N.bytes,_=(P.dataView||(P.dataView=new DataView(P.buffer,P.byteOffset,P.byteLength))).getFloat64(N.position+L.offset,!0);if(isNaN(_)){let k=P[N.position+L.offset];if(k>=246)return d3(k)}return _};break;case 1:M=function(N){let O=N.bytes[N.position+L.offset];return O<246?O:d3(O)};break}break;case qT:M=function(N){let P=N.bytes,O=P.dataView||(P.dataView=new DataView(P.buffer,P.byteOffset,P.byteLength));return new Date(O.getFloat64(N.position+L.offset,!0))};break}L.get=M}if(F50){let q=[],F=[],x=0,c;for(let B of v){if($.alwaysLazyProperty&&$.alwaysLazyProperty(B.key)){c=!0;continue}Object.defineProperty(G,B.key,{get:gb1(B.get),enumerable:!0});let j="v"+x++;F.push(j),q.push("o["+JSON.stringify(B.key)+"]="+j+"(s)")}if(c)q.push("__proto__:this");let w=new Function(...F,"var c=this;return function(s){var o=new c();"+q.join(";")+";return o;}").apply(W,v.map((B)=>B.get));Object.defineProperty(G,"toJSON",{value(B){return w.call(this,this[HT])}})}else Object.defineProperty(G,"toJSON",{value(q){let F={};for(let x=0,c=v.length;x<c;x++){let w=v[x].key;F[w]=this[w]}return F}})}var z=new K;return z[HT]={bytes:Z,position:J,srcString:"",bytesEnd:X},z}function d3(Z){switch(Z){case 246:return null;case 247:return;case 248:return!1;case 249:return!0}throw new Error("Unknown constant")}function gb1(Z){return function(){return Z(this[HT])}}function db1(){if(c7)c7.bytes=Uint8Array.prototype.slice.call(c7.bytes,c7.position,c7.bytesEnd),c7.position=0,c7.bytesEnd=c7.bytes.length}function ab1(Z,J){if(J.typedStructs){let $=new Map;$.set("named",Z),$.set("typed",J.typedStructs),Z=$}let X=J.lastTypedStructuresLength||0;return Z.isCompatible=($)=>{let Y=!0;if($ instanceof Map){if(($.get("named")||[]).length!==(J.lastNamedStructuresLength||0))Y=!1;if(($.get("typed")||[]).length!==X)Y=!1}else if($ instanceof Array||Array.isArray($)){if($.length!==(J.lastNamedStructuresLength||0))Y=!1}if(!Y)J._mergeStructures($);return Y},J.lastTypedStructuresLength=J.typedStructs&&J.typedStructs.length,Z}$50(ib1,pb1,db1);var ob1=process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED!==void 0&&process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED.toLowerCase()==="true";if(!ob1){let Z;try{if(Z=g("msgpackr-extract"),Z)r60(Z.extractStrings)}catch(J){}}var YU=t(WY0(),1);import Ua1 from"http";import Ba1 from"https";import $U from"fs";import ja1 from"path";import La1 from"url";var GY0=`-----BEGIN CERTIFICATE-----
406
406
  MIIDRjCCAi6gAwIBAgIFOTEzNTIwDQYJKoZIhvcNAQELBQAwWDEQMA4GA1UEAxMH
407
407
  SFlUT1BJQTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0b24xEDAOBgNV
408
408
  BAcTB1NlYXR0bGUxEDAOBgNVBAoTB0hZVE9QSUEwHhcNMjQxMTEzMjIyMjEwWhcN
@@ -447,7 +447,7 @@ qYGMwU/HBVHkLAn5XvT2a9xM0mzZ558d+ahbw8qAgRxg7BZ+2PW/bf7F2WRBUk1f
447
447
  xauhAoGBALEspoxQozwohGQnP7EMF0/0JoKNpdNv0b0qCVvNiMo0+N297lI2mFQp
448
448
  6xYlW/1l9afLokklF/J2IsyBrTCZoY7SaEk/lMMrQSyra+y0z71ogZ8A4ny9fxsj
449
449
  0dDYJZGllL+3E/MQfd7k+KnOM/+A+cPoAnci76+L3vdkUb2P8SJk
450
- -----END RSA PRIVATE KEY-----`;var Cf=process.env.PORT??8080,ff="0.10.16",kf;((Y)=>{Y.READY="WEBSERVER.READY";Y.STOPPED="WEBSERVER.STOPPED";Y.ERROR="WEBSERVER.ERROR";Y.UPGRADE="WEBSERVER.UPGRADE"})(kf||={});class FK extends B0{static instance=new FK;_webserver=YU.default();_internalHttpServer;constructor(){super();this._webserver.use((Z,J,X)=>{J.header("Access-Control-Allow-Origin","*"),X()}),this._webserver.get("/",(Z,J)=>{J.json({status:"OK",version:ff,runtime:"node"})}),this._webserver.use(YU.default.static("assets",{dotfiles:"allow"}));try{this._webserver.use(YU.default.static(ja1.dirname(g.resolve("/Users/arkdev/Desktop/HYTOPIA/hytopia/assets/release/index.js")),{dotfiles:"allow"}))}catch{}}start(){if(!this._internalHttpServer)this._internalHttpServer=process.env.NODE_ENV==="production"?Ua1.createServer(this._webserver):Ba1.createServer({key:$U.existsSync("assets/certs/localhost.key")?$U.readFileSync("assets/certs/localhost.key"):zY0,cert:$U.existsSync("assets/certs/localhost.crt")?$U.readFileSync("assets/certs/localhost.crt"):GY0},this._webserver),this._internalHttpServer.on("upgrade",this._onUpgrade),this._internalHttpServer.on("error",this._onError),this._internalHttpServer.on("close",this._onStopped);else p.warning("WebServer.start(): server already started!");this._internalHttpServer.listen(Cf,this._onStarted),console.info(`WebServer.start(): Server running on port ${Cf}.`)}stop(){if(this._internalHttpServer)return new Promise((Z,J)=>{this._internalHttpServer.close((X)=>{if(X)J(X);else Z(!0)})});else return p.warning("WebServer.stop(): server not started."),Promise.resolve(!1)}_onStarted=()=>{this.emitWithGlobal("WEBSERVER.READY",{})};_onUpgrade=async(Z,J,X)=>{let $=La1.parse(Z.url??"",!0).query,Y=$.connectionId?.toString(),Q=$.sessionToken?.toString()??"";if(Y&&M7.instance.isValidConnectionId(Y))Z.connectionId=Y;else{let K=await O4.instance.getPlayerSession(Q);if(K?.error){let W=`${K.error.code}: ${K.error.message}`;J.write(`HTTP/1.1 401 Unauthorized\r
450
+ -----END RSA PRIVATE KEY-----`;var Cf=process.env.PORT??8080,ff="0.10.17",kf;((Y)=>{Y.READY="WEBSERVER.READY";Y.STOPPED="WEBSERVER.STOPPED";Y.ERROR="WEBSERVER.ERROR";Y.UPGRADE="WEBSERVER.UPGRADE"})(kf||={});class FK extends B0{static instance=new FK;_webserver=YU.default();_internalHttpServer;constructor(){super();this._webserver.use((Z,J,X)=>{J.header("Access-Control-Allow-Origin","*"),X()}),this._webserver.get("/",(Z,J)=>{J.json({status:"OK",version:ff,runtime:"node"})}),this._webserver.use(YU.default.static("assets",{dotfiles:"allow"}));try{this._webserver.use(YU.default.static(ja1.dirname(g.resolve("/Users/arkdev/Desktop/HYTOPIA/hytopia/assets/release/index.js")),{dotfiles:"allow"}))}catch{}}start(){if(!this._internalHttpServer)this._internalHttpServer=process.env.NODE_ENV==="production"?Ua1.createServer(this._webserver):Ba1.createServer({key:$U.existsSync("assets/certs/localhost.key")?$U.readFileSync("assets/certs/localhost.key"):zY0,cert:$U.existsSync("assets/certs/localhost.crt")?$U.readFileSync("assets/certs/localhost.crt"):GY0},this._webserver),this._internalHttpServer.on("upgrade",this._onUpgrade),this._internalHttpServer.on("error",this._onError),this._internalHttpServer.on("close",this._onStopped);else p.warning("WebServer.start(): server already started!");this._internalHttpServer.listen(Cf,this._onStarted),console.info(`WebServer.start(): Server running on port ${Cf}.`)}stop(){if(this._internalHttpServer)return new Promise((Z,J)=>{this._internalHttpServer.close((X)=>{if(X)J(X);else Z(!0)})});else return p.warning("WebServer.stop(): server not started."),Promise.resolve(!1)}_onStarted=()=>{this.emitWithGlobal("WEBSERVER.READY",{})};_onUpgrade=async(Z,J,X)=>{let $=La1.parse(Z.url??"",!0).query,Y=$.connectionId?.toString(),Q=$.sessionToken?.toString()??"";if(Y&&M7.instance.isValidConnectionId(Y))Z.connectionId=Y;else{let K=await O4.instance.getPlayerSession(Q);if(K?.error){let W=`${K.error.code}: ${K.error.message}`;J.write(`HTTP/1.1 401 Unauthorized\r
451
451
  Content-Type: text/plain\r
452
452
  Content-Length: ${W.length}\r
453
453
  Connection: close\r
@@ -480,4 +480,4 @@ ${Y.stack}`:"unknown"}}}}}var is1=(Z={})=>{let J=Z.limit??Ss1;return{name:As1,pr
480
480
  `),F=q.shift();if(!F)return Z.destroy(),X(new Error("No header received from proxy CONNECT response"));let x=F.split(" "),c=+(x[1]||0),w=x.slice(2).join(" "),B={};for(let j of q){if(!j)continue;let L=j.indexOf(":");if(L===-1)return Z.destroy(),X(new Error(`Invalid header from proxy CONNECT response: "${j}"`));let R=j.slice(0,L).toLowerCase(),M=j.slice(L+1).trimStart(),N=B[R];if(typeof N==="string")B[R]=[N,M];else if(Array.isArray(N))N.push(M);else B[R]=M}kj("got proxy server response: %o %o",F,B),K(),J({connect:{statusCode:c,statusText:w,headers:B},buffered:H})}Z.on("error",G),Z.on("end",W),Q()})}function UH(...Z){u.log("[https-proxy-agent]",...Z)}class Ej extends pS{static __initStatic(){this.protocols=["http","https"]}constructor(Z,J){super(J);this.options={},this.proxy=typeof Z==="string"?new URL(Z):Z,this.proxyHeaders=J?.headers??{},UH("Creating new HttpsProxyAgent instance: %o",this.proxy.href);let X=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),$=this.proxy.port?parseInt(this.proxy.port,10):this.proxy.protocol==="https:"?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...J?C31(J,"headers"):null,host:X,port:$}}async connect(Z,J){let{proxy:X}=this;if(!J.host)throw new TypeError('No "host" provided');let $;if(X.protocol==="https:"){UH("Creating `tls.Socket`: %o",this.connectOpts);let H=this.connectOpts.servername||this.connectOpts.host;$=iS.connect({...this.connectOpts,servername:H&&jJ.isIP(H)?void 0:H})}else UH("Creating `net.Socket`: %o",this.connectOpts),$=jJ.connect(this.connectOpts);let Y=typeof this.proxyHeaders==="function"?this.proxyHeaders():{...this.proxyHeaders},Q=jJ.isIPv6(J.host)?`[${J.host}]`:J.host,K=`CONNECT ${Q}:${J.port} HTTP/1.1\r
481
481
  `;if(X.username||X.password){let H=`${decodeURIComponent(X.username)}:${decodeURIComponent(X.password)}`;Y["Proxy-Authorization"]=`Basic ${Buffer.from(H).toString("base64")}`}if(Y.Host=`${Q}:${J.port}`,!Y["Proxy-Connection"])Y["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close";for(let H of Object.keys(Y))K+=`${H}: ${Y[H]}\r
482
482
  `;let W=T31($);$.write(`${K}\r
483
- `);let{connect:G,buffered:z}=await W;if(Z.emit("proxyConnect",G),this.emit("proxyConnect",G,Z),G.statusCode===200){if(Z.once("socket",BJ6),J.secureEndpoint){UH("Upgrading socket connection to TLS");let H=J.servername||J.host;return iS.connect({...C31(J,"host","path","port"),socket:$,servername:jJ.isIP(H)?void 0:H})}return $}$.destroy();let v=new jJ.Socket({writable:!1});return v.readable=!0,Z.once("socket",(H)=>{UH("Replaying proxy buffer for failed request"),H.push(z),H.push(null)}),v}}Ej.__initStatic();function BJ6(Z){Z.resume()}function C31(Z,...J){let X={},$;for($ in Z)if(!J.includes($))X[$]=Z[$];return X}var RJ6=32768;function NJ6(Z){return new DJ6({read(){this.push(Z),this.push(null)}})}function Ij(Z){let J;try{J=new URL(Z.url)}catch(G){return t1(()=>{console.warn("[@sentry/node]: Invalid dsn or tunnel option, will not send any events. The tunnel option must be a full URL when used.")}),CK(Z,()=>Promise.resolve({}))}let X=J.protocol==="https:",$=OJ6(J,Z.proxy||(X?process.env.https_proxy:void 0)||process.env.http_proxy),Y=X?LJ6:jJ6,Q=Z.keepAlive===void 0?!1:Z.keepAlive,K=$?new Ej($):new Y.Agent({keepAlive:Q,maxSockets:30,timeout:2000}),W=PJ6(Z,Z.httpModule??Y,K);return CK(Z,W)}function OJ6(Z,J){let{no_proxy:X}=process.env;if(X?.split(",").some((Y)=>Z.host.endsWith(Y)||Z.hostname.endsWith(Y)))return;else return J}function PJ6(Z,J,X){let{hostname:$,pathname:Y,port:Q,protocol:K,search:W}=new URL(Z.url);return function G(z){return new Promise((v,H)=>{mv(()=>{let V=NJ6(z.body),q={...Z.headers};if(z.body.length>RJ6)q["content-encoding"]="gzip",V=V.pipe(MJ6());let F=J.request({method:"POST",agent:X,headers:q,hostname:$,path:`${Y}${W}`,port:Q,protocol:K,ca:Z.caCerts},(x)=>{x.on("data",()=>{}),x.on("end",()=>{}),x.setEncoding("utf8");let c=x.headers["retry-after"]??null,w=x.headers["x-sentry-rate-limits"]??null;v({statusCode:x.statusCode,headers:{"retry-after":c,"x-sentry-rate-limits":Array.isArray(w)?w[0]||null:w}})});F.on("error",H),V.pipe(F)})})}}var TJ6=new Set(["false","f","n","no","off","0"]),CJ6=new Set(["true","t","y","yes","on","1"]);function _j(Z,J){let X=String(Z).toLowerCase();if(TJ6.has(X))return!1;if(CJ6.has(X))return!0;return J?.strict?null:Boolean(Z)}import{posix as fJ6,sep as kJ6}from"node:path";function f31(Z){return Z.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}function bj(Z=process.argv[1]?ok(process.argv[1]):process.cwd(),J=kJ6==="\\"){let X=J?f31(Z):Z;return($)=>{if(!$)return;let Y=J?f31($):$,{dir:Q,base:K,ext:W}=fJ6.parse(Y);if(W===".js"||W===".mjs"||W===".cjs")K=K.slice(0,W.length*-1);let G=decodeURIComponent(K);if(!Q)Q=".";let z=Q.lastIndexOf("/node_modules");if(z>-1)return`${Q.slice(z+14).replace(/\//g,".")}:${G}`;if(Q.startsWith(X)){let v=Q.slice(X.length+1).replace(/\//g,".");return v?`${v}:${G}`:G}return G}}function hj(Z){if(process.env.SENTRY_RELEASE)return process.env.SENTRY_RELEASE;if(U0.SENTRY_RELEASE?.id)return U0.SENTRY_RELEASE.id;let J=process.env.GITHUB_SHA||process.env.CI_MERGE_REQUEST_SOURCE_BRANCH_SHA||process.env.CI_BUILD_REF||process.env.CI_COMMIT_SHA||process.env.BITBUCKET_COMMIT,X=process.env.APPVEYOR_PULL_REQUEST_HEAD_COMMIT||process.env.APPVEYOR_REPO_COMMIT||process.env.CODEBUILD_RESOLVED_SOURCE_VERSION||process.env.AWS_COMMIT_ID||process.env.BUILD_SOURCEVERSION||process.env.GIT_CLONE_COMMIT_HASH||process.env.BUDDY_EXECUTION_REVISION||process.env.BUILDKITE_COMMIT||process.env.CIRCLE_SHA1||process.env.CIRRUS_CHANGE_IN_REPO||process.env.CF_REVISION||process.env.CM_COMMIT||process.env.CF_PAGES_COMMIT_SHA||process.env.DRONE_COMMIT_SHA||process.env.FC_GIT_COMMIT_SHA||process.env.HEROKU_TEST_RUN_COMMIT_VERSION||process.env.HEROKU_SLUG_COMMIT||process.env.RAILWAY_GIT_COMMIT_SHA||process.env.RENDER_GIT_COMMIT||process.env.SEMAPHORE_GIT_SHA||process.env.TRAVIS_PULL_REQUEST_SHA||process.env.VERCEL_GIT_COMMIT_SHA||process.env.VERCEL_GITHUB_COMMIT_SHA||process.env.VERCEL_GITLAB_COMMIT_SHA||process.env.VERCEL_BITBUCKET_COMMIT_SHA||process.env.ZEIT_GITHUB_COMMIT_SHA||process.env.ZEIT_GITLAB_COMMIT_SHA||process.env.ZEIT_BITBUCKET_COMMIT_SHA,$=process.env.CI_COMMIT_ID||process.env.SOURCE_COMMIT||process.env.SOURCE_VERSION||process.env.GIT_COMMIT||process.env.COMMIT_REF||process.env.BUILD_VCS_NUMBER||process.env.CI_COMMIT_SHA;return J||X||$||Z}var Sj=xU(GE(bj()));var E31=t($0(),1),I31=t(Q1(),1);import*as k31 from"node:os";import{threadId as EJ6,isMainThread as IJ6}from"worker_threads";var _J6=60000;class BH extends fU{constructor(Z){let J=Z.serverName||global.process.env.SENTRY_NAME||k31.hostname(),X={...Z,platform:"node",runtime:{name:"node",version:global.process.version},serverName:J};if(Z.openTelemetryInstrumentations)I31.registerInstrumentations({instrumentations:Z.openTelemetryInstrumentations});lk(X,"node"),u.log(`Initializing Sentry: process: ${process.pid}, thread: ${IJ6?"main":`worker-${EJ6}`}.`);super(X);if(this.getOptions()._experiments?.enableLogs){if(this._logOnExitFlushListener=()=>{MX(this)},J)this.on("beforeCaptureLog",($)=>{$.attributes={...$.attributes,"server.address":J}});process.on("beforeExit",this._logOnExitFlushListener)}}get tracer(){if(this._tracer)return this._tracer;let Z="@sentry/node",J=Q8,X=E31.trace.getTracer(Z,J);return this._tracer=X,X}async flush(Z){let X=this.traceProvider?.activeSpanProcessor;if(X)await X.forceFlush();if(this.getOptions().sendClientReports)this._flushOutcomes();return super.flush(Z)}close(Z){if(this._clientReportInterval)clearInterval(this._clientReportInterval);if(this._clientReportOnExitFlushListener)process.off("beforeExit",this._clientReportOnExitFlushListener);if(this._logOnExitFlushListener)process.off("beforeExit",this._logOnExitFlushListener);return super.close(Z)}startClientReportTracking(){let Z=this.getOptions();if(Z.sendClientReports)this._clientReportOnExitFlushListener=()=>{this._flushOutcomes()},this._clientReportInterval=setInterval(()=>{A0&&u.log("Flushing client reports based on interval."),this._flushOutcomes()},Z.clientReportFlushInterval??_J6).unref(),process.on("beforeExit",this._clientReportOnExitFlushListener)}_getTraceInfoFromScope(Z){if(!Z)return[void 0,void 0];return e61(this,Z)}}var n9=t($0(),1),_31=t(Nb(),1),b31=t(Tb(),1),jW=t(U1(),1);var h31=t(S_(),1);import bJ6 from"module";var gS=1e6;function Aj(Z,J={}){if(Z.getOptions().debug)A31();let X=SJ6(Z,J);Z.traceProvider=X}function dS(){let[Z=0,J=0]=process.versions.node.split(".").map(Number);if(Z>=21||Z===20&&J>=6||Z===18&&J>=19){if(!U0._sentryEsmLoaderHookRegistered)try{let{addHookMessagePort:X}=h31.createAddHookMessageChannel();bJ6.register("import-in-the-middle/hook.mjs",import.meta.url,{data:{addHookMessagePort:X,include:[]},transferList:[X]})}catch(X){u.warn("Failed to register ESM hook",X)}}else t1(()=>{console.warn(`[Sentry] You are using Node.js v${process.versions.node} in ESM mode ("import syntax"). The Sentry Node.js SDK is not compatible with ESM in Node.js versions before 18.19.0 or before 20.6.0. Please either build your application with CommonJS ("require() syntax"), or upgrade your Node.js version.`)})}function S31(Z={}){let{debug:J}=Z;if(J)u.enable(),A31();if(!e4())dS();hJ6(Z.integrations).forEach((X)=>{if(X(),J)u.log(`[Sentry] Preloaded ${X.id} instrumentation`)})}function hJ6(Z){let J=P31();if(!Z)return J;return J.filter((X)=>Z.includes(X.id))}function SJ6(Z,J={}){let X=new b31.BasicTracerProvider({sampler:new nb(Z),resource:new _31.Resource({[jW.ATTR_SERVICE_NAME]:"node",[jW.SEMRESATTRS_SERVICE_NAMESPACE]:"sentry",[jW.ATTR_SERVICE_VERSION]:Q8}),forceFlushTimeoutMillis:500,spanProcessors:[new ab({timeout:AJ6(Z.getOptions().maxSpanWaitDuration)}),...J.spanProcessors||[]]});return n9.trace.setGlobalTracerProvider(X),n9.propagation.setGlobalPropagator(new yb),n9.context.setGlobalContextManager(new Cj),X}function AJ6(Z){if(Z==null)return;if(Z>gS)return A0&&u.warn(`\`maxSpanWaitDuration\` is too high, using the maximum value of ${gS}`),gS;else if(Z<=0||Number.isNaN(Z)){A0&&u.warn("`maxSpanWaitDuration` must be a positive number, using default value instead.");return}return Z}function A31(){let Z=new Proxy(u,{get(J,X,$){return Reflect.get(J,X==="verbose"?"debug":X,$)}});n9.diag.disable(),n9.diag.setLogger(Z,n9.DiagLogLevel.DEBUG)}function mJ6(){return e4()?[LB()]:[]}function aS(){return[nv(),av(),sv(),ov(),rv(),zB(),qB(),DB(),MB(),wB(),jB(),cB(),Pj(),O31(),...mJ6()]}function nS(Z){return[...aS(),...s6(Z)?fj():[]]}function mj(Z={}){return u31(Z,nS)}function m31(Z={}){return u31(Z,()=>[])}function u31(Z={},J){let X=uJ6(Z,J);if(X.debug===!0)if(A0)u.enable();else t1(()=>{console.warn("[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.")});if(!e4()&&X.registerEsmLoaderHooks!==!1)dS();if(QB(),i0().update(X.initialScope),X.spotlight&&!X.integrations.some(({name:Q})=>Q===CS))X.integrations.push(xj({sidecarUrl:typeof X.spotlight==="string"?X.spotlight:void 0}));let Y=new BH(X);if(i0().setClient(Y),Y.init(),u.log(`Running in ${e4()?"CommonJS":"ESM"} mode.`),Y.startClientReportTracking(),pJ6(),!X.skipOpenTelemetrySetup)Aj(Y,{spanProcessors:X.openTelemetrySpanProcessors}),sS();return i61(Y),Z51(Y),Y}function sS(){if(!A0)return;let Z=n61(),J=["SentryContextManager","SentryPropagator"];if(s6())J.push("SentrySpanProcessor");for(let X of J)if(!Z.includes(X))u.error(`You have to set up the ${X}. Without this, the OpenTelemetry & Sentry integration will not work properly.`);if(!Z.includes("SentrySampler"))u.warn("You have to set up the SentrySampler. Without this, the OpenTelemetry & Sentry integration may still work, but sample rates set for the Sentry SDK will not be respected. If you use a custom sampler, make sure to use `wrapSamplingDecision`.")}function uJ6(Z,J){let X=lJ6(Z.release),$=Z.spotlight??_j(process.env.SENTRY_SPOTLIGHT,{strict:!0})??process.env.SENTRY_SPOTLIGHT,Y=yJ6(Z.tracesSampleRate),Q={...Z,dsn:Z.dsn??process.env.SENTRY_DSN,environment:Z.environment??process.env.SENTRY_ENVIRONMENT,sendClientReports:Z.sendClientReports??!0,transport:Z.transport??Ij,stackParser:rf(Z.stackParser||Sj),release:X,tracesSampleRate:Y,spotlight:$,debug:_j(Z.debug??process.env.SENTRY_DEBUG)},K=Z.integrations,W=Z.defaultIntegrations??J(Q);return{...Q,integrations:fk({defaultIntegrations:W,integrations:K})}}function lJ6(Z){if(Z!==void 0)return Z;let J=hj();if(J!==void 0)return J;return}function yJ6(Z){if(Z!==void 0)return Z;let J=process.env.SENTRY_TRACES_SAMPLE_RATE;if(!J)return;let X=parseFloat(J);return isFinite(X)?X:void 0}function pJ6(){if(_j(process.env.SENTRY_USE_ENVIRONMENT)!==!1){let Z=process.env.SENTRY_TRACE,J=process.env.SENTRY_BAGGAGE,X=fY(Z,J);i0().setPropagationContext(X)}}var iJ6=[["january","1"],["february","2"],["march","3"],["april","4"],["may","5"],["june","6"],["july","7"],["august","8"],["september","9"],["october","10"],["november","11"],["december","12"],["jan","1"],["feb","2"],["mar","3"],["apr","4"],["may","5"],["jun","6"],["jul","7"],["aug","8"],["sep","9"],["oct","10"],["nov","11"],["dec","12"],["sunday","0"],["monday","1"],["tuesday","2"],["wednesday","3"],["thursday","4"],["friday","5"],["saturday","6"],["sun","0"],["mon","1"],["tue","2"],["wed","3"],["thu","4"],["fri","5"],["sat","6"]];function OQ(Z){return iJ6.reduce((J,[X,$])=>J.replace(new RegExp(X,"gi"),$),Z)}var l31="Automatic instrumentation of CronJob only supports crontab string";function y31(Z,J){let X=!1;return new Proxy(Z,{construct($,Y){let[Q,K,W,G,z,...v]=Y;if(typeof Q!=="string")throw new Error(l31);if(X)throw new Error(`A job named '${J}' has already been scheduled`);X=!0;let H=OQ(Q);async function V(q,F){return N7(J,async()=>{try{await K(q,F)}catch(x){throw V1(x),x}},{schedule:{type:"crontab",value:H},timezone:z||void 0})}return new $(Q,V,W,G,z,...v)},get($,Y){if(Y==="from")return(Q)=>{let{cronTime:K,onTick:W,timeZone:G}=Q;if(typeof K!=="string")throw new Error(l31);if(X)throw new Error(`A job named '${J}' has already been scheduled`);X=!0;let z=OQ(K);return Q.onTick=async(v,H)=>{return N7(J,async()=>{try{await W(v,H)}catch(V){throw V1(V),V}},{schedule:{type:"crontab",value:z},timezone:G||void 0})},$.from(Q)};else return $[Y]}})}function p31(Z){return new Proxy(Z,{get(J,X){if(X==="schedule"&&J.schedule)return new Proxy(J.schedule,{apply($,Y,Q){let[K,W,G]=Q,z=G?.name,v=G?.timezone;if(!z)throw new Error('Missing "name" for scheduled job. A name is required for Sentry check-in monitoring.');let H=async()=>{return N7(z,async()=>{try{return await W()}catch(V){throw V1(V),V}},{schedule:{type:"crontab",value:OQ(K)},timezone:v})};return $.apply(Y,[K,H,G])}});else return J[X]}})}function i31(Z){return new Proxy(Z,{get(J,X){if(X==="scheduleJob")return new Proxy(J.scheduleJob,{apply($,Y,Q){let[K,W,G]=Q;if(typeof K!=="string"||typeof W!=="string"||typeof G!=="function")throw new Error("Automatic instrumentation of 'node-schedule' requires the first parameter of 'scheduleJob' to be a job name string and the second parameter to be a crontab string");let z=K,v=W;async function H(){return N7(z,async()=>{await G?.()},{schedule:{type:"crontab",value:OQ(v)}})}return $.apply(Y,[z,v,H])}});return J[X]}})}var g31={instrumentCron:y31,instrumentNodeCron:p31,instrumentNodeSchedule:i31};var PQ;((x)=>{x.BUILD_PACKETS="build_packets";x.ENTITIES_EMIT_UPDATES="entities_emit_updates";x.ENTITIES_TICK="entities_tick";x.NETWORK_SYNCHRONIZE="network_synchronize";x.NETWORK_SYNCHRONIZE_CLEANUP="network_synchronize_cleanup";x.PHYSICS_CLEANUP="physics_cleanup";x.PHYSICS_STEP="physics_step";x.SEND_ALL_PACKETS="send_all_packets";x.SEND_PACKETS="send_packets";x.SERIALIZE_FREE_BUFFERS="serialize_free_buffers";x.SERIALIZE_PACKETS="serialize_packets";x.SERIALIZE_PACKETS_ENCODE="serialize_packets_encode";x.SIMULATION_STEP="simulation_step";x.TICKER_TICK="ticker_tick";x.WORLD_TICK="world_tick"})(PQ||={});class V8{static getProcessStats(Z=!1){let J=process.memoryUsage(),X={jsHeapSizeMb:{value:J.heapUsed/1024/1024,unit:"megabyte"},jsHeapCapacityMb:{value:J.heapTotal/1024/1024,unit:"megabyte"},jsHeapUsagePercent:{value:J.heapUsed/J.heapTotal,unit:"percent"},processHeapSizeMb:{value:J.heapUsed/1024/1024,unit:"megabyte"},rssSizeMb:{value:J.rss/1024/1024,unit:"megabyte"}};if(Z)return X;return Object.fromEntries(Object.entries(X).map(([$,Y])=>[$,Y.value]))}static initializeSentry(Z,J=50){mj({dsn:Z,release:ff,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=V8.getProcessStats(),X},beforeSendTransaction:(X)=>{if(X.contexts?.trace?.op==="ticker_tick"){let Y=X?.start_timestamp,Q=X?.timestamp;if(!Y||!Q)return null;if((Q-Y)*1000>J)return X.measurements=V8.getProcessStats(!0),X}return null}})}static startSpan(Z,J){if(iv())return A4({attributes:Z.attributes,name:Z.operation,op:Z.operation},J);else return J()}static sentry(){return oS}}var d31=new YY({useFloat32:iz.ALWAYS}),dJ6=5000;class C9 extends B0{static _cachedPacketsSerializedBuffer=new Map;_closeTimeout=null;_wrtcDirectTransport=null;_wrtcClientServerTransport=null;_wrtcClientServerDataProducers=[];_wrtcClientServerDataConsumers=[];_wrtcServerClientTransport=null;_wrtcServerClientReliableDataProducer=null;_wrtcServerClientUnreliableDataProducer=null;_wrtcServerClientDataConsumers=[];_ws;id;constructor(Z,J){super();this.id=h60(),this.onPacket(Y0.PacketId.CONNECTION,this._onConnectionPacket),this.onPacket(Y0.PacketId.HEARTBEAT,this._onHeartbeatPacket),this.bindWs(Z),B0.globalInstance.emit("CONNECTION.OPENED",{connection:this,req:J})}static clearCachedPacketsSerializedBuffers(){if(C9._cachedPacketsSerializedBuffer.size>0)C9._cachedPacketsSerializedBuffer.clear()}static serializePackets(Z){for(let X of Z)if(!Y0.isValidPacket(X))return p.error(`Connection.serializePackets(): Invalid packet payload: ${JSON.stringify(X)}`);let J=C9._cachedPacketsSerializedBuffer.get(Z);if(J)return J;return V8.startSpan({operation:"serialize_packets",attributes:{packets:Z.length,packetIds:Z.map((X)=>X[0]).join(",")}},(X)=>{let $=d31.pack(Z);if($.byteLength>65536)$=gJ6($,{level:1});return X?.setAttribute("serializedBytes",$.byteLength),C9._cachedPacketsSerializedBuffer.set(Z,$),$})}bindWs(Z){let J=!!this._ws;if(J&&this._closeTimeout)clearTimeout(this._closeTimeout),this._closeTimeout=null;if(this._ws)this._ws.onmessage=()=>{},this._ws.onclose=()=>{},this._ws.onerror=()=>{},this.send([Y0.createPacket(Y0.bidirectionalPackets.connectionPacketDefinition,{k:!0})]);if(this._ws=Z,this._ws.binaryType="nodebuffer",this._ws.onmessage=(X)=>this._onMessage(X.data),this._ws.onclose=this._onWsClose,this._ws.onerror=this._onWsError,this.send([Y0.createPacket(Y0.bidirectionalPackets.connectionPacketDefinition,{i:this.id})],!0,!0),J)this.emitWithGlobal("CONNECTION.RECONNECTED",{connection:this});if(M7.instance.isWrtcEnabled)this._upgradeToWRTC()}closeWrtc(){this._closeWrtcClientServerTransport(),this._closeWrtcServerClientTransport()}disconnect(){if(this._ws.readyState!==r$.default.OPEN)return;try{this._ws.close()}catch(Z){p.error(`Connection.disconnect(): Connection disconnect failed. Error: ${Z}`)}}onPacket(Z,J){this.on("CONNECTION.PACKET_RECEIVED",({packet:X})=>{if(X[0]===Z)J(X)})}send(Z,J=!0,X=!1){if(this._closeTimeout)return;if(this._ws.readyState!==r$.default.OPEN)return;if(!J&&this._ws.bufferedAmount>4096)return;V8.startSpan({operation:"send_packets",attributes:{forceWs:X?"true":"false",wrtcConnected:this._wrtcServerClientTransport?.iceState==="completed"?"true":"false"}},()=>{try{let $=C9.serializePackets(Z);if(!$)return;if(this._wrtcServerClientTransport?.iceState==="completed"&&$.length<(this._wrtcServerClientTransport?.sctpParameters?.maxMessageSize??0)&&!X)try{(J?this._wrtcServerClientReliableDataProducer:this._wrtcServerClientUnreliableDataProducer).send($)}catch{this._ws.send($)}else this._ws.send($);this.emitWithGlobal("CONNECTION.PACKETS_SENT",{connection:this,packets:Z})}catch($){p.error(`Connection.send(): Packet send failed. Error: ${$}`)}})}_closeWrtcClientServerTransport(){this._wrtcDirectTransport?.close(),this._wrtcDirectTransport=null,this._wrtcClientServerTransport?.close(),this._wrtcClientServerTransport=null,this._wrtcClientServerDataProducers.forEach((Z)=>Z.close()),this._wrtcClientServerDataProducers=[],this._wrtcClientServerDataConsumers.forEach((Z)=>Z.close()),this._wrtcClientServerDataConsumers=[]}_closeWrtcServerClientTransport(){this._wrtcServerClientTransport?.close(),this._wrtcServerClientTransport=null,this._wrtcServerClientDataConsumers.forEach((Z)=>Z.close()),this._wrtcServerClientDataConsumers=[],this._wrtcServerClientReliableDataProducer?.close(),this._wrtcServerClientReliableDataProducer=null,this._wrtcServerClientUnreliableDataProducer?.close(),this._wrtcServerClientUnreliableDataProducer=null}_onConnectionPacket=async(Z)=>{let J=Z[1],X=J.c,$=J.d;if(X){let{i:Y,d:Q}=X,K=!1;if(Y==this._wrtcClientServerTransport?.id)await this._wrtcClientServerTransport.connect({dtlsParameters:Q}),K=!0;if(Y==this._wrtcServerClientTransport?.id)await this._wrtcServerClientTransport.connect({dtlsParameters:Q}),K=!0;if(K)this.send([Y0.createPacket(Y0.bidirectionalPackets.connectionPacketDefinition,{ca:{i:Y}})])}if($)for(let Y of $){let{s:Q,l:K}=Y,W=await this._wrtcClientServerTransport.produceData({label:K,sctpStreamParameters:Q}),G=await this._wrtcDirectTransport.consumeData({dataProducerId:W.id});this._wrtcClientServerDataProducers.push(W),this._wrtcClientServerDataConsumers.push(G),G.on("message",(z)=>this._onMessage(z)),this.send([Y0.createPacket(Y0.bidirectionalPackets.connectionPacketDefinition,{pa:{i:W.id,l:K}})])}};_onHeartbeatPacket=()=>{this.send([Y0.createPacket(Y0.bidirectionalPackets.heartbeatPacketDefinition,null)],!0,!0)};_onMessage=(Z)=>{try{let J=this._deserialize(Z);if(!J)return;this.emitWithGlobal("CONNECTION.PACKET_RECEIVED",{connection:this,packet:J})}catch(J){p.error(`Connection._ws.onmessage(): Error: ${J}`)}};_onWrtcIceStateChange=(Z,J)=>{if(["disconnected","closed"].includes(J)){if(Z==this._wrtcClientServerTransport)this._closeWrtcClientServerTransport();else if(Z==this._wrtcServerClientTransport)this._closeWrtcServerClientTransport()}};_onWsClose=()=>{this.closeWrtc(),this.emitWithGlobal("CONNECTION.DISCONNECTED",{connection:this}),this._closeTimeout=setTimeout(()=>{this.emitWithGlobal("CONNECTION.CLOSED",{connection:this}),this.offAll()},dJ6)};_onWsError=(Z)=>{this.emitWithGlobal("CONNECTION.ERROR",{connection:this,error:Z})};_upgradeToWRTC=async()=>{let Z=await M7.instance.createWrtcTransports();if(!Z)return!1;let{directTransport:J,clientServerTransport:X,serverClientTransport:$}=Z;this._wrtcDirectTransport=J,this._wrtcClientServerTransport=X,this._wrtcClientServerTransport.on("icestatechange",(K)=>{this._onWrtcIceStateChange(this._wrtcClientServerTransport,K)}),this._wrtcServerClientTransport=$,this._wrtcServerClientTransport.on("icestatechange",(K)=>{this._onWrtcIceStateChange(this._wrtcServerClientTransport,K)}),this._wrtcServerClientReliableDataProducer=await this._wrtcServerClientTransport.produceData({label:"scr",sctpStreamParameters:{streamId:0,ordered:!0}}),this._wrtcServerClientUnreliableDataProducer=await this._wrtcServerClientTransport.produceData({label:"scu",sctpStreamParameters:{streamId:1,ordered:!1,maxPacketLifeTime:35}});let Y=await this._wrtcServerClientTransport.consumeData({dataProducerId:this._wrtcServerClientReliableDataProducer.id}),Q=await this._wrtcServerClientTransport.consumeData({dataProducerId:this._wrtcServerClientUnreliableDataProducer.id});return this._wrtcServerClientDataConsumers.push(Y,Q),this.send([Y0.createPacket(Y0.bidirectionalPackets.connectionPacketDefinition,{d:[{i:Y.id,pi:Y.dataProducerId,l:"scr",s:Y.sctpStreamParameters},{i:Q.id,pi:Q.dataProducerId,l:"scu",s:Q.sctpStreamParameters}],t:[{i:this._wrtcClientServerTransport.id,f:"cs",d:this._wrtcClientServerTransport.dtlsParameters,ic:this._wrtcClientServerTransport.iceCandidates,ip:this._wrtcClientServerTransport.iceParameters,s:this._wrtcClientServerTransport.sctpParameters},{i:this._wrtcServerClientTransport.id,f:"sc",d:this._wrtcServerClientTransport.dtlsParameters,ic:this._wrtcServerClientTransport.iceCandidates,ip:this._wrtcServerClientTransport.iceParameters,s:this._wrtcServerClientTransport.sctpParameters}]})]),!0};_deserialize(Z){let J=d31.unpack(Z);if(!J||typeof J!=="object"||typeof J[0]!=="number")return p.error(`Connection._deserialize(): Invalid packet format. Packet: ${JSON.stringify(J)}`);if(!Y0.isValidPacket(J))return p.error(`Connection._deserialize(): Invalid packet payload. Packet: ${JSON.stringify(J)}`);return J}}class jH{_lights=new Map;_nextLightId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}despawnEntityAttachedLights(Z){this.getAllEntityAttachedLights(Z).forEach((J)=>{J.despawn()})}getAllLights(){return Array.from(this._lights.values())}getAllEntityAttachedLights(Z){return this.getAllLights().filter((J)=>J.attachedToEntity===Z)}registerLight(Z){if(Z.id!==void 0)return Z.id;let J=this._nextLightId;return this._lights.set(J,Z),this._nextLightId++,J}unregisterLight(Z){if(Z.id===void 0)return;this._lights.delete(Z.id)}}class r8{_map=new Map;_values=[];_isDirty=!1;get size(){return this._map.size}get valuesArray(){if(this._isDirty)this._syncArray();return this._values}get(Z){return this._map.get(Z)}set(Z,J){let X=this._map.has(Z);if(this._map.set(Z,J),!X)this._values.push(J);else this._isDirty=!0;return this}has(Z){return this._map.has(Z)}delete(Z){let J=this._map.delete(Z);if(J)this._isDirty=!0;return J}clear(){this._map.clear(),this._values.length=0,this._isDirty=!1}forEach(Z,J){this._map.forEach((X,$)=>{Z.call(J,X,$,this)})}keys(){return this._map.keys()}values(){return this._map.values()}entries(){return this._map.entries()}[Symbol.iterator](){return this._map[Symbol.iterator]()}_syncArray(){this._values.length=0;for(let Z of this._map.values())this._values.push(Z);this._isDirty=!1}}var a31;((X)=>{X[X.POINTLIGHT=0]="POINTLIGHT";X[X.SPOTLIGHT=1]="SPOTLIGHT"})(a31||={});var rS;((V)=>{V.DESPAWN="LIGHT.DESPAWN";V.SET_ANGLE="LIGHT.SET_ANGLE";V.SET_ATTACHED_TO_ENTITY="LIGHT.SET_ATTACHED_TO_ENTITY";V.SET_COLOR="LIGHT.SET_COLOR";V.SET_DISTANCE="LIGHT.SET_DISTANCE";V.SET_INTENSITY="LIGHT.SET_INTENSITY";V.SET_OFFSET="LIGHT.SET_OFFSET";V.SET_PENUMBRA="LIGHT.SET_PENUMBRA";V.SET_POSITION="LIGHT.SET_POSITION";V.SET_TRACKED_ENTITY="LIGHT.SET_TRACKED_ENTITY";V.SET_TRACKED_POSITION="LIGHT.SET_TRACKED_POSITION";V.SPAWN="LIGHT.SPAWN"})(rS||={});class tS extends B0{_id;_angle;_attachedToEntity;_color;_distance;_intensity;_offset;_penumbra;_position;_trackedEntity;_trackedPosition;_type;_world;constructor(Z){if(!!Z.attachedToEntity===!!Z.position)p.fatalError("Either attachedToEntity or position must be set, but not both.");super();p.warning("WARNING: Lights are poorly optimized at this time. Using more than a few lights in your game can cause extremely bad performance (FPS) issues. Use lights sparingly!"),this._angle=Z.angle,this._attachedToEntity=Z.attachedToEntity,this._color=Z.color??{r:255,g:255,b:255},this._distance=Z.distance,this._intensity=Z.intensity??1,this._offset=Z.offset,this._penumbra=Z.penumbra,this._position=Z.position,this._trackedEntity=Z.trackedEntity,this._trackedPosition=Z.trackedPosition,this._type=Z.type??0}get id(){return this._id}get angle(){return this._angle}get attachedToEntity(){return this._attachedToEntity}get color(){return this._color}get distance(){return this._distance}get intensity(){return this._intensity}get isSpawned(){return this._id!==void 0}get offset(){return this._offset}get penumbra(){return this._penumbra}get position(){return this._position}get trackedEntity(){return this._trackedEntity}get trackedPosition(){return this._trackedPosition}get type(){return this._type}get world(){return this._world}setAngle(Z){if(this._angle===Z)return;if(this._angle=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ANGLE",{light:this,angle:Z})}setAttachedToEntity(Z){if(!Z.isSpawned)return p.error(`Light.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);if(this._attachedToEntity===Z)return;if(this._attachedToEntity=Z,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ATTACHED_TO_ENTITY",{light:this,entity:Z})}setColor(Z){if(this._color.r===Z.r&&this._color.g===Z.g&&this._color.b===Z.b)return;if(this._color=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_COLOR",{light:this,color:Z})}setDistance(Z){if(this._distance===Z)return;if(this._distance=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_DISTANCE",{light:this,distance:Z})}setIntensity(Z){if(this._intensity===Z)return;if(this._intensity=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_INTENSITY",{light:this,intensity:Z})}setOffset(Z){if(this._offset&&this._offset.x===Z.x&&this._offset.y===Z.y&&this._offset.z===Z.z)return;if(this._offset=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_OFFSET",{light:this,offset:Z})}setPenumbra(Z){if(this._penumbra===Z)return;if(this._penumbra=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_PENUMBRA",{light:this,penumbra:Z})}setPosition(Z){if(this._position&&this._position.x===Z.x&&this._position.y===Z.y&&this._position.z===Z.z)return;if(this._position=Z,this._attachedToEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_POSITION",{light:this,position:Z})}setTrackedEntity(Z){if(!Z.isSpawned)return p.error(`Light.setTrackedEntity(): Entity ${Z.id} is not spawned!`);if(this._trackedEntity===Z)return;if(this._trackedEntity=Z,this._trackedPosition=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_ENTITY",{light:this,entity:Z})}setTrackedPosition(Z){if(this._trackedPosition===Z)return;if(this._trackedPosition=Z,this._trackedEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_POSITION",{light:this,position:Z})}despawn(){if(!this.isSpawned||!this._world)return;this._world.lightManager.unregisterLight(this),this.emitWithWorld(this._world,"LIGHT.DESPAWN",{light:this}),this._id=void 0,this._world=void 0}spawn(Z){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return p.error(`Light.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning Light!`);this._id=Z.lightManager.registerLight(this),this._world=Z,this.emitWithWorld(Z,"LIGHT.SPAWN",{light:this})}serialize(){return T0.serializeLight(this)}}var eS;((I)=>{I.BURST="PARTICLE_EMITTER.BURST";I.DESPAWN="PARTICLE_EMITTER.DESPAWN";I.SET_ALPHA_TEST="PARTICLE_EMITTER.SET_ALPHA_TEST";I.SET_ATTACHED_TO_ENTITY="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY";I.SET_ATTACHED_TO_ENTITY_NODE_NAME="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME";I.SET_COLOR_END="PARTICLE_EMITTER.SET_COLOR_END";I.SET_COLOR_END_VARIANCE="PARTICLE_EMITTER.SET_COLOR_END_VARIANCE";I.SET_COLOR_START="PARTICLE_EMITTER.SET_COLOR_START";I.SET_COLOR_START_VARIANCE="PARTICLE_EMITTER.SET_COLOR_START_VARIANCE";I.SET_GRAVITY="PARTICLE_EMITTER.SET_GRAVITY";I.SET_LIFETIME="PARTICLE_EMITTER.SET_LIFETIME";I.SET_LIFETIME_VARIANCE="PARTICLE_EMITTER.SET_LIFETIME_VARIANCE";I.SET_MAX_PARTICLES="PARTICLE_EMITTER.SET_MAX_PARTICLES";I.SET_OFFSET="PARTICLE_EMITTER.SET_OFFSET";I.SET_OPACITY_END="PARTICLE_EMITTER.SET_OPACITY_END";I.SET_OPACITY_END_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE";I.SET_OPACITY_START="PARTICLE_EMITTER.SET_OPACITY_START";I.SET_OPACITY_START_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE";I.SET_PAUSED="PARTICLE_EMITTER.SET_PAUSED";I.SET_POSITION="PARTICLE_EMITTER.SET_POSITION";I.SET_POSITION_VARIANCE="PARTICLE_EMITTER.SET_POSITION_VARIANCE";I.SET_RATE="PARTICLE_EMITTER.SET_RATE";I.SET_RATE_VARIANCE="PARTICLE_EMITTER.SET_RATE_VARIANCE";I.SET_SIZE_END="PARTICLE_EMITTER.SET_SIZE_END";I.SET_SIZE_END_VARIANCE="PARTICLE_EMITTER.SET_SIZE_END_VARIANCE";I.SET_SIZE_START="PARTICLE_EMITTER.SET_SIZE_START";I.SET_SIZE_START_VARIANCE="PARTICLE_EMITTER.SET_SIZE_START_VARIANCE";I.SET_TEXTURE_URI="PARTICLE_EMITTER.SET_TEXTURE_URI";I.SET_TRANSPARENT="PARTICLE_EMITTER.SET_TRANSPARENT";I.SET_VELOCITY="PARTICLE_EMITTER.SET_VELOCITY";I.SET_VELOCITY_VARIANCE="PARTICLE_EMITTER.SET_VELOCITY_VARIANCE";I.SPAWN="PARTICLE_EMITTER.SPAWN"})(eS||={});class ZA extends B0{_id;_alphaTest;_attachedToEntity;_attachedToEntityNodeName;_colorEnd;_colorEndVariance;_colorStart;_colorStartVariance;_gravity;_lifetime;_lifetimeVariance;_maxParticles;_offset;_opacityEnd;_opacityEndVariance;_opacityStart;_opacityStartVariance;_paused;_position;_positionVariance;_rate;_rateVariance;_sizeEnd;_sizeEndVariance;_sizeStart;_sizeStartVariance;_sizeVariance;_textureUri;_transparent;_velocity;_velocityVariance;_world;constructor(Z){if(!!Z.attachedToEntity===!!Z.position)p.fatalError("Either attachedToEntity or position must be set, but not both.");if(!Z.textureUri)p.fatalError("ParticleEmitter.constructor(): textureUri must be provided.");super();this._alphaTest=Z.alphaTest??0.05,this._attachedToEntity=Z.attachedToEntity,this._attachedToEntityNodeName=Z.attachedToEntityNodeName,this._colorEnd=Z.colorEnd,this._colorEndVariance=Z.colorEndVariance,this._colorStart=Z.colorStart,this._colorStartVariance=Z.colorStartVariance,this._gravity=Z.gravity,this._lifetime=Z.lifetime,this._lifetimeVariance=Z.lifetimeVariance,this._maxParticles=Z.maxParticles,this._offset=Z.offset,this._opacityEnd=Z.opacityEnd,this._opacityEndVariance=Z.opacityEndVariance,this._opacityStart=Z.opacityStart,this._opacityStartVariance=Z.opacityStartVariance,this._paused=!1,this._position=Z.position,this._positionVariance=Z.positionVariance,this._rate=Z.rate,this._rateVariance=Z.rateVariance,this._sizeEnd=Z.sizeEnd,this._sizeEndVariance=Z.sizeEndVariance,this._sizeStart=Z.sizeStart,this._sizeStartVariance=Z.sizeStartVariance,this._textureUri=Z.textureUri,this._transparent=Z.transparent,this._velocity=Z.velocity,this._velocityVariance=Z.velocityVariance}get id(){return this._id}get alphaTest(){return this._alphaTest}get attachedToEntity(){return this._attachedToEntity}get attachedToEntityNodeName(){return this._attachedToEntityNodeName}get colorEnd(){return this._colorEnd}get colorEndVariance(){return this._colorEndVariance}get colorStart(){return this._colorStart}get colorStartVariance(){return this._colorStartVariance}get gravity(){return this._gravity}get isSpawned(){return this._id!==void 0}get lifetime(){return this._lifetime}get lifetimeVariance(){return this._lifetimeVariance}get maxParticles(){return this._maxParticles}get offset(){return this._offset}get opacityEnd(){return this._opacityEnd}get opacityEndVariance(){return this._opacityEndVariance}get opacityStart(){return this._opacityStart}get opacityStartVariance(){return this._opacityStartVariance}get paused(){return this._paused}get position(){return this._position}get positionVariance(){return this._positionVariance}get rate(){return this._rate}get rateVariance(){return this._rateVariance}get sizeEnd(){return this._sizeEnd}get sizeEndVariance(){return this._sizeEndVariance}get sizeStart(){return this._sizeStart}get sizeStartVariance(){return this._sizeStartVariance}get sizeVariance(){return this._sizeVariance}get textureUri(){return this._textureUri}get transparent(){return this._transparent}get velocity(){return this._velocity}get velocityVariance(){return this._velocityVariance}get world(){return this._world}setAlphaTest(Z){if(this._alphaTest===Z)return;if(this._alphaTest=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ALPHA_TEST",{particleEmitter:this,alphaTest:Z})}setAttachedToEntity(Z){if(!Z.isSpawned)return p.error(`ParticleEmitter.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);if(this._attachedToEntity===Z)return;if(this._attachedToEntity=Z,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY",{particleEmitter:this,entity:Z})}setAttachedToEntityNodeName(Z){if(this._attachedToEntityNodeName===Z)return;if(this._attachedToEntityNodeName=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME",{particleEmitter:this,attachedToEntityNodeName:Z})}setColorEnd(Z){if(this._colorEnd&&this._colorEnd.r===Z.r&&this._colorEnd.g===Z.g&&this._colorEnd.b===Z.b)return;if(this._colorEnd=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_END",{particleEmitter:this,colorEnd:Z})}setColorEndVariance(Z){if(this._colorEndVariance&&this._colorEndVariance.r===Z.r&&this._colorEndVariance.g===Z.g&&this._colorEndVariance.b===Z.b)return;if(this._colorEndVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_END_VARIANCE",{particleEmitter:this,colorEndVariance:Z})}setColorStart(Z){if(this._colorStart&&this._colorStart.r===Z.r&&this._colorStart.g===Z.g&&this._colorStart.b===Z.b)return;if(this._colorStart=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_START",{particleEmitter:this,colorStart:Z})}setColorStartVariance(Z){if(this._colorStartVariance&&this._colorStartVariance.r===Z.r&&this._colorStartVariance.g===Z.g&&this._colorStartVariance.b===Z.b)return;if(this._colorStartVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_START_VARIANCE",{particleEmitter:this,colorStartVariance:Z})}setGravity(Z){if(this._gravity&&this._gravity.x===Z.x&&this._gravity.y===Z.y&&this._gravity.z===Z.z)return;if(this._gravity=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_GRAVITY",{particleEmitter:this,gravity:Z})}setLifetime(Z){if(this._lifetime===Z)return;if(this._lifetime=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_LIFETIME",{particleEmitter:this,lifetime:Z})}setLifetimeVariance(Z){if(this._lifetimeVariance===Z)return;if(this._lifetimeVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_LIFETIME_VARIANCE",{particleEmitter:this,lifetimeVariance:Z})}setMaxParticles(Z){if(this._maxParticles===Z)return;if(this._maxParticles=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_MAX_PARTICLES",{particleEmitter:this,maxParticles:Z})}setOffset(Z){if(this._offset&&this._offset.x===Z.x&&this._offset.y===Z.y&&this._offset.z===Z.z)return;if(this._offset=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OFFSET",{particleEmitter:this,offset:Z})}setOpacityEnd(Z){if(this._opacityEnd===Z)return;if(this._opacityEnd=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_END",{particleEmitter:this,opacityEnd:Z})}setOpacityEndVariance(Z){if(this._opacityEndVariance===Z)return;if(this._opacityEndVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE",{particleEmitter:this,opacityEndVariance:Z})}setOpacityStart(Z){if(this._opacityStart===Z)return;if(this._opacityStart=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_START",{particleEmitter:this,opacityStart:Z})}setOpacityStartVariance(Z){if(this._opacityStartVariance===Z)return;if(this._opacityStartVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE",{particleEmitter:this,opacityStartVariance:Z})}setPosition(Z){if(this._position&&this._position.x===Z.x&&this._position.y===Z.y&&this._position.z===Z.z)return;if(this._position=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_POSITION",{particleEmitter:this,position:Z})}setPositionVariance(Z){if(this._positionVariance&&this._positionVariance.x===Z.x&&this._positionVariance.y===Z.y&&this._positionVariance.z===Z.z)return;if(this._positionVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_POSITION_VARIANCE",{particleEmitter:this,positionVariance:Z})}setRate(Z){if(this._rate===Z)return;if(this._rate=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_RATE",{particleEmitter:this,rate:Z})}setRateVariance(Z){if(this._rateVariance===Z)return;if(this._rateVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_RATE_VARIANCE",{particleEmitter:this,rateVariance:Z})}setSizeEnd(Z){if(this._sizeEnd===Z)return;if(this._sizeEnd=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_END",{particleEmitter:this,sizeEnd:Z})}setSizeEndVariance(Z){if(this._sizeEndVariance===Z)return;if(this._sizeEndVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_END_VARIANCE",{particleEmitter:this,sizeEndVariance:Z})}setSizeStart(Z){if(this._sizeStart===Z)return;if(this._sizeStart=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_START",{particleEmitter:this,sizeStart:Z})}setSizeStartVariance(Z){if(this._sizeStartVariance===Z)return;if(this._sizeStartVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_START_VARIANCE",{particleEmitter:this,sizeStartVariance:Z})}setTextureUri(Z){if(this._textureUri===Z)return;if(this._textureUri=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_TEXTURE_URI",{particleEmitter:this,textureUri:Z})}setTransparent(Z){if(this._transparent===Z)return;if(this._transparent=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_TRANSPARENT",{particleEmitter:this,transparent:Z})}setVelocity(Z){if(this._velocity&&this._velocity.x===Z.x&&this._velocity.y===Z.y&&this._velocity.z===Z.z)return;if(this._velocity=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_VELOCITY",{particleEmitter:this,velocity:Z})}setVelocityVariance(Z){if(this._velocityVariance&&this._velocityVariance.x===Z.x&&this._velocityVariance.y===Z.y&&this._velocityVariance.z===Z.z)return;if(this._velocityVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_VELOCITY_VARIANCE",{particleEmitter:this,velocityVariance:Z})}burst(Z){if(this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.BURST",{particleEmitter:this,count:Z})}despawn(){if(!this.isSpawned||!this._world)return;this._world.particleEmitterManager.unregisterParticleEmitter(this),this.emitWithWorld(this._world,"PARTICLE_EMITTER.DESPAWN",{particleEmitter:this}),this._id=void 0,this._world=void 0}restart(){if(!this._paused)return;if(this._paused=!1,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_PAUSED",{particleEmitter:this,paused:this._paused})}stop(){if(this._paused)return;if(this._paused=!0,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_PAUSED",{particleEmitter:this,paused:this._paused})}spawn(Z){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return p.error(`ParticleEmitter.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning ParticleEmitter!`);this._id=Z.particleEmitterManager.registerParticleEmitter(this),this._world=Z,this.emitWithWorld(Z,"PARTICLE_EMITTER.SPAWN",{particleEmitter:this})}serialize(){return T0.serializeParticleEmitter(this)}}var aJ6={x:0,y:-32,z:0},JA=60,XA;((Y)=>{Y.STEP_START="SIMULATION.STEP_START";Y.STEP_END="SIMULATION.STEP_END";Y.DEBUG_RAYCAST="SIMULATION.DEBUG_RAYCAST";Y.DEBUG_RENDER="SIMULATION.DEBUG_RENDER"})(XA||={});class LH extends B0{_colliderMap=new Sz;_debugRaycastingEnabled=!1;_debugRenderingEnabled=!1;_debugRenderingFilterFlags;_rapierEventQueue;_rapierSimulation;_world;constructor(Z,J=JA,X=aJ6){super();this._rapierEventQueue=new X1.EventQueue(!0),this._rapierSimulation=new X1.World(X),this._rapierSimulation.timestep=Math.fround(1/J),this._world=Z}get colliderMap(){return this._colliderMap}get isDebugRaycastingEnabled(){return this._debugRaycastingEnabled}get isDebugRenderingEnabled(){return this._debugRenderingEnabled}get gravity(){return this._rapierSimulation.gravity}get timestepS(){return this._rapierSimulation.timestep}get world(){return this._world}createRawCollider(Z,J){return this._rapierSimulation.createCollider(Z,J)}createRawRigidBody(Z){return this._rapierSimulation.createRigidBody(Z)}enableDebugRaycasting(Z){this._debugRaycastingEnabled=Z}enableDebugRendering(Z,J=X1.QueryFilterFlags.EXCLUDE_FIXED){this._debugRenderingEnabled=Z,this._debugRenderingFilterFlags=J}getContactManifolds(Z,J){let X=[];return this._rapierSimulation.narrowPhase.contactPair(Z,J,($,Y)=>{if($.numContacts()===0)return;let Q=$.normal(),K=[];for(let W=0;W<$.numSolverContacts();W++)K.push($.solverContactPoint(W));X.push({contactPoints:K,localNormalA:!Y?$.localNormal1():$.localNormal2(),localNormalB:!Y?$.localNormal2():$.localNormal1(),normal:!Y?Q:{x:-Q.x,y:-Q.y,z:-Q.z}})}),X}intersectionsWithRawShape(Z,J,X,$={}){let Y=new Set,Q=[];return this._rapierSimulation.intersectionsWithShape(J,X,Z,(K)=>{let W=this._colliderMap.getColliderHandleBlockType(K.handle);if(W&&!Y.has(W))return Y.add(W),Q.push({intersectedBlockType:W}),!0;let G=this._colliderMap.getColliderHandleEntity(K.handle);if(G&&!Y.has(G))return Y.add(G),Q.push({intersectedEntity:G}),!0;return!0},$.filterFlags,$.filterGroups,$.filterExcludeCollider,$.filterExcludeRigidBody,$.filterPredicate),Q}raycast(Z,J,X,$={}){let Y=new X1.Ray(Z,J),Q=this._rapierSimulation.castRay(Y,X,$.solidMode??!0,$.filterFlags,$.filterGroups,$.filterExcludeCollider,$.filterExcludeRigidBody,$.filterPredicate);if(this._debugRaycastingEnabled)this.emitWithWorld(this._world,"SIMULATION.DEBUG_RAYCAST",{simulation:this,origin:Z,direction:J,length:X,hit:!!Q});if(!Q)return null;let K=Y.pointAt(Q.timeOfImpact),W=Q.timeOfImpact,G=Q.collider,z=this._colliderMap.getColliderHandleBlockType(G.handle);if(z)return{hitBlock:bQ.fromGlobalCoordinate({x:Math.floor(K.x-(Y.dir.x<0?0.0001:-0.0001)),y:Math.floor(K.y-(Y.dir.y<0?0.0001:-0.0001)),z:Math.floor(K.z-(Y.dir.z<0?0.0001:-0.0001))},z),hitPoint:K,hitDistance:W};let v=this._colliderMap.getColliderHandleEntity(G.handle);if(v)return{hitEntity:v,hitPoint:K,hitDistance:W};return null}removeRawCollider(Z){this._colliderMap.queueColliderHandleForCleanup(Z.handle),this._rapierSimulation.removeCollider(Z,!1)}removeRawRigidBody(Z){this._rapierSimulation.removeRigidBody(Z)}setGravity(Z){this._rapierSimulation.gravity=Z}step=(Z)=>{this.emitWithWorld(this._world,"SIMULATION.STEP_START",{simulation:this,tickDeltaMs:Z});let J=performance.now();if(V8.startSpan({operation:"physics_step"},()=>{this._rapierSimulation.step(this._rapierEventQueue)}),V8.startSpan({operation:"physics_cleanup"},()=>{this._rapierEventQueue.drainContactForceEvents(this._onContactForceEvent),this._rapierEventQueue.drainCollisionEvents(this._onCollisionEvent),this._colliderMap.cleanup()}),this.emitWithWorld(this._world,"SIMULATION.STEP_END",{simulation:this,stepDurationMs:performance.now()-J}),this._debugRenderingEnabled)this.emitWithWorld(this._world,"SIMULATION.DEBUG_RENDER",{simulation:this,...this._rapierSimulation.debugRender(this._debugRenderingFilterFlags)})};_onCollisionEvent=(Z,J,X)=>{let[$,Y]=this._getCollisionObjects(Z,J);if(!$||!Y)return;let Q=(K,W)=>{if(K instanceof A5&&W instanceof j8&&K.hasListeners("BLOCK_TYPE.ENTITY_COLLISION"))K.emit("BLOCK_TYPE.ENTITY_COLLISION",{blockType:K,entity:W,started:X,colliderHandleA:Z,colliderHandleB:J});else if(K instanceof j8&&W instanceof A5&&K.hasListeners("ENTITY.BLOCK_COLLISION"))K.emit("ENTITY.BLOCK_COLLISION",{entity:K,blockType:W,started:X,colliderHandleA:Z,colliderHandleB:J});else if(K instanceof j8&&W instanceof j8&&K.hasListeners("ENTITY.ENTITY_COLLISION"))K.emit("ENTITY.ENTITY_COLLISION",{entity:K,otherEntity:W,started:X,colliderHandleA:Z,colliderHandleB:J});else if(typeof K==="function"&&(W instanceof j8||W instanceof A5))K(W,X,Z,J)};Q($,Y),Q(Y,$)};_onContactForceEvent=(Z)=>{let[J,X]=this._getCollisionObjects(Z.collider1(),Z.collider2());if(!J||typeof J==="function"||!X||typeof X==="function")return;let $={totalForce:Z.totalForce(),totalForceMagnitude:Z.totalForceMagnitude(),maxForceDirection:Z.maxForceDirection(),maxForceMagnitude:Z.maxForceMagnitude()},Y=(Q,K)=>{if(Q instanceof A5&&K instanceof j8&&Q.hasListeners("BLOCK_TYPE.ENTITY_CONTACT_FORCE"))Q.emit("BLOCK_TYPE.ENTITY_CONTACT_FORCE",{blockType:Q,entity:K,contactForceData:$});else if(Q instanceof j8&&K instanceof A5&&Q.hasListeners("ENTITY.BLOCK_CONTACT_FORCE"))Q.emit("ENTITY.BLOCK_CONTACT_FORCE",{entity:Q,blockType:K,contactForceData:$});else if(Q instanceof j8&&K instanceof j8&&Q.hasListeners("ENTITY.ENTITY_CONTACT_FORCE"))Q.emit("ENTITY.ENTITY_CONTACT_FORCE",{entity:Q,otherEntity:K,contactForceData:$})};Y(J,X),Y(X,J)};_getCollisionObjects(Z,J){let X=this._colliderMap.getColliderHandleBlockType(Z)??this._colliderMap.getColliderHandleCollisionCallback(Z)??this._colliderMap.getColliderHandleEntity(Z),$=this._colliderMap.getColliderHandleBlockType(J)??this._colliderMap.getColliderHandleCollisionCallback(J)??this._colliderMap.getColliderHandleEntity(J);return[X,$]}}class uj{_synchronizedPlayerReliablePackets=new r8;_queuedBroadcasts=[];_queuedAudioSynchronizations=new r8;_queuedBlockSynchronizations=new r8;_queuedBlockTypeSynchronizations=new r8;_queuedChunkSynchronizations=new r8;_queuedDebugRaycastSynchronizations=[];_queuedEntitySynchronizations=new r8;_queuedLightSynchronizations=new r8;_queuedParticleEmitterSynchronizations=new r8;_queuedPerPlayerSynchronizations=new r8;_queuedPerPlayerCameraSynchronizations=new r8;_queuedPerPlayerUISynchronizations=new r8;_queuedPerPlayerUIDatasSynchronizations=new r8;_queuedPlayerSynchronizations=new r8;_queuedSceneUISynchronizations=new r8;_queuedWorldSynchronization;_loadedSceneUIs=new Set;_spawnedChunks=new Set;_spawnedEntities=new Set;_world;constructor(Z){this._world=Z,this._subscribeToAudioEvents(),this._subscribeToBlockTypeRegistryEvents(),this._subscribeToChatEvents(),this._subscribeToChunkLatticeEvents(),this._subscribeToEntityEvents(),this._subscribeToLightEvents(),this._subscribeToParticleEmitterEvents(),this._subscribeToPlayerEvents(),this._subscribeToPlayerCameraEvents(),this._subscribeToPlayerUIEvents(),this._subscribeToSceneUIEvents(),this._subscribeToSimulationEvents(),this._subscribeToWorldEvents()}synchronize(){let Z=[],J=[],X=this._world.loop.currentTick;if(this._queuedPerPlayerSynchronizations.size>0)for(let[$,Y]of this._queuedPerPlayerSynchronizations)this._createOrGetSynchronizedPlayerReliablePackets($,Z).push(...Y);if(this._queuedEntitySynchronizations.size>0){let $=[],Y=[];for(let Q of this._queuedEntitySynchronizations.valuesArray){let K=!1;for(let W in Q)if(W!=="i"&&W!=="p"&&W!=="r"){K=!0;break}if(K)$.push(Q);else Y.push(Q)}if(Y.length>0){let Q=Y0.createPacket(Y0.outboundPackets.entitiesPacketDefinition,Y,X);J.push(Q)}if($.length>0){let Q=Y0.createPacket(Y0.outboundPackets.entitiesPacketDefinition,$,X);Z.push(Q);for(let K of this._synchronizedPlayerReliablePackets.valuesArray)K.push(Q)}}if(this._queuedAudioSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.audiosPacketDefinition,this._queuedAudioSynchronizations.valuesArray,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedBlockTypeSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.blockTypesPacketDefinition,this._queuedBlockTypeSynchronizations.valuesArray,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedChunkSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.chunksPacketDefinition,this._queuedChunkSynchronizations.valuesArray,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedBlockSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.blocksPacketDefinition,this._queuedBlockSynchronizations.valuesArray,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedLightSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.lightsPacketDefinition,this._queuedLightSynchronizations.valuesArray,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedParticleEmitterSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.particleEmittersPacketDefinition,this._queuedParticleEmitterSynchronizations.valuesArray,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedPerPlayerUISynchronizations.size>0)for(let[$,Y]of this._queuedPerPlayerUISynchronizations){let Q=Y0.createPacket(Y0.outboundPackets.uiPacketDefinition,Y,X);this._createOrGetSynchronizedPlayerReliablePackets($,Z).push(Q)}if(this._queuedPerPlayerUIDatasSynchronizations.size>0)for(let[$,Y]of this._queuedPerPlayerUIDatasSynchronizations){let Q=Y0.createPacket(Y0.outboundPackets.uiDatasPacketDefinition,Y,X);this._createOrGetSynchronizedPlayerReliablePackets($,Z).push(Q)}if(this._queuedSceneUISynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.sceneUIsPacketDefinition,this._queuedSceneUISynchronizations.valuesArray,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedWorldSynchronization){let $=Y0.createPacket(Y0.outboundPackets.worldPacketDefinition,this._queuedWorldSynchronization,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedPerPlayerCameraSynchronizations.size>0)for(let[$,Y]of this._queuedPerPlayerCameraSynchronizations){let Q=Y0.createPacket(Y0.outboundPackets.cameraPacketDefinition,Y,X);this._createOrGetSynchronizedPlayerReliablePackets($,Z).push(Q)}if(this._queuedPlayerSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.playersPacketDefinition,this._queuedPlayerSynchronizations.valuesArray,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedBroadcasts.length>0)for(let $ of this._queuedBroadcasts){Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedDebugRaycastSynchronizations.length>0){let $=Y0.createPacket(Y0.outboundPackets.physicsDebugRaycastsPacketDefinition,this._queuedDebugRaycastSynchronizations,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}V8.startSpan({operation:"send_all_packets"},()=>{for(let $ of n5.instance.getConnectedPlayersByWorld(this._world)){let Y=this._synchronizedPlayerReliablePackets.get($)??Z;if(Y.length>0)$.connection.send(Y);if(J.length>0)$.connection.send(J,!1)}}),V8.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();C9.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_SYNC",this._onPlayerRequestSync)}_subscribeToPlayerCameraEvents(){this._world.final("PLAYER_CAMERA.LOOK_AT_ENTITY",this._onPlayerCameraLookAtEntity),this._world.final("PLAYER_CAMERA.LOOK_AT_POSITION",this._onPlayerCameraLookAtPosition),this._world.final("PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY",this._onPlayerCameraSetAttachedToEntity),this._world.final("PLAYER_CAMERA.SET_ATTACHED_TO_POSITION",this._onPlayerCameraSetAttachedToPosition),this._world.final("PLAYER_CAMERA.SET_FILM_OFFSET",this._onPlayerCameraSetFilmOffset),this._world.final("PLAYER_CAMERA.SET_FORWARD_OFFSET",this._onPlayerCameraSetForwardOffset),this._world.final("PLAYER_CAMERA.SET_FOV",this._onPlayerCameraSetFov),this._world.final("PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES",this._onPlayerCameraSetModelHiddenNodes),this._world.final("PLAYER_CAMERA.SET_MODEL_SHOWN_NODES",this._onPlayerCameraSetModelShownNodes),this._world.final("PLAYER_CAMERA.SET_MODE",this._onPlayerCameraSetMode),this._world.final("PLAYER_CAMERA.SET_OFFSET",this._onPlayerCameraSetOffset),this._world.final("PLAYER_CAMERA.SET_SHOULDER_ANGLE",this._onPlayerCameraSetShoulderAngle),this._world.final("PLAYER_CAMERA.SET_TRACKED_ENTITY",this._onPlayerCameraSetTrackedEntity),this._world.final("PLAYER_CAMERA.SET_TRACKED_POSITION",this._onPlayerCameraSetTrackedPosition),this._world.final("PLAYER_CAMERA.SET_ZOOM",this._onPlayerCameraSetZoom)}_subscribeToPlayerUIEvents(){this._world.final("PLAYER_UI.LOAD",this._onPlayerUILoad),this._world.final("PLAYER_UI.LOCK_POINTER",this._onPlayerUILockPointer),this._world.final("PLAYER_UI.SEND_DATA",this._onPlayerUISendData)}_subscribeToSceneUIEvents(){this._world.final("SCENE_UI.LOAD",this._onSceneUILoad),this._world.final("SCENE_UI.SET_ATTACHED_TO_ENTITY",this._onSceneUISetAttachedToEntity),this._world.final("SCENE_UI.SET_OFFSET",this._onSceneUISetOffset),this._world.final("SCENE_UI.SET_POSITION",this._onSceneUISetPosition),this._world.final("SCENE_UI.SET_STATE",this._onSceneUISetState),this._world.final("SCENE_UI.SET_VIEW_DISTANCE",this._onSceneUISetViewDistance),this._world.final("SCENE_UI.UNLOAD",this._onSceneUIUnload)}_subscribeToSimulationEvents(){this._world.final("SIMULATION.DEBUG_RAYCAST",this._onSimulationDebugRaycast),this._world.final("SIMULATION.DEBUG_RENDER",this._onSimulationDebugRender)}_subscribeToWorldEvents(){this._world.final("WORLD.SET_AMBIENT_LIGHT_COLOR",this._onWorldSetAmbientLightColor),this._world.final("WORLD.SET_AMBIENT_LIGHT_INTENSITY",this._onWorldSetAmbientLightIntensity),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_COLOR",this._onWorldSetDirectionalLightColor),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY",this._onWorldSetDirectionalLightIntensity),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_POSITION",this._onWorldSetDirectionalLightPosition),this._world.final("WORLD.SET_FOG_COLOR",this._onWorldSetFogColor),this._world.final("WORLD.SET_FOG_FAR",this._onWorldSetFogFar),this._world.final("WORLD.SET_FOG_NEAR",this._onWorldSetFogNear),this._world.final("WORLD.SET_SKYBOX_INTENSITY",this._onWorldSetSkyboxIntensity)}_onAudioPause=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.pa=!0,delete J.pl,delete J.r};_onAudioPlay=(Z)=>{let J=Z.audio.serialize();J.pl=!0,delete J.pa,delete J.r,this._queuedAudioSynchronizations.set(J.i,J)};_onAudioPlayRestart=(Z)=>{let J=Z.audio.serialize();J.r=!0,delete J.pa,delete J.pl,this._queuedAudioSynchronizations.set(J.i,J)};_onAudioSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onAudioSetCutoffDistance=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.cd=Z.cutoffDistance};_onAudioSetDetune=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.de=Z.detune};_onAudioSetDistortion=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.di=Z.distortion};_onAudioSetPosition=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.e=Z.position?void 0:J.e,J.p=Z.position?T0.serializeVector(Z.position):void 0};_onAudioSetPlaybackRate=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.pr=Z.playbackRate};_onAudioSetReferenceDistance=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.rd=Z.referenceDistance};_onAudioSetVolume=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.v=Z.volume};_onBlockTypeRegistryRegisterBlockType=(Z)=>{let J=Z.blockType.serialize();this._queuedBlockTypeSynchronizations.set(Z.blockType.id,J)};_onChatSendBroadcastMessage=(Z)=>{let{player:J,message:X,color:$}=Z;this._queuedBroadcasts.push(Y0.createPacket(Y0.outboundPackets.chatMessagesPacketDefinition,[{m:X,c:$,p:J?.id}],this._world.loop.currentTick))};_onChatSendPlayerMessage=(Z)=>{let{player:J,message:X,color:$}=Z,Y=this._queuedPerPlayerSynchronizations.get(J)??[];Y.push(Y0.createPacket(Y0.outboundPackets.chatMessagesPacketDefinition,[{m:X,c:$}],this._world.loop.currentTick)),this._queuedPerPlayerSynchronizations.set(J,Y)};_onChunkLatticeAddChunk=(Z)=>{let J=this._createOrGetQueuedChunkSync(Z.chunk);J.b=Array.from(Z.chunk.blocks),J.rm=void 0,this._spawnedChunks.add(J.c.join(","))};_onChunkLatticeRemoveChunk=(Z)=>{let J=this._createOrGetQueuedChunkSync(Z.chunk),X=J.c.join(",");if(this._spawnedChunks.has(X))this._queuedChunkSynchronizations.delete(X),this._spawnedChunks.delete(X);else J.rm=!0};_onChunkLatticeSetBlock=(Z)=>{let J=this._createOrGetQueuedBlockSync(Z.globalCoordinate);J.i=Z.blockTypeId};_onEntitySetModelAnimationsPlaybackRate=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.ap=Z.playbackRate};_onEntitySpawn=(Z)=>{let J=Z.entity.serialize();this._queuedEntitySynchronizations.set(J.i,J),this._spawnedEntities.add(J.i)};_onEntityDespawn=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(this._spawnedEntities.has(J.i))this._queuedEntitySynchronizations.delete(J.i),this._spawnedEntities.delete(J.i);else J.rm=!0};_onEntitySetModelHiddenNodes=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.h=Array.from(Z.modelHiddenNodes)};_onEntitySetModelScale=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.s=Z.modelScale};_onEntitySetModelShownNodes=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.sn=Array.from(Z.modelShownNodes)};_onEntitySetModelTextureUri=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.mt=Z.modelTextureUri};_onEntitySetOpacity=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.o=Z.opacity};_onEntitySetParent=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.pe=Z.parent?Z.parent.id:void 0,J.pn=Z.parentNodeName};_onEntitySetTintColor=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.t=Z.tintColor?T0.serializeRgbColor(Z.tintColor):void 0};_onEntityStartModelLoopedAnimations=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(J.al=Array.from(new Set([...J.al??[],...Z.animations])),J.as)J.as=J.as.filter((X)=>!Z.animations.has(X)).filter(Boolean)};_onEntityStartModelOneshotAnimations=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(J.ao=Array.from(new Set([...J.ao??[],...Z.animations])),J.as)J.as=J.as.filter((X)=>!Z.animations.has(X)).filter(Boolean)};_onEntityStopModelAnimations=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(J.al)J.al=J.al.filter((X)=>!Z.animations.has(X)).filter(Boolean);if(J.ao)J.ao=J.ao.filter((X)=>!Z.animations.has(X)).filter(Boolean);J.as=Array.from(new Set([...J.as??[],...Z.animations]))};_onEntityUpdateRotation=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.r=[Z.rotation.x,Z.rotation.y,Z.rotation.z,Z.rotation.w]};_onEntityUpdatePosition=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.p=[Z.position.x,Z.position.y,Z.position.z]};_onLightDespawn=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.rm=!0};_onLightSetAngle=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.a=Z.angle};_onLightSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onLightSetColor=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.c=T0.serializeRgbColor(Z.color)};_onLightSetDistance=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.d=Z.distance};_onLightSetIntensity=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.n=Z.intensity};_onLightSetOffset=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.o=Z.offset?T0.serializeVector(Z.offset):void 0};_onLightSetPenumbra=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.pe=Z.penumbra};_onLightSetPosition=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.p=Z.position?T0.serializeVector(Z.position):void 0,J.e=Z.position?void 0:J.e};_onLightSetTrackedEntity=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.te=Z.entity?Z.entity.id:void 0,J.tp=Z.entity?void 0:J.tp};_onLightSetTrackedPosition=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.tp=Z.position?T0.serializeVector(Z.position):void 0,J.te=Z.position?void 0:J.te};_onLightSpawn=(Z)=>{let J=Z.light.serialize();this._queuedLightSynchronizations.set(J.i,J)};_onParticleEmitterBurst=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.b=Z.count};_onParticleEmitterDespawn=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.rm=!0};_onParticleEmitterSetAlphaTest=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.at=Z.alphaTest};_onParticleEmitterSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onParticleEmitterSetAttachedToEntityNodeName=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.en=Z.attachedToEntityNodeName};_onParticleEmitterSetColorEnd=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.ce=Z.colorEnd?T0.serializeRgbColor(Z.colorEnd):void 0};_onParticleEmitterSetColorEndVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.cev=Z.colorEndVariance?T0.serializeRgbColor(Z.colorEndVariance):void 0};_onParticleEmitterSetColorStart=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.cs=Z.colorStart?T0.serializeRgbColor(Z.colorStart):void 0};_onParticleEmitterSetColorStartVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.csv=Z.colorStartVariance?T0.serializeRgbColor(Z.colorStartVariance):void 0};_onParticleEmitterSetGravity=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.g=Z.gravity?T0.serializeVector(Z.gravity):void 0};_onParticleEmitterSetLifetime=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.l=Z.lifetime};_onParticleEmitterSetLifetimeVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.lv=Z.lifetimeVariance};_onParticleEmitterSetMaxParticles=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.mp=Z.maxParticles};_onParticleEmitterSetOffset=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.o=Z.offset?T0.serializeVector(Z.offset):void 0};_onParticleEmitterSetOpacityEnd=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.oe=Z.opacityEnd};_onParticleEmitterSetOpacityEndVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.oev=Z.opacityEndVariance};_onParticleEmitterSetOpacityStart=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.os=Z.opacityStart};_onParticleEmitterSetOpacityStartVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.osv=Z.opacityStartVariance};_onParticleEmitterSetPaused=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.pa=Z.paused};_onParticleEmitterSetPosition=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.p=Z.position?T0.serializeVector(Z.position):void 0,J.e=Z.position?void 0:J.e,J.en=Z.position?void 0:J.en};_onParticleEmitterSetPositionVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.pv=Z.positionVariance?T0.serializeVector(Z.positionVariance):void 0};_onParticleEmitterSetRate=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.r=Z.rate};_onParticleEmitterSetRateVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.rv=Z.rateVariance};_onParticleEmitterSetSizeEnd=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.se=Z.sizeEnd};_onParticleEmitterSetSizeEndVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.sev=Z.sizeEndVariance};_onParticleEmitterSetSizeStart=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.ss=Z.sizeStart};_onParticleEmitterSetSizeStartVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.ssv=Z.sizeStartVariance};_onParticleEmitterSetTextureUri=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.tu=Z.textureUri};_onParticleEmitterSetTransparent=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.t=Z.transparent};_onParticleEmitterSetVelocity=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.v=Z.velocity?T0.serializeVector(Z.velocity):void 0};_onParticleEmitterSetVelocityVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.vv=Z.velocityVariance?T0.serializeVector(Z.velocityVariance):void 0};_onParticleEmitterSpawn=(Z)=>{let J=Z.particleEmitter.serialize();this._queuedParticleEmitterSynchronizations.set(J.i,J)};_onPlayerCameraLookAtEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pl=T0.serializeVector(Z.entity.position),delete J.et,delete J.pt};_onPlayerCameraLookAtPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pl=Z.position?T0.serializeVector(Z.position):void 0,delete J.et,delete J.pt};_onPlayerCameraSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.e=Z.entity.id,delete J.p};_onPlayerCameraSetAttachedToPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.p=Z.position?T0.serializeVector(Z.position):void 0,delete J.e};_onPlayerCameraSetFilmOffset=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.fo=Z.filmOffset};_onPlayerCameraSetForwardOffset=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.ffo=Z.forwardOffset};_onPlayerCameraSetFov=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.fv=Z.fov};_onPlayerCameraSetModelHiddenNodes=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.h=Array.from(Z.modelHiddenNodes)};_onPlayerCameraSetModelShownNodes=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.s=Array.from(Z.modelShownNodes)};_onPlayerCameraSetMode=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.m=Z.mode};_onPlayerCameraSetOffset=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.o=Z.offset?T0.serializeVector(Z.offset):void 0};_onPlayerCameraSetShoulderAngle=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.sa=Z.shoulderAngle};_onPlayerCameraSetTrackedEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.et=Z.entity?Z.entity.id:void 0,delete J.pl,delete J.pt};_onPlayerCameraSetTrackedPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pt=Z.position?T0.serializeVector(Z.position):void 0,delete J.et,delete J.pl};_onPlayerCameraSetZoom=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.z=Z.zoom};_onPlayerJoinedWorld=(Z)=>{let{player:J}=Z,X=this._queuedPerPlayerSynchronizations.get(J)??[];X.push(Y0.createPacket(Y0.outboundPackets.worldPacketDefinition,this._world.serialize(),this._world.loop.currentTick)),X.push(Y0.createPacket(Y0.outboundPackets.blockTypesPacketDefinition,this._world.blockTypeRegistry.serialize(),this._world.loop.currentTick)),X.push(Y0.createPacket(Y0.outboundPackets.chunksPacketDefinition,this._world.chunkLattice.getAllChunks().map((Y)=>Y.serialize()),this._world.loop.currentTick)),X.push(Y0.createPacket(Y0.outboundPackets.entitiesPacketDefinition,this._world.entityManager.getAllEntities().map((Y)=>{if(J.camera.attachedToEntity===void 0&&Y instanceof F7&&Y.player===J)J.camera.setAttachedToEntity(Y);return Y.serialize()}),this._world.loop.currentTick)),X.push(Y0.createPacket(Y0.outboundPackets.audiosPacketDefinition,this._world.audioManager.getAllAudios().map((Y)=>Y.serialize()),this._world.loop.currentTick)),X.push(Y0.createPacket(Y0.outboundPackets.lightsPacketDefinition,this._world.lightManager.getAllLights().map((Y)=>Y.serialize()),this._world.loop.currentTick)),X.push(Y0.createPacket(Y0.outboundPackets.particleEmittersPacketDefinition,this._world.particleEmitterManager.getAllParticleEmitters().map((Y)=>Y.serialize()),this._world.loop.currentTick)),X.push(Y0.createPacket(Y0.outboundPackets.sceneUIsPacketDefinition,this._world.sceneUIManager.getAllSceneUIs().map((Y)=>Y.serialize()),this._world.loop.currentTick)),X.push(Y0.createPacket(Y0.outboundPackets.playersPacketDefinition,n5.instance.getConnectedPlayers().map((Y)=>Y.serialize()),this._world.loop.currentTick));let $=this._createOrGetQueuedPlayerCameraSync(J.camera);this._queuedPerPlayerCameraSynchronizations.set(J,{...J.camera.serialize(),...$}),this._queuedPerPlayerSynchronizations.set(J,X),this._queuedPlayerSynchronizations.set(J.id,J.serialize())};_onPlayerLeftWorld=(Z)=>{let J=this._createOrGetQueuedPlayerSync(Z.player);J.rm=!0};_onPlayerReconnectedWorld=(Z)=>{this._onPlayerJoinedWorld(Z)};_onPlayerRequestSync=(Z)=>{Z.player.connection.send([Y0.createPacket(Y0.outboundPackets.syncResponsePacketDefinition,{r:Z.receivedAt,s:Date.now(),p:performance.now()-Z.receivedAtMs,n:this._world.loop.nextTickMs},this._world.loop.currentTick)])};_onPlayerUILoad=(Z)=>{let J=this._createOrGetQueuedPlayerUISync(Z.playerUI);J.u=Z.htmlUri};_onPlayerUILockPointer=(Z)=>{let J=this._createOrGetQueuedPlayerUISync(Z.playerUI);J.p=Z.lock};_onPlayerUISendData=(Z)=>{this._createOrGetQueuedPlayerUIDatasSync(Z.playerUI).push(Z.data)};_onSceneUILoad=(Z)=>{let J=Z.sceneUI.serialize();this._queuedSceneUISynchronizations.set(J.i,J),this._loadedSceneUIs.add(J.i)};_onSceneUISetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onSceneUISetOffset=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.o=Z.offset?T0.serializeVector(Z.offset):void 0};_onSceneUISetPosition=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.p=Z.position?T0.serializeVector(Z.position):void 0,J.e=Z.position?void 0:J.e};_onSceneUISetState=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.s=Z.state};_onSceneUISetViewDistance=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.v=Z.viewDistance};_onSceneUIUnload=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);if(this._loadedSceneUIs.has(J.i))this._queuedSceneUISynchronizations.delete(J.i),this._loadedSceneUIs.delete(J.i);else J.rm=!0};_onSimulationDebugRaycast=(Z)=>{this._queuedDebugRaycastSynchronizations.push(T0.serializePhysicsDebugRaycast(Z))};_onSimulationDebugRender=(Z)=>{this._queuedBroadcasts.push(Y0.createPacket(Y0.outboundPackets.physicsDebugRenderPacketDefinition,{v:Array.from(Z.vertices),c:Array.from(Z.colors)},this._world.loop.currentTick))};_onWorldSetAmbientLightColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.ac=T0.serializeRgbColor(Z.color)};_onWorldSetAmbientLightIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.ai=Z.intensity};_onWorldSetDirectionalLightColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.dc=T0.serializeRgbColor(Z.color)};_onWorldSetDirectionalLightIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.di=Z.intensity};_onWorldSetDirectionalLightPosition=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.dp=T0.serializeVector(Z.position)};_onWorldSetFogColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.fc=T0.serializeRgbColor(Z.color)};_onWorldSetFogFar=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.ff=Z.far};_onWorldSetFogNear=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.fn=Z.near};_onWorldSetSkyboxIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.si=Z.intensity};_createOrGetQueuedAudioSync(Z){if(Z.id===void 0)p.fatalError("NetworkSynchronizer._createOrGetQueuedAudioSync(): Audio has no id!");let J=this._queuedAudioSynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedAudioSynchronizations.set(Z.id,J);return J}_createOrGetQueuedBlockSync(Z){let{x:J,y:X,z:$}=Z,Y=`${J},${X},${$}`,Q=this._queuedBlockSynchronizations.get(Y);if(!Q)Q={i:0,c:[J,X,$]},this._queuedBlockSynchronizations.set(Y,Q);return Q}_createOrGetQueuedChunkSync(Z){if(!Z.originCoordinate)p.fatalError("NetworkSynchronizer._createOrGetQueuedChunkSync(): Chunk has no origin coordinate!");let{x:J,y:X,z:$}=Z.originCoordinate,Y=`${J},${X},${$}`,Q=this._queuedChunkSynchronizations.get(Y);if(!Q)Q={c:[J,X,$]},this._queuedChunkSynchronizations.set(Y,Q);return Q}_createOrGetQueuedEntitySync(Z){if(Z.id===void 0)p.fatalError("NetworkSynchronizer._createOrGetQueuedEntitySync(): Entity has no id!");let J=this._queuedEntitySynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedEntitySynchronizations.set(Z.id,J);return J}_createOrGetQueuedLightSync(Z){if(Z.id===void 0)p.fatalError("NetworkSynchronizer._createOrGetQueuedLightSync(): Light has no id!");let J=this._queuedLightSynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedLightSynchronizations.set(Z.id,J);return J}_createOrGetQueuedParticleEmitterSync(Z){if(Z.id===void 0)p.fatalError("NetworkSynchronizer._createOrGetQueuedParticleEmitterSync(): ParticleEmitter has no id!");let J=this._queuedParticleEmitterSynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedParticleEmitterSynchronizations.set(Z.id,J);return J}_createOrGetQueuedPlayerSync(Z){if(Z.id===void 0)p.fatalError("NetworkSynchronizer._createOrGetQueuedPlayerSync(): Player has no id!");let J=this._queuedPlayerSynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedPlayerSynchronizations.set(Z.id,J);return J}_createOrGetQueuedPlayerCameraSync(Z){let J=this._queuedPerPlayerCameraSynchronizations.get(Z.player);if(!J)J={},this._queuedPerPlayerCameraSynchronizations.set(Z.player,J);return J}_createOrGetQueuedPlayerUISync(Z){let J=this._queuedPerPlayerUISynchronizations.get(Z.player);if(!J)J={},this._queuedPerPlayerUISynchronizations.set(Z.player,J);return J}_createOrGetQueuedPlayerUIDatasSync(Z){let J=this._queuedPerPlayerUIDatasSynchronizations.get(Z.player);if(!J)J=[],this._queuedPerPlayerUIDatasSynchronizations.set(Z.player,J);return J}_createOrGetQueuedSceneUISync(Z){if(Z.id===void 0)p.fatalError("NetworkSynchronizer._createOrGetQueuedSceneUISync(): SceneUI has no id!");let J=this._queuedSceneUISynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedSceneUISynchronizations.set(Z.id,J);return J}_createOrGetQueuedWorldSync(Z){if(Z.id!==this._world.id)p.fatalError("NetworkSynchronizer._createOrGetQueuedWorldSync(): World does not match this network synchronizer world!");return this._queuedWorldSynchronization??={i:Z.id}}_createOrGetSynchronizedPlayerReliablePackets(Z,J){let X=this._synchronizedPlayerReliablePackets.get(Z);if(!X)X=[...J],this._synchronizedPlayerReliablePackets.set(Z,X);return X}}class DH{_particleEmitters=new Map;_nextParticleEmitterId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}despawnEntityAttachedParticleEmitters(Z){this.getAllEntityAttachedParticleEmitters(Z).forEach((J)=>{J.despawn()})}getAllParticleEmitters(){return Array.from(this._particleEmitters.values())}getAllEntityAttachedParticleEmitters(Z){return this.getAllParticleEmitters().filter((J)=>J.attachedToEntity===Z)}registerParticleEmitter(Z){if(Z.id!==void 0)return Z.id;let J=this._nextParticleEmitterId;return this._particleEmitters.set(J,Z),this._nextParticleEmitterId++,J}unregisterParticleEmitter(Z){if(Z.id===void 0)return;this._particleEmitters.delete(Z.id)}}class MH{_sceneUIs=new Map;_nextSceneUIId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}getAllSceneUIs(){return Array.from(this._sceneUIs.values())}getAllEntityAttachedSceneUIs(Z){return this.getAllSceneUIs().filter((J)=>J.attachedToEntity===Z)}getSceneUIById(Z){return this._sceneUIs.get(Z)}registerSceneUI(Z){if(Z.id!==void 0)return Z.id;let J=this._nextSceneUIId;return this._sceneUIs.set(J,Z),this._nextSceneUIId++,J}unloadEntityAttachedSceneUIs(Z){this.getAllEntityAttachedSceneUIs(Z).forEach((J)=>{J.unload()})}unregisterSceneUI(Z){if(Z.id===void 0)return;this._sceneUIs.delete(Z.id)}}var nJ6=2,sJ6=3;class RH{_accumulatorMs=0;_targetTicksPerSecond;_fixedTimestepMs;_fixedTimestepS;_maxAccumulatorMs;_nextTickMs=0;_lastLoopTimeMs=0;_tickFunction;_tickErrorCallback;_tickHandle=null;constructor(Z,J,X){this._targetTicksPerSecond=Z,this._fixedTimestepS=Math.fround(1/Z),this._fixedTimestepMs=Math.fround(this._fixedTimestepS*1000),this._maxAccumulatorMs=this._fixedTimestepMs*sJ6,this._tickFunction=J,this._tickErrorCallback=X}get targetTicksPerSecond(){return this._targetTicksPerSecond}get fixedTimestepMs(){return this._fixedTimestepMs}get fixedTimestepS(){return this._fixedTimestepS}get isStarted(){return!!this._tickHandle}get nextTickMs(){return this._nextTickMs}start(){if(this._tickHandle)return;this._lastLoopTimeMs=performance.now();let Z=()=>{let J=performance.now(),X=J-this._lastLoopTimeMs;if(this._lastLoopTimeMs=J,this._accumulatorMs+=X,this._accumulatorMs>this._maxAccumulatorMs)this._accumulatorMs=this._maxAccumulatorMs;if(this._accumulatorMs>=this._fixedTimestepMs)V8.startSpan({operation:"ticker_tick"},()=>{let $=0;while(this._accumulatorMs>=this._fixedTimestepMs&&$<nJ6)this._tick(this._fixedTimestepMs),this._accumulatorMs-=this._fixedTimestepMs,$++});this._nextTickMs=Math.max(0,this._fixedTimestepMs-this._accumulatorMs),this._tickHandle=setTimeout(Z,this._nextTickMs)};Z()}stop(){if(!this._tickHandle)return;clearTimeout(this._tickHandle),this._tickHandle=null}_tick(Z){try{this._tickFunction(Z)}catch(J){if(J instanceof Error&&this._tickErrorCallback)this._tickErrorCallback(J);else p.warning(`Ticker._tick(): tick callback threw an error, but it was not an instance of Error. Error: ${J}`)}}}var n31;((Q)=>{Q.START="WORLD_LOOP.START";Q.STOP="WORLD_LOOP.STOP";Q.TICK_START="WORLD_LOOP.TICK_START";Q.TICK_END="WORLD_LOOP.TICK_END";Q.TICK_ERROR="WORLD_LOOP.TICK_ERROR"})(n31||={});class NH extends B0{_currentTick=0;_ticker;_world;constructor(Z,J=JA){super();this._ticker=new RH(J,this._tick,this._onTickError),this._world=Z}get currentTick(){return this._currentTick}get isStarted(){return this._ticker.isStarted}get nextTickMs(){return this._ticker.nextTickMs}get timestepS(){return this._ticker.fixedTimestepS}get world(){return this._world}start(){this._ticker.start(),this.emitWithWorld(this._world,"WORLD_LOOP.START",{worldLoop:this})}stop(){this._ticker.stop(),this.emitWithWorld(this._world,"WORLD_LOOP.STOP",{worldLoop:this})}_tick=(Z)=>{this.emitWithWorld(this._world,"WORLD_LOOP.TICK_START",{worldLoop:this,tickDeltaMs:Z});let J=performance.now();V8.startSpan({operation:"world_tick",attributes:{serverPlayerCount:n5.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}},()=>{V8.startSpan({operation:"entities_tick"},()=>this._world.entityManager.tickEntities(Z)),V8.startSpan({operation:"simulation_step"},()=>this._world.simulation.step(Z)),V8.startSpan({operation:"entities_emit_updates"},()=>this._world.entityManager.checkAndEmitUpdates()),V8.startSpan({operation:"network_synchronize"},()=>this._world.networkSynchronizer.synchronize())}),this._currentTick++,this.emitWithWorld(this._world,"WORLD_LOOP.TICK_END",{worldLoop:this,tickDurationMs:performance.now()-J})};_onTickError=(Z)=>{p.error(`WorldLoop._onTickError(): Error: ${Z}`),this.emitWithWorld(this._world,"WORLD_LOOP.TICK_ERROR",{worldLoop:this,error:Z})}}var $A;((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.START="WORLD.START";H.STOP="WORLD.STOP"})($A||={});class OH extends B0{_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(Z){super();if(this._id=Z.id,this._ambientLightColor=Z.ambientLightColor??{r:255,g:255,b:255},this._ambientLightIntensity=Z.ambientLightIntensity??1,this._directionalLightColor=Z.directionalLightColor??{r:255,g:255,b:255},this._directionalLightIntensity=Z.directionalLightIntensity??3,this._directionalLightPosition=Z.directionalLightPosition??{x:100,y:150,z:100},this._fogColor=Z.fogColor,this._fogFar=Z.fogFar??550,this._fogNear=Z.fogNear??500,this._name=Z.name,this._skyboxIntensity=Z.skyboxIntensity??1,this._skyboxUri=Z.skyboxUri,this._tag=Z.tag,this._audioManager=new NW(this),this._blockTypeRegistry=new rG(this),this._chatManager=new bz(this),this._chunkLattice=new hz(this),this._entityManager=new uz(this),this._lightManager=new jH(this),this._loop=new NH(this,Z.tickRate),this._networkSynchronizer=new uj(this),this._particleEmitterManager=new DH(this),this._sceneUIManager=new MH(this),this._simulation=new LH(this,Z.tickRate,Z.gravity),Z.map)this.loadMap(Z.map)}get id(){return this._id}get ambientLightColor(){return this._ambientLightColor}get ambientLightIntensity(){return this._ambientLightIntensity}get 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(Z){if(this.chunkLattice.clear(),Z.blockTypes)for(let J of Z.blockTypes)this.blockTypeRegistry.registerGenericBlockType({id:J.id,isLiquid:J.isLiquid,lightLevel:J.lightLevel,name:J.name,textureUri:J.textureUri});if(Z.blocks)for(let[J,X]of Object.entries(Z.blocks)){let[$,Y,Q]=J.split(",").map(Number);this.chunkLattice.setBlock({x:$,y:Y,z:Q},X)}if(Z.entities)for(let[J,X]of Object.entries(Z.entities)){let[$,Y,Q]=J.split(",").map(Number);new j8({isEnvironmental:!0,...X}).spawn(this,{x:$,y:Y,z:Q})}}setAmbientLightColor(Z){this._ambientLightColor=Z,this.emit("WORLD.SET_AMBIENT_LIGHT_COLOR",{world:this,color:Z})}setAmbientLightIntensity(Z){this._ambientLightIntensity=Z,this.emit("WORLD.SET_AMBIENT_LIGHT_INTENSITY",{world:this,intensity:Z})}setDirectionalLightColor(Z){this._directionalLightColor=Z,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_COLOR",{world:this,color:Z})}setDirectionalLightIntensity(Z){this._directionalLightIntensity=Z,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY",{world:this,intensity:Z})}setDirectionalLightPosition(Z){this._directionalLightPosition=Z,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_POSITION",{world:this,position:Z})}setFogColor(Z){this._fogColor=Z,this.emit("WORLD.SET_FOG_COLOR",{world:this,color:Z})}setFogFar(Z){this._fogFar=Z,this.emit("WORLD.SET_FOG_FAR",{world:this,far:Z})}setFogNear(Z){this._fogNear=Z,this.emit("WORLD.SET_FOG_NEAR",{world:this,near:Z})}setSkyboxIntensity(Z){this._skyboxIntensity=Z,this.emit("WORLD.SET_SKYBOX_INTENSITY",{world:this,intensity:Z})}start(){if(this._loop.isStarted)return;this._loop.start(),this.emit("WORLD.START",{world:this,startedAtMs:Date.now()})}stop(){if(!this._loop.isStarted)return;this._loop.stop(),this.emit("WORLD.STOP",{world:this,stoppedAtMs:Date.now()})}serialize(){return T0.serializeWorld(this)}}var s31;((J)=>J.WORLD_CREATED="WORLD_MANAGER.WORLD_CREATED")(s31||={});class q${static instance=new q$;_defaultWorld;_nextWorldId=1;_worlds=new Map;createWorld(Z){let J=new OH({...Z,id:this._nextWorldId++});return J.start(),this._worlds.set(J.id,J),B0.globalInstance.emit("WORLD_MANAGER.WORLD_CREATED",{world:J}),J}getAllWorlds(){return Array.from(this._worlds.values())}getDefaultWorld(){return this._defaultWorld??=this.createWorld({name:"Default World",skyboxUri:"skyboxes/partly-cloudy"}),this._defaultWorld}getWorldsByTag(Z){let J=[];return this._worlds.forEach((X)=>{if(X.tag===Z)J.push(X)}),J}getWorld(Z){return this._worlds.get(Z)}setDefaultWorld(Z){this._defaultWorld=Z}}var o31;(($)=>{$.PLAYER_CONNECTED="PLAYER_MANAGER.PLAYER_CONNECTED";$.PLAYER_DISCONNECTED="PLAYER_MANAGER.PLAYER_DISCONNECTED";$.PLAYER_RECONNECTED="PLAYER_MANAGER.PLAYER_RECONNECTED"})(o31||={});class n5{static instance=new n5;worldSelectionHandler;_connectionPlayers=new Map;constructor(){B0.globalInstance.on("CONNECTION.OPENED",({connection:Z,req:J})=>{this._onConnectionOpened(Z,J.session)}),B0.globalInstance.on("CONNECTION.DISCONNECTED",({connection:Z})=>{this._onConnectionDisconnected(Z)}),B0.globalInstance.on("CONNECTION.RECONNECTED",({connection:Z})=>{this._onConnectionReconnected(Z)}),B0.globalInstance.on("CONNECTION.CLOSED",({connection:Z})=>{this._onConnectionClosed(Z)})}get playerCount(){return this._connectionPlayers.size}getConnectedPlayers(){return Array.from(this._connectionPlayers.values())}getConnectedPlayersByWorld(Z){return this.getConnectedPlayers().filter((J)=>J.world===Z)}getConnectedPlayerByUsername(Z){return Array.from(this._connectionPlayers.values()).find((J)=>{return J.username.toLowerCase()===Z.toLowerCase()})}async _onConnectionOpened(Z,J){let X=new g3(Z,J);await X.loadInitialPersistedData(),B0.globalInstance.emit("PLAYER_MANAGER.PLAYER_CONNECTED",{player:X});let $=await this.worldSelectionHandler?.(X);X.joinWorld($??q$.instance.getDefaultWorld()),this._connectionPlayers.set(Z,X)}_onConnectionDisconnected(Z){let J=this._connectionPlayers.get(Z);if(J)J.resetInputs(),J.camera.reset()}_onConnectionReconnected(Z){let J=this._connectionPlayers.get(Z);if(J)J.reconnected(),B0.globalInstance.emit("PLAYER_MANAGER.PLAYER_RECONNECTED",{player:J});else p.warning(`PlayerManager._onConnectionReconnected(): Connection ${Z.id} not in the PlayerManager._connectionPlayers map.`)}_onConnectionClosed(Z){let J=this._connectionPlayers.get(Z);if(J)J.disconnect(),this._connectionPlayers.delete(Z),B0.globalInstance.emit("PLAYER_MANAGER.PLAYER_DISCONNECTED",{player:J});else p.warning(`PlayerManager._onConnectionClosed(): Connection ${Z.id} not in the PlayerManager._connectionPlayers map.`)}}Buffer.poolSize=134217728;var r31;((X)=>{X.START="GAMESERVER.START";X.STOP="GAMESERVER.STOP"})(r31||={});function oJ6(Z){X1.init().then(()=>{return TQ.instance.modelRegistry.preloadModels()}).then(()=>{if(Z.length>0)Z(TQ.instance.worldManager.getDefaultWorld());else Z();TQ.instance.start()}).catch((J)=>{p.fatalError(`Failed to initialize the game engine, exiting. Error: ${J}`)})}class TQ{static _instance;_modelRegistry=j6.instance;_playerManager=n5.instance;_socket=M7.instance;_worldManager=q$.instance;_webServer=FK.instance;constructor(){}static get instance(){if(!this._instance)this._instance=new TQ;return this._instance}get modelRegistry(){return this._modelRegistry}get playerManager(){return this._playerManager}get socket(){return this._socket}get webServer(){return this._webServer}get worldManager(){return this._worldManager}start(){B0.globalInstance.emit("GAMESERVER.START",{startedAtMs:performance.now()}),this._webServer.start()}}var t8=t(kQ(),1);class EQ extends Float32Array{constructor(Z,J,X,$){super([Z,J,X,$])}get determinant(){return t8.mat2.determinant(this)}get frobeniusNorm(){return t8.mat2.frob(this)}static create(){let Z=new EQ(0,0,0,0);return t8.mat2.identity(Z),Z}static fromRotation(Z){let J=EQ.create();return t8.mat2.fromRotation(J,Z),J}static fromScaling(Z){let J=EQ.create();return t8.mat2.fromScaling(J,Z),J}add(Z){return t8.mat2.add(this,this,Z),this}adjoint(){return t8.mat2.adjoint(this,this),this}clone(){return new EQ(this[0],this[1],this[2],this[3])}copy(Z){return t8.mat2.copy(this,Z),this}equals(Z){return t8.mat2.equals(this,Z)}exactEquals(Z){return t8.mat2.exactEquals(this,Z)}identity(){return t8.mat2.identity(this),this}invert(){return t8.mat2.invert(this,this),this}multiply(Z){return t8.mat2.mul(this,this,Z),this}multiplyScalar(Z){return t8.mat2.multiplyScalar(this,this,Z),this}rotate(Z){return t8.mat2.rotate(this,this,Z),this}subtract(Z){return t8.mat2.sub(this,this,Z),this}toString(){return`[${this[0]},${this[1]}][${this[2]},${this[3]}]`}transpose(){return t8.mat2.transpose(this,this),this}}var H8=t(kQ(),1);class p7 extends Float32Array{constructor(Z,J,X,$,Y,Q,K,W,G){super([Z,J,X,$,Y,Q,K,W,G])}get determinant(){return H8.mat3.determinant(this)}get frobeniusNorm(){return H8.mat3.frob(this)}static create(){let Z=new p7(0,0,0,0,0,0,0,0,0);return H8.mat3.identity(Z),Z}static fromMatrix4(Z){let J=p7.create();return H8.mat3.fromMat4(J,Z),J}static fromQuaternion(Z){let J=p7.create();return H8.mat3.fromQuat(J,Z),J}static fromRotation(Z){let J=p7.create();return H8.mat3.fromRotation(J,Z),J}static fromScaling(Z){let J=p7.create();return H8.mat3.fromScaling(J,Z),J}static fromTranslation(Z){let J=p7.create();return H8.mat3.fromTranslation(J,Z),J}add(Z){return H8.mat3.add(this,this,Z),this}adjoint(){return H8.mat3.adjoint(this,this),this}clone(){return new p7(this[0],this[1],this[2],this[3],this[4],this[5],this[6],this[7],this[8])}copy(Z){return H8.mat3.copy(this,Z),this}equals(Z){return H8.mat3.equals(this,Z)}exactEquals(Z){return H8.mat3.exactEquals(this,Z)}identity(){return H8.mat3.identity(this),this}invert(){return H8.mat3.invert(this,this),this}multiply(Z){return H8.mat3.mul(this,this,Z),this}multiplyScalar(Z){return H8.mat3.multiplyScalar(this,this,Z),this}transformVector(Z){return Z.transformMatrix3(this)}projection(Z,J){return H8.mat3.projection(this,Z,J),this}rotate(Z){return H8.mat3.rotate(this,this,Z),this}subtract(Z){return H8.mat3.sub(this,this,Z),this}toString(){return`[${this[0]},${this[1]},${this[2]}][${this[3]},${this[4]},${this[5]}][${this[6]},${this[7]},${this[8]}]`}transpose(){return H8.mat3.transpose(this,this),this}}var Z1=t(kQ(),1);class W5 extends Float32Array{constructor(Z,J,X,$,Y,Q,K,W,G,z,v,H,V,q,F,x){super([Z,J,X,$,Y,Q,K,W,G,z,v,H,V,q,F,x])}get determinant(){return Z1.mat4.determinant(this)}get frobeniusNorm(){return Z1.mat4.frob(this)}static create(){let Z=new W5(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return Z1.mat4.identity(Z),Z}static fromQuaternion(Z){let J=W5.create();return Z1.mat4.fromQuat(J,Z),J}static fromRotation(Z,J){let X=W5.create();return Z1.mat4.fromRotation(X,Z,J),X}static fromRotationTranslation(Z,J){let X=W5.create();return Z1.mat4.fromRotationTranslation(X,Z,J),X}static fromRotationTranslationScale(Z,J,X){let $=W5.create();return Z1.mat4.fromRotationTranslationScale($,Z,J,X),$}static fromRotationTranslationScaleOrigin(Z,J,X,$){let Y=W5.create();return Z1.mat4.fromRotationTranslationScaleOrigin(Y,Z,J,X,$),Y}static fromScaling(Z){let J=W5.create();return Z1.mat4.fromScaling(J,Z),J}static fromTranslation(Z){let J=W5.create();return Z1.mat4.fromTranslation(J,Z),J}static fromXRotation(Z){let J=W5.create();return Z1.mat4.fromXRotation(J,Z),J}static fromYRotation(Z){let J=W5.create();return Z1.mat4.fromYRotation(J,Z),J}static fromZRotation(Z){let J=W5.create();return Z1.mat4.fromZRotation(J,Z),J}add(Z){return Z1.mat4.add(this,this,Z),this}adjoint(){return Z1.mat4.adjoint(this,this),this}clone(){return new W5(this[0],this[1],this[2],this[3],this[4],this[5],this[6],this[7],this[8],this[9],this[10],this[11],this[12],this[13],this[14],this[15])}copy(Z){return Z1.mat4.copy(this,Z),this}equals(Z){return Z1.mat4.equals(this,Z)}exactEquals(Z){return Z1.mat4.exactEquals(this,Z)}frustrum(Z,J,X,$,Y,Q){return Z1.mat4.frustum(this,Z,J,X,$,Y,Q),this}identity(){return Z1.mat4.identity(this),this}invert(){return Z1.mat4.invert(this,this),this}lookAt(Z,J,X){return Z1.mat4.lookAt(this,Z,J,X),this}multiply(Z){return Z1.mat4.mul(this,this,Z),this}multiplyScalar(Z){return Z1.mat4.multiplyScalar(this,this,Z),this}orthographic(Z,J,X,$,Y,Q){return Z1.mat4.ortho(this,Z,J,X,$,Y,Q),this}perspective(Z,J,X,$){return Z1.mat4.perspective(this,Z,J,X,$),this}rotate(Z,J){return Z1.mat4.rotate(this,this,Z,J),this}rotateX(Z){return Z1.mat4.rotateX(this,this,Z),this}rotateY(Z){return Z1.mat4.rotateY(this,this,Z),this}rotateZ(Z){return Z1.mat4.rotateZ(this,this,Z),this}scale(Z){return Z1.mat4.scale(this,this,Z),this}subtract(Z){return Z1.mat4.sub(this,this,Z),this}targetTo(Z,J,X){return Z1.mat4.targetTo(this,Z,J,X),this}toString(){return`[${this[0]},${this[1]},${this[2]},${this[3]}][${this[4]},${this[5]},${this[6]},${this[7]}][${this[8]},${this[9]},${this[10]},${this[11]}][${this[12]},${this[13]},${this[14]},${this[15]}]`}translate(Z){return Z1.mat4.translate(this,this,Z),this}transpose(){return Z1.mat4.transpose(this,this),this}}var I1=t(kQ(),1);class LW extends Float32Array{constructor(Z,J,X,$){super([Z,J,X,$])}get length(){return I1.quat.length(this)}get squaredLength(){return I1.quat.squaredLength(this)}get magnitude(){return I1.quat.length(this)}get squaredMagnitude(){return I1.quat.squaredLength(this)}get x(){return this[0]}set x(Z){this[0]=Z}get y(){return this[1]}set y(Z){this[1]=Z}get z(){return this[2]}set z(Z){this[2]=Z}get w(){return this[3]}set w(Z){this[3]=Z}static fromEuler(Z,J,X){let $=I1.quat.fromEuler(new Float32Array(4),Z,J,X);return new LW($[0],$[1],$[2],$[3])}static fromQuaternionLike(Z){return new LW(Z.x,Z.y,Z.z,Z.w)}clone(){return new LW(this.x,this.y,this.z,this.w)}conjugate(){return I1.quat.conjugate(this,this),this}copy(Z){return I1.quat.copy(this,Z),this}dot(Z){return I1.quat.dot(this,Z)}exponential(){return I1.quat.exp(this,this),this}equals(Z){return I1.quat.equals(this,Z)}exactEquals(Z){return I1.quat.exactEquals(this,Z)}getAngle(Z){return I1.quat.getAngle(this,Z)}identity(){return I1.quat.identity(this),this}invert(){return I1.quat.invert(this,this),this}lerp(Z,J){return I1.quat.lerp(this,this,Z,J),this}logarithm(){return I1.quat.ln(this,this),this}multiply(Z){return I1.quat.multiply(this,this,Z),this}transformVector(Z){return Z.transformQuaternion(this)}normalize(){return I1.quat.normalize(this,this),this}power(Z){return I1.quat.pow(this,this,Z),this}randomize(){return I1.quat.random(this),this}rotateX(Z){return I1.quat.rotateX(this,this,Z),this}rotateY(Z){return I1.quat.rotateY(this,this,Z),this}rotateZ(Z){return I1.quat.rotateZ(this,this,Z),this}scale(Z){return I1.quat.scale(this,this,Z),this}setAxisAngle(Z,J){return I1.quat.setAxisAngle(this,Z,J),this}slerp(Z,J){return I1.quat.slerp(this,this,Z,J),this}toString(){return`${this.x},${this.y},${this.z},${this.w}`}}var q1=t(kQ(),1);class PH extends Float32Array{constructor(Z,J){super([Z,J])}get length(){return q1.vec2.length(this)}get squaredLength(){return q1.vec2.squaredLength(this)}get magnitude(){return q1.vec2.length(this)}get squaredMagnitude(){return q1.vec2.squaredLength(this)}get x(){return this[0]}set x(Z){this[0]=Z}get y(){return this[1]}set y(Z){this[1]=Z}static create(){return new PH(0,0)}add(Z){return q1.vec2.add(this,this,Z),this}angle(Z){return q1.vec2.angle(this,Z)}ceil(){return q1.vec2.ceil(this,this),this}clone(){return new PH(this.x,this.y)}copy(Z){return q1.vec2.copy(this,Z),this}distance(Z){return q1.vec2.distance(this,Z)}divide(Z){return q1.vec2.divide(this,this,Z),this}dot(Z){return q1.vec2.dot(this,Z)}equals(Z){return q1.vec2.equals(this,Z)}exactEquals(Z){return q1.vec2.exactEquals(this,Z)}floor(){return q1.vec2.floor(this,this),this}invert(){return q1.vec2.inverse(this,this),this}lerp(Z,J){return q1.vec2.lerp(this,this,Z,J),this}max(Z){return q1.vec2.max(this,this,Z),this}min(Z){return q1.vec2.min(this,this,Z),this}multiply(Z){return q1.vec2.mul(this,this,Z),this}negate(){return q1.vec2.negate(this,this),this}normalize(){return q1.vec2.normalize(this,this),this}randomize(Z){return q1.vec2.random(this,Z),this}rotate(Z,J){return q1.vec2.rotate(this,this,Z,J),this}round(){return q1.vec2.round(this,this),this}scale(Z){return q1.vec2.scale(this,this,Z),this}scaleAndAdd(Z,J){return q1.vec2.scaleAndAdd(this,this,Z,J),this}subtract(Z){return q1.vec2.sub(this,this,Z),this}toString(){return`${this.x},${this.y}`}transformMatrix2(Z){return q1.vec2.transformMat2(this,this,Z),this}transformMatrix3(Z){return q1.vec2.transformMat3(this,this,Z),this}transformMatrix4(Z){return q1.vec2.transformMat4(this,this,Z),this}zero(){return q1.vec2.zero(this),this}}var z1=t(kQ(),1);class DW extends Float32Array{constructor(Z,J,X){super([Z,J,X])}get length(){return z1.vec3.length(this)}get squaredLength(){return z1.vec3.squaredLength(this)}get magnitude(){return z1.vec3.length(this)}get squaredMagnitude(){return z1.vec3.squaredLength(this)}get x(){return this[0]}set x(Z){this[0]=Z}get y(){return this[1]}set y(Z){this[1]=Z}get z(){return this[2]}set z(Z){this[2]=Z}static create(){return new DW(0,0,0)}static fromVector3Like(Z){return new DW(Z.x,Z.y,Z.z)}add(Z){return z1.vec3.add(this,this,Z),this}ceil(){return z1.vec3.ceil(this,this),this}clone(){return new DW(this.x,this.y,this.z)}copy(Z){return z1.vec3.copy(this,Z),this}cross(Z){return z1.vec3.cross(this,this,Z),this}distance(Z){return z1.vec3.distance(this,Z)}divide(Z){return z1.vec3.div(this,this,Z),this}dot(Z){return z1.vec3.dot(this,Z)}equals(Z){return z1.vec3.equals(this,Z)}exactEquals(Z){return z1.vec3.exactEquals(this,Z)}floor(){return z1.vec3.floor(this,this),this}invert(){return z1.vec3.inverse(this,this),this}lerp(Z,J){return z1.vec3.lerp(this,this,Z,J),this}max(Z){return z1.vec3.max(this,this,Z),this}min(Z){return z1.vec3.min(this,this,Z),this}multiply(Z){return z1.vec3.mul(this,this,Z),this}negate(){return z1.vec3.negate(this,this),this}normalize(){return z1.vec3.normalize(this,this),this}randomize(Z){return z1.vec3.random(this,Z),this}rotateX(Z,J){return z1.vec3.rotateX(this,this,Z,J),this}rotateY(Z,J){return z1.vec3.rotateY(this,this,Z,J),this}rotateZ(Z,J){return z1.vec3.rotateZ(this,this,Z,J),this}round(){return z1.vec3.round(this,this),this}scale(Z){return z1.vec3.scale(this,this,Z),this}scaleAndAdd(Z,J){return z1.vec3.scaleAndAdd(this,this,Z,J),this}subtract(Z){return z1.vec3.sub(this,this,Z),this}toString(){return`${this.x},${this.y},${this.z}`}transformMatrix3(Z){return z1.vec3.transformMat3(this,this,Z),this}transformMatrix4(Z){return z1.vec3.transformMat4(this,this,Z),this}transformQuaternion(Z){return z1.vec3.transformQuat(this,this,Z),this}zero(){return z1.vec3.zero(this),this}}var mW1=t(SW1(),1);var AW1=0.099856;class TH extends x${faceSpeed=0;idleLoopedAnimations=[];idleLoopedAnimationsSpeed;jumpOneshotAnimations=[];moveLoopedAnimations=[];moveLoopedAnimationsSpeed;moveSpeed=0;_faceTarget;_jumpHeight=0;_moveCompletesWhenStuck=!1;_moveIgnoreAxes={};_moveStartMoveAnimations=!1;_moveStartIdleAnimationsOnCompletion=!0;_moveStoppingDistanceSquared=AW1;_moveStuckAccumulatorMs=0;_moveStuckLastPosition;_moveTarget;_onFace;_onFaceComplete;_onMove;_onMoveComplete;_stopFaceRequested=!1;_stopMoveRequested=!1;constructor(Z={}){super();this.idleLoopedAnimations=Z.idleLoopedAnimations??this.idleLoopedAnimations,this.idleLoopedAnimationsSpeed=Z.idleLoopedAnimationsSpeed??this.idleLoopedAnimationsSpeed,this.jumpOneshotAnimations=Z.jumpOneshotAnimations??this.jumpOneshotAnimations,this.moveLoopedAnimations=Z.moveLoopedAnimations??this.moveLoopedAnimations,this.moveLoopedAnimationsSpeed=Z.moveLoopedAnimationsSpeed??this.moveLoopedAnimationsSpeed}spawn(Z){super.spawn(Z),this._startIdleAnimations(Z)}face(Z,J,X){this._faceTarget=Z,this.faceSpeed=J,this._onFace=X?.faceCallback,this._onFaceComplete=X?.faceCompleteCallback}jump(Z){this._jumpHeight=Z}move(Z,J,X){this.moveSpeed=J,this._moveCompletesWhenStuck=X?.moveCompletesWhenStuck??!1,this._moveIgnoreAxes=X?.moveIgnoreAxes??{},this._moveStartIdleAnimationsOnCompletion=X?.moveStartIdleAnimationsOnCompletion??!0,this._moveStartMoveAnimations=!0,this._moveStoppingDistanceSquared=X?.moveStoppingDistance?X.moveStoppingDistance**2:AW1,this._moveTarget=Z,this._onMove=X?.moveCallback,this._onMoveComplete=X?.moveCompleteCallback,this._moveStuckAccumulatorMs=0,this._moveStuckLastPosition=void 0}stopFace(){this._stopFaceRequested=!0}stopMove(){this._stopMoveRequested=!0}tick(Z,J){if(super.tick(Z,J),!this._moveTarget&&!this._faceTarget&&!this._jumpHeight)return;if(this._moveStartMoveAnimations)this._startMoveAnimations(Z),this._moveStartMoveAnimations=!1;let X=J/1000,$=Z.position;if(Z.isDynamic&&this._jumpHeight>0){let Y=Math.abs(Z.world.simulation.gravity.y),Q=Math.sqrt(2*Y*this._jumpHeight);Z.applyImpulse({x:0,y:Q*Z.mass,z:0}),this._jumpHeight=0,this._startJumpAnimations(Z)}if(this._moveTarget){let Y={x:this._moveIgnoreAxes.x?0:this._moveTarget.x-$.x,y:this._moveIgnoreAxes.y?0:this._moveTarget.y-$.y,z:this._moveIgnoreAxes.z?0:this._moveTarget.z-$.z},Q=Y.x*Y.x+Y.y*Y.y+Y.z*Y.z,K=!1;if(this._moveCompletesWhenStuck){if(this._moveStuckAccumulatorMs+=J,this._moveStuckAccumulatorMs>=500){if(this._moveStuckLastPosition){let W=$.x-this._moveStuckLastPosition.x,G=$.y-this._moveStuckLastPosition.y,z=$.z-this._moveStuckLastPosition.z;K=Math.sqrt(W*W+G*G+z*z)<this.moveSpeed*0.1}this._moveStuckLastPosition=$,this._moveStuckAccumulatorMs=0}}if(Q>this._moveStoppingDistanceSquared&&!this._stopMoveRequested&&!K){let W=Math.sqrt(Q),G=this.moveSpeed*X,v=Math.min(W,G)/W,H={x:$.x+Y.x*v,y:$.y+Y.y*v,z:$.z+Y.z*v};if(Z.setPosition(H),this._onMove)this._onMove(H,this._moveTarget)}else{if(this._moveStuckAccumulatorMs=0,this._moveStuckLastPosition=void 0,this._moveTarget=void 0,this._stopMoveRequested=!1,this._moveStartIdleAnimationsOnCompletion)this._startIdleAnimations(Z);if(this._onMoveComplete){let W=this._onMoveComplete;this._onMove=void 0,this._onMoveComplete=void 0,W($)}}}if(this._faceTarget){let Y={x:this._faceTarget.x-$.x,z:this._faceTarget.z-$.z},Q=Math.atan2(-Y.x,-Y.z),K=Z.rotation,W=Math.atan2(2*(K.w*K.y),1-2*(K.y*K.y)),G=Q-W;while(G>Math.PI)G-=2*Math.PI;while(G<-Math.PI)G+=2*Math.PI;if(Math.abs(G)>0.01&&!this._stopFaceRequested){let z=this.faceSpeed*X,v=Math.abs(G)<z?G:Math.sign(G)*z,V=(W+v)/2,q={x:0,y:Math.fround(Math.sin(V)),z:0,w:Math.fround(Math.cos(V))};if(Z.setRotation(q),this._onFace)this._onFace(K,q)}else if(this._faceTarget=void 0,this._stopFaceRequested=!1,this._onFaceComplete){let z=this._onFaceComplete;this._onFace=void 0,this._onFaceComplete=void 0,z(Z.rotation)}}}_startIdleAnimations(Z){if(this.idleLoopedAnimationsSpeed)Z.setModelAnimationsPlaybackRate(this.idleLoopedAnimationsSpeed);Z.stopModelAnimations(this.moveLoopedAnimations),Z.stopModelAnimations(this.jumpOneshotAnimations),Z.startModelLoopedAnimations(this.idleLoopedAnimations)}_startJumpAnimations(Z){Z.stopModelAnimations(this.moveLoopedAnimations),Z.stopModelAnimations(this.idleLoopedAnimations),Z.startModelOneshotAnimations(this.jumpOneshotAnimations)}_startMoveAnimations(Z){if(this.moveLoopedAnimationsSpeed)Z.setModelAnimationsPlaybackRate(this.moveLoopedAnimationsSpeed);Z.stopModelAnimations(this.jumpOneshotAnimations),Z.stopModelAnimations(this.idleLoopedAnimations),Z.startModelLoopedAnimations(this.moveLoopedAnimations)}}class HA extends TH{_debug=!1;_entity;_maxFall=0;_maxJump=0;_maxOpenSetIterations=200;_onPathfindAbort;_onPathfindComplete;_onWaypointMoveComplete;_onWaypointMoveSkipped;_speed=0;_target;_verticalPenalty=0;_waypoints=[];_waypointNextIndex=0;_waypointStoppingDistance;_waypointTimeoutMs=2000;constructor(Z={}){super(Z)}get debug(){return this._debug}get maxFall(){return this._maxFall}get maxJump(){return this._maxJump}get maxOpenSetIterations(){return this._maxOpenSetIterations}get speed(){return this._speed}get target(){return this._target}get verticalPenalty(){return this._verticalPenalty}get waypoints(){return this._waypoints}get waypointNextIndex(){return this._waypointNextIndex}get waypointTimeoutMs(){return this._waypointTimeoutMs}pathfind(Z,J,X){if(this._target=Z,this._speed=J,this._debug=X?.debug??!1,this._maxFall=X?.maxFall?-Math.abs(X.maxFall):0,this._maxJump=X?.maxJump?Math.abs(X.maxJump):0,this._maxOpenSetIterations=X?.maxOpenSetIterations??200,this._onPathfindAbort=X?.pathfindAbortCallback,this._onPathfindComplete=X?.pathfindCompleteCallback,this._onWaypointMoveComplete=X?.waypointMoveCompleteCallback,this._onWaypointMoveSkipped=X?.waypointMoveSkippedCallback,this._verticalPenalty=X?.verticalPenalty??0,this._waypoints=[],this._waypointNextIndex=0,this._waypointStoppingDistance=X?.waypointStoppingDistance,this._waypointTimeoutMs=X?.waypointTimeoutMs??2000/J,!this._calculatePath())return!1;return this._moveToNextWaypoint(),!0}attach(Z){super.attach(Z),this._entity=Z}detach(Z){super.detach(Z),this._entity=void 0}_calculatePath(){if(!this._target||!this._entity?.world)return p.error("PathfindingEntityController._calculatePath: No target or world"),!1;let Z=this._entity.height,J=this._findGroundedStart();if(!J){if(this._debug)p.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)},$=Math.abs(X.x-J.x),Y=Math.abs(X.y-J.y),Q=Math.abs(X.z-J.z);if($<=2&&Y<=2&&Q<=2&&!this._isNeighborCoordinateBlocked(J,X,this._entity.height))return this._waypoints=[{x:J.x+0.5,y:J.y+Z/2,z:J.z+0.5},{x:X.x+0.5,y:X.y+Z/2,z:X.z+0.5}],!0;if(J.x===X.x&&J.y===X.y&&J.z===X.z)return this._waypoints=[{x:J.x+0.5,y:J.y+Z/2,z:J.z+0.5}],!0;let W=this._coordinateToKey(J),G=new Map,z=new Map([[W,0]]),v=new Map([[W,this._pathfindingHeuristic(J,X)]]),H=new Set,V=new mW1.Heap((j,L)=>{let R=v.get(j[0])??1/0,M=v.get(L[0])??1/0;return R-M});V.push([W,J]);let q=[{x:0,y:0,z:1},{x:1,y:0,z:0},{x:0,y:0,z:-1},{x:-1,y:0,z:0},{x:1,y:0,z:1},{x:1,y:0,z:-1},{x:-1,y:0,z:1},{x:-1,y:0,z:-1}],F=[];for(let j=this._maxJump;j>=this._maxFall;j--){if(j===0)continue;let L=Math.abs(J.y+j-X.y);F.push({y:j,distanceToTargetY:L})}F.sort((j,L)=>j.distanceToTargetY-L.distanceToTargetY);let x=[...q,...F.flatMap(({y:j})=>q.map((L)=>({...L,y:j})))],c=0,w=Math.abs(X.x-J.x)+Math.abs(X.y-J.y)+Math.abs(X.z-J.z),B=Math.min(this._maxOpenSetIterations,w*20);while(!V.isEmpty()&&c<B){c++;let[j,L]=V.pop();if(L.x===X.x&&L.y===X.y&&L.z===X.z){let N=this._reconstructPath(G,L);if(this._waypoints=N.map((P)=>({x:P.x+0.5,y:P.y+Z/2,z:P.z+0.5})),this._debug)console.log(`PathfindingEntityController._calculatePath: Path found after ${c} open set iterations. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`);return!0}H.add(j);let R=z.get(j),M=new Map;for(let N of x){let P=`${N.x},${N.z}`,O=N.y<0;if(O&&M.has(P))continue;let _={x:L.x+N.x,y:L.y+N.y,z:L.z+N.z};if(Math.abs(X.x-_.x)+Math.abs(X.y-_.y)+Math.abs(X.z-_.z)>w*1.5)continue;let h=this._coordinateToKey(_);if(H.has(h))continue;let f=this._isNeighborCoordinateBlocked(L,_,this._entity.height);if(O&&f){M.set(P,!0);continue}if(f)continue;let C=Math.abs(N.x),b=Math.abs(N.y),I=Math.abs(N.z),a=b===0?0:this._verticalPenalty,s=(Math.max(C,b,I)===1&&C+b+I>1?1.4:1)+a,Z0=R+s,o=z.get(h)??1/0;if(Z0>=o)continue;G.set(h,L),z.set(h,Z0);let M0=Z0+this._pathfindingHeuristic(_,X);v.set(h,M0),V.push([h,_])}}if(c>=B){if(this._onPathfindAbort?.(),this._debug)p.warning(`PathfindingEntityController._calculatePath: Maximum open set iterations reached (${B}), path search aborted. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`)}else if(this._debug)p.warning(`PathfindingEntityController._calculatePath: No valid path found. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`);return this._target=void 0,this._waypoints=[],!1}_reconstructPath(Z,J){let X=[J],$=J;while(Z.has(this._coordinateToKey($)))$=Z.get(this._coordinateToKey($)),X.unshift($);return X}_coordinateToKey(Z){return`${Z.x},${Z.y},${Z.z}`}_moveToNextWaypoint(){let Z=this._waypointNextIndex>0?this._waypoints[this._waypointNextIndex-1]:void 0,J=this._waypoints[this._waypointNextIndex];if(!J||!this._entity)return;let X=0;if(this._entity.isDynamic&&Z&&J.y>Z.y){let $=J.y-Z.y,Y=Math.min($,this._maxJump)+0.75;this.jump(Y);let Q=Math.abs(this._entity.world.simulation.gravity.y),K=Math.sqrt(2*Q*Y),W=Z.x+0.5,G=Z.z+0.5,z=J.x+0.5,v=J.z+0.5,H=z-W,V=v-G,q=Math.sqrt(H*H+V*V),F=K/Q,x=q/this._speed;X=Math.min(F*0.8,x)*1000}setTimeout(()=>{if(!this._entity)return;let $=Date.now();this.face(J,this._speed),this.move(J,this._speed,{moveCompletesWhenStuck:!0,moveIgnoreAxes:{y:this._entity.isDynamic},moveStartIdleAnimationsOnCompletion:this._waypointNextIndex===this._waypoints.length-1,moveStoppingDistance:this._waypointStoppingDistance,moveCallback:()=>{if(Date.now()-$>this._waypointTimeoutMs&&this._waypointNextIndex<this._waypoints.length-1)this._onWaypointMoveSkipped?.(J,this._waypointNextIndex),this._waypointNextIndex++,this._moveToNextWaypoint()},moveCompleteCallback:()=>{if(this._waypointNextIndex<this._waypoints.length-1)this._onWaypointMoveComplete?.(J,this._waypointNextIndex),this._waypointNextIndex++,this._moveToNextWaypoint();else this._onPathfindComplete?.()}})},X)}_pathfindingHeuristic(Z,J){return Math.abs(Z.x-J.x)+Math.abs(Z.y-J.y)+Math.abs(Z.z-J.z)}_isNeighborCoordinateBlocked(Z,J,X){if(!this._entity?.world)return!1;let $=this._entity.world,Y=Math.floor(J.x),Q=Math.floor(J.y),K=Math.floor(J.z),W=Math.floor(Z.x),G=Math.floor(Z.z);if(!$.chunkLattice.hasBlock({x:Y,y:Q-1,z:K}))return!0;for(let z=0;z<X;z++)if($.chunkLattice.hasBlock({x:Y,y:Q+z,z:K}))return!0;if(Y!==W&&K!==G)for(let z=0;z<X;z++){let v=$.chunkLattice.hasBlock({x:Y,y:Q+z,z:G}),H=$.chunkLattice.hasBlock({x:W,y:Q+z,z:K});if(v||H)return!0}return!1}_findGroundedStart(){if(!this._entity?.world)return;let{x:Z,y:J,z:X}=this._entity.position,$={x:Math.floor(Z),y:Math.floor(J),z:Math.floor(X)};for(let Y=0;Y<=Math.abs(this._maxFall);Y++)if(this._entity.world.chunkLattice.hasBlock({...$,y:$.y-Y-1}))return{...$,y:$.y-Y};return}}export{oJ6 as startServer,s31 as WorldManagerEvent,q$ as WorldManager,n31 as WorldLoopEvent,NH as WorldLoop,$A as WorldEvent,OH as World,kf as WebServerEvent,FK as WebServer,DW as Vector3,PH as Vector2,RH as Ticker,PQ as TelemetrySpanOperation,V8 as Telemetry,XA as SimulationEvent,LH as Simulation,TH as SimpleEntityController,MH as SceneUIManager,iP as SceneUIEvent,mz as SceneUI,N80 as SUPPORTED_INPUT_KEYS,oG as RigidBodyType,u$ as RigidBody,LW as Quaternion,gc as PlayerUIEvent,Iz as PlayerUI,o31 as PlayerManagerEvent,n5 as PlayerManager,_z as PlayerEvent,F7 as PlayerEntity,R80 as PlayerCameraMode,uP as PlayerCameraEvent,Ez as PlayerCamera,g3 as Player,e$ as PersistenceManager,HA as PathfindingEntityController,DH as ParticleEmitterManager,eS as ParticleEmitterEvent,ZA as ParticleEmitter,Cf as PORT,f80 as PLAYER_ROTATION_UPDATE_THRESHOLD,C80 as PLAYER_POSITION_UPDATE_THRESHOLD_SQ,j6 as ModelRegistry,W5 as Matrix4,p7 as Matrix3,EQ as Matrix2,a31 as LightType,jH as LightManager,rS as LightEvent,tS as Light,r8 as IterationMap,r31 as GameServerEvent,TQ as GameServer,B0 as EventRouter,p as ErrorHandler,uz as EntityManager,Az as EntityEvent,j8 as Entity,T80 as ENTITY_ROTATION_UPDATE_THRESHOLD,P80 as ENTITY_POSITION_UPDATE_THRESHOLD_SQ,b1 as DefaultPlayerEntityController,gP as DefaultPlayerEntity,O80 as DEFAULT_ENTITY_RIGID_BODY_OPTIONS,v9 as CollisionGroupsBuilder,B$ as CollisionGroup,O3 as ColliderShape,Sz as ColliderMap,S5 as Collider,lN as CoefficientCombineRule,pP as ChunkLatticeEvent,hz as ChunkLattice,p5 as Chunk,bz as ChatManager,lP as ChatEvent,pN as BlockTypeRegistryEvent,rG as BlockTypeRegistry,yN as BlockTypeEvent,A5 as BlockType,bQ as Block,BA as BaseEntityControllerEvent,x$ as BaseEntityController,NW as AudioManager,$L as AudioEvent,RW as Audio};
483
+ `);let{connect:G,buffered:z}=await W;if(Z.emit("proxyConnect",G),this.emit("proxyConnect",G,Z),G.statusCode===200){if(Z.once("socket",BJ6),J.secureEndpoint){UH("Upgrading socket connection to TLS");let H=J.servername||J.host;return iS.connect({...C31(J,"host","path","port"),socket:$,servername:jJ.isIP(H)?void 0:H})}return $}$.destroy();let v=new jJ.Socket({writable:!1});return v.readable=!0,Z.once("socket",(H)=>{UH("Replaying proxy buffer for failed request"),H.push(z),H.push(null)}),v}}Ej.__initStatic();function BJ6(Z){Z.resume()}function C31(Z,...J){let X={},$;for($ in Z)if(!J.includes($))X[$]=Z[$];return X}var RJ6=32768;function NJ6(Z){return new DJ6({read(){this.push(Z),this.push(null)}})}function Ij(Z){let J;try{J=new URL(Z.url)}catch(G){return t1(()=>{console.warn("[@sentry/node]: Invalid dsn or tunnel option, will not send any events. The tunnel option must be a full URL when used.")}),CK(Z,()=>Promise.resolve({}))}let X=J.protocol==="https:",$=OJ6(J,Z.proxy||(X?process.env.https_proxy:void 0)||process.env.http_proxy),Y=X?LJ6:jJ6,Q=Z.keepAlive===void 0?!1:Z.keepAlive,K=$?new Ej($):new Y.Agent({keepAlive:Q,maxSockets:30,timeout:2000}),W=PJ6(Z,Z.httpModule??Y,K);return CK(Z,W)}function OJ6(Z,J){let{no_proxy:X}=process.env;if(X?.split(",").some((Y)=>Z.host.endsWith(Y)||Z.hostname.endsWith(Y)))return;else return J}function PJ6(Z,J,X){let{hostname:$,pathname:Y,port:Q,protocol:K,search:W}=new URL(Z.url);return function G(z){return new Promise((v,H)=>{mv(()=>{let V=NJ6(z.body),q={...Z.headers};if(z.body.length>RJ6)q["content-encoding"]="gzip",V=V.pipe(MJ6());let F=J.request({method:"POST",agent:X,headers:q,hostname:$,path:`${Y}${W}`,port:Q,protocol:K,ca:Z.caCerts},(x)=>{x.on("data",()=>{}),x.on("end",()=>{}),x.setEncoding("utf8");let c=x.headers["retry-after"]??null,w=x.headers["x-sentry-rate-limits"]??null;v({statusCode:x.statusCode,headers:{"retry-after":c,"x-sentry-rate-limits":Array.isArray(w)?w[0]||null:w}})});F.on("error",H),V.pipe(F)})})}}var TJ6=new Set(["false","f","n","no","off","0"]),CJ6=new Set(["true","t","y","yes","on","1"]);function _j(Z,J){let X=String(Z).toLowerCase();if(TJ6.has(X))return!1;if(CJ6.has(X))return!0;return J?.strict?null:Boolean(Z)}import{posix as fJ6,sep as kJ6}from"node:path";function f31(Z){return Z.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}function bj(Z=process.argv[1]?ok(process.argv[1]):process.cwd(),J=kJ6==="\\"){let X=J?f31(Z):Z;return($)=>{if(!$)return;let Y=J?f31($):$,{dir:Q,base:K,ext:W}=fJ6.parse(Y);if(W===".js"||W===".mjs"||W===".cjs")K=K.slice(0,W.length*-1);let G=decodeURIComponent(K);if(!Q)Q=".";let z=Q.lastIndexOf("/node_modules");if(z>-1)return`${Q.slice(z+14).replace(/\//g,".")}:${G}`;if(Q.startsWith(X)){let v=Q.slice(X.length+1).replace(/\//g,".");return v?`${v}:${G}`:G}return G}}function hj(Z){if(process.env.SENTRY_RELEASE)return process.env.SENTRY_RELEASE;if(U0.SENTRY_RELEASE?.id)return U0.SENTRY_RELEASE.id;let J=process.env.GITHUB_SHA||process.env.CI_MERGE_REQUEST_SOURCE_BRANCH_SHA||process.env.CI_BUILD_REF||process.env.CI_COMMIT_SHA||process.env.BITBUCKET_COMMIT,X=process.env.APPVEYOR_PULL_REQUEST_HEAD_COMMIT||process.env.APPVEYOR_REPO_COMMIT||process.env.CODEBUILD_RESOLVED_SOURCE_VERSION||process.env.AWS_COMMIT_ID||process.env.BUILD_SOURCEVERSION||process.env.GIT_CLONE_COMMIT_HASH||process.env.BUDDY_EXECUTION_REVISION||process.env.BUILDKITE_COMMIT||process.env.CIRCLE_SHA1||process.env.CIRRUS_CHANGE_IN_REPO||process.env.CF_REVISION||process.env.CM_COMMIT||process.env.CF_PAGES_COMMIT_SHA||process.env.DRONE_COMMIT_SHA||process.env.FC_GIT_COMMIT_SHA||process.env.HEROKU_TEST_RUN_COMMIT_VERSION||process.env.HEROKU_SLUG_COMMIT||process.env.RAILWAY_GIT_COMMIT_SHA||process.env.RENDER_GIT_COMMIT||process.env.SEMAPHORE_GIT_SHA||process.env.TRAVIS_PULL_REQUEST_SHA||process.env.VERCEL_GIT_COMMIT_SHA||process.env.VERCEL_GITHUB_COMMIT_SHA||process.env.VERCEL_GITLAB_COMMIT_SHA||process.env.VERCEL_BITBUCKET_COMMIT_SHA||process.env.ZEIT_GITHUB_COMMIT_SHA||process.env.ZEIT_GITLAB_COMMIT_SHA||process.env.ZEIT_BITBUCKET_COMMIT_SHA,$=process.env.CI_COMMIT_ID||process.env.SOURCE_COMMIT||process.env.SOURCE_VERSION||process.env.GIT_COMMIT||process.env.COMMIT_REF||process.env.BUILD_VCS_NUMBER||process.env.CI_COMMIT_SHA;return J||X||$||Z}var Sj=xU(GE(bj()));var E31=t($0(),1),I31=t(Q1(),1);import*as k31 from"node:os";import{threadId as EJ6,isMainThread as IJ6}from"worker_threads";var _J6=60000;class BH extends fU{constructor(Z){let J=Z.serverName||global.process.env.SENTRY_NAME||k31.hostname(),X={...Z,platform:"node",runtime:{name:"node",version:global.process.version},serverName:J};if(Z.openTelemetryInstrumentations)I31.registerInstrumentations({instrumentations:Z.openTelemetryInstrumentations});lk(X,"node"),u.log(`Initializing Sentry: process: ${process.pid}, thread: ${IJ6?"main":`worker-${EJ6}`}.`);super(X);if(this.getOptions()._experiments?.enableLogs){if(this._logOnExitFlushListener=()=>{MX(this)},J)this.on("beforeCaptureLog",($)=>{$.attributes={...$.attributes,"server.address":J}});process.on("beforeExit",this._logOnExitFlushListener)}}get tracer(){if(this._tracer)return this._tracer;let Z="@sentry/node",J=Q8,X=E31.trace.getTracer(Z,J);return this._tracer=X,X}async flush(Z){let X=this.traceProvider?.activeSpanProcessor;if(X)await X.forceFlush();if(this.getOptions().sendClientReports)this._flushOutcomes();return super.flush(Z)}close(Z){if(this._clientReportInterval)clearInterval(this._clientReportInterval);if(this._clientReportOnExitFlushListener)process.off("beforeExit",this._clientReportOnExitFlushListener);if(this._logOnExitFlushListener)process.off("beforeExit",this._logOnExitFlushListener);return super.close(Z)}startClientReportTracking(){let Z=this.getOptions();if(Z.sendClientReports)this._clientReportOnExitFlushListener=()=>{this._flushOutcomes()},this._clientReportInterval=setInterval(()=>{A0&&u.log("Flushing client reports based on interval."),this._flushOutcomes()},Z.clientReportFlushInterval??_J6).unref(),process.on("beforeExit",this._clientReportOnExitFlushListener)}_getTraceInfoFromScope(Z){if(!Z)return[void 0,void 0];return e61(this,Z)}}var n9=t($0(),1),_31=t(Nb(),1),b31=t(Tb(),1),jW=t(U1(),1);var h31=t(S_(),1);import bJ6 from"module";var gS=1e6;function Aj(Z,J={}){if(Z.getOptions().debug)A31();let X=SJ6(Z,J);Z.traceProvider=X}function dS(){let[Z=0,J=0]=process.versions.node.split(".").map(Number);if(Z>=21||Z===20&&J>=6||Z===18&&J>=19){if(!U0._sentryEsmLoaderHookRegistered)try{let{addHookMessagePort:X}=h31.createAddHookMessageChannel();bJ6.register("import-in-the-middle/hook.mjs",import.meta.url,{data:{addHookMessagePort:X,include:[]},transferList:[X]})}catch(X){u.warn("Failed to register ESM hook",X)}}else t1(()=>{console.warn(`[Sentry] You are using Node.js v${process.versions.node} in ESM mode ("import syntax"). The Sentry Node.js SDK is not compatible with ESM in Node.js versions before 18.19.0 or before 20.6.0. Please either build your application with CommonJS ("require() syntax"), or upgrade your Node.js version.`)})}function S31(Z={}){let{debug:J}=Z;if(J)u.enable(),A31();if(!e4())dS();hJ6(Z.integrations).forEach((X)=>{if(X(),J)u.log(`[Sentry] Preloaded ${X.id} instrumentation`)})}function hJ6(Z){let J=P31();if(!Z)return J;return J.filter((X)=>Z.includes(X.id))}function SJ6(Z,J={}){let X=new b31.BasicTracerProvider({sampler:new nb(Z),resource:new _31.Resource({[jW.ATTR_SERVICE_NAME]:"node",[jW.SEMRESATTRS_SERVICE_NAMESPACE]:"sentry",[jW.ATTR_SERVICE_VERSION]:Q8}),forceFlushTimeoutMillis:500,spanProcessors:[new ab({timeout:AJ6(Z.getOptions().maxSpanWaitDuration)}),...J.spanProcessors||[]]});return n9.trace.setGlobalTracerProvider(X),n9.propagation.setGlobalPropagator(new yb),n9.context.setGlobalContextManager(new Cj),X}function AJ6(Z){if(Z==null)return;if(Z>gS)return A0&&u.warn(`\`maxSpanWaitDuration\` is too high, using the maximum value of ${gS}`),gS;else if(Z<=0||Number.isNaN(Z)){A0&&u.warn("`maxSpanWaitDuration` must be a positive number, using default value instead.");return}return Z}function A31(){let Z=new Proxy(u,{get(J,X,$){return Reflect.get(J,X==="verbose"?"debug":X,$)}});n9.diag.disable(),n9.diag.setLogger(Z,n9.DiagLogLevel.DEBUG)}function mJ6(){return e4()?[LB()]:[]}function aS(){return[nv(),av(),sv(),ov(),rv(),zB(),qB(),DB(),MB(),wB(),jB(),cB(),Pj(),O31(),...mJ6()]}function nS(Z){return[...aS(),...s6(Z)?fj():[]]}function mj(Z={}){return u31(Z,nS)}function m31(Z={}){return u31(Z,()=>[])}function u31(Z={},J){let X=uJ6(Z,J);if(X.debug===!0)if(A0)u.enable();else t1(()=>{console.warn("[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.")});if(!e4()&&X.registerEsmLoaderHooks!==!1)dS();if(QB(),i0().update(X.initialScope),X.spotlight&&!X.integrations.some(({name:Q})=>Q===CS))X.integrations.push(xj({sidecarUrl:typeof X.spotlight==="string"?X.spotlight:void 0}));let Y=new BH(X);if(i0().setClient(Y),Y.init(),u.log(`Running in ${e4()?"CommonJS":"ESM"} mode.`),Y.startClientReportTracking(),pJ6(),!X.skipOpenTelemetrySetup)Aj(Y,{spanProcessors:X.openTelemetrySpanProcessors}),sS();return i61(Y),Z51(Y),Y}function sS(){if(!A0)return;let Z=n61(),J=["SentryContextManager","SentryPropagator"];if(s6())J.push("SentrySpanProcessor");for(let X of J)if(!Z.includes(X))u.error(`You have to set up the ${X}. Without this, the OpenTelemetry & Sentry integration will not work properly.`);if(!Z.includes("SentrySampler"))u.warn("You have to set up the SentrySampler. Without this, the OpenTelemetry & Sentry integration may still work, but sample rates set for the Sentry SDK will not be respected. If you use a custom sampler, make sure to use `wrapSamplingDecision`.")}function uJ6(Z,J){let X=lJ6(Z.release),$=Z.spotlight??_j(process.env.SENTRY_SPOTLIGHT,{strict:!0})??process.env.SENTRY_SPOTLIGHT,Y=yJ6(Z.tracesSampleRate),Q={...Z,dsn:Z.dsn??process.env.SENTRY_DSN,environment:Z.environment??process.env.SENTRY_ENVIRONMENT,sendClientReports:Z.sendClientReports??!0,transport:Z.transport??Ij,stackParser:rf(Z.stackParser||Sj),release:X,tracesSampleRate:Y,spotlight:$,debug:_j(Z.debug??process.env.SENTRY_DEBUG)},K=Z.integrations,W=Z.defaultIntegrations??J(Q);return{...Q,integrations:fk({defaultIntegrations:W,integrations:K})}}function lJ6(Z){if(Z!==void 0)return Z;let J=hj();if(J!==void 0)return J;return}function yJ6(Z){if(Z!==void 0)return Z;let J=process.env.SENTRY_TRACES_SAMPLE_RATE;if(!J)return;let X=parseFloat(J);return isFinite(X)?X:void 0}function pJ6(){if(_j(process.env.SENTRY_USE_ENVIRONMENT)!==!1){let Z=process.env.SENTRY_TRACE,J=process.env.SENTRY_BAGGAGE,X=fY(Z,J);i0().setPropagationContext(X)}}var iJ6=[["january","1"],["february","2"],["march","3"],["april","4"],["may","5"],["june","6"],["july","7"],["august","8"],["september","9"],["october","10"],["november","11"],["december","12"],["jan","1"],["feb","2"],["mar","3"],["apr","4"],["may","5"],["jun","6"],["jul","7"],["aug","8"],["sep","9"],["oct","10"],["nov","11"],["dec","12"],["sunday","0"],["monday","1"],["tuesday","2"],["wednesday","3"],["thursday","4"],["friday","5"],["saturday","6"],["sun","0"],["mon","1"],["tue","2"],["wed","3"],["thu","4"],["fri","5"],["sat","6"]];function OQ(Z){return iJ6.reduce((J,[X,$])=>J.replace(new RegExp(X,"gi"),$),Z)}var l31="Automatic instrumentation of CronJob only supports crontab string";function y31(Z,J){let X=!1;return new Proxy(Z,{construct($,Y){let[Q,K,W,G,z,...v]=Y;if(typeof Q!=="string")throw new Error(l31);if(X)throw new Error(`A job named '${J}' has already been scheduled`);X=!0;let H=OQ(Q);async function V(q,F){return N7(J,async()=>{try{await K(q,F)}catch(x){throw V1(x),x}},{schedule:{type:"crontab",value:H},timezone:z||void 0})}return new $(Q,V,W,G,z,...v)},get($,Y){if(Y==="from")return(Q)=>{let{cronTime:K,onTick:W,timeZone:G}=Q;if(typeof K!=="string")throw new Error(l31);if(X)throw new Error(`A job named '${J}' has already been scheduled`);X=!0;let z=OQ(K);return Q.onTick=async(v,H)=>{return N7(J,async()=>{try{await W(v,H)}catch(V){throw V1(V),V}},{schedule:{type:"crontab",value:z},timezone:G||void 0})},$.from(Q)};else return $[Y]}})}function p31(Z){return new Proxy(Z,{get(J,X){if(X==="schedule"&&J.schedule)return new Proxy(J.schedule,{apply($,Y,Q){let[K,W,G]=Q,z=G?.name,v=G?.timezone;if(!z)throw new Error('Missing "name" for scheduled job. A name is required for Sentry check-in monitoring.');let H=async()=>{return N7(z,async()=>{try{return await W()}catch(V){throw V1(V),V}},{schedule:{type:"crontab",value:OQ(K)},timezone:v})};return $.apply(Y,[K,H,G])}});else return J[X]}})}function i31(Z){return new Proxy(Z,{get(J,X){if(X==="scheduleJob")return new Proxy(J.scheduleJob,{apply($,Y,Q){let[K,W,G]=Q;if(typeof K!=="string"||typeof W!=="string"||typeof G!=="function")throw new Error("Automatic instrumentation of 'node-schedule' requires the first parameter of 'scheduleJob' to be a job name string and the second parameter to be a crontab string");let z=K,v=W;async function H(){return N7(z,async()=>{await G?.()},{schedule:{type:"crontab",value:OQ(v)}})}return $.apply(Y,[z,v,H])}});return J[X]}})}var g31={instrumentCron:y31,instrumentNodeCron:p31,instrumentNodeSchedule:i31};var PQ;((x)=>{x.BUILD_PACKETS="build_packets";x.ENTITIES_EMIT_UPDATES="entities_emit_updates";x.ENTITIES_TICK="entities_tick";x.NETWORK_SYNCHRONIZE="network_synchronize";x.NETWORK_SYNCHRONIZE_CLEANUP="network_synchronize_cleanup";x.PHYSICS_CLEANUP="physics_cleanup";x.PHYSICS_STEP="physics_step";x.SEND_ALL_PACKETS="send_all_packets";x.SEND_PACKETS="send_packets";x.SERIALIZE_FREE_BUFFERS="serialize_free_buffers";x.SERIALIZE_PACKETS="serialize_packets";x.SERIALIZE_PACKETS_ENCODE="serialize_packets_encode";x.SIMULATION_STEP="simulation_step";x.TICKER_TICK="ticker_tick";x.WORLD_TICK="world_tick"})(PQ||={});class V8{static getProcessStats(Z=!1){let J=process.memoryUsage(),X={jsHeapSizeMb:{value:J.heapUsed/1024/1024,unit:"megabyte"},jsHeapCapacityMb:{value:J.heapTotal/1024/1024,unit:"megabyte"},jsHeapUsagePercent:{value:J.heapUsed/J.heapTotal,unit:"percent"},processHeapSizeMb:{value:J.heapUsed/1024/1024,unit:"megabyte"},rssSizeMb:{value:J.rss/1024/1024,unit:"megabyte"}};if(Z)return X;return Object.fromEntries(Object.entries(X).map(([$,Y])=>[$,Y.value]))}static initializeSentry(Z,J=50){mj({dsn:Z,release:ff,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=V8.getProcessStats(),X},beforeSendTransaction:(X)=>{if(X.contexts?.trace?.op==="ticker_tick"){let Y=X?.start_timestamp,Q=X?.timestamp;if(!Y||!Q)return null;if((Q-Y)*1000>J)return X.measurements=V8.getProcessStats(!0),X}return null}})}static startSpan(Z,J){if(iv())return A4({attributes:Z.attributes,name:Z.operation,op:Z.operation},J);else return J()}static sentry(){return oS}}var d31=new YY({useFloat32:iz.ALWAYS}),dJ6=5000;class C9 extends B0{static _cachedPacketsSerializedBuffer=new Map;_closeTimeout=null;_wrtcDirectTransport=null;_wrtcClientServerTransport=null;_wrtcClientServerDataProducers=[];_wrtcClientServerDataConsumers=[];_wrtcServerClientTransport=null;_wrtcServerClientReliableDataProducer=null;_wrtcServerClientUnreliableDataProducer=null;_wrtcServerClientDataConsumers=[];_ws;id;constructor(Z,J){super();this.id=h60(),this.onPacket(Y0.PacketId.CONNECTION,this._onConnectionPacket),this.onPacket(Y0.PacketId.HEARTBEAT,this._onHeartbeatPacket),this.bindWs(Z),B0.globalInstance.emit("CONNECTION.OPENED",{connection:this,req:J})}static clearCachedPacketsSerializedBuffers(){if(C9._cachedPacketsSerializedBuffer.size>0)C9._cachedPacketsSerializedBuffer.clear()}static serializePackets(Z){for(let X of Z)if(!Y0.isValidPacket(X))return p.error(`Connection.serializePackets(): Invalid packet payload: ${JSON.stringify(X)}`);let J=C9._cachedPacketsSerializedBuffer.get(Z);if(J)return J;return V8.startSpan({operation:"serialize_packets",attributes:{packets:Z.length,packetIds:Z.map((X)=>X[0]).join(",")}},(X)=>{let $=d31.pack(Z);if($.byteLength>65536)$=gJ6($,{level:1});return X?.setAttribute("serializedBytes",$.byteLength),C9._cachedPacketsSerializedBuffer.set(Z,$),$})}bindWs(Z){let J=!!this._ws;if(J&&this._closeTimeout)clearTimeout(this._closeTimeout),this._closeTimeout=null;if(this._ws)this._ws.onmessage=()=>{},this._ws.onclose=()=>{},this._ws.onerror=()=>{},this.send([Y0.createPacket(Y0.bidirectionalPackets.connectionPacketDefinition,{k:!0})]);if(this._ws=Z,this._ws.binaryType="nodebuffer",this._ws.onmessage=(X)=>this._onMessage(X.data),this._ws.onclose=this._onWsClose,this._ws.onerror=this._onWsError,this.send([Y0.createPacket(Y0.bidirectionalPackets.connectionPacketDefinition,{i:this.id})],!0,!0),J)this.emitWithGlobal("CONNECTION.RECONNECTED",{connection:this});if(M7.instance.isWrtcEnabled)this._upgradeToWRTC()}closeWrtc(){this._closeWrtcClientServerTransport(),this._closeWrtcServerClientTransport()}disconnect(){if(this._ws.readyState!==r$.default.OPEN)return;try{this._ws.close()}catch(Z){p.error(`Connection.disconnect(): Connection disconnect failed. Error: ${Z}`)}}onPacket(Z,J){this.on("CONNECTION.PACKET_RECEIVED",({packet:X})=>{if(X[0]===Z)J(X)})}send(Z,J=!0,X=!1){if(this._closeTimeout)return;if(this._ws.readyState!==r$.default.OPEN)return;if(!J&&this._ws.bufferedAmount>4096)return;V8.startSpan({operation:"send_packets",attributes:{forceWs:X?"true":"false",wrtcConnected:this._wrtcServerClientTransport?.iceState==="completed"?"true":"false"}},()=>{try{let $=C9.serializePackets(Z);if(!$)return;if(this._wrtcServerClientTransport?.iceState==="completed"&&$.length<(this._wrtcServerClientTransport?.sctpParameters?.maxMessageSize??0)&&!X)try{(J?this._wrtcServerClientReliableDataProducer:this._wrtcServerClientUnreliableDataProducer).send($)}catch{this._ws.send($)}else this._ws.send($);this.emitWithGlobal("CONNECTION.PACKETS_SENT",{connection:this,packets:Z})}catch($){p.error(`Connection.send(): Packet send failed. Error: ${$}`)}})}_closeWrtcClientServerTransport(){this._wrtcDirectTransport?.close(),this._wrtcDirectTransport=null,this._wrtcClientServerTransport?.close(),this._wrtcClientServerTransport=null,this._wrtcClientServerDataProducers.forEach((Z)=>Z.close()),this._wrtcClientServerDataProducers=[],this._wrtcClientServerDataConsumers.forEach((Z)=>Z.close()),this._wrtcClientServerDataConsumers=[]}_closeWrtcServerClientTransport(){this._wrtcServerClientTransport?.close(),this._wrtcServerClientTransport=null,this._wrtcServerClientDataConsumers.forEach((Z)=>Z.close()),this._wrtcServerClientDataConsumers=[],this._wrtcServerClientReliableDataProducer?.close(),this._wrtcServerClientReliableDataProducer=null,this._wrtcServerClientUnreliableDataProducer?.close(),this._wrtcServerClientUnreliableDataProducer=null}_onConnectionPacket=async(Z)=>{let J=Z[1],X=J.c,$=J.d;if(X){let{i:Y,d:Q}=X,K=!1;if(Y==this._wrtcClientServerTransport?.id)await this._wrtcClientServerTransport.connect({dtlsParameters:Q}),K=!0;if(Y==this._wrtcServerClientTransport?.id)await this._wrtcServerClientTransport.connect({dtlsParameters:Q}),K=!0;if(K)this.send([Y0.createPacket(Y0.bidirectionalPackets.connectionPacketDefinition,{ca:{i:Y}})])}if($)for(let Y of $){let{s:Q,l:K}=Y,W=await this._wrtcClientServerTransport.produceData({label:K,sctpStreamParameters:Q}),G=await this._wrtcDirectTransport.consumeData({dataProducerId:W.id});this._wrtcClientServerDataProducers.push(W),this._wrtcClientServerDataConsumers.push(G),G.on("message",(z)=>this._onMessage(z)),this.send([Y0.createPacket(Y0.bidirectionalPackets.connectionPacketDefinition,{pa:{i:W.id,l:K}})])}};_onHeartbeatPacket=()=>{this.send([Y0.createPacket(Y0.bidirectionalPackets.heartbeatPacketDefinition,null)],!0,!0)};_onMessage=(Z)=>{try{let J=this._deserialize(Z);if(!J)return;this.emitWithGlobal("CONNECTION.PACKET_RECEIVED",{connection:this,packet:J})}catch(J){p.error(`Connection._ws.onmessage(): Error: ${J}`)}};_onWrtcIceStateChange=(Z,J)=>{if(["disconnected","closed"].includes(J)){if(Z==this._wrtcClientServerTransport)this._closeWrtcClientServerTransport();else if(Z==this._wrtcServerClientTransport)this._closeWrtcServerClientTransport()}};_onWsClose=()=>{this.closeWrtc(),this.emitWithGlobal("CONNECTION.DISCONNECTED",{connection:this}),this._closeTimeout=setTimeout(()=>{this.emitWithGlobal("CONNECTION.CLOSED",{connection:this}),this.offAll()},dJ6)};_onWsError=(Z)=>{this.emitWithGlobal("CONNECTION.ERROR",{connection:this,error:Z})};_upgradeToWRTC=async()=>{let Z=await M7.instance.createWrtcTransports();if(!Z)return!1;let{directTransport:J,clientServerTransport:X,serverClientTransport:$}=Z;this._wrtcDirectTransport=J,this._wrtcClientServerTransport=X,this._wrtcClientServerTransport.on("icestatechange",(K)=>{this._onWrtcIceStateChange(this._wrtcClientServerTransport,K)}),this._wrtcServerClientTransport=$,this._wrtcServerClientTransport.on("icestatechange",(K)=>{this._onWrtcIceStateChange(this._wrtcServerClientTransport,K)}),this._wrtcServerClientReliableDataProducer=await this._wrtcServerClientTransport.produceData({label:"scr",sctpStreamParameters:{streamId:0,ordered:!0}}),this._wrtcServerClientUnreliableDataProducer=await this._wrtcServerClientTransport.produceData({label:"scu",sctpStreamParameters:{streamId:1,ordered:!1,maxPacketLifeTime:35}});let Y=await this._wrtcServerClientTransport.consumeData({dataProducerId:this._wrtcServerClientReliableDataProducer.id}),Q=await this._wrtcServerClientTransport.consumeData({dataProducerId:this._wrtcServerClientUnreliableDataProducer.id});return this._wrtcServerClientDataConsumers.push(Y,Q),this.send([Y0.createPacket(Y0.bidirectionalPackets.connectionPacketDefinition,{d:[{i:Y.id,pi:Y.dataProducerId,l:"scr",s:Y.sctpStreamParameters},{i:Q.id,pi:Q.dataProducerId,l:"scu",s:Q.sctpStreamParameters}],t:[{i:this._wrtcClientServerTransport.id,f:"cs",d:this._wrtcClientServerTransport.dtlsParameters,ic:this._wrtcClientServerTransport.iceCandidates,ip:this._wrtcClientServerTransport.iceParameters,s:this._wrtcClientServerTransport.sctpParameters},{i:this._wrtcServerClientTransport.id,f:"sc",d:this._wrtcServerClientTransport.dtlsParameters,ic:this._wrtcServerClientTransport.iceCandidates,ip:this._wrtcServerClientTransport.iceParameters,s:this._wrtcServerClientTransport.sctpParameters}]})]),!0};_deserialize(Z){let J=d31.unpack(Z);if(!J||typeof J!=="object"||typeof J[0]!=="number")return p.error(`Connection._deserialize(): Invalid packet format. Packet: ${JSON.stringify(J)}`);if(!Y0.isValidPacket(J))return p.error(`Connection._deserialize(): Invalid packet payload. Packet: ${JSON.stringify(J)}`);return J}}class jH{_lights=new Map;_nextLightId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}despawnEntityAttachedLights(Z){this.getAllEntityAttachedLights(Z).forEach((J)=>{J.despawn()})}getAllLights(){return Array.from(this._lights.values())}getAllEntityAttachedLights(Z){return this.getAllLights().filter((J)=>J.attachedToEntity===Z)}registerLight(Z){if(Z.id!==void 0)return Z.id;let J=this._nextLightId;return this._lights.set(J,Z),this._nextLightId++,J}unregisterLight(Z){if(Z.id===void 0)return;this._lights.delete(Z.id)}}class r8{_map=new Map;_values=[];_isDirty=!1;get size(){return this._map.size}get valuesArray(){if(this._isDirty)this._syncArray();return this._values}get(Z){return this._map.get(Z)}set(Z,J){let X=this._map.has(Z);if(this._map.set(Z,J),!X)this._values.push(J);else this._isDirty=!0;return this}has(Z){return this._map.has(Z)}delete(Z){let J=this._map.delete(Z);if(J)this._isDirty=!0;return J}clear(){this._map.clear(),this._values.length=0,this._isDirty=!1}forEach(Z,J){this._map.forEach((X,$)=>{Z.call(J,X,$,this)})}keys(){return this._map.keys()}values(){return this._map.values()}entries(){return this._map.entries()}[Symbol.iterator](){return this._map[Symbol.iterator]()}_syncArray(){this._values.length=0;for(let Z of this._map.values())this._values.push(Z);this._isDirty=!1}}var a31;((X)=>{X[X.POINTLIGHT=0]="POINTLIGHT";X[X.SPOTLIGHT=1]="SPOTLIGHT"})(a31||={});var rS;((V)=>{V.DESPAWN="LIGHT.DESPAWN";V.SET_ANGLE="LIGHT.SET_ANGLE";V.SET_ATTACHED_TO_ENTITY="LIGHT.SET_ATTACHED_TO_ENTITY";V.SET_COLOR="LIGHT.SET_COLOR";V.SET_DISTANCE="LIGHT.SET_DISTANCE";V.SET_INTENSITY="LIGHT.SET_INTENSITY";V.SET_OFFSET="LIGHT.SET_OFFSET";V.SET_PENUMBRA="LIGHT.SET_PENUMBRA";V.SET_POSITION="LIGHT.SET_POSITION";V.SET_TRACKED_ENTITY="LIGHT.SET_TRACKED_ENTITY";V.SET_TRACKED_POSITION="LIGHT.SET_TRACKED_POSITION";V.SPAWN="LIGHT.SPAWN"})(rS||={});class tS extends B0{_id;_angle;_attachedToEntity;_color;_distance;_intensity;_offset;_penumbra;_position;_trackedEntity;_trackedPosition;_type;_world;constructor(Z){if(!!Z.attachedToEntity===!!Z.position)p.fatalError("Either attachedToEntity or position must be set, but not both.");super();p.warning("WARNING: Lights are poorly optimized at this time. Using more than a few lights in your game can cause extremely bad performance (FPS) issues. Use lights sparingly!"),this._angle=Z.angle,this._attachedToEntity=Z.attachedToEntity,this._color=Z.color??{r:255,g:255,b:255},this._distance=Z.distance,this._intensity=Z.intensity??1,this._offset=Z.offset,this._penumbra=Z.penumbra,this._position=Z.position,this._trackedEntity=Z.trackedEntity,this._trackedPosition=Z.trackedPosition,this._type=Z.type??0}get id(){return this._id}get angle(){return this._angle}get attachedToEntity(){return this._attachedToEntity}get color(){return this._color}get distance(){return this._distance}get intensity(){return this._intensity}get isSpawned(){return this._id!==void 0}get offset(){return this._offset}get penumbra(){return this._penumbra}get position(){return this._position}get trackedEntity(){return this._trackedEntity}get trackedPosition(){return this._trackedPosition}get type(){return this._type}get world(){return this._world}setAngle(Z){if(this._angle===Z)return;if(this._angle=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ANGLE",{light:this,angle:Z})}setAttachedToEntity(Z){if(!Z.isSpawned)return p.error(`Light.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);if(this._attachedToEntity===Z)return;if(this._attachedToEntity=Z,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ATTACHED_TO_ENTITY",{light:this,entity:Z})}setColor(Z){if(this._color.r===Z.r&&this._color.g===Z.g&&this._color.b===Z.b)return;if(this._color=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_COLOR",{light:this,color:Z})}setDistance(Z){if(this._distance===Z)return;if(this._distance=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_DISTANCE",{light:this,distance:Z})}setIntensity(Z){if(this._intensity===Z)return;if(this._intensity=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_INTENSITY",{light:this,intensity:Z})}setOffset(Z){if(this._offset&&this._offset.x===Z.x&&this._offset.y===Z.y&&this._offset.z===Z.z)return;if(this._offset=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_OFFSET",{light:this,offset:Z})}setPenumbra(Z){if(this._penumbra===Z)return;if(this._penumbra=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_PENUMBRA",{light:this,penumbra:Z})}setPosition(Z){if(this._position&&this._position.x===Z.x&&this._position.y===Z.y&&this._position.z===Z.z)return;if(this._position=Z,this._attachedToEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_POSITION",{light:this,position:Z})}setTrackedEntity(Z){if(!Z.isSpawned)return p.error(`Light.setTrackedEntity(): Entity ${Z.id} is not spawned!`);if(this._trackedEntity===Z)return;if(this._trackedEntity=Z,this._trackedPosition=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_ENTITY",{light:this,entity:Z})}setTrackedPosition(Z){if(this._trackedPosition===Z)return;if(this._trackedPosition=Z,this._trackedEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_POSITION",{light:this,position:Z})}despawn(){if(!this.isSpawned||!this._world)return;this._world.lightManager.unregisterLight(this),this.emitWithWorld(this._world,"LIGHT.DESPAWN",{light:this}),this._id=void 0,this._world=void 0}spawn(Z){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return p.error(`Light.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning Light!`);this._id=Z.lightManager.registerLight(this),this._world=Z,this.emitWithWorld(Z,"LIGHT.SPAWN",{light:this})}serialize(){return T0.serializeLight(this)}}var eS;((I)=>{I.BURST="PARTICLE_EMITTER.BURST";I.DESPAWN="PARTICLE_EMITTER.DESPAWN";I.SET_ALPHA_TEST="PARTICLE_EMITTER.SET_ALPHA_TEST";I.SET_ATTACHED_TO_ENTITY="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY";I.SET_ATTACHED_TO_ENTITY_NODE_NAME="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME";I.SET_COLOR_END="PARTICLE_EMITTER.SET_COLOR_END";I.SET_COLOR_END_VARIANCE="PARTICLE_EMITTER.SET_COLOR_END_VARIANCE";I.SET_COLOR_START="PARTICLE_EMITTER.SET_COLOR_START";I.SET_COLOR_START_VARIANCE="PARTICLE_EMITTER.SET_COLOR_START_VARIANCE";I.SET_GRAVITY="PARTICLE_EMITTER.SET_GRAVITY";I.SET_LIFETIME="PARTICLE_EMITTER.SET_LIFETIME";I.SET_LIFETIME_VARIANCE="PARTICLE_EMITTER.SET_LIFETIME_VARIANCE";I.SET_MAX_PARTICLES="PARTICLE_EMITTER.SET_MAX_PARTICLES";I.SET_OFFSET="PARTICLE_EMITTER.SET_OFFSET";I.SET_OPACITY_END="PARTICLE_EMITTER.SET_OPACITY_END";I.SET_OPACITY_END_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE";I.SET_OPACITY_START="PARTICLE_EMITTER.SET_OPACITY_START";I.SET_OPACITY_START_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE";I.SET_PAUSED="PARTICLE_EMITTER.SET_PAUSED";I.SET_POSITION="PARTICLE_EMITTER.SET_POSITION";I.SET_POSITION_VARIANCE="PARTICLE_EMITTER.SET_POSITION_VARIANCE";I.SET_RATE="PARTICLE_EMITTER.SET_RATE";I.SET_RATE_VARIANCE="PARTICLE_EMITTER.SET_RATE_VARIANCE";I.SET_SIZE_END="PARTICLE_EMITTER.SET_SIZE_END";I.SET_SIZE_END_VARIANCE="PARTICLE_EMITTER.SET_SIZE_END_VARIANCE";I.SET_SIZE_START="PARTICLE_EMITTER.SET_SIZE_START";I.SET_SIZE_START_VARIANCE="PARTICLE_EMITTER.SET_SIZE_START_VARIANCE";I.SET_TEXTURE_URI="PARTICLE_EMITTER.SET_TEXTURE_URI";I.SET_TRANSPARENT="PARTICLE_EMITTER.SET_TRANSPARENT";I.SET_VELOCITY="PARTICLE_EMITTER.SET_VELOCITY";I.SET_VELOCITY_VARIANCE="PARTICLE_EMITTER.SET_VELOCITY_VARIANCE";I.SPAWN="PARTICLE_EMITTER.SPAWN"})(eS||={});class ZA extends B0{_id;_alphaTest;_attachedToEntity;_attachedToEntityNodeName;_colorEnd;_colorEndVariance;_colorStart;_colorStartVariance;_gravity;_lifetime;_lifetimeVariance;_maxParticles;_offset;_opacityEnd;_opacityEndVariance;_opacityStart;_opacityStartVariance;_paused;_position;_positionVariance;_rate;_rateVariance;_sizeEnd;_sizeEndVariance;_sizeStart;_sizeStartVariance;_sizeVariance;_textureUri;_transparent;_velocity;_velocityVariance;_world;constructor(Z){if(!!Z.attachedToEntity===!!Z.position)p.fatalError("Either attachedToEntity or position must be set, but not both.");if(!Z.textureUri)p.fatalError("ParticleEmitter.constructor(): textureUri must be provided.");super();this._alphaTest=Z.alphaTest??0.05,this._attachedToEntity=Z.attachedToEntity,this._attachedToEntityNodeName=Z.attachedToEntityNodeName,this._colorEnd=Z.colorEnd,this._colorEndVariance=Z.colorEndVariance,this._colorStart=Z.colorStart,this._colorStartVariance=Z.colorStartVariance,this._gravity=Z.gravity,this._lifetime=Z.lifetime,this._lifetimeVariance=Z.lifetimeVariance,this._maxParticles=Z.maxParticles,this._offset=Z.offset,this._opacityEnd=Z.opacityEnd,this._opacityEndVariance=Z.opacityEndVariance,this._opacityStart=Z.opacityStart,this._opacityStartVariance=Z.opacityStartVariance,this._paused=!1,this._position=Z.position,this._positionVariance=Z.positionVariance,this._rate=Z.rate,this._rateVariance=Z.rateVariance,this._sizeEnd=Z.sizeEnd,this._sizeEndVariance=Z.sizeEndVariance,this._sizeStart=Z.sizeStart,this._sizeStartVariance=Z.sizeStartVariance,this._textureUri=Z.textureUri,this._transparent=Z.transparent,this._velocity=Z.velocity,this._velocityVariance=Z.velocityVariance}get id(){return this._id}get alphaTest(){return this._alphaTest}get attachedToEntity(){return this._attachedToEntity}get attachedToEntityNodeName(){return this._attachedToEntityNodeName}get colorEnd(){return this._colorEnd}get colorEndVariance(){return this._colorEndVariance}get colorStart(){return this._colorStart}get colorStartVariance(){return this._colorStartVariance}get gravity(){return this._gravity}get isSpawned(){return this._id!==void 0}get lifetime(){return this._lifetime}get lifetimeVariance(){return this._lifetimeVariance}get maxParticles(){return this._maxParticles}get offset(){return this._offset}get opacityEnd(){return this._opacityEnd}get opacityEndVariance(){return this._opacityEndVariance}get opacityStart(){return this._opacityStart}get opacityStartVariance(){return this._opacityStartVariance}get paused(){return this._paused}get position(){return this._position}get positionVariance(){return this._positionVariance}get rate(){return this._rate}get rateVariance(){return this._rateVariance}get sizeEnd(){return this._sizeEnd}get sizeEndVariance(){return this._sizeEndVariance}get sizeStart(){return this._sizeStart}get sizeStartVariance(){return this._sizeStartVariance}get sizeVariance(){return this._sizeVariance}get textureUri(){return this._textureUri}get transparent(){return this._transparent}get velocity(){return this._velocity}get velocityVariance(){return this._velocityVariance}get world(){return this._world}setAlphaTest(Z){if(this._alphaTest===Z)return;if(this._alphaTest=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ALPHA_TEST",{particleEmitter:this,alphaTest:Z})}setAttachedToEntity(Z){if(!Z.isSpawned)return p.error(`ParticleEmitter.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);if(this._attachedToEntity===Z)return;if(this._attachedToEntity=Z,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY",{particleEmitter:this,entity:Z})}setAttachedToEntityNodeName(Z){if(this._attachedToEntityNodeName===Z)return;if(this._attachedToEntityNodeName=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME",{particleEmitter:this,attachedToEntityNodeName:Z})}setColorEnd(Z){if(this._colorEnd&&this._colorEnd.r===Z.r&&this._colorEnd.g===Z.g&&this._colorEnd.b===Z.b)return;if(this._colorEnd=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_END",{particleEmitter:this,colorEnd:Z})}setColorEndVariance(Z){if(this._colorEndVariance&&this._colorEndVariance.r===Z.r&&this._colorEndVariance.g===Z.g&&this._colorEndVariance.b===Z.b)return;if(this._colorEndVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_END_VARIANCE",{particleEmitter:this,colorEndVariance:Z})}setColorStart(Z){if(this._colorStart&&this._colorStart.r===Z.r&&this._colorStart.g===Z.g&&this._colorStart.b===Z.b)return;if(this._colorStart=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_START",{particleEmitter:this,colorStart:Z})}setColorStartVariance(Z){if(this._colorStartVariance&&this._colorStartVariance.r===Z.r&&this._colorStartVariance.g===Z.g&&this._colorStartVariance.b===Z.b)return;if(this._colorStartVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_START_VARIANCE",{particleEmitter:this,colorStartVariance:Z})}setGravity(Z){if(this._gravity&&this._gravity.x===Z.x&&this._gravity.y===Z.y&&this._gravity.z===Z.z)return;if(this._gravity=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_GRAVITY",{particleEmitter:this,gravity:Z})}setLifetime(Z){if(this._lifetime===Z)return;if(this._lifetime=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_LIFETIME",{particleEmitter:this,lifetime:Z})}setLifetimeVariance(Z){if(this._lifetimeVariance===Z)return;if(this._lifetimeVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_LIFETIME_VARIANCE",{particleEmitter:this,lifetimeVariance:Z})}setMaxParticles(Z){if(this._maxParticles===Z)return;if(this._maxParticles=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_MAX_PARTICLES",{particleEmitter:this,maxParticles:Z})}setOffset(Z){if(this._offset&&this._offset.x===Z.x&&this._offset.y===Z.y&&this._offset.z===Z.z)return;if(this._offset=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OFFSET",{particleEmitter:this,offset:Z})}setOpacityEnd(Z){if(this._opacityEnd===Z)return;if(this._opacityEnd=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_END",{particleEmitter:this,opacityEnd:Z})}setOpacityEndVariance(Z){if(this._opacityEndVariance===Z)return;if(this._opacityEndVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE",{particleEmitter:this,opacityEndVariance:Z})}setOpacityStart(Z){if(this._opacityStart===Z)return;if(this._opacityStart=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_START",{particleEmitter:this,opacityStart:Z})}setOpacityStartVariance(Z){if(this._opacityStartVariance===Z)return;if(this._opacityStartVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE",{particleEmitter:this,opacityStartVariance:Z})}setPosition(Z){if(this._position&&this._position.x===Z.x&&this._position.y===Z.y&&this._position.z===Z.z)return;if(this._position=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_POSITION",{particleEmitter:this,position:Z})}setPositionVariance(Z){if(this._positionVariance&&this._positionVariance.x===Z.x&&this._positionVariance.y===Z.y&&this._positionVariance.z===Z.z)return;if(this._positionVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_POSITION_VARIANCE",{particleEmitter:this,positionVariance:Z})}setRate(Z){if(this._rate===Z)return;if(this._rate=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_RATE",{particleEmitter:this,rate:Z})}setRateVariance(Z){if(this._rateVariance===Z)return;if(this._rateVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_RATE_VARIANCE",{particleEmitter:this,rateVariance:Z})}setSizeEnd(Z){if(this._sizeEnd===Z)return;if(this._sizeEnd=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_END",{particleEmitter:this,sizeEnd:Z})}setSizeEndVariance(Z){if(this._sizeEndVariance===Z)return;if(this._sizeEndVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_END_VARIANCE",{particleEmitter:this,sizeEndVariance:Z})}setSizeStart(Z){if(this._sizeStart===Z)return;if(this._sizeStart=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_START",{particleEmitter:this,sizeStart:Z})}setSizeStartVariance(Z){if(this._sizeStartVariance===Z)return;if(this._sizeStartVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_START_VARIANCE",{particleEmitter:this,sizeStartVariance:Z})}setTextureUri(Z){if(this._textureUri===Z)return;if(this._textureUri=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_TEXTURE_URI",{particleEmitter:this,textureUri:Z})}setTransparent(Z){if(this._transparent===Z)return;if(this._transparent=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_TRANSPARENT",{particleEmitter:this,transparent:Z})}setVelocity(Z){if(this._velocity&&this._velocity.x===Z.x&&this._velocity.y===Z.y&&this._velocity.z===Z.z)return;if(this._velocity=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_VELOCITY",{particleEmitter:this,velocity:Z})}setVelocityVariance(Z){if(this._velocityVariance&&this._velocityVariance.x===Z.x&&this._velocityVariance.y===Z.y&&this._velocityVariance.z===Z.z)return;if(this._velocityVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_VELOCITY_VARIANCE",{particleEmitter:this,velocityVariance:Z})}burst(Z){if(this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.BURST",{particleEmitter:this,count:Z})}despawn(){if(!this.isSpawned||!this._world)return;this._world.particleEmitterManager.unregisterParticleEmitter(this),this.emitWithWorld(this._world,"PARTICLE_EMITTER.DESPAWN",{particleEmitter:this}),this._id=void 0,this._world=void 0}restart(){if(!this._paused)return;if(this._paused=!1,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_PAUSED",{particleEmitter:this,paused:this._paused})}stop(){if(this._paused)return;if(this._paused=!0,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_PAUSED",{particleEmitter:this,paused:this._paused})}spawn(Z){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return p.error(`ParticleEmitter.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning ParticleEmitter!`);this._id=Z.particleEmitterManager.registerParticleEmitter(this),this._world=Z,this.emitWithWorld(Z,"PARTICLE_EMITTER.SPAWN",{particleEmitter:this})}serialize(){return T0.serializeParticleEmitter(this)}}var aJ6={x:0,y:-32,z:0},JA=60,XA;((Y)=>{Y.STEP_START="SIMULATION.STEP_START";Y.STEP_END="SIMULATION.STEP_END";Y.DEBUG_RAYCAST="SIMULATION.DEBUG_RAYCAST";Y.DEBUG_RENDER="SIMULATION.DEBUG_RENDER"})(XA||={});class LH extends B0{_colliderMap=new Sz;_debugRaycastingEnabled=!1;_debugRenderingEnabled=!1;_debugRenderingFilterFlags;_rapierEventQueue;_rapierSimulation;_world;constructor(Z,J=JA,X=aJ6){super();this._rapierEventQueue=new X1.EventQueue(!0),this._rapierSimulation=new X1.World(X),this._rapierSimulation.timestep=Math.fround(1/J),this._world=Z}get colliderMap(){return this._colliderMap}get isDebugRaycastingEnabled(){return this._debugRaycastingEnabled}get isDebugRenderingEnabled(){return this._debugRenderingEnabled}get gravity(){return this._rapierSimulation.gravity}get timestepS(){return this._rapierSimulation.timestep}get world(){return this._world}createRawCollider(Z,J){return this._rapierSimulation.createCollider(Z,J)}createRawRigidBody(Z){return this._rapierSimulation.createRigidBody(Z)}enableDebugRaycasting(Z){this._debugRaycastingEnabled=Z}enableDebugRendering(Z,J=X1.QueryFilterFlags.EXCLUDE_FIXED){this._debugRenderingEnabled=Z,this._debugRenderingFilterFlags=J}getContactManifolds(Z,J){let X=[];return this._rapierSimulation.narrowPhase.contactPair(Z,J,($,Y)=>{if($.numContacts()===0)return;let Q=$.normal(),K=[];for(let W=0;W<$.numSolverContacts();W++)K.push($.solverContactPoint(W));X.push({contactPoints:K,localNormalA:!Y?$.localNormal1():$.localNormal2(),localNormalB:!Y?$.localNormal2():$.localNormal1(),normal:!Y?Q:{x:-Q.x,y:-Q.y,z:-Q.z}})}),X}intersectionsWithRawShape(Z,J,X,$={}){let Y=new Set,Q=[];return this._rapierSimulation.intersectionsWithShape(J,X,Z,(K)=>{let W=this._colliderMap.getColliderHandleBlockType(K.handle);if(W&&!Y.has(W))return Y.add(W),Q.push({intersectedBlockType:W}),!0;let G=this._colliderMap.getColliderHandleEntity(K.handle);if(G&&!Y.has(G))return Y.add(G),Q.push({intersectedEntity:G}),!0;return!0},$.filterFlags,$.filterGroups,$.filterExcludeCollider,$.filterExcludeRigidBody,$.filterPredicate),Q}raycast(Z,J,X,$={}){let Y=new X1.Ray(Z,J),Q=this._rapierSimulation.castRay(Y,X,$.solidMode??!0,$.filterFlags,$.filterGroups,$.filterExcludeCollider,$.filterExcludeRigidBody,$.filterPredicate);if(this._debugRaycastingEnabled)this.emitWithWorld(this._world,"SIMULATION.DEBUG_RAYCAST",{simulation:this,origin:Z,direction:J,length:X,hit:!!Q});if(!Q)return null;let K=Y.pointAt(Q.timeOfImpact),W=Q.timeOfImpact,G=Q.collider,z=this._colliderMap.getColliderHandleBlockType(G.handle);if(z)return{hitBlock:bQ.fromGlobalCoordinate({x:Math.floor(K.x-(Y.dir.x<0?0.0001:-0.0001)),y:Math.floor(K.y-(Y.dir.y<0?0.0001:-0.0001)),z:Math.floor(K.z-(Y.dir.z<0?0.0001:-0.0001))},z),hitPoint:K,hitDistance:W};let v=this._colliderMap.getColliderHandleEntity(G.handle);if(v)return{hitEntity:v,hitPoint:K,hitDistance:W};return null}removeRawCollider(Z){this._colliderMap.queueColliderHandleForCleanup(Z.handle),this._rapierSimulation.removeCollider(Z,!1)}removeRawRigidBody(Z){this._rapierSimulation.removeRigidBody(Z)}setGravity(Z){this._rapierSimulation.gravity=Z}step=(Z)=>{this.emitWithWorld(this._world,"SIMULATION.STEP_START",{simulation:this,tickDeltaMs:Z});let J=performance.now();if(V8.startSpan({operation:"physics_step"},()=>{this._rapierSimulation.step(this._rapierEventQueue)}),V8.startSpan({operation:"physics_cleanup"},()=>{this._rapierEventQueue.drainContactForceEvents(this._onContactForceEvent),this._rapierEventQueue.drainCollisionEvents(this._onCollisionEvent),this._colliderMap.cleanup()}),this.emitWithWorld(this._world,"SIMULATION.STEP_END",{simulation:this,stepDurationMs:performance.now()-J}),this._debugRenderingEnabled)this.emitWithWorld(this._world,"SIMULATION.DEBUG_RENDER",{simulation:this,...this._rapierSimulation.debugRender(this._debugRenderingFilterFlags)})};_onCollisionEvent=(Z,J,X)=>{let[$,Y]=this._getCollisionObjects(Z,J);if(!$||!Y)return;let Q=(K,W)=>{if(K instanceof A5&&W instanceof j8&&K.hasListeners("BLOCK_TYPE.ENTITY_COLLISION"))K.emit("BLOCK_TYPE.ENTITY_COLLISION",{blockType:K,entity:W,started:X,colliderHandleA:Z,colliderHandleB:J});else if(K instanceof j8&&W instanceof A5&&K.hasListeners("ENTITY.BLOCK_COLLISION"))K.emit("ENTITY.BLOCK_COLLISION",{entity:K,blockType:W,started:X,colliderHandleA:Z,colliderHandleB:J});else if(K instanceof j8&&W instanceof j8&&K.hasListeners("ENTITY.ENTITY_COLLISION"))K.emit("ENTITY.ENTITY_COLLISION",{entity:K,otherEntity:W,started:X,colliderHandleA:Z,colliderHandleB:J});else if(typeof K==="function"&&(W instanceof j8||W instanceof A5))K(W,X,Z,J)};Q($,Y),Q(Y,$)};_onContactForceEvent=(Z)=>{let[J,X]=this._getCollisionObjects(Z.collider1(),Z.collider2());if(!J||typeof J==="function"||!X||typeof X==="function")return;let $={totalForce:Z.totalForce(),totalForceMagnitude:Z.totalForceMagnitude(),maxForceDirection:Z.maxForceDirection(),maxForceMagnitude:Z.maxForceMagnitude()},Y=(Q,K)=>{if(Q instanceof A5&&K instanceof j8&&Q.hasListeners("BLOCK_TYPE.ENTITY_CONTACT_FORCE"))Q.emit("BLOCK_TYPE.ENTITY_CONTACT_FORCE",{blockType:Q,entity:K,contactForceData:$});else if(Q instanceof j8&&K instanceof A5&&Q.hasListeners("ENTITY.BLOCK_CONTACT_FORCE"))Q.emit("ENTITY.BLOCK_CONTACT_FORCE",{entity:Q,blockType:K,contactForceData:$});else if(Q instanceof j8&&K instanceof j8&&Q.hasListeners("ENTITY.ENTITY_CONTACT_FORCE"))Q.emit("ENTITY.ENTITY_CONTACT_FORCE",{entity:Q,otherEntity:K,contactForceData:$})};Y(J,X),Y(X,J)};_getCollisionObjects(Z,J){let X=this._colliderMap.getColliderHandleBlockType(Z)??this._colliderMap.getColliderHandleCollisionCallback(Z)??this._colliderMap.getColliderHandleEntity(Z),$=this._colliderMap.getColliderHandleBlockType(J)??this._colliderMap.getColliderHandleCollisionCallback(J)??this._colliderMap.getColliderHandleEntity(J);return[X,$]}}class uj{_synchronizedPlayerReliablePackets=new r8;_queuedBroadcasts=[];_queuedAudioSynchronizations=new r8;_queuedBlockSynchronizations=new r8;_queuedBlockTypeSynchronizations=new r8;_queuedChunkSynchronizations=new r8;_queuedDebugRaycastSynchronizations=[];_queuedEntitySynchronizations=new r8;_queuedLightSynchronizations=new r8;_queuedParticleEmitterSynchronizations=new r8;_queuedPerPlayerSynchronizations=new r8;_queuedPerPlayerCameraSynchronizations=new r8;_queuedPerPlayerUISynchronizations=new r8;_queuedPerPlayerUIDatasSynchronizations=new r8;_queuedPlayerSynchronizations=new r8;_queuedSceneUISynchronizations=new r8;_queuedWorldSynchronization;_loadedSceneUIs=new Set;_spawnedChunks=new Set;_spawnedEntities=new Set;_world;constructor(Z){this._world=Z,this._subscribeToAudioEvents(),this._subscribeToBlockTypeRegistryEvents(),this._subscribeToChatEvents(),this._subscribeToChunkLatticeEvents(),this._subscribeToEntityEvents(),this._subscribeToLightEvents(),this._subscribeToParticleEmitterEvents(),this._subscribeToPlayerEvents(),this._subscribeToPlayerCameraEvents(),this._subscribeToPlayerUIEvents(),this._subscribeToSceneUIEvents(),this._subscribeToSimulationEvents(),this._subscribeToWorldEvents()}synchronize(){let Z=[],J=[],X=this._world.loop.currentTick;if(this._queuedPerPlayerSynchronizations.size>0)for(let[$,Y]of this._queuedPerPlayerSynchronizations)this._createOrGetSynchronizedPlayerReliablePackets($,Z).push(...Y);if(this._queuedEntitySynchronizations.size>0){let $=[],Y=[];for(let Q of this._queuedEntitySynchronizations.valuesArray){let K=!1;for(let W in Q)if(W!=="i"&&W!=="p"&&W!=="r"){K=!0;break}if(K)$.push(Q);else Y.push(Q)}if(Y.length>0){let Q=Y0.createPacket(Y0.outboundPackets.entitiesPacketDefinition,Y,X);J.push(Q)}if($.length>0){let Q=Y0.createPacket(Y0.outboundPackets.entitiesPacketDefinition,$,X);Z.push(Q);for(let K of this._synchronizedPlayerReliablePackets.valuesArray)K.push(Q)}}if(this._queuedAudioSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.audiosPacketDefinition,this._queuedAudioSynchronizations.valuesArray,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedBlockTypeSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.blockTypesPacketDefinition,this._queuedBlockTypeSynchronizations.valuesArray,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedChunkSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.chunksPacketDefinition,this._queuedChunkSynchronizations.valuesArray,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedBlockSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.blocksPacketDefinition,this._queuedBlockSynchronizations.valuesArray,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedLightSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.lightsPacketDefinition,this._queuedLightSynchronizations.valuesArray,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedParticleEmitterSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.particleEmittersPacketDefinition,this._queuedParticleEmitterSynchronizations.valuesArray,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedPerPlayerUISynchronizations.size>0)for(let[$,Y]of this._queuedPerPlayerUISynchronizations){let Q=Y0.createPacket(Y0.outboundPackets.uiPacketDefinition,Y,X);this._createOrGetSynchronizedPlayerReliablePackets($,Z).push(Q)}if(this._queuedPerPlayerUIDatasSynchronizations.size>0)for(let[$,Y]of this._queuedPerPlayerUIDatasSynchronizations){let Q=Y0.createPacket(Y0.outboundPackets.uiDatasPacketDefinition,Y,X);this._createOrGetSynchronizedPlayerReliablePackets($,Z).push(Q)}if(this._queuedSceneUISynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.sceneUIsPacketDefinition,this._queuedSceneUISynchronizations.valuesArray,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedWorldSynchronization){let $=Y0.createPacket(Y0.outboundPackets.worldPacketDefinition,this._queuedWorldSynchronization,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedPerPlayerCameraSynchronizations.size>0)for(let[$,Y]of this._queuedPerPlayerCameraSynchronizations){let Q=Y0.createPacket(Y0.outboundPackets.cameraPacketDefinition,Y,X);this._createOrGetSynchronizedPlayerReliablePackets($,Z).push(Q)}if(this._queuedPlayerSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.playersPacketDefinition,this._queuedPlayerSynchronizations.valuesArray,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedBroadcasts.length>0)for(let $ of this._queuedBroadcasts){Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}if(this._queuedDebugRaycastSynchronizations.length>0){let $=Y0.createPacket(Y0.outboundPackets.physicsDebugRaycastsPacketDefinition,this._queuedDebugRaycastSynchronizations,X);Z.push($);for(let Y of this._synchronizedPlayerReliablePackets.valuesArray)Y.push($)}V8.startSpan({operation:"send_all_packets"},()=>{for(let $ of n5.instance.getConnectedPlayersByWorld(this._world)){let Y=this._synchronizedPlayerReliablePackets.get($)??Z;if(Y.length>0)$.connection.send(Y);if(J.length>0)$.connection.send(J,!1)}}),V8.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();C9.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_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=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.pa=!0,delete J.pl,delete J.r};_onAudioPlay=(Z)=>{let J=Z.audio.serialize();J.pl=!0,delete J.pa,delete J.r,this._queuedAudioSynchronizations.set(J.i,J)};_onAudioPlayRestart=(Z)=>{let J=Z.audio.serialize();J.r=!0,delete J.pa,delete J.pl,this._queuedAudioSynchronizations.set(J.i,J)};_onAudioSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onAudioSetCutoffDistance=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.cd=Z.cutoffDistance};_onAudioSetDetune=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.de=Z.detune};_onAudioSetDistortion=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.di=Z.distortion};_onAudioSetPosition=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.e=Z.position?void 0:J.e,J.p=Z.position?T0.serializeVector(Z.position):void 0};_onAudioSetPlaybackRate=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.pr=Z.playbackRate};_onAudioSetReferenceDistance=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.rd=Z.referenceDistance};_onAudioSetVolume=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.v=Z.volume};_onBlockTypeRegistryRegisterBlockType=(Z)=>{let J=Z.blockType.serialize();this._queuedBlockTypeSynchronizations.set(Z.blockType.id,J)};_onChatSendBroadcastMessage=(Z)=>{let{player:J,message:X,color:$}=Z;this._queuedBroadcasts.push(Y0.createPacket(Y0.outboundPackets.chatMessagesPacketDefinition,[{m:X,c:$,p:J?.id}],this._world.loop.currentTick))};_onChatSendPlayerMessage=(Z)=>{let{player:J,message:X,color:$}=Z,Y=this._queuedPerPlayerSynchronizations.get(J)??[];Y.push(Y0.createPacket(Y0.outboundPackets.chatMessagesPacketDefinition,[{m:X,c:$}],this._world.loop.currentTick)),this._queuedPerPlayerSynchronizations.set(J,Y)};_onChunkLatticeAddChunk=(Z)=>{let J=this._createOrGetQueuedChunkSync(Z.chunk);J.b=Array.from(Z.chunk.blocks),J.rm=void 0,this._spawnedChunks.add(J.c.join(","))};_onChunkLatticeRemoveChunk=(Z)=>{let J=this._createOrGetQueuedChunkSync(Z.chunk),X=J.c.join(",");if(this._spawnedChunks.has(X))this._queuedChunkSynchronizations.delete(X),this._spawnedChunks.delete(X);else J.rm=!0};_onChunkLatticeSetBlock=(Z)=>{let J=this._createOrGetQueuedBlockSync(Z.globalCoordinate);J.i=Z.blockTypeId};_onEntitySetModelAnimationsPlaybackRate=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.ap=Z.playbackRate};_onEntitySpawn=(Z)=>{let J=Z.entity.serialize();this._queuedEntitySynchronizations.set(J.i,J),this._spawnedEntities.add(J.i)};_onEntityDespawn=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(this._spawnedEntities.has(J.i))this._queuedEntitySynchronizations.delete(J.i),this._spawnedEntities.delete(J.i);else J.rm=!0};_onEntitySetModelHiddenNodes=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.h=Array.from(Z.modelHiddenNodes)};_onEntitySetModelScale=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.s=Z.modelScale};_onEntitySetModelShownNodes=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.sn=Array.from(Z.modelShownNodes)};_onEntitySetModelTextureUri=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.mt=Z.modelTextureUri};_onEntitySetOpacity=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.o=Z.opacity};_onEntitySetParent=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.pe=Z.parent?Z.parent.id:void 0,J.pn=Z.parentNodeName};_onEntitySetTintColor=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.t=Z.tintColor?T0.serializeRgbColor(Z.tintColor):void 0};_onEntityStartModelLoopedAnimations=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(J.al=Array.from(new Set([...J.al??[],...Z.animations])),J.as)J.as=J.as.filter((X)=>!Z.animations.has(X)).filter(Boolean)};_onEntityStartModelOneshotAnimations=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(J.ao=Array.from(new Set([...J.ao??[],...Z.animations])),J.as)J.as=J.as.filter((X)=>!Z.animations.has(X)).filter(Boolean)};_onEntityStopModelAnimations=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(J.al)J.al=J.al.filter((X)=>!Z.animations.has(X)).filter(Boolean);if(J.ao)J.ao=J.ao.filter((X)=>!Z.animations.has(X)).filter(Boolean);J.as=Array.from(new Set([...J.as??[],...Z.animations]))};_onEntityUpdateRotation=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.r=[Z.rotation.x,Z.rotation.y,Z.rotation.z,Z.rotation.w]};_onEntityUpdatePosition=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.p=[Z.position.x,Z.position.y,Z.position.z]};_onLightDespawn=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.rm=!0};_onLightSetAngle=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.a=Z.angle};_onLightSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onLightSetColor=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.c=T0.serializeRgbColor(Z.color)};_onLightSetDistance=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.d=Z.distance};_onLightSetIntensity=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.n=Z.intensity};_onLightSetOffset=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.o=Z.offset?T0.serializeVector(Z.offset):void 0};_onLightSetPenumbra=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.pe=Z.penumbra};_onLightSetPosition=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.p=Z.position?T0.serializeVector(Z.position):void 0,J.e=Z.position?void 0:J.e};_onLightSetTrackedEntity=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.te=Z.entity?Z.entity.id:void 0,J.tp=Z.entity?void 0:J.tp};_onLightSetTrackedPosition=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.tp=Z.position?T0.serializeVector(Z.position):void 0,J.te=Z.position?void 0:J.te};_onLightSpawn=(Z)=>{let J=Z.light.serialize();this._queuedLightSynchronizations.set(J.i,J)};_onParticleEmitterBurst=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.b=Z.count};_onParticleEmitterDespawn=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.rm=!0};_onParticleEmitterSetAlphaTest=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.at=Z.alphaTest};_onParticleEmitterSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onParticleEmitterSetAttachedToEntityNodeName=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.en=Z.attachedToEntityNodeName};_onParticleEmitterSetColorEnd=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.ce=Z.colorEnd?T0.serializeRgbColor(Z.colorEnd):void 0};_onParticleEmitterSetColorEndVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.cev=Z.colorEndVariance?T0.serializeRgbColor(Z.colorEndVariance):void 0};_onParticleEmitterSetColorStart=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.cs=Z.colorStart?T0.serializeRgbColor(Z.colorStart):void 0};_onParticleEmitterSetColorStartVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.csv=Z.colorStartVariance?T0.serializeRgbColor(Z.colorStartVariance):void 0};_onParticleEmitterSetGravity=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.g=Z.gravity?T0.serializeVector(Z.gravity):void 0};_onParticleEmitterSetLifetime=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.l=Z.lifetime};_onParticleEmitterSetLifetimeVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.lv=Z.lifetimeVariance};_onParticleEmitterSetMaxParticles=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.mp=Z.maxParticles};_onParticleEmitterSetOffset=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.o=Z.offset?T0.serializeVector(Z.offset):void 0};_onParticleEmitterSetOpacityEnd=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.oe=Z.opacityEnd};_onParticleEmitterSetOpacityEndVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.oev=Z.opacityEndVariance};_onParticleEmitterSetOpacityStart=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.os=Z.opacityStart};_onParticleEmitterSetOpacityStartVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.osv=Z.opacityStartVariance};_onParticleEmitterSetPaused=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.pa=Z.paused};_onParticleEmitterSetPosition=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.p=Z.position?T0.serializeVector(Z.position):void 0,J.e=Z.position?void 0:J.e,J.en=Z.position?void 0:J.en};_onParticleEmitterSetPositionVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.pv=Z.positionVariance?T0.serializeVector(Z.positionVariance):void 0};_onParticleEmitterSetRate=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.r=Z.rate};_onParticleEmitterSetRateVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.rv=Z.rateVariance};_onParticleEmitterSetSizeEnd=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.se=Z.sizeEnd};_onParticleEmitterSetSizeEndVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.sev=Z.sizeEndVariance};_onParticleEmitterSetSizeStart=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.ss=Z.sizeStart};_onParticleEmitterSetSizeStartVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.ssv=Z.sizeStartVariance};_onParticleEmitterSetTextureUri=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.tu=Z.textureUri};_onParticleEmitterSetTransparent=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.t=Z.transparent};_onParticleEmitterSetVelocity=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.v=Z.velocity?T0.serializeVector(Z.velocity):void 0};_onParticleEmitterSetVelocityVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.vv=Z.velocityVariance?T0.serializeVector(Z.velocityVariance):void 0};_onParticleEmitterSpawn=(Z)=>{let J=Z.particleEmitter.serialize();this._queuedParticleEmitterSynchronizations.set(J.i,J)};_onPlayerCameraLookAtEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pl=T0.serializeVector(Z.entity.position),delete J.et,delete J.pt};_onPlayerCameraLookAtPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pl=Z.position?T0.serializeVector(Z.position):void 0,delete J.et,delete J.pt};_onPlayerCameraSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.e=Z.entity.id,delete J.p};_onPlayerCameraSetAttachedToPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.p=Z.position?T0.serializeVector(Z.position):void 0,delete J.e};_onPlayerCameraSetFilmOffset=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.fo=Z.filmOffset};_onPlayerCameraSetForwardOffset=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.ffo=Z.forwardOffset};_onPlayerCameraSetFov=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.fv=Z.fov};_onPlayerCameraSetModelHiddenNodes=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.h=Array.from(Z.modelHiddenNodes)};_onPlayerCameraSetModelShownNodes=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.s=Array.from(Z.modelShownNodes)};_onPlayerCameraSetMode=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.m=Z.mode};_onPlayerCameraSetOffset=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.o=Z.offset?T0.serializeVector(Z.offset):void 0};_onPlayerCameraSetShoulderAngle=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.sa=Z.shoulderAngle};_onPlayerCameraSetTrackedEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.et=Z.entity?Z.entity.id:void 0,delete J.pl,delete J.pt};_onPlayerCameraSetTrackedPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pt=Z.position?T0.serializeVector(Z.position):void 0,delete J.et,delete J.pl};_onPlayerCameraSetZoom=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.z=Z.zoom};_onPlayerJoinedWorld=(Z)=>{let{player:J}=Z,X=this._queuedPerPlayerSynchronizations.get(J)??[];X.push(Y0.createPacket(Y0.outboundPackets.worldPacketDefinition,this._world.serialize(),this._world.loop.currentTick)),X.push(Y0.createPacket(Y0.outboundPackets.blockTypesPacketDefinition,this._world.blockTypeRegistry.serialize(),this._world.loop.currentTick)),X.push(Y0.createPacket(Y0.outboundPackets.chunksPacketDefinition,this._world.chunkLattice.getAllChunks().map((Y)=>Y.serialize()),this._world.loop.currentTick)),X.push(Y0.createPacket(Y0.outboundPackets.entitiesPacketDefinition,this._world.entityManager.getAllEntities().map((Y)=>{if(J.camera.attachedToEntity===void 0&&Y instanceof F7&&Y.player===J)J.camera.setAttachedToEntity(Y);return Y.serialize()}),this._world.loop.currentTick)),X.push(Y0.createPacket(Y0.outboundPackets.audiosPacketDefinition,this._world.audioManager.getAllAudios().map((Y)=>Y.serialize()),this._world.loop.currentTick)),X.push(Y0.createPacket(Y0.outboundPackets.lightsPacketDefinition,this._world.lightManager.getAllLights().map((Y)=>Y.serialize()),this._world.loop.currentTick)),X.push(Y0.createPacket(Y0.outboundPackets.particleEmittersPacketDefinition,this._world.particleEmitterManager.getAllParticleEmitters().map((Y)=>Y.serialize()),this._world.loop.currentTick)),X.push(Y0.createPacket(Y0.outboundPackets.sceneUIsPacketDefinition,this._world.sceneUIManager.getAllSceneUIs().map((Y)=>Y.serialize()),this._world.loop.currentTick)),X.push(Y0.createPacket(Y0.outboundPackets.playersPacketDefinition,n5.instance.getConnectedPlayers().map((Y)=>Y.serialize()),this._world.loop.currentTick));let $=this._createOrGetQueuedPlayerCameraSync(J.camera);this._queuedPerPlayerCameraSynchronizations.set(J,{...J.camera.serialize(),...$}),this._queuedPerPlayerSynchronizations.set(J,X),this._queuedPlayerSynchronizations.set(J.id,J.serialize())};_onPlayerLeftWorld=(Z)=>{let J=this._createOrGetQueuedPlayerSync(Z.player);J.rm=!0};_onPlayerReconnectedWorld=(Z)=>{this._onPlayerJoinedWorld(Z)};_onPlayerRequestSync=(Z)=>{Z.player.connection.send([Y0.createPacket(Y0.outboundPackets.syncResponsePacketDefinition,{r:Z.receivedAt,s:Date.now(),p:performance.now()-Z.receivedAtMs,n:this._world.loop.nextTickMs},this._world.loop.currentTick)])};_onPlayerUILoad=(Z)=>{let J=this._createOrGetQueuedPlayerUISync(Z.playerUI);J.u=Z.htmlUri};_onPlayerUILockPointer=(Z)=>{let J=this._createOrGetQueuedPlayerUISync(Z.playerUI);J.p=Z.lock};_onPlayerUISendData=(Z)=>{this._createOrGetQueuedPlayerUIDatasSync(Z.playerUI).push(Z.data)};_onSceneUILoad=(Z)=>{let J=Z.sceneUI.serialize();this._queuedSceneUISynchronizations.set(J.i,J),this._loadedSceneUIs.add(J.i)};_onSceneUISetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onSceneUISetOffset=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.o=Z.offset?T0.serializeVector(Z.offset):void 0};_onSceneUISetPosition=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.p=Z.position?T0.serializeVector(Z.position):void 0,J.e=Z.position?void 0:J.e};_onSceneUISetState=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.s=Z.state};_onSceneUISetViewDistance=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.v=Z.viewDistance};_onSceneUIUnload=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);if(this._loadedSceneUIs.has(J.i))this._queuedSceneUISynchronizations.delete(J.i),this._loadedSceneUIs.delete(J.i);else J.rm=!0};_onSimulationDebugRaycast=(Z)=>{this._queuedDebugRaycastSynchronizations.push(T0.serializePhysicsDebugRaycast(Z))};_onSimulationDebugRender=(Z)=>{this._queuedBroadcasts.push(Y0.createPacket(Y0.outboundPackets.physicsDebugRenderPacketDefinition,{v:Array.from(Z.vertices),c:Array.from(Z.colors)},this._world.loop.currentTick))};_onWorldSetAmbientLightColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.ac=T0.serializeRgbColor(Z.color)};_onWorldSetAmbientLightIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.ai=Z.intensity};_onWorldSetDirectionalLightColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.dc=T0.serializeRgbColor(Z.color)};_onWorldSetDirectionalLightIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.di=Z.intensity};_onWorldSetDirectionalLightPosition=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.dp=T0.serializeVector(Z.position)};_onWorldSetFogColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.fc=T0.serializeRgbColor(Z.color)};_onWorldSetFogFar=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.ff=Z.far};_onWorldSetFogNear=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.fn=Z.near};_onWorldSetSkyboxIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.si=Z.intensity};_onWorldSetSkyboxUri=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.s=Z.uri};_createOrGetQueuedAudioSync(Z){if(Z.id===void 0)p.fatalError("NetworkSynchronizer._createOrGetQueuedAudioSync(): Audio has no id!");let J=this._queuedAudioSynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedAudioSynchronizations.set(Z.id,J);return J}_createOrGetQueuedBlockSync(Z){let{x:J,y:X,z:$}=Z,Y=`${J},${X},${$}`,Q=this._queuedBlockSynchronizations.get(Y);if(!Q)Q={i:0,c:[J,X,$]},this._queuedBlockSynchronizations.set(Y,Q);return Q}_createOrGetQueuedChunkSync(Z){if(!Z.originCoordinate)p.fatalError("NetworkSynchronizer._createOrGetQueuedChunkSync(): Chunk has no origin coordinate!");let{x:J,y:X,z:$}=Z.originCoordinate,Y=`${J},${X},${$}`,Q=this._queuedChunkSynchronizations.get(Y);if(!Q)Q={c:[J,X,$]},this._queuedChunkSynchronizations.set(Y,Q);return Q}_createOrGetQueuedEntitySync(Z){if(Z.id===void 0)p.fatalError("NetworkSynchronizer._createOrGetQueuedEntitySync(): Entity has no id!");let J=this._queuedEntitySynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedEntitySynchronizations.set(Z.id,J);return J}_createOrGetQueuedLightSync(Z){if(Z.id===void 0)p.fatalError("NetworkSynchronizer._createOrGetQueuedLightSync(): Light has no id!");let J=this._queuedLightSynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedLightSynchronizations.set(Z.id,J);return J}_createOrGetQueuedParticleEmitterSync(Z){if(Z.id===void 0)p.fatalError("NetworkSynchronizer._createOrGetQueuedParticleEmitterSync(): ParticleEmitter has no id!");let J=this._queuedParticleEmitterSynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedParticleEmitterSynchronizations.set(Z.id,J);return J}_createOrGetQueuedPlayerSync(Z){if(Z.id===void 0)p.fatalError("NetworkSynchronizer._createOrGetQueuedPlayerSync(): Player has no id!");let J=this._queuedPlayerSynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedPlayerSynchronizations.set(Z.id,J);return J}_createOrGetQueuedPlayerCameraSync(Z){let J=this._queuedPerPlayerCameraSynchronizations.get(Z.player);if(!J)J={},this._queuedPerPlayerCameraSynchronizations.set(Z.player,J);return J}_createOrGetQueuedPlayerUISync(Z){let J=this._queuedPerPlayerUISynchronizations.get(Z.player);if(!J)J={},this._queuedPerPlayerUISynchronizations.set(Z.player,J);return J}_createOrGetQueuedPlayerUIDatasSync(Z){let J=this._queuedPerPlayerUIDatasSynchronizations.get(Z.player);if(!J)J=[],this._queuedPerPlayerUIDatasSynchronizations.set(Z.player,J);return J}_createOrGetQueuedSceneUISync(Z){if(Z.id===void 0)p.fatalError("NetworkSynchronizer._createOrGetQueuedSceneUISync(): SceneUI has no id!");let J=this._queuedSceneUISynchronizations.get(Z.id);if(!J)J={i:Z.id},this._queuedSceneUISynchronizations.set(Z.id,J);return J}_createOrGetQueuedWorldSync(Z){if(Z.id!==this._world.id)p.fatalError("NetworkSynchronizer._createOrGetQueuedWorldSync(): World does not match this network synchronizer world!");return this._queuedWorldSynchronization??={i:Z.id}}_createOrGetSynchronizedPlayerReliablePackets(Z,J){let X=this._synchronizedPlayerReliablePackets.get(Z);if(!X)X=[...J],this._synchronizedPlayerReliablePackets.set(Z,X);return X}}class DH{_particleEmitters=new Map;_nextParticleEmitterId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}despawnEntityAttachedParticleEmitters(Z){this.getAllEntityAttachedParticleEmitters(Z).forEach((J)=>{J.despawn()})}getAllParticleEmitters(){return Array.from(this._particleEmitters.values())}getAllEntityAttachedParticleEmitters(Z){return this.getAllParticleEmitters().filter((J)=>J.attachedToEntity===Z)}registerParticleEmitter(Z){if(Z.id!==void 0)return Z.id;let J=this._nextParticleEmitterId;return this._particleEmitters.set(J,Z),this._nextParticleEmitterId++,J}unregisterParticleEmitter(Z){if(Z.id===void 0)return;this._particleEmitters.delete(Z.id)}}class MH{_sceneUIs=new Map;_nextSceneUIId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}getAllSceneUIs(){return Array.from(this._sceneUIs.values())}getAllEntityAttachedSceneUIs(Z){return this.getAllSceneUIs().filter((J)=>J.attachedToEntity===Z)}getSceneUIById(Z){return this._sceneUIs.get(Z)}registerSceneUI(Z){if(Z.id!==void 0)return Z.id;let J=this._nextSceneUIId;return this._sceneUIs.set(J,Z),this._nextSceneUIId++,J}unloadEntityAttachedSceneUIs(Z){this.getAllEntityAttachedSceneUIs(Z).forEach((J)=>{J.unload()})}unregisterSceneUI(Z){if(Z.id===void 0)return;this._sceneUIs.delete(Z.id)}}var nJ6=2,sJ6=3;class RH{_accumulatorMs=0;_targetTicksPerSecond;_fixedTimestepMs;_fixedTimestepS;_maxAccumulatorMs;_nextTickMs=0;_lastLoopTimeMs=0;_tickFunction;_tickErrorCallback;_tickHandle=null;constructor(Z,J,X){this._targetTicksPerSecond=Z,this._fixedTimestepS=Math.fround(1/Z),this._fixedTimestepMs=Math.fround(this._fixedTimestepS*1000),this._maxAccumulatorMs=this._fixedTimestepMs*sJ6,this._tickFunction=J,this._tickErrorCallback=X}get targetTicksPerSecond(){return this._targetTicksPerSecond}get fixedTimestepMs(){return this._fixedTimestepMs}get fixedTimestepS(){return this._fixedTimestepS}get isStarted(){return!!this._tickHandle}get nextTickMs(){return this._nextTickMs}start(){if(this._tickHandle)return;this._lastLoopTimeMs=performance.now();let Z=()=>{let J=performance.now(),X=J-this._lastLoopTimeMs;if(this._lastLoopTimeMs=J,this._accumulatorMs+=X,this._accumulatorMs>this._maxAccumulatorMs)this._accumulatorMs=this._maxAccumulatorMs;if(this._accumulatorMs>=this._fixedTimestepMs)V8.startSpan({operation:"ticker_tick"},()=>{let $=0;while(this._accumulatorMs>=this._fixedTimestepMs&&$<nJ6)this._tick(this._fixedTimestepMs),this._accumulatorMs-=this._fixedTimestepMs,$++});this._nextTickMs=Math.max(0,this._fixedTimestepMs-this._accumulatorMs),this._tickHandle=setTimeout(Z,this._nextTickMs)};Z()}stop(){if(!this._tickHandle)return;clearTimeout(this._tickHandle),this._tickHandle=null}_tick(Z){try{this._tickFunction(Z)}catch(J){if(J instanceof Error&&this._tickErrorCallback)this._tickErrorCallback(J);else p.warning(`Ticker._tick(): tick callback threw an error, but it was not an instance of Error. Error: ${J}`)}}}var n31;((Q)=>{Q.START="WORLD_LOOP.START";Q.STOP="WORLD_LOOP.STOP";Q.TICK_START="WORLD_LOOP.TICK_START";Q.TICK_END="WORLD_LOOP.TICK_END";Q.TICK_ERROR="WORLD_LOOP.TICK_ERROR"})(n31||={});class NH extends B0{_currentTick=0;_ticker;_world;constructor(Z,J=JA){super();this._ticker=new RH(J,this._tick,this._onTickError),this._world=Z}get currentTick(){return this._currentTick}get isStarted(){return this._ticker.isStarted}get nextTickMs(){return this._ticker.nextTickMs}get timestepS(){return this._ticker.fixedTimestepS}get world(){return this._world}start(){this._ticker.start(),this.emitWithWorld(this._world,"WORLD_LOOP.START",{worldLoop:this})}stop(){this._ticker.stop(),this.emitWithWorld(this._world,"WORLD_LOOP.STOP",{worldLoop:this})}_tick=(Z)=>{this.emitWithWorld(this._world,"WORLD_LOOP.TICK_START",{worldLoop:this,tickDeltaMs:Z});let J=performance.now();V8.startSpan({operation:"world_tick",attributes:{serverPlayerCount:n5.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}},()=>{V8.startSpan({operation:"entities_tick"},()=>this._world.entityManager.tickEntities(Z)),V8.startSpan({operation:"simulation_step"},()=>this._world.simulation.step(Z)),V8.startSpan({operation:"entities_emit_updates"},()=>this._world.entityManager.checkAndEmitUpdates()),V8.startSpan({operation:"network_synchronize"},()=>this._world.networkSynchronizer.synchronize())}),this._currentTick++,this.emitWithWorld(this._world,"WORLD_LOOP.TICK_END",{worldLoop:this,tickDurationMs:performance.now()-J})};_onTickError=(Z)=>{p.error(`WorldLoop._onTickError(): Error: ${Z}`),this.emitWithWorld(this._world,"WORLD_LOOP.TICK_ERROR",{worldLoop:this,error:Z})}}var $A;((V)=>{V.SET_AMBIENT_LIGHT_COLOR="WORLD.SET_AMBIENT_LIGHT_COLOR";V.SET_AMBIENT_LIGHT_INTENSITY="WORLD.SET_AMBIENT_LIGHT_INTENSITY";V.SET_DIRECTIONAL_LIGHT_COLOR="WORLD.SET_DIRECTIONAL_LIGHT_COLOR";V.SET_DIRECTIONAL_LIGHT_INTENSITY="WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY";V.SET_DIRECTIONAL_LIGHT_POSITION="WORLD.SET_DIRECTIONAL_LIGHT_POSITION";V.SET_FOG_COLOR="WORLD.SET_FOG_COLOR";V.SET_FOG_FAR="WORLD.SET_FOG_FAR";V.SET_FOG_NEAR="WORLD.SET_FOG_NEAR";V.SET_SKYBOX_INTENSITY="WORLD.SET_SKYBOX_INTENSITY";V.SET_SKYBOX_URI="WORLD.SET_SKYBOX_URI";V.START="WORLD.START";V.STOP="WORLD.STOP"})($A||={});class OH extends B0{_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(Z){super();if(this._id=Z.id,this._ambientLightColor=Z.ambientLightColor??{r:255,g:255,b:255},this._ambientLightIntensity=Z.ambientLightIntensity??1,this._directionalLightColor=Z.directionalLightColor??{r:255,g:255,b:255},this._directionalLightIntensity=Z.directionalLightIntensity??3,this._directionalLightPosition=Z.directionalLightPosition??{x:100,y:150,z:100},this._fogColor=Z.fogColor,this._fogFar=Z.fogFar??550,this._fogNear=Z.fogNear??500,this._name=Z.name,this._skyboxIntensity=Z.skyboxIntensity??1,this._skyboxUri=Z.skyboxUri,this._tag=Z.tag,this._audioManager=new NW(this),this._blockTypeRegistry=new rG(this),this._chatManager=new bz(this),this._chunkLattice=new hz(this),this._entityManager=new uz(this),this._lightManager=new jH(this),this._loop=new NH(this,Z.tickRate),this._networkSynchronizer=new uj(this),this._particleEmitterManager=new DH(this),this._sceneUIManager=new MH(this),this._simulation=new LH(this,Z.tickRate,Z.gravity),Z.map)this.loadMap(Z.map)}get id(){return this._id}get ambientLightColor(){return this._ambientLightColor}get ambientLightIntensity(){return this._ambientLightIntensity}get 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(Z){if(this.chunkLattice.clear(),Z.blockTypes)for(let J of Z.blockTypes)this.blockTypeRegistry.registerGenericBlockType({id:J.id,isLiquid:J.isLiquid,lightLevel:J.lightLevel,name:J.name,textureUri:J.textureUri});if(Z.blocks)for(let[J,X]of Object.entries(Z.blocks)){let[$,Y,Q]=J.split(",").map(Number);this.chunkLattice.setBlock({x:$,y:Y,z:Q},X)}if(Z.entities)for(let[J,X]of Object.entries(Z.entities)){let[$,Y,Q]=J.split(",").map(Number);new j8({isEnvironmental:!0,...X}).spawn(this,{x:$,y:Y,z:Q})}}setAmbientLightColor(Z){this._ambientLightColor=Z,this.emit("WORLD.SET_AMBIENT_LIGHT_COLOR",{world:this,color:Z})}setAmbientLightIntensity(Z){this._ambientLightIntensity=Z,this.emit("WORLD.SET_AMBIENT_LIGHT_INTENSITY",{world:this,intensity:Z})}setDirectionalLightColor(Z){this._directionalLightColor=Z,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_COLOR",{world:this,color:Z})}setDirectionalLightIntensity(Z){this._directionalLightIntensity=Z,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY",{world:this,intensity:Z})}setDirectionalLightPosition(Z){this._directionalLightPosition=Z,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_POSITION",{world:this,position:Z})}setFogColor(Z){this._fogColor=Z,this.emit("WORLD.SET_FOG_COLOR",{world:this,color:Z})}setFogFar(Z){this._fogFar=Z,this.emit("WORLD.SET_FOG_FAR",{world:this,far:Z})}setFogNear(Z){this._fogNear=Z,this.emit("WORLD.SET_FOG_NEAR",{world:this,near:Z})}setSkyboxIntensity(Z){this._skyboxIntensity=Z,this.emit("WORLD.SET_SKYBOX_INTENSITY",{world:this,intensity:Z})}setSkyboxUri(Z){this._skyboxUri=Z,this.emit("WORLD.SET_SKYBOX_URI",{world:this,uri:Z})}start(){if(this._loop.isStarted)return;this._loop.start(),this.emit("WORLD.START",{world:this,startedAtMs:Date.now()})}stop(){if(!this._loop.isStarted)return;this._loop.stop(),this.emit("WORLD.STOP",{world:this,stoppedAtMs:Date.now()})}serialize(){return T0.serializeWorld(this)}}var s31;((J)=>J.WORLD_CREATED="WORLD_MANAGER.WORLD_CREATED")(s31||={});class q${static instance=new q$;_defaultWorld;_nextWorldId=1;_worlds=new Map;createWorld(Z){let J=new OH({...Z,id:this._nextWorldId++});return J.start(),this._worlds.set(J.id,J),B0.globalInstance.emit("WORLD_MANAGER.WORLD_CREATED",{world:J}),J}getAllWorlds(){return Array.from(this._worlds.values())}getDefaultWorld(){return this._defaultWorld??=this.createWorld({name:"Default World",skyboxUri:"skyboxes/partly-cloudy"}),this._defaultWorld}getWorldsByTag(Z){let J=[];return this._worlds.forEach((X)=>{if(X.tag===Z)J.push(X)}),J}getWorld(Z){return this._worlds.get(Z)}setDefaultWorld(Z){this._defaultWorld=Z}}var o31;(($)=>{$.PLAYER_CONNECTED="PLAYER_MANAGER.PLAYER_CONNECTED";$.PLAYER_DISCONNECTED="PLAYER_MANAGER.PLAYER_DISCONNECTED";$.PLAYER_RECONNECTED="PLAYER_MANAGER.PLAYER_RECONNECTED"})(o31||={});class n5{static instance=new n5;worldSelectionHandler;_connectionPlayers=new Map;constructor(){B0.globalInstance.on("CONNECTION.OPENED",({connection:Z,req:J})=>{this._onConnectionOpened(Z,J.session)}),B0.globalInstance.on("CONNECTION.DISCONNECTED",({connection:Z})=>{this._onConnectionDisconnected(Z)}),B0.globalInstance.on("CONNECTION.RECONNECTED",({connection:Z})=>{this._onConnectionReconnected(Z)}),B0.globalInstance.on("CONNECTION.CLOSED",({connection:Z})=>{this._onConnectionClosed(Z)})}get playerCount(){return this._connectionPlayers.size}getConnectedPlayers(){return Array.from(this._connectionPlayers.values())}getConnectedPlayersByWorld(Z){return this.getConnectedPlayers().filter((J)=>J.world===Z)}getConnectedPlayerByUsername(Z){return Array.from(this._connectionPlayers.values()).find((J)=>{return J.username.toLowerCase()===Z.toLowerCase()})}async _onConnectionOpened(Z,J){let X=new g3(Z,J);await X.loadInitialPersistedData(),B0.globalInstance.emit("PLAYER_MANAGER.PLAYER_CONNECTED",{player:X});let $=await this.worldSelectionHandler?.(X);X.joinWorld($??q$.instance.getDefaultWorld()),this._connectionPlayers.set(Z,X)}_onConnectionDisconnected(Z){let J=this._connectionPlayers.get(Z);if(J)J.resetInputs(),J.camera.reset()}_onConnectionReconnected(Z){let J=this._connectionPlayers.get(Z);if(J)J.reconnected(),B0.globalInstance.emit("PLAYER_MANAGER.PLAYER_RECONNECTED",{player:J});else p.warning(`PlayerManager._onConnectionReconnected(): Connection ${Z.id} not in the PlayerManager._connectionPlayers map.`)}_onConnectionClosed(Z){let J=this._connectionPlayers.get(Z);if(J)J.disconnect(),this._connectionPlayers.delete(Z),B0.globalInstance.emit("PLAYER_MANAGER.PLAYER_DISCONNECTED",{player:J});else p.warning(`PlayerManager._onConnectionClosed(): Connection ${Z.id} not in the PlayerManager._connectionPlayers map.`)}}Buffer.poolSize=134217728;var r31;((X)=>{X.START="GAMESERVER.START";X.STOP="GAMESERVER.STOP"})(r31||={});function oJ6(Z){X1.init().then(()=>{return TQ.instance.modelRegistry.preloadModels()}).then(()=>{if(Z.length>0)Z(TQ.instance.worldManager.getDefaultWorld());else Z();TQ.instance.start()}).catch((J)=>{p.fatalError(`Failed to initialize the game engine, exiting. Error: ${J}`)})}class TQ{static _instance;_modelRegistry=j6.instance;_playerManager=n5.instance;_socket=M7.instance;_worldManager=q$.instance;_webServer=FK.instance;constructor(){}static get instance(){if(!this._instance)this._instance=new TQ;return this._instance}get modelRegistry(){return this._modelRegistry}get playerManager(){return this._playerManager}get socket(){return this._socket}get webServer(){return this._webServer}get worldManager(){return this._worldManager}start(){B0.globalInstance.emit("GAMESERVER.START",{startedAtMs:performance.now()}),this._webServer.start()}}var t8=t(kQ(),1);class EQ extends Float32Array{constructor(Z,J,X,$){super([Z,J,X,$])}get determinant(){return t8.mat2.determinant(this)}get frobeniusNorm(){return t8.mat2.frob(this)}static create(){let Z=new EQ(0,0,0,0);return t8.mat2.identity(Z),Z}static fromRotation(Z){let J=EQ.create();return t8.mat2.fromRotation(J,Z),J}static fromScaling(Z){let J=EQ.create();return t8.mat2.fromScaling(J,Z),J}add(Z){return t8.mat2.add(this,this,Z),this}adjoint(){return t8.mat2.adjoint(this,this),this}clone(){return new EQ(this[0],this[1],this[2],this[3])}copy(Z){return t8.mat2.copy(this,Z),this}equals(Z){return t8.mat2.equals(this,Z)}exactEquals(Z){return t8.mat2.exactEquals(this,Z)}identity(){return t8.mat2.identity(this),this}invert(){return t8.mat2.invert(this,this),this}multiply(Z){return t8.mat2.mul(this,this,Z),this}multiplyScalar(Z){return t8.mat2.multiplyScalar(this,this,Z),this}rotate(Z){return t8.mat2.rotate(this,this,Z),this}subtract(Z){return t8.mat2.sub(this,this,Z),this}toString(){return`[${this[0]},${this[1]}][${this[2]},${this[3]}]`}transpose(){return t8.mat2.transpose(this,this),this}}var H8=t(kQ(),1);class p7 extends Float32Array{constructor(Z,J,X,$,Y,Q,K,W,G){super([Z,J,X,$,Y,Q,K,W,G])}get determinant(){return H8.mat3.determinant(this)}get frobeniusNorm(){return H8.mat3.frob(this)}static create(){let Z=new p7(0,0,0,0,0,0,0,0,0);return H8.mat3.identity(Z),Z}static fromMatrix4(Z){let J=p7.create();return H8.mat3.fromMat4(J,Z),J}static fromQuaternion(Z){let J=p7.create();return H8.mat3.fromQuat(J,Z),J}static fromRotation(Z){let J=p7.create();return H8.mat3.fromRotation(J,Z),J}static fromScaling(Z){let J=p7.create();return H8.mat3.fromScaling(J,Z),J}static fromTranslation(Z){let J=p7.create();return H8.mat3.fromTranslation(J,Z),J}add(Z){return H8.mat3.add(this,this,Z),this}adjoint(){return H8.mat3.adjoint(this,this),this}clone(){return new p7(this[0],this[1],this[2],this[3],this[4],this[5],this[6],this[7],this[8])}copy(Z){return H8.mat3.copy(this,Z),this}equals(Z){return H8.mat3.equals(this,Z)}exactEquals(Z){return H8.mat3.exactEquals(this,Z)}identity(){return H8.mat3.identity(this),this}invert(){return H8.mat3.invert(this,this),this}multiply(Z){return H8.mat3.mul(this,this,Z),this}multiplyScalar(Z){return H8.mat3.multiplyScalar(this,this,Z),this}transformVector(Z){return Z.transformMatrix3(this)}projection(Z,J){return H8.mat3.projection(this,Z,J),this}rotate(Z){return H8.mat3.rotate(this,this,Z),this}subtract(Z){return H8.mat3.sub(this,this,Z),this}toString(){return`[${this[0]},${this[1]},${this[2]}][${this[3]},${this[4]},${this[5]}][${this[6]},${this[7]},${this[8]}]`}transpose(){return H8.mat3.transpose(this,this),this}}var Z1=t(kQ(),1);class W5 extends Float32Array{constructor(Z,J,X,$,Y,Q,K,W,G,z,v,H,V,q,F,x){super([Z,J,X,$,Y,Q,K,W,G,z,v,H,V,q,F,x])}get determinant(){return Z1.mat4.determinant(this)}get frobeniusNorm(){return Z1.mat4.frob(this)}static create(){let Z=new W5(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return Z1.mat4.identity(Z),Z}static fromQuaternion(Z){let J=W5.create();return Z1.mat4.fromQuat(J,Z),J}static fromRotation(Z,J){let X=W5.create();return Z1.mat4.fromRotation(X,Z,J),X}static fromRotationTranslation(Z,J){let X=W5.create();return Z1.mat4.fromRotationTranslation(X,Z,J),X}static fromRotationTranslationScale(Z,J,X){let $=W5.create();return Z1.mat4.fromRotationTranslationScale($,Z,J,X),$}static fromRotationTranslationScaleOrigin(Z,J,X,$){let Y=W5.create();return Z1.mat4.fromRotationTranslationScaleOrigin(Y,Z,J,X,$),Y}static fromScaling(Z){let J=W5.create();return Z1.mat4.fromScaling(J,Z),J}static fromTranslation(Z){let J=W5.create();return Z1.mat4.fromTranslation(J,Z),J}static fromXRotation(Z){let J=W5.create();return Z1.mat4.fromXRotation(J,Z),J}static fromYRotation(Z){let J=W5.create();return Z1.mat4.fromYRotation(J,Z),J}static fromZRotation(Z){let J=W5.create();return Z1.mat4.fromZRotation(J,Z),J}add(Z){return Z1.mat4.add(this,this,Z),this}adjoint(){return Z1.mat4.adjoint(this,this),this}clone(){return new W5(this[0],this[1],this[2],this[3],this[4],this[5],this[6],this[7],this[8],this[9],this[10],this[11],this[12],this[13],this[14],this[15])}copy(Z){return Z1.mat4.copy(this,Z),this}equals(Z){return Z1.mat4.equals(this,Z)}exactEquals(Z){return Z1.mat4.exactEquals(this,Z)}frustrum(Z,J,X,$,Y,Q){return Z1.mat4.frustum(this,Z,J,X,$,Y,Q),this}identity(){return Z1.mat4.identity(this),this}invert(){return Z1.mat4.invert(this,this),this}lookAt(Z,J,X){return Z1.mat4.lookAt(this,Z,J,X),this}multiply(Z){return Z1.mat4.mul(this,this,Z),this}multiplyScalar(Z){return Z1.mat4.multiplyScalar(this,this,Z),this}orthographic(Z,J,X,$,Y,Q){return Z1.mat4.ortho(this,Z,J,X,$,Y,Q),this}perspective(Z,J,X,$){return Z1.mat4.perspective(this,Z,J,X,$),this}rotate(Z,J){return Z1.mat4.rotate(this,this,Z,J),this}rotateX(Z){return Z1.mat4.rotateX(this,this,Z),this}rotateY(Z){return Z1.mat4.rotateY(this,this,Z),this}rotateZ(Z){return Z1.mat4.rotateZ(this,this,Z),this}scale(Z){return Z1.mat4.scale(this,this,Z),this}subtract(Z){return Z1.mat4.sub(this,this,Z),this}targetTo(Z,J,X){return Z1.mat4.targetTo(this,Z,J,X),this}toString(){return`[${this[0]},${this[1]},${this[2]},${this[3]}][${this[4]},${this[5]},${this[6]},${this[7]}][${this[8]},${this[9]},${this[10]},${this[11]}][${this[12]},${this[13]},${this[14]},${this[15]}]`}translate(Z){return Z1.mat4.translate(this,this,Z),this}transpose(){return Z1.mat4.transpose(this,this),this}}var I1=t(kQ(),1);class LW extends Float32Array{constructor(Z,J,X,$){super([Z,J,X,$])}get length(){return I1.quat.length(this)}get squaredLength(){return I1.quat.squaredLength(this)}get magnitude(){return I1.quat.length(this)}get squaredMagnitude(){return I1.quat.squaredLength(this)}get x(){return this[0]}set x(Z){this[0]=Z}get y(){return this[1]}set y(Z){this[1]=Z}get z(){return this[2]}set z(Z){this[2]=Z}get w(){return this[3]}set w(Z){this[3]=Z}static fromEuler(Z,J,X){let $=I1.quat.fromEuler(new Float32Array(4),Z,J,X);return new LW($[0],$[1],$[2],$[3])}static fromQuaternionLike(Z){return new LW(Z.x,Z.y,Z.z,Z.w)}clone(){return new LW(this.x,this.y,this.z,this.w)}conjugate(){return I1.quat.conjugate(this,this),this}copy(Z){return I1.quat.copy(this,Z),this}dot(Z){return I1.quat.dot(this,Z)}exponential(){return I1.quat.exp(this,this),this}equals(Z){return I1.quat.equals(this,Z)}exactEquals(Z){return I1.quat.exactEquals(this,Z)}getAngle(Z){return I1.quat.getAngle(this,Z)}identity(){return I1.quat.identity(this),this}invert(){return I1.quat.invert(this,this),this}lerp(Z,J){return I1.quat.lerp(this,this,Z,J),this}logarithm(){return I1.quat.ln(this,this),this}multiply(Z){return I1.quat.multiply(this,this,Z),this}transformVector(Z){return Z.transformQuaternion(this)}normalize(){return I1.quat.normalize(this,this),this}power(Z){return I1.quat.pow(this,this,Z),this}randomize(){return I1.quat.random(this),this}rotateX(Z){return I1.quat.rotateX(this,this,Z),this}rotateY(Z){return I1.quat.rotateY(this,this,Z),this}rotateZ(Z){return I1.quat.rotateZ(this,this,Z),this}scale(Z){return I1.quat.scale(this,this,Z),this}setAxisAngle(Z,J){return I1.quat.setAxisAngle(this,Z,J),this}slerp(Z,J){return I1.quat.slerp(this,this,Z,J),this}toString(){return`${this.x},${this.y},${this.z},${this.w}`}}var q1=t(kQ(),1);class PH extends Float32Array{constructor(Z,J){super([Z,J])}get length(){return q1.vec2.length(this)}get squaredLength(){return q1.vec2.squaredLength(this)}get magnitude(){return q1.vec2.length(this)}get squaredMagnitude(){return q1.vec2.squaredLength(this)}get x(){return this[0]}set x(Z){this[0]=Z}get y(){return this[1]}set y(Z){this[1]=Z}static create(){return new PH(0,0)}add(Z){return q1.vec2.add(this,this,Z),this}angle(Z){return q1.vec2.angle(this,Z)}ceil(){return q1.vec2.ceil(this,this),this}clone(){return new PH(this.x,this.y)}copy(Z){return q1.vec2.copy(this,Z),this}distance(Z){return q1.vec2.distance(this,Z)}divide(Z){return q1.vec2.divide(this,this,Z),this}dot(Z){return q1.vec2.dot(this,Z)}equals(Z){return q1.vec2.equals(this,Z)}exactEquals(Z){return q1.vec2.exactEquals(this,Z)}floor(){return q1.vec2.floor(this,this),this}invert(){return q1.vec2.inverse(this,this),this}lerp(Z,J){return q1.vec2.lerp(this,this,Z,J),this}max(Z){return q1.vec2.max(this,this,Z),this}min(Z){return q1.vec2.min(this,this,Z),this}multiply(Z){return q1.vec2.mul(this,this,Z),this}negate(){return q1.vec2.negate(this,this),this}normalize(){return q1.vec2.normalize(this,this),this}randomize(Z){return q1.vec2.random(this,Z),this}rotate(Z,J){return q1.vec2.rotate(this,this,Z,J),this}round(){return q1.vec2.round(this,this),this}scale(Z){return q1.vec2.scale(this,this,Z),this}scaleAndAdd(Z,J){return q1.vec2.scaleAndAdd(this,this,Z,J),this}subtract(Z){return q1.vec2.sub(this,this,Z),this}toString(){return`${this.x},${this.y}`}transformMatrix2(Z){return q1.vec2.transformMat2(this,this,Z),this}transformMatrix3(Z){return q1.vec2.transformMat3(this,this,Z),this}transformMatrix4(Z){return q1.vec2.transformMat4(this,this,Z),this}zero(){return q1.vec2.zero(this),this}}var z1=t(kQ(),1);class DW extends Float32Array{constructor(Z,J,X){super([Z,J,X])}get length(){return z1.vec3.length(this)}get squaredLength(){return z1.vec3.squaredLength(this)}get magnitude(){return z1.vec3.length(this)}get squaredMagnitude(){return z1.vec3.squaredLength(this)}get x(){return this[0]}set x(Z){this[0]=Z}get y(){return this[1]}set y(Z){this[1]=Z}get z(){return this[2]}set z(Z){this[2]=Z}static create(){return new DW(0,0,0)}static fromVector3Like(Z){return new DW(Z.x,Z.y,Z.z)}add(Z){return z1.vec3.add(this,this,Z),this}ceil(){return z1.vec3.ceil(this,this),this}clone(){return new DW(this.x,this.y,this.z)}copy(Z){return z1.vec3.copy(this,Z),this}cross(Z){return z1.vec3.cross(this,this,Z),this}distance(Z){return z1.vec3.distance(this,Z)}divide(Z){return z1.vec3.div(this,this,Z),this}dot(Z){return z1.vec3.dot(this,Z)}equals(Z){return z1.vec3.equals(this,Z)}exactEquals(Z){return z1.vec3.exactEquals(this,Z)}floor(){return z1.vec3.floor(this,this),this}invert(){return z1.vec3.inverse(this,this),this}lerp(Z,J){return z1.vec3.lerp(this,this,Z,J),this}max(Z){return z1.vec3.max(this,this,Z),this}min(Z){return z1.vec3.min(this,this,Z),this}multiply(Z){return z1.vec3.mul(this,this,Z),this}negate(){return z1.vec3.negate(this,this),this}normalize(){return z1.vec3.normalize(this,this),this}randomize(Z){return z1.vec3.random(this,Z),this}rotateX(Z,J){return z1.vec3.rotateX(this,this,Z,J),this}rotateY(Z,J){return z1.vec3.rotateY(this,this,Z,J),this}rotateZ(Z,J){return z1.vec3.rotateZ(this,this,Z,J),this}round(){return z1.vec3.round(this,this),this}scale(Z){return z1.vec3.scale(this,this,Z),this}scaleAndAdd(Z,J){return z1.vec3.scaleAndAdd(this,this,Z,J),this}subtract(Z){return z1.vec3.sub(this,this,Z),this}toString(){return`${this.x},${this.y},${this.z}`}transformMatrix3(Z){return z1.vec3.transformMat3(this,this,Z),this}transformMatrix4(Z){return z1.vec3.transformMat4(this,this,Z),this}transformQuaternion(Z){return z1.vec3.transformQuat(this,this,Z),this}zero(){return z1.vec3.zero(this),this}}var mW1=t(SW1(),1);var AW1=0.099856;class TH extends x${faceSpeed=0;idleLoopedAnimations=[];idleLoopedAnimationsSpeed;jumpOneshotAnimations=[];moveLoopedAnimations=[];moveLoopedAnimationsSpeed;moveSpeed=0;_faceTarget;_jumpHeight=0;_moveCompletesWhenStuck=!1;_moveIgnoreAxes={};_moveStartMoveAnimations=!1;_moveStartIdleAnimationsOnCompletion=!0;_moveStoppingDistanceSquared=AW1;_moveStuckAccumulatorMs=0;_moveStuckLastPosition;_moveTarget;_onFace;_onFaceComplete;_onMove;_onMoveComplete;_stopFaceRequested=!1;_stopMoveRequested=!1;constructor(Z={}){super();this.idleLoopedAnimations=Z.idleLoopedAnimations??this.idleLoopedAnimations,this.idleLoopedAnimationsSpeed=Z.idleLoopedAnimationsSpeed??this.idleLoopedAnimationsSpeed,this.jumpOneshotAnimations=Z.jumpOneshotAnimations??this.jumpOneshotAnimations,this.moveLoopedAnimations=Z.moveLoopedAnimations??this.moveLoopedAnimations,this.moveLoopedAnimationsSpeed=Z.moveLoopedAnimationsSpeed??this.moveLoopedAnimationsSpeed}spawn(Z){super.spawn(Z),this._startIdleAnimations(Z)}face(Z,J,X){this._faceTarget=Z,this.faceSpeed=J,this._onFace=X?.faceCallback,this._onFaceComplete=X?.faceCompleteCallback}jump(Z){this._jumpHeight=Z}move(Z,J,X){this.moveSpeed=J,this._moveCompletesWhenStuck=X?.moveCompletesWhenStuck??!1,this._moveIgnoreAxes=X?.moveIgnoreAxes??{},this._moveStartIdleAnimationsOnCompletion=X?.moveStartIdleAnimationsOnCompletion??!0,this._moveStartMoveAnimations=!0,this._moveStoppingDistanceSquared=X?.moveStoppingDistance?X.moveStoppingDistance**2:AW1,this._moveTarget=Z,this._onMove=X?.moveCallback,this._onMoveComplete=X?.moveCompleteCallback,this._moveStuckAccumulatorMs=0,this._moveStuckLastPosition=void 0}stopFace(){this._stopFaceRequested=!0}stopMove(){this._stopMoveRequested=!0}tick(Z,J){if(super.tick(Z,J),!this._moveTarget&&!this._faceTarget&&!this._jumpHeight)return;if(this._moveStartMoveAnimations)this._startMoveAnimations(Z),this._moveStartMoveAnimations=!1;let X=J/1000,$=Z.position;if(Z.isDynamic&&this._jumpHeight>0){let Y=Math.abs(Z.world.simulation.gravity.y),Q=Math.sqrt(2*Y*this._jumpHeight);Z.applyImpulse({x:0,y:Q*Z.mass,z:0}),this._jumpHeight=0,this._startJumpAnimations(Z)}if(this._moveTarget){let Y={x:this._moveIgnoreAxes.x?0:this._moveTarget.x-$.x,y:this._moveIgnoreAxes.y?0:this._moveTarget.y-$.y,z:this._moveIgnoreAxes.z?0:this._moveTarget.z-$.z},Q=Y.x*Y.x+Y.y*Y.y+Y.z*Y.z,K=!1;if(this._moveCompletesWhenStuck){if(this._moveStuckAccumulatorMs+=J,this._moveStuckAccumulatorMs>=500){if(this._moveStuckLastPosition){let W=$.x-this._moveStuckLastPosition.x,G=$.y-this._moveStuckLastPosition.y,z=$.z-this._moveStuckLastPosition.z;K=Math.sqrt(W*W+G*G+z*z)<this.moveSpeed*0.1}this._moveStuckLastPosition=$,this._moveStuckAccumulatorMs=0}}if(Q>this._moveStoppingDistanceSquared&&!this._stopMoveRequested&&!K){let W=Math.sqrt(Q),G=this.moveSpeed*X,v=Math.min(W,G)/W,H={x:$.x+Y.x*v,y:$.y+Y.y*v,z:$.z+Y.z*v};if(Z.setPosition(H),this._onMove)this._onMove(H,this._moveTarget)}else{if(this._moveStuckAccumulatorMs=0,this._moveStuckLastPosition=void 0,this._moveTarget=void 0,this._stopMoveRequested=!1,this._moveStartIdleAnimationsOnCompletion)this._startIdleAnimations(Z);if(this._onMoveComplete){let W=this._onMoveComplete;this._onMove=void 0,this._onMoveComplete=void 0,W($)}}}if(this._faceTarget){let Y={x:this._faceTarget.x-$.x,z:this._faceTarget.z-$.z},Q=Math.atan2(-Y.x,-Y.z),K=Z.rotation,W=Math.atan2(2*(K.w*K.y),1-2*(K.y*K.y)),G=Q-W;while(G>Math.PI)G-=2*Math.PI;while(G<-Math.PI)G+=2*Math.PI;if(Math.abs(G)>0.01&&!this._stopFaceRequested){let z=this.faceSpeed*X,v=Math.abs(G)<z?G:Math.sign(G)*z,V=(W+v)/2,q={x:0,y:Math.fround(Math.sin(V)),z:0,w:Math.fround(Math.cos(V))};if(Z.setRotation(q),this._onFace)this._onFace(K,q)}else if(this._faceTarget=void 0,this._stopFaceRequested=!1,this._onFaceComplete){let z=this._onFaceComplete;this._onFace=void 0,this._onFaceComplete=void 0,z(Z.rotation)}}}_startIdleAnimations(Z){if(this.idleLoopedAnimationsSpeed)Z.setModelAnimationsPlaybackRate(this.idleLoopedAnimationsSpeed);Z.stopModelAnimations(this.moveLoopedAnimations),Z.stopModelAnimations(this.jumpOneshotAnimations),Z.startModelLoopedAnimations(this.idleLoopedAnimations)}_startJumpAnimations(Z){Z.stopModelAnimations(this.moveLoopedAnimations),Z.stopModelAnimations(this.idleLoopedAnimations),Z.startModelOneshotAnimations(this.jumpOneshotAnimations)}_startMoveAnimations(Z){if(this.moveLoopedAnimationsSpeed)Z.setModelAnimationsPlaybackRate(this.moveLoopedAnimationsSpeed);Z.stopModelAnimations(this.jumpOneshotAnimations),Z.stopModelAnimations(this.idleLoopedAnimations),Z.startModelLoopedAnimations(this.moveLoopedAnimations)}}class HA extends TH{_debug=!1;_entity;_maxFall=0;_maxJump=0;_maxOpenSetIterations=200;_onPathfindAbort;_onPathfindComplete;_onWaypointMoveComplete;_onWaypointMoveSkipped;_speed=0;_target;_verticalPenalty=0;_waypoints=[];_waypointNextIndex=0;_waypointStoppingDistance;_waypointTimeoutMs=2000;constructor(Z={}){super(Z)}get debug(){return this._debug}get maxFall(){return this._maxFall}get maxJump(){return this._maxJump}get maxOpenSetIterations(){return this._maxOpenSetIterations}get speed(){return this._speed}get target(){return this._target}get verticalPenalty(){return this._verticalPenalty}get waypoints(){return this._waypoints}get waypointNextIndex(){return this._waypointNextIndex}get waypointTimeoutMs(){return this._waypointTimeoutMs}pathfind(Z,J,X){if(this._target=Z,this._speed=J,this._debug=X?.debug??!1,this._maxFall=X?.maxFall?-Math.abs(X.maxFall):0,this._maxJump=X?.maxJump?Math.abs(X.maxJump):0,this._maxOpenSetIterations=X?.maxOpenSetIterations??200,this._onPathfindAbort=X?.pathfindAbortCallback,this._onPathfindComplete=X?.pathfindCompleteCallback,this._onWaypointMoveComplete=X?.waypointMoveCompleteCallback,this._onWaypointMoveSkipped=X?.waypointMoveSkippedCallback,this._verticalPenalty=X?.verticalPenalty??0,this._waypoints=[],this._waypointNextIndex=0,this._waypointStoppingDistance=X?.waypointStoppingDistance,this._waypointTimeoutMs=X?.waypointTimeoutMs??2000/J,!this._calculatePath())return!1;return this._moveToNextWaypoint(),!0}attach(Z){super.attach(Z),this._entity=Z}detach(Z){super.detach(Z),this._entity=void 0}_calculatePath(){if(!this._target||!this._entity?.world)return p.error("PathfindingEntityController._calculatePath: No target or world"),!1;let Z=this._entity.height,J=this._findGroundedStart();if(!J){if(this._debug)p.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)},$=Math.abs(X.x-J.x),Y=Math.abs(X.y-J.y),Q=Math.abs(X.z-J.z);if($<=2&&Y<=2&&Q<=2&&!this._isNeighborCoordinateBlocked(J,X,this._entity.height))return this._waypoints=[{x:J.x+0.5,y:J.y+Z/2,z:J.z+0.5},{x:X.x+0.5,y:X.y+Z/2,z:X.z+0.5}],!0;if(J.x===X.x&&J.y===X.y&&J.z===X.z)return this._waypoints=[{x:J.x+0.5,y:J.y+Z/2,z:J.z+0.5}],!0;let W=this._coordinateToKey(J),G=new Map,z=new Map([[W,0]]),v=new Map([[W,this._pathfindingHeuristic(J,X)]]),H=new Set,V=new mW1.Heap((j,L)=>{let R=v.get(j[0])??1/0,M=v.get(L[0])??1/0;return R-M});V.push([W,J]);let q=[{x:0,y:0,z:1},{x:1,y:0,z:0},{x:0,y:0,z:-1},{x:-1,y:0,z:0},{x:1,y:0,z:1},{x:1,y:0,z:-1},{x:-1,y:0,z:1},{x:-1,y:0,z:-1}],F=[];for(let j=this._maxJump;j>=this._maxFall;j--){if(j===0)continue;let L=Math.abs(J.y+j-X.y);F.push({y:j,distanceToTargetY:L})}F.sort((j,L)=>j.distanceToTargetY-L.distanceToTargetY);let x=[...q,...F.flatMap(({y:j})=>q.map((L)=>({...L,y:j})))],c=0,w=Math.abs(X.x-J.x)+Math.abs(X.y-J.y)+Math.abs(X.z-J.z),B=Math.min(this._maxOpenSetIterations,w*20);while(!V.isEmpty()&&c<B){c++;let[j,L]=V.pop();if(L.x===X.x&&L.y===X.y&&L.z===X.z){let N=this._reconstructPath(G,L);if(this._waypoints=N.map((P)=>({x:P.x+0.5,y:P.y+Z/2,z:P.z+0.5})),this._debug)console.log(`PathfindingEntityController._calculatePath: Path found after ${c} open set iterations. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`);return!0}H.add(j);let R=z.get(j),M=new Map;for(let N of x){let P=`${N.x},${N.z}`,O=N.y<0;if(O&&M.has(P))continue;let _={x:L.x+N.x,y:L.y+N.y,z:L.z+N.z};if(Math.abs(X.x-_.x)+Math.abs(X.y-_.y)+Math.abs(X.z-_.z)>w*1.5)continue;let h=this._coordinateToKey(_);if(H.has(h))continue;let f=this._isNeighborCoordinateBlocked(L,_,this._entity.height);if(O&&f){M.set(P,!0);continue}if(f)continue;let C=Math.abs(N.x),b=Math.abs(N.y),I=Math.abs(N.z),a=b===0?0:this._verticalPenalty,s=(Math.max(C,b,I)===1&&C+b+I>1?1.4:1)+a,Z0=R+s,o=z.get(h)??1/0;if(Z0>=o)continue;G.set(h,L),z.set(h,Z0);let M0=Z0+this._pathfindingHeuristic(_,X);v.set(h,M0),V.push([h,_])}}if(c>=B){if(this._onPathfindAbort?.(),this._debug)p.warning(`PathfindingEntityController._calculatePath: Maximum open set iterations reached (${B}), path search aborted. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`)}else if(this._debug)p.warning(`PathfindingEntityController._calculatePath: No valid path found. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`);return this._target=void 0,this._waypoints=[],!1}_reconstructPath(Z,J){let X=[J],$=J;while(Z.has(this._coordinateToKey($)))$=Z.get(this._coordinateToKey($)),X.unshift($);return X}_coordinateToKey(Z){return`${Z.x},${Z.y},${Z.z}`}_moveToNextWaypoint(){let Z=this._waypointNextIndex>0?this._waypoints[this._waypointNextIndex-1]:void 0,J=this._waypoints[this._waypointNextIndex];if(!J||!this._entity)return;let X=0;if(this._entity.isDynamic&&Z&&J.y>Z.y){let $=J.y-Z.y,Y=Math.min($,this._maxJump)+0.75;this.jump(Y);let Q=Math.abs(this._entity.world.simulation.gravity.y),K=Math.sqrt(2*Q*Y),W=Z.x+0.5,G=Z.z+0.5,z=J.x+0.5,v=J.z+0.5,H=z-W,V=v-G,q=Math.sqrt(H*H+V*V),F=K/Q,x=q/this._speed;X=Math.min(F*0.8,x)*1000}setTimeout(()=>{if(!this._entity)return;let $=Date.now();this.face(J,this._speed),this.move(J,this._speed,{moveCompletesWhenStuck:!0,moveIgnoreAxes:{y:this._entity.isDynamic},moveStartIdleAnimationsOnCompletion:this._waypointNextIndex===this._waypoints.length-1,moveStoppingDistance:this._waypointStoppingDistance,moveCallback:()=>{if(Date.now()-$>this._waypointTimeoutMs&&this._waypointNextIndex<this._waypoints.length-1)this._onWaypointMoveSkipped?.(J,this._waypointNextIndex),this._waypointNextIndex++,this._moveToNextWaypoint()},moveCompleteCallback:()=>{if(this._waypointNextIndex<this._waypoints.length-1)this._onWaypointMoveComplete?.(J,this._waypointNextIndex),this._waypointNextIndex++,this._moveToNextWaypoint();else this._onPathfindComplete?.()}})},X)}_pathfindingHeuristic(Z,J){return Math.abs(Z.x-J.x)+Math.abs(Z.y-J.y)+Math.abs(Z.z-J.z)}_isNeighborCoordinateBlocked(Z,J,X){if(!this._entity?.world)return!1;let $=this._entity.world,Y=Math.floor(J.x),Q=Math.floor(J.y),K=Math.floor(J.z),W=Math.floor(Z.x),G=Math.floor(Z.z);if(!$.chunkLattice.hasBlock({x:Y,y:Q-1,z:K}))return!0;for(let z=0;z<X;z++)if($.chunkLattice.hasBlock({x:Y,y:Q+z,z:K}))return!0;if(Y!==W&&K!==G)for(let z=0;z<X;z++){let v=$.chunkLattice.hasBlock({x:Y,y:Q+z,z:G}),H=$.chunkLattice.hasBlock({x:W,y:Q+z,z:K});if(v||H)return!0}return!1}_findGroundedStart(){if(!this._entity?.world)return;let{x:Z,y:J,z:X}=this._entity.position,$={x:Math.floor(Z),y:Math.floor(J),z:Math.floor(X)};for(let Y=0;Y<=Math.abs(this._maxFall);Y++)if(this._entity.world.chunkLattice.hasBlock({...$,y:$.y-Y-1}))return{...$,y:$.y-Y};return}}export{oJ6 as startServer,s31 as WorldManagerEvent,q$ as WorldManager,n31 as WorldLoopEvent,NH as WorldLoop,$A as WorldEvent,OH as World,kf as WebServerEvent,FK as WebServer,DW as Vector3,PH as Vector2,RH as Ticker,PQ as TelemetrySpanOperation,V8 as Telemetry,XA as SimulationEvent,LH as Simulation,TH as SimpleEntityController,MH as SceneUIManager,iP as SceneUIEvent,mz as SceneUI,N80 as SUPPORTED_INPUT_KEYS,oG as RigidBodyType,u$ as RigidBody,LW as Quaternion,gc as PlayerUIEvent,Iz as PlayerUI,o31 as PlayerManagerEvent,n5 as PlayerManager,_z as PlayerEvent,F7 as PlayerEntity,R80 as PlayerCameraMode,uP as PlayerCameraEvent,Ez as PlayerCamera,g3 as Player,e$ as PersistenceManager,HA as PathfindingEntityController,DH as ParticleEmitterManager,eS as ParticleEmitterEvent,ZA as ParticleEmitter,Cf as PORT,f80 as PLAYER_ROTATION_UPDATE_THRESHOLD,C80 as PLAYER_POSITION_UPDATE_THRESHOLD_SQ,j6 as ModelRegistry,W5 as Matrix4,p7 as Matrix3,EQ as Matrix2,a31 as LightType,jH as LightManager,rS as LightEvent,tS as Light,r8 as IterationMap,r31 as GameServerEvent,TQ as GameServer,B0 as EventRouter,p as ErrorHandler,uz as EntityManager,Az as EntityEvent,j8 as Entity,T80 as ENTITY_ROTATION_UPDATE_THRESHOLD,P80 as ENTITY_POSITION_UPDATE_THRESHOLD_SQ,b1 as DefaultPlayerEntityController,gP as DefaultPlayerEntity,O80 as DEFAULT_ENTITY_RIGID_BODY_OPTIONS,v9 as CollisionGroupsBuilder,B$ as CollisionGroup,O3 as ColliderShape,Sz as ColliderMap,S5 as Collider,lN as CoefficientCombineRule,pP as ChunkLatticeEvent,hz as ChunkLattice,p5 as Chunk,bz as ChatManager,lP as ChatEvent,pN as BlockTypeRegistryEvent,rG as BlockTypeRegistry,yN as BlockTypeEvent,A5 as BlockType,bQ as Block,BA as BaseEntityControllerEvent,x$ as BaseEntityController,NW as AudioManager,$L as AudioEvent,RW as Audio};