173 use PermissibleDelegateTrait;
175 private const MOVES_PER_TICK = 2;
176 private const MOVE_BACKLOG_SIZE = 100 * self::MOVES_PER_TICK;
179 private const MAX_CHAT_CHAR_LENGTH = 512;
185 private const MAX_CHAT_BYTE_LENGTH = self::MAX_CHAT_CHAR_LENGTH * 4;
186 private const MAX_REACH_DISTANCE_CREATIVE = 13;
187 private const MAX_REACH_DISTANCE_SURVIVAL = 7;
188 private const MAX_REACH_DISTANCE_ENTITY_INTERACTION = 8;
190 public const DEFAULT_FLIGHT_SPEED_MULTIPLIER = 0.05;
192 public const TAG_FIRST_PLAYED =
"firstPlayed";
193 public const TAG_LAST_PLAYED =
"lastPlayed";
194 private const TAG_GAME_MODE =
"playerGameType";
195 private const TAG_SPAWN_WORLD =
"SpawnLevel";
196 private const TAG_SPAWN_X =
"SpawnX";
197 private const TAG_SPAWN_Y =
"SpawnY";
198 private const TAG_SPAWN_Z =
"SpawnZ";
199 private const TAG_DEATH_WORLD =
"DeathLevel";
200 private const TAG_DEATH_X =
"DeathPositionX";
201 private const TAG_DEATH_Y =
"DeathPositionY";
202 private const TAG_DEATH_Z =
"DeathPositionZ";
203 public const TAG_LEVEL =
"Level";
204 public const TAG_LAST_KNOWN_XUID =
"LastKnownXUID";
214 $lname = strtolower($name);
215 $len = strlen($name);
216 return $lname !==
"rcon" && $lname !==
"console" && $len >= 1 && $len <= 16 && preg_match(
"/[^A-Za-z0-9_ ]/", $name) === 0;
221 public bool $spawned =
false;
223 protected string $username;
224 protected string $displayName;
225 protected string $xuid =
"";
226 protected bool $authenticated;
229 protected ?Inventory $currentWindow =
null;
231 protected array $permanentWindows = [];
232 protected PlayerCursorInventory $cursorInventory;
233 protected PlayerCraftingInventory $craftingGrid;
234 protected CreativeInventory $creativeInventory;
236 protected int $messageCounter = 2;
238 protected int $firstPlayed;
239 protected int $lastPlayed;
240 protected GameMode $gamemode;
246 protected array $usedChunks = [];
251 private array $activeChunkGenerationRequests = [];
256 protected array $loadQueue = [];
257 protected int $nextChunkOrderRun = 5;
260 private array $tickingChunks = [];
262 protected int $viewDistance = -1;
263 protected int $spawnThreshold;
264 protected int $spawnChunkLoadCount = 0;
265 protected int $chunksPerTick;
266 protected ChunkSelector $chunkSelector;
267 protected ChunkLoader $chunkLoader;
268 protected ChunkTicker $chunkTicker;
271 protected array $hiddenPlayers = [];
273 protected float $moveRateLimit = 10 * self::MOVES_PER_TICK;
274 protected ?
float $lastMovementProcess =
null;
276 protected int $inAirTicks = 0;
278 protected float $stepHeight = 0.6;
280 protected ?Vector3 $sleeping =
null;
281 private ?
Position $spawnPosition =
null;
283 private bool $respawnLocked =
false;
285 private ?
Position $deathPosition =
null;
288 protected bool $autoJump =
true;
289 protected bool $allowFlight =
false;
290 protected bool $blockCollision =
true;
291 protected bool $flying =
false;
293 protected float $flightSpeedMultiplier = self::DEFAULT_FLIGHT_SPEED_MULTIPLIER;
296 protected ?
int $lineHeight =
null;
297 protected string $locale =
"en_US";
299 protected int $startAction = -1;
305 protected array $usedItemsCooldown = [];
307 private int $lastEmoteTick = 0;
309 protected int $formIdCounter = 0;
311 protected array $forms = [];
313 protected \Logger $logger;
318 $username = TextFormat::clean($playerInfo->getUsername());
319 $this->logger = new \PrefixedLogger($server->getLogger(),
"Player: $username");
322 $this->networkSession = $session;
323 $this->playerInfo = $playerInfo;
324 $this->authenticated = $authenticated;
326 $this->username = $username;
327 $this->displayName = $this->username;
328 $this->locale = $this->playerInfo->getLocale();
330 $this->uuid = $this->playerInfo->getUuid();
331 $this->xuid = $this->playerInfo instanceof
XboxLivePlayerInfo ? $this->playerInfo->getXuid() :
"";
333 $this->creativeInventory = CreativeInventory::getInstance();
335 $rootPermissions = [DefaultPermissions::ROOT_USER =>
true];
336 if($this->
server->isOp($this->username)){
337 $rootPermissions[DefaultPermissions::ROOT_OPERATOR] =
true;
340 $this->chunksPerTick = $this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_PER_TICK, 4);
341 $this->spawnThreshold = (int) (($this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4) ** 2) * M_PI);
344 $this->chunkLoader =
new class implements
ChunkLoader{};
346 $world = $spawnLocation->
getWorld();
348 $xSpawnChunk = $spawnLocation->getFloorX() >> Chunk::COORD_BIT_SIZE;
349 $zSpawnChunk = $spawnLocation->getFloorZ() >> Chunk::COORD_BIT_SIZE;
350 $world->registerChunkLoader($this->chunkLoader, $xSpawnChunk, $zSpawnChunk,
true);
351 $world->registerChunkListener($this, $xSpawnChunk, $zSpawnChunk);
352 $this->usedChunks[World::chunkHash($xSpawnChunk, $zSpawnChunk)] = UsedChunkStatus::NEEDED;
354 parent::__construct($spawnLocation, $this->playerInfo->getSkin(), $namedtag);
358 $this->setNameTag($this->username);
361 private function callDummyItemHeldEvent() : void{
362 $slot = $this->inventory->getHeldItemIndex();
371 protected function initEntity(
CompoundTag $nbt) : void{
372 parent::initEntity($nbt);
373 $this->addDefaultWindows();
375 $this->inventory->getListeners()->add(
new CallbackInventoryListener(
376 function(Inventory $unused,
int $slot) :
void{
377 if($slot === $this->inventory->getHeldItemIndex()){
378 $this->setUsingItem(
false);
380 $this->callDummyItemHeldEvent();
384 $this->setUsingItem(
false);
385 $this->callDummyItemHeldEvent();
389 $this->firstPlayed = $nbt->getLong(self::TAG_FIRST_PLAYED, $now = (
int) (microtime(
true) * 1000));
390 $this->lastPlayed = $nbt->getLong(self::TAG_LAST_PLAYED, $now);
392 if(!$this->
server->getForceGamemode() && ($gameModeTag = $nbt->
getTag(self::TAG_GAME_MODE)) instanceof IntTag){
393 $this->internalSetGameMode(GameModeIdMap::getInstance()->fromId($gameModeTag->getValue()) ?? GameMode::SURVIVAL);
395 $this->internalSetGameMode($this->
server->getGamemode());
398 $this->keepMovement =
true;
400 $this->setNameTagVisible();
401 $this->setNameTagAlwaysVisible();
402 $this->setCanClimb();
404 if(($world = $this->
server->getWorldManager()->getWorldByName($nbt->getString(self::TAG_SPAWN_WORLD,
""))) instanceof World){
405 $this->spawnPosition =
new Position($nbt->getInt(self::TAG_SPAWN_X), $nbt->getInt(self::TAG_SPAWN_Y), $nbt->getInt(self::TAG_SPAWN_Z), $world);
407 if(($world = $this->
server->getWorldManager()->getWorldByName($nbt->getString(self::TAG_DEATH_WORLD,
""))) instanceof World){
408 $this->deathPosition =
new Position($nbt->getInt(self::TAG_DEATH_X), $nbt->getInt(self::TAG_DEATH_Y), $nbt->getInt(self::TAG_DEATH_Z), $world);
412 public function getLeaveMessage() : Translatable|string{
414 return KnownTranslationFactory::multiplayer_player_left($this->getDisplayName())->prefix(TextFormat::YELLOW);
420 public function isAuthenticated() : bool{
421 return $this->authenticated;
446 return parent::getUniqueId();
453 return $this->firstPlayed;
460 return $this->lastPlayed;
463 public function hasPlayedBefore() : bool{
464 return $this->lastPlayed - $this->firstPlayed > 1;
477 if($this->allowFlight !== $value){
478 $this->allowFlight = $value;
479 $this->getNetworkSession()->syncAbilities($this);
490 return $this->allowFlight;
502 if($this->blockCollision !== $value){
503 $this->blockCollision = $value;
504 $this->getNetworkSession()->syncAbilities($this);
513 return $this->blockCollision;
516 public function setFlying(
bool $value) : void{
517 if($this->flying !== $value){
518 $this->flying = $value;
519 $this->resetFallDistance();
520 $this->getNetworkSession()->syncAbilities($this);
524 public function isFlying() : bool{
525 return $this->flying;
542 if($this->flightSpeedMultiplier !== $flightSpeedMultiplier){
543 $this->flightSpeedMultiplier = $flightSpeedMultiplier;
544 $this->getNetworkSession()->syncAbilities($this);
560 return $this->flightSpeedMultiplier;
563 public function setAutoJump(
bool $value) : void{
564 if($this->autoJump !== $value){
565 $this->autoJump = $value;
566 $this->getNetworkSession()->syncAdventureSettings();
570 public function hasAutoJump() : bool{
571 return $this->autoJump;
574 public function spawnTo(Player $player) : void{
575 if($this->isAlive() && $player->isAlive() && $player->canSee($this) && !$this->isSpectator()){
576 parent::spawnTo($player);
580 public function getServer() : Server{
585 return $this->lineHeight ?? 7;
589 if($height !== null && $height < 1){
590 throw new \InvalidArgumentException(
"Line height must be at least 1");
592 $this->lineHeight = $height;
595 public function canSee(
Player $player) : bool{
596 return !isset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
599 public function hidePlayer(Player $player) : void{
600 if($player === $this){
603 $this->hiddenPlayers[$player->getUniqueId()->getBytes()] =
true;
604 $player->despawnFrom($this);
607 public function showPlayer(Player $player) : void{
608 if($player === $this){
611 unset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
612 if($player->isOnline()){
613 $player->spawnTo($this);
617 public function canCollideWith(Entity $entity) : bool{
621 public function canBeCollidedWith() : bool{
622 return !$this->isSpectator() && parent::canBeCollidedWith();
625 public function resetFallDistance() : void{
626 parent::resetFallDistance();
627 $this->inAirTicks = 0;
630 public function getViewDistance() : int{
631 return $this->viewDistance;
634 public function setViewDistance(
int $distance) : void{
635 $newViewDistance = $this->
server->getAllowedViewDistance($distance);
637 if($newViewDistance !== $this->viewDistance){
638 $ev =
new PlayerViewDistanceChangeEvent($this, $this->viewDistance, $newViewDistance);
642 $this->viewDistance = $newViewDistance;
644 $this->spawnThreshold = (int) (min($this->viewDistance, $this->
server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4)) ** 2 * M_PI);
646 $this->nextChunkOrderRun = 0;
648 $this->getNetworkSession()->syncViewAreaRadius($this->viewDistance);
650 $this->logger->debug(
"Setting view distance to " . $this->viewDistance .
" (requested " . $distance .
")");
653 public function isOnline() : bool{
654 return $this->isConnected();
657 public function isConnected() : bool{
658 return $this->networkSession !== null && $this->networkSession->isConnected();
661 public function getNetworkSession() : NetworkSession{
662 if($this->networkSession === null){
663 throw new \LogicException(
"Player is not connected");
665 return $this->networkSession;
672 return $this->username;
679 return $this->displayName;
682 public function setDisplayName(
string $name) : void{
686 $this->displayName = $ev->getNewName();
697 return $this->locale;
700 public function getLanguage() :
Language{
701 return $this->
server->getLanguage();
708 public function changeSkin(
Skin $skin,
string $newSkinName,
string $oldSkinName) : bool{
712 if($ev->isCancelled()){
713 $this->sendSkin([$this]);
717 $this->setSkin($ev->getNewSkin());
718 $this->sendSkin($this->server->getOnlinePlayers());
727 public function sendSkin(?array $targets =
null) : void{
728 parent::sendSkin($targets ?? $this->
server->getOnlinePlayers());
735 return $this->startAction > -1;
738 public function setUsingItem(
bool $value) : void{
739 $this->startAction = $value ? $this->
server->getTick() : -1;
740 $this->networkPropertiesDirty =
true;
748 return $this->startAction === -1 ? -1 : ($this->
server->getTick() - $this->startAction);
755 $this->checkItemCooldowns();
756 return $this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()] ?? 0;
763 $this->checkItemCooldowns();
764 return isset($this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()]);
771 $ticks = $ticks ?? $item->getCooldownTicks();
773 $this->usedItemsCooldown[$item->
getCooldownTag() ?? $item->getStateId()] = $this->
server->getTick() + $ticks;
774 $this->getNetworkSession()->onItemCooldownChanged($item, $ticks);
778 protected function checkItemCooldowns() : void{
779 $serverTick = $this->
server->getTick();
780 foreach($this->usedItemsCooldown as $itemId => $cooldownUntil){
781 if($cooldownUntil <= $serverTick){
782 unset($this->usedItemsCooldown[$itemId]);
787 protected function setPosition(Vector3 $pos) : bool{
788 $oldWorld = $this->location->isValid() ? $this->location->getWorld() : null;
789 if(parent::setPosition($pos)){
790 $newWorld = $this->getWorld();
791 if($oldWorld !== $newWorld){
792 if($oldWorld !==
null){
793 foreach($this->usedChunks as $index => $status){
794 World::getXZ($index, $X, $Z);
795 $this->unloadChunk($X, $Z, $oldWorld);
799 $this->usedChunks = [];
800 $this->loadQueue = [];
801 $this->getNetworkSession()->onEnterWorld();
810 protected function unloadChunk(
int $x,
int $z, ?World $world =
null) : void{
811 $world = $world ?? $this->getWorld();
812 $index = World::chunkHash($x, $z);
813 if(isset($this->usedChunks[$index])){
814 foreach($world->getChunkEntities($x, $z) as $entity){
815 if($entity !== $this){
816 $entity->despawnFrom($this);
819 $this->getNetworkSession()->stopUsingChunk($x, $z);
820 unset($this->usedChunks[$index]);
821 unset($this->activeChunkGenerationRequests[$index]);
823 $world->unregisterChunkLoader($this->chunkLoader, $x, $z);
824 $world->unregisterChunkListener($this, $x, $z);
825 unset($this->loadQueue[$index]);
826 $world->unregisterTickingChunk($this->chunkTicker, $x, $z);
827 unset($this->tickingChunks[$index]);
830 protected function spawnEntitiesOnAllChunks() : void{
831 foreach($this->usedChunks as $chunkHash => $status){
832 if($status === UsedChunkStatus::SENT){
833 World::getXZ($chunkHash, $chunkX, $chunkZ);
834 $this->spawnEntitiesOnChunk($chunkX, $chunkZ);
839 protected function spawnEntitiesOnChunk(
int $chunkX,
int $chunkZ) : void{
840 foreach($this->getWorld()->getChunkEntities($chunkX, $chunkZ) as $entity){
841 if($entity !== $this && !$entity->isFlaggedForDespawn()){
842 $entity->spawnTo($this);
852 if(!$this->isConnected()){
856 Timings::$playerChunkSend->startTiming();
859 $world = $this->getWorld();
861 $limit = $this->chunksPerTick - count($this->activeChunkGenerationRequests);
862 foreach($this->loadQueue as $index => $distance){
863 if($count >= $limit){
869 World::getXZ($index, $X, $Z);
873 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_GENERATION;
874 $this->activeChunkGenerationRequests[$index] =
true;
875 unset($this->loadQueue[$index]);
876 $world->registerChunkLoader($this->chunkLoader, $X, $Z,
true);
877 $world->registerChunkListener($this, $X, $Z);
878 if(isset($this->tickingChunks[$index])){
879 $world->registerTickingChunk($this->chunkTicker, $X, $Z);
882 $world->requestChunkPopulation($X, $Z, $this->chunkLoader)->onCompletion(
883 function() use ($X, $Z, $index, $world) :
void{
884 if(!$this->isConnected() || !isset($this->usedChunks[$index]) || $world !== $this->getWorld()){
887 if($this->usedChunks[$index] !== UsedChunkStatus::REQUESTED_GENERATION){
893 unset($this->activeChunkGenerationRequests[$index]);
894 $this->usedChunks[$index] = UsedChunkStatus::REQUESTED_SENDING;
896 $this->getNetworkSession()->startUsingChunk($X, $Z,
function() use ($X, $Z, $index) :
void{
897 $this->usedChunks[$index] = UsedChunkStatus::SENT;
898 if($this->spawnChunkLoadCount === -1){
899 $this->spawnEntitiesOnChunk($X, $Z);
900 }elseif($this->spawnChunkLoadCount++ === $this->spawnThreshold){
901 $this->spawnChunkLoadCount = -1;
903 $this->spawnEntitiesOnAllChunks();
905 $this->getNetworkSession()->notifyTerrainReady();
907 (
new PlayerPostChunkSendEvent($this, $X, $Z))->call();
910 static function() :
void{
916 Timings::$playerChunkSend->stopTiming();
919 private function recheckBroadcastPermissions() : void{
921 DefaultPermissionNames::BROADCAST_ADMIN => Server::BROADCAST_CHANNEL_ADMINISTRATIVE,
922 DefaultPermissionNames::BROADCAST_USER => Server::BROADCAST_CHANNEL_USERS
923 ] as $permission => $channel){
924 if($this->hasPermission($permission)){
925 $this->
server->subscribeToBroadcastChannel($channel, $this);
927 $this->
server->unsubscribeFromBroadcastChannel($channel, $this);
940 $this->spawned =
true;
941 $this->recheckBroadcastPermissions();
942 $this->getPermissionRecalculationCallbacks()->add(
function(array $changedPermissionsOldValues) :
void{
943 if(isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_ADMINISTRATIVE]) || isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_USERS])){
944 $this->recheckBroadcastPermissions();
948 $ev =
new PlayerJoinEvent($this,
949 KnownTranslationFactory::multiplayer_player_joined($this->getDisplayName())->prefix(TextFormat::YELLOW)
952 if($ev->getJoinMessage() !==
""){
953 $this->server->broadcastMessage($ev->getJoinMessage());
956 $this->noDamageTicks = 60;
960 if($this->getHealth() <= 0){
961 $this->logger->debug(
"Quit while dead, forcing respawn");
962 $this->actuallyRespawn();
973 private function updateTickingChunkRegistrations(array $oldTickingChunks, array $newTickingChunks) : void{
974 $world = $this->getWorld();
975 foreach($oldTickingChunks as $hash => $_){
976 if(!isset($newTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
978 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
979 $world->unregisterTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
982 foreach($newTickingChunks as $hash => $_){
983 if(!isset($oldTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
985 World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
986 $world->registerTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
996 if(!$this->isConnected() || $this->viewDistance === -1){
1000 Timings::$playerChunkOrder->startTiming();
1003 $tickingChunks = [];
1004 $unloadChunks = $this->usedChunks;
1006 $world = $this->getWorld();
1007 $tickingChunkRadius = $world->getChunkTickRadius();
1009 foreach($this->chunkSelector->selectChunks(
1010 $this->server->getAllowedViewDistance($this->viewDistance),
1011 $this->location->getFloorX() >> Chunk::COORD_BIT_SIZE,
1012 $this->location->getFloorZ() >> Chunk::COORD_BIT_SIZE
1013 ) as $radius => $hash){
1014 if(!isset($this->usedChunks[$hash]) || $this->usedChunks[$hash] === UsedChunkStatus::NEEDED){
1015 $newOrder[$hash] =
true;
1017 if($radius < $tickingChunkRadius){
1018 $tickingChunks[$hash] =
true;
1020 unset($unloadChunks[$hash]);
1023 foreach($unloadChunks as $index => $status){
1024 World::getXZ($index, $X, $Z);
1025 $this->unloadChunk($X, $Z);
1028 $this->loadQueue = $newOrder;
1030 $this->updateTickingChunkRegistrations($this->tickingChunks, $tickingChunks);
1031 $this->tickingChunks = $tickingChunks;
1033 if(count($this->loadQueue) > 0 || count($unloadChunks) > 0){
1034 $this->getNetworkSession()->syncViewAreaCenterPoint($this->location, $this->viewDistance);
1037 Timings::$playerChunkOrder->stopTiming();
1045 return isset($this->usedChunks[
World::chunkHash($chunkX, $chunkZ)]);
1053 return $this->usedChunks;
1060 return $this->usedChunks[
World::chunkHash($chunkX, $chunkZ)] ?? null;
1067 $status = $this->usedChunks[
World::chunkHash($chunkX, $chunkZ)] ?? null;
1068 return $status === UsedChunkStatus::SENT;
1075 if($this->nextChunkOrderRun !== PHP_INT_MAX && $this->nextChunkOrderRun-- <= 0){
1076 $this->nextChunkOrderRun = PHP_INT_MAX;
1077 $this->orderChunks();
1080 if(count($this->loadQueue) > 0){
1081 $this->requestChunks();
1085 public function getDeathPosition() : ?Position{
1086 if($this->deathPosition !== null && !$this->deathPosition->isValid()){
1087 $this->deathPosition =
null;
1089 return $this->deathPosition;
1097 if($pos instanceof
Position && $pos->world !==
null){
1098 $world = $pos->world;
1100 $world = $this->getWorld();
1102 $this->deathPosition =
new Position($pos->x, $pos->y, $pos->z, $world);
1104 $this->deathPosition =
null;
1106 $this->networkPropertiesDirty =
true;
1113 if($this->hasValidCustomSpawn()){
1114 return $this->spawnPosition;
1116 $world = $this->
server->getWorldManager()->getDefaultWorld();
1118 return $world->getSpawnLocation();
1122 public function hasValidCustomSpawn() : bool{
1123 return $this->spawnPosition !== null && $this->spawnPosition->isValid();
1135 $world = $this->getWorld();
1137 $world = $pos->getWorld();
1139 $this->spawnPosition =
new Position($pos->x, $pos->y, $pos->z, $world);
1141 $this->spawnPosition =
null;
1143 $this->getNetworkSession()->syncPlayerSpawnPoint($this->getSpawn());
1146 public function isSleeping() : bool{
1147 return $this->sleeping !== null;
1150 public function sleepOn(Vector3 $pos) : bool{
1151 $pos = $pos->floor();
1152 $b = $this->getWorld()->getBlock($pos);
1154 $ev =
new PlayerBedEnterEvent($this, $b);
1156 if($ev->isCancelled()){
1160 if($b instanceof Bed){
1162 $this->getWorld()->setBlock($pos, $b);
1165 $this->sleeping = $pos;
1166 $this->networkPropertiesDirty =
true;
1168 $this->setSpawn($pos);
1170 $this->getWorld()->setSleepTicks(60);
1175 public function stopSleep() : void{
1176 if($this->sleeping instanceof Vector3){
1177 $b = $this->getWorld()->getBlock($this->sleeping);
1178 if($b instanceof Bed){
1179 $b->setOccupied(
false);
1180 $this->getWorld()->setBlock($this->sleeping, $b);
1182 (
new PlayerBedLeaveEvent($this, $b))->call();
1184 $this->sleeping =
null;
1185 $this->networkPropertiesDirty =
true;
1187 $this->getWorld()->setSleepTicks(0);
1189 $this->getNetworkSession()->sendDataPacket(AnimatePacket::create($this->getId(), AnimatePacket::ACTION_STOP_SLEEP));
1193 public function getGamemode() : GameMode{
1194 return $this->gamemode;
1197 protected function internalSetGameMode(GameMode $gameMode) : void{
1198 $this->gamemode = $gameMode;
1200 $this->allowFlight = $this->gamemode === GameMode::CREATIVE;
1201 $this->hungerManager->setEnabled($this->isSurvival());
1203 if($this->isSpectator()){
1204 $this->setFlying(
true);
1205 $this->setHasBlockCollision(
false);
1207 $this->onGround =
false;
1211 $this->sendPosition($this->location,
null,
null, MovePlayerPacket::MODE_TELEPORT);
1213 if($this->isSurvival()){
1214 $this->setFlying(
false);
1216 $this->setHasBlockCollision(
true);
1217 $this->setSilent(
false);
1218 $this->checkGroundState(0, 0, 0, 0, 0, 0);
1226 if($this->gamemode === $gm){
1232 if($ev->isCancelled()){
1236 $this->internalSetGameMode($gm);
1238 if($this->isSpectator()){
1239 $this->despawnFromAll();
1241 $this->spawnToAll();
1244 $this->getNetworkSession()->syncGameMode($this->gamemode);
1255 return $this->gamemode === GameMode::SURVIVAL || (!$literal && $this->gamemode === GameMode::ADVENTURE);
1265 return $this->gamemode === GameMode::CREATIVE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1275 return $this->gamemode === GameMode::ADVENTURE || (!$literal && $this->gamemode === GameMode::SPECTATOR);
1278 public function isSpectator() : bool{
1279 return $this->gamemode === GameMode::SPECTATOR;
1286 return $this->gamemode !== GameMode::CREATIVE;
1290 if($this->hasFiniteResources()){
1291 return parent::getDrops();
1298 if($this->hasFiniteResources()){
1299 return parent::getXpDropAmount();
1305 protected function checkGroundState(
float $wantedX,
float $wantedY,
float $wantedZ,
float $dx,
float $dy,
float $dz) : void{
1306 if($this->gamemode === GameMode::SPECTATOR){
1307 $this->onGround =
false;
1309 $bb = clone $this->boundingBox;
1310 $bb->minY = $this->location->y - 0.2;
1311 $bb->maxY = $this->location->y + 0.2;
1315 $bb = $bb->addCoord(-$dx, -$dy, -$dz);
1317 $this->onGround = $this->isCollided = count($this->getWorld()->getCollisionBlocks($bb,
true)) > 0;
1325 protected function checkNearEntities() : void{
1326 foreach($this->getWorld()->getNearbyEntities($this->boundingBox->expandedCopy(1, 0.5, 1), $this) as $entity){
1327 $entity->scheduleUpdate();
1329 if(!$entity->isAlive() || $entity->isFlaggedForDespawn()){
1333 $entity->onCollideWithPlayer($this);
1337 public function getInAirTicks() : int{
1338 return $this->inAirTicks;
1350 Timings::$playerMove->startTiming();
1352 $this->actuallyHandleMovement($newPos);
1354 Timings::$playerMove->stopTiming();
1358 private function actuallyHandleMovement(Vector3 $newPos) : void{
1359 $this->moveRateLimit--;
1360 if($this->moveRateLimit < 0){
1364 $oldPos = $this->location;
1365 $distanceSquared = $newPos->distanceSquared($oldPos);
1369 if($distanceSquared > 225){
1381 $this->logger->debug(
"Moved too fast (" . sqrt($distanceSquared) .
" blocks in 1 movement), reverting movement");
1382 $this->logger->debug(
"Old position: " . $oldPos->asVector3() .
", new position: " . $newPos);
1384 }elseif(!$this->getWorld()->isInLoadedTerrain($newPos)){
1386 $this->nextChunkOrderRun = 0;
1389 if(!$revert && $distanceSquared !== 0.0){
1390 $dx = $newPos->x - $oldPos->x;
1391 $dy = $newPos->y - $oldPos->y;
1392 $dz = $newPos->z - $oldPos->z;
1394 $this->move($dx, $dy, $dz);
1398 $this->revertMovement($oldPos);
1406 $now = microtime(true);
1407 $multiplier = $this->lastMovementProcess !==
null ? ($now - $this->lastMovementProcess) * 20 : 1;
1408 $exceededRateLimit = $this->moveRateLimit < 0;
1409 $this->moveRateLimit = min(self::MOVE_BACKLOG_SIZE, max(0, $this->moveRateLimit) + self::MOVES_PER_TICK * $multiplier);
1410 $this->lastMovementProcess = $now;
1412 $from = clone $this->lastLocation;
1413 $to = clone $this->location;
1415 $delta = $to->distanceSquared($from);
1416 $deltaAngle = abs($this->lastLocation->yaw - $to->yaw) + abs($this->lastLocation->pitch - $to->pitch);
1418 if($delta > 0.0001 || $deltaAngle > 1.0){
1419 if(PlayerMoveEvent::hasHandlers()){
1424 if($ev->isCancelled()){
1425 $this->revertMovement($from);
1429 if($to->distanceSquared($ev->getTo()) > 0.01){
1430 $this->teleport($ev->getTo());
1435 $this->lastLocation = $to;
1436 $this->broadcastMovement();
1438 $horizontalDistanceTravelled = sqrt((($from->x - $to->x) ** 2) + (($from->z - $to->z) ** 2));
1439 if($horizontalDistanceTravelled > 0){
1441 if($this->isSprinting()){
1442 $this->hungerManager->exhaust(0.01 * $horizontalDistanceTravelled, PlayerExhaustEvent::CAUSE_SPRINTING);
1444 $this->hungerManager->exhaust(0.0, PlayerExhaustEvent::CAUSE_WALKING);
1447 if($this->nextChunkOrderRun > 20){
1448 $this->nextChunkOrderRun = 20;
1453 if($exceededRateLimit){
1454 $this->logger->debug(
"Exceeded movement rate limit, forcing to last accepted position");
1455 $this->sendPosition($this->location, $this->location->getYaw(), $this->location->getPitch(), MovePlayerPacket::MODE_RESET);
1459 protected function revertMovement(Location $from) : void{
1460 $this->setPosition($from);
1461 $this->sendPosition($from, $from->yaw, $from->pitch, MovePlayerPacket::MODE_RESET);
1464 protected function calculateFallDamage(
float $fallDistance) : float{
1465 return $this->flying ? 0 : parent::calculateFallDamage($fallDistance);
1473 public function setMotion(
Vector3 $motion) : bool{
1474 if(parent::setMotion($motion)){
1475 $this->broadcastMotion();
1476 $this->getNetworkSession()->sendDataPacket(SetActorMotionPacket::create($this->
id, $motion, tick: 0));
1483 protected function updateMovement(
bool $teleport =
false) : void{
1487 protected function tryChangeMovement() : void{
1491 public function onUpdate(int $currentTick) : bool{
1492 $tickDiff = $currentTick - $this->lastUpdate;
1498 $this->messageCounter = 2;
1500 $this->lastUpdate = $currentTick;
1502 if($this->justCreated){
1503 $this->onFirstUpdate($currentTick);
1506 if(!$this->isAlive() && $this->spawned){
1507 $this->onDeathUpdate($tickDiff);
1511 $this->timings->startTiming();
1514 Timings::$playerMove->startTiming();
1515 $this->processMostRecentMovements();
1516 $this->motion = Vector3::zero();
1517 if($this->onGround){
1518 $this->inAirTicks = 0;
1520 $this->inAirTicks += $tickDiff;
1522 Timings::$playerMove->stopTiming();
1524 Timings::$entityBaseTick->startTiming();
1525 $this->entityBaseTick($tickDiff);
1526 Timings::$entityBaseTick->stopTiming();
1528 if($this->isCreative() && $this->fireTicks > 1){
1529 $this->fireTicks = 1;
1532 if(!$this->isSpectator() && $this->isAlive()){
1533 Timings::$playerCheckNearEntities->startTiming();
1534 $this->checkNearEntities();
1535 Timings::$playerCheckNearEntities->stopTiming();
1538 if($this->blockBreakHandler !==
null && !$this->blockBreakHandler->update()){
1539 $this->blockBreakHandler =
null;
1543 $this->timings->stopTiming();
1549 return $this->isCreative() || parent::canEat();
1553 return $this->isCreative() || parent::canBreathe();
1562 $eyePos = $this->getEyePos();
1563 if($eyePos->distanceSquared($pos) > $maxDistance ** 2){
1567 $dV = $this->getDirectionVector();
1568 $eyeDot = $dV->dot($eyePos);
1569 $targetDot = $dV->dot($pos);
1570 return ($targetDot - $eyeDot) >= -$maxDiff;
1577 public function chat(
string $message) : bool{
1578 $this->removeCurrentWindow();
1580 if($this->messageCounter <= 0){
1586 $maxTotalLength = $this->messageCounter * (self::MAX_CHAT_BYTE_LENGTH + 1);
1587 if(strlen($message) > $maxTotalLength){
1591 $message = TextFormat::clean($message,
false);
1592 foreach(explode(
"\n", $message, $this->messageCounter + 1) as $messagePart){
1593 if(trim($messagePart) !==
"" && strlen($messagePart) <= self::MAX_CHAT_BYTE_LENGTH && mb_strlen($messagePart,
'UTF-8') <= self::MAX_CHAT_CHAR_LENGTH && $this->messageCounter-- > 0){
1594 if(str_starts_with($messagePart,
'./')){
1595 $messagePart = substr($messagePart, 1);
1598 if(str_starts_with($messagePart,
"/")){
1599 Timings::$playerCommand->startTiming();
1600 $this->server->dispatchCommand($this, substr($messagePart, 1));
1601 Timings::$playerCommand->stopTiming();
1603 $ev =
new PlayerChatEvent($this, $messagePart, $this->
server->getBroadcastChannelSubscribers(Server::BROADCAST_CHANNEL_USERS),
new StandardChatFormatter());
1605 if(!$ev->isCancelled()){
1606 $this->
server->broadcastMessage($ev->getFormatter()->format($ev->getPlayer()->getDisplayName(), $ev->getMessage()), $ev->getRecipients());
1615 public function selectHotbarSlot(
int $hotbarSlot) : bool{
1616 if(!$this->inventory->isHotbarSlot($hotbarSlot)){
1619 if($hotbarSlot === $this->inventory->getHeldItemIndex()){
1623 $ev =
new PlayerItemHeldEvent($this, $this->inventory->getItem($hotbarSlot), $hotbarSlot);
1625 if($ev->isCancelled()){
1629 $this->inventory->setHeldItemIndex($hotbarSlot);
1630 $this->setUsingItem(
false);
1638 private function returnItemsFromAction(Item $oldHeldItem, Item $newHeldItem, array $extraReturnedItems) : void{
1639 $heldItemChanged = false;
1641 if(!$newHeldItem->equalsExact($oldHeldItem) && $oldHeldItem->equalsExact($this->inventory->getItemInHand())){
1644 $newReplica = clone $oldHeldItem;
1645 $newReplica->setCount($newHeldItem->getCount());
1646 if($newReplica instanceof Durable && $newHeldItem instanceof Durable){
1647 $newDamage = $newHeldItem->getDamage();
1648 if($newDamage >= 0 && $newDamage <= $newReplica->getMaxDurability()){
1649 $newReplica->setDamage($newDamage);
1652 $damagedOrDeducted = $newReplica->equalsExact($newHeldItem);
1654 if(!$damagedOrDeducted || $this->hasFiniteResources()){
1655 if($newHeldItem instanceof Durable && $newHeldItem->isBroken()){
1656 $this->broadcastSound(
new ItemBreakSound());
1658 $this->inventory->setItemInHand($newHeldItem);
1659 $heldItemChanged =
true;
1663 if(!$heldItemChanged){
1664 $newHeldItem = $oldHeldItem;
1667 if($heldItemChanged && count($extraReturnedItems) > 0 && $newHeldItem->isNull()){
1668 $this->inventory->setItemInHand(array_shift($extraReturnedItems));
1670 foreach($this->inventory->addItem(...$extraReturnedItems) as $drop){
1672 $ev =
new PlayerDropItemEvent($this, $drop);
1673 if($this->isSpectator()){
1677 if(!$ev->isCancelled()){
1678 $this->dropItem($drop);
1689 $directionVector = $this->getDirectionVector();
1690 $item = $this->inventory->getItemInHand();
1691 $oldItem = clone $item;
1694 if($this->hasItemCooldown($item) || $this->isSpectator()){
1700 if($ev->isCancelled()){
1704 $returnedItems = [];
1705 $result = $item->onClickAir($this, $directionVector, $returnedItems);
1706 if($result === ItemUseResult::FAIL){
1710 $this->resetItemCooldown($oldItem);
1711 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1713 $this->setUsingItem($item instanceof Releasable && $item->canStartUsingItem($this));
1724 $slot = $this->inventory->getItemInHand();
1726 $oldItem = clone $slot;
1729 if($this->hasItemCooldown($slot)){
1734 if($ev->isCancelled() || !$this->consumeObject($slot)){
1738 $this->setUsingItem(
false);
1739 $this->resetItemCooldown($oldItem);
1742 $this->returnItemsFromAction($oldItem, $slot, [$slot->getResidue()]);
1757 $item = $this->inventory->getItemInHand();
1758 if(!$this->isUsingItem() || $this->hasItemCooldown($item)){
1762 $oldItem = clone $item;
1764 $returnedItems = [];
1765 $result = $item->onReleaseUsing($this, $returnedItems);
1766 if($result === ItemUseResult::SUCCESS){
1767 $this->resetItemCooldown($oldItem);
1768 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1774 $this->setUsingItem(
false);
1778 public function pickBlock(Vector3 $pos,
bool $addTileNBT) : bool{
1779 $block = $this->getWorld()->getBlock($pos);
1780 if($block instanceof UnknownBlock){
1784 $item = $block->getPickedItem($addTileNBT);
1786 $ev =
new PlayerBlockPickEvent($this, $block, $item);
1787 $existingSlot = $this->inventory->first($item);
1788 if($existingSlot === -1 && $this->hasFiniteResources()){
1793 if(!$ev->isCancelled()){
1794 $this->equipOrAddPickedItem($existingSlot, $item);
1800 public function pickEntity(
int $entityId) : bool{
1801 $entity = $this->getWorld()->getEntity($entityId);
1802 if($entity ===
null){
1806 $item = $entity->getPickedItem();
1811 $ev =
new PlayerEntityPickEvent($this, $entity, $item);
1812 $existingSlot = $this->inventory->first($item);
1813 if($existingSlot === -1 && ($this->hasFiniteResources() || $this->isSpectator())){
1818 if(!$ev->isCancelled()){
1819 $this->equipOrAddPickedItem($existingSlot, $item);
1825 private function equipOrAddPickedItem(
int $existingSlot, Item $item) : void{
1826 if($existingSlot !== -1){
1827 if($existingSlot < $this->inventory->getHotbarSize()){
1828 $this->inventory->setHeldItemIndex($existingSlot);
1830 $this->inventory->swap($this->inventory->getHeldItemIndex(), $existingSlot);
1833 $firstEmpty = $this->inventory->firstEmpty();
1834 if($firstEmpty === -1){
1835 $this->inventory->setItemInHand($item);
1836 }elseif($firstEmpty < $this->inventory->getHotbarSize()){
1837 $this->inventory->setItem($firstEmpty, $item);
1838 $this->inventory->setHeldItemIndex($firstEmpty);
1840 $this->inventory->swap($this->inventory->getHeldItemIndex(), $firstEmpty);
1841 $this->inventory->setItemInHand($item);
1852 if($pos->distanceSquared($this->location) > 10000){
1856 $target = $this->getWorld()->getBlock($pos);
1858 $ev =
new PlayerInteractEvent($this, $this->inventory->getItemInHand(), $target,
null, $face, PlayerInteractEvent::LEFT_CLICK_BLOCK);
1859 if($this->isSpectator()){
1863 if($ev->isCancelled()){
1866 $this->broadcastAnimation(
new ArmSwingAnimation($this), $this->getViewers());
1867 if($target->onAttack($this->inventory->getItemInHand(), $face, $this)){
1871 $block = $target->getSide($face);
1872 if($block->hasTypeTag(BlockTypeTags::FIRE)){
1873 $this->getWorld()->setBlock($block->getPosition(), VanillaBlocks::AIR());
1874 $this->getWorld()->addSound($block->getPosition()->add(0.5, 0.5, 0.5),
new FireExtinguishSound());
1878 if(!$this->isCreative() && !$target->getBreakInfo()->breaksInstantly()){
1879 $this->blockBreakHandler =
new SurvivalBlockBreakHandler($this, $pos, $target, $face, 16);
1885 public function continueBreakBlock(Vector3 $pos,
int $face) : void{
1886 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1887 $this->blockBreakHandler->setTargetedFace($face);
1891 public function stopBreakBlock(Vector3 $pos) : void{
1892 if($this->blockBreakHandler !== null && $this->blockBreakHandler->getBlockPos()->distanceSquared($pos) < 0.0001){
1893 $this->blockBreakHandler =
null;
1903 $this->removeCurrentWindow();
1905 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1906 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1907 $this->stopBreakBlock($pos);
1908 $item = $this->inventory->getItemInHand();
1909 $oldItem = clone $item;
1910 $returnedItems = [];
1911 if($this->getWorld()->useBreakOn($pos, $item, $this, true, $returnedItems)){
1912 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1913 $this->hungerManager->exhaust(0.005, PlayerExhaustEvent::CAUSE_MINING);
1917 $this->logger->debug(
"Cancelled block break at $pos due to not currently being interactable");
1929 $this->setUsingItem(false);
1931 if($this->canInteract($pos->add(0.5, 0.5, 0.5), $this->isCreative() ? self::MAX_REACH_DISTANCE_CREATIVE : self::MAX_REACH_DISTANCE_SURVIVAL)){
1932 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
1933 $item = $this->inventory->getItemInHand();
1934 $oldItem = clone $item;
1935 $returnedItems = [];
1936 if($this->getWorld()->useItemOn($pos, $item, $face, $clickOffset, $this, true, $returnedItems)){
1937 $this->returnItemsFromAction($oldItem, $item, $returnedItems);
1941 $this->logger->debug(
"Cancelled interaction of block at $pos due to not currently being interactable");
1954 if(!$entity->isAlive()){
1958 $this->logger->debug(
"Attempted to attack non-attackable entity " . get_class($entity));
1962 $heldItem = $this->inventory->getItemInHand();
1963 $oldItem = clone $heldItem;
1965 $ev =
new EntityDamageByEntityEvent($this, $entity, EntityDamageEvent::CAUSE_ENTITY_ATTACK, $heldItem->getAttackPoints());
1966 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
1967 $this->logger->debug(
"Cancelled attack of entity " . $entity->getId() .
" due to not currently being interactable");
1969 }elseif($this->isSpectator() || ($entity instanceof Player && !$this->server->getConfigGroup()->getConfigBool(ServerProperties::PVP))){
1973 $meleeEnchantmentDamage = 0;
1975 $meleeEnchantments = [];
1976 foreach($heldItem->getEnchantments() as $enchantment){
1977 $type = $enchantment->getType();
1978 if($type instanceof MeleeWeaponEnchantment && $type->isApplicableTo($entity)){
1979 $meleeEnchantmentDamage += $type->getDamageBonus($enchantment->getLevel());
1980 $meleeEnchantments[] = $enchantment;
1983 $ev->setModifier($meleeEnchantmentDamage, EntityDamageEvent::MODIFIER_WEAPON_ENCHANTMENTS);
1985 if(!$this->isSprinting() && !$this->isFlying() && $this->fallDistance > 0 && !$this->effectManager->has(VanillaEffects::BLINDNESS()) && !$this->isUnderwater()){
1986 $ev->setModifier($ev->getFinalDamage() / 2, EntityDamageEvent::MODIFIER_CRITICAL);
1989 $entity->attack($ev);
1990 $this->broadcastAnimation(
new ArmSwingAnimation($this), $this->getViewers());
1992 $soundPos = $entity->getPosition()->add(0, $entity->size->getHeight() / 2, 0);
1993 if($ev->isCancelled()){
1994 $this->getWorld()->addSound($soundPos,
new EntityAttackNoDamageSound());
1997 $this->getWorld()->addSound($soundPos,
new EntityAttackSound());
1999 if($ev->getModifier(EntityDamageEvent::MODIFIER_CRITICAL) > 0 && $entity instanceof Living){
2000 $entity->broadcastAnimation(
new CriticalHitAnimation($entity));
2003 foreach($meleeEnchantments as $enchantment){
2004 $type = $enchantment->getType();
2005 assert($type instanceof MeleeWeaponEnchantment);
2006 $type->onPostAttack($this, $entity, $enchantment->getLevel());
2009 if($this->isAlive()){
2012 $returnedItems = [];
2013 $heldItem->onAttackEntity($entity, $returnedItems);
2014 $this->returnItemsFromAction($oldItem, $heldItem, $returnedItems);
2016 $this->hungerManager->exhaust(0.1, PlayerExhaustEvent::CAUSE_ATTACK);
2029 if(!$ev->isCancelled()){
2030 $this->broadcastSound(new EntityAttackNoDamageSound());
2031 $this->broadcastAnimation(new ArmSwingAnimation($this), $this->getViewers());
2041 if(!$this->canInteract($entity->getLocation(), self::MAX_REACH_DISTANCE_ENTITY_INTERACTION)){
2042 $this->logger->debug(
"Cancelled interaction with entity " . $entity->getId() .
" due to not currently being interactable");
2048 $item = $this->inventory->getItemInHand();
2049 $oldItem = clone $item;
2050 if(!$ev->isCancelled()){
2051 if($item->onInteractEntity($this, $entity, $clickPos)){
2052 if($this->hasFiniteResources() && !$item->equalsExact($oldItem) && $oldItem->equalsExact($this->inventory->getItemInHand())){
2053 if($item instanceof Durable && $item->isBroken()){
2054 $this->broadcastSound(new ItemBreakSound());
2056 $this->inventory->setItemInHand($item);
2059 return $entity->
onInteract($this, $clickPos);
2064 public function toggleSprint(
bool $sprint) : bool{
2065 if($sprint === $this->sprinting){
2068 $ev =
new PlayerToggleSprintEvent($this, $sprint);
2070 if($ev->isCancelled()){
2073 $this->setSprinting($sprint);
2077 public function toggleSneak(
bool $sneak) : bool{
2078 if($sneak === $this->sneaking){
2081 $ev =
new PlayerToggleSneakEvent($this, $sneak);
2083 if($ev->isCancelled()){
2086 $this->setSneaking($sneak);
2090 public function toggleFlight(
bool $fly) : bool{
2091 if($fly === $this->flying){
2094 $ev =
new PlayerToggleFlightEvent($this, $fly);
2095 if(!$this->allowFlight){
2099 if($ev->isCancelled()){
2102 $this->setFlying($fly);
2106 public function toggleGlide(
bool $glide) : bool{
2107 if($glide === $this->gliding){
2110 $ev =
new PlayerToggleGlideEvent($this, $glide);
2112 if($ev->isCancelled()){
2115 $this->setGliding($glide);
2119 public function toggleSwim(
bool $swim) : bool{
2120 if($swim === $this->swimming){
2123 $ev =
new PlayerToggleSwimEvent($this, $swim);
2125 if($ev->isCancelled()){
2128 $this->setSwimming($swim);
2132 public function emote(
string $emoteId) : void{
2133 $currentTick = $this->
server->getTick();
2134 if($currentTick - $this->lastEmoteTick > 5){
2135 $this->lastEmoteTick = $currentTick;
2136 $event =
new PlayerEmoteEvent($this, $emoteId);
2138 if(!$event->isCancelled()){
2139 $emoteId = $event->getEmoteId();
2140 parent::emote($emoteId);
2150 $this->getWorld()->dropItem($this->location->add(0, 1.3, 0), $item, $this->getDirectionVector()->multiply(0.4), 40);
2160 public function sendTitle(
string $title,
string $subtitle =
"",
int $fadeIn = -1,
int $stay = -1,
int $fadeOut = -1) : void{
2161 $this->setTitleDuration($fadeIn, $stay, $fadeOut);
2162 if($subtitle !==
""){
2163 $this->sendSubTitle($subtitle);
2165 $this->getNetworkSession()->onTitle($title);
2172 $this->getNetworkSession()->onSubTitle($subtitle);
2179 $this->getNetworkSession()->onActionBar($message);
2186 $this->getNetworkSession()->onClearTitle();
2193 $this->getNetworkSession()->onResetTitleOptions();
2204 if($fadeIn >= 0 && $stay >= 0 && $fadeOut >= 0){
2205 $this->getNetworkSession()->onTitleDuration($fadeIn, $stay, $fadeOut);
2213 $this->getNetworkSession()->onChatMessage($message);
2216 public function sendJukeboxPopup(
Translatable|
string $message) : void{
2217 $this->getNetworkSession()->onJukeboxPopup($message);
2226 $this->getNetworkSession()->onPopup($message);
2229 public function sendTip(
string $message) : void{
2230 $this->getNetworkSession()->onTip($message);
2237 $this->getNetworkSession()->onToastNotification($title, $body);
2246 $id = $this->formIdCounter++;
2247 if($this->getNetworkSession()->onFormSent($id, $form)){
2248 $this->forms[$id] = $form;
2252 public function onFormSubmit(
int $formId, mixed $responseData) : bool{
2253 if(!isset($this->forms[$formId])){
2254 $this->logger->debug(
"Got unexpected response for form $formId");
2259 $this->forms[$formId]->handleResponse($this, $responseData);
2260 }
catch(FormValidationException $e){
2261 $this->logger->critical(
"Failed to validate form " . get_class($this->forms[$formId]) .
": " . $e->getMessage());
2262 $this->logger->logException($e);
2264 unset($this->forms[$formId]);
2274 $this->getNetworkSession()->onCloseAllForms();
2289 if(!$ev->isCancelled()){
2290 $this->getNetworkSession()->transfer($ev->getAddress(), $ev->getPort(), $ev->getMessage());
2305 $ev = new
PlayerKickEvent($this, $reason, $quitMessage ?? $this->getLeaveMessage(), $disconnectScreenMessage);
2307 if(!$ev->isCancelled()){
2308 $reason = $ev->getDisconnectReason();
2310 $reason = KnownTranslationFactory::disconnectionScreen_noReason();
2312 $disconnectScreenMessage = $ev->getDisconnectScreenMessage() ?? $reason;
2313 if($disconnectScreenMessage ===
""){
2314 $disconnectScreenMessage = KnownTranslationFactory::disconnectionScreen_noReason();
2316 $this->disconnect($reason, $ev->getQuitMessage(), $disconnectScreenMessage);
2338 if(!$this->isConnected()){
2342 $this->getNetworkSession()->onPlayerDestroyed($reason, $disconnectScreenMessage ?? $reason);
2343 $this->onPostDisconnect($reason, $quitMessage);
2354 if($this->isConnected()){
2355 throw new \LogicException(
"Player is still connected");
2359 $this->server->unsubscribeFromAllBroadcastChannels($this);
2361 $this->removeCurrentWindow();
2363 $ev =
new PlayerQuitEvent($this, $quitMessage ?? $this->getLeaveMessage(), $reason);
2365 if(($quitMessage = $ev->getQuitMessage()) !==
""){
2366 $this->server->broadcastMessage($quitMessage);
2370 $this->spawned =
false;
2373 $this->blockBreakHandler =
null;
2374 $this->despawnFromAll();
2376 $this->
server->removeOnlinePlayer($this);
2378 foreach($this->
server->getOnlinePlayers() as $player){
2379 if(!$player->canSee($this)){
2380 $player->showPlayer($this);
2383 $this->hiddenPlayers = [];
2385 if($this->location->isValid()){
2386 foreach($this->usedChunks as $index => $status){
2387 World::getXZ($index, $chunkX, $chunkZ);
2388 $this->unloadChunk($chunkX, $chunkZ);
2391 if(count($this->usedChunks) !== 0){
2392 throw new AssumptionFailedError(
"Previous loop should have cleared this array");
2394 $this->loadQueue = [];
2396 $this->removeCurrentWindow();
2397 $this->removePermanentInventories();
2399 $this->perm->getPermissionRecalculationCallbacks()->clear();
2401 $this->flagForDespawn();
2405 $this->disconnect(
"Player destroyed");
2406 $this->cursorInventory->removeAllViewers();
2407 $this->craftingGrid->removeAllViewers();
2408 parent::onDispose();
2412 $this->networkSession = null;
2413 unset($this->cursorInventory);
2414 unset($this->craftingGrid);
2415 $this->spawnPosition =
null;
2416 $this->deathPosition =
null;
2417 $this->blockBreakHandler =
null;
2418 parent::destroyCycles();
2428 public function __destruct(){
2429 parent::__destruct();
2430 $this->logger->debug(
"Destroyed by garbage collector");
2438 throw new \BadMethodCallException(
"Players can't be saved with chunks");
2442 $nbt = $this->saveNBT();
2444 $nbt->
setString(self::TAG_LAST_KNOWN_XUID, $this->xuid);
2446 if($this->location->isValid()){
2447 $nbt->setString(self::TAG_LEVEL, $this->getWorld()->getFolderName());
2450 if($this->hasValidCustomSpawn()){
2451 $spawn = $this->getSpawn();
2452 $nbt->setString(self::TAG_SPAWN_WORLD, $spawn->getWorld()->getFolderName());
2453 $nbt->setInt(self::TAG_SPAWN_X, $spawn->getFloorX());
2454 $nbt->setInt(self::TAG_SPAWN_Y, $spawn->getFloorY());
2455 $nbt->setInt(self::TAG_SPAWN_Z, $spawn->getFloorZ());
2458 if($this->deathPosition !==
null && $this->deathPosition->isValid()){
2459 $nbt->setString(self::TAG_DEATH_WORLD, $this->deathPosition->getWorld()->getFolderName());
2460 $nbt->setInt(self::TAG_DEATH_X, $this->deathPosition->getFloorX());
2461 $nbt->setInt(self::TAG_DEATH_Y, $this->deathPosition->getFloorY());
2462 $nbt->setInt(self::TAG_DEATH_Z, $this->deathPosition->getFloorZ());
2465 $nbt->
setInt(self::TAG_GAME_MODE, GameModeIdMap::getInstance()->toId($this->gamemode));
2466 $nbt->
setLong(self::TAG_FIRST_PLAYED, $this->firstPlayed);
2467 $nbt->
setLong(self::TAG_LAST_PLAYED, (
int) floor(microtime(
true) * 1000));
2476 $this->
server->saveOfflinePlayerData($this->username, $this->getSaveData());
2482 $this->removeCurrentWindow();
2484 $this->setDeathPosition($this->getPosition());
2486 $ev =
new PlayerDeathEvent($this, $this->getDrops(), $this->getXpDropAmount(),
null);
2489 if(!$ev->getKeepInventory()){
2490 foreach($ev->getDrops() as $item){
2491 $this->getWorld()->dropItem($this->location, $item);
2494 $clearInventory = fn(
Inventory $inventory) => $inventory->setContents(array_filter($inventory->getContents(), fn(
Item $item) => $item->
keepOnDeath()));
2495 $this->inventory->setHeldItemIndex(0);
2496 $clearInventory($this->inventory);
2497 $clearInventory($this->armorInventory);
2498 $clearInventory($this->offHandInventory);
2501 if(!$ev->getKeepXp()){
2502 $this->getWorld()->dropExperience($this->location, $ev->getXpDropAmount());
2503 $this->xpManager->setXpAndProgress(0, 0.0);
2506 if($ev->getDeathMessage() !==
""){
2507 $this->server->broadcastMessage($ev->getDeathMessage());
2510 $this->startDeathAnimation();
2512 $this->getNetworkSession()->onServerDeath($ev->getDeathScreenMessage());
2516 parent::onDeathUpdate($tickDiff);
2520 public function respawn() : void{
2521 if($this->
server->isHardcore()){
2522 if($this->kick(KnownTranslationFactory::pocketmine_disconnect_ban(KnownTranslationFactory::pocketmine_disconnect_ban_hardcore()))){
2523 $this->
server->getNameBans()->addBan($this->getName(),
"Died in hardcore mode");
2528 $this->actuallyRespawn();
2531 protected function actuallyRespawn() : void{
2532 if($this->respawnLocked){
2535 $this->respawnLocked =
true;
2537 $this->logger->debug(
"Waiting for safe respawn position to be located");
2538 $spawn = $this->getSpawn();
2539 $spawn->getWorld()->requestSafeSpawn($spawn)->onCompletion(
2540 function(Position $safeSpawn) :
void{
2541 if(!$this->isConnected()){
2544 $this->logger->debug(
"Respawn position located, completing respawn");
2545 $ev =
new PlayerRespawnEvent($this, $safeSpawn);
2546 $spawnPosition = $ev->getRespawnPosition();
2547 $spawnBlock = $spawnPosition->
getWorld()->getBlock($spawnPosition);
2548 if($spawnBlock instanceof RespawnAnchor){
2549 if($spawnBlock->getCharges() > 0){
2550 $spawnPosition->
getWorld()->setBlock($spawnPosition, $spawnBlock->setCharges($spawnBlock->getCharges() - 1));
2551 $spawnPosition->
getWorld()->addSound($spawnPosition,
new RespawnAnchorDepleteSound());
2553 $defaultSpawn = $this->
server->getWorldManager()->getDefaultWorld()?->getSpawnLocation();
2554 if($defaultSpawn !==
null){
2555 $this->setSpawn($defaultSpawn);
2556 $ev->setRespawnPosition($defaultSpawn);
2557 $this->sendMessage(KnownTranslationFactory::tile_respawn_anchor_notValid()->prefix(TextFormat::GRAY));
2563 $realSpawn = Position::fromObject($ev->getRespawnPosition()->add(0.5, 0, 0.5), $ev->getRespawnPosition()->getWorld());
2564 $this->teleport($realSpawn);
2566 $this->setSprinting(
false);
2567 $this->setSneaking(
false);
2568 $this->setFlying(
false);
2570 $this->extinguish(EntityExtinguishEvent::CAUSE_RESPAWN);
2571 $this->setAirSupplyTicks($this->getMaxAirSupplyTicks());
2572 $this->deadTicks = 0;
2573 $this->noDamageTicks = 60;
2575 $this->effectManager->clear();
2576 $this->setHealth($this->getMaxHealth());
2578 foreach($this->attributeMap->getAll() as $attr){
2579 if($attr->getId() === Attribute::EXPERIENCE || $attr->getId() === Attribute::EXPERIENCE_LEVEL){
2582 $attr->resetToDefault();
2585 $this->spawnToAll();
2586 $this->scheduleUpdate();
2588 $this->getNetworkSession()->onServerRespawn();
2589 $this->respawnLocked =
false;
2592 if($this->isConnected()){
2593 $this->getNetworkSession()->disconnectWithError(KnownTranslationFactory::pocketmine_disconnect_error_respawn());
2600 parent::applyPostDamageEffects($source);
2602 $this->hungerManager->exhaust(0.1, PlayerExhaustEvent::CAUSE_DAMAGE);
2606 if(!$this->isAlive()){
2610 if($this->isCreative()
2611 && $source->getCause() !== EntityDamageEvent::CAUSE_SUICIDE
2614 }elseif($this->allowFlight && $source->getCause() === EntityDamageEvent::CAUSE_FALL){
2618 parent::attack($source);
2621 protected function syncNetworkData(EntityMetadataCollection $properties) : void{
2622 parent::syncNetworkData($properties);
2624 $properties->setGenericFlag(EntityMetadataFlags::ACTION, $this->startAction > -1);
2625 $properties->setGenericFlag(EntityMetadataFlags::HAS_COLLISION, $this->hasBlockCollision());
2627 $properties->setPlayerFlag(PlayerMetadataFlags::SLEEP, $this->sleeping !==
null);
2628 $properties->setBlockPos(EntityMetadataProperties::PLAYER_BED_POSITION, $this->sleeping !==
null ? BlockPosition::fromVector3($this->sleeping) :
new BlockPosition(0, 0, 0));
2630 if($this->deathPosition !==
null && $this->deathPosition->world === $this->location->world){
2631 $properties->setBlockPos(EntityMetadataProperties::PLAYER_DEATH_POSITION, BlockPosition::fromVector3($this->deathPosition));
2633 $properties->setInt(EntityMetadataProperties::PLAYER_DEATH_DIMENSION, DimensionIds::OVERWORLD);
2634 $properties->setByte(EntityMetadataProperties::PLAYER_HAS_DIED, 1);
2636 $properties->setBlockPos(EntityMetadataProperties::PLAYER_DEATH_POSITION, new BlockPosition(0, 0, 0));
2637 $properties->setInt(EntityMetadataProperties::PLAYER_DEATH_DIMENSION, DimensionIds::OVERWORLD);
2638 $properties->setByte(EntityMetadataProperties::PLAYER_HAS_DIED, 0);
2642 public function sendData(?array $targets, ?array $data =
null) : void{
2643 if($targets === null){
2644 $targets = $this->getViewers();
2647 parent::sendData($targets, $data);
2651 if($this->spawned && $targets === null){
2652 $targets = $this->getViewers();
2655 parent::broadcastAnimation($animation, $targets);
2659 if($this->spawned && $targets === null){
2660 $targets = $this->getViewers();
2663 parent::broadcastSound($sound, $targets);
2669 protected function sendPosition(
Vector3 $pos, ?
float $yaw =
null, ?
float $pitch =
null,
int $mode = MovePlayerPacket::MODE_NORMAL) : void{
2670 $this->getNetworkSession()->syncMovement($pos, $yaw, $pitch, $mode);
2676 if(parent::teleport($pos, $yaw, $pitch)){
2678 $this->removeCurrentWindow();
2681 $this->sendPosition($this->location, $this->location->yaw, $this->location->pitch, MovePlayerPacket::MODE_TELEPORT);
2682 $this->broadcastMovement(
true);
2684 $this->spawnToAll();
2686 $this->resetFallDistance();
2687 $this->nextChunkOrderRun = 0;
2688 if($this->spawnChunkLoadCount !== -1){
2689 $this->spawnChunkLoadCount = 0;
2691 $this->blockBreakHandler =
null;
2695 $this->resetLastMovements();
2703 protected function addDefaultWindows() : void{
2704 $this->cursorInventory = new PlayerCursorInventory($this);
2705 $this->craftingGrid =
new PlayerCraftingInventory($this);
2707 $this->addPermanentInventories($this->inventory, $this->armorInventory, $this->cursorInventory, $this->offHandInventory, $this->craftingGrid);
2712 public function getCursorInventory() : PlayerCursorInventory{
2713 return $this->cursorInventory;
2716 public function getCraftingGrid() : CraftingGrid{
2717 return $this->craftingGrid;
2725 return $this->creativeInventory;
2732 $this->creativeInventory = $inventory;
2733 if($this->spawned && $this->isConnected()){
2734 $this->getNetworkSession()->getInvManager()?->syncCreative();
2742 private function doCloseInventory() : void{
2743 $inventories = [$this->craftingGrid, $this->cursorInventory];
2744 if($this->currentWindow instanceof TemporaryInventory){
2745 $inventories[] = $this->currentWindow;
2748 $builder =
new TransactionBuilder();
2749 foreach($inventories as $inventory){
2750 $contents = $inventory->getContents();
2752 if(count($contents) > 0){
2753 $drops = $builder->getInventory($this->inventory)->addItem(...$contents);
2754 foreach($drops as $drop){
2755 $builder->addAction(
new DropItemAction($drop));
2758 $builder->getInventory($inventory)->clearAll();
2762 $actions = $builder->generateActions();
2763 if(count($actions) !== 0){
2764 $transaction =
new InventoryTransaction($this, $actions);
2766 $transaction->execute();
2767 $this->logger->debug(
"Successfully evacuated items from temporary inventories");
2768 }
catch(TransactionCancelledException){
2769 $this->logger->debug(
"Plugin cancelled transaction evacuating items from temporary inventories; items will be destroyed");
2770 foreach($inventories as $inventory){
2771 $inventory->clearAll();
2773 }
catch(TransactionValidationException $e){
2774 throw new AssumptionFailedError(
"This server-generated transaction should never be invalid", 0, $e);
2783 return $this->currentWindow;
2790 if($inventory === $this->currentWindow){
2795 if($ev->isCancelled()){
2799 $this->removeCurrentWindow();
2801 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) ===
null){
2802 throw new \InvalidArgumentException(
"Player cannot open inventories in this state");
2804 $this->logger->debug(
"Opening inventory " . get_class($inventory) .
"#" . spl_object_id($inventory));
2805 $inventoryManager->onCurrentWindowChange($inventory);
2806 $inventory->onOpen($this);
2807 $this->currentWindow = $inventory;
2811 public function removeCurrentWindow() : void{
2812 $this->doCloseInventory();
2813 if($this->currentWindow !==
null){
2814 $currentWindow = $this->currentWindow;
2815 $this->logger->debug(
"Closing inventory " . get_class($this->currentWindow) .
"#" . spl_object_id($this->currentWindow));
2816 $this->currentWindow->onClose($this);
2817 if(($inventoryManager = $this->getNetworkSession()->getInvManager()) !==
null){
2818 $inventoryManager->onCurrentWindowRemove();
2820 $this->currentWindow =
null;
2821 (
new InventoryCloseEvent($currentWindow, $this))->call();
2825 protected function addPermanentInventories(Inventory ...$inventories) : void{
2826 foreach($inventories as $inventory){
2827 $inventory->onOpen($this);
2828 $this->permanentWindows[spl_object_id($inventory)] = $inventory;
2832 protected function removePermanentInventories() : void{
2833 foreach($this->permanentWindows as $inventory){
2834 $inventory->onClose($this);
2836 $this->permanentWindows = [];
2844 $block = $this->getWorld()->getBlock($position);
2846 $this->getWorld()->setBlock($position, $block->setEditorEntityRuntimeId($this->getId()));
2847 $this->getNetworkSession()->onOpenSignEditor($position,
true);
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);