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