141 private const INCOMING_PACKET_BATCH_PER_TICK = 2;
142 private const INCOMING_PACKET_BATCH_BUFFER_TICKS = 100;
144 private const INCOMING_GAME_PACKETS_PER_TICK = 2;
145 private const INCOMING_GAME_PACKETS_BUFFER_TICKS = 100;
150 private \PrefixedLogger $logger;
151 private ?
Player $player =
null;
153 private ?
int $ping =
null;
157 private bool $connected =
true;
158 private bool $disconnectGuard =
false;
159 private bool $loggedIn =
false;
160 private bool $authenticated =
false;
161 private int $connectTime;
162 private ?
CompoundTag $cachedOfflinePlayerData =
null;
170 private array $sendBuffer = [];
175 private array $sendBufferAckPromises = [];
178 private \SplQueue $compressedQueue;
179 private bool $forceAsyncCompression =
true;
180 private bool $enableCompression =
false;
182 private int $nextAckReceiptId = 0;
187 private array $ackPromisesByReceiptId = [];
197 public function __construct(
209 $this->logger = new \PrefixedLogger($this->
server->getLogger(), $this->getLogPrefix());
211 $this->compressedQueue = new \SplQueue();
215 $this->connectTime = time();
216 $this->packetBatchLimiter =
new PacketRateLimiter(
"Packet Batches", self::INCOMING_PACKET_BATCH_PER_TICK, self::INCOMING_PACKET_BATCH_BUFFER_TICKS);
217 $this->gamePacketLimiter =
new PacketRateLimiter(
"Game Packets", self::INCOMING_GAME_PACKETS_PER_TICK, self::INCOMING_GAME_PACKETS_BUFFER_TICKS);
221 $this->onSessionStartSuccess(...)
224 $this->manager->add($this);
225 $this->logger->info($this->
server->getLanguage()->translate(KnownTranslationFactory::pocketmine_network_session_open()));
228 private function getLogPrefix() :
string{
229 return "NetworkSession: " . $this->getDisplayName();
232 public function getLogger() : \
Logger{
233 return $this->logger;
236 private function onSessionStartSuccess() :
void{
237 $this->logger->debug(
"Session start handshake completed, awaiting login packet");
238 $this->flushGamePacketQueue();
239 $this->enableCompression =
true;
245 $this->logger->info($this->
server->getLanguage()->translate(KnownTranslationFactory::pocketmine_network_session_playerName(TextFormat::AQUA . $info->getUsername() . TextFormat::RESET)));
246 $this->logger->setPrefix($this->getLogPrefix());
247 $this->manager->markLoginReceived($this);
249 $this->setAuthenticationStatus(...)
253 protected function createPlayer() :
void{
254 $this->
server->createPlayer($this, $this->info, $this->authenticated, $this->cachedOfflinePlayerData)->onCompletion(
255 $this->onPlayerCreated(...),
258 $this->disconnectWithError(
259 reason:
"Failed to create player",
260 disconnectScreenMessage: KnownTranslationFactory::pocketmine_disconnect_error_internal()
266 private function onPlayerCreated(
Player $player) :
void{
267 if(!$this->isConnected()){
271 $this->player = $player;
272 if(!$this->
server->addOnlinePlayer($player)){
278 $effectManager = $this->player->getEffects();
279 $effectManager->getEffectAddHooks()->add($effectAddHook =
function(
EffectInstance $effect,
bool $replacesOldEffect) :
void{
280 $this->entityEventBroadcaster->onEntityEffectAdded([$this], $this->player, $effect, $replacesOldEffect);
282 $effectManager->getEffectRemoveHooks()->add($effectRemoveHook =
function(
EffectInstance $effect) :
void{
283 $this->entityEventBroadcaster->onEntityEffectRemoved([$this], $this->player, $effect);
285 $this->disposeHooks->add(
static function() use ($effectManager, $effectAddHook, $effectRemoveHook) :
void{
286 $effectManager->getEffectAddHooks()->remove($effectAddHook);
287 $effectManager->getEffectRemoveHooks()->remove($effectRemoveHook);
290 $permissionHooks = $this->player->getPermissionRecalculationCallbacks();
291 $permissionHooks->add($permHook =
function() :
void{
292 $this->logger->debug(
"Syncing available commands and abilities/permissions due to permission recalculation");
293 $this->syncAbilities($this->player);
294 $this->syncAvailableCommands();
296 $this->disposeHooks->add(
static function() use ($permissionHooks, $permHook) :
void{
297 $permissionHooks->remove($permHook);
299 $this->beginSpawnSequence();
302 public function getPlayer() : ?
Player{
303 return $this->player;
306 public function getPlayerInfo() : ?
PlayerInfo{
310 public function isConnected() :
bool{
311 return $this->connected && !$this->disconnectGuard;
314 public function getIp() :
string{
318 public function getPort() :
int{
322 public function getDisplayName() :
string{
323 return $this->info !==
null ? $this->info->getUsername() : $this->ip .
" " . $this->port;
336 public function updatePing(
int $ping) : void{
340 public function getHandler() : ?PacketHandler{
341 return $this->handler;
344 public function setHandler(?PacketHandler $handler) : void{
345 if($this->connected){
346 $this->handler = $handler;
347 if($this->handler !==
null){
348 $this->handler->setUp();
357 if(!$this->connected){
361 Timings::$playerNetworkReceive->startTiming();
363 $this->packetBatchLimiter->decrement();
365 if($this->cipher !==
null){
366 Timings::$playerNetworkReceiveDecrypt->startTiming();
368 $payload = $this->cipher->decrypt($payload);
369 }
catch(DecryptionException $e){
370 $this->logger->debug(
"Encrypted packet: " . base64_encode($payload));
371 throw PacketHandlingException::wrap($e,
"Packet decryption error");
373 Timings::$playerNetworkReceiveDecrypt->stopTiming();
377 if(strlen($payload) < 1){
378 throw new PacketHandlingException(
"No bytes in payload");
381 if($this->enableCompression){
382 $compressionType = ord($payload[0]);
383 $compressed = substr($payload, 1);
384 if($compressionType === CompressionAlgorithm::NONE){
385 $decompressed = $compressed;
386 }elseif($compressionType === $this->compressor->getNetworkId()){
387 Timings::$playerNetworkReceiveDecompress->startTiming();
389 $decompressed = $this->compressor->decompress($compressed);
390 }
catch(DecompressionException $e){
391 $this->logger->debug(
"Failed to decompress packet: " . base64_encode($compressed));
392 throw PacketHandlingException::wrap($e,
"Compressed packet batch decode error");
394 Timings::$playerNetworkReceiveDecompress->stopTiming();
397 throw new PacketHandlingException(
"Packet compressed with unexpected compression type $compressionType");
400 $decompressed = $payload;
404 $stream =
new BinaryStream($decompressed);
405 foreach(PacketBatch::decodeRaw($stream) as $buffer){
406 $this->gamePacketLimiter->decrement();
407 $packet = $this->packetPool->getPacket($buffer);
408 if($packet ===
null){
409 $this->logger->debug(
"Unknown packet: " . base64_encode($buffer));
410 throw new PacketHandlingException(
"Unknown packet received");
413 $this->handleDataPacket($packet, $buffer);
414 }
catch(PacketHandlingException $e){
415 $this->logger->debug($packet->getName() .
": " . base64_encode($buffer));
416 throw PacketHandlingException::wrap($e,
"Error processing " . $packet->getName());
419 }
catch(PacketDecodeException|BinaryDataException $e){
420 $this->logger->logException($e);
421 throw PacketHandlingException::wrap($e,
"Packet batch decode error");
424 Timings::$playerNetworkReceive->stopTiming();
436 $timings = Timings::getReceiveDataPacketTimings($packet);
437 $timings->startTiming();
440 if(DataPacketDecodeEvent::hasHandlers()){
443 if($ev->isCancelled()){
448 $decodeTimings = Timings::getDecodeDataPacketTimings($packet);
449 $decodeTimings->startTiming();
451 $stream = PacketSerializer::decoder($buffer, 0);
453 $packet->decode($stream);
454 }
catch(PacketDecodeException $e){
455 throw PacketHandlingException::wrap($e);
457 if(!$stream->feof()){
458 $remains = substr($stream->getBuffer(), $stream->getOffset());
459 $this->logger->debug(
"Still " . strlen($remains) .
" bytes unread in " . $packet->getName() .
": " . bin2hex($remains));
462 $decodeTimings->stopTiming();
465 if(DataPacketReceiveEvent::hasHandlers()){
466 $ev =
new DataPacketReceiveEvent($this, $packet);
468 if($ev->isCancelled()){
472 $handlerTimings = Timings::getHandleDataPacketTimings($packet);
473 $handlerTimings->startTiming();
475 if($this->handler ===
null || !$packet->handle($this->handler)){
476 $this->logger->debug(
"Unhandled " . $packet->getName() .
": " . base64_encode($stream->getBuffer()));
479 $handlerTimings->stopTiming();
482 $timings->stopTiming();
486 public function handleAckReceipt(
int $receiptId) : void{
487 if(!$this->connected){
490 if(isset($this->ackPromisesByReceiptId[$receiptId])){
491 $promises = $this->ackPromisesByReceiptId[$receiptId];
492 unset($this->ackPromisesByReceiptId[$receiptId]);
493 foreach($promises as $promise){
494 $promise->resolve(
true);
502 private function sendDataPacketInternal(ClientboundPacket $packet,
bool $immediate, ?PromiseResolver $ackReceiptResolver) : bool{
503 if(!$this->connected){
507 if(!$this->loggedIn && !$packet->canBeSentBeforeLogin()){
508 throw new \InvalidArgumentException(
"Attempted to send " . get_class($packet) .
" to " . $this->getDisplayName() .
" too early");
511 $timings = Timings::getSendDataPacketTimings($packet);
512 $timings->startTiming();
514 if(DataPacketSendEvent::hasHandlers()){
515 $ev = new DataPacketSendEvent([$this], [$packet]);
517 if($ev->isCancelled()){
520 $packets = $ev->getPackets();
522 $packets = [$packet];
525 if($ackReceiptResolver !==
null){
526 $this->sendBufferAckPromises[] = $ackReceiptResolver;
528 foreach($packets as $evPacket){
529 $this->addToSendBuffer(self::encodePacketTimed(PacketSerializer::encoder(), $evPacket));
532 $this->flushGamePacketQueue();
537 $timings->stopTiming();
541 public function sendDataPacket(ClientboundPacket $packet,
bool $immediate =
false) : bool{
542 return $this->sendDataPacketInternal($packet, $immediate, null);
552 if(!$this->sendDataPacketInternal($packet, $immediate, $resolver)){
562 public static function encodePacketTimed(PacketSerializer $serializer, ClientboundPacket $packet) : string{
563 $timings =
Timings::getEncodeDataPacketTimings($packet);
564 $timings->startTiming();
566 $packet->encode($serializer);
567 return $serializer->getBuffer();
569 $timings->stopTiming();
576 public function addToSendBuffer(
string $buffer) : void{
577 $this->sendBuffer[] = $buffer;
580 private function flushGamePacketQueue() : void{
581 if(count($this->sendBuffer) > 0){
582 Timings::$playerNetworkSend->startTiming();
585 if($this->forceAsyncCompression){
589 $stream =
new BinaryStream();
590 PacketBatch::encodeRaw($stream, $this->sendBuffer);
592 if($this->enableCompression){
593 $batch = $this->
server->prepareBatch($stream->getBuffer(), $this->compressor, $syncMode, Timings::$playerNetworkSendCompressSessionBuffer);
595 $batch = $stream->getBuffer();
597 $this->sendBuffer = [];
598 $ackPromises = $this->sendBufferAckPromises;
599 $this->sendBufferAckPromises = [];
602 $this->queueCompressedNoGamePacketFlush($batch, networkFlush:
true, ackPromises: $ackPromises);
604 Timings::$playerNetworkSend->stopTiming();
609 public function getBroadcaster() : PacketBroadcaster{ return $this->broadcaster; }
611 public function getEntityEventBroadcaster() : EntityEventBroadcaster{ return $this->entityEventBroadcaster; }
613 public function getCompressor() : Compressor{
614 return $this->compressor;
617 public function getTypeConverter() : TypeConverter{ return $this->typeConverter; }
619 public function queueCompressed(CompressBatchPromise|
string $payload,
bool $immediate =
false) : void{
620 Timings::$playerNetworkSend->startTiming();
624 $this->flushGamePacketQueue();
625 $this->queueCompressedNoGamePacketFlush($payload, $immediate);
627 Timings::$playerNetworkSend->stopTiming();
636 private function queueCompressedNoGamePacketFlush(CompressBatchPromise|
string $batch,
bool $networkFlush =
false, array $ackPromises = []) : void{
637 Timings::$playerNetworkSend->startTiming();
639 $this->compressedQueue->enqueue([$batch, $ackPromises, $networkFlush]);
640 if(is_string($batch)){
641 $this->flushCompressedQueue();
643 $batch->onResolve(
function() :
void{
644 if($this->connected){
645 $this->flushCompressedQueue();
650 Timings::$playerNetworkSend->stopTiming();
654 private function flushCompressedQueue() : void{
655 Timings::$playerNetworkSend->startTiming();
657 while(!$this->compressedQueue->isEmpty()){
659 [$current, $ackPromises, $networkFlush] = $this->compressedQueue->bottom();
660 if(is_string($current)){
661 $this->compressedQueue->dequeue();
662 $this->sendEncoded($current, $networkFlush, $ackPromises);
664 }elseif($current->hasResult()){
665 $this->compressedQueue->dequeue();
666 $this->sendEncoded($current->getResult(), $networkFlush, $ackPromises);
674 Timings::$playerNetworkSend->stopTiming();
682 private function sendEncoded(
string $payload,
bool $immediate, array $ackPromises) : void{
683 if($this->cipher !== null){
684 Timings::$playerNetworkSendEncrypt->startTiming();
685 $payload = $this->cipher->encrypt($payload);
686 Timings::$playerNetworkSendEncrypt->stopTiming();
689 if(count($ackPromises) > 0){
690 $ackReceiptId = $this->nextAckReceiptId++;
691 $this->ackPromisesByReceiptId[$ackReceiptId] = $ackPromises;
693 $ackReceiptId =
null;
695 $this->sender->send($payload, $immediate, $ackReceiptId);
701 private function tryDisconnect(\Closure $func, Translatable|
string $reason) : void{
702 if($this->connected && !$this->disconnectGuard){
703 $this->disconnectGuard =
true;
705 $this->disconnectGuard =
false;
706 $this->flushGamePacketQueue();
707 $this->sender->close(
"");
708 foreach($this->disposeHooks as $callback){
711 $this->disposeHooks->clear();
712 $this->setHandler(
null);
713 $this->connected =
false;
715 $ackPromisesByReceiptId = $this->ackPromisesByReceiptId;
716 $this->ackPromisesByReceiptId = [];
717 foreach($ackPromisesByReceiptId as $resolvers){
718 foreach($resolvers as $resolver){
722 $sendBufferAckPromises = $this->sendBufferAckPromises;
723 $this->sendBufferAckPromises = [];
724 foreach($sendBufferAckPromises as $resolver){
728 $this->logger->info($this->
server->getLanguage()->translate(KnownTranslationFactory::pocketmine_network_session_close($reason)));
736 private function dispose() : void{
737 $this->invManager = null;
740 private function sendDisconnectPacket(Translatable|
string $message) : void{
741 if($message instanceof Translatable){
742 $translated = $this->
server->getLanguage()->translate($message);
744 $translated = $message;
746 $this->sendDataPacket(DisconnectPacket::create(0, $translated,
""));
756 $this->tryDisconnect(function() use ($reason, $disconnectScreenMessage, $notify) : void{
758 $this->sendDisconnectPacket($disconnectScreenMessage ?? $reason);
760 if($this->player !==
null){
761 $this->player->onPostDisconnect($reason,
null);
766 public function disconnectWithError(Translatable|
string $reason, Translatable|
string|
null $disconnectScreenMessage =
null) : void{
767 $errorId = implode(
"-", str_split(bin2hex(random_bytes(6)), 4));
770 reason: KnownTranslationFactory::pocketmine_disconnect_error($reason, $errorId)->prefix(TextFormat::RED),
771 disconnectScreenMessage: KnownTranslationFactory::pocketmine_disconnect_error($disconnectScreenMessage ?? $reason, $errorId),
775 public function disconnectIncompatibleProtocol(
int $protocolVersion) : void{
776 $this->tryDisconnect(
777 function() use ($protocolVersion) : void{
778 $this->sendDataPacket(PlayStatusPacket::create($protocolVersion < ProtocolInfo::CURRENT_PROTOCOL ? PlayStatusPacket::LOGIN_FAILED_CLIENT : PlayStatusPacket::LOGIN_FAILED_SERVER), true);
780 KnownTranslationFactory::pocketmine_disconnect_incompatibleProtocol((
string) $protocolVersion)
789 $this->tryDisconnect(
function() use ($ip, $port, $reason) :
void{
790 $this->sendDataPacket(TransferPacket::create($ip, $port,
false),
true);
791 if($this->player !==
null){
792 $this->player->onPostDisconnect($reason,
null);
801 $this->tryDisconnect(function() use ($disconnectScreenMessage) : void{
802 $this->sendDisconnectPacket($disconnectScreenMessage);
811 $this->tryDisconnect(function() use ($reason) : void{
812 if($this->player !== null){
813 $this->player->onPostDisconnect($reason,
null);
818 private function setAuthenticationStatus(
bool $authenticated,
bool $authRequired,
Translatable|
string|
null $error, ?
string $clientPubKey) : void{
819 if(!$this->connected){
823 if($authenticated && !($this->info instanceof XboxLivePlayerInfo)){
824 $error =
"Expected XUID but none found";
825 }elseif($clientPubKey ===
null){
826 $error =
"Missing client public key";
831 $this->disconnectWithError(
832 reason: KnownTranslationFactory::pocketmine_disconnect_invalidSession($error),
833 disconnectScreenMessage: KnownTranslationFactory::pocketmine_disconnect_error_authentication()
839 $this->authenticated = $authenticated;
841 if(!$this->authenticated){
843 $this->disconnect(
"Not authenticated", KnownTranslationFactory::disconnectionScreen_notAuthenticated());
846 if($this->info instanceof XboxLivePlayerInfo){
847 $this->logger->warning(
"Discarding unexpected XUID for non-authenticated player");
848 $this->info = $this->info->withoutXboxData();
851 $this->logger->debug(
"Xbox Live authenticated: " . ($this->authenticated ?
"YES" :
"NO"));
853 $checkXUID = $this->
server->getConfigGroup()->getPropertyBool(YmlServerProperties::PLAYER_VERIFY_XUID,
true);
854 $myXUID = $this->info instanceof XboxLivePlayerInfo ? $this->info->getXuid() :
"";
855 $kickForXUIDMismatch =
function(
string $xuid) use ($checkXUID, $myXUID) : bool{
856 if($checkXUID && $myXUID !== $xuid){
857 $this->logger->debug(
"XUID mismatch: expected '$xuid', but got '$myXUID'");
862 $this->disconnect(
"XUID does not match (possible impersonation attempt)");
868 foreach($this->manager->getSessions() as $existingSession){
869 if($existingSession === $this){
872 $info = $existingSession->getPlayerInfo();
873 if($info !==
null && (strcasecmp($info->getUsername(), $this->info->getUsername()) === 0 || $info->getUuid()->equals($this->info->getUuid()))){
874 if($kickForXUIDMismatch($info instanceof XboxLivePlayerInfo ? $info->getXuid() :
"")){
877 $ev =
new PlayerDuplicateLoginEvent($this, $existingSession, KnownTranslationFactory::disconnectionScreen_loggedinOtherLocation(),
null);
879 if($ev->isCancelled()){
880 $this->disconnect($ev->getDisconnectReason(), $ev->getDisconnectScreenMessage());
884 $existingSession->disconnect($ev->getDisconnectReason(), $ev->getDisconnectScreenMessage());
890 $this->cachedOfflinePlayerData = $this->
server->getOfflinePlayerData($this->info->getUsername());
892 $recordedXUID = $this->cachedOfflinePlayerData !==
null ? $this->cachedOfflinePlayerData->getTag(Player::TAG_LAST_KNOWN_XUID) :
null;
893 if(!($recordedXUID instanceof StringTag)){
894 $this->logger->debug(
"No previous XUID recorded, no choice but to trust this player");
895 }elseif(!$kickForXUIDMismatch($recordedXUID->getValue())){
896 $this->logger->debug(
"XUID match");
900 if(EncryptionContext::$ENABLED){
901 $this->
server->getAsyncPool()->submitTask(
new PrepareEncryptionTask($clientPubKey,
function(
string $encryptionKey,
string $handshakeJwt) :
void{
902 if(!$this->connected){
905 $this->sendDataPacket(ServerToClientHandshakePacket::create($handshakeJwt),
true);
907 $this->cipher = EncryptionContext::fakeGCM($encryptionKey);
909 $this->setHandler(
new HandshakePacketHandler($this->onServerLoginSuccess(...)));
910 $this->logger->debug(
"Enabled encryption");
913 $this->onServerLoginSuccess();
917 private function onServerLoginSuccess() : void{
918 $this->loggedIn = true;
920 $this->sendDataPacket(PlayStatusPacket::create(PlayStatusPacket::LOGIN_SUCCESS));
922 $this->logger->debug(
"Initiating resource packs phase");
924 $packManager = $this->
server->getResourcePackManager();
925 $resourcePacks = $packManager->getResourceStack();
927 foreach($resourcePacks as $resourcePack){
928 $key = $packManager->getPackEncryptionKey($resourcePack->getPackId());
930 $keys[$resourcePack->getPackId()] = $key;
933 $event =
new PlayerResourcePackOfferEvent($this->info, $resourcePacks, $keys, $packManager->resourcePacksRequired());
935 $this->setHandler(
new ResourcePacksPacketHandler($this, $event->getResourcePacks(), $event->getEncryptionKeys(), $event->mustAccept(),
function() :
void{
936 $this->createPlayer();
940 private function beginSpawnSequence() : void{
941 $this->setHandler(new PreSpawnPacketHandler($this->
server, $this->player, $this, $this->invManager));
942 $this->player->setNoClientPredictions();
944 $this->logger->debug(
"Waiting for chunk radius request");
947 public function notifyTerrainReady() : void{
948 $this->logger->debug(
"Sending spawn notification, waiting for spawn response");
949 $this->sendDataPacket(PlayStatusPacket::create(PlayStatusPacket::PLAYER_SPAWN));
950 $this->setHandler(
new SpawnResponsePacketHandler($this->onClientSpawnResponse(...)));
953 private function onClientSpawnResponse() : void{
954 $this->logger->debug(
"Received spawn response, entering in-game phase");
955 $this->player->setNoClientPredictions(
false);
956 $this->player->doFirstSpawn();
957 $this->forceAsyncCompression =
false;
958 $this->setHandler(
new InGamePacketHandler($this->player, $this, $this->invManager));
961 public function onServerDeath(Translatable|
string $deathMessage) : void{
962 if($this->handler instanceof InGamePacketHandler){
963 $this->setHandler(
new DeathPacketHandler($this->player, $this, $this->invManager ??
throw new AssumptionFailedError(), $deathMessage));
967 public function onServerRespawn() : void{
968 $this->entityEventBroadcaster->syncAttributes([$this], $this->player, $this->player->getAttributeMap()->getAll());
969 $this->player->sendData(
null);
971 $this->syncAbilities($this->player);
972 $this->invManager->syncAll();
973 $this->setHandler(
new InGamePacketHandler($this->player, $this, $this->invManager));
976 public function syncMovement(Vector3 $pos, ?
float $yaw =
null, ?
float $pitch =
null,
int $mode = MovePlayerPacket::MODE_NORMAL) : void{
977 if($this->player !== null){
978 $location = $this->player->getLocation();
979 $yaw = $yaw ?? $location->getYaw();
980 $pitch = $pitch ?? $location->getPitch();
982 $this->sendDataPacket(MovePlayerPacket::simple(
983 $this->player->getId(),
984 $this->player->getOffsetPosition($pos),
989 $this->player->onGround,
994 if($this->handler instanceof InGamePacketHandler){
995 $this->handler->forceMoveSync =
true;
1000 public function syncViewAreaRadius(
int $distance) : void{
1001 $this->sendDataPacket(ChunkRadiusUpdatedPacket::create($distance));
1004 public function syncViewAreaCenterPoint(Vector3 $newPos,
int $viewDistance) : void{
1005 $this->sendDataPacket(NetworkChunkPublisherUpdatePacket::create(BlockPosition::fromVector3($newPos), $viewDistance * 16, []));
1008 public function syncPlayerSpawnPoint(Position $newSpawn) : void{
1009 $newSpawnBlockPosition = BlockPosition::fromVector3($newSpawn);
1011 $this->sendDataPacket(SetSpawnPositionPacket::playerSpawn($newSpawnBlockPosition, DimensionIds::OVERWORLD, $newSpawnBlockPosition));
1014 public function syncWorldSpawnPoint(Position $newSpawn) : void{
1015 $this->sendDataPacket(SetSpawnPositionPacket::worldSpawn(BlockPosition::fromVector3($newSpawn), DimensionIds::OVERWORLD));
1018 public function syncGameMode(GameMode $mode,
bool $isRollback =
false) : void{
1019 $this->sendDataPacket(SetPlayerGameTypePacket::create($this->typeConverter->coreGameModeToProtocol($mode)));
1020 if($this->player !==
null){
1021 $this->syncAbilities($this->player);
1022 $this->syncAdventureSettings();
1024 if(!$isRollback && $this->invManager !==
null){
1025 $this->invManager->syncCreative();
1029 public function syncAbilities(Player $for) : void{
1030 $isOp = $for->hasPermission(DefaultPermissions::ROOT_OPERATOR);
1034 AbilitiesLayer::ABILITY_ALLOW_FLIGHT => $for->getAllowFlight(),
1035 AbilitiesLayer::ABILITY_FLYING => $for->isFlying(),
1036 AbilitiesLayer::ABILITY_NO_CLIP => !$for->hasBlockCollision(),
1037 AbilitiesLayer::ABILITY_OPERATOR => $isOp,
1038 AbilitiesLayer::ABILITY_TELEPORT => $for->hasPermission(DefaultPermissionNames::COMMAND_TELEPORT_SELF),
1039 AbilitiesLayer::ABILITY_INVULNERABLE => $for->isCreative(),
1040 AbilitiesLayer::ABILITY_MUTED =>
false,
1041 AbilitiesLayer::ABILITY_WORLD_BUILDER =>
false,
1042 AbilitiesLayer::ABILITY_INFINITE_RESOURCES => !$for->hasFiniteResources(),
1043 AbilitiesLayer::ABILITY_LIGHTNING =>
false,
1044 AbilitiesLayer::ABILITY_BUILD => !$for->isSpectator(),
1045 AbilitiesLayer::ABILITY_MINE => !$for->isSpectator(),
1046 AbilitiesLayer::ABILITY_DOORS_AND_SWITCHES => !$for->isSpectator(),
1047 AbilitiesLayer::ABILITY_OPEN_CONTAINERS => !$for->isSpectator(),
1048 AbilitiesLayer::ABILITY_ATTACK_PLAYERS => !$for->isSpectator(),
1049 AbilitiesLayer::ABILITY_ATTACK_MOBS => !$for->isSpectator(),
1050 AbilitiesLayer::ABILITY_PRIVILEGED_BUILDER =>
false,
1054 new AbilitiesLayer(AbilitiesLayer::LAYER_BASE, $boolAbilities, $for->getFlightSpeedMultiplier(), 1, 0.1),
1056 if(!$for->hasBlockCollision()){
1062 $layers[] = new AbilitiesLayer(AbilitiesLayer::LAYER_SPECTATOR, [
1063 AbilitiesLayer::ABILITY_FLYING => true,
1064 ], null, null, null);
1067 $this->sendDataPacket(UpdateAbilitiesPacket::create(
new AbilitiesData(
1068 $isOp ? CommandPermissions::OPERATOR : CommandPermissions::NORMAL,
1069 $isOp ? PlayerPermissions::OPERATOR : PlayerPermissions::MEMBER,
1075 public function syncAdventureSettings() : void{
1076 if($this->player === null){
1077 throw new \LogicException(
"Cannot sync adventure settings for a player that is not yet created");
1080 $this->sendDataPacket(UpdateAdventureSettingsPacket::create(
1081 noAttackingMobs:
false,
1082 noAttackingPlayers:
false,
1083 worldImmutable:
false,
1085 autoJump: $this->player->hasAutoJump()
1089 public function syncAvailableCommands() : void{
1091 foreach($this->
server->getCommandMap()->getCommands() as $command){
1092 if(isset($commandData[$command->getLabel()]) || $command->getLabel() ===
"help" || !$command->testPermissionSilent($this->player)){
1096 $lname = strtolower($command->getLabel());
1097 $aliases = $command->getAliases();
1099 if(count($aliases) > 0){
1100 if(!in_array($lname, $aliases,
true)){
1102 $aliases[] = $lname;
1104 $aliasObj =
new CommandEnum(ucfirst($command->getLabel()) .
"Aliases", $aliases);
1107 $description = $command->getDescription();
1108 $data =
new CommandData(
1110 $description instanceof Translatable ? $this->player->getLanguage()->translate($description) : $description,
1115 new CommandOverload(chaining:
false, parameters: [CommandParameter::standard(
"args", AvailableCommandsPacket::ARG_TYPE_RAWTEXT, 0,
true)])
1117 chainedSubCommandData: []
1120 $commandData[$command->getLabel()] = $data;
1123 $this->sendDataPacket(AvailableCommandsPacket::create($commandData, [], [], []));
1132 $language = $this->player->getLanguage();
1134 return [$language->translateString($message->getText(), $parameters,
"pocketmine."), $parameters];
1137 public function onChatMessage(
Translatable|
string $message) : void{
1139 if(!$this->
server->isLanguageForced()){
1140 $this->sendDataPacket(TextPacket::translation(...$this->prepareClientTranslatableMessage($message)));
1142 $this->sendDataPacket(TextPacket::raw($this->player->getLanguage()->translate($message)));
1145 $this->sendDataPacket(TextPacket::raw($message));
1149 public function onJukeboxPopup(Translatable|
string $message) : void{
1151 if($message instanceof Translatable){
1152 if(!$this->server->isLanguageForced()){
1153 [$message, $parameters] = $this->prepareClientTranslatableMessage($message);
1155 $message = $this->player->getLanguage()->translate($message);
1158 $this->sendDataPacket(TextPacket::jukeboxPopup($message, $parameters));
1161 public function onPopup(
string $message) : void{
1162 $this->sendDataPacket(TextPacket::popup($message));
1165 public function onTip(
string $message) : void{
1166 $this->sendDataPacket(TextPacket::tip($message));
1169 public function onFormSent(
int $id, Form $form) : bool{
1170 return $this->sendDataPacket(ModalFormRequestPacket::create($id, json_encode($form, JSON_THROW_ON_ERROR)));
1173 public function onCloseAllForms() : void{
1174 $this->sendDataPacket(ClientboundCloseFormPacket::create());
1180 private function sendChunkPacket(
string $chunkPacket, \Closure $onCompletion, World $world) : void{
1181 $world->timings->syncChunkSend->startTiming();
1183 $this->queueCompressed($chunkPacket);
1186 $world->timings->syncChunkSend->stopTiming();
1196 $world = $this->player->getLocation()->getWorld();
1197 $promiseOrPacket = ChunkCache::getInstance($world, $this->compressor)->request($chunkX, $chunkZ);
1198 if(is_string($promiseOrPacket)){
1199 $this->sendChunkPacket($promiseOrPacket, $onCompletion, $world);
1202 $promiseOrPacket->onResolve(
1205 if(!$this->isConnected()){
1208 $currentWorld = $this->player->getLocation()->getWorld();
1209 if($world !== $currentWorld || ($status = $this->player->getUsedChunkStatus($chunkX, $chunkZ)) ===
null){
1210 $this->logger->debug(
"Tried to send no-longer-active chunk $chunkX $chunkZ in world " . $world->getFolderName());
1213 if($status !== UsedChunkStatus::REQUESTED_SENDING){
1220 $this->sendChunkPacket($promise->getResult(), $onCompletion, $world);
1225 public function stopUsingChunk(
int $chunkX,
int $chunkZ) : void{
1229 public function onEnterWorld() : void{
1230 if($this->player !== null){
1231 $world = $this->player->getWorld();
1232 $this->syncWorldTime($world->getTime());
1233 $this->syncWorldDifficulty($world->getDifficulty());
1234 $this->syncWorldSpawnPoint($world->getSpawnLocation());
1239 public function syncWorldTime(
int $worldTime) : void{
1240 $this->sendDataPacket(SetTimePacket::create($worldTime));
1243 public function syncWorldDifficulty(
int $worldDifficulty) : void{
1244 $this->sendDataPacket(SetDifficultyPacket::create($worldDifficulty));
1247 public function getInvManager() : ?InventoryManager{
1248 return $this->invManager;
1256 return
PlayerListEntry::createAdditionEntry($player->getUniqueId(), $player->getId(), $player->getDisplayName(), $this->typeConverter->getSkinAdapter()->toSkinData($player->getSkin()), $player->getXuid());
1260 public function onPlayerAdded(
Player $p) : void{
1261 $this->sendDataPacket(PlayerListPacket::add([PlayerListEntry::createAdditionEntry($p->getUniqueId(), $p->getId(), $p->getDisplayName(), $this->typeConverter->getSkinAdapter()->toSkinData($p->getSkin()), $p->getXuid())]));
1264 public function onPlayerRemoved(
Player $p) : void{
1265 if($p !== $this->player){
1266 $this->sendDataPacket(PlayerListPacket::remove([PlayerListEntry::createRemovalEntry($p->
getUniqueId())]));
1270 public function onTitle(
string $title) : void{
1271 $this->sendDataPacket(SetTitlePacket::title($title));
1274 public function onSubTitle(
string $subtitle) : void{
1275 $this->sendDataPacket(SetTitlePacket::subtitle($subtitle));
1278 public function onActionBar(
string $actionBar) : void{
1279 $this->sendDataPacket(SetTitlePacket::actionBarMessage($actionBar));
1282 public function onClearTitle() : void{
1283 $this->sendDataPacket(SetTitlePacket::clearTitle());
1286 public function onResetTitleOptions() : void{
1287 $this->sendDataPacket(SetTitlePacket::resetTitleOptions());
1290 public function onTitleDuration(
int $fadeIn,
int $stay,
int $fadeOut) : void{
1291 $this->sendDataPacket(SetTitlePacket::setAnimationTimes($fadeIn, $stay, $fadeOut));
1294 public function onToastNotification(
string $title,
string $body) : void{
1295 $this->sendDataPacket(ToastRequestPacket::create($title, $body));
1298 public function onOpenSignEditor(Vector3 $signPosition,
bool $frontSide) : void{
1299 $this->sendDataPacket(OpenSignPacket::create(BlockPosition::fromVector3($signPosition), $frontSide));
1302 public function onItemCooldownChanged(Item $item,
int $ticks) : void{
1303 $this->sendDataPacket(PlayerStartItemCooldownPacket::create(
1304 GlobalItemDataHandlers::getSerializer()->serializeType($item)->getName(),
1309 public function tick() : void{
1310 if(!$this->isConnected()){
1315 if($this->info ===
null){
1316 if(time() >= $this->connectTime + 10){
1317 $this->disconnectWithError(KnownTranslationFactory::pocketmine_disconnect_error_loginTimeout());
1323 if($this->player !==
null){
1324 $this->player->doChunkRequests();
1326 $dirtyAttributes = $this->player->getAttributeMap()->needSend();
1327 $this->entityEventBroadcaster->syncAttributes([$this], $this->player, $dirtyAttributes);
1328 foreach($dirtyAttributes as $attribute){
1331 $attribute->markSynchronized();
1334 Timings::$playerNetworkSendInventorySync->startTiming();
1336 $this->invManager?->flushPendingUpdates();
1338 Timings::$playerNetworkSendInventorySync->stopTiming();
1341 $this->flushGamePacketQueue();