171 use PermissibleDelegateTrait;
173 private const MOVES_PER_TICK = 2;
174 private const MOVE_BACKLOG_SIZE = 100 * self::MOVES_PER_TICK;
177 private const MAX_CHAT_CHAR_LENGTH = 512;
183 private const MAX_CHAT_BYTE_LENGTH = self::MAX_CHAT_CHAR_LENGTH * 4;
184 private const MAX_REACH_DISTANCE_CREATIVE = 13;
185 private const MAX_REACH_DISTANCE_SURVIVAL = 7;
186 private const MAX_REACH_DISTANCE_ENTITY_INTERACTION = 8;
188 public const TAG_FIRST_PLAYED =
"firstPlayed";
189 public const TAG_LAST_PLAYED =
"lastPlayed";
190 private const TAG_GAME_MODE =
"playerGameType";
191 private const TAG_SPAWN_WORLD =
"SpawnLevel";
192 private const TAG_SPAWN_X =
"SpawnX";
193 private const TAG_SPAWN_Y =
"SpawnY";
194 private const TAG_SPAWN_Z =
"SpawnZ";
195 public const TAG_LEVEL =
"Level";
196 public const TAG_LAST_KNOWN_XUID =
"LastKnownXUID";
206 $lname = strtolower($name);
207 $len = strlen($name);
208 return $lname !==
"rcon" && $lname !==
"console" && $len >= 1 && $len <= 16 && preg_match(
"/[^A-Za-z0-9_ ]/", $name) === 0;
213 public bool $spawned =
false;
215 protected string $username;
216 protected string $displayName;
217 protected string $xuid =
"";
218 protected bool $authenticated;
221 protected ?Inventory $currentWindow =
null;
223 protected array $permanentWindows = [];
224 protected PlayerCursorInventory $cursorInventory;
225 protected PlayerCraftingInventory $craftingGrid;
226 protected CreativeInventory $creativeInventory;
228 protected int $messageCounter = 2;
230 protected DateTimeImmutable $firstPlayed;
231 protected DateTimeImmutable $lastPlayed;
232 protected GameMode $gamemode;
238 protected array $usedChunks = [];
243 private array $activeChunkGenerationRequests = [];
248 protected array $loadQueue = [];
249 protected int $nextChunkOrderRun = 5;
252 private array $tickingChunks = [];
254 protected int $viewDistance = -1;
255 protected int $spawnThreshold;
256 protected int $spawnChunkLoadCount = 0;
257 protected int $chunksPerTick;
258 protected ChunkSelector $chunkSelector;
259 protected ChunkLoader $chunkLoader;
260 protected ChunkTicker $chunkTicker;
263 protected array $hiddenPlayers = [];
265 protected float $moveRateLimit = 10 * self::MOVES_PER_TICK;
266 protected ?
float $lastMovementProcess =
null;
268 protected int $inAirTicks = 0;
270 protected float $stepHeight = 0.6;
272 protected ?Vector3 $sleeping =
null;
273 private ?
Position $spawnPosition =
null;
275 private bool $respawnLocked =
false;
278 protected bool $autoJump =
true;
279 protected bool $allowFlight =
false;
280 protected bool $blockCollision =
true;
281 protected bool $flying =
false;
284 protected ?
int $lineHeight =
null;
285 protected string $locale =
"en_US";
287 protected int $startAction = -1;
293 protected array $usedItemsCooldown = [];
295 private int $lastEmoteTick = 0;
297 protected int $formIdCounter = 0;
299 protected array $forms = [];
301 protected \Logger $logger;
306 $username = TextFormat::clean($playerInfo->getUsername());
307 $this->logger = new \PrefixedLogger($server->getLogger(),
"Player: $username");
310 $this->networkSession = $session;
311 $this->playerInfo = $playerInfo;
312 $this->authenticated = $authenticated;
314 $this->username = $username;
315 $this->displayName = $this->username;
316 $this->locale = $this->playerInfo->getLocale();
318 $this->uuid = $this->playerInfo->getUuid();
319 $this->xuid = $this->playerInfo instanceof
XboxLivePlayerInfo ? $this->playerInfo->getXuid() :
"";
321 $this->creativeInventory = CreativeInventory::getInstance();
323 $rootPermissions = [DefaultPermissions::ROOT_USER =>
true];
324 if($this->
server->isOp($this->username)){
325 $rootPermissions[DefaultPermissions::ROOT_OPERATOR] =
true;
328 $this->chunksPerTick = $this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_PER_TICK, 4);
329 $this->spawnThreshold = (int) (($this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4) ** 2) * M_PI);
332 $this->chunkLoader =
new class implements
ChunkLoader{};
334 $world = $spawnLocation->
getWorld();
336 $xSpawnChunk = $spawnLocation->getFloorX() >> Chunk::COORD_BIT_SIZE;
337 $zSpawnChunk = $spawnLocation->getFloorZ() >> Chunk::COORD_BIT_SIZE;
338 $world->registerChunkLoader($this->chunkLoader, $xSpawnChunk, $zSpawnChunk,
true);
339 $world->registerChunkListener($this, $xSpawnChunk, $zSpawnChunk);
340 $this->usedChunks[World::chunkHash($xSpawnChunk, $zSpawnChunk)] = UsedChunkStatus::NEEDED;
342 parent::__construct($spawnLocation, $this->playerInfo->getSkin(), $namedtag);
346 $this->setNameTag($this->username);
349 private function callDummyItemHeldEvent() : void{
350 $slot = $this->inventory->getHeldItemIndex();
359 protected function initEntity(
CompoundTag $nbt) : void{
360 parent::initEntity($nbt);
361 $this->addDefaultWindows();
363 $this->inventory->getListeners()->add(
new CallbackInventoryListener(
364 function(Inventory $unused,
int $slot) :
void{
365 if($slot === $this->inventory->getHeldItemIndex()){
366 $this->setUsingItem(
false);
368 $this->callDummyItemHeldEvent();
372 $this->setUsingItem(
false);
373 $this->callDummyItemHeldEvent();
377 $now = (int) (microtime(
true) * 1000);
378 $createDateTimeImmutable =
static function(
string $tag) use ($nbt, $now) : DateTimeImmutable{
379 return new DateTimeImmutable(
'@' . $nbt->getLong($tag, $now) / 1000);
381 $this->firstPlayed = $createDateTimeImmutable(self::TAG_FIRST_PLAYED);
382 $this->lastPlayed = $createDateTimeImmutable(self::TAG_LAST_PLAYED);
384 if(!$this->
server->getForceGamemode() && ($gameModeTag = $nbt->
getTag(self::TAG_GAME_MODE)) instanceof IntTag){
385 $this->internalSetGameMode(GameModeIdMap::getInstance()->fromId($gameModeTag->getValue()) ?? GameMode::SURVIVAL);
387 $this->internalSetGameMode($this->
server->getGamemode());
390 $this->keepMovement =
true;
392 $this->setNameTagVisible();
393 $this->setNameTagAlwaysVisible();
394 $this->setCanClimb();
396 if(($world = $this->
server->getWorldManager()->getWorldByName($nbt->getString(self::TAG_SPAWN_WORLD,
""))) instanceof World){
397 $this->spawnPosition =
new Position($nbt->getInt(self::TAG_SPAWN_X), $nbt->getInt(self::TAG_SPAWN_Y), $nbt->getInt(self::TAG_SPAWN_Z), $world);
401 public function getLeaveMessage() : Translatable|string{
403 return KnownTranslationFactory::multiplayer_player_left($this->getDisplayName())->prefix(TextFormat::YELLOW);
409 public function isAuthenticated() : bool{
410 return $this->authenticated;
435 return parent::getUniqueId();
442 return $this->firstPlayed;
449 return $this->lastPlayed;
452 public function hasPlayedBefore() : bool{
453 return ((int) $this->firstPlayed->diff($this->lastPlayed)->format(
'%s')) > 1;
466 if($this->allowFlight !== $value){
467 $this->allowFlight = $value;
468 $this->getNetworkSession()->syncAbilities($this);
479 return $this->allowFlight;
491 if($this->blockCollision !== $value){
492 $this->blockCollision = $value;
493 $this->getNetworkSession()->syncAbilities($this);
502 return $this->blockCollision;
505 public function setFlying(
bool $value) : void{
506 if($this->flying !== $value){
507 $this->flying = $value;
508 $this->resetFallDistance();
509 $this->getNetworkSession()->syncAbilities($this);
513 public function isFlying() : bool{
514 return $this->flying;
517 public function setAutoJump(
bool $value) : void{
518 if($this->autoJump !== $value){
519 $this->autoJump = $value;
520 $this->getNetworkSession()->syncAdventureSettings();
524 public function hasAutoJump() : bool{
525 return $this->autoJump;
528 public function spawnTo(Player $player) : void{
529 if($this->isAlive() && $player->isAlive() && $player->canSee($this) && !$this->isSpectator()){
530 parent::spawnTo($player);
534 public function getServer() : Server{
539 return $this->lineHeight ?? 7;
543 if($height !== null && $height < 1){
544 throw new \InvalidArgumentException(
"Line height must be at least 1");
546 $this->lineHeight = $height;
549 public function canSee(
Player $player) : bool{
550 return !isset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
553 public function hidePlayer(Player $player) : void{
554 if($player === $this){
557 $this->hiddenPlayers[$player->getUniqueId()->getBytes()] =
true;
558 $player->despawnFrom($this);
561 public function showPlayer(Player $player) : void{
562 if($player === $this){
565 unset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
566 if($player->isOnline()){
567 $player->spawnTo($this);
571 public function canCollideWith(Entity $entity) : bool{
575 public function canBeCollidedWith() : bool{
576 return !$this->isSpectator() && parent::canBeCollidedWith();
579 public function resetFallDistance() : void{
580 parent::resetFallDistance();
581 $this->inAirTicks = 0;
584 public function getViewDistance() : int{
585 return $this->viewDistance;
588 public function setViewDistance(
int $distance) : void{
589 $newViewDistance = $this->
server->getAllowedViewDistance($distance);
591 if($newViewDistance !== $this->viewDistance){
592 $ev =
new PlayerViewDistanceChangeEvent($this, $this->viewDistance, $newViewDistance);
596 $this->viewDistance = $newViewDistance;
598 $this->spawnThreshold = (int) (min($this->viewDistance, $this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4)) ** 2 * M_PI);
600 $this->nextChunkOrderRun = 0;
602 $this->getNetworkSession()->syncViewAreaRadius($this->viewDistance);
604 $this->logger->debug(
"Setting view distance to " . $this->viewDistance .
" (requested " . $distance .
")");
607 public function isOnline() : bool{
608 return $this->isConnected();
611 public function isConnected() : bool{
612 return $this->networkSession !== null && $this->networkSession->isConnected();
615 public function getNetworkSession() : NetworkSession{
616 if($this->networkSession === null){
617 throw new \LogicException(
"Player is not connected");
619 return $this->networkSession;
626 return $this->username;
633 return $this->displayName;
636 public function setDisplayName(
string $name) : void{
640 $this->displayName = $ev->getNewName();
651 return $this->locale;
654 public function getLanguage() :
Language{
655 return $this->
server->getLanguage();
662 public function changeSkin(
Skin $skin,
string $newSkinName,
string $oldSkinName) : bool{
666 if($ev->isCancelled()){
667 $this->sendSkin([$this]);
671 $this->setSkin($ev->getNewSkin());
672 $this->sendSkin($this->server->getOnlinePlayers());
681 public function sendSkin(?array $targets =
null) : void{
682 parent::sendSkin($targets ?? $this->
server->getOnlinePlayers());
689 return $this->startAction > -1;
692 public function setUsingItem(
bool $value) : void{
693 $this->startAction = $value ? $this->
server->getTick() : -1;
694 $this->networkPropertiesDirty =
true;
702 return $this->startAction === -1 ? -1 : ($this->
server->getTick() - $this->startAction);
709 $this->checkItemCooldowns();
710 return $this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()] ?? 0;
717 $this->checkItemCooldowns();
718 return isset($this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()]);
725 $ticks = $ticks ?? $item->getCooldownTicks();
727 $this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()] = $this->
server->getTick() + $ticks;
728 $this->getNetworkSession()->onItemCooldownChanged($item, $ticks);
732 protected function checkItemCooldowns() : void{
733 $serverTick = $this->
server->getTick();
734 foreach($this->usedItemsCooldown as $itemId => $cooldownUntil){
735 if($cooldownUntil <= $serverTick){
736 unset($this->usedItemsCooldown[$itemId]);
741 protected function setPosition(Vector3 $pos) : bool{
742 $oldWorld = $this->location->isValid() ? $this->location->getWorld() : null;
743 if(parent::setPosition($pos)){
744 $newWorld = $this->getWorld();
745 if($oldWorld !== $newWorld){
746 if($oldWorld !==
null){
747 foreach($this->usedChunks as $index => $status){
748 World::getXZ($index, $X, $Z);
749 $this->unloadChunk($X, $Z, $oldWorld);
753 $this->usedChunks = [];
754 $this->loadQueue = [];
755 $this->getNetworkSession()->onEnterWorld();
764 protected function unloadChunk(
int $x,
int $z, ?World $world =
null) : void{
765 $world = $world ?? $this->getWorld();
766 $index = World::chunkHash($x, $z);
767 if(isset($this->usedChunks[$index])){
768 foreach($world->getChunkEntities($x, $z) as $entity){
769 if($entity !== $this){
770 $entity->despawnFrom($this);
773 $this->getNetworkSession()->stopUsingChunk($x, $z);
774 unset($this->usedChunks[$index]);
775 unset($this->activeChunkGenerationRequests[$index]);
777 $world->unregisterChunkLoader($this->chunkLoader, $x, $z);
778 $world->unregisterChunkListener($this, $x, $z);
779 unset($this->loadQueue[$index]);
780 $world->unregisterTickingChunk($this->chunkTicker, $x, $z);
781 unset($this->tickingChunks[$index]);
784 protected function spawnEntitiesOnAllChunks() : void{
785 foreach($this->usedChunks as $chunkHash => $status){
786 if($status === UsedChunkStatus::SENT){
787 World::getXZ($chunkHash, $chunkX, $chunkZ);
788 $this->spawnEntitiesOnChunk($chunkX, $chunkZ);
793 protected function spawnEntitiesOnChunk(
int $chunkX,
int $chunkZ) : void{
794 foreach($this->getWorld()->getChunkEntities($chunkX, $chunkZ) as $entity){
795 if($entity !== $this && !$entity->isFlaggedForDespawn()){
796 $entity->spawnTo($this);
806 if(!$this->isConnected()){
810 Timings::$playerChunkSend->startTiming();
813 $world = $this->getWorld();
815 $limit = $this->chunksPerTick - count($this->activeChunkGenerationRequests);
816 foreach($this->loadQueue as $index => $distance){
817 if($count >= $limit){
823 World::getXZ($index, $X, $Z);
824 assert(is_int($X) && is_int($Z));
828 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_GENERATION;
829 $this->activeChunkGenerationRequests[$index] =
true;
830 unset($this->loadQueue[$index]);
831 $world->registerChunkLoader($this->chunkLoader, $X, $Z,
true);
832 $world->registerChunkListener($this, $X, $Z);
833 if(isset($this->tickingChunks[$index])){
834 $world->registerTickingChunk($this->chunkTicker, $X, $Z);
837 $world->requestChunkPopulation($X, $Z, $this->chunkLoader)->onCompletion(
838 function() use ($X, $Z, $index, $world) :
void{
839 if(!$this->isConnected() || !isset($this->usedChunks[$index]) || $world !== $this->getWorld()){
842 if($this->usedChunks[$index] !== UsedChunkStatus::REQUESTED_GENERATION){
848 unset($this->activeChunkGenerationRequests[$index]);
849 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_SENDING;
851 $this->getNetworkSession()->startUsingChunk($X, $Z,
function() use ($X, $Z, $index) :
void{
852 $this->usedChunks[$index] = UsedChunkStatus::SENT;
853 if($this->spawnChunkLoadCount === -1){
854 $this->spawnEntitiesOnChunk($X, $Z);
855 }elseif($this->spawnChunkLoadCount++ === $this->spawnThreshold){
856 $this->spawnChunkLoadCount = -1;
858 $this->spawnEntitiesOnAllChunks();
860 $this->getNetworkSession()->notifyTerrainReady();
862 (
new PlayerPostChunkSendEvent($this, $X, $Z))->call();
865 static function() :
void{
871 Timings::$playerChunkSend->stopTiming();
874 private function recheckBroadcastPermissions() : void{
876 DefaultPermissionNames::BROADCAST_ADMIN => Server::BROADCAST_CHANNEL_ADMINISTRATIVE,
877 DefaultPermissionNames::BROADCAST_USER => Server::BROADCAST_CHANNEL_USERS
878 ] as $permission => $channel){
879 if($this->hasPermission($permission)){
880 $this->
server->subscribeToBroadcastChannel($channel, $this);
882 $this->
server->unsubscribeFromBroadcastChannel($channel, $this);
895 $this->spawned =
true;
896 $this->recheckBroadcastPermissions();
897 $this->getPermissionRecalculationCallbacks()->add(
function(array $changedPermissionsOldValues) :
void{
898 if(isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_ADMINISTRATIVE]) || isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_USERS])){
899 $this->recheckBroadcastPermissions();
903 $ev =
new PlayerJoinEvent($this,
904 KnownTranslationFactory::multiplayer_player_joined($this->getDisplayName())->prefix(TextFormat::YELLOW)
907 if($ev->getJoinMessage() !==
""){
908 $this->server->broadcastMessage($ev->getJoinMessage());
911 $this->noDamageTicks = 60;
915 if($this->getHealth() <= 0){
916 $this->logger->debug(
"Quit while dead, forcing respawn");
917 $this->actuallyRespawn();
928 private function updateTickingChunkRegistrations(array $oldTickingChunks, array $newTickingChunks) : void{
929 $world = $this->getWorld();
930 foreach($oldTickingChunks as $hash => $_){
931 if(!isset($newTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
933 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
934 $world->unregisterTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
937 foreach($newTickingChunks as $hash => $_){
938 if(!isset($oldTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
940 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
941 $world->registerTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
951 if(!$this->isConnected() || $this->viewDistance === -1){
955 Timings::$playerChunkOrder->startTiming();
959 $unloadChunks = $this->usedChunks;
961 $world = $this->getWorld();
962 $tickingChunkRadius = $world->getChunkTickRadius();
964 foreach($this->chunkSelector->selectChunks(
965 $this->server->getAllowedViewDistance($this->viewDistance),
966 $this->location->getFloorX() >> Chunk::COORD_BIT_SIZE,
967 $this->location->getFloorZ() >> Chunk::COORD_BIT_SIZE
968 ) as $radius => $hash){
969 if(!isset($this->usedChunks[$hash]) || $this->usedChunks[$hash] === UsedChunkStatus::NEEDED){
970 $newOrder[$hash] =
true;
972 if($radius < $tickingChunkRadius){
973 $tickingChunks[$hash] =
true;
975 unset($unloadChunks[$hash]);
978 foreach($unloadChunks as $index => $status){
979 World::getXZ($index, $X, $Z);
980 $this->unloadChunk($X, $Z);
983 $this->loadQueue = $newOrder;
985 $this->updateTickingChunkRegistrations($this->tickingChunks, $tickingChunks);
986 $this->tickingChunks = $tickingChunks;
988 if(count($this->loadQueue) > 0 || count($unloadChunks) > 0){
989 $this->getNetworkSession()->syncViewAreaCenterPoint($this->location, $this->viewDistance);
992 Timings::$playerChunkOrder->stopTiming();
1000 return isset($this->usedChunks[
World::chunkHash($chunkX, $chunkZ)]);
1008 return $this->usedChunks;
1015 return $this->usedChunks[
World::chunkHash($chunkX, $chunkZ)] ?? null;
1022 $status = $this->usedChunks[
World::chunkHash($chunkX, $chunkZ)] ?? null;
1023 return $status === UsedChunkStatus::SENT;
1030 if($this->nextChunkOrderRun !== PHP_INT_MAX && $this->nextChunkOrderRun-- <= 0){
1031 $this->nextChunkOrderRun = PHP_INT_MAX;
1032 $this->orderChunks();
1035 if(count($this->loadQueue) > 0){
1036 $this->requestChunks();
1044 if($this->hasValidCustomSpawn()){
1045 return $this->spawnPosition;
1047 $world = $this->
server->getWorldManager()->getDefaultWorld();
1049 return $world->getSpawnLocation();
1053 public function hasValidCustomSpawn() : bool{
1054 return $this->spawnPosition !== null && $this->spawnPosition->isValid();
1066 $world = $this->getWorld();
1068 $world = $pos->getWorld();
1070 $this->spawnPosition =
new Position($pos->x, $pos->y, $pos->z, $world);
1072 $this->spawnPosition =
null;
1074 $this->getNetworkSession()->syncPlayerSpawnPoint($this->getSpawn());
1077 public function isSleeping() : bool{
1078 return $this->sleeping !== null;
1081 public function sleepOn(Vector3 $pos) : bool{
1082 $pos = $pos->floor();
1083 $b = $this->getWorld()->getBlock($pos);
1085 $ev =
new PlayerBedEnterEvent($this, $b);
1087 if($ev->isCancelled()){
1091 if($b instanceof Bed){
1093 $this->getWorld()->setBlock($pos, $b);
1096 $this->sleeping = $pos;
1097 $this->networkPropertiesDirty =
true;
1099 $this->setSpawn($pos);
1101 $this->getWorld()->setSleepTicks(60);
1106 public function stopSleep() : void{
1107 if($this->sleeping instanceof Vector3){
1108 $b = $this->getWorld()->getBlock($this->sleeping);
1109 if($b instanceof Bed){
1110 $b->setOccupied(
false);
1111 $this->getWorld()->setBlock($this->sleeping, $b);
1113 (
new PlayerBedLeaveEvent($this, $b))->call();
1115 $this->sleeping =
null;
1116 $this->networkPropertiesDirty =
true;
1118 $this->getWorld()->setSleepTicks(0);
1120 $this->getNetworkSession()->sendDataPacket(AnimatePacket::create($this->getId(), AnimatePacket::ACTION_STOP_SLEEP));
1124 public function getGamemode() : GameMode{
1125 return $this->gamemode;
1128 protected function internalSetGameMode(GameMode $gameMode) : void{
1129 $this->gamemode = $gameMode;
1131 $this->allowFlight = $this->gamemode === GameMode::CREATIVE;
1132 $this->hungerManager->setEnabled($this->isSurvival());
1134 if($this->isSpectator()){
1135 $this->setFlying(
true);
1136 $this->setHasBlockCollision(
false);
1138 $this->onGround =
false;
1142 $this->sendPosition($this->location,
null,
null, MovePlayerPacket::MODE_TELEPORT);
1144 if($this->isSurvival()){
1145 $this->setFlying(
false);
1147 $this->setHasBlockCollision(
true);
1148 $this->setSilent(
false);
1149 $this->checkGroundState(0, 0, 0, 0, 0, 0);
1157 if($this->gamemode === $gm){
1163 if($ev->isCancelled()){
1167 $this->internalSetGameMode($gm);
1169 if($this->isSpectator()){
1170 $this->despawnFromAll();
1172 $this->spawnToAll();
1175 $this->getNetworkSession()->syncGameMode($this->gamemode);
1186 return $this->gamemode === GameMode::SURVIVAL || (!$literal && $this->gamemode === GameMode::ADVENTURE);
1196 return $this->gamemode === GameMode::CREATIVE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1206 return $this->gamemode === GameMode::ADVENTURE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1209 public function isSpectator() : bool{
1210 return $this->gamemode === GameMode::SPECTATOR;
1217 return $this->gamemode !== GameMode::CREATIVE;
1221 if($this->hasFiniteResources()){
1222 return parent::getDrops();
1229 if($this->hasFiniteResources()){
1230 return parent::getXpDropAmount();
1236 protected function checkGroundState(
float $wantedX,
float $wantedY,
float $wantedZ,
float $dx,
float $dy,
float $dz) : void{
1237 if($this->gamemode === GameMode::SPECTATOR){
1238 $this->onGround =
false;
1240 $bb = clone $this->boundingBox;
1241 $bb->minY = $this->location->y - 0.2;
1242 $bb->maxY = $this->location->y + 0.2;
1246 $bb = $bb->addCoord(-$dx, -$dy, -$dz);
1248 $this->onGround = $this->isCollided = count($this->getWorld()->getCollisionBlocks($bb,
true)) > 0;
1256 protected function checkNearEntities() : void{
1257 foreach($this->getWorld()->getNearbyEntities($this->boundingBox->expandedCopy(1, 0.5, 1), $this) as $entity){
1258 $entity->scheduleUpdate();
1260 if(!$entity->isAlive() || $entity->isFlaggedForDespawn()){
1264 $entity->onCollideWithPlayer($this);
1268 public function getInAirTicks() : int{
1269 return $this->inAirTicks;
1281 Timings::$playerMove->startTiming();
1283 $this->actuallyHandleMovement($newPos);
1285 Timings::$playerMove->stopTiming();
1289 private function actuallyHandleMovement(Vector3 $newPos) : void{
1290 $this->moveRateLimit--;
1291 if($this->moveRateLimit < 0){
1295 $oldPos = $this->location;
1296 $distanceSquared = $newPos->distanceSquared($oldPos);
1300 if($distanceSquared > 225){
1312 $this->logger->debug(
"Moved too fast (" . sqrt($distanceSquared) .
" blocks in 1 movement), reverting movement");
1313 $this->logger->debug(
"Old position: " . $oldPos->asVector3() .
", new position: " . $newPos);
1315 }elseif(!$this->getWorld()->isInLoadedTerrain($newPos)){
1317 $this->nextChunkOrderRun = 0;
1320 if(!$revert && $distanceSquared != 0){
1321 $dx = $newPos->x - $oldPos->x;
1322 $dy = $newPos->y - $oldPos->y;
1323 $dz = $newPos->z - $oldPos->z;
1325 $this->move($dx, $dy, $dz);
1329 $this->revertMovement($oldPos);
1337 $now = microtime(true);
1338 $multiplier = $this->lastMovementProcess !==
null ? ($now - $this->lastMovementProcess) * 20 : 1;
1339 $exceededRateLimit = $this->moveRateLimit < 0;
1340 $this->moveRateLimit = min(self::MOVE_BACKLOG_SIZE, max(0, $this->moveRateLimit) + self::MOVES_PER_TICK * $multiplier);
1341 $this->lastMovementProcess = $now;
1343 $from = clone $this->lastLocation;
1344 $to = clone $this->location;
1346 $delta = $to->distanceSquared($from);
1347 $deltaAngle = abs($this->lastLocation->yaw - $to->yaw) + abs($this->lastLocation->pitch - $to->pitch);
1349 if($delta > 0.0001 || $deltaAngle > 1.0){
1350 if(PlayerMoveEvent::hasHandlers()){
1355 if($ev->isCancelled()){
1356 $this->revertMovement($from);
1360 if($to->distanceSquared($ev->getTo()) > 0.01){
1361 $this->teleport($ev->getTo());
1366 $this->lastLocation = $to;
1367 $this->broadcastMovement();
1369 $horizontalDistanceTravelled = sqrt((($from->x - $to->x) ** 2) + (($from->z - $to->z) ** 2));
1370 if($horizontalDistanceTravelled > 0){
1372 if($this->isSprinting()){
1373 $this->hungerManager->exhaust(0.01 * $horizontalDistanceTravelled, PlayerExhaustEvent::CAUSE_SPRINTING);
1375 $this->hungerManager->exhaust(0.0, PlayerExhaustEvent::CAUSE_WALKING);
1378 if($this->nextChunkOrderRun > 20){
1379 $this->nextChunkOrderRun = 20;
1384 if($exceededRateLimit){
1385 $this->logger->debug(
"Exceeded movement rate limit, forcing to last accepted position");
1386 $this->sendPosition($this->location, $this->location->getYaw(), $this->location->getPitch(), MovePlayerPacket::MODE_RESET);
1390 protected function revertMovement(Location $from) : void{
1391 $this->setPosition($from);
1392 $this->sendPosition($from, $from->yaw, $from->pitch, MovePlayerPacket::MODE_RESET);
1395 protected function calculateFallDamage(
float $fallDistance) : float{
1396 return $this->flying ? 0 : parent::calculateFallDamage($fallDistance);
1404 public function setMotion(
Vector3 $motion) : bool{
1405 if(parent::setMotion($motion)){
1406 $this->broadcastMotion();
1407 $this->getNetworkSession()->sendDataPacket(SetActorMotionPacket::create($this->
id, $motion, tick: 0));
1414 protected function updateMovement(
bool $teleport =
false) : void{
1418 protected function tryChangeMovement() : void{
1422 public function onUpdate(int $currentTick) : bool{
1423 $tickDiff = $currentTick - $this->lastUpdate;
1429 $this->messageCounter = 2;
1431 $this->lastUpdate = $currentTick;
1433 if($this->justCreated){
1434 $this->onFirstUpdate($currentTick);
1437 if(!$this->isAlive() && $this->spawned){
1438 $this->onDeathUpdate($tickDiff);
1442 $this->timings->startTiming();
1445 Timings::$playerMove->startTiming();
1446 $this->processMostRecentMovements();
1447 $this->motion = Vector3::zero();
1448 if($this->onGround){
1449 $this->inAirTicks = 0;
1451 $this->inAirTicks += $tickDiff;
1453 Timings::$playerMove->stopTiming();
1455 Timings::$entityBaseTick->startTiming();
1456 $this->entityBaseTick($tickDiff);
1457 Timings::$entityBaseTick->stopTiming();
1459 if($this->isCreative() && $this->fireTicks > 1){
1460 $this->fireTicks = 1;
1463 if(!$this->isSpectator() && $this->isAlive()){
1464 Timings::$playerCheckNearEntities->startTiming();
1465 $this->checkNearEntities();
1466 Timings::$playerCheckNearEntities->stopTiming();
1469 if($this->blockBreakHandler !==
null && !$this->blockBreakHandler->update()){
1470 $this->blockBreakHandler =
null;
1474 $this->timings->stopTiming();
1480 return $this->isCreative() || parent::canBreathe();
1489 $eyePos = $this->getEyePos();
1490 if($eyePos->distanceSquared($pos) > $maxDistance ** 2){
1494 $dV = $this->getDirectionVector();
1495 $eyeDot = $dV->dot($eyePos);
1496 $targetDot = $dV->dot($pos);
1497 return ($targetDot - $eyeDot) >= -$maxDiff;
1504 public function chat(
string $message) : bool{
1505 $this->removeCurrentWindow();
1507 if($this->messageCounter <= 0){
1513 $maxTotalLength = $this->messageCounter * (self::MAX_CHAT_BYTE_LENGTH + 1);
1514 if(strlen($message) > $maxTotalLength){
1518 $message = TextFormat::clean($message,
false);
1519 foreach(explode(
"\n", $message, $this->messageCounter + 1) as $messagePart){
1520 if(trim($messagePart) !==
"" && strlen($messagePart) <= self::MAX_CHAT_BYTE_LENGTH && mb_strlen($messagePart,
'UTF-8') <= self::MAX_CHAT_CHAR_LENGTH && $this->messageCounter-- > 0){
1521 if(str_starts_with($messagePart,
'./')){
1522 $messagePart = substr($messagePart, 1);
1525 if(str_starts_with($messagePart,
"/")){
1526 Timings::$playerCommand->startTiming();
1527 $this->server->dispatchCommand($this, substr($messagePart, 1));
1528 Timings::$playerCommand->stopTiming();
1530 $ev =
new PlayerChatEvent($this, $messagePart, $this->
server->getBroadcastChannelSubscribers(Server::BROADCAST_CHANNEL_USERS),
new StandardChatFormatter());
1532 if(!$ev->isCancelled()){
1533 $this->
server->broadcastMessage($ev->getFormatter()->format($ev->getPlayer()->getDisplayName(), $ev->getMessage()), $ev->getRecipients());
1542 public function selectHotbarSlot(
int $hotbarSlot) : bool{
1543 if(!$this->inventory->isHotbarSlot($hotbarSlot)){
1546 if($hotbarSlot === $this->inventory->getHeldItemIndex()){
1550 $ev =
new PlayerItemHeldEvent($this, $this->inventory->getItem($hotbarSlot), $hotbarSlot);
1552 if($ev->isCancelled()){
1556 $this->inventory->setHeldItemIndex($hotbarSlot);
1557 $this->setUsingItem(
false);
1565 private function returnItemsFromAction(Item $oldHeldItem, Item $newHeldItem, array $extraReturnedItems) : void{
1566 $heldItemChanged = false;
1568 if(!$newHeldItem->equalsExact($oldHeldItem) && $oldHeldItem->equalsExact($this->inventory->getItemInHand())){
1571 $newReplica = clone $oldHeldItem;
1572 $newReplica->setCount($newHeldItem->getCount());
1573 if($newReplica instanceof Durable && $newHeldItem instanceof Durable){
1574 $newReplica->setDamage($newHeldItem->getDamage());
1576 $damagedOrDeducted = $newReplica->equalsExact($newHeldItem);
1578 if(!$damagedOrDeducted || $this->hasFiniteResources()){
1579 if($newHeldItem instanceof Durable && $newHeldItem->isBroken()){
1580 $this->broadcastSound(
new ItemBreakSound());
1582 $this->inventory->setItemInHand($newHeldItem);
1583 $heldItemChanged =
true;
1587 if(!$heldItemChanged){
1588 $newHeldItem = $oldHeldItem;
1591 if($heldItemChanged && count($extraReturnedItems) > 0 && $newHeldItem->isNull()){
1592 $this->inventory->setItemInHand(array_shift($extraReturnedItems));
1594 foreach($this->inventory->addItem(...$extraReturnedItems) as $drop){
1596 $ev =
new PlayerDropItemEvent($this, $drop);
1597 if($this->isSpectator()){
1601 if(!$ev->isCancelled()){
1602 $this->dropItem($drop);
1613 $directionVector = $this->getDirectionVector();
1614 $item = $this->inventory->getItemInHand();
1615 $oldItem = clone $item;
1618 if($this->hasItemCooldown($item) || $this->isSpectator()){
1624 if($ev->isCancelled()){
1628 $returnedItems = [];
1629 $result = $item->onClickAir($this, $directionVector, $returnedItems);
1630 if($result === ItemUseResult::FAIL){
1634 $this->resetItemCooldown($oldItem);
1635 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1637 $this->setUsingItem($item instanceof Releasable && $item->canStartUsingItem($this));
1648 $slot = $this->inventory->getItemInHand();
1650 $oldItem = clone $slot;
1653 if($this->hasItemCooldown($slot)){
1658 if($ev->isCancelled() || !$this->consumeObject($slot)){
1662 $this->setUsingItem(
false);
1663 $this->resetItemCooldown($oldItem);
1666 $this->returnItemsFromAction($oldItem, $slot, [$slot->getResidue()]);
1681 $item = $this->inventory->getItemInHand();
1682 if(!$this->isUsingItem() || $this->hasItemCooldown($item)){
1686 $oldItem = clone $item;
1688 $returnedItems = [];
1689 $result = $item->onReleaseUsing($this, $returnedItems);
1690 if($result === ItemUseResult::SUCCESS){
1691 $this->resetItemCooldown($oldItem);
1692 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1698 $this->setUsingItem(
false);
1702 public function pickBlock(Vector3 $pos,
bool $addTileNBT) : bool{
1703 $block = $this->getWorld()->getBlock($pos);
1704 if($block instanceof UnknownBlock){
1708 $item = $block->getPickedItem($addTileNBT);
1710 $ev =
new PlayerBlockPickEvent($this, $block, $item);
1711 $existingSlot = $this->inventory->first($item);
1712 if($existingSlot === -1 && $this->hasFiniteResources()){
1717 if(!$ev->isCancelled()){
1718 $this->equipOrAddPickedItem($existingSlot, $item);
1724 public function pickEntity(
int $entityId) : bool{
1725 $entity = $this->getWorld()->getEntity($entityId);
1726 if($entity ===
null){
1730 $item = $entity->getPickedItem();
1735 $ev =
new PlayerEntityPickEvent($this, $entity, $item);
1736 $existingSlot = $this->inventory->first($item);
1737 if($existingSlot === -1 && ($this->hasFiniteResources() || $this->isSpectator())){
1742 if(!$ev->isCancelled()){
1743 $this->equipOrAddPickedItem($existingSlot, $item);
1749 private function equipOrAddPickedItem(
int $existingSlot, Item $item) : void{
1750 if($existingSlot !== -1){
1751 if($existingSlot < $this->inventory->getHotbarSize()){
1752 $this->inventory->setHeldItemIndex($existingSlot);
1754 $this->inventory->swap($this->inventory->getHeldItemIndex(), $existingSlot);
1757 $firstEmpty = $this->inventory->firstEmpty();
1758 if($firstEmpty === -1){
1759 $this->inventory->setItemInHand($item);
1760 }elseif($firstEmpty < $this->inventory->getHotbarSize()){
1761 $this->inventory->setItem($firstEmpty, $item);
1762 $this->inventory->setHeldItemIndex($firstEmpty);
1764 $this->inventory->swap($this->inventory->getHeldItemIndex(), $firstEmpty);
1765 $this->inventory->setItemInHand($item);
1776 if($pos->distanceSquared($this->location) > 10000){
1780 $target = $this->getWorld()->getBlock($pos);
1782 $ev =
new PlayerInteractEvent($this, $this->inventory->getItemInHand(), $target,
null, $face, PlayerInteractEvent::LEFT_CLICK_BLOCK);
1783 if($this->isSpectator()){
1787 if($ev->isCancelled()){
1790 $this->broadcastAnimation(
new ArmSwingAnimation($this), $this->getViewers());
1791 if($target->onAttack($this->inventory->getItemInHand(), $face, $this)){
1795 $block = $target->getSide($face);
1796 if($block->hasTypeTag(BlockTypeTags::FIRE)){
1797 $this->getWorld()->setBlock($block->getPosition(), VanillaBlocks::AIR());
1798 $this->getWorld()->addSound($block->getPosition()->add(0.5, 0.5, 0.5),
new FireExtinguishSound());
1802 if(!$this->isCreative() && !$block->getBreakInfo()->breaksInstantly()){
1803 $this->blockBreakHandler =
new SurvivalBlockBreakHandler($this, $pos, $target, $face, 16);
1809 public function continueBreakBlock(Vector3 $pos,
int $face) : void{
1810 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1811 $this->blockBreakHandler->setTargetedFace($face);
1815 public function stopBreakBlock(Vector3 $pos) : void{
1816 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1817 $this->blockBreakHandler =
null;
1827 $this->removeCurrentWindow();
1829 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1830 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1831 $this->stopBreakBlock($pos);
1832 $item = $this->inventory->getItemInHand();
1833 $oldItem = clone $item;
1834 $returnedItems = [];
1835 if($this->getWorld()->useBreakOn($pos, $item, $this, true, $returnedItems)){
1836 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1837 $this->hungerManager->exhaust(0.005, PlayerExhaustEvent::CAUSE_MINING);
1841 $this->logger->debug(
"Cancelled block break at $pos due to not currently being interactable");
1853 $this->setUsingItem(false);
1855 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1856 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1857 $item = $this->inventory->getItemInHand();
1858 $oldItem = clone $item;
1859 $returnedItems = [];
1860 if($this->getWorld()->useItemOn($pos, $item, $face, $clickOffset, $this, true, $returnedItems)){
1861 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1865 $this->logger->debug(
"Cancelled interaction of block at $pos due to not currently being interactable");
1878 if(!$entity->isAlive()){
1882 $this->logger->debug(
"Attempted to attack non-attackable entity " . get_class($entity));
1886 $heldItem = $this->inventory->getItemInHand();
1887 $oldItem = clone $heldItem;
1889 $ev =
new EntityDamageByEntityEvent($this, $entity, EntityDamageEvent::CAUSE_ENTITY_ATTACK, $heldItem->getAttackPoints());
1890 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
1891 $this->logger->debug(
"Cancelled attack of entity " . $entity->getId() .
" due to not currently being interactable");
1893 }elseif($this->isSpectator() || ($entity instanceof Player && !$this->server->getConfigGroup()->getConfigBool(ServerProperties::PVP))){
1897 $meleeEnchantmentDamage = 0;
1899 $meleeEnchantments = [];
1900 foreach($heldItem->getEnchantments() as $enchantment){
1901 $type = $enchantment->getType();
1902 if($type instanceof MeleeWeaponEnchantment && $type->isApplicableTo($entity)){
1903 $meleeEnchantmentDamage += $type->getDamageBonus($enchantment->getLevel());
1904 $meleeEnchantments[] = $enchantment;
1907 $ev->setModifier($meleeEnchantmentDamage, EntityDamageEvent::MODIFIER_WEAPON_ENCHANTMENTS);
1909 if(!$this->isSprinting() && !$this->isFlying() && $this->fallDistance > 0 && !$this->effectManager->has(VanillaEffects::BLINDNESS()) && !$this->isUnderwater()){
1910 $ev->setModifier($ev->getFinalDamage() / 2, EntityDamageEvent::MODIFIER_CRITICAL);
1913 $entity->attack($ev);
1914 $this->broadcastAnimation(
new ArmSwingAnimation($this), $this->getViewers());
1916 $soundPos = $entity->getPosition()->add(0, $entity->size->getHeight() / 2, 0);
1917 if($ev->isCancelled()){
1918 $this->getWorld()->addSound($soundPos,
new EntityAttackNoDamageSound());
1921 $this->getWorld()->addSound($soundPos,
new EntityAttackSound());
1923 if($ev->getModifier(EntityDamageEvent::MODIFIER_CRITICAL) > 0 && $entity instanceof Living){
1924 $entity->broadcastAnimation(
new CriticalHitAnimation($entity));
1927 foreach($meleeEnchantments as $enchantment){
1928 $type = $enchantment->getType();
1929 assert($type instanceof MeleeWeaponEnchantment);
1930 $type->onPostAttack($this, $entity, $enchantment->getLevel());
1933 if($this->isAlive()){
1936 $returnedItems = [];
1937 $heldItem->onAttackEntity($entity, $returnedItems);
1938 $this->returnItemsFromAction($oldItem, $heldItem, $returnedItems);
1940 $this->hungerManager->exhaust(0.1, PlayerExhaustEvent::CAUSE_ATTACK);
1953 if(!$ev->isCancelled()){
1954 $this->broadcastSound(new EntityAttackNoDamageSound());
1955 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1965 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
1966 $this->logger->debug(
"Cancelled interaction with entity " . $entity->getId() .
" due to not currently being interactable");
1972 $item = $this->inventory->getItemInHand();
1973 $oldItem = clone $item;
1974 if(!$ev->isCancelled()){
1975 if($item->onInteractEntity($this, $entity, $clickPos)){
1976 if($this->hasFiniteResources() && !$item->equalsExact($oldItem) && $oldItem->equalsExact($this->inventory->getItemInHand())){
1977 if($item instanceof Durable && $item->isBroken()){
1978 $this->broadcastSound(new ItemBreakSound());
1980 $this->inventory->setItemInHand($item);
1983 return $entity->
onInteract($this, $clickPos);
1988 public function toggleSprint(
bool $sprint) : bool{
1989 if($sprint === $this->sprinting){
1992 $ev =
new PlayerToggleSprintEvent($this, $sprint);
1994 if($ev->isCancelled()){
1997 $this->setSprinting($sprint);
2001 public function toggleSneak(
bool $sneak) : bool{
2002 if($sneak === $this->sneaking){
2005 $ev =
new PlayerToggleSneakEvent($this, $sneak);
2007 if($ev->isCancelled()){
2010 $this->setSneaking($sneak);
2014 public function toggleFlight(
bool $fly) : bool{
2015 if($fly === $this->flying){
2018 $ev =
new PlayerToggleFlightEvent($this, $fly);
2019 if(!$this->allowFlight){
2023 if($ev->isCancelled()){
2026 $this->setFlying($fly);
2030 public function toggleGlide(
bool $glide) : bool{
2031 if($glide === $this->gliding){
2034 $ev =
new PlayerToggleGlideEvent($this, $glide);
2036 if($ev->isCancelled()){
2039 $this->setGliding($glide);
2043 public function toggleSwim(
bool $swim) : bool{
2044 if($swim === $this->swimming){
2047 $ev =
new PlayerToggleSwimEvent($this, $swim);
2049 if($ev->isCancelled()){
2052 $this->setSwimming($swim);
2056 public function emote(
string $emoteId) : void{
2057 $currentTick = $this->
server->getTick();
2058 if($currentTick - $this->lastEmoteTick > 5){
2059 $this->lastEmoteTick = $currentTick;
2060 $event =
new PlayerEmoteEvent($this, $emoteId);
2062 if(!$event->isCancelled()){
2063 $emoteId = $event->getEmoteId();
2064 parent::emote($emoteId);
2074 $this->getWorld()->dropItem($this->location->add(0, 1.3, 0), $item, $this->getDirectionVector()->multiply(0.4), 40);
2084 public function sendTitle(
string $title,
string $subtitle =
"",
int $fadeIn = -1,
int $stay = -1,
int $fadeOut = -1) : void{
2085 $this->setTitleDuration($fadeIn, $stay, $fadeOut);
2086 if($subtitle !==
""){
2087 $this->sendSubTitle($subtitle);
2089 $this->getNetworkSession()->onTitle($title);
2096 $this->getNetworkSession()->onSubTitle($subtitle);
2103 $this->getNetworkSession()->onActionBar($message);
2110 $this->getNetworkSession()->onClearTitle();
2117 $this->getNetworkSession()->onResetTitleOptions();
2128 if($fadeIn >= 0 && $stay >= 0 && $fadeOut >= 0){
2129 $this->getNetworkSession()->onTitleDuration($fadeIn, $stay, $fadeOut);
2137 $this->getNetworkSession()->onChatMessage($message);
2140 public function sendJukeboxPopup(
Translatable|
string $message) : void{
2141 $this->getNetworkSession()->onJukeboxPopup($message);
2150 $this->getNetworkSession()->onPopup($message);
2153 public function sendTip(
string $message) : void{
2154 $this->getNetworkSession()->onTip($message);
2161 $this->getNetworkSession()->onToastNotification($title, $body);
2170 $id = $this->formIdCounter++;
2171 if($this->getNetworkSession()->onFormSent($id, $form)){
2172 $this->forms[$id] = $form;
2176 public function onFormSubmit(
int $formId, mixed $responseData) : bool{
2177 if(!isset($this->forms[$formId])){
2178 $this->logger->debug(
"Got unexpected response for form $formId");
2183 $this->forms[$formId]->handleResponse($this, $responseData);
2184 }
catch(FormValidationException $e){
2185 $this->logger->critical(
"Failed to validate form " . get_class($this->forms[$formId]) .
": " . $e->getMessage());
2186 $this->logger->logException($e);
2188 unset($this->forms[$formId]);
2198 $this->getNetworkSession()->onCloseAllForms();
2213 if(!$ev->isCancelled()){
2214 $this->getNetworkSession()->transfer($ev->getAddress(), $ev->getPort(), $ev->getMessage());
2229 $ev = new
PlayerKickEvent($this, $reason, $quitMessage ?? $this->getLeaveMessage(), $disconnectScreenMessage);
2231 if(!$ev->isCancelled()){
2232 $reason = $ev->getDisconnectReason();
2234 $reason = KnownTranslationFactory::disconnectionScreen_noReason();
2236 $disconnectScreenMessage = $ev->getDisconnectScreenMessage() ?? $reason;
2237 if($disconnectScreenMessage ===
""){
2238 $disconnectScreenMessage = KnownTranslationFactory::disconnectionScreen_noReason();
2240 $this->disconnect($reason, $ev->getQuitMessage(), $disconnectScreenMessage);
2262 if(!$this->isConnected()){
2266 $this->getNetworkSession()->onPlayerDestroyed($reason, $disconnectScreenMessage ?? $reason);
2267 $this->onPostDisconnect($reason, $quitMessage);
2278 if($this->isConnected()){
2279 throw new \LogicException(
"Player is still connected");
2283 $this->server->unsubscribeFromAllBroadcastChannels($this);
2285 $this->removeCurrentWindow();
2287 $ev =
new PlayerQuitEvent($this, $quitMessage ?? $this->getLeaveMessage(), $reason);
2289 if(($quitMessage = $ev->getQuitMessage()) !=
""){
2290 $this->server->broadcastMessage($quitMessage);
2294 $this->spawned =
false;
2297 $this->blockBreakHandler =
null;
2298 $this->despawnFromAll();
2300 $this->
server->removeOnlinePlayer($this);
2302 foreach($this->
server->getOnlinePlayers() as $player){
2303 if(!$player->canSee($this)){
2304 $player->showPlayer($this);
2307 $this->hiddenPlayers = [];
2309 if($this->location->isValid()){
2310 foreach($this->usedChunks as $index => $status){
2311 World::getXZ($index, $chunkX, $chunkZ);
2312 $this->unloadChunk($chunkX, $chunkZ);
2315 if(count($this->usedChunks) !== 0){
2316 throw new AssumptionFailedError(
"Previous loop should have cleared this array");
2318 $this->loadQueue = [];
2320 $this->removeCurrentWindow();
2321 $this->removePermanentInventories();
2323 $this->perm->getPermissionRecalculationCallbacks()->clear();
2325 $this->flagForDespawn();
2329 $this->disconnect(
"Player destroyed");
2330 $this->cursorInventory->removeAllViewers();
2331 $this->craftingGrid->removeAllViewers();
2332 parent::onDispose();
2336 $this->networkSession = null;
2337 unset($this->cursorInventory);
2338 unset($this->craftingGrid);
2339 $this->spawnPosition =
null;
2340 $this->blockBreakHandler =
null;
2341 parent::destroyCycles();
2351 public function __destruct(){
2352 parent::__destruct();
2353 $this->logger->debug(
"Destroyed by garbage collector");
2361 throw new \BadMethodCallException(
"Players can't be saved with chunks");
2365 $nbt = $this->saveNBT();
2367 $nbt->
setString(self::TAG_LAST_KNOWN_XUID, $this->xuid);
2369 if($this->location->isValid()){
2370 $nbt->setString(self::TAG_LEVEL, $this->getWorld()->getFolderName());
2373 if($this->hasValidCustomSpawn()){
2374 $spawn = $this->getSpawn();
2375 $nbt->setString(self::TAG_SPAWN_WORLD, $spawn->getWorld()->getFolderName());
2376 $nbt->setInt(self::TAG_SPAWN_X, $spawn->getFloorX());
2377 $nbt->setInt(self::TAG_SPAWN_Y, $spawn->getFloorY());
2378 $nbt->setInt(self::TAG_SPAWN_Z, $spawn->getFloorZ());
2381 $nbt->
setInt(self::TAG_GAME_MODE, GameModeIdMap::getInstance()->toId($this->gamemode));
2382 $nbt->
setLong(self::TAG_FIRST_PLAYED, (
int) $this->firstPlayed->format(
'Uv'));
2383 $nbt->
setLong(self::TAG_LAST_PLAYED, (
int) floor(microtime(
true) * 1000));
2392 $this->
server->saveOfflinePlayerData($this->username, $this->getSaveData());
2398 $this->removeCurrentWindow();
2400 $ev =
new PlayerDeathEvent($this, $this->getDrops(), $this->getXpDropAmount(),
null);
2403 if(!$ev->getKeepInventory()){
2404 foreach($ev->getDrops() as $item){
2405 $this->getWorld()->dropItem($this->location, $item);
2408 $clearInventory = fn(
Inventory $inventory) => $inventory->setContents(array_filter($inventory->getContents(), fn(
Item $item) => $item->
keepOnDeath()));
2409 $this->inventory->setHeldItemIndex(0);
2410 $clearInventory($this->inventory);
2411 $clearInventory($this->armorInventory);
2412 $clearInventory($this->offHandInventory);
2415 if(!$ev->getKeepXp()){
2416 $this->getWorld()->dropExperience($this->location, $ev->getXpDropAmount());
2417 $this->xpManager->setXpAndProgress(0, 0.0);
2420 if($ev->getDeathMessage() !=
""){
2421 $this->server->broadcastMessage($ev->getDeathMessage());
2424 $this->startDeathAnimation();
2426 $this->getNetworkSession()->onServerDeath($ev->getDeathScreenMessage());
2430 parent::onDeathUpdate($tickDiff);
2434 public function respawn() : void{
2435 if($this->
server->isHardcore()){
2436 if($this->kick(KnownTranslationFactory::pocketmine_disconnect_ban(KnownTranslationFactory::pocketmine_disconnect_ban_hardcore()))){
2437 $this->
server->getNameBans()->addBan($this->getName(),
"Died in hardcore mode");
2442 $this->actuallyRespawn();
2445 protected function actuallyRespawn() : void{
2446 if($this->respawnLocked){
2449 $this->respawnLocked =
true;
2451 $this->logger->debug(
"Waiting for safe respawn position to be located");
2452 $spawn = $this->getSpawn();
2453 $spawn->getWorld()->requestSafeSpawn($spawn)->onCompletion(
2454 function(Position $safeSpawn) :
void{
2455 if(!$this->isConnected()){
2458 $this->logger->debug(
"Respawn position located, completing respawn");
2459 $ev =
new PlayerRespawnEvent($this, $safeSpawn);
2462 $realSpawn = Position::fromObject($ev->getRespawnPosition()->add(0.5, 0, 0.5), $ev->getRespawnPosition()->getWorld());
2463 $this->teleport($realSpawn);
2465 $this->setSprinting(
false);
2466 $this->setSneaking(
false);
2467 $this->setFlying(
false);
2469 $this->extinguish();
2470 $this->setAirSupplyTicks($this->getMaxAirSupplyTicks());
2471 $this->deadTicks = 0;
2472 $this->noDamageTicks = 60;
2474 $this->effectManager->clear();
2475 $this->setHealth($this->getMaxHealth());
2477 foreach($this->attributeMap->getAll() as $attr){
2478 if($attr->getId() === Attribute::EXPERIENCE || $attr->getId() === Attribute::EXPERIENCE_LEVEL){
2481 $attr->resetToDefault();
2484 $this->spawnToAll();
2485 $this->scheduleUpdate();
2487 $this->getNetworkSession()->onServerRespawn();
2488 $this->respawnLocked =
false;
2491 if($this->isConnected()){
2492 $this->getNetworkSession()->disconnectWithError(KnownTranslationFactory::pocketmine_disconnect_error_respawn());
2499 parent::applyPostDamageEffects($source);
2501 $this->hungerManager->exhaust(0.1, PlayerExhaustEvent::CAUSE_DAMAGE);
2505 if(!$this->isAlive()){
2509 if($this->isCreative()
2510 && $source->getCause() !== EntityDamageEvent::CAUSE_SUICIDE
2513 }elseif($this->allowFlight && $source->getCause() === EntityDamageEvent::CAUSE_FALL){
2517 parent::attack($source);
2520 protected function syncNetworkData(EntityMetadataCollection $properties) : void{
2521 parent::syncNetworkData($properties);
2523 $properties->setGenericFlag(EntityMetadataFlags::ACTION, $this->startAction > -1);
2524 $properties->setGenericFlag(EntityMetadataFlags::HAS_COLLISION, $this->hasBlockCollision());
2526 $properties->setPlayerFlag(PlayerMetadataFlags::SLEEP, $this->sleeping !==
null);
2527 $properties->setBlockPos(EntityMetadataProperties::PLAYER_BED_POSITION, $this->sleeping !==
null ? BlockPosition::fromVector3($this->sleeping) :
new BlockPosition(0, 0, 0));
2530 public function sendData(?array $targets, ?array $data =
null) : void{
2531 if($targets === null){
2532 $targets = $this->getViewers();
2535 parent::sendData($targets, $data);
2539 if($this->spawned && $targets === null){
2540 $targets = $this->getViewers();
2543 parent::broadcastAnimation($animation, $targets);
2547 if($this->spawned && $targets === null){
2548 $targets = $this->getViewers();
2551 parent::broadcastSound($sound, $targets);
2557 protected function sendPosition(
Vector3 $pos, ?
float $yaw =
null, ?
float $pitch =
null,
int $mode = MovePlayerPacket::MODE_NORMAL) : void{
2558 $this->getNetworkSession()->syncMovement($pos, $yaw, $pitch, $mode);
2564 if(parent::teleport($pos, $yaw, $pitch)){
2566 $this->removeCurrentWindow();
2569 $this->sendPosition($this->location, $this->location->yaw, $this->location->pitch, MovePlayerPacket::MODE_TELEPORT);
2570 $this->broadcastMovement(
true);
2572 $this->spawnToAll();
2574 $this->resetFallDistance();
2575 $this->nextChunkOrderRun = 0;
2576 if($this->spawnChunkLoadCount !== -1){
2577 $this->spawnChunkLoadCount = 0;
2579 $this->blockBreakHandler =
null;
2583 $this->resetLastMovements();
2591 protected function addDefaultWindows() : void{
2592 $this->cursorInventory = new PlayerCursorInventory($this);
2593 $this->craftingGrid =
new PlayerCraftingInventory($this);
2595 $this->addPermanentInventories($this->inventory, $this->armorInventory, $this->cursorInventory, $this->offHandInventory, $this->craftingGrid);
2600 public function getCursorInventory() : PlayerCursorInventory{
2601 return $this->cursorInventory;
2604 public function getCraftingGrid() : CraftingGrid{
2605 return $this->craftingGrid;
2613 return $this->creativeInventory;
2620 $this->creativeInventory = $inventory;
2621 if($this->spawned && $this->isConnected()){
2622 $this->getNetworkSession()->getInvManager()?->syncCreative();
2630 private function doCloseInventory() : void{
2631 $inventories = [$this->craftingGrid, $this->cursorInventory];
2632 if($this->currentWindow instanceof TemporaryInventory){
2633 $inventories[] = $this->currentWindow;
2636 $builder =
new TransactionBuilder();
2637 foreach($inventories as $inventory){
2638 $contents = $inventory->getContents();
2640 if(count($contents) > 0){
2641 $drops = $builder->getInventory($this->inventory)->addItem(...$contents);
2642 foreach($drops as $drop){
2643 $builder->addAction(
new DropItemAction($drop));
2646 $builder->getInventory($inventory)->clearAll();
2650 $actions = $builder->generateActions();
2651 if(count($actions) !== 0){
2652 $transaction =
new InventoryTransaction($this, $actions);
2654 $transaction->execute();
2655 $this->logger->debug(
"Successfully evacuated items from temporary inventories");
2656 }
catch(TransactionCancelledException){
2657 $this->logger->debug(
"Plugin cancelled transaction evacuating items from temporary inventories; items will be destroyed");
2658 foreach($inventories as $inventory){
2659 $inventory->clearAll();
2661 }
catch(TransactionValidationException $e){
2662 throw new AssumptionFailedError(
"This server-generated transaction should never be invalid", 0, $e);
2671 return $this->currentWindow;
2678 if($inventory === $this->currentWindow){
2683 if($ev->isCancelled()){
2687 $this->removeCurrentWindow();
2689 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) ===
null){
2690 throw new \InvalidArgumentException(
"Player cannot open inventories in this state");
2692 $this->logger->debug(
"Opening inventory " . get_class($inventory) .
"#" . spl_object_id($inventory));
2693 $inventoryManager->onCurrentWindowChange($inventory);
2694 $inventory->onOpen($this);
2695 $this->currentWindow = $inventory;
2699 public function removeCurrentWindow() : void{
2700 $this->doCloseInventory();
2701 if($this->currentWindow !==
null){
2702 $currentWindow = $this->currentWindow;
2703 $this->logger->debug(
"Closing inventory " . get_class($this->currentWindow) .
"#" . spl_object_id($this->currentWindow));
2704 $this->currentWindow->onClose($this);
2705 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) !==
null){
2706 $inventoryManager->onCurrentWindowRemove();
2708 $this->currentWindow =
null;
2709 (
new InventoryCloseEvent($currentWindow, $this))->call();
2713 protected function addPermanentInventories(Inventory ...$inventories) : void{
2714 foreach($inventories as $inventory){
2715 $inventory->onOpen($this);
2716 $this->permanentWindows[spl_object_id($inventory)] = $inventory;
2720 protected function removePermanentInventories() : void{
2721 foreach($this->permanentWindows as $inventory){
2722 $inventory->onClose($this);
2724 $this->permanentWindows = [];
2732 $block = $this->getWorld()->getBlock($position);
2734 $this->getWorld()->setBlock($position, $block->setEditorEntityRuntimeId($this->getId()));
2735 $this->getNetworkSession()->onOpenSignEditor($position,
true);
2737 throw new \InvalidArgumentException(
"Block at this position is not a sign");
2741 use ChunkListenerNoOpTrait {
2742 onChunkChanged as
private;
2743 onChunkUnloaded as
private;
2747 $status = $this->usedChunks[$hash =
World::chunkHash($chunkX, $chunkZ)] ?? null;
2748 if($status === UsedChunkStatus::SENT){
2749 $this->usedChunks[$hash] = UsedChunkStatus::NEEDED;
2750 $this->nextChunkOrderRun = 0;
2755 if($this->isUsingChunk($chunkX, $chunkZ)){
2756 $this->logger->debug(
"Detected forced unload of chunk " . $chunkX .
" " . $chunkZ);
2757 $this->unloadChunk($chunkX, $chunkZ);