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