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