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