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