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