174 use PermissibleDelegateTrait;
176 private const MOVES_PER_TICK = 2;
177 private const MOVE_BACKLOG_SIZE = 100 * self::MOVES_PER_TICK;
180 private const MAX_CHAT_CHAR_LENGTH = 512;
186 private const MAX_CHAT_BYTE_LENGTH = self::MAX_CHAT_CHAR_LENGTH * 4;
187 private const MAX_REACH_DISTANCE_CREATIVE = 13;
188 private const MAX_REACH_DISTANCE_SURVIVAL = 7;
189 private const MAX_REACH_DISTANCE_ENTITY_INTERACTION = 8;
191 public const DEFAULT_FLIGHT_SPEED_MULTIPLIER = 0.05;
193 public const TAG_FIRST_PLAYED =
"firstPlayed";
194 public const TAG_LAST_PLAYED =
"lastPlayed";
195 private const TAG_GAME_MODE =
"playerGameType";
196 private const TAG_SPAWN_WORLD =
"SpawnLevel";
197 private const TAG_SPAWN_X =
"SpawnX";
198 private const TAG_SPAWN_Y =
"SpawnY";
199 private const TAG_SPAWN_Z =
"SpawnZ";
200 private const TAG_DEATH_WORLD =
"DeathLevel";
201 private const TAG_DEATH_X =
"DeathPositionX";
202 private const TAG_DEATH_Y =
"DeathPositionY";
203 private const TAG_DEATH_Z =
"DeathPositionZ";
204 public const TAG_LEVEL =
"Level";
205 public const TAG_LAST_KNOWN_XUID =
"LastKnownXUID";
215 $lname = strtolower($name);
216 $len = strlen($name);
217 return $lname !==
"rcon" && $lname !==
"console" && $len >= 1 && $len <= 16 && preg_match(
"/[^A-Za-z0-9_ ]/", $name) === 0;
222 public bool $spawned =
false;
224 protected string $username;
225 protected string $displayName;
226 protected string $xuid =
"";
227 protected bool $authenticated;
230 protected ?Inventory $currentWindow =
null;
232 protected array $permanentWindows = [];
233 protected PlayerCursorInventory $cursorInventory;
234 protected PlayerCraftingInventory $craftingGrid;
235 protected CreativeInventory $creativeInventory;
237 protected int $messageCounter = 2;
239 protected int $firstPlayed;
240 protected int $lastPlayed;
241 protected GameMode $gamemode;
247 protected array $usedChunks = [];
252 private array $activeChunkGenerationRequests = [];
257 protected array $loadQueue = [];
258 protected int $nextChunkOrderRun = 5;
261 private array $tickingChunks = [];
263 protected int $viewDistance = -1;
264 protected int $spawnThreshold;
265 protected int $spawnChunkLoadCount = 0;
266 protected int $chunksPerTick;
267 protected ChunkSelector $chunkSelector;
268 protected ChunkLoader $chunkLoader;
269 protected ChunkTicker $chunkTicker;
272 protected array $hiddenPlayers = [];
274 protected float $moveRateLimit = 10 * self::MOVES_PER_TICK;
275 protected ?
float $lastMovementProcess =
null;
277 protected int $inAirTicks = 0;
279 protected float $stepHeight = 0.6;
281 protected ?Vector3 $sleeping =
null;
282 private ?
Position $spawnPosition =
null;
284 private bool $respawnLocked =
false;
286 private ?
Position $deathPosition =
null;
289 protected bool $autoJump =
true;
290 protected bool $allowFlight =
false;
291 protected bool $blockCollision =
true;
292 protected bool $flying =
false;
294 protected float $flightSpeedMultiplier = self::DEFAULT_FLIGHT_SPEED_MULTIPLIER;
297 protected ?
int $lineHeight =
null;
298 protected string $locale =
"en_US";
300 protected int $startAction = -1;
306 protected array $usedItemsCooldown = [];
308 private int $lastEmoteTick = 0;
310 protected int $formIdCounter = 0;
312 protected array $forms = [];
314 protected \Logger $logger;
319 $username = TextFormat::clean($playerInfo->getUsername());
320 $this->logger = new \PrefixedLogger($server->getLogger(),
"Player: $username");
323 $this->networkSession = $session;
324 $this->playerInfo = $playerInfo;
325 $this->authenticated = $authenticated;
327 $this->username = $username;
328 $this->displayName = $this->username;
329 $this->locale = $this->playerInfo->getLocale();
331 $this->uuid = $this->playerInfo->getUuid();
332 $this->xuid = $this->playerInfo instanceof
XboxLivePlayerInfo ? $this->playerInfo->getXuid() :
"";
334 $this->creativeInventory = CreativeInventory::getInstance();
336 $rootPermissions = [DefaultPermissions::ROOT_USER =>
true];
337 if($this->
server->isOp($this->username)){
338 $rootPermissions[DefaultPermissions::ROOT_OPERATOR] =
true;
341 $this->chunksPerTick = $this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_PER_TICK, 4);
342 $this->spawnThreshold = (int) (($this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4) ** 2) * M_PI);
345 $this->chunkLoader =
new class implements
ChunkLoader{};
347 $world = $spawnLocation->
getWorld();
349 $xSpawnChunk = $spawnLocation->getFloorX() >> Chunk::COORD_BIT_SIZE;
350 $zSpawnChunk = $spawnLocation->getFloorZ() >> Chunk::COORD_BIT_SIZE;
351 $world->registerChunkLoader($this->chunkLoader, $xSpawnChunk, $zSpawnChunk,
true);
352 $world->registerChunkListener($this, $xSpawnChunk, $zSpawnChunk);
353 $this->usedChunks[World::chunkHash($xSpawnChunk, $zSpawnChunk)] = UsedChunkStatus::NEEDED;
355 parent::__construct($spawnLocation, $this->playerInfo->getSkin(), $namedtag);
359 $this->setNameTag($this->username);
362 private function callDummyItemHeldEvent() : void{
363 $slot = $this->inventory->getHeldItemIndex();
372 protected function initEntity(
CompoundTag $nbt) : void{
373 parent::initEntity($nbt);
374 $this->addDefaultWindows();
376 $this->inventory->getListeners()->add(
new CallbackInventoryListener(
377 function(Inventory $unused,
int $slot) :
void{
378 if($slot === $this->inventory->getHeldItemIndex()){
379 $this->setUsingItem(
false);
381 $this->callDummyItemHeldEvent();
385 $this->setUsingItem(
false);
386 $this->callDummyItemHeldEvent();
390 $this->firstPlayed = $nbt->getLong(self::TAG_FIRST_PLAYED, $now = (
int) (microtime(
true) * 1000));
391 $this->lastPlayed = $nbt->getLong(self::TAG_LAST_PLAYED, $now);
393 if(!$this->
server->getForceGamemode() && ($gameModeTag = $nbt->
getTag(self::TAG_GAME_MODE)) instanceof IntTag){
394 $this->internalSetGameMode(GameModeIdMap::getInstance()->fromId($gameModeTag->getValue()) ?? GameMode::SURVIVAL);
396 $this->internalSetGameMode($this->
server->getGamemode());
399 $this->keepMovement =
true;
401 $this->setNameTagVisible();
402 $this->setNameTagAlwaysVisible();
403 $this->setCanClimb();
405 if(($world = $this->
server->getWorldManager()->getWorldByName($nbt->getString(self::TAG_SPAWN_WORLD,
""))) instanceof World){
406 $this->spawnPosition =
new Position($nbt->getInt(self::TAG_SPAWN_X), $nbt->getInt(self::TAG_SPAWN_Y), $nbt->getInt(self::TAG_SPAWN_Z), $world);
408 if(($world = $this->
server->getWorldManager()->getWorldByName($nbt->getString(self::TAG_DEATH_WORLD,
""))) instanceof World){
409 $this->deathPosition =
new Position($nbt->getInt(self::TAG_DEATH_X), $nbt->getInt(self::TAG_DEATH_Y), $nbt->getInt(self::TAG_DEATH_Z), $world);
413 public function getLeaveMessage() : Translatable|string{
415 return KnownTranslationFactory::multiplayer_player_left($this->getDisplayName())->prefix(TextFormat::YELLOW);
421 public function isAuthenticated() : bool{
422 return $this->authenticated;
447 return parent::getUniqueId();
454 return $this->firstPlayed;
461 return $this->lastPlayed;
464 public function hasPlayedBefore() : bool{
465 return $this->lastPlayed - $this->firstPlayed > 1;
478 if($this->allowFlight !== $value){
479 $this->allowFlight = $value;
480 $this->getNetworkSession()->syncAbilities($this);
491 return $this->allowFlight;
503 if($this->blockCollision !== $value){
504 $this->blockCollision = $value;
505 $this->getNetworkSession()->syncAbilities($this);
514 return $this->blockCollision;
517 public function setFlying(
bool $value) : void{
518 if($this->flying !== $value){
519 $this->flying = $value;
520 $this->resetFallDistance();
521 $this->getNetworkSession()->syncAbilities($this);
525 public function isFlying() : bool{
526 return $this->flying;
543 if($this->flightSpeedMultiplier !== $flightSpeedMultiplier){
544 $this->flightSpeedMultiplier = $flightSpeedMultiplier;
545 $this->getNetworkSession()->syncAbilities($this);
561 return $this->flightSpeedMultiplier;
564 public function setAutoJump(
bool $value) : void{
565 if($this->autoJump !== $value){
566 $this->autoJump = $value;
567 $this->getNetworkSession()->syncAdventureSettings();
571 public function hasAutoJump() : bool{
572 return $this->autoJump;
575 public function spawnTo(Player $player) : void{
576 if($this->isAlive() && $player->isAlive() && $player->canSee($this) && !$this->isSpectator()){
577 parent::spawnTo($player);
581 public function getServer() : Server{
586 return $this->lineHeight ?? 7;
590 if($height !== null && $height < 1){
591 throw new \InvalidArgumentException(
"Line height must be at least 1");
593 $this->lineHeight = $height;
596 public function canSee(
Player $player) : bool{
597 return !isset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
600 public function hidePlayer(Player $player) : void{
601 if($player === $this){
604 $this->hiddenPlayers[$player->getUniqueId()->getBytes()] =
true;
605 $player->despawnFrom($this);
608 public function showPlayer(Player $player) : void{
609 if($player === $this){
612 unset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
613 if($player->isOnline()){
614 $player->spawnTo($this);
618 public function canCollideWith(Entity $entity) : bool{
622 public function canBeCollidedWith() : bool{
623 return !$this->isSpectator() && parent::canBeCollidedWith();
626 public function resetFallDistance() : void{
627 parent::resetFallDistance();
628 $this->inAirTicks = 0;
631 public function getViewDistance() : int{
632 return $this->viewDistance;
635 public function setViewDistance(
int $distance) : void{
636 $newViewDistance = $this->
server->getAllowedViewDistance($distance);
638 if($newViewDistance !== $this->viewDistance){
639 $ev =
new PlayerViewDistanceChangeEvent($this, $this->viewDistance, $newViewDistance);
643 $this->viewDistance = $newViewDistance;
645 $this->spawnThreshold = (int) (min($this->viewDistance, $this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4)) ** 2 * M_PI);
647 $this->nextChunkOrderRun = 0;
649 $this->getNetworkSession()->syncViewAreaRadius($this->viewDistance);
651 $this->logger->debug(
"Setting view distance to " . $this->viewDistance .
" (requested " . $distance .
")");
654 public function isOnline() : bool{
655 return $this->isConnected();
658 public function isConnected() : bool{
659 return $this->networkSession !== null && $this->networkSession->isConnected();
662 public function getNetworkSession() : NetworkSession{
663 if($this->networkSession === null){
664 throw new \LogicException(
"Player is not connected");
666 return $this->networkSession;
673 return $this->username;
680 return $this->displayName;
683 public function setDisplayName(
string $name) : void{
687 $this->displayName = $ev->getNewName();
698 return $this->locale;
701 public function getLanguage() :
Language{
702 return $this->
server->getLanguage();
709 public function changeSkin(
Skin $skin,
string $newSkinName,
string $oldSkinName) : bool{
713 if($ev->isCancelled()){
714 $this->sendSkin([$this]);
718 $this->setSkin($ev->getNewSkin());
719 $this->sendSkin($this->server->getOnlinePlayers());
728 public function sendSkin(?array $targets =
null) : void{
729 parent::sendSkin($targets ?? $this->
server->getOnlinePlayers());
736 return $this->startAction > -1;
739 public function setUsingItem(
bool $value) : void{
740 $this->startAction = $value ? $this->
server->getTick() : -1;
741 $this->networkPropertiesDirty =
true;
749 return $this->startAction === -1 ? -1 : ($this->
server->getTick() - $this->startAction);
756 $this->checkItemCooldowns();
757 return $this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()] ?? 0;
764 $this->checkItemCooldowns();
765 return isset($this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()]);
772 $ticks = $ticks ?? $item->getCooldownTicks();
774 $this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()] = $this->
server->getTick() + $ticks;
775 $this->getNetworkSession()->onItemCooldownChanged($item, $ticks);
779 protected function checkItemCooldowns() : void{
780 $serverTick = $this->
server->getTick();
781 foreach($this->usedItemsCooldown as $itemId => $cooldownUntil){
782 if($cooldownUntil <= $serverTick){
783 unset($this->usedItemsCooldown[$itemId]);
788 protected function setPosition(Vector3 $pos) : bool{
789 $oldWorld = $this->location->isValid() ? $this->location->getWorld() : null;
790 if(parent::setPosition($pos)){
791 $newWorld = $this->getWorld();
792 if($oldWorld !== $newWorld){
793 if($oldWorld !==
null){
794 foreach($this->usedChunks as $index => $status){
795 World::getXZ($index, $X, $Z);
796 $this->unloadChunk($X, $Z, $oldWorld);
800 $this->usedChunks = [];
801 $this->loadQueue = [];
802 $this->getNetworkSession()->onEnterWorld();
811 protected function unloadChunk(
int $x,
int $z, ?World $world =
null) : void{
812 $world = $world ?? $this->getWorld();
813 $index = World::chunkHash($x, $z);
814 if(isset($this->usedChunks[$index])){
815 foreach($world->getChunkEntities($x, $z) as $entity){
816 if($entity !== $this){
817 $entity->despawnFrom($this);
820 $this->getNetworkSession()->stopUsingChunk($x, $z);
821 unset($this->usedChunks[$index]);
822 unset($this->activeChunkGenerationRequests[$index]);
824 $world->unregisterChunkLoader($this->chunkLoader, $x, $z);
825 $world->unregisterChunkListener($this, $x, $z);
826 unset($this->loadQueue[$index]);
827 $world->unregisterTickingChunk($this->chunkTicker, $x, $z);
828 unset($this->tickingChunks[$index]);
831 protected function spawnEntitiesOnAllChunks() : void{
832 foreach($this->usedChunks as $chunkHash => $status){
833 if($status === UsedChunkStatus::SENT){
834 World::getXZ($chunkHash, $chunkX, $chunkZ);
835 $this->spawnEntitiesOnChunk($chunkX, $chunkZ);
840 protected function spawnEntitiesOnChunk(
int $chunkX,
int $chunkZ) : void{
841 foreach($this->getWorld()->getChunkEntities($chunkX, $chunkZ) as $entity){
842 if($entity !== $this && !$entity->isFlaggedForDespawn()){
843 $entity->spawnTo($this);
853 if(!$this->isConnected()){
857 Timings::$playerChunkSend->startTiming();
860 $world = $this->getWorld();
862 $limit = $this->chunksPerTick - count($this->activeChunkGenerationRequests);
863 foreach($this->loadQueue as $index => $distance){
864 if($count >= $limit){
870 World::getXZ($index, $X, $Z);
874 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_GENERATION;
875 $this->activeChunkGenerationRequests[$index] =
true;
876 unset($this->loadQueue[$index]);
877 $world->registerChunkLoader($this->chunkLoader, $X, $Z,
true);
878 $world->registerChunkListener($this, $X, $Z);
879 if(isset($this->tickingChunks[$index])){
880 $world->registerTickingChunk($this->chunkTicker, $X, $Z);
883 $world->requestChunkPopulation($X, $Z, $this->chunkLoader)->onCompletion(
884 function() use ($X, $Z, $index, $world) :
void{
885 if(!$this->isConnected() || !isset($this->usedChunks[$index]) || $world !== $this->getWorld()){
888 if($this->usedChunks[$index] !== UsedChunkStatus::REQUESTED_GENERATION){
894 unset($this->activeChunkGenerationRequests[$index]);
895 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_SENDING;
897 $this->getNetworkSession()->startUsingChunk($X, $Z,
function() use ($X, $Z, $index) :
void{
898 $this->usedChunks[$index] = UsedChunkStatus::SENT;
899 if($this->spawnChunkLoadCount === -1){
900 $this->spawnEntitiesOnChunk($X, $Z);
901 }elseif($this->spawnChunkLoadCount++ === $this->spawnThreshold){
902 $this->spawnChunkLoadCount = -1;
904 $this->spawnEntitiesOnAllChunks();
906 $this->getNetworkSession()->notifyTerrainReady();
908 (
new PlayerPostChunkSendEvent($this, $X, $Z))->call();
911 static function() :
void{
917 Timings::$playerChunkSend->stopTiming();
920 private function recheckBroadcastPermissions() : void{
922 DefaultPermissionNames::BROADCAST_ADMIN => Server::BROADCAST_CHANNEL_ADMINISTRATIVE,
923 DefaultPermissionNames::BROADCAST_USER => Server::BROADCAST_CHANNEL_USERS
924 ] as $permission => $channel){
925 if($this->hasPermission($permission)){
926 $this->
server->subscribeToBroadcastChannel($channel, $this);
928 $this->
server->unsubscribeFromBroadcastChannel($channel, $this);
941 $this->spawned =
true;
942 $this->recheckBroadcastPermissions();
943 $this->getPermissionRecalculationCallbacks()->add(
function(array $changedPermissionsOldValues) :
void{
944 if(isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_ADMINISTRATIVE]) || isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_USERS])){
945 $this->recheckBroadcastPermissions();
949 $ev =
new PlayerJoinEvent($this,
950 KnownTranslationFactory::multiplayer_player_joined($this->getDisplayName())->prefix(TextFormat::YELLOW)
953 if($ev->getJoinMessage() !==
""){
954 $this->server->broadcastMessage($ev->getJoinMessage());
957 $this->noDamageTicks = 60;
961 if($this->getHealth() <= 0){
962 $this->logger->debug(
"Quit while dead, forcing respawn");
963 $this->actuallyRespawn();
974 private function updateTickingChunkRegistrations(array $oldTickingChunks, array $newTickingChunks) : void{
975 $world = $this->getWorld();
976 foreach($oldTickingChunks as $hash => $_){
977 if(!isset($newTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
979 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
980 $world->unregisterTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
983 foreach($newTickingChunks as $hash => $_){
984 if(!isset($oldTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
986 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
987 $world->registerTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
997 if(!$this->isConnected() || $this->viewDistance === -1){
1001 Timings::$playerChunkOrder->startTiming();
1004 $tickingChunks = [];
1005 $unloadChunks = $this->usedChunks;
1007 $world = $this->getWorld();
1008 $tickingChunkRadius = $world->getChunkTickRadius();
1010 foreach($this->chunkSelector->selectChunks(
1011 $this->server->getAllowedViewDistance($this->viewDistance),
1012 $this->location->getFloorX() >> Chunk::COORD_BIT_SIZE,
1013 $this->location->getFloorZ() >> Chunk::COORD_BIT_SIZE
1014 ) as $radius => $hash){
1015 if(!isset($this->usedChunks[$hash]) || $this->usedChunks[$hash] === UsedChunkStatus::NEEDED){
1016 $newOrder[$hash] =
true;
1018 if($radius < $tickingChunkRadius){
1019 $tickingChunks[$hash] =
true;
1021 unset($unloadChunks[$hash]);
1024 foreach($unloadChunks as $index => $status){
1025 World::getXZ($index, $X, $Z);
1026 $this->unloadChunk($X, $Z);
1029 $this->loadQueue = $newOrder;
1031 $this->updateTickingChunkRegistrations($this->tickingChunks, $tickingChunks);
1032 $this->tickingChunks = $tickingChunks;
1034 if(count($this->loadQueue) > 0 || count($unloadChunks) > 0){
1035 $this->getNetworkSession()->syncViewAreaCenterPoint($this->location, $this->viewDistance);
1038 Timings::$playerChunkOrder->stopTiming();
1046 return isset($this->usedChunks[
World::chunkHash($chunkX, $chunkZ)]);
1054 return $this->usedChunks;
1061 return $this->usedChunks[
World::chunkHash($chunkX, $chunkZ)] ?? null;
1068 $status = $this->usedChunks[
World::chunkHash($chunkX, $chunkZ)] ?? null;
1069 return $status === UsedChunkStatus::SENT;
1076 if($this->nextChunkOrderRun !== PHP_INT_MAX && $this->nextChunkOrderRun-- <= 0){
1077 $this->nextChunkOrderRun = PHP_INT_MAX;
1078 $this->orderChunks();
1081 if(count($this->loadQueue) > 0){
1082 $this->requestChunks();
1086 public function getDeathPosition() : ?Position{
1087 if($this->deathPosition !== null && !$this->deathPosition->isValid()){
1088 $this->deathPosition =
null;
1090 return $this->deathPosition;
1098 if($pos instanceof
Position && $pos->world !==
null){
1099 $world = $pos->world;
1101 $world = $this->getWorld();
1103 $this->deathPosition =
new Position($pos->x, $pos->y, $pos->z, $world);
1105 $this->deathPosition =
null;
1107 $this->networkPropertiesDirty =
true;
1114 if($this->hasValidCustomSpawn()){
1115 return $this->spawnPosition;
1117 $world = $this->
server->getWorldManager()->getDefaultWorld();
1119 return $world->getSpawnLocation();
1123 public function hasValidCustomSpawn() : bool{
1124 return $this->spawnPosition !== null && $this->spawnPosition->isValid();
1136 $world = $this->getWorld();
1138 $world = $pos->getWorld();
1140 $this->spawnPosition =
new Position($pos->x, $pos->y, $pos->z, $world);
1142 $this->spawnPosition =
null;
1144 $this->getNetworkSession()->syncPlayerSpawnPoint($this->getSpawn());
1147 public function isSleeping() : bool{
1148 return $this->sleeping !== null;
1151 public function sleepOn(Vector3 $pos) : bool{
1152 $pos = $pos->floor();
1153 $b = $this->getWorld()->getBlock($pos);
1155 $ev =
new PlayerBedEnterEvent($this, $b);
1157 if($ev->isCancelled()){
1161 if($b instanceof Bed){
1163 $this->getWorld()->setBlock($pos, $b);
1166 $this->sleeping = $pos;
1167 $this->networkPropertiesDirty =
true;
1169 $this->setSpawn($pos);
1171 $this->getWorld()->setSleepTicks(60);
1176 public function stopSleep() : void{
1177 if($this->sleeping instanceof Vector3){
1178 $b = $this->getWorld()->getBlock($this->sleeping);
1179 if($b instanceof Bed){
1180 $b->setOccupied(
false);
1181 $this->getWorld()->setBlock($this->sleeping, $b);
1183 (
new PlayerBedLeaveEvent($this, $b))->call();
1185 $this->sleeping =
null;
1186 $this->networkPropertiesDirty =
true;
1188 $this->getWorld()->setSleepTicks(0);
1190 $this->getNetworkSession()->sendDataPacket(AnimatePacket::create($this->getId(), AnimatePacket::ACTION_STOP_SLEEP));
1194 public function getGamemode() : GameMode{
1195 return $this->gamemode;
1198 protected function internalSetGameMode(GameMode $gameMode) : void{
1199 $this->gamemode = $gameMode;
1201 $this->allowFlight = $this->gamemode === GameMode::CREATIVE;
1202 $this->hungerManager->setEnabled($this->isSurvival());
1204 if($this->isSpectator()){
1205 $this->setFlying(
true);
1206 $this->setHasBlockCollision(
false);
1208 $this->onGround =
false;
1212 $this->sendPosition($this->location,
null,
null, MovePlayerPacket::MODE_TELEPORT);
1214 if($this->isSurvival()){
1215 $this->setFlying(
false);
1217 $this->setHasBlockCollision(
true);
1218 $this->setSilent(
false);
1219 $this->checkGroundState(0, 0, 0, 0, 0, 0);
1227 if($this->gamemode === $gm){
1233 if($ev->isCancelled()){
1237 $this->internalSetGameMode($gm);
1239 if($this->isSpectator()){
1240 $this->despawnFromAll();
1242 $this->spawnToAll();
1245 $this->getNetworkSession()->syncGameMode($this->gamemode);
1256 return $this->gamemode === GameMode::SURVIVAL || (!$literal && $this->gamemode === GameMode::ADVENTURE);
1266 return $this->gamemode === GameMode::CREATIVE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1276 return $this->gamemode === GameMode::ADVENTURE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1279 public function isSpectator() : bool{
1280 return $this->gamemode === GameMode::SPECTATOR;
1287 return $this->gamemode !== GameMode::CREATIVE;
1291 if($this->hasFiniteResources()){
1292 return parent::getDrops();
1299 if($this->hasFiniteResources()){
1300 return parent::getXpDropAmount();
1306 protected function checkGroundState(
float $wantedX,
float $wantedY,
float $wantedZ,
float $dx,
float $dy,
float $dz) : void{
1307 if($this->gamemode === GameMode::SPECTATOR){
1308 $this->onGround =
false;
1310 $bb = clone $this->boundingBox;
1311 $bb->minY = $this->location->y - 0.2;
1312 $bb->maxY = $this->location->y + 0.2;
1316 $bb = $bb->addCoord(-$dx, -$dy, -$dz);
1318 $this->onGround = $this->isCollided = count($this->getWorld()->getCollisionBlocks($bb,
true)) > 0;
1326 protected function checkNearEntities() : void{
1327 foreach($this->getWorld()->getNearbyEntities($this->boundingBox->expandedCopy(1, 0.5, 1), $this) as $entity){
1328 $entity->scheduleUpdate();
1330 if(!$entity->isAlive() || $entity->isFlaggedForDespawn()){
1334 $entity->onCollideWithPlayer($this);
1338 public function getInAirTicks() : int{
1339 return $this->inAirTicks;
1351 Timings::$playerMove->startTiming();
1353 $this->actuallyHandleMovement($newPos);
1355 Timings::$playerMove->stopTiming();
1359 private function actuallyHandleMovement(Vector3 $newPos) : void{
1360 $this->moveRateLimit--;
1361 if($this->moveRateLimit < 0){
1365 $oldPos = $this->location;
1366 $distanceSquared = $newPos->distanceSquared($oldPos);
1370 if($distanceSquared > 225){
1382 $this->logger->debug(
"Moved too fast (" . sqrt($distanceSquared) .
" blocks in 1 movement), reverting movement");
1383 $this->logger->debug(
"Old position: " . $oldPos->asVector3() .
", new position: " . $newPos);
1385 }elseif(!$this->getWorld()->isInLoadedTerrain($newPos)){
1387 $this->nextChunkOrderRun = 0;
1390 if(!$revert && $distanceSquared !== 0.0){
1391 $dx = $newPos->x - $oldPos->x;
1392 $dy = $newPos->y - $oldPos->y;
1393 $dz = $newPos->z - $oldPos->z;
1395 $this->move($dx, $dy, $dz);
1399 $this->revertMovement($oldPos);
1407 $now = microtime(true);
1408 $multiplier = $this->lastMovementProcess !==
null ? ($now - $this->lastMovementProcess) * 20 : 1;
1409 $exceededRateLimit = $this->moveRateLimit < 0;
1410 $this->moveRateLimit = min(self::MOVE_BACKLOG_SIZE, max(0, $this->moveRateLimit) + self::MOVES_PER_TICK * $multiplier);
1411 $this->lastMovementProcess = $now;
1413 $from = clone $this->lastLocation;
1414 $to = clone $this->location;
1416 $delta = $to->distanceSquared($from);
1417 $deltaAngle = abs($this->lastLocation->yaw - $to->yaw) + abs($this->lastLocation->pitch - $to->pitch);
1419 if($delta > 0.0001 || $deltaAngle > 1.0){
1420 if(PlayerMoveEvent::hasHandlers()){
1425 if($ev->isCancelled()){
1426 $this->revertMovement($from);
1430 if($to->distanceSquared($ev->getTo()) > 0.01){
1431 $this->teleport($ev->getTo());
1436 $this->lastLocation = $to;
1437 $this->broadcastMovement();
1439 $horizontalDistanceTravelled = sqrt((($from->x - $to->x) ** 2) + (($from->z - $to->z) ** 2));
1440 if($horizontalDistanceTravelled > 0){
1442 if($this->isSprinting()){
1443 $this->hungerManager->exhaust(0.01 * $horizontalDistanceTravelled, PlayerExhaustEvent::CAUSE_SPRINTING);
1445 $this->hungerManager->exhaust(0.0, PlayerExhaustEvent::CAUSE_WALKING);
1448 if($this->nextChunkOrderRun > 20){
1449 $this->nextChunkOrderRun = 20;
1454 if($exceededRateLimit){
1455 $this->logger->debug(
"Exceeded movement rate limit, forcing to last accepted position");
1456 $this->sendPosition($this->location, $this->location->getYaw(), $this->location->getPitch(), MovePlayerPacket::MODE_RESET);
1460 protected function revertMovement(Location $from) : void{
1461 $this->setPosition($from);
1462 $this->sendPosition($from, $from->yaw, $from->pitch, MovePlayerPacket::MODE_RESET);
1465 protected function calculateFallDamage(
float $fallDistance) : float{
1466 return $this->flying ? 0 : parent::calculateFallDamage($fallDistance);
1474 public function setMotion(
Vector3 $motion) : bool{
1475 if(parent::setMotion($motion)){
1476 $this->broadcastMotion();
1477 $this->getNetworkSession()->sendDataPacket(SetActorMotionPacket::create($this->
id, $motion, tick: 0));
1484 protected function updateMovement(
bool $teleport =
false) : void{
1488 protected function tryChangeMovement() : void{
1492 public function onUpdate(int $currentTick) : bool{
1493 $tickDiff = $currentTick - $this->lastUpdate;
1499 $this->messageCounter = 2;
1501 $this->lastUpdate = $currentTick;
1503 if($this->justCreated){
1504 $this->onFirstUpdate($currentTick);
1507 if(!$this->isAlive() && $this->spawned){
1508 $this->onDeathUpdate($tickDiff);
1512 $this->timings->startTiming();
1515 Timings::$playerMove->startTiming();
1516 $this->processMostRecentMovements();
1517 $this->motion = Vector3::zero();
1518 if($this->onGround){
1519 $this->inAirTicks = 0;
1521 $this->inAirTicks += $tickDiff;
1523 Timings::$playerMove->stopTiming();
1525 Timings::$entityBaseTick->startTiming();
1526 $this->entityBaseTick($tickDiff);
1527 Timings::$entityBaseTick->stopTiming();
1529 if($this->isCreative() && $this->fireTicks > 1){
1530 $this->fireTicks = 1;
1533 if(!$this->isSpectator() && $this->isAlive()){
1534 Timings::$playerCheckNearEntities->startTiming();
1535 $this->checkNearEntities();
1536 Timings::$playerCheckNearEntities->stopTiming();
1539 if($this->blockBreakHandler !==
null && !$this->blockBreakHandler->update()){
1540 $this->blockBreakHandler =
null;
1544 $this->timings->stopTiming();
1550 return $this->isCreative() || parent::canEat();
1554 return $this->isCreative() || parent::canBreathe();
1563 $eyePos = $this->getEyePos();
1564 if($eyePos->distanceSquared($pos) > $maxDistance ** 2){
1568 $dV = $this->getDirectionVector();
1569 $eyeDot = $dV->dot($eyePos);
1570 $targetDot = $dV->dot($pos);
1571 return ($targetDot - $eyeDot) >= -$maxDiff;
1578 public function chat(
string $message) : bool{
1579 $this->removeCurrentWindow();
1581 if($this->messageCounter <= 0){
1587 $maxTotalLength = $this->messageCounter * (self::MAX_CHAT_BYTE_LENGTH + 1);
1588 if(strlen($message) > $maxTotalLength){
1592 $message = TextFormat::clean($message,
false);
1593 foreach(explode(
"\n", $message, $this->messageCounter + 1) as $messagePart){
1594 if(trim($messagePart) !==
"" && strlen($messagePart) <= self::MAX_CHAT_BYTE_LENGTH && mb_strlen($messagePart,
'UTF-8') <= self::MAX_CHAT_CHAR_LENGTH && $this->messageCounter-- > 0){
1595 if(str_starts_with($messagePart,
'./')){
1596 $messagePart = substr($messagePart, 1);
1599 if(str_starts_with($messagePart,
"/")){
1600 Timings::$playerCommand->startTiming();
1601 $this->server->dispatchCommand($this, substr($messagePart, 1));
1602 Timings::$playerCommand->stopTiming();
1604 $ev =
new PlayerChatEvent($this, $messagePart, $this->
server->getBroadcastChannelSubscribers(Server::BROADCAST_CHANNEL_USERS),
new StandardChatFormatter());
1606 if(!$ev->isCancelled()){
1607 $this->
server->broadcastMessage($ev->getFormatter()->format($ev->getPlayer()->getDisplayName(), $ev->getMessage()), $ev->getRecipients());
1616 public function selectHotbarSlot(
int $hotbarSlot) : bool{
1617 if(!$this->inventory->isHotbarSlot($hotbarSlot)){
1620 if($hotbarSlot === $this->inventory->getHeldItemIndex()){
1624 $ev =
new PlayerItemHeldEvent($this, $this->inventory->getItem($hotbarSlot), $hotbarSlot);
1626 if($ev->isCancelled()){
1630 $this->inventory->setHeldItemIndex($hotbarSlot);
1631 $this->setUsingItem(
false);
1639 private function returnItemsFromAction(Item $oldHeldItem, Item $newHeldItem, array $extraReturnedItems) : void{
1640 $heldItemChanged = false;
1642 if(!$newHeldItem->equalsExact($oldHeldItem) && $oldHeldItem->equalsExact($this->inventory->getItemInHand())){
1645 $newReplica = clone $oldHeldItem;
1646 $newReplica->setCount($newHeldItem->getCount());
1647 if($newReplica instanceof Durable && $newHeldItem instanceof Durable){
1648 $newDamage = $newHeldItem->getDamage();
1649 if($newDamage >= 0 && $newDamage <= $newReplica->getMaxDurability()){
1650 $newReplica->setDamage($newDamage);
1653 $damagedOrDeducted = $newReplica->equalsExact($newHeldItem);
1655 if(!$damagedOrDeducted || $this->hasFiniteResources()){
1656 if($newHeldItem instanceof Durable && $newHeldItem->isBroken()){
1657 $this->broadcastSound(
new ItemBreakSound());
1659 $this->inventory->setItemInHand($newHeldItem);
1660 $heldItemChanged =
true;
1664 if(!$heldItemChanged){
1665 $newHeldItem = $oldHeldItem;
1668 if($heldItemChanged && count($extraReturnedItems) > 0 && $newHeldItem->isNull()){
1669 $this->inventory->setItemInHand(array_shift($extraReturnedItems));
1671 foreach($this->inventory->addItem(...$extraReturnedItems) as $drop){
1673 $ev =
new PlayerDropItemEvent($this, $drop);
1674 if($this->isSpectator()){
1678 if(!$ev->isCancelled()){
1679 $this->dropItem($drop);
1690 $directionVector = $this->getDirectionVector();
1691 $item = $this->inventory->getItemInHand();
1692 $oldItem = clone $item;
1695 if($this->hasItemCooldown($item) || $this->isSpectator()){
1701 if($ev->isCancelled()){
1705 $returnedItems = [];
1706 $result = $item->onClickAir($this, $directionVector, $returnedItems);
1707 if($result === ItemUseResult::FAIL){
1711 $this->resetItemCooldown($oldItem);
1712 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1714 $this->setUsingItem($item instanceof Releasable && $item->canStartUsingItem($this));
1725 $slot = $this->inventory->getItemInHand();
1727 $oldItem = clone $slot;
1730 if($this->hasItemCooldown($slot)){
1735 if($ev->isCancelled() || !$this->consumeObject($slot)){
1739 $this->setUsingItem(
false);
1740 $this->resetItemCooldown($oldItem);
1743 $this->returnItemsFromAction($oldItem, $slot, [$slot->getResidue()]);
1758 $item = $this->inventory->getItemInHand();
1759 if(!$this->isUsingItem() || $this->hasItemCooldown($item)){
1763 $oldItem = clone $item;
1765 $returnedItems = [];
1766 $result = $item->onReleaseUsing($this, $returnedItems);
1767 if($result === ItemUseResult::SUCCESS){
1768 $this->resetItemCooldown($oldItem);
1769 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1775 $this->setUsingItem(
false);
1779 public function pickBlock(Vector3 $pos,
bool $addTileNBT) : bool{
1780 $block = $this->getWorld()->getBlock($pos);
1781 if($block instanceof UnknownBlock){
1785 $item = $block->getPickedItem($addTileNBT);
1787 $ev =
new PlayerBlockPickEvent($this, $block, $item);
1788 $existingSlot = $this->inventory->first($item);
1789 if($existingSlot === -1 && $this->hasFiniteResources()){
1794 if(!$ev->isCancelled()){
1795 $this->equipOrAddPickedItem($existingSlot, $item);
1801 public function pickEntity(
int $entityId) : bool{
1802 $entity = $this->getWorld()->getEntity($entityId);
1803 if($entity ===
null){
1807 $item = $entity->getPickedItem();
1812 $ev =
new PlayerEntityPickEvent($this, $entity, $item);
1813 $existingSlot = $this->inventory->first($item);
1814 if($existingSlot === -1 && ($this->hasFiniteResources() || $this->isSpectator())){
1819 if(!$ev->isCancelled()){
1820 $this->equipOrAddPickedItem($existingSlot, $item);
1826 private function equipOrAddPickedItem(
int $existingSlot, Item $item) : void{
1827 if($existingSlot !== -1){
1828 if($existingSlot < $this->inventory->getHotbarSize()){
1829 $this->inventory->setHeldItemIndex($existingSlot);
1831 $this->inventory->swap($this->inventory->getHeldItemIndex(), $existingSlot);
1834 $firstEmpty = $this->inventory->firstEmpty();
1835 if($firstEmpty === -1){
1836 $this->inventory->setItemInHand($item);
1837 }elseif($firstEmpty < $this->inventory->getHotbarSize()){
1838 $this->inventory->setItem($firstEmpty, $item);
1839 $this->inventory->setHeldItemIndex($firstEmpty);
1841 $this->inventory->swap($this->inventory->getHeldItemIndex(), $firstEmpty);
1842 $this->inventory->setItemInHand($item);
1853 if($pos->distanceSquared($this->location) > 10000){
1857 $target = $this->getWorld()->getBlock($pos);
1859 $ev =
new PlayerInteractEvent($this, $this->inventory->getItemInHand(), $target,
null, $face, PlayerInteractEvent::LEFT_CLICK_BLOCK);
1860 if($this->isSpectator()){
1864 if($ev->isCancelled()){
1867 $this->broadcastAnimation(
new ArmSwingAnimation($this), $this->getViewers());
1868 if($target->onAttack($this->inventory->getItemInHand(), $face, $this)){
1872 $block = $target->getSide($face);
1873 if($block->hasTypeTag(BlockTypeTags::FIRE)){
1874 $this->getWorld()->setBlock($block->getPosition(), VanillaBlocks::AIR());
1875 $this->getWorld()->addSound($block->getPosition()->add(0.5, 0.5, 0.5),
new FireExtinguishSound());
1879 if(!$this->isCreative() && !$target->getBreakInfo()->breaksInstantly()){
1880 $this->blockBreakHandler =
new SurvivalBlockBreakHandler($this, $pos, $target, $face, 16);
1886 public function continueBreakBlock(Vector3 $pos,
int $face) : void{
1887 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1888 $this->blockBreakHandler->setTargetedFace($face);
1892 public function stopBreakBlock(Vector3 $pos) : void{
1893 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1894 $this->blockBreakHandler =
null;
1904 $this->removeCurrentWindow();
1906 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1907 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1908 $this->stopBreakBlock($pos);
1909 $item = $this->inventory->getItemInHand();
1910 $oldItem = clone $item;
1911 $returnedItems = [];
1912 if($this->getWorld()->useBreakOn($pos, $item, $this, true, $returnedItems)){
1913 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1914 $this->hungerManager->exhaust(0.005, PlayerExhaustEvent::CAUSE_MINING);
1918 $this->logger->debug(
"Cancelled block break at $pos due to not currently being interactable");
1930 $this->setUsingItem(false);
1932 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1933 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1934 $item = $this->inventory->getItemInHand();
1935 $oldItem = clone $item;
1936 $returnedItems = [];
1937 if($this->getWorld()->useItemOn($pos, $item, $face, $clickOffset, $this, true, $returnedItems)){
1938 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1942 $this->logger->debug(
"Cancelled interaction of block at $pos due to not currently being interactable");
1955 if(!$entity->isAlive()){
1959 $this->logger->debug(
"Attempted to attack non-attackable entity " . get_class($entity));
1963 $heldItem = $this->inventory->getItemInHand();
1964 $oldItem = clone $heldItem;
1966 $ev =
new EntityDamageByEntityEvent($this, $entity, EntityDamageEvent::CAUSE_ENTITY_ATTACK, $heldItem->getAttackPoints());
1967 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
1968 $this->logger->debug(
"Cancelled attack of entity " . $entity->getId() .
" due to not currently being interactable");
1970 }elseif($this->isSpectator() || ($entity instanceof Player && !$this->server->getConfigGroup()->getConfigBool(ServerProperties::PVP))){
1974 $meleeEnchantmentDamage = 0;
1976 $meleeEnchantments = [];
1977 foreach($heldItem->getEnchantments() as $enchantment){
1978 $type = $enchantment->getType();
1979 if($type instanceof MeleeWeaponEnchantment && $type->isApplicableTo($entity)){
1980 $meleeEnchantmentDamage += $type->getDamageBonus($enchantment->getLevel());
1981 $meleeEnchantments[] = $enchantment;
1984 $ev->setModifier($meleeEnchantmentDamage, EntityDamageEvent::MODIFIER_WEAPON_ENCHANTMENTS);
1986 if(!$this->isSprinting() && !$this->isFlying() && $this->fallDistance > 0 && !$this->effectManager->has(VanillaEffects::BLINDNESS()) && !$this->isUnderwater()){
1987 $ev->setModifier($ev->getFinalDamage() / 2, EntityDamageEvent::MODIFIER_CRITICAL);
1990 $entity->attack($ev);
1991 $this->broadcastAnimation(
new ArmSwingAnimation($this), $this->getViewers());
1993 $soundPos = $entity->getPosition()->add(0, $entity->size->getHeight() / 2, 0);
1994 if($ev->isCancelled()){
1995 $this->getWorld()->addSound($soundPos,
new EntityAttackNoDamageSound());
1998 $this->getWorld()->addSound($soundPos,
new EntityAttackSound());
2000 if($ev->getModifier(EntityDamageEvent::MODIFIER_CRITICAL) > 0 && $entity instanceof Living){
2001 $entity->broadcastAnimation(
new CriticalHitAnimation($entity));
2004 foreach($meleeEnchantments as $enchantment){
2005 $type = $enchantment->getType();
2006 assert($type instanceof MeleeWeaponEnchantment);
2007 $type->onPostAttack($this, $entity, $enchantment->getLevel());
2010 if($this->isAlive()){
2013 $returnedItems = [];
2014 $heldItem->onAttackEntity($entity, $returnedItems);
2015 $this->returnItemsFromAction($oldItem, $heldItem, $returnedItems);
2017 $this->hungerManager->exhaust(0.1, PlayerExhaustEvent::CAUSE_ATTACK);
2030 if(!$ev->isCancelled()){
2031 $this->broadcastSound(new EntityAttackNoDamageSound());
2032 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
2042 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
2043 $this->logger->debug(
"Cancelled interaction with entity " . $entity->getId() .
" due to not currently being interactable");
2049 $item = $this->inventory->getItemInHand();
2050 $oldItem = clone $item;
2051 if(!$ev->isCancelled()){
2052 if($item->onInteractEntity($this, $entity, $clickPos)){
2053 if($this->hasFiniteResources() && !$item->equalsExact($oldItem) && $oldItem->equalsExact($this->inventory->getItemInHand())){
2054 if($item instanceof Durable && $item->isBroken()){
2055 $this->broadcastSound(new ItemBreakSound());
2057 $this->inventory->setItemInHand($item);
2060 return $entity->
onInteract($this, $clickPos);
2065 public function toggleSprint(
bool $sprint) : bool{
2066 if($sprint === $this->sprinting){
2069 $ev =
new PlayerToggleSprintEvent($this, $sprint);
2071 if($ev->isCancelled()){
2074 $this->setSprinting($sprint);
2078 public function toggleSneak(
bool $sneak) : bool{
2079 if($sneak === $this->sneaking){
2082 $ev =
new PlayerToggleSneakEvent($this, $sneak);
2084 if($ev->isCancelled()){
2087 $this->setSneaking($sneak);
2091 public function toggleFlight(
bool $fly) : bool{
2092 if($fly === $this->flying){
2095 $ev =
new PlayerToggleFlightEvent($this, $fly);
2096 if(!$this->allowFlight){
2100 if($ev->isCancelled()){
2103 $this->setFlying($fly);
2107 public function toggleGlide(
bool $glide) : bool{
2108 if($glide === $this->gliding){
2111 $ev =
new PlayerToggleGlideEvent($this, $glide);
2113 if($ev->isCancelled()){
2116 $this->setGliding($glide);
2120 public function toggleSwim(
bool $swim) : bool{
2121 if($swim === $this->swimming){
2124 $ev =
new PlayerToggleSwimEvent($this, $swim);
2126 if($ev->isCancelled()){
2129 $this->setSwimming($swim);
2133 public function emote(
string $emoteId) : void{
2134 $currentTick = $this->
server->getTick();
2135 if($currentTick - $this->lastEmoteTick > 5){
2136 $this->lastEmoteTick = $currentTick;
2137 $event =
new PlayerEmoteEvent($this, $emoteId);
2139 if(!$event->isCancelled()){
2140 $emoteId = $event->getEmoteId();
2141 parent::emote($emoteId);
2151 $this->getWorld()->dropItem($this->location->add(0, 1.3, 0), $item, $this->getDirectionVector()->multiply(0.4), 40);
2161 public function sendTitle(
string $title,
string $subtitle =
"",
int $fadeIn = -1,
int $stay = -1,
int $fadeOut = -1) : void{
2162 $this->setTitleDuration($fadeIn, $stay, $fadeOut);
2163 if($subtitle !==
""){
2164 $this->sendSubTitle($subtitle);
2166 $this->getNetworkSession()->onTitle($title);
2173 $this->getNetworkSession()->onSubTitle($subtitle);
2180 $this->getNetworkSession()->onActionBar($message);
2187 $this->getNetworkSession()->onClearTitle();
2194 $this->getNetworkSession()->onResetTitleOptions();
2205 if($fadeIn >= 0 && $stay >= 0 && $fadeOut >= 0){
2206 $this->getNetworkSession()->onTitleDuration($fadeIn, $stay, $fadeOut);
2214 $this->getNetworkSession()->onChatMessage($message);
2217 public function sendJukeboxPopup(
Translatable|
string $message) : void{
2218 $this->getNetworkSession()->onJukeboxPopup($message);
2227 $this->getNetworkSession()->onPopup($message);
2230 public function sendTip(
string $message) : void{
2231 $this->getNetworkSession()->onTip($message);
2238 $this->getNetworkSession()->onToastNotification($title, $body);
2247 $id = $this->formIdCounter++;
2248 if($this->getNetworkSession()->onFormSent($id, $form)){
2249 $this->forms[$id] = $form;
2253 public function onFormSubmit(
int $formId, mixed $responseData) : bool{
2254 if(!isset($this->forms[$formId])){
2255 $this->logger->debug(
"Got unexpected response for form $formId");
2260 $this->forms[$formId]->handleResponse($this, $responseData);
2261 }
catch(FormValidationException $e){
2262 $this->logger->critical(
"Failed to validate form " . get_class($this->forms[$formId]) .
": " . $e->getMessage());
2263 $this->logger->logException($e);
2265 unset($this->forms[$formId]);
2275 $this->getNetworkSession()->onCloseAllForms();
2290 if(!$ev->isCancelled()){
2291 $this->getNetworkSession()->transfer($ev->getAddress(), $ev->getPort(), $ev->getMessage());
2306 $ev = new
PlayerKickEvent($this, $reason, $quitMessage ?? $this->getLeaveMessage(), $disconnectScreenMessage);
2308 if(!$ev->isCancelled()){
2309 $reason = $ev->getDisconnectReason();
2311 $reason = KnownTranslationFactory::disconnectionScreen_noReason();
2313 $disconnectScreenMessage = $ev->getDisconnectScreenMessage() ?? $reason;
2314 if($disconnectScreenMessage ===
""){
2315 $disconnectScreenMessage = KnownTranslationFactory::disconnectionScreen_noReason();
2317 $this->disconnect($reason, $ev->getQuitMessage(), $disconnectScreenMessage);
2339 if(!$this->isConnected()){
2343 $this->getNetworkSession()->onPlayerDestroyed($reason, $disconnectScreenMessage ?? $reason);
2344 $this->onPostDisconnect($reason, $quitMessage);
2355 if($this->isConnected()){
2356 throw new \LogicException(
"Player is still connected");
2360 $this->server->unsubscribeFromAllBroadcastChannels($this);
2362 $this->removeCurrentWindow();
2364 $ev =
new PlayerQuitEvent($this, $quitMessage ?? $this->getLeaveMessage(), $reason);
2366 if(($quitMessage = $ev->getQuitMessage()) !==
""){
2367 $this->server->broadcastMessage($quitMessage);
2371 $this->spawned =
false;
2374 $this->blockBreakHandler =
null;
2375 $this->despawnFromAll();
2377 $this->
server->removeOnlinePlayer($this);
2379 foreach($this->
server->getOnlinePlayers() as $player){
2380 if(!$player->canSee($this)){
2381 $player->showPlayer($this);
2384 $this->hiddenPlayers = [];
2386 if($this->location->isValid()){
2387 foreach($this->usedChunks as $index => $status){
2388 World::getXZ($index, $chunkX, $chunkZ);
2389 $this->unloadChunk($chunkX, $chunkZ);
2392 if(count($this->usedChunks) !== 0){
2393 throw new AssumptionFailedError(
"Previous loop should have cleared this array");
2395 $this->loadQueue = [];
2397 $this->removeCurrentWindow();
2398 $this->removePermanentInventories();
2400 $this->perm->getPermissionRecalculationCallbacks()->clear();
2402 $this->flagForDespawn();
2406 $this->disconnect(
"Player destroyed");
2407 $this->cursorInventory->removeAllViewers();
2408 $this->craftingGrid->removeAllViewers();
2409 parent::onDispose();
2413 $this->networkSession = null;
2414 unset($this->cursorInventory);
2415 unset($this->craftingGrid);
2416 $this->spawnPosition =
null;
2417 $this->deathPosition =
null;
2418 $this->blockBreakHandler =
null;
2419 parent::destroyCycles();
2429 public function __destruct(){
2430 parent::__destruct();
2431 $this->logger->debug(
"Destroyed by garbage collector");
2439 throw new \BadMethodCallException(
"Players can't be saved with chunks");
2443 $nbt = $this->saveNBT();
2445 $nbt->
setString(self::TAG_LAST_KNOWN_XUID, $this->xuid);
2447 if($this->location->isValid()){
2448 $nbt->setString(self::TAG_LEVEL, $this->getWorld()->getFolderName());
2451 if($this->hasValidCustomSpawn()){
2452 $spawn = $this->getSpawn();
2453 $nbt->setString(self::TAG_SPAWN_WORLD, $spawn->getWorld()->getFolderName());
2454 $nbt->setInt(self::TAG_SPAWN_X, $spawn->getFloorX());
2455 $nbt->setInt(self::TAG_SPAWN_Y, $spawn->getFloorY());
2456 $nbt->setInt(self::TAG_SPAWN_Z, $spawn->getFloorZ());
2459 if($this->deathPosition !==
null && $this->deathPosition->isValid()){
2460 $nbt->setString(self::TAG_DEATH_WORLD, $this->deathPosition->getWorld()->getFolderName());
2461 $nbt->setInt(self::TAG_DEATH_X, $this->deathPosition->getFloorX());
2462 $nbt->setInt(self::TAG_DEATH_Y, $this->deathPosition->getFloorY());
2463 $nbt->setInt(self::TAG_DEATH_Z, $this->deathPosition->getFloorZ());
2466 $nbt->
setInt(self::TAG_GAME_MODE, GameModeIdMap::getInstance()->toId($this->gamemode));
2467 $nbt->
setLong(self::TAG_FIRST_PLAYED, $this->firstPlayed);
2468 $nbt->
setLong(self::TAG_LAST_PLAYED, (
int) floor(microtime(
true) * 1000));
2477 $this->
server->saveOfflinePlayerData($this->username, $this->getSaveData());
2483 $this->removeCurrentWindow();
2485 $this->setDeathPosition($this->getPosition());
2487 $ev =
new PlayerDeathEvent($this, $this->getDrops(), $this->getXpDropAmount(),
null);
2490 if(!$ev->getKeepInventory()){
2491 foreach($ev->getDrops() as $item){
2492 $this->getWorld()->dropItem($this->location, $item);
2495 $clearInventory = fn(
Inventory $inventory) => $inventory->setContents(array_filter($inventory->getContents(), fn(
Item $item) => $item->
keepOnDeath()));
2496 $this->inventory->setHeldItemIndex(0);
2497 $clearInventory($this->inventory);
2498 $clearInventory($this->armorInventory);
2499 $clearInventory($this->offHandInventory);
2502 if(!$ev->getKeepXp()){
2503 $this->getWorld()->dropExperience($this->location, $ev->getXpDropAmount());
2504 $this->xpManager->setXpAndProgress(0, 0.0);
2507 if($ev->getDeathMessage() !==
""){
2508 $this->server->broadcastMessage($ev->getDeathMessage());
2511 $this->startDeathAnimation();
2513 $this->getNetworkSession()->onServerDeath($ev->getDeathScreenMessage());
2517 parent::onDeathUpdate($tickDiff);
2521 public function respawn() : void{
2522 if($this->
server->isHardcore()){
2523 if($this->kick(KnownTranslationFactory::pocketmine_disconnect_ban(KnownTranslationFactory::pocketmine_disconnect_ban_hardcore()))){
2524 $this->
server->getNameBans()->addBan($this->getName(),
"Died in hardcore mode");
2529 $this->actuallyRespawn();
2532 protected function actuallyRespawn() : void{
2533 if($this->respawnLocked){
2536 $this->respawnLocked =
true;
2538 $this->logger->debug(
"Waiting for safe respawn position to be located");
2539 $spawn = $this->getSpawn();
2540 $spawn->getWorld()->requestSafeSpawn($spawn)->onCompletion(
2541 function(Position $safeSpawn) :
void{
2542 if(!$this->isConnected()){
2545 $this->logger->debug(
"Respawn position located, completing respawn");
2546 $ev =
new PlayerRespawnEvent($this, $safeSpawn);
2547 $spawnPosition = $ev->getRespawnPosition();
2548 $spawnBlock = $spawnPosition->
getWorld()->getBlock($spawnPosition);
2549 if($spawnBlock instanceof RespawnAnchor){
2550 if($spawnBlock->getCharges() > 0){
2551 $spawnPosition->
getWorld()->setBlock($spawnPosition, $spawnBlock->setCharges($spawnBlock->getCharges() - 1));
2552 $spawnPosition->
getWorld()->addSound($spawnPosition,
new RespawnAnchorDepleteSound());
2554 $defaultSpawn = $this->
server->getWorldManager()->getDefaultWorld()?->getSpawnLocation();
2555 if($defaultSpawn !==
null){
2556 $this->setSpawn($defaultSpawn);
2557 $ev->setRespawnPosition($defaultSpawn);
2558 $this->sendMessage(KnownTranslationFactory::tile_respawn_anchor_notValid()->prefix(TextFormat::GRAY));
2564 $realSpawn = Position::fromObject($ev->getRespawnPosition()->add(0.5, 0, 0.5), $ev->getRespawnPosition()->getWorld());
2565 $this->teleport($realSpawn);
2567 $this->setSprinting(
false);
2568 $this->setSneaking(
false);
2569 $this->setFlying(
false);
2571 $this->extinguish(EntityExtinguishEvent::CAUSE_RESPAWN);
2572 $this->setAirSupplyTicks($this->getMaxAirSupplyTicks());
2573 $this->deadTicks = 0;
2574 $this->noDamageTicks = 60;
2576 $this->effectManager->clear();
2577 $this->setHealth($this->getMaxHealth());
2579 foreach($this->attributeMap->getAll() as $attr){
2580 if($attr->getId() === Attribute::EXPERIENCE || $attr->getId() === Attribute::EXPERIENCE_LEVEL){
2583 $attr->resetToDefault();
2586 $this->spawnToAll();
2587 $this->scheduleUpdate();
2589 $this->getNetworkSession()->onServerRespawn();
2590 $this->respawnLocked =
false;
2593 if($this->isConnected()){
2594 $this->getNetworkSession()->disconnectWithError(KnownTranslationFactory::pocketmine_disconnect_error_respawn());
2601 parent::applyPostDamageEffects($source);
2603 $this->hungerManager->exhaust(0.1, PlayerExhaustEvent::CAUSE_DAMAGE);
2607 if(!$this->isAlive()){
2611 if($this->isCreative()
2612 && $source->getCause() !== EntityDamageEvent::CAUSE_SUICIDE
2615 }elseif($this->allowFlight && $source->getCause() === EntityDamageEvent::CAUSE_FALL){
2619 parent::attack($source);
2622 protected function syncNetworkData(EntityMetadataCollection $properties) : void{
2623 parent::syncNetworkData($properties);
2625 $properties->setGenericFlag(EntityMetadataFlags::ACTION, $this->startAction > -1);
2626 $properties->setGenericFlag(EntityMetadataFlags::HAS_COLLISION, $this->hasBlockCollision());
2628 $properties->setPlayerFlag(PlayerMetadataFlags::SLEEP, $this->sleeping !==
null);
2629 $properties->setBlockPos(EntityMetadataProperties::PLAYER_BED_POSITION, $this->sleeping !==
null ? BlockPosition::fromVector3($this->sleeping) :
new BlockPosition(0, 0, 0));
2631 if($this->deathPosition !==
null && $this->deathPosition->world === $this->location->world){
2632 $properties->setBlockPos(EntityMetadataProperties::PLAYER_DEATH_POSITION, BlockPosition::fromVector3($this->deathPosition));
2634 $properties->setInt(EntityMetadataProperties::PLAYER_DEATH_DIMENSION, DimensionIds::OVERWORLD);
2635 $properties->setByte(EntityMetadataProperties::PLAYER_HAS_DIED, 1);
2637 $properties->setBlockPos(EntityMetadataProperties::PLAYER_DEATH_POSITION, new BlockPosition(0, 0, 0));
2638 $properties->setInt(EntityMetadataProperties::PLAYER_DEATH_DIMENSION, DimensionIds::OVERWORLD);
2639 $properties->setByte(EntityMetadataProperties::PLAYER_HAS_DIED, 0);
2643 public function sendData(?array $targets, ?array $data =
null) : void{
2644 if($targets === null){
2645 $targets = $this->getViewers();
2648 parent::sendData($targets, $data);
2652 if($this->spawned && $targets === null){
2653 $targets = $this->getViewers();
2656 parent::broadcastAnimation($animation, $targets);
2660 if($this->spawned && $targets === null){
2661 $targets = $this->getViewers();
2664 parent::broadcastSound($sound, $targets);
2670 protected function sendPosition(
Vector3 $pos, ?
float $yaw =
null, ?
float $pitch =
null,
int $mode = MovePlayerPacket::MODE_NORMAL) : void{
2671 $this->getNetworkSession()->syncMovement($pos, $yaw, $pitch, $mode);
2677 if(parent::teleport($pos, $yaw, $pitch)){
2679 $this->removeCurrentWindow();
2682 $this->sendPosition($this->location, $this->location->yaw, $this->location->pitch, MovePlayerPacket::MODE_TELEPORT);
2683 $this->broadcastMovement(
true);
2685 $this->spawnToAll();
2687 $this->resetFallDistance();
2688 $this->nextChunkOrderRun = 0;
2689 if($this->spawnChunkLoadCount !== -1){
2690 $this->spawnChunkLoadCount = 0;
2692 $this->blockBreakHandler =
null;
2696 $this->resetLastMovements();
2704 protected function addDefaultWindows() : void{
2705 $this->cursorInventory = new PlayerCursorInventory($this);
2706 $this->craftingGrid =
new PlayerCraftingInventory($this);
2708 $this->addPermanentInventories($this->inventory, $this->armorInventory, $this->cursorInventory, $this->offHandInventory, $this->craftingGrid);
2713 public function getCursorInventory() : PlayerCursorInventory{
2714 return $this->cursorInventory;
2717 public function getCraftingGrid() : CraftingGrid{
2718 return $this->craftingGrid;
2726 return $this->creativeInventory;
2733 $this->creativeInventory = $inventory;
2734 if($this->spawned && $this->isConnected()){
2735 $this->getNetworkSession()->getInvManager()?->syncCreative();
2743 private function doCloseInventory() : void{
2744 $inventories = [$this->craftingGrid, $this->cursorInventory];
2745 if($this->currentWindow instanceof TemporaryInventory){
2746 $inventories[] = $this->currentWindow;
2749 $builder =
new TransactionBuilder();
2750 foreach($inventories as $inventory){
2751 $contents = $inventory->getContents();
2753 if(count($contents) > 0){
2754 $drops = $builder->getInventory($this->inventory)->addItem(...$contents);
2755 foreach($drops as $drop){
2756 $builder->addAction(
new DropItemAction($drop));
2759 $builder->getInventory($inventory)->clearAll();
2763 $actions = $builder->generateActions();
2764 if(count($actions) !== 0){
2765 $transaction =
new InventoryTransaction($this, $actions);
2767 $transaction->execute();
2768 $this->logger->debug(
"Successfully evacuated items from temporary inventories");
2769 }
catch(TransactionCancelledException){
2770 $this->logger->debug(
"Plugin cancelled transaction evacuating items from temporary inventories; items will be destroyed");
2771 foreach($inventories as $inventory){
2772 $inventory->clearAll();
2774 }
catch(TransactionValidationException $e){
2775 throw new AssumptionFailedError(
"This server-generated transaction should never be invalid", 0, $e);
2784 return $this->currentWindow;
2791 if($inventory === $this->currentWindow){
2796 if($ev->isCancelled()){
2800 $this->removeCurrentWindow();
2802 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) ===
null){
2803 throw new \InvalidArgumentException(
"Player cannot open inventories in this state");
2805 $this->logger->debug(
"Opening inventory " . get_class($inventory) .
"#" . spl_object_id($inventory));
2806 $inventoryManager->onCurrentWindowChange($inventory);
2807 $inventory->onOpen($this);
2808 $this->currentWindow = $inventory;
2812 public function removeCurrentWindow() : void{
2813 $this->doCloseInventory();
2814 if($this->currentWindow !==
null){
2815 $currentWindow = $this->currentWindow;
2816 $this->logger->debug(
"Closing inventory " . get_class($this->currentWindow) .
"#" . spl_object_id($this->currentWindow));
2817 $this->currentWindow->onClose($this);
2818 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) !==
null){
2819 $inventoryManager->onCurrentWindowRemove();
2821 $this->currentWindow =
null;
2822 (
new InventoryCloseEvent($currentWindow, $this))->call();
2826 protected function addPermanentInventories(Inventory ...$inventories) : void{
2827 foreach($inventories as $inventory){
2828 $inventory->onOpen($this);
2829 $this->permanentWindows[spl_object_id($inventory)] = $inventory;
2833 protected function removePermanentInventories() : void{
2834 foreach($this->permanentWindows as $inventory){
2835 $inventory->onClose($this);
2837 $this->permanentWindows = [];
2844 $block = $this->getWorld()->getBlock($position);
2846 $this->getWorld()->setBlock($position, $block->setEditorEntityRuntimeId($this->getId()));
2847 $this->getNetworkSession()->onOpenSignEditor($position, $frontFace);
2849 throw new \InvalidArgumentException(
"Block at this position is not a sign");
2853 use ChunkListenerNoOpTrait {
2854 onChunkChanged as
private;
2855 onChunkUnloaded as
private;
2859 $status = $this->usedChunks[$hash =
World::chunkHash($chunkX, $chunkZ)] ?? null;
2860 if($status === UsedChunkStatus::SENT){
2861 $this->usedChunks[$hash] = UsedChunkStatus::NEEDED;
2862 $this->nextChunkOrderRun = 0;
2867 if($this->isUsingChunk($chunkX, $chunkZ)){
2868 $this->logger->debug(
"Detected forced unload of chunk " . $chunkX .
" " . $chunkZ);
2869 $this->unloadChunk($chunkX, $chunkZ);