22declare(strict_types=1);
24namespace pocketmine\network\mcpe;
100use pocketmine\player\GameMode;
103use pocketmine\player\UsedChunkStatus;
116use
function array_map;
117use
function array_values;
118use
function base64_encode;
121use
function get_class;
123use
function in_array;
124use
function is_string;
125use
function json_encode;
127use
function random_bytes;
128use
function str_split;
129use
function strcasecmp;
131use
function strtolower;
135use
const JSON_THROW_ON_ERROR;
138 private const INCOMING_PACKET_BATCH_PER_TICK = 2;
139 private const INCOMING_PACKET_BATCH_BUFFER_TICKS = 100;
141 private const INCOMING_GAME_PACKETS_PER_TICK = 2;
142 private const INCOMING_GAME_PACKETS_BUFFER_TICKS = 100;
147 private \PrefixedLogger $logger;
148 private ?
Player $player =
null;
150 private ?
int $ping =
null;
154 private bool $connected =
true;
155 private bool $disconnectGuard =
false;
156 private bool $loggedIn =
false;
157 private bool $authenticated =
false;
158 private int $connectTime;
159 private ?
CompoundTag $cachedOfflinePlayerData =
null;
164 private array $sendBuffer = [];
169 private array $sendBufferAckPromises = [];
172 private \SplQueue $compressedQueue;
173 private bool $forceAsyncCompression =
true;
174 private bool $enableCompression =
false;
176 private int $nextAckReceiptId = 0;
181 private array $ackPromisesByReceiptId = [];
191 public function __construct(
203 $this->logger = new \PrefixedLogger($this->
server->getLogger(), $this->getLogPrefix());
205 $this->compressedQueue = new \SplQueue();
209 $this->connectTime = time();
210 $this->packetBatchLimiter =
new PacketRateLimiter(
"Packet Batches", self::INCOMING_PACKET_BATCH_PER_TICK, self::INCOMING_PACKET_BATCH_BUFFER_TICKS);
211 $this->gamePacketLimiter =
new PacketRateLimiter(
"Game Packets", self::INCOMING_GAME_PACKETS_PER_TICK, self::INCOMING_GAME_PACKETS_BUFFER_TICKS);
215 $this->onSessionStartSuccess(...)
218 $this->manager->add($this);
219 $this->logger->info($this->
server->getLanguage()->translate(KnownTranslationFactory::pocketmine_network_session_open()));
222 private function getLogPrefix() :
string{
223 return "NetworkSession: " . $this->getDisplayName();
226 public function getLogger() :
\Logger{
227 return $this->logger;
230 private function onSessionStartSuccess() :
void{
231 $this->logger->debug(
"Session start handshake completed, awaiting login packet");
232 $this->flushSendBuffer(
true);
233 $this->enableCompression =
true;
239 $this->logger->info($this->
server->getLanguage()->translate(KnownTranslationFactory::pocketmine_network_session_playerName(TextFormat::AQUA . $info->getUsername() . TextFormat::RESET)));
240 $this->logger->setPrefix($this->getLogPrefix());
241 $this->manager->markLoginReceived($this);
243 $this->setAuthenticationStatus(...)
247 protected function createPlayer() :
void{
248 $this->
server->createPlayer($this, $this->info, $this->authenticated, $this->cachedOfflinePlayerData)->onCompletion(
249 $this->onPlayerCreated(...),
252 $this->disconnectWithError(
253 reason:
"Failed to create player",
254 disconnectScreenMessage: KnownTranslationFactory::pocketmine_disconnect_error_internal()
260 private function onPlayerCreated(
Player $player) :
void{
261 if(!$this->isConnected()){
265 $this->player = $player;
266 if(!$this->
server->addOnlinePlayer($player)){
272 $effectManager = $this->player->getEffects();
273 $effectManager->getEffectAddHooks()->add($effectAddHook =
function(
EffectInstance $effect,
bool $replacesOldEffect) :
void{
274 $this->entityEventBroadcaster->onEntityEffectAdded([$this], $this->player, $effect, $replacesOldEffect);
276 $effectManager->getEffectRemoveHooks()->add($effectRemoveHook =
function(
EffectInstance $effect) :
void{
277 $this->entityEventBroadcaster->onEntityEffectRemoved([$this], $this->player, $effect);
279 $this->disposeHooks->add(
static function() use ($effectManager, $effectAddHook, $effectRemoveHook) :
void{
280 $effectManager->getEffectAddHooks()->
remove($effectAddHook);
281 $effectManager->getEffectRemoveHooks()->
remove($effectRemoveHook);
284 $permissionHooks = $this->player->getPermissionRecalculationCallbacks();
285 $permissionHooks->add($permHook =
function() :
void{
286 $this->logger->debug(
"Syncing available commands and abilities/permissions due to permission recalculation");
287 $this->syncAbilities($this->player);
288 $this->syncAvailableCommands();
290 $this->disposeHooks->add(
static function() use ($permissionHooks, $permHook) :
void{
291 $permissionHooks->remove($permHook);
293 $this->beginSpawnSequence();
296 public function getPlayer() : ?
Player{
297 return $this->player;
300 public function getPlayerInfo() : ?
PlayerInfo{
304 public function isConnected() :
bool{
305 return $this->connected && !$this->disconnectGuard;
308 public function getIp() :
string{
312 public function getPort() :
int{
316 public function getDisplayName() :
string{
317 return $this->info !==
null ? $this->info->getUsername() : $this->ip .
" " . $this->port;
330 public function updatePing(
int $ping) : void{
334 public function getHandler() : ?PacketHandler{
335 return $this->handler;
338 public function setHandler(?PacketHandler $handler) : void{
339 if($this->connected){
340 $this->handler = $handler;
341 if($this->handler !==
null){
342 $this->handler->setUp();
351 if(!$this->connected){
355 Timings::$playerNetworkReceive->startTiming();
357 $this->packetBatchLimiter->decrement();
359 if($this->cipher !==
null){
360 Timings::$playerNetworkReceiveDecrypt->startTiming();
362 $payload = $this->cipher->decrypt($payload);
363 }
catch(DecryptionException $e){
364 $this->logger->debug(
"Encrypted packet: " . base64_encode($payload));
365 throw PacketHandlingException::wrap($e,
"Packet decryption error");
367 Timings::$playerNetworkReceiveDecrypt->stopTiming();
371 if(strlen($payload) < 1){
372 throw new PacketHandlingException(
"No bytes in payload");
375 if($this->enableCompression){
376 $compressionType = ord($payload[0]);
377 $compressed = substr($payload, 1);
378 if($compressionType === CompressionAlgorithm::NONE){
379 $decompressed = $compressed;
380 }elseif($compressionType === $this->compressor->getNetworkId()){
381 Timings::$playerNetworkReceiveDecompress->startTiming();
383 $decompressed = $this->compressor->decompress($compressed);
384 }
catch(DecompressionException $e){
385 $this->logger->debug(
"Failed to decompress packet: " . base64_encode($compressed));
386 throw PacketHandlingException::wrap($e,
"Compressed packet batch decode error");
388 Timings::$playerNetworkReceiveDecompress->stopTiming();
391 throw new PacketHandlingException(
"Packet compressed with unexpected compression type $compressionType");
394 $decompressed = $payload;
398 $stream =
new BinaryStream($decompressed);
399 foreach(PacketBatch::decodeRaw($stream) as $buffer){
400 $this->gamePacketLimiter->decrement();
401 $packet = $this->packetPool->getPacket($buffer);
402 if($packet ===
null){
403 $this->logger->debug(
"Unknown packet: " . base64_encode($buffer));
404 throw new PacketHandlingException(
"Unknown packet received");
407 $this->handleDataPacket($packet, $buffer);
408 }
catch(PacketHandlingException $e){
409 $this->logger->debug($packet->getName() .
": " . base64_encode($buffer));
410 throw PacketHandlingException::wrap($e,
"Error processing " . $packet->getName());
413 }
catch(PacketDecodeException|BinaryDataException $e){
414 $this->logger->logException($e);
415 throw PacketHandlingException::wrap($e,
"Packet batch decode error");
418 Timings::$playerNetworkReceive->stopTiming();
430 $timings = Timings::getReceiveDataPacketTimings($packet);
431 $timings->startTiming();
434 if(DataPacketDecodeEvent::hasHandlers()){
437 if($ev->isCancelled()){
442 $decodeTimings = Timings::getDecodeDataPacketTimings($packet);
443 $decodeTimings->startTiming();
445 $stream = PacketSerializer::decoder($buffer, 0);
447 $packet->decode($stream);
448 }
catch(PacketDecodeException $e){
449 throw PacketHandlingException::wrap($e);
451 if(!$stream->feof()){
452 $remains = substr($stream->getBuffer(), $stream->getOffset());
453 $this->logger->debug(
"Still " . strlen($remains) .
" bytes unread in " . $packet->getName() .
": " . bin2hex($remains));
456 $decodeTimings->stopTiming();
459 if(DataPacketReceiveEvent::hasHandlers()){
460 $ev =
new DataPacketReceiveEvent($this, $packet);
462 if($ev->isCancelled()){
466 $handlerTimings = Timings::getHandleDataPacketTimings($packet);
467 $handlerTimings->startTiming();
469 if($this->handler ===
null || !$packet->handle($this->handler)){
470 $this->logger->debug(
"Unhandled " . $packet->getName() .
": " . base64_encode($stream->getBuffer()));
473 $handlerTimings->stopTiming();
476 $timings->stopTiming();
480 public function handleAckReceipt(
int $receiptId) : void{
481 if(!$this->connected){
484 if(isset($this->ackPromisesByReceiptId[$receiptId])){
485 $promises = $this->ackPromisesByReceiptId[$receiptId];
486 unset($this->ackPromisesByReceiptId[$receiptId]);
487 foreach($promises as $promise){
488 $promise->resolve(
true);
496 private function sendDataPacketInternal(ClientboundPacket $packet,
bool $immediate, ?PromiseResolver $ackReceiptResolver) : bool{
497 if(!$this->connected){
501 if(!$this->loggedIn && !$packet->canBeSentBeforeLogin()){
502 throw new \InvalidArgumentException(
"Attempted to send " . get_class($packet) .
" to " . $this->getDisplayName() .
" too early");
505 $timings = Timings::getSendDataPacketTimings($packet);
506 $timings->startTiming();
508 if(DataPacketSendEvent::hasHandlers()){
509 $ev =
new DataPacketSendEvent([$this], [$packet]);
511 if($ev->isCancelled()){
514 $packets = $ev->getPackets();
516 $packets = [$packet];
519 if($ackReceiptResolver !==
null){
520 $this->sendBufferAckPromises[] = $ackReceiptResolver;
522 foreach($packets as $evPacket){
523 $this->addToSendBuffer(self::encodePacketTimed(PacketSerializer::encoder(), $evPacket));
526 $this->flushSendBuffer(
true);
531 $timings->stopTiming();
535 public function sendDataPacket(ClientboundPacket $packet,
bool $immediate =
false) : bool{
536 return $this->sendDataPacketInternal($packet, $immediate, null);
545 if(!$this->sendDataPacketInternal($packet, $immediate, $resolver)){
549 return $resolver->getPromise();
555 public static function encodePacketTimed(PacketSerializer $serializer, ClientboundPacket $packet) : string{
556 $timings =
Timings::getEncodeDataPacketTimings($packet);
557 $timings->startTiming();
559 $packet->encode($serializer);
560 return $serializer->getBuffer();
562 $timings->stopTiming();
569 public function addToSendBuffer(
string $buffer) : void{
570 $this->sendBuffer[] = $buffer;
573 private function flushSendBuffer(
bool $immediate =
false) : void{
574 if(count($this->sendBuffer) > 0){
575 Timings::$playerNetworkSend->startTiming();
580 }elseif($this->forceAsyncCompression){
584 $stream =
new BinaryStream();
585 PacketBatch::encodeRaw($stream, $this->sendBuffer);
587 if($this->enableCompression){
588 $batch = $this->
server->prepareBatch($stream->getBuffer(), $this->compressor, $syncMode, Timings::$playerNetworkSendCompressSessionBuffer);
590 $batch = $stream->getBuffer();
592 $this->sendBuffer = [];
593 $ackPromises = $this->sendBufferAckPromises;
594 $this->sendBufferAckPromises = [];
595 $this->queueCompressedNoBufferFlush($batch, $immediate, $ackPromises);
597 Timings::$playerNetworkSend->stopTiming();
602 public function getBroadcaster() : PacketBroadcaster{ return $this->broadcaster; }
604 public function getEntityEventBroadcaster() : EntityEventBroadcaster{ return $this->entityEventBroadcaster; }
606 public function getCompressor() : Compressor{
607 return $this->compressor;
610 public function getTypeConverter() : TypeConverter{ return $this->typeConverter; }
612 public function queueCompressed(CompressBatchPromise|
string $payload,
bool $immediate =
false) : void{
613 Timings::$playerNetworkSend->startTiming();
615 $this->flushSendBuffer($immediate);
616 $this->queueCompressedNoBufferFlush($payload, $immediate);
618 Timings::$playerNetworkSend->stopTiming();
627 private function queueCompressedNoBufferFlush(CompressBatchPromise|
string $batch,
bool $immediate =
false, array $ackPromises = []) : void{
628 Timings::$playerNetworkSend->startTiming();
630 if(is_string($batch)){
633 $this->sendEncoded($batch,
true, $ackPromises);
635 $this->compressedQueue->enqueue([$batch, $ackPromises]);
636 $this->flushCompressedQueue();
640 $this->sendEncoded($batch->getResult(),
true, $ackPromises);
642 $this->compressedQueue->enqueue([$batch, $ackPromises]);
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] = $this->compressedQueue->bottom();
660 if(is_string($current)){
661 $this->compressedQueue->dequeue();
662 $this->sendEncoded($current,
false, $ackPromises);
664 }elseif($current->hasResult()){
665 $this->compressedQueue->dequeue();
666 $this->sendEncoded($current->getResult(),
false, $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->flushSendBuffer(
true);
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),
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,
1055 new AbilitiesLayer(AbilitiesLayer::LAYER_BASE, $boolAbilities, 0.05, 0.1),
1057 if(!$for->hasBlockCollision()){
1063 $layers[] =
new AbilitiesLayer(AbilitiesLayer::LAYER_SPECTATOR, [
1064 AbilitiesLayer::ABILITY_FLYING =>
true,
1068 $this->sendDataPacket(UpdateAbilitiesPacket::create(
new AbilitiesData(
1069 $isOp ? CommandPermissions::OPERATOR : CommandPermissions::NORMAL,
1070 $isOp ? PlayerPermissions::OPERATOR : PlayerPermissions::MEMBER,
1076 public function syncAdventureSettings() : void{
1077 if($this->player === null){
1078 throw new \LogicException(
"Cannot sync adventure settings for a player that is not yet created");
1081 $this->sendDataPacket(UpdateAdventureSettingsPacket::create(
1082 noAttackingMobs:
false,
1083 noAttackingPlayers:
false,
1084 worldImmutable:
false,
1086 autoJump: $this->player->hasAutoJump()
1090 public function syncAvailableCommands() : void{
1092 foreach($this->
server->getCommandMap()->getCommands() as $name => $command){
1093 if(isset($commandData[$command->getLabel()]) || $command->getLabel() ===
"help" || !$command->testPermissionSilent($this->player)){
1097 $lname = strtolower($command->getLabel());
1098 $aliases = $command->getAliases();
1100 if(count($aliases) > 0){
1101 if(!in_array($lname, $aliases,
true)){
1103 $aliases[] = $lname;
1105 $aliasObj =
new CommandEnum(ucfirst($command->getLabel()) .
"Aliases", array_values($aliases));
1108 $description = $command->getDescription();
1109 $data =
new CommandData(
1111 $description instanceof Translatable ? $this->player->getLanguage()->translate($description) : $description,
1116 new CommandOverload(chaining:
false, parameters: [CommandParameter::standard(
"args", AvailableCommandsPacket::ARG_TYPE_RAWTEXT, 0,
true)])
1118 chainedSubCommandData: []
1121 $commandData[$command->getLabel()] = $data;
1124 $this->sendDataPacket(AvailableCommandsPacket::create($commandData, [], [], []));
1133 $language = $this->player->getLanguage();
1135 return [$language->translateString($message->getText(), $parameters,
"pocketmine."), $parameters];
1138 public function onChatMessage(
Translatable|
string $message) : void{
1140 if(!$this->
server->isLanguageForced()){
1141 $this->sendDataPacket(TextPacket::translation(...$this->prepareClientTranslatableMessage($message)));
1143 $this->sendDataPacket(TextPacket::raw($this->player->getLanguage()->translate($message)));
1146 $this->sendDataPacket(TextPacket::raw($message));
1150 public function onJukeboxPopup(Translatable|
string $message) : void{
1152 if($message instanceof Translatable){
1153 if(!$this->
server->isLanguageForced()){
1154 [$message, $parameters] = $this->prepareClientTranslatableMessage($message);
1156 $message = $this->player->getLanguage()->translate($message);
1159 $this->sendDataPacket(TextPacket::jukeboxPopup($message, $parameters));
1162 public function onPopup(
string $message) : void{
1163 $this->sendDataPacket(TextPacket::popup($message));
1166 public function onTip(
string $message) : void{
1167 $this->sendDataPacket(TextPacket::tip($message));
1170 public function onFormSent(
int $id, Form $form) : bool{
1171 return $this->sendDataPacket(ModalFormRequestPacket::create($id, json_encode($form, JSON_THROW_ON_ERROR)));
1174 public function onCloseAllForms() : void{
1175 $this->sendDataPacket(ClientboundCloseFormPacket::create());
1184 $world = $this->player->getLocation()->getWorld();
1185 ChunkCache::getInstance($world, $this->compressor)->request($chunkX, $chunkZ)->onResolve(
1189 if(!$this->isConnected()){
1192 $currentWorld = $this->player->getLocation()->getWorld();
1193 if($world !== $currentWorld || ($status = $this->player->getUsedChunkStatus($chunkX, $chunkZ)) ===
null){
1194 $this->logger->debug(
"Tried to send no-longer-active chunk $chunkX $chunkZ in world " . $world->getFolderName());
1197 if($status !== UsedChunkStatus::REQUESTED_SENDING){
1204 $world->timings->syncChunkSend->startTiming();
1206 $this->queueCompressed($promise);
1209 $world->timings->syncChunkSend->stopTiming();
1215 public function stopUsingChunk(
int $chunkX,
int $chunkZ) : void{
1219 public function onEnterWorld() : void{
1220 if($this->player !== null){
1221 $world = $this->player->getWorld();
1222 $this->syncWorldTime($world->getTime());
1223 $this->syncWorldDifficulty($world->getDifficulty());
1224 $this->syncWorldSpawnPoint($world->getSpawnLocation());
1229 public function syncWorldTime(
int $worldTime) : void{
1230 $this->sendDataPacket(SetTimePacket::create($worldTime));
1233 public function syncWorldDifficulty(
int $worldDifficulty) : void{
1234 $this->sendDataPacket(SetDifficultyPacket::create($worldDifficulty));
1237 public function getInvManager() : ?InventoryManager{
1238 return $this->invManager;
1246 return
PlayerListEntry::createAdditionEntry($player->getUniqueId(), $player->getId(), $player->getDisplayName(), $this->typeConverter->getSkinAdapter()->toSkinData($player->getSkin()), $player->getXuid());
1250 public function onPlayerAdded(
Player $p) : void{
1251 $this->sendDataPacket(PlayerListPacket::add([PlayerListEntry::createAdditionEntry($p->getUniqueId(), $p->getId(), $p->getDisplayName(), $this->typeConverter->getSkinAdapter()->toSkinData($p->getSkin()), $p->getXuid())]));
1254 public function onPlayerRemoved(
Player $p) : void{
1255 if($p !== $this->player){
1256 $this->sendDataPacket(PlayerListPacket::remove([PlayerListEntry::createRemovalEntry($p->
getUniqueId())]));
1260 public function onTitle(
string $title) : void{
1261 $this->sendDataPacket(SetTitlePacket::title($title));
1264 public function onSubTitle(
string $subtitle) : void{
1265 $this->sendDataPacket(SetTitlePacket::subtitle($subtitle));
1268 public function onActionBar(
string $actionBar) : void{
1269 $this->sendDataPacket(SetTitlePacket::actionBarMessage($actionBar));
1272 public function onClearTitle() : void{
1273 $this->sendDataPacket(SetTitlePacket::clearTitle());
1276 public function onResetTitleOptions() : void{
1277 $this->sendDataPacket(SetTitlePacket::resetTitleOptions());
1280 public function onTitleDuration(
int $fadeIn,
int $stay,
int $fadeOut) : void{
1281 $this->sendDataPacket(SetTitlePacket::setAnimationTimes($fadeIn, $stay, $fadeOut));
1284 public function onToastNotification(
string $title,
string $body) : void{
1285 $this->sendDataPacket(ToastRequestPacket::create($title, $body));
1288 public function onOpenSignEditor(Vector3 $signPosition,
bool $frontSide) : void{
1289 $this->sendDataPacket(OpenSignPacket::create(BlockPosition::fromVector3($signPosition), $frontSide));
1292 public function tick() : void{
1293 if(!$this->isConnected()){
1298 if($this->info ===
null){
1299 if(time() >= $this->connectTime + 10){
1300 $this->disconnectWithError(KnownTranslationFactory::pocketmine_disconnect_error_loginTimeout());
1306 if($this->player !==
null){
1307 $this->player->doChunkRequests();
1309 $dirtyAttributes = $this->player->getAttributeMap()->needSend();
1310 $this->entityEventBroadcaster->syncAttributes([$this], $this->player, $dirtyAttributes);
1311 foreach($dirtyAttributes as $attribute){
1314 $attribute->markSynchronized();
1317 Timings::$playerNetworkSendInventorySync->startTiming();
1319 $this->invManager?->flushPendingUpdates();
1321 Timings::$playerNetworkSendInventorySync->stopTiming();
1324 $this->flushSendBuffer();
handleDataPacket(Packet $packet, string $buffer)
prepareClientTranslatableMessage(Translatable $message)
onPlayerDestroyed(Translatable|string $reason, Translatable|string $disconnectScreenMessage)
syncPlayerList(array $players)
sendDataPacketWithReceipt(ClientboundPacket $packet, bool $immediate=false)
onClientDisconnect(Translatable|string $reason)
handleEncoded(string $payload)
transfer(string $ip, int $port, Translatable|string|null $reason=null)
disconnect(Translatable|string $reason, Translatable|string|null $disconnectScreenMessage=null, bool $notify=true)
startUsingChunk(int $chunkX, int $chunkZ, \Closure $onCompletion)