22declare(strict_types=1);
24namespace pocketmine\player;
119use pocketmine\permission\PermissibleDelegateTrait;
127use pocketmine\world\ChunkListenerNoOpTrait;
139use Ramsey\Uuid\UuidInterface;
141use
function array_filter;
142use
function array_shift;
147use
function get_class;
150use
function mb_strlen;
151use
function microtime;
153use
function preg_match;
154use
function spl_object_id;
156use
function str_starts_with;
158use
function strtolower;
163use
const PHP_INT_MAX;
169 use PermissibleDelegateTrait;
171 private const MOVES_PER_TICK = 2;
172 private const MOVE_BACKLOG_SIZE = 100 * self::MOVES_PER_TICK;
175 private const MAX_CHAT_CHAR_LENGTH = 512;
181 private const MAX_CHAT_BYTE_LENGTH = self::MAX_CHAT_CHAR_LENGTH * 4;
182 private const MAX_REACH_DISTANCE_CREATIVE = 13;
183 private const MAX_REACH_DISTANCE_SURVIVAL = 7;
184 private const MAX_REACH_DISTANCE_ENTITY_INTERACTION = 8;
186 public const TAG_FIRST_PLAYED =
"firstPlayed";
187 public const TAG_LAST_PLAYED =
"lastPlayed";
188 private const TAG_GAME_MODE =
"playerGameType";
189 private const TAG_SPAWN_WORLD =
"SpawnLevel";
190 private const TAG_SPAWN_X =
"SpawnX";
191 private const TAG_SPAWN_Y =
"SpawnY";
192 private const TAG_SPAWN_Z =
"SpawnZ";
193 public const TAG_LEVEL =
"Level";
194 public const TAG_LAST_KNOWN_XUID =
"LastKnownXUID";
204 $lname = strtolower($name);
205 $len = strlen($name);
206 return $lname !==
"rcon" && $lname !==
"console" && $len >= 1 && $len <= 16 && preg_match(
"/[^A-Za-z0-9_ ]/", $name) === 0;
211 public bool $spawned =
false;
213 protected string $username;
214 protected string $displayName;
215 protected string $xuid =
"";
216 protected bool $authenticated;
219 protected ?Inventory $currentWindow =
null;
221 protected array $permanentWindows = [];
222 protected PlayerCursorInventory $cursorInventory;
223 protected PlayerCraftingInventory $craftingGrid;
224 protected CreativeInventory $creativeInventory;
226 protected int $messageCounter = 2;
228 protected int $firstPlayed;
229 protected int $lastPlayed;
230 protected GameMode $gamemode;
236 protected array $usedChunks = [];
241 private array $activeChunkGenerationRequests = [];
246 protected array $loadQueue = [];
247 protected int $nextChunkOrderRun = 5;
250 private array $tickingChunks = [];
252 protected int $viewDistance = -1;
253 protected int $spawnThreshold;
254 protected int $spawnChunkLoadCount = 0;
255 protected int $chunksPerTick;
256 protected ChunkSelector $chunkSelector;
257 protected ChunkLoader $chunkLoader;
258 protected ChunkTicker $chunkTicker;
261 protected array $hiddenPlayers = [];
263 protected float $moveRateLimit = 10 * self::MOVES_PER_TICK;
264 protected ?
float $lastMovementProcess =
null;
266 protected int $inAirTicks = 0;
268 protected float $stepHeight = 0.6;
270 protected ?Vector3 $sleeping =
null;
271 private ?
Position $spawnPosition =
null;
273 private bool $respawnLocked =
false;
276 protected bool $autoJump =
true;
277 protected bool $allowFlight =
false;
278 protected bool $blockCollision =
true;
279 protected bool $flying =
false;
282 protected ?
int $lineHeight =
null;
283 protected string $locale =
"en_US";
285 protected int $startAction = -1;
287 protected array $usedItemsCooldown = [];
289 private int $lastEmoteTick = 0;
291 protected int $formIdCounter = 0;
293 protected array $forms = [];
295 protected \Logger $logger;
301 $this->logger = new \PrefixedLogger($server->getLogger(),
"Player: $username");
304 $this->networkSession = $session;
305 $this->playerInfo = $playerInfo;
306 $this->authenticated = $authenticated;
308 $this->username = $username;
309 $this->displayName = $this->username;
310 $this->locale = $this->playerInfo->getLocale();
312 $this->uuid = $this->playerInfo->getUuid();
313 $this->xuid = $this->playerInfo instanceof
XboxLivePlayerInfo ? $this->playerInfo->getXuid() :
"";
315 $this->creativeInventory = CreativeInventory::getInstance();
317 $rootPermissions = [DefaultPermissions::ROOT_USER =>
true];
318 if($this->
server->isOp($this->username)){
319 $rootPermissions[DefaultPermissions::ROOT_OPERATOR] =
true;
322 $this->chunksPerTick = $this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_PER_TICK, 4);
323 $this->spawnThreshold = (int) (($this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4) ** 2) * M_PI);
326 $this->chunkLoader =
new class implements
ChunkLoader{};
328 $world = $spawnLocation->
getWorld();
330 $xSpawnChunk = $spawnLocation->getFloorX() >> Chunk::COORD_BIT_SIZE;
331 $zSpawnChunk = $spawnLocation->getFloorZ() >> Chunk::COORD_BIT_SIZE;
332 $world->registerChunkLoader($this->chunkLoader, $xSpawnChunk, $zSpawnChunk,
true);
333 $world->registerChunkListener($this, $xSpawnChunk, $zSpawnChunk);
334 $this->usedChunks[
World::chunkHash($xSpawnChunk, $zSpawnChunk)] = UsedChunkStatus::NEEDED;
336 parent::__construct($spawnLocation, $this->playerInfo->getSkin(), $namedtag);
340 $this->setNameTag($this->username);
343 private function callDummyItemHeldEvent() : void{
344 $slot = $this->inventory->getHeldItemIndex();
353 protected function initEntity(
CompoundTag $nbt) : void{
354 parent::initEntity($nbt);
355 $this->addDefaultWindows();
357 $this->inventory->getListeners()->add(
new CallbackInventoryListener(
358 function(Inventory $unused,
int $slot) :
void{
359 if($slot === $this->inventory->getHeldItemIndex()){
360 $this->setUsingItem(false);
362 $this->callDummyItemHeldEvent();
366 $this->setUsingItem(
false);
367 $this->callDummyItemHeldEvent();
371 $this->firstPlayed = $nbt->getLong(self::TAG_FIRST_PLAYED, $now = (
int) (microtime(
true) * 1000));
372 $this->lastPlayed = $nbt->getLong(self::TAG_LAST_PLAYED, $now);
374 if(!$this->
server->getForceGamemode() && ($gameModeTag = $nbt->
getTag(self::TAG_GAME_MODE)) instanceof IntTag){
375 $this->internalSetGameMode(GameModeIdMap::getInstance()->fromId($gameModeTag->getValue()) ?? GameMode::SURVIVAL);
377 $this->internalSetGameMode($this->
server->getGamemode());
380 $this->keepMovement =
true;
382 $this->setNameTagVisible();
383 $this->setNameTagAlwaysVisible();
384 $this->setCanClimb();
386 if(($world = $this->
server->getWorldManager()->getWorldByName($nbt->getString(self::TAG_SPAWN_WORLD,
""))) instanceof World){
387 $this->spawnPosition =
new Position($nbt->getInt(self::TAG_SPAWN_X), $nbt->getInt(self::TAG_SPAWN_Y), $nbt->getInt(self::TAG_SPAWN_Z), $world);
391 public function getLeaveMessage() : Translatable|string{
393 return KnownTranslationFactory::multiplayer_player_left($this->getDisplayName())->prefix(TextFormat::YELLOW);
399 public function isAuthenticated() : bool{
400 return $this->authenticated;
425 return parent::getUniqueId();
432 return $this->firstPlayed;
439 return $this->lastPlayed;
442 public function hasPlayedBefore() : bool{
443 return $this->lastPlayed - $this->firstPlayed > 1;
456 if($this->allowFlight !== $value){
457 $this->allowFlight = $value;
458 $this->getNetworkSession()->syncAbilities($this);
469 return $this->allowFlight;
481 if($this->blockCollision !== $value){
482 $this->blockCollision = $value;
483 $this->getNetworkSession()->syncAbilities($this);
492 return $this->blockCollision;
495 public function setFlying(
bool $value) : void{
496 if($this->flying !== $value){
497 $this->flying = $value;
498 $this->resetFallDistance();
499 $this->getNetworkSession()->syncAbilities($this);
503 public function isFlying() : bool{
504 return $this->flying;
507 public function setAutoJump(
bool $value) : void{
508 if($this->autoJump !== $value){
509 $this->autoJump = $value;
510 $this->getNetworkSession()->syncAdventureSettings();
514 public function hasAutoJump() : bool{
515 return $this->autoJump;
518 public function spawnTo(Player $player) : void{
519 if($this->isAlive() && $player->isAlive() && $player->canSee($this) && !$this->isSpectator()){
520 parent::spawnTo($player);
524 public function getServer() : Server{
529 return $this->lineHeight ?? 7;
533 if($height !== null && $height < 1){
534 throw new \InvalidArgumentException(
"Line height must be at least 1");
536 $this->lineHeight = $height;
539 public function canSee(
Player $player) : bool{
540 return !isset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
543 public function hidePlayer(Player $player) : void{
544 if($player === $this){
547 $this->hiddenPlayers[$player->getUniqueId()->getBytes()] =
true;
548 $player->despawnFrom($this);
551 public function showPlayer(Player $player) : void{
552 if($player === $this){
555 unset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
556 if($player->isOnline()){
557 $player->spawnTo($this);
561 public function canCollideWith(Entity $entity) : bool{
565 public function canBeCollidedWith() : bool{
566 return !$this->isSpectator() && parent::canBeCollidedWith();
569 public function resetFallDistance() : void{
570 parent::resetFallDistance();
571 $this->inAirTicks = 0;
574 public function getViewDistance() : int{
575 return $this->viewDistance;
578 public function setViewDistance(
int $distance) : void{
579 $newViewDistance = $this->
server->getAllowedViewDistance($distance);
581 if($newViewDistance !== $this->viewDistance){
582 $ev =
new PlayerViewDistanceChangeEvent($this, $this->viewDistance, $newViewDistance);
586 $this->viewDistance = $newViewDistance;
588 $this->spawnThreshold = (int) (min($this->viewDistance, $this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4)) ** 2 * M_PI);
590 $this->nextChunkOrderRun = 0;
592 $this->getNetworkSession()->syncViewAreaRadius($this->viewDistance);
594 $this->logger->debug(
"Setting view distance to " . $this->viewDistance .
" (requested " . $distance .
")");
597 public function isOnline() : bool{
598 return $this->isConnected();
601 public function isConnected() : bool{
602 return $this->networkSession !== null && $this->networkSession->isConnected();
605 public function getNetworkSession() : NetworkSession{
606 if($this->networkSession === null){
607 throw new \LogicException(
"Player is not connected");
609 return $this->networkSession;
616 return $this->username;
623 return $this->displayName;
626 public function setDisplayName(
string $name) : void{
630 $this->displayName = $ev->getNewName();
641 return $this->locale;
644 public function getLanguage() :
Language{
645 return $this->
server->getLanguage();
652 public function changeSkin(
Skin $skin,
string $newSkinName,
string $oldSkinName) : bool{
656 if($ev->isCancelled()){
657 $this->sendSkin([$this]);
661 $this->setSkin($ev->getNewSkin());
662 $this->sendSkin($this->
server->getOnlinePlayers());
671 public function sendSkin(?array $targets =
null) : void{
672 parent::sendSkin($targets ?? $this->
server->getOnlinePlayers());
679 return $this->startAction > -1;
682 public function setUsingItem(
bool $value) : void{
683 $this->startAction = $value ? $this->
server->getTick() : -1;
684 $this->networkPropertiesDirty =
true;
692 return $this->startAction === -1 ? -1 : ($this->
server->getTick() - $this->startAction);
699 $this->checkItemCooldowns();
700 return $this->usedItemsCooldown[$item->getStateId()] ?? 0;
707 $this->checkItemCooldowns();
708 return isset($this->usedItemsCooldown[$item->getStateId()]);
715 $ticks = $ticks ?? $item->getCooldownTicks();
717 $this->usedItemsCooldown[$item->getStateId()] = $this->
server->getTick() + $ticks;
721 protected function checkItemCooldowns() : void{
722 $serverTick = $this->
server->getTick();
723 foreach($this->usedItemsCooldown as $itemId => $cooldownUntil){
724 if($cooldownUntil <= $serverTick){
725 unset($this->usedItemsCooldown[$itemId]);
730 protected function setPosition(Vector3 $pos) : bool{
731 $oldWorld = $this->location->isValid() ? $this->location->getWorld() : null;
732 if(parent::setPosition($pos)){
733 $newWorld = $this->getWorld();
734 if($oldWorld !== $newWorld){
735 if($oldWorld !==
null){
736 foreach($this->usedChunks as $index => $status){
737 World::getXZ($index, $X, $Z);
738 $this->unloadChunk($X, $Z, $oldWorld);
742 $this->usedChunks = [];
743 $this->loadQueue = [];
744 $this->getNetworkSession()->onEnterWorld();
753 protected function unloadChunk(
int $x,
int $z, ?World $world =
null) : void{
754 $world = $world ?? $this->getWorld();
755 $index = World::chunkHash($x, $z);
756 if(isset($this->usedChunks[$index])){
757 foreach($world->getChunkEntities($x, $z) as $entity){
758 if($entity !== $this){
759 $entity->despawnFrom($this);
762 $this->getNetworkSession()->stopUsingChunk($x, $z);
763 unset($this->usedChunks[$index]);
764 unset($this->activeChunkGenerationRequests[$index]);
766 $world->unregisterChunkLoader($this->chunkLoader, $x, $z);
767 $world->unregisterChunkListener($this, $x, $z);
768 unset($this->loadQueue[$index]);
769 $world->unregisterTickingChunk($this->chunkTicker, $x, $z);
770 unset($this->tickingChunks[$index]);
773 protected function spawnEntitiesOnAllChunks() : void{
774 foreach($this->usedChunks as $chunkHash => $status){
775 if($status === UsedChunkStatus::SENT){
776 World::getXZ($chunkHash, $chunkX, $chunkZ);
777 $this->spawnEntitiesOnChunk($chunkX, $chunkZ);
782 protected function spawnEntitiesOnChunk(
int $chunkX,
int $chunkZ) : void{
783 foreach($this->getWorld()->getChunkEntities($chunkX, $chunkZ) as $entity){
784 if($entity !== $this && !$entity->isFlaggedForDespawn()){
785 $entity->spawnTo($this);
795 if(!$this->isConnected()){
799 Timings::$playerChunkSend->startTiming();
802 $world = $this->getWorld();
804 $limit = $this->chunksPerTick - count($this->activeChunkGenerationRequests);
805 foreach($this->loadQueue as $index => $distance){
806 if($count >= $limit){
812 World::getXZ($index, $X, $Z);
813 assert(is_int($X) && is_int($Z));
817 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_GENERATION;
818 $this->activeChunkGenerationRequests[$index] =
true;
819 unset($this->loadQueue[$index]);
820 $world->registerChunkLoader($this->chunkLoader, $X, $Z,
true);
821 $world->registerChunkListener($this, $X, $Z);
822 if(isset($this->tickingChunks[$index])){
823 $world->registerTickingChunk($this->chunkTicker, $X, $Z);
826 $world->requestChunkPopulation($X, $Z, $this->chunkLoader)->onCompletion(
827 function() use ($X, $Z, $index, $world) :
void{
828 if(!$this->isConnected() || !isset($this->usedChunks[$index]) || $world !== $this->getWorld()){
831 if($this->usedChunks[$index] !== UsedChunkStatus::REQUESTED_GENERATION){
837 unset($this->activeChunkGenerationRequests[$index]);
838 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_SENDING;
840 $this->getNetworkSession()->startUsingChunk($X, $Z,
function() use ($X, $Z, $index) :
void{
841 $this->usedChunks[$index] = UsedChunkStatus::SENT;
842 if($this->spawnChunkLoadCount === -1){
843 $this->spawnEntitiesOnChunk($X, $Z);
844 }elseif($this->spawnChunkLoadCount++ === $this->spawnThreshold){
845 $this->spawnChunkLoadCount = -1;
847 $this->spawnEntitiesOnAllChunks();
849 $this->getNetworkSession()->notifyTerrainReady();
851 (
new PlayerPostChunkSendEvent($this, $X, $Z))->call();
854 static function() :
void{
860 Timings::$playerChunkSend->stopTiming();
863 private function recheckBroadcastPermissions() : void{
865 DefaultPermissionNames::BROADCAST_ADMIN => Server::BROADCAST_CHANNEL_ADMINISTRATIVE,
866 DefaultPermissionNames::BROADCAST_USER => Server::BROADCAST_CHANNEL_USERS
867 ] as $permission => $channel){
868 if($this->hasPermission($permission)){
869 $this->
server->subscribeToBroadcastChannel($channel, $this);
871 $this->
server->unsubscribeFromBroadcastChannel($channel, $this);
884 $this->spawned =
true;
885 $this->recheckBroadcastPermissions();
886 $this->getPermissionRecalculationCallbacks()->add(
function(array $changedPermissionsOldValues) :
void{
887 if(isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_ADMINISTRATIVE]) || isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_USERS])){
888 $this->recheckBroadcastPermissions();
892 $ev =
new PlayerJoinEvent($this,
893 KnownTranslationFactory::multiplayer_player_joined($this->getDisplayName())->prefix(TextFormat::YELLOW)
896 if($ev->getJoinMessage() !==
""){
897 $this->server->broadcastMessage($ev->getJoinMessage());
900 $this->noDamageTicks = 60;
904 if($this->getHealth() <= 0){
905 $this->logger->debug(
"Quit while dead, forcing respawn");
906 $this->actuallyRespawn();
917 private function updateTickingChunkRegistrations(array $oldTickingChunks, array $newTickingChunks) : void{
918 $world = $this->getWorld();
919 foreach($oldTickingChunks as $hash => $_){
920 if(!isset($newTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
922 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
923 $world->unregisterTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
926 foreach($newTickingChunks as $hash => $_){
927 if(!isset($oldTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
929 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
930 $world->registerTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
940 if(!$this->isConnected() || $this->viewDistance === -1){
944 Timings::$playerChunkOrder->startTiming();
948 $unloadChunks = $this->usedChunks;
950 $world = $this->getWorld();
951 $tickingChunkRadius = $world->getChunkTickRadius();
953 foreach($this->chunkSelector->selectChunks(
954 $this->server->getAllowedViewDistance($this->viewDistance),
955 $this->location->getFloorX() >> Chunk::COORD_BIT_SIZE,
956 $this->location->getFloorZ() >> Chunk::COORD_BIT_SIZE
957 ) as $radius => $hash){
958 if(!isset($this->usedChunks[$hash]) || $this->usedChunks[$hash] === UsedChunkStatus::NEEDED){
959 $newOrder[$hash] =
true;
961 if($radius < $tickingChunkRadius){
962 $tickingChunks[$hash] =
true;
964 unset($unloadChunks[$hash]);
967 foreach($unloadChunks as $index => $status){
968 World::getXZ($index, $X, $Z);
969 $this->unloadChunk($X, $Z);
972 $this->loadQueue = $newOrder;
974 $this->updateTickingChunkRegistrations($this->tickingChunks, $tickingChunks);
975 $this->tickingChunks = $tickingChunks;
977 if(count($this->loadQueue) > 0 || count($unloadChunks) > 0){
978 $this->getNetworkSession()->syncViewAreaCenterPoint($this->location, $this->viewDistance);
981 Timings::$playerChunkOrder->stopTiming();
989 return isset($this->usedChunks[
World::chunkHash($chunkX, $chunkZ)]);
997 return $this->usedChunks;
1004 return $this->usedChunks[
World::chunkHash($chunkX, $chunkZ)] ?? null;
1011 $status = $this->usedChunks[
World::chunkHash($chunkX, $chunkZ)] ?? null;
1012 return $status === UsedChunkStatus::SENT;
1019 if($this->nextChunkOrderRun !== PHP_INT_MAX && $this->nextChunkOrderRun-- <= 0){
1020 $this->nextChunkOrderRun = PHP_INT_MAX;
1021 $this->orderChunks();
1024 if(count($this->loadQueue) > 0){
1025 $this->requestChunks();
1033 if($this->hasValidCustomSpawn()){
1034 return $this->spawnPosition;
1036 $world = $this->
server->getWorldManager()->getDefaultWorld();
1038 return $world->getSpawnLocation();
1042 public function hasValidCustomSpawn() : bool{
1043 return $this->spawnPosition !== null && $this->spawnPosition->isValid();
1055 $world = $this->getWorld();
1057 $world = $pos->getWorld();
1059 $this->spawnPosition =
new Position($pos->x, $pos->y, $pos->z, $world);
1061 $this->spawnPosition =
null;
1063 $this->getNetworkSession()->syncPlayerSpawnPoint($this->getSpawn());
1066 public function isSleeping() : bool{
1067 return $this->sleeping !== null;
1070 public function sleepOn(Vector3 $pos) : bool{
1071 $pos = $pos->floor();
1072 $b = $this->getWorld()->getBlock($pos);
1074 $ev =
new PlayerBedEnterEvent($this, $b);
1076 if($ev->isCancelled()){
1080 if($b instanceof Bed){
1082 $this->getWorld()->setBlock($pos, $b);
1085 $this->sleeping = $pos;
1086 $this->networkPropertiesDirty =
true;
1088 $this->setSpawn($pos);
1090 $this->getWorld()->setSleepTicks(60);
1095 public function stopSleep() : void{
1096 if($this->sleeping instanceof Vector3){
1097 $b = $this->getWorld()->getBlock($this->sleeping);
1098 if($b instanceof Bed){
1099 $b->setOccupied(
false);
1100 $this->getWorld()->setBlock($this->sleeping, $b);
1102 (
new PlayerBedLeaveEvent($this, $b))->call();
1104 $this->sleeping =
null;
1105 $this->networkPropertiesDirty =
true;
1107 $this->getWorld()->setSleepTicks(0);
1109 $this->getNetworkSession()->sendDataPacket(AnimatePacket::create($this->getId(), AnimatePacket::ACTION_STOP_SLEEP));
1113 public function getGamemode() : GameMode{
1114 return $this->gamemode;
1117 protected function internalSetGameMode(GameMode $gameMode) : void{
1118 $this->gamemode = $gameMode;
1120 $this->allowFlight = $this->gamemode === GameMode::CREATIVE;
1121 $this->hungerManager->setEnabled($this->isSurvival());
1123 if($this->isSpectator()){
1124 $this->setFlying(
true);
1125 $this->setHasBlockCollision(
false);
1127 $this->onGround =
false;
1131 $this->sendPosition($this->location,
null,
null, MovePlayerPacket::MODE_TELEPORT);
1133 if($this->isSurvival()){
1134 $this->setFlying(
false);
1136 $this->setHasBlockCollision(
true);
1137 $this->setSilent(
false);
1138 $this->checkGroundState(0, 0, 0, 0, 0, 0);
1146 if($this->gamemode === $gm){
1152 if($ev->isCancelled()){
1156 $this->internalSetGameMode($gm);
1158 if($this->isSpectator()){
1159 $this->despawnFromAll();
1161 $this->spawnToAll();
1164 $this->getNetworkSession()->syncGameMode($this->gamemode);
1175 return $this->gamemode === GameMode::SURVIVAL || (!$literal && $this->gamemode === GameMode::ADVENTURE);
1185 return $this->gamemode === GameMode::CREATIVE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1195 return $this->gamemode === GameMode::ADVENTURE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1198 public function isSpectator() : bool{
1199 return $this->gamemode === GameMode::SPECTATOR;
1206 return $this->gamemode !== GameMode::CREATIVE;
1210 if($this->hasFiniteResources()){
1211 return parent::getDrops();
1218 if($this->hasFiniteResources()){
1219 return parent::getXpDropAmount();
1225 protected function checkGroundState(
float $wantedX,
float $wantedY,
float $wantedZ,
float $dx,
float $dy,
float $dz) : void{
1226 if($this->gamemode === GameMode::SPECTATOR){
1227 $this->onGround =
false;
1229 $bb = clone $this->boundingBox;
1230 $bb->minY = $this->location->y - 0.2;
1231 $bb->maxY = $this->location->y + 0.2;
1235 $bb = $bb->addCoord(-$dx, -$dy, -$dz);
1237 $this->onGround = $this->isCollided = count($this->getWorld()->getCollisionBlocks($bb,
true)) > 0;
1245 protected function checkNearEntities() : void{
1246 foreach($this->getWorld()->getNearbyEntities($this->boundingBox->expandedCopy(1, 0.5, 1), $this) as $entity){
1247 $entity->scheduleUpdate();
1249 if(!$entity->isAlive() || $entity->isFlaggedForDespawn()){
1253 $entity->onCollideWithPlayer($this);
1257 public function getInAirTicks() : int{
1258 return $this->inAirTicks;
1270 Timings::$playerMove->startTiming();
1272 $this->actuallyHandleMovement($newPos);
1274 Timings::$playerMove->stopTiming();
1278 private function actuallyHandleMovement(Vector3 $newPos) : void{
1279 $this->moveRateLimit--;
1280 if($this->moveRateLimit < 0){
1284 $oldPos = $this->location;
1285 $distanceSquared = $newPos->distanceSquared($oldPos);
1289 if($distanceSquared > 225){
1301 $this->logger->debug(
"Moved too fast (" . sqrt($distanceSquared) .
" blocks in 1 movement), reverting movement");
1302 $this->logger->debug(
"Old position: " . $oldPos->asVector3() .
", new position: " . $newPos);
1304 }elseif(!$this->getWorld()->isInLoadedTerrain($newPos)){
1306 $this->nextChunkOrderRun = 0;
1309 if(!$revert && $distanceSquared != 0){
1310 $dx = $newPos->x - $oldPos->x;
1311 $dy = $newPos->y - $oldPos->y;
1312 $dz = $newPos->z - $oldPos->z;
1314 $this->move($dx, $dy, $dz);
1318 $this->revertMovement($oldPos);
1326 $now = microtime(true);
1327 $multiplier = $this->lastMovementProcess !==
null ? ($now - $this->lastMovementProcess) * 20 : 1;
1328 $exceededRateLimit = $this->moveRateLimit < 0;
1329 $this->moveRateLimit = min(self::MOVE_BACKLOG_SIZE, max(0, $this->moveRateLimit) + self::MOVES_PER_TICK * $multiplier);
1330 $this->lastMovementProcess = $now;
1332 $from = clone $this->lastLocation;
1333 $to = clone $this->location;
1335 $delta = $to->distanceSquared($from);
1336 $deltaAngle = abs($this->lastLocation->yaw - $to->yaw) + abs($this->lastLocation->pitch - $to->pitch);
1338 if($delta > 0.0001 || $deltaAngle > 1.0){
1339 if(PlayerMoveEvent::hasHandlers()){
1344 if($ev->isCancelled()){
1345 $this->revertMovement($from);
1349 if($to->distanceSquared($ev->getTo()) > 0.01){
1350 $this->teleport($ev->getTo());
1355 $this->lastLocation = $to;
1356 $this->broadcastMovement();
1358 $horizontalDistanceTravelled = sqrt((($from->x - $to->x) ** 2) + (($from->z - $to->z) ** 2));
1359 if($horizontalDistanceTravelled > 0){
1361 if($this->isSprinting()){
1362 $this->hungerManager->exhaust(0.01 * $horizontalDistanceTravelled, PlayerExhaustEvent::CAUSE_SPRINTING);
1364 $this->hungerManager->exhaust(0.0, PlayerExhaustEvent::CAUSE_WALKING);
1367 if($this->nextChunkOrderRun > 20){
1368 $this->nextChunkOrderRun = 20;
1373 if($exceededRateLimit){
1374 $this->logger->debug(
"Exceeded movement rate limit, forcing to last accepted position");
1375 $this->sendPosition($this->location, $this->location->getYaw(), $this->location->getPitch(), MovePlayerPacket::MODE_RESET);
1379 protected function revertMovement(Location $from) : void{
1380 $this->setPosition($from);
1381 $this->sendPosition($from, $from->yaw, $from->pitch, MovePlayerPacket::MODE_RESET);
1384 protected function calculateFallDamage(
float $fallDistance) : float{
1385 return $this->flying ? 0 : parent::calculateFallDamage($fallDistance);
1393 public function setMotion(
Vector3 $motion) : bool{
1394 if(parent::setMotion($motion)){
1395 $this->broadcastMotion();
1396 $this->getNetworkSession()->sendDataPacket(SetActorMotionPacket::create($this->
id, $motion, tick: 0));
1403 protected function updateMovement(
bool $teleport =
false) : void{
1407 protected function tryChangeMovement() : void{
1411 public function onUpdate(int $currentTick) : bool{
1412 $tickDiff = $currentTick - $this->lastUpdate;
1418 $this->messageCounter = 2;
1420 $this->lastUpdate = $currentTick;
1422 if($this->justCreated){
1423 $this->onFirstUpdate($currentTick);
1426 if(!$this->isAlive() && $this->spawned){
1427 $this->onDeathUpdate($tickDiff);
1431 $this->timings->startTiming();
1434 Timings::$playerMove->startTiming();
1435 $this->processMostRecentMovements();
1436 $this->motion = Vector3::zero();
1437 if($this->onGround){
1438 $this->inAirTicks = 0;
1440 $this->inAirTicks += $tickDiff;
1442 Timings::$playerMove->stopTiming();
1444 Timings::$entityBaseTick->startTiming();
1445 $this->entityBaseTick($tickDiff);
1446 Timings::$entityBaseTick->stopTiming();
1448 if($this->isCreative() && $this->fireTicks > 1){
1449 $this->fireTicks = 1;
1452 if(!$this->isSpectator() && $this->isAlive()){
1453 Timings::$playerCheckNearEntities->startTiming();
1454 $this->checkNearEntities();
1455 Timings::$playerCheckNearEntities->stopTiming();
1458 if($this->blockBreakHandler !==
null && !$this->blockBreakHandler->update()){
1459 $this->blockBreakHandler =
null;
1463 $this->timings->stopTiming();
1469 return $this->isCreative() || parent::canBreathe();
1478 $eyePos = $this->getEyePos();
1479 if($eyePos->distanceSquared($pos) > $maxDistance ** 2){
1483 $dV = $this->getDirectionVector();
1484 $eyeDot = $dV->dot($eyePos);
1485 $targetDot = $dV->dot($pos);
1486 return ($targetDot - $eyeDot) >= -$maxDiff;
1493 public function chat(
string $message) : bool{
1494 $this->removeCurrentWindow();
1496 if($this->messageCounter <= 0){
1502 $maxTotalLength = $this->messageCounter * (self::MAX_CHAT_BYTE_LENGTH + 1);
1503 if(strlen($message) > $maxTotalLength){
1507 $message = TextFormat::clean($message,
false);
1508 foreach(explode(
"\n", $message, $this->messageCounter + 1) as $messagePart){
1509 if(trim($messagePart) !==
"" && strlen($messagePart) <= self::MAX_CHAT_BYTE_LENGTH && mb_strlen($messagePart,
'UTF-8') <= self::MAX_CHAT_CHAR_LENGTH && $this->messageCounter-- > 0){
1510 if(str_starts_with($messagePart,
'./')){
1511 $messagePart = substr($messagePart, 1);
1514 if(str_starts_with($messagePart,
"/")){
1515 Timings::$playerCommand->startTiming();
1516 $this->server->dispatchCommand($this, substr($messagePart, 1));
1517 Timings::$playerCommand->stopTiming();
1519 $ev =
new PlayerChatEvent($this, $messagePart, $this->
server->getBroadcastChannelSubscribers(Server::BROADCAST_CHANNEL_USERS),
new StandardChatFormatter());
1521 if(!$ev->isCancelled()){
1522 $this->
server->broadcastMessage($ev->getFormatter()->format($ev->getPlayer()->getDisplayName(), $ev->getMessage()), $ev->getRecipients());
1531 public function selectHotbarSlot(
int $hotbarSlot) : bool{
1532 if(!$this->inventory->isHotbarSlot($hotbarSlot)){
1535 if($hotbarSlot === $this->inventory->getHeldItemIndex()){
1539 $ev =
new PlayerItemHeldEvent($this, $this->inventory->getItem($hotbarSlot), $hotbarSlot);
1541 if($ev->isCancelled()){
1545 $this->inventory->setHeldItemIndex($hotbarSlot);
1546 $this->setUsingItem(
false);
1554 private function returnItemsFromAction(Item $oldHeldItem, Item $newHeldItem, array $extraReturnedItems) : void{
1555 $heldItemChanged = false;
1557 if(!$newHeldItem->equalsExact($oldHeldItem) && $oldHeldItem->equalsExact($this->inventory->getItemInHand())){
1560 $newReplica = clone $oldHeldItem;
1561 $newReplica->setCount($newHeldItem->getCount());
1562 if($newReplica instanceof Durable && $newHeldItem instanceof Durable){
1563 $newReplica->setDamage($newHeldItem->getDamage());
1565 $damagedOrDeducted = $newReplica->equalsExact($newHeldItem);
1567 if(!$damagedOrDeducted || $this->hasFiniteResources()){
1568 if($newHeldItem instanceof Durable && $newHeldItem->isBroken()){
1569 $this->broadcastSound(
new ItemBreakSound());
1571 $this->inventory->setItemInHand($newHeldItem);
1572 $heldItemChanged =
true;
1576 if(!$heldItemChanged){
1577 $newHeldItem = $oldHeldItem;
1580 if($heldItemChanged && count($extraReturnedItems) > 0 && $newHeldItem->isNull()){
1581 $this->inventory->setItemInHand(array_shift($extraReturnedItems));
1583 foreach($this->inventory->addItem(...$extraReturnedItems) as $drop){
1585 $ev =
new PlayerDropItemEvent($this, $drop);
1586 if($this->isSpectator()){
1590 if(!$ev->isCancelled()){
1591 $this->dropItem($drop);
1602 $directionVector = $this->getDirectionVector();
1603 $item = $this->inventory->getItemInHand();
1604 $oldItem = clone $item;
1607 if($this->hasItemCooldown($item) || $this->isSpectator()){
1613 if($ev->isCancelled()){
1617 $returnedItems = [];
1618 $result = $item->onClickAir($this, $directionVector, $returnedItems);
1619 if($result === ItemUseResult::FAIL){
1623 $this->resetItemCooldown($item);
1624 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1626 $this->setUsingItem($item instanceof Releasable && $item->canStartUsingItem($this));
1637 $slot = $this->inventory->getItemInHand();
1639 $oldItem = clone $slot;
1642 if($this->hasItemCooldown($slot)){
1647 if($ev->isCancelled() || !$this->consumeObject($slot)){
1651 $this->setUsingItem(
false);
1652 $this->resetItemCooldown($slot);
1655 $this->returnItemsFromAction($oldItem, $slot, [$slot->getResidue()]);
1670 $item = $this->inventory->getItemInHand();
1671 if(!$this->isUsingItem() || $this->hasItemCooldown($item)){
1675 $oldItem = clone $item;
1677 $returnedItems = [];
1678 $result = $item->onReleaseUsing($this, $returnedItems);
1679 if($result === ItemUseResult::SUCCESS){
1680 $this->resetItemCooldown($item);
1681 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1687 $this->setUsingItem(
false);
1691 public function pickBlock(Vector3 $pos,
bool $addTileNBT) : bool{
1692 $block = $this->getWorld()->getBlock($pos);
1693 if($block instanceof UnknownBlock){
1697 $item = $block->getPickedItem($addTileNBT);
1699 $ev =
new PlayerBlockPickEvent($this, $block, $item);
1700 $existingSlot = $this->inventory->first($item);
1701 if($existingSlot === -1 && $this->hasFiniteResources()){
1706 if(!$ev->isCancelled()){
1707 if($existingSlot !== -1){
1708 if($existingSlot < $this->inventory->getHotbarSize()){
1709 $this->inventory->setHeldItemIndex($existingSlot);
1711 $this->inventory->swap($this->inventory->getHeldItemIndex(), $existingSlot);
1714 $firstEmpty = $this->inventory->firstEmpty();
1715 if($firstEmpty === -1){
1716 $this->inventory->setItemInHand($item);
1717 }elseif($firstEmpty < $this->inventory->getHotbarSize()){
1718 $this->inventory->setItem($firstEmpty, $item);
1719 $this->inventory->setHeldItemIndex($firstEmpty);
1721 $this->inventory->swap($this->inventory->getHeldItemIndex(), $firstEmpty);
1722 $this->inventory->setItemInHand($item);
1736 if($pos->distanceSquared($this->location) > 10000){
1740 $target = $this->getWorld()->getBlock($pos);
1742 $ev =
new PlayerInteractEvent($this, $this->inventory->getItemInHand(), $target,
null, $face, PlayerInteractEvent::LEFT_CLICK_BLOCK);
1743 if($this->isSpectator()){
1747 if($ev->isCancelled()){
1750 $this->broadcastAnimation(
new ArmSwingAnimation($this), $this->getViewers());
1751 if($target->onAttack($this->inventory->getItemInHand(), $face, $this)){
1755 $block = $target->getSide($face);
1756 if($block->hasTypeTag(BlockTypeTags::FIRE)){
1757 $this->getWorld()->setBlock($block->getPosition(), VanillaBlocks::AIR());
1758 $this->getWorld()->addSound($block->getPosition()->add(0.5, 0.5, 0.5),
new FireExtinguishSound());
1762 if(!$this->isCreative() && !$block->getBreakInfo()->breaksInstantly()){
1763 $this->blockBreakHandler =
new SurvivalBlockBreakHandler($this, $pos, $target, $face, 16);
1769 public function continueBreakBlock(Vector3 $pos,
int $face) : void{
1770 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1771 $this->blockBreakHandler->setTargetedFace($face);
1775 public function stopBreakBlock(Vector3 $pos) : void{
1776 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1777 $this->blockBreakHandler =
null;
1787 $this->removeCurrentWindow();
1789 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1791 $this->stopBreakBlock($pos);
1792 $item = $this->inventory->getItemInHand();
1793 $oldItem = clone $item;
1794 $returnedItems = [];
1795 if($this->getWorld()->useBreakOn($pos, $item, $this,
true, $returnedItems)){
1796 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1797 $this->hungerManager->exhaust(0.005, PlayerExhaustEvent::CAUSE_MINING);
1801 $this->logger->debug(
"Cancelled block break at $pos due to not currently being interactable");
1813 $this->setUsingItem(false);
1815 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1817 $item = $this->inventory->getItemInHand();
1818 $oldItem = clone $item;
1819 $returnedItems = [];
1820 if($this->getWorld()->useItemOn($pos, $item, $face, $clickOffset, $this,
true, $returnedItems)){
1821 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1825 $this->logger->debug(
"Cancelled interaction of block at $pos due to not currently being interactable");
1838 if(!$entity->isAlive()){
1842 $this->logger->debug(
"Attempted to attack non-attackable entity " . get_class($entity));
1846 $heldItem = $this->inventory->getItemInHand();
1847 $oldItem = clone $heldItem;
1849 $ev =
new EntityDamageByEntityEvent($this, $entity, EntityDamageEvent::CAUSE_ENTITY_ATTACK, $heldItem->getAttackPoints());
1850 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
1851 $this->logger->debug(
"Cancelled attack of entity " . $entity->getId() .
" due to not currently being interactable");
1853 }elseif($this->isSpectator() || ($entity instanceof Player && !$this->server->getConfigGroup()->getConfigBool(ServerProperties::PVP))){
1857 $meleeEnchantmentDamage = 0;
1859 $meleeEnchantments = [];
1860 foreach($heldItem->getEnchantments() as $enchantment){
1861 $type = $enchantment->getType();
1862 if($type instanceof MeleeWeaponEnchantment && $type->isApplicableTo($entity)){
1863 $meleeEnchantmentDamage += $type->getDamageBonus($enchantment->getLevel());
1864 $meleeEnchantments[] = $enchantment;
1867 $ev->setModifier($meleeEnchantmentDamage, EntityDamageEvent::MODIFIER_WEAPON_ENCHANTMENTS);
1869 if(!$this->isSprinting() && !$this->isFlying() && $this->fallDistance > 0 && !$this->effectManager->has(VanillaEffects::BLINDNESS()) && !$this->isUnderwater()){
1870 $ev->setModifier($ev->getFinalDamage() / 2, EntityDamageEvent::MODIFIER_CRITICAL);
1873 $entity->attack($ev);
1874 $this->broadcastAnimation(
new ArmSwingAnimation($this), $this->getViewers());
1876 $soundPos = $entity->getPosition()->add(0, $entity->size->getHeight() / 2, 0);
1877 if($ev->isCancelled()){
1878 $this->getWorld()->addSound($soundPos,
new EntityAttackNoDamageSound());
1881 $this->getWorld()->addSound($soundPos,
new EntityAttackSound());
1883 if($ev->getModifier(EntityDamageEvent::MODIFIER_CRITICAL) > 0 && $entity instanceof Living){
1884 $entity->broadcastAnimation(
new CriticalHitAnimation($entity));
1887 foreach($meleeEnchantments as $enchantment){
1888 $type = $enchantment->getType();
1889 assert($type instanceof MeleeWeaponEnchantment);
1890 $type->onPostAttack($this, $entity, $enchantment->getLevel());
1893 if($this->isAlive()){
1896 $returnedItems = [];
1897 $heldItem->onAttackEntity($entity, $returnedItems);
1898 $this->returnItemsFromAction($oldItem, $heldItem, $returnedItems);
1900 $this->hungerManager->exhaust(0.1, PlayerExhaustEvent::CAUSE_ATTACK);
1913 if(!$ev->isCancelled()){
1925 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
1926 $this->logger->debug(
"Cancelled interaction with entity " . $entity->getId() .
" due to not currently being interactable");
1932 $item = $this->inventory->getItemInHand();
1933 $oldItem = clone $item;
1934 if(!$ev->isCancelled()){
1935 if($item->onInteractEntity($this, $entity, $clickPos)){
1936 if($this->hasFiniteResources() && !$item->equalsExact($oldItem) && $oldItem->equalsExact($this->inventory->getItemInHand())){
1940 $this->inventory->setItemInHand($item);
1943 return $entity->
onInteract($this, $clickPos);
1948 public function toggleSprint(
bool $sprint) : bool{
1949 if($sprint === $this->sprinting){
1952 $ev =
new PlayerToggleSprintEvent($this, $sprint);
1954 if($ev->isCancelled()){
1957 $this->setSprinting($sprint);
1961 public function toggleSneak(
bool $sneak) : bool{
1962 if($sneak === $this->sneaking){
1965 $ev =
new PlayerToggleSneakEvent($this, $sneak);
1967 if($ev->isCancelled()){
1970 $this->setSneaking($sneak);
1974 public function toggleFlight(
bool $fly) : bool{
1975 if($fly === $this->flying){
1978 $ev =
new PlayerToggleFlightEvent($this, $fly);
1979 if(!$this->allowFlight){
1983 if($ev->isCancelled()){
1986 $this->setFlying($fly);
1990 public function toggleGlide(
bool $glide) : bool{
1991 if($glide === $this->gliding){
1994 $ev =
new PlayerToggleGlideEvent($this, $glide);
1996 if($ev->isCancelled()){
1999 $this->setGliding($glide);
2003 public function toggleSwim(
bool $swim) : bool{
2004 if($swim === $this->swimming){
2007 $ev =
new PlayerToggleSwimEvent($this, $swim);
2009 if($ev->isCancelled()){
2012 $this->setSwimming($swim);
2016 public function emote(
string $emoteId) : void{
2017 $currentTick = $this->
server->getTick();
2018 if($currentTick - $this->lastEmoteTick > 5){
2019 $this->lastEmoteTick = $currentTick;
2020 $event =
new PlayerEmoteEvent($this, $emoteId);
2022 if(!$event->isCancelled()){
2023 $emoteId = $event->getEmoteId();
2024 parent::emote($emoteId);
2034 $this->getWorld()->dropItem($this->location->add(0, 1.3, 0), $item, $this->getDirectionVector()->multiply(0.4), 40);
2044 public function sendTitle(
string $title,
string $subtitle =
"",
int $fadeIn = -1,
int $stay = -1,
int $fadeOut = -1) : void{
2045 $this->setTitleDuration($fadeIn, $stay, $fadeOut);
2046 if($subtitle !==
""){
2047 $this->sendSubTitle($subtitle);
2049 $this->getNetworkSession()->onTitle($title);
2056 $this->getNetworkSession()->onSubTitle($subtitle);
2063 $this->getNetworkSession()->onActionBar($message);
2070 $this->getNetworkSession()->onClearTitle();
2077 $this->getNetworkSession()->onResetTitleOptions();
2088 if($fadeIn >= 0 && $stay >= 0 && $fadeOut >= 0){
2089 $this->getNetworkSession()->onTitleDuration($fadeIn, $stay, $fadeOut);
2097 $this->getNetworkSession()->onChatMessage($message);
2100 public function sendJukeboxPopup(
Translatable|
string $message) : void{
2101 $this->getNetworkSession()->onJukeboxPopup($message);
2110 $this->getNetworkSession()->onPopup($message);
2113 public function sendTip(
string $message) : void{
2114 $this->getNetworkSession()->onTip($message);
2121 $this->getNetworkSession()->onToastNotification($title, $body);
2130 $id = $this->formIdCounter++;
2131 if($this->getNetworkSession()->onFormSent($id, $form)){
2132 $this->forms[$id] = $form;
2136 public function onFormSubmit(
int $formId, mixed $responseData) : bool{
2137 if(!isset($this->forms[$formId])){
2138 $this->logger->debug(
"Got unexpected response for form $formId");
2143 $this->forms[$formId]->handleResponse($this, $responseData);
2144 }
catch(FormValidationException $e){
2145 $this->logger->critical(
"Failed to validate form " . get_class($this->forms[$formId]) .
": " . $e->getMessage());
2146 $this->logger->logException($e);
2148 unset($this->forms[$formId]);
2158 $this->getNetworkSession()->onCloseAllForms();
2173 if(!$ev->isCancelled()){
2174 $this->getNetworkSession()->transfer($ev->getAddress(), $ev->getPort(), $ev->getMessage());
2189 $ev = new
PlayerKickEvent($this, $reason, $quitMessage ?? $this->getLeaveMessage(), $disconnectScreenMessage);
2191 if(!$ev->isCancelled()){
2192 $reason = $ev->getDisconnectReason();
2194 $reason = KnownTranslationFactory::disconnectionScreen_noReason();
2196 $disconnectScreenMessage = $ev->getDisconnectScreenMessage() ?? $reason;
2197 if($disconnectScreenMessage ===
""){
2198 $disconnectScreenMessage = KnownTranslationFactory::disconnectionScreen_noReason();
2200 $this->disconnect($reason, $ev->getQuitMessage(), $disconnectScreenMessage);
2222 if(!$this->isConnected()){
2226 $this->getNetworkSession()->onPlayerDestroyed($reason, $disconnectScreenMessage ?? $reason);
2227 $this->onPostDisconnect($reason, $quitMessage);
2238 if($this->isConnected()){
2239 throw new \LogicException(
"Player is still connected");
2243 $this->server->unsubscribeFromAllBroadcastChannels($this);
2245 $this->removeCurrentWindow();
2247 $ev =
new PlayerQuitEvent($this, $quitMessage ?? $this->getLeaveMessage(), $reason);
2249 if(($quitMessage = $ev->getQuitMessage()) !=
""){
2250 $this->server->broadcastMessage($quitMessage);
2254 $this->spawned =
false;
2257 $this->blockBreakHandler =
null;
2258 $this->despawnFromAll();
2260 $this->
server->removeOnlinePlayer($this);
2262 foreach($this->
server->getOnlinePlayers() as $player){
2263 if(!$player->canSee($this)){
2264 $player->showPlayer($this);
2267 $this->hiddenPlayers = [];
2269 if($this->location->isValid()){
2270 foreach($this->usedChunks as $index => $status){
2271 World::getXZ($index, $chunkX, $chunkZ);
2272 $this->unloadChunk($chunkX, $chunkZ);
2275 if(count($this->usedChunks) !== 0){
2276 throw new AssumptionFailedError(
"Previous loop should have cleared this array");
2278 $this->loadQueue = [];
2280 $this->removeCurrentWindow();
2281 $this->removePermanentInventories();
2283 $this->perm->getPermissionRecalculationCallbacks()->clear();
2285 $this->flagForDespawn();
2289 $this->disconnect(
"Player destroyed");
2290 $this->cursorInventory->removeAllViewers();
2291 $this->craftingGrid->removeAllViewers();
2292 parent::onDispose();
2296 $this->networkSession = null;
2297 unset($this->cursorInventory);
2298 unset($this->craftingGrid);
2299 $this->spawnPosition =
null;
2300 $this->blockBreakHandler =
null;
2301 parent::destroyCycles();
2311 public function __destruct(){
2312 parent::__destruct();
2313 $this->logger->debug(
"Destroyed by garbage collector");
2321 throw new \BadMethodCallException(
"Players can't be saved with chunks");
2325 $nbt = $this->saveNBT();
2327 $nbt->
setString(self::TAG_LAST_KNOWN_XUID, $this->xuid);
2329 if($this->location->isValid()){
2330 $nbt->
setString(self::TAG_LEVEL, $this->getWorld()->getFolderName());
2333 if($this->hasValidCustomSpawn()){
2334 $spawn = $this->getSpawn();
2335 $nbt->
setString(self::TAG_SPAWN_WORLD, $spawn->getWorld()->getFolderName());
2336 $nbt->
setInt(self::TAG_SPAWN_X, $spawn->getFloorX());
2337 $nbt->
setInt(self::TAG_SPAWN_Y, $spawn->getFloorY());
2338 $nbt->
setInt(self::TAG_SPAWN_Z, $spawn->getFloorZ());
2341 $nbt->
setInt(self::TAG_GAME_MODE, GameModeIdMap::getInstance()->toId($this->gamemode));
2342 $nbt->
setLong(self::TAG_FIRST_PLAYED, $this->firstPlayed);
2343 $nbt->
setLong(self::TAG_LAST_PLAYED, (
int) floor(microtime(
true) * 1000));
2352 $this->
server->saveOfflinePlayerData($this->username, $this->getSaveData());
2358 $this->removeCurrentWindow();
2360 $ev =
new PlayerDeathEvent($this, $this->getDrops(), $this->getXpDropAmount(),
null);
2363 if(!$ev->getKeepInventory()){
2364 foreach($ev->getDrops() as $item){
2365 $this->getWorld()->dropItem($this->location, $item);
2368 $clearInventory = fn(
Inventory $inventory) => $inventory->setContents(array_filter($inventory->getContents(), fn(
Item $item) => $item->
keepOnDeath()));
2369 $this->inventory->setHeldItemIndex(0);
2370 $clearInventory($this->inventory);
2371 $clearInventory($this->armorInventory);
2372 $clearInventory($this->offHandInventory);
2375 if(!$ev->getKeepXp()){
2376 $this->getWorld()->dropExperience($this->location, $ev->getXpDropAmount());
2377 $this->xpManager->setXpAndProgress(0, 0.0);
2380 if($ev->getDeathMessage() !=
""){
2381 $this->server->broadcastMessage($ev->getDeathMessage());
2384 $this->startDeathAnimation();
2386 $this->getNetworkSession()->onServerDeath($ev->getDeathScreenMessage());
2390 parent::onDeathUpdate($tickDiff);
2394 public function respawn() : void{
2395 if($this->
server->isHardcore()){
2396 if($this->kick(KnownTranslationFactory::pocketmine_disconnect_ban(KnownTranslationFactory::pocketmine_disconnect_ban_hardcore()))){
2397 $this->
server->getNameBans()->addBan($this->getName(),
"Died in hardcore mode");
2402 $this->actuallyRespawn();
2405 protected function actuallyRespawn() : void{
2406 if($this->respawnLocked){
2409 $this->respawnLocked =
true;
2411 $this->logger->debug(
"Waiting for safe respawn position to be located");
2412 $spawn = $this->getSpawn();
2413 $spawn->getWorld()->requestSafeSpawn($spawn)->onCompletion(
2414 function(Position $safeSpawn) :
void{
2415 if(!$this->isConnected()){
2418 $this->logger->debug(
"Respawn position located, completing respawn");
2419 $ev =
new PlayerRespawnEvent($this, $safeSpawn);
2422 $realSpawn = Position::fromObject($ev->getRespawnPosition()->add(0.5, 0, 0.5), $ev->getRespawnPosition()->getWorld());
2423 $this->teleport($realSpawn);
2425 $this->setSprinting(
false);
2426 $this->setSneaking(
false);
2427 $this->setFlying(
false);
2429 $this->extinguish();
2430 $this->setAirSupplyTicks($this->getMaxAirSupplyTicks());
2431 $this->deadTicks = 0;
2432 $this->noDamageTicks = 60;
2434 $this->effectManager->clear();
2435 $this->setHealth($this->getMaxHealth());
2437 foreach($this->attributeMap->getAll() as $attr){
2438 if($attr->getId() === Attribute::EXPERIENCE || $attr->getId() === Attribute::EXPERIENCE_LEVEL){
2441 $attr->resetToDefault();
2444 $this->spawnToAll();
2445 $this->scheduleUpdate();
2447 $this->getNetworkSession()->onServerRespawn();
2448 $this->respawnLocked =
false;
2451 if($this->isConnected()){
2452 $this->getNetworkSession()->disconnectWithError(KnownTranslationFactory::pocketmine_disconnect_error_respawn());
2459 parent::applyPostDamageEffects($source);
2461 $this->hungerManager->exhaust(0.1, PlayerExhaustEvent::CAUSE_DAMAGE);
2465 if(!$this->isAlive()){
2469 if($this->isCreative()
2470 && $source->getCause() !== EntityDamageEvent::CAUSE_SUICIDE
2473 }elseif($this->allowFlight && $source->getCause() === EntityDamageEvent::CAUSE_FALL){
2477 parent::attack($source);
2480 protected function syncNetworkData(EntityMetadataCollection $properties) : void{
2481 parent::syncNetworkData($properties);
2483 $properties->setGenericFlag(EntityMetadataFlags::ACTION, $this->startAction > -1);
2484 $properties->setGenericFlag(EntityMetadataFlags::HAS_COLLISION, $this->hasBlockCollision());
2486 $properties->setPlayerFlag(PlayerMetadataFlags::SLEEP, $this->sleeping !==
null);
2487 $properties->setBlockPos(EntityMetadataProperties::PLAYER_BED_POSITION, $this->sleeping !==
null ? BlockPosition::fromVector3($this->sleeping) :
new BlockPosition(0, 0, 0));
2490 public function sendData(?array $targets, ?array $data =
null) : void{
2491 if($targets === null){
2492 $targets = $this->getViewers();
2495 parent::sendData($targets, $data);
2499 if($this->spawned && $targets === null){
2500 $targets = $this->getViewers();
2503 parent::broadcastAnimation($animation, $targets);
2507 if($this->spawned && $targets === null){
2508 $targets = $this->getViewers();
2511 parent::broadcastSound($sound, $targets);
2517 protected function sendPosition(
Vector3 $pos, ?
float $yaw =
null, ?
float $pitch =
null,
int $mode = MovePlayerPacket::MODE_NORMAL) : void{
2518 $this->getNetworkSession()->syncMovement($pos, $yaw, $pitch, $mode);
2524 if(parent::teleport($pos, $yaw, $pitch)){
2526 $this->removeCurrentWindow();
2529 $this->sendPosition($this->location, $this->location->yaw, $this->location->pitch, MovePlayerPacket::MODE_TELEPORT);
2530 $this->broadcastMovement(
true);
2532 $this->spawnToAll();
2534 $this->resetFallDistance();
2535 $this->nextChunkOrderRun = 0;
2536 if($this->spawnChunkLoadCount !== -1){
2537 $this->spawnChunkLoadCount = 0;
2539 $this->blockBreakHandler =
null;
2543 $this->resetLastMovements();
2551 protected function addDefaultWindows() : void{
2552 $this->cursorInventory = new PlayerCursorInventory($this);
2553 $this->craftingGrid =
new PlayerCraftingInventory($this);
2555 $this->addPermanentInventories($this->inventory, $this->armorInventory, $this->cursorInventory, $this->offHandInventory, $this->craftingGrid);
2560 public function getCursorInventory() : PlayerCursorInventory{
2561 return $this->cursorInventory;
2564 public function getCraftingGrid() : CraftingGrid{
2565 return $this->craftingGrid;
2573 return $this->creativeInventory;
2580 $this->creativeInventory = $inventory;
2581 if($this->spawned && $this->isConnected()){
2582 $this->getNetworkSession()->getInvManager()?->syncCreative();
2590 private function doCloseInventory() : void{
2591 $inventories = [$this->craftingGrid, $this->cursorInventory];
2592 if($this->currentWindow instanceof TemporaryInventory){
2593 $inventories[] = $this->currentWindow;
2596 $builder =
new TransactionBuilder();
2597 foreach($inventories as $inventory){
2598 $contents = $inventory->getContents();
2600 if(count($contents) > 0){
2601 $drops = $builder->getInventory($this->inventory)->addItem(...$contents);
2602 foreach($drops as $drop){
2603 $builder->addAction(
new DropItemAction($drop));
2606 $builder->getInventory($inventory)->clearAll();
2610 $actions = $builder->generateActions();
2611 if(count($actions) !== 0){
2612 $transaction =
new InventoryTransaction($this, $actions);
2614 $transaction->execute();
2615 $this->logger->debug(
"Successfully evacuated items from temporary inventories");
2616 }
catch(TransactionCancelledException){
2617 $this->logger->debug(
"Plugin cancelled transaction evacuating items from temporary inventories; items will be destroyed");
2618 foreach($inventories as $inventory){
2619 $inventory->clearAll();
2621 }
catch(TransactionValidationException $e){
2622 throw new AssumptionFailedError(
"This server-generated transaction should never be invalid", 0, $e);
2631 return $this->currentWindow;
2638 if($inventory === $this->currentWindow){
2643 if($ev->isCancelled()){
2647 $this->removeCurrentWindow();
2649 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) ===
null){
2650 throw new \InvalidArgumentException(
"Player cannot open inventories in this state");
2652 $this->logger->debug(
"Opening inventory " . get_class($inventory) .
"#" . spl_object_id($inventory));
2653 $inventoryManager->onCurrentWindowChange($inventory);
2654 $inventory->onOpen($this);
2655 $this->currentWindow = $inventory;
2659 public function removeCurrentWindow() : void{
2660 $this->doCloseInventory();
2661 if($this->currentWindow !==
null){
2662 $currentWindow = $this->currentWindow;
2663 $this->logger->debug(
"Closing inventory " . get_class($this->currentWindow) .
"#" . spl_object_id($this->currentWindow));
2664 $this->currentWindow->onClose($this);
2665 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) !==
null){
2666 $inventoryManager->onCurrentWindowRemove();
2668 $this->currentWindow =
null;
2669 (
new InventoryCloseEvent($currentWindow, $this))->call();
2673 protected function addPermanentInventories(Inventory ...$inventories) : void{
2674 foreach($inventories as $inventory){
2675 $inventory->onOpen($this);
2676 $this->permanentWindows[spl_object_id($inventory)] = $inventory;
2680 protected function removePermanentInventories() : void{
2681 foreach($this->permanentWindows as $inventory){
2682 $inventory->onClose($this);
2684 $this->permanentWindows = [];
2692 $block = $this->getWorld()->getBlock($position);
2694 $this->getWorld()->setBlock($position, $block->setEditorEntityRuntimeId($this->getId()));
2695 $this->getNetworkSession()->onOpenSignEditor($position,
true);
2697 throw new \InvalidArgumentException(
"Block at this position is not a sign");
2701 use ChunkListenerNoOpTrait {
2702 onChunkChanged as
private;
2703 onChunkUnloaded as
private;
2707 $status = $this->usedChunks[$hash =
World::chunkHash($chunkX, $chunkZ)] ?? null;
2708 if($status === UsedChunkStatus::SENT){
2709 $this->usedChunks[$hash] = UsedChunkStatus::NEEDED;
2710 $this->nextChunkOrderRun = 0;
2715 if($this->isUsingChunk($chunkX, $chunkZ)){
2716 $this->logger->debug(
"Detected forced unload of chunk " . $chunkX .
" " . $chunkZ);
2717 $this->unloadChunk($chunkX, $chunkZ);
onInteract(Player $player, Vector3 $clickPos)
setString(string $name, string $value)
setInt(string $name, int $value)
setLong(string $name, int $value)
interactBlock(Vector3 $pos, int $face, Vector3 $clickOffset)
setCreativeInventory(CreativeInventory $inventory)
hasItemCooldown(Item $item)
processMostRecentMovements()
attackBlock(Vector3 $pos, int $face)
isUsingChunk(int $chunkX, int $chunkZ)
setScreenLineHeight(?int $height)
setCanSaveWithChunk(bool $value)
kick(Translatable|string $reason="", Translatable|string|null $quitMessage=null, Translatable|string|null $disconnectScreenMessage=null)
teleport(Vector3 $pos, ?float $yaw=null, ?float $pitch=null)
applyPostDamageEffects(EntityDamageEvent $source)
setAllowFlight(bool $value)
initHumanData(CompoundTag $nbt)
getItemCooldownExpiry(Item $item)
sendTitle(string $title, string $subtitle="", int $fadeIn=-1, int $stay=-1, int $fadeOut=-1)
transfer(string $address, int $port=19132, Translatable|string|null $message=null)
changeSkin(Skin $skin, string $newSkinName, string $oldSkinName)
broadcastAnimation(Animation $animation, ?array $targets=null)
sendMessage(Translatable|string $message)
hasReceivedChunk(int $chunkX, int $chunkZ)
static isValidUserName(?string $name)
openSignEditor(Vector3 $position)
attackEntity(Entity $entity)
onDeathUpdate(int $tickDiff)
sendToastNotification(string $title, string $body)
resetItemCooldown(Item $item, ?int $ticks=null)
setTitleDuration(int $fadeIn, int $stay, int $fadeOut)
sendPosition(Vector3 $pos, ?float $yaw=null, ?float $pitch=null, int $mode=MovePlayerPacket::MODE_NORMAL)
onChunkUnloaded as onChunkChanged(int $chunkX, int $chunkZ, Chunk $chunk)
setCurrentWindow(Inventory $inventory)
sendData(?array $targets, ?array $data=null)
isCreative(bool $literal=false)
onChunkUnloaded(int $chunkX, int $chunkZ, Chunk $chunk)
sendActionBarMessage(string $message)
sendPopup(string $message)
isAdventure(bool $literal=false)
canInteract(Vector3 $pos, float $maxDistance, float $maxDiff=M_SQRT3/2)
broadcastSound(Sound $sound, ?array $targets=null)
getUsedChunkStatus(int $chunkX, int $chunkZ)
interactEntity(Entity $entity, Vector3 $clickPos)
sendSkin(?array $targets=null)
isSurvival(bool $literal=false)
disconnect(Translatable|string $reason, Translatable|string|null $quitMessage=null, Translatable|string|null $disconnectScreenMessage=null)
handleMovement(Vector3 $newPos)
setHasBlockCollision(bool $value)
setGamemode(GameMode $gm)
sendSubTitle(string $subtitle)
static clean(string $string, bool $removeFormat=true)
static chunkHash(int $x, int $z)