PocketMine-MP 5.33.2 git-09cc76ae2b49f1fe3ab0253e6e987fb82bd0a08f
Loading...
Searching...
No Matches
Player.php
1<?php
2
3/*
4 *
5 * ____ _ _ __ __ _ __ __ ____
6 * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
7 * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
8 * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
9 * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
10 *
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU Lesser General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * @author PocketMine Team
17 * @link http://www.pocketmine.net/
18 *
19 *
20 */
21
22declare(strict_types=1);
23
24namespace pocketmine\player;
25
123use pocketmine\permission\PermissibleDelegateTrait;
131use pocketmine\world\ChunkListenerNoOpTrait;
144use Ramsey\Uuid\UuidInterface;
145use function abs;
146use function array_filter;
147use function array_shift;
148use function assert;
149use function count;
150use function explode;
151use function floor;
152use function get_class;
153use function max;
154use function mb_strlen;
155use function microtime;
156use function min;
157use function preg_match;
158use function spl_object_id;
159use function sqrt;
160use function str_starts_with;
161use function strlen;
162use function strtolower;
163use function substr;
164use function trim;
165use const M_PI;
166use const M_SQRT3;
167use const PHP_INT_MAX;
168
172class Player extends Human implements CommandSender, ChunkListener, IPlayer{
173 use PermissibleDelegateTrait;
174
175 private const MOVES_PER_TICK = 2;
176 private const MOVE_BACKLOG_SIZE = 100 * self::MOVES_PER_TICK; //100 ticks backlog (5 seconds)
177
179 private const MAX_CHAT_CHAR_LENGTH = 512;
185 private const MAX_CHAT_BYTE_LENGTH = self::MAX_CHAT_CHAR_LENGTH * 4;
186 private const MAX_REACH_DISTANCE_CREATIVE = 13;
187 private const MAX_REACH_DISTANCE_SURVIVAL = 7;
188 private const MAX_REACH_DISTANCE_ENTITY_INTERACTION = 8;
189
190 public const DEFAULT_FLIGHT_SPEED_MULTIPLIER = 0.05;
191
192 public const TAG_FIRST_PLAYED = "firstPlayed"; //TAG_Long
193 public const TAG_LAST_PLAYED = "lastPlayed"; //TAG_Long
194 private const TAG_GAME_MODE = "playerGameType"; //TAG_Int
195 private const TAG_SPAWN_WORLD = "SpawnLevel"; //TAG_String
196 private const TAG_SPAWN_X = "SpawnX"; //TAG_Int
197 private const TAG_SPAWN_Y = "SpawnY"; //TAG_Int
198 private const TAG_SPAWN_Z = "SpawnZ"; //TAG_Int
199 private const TAG_DEATH_WORLD = "DeathLevel"; //TAG_String
200 private const TAG_DEATH_X = "DeathPositionX"; //TAG_Int
201 private const TAG_DEATH_Y = "DeathPositionY"; //TAG_Int
202 private const TAG_DEATH_Z = "DeathPositionZ"; //TAG_Int
203 public const TAG_LEVEL = "Level"; //TAG_String
204 public const TAG_LAST_KNOWN_XUID = "LastKnownXUID"; //TAG_String
205
209 public static function isValidUserName(?string $name) : bool{
210 if($name === null){
211 return false;
212 }
213
214 $lname = strtolower($name);
215 $len = strlen($name);
216 return $lname !== "rcon" && $lname !== "console" && $len >= 1 && $len <= 16 && preg_match("/[^A-Za-z0-9_ ]/", $name) === 0;
217 }
218
219 protected ?NetworkSession $networkSession;
220
221 public bool $spawned = false;
222
223 protected string $username;
224 protected string $displayName;
225 protected string $xuid = "";
226 protected bool $authenticated;
227 protected PlayerInfo $playerInfo;
228
229 protected ?Inventory $currentWindow = null;
231 protected array $permanentWindows = [];
232 protected PlayerCursorInventory $cursorInventory;
233 protected PlayerCraftingInventory $craftingGrid;
234 protected CreativeInventory $creativeInventory;
235
236 protected int $messageCounter = 2;
237
238 protected int $firstPlayed;
239 protected int $lastPlayed;
240 protected GameMode $gamemode;
241
246 protected array $usedChunks = [];
251 private array $activeChunkGenerationRequests = [];
256 protected array $loadQueue = [];
257 protected int $nextChunkOrderRun = 5;
258
260 private array $tickingChunks = [];
261
262 protected int $viewDistance = -1;
263 protected int $spawnThreshold;
264 protected int $spawnChunkLoadCount = 0;
265 protected int $chunksPerTick;
266 protected ChunkSelector $chunkSelector;
267 protected ChunkLoader $chunkLoader;
268 protected ChunkTicker $chunkTicker;
269
271 protected array $hiddenPlayers = [];
272
273 protected float $moveRateLimit = 10 * self::MOVES_PER_TICK;
274 protected ?float $lastMovementProcess = null;
275
276 protected int $inAirTicks = 0;
277
278 protected float $stepHeight = 0.6;
279
280 protected ?Vector3 $sleeping = null;
281 private ?Position $spawnPosition = null;
282
283 private bool $respawnLocked = false;
284
285 private ?Position $deathPosition = null;
286
287 //TODO: Abilities
288 protected bool $autoJump = true;
289 protected bool $allowFlight = false;
290 protected bool $blockCollision = true;
291 protected bool $flying = false;
292
293 protected float $flightSpeedMultiplier = self::DEFAULT_FLIGHT_SPEED_MULTIPLIER;
294
296 protected ?int $lineHeight = null;
297 protected string $locale = "en_US";
298
299 protected int $startAction = -1;
300
305 protected array $usedItemsCooldown = [];
306
307 private int $lastEmoteTick = 0;
308
309 protected int $formIdCounter = 0;
311 protected array $forms = [];
312
313 protected \Logger $logger;
314
315 protected ?SurvivalBlockBreakHandler $blockBreakHandler = null;
316
317 public function __construct(Server $server, NetworkSession $session, PlayerInfo $playerInfo, bool $authenticated, Location $spawnLocation, ?CompoundTag $namedtag){
318 $username = TextFormat::clean($playerInfo->getUsername());
319 $this->logger = new \PrefixedLogger($server->getLogger(), "Player: $username");
320
321 $this->server = $server;
322 $this->networkSession = $session;
323 $this->playerInfo = $playerInfo;
324 $this->authenticated = $authenticated;
325
326 $this->username = $username;
327 $this->displayName = $this->username;
328 $this->locale = $this->playerInfo->getLocale();
329
330 $this->uuid = $this->playerInfo->getUuid();
331 $this->xuid = $this->playerInfo instanceof XboxLivePlayerInfo ? $this->playerInfo->getXuid() : "";
332
333 $this->creativeInventory = CreativeInventory::getInstance();
334
335 $rootPermissions = [DefaultPermissions::ROOT_USER => true];
336 if($this->server->isOp($this->username)){
337 $rootPermissions[DefaultPermissions::ROOT_OPERATOR] = true;
338 }
339 $this->perm = new PermissibleBase($rootPermissions);
340 $this->chunksPerTick = $this->server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_PER_TICK, 4);
341 $this->spawnThreshold = (int) (($this->server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4) ** 2) * M_PI);
342 $this->chunkSelector = new ChunkSelector();
343
344 $this->chunkLoader = new class implements ChunkLoader{};
345 $this->chunkTicker = new ChunkTicker();
346 $world = $spawnLocation->getWorld();
347 //load the spawn chunk so we can see the terrain
348 $xSpawnChunk = $spawnLocation->getFloorX() >> Chunk::COORD_BIT_SIZE;
349 $zSpawnChunk = $spawnLocation->getFloorZ() >> Chunk::COORD_BIT_SIZE;
350 $world->registerChunkLoader($this->chunkLoader, $xSpawnChunk, $zSpawnChunk, true);
351 $world->registerChunkListener($this, $xSpawnChunk, $zSpawnChunk);
352 $this->usedChunks[World::chunkHash($xSpawnChunk, $zSpawnChunk)] = UsedChunkStatus::NEEDED;
353
354 parent::__construct($spawnLocation, $this->playerInfo->getSkin(), $namedtag);
355 }
356
357 protected function initHumanData(CompoundTag $nbt) : void{
358 $this->setNameTag($this->username);
359 }
360
361 private function callDummyItemHeldEvent() : void{
362 $slot = $this->inventory->getHeldItemIndex();
363
364 $event = new PlayerItemHeldEvent($this, $this->inventory->getItem($slot), $slot);
365 $event->call();
366 //TODO: this event is actually cancellable, but cancelling it here has no meaningful result, so we
367 //just ignore it. We fire this only because the content of the held slot changed, not because the
368 //held slot index changed. We can't prevent that from here, and nor would it be sensible to.
369 }
370
371 protected function initEntity(CompoundTag $nbt) : void{
372 parent::initEntity($nbt);
373 $this->addDefaultWindows();
374
375 $this->inventory->getListeners()->add(new CallbackInventoryListener(
376 function(Inventory $unused, int $slot) : void{
377 if($slot === $this->inventory->getHeldItemIndex()){
378 $this->setUsingItem(false);
379
380 $this->callDummyItemHeldEvent();
381 }
382 },
383 function() : void{
384 $this->setUsingItem(false);
385 $this->callDummyItemHeldEvent();
386 }
387 ));
388
389 $this->firstPlayed = $nbt->getLong(self::TAG_FIRST_PLAYED, $now = (int) (microtime(true) * 1000));
390 $this->lastPlayed = $nbt->getLong(self::TAG_LAST_PLAYED, $now);
391
392 if(!$this->server->getForceGamemode() && ($gameModeTag = $nbt->getTag(self::TAG_GAME_MODE)) instanceof IntTag){
393 $this->internalSetGameMode(GameModeIdMap::getInstance()->fromId($gameModeTag->getValue()) ?? GameMode::SURVIVAL); //TODO: bad hack here to avoid crashes on corrupted data
394 }else{
395 $this->internalSetGameMode($this->server->getGamemode());
396 }
397
398 $this->keepMovement = true;
399
400 $this->setNameTagVisible();
401 $this->setNameTagAlwaysVisible();
402 $this->setCanClimb();
403
404 if(($world = $this->server->getWorldManager()->getWorldByName($nbt->getString(self::TAG_SPAWN_WORLD, ""))) instanceof World){
405 $this->spawnPosition = new Position($nbt->getInt(self::TAG_SPAWN_X), $nbt->getInt(self::TAG_SPAWN_Y), $nbt->getInt(self::TAG_SPAWN_Z), $world);
406 }
407 if(($world = $this->server->getWorldManager()->getWorldByName($nbt->getString(self::TAG_DEATH_WORLD, ""))) instanceof World){
408 $this->deathPosition = new Position($nbt->getInt(self::TAG_DEATH_X), $nbt->getInt(self::TAG_DEATH_Y), $nbt->getInt(self::TAG_DEATH_Z), $world);
409 }
410 }
411
412 public function getLeaveMessage() : Translatable|string{
413 if($this->spawned){
414 return KnownTranslationFactory::multiplayer_player_left($this->getDisplayName())->prefix(TextFormat::YELLOW);
415 }
416
417 return "";
418 }
419
420 public function isAuthenticated() : bool{
421 return $this->authenticated;
422 }
423
428 public function getPlayerInfo() : PlayerInfo{ return $this->playerInfo; }
429
434 public function getXuid() : string{
435 return $this->xuid;
436 }
437
445 public function getUniqueId() : UuidInterface{
446 return parent::getUniqueId();
447 }
448
452 public function getFirstPlayed() : ?int{
453 return $this->firstPlayed;
454 }
455
459 public function getLastPlayed() : ?int{
460 return $this->lastPlayed;
461 }
462
463 public function hasPlayedBefore() : bool{
464 return $this->lastPlayed - $this->firstPlayed > 1; // microtime(true) - microtime(true) may have less than one millisecond difference
465 }
466
476 public function setAllowFlight(bool $value) : void{
477 if($this->allowFlight !== $value){
478 $this->allowFlight = $value;
479 $this->getNetworkSession()->syncAbilities($this);
480 }
481 }
482
489 public function getAllowFlight() : bool{
490 return $this->allowFlight;
491 }
492
501 public function setHasBlockCollision(bool $value) : void{
502 if($this->blockCollision !== $value){
503 $this->blockCollision = $value;
504 $this->getNetworkSession()->syncAbilities($this);
505 }
506 }
507
512 public function hasBlockCollision() : bool{
513 return $this->blockCollision;
514 }
515
516 public function setFlying(bool $value) : void{
517 if($this->flying !== $value){
518 $this->flying = $value;
519 $this->resetFallDistance();
520 $this->getNetworkSession()->syncAbilities($this);
521 }
522 }
523
524 public function isFlying() : bool{
525 return $this->flying;
526 }
527
541 public function setFlightSpeedMultiplier(float $flightSpeedMultiplier) : void{
542 if($this->flightSpeedMultiplier !== $flightSpeedMultiplier){
543 $this->flightSpeedMultiplier = $flightSpeedMultiplier;
544 $this->getNetworkSession()->syncAbilities($this);
545 }
546 }
547
559 public function getFlightSpeedMultiplier() : float{
560 return $this->flightSpeedMultiplier;
561 }
562
563 public function setAutoJump(bool $value) : void{
564 if($this->autoJump !== $value){
565 $this->autoJump = $value;
566 $this->getNetworkSession()->syncAdventureSettings();
567 }
568 }
569
570 public function hasAutoJump() : bool{
571 return $this->autoJump;
572 }
573
574 public function spawnTo(Player $player) : void{
575 if($this->isAlive() && $player->isAlive() && $player->canSee($this) && !$this->isSpectator()){
576 parent::spawnTo($player);
577 }
578 }
579
580 public function getServer() : Server{
581 return $this->server;
582 }
583
584 public function getScreenLineHeight() : int{
585 return $this->lineHeight ?? 7;
586 }
587
588 public function setScreenLineHeight(?int $height) : void{
589 if($height !== null && $height < 1){
590 throw new \InvalidArgumentException("Line height must be at least 1");
591 }
592 $this->lineHeight = $height;
593 }
594
595 public function canSee(Player $player) : bool{
596 return !isset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
597 }
598
599 public function hidePlayer(Player $player) : void{
600 if($player === $this){
601 return;
602 }
603 $this->hiddenPlayers[$player->getUniqueId()->getBytes()] = true;
604 $player->despawnFrom($this);
605 }
606
607 public function showPlayer(Player $player) : void{
608 if($player === $this){
609 return;
610 }
611 unset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
612 if($player->isOnline()){
613 $player->spawnTo($this);
614 }
615 }
616
617 public function canCollideWith(Entity $entity) : bool{
618 return false;
619 }
620
621 public function canBeCollidedWith() : bool{
622 return !$this->isSpectator() && parent::canBeCollidedWith();
623 }
624
625 public function resetFallDistance() : void{
626 parent::resetFallDistance();
627 $this->inAirTicks = 0;
628 }
629
630 public function getViewDistance() : int{
631 return $this->viewDistance;
632 }
633
634 public function setViewDistance(int $distance) : void{
635 $newViewDistance = $this->server->getAllowedViewDistance($distance);
636
637 if($newViewDistance !== $this->viewDistance){
638 $ev = new PlayerViewDistanceChangeEvent($this, $this->viewDistance, $newViewDistance);
639 $ev->call();
640 }
641
642 $this->viewDistance = $newViewDistance;
643
644 $this->spawnThreshold = (int) (min($this->viewDistance, $this->server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4)) ** 2 * M_PI);
645
646 $this->nextChunkOrderRun = 0;
647
648 $this->getNetworkSession()->syncViewAreaRadius($this->viewDistance);
649
650 $this->logger->debug("Setting view distance to " . $this->viewDistance . " (requested " . $distance . ")");
651 }
652
653 public function isOnline() : bool{
654 return $this->isConnected();
655 }
656
657 public function isConnected() : bool{
658 return $this->networkSession !== null && $this->networkSession->isConnected();
659 }
660
661 public function getNetworkSession() : NetworkSession{
662 if($this->networkSession === null){
663 throw new \LogicException("Player is not connected");
664 }
665 return $this->networkSession;
666 }
667
671 public function getName() : string{
672 return $this->username;
673 }
674
678 public function getDisplayName() : string{
679 return $this->displayName;
680 }
681
682 public function setDisplayName(string $name) : void{
683 $ev = new PlayerDisplayNameChangeEvent($this, $this->displayName, $name);
684 $ev->call();
685
686 $this->displayName = $ev->getNewName();
687 }
688
689 public function canBeRenamed() : bool{
690 return false;
691 }
692
696 public function getLocale() : string{
697 return $this->locale;
698 }
699
700 public function getLanguage() : Language{
701 return $this->server->getLanguage();
702 }
703
708 public function changeSkin(Skin $skin, string $newSkinName, string $oldSkinName) : bool{
709 $ev = new PlayerChangeSkinEvent($this, $this->getSkin(), $skin);
710 $ev->call();
711
712 if($ev->isCancelled()){
713 $this->sendSkin([$this]);
714 return true;
715 }
716
717 $this->setSkin($ev->getNewSkin());
718 $this->sendSkin($this->server->getOnlinePlayers());
719 return true;
720 }
721
727 public function sendSkin(?array $targets = null) : void{
728 parent::sendSkin($targets ?? $this->server->getOnlinePlayers());
729 }
730
734 public function isUsingItem() : bool{
735 return $this->startAction > -1;
736 }
737
738 public function setUsingItem(bool $value) : void{
739 $this->startAction = $value ? $this->server->getTick() : -1;
740 $this->networkPropertiesDirty = true;
741 }
742
747 public function getItemUseDuration() : int{
748 return $this->startAction === -1 ? -1 : ($this->server->getTick() - $this->startAction);
749 }
750
754 public function getItemCooldownExpiry(Item $item) : int{
755 $this->checkItemCooldowns();
756 return $this->usedItemsCooldown[$item->getCooldownTag() ?? $item->getStateId()] ?? 0;
757 }
758
762 public function hasItemCooldown(Item $item) : bool{
763 $this->checkItemCooldowns();
764 return isset($this->usedItemsCooldown[$item->getCooldownTag() ?? $item->getStateId()]);
765 }
766
770 public function resetItemCooldown(Item $item, ?int $ticks = null) : void{
771 $ticks = $ticks ?? $item->getCooldownTicks();
772 if($ticks > 0){
773 $this->usedItemsCooldown[$item->getCooldownTag() ?? $item->getStateId()] = $this->server->getTick() + $ticks;
774 $this->getNetworkSession()->onItemCooldownChanged($item, $ticks);
775 }
776 }
777
778 protected function checkItemCooldowns() : void{
779 $serverTick = $this->server->getTick();
780 foreach($this->usedItemsCooldown as $itemId => $cooldownUntil){
781 if($cooldownUntil <= $serverTick){
782 unset($this->usedItemsCooldown[$itemId]);
783 }
784 }
785 }
786
787 protected function setPosition(Vector3 $pos) : bool{
788 $oldWorld = $this->location->isValid() ? $this->location->getWorld() : null;
789 if(parent::setPosition($pos)){
790 $newWorld = $this->getWorld();
791 if($oldWorld !== $newWorld){
792 if($oldWorld !== null){
793 foreach($this->usedChunks as $index => $status){
794 World::getXZ($index, $X, $Z);
795 $this->unloadChunk($X, $Z, $oldWorld);
796 }
797 }
798
799 $this->usedChunks = [];
800 $this->loadQueue = [];
801 $this->getNetworkSession()->onEnterWorld();
802 }
803
804 return true;
805 }
806
807 return false;
808 }
809
810 protected function unloadChunk(int $x, int $z, ?World $world = null) : void{
811 $world = $world ?? $this->getWorld();
812 $index = World::chunkHash($x, $z);
813 if(isset($this->usedChunks[$index])){
814 foreach($world->getChunkEntities($x, $z) as $entity){
815 if($entity !== $this){
816 $entity->despawnFrom($this);
817 }
818 }
819 $this->getNetworkSession()->stopUsingChunk($x, $z);
820 unset($this->usedChunks[$index]);
821 unset($this->activeChunkGenerationRequests[$index]);
822 }
823 $world->unregisterChunkLoader($this->chunkLoader, $x, $z);
824 $world->unregisterChunkListener($this, $x, $z);
825 unset($this->loadQueue[$index]);
826 $world->unregisterTickingChunk($this->chunkTicker, $x, $z);
827 unset($this->tickingChunks[$index]);
828 }
829
830 protected function spawnEntitiesOnAllChunks() : void{
831 foreach($this->usedChunks as $chunkHash => $status){
832 if($status === UsedChunkStatus::SENT){
833 World::getXZ($chunkHash, $chunkX, $chunkZ);
834 $this->spawnEntitiesOnChunk($chunkX, $chunkZ);
835 }
836 }
837 }
838
839 protected function spawnEntitiesOnChunk(int $chunkX, int $chunkZ) : void{
840 foreach($this->getWorld()->getChunkEntities($chunkX, $chunkZ) as $entity){
841 if($entity !== $this && !$entity->isFlaggedForDespawn()){
842 $entity->spawnTo($this);
843 }
844 }
845 }
846
851 protected function requestChunks() : void{
852 if(!$this->isConnected()){
853 return;
854 }
855
856 Timings::$playerChunkSend->startTiming();
857
858 $count = 0;
859 $world = $this->getWorld();
860
861 $limit = $this->chunksPerTick - count($this->activeChunkGenerationRequests);
862 foreach($this->loadQueue as $index => $distance){
863 if($count >= $limit){
864 break;
865 }
866
867 $X = null;
868 $Z = null;
869 World::getXZ($index, $X, $Z);
870
871 ++$count;
872
873 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_GENERATION;
874 $this->activeChunkGenerationRequests[$index] = true;
875 unset($this->loadQueue[$index]);
876 $world->registerChunkLoader($this->chunkLoader, $X, $Z, true);
877 $world->registerChunkListener($this, $X, $Z);
878 if(isset($this->tickingChunks[$index])){
879 $world->registerTickingChunk($this->chunkTicker, $X, $Z);
880 }
881
882 $world->requestChunkPopulation($X, $Z, $this->chunkLoader)->onCompletion(
883 function() use ($X, $Z, $index, $world) : void{
884 if(!$this->isConnected() || !isset($this->usedChunks[$index]) || $world !== $this->getWorld()){
885 return;
886 }
887 if($this->usedChunks[$index] !== UsedChunkStatus::REQUESTED_GENERATION){
888 //We may have previously requested this, decided we didn't want it, and then decided we did want
889 //it again, all before the generation request got executed. In that case, the promise would have
890 //multiple callbacks for this player. In that case, only the first one matters.
891 return;
892 }
893 unset($this->activeChunkGenerationRequests[$index]);
894 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_SENDING;
895
896 $this->getNetworkSession()->startUsingChunk($X, $Z, function() use ($X, $Z, $index) : void{
897 $this->usedChunks[$index] = UsedChunkStatus::SENT;
898 if($this->spawnChunkLoadCount === -1){
899 $this->spawnEntitiesOnChunk($X, $Z);
900 }elseif($this->spawnChunkLoadCount++ === $this->spawnThreshold){
901 $this->spawnChunkLoadCount = -1;
902
903 $this->spawnEntitiesOnAllChunks();
904
905 $this->getNetworkSession()->notifyTerrainReady();
906 }
907 (new PlayerPostChunkSendEvent($this, $X, $Z))->call();
908 });
909 },
910 static function() : void{
911 //NOOP: we'll re-request this if it fails anyway
912 }
913 );
914 }
915
916 Timings::$playerChunkSend->stopTiming();
917 }
918
919 private function recheckBroadcastPermissions() : void{
920 foreach([
921 DefaultPermissionNames::BROADCAST_ADMIN => Server::BROADCAST_CHANNEL_ADMINISTRATIVE,
922 DefaultPermissionNames::BROADCAST_USER => Server::BROADCAST_CHANNEL_USERS
923 ] as $permission => $channel){
924 if($this->hasPermission($permission)){
925 $this->server->subscribeToBroadcastChannel($channel, $this);
926 }else{
927 $this->server->unsubscribeFromBroadcastChannel($channel, $this);
928 }
929 }
930 }
931
936 public function doFirstSpawn() : void{
937 if($this->spawned){
938 return;
939 }
940 $this->spawned = true;
941 $this->recheckBroadcastPermissions();
942 $this->getPermissionRecalculationCallbacks()->add(function(array $changedPermissionsOldValues) : void{
943 if(isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_ADMINISTRATIVE]) || isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_USERS])){
944 $this->recheckBroadcastPermissions();
945 }
946 });
947
948 $ev = new PlayerJoinEvent($this,
949 KnownTranslationFactory::multiplayer_player_joined($this->getDisplayName())->prefix(TextFormat::YELLOW)
950 );
951 $ev->call();
952 if($ev->getJoinMessage() !== ""){
953 $this->server->broadcastMessage($ev->getJoinMessage());
954 }
955
956 $this->noDamageTicks = 60;
957
958 $this->spawnToAll();
959
960 if($this->getHealth() <= 0){
961 $this->logger->debug("Quit while dead, forcing respawn");
962 $this->actuallyRespawn();
963 }
964 }
965
973 private function updateTickingChunkRegistrations(array $oldTickingChunks, array $newTickingChunks) : void{
974 $world = $this->getWorld();
975 foreach($oldTickingChunks as $hash => $_){
976 if(!isset($newTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
977 //we are (probably) still using this chunk, but it's no longer within ticking range
978 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
979 $world->unregisterTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
980 }
981 }
982 foreach($newTickingChunks as $hash => $_){
983 if(!isset($oldTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
984 //we were already using this chunk, but it is now within ticking range
985 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
986 $world->registerTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
987 }
988 }
989 }
990
995 protected function orderChunks() : void{
996 if(!$this->isConnected() || $this->viewDistance === -1){
997 return;
998 }
999
1000 Timings::$playerChunkOrder->startTiming();
1001
1002 $newOrder = [];
1003 $tickingChunks = [];
1004 $unloadChunks = $this->usedChunks;
1005
1006 $world = $this->getWorld();
1007 $tickingChunkRadius = $world->getChunkTickRadius();
1008
1009 foreach($this->chunkSelector->selectChunks(
1010 $this->server->getAllowedViewDistance($this->viewDistance),
1011 $this->location->getFloorX() >> Chunk::COORD_BIT_SIZE,
1012 $this->location->getFloorZ() >> Chunk::COORD_BIT_SIZE
1013 ) as $radius => $hash){
1014 if(!isset($this->usedChunks[$hash]) || $this->usedChunks[$hash] === UsedChunkStatus::NEEDED){
1015 $newOrder[$hash] = true;
1016 }
1017 if($radius < $tickingChunkRadius){
1018 $tickingChunks[$hash] = true;
1019 }
1020 unset($unloadChunks[$hash]);
1021 }
1022
1023 foreach($unloadChunks as $index => $status){
1024 World::getXZ($index, $X, $Z);
1025 $this->unloadChunk($X, $Z);
1026 }
1027
1028 $this->loadQueue = $newOrder;
1029
1030 $this->updateTickingChunkRegistrations($this->tickingChunks, $tickingChunks);
1031 $this->tickingChunks = $tickingChunks;
1032
1033 if(count($this->loadQueue) > 0 || count($unloadChunks) > 0){
1034 $this->getNetworkSession()->syncViewAreaCenterPoint($this->location, $this->viewDistance);
1035 }
1036
1037 Timings::$playerChunkOrder->stopTiming();
1038 }
1039
1044 public function isUsingChunk(int $chunkX, int $chunkZ) : bool{
1045 return isset($this->usedChunks[World::chunkHash($chunkX, $chunkZ)]);
1046 }
1047
1052 public function getUsedChunks() : array{
1053 return $this->usedChunks;
1054 }
1055
1059 public function getUsedChunkStatus(int $chunkX, int $chunkZ) : ?UsedChunkStatus{
1060 return $this->usedChunks[World::chunkHash($chunkX, $chunkZ)] ?? null;
1061 }
1062
1066 public function hasReceivedChunk(int $chunkX, int $chunkZ) : bool{
1067 $status = $this->usedChunks[World::chunkHash($chunkX, $chunkZ)] ?? null;
1068 return $status === UsedChunkStatus::SENT;
1069 }
1070
1074 public function doChunkRequests() : void{
1075 if($this->nextChunkOrderRun !== PHP_INT_MAX && $this->nextChunkOrderRun-- <= 0){
1076 $this->nextChunkOrderRun = PHP_INT_MAX;
1077 $this->orderChunks();
1078 }
1079
1080 if(count($this->loadQueue) > 0){
1081 $this->requestChunks();
1082 }
1083 }
1084
1085 public function getDeathPosition() : ?Position{
1086 if($this->deathPosition !== null && !$this->deathPosition->isValid()){
1087 $this->deathPosition = null;
1088 }
1089 return $this->deathPosition;
1090 }
1091
1095 public function setDeathPosition(?Vector3 $pos) : void{
1096 if($pos !== null){
1097 if($pos instanceof Position && $pos->world !== null){
1098 $world = $pos->world;
1099 }else{
1100 $world = $this->getWorld();
1101 }
1102 $this->deathPosition = new Position($pos->x, $pos->y, $pos->z, $world);
1103 }else{
1104 $this->deathPosition = null;
1105 }
1106 $this->networkPropertiesDirty = true;
1107 }
1108
1112 public function getSpawn(){
1113 if($this->hasValidCustomSpawn()){
1114 return $this->spawnPosition;
1115 }else{
1116 $world = $this->server->getWorldManager()->getDefaultWorld();
1117
1118 return $world->getSpawnLocation();
1119 }
1120 }
1121
1122 public function hasValidCustomSpawn() : bool{
1123 return $this->spawnPosition !== null && $this->spawnPosition->isValid();
1124 }
1125
1132 public function setSpawn(?Vector3 $pos) : void{
1133 if($pos !== null){
1134 if(!($pos instanceof Position)){
1135 $world = $this->getWorld();
1136 }else{
1137 $world = $pos->getWorld();
1138 }
1139 $this->spawnPosition = new Position($pos->x, $pos->y, $pos->z, $world);
1140 }else{
1141 $this->spawnPosition = null;
1142 }
1143 $this->getNetworkSession()->syncPlayerSpawnPoint($this->getSpawn());
1144 }
1145
1146 public function isSleeping() : bool{
1147 return $this->sleeping !== null;
1148 }
1149
1150 public function sleepOn(Vector3 $pos) : bool{
1151 $pos = $pos->floor();
1152 $b = $this->getWorld()->getBlock($pos);
1153
1154 $ev = new PlayerBedEnterEvent($this, $b);
1155 $ev->call();
1156 if($ev->isCancelled()){
1157 return false;
1158 }
1159
1160 if($b instanceof Bed){
1161 $b->setOccupied();
1162 $this->getWorld()->setBlock($pos, $b);
1163 }
1164
1165 $this->sleeping = $pos;
1166 $this->networkPropertiesDirty = true;
1167
1168 $this->setSpawn($pos);
1169
1170 $this->getWorld()->setSleepTicks(60);
1171
1172 return true;
1173 }
1174
1175 public function stopSleep() : void{
1176 if($this->sleeping instanceof Vector3){
1177 $b = $this->getWorld()->getBlock($this->sleeping);
1178 if($b instanceof Bed){
1179 $b->setOccupied(false);
1180 $this->getWorld()->setBlock($this->sleeping, $b);
1181 }
1182 (new PlayerBedLeaveEvent($this, $b))->call();
1183
1184 $this->sleeping = null;
1185 $this->networkPropertiesDirty = true;
1186
1187 $this->getWorld()->setSleepTicks(0);
1188
1189 $this->getNetworkSession()->sendDataPacket(AnimatePacket::create($this->getId(), AnimatePacket::ACTION_STOP_SLEEP));
1190 }
1191 }
1192
1193 public function getGamemode() : GameMode{
1194 return $this->gamemode;
1195 }
1196
1197 protected function internalSetGameMode(GameMode $gameMode) : void{
1198 $this->gamemode = $gameMode;
1199
1200 $this->allowFlight = $this->gamemode === GameMode::CREATIVE;
1201 $this->hungerManager->setEnabled($this->isSurvival());
1202
1203 if($this->isSpectator()){
1204 $this->setFlying(true);
1205 $this->setHasBlockCollision(false);
1206 $this->setSilent();
1207 $this->onGround = false;
1208
1209 //TODO: HACK! this syncs the onground flag with the client so that flying works properly
1210 //this is a yucky hack but we don't have any other options :(
1211 $this->sendPosition($this->location, null, null, MovePlayerPacket::MODE_TELEPORT);
1212 }else{
1213 if($this->isSurvival()){
1214 $this->setFlying(false);
1215 }
1216 $this->setHasBlockCollision(true);
1217 $this->setSilent(false);
1218 $this->checkGroundState(0, 0, 0, 0, 0, 0);
1219 }
1220 }
1221
1225 public function setGamemode(GameMode $gm) : bool{
1226 if($this->gamemode === $gm){
1227 return false;
1228 }
1229
1230 $ev = new PlayerGameModeChangeEvent($this, $gm);
1231 $ev->call();
1232 if($ev->isCancelled()){
1233 return false;
1234 }
1235
1236 $this->internalSetGameMode($gm);
1237
1238 if($this->isSpectator()){
1239 $this->despawnFromAll();
1240 }else{
1241 $this->spawnToAll();
1242 }
1243
1244 $this->getNetworkSession()->syncGameMode($this->gamemode);
1245 return true;
1246 }
1247
1254 public function isSurvival(bool $literal = false) : bool{
1255 return $this->gamemode === GameMode::SURVIVAL || (!$literal && $this->gamemode === GameMode::ADVENTURE);
1256 }
1257
1264 public function isCreative(bool $literal = false) : bool{
1265 return $this->gamemode === GameMode::CREATIVE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1266 }
1267
1274 public function isAdventure(bool $literal = false) : bool{
1275 return $this->gamemode === GameMode::ADVENTURE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1276 }
1277
1278 public function isSpectator() : bool{
1279 return $this->gamemode === GameMode::SPECTATOR;
1280 }
1281
1285 public function hasFiniteResources() : bool{
1286 return $this->gamemode !== GameMode::CREATIVE;
1287 }
1288
1289 public function getDrops() : array{
1290 if($this->hasFiniteResources()){
1291 return parent::getDrops();
1292 }
1293
1294 return [];
1295 }
1296
1297 public function getXpDropAmount() : int{
1298 if($this->hasFiniteResources()){
1299 return parent::getXpDropAmount();
1300 }
1301
1302 return 0;
1303 }
1304
1305 protected function checkGroundState(float $wantedX, float $wantedY, float $wantedZ, float $dx, float $dy, float $dz) : void{
1306 if($this->gamemode === GameMode::SPECTATOR){
1307 $this->onGround = false;
1308 }else{
1309 $bb = clone $this->boundingBox;
1310 $bb->minY = $this->location->y - 0.2;
1311 $bb->maxY = $this->location->y + 0.2;
1312
1313 //we're already at the new position at this point; check if there are blocks we might have landed on between
1314 //the old and new positions (running down stairs necessitates this)
1315 $bb = $bb->addCoord(-$dx, -$dy, -$dz);
1316
1317 $this->onGround = $this->isCollided = count($this->getWorld()->getCollisionBlocks($bb, true)) > 0;
1318 }
1319 }
1320
1321 public function canBeMovedByCurrents() : bool{
1322 return false; //currently has no server-side movement
1323 }
1324
1325 protected function checkNearEntities() : void{
1326 foreach($this->getWorld()->getNearbyEntities($this->boundingBox->expandedCopy(1, 0.5, 1), $this) as $entity){
1327 $entity->scheduleUpdate();
1328
1329 if(!$entity->isAlive() || $entity->isFlaggedForDespawn()){
1330 continue;
1331 }
1332
1333 $entity->onCollideWithPlayer($this);
1334 }
1335 }
1336
1337 public function getInAirTicks() : int{
1338 return $this->inAirTicks;
1339 }
1340
1349 public function handleMovement(Vector3 $newPos) : void{
1350 Timings::$playerMove->startTiming();
1351 try{
1352 $this->actuallyHandleMovement($newPos);
1353 }finally{
1354 Timings::$playerMove->stopTiming();
1355 }
1356 }
1357
1358 private function actuallyHandleMovement(Vector3 $newPos) : void{
1359 $this->moveRateLimit--;
1360 if($this->moveRateLimit < 0){
1361 return;
1362 }
1363
1364 $oldPos = $this->location;
1365 $distanceSquared = $newPos->distanceSquared($oldPos);
1366
1367 $revert = false;
1368
1369 if($distanceSquared > 225){ //15 blocks
1370 //TODO: this is probably too big if we process every movement
1371 /* !!! BEWARE YE WHO ENTER HERE !!!
1372 *
1373 * This is NOT an anti-cheat check. It is a safety check.
1374 * Without it hackers can teleport with freedom on their own and cause lots of undesirable behaviour, like
1375 * freezes, lag spikes and memory exhaustion due to sync chunk loading and collision checks across large distances.
1376 * Not only that, but high-latency players can trigger such behaviour innocently.
1377 *
1378 * If you must tamper with this code, be aware that this can cause very nasty results. Do not waste our time
1379 * asking for help if you suffer the consequences of messing with this.
1380 */
1381 $this->logger->debug("Moved too fast (" . sqrt($distanceSquared) . " blocks in 1 movement), reverting movement");
1382 $this->logger->debug("Old position: " . $oldPos->asVector3() . ", new position: " . $newPos);
1383 $revert = true;
1384 }elseif(!$this->getWorld()->isInLoadedTerrain($newPos)){
1385 $revert = true;
1386 $this->nextChunkOrderRun = 0;
1387 }
1388
1389 if(!$revert && $distanceSquared !== 0.0){
1390 $dx = $newPos->x - $oldPos->x;
1391 $dy = $newPos->y - $oldPos->y;
1392 $dz = $newPos->z - $oldPos->z;
1393
1394 $this->move($dx, $dy, $dz);
1395 }
1396
1397 if($revert){
1398 $this->revertMovement($oldPos);
1399 }
1400 }
1401
1405 protected function processMostRecentMovements() : void{
1406 $now = microtime(true);
1407 $multiplier = $this->lastMovementProcess !== null ? ($now - $this->lastMovementProcess) * 20 : 1;
1408 $exceededRateLimit = $this->moveRateLimit < 0;
1409 $this->moveRateLimit = min(self::MOVE_BACKLOG_SIZE, max(0, $this->moveRateLimit) + self::MOVES_PER_TICK * $multiplier);
1410 $this->lastMovementProcess = $now;
1411
1412 $from = clone $this->lastLocation;
1413 $to = clone $this->location;
1414
1415 $delta = $to->distanceSquared($from);
1416 $deltaAngle = abs($this->lastLocation->yaw - $to->yaw) + abs($this->lastLocation->pitch - $to->pitch);
1417
1418 if($delta > 0.0001 || $deltaAngle > 1.0){
1419 if(PlayerMoveEvent::hasHandlers()){
1420 $ev = new PlayerMoveEvent($this, $from, $to);
1421
1422 $ev->call();
1423
1424 if($ev->isCancelled()){
1425 $this->revertMovement($from);
1426 return;
1427 }
1428
1429 if($to->distanceSquared($ev->getTo()) > 0.01){ //If plugins modify the destination
1430 $this->teleport($ev->getTo());
1431 return;
1432 }
1433 }
1434
1435 $this->lastLocation = $to;
1436 $this->broadcastMovement();
1437
1438 $horizontalDistanceTravelled = sqrt((($from->x - $to->x) ** 2) + (($from->z - $to->z) ** 2));
1439 if($horizontalDistanceTravelled > 0){
1440 //TODO: check for swimming
1441 if($this->isSprinting()){
1442 $this->hungerManager->exhaust(0.01 * $horizontalDistanceTravelled, PlayerExhaustEvent::CAUSE_SPRINTING);
1443 }else{
1444 $this->hungerManager->exhaust(0.0, PlayerExhaustEvent::CAUSE_WALKING);
1445 }
1446
1447 if($this->nextChunkOrderRun > 20){
1448 $this->nextChunkOrderRun = 20;
1449 }
1450 }
1451 }
1452
1453 if($exceededRateLimit){ //client and server positions will be out of sync if this happens
1454 $this->logger->debug("Exceeded movement rate limit, forcing to last accepted position");
1455 $this->sendPosition($this->location, $this->location->getYaw(), $this->location->getPitch(), MovePlayerPacket::MODE_RESET);
1456 }
1457 }
1458
1459 protected function revertMovement(Location $from) : void{
1460 $this->setPosition($from);
1461 $this->sendPosition($from, $from->yaw, $from->pitch, MovePlayerPacket::MODE_RESET);
1462 }
1463
1464 protected function calculateFallDamage(float $fallDistance) : float{
1465 return $this->flying ? 0 : parent::calculateFallDamage($fallDistance);
1466 }
1467
1468 public function jump() : void{
1469 (new PlayerJumpEvent($this))->call();
1470 parent::jump();
1471 }
1472
1473 public function setMotion(Vector3 $motion) : bool{
1474 if(parent::setMotion($motion)){
1475 $this->broadcastMotion();
1476 $this->getNetworkSession()->sendDataPacket(SetActorMotionPacket::create($this->id, $motion, tick: 0));
1477
1478 return true;
1479 }
1480 return false;
1481 }
1482
1483 protected function updateMovement(bool $teleport = false) : void{
1484
1485 }
1486
1487 protected function tryChangeMovement() : void{
1488
1489 }
1490
1491 public function onUpdate(int $currentTick) : bool{
1492 $tickDiff = $currentTick - $this->lastUpdate;
1493
1494 if($tickDiff <= 0){
1495 return true;
1496 }
1497
1498 $this->messageCounter = 2;
1499
1500 $this->lastUpdate = $currentTick;
1501
1502 if($this->justCreated){
1503 $this->onFirstUpdate($currentTick);
1504 }
1505
1506 if(!$this->isAlive() && $this->spawned){
1507 $this->onDeathUpdate($tickDiff);
1508 return true;
1509 }
1510
1511 $this->timings->startTiming();
1512
1513 if($this->spawned){
1514 Timings::$playerMove->startTiming();
1515 $this->processMostRecentMovements();
1516 $this->motion = Vector3::zero(); //TODO: HACK! (Fixes player knockback being messed up)
1517 if($this->onGround){
1518 $this->inAirTicks = 0;
1519 }else{
1520 $this->inAirTicks += $tickDiff;
1521 }
1522 Timings::$playerMove->stopTiming();
1523
1524 Timings::$entityBaseTick->startTiming();
1525 $this->entityBaseTick($tickDiff);
1526 Timings::$entityBaseTick->stopTiming();
1527
1528 if($this->isCreative() && $this->fireTicks > 1){
1529 $this->fireTicks = 1;
1530 }
1531
1532 if(!$this->isSpectator() && $this->isAlive()){
1533 Timings::$playerCheckNearEntities->startTiming();
1534 $this->checkNearEntities();
1535 Timings::$playerCheckNearEntities->stopTiming();
1536 }
1537
1538 if($this->blockBreakHandler !== null && !$this->blockBreakHandler->update()){
1539 $this->blockBreakHandler = null;
1540 }
1541 }
1542
1543 $this->timings->stopTiming();
1544
1545 return true;
1546 }
1547
1548 public function canEat() : bool{
1549 return $this->isCreative() || parent::canEat();
1550 }
1551
1552 public function canBreathe() : bool{
1553 return $this->isCreative() || parent::canBreathe();
1554 }
1555
1561 public function canInteract(Vector3 $pos, float $maxDistance, float $maxDiff = M_SQRT3 / 2) : bool{
1562 $eyePos = $this->getEyePos();
1563 if($eyePos->distanceSquared($pos) > $maxDistance ** 2){
1564 return false;
1565 }
1566
1567 $dV = $this->getDirectionVector();
1568 $eyeDot = $dV->dot($eyePos);
1569 $targetDot = $dV->dot($pos);
1570 return ($targetDot - $eyeDot) >= -$maxDiff;
1571 }
1572
1577 public function chat(string $message) : bool{
1578 $this->removeCurrentWindow();
1579
1580 if($this->messageCounter <= 0){
1581 //the check below would take care of this (0 * (maxlen + 1) = 0), but it's better be explicit
1582 return false;
1583 }
1584
1585 //Fast length check, to make sure we don't get hung trying to explode MBs of string ...
1586 $maxTotalLength = $this->messageCounter * (self::MAX_CHAT_BYTE_LENGTH + 1);
1587 if(strlen($message) > $maxTotalLength){
1588 return false;
1589 }
1590
1591 $message = TextFormat::clean($message, false);
1592 foreach(explode("\n", $message, $this->messageCounter + 1) as $messagePart){
1593 if(trim($messagePart) !== "" && strlen($messagePart) <= self::MAX_CHAT_BYTE_LENGTH && mb_strlen($messagePart, 'UTF-8') <= self::MAX_CHAT_CHAR_LENGTH && $this->messageCounter-- > 0){
1594 if(str_starts_with($messagePart, './')){
1595 $messagePart = substr($messagePart, 1);
1596 }
1597
1598 if(str_starts_with($messagePart, "/")){
1599 Timings::$playerCommand->startTiming();
1600 $this->server->dispatchCommand($this, substr($messagePart, 1));
1601 Timings::$playerCommand->stopTiming();
1602 }else{
1603 $ev = new PlayerChatEvent($this, $messagePart, $this->server->getBroadcastChannelSubscribers(Server::BROADCAST_CHANNEL_USERS), new StandardChatFormatter());
1604 $ev->call();
1605 if(!$ev->isCancelled()){
1606 $this->server->broadcastMessage($ev->getFormatter()->format($ev->getPlayer()->getDisplayName(), $ev->getMessage()), $ev->getRecipients());
1607 }
1608 }
1609 }
1610 }
1611
1612 return true;
1613 }
1614
1615 public function selectHotbarSlot(int $hotbarSlot) : bool{
1616 if(!$this->inventory->isHotbarSlot($hotbarSlot)){ //TODO: exception here?
1617 return false;
1618 }
1619 if($hotbarSlot === $this->inventory->getHeldItemIndex()){
1620 return true;
1621 }
1622
1623 $ev = new PlayerItemHeldEvent($this, $this->inventory->getItem($hotbarSlot), $hotbarSlot);
1624 $ev->call();
1625 if($ev->isCancelled()){
1626 return false;
1627 }
1628
1629 $this->inventory->setHeldItemIndex($hotbarSlot);
1630 $this->setUsingItem(false);
1631
1632 return true;
1633 }
1634
1638 private function returnItemsFromAction(Item $oldHeldItem, Item $newHeldItem, array $extraReturnedItems) : void{
1639 $heldItemChanged = false;
1640
1641 if(!$newHeldItem->equalsExact($oldHeldItem) && $oldHeldItem->equalsExact($this->inventory->getItemInHand())){
1642 //determine if the item was changed in some meaningful way, or just damaged/changed count
1643 //if it was really changed we always need to set it, whether we have finite resources or not
1644 $newReplica = clone $oldHeldItem;
1645 $newReplica->setCount($newHeldItem->getCount());
1646 if($newReplica instanceof Durable && $newHeldItem instanceof Durable){
1647 $newDamage = $newHeldItem->getDamage();
1648 if($newDamage >= 0 && $newDamage <= $newReplica->getMaxDurability()){
1649 $newReplica->setDamage($newDamage);
1650 }
1651 }
1652 $damagedOrDeducted = $newReplica->equalsExact($newHeldItem);
1653
1654 if(!$damagedOrDeducted || $this->hasFiniteResources()){
1655 if($newHeldItem instanceof Durable && $newHeldItem->isBroken()){
1656 $this->broadcastSound(new ItemBreakSound());
1657 }
1658 $this->inventory->setItemInHand($newHeldItem);
1659 $heldItemChanged = true;
1660 }
1661 }
1662
1663 if(!$heldItemChanged){
1664 $newHeldItem = $oldHeldItem;
1665 }
1666
1667 if($heldItemChanged && count($extraReturnedItems) > 0 && $newHeldItem->isNull()){
1668 $this->inventory->setItemInHand(array_shift($extraReturnedItems));
1669 }
1670 foreach($this->inventory->addItem(...$extraReturnedItems) as $drop){
1671 //TODO: we can't generate a transaction for this since the items aren't coming from an inventory :(
1672 $ev = new PlayerDropItemEvent($this, $drop);
1673 if($this->isSpectator()){
1674 $ev->cancel();
1675 }
1676 $ev->call();
1677 if(!$ev->isCancelled()){
1678 $this->dropItem($drop);
1679 }
1680 }
1681 }
1682
1688 public function useHeldItem() : bool{
1689 $directionVector = $this->getDirectionVector();
1690 $item = $this->inventory->getItemInHand();
1691 $oldItem = clone $item;
1692
1693 $ev = new PlayerItemUseEvent($this, $item, $directionVector);
1694 if($this->hasItemCooldown($item) || $this->isSpectator()){
1695 $ev->cancel();
1696 }
1697
1698 $ev->call();
1699
1700 if($ev->isCancelled()){
1701 return false;
1702 }
1703
1704 $returnedItems = [];
1705 $result = $item->onClickAir($this, $directionVector, $returnedItems);
1706 if($result === ItemUseResult::FAIL){
1707 return false;
1708 }
1709
1710 $this->resetItemCooldown($oldItem);
1711 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1712
1713 $this->setUsingItem($item instanceof Releasable && $item->canStartUsingItem($this));
1714
1715 return true;
1716 }
1717
1723 public function consumeHeldItem() : bool{
1724 $slot = $this->inventory->getItemInHand();
1725 if($slot instanceof ConsumableItem){
1726 $oldItem = clone $slot;
1727
1728 $ev = new PlayerItemConsumeEvent($this, $slot);
1729 if($this->hasItemCooldown($slot)){
1730 $ev->cancel();
1731 }
1732 $ev->call();
1733
1734 if($ev->isCancelled() || !$this->consumeObject($slot)){
1735 return false;
1736 }
1737
1738 $this->setUsingItem(false);
1739 $this->resetItemCooldown($oldItem);
1740
1741 $slot->pop();
1742 $this->returnItemsFromAction($oldItem, $slot, [$slot->getResidue()]);
1743
1744 return true;
1745 }
1746
1747 return false;
1748 }
1749
1755 public function releaseHeldItem() : bool{
1756 try{
1757 $item = $this->inventory->getItemInHand();
1758 if(!$this->isUsingItem() || $this->hasItemCooldown($item)){
1759 return false;
1760 }
1761
1762 $oldItem = clone $item;
1763
1764 $returnedItems = [];
1765 $result = $item->onReleaseUsing($this, $returnedItems);
1766 if($result === ItemUseResult::SUCCESS){
1767 $this->resetItemCooldown($oldItem);
1768 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1769 return true;
1770 }
1771
1772 return false;
1773 }finally{
1774 $this->setUsingItem(false);
1775 }
1776 }
1777
1778 public function pickBlock(Vector3 $pos, bool $addTileNBT) : bool{
1779 $block = $this->getWorld()->getBlock($pos);
1780 if($block instanceof UnknownBlock){
1781 return true;
1782 }
1783
1784 $item = $block->getPickedItem($addTileNBT);
1785
1786 $ev = new PlayerBlockPickEvent($this, $block, $item);
1787 $existingSlot = $this->inventory->first($item);
1788 if($existingSlot === -1 && $this->hasFiniteResources()){
1789 $ev->cancel();
1790 }
1791 $ev->call();
1792
1793 if(!$ev->isCancelled()){
1794 $this->equipOrAddPickedItem($existingSlot, $item);
1795 }
1796
1797 return true;
1798 }
1799
1800 public function pickEntity(int $entityId) : bool{
1801 $entity = $this->getWorld()->getEntity($entityId);
1802 if($entity === null){
1803 return true;
1804 }
1805
1806 $item = $entity->getPickedItem();
1807 if($item === null){
1808 return true;
1809 }
1810
1811 $ev = new PlayerEntityPickEvent($this, $entity, $item);
1812 $existingSlot = $this->inventory->first($item);
1813 if($existingSlot === -1 && ($this->hasFiniteResources() || $this->isSpectator())){
1814 $ev->cancel();
1815 }
1816 $ev->call();
1817
1818 if(!$ev->isCancelled()){
1819 $this->equipOrAddPickedItem($existingSlot, $item);
1820 }
1821
1822 return true;
1823 }
1824
1825 private function equipOrAddPickedItem(int $existingSlot, Item $item) : void{
1826 if($existingSlot !== -1){
1827 if($existingSlot < $this->inventory->getHotbarSize()){
1828 $this->inventory->setHeldItemIndex($existingSlot);
1829 }else{
1830 $this->inventory->swap($this->inventory->getHeldItemIndex(), $existingSlot);
1831 }
1832 }else{
1833 $firstEmpty = $this->inventory->firstEmpty();
1834 if($firstEmpty === -1){ //full inventory
1835 $this->inventory->setItemInHand($item);
1836 }elseif($firstEmpty < $this->inventory->getHotbarSize()){
1837 $this->inventory->setItem($firstEmpty, $item);
1838 $this->inventory->setHeldItemIndex($firstEmpty);
1839 }else{
1840 $this->inventory->swap($this->inventory->getHeldItemIndex(), $firstEmpty);
1841 $this->inventory->setItemInHand($item);
1842 }
1843 }
1844 }
1845
1851 public function attackBlock(Vector3 $pos, int $face) : bool{
1852 if($pos->distanceSquared($this->location) > 10000){
1853 return false; //TODO: maybe this should throw an exception instead?
1854 }
1855
1856 $target = $this->getWorld()->getBlock($pos);
1857
1858 $ev = new PlayerInteractEvent($this, $this->inventory->getItemInHand(), $target, null, $face, PlayerInteractEvent::LEFT_CLICK_BLOCK);
1859 if($this->isSpectator()){
1860 $ev->cancel();
1861 }
1862 $ev->call();
1863 if($ev->isCancelled()){
1864 return false;
1865 }
1866 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1867 if($target->onAttack($this->inventory->getItemInHand(), $face, $this)){
1868 return true;
1869 }
1870
1871 $block = $target->getSide($face);
1872 if($block->hasTypeTag(BlockTypeTags::FIRE)){
1873 $this->getWorld()->setBlock($block->getPosition(), VanillaBlocks::AIR());
1874 $this->getWorld()->addSound($block->getPosition()->add(0.5, 0.5, 0.5), new FireExtinguishSound());
1875 return true;
1876 }
1877
1878 if(!$this->isCreative() && !$target->getBreakInfo()->breaksInstantly()){
1879 $this->blockBreakHandler = new SurvivalBlockBreakHandler($this, $pos, $target, $face, 16);
1880 }
1881
1882 return true;
1883 }
1884
1885 public function continueBreakBlock(Vector3 $pos, int $face) : void{
1886 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1887 $this->blockBreakHandler->setTargetedFace($face);
1888 }
1889 }
1890
1891 public function stopBreakBlock(Vector3 $pos) : void{
1892 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1893 $this->blockBreakHandler = null;
1894 }
1895 }
1896
1902 public function breakBlock(Vector3 $pos) : bool{
1903 $this->removeCurrentWindow();
1904
1905 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1906 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1907 $this->stopBreakBlock($pos);
1908 $item = $this->inventory->getItemInHand();
1909 $oldItem = clone $item;
1910 $returnedItems = [];
1911 if($this->getWorld()->useBreakOn($pos, $item, $this, true, $returnedItems)){
1912 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1913 $this->hungerManager->exhaust(0.005, PlayerExhaustEvent::CAUSE_MINING);
1914 return true;
1915 }
1916 }else{
1917 $this->logger->debug("Cancelled block break at $pos due to not currently being interactable");
1918 }
1919
1920 return false;
1921 }
1922
1928 public function interactBlock(Vector3 $pos, int $face, Vector3 $clickOffset) : bool{
1929 $this->setUsingItem(false);
1930
1931 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1932 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1933 $item = $this->inventory->getItemInHand(); //this is a copy of the real item
1934 $oldItem = clone $item;
1935 $returnedItems = [];
1936 if($this->getWorld()->useItemOn($pos, $item, $face, $clickOffset, $this, true, $returnedItems)){
1937 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1938 return true;
1939 }
1940 }else{
1941 $this->logger->debug("Cancelled interaction of block at $pos due to not currently being interactable");
1942 }
1943
1944 return false;
1945 }
1946
1953 public function attackEntity(Entity $entity) : bool{
1954 if(!$entity->isAlive()){
1955 return false;
1956 }
1957 if($entity instanceof ItemEntity || $entity instanceof Arrow){
1958 $this->logger->debug("Attempted to attack non-attackable entity " . get_class($entity));
1959 return false;
1960 }
1961
1962 $heldItem = $this->inventory->getItemInHand();
1963 $oldItem = clone $heldItem;
1964
1965 $ev = new EntityDamageByEntityEvent($this, $entity, EntityDamageEvent::CAUSE_ENTITY_ATTACK, $heldItem->getAttackPoints());
1966 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
1967 $this->logger->debug("Cancelled attack of entity " . $entity->getId() . " due to not currently being interactable");
1968 $ev->cancel();
1969 }elseif($this->isSpectator() || ($entity instanceof Player && !$this->server->getConfigGroup()->getConfigBool(ServerProperties::PVP))){
1970 $ev->cancel();
1971 }
1972
1973 $meleeEnchantmentDamage = 0;
1975 $meleeEnchantments = [];
1976 foreach($heldItem->getEnchantments() as $enchantment){
1977 $type = $enchantment->getType();
1978 if($type instanceof MeleeWeaponEnchantment && $type->isApplicableTo($entity)){
1979 $meleeEnchantmentDamage += $type->getDamageBonus($enchantment->getLevel());
1980 $meleeEnchantments[] = $enchantment;
1981 }
1982 }
1983 $ev->setModifier($meleeEnchantmentDamage, EntityDamageEvent::MODIFIER_WEAPON_ENCHANTMENTS);
1984
1985 if(!$this->isSprinting() && !$this->isFlying() && $this->fallDistance > 0 && !$this->effectManager->has(VanillaEffects::BLINDNESS()) && !$this->isUnderwater()){
1986 $ev->setModifier($ev->getFinalDamage() / 2, EntityDamageEvent::MODIFIER_CRITICAL);
1987 }
1988
1989 $entity->attack($ev);
1990 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1991
1992 $soundPos = $entity->getPosition()->add(0, $entity->size->getHeight() / 2, 0);
1993 if($ev->isCancelled()){
1994 $this->getWorld()->addSound($soundPos, new EntityAttackNoDamageSound());
1995 return false;
1996 }
1997 $this->getWorld()->addSound($soundPos, new EntityAttackSound());
1998
1999 if($ev->getModifier(EntityDamageEvent::MODIFIER_CRITICAL) > 0 && $entity instanceof Living){
2000 $entity->broadcastAnimation(new CriticalHitAnimation($entity));
2001 }
2002
2003 foreach($meleeEnchantments as $enchantment){
2004 $type = $enchantment->getType();
2005 assert($type instanceof MeleeWeaponEnchantment);
2006 $type->onPostAttack($this, $entity, $enchantment->getLevel());
2007 }
2008
2009 if($this->isAlive()){
2010 //reactive damage like thorns might cause us to be killed by attacking another mob, which
2011 //would mean we'd already have dropped the inventory by the time we reached here
2012 $returnedItems = [];
2013 $heldItem->onAttackEntity($entity, $returnedItems);
2014 $this->returnItemsFromAction($oldItem, $heldItem, $returnedItems);
2015
2016 $this->hungerManager->exhaust(0.1, PlayerExhaustEvent::CAUSE_ATTACK);
2017 }
2018
2019 return true;
2020 }
2021
2026 public function missSwing() : void{
2027 $ev = new PlayerMissSwingEvent($this);
2028 $ev->call();
2029 if(!$ev->isCancelled()){
2030 $this->broadcastSound(new EntityAttackNoDamageSound());
2031 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
2032 }
2033 }
2034
2038 public function interactEntity(Entity $entity, Vector3 $clickPos) : bool{
2039 $ev = new PlayerEntityInteractEvent($this, $entity, $clickPos);
2040
2041 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
2042 $this->logger->debug("Cancelled interaction with entity " . $entity->getId() . " due to not currently being interactable");
2043 $ev->cancel();
2044 }
2045
2046 $ev->call();
2047
2048 $item = $this->inventory->getItemInHand();
2049 $oldItem = clone $item;
2050 if(!$ev->isCancelled()){
2051 if($item->onInteractEntity($this, $entity, $clickPos)){
2052 if($this->hasFiniteResources() && !$item->equalsExact($oldItem) && $oldItem->equalsExact($this->inventory->getItemInHand())){
2053 if($item instanceof Durable && $item->isBroken()){
2054 $this->broadcastSound(new ItemBreakSound());
2055 }
2056 $this->inventory->setItemInHand($item);
2057 }
2058 }
2059 return $entity->onInteract($this, $clickPos);
2060 }
2061 return false;
2062 }
2063
2064 public function toggleSprint(bool $sprint) : bool{
2065 if($sprint === $this->sprinting){
2066 return true;
2067 }
2068 $ev = new PlayerToggleSprintEvent($this, $sprint);
2069 $ev->call();
2070 if($ev->isCancelled()){
2071 return false;
2072 }
2073 $this->setSprinting($sprint);
2074 return true;
2075 }
2076
2077 public function toggleSneak(bool $sneak) : bool{
2078 if($sneak === $this->sneaking){
2079 return true;
2080 }
2081 $ev = new PlayerToggleSneakEvent($this, $sneak);
2082 $ev->call();
2083 if($ev->isCancelled()){
2084 return false;
2085 }
2086 $this->setSneaking($sneak);
2087 return true;
2088 }
2089
2090 public function toggleFlight(bool $fly) : bool{
2091 if($fly === $this->flying){
2092 return true;
2093 }
2094 $ev = new PlayerToggleFlightEvent($this, $fly);
2095 if(!$this->allowFlight){
2096 $ev->cancel();
2097 }
2098 $ev->call();
2099 if($ev->isCancelled()){
2100 return false;
2101 }
2102 $this->setFlying($fly);
2103 return true;
2104 }
2105
2106 public function toggleGlide(bool $glide) : bool{
2107 if($glide === $this->gliding){
2108 return true;
2109 }
2110 $ev = new PlayerToggleGlideEvent($this, $glide);
2111 $ev->call();
2112 if($ev->isCancelled()){
2113 return false;
2114 }
2115 $this->setGliding($glide);
2116 return true;
2117 }
2118
2119 public function toggleSwim(bool $swim) : bool{
2120 if($swim === $this->swimming){
2121 return true;
2122 }
2123 $ev = new PlayerToggleSwimEvent($this, $swim);
2124 $ev->call();
2125 if($ev->isCancelled()){
2126 return false;
2127 }
2128 $this->setSwimming($swim);
2129 return true;
2130 }
2131
2132 public function emote(string $emoteId) : void{
2133 $currentTick = $this->server->getTick();
2134 if($currentTick - $this->lastEmoteTick > 5){
2135 $this->lastEmoteTick = $currentTick;
2136 $event = new PlayerEmoteEvent($this, $emoteId);
2137 $event->call();
2138 if(!$event->isCancelled()){
2139 $emoteId = $event->getEmoteId();
2140 parent::emote($emoteId);
2141 }
2142 }
2143 }
2144
2148 public function dropItem(Item $item) : void{
2149 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
2150 $this->getWorld()->dropItem($this->location->add(0, 1.3, 0), $item, $this->getDirectionVector()->multiply(0.4), 40);
2151 }
2152
2160 public function sendTitle(string $title, string $subtitle = "", int $fadeIn = -1, int $stay = -1, int $fadeOut = -1) : void{
2161 $this->setTitleDuration($fadeIn, $stay, $fadeOut);
2162 if($subtitle !== ""){
2163 $this->sendSubTitle($subtitle);
2164 }
2165 $this->getNetworkSession()->onTitle($title);
2166 }
2167
2171 public function sendSubTitle(string $subtitle) : void{
2172 $this->getNetworkSession()->onSubTitle($subtitle);
2173 }
2174
2178 public function sendActionBarMessage(string $message) : void{
2179 $this->getNetworkSession()->onActionBar($message);
2180 }
2181
2185 public function removeTitles() : void{
2186 $this->getNetworkSession()->onClearTitle();
2187 }
2188
2192 public function resetTitles() : void{
2193 $this->getNetworkSession()->onResetTitleOptions();
2194 }
2195
2203 public function setTitleDuration(int $fadeIn, int $stay, int $fadeOut) : void{
2204 if($fadeIn >= 0 && $stay >= 0 && $fadeOut >= 0){
2205 $this->getNetworkSession()->onTitleDuration($fadeIn, $stay, $fadeOut);
2206 }
2207 }
2208
2212 public function sendMessage(Translatable|string $message) : void{
2213 $this->getNetworkSession()->onChatMessage($message);
2214 }
2215
2216 public function sendJukeboxPopup(Translatable|string $message) : void{
2217 $this->getNetworkSession()->onJukeboxPopup($message);
2218 }
2219
2225 public function sendPopup(string $message) : void{
2226 $this->getNetworkSession()->onPopup($message);
2227 }
2228
2229 public function sendTip(string $message) : void{
2230 $this->getNetworkSession()->onTip($message);
2231 }
2232
2236 public function sendToastNotification(string $title, string $body) : void{
2237 $this->getNetworkSession()->onToastNotification($title, $body);
2238 }
2239
2245 public function sendForm(Form $form) : void{
2246 $id = $this->formIdCounter++;
2247 if($this->getNetworkSession()->onFormSent($id, $form)){
2248 $this->forms[$id] = $form;
2249 }
2250 }
2251
2252 public function onFormSubmit(int $formId, mixed $responseData) : bool{
2253 if(!isset($this->forms[$formId])){
2254 $this->logger->debug("Got unexpected response for form $formId");
2255 return false;
2256 }
2257
2258 try{
2259 $this->forms[$formId]->handleResponse($this, $responseData);
2260 }catch(FormValidationException $e){
2261 $this->logger->critical("Failed to validate form " . get_class($this->forms[$formId]) . ": " . $e->getMessage());
2262 $this->logger->logException($e);
2263 }finally{
2264 unset($this->forms[$formId]);
2265 }
2266
2267 return true;
2268 }
2269
2273 public function closeAllForms() : void{
2274 $this->getNetworkSession()->onCloseAllForms();
2275 }
2276
2286 public function transfer(string $address, int $port = 19132, Translatable|string|null $message = null) : bool{
2287 $ev = new PlayerTransferEvent($this, $address, $port, $message ?? KnownTranslationFactory::pocketmine_disconnect_transfer());
2288 $ev->call();
2289 if(!$ev->isCancelled()){
2290 $this->getNetworkSession()->transfer($ev->getAddress(), $ev->getPort(), $ev->getMessage());
2291 return true;
2292 }
2293
2294 return false;
2295 }
2296
2304 public function kick(Translatable|string $reason = "", Translatable|string|null $quitMessage = null, Translatable|string|null $disconnectScreenMessage = null) : bool{
2305 $ev = new PlayerKickEvent($this, $reason, $quitMessage ?? $this->getLeaveMessage(), $disconnectScreenMessage);
2306 $ev->call();
2307 if(!$ev->isCancelled()){
2308 $reason = $ev->getDisconnectReason();
2309 if($reason === ""){
2310 $reason = KnownTranslationFactory::disconnectionScreen_noReason();
2311 }
2312 $disconnectScreenMessage = $ev->getDisconnectScreenMessage() ?? $reason;
2313 if($disconnectScreenMessage === ""){
2314 $disconnectScreenMessage = KnownTranslationFactory::disconnectionScreen_noReason();
2315 }
2316 $this->disconnect($reason, $ev->getQuitMessage(), $disconnectScreenMessage);
2317
2318 return true;
2319 }
2320
2321 return false;
2322 }
2323
2337 public function disconnect(Translatable|string $reason, Translatable|string|null $quitMessage = null, Translatable|string|null $disconnectScreenMessage = null) : void{
2338 if(!$this->isConnected()){
2339 return;
2340 }
2341
2342 $this->getNetworkSession()->onPlayerDestroyed($reason, $disconnectScreenMessage ?? $reason);
2343 $this->onPostDisconnect($reason, $quitMessage);
2344 }
2345
2353 public function onPostDisconnect(Translatable|string $reason, Translatable|string|null $quitMessage) : void{
2354 if($this->isConnected()){
2355 throw new \LogicException("Player is still connected");
2356 }
2357
2358 //prevent the player receiving their own disconnect message
2359 $this->server->unsubscribeFromAllBroadcastChannels($this);
2360
2361 $this->removeCurrentWindow();
2362
2363 $ev = new PlayerQuitEvent($this, $quitMessage ?? $this->getLeaveMessage(), $reason);
2364 $ev->call();
2365 if(($quitMessage = $ev->getQuitMessage()) !== ""){
2366 $this->server->broadcastMessage($quitMessage);
2367 }
2368 $this->save();
2369
2370 $this->spawned = false;
2371
2372 $this->stopSleep();
2373 $this->blockBreakHandler = null;
2374 $this->despawnFromAll();
2375
2376 $this->server->removeOnlinePlayer($this);
2377
2378 foreach($this->server->getOnlinePlayers() as $player){
2379 if(!$player->canSee($this)){
2380 $player->showPlayer($this);
2381 }
2382 }
2383 $this->hiddenPlayers = [];
2384
2385 if($this->location->isValid()){
2386 foreach($this->usedChunks as $index => $status){
2387 World::getXZ($index, $chunkX, $chunkZ);
2388 $this->unloadChunk($chunkX, $chunkZ);
2389 }
2390 }
2391 if(count($this->usedChunks) !== 0){
2392 throw new AssumptionFailedError("Previous loop should have cleared this array");
2393 }
2394 $this->loadQueue = [];
2395
2396 $this->removeCurrentWindow();
2397 $this->removePermanentInventories();
2398
2399 $this->perm->getPermissionRecalculationCallbacks()->clear();
2400
2401 $this->flagForDespawn();
2402 }
2403
2404 protected function onDispose() : void{
2405 $this->disconnect("Player destroyed");
2406 $this->cursorInventory->removeAllViewers();
2407 $this->craftingGrid->removeAllViewers();
2408 parent::onDispose();
2409 }
2410
2411 protected function destroyCycles() : void{
2412 $this->networkSession = null;
2413 unset($this->cursorInventory);
2414 unset($this->craftingGrid);
2415 $this->spawnPosition = null;
2416 $this->deathPosition = null;
2417 $this->blockBreakHandler = null;
2418 parent::destroyCycles();
2419 }
2420
2424 public function __debugInfo() : array{
2425 return [];
2426 }
2427
2428 public function __destruct(){
2429 parent::__destruct();
2430 $this->logger->debug("Destroyed by garbage collector");
2431 }
2432
2433 public function canSaveWithChunk() : bool{
2434 return false;
2435 }
2436
2437 public function setCanSaveWithChunk(bool $value) : void{
2438 throw new \BadMethodCallException("Players can't be saved with chunks");
2439 }
2440
2441 public function getSaveData() : CompoundTag{
2442 $nbt = $this->saveNBT();
2443
2444 $nbt->setString(self::TAG_LAST_KNOWN_XUID, $this->xuid);
2445
2446 if($this->location->isValid()){
2447 $nbt->setString(self::TAG_LEVEL, $this->getWorld()->getFolderName());
2448 }
2449
2450 if($this->hasValidCustomSpawn()){
2451 $spawn = $this->getSpawn();
2452 $nbt->setString(self::TAG_SPAWN_WORLD, $spawn->getWorld()->getFolderName());
2453 $nbt->setInt(self::TAG_SPAWN_X, $spawn->getFloorX());
2454 $nbt->setInt(self::TAG_SPAWN_Y, $spawn->getFloorY());
2455 $nbt->setInt(self::TAG_SPAWN_Z, $spawn->getFloorZ());
2456 }
2457
2458 if($this->deathPosition !== null && $this->deathPosition->isValid()){
2459 $nbt->setString(self::TAG_DEATH_WORLD, $this->deathPosition->getWorld()->getFolderName());
2460 $nbt->setInt(self::TAG_DEATH_X, $this->deathPosition->getFloorX());
2461 $nbt->setInt(self::TAG_DEATH_Y, $this->deathPosition->getFloorY());
2462 $nbt->setInt(self::TAG_DEATH_Z, $this->deathPosition->getFloorZ());
2463 }
2464
2465 $nbt->setInt(self::TAG_GAME_MODE, GameModeIdMap::getInstance()->toId($this->gamemode));
2466 $nbt->setLong(self::TAG_FIRST_PLAYED, $this->firstPlayed);
2467 $nbt->setLong(self::TAG_LAST_PLAYED, (int) floor(microtime(true) * 1000));
2468
2469 return $nbt;
2470 }
2471
2475 public function save() : void{
2476 $this->server->saveOfflinePlayerData($this->username, $this->getSaveData());
2477 }
2478
2479 protected function onDeath() : void{
2480 //Crafting grid must always be evacuated even if keep-inventory is true. This dumps the contents into the
2481 //main inventory and drops the rest on the ground.
2482 $this->removeCurrentWindow();
2483
2484 $this->setDeathPosition($this->getPosition());
2485
2486 $ev = new PlayerDeathEvent($this, $this->getDrops(), $this->getXpDropAmount(), null);
2487 $ev->call();
2488
2489 if(!$ev->getKeepInventory()){
2490 foreach($ev->getDrops() as $item){
2491 $this->getWorld()->dropItem($this->location, $item);
2492 }
2493
2494 $clearInventory = fn(Inventory $inventory) => $inventory->setContents(array_filter($inventory->getContents(), fn(Item $item) => $item->keepOnDeath()));
2495 $this->inventory->setHeldItemIndex(0);
2496 $clearInventory($this->inventory);
2497 $clearInventory($this->armorInventory);
2498 $clearInventory($this->offHandInventory);
2499 }
2500
2501 if(!$ev->getKeepXp()){
2502 $this->getWorld()->dropExperience($this->location, $ev->getXpDropAmount());
2503 $this->xpManager->setXpAndProgress(0, 0.0);
2504 }
2505
2506 if($ev->getDeathMessage() !== ""){
2507 $this->server->broadcastMessage($ev->getDeathMessage());
2508 }
2509
2510 $this->startDeathAnimation();
2511
2512 $this->getNetworkSession()->onServerDeath($ev->getDeathScreenMessage());
2513 }
2514
2515 protected function onDeathUpdate(int $tickDiff) : bool{
2516 parent::onDeathUpdate($tickDiff);
2517 return false; //never flag players for despawn
2518 }
2519
2520 public function respawn() : void{
2521 if($this->server->isHardcore()){
2522 if($this->kick(KnownTranslationFactory::pocketmine_disconnect_ban(KnownTranslationFactory::pocketmine_disconnect_ban_hardcore()))){ //this allows plugins to prevent the ban by cancelling PlayerKickEvent
2523 $this->server->getNameBans()->addBan($this->getName(), "Died in hardcore mode");
2524 }
2525 return;
2526 }
2527
2528 $this->actuallyRespawn();
2529 }
2530
2531 protected function actuallyRespawn() : void{
2532 if($this->respawnLocked){
2533 return;
2534 }
2535 $this->respawnLocked = true;
2536
2537 $this->logger->debug("Waiting for safe respawn position to be located");
2538 $spawn = $this->getSpawn();
2539 $spawn->getWorld()->requestSafeSpawn($spawn)->onCompletion(
2540 function(Position $safeSpawn) : void{
2541 if(!$this->isConnected()){
2542 return;
2543 }
2544 $this->logger->debug("Respawn position located, completing respawn");
2545 $ev = new PlayerRespawnEvent($this, $safeSpawn);
2546 $spawnPosition = $ev->getRespawnPosition();
2547 $spawnBlock = $spawnPosition->getWorld()->getBlock($spawnPosition);
2548 if($spawnBlock instanceof RespawnAnchor){
2549 if($spawnBlock->getCharges() > 0){
2550 $spawnPosition->getWorld()->setBlock($spawnPosition, $spawnBlock->setCharges($spawnBlock->getCharges() - 1));
2551 $spawnPosition->getWorld()->addSound($spawnPosition, new RespawnAnchorDepleteSound());
2552 }else{
2553 $defaultSpawn = $this->server->getWorldManager()->getDefaultWorld()?->getSpawnLocation();
2554 if($defaultSpawn !== null){
2555 $this->setSpawn($defaultSpawn);
2556 $ev->setRespawnPosition($defaultSpawn);
2557 $this->sendMessage(KnownTranslationFactory::tile_respawn_anchor_notValid()->prefix(TextFormat::GRAY));
2558 }
2559 }
2560 }
2561 $ev->call();
2562
2563 $realSpawn = Position::fromObject($ev->getRespawnPosition()->add(0.5, 0, 0.5), $ev->getRespawnPosition()->getWorld());
2564 $this->teleport($realSpawn);
2565
2566 $this->setSprinting(false);
2567 $this->setSneaking(false);
2568 $this->setFlying(false);
2569
2570 $this->extinguish(EntityExtinguishEvent::CAUSE_RESPAWN);
2571 $this->setAirSupplyTicks($this->getMaxAirSupplyTicks());
2572 $this->deadTicks = 0;
2573 $this->noDamageTicks = 60;
2574
2575 $this->effectManager->clear();
2576 $this->setHealth($this->getMaxHealth());
2577
2578 foreach($this->attributeMap->getAll() as $attr){
2579 if($attr->getId() === Attribute::EXPERIENCE || $attr->getId() === Attribute::EXPERIENCE_LEVEL){ //we have already reset both of those if needed when the player died
2580 continue;
2581 }
2582 $attr->resetToDefault();
2583 }
2584
2585 $this->spawnToAll();
2586 $this->scheduleUpdate();
2587
2588 $this->getNetworkSession()->onServerRespawn();
2589 $this->respawnLocked = false;
2590 },
2591 function() : void{
2592 if($this->isConnected()){
2593 $this->getNetworkSession()->disconnectWithError(KnownTranslationFactory::pocketmine_disconnect_error_respawn());
2594 }
2595 }
2596 );
2597 }
2598
2599 protected function applyPostDamageEffects(EntityDamageEvent $source) : void{
2600 parent::applyPostDamageEffects($source);
2601
2602 $this->hungerManager->exhaust(0.1, PlayerExhaustEvent::CAUSE_DAMAGE);
2603 }
2604
2605 public function attack(EntityDamageEvent $source) : void{
2606 if(!$this->isAlive()){
2607 return;
2608 }
2609
2610 if($this->isCreative()
2611 && $source->getCause() !== EntityDamageEvent::CAUSE_SUICIDE
2612 ){
2613 $source->cancel();
2614 }elseif($this->allowFlight && $source->getCause() === EntityDamageEvent::CAUSE_FALL){
2615 $source->cancel();
2616 }
2617
2618 parent::attack($source);
2619 }
2620
2621 protected function syncNetworkData(EntityMetadataCollection $properties) : void{
2622 parent::syncNetworkData($properties);
2623
2624 $properties->setGenericFlag(EntityMetadataFlags::ACTION, $this->startAction > -1);
2625 $properties->setGenericFlag(EntityMetadataFlags::HAS_COLLISION, $this->hasBlockCollision());
2626
2627 $properties->setPlayerFlag(PlayerMetadataFlags::SLEEP, $this->sleeping !== null);
2628 $properties->setBlockPos(EntityMetadataProperties::PLAYER_BED_POSITION, $this->sleeping !== null ? BlockPosition::fromVector3($this->sleeping) : new BlockPosition(0, 0, 0));
2629
2630 if($this->deathPosition !== null && $this->deathPosition->world === $this->location->world){
2631 $properties->setBlockPos(EntityMetadataProperties::PLAYER_DEATH_POSITION, BlockPosition::fromVector3($this->deathPosition));
2632 //TODO: this should be updated when dimensions are implemented
2633 $properties->setInt(EntityMetadataProperties::PLAYER_DEATH_DIMENSION, DimensionIds::OVERWORLD);
2634 $properties->setByte(EntityMetadataProperties::PLAYER_HAS_DIED, 1);
2635 }else{
2636 $properties->setBlockPos(EntityMetadataProperties::PLAYER_DEATH_POSITION, new BlockPosition(0, 0, 0));
2637 $properties->setInt(EntityMetadataProperties::PLAYER_DEATH_DIMENSION, DimensionIds::OVERWORLD);
2638 $properties->setByte(EntityMetadataProperties::PLAYER_HAS_DIED, 0);
2639 }
2640 }
2641
2642 public function sendData(?array $targets, ?array $data = null) : void{
2643 if($targets === null){
2644 $targets = $this->getViewers();
2645 $targets[] = $this;
2646 }
2647 parent::sendData($targets, $data);
2648 }
2649
2650 public function broadcastAnimation(Animation $animation, ?array $targets = null) : void{
2651 if($this->spawned && $targets === null){
2652 $targets = $this->getViewers();
2653 $targets[] = $this;
2654 }
2655 parent::broadcastAnimation($animation, $targets);
2656 }
2657
2658 public function broadcastSound(Sound $sound, ?array $targets = null) : void{
2659 if($this->spawned && $targets === null){
2660 $targets = $this->getViewers();
2661 $targets[] = $this;
2662 }
2663 parent::broadcastSound($sound, $targets);
2664 }
2665
2669 protected function sendPosition(Vector3 $pos, ?float $yaw = null, ?float $pitch = null, int $mode = MovePlayerPacket::MODE_NORMAL) : void{
2670 $this->getNetworkSession()->syncMovement($pos, $yaw, $pitch, $mode);
2671
2672 $this->ySize = 0;
2673 }
2674
2675 public function teleport(Vector3 $pos, ?float $yaw = null, ?float $pitch = null) : bool{
2676 if(parent::teleport($pos, $yaw, $pitch)){
2677
2678 $this->removeCurrentWindow();
2679 $this->stopSleep();
2680
2681 $this->sendPosition($this->location, $this->location->yaw, $this->location->pitch, MovePlayerPacket::MODE_TELEPORT);
2682 $this->broadcastMovement(true);
2683
2684 $this->spawnToAll();
2685
2686 $this->resetFallDistance();
2687 $this->nextChunkOrderRun = 0;
2688 if($this->spawnChunkLoadCount !== -1){
2689 $this->spawnChunkLoadCount = 0;
2690 }
2691 $this->blockBreakHandler = null;
2692
2693 //TODO: workaround for player last pos not getting updated
2694 //Entity::updateMovement() normally handles this, but it's overridden with an empty function in Player
2695 $this->resetLastMovements();
2696
2697 return true;
2698 }
2699
2700 return false;
2701 }
2702
2703 protected function addDefaultWindows() : void{
2704 $this->cursorInventory = new PlayerCursorInventory($this);
2705 $this->craftingGrid = new PlayerCraftingInventory($this);
2706
2707 $this->addPermanentInventories($this->inventory, $this->armorInventory, $this->cursorInventory, $this->offHandInventory, $this->craftingGrid);
2708
2709 //TODO: more windows
2710 }
2711
2712 public function getCursorInventory() : PlayerCursorInventory{
2713 return $this->cursorInventory;
2714 }
2715
2716 public function getCraftingGrid() : CraftingGrid{
2717 return $this->craftingGrid;
2718 }
2719
2725 return $this->creativeInventory;
2726 }
2727
2731 public function setCreativeInventory(CreativeInventory $inventory) : void{
2732 $this->creativeInventory = $inventory;
2733 if($this->spawned && $this->isConnected()){
2734 $this->getNetworkSession()->getInvManager()?->syncCreative();
2735 }
2736 }
2737
2742 private function doCloseInventory() : void{
2743 $inventories = [$this->craftingGrid, $this->cursorInventory];
2744 if($this->currentWindow instanceof TemporaryInventory){
2745 $inventories[] = $this->currentWindow;
2746 }
2747
2748 $builder = new TransactionBuilder();
2749 foreach($inventories as $inventory){
2750 $contents = $inventory->getContents();
2751
2752 if(count($contents) > 0){
2753 $drops = $builder->getInventory($this->inventory)->addItem(...$contents);
2754 foreach($drops as $drop){
2755 $builder->addAction(new DropItemAction($drop));
2756 }
2757
2758 $builder->getInventory($inventory)->clearAll();
2759 }
2760 }
2761
2762 $actions = $builder->generateActions();
2763 if(count($actions) !== 0){
2764 $transaction = new InventoryTransaction($this, $actions);
2765 try{
2766 $transaction->execute();
2767 $this->logger->debug("Successfully evacuated items from temporary inventories");
2768 }catch(TransactionCancelledException){
2769 $this->logger->debug("Plugin cancelled transaction evacuating items from temporary inventories; items will be destroyed");
2770 foreach($inventories as $inventory){
2771 $inventory->clearAll();
2772 }
2773 }catch(TransactionValidationException $e){
2774 throw new AssumptionFailedError("This server-generated transaction should never be invalid", 0, $e);
2775 }
2776 }
2777 }
2778
2782 public function getCurrentWindow() : ?Inventory{
2783 return $this->currentWindow;
2784 }
2785
2789 public function setCurrentWindow(Inventory $inventory) : bool{
2790 if($inventory === $this->currentWindow){
2791 return true;
2792 }
2793 $ev = new InventoryOpenEvent($inventory, $this);
2794 $ev->call();
2795 if($ev->isCancelled()){
2796 return false;
2797 }
2798
2799 $this->removeCurrentWindow();
2800
2801 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) === null){
2802 throw new \InvalidArgumentException("Player cannot open inventories in this state");
2803 }
2804 $this->logger->debug("Opening inventory " . get_class($inventory) . "#" . spl_object_id($inventory));
2805 $inventoryManager->onCurrentWindowChange($inventory);
2806 $inventory->onOpen($this);
2807 $this->currentWindow = $inventory;
2808 return true;
2809 }
2810
2811 public function removeCurrentWindow() : void{
2812 $this->doCloseInventory();
2813 if($this->currentWindow !== null){
2814 $currentWindow = $this->currentWindow;
2815 $this->logger->debug("Closing inventory " . get_class($this->currentWindow) . "#" . spl_object_id($this->currentWindow));
2816 $this->currentWindow->onClose($this);
2817 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) !== null){
2818 $inventoryManager->onCurrentWindowRemove();
2819 }
2820 $this->currentWindow = null;
2821 (new InventoryCloseEvent($currentWindow, $this))->call();
2822 }
2823 }
2824
2825 protected function addPermanentInventories(Inventory ...$inventories) : void{
2826 foreach($inventories as $inventory){
2827 $inventory->onOpen($this);
2828 $this->permanentWindows[spl_object_id($inventory)] = $inventory;
2829 }
2830 }
2831
2832 protected function removePermanentInventories() : void{
2833 foreach($this->permanentWindows as $inventory){
2834 $inventory->onClose($this);
2835 }
2836 $this->permanentWindows = [];
2837 }
2838
2843 public function openSignEditor(Vector3 $position) : void{
2844 $block = $this->getWorld()->getBlock($position);
2845 if($block instanceof BaseSign){
2846 $this->getWorld()->setBlock($position, $block->setEditorEntityRuntimeId($this->getId()));
2847 $this->getNetworkSession()->onOpenSignEditor($position, true);
2848 }else{
2849 throw new \InvalidArgumentException("Block at this position is not a sign");
2850 }
2851 }
2852
2853 use ChunkListenerNoOpTrait {
2854 onChunkChanged as private;
2855 onChunkUnloaded as private;
2856 }
2857
2858 public function onChunkChanged(int $chunkX, int $chunkZ, Chunk $chunk) : void{
2859 $status = $this->usedChunks[$hash = World::chunkHash($chunkX, $chunkZ)] ?? null;
2860 if($status === UsedChunkStatus::SENT){
2861 $this->usedChunks[$hash] = UsedChunkStatus::NEEDED;
2862 $this->nextChunkOrderRun = 0;
2863 }
2864 }
2865
2866 public function onChunkUnloaded(int $chunkX, int $chunkZ, Chunk $chunk) : void{
2867 if($this->isUsingChunk($chunkX, $chunkZ)){
2868 $this->logger->debug("Detected forced unload of chunk " . $chunkX . " " . $chunkZ);
2869 $this->unloadChunk($chunkX, $chunkZ);
2870 }
2871 }
2872}
onInteract(Player $player, Vector3 $clickPos)
Definition Entity.php:1132
setString(string $name, string $value)
setInt(string $name, int $value)
setLong(string $name, int $value)
interactBlock(Vector3 $pos, int $face, Vector3 $clickOffset)
Definition Player.php:1928
setCreativeInventory(CreativeInventory $inventory)
Definition Player.php:2731
hasItemCooldown(Item $item)
Definition Player.php:762
attackBlock(Vector3 $pos, int $face)
Definition Player.php:1851
isUsingChunk(int $chunkX, int $chunkZ)
Definition Player.php:1044
setDeathPosition(?Vector3 $pos)
Definition Player.php:1095
setScreenLineHeight(?int $height)
Definition Player.php:588
setCanSaveWithChunk(bool $value)
Definition Player.php:2437
kick(Translatable|string $reason="", Translatable|string|null $quitMessage=null, Translatable|string|null $disconnectScreenMessage=null)
Definition Player.php:2304
teleport(Vector3 $pos, ?float $yaw=null, ?float $pitch=null)
Definition Player.php:2675
applyPostDamageEffects(EntityDamageEvent $source)
Definition Player.php:2599
setAllowFlight(bool $value)
Definition Player.php:476
initHumanData(CompoundTag $nbt)
Definition Player.php:357
getItemCooldownExpiry(Item $item)
Definition Player.php:754
sendTitle(string $title, string $subtitle="", int $fadeIn=-1, int $stay=-1, int $fadeOut=-1)
Definition Player.php:2160
transfer(string $address, int $port=19132, Translatable|string|null $message=null)
Definition Player.php:2286
setFlightSpeedMultiplier(float $flightSpeedMultiplier)
Definition Player.php:541
changeSkin(Skin $skin, string $newSkinName, string $oldSkinName)
Definition Player.php:708
broadcastAnimation(Animation $animation, ?array $targets=null)
Definition Player.php:2650
sendMessage(Translatable|string $message)
Definition Player.php:2212
hasReceivedChunk(int $chunkX, int $chunkZ)
Definition Player.php:1066
static isValidUserName(?string $name)
Definition Player.php:209
openSignEditor(Vector3 $position)
Definition Player.php:2843
attackEntity(Entity $entity)
Definition Player.php:1953
breakBlock(Vector3 $pos)
Definition Player.php:1902
onDeathUpdate(int $tickDiff)
Definition Player.php:2515
sendToastNotification(string $title, string $body)
Definition Player.php:2236
resetItemCooldown(Item $item, ?int $ticks=null)
Definition Player.php:770
setTitleDuration(int $fadeIn, int $stay, int $fadeOut)
Definition Player.php:2203
sendPosition(Vector3 $pos, ?float $yaw=null, ?float $pitch=null, int $mode=MovePlayerPacket::MODE_NORMAL)
Definition Player.php:2669
setSpawn(?Vector3 $pos)
Definition Player.php:1132
onChunkUnloaded as onChunkChanged(int $chunkX, int $chunkZ, Chunk $chunk)
Definition Player.php:2858
setCurrentWindow(Inventory $inventory)
Definition Player.php:2789
sendData(?array $targets, ?array $data=null)
Definition Player.php:2642
isCreative(bool $literal=false)
Definition Player.php:1264
onChunkUnloaded(int $chunkX, int $chunkZ, Chunk $chunk)
Definition Player.php:2866
chat(string $message)
Definition Player.php:1577
sendActionBarMessage(string $message)
Definition Player.php:2178
sendPopup(string $message)
Definition Player.php:2225
isAdventure(bool $literal=false)
Definition Player.php:1274
canInteract(Vector3 $pos, float $maxDistance, float $maxDiff=M_SQRT3/2)
Definition Player.php:1561
broadcastSound(Sound $sound, ?array $targets=null)
Definition Player.php:2658
getUsedChunkStatus(int $chunkX, int $chunkZ)
Definition Player.php:1059
interactEntity(Entity $entity, Vector3 $clickPos)
Definition Player.php:2038
sendSkin(?array $targets=null)
Definition Player.php:727
isSurvival(bool $literal=false)
Definition Player.php:1254
disconnect(Translatable|string $reason, Translatable|string|null $quitMessage=null, Translatable|string|null $disconnectScreenMessage=null)
Definition Player.php:2337
handleMovement(Vector3 $newPos)
Definition Player.php:1349
setHasBlockCollision(bool $value)
Definition Player.php:501
setGamemode(GameMode $gm)
Definition Player.php:1225
sendSubTitle(string $subtitle)
Definition Player.php:2171