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